Merge phase5/ui-vm-2: the remaining Slint controllers split into toolkit-free logic (voelin-ui-vm) and Slint bind files, the engine-event transitions in vm::events::apply, the ui-vm gate follow-ups (plan section 6 step 2)
CI / Linux checks (push) Successful in 25m39s

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Fable 5.1 committed 2026-10-25 10:59:44 +03:00
commit 2e985d793c
64 files changed
+12756 -6409

No files matched your search

+11 -7
View File
@@ -69,13 +69,17 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
### Changed
- The view models, the app's state and the decisions of the settings pages and
of the Stream Studio moved out of `voelin-ui` into a new crate,
`voelin-ui-vm`, which depends on no UI toolkit (a second front end can use
it); `voelin-ui` converts its plain rows into Slint's and keeps the window,
the Bridge writes and the engine's tasks. The chat formatting reader and the
Twemoji archive moved with them. Nothing changes on screen. See
docs/ui.md, "Two crates".
- The 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
Generated
+1
View File
@@ -9768,6 +9768,7 @@ dependencies = [
"image",
"miniz_oxide 0.8.9",
"png",
"roxmltree",
"serde",
"serde_json",
"unicode-segmentation",
+7 -5
View File
@@ -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
+15 -1
View File
@@ -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<Span>,
}
/// 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<Block>,
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -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<L>, tab: &Tab<L>, 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,
}
File diff suppressed because it is too large. Load diff
+6
View File
@@ -0,0 +1,6 @@
//! The sample data of `VOELIN_DEMO_UI` and the helpers of the development
//! switches that only look at the state. [`logic`] has the sample servers,
//! people, chats, contacts, notices and pictures as plain values and as the
//! events a server would send.
pub mod logic;
+2
View File
@@ -298,7 +298,9 @@ pub fn first_key(text: &str) -> Option<String> {
/// A piece of text: plain, or one emoji (`emoji` is its key).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Run {
/// The text: the word with its space, or the emoji's own characters.
pub text: String,
/// The key of the Twemoji picture, none for plain text.
pub emoji: Option<String>,
}
+103
View File
@@ -0,0 +1,103 @@
//! What a server's gateway tells besides chat: its events (the events page,
//! RSVP, reminders), the stream directory and the activity feed (the home
//! page), our permissions there, its configuration (gateway administration).
//! The pins, reactions and topics are in `chat::logic`.
use voelin_core::{GatewayRequest, GatewayUpdate};
use voelin_gateway_proto::{EventQuery, feature};
use crate::host::Cx;
use crate::social::{NoticeKind, NoticeRequest, NoticeTarget, server_name};
use crate::state::{AppState, Lines};
/// Keep what a gateway update tells the home, events and administration
/// screens (before the chat handles its part), and ask for what a new
/// connection needs.
pub fn extra<L: Lines>(state: &mut AppState<L>, cx: &mut Cx<'_>, id: i64, update: &GatewayUpdate) {
use GatewayUpdate as U;
let mut ask: Vec<GatewayRequest> = Vec::new();
let mut remind = None;
let extra = &mut state.sessions.entry(id).or_default().extra;
match update {
U::Connected { uid, capabilities, .. } => {
extra.gateway_uid = Some(uid.clone());
let has = |f: &str| capabilities.iter().any(|c| c == f);
ask.push(GatewayRequest::Permissions { channel: None });
if has(feature::EVENTS) {
ask.push(GatewayRequest::Events { query: EventQuery::default() });
}
if has(feature::STREAMS) {
ask.push(GatewayRequest::Streams);
}
if has(feature::ACTIVITY) {
ask.push(GatewayRequest::Activity { before: None, limit: Some(30) });
}
}
U::Disconnected { .. } => {
extra.directory.clear();
extra.events.clear();
extra.events_loaded = false;
extra.activity.clear();
extra.actions.clear();
extra.config.clear();
extra.perms.clear();
}
U::Permissions { channel: None, actions } => extra.actions = actions.clone(),
U::Events { events } => {
extra.events = events.clone();
extra.events.sort_by_key(|e| e.spec.start_ms);
extra.events_loaded = true;
}
U::Event { event } => {
match extra.events.iter().position(|e| e.id == event.id) {
Some(i) => extra.events[i] = event.clone(),
None => extra.events.push(event.clone()),
}
extra.events.sort_by_key(|e| e.spec.start_ms);
}
U::EventDeleted { id: event } => extra.events.retain(|e| e.id != *event),
U::EventReminder { event, starts_in_ms } => remind = Some((event.clone(), *starts_in_ms)),
U::Streams { streams } => extra.directory = streams.clone(),
U::StreamStarted { stream }
| U::StreamUpdated { stream }
| U::StreamRegistered { stream } => {
extra.directory.retain(|e| e.id != stream.id);
extra.directory.push(stream.clone());
}
U::StreamEnded { id: stream, .. } => extra.directory.retain(|e| e.id != *stream),
U::Activity { entries, .. } => extra.activity = entries.clone(),
U::ActivityAdded { entry } => {
extra.activity.insert(0, entry.clone());
extra.activity.truncate(100);
}
U::Config { entries } => extra.config = entries.clone(),
U::ConfigValue { entry } => match extra.config.iter().position(|e| e.key == entry.key) {
Some(i) => extra.config[i] = entry.clone(),
None => extra.config.push(entry.clone()),
},
U::PermRules { rules } => extra.perms = rules.clone(),
_ => return,
}
for request in ask {
cx.gateway_to(id, request);
}
if let Some((event, starts_in_ms)) = remind {
let minutes = starts_in_ms / 60_000;
let title = if minutes <= 0 {
format!("{} starts now", event.spec.title)
} else {
format!("{} starts in {minutes} min", event.spec.title)
};
cx.update.notices.push(NoticeRequest {
kind: NoticeKind::Event,
title,
body: format!("on {}", server_name(state, id)),
target: NoticeTarget::Event(id, event.id),
name: event.creator.name.clone(),
uid: Some(event.creator.uid.clone()),
});
}
cx.update.refresh.home = true;
cx.update.refresh.events = true;
cx.update.refresh.gateways = true;
}
+531
View File
@@ -0,0 +1,531 @@
//! What the engine's events do to the client's state. [`handle`] takes an
//! [`Event`], changes the [`AppState`] and the [`Social`] state and returns
//! an [`Update`]: what to draw again, the status line, the commands for the
//! engine, what to keep. A front end calls it for every event and then does
//! what the update says; it has no dispatch of its own, so the Slint client
//! and a GPUI one change the state the same way. [`apply`] is the part that
//! changes the [`AppState`] alone; [`handle`] first lets
//! [`crate::social::logic::event`] look at the event (the friends, the
//! pokes, the notices and the offline messages), which has to see the state
//! as it was before the event.
//!
//! In [`Update::rest`] come back the events whose state is not in the
//! [`AppState`]: the Stream Studio's stream (`Host::studio_streams_to`), a
//! setting that changed (the settings service), and the answers to the
//! offline message requests (the list that failed, a request that is done),
//! which the messages page keeps (docs/ui.md, "Controllers still to split").
//! A front end handles them before it draws what the update says is to be
//! drawn again. The text of an offline message is not among them: it is
//! state of the [`Social`], changed by [`handle`].
mod gateway;
use voelin_core::{BackendInfo, Command, Event, GatewayUpdate, JoinFailure, Source, VoiceState};
use voelin_model::{ChannelId, ChatTarget};
use voelin_store::Bookmark;
use crate::chat::logic::{
add_message, gateway_update, history_batch, load_reads, open_chat, save_reads, track_reading,
transfer_progress,
};
use crate::host::{Cx, Host, Persist, Update};
use crate::previews::fetch_previews;
use crate::servers::{AfterConnect, JoinStep, after_connect, join_password};
use crate::settings::LastVoice;
use crate::social::logic::Social;
use crate::state::{AppState, Lines, SessionView};
use crate::streams::logic as streams;
/// Apply an event to the [`AppState`]; see the [module](self).
pub fn apply<L: Lines>(state: &mut AppState<L>, host: &dyn Host, event: Event) -> Update {
let mut cx = Cx::new(host);
dispatch(state, &mut cx, event);
finish(state, cx)
}
/// Take an event in: what the social screens make of it first
/// ([`crate::social::logic::event`]), then [`apply`]. The one entry point
/// of a front end.
pub fn handle<L: Lines, D>(
state: &mut AppState<L>,
social: &mut Social<D>,
host: &dyn Host,
event: Event,
) -> Update {
let mut cx = Cx::new(host);
crate::social::logic::event(state, social, &mut cx, &event);
dispatch(state, &mut cx, event);
finish(state, cx)
}
/// The status line shows what the update says.
fn finish<L>(state: &mut AppState<L>, cx: Cx<'_>) -> Update {
if let Some(text) = &cx.update.status {
state.status.clone_from(text);
}
cx.update
}
fn dispatch<L: Lines>(state: &mut AppState<L>, cx: &mut Cx<'_>, event: Event) {
// The Stream Studio's stream is the studio's.
if let Event::StreamState { session, .. } | Event::StreamViewers { session, .. } = &event
&& cx.host.studio_streams_to(*session as i64)
{
cx.update.rest = Some(event);
return;
}
match event {
Event::State { session, state: now } => session_state(state, cx, session as i64, now),
Event::ServerInfo { session, name, backend, capabilities } => {
let id = session as i64;
state.sessions.entry(id).or_default().capabilities = capabilities;
adopt_server_name(state, cx, id, &name);
if state.current == Some(id) {
cx.status(connected_status(&name, &backend));
}
cx.update.refresh.streams = true;
cx.update.autoshare = true;
}
Event::Presence { session, presence } => {
let id = session as i64;
let view = state.sessions.entry(id).or_default();
// The server chat shows its welcome and host message, with their
// pictures.
let said = crate::chat::server_texts(&view.presence.server)
!= crate::chat::server_texts(&presence.server);
// Our channel's path: known only now (a new connection), or
// renamed.
let path = |v: &SessionView<L>| {
v.state.own_channel.map(|c| crate::tree::channel_path(&v.presence, c))
};
let path_before = path(view);
view.presence = presence;
let renamed = path(view) != path_before;
apply_client_playback(state, cx, id);
join_after_connect(state, cx, id);
if renamed && remember_voice(state, cx, id) {
cx.update.refresh.servers = true;
}
if state.current == Some(id) {
if said {
fetch_previews(state, cx, id);
}
let r = &mut cx.update.refresh;
(r.toolbar, r.tree, r.chat, r.streams) = (true, true, true, true);
cx.update.first_client = true;
}
}
Event::Talking { session, client, talking } => {
let id = session as i64;
let view = state.sessions.entry(id).or_default();
if talking {
view.talking.insert(client);
} else {
view.talking.remove(&client);
}
if state.current == Some(id) {
cx.update.refresh.tree = true;
}
}
Event::InputLevel { session, level_db, sending } => {
let shown = match session {
Some(s) => state.current == Some(s as i64),
None => state.mic_test,
};
if shown {
cx.update.input_level = Some((level_db, sending));
}
}
Event::MicrophoneTestError { message } => {
cx.status(format!("Microphone test: {message}"));
}
// Only for sessions the engine keeps no history for (it does not
// know the server yet): those get ids and reactions instead.
Event::Chat { session, message } => {
let id = session as i64;
if !state.sessions.entry(id).or_default().has_history() {
add_message(state, cx, id, message);
}
}
Event::ChatHistory { session, target, messages, source, complete } => {
history_batch(state, cx, session as i64, &target, messages, source, complete);
}
Event::Gateway { session, update } => {
let id = session as i64;
if let GatewayUpdate::Connected { url, .. } = &update {
gateway_in_use(state, cx, id, url);
}
gateway::extra(state, cx, id, &update);
gateway_update(state, cx, id, update);
}
Event::Groups { session, server_groups, channel_groups } => {
let id = session as i64;
let view = state.sessions.entry(id).or_default();
view.server_groups = (*server_groups).clone();
// Display order, as TeamSpeak sorts them.
view.server_groups.sort_by_key(|g| (g.sort_id, g.id));
view.channel_groups = (*channel_groups).clone();
if state.current == Some(id) {
cx.update.refresh.tree = true;
}
}
Event::ServerDetails { session, address, details } => {
remember_server_icon(state, cx, session as i64, &address, details.icon);
cx.update.refresh.servers = true;
cx.update.refresh.toolbar = true;
}
// Pictures can arrive after the rows were built: draw them again.
Event::AvatarReady { session, client_uid, path, .. } => {
let id = session as i64;
// A file that arrives again is decoded again if it changed.
cx.update.reloaded.push(path.clone());
state.sessions.entry(id).or_default().avatars.insert(client_uid, path);
if state.current == Some(id) {
let r = &mut cx.update.refresh;
(r.tree, r.chat, r.toolbar, r.member_card, r.streams) =
(true, true, true, true, true);
}
}
Event::IconReady { session, icon, path } => {
let id = session as i64;
cx.update.reloaded.push(path.clone());
state.sessions.entry(id).or_default().icons.insert(icon, path);
cx.update.refresh.servers = true;
if state.current == Some(id) {
cx.update.refresh.tree = true;
cx.update.refresh.toolbar = true;
}
}
Event::PictureReady { session, url, path } => {
let id = session as i64;
// The host banner reloads into the same file.
cx.update.reloaded.push(path.clone());
state.sessions.entry(id).or_default().pictures.insert(url, path);
if state.current == Some(id) {
let r = &mut cx.update.refresh;
(r.toolbar, r.tree, r.chat, r.member_card) = (true, true, true, true);
}
}
Event::Transfer { session, transfer, state: progress } => {
transfer_progress(state, cx, session as i64, transfer, progress);
}
// The engine's contacts would replace the sample ones.
Event::ContactsChanged { .. } if cx.host.demo_ui() && !state.contacts.is_empty() => {}
Event::ContactsChanged { contacts } => {
state.contacts = contacts.iter().map(|c| (c.uid.clone(), c.clone())).collect();
cx.update.refresh.member_card = true;
}
// The sample sessions of VOELIN_DEMO_UI are unknown to the engine.
Event::Error { .. } if cx.host.demo_ui() => {}
Event::Error { message, .. } => cx.status(message),
Event::JoinFailed { session, channel, reason } => {
join_failed(state, cx, session as i64, channel, reason);
}
Event::SettingRejected { key, message } => {
cx.status(format!("Setting {key}: {message}"));
}
Event::StreamsChanged { session, streams } => {
let id = session as i64;
// Development switch: watch the first stream that shows up.
let autowatch = cx.host.autowatch() && !cx.host.watching() && state.current == Some(id);
// A client whose stream was asked for while it was looked up.
let pending = state
.pending_watch
.filter(|(s, _)| *s == id)
.and_then(|(_, client)| streams.iter().find(|s| s.streamer == client))
.map(|s| s.id.clone());
let view = state.sessions.entry(id).or_default();
let first = streams
.iter()
.find(|s| view.state.own_client != Some(s.streamer))
.map(|s| s.id.clone());
view.streams = streams;
cx.update.refresh.streams = true;
cx.update.refresh.servers = true;
if let Some(stream) = pending {
state.pending_watch = None;
cx.update.watch = Some(stream);
} else if autowatch && let Some(stream) = first {
cx.update.watch = Some(stream);
}
}
// The streams we share and watch.
Event::StreamState { session, state: now } => {
streams::share_state(state, cx, session as i64, now);
}
Event::StreamViewerRequest { session, viewer, .. } => {
streams::viewer_request(state, cx, session as i64, viewer);
}
Event::StreamViewers { session, viewers } => {
streams::viewers(state, cx, session as i64, viewers);
}
Event::WatchState { session, stream_id, state: now } => {
streams::watch_state(state, cx, session as i64, &stream_id, now);
}
Event::WatchLayers { session, stream_id, layers, layer } => {
streams::watch_layers(state, cx, session as i64, &stream_id, layers, layer);
}
// Also flagged on the sink, which the encoder reads.
Event::StreamKeyframeRequest { .. } | Event::StreamLayerBitrate { .. } => {}
// The text of an offline message is in the `Social` state, which
// `handle` has changed before (`social::logic::event`).
Event::OfflineMessage { .. } => {}
// What the settings service and the offline messages' requests make
// of the rest, the front end keeps (see the module's note).
event => cx.update.rest = Some(event),
}
}
/// A session's connections changed.
fn session_state<L: Lines>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
id: i64,
now: voelin_core::SessionState,
) {
let view = state.sessions.entry(id).or_default();
let was_voice = view.state.voice;
let was_observe = view.state.observe;
let was_channel = view.state.own_channel;
view.state = now.clone();
if now.voice != VoiceState::Connected {
view.focused_own_channel = false;
}
if now.voice == VoiceState::Disconnected && was_voice != VoiceState::Disconnected {
view.channel_passwords.clear();
view.join_after_connect = None;
}
if now.voice == VoiceState::Connected && was_voice != VoiceState::Connected {
// A new connection: volumes are sent again.
view.applied_playback.clear();
}
// Where its chats were read, once the server is known; kept when the
// session ends.
load_reads(state, cx, id);
let off = |voice: VoiceState, observe: voelin_core::ObserveState| {
voice == VoiceState::Disconnected && observe == voelin_core::ObserveState::Off
};
if off(now.voice, now.observe) && !off(was_voice, was_observe) {
save_reads(state, cx, id);
}
let focus = !state.sessions.entry(id).or_default().focused_own_channel;
if now.voice == VoiceState::Connected && was_voice != VoiceState::Connected {
cx.status("Connected");
}
if state.current == Some(id) {
if track_reading(state, cx) {
cx.update.refresh.chat = true;
}
// The voice channel's chat is always at hand, and focused once per
// connection.
if let (Some(cid), VoiceState::Connected) = (now.own_channel, now.voice) {
open_chat(state, cx, ChatTarget::Channel(cid), focus);
state.sessions.entry(id).or_default().focused_own_channel = true;
}
}
// Where we are with voice, when it changed here: home's last place,
// which the rail's refresh shows (voice on another server does not take
// it back at each of its events).
if (now.voice, now.own_channel) != (was_voice, was_channel) {
remember_voice(state, cx, id);
}
let r = &mut cx.update.refresh;
(r.servers, r.toolbar, r.tree, r.streams) = (true, true, true, true);
cx.update.autoshare = true;
if state.current == Some(id) {
cx.update.first_client = true;
}
join_after_connect(state, cx, id);
}
/// The status line once a server answered: "Connected to Nightfall Guild
/// (TeamSpeak 6 6.0.0-beta13.1)".
pub fn connected_status(name: &str, backend: &BackendInfo) -> String {
format!("Connected to {name} ({})", backend.label())
}
/// The gateway logged in at `url`: it is the one in use from now on.
fn gateway_in_use<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, id: i64, url: &str) {
let Some(b) = state.bookmarks.iter_mut().find(|b| b.id == id) else { return };
if b.gateway_in_use(url) {
cx.persist(Persist::Bookmark { id, what: "gateway in use" });
}
}
/// The server told its name: a server still named by its address takes it,
/// so the address is all a user has to type.
fn adopt_server_name<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, id: i64, name: &str) {
let Some(b) = state.bookmarks.iter_mut().find(|b| b.id == id && b.name == b.address) else {
return;
};
if name.trim().is_empty() || cx.host.demo_ui() {
return;
}
b.name = name.trim().to_owned();
cx.persist(Persist::Bookmark { id, what: "server named" });
cx.update.refresh.servers = true;
cx.update.refresh.toolbar = true;
}
/// Apply only details originating from the bookmark's current address.
/// Returns whether its persisted metadata changed.
pub fn apply_server_icon<L>(
bookmark: &mut Bookmark,
view: &mut SessionView<L>,
address: &str,
icon: u32,
) -> bool {
if bookmark.address != address {
return false;
}
view.icon_address = Some(address.to_owned());
view.server_icon = icon;
let before = bookmark.cached_server_icon.clone();
bookmark.remember_server_icon(icon);
bookmark.cached_server_icon != before
}
/// Keep only metadata supplied by the bookmark's current server.
fn remember_server_icon<L: Lines>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
id: i64,
address: &str,
icon: u32,
) {
let Some(bookmark) = state.bookmarks.iter_mut().find(|b| b.id == id) else {
return;
};
let changed = apply_server_icon(bookmark, state.sessions.entry(id).or_default(), address, icon);
if changed && !cx.host.demo_ui() {
cx.persist(Persist::Bookmark { id, what: "server icon" });
}
}
/// Keep where we are with voice in `session` as the last place
/// (`ui.last_voice`); whether it changed. Not for the sample sessions.
pub fn remember_voice<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, session: i64) -> bool {
if cx.host.demo_ui() {
return false;
}
let Some(view) = state.sessions.get(&session) else { return false };
let (VoiceState::Connected, Some(cid)) = (view.state.voice, view.state.own_channel) else {
return false;
};
let channel = crate::tree::channel_path(&view.presence, cid);
let Some(b) = state.bookmarks.iter().find(|b| b.id == session).filter(|_| !channel.is_empty())
else {
return false;
};
let last = LastVoice { bookmark: session, address: b.address.clone(), channel };
if state.settings.last_voice.as_ref() == Some(&last) {
return false;
}
state.settings.last_voice = Some(last);
cx.persist(Persist::Settings);
true
}
/// Send the stored volumes of clients that appeared in a voice session.
pub fn apply_client_playback<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, session: i64) {
let Some(view) = state.sessions.get_mut(&session) else { return };
if view.state.voice != VoiceState::Connected
|| view.state.presence_source != Some(Source::Voice)
{
return;
}
let presence = view.presence.clone();
view.applied_playback.retain(|id| presence.clients.contains_key(id));
for client in presence.clients.values() {
if !view.applied_playback.insert(client.id) {
continue;
}
let stored = client.uid.as_ref().and_then(|uid| state.playback.get(uid));
let Some(playback) = stored else { continue };
let (s, c) = (session as u64, client.id);
cx.send(Command::SetClientVolume { session: s, client: c, volume: playback.volume });
if playback.muted {
cx.send(Command::SetClientMuted { session: s, client: c, muted: true });
}
}
}
/// Connected into another channel than the one asked for
/// (`SessionView::join_after_connect`): the server says nothing when, for
/// one, the password was wrong, so it is joined again, and that move says
/// why. Once the channel shows in the voice connection's presence, which
/// can come after the own channel.
pub fn join_after_connect<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, session: i64) {
let Some(view) = state.sessions.get_mut(&session) else { return };
let (VoiceState::Connected, Some(asked)) = (view.state.voice, view.join_after_connect) else {
return;
};
let known = view.presence.channels.contains_key(&asked);
match after_connect(view.state.own_channel, asked, known) {
AfterConnect::Wait => {}
AfterConnect::Joined => view.join_after_connect = None,
AfterConnect::JoinAgain => {
view.join_after_connect = None;
move_into(state, cx, session, asked);
}
}
}
/// Move into a channel of a session connected with voice: with its
/// password, or asking for one when it is locked and none was given this
/// connection.
fn move_into<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, session: i64, channel: ChannelId) {
let Some(view) = state.sessions.get(&session) else { return };
let Some(info) = view.presence.channels.get(&channel) else { return };
let remembered = view.channel_passwords.get(&channel).map(String::as_str);
match join_password(info, remembered) {
JoinStep::Send(password) => {
cx.send_real(Command::MoveToChannel { session: session as u64, channel, password });
}
JoinStep::Ask => ask_password(state, cx, session, channel, false),
}
}
/// Open the password dialog for a locked channel; `wrong`: the one given
/// was refused.
pub fn ask_password<L>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
session: i64,
channel: ChannelId,
wrong: bool,
) {
let Some(info) = state.sessions.get(&session).and_then(|v| v.presence.channels.get(&channel))
else {
return;
};
let name = crate::tree::channel_title(info).0.to_owned();
state.join_target = Some((session, channel));
cx.ask_password(name, wrong);
}
/// The server refused a move ([`Event::JoinFailed`]): a password asks again
/// (the one given is forgotten), the rest is a toast.
pub fn join_failed<L>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
session: i64,
channel: ChannelId,
reason: JoinFailure,
) {
match reason {
JoinFailure::Password => {
let given = state
.sessions
.get_mut(&session)
.and_then(|v| v.channel_passwords.remove(&channel))
.is_some();
ask_password(state, cx, session, channel, given);
}
JoinFailure::Full => cx.status("The channel is full"),
JoinFailure::Other(text) => cx.status(text),
}
}
#[cfg(test)]
mod tests;
+725
View File
@@ -0,0 +1,725 @@
//! Tapes of engine events replayed through [`apply`] against a fake host:
//! the state they leave, and what each update asks of a front end.
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use voelin_core::StreamState;
use voelin_core::gateway::Pin;
use voelin_core::stream::StreamInfo;
use voelin_core::{
BackendInfo, Command, Event, GatewayRequest, GatewayUpdate, HistoryMessage, HistorySource,
JoinFailure, TransferState, VoiceState,
};
use voelin_gateway_proto::{UserRef, feature};
use voelin_model::{Capabilities, ChatMessage, ChatTarget};
use voelin_store::{Bookmark, ChatRead, ChatTarget as StoredTarget};
use super::*;
use crate::host::Refresh;
use crate::host::testing::Fake;
use crate::settings::{ClientPlayback, LastVoice};
use crate::host::testing::{State, presence, said, session, state};
fn games(messages: Vec<HistoryMessage>, source: HistorySource) -> Event {
Event::ChatHistory {
session: 1,
target: ChatTarget::Channel(2),
messages,
source,
complete: true,
}
}
fn run(state: &mut State, host: &Fake, tape: Vec<Event>) -> Vec<Update> {
tape.into_iter().map(|event| apply(state, host, event)).collect()
}
fn gateway(update: GatewayUpdate) -> Event {
Event::Gateway { session: 1, update }
}
fn open_chats(update: &Update) -> Vec<ChatTarget> {
update
.commands
.iter()
.filter_map(|c| match c {
Command::OpenChat { target, .. } => Some(target.clone()),
_ => None,
})
.collect()
}
/// A first connection to a server, event by event: what the session knows
/// after each, and what the front end is told to do.
#[test]
fn a_first_connection() {
let mut st = state();
let host = Fake {
reads: HashMap::from([(
"srv=".to_owned(),
vec![(StoredTarget::Channel(2), ChatRead { ts_ms: 200, id: 7, updated_ms: 1 })],
)]),
..Default::default()
};
let backend = BackendInfo { product: "TeamSpeak 6".into(), version: "6.0.0".into() };
let caps = Capabilities { streams: true, file_transfer: true, ..Default::default() };
// Connecting: the rail and the bar change, nothing is sent.
let ups = run(
&mut st,
&host,
vec![Event::State { session: 1, state: session(VoiceState::Connecting, None) }],
);
assert_eq!(st.sessions[&1].state.voice, VoiceState::Connecting);
assert!(ups[0].refresh.servers && ups[0].refresh.toolbar && ups[0].refresh.tree);
assert!(ups[0].commands.is_empty() && ups[0].status.is_none() && ups[0].autoshare);
// The server answers: it gives its name to a bookmark that has only the
// address, and says what it runs.
let ups = run(
&mut st,
&host,
vec![Event::ServerInfo {
session: 1,
name: " Nightfall Guild ".into(),
backend,
capabilities: caps,
}],
);
assert_eq!(st.bookmarks[0].name, "Nightfall Guild");
assert_eq!(ups[0].persist, [Persist::Bookmark { id: 1, what: "server named" }]);
assert_eq!(
ups[0].status.as_deref(),
Some("Connected to Nightfall Guild (TeamSpeak 6 6.0.0)")
);
assert_eq!(st.status, "Connected to Nightfall Guild (TeamSpeak 6 6.0.0)");
assert!(st.sessions[&1].capabilities.streams && ups[0].refresh.streams);
// Its presence: the bar, the tree and the chat are drawn; the stored
// volume of Alice is sent once voice is connected, not before.
st.playback.insert("alice=".into(), ClientPlayback { volume: 0.5, muted: true });
let ups = run(&mut st, &host, vec![Event::Presence { session: 1, presence: presence() }]);
assert_eq!(st.sessions[&1].presence.clients.len(), 2);
assert!(ups[0].refresh.tree && ups[0].refresh.chat && ups[0].first_client);
assert!(ups[0].commands.is_empty());
// Voice connected into Games: its chat opens and is shown, with the
// store's read marker; the place is remembered.
let ups = run(
&mut st,
&host,
vec![Event::State { session: 1, state: session(VoiceState::Connected, Some(2)) }],
);
let view = &st.sessions[&1];
assert_eq!(view.reads_of.as_deref(), Some("srv="));
assert_eq!(view.tabs[view.current_tab].target, ChatTarget::Channel(2));
assert_eq!(view.tabs[view.current_tab].read, Some((200, 7)));
assert_eq!(view.channel_tab, ChatTarget::Channel(2));
assert!(view.focused_own_channel);
assert_eq!(open_chats(&ups[0]), [ChatTarget::Channel(2)]);
assert_eq!(ups[0].status.as_deref(), Some("Connected"));
assert_eq!(
st.settings.last_voice,
Some(LastVoice {
bookmark: 1,
address: "ts.example".into(),
channel: vec!["Games".into()]
})
);
assert!(ups[0].persist.contains(&Persist::Settings));
assert!(ups[0].refresh.chat && ups[0].refresh.servers);
// The presence again, now that voice is connected: Alice's volume goes
// to the engine, once.
let ups = run(
&mut st,
&host,
vec![
Event::Presence { session: 1, presence: presence() },
Event::Presence { session: 1, presence: presence() },
],
);
assert!(matches!(
ups[0].commands.as_slice(),
[
Command::SetClientVolume { session: 1, client: 11, volume },
Command::SetClientMuted { session: 1, client: 11, muted: true },
] if *volume == 0.5
));
assert!(ups[1].commands.is_empty());
}
/// The messages of a chat: a stored page, then live ones, with the chat on
/// screen or not, and what is kept of how far it was read.
#[test]
fn messages_are_counted_read_and_kept() {
let mut st = state();
let host = Fake::default();
run(
&mut st,
&host,
vec![
Event::Presence { session: 1, presence: presence() },
Event::State { session: 1, state: session(VoiceState::Connected, Some(2)) },
],
);
// The stored page: two read before, one new. (Its marker came from the
// store: nothing here, so what the tab held when the page came counts as
// read.)
let ups = run(
&mut st,
&host,
vec![games(
vec![said(6, 190, false, "hi"), said(7, 200, true, "hello"), said(8, 300, false, "x")],
HistorySource::Local,
)],
);
let tab = &st.sessions[&1].tabs[1];
assert_eq!(tab.messages.iter().map(|m| m.message.id).collect::<Vec<_>>(), [6, 7, 8]);
assert!(tab.complete && !tab.loading);
assert_eq!(tab.unread, 0, "a first page is what was read");
assert_eq!(ups[0].chats, [(1, ChatTarget::Channel(2))]);
assert!(ups[0].refresh.chat);
// A live message while the chat is not on screen is new.
let ups =
run(&mut st, &host, vec![games(vec![said(9, 400, false, "new")], HistorySource::Live)]);
assert_eq!(st.sessions[&1].tabs[1].unread, 1);
assert!(ups[0].refresh.servers, "the rail counts it");
// Our own is not.
st.own_uids.insert("me=".into());
run(&mut st, &host, vec![games(vec![said(10, 410, true, "mine")], HistorySource::Live)]);
assert_eq!(st.sessions[&1].tabs[1].unread, 1);
// The chat comes on screen: read up to its end, a divider over the new.
host.shown.set(true);
let mut cx = Cx::new(&host);
assert!(crate::chat::logic::track_reading(&mut st, &mut cx));
let tab = &st.sessions[&1].tabs[1];
assert_eq!((tab.unread, tab.divider, tab.read), (0, Some(9), Some((410, 10))));
assert_eq!(st.reading, Some((1, ChatTarget::Channel(2))));
// A live one now is read at once.
run(&mut st, &host, vec![games(vec![said(11, 500, false, "seen")], HistorySource::Live)]);
assert_eq!(st.sessions[&1].tabs[1].unread, 0);
assert_eq!(st.sessions[&1].tabs[1].read, Some((500, 11)));
// The session ends: where the chats were read is stored, and what the
// store has is what the tab then says it has.
let mut ended = session(VoiceState::Disconnected, None);
ended.server_uid = Some("srv=".into());
let ups = run(&mut st, &host, vec![Event::State { session: 1, state: ended }]);
let written = host.written.borrow();
assert_eq!(written.len(), 1, "{written:?}");
assert_eq!(written[0].0, "srv=");
assert_eq!(written[0].1, StoredTarget::Channel(2));
assert_eq!((written[0].2.ts_ms, written[0].2.id), (500, 11));
assert_eq!(st.sessions[&1].tabs[1].stored_read, Some((500, 11)));
assert!(ups[0].refresh.servers);
}
/// Where the chat lines go when the engine keeps no history (it does not
/// know the server yet): one row appended per message.
#[test]
fn a_session_without_history_appends_lines() {
let mut st = state();
let host = Fake::default();
let message = |text: &str| ChatMessage {
target: ChatTarget::Server,
author_name: "Alice".into(),
author_uid: Some("alice=".into()),
author_id: Some(11),
text: text.into(),
ts_ms: 1000,
via_relay: false,
blocked: false,
};
let ups = run(
&mut st,
&host,
vec![
Event::Chat { session: 1, message: message("one") },
Event::Chat { session: 1, message: message("two") },
],
);
let tab = &st.sessions[&1].tabs[0];
assert_eq!(tab.lines.len(), 2);
assert_eq!(tab.unread, 2);
assert_eq!(ups[1].chats, [(1, ChatTarget::Server)]);
assert!(ups[1].refresh.chat && ups[1].refresh.servers);
// With a server unique id the engine has the history, and the live
// message arrives as `ChatHistory`.
st.sessions.get_mut(&1).unwrap().state.server_uid = Some("srv=".into());
run(&mut st, &host, vec![Event::Chat { session: 1, message: message("three") }]);
assert_eq!(st.sessions[&1].tabs[0].lines.len(), 2);
}
/// What a gateway brings: capabilities, requests for what the screens
/// show, pins, the stream directory, reminders for the bell.
#[test]
fn a_gateway_connects_and_tells() {
let mut st = state();
let host = Fake::default();
run(
&mut st,
&host,
vec![
Event::Presence { session: 1, presence: presence() },
Event::State { session: 1, state: session(VoiceState::Connected, Some(2)) },
],
);
let caps: Vec<String> = [feature::EVENTS, feature::PINS, feature::TOPICS, feature::STREAMS]
.map(String::from)
.into();
st.bookmarks[0].gateway_urls = vec!["wss://gw.example/v1".into()];
let ups = run(
&mut st,
&host,
vec![gateway(GatewayUpdate::Connected {
url: "wss://gw.example/v1".into(),
gateway_id: "g".into(),
server_uid: "srv=".into(),
server_name: "Nightfall Guild".into(),
uid: "me=".into(),
capabilities: caps,
})],
);
let view = &st.sessions[&1];
assert!(view.gateway_has(feature::PINS) && view.gateway_has(feature::EVENTS));
assert_eq!(view.extra.gateway_uid.as_deref(), Some("me="));
assert_eq!(
st.bookmarks[0].gateway_url.as_deref(),
Some("wss://gw.example/v1"),
"the gateway in use is kept"
);
assert!(ups[0].persist.contains(&Persist::Bookmark { id: 1, what: "gateway in use" }));
// The permissions, the events and the directory, then the current
// chat's pins and topics.
let asked: Vec<&GatewayRequest> = ups[0]
.commands
.iter()
.filter_map(|c| match c {
Command::Gateway { session: 1, request } => Some(request),
_ => None,
})
.collect();
assert!(matches!(
asked.as_slice(),
[
GatewayRequest::Permissions { channel: None },
GatewayRequest::Events { .. },
GatewayRequest::Streams,
GatewayRequest::Pins { target: ChatTarget::Channel(2) },
GatewayRequest::Topics { target: ChatTarget::Channel(2), .. },
]
));
assert!(ups[0].refresh.home && ups[0].refresh.events && ups[0].refresh.gateways);
// The answers: pins (newest first), the directory's viewer counts, a
// failed request of the user.
let pin = |id: i64, ts_ms: i64| Pin {
message: said(id, ts_ms, false, "pinned"),
by: UserRef { uid: "alice=".into(), name: "Alice".into() },
ts_ms,
};
let ups = run(
&mut st,
&host,
vec![
gateway(GatewayUpdate::Pins {
target: ChatTarget::Channel(2),
pins: vec![pin(3, 10), pin(4, 20)],
}),
gateway(GatewayUpdate::Failed {
request: "pin".into(),
code: Some(voelin_gateway_proto::ErrorCode::Forbidden),
message: "no".into(),
}),
],
);
let tab = &st.sessions[&1].tabs[1];
assert!(tab.pins_loaded);
assert_eq!(tab.pins.iter().map(|p| p.message.id).collect::<Vec<_>>(), [4, 3]);
assert!(ups[0].refresh.chat);
assert_eq!(ups[1].status.as_deref(), Some("Not allowed on this server."));
// Gone: nothing of the gateway stays.
run(&mut st, &host, vec![gateway(GatewayUpdate::Disconnected { reason: None })]);
let view = &st.sessions[&1];
assert!(view.gateway_caps.is_empty() && !view.tabs[1].pins_loaded);
}
/// A password that was refused asks again, and says so the second time.
#[test]
fn a_locked_channel_asks_for_its_password() {
let mut st = state();
let host = Fake::default();
run(&mut st, &host, vec![Event::Presence { session: 1, presence: presence() }]);
let failed = || Event::JoinFailed { session: 1, channel: 1, reason: JoinFailure::Password };
let ups = run(&mut st, &host, vec![failed()]);
let prompt = ups[0].password.clone().unwrap();
assert_eq!((prompt.name.as_str(), prompt.wrong), ("Lobby", false));
assert_eq!(st.join_target, Some((1, 1)));
// A password was given and refused: it is forgotten, the prompt says so.
st.sessions.get_mut(&1).unwrap().channel_passwords.insert(1, "nope".into());
let ups = run(&mut st, &host, vec![failed()]);
assert!(ups[0].password.as_ref().unwrap().wrong);
assert!(st.sessions[&1].channel_passwords.is_empty());
// The others are a toast.
let ups = run(
&mut st,
&host,
vec![Event::JoinFailed { session: 1, channel: 1, reason: JoinFailure::Full }],
);
assert_eq!(ups[0].status.as_deref(), Some("The channel is full"));
}
/// Connected into another channel than the one asked for: joined again,
/// with the password given this connection.
#[test]
fn a_channel_asked_for_and_not_entered_is_joined_again() {
let mut st = state();
let host = Fake::default();
run(&mut st, &host, vec![Event::Presence { session: 1, presence: presence() }]);
let view = st.sessions.get_mut(&1).unwrap();
view.join_after_connect = Some(1);
view.channel_passwords.insert(1, "pw".into());
// Connected into Games, not the Lobby that was asked for.
let ups = run(
&mut st,
&host,
vec![Event::State { session: 1, state: session(VoiceState::Connected, Some(2)) }],
);
assert!(ups[0].commands.iter().any(|c| matches!(
c,
Command::MoveToChannel { session: 1, channel: 1, password: Some(p) } if p == "pw"
)));
assert_eq!(st.sessions[&1].join_after_connect, None);
// The sample sessions send nothing to the engine.
let mut demo = state();
let host = Fake { demo: true, ..Default::default() };
run(&mut demo, &host, vec![Event::Presence { session: 1, presence: presence() }]);
demo.sessions.get_mut(&1).unwrap().join_after_connect = Some(1);
let ups = run(
&mut demo,
&host,
vec![Event::State { session: 1, state: session(VoiceState::Connected, Some(2)) }],
);
assert!(open_chats(&ups[0]).is_empty());
assert!(!ups[0].commands.iter().any(|c| matches!(c, Command::MoveToChannel { .. })));
}
/// Pictures and files: the engine's cache, an upload from the composer, a
/// download that runs, the contacts, errors.
#[test]
fn pictures_files_contacts_and_errors() {
let mut st = state();
let host = Fake::default();
run(&mut st, &host, vec![Event::Presence { session: 1, presence: presence() }]);
let path = PathBuf::from("/cache/avatars/ab");
let ups = run(
&mut st,
&host,
vec![
Event::AvatarReady {
session: 1,
client_uid: "alice=".into(),
path: path.clone(),
hash: "ab".into(),
},
Event::IconReady { session: 1, icon: 5, path: "/cache/icons/5".into() },
Event::PictureReady {
session: 1,
url: "https://e.com/a.png".into(),
path: "/cache/pictures/a".into(),
},
],
);
let view = &st.sessions[&1];
assert_eq!(view.avatars.get("alice="), Some(&path));
assert!(view.icons.contains_key(&5) && view.pictures.contains_key("https://e.com/a.png"));
assert_eq!(ups[0].reloaded, [path]);
assert_eq!(
ups[0].refresh,
Refresh {
tree: true,
chat: true,
toolbar: true,
member_card: true,
streams: true,
..Refresh::default()
}
);
assert!(ups[1].refresh.servers && ups[1].refresh.tree && !ups[1].refresh.chat);
// An upload from the composer posts its link once it is up.
st.uploads.insert(7, (1, 2, "notes.txt".into()));
let done = TransferState::Done { size: 12, data: None, path: None };
let ups = run(&mut st, &host, vec![Event::Transfer { session: 1, transfer: 7, state: done }]);
assert!(st.uploads.is_empty());
assert_eq!(ups[0].status.as_deref(), Some("notes.txt shared"));
assert!(matches!(
ups[0].commands.as_slice(),
[Command::SendChat { session: 1, target: ChatTarget::Channel(2), text }] if text.contains("notes.txt")
));
st.uploads.insert(8, (1, 2, "big.iso".into()));
let failed = TransferState::Failed("full".into());
let ups = run(&mut st, &host, vec![Event::Transfer { session: 1, transfer: 8, state: failed }]);
assert_eq!(ups[0].status.as_deref(), Some("Could not upload big.iso: full"));
// Errors and rejected settings reach the status line, but not the sample
// sessions' (the engine does not know them).
let ups = run(
&mut st,
&host,
vec![
Event::Error { session: 1, message: "kicked".into() },
Event::SettingRejected { key: "audio".into(), message: "no".into() },
Event::MicrophoneTestError { message: "no device".into() },
],
);
assert_eq!(ups[0].status.as_deref(), Some("kicked"));
assert_eq!(ups[1].status.as_deref(), Some("Setting audio: no"));
assert_eq!(st.status, "Microphone test: no device");
let demo = Fake { demo: true, ..Default::default() };
let ups = run(&mut st, &demo, vec![Event::Error { session: 1, message: "kicked".into() }]);
assert!(ups[0].status.is_none());
}
/// A client that talks, the meter, the groups in the order TeamSpeak sorts
/// them.
#[test]
fn talking_the_meter_and_groups() {
let mut st = state();
let host = Fake::default();
run(&mut st, &host, vec![Event::Presence { session: 1, presence: presence() }]);
let ups = run(
&mut st,
&host,
vec![
Event::Talking { session: 1, client: 11, talking: true },
Event::Talking { session: 1, client: 11, talking: false },
Event::InputLevel { session: Some(1), level_db: -20.0, sending: true },
Event::InputLevel { session: None, level_db: -30.0, sending: false },
Event::InputLevel { session: Some(2), level_db: -10.0, sending: true },
],
);
assert!(st.sessions[&1].talking.is_empty());
assert!(ups[0].refresh.tree);
assert_eq!(ups[2].input_level, Some((-20.0, true)));
assert_eq!(ups[3].input_level, None, "no microphone test is running");
assert_eq!(ups[4].input_level, None, "another server's");
st.mic_test = true;
let ups = run(
&mut st,
&host,
vec![Event::InputLevel { session: None, level_db: -30.0, sending: false }],
);
assert_eq!(ups[0].input_level, Some((-30.0, false)));
let group = |id, sort_id| voelin_model::GroupInfo { id, sort_id, ..Default::default() };
run(
&mut st,
&host,
vec![Event::Groups {
session: 1,
server_groups: Arc::new(vec![group(7, 20), group(6, 20), group(9, 10)]),
channel_groups: Arc::new(vec![group(5, 0)]),
}],
);
let ids: Vec<_> = st.sessions[&1].server_groups.iter().map(|g| g.id).collect();
assert_eq!(ids, [9, 6, 7]);
}
/// The streams the voice connection lists: the one a lookup waited for is
/// to be watched; the rest of the stream events are the front end's.
#[test]
fn streams_are_listed_and_a_lookup_is_watched() {
let mut st = state();
let host = Fake::default();
run(&mut st, &host, vec![Event::Presence { session: 1, presence: presence() }]);
let stream = |id: &str, streamer| StreamInfo {
id: id.into(),
streamer,
name: "screen".into(),
kind: voelin_core::stream::StreamKind::Screen,
bitrate: 0,
viewer_limit: 0,
audio: false,
viewers: Some(1),
};
let ups = run(
&mut st,
&host,
vec![Event::StreamsChanged { session: 1, streams: vec![stream("s1", 11)] }],
);
assert_eq!(st.sessions[&1].streams.len(), 1);
assert!(ups[0].refresh.streams && ups[0].refresh.servers && ups[0].watch.is_none());
// A client's stream was asked for before the list knew it.
st.pending_watch = Some((1, 11));
let ups = run(
&mut st,
&host,
vec![Event::StreamsChanged { session: 1, streams: vec![stream("s2", 11)] }],
);
assert_eq!(ups[0].watch.as_deref(), Some("s2"));
assert_eq!(st.pending_watch, None);
// The development switch watches the first stream that is not ours.
let host = Fake { autowatch: true, ..Default::default() };
let ups = run(
&mut st,
&host,
vec![Event::StreamsChanged { session: 1, streams: vec![stream("s3", 11)] }],
);
assert_eq!(ups[0].watch.as_deref(), Some("s3"));
// Keyframe requests are the encoder's, read from the sink; a setting that
// changed is the settings service's: the front end keeps it.
let ups = run(
&mut st,
&host,
vec![
Event::StreamKeyframeRequest { session: 1, layer: 0 },
Event::SettingChanged { key: "audio".into() },
],
);
assert!(ups[0].rest.is_none() && ups[0].refresh.is_empty() && ups[0].commands.is_empty());
assert!(matches!(&ups[1].rest, Some(Event::SettingChanged { key }) if key == "audio"));
}
/// The streams of the events: the studio's stream is the studio's; ours and
/// the one we watch change the state and say what the capture and the
/// decoder are to do.
#[test]
fn the_streams_we_share_and_watch_follow_the_events() {
use crate::streams::logic::{Sharing, Watching, demo_viewers};
use voelin_core::WatchState;
use voelin_core::stream::EndReason;
let mut st = state();
run(&mut st, &Fake::default(), vec![Event::Presence { session: 1, presence: presence() }]);
st.share = Some(Sharing { session: 1, live: true, viewers: Vec::new(), stopping: false });
st.watch = Some(Watching {
session: Some(1),
stream_id: "s1".into(),
title: "Speedrun".into(),
streamer: "Alice".into(),
status: String::new(),
connected: true,
ended: false,
has_frame: true,
shown: true,
since: None,
layers: Vec::new(),
layer: None,
});
// The studio streams to the server: its events are handed back as they
// are, and our share is not touched.
let studio = Fake { studio: Some(1), ..Default::default() };
let ups = run(
&mut st,
&studio,
vec![
Event::StreamViewers { session: 1, viewers: demo_viewers() },
Event::StreamState { session: 1, state: StreamState::Ended(EndReason::Stopped) },
],
);
assert!(matches!(ups[0].rest, Some(Event::StreamViewers { .. })));
assert!(matches!(ups[1].rest, Some(Event::StreamState { .. })));
assert!(st.share.as_ref().unwrap().viewers.is_empty() && st.share.as_ref().unwrap().live);
// Elsewhere they are ours.
let host = Fake::default();
let ups = run(
&mut st,
&host,
vec![
Event::StreamViewers { session: 1, viewers: demo_viewers() },
Event::StreamViewerRequest { session: 1, viewer: 11, message: "hi".into() },
Event::WatchState {
session: 1,
stream_id: "s1".into(),
state: WatchState::Ended(EndReason::Stopped),
},
Event::StreamState { session: 1, state: StreamState::Ended(EndReason::Local) },
],
);
assert!(ups[0].refresh.streams && ups[0].rest.is_none());
assert_eq!(ups[1].status.as_deref(), Some("Alice wants to watch your stream"));
let watch = st.watch.as_ref().unwrap();
assert!(watch.ended && ups[2].stream.drop_decoder);
assert_eq!(watch.status, "The stream has ended.");
assert!(st.share.is_none() && ups[3].stream.drop_share && ups[3].stream.mixer);
assert_eq!(ups[3].status.as_deref(), Some("You stopped sharing"));
}
/// Pictures linked in a chat are downloaded once, up to the limit.
#[test]
fn linked_pictures_are_fetched_once() {
let mut st = state();
let host = Fake { limit: 100 * 1024, ..Default::default() };
let mut connected = session(VoiceState::Connected, Some(2));
connected.server_uid = Some("srv=".into());
run(
&mut st,
&host,
vec![
Event::ServerInfo {
session: 1,
name: "S".into(),
backend: BackendInfo::default(),
capabilities: Capabilities { file_transfer: true, ..Default::default() },
},
Event::Presence { session: 1, presence: presence() },
Event::State { session: 1, state: connected },
],
);
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]";
let ups =
run(&mut st, &host, vec![games(vec![said(1, 100, false, link)], HistorySource::Live)]);
let downloads: Vec<_> =
ups[0].commands.iter().filter(|c| matches!(c, Command::DownloadChatFile { .. })).collect();
assert_eq!(downloads.len(), 1, "{:?}", ups[0].commands);
// Asked once: the same page again asks for nothing.
let ups =
run(&mut st, &host, vec![games(vec![said(1, 100, false, link)], HistorySource::Live)]);
assert!(!ups[0].commands.iter().any(|c| matches!(c, Command::DownloadChatFile { .. })));
}
#[test]
fn the_status_line_names_the_servers_software() {
let backend = |product: &str, version: &str| BackendInfo {
product: product.into(),
version: version.into(),
};
assert_eq!(
connected_status("Nightfall Guild", &backend("TeamSpeak 6", "6.0.0-beta13.1")),
"Connected to Nightfall Guild (TeamSpeak 6 6.0.0-beta13.1)"
);
assert_eq!(
connected_status("Pixel Lounge", &backend("TeamSpeak 3", "3.13.8")),
"Connected to Pixel Lounge (TeamSpeak 3 3.13.8)"
);
// Not recognised: the version string the server sent.
assert_eq!(connected_status("Home", &backend("", "custom 9")), "Connected to Home (custom 9)");
}
#[test]
fn a_server_icon_is_taken_from_the_bookmarks_own_address_only() {
let path = std::env::temp_dir()
.join(format!("voelin-server-icon-provenance-{}.svg", std::process::id()));
std::fs::write(
&path,
r#"<svg xmlns="http://www.w3.org/2000/svg" width="4" height="4"><rect width="4" height="4" fill="red"/></svg>"#,
)
.unwrap();
let mut bookmark = Bookmark { address: "a.test".into(), ..Default::default() };
let mut view = SessionView::<()>::default();
view.icons.insert(1234, path.clone());
assert!(apply_server_icon(&mut bookmark, &mut view, "a.test", 1234));
assert_eq!(view.server_icon_for(&bookmark.address).size().width, 4);
// Details from another address, queued before an edit, change nothing.
assert!(!apply_server_icon(&mut bookmark, &mut view, "b.test", 77));
assert_eq!(view.server_icon, 1234);
std::fs::remove_file(path).unwrap();
}
+2
View File
@@ -18,9 +18,11 @@ pub enum ResumeAction {
/// The card: the server, the channel and the button.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Resume {
/// The id of the server's bookmark.
pub bookmark: i64,
/// The channel's path, its names from the top as the server has them.
pub path: Vec<String>,
/// What the button does.
pub action: ResumeAction,
}
+444
View File
@@ -0,0 +1,444 @@
//! What the transitions of the client's state need from the front end and
//! tell it. A transition (`events::apply`, the functions of `chat::logic`)
//! changes the [`AppState`](crate::state::AppState) it is given and puts
//! everything else into an [`Update`]: what to redraw, the status line, the
//! engine commands to send, what to keep; the little it must ask a front end
//! for while it runs (is the chat on screen, what the store knows) goes
//! through [`Host`]. Neither the engine nor the store nor a toolkit is
//! touched here, so the transitions are tested with a fake host
//! (`events::tests`).
use std::path::PathBuf;
use voelin_core::{Command, Event, GatewayRequest, StreamSink};
use voelin_model::ChatTarget;
use voelin_store::{ChatRead, ChatTarget as StoredTarget};
use crate::social::NoticeRequest;
/// What a transition asks of its front end while it runs.
pub trait Host {
/// The sample data of `VOELIN_DEMO_UI` is shown: nothing is sent to the
/// engine or kept in the store.
fn demo_ui(&self) -> bool;
/// The current chat's messages are on screen (a page shows the chat).
fn chat_shown(&self) -> bool;
/// A stream is in the viewer.
fn watching(&self) -> bool;
/// The development switch `VOELIN_AUTOWATCH=1`: watch the first stream
/// that shows up.
fn autowatch(&self) -> bool;
/// The Stream Studio streams to this session: the events of that stream
/// are its own.
fn studio_streams_to(&self, session: i64) -> bool;
/// The largest picture previewed in chats, in bytes (0: none), from
/// `ui.image_preview_kb`.
fn preview_limit(&self) -> u64;
/// Pictures on the web are fetched and shown (`cache.fetch_images`).
fn fetch_images(&self) -> bool;
/// The private chat with this peer (unique id) of this session is on
/// screen, in the messages page.
fn dm_shown(&self, session: i64, uid: &str) -> bool;
/// Now, in milliseconds since the epoch.
fn now_ms(&self) -> i64 {
crate::social::now_ms()
}
/// How far the chats of a server were read, from the store.
fn chat_reads(&self, server_uid: &str) -> Result<Vec<(StoredTarget, ChatRead)>, String>;
/// Keep how far a chat of a server was read.
fn set_chat_read(
&self,
server_uid: &str,
target: &StoredTarget,
read: &ChatRead,
) -> Result<(), String>;
}
/// The parts of the screen to draw again. Each is a function of the state,
/// so a front end draws each flagged part once, however many events set it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Refresh {
/// The server rail.
pub servers: bool,
/// The top bar of the server page.
pub toolbar: bool,
/// The channel tree and the members.
pub tree: bool,
/// The chat tabs, the lines and what belongs to them (pins, topics).
pub chat: bool,
/// The streams panel and the voice card's streams.
pub streams: bool,
/// The stream viewer's header.
pub viewer: bool,
/// The open member card.
pub member_card: bool,
/// The home page.
pub home: bool,
/// The events page.
pub events: bool,
/// The gateway pages of the settings.
pub gateways: bool,
/// The friends page, home's friends and activity, the block list.
pub people: bool,
/// The lists of direct messages and the offline messages (asked for
/// again when a voice connection came up).
pub conversations: bool,
/// The peer card of the open direct message.
pub dm: bool,
}
impl Refresh {
/// Every part.
pub const ALL: Self = Self {
servers: true,
toolbar: true,
tree: true,
chat: true,
streams: true,
viewer: true,
member_card: true,
home: true,
events: true,
gateways: true,
people: true,
conversations: true,
dm: true,
};
/// Whether nothing is to be drawn.
pub fn is_empty(&self) -> bool {
*self == Self::default()
}
}
/// What a transition wants kept.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Persist {
/// The bookmark with this id changed (the store has the old one).
Bookmark {
/// The bookmark.
id: i64,
/// What it was changed for, for the log.
what: &'static str,
},
/// The UI's own settings changed (`AppState::settings`).
Settings,
/// The audio settings changed (`AppState::audio`).
Audio,
/// The clients' local volumes changed (`AppState::playback`).
Playback,
}
/// The password dialog of a locked channel is to open
/// (`AppState::join_target` names the channel).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PasswordPrompt {
/// The channel's name as the tree shows it.
pub name: String,
/// The password given before was refused.
pub wrong: bool,
}
/// What the streams we share and watch need of the front end, which owns the
/// capture and the decoder.
#[derive(Debug, Default)]
pub struct StreamEffects {
/// Encode into the live stream: the sink of our stream.
pub attach: Option<StreamSink>,
/// Our stream is over: the capture stops.
pub drop_share: bool,
/// The watched stream is over, or left: its decoder stops.
pub drop_decoder: bool,
/// The audio mixer's rows follow the capture again.
pub mixer: bool,
/// The player leaves full screen.
pub leave_fullscreen: bool,
}
/// What a transition tells its front end, besides the changed state.
#[derive(Debug, Default)]
pub struct Update {
/// What to draw again.
pub refresh: Refresh,
/// The status line's new text.
pub status: Option<String>,
/// Commands for the engine, in order.
pub commands: Vec<Command>,
/// What to keep, in order.
pub persist: Vec<Persist>,
/// Pictures the engine wrote again: a front end drops what it decoded
/// of them.
pub reloaded: Vec<PathBuf>,
/// The microphone meter: level in dBFS, and whether voice is sent.
pub input_level: Option<(f32, bool)>,
/// Open the password dialog.
pub password: Option<PasswordPrompt>,
/// Notices for the bell, in order.
pub notices: Vec<NoticeRequest>,
/// What went wrong that nothing else shows, for the log.
pub warnings: Vec<String>,
/// Chats whose messages changed (session, chat): the Stream Studio
/// follows the chat of its channel.
pub chats: Vec<(i64, ChatTarget)>,
/// A stream to watch (its id): the one a lookup was waiting for, or the
/// development switch's.
pub watch: Option<String>,
/// The capture and the decoder.
pub stream: StreamEffects,
/// A server connected or answered: the development switch that shares
/// the test pattern may start now.
pub autoshare: bool,
/// The session on screen got its state or its presence: the development
/// switch that opens the volume dialog of the first client may act.
pub first_client: bool,
/// The event, when its state is not in the [`AppState`]: the Stream
/// Studio's stream (`Host::studio_streams_to`), a setting that changed (the
/// settings service) and the answers to the offline message requests, which
/// the messages page keeps. The watched and shared streams are not among
/// them: they are state here and go through the stream effects. The front
/// end handles these itself ([`crate::events`] lists them), before it draws
/// what `refresh` names, as what it keeps may be on screen.
pub rest: Option<Event>,
}
/// The host and the update of a transition in progress.
pub struct Cx<'a> {
/// What the front end answers.
pub host: &'a dyn Host,
/// What is collected.
pub update: Update,
}
impl<'a> Cx<'a> {
/// A transition that starts with nothing to tell.
pub fn new(host: &'a dyn Host) -> Self {
Self { host, update: Update::default() }
}
/// The status line says this from now on.
pub fn status(&mut self, text: impl Into<String>) {
self.update.status = Some(text.into());
}
/// A command for the engine.
pub fn send(&mut self, command: Command) {
self.update.commands.push(command);
}
/// A command for the engine, but not for the sample sessions of
/// `VOELIN_DEMO_UI`: the engine would open them for real.
pub fn send_real(&mut self, command: Command) {
if !self.host.demo_ui() {
self.send(command);
}
}
/// A request to a session's gateway (not for the sample sessions).
pub fn gateway_to(&mut self, session: i64, request: GatewayRequest) {
self.send_real(Command::Gateway { session: session as u64, request });
}
/// Something went wrong that nothing else shows: it is logged.
pub fn warn(&mut self, text: impl Into<String>) {
self.update.warnings.push(text.into());
}
/// Keep this.
pub fn persist(&mut self, what: Persist) {
self.update.persist.push(what);
}
/// The password dialog of a locked channel opens.
pub fn ask_password(&mut self, channel_name: String, wrong: bool) {
self.update.password = Some(PasswordPrompt { name: channel_name, wrong });
}
/// The chat `target` of session `id` changed.
pub fn chat_changed(&mut self, id: i64, target: &ChatTarget) {
self.update.chats.push((id, target.clone()));
}
}
/// A front end for the tests of the transitions.
#[cfg(test)]
pub(crate) mod testing {
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use voelin_store::{ChatRead, ChatTarget as StoredTarget};
use super::Host;
use std::sync::Arc;
use voelin_core::{
AudioSettings, HistoryMessage, ObserveState, SessionState, Source, VoiceState,
};
use voelin_model::{ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence, ServerDetails};
use voelin_store::{Bookmark, MessageSource};
use crate::bridge::ChatLine;
use crate::settings::{ClientPlaybackMap, UiSettings};
use crate::state::AppState;
/// The front end of the tests: answers what the transitions ask and keeps
/// what they store.
#[derive(Default)]
pub(crate) struct Fake {
pub(crate) demo: bool,
pub(crate) shown: Cell<bool>,
pub(crate) watching: bool,
pub(crate) autowatch: bool,
/// The session the Stream Studio streams to.
pub(crate) studio: Option<i64>,
pub(crate) limit: u64,
/// The private chat on screen: session and peer.
pub(crate) dm: Option<(i64, String)>,
/// What time it is.
pub(crate) now: Cell<i64>,
/// What the store has: server unique id, its chats' reads.
pub(crate) reads: HashMap<String, Vec<(StoredTarget, ChatRead)>>,
/// What was stored.
pub(crate) written: RefCell<Vec<(String, StoredTarget, ChatRead)>>,
}
impl Host for Fake {
fn demo_ui(&self) -> bool {
self.demo
}
fn chat_shown(&self) -> bool {
self.shown.get()
}
fn watching(&self) -> bool {
self.watching
}
fn autowatch(&self) -> bool {
self.autowatch
}
fn studio_streams_to(&self, session: i64) -> bool {
self.studio == Some(session)
}
fn preview_limit(&self) -> u64 {
self.limit
}
fn fetch_images(&self) -> bool {
false
}
fn dm_shown(&self, session: i64, uid: &str) -> bool {
self.dm.as_ref().is_some_and(|(s, u)| *s == session && u == uid)
}
fn now_ms(&self) -> i64 {
self.now.get()
}
fn chat_reads(&self, server_uid: &str) -> Result<Vec<(StoredTarget, ChatRead)>, String> {
Ok(self.reads.get(server_uid).cloned().unwrap_or_default())
}
fn set_chat_read(
&self,
server_uid: &str,
target: &StoredTarget,
read: &ChatRead,
) -> Result<(), String> {
self.written.borrow_mut().push((server_uid.to_owned(), target.clone(), *read));
Ok(())
}
}
pub(crate) type State = AppState<Vec<ChatLine>>;
pub(crate) fn state() -> State {
let bookmark = Bookmark {
id: 1,
name: "ts.example".into(),
address: "ts.example".into(),
nickname: "Me".into(),
..Default::default()
};
AppState::new(
vec![bookmark],
UiSettings::default(),
AudioSettings::default(),
ClientPlaybackMap::new(),
)
}
pub(crate) fn session(voice: VoiceState, own_channel: Option<u64>) -> SessionState {
let connected = voice == VoiceState::Connected;
SessionState {
voice,
observe: ObserveState::Off,
presence_source: connected.then_some(Source::Voice),
own_channel,
own_client: connected.then_some(10),
server_uid: connected.then(|| "srv=".to_owned()),
..Default::default()
}
}
/// Lobby (1) and Games (2), with Me (10, in Games) and Alice (11, in
/// Games).
pub(crate) fn presence() -> Arc<Presence> {
let mut p = Presence { server_name: "Nightfall Guild".into(), ..Default::default() };
for (id, order, name) in [(1, 0, "Lobby"), (2, 1, "Games")] {
p.channels
.insert(id, ChannelInfo { id, order, name: name.into(), ..Default::default() });
}
for (id, name, uid) in [(10, "Me", "me="), (11, "Alice", "alice=")] {
p.clients.insert(
id,
ClientInfo {
id,
channel: 2,
nickname: name.into(),
uid: Some(uid.into()),
..Default::default()
},
);
}
p.server = ServerDetails { welcome_message: "Welcome".into(), ..Default::default() };
Arc::new(p)
}
/// A message of Games, by Alice unless `mine`.
pub(crate) fn said(id: i64, ts_ms: i64, mine: bool, text: &str) -> HistoryMessage {
HistoryMessage {
id,
message: ChatMessage {
target: ChatTarget::Channel(2),
author_name: if mine { "Me" } else { "Alice" }.into(),
author_uid: Some(if mine { "me=" } else { "alice=" }.into()),
author_id: Some(if mine { 10 } else { 11 }),
text: text.into(),
ts_ms,
via_relay: false,
blocked: false,
},
source: MessageSource::Voice,
remote_id: Some(id + 1000),
topic_id: None,
reactions: Vec::new(),
pinned: false,
rev: 0,
}
}
}
+209 -74
View File
@@ -4,6 +4,8 @@
use std::collections::HashMap;
use std::fmt;
use std::hash::{DefaultHasher, Hasher};
use std::io::Cursor;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::SystemTime;
@@ -28,15 +30,8 @@ pub enum ImageSource {
/// What the file was when the reference was made.
stamp: Stamp,
},
/// Decoded pixels, 4 bytes per pixel in the order red, green, blue, alpha.
Rgba {
/// Width in pixels.
w: u32,
/// Height in pixels.
h: u32,
/// `w * h * 4` bytes.
bytes: Arc<[u8]>,
},
/// Decoded pixels; [`ImageSource::rgba`] makes them.
Rgba(Pixels),
/// An SVG document.
Svg(Arc<[u8]>),
/// A picture file held in memory (a chat picture downloaded for its
@@ -55,7 +50,7 @@ impl fmt::Debug for ImageSource {
match self {
Self::None => f.write_str("None"),
Self::File { path, .. } => f.debug_tuple("File").field(path).finish(),
Self::Rgba { w, h, .. } => write!(f, "Rgba({w}x{h})"),
Self::Rgba(pixels) => write!(f, "Rgba({}x{})", pixels.width(), pixels.height()),
Self::Svg(bytes) => write!(f, "Svg({} bytes)", bytes.len()),
Self::Memory { key, bytes } => write!(f, "Memory({key}, {} bytes)", bytes.len()),
}
@@ -88,6 +83,39 @@ pub struct Size {
pub height: u32,
}
/// Decoded pixels, 4 bytes per pixel in the order red, green, blue, alpha.
/// The length always fits the size (`width * height * 4`), so a front end
/// can hand the bytes to its toolkit without checking them.
#[derive(Clone, PartialEq, Eq)]
pub struct Pixels {
w: u32,
h: u32,
bytes: Arc<[u8]>,
}
impl Pixels {
/// The pixels `bytes` hold, if there are `w * h * 4` of them.
pub fn new(w: u32, h: u32, bytes: impl Into<Arc<[u8]>>) -> Option<Self> {
let bytes = bytes.into();
(bytes.len() as u128 == u128::from(w) * u128::from(h) * 4).then_some(Self { w, h, bytes })
}
/// Width in pixels.
pub fn width(&self) -> u32 {
self.w
}
/// Height in pixels.
pub fn height(&self) -> u32 {
self.h
}
/// `width * height * 4` bytes: red, green, blue, alpha of each pixel, row by row.
pub fn bytes(&self) -> &[u8] {
&self.bytes
}
}
impl ImageSource {
/// A reference to no picture.
pub fn none() -> ImageRef {
@@ -104,27 +132,24 @@ impl ImageSource {
/// A reference to decoded pixels (`bytes`: `w * h * 4`, red, green, blue,
/// alpha); no picture if the length does not fit.
pub fn rgba(w: u32, h: u32, bytes: impl Into<Arc<[u8]>>) -> ImageRef {
let bytes = bytes.into();
if bytes.len() as u64 == u64::from(w) * u64::from(h) * 4 {
Arc::new(Self::Rgba { w, h, bytes })
} else {
Self::none()
}
Pixels::new(w, h, bytes).map_or_else(Self::none, |pixels| Arc::new(Self::Rgba(pixels)))
}
/// The size the picture shows with; 0 by 0 when there is none or it can
/// not be shown: a file that is missing, is not a picture, or is too
/// large to decode (a front end drops those, as it would show nothing).
/// A file's size is read from its header, once while it stays as it is;
/// a vector picture has none of its own: its stated width and height,
/// else 1 by 1.
/// not be shown: a file that is missing, does not decode, or is too large
/// to decode (a front end drops those, as it would show nothing). So a
/// picture that has a size shows: a raster picture is decoded to tell
/// (its first frame, as a front end would show it), an SVG document must
/// parse. A file or a downloaded picture is checked once while it stays
/// as it is; a vector picture has no size of its own: its stated width
/// and height, else 1 by 1.
pub fn size(&self) -> Size {
match self {
Self::None => Size::default(),
Self::File { path, stamp } => file_size(path, *stamp),
Self::Rgba { w, h, .. } => Size { width: *w, height: *h },
Self::Rgba(pixels) => Size { width: pixels.width(), height: pixels.height() },
Self::Svg(bytes) => svg_size(bytes),
Self::Memory { bytes, .. } => bytes_size(bytes),
Self::Memory { key, bytes } => memory_size(key, bytes),
}
}
@@ -138,24 +163,38 @@ impl ImageSource {
const MAX_DECODED_BYTES: u64 = 128 << 20;
fn checked(width: u32, height: u32) -> Size {
if width == 0 || height == 0 || u64::from(width) * u64::from(height) * 4 > MAX_DECODED_BYTES {
let bytes = u128::from(width) * u128::from(height) * 4;
if width == 0 || height == 0 || bytes > u128::from(MAX_DECODED_BYTES) {
Size::default()
} else {
Size { width, height }
}
}
/// The size of a picture file's bytes, told by content.
/// What a picture file's bytes show as, told by content: a raster picture is
/// decoded (its first frame; the size comes from the header, the decoding
/// tells whether the rest of the file is a picture too), an SVG document
/// must parse. Anything else, or anything that does not decode, shows
/// nothing.
fn bytes_size(bytes: &[u8]) -> Size {
let bytes = bytes.strip_prefix(b"\xef\xbb\xbf").unwrap_or(bytes);
let Ok(reader) = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format()
else {
let Ok(mut reader) = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format() else {
return Size::default();
};
if reader.format().is_none() {
return if voelin_core::is_svg(bytes) { svg_size(bytes) } else { Size::default() };
}
reader.into_dimensions().map_or_else(|_| Size::default(), |(w, h)| checked(w, h))
// What a front end allows itself: 16 bits a channel take twice the bytes.
let mut limits = image::Limits::default();
limits.max_alloc = Some(2 * MAX_DECODED_BYTES + (64 << 20));
reader.limits(limits);
let Ok(decoder) = reader.into_decoder() else { return Size::default() };
let (width, height) = image::ImageDecoder::dimensions(&decoder);
let size = checked(width, height);
if size == Size::default() || image::DynamicImage::from_decoder(decoder).is_err() {
return Size::default();
}
size
}
/// The number at the start of an attribute's value ("48", "48px", "4.5em").
@@ -164,34 +203,25 @@ fn number(value: &str) -> Option<u32> {
value[..end].parse::<f32>().ok().filter(|v| *v >= 1.0).map(|v| v as u32)
}
/// The value of `name="…"` in the root tag of an SVG.
fn attribute<'a>(tag: &'a str, name: &str) -> Option<&'a str> {
let mut rest = tag;
while let Some(at) = rest.find(name) {
let before = rest[..at].chars().next_back();
let after = &rest[at + name.len()..];
let after = after.trim_start();
if before.is_none_or(char::is_whitespace)
&& let Some(value) = after.strip_prefix('=')
{
let value = value.trim_start();
let quote = value.chars().next().filter(|q| matches!(q, '"' | '\''))?;
return value[1..].split(quote).next();
}
rest = &rest[at + name.len()..];
}
None
}
/// The size of an SVG document: none unless it is XML (as the vector
/// renderers read it, a doctype allowed) whose root is an `svg` element.
fn svg_size(bytes: &[u8]) -> Size {
let text = String::from_utf8_lossy(bytes);
let Some(start) = text.find("<svg") else { return Size { width: 1, height: 1 } };
let tag = &text[start..];
let tag = &tag[..tag.find('>').unwrap_or(tag.len())];
const NAMESPACE: &str = "http://www.w3.org/2000/svg";
let bytes = bytes.strip_prefix(b"\xef\xbb\xbf").unwrap_or(bytes);
let Ok(text) = std::str::from_utf8(bytes) else { return Size::default() };
let options = roxmltree::ParsingOptions { allow_dtd: true, ..Default::default() };
let Ok(document) = roxmltree::Document::parse_with_options(text, options) else {
return Size::default();
};
let root = document.root_element();
let name = root.tag_name();
if name.name() != "svg" || name.namespace().is_some_and(|ns| ns != NAMESPACE) {
return Size::default();
}
let stated =
attribute(tag, "width").and_then(number).zip(attribute(tag, "height").and_then(number));
root.attribute("width").and_then(number).zip(root.attribute("height").and_then(number));
let boxed = || {
let mut parts = attribute(tag, "viewBox")?.split([' ', ',']).filter(|p| !p.is_empty());
let mut parts = root.attribute("viewBox")?.split([' ', ',']).filter(|p| !p.is_empty());
let (_, _, w, h) = (parts.next()?, parts.next()?, parts.next()?, parts.next()?);
number(w).zip(number(h))
};
@@ -199,34 +229,66 @@ fn svg_size(bytes: &[u8]) -> Size {
checked(width, height)
}
/// What a probe of a file found, and what the file was then.
type Probe = (Stamp, Size);
/// What identifies the bytes a probe looked at.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Seen {
/// A file as it was (length and time).
File(Stamp),
/// A picture in memory: its length and a hash of its bytes.
Bytes(usize, u64),
}
/// Probed files, so a picture shown in many rows is read once; entries are
/// checked against the file's length and time before use.
static PROBES: Mutex<Option<HashMap<PathBuf, Probe>>> = Mutex::new(None);
/// Where a probed picture is.
#[derive(Clone, PartialEq, Eq, Hash)]
enum Probed {
File(PathBuf),
Memory(Arc<str>),
}
/// Probed pictures with what they were then, so a picture shown in many
/// rows is decoded once; an entry is checked against the picture's length
/// and time (or bytes) before use.
static PROBES: Mutex<Option<HashMap<Probed, (Seen, Size)>>> = Mutex::new(None);
/// Probes kept at most; the picture cache is far smaller than this.
const MAX_PROBES: usize = 4096;
/// The size of the picture at `at`, from the cache when it is still the
/// same, else from `probe` (run without the lock: it decodes).
fn probed(at: Probed, seen: Seen, probe: impl FnOnce() -> Size) -> Size {
{
let guard = PROBES.lock().unwrap_or_else(|e| e.into_inner());
if let Some((was, size)) = guard.as_ref().and_then(|probes| probes.get(&at))
&& *was == seen
{
return *size;
}
}
let size = probe();
let mut guard = PROBES.lock().unwrap_or_else(|e| e.into_inner());
let probes = guard.get_or_insert_with(HashMap::new);
if probes.len() >= MAX_PROBES {
probes.clear();
}
probes.insert(at, (seen, size));
size
}
fn file_size(path: &Path, stamp: Stamp) -> Size {
if stamp == Stamp::default() {
return Size::default();
}
let mut guard = PROBES.lock().unwrap_or_else(|e| e.into_inner());
let probes = guard.get_or_insert_with(HashMap::new);
if let Some((was, size)) = probes.get(path)
&& *was == stamp
{
return *size;
}
// The file is read with the lock held; probes are short and rare.
let size = std::fs::read(path).map_or_else(|_| Size::default(), |bytes| bytes_size(&bytes));
if probes.len() >= MAX_PROBES {
probes.clear();
}
probes.insert(path.to_owned(), (stamp, size));
size
probed(Probed::File(path.to_owned()), Seen::File(stamp), || {
std::fs::read(path).map_or_else(|_| Size::default(), |bytes| bytes_size(&bytes))
})
}
fn memory_size(key: &Arc<str>, bytes: &[u8]) -> Size {
let mut hasher = DefaultHasher::new();
hasher.write(bytes);
probed(Probed::Memory(key.clone()), Seen::Bytes(bytes.len(), hasher.finish()), || {
bytes_size(bytes)
})
}
#[cfg(test)]
@@ -239,7 +301,15 @@ mod tests {
let mut encoder = ::png::Encoder::new(&mut bytes, width, height);
encoder.set_color(::png::ColorType::Rgba);
encoder.set_depth(::png::BitDepth::Eight);
let pixels = vec![200; width as usize * height as usize * 4];
// Pixels that do not compress to nothing, so cutting the file short
// cuts into the picture.
let mut seed = 0x2545_f491_u32;
let pixels: Vec<u8> = (0..width as usize * height as usize * 4)
.map(|_| {
seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
(seed >> 24) as u8
})
.collect();
encoder.write_header().unwrap().write_image_data(&pixels).unwrap();
bytes
}
@@ -257,8 +327,13 @@ mod tests {
let pixels = ImageSource::rgba(2, 3, vec![0u8; 24]);
assert_eq!(pixels.size(), Size { width: 2, height: 3 });
assert!(!pixels.is_empty());
// The wrong length is no picture.
// The wrong length is no picture, and no pixels either.
assert!(ImageSource::rgba(2, 3, vec![0u8; 23]).is_empty());
assert!(ImageSource::rgba(2, 3, vec![0u8; 25]).is_empty());
assert!(Pixels::new(2, 3, vec![0u8; 23]).is_none());
assert!(Pixels::new(u32::MAX, u32::MAX, vec![0u8; 4]).is_none());
let ImageSource::Rgba(inner) = &*pixels else { panic!("pixels") };
assert_eq!((inner.width(), inner.height(), inner.bytes().len()), (2, 3, 24));
assert_eq!(format!("{pixels:?}"), "Rgba(2x3)");
}
@@ -284,6 +359,48 @@ mod tests {
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn a_file_that_does_not_decode_shows_nothing() {
let dir = temp("corrupt");
let whole = png(32, 32);
// The header is fine, the picture is cut short (a download that
// stopped, a cache file written halfway).
let cut = dir.join("cut");
std::fs::write(&cut, &whole[..whole.len() * 2 / 3]).unwrap();
assert!(ImageSource::file(&cut).is_empty());
// The header is fine, the data is not: flipped bytes in the image
// data, from the middle of the file to its end.
let mut flipped = whole.clone();
let from = flipped.len() / 2;
for byte in &mut flipped[from..] {
*byte = !*byte;
}
let garbled = dir.join("garbled");
std::fs::write(&garbled, &flipped).unwrap();
assert!(ImageSource::file(&garbled).is_empty());
// The whole file shows, and the answer is kept while it stays so.
let good = dir.join("good");
std::fs::write(&good, &whole).unwrap();
assert_eq!(ImageSource::file(&good).size(), Size { width: 32, height: 32 });
// A file that is made whole shows (another stamp: another answer).
std::fs::write(&cut, &whole).unwrap();
assert_eq!(ImageSource::file(&cut).size(), Size { width: 32, height: 32 });
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn a_downloaded_picture_is_checked_too() {
let whole = png(16, 16);
let memory =
|key: &str, bytes: &[u8]| ImageSource::Memory { key: key.into(), bytes: bytes.into() };
assert_eq!(memory("whole", &whole).size(), Size { width: 16, height: 16 });
assert!(memory("cut", &whole[..whole.len() / 2]).is_empty());
// The same key with other bytes is another picture.
assert!(memory("same", &whole[..whole.len() / 2]).is_empty());
assert_eq!(memory("same", &whole).size(), Size { width: 16, height: 16 });
assert!(memory("none", b"").is_empty());
}
#[test]
fn vector_pictures() {
let size = |svg: &str| ImageSource::Svg(svg.as_bytes().into()).size();
@@ -296,6 +413,24 @@ mod tests {
ImageSource::Svg(b"<svg width=\"99999\" height=\"99999\"/>".as_slice().into())
.is_empty()
);
// Not an SVG document: cut off, a sibling of the root, other roots,
// not text.
assert!(size("<svg width=\"8\" height=\"8\"").width == 0);
assert!(size("<svg width=\"8\" height=\"8\"><g>").width == 0);
assert!(size("<svg width=\"8\" height=\"8\"/><svg/>").width == 0);
assert!(size("<html width=\"8\" height=\"8\"/>").width == 0);
assert!(size("<svg xmlns='urn:other' width='8' height='8'/>").width == 0);
assert_eq!(
size("<svg xmlns='http://www.w3.org/2000/svg' width='8' height='9'/>").height,
9
);
assert!(
ImageSource::Svg(b"<svg width='8' height='8'>\xff</svg>".as_slice().into()).is_empty()
);
// A doctype, as editors write it.
let doctype = "<?xml version=\"1.0\"?><!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \
\"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\"><svg width=\"5\" height=\"6\"/>";
assert_eq!(size(doctype), Size { width: 5, height: 6 });
// An SVG file with a byte order mark and a prolog, and in memory.
let svg: &[u8] = b"\xef\xbb\xbf<?xml version=\"1.0\"?><svg width=\"8\" height=\"8\"/>";
let dir = temp("svg");
+10 -1
View File
@@ -3,17 +3,26 @@
//! Neither Slint nor GPUI is a dependency; each front end converts these
//! types (docs/ui.md, "Two crates").
// Every public item is documented, the 559 fields of the two mirror modules
// (`bridge`, `studio_bridge`) included.
#![warn(missing_docs)]
pub mod avatar;
pub mod bbcode;
pub mod bridge;
pub mod chat;
pub mod color;
pub mod dev;
pub mod emoji;
pub mod events;
pub mod home;
pub mod host;
pub mod image;
pub mod list;
pub mod previews;
pub mod servers;
pub mod settings;
pub mod settings_page;
pub mod settings_pages;
pub mod social;
pub mod state;
@@ -23,4 +32,4 @@ pub mod studio_bridge;
pub mod tree;
pub use color::Rgb;
pub use image::{ImageRef, ImageSource, Size};
pub use image::{ImageRef, ImageSource, Pixels, Size};
+172
View File
@@ -0,0 +1,172 @@
//! Pictures linked in chat, shown inline: a link to a PNG, JPEG, GIF or
//! WebP file (by name) up to `ui.image_preview_kb` is downloaded into
//! memory once (`Command::DownloadChatFile` with `DownloadTo::Memory`,
//! voice connections only) and the chat shows it as a picture card, and a
//! click opens it larger. A picture on the web a message shows (`[img]`)
//! comes the way banners do, into the engine's cache (`Command::FetchPicture`,
//! up to the same size, only with `cache.fetch_images`), and until it is
//! there the message shows its address.
use std::sync::Arc;
use voelin_core::{Command, DownloadTo, TransferState, VoiceState};
use voelin_model::{ChatTarget, FileRef};
use crate::host::Cx;
use crate::image::{ImageRef, ImageSource};
use crate::state::{AppState, Preview, SessionView};
/// Whether a file name is a picture the chat shows inline.
pub fn is_previewable(name: &str) -> bool {
let lower = name.to_ascii_lowercase();
[".png", ".jpg", ".jpeg", ".gif", ".webp"].iter().any(|e| lower.ends_with(e))
}
/// The key of a link: where the file is.
pub fn link_key(file: &FileRef) -> String {
format!(
"{}/{}{}{}",
file.server_uid.as_deref().unwrap_or(""),
file.channel,
file.path,
file.name
)
}
/// The picture of a link, if it is there and shows.
pub fn image_of<L>(view: &SessionView<L>, file: &FileRef) -> Option<ImageRef> {
let key = link_key(file);
match view.extra.previews.get(&key)? {
Preview::Ready(bytes) => {
let image = Arc::new(ImageSource::Memory { key: key.into(), bytes: bytes.0.clone() });
(!image.is_empty()).then_some(image)
}
_ => None,
}
}
/// Download the pictures linked in the current chat of `session` that are
/// not there yet.
pub fn fetch_previews<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, session: i64) {
if cx.host.demo_ui() {
return;
}
let limit = cx.host.preview_limit();
if limit == 0 {
return;
}
fetch_web_pictures(state, cx, session, limit);
let Some(view) = state.sessions.get_mut(&session) else { return };
if view.state.voice != VoiceState::Connected || !view.capabilities.file_transfer {
return;
}
let Some(tab) = view.tabs.get(view.current_tab) else { return };
// Channel chats only: a link names its channel's file browser.
if matches!(tab.target, ChatTarget::Private(_)) && tab.messages.is_empty() {
return;
}
let wanted: Vec<FileRef> = tab
.messages
.iter()
.rev()
.take(200)
.flat_map(|m| m.message.message.file_refs())
.filter(|f| is_previewable(&f.name) && f.size.is_some_and(|s| s <= limit))
.filter(|f| !view.extra.previews.contains_key(&link_key(f)))
.collect();
for file in wanted {
let transfer = view.next_transfer;
view.next_transfer += 1;
view.extra.previews.insert(link_key(&file), Preview::Loading(transfer));
cx.send(Command::DownloadChatFile {
session: session as u64,
transfer,
file,
password: None,
to: DownloadTo::Memory,
});
}
}
/// Ask the engine for the pictures on the web (`[img]`) of the current chat
/// of `session` that it has not reported; it fetches each once.
fn fetch_web_pictures<L>(state: &AppState<L>, cx: &mut Cx<'_>, session: i64, limit: u64) {
if !cx.host.fetch_images() {
return;
}
let Some(view) = state.sessions.get(&session) else { return };
let Some(tab) = view.tabs.get(view.current_tab) else { return };
// The server chat starts with the server's messages.
let server = match tab.target {
ChatTarget::Server => crate::chat::server_texts(&view.presence.server),
_ => Vec::new(),
};
let wanted: Vec<String> = tab
.messages
.iter()
.rev()
.take(200)
.map(|m| m.message.message.text.as_str())
.chain(server.into_iter().map(|(text, _)| text))
.flat_map(crate::chat::web_pictures)
.filter(|url| !view.pictures.contains_key(url))
.collect();
for url in wanted {
cx.send(Command::FetchPicture { session: session as u64, url, max_bytes: limit });
}
}
/// A transfer of a picture: `true` if it was one.
pub fn preview_progress<L>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
session: i64,
transfer: u64,
progress: &TransferState,
) -> bool {
let limit = cx.host.preview_limit();
let current = state.current == Some(session);
let Some(view) = state.sessions.get_mut(&session) else { return false };
let Some(key) = view
.extra
.previews
.iter()
.find(|(_, p)| matches!(p, Preview::Loading(t) if *t == transfer))
.map(|(k, _)| k.clone())
else {
return false;
};
match progress {
TransferState::Started { size, .. } if *size > limit => {
view.extra.previews.insert(key, Preview::Failed);
cx.send_real(Command::CancelTransfer { session: session as u64, transfer });
}
TransferState::Done { data: Some(data), .. } => {
view.extra.previews.insert(key, Preview::Ready(data.clone()));
if current {
cx.update.refresh.chat = true;
}
}
TransferState::Done { .. } | TransferState::Failed(_) | TransferState::Cancelled => {
view.extra.previews.insert(key, Preview::Failed);
}
_ => {}
}
true
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn previewable_names() {
assert!(is_previewable("Banner.PNG"));
assert!(is_previewable("a.webp"));
assert!(!is_previewable("notes.svg"));
assert!(!is_previewable("route.pdf"));
let file =
FileRef { channel: 2, path: "/".into(), name: "a.png".into(), ..Default::default() };
assert_eq!(link_key(&file), "/2/a.png");
}
}
+956
View File
@@ -0,0 +1,956 @@
//! Servers: what the rail, the server card and the channel tree show, which
//! server is shown and how it is observed, the gateway found for it, and
//! joining a channel. The functions change the [`AppState`] and say in the
//! [`Cx`]'s update what to draw and send; the store, the secrets, the identity
//! and the sockets are the front end's.
use voelin_core::ts::identity::LaunchImport;
use voelin_core::{Command, ObserveState, Source, VoiceOptions, VoiceState};
use voelin_model::{ChannelId, ChatTarget};
use voelin_store::{Bookmark, QueryConfig};
use super::{JoinStep, item, join_password, tints};
use crate::bridge::{BookmarkForm, MemberItem, ServerItem, TreeItem};
use crate::chat::logic::{open_chat, prefetch_counts, save_reads, track_reading};
use crate::host::{Cx, Persist};
use crate::image::ImageRef;
use crate::state::{AppState, Lines, SessionView};
/// The name of the identity the app creates when it has none.
pub const CREATED_IDENTITY: &str = "Default";
/// What to tell the user about the identities imported from the official
/// clients at start ([`voelin_core::ts::identity::import_new`]), if anything.
pub fn imported_status(report: &LaunchImport) -> Option<String> {
let n = report.added.len();
let names = report.added.iter().map(|f| f.nickname.as_str()).collect::<Vec<_>>().join(", ");
let more = if n > 1 { format!(" ({n} imported: {names})") } else { String::new() };
Some(match &report.default {
Some(f) if report.replaced => format!(
"You now use your TeamSpeak identity \u{201c}{}\u{201d}; your previous one is kept{more}",
f.nickname
),
Some(f) => format!("Using your TeamSpeak identity \u{201c}{}\u{201d}{more}", f.nickname),
None if n == 1 => format!("Imported the identity \u{201c}{names}\u{201d} from TeamSpeak"),
None if n > 1 => format!("Imported {n} identities from TeamSpeak: {names}"),
None => return None,
})
}
/// The bookmark the form describes, over `old` (what the form does not show,
/// like the identity, the default channel or the client version, stays; a
/// new server has none of it). Only the address is needed: the name is the
/// address until the server tells its own, the nickname `default_nickname`,
/// the gateway is looked up in DNS. A new address drops the gateway and the
/// query login found or set for the old one.
pub fn bookmark_from_form(
old: Option<&Bookmark>,
form: &BookmarkForm,
default_nickname: impl FnOnce() -> String,
) -> Bookmark {
let mut bookmark = old.cloned().unwrap_or_default();
bookmark.id = form.id as i64;
bookmark.address = form.address.trim().to_string();
if old.is_some_and(|old| old.address != bookmark.address) {
bookmark.cached_server_icon = None;
bookmark.gateway_url = None;
bookmark.gateway_urls.clear();
bookmark.query = None;
}
bookmark.name = match form.name.trim() {
"" => bookmark.address.clone(),
name => name.to_string(),
};
bookmark.nickname = match form.nickname.trim() {
"" => default_nickname(),
nickname => nickname.to_string(),
};
bookmark
}
/// Whether observing goes on as it is when discovery changed the gateways
/// kept from `previous` to `found`: the same ones (an older version kept
/// only the one in use), or logged in through `in_use`, still published.
/// What was found is kept for the next start, without a new login now.
pub fn observing_stays(
previous: &[String],
found: &[String],
in_use: Option<&str>,
observe: ObserveState,
) -> bool {
found == previous
|| (observe == ObserveState::Observing
&& in_use.is_some_and(|url| found.iter().any(|u| u == url)))
}
/// The options of a voice connection to `bookmark`, into `channel` (a path,
/// or `/<id>`, with its password) if given, with a privilege key if given;
/// the reason when the bookmark's client version is not one. The identity,
/// the server's password and the stream peer are the front end's to add.
pub fn voice_options(
bookmark: &Bookmark,
channel: Option<String>,
channel_password: Option<String>,
token: Option<String>,
) -> Result<VoiceOptions, String> {
let mut options = VoiceOptions::new(&bookmark.address, &bookmark.nickname);
if let Some(spec) = &bookmark.client_version {
// The engine resolves the spec when it connects; asking now tells the
// user at once.
if let Err(error) = voelin_core::ts::versions::resolve(spec) {
return Err(format!("Invalid client compatibility version: {error}"));
}
options.client_version = Some(spec.clone());
}
options.channel = channel;
options.channel_password = channel_password;
options.token = token;
options.audio = true;
Ok(options)
}
// Which server is shown, and how it is observed.
/// Show a server (the front end then observes it).
pub fn select_server<L: Lines>(state: &mut AppState<L>, cx: &mut Cx<'_>, id: i64) {
state.current = Some(id);
prefetch_counts(state, cx);
track_reading(state, cx);
let r = &mut cx.update.refresh;
(r.servers, r.toolbar, r.tree, r.chat, r.streams) = (true, true, true, true, true);
}
/// A server was removed from the list (the store has the rest now): its
/// session goes, and the first server is shown.
pub fn forget_server<L: Lines>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
id: i64,
bookmarks: Vec<Bookmark>,
) {
save_reads(state, cx, id);
state.sessions.remove(&id);
state.gateways_looked_up.remove(&id);
state.bookmarks = bookmarks;
state.current = state.bookmarks.first().map(|b| b.id);
prefetch_counts(state, cx);
track_reading(state, cx);
let r = &mut cx.update.refresh;
(r.servers, r.toolbar, r.tree, r.chat, r.streams) = (true, true, true, true, true);
}
/// What observing a server invisibly comes to ([`observe_plan`]).
#[derive(Clone, Debug, PartialEq)]
pub enum ObservePlan {
/// Nothing to do: it is observed already, or there is no server.
Nothing,
/// The gateway is still being connected to: the engine tries it again
/// now.
Retry(Vec<String>),
/// Observe through these gateways (best first), and look the gateway up
/// again; the status line says so.
Gateway(Vec<String>),
/// Observe through the server's own query login; the status line says so.
Query(QueryConfig),
/// There is neither: the gateway is looked up, and observing starts
/// when it is found.
Discover,
}
/// How to observe server `id` invisibly, unless it is already: through its
/// gateway, else its own query login. Without either the gateway is looked
/// up first, and observing starts when it is found. Asked while still
/// connecting, the engine tries the gateway again sooner.
pub fn observe_plan<L>(state: &AppState<L>, cx: &Cx<'_>, id: i64) -> ObservePlan {
let Some(b) = state.bookmarks.iter().find(|b| b.id == id) else { return ObservePlan::Nothing };
if cx.host.demo_ui() {
return ObservePlan::Nothing;
}
let observing = state.sessions.get(&id).map(|v| v.state.observe).unwrap_or_default();
let urls = b.gateways();
match observing {
ObserveState::Observing => return ObservePlan::Nothing,
// The engine decides: the same gateways are not started over, at most
// tried again now.
ObserveState::Connecting => {
return if urls.is_empty() { ObservePlan::Nothing } else { ObservePlan::Retry(urls) };
}
ObserveState::Off => {}
}
if !urls.is_empty() {
ObservePlan::Gateway(urls)
} else if let Some(q) = &b.query {
ObservePlan::Query(q.clone())
} else {
ObservePlan::Discover
}
}
/// The address of server `id` to look the gateway up for, once a run (not
/// for the sample sessions).
pub fn discover_wanted<L>(state: &mut AppState<L>, cx: &Cx<'_>, id: i64) -> Option<String> {
if cx.host.demo_ui() || !state.gateways_looked_up.insert(id) {
return None;
}
state.bookmarks.iter().find(|b| b.id == id).map(|b| b.address.clone())
}
/// What finding the gateways of a server comes to.
#[derive(Clone, Debug, PartialEq)]
pub enum GatewayFound {
/// Nothing changed, or the server is another one now.
Same,
/// Kept, and observing goes on as it is; `observe` when the server on
/// screen is not observed yet.
Kept {
/// Observe the server now.
observe: bool,
},
/// Kept, and the old ones are left: observing was through them. The
/// server on screen is observed through the new ones.
Changed {
/// The gateways observed through before (the engine stops them).
stop: bool,
/// Observe the server now.
observe: bool,
/// Every URL the server publishes, best first, for the log.
urls: Vec<String>,
},
}
/// Gateways were found for the server at `address` (best first); they are
/// kept unless the server changed meanwhile. Users never hear of them
/// (logged only).
pub fn gateway_found<L>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
id: i64,
address: &str,
urls: Vec<String>,
) -> GatewayFound {
let Some(b) = state.bookmarks.iter_mut().find(|b| b.id == id && b.address == address) else {
return GatewayFound::Same;
};
let previous = b.gateways();
let in_use = b.gateway_url.clone();
if !b.set_gateways(urls) {
return GatewayFound::Same;
}
cx.persist(Persist::Bookmark { id, what: "gateway found" });
let found = b.gateways();
let observe = state.sessions.get(&id).map(|v| v.state.observe).unwrap_or_default();
let kept = observing_stays(&previous, &found, in_use.as_deref(), observe);
cx.update.refresh.toolbar = true;
let current = state.current == Some(id);
if kept {
return GatewayFound::Kept { observe: current && observe == ObserveState::Off };
}
// Observed through the old ones: through these now.
let stop = !previous.is_empty();
if stop && let Some(view) = state.sessions.get_mut(&id) {
view.state.observe = ObserveState::Off;
}
GatewayFound::Changed { stop, observe: current, urls: found }
}
// Joining a channel.
/// Join a channel of a session (a double-click in the tree, joining a
/// friend): move there with voice, or the password to connect into it with
/// when there is no voice on that server. A locked channel asks for its
/// password first, unless it was given this connection.
pub fn join_channel<L: Lines>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
session: i64,
channel: ChannelId,
) -> Option<Option<String>> {
let view = state.sessions.get(&session)?;
let info = view.presence.channels.get(&channel)?;
let remembered = view.channel_passwords.get(&channel).map(String::as_str);
match join_password(info, remembered) {
JoinStep::Send(password) => enter_channel(state, cx, session, channel, password),
JoinStep::Ask => {
crate::events::ask_password(state, cx, session, channel, false);
None
}
}
}
/// The password dialog's Join: the same, with that password.
pub fn join_with_password<L: Lines>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
password: String,
) -> Option<(i64, ChannelId, Option<String>)> {
let (session, channel) = state.join_target.take()?;
if password.is_empty() {
return None;
}
if let Some(view) = state.sessions.get_mut(&session) {
view.channel_passwords.insert(channel, password.clone());
}
enter_channel(state, cx, session, channel, Some(password)).map(|p| (session, channel, p))
}
/// Move into a channel; without voice on its server the front end connects
/// into it, with the password returned.
pub fn enter_channel<L>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
session: i64,
channel: ChannelId,
password: Option<String>,
) -> Option<Option<String>> {
let view = state.sessions.get_mut(&session)?;
if view.state.voice != VoiceState::Disconnected {
// Chosen while connecting: no longer the one to join after.
view.join_after_connect = None;
cx.send_real(Command::MoveToChannel { session: session as u64, channel, password });
return None;
}
Some(password)
}
/// Voice is being connected into `channel` of session `session`: once
/// connected, it is joined again if the server put us elsewhere.
pub fn join_after_connect<L>(state: &mut AppState<L>, session: i64, channel: ChannelId) {
if let Some(view) = state.sessions.get_mut(&session) {
view.join_after_connect = Some(channel);
}
}
/// Fold or unfold a channel of the current session.
pub fn toggle_collapse<L: Lines>(state: &mut AppState<L>, cx: &mut Cx<'_>, channel: ChannelId) {
if let Some(id) = state.current {
let view = state.sessions.entry(id).or_default();
if !view.collapsed.remove(&channel) {
view.collapsed.insert(channel);
}
}
cx.update.refresh.tree = true;
}
/// The members panel's search.
pub fn search_members<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, text: String) {
if state.member_filter != text {
state.member_filter = text;
cx.update.refresh.tree = true;
}
}
/// The voice channel view was opened or closed: its chat is our channel's,
/// and its people lead the members panel.
pub fn show_voice_view<L: Lines>(state: &mut AppState<L>, cx: &mut Cx<'_>, on: bool) {
state.voice_view = on;
let channel =
state.current.and_then(|id| state.sessions.get(&id)).and_then(|v| v.state.own_channel);
if on && let Some(channel) = channel {
open_chat(state, cx, ChatTarget::Channel(channel), true);
}
cx.update.refresh.tree = true;
}
/// A link to the voice channel we are in, for the Invite button (which
/// copies it, and the copy's toast names the channel); the reason without
/// one.
pub fn invite_link<L>(state: &mut AppState<L>) -> Result<String, &'static str> {
let address = state
.current
.and_then(|id| state.bookmarks.iter().find(|b| b.id == id))
.map(|b| b.address.clone());
let path = state.current.and_then(|id| state.sessions.get(&id)).and_then(|v| {
let cid = v.state.own_channel?;
let own = v.presence.channels.get(&cid)?;
// The link names the channels as the server has them; the toast as
// the tree shows them.
Some((
crate::tree::channel_path(&v.presence, cid),
crate::tree::channel_title(own).0.to_owned(),
))
});
let (Some(address), Some((path, title))) = (address, path) else {
return Err("Join a voice channel to invite others to it");
};
let path: Vec<&str> = path.iter().map(String::as_str).collect();
let link = super::invite_link(&address, &path);
state.copy_note = Some(format!("Copied an invite to {title}: {link}"));
Ok(link)
}
// What is shown.
/// The rail: servers with their state, unread count (without private chats)
/// and streams. `icon` gives a server's icon (what its session fetched, else
/// what was cached).
pub fn rail<L>(state: &AppState<L>, icon: impl Fn(&Bookmark) -> ImageRef) -> Vec<ServerItem> {
state
.bookmarks
.iter()
.zip(tints(&state.bookmarks))
.map(|(b, tint)| {
let view = state.sessions.get(&b.id);
let session = view.map(|v| v.state.clone()).unwrap_or_default();
let unread = view.map_or(0, SessionView::channel_unread);
let live = view.is_some_and(|v| v.streams_available() && !v.streams.is_empty());
let detail = view
.filter(|v| !v.presence.channels.is_empty())
.map(|v| crate::tree::stats(&v.presence))
.unwrap_or_default();
let product = view.map(|v| v.extra.product.clone()).unwrap_or_default();
item(b, &session, unread, live, detail, product, icon(b), tint)
})
.collect()
}
/// A server's colour, as the rail shows it; none for a server that is not
/// in the list (a chat that outlived its bookmark).
pub fn server_tint<L>(state: &AppState<L>, id: i64) -> Option<crate::color::Rgb> {
let position = state.bookmarks.iter().position(|b| b.id == id)?;
Some(tints(&state.bookmarks)[position])
}
/// The colour of a chat's avatar in a list: the server's own colour, as the
/// rail shows it, for the chat of a server (`kind` 0 of a
/// [`ConversationItem`](crate::bridge::ConversationItem)) that is still in
/// the list; for every other chat, and for a server chat that outlived its
/// bookmark, the colour of the `title`, never black.
pub fn conversation_tint<L>(
state: &AppState<L>,
kind: i32,
session: Option<i64>,
title: &str,
) -> crate::color::Rgb {
match (kind, session) {
(0, Some(session)) => server_tint(state, session),
_ => None,
}
.unwrap_or_else(|| crate::avatar::tint(title))
}
/// The server card, the voice controls and who we are.
pub struct ToolbarView {
/// The server's icon.
pub server_icon: ImageRef,
/// Its name.
pub server_title: String,
/// "9 online · 7 channels", once its presence is known.
pub server_stats: String,
/// Our nickname there.
pub nickname: String,
/// Our avatar.
pub own_avatar: ImageRef,
/// The server's banner.
pub server_banner: ImageRef,
/// How it is drawn.
pub server_banner_mode: i32,
/// The channel we are in.
pub own_channel: String,
/// Its topic.
pub own_channel_topic: String,
/// Its banner.
pub own_channel_banner: ImageRef,
/// How it is drawn.
pub own_channel_banner_mode: i32,
/// Its client limit, -1 without one.
pub own_channel_limit: i32,
/// Voice is connected.
pub voice_connected: bool,
/// Voice is connecting.
pub voice_connecting: bool,
/// The server is observed.
pub observing: bool,
/// Our microphone is muted.
pub input_muted: bool,
/// Our sound is muted.
pub output_muted: bool,
/// Voice is transmitted.
pub transmitting: bool,
/// Where the presence comes from, for people to read.
pub presence_source: &'static str,
}
/// The server card for the current server; `icon` is its icon.
pub fn toolbar<L>(state: &AppState<L>, icon: impl Fn(&Bookmark) -> ImageRef) -> ToolbarView {
let bookmark = state.current.and_then(|id| state.bookmarks.iter().find(|b| b.id == id));
let view = state.current.and_then(|id| state.sessions.get(&id));
let session = view.map(|v| v.state.clone()).unwrap_or_default();
let has_presence = view.is_some_and(|v| !v.presence.channels.is_empty())
&& (session.voice == VoiceState::Connected || session.observe == ObserveState::Observing);
let own = view.zip(session.own_client).and_then(|(v, c)| v.avatar(c));
let banner =
|url: Option<&str>| view.map(|v| crate::tree::banner(&v.pictures, url)).unwrap_or_default();
let details = view.map(|v| &v.presence.server);
let own_channel =
view.and_then(|v| session.own_channel.and_then(|c| v.presence.channels.get(&c)));
ToolbarView {
server_icon: bookmark.map(&icon).unwrap_or_default(),
server_title: bookmark.map_or("No server selected".into(), |b| b.name.clone()),
server_stats: view
.filter(|_| has_presence)
.map(|v| crate::tree::stats(&v.presence))
.unwrap_or_default(),
nickname: bookmark.map(|b| b.nickname.clone()).unwrap_or_default(),
own_avatar: crate::avatar::image(own),
server_banner: banner(details.map(|d| d.banner_gfx_url.as_str())),
server_banner_mode: details.map_or(0, |d| crate::tree::banner_mode(d.banner_mode)),
own_channel: own_channel
.map(|c| crate::tree::channel_title(c).0.to_owned())
.unwrap_or_default(),
own_channel_topic: own_channel.and_then(|c| c.topic.clone()).unwrap_or_default(),
own_channel_banner: banner(own_channel.and_then(|c| c.banner_gfx_url.as_deref())),
own_channel_banner_mode: own_channel.map_or(0, |c| crate::tree::banner_mode(c.banner_mode)),
own_channel_limit: own_channel
.and_then(|c| c.max_clients)
.filter(|m| *m >= 0)
.unwrap_or(-1),
voice_connected: session.voice == VoiceState::Connected,
voice_connecting: session.voice == VoiceState::Connecting,
observing: session.observe != ObserveState::Off,
input_muted: session.input_muted,
output_muted: session.output_muted,
transmitting: session.transmitting,
presence_source: match session.presence_source {
Some(Source::Voice) => "live (voice)",
Some(Source::Gateway) => "invisible (gateway)",
Some(Source::Query) => "invisible (query)",
None => "",
},
}
}
/// The channel tree and the members.
pub struct TreeView {
/// The channels and clients, as the tree lists them.
pub rows: Vec<TreeItem>,
/// The members of our channel (while voice is connected).
pub members: Vec<MemberItem>,
/// Everyone on the server, filtered by the panel's search.
pub server_members: Vec<MemberItem>,
/// How many are on the server (without query clients).
pub member_total: i32,
}
/// The channel tree, the members of our channel and everyone on the server;
/// none when no server is shown. `popped_out`: the stream plays in a window
/// of its own.
pub fn tree_view<L>(state: &AppState<L>, popped_out: bool) -> Option<TreeView> {
let view = state.current.and_then(|id| state.sessions.get(&id))?;
let input = crate::tree::TreeInput {
presence: &view.presence,
collapsed: &view.collapsed,
talking: &view.talking,
playback: &state.playback,
own_channel: view.state.own_channel,
own_client: view.state.own_client,
filter: "",
avatars: &view.avatars,
icons: &view.icons,
pictures: &view.pictures,
groups: &view.server_groups,
channel_groups: &view.channel_groups,
};
let rows = crate::tree::rows(&input);
let connected = view.state.voice == VoiceState::Connected;
let members = if connected { crate::tree::members(&input) } else { Vec::new() };
// The people in our channel first while their view is shown (not while
// the stream plays in a window of its own).
let watching = state.watch.as_ref().is_some_and(|w| w.shown) && !popped_out;
let voice_first = connected && (state.voice_view || watching);
let everyone = crate::tree::server_members(&input, voice_first);
let filter = state.member_filter.trim().to_lowercase();
let server_members =
if filter.is_empty() { everyone } else { crate::tree::matching(everyone, &filter) };
Some(TreeView {
rows,
members,
server_members,
member_total: view.presence.clients.values().filter(|c| !c.is_query).count() as i32,
})
}
#[cfg(test)]
mod tests {
use voelin_core::SessionState;
use voelin_model::ChannelInfo;
use super::*;
use crate::host::testing::{Fake, State, presence, session, state};
fn bookmark(id: i64, name: &str, address: &str) -> Bookmark {
Bookmark { id, name: name.into(), address: address.into(), ..Default::default() }
}
#[test]
fn edited_server_rejects_queued_icons_and_failed_reconnect_keeps_them_hidden() {
use crate::events::apply_server_icon;
let path = std::env::temp_dir()
.join(format!("voelin-server-icon-edited-{}.svg", std::process::id()));
std::fs::write(&path, r#"<svg xmlns="http://www.w3.org/2000/svg" width="4" height="4"><rect width="4" height="4" fill="red"/></svg>"#).unwrap();
let mut bookmark = Bookmark { address: "a.test".into(), ..Default::default() };
let mut view = SessionView::<()>::default();
view.icons.insert(1234, path.clone());
assert!(apply_server_icon(&mut bookmark, &mut view, "a.test", 1234));
assert_eq!(view.server_icon_for(&bookmark.address).size().width, 4);
bookmark = bookmark_from_form(
Some(&bookmark),
&BookmarkForm { address: "b.test".into(), ..Default::default() },
|| "Me".into(),
);
// Connecting does not retag received imagery. A failed B connection
// must not make A's image appear under B's name.
for state in [VoiceState::Connecting, VoiceState::Disconnected] {
view.state.voice = state;
assert_eq!(view.server_icon_for(&bookmark.address).size().width, 0);
}
assert!(!apply_server_icon(&mut bookmark, &mut view, "a.test", 4321));
assert_eq!(view.server_icon, 1234);
assert_eq!(view.icon_address.as_deref(), Some("a.test"));
assert!(bookmark.server_icon_id().is_none());
// Equal icon IDs on the next server still need new provenance.
assert!(apply_server_icon(&mut bookmark, &mut view, "b.test", 1234));
assert_eq!(bookmark.server_icon_id(), Some(1234));
assert_eq!(view.server_icon_for(&bookmark.address).size().width, 4);
assert!(!apply_server_icon(&mut bookmark, &mut view, "a.test", 0));
assert_eq!(bookmark.server_icon_id(), Some(1234));
assert!(apply_server_icon(&mut bookmark, &mut view, "b.test", 0));
assert!(bookmark.server_icon_id().is_none());
assert_eq!(view.server_icon_for(&bookmark.address).size().width, 0);
std::fs::remove_file(path).unwrap();
}
#[test]
fn the_address_alone_makes_a_server() {
let form =
BookmarkForm { id: -1, address: " ts.example.test ".into(), ..Default::default() };
let b = bookmark_from_form(None, &form, || "Nick".into());
assert_eq!((b.address.as_str(), b.name.as_str()), ("ts.example.test", "ts.example.test"));
assert_eq!(b.nickname, "Nick");
assert_eq!(
(b.gateway_url, b.query, b.identity, b.default_channel),
(None, None, None, None)
);
}
#[test]
fn editing_keeps_what_the_form_does_not_show() {
let old = Bookmark {
id: 7,
name: "Old".into(),
address: "old.example.test".into(),
nickname: "Me".into(),
identity: Some(2),
default_channel: Some("Lobby/Sub".into()),
gateway_url: Some("ws://gw.example.test:7788/v1".into()),
gateway_urls: vec!["ws://gw.example.test:7788/v1".into()],
query: Some(QueryConfig { server_port: Some(9988), ..Default::default() }),
client_version: Some("linux".into()),
cached_server_icon: Some(voelin_store::CachedServerIcon {
address: "old.example.test".into(),
id: 1234,
}),
};
// Same address: the gateway found and the query login stay.
let same = BookmarkForm {
id: 7,
name: "Mine".into(),
address: "old.example.test".into(),
nickname: "Other".into(),
..Default::default()
};
let b = bookmark_from_form(Some(&old), &same, || unreachable!("a nickname was given"));
assert_eq!((b.id, b.name.as_str(), b.nickname.as_str()), (7, "Mine", "Other"));
assert_eq!(b.gateway_url, old.gateway_url);
assert_eq!(b.query, old.query);
assert_eq!(b.cached_server_icon, old.cached_server_icon);
// Another address: looked up again, for the new server.
let form = BookmarkForm { address: "new.example.test:9988".into(), ..same };
let b = bookmark_from_form(Some(&old), &form, || unreachable!("a nickname was given"));
assert_eq!(b.address, "new.example.test:9988");
assert!(b.cached_server_icon.is_none());
assert_eq!((b.identity, b.default_channel), (Some(2), Some("Lobby/Sub".into())));
assert_eq!(b.client_version.as_deref(), Some("linux"));
assert_eq!((b.gateway_url, b.query), (None, None));
assert!(b.gateway_urls.is_empty());
}
#[test]
fn a_gateway_found_again_is_not_logged_in_again() {
let (tls, plain) = ("wss://gw.example.test/v1", "ws://ts.example.test:7788/v1");
let urls = |list: &[&str]| list.iter().map(|u| u.to_string()).collect::<Vec<_>>();
let stays = |previous: &[&str], found: &[&str], observe| {
observing_stays(&urls(previous), &urls(found), Some(plain), observe)
};
// The same ones (an older version kept only the one in use).
assert!(stays(&[plain], &[plain], ObserveState::Connecting));
assert!(stays(&[plain], &[plain], ObserveState::Observing));
// Logged in through one still published.
assert!(stays(&[plain], &[tls, plain], ObserveState::Observing));
// Not logged in yet: through the new ones.
assert!(!stays(&[plain], &[tls, plain], ObserveState::Connecting));
// The one in use is no longer published.
assert!(!stays(&[plain], &[tls], ObserveState::Observing));
assert!(!observing_stays(&[], &urls(&[tls]), None, ObserveState::Off));
}
/// How a server is observed: through its gateway, its query login, or
/// after the gateway was looked up; not twice, not for sample servers.
#[test]
fn a_server_is_observed_through_what_it_has() {
let mut st = state();
let host = Fake::default();
let cx = Cx::new(&host);
assert_eq!(observe_plan(&st, &cx, 9), ObservePlan::Nothing, "no such server");
assert_eq!(observe_plan(&st, &cx, 1), ObservePlan::Discover);
st.bookmarks[0].query = Some(QueryConfig::default());
assert!(matches!(observe_plan(&st, &cx, 1), ObservePlan::Query(_)));
st.bookmarks[0].gateway_urls = vec!["wss://gw/v1".into()];
assert_eq!(observe_plan(&st, &cx, 1), ObservePlan::Gateway(vec!["wss://gw/v1".into()]));
let view = st.sessions.entry(1).or_default();
view.state.observe = ObserveState::Connecting;
assert_eq!(observe_plan(&st, &cx, 1), ObservePlan::Retry(vec!["wss://gw/v1".into()]));
st.sessions.get_mut(&1).unwrap().state.observe = ObserveState::Observing;
assert_eq!(observe_plan(&st, &cx, 1), ObservePlan::Nothing);
let demo = Fake { demo: true, ..Default::default() };
assert_eq!(observe_plan(&st, &Cx::new(&demo), 1), ObservePlan::Nothing);
// The gateway is looked up once a run.
assert_eq!(discover_wanted(&mut st, &cx, 1).as_deref(), Some("ts.example"));
assert_eq!(discover_wanted(&mut st, &cx, 1), None);
}
/// What finding the gateways does to a server.
#[test]
fn found_gateways_are_kept_and_observed_through() {
let mut st = state();
let host = Fake::default();
let found = |st: &mut State, urls: &[&str], address: &str| {
let mut cx = Cx::new(&host);
let result = gateway_found(
st,
&mut cx,
1,
address,
urls.iter().map(|s| s.to_string()).collect(),
);
(result, cx.update.persist.len(), cx.update.refresh.toolbar)
};
// Another address now: nothing.
assert_eq!(found(&mut st, &["wss://gw/v1"], "other.example").0, GatewayFound::Same);
// First found, the server is shown and not observed: observe.
let (result, kept, toolbar) = found(&mut st, &["wss://gw/v1"], "ts.example");
assert_eq!(
result,
GatewayFound::Changed { stop: false, observe: true, urls: vec!["wss://gw/v1".into()] }
);
assert!(kept == 1 && toolbar);
// The same again: nothing changed.
assert_eq!(found(&mut st, &["wss://gw/v1"], "ts.example").0, GatewayFound::Same);
// Observing through the old: a different gateway list leaves them.
st.sessions.entry(1).or_default().state.observe = ObserveState::Observing;
let (result, ..) = found(&mut st, &["wss://new/v1"], "ts.example");
assert_eq!(
result,
GatewayFound::Changed { stop: true, observe: true, urls: vec!["wss://new/v1".into()] }
);
assert_eq!(st.sessions[&1].state.observe, ObserveState::Off);
// One that still lists the one in use keeps observing.
st.bookmarks[0].gateway_url = Some("wss://new/v1".into());
st.sessions.get_mut(&1).unwrap().state.observe = ObserveState::Observing;
let (result, ..) = found(&mut st, &["wss://new/v1", "wss://more/v1"], "ts.example");
assert_eq!(result, GatewayFound::Kept { observe: false });
}
/// Joining a channel: a free one at once (or connecting into it), a locked
/// one asks, the password dialog's Join goes on.
#[test]
fn joining_a_channel_moves_asks_or_connects() {
let mut st = state();
let host = Fake::default();
let mut locked = ChannelInfo { id: 3, name: "Vault".into(), ..Default::default() };
locked.has_password = true;
let mut p = (*presence()).clone();
p.channels.insert(3, locked);
st.sessions.entry(1).or_default().presence = std::sync::Arc::new(p);
// Connected: moving.
st.sessions.get_mut(&1).unwrap().state = session(VoiceState::Connected, Some(2));
let mut cx = Cx::new(&host);
assert_eq!(join_channel(&mut st, &mut cx, 1, 1), None);
assert!(matches!(
cx.update.commands.as_slice(),
[Command::MoveToChannel { session: 1, channel: 1, password: None }]
));
// A locked one asks.
let mut cx = Cx::new(&host);
assert_eq!(join_channel(&mut st, &mut cx, 1, 3), None);
assert_eq!(cx.update.password.as_ref().map(|p| p.name.as_str()), Some("Vault"));
assert_eq!(st.join_target, Some((1, 3)));
let mut cx = Cx::new(&host);
assert_eq!(join_with_password(&mut st, &mut cx, "".into()), None);
st.join_target = Some((1, 3));
assert_eq!(join_with_password(&mut st, &mut cx, "pw".into()), None);
assert_eq!(st.sessions[&1].channel_passwords.get(&3).map(String::as_str), Some("pw"));
assert!(matches!(
cx.update.commands.as_slice(),
[Command::MoveToChannel { channel: 3, password: Some(p), .. }] if p == "pw"
));
// Not connected: the front end connects into it.
st.sessions.get_mut(&1).unwrap().state = SessionState::default();
let mut cx = Cx::new(&host);
assert_eq!(join_channel(&mut st, &mut cx, 1, 1), Some(None));
join_after_connect(&mut st, 1, 1);
assert_eq!(st.sessions[&1].join_after_connect, Some(1));
assert!(cx.update.commands.is_empty());
}
/// The server card, the rail and the tree for the server shown.
#[test]
fn the_rail_the_card_and_the_tree() {
let mut st = state();
let no_icon = |_: &Bookmark| ImageRef::default();
// Nothing connected yet.
let rail_rows = rail(&st, no_icon);
assert_eq!(rail_rows.len(), 1);
assert_eq!((&*rail_rows[0].status, &*rail_rows[0].detail), ("offline", "ts.example"));
let card = toolbar(&st, no_icon);
assert_eq!((card.server_title.as_str(), card.nickname.as_str()), ("ts.example", "Me"));
assert!(!card.voice_connected && card.presence_source.is_empty());
assert!(tree_view(&st, false).is_none(), "no session yet");
// Connected into Games.
let host = Fake::default();
for event in [
voelin_core::Event::Presence { session: 1, presence: presence() },
voelin_core::Event::State {
session: 1,
state: session(VoiceState::Connected, Some(2)),
},
] {
crate::events::apply(&mut st, &host, event);
}
let rail_rows = rail(&st, no_icon);
assert_eq!(
(&*rail_rows[0].status, &*rail_rows[0].detail),
("connected", "2 online · 2 channels")
);
assert_eq!(server_tint(&st, 1), Some(tints(&st.bookmarks)[0]));
assert_eq!(server_tint(&st, 9), None);
let card = toolbar(&st, no_icon);
assert!(card.voice_connected && card.own_channel == "Games");
assert_eq!(card.presence_source, "live (voice)");
assert_eq!(card.own_channel_limit, -1);
let tree = tree_view(&st, false).unwrap();
assert_eq!(tree.rows.len(), 4, "two channels and their clients");
assert_eq!(tree.members.len(), 2);
assert_eq!(tree.member_total, 2);
// The members' search filters the server's people only.
let mut cx = Cx::new(&host);
search_members(&mut st, &mut cx, "ali".into());
assert!(cx.update.refresh.tree);
let tree = tree_view(&st, false).unwrap();
assert_eq!(
tree.server_members
.iter()
.filter(|m| !m.group.is_empty() && &*m.name == "Alice")
.count(),
1
);
assert!(tree.server_members.iter().all(|m| &*m.name != "Me"));
// Folding a channel; the tree is drawn again.
let mut cx = Cx::new(&host);
toggle_collapse(&mut st, &mut cx, 1);
assert!(st.sessions[&1].collapsed.contains(&1) && cx.update.refresh.tree);
toggle_collapse(&mut st, &mut cx, 1);
assert!(st.sessions[&1].collapsed.is_empty());
}
/// A chat takes its server's colour only while it is a server chat of a
/// server in the list: a chat whose server is gone, and a chat that is a
/// channel's or a person's, take the colour of their own title. Black
/// is what a missing colour would be (`Rgb::default()`).
#[test]
fn a_chat_takes_its_servers_colour_or_that_of_its_title() {
let st = state();
let server = tints(&st.bookmarks)[0];
let titled = |title: &str| crate::avatar::tint(title);
// Titles whose own colour is not the server's, so that the chat
// below can tell the two apart.
assert_ne!(titled("Old Server"), server);
assert_ne!(titled("Alice"), server);
assert_ne!(titled("Alice"), crate::color::Rgb::default());
// The server's chat, the server in the list: its colour, not the
// title's.
assert_eq!(conversation_tint(&st, 0, Some(1), "Old Server"), server);
// The server is gone from the list: the title's colour.
assert_eq!(conversation_tint(&st, 0, Some(9), "Old Server"), titled("Old Server"));
// Not a server chat of a known server: the title's colour, whether
// the server is in the list or not, or not known at all.
assert_eq!(conversation_tint(&st, 1, Some(1), "Alice"), titled("Alice"));
assert_eq!(conversation_tint(&st, 2, Some(1), "Alice"), titled("Alice"));
assert_eq!(conversation_tint(&st, 2, Some(9), "Alice"), titled("Alice"));
assert_eq!(conversation_tint(&st, 0, None, "Alice"), titled("Alice"));
}
/// The Invite button's link and note; the voice view's chat.
#[test]
fn invite_and_voice_view() {
let mut st = state();
let host = Fake::default();
assert_eq!(invite_link(&mut st), Err("Join a voice channel to invite others to it"));
for event in [
voelin_core::Event::Presence { session: 1, presence: presence() },
voelin_core::Event::State {
session: 1,
state: session(VoiceState::Connected, Some(2)),
},
] {
crate::events::apply(&mut st, &host, event);
}
let link = invite_link(&mut st).unwrap();
assert!(link.contains("ts.example") && link.contains("Games"), "{link}");
assert_eq!(st.copy_note.as_deref(), Some(&*format!("Copied an invite to Games: {link}")));
let mut cx = Cx::new(&host);
show_voice_view(&mut st, &mut cx, true);
assert!(st.voice_view && cx.update.refresh.tree && cx.update.refresh.chat);
}
/// A server leaves the list; the first one that is left is shown.
#[test]
fn forgetting_a_server_shows_the_first_left() {
let mut st = state();
st.bookmarks.push(bookmark(2, "Other", "other.example"));
let host = Fake::default();
st.sessions.entry(1).or_default();
st.gateways_looked_up.insert(1);
let mut cx = Cx::new(&host);
forget_server(&mut st, &mut cx, 1, vec![bookmark(2, "Other", "other.example")]);
assert_eq!(st.current, Some(2));
assert!(st.sessions.is_empty() && st.gateways_looked_up.is_empty());
let r = cx.update.refresh;
assert!(r.servers && r.toolbar && r.tree && r.chat && r.streams);
let mut cx = Cx::new(&host);
select_server(&mut st, &mut cx, 2);
assert_eq!(st.current, Some(2));
}
#[test]
fn the_voice_options_follow_the_bookmark() {
let mut b = bookmark(1, "G", "ts.example");
b.nickname = "Me".into();
let options =
voice_options(&b, Some("/5".into()), Some("pw".into()), Some("key".into())).unwrap();
assert_eq!(options.channel.as_deref(), Some("/5"));
assert_eq!(options.channel_password.as_deref(), Some("pw"));
assert_eq!(options.token.as_deref(), Some("key"));
assert!(options.audio);
// A bookmark without a version spec leaves the engine's default.
assert_eq!(options.client_version, None);
// A spec that resolves goes on as the spec: the engine resolves it
// when it connects.
b.client_version = Some("default".into());
let options = voice_options(&b, None, None, None).unwrap();
assert_eq!(options.client_version.as_deref(), Some("default"));
b.client_version = Some("no such version".into());
let error = voice_options(&b, None, None, None).err().unwrap();
assert!(error.starts_with("Invalid client compatibility version"), "{error}");
}
}
@@ -1,4 +1,8 @@
//! The server rail, the server dialog, and joining a channel.
//! The server rail, the server dialog, and joining a channel; [`logic`] has
//! which server is shown, how it is observed, and the rail, the server card
//! and the channel tree as plain data.
pub mod logic;
use std::sync::Arc;
@@ -126,6 +130,7 @@ pub fn form(
pub struct ConnectTo {
/// A channel path, or `/<id>`.
pub channel: Option<String>,
/// The channel's password, if the form has one.
pub channel_password: Option<String>,
/// A privilege key.
pub token: Option<String>,
+15
View File
@@ -31,8 +31,10 @@ pub static CLIENT_PLAYBACK: Key<ClientPlaybackMap> = Key::new(
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ThemeChoice {
/// The dark palette.
#[default]
Dark,
/// The light palette.
Light,
/// The system's light or dark scheme.
System,
@@ -128,8 +130,11 @@ pub fn appearance_keys() -> [&'static dyn voelin_core::settings::Setting; 6] {
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum NotifyLevel {
/// Nothing.
Off,
/// The bell in the app.
App,
/// The bell and a desktop notification.
#[default]
Desktop,
}
@@ -294,6 +299,7 @@ pub struct UiSettings {
pub openh264: bool,
/// The ScreenCast portal's token for the last shared screen.
pub portal_restore_token: Option<String>,
/// The last choices in the share dialog.
pub share: ShareDefaults,
/// Write crash reports to disk (opt-in; never uploaded).
pub crash_reports: bool,
@@ -321,8 +327,11 @@ impl Default for UiSettings {
/// path, its names from the top as the server has them.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct LastVoice {
/// The id of the server's bookmark.
pub bookmark: i64,
/// The address the bookmark had then.
pub address: String,
/// The channel's names from the top.
pub channel: Vec<String>,
}
@@ -333,9 +342,13 @@ pub struct LastVoice {
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct ShareDefaults {
/// The frame rate's position in the old list ([`LEGACY_FPS_CHOICES`]).
pub fps_index: usize,
/// The bitrate's position in the old list ([`LEGACY_BITRATE_CHOICES`]).
pub bitrate_index: usize,
/// Share the sound too.
pub audio: bool,
/// Accept the viewers that ask to watch without asking us.
pub auto_accept: bool,
}
@@ -350,6 +363,7 @@ impl Default for ShareDefaults {
pub struct ClientPlayback {
/// Linear, 1 = unchanged.
pub volume: f32,
/// Not played at all.
pub muted: bool,
}
@@ -372,6 +386,7 @@ pub type ClientPlaybackMap = BTreeMap<String, ClientPlayback>;
/// Audio devices as listed in the settings: the system default first.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct DeviceChoices {
/// What the list shows, by index.
pub names: Vec<String>,
/// Device ids by index; `None` for the system default.
pub ids: Vec<Option<String>>,
@@ -0,0 +1,412 @@
//! The audio settings page and the local volume of clients: the device
//! lists and the form, what a change of the form sends to the engine, the
//! microphone test, the push-to-talk and H.264 switches, the crash notice
//! and the volume dialog. The functions change the
//! [`AppState`] and say in the [`Cx`]'s update what
//! to send and keep; the devices, the hotkey, the store and the window are
//! the front end's.
use voelin_core::Command;
use crate::bridge::{AudioForm, ClientAudio};
use crate::host::{Cx, Persist};
use crate::settings::{ClientPlayback, DeviceChoices, apply_audio_form, audio_form};
use crate::state::AppState;
/// What the settings page shows when it opens ([`open_settings`]).
#[derive(Clone, Debug, PartialEq)]
pub struct SettingsView {
/// The input devices' names, the system default first.
pub input_devices: Vec<String>,
/// The output devices' names, the system default first.
pub output_devices: Vec<String>,
/// The form of the audio settings.
pub audio: AudioForm,
/// The push-to-talk key works in every window.
pub global_ptt: bool,
/// The push-to-talk key.
pub ptt_key: String,
/// H.264 through the downloaded OpenH264 is on.
pub h264_enabled: bool,
}
/// An audio device the system lists: its id, its name and whether it is the
/// system's default of its direction.
pub type Device = (String, String, bool);
/// The settings page opens: the devices the system lists become the choices
/// (a device that is stored but not there stays in the list), and the form
/// and the switches are those of the state.
pub fn open_settings<L>(
state: &mut AppState<L>,
inputs: &[Device],
outputs: &[Device],
) -> SettingsView {
state.inputs = DeviceChoices::new(inputs, state.audio.input_device.as_deref());
state.outputs = DeviceChoices::new(outputs, state.audio.output_device.as_deref());
SettingsView {
input_devices: state.inputs.names.clone(),
output_devices: state.outputs.names.clone(),
audio: audio_form(&state.audio, &state.inputs, &state.outputs),
global_ptt: state.settings.global_ptt,
ptt_key: state.settings.ptt_key.clone(),
h264_enabled: state.settings.openh264,
}
}
/// The form changed: the engine gets the new audio settings, and they are
/// kept later ([`save_audio`]), if the form changed anything.
pub fn audio_changed<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, form: &AudioForm) {
let audio = apply_audio_form(form, &state.audio, &state.inputs, &state.outputs);
if audio == state.audio {
return;
}
state.audio = audio;
state.audio_dirty = true;
cx.send(Command::SetAudioSettings(Box::new(state.audio.clone())));
}
/// Keep the audio settings, if they changed since they were kept.
pub fn save_audio<L>(state: &mut AppState<L>, cx: &mut Cx<'_>) {
if state.audio_dirty {
state.audio_dirty = false;
cx.persist(Persist::Audio);
}
}
/// The settings page closes: the microphone test stops and the audio
/// settings are kept. Whether the test was on.
pub fn close_settings<L>(state: &mut AppState<L>, cx: &mut Cx<'_>) -> bool {
let was_on = set_mic_test(state, cx, false);
save_audio(state, cx);
was_on
}
/// Start or stop the microphone test: whether that changed anything.
pub fn set_mic_test<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, on: bool) -> bool {
if state.mic_test == on {
return false;
}
state.mic_test = on;
cx.send(Command::TestMicrophone { on });
true
}
/// The push-to-talk switch and key: kept, and the key to register as a
/// hotkey of the whole desktop, none to unregister it. A blank key leaves
/// the one that was set.
pub fn apply_ptt<L>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
enabled: bool,
key: &str,
) -> Option<String> {
let key = key.trim().to_owned();
state.settings.global_ptt = enabled;
if !key.is_empty() {
state.settings.ptt_key = key.clone();
}
cx.persist(Persist::Settings);
(enabled && !key.is_empty()).then_some(key)
}
/// The H.264 switch: kept; the front end tells the encoder.
pub fn set_h264<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, enabled: bool) {
state.settings.openh264 = enabled;
cx.persist(Persist::Settings);
}
/// What the H.264 rows show ([`h264_view`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct H264View {
/// The library is loaded.
pub loaded: bool,
/// It is being downloaded.
pub busy: bool,
/// What the front end's codec says.
pub status: String,
}
/// The H.264 rows for the codec's state: `loaded`, and its `status` text
/// ("Downloading …" while it is being fetched).
pub fn h264_view(loaded: bool, status: String) -> H264View {
H264View { loaded, busy: status.starts_with("Downloading"), status }
}
/// The crash reports switch: kept (the front end also tells the crash
/// handler and the settings service).
pub fn set_crash_reports<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, enabled: bool) {
state.settings.crash_reports = enabled;
// Also in the blob, for older versions.
cx.persist(Persist::Settings);
}
/// The notice while crash reports are on disk: `summaries` are the first
/// lines of their panic messages, oldest first. Empty without reports.
pub fn crash_notice(summaries: &[String]) -> String {
let Some(newest) = summaries.last() else { return String::new() };
let saved = match summaries.len() {
1 => "1 crash report is saved".to_owned(),
n => format!("{n} crash reports are saved"),
};
format!("The app crashed earlier ({newest}). {saved} on this device.")
}
// Local volume and mute of clients.
/// Fill the volume dialog for `client` of the current session; none when
/// there is no such client.
pub fn open_client<L>(state: &mut AppState<L>, client: u16) -> Option<ClientAudio> {
let id = state.current?;
let info = state.sessions.get(&id)?.presence.clients.get(&client)?.clone();
let playback =
info.uid.as_ref().and_then(|uid| state.playback.get(uid)).copied().unwrap_or_default();
state.playback_dialog = Some((id, client, info.uid.clone()));
Some(ClientAudio {
id: i32::from(client),
name: info.nickname.into(),
volume: playback.volume * 100.0,
muted: playback.muted,
streaming: info.streaming == Some(true),
})
}
/// The volume dialog changed: the engine plays the client so, and the
/// choice is kept by the client's unique id (a client without one only for
/// this connection), the default as no choice. The tree shows who is muted.
pub fn client_playback_changed<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, form: &ClientAudio) {
let Some((session, client, uid)) = state.playback_dialog.clone() else { return };
let playback =
ClientPlayback { volume: (form.volume / 100.0).clamp(0.0, 4.0), muted: form.muted };
let session = session as u64;
cx.send(Command::SetClientVolume { session, client, volume: playback.volume });
cx.send(Command::SetClientMuted { session, client, muted: playback.muted });
if let Some(uid) = uid {
if playback.is_default() {
state.playback.remove(&uid);
} else {
state.playback.insert(uid, playback);
}
cx.persist(Persist::Playback);
}
cx.update.refresh.tree = true;
}
/// The first client of the current session that is not us nor a query
/// client (`VOELIN_OPEN=client`): its id, when we are in the session.
pub fn first_client<L>(state: &AppState<L>) -> Option<u16> {
let view = state.current.and_then(|id| state.sessions.get(&id))?;
let own = view.state.own_client?;
view.presence.clients.values().filter(|c| c.id != own && !c.is_query).map(|c| c.id).min()
}
#[cfg(test)]
mod tests {
use voelin_core::VoiceState;
use super::*;
use crate::host::testing::{Fake, State, presence, session, state};
fn device(id: &str, name: &str, default: bool) -> Device {
(id.into(), name.into(), default)
}
#[test]
fn the_page_opens_with_the_devices_and_a_stored_one_stays() {
let mut st = state();
st.audio.input_device = Some("gone".into());
st.settings.global_ptt = true;
st.settings.ptt_key = "F9".into();
let inputs = [device("a", "Built-in", true), device("b", "Headset", false)];
let outputs = [device("a", "Built-in", false), device("b", "Headset", true)];
let view = open_settings(&mut st, &inputs, &outputs);
// The system default first, named after the one that is the default.
assert_eq!(
view.input_devices,
["System default (Built-in)", "Built-in", "Headset", "gone (not connected)"]
);
// Outputs have the other as the default, and no stored device.
assert_eq!(view.output_devices, ["System default (Headset)", "Built-in", "Headset"]);
assert_eq!(view.audio.input_index, 3, "the stored device is selected");
assert_eq!(view.audio.output_index, 0, "no stored output: the default");
assert!(view.global_ptt && view.ptt_key == "F9" && !view.h264_enabled);
assert_eq!(st.inputs.names, view.input_devices);
}
#[test]
fn a_change_of_the_form_goes_to_the_engine_once_and_is_kept_later() {
let mut st = state();
let host = Fake::default();
open_settings(&mut st, &[], &[]);
let mut form = audio_form(&st.audio, &st.inputs, &st.outputs);
// Nothing changed: nothing sent.
let mut cx = Cx::new(&host);
audio_changed(&mut st, &mut cx, &form);
assert!(cx.update.commands.is_empty() && !st.audio_dirty);
form.output_volume = 50.0;
audio_changed(&mut st, &mut cx, &form);
assert!(matches!(
cx.update.commands.as_slice(),
[Command::SetAudioSettings(audio)] if audio.output_volume == 0.5
));
assert!(st.audio_dirty);
// The same form again changes nothing.
audio_changed(&mut st, &mut cx, &form);
assert_eq!(cx.update.commands.len(), 1);
// Kept once, when the page closes or the clock ticks.
save_audio(&mut st, &mut cx);
save_audio(&mut st, &mut cx);
assert_eq!(cx.update.persist, [Persist::Audio]);
assert!(!st.audio_dirty);
}
#[test]
fn the_microphone_test_stops_with_the_page() {
let mut st = state();
let host = Fake::default();
let mut cx = Cx::new(&host);
assert!(!close_settings(&mut st, &mut cx), "it was not on");
assert!(cx.update.commands.is_empty());
assert!(set_mic_test(&mut st, &mut cx, true));
assert!(!set_mic_test(&mut st, &mut cx, true), "already on");
st.audio_dirty = true;
assert!(close_settings(&mut st, &mut cx), "it was on");
assert!(!st.mic_test);
assert!(matches!(
cx.update.commands.as_slice(),
[Command::TestMicrophone { on: true }, Command::TestMicrophone { on: false }]
));
assert_eq!(cx.update.persist, [Persist::Audio]);
}
#[test]
fn the_push_to_talk_key_is_registered_when_it_is_on_and_set() {
let mut st = state();
let host = Fake::default();
let mut cx = Cx::new(&host);
assert_eq!(apply_ptt(&mut st, &mut cx, true, " F9 ").as_deref(), Some("F9"));
assert!(st.settings.global_ptt);
assert_eq!(st.settings.ptt_key, "F9");
// Off: unregistered, the key stays for later.
assert_eq!(apply_ptt(&mut st, &mut cx, false, "F10"), None);
assert_eq!(st.settings.ptt_key, "F10");
// A blank key leaves the one that was set, and registers nothing.
assert_eq!(apply_ptt(&mut st, &mut cx, true, " "), None);
assert_eq!(st.settings.ptt_key, "F10");
assert_eq!(cx.update.persist, [Persist::Settings, Persist::Settings, Persist::Settings]);
}
#[test]
fn the_switches_are_kept() {
let mut st = state();
let host = Fake::default();
let mut cx = Cx::new(&host);
set_h264(&mut st, &mut cx, true);
set_crash_reports(&mut st, &mut cx, true);
assert!(st.settings.openh264 && st.settings.crash_reports);
assert_eq!(cx.update.persist, [Persist::Settings, Persist::Settings]);
assert_eq!(
h264_view(false, "Downloading OpenH264… 40%".into()),
H264View { loaded: false, busy: true, status: "Downloading OpenH264… 40%".into() }
);
assert!(!h264_view(true, "Loaded".into()).busy);
}
#[test]
fn the_crash_notice_counts_the_reports() {
assert_eq!(crash_notice(&[]), "");
assert_eq!(
crash_notice(&["index out of bounds".into()]),
"The app crashed earlier (index out of bounds). 1 crash report is saved on this device."
);
assert_eq!(
crash_notice(&["old".into(), "new".into()]),
"The app crashed earlier (new). 2 crash reports are saved on this device."
);
}
/// Connected, with Alice (11) in Games next to us (10), a query client
/// (12) and Zed (9, a lower id).
fn with_clients() -> State {
let mut st = state();
let mut p = (*presence()).clone();
p.clients.get_mut(&11).unwrap().streaming = Some(true);
for (id, name, query) in [(12, "serveradmin", true), (9, "Zed", false)] {
p.clients.insert(
id,
voelin_model::ClientInfo {
id,
channel: 2,
nickname: name.into(),
is_query: query,
..Default::default()
},
);
}
let view = st.sessions.entry(1).or_default();
view.presence = std::sync::Arc::new(p);
view.state = session(VoiceState::Connected, Some(2));
st
}
#[test]
fn the_volume_dialog_fills_from_what_was_kept() {
let mut st = with_clients();
assert_eq!(open_client(&mut st, 99), None, "no such client");
let form = open_client(&mut st, 11).unwrap();
assert_eq!((form.id, &*form.name, form.volume, form.muted), (11, "Alice", 100.0, false));
assert!(form.streaming);
assert_eq!(st.playback_dialog, Some((1, 11, Some("alice=".into()))));
st.playback.insert("alice=".into(), ClientPlayback { volume: 0.5, muted: true });
let form = open_client(&mut st, 11).unwrap();
assert_eq!((form.volume, form.muted), (50.0, true));
st.current = None;
assert_eq!(open_client(&mut st, 11), None, "no server shown");
}
#[test]
fn a_client_is_played_as_the_dialog_says_and_the_default_is_forgotten() {
let mut st = with_clients();
let host = Fake::default();
let mut cx = Cx::new(&host);
// No dialog open: nothing.
client_playback_changed(&mut st, &mut cx, &ClientAudio::default());
assert!(cx.update.commands.is_empty());
let mut form = open_client(&mut st, 11).unwrap();
form.volume = 900.0;
form.muted = true;
client_playback_changed(&mut st, &mut cx, &form);
// Clamped to four times, sent, kept by unique id, the tree shows it.
assert!(matches!(
cx.update.commands.as_slice(),
[
Command::SetClientVolume { session: 1, client: 11, volume: 4.0 },
Command::SetClientMuted { session: 1, client: 11, muted: true },
]
));
assert_eq!(st.playback["alice="], ClientPlayback { volume: 4.0, muted: true });
assert_eq!(cx.update.persist, [Persist::Playback]);
assert!(cx.update.refresh.tree);
// Back to the default: no entry.
form.volume = 100.0;
form.muted = false;
client_playback_changed(&mut st, &mut cx, &form);
assert!(st.playback.is_empty());
// A client without a unique id is played so only for now.
st.playback_dialog = Some((1, 9, None));
let before = cx.update.persist.len();
client_playback_changed(&mut st, &mut cx, &form);
assert!(st.playback.is_empty());
assert_eq!(cx.update.persist.len(), before);
}
#[test]
fn the_first_client_is_the_lowest_id_that_is_not_us() {
let mut st = with_clients();
assert_eq!(first_client(&st), Some(9), "not us (10), not the query client");
st.sessions.get_mut(&1).unwrap().state.own_client = None;
assert_eq!(first_client(&st), None, "not in the session");
st.current = None;
assert_eq!(first_client(&st), None);
}
}
@@ -0,0 +1,6 @@
//! The settings page of the audio devices and the voice controls, the push
//! to talk key, the H.264 switch, the crash reports and the volume of a
//! client. [`logic`] has what the page shows and what its controls change;
//! the engine, the store, the hotkey and the window are the front end's.
pub mod logic;
@@ -118,7 +118,7 @@ pub fn layer_of(item: &LayerItem, base: &LayerSetting) -> Option<LayerSetting> {
}
/// The layers of quality preset `quality` (0: none, the source's size;
/// then [`PRESETS`]) at `kbps` (0: automatic, for the preset's size and
/// then `PRESETS`) at `kbps` (0: automatic, for the preset's size and
/// `fps`); `None` for no preset (layers of one's own).
pub fn preset_layers(quality: i32, kbps: u32, fps: u32) -> Option<Vec<LayerSetting>> {
match usize::try_from(quality).ok()? {
File diff suppressed because it is too large. Load diff
@@ -3,9 +3,232 @@
//! `vm::bbcode`), mentions, event dates, a poke's message, the private
//! chats of the home sidebar; pure, so they are tested here.
pub mod logic;
use std::collections::HashSet;
use chrono::{DateTime, Local, NaiveDateTime, TimeZone};
use voelin_core::HistoryMessage;
use voelin_model::ChatTarget;
use voelin_core::{HistoryMessage, VoiceState};
use voelin_model::{ChatMessage, ChatTarget};
use crate::state::AppState;
/// Now, in milliseconds since the epoch.
pub fn now_ms() -> i64 {
chrono::Utc::now().timestamp_millis()
}
/// What a notification of the bell is about.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NoticeKind {
/// Someone mentioned us.
Mention,
/// Someone poked us.
Poke,
/// A private message.
Message,
/// A scheduled event starts soon.
Event,
/// A friend came online.
Friend,
}
impl NoticeKind {
/// The name the bell's rows carry.
pub fn name(self) -> &'static str {
match self {
Self::Mention => "mention",
Self::Poke => "poke",
Self::Message => "message",
Self::Event => "event",
Self::Friend => "friend",
}
}
}
/// Where a notification leads.
#[derive(Clone, Debug, PartialEq)]
pub enum NoticeTarget {
/// A chat of a session.
Chat(i64, ChatTarget),
/// A private chat with someone, in a session.
Dm(i64, String),
/// An event of a session's gateway (session, event id).
Event(i64, i64),
/// A contact, by unique id.
Contact(String),
}
/// A notification a transition asks for; the front end adds it to the bell
/// as the setting of its kind says.
#[derive(Clone, Debug, PartialEq)]
pub struct NoticeRequest {
/// What it is about.
pub kind: NoticeKind,
/// The headline.
pub title: String,
/// The line under it.
pub body: String,
/// Where it leads.
pub target: NoticeTarget,
/// Whose avatar it shows (initials from the name).
pub name: String,
/// Whose avatar picture it shows.
pub uid: Option<String>,
}
/// Whether a message is ours: by one of our unique ids, or by our client in
/// its session (`own_client`).
pub fn own_message(
own_uids: &HashSet<String>,
own_client: Option<u16>,
message: &ChatMessage,
) -> bool {
message.author_uid.as_ref().is_some_and(|u| own_uids.contains(u))
|| (own_client.is_some() && message.author_id == own_client)
}
/// A poke we got.
#[derive(Clone, Debug, PartialEq)]
pub struct Poke {
/// The session it came in.
pub session: i64,
/// Who poked, by unique id, when known.
pub uid: Option<String>,
/// Who poked, by name.
pub name: String,
/// What they wrote with it.
pub message: String,
/// When, in milliseconds since the epoch.
pub ts_ms: i64,
}
/// The avatar picture of someone by unique id, from any session.
pub fn avatar_of<L>(state: &AppState<L>, uid: &str) -> crate::image::ImageRef {
crate::avatar::image(state.sessions.values().find_map(|v| v.avatars.get(uid)))
}
/// Pokes from `uid` as lines of their private chat, among its messages
/// (with the time of each, oldest first).
pub fn poke_lines<L>(
state: &AppState<L>,
pokes: &[Poke],
session: i64,
uid: &str,
) -> Vec<(i64, crate::bridge::ChatLine)> {
pokes
.iter()
.enumerate()
.filter(|(_, p)| p.session == session && p.uid.as_deref() == Some(uid))
.map(|(i, p)| {
let text = if p.message.is_empty() {
"👋 poked you".to_owned()
} else {
format!("👋 poked you: {}", p.message)
};
let message = ChatMessage {
target: ChatTarget::Private(uid.to_owned()),
author_name: p.name.clone(),
author_uid: p.uid.clone(),
author_id: None,
text,
ts_ms: p.ts_ms,
via_relay: false,
blocked: false,
};
let mut line = crate::chat::line(&message, None);
line.key = -1_000_000 - i as i32;
line.avatar = avatar_of(state, uid);
(p.ts_ms, line)
})
.collect()
}
/// Whether a message of a session is ours.
pub fn is_own<L>(state: &AppState<L>, session: i64, message: &ChatMessage) -> bool {
let own_client = state.sessions.get(&session).and_then(|v| v.state.own_client);
own_message(&state.own_uids, own_client, message)
}
/// Where someone is in one session.
#[derive(Clone, Debug, PartialEq)]
pub struct Spot {
/// The session.
pub session: i64,
/// The server's name.
pub server: String,
/// The client's id there.
pub client: u16,
/// The channel it is in.
pub channel: u64,
/// The channel's name as shown (a spacer's text).
pub channel_title: String,
/// Its away message, if it is away.
pub away: Option<String>,
/// It streams.
pub streaming: bool,
/// We are connected with voice there (messages, pokes, moving).
pub voice: bool,
}
/// A server's name: its bookmark's, else what the session calls it.
pub fn server_name<L>(state: &AppState<L>, session: i64) -> String {
state.bookmarks.iter().find(|b| b.id == session).map(|b| b.name.clone()).unwrap_or_else(|| {
state.sessions.get(&session).map(|v| v.presence.server_name.clone()).unwrap_or_default()
})
}
/// Every session where the client with this unique id is, in bookmark
/// order.
pub fn spots_of<L>(state: &AppState<L>, uid: &str) -> Vec<Spot> {
let mut ids: Vec<i64> = state.sessions.keys().copied().collect();
ids.sort_by_key(|id| state.bookmarks.iter().position(|b| b.id == *id).unwrap_or(usize::MAX));
let mut spots = Vec::new();
for id in ids {
let view = &state.sessions[&id];
let Some(c) = view.presence.clients.values().find(|c| c.uid.as_deref() == Some(uid)) else {
continue;
};
let channel = view.presence.channels.get(&c.channel);
spots.push(Spot {
session: id,
server: server_name(state, id),
client: c.id,
channel: c.channel,
channel_title: channel
.map(|ch| crate::tree::channel_title(ch).0.to_owned())
.unwrap_or_default(),
away: c.away.clone(),
streaming: c.streaming == Some(true),
voice: view.state.voice == VoiceState::Connected,
});
}
spots
}
/// What we call the peer of a private chat: its contact's nickname, the name
/// it has where it is now, the name on a message of theirs (`last`, or one in
/// any open chat), else the start of its unique id.
pub fn peer_name<L>(state: &AppState<L>, uid: &str, last: Option<&HistoryMessage>) -> String {
if let Some(c) = state.contacts.get(uid).filter(|c| !c.nickname.is_empty()) {
return c.nickname.clone();
}
if let Some(s) = spots_of(state, uid).first() {
return state.sessions[&s.session].nickname(s.client);
}
let from_peer = |m: &HistoryMessage| {
(m.message.author_uid.as_deref() == Some(uid)).then(|| m.message.author_name.clone())
};
last.and_then(from_peer)
.or_else(|| {
state.sessions.values().flat_map(|v| &v.tabs).find_map(|t| {
(t.target == ChatTarget::Private(uid.to_owned()))
.then(|| t.messages.iter().rev().find_map(|m| from_peer(&m.message)))
.flatten()
})
})
.unwrap_or_else(|| uid.chars().take(8).collect())
}
/// A chat of any server.
#[derive(Clone, Debug, PartialEq)]
@@ -218,6 +441,18 @@ mod tests {
NaiveDateTime::parse_from_str(text, "%Y-%m-%d %H:%M").unwrap()
}
/// The bell's rows carry the kind's name and the Slint side picks the
/// colour and the icon by it (`ui/screens/overlays.slint`; the message is
/// what no other name matches), so a renamed kind must fail here.
#[test]
fn notice_kinds_are_named_as_the_bell_keys_them() {
use NoticeKind::{Event, Friend, Mention, Message, Poke};
assert_eq!(
[Mention, Poke, Message, Event, Friend].map(NoticeKind::name),
["mention", "poke", "message", "event", "friend"]
);
}
#[test]
fn times() {
let now = 1_800_000_000_000;
+32 -6
View File
@@ -21,9 +21,11 @@ use voelin_gateway_proto::{
use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, GroupInfo, Presence};
use voelin_store::Bookmark;
use crate::bridge::ChatLine;
use crate::chat::{LineCache, Previous};
use crate::image::ImageRef;
use crate::settings::{ClientPlaybackMap, DeviceChoices, UiSettings};
use crate::streams::logic::{Sharing, Watching};
/// The store's name of a chat.
pub fn store_target(target: &ChatTarget) -> voelin_store::ChatTarget {
@@ -34,6 +36,20 @@ pub fn store_target(target: &ChatTarget) -> voelin_store::ChatTarget {
}
}
/// The lines of a chat tab, in the front end's own list type (a Slint model
/// kept in step with them, or a plain `Vec`): what a message that arrives
/// without stored history appends.
pub trait Lines: Default {
/// Append a line.
fn push(&mut self, line: ChatLine);
}
impl Lines for Vec<ChatLine> {
fn push(&mut self, line: ChatLine) {
Vec::push(self, line);
}
}
/// A file being downloaded from a chat message.
pub struct Download {
/// The message's handle.
@@ -283,21 +299,21 @@ pub struct SessionView<L> {
/// Clients whose stored volume was sent for this voice connection.
pub applied_playback: HashSet<u16>,
/// Avatar pictures in the engine's cache, by unique id
/// ([`Event::AvatarReady`]).
/// ([`voelin_core::Event::AvatarReady`]).
pub avatars: HashMap<String, PathBuf>,
/// Icons in the engine's cache, by icon id ([`Event::IconReady`]).
/// Icons in the engine's cache, by icon id ([`voelin_core::Event::IconReady`]).
pub icons: HashMap<u32, PathBuf>,
/// Banners and badges in the engine's cache, by address
/// ([`Event::PictureReady`]).
/// ([`voelin_core::Event::PictureReady`]).
pub pictures: HashMap<String, PathBuf>,
/// The server's icon id as its voice connection last told it
/// ([`Event::ServerDetails`]); kept while disconnected, for the rail.
/// ([`voelin_core::Event::ServerDetails`]); kept while disconnected, for the rail.
pub server_icon: u32,
/// Bookmark address that supplied this session's icon.
pub icon_address: Option<String>,
/// The server groups in display order ([`Event::Groups`]).
/// The server groups in display order ([`voelin_core::Event::Groups`]).
pub server_groups: Vec<GroupInfo>,
/// The channel groups ([`Event::Groups`]).
/// The channel groups ([`voelin_core::Event::Groups`]).
pub channel_groups: Vec<GroupInfo>,
/// What the session's gateway offers (`voelin_gateway_proto::feature`).
pub gateway_caps: Vec<String>,
@@ -550,6 +566,13 @@ pub struct AppState<L> {
/// Files being uploaded to a channel from the composer: session,
/// channel and name, so the link can be posted when they are up.
pub uploads: HashMap<u64, (i64, u64, String)>,
/// Our unique ids (TeamSpeak 3 and 6 of every identity): messages by
/// them are ours ([`crate::social::own_message`]).
pub own_uids: HashSet<String>,
/// Our stream (the capture that feeds it is the front end's).
pub share: Option<Sharing>,
/// The stream in the viewer (its decoder is the front end's).
pub watch: Option<Watching>,
}
impl<L> AppState<L> {
@@ -589,6 +612,9 @@ impl<L> AppState<L> {
stream_volume: 100.0,
gateways_looked_up: HashSet::new(),
uploads: HashMap::new(),
own_uids: HashSet::new(),
share: None,
watch: None,
}
}
}
File diff suppressed because it is too large. Load diff
@@ -1,5 +1,8 @@
//! Streams on the voice view, the phone's Activity tab and Home: what is
//! shared, and who shares it.
//! shared, and who shares it; [`logic`] has the state of the streams we
//! share and watch, and what happens to them.
pub mod logic;
use std::path::PathBuf;
+3
View File
@@ -117,6 +117,7 @@ pub fn audio_label(kind: &AudioSourceKindSetting) -> (String, String, &'static s
pub struct AudioLive {
/// Peak in dBFS.
pub level: f32,
/// What went wrong with the source, if something did.
pub error: Option<String>,
}
@@ -502,7 +503,9 @@ pub fn placement(kind: &SourceKind, (w, h): (u32, u32)) -> Transform {
/// (`None`: switched off, so it is removed).
#[derive(Clone, Debug, PartialEq)]
pub struct Overlay {
/// The source's name.
pub name: &'static str,
/// What it shows, none to remove it.
pub text: Option<String>,
}
+62 -1
View File
@@ -1,6 +1,6 @@
//! The Stream Studio's structs: the plain counterparts of
//! `crates/voelin-ui/ui/studio-bridge.slint`, as [`crate::bridge`] has those of
//! `bridge.slint`.
//! `bridge.slint`. As there, every field is documented.
use std::sync::Arc;
@@ -9,7 +9,9 @@ use crate::image::ImageRef;
/// A scene of the studio.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct StudioScene {
/// The scene's id.
pub id: i32,
/// The scene's name.
pub name: Arc<str>,
/// Its sources, front first: "Screen + Camera + Text".
pub detail: Arc<str>,
@@ -22,11 +24,15 @@ pub struct StudioScene {
/// A source of the live scene, front first.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct StudioSource {
/// The source's id in its scene.
pub id: i32,
/// The source's name.
pub name: Arc<str>,
/// screen, window, portal, camera, image, text, colour, pattern
pub kind: Arc<str>,
/// It is shown in the output.
pub visible: bool,
/// It cannot be moved, resized or cropped.
pub locked: bool,
/// keep, blur, image, colour
pub background: Arc<str>,
@@ -36,18 +42,22 @@ pub struct StudioSource {
pub info: Arc<str>,
/// At the front or the back (cannot move further).
pub front: bool,
/// At the back; it cannot move further.
pub back: bool,
}
/// An audio source of the stream (`stream.audio_sources`).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct StudioAudio {
/// The source's name.
pub name: Arc<str>,
/// "Elgato Wave:3", the application...
pub detail: Arc<str>,
/// microphone, desktop, app, window, tone
pub kind: Arc<str>,
/// Its gain in dB.
pub gain_db: f32,
/// It is muted in the mix.
pub muted: bool,
/// The meter in dBFS, after the gain.
pub level: f32,
@@ -60,6 +70,7 @@ pub struct StudioAudio {
pub struct StudioLayer {
/// "1280x720"; empty: `scale` of the output.
pub size: Arc<str>,
/// The factor on the output's size when `size` is empty.
pub scale: Arc<str>,
/// Frame-rate cap; empty: the output's.
pub fps: Arc<str>,
@@ -72,7 +83,9 @@ pub struct StudioLayer {
/// A viewer of the studio's stream.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct StudioViewer {
/// The viewer's client id.
pub client: i32,
/// The viewer's name.
pub name: Arc<str>,
/// requested, connecting, connected
pub state: Arc<str>,
@@ -81,7 +94,9 @@ pub struct StudioViewer {
/// An entry of a picker (screens, windows, cameras, audio sources).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct StudioPick {
/// The entry's name.
pub name: Arc<str>,
/// The line under the name.
pub detail: Arc<str>,
/// For the icon: monitor, window, portal, camera, microphone, desktop, app, tone
pub kind: Arc<str>,
@@ -100,48 +115,70 @@ pub struct StudioStatus {
pub destination: Arc<str>,
/// 0: not live, 1: poor, 2: fair, 3: good, 4: excellent.
pub quality: i32,
/// The words for `quality`.
pub quality_text: Arc<str>,
/// "1080p • 60 FPS • 8,250 kbps"
pub format: Arc<str>,
/// The numbers behind it, for the info button.
pub details: Arc<str>,
/// The stream is live.
pub live: bool,
/// Going live: waiting for the server.
pub starting: bool,
/// "00:12:34"
pub elapsed: Arc<str>,
/// How many watch the stream.
pub viewers: i32,
/// How many viewers the stream has, those who only asked included.
pub participants: i32,
/// Go Live is possible.
pub can_go_live: bool,
/// Why Go Live is off, or what goes wrong.
pub hint: Arc<str>,
/// A recording runs.
pub recording: bool,
/// How long the recording runs: "00:12:34".
pub recorded: Arc<str>,
/// The replay buffer's window (0: off) and what it holds now.
pub replay_seconds: i32,
/// What the replay buffer holds now: "30 s".
pub replay_held: Arc<str>,
/// The output's width in pixels.
pub output_width: i32,
/// The output's height in pixels.
pub output_height: i32,
/// The output's frame rate.
pub fps: i32,
/// The studio is in a window of its own.
pub detached: bool,
/// A window of its own is possible (not on Android).
pub can_detach: bool,
/// The live scene shows a screen, a camera, a window (the phone's cards).
pub screen_shown: bool,
/// The live scene shows a camera.
pub camera_shown: bool,
/// The live scene shows a window.
pub window_shown: bool,
}
/// The stream settings panel (`studio.stream`, `stream.bitrate_kbps`).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct StudioForm {
/// Index into the destinations offered (channels to stream to); -1: none.
pub destination: i32,
/// The stream's title.
pub title: Arc<str>,
/// Game or category: it follows the title in the stream's name.
pub game: Arc<str>,
/// Sent to the channel's chat when the stream goes live.
pub message: Arc<str>,
/// The viewers are an overlay in the live scene.
pub show_viewers: bool,
/// The stream chat's last lines are an overlay.
pub show_chat: bool,
/// The title and the game are an overlay.
pub show_now_playing: bool,
/// The stream carries the mixer's sources; off: none.
pub audio: bool,
/// kbit/s of the stream without layers, as typed.
pub bitrate: Arc<str>,
@@ -151,45 +188,69 @@ pub struct StudioForm {
/// sources: `id` -1). Numbers as typed.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct StudioSourceForm {
/// The source's id; -1: a new one.
pub id: i32,
/// The source's name.
pub name: Arc<str>,
/// screen, window, portal, camera, image, text, colour or pattern.
pub kind: Arc<str>,
/// The left edge in output pixels.
pub x: Arc<str>,
/// The top edge in output pixels.
pub y: Arc<str>,
/// Empty: the source's own size times `scale`.
pub width: Arc<str>,
/// As `width`, for the height.
pub height: Arc<str>,
/// The factor on the source's own size, where `width` or `height` is empty.
pub scale: Arc<str>,
/// contain, cover, stretch
pub fit: Arc<str>,
/// Pixels cut off the source's left edge.
pub crop_left: Arc<str>,
/// Pixels cut off its top edge.
pub crop_top: Arc<str>,
/// Pixels cut off its right edge.
pub crop_right: Arc<str>,
/// Pixels cut off its bottom edge.
pub crop_bottom: Arc<str>,
/// Percent.
pub opacity: f32,
/// It cannot be moved, resized or cropped.
pub locked: bool,
/// It is shown in the output.
pub visible: bool,
/// keep, blur, image, colour
pub background: Arc<str>,
/// Blur radius in percent of the picture's height.
pub blur: Arc<str>,
/// The picture behind the source, for the background `image`.
pub background_path: Arc<str>,
/// The colour behind the source, for the background `colour`.
pub background_colour: Arc<str>,
/// Text, colour ("#rrggbb" or "#rrggbbaa") and image sources.
pub text: Arc<str>,
/// The text's size in pixels.
pub text_size: Arc<str>,
/// The text's or the colour source's colour.
pub colour: Arc<str>,
/// The image source's file.
pub path: Arc<str>,
/// The camera picture is mirrored.
pub mirror: bool,
}
/// The studio settings dialog (`studio.*` keys and the preview).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct StudioSettingsForm {
/// Seconds the replay buffer keeps; 0: off.
pub replay_seconds: Arc<str>,
/// MiB of the replay buffer kept in memory.
pub replay_memory: Arc<str>,
/// The folder of recordings and clips; empty: the default.
pub recording_dir: Arc<str>,
/// The preview's width in pixels.
pub preview_width: Arc<str>,
/// The preview's frame rate.
pub preview_fps: Arc<str>,
}
+6
View File
@@ -56,11 +56,17 @@ pub fn badge_items(guids: &[String], pictures: &HashMap<String, PathBuf>) -> Vec
/// What the tree shows besides the presence.
pub struct TreeInput<'a> {
/// The channels and clients of the server.
pub presence: &'a Presence,
/// The channels folded shut.
pub collapsed: &'a HashSet<ChannelId>,
/// The clients that are talking.
pub talking: &'a HashSet<u16>,
/// Local volume and mute of the clients we changed.
pub playback: &'a ClientPlaybackMap,
/// The channel we are in.
pub own_channel: Option<ChannelId>,
/// Our own client.
pub own_client: Option<u16>,
/// Search text: only matching channels and clients (and the channels
/// above them) are shown. Empty: everything.
+30 -282
View File
@@ -2,11 +2,12 @@
//! event loop glue and the state the screens share.
//!
//! The screens' logic is elsewhere: servers and the channel tree in
//! `servers.rs`, chat in `chat.rs`, streams in `streams.rs`, the settings
//! page in `settings_page.rs` and `appearance.rs`, the settings pages in
//! `settings_pages/`, the Stream Studio in `studio/`, the view models in the
//! `voelin-ui-vm` crate (`vm`), callbacks in `bind/`, development switches in
//! `dev.rs`.
//! `servers/`, chat in `chat/`, streams in `streams/`, the people, the bell
//! and the search in `social/`, the settings page in `settings_page/` and
//! `appearance.rs`, the settings pages in `settings_pages/`, the Stream
//! Studio in `studio/`, what the screens show and what a move or an event
//! does in the `voelin-ui-vm` crate (`vm`), callbacks in `bind/`,
//! development switches in `dev/`.
use std::cell::RefCell;
use std::path::{Path, PathBuf};
@@ -23,18 +24,15 @@ use voelin_core::settings::{
AUDIO, CRASH_REPORTS, IDENTITY_IMPORT, STREAM_DECODER_BACKEND, STREAM_HARDWARE_DECODING,
Settings,
};
use voelin_core::{
AudioSettings, BackendInfo, Command, Engine, Event, History, ObserveState, VoiceState,
};
use voelin_model::ChatTarget;
use voelin_core::{AudioSettings, Command, Engine, Event, History};
use voelin_platform::crash;
use voelin_store::{Bookmark, MemorySecrets, Secrets, Store};
use crate::bind::rows::Rows;
use crate::hotkey::GlobalPtt;
use crate::settings::{CLIENT_PLAYBACK, ClientPlaybackMap, UI, UiSettings, appearance_keys};
use crate::streams::{Share, Watch};
use crate::video::Video;
use crate::streams::Share;
use crate::video::{Decoder, Video};
use crate::vm;
slint::include_modules!();
@@ -119,6 +117,12 @@ impl Secrets for FallbackSecrets {
/// The lines of a chat as the chat view shows them.
pub(crate) type ChatRows = Rows<vm::bridge::ChatLine>;
impl vm::state::Lines for ChatRows {
fn push(&mut self, line: vm::bridge::ChatLine) {
Rows::push(self, line);
}
}
/// A chat of a session (see `voelin_ui_vm::state`).
pub(crate) type Tab = vm::state::Tab<ChatRows>;
@@ -225,13 +229,13 @@ pub(crate) struct App {
pub prefs: Settings,
pub ptt: GlobalPtt,
pub video: Video,
/// Our stream.
/// The capture of our stream (`state.share` has the rest of it).
pub share: Option<Share>,
/// The stream in the viewer.
pub watch: Option<Watch>,
/// The decoder of the stream in the viewer (`state.watch` has the rest).
pub decoder: Option<Decoder>,
/// `VOELIN_DEMO_STREAM`: the viewer shows a local test stream.
pub demo: bool,
/// `VOELIN_DEMO_UI`: sample servers, channels and chat (dev.rs).
/// `VOELIN_DEMO_UI`: sample servers, channels and chat (dev/).
pub demo_ui: bool,
/// `VOELIN_AUTOSHARE=test-pattern`: share the test pattern once streams work.
pub autoshare: bool,
@@ -347,7 +351,7 @@ pub fn run(options: RunOptions) -> Result<()> {
let HostedEngine { engine, runtime, mut events } = hosted;
// VOELIN_DATA_DIR isolates the database; the other development
// switches are in dev.rs.
// switches are in dev/.
// A host that names the data directory (Android) has no platform cache
// directory either: avatars and icons go next to the database.
if let Some(dir) = &options.data_dir {
@@ -386,7 +390,7 @@ pub fn run(options: RunOptions) -> Result<()> {
// Creating an identity takes a moment (security level 8).
let identity = tsclientlib::Identity::create();
let origin = voelin_store::IdentityOrigin::Created;
store.add_identity(crate::servers::CREATED_IDENTITY, &identity, origin)?;
store.add_identity(vm::servers::logic::CREATED_IDENTITY, &identity, origin)?;
identity
}
};
@@ -438,7 +442,7 @@ pub fn run(options: RunOptions) -> Result<()> {
ptt,
video,
share: None,
watch: None,
decoder: None,
demo: switches.demo_stream,
demo_ui: switches.demo_ui,
autoshare: switches.autoshare,
@@ -473,7 +477,7 @@ pub fn run(options: RunOptions) -> Result<()> {
if app.demo {
app.start_demo();
}
if let Some(text) = crate::servers::imported_status(&imported) {
if let Some(text) = vm::servers::logic::imported_status(&imported) {
app.set_status(text);
}
});
@@ -512,7 +516,9 @@ pub fn run(options: RunOptions) -> Result<()> {
for id in ids {
app.save_reads(id);
}
app.watch = None;
app.state.watch = None;
app.decoder = None;
app.state.share = None;
app.share = None;
if own && !app.demo_ui {
for id in app.state.sessions.keys() {
@@ -627,7 +633,7 @@ impl App {
/// A setting changed, maybe elsewhere (a command, another window): take
/// the values the window keeps copies of. The engine applies audio
/// settings itself.
fn setting_changed(&mut self, key: &str) {
pub(crate) fn setting_changed(&mut self, key: &str) {
if key == AUDIO.name() && !self.state.audio_dirty {
self.state.audio = self.prefs.get(&AUDIO);
// The voice controls follow the transmit mode.
@@ -644,7 +650,7 @@ impl App {
} else if appearance_keys().iter().any(|k| k.name() == key) {
self.apply_appearance();
} else if key == voelin_core::settings::STREAM_AUDIO_SOURCES.name() {
// A running share mixes the new sources (streams.rs).
// A running share mixes the new sources (streams/bind.rs).
self.share_audio_changed();
} else if key == STREAM_HARDWARE_DECODING.name() || key == STREAM_DECODER_BACKEND.name() {
self.video.set_decoder_preference(decoder_preference(&self.prefs));
@@ -652,239 +658,6 @@ impl App {
self.page_setting_changed(key);
}
pub(crate) fn handle_event(&mut self, event: Event) {
let touched = self.social_event(&event);
self.dispatch(event);
self.social_refresh(touched);
}
fn dispatch(&mut self, event: Event) {
match event {
Event::State { session, state } => {
let id = session as i64;
let view = self.state.sessions.entry(id).or_default();
let was_voice = view.state.voice;
let was_observe = view.state.observe;
let was_channel = view.state.own_channel;
view.state = state.clone();
if state.voice != VoiceState::Connected {
view.focused_own_channel = false;
}
if state.voice == VoiceState::Disconnected && was_voice != VoiceState::Disconnected
{
view.channel_passwords.clear();
view.join_after_connect = None;
}
if state.voice == VoiceState::Connected && was_voice != VoiceState::Connected {
// A new connection: volumes are sent again.
view.applied_playback.clear();
}
// Where its chats were read, once the server is known; kept
// when the session ends.
self.load_reads(id);
let off = |voice: VoiceState, observe: ObserveState| {
voice == VoiceState::Disconnected && observe == ObserveState::Off
};
if off(state.voice, state.observe) && !off(was_voice, was_observe) {
self.save_reads(id);
}
let view = self.state.sessions.entry(id).or_default();
let focus = !view.focused_own_channel;
if state.voice == VoiceState::Connected && was_voice != VoiceState::Connected {
self.set_status("Connected");
}
if self.state.current == Some(id) {
if self.track_reading() {
self.refresh_chat();
}
// The voice channel's chat is always at hand, and focused
// once per connection.
if let (Some(cid), VoiceState::Connected) = (state.own_channel, state.voice) {
self.open_chat(ChatTarget::Channel(cid), focus);
self.state.sessions.entry(id).or_default().focused_own_channel = true;
}
}
// Where we are with voice, when it changed here: home's last
// place, which `refresh_servers` shows (voice on another
// server does not take it back at each of its events).
if (state.voice, state.own_channel) != (was_voice, was_channel) {
self.remember_voice(id);
}
self.refresh_servers();
self.refresh_toolbar();
self.refresh_tree();
self.refresh_streams();
self.autoshare();
if self.open_client_pending && self.state.current == Some(id) {
self.open_first_client();
}
self.join_after_connect(id);
}
Event::ServerInfo { session, name, backend, capabilities } => {
self.state.sessions.entry(session as i64).or_default().capabilities = capabilities;
self.adopt_server_name(session as i64, &name);
if self.state.current == Some(session as i64) {
self.set_status(connected_status(&name, &backend));
}
self.refresh_streams();
self.autoshare();
}
Event::Presence { session, presence } => {
let view = self.state.sessions.entry(session as i64).or_default();
// The server chat shows its welcome and host message, with
// their pictures.
let said = crate::chat::server_texts(&view.presence.server)
!= crate::chat::server_texts(&presence.server);
// Our channel's path: known only now (a new connection),
// or renamed.
let path = |v: &SessionView| {
v.state.own_channel.map(|c| crate::vm::tree::channel_path(&v.presence, c))
};
let path_before = path(view);
view.presence = presence;
let renamed = path(view) != path_before;
self.apply_client_playback(session as i64);
self.join_after_connect(session as i64);
if renamed && self.remember_voice(session as i64) {
self.refresh_servers();
}
if self.state.current == Some(session as i64) {
if said {
self.fetch_previews(session as i64);
}
self.refresh_toolbar();
self.refresh_tree();
self.refresh_chat();
self.refresh_streams();
if self.open_client_pending {
self.open_first_client();
}
}
}
Event::Talking { session, client, talking } => {
let view = self.state.sessions.entry(session as i64).or_default();
if talking {
view.talking.insert(client);
} else {
view.talking.remove(&client);
}
if self.state.current == Some(session as i64) {
self.refresh_tree();
}
}
Event::InputLevel { session, level_db, sending } => {
let shown = match session {
Some(s) => self.state.current == Some(s as i64),
None => self.state.mic_test,
};
if shown && let Some(ui) = self.ui.upgrade() {
let bridge = ui.global::<Bridge>();
bridge.set_input_level(level_db);
bridge.set_input_sending(sending);
}
}
Event::MicrophoneTestError { message } => {
self.set_status(format!("Microphone test: {message}"))
}
// Only for sessions the engine keeps no history for (it does not
// know the server yet): those get ids and reactions instead.
Event::Chat { session, message } => {
let id = session as i64;
if !self.state.sessions.entry(id).or_default().has_history() {
self.add_message(id, message);
}
}
Event::ChatHistory { session, target, messages, source, complete } => {
self.history_batch(session as i64, &target, messages, source, complete);
}
Event::Gateway { session, update } => {
if let voelin_core::gateway::GatewayUpdate::Connected { url, .. } = &update {
self.gateway_in_use(session as i64, url);
}
self.gateway_extra(session as i64, &update);
self.gateway_update(session as i64, update);
}
Event::Groups { session, server_groups, channel_groups } => {
let view = self.state.sessions.entry(session as i64).or_default();
view.server_groups = (*server_groups).clone();
// Display order, as TeamSpeak sorts them.
view.server_groups.sort_by_key(|g| (g.sort_id, g.id));
view.channel_groups = (*channel_groups).clone();
if self.state.current == Some(session as i64) {
self.refresh_tree();
}
}
Event::ServerDetails { session, address, details } => {
self.remember_server_icon(session as i64, &address, details.icon);
self.refresh_servers();
self.refresh_toolbar();
}
// Pictures can arrive after the rows were built: draw them again.
Event::AvatarReady { session, client_uid, path, .. } => {
let view = self.state.sessions.entry(session as i64).or_default();
// A file that arrives again is decoded again if it changed.
crate::images::reloaded(&path);
view.avatars.insert(client_uid, path);
if self.state.current == Some(session as i64) {
self.refresh_tree();
self.refresh_chat();
self.refresh_toolbar();
self.refresh_member_card();
self.refresh_streams();
}
}
Event::IconReady { session, icon, path } => {
let view = self.state.sessions.entry(session as i64).or_default();
crate::images::reloaded(&path);
view.icons.insert(icon, path);
self.refresh_servers();
if self.state.current == Some(session as i64) {
self.refresh_tree();
self.refresh_toolbar();
}
}
Event::PictureReady { session, url, path } => {
let view = self.state.sessions.entry(session as i64).or_default();
// The host banner reloads into the same file.
crate::images::reloaded(&path);
view.pictures.insert(url, path);
if self.state.current == Some(session as i64) {
self.refresh_toolbar();
self.refresh_tree();
self.refresh_chat();
self.refresh_member_card();
}
}
Event::Transfer { session, transfer, state } => {
self.transfer_progress(session as i64, transfer, state);
}
// The engine's contacts would replace the sample ones.
Event::ContactsChanged { .. } if self.demo_ui && !self.state.contacts.is_empty() => {}
Event::ContactsChanged { contacts } => {
self.state.contacts = contacts.iter().map(|c| (c.uid.clone(), c.clone())).collect();
self.refresh_member_card();
}
// The sample sessions of VOELIN_DEMO_UI are unknown to the engine.
Event::Error { .. } if self.demo_ui => {}
Event::Error { message, .. } => self.set_status(message),
Event::JoinFailed { session, channel, reason } => {
self.join_failed(session as i64, channel, reason);
}
Event::SettingChanged { key } => self.setting_changed(&key),
Event::SettingRejected { key, message } => {
self.set_status(format!("Setting {key}: {message}"));
}
// The Stream Studio's stream (studio/).
Event::StreamState { session, state } if self.studio_streams_to(session as i64) => {
self.studio_stream_state(state);
}
Event::StreamViewers { session, viewers } if self.studio_streams_to(session as i64) => {
self.studio_viewers(viewers);
}
event => self.stream_event(event),
}
}
/// Once a second.
fn tick(&mut self) {
self.tick_streams();
@@ -903,36 +676,11 @@ impl App {
}
}
/// The status line once a server answered: "Connected to Nightfall Guild
/// (TeamSpeak 6 6.0.0-beta13.1)".
fn connected_status(name: &str, backend: &BackendInfo) -> String {
format!("Connected to {name} ({})", backend.label())
}
#[cfg(test)]
mod tests {
use super::*;
use voelin_model::ChatTarget;
#[test]
fn the_status_line_names_the_servers_software() {
let backend = |product: &str, version: &str| BackendInfo {
product: product.into(),
version: version.into(),
};
assert_eq!(
connected_status("Nightfall Guild", &backend("TeamSpeak 6", "6.0.0-beta13.1")),
"Connected to Nightfall Guild (TeamSpeak 6 6.0.0-beta13.1)"
);
assert_eq!(
connected_status("Pixel Lounge", &backend("TeamSpeak 3", "3.13.8")),
"Connected to Pixel Lounge (TeamSpeak 3 3.13.8)"
);
// Not recognised: the version string the server sent.
assert_eq!(
connected_status("Home", &backend("", "custom 9")),
"Connected to Home (custom 9)"
);
}
use super::*;
#[test]
fn channel_unread_ignores_private_tabs() {
+39 -2
View File
@@ -37,8 +37,14 @@ pub(crate) fn image(picture: &ImageRef) -> Image {
match &**picture {
ImageSource::None => Image::default(),
ImageSource::File { path, .. } => crate::images::file(path),
ImageSource::Rgba { w, h, bytes } => {
Image::from_rgba8(SharedPixelBuffer::<Rgba8Pixel>::clone_from_slice(bytes, *w, *h))
// `Pixels` holds `width * height * 4` bytes, which `clone_from_slice`
// needs (it panics otherwise).
ImageSource::Rgba(pixels) => {
Image::from_rgba8(SharedPixelBuffer::<Rgba8Pixel>::clone_from_slice(
pixels.bytes(),
pixels.width(),
pixels.height(),
))
}
ImageSource::Svg(data) => Image::load_from_svg_data(data).unwrap_or_default(),
ImageSource::Memory { key, bytes } => crate::images::picture(key, bytes),
@@ -71,3 +77,34 @@ pub(crate) fn model<V, S: for<'a> From<&'a V> + Clone + 'static>(rows: &[V]) ->
pub(crate) fn rows<S: Clone + 'static, V: From<S>>(model: &ModelRc<S>) -> Vec<V> {
slint::Model::iter(model).map(V::from).collect()
}
#[cfg(test)]
mod tests {
use super::*;
/// A picture of pixels shows as wide and as high as it was made, with
/// every pixel in its place: a width that is not the height tells the two
/// apart, and every pixel holds its column and its row.
#[test]
fn a_picture_of_pixels_keeps_its_size_and_its_places() {
let (w, h) = (3u32, 2u32);
let bytes: Vec<u8> = (0..h)
.flat_map(|y| (0..w).flat_map(move |x| [x as u8 + 1, y as u8 + 10, 7, 255]))
.collect();
let picture = image(&ImageSource::rgba(w, h, bytes));
let size = picture.size();
assert_eq!((size.width, size.height), (w, h));
let pixels = picture.to_rgba8().expect("a picture made of pixels");
let at = |x: u32, y: u32| {
let p = pixels.as_slice()[(y * w + x) as usize];
(p.r, p.g, p.b, p.a)
};
assert_eq!(at(0, 0), (1, 10, 7, 255));
assert_eq!(at(2, 0), (3, 10, 7, 255));
assert_eq!(at(0, 1), (1, 11, 7, 255));
assert_eq!(at(2, 1), (3, 11, 7, 255));
// Pixels of another length are no picture (and no panic).
let none = image(&ImageSource::rgba(w, h, vec![0u8; 23]));
assert_eq!((none.size().width, none.size().height), (0, 0));
}
}
File diff suppressed because it is too large. Load diff
+290
View File
@@ -0,0 +1,290 @@
//! The Slint side of the chat: the Bridge writes of the tabs, the lines and
//! the drawers, and the callbacks' ways into the transitions of
//! `voelin_ui_vm::chat::logic`.
use slint::ComponentHandle;
use voelin_core::{HistoryMessage, HistorySource};
use voelin_model::{ChatMessage, ChatTarget};
use crate::app::{App, Bridge, Nav, SessionView, Tab};
use crate::settings::UI_IMAGE_PREVIEW_KB;
use crate::vm;
use crate::vm::bbcode::LinkKind;
use crate::vm::bridge::{ChatLine, ChatTab};
use crate::vm::chat::logic::{self as logic, LinesFacts};
use voelin_core::settings::CACHE_FETCH_IMAGES;
impl App {
/// Open the chat `target` of the current session, and with `focus` show
/// it ([`logic::open_chat`]).
pub(crate) fn open_chat(&mut self, target: ChatTarget, focus: bool) {
self.transition(|state, cx| logic::open_chat(state, cx, target, focus));
}
/// The index of `target`'s tab in session `id`, opened if new (the
/// engine then sends its history).
pub(crate) fn chat_tab(&mut self, id: i64, target: ChatTarget) -> usize {
self.transition(|state, cx| logic::chat_tab(state, cx, id, target))
}
/// The session's tab that tab `index` of the chat strip is
/// (`Bridge.tabs`, [`vm::chat::strip`]).
pub(crate) fn strip_tab(&self, index: i32) -> Option<usize> {
self.models.strip.borrow().get(usize::try_from(index).ok()?).copied()
}
pub(crate) fn select_tab(&mut self, index: usize) {
self.transition(|state, cx| logic::select_tab(state, cx, index));
}
pub(crate) fn close_tab(&mut self, index: usize) {
self.transition(|state, cx| logic::close_tab(state, cx, index));
}
pub(crate) fn send_message(&mut self, text: String) {
self.transition(|state, cx| logic::send_message(state, cx, text));
}
/// A live message of a session without stored history.
pub(crate) fn add_message(&mut self, id: i64, message: ChatMessage) {
self.transition(|state, cx| logic::add_message(state, cx, id, message));
}
/// Messages the engine stored: added or updated by their local id.
pub(crate) fn history_batch(
&mut self,
id: i64,
target: &ChatTarget,
messages: Vec<HistoryMessage>,
source: HistorySource,
complete: bool,
) {
self.transition(|state, cx| {
logic::history_batch(state, cx, id, target, messages, source, complete);
});
}
/// The page of messages before the oldest one shown.
pub(crate) fn load_older(&mut self) {
if let Some(sample) = self.transition(logic::load_older) {
// No engine answers in demo mode.
crate::dev::answer_older(sample.session, sample.target, sample.oldest);
}
}
/// What the lines of a chat need besides the state.
fn lines_facts(&self) -> LinesFacts<'_> {
LinesFacts {
// Pictures on the web show only while pictures are fetched and
// shown.
pictures_shown: self.prefs.get(&CACHE_FETCH_IMAGES)
&& self.prefs.get(&UI_IMAGE_PREVIEW_KB) > 0,
pokes: &self.social.pokes,
}
}
/// The lines of a tab's messages (`main`) or of its open topic, grouped
/// and with everything the row shows (also the stream chat of the
/// Stream Studio, studio/).
pub(crate) fn lines_of(&self, view: &SessionView, tab: &Tab, main: bool) -> Vec<ChatLine> {
logic::lines_of(&self.state, view, tab, main, &self.lines_facts())
}
/// Tabs and the shown tab's messages.
pub(crate) fn refresh_chat(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let Some(chat) = logic::chat_view(&self.state, &self.lines_facts()) else {
self.models.tabs.sync(&[ChatTab { title: "Server".into(), ..Default::default() }]);
*self.models.strip.borrow_mut() = vec![0];
bridge.set_current_tab(0);
bridge.set_current_chat(0);
let empty = self.models.no_chat.model();
if bridge.get_messages() != empty {
bridge.set_messages(empty);
}
bridge.set_unread_index(-1);
return;
};
self.models.tabs.sync(&chat.tabs);
*self.models.strip.borrow_mut() = chat.strip;
if bridge.get_current_tab() != chat.current {
bridge.set_current_tab(chat.current);
}
bridge.set_current_chat(chat.current_chat);
// The tab on screen: its lines are what the chat view shows.
if let Some(view) = self.view() {
let tab = &view.tabs[view.current_tab];
if let Some(lines) = &chat.lines {
tab.lines.sync(lines);
}
let lines = tab.lines.model();
if bridge.get_messages() != lines {
bridge.set_messages(lines);
}
}
bridge.set_unread_index(chat.unread_index);
bridge.set_unread_count(chat.unread_count);
bridge.set_unread_since(chat.unread_since.into());
bridge.set_more_history(chat.more_history);
bridge.set_loading_history(chat.loading_history);
bridge.set_local_history(chat.local_history);
bridge.set_has_pins(chat.has_pins);
bridge.set_has_reactions(chat.has_reactions);
bridge.set_has_topics(chat.has_topics);
bridge.set_pins_loading(chat.pins_loading);
bridge.set_topics_loading(chat.topics_loading);
bridge.set_pins_count(chat.pins_count);
bridge.set_topics_count(chat.topics_count);
self.models.pins.sync(&chat.pins);
self.models.topics.sync(&chat.topics);
bridge.set_current_topic(chat.current_topic);
bridge.set_topic_title(chat.topic_title.into());
self.models.topic_messages.sync(&chat.topic_lines);
}
/// A link in a message was clicked (`masked`: its text shows something
/// else, [`vm::bbcode::is_masked`]). A page on the web opens in the
/// browser, a masked one once the user saw where it goes (Nav.link-open);
/// a TeamSpeak link in Voelin ([`App::open_link`]).
pub(crate) fn open_link_text(&mut self, link: &str, masked: bool) {
match vm::bbcode::classify_link(link) {
LinkKind::Web(url) if masked => {
if let Some(ui) = self.ui.upgrade() {
let nav = ui.global::<Nav>();
nav.set_link_host(vm::bbcode::link_host(&url).into());
nav.set_link_url(url.into());
nav.set_link_open(true);
}
}
LinkKind::Web(url) => {
if let Err(e) = self.open_url(&url) {
self.set_status(format!("Cannot open the link: {e}"));
}
}
LinkKind::Server(url) => self.open_link(&url),
// A file opens from its card.
LinkKind::File | LinkKind::Refused => {}
}
}
// What is read.
/// The current chat came on screen or left it (`Nav.chat-shown`).
pub(crate) fn chat_shown_changed(&mut self) {
self.transition(logic::chat_shown_changed);
}
/// The window gained or lost the focus (winit's events: the desktop
/// only).
#[cfg(not(target_os = "android"))]
pub(crate) fn window_focused(&mut self, focused: bool) {
self.transition(|state, cx| logic::window_focused(state, cx, focused));
}
/// The current chat is read (the bar over its messages): the divider
/// goes.
pub(crate) fn mark_read(&mut self) {
self.transition(logic::mark_read);
}
/// Store where every chat of session `id` was read (it ended, or the
/// app exits).
pub(crate) fn save_reads(&mut self, id: i64) {
self.transition(|state, cx| logic::save_reads(state, cx, id));
}
// Gateway features of a chat.
/// Add or remove our reaction to a message.
pub(crate) fn react(&mut self, key: i32, emoji: String) {
self.transition(|state, cx| logic::react(state, cx, key, emoji));
}
pub(crate) fn pin(&mut self, key: i32, on: bool) {
self.transition(|state, cx| logic::pin(state, cx, key, on));
}
/// 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(crate) fn prefetch_counts(&mut self) {
self.transition(|state, cx| logic::prefetch_counts(state, cx));
}
/// Open the pins of the current chat (loading them once).
pub(crate) fn open_pins(&mut self) {
self.transition(|state, cx| logic::open_pins(state, cx));
}
/// Highlight a pinned message in the chat.
pub(crate) fn jump_to_pin(&mut self, key: i32) {
let row = self.transition(|state, cx| logic::jump_to_pin(state, cx, key));
if let (Some(row), Some(ui)) = (row, self.ui.upgrade()) {
let bridge = ui.global::<Bridge>();
bridge.set_jump_index(row as i32);
bridge.set_jump_requests(bridge.get_jump_requests().wrapping_add(1));
}
}
/// The topics drawer's search.
pub(crate) fn search_topics(&mut self, text: String) {
self.transition(|state, cx| logic::search_topics(state, cx, text));
}
pub(crate) fn open_topics(&mut self) {
self.transition(|state, cx| logic::open_topics(state, cx));
}
/// Show a topic's messages (`-1` goes back to the chat).
pub(crate) fn open_topic(&mut self, id: i32) {
self.transition(|state, cx| logic::open_topic(state, cx, id));
}
pub(crate) fn send_topic_message(&mut self, text: String) {
self.transition(|state, cx| logic::send_topic_message(state, cx, text));
}
/// Start a topic from a message (`key` < 0: a standalone topic).
pub(crate) fn create_topic(&mut self, key: i32, title: String) {
self.transition(|state, cx| logic::create_topic(state, cx, key, title));
}
// Files in chat.
/// Download a file a message links, into the download folder.
pub(crate) fn download_file(&mut self, key: i32, index: i32) {
let dir = dirs::download_dir().unwrap_or_else(|| std::path::PathBuf::from("."));
self.transition(|state, cx| logic::download_file(state, cx, key, index, &dir));
}
/// Attach a file to the current channel chat: ask for one, upload it
/// into the channel and post its link.
pub(crate) fn attach_file(&mut self) {
let (id, channel) = match logic::attach_target(&self.state) {
Ok(Some(target)) => target,
Ok(None) => return,
Err(reason) => {
self.set_status(reason);
return;
}
};
if !voelin_platform::files::available() {
self.set_status("No file chooser on this platform.");
return;
}
let runtime = self.engine.runtime().clone();
runtime.spawn(async move {
let picked = voelin_platform::files::pick_file("Attach a file").await;
crate::app::later(move |app| match picked {
Ok(Some(path)) => app.upload(id, channel, path),
Ok(None) => {}
Err(e) => app.set_status(format!("Could not open the file chooser: {e}")),
});
});
}
/// Upload a file into a channel and link it in the chat once it is up.
pub(crate) fn upload(&mut self, id: i64, channel: u64, from: std::path::PathBuf) {
self.transition(|state, cx| logic::upload(state, cx, id, channel, from));
}
}
+13
View File
@@ -0,0 +1,13 @@
//! Chat: tabs per session (server, channels, private chats), their
//! messages, and what a gateway adds to them (pins, reactions, topics).
//! What the state does is in `voelin_ui_vm::chat::logic`; `bind` has the
//! Bridge writes and the models.
//!
//! The chat strip shows the server's and the channels' tabs; a private chat
//! is the current tab only while the messages page shows it (messages.rs).
//! The engine keeps the history: a tab holds the messages it was given,
//! ordered by `(ts_ms, id)`, and the lines of the selected tab are rebuilt
//! from them and synced ([`crate::bind::rows::Rows::sync`]), which touches
//! only the rows that changed.
mod bind;
+506
View File
@@ -0,0 +1,506 @@
//! The Slint side of the development switches: the window's size, the
//! screenshot, the screens opened at start (`VOELIN_OPEN`), and the sample
//! data fed through the app's own events. The sample data itself is in
//! `voelin_ui_vm::dev::logic`.
use std::sync::Arc;
use std::time::Duration;
use anyhow::Result;
use slint::{ComponentHandle, Rgba8Pixel, SharedPixelBuffer};
use voelin_core::{Event, HistoryMessage, HistorySource, JoinFailure};
use voelin_model::ChatTarget;
use crate::app::{App, Bridge, MainWindow, MobileTab, Nav, Page, SettingsSection, with_app};
use crate::social::now_ms;
use crate::vm::dev::logic::{self, DEMO};
/// 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<String>,
autoconnect: Option<String>,
screenshot: Option<std::path::PathBuf>,
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<String> = 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<slint::Timer>,
_resize: Option<slint::Timer>,
_scroll: Option<slint::Timer>,
_more: Option<slint::Timer>,
}
/// 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::<Nav>();
for open in &switches.open {
let (what, arg) = open.split_once(':').unwrap_or((open.as_str(), ""));
match what {
"home" => nav.invoke_show(Page::Home),
"server" => {
nav.invoke_show(Page::Server);
// The server chat, which starts with the welcome message.
if arg == "chat" {
with_app(|app| app.select_tab(0));
}
}
"settings" => nav.invoke_open_settings(section(arg)),
"about" => nav.invoke_open_about(),
"share" => {
nav.invoke_open_share();
// The sample share of the test pattern, live at once.
if arg == "live" && switches.demo_ui {
with_app(|app| app.demo_share());
}
}
// The current server's dialog, Advanced open.
"bookmark" if arg == "edit" => {
if let Some(id) = with_app(|app| app.state.current).flatten() {
nav.invoke_edit_server(id as i32);
}
}
// `join`: the same dialog (Join a server was one of its own).
"bookmark" | "join" => nav.invoke_add_server(),
"emoji" => nav.set_emoji_open(true),
"panel" => nav.set_right_panel_open(true),
"no-panel" => nav.set_right_panel_open(false),
"tab" => nav.set_mobile_tab(mobile_tab(arg)),
"voice" => {
nav.invoke_show_voice(true);
// The smaller stage, for this run only.
if arg == "compact" {
nav.set_voice_compact(true);
}
}
"pins" => nav.invoke_show_pins(true),
// Opened once laid out (below).
"more" => {}
// The phone's members page.
"members" => nav.set_members_open(true),
// What Android hands over: a tapped voice notification, text
// shared to the app.
"notification" => crate::inbox::request(crate::inbox::Request::ShowVoice),
"shared" => crate::inbox::request(crate::inbox::Request::Share {
text: Some(arg.to_owned()),
files: Vec::new(),
}),
"topics" => nav.invoke_show_topics(true),
"topic" => {
with_app(|app| {
app.open_topic(arg.parse().unwrap_or(1));
// No gateway answers in demo mode.
if switches.demo_ui {
app.handle_event(logic::topic_history(now_ms()));
}
});
}
"member" => {
with_app(|app| app.open_first_member());
}
// After `friends` the contact path (Kairo without a contact
// chosen), else the member card's.
"poke" => {
let friends = nav.get_page() == Page::Friends;
with_app(|app| {
if friends {
let uid = app.social.selected.clone().unwrap_or_else(|| "demo-3".into());
app.contact_action(&uid, "poke");
} else {
app.open_first_member();
app.member_action("poke");
}
});
}
"channel-password" => {
with_app(|app| open_channel_password(app, arg == "wrong"));
}
// A screenshot cannot hover.
"actions" => nav.set_show_actions(true),
// Home as before the first server, over the sample data.
"first-run" => nav.set_first_run(true),
// `end`: further back, so the divider is above the view.
"unread" => {
with_app(|app| open_unread(app, if arg == "end" { 10 } else { 5 }));
}
"link-confirm" => {
let url = if arg.is_empty() { logic::DEMO_RAID_BOARD } else { arg };
with_app(|app| app.open_link_text(url, true));
}
// As a link from the platform comes.
"link" => crate::inbox::request(crate::inbox::Request::OpenLink(arg.to_owned())),
"watch" | "popout" => {
with_app(|app| {
if switches.demo_ui {
app.demo_watch();
} else {
app.watch_first_stream();
}
if what == "popout" {
app.viewer_pop_out();
}
});
}
"theatre" => nav.set_theatre(true),
// Home, friends, messages, events, the bell, the search.
"friends" => {
with_app(|app| app.select_contact(arg.to_owned()));
nav.invoke_show(Page::Friends);
}
"messages" | "dm" => {
let uid = if arg.is_empty() { "demo-3" } else { arg };
with_app(|app| app.open_dm_with(Some(logic::DEMO), uid));
nav.invoke_show(Page::Messages);
}
"inbox" => {
nav.set_dm_tab(2);
with_app(|app| app.dm_tab(2));
nav.invoke_show(Page::Messages);
}
"library" => nav.invoke_show(Page::Library),
"events" => nav.invoke_show(Page::Events),
"event-form" => nav.invoke_create_event(),
"search" => nav.invoke_open_search(arg.into()),
"notifications" => nav.set_notifications_open(true),
"offline" => nav.invoke_write_offline("demo-ari".into(), "Ari".into()),
"picture" => {
let picture = logic::demo_picture(1280, 720, 16);
let image = crate::images::picture("demo:lightbox", &picture);
nav.set_lightbox(image);
nav.set_lightbox_open(true);
}
// The camera preview of the settings (the test pattern).
"camera" => {
with_app(|app| {
app.start_camera();
app.refresh_pages();
});
}
"studio" => {
if arg != "window" {
nav.invoke_open_studio();
}
with_app(|app| app.studio_dev(arg));
}
// Opened once connected (settings_page/bind.rs).
"client" => {}
other => eprintln!("VOELIN_OPEN: unknown screen {other:?}"),
}
}
// A window manager can refuse the size set before the window opened,
// so ask again once it is up. (Under `xvfb-run` in a Wayland session,
// remove WAYLAND_DISPLAY, or winit opens the window on the desktop.)
let resize = switches.window_size.map(|(w, h)| {
let weak = ui.as_weak();
let timer = slint::Timer::default();
timer.start(
slint::TimerMode::SingleShot,
Duration::from_millis(switches.screenshot_delay * 1000 / 2),
move || {
if let Some(ui) = weak.upgrade() {
ui.window().set_size(slint::LogicalSize::new(w, h));
}
},
);
timer
});
// `unread`: up to the divider once the list is laid out (after the
// resize above).
let scroll = switches.open.iter().any(|o| o == "unread").then(|| {
late(ui, switches, |ui| {
let bridge = ui.global::<Bridge>();
bridge.set_jump_index(bridge.get_unread_index());
bridge.set_jump_requests(bridge.get_jump_requests().wrapping_add(1));
})
});
// `more`: the phone voice screen's More menu (a screenshot cannot tap).
let more = switches.open.iter().any(|o| o == "more").then(|| {
late(ui, switches, |ui| {
let nav = ui.global::<Nav>();
nav.set_more_requests(nav.get_more_requests().wrapping_add(1));
})
});
let screenshot = switches.screenshot.clone().map(|path| {
let weak = ui.as_weak();
let timer = slint::Timer::default();
timer.start(
slint::TimerMode::SingleShot,
Duration::from_secs(switches.screenshot_delay),
move || {
if let Some(ui) = weak.upgrade() {
if let Err(e) = save_screenshot(&ui, &path) {
eprintln!("screenshot failed: {e}");
}
let _ = ui.hide();
// Also when the studio's or the stream's own window is
// open.
let _ = slint::quit_event_loop();
}
},
);
timer
});
Running { _screenshot: screenshot, _resize: resize, _scroll: scroll, _more: more }
}
/// A timer that runs `action` at three quarters of the screenshot delay, once
/// the window has its size and the screens are laid out.
fn late(
ui: &MainWindow,
switches: &Switches,
action: impl Fn(&MainWindow) + 'static,
) -> slint::Timer {
let weak = ui.as_weak();
let timer = slint::Timer::default();
timer.start(
slint::TimerMode::SingleShot,
Duration::from_millis(switches.screenshot_delay * 1000 * 3 / 4),
move || {
if let Some(ui) = weak.upgrade() {
action(&ui);
}
},
);
timer
}
fn save_screenshot(ui: &MainWindow, path: &std::path::Path) -> Result<()> {
let mut image = ui.window().take_snapshot()?;
let window = with_app(|app| app.studio_snapshot().or_else(|| app.viewer_snapshot())).flatten();
if let Some(window) = window {
let stem = path.file_stem().unwrap_or_default().to_string_lossy();
save_png(&window, &path.with_file_name(format!("{stem}-window.png")))?;
paste(&mut image, &window);
}
save_png(&image, path)
}
/// Draw `top` over the bottom right of `image` with a border, as a second
/// window sits on a desktop.
fn paste(image: &mut SharedPixelBuffer<Rgba8Pixel>, top: &SharedPixelBuffer<Rgba8Pixel>) {
let (w, h) = (image.width() as usize, image.height() as usize);
let (tw, th) = (top.width() as usize, top.height() as usize);
let (x0, y0) = (w.saturating_sub(tw + 24), h.saturating_sub(th + 24));
let border = Rgba8Pixel { r: 0x3f, g: 0x7b, b: 0xff, a: 0xff };
let pixels = image.make_mut_slice();
for y in y0.saturating_sub(1)..(y0 + th + 1).min(h) {
for x in x0.saturating_sub(1)..(x0 + tw + 1).min(w) {
let (ty, tx) = (y.wrapping_sub(y0), x.wrapping_sub(x0));
pixels[y * w + x] =
if ty < th && tx < tw { top.as_slice()[ty * tw + tx] } else { border };
}
}
}
fn save_png(image: &SharedPixelBuffer<Rgba8Pixel>, path: &std::path::Path) -> Result<()> {
let file = std::io::BufWriter::new(std::fs::File::create(path)?);
let mut encoder = png::Encoder::new(file, image.width(), image.height());
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
encoder.write_header()?.write_image_data(image.as_bytes())?;
Ok(())
}
/// The current chat's read marker `back` messages before its end
/// ([`logic::unread_from`]), its "New" divider shown (`VOELIN_OPEN=unread`).
fn open_unread(app: &mut App, back: usize) {
if logic::unread_from(&mut app.state, back) {
app.refresh_chat();
app.refresh_servers();
}
}
/// `VOELIN_OPEN=channel-password`: join the current server's first locked
/// channel, which asks for its password; `wrong` as if the server had
/// refused one.
fn open_channel_password(app: &mut App, wrong: bool) {
let Some((session, channel)) = logic::first_locked_channel(&app.state) else { return };
if wrong {
if let Some(view) = app.view_mut() {
view.channel_passwords.insert(channel, "guess".into());
}
app.join_failed(session, channel, JoinFailure::Password);
} else {
app.join_channel(session, channel);
}
}
/// Sample data through the same events a server would send.
fn demo_ui(app: &mut App) {
app.state.bookmarks = logic::bookmarks();
app.state.settings.last_voice = Some(logic::last_voice());
app.state.current = Some(DEMO);
for event in logic::server_events() {
app.handle_event(event);
}
demo_pictures(app);
for event in logic::chat_events(now_ms()) {
app.handle_event(event);
}
demo_social(app);
// No toast over the screenshots.
app.set_status("");
app.refresh_all();
}
/// Avatars, icons, banners and badges as the engine reports them once they
/// are in its cache (here a folder of synthetic pictures in the temporary
/// directory).
fn demo_pictures(app: &mut App) {
let dir = std::env::temp_dir().join("voelin-demo-pictures");
let _ = std::fs::create_dir_all(&dir);
let address = app.bookmark(DEMO).map(|b| b.address.clone()).unwrap_or_default();
let events = logic::pictures(&address, |name, png| {
let path = dir.join(name);
let _ = std::fs::write(&path, png);
path
});
for event in events {
app.handle_event(event);
}
}
/// Sample people, private chats, pokes, notifications, events, a picture
/// and recordings for the home, friends, messages, events and settings
/// screens (`VOELIN_DEMO_UI`).
fn demo_social(app: &mut App) {
let now = now_ms();
// The second sample server is observed: a few people there.
for event in logic::lounge_events() {
app.handle_event(event);
}
app.handle_event(Event::ContactsChanged { contacts: Arc::new(logic::contacts(now)) });
for (uid, since) in logic::online_since(now) {
app.social.online_since.insert(uid.into(), since);
}
for event in logic::private_chat_events(now) {
app.handle_event(event);
}
let (server_uid, chat, bookmark) = logic::stored_chat(now);
app.social.dm.stored.push((server_uid.into(), chat));
app.social.dm.bookmark_of.insert(server_uid.into(), bookmark);
logic::read_samples(&mut app.state);
let (poke, ts_ms) = logic::poke(now);
app.handle_event(poke);
if let Some(p) = app.social.pokes.last_mut() {
p.ts_ms = ts_ms;
}
app.handle_event(logic::offline_messages(now));
logic::link_previews(&mut app.state);
for event in logic::gateway_events(now) {
app.handle_event(event);
}
for n in logic::notices() {
app.notify(n.kind, n.title, n.body, n.target, n.name, n.uid);
}
logic::age_notices(&mut app.social, now);
app.refresh_notices();
app.models.social.recordings.sync(&logic::recordings());
app.refresh_chats();
app.refresh_people();
app.refresh_home();
}
/// Answer [`App::load_older`] in demo mode (no engine runs) with
/// [`logic::demo_older`], a moment later as a server would.
pub(crate) fn answer_older(session: i64, target: ChatTarget, oldest: Option<HistoryMessage>) {
slint::Timer::single_shot(Duration::from_millis(600), move || {
let now = now_ms();
let (messages, complete) = logic::demo_older(&target, oldest.as_ref(), now);
with_app(|app| {
app.handle_event(Event::ChatHistory {
session: session as u64,
target,
messages,
source: HistorySource::Gateway,
complete,
});
});
});
}
+67
View File
@@ -0,0 +1,67 @@
//! Development switches (environment variables), for trying screens and
//! taking screenshots without a server:
//!
//! - `VOELIN_DATA_DIR=<dir>`: the database (app.rs).
//! - `VOELIN_AUTOCONNECT=voice|observe`: connect the first bookmark on start.
//! - `VOELIN_SCREENSHOT=<png>`: save the window after
//! `VOELIN_SCREENSHOT_DELAY` seconds (default 4) and exit.
//! - `VOELIN_WINDOW_SIZE=<w>x<h>`: 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=<what>[,<what>...]`: open screens on start: `home`,
//! `server` (`server:chat`: its server chat), `settings[:<section>]`
//! (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>` (text shared to the app on Android),
//! `pins`, `topics` (the drawers),
//! `topic:<id>` (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[:<url>]` (the question before a masked link opens, by
//! default the sample's raid board), `link:<url>` (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:<home|servers|chat|activity|you>` (phone layout); `friends[:<uid>]`,
//! `messages[:<uid>]` (a private chat), `inbox` (offline messages),
//! `library`, `events`, `event-form`, `search[:<text>]`,
//! `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[:<what>]`: 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
//! (`<name>-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.
mod bind;
pub(crate) use bind::{Switches, answer_older, start};
+3 -99
View File
@@ -1,16 +1,16 @@
//! What a server's gateway tells besides chat: its events (the events
//! page, RSVP, reminders), the stream directory and the activity feed (the
//! home page), our permissions there, its configuration (gateway
//! administration). The pins, reactions and topics are in `chat.rs`.
//! administration). The pins, reactions and topics are in `chat/`.
use std::sync::Arc;
use slint::{ComponentHandle, SharedString};
use voelin_core::{Command, GatewayRequest, GatewayUpdate};
use voelin_core::{Command, GatewayRequest};
use voelin_gateway_proto::{Action, EventKind, EventQuery, EventSpec, RsvpStatus, feature};
use crate::app::{App, Bridge};
use crate::social::{NoticeKind, NoticeTarget, now_ms};
use crate::social::now_ms;
use crate::vm;
use crate::vm::bridge::{EventForm, EventItem};
use crate::vm::social::{date_block, event_when, format_local, parse_local, soon};
@@ -23,102 +23,6 @@ impl App {
}
}
/// Keep what a gateway update tells these screens (before the chat
/// handles its part).
pub(crate) fn gateway_extra(&mut self, id: i64, update: &GatewayUpdate) {
use GatewayUpdate as U;
let mut ask: Vec<GatewayRequest> = Vec::new();
let mut remind = None;
let extra = &mut self.state.sessions.entry(id).or_default().extra;
match update {
U::Connected { uid, capabilities, .. } => {
extra.gateway_uid = Some(uid.clone());
let has = |f: &str| capabilities.iter().any(|c| c == f);
ask.push(GatewayRequest::Permissions { channel: None });
if has(feature::EVENTS) {
ask.push(GatewayRequest::Events { query: EventQuery::default() });
}
if has(feature::STREAMS) {
ask.push(GatewayRequest::Streams);
}
if has(feature::ACTIVITY) {
ask.push(GatewayRequest::Activity { before: None, limit: Some(30) });
}
}
U::Disconnected { .. } => {
extra.directory.clear();
extra.events.clear();
extra.events_loaded = false;
extra.activity.clear();
extra.actions.clear();
extra.config.clear();
extra.perms.clear();
}
U::Permissions { channel: None, actions } => extra.actions = actions.clone(),
U::Events { events } => {
extra.events = events.clone();
extra.events.sort_by_key(|e| e.spec.start_ms);
extra.events_loaded = true;
}
U::Event { event } => {
match extra.events.iter().position(|e| e.id == event.id) {
Some(i) => extra.events[i] = event.clone(),
None => extra.events.push(event.clone()),
}
extra.events.sort_by_key(|e| e.spec.start_ms);
}
U::EventDeleted { id: event } => extra.events.retain(|e| e.id != *event),
U::EventReminder { event, starts_in_ms } => {
remind = Some((event.clone(), *starts_in_ms))
}
U::Streams { streams } => extra.directory = streams.clone(),
U::StreamStarted { stream }
| U::StreamUpdated { stream }
| U::StreamRegistered { stream } => {
extra.directory.retain(|e| e.id != stream.id);
extra.directory.push(stream.clone());
}
U::StreamEnded { id: stream, .. } => extra.directory.retain(|e| e.id != *stream),
U::Activity { entries, .. } => extra.activity = entries.clone(),
U::ActivityAdded { entry } => {
extra.activity.insert(0, entry.clone());
extra.activity.truncate(100);
}
U::Config { entries } => extra.config = entries.clone(),
U::ConfigValue { entry } => {
match extra.config.iter().position(|e| e.key == entry.key) {
Some(i) => extra.config[i] = entry.clone(),
None => extra.config.push(entry.clone()),
}
}
U::PermRules { rules } => extra.perms = rules.clone(),
_ => return,
}
for request in ask {
self.gateway_to(id, request);
}
if let Some((event, starts_in_ms)) = remind {
let minutes = starts_in_ms / 60_000;
let title = if minutes <= 0 {
format!("{} starts now", event.spec.title)
} else {
format!("{} starts in {minutes} min", event.spec.title)
};
let body = format!("on {}", self.server_name(id));
self.notify(
NoticeKind::Event,
title,
body,
NoticeTarget::Event(id, event.id),
event.creator.name.clone(),
Some(event.creator.uid.clone()),
);
}
self.refresh_home();
self.refresh_events();
self.refresh_gateways();
}
/// The events page of the current server was opened.
pub(crate) fn open_events(&mut self) {
let Some(id) = self.state.current else { return };
+1 -23
View File
@@ -1,7 +1,7 @@
//! The home page (design mockup 01): where we were with voice last, live
//! streams on our servers, what is happening there (events, scheduled
//! streams, server news), and the Library of recordings and clips.
//! Friends and the unread mentions are in `social.rs`, the recent chats in
//! Friends and the unread mentions are in `social/`, the recent chats in
//! `messages.rs`.
use std::path::{Path, PathBuf};
@@ -10,7 +10,6 @@ use slint::ComponentHandle;
use voelin_core::VoiceState;
use crate::app::{App, Bridge, Page};
use crate::settings::LastVoice;
use crate::vm;
use crate::vm::bridge::{HappeningItem, LiveItem, RecordingItem, ResumeItem, ServerItem};
use crate::vm::home::ResumeAction;
@@ -269,27 +268,6 @@ impl App {
}
}
/// Keep where we are with voice in `session` as the last place
/// (`ui.last_voice`); whether it changed. Not for the sample sessions.
pub(crate) fn remember_voice(&mut self, session: i64) -> bool {
if self.demo_ui {
return false;
}
let Some(view) = self.state.sessions.get(&session) else { return false };
let (VoiceState::Connected, Some(cid)) = (view.state.voice, view.state.own_channel) else {
return false;
};
let channel = vm::tree::channel_path(&view.presence, cid);
let Some(b) = self.bookmark(session).filter(|_| !channel.is_empty()) else { return false };
let last = LastVoice { bookmark: session, address: b.address.clone(), channel };
if self.state.settings.last_voice.as_ref() == Some(&last) {
return false;
}
self.state.settings.last_voice = Some(last);
self.store_settings();
true
}
/// The folder of recordings and clips.
fn recordings_dir(&self) -> PathBuf {
voelin_core::studio::recording_dir(&self.prefs)
+335
View File
@@ -0,0 +1,335 @@
//! The Slint side of the transitions of `voelin-ui-vm`: what they ask of
//! the front end while they run ([`SlintHost`]) and doing what their
//! [`Update`] says ([`App::perform`]). The state changes are in the view
//! model crate; this is where the engine, the store and the window are
//! touched for them.
use slint::ComponentHandle;
use tracing::{debug, warn};
use voelin_core::Event;
use voelin_core::settings::{AUDIO, CACHE_FETCH_IMAGES, Settings};
use voelin_store::{ChatRead, ChatTarget as StoredTarget, Store};
use crate::app::{App, AppState, Bridge, MainWindow, Nav, Page};
use crate::settings::{CLIENT_PLAYBACK, UI_IMAGE_PREVIEW_KB};
use crate::social::Social;
use crate::studio::StudioState;
use crate::vm::host::{Cx, Host, PasswordPrompt, Persist, Refresh, Update};
/// What the transitions ask while they run: the window, the store and the
/// settings, borrowed from the app besides its state.
pub(crate) struct SlintHost<'a> {
pub demo_ui: bool,
pub watching: bool,
/// The private chat the messages page has open: session and peer.
pub dm: Option<(i64, String)>,
pub ui: &'a slint::Weak<MainWindow>,
pub store: &'a Store,
pub prefs: &'a Settings,
pub studio: &'a StudioState,
}
impl Host for SlintHost<'_> {
fn demo_ui(&self) -> bool {
self.demo_ui
}
fn chat_shown(&self) -> bool {
self.ui.upgrade().is_some_and(|ui| ui.global::<Nav>().get_chat_shown())
}
fn watching(&self) -> bool {
self.watching
}
fn autowatch(&self) -> bool {
std::env::var("VOELIN_AUTOWATCH").is_ok_and(|v| v == "1")
}
fn studio_streams_to(&self, session: i64) -> bool {
self.studio.streams_to(session)
}
fn preview_limit(&self) -> u64 {
u64::from(self.prefs.get(&UI_IMAGE_PREVIEW_KB)) * 1024
}
fn fetch_images(&self) -> bool {
self.prefs.get(&CACHE_FETCH_IMAGES)
}
fn dm_shown(&self, session: i64, uid: &str) -> bool {
self.dm.as_ref().is_some_and(|(s, u)| *s == session && u == uid)
&& self.ui.upgrade().is_some_and(|ui| ui.global::<Nav>().get_page() == Page::Messages)
}
fn chat_reads(&self, server_uid: &str) -> Result<Vec<(StoredTarget, ChatRead)>, String> {
self.store.chat_reads(server_uid).map_err(|e| e.to_string())
}
fn set_chat_read(
&self,
server_uid: &str,
target: &StoredTarget,
read: &ChatRead,
) -> Result<(), String> {
self.store.set_chat_read(server_uid, target, read).map_err(|e| e.to_string())
}
}
impl App {
/// Run `f` with the state and the host, and return what it returns.
pub(crate) fn with_host<R>(&mut self, f: impl FnOnce(&mut AppState, &SlintHost<'_>) -> R) -> R {
self.with_social(|state, _, host| f(state, host))
}
/// Run `f` with the state, the social state and the host.
pub(crate) fn with_social<R>(
&mut self,
f: impl FnOnce(&mut AppState, &mut Social, &SlintHost<'_>) -> R,
) -> R {
let host = SlintHost {
demo_ui: self.demo_ui,
watching: self.state.watch.is_some(),
dm: self.social.dm.open.as_ref().and_then(|open| {
open.session.filter(|_| open.mail.is_none()).map(|s| (s, open.uid.clone()))
}),
ui: &self.ui,
store: &self.store,
prefs: &self.prefs,
studio: &self.studio,
};
f(&mut self.state, &mut self.social, &host)
}
/// An engine event: what it does to the state is in `voelin-ui-vm`
/// ([`crate::vm::events::handle`]), then the update is carried out.
pub(crate) fn handle_event(&mut self, event: Event) {
let update = self.with_social(|state, social, host| {
crate::vm::events::handle(state, social, host, event)
});
self.perform(update);
}
/// Run a transition of the view model on the state, and carry out what
/// it says.
pub(crate) fn transition<R>(&mut self, f: impl FnOnce(&mut AppState, &mut Cx<'_>) -> R) -> R {
let (result, update) = self.with_host(|state, host| {
let mut cx = Cx::new(host);
let result = f(state, &mut cx);
(result, cx.update)
});
self.perform(update);
result
}
/// Like [`App::transition`], for a transition that changes the social
/// state too.
pub(crate) fn social_transition<R>(
&mut self,
f: impl FnOnce(&mut AppState, &mut Social, &mut Cx<'_>) -> R,
) -> R {
let (result, update) = self.with_social(|state, social, host| {
let mut cx = Cx::new(host);
let result = f(state, social, &mut cx);
(result, cx.update)
});
self.perform(update);
result
}
/// Do what a transition asked for: tell the engine, keep what is to be
/// kept, draw what changed, and hand the rest back to the code that
/// still owns it.
pub(crate) fn perform(&mut self, update: Update) {
let Update {
refresh,
status,
commands,
persist,
reloaded,
input_level,
password,
notices,
warnings,
chats,
watch,
stream,
autoshare,
first_client,
rest,
} = update;
for text in warnings {
warn!("{text}");
}
// What the engine wrote again is decoded again, when it is drawn.
for path in &reloaded {
crate::images::reloaded(path);
}
for command in commands {
self.engine.send(command);
}
// The capture and the decoder.
if let Some(sink) = stream.attach
&& let Some(share) = &self.share
{
share.capture.attach(sink);
}
if stream.drop_share {
self.share = None;
}
if stream.drop_decoder {
self.decoder = None;
}
if stream.leave_fullscreen {
self.set_fullscreen(false);
}
if stream.mixer {
self.mixer_refresh();
}
if let Some(text) = status {
self.set_status(text);
}
for what in persist {
self.keep(what);
}
if let Some((level_db, sending)) = input_level
&& let Some(ui) = self.ui.upgrade()
{
let bridge = ui.global::<Bridge>();
bridge.set_input_level(level_db);
bridge.set_input_sending(sending);
}
if let Some(PasswordPrompt { name, wrong }) = password
&& let Some(ui) = self.ui.upgrade()
{
let nav = ui.global::<Nav>();
nav.set_channel_password_name(name.into());
nav.set_channel_password_error(wrong);
nav.set_channel_password_open(true);
}
for notice in notices {
self.notify(
notice.kind,
notice.title,
notice.body,
notice.target,
notice.name,
notice.uid,
);
}
// What the front end keeps itself comes before the drawing: what
// it changes is on screen then.
if let Some(event) = rest {
self.event_rest(event);
}
self.refresh_parts(refresh);
for (id, target) in chats {
self.studio_chat_changed(id, &target);
}
if let Some(stream) = watch {
self.watch_stream(stream);
}
if autoshare {
self.autoshare();
}
if first_client && self.open_client_pending {
self.open_first_client();
}
}
/// Keep what a transition changed.
fn keep(&mut self, what: Persist) {
match what {
Persist::Bookmark { id, what } => {
let Some(bookmark) = self.state.bookmarks.iter().find(|b| b.id == id) else {
return;
};
match self.store.update_bookmark(bookmark) {
Ok(()) => debug!(server = %bookmark.address, "{what}"),
Err(e) => warn!(%e, "could not keep the bookmark: {what}"),
}
}
Persist::Settings => self.store_settings(),
Persist::Audio => {
if let Err(e) = self.prefs.set(&AUDIO, self.state.audio.clone()) {
warn!(%e, "could not store audio settings");
}
}
Persist::Playback => {
if let Err(e) = self.prefs.set(&CLIENT_PLAYBACK, self.state.playback.clone()) {
warn!(%e, "could not store client volumes");
}
}
}
}
/// Draw the parts of the window a transition changed.
pub(crate) fn refresh_parts(&mut self, parts: Refresh) {
if parts.servers {
self.refresh_servers();
}
if parts.toolbar {
self.refresh_toolbar();
}
if parts.tree {
self.refresh_tree();
}
if parts.chat {
self.refresh_chat();
}
if parts.streams {
self.refresh_streams();
}
if parts.viewer {
self.refresh_viewer();
}
if parts.member_card {
self.refresh_member_card();
}
if parts.people {
self.refresh_people();
}
if parts.conversations {
self.ask_inboxes();
self.refresh_chats();
}
if parts.home {
self.refresh_home();
}
if parts.dm {
self.refresh_dm();
}
if parts.events {
self.refresh_events();
}
if parts.gateways {
self.refresh_gateways();
}
}
/// The events whose state the view model does not hold: a setting that
/// changed, the studio's stream and the requests of the messages page.
/// [`App::perform`] runs this before it draws, so that what these change
/// is what is drawn.
fn event_rest(&mut self, event: Event) {
match event {
Event::SettingChanged { key } => self.setting_changed(&key),
// The Stream Studio's stream (studio/).
Event::StreamState { session, state } if self.studio_streams_to(session as i64) => {
self.studio_stream_state(state);
}
Event::StreamViewers { session, viewers } if self.studio_streams_to(session as i64) => {
self.studio_viewers(viewers);
}
// The messages page keeps the offline message requests
// (messages.rs); the text of a message is the view model's
// (`social::logic::event`).
Event::OfflineMessages { result: Err(e), .. } => debug!("offline messages: {e}"),
Event::RequestDone { session, request, result } => {
self.request_done(session as i64, request, result);
}
_ => {}
}
}
}
+1
View File
@@ -8,6 +8,7 @@ mod chat;
mod dev;
mod events;
mod home;
mod host;
mod hotkey;
mod identities;
mod images;
+7 -89
View File
@@ -17,11 +17,11 @@ use std::collections::HashMap;
use std::sync::Arc;
use slint::ComponentHandle;
use voelin_core::{Command, HistoryMessage, OfflineMessage, OfflineMessageInfo, VoiceState};
use voelin_core::{Command, HistoryMessage, OfflineMessageInfo, VoiceState};
use voelin_model::ChatTarget;
use voelin_store::PageQuery;
use crate::app::{App, Bridge, Nav, Page, SessionView, later};
use crate::app::{App, Bridge, Page, SessionView, later};
use crate::vm;
use crate::vm::bridge::{ConversationItem, DmPeer, FileItem, OfflineForm};
use crate::vm::social::{ChatRef, ago, list_time, matches, plain, preview};
@@ -55,8 +55,6 @@ pub(crate) struct Dms {
pub tab: i32,
pub filter: String,
pub open: Option<Open>,
/// The text of the open offline message.
pub mail: Option<OfflineMessage>,
/// Offline message requests in flight: session and what for.
pub requests: HashMap<u64, (i64, &'static str)>,
pub next_request: u64,
@@ -106,24 +104,7 @@ impl App {
/// What we call the peer of a private chat.
pub(crate) fn peer_name(&self, uid: &str, last: Option<&HistoryMessage>) -> String {
if let Some(c) = self.state.contacts.get(uid).filter(|c| !c.nickname.is_empty()) {
return c.nickname.clone();
}
if let Some(s) = self.spots_of(uid).first() {
return self.state.sessions[&s.session].nickname(s.client);
}
let from_peer = |m: &HistoryMessage| {
(m.message.author_uid.as_deref() == Some(uid)).then(|| m.message.author_name.clone())
};
last.and_then(from_peer)
.or_else(|| {
self.state.sessions.values().flat_map(|v| &v.tabs).find_map(|t| {
(t.target == ChatTarget::Private(uid.to_owned()))
.then(|| t.messages.iter().rev().find_map(|m| from_peer(&m.message)))
.flatten()
})
})
.unwrap_or_else(|| uid.chars().take(8).collect())
vm::social::peer_name(&self.state, uid, last)
}
/// Every chat, newest first; then the lists that show them.
@@ -220,11 +201,7 @@ impl App {
ago: ago(ts).into(),
unread: chat.unread,
initials: vm::avatar::initials(&title).into(),
// A server's chat in the server's colour.
tint: match (kind, session) {
(0, Some(s)) => self.server_tint(s),
_ => vm::avatar::tint(&title),
},
tint: vm::servers::logic::conversation_tint(&self.state, kind, session, &title),
avatar,
online,
selected: open.is_some_and(|o| {
@@ -454,7 +431,7 @@ impl App {
mail: None,
stored: !live,
});
self.social.dm.mail = None;
self.social.mail = None;
self.models.social.dm_lines.sync(&[]);
let target = ChatTarget::Private(uid.to_owned());
if let (true, Some(id)) = (live, session) {
@@ -501,18 +478,6 @@ impl App {
self.refresh_dm();
}
/// Whether the private chat with `uid` in `session` is on screen.
pub(crate) fn dm_shown(&self, session: i64, uid: &str) -> bool {
let page = self.ui.upgrade().map(|ui| ui.global::<Nav>().get_page());
page == Some(Page::Messages)
&& self
.social
.dm
.open
.as_ref()
.is_some_and(|o| o.mail.is_none() && o.uid == uid && o.session == Some(session))
}
/// Who the open conversation is with, and what can be done.
pub(crate) fn refresh_dm(&self) {
let Some(ui) = self.ui.upgrade() else { return };
@@ -584,7 +549,7 @@ impl App {
for m in tab.iter().flat_map(|t| t.messages.iter().rev()) {
let message = &m.message.message;
for f in message.file_refs() {
if let Some(image) = view.and_then(|v| crate::previews::image_of(v, &f)) {
if let Some(image) = view.and_then(|v| vm::previews::image_of(v, &f)) {
media.push(image);
continue;
}
@@ -672,7 +637,6 @@ impl App {
mail_subject: mail.as_ref().map(|m| m.subject.clone()).unwrap_or_default().into(),
mail_text: self
.social
.dm
.mail
.as_ref()
.map(|m| plain(&m.text))
@@ -790,7 +754,7 @@ impl App {
mail: Some((session, m.id)),
stored: false,
});
self.social.dm.mail = None;
self.social.mail = None;
let request = self.offline_request(session, "get");
if !self.demo_ui {
self.engine.send(Command::GetOfflineMessage {
@@ -802,20 +766,6 @@ impl App {
self.refresh_chats();
}
pub(crate) fn mail_arrived(&mut self, session: i64, result: Result<OfflineMessage, String>) {
match result {
Ok(m) => {
if let Some(view) = self.state.sessions.get_mut(&session)
&& let Some(info) = view.extra.inbox.iter_mut().find(|i| i.id == m.id)
{
info.read = true;
}
self.social.dm.mail = Some(m);
}
Err(e) => self.set_status(format!("Could not read the offline message: {e}")),
}
}
pub(crate) fn request_done(&mut self, session: i64, request: u64, result: Result<(), String>) {
let Some((_, what)) = self.social.dm.requests.remove(&request) else { return };
match (what, result) {
@@ -855,36 +805,4 @@ impl App {
self.engine.send(Command::ListOfflineMessages { session: id as u64, request });
}
}
/// Pokes from `uid` as lines of their private chat, among its messages
/// (`lines` and `times` in step, oldest first).
pub(crate) fn poke_lines(&self, session: i64, uid: &str) -> Vec<(i64, vm::bridge::ChatLine)> {
self.social
.pokes
.iter()
.enumerate()
.filter(|(_, p)| p.session == session && p.uid.as_deref() == Some(uid))
.map(|(i, p)| {
let text = if p.message.is_empty() {
"👋 poked you".to_owned()
} else {
format!("👋 poked you: {}", p.message)
};
let message = voelin_model::ChatMessage {
target: ChatTarget::Private(uid.to_owned()),
author_name: p.name.clone(),
author_uid: p.uid.clone(),
author_id: None,
text,
ts_ms: p.ts_ms,
via_relay: false,
blocked: false,
};
let mut line = vm::chat::line(&message, None);
line.key = -1_000_000 - i as i32;
line.avatar = self.avatar_of(uid);
(p.ts_ms, line)
})
.collect()
}
}
+5 -3
View File
@@ -42,7 +42,8 @@ impl App {
/// The player into a window of its own.
pub(crate) fn viewer_pop_out(&mut self) {
// One window on Android.
if cfg!(target_os = "android") || self.popout.window.is_some() || self.watch.is_none() {
if cfg!(target_os = "android") || self.popout.window.is_some() || self.state.watch.is_none()
{
return;
}
// The main window's full screen was the player's.
@@ -86,7 +87,7 @@ impl App {
/// The player back into the main window, on the stream's server page.
pub(crate) fn viewer_dock(&mut self) {
let Some(window) = self.close_popout() else { return };
if let Some(watch) = &mut self.watch {
if let Some(watch) = &mut self.state.watch {
watch.shown = true;
}
if let Some(ui) = self.ui.upgrade() {
@@ -95,6 +96,7 @@ impl App {
// The main window may have gone to another server meanwhile: else
// the stream would play on, unseen.
let session = self
.state
.watch
.as_ref()
.and_then(|w| w.session)
@@ -127,7 +129,7 @@ impl App {
self.with_player(|_, window| crate::streams::show_cursor(window, shown));
}
/// A picture of the viewer's window (screenshots, dev.rs).
/// A picture of the viewer's window (screenshots, dev/).
pub(crate) fn viewer_snapshot(&self) -> Option<SharedPixelBuffer<Rgba8Pixel>> {
self.popout.window.as_ref()?.window().take_snapshot().ok()
}
+7 -167
View File
@@ -9,162 +9,16 @@
//! message shows its address.
use std::borrow::Cow;
use std::sync::Arc;
use voelin_core::settings::CACHE_FETCH_IMAGES;
use voelin_core::{Command, DownloadTo, TransferState, VoiceState};
use voelin_model::{ChatTarget, FileRef};
use crate::app::{App, SessionView};
use crate::app::App;
use crate::bind::convert;
use crate::settings::UI_IMAGE_PREVIEW_KB;
use crate::vm;
use crate::vm::state::Preview;
use crate::vm::{ImageRef, ImageSource};
/// Whether a file name is a picture the chat shows inline.
pub(crate) fn is_previewable(name: &str) -> bool {
let lower = name.to_ascii_lowercase();
[".png", ".jpg", ".jpeg", ".gif", ".webp"].iter().any(|e| lower.ends_with(e))
}
/// The key of a link: where the file is.
pub(crate) fn link_key(file: &FileRef) -> String {
format!(
"{}/{}{}{}",
file.server_uid.as_deref().unwrap_or(""),
file.channel,
file.path,
file.name
)
}
/// The decoded picture of a link, if it is there (decoded once, kept by
/// the image cache).
pub(crate) fn image_of(view: &SessionView, file: &FileRef) -> Option<ImageRef> {
let key = link_key(file);
match view.extra.previews.get(&key)? {
Preview::Ready(bytes) => {
let image = Arc::new(ImageSource::Memory { key: key.into(), bytes: bytes.0.clone() });
(!image.is_empty()).then_some(image)
}
_ => None,
}
}
impl App {
/// Download the pictures linked in the current chat of `session` that
/// are not there yet.
/// are not there yet ([`vm::previews::fetch_previews`]).
pub(crate) fn fetch_previews(&mut self, session: i64) {
if self.demo_ui {
return;
}
let limit = u64::from(self.prefs.get(&UI_IMAGE_PREVIEW_KB)) * 1024;
if limit == 0 {
return;
}
self.fetch_web_pictures(session, limit);
let Some(view) = self.state.sessions.get_mut(&session) else { return };
if view.state.voice != VoiceState::Connected || !view.capabilities.file_transfer {
return;
}
let Some(tab) = view.tabs.get(view.current_tab) else { return };
// Channel chats only: a link names its channel's file browser.
if matches!(tab.target, ChatTarget::Private(_)) && tab.messages.is_empty() {
return;
}
let wanted: Vec<FileRef> = tab
.messages
.iter()
.rev()
.take(200)
.flat_map(|m| m.message.message.file_refs())
.filter(|f| is_previewable(&f.name) && f.size.is_some_and(|s| s <= limit))
.filter(|f| !view.extra.previews.contains_key(&link_key(f)))
.collect();
for file in wanted {
let transfer = view.next_transfer;
view.next_transfer += 1;
view.extra.previews.insert(link_key(&file), Preview::Loading(transfer));
self.engine.send(Command::DownloadChatFile {
session: session as u64,
transfer,
file,
password: None,
to: DownloadTo::Memory,
});
}
}
/// Ask the engine for the pictures on the web (`[img]`) of the current
/// chat of `session` that it has not reported; it fetches each once.
fn fetch_web_pictures(&self, session: i64, limit: u64) {
if !self.prefs.get(&CACHE_FETCH_IMAGES) {
return;
}
let Some(view) = self.state.sessions.get(&session) else { return };
let Some(tab) = view.tabs.get(view.current_tab) else { return };
// The server chat starts with the server's messages.
let server = match tab.target {
ChatTarget::Server => crate::chat::server_texts(&view.presence.server),
_ => Vec::new(),
};
let wanted: Vec<String> = tab
.messages
.iter()
.rev()
.take(200)
.map(|m| m.message.message.text.as_str())
.chain(server.into_iter().map(|(text, _)| text))
.flat_map(vm::chat::web_pictures)
.filter(|url| !view.pictures.contains_key(url))
.collect();
for url in wanted {
self.engine.send(Command::FetchPicture {
session: session as u64,
url,
max_bytes: limit,
});
}
}
/// A transfer of a picture: `true` if it was one.
pub(crate) fn preview_progress(
&mut self,
session: i64,
transfer: u64,
state: &TransferState,
) -> bool {
let limit = u64::from(self.prefs.get(&UI_IMAGE_PREVIEW_KB)) * 1024;
let Some(view) = self.state.sessions.get_mut(&session) else { return false };
let Some(key) = view
.extra
.previews
.iter()
.find(|(_, p)| matches!(p, Preview::Loading(t) if *t == transfer))
.map(|(k, _)| k.clone())
else {
return false;
};
match state {
TransferState::Started { size, .. } if *size > limit => {
view.extra.previews.insert(key, Preview::Failed);
if !self.demo_ui {
self.engine.send(Command::CancelTransfer { session: session as u64, transfer });
}
}
TransferState::Done { data: Some(data), .. } => {
view.extra.previews.insert(key, Preview::Ready(data.clone()));
if self.state.current == Some(session) {
self.refresh_chat();
}
}
TransferState::Done { .. } | TransferState::Failed(_) | TransferState::Cancelled => {
view.extra.previews.insert(key, Preview::Failed);
}
_ => {}
}
true
self.transition(|state, cx| vm::previews::fetch_previews(state, cx, session));
}
/// The picture of link `index` of a message of the current chat (its
@@ -175,14 +29,16 @@ impl App {
let message = match tab.message(key) {
Some(message) => Cow::Borrowed(&message.message),
// A line of the server.
None => match crate::chat::server_text(view, tab, key) {
None => match vm::chat::server_text(view, tab, key) {
Some(text) => Cow::Owned(vm::chat::server_message("", text)),
None => return slint::Image::default(),
},
};
let index = index.max(0) as usize;
match message.file_refs().get(index) {
Some(file) => image_of(view, file).map(|i| convert::image(&i)).unwrap_or_default(),
Some(file) => {
vm::previews::image_of(view, file).map(|i| convert::image(&i)).unwrap_or_default()
}
None => vm::chat::picture_link(&message, index)
.and_then(|url| view.pictures.get(&url))
.map(|path| crate::images::file(path))
@@ -190,19 +46,3 @@ impl App {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn previewable_names() {
assert!(is_previewable("Banner.PNG"));
assert!(is_previewable("a.webp"));
assert!(!is_previewable("notes.svg"));
assert!(!is_previewable("route.pdf"));
let file =
FileRef { channel: 2, path: "/".into(), name: "a.png".into(), ..Default::default() };
assert_eq!(link_key(&file), "/2/a.png");
}
}
-920
View File
@@ -1,920 +0,0 @@
//! Servers: bookmarks, connecting and observing, the rail, the sidebar's
//! server card and the channel tree.
use std::time::Instant;
use slint::ComponentHandle;
use tracing::{debug, info, warn};
use voelin_core::ts::identity::LaunchImport;
use voelin_core::{Command, JoinFailure, ObserveState, Source, VoiceOptions, VoiceState};
use voelin_model::ChannelId;
use voelin_store::{Bookmark, QueryTransport};
use crate::app::{App, Bridge, Nav, SessionView, later};
use crate::bind::convert;
use crate::vm;
use crate::vm::bridge::BookmarkForm;
use crate::vm::servers::{AfterConnect, JoinStep};
/// The name of the identity the app creates when it has none.
pub(crate) const CREATED_IDENTITY: &str = "Default";
/// What to tell the user about the identities imported from the official
/// clients at start ([`voelin_core::ts::identity::import_new`]), if anything.
pub(crate) fn imported_status(report: &LaunchImport) -> Option<String> {
let n = report.added.len();
let names = report.added.iter().map(|f| f.nickname.as_str()).collect::<Vec<_>>().join(", ");
let more = if n > 1 { format!(" ({n} imported: {names})") } else { String::new() };
Some(match &report.default {
Some(f) if report.replaced => format!(
"You now use your TeamSpeak identity \u{201c}{}\u{201d}; your previous one is kept{more}",
f.nickname
),
Some(f) => format!("Using your TeamSpeak identity \u{201c}{}\u{201d}{more}", f.nickname),
None if n == 1 => format!("Imported the identity \u{201c}{names}\u{201d} from TeamSpeak"),
None if n > 1 => format!("Imported {n} identities from TeamSpeak: {names}"),
None => return None,
})
}
/// The bookmark the form describes, over `old` (what the form does not show,
/// like the identity, the default channel or the client version, stays; a
/// new server has none of it). Only the address is needed: the name is the
/// address until the server tells its own (`adopt_server_name`), the
/// nickname `default_nickname`, the gateway is looked up in DNS
/// (`discover_gateway`). A new address drops the gateway and the query
/// login found or set for the old one.
fn bookmark_from_form(
old: Option<&Bookmark>,
form: &BookmarkForm,
default_nickname: impl FnOnce() -> String,
) -> Bookmark {
let mut bookmark = old.cloned().unwrap_or_default();
bookmark.id = form.id as i64;
bookmark.address = form.address.trim().to_string();
if old.is_some_and(|old| old.address != bookmark.address) {
bookmark.cached_server_icon = None;
bookmark.gateway_url = None;
bookmark.gateway_urls.clear();
bookmark.query = None;
}
bookmark.name = match form.name.trim() {
"" => bookmark.address.clone(),
name => name.to_string(),
};
bookmark.nickname = match form.nickname.trim() {
"" => default_nickname(),
nickname => nickname.to_string(),
};
bookmark
}
/// Apply only details originating from the bookmark's current address.
/// Returns whether its persisted metadata changed.
fn apply_server_icon(
bookmark: &mut Bookmark,
view: &mut SessionView,
address: &str,
icon: u32,
) -> bool {
if bookmark.address != address {
return false;
}
view.icon_address = Some(address.to_owned());
view.server_icon = icon;
let before = bookmark.cached_server_icon.clone();
bookmark.remember_server_icon(icon);
bookmark.cached_server_icon != before
}
/// Whether observing goes on as it is when discovery changed the gateways
/// kept from `previous` to `found`: the same ones (an older version kept
/// only the one in use), or logged in through `in_use`, still published.
/// What was found is kept for the next start, without a new login now.
fn observing_stays(
previous: &[String],
found: &[String],
in_use: Option<&str>,
observe: ObserveState,
) -> bool {
found == previous
|| (observe == ObserveState::Observing
&& in_use.is_some_and(|url| found.iter().any(|u| u == url)))
}
impl App {
pub(crate) fn connect_voice(&mut self) {
let channel = self
.state
.current
.and_then(|id| self.bookmark(id))
.and_then(|b| b.default_channel.clone());
self.connect_voice_to(channel, None, None);
}
/// Connect the current server with voice, into `channel` (a path, or
/// `/<id>`, with its password) if given, with a privilege key if given;
/// whether it was asked for.
pub(crate) fn connect_voice_to(
&mut self,
channel: Option<String>,
channel_password: Option<String>,
token: Option<String>,
) -> bool {
let Some(b) = self.state.current.and_then(|id| self.bookmark(id)).cloned() else {
return false;
};
if self.demo_ui {
return false;
}
let mut options = VoiceOptions::new(&b.address, &b.nickname);
if let Some(spec) = &b.client_version {
// The engine resolves the spec when it connects; asking now tells the
// user at once.
if let Err(error) = voelin_core::ts::versions::resolve(spec) {
self.set_status(format!("Invalid client compatibility version: {error}"));
return false;
}
options.client_version = Some(spec.clone());
}
options.identity = Some(voelin_core::ts::identity::to_blob(&self.identity_for(Some(b.id))));
options.server_password = self.secrets.get(&b.server_password_key()).ok().flatten();
options.channel = channel;
options.channel_password = channel_password;
options.token = token;
options.audio = true;
options.stream_peer = self.video.peer_config(options.stream_peer);
self.engine
.send(Command::ConnectVoice { session: b.id as u64, options: Box::new(options) });
self.set_status(format!("Connecting to {}…", b.address));
// The admin may have published the gateway since it was added.
self.discover_gateway(b.id);
true
}
/// The nickname a new server gets: the default identity's (one imported
/// from TeamSpeak keeps the nickname used there), else the system user's.
pub(crate) fn default_nickname(&self) -> String {
self.store
.default_identity()
.ok()
.flatten()
.map(|identity| identity.name)
.filter(|name| {
![CREATED_IDENTITY, voelin_core::ts::identity::DEFAULT_NICKNAME]
.contains(&name.as_str())
})
.or_else(|| std::env::var("USER").or_else(|_| std::env::var("USERNAME")).ok())
// Servers refuse an empty nickname (Android has no user name).
.filter(|name| !name.trim().is_empty())
.unwrap_or_else(|| "Voelin user".to_owned())
}
/// Look up the gateway of a server ([`voelin_core::discover`]), once a
/// run: every one the server publishes is kept, best first, and tried in
/// turn; they take the place of a stored one that is no longer published
/// (a gateway that moved, or one typed into an older version, which
/// showed the field). Nothing found keeps what is stored.
pub(crate) fn discover_gateway(&mut self, id: i64) {
if self.demo_ui || !self.state.gateways_looked_up.insert(id) {
return;
}
let Some(b) = self.bookmark(id) else { return };
let address = b.address.clone();
self.engine.runtime().spawn(async move {
let started = Instant::now();
let urls = voelin_core::discover::gateways(&address).await;
let elapsed_ms = started.elapsed().as_millis() as u64;
if urls.is_empty() {
info!(server = %address, elapsed_ms, "no gateway published");
} else {
later(move |app| app.gateway_found(id, &address, urls, elapsed_ms));
}
});
}
/// Gateways were found for the server at `address` (best first); they
/// are kept unless the server changed meanwhile, and the server is
/// observed through them if it is the one shown. Users never hear of
/// them (logged only).
fn gateway_found(&mut self, id: i64, address: &str, urls: Vec<String>, elapsed_ms: u64) {
let Some(b) = self.state.bookmarks.iter_mut().find(|b| b.id == id && b.address == address)
else {
return;
};
let previous = b.gateways();
let in_use = b.gateway_url.clone();
if !b.set_gateways(urls) {
debug!(server = %b.address, urls = ?b.gateway_urls, elapsed_ms, "gateway found, as kept");
return;
}
if let Err(e) = self.store.update_bookmark(b) {
warn!(%e, "could not keep the gateway found");
return;
}
let observe = self.state.sessions.get(&id).map(|v| v.state.observe).unwrap_or_default();
let kept = observing_stays(&previous, &b.gateways(), in_use.as_deref(), observe);
info!(server = %b.address, urls = ?b.gateway_urls, ?previous, kept, elapsed_ms, "gateway found");
self.refresh_toolbar();
if kept {
if self.state.current == Some(id) && observe == ObserveState::Off {
self.observe(id);
}
return;
}
// Observed through the old ones: through these now.
if !previous.is_empty() {
self.engine.send(Command::StopObserving { session: id as u64 });
if let Some(view) = self.state.sessions.get_mut(&id) {
view.state.observe = ObserveState::Off;
}
}
if self.state.current == Some(id) {
self.observe(id);
}
}
/// The gateway logged in at `url`: it is the one in use from now on.
pub(crate) fn gateway_in_use(&mut self, id: i64, url: &str) {
let Some(b) = self.state.bookmarks.iter_mut().find(|b| b.id == id) else { return };
if !b.gateway_in_use(url) {
return;
}
if let Err(e) = self.store.update_bookmark(b) {
warn!(%e, "could not keep the gateway in use");
return;
}
info!(server = %b.address, %url, "gateway in use");
}
/// The server told its name: a server still named by its address takes
/// it, so the address is all a user has to type.
pub(crate) fn adopt_server_name(&mut self, id: i64, name: &str) {
let Some(b) = self.state.bookmarks.iter_mut().find(|b| b.id == id && b.name == b.address)
else {
return;
};
if name.trim().is_empty() || self.demo_ui {
return;
}
b.name = name.trim().to_owned();
if let Err(e) = self.store.update_bookmark(b) {
warn!(%e, "could not name the server");
}
self.refresh_servers();
self.refresh_toolbar();
}
/// Observe the server invisibly, unless it is already: through its
/// gateway, else its own query login. Without either the gateway is
/// looked up first, and observing starts when it is found
/// (`gateway_found`). Asked while still connecting, the engine tries
/// the gateway again sooner.
pub(crate) fn observe(&mut self, id: i64) {
let Some(b) = self.bookmark(id).cloned() else { return };
if self.demo_ui {
return;
}
let session = b.id as u64;
let state = self.state.sessions.get(&b.id).map(|v| v.state.observe).unwrap_or_default();
let urls = b.gateways();
match state {
ObserveState::Observing => return,
// The engine decides: the same gateways are not started over,
// at most tried again now.
ObserveState::Connecting => {
if !urls.is_empty() {
debug!(server = %b.address, "still connecting to the gateway: try now");
self.engine.send(Command::ObserveGateway {
session,
urls,
identity: Box::new(voelin_core::ts::identity::to_blob(
&self.identity_for(Some(b.id)),
)),
});
}
return;
}
ObserveState::Off => {}
}
if !urls.is_empty() {
info!(server = %b.address, ?urls, "observing through the gateway");
self.engine.send(Command::ObserveGateway {
session,
urls,
identity: Box::new(voelin_core::ts::identity::to_blob(
&self.identity_for(Some(b.id)),
)),
});
// Still the one the server publishes?
self.discover_gateway(b.id);
} else if let Some(q) = &b.query {
let secret = self.secrets.get(&b.query_password_key()).ok().flatten();
let transport = match q.transport {
QueryTransport::Raw => voelin_core::QueryTransport::Raw,
QueryTransport::Ssh => voelin_core::QueryTransport::Ssh,
QueryTransport::Http => voelin_core::QueryTransport::Http,
};
let connect = voelin_core::QueryLogin {
transport,
address: format!("{}:{}", q.host, q.port),
user: q.user.clone(),
secret,
server_port: q.server_port,
server_id: None,
allowlisted: false,
};
self.engine.send(Command::ObserveQuery { session, connect: Box::new(connect) });
} else {
self.discover_gateway(b.id);
return;
}
self.set_status("Observing invisibly…");
}
/// Show a server, and observe it.
pub(crate) fn select_server(&mut self, id: i64) {
self.state.current = Some(id);
self.prefetch_counts();
self.track_reading();
self.refresh_all();
self.observe(id);
}
pub(crate) fn bookmark_form(&self, id: i64) -> BookmarkForm {
let Some(b) = self.bookmark(id) else {
return BookmarkForm {
id: -1,
nickname: self.default_nickname().into(),
..Default::default()
};
};
let password = self.secrets.get(&b.server_password_key()).ok().flatten();
let state = self.state.sessions.get(&b.id).map(|view| &view.state);
vm::servers::form(b, state, password.as_deref().unwrap_or_default())
}
/// Save the server dialog's server, and show it; its id, none when it
/// could not be saved (the toast says why).
pub(crate) fn save_bookmark(&mut self, form: &BookmarkForm) -> Option<i64> {
let old = self.bookmark(form.id as i64).cloned();
let mut bookmark = bookmark_from_form(old.as_ref(), form, || self.default_nickname());
let result = if bookmark.id < 0 {
self.store.add_bookmark(&bookmark).map(|id| bookmark.id = id)
} else {
self.store.update_bookmark(&bookmark)
};
if let Err(e) = result {
self.set_status(format!("Could not save: {e}"));
return None;
}
let key = bookmark.server_password_key();
let result = if form.server_password.is_empty() {
self.secrets.delete(&key)
} else {
self.secrets.set(&key, &form.server_password)
};
if let Err(e) = result {
warn!(%e, "could not store secret");
}
// Another server: what was observed is the old one's, and its
// gateway is looked up anew.
if let Some(old) = old.filter(|old| old.address != bookmark.address) {
if old.query.is_some() {
let _ = self.secrets.delete(&old.query_password_key());
}
self.state.gateways_looked_up.remove(&bookmark.id);
self.engine.send(Command::StopObserving { session: bookmark.id as u64 });
if let Some(view) = self.state.sessions.get_mut(&bookmark.id) {
view.state.observe = ObserveState::Off;
}
}
self.state.bookmarks = self.store.bookmarks().unwrap_or_default();
self.select_server(bookmark.id);
Some(bookmark.id)
}
/// The server dialog's Connect: save the server, then connect it with
/// voice, into the channel of the link that filled the form if one did
/// ([`vm::servers::connect_to`]). Only once saved: connecting what is
/// shown after a failed save would connect the server shown before.
/// Whether it was saved.
pub(crate) fn save_and_connect(&mut self, form: &BookmarkForm) -> bool {
let saved = self.save_bookmark(form);
let Some(to) = vm::servers::connect_to(form, saved.and_then(|id| self.bookmark(id))) else {
return false;
};
self.connect_voice_to(to.channel, to.channel_password, to.token);
true
}
pub(crate) fn delete_bookmark(&mut self, id: i64) {
self.engine.send(Command::CloseSession { session: id as u64 });
if let Some(b) = self.bookmark(id).cloned() {
let _ = self.secrets.delete(&b.server_password_key());
let _ = self.secrets.delete(&b.query_password_key());
}
let _ = self.store.delete_bookmark(id);
self.save_reads(id);
self.state.sessions.remove(&id);
self.state.gateways_looked_up.remove(&id);
self.state.bookmarks = self.store.bookmarks().unwrap_or_default();
self.state.current = self.state.bookmarks.first().map(|b| b.id);
self.prefetch_counts();
self.track_reading();
self.refresh_all();
}
/// Keep only metadata supplied by the bookmark's current server.
pub(crate) fn remember_server_icon(&mut self, id: i64, address: &str, icon: u32) {
let Some(bookmark) = self.state.bookmarks.iter_mut().find(|b| b.id == id) else {
return;
};
let changed =
apply_server_icon(bookmark, self.state.sessions.entry(id).or_default(), address, icon);
if changed
&& !self.demo_ui
&& let Err(error) = self.store.update_bookmark(bookmark)
{
warn!(%error, "could not keep the server icon");
}
}
pub(crate) fn server_list_icon(&self, bookmark: &Bookmark) -> vm::ImageRef {
let current = self
.state
.sessions
.get(&bookmark.id)
.map(|view| view.server_icon_for(&bookmark.address))
.unwrap_or_default();
if current.size().width > 0 {
current
} else {
vm::servers::cached_icon(bookmark, &self.engine.cache())
}
}
/// A server's colour, as the rail shows it ([`vm::servers::tints`]).
pub(crate) fn server_tint(&self, id: i64) -> vm::Rgb {
let tints = vm::servers::tints(&self.state.bookmarks);
self.state.bookmarks.iter().position(|b| b.id == id).map(|i| tints[i]).unwrap_or_default()
}
/// The rail: servers with their state, unread count (without private
/// chats) and streams; what the chat strip and the private chats have
/// unread.
pub(crate) fn refresh_servers(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let tints = vm::servers::tints(&self.state.bookmarks);
let items: Vec<_> = self
.state
.bookmarks
.iter()
.zip(tints)
.map(|(b, tint)| {
let view = self.state.sessions.get(&b.id);
let state = view.map(|v| v.state.clone()).unwrap_or_default();
let unread = view.map_or(0, SessionView::channel_unread);
let live = view.is_some_and(|v| v.streams_available() && !v.streams.is_empty());
let detail = view
.filter(|v| !v.presence.channels.is_empty())
.map(|v| vm::tree::stats(&v.presence))
.unwrap_or_default();
let product = view.map(|v| v.extra.product.clone()).unwrap_or_default();
let icon = self.server_list_icon(b);
vm::servers::item(b, &state, unread, live, detail, product, icon, tint)
})
.collect();
self.models.servers.sync(&items);
bridge.set_last_place(self.last_place(&items).into());
bridge.set_current_server(self.state.current.map_or(-1, |id| id as i32));
// Private chats count on the messages page (and the phone's Home).
bridge.set_unread_total(self.view().map_or(0, SessionView::channel_unread));
bridge.set_dm_unread(self.dm_unread());
}
/// The server card, the voice controls and who we are.
pub(crate) fn refresh_toolbar(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let bookmark = self.state.current.and_then(|id| self.bookmark(id));
let view = self.view();
let state = view.map(|v| v.state.clone()).unwrap_or_default();
bridge.set_server_icon(convert::image(
&bookmark.map(|b| self.server_list_icon(b)).unwrap_or_default(),
));
bridge.set_server_title(
bookmark.map_or("No server selected".into(), |b| b.name.clone()).into(),
);
let has_presence = view.is_some_and(|v| !v.presence.channels.is_empty())
&& (state.voice == VoiceState::Connected || state.observe == ObserveState::Observing);
bridge.set_server_stats(
view.filter(|_| has_presence)
.map(|v| vm::tree::stats(&v.presence))
.unwrap_or_default()
.into(),
);
bridge.set_nickname(bookmark.map(|b| b.nickname.clone()).unwrap_or_default().into());
let own = view.zip(state.own_client).and_then(|(v, c)| v.avatar(c));
bridge.set_own_avatar(convert::image(&vm::avatar::image(own)));
let banner = |url: Option<&str>| {
view.map(|v| vm::tree::banner(&v.pictures, url)).unwrap_or_default()
};
let details = view.map(|v| &v.presence.server);
bridge
.set_server_banner(convert::image(&banner(details.map(|d| d.banner_gfx_url.as_str()))));
bridge.set_server_banner_mode(details.map_or(0, |d| vm::tree::banner_mode(d.banner_mode)));
let own_channel =
view.and_then(|v| state.own_channel.and_then(|c| v.presence.channels.get(&c)));
bridge.set_own_channel(
own_channel.map(|c| vm::tree::channel_title(c).0).unwrap_or_default().into(),
);
bridge.set_own_channel_topic(
own_channel.and_then(|c| c.topic.clone()).unwrap_or_default().into(),
);
bridge.set_own_channel_banner(convert::image(&banner(
own_channel.and_then(|c| c.banner_gfx_url.as_deref()),
)));
bridge.set_own_channel_banner_mode(
own_channel.map_or(0, |c| vm::tree::banner_mode(c.banner_mode)),
);
bridge.set_own_channel_limit(
own_channel.and_then(|c| c.max_clients).filter(|m| *m >= 0).unwrap_or(-1),
);
bridge.set_voice_connected(state.voice == VoiceState::Connected);
bridge.set_voice_connecting(state.voice == VoiceState::Connecting);
bridge.set_observing(state.observe != ObserveState::Off);
bridge.set_input_muted(state.input_muted);
bridge.set_output_muted(state.output_muted);
bridge.set_transmitting(state.transmitting);
bridge.set_presence_source(
match state.presence_source {
Some(Source::Voice) => "live (voice)",
Some(Source::Gateway) => "invisible (gateway)",
Some(Source::Query) => "invisible (query)",
None => "",
}
.into(),
);
if state.voice != VoiceState::Connected {
bridge.set_input_level(-100.0);
bridge.set_input_sending(false);
}
}
/// The channel tree, the members of our channel and everyone on the
/// server.
pub(crate) fn refresh_tree(&self) {
let Some(view) = self.view() else {
self.models.tree.sync(&[]);
self.models.members.sync(&[]);
self.models.server_members.sync(&[]);
return;
};
let input = vm::tree::TreeInput {
presence: &view.presence,
collapsed: &view.collapsed,
talking: &view.talking,
playback: &self.state.playback,
own_channel: view.state.own_channel,
own_client: view.state.own_client,
filter: "",
avatars: &view.avatars,
icons: &view.icons,
pictures: &view.pictures,
groups: &view.server_groups,
channel_groups: &view.channel_groups,
};
self.models.tree.sync(&vm::tree::rows(&input));
let connected = view.state.voice == VoiceState::Connected;
let members = if connected { vm::tree::members(&input) } else { Vec::new() };
self.models.members.sync(&members);
// The people in our channel first while their view is shown (not
// while the stream plays in a window of its own).
let watching = self.watch.as_ref().is_some_and(|w| w.shown) && self.popout.window.is_none();
let voice_first = connected && (self.state.voice_view || watching);
let everyone = vm::tree::server_members(&input, voice_first);
let filter = self.state.member_filter.trim().to_lowercase();
let shown =
if filter.is_empty() { everyone } else { vm::tree::matching(everyone, &filter) };
self.models.server_members.sync(&shown);
if let Some(ui) = self.ui.upgrade() {
let total = view.presence.clients.values().filter(|c| !c.is_query).count();
ui.global::<crate::app::Bridge>().set_member_total(total as i32);
}
}
/// The members panel's search.
pub(crate) fn search_members(&mut self, text: String) {
if self.state.member_filter != text {
self.state.member_filter = text;
self.refresh_tree();
}
}
/// The voice channel view was opened or closed: its chat is our
/// channel's, and its people lead the members panel.
pub(crate) fn show_voice_view(&mut self, on: bool) {
self.state.voice_view = on;
if on && let Some(channel) = self.view().and_then(|v| v.state.own_channel) {
self.open_chat(voelin_model::ChatTarget::Channel(channel), true);
}
self.refresh_tree();
}
/// A link to the voice channel we are in, for the Invite button (which
/// copies it, and the copy's toast names the channel); empty, with a
/// note, without one.
pub(crate) fn invite_link(&mut self) -> String {
let bookmark =
self.state.current.and_then(|id| self.bookmark(id)).map(|b| b.address.clone());
let path = self.view().and_then(|v| {
let cid = v.state.own_channel?;
let own = v.presence.channels.get(&cid)?;
// The link names the channels as the server has them; the
// toast as the tree shows them.
Some((
vm::tree::channel_path(&v.presence, cid),
vm::tree::channel_title(own).0.to_owned(),
))
});
let (Some(address), Some((path, title))) = (bookmark, path) else {
self.set_status("Join a voice channel to invite others to it");
return String::new();
};
let path: Vec<&str> = path.iter().map(String::as_str).collect();
let link = vm::servers::invite_link(&address, &path);
self.state.copy_note = Some(format!("Copied an invite to {title}: {link}"));
link
}
/// Join a channel of a session (a double-click in the tree, joining a
/// friend): move there with voice, or connect into it. A locked channel
/// asks for its password first, unless it was given this connection.
pub(crate) fn join_channel(&mut self, session: i64, channel: ChannelId) {
let Some(view) = self.state.sessions.get(&session) else { return };
let Some(info) = view.presence.channels.get(&channel) else { return };
let remembered = view.channel_passwords.get(&channel).map(String::as_str);
match vm::servers::join_password(info, remembered) {
JoinStep::Send(password) => self.enter_channel(session, channel, password),
JoinStep::Ask => self.ask_channel_password(session, channel, false),
}
}
/// The password dialog's Join.
pub(crate) fn join_with_password(&mut self, password: String) {
let Some((session, channel)) = self.state.join_target.take() else { return };
if password.is_empty() {
return;
}
if let Some(view) = self.state.sessions.get_mut(&session) {
view.channel_passwords.insert(channel, password.clone());
}
self.enter_channel(session, channel, Some(password));
}
/// Move into a channel; without voice on its server, connect into it.
fn enter_channel(&mut self, session: i64, channel: ChannelId, password: Option<String>) {
let Some(view) = self.state.sessions.get_mut(&session) else { return };
if view.state.voice != VoiceState::Disconnected {
// Chosen while connecting: no longer the one to join after.
view.join_after_connect = None;
if !self.demo_ui {
self.engine.send(Command::MoveToChannel {
session: session as u64,
channel,
password,
});
}
return;
}
if self.state.current != Some(session) {
self.select_server(session);
}
// By id: by its name the server finds only a top-level channel (a
// subchannel's name connects into the default channel).
if self.connect_voice_to(Some(format!("/{channel}")), password, None)
&& let Some(view) = self.state.sessions.get_mut(&session)
{
view.join_after_connect = Some(channel);
}
}
/// Connected into another channel than the one asked for
/// (`SessionView::join_after_connect`): the server says nothing when,
/// for one, the password was wrong, so it is joined again, and that
/// move says why. Once the channel shows in the voice
/// connection's presence, which can come after the own channel.
pub(crate) fn join_after_connect(&mut self, session: i64) {
let Some(view) = self.state.sessions.get_mut(&session) else { return };
let (VoiceState::Connected, Some(asked)) = (view.state.voice, view.join_after_connect)
else {
return;
};
let known = view.presence.channels.contains_key(&asked);
match vm::servers::after_connect(view.state.own_channel, asked, known) {
AfterConnect::Wait => {}
AfterConnect::Joined => view.join_after_connect = None,
AfterConnect::JoinAgain => {
view.join_after_connect = None;
self.join_channel(session, asked);
}
}
}
/// Open the password dialog for a locked channel; `wrong`: the one
/// given was refused.
fn ask_channel_password(&mut self, session: i64, channel: ChannelId, wrong: bool) {
let Some(info) =
self.state.sessions.get(&session).and_then(|v| v.presence.channels.get(&channel))
else {
return;
};
let name = vm::tree::channel_title(info).0.to_owned();
self.state.join_target = Some((session, channel));
let Some(ui) = self.ui.upgrade() else { return };
let nav = ui.global::<Nav>();
nav.set_channel_password_name(name.into());
nav.set_channel_password_error(wrong);
nav.set_channel_password_open(true);
}
/// The server refused a move ([`voelin_core::Event::JoinFailed`]): a
/// password asks again (the one given is forgotten), the rest is a
/// toast.
pub(crate) fn join_failed(&mut self, session: i64, channel: ChannelId, reason: JoinFailure) {
match reason {
JoinFailure::Password => {
let given = self
.state
.sessions
.get_mut(&session)
.and_then(|v| v.channel_passwords.remove(&channel))
.is_some();
self.ask_channel_password(session, channel, given);
}
JoinFailure::Full => self.set_status("The channel is full"),
JoinFailure::Other(text) => self.set_status(text),
}
}
pub(crate) fn toggle_collapse(&mut self, channel: u64) {
if let Some(view) = self.view_mut()
&& !view.collapsed.remove(&channel)
{
view.collapsed.insert(channel);
}
self.refresh_tree();
}
}
#[cfg(test)]
mod tests {
use voelin_core::ts::identity::Found;
use super::*;
use voelin_store::QueryConfig;
#[test]
fn edited_server_rejects_queued_icons_and_failed_reconnect_keeps_them_hidden() {
let path = std::env::temp_dir()
.join(format!("voelin-server-icon-provenance-{}.svg", std::process::id()));
std::fs::write(&path, r#"<svg xmlns="http://www.w3.org/2000/svg" width="4" height="4"><rect width="4" height="4" fill="red"/></svg>"#).unwrap();
let mut bookmark = Bookmark { address: "a.test".into(), ..Default::default() };
let mut view = SessionView::default();
view.icons.insert(1234, path.clone());
assert!(apply_server_icon(&mut bookmark, &mut view, "a.test", 1234));
assert_eq!(view.server_icon_for(&bookmark.address).size().width, 4);
bookmark = bookmark_from_form(
Some(&bookmark),
&BookmarkForm { address: "b.test".into(), ..Default::default() },
|| "Me".into(),
);
// Connecting does not retag received imagery. A failed B connection
// must not make A's image appear under B's name.
for state in [VoiceState::Connecting, VoiceState::Disconnected] {
view.state.voice = state;
assert_eq!(view.server_icon_for(&bookmark.address).size().width, 0);
}
assert!(!apply_server_icon(&mut bookmark, &mut view, "a.test", 4321));
assert_eq!(view.server_icon, 1234);
assert_eq!(view.icon_address.as_deref(), Some("a.test"));
assert!(bookmark.server_icon_id().is_none());
// Equal icon IDs on the next server still need new provenance.
assert!(apply_server_icon(&mut bookmark, &mut view, "b.test", 1234));
assert_eq!(bookmark.server_icon_id(), Some(1234));
assert_eq!(view.server_icon_for(&bookmark.address).size().width, 4);
assert!(!apply_server_icon(&mut bookmark, &mut view, "a.test", 0));
assert_eq!(bookmark.server_icon_id(), Some(1234));
assert!(apply_server_icon(&mut bookmark, &mut view, "b.test", 0));
assert!(bookmark.server_icon_id().is_none());
assert_eq!(view.server_icon_for(&bookmark.address).size().width, 0);
std::fs::remove_file(path).unwrap();
}
#[test]
fn the_address_alone_makes_a_server() {
let form =
BookmarkForm { id: -1, address: " ts.example.test ".into(), ..Default::default() };
let b = bookmark_from_form(None, &form, || "Nick".into());
assert_eq!((b.address.as_str(), b.name.as_str()), ("ts.example.test", "ts.example.test"));
assert_eq!(b.nickname, "Nick");
assert_eq!(
(b.gateway_url, b.query, b.identity, b.default_channel),
(None, None, None, None)
);
}
#[test]
fn editing_keeps_what_the_form_does_not_show() {
let old = Bookmark {
id: 7,
name: "Old".into(),
address: "old.example.test".into(),
nickname: "Me".into(),
identity: Some(2),
default_channel: Some("Lobby/Sub".into()),
gateway_url: Some("ws://gw.example.test:7788/v1".into()),
gateway_urls: vec!["ws://gw.example.test:7788/v1".into()],
query: Some(QueryConfig { server_port: Some(9988), ..Default::default() }),
client_version: Some("linux".into()),
cached_server_icon: Some(voelin_store::CachedServerIcon {
address: "old.example.test".into(),
id: 1234,
}),
};
// Same address: the gateway found and the query login stay.
let same = BookmarkForm {
id: 7,
name: "Mine".into(),
address: "old.example.test".into(),
nickname: "Other".into(),
..Default::default()
};
let b = bookmark_from_form(Some(&old), &same, || unreachable!("a nickname was given"));
assert_eq!((b.id, b.name.as_str(), b.nickname.as_str()), (7, "Mine", "Other"));
assert_eq!(b.gateway_url, old.gateway_url);
assert_eq!(b.query, old.query);
assert_eq!(b.cached_server_icon, old.cached_server_icon);
// Another address: looked up again, for the new server.
let form = BookmarkForm { address: "new.example.test:9988".into(), ..same };
let b = bookmark_from_form(Some(&old), &form, || unreachable!("a nickname was given"));
assert_eq!(b.address, "new.example.test:9988");
assert!(b.cached_server_icon.is_none());
assert_eq!((b.identity, b.default_channel), (Some(2), Some("Lobby/Sub".into())));
assert_eq!(b.client_version.as_deref(), Some("linux"));
assert_eq!((b.gateway_url, b.query), (None, None));
assert!(b.gateway_urls.is_empty());
}
#[test]
fn the_import_is_told_by_nickname() {
let found = |nickname: &str| Found {
nickname: nickname.into(),
identity: tsclientlib::Identity::create(),
source: "settings.db".into(),
selected: false,
};
let report = |added: &[&str], default: Option<&str>, replaced| LaunchImport {
added: added.iter().map(|n| found(n)).collect(),
default: default.map(found),
replaced,
};
assert_eq!(imported_status(&report(&[], None, false)), None);
assert_eq!(
imported_status(&report(&["Main"], Some("Main"), false)).unwrap(),
"Using your TeamSpeak identity \u{201c}Main\u{201d}"
);
assert_eq!(
imported_status(&report(&["Main", "Alt"], None, false)).unwrap(),
"Imported 2 identities from TeamSpeak: Main, Alt"
);
// Imported earlier, now ours instead of the one the app made.
assert_eq!(
imported_status(&report(&[], Some("Main"), true)).unwrap(),
"You now use your TeamSpeak identity \u{201c}Main\u{201d}; your previous one is kept"
);
}
#[test]
fn a_gateway_found_again_is_not_logged_in_again() {
let (tls, plain) = ("wss://gw.example.test/v1", "ws://ts.example.test:7788/v1");
let urls = |list: &[&str]| list.iter().map(|u| u.to_string()).collect::<Vec<_>>();
let stays = |previous: &[&str], found: &[&str], observe| {
observing_stays(&urls(previous), &urls(found), Some(plain), observe)
};
// The same ones (an older version kept only the one in use).
assert!(stays(&[plain], &[plain], ObserveState::Connecting));
assert!(stays(&[plain], &[plain], ObserveState::Observing));
// Logged in through one still published.
assert!(stays(&[plain], &[tls, plain], ObserveState::Observing));
// Not logged in yet: through the new ones.
assert!(!stays(&[plain], &[tls, plain], ObserveState::Connecting));
// The one in use is no longer published.
assert!(!stays(&[plain], &[tls], ObserveState::Observing));
assert!(!observing_stays(&[], &urls(&[tls]), None, ObserveState::Off));
}
}
+455
View File
@@ -0,0 +1,455 @@
//! The Slint side of the servers: connecting and observing (the store, the
//! secrets, the engine), the Bridge writes of the rail, the server card and
//! the channel tree, and the callbacks' ways into the transitions of
//! `voelin_ui_vm::servers::logic`.
use std::time::Instant;
use slint::ComponentHandle;
use tracing::{debug, info, warn};
use voelin_core::{Command, JoinFailure, ObserveState};
use voelin_model::ChannelId;
use voelin_store::{Bookmark, QueryTransport};
use crate::app::{App, Bridge, later};
use crate::bind::convert;
use crate::vm;
use crate::vm::bridge::BookmarkForm;
use crate::vm::servers::logic::{self as logic, GatewayFound, ObservePlan};
impl App {
pub(crate) fn connect_voice(&mut self) {
let channel = self
.state
.current
.and_then(|id| self.bookmark(id))
.and_then(|b| b.default_channel.clone());
self.connect_voice_to(channel, None, None);
}
/// Connect the current server with voice, into `channel` (a path, or
/// `/<id>`, with its password) if given, with a privilege key if given;
/// whether it was asked for.
pub(crate) fn connect_voice_to(
&mut self,
channel: Option<String>,
channel_password: Option<String>,
token: Option<String>,
) -> bool {
let Some(b) = self.state.current.and_then(|id| self.bookmark(id)).cloned() else {
return false;
};
if self.demo_ui {
return false;
}
let mut options = match logic::voice_options(&b, channel, channel_password, token) {
Ok(options) => options,
Err(error) => {
self.set_status(error);
return false;
}
};
options.identity = Some(voelin_core::ts::identity::to_blob(&self.identity_for(Some(b.id))));
options.server_password = self.secrets.get(&b.server_password_key()).ok().flatten();
options.stream_peer = self.video.peer_config(options.stream_peer);
self.engine
.send(Command::ConnectVoice { session: b.id as u64, options: Box::new(options) });
self.set_status(format!("Connecting to {}…", b.address));
// The admin may have published the gateway since it was added.
self.discover_gateway(b.id);
true
}
/// The nickname a new server gets: the default identity's (one imported
/// from TeamSpeak keeps the nickname used there), else the system user's.
pub(crate) fn default_nickname(&self) -> String {
self.store
.default_identity()
.ok()
.flatten()
.map(|identity| identity.name)
.filter(|name| {
![logic::CREATED_IDENTITY, voelin_core::ts::identity::DEFAULT_NICKNAME]
.contains(&name.as_str())
})
.or_else(|| std::env::var("USER").or_else(|_| std::env::var("USERNAME")).ok())
// Servers refuse an empty nickname (Android has no user name).
.filter(|name| !name.trim().is_empty())
.unwrap_or_else(|| "Voelin user".to_owned())
}
/// Look up the gateway of a server ([`voelin_core::discover`]), once a
/// run ([`logic::discover_wanted`]): every one the server publishes is
/// kept, best first, and tried in turn; they take the place of a stored
/// one that is no longer published (a gateway that moved, or one typed
/// into an older version, which showed the field). Nothing found keeps
/// what is stored.
pub(crate) fn discover_gateway(&mut self, id: i64) {
let Some(address) = self.transition(|state, cx| logic::discover_wanted(state, cx, id))
else {
return;
};
self.engine.runtime().spawn(async move {
let started = Instant::now();
let urls = voelin_core::discover::gateways(&address).await;
let elapsed_ms = started.elapsed().as_millis() as u64;
if urls.is_empty() {
info!(server = %address, elapsed_ms, "no gateway published");
} else {
later(move |app| app.gateway_found(id, &address, urls, elapsed_ms));
}
});
}
/// Gateways were found for the server at `address` (best first); they
/// are kept unless the server changed meanwhile ([`logic::gateway_found`]),
/// and the server is observed through them if it is the one shown. Users
/// never hear of them (logged only).
fn gateway_found(&mut self, id: i64, address: &str, urls: Vec<String>, elapsed_ms: u64) {
let found = self.transition(|state, cx| logic::gateway_found(state, cx, id, address, urls));
match found {
GatewayFound::Same => {
debug!(server = %address, elapsed_ms, "gateway found, as kept");
}
GatewayFound::Kept { observe } => {
info!(server = %address, elapsed_ms, kept = true, "gateway found");
if observe {
self.observe(id);
}
}
GatewayFound::Changed { stop, observe, urls } => {
info!(server = %address, ?urls, elapsed_ms, kept = false, "gateway found");
if stop {
self.engine.send(Command::StopObserving { session: id as u64 });
}
if observe {
self.observe(id);
}
}
}
}
/// Observe the server invisibly ([`logic::observe_plan`]): through its
/// gateway, else its own query login. Without either the gateway is
/// looked up first, and observing starts when it is found
/// (`gateway_found`).
pub(crate) fn observe(&mut self, id: i64) {
let Some(b) = self.bookmark(id).cloned() else { return };
let session = b.id as u64;
match self.transition(|state, cx| logic::observe_plan(state, cx, id)) {
ObservePlan::Nothing => return,
ObservePlan::Retry(urls) => {
debug!(server = %b.address, "still connecting to the gateway: try now");
self.engine.send(Command::ObserveGateway {
session,
urls,
identity: Box::new(voelin_core::ts::identity::to_blob(
&self.identity_for(Some(b.id)),
)),
});
return;
}
ObservePlan::Gateway(urls) => {
info!(server = %b.address, ?urls, "observing through the gateway");
self.engine.send(Command::ObserveGateway {
session,
urls,
identity: Box::new(voelin_core::ts::identity::to_blob(
&self.identity_for(Some(b.id)),
)),
});
// Still the one the server publishes?
self.discover_gateway(b.id);
}
ObservePlan::Query(q) => {
let secret = self.secrets.get(&b.query_password_key()).ok().flatten();
let transport = match q.transport {
QueryTransport::Raw => voelin_core::QueryTransport::Raw,
QueryTransport::Ssh => voelin_core::QueryTransport::Ssh,
QueryTransport::Http => voelin_core::QueryTransport::Http,
};
let connect = voelin_core::QueryLogin {
transport,
address: format!("{}:{}", q.host, q.port),
user: q.user.clone(),
secret,
server_port: q.server_port,
server_id: None,
allowlisted: false,
};
self.engine.send(Command::ObserveQuery { session, connect: Box::new(connect) });
}
ObservePlan::Discover => {
self.discover_gateway(b.id);
return;
}
}
self.set_status("Observing invisibly…");
}
/// Show a server, and observe it.
pub(crate) fn select_server(&mut self, id: i64) {
self.transition(|state, cx| logic::select_server(state, cx, id));
self.observe(id);
}
pub(crate) fn bookmark_form(&self, id: i64) -> BookmarkForm {
let Some(b) = self.bookmark(id) else {
return BookmarkForm {
id: -1,
nickname: self.default_nickname().into(),
..Default::default()
};
};
let password = self.secrets.get(&b.server_password_key()).ok().flatten();
let state = self.state.sessions.get(&b.id).map(|view| &view.state);
vm::servers::form(b, state, password.as_deref().unwrap_or_default())
}
/// Save the server dialog's server, and show it; its id, none when it
/// could not be saved (the toast says why).
pub(crate) fn save_bookmark(&mut self, form: &BookmarkForm) -> Option<i64> {
let old = self.bookmark(form.id as i64).cloned();
let mut bookmark =
logic::bookmark_from_form(old.as_ref(), form, || self.default_nickname());
let result = if bookmark.id < 0 {
self.store.add_bookmark(&bookmark).map(|id| bookmark.id = id)
} else {
self.store.update_bookmark(&bookmark)
};
if let Err(e) = result {
self.set_status(format!("Could not save: {e}"));
return None;
}
let key = bookmark.server_password_key();
let result = if form.server_password.is_empty() {
self.secrets.delete(&key)
} else {
self.secrets.set(&key, &form.server_password)
};
if let Err(e) = result {
warn!(%e, "could not store secret");
}
// Another server: what was observed is the old one's, and its
// gateway is looked up anew.
if let Some(old) = old.filter(|old| old.address != bookmark.address) {
if old.query.is_some() {
let _ = self.secrets.delete(&old.query_password_key());
}
self.state.gateways_looked_up.remove(&bookmark.id);
self.engine.send(Command::StopObserving { session: bookmark.id as u64 });
if let Some(view) = self.state.sessions.get_mut(&bookmark.id) {
view.state.observe = ObserveState::Off;
}
}
self.state.bookmarks = self.store.bookmarks().unwrap_or_default();
self.select_server(bookmark.id);
Some(bookmark.id)
}
/// The server dialog's Connect: save the server, then connect it with
/// voice, into the channel of the link that filled the form if one did
/// ([`vm::servers::connect_to`]). Only once saved: connecting what is
/// shown after a failed save would connect the server shown before.
/// Whether it was saved.
pub(crate) fn save_and_connect(&mut self, form: &BookmarkForm) -> bool {
let saved = self.save_bookmark(form);
let Some(to) = vm::servers::connect_to(form, saved.and_then(|id| self.bookmark(id))) else {
return false;
};
self.connect_voice_to(to.channel, to.channel_password, to.token);
true
}
pub(crate) fn delete_bookmark(&mut self, id: i64) {
self.engine.send(Command::CloseSession { session: id as u64 });
if let Some(b) = self.bookmark(id).cloned() {
let _ = self.secrets.delete(&b.server_password_key());
let _ = self.secrets.delete(&b.query_password_key());
}
let _ = self.store.delete_bookmark(id);
let bookmarks = self.store.bookmarks().unwrap_or_default();
self.transition(|state, cx| logic::forget_server(state, cx, id, bookmarks));
}
pub(crate) fn server_list_icon(&self, bookmark: &Bookmark) -> vm::ImageRef {
let current = self
.state
.sessions
.get(&bookmark.id)
.map(|view| view.server_icon_for(&bookmark.address))
.unwrap_or_default();
if current.size().width > 0 {
current
} else {
vm::servers::cached_icon(bookmark, &self.engine.cache())
}
}
/// The rail: servers with their state, unread count (without private
/// chats) and streams; what the chat strip and the private chats have
/// unread.
pub(crate) fn refresh_servers(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let items = logic::rail(&self.state, |b| self.server_list_icon(b));
self.models.servers.sync(&items);
bridge.set_last_place(self.last_place(&items).into());
bridge.set_current_server(self.state.current.map_or(-1, |id| id as i32));
// Private chats count on the messages page (and the phone's Home).
bridge.set_unread_total(self.view().map_or(0, crate::app::SessionView::channel_unread));
bridge.set_dm_unread(self.dm_unread());
}
/// The server card, the voice controls and who we are
/// ([`logic::toolbar`]).
pub(crate) fn refresh_toolbar(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let card = logic::toolbar(&self.state, |b| self.server_list_icon(b));
bridge.set_server_icon(convert::image(&card.server_icon));
bridge.set_server_title(card.server_title.into());
bridge.set_server_stats(card.server_stats.into());
bridge.set_nickname(card.nickname.into());
bridge.set_own_avatar(convert::image(&card.own_avatar));
bridge.set_server_banner(convert::image(&card.server_banner));
bridge.set_server_banner_mode(card.server_banner_mode);
bridge.set_own_channel(card.own_channel.into());
bridge.set_own_channel_topic(card.own_channel_topic.into());
bridge.set_own_channel_banner(convert::image(&card.own_channel_banner));
bridge.set_own_channel_banner_mode(card.own_channel_banner_mode);
bridge.set_own_channel_limit(card.own_channel_limit);
bridge.set_voice_connected(card.voice_connected);
bridge.set_voice_connecting(card.voice_connecting);
bridge.set_observing(card.observing);
bridge.set_input_muted(card.input_muted);
bridge.set_output_muted(card.output_muted);
bridge.set_transmitting(card.transmitting);
bridge.set_presence_source(card.presence_source.into());
if !card.voice_connected {
bridge.set_input_level(-100.0);
bridge.set_input_sending(false);
}
}
/// The channel tree, the members of our channel and everyone on the
/// server ([`logic::tree_view`]).
pub(crate) fn refresh_tree(&self) {
let Some(tree) = logic::tree_view(&self.state, self.popout.window.is_some()) else {
self.models.tree.sync(&[]);
self.models.members.sync(&[]);
self.models.server_members.sync(&[]);
return;
};
self.models.tree.sync(&tree.rows);
self.models.members.sync(&tree.members);
self.models.server_members.sync(&tree.server_members);
if let Some(ui) = self.ui.upgrade() {
ui.global::<Bridge>().set_member_total(tree.member_total);
}
}
/// The members panel's search.
pub(crate) fn search_members(&mut self, text: String) {
self.transition(|state, cx| logic::search_members(state, cx, text));
}
/// The voice channel view was opened or closed.
pub(crate) fn show_voice_view(&mut self, on: bool) {
self.transition(|state, cx| logic::show_voice_view(state, cx, on));
}
/// A link to the voice channel we are in, for the Invite button; empty,
/// with a note, without one ([`logic::invite_link`]).
pub(crate) fn invite_link(&mut self) -> String {
match logic::invite_link(&mut self.state) {
Ok(link) => link,
Err(why) => {
self.set_status(why);
String::new()
}
}
}
/// Join a channel of a session ([`logic::join_channel`]): the transition
/// moves there with voice or asks for the password; without voice on that
/// server we connect into it.
pub(crate) fn join_channel(&mut self, session: i64, channel: ChannelId) {
if let Some(password) =
self.transition(|state, cx| logic::join_channel(state, cx, session, channel))
{
self.connect_into(session, channel, password);
}
}
/// The password dialog's Join.
pub(crate) fn join_with_password(&mut self, password: String) {
if let Some((session, channel, password)) =
self.transition(|state, cx| logic::join_with_password(state, cx, password))
{
self.connect_into(session, channel, password);
}
}
/// Connect voice into a channel of a server that has none.
fn connect_into(&mut self, session: i64, channel: ChannelId, password: Option<String>) {
if self.state.current != Some(session) {
self.select_server(session);
}
// By id: by its name the server finds only a top-level channel (a
// subchannel's name connects into the default channel).
if self.connect_voice_to(Some(format!("/{channel}")), password, None) {
logic::join_after_connect(&mut self.state, session, channel);
}
}
/// The server refused a move ([`voelin_core::Event::JoinFailed`]): a
/// password asks again (the one given is forgotten), the rest is a
/// toast.
pub(crate) fn join_failed(&mut self, session: i64, channel: ChannelId, reason: JoinFailure) {
self.transition(|state, cx| vm::events::join_failed(state, cx, session, channel, reason));
}
pub(crate) fn toggle_collapse(&mut self, channel: u64) {
self.transition(|state, cx| logic::toggle_collapse(state, cx, channel));
}
}
#[cfg(test)]
mod tests {
use voelin_core::ts::identity::{Found, LaunchImport};
use super::*;
/// The report is the engine's ([`LaunchImport`], with identities of
/// `tsclientlib`, which the view model crate does not have).
#[test]
fn the_import_is_told_by_nickname() {
let found = |nickname: &str| Found {
nickname: nickname.into(),
identity: tsclientlib::Identity::create(),
source: "settings.db".into(),
selected: false,
};
let report = |added: &[&str], default: Option<&str>, replaced| LaunchImport {
added: added.iter().map(|n| found(n)).collect(),
default: default.map(found),
replaced,
};
let told = logic::imported_status;
assert_eq!(told(&report(&[], None, false)), None);
assert_eq!(
told(&report(&["Main"], Some("Main"), false)).unwrap(),
"Using your TeamSpeak identity \u{201c}Main\u{201d}"
);
assert_eq!(
told(&report(&["Main", "Alt"], None, false)).unwrap(),
"Imported 2 identities from TeamSpeak: Main, Alt"
);
// Imported earlier, now ours instead of the one the app made.
assert_eq!(
told(&report(&[], Some("Main"), true)).unwrap(),
"You now use your TeamSpeak identity \u{201c}Main\u{201d}; your previous one is kept"
);
}
}
+8
View File
@@ -0,0 +1,8 @@
//! Servers: bookmarks, connecting and observing, the rail, the sidebar's
//! server card and the channel tree. What the state does (which server is
//! shown, how it is observed, the rail, the card and the tree as plain data,
//! joining a channel) is in `voelin_ui_vm::servers::logic`; `bind` has the
//! store and the secrets, the engine's commands and the Bridge and model
//! writes.
mod bind;
-308
View File
@@ -1,308 +0,0 @@
//! The settings page (audio, push-to-talk, H.264, crash reports), the
//! About page's notices, and the local volume of clients.
use slint::{ComponentHandle, SharedString};
use tracing::warn;
use voelin_core::settings::{AUDIO, CRASH_REPORTS};
use voelin_core::{Command, Source, VoiceState};
use voelin_platform::{crash, notices};
use crate::app::{App, Bridge, later, model};
use crate::settings::{self, CLIENT_PLAYBACK, ClientPlayback, DeviceChoices};
use crate::vm::bridge::{AudioForm, ClientAudio};
impl App {
pub(crate) fn open_settings(&mut self) {
let list = |devices: voelin_audio::Result<Vec<voelin_audio::device::DeviceInfo>>,
input: bool| {
let devices = devices.unwrap_or_else(|e| {
warn!("cannot list audio devices: {e}");
Vec::new()
});
devices
.into_iter()
.map(|d| {
let default = if input { d.default_input } else { d.default_output };
(d.id, d.name, default)
})
.collect::<Vec<_>>()
};
let inputs = list(voelin_audio::device::input_devices(), true);
let outputs = list(voelin_audio::device::output_devices(), false);
self.state.inputs = DeviceChoices::new(&inputs, self.state.audio.input_device.as_deref());
self.state.outputs =
DeviceChoices::new(&outputs, self.state.audio.output_device.as_deref());
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let names = |c: &DeviceChoices| model(c.names.iter().map(SharedString::from).collect());
bridge.set_input_devices(names(&self.state.inputs));
bridge.set_output_devices(names(&self.state.outputs));
bridge.set_audio(
settings::audio_form(&self.state.audio, &self.state.inputs, &self.state.outputs).into(),
);
bridge.set_global_ptt(self.state.settings.global_ptt);
bridge.set_ptt_key(self.state.settings.ptt_key.clone().into());
bridge.set_h264_enabled(self.state.settings.openh264);
bridge.set_image_cache_usage(crate::images::usage_text().into());
self.refresh_h264();
self.refresh_identities();
}
pub(crate) fn close_settings(&mut self) {
self.set_mic_test(false);
self.save_audio();
}
pub(crate) fn audio_changed(&mut self, form: &AudioForm) {
let audio = settings::apply_audio_form(
form,
&self.state.audio,
&self.state.inputs,
&self.state.outputs,
);
if audio == self.state.audio {
return;
}
self.state.audio = audio;
self.state.audio_dirty = true;
self.engine.send(Command::SetAudioSettings(Box::new(self.state.audio.clone())));
}
pub(crate) fn save_audio(&mut self) {
if !self.state.audio_dirty {
return;
}
self.state.audio_dirty = false;
if let Err(e) = self.prefs.set(&AUDIO, self.state.audio.clone()) {
warn!(%e, "could not store audio settings");
}
}
pub(crate) fn set_mic_test(&mut self, on: bool) {
if self.state.mic_test == on {
return;
}
self.state.mic_test = on;
self.engine.send(Command::TestMicrophone { on });
if let Some(ui) = self.ui.upgrade() {
let bridge = ui.global::<Bridge>();
bridge.set_mic_test(on);
if !on {
bridge.set_input_level(-100.0);
}
}
}
pub(crate) fn apply_ptt(&mut self, enabled: bool, key: String) {
let key = key.trim().to_owned();
self.state.settings.global_ptt = enabled;
if !key.is_empty() {
self.state.settings.ptt_key = key.clone();
}
self.store_settings();
self.ptt.set((enabled && !key.is_empty()).then_some(key));
}
pub(crate) fn set_ptt_status(&mut self, status: String) {
if let Some(ui) = self.ui.upgrade() {
ui.global::<Bridge>().set_ptt_status(status.into());
}
}
pub(crate) fn set_h264(&mut self, enabled: bool) {
self.state.settings.openh264 = enabled;
self.store_settings();
self.video.set_h264(enabled);
self.refresh_h264();
}
pub(crate) fn download_h264(&mut self) {
let runtime = self.engine.runtime().clone();
self.video.download_h264(&runtime, |download| {
later(move |app| {
app.video.downloaded(download, app.state.settings.openh264);
app.refresh_h264();
});
});
self.refresh_h264();
}
fn refresh_h264(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let (loaded, status) = self.video.h264_status();
bridge.set_h264_loaded(loaded);
bridge.set_h264_busy(status.starts_with("Downloading"));
bridge.set_h264_status(status.into());
}
/// Switches the About page and the settings show.
pub(crate) fn refresh_settings_flags(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
bridge.set_h264_enabled(self.state.settings.openh264);
bridge.set_h264_attribution(notices::OPENH264_ATTRIBUTION.into());
bridge.set_crash_reports(self.state.settings.crash_reports);
}
/// The transmit mode for the voice controls (Hold to talk shows for
/// push-to-talk) before the settings page fills the whole form: only
/// `transmit` changes, as the device lists are not read yet.
pub(crate) fn refresh_transmit(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let mut form = bridge.get_audio();
form.transmit = settings::transmit_index(self.state.audio.transmit);
bridge.set_audio(form);
}
pub(crate) fn set_crash_reports(&mut self, enabled: bool) {
self.state.settings.crash_reports = enabled;
// Also in the blob, for older versions.
self.store_settings();
if let Err(e) = self.prefs.set(&CRASH_REPORTS, enabled) {
warn!(%e, "could not store the crash report setting");
}
crash::set_enabled(enabled);
}
/// A notice while crash reports are on disk.
pub(crate) fn refresh_crash_notice(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let text = match crash::pending_reports() {
Ok(reports) if !reports.is_empty() => {
let newest = &reports[reports.len() - 1];
let saved = match reports.len() {
1 => "1 crash report is saved".to_owned(),
n => format!("{n} crash reports are saved"),
};
format!("The app crashed earlier ({}). {saved} on this device.", newest.summary)
}
_ => String::new(),
};
ui.global::<Bridge>().set_crash_notice(text.into());
}
pub(crate) fn open_crash_folder(&mut self) {
let result = crash::dir().ok_or_else(|| "no crash report folder".to_owned());
if let Err(e) =
result.and_then(|dir| crate::app::open_path(&dir).map_err(|e| e.to_string()))
{
self.set_status(format!("Cannot open the crash report folder: {e}"));
}
}
pub(crate) fn delete_crash_reports(&mut self) {
match crash::clear() {
Ok(n) => self.set_status(format!("Deleted {n} crash reports")),
Err(e) => self.set_status(format!("Cannot delete the crash reports: {e}")),
}
self.refresh_crash_notice();
}
/// The third-party notices, one model entry per line.
pub(crate) fn load_notices(&mut self) {
if self.notices_loaded {
return;
}
let Some(ui) = self.ui.upgrade() else { return };
let lines: Vec<SharedString> = notices::text().lines().map(SharedString::from).collect();
ui.global::<Bridge>().set_notices(model(lines));
self.notices_loaded = true;
}
// Local volume and mute of clients.
/// Fill the volume dialog for `client` of the current session.
pub(crate) fn open_client(&mut self, client: u16) -> bool {
let Some(id) = self.state.current else { return false };
let Some(info) = self.view().and_then(|v| v.presence.clients.get(&client)).cloned() else {
return false;
};
let playback = info
.uid
.as_ref()
.and_then(|uid| self.state.playback.get(uid))
.copied()
.unwrap_or_default();
self.state.playback_dialog = Some((id, client, info.uid.clone()));
if let Some(ui) = self.ui.upgrade() {
ui.global::<Bridge>().set_client_audio(
ClientAudio {
id: client as i32,
name: info.nickname.into(),
volume: playback.volume * 100.0,
muted: playback.muted,
streaming: info.streaming == Some(true),
}
.into(),
);
}
true
}
pub(crate) fn client_playback_changed(&mut self, form: &ClientAudio) {
let Some((session, client, uid)) = self.state.playback_dialog.clone() else { return };
let playback =
ClientPlayback { volume: (form.volume / 100.0).clamp(0.0, 4.0), muted: form.muted };
let session = session as u64;
self.engine.send(Command::SetClientVolume { session, client, volume: playback.volume });
self.engine.send(Command::SetClientMuted { session, client, muted: playback.muted });
// Kept by unique id; clients without one only for this connection.
if let Some(uid) = uid {
if playback.is_default() {
self.state.playback.remove(&uid);
} else {
self.state.playback.insert(uid, playback);
}
if let Err(e) = self.prefs.set(&CLIENT_PLAYBACK, self.state.playback.clone()) {
warn!(%e, "could not store client volumes");
}
}
self.refresh_tree();
}
/// `VOELIN_OPEN=client`: the volume dialog of the first client that is not us.
pub(crate) fn open_first_client(&mut self) {
let Some(view) = self.view().filter(|v| v.state.own_client.is_some()) else { return };
let own = view.state.own_client;
let mut others: Vec<_> =
view.presence.clients.values().filter(|c| Some(c.id) != own && !c.is_query).collect();
others.sort_by_key(|c| c.id);
let Some(id) = others.first().map(|c| c.id) else { return };
self.open_client_pending = false;
if self.open_client(id)
&& let Some(ui) = self.ui.upgrade()
{
ui.global::<crate::app::Nav>().set_client_open(true);
}
}
/// Send the stored volumes of clients that appeared in a voice session.
pub(crate) fn apply_client_playback(&mut self, session: i64) {
let Some(view) = self.state.sessions.get_mut(&session) else { return };
if view.state.voice != VoiceState::Connected
|| view.state.presence_source != Some(Source::Voice)
{
return;
}
let presence = view.presence.clone();
view.applied_playback.retain(|id| presence.clients.contains_key(id));
for client in presence.clients.values() {
if !view.applied_playback.insert(client.id) {
continue;
}
let stored = client.uid.as_ref().and_then(|uid| self.state.playback.get(uid));
let Some(playback) = stored else { continue };
let (s, c) = (session as u64, client.id);
self.engine.send(Command::SetClientVolume {
session: s,
client: c,
volume: playback.volume,
});
if playback.muted {
self.engine.send(Command::SetClientMuted { session: s, client: c, muted: true });
}
}
}
}
+222
View File
@@ -0,0 +1,222 @@
//! The Slint side of the settings page: the system's audio devices, the
//! hotkey, the codec download and the crash reports, the Bridge writes, and
//! the callbacks' ways into the transitions of
//! `voelin_ui_vm::settings_page::logic`.
use slint::{ComponentHandle, SharedString};
use tracing::warn;
use voelin_core::settings::CRASH_REPORTS;
use voelin_platform::{crash, notices};
use crate::app::{App, Bridge, Nav, later, model};
use crate::settings;
use crate::vm::bridge::{AudioForm, ClientAudio};
use crate::vm::settings_page::logic::{self, Device};
/// The audio devices the system lists in one direction, as `(id, name,
/// is the default)`; none, and a warning, when it cannot list them.
fn devices(
list: voelin_audio::Result<Vec<voelin_audio::device::DeviceInfo>>,
input: bool,
) -> Vec<Device> {
list.unwrap_or_else(|e| {
warn!("cannot list audio devices: {e}");
Vec::new()
})
.into_iter()
.map(|d| {
let default = if input { d.default_input } else { d.default_output };
(d.id, d.name, default)
})
.collect()
}
impl App {
pub(crate) fn open_settings(&mut self) {
let inputs = devices(voelin_audio::device::input_devices(), true);
let outputs = devices(voelin_audio::device::output_devices(), false);
let page = logic::open_settings(&mut self.state, &inputs, &outputs);
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let names = |names: Vec<String>| model(names.into_iter().map(SharedString::from).collect());
bridge.set_input_devices(names(page.input_devices));
bridge.set_output_devices(names(page.output_devices));
bridge.set_audio(page.audio.into());
bridge.set_global_ptt(page.global_ptt);
bridge.set_ptt_key(page.ptt_key.into());
bridge.set_h264_enabled(page.h264_enabled);
bridge.set_image_cache_usage(crate::images::usage_text().into());
self.refresh_h264();
self.refresh_identities();
}
pub(crate) fn close_settings(&mut self) {
if self.transition(logic::close_settings) {
self.mic_test_stopped();
}
}
pub(crate) fn audio_changed(&mut self, form: &AudioForm) {
self.transition(|state, cx| logic::audio_changed(state, cx, form));
}
pub(crate) fn save_audio(&mut self) {
self.transition(logic::save_audio);
}
pub(crate) fn set_mic_test(&mut self, on: bool) {
if self.transition(|state, cx| logic::set_mic_test(state, cx, on)) {
if on {
self.mic_test_started();
} else {
self.mic_test_stopped();
}
}
}
/// The Bridge shows the microphone test running.
fn mic_test_started(&self) {
if let Some(ui) = self.ui.upgrade() {
ui.global::<Bridge>().set_mic_test(true);
}
}
/// The Bridge shows the microphone test over, and its level gone.
fn mic_test_stopped(&self) {
if let Some(ui) = self.ui.upgrade() {
let bridge = ui.global::<Bridge>();
bridge.set_mic_test(false);
bridge.set_input_level(-100.0);
}
}
pub(crate) fn apply_ptt(&mut self, enabled: bool, key: String) {
let hotkey = self.transition(|state, cx| logic::apply_ptt(state, cx, enabled, &key));
self.ptt.set(hotkey);
}
pub(crate) fn set_ptt_status(&mut self, status: String) {
if let Some(ui) = self.ui.upgrade() {
ui.global::<Bridge>().set_ptt_status(status.into());
}
}
pub(crate) fn set_h264(&mut self, enabled: bool) {
self.transition(|state, cx| logic::set_h264(state, cx, enabled));
self.video.set_h264(enabled);
self.refresh_h264();
}
pub(crate) fn download_h264(&mut self) {
let runtime = self.engine.runtime().clone();
self.video.download_h264(&runtime, |download| {
later(move |app| {
app.video.downloaded(download, app.state.settings.openh264);
app.refresh_h264();
});
});
self.refresh_h264();
}
fn refresh_h264(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let (loaded, status) = self.video.h264_status();
let view = logic::h264_view(loaded, status);
bridge.set_h264_loaded(view.loaded);
bridge.set_h264_busy(view.busy);
bridge.set_h264_status(view.status.into());
}
/// Switches the About page and the settings show.
pub(crate) fn refresh_settings_flags(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
bridge.set_h264_enabled(self.state.settings.openh264);
bridge.set_h264_attribution(notices::OPENH264_ATTRIBUTION.into());
bridge.set_crash_reports(self.state.settings.crash_reports);
}
/// The transmit mode for the voice controls (Hold to talk shows for
/// push-to-talk) before the settings page fills the whole form: only
/// `transmit` changes, as the device lists are not read yet.
pub(crate) fn refresh_transmit(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let mut form = bridge.get_audio();
form.transmit = settings::transmit_index(self.state.audio.transmit);
bridge.set_audio(form);
}
pub(crate) fn set_crash_reports(&mut self, enabled: bool) {
self.transition(|state, cx| logic::set_crash_reports(state, cx, enabled));
if let Err(e) = self.prefs.set(&CRASH_REPORTS, enabled) {
warn!(%e, "could not store the crash report setting");
}
crash::set_enabled(enabled);
}
/// A notice while crash reports are on disk ([`logic::crash_notice`]).
pub(crate) fn refresh_crash_notice(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let summaries: Vec<String> = crash::pending_reports()
.map(|reports| reports.into_iter().map(|r| r.summary).collect())
.unwrap_or_default();
ui.global::<Bridge>().set_crash_notice(logic::crash_notice(&summaries).into());
}
pub(crate) fn open_crash_folder(&mut self) {
let result = crash::dir().ok_or_else(|| "no crash report folder".to_owned());
if let Err(e) =
result.and_then(|dir| crate::app::open_path(&dir).map_err(|e| e.to_string()))
{
self.set_status(format!("Cannot open the crash report folder: {e}"));
}
}
pub(crate) fn delete_crash_reports(&mut self) {
match crash::clear() {
Ok(n) => self.set_status(format!("Deleted {n} crash reports")),
Err(e) => self.set_status(format!("Cannot delete the crash reports: {e}")),
}
self.refresh_crash_notice();
}
/// The third-party notices, one model entry per line.
pub(crate) fn load_notices(&mut self) {
if self.notices_loaded {
return;
}
let Some(ui) = self.ui.upgrade() else { return };
let lines: Vec<SharedString> = notices::text().lines().map(SharedString::from).collect();
ui.global::<Bridge>().set_notices(model(lines));
self.notices_loaded = true;
}
// Local volume and mute of clients.
/// Fill the volume dialog for `client` of the current session
/// ([`logic::open_client`]).
pub(crate) fn open_client(&mut self, client: u16) -> bool {
let Some(form) = logic::open_client(&mut self.state, client) else { return false };
if let Some(ui) = self.ui.upgrade() {
ui.global::<Bridge>().set_client_audio(form.into());
}
true
}
pub(crate) fn client_playback_changed(&mut self, form: &ClientAudio) {
self.transition(|state, cx| logic::client_playback_changed(state, cx, form));
}
/// `VOELIN_OPEN=client`: the volume dialog of the first client that is not us.
pub(crate) fn open_first_client(&mut self) {
let Some(id) = logic::first_client(&self.state) else { return };
self.open_client_pending = false;
if self.open_client(id)
&& let Some(ui) = self.ui.upgrade()
{
ui.global::<Nav>().set_client_open(true);
}
}
}
@@ -0,0 +1,6 @@
//! The settings page (audio, push-to-talk, H.264, crash reports), the
//! About page's notices, and the local volume of clients. What the state
//! does is in `voelin_ui_vm::settings_page::logic`; `bind` has the devices,
//! the hotkey, the codec, the crash reports and the Bridge writes.
mod bind;
+1 -1
View File
@@ -423,7 +423,7 @@ impl App {
uids.insert(ids.ts6);
}
}
self.social.own_uids = uids;
self.state.own_uids = uids;
}
/// The identity servers see us as on `bookmark` (the one place that
File diff suppressed because it is too large. Load diff
+254
View File
@@ -0,0 +1,254 @@
//! The Slint side of the social screens: the Bridge writes of the friends,
//! the bell and the search, the desktop toasts, the navigation after a move,
//! and the callbacks' ways into the transitions of
//! `voelin_ui_vm::social::logic`.
use slint::ComponentHandle;
use tracing::debug;
use voelin_model::{ChatMessage, ChatTarget};
use crate::app::{App, Bridge, Nav, Page, SettingsSection};
use crate::settings::{
NOTIFY_EVENTS, NOTIFY_FRIENDS, NOTIFY_MENTIONS, NOTIFY_MESSAGES, NOTIFY_POKES, NotifyLevel,
};
use crate::vm;
use crate::vm::social::logic::{self, ContactMove, Found, SettingsPage};
use crate::vm::social::{NoticeRequest, Spot};
use super::{NoticeKind, NoticeTarget, now_ms};
/// The Slint enum for a page of the settings.
fn section(page: SettingsPage) -> SettingsSection {
match page {
SettingsPage::Account => SettingsSection::Account,
SettingsPage::Profiles => SettingsSection::Profiles,
SettingsPage::Appearance => SettingsSection::Appearance,
SettingsPage::Voice => SettingsSection::Voice,
SettingsPage::Streaming => SettingsSection::Streaming,
SettingsPage::Devices => SettingsSection::Devices,
SettingsPage::Notifications => SettingsSection::Notifications,
SettingsPage::Privacy => SettingsSection::Privacy,
SettingsPage::Keybinds => SettingsSection::Keybinds,
SettingsPage::Integrations => SettingsSection::Integrations,
SettingsPage::Advanced => SettingsSection::Advanced,
}
}
impl App {
/// The avatar picture of someone by unique id, from any session.
pub(crate) fn avatar_of(&self, uid: &str) -> vm::ImageRef {
vm::social::avatar_of(&self.state, uid)
}
/// A server's name: its bookmark's, else what the session calls it.
pub(crate) fn server_name(&self, session: i64) -> String {
vm::social::server_name(&self.state, session)
}
/// Every session where the client with this unique id is, in bookmark
/// order.
pub(crate) fn spots_of(&self, uid: &str) -> Vec<Spot> {
vm::social::spots_of(&self.state, uid)
}
/// Friends page, home's friends and activity, the block list
/// ([`logic::people`]).
pub(crate) fn refresh_people(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let m = &self.models.social;
let people = logic::people(&self.state, &self.social);
m.friends_online.sync(&people.online);
m.friend_activity.sync(&people.activity);
m.blocked.sync(&people.blocked);
bridge.set_contacts_online(people.online_count);
bridge.set_contacts_all(people.all_count);
bridge.set_contacts_blocked(people.blocked_count);
m.contacts.sync(&people.shown);
bridge.set_contact(people.selected.into());
}
pub(crate) fn friends_tab(&mut self, tab: i32) {
self.social_transition(|_, social, cx| logic::set_friends_tab(social, cx, tab));
}
pub(crate) fn search_contacts(&mut self, text: String) {
self.social_transition(|_, social, cx| logic::search_contacts(social, cx, text));
}
pub(crate) fn select_contact(&mut self, uid: String) {
self.social_transition(|_, social, cx| logic::select_contact(social, cx, uid));
}
/// The buttons of a contact: "message", "poke", "join", "watch",
/// "friend", "block", "neutral", "remove", "mute"
/// ([`logic::contact_action`]); what the move needs a window for is done
/// here.
pub(crate) fn contact_action(&mut self, uid: &str, action: &str) {
let next = self.social_transition(|state, social, cx| {
logic::contact_action(state, social, cx, uid, action)
});
match next {
Some(ContactMove::Message) => self.message_person(uid),
Some(ContactMove::Poke(session, client)) => self.ask_poke(session, client),
Some(ContactMove::Join(spot)) => {
self.show_server(spot.session);
self.join_channel(spot.session, spot.channel);
}
Some(ContactMove::Watch(spot)) => {
self.show_server(spot.session);
self.watch_client(spot.client);
}
None => {}
}
}
pub(crate) fn contact_note(&mut self, uid: &str, note: String) {
self.transition(|state, cx| logic::contact_note(state, cx, uid, note));
}
pub(crate) fn contact_volume(&mut self, uid: &str, percent: f32) {
self.transition(|state, cx| logic::contact_volume(state, cx, uid, percent));
}
/// The server page of a session.
pub(crate) fn show_server(&mut self, session: i64) {
if self.state.current != Some(session) {
self.select_server(session);
}
self.navigate(|nav| nav.invoke_show(Page::Server));
}
/// Navigate after the current callback: `Nav`'s functions call back
/// into the app (`Bridge.open-*`), which is borrowed now.
pub(crate) fn navigate(&self, f: impl FnOnce(&Nav) + Send + 'static) {
let weak = self.ui.clone();
let _ = slint::invoke_from_event_loop(move || {
if let Some(ui) = weak.upgrade() {
f(&ui.global::<Nav>());
}
});
}
// The bell.
/// Add a notification as the kind's setting says ([`logic::notify`]),
/// and show it on the desktop if the setting says so.
#[allow(clippy::too_many_arguments)]
pub(crate) fn notify(
&mut self,
kind: NoticeKind,
title: String,
body: String,
target: NoticeTarget,
name: String,
uid: Option<String>,
) {
let key = match kind {
NoticeKind::Mention => &NOTIFY_MENTIONS,
NoticeKind::Poke => &NOTIFY_POKES,
NoticeKind::Message => &NOTIFY_MESSAGES,
NoticeKind::Event => &NOTIFY_EVENTS,
NoticeKind::Friend => &NOTIFY_FRIENDS,
};
let level = self.prefs.get(key);
if level == NotifyLevel::Off {
return;
}
let request = NoticeRequest { kind, title, body, target, name, uid };
if let Some(toast) = logic::notify(&mut self.social, level, self.demo_ui, request, now_ms())
{
let n = voelin_platform::Notification {
urgent: toast.urgent,
..voelin_platform::Notification::new(toast.title, toast.body)
};
self.engine.runtime().spawn(async move {
if let Err(e) = voelin_platform::notify(&n).await {
debug!("no desktop notification: {e}");
}
});
}
self.refresh_notices();
}
/// The bell's notices, and home's unread mentions (the newest three).
pub(crate) fn refresh_notices(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let rows = logic::notice_rows(&self.state, &self.social);
self.models.social.notices.sync(&rows.notices);
self.models.social.mentions.sync(&rows.mentions);
ui.global::<Bridge>().set_notifications_unread(rows.unread);
}
pub(crate) fn mark_notices_read(&mut self) {
logic::mark_notices_read(&mut self.social);
self.refresh_notices();
}
pub(crate) fn clear_notices(&mut self) {
logic::clear_notices(&mut self.social);
self.refresh_notices();
}
/// Open what a notification is about.
pub(crate) fn open_notice(&mut self, key: i32) {
let Some(target) =
self.social_transition(|_, social, cx| logic::open_notice(social, cx, key))
else {
return;
};
self.refresh_notices();
match target {
NoticeTarget::Chat(session, chat) => {
self.show_server(session);
self.open_chat(chat, true);
}
NoticeTarget::Dm(session, uid) => self.open_dm_with(Some(session), &uid),
NoticeTarget::Event(session, _) => {
self.select_server(session);
self.navigate(|nav| nav.invoke_show(Page::Events));
}
NoticeTarget::Contact(_) => self.navigate(|nav| nav.invoke_show(Page::Friends)),
}
}
/// Whether a message is ours.
pub(crate) fn is_own(&self, session: i64, message: &ChatMessage) -> bool {
vm::social::is_own(&self.state, session, message)
}
// The search (Ctrl+K).
/// Fill the results for `text` ([`logic::search`]).
pub(crate) fn search(&mut self, text: String) {
let (items, found) = logic::search(&self.state, &text, |b| self.server_list_icon(b));
self.social.found = found;
self.models.social.search.sync(&items);
}
/// Open a search result.
pub(crate) fn search_activate(&mut self, index: i32) {
let Some(found) =
self.social_transition(|_, social, cx| logic::search_activate(social, cx, index))
else {
return;
};
match found {
Found::Server(id) => self.show_server(id),
Found::Channel(id, channel) => {
self.show_server(id);
self.open_chat(ChatTarget::Channel(channel), true);
}
Found::Person(id, _, Some(uid)) => self.open_dm_with(Some(id), &uid),
Found::Person(id, client, None) => {
self.show_server(id);
self.open_member(i32::from(client));
}
Found::Contact(_) => self.navigate(|nav| nav.invoke_show(Page::Friends)),
Found::Setting(page) => {
let section = section(page);
self.navigate(move |nav| nav.invoke_open_settings(section));
}
}
}
}
+80
View File
@@ -0,0 +1,80 @@
//! People across servers: contacts and where they are (Friends, home), the
//! bell's notifications, pokes, and the search (Ctrl+K). The direct
//! messages are in `messages.rs`, the home page in `home.rs`, a server's
//! events in `events.rs`.
//!
//! Every contact's whereabouts come from the sessions' presence (voice,
//! gateway or query), so they are current for friends and the others alike;
//! [`voelin_core::Event::FriendPresence`] adds when a friend came online, for
//! "12m ago" and the notification. What the screens show and what an event
//! or a move does to them is in `voelin_ui_vm::social::logic`; `bind` has
//! the Bridge writes, the desktop toasts and the navigation.
mod bind;
use crate::app::Bridge;
use crate::bind::rows::Rows;
use crate::vm;
pub(crate) use vm::social::{NoticeKind, NoticeTarget, now_ms};
/// State of the home, friends, messages, bell and search screens: the
/// view model's, with what the messages page keeps.
pub(crate) type Social = vm::social::logic::Social<crate::messages::Dms>;
/// The models of these screens, set on the Bridge once.
pub(crate) struct SocialModels {
pub friends_online: Rows<vm::bridge::ContactItem>,
pub friend_activity: Rows<vm::bridge::ContactItem>,
pub contacts: Rows<vm::bridge::ContactItem>,
pub blocked: Rows<vm::bridge::ContactItem>,
pub live: Rows<vm::bridge::LiveItem>,
pub recent: Rows<vm::bridge::ConversationItem>,
pub sidebar_dms: Rows<vm::bridge::ConversationItem>,
pub conversations: Rows<vm::bridge::ConversationItem>,
pub dm_lines: Rows<vm::bridge::ChatLine>,
pub happenings: Rows<vm::bridge::HappeningItem>,
pub recordings: Rows<vm::bridge::RecordingItem>,
pub notices: Rows<vm::bridge::NoticeItem>,
pub mentions: Rows<vm::bridge::NoticeItem>,
pub search: Rows<vm::bridge::SearchItem>,
pub events: Rows<vm::bridge::EventItem>,
}
impl SocialModels {
pub fn new(bridge: &Bridge) -> Self {
let m = Self {
friends_online: Rows::default(),
friend_activity: Rows::default(),
contacts: Rows::default(),
blocked: Rows::default(),
live: Rows::default(),
recent: Rows::default(),
sidebar_dms: Rows::default(),
conversations: Rows::default(),
dm_lines: Rows::default(),
happenings: Rows::default(),
recordings: Rows::default(),
notices: Rows::default(),
mentions: Rows::default(),
search: Rows::default(),
events: Rows::default(),
};
bridge.set_friends_online(m.friends_online.model());
bridge.set_friend_activity(m.friend_activity.model());
bridge.set_contacts(m.contacts.model());
bridge.set_blocked(m.blocked.model());
bridge.set_live_rooms(m.live.model());
bridge.set_recent_chats(m.recent.model());
bridge.set_sidebar_dms(m.sidebar_dms.model());
bridge.set_conversations(m.conversations.model());
bridge.set_dm_messages(m.dm_lines.model());
bridge.set_happenings(m.happenings.model());
bridge.set_recordings(m.recordings.model());
bridge.set_notifications(m.notices.model());
bridge.set_home_mentions(m.mentions.model());
bridge.set_search_results(m.search.model());
bridge.set_events(m.events.model());
m
}
}
File diff suppressed because it is too large. Load diff
+425
View File
@@ -0,0 +1,425 @@
//! The Slint side of the streams: the Bridge writes of the streams panel,
//! the share dialog and the viewer, the capture and the decoder, the
//! viewer's window. The state and its transitions are in
//! `voelin_ui_vm::streams::logic`.
use std::time::Duration;
use slint::{ComponentHandle, Model};
use tracing::warn;
use voelin_core::media::{Streamer, audio_source_specs};
use voelin_core::settings::{STREAM_AUDIO_SOURCES, STREAM_BITRATE_KBPS, STREAM_FPS};
use voelin_core::stream::StreamSetup;
use super::Share;
use crate::app::{App, Bridge, later, with_app};
use crate::bind::convert;
use crate::video::{self, Capture, Decoder};
use crate::vm::bridge::{ShareForm, SourceItem};
use crate::vm::streams::logic::{
self as logic, CaptureFacts, CaptureStarted, SharePlan, StreamsFacts, viewer_view,
};
/// Show or hide the pointer over `window`. In full screen the player hides
/// it with its controls: Slint applies a TouchArea's cursor only when the
/// pointer moves, so the window is told directly. (No pointer on Android.)
pub(crate) fn show_cursor(window: &slint::Window, shown: bool) {
#[cfg(not(target_os = "android"))]
{
use slint::winit_030::WinitWindowAccessor;
window.with_winit_window(|w| w.set_cursor_visible(shown));
}
#[cfg(target_os = "android")]
let _ = (window, shown);
}
impl App {
/// The streams panel, the voice card's streams and the share card.
pub(crate) fn refresh_streams(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let current = self.state.current;
let capture = self.share.as_ref().map(|s| CaptureFacts {
status: s.capture.status(),
source_name: s.capture.source_name().to_owned(),
has_audio: s.capture.has_audio(),
});
let facts = StreamsFacts {
demo: self.demo,
studio_live_here: current.is_some_and(|c| self.studio_streams_to(c)),
capture: capture.as_ref(),
};
let view = logic::streams_view(&self.state, &facts);
bridge.set_streams_available(view.available);
self.models.streams.sync(&view.items);
bridge.set_can_share(video::AVAILABLE);
let share = view.share;
bridge.set_share_state(share.state.into());
bridge.set_share_busy(share.busy);
bridge.set_share_error(share.error.into());
bridge.set_share_audio(share.audio);
bridge.set_share_requests(share.requests);
self.models.viewers.sync(&share.viewers);
bridge.set_share_status(share.status.into());
}
/// The viewer in the main window and in its own: the same facts, but
/// the main window's player only while the stream is not popped out.
pub(crate) fn refresh_viewer(&self) {
let popped = self.popout.window.is_some();
let Some(watch) = &self.state.watch else {
self.viewer_each(|bridge| {
bridge.set_viewer_open(false);
bridge.set_viewer_popped(popped);
bridge.set_viewer_has_frame(false);
bridge.set_viewer_frame(slint::Image::default());
});
return;
};
if let Some(ui) = self.ui.upgrade() {
let bridge = ui.global::<Bridge>();
let open = watch.shown && !popped && self.watch_here();
if !open && bridge.get_viewer_open() && bridge.get_viewer_fullscreen() {
// The player goes, still in full screen: it may have hidden the cursor.
show_cursor(ui.window(), true);
}
bridge.set_viewer_open(open);
}
if let Some(window) = &self.popout.window {
window.global::<Bridge>().set_viewer_open(true);
}
let decoded = self.decoder.as_ref().map(Decoder::info).unwrap_or_default();
let view = viewer_view(&self.state, watch, &decoded);
// The members are the current server's.
let admin = self.watch_here()
&& self.models.members.rows().iter().any(|m| m.id == view.streamer_id && m.admin);
self.models.qualities.sync(&view.qualities);
let channel = slint::SharedString::from(view.channel.as_str());
let elapsed = slint::SharedString::from(view.elapsed.as_str());
self.viewer_each(|bridge| {
bridge.set_viewer_popped(popped);
bridge.set_viewer_title(view.title.as_str().into());
bridge.set_viewer_status(view.status.as_str().into());
bridge.set_viewer_ended(view.ended);
bridge.set_viewer_has_frame(view.has_frame);
bridge.set_viewer_volume(view.volume);
bridge.set_viewer_info(view.info.as_str().into());
bridge.set_viewer_streamer(view.streamer.as_str().into());
bridge.set_viewer_streamer_avatar(convert::image(&view.avatar));
bridge.set_viewer_streamer_initials(view.initials.as_ref().into());
bridge.set_viewer_streamer_tint(convert::color(view.tint));
bridge.set_viewer_streamer_admin(admin);
bridge.set_viewer_channel(channel.clone());
bridge.set_viewer_elapsed(elapsed.clone());
bridge.set_viewer_count(view.count);
if bridge.get_viewer_quality() != view.quality {
bridge.set_viewer_quality(view.quality);
}
bridge.set_viewer_quality_detail(view.detail.as_str().into());
});
}
/// The watched stream is on the server on screen (or is the local test
/// stream).
pub(crate) fn watch_here(&self) -> bool {
self.state.watch.as_ref().is_some_and(|w| w.here(self.state.current))
}
/// A simulcast layer of the watched stream (0: follow the bandwidth
/// estimate), asked of the streamer; the engine confirms with
/// `WatchLayers`.
pub(crate) fn set_stream_quality(&mut self, index: i32) {
self.transition(|state, cx| logic::set_quality(state, cx, index));
}
/// Once a second: statistics, a capture that ended, decoder problems.
pub(crate) fn tick_streams(&mut self) {
if self.share.as_ref().is_some_and(|s| s.capture.ended()) {
self.transition(logic::capture_ended);
}
if self.state.watch.as_ref().is_some_and(|w| w.connected && !w.has_frame)
&& let Some(error) = self.decoder.as_ref().and_then(Decoder::error)
{
logic::decoder_failed(&mut self.state, &error);
}
if self.state.share.is_some() {
self.refresh_streams();
}
// The share dialog's audio mixer (studio/).
self.mixer_tick();
if self.state.watch.is_some() {
self.refresh_viewer();
}
}
// Sharing.
/// Fill the share dialog: sources and the last choices.
pub(crate) fn open_share(&mut self) -> ShareForm {
let test_pattern = cfg!(debug_assertions)
|| self.demo
|| std::env::var("VOELIN_TEST_PATTERN").is_ok_and(|v| v == "1");
let restorable = self.state.settings.portal_restore_token.is_some();
let sources =
logic::sources_listed(&mut self.state, self.video.sources(test_pattern, restorable));
if let Some(ui) = self.ui.upgrade() {
let items: Vec<SourceItem> = sources
.into_iter()
.map(|(name, detail)| SourceItem { name: name.into(), detail: detail.into() })
.collect();
ui.global::<Bridge>().set_share_sources(convert::model(&items));
}
self.refresh_streams();
// Its audio: the Stream Studio's mixer rows and picker.
self.mixer_show();
let (fps, bitrate) = (self.prefs.get(&STREAM_FPS), self.prefs.get(&STREAM_BITRATE_KBPS));
logic::share_form(&self.state, fps, bitrate)
}
/// The share dialog's form with the test pattern chosen.
fn test_pattern_form(&mut self) -> Option<ShareForm> {
let mut form = self.open_share();
let ui = self.ui.upgrade()?;
let sources = ui.global::<Bridge>().get_share_sources();
let pattern = (0..sources.row_count())
.find(|&i| sources.row_data(i).is_some_and(|s| s.name == "Test pattern"))?;
form.source = pattern as i32;
Some(form)
}
/// Development switch `VOELIN_AUTOSHARE`: share the test pattern once.
pub(crate) fn autoshare(&mut self) {
if !self.autoshare || !self.view().is_some_and(|v| v.streams_available()) {
return;
}
self.autoshare = false;
if let Some(form) = self.test_pattern_form() {
self.start_share(ShareForm { auto_accept: true, ..form });
}
}
/// `VOELIN_OPEN=share:live` with sample data: the test pattern shared
/// with the sample mixer's sources (live at once, `capture_ready`).
pub(crate) fn demo_share(&mut self) {
if let Some(form) = self.test_pattern_form() {
self.start_share(ShareForm { audio: true, ..form });
}
}
pub(crate) fn start_share(&mut self, form: ShareForm) {
let Some(session) = self.state.current else { return };
// The mixer's sources (the sample studio's with VOELIN_DEMO_UI).
let sources = self.studio_settings().get(&STREAM_AUDIO_SOURCES);
let studio_live_here = self.studio_streams_to(session);
let Some(plan) = self.transition(|state, cx| {
logic::plan_share(state, cx, &form, studio_live_here, &sources)
}) else {
return;
};
let SharePlan { session, source, fps, bitrate, request, setup, auto_accept } = plan;
// The next share starts from these.
for result in
[self.prefs.set(&STREAM_FPS, fps), self.prefs.set(&STREAM_BITRATE_KBPS, bitrate)]
{
if let Err(e) = result {
warn!(%e, "could not store the share settings");
}
}
let runtime = self.engine.runtime().clone();
self.video.start_capture(&runtime, source, request, move |result| {
later(move |app| app.capture_ready(session, setup, auto_accept, result));
});
}
/// The capture started (or not): go live.
fn capture_ready(
&mut self,
session: i64,
setup: StreamSetup,
auto_accept: bool,
result: Result<Capture, String>,
) {
let started = result.as_ref().map(started).map_err(Clone::clone);
let (keep, update) = self.with_host(|state, host| {
let mut cx = crate::vm::host::Cx::new(host);
let keep = logic::capture_ready(state, &mut cx, session, setup, auto_accept, started);
(keep, cx.update)
});
// The capture is kept before the update is carried out: the mixer's
// rows it asks for follow it.
if let (true, Ok(capture)) = (keep, result) {
let meters = slint::Timer::default();
meters.start(slint::TimerMode::Repeated, Duration::from_millis(66), || {
with_app(|app| app.studio_meters());
});
self.share = Some(Share { capture, _meters: meters });
}
self.perform(update);
}
pub(crate) fn stop_share(&mut self) {
self.transition(logic::stop_share);
}
/// The running share's streamer (the mixer's rows, studio/).
pub(crate) fn share_streamer(&self) -> Option<&Streamer> {
self.share.as_ref().map(|s| s.capture.streamer())
}
/// `stream.audio_sources` changed (the mixer, the settings, another
/// window): a running share mixes the new sources.
pub(crate) fn share_audio_changed(&mut self) {
if self.share.is_none() {
return;
}
let sources = audio_source_specs(&self.studio_settings().get(&STREAM_AUDIO_SOURCES));
let codecs = self.video.codecs();
let Some(share) = &self.share else { return };
if let Err(e) = share.capture.follow_audio(&codecs, sources) {
self.set_status(format!("Stream audio: {e}"));
}
self.mixer_refresh();
}
pub(crate) fn respond_viewer(&mut self, viewer: u16, accept: bool) {
self.transition(|state, cx| logic::respond_viewer(state, cx, viewer, accept));
}
pub(crate) fn kick_viewer(&mut self, viewer: u16) {
self.transition(|state, cx| logic::kick_viewer(state, cx, viewer));
}
// Watching.
pub(crate) fn watch_stream(&mut self, stream_id: String) {
if stream_id == "demo" && self.demo {
self.start_demo();
return;
}
let Some(session) = self.transition(|state, cx| logic::watch_stream(state, cx, &stream_id))
else {
return;
};
let wake = || later(|app| app.show_picture());
self.decoder = Some(self.video.watch(&self.engine, session as u64, &stream_id, wake));
self.refresh_viewer();
}
/// Watch the stream of `client` (a click on a streaming user in the
/// channel tree or the members): at once if it is known, else as soon as
/// the lookup brings it (it may have started in another channel or
/// before we joined).
pub(crate) fn watch_client(&mut self, client: u16) {
if let Some(id) = self.transition(|state, cx| logic::watch_client(state, cx, client)) {
self.watch_stream(id);
}
}
/// `VOELIN_OPEN=watch`: watch the first stream of our channel.
pub(crate) fn watch_first_stream(&mut self) {
if let Some(id) = logic::first_stream(&self.state) {
self.watch_stream(id);
}
}
/// The local test stream in the viewer (`VOELIN_DEMO_STREAM`).
pub(crate) fn start_demo(&mut self) {
self.transition(logic::start_demo);
let runtime = self.engine.runtime().clone();
let wake = || later(|app| app.show_picture());
self.video.demo(&runtime, wake, |result| {
later(move |app| {
let Some(watch) = app.state.watch.as_mut().filter(|w| w.session.is_none()) else {
return;
};
match result {
Ok(decoder) => app.decoder = Some(decoder),
Err(e) => watch.status = format!("The preview failed: {e}"),
}
app.refresh_viewer();
});
});
}
/// `VOELIN_OPEN=watch` with sample data: the local test pattern in the
/// viewer, dressed as the first stream of our channel.
pub(crate) fn demo_watch(&mut self) {
let sample = logic::demo_sample(&self.state);
self.start_demo();
if let (Some(watch), Some((id, title, streamer))) = (&mut self.state.watch, sample) {
(watch.stream_id, watch.title, watch.streamer) = (id, title, streamer);
}
self.refresh_viewer();
// Its card shows it as watched.
self.refresh_streams();
}
/// A decoded picture is waiting.
fn show_picture(&mut self) {
if self.state.watch.is_none() {
return;
}
let Some(image) = self.decoder.as_ref().and_then(Decoder::take_picture) else { return };
let first = logic::picture_shown(&mut self.state);
// Only the window with the player: each would scale it again.
self.with_player(|bridge, _| bridge.set_viewer_frame(image));
if first {
self.refresh_viewer();
}
}
pub(crate) fn show_viewer(&mut self, shown: bool) {
// Shown in the main window: from a window of its own, it comes back.
if shown && self.popout.window.is_some() {
self.viewer_dock();
return;
}
self.transition(|state, cx| logic::show_viewer(state, cx, shown));
}
/// Stop watching and close the viewer, its own window too.
pub(crate) fn leave_stream(&mut self) {
self.close_popout();
self.stop_watching();
}
/// Stop watching; a window of its own stays (for the next stream).
fn stop_watching(&mut self) {
self.transition(logic::stop_watching);
}
pub(crate) fn set_stream_volume(&mut self, percent: f32) {
self.transition(|state, cx| logic::set_volume(state, cx, percent));
}
pub(crate) fn toggle_fullscreen(&mut self) {
let mut full = false;
self.with_player(|bridge, _| full = !bridge.get_viewer_fullscreen());
self.set_fullscreen(full);
}
/// The window with the player in full screen, or back.
pub(crate) fn set_fullscreen(&self, full: bool) {
self.with_player(|bridge, window| {
if bridge.get_viewer_fullscreen() == full {
return;
}
bridge.set_viewer_fullscreen(full);
window.set_fullscreen(full);
if !full {
// The player that hid the cursor may be gone already.
show_cursor(window, true);
}
});
}
}
/// What the state needs to know of a capture that started.
fn started(capture: &Capture) -> CaptureStarted {
CaptureStarted {
restore_token: capture.restore_token(),
automatic_bitrate: capture.streamer().bitrate_kbps(),
has_audio: capture.has_audio(),
audio_error: capture.audio_error(),
}
}
+19
View File
@@ -0,0 +1,19 @@
//! Streams (TeamSpeak 6): the streams panel, sharing our screen and the
//! viewer. The engine runs the stream sessions; `video.rs` captures,
//! encodes and decodes. What is state of the streams (what we share, what we
//! watch, the rows and texts) is in `voelin_ui_vm::streams::logic`; `bind`
//! has the Bridge writes, the capture and the decoder.
mod bind;
use crate::video::Capture;
pub(crate) use bind::show_cursor;
/// The capture that feeds our stream, while we share (`AppState::share` has
/// the rest): it stops when dropped.
pub(crate) struct Share {
pub capture: Capture,
/// The audio mixer's meters (the studio's rows), about 15 times a second.
_meters: slint::Timer,
}
+6 -6
View File
@@ -490,7 +490,7 @@ impl App {
if self.studio.run.is_some() {
return;
}
if self.share.is_some() {
if self.state.share.is_some() {
self.mixer_refresh();
}
if !self.ui.upgrade().is_some_and(|ui| ui.global::<Nav>().get_share_open()) {
@@ -566,7 +566,7 @@ impl App {
self.studio.models.chat.sync(&lines);
}
/// A chat of session `id` changed (chat.rs): follow it if it is the
/// A chat of session `id` changed (chat/): follow it if it is the
/// stream's.
pub(crate) fn studio_chat_changed(&mut self, id: i64, target: &ChatTarget) {
if self.studio.run.is_some()
@@ -596,7 +596,7 @@ impl App {
let sharing = st
.data
.destination
.is_some_and(|d| self.share.as_ref().is_some_and(|s| s.session == d));
.is_some_and(|d| self.state.share.as_ref().is_some_and(|s| s.session == d));
let session = st.data.stream.as_ref().map(|s| s.session);
let viewer_name = |v: &ViewerInfo| logic::viewer_name(&self.state, session, v.client);
let cx = logic::StatusContext {
@@ -1068,7 +1068,7 @@ impl App {
if self.studio.data.stream.is_some() || self.studio_streamer().is_none() {
return;
}
if self.share.as_ref().is_some_and(|s| s.session == session) {
if self.state.share.as_ref().is_some_and(|s| s.session == session) {
self.set_status("Stop sharing your screen first.");
return;
}
@@ -1253,12 +1253,12 @@ impl App {
});
}
/// A picture of the studio window (screenshots, dev.rs).
/// A picture of the studio window (screenshots, dev/).
pub(crate) fn studio_snapshot(&self) -> Option<SharedPixelBuffer<Rgba8Pixel>> {
self.studio.window.as_ref()?.window().take_snapshot().ok()
}
// Development switches and sample data (dev.rs).
// Development switches and sample data (dev/).
/// `VOELIN_OPEN=studio:<what>`: `window` (the window of its own), `live`,
/// `record`, or a dialog: `source`, `audio`, `camera`, `scene`, `settings`.
+8
View File
@@ -101,3 +101,11 @@ pub(crate) struct StudioState {
meters: Vec<Option<SourceHandle>>,
has_preview: bool,
}
impl StudioState {
/// The Stream Studio streams to `session`: the events of that stream
/// are its own.
pub(crate) fn streams_to(&self, session: i64) -> bool {
self.data.streams_to(session)
}
}
+1 -8
View File
@@ -509,14 +509,7 @@ fn share_rows(
}
/// Share settings from the dialog.
pub(crate) struct CaptureRequest {
pub fps: u32,
pub bitrate_kbps: u32,
pub audio: bool,
/// Mixed into the stream's audio (`stream.audio_sources`).
pub audio_sources: Vec<AudioSourceSpec>,
pub restore_token: Option<String>,
}
pub(crate) use crate::vm::streams::logic::CaptureRequest;
/// A running capture for our stream. Stops when dropped.
pub(crate) struct Capture {
+1 -1
View File
@@ -1,6 +1,6 @@
// Where the user is: the page, open dialogs, panel sizes. Any screen can
// navigate through these functions; Rust sets the same properties for the
// development switch VOELIN_OPEN (src/dev.rs).
// development switch VOELIN_OPEN (src/dev/mod.rs).
import { Bridge, BookmarkForm, ShareForm, EventForm, OfflineForm } from "bridge.slint";
import { StudioBridge } from "studio-bridge.slint";
+153 -35
View File
@@ -22,11 +22,29 @@ crates/voelin-ui-vm/ view models and state, no UI toolkit
studio_bridge.rs the same for the Stream Studio
state.rs AppState, SessionView, Tab, Msg: what the client knows apart from
the window, generic over the list type of a chat tab's lines
servers.rs tree.rs chat.rs social.rs home.rs streams.rs avatar.rs studio/mod.rs
host.rs Host (what a transition asks of its front end), Update (what it
tells: Refresh, status, commands, Persist, ...), Cx
events/ events::apply: what an engine event does to the AppState
(mod.rs; gateway.rs: the gateway's events and directory)
previews.rs pictures linked in chat: which to fetch, the transfers
servers/mod.rs tree.rs chat/mod.rs social/mod.rs home.rs streams/mod.rs avatar.rs studio/mod.rs
pure view models (engine state → bridge structs), unit-tested
chat/logic.rs chat tabs, messages and what is read, pins and topics, files; the
chat view (tabs, lines, divider, drawers) and the user's moves
streams/logic.rs the streams we share and watch: their state, the events and the
user's choices, the streams panel's, the share card's and the
viewer's rows and texts
servers/logic.rs which server is shown and how it is observed, joining a channel;
the rail, the server card and the channel tree as plain data
settings.rs the UI's settings keys, the audio form
settings_pages/logic.rs, studio/logic.rs
the decisions of the settings pages and of the Stream Studio
dev/logic.rs the sample data of `VOELIN_DEMO_UI` as plain values and events
social/logic.rs the friends, the bell and the search as rows, what the user's moves on
them do, and what an event does to the friends, pokes and notices
settings_page/logic.rs
the audio settings page (devices, form, microphone test, push to
talk), the crash notice and the volume dialog of a client
bbcode.rs emoji.rs chat formatting; the Twemoji archive, text → runs of text and emoji
crates/voelin-ui/ the Slint front end
ui/
@@ -53,20 +71,32 @@ crates/voelin-ui/ the Slint front end
phone layout)
assets/ fonts/ (Inter, OFL), icons/ (Lucide, ISC), logo.svg
src/
app.rs setup, the Slint models (`Models`), event dispatch; `App` holds
app.rs setup, the Slint models (`Models`), the event loop; `App` holds
a `voelin_ui_vm::state::AppState` and the window
servers.rs chat.rs members.rs streams.rs settings_page.rs appearance.rs
home.rs social.rs messages.rs events.rs previews.rs popout.rs
the Slint side of each area (social.rs: contacts, the bell and the
search; previews.rs: pictures in chat; popout.rs: the stream's own
window)
host.rs SlintHost (the answers the transitions ask for), `App::handle_event`,
`transition` and `perform`: doing what an `Update` says
members.rs appearance.rs
home.rs messages.rs events.rs previews.rs popout.rs
the Slint side of each area (previews.rs: pictures in chat;
popout.rs: the stream's own window)
chat/ mod.rs, bind.rs: the chat view's Bridge writes and models
servers/ mod.rs, bind.rs: connecting and observing (store, secrets, engine),
the rail, the server card and the tree on the Bridge
social/ mod.rs (the models), bind.rs: contacts, the bell and the search on
the Bridge, the desktop toasts, the navigation after a move
settings_page/ mod.rs, bind.rs: the audio devices, the hotkey, the codec download,
the crash reports and the Bridge writes of the settings page
settings_pages/ mod.rs (Pages), bind.rs: the settings pages on the Bridge
streams/ mod.rs (Share: the capture), bind.rs: the streams panel, the share
dialog and the viewer on the Bridge, the capture and the decoder
studio/ mod.rs (StudioState), bind.rs: the Stream Studio's windows and engine
bind/ callbacks of each area, wired once; convert.rs, convert/items.rs
(plain values → Slint values), rows.rs (a Slint model kept in step
with a plain list)
images.rs the image cache (LRU, bounded by `ui.image_cache_mb`)
dev.rs development switches (screenshots, sample data)
dev/ mod.rs (the switches, listed), bind.rs: the window's size, the
screenshot, the screens opened at start, the sample data fed through
the app's own events
```
Models are created once (`app::Models`) and updated row by row with
@@ -87,12 +117,18 @@ this file is `voelin_ui_vm::chat`. The boundary:
- **Values.** A picture is an `ImageRef` (`Arc<ImageSource>`: a file of the
engine's cache with its stamp, decoded RGBA pixels, SVG or memory bytes,
or none; `size()` reads a file's header). A colour is an `Rgb(u32)`, a
or none; `size()` decodes a raster file once to tell it shows, and parses an SVG, so a
picture with a size is one a front end can draw). A colour is an `Rgb(u32)`, a
shared string an `Arc<str>`, a list a `Vec`. The bridge structs (51 in
`bridge.rs`, 10 in `studio_bridge.rs`) are plain `Clone + PartialEq + Debug`
structs with the field names of the Slint structs in `bridge.slint` and
`studio-bridge.slint`; `MytsBadge` and `MytsForm`, which have no data source
in this build, stay Slint-only.
in this build, stay Slint-only. The crate warns about undocumented public
items (`#![warn(missing_docs)]`) and has none, the mirror modules' 559
fields (460 in `bridge.rs`, 99 in `studio_bridge.rs`) included: 210 carry
the comments of the `.slint` files, and the other 349 (288 in `bridge.rs`,
61 in `studio_bridge.rs`), which had none there, were described from the
code that fills them. No module is exempt from the lint.
- **Lists.** `list::diff(old, new)` gives `Changes`: updates, removals and
insertions by index, in the order to apply them. `bind/rows.rs` applies
them to a `VecModel` and converts only the changed rows; a GPUI view
@@ -106,44 +142,124 @@ this file is `voelin_ui_vm::chat`. The boundary:
`voelin_ui_vm::state`, generic over the list type `L` of a chat tab's
lines: the Slint app plugs in `Rows<ChatLine>` (`app::ChatRows`), a front
end that re-renders can use a `Vec`. `App.state` is the one `AppState`.
- **Events.** `voelin_ui_vm::events::handle(state, social, host, event)` is
the one dispatch: it lets `social::logic::event` look at the event first
(the friends, pokes, offline messages and the notices, which need the state
as it was before the event), then `events::apply` changes the `AppState`,
and returns an `Update`, which says what the front end has to do: the parts
to draw again (`Refresh`, each once however many events set it), the status
line, the engine commands in order, what to keep (`Persist`: a bookmark,
the UI's settings, the audio settings, the clients' volumes), pictures to
decode again, the password dialog, notices for the bell, the chats that
changed and a stream to watch. `Host` is what the transitions ask while
they run: whether the chat or a private chat is on screen, the store's read
markers, the preview limit, the time. The Slint client's
`App::handle_event` is `handle` and then `perform`, which carries the update
out in `host.rs`; a GPUI client calls `handle` and draws what
`Update::refresh` names. The vm tests replay tapes of events against a fake
`Host` (`events/tests.rs`, `social/logic.rs`). `Update::rest` hands back the
events whose state is not in the `AppState`: the Stream Studio's stream
(`StreamState` and `StreamViewers` while `Host::studio_streams_to`),
`SettingChanged`, the answers to the offline message requests
(`RequestDone`, a list that failed; `messages.rs` keeps those for now), and
the rest that no screen looks at. `perform` handles `rest` before it draws
what `Update::refresh` names, as what the front end keeps may be on screen.
The text of an offline message is not in `rest`: `Event::OfflineMessage`
changes the `Social` state (`mail`, and the inbox row turns read) in
`social::logic::event`, so the redraw shows it (a tape test in
`social/logic.rs`). The streams we share and watch are in the `AppState`
(`share`, `watch`; the capture and the decoder are the front end's, and an
update says when to attach or drop them). The friends, the pokes, the
bell's notices, the text of the open
offline message and what the friends page and the search keep are in
`Social` (`social::logic`), which a front end passes to `handle` besides
the `AppState`.
- **Logic and bind.** An area that interleaves decisions with Bridge writes
is split into `<area>/logic.rs` in `voelin-ui-vm` (functions over the
settings service, the `AppState` and plain rows; they return rows,
commands or messages for the status line, and write no Bridge) and
`<area>/bind.rs` in `voelin-ui` (the Bridge and model writes, windows,
timers, threads, engine commands). Done: `settings_pages` and `studio`.
timers, threads, engine commands). Done: `settings_pages`, `studio`, `streams`, `chat`, `servers`, `settings_page`, `social` and `dev`.
The pure code is tested in `voelin-ui-vm` (`cargo test -p voelin-ui-vm`,
no display); the Slint crate's tests are what needs the window types.
### Controllers still to split
Counted as `.set_` calls per file (`grep -c '\.set_'`, the status line's
`set_status` included) before this round's splits; Bridge writes alone are
about four fifths of each. Each one is a slice of the same shape as
`settings_pages` and `studio`: move the decisions into
`voelin-ui-vm/src/<area>/logic.rs`, keep the writes in
`voelin-ui/src/<area>/bind.rs`.
Plan section 6 step 2 (the toolkit-free `voelin-ui-vm` crate) is done: the
view models, the state, the state transition of every engine event and the
decisions of every area controller that interleaved them with Bridge writes
are in `voelin-ui-vm`, and the Slint crate keeps the writes. What is left
for step 3 (the GPUI front end) is the list at the end of this section.
Status at the merge of main 6e0df51 (2026-10-24): the branch carries the
session seam of main (c60acf9) and, since, the CI deploy key, the media codec
test and the seam follow-ups. None of them touches `voelin-ui` or
`voelin-ui-vm`, and the `.set_` counts below were counted again on the merged
tree and are as stated. The colour of a chat's avatar (the server's own for a
server's chat, the title's colour for any other and for a server that is
gone, never black) is `servers::logic::conversation_tint`, which `messages.rs`
calls and a test pins.
The measure is the number of `.set_` calls in the file (`grep -c '\.set_'`):
every setter counts, those of the Bridge, `Nav`, the window, models and the
engine, and the status line's `self.set_status(…)`, which writes the Bridge's
status text too. In the seven largest files before this round's splits
(230 calls: `streams.rs`, `chat.rs`, `app.rs`, `servers.rs`, `settings_page.rs`,
`social.rs` and `dev.rs`) 150 are direct writes to the Bridge (140 written as
`bridge.set_…`, ten as `ui.global::<Bridge>().set_…` or a chained setter;
one of the ten is `set_status_text`, the write inside `set_status`, so it is
not one of the 36) and 36 go through the status line, so Bridge writes are 186
of the 230, about four fifths of those files, and direct ones about two
thirds; the rest are `Nav`, window and engine setters (in `dev.rs` mostly
those). Each controller was a slice of the same shape as `settings_pages` and
`studio`: the decisions moved into
`voelin-ui-vm/src/<area>/logic.rs`, the writes stayed in
`voelin-ui/src/<area>/bind.rs`. The `.set_` calls of each file before and
after, every number counted with that command:
| Area | Before | After |
|---|---|---|
| Stream Studio | `studio.rs` 64 (62 once the view models had moved) | `studio/bind.rs` 58 |
| Settings pages | `settings_pages.rs` 52 | `settings_pages/bind.rs` 51 |
| Streams | `streams.rs` 45 | `streams/bind.rs` 38 |
| Chat | `chat.rs` 38 | `chat/bind.rs` 31 |
| Servers | `servers.rs` 37 | `servers/bind.rs` 31 |
| Audio settings page | `settings_page.rs` 26 | `settings_page/bind.rs` 26 |
| Friends, the bell, search | `social.rs` 23 | `social/bind.rs` 5 and `social/mod.rs` 15 (the models handed to the Bridge once) |
| Development switches | `dev.rs` 23 | `dev/bind.rs` 21 |
| Event dispatch and setup | `app.rs` 38 | `app.rs` 31 and `host.rs` 8 (carrying out an `Update`) |
The Bridge and model writes stay where the toolkit is, and what each write
says now comes from `logic.rs`, which has tests of its own.
Why the studio went before `streams.rs`: it had the most calls, and it is
self-contained. It has its own state (`StudioState`), windows and bridge
(`studio-bridge.slint`), so its decisions moved without touching the event
dispatch of `app.rs`. `streams.rs`, `chat.rs` and the rest of the list were
driven by that dispatch (the watch, share and history events), so they
followed it: the state transition of every engine event came first
(`events::apply`), then the controllers that show the result, `streams` first
as the one whose events were still the front end's.
Still to split before or while the GPUI front end is written (the files as they
stand):
| File | `.set_` calls | What it mixes |
|---|---|---|
| `streams.rs` | 45 | the streams panel, viewer and share dialog: what the voice card, the viewer header and the share form say, with the watch and share bookkeeping |
| `chat.rs` | 38 | the chat view: lines, the unread divider, pins, topics and downloads, with the engine's history batches |
| `app.rs` | 38 | event dispatch and the status line, the toolbar and tree refreshes |
| `servers.rs` | 37 | the rail, the server dialog and the channel tree's refresh |
| `settings_page.rs` | 26 | the audio settings page and the devices |
| `social.rs` | 23 | home's contacts, the bell and the search |
| `dev.rs` | 23 | development switches and the sample data (the switches stay with the window; the sample rows can move) |
| `app.rs` | 31 (4 in tests) | setup and the model hand-off, the status line, `setting_changed` (which setting touches what); the event dispatch itself is `vm::events::handle` and `events::apply`; the toolbar and tree refreshes are `servers/bind.rs` (`refresh_toolbar`, `refresh_tree`), which `app.rs` only calls |
| `images.rs` | 13 | the decoded-picture cache |
| `messages.rs` | 12 | direct messages |
| `messages.rs` | 11 | direct messages |
| `appearance.rs` | 11 | theme, font scale and breakpoints |
| `popout.rs` | 8 | the viewer's own window |
| `members.rs`, `links.rs`, `inbox.rs`, `home.rs`, `events.rs` | 6, 5, 5, 5, 4 | small; split with their neighbours |
Before this round: `studio.rs` had 62 and `settings_pages.rs` 52 (the two
with the most). Their `bind.rs` files still show 58 and 51 `.set_` calls: the
Bridge and model writes stay where the toolkit is, and what each write says
now comes from `logic.rs`, which has tests of its own.
The gate that accepted `voelin-ui-vm` asked for the `app.rs`/`events.rs` split
before the GPUI client. The dispatch is what moved (the `app.rs` part:
`handle` and `apply` in the crate, `host.rs` here); `events.rs` of
`voelin-ui` is no dispatch but the controller of the gateway's events page
(the event form, RSVP, the channels an event can be in), and it is not split.
Neither is the rest of `app.rs` named above: they are the next slices.
## Theme tokens
@@ -423,14 +539,16 @@ with the sample studio's sources, live at once with sample viewers.
## Adding a server
The add-server dialog (`BookmarkDialog` in `screens/dialogs.slint`, logic in
`servers.rs`) asks for the address (host, host:port, IP or server
`servers/`: the decisions in `voelin-ui-vm`'s `servers::logic`, the Slint side
in `servers/bind.rs`) asks for the address (host, host:port, IP or server
nickname; the resolver finds the port through SRV records and TSDNS) and
an optional server password. *Advanced* (open when editing) has the name
and the nickname, and empty fields there are filled in: the name is the
address until the first connection, then the server's own name
(`adopt_server_name`); the nickname is the default identity's (one imported
from TeamSpeak keeps its nickname there), else the system user's, else
"Voelin user"; the identity is the default one, there is no default channel.
(`adopt_server_name` in `voelin-ui-vm`'s `events`); the nickname is the
default identity's (one imported from TeamSpeak keeps its nickname there),
else the system user's, else "Voelin user"; the identity is the default one,
there is no default channel.
There are no gateway or ServerQuery fields: the gateway is looked up from
the address (DNS SRV records, else the gateway's `/.well-known/tsgw`) when
the server is saved, selected or connected
@@ -515,7 +633,7 @@ for importing the official clients' identities on start
the Slint side as `impl App` in `voelin-ui/src/<name>.rs`, with the
decisions in the view-model crate (`<name>/logic.rs`, [Two
crates](#two-crates)).
5. A development switch to open it (`dev.rs`, `VOELIN_OPEN=<name>`), a
5. A development switch to open it (`dev/bind.rs`, `VOELIN_OPEN=<name>`), a
screenshot (below) and a line in this file.
## Settings
@@ -601,7 +719,7 @@ notifications and the home's news show the text on one line
## Development switches and screenshots
Environment variables (see `src/dev.rs`):
Environment variables (see `src/dev/mod.rs`):
- `VOELIN_DEMO_UI=1`: sample servers, channels, members, chat with
formatting and emoji (and two pages of older messages, which load when