diff --git a/CHANGELOG.md b/CHANGELOG.md index 8f76932..d2c4a80 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -69,6 +69,13 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows ### Changed +- The view models, the app's state and the decisions of the settings pages and + of the Stream Studio moved out of `voelin-ui` into a new crate, + `voelin-ui-vm`, which depends on no UI toolkit (a second front end can use + it); `voelin-ui` converts its plain rows into Slint's and keeps the window, + the Bridge writes and the engine's tasks. The chat formatting reader and the + Twemoji archive moved with them. Nothing changes on screen. See + docs/ui.md, "Two crates". - The identity store keeps identities of more than one kind (TeamSpeak, a Voelin key, the signed-in account) with the account each belongs to, as a `voelin-identity` key store, in two database migrations. Existing diff --git a/Cargo.lock b/Cargo.lock index 8f1b713..73c9f0a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9740,7 +9740,6 @@ dependencies = [ "chrono", "dirs", "image", - "miniz_oxide 0.8.9", "png", "serde", "serde_json", @@ -9758,6 +9757,25 @@ dependencies = [ "voelin-platform", "voelin-query", "voelin-store", + "voelin-ui-vm", +] + +[[package]] +name = "voelin-ui-vm" +version = "0.0.1-alpha" +dependencies = [ + "chrono", + "image", + "miniz_oxide 0.8.9", + "png", + "serde", + "serde_json", + "unicode-segmentation", + "voelin-audio", + "voelin-core", + "voelin-gateway-proto", + "voelin-model", + "voelin-store", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 128e4fb..10350af 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -22,6 +22,7 @@ members = [ "crates/voelin-store", "crates/voelin-stream", "crates/voelin-ui", + "crates/voelin-ui-vm", "tools/voelinctl", ] default-members = [ @@ -41,6 +42,7 @@ default-members = [ "crates/voelin-store", "crates/voelin-stream", "crates/voelin-ui", + "crates/voelin-ui-vm", "tools/voelinctl", ] diff --git a/README.md b/README.md index f7e389b..96986e6 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,9 @@ Done so far (milestones M0–M4 and the first part of M5 of [the plan](docs/arch (in the window and as a global hotkey), audio settings with a level meter, per-client volume, and on TeamSpeak 6 streams: watch in a viewer, share the screen with sound. Desktop and phone layouts from one design system, dark and light themes, text size, emoji ([docs/ui.md](docs/ui.md)) +- `crates/voelin-ui-vm`: the view models and the app's state behind the UI, with no UI toolkit: engine state + as plain rows and forms, chat formatting, the Twemoji archive, and what the settings pages and the + Stream Studio decide; `voelin-ui` puts them on Slint windows ([docs/ui.md](docs/ui.md)) - `crates/voelin-stream`: TeamSpeak 6 streams: stream commands and notifications, JSON signalling, WebRTC peers (str0m) with host and STUN candidates. A live test streams VP8 + Opus between two clients through a TS6 server diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 7aa38c6..4dddbc0 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -11991,7 +11991,8 @@ bzip2/libbzip2 version 1.1.0 of 6 September 2010 -The user interface bundles these assets (in crates/voelin-ui): +The user interface bundles these assets (in crates/voelin-ui, the Twemoji +archive in crates/voelin-ui-vm): - Inter (the UI font), Copyright (c) 2016 The Inter Project Authors, under the SIL Open Font License 1.1 (OFL-1.1; text below). diff --git a/about-assets.md b/about-assets.md index 7fb3f4e..78580fd 100644 --- a/about-assets.md +++ b/about-assets.md @@ -3,7 +3,8 @@ -The user interface bundles these assets (in crates/voelin-ui): +The user interface bundles these assets (in crates/voelin-ui, the Twemoji +archive in crates/voelin-ui-vm): - Inter (the UI font), Copyright (c) 2016 The Inter Project Authors, under the SIL Open Font License 1.1 (OFL-1.1; text below). diff --git a/crates/voelin-ui-vm/Cargo.toml b/crates/voelin-ui-vm/Cargo.toml new file mode 100644 index 0000000..f06af6c --- /dev/null +++ b/crates/voelin-ui-vm/Cargo.toml @@ -0,0 +1,39 @@ +[package] +name = "voelin-ui-vm" +version = "0.0.1-alpha" +description = "Toolkit-free view models of the desktop client: engine state turned into plain rows, shared by the Slint and GPUI front ends." +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +publish.workspace = true + +[lib] +name = "voelin_ui_vm" +path = "src/lib.rs" + +# No UI toolkit here (no slint, no gpui): `cargo tree -p voelin-ui-vm -e normal` +# must show neither. The front ends convert these types (docs/ui.md). +[dependencies] +chrono = { version = "0.4.45", default-features = false, features = ["clock"] } +# Picture sizes (the header of a file); PNG and JPEG are listed as the +# front end's toolkit used to bring them. +image = { version = "0.25", default-features = false, features = ["png", "jpeg", "gif", "webp", "bmp", "ico"] } +serde = { version = "1", features = ["derive"] } +# JSON values of the settings and the gateway's configuration keys. +serde_json = "1" +# The Twemoji archive's blocks (raw deflate). +miniz_oxide = "0.8" +# Grapheme clusters for emoji in chat text. +unicode-segmentation = "1.13" +voelin-audio = { path = "../voelin-audio", default-features = false } +voelin-core = { path = "../voelin-core", default-features = false, features = ["media"] } +voelin-gateway-proto = { path = "../voelin-gateway-proto" } +voelin-model = { workspace = true } +voelin-store = { path = "../voelin-store" } + +[dev-dependencies] +png = "0.18" + +[lints] +workspace = true diff --git a/crates/voelin-ui-vm/assets/README.md b/crates/voelin-ui-vm/assets/README.md new file mode 100644 index 0000000..9cf1e4a --- /dev/null +++ b/crates/voelin-ui-vm/assets/README.md @@ -0,0 +1,11 @@ +# Bundled assets + +- `twemoji.bin`: the Twemoji 15.0 SVGs (3720 emoji, from the `@twemoji/svg` + 15.0.0 package) packed by `scripts/pack-twemoji.py` into blocks of raw + deflate with an index; `src/emoji.rs` reads it. Twemoji graphics by Twitter, + Inc and other contributors, licensed under CC-BY 4.0 + (https://creativecommons.org/licenses/by/4.0/). The files are unchanged + apart from surrounding whitespace. + +It is credited in `THIRD_PARTY_NOTICES.md` and the About page, with the fonts +and icons of the Slint front end (`crates/voelin-ui/assets/README.md`). diff --git a/crates/voelin-ui/assets/twemoji.bin b/crates/voelin-ui-vm/assets/twemoji.bin similarity index 100% rename from crates/voelin-ui/assets/twemoji.bin rename to crates/voelin-ui-vm/assets/twemoji.bin diff --git a/crates/voelin-ui/src/vm/avatar.rs b/crates/voelin-ui-vm/src/avatar.rs similarity index 82% rename from crates/voelin-ui/src/vm/avatar.rs rename to crates/voelin-ui-vm/src/avatar.rs index 74af518..51347f0 100644 --- a/crates/voelin-ui/src/vm/avatar.rs +++ b/crates/voelin-ui-vm/src/avatar.rs @@ -1,8 +1,10 @@ //! Avatars without pictures: initials on a colour from the name. -use slint::Color; 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, @@ -31,10 +33,10 @@ 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), decoded -/// once; an empty image when there is none. -pub fn image(path: Option<&std::path::PathBuf>) -> slint::Image { - path.map(|p| crate::images::file(p)).unwrap_or_default() +/// 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). @@ -48,12 +50,12 @@ pub fn name_hash(name: &str) -> u32 { } /// `0xrrggbb` as a colour. -pub fn rgb(rgb: u32) -> Color { - Color::from_rgb_u8((rgb >> 16) as u8, (rgb >> 8) as u8, rgb as u8) +pub fn rgb(rgb: u32) -> Rgb { + Rgb::from(rgb) } /// A stable colour for a name. -pub fn tint(name: &str) -> Color { +pub fn tint(name: &str) -> Rgb { rgb(TINTS[(name_hash(name) % TINTS.len() as u32) as usize]) } @@ -86,10 +88,7 @@ mod tests { 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).as_argb_encoded()) - .collect(); + ["Alice", "Bob", "Carol", "Dave", "Eve", "Mallory"].iter().map(|n| tint(n).0).collect(); assert!(distinct.len() > 2); } } diff --git a/crates/voelin-ui/src/vm/bbcode.rs b/crates/voelin-ui-vm/src/bbcode.rs similarity index 100% rename from crates/voelin-ui/src/vm/bbcode.rs rename to crates/voelin-ui-vm/src/bbcode.rs diff --git a/crates/voelin-ui-vm/src/bridge.rs b/crates/voelin-ui-vm/src/bridge.rs new file mode 100644 index 0000000..6dcdf21 --- /dev/null +++ b/crates/voelin-ui-vm/src/bridge.rs @@ -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`, 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, + pub address: Arc, + /// "offline", "connecting", "observing" or "connected" + pub status: Arc, + /// Avatar of a server without an icon. + pub initials: Arc, + 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, + /// "TeamSpeak 6", "TeamSpeak 3", "" before it was reached. + pub product: Arc, + /// 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, + 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, + 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, + pub initials: Arc, + 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, + /// The away message, empty without one. + pub away_message: Arc, + /// The section the row is in (a server group, "In Voice", + /// "Streaming"), and the group's icon. + pub group: Arc, + 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, + 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, + pub description: Arc, + 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, + pub initials: Arc, + pub tint: Rgb, + pub avatar: ImageRef, + pub status: Arc, + pub description: Arc, + /// Server groups, one per line. + pub groups: Vec>, + /// The badges the client shows (at most three, in its order). + pub badges: Vec, + pub country: Arc, + 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, + /// The name alone ("Lobby"). + pub name: Arc, + /// 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, + /// The last message ("Mira: the banner I promised") and its time. + pub last: Arc, + pub time: Arc, + /// 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, + pub emoji: Arc, + 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, + pub ink_light: Option, + /// 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, + 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, + /// 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, +} + +/// 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, + pub text: Arc, + 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, + /// "2.4 MB", or what the transfer is doing. + pub detail: Arc, + /// Index of the link in the message (what `download-file` takes). + pub index: i32, + /// "", "running", "done", "failed" + pub state: Arc, + /// 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, + /// 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, + pub time: Arc, + /// The text in blocks of styled runs; only filled when it has + /// formatting or emoji (`rich`). + pub blocks: Vec, + 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, + pub tint: Rgb, + pub avatar: ImageRef, + /// From a blocked contact. + pub blocked: bool, + pub pinned: bool, + pub reactions: Vec, + pub files: Vec, + /// 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, + /// Highlighted after jumping to it from the pins. + pub marked: bool, + /// The first web address it links to, "" if none. + pub link: Arc, + /// 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, +} + +/// A gateway topic (thread). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct TopicItem { + pub id: i32, + pub title: Arc, + pub creator: Arc, + /// "12 messages · by Nova" + pub detail: Arc, + /// "Last active 3 min ago", and whether that was within the hour. + pub activity: Arc, + 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, + pub address: Arc, + pub nickname: Arc, + pub server_password: Arc, + /// The server has voice: no Connect. + pub connected: bool, + /// From a link, not stored with the server: the channel to join (a + /// path, or /), its password and a privilege key. + pub channel: Arc, + pub channel_password: Arc, + pub token: Arc, +} + +/// 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, + pub name: Arc, + pub streamer: Arc, + /// The streamer's channel when it is not ours; empty in ours. + pub channel: Arc, + /// 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, + 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, + pub bitrate: Arc, + /// 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, + pub state: Arc, + pub message: Arc, + /// 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, + pub detail: Arc, +} + +/// 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, + /// 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, + /// 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, + 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, + 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, + 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, + pub name: Arc, + pub initials: Arc, + pub tint: Rgb, + pub avatar: ImageRef, + /// "friend", "blocked" or "neutral" + pub relation: Arc, + pub online: bool, + pub away: bool, + pub streaming: bool, + /// What they do: "In Chill Zone", "Streaming", "Away: brb", "Offline". + pub status: Arc, + /// Where: the server of the first session that sees them, or "Last seen + /// 2 h ago on Nightfall Guild". + pub place: Arc, + /// "12m ago": online since (this run), else when last seen. + pub when: Arc, + pub note: Arc, + /// Local playback in percent. + pub volume: f32, + pub muted: bool, + /// "Contact since 14 Jan 2022". + pub since: Arc, + /// Every session that sees them: "Nightfall Guild · Chill Zone". + pub spots: Vec>, + /// 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, + pub title: Arc, + pub streamer: Arc, + pub initials: Arc, + pub tint: Rgb, + pub avatar: ImageRef, + pub server: Arc, + pub channel: Arc, + /// 0: unknown. + pub viewers: i32, + /// "Screen", "Camera", ... + pub kind: Arc, + /// 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, + /// The server's name. + pub server: Arc, + /// "You: That works!", "Sent a file". + pub preview: Arc, + /// "11:42", "Yesterday", "Mon", "12 Mar". + pub time: Arc, + /// "10m ago". + pub ago: Arc, + pub unread: i32, + pub initials: Arc, + 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, + pub title: Arc, + pub body: Arc, + /// "3 min ago" + pub time: Arc, + pub unread: bool, + pub initials: Arc, + 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, + pub title: Arc, + pub subtitle: Arc, + pub initials: Arc, + pub tint: Rgb, + pub avatar: ImageRef, + /// The first result of a group names it ("Servers", "People", ...). + pub header: Arc, +} + +/// 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, + pub title: Arc, + pub subtitle: Arc, + /// "Sat 26 Apr · 19:00" + pub when: Arc, + 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, + pub initials: Arc, + pub tint: Rgb, + pub icon: ImageRef, + /// The channel's name as the tree shows it. + pub channel: Arc, + /// 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, + pub description: Arc, + /// The date block: "SAT", "26", "APR". + pub weekday: Arc, + pub day: Arc, + pub month: Arc, + /// "Sat 26 Apr, 19:00 – 21:00" + pub when: Arc, + /// "Raid Night" or "Server-wide". + pub place: Arc, + /// A scheduled stream: "Exploring the Lands Between · Elden Ring". + pub stream: Arc, + pub live: bool, + pub going: i32, + pub maybe: i32, + pub not_going: i32, + /// "going", "maybe", "not_going" or "". + pub rsvp: Arc, + pub creator: Arc, + /// We may edit and delete it (ours, or we moderate). + pub editable: bool, + /// "Starts in 15 min", "Started 5 min ago", "". + pub soon: Arc, + /// "Nova (going)", ...; filled once the event was opened. + pub attendees: Vec>, + 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, + pub description: Arc, + /// "2026-10-04 19:00", local time. + pub start: Arc, + /// Empty: no end. + pub end: Arc, + /// Index into `event-channels` (0: server-wide). + pub channel: i32, + pub stream: bool, + pub stream_title: Arc, + pub game: Arc, +} + +/// 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, + pub to: Arc, + pub subject: Arc, + pub text: Arc, +} + +/// The open direct message: who, and what can be done. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct DmPeer { + pub open: bool, + pub uid: Arc, + pub name: Arc, + pub initials: Arc, + pub tint: Rgb, + pub avatar: ImageRef, + pub online: bool, + /// "Online · Nightfall Guild · Chill Zone", "Offline · last seen 2 h ago". + pub status: Arc, + pub description: Arc, + pub groups: Vec>, + pub note: Arc, + pub since: Arc, + /// Where they are now, or where they were last seen. + pub servers: Vec>, + /// 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, + pub media_more: i32, + pub files: Vec, + 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, + /// 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, + pub mail_text: Arc, + pub mail_time: Arc, +} + +/// An identity (Profiles page); never its key. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct IdentityItem { + pub id: i32, + pub name: Arc, + /// Unique ids on TeamSpeak 3 and TeamSpeak 6 servers. + pub uid: Arc, + pub uid6: Arc, + 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, + /// 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, +} + +/// An identity found in another client's files (import). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct FoundIdentity { + pub name: Arc, + pub uid: Arc, + pub level: i32, + pub source: Arc, + /// 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, + /// 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, + /// `stream.fps` as typed. + pub fps: Arc, + /// 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, + /// Frames per second; "" no cap. + pub fps: Arc, + /// kbit/s. + pub bitrate: Arc, + pub min_bitrate: Arc, + pub max_bitrate: Arc, +} + +/// An audio source mixed into our stream. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct AudioSourceItem { + /// "desktop", "app", "window", "microphone", "synthetic" + pub kind: Arc, + pub name: Arc, + pub detail: Arc, + /// Percent. + pub gain: f32, + pub muted: bool, +} + +/// Stream defaults (Streaming page). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct StreamingForm { + pub fps: Arc, + pub bitrate: Arc, + /// auto, vp8, vp9, h264, av1. + pub codec: i32, + /// auto, portal, wlroots, x11. + pub capture: i32, + pub replay_seconds: Arc, + pub replay_memory: Arc, + pub recording_dir: Arc, +} + +/// 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, + pub url: Arc, + /// "connected", "connecting", "off" + pub status: Arc, + pub features: Vec>, + pub admin: bool, +} + +/// A gateway configuration key (gateway administration). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ConfigItem { + pub key: Arc, + /// JSON. + pub value: Arc, + pub source: Arc, + pub description: Arc, + pub kind: Arc, + pub bootstrap: bool, +} + +/// A gateway permission rule. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct PermItem { + pub action: Arc, + /// "Everyone", "Server groups 6, 7", "Default: server admins". + pub rule: Arc, + pub source: Arc, + pub everyone: bool, + pub server_groups: Arc, + pub channel_groups: Arc, +} + +/// A video encoder backend (Integrations page). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct EncoderItem { + pub name: Arc, + pub api: Arc, + pub codec: Arc, + pub hardware: bool, + pub ok: bool, + /// Why it does not work, or "used first". + pub status: Arc, +} + +/// Any registered setting (Advanced page). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct SettingItem { + pub key: Arc, + pub doc: Arc, + /// JSON. + pub value: Arc, + /// "set here", "command line", "config file", "default". + pub source: Arc, +} + +/// A recording or clip of the Stream Studio (Library). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct RecordingItem { + pub name: Arc, + /// "12.3 MB · 3 Oct 18:04". + pub detail: Arc, + pub clip: bool, + pub path: Arc, +} + +/// Encoders, chat history, cache and logs (Advanced page); numbers as typed. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct AdvancedForm { + pub encoder: Arc, + pub hardware: bool, + /// `stream.decoder_backend`, `stream.hardware_decoding`. + pub decoder: Arc, + pub hardware_decoding: bool, + pub store_history: bool, + pub history_page: Arc, + pub dedupe_ms: Arc, + pub retention_days: Arc, + pub cache_mb: Arc, + pub fetch_images: bool, + pub progress_ms: Arc, + /// `ui.image_preview_kb`. + pub preview_kb: Arc, + pub logs: Arc, + pub crash_dir: Arc, +} + +/// 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, + pub identity: Arc, + pub uid: Arc, + pub uid6: Arc, + pub level: i32, + pub server: Arc, +} + +/// One emoji of the picker. `text` is what picking it inserts. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct EmojiCell { + pub key: Arc, + pub name: Arc, + pub text: Arc, +} + +/// 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, +} diff --git a/crates/voelin-ui/src/vm/chat.rs b/crates/voelin-ui-vm/src/chat.rs similarity index 88% rename from crates/voelin-ui/src/vm/chat.rs rename to crates/voelin-ui-vm/src/chat.rs index af034ba..e7c0b3c 100644 --- a/crates/voelin-ui/src/vm/chat.rs +++ b/crates/voelin-ui-vm/src/chat.rs @@ -6,17 +6,17 @@ use std::borrow::Cow; use std::cell::RefCell; use std::collections::HashMap; use std::path::PathBuf; -use std::rc::Rc; -use slint::{Color, Image, ModelRc, VecModel}; use unicode_segmentation::UnicodeSegmentation; use voelin_core::HistoryMessage; use voelin_model::{ChatMessage, ChatTarget, FileRef, Presence}; -use crate::app::{ChatLine, FileItem, ReactionItem, TextBlock, TextRun}; +use crate::avatar; +use crate::bbcode::{self, BlockKind, Doc, Span, Style}; +use crate::bridge::{ChatLine, FileItem, ReactionItem, TextBlock, TextRun}; +use crate::color::Rgb; use crate::emoji; -use crate::vm::avatar; -use crate::vm::bbcode::{self, BlockKind, Doc, Span, Style}; +use crate::image::ImageRef; /// Lines of the same author within this time are grouped (no header). const GROUP_MS: i64 = 5 * 60 * 1000; @@ -29,6 +29,7 @@ pub struct Previous { } impl Previous { + /// The line `message` is, as the line after it sees it. pub fn of(message: &ChatMessage) -> Self { Self { author: message.author_name.clone(), ts_ms: message.ts_ms } } @@ -40,7 +41,7 @@ pub struct LineCtx<'a> { /// The message's handle in its chat. pub key: i32, /// The author's avatar picture. - pub avatar: Image, + pub avatar: ImageRef, /// The gateway takes reactions and pins for this chat. pub gateway: bool, /// Highlighted (jumped to from the pins). @@ -50,7 +51,7 @@ pub struct LineCtx<'a> { /// The state of the downloads started from this message, by link index. pub downloads: Vec<(usize, FileItem)>, /// Pictures of the links shown inline, by link index. - pub previews: Vec<(usize, Image)>, + pub previews: Vec<(usize, ImageRef)>, /// Pictures on the web in the engine's cache, by address: the `[img]` /// pictures here show as picture cards, the others as links (`None`: /// all as links). @@ -137,7 +138,7 @@ pub fn size_text(bytes: u64) -> String { #[derive(Clone, Default)] struct Body { text: String, - blocks: ModelRc, + blocks: Vec, rich: bool, jumbo: bool, link: String, @@ -152,10 +153,9 @@ struct Read { } /// What lines of a chat were built from, by message id, kept between -/// refreshes: a message whose text, reactions and cards did not change is -/// not read again and gets the same models (they compare by pointer), so -/// its line compares equal and `list::sync` leaves its row. (Not with an -/// empty picture: Slint's empty `Image` equals nothing, not even itself.) +/// refreshes: a message whose text did not change is not read again (its +/// BBCode parsed, its blocks and runs split), and builds the same line, so +/// the list diff leaves its row. #[derive(Default)] pub struct LineCache(RefCell>); @@ -166,8 +166,6 @@ struct Parts { read: Option, /// The body last built, and which pictures were cards then. body: Option<(Vec, Body)>, - reactions: (Vec, ModelRc), - files: (Vec, ModelRc), } impl LineCache { @@ -190,22 +188,6 @@ fn current<'a>(all: &'a mut HashMap, id: i64, rev: i64, text: &str) parts } -/// `rows` as a model: the one in `kept` when they are the same rows. -fn model_of( - rows: Vec, - kept: Option<&mut (Vec, ModelRc)>, -) -> ModelRc { - match kept { - Some((old, model)) if *old == rows => model.clone(), - Some(kept) => { - let model = ModelRc::from(Rc::new(VecModel::from(rows.clone()))); - *kept = (rows, model.clone()); - model - } - None => ModelRc::from(Rc::new(VecModel::from(rows))), - } -} - /// A link to a channel's file, which the chat shows as a card. fn is_file(address: &str) -> bool { FileRef::parse(address).is_some() @@ -236,11 +218,13 @@ pub fn web_pictures(text: &str) -> Vec { /// The colours of a span: the author's made readable on the dark and the /// light theme, or transparent for the text's own. -fn inks(color: Option<[u8; 3]>) -> (Color, Color) { - let rgb = |[r, g, b]: [u8; 3]| Color::from_rgb_u8(r, g, b); +fn inks(color: Option<[u8; 3]>) -> (Option, Option) { match color { - Some(c) => (rgb(bbcode::readable(c, true)), rgb(bbcode::readable(c, false))), - None => (Color::default(), Color::default()), + Some(c) => ( + Some(Rgb::from(bbcode::readable(c, true))), + Some(Rgb::from(bbcode::readable(c, false))), + ), + None => (None, None), } } @@ -251,7 +235,7 @@ fn run( emoji: Option, style: &Style, masked: bool, - inks: (Color, Color), + inks: (Option, Option), ) -> TextRun { TextRun { text: text.into(), @@ -356,11 +340,7 @@ fn blocks_of(doc: &Doc) -> Option<(Vec, bool)> { if count > bbcode::MAX_RUNS { return None; } - blocks.push(TextBlock { - runs: ModelRc::from(Rc::new(VecModel::from(runs))), - kind, - caption: caption.into(), - }); + blocks.push(TextBlock { runs, kind, caption: caption.into() }); } } Some((blocks, any_emoji)) @@ -388,19 +368,13 @@ fn body_of(doc: &Doc, cards: &[bool]) -> Body { let rich = !doc.is_plain() || words.iter().any(|w| w.emoji.is_some()); // Past the runs a line can have: its plain text. match rich.then(|| blocks_of(&doc)).flatten() { - Some((blocks, _)) => Body { - text, - blocks: ModelRc::from(Rc::new(VecModel::from(blocks))), - rich: true, - jumbo, - link, - }, - None => Body { text, blocks: ModelRc::default(), rich: false, jumbo, link }, + Some((blocks, _)) => Body { text, blocks, rich: true, jumbo, link }, + None => Body { text, blocks: Vec::new(), rich: false, jumbo, link }, } } /// The picture at `url`, if the engine has it and it can be shown. -fn picture(pictures: Option<&HashMap>, url: &str) -> Option { +fn picture(pictures: Option<&HashMap>, url: &str) -> Option { let image = avatar::image(pictures?.get(url)); (image.size().width > 0).then_some(image) } @@ -417,7 +391,7 @@ pub fn tab_title(presence: &Presence, target: &ChatTarget, peer: &str) -> String match target { ChatTarget::Channel(cid) => presence.channels.get(cid).map_or_else( || format!("Channel {cid}"), - |c| crate::vm::tree::channel_title(c).0.to_owned(), + |c| crate::tree::channel_title(c).0.to_owned(), ), ChatTarget::Private(_) => format!("@{peer}"), ChatTarget::Server => "Server".into(), @@ -469,7 +443,7 @@ pub fn preview(message: &ChatMessage) -> (String, String) { std::iter::once(read.doc.one_line()).chain(names).collect::>().join(" ") }; // A one-line text cannot show emoji (they are pictures): left out. - let mut text = crate::vm::social::without_emoji(&text); + let mut text = crate::social::without_emoji(&text); if text.is_empty() { text = "sent an emoji".into(); } @@ -560,12 +534,11 @@ fn line_of( && previous.is_some_and(|p| { p.author == message.author_name && (0..GROUP_MS).contains(&(message.ts_ms - p.ts_ms)) }); - let cached = parts.is_some(); let mut own = Parts::default(); let parts = parts.unwrap_or(&mut own); let read = parts.read.get_or_insert_with(|| read(message)); // Pictures on the web that are here are cards, after the files'. - let pictures: Vec> = + let pictures: Vec> = read.images.iter().map(|url| picture(ctx.pictures, url)).collect(); let shown: Vec = pictures.iter().map(Option::is_some).collect(); let body = match &parts.body { @@ -612,8 +585,6 @@ fn line_of( }); } } - let files = model_of(cards, cached.then_some(&mut parts.files)); - let reactions = model_of(reactions, cached.then_some(&mut parts.reactions)); ChatLine { key: ctx.key, author: message.author_name.clone().into(), @@ -629,7 +600,7 @@ fn line_of( blocked: message.blocked, pinned: false, reactions, - files, + files: cards, remote: false, topic: ctx.topic.clone().into(), marked: ctx.marked, @@ -645,6 +616,7 @@ pub fn picture_link(message: &ChatMessage, index: usize) -> Option { index.checked_sub(read.files.len()).and_then(|i| read.images.into_iter().nth(i)) } +/// Whether a file name is a picture's, by its extension. pub fn is_picture(name: &str) -> bool { let lower = name.to_ascii_lowercase(); [".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".svg"].iter().any(|e| lower.ends_with(e)) @@ -652,7 +624,7 @@ pub fn is_picture(name: &str) -> bool { #[cfg(test)] mod tests { - use slint::Model; + use crate::image::ImageSource; use voelin_core::HistoryMessage; use voelin_gateway_proto::ReactionCount; use voelin_store::MessageSource; @@ -690,7 +662,7 @@ mod tests { let first = message("Alice", "hi", 1_000_000); let a = line(&first, None); assert!(!a.continued); - assert_eq!(a.initials, "AL"); + assert_eq!(&*a.initials, "AL"); let prev = Previous::of(&first); assert!(line(&message("Alice", "again", 1_060_000), Some(&prev)).continued); assert!(!line(&message("Bob", "me", 1_060_000), Some(&prev)).continued); @@ -744,27 +716,27 @@ mod tests { /// The runs of block `i` of a line, as (text, emoji). fn runs(line: &ChatLine, i: usize) -> Vec { - line.blocks.row_data(i).unwrap().runs.iter().collect() + line.blocks[i].runs.clone() } #[test] fn emoji_runs() { let plain = line(&message("A", "no emoji here\nnor here", 0), None); - assert!(!plain.rich && plain.blocks.row_count() == 0); - assert_eq!(plain.text, "no emoji here\nnor here"); + assert!(!plain.rich && plain.blocks.is_empty()); + assert_eq!(&*plain.text, "no emoji here\nnor here"); let rich = line(&message("A", "gg 🎉", 0), None); assert!(rich.rich && !rich.jumbo); - assert_eq!(rich.blocks.row_count(), 1); + assert_eq!(rich.blocks.len(), 1); let r = runs(&rich, 0); - assert_eq!((r.len(), r[0].text.as_str(), r[1].emoji.as_str()), (2, "gg ", "1f389")); + assert_eq!((r.len(), r[0].text.as_ref(), r[1].emoji.as_ref()), (2, "gg ", "1f389")); assert!(line(&message("A", "🎉", 0), None).jumbo); // Formatting around it: still large. let jumbo = line(&message("A", "[b]🎉[/b]", 0), None); assert!(jumbo.rich && jumbo.jumbo); // Lines stay lines with emoji (they were run together). let lines = line(&message("A", "first 🎉\nsecond", 0), None); - assert_eq!(lines.blocks.row_count(), 2); - assert_eq!(lines.text, "first 🎉\nsecond"); + assert_eq!(lines.blocks.len(), 2); + assert_eq!(&*lines.text, "first 🎉\nsecond"); } #[test] @@ -775,10 +747,10 @@ mod tests { let line = line(&message("A", text, 0), None); assert!(line.rich && !line.jumbo); assert_eq!( - line.text, + &*line.text, "Raid at 8, see https://x.org/raid\n> Nova: bring elixirs\n• one\n• two\n---\na\n\nb" ); - assert_eq!(line.link, "https://x.org/raid"); + assert_eq!(&*line.link, "https://x.org/raid"); let kinds: Vec<(i32, String)> = line.blocks.iter().map(|b| (b.kind, b.caption.to_string())).collect(); let kind = |k: i32| (k, String::new()); @@ -787,15 +759,15 @@ mod tests { [kind(0), (1, "Nova".into()), kind(3), kind(3), kind(4), kind(2), kind(2), kind(2)] ); let first = runs(&line, 0); - assert!(first[0].bold && first[0].text == "Raid"); + assert!(first[0].bold && &*first[0].text == "Raid"); let eight = first.iter().find(|r| r.text.starts_with('8')).unwrap(); // The author's red, readable on both themes. - assert!(eight.ink_dark.alpha() == 255 && eight.ink_light.alpha() == 255); - assert!(eight.ink_dark.red() > eight.ink_dark.green()); - assert_eq!(first[0].ink_dark.alpha(), 0, "the text's own colour"); + let (dark, light) = (eight.ink_dark.unwrap(), eight.ink_light.unwrap()); + assert!(dark.r() > dark.g() && light.r() > light.g()); + assert_eq!(first[0].ink_dark, None, "the text's own colour"); let address = first.iter().find(|r| !r.link.is_empty()).unwrap(); assert_eq!( - (address.text.as_str(), address.link.as_str()), + (address.text.as_ref(), address.link.as_ref()), ("https://x.org/raid", "https://x.org/raid") ); assert!(!address.masked, "its own address"); @@ -807,10 +779,10 @@ mod tests { // Inline code: one run. let inline = super::line(&message("A", "run [code]/pull 10[/code]", 0), None); let r = runs(&inline, 0); - assert!(r[1].code && r[1].text == "/pull 10"); + assert!(r[1].code && &*r[1].text == "/pull 10"); // Not formatting: plain. let relayed = super::line(&message("A", "[Nova] hi [1]", 0), None); - assert!(!relayed.rich && relayed.text == "[Nova] hi [1]" && relayed.link.is_empty()); + assert!(!relayed.rich && &*relayed.text == "[Nova] hi [1]" && relayed.link.is_empty()); } /// A link whose text is not its address asks before it opens: each of @@ -916,15 +888,15 @@ mod tests { let url = format!("https://x.org/{}", "a".repeat(40)); let line = line(&message("A", &format!("see {url}"), 0), None); let r = runs(&line, 0); - let pieces: Vec<&str> = r[1..].iter().map(|r| r.text.as_str()).collect(); + let pieces: Vec<&str> = r[1..].iter().map(|r| r.text.as_ref()).collect(); assert_eq!(pieces.concat(), url); assert!(pieces.len() == 3 && pieces.iter().all(|p| p.chars().count() <= LONG_WORD)); - assert!(r[1..].iter().all(|r| r.link == url.as_str())); + assert!(r[1..].iter().all(|r| &*r.link == url.as_str())); let code = "cargo build --release --locked -j 1"; let line = super::line(&message("A", &format!("[code]{code}[/code]"), 0), None); let r = runs(&line, 0); assert!(r.len() > 1 && r.iter().all(|r| r.code)); - assert_eq!(r.iter().map(|r| r.text.as_str()).collect::(), code); + assert_eq!(r.iter().map(|r| r.text.as_ref()).collect::(), code); } #[test] @@ -933,9 +905,9 @@ mod tests { let text = format!("loot [img]{url}[/img]"); // Not here (or not fetched): the address, as a link. let link = line(&message("A", &text, 0), None); - assert_eq!(link.files.row_count(), 0); + assert_eq!(link.files.len(), 0); let r = runs(&link, 0); - assert_eq!((r[1].text.as_str(), r[1].link.as_str()), (url, url)); + assert_eq!((r[1].text.as_ref(), r[1].link.as_ref()), (url, url)); // Here: a picture card after the files, and no address. let dir = std::env::temp_dir().join(format!("voelin-chat-picture-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); @@ -951,10 +923,10 @@ mod tests { let stored = stored(message("A", &format!("{text} [URL={file}]plan.pdf[/URL]"), 0)); let ctx = LineCtx { pictures: Some(&pictures), ..Default::default() }; let shown = history_line(&stored, None, &ctx); - assert_eq!(shown.text, "loot"); - assert_eq!(shown.files.row_count(), 2); - let card = shown.files.row_data(1).unwrap(); - assert_eq!((card.name.as_str(), card.index, card.preview.size().width), ("loot.png", 1, 4)); + assert_eq!(&*shown.text, "loot"); + assert_eq!(shown.files.len(), 2); + let card = shown.files[1].clone(); + assert_eq!((card.name.as_ref(), card.index, card.preview.size().width), ("loot.png", 1, 4)); assert_eq!(picture_link(&stored.message, 1).as_deref(), Some(url)); assert_eq!(picture_link(&stored.message, 0), None); assert_eq!(web_pictures(&text), [url]); @@ -962,20 +934,18 @@ mod tests { std::fs::remove_dir_all(dir).unwrap(); } - /// A line built again from an unchanged message is equal (its models - /// are the same), so `list::sync` leaves its row; a change builds anew. + /// A line built again from an unchanged message is equal (so the list diff + /// leaves its row), with the cache or without; a change builds anew. #[test] fn unchanged_lines_compare_equal() { let cache = LineCache::default(); - // An avatar: an empty picture is never equal. - let avatar = Image::from_rgba8(slint::SharedPixelBuffer::new(1, 1)); + let avatar = ImageSource::rgba(1, 1, vec![0u8; 4]); let ctx = LineCtx { key: 3, avatar, cache: Some(&cache), ..Default::default() }; let mut stored = stored(message("A", "[b]hi[/b] 🎉", 0)); let first = history_line(&stored, None, &ctx); assert!(first == history_line(&stored, None, &ctx)); - // Without the cache, models are new each time. let plain = LineCtx { key: 3, avatar: ctx.avatar.clone(), ..Default::default() }; - assert!(history_line(&stored, None, &plain) != history_line(&stored, None, &plain)); + assert!(history_line(&stored, None, &plain) == first); stored.reactions[0].count = 3; let reacted = history_line(&stored, None, &ctx); assert!(reacted != first && reacted.blocks == first.blocks); @@ -983,7 +953,7 @@ mod tests { stored.rev = 2; let edited = history_line(&stored, None, &ctx); assert!(edited.blocks != first.blocks); - assert_eq!(edited.text, "edited"); + assert_eq!(&*edited.text, "edited"); cache.keep([], 0); assert_eq!(cache.0.borrow().len(), 1, "few: kept"); } @@ -994,9 +964,9 @@ mod tests { let ctx = LineCtx { key: -1, cache: Some(&cache), ..Default::default() }; let welcome = server_line("Nightfall", "Welcome to [b]Nightfall[/b]!", i64::MIN, false, &ctx); - assert_eq!((welcome.author.as_str(), welcome.time.as_str()), ("Nightfall", "")); + assert_eq!((welcome.author.as_ref(), welcome.time.as_ref()), ("Nightfall", "")); assert!(welcome.rich && !welcome.continued && !welcome.remote && welcome.key == -1); - assert_eq!(welcome.text, "Welcome to Nightfall!"); + assert_eq!(&*welcome.text, "Welcome to Nightfall!"); assert!(server_line("Nightfall", "News", i64::MIN + 1, true, &ctx).continued); } @@ -1005,9 +975,9 @@ mod tests { let ctx = LineCtx { key: 4, gateway: true, ..Default::default() }; let line = history_line(&stored(message("A", "hi", 0)), None, &ctx); assert!(line.pinned && line.remote && line.key == 4); - assert_eq!(line.reactions.row_count(), 1); - let r = line.reactions.row_data(0).unwrap(); - assert_eq!((r.key.as_str(), r.count, r.me), ("1f389", 2, true)); + assert_eq!(line.reactions.len(), 1); + let r = line.reactions[0].clone(); + assert_eq!((r.key.as_ref(), r.count, r.me), ("1f389", 2, true)); // Without a gateway nothing can be pinned or reacted to. let plain = history_line(&stored(message("A", "hi", 0)), None, &LineCtx::default()); assert!(!plain.remote); @@ -1022,10 +992,10 @@ mod tests { format!("here you go {url} 🎉"), ] { let line = line(&message("A", &text, 0), None); - assert_eq!(line.files.row_count(), 1); - let file = line.files.row_data(0).unwrap(); - assert_eq!((file.name.as_str(), file.detail.as_str()), ("plan.pdf", "2.0 kB")); - assert_eq!(line.text, "here you go 🎉"); + assert_eq!(line.files.len(), 1); + let file = line.files[0].clone(); + assert_eq!((file.name.as_ref(), file.detail.as_ref()), ("plan.pdf", "2.0 kB")); + assert_eq!(&*line.text, "here you go 🎉"); assert!(line.rich); } // Only the link: no text. diff --git a/crates/voelin-ui-vm/src/color.rs b/crates/voelin-ui-vm/src/color.rs new file mode 100644 index 0000000..7a70f88 --- /dev/null +++ b/crates/voelin-ui-vm/src/color.rs @@ -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`. +#[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 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)); + } +} diff --git a/crates/voelin-ui/src/emoji.rs b/crates/voelin-ui-vm/src/emoji.rs similarity index 98% rename from crates/voelin-ui/src/emoji.rs rename to crates/voelin-ui-vm/src/emoji.rs index 413e950..00af232 100644 --- a/crates/voelin-ui/src/emoji.rs +++ b/crates/voelin-ui-vm/src/emoji.rs @@ -119,12 +119,7 @@ impl Archive { .map(|i| &self.entries[i]) } - /// Number of emoji in the archive. - #[cfg(test)] - pub fn len(&self) -> usize { - self.entries.len() - } - + /// The archive has an emoji for this key (code points joined by `-`). pub fn contains(&self, key: &str) -> bool { self.find(key).is_some() } @@ -350,7 +345,7 @@ mod tests { #[test] fn archive_opens() { let a = archive(); - assert!(a.len() > 3000); + assert!(a.entries.len() > 3000); assert!(a.contains("1f600")); assert!(!a.contains("zzz")); assert_eq!(a.name("1f600"), Some("grinning face")); diff --git a/crates/voelin-ui/src/vm/home.rs b/crates/voelin-ui-vm/src/home.rs similarity index 100% rename from crates/voelin-ui/src/vm/home.rs rename to crates/voelin-ui-vm/src/home.rs diff --git a/crates/voelin-ui-vm/src/image.rs b/crates/voelin-ui-vm/src/image.rs new file mode 100644 index 0000000..e92f464 --- /dev/null +++ b/crates/voelin-ui-vm/src/image.rs @@ -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; + +/// 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/`, `icons/`, + /// 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, + /// 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, +} + +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) -> 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>) -> 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 { + let end = value.find(|c: char| !c.is_ascii_digit() && c != '.').unwrap_or(value.len()); + value[..end].parse::().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("').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>> = 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 { + 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(""), Size { width: 32, height: 16 }); + assert_eq!(size(""), Size { width: 24, height: 12 }); + assert_eq!(size(""), Size { width: 1, height: 1 }); + assert_eq!(size("").width, 4096); + // Too large to decode. + assert!( + ImageSource::Svg(b"".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"; + 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(); + } +} diff --git a/crates/voelin-ui-vm/src/lib.rs b/crates/voelin-ui-vm/src/lib.rs new file mode 100644 index 0000000..fa25c8f --- /dev/null +++ b/crates/voelin-ui-vm/src/lib.rs @@ -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}; diff --git a/crates/voelin-ui-vm/src/list.rs b/crates/voelin-ui-vm/src/list.rs new file mode 100644 index 0000000..9aa690b --- /dev/null +++ b/crates/voelin-ui-vm/src/list.rs @@ -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); + +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(&self, rows: &mut Vec, 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(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> = (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, + })); + } + } + } +} diff --git a/crates/voelin-ui/src/vm/servers.rs b/crates/voelin-ui-vm/src/servers.rs similarity index 93% rename from crates/voelin-ui/src/vm/servers.rs rename to crates/voelin-ui-vm/src/servers.rs index c737f31..fe4e8cd 100644 --- a/crates/voelin-ui/src/vm/servers.rs +++ b/crates/voelin-ui-vm/src/servers.rs @@ -1,16 +1,19 @@ //! The server rail, the server dialog, and joining a channel. -use slint::{Color, SharedString}; +use std::sync::Arc; + use voelin_core::{ObserveState, SessionState, VoiceState}; use voelin_model::{ChannelId, ChannelInfo, Presence, ServerLink}; use voelin_store::Bookmark; -use crate::app::{BookmarkForm, ServerItem}; -use crate::vm::avatar; +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) -> slint::Image { +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()) } @@ -33,7 +36,7 @@ const SERVER_TINTS: [u32; 10] = [ /// 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 { +pub fn tints(bookmarks: &[Bookmark]) -> Vec { let n = SERVER_TINTS.len(); let mut taken = [false; SERVER_TINTS.len()]; bookmarks @@ -76,8 +79,8 @@ pub fn item( live: bool, detail: String, product: String, - icon: slint::Image, - tint: Color, + icon: ImageRef, + tint: Rgb, ) -> ServerItem { ServerItem { id: bookmark.id as i32, @@ -106,7 +109,7 @@ pub fn form( BookmarkForm { id: bookmark.id as i32, name: if bookmark.name == bookmark.address { - SharedString::new() + "".into() } else { bookmark.name.clone().into() }, @@ -134,7 +137,7 @@ pub struct ConnectTo { /// channel; and the link's privilege key. pub fn connect_to(form: &BookmarkForm, saved: Option<&Bookmark>) -> Option { let saved = saved?; - let given = |text: &SharedString| Some(text.to_string()).filter(|t| !t.is_empty()); + let given = |text: &Arc| 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)), @@ -215,7 +218,7 @@ pub fn link_form( mut form: BookmarkForm, default_nickname: &str, ) -> BookmarkForm { - let text = |value: &Option| SharedString::from(value.as_deref().unwrap_or_default()); + let text = |value: &Option| Arc::::from(value.as_deref().unwrap_or_default()); if form.id < 0 { form.address = link.address().into(); } @@ -223,7 +226,7 @@ pub fn link_form( form.nickname = link.nickname.as_deref().unwrap_or(default_nickname).into(); } if let Some(password) = &link.password { - form.server_password = password.into(); + form.server_password = password.as_str().into(); } form.channel = text(&link.channel); form.channel_password = text(&link.channel_password); @@ -302,9 +305,9 @@ mod tests { String::new(), String::new(), cached_icon(&bookmark, &cache), - Color::default(), + Rgb::default(), ); - assert_eq!(server.status.as_str(), "offline"); + 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); @@ -328,12 +331,12 @@ mod tests { String::new(), product.into(), Default::default(), - Color::default(), + Rgb::default(), ) }; - assert_eq!(on("TeamSpeak 6").product.as_str(), "TeamSpeak 6"); + 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_str(), ""); + assert_eq!(on("").product.as_ref(), ""); } fn named(names: &[&str]) -> Vec { @@ -341,7 +344,7 @@ mod tests { } /// The colour a name picks. - fn own_tint(name: &str, step: usize) -> Color { + 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]) } @@ -351,7 +354,7 @@ mod tests { let names: Vec = (0..SERVER_TINTS.len()).map(|i| format!("Server {i}")).collect(); let mut bookmarks = named(&names.iter().map(String::as_str).collect::>()); let distinct: std::collections::HashSet<_> = - tints(&bookmarks).iter().map(|t| t.as_argb_encoded()).collect(); + 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"])); @@ -385,8 +388,8 @@ mod tests { }; let mut state = SessionState::default(); let f = form(&b, None, "pw"); - assert_eq!((f.id, f.name.as_str(), f.address.as_str()), (3, "", "ts.example.test")); - assert_eq!((f.nickname.as_str(), f.server_password.as_str()), ("Nova", "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), @@ -402,7 +405,7 @@ mod tests { state.observe = ObserveState::Observing; assert!(!form(&b, Some(&state), "").connected); let named = Bookmark { name: "Nightfall".into(), ..b }; - assert_eq!(form(&named, None, "").name.as_str(), "Nightfall"); + assert_eq!(form(&named, None, "").name.as_ref(), "Nightfall"); } #[test] @@ -568,16 +571,16 @@ mod tests { // 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_str(), f.address.as_str()), (-1, "", "ts.example.org:9988")); - assert_eq!((f.nickname.as_str(), f.server_password.as_str()), ("Link", "pw")); + 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_str(), f.channel_password.as_str(), f.token.as_str()), + (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_str(), f.nickname.as_str()), ("ts.example.org", "Me")); + assert_eq!((f.address.as_ref(), f.nickname.as_ref()), ("ts.example.org", "Me")); assert_eq!( - (f.server_password.as_str(), f.channel.as_str(), f.token.as_str()), + (f.server_password.as_ref(), f.channel.as_ref(), f.token.as_ref()), ("", "", "") ); // A saved server keeps its address, name, nickname and password... @@ -591,14 +594,14 @@ mod tests { }; let f = link_form(&bare, saved.clone(), "Me"); assert_eq!( - (f.id, f.name.as_str(), f.address.as_str()), + (f.id, f.name.as_ref(), f.address.as_ref()), (3, "Nightfall", "TS.example.org:9988") ); - assert_eq!((f.nickname.as_str(), f.server_password.as_str()), ("Nova", "stored")); + 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_str(), f.server_password.as_str()), ("Nova", "pw")); - assert_eq!((f.channel.as_str(), f.token.as_str()), ("Gaming/Raid Night", "key")); + 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] diff --git a/crates/voelin-ui/src/settings.rs b/crates/voelin-ui-vm/src/settings.rs similarity index 94% rename from crates/voelin-ui/src/settings.rs rename to crates/voelin-ui-vm/src/settings.rs index 8d1c2f0..715b70e 100644 --- a/crates/voelin-ui/src/settings.rs +++ b/crates/voelin-ui-vm/src/settings.rs @@ -9,7 +9,7 @@ use voelin_audio::process::NoiseLevel; use voelin_core::settings::{Key, Kind}; use voelin_core::{AudioSettings, TransmitMode}; -use crate::app::AudioForm; +use crate::bridge::AudioForm; /// The window's settings, one value (the `ui` blob of earlier versions). pub static UI: Key = Key::new( @@ -39,6 +39,7 @@ pub enum ThemeChoice { } impl ThemeChoice { + /// The value stored for this choice. pub fn as_str(self) -> &'static str { match self { Self::Dark => "dark", @@ -47,6 +48,7 @@ impl ThemeChoice { } } + /// The choice a stored value names (dark for any other). pub fn parse(text: &str) -> Self { match text { "light" => Self::Light, @@ -133,10 +135,12 @@ pub enum NotifyLevel { } 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, @@ -155,22 +159,26 @@ pub static NOTIFY_MENTIONS: Key = Key::new( "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 = 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 = 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 = 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 = Key::new( "notify.friends_online", NOTIFY_LEVELS, @@ -253,11 +261,14 @@ pub fn page_keys() -> [&'static dyn voelin_core::settings::Setting; 10] { /// 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`. @@ -270,6 +281,8 @@ pub fn parse_positive(text: &str) -> Option { 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 { @@ -347,11 +360,13 @@ impl Default for ClientPlayback { } 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; /// Audio devices as listed in the settings: the system default first. @@ -387,10 +402,14 @@ impl DeviceChoices { 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 { usize::try_from(index).ok().and_then(|i| self.ids.get(i).cloned()).flatten() } diff --git a/crates/voelin-ui-vm/src/settings_pages/logic.rs b/crates/voelin-ui-vm/src/settings_pages/logic.rs new file mode 100644 index 0000000..204fa4f --- /dev/null +++ b/crates/voelin-ui-vm/src/settings_pages/logic.rs @@ -0,0 +1,1367 @@ +//! What the settings pages show and what their controls change, apart from +//! the toolkit: the forms read from the settings, the settings written from +//! the forms, and the lists of the Integrations and Profiles pages. +//! +//! The functions work on the settings service (`voelin_core::settings`), the +//! app's state ([`AppState`]) and the plain rows of [`crate::bridge`]. A +//! function that changes settings returns the messages for the status line +//! (what the service refused, what was typed wrong); the front end shows them +//! and fills its forms again. The Slint front end's side of this is +//! `voelin-ui`'s `settings_pages/bind.rs`. + +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; +use std::sync::atomic::AtomicBool; + +use serde::Serialize; +use serde::de::DeserializeOwned; +use voelin_core::media::auto_bitrate; +use voelin_core::media::voelin_media::EncoderInfo; +use voelin_core::settings::{ + AudioSourceKindSetting, AudioSourceSetting, BlockMode, CACHE_FETCH_IMAGES, CACHE_MAX_MB, + CHAT_DEDUPE_TOLERANCE_MS, CHAT_HISTORY_PAGE, CHAT_RETENTION_DAYS, CHAT_STORE_HISTORY, + CaptureChoice, CodecChoice, FILES_PROGRESS_MS, Key, LayerSetting, PRIVACY_BLOCK_MODE, + PRIVACY_POKES, PRIVACY_PRIVATE_MESSAGES, SRTP_PROFILES, STREAM_AUDIO_SOURCES, + STREAM_BITRATE_KBPS, STREAM_CAPTURE_BACKEND, STREAM_CODEC, STREAM_DECODER_BACKEND, + STREAM_ENCODER_BACKEND, STREAM_FPS, STREAM_HARDWARE_ACCELERATION, STREAM_HARDWARE_DECODING, + STREAM_LAYERS, STREAM_PERMISSIONS, STREAM_SRTP_PROFILES, STUDIO_RECORDING_DIR, + STUDIO_REPLAY_MEMORY_MB, STUDIO_REPLAY_SECONDS, Settings, Source as SettingSource, + StreamPermissions, +}; +use voelin_core::ts::identity::Found; +use voelin_gateway_proto::{ConfigSource, PermRule, feature}; +use voelin_store::{Bookmark, IdentityEntry, IdentityOrigin}; + +use crate::bridge::{ + AccountForm, AdvancedForm, AudioSourceItem, BookmarkIdentity, ConfigItem, EncoderItem, + FoundIdentity, GatewayItem, IdentityItem, LayerItem, NotifyForm, PermItem, PrivacyForm, + SettingItem, StreamingForm, VideoForm, +}; +use crate::settings::{ + NOTIFY_EVENTS, NOTIFY_FRIENDS, NOTIFY_MENTIONS, NOTIFY_MESSAGES, NOTIFY_POKES, NotifyLevel, + UI_IMAGE_PREVIEW_KB, VIDEO_BACKGROUND, VIDEO_CAMERA, VIDEO_MIRROR, VIDEO_RESOLUTION, + parse_positive, parse_size, +}; +use crate::state::{AppState, SessionExtra}; + +/// Sizes of the stream quality presets (Auto: the source's size). +const PRESETS: [(u32, u32); 5] = + [(1280, 720), (1920, 1080), (2560, 1440), (3840, 2160), (7680, 4320)]; + +/// An identity whose level is being raised. +pub struct Improving { + /// The level aimed at. + pub target: u8, + /// The best level reached so far. + pub reached: u8, + /// Set to stop the search. + pub cancel: Arc, +} + +/// What the settings pages remember apart from the settings themselves. +#[derive(Default)] +pub struct PagesState { + /// The identities whose level is being raised, by store id. + pub improving: HashMap, + /// Identities found in other clients' files, picked for import. + pub found: Vec<(Found, bool)>, + /// What the list of all settings is filtered by. + pub settings_filter: String, + /// The gateway being administered (a bookmark id). + pub admin: Option, + /// Camera ids by the index of the cameras list. + pub cameras: Vec, + /// The encoders are being probed. + pub encoders_loading: bool, +} + +/// "1920x1080" or "0.5" for a layer. +fn layer_size(l: &LayerSetting) -> String { + match l.size { + Some((w, h)) => format!("{w}x{h}"), + None => format!("{}", l.scale), + } +} + +/// kbit/s of bit/s, as typed. +fn kbps(bits: u64) -> String { + (bits / 1000).to_string() +} + +/// A layer as the Streaming page's row shows it. +pub fn layer_item(l: &LayerSetting) -> LayerItem { + LayerItem { + size: layer_size(l).into(), + fps: l.max_fps.map(|f| f.to_string()).unwrap_or_default().into(), + bitrate: kbps(l.bitrate).into(), + min_bitrate: kbps(l.min_bitrate).into(), + max_bitrate: l.max_bitrate.map(kbps).unwrap_or_default().into(), + } +} + +/// A layer from what was typed; `None` when it is not a layer. +pub fn layer_of(item: &LayerItem, base: &LayerSetting) -> Option { + let mut l = base.clone(); + match parse_size(&item.size) { + Some(size) => l.size = Some(size), + None => { + l.size = None; + l.scale = item.size.trim().parse().ok().filter(|s: &f32| *s > 0.0)?; + } + } + let number = |t: &str| t.trim().parse::().ok(); + l.max_fps = number(&item.fps).map(|f| f as u32).filter(|f| *f > 0); + l.bitrate = number(&item.bitrate).filter(|b| *b > 0)? * 1000; + l.min_bitrate = number(&item.min_bitrate).unwrap_or(0) * 1000; + l.max_bitrate = number(&item.max_bitrate).map(|b| b * 1000).filter(|m| *m >= l.bitrate); + Some(l) +} + +/// The layers of quality preset `quality` (0: none, the source's size; +/// then [`PRESETS`]) at `kbps` (0: automatic, for the preset's size and +/// `fps`); `None` for no preset (layers of one's own). +pub fn preset_layers(quality: i32, kbps: u32, fps: u32) -> Option> { + match usize::try_from(quality).ok()? { + 0 => Some(Vec::new()), + q => PRESETS.get(q - 1).map(|&(width, height)| { + let bitrate = match kbps { + 0 => auto_bitrate(width, height, fps), + kbps => u64::from(kbps) * 1000, + }; + vec![LayerSetting { size: Some((width, height)), bitrate, ..LayerSetting::default() }] + }), + } +} + +/// The preset of a list of layers: 0 Auto (none), 1..5 a preset size, -1 +/// other layers. +pub fn quality_of(layers: &[LayerSetting]) -> i32 { + match layers { + [] => 0, + [one] => PRESETS.iter().position(|p| one.size == Some(*p)).map_or(-1, |i| i as i32 + 1), + _ => -1, + } +} + +/// An audio source of the stream as the Streaming page's row shows it +/// (`app_name`: the app's own name, for "Desktop without ..."). +pub fn source_item(s: &AudioSourceSetting, app_name: &str) -> AudioSourceItem { + let (kind, name, detail) = match &s.kind { + AudioSourceKindSetting::Desktop => { + ("desktop", format!("Desktop without {app_name}"), "Everything that plays".to_owned()) + } + AudioSourceKindSetting::App { name, pid } => ( + "app", + name.clone().unwrap_or_else(|| format!("Process {}", pid.unwrap_or_default())), + "Application".to_owned(), + ), + AudioSourceKindSetting::Window => { + ("window", "The shared window's app".to_owned(), "Where the system tells".to_owned()) + } + AudioSourceKindSetting::Microphone => { + ("microphone", "Microphone".to_owned(), "After noise suppression".to_owned()) + } + AudioSourceKindSetting::Synthetic { frequency } => { + ("synthetic", "Test tone".to_owned(), format!("{frequency} Hz")) + } + }; + AudioSourceItem { + kind: kind.into(), + name: name.into(), + detail: detail.into(), + gain: s.gain * 100.0, + muted: s.muted, + } +} + +/// Where a gateway's configuration value comes from, in words. +pub fn config_source(s: ConfigSource) -> &'static str { + match s { + ConfigSource::Db => "set at runtime", + ConfigSource::Cli => "command line", + ConfigSource::Env => "environment", + ConfigSource::File => "file", + ConfigSource::Default => "default", + ConfigSource::Unknown => "?", + } +} + +/// A permission rule in words. +pub fn rule_text(rule: &PermRule) -> String { + let mut parts = Vec::new(); + if rule.everyone { + parts.push("everyone".to_owned()); + } + let list = |ids: &[u64]| ids.iter().map(u64::to_string).collect::>().join(", "); + if !rule.server_groups.is_empty() { + parts.push(format!("server groups {}", list(&rule.server_groups))); + } + if !rule.channel_groups.is_empty() { + parts.push(format!("channel groups {}", list(&rule.channel_groups))); + } + if parts.is_empty() { "nobody".into() } else { parts.join("; ") } +} + +/// "6, 7" → [6, 7] (other words are left out). +pub fn group_ids(text: &str) -> Vec { + text.split([',', ' ']).filter_map(|t| t.trim().parse().ok()).collect() +} + +/// A value typed into a JSON field: JSON when it parses, else a string. +pub fn json_of(text: &str) -> serde_json::Value { + serde_json::from_str(text).unwrap_or_else(|_| serde_json::Value::String(text.to_owned())) +} + +/// The codec choice as the pages' lists index it. +pub fn codec_index(c: CodecChoice) -> i32 { + match c { + CodecChoice::Auto => 0, + CodecChoice::Vp8 => 1, + CodecChoice::Vp9 => 2, + CodecChoice::H264 => 3, + CodecChoice::Av1 => 4, + } +} + +/// The codec choice of an index of the pages' lists. +pub fn codec_of(i: i32) -> CodecChoice { + match i { + 1 => CodecChoice::Vp8, + 2 => CodecChoice::Vp9, + 3 => CodecChoice::H264, + 4 => CodecChoice::Av1, + _ => CodecChoice::Auto, + } +} + +/// Where an identity came from, as Profiles says it. +pub fn origin_label(origin: IdentityOrigin) -> &'static str { + match origin { + IdentityOrigin::Created => "Made in Voelin", + IdentityOrigin::Imported => "Imported", + IdentityOrigin::User => "Chosen by you", + } +} + +// The forms, from the settings. + +/// The Voice & Video form. `cameras`: the ids of the cameras list; +/// `preview`: the camera preview runs. +pub fn video_form(p: &Settings, cameras: &[String], preview: bool) -> VideoForm { + let camera = p.get(&VIDEO_CAMERA); + VideoForm { + camera: cameras.iter().position(|c| *c == camera).unwrap_or(0) as i32, + background: i32::from(p.get(&VIDEO_BACKGROUND) == "blur"), + resolution: p.get(&VIDEO_RESOLUTION).into(), + fps: p.get(&STREAM_FPS).to_string().into(), + codec: codec_index(p.get(&STREAM_CODEC)), + hardware: p.get(&STREAM_HARDWARE_ACCELERATION), + mirror: p.get(&VIDEO_MIRROR), + permissions: match p.get(&STREAM_PERMISSIONS) { + StreamPermissions::Everyone => 0, + StreamPermissions::Friends => 1, + StreamPermissions::Channel => 2, + StreamPermissions::Nobody => 3, + }, + quality: quality_of(&p.get(&STREAM_LAYERS)), + bitrate: p.get(&STREAM_BITRATE_KBPS) as f32, + preview, + } +} + +/// The Streaming page's defaults. +pub fn streaming_form(p: &Settings) -> StreamingForm { + StreamingForm { + fps: p.get(&STREAM_FPS).to_string().into(), + bitrate: p.get(&STREAM_BITRATE_KBPS).to_string().into(), + codec: codec_index(p.get(&STREAM_CODEC)), + capture: match p.get(&STREAM_CAPTURE_BACKEND) { + CaptureChoice::Auto => 0, + CaptureChoice::Portal => 1, + CaptureChoice::Wlroots => 2, + CaptureChoice::X11 => 3, + }, + replay_seconds: p.get(&STUDIO_REPLAY_SECONDS).to_string().into(), + replay_memory: p.get(&STUDIO_REPLAY_MEMORY_MB).to_string().into(), + recording_dir: p.get(&STUDIO_RECORDING_DIR).into(), + } +} + +/// The stream's layers, one row each. +pub fn layer_items(p: &Settings) -> Vec { + p.get(&STREAM_LAYERS).iter().map(layer_item).collect() +} + +/// The stream's audio sources, one row each (`app_name`: see +/// [`source_item`]). +pub fn audio_source_items(p: &Settings, app_name: &str) -> Vec { + p.get(&STREAM_AUDIO_SOURCES).iter().map(|s| source_item(s, app_name)).collect() +} + +/// The notification levels. +pub fn notify_form(p: &Settings) -> NotifyForm { + NotifyForm { + mentions: p.get(&NOTIFY_MENTIONS).index(), + pokes: p.get(&NOTIFY_POKES).index(), + messages: p.get(&NOTIFY_MESSAGES).index(), + events: p.get(&NOTIFY_EVENTS).index(), + friends: p.get(&NOTIFY_FRIENDS).index(), + } +} + +/// What a privacy or notification choice is as an index, and back. +pub fn allowed_index(a: voelin_core::settings::Allowed) -> i32 { + match a { + voelin_core::settings::Allowed::Everyone => 0, + voelin_core::settings::Allowed::Friends => 1, + voelin_core::settings::Allowed::Nobody => 2, + } +} + +/// The privacy or notification choice of an index. +pub fn allowed_of(index: i32) -> voelin_core::settings::Allowed { + match index { + 1 => voelin_core::settings::Allowed::Friends, + 2 => voelin_core::settings::Allowed::Nobody, + _ => voelin_core::settings::Allowed::Everyone, + } +} + +/// Privacy & Safety. +pub fn privacy_form(p: &Settings) -> PrivacyForm { + PrivacyForm { + block_mode: i32::from(p.get(&PRIVACY_BLOCK_MODE) == BlockMode::Flag), + messages: allowed_index(p.get(&PRIVACY_PRIVATE_MESSAGES)), + pokes: allowed_index(p.get(&PRIVACY_POKES)), + } +} + +/// Advanced. `logs` and `crash_dir` are the texts about where the logs and +/// crash reports go, which the front end knows. +pub fn advanced_form(p: &Settings, logs: &str, crash_dir: &str) -> AdvancedForm { + AdvancedForm { + encoder: p.get(&STREAM_ENCODER_BACKEND).into(), + hardware: p.get(&STREAM_HARDWARE_ACCELERATION), + decoder: p.get(&STREAM_DECODER_BACKEND).into(), + hardware_decoding: p.get(&STREAM_HARDWARE_DECODING), + store_history: p.get(&CHAT_STORE_HISTORY), + history_page: p.get(&CHAT_HISTORY_PAGE).to_string().into(), + dedupe_ms: p.get(&CHAT_DEDUPE_TOLERANCE_MS).to_string().into(), + retention_days: p.get(&CHAT_RETENTION_DAYS).to_string().into(), + cache_mb: p.get(&CACHE_MAX_MB).to_string().into(), + fetch_images: p.get(&CACHE_FETCH_IMAGES), + progress_ms: p.get(&FILES_PROGRESS_MS).to_string().into(), + preview_kb: p.get(&UI_IMAGE_PREVIEW_KB).to_string().into(), + logs: logs.into(), + crash_dir: crash_dir.into(), + } +} + +/// The SRTP profiles that are not offered (those that can be added). +pub fn srtp_unused(offered: &[String]) -> Vec<&'static str> { + SRTP_PROFILES.iter().filter(|n| !offered.iter().any(|s| s == *n)).copied().collect() +} + +/// Every registered setting (Advanced) whose name or description has +/// `filter` (lower case; empty: all). +pub fn setting_items(p: &Settings, filter: &str) -> Vec { + p.keys() + .into_iter() + .filter(|k| { + filter.is_empty() + || k.name().contains(filter) + || k.doc().to_lowercase().contains(filter) + }) + .map(|k| SettingItem { + key: k.name().into(), + doc: k.doc().into(), + value: p.get_json(k.name()).map(|v| v.to_string()).unwrap_or_default().into(), + source: match p.source(k.name()) { + Some(SettingSource::Runtime) => "set here", + Some(SettingSource::Override) => "command line", + Some(SettingSource::Config) => "config file", + _ => "default", + } + .into(), + }) + .collect() +} + +// The settings, from the forms. + +/// Stores settings, and keeps what is to be said about it. +struct Put<'a> { + prefs: &'a Settings, + said: Vec, +} + +impl<'a> Put<'a> { + fn new(prefs: &'a Settings) -> Self { + Self { prefs, said: Vec::new() } + } + + /// Store a setting; a refusal is something to say. + fn put(&mut self, key: &'static Key, value: T) + where + T: Serialize + DeserializeOwned + Send + Sync + 'static, + { + if let Err(e) = self.prefs.set(key, value) { + self.said.push(e.to_string()); + } + } + + /// Store a setting unless it is what it is already. + fn put_if_changed(&mut self, key: &'static Key, value: T) + where + T: Clone + PartialEq + Serialize + DeserializeOwned + Send + Sync + 'static, + { + if self.prefs.get(key) != value { + self.put(key, value); + } + } + + fn say(&mut self, text: impl Into) { + self.said.push(text.into()); + } + + fn done(self) -> Vec { + self.said + } +} + +/// The Voice & Video form was changed. `cameras`: the ids of the cameras +/// list. Returns what is to be said in the status line. +pub fn apply_video(prefs: &Settings, cameras: &[String], form: &VideoForm) -> Vec { + let mut p = Put::new(prefs); + if let Some(id) = usize::try_from(form.camera).ok().and_then(|i| cameras.get(i)).cloned() { + p.put_if_changed(&VIDEO_CAMERA, id); + } + let background = if form.background == 1 { "blur" } else { "none" }; + p.put_if_changed(&VIDEO_BACKGROUND, background.to_owned()); + p.put_if_changed(&VIDEO_RESOLUTION, form.resolution.to_string()); + if let Some(fps) = parse_positive(&form.fps) { + p.put_if_changed(&STREAM_FPS, fps); + } + p.put_if_changed(&STREAM_CODEC, codec_of(form.codec)); + p.put_if_changed(&STREAM_HARDWARE_ACCELERATION, form.hardware); + p.put_if_changed(&VIDEO_MIRROR, form.mirror); + let permissions = match form.permissions { + 0 => StreamPermissions::Everyone, + 1 => StreamPermissions::Friends, + 3 => StreamPermissions::Nobody, + _ => StreamPermissions::Channel, + }; + p.put_if_changed(&STREAM_PERMISSIONS, permissions); + // 0: automatic. + let bitrate = form.bitrate.round().max(0.0) as u32; + p.put_if_changed(&STREAM_BITRATE_KBPS, bitrate); + // A preset: one layer of that size at the bitrate (an automatic one + // for that size and the frame rate); Auto: none. + let layers = prefs.get(&STREAM_LAYERS); + let wanted = preset_layers(form.quality, bitrate, prefs.get(&STREAM_FPS)); + if let Some(wanted) = wanted.filter(|w| *w != layers) { + p.put(&STREAM_LAYERS, wanted); + } + p.done() +} + +/// The Streaming page's defaults were changed. +pub fn apply_streaming(prefs: &Settings, form: &StreamingForm) -> Vec { + let mut p = Put::new(prefs); + if let Some(fps) = parse_positive(&form.fps) { + p.put(&STREAM_FPS, fps); + } + // Nothing, 0 or "auto": automatic. + let bitrate = form.bitrate.trim(); + let auto = bitrate.is_empty() || bitrate == "0" || bitrate.eq_ignore_ascii_case("auto"); + if let Some(bitrate) = parse_positive(bitrate).or(auto.then_some(0)) { + p.put(&STREAM_BITRATE_KBPS, bitrate); + } + p.put(&STREAM_CODEC, codec_of(form.codec)); + p.put( + &STREAM_CAPTURE_BACKEND, + match form.capture { + 1 => CaptureChoice::Portal, + 2 => CaptureChoice::Wlroots, + 3 => CaptureChoice::X11, + _ => CaptureChoice::Auto, + }, + ); + if let Ok(seconds) = form.replay_seconds.trim().parse() { + p.put(&STUDIO_REPLAY_SECONDS, seconds); + } + if let Ok(mb) = form.replay_memory.trim().parse() { + p.put(&STUDIO_REPLAY_MEMORY_MB, mb); + } + p.put(&STUDIO_RECORDING_DIR, form.recording_dir.trim().to_owned()); + p.done() +} + +/// A row of the stream's layers was edited. `None`: there is no such layer, +/// nothing was done. +pub fn apply_layer(prefs: &Settings, index: i32, item: &LayerItem) -> Option> { + let mut layers = prefs.get(&STREAM_LAYERS); + let slot = usize::try_from(index).ok().filter(|i| *i < layers.len())?; + let mut p = Put::new(prefs); + match layer_of(item, &layers[slot]) { + Some(layer) => { + layers[slot] = layer; + p.put(&STREAM_LAYERS, layers); + } + None => p.say("A layer needs a size (1280x720) or scale (0.5) and a bitrate."), + } + Some(p.done()) +} + +/// Add a layer: half the size of the one before and a quarter of its +/// bitrate. +pub fn add_layer(prefs: &Settings) -> Vec { + let mut layers = prefs.get(&STREAM_LAYERS); + let bitrate = u64::from(prefs.get(&STREAM_BITRATE_KBPS)) * 1000; + let scale = 0.5f32.powi(layers.len() as i32); + layers.push(LayerSetting { + scale, + bitrate: (bitrate / 4u64.pow(layers.len() as u32)).max(100_000), + ..LayerSetting::default() + }); + let mut p = Put::new(prefs); + p.put(&STREAM_LAYERS, layers); + p.done() +} + +/// Remove a layer (no such one: nothing). +pub fn remove_layer(prefs: &Settings, index: i32) -> Vec { + let mut layers = prefs.get(&STREAM_LAYERS); + let mut p = Put::new(prefs); + if let Some(i) = usize::try_from(index).ok().filter(|i| *i < layers.len()) { + layers.remove(i); + p.put(&STREAM_LAYERS, layers); + } + p.done() +} + +/// The gain or the mute of an audio source of the stream was changed. +pub fn apply_audio_source(prefs: &Settings, index: i32, item: &AudioSourceItem) -> Vec { + let mut sources = prefs.get(&STREAM_AUDIO_SOURCES); + let mut p = Put::new(prefs); + if let Some(s) = usize::try_from(index).ok().and_then(|i| sources.get_mut(i)) { + s.gain = (item.gain / 100.0).max(0.0); + s.muted = item.muted; + p.put(&STREAM_AUDIO_SOURCES, sources); + } + p.done() +} + +/// Add an audio source of `kind` ("desktop", "window", "microphone", or +/// "app" with its `name`). `None`: not a source, nothing was done. +pub fn add_audio_source(prefs: &Settings, kind: &str, name: &str) -> Option> { + let kind = match kind { + "desktop" => AudioSourceKindSetting::Desktop, + "window" => AudioSourceKindSetting::Window, + "microphone" => AudioSourceKindSetting::Microphone, + "app" if !name.is_empty() => { + AudioSourceKindSetting::App { name: Some(name.to_owned()), pid: None } + } + _ => return None, + }; + let mut sources = prefs.get(&STREAM_AUDIO_SOURCES); + sources.push(AudioSourceSetting::new(kind)); + let mut p = Put::new(prefs); + p.put(&STREAM_AUDIO_SOURCES, sources); + Some(p.done()) +} + +/// Remove an audio source of the stream (no such one: nothing). +pub fn remove_audio_source(prefs: &Settings, index: i32) -> Vec { + let mut sources = prefs.get(&STREAM_AUDIO_SOURCES); + let mut p = Put::new(prefs); + if let Some(i) = usize::try_from(index).ok().filter(|i| *i < sources.len()) { + sources.remove(i); + p.put(&STREAM_AUDIO_SOURCES, sources); + } + p.done() +} + +/// The notification levels were changed. +pub fn apply_notify(prefs: &Settings, form: &NotifyForm) -> Vec { + let mut p = Put::new(prefs); + p.put(&NOTIFY_MENTIONS, NotifyLevel::from_index(form.mentions)); + p.put(&NOTIFY_POKES, NotifyLevel::from_index(form.pokes)); + p.put(&NOTIFY_MESSAGES, NotifyLevel::from_index(form.messages)); + p.put(&NOTIFY_EVENTS, NotifyLevel::from_index(form.events)); + p.put(&NOTIFY_FRIENDS, NotifyLevel::from_index(form.friends)); + p.done() +} + +/// Privacy & Safety was changed. +pub fn apply_privacy(prefs: &Settings, form: &PrivacyForm) -> Vec { + let mut p = Put::new(prefs); + p.put( + &PRIVACY_BLOCK_MODE, + if form.block_mode == 1 { BlockMode::Flag } else { BlockMode::Hide }, + ); + p.put(&PRIVACY_PRIVATE_MESSAGES, allowed_of(form.messages)); + p.put(&PRIVACY_POKES, allowed_of(form.pokes)); + p.done() +} + +/// Advanced was changed (a number that is not one leaves its setting alone). +pub fn apply_advanced(prefs: &Settings, form: &AdvancedForm) -> Vec { + let mut p = Put::new(prefs); + let number = |t: &Arc| t.trim().parse::().ok(); + if !form.encoder.trim().is_empty() { + p.put(&STREAM_ENCODER_BACKEND, form.encoder.trim().to_owned()); + } + p.put(&STREAM_HARDWARE_ACCELERATION, form.hardware); + if !form.decoder.trim().is_empty() { + p.put(&STREAM_DECODER_BACKEND, form.decoder.trim().to_owned()); + } + p.put(&STREAM_HARDWARE_DECODING, form.hardware_decoding); + p.put(&CHAT_STORE_HISTORY, form.store_history); + if let Some(v) = number(&form.history_page) { + p.put(&CHAT_HISTORY_PAGE, v as u32); + } + if let Some(v) = number(&form.dedupe_ms) { + p.put(&CHAT_DEDUPE_TOLERANCE_MS, v); + } + if let Some(v) = number(&form.retention_days) { + p.put(&CHAT_RETENTION_DAYS, v as u32); + } + if let Some(v) = number(&form.cache_mb) { + p.put(&CACHE_MAX_MB, v); + } + p.put(&CACHE_FETCH_IMAGES, form.fetch_images); + if let Some(v) = number(&form.progress_ms) { + p.put(&FILES_PROGRESS_MS, v as u32); + } + if let Some(v) = number(&form.preview_kb) { + p.put(&UI_IMAGE_PREVIEW_KB, v as u32); + } + p.done() +} + +/// Move an SRTP profile up (`by` -1) or down (1). `None`: it cannot be +/// moved there, nothing was done. +pub fn srtp_move(prefs: &Settings, index: i32, by: i32) -> Option> { + let mut list = prefs.get(&STREAM_SRTP_PROFILES); + let (Ok(from), Ok(to)) = (usize::try_from(index), usize::try_from(index + by)) else { + return None; + }; + let mut p = Put::new(prefs); + if from < list.len() && to < list.len() { + list.swap(from, to); + p.put(&STREAM_SRTP_PROFILES, list); + } + Some(p.done()) +} + +/// Offer a profile, or stop offering it (one stays). `None`: it is the one +/// that stays, nothing was done. +pub fn srtp_toggle(prefs: &Settings, name: &str) -> Option> { + let mut list = prefs.get(&STREAM_SRTP_PROFILES); + match list.iter().position(|p| p == name) { + Some(i) if list.len() > 1 => { + list.remove(i); + } + Some(_) => return None, + None => list.push(name.to_owned()), + } + let mut p = Put::new(prefs); + p.put(&STREAM_SRTP_PROFILES, list); + Some(p.done()) +} + +// Integrations. + +/// The gateways of our servers, one row each. +pub fn gateway_items(state: &AppState) -> Vec { + state + .bookmarks + .iter() + .filter_map(|b| { + let url = b.gateway_url.clone()?; + let view = state.sessions.get(&b.id); + let caps = view.map(|v| v.gateway_caps.clone()).unwrap_or_default(); + let status = match view.map(|v| v.state.observe) { + _ if !caps.is_empty() => "connected", + Some(voelin_core::ObserveState::Connecting) => "connecting", + _ => "off", + }; + Some(GatewayItem { + session: b.id as i32, + server: b.name.clone().into(), + url: url.into(), + status: status.into(), + admin: caps.iter().any(|c| c == feature::ADMIN), + features: caps.into_iter().map(Arc::::from).collect(), + }) + }) + .collect() +} + +/// The configuration keys of the gateway being administered. +pub fn config_items(extra: Option<&SessionExtra>) -> Vec { + extra + .map(|e| { + e.config + .iter() + .map(|c| ConfigItem { + key: c.key.clone().into(), + value: c.value.to_string().into(), + source: config_source(c.source).into(), + description: c.description.clone().into(), + kind: c.value_type.clone().into(), + bootstrap: c.bootstrap, + }) + .collect() + }) + .unwrap_or_default() +} + +/// The permission rules of the gateway being administered. +pub fn perm_items(extra: Option<&SessionExtra>) -> Vec { + extra + .map(|e| { + e.perms + .iter() + .map(|r| { + let rule = r.rule.clone().unwrap_or_default(); + let list = + |ids: &[u64]| ids.iter().map(u64::to_string).collect::>().join(", "); + PermItem { + action: r.action.as_str().into(), + rule: match &r.rule { + Some(rule) => rule_text(rule), + None => format!("Default: {}", r.default), + } + .into(), + source: config_source(r.source).into(), + everyone: rule.everyone, + server_groups: list(&rule.server_groups).into(), + channel_groups: list(&rule.channel_groups).into(), + } + }) + .collect() + }) + .unwrap_or_default() +} + +/// The encoders (or decoders) the probe found, one row each. A decoder's +/// entry is an encoder's (its rank: the place in its codec's ladder). +pub fn encoder_items(list: &[EncoderInfo]) -> Vec { + list.iter() + .map(|e| EncoderItem { + name: e.name.clone().into(), + api: e.api.clone().into(), + codec: format!("{:?}", e.codec).to_uppercase().into(), + hardware: e.hardware, + ok: e.status.is_ok(), + status: match (&e.status, e.rank) { + (Err(why), _) => why.clone(), + (Ok(()), Some(0)) => format!("{} · used first", e.api), + (Ok(()), Some(n)) => format!("{} · choice {}", e.api, n + 1), + (Ok(()), None) => format!("{} · not used", e.api), + } + .into(), + }) + .collect() +} + +/// What the probe says of FFmpeg. +pub fn ffmpeg_status(ffmpeg: &Result) -> String { + match ffmpeg { + Ok(v) => format!("FFmpeg: {v}"), + Err(e) => format!("FFmpeg is not used: {e}"), + } +} + +/// What the probe says of capture without a copy. +pub fn zero_copy_status(zero_copy: &Result<(), String>) -> String { + match zero_copy { + Ok(()) => "Screen capture goes to the GPU encoder without a copy.".to_owned(), + Err(e) => format!("No zero-copy capture: {e}"), + } +} + +/// The screens and windows that can be shared, as the list shows them (the +/// error for a list that could not be made). +pub fn capture_source_names(listed: Result, String>) -> Vec { + match listed { + Ok(list) => list + .into_iter() + .map(|(n, d)| if d.is_empty() { n } else { format!("{n} · {d}") }) + .collect(), + Err(e) => vec![e], + } +} + +// Identities. + +/// An identity of the store with what its key says: its unique id on +/// TeamSpeak 6 servers and its level (`None` when the key could not be read). +pub struct IdentityFacts<'a> { + /// The store's entry. + pub entry: &'a IdentityEntry, + /// The unique id on TeamSpeak 6 servers and the level of the key. + pub key: Option<(String, u8)>, +} + +/// The identities, one row each. `used`: each bookmark's name and the +/// identity it connects with; `improving`: the level aimed at and the best +/// one reached of an identity whose level is being raised. +pub fn identity_items( + identities: &[IdentityFacts<'_>], + default: Option, + used: &[(&str, Option)], + improving: impl Fn(i64) -> Option<(u8, u8)>, +) -> Vec { + identities + .iter() + .map(|IdentityFacts { entry: e, key }| { + let improving = improving(e.id); + let used: Vec<&str> = + used.iter().filter(|(_, id)| *id == Some(e.id)).map(|(name, _)| *name).collect(); + IdentityItem { + id: e.id as i32, + name: e.name.clone().into(), + uid: e.uid.clone().into(), + uid6: key.as_ref().map(|k| k.0.clone()).unwrap_or_default().into(), + level: i32::from(key.as_ref().map_or(e.level, |k| k.1)), + default: Some(e.id) == default, + origin: origin_label(e.origin).into(), + improving: improving.map_or(0, |i| i32::from(i.0)), + reached: improving.map_or(0, |i| i32::from(i.1)), + used_by: used.join(", ").into(), + } + }) + .collect() +} + +/// The names the bookmarks' identity pickers offer: the default first, then +/// every identity. +pub fn identity_names(entries: &[IdentityEntry]) -> Vec { + let mut names = vec!["Default identity".to_owned()]; + names.extend(entries.iter().map(|e| e.name.clone())); + names +} + +/// The bookmarks and the identity each connects with (an index into +/// [`identity_names`]). +pub fn bookmark_identities( + bookmarks: &[Bookmark], + entries: &[IdentityEntry], +) -> Vec { + bookmarks + .iter() + .map(|b| BookmarkIdentity { + id: b.id as i32, + name: b.name.clone().into(), + identity: b + .identity + .and_then(|id| entries.iter().position(|e| e.id == id)) + .map_or(0, |i| i as i32 + 1), + }) + .collect() +} + +/// An identity another client's files had, for the import list. +pub struct Discovered { + /// The nickname the other client kept with it. + pub nickname: String, + /// Its unique id on TeamSpeak 3 servers (how the store keys it). + pub uid: String, + /// Its level. + pub level: u8, + /// The file it came from. + pub source: String, + /// Picked for import. + pub picked: bool, +} + +/// What an import found, one row each; `known`: the unique ids of the +/// identities we have. +pub fn found_items(found: &[Discovered], known: &HashSet<&str>) -> Vec { + found + .iter() + .map(|f| FoundIdentity { + name: f.nickname.clone().into(), + known: known.contains(f.uid.as_str()), + uid: f.uid.clone().into(), + level: i32::from(f.level), + source: f.source.clone().into(), + picked: f.picked, + }) + .collect() +} + +/// What the search of the other clients' files says. +pub fn found_status(found: usize, first_error: Option<&str>) -> String { + match (found, first_error) { + (0, Some(e)) => format!("Nothing found ({e})."), + (0, None) => "No TeamSpeak client settings found on this device.".to_owned(), + (n, _) => format!("{n} identities found."), + } +} + +/// A file name for an exported identity: letters, digits and `-` stay. +pub fn export_file_stem(name: &str) -> String { + name.chars().map(|c| if c.is_alphanumeric() || c == '-' { c } else { '_' }).collect() +} + +/// My Account: the identity the current server sees us as (`bookmark`: that +/// server's). +pub fn account_form( + bookmark: Option<&Bookmark>, + identity_name: &str, + uid: &str, + uid6: &str, + level: u8, +) -> AccountForm { + AccountForm { + nickname: bookmark.map(|b| b.nickname.clone()).unwrap_or_default().into(), + identity: identity_name.into(), + uid: uid.into(), + uid6: uid6.into(), + level: i32::from(level), + server: bookmark.map(|b| b.name.clone()).unwrap_or_default().into(), + } +} + +#[cfg(test)] +mod tests { + use voelin_core::ObserveState; + use voelin_gateway_proto::{Action, ConfigEntry, PermRuleInfo}; + + use super::*; + use crate::settings::UiSettings; + + #[test] + fn layers_round_trip() { + let base = LayerSetting::default(); + let item = LayerItem { + size: "1280x720".into(), + fps: "30".into(), + bitrate: "2500".into(), + min_bitrate: "800".into(), + max_bitrate: "".into(), + }; + let layer = layer_of(&item, &base).unwrap(); + assert_eq!( + (layer.size, layer.max_fps, layer.bitrate), + (Some((1280, 720)), Some(30), 2_500_000) + ); + assert_eq!(layer.min_bitrate, 800_000); + assert_eq!(layer_item(&layer), item); + let scaled = layer_of( + &LayerItem { size: "0.5".into(), bitrate: "900".into(), ..item.clone() }, + &base, + ) + .unwrap(); + assert_eq!((scaled.size, scaled.scale), (None, 0.5)); + assert!(layer_of(&LayerItem { size: "big".into(), ..item.clone() }, &base).is_none()); + assert!(layer_of(&LayerItem { bitrate: "0".into(), ..item }, &base).is_none()); + } + + #[test] + fn quality_presets() { + assert_eq!(quality_of(&[]), 0); + let layer = |size| LayerSetting { size: Some(size), ..LayerSetting::default() }; + assert_eq!(quality_of(&[layer((1920, 1080))]), 2); + assert_eq!(quality_of(&[layer((3840, 2160))]), 4); + assert_eq!(quality_of(&[layer((7680, 4320))]), 5); + assert_eq!(quality_of(&[layer((800, 600))]), -1); + // A preset at the bitrate, or the automatic one of its size and rate. + let one = |l: Option>| l.map(|l| (l[0].size, l[0].bitrate)); + assert_eq!(one(preset_layers(5, 60_000, 30)), Some((Some((7680, 4320)), 60_000_000))); + assert_eq!(one(preset_layers(4, 0, 60)), Some((Some((3840, 2160)), 59_719_680))); + assert_eq!(preset_layers(0, 0, 60), Some(Vec::new())); + assert_eq!(preset_layers(-1, 0, 60), None); + assert_eq!(preset_layers(6, 0, 60), None); + assert_eq!(quality_of(&[layer((1280, 720)), layer((640, 360))]), -1); + for i in 0..5 { + assert_eq!(codec_index(codec_of(i)), i); + } + } + + #[test] + fn typed_values() { + assert_eq!(group_ids("6, 7 x 9"), [6, 7, 9]); + assert_eq!(json_of("30"), serde_json::json!(30)); + assert_eq!(json_of("[1,2]"), serde_json::json!([1, 2])); + assert_eq!(json_of("hello"), serde_json::json!("hello")); + let rule = PermRule { everyone: false, server_groups: vec![6], channel_groups: vec![] }; + assert_eq!(rule_text(&rule), "server groups 6"); + assert_eq!(rule_text(&PermRule::default()), "nobody"); + } + + #[test] + fn privacy_indices() { + for i in 0..3 { + assert_eq!(allowed_index(allowed_of(i)), i); + } + assert_eq!(allowed_of(9), voelin_core::settings::Allowed::Everyone); + } + + #[test] + fn rows_say_where_an_identity_came_from() { + assert_eq!(origin_label(IdentityOrigin::Created), "Made in Voelin"); + assert_eq!(origin_label(IdentityOrigin::Imported), "Imported"); + // Made by the app, then chosen: an import never replaces it. + assert_eq!(origin_label(IdentityOrigin::User), "Chosen by you"); + } + + /// A form read from the settings and applied again changes nothing. + #[test] + fn forms_are_stable_through_the_settings() { + let prefs = Settings::in_memory(); + let cameras = vec!["a".to_owned(), "b".to_owned()]; + let video = video_form(&prefs, &cameras, false); + assert!(apply_video(&prefs, &cameras, &video).is_empty()); + assert_eq!(video_form(&prefs, &cameras, false), video); + let streaming = streaming_form(&prefs); + assert!(apply_streaming(&prefs, &streaming).is_empty()); + assert_eq!(streaming_form(&prefs), streaming); + let (notify, privacy) = (notify_form(&prefs), privacy_form(&prefs)); + assert!(apply_notify(&prefs, ¬ify).is_empty()); + assert!(apply_privacy(&prefs, &privacy).is_empty()); + assert_eq!((notify_form(&prefs), privacy_form(&prefs)), (notify, privacy)); + let advanced = advanced_form(&prefs, "logs", "crashes"); + assert!(apply_advanced(&prefs, &advanced).is_empty()); + assert_eq!(advanced_form(&prefs, "logs", "crashes"), advanced); + assert_eq!((&*advanced.logs, &*advanced.crash_dir), ("logs", "crashes")); + } + + #[test] + fn the_video_form_sets_what_it_says() { + let prefs = Settings::in_memory(); + let cameras = vec!["a".to_owned(), "b".to_owned()]; + let form = VideoForm { + camera: 1, + background: 1, + resolution: "1280x720".into(), + fps: "30".into(), + codec: 2, + mirror: true, + permissions: 3, + quality: 2, + bitrate: 8000.0, + ..video_form(&prefs, &cameras, false) + }; + assert!(apply_video(&prefs, &cameras, &form).is_empty()); + assert_eq!(prefs.get(&VIDEO_CAMERA), "b"); + assert_eq!(prefs.get(&VIDEO_BACKGROUND), "blur"); + assert_eq!(prefs.get(&STREAM_FPS), 30); + assert_eq!(prefs.get(&STREAM_CODEC), CodecChoice::Vp9); + assert_eq!(prefs.get(&STREAM_PERMISSIONS), StreamPermissions::Nobody); + // The 1080p preset at the bitrate. + let layers = prefs.get(&STREAM_LAYERS); + assert_eq!((layers[0].size, layers[0].bitrate), (Some((1920, 1080)), 8_000_000)); + assert_eq!(video_form(&prefs, &cameras, true).camera, 1); + assert!(video_form(&prefs, &cameras, true).preview); + } + + #[test] + fn typed_numbers_that_are_not_numbers_leave_the_setting_alone() { + let prefs = Settings::in_memory(); + let before = advanced_form(&prefs, "", ""); + let form = AdvancedForm { + history_page: "many".into(), + cache_mb: "-1".into(), + progress_ms: "".into(), + encoder: " ".into(), + ..before.clone() + }; + assert!(apply_advanced(&prefs, &form).is_empty()); + assert_eq!(advanced_form(&prefs, "", ""), before); + let form = AdvancedForm { history_page: " 25 ".into(), ..before }; + assert!(apply_advanced(&prefs, &form).is_empty()); + assert_eq!(&*advanced_form(&prefs, "", "").history_page, "25"); + // The Streaming page: auto, a number, or nothing at all. + let form = StreamingForm { bitrate: "Auto".into(), ..streaming_form(&prefs) }; + apply_streaming(&prefs, &form); + assert_eq!(prefs.get(&STREAM_BITRATE_KBPS), 0); + apply_streaming(&prefs, &StreamingForm { bitrate: "4500".into(), ..form.clone() }); + assert_eq!(prefs.get(&STREAM_BITRATE_KBPS), 4500); + apply_streaming(&prefs, &StreamingForm { bitrate: "fast".into(), ..form }); + assert_eq!(prefs.get(&STREAM_BITRATE_KBPS), 4500); + } + + #[test] + fn layers_are_added_edited_and_removed() { + let prefs = Settings::in_memory(); + prefs.set(&STREAM_BITRATE_KBPS, 8000).unwrap(); + assert!(add_layer(&prefs).is_empty()); + assert!(add_layer(&prefs).is_empty()); + let layers = prefs.get(&STREAM_LAYERS); + assert_eq!(layers.len(), 2); + // Each new layer half the size and a quarter of the bitrate. + assert_eq!((layers[0].scale, layers[0].bitrate), (1.0, 8_000_000)); + assert_eq!((layers[1].scale, layers[1].bitrate), (0.5, 2_000_000)); + let mut item = layer_item(&layers[1]); + item.size = "640x360".into(); + assert_eq!(apply_layer(&prefs, 1, &item), Some(Vec::new())); + assert_eq!(prefs.get(&STREAM_LAYERS)[1].size, Some((640, 360))); + // A row that is not a layer is said so; there is no row 5 or -1. + item.bitrate = "0".into(); + assert_eq!(apply_layer(&prefs, 1, &item).map(|s| s.len()), Some(1)); + assert_eq!(prefs.get(&STREAM_LAYERS)[1].size, Some((640, 360))); + assert_eq!(apply_layer(&prefs, 5, &item), None); + assert_eq!(apply_layer(&prefs, -1, &item), None); + assert!(remove_layer(&prefs, 0).is_empty()); + assert!(remove_layer(&prefs, 7).is_empty()); + assert_eq!(prefs.get(&STREAM_LAYERS).len(), 1); + assert_eq!(layer_items(&prefs).len(), 1); + } + + #[test] + fn audio_sources_are_added_changed_and_removed() { + let prefs = Settings::in_memory(); + let before = prefs.get(&STREAM_AUDIO_SOURCES).len(); + assert_eq!(add_audio_source(&prefs, "app", ""), None); + assert_eq!(add_audio_source(&prefs, "radio", "x"), None); + assert_eq!(add_audio_source(&prefs, "app", "firefox"), Some(Vec::new())); + let sources = prefs.get(&STREAM_AUDIO_SOURCES); + assert_eq!(sources.len(), before + 1); + let rows = audio_source_items(&prefs, "Voelin"); + let last = &rows[before]; + assert_eq!((&*last.kind, &*last.name, last.gain), ("app", "firefox", 100.0)); + let item = AudioSourceItem { gain: 50.0, muted: true, ..last.clone() }; + assert!(apply_audio_source(&prefs, before as i32, &item).is_empty()); + let changed = &prefs.get(&STREAM_AUDIO_SOURCES)[before]; + assert_eq!((changed.gain, changed.muted), (0.5, true)); + assert!(remove_audio_source(&prefs, before as i32).is_empty()); + assert_eq!(prefs.get(&STREAM_AUDIO_SOURCES).len(), before); + let desktop = AudioSourceSetting::new(AudioSourceKindSetting::Desktop); + assert_eq!(&*source_item(&desktop, "Voelin").name, "Desktop without Voelin"); + } + + #[test] + fn srtp_profiles_are_moved_and_offered() { + let prefs = Settings::in_memory(); + let offered = prefs.get(&STREAM_SRTP_PROFILES); + assert!(offered.len() > 1); + assert_eq!(srtp_move(&prefs, -1, 1), None); + assert_eq!(srtp_move(&prefs, 0, 1), Some(Vec::new())); + let moved = prefs.get(&STREAM_SRTP_PROFILES); + assert_eq!((&moved[0], &moved[1]), (&offered[1], &offered[0])); + // Off the end: nothing to do, but the page is filled again. + assert_eq!(srtp_move(&prefs, offered.len() as i32 - 1, 1), Some(Vec::new())); + assert_eq!(prefs.get(&STREAM_SRTP_PROFILES), moved); + let name = moved[0].clone(); + assert_eq!(srtp_toggle(&prefs, &name), Some(Vec::new())); + assert!(!prefs.get(&STREAM_SRTP_PROFILES).contains(&name)); + assert!(srtp_unused(&prefs.get(&STREAM_SRTP_PROFILES)).contains(&name.as_str())); + assert_eq!(srtp_toggle(&prefs, &name), Some(Vec::new())); + assert_eq!(prefs.get(&STREAM_SRTP_PROFILES).len(), offered.len()); + // One profile stays. + let one = prefs.get(&STREAM_SRTP_PROFILES)[0].clone(); + prefs.set(&STREAM_SRTP_PROFILES, vec![one.clone()]).unwrap(); + assert_eq!(srtp_toggle(&prefs, &one), None); + assert_eq!(prefs.get(&STREAM_SRTP_PROFILES), [one]); + } + + #[test] + fn the_settings_list_is_filtered_by_name_and_description() { + let prefs = Settings::in_memory(); + let all = setting_items(&prefs, ""); + assert!(all.len() > 10); + let some = setting_items(&prefs, "srtp"); + assert!(!some.is_empty() && some.len() < all.len()); + assert!( + some.iter().all(|s| s.key.contains("srtp") || s.doc.to_lowercase().contains("srtp")) + ); + assert!(setting_items(&prefs, "no such setting xyz").is_empty()); + prefs.set(&STREAM_FPS, 45).unwrap(); + let fps = all.iter().find(|s| &*s.key == "stream.fps").unwrap(); + assert_eq!(&*fps.source, "default"); + let fps = setting_items(&prefs, "stream.fps").into_iter().next().unwrap(); + assert_eq!((&*fps.value, &*fps.source), ("45", "set here")); + } + + fn state() -> AppState<()> { + let bookmark = |id, name: &str, gateway: Option<&str>| Bookmark { + id, + name: name.into(), + gateway_url: gateway.map(str::to_owned), + ..Bookmark::default() + }; + AppState::<()>::new( + vec![bookmark(1, "One", Some("wss://one")), bookmark(2, "Two", None)], + UiSettings::default(), + Default::default(), + Default::default(), + ) + } + + #[test] + fn gateways_are_listed_with_what_they_offer() { + let mut state = state(); + state.bookmarks.push(Bookmark { + id: 3, + name: "Three".into(), + gateway_url: Some("wss://three".into()), + ..Bookmark::default() + }); + let items = gateway_items(&state); + // A server without a gateway is not listed; one not connected is off. + assert_eq!(items.iter().map(|i| &*i.server).collect::>(), ["One", "Three"]); + assert_eq!(&*items[0].status, "off"); + let view = state.sessions.entry(1).or_default(); + view.state.observe = ObserveState::Connecting; + assert_eq!(&*gateway_items(&state)[0].status, "connecting"); + let view = state.sessions.entry(1).or_default(); + view.gateway_caps = vec![feature::ADMIN.to_owned(), "chat".to_owned()]; + let items = gateway_items(&state); + assert_eq!( + (&*items[0].status, items[0].admin, items[0].features.len()), + ("connected", true, 2) + ); + assert_eq!((&*items[1].status, items[1].admin), ("off", false)); + } + + #[test] + fn the_administered_gateway_shows_its_keys_and_rules() { + assert!(config_items(None).is_empty() && perm_items(None).is_empty()); + let extra = SessionExtra { + config: vec![ConfigEntry { + key: "history.retention_days".into(), + value: serde_json::json!(30), + source: ConfigSource::Db, + default: serde_json::json!(0), + value_type: "int".into(), + description: "Days kept".into(), + bootstrap: false, + }], + perms: vec![ + PermRuleInfo { + action: Action::React, + rule: Some(PermRule { + everyone: false, + server_groups: vec![6, 7], + channel_groups: vec![], + }), + source: ConfigSource::File, + default: "everyone".into(), + }, + PermRuleInfo { + action: Action::Pin, + rule: None, + source: ConfigSource::Default, + default: "server admins".into(), + }, + ], + ..SessionExtra::default() + }; + let config = config_items(Some(&extra)); + assert_eq!( + (&*config[0].key, &*config[0].value, &*config[0].source, &*config[0].kind), + ("history.retention_days", "30", "set at runtime", "int") + ); + let perms = perm_items(Some(&extra)); + assert_eq!((&*perms[0].rule, &*perms[0].server_groups), ("server groups 6, 7", "6, 7")); + assert_eq!((&*perms[1].rule, &*perms[1].source), ("Default: server admins", "default")); + } + + #[test] + fn encoders_say_why_they_are_used_or_not() { + use voelin_core::media::voelin_media::Codec; + let info = |status: Result<(), String>, rank| EncoderInfo { + name: "enc".into(), + api: "VA-API".into(), + codec: Codec::H264, + hardware: true, + status, + rank, + }; + let items = encoder_items(&[ + info(Ok(()), Some(0)), + info(Ok(()), Some(1)), + info(Ok(()), None), + info(Err("no device".into()), None), + ]); + let status: Vec<&str> = items.iter().map(|i| &*i.status).collect(); + assert_eq!( + status, + ["VA-API · used first", "VA-API · choice 2", "VA-API · not used", "no device"] + ); + assert_eq!((&*items[0].codec, items[0].ok, items[3].ok), ("H264", true, false)); + assert_eq!(ffmpeg_status(&Ok("7.1".into())), "FFmpeg: 7.1"); + assert_eq!(ffmpeg_status(&Err("missing".into())), "FFmpeg is not used: missing"); + assert!(zero_copy_status(&Ok(())).starts_with("Screen capture goes")); + assert_eq!(zero_copy_status(&Err("x".into())), "No zero-copy capture: x"); + let listed = capture_source_names(Ok(vec![ + ("A".into(), String::new()), + ("B".into(), "1080p".into()), + ])); + assert_eq!(listed, ["A", "B · 1080p"]); + assert_eq!(capture_source_names(Err("none".into())), ["none"]); + } + + #[test] + fn identities_say_who_uses_them_and_what_is_being_raised() { + let entry = |id, name: &str, level, origin| IdentityEntry { + id, + name: name.into(), + uid: format!("uid{id}"), + level, + origin, + is_default: false, + }; + let entries = [ + entry(1, "Main", 8, IdentityOrigin::Created), + entry(2, "Alt", 20, IdentityOrigin::Imported), + ]; + let facts = [ + IdentityFacts { entry: &entries[0], key: Some(("six1".into(), 10)) }, + IdentityFacts { entry: &entries[1], key: None }, + ]; + let used = [("Home", Some(1)), ("Work", Some(2)), ("Club", Some(1)), ("Lost", None)]; + let items = identity_items(&facts, Some(1), &used, |id| (id == 2).then_some((30, 22))); + assert_eq!( + (&*items[0].used_by, items[0].default, &*items[0].uid6, items[0].level), + ("Home, Club", true, "six1", 10) + ); + assert_eq!( + (&*items[1].used_by, items[1].default, &*items[1].uid6, items[1].level), + ("Work", false, "", 20) + ); + assert_eq!((items[0].improving, items[1].improving, items[1].reached), (0, 30, 22)); + assert_eq!(&*items[1].origin, "Imported"); + assert_eq!(identity_names(&entries), ["Default identity", "Main", "Alt"]); + let bookmark = + |id, identity| Bookmark { id, name: format!("b{id}"), identity, ..Bookmark::default() }; + let picks = bookmark_identities( + &[bookmark(1, None), bookmark(2, Some(2)), bookmark(3, Some(9))], + &entries, + ); + assert_eq!(picks.iter().map(|p| p.identity).collect::>(), [0, 2, 0]); + let found = [ + Discovered { + nickname: "Old".into(), + uid: "uid2".into(), + level: 5, + source: "/x".into(), + picked: true, + }, + Discovered { + nickname: "New".into(), + uid: "uid9".into(), + level: 6, + source: "/y".into(), + picked: false, + }, + ]; + let known: HashSet<&str> = entries.iter().map(|e| e.uid.as_str()).collect(); + let rows = found_items(&found, &known); + assert_eq!( + rows.iter().map(|r| (r.known, r.picked)).collect::>(), + [(true, true), (false, false)] + ); + assert_eq!(found_status(0, Some("denied")), "Nothing found (denied)."); + assert_eq!(found_status(0, None), "No TeamSpeak client settings found on this device."); + assert_eq!(found_status(2, Some("ignored")), "2 identities found."); + assert_eq!(export_file_stem("My ID: 1/2-b"), "My_ID__1_2-b"); + let account = account_form(Some(&bookmark(1, None)), "Main", "u3", "u6", 12); + assert_eq!((&*account.server, &*account.identity, account.level), ("b1", "Main", 12)); + } +} diff --git a/crates/voelin-ui-vm/src/settings_pages/mod.rs b/crates/voelin-ui-vm/src/settings_pages/mod.rs new file mode 100644 index 0000000..d25a51f --- /dev/null +++ b/crates/voelin-ui-vm/src/settings_pages/mod.rs @@ -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; diff --git a/crates/voelin-ui/src/vm/social.rs b/crates/voelin-ui-vm/src/social.rs similarity index 93% rename from crates/voelin-ui/src/vm/social.rs rename to crates/voelin-ui-vm/src/social.rs index 9bb6f91..8321390 100644 --- a/crates/voelin-ui/src/vm/social.rs +++ b/crates/voelin-ui-vm/src/social.rs @@ -4,6 +4,23 @@ //! 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, + /// The server's unique id. + pub server_uid: Option, + /// Which chat of the server. + pub target: ChatTarget, + /// Its newest message. + pub last: Option, + /// Messages not read. + pub unread: i32, +} fn local(ts_ms: i64) -> Option { DateTime::from_timestamp_millis(ts_ms).map(|t| t.with_timezone(&Local).naive_local()) @@ -18,6 +35,7 @@ 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(); @@ -39,6 +57,7 @@ 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(); @@ -53,7 +72,7 @@ pub fn list_time_at(then: NaiveDateTime, now: NaiveDateTime) -> String { /// Chat text without BBCode (`[b]`, `[URL=…]`, `[/URL]`), on one line. pub fn plain(text: &str) -> String { - without_emoji(&crate::vm::bbcode::parse(text).one_line()) + without_emoji(&crate::bbcode::parse(text).one_line()) } /// Text without emoji, runs of spaces as one: one line of text draws no @@ -76,7 +95,7 @@ fn is_emoji(c: char) -> bool { 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::vm::chat::is_picture(&f.name)) { + if files.iter().any(|f| crate::chat::is_picture(&f.name)) { "Sent a picture".to_owned() } else { "Sent a file".to_owned() @@ -116,7 +135,7 @@ pub fn poke_message(text: &str) -> String { /// 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: &[crate::messages::ChatRef], n: usize) -> Vec { +pub fn sidebar_dms(chats: &[ChatRef], n: usize) -> Vec { let mut private: Vec = (0..chats.len()) .filter(|&i| matches!(chats[i].target, voelin_model::ChatTarget::Private(_))) .collect(); @@ -133,7 +152,7 @@ pub fn found_channels<'a>( ) -> Vec<(u64, &'a str)> { channels .into_iter() - .filter_map(|c| Some((c.id, crate::vm::tree::listed_title(c)?))) + .filter_map(|c| Some((c.id, crate::tree::listed_title(c)?))) .filter(|(_, title)| matches(query, &[*title])) .collect() } @@ -287,7 +306,7 @@ mod tests { #[test] fn sidebar_chats() { use voelin_model::ChatTarget; - let chat = |target: ChatTarget, unread| crate::messages::ChatRef { + let chat = |target: ChatTarget, unread| ChatRef { session: Some(1), server_uid: None, target, diff --git a/crates/voelin-ui-vm/src/state.rs b/crates/voelin-ui-vm/src/state.rs new file mode 100644 index 0000000..bdc81f2 --- /dev/null +++ b/crates/voelin-ui-vm/src/state.rs @@ -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, + /// The gateway's events by start time. + pub events: Vec, + /// The events were asked for and arrived. + pub events_loaded: bool, + /// The events whose answers are shown (by event id). + pub expanded: HashSet, + /// The activity feed, newest first. + pub activity: Vec, + /// Our unique id at the gateway. + pub gateway_uid: Option, + /// What we may do at the gateway. + pub actions: Vec, + /// Gateway administration: its keys. + pub config: Vec, + /// Gateway administration: its permission rules. + pub perms: Vec, + /// Offline messages (voice). + pub inbox: Vec, + /// The offline messages were asked for. + pub inbox_asked: bool, + /// Pictures linked in chat, by link. + pub previews: HashMap, + /// 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 { + /// 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, + /// Live messages of a session that keeps no history (no server unique + /// id yet): grouped from the message before, without ids. + pub last: Option, + /// 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, + /// 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, + /// The pins were asked for and arrived. + pub pins_loaded: bool, + /// The gateway topics of this chat. + pub topics: Vec, + /// The topics were asked for and arrived. + pub topics_loaded: bool, + /// The open topic. + pub topic: Option, + /// The messages of the open topic. + pub topic_messages: Vec, + /// The message jumped to from the pins. + pub marked: Option, + /// What the lines of `messages` were built from. + pub cache: LineCache, +} + +impl Tab { + /// 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 Tab { + /// 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) { + 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 { + /// Where the connections stand. + pub state: SessionState, + /// What the server offers. + pub capabilities: Capabilities, + /// The server's channels and clients. + pub presence: Arc, + /// The channels folded in the tree. + pub collapsed: HashSet, + /// The clients talking now. + pub talking: HashSet, + /// The chats, the server's first. + pub tabs: Vec>, + /// 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, + /// Clients whose stored volume was sent for this voice connection. + pub applied_playback: HashSet, + /// Avatar pictures in the engine's cache, by unique id + /// ([`Event::AvatarReady`]). + pub avatars: HashMap, + /// Icons in the engine's cache, by icon id ([`Event::IconReady`]). + pub icons: HashMap, + /// Banners and badges in the engine's cache, by address + /// ([`Event::PictureReady`]). + pub pictures: HashMap, + /// The server's icon id as its voice connection last told it + /// ([`Event::ServerDetails`]); kept while disconnected, for the rail. + pub server_icon: u32, + /// Bookmark address that supplied this session's icon. + pub icon_address: Option, + /// The server groups in display order ([`Event::Groups`]). + pub server_groups: Vec, + /// The channel groups ([`Event::Groups`]). + pub channel_groups: Vec, + /// What the session's gateway offers (`voelin_gateway_proto::feature`). + pub gateway_caps: Vec, + /// The client whose member card is open. + pub member_card: Option, + /// Passwords given for locked channels, until voice disconnects. + pub channel_passwords: HashMap, + /// The channel a voice connection was asked into, until it is joined + /// or joined again (`App::join_after_connect`). + pub join_after_connect: Option, + /// Viewers of the streams in the gateway's directory, by stream id. + pub stream_viewers: HashMap, + /// Downloads started from chat, by transfer id. + pub downloads: HashMap, + /// 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, + /// The server unique id `reads` are for. + pub reads_of: Option, +} + +impl Default for SessionView { + 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 SessionView { + /// 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 { + 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 { + 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 SessionView { + /// A new tab for `target`, read as far as the store says. + pub fn new_tab(&self, target: ChatTarget, title: String) -> Tab { + 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 { + /// The saved servers, in the rail's order. + pub bookmarks: Vec, + /// The server shown (a bookmark id). + pub current: Option, + /// What is known of each server's session, by bookmark id. + pub sessions: HashMap>, + /// 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, + /// 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, + /// The client in the volume dialog: session, client id, unique id. + pub playback_dialog: Option<(i64, u16, Option)>, + /// 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, + /// 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, +} + +impl AppState { + /// 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, + 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)); + } +} diff --git a/crates/voelin-ui/src/vm/streams.rs b/crates/voelin-ui-vm/src/streams.rs similarity index 90% rename from crates/voelin-ui/src/vm/streams.rs rename to crates/voelin-ui-vm/src/streams.rs index f922a4b..af50de7 100644 --- a/crates/voelin-ui/src/vm/streams.rs +++ b/crates/voelin-ui-vm/src/streams.rs @@ -5,8 +5,8 @@ use std::path::PathBuf; use voelin_core::stream::StreamKind; -use crate::app::StreamItem; -use crate::vm::avatar; +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 { @@ -40,6 +40,7 @@ pub fn streamer(name: &str, picture: Option<&PathBuf>) -> StreamItem { #[cfg(test)] mod tests { use super::*; + use crate::Size; #[test] fn kinds_have_labels() { @@ -60,10 +61,10 @@ mod tests { #[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.streamer, "Nova Star"); + assert_eq!(&*item.initials, "NS"); assert_eq!(item.tint, avatar::tint("Nova Star")); - assert_eq!(item.avatar.size(), slint::Image::default().size()); + assert_eq!(item.avatar.size(), Size::default()); assert!(item.id.is_empty() && !item.own && !item.studio); } } diff --git a/crates/voelin-ui-vm/src/studio/logic.rs b/crates/voelin-ui-vm/src/studio/logic.rs new file mode 100644 index 0000000..f43f81b --- /dev/null +++ b/crates/voelin-ui-vm/src/studio/logic.rs @@ -0,0 +1,1944 @@ +//! What the Stream Studio does and when, apart from the toolkit and the +//! engine's runtime: the stream settings panel's fields, where the stream +//! goes, what the header and the bottom bar say, which overlays the switches +//! ask for, what the layer, source, picker and mixer controls change. +//! +//! [`StudioData`] is the studio's state; the functions work on it, on the +//! settings service, the scene graph (`voelin_core::studio::scene`) and the +//! app's state ([`AppState`]), and return rows ([`crate::studio_bridge`]), +//! commands for the studio or messages for the status line. Running the +//! studio (its tasks, the preview, the windows, the encoder) is the front +//! end's: `voelin-ui`'s `studio/bind.rs`. + +use std::path::Path; +use std::sync::Arc; + +use serde::{Deserialize, Serialize}; +use voelin_core::HistoryMessage; +use voelin_core::media::voelin_media::capture::{CaptureSource, SourceId}; +use voelin_core::media::{ + AudioApp, AudioSourceSpec, AudioSourceStats, StreamerStats, auto_bitrate, +}; +use voelin_core::settings::{ + AudioSourceKindSetting, AudioSourceSetting, Key, Kind, STREAM_AUDIO_SOURCES, + STREAM_BITRATE_KBPS, STREAM_LAYERS, STUDIO_RECORDING_DIR, STUDIO_REPLAY_MEMORY_MB, + STUDIO_REPLAY_SECONDS, STUDIO_SCENES, Settings, layer_specs, +}; +use voelin_core::stream::{ + EndReason, LayerSpec, StreamInfo, StreamKind, StreamSetup, ViewerInfo, ViewerState, +}; +use voelin_core::studio::scene::{ + Align, Background, Colour, Crop, Fit, Scene, Scenes, Source, SourceKind, Transform, +}; +use voelin_core::studio::{self, SourceChange, Stats, Status, camera}; +use voelin_model::{ChatMessage, ChatTarget, ClientId}; +use voelin_store::MessageSource; + +use super::{ + AudioLive, OVERLAY_CHAT, OVERLAY_NOW_PLAYING, OVERLAY_VIEWERS, Overlay, audio_label, clock, + format_line, next_layer, parse_layer, placement, quality, thousands, +}; +use crate::bridge::ChatLine; +use crate::image::ImageSource; +use crate::settings::parse_positive; +use crate::state::AppState; +use crate::studio_bridge::{ + StudioForm, StudioLayer, StudioPick, StudioSettingsForm, StudioSourceForm, StudioStatus, + StudioViewer, +}; + +/// The stream settings panel and the studio's own choices. +pub static STUDIO_UI: Key = Key::new( + "studio.ui", + Kind::Json, + "Stream Studio: title, game, go-live message, overlays, stream audio, preview size.", + StudioUi::default, +); + +/// The stream settings panel's fields (`studio.ui`). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct StudioUi { + /// The stream's title. + pub title: String, + /// Game or category: goes into the stream's name after the title. + pub game: String, + /// Sent to the channel's chat when the stream goes live. + pub message: String, + /// Overlay sources kept in the live scene ([`super::apply_overlays`]). + pub show_viewers: bool, + /// The stream chat's last lines as an overlay. + pub show_chat: bool, + /// The title and the game as an overlay. + pub show_now_playing: bool, + /// The stream's audio (the mixer's sources); off: none. + pub audio: bool, + /// The preview's width in pixels (its height follows the output) and + /// frame rate. + pub preview_width: u32, + /// The preview's frame rate. + pub preview_fps: u32, +} + +impl Default for StudioUi { + fn default() -> Self { + Self { + title: String::new(), + game: String::new(), + message: String::new(), + show_viewers: false, + show_chat: false, + show_now_playing: false, + audio: true, + preview_width: 960, + preview_fps: 15, + } + } +} + +/// The overlay text of what is on: the title and the game. +pub fn now_playing(ui: &StudioUi) -> Option { + let lines: Vec<&str> = + [ui.title.trim(), ui.game.trim()].into_iter().filter(|s| !s.is_empty()).collect(); + (!lines.is_empty()).then(|| lines.join("\n")) +} + +/// The stream's name: the title, and the game after it. TeamSpeak streams +/// have a name only, and the gateway's directory takes it from there. +pub fn stream_name(ui: &StudioUi) -> String { + match (ui.title.trim(), ui.game.trim()) { + (title, "") => title.to_owned(), + ("", game) => game.to_owned(), + (title, game) => format!("{title} — {game}"), + } +} + +/// A file name for a recording or a clip, stamped with the time. +pub fn file_name(what: &str) -> String { + format!("{what} {}.mkv", chrono::Local::now().format("%Y-%m-%d %H-%M-%S")) +} + +/// What a picker row adds. +pub enum Pick { + /// A source for the live scene. + Source { + /// Its name. + name: String, + /// What it shows. + kind: SourceKind, + }, + /// An audio source for the mixer. + Audio(AudioSourceSetting), +} + +/// The rows of a picker, each with what picking it adds. +pub type Picks = Vec<(Pick, StudioPick)>; + +/// Our stream from the studio. +pub struct Outgoing { + /// The session it goes to. + pub session: i64, + /// The server has it up. + pub live: bool, + /// Who watches or asked to. + pub viewers: Vec, +} + +/// What the studio knows apart from its running parts (the front end's). +#[derive(Default)] +pub struct StudioData { + /// Why it does not run or cannot stream. + pub error: String, + /// Where it keeps its keys: the app's settings, or with VOELIN_DEMO_UI + /// its own in memory (nothing stored). + pub settings: Option, + /// The scene graph as the studio last said. + pub scenes: Arc, + /// Live, recording, the output. + pub status: Status, + /// The statistics of the second. + pub stats: Option>, + /// What the stream's encoder does. + pub encoder: Option, + /// The stream settings panel. + pub ui: StudioUi, + /// The session the stream (and its chat) goes to. + pub destination: Option, + /// Our stream, once started. + pub stream: Option, + /// What the picker's rows add. + pub picks: Vec, + /// The overlays last asked for. + pub overlays: Vec, + /// Stats ticks it was not shown; it stops after a few. + pub hidden: u32, + /// Development switches waiting for the studio. + pub dev: Vec, +} + +/// What the header and the bottom bar say depends on, besides +/// [`StudioData`]: the front end's side of the picture. +pub struct StatusContext<'a> { + /// The studio runs. + pub running: bool, + /// Its encoder started. + pub has_encoder: bool, + /// The studio is in a window of its own. + pub detached: bool, + /// A quick share goes to the destination. + pub sharing: bool, + /// The destination's name ([`destination_name`]). + pub destination: Option, + /// The name of a viewer. + pub viewer_name: &'a dyn Fn(&ViewerInfo) -> String, +} + +impl StudioData { + /// `stream.bitrate_kbps`, an automatic one (0) as it comes to for the + /// output's size and frame rate. + pub fn bitrate_kbps(&self, settings: &Settings) -> u32 { + match settings.get(&STREAM_BITRATE_KBPS) { + 0 => { + let (width, height) = self.scenes.size(); + let bitrate = auto_bitrate(width, height, self.scenes.fps()); + u32::try_from(bitrate / 1000).unwrap_or(u32::MAX) + } + kbps => kbps, + } + } + + /// The stream's layers for the engine: `stream.layers`, or the single + /// layer at [`bitrate_kbps`](Self::bitrate_kbps). + pub fn session_layers(&self, settings: &Settings) -> Vec { + match layer_specs(&settings.get(&STREAM_LAYERS)) { + layers if layers.is_empty() => { + vec![LayerSpec::single(u64::from(self.bitrate_kbps(settings)) * 1000)] + } + layers => layers, + } + } + + /// The bitrate the stream is announced with: the top layer's, else + /// [`bitrate_kbps`](Self::bitrate_kbps). + pub fn go_live_bitrate(&self, settings: &Settings) -> u32 { + match settings.get(&STREAM_LAYERS).iter().map(|l| l.bitrate).max() { + Some(bps) => u32::try_from(bps / 1000).unwrap_or(u32::MAX), + None => self.bitrate_kbps(settings), + } + } + + /// How the stream starts. + pub fn stream_setup(&self, settings: &Settings) -> StreamSetup { + StreamSetup { + name: stream_name(&self.ui), + bitrate: self.go_live_bitrate(settings), + audio: self.ui.audio, + ..StreamSetup::default() + } + } + + /// Whether `session` is where the studio streams to. + pub fn streams_to(&self, session: i64) -> bool { + self.stream.as_ref().is_some_and(|s| s.session == session) + } + + /// A source of the live scene. + pub fn live_source(&self, id: u64) -> Option<&Source> { + self.scenes.active()?.source(id) + } + + /// The live scene. + pub fn live_scene(&self) -> Option { + self.scenes.active().map(|s| s.id) + } + + /// Streaming or recording: the studio runs although it is not shown. + pub fn busy(&self) -> bool { + self.stream.is_some() || self.status.recording.is_some() + } + + /// Viewers connected now. + pub fn watching(&self) -> usize { + self.stream + .as_ref() + .map_or(0, |s| s.viewers.iter().filter(|v| v.state == ViewerState::Connected).count()) + } + + /// Once a second: whether the studio keeps running (it does while it is + /// shown or busy, and for a few ticks after). + pub fn keep_running(&mut self, shown: bool) -> bool { + if shown || self.busy() { + self.hidden = 0; + true + } else { + self.hidden += 1; + self.hidden < 3 + } + } + + /// The size and rate of the preview: its width, the output's shape. + pub fn preview_command(&self) -> studio::Command { + let (w, h) = self.scenes.size(); + let width = self.ui.preview_width.max(16); + let height = ((u64::from(width) * u64::from(h) / u64::from(w.max(1))) as u32).max(2) & !1; + let fps = self.ui.preview_fps.max(1); + studio::Command::SetPreview { width, height, fps } + } + + /// New scenes came from the studio: whether the live scene changed and + /// whether the output's size did. + pub fn set_scenes(&mut self, scenes: Arc) -> (bool, bool) { + let switched = self.scenes.active().map(|s| s.id) != scenes.active().map(|s| s.id); + let resized = self.scenes.size() != scenes.size(); + self.scenes = scenes; + (switched, resized) + } + + /// Keep the destination while it works (and while live), else the + /// stream's, else the first one. + pub fn choose_destination(&mut self, list: &[(i64, String)]) { + let keep = self.stream.as_ref().map(|s| s.session).or(self.destination); + self.destination = keep.filter(|id| list.iter().any(|(d, _)| d == id)).or_else(|| { + self.stream.as_ref().map(|s| s.session).or(list.first().map(|(id, _)| *id)) + }); + } + + /// The stream settings panel's form. `destinations`: [`destinations`]. + pub fn form(&self, destinations: &[(i64, String)]) -> StudioForm { + let ui = &self.ui; + let destination = self + .destination + .and_then(|id| destinations.iter().position(|(d, _)| *d == id)) + .map_or(-1, |i| i as i32); + // Automatic (0): the field stays empty and says so. + let bitrate = self.settings.as_ref().map_or(0, |s| s.get(&STREAM_BITRATE_KBPS)); + let bitrate = if bitrate == 0 { String::new() } else { bitrate.to_string() }; + StudioForm { + destination, + title: ui.title.clone().into(), + game: ui.game.clone().into(), + message: ui.message.clone().into(), + show_viewers: ui.show_viewers, + show_chat: ui.show_chat, + show_now_playing: ui.show_now_playing, + audio: ui.audio, + bitrate: bitrate.into(), + } + } + + /// The header, the preview's badges and the bottom bar, and the viewers + /// that asked to watch. + pub fn status_view(&self, cx: &StatusContext<'_>) -> (StudioStatus, Vec) { + let live = self.stream.as_ref().is_some_and(|s| s.live); + let starting = self.stream.as_ref().is_some_and(|s| !s.live); + let encoder = self.encoder.as_ref(); + let (w, h) = self.scenes.size(); + let fps = self.scenes.fps(); + let settings = self.settings.as_ref(); + // What is sent: measured, else as set. + let measured: f64 = encoder.map_or(0.0, |e| e.layers.iter().map(|l| l.kbps).sum()); + let layers = settings.map(|s| s.get(&STREAM_LAYERS)).unwrap_or_default(); + let configured_bps: u64 = if layers.is_empty() { + settings.map_or(0, |s| u64::from(self.bitrate_kbps(s)) * 1000) + } else { + layers.iter().map(|l| l.bitrate).max().unwrap_or(0) + }; + let kbps = if measured > 0.0 { measured.round() as u64 } else { configured_bps / 1000 }; + // The viewers' bandwidth against the top layer's bitrate. + let bandwidth = self + .stream + .as_ref() + .and_then(|s| { + s.viewers + .iter() + .filter(|v| v.state == ViewerState::Connected) + .filter_map(|v| v.estimate) + .min() + }) + .filter(|_| configured_bps > 0) + .map(|e| e as f64 / configured_bps as f64); + let composed = self.stats.as_ref().map_or(f64::from(fps), |s| s.fps); + let (quality, quality_text) = quality(live, fps, composed, bandwidth); + let viewers = self.stream.as_ref().map_or(&[][..], |s| &s.viewers[..]); + let watching = viewers.iter().filter(|v| v.state == ViewerState::Connected).count(); + let hint = if !self.error.is_empty() { + self.error.clone() + } else if !cx.running || !cx.has_encoder { + "Starting the studio…".to_owned() + } else if cx.destination.is_none() { + "Join a voice channel on a TeamSpeak 6 server to go live.".to_owned() + } else if cx.sharing { + "Stop sharing your screen first.".to_owned() + } else if starting { + "Waiting for the server…".to_owned() + } else { + String::new() + }; + let replay = self.stats.as_ref().map(|s| &s.replay); + let replay_seconds = settings.map_or(0, |s| s.get(&STUDIO_REPLAY_SECONDS)); + let mut details = vec![format!( + "Composite {w}×{h}: {composed:.1} of {fps} fps, {:.1} ms a frame", + self.stats.as_ref().map_or(0.0, |s| s.compose.compose_time.as_secs_f64() * 1000.0) + )]; + if let Some(e) = encoder { + let codec = e.codec.map(|c| c.to_string()).unwrap_or_default(); + let backend = e.layers.first().and_then(|l| l.backend).map(|b| format!(" ({b})")); + details.push(format!( + "Encoder {codec}{}: {} layer(s), {} kbit/s", + backend.unwrap_or_default(), + e.layers.len(), + thousands(kbps) + )); + } + if let Some(r) = replay.filter(|_| replay_seconds > 0) { + details.push(format!( + "Replay buffer: {} s held, {:.1} MB", + r.duration.as_secs(), + (r.memory_bytes + r.spilled_bytes) as f64 / 1e6 + )); + } + let scene = self.scenes.active(); + let shows = |f: fn(&SourceKind) -> bool| { + scene.is_some_and(|s| s.sources.iter().any(|src| src.visible && f(&src.kind))) + }; + let status = StudioStatus { + running: cx.running, + destination: cx.destination.clone().unwrap_or_default().into(), + quality, + quality_text: quality_text.into(), + format: format_line(h, fps, kbps).into(), + details: details.join("\n").into(), + live, + starting, + elapsed: clock(self.status.live_for).into(), + viewers: watching as i32, + participants: viewers.len() as i32, + can_go_live: hint.is_empty() && !live && !starting, + hint: hint.into(), + recording: self.status.recording.is_some(), + recorded: clock(self.status.recorded_for).into(), + replay_seconds: replay_seconds as i32, + replay_held: replay + .map_or(String::new(), |r| format!("{} s", r.duration.as_secs())) + .into(), + output_width: w as i32, + output_height: h as i32, + fps: fps as i32, + detached: cx.detached, + can_detach: cfg!(not(target_os = "android")), + screen_shown: shows(|k| { + matches!( + k, + SourceKind::Screen { .. } + | SourceKind::Portal { .. } + | SourceKind::Pattern { .. } + ) + }), + camera_shown: shows(|k| matches!(k, SourceKind::Camera { .. })), + window_shown: shows(|k| matches!(k, SourceKind::Window { .. })), + }; + let requests: Vec = viewers + .iter() + .filter(|v| v.state == ViewerState::Requested) + .map(|v| StudioViewer { + client: i32::from(v.client), + name: (cx.viewer_name)(v).into(), + state: "requested".into(), + }) + .collect(); + (status, requests) + } + + /// The overlays the switches ask for; `chat` is called for the chat + /// overlay when it is on (see [`chat_tail`]). + pub fn wanted_overlays(&self, chat: impl FnOnce() -> Option) -> Vec { + let ui = &self.ui; + let chat = ui.show_chat.then(chat).flatten(); + vec![ + Overlay { + name: OVERLAY_VIEWERS, + text: ui.show_viewers.then(|| format!("{} watching", self.watching())), + }, + Overlay { name: OVERLAY_CHAT, text: chat }, + Overlay { + name: OVERLAY_NOW_PLAYING, + text: ui.show_now_playing.then(|| now_playing(ui)).flatten(), + }, + ] + } + + /// Remember the overlays asked for: the ones to send to the studio + /// (`force`: also when nothing changed, e.g. after a scene switch). + pub fn overlay_change(&mut self, force: bool, wanted: Vec) -> Option> { + (force || wanted != self.overlays).then(|| { + self.overlays.clone_from(&wanted); + wanted + }) + } +} + +/// The mixer's id of each audio source of the settings, if the mixer has +/// it (its meter is read from there). +pub fn meter_ids(sources: &[AudioSourceSetting], stats: &[AudioSourceStats]) -> Vec> { + sources + .iter() + .map(|setting| { + let kind = AudioSourceSpec::from(setting).kind; + stats.iter().find(|s| s.spec.kind == kind).map(|s| s.id) + }) + .collect() +} + +/// The last lines of the stream's chat, for the chat overlay. +pub fn chat_tail(chat: &[ChatLine], lines: usize) -> Option { + let count = chat.len(); + let text: Vec = chat[count.saturating_sub(lines)..] + .iter() + .map(|l| { + let line = format!("{}: {}", l.author, l.text); + match line.char_indices().nth(64) { + Some((at, _)) => format!("{}…", &line[..at]), + None => line, + } + }) + .collect(); + (!text.is_empty()).then(|| text.join("\n")) +} + +/// The mixer rows' live parts: the level (from the mixer's meters, +/// `levels`: dBFS peaks by row) and why a source captures nothing. +pub fn audio_live( + sources: &[AudioSourceSetting], + stats: &[AudioSourceStats], + levels: &[Option], +) -> Vec> { + sources + .iter() + .enumerate() + .map(|(i, setting)| { + let kind = AudioSourceSpec::from(setting).kind; + let error = stats.iter().find(|s| s.spec.kind == kind).and_then(|s| s.error.clone()); + let level = levels.get(i).copied().flatten()?; + Some(AudioLive { level: level.max(-100.0), error }) + }) + .collect() +} + +/// A source for the live scene (a new scene if there is none). +pub fn add_to_live_scene(scenes: &mut Scenes, mut source: Source) { + if scenes.active().is_none() { + let id = scenes.next_scene_id(); + scenes.scenes.push(Scene::new(id, "Scene 1")); + scenes.active = id; + } + if let Some(scene) = scenes.active_mut() { + source.id = scene.next_source_id(); + scene.sources.push(source); + } +} + +/// What the studio's event says in the status line, if it says anything. +pub fn event_message(event: &studio::Event) -> Option { + match event { + studio::Event::RecordingStarted { path } => { + Some(format!("Recording to {}", path.display())) + } + studio::Event::RecordingStopped { path, duration, bytes } => Some(format!( + "Saved a recording of {} ({:.1} MB) to {}", + clock(*duration), + *bytes as f64 / 1e6, + path.display() + )), + studio::Event::ClipSaved { path, duration } => { + Some(format!("Saved a clip of {} seconds to {}", duration.as_secs(), path.display())) + } + studio::Event::Error { context, message } => { + Some(format!("Stream Studio ({context}): {message}")) + } + _ => None, + } +} + +/// What the status line says when the stream ended. +pub fn ended_message(reason: Option<&EndReason>) -> String { + match reason { + Some(EndReason::Failed(e)) => format!("The stream failed: {e}"), + _ => "The stream has ended".into(), + } +} + +// Where the stream goes. + +/// Sessions the stream can go to: TeamSpeak 6 with voice, the current one +/// first; each with its name ([`destination_name`]). +pub fn destinations(state: &AppState) -> Vec<(i64, String)> { + let mut ids: Vec = state + .sessions + .iter() + .filter(|(_, v)| v.streams_available() && v.state.own_channel.is_some()) + .map(|(id, _)| *id) + .collect(); + ids.sort_by_key(|id| (Some(*id) != state.current, *id)); + ids.into_iter().map(|id| (id, destination_name(state, id))).collect() +} + +/// The channel and the server of a destination. +pub fn destination_parts(state: &AppState, id: i64) -> (String, String) { + let Some(view) = state.sessions.get(&id) else { return Default::default() }; + let channel = view + .state + .own_channel + .and_then(|c| view.presence.channels.get(&c)) + .map(|c| crate::tree::channel_title(c).0.to_owned()) + .unwrap_or_default(); + let server = if view.presence.server_name.is_empty() { + state.bookmarks.iter().find(|b| b.id == id).map(|b| b.name.clone()).unwrap_or_default() + } else { + view.presence.server_name.clone() + }; + (channel, server) +} + +/// "Chill Zone • Nightfall Guild". +pub fn destination_name(state: &AppState, id: i64) -> String { + let (channel, server) = destination_parts(state, id); + format!("{channel} • {server}") +} + +/// The destination list as the picker shows it. +pub fn destination_rows(state: &AppState, list: &[(i64, String)]) -> Vec { + list.iter() + .map(|(id, _)| { + let (channel, server) = destination_parts(state, *id); + StudioPick { + name: channel.into(), + detail: server.into(), + kind: "server".into(), + ..Default::default() + } + }) + .collect() +} + +/// The session and channel the stream (and its chat) goes to. +pub fn chat_target(state: &AppState, destination: Option) -> Option<(i64, u64)> { + let id = destination?; + Some((id, state.sessions.get(&id)?.state.own_channel?)) +} + +/// The destination channel's chat tab, made if need be: the channel's name +/// and whether the tab is new (its chat is to be opened). +pub fn chat_tab(state: &mut AppState, id: i64, channel: u64) -> (String, bool) { + let target = ChatTarget::Channel(channel); + let view = state.sessions.entry(id).or_default(); + let name = view + .presence + .channels + .get(&channel) + .map(|c| crate::tree::channel_title(c).0.to_owned()) + .unwrap_or_default(); + let new = !view.tabs.iter().any(|t| t.target == target); + if new { + let tab = view.new_tab(target, name.clone()); + view.tabs.push(tab); + } + (name, new) +} + +/// The name of a viewer of the stream in `session`. +pub fn viewer_name(state: &AppState, session: Option, client: ClientId) -> String { + session + .and_then(|id| state.sessions.get(&id)) + .map_or_else(|| format!("client {client}"), |v| v.nickname(client)) +} + +// The stream settings panel. + +/// What editing a field of the stream settings asks for. +#[derive(Debug, PartialEq)] +pub enum Edit { + /// Store these settings. + Ui(StudioUi), + /// The bitrate typed: kbit/s (0 automatic); `None` if it is not one. + Bitrate(Option), + /// A destination picked, by its index in the list. + Destination(Option), + /// Not a field. + Nothing, +} + +/// What the bitrate field's refusal says. +pub const BITRATE_HINT: &str = "The bitrate is a whole number of kbit/s, or auto."; + +/// A field of the stream settings was edited (`value` as typed; a switch's +/// is "true" or "false"). +pub fn edit(ui: &StudioUi, key: &str, value: &str) -> Edit { + let mut ui = ui.clone(); + let on = value == "true"; + match key { + "title" => ui.title = value.into(), + "game" => ui.game = value.into(), + "message" => ui.message = value.into(), + "show-viewers" => ui.show_viewers = on, + "show-chat" => ui.show_chat = on, + "show-now-playing" => ui.show_now_playing = on, + "audio" => ui.audio = on, + "bitrate" => { + // Nothing, 0 or "auto": automatic. + let auto = + matches!(value.trim(), "" | "0") || value.trim().eq_ignore_ascii_case("auto"); + return Edit::Bitrate(parse_positive(value).or(auto.then_some(0))); + } + "destination" => return Edit::Destination(value.parse::().ok()), + _ => return Edit::Nothing, + } + Edit::Ui(ui) +} + +/// The output's size and rate typed: all three must be numbers above 0. +pub fn parse_output(width: &str, height: &str, fps: &str) -> Option<(u32, u32, u32)> { + Some((parse_positive(width)?, parse_positive(height)?, parse_positive(fps)?)) +} + +/// What the output's refusal says. +pub const OUTPUT_HINT: &str = "The output is a width, a height and a frame rate above 0."; + +/// A row of the stream's layers was edited. `None`: there is no such layer; +/// else what is to be said. +pub fn set_layer(settings: &Settings, index: usize, row: &StudioLayer) -> Option> { + let mut layers = settings.get(&STREAM_LAYERS); + let old = layers.get(index)?; + match parse_layer(row, old) { + Ok(layer) => layers[index] = layer, + Err(e) => return Some(vec![format!("Layer {}: {e}", index + 1)]), + } + Some(settings.set(&STREAM_LAYERS, layers).err().map(|e| e.to_string()).into_iter().collect()) +} + +/// Add a layer (the first addition makes two), the bitrate of the stream +/// without layers being `bitrate_kbps`. +pub fn add_layer(settings: &Settings, bitrate_kbps: u32) -> Vec { + let mut layers = settings.get(&STREAM_LAYERS); + if layers.is_empty() { + layers.push(next_layer(&[], bitrate_kbps)); + } + layers.push(next_layer(&layers, bitrate_kbps)); + settings.set(&STREAM_LAYERS, layers).err().map(|e| e.to_string()).into_iter().collect() +} + +/// Remove a layer (no such one: nothing); one layer left is the single layer. +pub fn remove_layer(settings: &Settings, index: usize) -> Vec { + let mut layers = settings.get(&STREAM_LAYERS); + let mut said = Vec::new(); + if index < layers.len() { + layers.remove(index); + // One layer left is the single layer. + if layers.len() == 1 { + layers.clear(); + } + said.extend(settings.set(&STREAM_LAYERS, layers).err().map(|e| e.to_string())); + } + said +} + +/// What the studio settings dialog (replay buffer, recordings, preview) +/// shows. +pub fn settings_form(settings: &Settings, ui: &StudioUi) -> StudioSettingsForm { + StudioSettingsForm { + replay_seconds: settings.get(&STUDIO_REPLAY_SECONDS).to_string().into(), + replay_memory: settings.get(&STUDIO_REPLAY_MEMORY_MB).to_string().into(), + recording_dir: settings.get(&STUDIO_RECORDING_DIR).into(), + preview_width: ui.preview_width.to_string().into(), + preview_fps: ui.preview_fps.to_string().into(), + } +} + +/// What applying the studio settings dialog did. +#[derive(Debug, Default, PartialEq)] +pub struct SettingsApplied { + /// A number that was not one, to be said at once. + pub notes: Vec, + /// The first refusal of the settings, to be said last. + pub refused: Option, + /// The stream settings with the preview's new size and rate, if they + /// changed. + pub ui: Option, +} + +/// The studio settings dialog was applied. +pub fn apply_settings_form( + settings: &Settings, + ui: &StudioUi, + form: &StudioSettingsForm, +) -> SettingsApplied { + let number = |text: &str| text.trim().parse::().ok(); + let mut done = SettingsApplied::default(); + let mut errors = Vec::new(); + match number(&form.replay_seconds).and_then(|v| u32::try_from(v).ok()) { + Some(v) => errors.extend(settings.set(&STUDIO_REPLAY_SECONDS, v).err()), + None => done.notes.push("The replay buffer is a whole number of seconds.".into()), + } + match number(&form.replay_memory) { + Some(v) => errors.extend(settings.set(&STUDIO_REPLAY_MEMORY_MB, v).err()), + None => done.notes.push("The replay memory is a whole number of MB.".into()), + } + errors.extend(settings.set(&STUDIO_RECORDING_DIR, form.recording_dir.trim().to_owned()).err()); + let mut changed = ui.clone(); + if let (Some(width), Some(fps)) = + (parse_positive(&form.preview_width), parse_positive(&form.preview_fps)) + { + changed.preview_width = width; + changed.preview_fps = fps; + } + done.ui = (changed != *ui).then_some(changed); + done.refused = errors.first().map(ToString::to_string); + done +} + +// Scenes and sources. + +/// What a source control of the live scene does. +pub enum SourceStep { + /// A command for the studio. + Apply(studio::Command), + /// A change of the source. + Update(SourceChange), + /// Something for the status line. + Say(&'static str), +} + +/// A control of source `id` in the live scene: up, down, lock, remove, +/// next-camera, bg-keep, bg-blur. `cameras` lists the cameras when the next +/// one is asked for. `None`: nothing to do. +pub fn source_action( + scenes: &Scenes, + id: u64, + action: &str, + cameras: impl FnOnce() -> Vec, +) -> Option { + let scene = scenes.active()?; + let index = scene.sources.iter().position(|s| s.id == id)?; + let source = &scene.sources[index]; + let (scene, locked) = (scene.id, source.locked); + match action { + "up" | "down" => { + let to = if action == "up" { index + 1 } else { index.saturating_sub(1) }; + Some(SourceStep::Apply(studio::Command::ReorderSource { scene, source: id, to })) + } + "lock" => { + Some(SourceStep::Update(SourceChange { locked: Some(!locked), ..Default::default() })) + } + "remove" => Some(SourceStep::Apply(studio::Command::RemoveSource { scene, source: id })), + // The next camera (a phone's front and back), mirrored as that + // camera is by default. + "next-camera" => { + let SourceKind::Camera { device, size, fps, .. } = source.kind.clone() else { + return None; + }; + let name = source.name.clone(); + let cameras = cameras(); + let real: Vec<_> = cameras.iter().filter(|c| c.backend != "synthetic").collect(); + let at = real.iter().position(|c| c.id == device); + let next = at.map_or(real.first(), |i| real.get((i + 1) % real.len())); + let Some(next) = next.filter(|c| c.id != device) else { + return Some(SourceStep::Say("There is no other camera.")); + }; + let kind = + SourceKind::Camera { device: next.id.clone(), size, fps, mirror: next.mirrored }; + // A source named after its camera is named after the next. + let renamed = name.is_empty() || at.is_some_and(|i| real[i].name == name); + let name = renamed.then(|| next.name.clone()); + Some(SourceStep::Update(SourceChange { kind: Some(kind), name, ..Default::default() })) + } + "bg-keep" | "bg-blur" => { + let background = if action == "bg-blur" { + Background::Blur { strength: 0.04 } + } else { + Background::Keep + }; + Some(SourceStep::Update(SourceChange { + background: Some(background), + ..Default::default() + })) + } + _ => None, + } +} + +/// What the source dialog changes of `old`, and a notice when part of it is +/// left out (a locked source keeps its place unless it is unlocked). +pub fn source_change( + form: &StudioSourceForm, + old: &Source, +) -> Result<(SourceChange, Option<&'static str>), String> { + let mut change = super::change(form, old)?; + if old.locked && form.locked && (change.transform.is_some() || change.crop.is_some()) { + change.transform = None; + change.crop = None; + return Ok((change, Some("Unlock the source to move, resize or crop it."))); + } + Ok((change, None)) +} + +/// The visibility changes of the phone's source cards: showing `kind` +/// ("screen", "camera", else window) and hiding the other two, as (source, +/// visible) for the sources that change; and whether the live scene has a +/// source of the kind. +pub fn main_source_changes(scene: Option<&Scene>, kind: &str) -> (Vec<(u64, bool)>, bool) { + let wanted = |k: &SourceKind| match kind { + "screen" => matches!( + k, + SourceKind::Screen { .. } | SourceKind::Portal { .. } | SourceKind::Pattern { .. } + ), + "camera" => matches!(k, SourceKind::Camera { .. }), + _ => matches!(k, SourceKind::Window { .. }), + }; + let main = |k: &SourceKind| { + matches!( + k, + SourceKind::Screen { .. } + | SourceKind::Portal { .. } + | SourceKind::Pattern { .. } + | SourceKind::Camera { .. } + | SourceKind::Window { .. } + ) + }; + let sources: Vec<(u64, bool, bool, bool)> = scene + .map(|s| { + s.sources.iter().map(|s| (s.id, wanted(&s.kind), main(&s.kind), s.visible)).collect() + }) + .unwrap_or_default(); + let changes = sources.iter().filter(|s| s.2 && s.1 != s.3).map(|s| (s.0, s.1)).collect(); + (changes, sources.iter().any(|s| s.1)) +} + +// The pickers. + +fn pick_row(name: &str, detail: String, icon: &str) -> StudioPick { + StudioPick { name: name.into(), detail: detail.into(), kind: icon.into(), ..Default::default() } +} + +fn source_pick(name: &str, kind: SourceKind) -> Pick { + Pick::Source { name: name.into(), kind } +} + +fn camera_pick(device: String, name: String, detail: String, mirror: bool) -> (Pick, StudioPick) { + let kind = SourceKind::Camera { device, size: None, fps: None, mirror }; + (source_pick(&name, kind), pick_row(&name, detail, "camera")) +} + +/// The cameras to pick from. +pub fn camera_picks(cameras: &[camera::Camera]) -> Picks { + cameras + .iter() + .map(|c| { + let biggest = c.formats.iter().flat_map(|f| &f.sizes).max_by_key(|(w, h)| w * h); + let detail = biggest.map_or(String::new(), |(w, h)| format!("up to {w}×{h}")); + camera_pick(c.id.clone(), c.name.clone(), detail, c.mirrored) + }) + .collect() +} + +/// The demo never opens a device, not even to list it: the test pattern. +pub fn demo_camera_picks() -> Picks { + vec![camera_pick( + camera::SYNTHETIC.to_owned(), + "Test pattern".to_owned(), + "1280×720".to_owned(), + true, + )] +} + +/// The screens (`kind` "screen") or windows ("window") to pick from; the +/// test pattern too when `test_pattern`. +pub fn screen_picks(kind: &str, list: Vec, test_pattern: bool) -> Picks { + let mut picks: Picks = Vec::new(); + for s in list { + let size = if s.width > 0 { format!("{}×{}", s.width, s.height) } else { String::new() }; + match s.id { + SourceId::Monitor(monitor) if kind == "screen" => { + let detail = if s.primary { format!("{size} · primary") } else { size }; + let k = SourceKind::Screen { monitor, backend: None, cursor: true }; + picks.push((source_pick(&s.name, k), pick_row(&s.name, detail, "monitor"))); + } + SourceId::Window(handle) if kind == "window" => { + let k = SourceKind::Window { handle, backend: None, cursor: true }; + picks.push((source_pick(&s.name, k), pick_row(&s.name, size, "window"))); + } + SourceId::Portal => { + let k = SourceKind::Portal { restore_token: None, cursor: true }; + let name = if kind == "screen" { "Screen" } else { "Window" }; + let detail = "Your desktop asks what to share".to_owned(); + picks.push(( + source_pick(name, k), + pick_row("Choose with the system dialog", detail, "portal"), + )); + } + _ => {} + } + } + if test_pattern { + let k = SourceKind::Pattern { size: (1280, 720) }; + picks.push(( + source_pick("Test pattern", k), + pick_row("Test pattern", "1280×720".into(), "pattern"), + )); + } + picks +} + +/// The desktop's own dialog is the one choice: it is added at once. +pub fn only_portal(picks: &Picks) -> bool { + picks.len() == 1 && matches!(&picks[0].0, Pick::Source { kind: SourceKind::Portal { .. }, .. }) +} + +/// The new source of a picked row: named, placed in the output. +pub fn picked_source(pick: &Pick, output: (u32, u32)) -> Option { + let Pick::Source { name, kind } = pick else { return None }; + let mut source = Source::new(0, kind.clone()); + source.name.clone_from(name); + source.transform = placement(kind, output); + Some(source) +} + +/// What can be added to the mixer: the fixed sources, then the sample tones +/// (`demo`) or the applications that play audio (`apps`); a row is selected +/// when its source is mixed in already (`current`). +pub fn audio_picks(current: &[AudioSourceSetting], apps: Vec, demo: bool) -> Picks { + let mut picks: Picks = Vec::new(); + let mut add = + |setting: AudioSourceSetting, name: String, detail: String, icon: Option<&str>| { + let (_, _, kind) = audio_label(&setting.kind); + let row = StudioPick { + name: name.into(), + detail: detail.into(), + kind: kind.into(), + // An application's own icon, when it gave a file (Android + // does; a desktop icon theme name is left out). + icon: icon + .map(Path::new) + .filter(|p| p.is_absolute()) + .map(ImageSource::file) + .unwrap_or_default(), + selected: current.iter().any(|s| s.kind == setting.kind), + }; + picks.push((Pick::Audio(setting), row)); + }; + let fixed = [ + (AudioSourceKindSetting::Microphone, "Microphone", "What you say in voice, cleaned up"), + (AudioSourceKindSetting::Desktop, "Desktop audio", "Everything that plays, without Voelin"), + ( + AudioSourceKindSetting::Window, + "Audio of the shared window", + "Its application (X11 and Windows)", + ), + ]; + for (kind, name, detail) in fixed { + // A phone shares the whole screen: there is no window's app. + if cfg!(target_os = "android") && kind == AudioSourceKindSetting::Window { + continue; + } + add(AudioSourceSetting::new(kind), name.into(), detail.into(), None); + } + if demo { + for frequency in [440, 660, 330] { + let kind = AudioSourceKindSetting::Synthetic { frequency }; + let detail = format!("{frequency} Hz"); + add(AudioSourceSetting::new(kind), "Test tone".into(), detail, None); + } + } else { + for app in apps { + let name = app.binary.clone().unwrap_or_else(|| app.name.clone()); + let kind = AudioSourceKindSetting::App { name: Some(name), pid: None }; + let detail = app + .media + .clone() + .unwrap_or_else(|| if app.playing { "playing".into() } else { String::new() }); + add(AudioSourceSetting::new(kind), app.name, detail, app.icon.as_deref()); + } + } + picks +} + +// The mixer. + +/// Mix a picked source in, or take it out if it is (the picker chooses +/// several at once). +pub fn toggle_audio(sources: &mut Vec, setting: AudioSourceSetting) { + if sources.iter().any(|s| s.kind == setting.kind) { + sources.retain(|s| s.kind != setting.kind); + } else { + sources.push(setting); + } +} + +/// Set the gain of a source (linear). +pub fn set_gain(sources: &mut [AudioSourceSetting], index: usize, gain: f32) { + if let Some(s) = sources.get_mut(index) { + s.gain = gain; + } +} + +/// Mute a source, or unmute it. +pub fn toggle_mute(sources: &mut [AudioSourceSetting], index: usize) { + if let Some(s) = sources.get_mut(index) { + s.muted = !s.muted; + } +} + +/// Take a source out of the mixer. +pub fn remove_audio(sources: &mut Vec, index: usize) { + if index < sources.len() { + sources.remove(index); + } +} + +// Sample data (VOELIN_DEMO_UI). + +/// The demo studio of VOELIN_DEMO_UI: sample scenes from synthetic sources, +/// test tones, recordings in a temporary folder; in memory only. +pub fn demo_settings() -> (Settings, Vec) { + let settings = Settings::in_memory(); + let text = |text: &str, size_px: f32| SourceKind::Text { + text: text.into(), + font: None, + size_px, + colour: Colour::WHITE, + backdrop: Colour::CLEAR, + align: Align::Center, + padding: 0, + }; + let source = |id: u64, name: &str, kind: SourceKind, transform: Transform| Source { + name: name.into(), + transform, + ..Source::new(id, kind) + }; + let slate = |id: u64, name: &str, words: &str| { + let mut scene = Scene::new(id, name); + scene.sources = vec![ + source( + 1, + "Backdrop", + SourceKind::Colour { colour: Colour::rgb(16, 26, 60), size: (1920, 1080) }, + Transform::full(1920, 1080), + ), + source(2, "Title", text(words, 120.0), Transform::box_at(160.0, 440.0, 1600.0, 200.0)), + ]; + scene + }; + let camera = SourceKind::Camera { + device: camera::SYNTHETIC.into(), + size: None, + fps: None, + mirror: false, + }; + let mut main = Scene::new(1, "Main Stream"); + let mut cam = source(2, "Camera", camera.clone(), Transform::default()); + cam.transform = placement(&camera, (1920, 1080)); + cam.background = Background::Blur { strength: 0.04 }; + let mut game = source( + 1, + "Game Capture", + SourceKind::Pattern { size: (1280, 720) }, + Transform { fit: Fit::Cover, ..Transform::full(1920, 1080) }, + ); + // The pattern's frame counter sits in its top-left corner, under the + // preview's LIVE badge and timer: cropped away. + game.crop = Crop { top: 120, ..Crop::default() }; + main.sources = vec![game, cam]; + let mut chatting = Scene::new(2, "Just Chatting"); + chatting.sources = vec![source( + 1, + "Camera", + camera, + Transform { fit: Fit::Cover, ..Transform::full(1920, 1080) }, + )]; + let scenes = Scenes { + scenes: vec![ + main, + chatting, + slate(3, "Be Right Back", "Be right back"), + slate(4, "Starting Soon", "Starting soon"), + slate(5, "Ending", "Thanks for watching"), + ], + active: 1, + width: 1920, + height: 1080, + fps: 60, + }; + let tone = |frequency, gain| AudioSourceSetting { + gain, + ..AudioSourceSetting::new(AudioSourceKindSetting::Synthetic { frequency }) + }; + let recordings = std::env::temp_dir().join("voelin-demo-recordings"); + let results = [ + settings.set(&STUDIO_SCENES, scenes), + settings.set( + &STREAM_AUDIO_SOURCES, + vec![ + AudioSourceSetting { + gain: 0.49, + ..AudioSourceSetting::new(AudioSourceKindSetting::Microphone) + }, + tone(440, 0.25), + tone(660, 0.39), + ], + ), + settings.set(&STUDIO_RECORDING_DIR, recordings.display().to_string()), + settings.set( + &STUDIO_UI, + StudioUi { + title: "Exploring the Lands Between".into(), + game: "Adventure".into(), + message: "Going live in Chill Zone — exploring the Lands Between. Come hang!" + .into(), + show_viewers: true, + show_now_playing: true, + ..StudioUi::default() + }, + ), + ]; + // The demo goes on with what it has. + let problems = results.into_iter().filter_map(|r| r.err()).map(|e| e.to_string()).collect(); + (settings, problems) +} + +/// The sample viewers of the demo stream going live. +pub fn demo_viewers() -> Vec { + let viewer = |id: u16, state: ViewerState, estimate: u64| ViewerInfo { + client: id, + state, + message: String::new(), + layer: Some(0), + estimate: Some(estimate), + srtp_profile: None, + codec: None, + }; + vec![ + viewer(3, ViewerState::Connected, 12_000_000), + viewer(4, ViewerState::Connected, 9_500_000), + viewer(9, ViewerState::Connected, 20_000_000), + viewer(5, ViewerState::Connecting, 0), + viewer(6, ViewerState::Requested, 0), + ] +} + +/// The id of the stream the sample server announces for the demo studio. +pub const DEMO_STREAM_ID: &str = "demo-studio"; + +/// The stream the sample server announces for ours (`own`: our client id). +pub fn demo_stream(own: ClientId, name: String, audio: bool) -> StreamInfo { + StreamInfo { + id: DEMO_STREAM_ID.into(), + streamer: own, + name, + kind: StreamKind::Screen, + bitrate: 8000, + viewer_limit: 0, + audio, + viewers: Some(3), + } +} + +/// A message sent in the demo, as the engine would have echoed it. +pub fn demo_message( + target: ChatTarget, + author: String, + client: Option, + text: String, + ts_ms: i64, +) -> ChatMessage { + ChatMessage { + target, + author_name: author, + author_uid: client.map(|c| format!("demo-{c}")), + author_id: client, + text, + ts_ms, + via_relay: false, + blocked: false, + } +} + +/// A demo message as a session with stored history keeps it (in memory only: +/// the id is negative). +pub fn demo_stored(message: ChatMessage) -> HistoryMessage { + HistoryMessage { + id: -message.ts_ms, + message, + source: MessageSource::Voice, + remote_id: None, + topic_id: None, + reactions: Vec::new(), + pinned: false, + rev: 0, + } +} + +#[cfg(test)] +mod tests { + use voelin_core::VoiceState; + use voelin_core::media::voelin_media::capture::CaptureSource; + use voelin_core::settings::LayerSetting; + use voelin_core::studio::camera::Camera; + use voelin_store::Bookmark; + + use super::*; + use crate::settings::UiSettings; + + fn viewer(client: u16, state: ViewerState, estimate: Option) -> ViewerInfo { + ViewerInfo { + client, + state, + message: String::new(), + layer: None, + estimate, + srtp_profile: None, + codec: None, + } + } + + fn state_with(sessions: &[(i64, bool)]) -> AppState<()> { + let bookmarks = sessions + .iter() + .map(|(id, _)| Bookmark { + id: *id, + name: format!("Server {id}"), + ..Bookmark::default() + }) + .collect(); + let mut state = AppState::<()>::new( + bookmarks, + UiSettings::default(), + Default::default(), + Default::default(), + ); + for (id, streams) in sessions { + let view = state.sessions.entry(*id).or_default(); + view.capabilities.streams = *streams; + view.state.voice = VoiceState::Connected; + view.state.own_channel = Some(7); + } + state + } + + fn data_with_scenes() -> StudioData { + let mut data = StudioData::default(); + let mut scene = Scene::new(1, "Main"); + scene.sources = vec![ + Source { + name: "Screen".into(), + ..Source::new(1, SourceKind::Pattern { size: (1280, 720) }) + }, + Source { + name: "Cam".into(), + ..Source::new( + 2, + SourceKind::Camera { device: "a".into(), size: None, fps: None, mirror: false }, + ) + }, + ]; + data.scenes = Arc::new(Scenes { + scenes: vec![scene, Scene::new(2, "Break")], + active: 1, + width: 1920, + height: 1080, + fps: 60, + }); + data + } + + #[test] + fn the_stream_is_named_after_its_title_and_game() { + let ui = |title: &str, game: &str| StudioUi { + title: title.into(), + game: game.into(), + ..StudioUi::default() + }; + assert_eq!(stream_name(&ui(" Speedrun ", "Zelda")), "Speedrun — Zelda"); + assert_eq!(stream_name(&ui("Speedrun", " ")), "Speedrun"); + assert_eq!(stream_name(&ui("", "Zelda")), "Zelda"); + assert_eq!(now_playing(&ui("Speedrun", "Zelda")).as_deref(), Some("Speedrun\nZelda")); + assert_eq!(now_playing(&ui(" ", "")), None); + assert!(file_name("Clip").starts_with("Clip 2") && file_name("Clip").ends_with(".mkv")); + } + + #[test] + fn editing_a_field_of_the_panel() { + let ui = StudioUi::default(); + let edited = |key, value| match edit(&ui, key, value) { + Edit::Ui(ui) => ui, + other => panic!("{key}: {other:?}"), + }; + assert_eq!(edited("title", "Hello").title, "Hello"); + assert!(edited("show-chat", "true").show_chat); + assert!(!edited("audio", "false").audio); + assert_eq!(edit(&ui, "bitrate", " 4500 "), Edit::Bitrate(Some(4500))); + assert_eq!(edit(&ui, "bitrate", "Auto"), Edit::Bitrate(Some(0))); + assert_eq!(edit(&ui, "bitrate", ""), Edit::Bitrate(Some(0))); + assert_eq!(edit(&ui, "bitrate", "fast"), Edit::Bitrate(None)); + assert_eq!(edit(&ui, "destination", "2"), Edit::Destination(Some(2))); + assert_eq!(edit(&ui, "destination", "-"), Edit::Destination(None)); + assert_eq!(edit(&ui, "colour", "red"), Edit::Nothing); + assert_eq!(parse_output("1920", "1080", "60"), Some((1920, 1080, 60))); + assert_eq!(parse_output("1920", "0", "60"), None); + assert_eq!(parse_output("wide", "1080", "60"), None); + } + + #[test] + fn the_bitrate_is_automatic_for_the_output_or_as_set() { + let mut data = data_with_scenes(); + let settings = Settings::in_memory(); + settings.set(&STREAM_BITRATE_KBPS, 0).unwrap(); + assert_eq!( + u64::from(data.bitrate_kbps(&settings)) * 1000, + auto_bitrate(1920, 1080, 60) / 1000 * 1000 + ); + settings.set(&STREAM_BITRATE_KBPS, 6000).unwrap(); + assert_eq!(data.bitrate_kbps(&settings), 6000); + // Without layers: one layer at that bitrate; with: the layers. + let layers = data.session_layers(&settings); + assert_eq!(layers.len(), 1); + assert_eq!(data.go_live_bitrate(&settings), 6000); + settings + .set( + &STREAM_LAYERS, + vec![ + LayerSetting { bitrate: 8_000_000, ..LayerSetting::default() }, + LayerSetting { bitrate: 2_000_000, scale: 0.5, ..LayerSetting::default() }, + ], + ) + .unwrap(); + assert_eq!(data.session_layers(&settings).len(), 2); + assert_eq!(data.go_live_bitrate(&settings), 8000); + data.ui = StudioUi { title: "T".into(), audio: false, ..StudioUi::default() }; + let setup = data.stream_setup(&settings); + assert_eq!((setup.name.as_str(), setup.bitrate, setup.audio), ("T", 8000, false)); + } + + #[test] + fn the_studio_stops_after_a_few_ticks_hidden() { + let mut data = StudioData::default(); + assert!(data.keep_running(true)); + assert!(data.keep_running(false) && data.keep_running(false)); + assert!(!data.keep_running(false)); + // Shown again, or busy: the count starts over. + assert!(data.keep_running(true)); + assert_eq!(data.hidden, 0); + data.status.recording = Some("clip.mkv".into()); + assert!(data.busy() && data.keep_running(false) && data.keep_running(false)); + data.status.recording = None; + data.stream = Some(Outgoing { session: 1, live: false, viewers: Vec::new() }); + assert!(data.busy() && data.keep_running(false)); + } + + #[test] + fn the_preview_follows_the_shape_of_the_output() { + let mut data = data_with_scenes(); + let size = |data: &StudioData| match data.preview_command() { + studio::Command::SetPreview { width, height, fps } => (width, height, fps), + other => panic!("{other:?}"), + }; + assert_eq!(size(&data), (960, 540, 15)); + data.ui.preview_width = 1; + data.ui.preview_fps = 0; + assert_eq!(size(&data), (16, 8, 1)); + let mut scenes = (*data.scenes).clone(); + scenes.width = 1000; + scenes.height = 1000; + let (switched, resized) = data.set_scenes(Arc::new(scenes.clone())); + assert!((switched, resized) == (false, true)); + scenes.active = 2; + assert_eq!(data.set_scenes(Arc::new(scenes)), (true, false)); + } + + #[test] + fn destinations_are_sessions_with_streams_and_a_channel() { + let mut state = state_with(&[(3, true), (1, true), (2, false)]); + state.current = Some(3); + let list = destinations(&state); + // TeamSpeak 6 with voice only; the current one first. + assert_eq!(list.iter().map(|d| d.0).collect::>(), [3, 1]); + assert_eq!(list[0].1, " • Server 3"); + assert_eq!(chat_target(&state, Some(1)), Some((1, 7))); + assert_eq!(chat_target(&state, Some(9)), None); + assert_eq!(chat_target(&state, None), None); + let rows = destination_rows(&state, &list); + assert_eq!((&*rows[1].detail, &*rows[1].kind), ("Server 1", "server")); + // The tab of the destination's channel is made once. + assert_eq!(chat_tab(&mut state, 1, 7), (String::new(), true)); + assert_eq!(chat_tab(&mut state, 1, 7), (String::new(), false)); + assert_eq!(state.sessions[&1].tabs.len(), 2); + assert_eq!(viewer_name(&state, Some(1), 5), "client 5"); + assert_eq!(viewer_name(&state, None, 5), "client 5"); + } + + #[test] + fn the_destination_stays_while_it_works() { + let list = vec![(1, "a".to_owned()), (2, "b".to_owned())]; + let mut data = StudioData::default(); + data.choose_destination(&list); + assert_eq!(data.destination, Some(1)); + data.destination = Some(2); + data.choose_destination(&list); + assert_eq!(data.destination, Some(2)); + // Gone: the first. Live to a session that is gone from the list: it + // stays the stream's. + data.choose_destination(&list[..1]); + assert_eq!(data.destination, Some(1)); + data.stream = Some(Outgoing { session: 5, live: true, viewers: Vec::new() }); + assert!(data.streams_to(5) && !data.streams_to(1)); + data.choose_destination(&list); + assert_eq!(data.destination, Some(5)); + data.choose_destination(&[]); + assert_eq!(data.destination, Some(5)); + data.stream = None; + data.choose_destination(&[]); + assert_eq!(data.destination, None); + // The form says where in the list. + data.destination = Some(2); + let form = data.form(&list); + assert_eq!((form.destination, &*form.bitrate), (1, "")); + data.destination = Some(9); + assert_eq!(data.form(&list).destination, -1); + } + + #[test] + fn the_status_says_what_keeps_the_stream_from_going_live() { + let named = |v: &ViewerInfo| format!("viewer {}", v.client); + let mut data = data_with_scenes(); + let cx = |running, has_encoder, sharing, destination: Option<&str>| StatusContext { + running, + has_encoder, + detached: false, + sharing, + destination: destination.map(str::to_owned), + viewer_name: &named, + }; + let hint = + |data: &StudioData, cx: &StatusContext<'_>| data.status_view(cx).0.hint.to_string(); + assert_eq!(hint(&data, &cx(false, false, false, None)), "Starting the studio…"); + assert_eq!(hint(&data, &cx(true, false, false, Some("a"))), "Starting the studio…"); + assert_eq!( + hint(&data, &cx(true, true, false, None)), + "Join a voice channel on a TeamSpeak 6 server to go live." + ); + assert_eq!( + hint(&data, &cx(true, true, true, Some("a"))), + "Stop sharing your screen first." + ); + data.error = "The studio did not start".into(); + assert_eq!(hint(&data, &cx(true, true, false, Some("a"))), "The studio did not start"); + data.error.clear(); + let (status, requests) = data.status_view(&cx(true, true, false, Some("Chill • Guild"))); + assert!(status.can_go_live && status.hint.is_empty() && !status.live); + assert_eq!( + (&*status.destination, status.output_height, status.fps), + ("Chill • Guild", 1080, 60) + ); + assert!(requests.is_empty()); + assert!(status.screen_shown && status.camera_shown && !status.window_shown); + assert_eq!(&*status.format, "1080p • 60 FPS • 0 kbps"); + let settings = Settings::in_memory(); + settings.set(&STREAM_BITRATE_KBPS, 8250).unwrap(); + data.settings = Some(settings); + let (status, _) = data.status_view(&cx(true, true, false, Some("Chill • Guild"))); + assert_eq!(&*status.format, "1080p • 60 FPS • 8,250 kbps"); + // Going live: waiting, then live with viewers. + data.stream = Some(Outgoing { + session: 1, + live: false, + viewers: vec![ + viewer(4, ViewerState::Requested, None), + viewer(5, ViewerState::Connected, Some(4_000_000)), + ], + }); + let (status, requests) = data.status_view(&cx(true, true, false, Some("a"))); + assert!(status.starting && !status.can_go_live); + assert_eq!(&*status.hint, "Waiting for the server…"); + assert_eq!((status.viewers, status.participants), (1, 2)); + assert_eq!(requests.len(), 1); + assert_eq!((&*requests[0].name, &*requests[0].state), ("viewer 4", "requested")); + data.stream.as_mut().unwrap().live = true; + let (status, _) = data.status_view(&cx(true, true, false, Some("a"))); + assert!(status.live && !status.can_go_live && status.quality > 0); + } + + #[test] + fn overlays_follow_the_switches() { + let mut data = StudioData { + ui: StudioUi { + title: "T".into(), + game: "G".into(), + show_viewers: true, + show_now_playing: true, + ..StudioUi::default() + }, + stream: Some(Outgoing { + session: 1, + live: true, + viewers: vec![ + viewer(1, ViewerState::Connected, None), + viewer(2, ViewerState::Connecting, None), + ], + }), + ..StudioData::default() + }; + let wanted = data.wanted_overlays(|| panic!("the chat is off")); + assert_eq!(wanted[0].text.as_deref(), Some("1 watching")); + assert_eq!(wanted[1].text, None); + assert_eq!(wanted[2].text.as_deref(), Some("T\nG")); + // Sent the first time, and again when something changed or when forced. + assert!(data.overlay_change(false, wanted.clone()).is_some()); + assert!(data.overlay_change(false, wanted.clone()).is_none()); + assert!(data.overlay_change(true, wanted.clone()).is_some()); + data.ui.show_chat = true; + let with_chat = data.wanted_overlays(|| Some("a: hi".into())); + assert_eq!(with_chat[1].text.as_deref(), Some("a: hi")); + assert_eq!(data.overlay_change(false, with_chat).map(|w| w.len()), Some(3)); + } + + #[test] + fn the_chat_overlay_has_the_last_lines_cut_short() { + let line = |author: &str, text: &str| ChatLine { + author: author.into(), + text: text.into(), + ..ChatLine::default() + }; + assert_eq!(chat_tail(&[], 5), None); + let long = "x".repeat(100); + let lines = [line("a", "one"), line("b", "two"), line("c", &long)]; + assert_eq!( + chat_tail(&lines, 2).as_deref(), + Some(format!("b: two\nc: {}…", "x".repeat(61)).as_str()) + ); + assert_eq!(chat_tail(&lines, 9).unwrap().lines().count(), 3); + } + + #[test] + fn layers_are_edited_in_the_settings() { + let settings = Settings::in_memory(); + let row = |size: &str, bitrate: &str| StudioLayer { + size: size.into(), + bitrate: bitrate.into(), + ..StudioLayer::default() + }; + assert!(add_layer(&settings, 6000).is_empty()); + assert_eq!(settings.get(&STREAM_LAYERS).len(), 2); + assert_eq!(set_layer(&settings, 5, &row("1280x720", "2500")), None); + let said = set_layer(&settings, 1, &row("nonsense", "2500")).unwrap(); + assert!(said[0].starts_with("Layer 2: "), "{said:?}"); + assert_eq!(set_layer(&settings, 1, &row("1280x720", "2500")), Some(Vec::new())); + assert_eq!(settings.get(&STREAM_LAYERS)[1].size, Some((1280, 720))); + // One layer left is the single layer: none. + assert!(remove_layer(&settings, 0).is_empty()); + assert!(settings.get(&STREAM_LAYERS).is_empty()); + assert!(remove_layer(&settings, 3).is_empty()); + } + + #[test] + fn the_source_controls_make_commands_and_changes() { + let data = data_with_scenes(); + let scenes = &*data.scenes; + let act = |id, action: &str| source_action(scenes, id, action, Vec::new); + assert!(matches!( + act(1, "up"), + Some(SourceStep::Apply(studio::Command::ReorderSource { scene: 1, source: 1, to: 1 })) + )); + assert!(matches!( + act(2, "down"), + Some(SourceStep::Apply(studio::Command::ReorderSource { to: 0, .. })) + )); + assert!(matches!( + act(1, "remove"), + Some(SourceStep::Apply(studio::Command::RemoveSource { scene: 1, source: 1 })) + )); + assert!(matches!( + act(1, "lock"), + Some(SourceStep::Update(SourceChange { locked: Some(true), .. })) + )); + assert!(matches!( + act(1, "bg-blur"), + Some(SourceStep::Update(SourceChange { + background: Some(Background::Blur { .. }), + .. + })) + )); + assert!(matches!( + act(1, "bg-keep"), + Some(SourceStep::Update(SourceChange { background: Some(Background::Keep), .. })) + )); + assert!(act(9, "up").is_none() && act(1, "spin").is_none()); + // The next camera: not a camera, no other one, another one. + assert!(act(1, "next-camera").is_none()); + assert!(matches!( + act(2, "next-camera"), + Some(SourceStep::Say("There is no other camera.")) + )); + let camera = |id: &str, name: &str, mirrored| Camera { + id: id.into(), + name: name.into(), + backend: "v4l2", + formats: Vec::new(), + mirrored, + }; + let two = || vec![camera("a", "Cam", true), camera("b", "Back", false)]; + let Some(SourceStep::Update(change)) = source_action(scenes, 2, "next-camera", two) else { + panic!("no camera change"); + }; + // Named after its camera: named after the next; mirrored as that one is. + assert_eq!(change.name.as_deref(), Some("Back")); + assert!( + matches!(change.kind, Some(SourceKind::Camera { ref device, mirror: false, .. }) if device == "b") + ); + } + + #[test] + fn a_locked_source_keeps_its_place() { + let mut data = data_with_scenes(); + let id = 1; + let scene = Arc::make_mut(&mut data.scenes).active_mut().unwrap(); + scene.sources[0].locked = true; + let old = data.live_source(id).unwrap().clone(); + let form = StudioSourceForm { x: "100".into(), ..super::super::form(&old) }; + let (change, notice) = source_change(&form, &old).unwrap(); + assert!(change.transform.is_none() && change.crop.is_none()); + assert_eq!(notice, Some("Unlock the source to move, resize or crop it.")); + let unlocked = StudioSourceForm { locked: false, ..form }; + let (change, notice) = source_change(&unlocked, &old).unwrap(); + assert!(notice.is_none() && change.locked == Some(false)); + } + + #[test] + fn the_phones_source_cards_show_one_kind() { + let data = data_with_scenes(); + let scene = data.scenes.active(); + // Camera: the screen goes, the camera stays. + let (changes, has) = main_source_changes(scene, "camera"); + assert_eq!((changes, has), (vec![(1, false)], true)); + let (changes, has) = main_source_changes(scene, "screen"); + assert_eq!((changes, has), (vec![(2, false)], true)); + // No window: both go and one is to be added. + let (changes, has) = main_source_changes(scene, "window"); + assert_eq!((changes, has), (vec![(1, false), (2, false)], false)); + assert_eq!(main_source_changes(None, "screen"), (Vec::new(), false)); + } + + #[test] + fn pickers_list_what_can_be_added() { + let camera = |id: &str, mirrored| Camera { + id: id.into(), + name: format!("Camera {id}"), + backend: "v4l2", + formats: Vec::new(), + mirrored, + }; + let picks = camera_picks(&[camera("a", true)]); + assert_eq!((&*picks[0].1.name, &*picks[0].1.kind), ("Camera a", "camera")); + assert!(matches!( + &picks[0].0, + Pick::Source { kind: SourceKind::Camera { mirror: true, .. }, .. } + )); + assert_eq!(demo_camera_picks().len(), 1); + let sources = vec![ + CaptureSource { + id: SourceId::Monitor(0), + name: "DP-1".into(), + width: 2560, + height: 1440, + primary: true, + }, + CaptureSource { + id: SourceId::Monitor(1), + name: "HDMI-1".into(), + width: 1920, + height: 1080, + primary: false, + }, + CaptureSource { + id: SourceId::Window(9), + name: "Editor".into(), + width: 800, + height: 600, + primary: false, + }, + ]; + let screens = screen_picks("screen", sources.clone(), false); + assert_eq!(screens.iter().map(|p| &*p.1.name).collect::>(), ["DP-1", "HDMI-1"]); + assert_eq!(&*screens[0].1.detail, "2560×1440 · primary"); + let windows = screen_picks("window", sources, true); + assert_eq!( + windows.iter().map(|p| &*p.1.name).collect::>(), + ["Editor", "Test pattern"] + ); + // The desktop's own dialog alone is added at once. + let portal = CaptureSource { + id: SourceId::Portal, + name: "Portal".into(), + width: 0, + height: 0, + primary: false, + }; + let only = screen_picks("screen", vec![portal], false); + assert!(only_portal(&only)); + assert_eq!(&*only[0].1.name, "Choose with the system dialog"); + assert!(!only_portal(&screens)); + let source = picked_source(&only[0].0, (1920, 1080)).unwrap(); + assert_eq!((source.name.as_str(), source.id), ("Screen", 0)); + let tone = AudioSourceSetting::new(AudioSourceKindSetting::Synthetic { frequency: 440 }); + assert!(picked_source(&Pick::Audio(tone), (1920, 1080)).is_none()); + } + + #[test] + fn the_audio_picker_marks_what_is_mixed_in() { + let mic = AudioSourceSetting::new(AudioSourceKindSetting::Microphone); + let app = |name: &str, playing| AudioApp { + name: name.into(), + pid: None, + binary: Some(format!("{name}-bin")), + icon: None, + media: None, + streams: 1, + playing, + }; + let picks = audio_picks( + std::slice::from_ref(&mic), + vec![app("Music", true), app("Idle", false)], + false, + ); + let names: Vec<&str> = picks.iter().map(|p| &*p.1.name).collect(); + assert!( + names.starts_with(&["Microphone", "Desktop audio"]) + && names.ends_with(&["Music", "Idle"]) + ); + assert!(picks[0].1.selected && !picks[1].1.selected); + assert_eq!(&*picks[picks.len() - 2].1.detail, "playing"); + assert_eq!(&*picks[picks.len() - 1].1.detail, ""); + let demo = audio_picks(&[], vec![app("Ignored", true)], true); + assert_eq!(demo.iter().filter(|p| &*p.1.name == "Test tone").count(), 3); + assert!(demo.iter().all(|p| &*p.1.name != "Ignored")); + } + + #[test] + fn the_mixer_controls_change_the_sources() { + let mic = AudioSourceSetting::new(AudioSourceKindSetting::Microphone); + let desktop = AudioSourceSetting::new(AudioSourceKindSetting::Desktop); + let mut sources = vec![mic.clone()]; + toggle_audio(&mut sources, desktop.clone()); + assert_eq!(sources.len(), 2); + toggle_audio(&mut sources, mic); + assert_eq!(sources, [desktop]); + set_gain(&mut sources, 0, 0.25); + set_gain(&mut sources, 4, 9.0); + toggle_mute(&mut sources, 0); + toggle_mute(&mut sources, 4); + assert_eq!((sources[0].gain, sources[0].muted), (0.25, true)); + remove_audio(&mut sources, 3); + assert_eq!(sources.len(), 1); + remove_audio(&mut sources, 0); + assert!(sources.is_empty()); + // Rows: the meters' levels where the mixer has them, floored. + let sources = vec![ + AudioSourceSetting::new(AudioSourceKindSetting::Microphone), + AudioSourceSetting::new(AudioSourceKindSetting::Desktop), + ]; + let live = audio_live(&sources, &[], &[Some(-140.0), None]); + assert_eq!(live[0].as_ref().map(|l| l.level), Some(-100.0)); + assert!(live[1].is_none()); + assert_eq!(meter_ids(&sources, &[]), [None, None]); + } + + #[test] + fn the_settings_dialog_stores_what_it_can() { + let settings = Settings::in_memory(); + let ui = StudioUi::default(); + let form = settings_form(&settings, &ui); + let done = apply_settings_form(&settings, &ui, &form); + assert_eq!(done, SettingsApplied::default()); + let form = StudioSettingsForm { + replay_seconds: "30".into(), + replay_memory: "lots".into(), + recording_dir: " /tmp/rec ".into(), + preview_width: "640".into(), + preview_fps: "30".into(), + }; + let done = apply_settings_form(&settings, &ui, &form); + assert_eq!(done.notes, ["The replay memory is a whole number of MB."]); + assert_eq!(done.refused, None); + assert_eq!(done.ui.as_ref().map(|u| (u.preview_width, u.preview_fps)), Some((640, 30))); + assert_eq!(settings.get(&STUDIO_REPLAY_SECONDS), 30); + assert_eq!(settings.get(&STUDIO_RECORDING_DIR), "/tmp/rec"); + let again = settings_form(&settings, &done.ui.unwrap()); + assert_eq!((&*again.replay_seconds, &*again.preview_width), ("30", "640")); + } + + #[test] + fn the_live_scene_takes_a_new_source() { + let mut scenes = Scenes::default(); + add_to_live_scene(&mut scenes, Source::new(0, SourceKind::Pattern { size: (16, 16) })); + assert_eq!( + (scenes.scenes.len(), scenes.active().map(|s| s.name.as_str())), + (1, Some("Scene 1")) + ); + add_to_live_scene(&mut scenes, Source::new(0, SourceKind::Pattern { size: (16, 16) })); + let ids: Vec = scenes.active().unwrap().sources.iter().map(|s| s.id).collect(); + assert_eq!(ids, [1, 2]); + } + + #[test] + fn events_and_endings_have_words() { + let path = std::path::PathBuf::from("/tmp/x.mkv"); + assert_eq!( + event_message(&studio::Event::RecordingStarted { path: path.clone() }).as_deref(), + Some("Recording to /tmp/x.mkv") + ); + assert_eq!( + event_message(&studio::Event::ClipSaved { + path: path.clone(), + duration: std::time::Duration::from_secs(30) + }) + .as_deref(), + Some("Saved a clip of 30 seconds to /tmp/x.mkv") + ); + assert_eq!( + event_message(&studio::Event::RecordingStopped { + path, + duration: std::time::Duration::from_secs(61), + bytes: 2_500_000, + }) + .as_deref(), + Some("Saved a recording of 00:01:01 (2.5 MB) to /tmp/x.mkv") + ); + assert_eq!( + event_message(&studio::Event::Error { + context: "record".into(), + message: "disk full".into() + }) + .as_deref(), + Some("Stream Studio (record): disk full") + ); + assert_eq!(event_message(&studio::Event::State(Status::default())), None); + assert_eq!(ended_message(None), "The stream has ended"); + assert_eq!( + ended_message(Some(&EndReason::Failed("no route".into()))), + "The stream failed: no route" + ); + } + + #[test] + fn the_demo_studio_has_scenes_and_viewers() { + let (settings, problems) = demo_settings(); + assert!(problems.is_empty(), "{problems:?}"); + let scenes = settings.get(&STUDIO_SCENES); + assert_eq!(scenes.scenes.len(), 5); + assert_eq!(settings.get(&STREAM_AUDIO_SOURCES).len(), 3); + assert_eq!(settings.get(&STUDIO_UI).title, "Exploring the Lands Between"); + let viewers = demo_viewers(); + assert_eq!(viewers.iter().filter(|v| v.state == ViewerState::Connected).count(), 3); + let info = demo_stream(4, "Show".into(), true); + assert_eq!((info.id.as_str(), info.streamer, info.viewers), (DEMO_STREAM_ID, 4, Some(3))); + let message = demo_message(ChatTarget::Channel(2), "me".into(), Some(4), "hi".into(), 1234); + assert_eq!((message.author_uid.as_deref(), message.author_id), (Some("demo-4"), Some(4))); + assert_eq!(demo_stored(message).id, -1234); + } +} diff --git a/crates/voelin-ui/src/vm/studio.rs b/crates/voelin-ui-vm/src/studio/mod.rs similarity index 95% rename from crates/voelin-ui/src/vm/studio.rs rename to crates/voelin-ui-vm/src/studio/mod.rs index 1530bf0..2d7c1dd 100644 --- a/crates/voelin-ui/src/vm/studio.rs +++ b/crates/voelin-ui-vm/src/studio/mod.rs @@ -1,6 +1,9 @@ //! 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; @@ -11,7 +14,7 @@ use voelin_core::studio::scene::{ Align, Background, Colour, Crop, Fit, Scene, Scenes, Source, SourceKind, Transform, }; -use crate::app::{StudioAudio, StudioLayer, StudioScene, StudioSource, StudioSourceForm}; +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 { @@ -36,6 +39,7 @@ fn summary(scene: &Scene) -> String { 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", @@ -259,6 +263,7 @@ pub fn parse_colour(text: &str) -> Option { 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) @@ -356,7 +361,7 @@ fn transform(form: &StudioSourceForm) -> Result { width: parse_size(&form.width, "width")?, height: parse_size(&form.height, "height")?, scale, - fit: match form.fit.as_str() { + fit: match form.fit.as_ref() { "cover" => Fit::Cover, "stretch" => Fit::Stretch, _ => Fit::Contain, @@ -365,7 +370,7 @@ fn transform(form: &StudioSourceForm) -> Result { } fn background(form: &StudioSourceForm) -> Result { - Ok(match form.background.as_str() { + 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() } @@ -392,7 +397,7 @@ pub fn change(form: &StudioSourceForm, old: &Source) -> Result Result) -> Result { - Ok(match (form.kind.as_str(), old) { + Ok(match (form.kind.as_ref(), old) { ("text", old) => { let (font, backdrop, align, padding) = match old { Some(SourceKind::Text { font, backdrop, align, padding, .. }) => { @@ -454,7 +459,7 @@ pub fn new_source(form: &StudioSourceForm, output: (u32, u32)) -> Result, } +/// 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 { @@ -598,11 +606,11 @@ mod tests { 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"); + 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_str()).collect::>(), + sources.iter().map(|s| s.name.as_ref()).collect::>(), ["Camera", "Screen"] ); assert!(sources[0].front && !sources[0].back && sources[1].back); @@ -652,7 +660,7 @@ mod tests { 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_str(), rows[0].bitrate.as_str()), ("0.5", "800")); + 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)); } @@ -673,8 +681,8 @@ mod tests { ); 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_str(), f.width.as_str()), ("10", "300")); + 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; diff --git a/crates/voelin-ui-vm/src/studio_bridge.rs b/crates/voelin-ui-vm/src/studio_bridge.rs new file mode 100644 index 0000000..6daa15e --- /dev/null +++ b/crates/voelin-ui-vm/src/studio_bridge.rs @@ -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, + /// Its sources, front first: "Screen + Camera + Text". + pub detail: Arc, + /// Composited now (the live scene). + pub live: bool, + /// The kind of its front-most source (for the icon). + pub kind: Arc, +} + +/// A source of the live scene, front first. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct StudioSource { + pub id: i32, + pub name: Arc, + /// screen, window, portal, camera, image, text, colour, pattern + pub kind: Arc, + pub visible: bool, + pub locked: bool, + /// keep, blur, image, colour + pub background: Arc, + /// Why it shows nothing ("" while it works). + pub error: Arc, + /// "1920×1080 · 60 fps" + pub info: Arc, + /// 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, + /// "Elgato Wave:3", the application... + pub detail: Arc, + /// microphone, desktop, app, window, tone + pub kind: Arc, + pub gain_db: f32, + pub muted: bool, + /// The meter in dBFS, after the gain. + pub level: f32, + /// Why it captures nothing. + pub error: Arc, +} + +/// 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, + pub scale: Arc, + /// Frame-rate cap; empty: the output's. + pub fps: Arc, + /// kbit/s. + pub bitrate: Arc, + /// kbit/s a viewer needs for this layer. + pub min_bitrate: Arc, +} + +/// A viewer of the studio's stream. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct StudioViewer { + pub client: i32, + pub name: Arc, + /// requested, connecting, connected + pub state: Arc, +} + +/// An entry of a picker (screens, windows, cameras, audio sources). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct StudioPick { + pub name: Arc, + pub detail: Arc, + /// For the icon: monitor, window, portal, camera, microphone, desktop, app, tone + pub kind: Arc, + /// 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, + /// 0: not live, 1: poor, 2: fair, 3: good, 4: excellent. + pub quality: i32, + pub quality_text: Arc, + /// "1080p • 60 FPS • 8,250 kbps" + pub format: Arc, + /// The numbers behind it, for the info button. + pub details: Arc, + pub live: bool, + /// Going live: waiting for the server. + pub starting: bool, + /// "00:12:34" + pub elapsed: Arc, + pub viewers: i32, + pub participants: i32, + pub can_go_live: bool, + /// Why Go Live is off, or what goes wrong. + pub hint: Arc, + pub recording: bool, + pub recorded: Arc, + /// The replay buffer's window (0: off) and what it holds now. + pub replay_seconds: i32, + pub replay_held: Arc, + 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, + pub game: Arc, + pub message: Arc, + 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, +} + +/// 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, + pub kind: Arc, + pub x: Arc, + pub y: Arc, + /// Empty: the source's own size times `scale`. + pub width: Arc, + pub height: Arc, + pub scale: Arc, + /// contain, cover, stretch + pub fit: Arc, + pub crop_left: Arc, + pub crop_top: Arc, + pub crop_right: Arc, + pub crop_bottom: Arc, + /// Percent. + pub opacity: f32, + pub locked: bool, + pub visible: bool, + /// keep, blur, image, colour + pub background: Arc, + /// Blur radius in percent of the picture's height. + pub blur: Arc, + pub background_path: Arc, + pub background_colour: Arc, + /// Text, colour ("#rrggbb" or "#rrggbbaa") and image sources. + pub text: Arc, + pub text_size: Arc, + pub colour: Arc, + pub path: Arc, + pub mirror: bool, +} + +/// The studio settings dialog (`studio.*` keys and the preview). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct StudioSettingsForm { + pub replay_seconds: Arc, + pub replay_memory: Arc, + pub recording_dir: Arc, + pub preview_width: Arc, + pub preview_fps: Arc, +} diff --git a/crates/voelin-ui/src/vm/tree.rs b/crates/voelin-ui-vm/src/tree.rs similarity index 96% rename from crates/voelin-ui/src/vm/tree.rs rename to crates/voelin-ui-vm/src/tree.rs index 06f23e0..146a569 100644 --- a/crates/voelin-ui/src/vm/tree.rs +++ b/crates/voelin-ui-vm/src/tree.rs @@ -10,9 +10,10 @@ use voelin_model::{ tree_rows, }; -use crate::app::{BadgeItem, MemberItem, TreeItem}; +use crate::avatar; +use crate::bridge::{BadgeItem, MemberItem, TreeItem}; +use crate::image::ImageRef; use crate::settings::ClientPlaybackMap; -use crate::vm::avatar; /// A banner mode as the UI takes it (`TreeItem.banner-mode`). pub fn banner_mode(mode: BannerMode) -> i32 { @@ -24,12 +25,12 @@ pub fn banner_mode(mode: BannerMode) -> i32 { } /// The picture of a banner address, if the engine fetched it. -pub fn banner(pictures: &HashMap, url: Option<&str>) -> slint::Image { +pub fn banner(pictures: &HashMap, 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, guid: &str) -> slint::Image { +fn badge_icon(pictures: &HashMap, guid: &str) -> ImageRef { avatar::image(badges::icon_url(guid).and_then(|url| pictures.get(&url))) } @@ -79,19 +80,19 @@ pub struct TreeInput<'a> { } impl TreeInput<'_> { - fn avatar(&self, client: &ClientInfo) -> slint::Image { + 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 { + fn icon(&self, id: u32) -> Option { let path = self.icons.get(&id).filter(|_| id != 0)?; Some(avatar::image(Some(path))).filter(|i| i.size().width > 0) } /// The icons beside a client, as TeamSpeak shows them: its server /// groups' in display order, its channel group's, its own. - fn client_icons(&self, client: &ClientInfo) -> Vec { + fn client_icons(&self, client: &ClientInfo) -> Vec { let groups = self.groups.iter().filter(|g| client.server_groups.contains(&g.id)); let channel_group = self.channel_groups.iter().filter(|g| client.channel_group == Some(g.id)); @@ -105,7 +106,7 @@ impl TreeInput<'_> { /// The pictures of the badges a client shows that arrived, in its /// order; empty slots last. - fn badges(&self, client: &ClientInfo) -> [slint::Image; badges::SHOWN] { + fn badges(&self, client: &ClientInfo) -> [ImageRef; badges::SHOWN] { let mut icons = client .badges .iter() @@ -384,7 +385,7 @@ impl TreeInput<'_> { #[derive(Clone, Default)] struct Section { title: String, - icon: slint::Image, + icon: ImageRef, } /// Rows in sections: each section's first row carries the heading and how @@ -456,7 +457,7 @@ pub fn matching(rows: Vec, filter: &str) -> Vec { pub fn server_members(input: &TreeInput, voice_first: bool) -> Vec { let first = Section { title: if voice_first { "In Voice" } else { "Streaming" }.into(), - icon: slint::Image::default(), + icon: ImageRef::default(), }; let clients = input .presence @@ -596,7 +597,7 @@ mod tests { }; let (t, c, pb) = (HashSet::new(), HashSet::new(), ClientPlaybackMap::new()); let rows = rows(&input(&p, &t, &c, &pb, "", &e)); - let width = |i: &slint::Image| i.size().width; + let 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]; @@ -631,11 +632,11 @@ mod tests { pictures: HashMap::from([picture(0, 3), picture(2, 5), picture(3, 7)]), ..Default::default() }; - let width = |i: &slint::Image| i.size().width; + let width = |i: &ImageRef| i.size().width; let card = badge_items(&guids, &e.pictures); - let names: Vec<_> = card.iter().map(|b| b.name.as_str()).collect(); + 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_str(), guids[1]); + assert_eq!(card[1].description.as_ref(), guids[1]); assert_eq!(card.iter().map(|b| width(&b.icon)).collect::>(), [3, 0, 5]); let mut p = presence(); @@ -697,7 +698,7 @@ mod tests { 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_str(), chess.spacer), ("[cspacer1]Chess", 0)); + 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. @@ -737,12 +738,12 @@ mod tests { 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_str()).collect(); + 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!(&*rows[3].initials, "BO"); assert_eq!(stats(&p), "3 online · 3 channels"); } @@ -752,7 +753,7 @@ mod tests { 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_str()).collect(); + 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); @@ -766,7 +767,7 @@ mod tests { 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_str(), m.status.as_str())).collect(); + let names: Vec<_> = members.iter().map(|m| (m.name.as_ref(), m.status.as_ref())).collect(); assert_eq!(names, [("bob", "Listening"), ("Carol", "Away")]); } @@ -790,7 +791,7 @@ mod tests { 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_str(), m.group.as_str(), m.first_in_group)).collect(); + 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); } @@ -884,12 +885,14 @@ mod tests { ] ); let all = server_members(&input(&p, &t, &c, &pb, "", &e), false); - assert_eq!(all[1].role, "Moderator"); + 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); + assert!( + found[0].first_in_group && &*found[0].group == "Guest" && found[0].group_count == 1 + ); } #[test] diff --git a/crates/voelin-ui/Cargo.toml b/crates/voelin-ui/Cargo.toml index 9c32074..07041f2 100644 --- a/crates/voelin-ui/Cargo.toml +++ b/crates/voelin-ui/Cargo.toml @@ -24,8 +24,6 @@ dirs = "6" # avatars, icons and banners on TeamSpeak servers are GIF and WebP too (the # decoders are in the tree already, for SVG pictures). image = { version = "0.25", default-features = false, features = ["gif", "webp", "bmp", "ico"] } -# Twemoji archive blocks (raw deflate); already used by png. -miniz_oxide = "0.8" png = "0.18" serde = { version = "1", features = ["derive"] } # Settings and gateway values as JSON (the advanced and integrations pages). @@ -44,6 +42,7 @@ voelin-model = { workspace = true } voelin-platform = { path = "../voelin-platform", default-features = false } voelin-query = { path = "../voelin-query" } voelin-store = { path = "../voelin-store" } +voelin-ui-vm = { path = "../voelin-ui-vm" } tsclientlib = { path = "../proto/tsclientlib" } # Desktop: the keyring for passwords, stream media with libvpx, OpenH264, X11 diff --git a/crates/voelin-ui/assets/README.md b/crates/voelin-ui/assets/README.md index 0819924..7b0e831 100644 --- a/crates/voelin-ui/assets/README.md +++ b/crates/voelin-ui/assets/README.md @@ -1,11 +1,7 @@ # Bundled assets -- `twemoji.bin`: the Twemoji 15.0 SVGs (3720 emoji, from the `@twemoji/svg` - 15.0.0 package) packed by `scripts/pack-twemoji.py` into blocks of raw - deflate with an index; `src/emoji.rs` reads it. Twemoji graphics by Twitter, - Inc and other contributors, licensed under CC-BY 4.0 - (https://creativecommons.org/licenses/by/4.0/). The files are unchanged - apart from surrounding whitespace. +The Twemoji archive is with the code that reads it, in +`crates/voelin-ui-vm/assets/` (its license note is there). The fonts (Inter, SIL OFL 1.1) and icons (Lucide, ISC) that the Slint files import are under `ui/assets/`, each with its license. All three are credited diff --git a/crates/voelin-ui/src/app.rs b/crates/voelin-ui/src/app.rs index 70de12b..8d65c79 100644 --- a/crates/voelin-ui/src/app.rs +++ b/crates/voelin-ui/src/app.rs @@ -3,11 +3,12 @@ //! //! The screens' logic is elsewhere: servers and the channel tree in //! `servers.rs`, chat in `chat.rs`, streams in `streams.rs`, the settings -//! page in `settings_page.rs` and `appearance.rs`, the view models in `vm/`, -//! callbacks in `bind/`, development switches in `dev.rs`. +//! page in `settings_page.rs` and `appearance.rs`, the settings pages in +//! `settings_pages/`, the Stream Studio in `studio/`, the view models in the +//! `voelin-ui-vm` crate (`vm`), callbacks in `bind/`, development switches in +//! `dev.rs`. use std::cell::RefCell; -use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; use std::rc::Rc; use std::sync::Arc; @@ -22,22 +23,19 @@ use voelin_core::settings::{ AUDIO, CRASH_REPORTS, IDENTITY_IMPORT, STREAM_DECODER_BACKEND, STREAM_HARDWARE_DECODING, Settings, }; -use voelin_core::stream::StreamInfo; use voelin_core::{ - AudioSettings, BackendInfo, Command, Engine, Event, History, HistoryMessage, ObserveState, - SessionState, VoiceState, + AudioSettings, BackendInfo, Command, Engine, Event, History, ObserveState, VoiceState, }; -use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, GroupInfo, Presence}; +use voelin_model::ChatTarget; use voelin_platform::crash; use voelin_store::{Bookmark, MemorySecrets, Secrets, Store}; +use crate::bind::rows::Rows; use crate::hotkey::GlobalPtt; -use crate::settings::{ - CLIENT_PLAYBACK, ClientPlaybackMap, DeviceChoices, UI, UiSettings, appearance_keys, -}; +use crate::settings::{CLIENT_PLAYBACK, ClientPlaybackMap, UI, UiSettings, appearance_keys}; use crate::streams::{Share, Watch}; use crate::video::Video; -use crate::vm::chat::Previous; +use crate::vm; slint::include_modules!(); @@ -58,7 +56,7 @@ fn open_settings(dir: &Path, overrides: &[String]) -> Settings { for key in crate::settings::page_keys() { prefs.register(key); } - prefs.register(&crate::studio::STUDIO_UI); + prefs.register(&crate::vm::studio::logic::STUDIO_UI); let config = std::env::var_os("VOELIN_CONFIG") .map(PathBuf::from) .or_else(|| Some(dir.join("config.toml")).filter(|p| p.exists())); @@ -118,420 +116,72 @@ impl Secrets for FallbackSecrets { } } -/// A message of a chat with the handle the UI knows it by: the engine's -/// local ids are 64 bit, a Slint `int` is not. -pub(crate) struct Msg { - pub key: i32, - pub message: HistoryMessage, -} +/// The lines of a chat as the chat view shows them. +pub(crate) type ChatRows = Rows; -/// A chat of a session: its lines are the model the chat view shows while -/// the tab is selected, so a new message is one row appended. -pub(crate) struct Tab { - pub target: ChatTarget, - pub title: String, - pub lines: Rc>, - /// The messages, oldest first, by `(ts_ms, id)`. - pub messages: Vec, - /// Live messages of a session that keeps no history (no server unique - /// id yet): grouped from the message before, without ids. - pub last: Option, - /// 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)>, - 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, - /// 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, - pub pins_loaded: bool, - /// The gateway topics of this chat, and the open one with its messages. - pub topics: Vec, - pub topics_loaded: bool, - pub topic: Option, - pub topic_messages: Vec, - /// The message jumped to from the pins. - pub marked: Option, - /// What the lines of `messages` were built from. - pub cache: crate::vm::chat::LineCache, -} - -impl Tab { - pub fn new(target: ChatTarget, title: String) -> Self { - Self { - target, - title, - lines: Rc::new(VecModel::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(), - } - } - - /// 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 - } - - 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::vm::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::vm::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::vm::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) { - if let Some(&read) = reads.get(&crate::chat::store_target(&self.target).key()) { - self.read = self.read.max(Some(read)); - self.stored_read = Some(read); - } - } -} +/// A chat of a session (see `voelin_ui_vm::state`). +pub(crate) type Tab = vm::state::Tab; /// What we know about one server session. -pub(crate) struct SessionView { - pub state: SessionState, - pub capabilities: Capabilities, - pub presence: Arc, - pub collapsed: HashSet, - pub talking: HashSet, - pub tabs: Vec, - 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, - /// Clients whose stored volume was sent for this voice connection. - pub applied_playback: HashSet, - /// Avatar pictures in the engine's cache, by unique id - /// ([`Event::AvatarReady`]). - pub avatars: HashMap, - /// Icons in the engine's cache, by icon id ([`Event::IconReady`]). - pub icons: HashMap, - /// Banners and badges in the engine's cache, by address - /// ([`Event::PictureReady`]). - pub pictures: HashMap, - /// The server's icon id as its voice connection last told it - /// ([`Event::ServerDetails`]); kept while disconnected, for the rail. - pub server_icon: u32, - /// Bookmark address that supplied this session's icon. - pub icon_address: Option, - /// The server groups in display order ([`Event::Groups`]). - pub server_groups: Vec, - /// The channel groups ([`Event::Groups`]). - pub channel_groups: Vec, - /// What the session's gateway offers (`voelin_gateway_proto::feature`). - pub gateway_caps: Vec, - /// The client whose member card is open. - pub member_card: Option, - /// Passwords given for locked channels, until voice disconnects. - pub channel_passwords: HashMap, - /// The channel a voice connection was asked into, until it is joined - /// or joined again (`App::join_after_connect`). - pub join_after_connect: Option, - /// Viewers of the streams in the gateway's directory, by stream id. - pub stream_viewers: HashMap, - /// Downloads started from chat, by transfer id. - pub downloads: HashMap, - /// The next transfer id. - pub next_transfer: u64, - /// What the home, messages and events screens keep of the session. - pub extra: crate::social::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, - pub reads_of: Option, -} +pub(crate) type SessionView = vm::state::SessionView; -impl Default for SessionView { - 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 SessionView { - /// 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 { - 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::vm::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 { - let tab = self.tabs.remove(index); - if self.current_tab > index { - self.current_tab -= 1; - } else if self.current_tab == index { - let (strip, _) = crate::vm::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 - } - - /// A new tab for `target`, read as far as the store says. - pub fn new_tab(&self, target: ChatTarget, title: String) -> Tab { - let mut tab = Tab::new(target, title); - tab.read_from(&self.reads); - tab - } - - /// 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) -> slint::Image { - crate::vm::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) -> slint::Image { - if self.icon_address.as_deref() == Some(address) { - self.server_icon() - } else { - slint::Image::default() - } - } -} +/// What the screens share, apart from the window and the engine. +pub(crate) type AppState = vm::state::AppState; /// The models the Bridge shows, created once and updated row by row -/// (`vm::list::sync`). +/// ([`Rows::sync`]). pub(crate) struct Models { - pub servers: Rc>, - pub tree: Rc>, - pub members: Rc>, - pub server_members: Rc>, + pub servers: Rows, + pub tree: Rows, + pub members: Rows, + pub server_members: Rows, /// The chat strip: the current session's tabs without its private chats. - pub tabs: Rc>, + pub tabs: Rows, /// Which of the session's tabs each of `tabs` is ([`crate::vm::chat::strip`]). pub strip: RefCell>, - pub streams: Rc>, - pub viewers: Rc>, - pub pins: Rc>, - pub topics: Rc>, - pub topic_messages: Rc>, + pub streams: Rows, + pub viewers: Rows, + pub pins: Rows, + pub topics: Rows, + pub topic_messages: Rows, /// The quality choices of the watched stream. - pub qualities: Rc>, + pub qualities: Rows>, /// Shown when there is no chat. - pub no_chat: Rc>, + pub no_chat: Rows, /// Home, friends, messages, the bell, the search, events. pub social: crate::social::SocialModels, /// Settings pages. - pub layers: Rc>, - pub audio_sources: Rc>, - pub identities: Rc>, - pub gateway_config: Rc>, - pub gateway_perms: Rc>, - pub all_settings: Rc>, + pub layers: Rows, + pub audio_sources: Rows, + pub identities: Rows, + pub gateway_config: Rows, + pub gateway_perms: Rows, + pub all_settings: Rows, } impl Models { fn new(bridge: &Bridge) -> Self { let models = Self { - servers: Rc::default(), - tree: Rc::default(), - members: Rc::default(), - server_members: Rc::default(), - tabs: Rc::default(), + servers: Rows::default(), + tree: Rows::default(), + members: Rows::default(), + server_members: Rows::default(), + tabs: Rows::default(), strip: RefCell::new(vec![0]), - streams: Rc::default(), - viewers: Rc::default(), - pins: Rc::default(), - topics: Rc::default(), - topic_messages: Rc::default(), - qualities: Rc::default(), - no_chat: Rc::default(), + streams: Rows::default(), + viewers: Rows::default(), + pins: Rows::default(), + topics: Rows::default(), + topic_messages: Rows::default(), + qualities: Rows::default(), + no_chat: Rows::default(), social: crate::social::SocialModels::new(bridge), - layers: Rc::default(), - audio_sources: Rc::default(), - identities: Rc::default(), - gateway_config: Rc::default(), - gateway_perms: Rc::default(), - all_settings: Rc::default(), + layers: Rows::default(), + audio_sources: Rows::default(), + identities: Rows::default(), + gateway_config: Rows::default(), + gateway_perms: Rows::default(), + all_settings: Rows::default(), }; models.attach(bridge); models @@ -540,24 +190,24 @@ impl Models { /// Show the models in `bridge`: the main window's, and the viewer's own /// window's (its player reads the stream's qualities). pub(crate) fn attach(&self, bridge: &Bridge) { - bridge.set_servers(ModelRc::from(self.servers.clone())); - bridge.set_tree(ModelRc::from(self.tree.clone())); - bridge.set_members(ModelRc::from(self.members.clone())); - bridge.set_server_members(ModelRc::from(self.server_members.clone())); - bridge.set_tabs(ModelRc::from(self.tabs.clone())); - bridge.set_streams(ModelRc::from(self.streams.clone())); - bridge.set_share_viewers(ModelRc::from(self.viewers.clone())); - bridge.set_pins(ModelRc::from(self.pins.clone())); - bridge.set_topics(ModelRc::from(self.topics.clone())); - bridge.set_topic_messages(ModelRc::from(self.topic_messages.clone())); - bridge.set_viewer_qualities(ModelRc::from(self.qualities.clone())); - bridge.set_messages(ModelRc::from(self.no_chat.clone())); - bridge.set_layers(ModelRc::from(self.layers.clone())); - bridge.set_audio_sources(ModelRc::from(self.audio_sources.clone())); - bridge.set_identities(ModelRc::from(self.identities.clone())); - bridge.set_gateway_config(ModelRc::from(self.gateway_config.clone())); - bridge.set_gateway_perms(ModelRc::from(self.gateway_perms.clone())); - bridge.set_all_settings(ModelRc::from(self.all_settings.clone())); + bridge.set_servers(self.servers.model()); + bridge.set_tree(self.tree.model()); + bridge.set_members(self.members.model()); + bridge.set_server_members(self.server_members.model()); + bridge.set_tabs(self.tabs.model()); + bridge.set_streams(self.streams.model()); + bridge.set_share_viewers(self.viewers.model()); + bridge.set_pins(self.pins.model()); + bridge.set_topics(self.topics.model()); + bridge.set_topic_messages(self.topic_messages.model()); + bridge.set_viewer_qualities(self.qualities.model()); + bridge.set_messages(self.no_chat.model()); + bridge.set_layers(self.layers.model()); + bridge.set_audio_sources(self.audio_sources.model()); + bridge.set_identities(self.identities.model()); + bridge.set_gateway_config(self.gateway_config.model()); + bridge.set_gateway_perms(self.gateway_perms.model()); + bridge.set_all_settings(self.all_settings.model()); } } @@ -567,80 +217,33 @@ pub(crate) struct App { pub secrets: Box, pub engine: Engine, pub identity: tsclientlib::Identity, - pub bookmarks: Vec, - pub current: Option, - pub sessions: HashMap, + /// The data the screens share (`voelin_ui_vm::state`). + pub state: AppState, pub models: Models, - 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, - /// 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 settings service (shared with the engine); `settings`, `audio` - /// and `playback` are working copies of its keys. + /// The settings service (shared with the engine); `state.settings`, + /// `state.audio` and `state.playback` are working copies of its keys. pub prefs: Settings, - pub settings: UiSettings, - pub audio: AudioSettings, - /// Audio settings changed since they were last stored. - pub audio_dirty: bool, - pub inputs: DeviceChoices, - pub outputs: DeviceChoices, - pub playback: ClientPlaybackMap, - /// The engine's contacts, by unique id ([`Event::ContactsChanged`]). - pub contacts: HashMap, - /// The client in the volume dialog: session, client id, unique id. - pub playback_dialog: Option<(i64, u16, Option)>, - /// 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: winit 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 (`App::track_reading`). - pub reading: Option<(i64, ChatTarget)>, - pub mic_test: bool, pub ptt: GlobalPtt, pub video: Video, /// Our stream. pub share: Option, - /// The capture for a share is being started. - pub share_busy: bool, - pub share_error: String, /// The stream in the viewer. pub watch: Option, - /// 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, /// `VOELIN_DEMO_STREAM`: the viewer shows a local test stream. pub demo: bool, /// `VOELIN_DEMO_UI`: sample servers, channels and chat (dev.rs). pub demo_ui: bool, - /// Servers whose gateway was looked up in this run (`discover_gateway`). - pub gateways_looked_up: HashSet, /// `VOELIN_AUTOSHARE=test-pattern`: share the test pattern once streams work. pub autoshare: bool, /// `VOELIN_OPEN=client`: open the volume dialog of the first other client. pub open_client_pending: bool, /// The notices are in the About page's model. pub notices_loaded: bool, - /// 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, /// Home, friends, messages, the bell and the search. pub social: crate::social::Social, /// The settings pages of the new design. pub pages: crate::settings_pages::Pages, - /// The Stream Studio (studio.rs). + /// The Stream Studio (studio/). pub studio: crate::studio::StudioState, /// The stream's own window (popout.rs). pub popout: crate::popout::Popout, @@ -829,44 +432,18 @@ pub fn run(options: RunOptions) -> Result<()> { }), engine: engine.clone(), identity, - current: bookmarks.first().map(|b| b.id), - bookmarks, - sessions: HashMap::new(), + state: AppState::new(bookmarks, settings, audio, playback), models, - status: String::new(), - copy_note: None, - member_filter: String::new(), - topic_filter: String::new(), - voice_view: false, prefs, - 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, ptt, video, share: None, - share_busy: false, - share_error: String::new(), watch: None, - pending_watch: None, - stream_volume: 100.0, demo: switches.demo_stream, demo_ui: switches.demo_ui, - gateways_looked_up: HashSet::new(), autoshare: switches.autoshare, open_client_pending: switches.open_client, notices_loaded: false, - uploads: HashMap::new(), social: Default::default(), pages: Default::default(), studio: Default::default(), @@ -931,18 +508,18 @@ pub fn run(options: RunOptions) -> Result<()> { if let Err(e) = app.prefs.flush() { warn!(%e, "could not store settings"); } - let ids: Vec = app.sessions.keys().copied().collect(); + let ids: Vec = app.state.sessions.keys().copied().collect(); for id in ids { app.save_reads(id); } app.watch = None; app.share = None; if own && !app.demo_ui { - for id in app.sessions.keys() { + for id in app.state.sessions.keys() { app.engine.send(Command::CloseSession { session: *id as u64 }); } } - own && !app.sessions.is_empty() && !app.demo_ui + own && !app.state.sessions.is_empty() && !app.demo_ui }); APP.with(|a| a.borrow_mut().take()); if let Some(runtime) = own_runtime { @@ -1001,30 +578,30 @@ pub(crate) fn model(items: Vec) -> ModelRc { impl App { pub fn view_mut(&mut self) -> Option<&mut SessionView> { - let id = self.current?; - Some(self.sessions.entry(id).or_default()) + let id = self.state.current?; + Some(self.state.sessions.entry(id).or_default()) } pub fn view(&self) -> Option<&SessionView> { - self.current.and_then(|id| self.sessions.get(&id)) + self.state.current.and_then(|id| self.state.sessions.get(&id)) } pub fn bookmark(&self, id: i64) -> Option<&Bookmark> { - self.bookmarks.iter().find(|b| b.id == id) + self.state.bookmarks.iter().find(|b| b.id == id) } /// Send a command for the current session. Not for the sample /// sessions of VOELIN_DEMO_UI: the engine would open them for real. pub fn command(&self, f: impl FnOnce(u64) -> Command) { - if let Some(id) = self.current.filter(|_| !self.demo_ui) { + if let Some(id) = self.state.current.filter(|_| !self.demo_ui) { self.engine.send(f(id as u64)); } } pub fn set_status(&mut self, text: impl Into) { - self.status = text.into(); + self.state.status = text.into(); if let Some(ui) = self.ui.upgrade() { - ui.global::().set_status_text(self.status.clone().into()); + ui.global::().set_status_text(self.state.status.clone().into()); } } @@ -1037,12 +614,12 @@ impl App { /// Nav.copy put text on the clipboard: one toast says so. pub fn copied(&mut self) { - let text = self.copy_note.take().unwrap_or_else(|| "Copied".to_owned()); + let text = self.state.copy_note.take().unwrap_or_else(|| "Copied".to_owned()); self.set_status(text); } pub fn store_settings(&self) { - if let Err(e) = self.prefs.set(&UI, self.settings.clone()) { + if let Err(e) = self.prefs.set(&UI, self.state.settings.clone()) { warn!(%e, "could not store settings"); } } @@ -1051,19 +628,19 @@ impl App { /// the values the window keeps copies of. The engine applies audio /// settings itself. fn setting_changed(&mut self, key: &str) { - if key == AUDIO.name() && !self.audio_dirty { - self.audio = self.prefs.get(&AUDIO); + if key == AUDIO.name() && !self.state.audio_dirty { + self.state.audio = self.prefs.get(&AUDIO); // The voice controls follow the transmit mode. self.refresh_transmit(); } else if key == CRASH_REPORTS.name() { let enabled = self.prefs.get(&CRASH_REPORTS); - if enabled != self.settings.crash_reports { - self.settings.crash_reports = enabled; + if enabled != self.state.settings.crash_reports { + self.state.settings.crash_reports = enabled; crash::set_enabled(enabled); self.refresh_settings_flags(); } } else if key == CLIENT_PLAYBACK.name() { - self.playback = self.prefs.get(&CLIENT_PLAYBACK); + self.state.playback = self.prefs.get(&CLIENT_PLAYBACK); } else if appearance_keys().iter().any(|k| k.name() == key) { self.apply_appearance(); } else if key == voelin_core::settings::STREAM_AUDIO_SOURCES.name() { @@ -1085,7 +662,7 @@ impl App { match event { Event::State { session, state } => { let id = session as i64; - let view = self.sessions.entry(id).or_default(); + let view = self.state.sessions.entry(id).or_default(); let was_voice = view.state.voice; let was_observe = view.state.observe; let was_channel = view.state.own_channel; @@ -1111,12 +688,12 @@ impl App { if off(state.voice, state.observe) && !off(was_voice, was_observe) { self.save_reads(id); } - let view = self.sessions.entry(id).or_default(); + let view = self.state.sessions.entry(id).or_default(); let focus = !view.focused_own_channel; if state.voice == VoiceState::Connected && was_voice != VoiceState::Connected { self.set_status("Connected"); } - if self.current == Some(id) { + if self.state.current == Some(id) { if self.track_reading() { self.refresh_chat(); } @@ -1124,7 +701,7 @@ impl App { // once per connection. if let (Some(cid), VoiceState::Connected) = (state.own_channel, state.voice) { self.open_chat(ChatTarget::Channel(cid), focus); - self.sessions.entry(id).or_default().focused_own_channel = true; + self.state.sessions.entry(id).or_default().focused_own_channel = true; } } // Where we are with voice, when it changed here: home's last @@ -1138,22 +715,22 @@ impl App { self.refresh_tree(); self.refresh_streams(); self.autoshare(); - if self.open_client_pending && self.current == Some(id) { + if self.open_client_pending && self.state.current == Some(id) { self.open_first_client(); } self.join_after_connect(id); } Event::ServerInfo { session, name, backend, capabilities } => { - self.sessions.entry(session as i64).or_default().capabilities = capabilities; + self.state.sessions.entry(session as i64).or_default().capabilities = capabilities; self.adopt_server_name(session as i64, &name); - if self.current == Some(session as i64) { + if self.state.current == Some(session as i64) { self.set_status(connected_status(&name, &backend)); } self.refresh_streams(); self.autoshare(); } Event::Presence { session, presence } => { - let view = self.sessions.entry(session as i64).or_default(); + let view = self.state.sessions.entry(session as i64).or_default(); // The server chat shows its welcome and host message, with // their pictures. let said = crate::chat::server_texts(&view.presence.server) @@ -1171,7 +748,7 @@ impl App { if renamed && self.remember_voice(session as i64) { self.refresh_servers(); } - if self.current == Some(session as i64) { + if self.state.current == Some(session as i64) { if said { self.fetch_previews(session as i64); } @@ -1185,20 +762,20 @@ impl App { } } Event::Talking { session, client, talking } => { - let view = self.sessions.entry(session as i64).or_default(); + let view = self.state.sessions.entry(session as i64).or_default(); if talking { view.talking.insert(client); } else { view.talking.remove(&client); } - if self.current == Some(session as i64) { + if self.state.current == Some(session as i64) { self.refresh_tree(); } } Event::InputLevel { session, level_db, sending } => { let shown = match session { - Some(s) => self.current == Some(s as i64), - None => self.mic_test, + Some(s) => self.state.current == Some(s as i64), + None => self.state.mic_test, }; if shown && let Some(ui) = self.ui.upgrade() { let bridge = ui.global::(); @@ -1213,7 +790,7 @@ impl App { // know the server yet): those get ids and reactions instead. Event::Chat { session, message } => { let id = session as i64; - if !self.sessions.entry(id).or_default().has_history() { + if !self.state.sessions.entry(id).or_default().has_history() { self.add_message(id, message); } } @@ -1228,12 +805,12 @@ impl App { self.gateway_update(session as i64, update); } Event::Groups { session, server_groups, channel_groups } => { - let view = self.sessions.entry(session as i64).or_default(); + let view = self.state.sessions.entry(session as i64).or_default(); view.server_groups = (*server_groups).clone(); // Display order, as TeamSpeak sorts them. view.server_groups.sort_by_key(|g| (g.sort_id, g.id)); view.channel_groups = (*channel_groups).clone(); - if self.current == Some(session as i64) { + if self.state.current == Some(session as i64) { self.refresh_tree(); } } @@ -1244,11 +821,11 @@ impl App { } // Pictures can arrive after the rows were built: draw them again. Event::AvatarReady { session, client_uid, path, .. } => { - let view = self.sessions.entry(session as i64).or_default(); + let view = self.state.sessions.entry(session as i64).or_default(); // A file that arrives again is decoded again if it changed. crate::images::reloaded(&path); view.avatars.insert(client_uid, path); - if self.current == Some(session as i64) { + if self.state.current == Some(session as i64) { self.refresh_tree(); self.refresh_chat(); self.refresh_toolbar(); @@ -1257,21 +834,21 @@ impl App { } } Event::IconReady { session, icon, path } => { - let view = self.sessions.entry(session as i64).or_default(); + let view = self.state.sessions.entry(session as i64).or_default(); crate::images::reloaded(&path); view.icons.insert(icon, path); self.refresh_servers(); - if self.current == Some(session as i64) { + if self.state.current == Some(session as i64) { self.refresh_tree(); self.refresh_toolbar(); } } Event::PictureReady { session, url, path } => { - let view = self.sessions.entry(session as i64).or_default(); + let view = self.state.sessions.entry(session as i64).or_default(); // The host banner reloads into the same file. crate::images::reloaded(&path); view.pictures.insert(url, path); - if self.current == Some(session as i64) { + if self.state.current == Some(session as i64) { self.refresh_toolbar(); self.refresh_tree(); self.refresh_chat(); @@ -1282,9 +859,9 @@ impl App { self.transfer_progress(session as i64, transfer, state); } // The engine's contacts would replace the sample ones. - Event::ContactsChanged { .. } if self.demo_ui && !self.contacts.is_empty() => {} + Event::ContactsChanged { .. } if self.demo_ui && !self.state.contacts.is_empty() => {} Event::ContactsChanged { contacts } => { - self.contacts = contacts.iter().map(|c| (c.uid.clone(), c.clone())).collect(); + self.state.contacts = contacts.iter().map(|c| (c.uid.clone(), c.clone())).collect(); self.refresh_member_card(); } // The sample sessions of VOELIN_DEMO_UI are unknown to the engine. @@ -1297,7 +874,7 @@ impl App { Event::SettingRejected { key, message } => { self.set_status(format!("Setting {key}: {message}")); } - // The Stream Studio's stream (studio.rs). + // The Stream Studio's stream (studio/). Event::StreamState { session, state } if self.studio_streams_to(session as i64) => { self.studio_stream_state(state); } @@ -1312,7 +889,7 @@ impl App { fn tick(&mut self) { self.tick_streams(); self.tick_pages(); - if self.audio_dirty { + if self.state.audio_dirty { self.save_audio(); } } diff --git a/crates/voelin-ui/src/appearance.rs b/crates/voelin-ui/src/appearance.rs index 310e4aa..478d7c5 100644 --- a/crates/voelin-ui/src/appearance.rs +++ b/crates/voelin-ui/src/appearance.rs @@ -6,12 +6,13 @@ use slint::ComponentHandle; use tracing::warn; -use crate::app::{App, AppearanceForm, Bridge, Nav, Theme}; +use crate::app::{App, Bridge, Nav, Theme}; use crate::images; use crate::settings::{ ThemeChoice, UI_FONT_SCALE, UI_IMAGE_CACHE_MB, UI_MEMBERS_WIDTH, UI_NARROW_BREAKPOINT, UI_THEME, UI_VOICE_COMPACT, }; +use crate::vm::bridge::AppearanceForm; impl App { /// Show the current values of the appearance keys. @@ -33,12 +34,15 @@ impl App { } nav.set_voice_compact(self.prefs.get(&UI_VOICE_COMPACT)); let bridge = ui.global::(); - bridge.set_appearance(AppearanceForm { - theme: theme.as_str().into(), - font_scale: scale, - narrow_breakpoint: breakpoint as f32, - image_cache_mb: cache_mb as f32, - }); + bridge.set_appearance( + AppearanceForm { + theme: theme.as_str().into(), + font_scale: scale, + narrow_breakpoint: breakpoint as f32, + image_cache_mb: cache_mb as f32, + } + .into(), + ); bridge.set_image_cache_usage(images::usage_text().into()); self.theme_windows(); } diff --git a/crates/voelin-ui/src/bind/convert.rs b/crates/voelin-ui/src/bind/convert.rs new file mode 100644 index 0000000..3cddcbb --- /dev/null +++ b/crates/voelin-ui/src/bind/convert.rs @@ -0,0 +1,73 @@ +//! Plain view-model values (`voelin-ui-vm`) to Slint values, and back where +//! that can be done. Temporary, like the Slint front end itself: the rows +//! (`items`) are converted when [`super::rows::Rows`] applies a change, so +//! only changed rows pay for it. + +use std::rc::Rc; +use std::sync::Arc; + +use slint::{Color, Image, ModelRc, Rgba8Pixel, SharedPixelBuffer, SharedString, VecModel}; +use voelin_ui_vm::{ImageRef, ImageSource, Rgb}; + +mod items; + +/// An opaque colour. +pub(crate) fn color(c: Rgb) -> Color { + Color::from_rgb_u8(c.r(), c.g(), c.b()) +} + +/// A colour that may be absent: transparent is the text's own colour. +pub(crate) fn ink(c: Option) -> Color { + c.map(color).unwrap_or_default() +} + +/// The opaque colour of a Slint colour (its transparency is dropped). +pub(crate) fn unrgb(c: Color) -> Rgb { + Rgb::new(c.red(), c.green(), c.blue()) +} + +/// The colour of a Slint colour, none for a transparent one. +pub(crate) fn unink(c: Color) -> Option { + (c.alpha() > 0).then(|| unrgb(c)) +} + +/// A picture as Slint shows it: files and downloaded pictures through the +/// decoded-picture cache (`images.rs`), pixels as they are. +pub(crate) fn image(picture: &ImageRef) -> Image { + match &**picture { + ImageSource::None => Image::default(), + ImageSource::File { path, .. } => crate::images::file(path), + ImageSource::Rgba { w, h, bytes } => { + Image::from_rgba8(SharedPixelBuffer::::clone_from_slice(bytes, *w, *h)) + } + ImageSource::Svg(data) => Image::load_from_svg_data(data).unwrap_or_default(), + ImageSource::Memory { key, bytes } => crate::images::picture(key, bytes), + } +} + +/// A model of pictures. +pub(crate) fn images(pictures: &[ImageRef]) -> ModelRc { + ModelRc::from(Rc::new(VecModel::from(pictures.iter().map(image).collect::>()))) +} + +/// A model of strings. +pub(crate) fn strings(texts: &[Arc]) -> ModelRc { + ModelRc::from(Rc::new(VecModel::from( + texts.iter().map(|t| SharedString::from(&**t)).collect::>(), + ))) +} + +/// The strings of a model. +pub(crate) fn unstrings(model: &ModelRc) -> Vec> { + slint::Model::iter(model).map(|t| Arc::from(t.as_str())).collect() +} + +/// A model of the Slint rows the plain rows convert to. +pub(crate) fn model From<&'a V> + Clone + 'static>(rows: &[V]) -> ModelRc { + ModelRc::from(Rc::new(VecModel::from(rows.iter().map(S::from).collect::>()))) +} + +/// The plain rows of a model. +pub(crate) fn rows>(model: &ModelRc) -> Vec { + slint::Model::iter(model).map(V::from).collect() +} diff --git a/crates/voelin-ui/src/bind/convert/items.rs b/crates/voelin-ui/src/bind/convert/items.rs new file mode 100644 index 0000000..f0dc0c2 --- /dev/null +++ b/crates/voelin-ui/src/bind/convert/items.rs @@ -0,0 +1,2419 @@ +//! The conversions of every bridge struct: plain to Slint for all of them, +//! Slint to plain for those without pictures (a picture cannot be turned back +//! into its source). Each struct lists all its fields, so a field added on one +//! side only does not compile. + +use std::sync::Arc; + +use slint::SharedString; +use voelin_ui_vm::bridge as vm; +use voelin_ui_vm::studio_bridge as studio; + +use super::{color, image, images, ink, model, rows, strings, unink, unstrings}; +use crate::app::*; +use crate::bind::rows::Row; + +impl From<&vm::ServerItem> for ServerItem { + fn from(v: &vm::ServerItem) -> Self { + Self { + id: v.id, + name: SharedString::from(&*v.name), + address: SharedString::from(&*v.address), + status: SharedString::from(&*v.status), + initials: SharedString::from(&*v.initials), + tint: color(v.tint), + icon: image(&v.icon), + unread: v.unread, + live: v.live, + detail: SharedString::from(&*v.detail), + product: SharedString::from(&*v.product), + gateway: v.gateway, + } + } +} + +impl From for ServerItem { + fn from(v: vm::ServerItem) -> Self { + Self::from(&v) + } +} + +impl Row for vm::ServerItem { + type Shown = ServerItem; + + fn show(&self) -> ServerItem { + ServerItem::from(self) + } +} + +impl From<&vm::TreeItem> for TreeItem { + fn from(v: &vm::TreeItem) -> Self { + Self { + is_channel: v.is_channel, + spacer: v.spacer, + depth: v.depth, + id: v.id, + name: SharedString::from(&*v.name), + own: v.own, + talking: v.talking, + muted: v.muted, + sound_off: v.sound_off, + away: v.away, + streaming: v.streaming, + locked: v.locked, + collapsed: v.collapsed, + local_muted: v.local_muted, + local_volume: v.local_volume, + myself: v.myself, + initials: SharedString::from(&*v.initials), + tint: color(v.tint), + avatar: image(&v.avatar), + members: v.members, + max_members: v.max_members, + icon: image(&v.icon), + icon_2: image(&v.icon_2), + icon_3: image(&v.icon_3), + badge: image(&v.badge), + badge_2: image(&v.badge_2), + badge_3: image(&v.badge_3), + banner: image(&v.banner), + banner_mode: v.banner_mode, + } + } +} + +impl From for TreeItem { + fn from(v: vm::TreeItem) -> Self { + Self::from(&v) + } +} + +impl Row for vm::TreeItem { + type Shown = TreeItem; + + fn show(&self) -> TreeItem { + TreeItem::from(self) + } +} + +impl From<&vm::MemberItem> for MemberItem { + fn from(v: &vm::MemberItem) -> Self { + Self { + id: v.id, + name: SharedString::from(&*v.name), + initials: SharedString::from(&*v.initials), + tint: color(v.tint), + avatar: image(&v.avatar), + talking: v.talking, + muted: v.muted, + sound_off: v.sound_off, + away: v.away, + streaming: v.streaming, + myself: v.myself, + status: SharedString::from(&*v.status), + away_message: SharedString::from(&*v.away_message), + group: SharedString::from(&*v.group), + group_icon: image(&v.group_icon), + first_in_group: v.first_in_group, + group_count: v.group_count, + admin: v.admin, + role: SharedString::from(&*v.role), + priority: v.priority, + commander: v.commander, + recording: v.recording, + cannot_talk: v.cannot_talk, + badge: image(&v.badge), + badge_2: image(&v.badge_2), + badge_3: image(&v.badge_3), + } + } +} + +impl From for MemberItem { + fn from(v: vm::MemberItem) -> Self { + Self::from(&v) + } +} + +impl Row for vm::MemberItem { + type Shown = MemberItem; + + fn show(&self) -> MemberItem { + MemberItem::from(self) + } +} + +impl From<&vm::BadgeItem> for BadgeItem { + fn from(v: &vm::BadgeItem) -> Self { + Self { + name: SharedString::from(&*v.name), + description: SharedString::from(&*v.description), + icon: image(&v.icon), + } + } +} + +impl From for BadgeItem { + fn from(v: vm::BadgeItem) -> Self { + Self::from(&v) + } +} + +impl Row for vm::BadgeItem { + type Shown = BadgeItem; + + fn show(&self) -> BadgeItem { + BadgeItem::from(self) + } +} + +impl From<&vm::MemberCard> for MemberCard { + fn from(v: &vm::MemberCard) -> Self { + Self { + open: v.open, + id: v.id, + name: SharedString::from(&*v.name), + initials: SharedString::from(&*v.initials), + tint: color(v.tint), + avatar: image(&v.avatar), + status: SharedString::from(&*v.status), + description: SharedString::from(&*v.description), + groups: strings(&v.groups), + badges: model(&v.badges), + country: SharedString::from(&*v.country), + talk_power: v.talk_power, + friend: v.friend, + blocked: v.blocked, + volume: v.volume, + muted: v.muted, + known: v.known, + streaming: v.streaming, + } + } +} + +impl From for MemberCard { + fn from(v: vm::MemberCard) -> Self { + Self::from(&v) + } +} + +impl Row for vm::MemberCard { + type Shown = MemberCard; + + fn show(&self) -> MemberCard { + MemberCard::from(self) + } +} + +impl From<&vm::ChatTab> for ChatTab { + fn from(v: &vm::ChatTab) -> Self { + Self { + title: SharedString::from(&*v.title), + name: SharedString::from(&*v.name), + kind: v.kind, + id: v.id, + unread: v.unread, + topic: SharedString::from(&*v.topic), + last: SharedString::from(&*v.last), + time: SharedString::from(&*v.time), + banner: image(&v.banner), + banner_mode: v.banner_mode, + } + } +} + +impl From for ChatTab { + fn from(v: vm::ChatTab) -> Self { + Self::from(&v) + } +} + +impl Row for vm::ChatTab { + type Shown = ChatTab; + + fn show(&self) -> ChatTab { + ChatTab::from(self) + } +} + +impl From<&vm::TextRun> for TextRun { + fn from(v: &vm::TextRun) -> Self { + Self { + text: SharedString::from(&*v.text), + emoji: SharedString::from(&*v.emoji), + bold: v.bold, + italic: v.italic, + underline: v.underline, + strike: v.strike, + code: v.code, + ink_dark: ink(v.ink_dark), + ink_light: ink(v.ink_light), + link: SharedString::from(&*v.link), + masked: v.masked, + } + } +} + +impl From for TextRun { + fn from(v: vm::TextRun) -> Self { + Self::from(&v) + } +} + +impl Row for vm::TextRun { + type Shown = TextRun; + + fn show(&self) -> TextRun { + TextRun::from(self) + } +} + +impl From for vm::TextRun { + fn from(v: TextRun) -> Self { + Self { + text: Arc::from(v.text.as_str()), + emoji: Arc::from(v.emoji.as_str()), + bold: v.bold, + italic: v.italic, + underline: v.underline, + strike: v.strike, + code: v.code, + ink_dark: unink(v.ink_dark), + ink_light: unink(v.ink_light), + link: Arc::from(v.link.as_str()), + masked: v.masked, + } + } +} + +impl From<&vm::TextBlock> for TextBlock { + fn from(v: &vm::TextBlock) -> Self { + Self { runs: model(&v.runs), kind: v.kind, caption: SharedString::from(&*v.caption) } + } +} + +impl From for TextBlock { + fn from(v: vm::TextBlock) -> Self { + Self::from(&v) + } +} + +impl Row for vm::TextBlock { + type Shown = TextBlock; + + fn show(&self) -> TextBlock { + TextBlock::from(self) + } +} + +impl From for vm::TextBlock { + fn from(v: TextBlock) -> Self { + Self { runs: rows(&v.runs), kind: v.kind, caption: Arc::from(v.caption.as_str()) } + } +} + +impl From<&vm::ReactionItem> for ReactionItem { + fn from(v: &vm::ReactionItem) -> Self { + Self { + key: SharedString::from(&*v.key), + text: SharedString::from(&*v.text), + count: v.count, + me: v.me, + } + } +} + +impl From for ReactionItem { + fn from(v: vm::ReactionItem) -> Self { + Self::from(&v) + } +} + +impl Row for vm::ReactionItem { + type Shown = ReactionItem; + + fn show(&self) -> ReactionItem { + ReactionItem::from(self) + } +} + +impl From for vm::ReactionItem { + fn from(v: ReactionItem) -> Self { + Self { + key: Arc::from(v.key.as_str()), + text: Arc::from(v.text.as_str()), + count: v.count, + me: v.me, + } + } +} + +impl From<&vm::FileItem> for FileItem { + fn from(v: &vm::FileItem) -> Self { + Self { + name: SharedString::from(&*v.name), + detail: SharedString::from(&*v.detail), + index: v.index, + state: SharedString::from(&*v.state), + progress: v.progress, + picture: v.picture, + preview: image(&v.preview), + } + } +} + +impl From for FileItem { + fn from(v: vm::FileItem) -> Self { + Self::from(&v) + } +} + +impl Row for vm::FileItem { + type Shown = FileItem; + + fn show(&self) -> FileItem { + FileItem::from(self) + } +} + +impl From<&vm::ChatLine> for ChatLine { + fn from(v: &vm::ChatLine) -> Self { + Self { + key: v.key, + author: SharedString::from(&*v.author), + text: SharedString::from(&*v.text), + time: SharedString::from(&*v.time), + blocks: model(&v.blocks), + rich: v.rich, + jumbo: v.jumbo, + continued: v.continued, + initials: SharedString::from(&*v.initials), + tint: color(v.tint), + avatar: image(&v.avatar), + blocked: v.blocked, + pinned: v.pinned, + reactions: model(&v.reactions), + files: model(&v.files), + remote: v.remote, + topic: SharedString::from(&*v.topic), + marked: v.marked, + link: SharedString::from(&*v.link), + unread_start: v.unread_start, + } + } +} + +impl From for ChatLine { + fn from(v: vm::ChatLine) -> Self { + Self::from(&v) + } +} + +impl Row for vm::ChatLine { + type Shown = ChatLine; + + fn show(&self) -> ChatLine { + ChatLine::from(self) + } +} + +impl From<&vm::PinItem> for PinItem { + fn from(v: &vm::PinItem) -> Self { + Self { line: (&v.line).into(), by: SharedString::from(&*v.by) } + } +} + +impl From for PinItem { + fn from(v: vm::PinItem) -> Self { + Self::from(&v) + } +} + +impl Row for vm::PinItem { + type Shown = PinItem; + + fn show(&self) -> PinItem { + PinItem::from(self) + } +} + +impl From<&vm::TopicItem> for TopicItem { + fn from(v: &vm::TopicItem) -> Self { + Self { + id: v.id, + title: SharedString::from(&*v.title), + creator: SharedString::from(&*v.creator), + detail: SharedString::from(&*v.detail), + activity: SharedString::from(&*v.activity), + recent: v.recent, + archived: v.archived, + } + } +} + +impl From for TopicItem { + fn from(v: vm::TopicItem) -> Self { + Self::from(&v) + } +} + +impl Row for vm::TopicItem { + type Shown = TopicItem; + + fn show(&self) -> TopicItem { + TopicItem::from(self) + } +} + +impl From for vm::TopicItem { + fn from(v: TopicItem) -> Self { + Self { + id: v.id, + title: Arc::from(v.title.as_str()), + creator: Arc::from(v.creator.as_str()), + detail: Arc::from(v.detail.as_str()), + activity: Arc::from(v.activity.as_str()), + recent: v.recent, + archived: v.archived, + } + } +} + +impl From<&vm::BookmarkForm> for BookmarkForm { + fn from(v: &vm::BookmarkForm) -> Self { + Self { + id: v.id, + name: SharedString::from(&*v.name), + address: SharedString::from(&*v.address), + nickname: SharedString::from(&*v.nickname), + server_password: SharedString::from(&*v.server_password), + connected: v.connected, + channel: SharedString::from(&*v.channel), + channel_password: SharedString::from(&*v.channel_password), + token: SharedString::from(&*v.token), + } + } +} + +impl From for BookmarkForm { + fn from(v: vm::BookmarkForm) -> Self { + Self::from(&v) + } +} + +impl Row for vm::BookmarkForm { + type Shown = BookmarkForm; + + fn show(&self) -> BookmarkForm { + BookmarkForm::from(self) + } +} + +impl From for vm::BookmarkForm { + fn from(v: BookmarkForm) -> Self { + Self { + id: v.id, + name: Arc::from(v.name.as_str()), + address: Arc::from(v.address.as_str()), + nickname: Arc::from(v.nickname.as_str()), + server_password: Arc::from(v.server_password.as_str()), + connected: v.connected, + channel: Arc::from(v.channel.as_str()), + channel_password: Arc::from(v.channel_password.as_str()), + token: Arc::from(v.token.as_str()), + } + } +} + +impl From<&vm::StreamItem> for StreamItem { + fn from(v: &vm::StreamItem) -> Self { + Self { + id: SharedString::from(&*v.id), + name: SharedString::from(&*v.name), + streamer: SharedString::from(&*v.streamer), + channel: SharedString::from(&*v.channel), + streamer_id: v.streamer_id, + initials: SharedString::from(&*v.initials), + tint: color(v.tint), + avatar: image(&v.avatar), + viewers: v.viewers, + audio: v.audio, + kind: SharedString::from(&*v.kind), + bitrate: SharedString::from(&*v.bitrate), + watching: v.watching, + own: v.own, + studio: v.studio, + } + } +} + +impl From for StreamItem { + fn from(v: vm::StreamItem) -> Self { + Self::from(&v) + } +} + +impl Row for vm::StreamItem { + type Shown = StreamItem; + + fn show(&self) -> StreamItem { + StreamItem::from(self) + } +} + +impl From<&vm::ViewerItem> for ViewerItem { + fn from(v: &vm::ViewerItem) -> Self { + Self { + client: v.client, + name: SharedString::from(&*v.name), + state: SharedString::from(&*v.state), + message: SharedString::from(&*v.message), + avatar: image(&v.avatar), + } + } +} + +impl From for ViewerItem { + fn from(v: vm::ViewerItem) -> Self { + Self::from(&v) + } +} + +impl Row for vm::ViewerItem { + type Shown = ViewerItem; + + fn show(&self) -> ViewerItem { + ViewerItem::from(self) + } +} + +impl From<&vm::SourceItem> for SourceItem { + fn from(v: &vm::SourceItem) -> Self { + Self { name: SharedString::from(&*v.name), detail: SharedString::from(&*v.detail) } + } +} + +impl From for SourceItem { + fn from(v: vm::SourceItem) -> Self { + Self::from(&v) + } +} + +impl Row for vm::SourceItem { + type Shown = SourceItem; + + fn show(&self) -> SourceItem { + SourceItem::from(self) + } +} + +impl From for vm::SourceItem { + fn from(v: SourceItem) -> Self { + Self { name: Arc::from(v.name.as_str()), detail: Arc::from(v.detail.as_str()) } + } +} + +impl From<&vm::ShareForm> for ShareForm { + fn from(v: &vm::ShareForm) -> Self { + Self { + source: v.source, + name: SharedString::from(&*v.name), + fps_index: v.fps_index, + fps: SharedString::from(&*v.fps), + bitrate_index: v.bitrate_index, + bitrate: SharedString::from(&*v.bitrate), + audio: v.audio, + auto_accept: v.auto_accept, + } + } +} + +impl From for ShareForm { + fn from(v: vm::ShareForm) -> Self { + Self::from(&v) + } +} + +impl Row for vm::ShareForm { + type Shown = ShareForm; + + fn show(&self) -> ShareForm { + ShareForm::from(self) + } +} + +impl From for vm::ShareForm { + fn from(v: ShareForm) -> Self { + Self { + source: v.source, + name: Arc::from(v.name.as_str()), + fps_index: v.fps_index, + fps: Arc::from(v.fps.as_str()), + bitrate_index: v.bitrate_index, + bitrate: Arc::from(v.bitrate.as_str()), + audio: v.audio, + auto_accept: v.auto_accept, + } + } +} + +impl From<&vm::AudioForm> for AudioForm { + fn from(v: &vm::AudioForm) -> Self { + Self { + input_index: v.input_index, + output_index: v.output_index, + transmit: v.transmit, + vad_threshold: v.vad_threshold, + echo_cancellation: v.echo_cancellation, + noise_suppression: v.noise_suppression, + noise_level: v.noise_level, + auto_gain: v.auto_gain, + input_gain: v.input_gain, + output_volume: v.output_volume, + playback_buffer: v.playback_buffer, + } + } +} + +impl From for AudioForm { + fn from(v: vm::AudioForm) -> Self { + Self::from(&v) + } +} + +impl Row for vm::AudioForm { + type Shown = AudioForm; + + fn show(&self) -> AudioForm { + AudioForm::from(self) + } +} + +impl From for vm::AudioForm { + fn from(v: AudioForm) -> Self { + Self { + input_index: v.input_index, + output_index: v.output_index, + transmit: v.transmit, + vad_threshold: v.vad_threshold, + echo_cancellation: v.echo_cancellation, + noise_suppression: v.noise_suppression, + noise_level: v.noise_level, + auto_gain: v.auto_gain, + input_gain: v.input_gain, + output_volume: v.output_volume, + playback_buffer: v.playback_buffer, + } + } +} + +impl From<&vm::ClientAudio> for ClientAudio { + fn from(v: &vm::ClientAudio) -> Self { + Self { + id: v.id, + name: SharedString::from(&*v.name), + volume: v.volume, + muted: v.muted, + streaming: v.streaming, + } + } +} + +impl From for ClientAudio { + fn from(v: vm::ClientAudio) -> Self { + Self::from(&v) + } +} + +impl Row for vm::ClientAudio { + type Shown = ClientAudio; + + fn show(&self) -> ClientAudio { + ClientAudio::from(self) + } +} + +impl From for vm::ClientAudio { + fn from(v: ClientAudio) -> Self { + Self { + id: v.id, + name: Arc::from(v.name.as_str()), + volume: v.volume, + muted: v.muted, + streaming: v.streaming, + } + } +} + +impl From<&vm::AppearanceForm> for AppearanceForm { + fn from(v: &vm::AppearanceForm) -> Self { + Self { + theme: SharedString::from(&*v.theme), + font_scale: v.font_scale, + narrow_breakpoint: v.narrow_breakpoint, + image_cache_mb: v.image_cache_mb, + } + } +} + +impl From for AppearanceForm { + fn from(v: vm::AppearanceForm) -> Self { + Self::from(&v) + } +} + +impl Row for vm::AppearanceForm { + type Shown = AppearanceForm; + + fn show(&self) -> AppearanceForm { + AppearanceForm::from(self) + } +} + +impl From for vm::AppearanceForm { + fn from(v: AppearanceForm) -> Self { + Self { + theme: Arc::from(v.theme.as_str()), + font_scale: v.font_scale, + narrow_breakpoint: v.narrow_breakpoint, + image_cache_mb: v.image_cache_mb, + } + } +} + +impl From<&vm::ContactItem> for ContactItem { + fn from(v: &vm::ContactItem) -> Self { + Self { + uid: SharedString::from(&*v.uid), + name: SharedString::from(&*v.name), + initials: SharedString::from(&*v.initials), + tint: color(v.tint), + avatar: image(&v.avatar), + relation: SharedString::from(&*v.relation), + online: v.online, + away: v.away, + streaming: v.streaming, + status: SharedString::from(&*v.status), + place: SharedString::from(&*v.place), + when: SharedString::from(&*v.when), + note: SharedString::from(&*v.note), + volume: v.volume, + muted: v.muted, + since: SharedString::from(&*v.since), + spots: strings(&v.spots), + reachable: v.reachable, + selected: v.selected, + } + } +} + +impl From for ContactItem { + fn from(v: vm::ContactItem) -> Self { + Self::from(&v) + } +} + +impl Row for vm::ContactItem { + type Shown = ContactItem; + + fn show(&self) -> ContactItem { + ContactItem::from(self) + } +} + +impl From<&vm::LiveItem> for LiveItem { + fn from(v: &vm::LiveItem) -> Self { + Self { + session: v.session, + id: SharedString::from(&*v.id), + title: SharedString::from(&*v.title), + streamer: SharedString::from(&*v.streamer), + initials: SharedString::from(&*v.initials), + tint: color(v.tint), + avatar: image(&v.avatar), + server: SharedString::from(&*v.server), + channel: SharedString::from(&*v.channel), + viewers: v.viewers, + kind: SharedString::from(&*v.kind), + backdrop: color(v.backdrop), + watchable: v.watchable, + } + } +} + +impl From for LiveItem { + fn from(v: vm::LiveItem) -> Self { + Self::from(&v) + } +} + +impl Row for vm::LiveItem { + type Shown = LiveItem; + + fn show(&self) -> LiveItem { + LiveItem::from(self) + } +} + +impl From<&vm::ConversationItem> for ConversationItem { + fn from(v: &vm::ConversationItem) -> Self { + Self { + key: v.key, + kind: v.kind, + title: SharedString::from(&*v.title), + server: SharedString::from(&*v.server), + preview: SharedString::from(&*v.preview), + time: SharedString::from(&*v.time), + ago: SharedString::from(&*v.ago), + unread: v.unread, + initials: SharedString::from(&*v.initials), + tint: color(v.tint), + avatar: image(&v.avatar), + online: v.online, + selected: v.selected, + } + } +} + +impl From for ConversationItem { + fn from(v: vm::ConversationItem) -> Self { + Self::from(&v) + } +} + +impl Row for vm::ConversationItem { + type Shown = ConversationItem; + + fn show(&self) -> ConversationItem { + ConversationItem::from(self) + } +} + +impl From<&vm::NoticeItem> for NoticeItem { + fn from(v: &vm::NoticeItem) -> Self { + Self { + key: v.key, + kind: SharedString::from(&*v.kind), + title: SharedString::from(&*v.title), + body: SharedString::from(&*v.body), + time: SharedString::from(&*v.time), + unread: v.unread, + initials: SharedString::from(&*v.initials), + tint: color(v.tint), + avatar: image(&v.avatar), + } + } +} + +impl From for NoticeItem { + fn from(v: vm::NoticeItem) -> Self { + Self::from(&v) + } +} + +impl Row for vm::NoticeItem { + type Shown = NoticeItem; + + fn show(&self) -> NoticeItem { + NoticeItem::from(self) + } +} + +impl From<&vm::SearchItem> for SearchItem { + fn from(v: &vm::SearchItem) -> Self { + Self { + kind: SharedString::from(&*v.kind), + title: SharedString::from(&*v.title), + subtitle: SharedString::from(&*v.subtitle), + initials: SharedString::from(&*v.initials), + tint: color(v.tint), + avatar: image(&v.avatar), + header: SharedString::from(&*v.header), + } + } +} + +impl From for SearchItem { + fn from(v: vm::SearchItem) -> Self { + Self::from(&v) + } +} + +impl Row for vm::SearchItem { + type Shown = SearchItem; + + fn show(&self) -> SearchItem { + SearchItem::from(self) + } +} + +impl From<&vm::HappeningItem> for HappeningItem { + fn from(v: &vm::HappeningItem) -> Self { + Self { + kind: SharedString::from(&*v.kind), + title: SharedString::from(&*v.title), + subtitle: SharedString::from(&*v.subtitle), + when: SharedString::from(&*v.when), + session: v.session, + id: v.id, + live: v.live, + } + } +} + +impl From for HappeningItem { + fn from(v: vm::HappeningItem) -> Self { + Self::from(&v) + } +} + +impl Row for vm::HappeningItem { + type Shown = HappeningItem; + + fn show(&self) -> HappeningItem { + HappeningItem::from(self) + } +} + +impl From for vm::HappeningItem { + fn from(v: HappeningItem) -> Self { + Self { + kind: Arc::from(v.kind.as_str()), + title: Arc::from(v.title.as_str()), + subtitle: Arc::from(v.subtitle.as_str()), + when: Arc::from(v.when.as_str()), + session: v.session, + id: v.id, + live: v.live, + } + } +} + +impl From<&vm::ResumeItem> for ResumeItem { + fn from(v: &vm::ResumeItem) -> Self { + Self { + shown: v.shown, + server_id: v.server_id, + server: SharedString::from(&*v.server), + initials: SharedString::from(&*v.initials), + tint: color(v.tint), + icon: image(&v.icon), + channel: SharedString::from(&*v.channel), + open: v.open, + connecting: v.connecting, + } + } +} + +impl From for ResumeItem { + fn from(v: vm::ResumeItem) -> Self { + Self::from(&v) + } +} + +impl Row for vm::ResumeItem { + type Shown = ResumeItem; + + fn show(&self) -> ResumeItem { + ResumeItem::from(self) + } +} + +impl From<&vm::EventItem> for EventItem { + fn from(v: &vm::EventItem) -> Self { + Self { + id: v.id, + title: SharedString::from(&*v.title), + description: SharedString::from(&*v.description), + weekday: SharedString::from(&*v.weekday), + day: SharedString::from(&*v.day), + month: SharedString::from(&*v.month), + when: SharedString::from(&*v.when), + place: SharedString::from(&*v.place), + stream: SharedString::from(&*v.stream), + live: v.live, + going: v.going, + maybe: v.maybe, + not_going: v.not_going, + rsvp: SharedString::from(&*v.rsvp), + creator: SharedString::from(&*v.creator), + editable: v.editable, + soon: SharedString::from(&*v.soon), + attendees: strings(&v.attendees), + expanded: v.expanded, + } + } +} + +impl From for EventItem { + fn from(v: vm::EventItem) -> Self { + Self::from(&v) + } +} + +impl Row for vm::EventItem { + type Shown = EventItem; + + fn show(&self) -> EventItem { + EventItem::from(self) + } +} + +impl From for vm::EventItem { + fn from(v: EventItem) -> Self { + Self { + id: v.id, + title: Arc::from(v.title.as_str()), + description: Arc::from(v.description.as_str()), + weekday: Arc::from(v.weekday.as_str()), + day: Arc::from(v.day.as_str()), + month: Arc::from(v.month.as_str()), + when: Arc::from(v.when.as_str()), + place: Arc::from(v.place.as_str()), + stream: Arc::from(v.stream.as_str()), + live: v.live, + going: v.going, + maybe: v.maybe, + not_going: v.not_going, + rsvp: Arc::from(v.rsvp.as_str()), + creator: Arc::from(v.creator.as_str()), + editable: v.editable, + soon: Arc::from(v.soon.as_str()), + attendees: unstrings(&v.attendees), + expanded: v.expanded, + } + } +} + +impl From<&vm::EventForm> for EventForm { + fn from(v: &vm::EventForm) -> Self { + Self { + id: v.id, + title: SharedString::from(&*v.title), + description: SharedString::from(&*v.description), + start: SharedString::from(&*v.start), + end: SharedString::from(&*v.end), + channel: v.channel, + stream: v.stream, + stream_title: SharedString::from(&*v.stream_title), + game: SharedString::from(&*v.game), + } + } +} + +impl From for EventForm { + fn from(v: vm::EventForm) -> Self { + Self::from(&v) + } +} + +impl Row for vm::EventForm { + type Shown = EventForm; + + fn show(&self) -> EventForm { + EventForm::from(self) + } +} + +impl From for vm::EventForm { + fn from(v: EventForm) -> Self { + Self { + id: v.id, + title: Arc::from(v.title.as_str()), + description: Arc::from(v.description.as_str()), + start: Arc::from(v.start.as_str()), + end: Arc::from(v.end.as_str()), + channel: v.channel, + stream: v.stream, + stream_title: Arc::from(v.stream_title.as_str()), + game: Arc::from(v.game.as_str()), + } + } +} + +impl From<&vm::OfflineForm> for OfflineForm { + fn from(v: &vm::OfflineForm) -> Self { + Self { + uid: SharedString::from(&*v.uid), + to: SharedString::from(&*v.to), + subject: SharedString::from(&*v.subject), + text: SharedString::from(&*v.text), + } + } +} + +impl From for OfflineForm { + fn from(v: vm::OfflineForm) -> Self { + Self::from(&v) + } +} + +impl Row for vm::OfflineForm { + type Shown = OfflineForm; + + fn show(&self) -> OfflineForm { + OfflineForm::from(self) + } +} + +impl From for vm::OfflineForm { + fn from(v: OfflineForm) -> Self { + Self { + uid: Arc::from(v.uid.as_str()), + to: Arc::from(v.to.as_str()), + subject: Arc::from(v.subject.as_str()), + text: Arc::from(v.text.as_str()), + } + } +} + +impl From<&vm::DmPeer> for DmPeer { + fn from(v: &vm::DmPeer) -> Self { + Self { + open: v.open, + uid: SharedString::from(&*v.uid), + name: SharedString::from(&*v.name), + initials: SharedString::from(&*v.initials), + tint: color(v.tint), + avatar: image(&v.avatar), + online: v.online, + status: SharedString::from(&*v.status), + description: SharedString::from(&*v.description), + groups: strings(&v.groups), + note: SharedString::from(&*v.note), + since: SharedString::from(&*v.since), + servers: strings(&v.servers), + media: images(&v.media), + media_more: v.media_more, + files: model(&v.files), + friend: v.friend, + blocked: v.blocked, + volume: v.volume, + muted: v.muted, + can_send: v.can_send, + notice: SharedString::from(&*v.notice), + offline: v.offline, + can_connect: v.can_connect, + stored: v.stored, + mail: v.mail, + mail_subject: SharedString::from(&*v.mail_subject), + mail_text: SharedString::from(&*v.mail_text), + mail_time: SharedString::from(&*v.mail_time), + } + } +} + +impl From for DmPeer { + fn from(v: vm::DmPeer) -> Self { + Self::from(&v) + } +} + +impl Row for vm::DmPeer { + type Shown = DmPeer; + + fn show(&self) -> DmPeer { + DmPeer::from(self) + } +} + +impl From<&vm::IdentityItem> for IdentityItem { + fn from(v: &vm::IdentityItem) -> Self { + Self { + id: v.id, + name: SharedString::from(&*v.name), + uid: SharedString::from(&*v.uid), + uid6: SharedString::from(&*v.uid6), + level: v.level, + default: v.default, + origin: SharedString::from(&*v.origin), + improving: v.improving, + reached: v.reached, + used_by: SharedString::from(&*v.used_by), + } + } +} + +impl From for IdentityItem { + fn from(v: vm::IdentityItem) -> Self { + Self::from(&v) + } +} + +impl Row for vm::IdentityItem { + type Shown = IdentityItem; + + fn show(&self) -> IdentityItem { + IdentityItem::from(self) + } +} + +impl From for vm::IdentityItem { + fn from(v: IdentityItem) -> Self { + Self { + id: v.id, + name: Arc::from(v.name.as_str()), + uid: Arc::from(v.uid.as_str()), + uid6: Arc::from(v.uid6.as_str()), + level: v.level, + default: v.default, + origin: Arc::from(v.origin.as_str()), + improving: v.improving, + reached: v.reached, + used_by: Arc::from(v.used_by.as_str()), + } + } +} + +impl From<&vm::FoundIdentity> for FoundIdentity { + fn from(v: &vm::FoundIdentity) -> Self { + Self { + name: SharedString::from(&*v.name), + uid: SharedString::from(&*v.uid), + level: v.level, + source: SharedString::from(&*v.source), + known: v.known, + picked: v.picked, + } + } +} + +impl From for FoundIdentity { + fn from(v: vm::FoundIdentity) -> Self { + Self::from(&v) + } +} + +impl Row for vm::FoundIdentity { + type Shown = FoundIdentity; + + fn show(&self) -> FoundIdentity { + FoundIdentity::from(self) + } +} + +impl From for vm::FoundIdentity { + fn from(v: FoundIdentity) -> Self { + Self { + name: Arc::from(v.name.as_str()), + uid: Arc::from(v.uid.as_str()), + level: v.level, + source: Arc::from(v.source.as_str()), + known: v.known, + picked: v.picked, + } + } +} + +impl From<&vm::BookmarkIdentity> for BookmarkIdentity { + fn from(v: &vm::BookmarkIdentity) -> Self { + Self { id: v.id, name: SharedString::from(&*v.name), identity: v.identity } + } +} + +impl From for BookmarkIdentity { + fn from(v: vm::BookmarkIdentity) -> Self { + Self::from(&v) + } +} + +impl Row for vm::BookmarkIdentity { + type Shown = BookmarkIdentity; + + fn show(&self) -> BookmarkIdentity { + BookmarkIdentity::from(self) + } +} + +impl From for vm::BookmarkIdentity { + fn from(v: BookmarkIdentity) -> Self { + Self { id: v.id, name: Arc::from(v.name.as_str()), identity: v.identity } + } +} + +impl From<&vm::VideoForm> for VideoForm { + fn from(v: &vm::VideoForm) -> Self { + Self { + camera: v.camera, + background: v.background, + resolution: SharedString::from(&*v.resolution), + fps: SharedString::from(&*v.fps), + codec: v.codec, + hardware: v.hardware, + mirror: v.mirror, + permissions: v.permissions, + quality: v.quality, + bitrate: v.bitrate, + preview: v.preview, + } + } +} + +impl From for VideoForm { + fn from(v: vm::VideoForm) -> Self { + Self::from(&v) + } +} + +impl Row for vm::VideoForm { + type Shown = VideoForm; + + fn show(&self) -> VideoForm { + VideoForm::from(self) + } +} + +impl From for vm::VideoForm { + fn from(v: VideoForm) -> Self { + Self { + camera: v.camera, + background: v.background, + resolution: Arc::from(v.resolution.as_str()), + fps: Arc::from(v.fps.as_str()), + codec: v.codec, + hardware: v.hardware, + mirror: v.mirror, + permissions: v.permissions, + quality: v.quality, + bitrate: v.bitrate, + preview: v.preview, + } + } +} + +impl From<&vm::LayerItem> for LayerItem { + fn from(v: &vm::LayerItem) -> Self { + Self { + size: SharedString::from(&*v.size), + fps: SharedString::from(&*v.fps), + bitrate: SharedString::from(&*v.bitrate), + min_bitrate: SharedString::from(&*v.min_bitrate), + max_bitrate: SharedString::from(&*v.max_bitrate), + } + } +} + +impl From for LayerItem { + fn from(v: vm::LayerItem) -> Self { + Self::from(&v) + } +} + +impl Row for vm::LayerItem { + type Shown = LayerItem; + + fn show(&self) -> LayerItem { + LayerItem::from(self) + } +} + +impl From for vm::LayerItem { + fn from(v: LayerItem) -> Self { + Self { + size: Arc::from(v.size.as_str()), + fps: Arc::from(v.fps.as_str()), + bitrate: Arc::from(v.bitrate.as_str()), + min_bitrate: Arc::from(v.min_bitrate.as_str()), + max_bitrate: Arc::from(v.max_bitrate.as_str()), + } + } +} + +impl From<&vm::AudioSourceItem> for AudioSourceItem { + fn from(v: &vm::AudioSourceItem) -> Self { + Self { + kind: SharedString::from(&*v.kind), + name: SharedString::from(&*v.name), + detail: SharedString::from(&*v.detail), + gain: v.gain, + muted: v.muted, + } + } +} + +impl From for AudioSourceItem { + fn from(v: vm::AudioSourceItem) -> Self { + Self::from(&v) + } +} + +impl Row for vm::AudioSourceItem { + type Shown = AudioSourceItem; + + fn show(&self) -> AudioSourceItem { + AudioSourceItem::from(self) + } +} + +impl From for vm::AudioSourceItem { + fn from(v: AudioSourceItem) -> Self { + Self { + kind: Arc::from(v.kind.as_str()), + name: Arc::from(v.name.as_str()), + detail: Arc::from(v.detail.as_str()), + gain: v.gain, + muted: v.muted, + } + } +} + +impl From<&vm::StreamingForm> for StreamingForm { + fn from(v: &vm::StreamingForm) -> Self { + Self { + fps: SharedString::from(&*v.fps), + bitrate: SharedString::from(&*v.bitrate), + codec: v.codec, + capture: v.capture, + replay_seconds: SharedString::from(&*v.replay_seconds), + replay_memory: SharedString::from(&*v.replay_memory), + recording_dir: SharedString::from(&*v.recording_dir), + } + } +} + +impl From for StreamingForm { + fn from(v: vm::StreamingForm) -> Self { + Self::from(&v) + } +} + +impl Row for vm::StreamingForm { + type Shown = StreamingForm; + + fn show(&self) -> StreamingForm { + StreamingForm::from(self) + } +} + +impl From for vm::StreamingForm { + fn from(v: StreamingForm) -> Self { + Self { + fps: Arc::from(v.fps.as_str()), + bitrate: Arc::from(v.bitrate.as_str()), + codec: v.codec, + capture: v.capture, + replay_seconds: Arc::from(v.replay_seconds.as_str()), + replay_memory: Arc::from(v.replay_memory.as_str()), + recording_dir: Arc::from(v.recording_dir.as_str()), + } + } +} + +impl From<&vm::NotifyForm> for NotifyForm { + fn from(v: &vm::NotifyForm) -> Self { + Self { + mentions: v.mentions, + pokes: v.pokes, + messages: v.messages, + events: v.events, + friends: v.friends, + } + } +} + +impl From for NotifyForm { + fn from(v: vm::NotifyForm) -> Self { + Self::from(&v) + } +} + +impl Row for vm::NotifyForm { + type Shown = NotifyForm; + + fn show(&self) -> NotifyForm { + NotifyForm::from(self) + } +} + +impl From for vm::NotifyForm { + fn from(v: NotifyForm) -> Self { + Self { + mentions: v.mentions, + pokes: v.pokes, + messages: v.messages, + events: v.events, + friends: v.friends, + } + } +} + +impl From<&vm::PrivacyForm> for PrivacyForm { + fn from(v: &vm::PrivacyForm) -> Self { + Self { block_mode: v.block_mode, messages: v.messages, pokes: v.pokes } + } +} + +impl From for PrivacyForm { + fn from(v: vm::PrivacyForm) -> Self { + Self::from(&v) + } +} + +impl Row for vm::PrivacyForm { + type Shown = PrivacyForm; + + fn show(&self) -> PrivacyForm { + PrivacyForm::from(self) + } +} + +impl From for vm::PrivacyForm { + fn from(v: PrivacyForm) -> Self { + Self { block_mode: v.block_mode, messages: v.messages, pokes: v.pokes } + } +} + +impl From<&vm::GatewayItem> for GatewayItem { + fn from(v: &vm::GatewayItem) -> Self { + Self { + session: v.session, + server: SharedString::from(&*v.server), + url: SharedString::from(&*v.url), + status: SharedString::from(&*v.status), + features: strings(&v.features), + admin: v.admin, + } + } +} + +impl From for GatewayItem { + fn from(v: vm::GatewayItem) -> Self { + Self::from(&v) + } +} + +impl Row for vm::GatewayItem { + type Shown = GatewayItem; + + fn show(&self) -> GatewayItem { + GatewayItem::from(self) + } +} + +impl From for vm::GatewayItem { + fn from(v: GatewayItem) -> Self { + Self { + session: v.session, + server: Arc::from(v.server.as_str()), + url: Arc::from(v.url.as_str()), + status: Arc::from(v.status.as_str()), + features: unstrings(&v.features), + admin: v.admin, + } + } +} + +impl From<&vm::ConfigItem> for ConfigItem { + fn from(v: &vm::ConfigItem) -> Self { + Self { + key: SharedString::from(&*v.key), + value: SharedString::from(&*v.value), + source: SharedString::from(&*v.source), + description: SharedString::from(&*v.description), + kind: SharedString::from(&*v.kind), + bootstrap: v.bootstrap, + } + } +} + +impl From for ConfigItem { + fn from(v: vm::ConfigItem) -> Self { + Self::from(&v) + } +} + +impl Row for vm::ConfigItem { + type Shown = ConfigItem; + + fn show(&self) -> ConfigItem { + ConfigItem::from(self) + } +} + +impl From for vm::ConfigItem { + fn from(v: ConfigItem) -> Self { + Self { + key: Arc::from(v.key.as_str()), + value: Arc::from(v.value.as_str()), + source: Arc::from(v.source.as_str()), + description: Arc::from(v.description.as_str()), + kind: Arc::from(v.kind.as_str()), + bootstrap: v.bootstrap, + } + } +} + +impl From<&vm::PermItem> for PermItem { + fn from(v: &vm::PermItem) -> Self { + Self { + action: SharedString::from(&*v.action), + rule: SharedString::from(&*v.rule), + source: SharedString::from(&*v.source), + everyone: v.everyone, + server_groups: SharedString::from(&*v.server_groups), + channel_groups: SharedString::from(&*v.channel_groups), + } + } +} + +impl From for PermItem { + fn from(v: vm::PermItem) -> Self { + Self::from(&v) + } +} + +impl Row for vm::PermItem { + type Shown = PermItem; + + fn show(&self) -> PermItem { + PermItem::from(self) + } +} + +impl From for vm::PermItem { + fn from(v: PermItem) -> Self { + Self { + action: Arc::from(v.action.as_str()), + rule: Arc::from(v.rule.as_str()), + source: Arc::from(v.source.as_str()), + everyone: v.everyone, + server_groups: Arc::from(v.server_groups.as_str()), + channel_groups: Arc::from(v.channel_groups.as_str()), + } + } +} + +impl From<&vm::EncoderItem> for EncoderItem { + fn from(v: &vm::EncoderItem) -> Self { + Self { + name: SharedString::from(&*v.name), + api: SharedString::from(&*v.api), + codec: SharedString::from(&*v.codec), + hardware: v.hardware, + ok: v.ok, + status: SharedString::from(&*v.status), + } + } +} + +impl From for EncoderItem { + fn from(v: vm::EncoderItem) -> Self { + Self::from(&v) + } +} + +impl Row for vm::EncoderItem { + type Shown = EncoderItem; + + fn show(&self) -> EncoderItem { + EncoderItem::from(self) + } +} + +impl From for vm::EncoderItem { + fn from(v: EncoderItem) -> Self { + Self { + name: Arc::from(v.name.as_str()), + api: Arc::from(v.api.as_str()), + codec: Arc::from(v.codec.as_str()), + hardware: v.hardware, + ok: v.ok, + status: Arc::from(v.status.as_str()), + } + } +} + +impl From<&vm::SettingItem> for SettingItem { + fn from(v: &vm::SettingItem) -> Self { + Self { + key: SharedString::from(&*v.key), + doc: SharedString::from(&*v.doc), + value: SharedString::from(&*v.value), + source: SharedString::from(&*v.source), + } + } +} + +impl From for SettingItem { + fn from(v: vm::SettingItem) -> Self { + Self::from(&v) + } +} + +impl Row for vm::SettingItem { + type Shown = SettingItem; + + fn show(&self) -> SettingItem { + SettingItem::from(self) + } +} + +impl From for vm::SettingItem { + fn from(v: SettingItem) -> Self { + Self { + key: Arc::from(v.key.as_str()), + doc: Arc::from(v.doc.as_str()), + value: Arc::from(v.value.as_str()), + source: Arc::from(v.source.as_str()), + } + } +} + +impl From<&vm::RecordingItem> for RecordingItem { + fn from(v: &vm::RecordingItem) -> Self { + Self { + name: SharedString::from(&*v.name), + detail: SharedString::from(&*v.detail), + clip: v.clip, + path: SharedString::from(&*v.path), + } + } +} + +impl From for RecordingItem { + fn from(v: vm::RecordingItem) -> Self { + Self::from(&v) + } +} + +impl Row for vm::RecordingItem { + type Shown = RecordingItem; + + fn show(&self) -> RecordingItem { + RecordingItem::from(self) + } +} + +impl From for vm::RecordingItem { + fn from(v: RecordingItem) -> Self { + Self { + name: Arc::from(v.name.as_str()), + detail: Arc::from(v.detail.as_str()), + clip: v.clip, + path: Arc::from(v.path.as_str()), + } + } +} + +impl From<&vm::AdvancedForm> for AdvancedForm { + fn from(v: &vm::AdvancedForm) -> Self { + Self { + encoder: SharedString::from(&*v.encoder), + hardware: v.hardware, + decoder: SharedString::from(&*v.decoder), + hardware_decoding: v.hardware_decoding, + store_history: v.store_history, + history_page: SharedString::from(&*v.history_page), + dedupe_ms: SharedString::from(&*v.dedupe_ms), + retention_days: SharedString::from(&*v.retention_days), + cache_mb: SharedString::from(&*v.cache_mb), + fetch_images: v.fetch_images, + progress_ms: SharedString::from(&*v.progress_ms), + preview_kb: SharedString::from(&*v.preview_kb), + logs: SharedString::from(&*v.logs), + crash_dir: SharedString::from(&*v.crash_dir), + } + } +} + +impl From for AdvancedForm { + fn from(v: vm::AdvancedForm) -> Self { + Self::from(&v) + } +} + +impl Row for vm::AdvancedForm { + type Shown = AdvancedForm; + + fn show(&self) -> AdvancedForm { + AdvancedForm::from(self) + } +} + +impl From for vm::AdvancedForm { + fn from(v: AdvancedForm) -> Self { + Self { + encoder: Arc::from(v.encoder.as_str()), + hardware: v.hardware, + decoder: Arc::from(v.decoder.as_str()), + hardware_decoding: v.hardware_decoding, + store_history: v.store_history, + history_page: Arc::from(v.history_page.as_str()), + dedupe_ms: Arc::from(v.dedupe_ms.as_str()), + retention_days: Arc::from(v.retention_days.as_str()), + cache_mb: Arc::from(v.cache_mb.as_str()), + fetch_images: v.fetch_images, + progress_ms: Arc::from(v.progress_ms.as_str()), + preview_kb: Arc::from(v.preview_kb.as_str()), + logs: Arc::from(v.logs.as_str()), + crash_dir: Arc::from(v.crash_dir.as_str()), + } + } +} + +impl From<&vm::AccountForm> for AccountForm { + fn from(v: &vm::AccountForm) -> Self { + Self { + nickname: SharedString::from(&*v.nickname), + identity: SharedString::from(&*v.identity), + uid: SharedString::from(&*v.uid), + uid6: SharedString::from(&*v.uid6), + level: v.level, + server: SharedString::from(&*v.server), + } + } +} + +impl From for AccountForm { + fn from(v: vm::AccountForm) -> Self { + Self::from(&v) + } +} + +impl Row for vm::AccountForm { + type Shown = AccountForm; + + fn show(&self) -> AccountForm { + AccountForm::from(self) + } +} + +impl From for vm::AccountForm { + fn from(v: AccountForm) -> Self { + Self { + nickname: Arc::from(v.nickname.as_str()), + identity: Arc::from(v.identity.as_str()), + uid: Arc::from(v.uid.as_str()), + uid6: Arc::from(v.uid6.as_str()), + level: v.level, + server: Arc::from(v.server.as_str()), + } + } +} + +impl From<&vm::EmojiCell> for EmojiCell { + fn from(v: &vm::EmojiCell) -> Self { + Self { + key: SharedString::from(&*v.key), + name: SharedString::from(&*v.name), + text: SharedString::from(&*v.text), + } + } +} + +impl From for EmojiCell { + fn from(v: vm::EmojiCell) -> Self { + Self::from(&v) + } +} + +impl Row for vm::EmojiCell { + type Shown = EmojiCell; + + fn show(&self) -> EmojiCell { + EmojiCell::from(self) + } +} + +impl From for vm::EmojiCell { + fn from(v: EmojiCell) -> Self { + Self { + key: Arc::from(v.key.as_str()), + name: Arc::from(v.name.as_str()), + text: Arc::from(v.text.as_str()), + } + } +} + +impl From<&vm::EmojiRow> for EmojiRow { + fn from(v: &vm::EmojiRow) -> Self { + Self { cells: model(&v.cells) } + } +} + +impl From for EmojiRow { + fn from(v: vm::EmojiRow) -> Self { + Self::from(&v) + } +} + +impl Row for vm::EmojiRow { + type Shown = EmojiRow; + + fn show(&self) -> EmojiRow { + EmojiRow::from(self) + } +} + +impl From for vm::EmojiRow { + fn from(v: EmojiRow) -> Self { + Self { cells: rows(&v.cells) } + } +} + +impl From<&studio::StudioScene> for StudioScene { + fn from(v: &studio::StudioScene) -> Self { + Self { + id: v.id, + name: SharedString::from(&*v.name), + detail: SharedString::from(&*v.detail), + live: v.live, + kind: SharedString::from(&*v.kind), + } + } +} + +impl From for StudioScene { + fn from(v: studio::StudioScene) -> Self { + Self::from(&v) + } +} + +impl Row for studio::StudioScene { + type Shown = StudioScene; + + fn show(&self) -> StudioScene { + StudioScene::from(self) + } +} + +impl From for studio::StudioScene { + fn from(v: StudioScene) -> Self { + Self { + id: v.id, + name: Arc::from(v.name.as_str()), + detail: Arc::from(v.detail.as_str()), + live: v.live, + kind: Arc::from(v.kind.as_str()), + } + } +} + +impl From<&studio::StudioSource> for StudioSource { + fn from(v: &studio::StudioSource) -> Self { + Self { + id: v.id, + name: SharedString::from(&*v.name), + kind: SharedString::from(&*v.kind), + visible: v.visible, + locked: v.locked, + background: SharedString::from(&*v.background), + error: SharedString::from(&*v.error), + info: SharedString::from(&*v.info), + front: v.front, + back: v.back, + } + } +} + +impl From for StudioSource { + fn from(v: studio::StudioSource) -> Self { + Self::from(&v) + } +} + +impl Row for studio::StudioSource { + type Shown = StudioSource; + + fn show(&self) -> StudioSource { + StudioSource::from(self) + } +} + +impl From for studio::StudioSource { + fn from(v: StudioSource) -> Self { + Self { + id: v.id, + name: Arc::from(v.name.as_str()), + kind: Arc::from(v.kind.as_str()), + visible: v.visible, + locked: v.locked, + background: Arc::from(v.background.as_str()), + error: Arc::from(v.error.as_str()), + info: Arc::from(v.info.as_str()), + front: v.front, + back: v.back, + } + } +} + +impl From<&studio::StudioAudio> for StudioAudio { + fn from(v: &studio::StudioAudio) -> Self { + Self { + name: SharedString::from(&*v.name), + detail: SharedString::from(&*v.detail), + kind: SharedString::from(&*v.kind), + gain_db: v.gain_db, + muted: v.muted, + level: v.level, + error: SharedString::from(&*v.error), + } + } +} + +impl From for StudioAudio { + fn from(v: studio::StudioAudio) -> Self { + Self::from(&v) + } +} + +impl Row for studio::StudioAudio { + type Shown = StudioAudio; + + fn show(&self) -> StudioAudio { + StudioAudio::from(self) + } +} + +impl From for studio::StudioAudio { + fn from(v: StudioAudio) -> Self { + Self { + name: Arc::from(v.name.as_str()), + detail: Arc::from(v.detail.as_str()), + kind: Arc::from(v.kind.as_str()), + gain_db: v.gain_db, + muted: v.muted, + level: v.level, + error: Arc::from(v.error.as_str()), + } + } +} + +impl From<&studio::StudioLayer> for StudioLayer { + fn from(v: &studio::StudioLayer) -> Self { + Self { + size: SharedString::from(&*v.size), + scale: SharedString::from(&*v.scale), + fps: SharedString::from(&*v.fps), + bitrate: SharedString::from(&*v.bitrate), + min_bitrate: SharedString::from(&*v.min_bitrate), + } + } +} + +impl From for StudioLayer { + fn from(v: studio::StudioLayer) -> Self { + Self::from(&v) + } +} + +impl Row for studio::StudioLayer { + type Shown = StudioLayer; + + fn show(&self) -> StudioLayer { + StudioLayer::from(self) + } +} + +impl From for studio::StudioLayer { + fn from(v: StudioLayer) -> Self { + Self { + size: Arc::from(v.size.as_str()), + scale: Arc::from(v.scale.as_str()), + fps: Arc::from(v.fps.as_str()), + bitrate: Arc::from(v.bitrate.as_str()), + min_bitrate: Arc::from(v.min_bitrate.as_str()), + } + } +} + +impl From<&studio::StudioViewer> for StudioViewer { + fn from(v: &studio::StudioViewer) -> Self { + Self { + client: v.client, + name: SharedString::from(&*v.name), + state: SharedString::from(&*v.state), + } + } +} + +impl From for StudioViewer { + fn from(v: studio::StudioViewer) -> Self { + Self::from(&v) + } +} + +impl Row for studio::StudioViewer { + type Shown = StudioViewer; + + fn show(&self) -> StudioViewer { + StudioViewer::from(self) + } +} + +impl From for studio::StudioViewer { + fn from(v: StudioViewer) -> Self { + Self { + client: v.client, + name: Arc::from(v.name.as_str()), + state: Arc::from(v.state.as_str()), + } + } +} + +impl From<&studio::StudioPick> for StudioPick { + fn from(v: &studio::StudioPick) -> Self { + Self { + name: SharedString::from(&*v.name), + detail: SharedString::from(&*v.detail), + kind: SharedString::from(&*v.kind), + icon: image(&v.icon), + selected: v.selected, + } + } +} + +impl From for StudioPick { + fn from(v: studio::StudioPick) -> Self { + Self::from(&v) + } +} + +impl Row for studio::StudioPick { + type Shown = StudioPick; + + fn show(&self) -> StudioPick { + StudioPick::from(self) + } +} + +impl From<&studio::StudioStatus> for StudioStatus { + fn from(v: &studio::StudioStatus) -> Self { + Self { + running: v.running, + destination: SharedString::from(&*v.destination), + quality: v.quality, + quality_text: SharedString::from(&*v.quality_text), + format: SharedString::from(&*v.format), + details: SharedString::from(&*v.details), + live: v.live, + starting: v.starting, + elapsed: SharedString::from(&*v.elapsed), + viewers: v.viewers, + participants: v.participants, + can_go_live: v.can_go_live, + hint: SharedString::from(&*v.hint), + recording: v.recording, + recorded: SharedString::from(&*v.recorded), + replay_seconds: v.replay_seconds, + replay_held: SharedString::from(&*v.replay_held), + output_width: v.output_width, + output_height: v.output_height, + fps: v.fps, + detached: v.detached, + can_detach: v.can_detach, + screen_shown: v.screen_shown, + camera_shown: v.camera_shown, + window_shown: v.window_shown, + } + } +} + +impl From for StudioStatus { + fn from(v: studio::StudioStatus) -> Self { + Self::from(&v) + } +} + +impl Row for studio::StudioStatus { + type Shown = StudioStatus; + + fn show(&self) -> StudioStatus { + StudioStatus::from(self) + } +} + +impl From for studio::StudioStatus { + fn from(v: StudioStatus) -> Self { + Self { + running: v.running, + destination: Arc::from(v.destination.as_str()), + quality: v.quality, + quality_text: Arc::from(v.quality_text.as_str()), + format: Arc::from(v.format.as_str()), + details: Arc::from(v.details.as_str()), + live: v.live, + starting: v.starting, + elapsed: Arc::from(v.elapsed.as_str()), + viewers: v.viewers, + participants: v.participants, + can_go_live: v.can_go_live, + hint: Arc::from(v.hint.as_str()), + recording: v.recording, + recorded: Arc::from(v.recorded.as_str()), + replay_seconds: v.replay_seconds, + replay_held: Arc::from(v.replay_held.as_str()), + output_width: v.output_width, + output_height: v.output_height, + fps: v.fps, + detached: v.detached, + can_detach: v.can_detach, + screen_shown: v.screen_shown, + camera_shown: v.camera_shown, + window_shown: v.window_shown, + } + } +} + +impl From<&studio::StudioForm> for StudioForm { + fn from(v: &studio::StudioForm) -> Self { + Self { + destination: v.destination, + title: SharedString::from(&*v.title), + game: SharedString::from(&*v.game), + message: SharedString::from(&*v.message), + show_viewers: v.show_viewers, + show_chat: v.show_chat, + show_now_playing: v.show_now_playing, + audio: v.audio, + bitrate: SharedString::from(&*v.bitrate), + } + } +} + +impl From for StudioForm { + fn from(v: studio::StudioForm) -> Self { + Self::from(&v) + } +} + +impl Row for studio::StudioForm { + type Shown = StudioForm; + + fn show(&self) -> StudioForm { + StudioForm::from(self) + } +} + +impl From for studio::StudioForm { + fn from(v: StudioForm) -> Self { + Self { + destination: v.destination, + title: Arc::from(v.title.as_str()), + game: Arc::from(v.game.as_str()), + message: Arc::from(v.message.as_str()), + show_viewers: v.show_viewers, + show_chat: v.show_chat, + show_now_playing: v.show_now_playing, + audio: v.audio, + bitrate: Arc::from(v.bitrate.as_str()), + } + } +} + +impl From<&studio::StudioSourceForm> for StudioSourceForm { + fn from(v: &studio::StudioSourceForm) -> Self { + Self { + id: v.id, + name: SharedString::from(&*v.name), + kind: SharedString::from(&*v.kind), + x: SharedString::from(&*v.x), + y: SharedString::from(&*v.y), + width: SharedString::from(&*v.width), + height: SharedString::from(&*v.height), + scale: SharedString::from(&*v.scale), + fit: SharedString::from(&*v.fit), + crop_left: SharedString::from(&*v.crop_left), + crop_top: SharedString::from(&*v.crop_top), + crop_right: SharedString::from(&*v.crop_right), + crop_bottom: SharedString::from(&*v.crop_bottom), + opacity: v.opacity, + locked: v.locked, + visible: v.visible, + background: SharedString::from(&*v.background), + blur: SharedString::from(&*v.blur), + background_path: SharedString::from(&*v.background_path), + background_colour: SharedString::from(&*v.background_colour), + text: SharedString::from(&*v.text), + text_size: SharedString::from(&*v.text_size), + colour: SharedString::from(&*v.colour), + path: SharedString::from(&*v.path), + mirror: v.mirror, + } + } +} + +impl From for StudioSourceForm { + fn from(v: studio::StudioSourceForm) -> Self { + Self::from(&v) + } +} + +impl Row for studio::StudioSourceForm { + type Shown = StudioSourceForm; + + fn show(&self) -> StudioSourceForm { + StudioSourceForm::from(self) + } +} + +impl From for studio::StudioSourceForm { + fn from(v: StudioSourceForm) -> Self { + Self { + id: v.id, + name: Arc::from(v.name.as_str()), + kind: Arc::from(v.kind.as_str()), + x: Arc::from(v.x.as_str()), + y: Arc::from(v.y.as_str()), + width: Arc::from(v.width.as_str()), + height: Arc::from(v.height.as_str()), + scale: Arc::from(v.scale.as_str()), + fit: Arc::from(v.fit.as_str()), + crop_left: Arc::from(v.crop_left.as_str()), + crop_top: Arc::from(v.crop_top.as_str()), + crop_right: Arc::from(v.crop_right.as_str()), + crop_bottom: Arc::from(v.crop_bottom.as_str()), + opacity: v.opacity, + locked: v.locked, + visible: v.visible, + background: Arc::from(v.background.as_str()), + blur: Arc::from(v.blur.as_str()), + background_path: Arc::from(v.background_path.as_str()), + background_colour: Arc::from(v.background_colour.as_str()), + text: Arc::from(v.text.as_str()), + text_size: Arc::from(v.text_size.as_str()), + colour: Arc::from(v.colour.as_str()), + path: Arc::from(v.path.as_str()), + mirror: v.mirror, + } + } +} + +impl From<&studio::StudioSettingsForm> for StudioSettingsForm { + fn from(v: &studio::StudioSettingsForm) -> Self { + Self { + replay_seconds: SharedString::from(&*v.replay_seconds), + replay_memory: SharedString::from(&*v.replay_memory), + recording_dir: SharedString::from(&*v.recording_dir), + preview_width: SharedString::from(&*v.preview_width), + preview_fps: SharedString::from(&*v.preview_fps), + } + } +} + +impl From for StudioSettingsForm { + fn from(v: studio::StudioSettingsForm) -> Self { + Self::from(&v) + } +} + +impl Row for studio::StudioSettingsForm { + type Shown = StudioSettingsForm; + + fn show(&self) -> StudioSettingsForm { + StudioSettingsForm::from(self) + } +} + +impl From for studio::StudioSettingsForm { + fn from(v: StudioSettingsForm) -> Self { + Self { + replay_seconds: Arc::from(v.replay_seconds.as_str()), + replay_memory: Arc::from(v.replay_memory.as_str()), + recording_dir: Arc::from(v.recording_dir.as_str()), + preview_width: Arc::from(v.preview_width.as_str()), + preview_fps: Arc::from(v.preview_fps.as_str()), + } + } +} diff --git a/crates/voelin-ui/src/bind/mod.rs b/crates/voelin-ui/src/bind/mod.rs index a47c447..79fc36d 100644 --- a/crates/voelin-ui/src/bind/mod.rs +++ b/crates/voelin-ui/src/bind/mod.rs @@ -2,8 +2,10 @@ //! area; each has a `wire` that the window calls once. mod chat; +pub(crate) mod convert; mod emoji; mod pages; +pub(crate) mod rows; mod servers; mod settings; mod social; diff --git a/crates/voelin-ui/src/bind/pages.rs b/crates/voelin-ui/src/bind/pages.rs index db8783f..63d96bb 100644 --- a/crates/voelin-ui/src/bind/pages.rs +++ b/crates/voelin-ui/src/bind/pages.rs @@ -1,4 +1,4 @@ -//! The settings pages of the new design (settings_pages.rs). +//! The settings pages of the new design (`settings_pages/`). use slint::ComponentHandle; @@ -33,7 +33,7 @@ pub(super) fn wire(ui: &MainWindow) { }); // Voice & Video. bridge.on_video_changed(|form| { - with_app(|app| app.video_changed(&form)); + with_app(|app| app.video_changed(&form.into())); }); bridge.on_toggle_camera_preview(|| { with_app(|app| app.toggle_camera_preview()); @@ -43,10 +43,10 @@ pub(super) fn wire(ui: &MainWindow) { }); // Streaming. bridge.on_streaming_changed(|form| { - with_app(|app| app.streaming_changed(&form)); + with_app(|app| app.streaming_changed(&form.into())); }); bridge.on_layer_changed(|index, item| { - with_app(|app| app.layer_changed(index, &item)); + with_app(|app| app.layer_changed(index, &item.into())); }); bridge.on_add_layer(|| { with_app(|app| app.add_layer()); @@ -55,7 +55,7 @@ pub(super) fn wire(ui: &MainWindow) { with_app(|app| app.remove_layer(index)); }); bridge.on_audio_source_changed(|index, item| { - with_app(|app| app.audio_source_changed(index, &item)); + with_app(|app| app.audio_source_changed(index, &item.into())); }); bridge.on_add_audio_source(|kind, name| { with_app(|app| app.add_audio_source(&kind, &name)); @@ -65,13 +65,13 @@ pub(super) fn wire(ui: &MainWindow) { }); // Notifications, privacy. bridge.on_notify_changed(|form| { - with_app(|app| app.notify_changed(&form)); + with_app(|app| app.notify_changed(&form.into())); }); bridge.on_test_notification(|| { with_app(|app| app.test_notification()); }); bridge.on_privacy_changed(|form| { - with_app(|app| app.privacy_changed(&form)); + with_app(|app| app.privacy_changed(&form.into())); }); // Integrations. bridge.on_gateway_admin(|session| { @@ -97,7 +97,7 @@ pub(super) fn wire(ui: &MainWindow) { }); // Advanced. bridge.on_advanced_changed(|form| { - with_app(|app| app.advanced_changed(&form)); + with_app(|app| app.advanced_changed(&form.into())); }); bridge.on_srtp_move(|index, by| { with_app(|app| app.srtp_move(index, by)); diff --git a/crates/voelin-ui/src/bind/rows.rs b/crates/voelin-ui/src/bind/rows.rs new file mode 100644 index 0000000..2f5540b --- /dev/null +++ b/crates/voelin-ui/src/bind/rows.rs @@ -0,0 +1,138 @@ +//! A Slint list model kept in step with plain rows: the view-model code +//! produces the new list, [`list::diff`](voelin_ui_vm::list::diff) finds +//! the row operations, and only those rows are converted and handed to the +//! `VecModel` (views redraw only the rows that changed: a client that +//! starts talking is one `set_row_data`). + +use std::cell::{Ref, RefCell}; +use std::rc::Rc; +use std::sync::Arc; + +use slint::{Model, ModelRc, SharedString, VecModel}; +use voelin_ui_vm::list::{Change, Changes, diff}; + +/// A plain row that a Slint model shows as another type. Implemented for +/// the bridge structs (`convert/items.rs`). +pub(crate) trait Row: Clone + PartialEq { + /// The Slint type of the row. + type Shown: Clone + 'static; + + /// The row as the window shows it. + fn show(&self) -> Self::Shown; +} + +impl Row for Arc { + type Shown = SharedString; + + fn show(&self) -> SharedString { + SharedString::from(&**self) + } +} + +/// The rows of a list as the view model made them (`T`), and the model the +/// window shows. +pub(crate) struct Rows { + model: Rc>, + rows: RefCell>, +} + +impl Default for Rows { + fn default() -> Self { + Self { model: Rc::default(), rows: RefCell::default() } + } +} + +impl Rows { + /// The model, for a window property. + pub fn model(&self) -> ModelRc { + ModelRc::from(self.model.clone()) + } + + /// The rows now. + pub fn rows(&self) -> Ref<'_, [T]> { + Ref::map(self.rows.borrow(), Vec::as_slice) + } + + /// Row `i` now. + pub fn get(&self, i: usize) -> Option { + self.rows.borrow().get(i).cloned() + } + + /// Change row `i` to `row` if it differs. + pub fn set(&self, i: usize, row: T) { + let mut rows = self.rows.borrow_mut(); + if rows.get(i).is_some_and(|old| *old != row) { + self.model.set_row_data(i, row.show()); + rows[i] = row; + } + } + + /// Append a row. + pub fn push(&self, row: T) { + self.model.push(row.show()); + self.rows.borrow_mut().push(row); + } + + /// Make the list `new`, with the fewest row operations. + pub fn sync(&self, new: &[T]) -> Changes { + let mut rows = self.rows.borrow_mut(); + let changes = diff(&rows, new); + for change in &changes.0 { + match *change { + Change::Update(i) => self.model.set_row_data(i, new[i].show()), + Change::Remove(i) => { + self.model.remove(i); + } + Change::Insert(i) => self.model.insert(i, new[i].show()), + } + } + changes.apply(&mut rows, new); + changes + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[derive(Clone, Debug, PartialEq)] + struct Plain(i32); + #[derive(Clone, Debug, PartialEq)] + struct Shown(i32); + impl Row for Plain { + type Shown = Shown; + + fn show(&self) -> Shown { + Shown(self.0 * 10) + } + } + + fn run(old: &[i32], new: &[i32]) -> Changes { + let rows: Rows = Rows::default(); + rows.sync(&old.iter().map(|&n| Plain(n)).collect::>()); + let changes = rows.sync(&new.iter().map(|&n| Plain(n)).collect::>()); + let shown: Vec = rows.model.iter().map(|s| s.0).collect(); + assert_eq!(shown, new.iter().map(|n| n * 10).collect::>(), "{old:?} -> {new:?}"); + assert_eq!(rows.rows.borrow().len(), new.len()); + changes + } + + #[test] + fn the_model_follows_the_rows() { + assert!(run(&[1, 2, 3], &[1, 2, 3]).is_empty()); + assert_eq!(run(&[1, 2, 3], &[1, 9, 3]).updated(), 1); + assert_eq!(run(&[1, 2, 3], &[1, 2, 7, 3]).inserted(), 1); + assert_eq!(run(&[1, 2, 3], &[1, 3]).removed(), 1); + run(&[], &[1, 2]); + run(&[1, 2], &[]); + run(&[1, 2, 1], &[1, 1, 2, 1]); + run(&[4, 5, 6], &[1, 2, 3, 4, 5, 6, 7]); + } + + #[test] + fn strings_are_rows() { + let rows: Rows> = Rows::default(); + rows.sync(&["720p".into(), "1080p".into()]); + assert_eq!(rows.model().row_data(1).as_deref(), Some("1080p")); + } +} diff --git a/crates/voelin-ui/src/bind/servers.rs b/crates/voelin-ui/src/bind/servers.rs index 54e9558..6425677 100644 --- a/crates/voelin-ui/src/bind/servers.rs +++ b/crates/voelin-ui/src/bind/servers.rs @@ -25,7 +25,7 @@ pub(super) fn wire(ui: &MainWindow) { }); bridge.on_join_channel(|cid| { with_app(|app| { - if let Some(session) = app.current { + if let Some(session) = app.state.current { app.join_channel(session, cid as ChannelId); } }); @@ -45,17 +45,21 @@ pub(super) fn wire(ui: &MainWindow) { bridge.on_push_to_talk(|on| { with_app(|app| app.command(|session| Command::SetTransmitting { session, on })); }); - bridge.on_edit_bookmark(|id| with_app(|app| app.bookmark_form(id as i64)).unwrap_or_default()); + bridge.on_edit_bookmark(|id| { + with_app(|app| app.bookmark_form(id as i64)).unwrap_or_default().into() + }); bridge.on_save_bookmark(|form| { - with_app(|app| app.save_bookmark(&form)); + with_app(|app| app.save_bookmark(&form.into())); + }); + bridge.on_save_and_connect(|form| { + with_app(|app| app.save_and_connect(&form.into())).unwrap_or(false) }); - bridge.on_save_and_connect(|form| with_app(|app| app.save_and_connect(&form)).unwrap_or(false)); bridge.on_delete_bookmark(|id| { with_app(|app| app.delete_bookmark(id as i64)); }); bridge.on_open_client(|id| with_app(|app| app.open_client(id as u16)).unwrap_or(false)); bridge.on_client_audio_changed(|form| { - with_app(|app| app.client_playback_changed(&form)); + with_app(|app| app.client_playback_changed(&form.into())); }); bridge.on_invite(|| with_app(|app| app.invite_link()).unwrap_or_default().into()); // Nav.copy, from any screen. diff --git a/crates/voelin-ui/src/bind/settings.rs b/crates/voelin-ui/src/bind/settings.rs index 7654074..d5979bd 100644 --- a/crates/voelin-ui/src/bind/settings.rs +++ b/crates/voelin-ui/src/bind/settings.rs @@ -13,10 +13,10 @@ pub(super) fn wire(ui: &MainWindow) { with_app(|app| app.close_settings()); }); bridge.on_audio_changed(|form| { - with_app(|app| app.audio_changed(&form)); + with_app(|app| app.audio_changed(&form.into())); }); bridge.on_toggle_mic_test(|| { - with_app(|app| app.set_mic_test(!app.mic_test)); + with_app(|app| app.set_mic_test(!app.state.mic_test)); }); bridge.on_apply_ptt(|enabled, key| { with_app(|app| app.apply_ptt(enabled, key.to_string())); @@ -34,7 +34,7 @@ pub(super) fn wire(ui: &MainWindow) { with_app(|app| app.voice_compact_changed(compact)); }); bridge.on_appearance_changed(|form| { - with_app(|app| app.appearance_changed(&form)); + with_app(|app| app.appearance_changed(&form.into())); }); bridge.on_set_crash_reports(|enabled| { with_app(|app| app.set_crash_reports(enabled)); diff --git a/crates/voelin-ui/src/bind/social.rs b/crates/voelin-ui/src/bind/social.rs index 5971719..cb04078 100644 --- a/crates/voelin-ui/src/bind/social.rs +++ b/crates/voelin-ui/src/bind/social.rs @@ -64,7 +64,7 @@ pub(super) fn wire(ui: &MainWindow) { with_app(|app| app.dm_volume(percent)); }); bridge.on_send_offline(|form| { - with_app(|app| app.send_offline(form)); + with_app(|app| app.send_offline(form.into())); }); // The bell. @@ -97,8 +97,10 @@ pub(super) fn wire(ui: &MainWindow) { bridge.on_toggle_event(|id| { with_app(|app| app.toggle_event(id)); }); - bridge.on_edit_event(|id| with_app(|app| app.edit_event(id)).unwrap_or_default()); - bridge.on_save_event(|form| with_app(|app| app.save_event(&form)).unwrap_or_default().into()); + bridge.on_edit_event(|id| with_app(|app| app.edit_event(id)).unwrap_or_default().into()); + bridge.on_save_event(|form| { + with_app(|app| app.save_event(&form.into())).unwrap_or_default().into() + }); bridge.on_delete_event(|id| { with_app(|app| app.delete_event(id)); }); diff --git a/crates/voelin-ui/src/bind/streams.rs b/crates/voelin-ui/src/bind/streams.rs index 93b02b9..ed30b87 100644 --- a/crates/voelin-ui/src/bind/streams.rs +++ b/crates/voelin-ui/src/bind/streams.rs @@ -4,9 +4,9 @@ use crate::app::{Bridge, with_app}; pub(crate) fn wire(bridge: &Bridge) { - bridge.on_open_share(|| with_app(|app| app.open_share()).unwrap_or_default()); + bridge.on_open_share(|| with_app(|app| app.open_share()).unwrap_or_default().into()); bridge.on_start_share(|form| { - with_app(|app| app.start_share(form)); + with_app(|app| app.start_share(form.into())); }); bridge.on_stop_share(|| { with_app(|app| app.stop_share()); diff --git a/crates/voelin-ui/src/bind/studio.rs b/crates/voelin-ui/src/bind/studio.rs index 4ed0b1c..7ffd743 100644 --- a/crates/voelin-ui/src/bind/studio.rs +++ b/crates/voelin-ui/src/bind/studio.rs @@ -52,13 +52,13 @@ pub(crate) fn wire(bridge: &StudioBridge) { with_app(|app| app.studio_add_picked(index(i))); }); bridge.on_add_source(|form| { - with_app(|app| app.studio_add_source(&form)); + with_app(|app| app.studio_add_source(&form.into())); }); bridge.on_source_form(|source| { - with_app(|app| app.studio_source_form(id(source))).unwrap_or_default() + with_app(|app| app.studio_source_form(id(source))).unwrap_or_default().into() }); bridge.on_apply_source(|form| { - with_app(|app| app.studio_apply_source(&form)); + with_app(|app| app.studio_apply_source(&form.into())); }); bridge.on_toggle_source(|source| { with_app(|app| app.studio_toggle_source(id(source))); @@ -93,7 +93,7 @@ pub(crate) fn wire(bridge: &StudioBridge) { with_app(|app| app.studio_set_output(&w, &h, &fps)); }); bridge.on_set_layer(|i, layer| { - with_app(|app| app.studio_set_layer(index(i), &layer)); + with_app(|app| app.studio_set_layer(index(i), &layer.into())); }); bridge.on_add_layer(|| { with_app(|app| app.studio_add_layer()); @@ -120,9 +120,10 @@ pub(crate) fn wire(bridge: &StudioBridge) { bridge.on_end_stream(|| { with_app(|app| app.studio_end()); }); - bridge.on_settings_form(|| with_app(|app| app.studio_settings_form()).unwrap_or_default()); + bridge + .on_settings_form(|| with_app(|app| app.studio_settings_form()).unwrap_or_default().into()); bridge.on_apply_settings(|form| { - with_app(|app| app.studio_apply_settings(&form)); + with_app(|app| app.studio_apply_settings(&form.into())); }); bridge.on_respond_viewer(|client, accept| { diff --git a/crates/voelin-ui/src/chat.rs b/crates/voelin-ui/src/chat.rs index 6444c64..5cf763a 100644 --- a/crates/voelin-ui/src/chat.rs +++ b/crates/voelin-ui/src/chat.rs @@ -6,7 +6,7 @@ //! The engine keeps the history: [`Event::ChatHistory`] is an upsert of //! messages by their local id (see `voelin_core::history`), so a tab holds //! the messages it was given, ordered by `(ts_ms, id)`, and the lines of -//! the selected tab are rebuilt from them with [`vm::list::sync`], which +//! the selected tab are rebuilt from them and synced ([`Rows::sync`]), which //! touches only the rows that changed. Sessions the engine keeps no history //! for (it does not know the server yet) fall back to [`Event::Chat`]. //! @@ -19,7 +19,7 @@ use std::collections::HashMap; use std::path::PathBuf; -use slint::{ComponentHandle, ModelRc}; +use slint::ComponentHandle; use voelin_core::gateway::Pin; use voelin_core::settings::CACHE_FETCH_IMAGES; use voelin_core::{ @@ -30,11 +30,13 @@ use voelin_gateway_proto::{ErrorCode, TopicInfo, feature}; use voelin_model::{ChatMessage, ChatTarget, HostMessageMode, ServerDetails}; use voelin_store::ChatRead; -use crate::app::{App, Bridge, ChatLine, ChatTab, FileItem, Msg, Nav, PinItem, SessionView, Tab}; +use crate::app::{App, Bridge, Nav, SessionView, Tab}; use crate::settings::UI_IMAGE_PREVIEW_KB; use crate::vm; use crate::vm::bbcode::LinkKind; +use crate::vm::bridge::{ChatLine, ChatTab, FileItem, PinItem}; use crate::vm::chat::{LineCache, LineCtx, Previous}; +use crate::vm::state::{Download, Msg, PinRow, store_target}; /// Where the server's welcome and host message keep what their lines were /// built from (`LineCache`), apart from the messages' ids. @@ -61,32 +63,6 @@ pub(crate) fn server_text<'a>(view: &'a SessionView, tab: &Tab, key: i32) -> Opt server_texts(&view.presence.server).get((-1 - key) as usize).map(|(text, _)| *text) } -/// The store's name of a chat. -pub(crate) 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(crate) struct Download { - /// The message's handle and which of its links this is. - pub key: i32, - pub index: usize, - pub name: String, - pub state: TransferState, -} - -/// A pinned message of a chat, with who pinned it. -pub(crate) struct PinRow { - pub key: i32, - pub message: HistoryMessage, - pub by: String, - pub ts_ms: i64, -} - /// "3 min ago", "yesterday", "12 Mar". fn ago(ts_ms: i64) -> String { let Some(then) = chrono::DateTime::from_timestamp_millis(ts_ms) else { return String::new() }; @@ -104,10 +80,10 @@ fn ago(ts_ms: i64) -> String { impl App { pub(crate) fn open_chat(&mut self, target: ChatTarget, focus: bool) { - let Some(id) = self.current else { return }; + let Some(id) = self.state.current else { return }; let index = self.chat_tab(id, target); if focus { - self.sessions.entry(id).or_default().focus_tab(index); + self.state.sessions.entry(id).or_default().focus_tab(index); self.prefetch_counts(); self.track_reading(); } @@ -122,7 +98,7 @@ impl App { ChatTarget::Private(uid) => self.peer_name(uid, None), _ => String::new(), }; - let view = self.sessions.entry(id).or_default(); + let view = self.state.sessions.entry(id).or_default(); if let Some(i) = view.tabs.iter().position(|t| t.target == target) { return i; } @@ -148,7 +124,7 @@ impl App { view.set_current_tab(index); view.tabs[index].topic = None; } - if let Some(id) = self.current { + if let Some(id) = self.state.current { self.fetch_previews(id); } self.prefetch_counts(); @@ -158,13 +134,13 @@ impl App { } pub(crate) fn close_tab(&mut self, index: usize) { - let Some(id) = self.current else { return }; - let view = self.sessions.entry(id).or_default(); + let Some(id) = self.state.current else { return }; + let view = self.state.sessions.entry(id).or_default(); if index == 0 || index >= view.tabs.len() { return; } self.save_read(id, index); - let tab = self.sessions.entry(id).or_default().remove_tab(index); + let tab = self.state.sessions.entry(id).or_default().remove_tab(index); self.engine.send(Command::CloseChat { session: id as u64, target: tab.target }); self.prefetch_counts(); self.track_reading(); @@ -173,8 +149,8 @@ impl App { } pub(crate) fn send_message(&mut self, text: String) { - let Some(id) = self.current else { return }; - let Some(view) = self.sessions.get(&id) else { return }; + let Some(id) = self.state.current else { return }; + let Some(view) = self.state.sessions.get(&id) else { return }; let target = view.tabs[view.current_tab].target.clone(); self.engine.send(Command::SendChat { session: id as u64, target, text }); } @@ -198,10 +174,10 @@ impl App { /// A live message of a session without stored history: appended as it /// comes, without an id. pub(crate) fn add_message(&mut self, id: i64, message: ChatMessage) { - let current = self.current == Some(id); + let current = self.state.current == Some(id); let reading = self.reads_now(id); let new = !self.is_own(id, &message); - let view = self.sessions.entry(id).or_default(); + let view = self.state.sessions.entry(id).or_default(); let title = vm::chat::tab_title(&view.presence, &message.target, &message.author_name); let index = Self::tab_for(view, &message.target, || title); let seen = reading && view.current_tab == index; @@ -231,7 +207,7 @@ impl App { source: HistorySource, complete: bool, ) { - let current = self.current == Some(id); + let current = self.state.current == Some(id); let reading = self.reads_now(id); // A private chat is named after the peer, whoever wrote first. let peer = match target { @@ -244,7 +220,7 @@ impl App { )), _ => None, }; - let view = self.sessions.entry(id).or_default(); + let view = self.state.sessions.entry(id).or_default(); let author = messages.first().map_or("", |m| m.message.author_name.as_str()); let title = peer.unwrap_or_else(|| vm::chat::tab_title(&view.presence, target, author)); let index = Self::tab_for(view, target, || title); @@ -308,8 +284,8 @@ impl App { /// The page of messages before the oldest one shown. pub(crate) fn load_older(&mut self) { - let Some(id) = self.current else { return }; - let Some(view) = self.sessions.get_mut(&id) else { return }; + let Some(id) = self.state.current else { return }; + let Some(view) = self.state.sessions.get_mut(&id) else { return }; let tab = &mut view.tabs[view.current_tab]; if tab.loading || tab.complete { return; @@ -329,7 +305,7 @@ impl App { /// The lines of a tab's messages (`main`) or of its open topic, grouped /// and with everything the row shows (also the stream chat of the - /// Stream Studio, studio.rs). The server chat starts with what the + /// Stream Studio, studio/). The server chat starts with what the /// server says to everyone who connects ([`Self::server_lines`]). pub(crate) fn lines_of(&self, view: &SessionView, tab: &Tab, main: bool) -> Vec { let messages = if main { &tab.messages } else { &tab.topic_messages }; @@ -384,7 +360,7 @@ impl App { cache.keep(ids, messages.len()); } // Pokes of a private chat's peer show among its messages. - if let (ChatTarget::Private(uid), Some(session)) = (&tab.target, self.current) { + if let (ChatTarget::Private(uid), Some(session)) = (&tab.target, self.state.current) { lines.extend(self.poke_lines(session, uid)); lines.sort_by_key(|(ts, _)| *ts); } @@ -466,14 +442,11 @@ impl App { let Some(ui) = self.ui.upgrade() else { return }; let bridge = ui.global::(); let Some(view) = self.view() else { - vm::list::sync( - &self.models.tabs, - &[ChatTab { title: "Server".into(), ..Default::default() }], - ); + self.models.tabs.sync(&[ChatTab { title: "Server".into(), ..Default::default() }]); *self.models.strip.borrow_mut() = vec![0]; bridge.set_current_tab(0); bridge.set_current_chat(0); - let empty = ModelRc::from(self.models.no_chat.clone()); + let empty = self.models.no_chat.model(); if bridge.get_messages() != empty { bridge.set_messages(empty); } @@ -523,7 +496,7 @@ impl App { } }) .collect(); - vm::list::sync(&self.models.tabs, &tabs); + self.models.tabs.sync(&tabs); *self.models.strip.borrow_mut() = strip; if bridge.get_current_tab() != current { bridge.set_current_tab(current); @@ -535,9 +508,9 @@ impl App { if view.has_history() { let lines = self.lines_of(view, tab, true); divider = lines.iter().position(|l| l.unread_start); - vm::list::sync(&tab.lines, &lines); + tab.lines.sync(&lines); } - let lines = ModelRc::from(tab.lines.clone()); + let lines = tab.lines.model(); if bridge.get_messages() != lines { bridge.set_messages(lines); } @@ -546,7 +519,7 @@ impl App { .divider .and_then(|d| tab.messages.iter().position(|m| m.message.id == d)) .map_or(&[][..], |i| &tab.messages[i..]); - let session = self.current.unwrap_or_default(); + let session = self.state.current.unwrap_or_default(); let count = new.iter().filter(|m| !self.is_own(session, &m.message.message)).count(); bridge.set_unread_index(divider.map_or(-1, |i| i as i32)); bridge.set_unread_count(count as i32); @@ -586,14 +559,14 @@ impl App { } }) .collect(); - vm::list::sync(&self.models.pins, &pins); - let filter = self.topic_filter.trim().to_lowercase(); + self.models.pins.sync(&pins); + let filter = self.state.topic_filter.trim().to_lowercase(); let now = chrono::Utc::now().timestamp_millis(); - let topics: Vec = tab + let topics: Vec = tab .topics .iter() .filter(|t| filter.is_empty() || t.title.to_lowercase().contains(&filter)) - .map(|t| crate::app::TopicItem { + .map(|t| vm::bridge::TopicItem { id: t.id as i32, title: t.title.clone().into(), creator: t.creator.name.clone().into(), @@ -609,7 +582,7 @@ impl App { archived: t.archived, }) .collect(); - vm::list::sync(&self.models.topics, &topics); + self.models.topics.sync(&topics); bridge.set_current_topic(tab.topic.map_or(-1, |t| t as i32)); bridge.set_topic_title( tab.topic @@ -618,7 +591,7 @@ impl App { .unwrap_or_default() .into(), ); - vm::list::sync(&self.models.topic_messages, &self.lines_of(view, tab, false)); + self.models.topic_messages.sync(&self.lines_of(view, tab, false)); } /// A link in a message was clicked (`masked`: its text shows something @@ -656,7 +629,7 @@ impl App { /// New messages of session `id` in its current tab are read as they /// come: they are on screen in the focused window. fn reads_now(&self, id: i64) -> bool { - self.focused && self.current == Some(id) && self.chat_shown() + self.state.focused && self.state.current == Some(id) && self.chat_shown() } /// After anything that can change which chat is on screen (a tab, a @@ -664,26 +637,26 @@ impl App { /// loses its divider; the one on screen, in the focused window, is read /// (its divider above what was new). `true` if a tab changed. pub(crate) fn track_reading(&mut self) -> bool { - let open = self.current.filter(|_| self.chat_shown()).and_then(|id| { - let view = self.sessions.get(&id)?; + let open = self.state.current.filter(|_| self.chat_shown()).and_then(|id| { + let view = self.state.sessions.get(&id)?; Some((id, view.tabs.get(view.current_tab)?.target.clone())) }); let mut changed = false; - if open != self.reading { - if let Some((id, target)) = self.reading.take() + if open != self.state.reading { + if let Some((id, target)) = self.state.reading.take() && let Some(index) = self.tab_index(id, &target) { - let tab = &mut self.sessions.entry(id).or_default().tabs[index]; + let tab = &mut self.state.sessions.entry(id).or_default().tabs[index]; changed |= tab.divider.take().is_some(); self.save_read(id, index); } - self.reading = open.clone(); + self.state.reading = open.clone(); } - if let (true, Some((id, target))) = (self.focused, open) + if let (true, Some((id, target))) = (self.state.focused, open) && let Some(index) = self.tab_index(id, &target) { let own_uids = &self.social.own_uids; - let view = self.sessions.entry(id).or_default(); + let view = self.state.sessions.entry(id).or_default(); let own_client = view.state.own_client; let tab = &mut view.tabs[index]; let before = (tab.unread, tab.divider); @@ -695,7 +668,7 @@ impl App { /// Where the tab of `target` is in session `id`. fn tab_index(&self, id: i64, target: &ChatTarget) -> Option { - self.sessions.get(&id)?.tabs.iter().position(|t| t.target == *target) + self.state.sessions.get(&id)?.tabs.iter().position(|t| t.target == *target) } /// The current chat came on screen or left it (`Nav.chat-shown`). @@ -710,7 +683,7 @@ impl App { /// only). #[cfg(not(target_os = "android"))] pub(crate) fn window_focused(&mut self, focused: bool) { - self.focused = focused; + self.state.focused = focused; if self.track_reading() { self.refresh_chat(); self.refresh_servers(); @@ -720,8 +693,8 @@ impl App { /// The current chat is read (the bar over its messages): the divider /// goes. pub(crate) fn mark_read(&mut self) { - let Some(id) = self.current else { return }; - let Some(view) = self.sessions.get_mut(&id) else { return }; + let Some(id) = self.state.current else { return }; + let Some(view) = self.state.sessions.get_mut(&id) else { return }; let index = view.current_tab; let tab = &mut view.tabs[index]; tab.divider = None; @@ -737,7 +710,7 @@ impl App { if self.demo_ui { return; } - let Some(view) = self.sessions.get_mut(&id) else { return }; + let Some(view) = self.state.sessions.get_mut(&id) else { return }; let Some(server_uid) = view.state.server_uid.as_deref() else { return }; let Some(tab) = view.tabs.get_mut(index) else { return }; let Some((ts_ms, message)) = tab.read.filter(|r| tab.stored_read != Some(*r)) else { @@ -759,7 +732,7 @@ impl App { /// Store where every chat of session `id` was read (it ended, or the /// app exits). pub(crate) fn save_reads(&mut self, id: i64) { - let count = self.sessions.get(&id).map_or(0, |v| v.tabs.len()); + let count = self.state.sessions.get(&id).map_or(0, |v| v.tabs.len()); for index in 0..count { self.save_read(id, index); } @@ -769,7 +742,7 @@ impl App { /// server is known (or another one: the gateway's id wins): its tabs /// start from there, now and when they open. pub(crate) fn load_reads(&mut self, id: i64) { - let Some(view) = self.sessions.get_mut(&id) else { return }; + let Some(view) = self.state.sessions.get_mut(&id) else { return }; if self.demo_ui || view.state.server_uid.is_none() || view.reads_of == view.state.server_uid { return; @@ -796,8 +769,8 @@ impl App { } pub(crate) fn gateway_update(&mut self, id: i64, update: GatewayUpdate) { - let current = self.current == Some(id); - let view = self.sessions.entry(id).or_default(); + let current = self.state.current == Some(id); + let view = self.state.sessions.entry(id).or_default(); match update { GatewayUpdate::Connected { capabilities, .. } | GatewayUpdate::Capabilities { capabilities } => { @@ -978,8 +951,8 @@ impl App { /// The topics drawer's search. pub(crate) fn search_topics(&mut self, text: String) { - if self.topic_filter != text { - self.topic_filter = text; + if self.state.topic_filter != text { + self.state.topic_filter = text; self.refresh_chat(); } } @@ -1026,7 +999,7 @@ impl App { /// Download a file a message links, into the download folder. pub(crate) fn download_file(&mut self, key: i32, index: i32) { - let Some(id) = self.current else { return }; + let Some(id) = self.state.current else { return }; let index = index.max(0) as usize; let Some(file) = self.message_of(key).and_then(|m| m.message.file_refs().into_iter().nth(index)) @@ -1035,7 +1008,7 @@ impl App { }; let dir = dirs::download_dir().unwrap_or_else(|| PathBuf::from(".")); let path = dir.join(&file.name); - let view = self.sessions.entry(id).or_default(); + let view = self.state.sessions.entry(id).or_default(); let transfer = view.next_transfer; view.next_transfer += 1; view.downloads.insert( @@ -1054,10 +1027,10 @@ impl App { pub(crate) fn transfer_progress(&mut self, id: i64, transfer: u64, state: TransferState) { // An upload from the composer: post the file's link once it is up. - if let Some((_, channel, name)) = self.uploads.get(&transfer).cloned() { + if let Some((_, channel, name)) = self.state.uploads.get(&transfer).cloned() { match &state { TransferState::Done { size, .. } => { - self.uploads.remove(&transfer); + self.state.uploads.remove(&transfer); let file = voelin_model::FileRef { channel, path: "/".into(), @@ -1073,11 +1046,11 @@ impl App { self.set_status(format!("{name} shared")); } TransferState::Failed(e) => { - self.uploads.remove(&transfer); + self.state.uploads.remove(&transfer); self.set_status(format!("Could not upload {name}: {e}")); } TransferState::Cancelled => { - self.uploads.remove(&transfer); + self.state.uploads.remove(&transfer); } _ => {} } @@ -1087,14 +1060,14 @@ impl App { return; } let done = matches!(state, TransferState::Done { .. }); - let view = self.sessions.entry(id).or_default(); + let view = self.state.sessions.entry(id).or_default(); let Some(entry) = view.downloads.get_mut(&transfer) else { return }; entry.state = state; let name = entry.name.clone(); if done { self.set_status(format!("{name} downloaded")); } - if self.current == Some(id) { + if self.state.current == Some(id) { self.refresh_chat(); } } @@ -1102,8 +1075,8 @@ impl App { /// Attach a file to the current channel chat: ask for one, upload it /// into the channel and post its link. pub(crate) fn attach_file(&mut self) { - let Some(id) = self.current else { return }; - let Some(view) = self.sessions.get(&id) else { return }; + let Some(id) = self.state.current else { return }; + let Some(view) = self.state.sessions.get(&id) else { return }; let ChatTarget::Channel(channel) = view.tabs[view.current_tab].target else { self.set_status("Files can be attached to a channel's chat."); return; @@ -1126,10 +1099,10 @@ impl App { /// Upload a file into a channel and link it in the chat once it is up. pub(crate) fn upload(&mut self, id: i64, channel: u64, from: PathBuf) { let Some(name) = from.file_name().map(|n| n.to_string_lossy().to_string()) else { return }; - let view = self.sessions.entry(id).or_default(); + let view = self.state.sessions.entry(id).or_default(); let transfer = view.next_transfer; view.next_transfer += 1; - self.uploads.insert(transfer, (id, channel, name.clone())); + self.state.uploads.insert(transfer, (id, channel, name.clone())); self.engine.send(Command::UploadFile { session: id as u64, transfer, diff --git a/crates/voelin-ui/src/dev.rs b/crates/voelin-ui/src/dev.rs index 9973194..597d088 100644 --- a/crates/voelin-ui/src/dev.rs +++ b/crates/voelin-ui/src/dev.rs @@ -83,10 +83,9 @@ use voelin_model::{ }; use voelin_store::{Bookmark, MessageSource}; -use crate::app::{ - App, Bridge, MainWindow, MobileTab, Nav, Page, RecordingItem, SettingsSection, with_app, -}; +use crate::app::{App, Bridge, MainWindow, MobileTab, Nav, Page, SettingsSection, with_app}; use crate::settings::LastVoice; +use crate::vm::bridge::RecordingItem; /// The switches read at start. #[derive(Clone, Debug, Default)] @@ -185,7 +184,7 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running { } Some("observe") => { with_app(|app| { - if let Some(id) = app.current { + if let Some(id) = app.state.current { app.observe(id); } }); @@ -215,7 +214,7 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running { } // The current server's dialog, Advanced open. "bookmark" if arg == "edit" => { - if let Some(id) = with_app(|app| app.current).flatten() { + if let Some(id) = with_app(|app| app.state.current).flatten() { nav.invoke_edit_server(id as i32); } } @@ -426,9 +425,9 @@ fn late( /// The current chat's read marker `back` messages before its end, as if /// they came while away, its "New" divider shown (`VOELIN_OPEN=unread`). fn open_unread(app: &mut App, back: usize) { - let Some(id) = app.current else { return }; + let Some(id) = app.state.current else { return }; let own_uids = app.social.own_uids.clone(); - let Some(view) = app.sessions.get_mut(&id) else { return }; + let Some(view) = app.state.sessions.get_mut(&id) else { return }; let own_client = view.state.own_client; let own = |m: &ChatMessage| crate::social::own_message(&own_uids, own_client, m); let index = view.current_tab; @@ -484,7 +483,7 @@ fn save_png(image: &SharedPixelBuffer, path: &std::path::Path) -> Re /// channel, which asks for its password; `wrong` as if the server had /// refused one. fn open_channel_password(app: &mut App, wrong: bool) { - let Some(session) = app.current else { return }; + let Some(session) = app.state.current else { return }; let locked = app .view() .and_then(|v| v.presence.channels.values().filter(|c| c.has_password).map(|c| c.id).min()); @@ -550,7 +549,7 @@ fn demo_ui(app: &mut App) { client_version: None, cached_server_icon: None, }; - app.bookmarks = vec![ + app.state.bookmarks = vec![ Bookmark { gateway_url: Some("wss://gw.nightfall.example/v1".into()), ..bookmark(DEMO, "Nightfall Guild", "ts.nightfall.example:9987") @@ -560,12 +559,12 @@ fn demo_ui(app: &mut App) { ]; // Home's "Continue where you left off": a channel of a server without // voice, so it shows Join. - app.settings.last_voice = Some(LastVoice { + app.state.settings.last_voice = Some(LastVoice { bookmark: DEMO + 1, address: "pixel.example".into(), channel: vec!["Art Corner".into()], }); - app.current = Some(DEMO); + app.state.current = Some(DEMO); let session = DEMO as u64; let mut p = Presence { server_name: "Nightfall Guild".into(), ..Default::default() }; @@ -941,7 +940,7 @@ fn demo_social(app: &mut App) { // The samples came one by one, as new ones do: all are read (no "New" // line, which a gateway page on screen gets), but for Mira's and // Lumen's messages, which came while away. - for view in app.sessions.values_mut() { + for view in app.state.sessions.values_mut() { for tab in &mut view.tabs { tab.divider = None; tab.catch_up(); @@ -984,7 +983,7 @@ fn demo_social(app: &mut App) { }); // The pictures of the links, as if downloaded. - if let Some(view) = app.sessions.get_mut(&DEMO) { + if let Some(view) = app.state.sessions.get_mut(&DEMO) { for (channel, name) in [(2, "night-castle.png"), (2, "guild-banner.png"), (2, "map-notes.png")] { @@ -996,7 +995,7 @@ fn demo_social(app: &mut App) { }; view.extra.previews.insert( crate::previews::link_key(&file), - crate::previews::Preview::Ready(voelin_core::Bytes( + crate::vm::state::Preview::Ready(voelin_core::Bytes( demo_picture(640, 360, name.len() as u32).into(), )), ); @@ -1195,15 +1194,12 @@ fn demo_social(app: &mut App) { clip: name.contains("clip"), path: format!("/tmp/{name}").into(), }; - crate::vm::list::sync( - &app.models.social.recordings, - &[ - recording("raid-night-2026-10-02.webm", "1.2 GB · 2 Oct 22:41"), - recording("clip-boss-down.mkv", "38.4 MB · 2 Oct 21:57"), - recording("lands-between-stream.mkv", "2.8 GB · 28 Sep 20:12"), - recording("clip-lucky-parry.mkv", "12.1 MB · 28 Sep 19:40"), - ], - ); + app.models.social.recordings.sync(&[ + recording("raid-night-2026-10-02.webm", "1.2 GB · 2 Oct 22:41"), + recording("clip-boss-down.mkv", "38.4 MB · 2 Oct 21:57"), + recording("lands-between-stream.mkv", "2.8 GB · 28 Sep 20:12"), + recording("clip-lucky-parry.mkv", "12.1 MB · 28 Sep 19:40"), + ]); app.refresh_chats(); app.refresh_people(); app.refresh_home(); @@ -1246,7 +1242,7 @@ fn demo_pictures(app: &mut App) { }; let mut events = vec![Event::ServerDetails { session, - address: app.bookmarks.iter().find(|b| b.id == DEMO).unwrap().address.clone(), + address: app.state.bookmarks.iter().find(|b| b.id == DEMO).unwrap().address.clone(), details: Arc::new(voelin_model::ServerDetails { icon: DEMO_SERVER_ICON, ..Default::default() @@ -1638,9 +1634,8 @@ fn demo_chat(app: &mut App, session: u64) { None, ), ]; - let mut id = 1; let mut pinned: Vec = Vec::new(); - for (chat, author, client, text, ago, relay, reactions, pin, topic) in lines { + for (id, (chat, author, client, text, ago, relay, reactions, pin, topic)) in (1..).zip(lines) { let target = if chat == DEMO { ChatTarget::Channel(2) } else { ChatTarget::Server }; let message = HistoryMessage { id, @@ -1671,7 +1666,6 @@ fn demo_chat(app: &mut App, session: u64) { source: HistorySource::Gateway, complete: false, }); - id += 1; } // A server chat besides the channel chat. app.handle_event(Event::ChatHistory { diff --git a/crates/voelin-ui/src/events.rs b/crates/voelin-ui/src/events.rs index 4758555..96e1256 100644 --- a/crates/voelin-ui/src/events.rs +++ b/crates/voelin-ui/src/events.rs @@ -3,13 +3,16 @@ //! home page), our permissions there, its configuration (gateway //! administration). The pins, reactions and topics are in `chat.rs`. +use std::sync::Arc; + use slint::{ComponentHandle, SharedString}; use voelin_core::{Command, GatewayRequest, GatewayUpdate}; use voelin_gateway_proto::{Action, EventKind, EventQuery, EventSpec, RsvpStatus, feature}; -use crate::app::{App, Bridge, EventForm, EventItem}; +use crate::app::{App, Bridge}; use crate::social::{NoticeKind, NoticeTarget, now_ms}; use crate::vm; +use crate::vm::bridge::{EventForm, EventItem}; use crate::vm::social::{date_block, event_when, format_local, parse_local, soon}; impl App { @@ -26,7 +29,7 @@ impl App { use GatewayUpdate as U; let mut ask: Vec = Vec::new(); let mut remind = None; - let extra = &mut self.sessions.entry(id).or_default().extra; + let extra = &mut self.state.sessions.entry(id).or_default().extra; match update { U::Connected { uid, capabilities, .. } => { extra.gateway_uid = Some(uid.clone()); @@ -118,8 +121,8 @@ impl App { /// The events page of the current server was opened. pub(crate) fn open_events(&mut self) { - let Some(id) = self.current else { return }; - let loaded = self.sessions.get(&id).is_some_and(|v| v.extra.events_loaded); + let Some(id) = self.state.current else { return }; + let loaded = self.state.sessions.get(&id).is_some_and(|v| v.extra.events_loaded); if !loaded { self.gateway_to(id, GatewayRequest::Events { query: EventQuery::default() }); } @@ -205,41 +208,40 @@ impl App { editable: moderate || extra.gateway_uid.as_deref() == Some(e.creator.uid.as_str()), soon: soon(e.spec.start_ms, e.spec.end_ms, now).into(), - attendees: crate::app::model( - e.attendees - .iter() - .map(|a| { - let status = match a.status { - RsvpStatus::Going => "going", - RsvpStatus::Maybe => "maybe", - RsvpStatus::NotGoing => "not going", - RsvpStatus::Unknown => "?", - }; - SharedString::from(format!("{} ({status})", a.user.name)) - }) - .collect(), - ), + attendees: e + .attendees + .iter() + .map(|a| { + let status = match a.status { + RsvpStatus::Going => "going", + RsvpStatus::Maybe => "maybe", + RsvpStatus::NotGoing => "not going", + RsvpStatus::Unknown => "?", + }; + Arc::::from(format!("{} ({status})", a.user.name)) + }) + .collect(), expanded: extra.expanded.contains(&e.id), } }) .collect() }) .unwrap_or_default(); - vm::list::sync(&self.models.social.events, &items); + self.models.social.events.sync(&items); } /// Answer an event ("" withdraws the answer). pub(crate) fn rsvp(&mut self, event_id: i32, status: &str) { - let Some(id) = self.current else { return }; + let Some(id) = self.state.current else { return }; let status = (!status.is_empty()).then(|| RsvpStatus::parse(status)); self.gateway_to(id, GatewayRequest::Rsvp { event_id: i64::from(event_id), status }); } /// Show or hide who answered (fetching the event with its attendees). pub(crate) fn toggle_event(&mut self, event_id: i32) { - let Some(id) = self.current else { return }; + let Some(id) = self.state.current else { return }; let event_id = i64::from(event_id); - let view = self.sessions.entry(id).or_default(); + let view = self.state.sessions.entry(id).or_default(); if !view.extra.expanded.remove(&event_id) { view.extra.expanded.insert(event_id); self.gateway_to(id, GatewayRequest::GetEvent { id: event_id }); @@ -275,7 +277,7 @@ impl App { /// Create or change an event; the reason when the form is not right. pub(crate) fn save_event(&mut self, form: &EventForm) -> String { - let Some(id) = self.current else { return "No server selected.".into() }; + let Some(id) = self.state.current else { return "No server selected.".into() }; let Some(start_ms) = parse_local(&form.start) else { return "Write the start as YYYY-MM-DD HH:MM.".into(); }; @@ -289,7 +291,7 @@ impl App { } }; let channels = self.event_channels(); - let text = |s: &slint::SharedString| Some(s.to_string()).filter(|s| !s.trim().is_empty()); + let text = |s: &Arc| Some(s.to_string()).filter(|s| !s.trim().is_empty()); let spec = EventSpec { title: form.title.trim().to_owned(), description: form.description.to_string(), @@ -313,14 +315,14 @@ impl App { } pub(crate) fn delete_event(&mut self, event_id: i32) { - if let Some(id) = self.current { + if let Some(id) = self.state.current { self.gateway_to(id, GatewayRequest::DeleteEvent { id: i64::from(event_id) }); } } /// Watch the stream of a live scheduled stream. pub(crate) fn watch_event(&mut self, event_id: i32) { - let Some(id) = self.current else { return }; + let Some(id) = self.state.current else { return }; let stream = self .view() .and_then(|v| v.extra.events.iter().find(|e| e.id == i64::from(event_id))) diff --git a/crates/voelin-ui/src/home.rs b/crates/voelin-ui/src/home.rs index eeedd70..532fa41 100644 --- a/crates/voelin-ui/src/home.rs +++ b/crates/voelin-ui/src/home.rs @@ -9,11 +9,10 @@ use std::path::{Path, PathBuf}; use slint::ComponentHandle; use voelin_core::VoiceState; -use crate::app::{ - App, Bridge, HappeningItem, LiveItem, Page, RecordingItem, ResumeItem, ServerItem, -}; +use crate::app::{App, Bridge, Page}; use crate::settings::LastVoice; use crate::vm; +use crate::vm::bridge::{HappeningItem, LiveItem, RecordingItem, ResumeItem, ServerItem}; use crate::vm::home::ResumeAction; use crate::vm::social::{event_when, plain}; @@ -30,8 +29,10 @@ impl App { /// streaming. fn live_rooms(&self) -> Vec { let mut rooms = Vec::new(); - for (b, backdrop) in self.bookmarks.iter().zip(vm::servers::tints(&self.bookmarks)) { - let Some(view) = self.sessions.get(&b.id) else { continue }; + for (b, backdrop) in + self.state.bookmarks.iter().zip(vm::servers::tints(&self.state.bookmarks)) + { + let Some(view) = self.state.sessions.get(&b.id) else { continue }; let channel_of = |cid: Option| { cid.and_then(|c| view.presence.channels.get(&c)) .map(|c| vm::tree::channel_title(c).0.to_owned()) @@ -45,7 +46,7 @@ impl App { let avatar = match (client, uid) { (Some(c), _) if view.avatar(c).is_some() => vm::avatar::image(view.avatar(c)), (_, Some(uid)) => self.avatar_of(uid), - _ => slint::Image::default(), + _ => vm::ImageRef::default(), }; LiveItem { session: b.id as i32, @@ -124,8 +125,8 @@ impl App { let now = crate::social::now_ms(); let mut events: Vec<(i64, HappeningItem, Happening)> = Vec::new(); let mut news = Vec::new(); - for b in &self.bookmarks { - let Some(view) = self.sessions.get(&b.id) else { continue }; + for b in &self.state.bookmarks { + let Some(view) = self.state.sessions.get(&b.id) else { continue }; for e in &view.extra.events { let ends = e.spec.end_ms.unwrap_or(e.spec.start_ms + 3 * 3_600_000); if ends < now { @@ -184,16 +185,16 @@ impl App { /// `refresh_chats`). pub(crate) fn refresh_home(&self) { let m = &self.models.social; - vm::list::sync(&m.live, &self.live_rooms()); + m.live.sync(&self.live_rooms()); let items: Vec = self.happenings().into_iter().map(|(i, _)| i).collect(); - vm::list::sync(&m.happenings, &items); + m.happenings.sync(&items); } /// A live room's card: watch it at once in our channel, else go to its /// server (and the streamer's channel, watching once there). pub(crate) fn watch_live(&mut self, session: i64, id: &str) { self.show_server(session); - let Some(view) = self.sessions.get(&session) else { return }; + let Some(view) = self.state.sessions.get(&session) else { return }; if view.streams_available() && view.streams.iter().any(|s| s.id == id) { self.watch_stream(id.to_owned()); return; @@ -233,8 +234,9 @@ impl App { } fn last_resume(&self) -> Option { - let voice = |id| self.sessions.get(&id).map_or(VoiceState::Disconnected, |v| v.state.voice); - vm::home::resume(self.settings.last_voice.as_ref(), &self.bookmarks, voice) + let voice = + |id| self.state.sessions.get(&id).map_or(VoiceState::Disconnected, |v| v.state.voice); + vm::home::resume(self.state.settings.last_voice.as_ref(), &self.state.bookmarks, voice) } /// Home's "Continue where you left off", its server as the rail shows @@ -253,7 +255,7 @@ impl App { icon: server.icon.clone(), channel: resume.title().into(), open: resume.action == ResumeAction::Open, - connecting: server.status == "connecting", + connecting: &*server.status == "connecting", } } @@ -273,17 +275,17 @@ impl App { if self.demo_ui { return false; } - let Some(view) = self.sessions.get(&session) else { return false }; + let Some(view) = self.state.sessions.get(&session) else { return false }; let (VoiceState::Connected, Some(cid)) = (view.state.voice, view.state.own_channel) else { return false; }; let channel = vm::tree::channel_path(&view.presence, cid); let Some(b) = self.bookmark(session).filter(|_| !channel.is_empty()) else { return false }; let last = LastVoice { bookmark: session, address: b.address.clone(), channel }; - if self.settings.last_voice.as_ref() == Some(&last) { + if self.state.settings.last_voice.as_ref() == Some(&last) { return false; } - self.settings.last_voice = Some(last); + self.state.settings.last_voice = Some(last); self.store_settings(); true } @@ -304,7 +306,7 @@ impl App { } let dir = self.recordings_dir(); let items = recordings_in(&dir); - vm::list::sync(&self.models.social.recordings, &items); + self.models.social.recordings.sync(&items); if let Some(ui) = self.ui.upgrade() { ui.global::().set_recordings_dir(dir.display().to_string().into()); } diff --git a/crates/voelin-ui/src/identities.rs b/crates/voelin-ui/src/identities.rs index c626e74..4fcd77f 100644 --- a/crates/voelin-ui/src/identities.rs +++ b/crates/voelin-ui/src/identities.rs @@ -2,23 +2,13 @@ //! `Store::default_identity`), chosen under Settings → Profiles, and the //! import of the official clients' identities on start //! (`voelin_core::ts::identity::import_new`, app.rs). The rest of the Profiles -//! page is in `settings_pages.rs`. +//! page is in `settings_pages/`. use tracing::warn; use voelin_core::settings::IDENTITY_IMPORT; -use voelin_store::IdentityOrigin; use crate::app::App; -/// Where an identity came from, as Profiles says it. -pub(crate) fn origin_label(origin: IdentityOrigin) -> &'static str { - match origin { - IdentityOrigin::Created => "Made in Voelin", - IdentityOrigin::Imported => "Imported", - IdentityOrigin::User => "Chosen by you", - } -} - impl App { /// The user's choice of the identity servers see us as, from the next /// connection on; no import replaces it. @@ -51,16 +41,3 @@ impl App { self.refresh_identities(); } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn rows_say_where_an_identity_came_from() { - assert_eq!(origin_label(IdentityOrigin::Created), "Made in Voelin"); - assert_eq!(origin_label(IdentityOrigin::Imported), "Imported"); - // Made by the app, then chosen: an import never replaces it. - assert_eq!(origin_label(IdentityOrigin::User), "Chosen by you"); - } -} diff --git a/crates/voelin-ui/src/inbox.rs b/crates/voelin-ui/src/inbox.rs index af7593c..9eaa569 100644 --- a/crates/voelin-ui/src/inbox.rs +++ b/crates/voelin-ui/src/inbox.rs @@ -65,8 +65,8 @@ pub(crate) fn take() { impl App { fn share(&mut self, nav: &Nav<'_>, text: Option, files: Vec) { - let current = self.current.and_then(|id| { - let view = self.sessions.get(&id)?; + let current = self.state.current.and_then(|id| { + let view = self.state.sessions.get(&id)?; let tab = &view.tabs[view.current_tab]; // Files go to the channel of the chat, else to ours. let channel = match tab.target { diff --git a/crates/voelin-ui/src/lib.rs b/crates/voelin-ui/src/lib.rs index 69ca05d..6bcc099 100644 --- a/crates/voelin-ui/src/lib.rs +++ b/crates/voelin-ui/src/lib.rs @@ -6,7 +6,6 @@ mod bind; mod camera; mod chat; mod dev; -mod emoji; mod events; mod home; mod hotkey; @@ -19,14 +18,15 @@ mod messages; mod popout; mod previews; mod servers; -mod settings; mod settings_page; mod settings_pages; mod social; mod streams; mod studio; mod video; -mod vm; + +// The view models live in their own crate; the modules keep their old paths. +use voelin_ui_vm::{self as vm, emoji, settings}; pub use app::{HostedEngine, RunOptions, run}; pub use inbox::{Request, request}; diff --git a/crates/voelin-ui/src/links.rs b/crates/voelin-ui/src/links.rs index 2445e78..3e73e26 100644 --- a/crates/voelin-ui/src/links.rs +++ b/crates/voelin-ui/src/links.rs @@ -29,9 +29,14 @@ impl App { } }; let in_voice = |id: i64| { - self.sessions.get(&id).is_some_and(|v| v.state.voice == VoiceState::Connected) + self.state.sessions.get(&id).is_some_and(|v| v.state.voice == VoiceState::Connected) }; - match vm::servers::link_server(&self.bookmarks, &link.address(), self.current, in_voice) { + match vm::servers::link_server( + &self.state.bookmarks, + &link.address(), + self.state.current, + in_voice, + ) { Some((id, true)) => self.move_by_link(id, &link), saved => self.open_link_form(saved.map(|(id, _)| id), &link), } @@ -41,7 +46,7 @@ impl App { fn move_by_link(&mut self, session: i64, link: &ServerLink) { self.show_server(session); let Some(path) = &link.channel else { return }; - let Some(view) = self.sessions.get_mut(&session) else { return }; + let Some(view) = self.state.sessions.get_mut(&session) else { return }; let Some(channel) = vm::servers::channel_by_path(&view.presence, path) else { let server = self.bookmark(session).map(|b| b.name.clone()).unwrap_or_default(); self.set_status(format!("{server} has no channel \u{201c}{path}\u{201d}")); @@ -64,7 +69,7 @@ impl App { let form = vm::servers::link_form(link, form, &self.default_nickname()); let Some(ui) = self.ui.upgrade() else { return }; let nav = ui.global::