Split the servers controller: the rail, the card, the tree and the moves into voelin-ui-vm

servers/logic.rs now has what a server does to the state and says in plain
data: which server is shown and forgotten, how it is observed (a plan:
nothing, retry, gateway, query or discover), what finding the gateways
comes to, joining a channel (a move, the password question, or connecting
into it), the members' search, the voice view and the invite link, and the
rail, the server card and the channel tree as rows and values (rail,
toolbar, tree_view, server_tint). The Slint side (servers/bind.rs) keeps
the store, the secrets and the engine commands, and writes the Bridge and
the models from what the logic returns.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Sonnet 5.5 committed 2026-10-21 12:57:24 +03:00
1 parent 02a3b3eab0
commit 156df9d95b
8 files changed
+1385 -829

No files matched your search

+903
View File
@@ -0,0 +1,903 @@
//! 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`](crate::state::AppState) and say in the
//! [`Cx`](crate::host::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::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::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 {
match voelin_core::versions::resolve(spec) {
Ok(version) => options.client_version = version,
Err(error) => return Err(format!("Invalid client compatibility version: {error}")),
}
}
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 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());
}
/// 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);
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;