diff --git a/CHANGELOG.md b/CHANGELOG.md index 1444e50..88ac674 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -75,13 +75,17 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows also reports a damaged TeamSpeak identity by the kind of damage and never repeats its key in an error. Nothing changes on screen yet: accounts and sign-in are later steps. -- 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 view models, the app's state, the state change of every engine event and + the decisions of the settings pages, the Stream Studio, the streams, the chat, + the servers, the audio settings page, the friends and the development + switches 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. Two things change on screen: the chat of + a server that is gone takes the colour of its title instead of opaque + black, and a cached avatar file cut after a valid header shows the + initials instead of a broken picture. 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 06e2cda..31c9466 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9768,6 +9768,7 @@ dependencies = [ "image", "miniz_oxide 0.8.9", "png", + "roxmltree", "serde", "serde_json", "unicode-segmentation", diff --git a/crates/voelin-ui-vm/Cargo.toml b/crates/voelin-ui-vm/Cargo.toml index f06af6c..b34df35 100644 --- a/crates/voelin-ui-vm/Cargo.toml +++ b/crates/voelin-ui-vm/Cargo.toml @@ -16,24 +16,26 @@ path = "src/lib.rs" # 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. +# Whether a picture file decodes, and its size; 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" +# Whether an SVG document is XML with an svg root (the vector renderers read +# it with this parser too). +roxmltree = { version = "0.21", default-features = false, features = ["std"] } # The Twemoji archive's blocks (raw deflate). miniz_oxide = "0.8" # Grapheme clusters for emoji in chat text. unicode-segmentation = "1.13" +# The sample pictures of the demo data (VOELIN_DEMO_UI) and the tests. +png = "0.18" 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/src/bbcode.rs b/crates/voelin-ui-vm/src/bbcode.rs index 1b8f238..24a67d3 100644 --- a/crates/voelin-ui-vm/src/bbcode.rs +++ b/crates/voelin-ui-vm/src/bbcode.rs @@ -36,9 +36,13 @@ pub const MAX_RUNS: usize = 1500; /// How a span of text looks. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Style { + /// Bold (`[b]`). pub bold: bool, + /// Italic (`[i]`). pub italic: bool, + /// Underlined (`[u]`). pub underline: bool, + /// Struck through (`[s]`). pub strike: bool, /// Code: on a background. pub code: bool, @@ -51,12 +55,16 @@ pub struct Style { /// A piece of a block. #[derive(Clone, Debug, PartialEq, Eq)] pub enum Span { + /// Text with one style. Text { + /// The characters. text: String, + /// How they look. style: Style, }, /// A picture at an address (`[img]…[/img]`). Image { + /// Where the picture is. url: String, }, } @@ -68,7 +76,10 @@ pub enum BlockKind { Text, /// A line of a quote; the first names who said it (`[quote=Name]`), when /// the quote does. - Quote { author: String }, + Quote { + /// Who said it, empty when the quote does not say. + author: String, + }, /// Code: all its lines in one span. Code, /// An item of a list. @@ -80,13 +91,16 @@ pub enum BlockKind { /// A line, a quote's line, code, a list item or a rule. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Block { + /// What the block is. pub kind: BlockKind, + /// Its pieces, left to right. pub spans: Vec, } /// A message's text: its blocks, top to bottom. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Doc { + /// The lines, quotes, code and rules in order. pub blocks: Vec, } diff --git a/crates/voelin-ui-vm/src/bridge.rs b/crates/voelin-ui-vm/src/bridge.rs index 6dcdf21..f027f46 100644 --- a/crates/voelin-ui-vm/src/bridge.rs +++ b/crates/voelin-ui-vm/src/bridge.rs @@ -5,6 +5,10 @@ //! (`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. +//! +//! Every field is documented here: the comments of `bridge.slint` were +//! carried over, and the fields that had none were described from the code +//! that fills them. use std::sync::Arc; @@ -14,13 +18,17 @@ 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 { + /// The bookmark's id, which is the session's too. pub id: i32, + /// The server's name. pub name: Arc, + /// The address the bookmark connects to. pub address: Arc, /// "offline", "connecting", "observing" or "connected" pub status: Arc, /// Avatar of a server without an icon. pub initials: Arc, + /// The colour of its avatar. pub tint: Rgb, /// The server's icon, empty without one. pub icon: ImageRef, @@ -39,50 +47,70 @@ pub struct ServerItem { /// A row or form of the bridge (the plain counterpart of the Slint struct `TreeItem`). #[derive(Clone, Debug, Default, PartialEq)] pub struct TreeItem { + /// A channel; else a client. 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, + /// How far the row is indented: its level in the tree. pub depth: i32, + /// The channel's or the client's id on the server. pub id: i32, + /// A channel's name (a spacer's text, without its `[cspacer1]` part) or a client's nickname. pub name: Arc, + /// Our own channel (channels). pub own: bool, + /// The client is speaking. pub talking: bool, + /// The client's microphone is muted. pub muted: bool, + /// The client's speakers are muted. pub sound_off: bool, + /// The client is away. pub away: bool, + /// The client streams. pub streaming: bool, + /// The channel needs a password. pub locked: bool, + /// The channel's contents are hidden. pub collapsed: bool, /// Local playback of this client: muted, or its volume in percent /// (100 = unchanged). pub local_muted: bool, + /// Its local volume in percent; 100 is unchanged. pub local_volume: i32, /// Our own client. pub myself: bool, /// Avatar of a client. pub initials: Arc, + /// The colour of the client's avatar. 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, + /// The channel's limit of clients; -1: none. 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, + /// The second icon, as `icon`. pub icon_2: ImageRef, + /// The third icon, as `icon`. 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, + /// The second badge, as `badge`. pub badge_2: ImageRef, + /// The third badge, as `badge`. 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, + /// How the server sizes the banner: 0 as it is, 1 stretched, 2 scaled keeping the aspect ratio. pub banner_mode: i32, } @@ -90,16 +118,27 @@ pub struct TreeItem { /// channel view (our channel). #[derive(Clone, Debug, Default, PartialEq)] pub struct MemberItem { + /// The client's id on the server. pub id: i32, + /// Its nickname. pub name: Arc, + /// The initials of its avatar. pub initials: Arc, + /// The colour of its avatar. pub tint: Rgb, + /// Its avatar picture, empty without one. pub avatar: ImageRef, + /// It is speaking. pub talking: bool, + /// Its microphone is muted. pub muted: bool, + /// Its speakers are muted. pub sound_off: bool, + /// It is away. pub away: bool, + /// It streams. pub streaming: bool, + /// Our own client. pub myself: bool, /// "Speaking", "Streaming", "Away", ... pub status: Arc, @@ -108,24 +147,31 @@ pub struct MemberItem { /// The section the row is in (a server group, "In Voice", /// "Streaming"), and the group's icon. pub group: Arc, + /// The section's icon, empty where it has none. 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, + /// The number of rows in its section. 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, + /// It is a priority speaker. pub priority: bool, + /// It is a channel commander. pub commander: bool, + /// It is recording the conversation. 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, + /// The second badge. pub badge_2: ImageRef, + /// The third badge. pub badge_3: ImageRef, } @@ -133,8 +179,11 @@ pub struct MemberItem { /// the app does not know; its picture is empty until it is downloaded. #[derive(Clone, Debug, Default, PartialEq)] pub struct BadgeItem { + /// The badge's name. pub name: Arc, + /// What the badge says of its holder. pub description: Arc, + /// The badge's picture, empty until it is downloaded. pub icon: ImageRef, } @@ -142,24 +191,37 @@ pub struct BadgeItem { /// can be done with them. #[derive(Clone, Debug, Default, PartialEq)] pub struct MemberCard { + /// The card is shown. pub open: bool, + /// The client's id on the server. pub id: i32, + /// Its nickname. pub name: Arc, + /// The initials of its avatar. pub initials: Arc, + /// The colour of its avatar. pub tint: Rgb, + /// Its avatar picture, empty without one. pub avatar: ImageRef, + /// What it does: "Speaking", "Streaming", "Away", ... (as `MemberItem::status`). pub status: Arc, + /// The description the client set. 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, + /// The country the server reports for it, empty if none. pub country: Arc, + /// Its talk power. pub talk_power: i32, + /// It is one of our friends. pub friend: bool, + /// It is a blocked contact. pub blocked: bool, /// Local playback, in percent. pub volume: f32, + /// Its voice is muted for us (local playback). pub muted: bool, /// The client has a unique id, so contacts and private chats work. pub known: bool, @@ -176,15 +238,19 @@ pub struct ChatTab { pub name: Arc, /// 0 = server chat, 1 = channel chat, 2 = private chat pub kind: i32, + /// A channel chat's channel id; 0 for the others. pub id: i32, + /// How many of its messages are unread. 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, + /// The time of the last message. pub time: Arc, /// The channel's banner picture behind the chat's header (as TreeItem). pub banner: ImageRef, + /// As `TreeItem::banner_mode`. pub banner_mode: i32, } @@ -193,27 +259,36 @@ pub struct ChatTab { /// characters). #[derive(Clone, Debug, Default, PartialEq)] pub struct TextRun { + /// The characters of the run. pub text: Arc, + /// The Twemoji key if the run is an emoji, else empty. pub emoji: Arc, + /// In bold. pub bold: bool, + /// In italics. pub italic: bool, + /// Underlined. pub underline: bool, + /// Struck through. 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, + /// The author's colour made readable on the light theme (`ink_dark`: the dark one). 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, + /// Its text shows something else than the address it links to. 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 { + /// The pieces of the block, in order. 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) @@ -227,7 +302,9 @@ pub struct TextBlock { pub struct ReactionItem { /// The Twemoji key of the first emoji in `text` ("1f389"), for the image. pub key: Arc, + /// The emoji, as text. pub text: Arc, + /// How many reacted with it. pub count: i32, /// We reacted with it. pub me: bool, @@ -236,6 +313,7 @@ pub struct ReactionItem { /// A file linked in a message (`ChatMessage::file_refs`). #[derive(Clone, Debug, Default, PartialEq)] pub struct FileItem { + /// The file's name. pub name: Arc, /// "2.4 MB", or what the transfer is doing. pub detail: Arc, @@ -257,26 +335,35 @@ 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, + /// The author's name. 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, + /// When it was sent, as shown ("11:42"). pub time: Arc, /// The text in blocks of styled runs; only filled when it has /// formatting or emoji (`rich`). pub blocks: Vec, + /// The blocks are shown, not `text`. 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, + /// The initials of the author's avatar. pub initials: Arc, + /// The colour of the author's avatar. pub tint: Rgb, + /// The author's avatar picture, empty without one. pub avatar: ImageRef, /// From a blocked contact. pub blocked: bool, + /// The message is pinned. pub pinned: bool, + /// The reactions to it. pub reactions: Vec, + /// The files it links to. pub files: Vec, /// The gateway knows this message: it can be pinned, reacted to and /// made into a topic. @@ -295,6 +382,7 @@ pub struct ChatLine { /// A pinned message in the pins drawer. #[derive(Clone, Debug, Default, PartialEq)] pub struct PinItem { + /// The pinned message. pub line: ChatLine, /// "pinned by Nova · 12:04" pub by: Arc, @@ -303,14 +391,19 @@ pub struct PinItem { /// A gateway topic (thread). #[derive(Clone, Debug, Default, PartialEq)] pub struct TopicItem { + /// The topic's id on the gateway. pub id: i32, + /// Its title. pub title: Arc, + /// Who started it. 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, + /// It was active within the hour. pub recent: bool, + /// It is archived. pub archived: bool, } @@ -318,17 +411,24 @@ pub struct TopicItem { /// Connect goes. #[derive(Clone, Debug, Default, PartialEq)] pub struct BookmarkForm { + /// The bookmark's id; -1: a new one. pub id: i32, + /// The name, empty to use the address. pub name: Arc, + /// The server's address. pub address: Arc, + /// The nickname to connect with. pub nickname: Arc, + /// The server's password. 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. + /// path, or `/`), its password and a privilege key. pub channel: Arc, + /// The password of the channel to join. pub channel_password: Arc, + /// A privilege key to use on joining. pub token: Arc, } @@ -337,8 +437,11 @@ pub struct BookmarkForm { /// being looked up (it started before we joined, or in another channel). #[derive(Clone, Debug, Default, PartialEq)] pub struct StreamItem { + /// The stream's id; empty while it is looked up. pub id: Arc, + /// The stream's title. pub name: Arc, + /// The streamer's name. pub streamer: Arc, /// The streamer's channel when it is not ours; empty in ours. pub channel: Arc, @@ -347,13 +450,17 @@ pub struct StreamItem { /// 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, + /// The colour of the streamer's avatar. pub tint: Rgb, + /// The streamer's picture, empty without one. pub avatar: ImageRef, /// How many watch it (the gateway's directory; 0 unknown). pub viewers: i32, + /// The stream has sound. pub audio: bool, /// "Screen", "Window", "Camera"; and the announced bitrate ("8 Mbit/s"). pub kind: Arc, + /// The announced bitrate, "8 Mbit/s". pub bitrate: Arc, /// Shown in the viewer. pub watching: bool, @@ -366,9 +473,13 @@ pub struct StreamItem { /// A viewer of our stream. state: "requested", "connecting" or "connected". #[derive(Clone, Debug, Default, PartialEq)] pub struct ViewerItem { + /// The viewer's client id. pub client: i32, + /// The viewer's name. pub name: Arc, + /// "requested", "connecting" or "connected". pub state: Arc, + /// The message of its request to watch. pub message: Arc, /// Their avatar picture, empty without one. pub avatar: ImageRef, @@ -377,14 +488,18 @@ pub struct ViewerItem { /// A capture source for the share dialog. #[derive(Clone, Debug, Default, PartialEq)] pub struct SourceItem { + /// The source's name. pub name: Arc, + /// The line under the name. 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 { + /// Index into the sources offered (`SourceItem`). pub source: i32, + /// The stream's title. pub name: Arc, /// Index into the frame rate choices (15, 30, 60, 120, 144, 240, 320). pub fps_index: i32, @@ -396,7 +511,9 @@ pub struct ShareForm { /// 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, + /// The stream carries sound too. pub audio: bool, + /// Viewers are let in without being asked. pub auto_accept: bool, } @@ -405,15 +522,19 @@ pub struct ShareForm { pub struct AudioForm { /// 0 = system default, then the devices. pub input_index: i32, + /// As `input_index`, for the output device. pub output_index: i32, /// 0 = push-to-talk, 1 = voice activation, 2 = continuous. pub transmit: i32, /// dBFS. pub vad_threshold: f32, + /// Echo cancellation is on. pub echo_cancellation: bool, + /// Noise suppression is on. pub noise_suppression: bool, /// 0 = low ... 3 = very high. pub noise_level: i32, + /// Automatic gain control is on. pub auto_gain: bool, /// dB. pub input_gain: f32, @@ -426,9 +547,13 @@ pub struct AudioForm { /// Local playback settings of one client. volume in percent. #[derive(Clone, Debug, Default, PartialEq)] pub struct ClientAudio { + /// The client's id on the server. pub id: i32, + /// Its nickname. pub name: Arc, + /// Its playback volume in percent. pub volume: f32, + /// Its playback is muted. pub muted: bool, /// The client streams: the dialog offers to watch it. pub streaming: bool, @@ -439,24 +564,34 @@ pub struct ClientAudio { pub struct AppearanceForm { /// "dark", "light" or "system" pub theme: Arc, + /// The factor the text size is scaled by; 1 is normal. pub font_scale: f32, /// Pixels. pub narrow_breakpoint: f32, + /// Memory for decoded pictures in MB; 0 keeps none. pub image_cache_mb: f32, } /// A contact (friend, blocked or neutral) and where they are now. #[derive(Clone, Debug, Default, PartialEq)] pub struct ContactItem { + /// The contact's unique id. pub uid: Arc, + /// The contact's name. pub name: Arc, + /// The initials of its avatar. pub initials: Arc, + /// The colour of its avatar. pub tint: Rgb, + /// Its avatar picture, empty without one. pub avatar: ImageRef, /// "friend", "blocked" or "neutral" pub relation: Arc, + /// A session sees them. pub online: bool, + /// They are away. pub away: bool, + /// They stream. pub streaming: bool, /// What they do: "In Chill Zone", "Streaming", "Away: brb", "Offline". pub status: Arc, @@ -465,9 +600,11 @@ pub struct ContactItem { pub place: Arc, /// "12m ago": online since (this run), else when last seen. pub when: Arc, + /// Our note about them. pub note: Arc, /// Local playback in percent. pub volume: f32, + /// Their voice is muted for us. pub muted: bool, /// "Contact since 14 Jan 2022". pub since: Arc, @@ -475,6 +612,7 @@ pub struct ContactItem { pub spots: Vec>, /// A voice connection sees them: they can be messaged, poked, joined. pub reachable: bool, + /// They are the contact the friends page shows in full. pub selected: bool, } @@ -483,13 +621,21 @@ pub struct ContactItem { pub struct LiveItem { /// The session (bookmark id) and the stream (directory or stream id). pub session: i32, + /// The stream's id in the directory or on the voice connection. pub id: Arc, + /// The stream's title. pub title: Arc, + /// The streamer's name. pub streamer: Arc, + /// The initials of the streamer's avatar. pub initials: Arc, + /// The colour of the streamer's avatar. pub tint: Rgb, + /// The streamer's picture, empty without one. pub avatar: ImageRef, + /// The server's name. pub server: Arc, + /// The channel's name. pub channel: Arc, /// 0: unknown. pub viewers: i32, @@ -508,6 +654,7 @@ pub struct ConversationItem { pub key: i32, /// 0 server chat, 1 channel chat, 2 private chat, 3 offline message. pub kind: i32, + /// The chat's title: the channel's or the person's name, or the server's. pub title: Arc, /// The server's name. pub server: Arc, @@ -517,27 +664,40 @@ pub struct ConversationItem { pub time: Arc, /// "10m ago". pub ago: Arc, + /// How many of its messages are unread. pub unread: i32, + /// The initials of its avatar. pub initials: Arc, + /// The colour of its avatar. pub tint: Rgb, + /// Its picture, empty without one. pub avatar: ImageRef, + /// The other person is online (private chats). pub online: bool, + /// It is the conversation that is open. pub selected: bool, } /// A notification of the bell. #[derive(Clone, Debug, Default, PartialEq)] pub struct NoticeItem { + /// What the rows call the notice. pub key: i32, /// "mention", "poke", "message", "event", "friend" pub kind: Arc, + /// The headline. pub title: Arc, + /// The line under it. pub body: Arc, /// "3 min ago" pub time: Arc, + /// It was not opened or marked read. pub unread: bool, + /// The initials of the avatar it shows. pub initials: Arc, + /// The colour of that avatar. pub tint: Rgb, + /// The avatar picture it shows, empty without one. pub avatar: ImageRef, } @@ -546,10 +706,15 @@ pub struct NoticeItem { pub struct SearchItem { /// "server", "channel", "person", "contact", "setting" pub kind: Arc, + /// What the result is called. pub title: Arc, + /// The line under it. pub subtitle: Arc, + /// The initials of its avatar. pub initials: Arc, + /// The colour of its avatar. pub tint: Rgb, + /// Its picture, empty without one. pub avatar: ImageRef, /// The first result of a group names it ("Servers", "People", ...). pub header: Arc, @@ -560,12 +725,17 @@ pub struct SearchItem { pub struct HappeningItem { /// "event", "stream", "news" pub kind: Arc, + /// The event's or stream's title, or the news' headline. pub title: Arc, + /// The line under it, with the server's name. pub subtitle: Arc, /// "Sat 26 Apr · 19:00" pub when: Arc, + /// The session (bookmark id) it is on. pub session: i32, + /// The event's id on the gateway; 0: news. pub id: i32, + /// Its stream is live. pub live: bool, } @@ -574,28 +744,39 @@ pub struct HappeningItem { pub struct ResumeItem { /// There is one: its server is still a bookmark at the same address. pub shown: bool, + /// The server's bookmark id. pub server_id: i32, + /// The server's name. pub server: Arc, + /// The initials of its avatar. pub initials: Arc, + /// The colour of its avatar. pub tint: Rgb, + /// The server's icon, empty without one. 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, + /// The server is connecting now. pub connecting: bool, } /// A scheduled event of a server's gateway. #[derive(Clone, Debug, Default, PartialEq)] pub struct EventItem { + /// The event's id on the gateway. pub id: i32, + /// The event's title. pub title: Arc, + /// Its description. pub description: Arc, /// The date block: "SAT", "26", "APR". pub weekday: Arc, + /// The day of the month, in the date block. pub day: Arc, + /// The month, abbreviated, in the date block. pub month: Arc, /// "Sat 26 Apr, 19:00 – 21:00" pub when: Arc, @@ -603,12 +784,17 @@ pub struct EventItem { pub place: Arc, /// A scheduled stream: "Exploring the Lands Between · Elden Ring". pub stream: Arc, + /// Its stream is live. pub live: bool, + /// How many go. pub going: i32, + /// How many may go. pub maybe: i32, + /// How many do not go. pub not_going: i32, /// "going", "maybe", "not_going" or "". pub rsvp: Arc, + /// Who made it. pub creator: Arc, /// We may edit and delete it (ours, or we moderate). pub editable: bool, @@ -616,6 +802,7 @@ pub struct EventItem { pub soon: Arc, /// "Nova (going)", ...; filled once the event was opened. pub attendees: Vec>, + /// Its details are open. pub expanded: bool, } @@ -624,7 +811,9 @@ pub struct EventItem { pub struct EventForm { /// -1: a new event. pub id: i32, + /// The event's title. pub title: Arc, + /// Its description. pub description: Arc, /// "2026-10-04 19:00", local time. pub start: Arc, @@ -632,8 +821,11 @@ pub struct EventForm { pub end: Arc, /// Index into `event-channels` (0: server-wide). pub channel: i32, + /// It is a scheduled stream. pub stream: bool, + /// The scheduled stream's title. pub stream_title: Arc, + /// The game or category it shows. pub game: Arc, } @@ -642,26 +834,40 @@ pub struct EventForm { pub struct OfflineForm { /// The peer's unique id and name. pub uid: Arc, + /// The recipient's name. pub to: Arc, + /// The message's subject. pub subject: Arc, + /// The message's text. pub text: Arc, } /// The open direct message: who, and what can be done. #[derive(Clone, Debug, Default, PartialEq)] pub struct DmPeer { + /// A conversation is open. pub open: bool, + /// The peer's unique id. pub uid: Arc, + /// The peer's name. pub name: Arc, + /// The initials of their avatar. pub initials: Arc, + /// The colour of their avatar. pub tint: Rgb, + /// Their avatar picture, empty without one. pub avatar: ImageRef, + /// They are online on one of our servers. pub online: bool, /// "Online · Nightfall Guild · Chill Zone", "Offline · last seen 2 h ago". pub status: Arc, + /// The description they set. pub description: Arc, + /// Their server groups. pub groups: Vec>, + /// Our note about them. pub note: Arc, + /// "Contact since 14 Jan 2022"; empty for no contact. pub since: Arc, /// Where they are now, or where they were last seen. pub servers: Vec>, @@ -669,11 +875,17 @@ pub struct DmPeer { /// 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, + /// How many pictures there are besides the ones in `media`. pub media_more: i32, + /// The other files linked in the conversation. pub files: Vec, + /// They are a friend. pub friend: bool, + /// They are blocked. pub blocked: bool, + /// Their local volume in percent. pub volume: f32, + /// Their voice is muted for us. pub muted: bool, /// Messages can be sent now (a voice connection that sees them). pub can_send: bool, @@ -687,19 +899,26 @@ pub struct DmPeer { pub stored: bool, /// An offline message is shown instead of the conversation. pub mail: bool, + /// The open offline message's subject. pub mail_subject: Arc, + /// Its text, empty until the server has sent it. pub mail_text: Arc, + /// When it was sent. pub mail_time: Arc, } /// An identity (Profiles page); never its key. #[derive(Clone, Debug, Default, PartialEq)] pub struct IdentityItem { + /// The identity's id in the store. pub id: i32, + /// The identity's name. pub name: Arc, /// Unique ids on TeamSpeak 3 and TeamSpeak 6 servers. pub uid: Arc, + /// Its unique id on TeamSpeak 6 servers. pub uid6: Arc, + /// The security level of its key. pub level: i32, /// The store's default: servers see us as this one unless a bookmark /// names another. @@ -708,6 +927,7 @@ pub struct IdentityItem { pub origin: Arc, /// Raising its level: the level aimed at and the best one reached (0: no). pub improving: i32, + /// The best level reached so far while it is raised. pub reached: i32, /// The bookmarks that use it. pub used_by: Arc, @@ -716,19 +936,26 @@ pub struct IdentityItem { /// An identity found in another client's files (import). #[derive(Clone, Debug, Default, PartialEq)] pub struct FoundIdentity { + /// The identity's name. pub name: Arc, + /// Its unique id. pub uid: Arc, + /// The security level of its key. pub level: i32, + /// The other client's file it was found in. pub source: Arc, /// Already in our identities. pub known: bool, + /// It is chosen for the import. pub picked: bool, } /// A bookmark and the identity it connects with (Profiles page). #[derive(Clone, Debug, Default, PartialEq)] pub struct BookmarkIdentity { + /// The bookmark's id. pub id: i32, + /// The bookmark's name. pub name: Arc, /// Index into `identity-names` (0: the default identity). pub identity: i32, @@ -747,7 +974,9 @@ pub struct VideoForm { pub fps: Arc, /// auto, vp8, vp9, h264, av1. pub codec: i32, + /// Hardware video encoders are used where there are some. pub hardware: bool, + /// The camera picture is mirrored. pub mirror: bool, /// everyone, friends, channel, nobody. pub permissions: i32, @@ -768,7 +997,9 @@ pub struct LayerItem { pub fps: Arc, /// kbit/s. pub bitrate: Arc, + /// kbit/s a viewer needs for the layer. pub min_bitrate: Arc, + /// kbit/s the layer may use at most, not below `bitrate`; empty: no limit. pub max_bitrate: Arc, } @@ -777,34 +1008,47 @@ pub struct LayerItem { pub struct AudioSourceItem { /// "desktop", "app", "window", "microphone", "synthetic" pub kind: Arc, + /// The source's name. pub name: Arc, + /// The line under the name. pub detail: Arc, /// Percent. pub gain: f32, + /// It is muted in the mix. pub muted: bool, } /// Stream defaults (Streaming page). #[derive(Clone, Debug, Default, PartialEq)] pub struct StreamingForm { + /// Frames per second as typed (`stream.fps`). pub fps: Arc, + /// kbit/s as typed (`stream.bitrate_kbps`); "Auto" or empty: from the size and frame rate. pub bitrate: Arc, /// auto, vp8, vp9, h264, av1. pub codec: i32, /// auto, portal, wlroots, x11. pub capture: i32, + /// Seconds the replay buffer keeps, as typed; 0: off. pub replay_seconds: Arc, + /// MiB of the replay buffer kept in memory, as typed. pub replay_memory: Arc, + /// The folder of recordings and clips; empty: the default. 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 { + /// How a mention notifies: 0 off, 1 in the app, 2 also on the desktop. pub mentions: i32, + /// How a poke notifies, as `mentions`. pub pokes: i32, + /// How a private message notifies, as `mentions`. pub messages: i32, + /// How an event that starts soon notifies, as `mentions`. pub events: i32, + /// How a friend coming online notifies, as `mentions`. pub friends: i32, } @@ -815,52 +1059,74 @@ pub struct PrivacyForm { pub block_mode: i32, /// everyone, friends, nobody. pub messages: i32, + /// Who may poke us, as `messages`. pub pokes: i32, } /// A server's gateway (Integrations page). #[derive(Clone, Debug, Default, PartialEq)] pub struct GatewayItem { + /// The session (bookmark id) whose gateway it is. pub session: i32, + /// The server's name. pub server: Arc, + /// The gateway's address. pub url: Arc, /// "connected", "connecting", "off" pub status: Arc, + /// The features it offers. pub features: Vec>, + /// We may administer it. pub admin: bool, } /// A gateway configuration key (gateway administration). #[derive(Clone, Debug, Default, PartialEq)] pub struct ConfigItem { + /// The dotted key, "history.retention_days". pub key: Arc, /// JSON. pub value: Arc, + /// Where the value comes from: "set at runtime", "command line", "environment", "file" or + /// "default". pub source: Arc, + /// What the key is for. pub description: Arc, + /// The type of the value: `bool`, `int`, `string`, `int_list`, `string_list` or `rule`. pub kind: Arc, + /// It is read at start only and cannot be set at runtime. pub bootstrap: bool, } /// A gateway permission rule. #[derive(Clone, Debug, Default, PartialEq)] pub struct PermItem { + /// What the rule allows. pub action: Arc, /// "Everyone", "Server groups 6, 7", "Default: server admins". pub rule: Arc, + /// Where the rule comes from, as `ConfigItem::source`. pub source: Arc, + /// Everyone is allowed. pub everyone: bool, + /// The server groups allowed, as a list. pub server_groups: Arc, + /// The channel groups allowed, as a list. pub channel_groups: Arc, } /// A video encoder backend (Integrations page). #[derive(Clone, Debug, Default, PartialEq)] pub struct EncoderItem { + /// The encoder backend's name. pub name: Arc, + /// The API it uses. pub api: Arc, + /// The codec it encodes. pub codec: Arc, + /// It encodes in hardware. pub hardware: bool, + /// It works on this machine. pub ok: bool, /// Why it does not work, or "used first". pub status: Arc, @@ -869,7 +1135,9 @@ pub struct EncoderItem { /// Any registered setting (Advanced page). #[derive(Clone, Debug, Default, PartialEq)] pub struct SettingItem { + /// The setting's key. pub key: Arc, + /// What the setting is for. pub doc: Arc, /// JSON. pub value: Arc, @@ -880,55 +1148,80 @@ pub struct SettingItem { /// A recording or clip of the Stream Studio (Library). #[derive(Clone, Debug, Default, PartialEq)] pub struct RecordingItem { + /// The file's name. pub name: Arc, /// "12.3 MB · 3 Oct 18:04". pub detail: Arc, + /// A clip saved from the replay buffer; else a recording. pub clip: bool, + /// Where the file is. pub path: Arc, } /// Encoders, chat history, cache and logs (Advanced page); numbers as typed. #[derive(Clone, Debug, Default, PartialEq)] pub struct AdvancedForm { + /// `stream.encoder_backend`: auto, software or an encoder's name. pub encoder: Arc, + /// `stream.hardware_acceleration`: hardware encoders where available. pub hardware: bool, /// `stream.decoder_backend`, `stream.hardware_decoding`. pub decoder: Arc, + /// `stream.hardware_decoding`: hardware decoders where available. pub hardware_decoding: bool, + /// `chat.store_history`: keep the chat history on this device. pub store_history: bool, + /// `chat.history_page`: messages per page; 0: all at once. pub history_page: Arc, + /// `chat.dedupe_tolerance_ms`: how far apart two copies of a message may be and count as one. pub dedupe_ms: Arc, + /// `chat.retention_days`: delete stored messages older than this; 0: keep all. pub retention_days: Arc, + /// `cache.max_mb`: the picture cache's size in MiB; 0: no limit. pub cache_mb: Arc, + /// `cache.fetch_images`: download pictures of servers and chats. pub fetch_images: bool, + /// `files.progress_interval_ms`: how often a transfer reports; 0: continuously. pub progress_ms: Arc, /// `ui.image_preview_kb`. pub preview_kb: Arc, + /// A text on where the logs go and how to get more of them. pub logs: Arc, + /// The folder crash reports are kept in; empty if there is none. 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 { + /// The nickname the current server's bookmark connects with. pub nickname: Arc, + /// The name of the identity the server sees us as. pub identity: Arc, + /// Its unique id on TeamSpeak 3 servers. pub uid: Arc, + /// Its unique id on TeamSpeak 6 servers. pub uid6: Arc, + /// The security level of its key. pub level: i32, + /// The name of the current server. pub server: Arc, } /// One emoji of the picker. `text` is what picking it inserts. #[derive(Clone, Debug, Default, PartialEq)] pub struct EmojiCell { + /// The Twemoji key, "1f600". pub key: Arc, + /// The emoji's name. pub name: Arc, + /// What picking it inserts. 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 { + /// The emoji of the row. pub cells: Vec, } diff --git a/crates/voelin-ui-vm/src/chat/logic.rs b/crates/voelin-ui-vm/src/chat/logic.rs new file mode 100644 index 0000000..f2f3d19 --- /dev/null +++ b/crates/voelin-ui-vm/src/chat/logic.rs @@ -0,0 +1,1537 @@ +//! What happens to a session's chats when the engine tells something: tabs +//! open, messages arrive and are read, the gateway adds pins and topics, +//! files move. The functions change the [`AppState`] and say in the +//! [`Cx`]'s update what to draw and send; nothing here touches a toolkit. +//! +//! 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)`. Sessions the engine +//! keeps no history for (it does not know the server yet) fall back to +//! `Event::Chat`. +//! +//! Messages are read while their tab is on screen in the focused window +//! ([`track_reading`]). A tab remembers the newest message read +//! (`Tab::read`, kept in the store's `chat_reads`), counts what came after +//! it, and when it comes on screen shows a "New" divider above the first of +//! those until it is left. + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +use voelin_core::gateway::Pin; +use voelin_core::{ + Command, DownloadTo, GatewayRequest, GatewayUpdate, HistoryMessage, HistorySource, + TransferState, +}; +use voelin_gateway_proto::{ErrorCode, TopicInfo, feature}; +use voelin_model::{ChatMessage, ChatTarget}; +use voelin_store::ChatRead; + +use super::{LineCache, LineCtx, Previous, SERVER_LINES, server_texts, tab_title}; +use crate::bridge::{ChatLine, ChatTab, FileItem, PinItem, TopicItem}; +use crate::host::Cx; +use crate::previews::{fetch_previews, image_of, preview_progress}; +use crate::social::{Poke, is_own, own_message, peer_name, poke_lines}; +use crate::state::{AppState, Download, Lines, Msg, PinRow, SessionView, Tab, store_target}; + +/// The index of `target`'s tab in session `id`, opened if new (the engine +/// then sends its history). +pub fn chat_tab( + state: &mut AppState, + cx: &mut Cx<'_>, + id: i64, + target: ChatTarget, +) -> usize { + let peer = match &target { + ChatTarget::Private(uid) => peer_name(state, uid, None), + _ => String::new(), + }; + let view = state.sessions.entry(id).or_default(); + if let Some(i) = view.tabs.iter().position(|t| t.target == target) { + return i; + } + let title = tab_title(&view.presence, &target, &peer); + let tab = view.new_tab(target.clone(), title); + view.tabs.push(tab); + let index = view.tabs.len() - 1; + cx.send_real(Command::OpenChat { session: id as u64, target }); + index +} + +/// Open the chat `target` of the current session, and with `focus` show it. +pub fn open_chat( + state: &mut AppState, + cx: &mut Cx<'_>, + target: ChatTarget, + focus: bool, +) { + let Some(id) = state.current else { return }; + let index = chat_tab(state, cx, id, target); + if focus { + state.sessions.entry(id).or_default().focus_tab(index); + prefetch_counts(state, cx); + track_reading(state, cx); + } + cx.update.refresh.chat = true; + cx.update.refresh.servers = true; +} + +/// The index of `target`'s tab, opening one if it is new. +fn tab_for( + view: &mut SessionView, + target: &ChatTarget, + title: impl FnOnce() -> String, +) -> usize { + match view.tabs.iter().position(|t| t.target == *target) { + Some(i) => i, + None => { + let tab = view.new_tab(target.clone(), title()); + view.tabs.push(tab); + view.tabs.len() - 1 + } + } +} + +/// A live message of a session without stored history: appended as it +/// comes, without an id. +pub fn add_message( + state: &mut AppState, + cx: &mut Cx<'_>, + id: i64, + message: ChatMessage, +) { + let current = state.current == Some(id); + let reading = reads_now(state, cx, id); + let new = !is_own(state, id, &message); + let view = state.sessions.entry(id).or_default(); + let title = tab_title(&view.presence, &message.target, &message.author_name); + let index = tab_for(view, &message.target, || title); + let seen = reading && view.current_tab == index; + let tab = &mut view.tabs[index]; + let line = super::line(&message, tab.last.as_ref()); + tab.last = Some(Previous::of(&message)); + tab.lines.push(line); + let counted = new && !seen; + if counted { + tab.unread += 1; + } + if current { + cx.update.refresh.chat = true; + } + if counted { + cx.update.refresh.servers = true; + } + cx.chat_changed(id, &message.target); +} + +/// Messages the engine stored: added or updated by their local id. +pub fn history_batch( + state: &mut AppState, + cx: &mut Cx<'_>, + id: i64, + target: &ChatTarget, + messages: Vec, + source: HistorySource, + complete: bool, +) { + let current = state.current == Some(id); + let reading = reads_now(state, cx, id); + // A private chat is named after the peer, whoever wrote first. + let peer = match target { + ChatTarget::Private(uid) => Some(format!( + "@{}", + peer_name( + state, + uid, + messages.iter().find(|m| m.message.author_uid.as_deref() == Some(uid.as_str())) + ) + )), + _ => None, + }; + let own_uids = &state.own_uids; + let view = 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(|| tab_title(&view.presence, target, author)); + let index = tab_for(view, target, || title); + let seen = reading && view.current_tab == index; + let own_client = view.state.own_client; + let tab = &mut view.tabs[index]; + if source == HistorySource::Gateway { + tab.synced = true; + } + if source != HistorySource::Live { + tab.loading = false; + tab.complete = tab.complete || complete; + } + // Without a marker, what the tab holds was read. + if tab.read.is_none() { + tab.read = tab.newest(); + } + for message in messages { + match tab.messages.iter().position(|m| m.message.id == message.id) { + Some(i) => tab.messages[i].message = message, + None => { + let key = tab.take_key(); + tab.messages.push(Msg { key, message }); + } + } + } + tab.messages.sort_by_key(|m| (m.message.message.ts_ms, m.message.id)); + // ...and so is a first stored page; a first live message is new. + if tab.read.is_none() { + tab.read = match source { + HistorySource::Live => tab + .messages + .first() + .map(|m| (m.message.message.ts_ms, m.message.id.saturating_sub(1))), + _ => tab.newest(), + }; + } + let unread = tab.unread; + let own = |m: &ChatMessage| own_message(own_uids, own_client, m); + if seen && source == HistorySource::Live { + tab.catch_up(); + } else { + tab.count_unread(own); + // What came while away (a stored or gateway page) gets the divider + // also when its chat is on screen already. + if seen { + tab.enter(own); + } + } + let counted = tab.unread != unread; + if current { + fetch_previews(state, cx, id); + cx.update.refresh.chat = true; + } + if counted { + cx.update.refresh.servers = true; + } + cx.chat_changed(id, target); +} + +// What is read. + +/// 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(state: &AppState, cx: &Cx<'_>, id: i64) -> bool { + state.focused && state.current == Some(id) && cx.host.chat_shown() +} + +/// Where the tab of `target` is in session `id`. +fn tab_index(state: &AppState, id: i64, target: &ChatTarget) -> Option { + state.sessions.get(&id)?.tabs.iter().position(|t| t.target == *target) +} + +/// After anything that can change which chat is on screen (a tab, a server, +/// the page, the window's focus): the chat left is stored and 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 fn track_reading(state: &mut AppState, cx: &mut Cx<'_>) -> bool { + let open = state.current.filter(|_| cx.host.chat_shown()).and_then(|id| { + let view = state.sessions.get(&id)?; + Some((id, view.tabs.get(view.current_tab)?.target.clone())) + }); + let mut changed = false; + if open != state.reading { + if let Some((id, target)) = state.reading.take() + && let Some(index) = tab_index(state, id, &target) + { + let tab = &mut state.sessions.entry(id).or_default().tabs[index]; + changed |= tab.divider.take().is_some(); + save_read(state, cx, id, index); + } + state.reading = open.clone(); + } + if let (true, Some((id, target))) = (state.focused, open) + && let Some(index) = tab_index(state, id, &target) + { + let own_uids = &state.own_uids; + let view = 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); + tab.enter(|m| own_message(own_uids, own_client, m)); + changed |= (tab.unread, tab.divider) != before; + } + changed +} + +/// Store where tab `index` of session `id` was read, if that moved (not for +/// the sample data of `VOELIN_DEMO_UI`). +pub fn save_read(state: &mut AppState, cx: &mut Cx<'_>, id: i64, index: usize) { + if cx.host.demo_ui() { + return; + } + let Some(view) = 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 { + return; + }; + let read = ChatRead { ts_ms, id: message, updated_ms: chrono::Utc::now().timestamp_millis() }; + let target = store_target(&tab.target); + match cx.host.set_chat_read(server_uid, &target, &read) { + Ok(()) => { + tab.stored_read = tab.read; + // A tab closed and opened again starts from here. + view.reads.insert(target.key(), (ts_ms, message)); + } + Err(e) => cx.warn(format!("could not keep where a chat was read: {e}")), + } +} + +/// Store where every chat of session `id` was read (it ended, or the app +/// exits). +pub fn save_reads(state: &mut AppState, cx: &mut Cx<'_>, id: i64) { + let count = state.sessions.get(&id).map_or(0, |v| v.tabs.len()); + for index in 0..count { + save_read(state, cx, id, index); + } +} + +/// Where the chats of session `id` were read, from the store, once its +/// server is known (or another one: the gateway's id wins): its tabs start +/// from there, now and when they open. +pub fn load_reads(state: &mut AppState, cx: &mut Cx<'_>, id: i64) { + let Some(view) = state.sessions.get_mut(&id) else { return }; + if cx.host.demo_ui() + || view.state.server_uid.is_none() + || view.reads_of == view.state.server_uid + { + return; + } + view.reads_of = view.state.server_uid.clone(); + let server_uid = view.reads_of.as_deref().unwrap_or_default(); + view.reads = match cx.host.chat_reads(server_uid) { + Ok(reads) => reads.into_iter().map(|(t, r)| (t.key(), (r.ts_ms, r.id))).collect(), + Err(e) => { + cx.warn(format!("could not read where the chats were read: {e}")); + HashMap::new() + } + }; + for tab in &mut view.tabs { + tab.read_from(&view.reads); + } +} + +// Gateway features of a chat. + +/// Ask the gateway for the current chat's pins and topics until it sent +/// them, so the header counts them before their drawers are opened. +pub fn prefetch_counts(state: &AppState, cx: &mut Cx<'_>) { + let Some(id) = state.current else { return }; + let Some(view) = state.sessions.get(&id) else { return }; + let Some(tab) = view.tabs.get(view.current_tab) else { return }; + if !tab.pins_loaded && view.gateway_has(feature::PINS) { + cx.gateway_to(id, GatewayRequest::Pins { target: tab.target.clone() }); + } + if !tab.topics_loaded && view.gateway_has(feature::TOPICS) { + let target = tab.target.clone(); + cx.gateway_to(id, GatewayRequest::Topics { target, include_archived: false }); + } +} + +/// What a gateway update says about the chats of session `id`: its +/// features, pins, topics and the viewers of its streams. +pub fn gateway_update( + state: &mut AppState, + cx: &mut Cx<'_>, + id: i64, + update: GatewayUpdate, +) { + let current = state.current == Some(id); + let view = state.sessions.entry(id).or_default(); + match update { + GatewayUpdate::Connected { capabilities, .. } + | GatewayUpdate::Capabilities { capabilities } => { + view.gateway_caps = capabilities; + if current { + prefetch_counts(state, cx); + } + } + GatewayUpdate::Disconnected { .. } => { + view.gateway_caps.clear(); + for tab in &mut view.tabs { + tab.pins_loaded = false; + tab.topics_loaded = false; + } + } + // Answers to our requests: a chat closed while they were on their way + // (prefetch_counts asks on every change of chat) stays closed. + GatewayUpdate::Pins { target, pins } => { + let Some(tab) = view.tabs.iter_mut().find(|t| t.target == target) else { return }; + tab.pins_loaded = true; + tab.pins = pins.into_iter().map(|p| pin_row(tab.take_key(), p)).collect(); + tab.pins.sort_by_key(|p| -p.ts_ms); + } + GatewayUpdate::Pinned { target, pin } => { + let index = tab_for(view, &target, || "Server".into()); + let tab = &mut view.tabs[index]; + let row = pin_row(tab.take_key(), pin); + tab.pins.retain(|p| p.message.id != row.message.id); + tab.pins.insert(0, row); + } + GatewayUpdate::Unpinned { target, message_id, .. } => { + let index = tab_for(view, &target, || "Server".into()); + view.tabs[index].pins.retain(|p| p.message.remote_id != Some(message_id)); + } + GatewayUpdate::Topics { target, topics } => { + let Some(tab) = view.tabs.iter_mut().find(|t| t.target == target) else { return }; + tab.topics = topics; + tab.topics_loaded = true; + } + GatewayUpdate::Topic { topic } => { + let index = tab_for(view, &topic.target.clone(), || "Server".into()); + upsert_topic(&mut view.tabs[index].topics, topic); + } + GatewayUpdate::TopicHistory { target, topic, messages, .. } => { + let index = tab_for(view, &target, || "Server".into()); + let tab = &mut view.tabs[index]; + if tab.topic != Some(topic) { + return; + } + for message in messages { + match tab.topic_messages.iter().position(|m| m.message.id == message.id) { + Some(i) => tab.topic_messages[i].message = message, + None => { + let key = tab.take_key(); + tab.topic_messages.push(Msg { key, message }); + } + } + } + tab.topic_messages.sort_by_key(|m| (m.message.message.ts_ms, m.message.id)); + } + GatewayUpdate::Failed { request, code, message } => { + cx.warn(format!("gateway request {request} failed ({code:?}): {message}")); + if let Some(text) = failure_text(&request, code, &message) { + cx.status(text); + } + return; + } + // The stream directory: how many watch each stream. + GatewayUpdate::Streams { streams } => { + view.stream_viewers = streams.iter().filter_map(viewers_of).collect(); + return stream_viewers_changed(cx, current); + } + GatewayUpdate::StreamStarted { stream } + | GatewayUpdate::StreamUpdated { stream } + | GatewayUpdate::StreamRegistered { stream } => { + if let Some((id, viewers)) = viewers_of(&stream) { + view.stream_viewers.insert(id, viewers); + } + return stream_viewers_changed(cx, current); + } + GatewayUpdate::StreamEnded { id, .. } => { + view.stream_viewers.remove(&id); + return stream_viewers_changed(cx, current); + } + // Posts, pins and reactions also arrive as stored messages. + _ => return, + } + if current { + cx.update.refresh.chat = true; + } +} + +fn stream_viewers_changed(cx: &mut Cx<'_>, current: bool) { + if current { + cx.update.refresh.streams = true; + cx.update.refresh.viewer = true; + } +} + +// Files in chat. + +/// A transfer of a file that was not a picture preview: an upload from the +/// composer posts the file's link once it is up; a download of a message's +/// file shows how far it is. +pub fn transfer_progress( + state: &mut AppState, + cx: &mut Cx<'_>, + id: i64, + transfer: u64, + progress: TransferState, +) { + // An upload from the composer: post the file's link once it is up. + if let Some((_, channel, name)) = state.uploads.get(&transfer).cloned() { + match &progress { + TransferState::Done { size, .. } => { + state.uploads.remove(&transfer); + let file = voelin_model::FileRef { + channel, + path: "/".into(), + name: name.clone(), + size: Some(*size), + ..Default::default() + }; + cx.send(Command::SendChat { + session: id as u64, + target: ChatTarget::Channel(channel), + text: file.to_bbcode(), + }); + cx.status(format!("{name} shared")); + } + TransferState::Failed(e) => { + state.uploads.remove(&transfer); + cx.status(format!("Could not upload {name}: {e}")); + } + TransferState::Cancelled => { + state.uploads.remove(&transfer); + } + _ => {} + } + return; + } + if preview_progress(state, cx, id, transfer, &progress) { + return; + } + let done = matches!(progress, TransferState::Done { .. }); + let current = state.current == Some(id); + let view = state.sessions.entry(id).or_default(); + let Some(entry) = view.downloads.get_mut(&transfer) else { return }; + entry.state = progress; + let name = entry.name.clone(); + if done { + cx.status(format!("{name} downloaded")); + } + if current { + cx.update.refresh.chat = true; + } +} + +// What the user does. + +/// A request to the current session's gateway. +fn gateway(state: &AppState, cx: &mut Cx<'_>, request: GatewayRequest) { + if let Some(id) = state.current { + cx.gateway_to(id, request); + } +} + +/// The message with this handle in the current chat. +fn message_of(state: &AppState, key: i32) -> Option<&HistoryMessage> { + let view = state.sessions.get(&state.current?)?; + view.tabs.get(view.current_tab)?.message(key) +} + +/// Show tab `index` of the current session. +pub fn select_tab(state: &mut AppState, cx: &mut Cx<'_>, index: usize) { + if let Some(id) = state.current { + let view = state.sessions.entry(id).or_default(); + if index < view.tabs.len() { + view.set_current_tab(index); + view.tabs[index].topic = None; + } + fetch_previews(state, cx, id); + } + prefetch_counts(state, cx); + track_reading(state, cx); + cx.update.refresh.chat = true; + cx.update.refresh.servers = true; +} + +/// Close tab `index` of the current session (never the server's chat). +pub fn close_tab(state: &mut AppState, cx: &mut Cx<'_>, index: usize) { + let Some(id) = state.current else { return }; + let view = state.sessions.entry(id).or_default(); + if index == 0 || index >= view.tabs.len() { + return; + } + save_read(state, cx, id, index); + let tab = state.sessions.entry(id).or_default().remove_tab(index); + cx.send(Command::CloseChat { session: id as u64, target: tab.target }); + prefetch_counts(state, cx); + track_reading(state, cx); + cx.update.refresh.chat = true; + cx.update.refresh.servers = true; +} + +/// Say `text` in the current chat. +pub fn send_message(state: &AppState, cx: &mut Cx<'_>, text: String) { + let Some(id) = state.current else { return }; + let Some(view) = state.sessions.get(&id) else { return }; + let target = view.tabs[view.current_tab].target.clone(); + cx.send(Command::SendChat { session: id as u64, target, text }); +} + +/// What the sample data answers an older page with (no engine does). +pub struct SampleOlder { + /// The session. + pub session: i64, + /// The chat. + pub target: ChatTarget, + /// The oldest message shown now. + pub oldest: Option, +} + +/// The page of messages before the oldest one shown is asked for; the +/// sample data's is answered by the front end. +pub fn load_older(state: &mut AppState, cx: &mut Cx<'_>) -> Option { + let id = state.current?; + let view = state.sessions.get_mut(&id)?; + let tab = &mut view.tabs[view.current_tab]; + if tab.loading || tab.complete { + return None; + } + tab.loading = true; + let target = tab.target.clone(); + let oldest = tab.messages.first().map(|m| &m.message); + cx.update.refresh.chat = true; + if cx.host.demo_ui() { + return Some(SampleOlder { session: id, target, oldest: oldest.cloned() }); + } + let before = oldest.map(|m| m.id); + cx.send(Command::LoadOlderHistory { session: id as u64, target, before }); + None +} + +/// The current chat is read (the bar over its messages): the divider goes. +pub fn mark_read(state: &mut AppState, cx: &mut Cx<'_>) { + let Some(id) = state.current else { return }; + let Some(view) = state.sessions.get_mut(&id) else { return }; + let index = view.current_tab; + let tab = &mut view.tabs[index]; + tab.divider = None; + tab.catch_up(); + save_read(state, cx, id, index); + cx.update.refresh.chat = true; + cx.update.refresh.servers = true; +} + +/// The chat on screen may have changed (the page, the window's focus). +pub fn chat_shown_changed(state: &mut AppState, cx: &mut Cx<'_>) { + if track_reading(state, cx) { + cx.update.refresh.chat = true; + cx.update.refresh.servers = true; + } +} + +/// The window gained or lost the focus. +pub fn window_focused(state: &mut AppState, cx: &mut Cx<'_>, focused: bool) { + state.focused = focused; + chat_shown_changed(state, cx); +} + +/// Add or remove our reaction to a message. +pub fn react(state: &AppState, cx: &mut Cx<'_>, key: i32, emoji: String) { + let Some(message) = message_of(state, key) else { return }; + let Some(message_id) = message.remote_id else { return }; + let had = message.reactions.iter().any(|r| r.emoji == emoji && r.me); + let request = if had { + GatewayRequest::Unreact { message_id, emoji } + } else { + GatewayRequest::React { message_id, emoji } + }; + gateway(state, cx, request); +} + +/// Pin or unpin a message. +pub fn pin(state: &AppState, cx: &mut Cx<'_>, key: i32, on: bool) { + let Some(message) = message_of(state, key) else { return }; + let Some(message_id) = message.remote_id else { return }; + let request = + if on { GatewayRequest::Pin { message_id } } else { GatewayRequest::Unpin { message_id } }; + gateway(state, cx, request); +} + +/// Open the pins of the current chat (loading them once). +pub fn open_pins(state: &AppState, cx: &mut Cx<'_>) { + let Some(view) = current_view(state) else { return }; + let tab = &view.tabs[view.current_tab]; + if !tab.pins_loaded { + let target = tab.target.clone(); + gateway(state, cx, GatewayRequest::Pins { target }); + } + cx.update.refresh.chat = true; +} + +/// Highlight a pinned message in the chat; the row of the line to scroll to, +/// if the message is loaded. +pub fn jump_to_pin(state: &mut AppState, cx: &mut Cx<'_>, key: i32) -> Option { + let id = state.current?; + let view = state.sessions.entry(id).or_default(); + let tab = &mut view.tabs[view.current_tab]; + tab.marked = tab.pins.iter().find(|p| p.key == key).map(|p| p.message.id); + // The message is in the chat, not in an open topic. + if tab.topic.take().is_some() { + tab.topic_messages.clear(); + } + // Older than what is loaded: only highlighted once it is. The server + // chat's first lines are the server's. + let row = tab.marked.and_then(|id| tab.messages.iter().position(|m| m.message.id == id)); + let first = match tab.target { + ChatTarget::Server => server_texts(&view.presence.server).len(), + _ => 0, + }; + cx.update.refresh.chat = true; + row.map(|row| row + first) +} + +/// The topics drawer's search. +pub fn search_topics(state: &mut AppState, cx: &mut Cx<'_>, text: String) { + if state.topic_filter != text { + state.topic_filter = text; + cx.update.refresh.chat = true; + } +} + +/// Open the topics of the current chat (loading them once). +pub fn open_topics(state: &AppState, cx: &mut Cx<'_>) { + let Some(view) = current_view(state) else { return }; + let tab = &view.tabs[view.current_tab]; + if !tab.topics_loaded { + let target = tab.target.clone(); + gateway(state, cx, GatewayRequest::Topics { target, include_archived: false }); + } + cx.update.refresh.chat = true; +} + +/// Show a topic's messages (`-1` goes back to the chat). +pub fn open_topic(state: &mut AppState, cx: &mut Cx<'_>, topic: i32) { + let Some(id) = state.current else { return }; + let view = state.sessions.entry(id).or_default(); + let tab = &mut view.tabs[view.current_tab]; + tab.topic_messages.clear(); + tab.topic = (topic >= 0).then_some(i64::from(topic)); + let target = tab.target.clone(); + if let Some(topic) = tab.topic { + gateway( + state, + cx, + GatewayRequest::TopicHistory { target, topic, before: None, limit: None }, + ); + } + cx.update.refresh.chat = true; +} + +/// Say `text` in the open topic. +pub fn send_topic_message(state: &AppState, cx: &mut Cx<'_>, text: String) { + let Some(view) = current_view(state) else { return }; + let tab = &view.tabs[view.current_tab]; + let (Some(topic), target) = (tab.topic, tab.target.clone()) else { return }; + gateway(state, cx, GatewayRequest::Post { target, text, topic: Some(topic) }); +} + +/// Start a topic from a message (`key` < 0: a standalone topic). +pub fn create_topic(state: &AppState, cx: &mut Cx<'_>, key: i32, title: String) { + let Some(view) = current_view(state) else { return }; + let target = view.tabs[view.current_tab].target.clone(); + let message_id = message_of(state, key).and_then(|m| m.remote_id); + gateway(state, cx, GatewayRequest::CreateTopic { target, title, message_id }); +} + +/// The current session's view. +fn current_view(state: &AppState) -> Option<&SessionView> { + state.sessions.get(&state.current?) +} + +/// Download a file a message links, into `dir`. +pub fn download_file( + state: &mut AppState, + cx: &mut Cx<'_>, + key: i32, + index: i32, + dir: &Path, +) { + let Some(id) = state.current else { return }; + let index = index.max(0) as usize; + let Some(file) = + message_of(state, key).and_then(|m| m.message.file_refs().into_iter().nth(index)) + else { + return; + }; + let path = dir.join(&file.name); + let view = state.sessions.entry(id).or_default(); + let transfer = view.next_transfer; + view.next_transfer += 1; + view.downloads.insert( + transfer, + Download { key, index, name: file.name.clone(), state: TransferState::Requested }, + ); + cx.send(Command::DownloadChatFile { + session: id as u64, + transfer, + file, + password: None, + to: DownloadTo::Path { path, resume: false }, + }); + cx.update.refresh.chat = true; +} + +/// Where a file attached to the current chat goes: its session and +/// channel; the reason when the chat is not a channel's. +pub fn attach_target(state: &AppState) -> Result, &'static str> { + let Some(id) = state.current else { return Ok(None) }; + let Some(view) = state.sessions.get(&id) else { return Ok(None) }; + match view.tabs[view.current_tab].target { + ChatTarget::Channel(channel) => Ok(Some((id, channel))), + _ => Err("Files can be attached to a channel's chat."), + } +} + +/// Upload a file into a channel and link it in the chat once it is up. +pub fn upload( + state: &mut AppState, + cx: &mut Cx<'_>, + id: i64, + channel: u64, + from: PathBuf, +) { + let Some(name) = from.file_name().map(|n| n.to_string_lossy().to_string()) else { return }; + let view = state.sessions.entry(id).or_default(); + let transfer = view.next_transfer; + view.next_transfer += 1; + state.uploads.insert(transfer, (id, channel, name.clone())); + cx.send(Command::UploadFile { + session: id as u64, + transfer, + channel, + password: None, + path: format!("/{name}"), + from, + overwrite: true, + resume: false, + }); + cx.status(format!("Uploading {name}…")); +} + +// What is shown. + +/// What the lines of a chat need besides the state. +pub struct LinesFacts<'a> { + /// Pictures on the web show: they are fetched and previews are on. + pub pictures_shown: bool, + /// The pokes we got (they show among a private chat's messages). + pub pokes: &'a [Poke], +} + +/// 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). +/// The server chat starts with what the server says to everyone who +/// connects (`server_lines`). +pub fn lines_of( + state: &AppState, + view: &SessionView, + tab: &Tab, + main: bool, + facts: &LinesFacts<'_>, +) -> Vec { + let messages = if main { &tab.messages } else { &tab.topic_messages }; + let gateway = view.gateway_has(feature::PINS) + || view.gateway_has(feature::REACTIONS) + || view.gateway_has(feature::TOPICS); + // Pictures on the web show only while pictures are fetched and shown. + let pictures = facts.pictures_shown.then_some(&view.pictures); + let cache = main.then_some(&tab.cache); + let mut previous: Option = None; + let mut lines: Vec<(i64, ChatLine)> = Vec::with_capacity(messages.len()); + for m in messages { + let avatar = m.message.message.author_uid.as_ref().and_then(|uid| view.avatars.get(uid)); + let topic = m + .message + .topic_id + .filter(|_| tab.topic.is_none()) + .and_then(|t| tab.topics.iter().find(|i| i.id == t)) + .map(|t| t.title.clone()) + .unwrap_or_default(); + let previews = m + .message + .message + .file_refs() + .iter() + .enumerate() + .filter_map(|(i, f)| image_of(view, f).map(|image| (i, image))) + .collect(); + let ctx = LineCtx { + key: m.key, + avatar: crate::avatar::image(avatar), + gateway, + marked: tab.marked == Some(m.message.id), + topic, + downloads: downloads_of(view, m.key), + previews, + pictures, + cache, + unread_start: main && tab.divider == Some(m.message.id), + }; + lines.push(( + m.message.message.ts_ms, + super::history_line(&m.message, previous.as_ref(), &ctx), + )); + previous = Some(Previous::of(&m.message.message)); + } + if let Some(cache) = cache { + let ids = messages.iter().map(|m| m.message.id).chain(SERVER_LINES); + 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, state.current) { + lines.extend(poke_lines(state, facts.pokes, session, uid)); + lines.sort_by_key(|(ts, _)| *ts); + } + let server = if main && tab.target == ChatTarget::Server { + server_lines(view, pictures, cache) + } else { + Vec::new() + }; + server.into_iter().chain(lines.into_iter().map(|(_, line)| line)).collect() +} + +/// What the server says to everyone who connects ([`server_texts`]) as the +/// first lines of the server chat: by the server, without reactions or +/// pins. +fn server_lines( + view: &SessionView, + pictures: Option<&HashMap>, + cache: Option<&LineCache>, +) -> Vec { + let name = match view.presence.server_name.as_str() { + "" => "Server", + name => name, + }; + server_texts(&view.presence.server) + .into_iter() + .enumerate() + .map(|(i, (text, id))| { + let ctx = LineCtx { key: -1 - i as i32, pictures, cache, ..Default::default() }; + super::server_line(name, text, id, i > 0, &ctx) + }) + .collect() +} + +/// The file cards of a message that has downloads running. +fn downloads_of(view: &SessionView, key: i32) -> Vec<(usize, FileItem)> { + view.downloads + .values() + .filter(|d| d.key == key) + .map(|d| { + let (detail, status, progress) = match &d.state { + TransferState::Requested => ("Starting…".to_owned(), "running", 0.0), + TransferState::Started { size, offset } => ( + format!("{} of {}", super::size_text(*offset), super::size_text(*size)), + "running", + if *size > 0 { *offset as f32 / *size as f32 } else { 0.0 }, + ), + TransferState::Progress { done, size } => ( + format!("{} of {}", super::size_text(*done), super::size_text(*size)), + "running", + if *size > 0 { *done as f32 / *size as f32 } else { 0.0 }, + ), + TransferState::Done { size, .. } => { + (format!("Downloaded · {}", super::size_text(*size)), "done", 1.0) + } + TransferState::Failed(e) => (e.clone(), "failed", 0.0), + TransferState::Cancelled => ("Cancelled".to_owned(), "failed", 0.0), + }; + ( + d.index, + FileItem { + name: d.name.clone().into(), + detail: detail.into(), + index: d.index as i32, + state: status.into(), + progress, + ..Default::default() + }, + ) + }) + .collect() +} + +/// "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() }; + let minutes = (chrono::Utc::now() - then).num_minutes(); + match minutes { + i64::MIN..=0 => "just now".into(), + 1 => "1 min ago".into(), + 2..=59 => format!("{minutes} min ago"), + 60..=119 => "1 hour ago".into(), + 120..=1439 => format!("{} hours ago", minutes / 60), + 1440..=2879 => "yesterday".into(), + _ => then.with_timezone(&chrono::Local).format("%e %b").to_string().trim().into(), + } +} + +/// What the chat view shows of the current session. +pub struct ChatView { + /// The chat strip's tabs (without private chats). + pub tabs: Vec, + /// Which of the session's tabs each of `tabs` is. + pub strip: Vec, + /// The strip's current tab (-1: the current tab is not in it). + pub current: i32, + /// The session's current tab. + pub current_chat: i32, + /// The lines of the current tab, built from its messages; none for a + /// session without stored history, whose tabs hold the lines they were + /// pushed. + pub lines: Option>, + /// The row of the "New" divider, -1 without one. + pub unread_index: i32, + /// How many came from there on. + pub unread_count: i32, + /// And since when. + pub unread_since: String, + /// Older messages can be asked for. + pub more_history: bool, + /// An older page was asked for. + pub loading_history: bool, + /// The chat is only what this device saw, though the gateway has history. + pub local_history: bool, + /// The gateway takes pins. + pub has_pins: bool, + /// The gateway takes reactions. + pub has_reactions: bool, + /// The gateway has topics. + pub has_topics: bool, + /// The pins were asked for and are not there yet. + pub pins_loading: bool, + /// The topics were asked for and are not there yet. + pub topics_loading: bool, + /// The header's pins count, -1 while unknown. + pub pins_count: i32, + /// The header's topics count, -1 while unknown. + pub topics_count: i32, + /// The pins drawer's rows. + pub pins: Vec, + /// The topics drawer's rows. + pub topics: Vec, + /// The open topic, -1 without one. + pub current_topic: i32, + /// Its title. + pub topic_title: String, + /// Its messages. + pub topic_lines: Vec, +} + +/// The tabs, the lines and the drawers of the current session's chat; +/// none when no server is shown. +pub fn chat_view(state: &AppState, facts: &LinesFacts<'_>) -> Option { + let view = current_view(state)?; + // Private chats are on the messages page, not in the strip. + let (strip, current) = super::strip(view.tabs.iter().map(|t| &t.target), view.current_tab); + let tabs: Vec = strip + .iter() + .map(|&i| &view.tabs[i]) + .map(|t| { + let (last, time) = + t.messages.last().map(|m| super::preview(&m.message.message)).unwrap_or_default(); + let channel = match t.target { + ChatTarget::Channel(cid) => view.presence.channels.get(&cid), + _ => None, + }; + ChatTab { + last: last.into(), + time: time.into(), + title: t.title.clone().into(), + name: super::tab_name(&t.title, &t.target).into(), + kind: match t.target { + ChatTarget::Server => 0, + ChatTarget::Channel(_) => 1, + ChatTarget::Private(_) => 2, + }, + id: match t.target { + ChatTarget::Channel(cid) => cid as i32, + _ => 0, + }, + unread: t.unread, + topic: channel.and_then(|c| c.topic.clone()).unwrap_or_default().into(), + banner: crate::tree::banner( + &view.pictures, + channel.and_then(|c| c.banner_gfx_url.as_deref()), + ), + banner_mode: channel.map_or(0, |c| crate::tree::banner_mode(c.banner_mode)), + } + }) + .collect(); + let tab = &view.tabs[view.current_tab]; + // Sessions without stored history push their lines themselves. + let lines = view.has_history().then(|| lines_of(state, view, tab, true, facts)); + let divider = lines.as_ref().and_then(|l| l.iter().position(|l| l.unread_start)); + // The "New" divider: how many came from there on, and when. + let new = tab + .divider + .and_then(|d| tab.messages.iter().position(|m| m.message.id == d)) + .map_or(&[][..], |i| &tab.messages[i..]); + let session = state.current.unwrap_or_default(); + let count = new.iter().filter(|m| !is_own(state, session, &m.message.message)).count(); + let pins: Vec = tab + .pins + .iter() + .map(|p| { + let avatar = p.message.message.author_uid.as_ref().and_then(|u| view.avatars.get(u)); + let ctx = LineCtx { + key: p.key, + avatar: crate::avatar::image(avatar), + gateway: true, + ..Default::default() + }; + PinItem { + line: super::history_line(&p.message, None, &ctx), + by: format!("Pinned by {} · {}", p.by, super::time_of(p.ts_ms)).into(), + } + }) + .collect(); + let filter = state.topic_filter.trim().to_lowercase(); + let now = chrono::Utc::now().timestamp_millis(); + let topics: Vec = tab + .topics + .iter() + .filter(|t| filter.is_empty() || t.title.to_lowercase().contains(&filter)) + .map(|t| TopicItem { + id: t.id as i32, + title: t.title.clone().into(), + creator: t.creator.name.clone().into(), + detail: format!( + "{} {} · by {}", + t.message_count, + if t.message_count == 1 { "message" } else { "messages" }, + t.creator.name + ) + .into(), + activity: format!("Last active {}", ago(t.last_activity_ms)).into(), + recent: now - t.last_activity_ms < 3_600_000, + archived: t.archived, + }) + .collect(); + Some(ChatView { + tabs, + strip, + current, + current_chat: view.current_tab as i32, + lines, + unread_index: divider.map_or(-1, |i| i as i32), + unread_count: count as i32, + unread_since: new + .first() + .map(|m| super::since_time(m.message.message.ts_ms)) + .unwrap_or_default(), + more_history: view.has_history() && !tab.complete, + loading_history: tab.loading, + local_history: view.has_history() && !tab.synced && view.gateway_has(feature::HISTORY), + has_pins: view.gateway_has(feature::PINS), + has_reactions: view.gateway_has(feature::REACTIONS), + has_topics: view.gateway_has(feature::TOPICS), + pins_loading: !tab.pins_loaded && view.gateway_has(feature::PINS), + topics_loading: !tab.topics_loaded && view.gateway_has(feature::TOPICS), + pins_count: super::known_count(tab.pins_loaded, tab.pins.len()), + topics_count: super::known_count(tab.topics_loaded, tab.topics.len()), + pins, + topics, + current_topic: tab.topic.map_or(-1, |t| t as i32), + topic_title: tab + .topic + .and_then(|t| tab.topics.iter().find(|i| i.id == t)) + .map(|t| t.title.clone()) + .unwrap_or_default(), + topic_lines: lines_of(state, view, tab, false, facts), + }) +} + +/// What a failed gateway request tells the user. What the app asked for by +/// itself (history, lists, subscriptions) fails quietly; what the user did +/// says so in plain words, never the gateway's; the gateway's own +/// administration page shows its message as it is. +pub fn failure_text(request: &str, code: Option, message: &str) -> Option { + if request.starts_with("config_") || request.starts_with("perm_") { + return Some(format!("{request}: {message}")); + } + // The requests a user makes by hand (a list, not an or-pattern: the + // pattern's layout differs between rustfmt releases). + const DONE_BY_USER: [&str; 11] = [ + "post", + "pin", + "unpin", + "react", + "unreact", + "create_topic", + "update_topic", + "create_event", + "update_event", + "delete_event", + "rsvp", + ]; + if !DONE_BY_USER.contains(&request) { + return None; + } + let text = match code { + Some(ErrorCode::Forbidden) => "Not allowed on this server.", + Some(ErrorCode::RateLimited) => "Too many requests; try again in a moment.", + Some(ErrorCode::QuotaExceeded) => "This server's limit is reached.", + Some(ErrorCode::NotFound) => "That is no longer there.", + Some(ErrorCode::FeatureDisabled) => "This server does not offer that.", + _ => "That did not work; try again later.", + }; + Some(text.to_owned()) +} + +/// A directory entry's stream id and viewer count, when it has both. +fn viewers_of(entry: &voelin_gateway_proto::StreamEntry) -> Option<(String, u32)> { + Some((entry.stream_id.clone()?, entry.viewers?)) +} + +fn pin_row(key: i32, pin: Pin) -> PinRow { + PinRow { key, message: pin.message, by: pin.by.name, ts_ms: pin.ts_ms } +} + +fn upsert_topic(topics: &mut Vec, topic: TopicInfo) { + match topics.iter().position(|t| t.id == topic.id) { + Some(i) => topics[i] = topic, + None => topics.insert(0, topic), + } +} + +#[cfg(test)] +mod tests { + use voelin_core::Event; + + use super::*; + use crate::events::apply; + use crate::host::testing::{Fake, State, presence, said, session, state}; + use voelin_core::VoiceState; + + #[test] + fn relative_times() { + let now = chrono::Utc::now().timestamp_millis(); + assert_eq!(ago(now), "just now"); + assert_eq!(ago(now - 3 * 60_000), "3 min ago"); + assert_eq!(ago(now - 3 * 3_600_000), "3 hours ago"); + assert_eq!(ago(now - 36 * 3_600_000), "yesterday"); + } + + #[test] + fn failures_say_what_the_user_did_never_the_gateway() { + let lost = "websocket: IO error: Connection refused (os error 111)"; + // The app's own requests fail quietly. + for request in ["history", "sync", "pins", "events", "subscribe_streams"] { + assert_eq!(failure_text(request, None, lost), None, "{request}"); + } + // The user's own, in plain words. + assert_eq!( + failure_text("pin", Some(ErrorCode::Forbidden), "no b_pin").as_deref(), + Some("Not allowed on this server.") + ); + let text = failure_text("post", None, lost).unwrap(); + assert!(!text.contains("websocket") && !text.to_lowercase().contains("gateway"), "{text}"); + // The gateway's administration page shows its message. + assert_eq!( + failure_text("config_set", Some(ErrorCode::BadRequest), "bad value").as_deref(), + Some("config_set: bad value") + ); + } + + /// Server 1 connected into Games with its chat (messages 6 and 7 of + /// Alice, a gateway with pins, reactions and topics), the Games tab + /// shown. + fn games() -> (State, Fake) { + let mut st = state(); + let host = Fake::default(); + for event in [ + Event::Presence { session: 1, presence: presence() }, + Event::State { session: 1, state: session(VoiceState::Connected, Some(2)) }, + Event::ChatHistory { + session: 1, + target: ChatTarget::Channel(2), + messages: vec![said(6, 190, false, "hi"), said(7, 200, false, "there")], + source: HistorySource::Local, + complete: false, + }, + ] { + apply(&mut st, &host, event); + } + st.sessions.get_mut(&1).unwrap().gateway_caps = + [feature::PINS, feature::REACTIONS, feature::TOPICS].map(String::from).into(); + (st, host) + } + + fn commands<'a>(cx: &'a Cx<'_>) -> Vec<&'a Command> { + cx.update.commands.iter().collect() + } + + /// Tabs open, are selected and closed (never the server's), and a message + /// goes to the chat on screen. + #[test] + fn tabs_open_are_selected_and_closed() { + let (mut st, host) = games(); + let mut cx = Cx::new(&host); + open_chat(&mut st, &mut cx, ChatTarget::Channel(1), true); + let view = &st.sessions[&1]; + assert_eq!(view.tabs.len(), 3); + assert_eq!(view.tabs[view.current_tab].target, ChatTarget::Channel(1)); + assert!( + matches!(commands(&cx).as_slice(), [Command::OpenChat { session: 1, target }, ..] if target == &ChatTarget::Channel(1)) + ); + // The gateway's pins and topics of the chat are asked for once. + assert!(commands(&cx).iter().any(|c| matches!( + c, + Command::Gateway { + request: GatewayRequest::Pins { target: ChatTarget::Channel(1) }, + .. + } + ))); + let mut cx = Cx::new(&host); + send_message(&st, &mut cx, "hello".into()); + assert!(matches!( + commands(&cx).as_slice(), + [Command::SendChat { session: 1, target: ChatTarget::Channel(1), text }] if text == "hello" + )); + // Back to Games; a topic that was open is closed with the move. + st.sessions.get_mut(&1).unwrap().tabs[1].topic = Some(3); + let mut cx = Cx::new(&host); + select_tab(&mut st, &mut cx, 1); + assert_eq!(st.sessions[&1].current_tab, 1); + assert_eq!(st.sessions[&1].tabs[1].topic, None); + assert!(cx.update.refresh.chat && cx.update.refresh.servers); + // The server's chat stays; the Lobby's goes, and the chat on screen with it. + let mut cx = Cx::new(&host); + close_tab(&mut st, &mut cx, 0); + assert_eq!(st.sessions[&1].tabs.len(), 3); + st.sessions.get_mut(&1).unwrap().set_current_tab(2); + close_tab(&mut st, &mut cx, 2); + assert_eq!(st.sessions[&1].tabs.len(), 2); + assert!(matches!( + commands(&cx).first(), + Some(Command::CloseChat { session: 1, target: ChatTarget::Channel(1) }) + )); + assert_eq!( + st.sessions[&1].tabs[st.sessions[&1].current_tab].target, + ChatTarget::Channel(2) + ); + } + + /// What the chat view shows: the strip, the lines, the divider and the + /// drawers' counts. + #[test] + fn the_chat_view_has_the_strip_the_divider_and_the_counts() { + let (mut st, host) = games(); + let facts = LinesFacts { pictures_shown: false, pokes: &[] }; + let chat = chat_view(&st, &facts).unwrap(); + assert_eq!(chat.strip, [0, 1]); + assert_eq!(chat.tabs.iter().map(|t| &*t.title).collect::>(), ["Server", "Games"]); + assert_eq!((chat.current, chat.current_chat), (1, 1)); + assert_eq!(chat.tabs[1].last.as_ref(), "Alice: there"); + // The stored page has the engine's history: its lines are rebuilt from + // the messages (and the server chat starts with the server's own). + assert_eq!(chat.lines.as_ref().map(Vec::len), Some(2)); + assert!(chat.has_pins && chat.has_reactions && chat.has_topics); + assert_eq!((chat.pins_count, chat.topics_count), (-1, -1)); + assert!(chat.pins_loading && chat.topics_loading); + assert_eq!((chat.unread_index, chat.unread_count), (-1, 0)); + assert!(chat.more_history && !chat.loading_history); + + // A message while away is new; on screen it gets the divider. + apply( + &mut st, + &host, + Event::ChatHistory { + session: 1, + target: ChatTarget::Channel(2), + messages: vec![said(8, 300, false, "new")], + source: HistorySource::Live, + complete: false, + }, + ); + host.shown.set(true); + let mut cx = Cx::new(&host); + assert!(track_reading(&mut st, &mut cx)); + let chat = chat_view(&st, &facts).unwrap(); + assert_eq!((chat.unread_index, chat.unread_count), (2, 1)); + assert!(!chat.unread_since.is_empty()); + assert!(chat.lines.as_ref().unwrap()[2].unread_start); + // Marked read: the divider goes and the position is kept. + let mut cx = Cx::new(&host); + mark_read(&mut st, &mut cx); + let chat = chat_view(&st, &facts).unwrap(); + assert_eq!((chat.unread_index, chat.unread_count), (-1, 0)); + assert_eq!(host.written.borrow().last().map(|w| (w.2.ts_ms, w.2.id)), Some((300, 8))); + + // Nothing on screen without a server. + st.current = None; + assert!(chat_view(&st, &facts).is_none()); + } + + /// Pins and topics: asked for when opened, the topic's messages, the + /// highlight of a pinned message, reactions. + #[test] + fn pins_topics_and_reactions() { + let (mut st, host) = games(); + let mut cx = Cx::new(&host); + open_pins(&st, &mut cx); + open_topics(&st, &mut cx); + assert!(matches!( + commands(&cx).as_slice(), + [ + Command::Gateway { request: GatewayRequest::Pins { .. }, .. }, + Command::Gateway { + request: GatewayRequest::Topics { include_archived: false, .. }, + .. + }, + ] + )); + assert!(cx.update.refresh.chat); + // A pin to jump to. + let pinned = Pin { + message: said(6, 190, false, "hi"), + by: voelin_gateway_proto::UserRef { uid: "alice=".into(), name: "Alice".into() }, + ts_ms: 10, + }; + let mut cx = Cx::new(&host); + gateway_update( + &mut st, + &mut cx, + 1, + GatewayUpdate::Pins { target: ChatTarget::Channel(2), pins: vec![pinned] }, + ); + let key = st.sessions[&1].tabs[1].pins[0].key; + let mut cx = Cx::new(&host); + assert_eq!(jump_to_pin(&mut st, &mut cx, key), Some(0)); + assert_eq!(st.sessions[&1].tabs[1].marked, Some(6)); + // A pin of a message that is not loaded is highlighted once it is. + assert_eq!(jump_to_pin(&mut st, &mut cx, 999), None); + assert_eq!(st.sessions[&1].tabs[1].marked, None); + // A topic: its history is asked for, going back closes it. + let mut cx = Cx::new(&host); + open_topic(&mut st, &mut cx, 5); + assert_eq!(st.sessions[&1].tabs[1].topic, Some(5)); + assert!(matches!( + commands(&cx).as_slice(), + [Command::Gateway { request: GatewayRequest::TopicHistory { topic: 5, .. }, .. }] + )); + let mut cx = Cx::new(&host); + send_topic_message(&st, &mut cx, "in the topic".into()); + assert!(matches!( + commands(&cx).as_slice(), + [Command::Gateway { request: GatewayRequest::Post { topic: Some(5), .. }, .. }] + )); + open_topic(&mut st, &mut cx, -1); + assert_eq!(st.sessions[&1].tabs[1].topic, None); + // The search of the drawer redraws only when the text changes. + let mut cx = Cx::new(&host); + search_topics(&mut st, &mut cx, "ban".into()); + search_topics(&mut st, &mut cx, "ban".into()); + assert_eq!(st.topic_filter, "ban"); + // Reactions and pins go by the gateway's id of the message. + let mut cx = Cx::new(&host); + let key = st.sessions[&1].tabs[1].messages[0].key; + react(&st, &mut cx, key, "👍".into()); + pin(&st, &mut cx, key, true); + create_topic(&st, &mut cx, key, "Plans".into()); + assert!(matches!( + commands(&cx).as_slice(), + [ + Command::Gateway { request: GatewayRequest::React { message_id: 1006, .. }, .. }, + Command::Gateway { request: GatewayRequest::Pin { message_id: 1006 }, .. }, + Command::Gateway { + request: GatewayRequest::CreateTopic { message_id: Some(1006), .. }, + .. + }, + ] + )); + // The sample sessions have no gateway to ask. + let demo = Fake { demo: true, ..Default::default() }; + let mut cx = Cx::new(&demo); + react(&st, &mut cx, key, "👍".into()); + assert!(cx.update.commands.is_empty()); + } + + /// Older pages are asked for once; files are downloaded into a folder and + /// uploaded from the composer. + #[test] + fn older_pages_and_files() { + let (mut st, host) = games(); + let mut cx = Cx::new(&host); + assert!(load_older(&mut st, &mut cx).is_none()); + assert!(matches!( + commands(&cx).as_slice(), + [Command::LoadOlderHistory { session: 1, before: Some(6), .. }] + )); + assert!(st.sessions[&1].tabs[1].loading); + // Asked: not again before the answer. + let mut cx = Cx::new(&host); + assert!(load_older(&mut st, &mut cx).is_none() && cx.update.commands.is_empty()); + // The sample data answers itself. + st.sessions.get_mut(&1).unwrap().tabs[1].loading = false; + let demo = Fake { demo: true, ..Default::default() }; + let mut cx = Cx::new(&demo); + let sample = load_older(&mut st, &mut cx).unwrap(); + assert_eq!((sample.session, sample.oldest.map(|m| m.id)), (1, Some(6))); + assert!(cx.update.commands.is_empty()); + + // A file the message links: downloaded into the folder, shown as it runs. + let link = "[URL=ts3file://ts.example?port=9987&channel=2&path=%2F&channelpassword=&filename=a.png&isDir=0&size=2048&fileSize=2048]a.png[/URL]"; + apply( + &mut st, + &host, + Event::ChatHistory { + session: 1, + target: ChatTarget::Channel(2), + messages: vec![said(9, 400, false, link)], + source: HistorySource::Live, + complete: false, + }, + ); + let key = st.sessions[&1].tabs[1].messages.last().unwrap().key; + let mut cx = Cx::new(&host); + download_file(&mut st, &mut cx, key, 0, Path::new("/home/me/Downloads")); + assert!(matches!( + commands(&cx).as_slice(), + [Command::DownloadChatFile { session: 1, transfer: 1, to: DownloadTo::Path { path, .. }, .. }] + if path == Path::new("/home/me/Downloads/a.png") + )); + let facts = LinesFacts { pictures_shown: false, pokes: &[] }; + let chat = chat_view(&st, &facts).unwrap(); + let line = chat.lines.unwrap().pop().unwrap(); + assert_eq!(line.files.len(), 1); + assert_eq!((&*line.files[0].state, &*line.files[0].detail), ("running", "Starting…")); + // Attaching: a channel's chat takes files, the server's does not. + assert_eq!(attach_target(&st), Ok(Some((1, 2)))); + st.sessions.get_mut(&1).unwrap().set_current_tab(0); + assert!(attach_target(&st).is_err()); + let mut cx = Cx::new(&host); + upload(&mut st, &mut cx, 1, 2, PathBuf::from("/tmp/notes.txt")); + assert!(matches!( + commands(&cx).as_slice(), + [Command::UploadFile { session: 1, channel: 2, path, .. }] if path == "/notes.txt" + )); + assert_eq!(cx.update.status.as_deref(), Some("Uploading notes.txt…")); + assert_eq!(st.uploads.len(), 1); + } + + /// A private chat shows the pokes of its peer among its messages. + #[test] + fn a_private_chat_has_the_pokes_of_its_peer() { + let (mut st, host) = games(); + let direct = said(20, 1000, false, "psst"); + let mut direct_message = direct.clone(); + direct_message.message.target = ChatTarget::Private("alice=".into()); + apply( + &mut st, + &host, + Event::ChatHistory { + session: 1, + target: ChatTarget::Private("alice=".into()), + messages: vec![direct_message], + source: HistorySource::Local, + complete: true, + }, + ); + let pokes = [Poke { + session: 1, + uid: Some("alice=".into()), + name: "Alice".into(), + message: "hey".into(), + ts_ms: 500, + }]; + let view = &st.sessions[&1]; + let tab = view.tabs.iter().find(|t| t.is_private()).unwrap(); + let facts = LinesFacts { pictures_shown: false, pokes: &pokes }; + let lines = lines_of(&st, view, tab, true, &facts); + assert_eq!(lines.len(), 2); + assert_eq!(lines[0].key, -1_000_000, "the poke came first"); + let none = + lines_of(&st, view, tab, true, &LinesFacts { pictures_shown: false, pokes: &[] }); + assert_eq!(none.len(), 1); + } +} diff --git a/crates/voelin-ui-vm/src/chat.rs b/crates/voelin-ui-vm/src/chat/mod.rs similarity index 96% rename from crates/voelin-ui-vm/src/chat.rs rename to crates/voelin-ui-vm/src/chat/mod.rs index e7c0b3c..dbc8667 100644 --- a/crates/voelin-ui-vm/src/chat.rs +++ b/crates/voelin-ui-vm/src/chat/mod.rs @@ -1,6 +1,9 @@ //! Chat lines: one [`ChatLine`] per message, with its text in blocks of //! styled runs (`vm::bbcode`), its reactions and the files and pictures it -//! links. +//! links; [`logic`] has what happens to a session's chats when the engine +//! tells something. + +pub mod logic; use std::borrow::Cow; use std::cell::RefCell; @@ -9,7 +12,7 @@ use std::path::PathBuf; use unicode_segmentation::UnicodeSegmentation; use voelin_core::HistoryMessage; -use voelin_model::{ChatMessage, ChatTarget, FileRef, Presence}; +use voelin_model::{ChatMessage, ChatTarget, FileRef, HostMessageMode, Presence, ServerDetails}; use crate::avatar; use crate::bbcode::{self, BlockKind, Doc, Span, Style}; @@ -17,6 +20,32 @@ use crate::bridge::{ChatLine, FileItem, ReactionItem, TextBlock, TextRun}; use crate::color::Rgb; use crate::emoji; use crate::image::ImageRef; +use crate::state::{SessionView, Tab}; + +/// Where the server's welcome and host message keep what their lines were +/// built from (`LineCache`), apart from the messages' ids. +pub const SERVER_LINES: [i64; 2] = [i64::MIN, i64::MIN + 1]; + +/// What the server says to everyone who connects, with where its line keeps +/// its parts: its welcome message, and its host message when that goes to +/// the chat log. +pub fn server_texts(details: &ServerDetails) -> Vec<(&str, i64)> { + let host = details.host_message_mode == HostMessageMode::Log; + [Some(&details.welcome_message), host.then_some(&details.host_message)] + .into_iter() + .zip(SERVER_LINES) + .filter_map(|(text, id)| Some((text.filter(|t| !t.trim().is_empty())?.as_str(), id))) + .collect() +} + +/// The text of the server's line `key` (-1, -2, ...) of a server chat, if +/// `tab` is one. +pub fn server_text<'a, L>(view: &'a SessionView, tab: &Tab, key: i32) -> Option<&'a str> { + if tab.target != ChatTarget::Server || key >= 0 { + return None; + } + server_texts(&view.presence.server).get((-1 - key) as usize).map(|(text, _)| *text) +} /// Lines of the same author within this time are grouped (no header). const GROUP_MS: i64 = 5 * 60 * 1000; @@ -24,7 +53,9 @@ const GROUP_MS: i64 = 5 * 60 * 1000; /// The author and time of the line before, for grouping. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Previous { + /// Who wrote it. pub author: String, + /// When, in milliseconds since the epoch. pub ts_ms: i64, } diff --git a/crates/voelin-ui/src/dev.rs b/crates/voelin-ui-vm/src/dev/logic.rs similarity index 61% rename from crates/voelin-ui/src/dev.rs rename to crates/voelin-ui-vm/src/dev/logic.rs index 597d088..7d0a7e3 100644 --- a/crates/voelin-ui/src/dev.rs +++ b/crates/voelin-ui-vm/src/dev/logic.rs @@ -1,77 +1,19 @@ -//! Development switches (environment variables), for trying screens and -//! taking screenshots without a server: -//! -//! - `VOELIN_DATA_DIR=`: the database (app.rs). -//! - `VOELIN_AUTOCONNECT=voice|observe`: connect the first bookmark on start. -//! - `VOELIN_SCREENSHOT=`: save the window after -//! `VOELIN_SCREENSHOT_DELAY` seconds (default 4) and exit. -//! - `VOELIN_WINDOW_SIZE=x`: the window's size (e.g. `390x844` for the -//! phone layout). -//! - `VOELIN_DEMO_UI=1`: sample servers, channels, chat (two pages of older -//! messages answer scrolling up) and streams, no server needed (nothing is -//! stored). -//! - `VOELIN_DEMO_STREAM=1`: a local test stream in the viewer. -//! - `VOELIN_OPEN=[,...]`: open screens on start: `home`, -//! `server` (`server:chat`: its server chat), `settings[:
]` -//! (voice, keybinds, streaming, privacy, appearance, or 0-4), `about`, -//! `share`, `bookmark` (add a server, also `join`; -//! `bookmark:edit` the current one, Advanced open), -//! `emoji` (the picker), `client` (the volume dialog of the first other -//! client once connected), `panel` / `no-panel` (the members panel), -//! `voice` (the voice channel view; on the phone its own screen; -//! `voice:compact` with the smaller stage, not stored), -//! `more` (after `voice` on the phone: the voice screen's More menu, -//! opened once the screen is laid out), -//! `members` (the phone's members page), `notification` (a tapped voice -//! notification), `shared:` (text shared to the app on Android), -//! `pins`, `topics` (the drawers), -//! `topic:` (a topic's messages), `member` (the member card of the -//! first other client), `poke` (the poke dialog: for the contact shown -//! after `friends`, else for the first other client, its card open), -//! `channel-password` (the password dialog of the first locked channel, -//! the sample's Officers; `channel-password:wrong` as after a refused -//! one), `actions` (the last message's actions, as if hovered), -//! `first-run` (home's banner as before the first server, over the -//! sample data), -//! `unread` (the current chat read up to five messages before its end: -//! the "New" divider, scrolled up to; `unread:end` ten messages before, -//! at the list's end, under the bar that counts the new messages), -//! `link-confirm[:]` (the question before a masked link opens, by -//! default the sample's raid board), `link:` (a TeamSpeak link -//! opened: the server dialog filled in from it, or in voice on its -//! server a move into its channel), `watch` (the first stream; with -//! sample data the local test pattern in its place), `theatre` (after -//! `watch`: in theatre mode), `popout` (`watch` in a window of its own), -//! `tab:` (phone layout); `friends[:]`, -//! `messages[:]` (a private chat), `inbox` (offline messages), -//! `library`, `events`, `event-form`, `search[:]`, -//! `notifications` (the bell), `offline` (an offline message), `picture` -//! (a chat picture opened large), `camera` (the settings' camera -//! preview); settings sections also `account`, -//! `profiles` (also `identities`), `devices`, `notifications`, -//! `integrations`, `advanced` (5-10); -//! `studio[:]`: the Stream Studio (with `VOELIN_DEMO_UI` a demo -//! studio from synthetic sources), `studio:window` in a window of its own, -//! `studio:live` going live (also with a screen opened after it: -//! `studio:live,server,voice` shows our stream's card with the studio's -//! picture), `studio:record`, or a dialog: `studio:source`, -//! `studio:audio`, `studio:camera`, `studio:scene`, `studio:settings`. -//! A screenshot also saves the studio's window, or the stream's -//! (`-window.png`), and draws it over the main window. -//! - `VOELIN_AUTOWATCH=1`: watch the first stream that shows up. -//! - `VOELIN_AUTOSHARE=test-pattern`: share the test pattern (accepting -//! everyone) once connected to a TeamSpeak 6 server. +//! Sample data of `VOELIN_DEMO_UI`: servers, channels, people, chats, +//! contacts, notices and pictures, as plain values and as the events a +//! server would send. A front end feeds the events to +//! [`crate::events::handle`], so the screens are filled by the same code +//! that fills them from a real server; nothing here touches the engine, +//! the store or a toolkit. The pictures are PNG bytes the front end saves +//! where it wants. +use std::path::PathBuf; use std::sync::Arc; -use std::time::Duration; -use anyhow::Result; -use slint::{ComponentHandle, Rgba8Pixel, SharedPixelBuffer}; use voelin_core::gateway::Pin; use voelin_core::stream::{StreamInfo, StreamKind}; use voelin_core::{ - BackendInfo, Contact, Event, GatewayUpdate, HistoryMessage, HistorySource, JoinFailure, - ObserveState, OfflineMessageInfo, Relation, SessionState, Source, VoiceState, + BackendInfo, Contact, Event, GatewayUpdate, HistoryMessage, HistorySource, ObserveState, + OfflineMessageInfo, Relation, SessionState, Source, VoiceState, }; use voelin_gateway_proto::{ Action, Attendee, ConfigEntry, ConfigSource, EventInfo, EventKind, EventSpec, PermRule, @@ -79,426 +21,19 @@ use voelin_gateway_proto::{ feature, }; use voelin_model::{ - BannerMode, Capabilities, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, GroupInfo, Presence, + BannerMode, Capabilities, ChannelId, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, + GroupInfo, Presence, }; use voelin_store::{Bookmark, MessageSource}; -use crate::app::{App, Bridge, MainWindow, MobileTab, Nav, Page, SettingsSection, with_app}; +use crate::bridge::RecordingItem; use crate::settings::LastVoice; -use crate::vm::bridge::RecordingItem; +use crate::social::logic::Social; +use crate::social::{NoticeKind, NoticeRequest, NoticeTarget}; +use crate::state::{AppState, Lines}; -/// The switches read at start. -#[derive(Clone, Debug, Default)] -pub(crate) struct Switches { - pub demo_stream: bool, - pub demo_ui: bool, - pub autoshare: bool, - pub open_client: bool, - open: Vec, - autoconnect: Option, - screenshot: Option, - screenshot_delay: u64, - window_size: Option<(f32, f32)>, -} - -fn flag(name: &str) -> bool { - std::env::var(name).is_ok_and(|v| v == "1") -} - -/// `390x844` → (390, 844). -fn parse_size(text: &str) -> Option<(f32, f32)> { - let (w, h) = text.split_once(['x', 'X'])?; - Some((w.trim().parse().ok()?, h.trim().parse().ok()?)) -} - -impl Switches { - pub fn from_env() -> Self { - let open: Vec = std::env::var("VOELIN_OPEN") - .unwrap_or_default() - .split(',') - .map(|s| s.trim().to_owned()) - .filter(|s| !s.is_empty()) - .collect(); - Self { - demo_stream: flag("VOELIN_DEMO_STREAM"), - demo_ui: flag("VOELIN_DEMO_UI"), - autoshare: std::env::var("VOELIN_AUTOSHARE").is_ok_and(|v| v == "test-pattern"), - open_client: open.iter().any(|o| o == "client"), - open, - autoconnect: std::env::var("VOELIN_AUTOCONNECT").ok(), - screenshot: std::env::var_os("VOELIN_SCREENSHOT").map(Into::into), - screenshot_delay: std::env::var("VOELIN_SCREENSHOT_DELAY") - .ok() - .and_then(|d| d.parse().ok()) - .unwrap_or(4), - window_size: std::env::var("VOELIN_WINDOW_SIZE").ok().as_deref().and_then(parse_size), - } - } -} - -fn section(name: &str) -> SettingsSection { - match name { - "1" | "keybinds" | "ptt" => SettingsSection::Keybinds, - "2" | "streaming" => SettingsSection::Streaming, - "3" | "privacy" => SettingsSection::Privacy, - "4" | "appearance" => SettingsSection::Appearance, - "5" | "account" => SettingsSection::Account, - "6" | "profiles" | "identities" => SettingsSection::Profiles, - "7" | "devices" => SettingsSection::Devices, - "8" | "notifications" => SettingsSection::Notifications, - "9" | "integrations" => SettingsSection::Integrations, - "10" | "advanced" => SettingsSection::Advanced, - _ => SettingsSection::Voice, - } -} - -fn mobile_tab(name: &str) -> MobileTab { - match name { - "home" => MobileTab::Home, - "servers" => MobileTab::Servers, - "activity" => MobileTab::Activity, - "you" => MobileTab::You, - _ => MobileTab::Chat, - } -} - -/// Timers that must live while the window runs. -pub(crate) struct Running { - _screenshot: Option, - _resize: Option, - _scroll: Option, - _more: Option, -} - -/// Apply the switches once the app is set up. -pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running { - if let Some((w, h)) = switches.window_size { - ui.window().set_size(slint::LogicalSize::new(w, h)); - } - if switches.demo_ui { - with_app(demo_ui); - } - match switches.autoconnect.as_deref() { - Some("voice") => { - with_app(|app| app.connect_voice()); - } - Some("observe") => { - with_app(|app| { - if let Some(id) = app.state.current { - app.observe(id); - } - }); - } - _ => {} - } - let nav = ui.global::