Merge main (ad20979) into phase4/session-seam

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

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

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

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

No files matched your search

+121 -544
View File
@@ -3,11 +3,12 @@
//!
//! The screens' logic is elsewhere: servers and the channel tree in
//! `servers.rs`, chat in `chat.rs`, streams in `streams.rs`, the settings
//! page in `settings_page.rs` and `appearance.rs`, the view models in `vm/`,
//! callbacks in `bind/`, development switches in `dev.rs`.
//! page in `settings_page.rs` and `appearance.rs`, the settings pages in
//! `settings_pages/`, the Stream Studio in `studio/`, the view models in the
//! `voelin-ui-vm` crate (`vm`), callbacks in `bind/`, development switches in
//! `dev.rs`.
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::Arc;
@@ -22,22 +23,19 @@ use voelin_core::settings::{
AUDIO, CRASH_REPORTS, IDENTITY_IMPORT, STREAM_DECODER_BACKEND, STREAM_HARDWARE_DECODING,
Settings,
};
use voelin_core::stream::StreamInfo;
use voelin_core::{
AudioSettings, BackendInfo, Command, Engine, Event, History, HistoryMessage, ObserveState,
SessionState, VoiceState,
AudioSettings, BackendInfo, Command, Engine, Event, History, ObserveState, VoiceState,
};
use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, GroupInfo, Presence};
use voelin_model::ChatTarget;
use voelin_platform::crash;
use voelin_store::{Bookmark, MemorySecrets, Secrets, Store};
use crate::bind::rows::Rows;
use crate::hotkey::GlobalPtt;
use crate::settings::{
CLIENT_PLAYBACK, ClientPlaybackMap, DeviceChoices, UI, UiSettings, appearance_keys,
};
use crate::settings::{CLIENT_PLAYBACK, ClientPlaybackMap, UI, UiSettings, appearance_keys};
use crate::streams::{Share, Watch};
use crate::video::Video;
use crate::vm::chat::Previous;
use crate::vm;
slint::include_modules!();
@@ -58,7 +56,7 @@ fn open_settings(dir: &Path, overrides: &[String]) -> Settings {
for key in crate::settings::page_keys() {
prefs.register(key);
}
prefs.register(&crate::studio::STUDIO_UI);
prefs.register(&crate::vm::studio::logic::STUDIO_UI);
let config = std::env::var_os("VOELIN_CONFIG")
.map(PathBuf::from)
.or_else(|| Some(dir.join("config.toml")).filter(|p| p.exists()));
@@ -118,420 +116,72 @@ impl Secrets for FallbackSecrets {
}
}
/// A message of a chat with the handle the UI knows it by: the engine's
/// local ids are 64 bit, a Slint `int` is not.
pub(crate) struct Msg {
pub key: i32,
pub message: HistoryMessage,
}
/// The lines of a chat as the chat view shows them.
pub(crate) type ChatRows = Rows<vm::bridge::ChatLine>;
/// A chat of a session: its lines are the model the chat view shows while
/// the tab is selected, so a new message is one row appended.
pub(crate) struct Tab {
pub target: ChatTarget,
pub title: String,
pub lines: Rc<VecModel<ChatLine>>,
/// The messages, oldest first, by `(ts_ms, id)`.
pub messages: Vec<Msg>,
/// Live messages of a session that keeps no history (no server unique
/// id yet): grouped from the message before, without ids.
pub last: Option<Previous>,
/// Messages not read, not ours: those after `read` (without stored
/// history, those that came while the tab was not on screen).
pub unread: i32,
/// The newest message read, by `(ts_ms, id)`: kept in the store
/// (`chat_reads`) when the tab is left, the session closes and on exit
/// (`App::save_read`). `stored_read` is what the store has.
pub read: Option<(i64, i64)>,
pub stored_read: Option<(i64, i64)>,
/// The message the "New" divider is above: the first that was new when
/// the tab came on screen. It stays until the tab is left.
pub divider: Option<i64>,
/// Nothing older exists as far as the engine can tell.
pub complete: bool,
/// A gateway page arrived: the chat is not only what we saw.
pub synced: bool,
/// An older page was asked for.
pub loading: bool,
/// The next message handle.
next_key: i32,
/// The pins of this chat, once asked for.
pub pins: Vec<crate::chat::PinRow>,
pub pins_loaded: bool,
/// The gateway topics of this chat, and the open one with its messages.
pub topics: Vec<voelin_gateway_proto::TopicInfo>,
pub topics_loaded: bool,
pub topic: Option<i64>,
pub topic_messages: Vec<Msg>,
/// The message jumped to from the pins.
pub marked: Option<i64>,
/// What the lines of `messages` were built from.
pub cache: crate::vm::chat::LineCache,
}
impl Tab {
pub fn new(target: ChatTarget, title: String) -> Self {
Self {
target,
title,
lines: Rc::new(VecModel::default()),
messages: Vec::new(),
last: None,
unread: 0,
read: None,
stored_read: None,
divider: None,
complete: false,
synced: false,
loading: false,
next_key: 1,
pins: Vec::new(),
pins_loaded: false,
topics: Vec::new(),
topics_loaded: false,
topic: None,
topic_messages: Vec::new(),
marked: None,
cache: Default::default(),
}
}
/// A private chat (on the Direct Messages page, not in the chat strip).
pub fn is_private(&self) -> bool {
matches!(self.target, ChatTarget::Private(_))
}
/// A handle for a message that has none yet.
pub fn take_key(&mut self) -> i32 {
self.next_key += 1;
self.next_key
}
pub fn message(&self, key: i32) -> Option<&HistoryMessage> {
self.messages.iter().chain(&self.topic_messages).find(|m| m.key == key).map(|m| &m.message)
}
/// Where each message is and whether it is ours (`own`), for the read
/// markers ([`crate::vm::chat::first_unread`]).
pub fn positions(&self, own: impl Fn(&ChatMessage) -> bool) -> Vec<(i64, i64, bool)> {
self.messages
.iter()
.map(|m| (m.message.message.ts_ms, m.message.id, own(&m.message.message)))
.collect()
}
/// Where the newest message is.
pub fn newest(&self) -> Option<(i64, i64)> {
self.messages.last().map(|m| (m.message.message.ts_ms, m.message.id))
}
/// The tab came on screen: the first new message gets the divider
/// (unless one shows), and everything is read.
pub fn enter(&mut self, own: impl Fn(&ChatMessage) -> bool) {
if self.unread > 0 && self.divider.is_none() {
let first = crate::vm::chat::first_unread(&self.positions(own), self.read);
self.divider = first.map(|i| self.messages[i].message.id);
}
self.catch_up();
}
/// Everything in the tab is read (it is on screen).
pub fn catch_up(&mut self) {
self.read = self.read.max(self.newest());
self.unread = 0;
}
/// Count what is not read: what came after `read`, not ours.
pub fn count_unread(&mut self, own: impl Fn(&ChatMessage) -> bool) {
self.unread = crate::vm::chat::unread_count(&self.positions(own), self.read);
}
/// Start from where the store says the chat was read (`reads`: by the
/// store's name of the chat).
pub fn read_from(&mut self, reads: &HashMap<String, (i64, i64)>) {
if let Some(&read) = reads.get(&crate::chat::store_target(&self.target).key()) {
self.read = self.read.max(Some(read));
self.stored_read = Some(read);
}
}
}
/// A chat of a session (see `voelin_ui_vm::state`).
pub(crate) type Tab = vm::state::Tab<ChatRows>;
/// What we know about one server session.
pub(crate) struct SessionView {
pub state: SessionState,
pub capabilities: Capabilities,
pub presence: Arc<Presence>,
pub collapsed: HashSet<ChannelId>,
pub talking: HashSet<u16>,
pub tabs: Vec<Tab>,
pub current_tab: usize,
/// The chat strip's chat last current (the server's or a channel's): a
/// private chat is current only on the Direct Messages page, and this
/// one is current again when that page is left.
pub channel_tab: ChatTarget,
/// The own channel's tab was focused for this voice connection.
pub focused_own_channel: bool,
/// The streams in our channel (TeamSpeak 6).
pub streams: Vec<StreamInfo>,
/// Clients whose stored volume was sent for this voice connection.
pub applied_playback: HashSet<u16>,
/// Avatar pictures in the engine's cache, by unique id
/// ([`Event::AvatarReady`]).
pub avatars: HashMap<String, PathBuf>,
/// Icons in the engine's cache, by icon id ([`Event::IconReady`]).
pub icons: HashMap<u32, PathBuf>,
/// Banners and badges in the engine's cache, by address
/// ([`Event::PictureReady`]).
pub pictures: HashMap<String, PathBuf>,
/// The server's icon id as its voice connection last told it
/// ([`Event::ServerDetails`]); kept while disconnected, for the rail.
pub server_icon: u32,
/// Bookmark address that supplied this session's icon.
pub icon_address: Option<String>,
/// The server groups in display order ([`Event::Groups`]).
pub server_groups: Vec<GroupInfo>,
/// The channel groups ([`Event::Groups`]).
pub channel_groups: Vec<GroupInfo>,
/// What the session's gateway offers (`voelin_gateway_proto::feature`).
pub gateway_caps: Vec<String>,
/// The client whose member card is open.
pub member_card: Option<u16>,
/// Passwords given for locked channels, until voice disconnects.
pub channel_passwords: HashMap<ChannelId, String>,
/// The channel a voice connection was asked into, until it is joined
/// or joined again (`App::join_after_connect`).
pub join_after_connect: Option<ChannelId>,
/// Viewers of the streams in the gateway's directory, by stream id.
pub stream_viewers: HashMap<String, u32>,
/// Downloads started from chat, by transfer id.
pub downloads: HashMap<u64, crate::chat::Download>,
/// The next transfer id.
pub next_transfer: u64,
/// What the home, messages and events screens keep of the session.
pub extra: crate::social::SessionExtra,
/// Where its chats were read, from the store (by the store's name of
/// the chat), for the server unique id `reads_of`.
pub reads: HashMap<String, (i64, i64)>,
pub reads_of: Option<String>,
}
pub(crate) type SessionView = vm::state::SessionView<ChatRows>;
impl Default for SessionView {
fn default() -> Self {
Self {
state: SessionState::default(),
capabilities: Capabilities::default(),
presence: Arc::default(),
collapsed: HashSet::new(),
talking: HashSet::new(),
tabs: vec![Tab::new(ChatTarget::Server, "Server".into())],
current_tab: 0,
channel_tab: ChatTarget::Server,
focused_own_channel: false,
streams: Vec::new(),
applied_playback: HashSet::new(),
avatars: HashMap::new(),
icons: HashMap::new(),
pictures: HashMap::new(),
server_icon: 0,
icon_address: None,
server_groups: Vec::new(),
channel_groups: Vec::new(),
gateway_caps: Vec::new(),
member_card: None,
channel_passwords: HashMap::new(),
join_after_connect: None,
stream_viewers: HashMap::new(),
downloads: HashMap::new(),
next_transfer: 1,
extra: Default::default(),
reads: HashMap::new(),
reads_of: None,
}
}
}
impl SessionView {
/// Streams can be watched and shared: TeamSpeak 6, connected with voice.
pub fn streams_available(&self) -> bool {
self.capabilities.streams && self.state.voice == VoiceState::Connected
}
/// The channel a client is in.
pub fn channel_of(&self, client: u16) -> Option<u64> {
self.presence.clients.get(&client).map(|c| c.channel)
}
/// The name of a client's channel when it is not ours; empty in ours.
pub fn other_channel_name(&self, client: u16) -> String {
self.channel_of(client)
.filter(|c| Some(*c) != self.state.own_channel)
.and_then(|c| self.presence.channels.get(&c))
.map_or_else(String::new, |c| crate::vm::tree::channel_title(c).0.to_owned())
}
/// A client's nickname, or its id.
pub fn nickname(&self, client: u16) -> String {
self.presence
.clients
.get(&client)
.map_or_else(|| format!("client {client}"), |c| c.nickname.clone())
}
/// Unread messages in the server's and the channels' chats (the rail and
/// the chat strip count them; private chats count on the Direct
/// Messages page).
pub fn channel_unread(&self) -> i32 {
self.tabs.iter().filter(|t| !t.is_private()).map(|t| t.unread).sum()
}
/// Unread messages in private chats.
pub fn private_unread(&self) -> i32 {
self.tabs.iter().filter(|t| t.is_private()).map(|t| t.unread).sum()
}
/// Make tab `index` the current one; the chat strip remembers it unless
/// it is a private chat.
pub fn set_current_tab(&mut self, index: usize) {
self.current_tab = index;
if let Some(tab) = self.tabs.get(index).filter(|t| !t.is_private()) {
self.channel_tab = tab.target.clone();
}
}
/// Focus tab `index`. While a private chat is current (the Direct
/// Messages page shows it, and its composer sends there), a chat of the
/// strip does not take its place: it is the strip's chat, current once
/// that page is left (voice connecting focuses its channel's chat).
pub fn focus_tab(&mut self, index: usize) {
let Some(tab) = self.tabs.get(index) else { return };
if !tab.is_private() && self.tabs.get(self.current_tab).is_some_and(Tab::is_private) {
self.channel_tab = tab.target.clone();
} else {
self.set_current_tab(index);
}
}
/// Remove tab `index`. The current tab stays; when it is this one, the
/// chat strip's next tab takes its place, else its last.
pub fn remove_tab(&mut self, index: usize) -> Tab {
let tab = self.tabs.remove(index);
if self.current_tab > index {
self.current_tab -= 1;
} else if self.current_tab == index {
let (strip, _) = crate::vm::chat::strip(self.tabs.iter().map(|t| &t.target), 0);
let next = strip.iter().find(|&&i| i >= index).or(strip.last()).copied();
self.set_current_tab(next.unwrap_or(0));
}
tab
}
/// Leave a current private chat for the chat strip's last one (the
/// Direct Messages page was left); `true` if the current tab changed.
pub fn leave_private(&mut self) -> bool {
if !self.tabs.get(self.current_tab).is_some_and(Tab::is_private) {
return false;
}
self.current_tab = self.tabs.iter().position(|t| t.target == self.channel_tab).unwrap_or(0);
true
}
/// A new tab for `target`, read as far as the store says.
pub fn new_tab(&self, target: ChatTarget, title: String) -> Tab {
let mut tab = Tab::new(target, title);
tab.read_from(&self.reads);
tab
}
/// The session's gateway offers this feature
/// (`voelin_gateway_proto::feature`).
pub fn gateway_has(&self, feature: &str) -> bool {
self.gateway_caps.iter().any(|c| c == feature)
}
/// The chat history is kept by the engine (it knows the server): its
/// messages come with ids, reactions and pins.
pub fn has_history(&self) -> bool {
self.state.server_uid.is_some()
}
/// The avatar picture of a client, if the engine fetched one.
pub fn avatar(&self, client: u16) -> Option<&PathBuf> {
let uid = self.presence.clients.get(&client)?.uid.as_deref()?;
self.avatars.get(uid)
}
/// The server's icon, if it has one and the engine fetched it.
pub fn server_icon(&self) -> slint::Image {
crate::vm::avatar::image(
self.icons.get(&self.server_icon).filter(|_| self.server_icon != 0),
)
}
/// Icons stay associated with the address that supplied them, including
/// while a reconnect to an edited bookmark is pending or has failed.
pub fn server_icon_for(&self, address: &str) -> slint::Image {
if self.icon_address.as_deref() == Some(address) {
self.server_icon()
} else {
slint::Image::default()
}
}
}
/// What the screens share, apart from the window and the engine.
pub(crate) type AppState = vm::state::AppState<ChatRows>;
/// The models the Bridge shows, created once and updated row by row
/// (`vm::list::sync`).
/// ([`Rows::sync`]).
pub(crate) struct Models {
pub servers: Rc<VecModel<ServerItem>>,
pub tree: Rc<VecModel<TreeItem>>,
pub members: Rc<VecModel<MemberItem>>,
pub server_members: Rc<VecModel<MemberItem>>,
pub servers: Rows<vm::bridge::ServerItem>,
pub tree: Rows<vm::bridge::TreeItem>,
pub members: Rows<vm::bridge::MemberItem>,
pub server_members: Rows<vm::bridge::MemberItem>,
/// The chat strip: the current session's tabs without its private chats.
pub tabs: Rc<VecModel<ChatTab>>,
pub tabs: Rows<vm::bridge::ChatTab>,
/// Which of the session's tabs each of `tabs` is ([`crate::vm::chat::strip`]).
pub strip: RefCell<Vec<usize>>,
pub streams: Rc<VecModel<StreamItem>>,
pub viewers: Rc<VecModel<ViewerItem>>,
pub pins: Rc<VecModel<PinItem>>,
pub topics: Rc<VecModel<TopicItem>>,
pub topic_messages: Rc<VecModel<ChatLine>>,
pub streams: Rows<vm::bridge::StreamItem>,
pub viewers: Rows<vm::bridge::ViewerItem>,
pub pins: Rows<vm::bridge::PinItem>,
pub topics: Rows<vm::bridge::TopicItem>,
pub topic_messages: Rows<vm::bridge::ChatLine>,
/// The quality choices of the watched stream.
pub qualities: Rc<VecModel<slint::SharedString>>,
pub qualities: Rows<Arc<str>>,
/// Shown when there is no chat.
pub no_chat: Rc<VecModel<ChatLine>>,
pub no_chat: Rows<vm::bridge::ChatLine>,
/// Home, friends, messages, the bell, the search, events.
pub social: crate::social::SocialModels,
/// Settings pages.
pub layers: Rc<VecModel<LayerItem>>,
pub audio_sources: Rc<VecModel<AudioSourceItem>>,
pub identities: Rc<VecModel<IdentityItem>>,
pub gateway_config: Rc<VecModel<ConfigItem>>,
pub gateway_perms: Rc<VecModel<PermItem>>,
pub all_settings: Rc<VecModel<SettingItem>>,
pub layers: Rows<vm::bridge::LayerItem>,
pub audio_sources: Rows<vm::bridge::AudioSourceItem>,
pub identities: Rows<vm::bridge::IdentityItem>,
pub gateway_config: Rows<vm::bridge::ConfigItem>,
pub gateway_perms: Rows<vm::bridge::PermItem>,
pub all_settings: Rows<vm::bridge::SettingItem>,
}
impl Models {
fn new(bridge: &Bridge) -> Self {
let models = Self {
servers: Rc::default(),
tree: Rc::default(),
members: Rc::default(),
server_members: Rc::default(),
tabs: Rc::default(),
servers: Rows::default(),
tree: Rows::default(),
members: Rows::default(),
server_members: Rows::default(),
tabs: Rows::default(),
strip: RefCell::new(vec![0]),
streams: Rc::default(),
viewers: Rc::default(),
pins: Rc::default(),
topics: Rc::default(),
topic_messages: Rc::default(),
qualities: Rc::default(),
no_chat: Rc::default(),
streams: Rows::default(),
viewers: Rows::default(),
pins: Rows::default(),
topics: Rows::default(),
topic_messages: Rows::default(),
qualities: Rows::default(),
no_chat: Rows::default(),
social: crate::social::SocialModels::new(bridge),
layers: Rc::default(),
audio_sources: Rc::default(),
identities: Rc::default(),
gateway_config: Rc::default(),
gateway_perms: Rc::default(),
all_settings: Rc::default(),
layers: Rows::default(),
audio_sources: Rows::default(),
identities: Rows::default(),
gateway_config: Rows::default(),
gateway_perms: Rows::default(),
all_settings: Rows::default(),
};
models.attach(bridge);
models
@@ -540,24 +190,24 @@ impl Models {
/// Show the models in `bridge`: the main window's, and the viewer's own
/// window's (its player reads the stream's qualities).
pub(crate) fn attach(&self, bridge: &Bridge) {
bridge.set_servers(ModelRc::from(self.servers.clone()));
bridge.set_tree(ModelRc::from(self.tree.clone()));
bridge.set_members(ModelRc::from(self.members.clone()));
bridge.set_server_members(ModelRc::from(self.server_members.clone()));
bridge.set_tabs(ModelRc::from(self.tabs.clone()));
bridge.set_streams(ModelRc::from(self.streams.clone()));
bridge.set_share_viewers(ModelRc::from(self.viewers.clone()));
bridge.set_pins(ModelRc::from(self.pins.clone()));
bridge.set_topics(ModelRc::from(self.topics.clone()));
bridge.set_topic_messages(ModelRc::from(self.topic_messages.clone()));
bridge.set_viewer_qualities(ModelRc::from(self.qualities.clone()));
bridge.set_messages(ModelRc::from(self.no_chat.clone()));
bridge.set_layers(ModelRc::from(self.layers.clone()));
bridge.set_audio_sources(ModelRc::from(self.audio_sources.clone()));
bridge.set_identities(ModelRc::from(self.identities.clone()));
bridge.set_gateway_config(ModelRc::from(self.gateway_config.clone()));
bridge.set_gateway_perms(ModelRc::from(self.gateway_perms.clone()));
bridge.set_all_settings(ModelRc::from(self.all_settings.clone()));
bridge.set_servers(self.servers.model());
bridge.set_tree(self.tree.model());
bridge.set_members(self.members.model());
bridge.set_server_members(self.server_members.model());
bridge.set_tabs(self.tabs.model());
bridge.set_streams(self.streams.model());
bridge.set_share_viewers(self.viewers.model());
bridge.set_pins(self.pins.model());
bridge.set_topics(self.topics.model());
bridge.set_topic_messages(self.topic_messages.model());
bridge.set_viewer_qualities(self.qualities.model());
bridge.set_messages(self.no_chat.model());
bridge.set_layers(self.layers.model());
bridge.set_audio_sources(self.audio_sources.model());
bridge.set_identities(self.identities.model());
bridge.set_gateway_config(self.gateway_config.model());
bridge.set_gateway_perms(self.gateway_perms.model());
bridge.set_all_settings(self.all_settings.model());
}
}
@@ -567,80 +217,33 @@ pub(crate) struct App {
pub secrets: Box<dyn Secrets>,
pub engine: Engine,
pub identity: tsclientlib::Identity,
pub bookmarks: Vec<Bookmark>,
pub current: Option<i64>,
pub sessions: HashMap<i64, SessionView>,
/// The data the screens share (`voelin_ui_vm::state`).
pub state: AppState,
pub models: Models,
pub status: String,
/// What the toast of the next copy says instead of "Copied" (an invite
/// names its channel and link).
pub copy_note: Option<String>,
/// The members panel's search.
pub member_filter: String,
/// The topics drawer's search.
pub topic_filter: String,
/// The voice channel view is shown (its people come first in the
/// members panel).
pub voice_view: bool,
/// The settings service (shared with the engine); `settings`, `audio`
/// and `playback` are working copies of its keys.
/// The settings service (shared with the engine); `state.settings`,
/// `state.audio` and `state.playback` are working copies of its keys.
pub prefs: Settings,
pub settings: UiSettings,
pub audio: AudioSettings,
/// Audio settings changed since they were last stored.
pub audio_dirty: bool,
pub inputs: DeviceChoices,
pub outputs: DeviceChoices,
pub playback: ClientPlaybackMap,
/// The engine's contacts, by unique id ([`Event::ContactsChanged`]).
pub contacts: HashMap<String, voelin_core::Contact>,
/// The client in the volume dialog: session, client id, unique id.
pub playback_dialog: Option<(i64, u16, Option<String>)>,
/// The locked channel the password dialog is for: session, channel.
pub join_target: Option<(i64, ChannelId)>,
/// Who the poke dialog pokes: session, client, nickname.
pub poke_target: Option<(i64, u16, String)>,
/// The window has the focus (desktop: winit tells; elsewhere assumed):
/// messages are read only then.
pub focused: bool,
/// The chat whose messages are on screen (session, target): when it is
/// left, it is stored and loses its divider (`App::track_reading`).
pub reading: Option<(i64, ChatTarget)>,
pub mic_test: bool,
pub ptt: GlobalPtt,
pub video: Video,
/// Our stream.
pub share: Option<Share>,
/// The capture for a share is being started.
pub share_busy: bool,
pub share_error: String,
/// The stream in the viewer.
pub watch: Option<Watch>,
/// A client whose stream was asked for before it was known (session,
/// client): watched when the lookup brings it.
pub pending_watch: Option<(i64, u16)>,
/// Stream volume in percent, kept between streams.
pub stream_volume: f32,
/// `VOELIN_DEMO_STREAM`: the viewer shows a local test stream.
pub demo: bool,
/// `VOELIN_DEMO_UI`: sample servers, channels and chat (dev.rs).
pub demo_ui: bool,
/// Servers whose gateway was looked up in this run (`discover_gateway`).
pub gateways_looked_up: HashSet<i64>,
/// `VOELIN_AUTOSHARE=test-pattern`: share the test pattern once streams work.
pub autoshare: bool,
/// `VOELIN_OPEN=client`: open the volume dialog of the first other client.
pub open_client_pending: bool,
/// The notices are in the About page's model.
pub notices_loaded: bool,
/// Files being uploaded to a channel from the composer: session,
/// channel and name, so the link can be posted when they are up.
pub uploads: HashMap<u64, (i64, u64, String)>,
/// Home, friends, messages, the bell and the search.
pub social: crate::social::Social,
/// The settings pages of the new design.
pub pages: crate::settings_pages::Pages,
/// The Stream Studio (studio.rs).
/// The Stream Studio (studio/).
pub studio: crate::studio::StudioState,
/// The stream's own window (popout.rs).
pub popout: crate::popout::Popout,
@@ -829,44 +432,18 @@ pub fn run(options: RunOptions) -> Result<()> {
}),
engine: engine.clone(),
identity,
current: bookmarks.first().map(|b| b.id),
bookmarks,
sessions: HashMap::new(),
state: AppState::new(bookmarks, settings, audio, playback),
models,
status: String::new(),
copy_note: None,
member_filter: String::new(),
topic_filter: String::new(),
voice_view: false,
prefs,
settings,
audio,
audio_dirty: false,
inputs: DeviceChoices::default(),
outputs: DeviceChoices::default(),
playback,
contacts: HashMap::new(),
playback_dialog: None,
join_target: None,
poke_target: None,
focused: true,
reading: None,
mic_test: false,
ptt,
video,
share: None,
share_busy: false,
share_error: String::new(),
watch: None,
pending_watch: None,
stream_volume: 100.0,
demo: switches.demo_stream,
demo_ui: switches.demo_ui,
gateways_looked_up: HashSet::new(),
autoshare: switches.autoshare,
open_client_pending: switches.open_client,
notices_loaded: false,
uploads: HashMap::new(),
social: Default::default(),
pages: Default::default(),
studio: Default::default(),
@@ -931,18 +508,18 @@ pub fn run(options: RunOptions) -> Result<()> {
if let Err(e) = app.prefs.flush() {
warn!(%e, "could not store settings");
}
let ids: Vec<i64> = app.sessions.keys().copied().collect();
let ids: Vec<i64> = app.state.sessions.keys().copied().collect();
for id in ids {
app.save_reads(id);
}
app.watch = None;
app.share = None;
if own && !app.demo_ui {
for id in app.sessions.keys() {
for id in app.state.sessions.keys() {
app.engine.send(Command::CloseSession { session: *id as u64 });
}
}
own && !app.sessions.is_empty() && !app.demo_ui
own && !app.state.sessions.is_empty() && !app.demo_ui
});
APP.with(|a| a.borrow_mut().take());
if let Some(runtime) = own_runtime {
@@ -1001,30 +578,30 @@ pub(crate) fn model<T: Clone + 'static>(items: Vec<T>) -> ModelRc<T> {
impl App {
pub fn view_mut(&mut self) -> Option<&mut SessionView> {
let id = self.current?;
Some(self.sessions.entry(id).or_default())
let id = self.state.current?;
Some(self.state.sessions.entry(id).or_default())
}
pub fn view(&self) -> Option<&SessionView> {
self.current.and_then(|id| self.sessions.get(&id))
self.state.current.and_then(|id| self.state.sessions.get(&id))
}
pub fn bookmark(&self, id: i64) -> Option<&Bookmark> {
self.bookmarks.iter().find(|b| b.id == id)
self.state.bookmarks.iter().find(|b| b.id == id)
}
/// Send a command for the current session. Not for the sample
/// sessions of VOELIN_DEMO_UI: the engine would open them for real.
pub fn command(&self, f: impl FnOnce(u64) -> Command) {
if let Some(id) = self.current.filter(|_| !self.demo_ui) {
if let Some(id) = self.state.current.filter(|_| !self.demo_ui) {
self.engine.send(f(id as u64));
}
}
pub fn set_status(&mut self, text: impl Into<String>) {
self.status = text.into();
self.state.status = text.into();
if let Some(ui) = self.ui.upgrade() {
ui.global::<Bridge>().set_status_text(self.status.clone().into());
ui.global::<Bridge>().set_status_text(self.state.status.clone().into());
}
}
@@ -1037,12 +614,12 @@ impl App {
/// Nav.copy put text on the clipboard: one toast says so.
pub fn copied(&mut self) {
let text = self.copy_note.take().unwrap_or_else(|| "Copied".to_owned());
let text = self.state.copy_note.take().unwrap_or_else(|| "Copied".to_owned());
self.set_status(text);
}
pub fn store_settings(&self) {
if let Err(e) = self.prefs.set(&UI, self.settings.clone()) {
if let Err(e) = self.prefs.set(&UI, self.state.settings.clone()) {
warn!(%e, "could not store settings");
}
}
@@ -1051,19 +628,19 @@ impl App {
/// the values the window keeps copies of. The engine applies audio
/// settings itself.
fn setting_changed(&mut self, key: &str) {
if key == AUDIO.name() && !self.audio_dirty {
self.audio = self.prefs.get(&AUDIO);
if key == AUDIO.name() && !self.state.audio_dirty {
self.state.audio = self.prefs.get(&AUDIO);
// The voice controls follow the transmit mode.
self.refresh_transmit();
} else if key == CRASH_REPORTS.name() {
let enabled = self.prefs.get(&CRASH_REPORTS);
if enabled != self.settings.crash_reports {
self.settings.crash_reports = enabled;
if enabled != self.state.settings.crash_reports {
self.state.settings.crash_reports = enabled;
crash::set_enabled(enabled);
self.refresh_settings_flags();
}
} else if key == CLIENT_PLAYBACK.name() {
self.playback = self.prefs.get(&CLIENT_PLAYBACK);
self.state.playback = self.prefs.get(&CLIENT_PLAYBACK);
} else if appearance_keys().iter().any(|k| k.name() == key) {
self.apply_appearance();
} else if key == voelin_core::settings::STREAM_AUDIO_SOURCES.name() {
@@ -1085,7 +662,7 @@ impl App {
match event {
Event::State { session, state } => {
let id = session as i64;
let view = self.sessions.entry(id).or_default();
let view = self.state.sessions.entry(id).or_default();
let was_voice = view.state.voice;
let was_observe = view.state.observe;
let was_channel = view.state.own_channel;
@@ -1111,12 +688,12 @@ impl App {
if off(state.voice, state.observe) && !off(was_voice, was_observe) {
self.save_reads(id);
}
let view = self.sessions.entry(id).or_default();
let view = self.state.sessions.entry(id).or_default();
let focus = !view.focused_own_channel;
if state.voice == VoiceState::Connected && was_voice != VoiceState::Connected {
self.set_status("Connected");
}
if self.current == Some(id) {
if self.state.current == Some(id) {
if self.track_reading() {
self.refresh_chat();
}
@@ -1124,7 +701,7 @@ impl App {
// once per connection.
if let (Some(cid), VoiceState::Connected) = (state.own_channel, state.voice) {
self.open_chat(ChatTarget::Channel(cid), focus);
self.sessions.entry(id).or_default().focused_own_channel = true;
self.state.sessions.entry(id).or_default().focused_own_channel = true;
}
}
// Where we are with voice, when it changed here: home's last
@@ -1138,22 +715,22 @@ impl App {
self.refresh_tree();
self.refresh_streams();
self.autoshare();
if self.open_client_pending && self.current == Some(id) {
if self.open_client_pending && self.state.current == Some(id) {
self.open_first_client();
}
self.join_after_connect(id);
}
Event::ServerInfo { session, name, backend, capabilities } => {
self.sessions.entry(session as i64).or_default().capabilities = capabilities;
self.state.sessions.entry(session as i64).or_default().capabilities = capabilities;
self.adopt_server_name(session as i64, &name);
if self.current == Some(session as i64) {
if self.state.current == Some(session as i64) {
self.set_status(connected_status(&name, &backend));
}
self.refresh_streams();
self.autoshare();
}
Event::Presence { session, presence } => {
let view = self.sessions.entry(session as i64).or_default();
let view = self.state.sessions.entry(session as i64).or_default();
// The server chat shows its welcome and host message, with
// their pictures.
let said = crate::chat::server_texts(&view.presence.server)
@@ -1171,7 +748,7 @@ impl App {
if renamed && self.remember_voice(session as i64) {
self.refresh_servers();
}
if self.current == Some(session as i64) {
if self.state.current == Some(session as i64) {
if said {
self.fetch_previews(session as i64);
}
@@ -1185,20 +762,20 @@ impl App {
}
}
Event::Talking { session, client, talking } => {
let view = self.sessions.entry(session as i64).or_default();
let view = self.state.sessions.entry(session as i64).or_default();
if talking {
view.talking.insert(client);
} else {
view.talking.remove(&client);
}
if self.current == Some(session as i64) {
if self.state.current == Some(session as i64) {
self.refresh_tree();
}
}
Event::InputLevel { session, level_db, sending } => {
let shown = match session {
Some(s) => self.current == Some(s as i64),
None => self.mic_test,
Some(s) => self.state.current == Some(s as i64),
None => self.state.mic_test,
};
if shown && let Some(ui) = self.ui.upgrade() {
let bridge = ui.global::<Bridge>();
@@ -1213,7 +790,7 @@ impl App {
// know the server yet): those get ids and reactions instead.
Event::Chat { session, message } => {
let id = session as i64;
if !self.sessions.entry(id).or_default().has_history() {
if !self.state.sessions.entry(id).or_default().has_history() {
self.add_message(id, message);
}
}
@@ -1228,12 +805,12 @@ impl App {
self.gateway_update(session as i64, update);
}
Event::Groups { session, server_groups, channel_groups } => {
let view = self.sessions.entry(session as i64).or_default();
let view = self.state.sessions.entry(session as i64).or_default();
view.server_groups = (*server_groups).clone();
// Display order, as TeamSpeak sorts them.
view.server_groups.sort_by_key(|g| (g.sort_id, g.id));
view.channel_groups = (*channel_groups).clone();
if self.current == Some(session as i64) {
if self.state.current == Some(session as i64) {
self.refresh_tree();
}
}
@@ -1244,11 +821,11 @@ impl App {
}
// Pictures can arrive after the rows were built: draw them again.
Event::AvatarReady { session, client_uid, path, .. } => {
let view = self.sessions.entry(session as i64).or_default();
let view = self.state.sessions.entry(session as i64).or_default();
// A file that arrives again is decoded again if it changed.
crate::images::reloaded(&path);
view.avatars.insert(client_uid, path);
if self.current == Some(session as i64) {
if self.state.current == Some(session as i64) {
self.refresh_tree();
self.refresh_chat();
self.refresh_toolbar();
@@ -1257,21 +834,21 @@ impl App {
}
}
Event::IconReady { session, icon, path } => {
let view = self.sessions.entry(session as i64).or_default();
let view = self.state.sessions.entry(session as i64).or_default();
crate::images::reloaded(&path);
view.icons.insert(icon, path);
self.refresh_servers();
if self.current == Some(session as i64) {
if self.state.current == Some(session as i64) {
self.refresh_tree();
self.refresh_toolbar();
}
}
Event::PictureReady { session, url, path } => {
let view = self.sessions.entry(session as i64).or_default();
let view = self.state.sessions.entry(session as i64).or_default();
// The host banner reloads into the same file.
crate::images::reloaded(&path);
view.pictures.insert(url, path);
if self.current == Some(session as i64) {
if self.state.current == Some(session as i64) {
self.refresh_toolbar();
self.refresh_tree();
self.refresh_chat();
@@ -1282,9 +859,9 @@ impl App {
self.transfer_progress(session as i64, transfer, state);
}
// The engine's contacts would replace the sample ones.
Event::ContactsChanged { .. } if self.demo_ui && !self.contacts.is_empty() => {}
Event::ContactsChanged { .. } if self.demo_ui && !self.state.contacts.is_empty() => {}
Event::ContactsChanged { contacts } => {
self.contacts = contacts.iter().map(|c| (c.uid.clone(), c.clone())).collect();
self.state.contacts = contacts.iter().map(|c| (c.uid.clone(), c.clone())).collect();
self.refresh_member_card();
}
// The sample sessions of VOELIN_DEMO_UI are unknown to the engine.
@@ -1297,7 +874,7 @@ impl App {
Event::SettingRejected { key, message } => {
self.set_status(format!("Setting {key}: {message}"));
}
// The Stream Studio's stream (studio.rs).
// The Stream Studio's stream (studio/).
Event::StreamState { session, state } if self.studio_streams_to(session as i64) => {
self.studio_stream_state(state);
}
@@ -1312,7 +889,7 @@ impl App {
fn tick(&mut self) {
self.tick_streams();
self.tick_pages();
if self.audio_dirty {
if self.state.audio_dirty {
self.save_audio();
}
}
+11 -7
View File
@@ -6,12 +6,13 @@
use slint::ComponentHandle;
use tracing::warn;
use crate::app::{App, AppearanceForm, Bridge, Nav, Theme};
use crate::app::{App, Bridge, Nav, Theme};
use crate::images;
use crate::settings::{
ThemeChoice, UI_FONT_SCALE, UI_IMAGE_CACHE_MB, UI_MEMBERS_WIDTH, UI_NARROW_BREAKPOINT,
UI_THEME, UI_VOICE_COMPACT,
};
use crate::vm::bridge::AppearanceForm;
impl App {
/// Show the current values of the appearance keys.
@@ -33,12 +34,15 @@ impl App {
}
nav.set_voice_compact(self.prefs.get(&UI_VOICE_COMPACT));
let bridge = ui.global::<Bridge>();
bridge.set_appearance(AppearanceForm {
theme: theme.as_str().into(),
font_scale: scale,
narrow_breakpoint: breakpoint as f32,
image_cache_mb: cache_mb as f32,
});
bridge.set_appearance(
AppearanceForm {
theme: theme.as_str().into(),
font_scale: scale,
narrow_breakpoint: breakpoint as f32,
image_cache_mb: cache_mb as f32,
}
.into(),
);
bridge.set_image_cache_usage(images::usage_text().into());
self.theme_windows();
}
+73
View File
@@ -0,0 +1,73 @@
//! Plain view-model values (`voelin-ui-vm`) to Slint values, and back where
//! that can be done. Temporary, like the Slint front end itself: the rows
//! (`items`) are converted when [`super::rows::Rows`] applies a change, so
//! only changed rows pay for it.
use std::rc::Rc;
use std::sync::Arc;
use slint::{Color, Image, ModelRc, Rgba8Pixel, SharedPixelBuffer, SharedString, VecModel};
use voelin_ui_vm::{ImageRef, ImageSource, Rgb};
mod items;
/// An opaque colour.
pub(crate) fn color(c: Rgb) -> Color {
Color::from_rgb_u8(c.r(), c.g(), c.b())
}
/// A colour that may be absent: transparent is the text's own colour.
pub(crate) fn ink(c: Option<Rgb>) -> Color {
c.map(color).unwrap_or_default()
}
/// The opaque colour of a Slint colour (its transparency is dropped).
pub(crate) fn unrgb(c: Color) -> Rgb {
Rgb::new(c.red(), c.green(), c.blue())
}
/// The colour of a Slint colour, none for a transparent one.
pub(crate) fn unink(c: Color) -> Option<Rgb> {
(c.alpha() > 0).then(|| unrgb(c))
}
/// A picture as Slint shows it: files and downloaded pictures through the
/// decoded-picture cache (`images.rs`), pixels as they are.
pub(crate) fn image(picture: &ImageRef) -> Image {
match &**picture {
ImageSource::None => Image::default(),
ImageSource::File { path, .. } => crate::images::file(path),
ImageSource::Rgba { w, h, bytes } => {
Image::from_rgba8(SharedPixelBuffer::<Rgba8Pixel>::clone_from_slice(bytes, *w, *h))
}
ImageSource::Svg(data) => Image::load_from_svg_data(data).unwrap_or_default(),
ImageSource::Memory { key, bytes } => crate::images::picture(key, bytes),
}
}
/// A model of pictures.
pub(crate) fn images(pictures: &[ImageRef]) -> ModelRc<Image> {
ModelRc::from(Rc::new(VecModel::from(pictures.iter().map(image).collect::<Vec<_>>())))
}
/// A model of strings.
pub(crate) fn strings(texts: &[Arc<str>]) -> ModelRc<SharedString> {
ModelRc::from(Rc::new(VecModel::from(
texts.iter().map(|t| SharedString::from(&**t)).collect::<Vec<_>>(),
)))
}
/// The strings of a model.
pub(crate) fn unstrings(model: &ModelRc<SharedString>) -> Vec<Arc<str>> {
slint::Model::iter(model).map(|t| Arc::from(t.as_str())).collect()
}
/// A model of the Slint rows the plain rows convert to.
pub(crate) fn model<V, S: for<'a> From<&'a V> + Clone + 'static>(rows: &[V]) -> ModelRc<S> {
ModelRc::from(Rc::new(VecModel::from(rows.iter().map(S::from).collect::<Vec<_>>())))
}
/// The plain rows of a model.
pub(crate) fn rows<S: Clone + 'static, V: From<S>>(model: &ModelRc<S>) -> Vec<V> {
slint::Model::iter(model).map(V::from).collect()
}
File diff suppressed because it is too large. Load diff
+2
View File
@@ -2,8 +2,10 @@
//! area; each has a `wire` that the window calls once.
mod chat;
pub(crate) mod convert;
mod emoji;
mod pages;
pub(crate) mod rows;
mod servers;
mod settings;
mod social;
+8 -8
View File
@@ -1,4 +1,4 @@
//! The settings pages of the new design (settings_pages.rs).
//! The settings pages of the new design (`settings_pages/`).
use slint::ComponentHandle;
@@ -33,7 +33,7 @@ pub(super) fn wire(ui: &MainWindow) {
});
// Voice & Video.
bridge.on_video_changed(|form| {
with_app(|app| app.video_changed(&form));
with_app(|app| app.video_changed(&form.into()));
});
bridge.on_toggle_camera_preview(|| {
with_app(|app| app.toggle_camera_preview());
@@ -43,10 +43,10 @@ pub(super) fn wire(ui: &MainWindow) {
});
// Streaming.
bridge.on_streaming_changed(|form| {
with_app(|app| app.streaming_changed(&form));
with_app(|app| app.streaming_changed(&form.into()));
});
bridge.on_layer_changed(|index, item| {
with_app(|app| app.layer_changed(index, &item));
with_app(|app| app.layer_changed(index, &item.into()));
});
bridge.on_add_layer(|| {
with_app(|app| app.add_layer());
@@ -55,7 +55,7 @@ pub(super) fn wire(ui: &MainWindow) {
with_app(|app| app.remove_layer(index));
});
bridge.on_audio_source_changed(|index, item| {
with_app(|app| app.audio_source_changed(index, &item));
with_app(|app| app.audio_source_changed(index, &item.into()));
});
bridge.on_add_audio_source(|kind, name| {
with_app(|app| app.add_audio_source(&kind, &name));
@@ -65,13 +65,13 @@ pub(super) fn wire(ui: &MainWindow) {
});
// Notifications, privacy.
bridge.on_notify_changed(|form| {
with_app(|app| app.notify_changed(&form));
with_app(|app| app.notify_changed(&form.into()));
});
bridge.on_test_notification(|| {
with_app(|app| app.test_notification());
});
bridge.on_privacy_changed(|form| {
with_app(|app| app.privacy_changed(&form));
with_app(|app| app.privacy_changed(&form.into()));
});
// Integrations.
bridge.on_gateway_admin(|session| {
@@ -97,7 +97,7 @@ pub(super) fn wire(ui: &MainWindow) {
});
// Advanced.
bridge.on_advanced_changed(|form| {
with_app(|app| app.advanced_changed(&form));
with_app(|app| app.advanced_changed(&form.into()));
});
bridge.on_srtp_move(|index, by| {
with_app(|app| app.srtp_move(index, by));
+138
View File
@@ -0,0 +1,138 @@
//! A Slint list model kept in step with plain rows: the view-model code
//! produces the new list, [`list::diff`](voelin_ui_vm::list::diff) finds
//! the row operations, and only those rows are converted and handed to the
//! `VecModel` (views redraw only the rows that changed: a client that
//! starts talking is one `set_row_data`).
use std::cell::{Ref, RefCell};
use std::rc::Rc;
use std::sync::Arc;
use slint::{Model, ModelRc, SharedString, VecModel};
use voelin_ui_vm::list::{Change, Changes, diff};
/// A plain row that a Slint model shows as another type. Implemented for
/// the bridge structs (`convert/items.rs`).
pub(crate) trait Row: Clone + PartialEq {
/// The Slint type of the row.
type Shown: Clone + 'static;
/// The row as the window shows it.
fn show(&self) -> Self::Shown;
}
impl Row for Arc<str> {
type Shown = SharedString;
fn show(&self) -> SharedString {
SharedString::from(&**self)
}
}
/// The rows of a list as the view model made them (`T`), and the model the
/// window shows.
pub(crate) struct Rows<T: Row> {
model: Rc<VecModel<T::Shown>>,
rows: RefCell<Vec<T>>,
}
impl<T: Row> Default for Rows<T> {
fn default() -> Self {
Self { model: Rc::default(), rows: RefCell::default() }
}
}
impl<T: Row> Rows<T> {
/// The model, for a window property.
pub fn model(&self) -> ModelRc<T::Shown> {
ModelRc::from(self.model.clone())
}
/// The rows now.
pub fn rows(&self) -> Ref<'_, [T]> {
Ref::map(self.rows.borrow(), Vec::as_slice)
}
/// Row `i` now.
pub fn get(&self, i: usize) -> Option<T> {
self.rows.borrow().get(i).cloned()
}
/// Change row `i` to `row` if it differs.
pub fn set(&self, i: usize, row: T) {
let mut rows = self.rows.borrow_mut();
if rows.get(i).is_some_and(|old| *old != row) {
self.model.set_row_data(i, row.show());
rows[i] = row;
}
}
/// Append a row.
pub fn push(&self, row: T) {
self.model.push(row.show());
self.rows.borrow_mut().push(row);
}
/// Make the list `new`, with the fewest row operations.
pub fn sync(&self, new: &[T]) -> Changes {
let mut rows = self.rows.borrow_mut();
let changes = diff(&rows, new);
for change in &changes.0 {
match *change {
Change::Update(i) => self.model.set_row_data(i, new[i].show()),
Change::Remove(i) => {
self.model.remove(i);
}
Change::Insert(i) => self.model.insert(i, new[i].show()),
}
}
changes.apply(&mut rows, new);
changes
}
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Clone, Debug, PartialEq)]
struct Plain(i32);
#[derive(Clone, Debug, PartialEq)]
struct Shown(i32);
impl Row for Plain {
type Shown = Shown;
fn show(&self) -> Shown {
Shown(self.0 * 10)
}
}
fn run(old: &[i32], new: &[i32]) -> Changes {
let rows: Rows<Plain> = Rows::default();
rows.sync(&old.iter().map(|&n| Plain(n)).collect::<Vec<_>>());
let changes = rows.sync(&new.iter().map(|&n| Plain(n)).collect::<Vec<_>>());
let shown: Vec<i32> = rows.model.iter().map(|s| s.0).collect();
assert_eq!(shown, new.iter().map(|n| n * 10).collect::<Vec<_>>(), "{old:?} -> {new:?}");
assert_eq!(rows.rows.borrow().len(), new.len());
changes
}
#[test]
fn the_model_follows_the_rows() {
assert!(run(&[1, 2, 3], &[1, 2, 3]).is_empty());
assert_eq!(run(&[1, 2, 3], &[1, 9, 3]).updated(), 1);
assert_eq!(run(&[1, 2, 3], &[1, 2, 7, 3]).inserted(), 1);
assert_eq!(run(&[1, 2, 3], &[1, 3]).removed(), 1);
run(&[], &[1, 2]);
run(&[1, 2], &[]);
run(&[1, 2, 1], &[1, 1, 2, 1]);
run(&[4, 5, 6], &[1, 2, 3, 4, 5, 6, 7]);
}
#[test]
fn strings_are_rows() {
let rows: Rows<Arc<str>> = Rows::default();
rows.sync(&["720p".into(), "1080p".into()]);
assert_eq!(rows.model().row_data(1).as_deref(), Some("1080p"));
}
}
+9 -5
View File
@@ -25,7 +25,7 @@ pub(super) fn wire(ui: &MainWindow) {
});
bridge.on_join_channel(|cid| {
with_app(|app| {
if let Some(session) = app.current {
if let Some(session) = app.state.current {
app.join_channel(session, cid as ChannelId);
}
});
@@ -45,17 +45,21 @@ pub(super) fn wire(ui: &MainWindow) {
bridge.on_push_to_talk(|on| {
with_app(|app| app.command(|session| Command::SetTransmitting { session, on }));
});
bridge.on_edit_bookmark(|id| with_app(|app| app.bookmark_form(id as i64)).unwrap_or_default());
bridge.on_edit_bookmark(|id| {
with_app(|app| app.bookmark_form(id as i64)).unwrap_or_default().into()
});
bridge.on_save_bookmark(|form| {
with_app(|app| app.save_bookmark(&form));
with_app(|app| app.save_bookmark(&form.into()));
});
bridge.on_save_and_connect(|form| {
with_app(|app| app.save_and_connect(&form.into())).unwrap_or(false)
});
bridge.on_save_and_connect(|form| with_app(|app| app.save_and_connect(&form)).unwrap_or(false));
bridge.on_delete_bookmark(|id| {
with_app(|app| app.delete_bookmark(id as i64));
});
bridge.on_open_client(|id| with_app(|app| app.open_client(id as u16)).unwrap_or(false));
bridge.on_client_audio_changed(|form| {
with_app(|app| app.client_playback_changed(&form));
with_app(|app| app.client_playback_changed(&form.into()));
});
bridge.on_invite(|| with_app(|app| app.invite_link()).unwrap_or_default().into());
// Nav.copy, from any screen.
+3 -3
View File
@@ -13,10 +13,10 @@ pub(super) fn wire(ui: &MainWindow) {
with_app(|app| app.close_settings());
});
bridge.on_audio_changed(|form| {
with_app(|app| app.audio_changed(&form));
with_app(|app| app.audio_changed(&form.into()));
});
bridge.on_toggle_mic_test(|| {
with_app(|app| app.set_mic_test(!app.mic_test));
with_app(|app| app.set_mic_test(!app.state.mic_test));
});
bridge.on_apply_ptt(|enabled, key| {
with_app(|app| app.apply_ptt(enabled, key.to_string()));
@@ -34,7 +34,7 @@ pub(super) fn wire(ui: &MainWindow) {
with_app(|app| app.voice_compact_changed(compact));
});
bridge.on_appearance_changed(|form| {
with_app(|app| app.appearance_changed(&form));
with_app(|app| app.appearance_changed(&form.into()));
});
bridge.on_set_crash_reports(|enabled| {
with_app(|app| app.set_crash_reports(enabled));
+5 -3
View File
@@ -64,7 +64,7 @@ pub(super) fn wire(ui: &MainWindow) {
with_app(|app| app.dm_volume(percent));
});
bridge.on_send_offline(|form| {
with_app(|app| app.send_offline(form));
with_app(|app| app.send_offline(form.into()));
});
// The bell.
@@ -97,8 +97,10 @@ pub(super) fn wire(ui: &MainWindow) {
bridge.on_toggle_event(|id| {
with_app(|app| app.toggle_event(id));
});
bridge.on_edit_event(|id| with_app(|app| app.edit_event(id)).unwrap_or_default());
bridge.on_save_event(|form| with_app(|app| app.save_event(&form)).unwrap_or_default().into());
bridge.on_edit_event(|id| with_app(|app| app.edit_event(id)).unwrap_or_default().into());
bridge.on_save_event(|form| {
with_app(|app| app.save_event(&form.into())).unwrap_or_default().into()
});
bridge.on_delete_event(|id| {
with_app(|app| app.delete_event(id));
});
+2 -2
View File
@@ -4,9 +4,9 @@
use crate::app::{Bridge, with_app};
pub(crate) fn wire(bridge: &Bridge) {
bridge.on_open_share(|| with_app(|app| app.open_share()).unwrap_or_default());
bridge.on_open_share(|| with_app(|app| app.open_share()).unwrap_or_default().into());
bridge.on_start_share(|form| {
with_app(|app| app.start_share(form));
with_app(|app| app.start_share(form.into()));
});
bridge.on_stop_share(|| {
with_app(|app| app.stop_share());
+7 -6
View File
@@ -52,13 +52,13 @@ pub(crate) fn wire(bridge: &StudioBridge) {
with_app(|app| app.studio_add_picked(index(i)));
});
bridge.on_add_source(|form| {
with_app(|app| app.studio_add_source(&form));
with_app(|app| app.studio_add_source(&form.into()));
});
bridge.on_source_form(|source| {
with_app(|app| app.studio_source_form(id(source))).unwrap_or_default()
with_app(|app| app.studio_source_form(id(source))).unwrap_or_default().into()
});
bridge.on_apply_source(|form| {
with_app(|app| app.studio_apply_source(&form));
with_app(|app| app.studio_apply_source(&form.into()));
});
bridge.on_toggle_source(|source| {
with_app(|app| app.studio_toggle_source(id(source)));
@@ -93,7 +93,7 @@ pub(crate) fn wire(bridge: &StudioBridge) {
with_app(|app| app.studio_set_output(&w, &h, &fps));
});
bridge.on_set_layer(|i, layer| {
with_app(|app| app.studio_set_layer(index(i), &layer));
with_app(|app| app.studio_set_layer(index(i), &layer.into()));
});
bridge.on_add_layer(|| {
with_app(|app| app.studio_add_layer());
@@ -120,9 +120,10 @@ pub(crate) fn wire(bridge: &StudioBridge) {
bridge.on_end_stream(|| {
with_app(|app| app.studio_end());
});
bridge.on_settings_form(|| with_app(|app| app.studio_settings_form()).unwrap_or_default());
bridge
.on_settings_form(|| with_app(|app| app.studio_settings_form()).unwrap_or_default().into());
bridge.on_apply_settings(|form| {
with_app(|app| app.studio_apply_settings(&form));
with_app(|app| app.studio_apply_settings(&form.into()));
});
bridge.on_respond_viewer(|client, accept| {
+66 -93
View File
@@ -6,7 +6,7 @@
//! The engine keeps the history: [`Event::ChatHistory`] is an upsert of
//! messages by their local id (see `voelin_core::history`), so a tab holds
//! the messages it was given, ordered by `(ts_ms, id)`, and the lines of
//! the selected tab are rebuilt from them with [`vm::list::sync`], which
//! the selected tab are rebuilt from them and synced ([`Rows::sync`]), which
//! touches only the rows that changed. Sessions the engine keeps no history
//! for (it does not know the server yet) fall back to [`Event::Chat`].
//!
@@ -19,7 +19,7 @@
use std::collections::HashMap;
use std::path::PathBuf;
use slint::{ComponentHandle, ModelRc};
use slint::ComponentHandle;
use voelin_core::gateway::Pin;
use voelin_core::settings::CACHE_FETCH_IMAGES;
use voelin_core::{
@@ -30,11 +30,13 @@ use voelin_gateway_proto::{ErrorCode, TopicInfo, feature};
use voelin_model::{ChatMessage, ChatTarget, HostMessageMode, ServerDetails};
use voelin_store::ChatRead;
use crate::app::{App, Bridge, ChatLine, ChatTab, FileItem, Msg, Nav, PinItem, SessionView, Tab};
use crate::app::{App, Bridge, Nav, SessionView, Tab};
use crate::settings::UI_IMAGE_PREVIEW_KB;
use crate::vm;
use crate::vm::bbcode::LinkKind;
use crate::vm::bridge::{ChatLine, ChatTab, FileItem, PinItem};
use crate::vm::chat::{LineCache, LineCtx, Previous};
use crate::vm::state::{Download, Msg, PinRow, store_target};
/// Where the server's welcome and host message keep what their lines were
/// built from (`LineCache`), apart from the messages' ids.
@@ -61,32 +63,6 @@ pub(crate) fn server_text<'a>(view: &'a SessionView, tab: &Tab, key: i32) -> Opt
server_texts(&view.presence.server).get((-1 - key) as usize).map(|(text, _)| *text)
}
/// The store's name of a chat.
pub(crate) fn store_target(target: &ChatTarget) -> voelin_store::ChatTarget {
match target {
ChatTarget::Server => voelin_store::ChatTarget::Server,
ChatTarget::Channel(cid) => voelin_store::ChatTarget::Channel(*cid),
ChatTarget::Private(uid) => voelin_store::ChatTarget::Private(uid.clone()),
}
}
/// A file being downloaded from a chat message.
pub(crate) struct Download {
/// The message's handle and which of its links this is.
pub key: i32,
pub index: usize,
pub name: String,
pub state: TransferState,
}
/// A pinned message of a chat, with who pinned it.
pub(crate) struct PinRow {
pub key: i32,
pub message: HistoryMessage,
pub by: String,
pub ts_ms: i64,
}
/// "3 min ago", "yesterday", "12 Mar".
fn ago(ts_ms: i64) -> String {
let Some(then) = chrono::DateTime::from_timestamp_millis(ts_ms) else { return String::new() };
@@ -104,10 +80,10 @@ fn ago(ts_ms: i64) -> String {
impl App {
pub(crate) fn open_chat(&mut self, target: ChatTarget, focus: bool) {
let Some(id) = self.current else { return };
let Some(id) = self.state.current else { return };
let index = self.chat_tab(id, target);
if focus {
self.sessions.entry(id).or_default().focus_tab(index);
self.state.sessions.entry(id).or_default().focus_tab(index);
self.prefetch_counts();
self.track_reading();
}
@@ -122,7 +98,7 @@ impl App {
ChatTarget::Private(uid) => self.peer_name(uid, None),
_ => String::new(),
};
let view = self.sessions.entry(id).or_default();
let view = self.state.sessions.entry(id).or_default();
if let Some(i) = view.tabs.iter().position(|t| t.target == target) {
return i;
}
@@ -148,7 +124,7 @@ impl App {
view.set_current_tab(index);
view.tabs[index].topic = None;
}
if let Some(id) = self.current {
if let Some(id) = self.state.current {
self.fetch_previews(id);
}
self.prefetch_counts();
@@ -158,13 +134,13 @@ impl App {
}
pub(crate) fn close_tab(&mut self, index: usize) {
let Some(id) = self.current else { return };
let view = self.sessions.entry(id).or_default();
let Some(id) = self.state.current else { return };
let view = self.state.sessions.entry(id).or_default();
if index == 0 || index >= view.tabs.len() {
return;
}
self.save_read(id, index);
let tab = self.sessions.entry(id).or_default().remove_tab(index);
let tab = self.state.sessions.entry(id).or_default().remove_tab(index);
self.engine.send(Command::CloseChat { session: id as u64, target: tab.target });
self.prefetch_counts();
self.track_reading();
@@ -173,8 +149,8 @@ impl App {
}
pub(crate) fn send_message(&mut self, text: String) {
let Some(id) = self.current else { return };
let Some(view) = self.sessions.get(&id) else { return };
let Some(id) = self.state.current else { return };
let Some(view) = self.state.sessions.get(&id) else { return };
let target = view.tabs[view.current_tab].target.clone();
self.engine.send(Command::SendChat { session: id as u64, target, text });
}
@@ -198,10 +174,10 @@ impl App {
/// A live message of a session without stored history: appended as it
/// comes, without an id.
pub(crate) fn add_message(&mut self, id: i64, message: ChatMessage) {
let current = self.current == Some(id);
let current = self.state.current == Some(id);
let reading = self.reads_now(id);
let new = !self.is_own(id, &message);
let view = self.sessions.entry(id).or_default();
let view = self.state.sessions.entry(id).or_default();
let title = vm::chat::tab_title(&view.presence, &message.target, &message.author_name);
let index = Self::tab_for(view, &message.target, || title);
let seen = reading && view.current_tab == index;
@@ -231,7 +207,7 @@ impl App {
source: HistorySource,
complete: bool,
) {
let current = self.current == Some(id);
let current = self.state.current == Some(id);
let reading = self.reads_now(id);
// A private chat is named after the peer, whoever wrote first.
let peer = match target {
@@ -244,7 +220,7 @@ impl App {
)),
_ => None,
};
let view = self.sessions.entry(id).or_default();
let view = self.state.sessions.entry(id).or_default();
let author = messages.first().map_or("", |m| m.message.author_name.as_str());
let title = peer.unwrap_or_else(|| vm::chat::tab_title(&view.presence, target, author));
let index = Self::tab_for(view, target, || title);
@@ -308,8 +284,8 @@ impl App {
/// The page of messages before the oldest one shown.
pub(crate) fn load_older(&mut self) {
let Some(id) = self.current else { return };
let Some(view) = self.sessions.get_mut(&id) else { return };
let Some(id) = self.state.current else { return };
let Some(view) = self.state.sessions.get_mut(&id) else { return };
let tab = &mut view.tabs[view.current_tab];
if tab.loading || tab.complete {
return;
@@ -329,7 +305,7 @@ impl App {
/// The lines of a tab's messages (`main`) or of its open topic, grouped
/// and with everything the row shows (also the stream chat of the
/// Stream Studio, studio.rs). The server chat starts with what the
/// Stream Studio, studio/). The server chat starts with what the
/// server says to everyone who connects ([`Self::server_lines`]).
pub(crate) fn lines_of(&self, view: &SessionView, tab: &Tab, main: bool) -> Vec<ChatLine> {
let messages = if main { &tab.messages } else { &tab.topic_messages };
@@ -384,7 +360,7 @@ impl App {
cache.keep(ids, messages.len());
}
// Pokes of a private chat's peer show among its messages.
if let (ChatTarget::Private(uid), Some(session)) = (&tab.target, self.current) {
if let (ChatTarget::Private(uid), Some(session)) = (&tab.target, self.state.current) {
lines.extend(self.poke_lines(session, uid));
lines.sort_by_key(|(ts, _)| *ts);
}
@@ -466,14 +442,11 @@ impl App {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let Some(view) = self.view() else {
vm::list::sync(
&self.models.tabs,
&[ChatTab { title: "Server".into(), ..Default::default() }],
);
self.models.tabs.sync(&[ChatTab { title: "Server".into(), ..Default::default() }]);
*self.models.strip.borrow_mut() = vec![0];
bridge.set_current_tab(0);
bridge.set_current_chat(0);
let empty = ModelRc::from(self.models.no_chat.clone());
let empty = self.models.no_chat.model();
if bridge.get_messages() != empty {
bridge.set_messages(empty);
}
@@ -523,7 +496,7 @@ impl App {
}
})
.collect();
vm::list::sync(&self.models.tabs, &tabs);
self.models.tabs.sync(&tabs);
*self.models.strip.borrow_mut() = strip;
if bridge.get_current_tab() != current {
bridge.set_current_tab(current);
@@ -535,9 +508,9 @@ impl App {
if view.has_history() {
let lines = self.lines_of(view, tab, true);
divider = lines.iter().position(|l| l.unread_start);
vm::list::sync(&tab.lines, &lines);
tab.lines.sync(&lines);
}
let lines = ModelRc::from(tab.lines.clone());
let lines = tab.lines.model();
if bridge.get_messages() != lines {
bridge.set_messages(lines);
}
@@ -546,7 +519,7 @@ impl App {
.divider
.and_then(|d| tab.messages.iter().position(|m| m.message.id == d))
.map_or(&[][..], |i| &tab.messages[i..]);
let session = self.current.unwrap_or_default();
let session = self.state.current.unwrap_or_default();
let count = new.iter().filter(|m| !self.is_own(session, &m.message.message)).count();
bridge.set_unread_index(divider.map_or(-1, |i| i as i32));
bridge.set_unread_count(count as i32);
@@ -586,14 +559,14 @@ impl App {
}
})
.collect();
vm::list::sync(&self.models.pins, &pins);
let filter = self.topic_filter.trim().to_lowercase();
self.models.pins.sync(&pins);
let filter = self.state.topic_filter.trim().to_lowercase();
let now = chrono::Utc::now().timestamp_millis();
let topics: Vec<crate::app::TopicItem> = tab
let topics: Vec<vm::bridge::TopicItem> = tab
.topics
.iter()
.filter(|t| filter.is_empty() || t.title.to_lowercase().contains(&filter))
.map(|t| crate::app::TopicItem {
.map(|t| vm::bridge::TopicItem {
id: t.id as i32,
title: t.title.clone().into(),
creator: t.creator.name.clone().into(),
@@ -609,7 +582,7 @@ impl App {
archived: t.archived,
})
.collect();
vm::list::sync(&self.models.topics, &topics);
self.models.topics.sync(&topics);
bridge.set_current_topic(tab.topic.map_or(-1, |t| t as i32));
bridge.set_topic_title(
tab.topic
@@ -618,7 +591,7 @@ impl App {
.unwrap_or_default()
.into(),
);
vm::list::sync(&self.models.topic_messages, &self.lines_of(view, tab, false));
self.models.topic_messages.sync(&self.lines_of(view, tab, false));
}
/// A link in a message was clicked (`masked`: its text shows something
@@ -656,7 +629,7 @@ impl App {
/// New messages of session `id` in its current tab are read as they
/// come: they are on screen in the focused window.
fn reads_now(&self, id: i64) -> bool {
self.focused && self.current == Some(id) && self.chat_shown()
self.state.focused && self.state.current == Some(id) && self.chat_shown()
}
/// After anything that can change which chat is on screen (a tab, a
@@ -664,26 +637,26 @@ impl App {
/// loses its divider; the one on screen, in the focused window, is read
/// (its divider above what was new). `true` if a tab changed.
pub(crate) fn track_reading(&mut self) -> bool {
let open = self.current.filter(|_| self.chat_shown()).and_then(|id| {
let view = self.sessions.get(&id)?;
let open = self.state.current.filter(|_| self.chat_shown()).and_then(|id| {
let view = self.state.sessions.get(&id)?;
Some((id, view.tabs.get(view.current_tab)?.target.clone()))
});
let mut changed = false;
if open != self.reading {
if let Some((id, target)) = self.reading.take()
if open != self.state.reading {
if let Some((id, target)) = self.state.reading.take()
&& let Some(index) = self.tab_index(id, &target)
{
let tab = &mut self.sessions.entry(id).or_default().tabs[index];
let tab = &mut self.state.sessions.entry(id).or_default().tabs[index];
changed |= tab.divider.take().is_some();
self.save_read(id, index);
}
self.reading = open.clone();
self.state.reading = open.clone();
}
if let (true, Some((id, target))) = (self.focused, open)
if let (true, Some((id, target))) = (self.state.focused, open)
&& let Some(index) = self.tab_index(id, &target)
{
let own_uids = &self.social.own_uids;
let view = self.sessions.entry(id).or_default();
let view = self.state.sessions.entry(id).or_default();
let own_client = view.state.own_client;
let tab = &mut view.tabs[index];
let before = (tab.unread, tab.divider);
@@ -695,7 +668,7 @@ impl App {
/// Where the tab of `target` is in session `id`.
fn tab_index(&self, id: i64, target: &ChatTarget) -> Option<usize> {
self.sessions.get(&id)?.tabs.iter().position(|t| t.target == *target)
self.state.sessions.get(&id)?.tabs.iter().position(|t| t.target == *target)
}
/// The current chat came on screen or left it (`Nav.chat-shown`).
@@ -710,7 +683,7 @@ impl App {
/// only).
#[cfg(not(target_os = "android"))]
pub(crate) fn window_focused(&mut self, focused: bool) {
self.focused = focused;
self.state.focused = focused;
if self.track_reading() {
self.refresh_chat();
self.refresh_servers();
@@ -720,8 +693,8 @@ impl App {
/// The current chat is read (the bar over its messages): the divider
/// goes.
pub(crate) fn mark_read(&mut self) {
let Some(id) = self.current else { return };
let Some(view) = self.sessions.get_mut(&id) else { return };
let Some(id) = self.state.current else { return };
let Some(view) = self.state.sessions.get_mut(&id) else { return };
let index = view.current_tab;
let tab = &mut view.tabs[index];
tab.divider = None;
@@ -737,7 +710,7 @@ impl App {
if self.demo_ui {
return;
}
let Some(view) = self.sessions.get_mut(&id) else { return };
let Some(view) = self.state.sessions.get_mut(&id) else { return };
let Some(server_uid) = view.state.server_uid.as_deref() else { return };
let Some(tab) = view.tabs.get_mut(index) else { return };
let Some((ts_ms, message)) = tab.read.filter(|r| tab.stored_read != Some(*r)) else {
@@ -759,7 +732,7 @@ impl App {
/// Store where every chat of session `id` was read (it ended, or the
/// app exits).
pub(crate) fn save_reads(&mut self, id: i64) {
let count = self.sessions.get(&id).map_or(0, |v| v.tabs.len());
let count = self.state.sessions.get(&id).map_or(0, |v| v.tabs.len());
for index in 0..count {
self.save_read(id, index);
}
@@ -769,7 +742,7 @@ impl App {
/// server is known (or another one: the gateway's id wins): its tabs
/// start from there, now and when they open.
pub(crate) fn load_reads(&mut self, id: i64) {
let Some(view) = self.sessions.get_mut(&id) else { return };
let Some(view) = self.state.sessions.get_mut(&id) else { return };
if self.demo_ui || view.state.server_uid.is_none() || view.reads_of == view.state.server_uid
{
return;
@@ -796,8 +769,8 @@ impl App {
}
pub(crate) fn gateway_update(&mut self, id: i64, update: GatewayUpdate) {
let current = self.current == Some(id);
let view = self.sessions.entry(id).or_default();
let current = self.state.current == Some(id);
let view = self.state.sessions.entry(id).or_default();
match update {
GatewayUpdate::Connected { capabilities, .. }
| GatewayUpdate::Capabilities { capabilities } => {
@@ -978,8 +951,8 @@ impl App {
/// The topics drawer's search.
pub(crate) fn search_topics(&mut self, text: String) {
if self.topic_filter != text {
self.topic_filter = text;
if self.state.topic_filter != text {
self.state.topic_filter = text;
self.refresh_chat();
}
}
@@ -1026,7 +999,7 @@ impl App {
/// Download a file a message links, into the download folder.
pub(crate) fn download_file(&mut self, key: i32, index: i32) {
let Some(id) = self.current else { return };
let Some(id) = self.state.current else { return };
let index = index.max(0) as usize;
let Some(file) =
self.message_of(key).and_then(|m| m.message.file_refs().into_iter().nth(index))
@@ -1035,7 +1008,7 @@ impl App {
};
let dir = dirs::download_dir().unwrap_or_else(|| PathBuf::from("."));
let path = dir.join(&file.name);
let view = self.sessions.entry(id).or_default();
let view = self.state.sessions.entry(id).or_default();
let transfer = view.next_transfer;
view.next_transfer += 1;
view.downloads.insert(
@@ -1054,10 +1027,10 @@ impl App {
pub(crate) fn transfer_progress(&mut self, id: i64, transfer: u64, state: TransferState) {
// An upload from the composer: post the file's link once it is up.
if let Some((_, channel, name)) = self.uploads.get(&transfer).cloned() {
if let Some((_, channel, name)) = self.state.uploads.get(&transfer).cloned() {
match &state {
TransferState::Done { size, .. } => {
self.uploads.remove(&transfer);
self.state.uploads.remove(&transfer);
let file = voelin_model::FileRef {
channel,
path: "/".into(),
@@ -1073,11 +1046,11 @@ impl App {
self.set_status(format!("{name} shared"));
}
TransferState::Failed(e) => {
self.uploads.remove(&transfer);
self.state.uploads.remove(&transfer);
self.set_status(format!("Could not upload {name}: {e}"));
}
TransferState::Cancelled => {
self.uploads.remove(&transfer);
self.state.uploads.remove(&transfer);
}
_ => {}
}
@@ -1087,14 +1060,14 @@ impl App {
return;
}
let done = matches!(state, TransferState::Done { .. });
let view = self.sessions.entry(id).or_default();
let view = self.state.sessions.entry(id).or_default();
let Some(entry) = view.downloads.get_mut(&transfer) else { return };
entry.state = state;
let name = entry.name.clone();
if done {
self.set_status(format!("{name} downloaded"));
}
if self.current == Some(id) {
if self.state.current == Some(id) {
self.refresh_chat();
}
}
@@ -1102,8 +1075,8 @@ impl App {
/// Attach a file to the current channel chat: ask for one, upload it
/// into the channel and post its link.
pub(crate) fn attach_file(&mut self) {
let Some(id) = self.current else { return };
let Some(view) = self.sessions.get(&id) else { return };
let Some(id) = self.state.current else { return };
let Some(view) = self.state.sessions.get(&id) else { return };
let ChatTarget::Channel(channel) = view.tabs[view.current_tab].target else {
self.set_status("Files can be attached to a channel's chat.");
return;
@@ -1126,10 +1099,10 @@ impl App {
/// Upload a file into a channel and link it in the chat once it is up.
pub(crate) fn upload(&mut self, id: i64, channel: u64, from: PathBuf) {
let Some(name) = from.file_name().map(|n| n.to_string_lossy().to_string()) else { return };
let view = self.sessions.entry(id).or_default();
let view = self.state.sessions.entry(id).or_default();
let transfer = view.next_transfer;
view.next_transfer += 1;
self.uploads.insert(transfer, (id, channel, name.clone()));
self.state.uploads.insert(transfer, (id, channel, name.clone()));
self.engine.send(Command::UploadFile {
session: id as u64,
transfer,
+21 -27
View File
@@ -83,10 +83,9 @@ use voelin_model::{
};
use voelin_store::{Bookmark, MessageSource};
use crate::app::{
App, Bridge, MainWindow, MobileTab, Nav, Page, RecordingItem, SettingsSection, with_app,
};
use crate::app::{App, Bridge, MainWindow, MobileTab, Nav, Page, SettingsSection, with_app};
use crate::settings::LastVoice;
use crate::vm::bridge::RecordingItem;
/// The switches read at start.
#[derive(Clone, Debug, Default)]
@@ -185,7 +184,7 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running {
}
Some("observe") => {
with_app(|app| {
if let Some(id) = app.current {
if let Some(id) = app.state.current {
app.observe(id);
}
});
@@ -215,7 +214,7 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running {
}
// The current server's dialog, Advanced open.
"bookmark" if arg == "edit" => {
if let Some(id) = with_app(|app| app.current).flatten() {
if let Some(id) = with_app(|app| app.state.current).flatten() {
nav.invoke_edit_server(id as i32);
}
}
@@ -426,9 +425,9 @@ fn late(
/// The current chat's read marker `back` messages before its end, as if
/// they came while away, its "New" divider shown (`VOELIN_OPEN=unread`).
fn open_unread(app: &mut App, back: usize) {
let Some(id) = app.current else { return };
let Some(id) = app.state.current else { return };
let own_uids = app.social.own_uids.clone();
let Some(view) = app.sessions.get_mut(&id) else { return };
let Some(view) = app.state.sessions.get_mut(&id) else { return };
let own_client = view.state.own_client;
let own = |m: &ChatMessage| crate::social::own_message(&own_uids, own_client, m);
let index = view.current_tab;
@@ -484,7 +483,7 @@ fn save_png(image: &SharedPixelBuffer<Rgba8Pixel>, path: &std::path::Path) -> Re
/// channel, which asks for its password; `wrong` as if the server had
/// refused one.
fn open_channel_password(app: &mut App, wrong: bool) {
let Some(session) = app.current else { return };
let Some(session) = app.state.current else { return };
let locked = app
.view()
.and_then(|v| v.presence.channels.values().filter(|c| c.has_password).map(|c| c.id).min());
@@ -550,7 +549,7 @@ fn demo_ui(app: &mut App) {
client_version: None,
cached_server_icon: None,
};
app.bookmarks = vec![
app.state.bookmarks = vec![
Bookmark {
gateway_url: Some("wss://gw.nightfall.example/v1".into()),
..bookmark(DEMO, "Nightfall Guild", "ts.nightfall.example:9987")
@@ -560,12 +559,12 @@ fn demo_ui(app: &mut App) {
];
// Home's "Continue where you left off": a channel of a server without
// voice, so it shows Join.
app.settings.last_voice = Some(LastVoice {
app.state.settings.last_voice = Some(LastVoice {
bookmark: DEMO + 1,
address: "pixel.example".into(),
channel: vec!["Art Corner".into()],
});
app.current = Some(DEMO);
app.state.current = Some(DEMO);
let session = DEMO as u64;
let mut p = Presence { server_name: "Nightfall Guild".into(), ..Default::default() };
@@ -941,7 +940,7 @@ fn demo_social(app: &mut App) {
// The samples came one by one, as new ones do: all are read (no "New"
// line, which a gateway page on screen gets), but for Mira's and
// Lumen's messages, which came while away.
for view in app.sessions.values_mut() {
for view in app.state.sessions.values_mut() {
for tab in &mut view.tabs {
tab.divider = None;
tab.catch_up();
@@ -984,7 +983,7 @@ fn demo_social(app: &mut App) {
});
// The pictures of the links, as if downloaded.
if let Some(view) = app.sessions.get_mut(&DEMO) {
if let Some(view) = app.state.sessions.get_mut(&DEMO) {
for (channel, name) in
[(2, "night-castle.png"), (2, "guild-banner.png"), (2, "map-notes.png")]
{
@@ -996,7 +995,7 @@ fn demo_social(app: &mut App) {
};
view.extra.previews.insert(
crate::previews::link_key(&file),
crate::previews::Preview::Ready(voelin_core::Bytes(
crate::vm::state::Preview::Ready(voelin_core::Bytes(
demo_picture(640, 360, name.len() as u32).into(),
)),
);
@@ -1195,15 +1194,12 @@ fn demo_social(app: &mut App) {
clip: name.contains("clip"),
path: format!("/tmp/{name}").into(),
};
crate::vm::list::sync(
&app.models.social.recordings,
&[
recording("raid-night-2026-10-02.webm", "1.2 GB · 2 Oct 22:41"),
recording("clip-boss-down.mkv", "38.4 MB · 2 Oct 21:57"),
recording("lands-between-stream.mkv", "2.8 GB · 28 Sep 20:12"),
recording("clip-lucky-parry.mkv", "12.1 MB · 28 Sep 19:40"),
],
);
app.models.social.recordings.sync(&[
recording("raid-night-2026-10-02.webm", "1.2 GB · 2 Oct 22:41"),
recording("clip-boss-down.mkv", "38.4 MB · 2 Oct 21:57"),
recording("lands-between-stream.mkv", "2.8 GB · 28 Sep 20:12"),
recording("clip-lucky-parry.mkv", "12.1 MB · 28 Sep 19:40"),
]);
app.refresh_chats();
app.refresh_people();
app.refresh_home();
@@ -1246,7 +1242,7 @@ fn demo_pictures(app: &mut App) {
};
let mut events = vec![Event::ServerDetails {
session,
address: app.bookmarks.iter().find(|b| b.id == DEMO).unwrap().address.clone(),
address: app.state.bookmarks.iter().find(|b| b.id == DEMO).unwrap().address.clone(),
details: Arc::new(voelin_model::ServerDetails {
icon: DEMO_SERVER_ICON,
..Default::default()
@@ -1638,9 +1634,8 @@ fn demo_chat(app: &mut App, session: u64) {
None,
),
];
let mut id = 1;
let mut pinned: Vec<HistoryMessage> = Vec::new();
for (chat, author, client, text, ago, relay, reactions, pin, topic) in lines {
for (id, (chat, author, client, text, ago, relay, reactions, pin, topic)) in (1..).zip(lines) {
let target = if chat == DEMO { ChatTarget::Channel(2) } else { ChatTarget::Server };
let message = HistoryMessage {
id,
@@ -1671,7 +1666,6 @@ fn demo_chat(app: &mut App, session: u64) {
source: HistorySource::Gateway,
complete: false,
});
id += 1;
}
// A server chat besides the channel chat.
app.handle_event(Event::ChatHistory {
-418
View File
@@ -1,418 +0,0 @@
//! Twemoji as images. The software renderer draws no colour glyphs, so the
//! UI shows emoji as pictures: this module reads the packed archive
//! (`assets/twemoji.bin`, made by `scripts/pack-twemoji.py`), finds the
//! picture of a grapheme cluster, splits text into runs of words and emoji,
//! and lists emoji for the picker. Decoding the SVGs into images is
//! `images.rs`' job.
use std::sync::{Arc, Mutex, OnceLock};
use unicode_segmentation::UnicodeSegmentation;
static DATA: &[u8] = include_bytes!("../assets/twemoji.bin");
const MAGIC: &[u8; 8] = b"VTWEMOJ1";
const ENTRY_SIZE: usize = 28;
#[derive(Clone, Copy, Debug)]
struct Block {
offset: u32,
len: u32,
raw_len: u32,
}
#[derive(Clone, Copy, Debug)]
struct Entry {
key: (u32, u16),
category: u16,
block: u32,
offset: u32,
len: u32,
name: (u32, u16),
picker: bool,
}
/// An emoji of the picker.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PickerEmoji {
/// The archive key (`1f600`).
pub key: &'static str,
/// Lower-case name for search and screen readers.
pub name: &'static str,
/// The characters picking it inserts.
pub text: String,
}
/// The packed Twemoji: an index sorted by key and deflate blocks.
pub struct Archive {
entries: Vec<Entry>,
blocks: Vec<Block>,
strings: &'static [u8],
data: &'static [u8],
/// Picker entries (indices into `entries`) in picker order.
picker: Vec<u32>,
/// The last decompressed block: neighbours are often wanted together.
last: Mutex<Option<(u32, Arc<[u8]>)>>,
}
fn u32_at(b: &[u8], at: usize) -> Option<u32> {
Some(u32::from_le_bytes(b.get(at..at + 4)?.try_into().ok()?))
}
fn u16_at(b: &[u8], at: usize) -> Option<u16> {
Some(u16::from_le_bytes(b.get(at..at + 2)?.try_into().ok()?))
}
impl Archive {
/// Parse the index of an archive; `None` if it is malformed.
pub fn parse(bytes: &'static [u8]) -> Option<Self> {
if bytes.get(..8)? != MAGIC {
return None;
}
let count = u32_at(bytes, 8)? as usize;
let block_count = u32_at(bytes, 12)? as usize;
let strings_len = u32_at(bytes, 16)? as usize;
let mut at = 20;
let mut blocks = Vec::with_capacity(block_count);
for _ in 0..block_count {
blocks.push(Block {
offset: u32_at(bytes, at)?,
len: u32_at(bytes, at + 4)?,
raw_len: u32_at(bytes, at + 8)?,
});
at += 12;
}
let mut entries = Vec::with_capacity(count);
for _ in 0..count {
entries.push(Entry {
key: (u32_at(bytes, at)?, u16_at(bytes, at + 4)?),
category: u16_at(bytes, at + 6)?,
block: u32_at(bytes, at + 8)?,
offset: u32_at(bytes, at + 12)?,
len: u32_at(bytes, at + 16)?,
name: (u32_at(bytes, at + 20)?, u16_at(bytes, at + 24)?),
picker: u16_at(bytes, at + 26)? & 1 == 1,
});
at += ENTRY_SIZE;
}
let strings = bytes.get(at..at + strings_len)?;
let data = bytes.get(at + strings_len..)?;
let mut picker: Vec<u32> =
(0..entries.len() as u32).filter(|&i| entries[i as usize].picker).collect();
picker.sort_by_key(|&i| {
let e = &entries[i as usize];
(e.category, e.block, e.offset)
});
Some(Self { entries, blocks, strings, data, picker, last: Mutex::new(None) })
}
fn string(&self, (offset, len): (u32, u16)) -> &'static str {
let (offset, len) = (offset as usize, len as usize);
let strings: &'static [u8] = self.strings;
strings.get(offset..offset + len).and_then(|b| std::str::from_utf8(b).ok()).unwrap_or("")
}
fn find(&self, key: &str) -> Option<&Entry> {
self.entries
.binary_search_by(|e| self.string(e.key).cmp(key))
.ok()
.map(|i| &self.entries[i])
}
/// Number of emoji in the archive.
#[cfg(test)]
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn contains(&self, key: &str) -> bool {
self.find(key).is_some()
}
/// The name of an emoji (lower case), if the archive has it.
#[allow(dead_code, reason = "for screens that label emoji (reactions)")]
pub fn name(&self, key: &str) -> Option<&'static str> {
self.find(key).map(|e| self.string(e.name))
}
/// The SVG of an emoji.
pub fn svg(&self, key: &str) -> Option<Vec<u8>> {
let entry = *self.find(key)?;
let block = self.block(entry.block)?;
let (start, len) = (entry.offset as usize, entry.len as usize);
block.get(start..start + len).map(<[u8]>::to_vec)
}
fn block(&self, index: u32) -> Option<Arc<[u8]>> {
let mut last = self.last.lock().unwrap_or_else(|e| e.into_inner());
if let Some((i, block)) = last.as_ref()
&& *i == index
{
return Some(block.clone());
}
let b = self.blocks.get(index as usize)?;
let compressed = self.data.get(b.offset as usize..(b.offset + b.len) as usize)?;
let raw =
miniz_oxide::inflate::decompress_to_vec_with_limit(compressed, b.raw_len as usize)
.ok()?;
let raw: Arc<[u8]> = raw.into();
*last = Some((index, raw.clone()));
Some(raw)
}
fn picker_emoji(&self, entry: &Entry) -> PickerEmoji {
let key = self.string(entry.key);
PickerEmoji { key, name: self.string(entry.name), text: text_of(key) }
}
/// The picker's emoji of a category: smileys, people, nature, food,
/// activities, travel, objects, symbols, flags (0-8).
pub fn category(&self, category: usize) -> Vec<PickerEmoji> {
self.picker
.iter()
.map(|&i| &self.entries[i as usize])
.filter(|e| e.category as usize == category)
.map(|e| self.picker_emoji(e))
.collect()
}
/// Picker emoji whose name has every word of `query` (case-insensitive).
pub fn search(&self, query: &str) -> Vec<PickerEmoji> {
let words: Vec<String> = query.split_whitespace().map(str::to_lowercase).collect();
if words.is_empty() {
return Vec::new();
}
self.picker
.iter()
.map(|&i| &self.entries[i as usize])
.filter(|e| {
let name = self.string(e.name);
words.iter().all(|w| name.contains(w.as_str()))
})
.map(|e| self.picker_emoji(e))
.collect()
}
}
/// The archive in the binary.
pub fn archive() -> &'static Archive {
static ARCHIVE: OnceLock<Archive> = OnceLock::new();
ARCHIVE.get_or_init(|| Archive::parse(DATA).expect("the bundled emoji archive is valid"))
}
/// Characters shown as emoji even without U+FE0F: Emoji_Presentation=Yes
/// below U+1F000 (above it nearly everything is).
const PRESENTATION_BMP: &[(u32, u32)] = &[
(0x231A, 0x231B),
(0x23E9, 0x23EC),
(0x23F0, 0x23F0),
(0x23F3, 0x23F3),
(0x25FD, 0x25FE),
(0x2614, 0x2615),
(0x2648, 0x2653),
(0x267F, 0x267F),
(0x2693, 0x2693),
(0x26A1, 0x26A1),
(0x26AA, 0x26AB),
(0x26BD, 0x26BE),
(0x26C4, 0x26C5),
(0x26CE, 0x26CE),
(0x26D4, 0x26D4),
(0x26EA, 0x26EA),
(0x26F2, 0x26F3),
(0x26F5, 0x26F5),
(0x26FA, 0x26FA),
(0x26FD, 0x26FD),
(0x2705, 0x2705),
(0x270A, 0x270B),
(0x2728, 0x2728),
(0x274C, 0x274C),
(0x274E, 0x274E),
(0x2753, 0x2755),
(0x2757, 0x2757),
(0x2795, 0x2797),
(0x27B0, 0x27B0),
(0x27BF, 0x27BF),
(0x2B1B, 0x2B1C),
(0x2B50, 0x2B50),
(0x2B55, 0x2B55),
];
fn emoji_presentation(cp: u32) -> bool {
cp >= 0x1F000 || PRESENTATION_BMP.iter().any(|&(lo, hi)| (lo..=hi).contains(&cp))
}
/// Whether a character can start an emoji; text without any is plain.
fn may_be_emoji(c: char) -> bool {
c as u32 >= 0x2000 || c == '\u{FE0F}' || c == '\u{20E3}' || c == '\u{a9}' || c == '\u{ae}'
}
fn key_of(cps: &[u32]) -> String {
cps.iter().map(|cp| format!("{cp:x}")).collect::<Vec<_>>().join("-")
}
/// The characters of an archive key, with U+FE0F after a lone character
/// that is text by default, so other clients show an emoji too.
pub fn text_of(key: &str) -> String {
let cps: Vec<u32> = key.split('-').filter_map(|p| u32::from_str_radix(p, 16).ok()).collect();
let mut text: String = cps.iter().filter_map(|&cp| char::from_u32(cp)).collect();
if cps.len() == 1 && !emoji_presentation(cps[0]) {
text.push('\u{FE0F}');
}
text
}
/// The archive key of a grapheme cluster that is an emoji: code points in
/// hex joined by `-`, without U+FE0F unless the sequence has a ZWJ (as
/// Twemoji names its files).
pub fn key_for(grapheme: &str) -> Option<String> {
let cps: Vec<u32> = grapheme.chars().map(|c| c as u32).collect();
let first = *cps.first()?;
let has_vs = cps.contains(&0xFE0F);
let has_keycap = cps.contains(&0x20E3);
// Text characters (digits, ©, ↔) are emoji only with U+FE0F or a keycap.
if cps.len() == 1 && !emoji_presentation(first) {
return None;
}
if first < 0x2000 && !has_vs && !has_keycap && first != 0xA9 && first != 0xAE {
return None;
}
if (first == 0xA9 || first == 0xAE) && !has_vs {
return None;
}
let archive = archive();
let key = if cps.contains(&0x200D) {
key_of(&cps)
} else {
key_of(&cps.iter().copied().filter(|&cp| cp != 0xFE0F).collect::<Vec<_>>())
};
if archive.contains(&key) {
return Some(key);
}
// Some ZWJ sequences are named without their U+FE0F.
let bare = key_of(&cps.iter().copied().filter(|&cp| cp != 0xFE0F).collect::<Vec<_>>());
archive.contains(&bare).then_some(bare)
}
/// The archive key of the first emoji in `text` (a reaction's emoji, which
/// may be any string).
pub fn first_key(text: &str) -> Option<String> {
text.graphemes(true).find_map(key_for)
}
/// A piece of text: plain, or one emoji (`emoji` is its key).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Run {
pub text: String,
pub emoji: Option<String>,
}
/// A line of text split into runs for a wrapping layout: a run per word
/// (with the space after it) and per emoji. A line break is a space: lines
/// are blocks of their own (`vm::bbcode`).
pub fn split(text: &str) -> Vec<Run> {
let emoji = text.chars().any(may_be_emoji);
let mut out: Vec<Run> = Vec::new();
let mut word = String::new();
for g in text.graphemes(true) {
if let Some(key) = emoji.then(|| key_for(g)).flatten() {
if !word.is_empty() {
out.push(Run { text: std::mem::take(&mut word), emoji: None });
}
out.push(Run { text: g.to_owned(), emoji: Some(key) });
continue;
}
if g.chars().all(char::is_whitespace) {
// Spaces stay with the word before them (or stand alone after
// an emoji).
word.push(' ');
out.push(Run { text: std::mem::take(&mut word), emoji: None });
} else {
word.push_str(g);
}
}
if !word.is_empty() {
out.push(Run { text: word, emoji: None });
}
out
}
/// One to three emoji and nothing else but spaces: shown large.
pub fn is_jumbo(runs: &[Run]) -> bool {
let emoji = runs.iter().filter(|r| r.emoji.is_some()).count();
(1..=3).contains(&emoji) && runs.iter().all(|r| r.emoji.is_some() || r.text.trim().is_empty())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn archive_opens() {
let a = archive();
assert!(a.len() > 3000);
assert!(a.contains("1f600"));
assert!(!a.contains("zzz"));
assert_eq!(a.name("1f600"), Some("grinning face"));
let svg = a.svg("1f600").unwrap();
assert!(svg.starts_with(b"<svg"), "{:?}", String::from_utf8_lossy(&svg[..20]));
assert!(svg.ends_with(b"</svg>"));
// Twice (the cached block).
assert_eq!(a.svg("1f600").unwrap(), svg);
let zwj = a.svg("1f468-200d-1f4bb").unwrap();
assert!(zwj.starts_with(b"<svg"));
}
#[test]
fn keys_of_graphemes() {
assert_eq!(key_for("😀").as_deref(), Some("1f600"));
// U+FE0F dropped outside ZWJ sequences.
assert_eq!(key_for("❤\u{FE0F}").as_deref(), Some("2764"));
// Keycap.
assert_eq!(key_for("1\u{FE0F}\u{20E3}").as_deref(), Some("31-20e3"));
// Skin tone.
assert_eq!(key_for("👍🏽").as_deref(), Some("1f44d-1f3fd"));
// ZWJ sequence.
assert_eq!(key_for("👨\u{200D}💻").as_deref(), Some("1f468-200d-1f4bb"));
// Flag.
assert_eq!(key_for("🇩🇪").as_deref(), Some("1f1e9-1f1ea"));
// Text stays text.
assert_eq!(key_for("a"), None);
assert_eq!(key_for("1"), None);
assert_eq!(key_for("©"), None);
assert_eq!(key_for("❤"), None);
assert_eq!(key_for("—"), None);
}
#[test]
fn text_runs() {
let texts = |text: &str| -> Vec<(String, Option<String>)> {
split(text).into_iter().map(|r| (r.text, r.emoji)).collect()
};
let word = |w: &str| (w.to_owned(), None);
assert_eq!(texts("plain text, no"), [word("plain "), word("text, "), word("no")]);
assert_eq!(texts("em — dash"), [word("em "), word("— "), word("dash")]);
let r = split("hi 👋 there");
assert_eq!(
texts("hi 👋 there"),
[word("hi "), ("👋".into(), Some("1f44b".into())), word(" "), word("there")]
);
assert!(!is_jumbo(&r));
assert!(is_jumbo(&split("🔥🔥 ")));
assert!(!is_jumbo(&split("🔥🔥🔥🔥")));
assert!(!is_jumbo(&split("no emoji")));
}
#[test]
fn picker() {
let a = archive();
let smileys = a.category(0);
assert!(smileys.len() > 50);
assert_eq!(smileys[0].key, "1f600");
assert_eq!(smileys[0].text, "😀");
assert!(a.category(1).iter().all(|e| !e.key.contains("1f3fb")), "no skin tone variants");
let hearts = a.search("red heart");
assert!(hearts.iter().any(|e| e.key == "2764" && e.text == "❤\u{FE0F}"));
assert!(a.search(" ").is_empty());
}
}
+28 -26
View File
@@ -3,13 +3,16 @@
//! home page), our permissions there, its configuration (gateway
//! administration). The pins, reactions and topics are in `chat.rs`.
use std::sync::Arc;
use slint::{ComponentHandle, SharedString};
use voelin_core::{Command, GatewayRequest, GatewayUpdate};
use voelin_gateway_proto::{Action, EventKind, EventQuery, EventSpec, RsvpStatus, feature};
use crate::app::{App, Bridge, EventForm, EventItem};
use crate::app::{App, Bridge};
use crate::social::{NoticeKind, NoticeTarget, now_ms};
use crate::vm;
use crate::vm::bridge::{EventForm, EventItem};
use crate::vm::social::{date_block, event_when, format_local, parse_local, soon};
impl App {
@@ -26,7 +29,7 @@ impl App {
use GatewayUpdate as U;
let mut ask: Vec<GatewayRequest> = Vec::new();
let mut remind = None;
let extra = &mut self.sessions.entry(id).or_default().extra;
let extra = &mut self.state.sessions.entry(id).or_default().extra;
match update {
U::Connected { uid, capabilities, .. } => {
extra.gateway_uid = Some(uid.clone());
@@ -118,8 +121,8 @@ impl App {
/// The events page of the current server was opened.
pub(crate) fn open_events(&mut self) {
let Some(id) = self.current else { return };
let loaded = self.sessions.get(&id).is_some_and(|v| v.extra.events_loaded);
let Some(id) = self.state.current else { return };
let loaded = self.state.sessions.get(&id).is_some_and(|v| v.extra.events_loaded);
if !loaded {
self.gateway_to(id, GatewayRequest::Events { query: EventQuery::default() });
}
@@ -205,41 +208,40 @@ impl App {
editable: moderate
|| extra.gateway_uid.as_deref() == Some(e.creator.uid.as_str()),
soon: soon(e.spec.start_ms, e.spec.end_ms, now).into(),
attendees: crate::app::model(
e.attendees
.iter()
.map(|a| {
let status = match a.status {
RsvpStatus::Going => "going",
RsvpStatus::Maybe => "maybe",
RsvpStatus::NotGoing => "not going",
RsvpStatus::Unknown => "?",
};
SharedString::from(format!("{} ({status})", a.user.name))
})
.collect(),
),
attendees: e
.attendees
.iter()
.map(|a| {
let status = match a.status {
RsvpStatus::Going => "going",
RsvpStatus::Maybe => "maybe",
RsvpStatus::NotGoing => "not going",
RsvpStatus::Unknown => "?",
};
Arc::<str>::from(format!("{} ({status})", a.user.name))
})
.collect(),
expanded: extra.expanded.contains(&e.id),
}
})
.collect()
})
.unwrap_or_default();
vm::list::sync(&self.models.social.events, &items);
self.models.social.events.sync(&items);
}
/// Answer an event ("" withdraws the answer).
pub(crate) fn rsvp(&mut self, event_id: i32, status: &str) {
let Some(id) = self.current else { return };
let Some(id) = self.state.current else { return };
let status = (!status.is_empty()).then(|| RsvpStatus::parse(status));
self.gateway_to(id, GatewayRequest::Rsvp { event_id: i64::from(event_id), status });
}
/// Show or hide who answered (fetching the event with its attendees).
pub(crate) fn toggle_event(&mut self, event_id: i32) {
let Some(id) = self.current else { return };
let Some(id) = self.state.current else { return };
let event_id = i64::from(event_id);
let view = self.sessions.entry(id).or_default();
let view = self.state.sessions.entry(id).or_default();
if !view.extra.expanded.remove(&event_id) {
view.extra.expanded.insert(event_id);
self.gateway_to(id, GatewayRequest::GetEvent { id: event_id });
@@ -275,7 +277,7 @@ impl App {
/// Create or change an event; the reason when the form is not right.
pub(crate) fn save_event(&mut self, form: &EventForm) -> String {
let Some(id) = self.current else { return "No server selected.".into() };
let Some(id) = self.state.current else { return "No server selected.".into() };
let Some(start_ms) = parse_local(&form.start) else {
return "Write the start as YYYY-MM-DD HH:MM.".into();
};
@@ -289,7 +291,7 @@ impl App {
}
};
let channels = self.event_channels();
let text = |s: &slint::SharedString| Some(s.to_string()).filter(|s| !s.trim().is_empty());
let text = |s: &Arc<str>| Some(s.to_string()).filter(|s| !s.trim().is_empty());
let spec = EventSpec {
title: form.title.trim().to_owned(),
description: form.description.to_string(),
@@ -313,14 +315,14 @@ impl App {
}
pub(crate) fn delete_event(&mut self, event_id: i32) {
if let Some(id) = self.current {
if let Some(id) = self.state.current {
self.gateway_to(id, GatewayRequest::DeleteEvent { id: i64::from(event_id) });
}
}
/// Watch the stream of a live scheduled stream.
pub(crate) fn watch_event(&mut self, event_id: i32) {
let Some(id) = self.current else { return };
let Some(id) = self.state.current else { return };
let stream = self
.view()
.and_then(|v| v.extra.events.iter().find(|e| e.id == i64::from(event_id)))
+20 -18
View File
@@ -9,11 +9,10 @@ use std::path::{Path, PathBuf};
use slint::ComponentHandle;
use voelin_core::VoiceState;
use crate::app::{
App, Bridge, HappeningItem, LiveItem, Page, RecordingItem, ResumeItem, ServerItem,
};
use crate::app::{App, Bridge, Page};
use crate::settings::LastVoice;
use crate::vm;
use crate::vm::bridge::{HappeningItem, LiveItem, RecordingItem, ResumeItem, ServerItem};
use crate::vm::home::ResumeAction;
use crate::vm::social::{event_when, plain};
@@ -30,8 +29,10 @@ impl App {
/// streaming.
fn live_rooms(&self) -> Vec<LiveItem> {
let mut rooms = Vec::new();
for (b, backdrop) in self.bookmarks.iter().zip(vm::servers::tints(&self.bookmarks)) {
let Some(view) = self.sessions.get(&b.id) else { continue };
for (b, backdrop) in
self.state.bookmarks.iter().zip(vm::servers::tints(&self.state.bookmarks))
{
let Some(view) = self.state.sessions.get(&b.id) else { continue };
let channel_of = |cid: Option<u64>| {
cid.and_then(|c| view.presence.channels.get(&c))
.map(|c| vm::tree::channel_title(c).0.to_owned())
@@ -45,7 +46,7 @@ impl App {
let avatar = match (client, uid) {
(Some(c), _) if view.avatar(c).is_some() => vm::avatar::image(view.avatar(c)),
(_, Some(uid)) => self.avatar_of(uid),
_ => slint::Image::default(),
_ => vm::ImageRef::default(),
};
LiveItem {
session: b.id as i32,
@@ -124,8 +125,8 @@ impl App {
let now = crate::social::now_ms();
let mut events: Vec<(i64, HappeningItem, Happening)> = Vec::new();
let mut news = Vec::new();
for b in &self.bookmarks {
let Some(view) = self.sessions.get(&b.id) else { continue };
for b in &self.state.bookmarks {
let Some(view) = self.state.sessions.get(&b.id) else { continue };
for e in &view.extra.events {
let ends = e.spec.end_ms.unwrap_or(e.spec.start_ms + 3 * 3_600_000);
if ends < now {
@@ -184,16 +185,16 @@ impl App {
/// `refresh_chats`).
pub(crate) fn refresh_home(&self) {
let m = &self.models.social;
vm::list::sync(&m.live, &self.live_rooms());
m.live.sync(&self.live_rooms());
let items: Vec<HappeningItem> = self.happenings().into_iter().map(|(i, _)| i).collect();
vm::list::sync(&m.happenings, &items);
m.happenings.sync(&items);
}
/// A live room's card: watch it at once in our channel, else go to its
/// server (and the streamer's channel, watching once there).
pub(crate) fn watch_live(&mut self, session: i64, id: &str) {
self.show_server(session);
let Some(view) = self.sessions.get(&session) else { return };
let Some(view) = self.state.sessions.get(&session) else { return };
if view.streams_available() && view.streams.iter().any(|s| s.id == id) {
self.watch_stream(id.to_owned());
return;
@@ -233,8 +234,9 @@ impl App {
}
fn last_resume(&self) -> Option<vm::home::Resume> {
let voice = |id| self.sessions.get(&id).map_or(VoiceState::Disconnected, |v| v.state.voice);
vm::home::resume(self.settings.last_voice.as_ref(), &self.bookmarks, voice)
let voice =
|id| self.state.sessions.get(&id).map_or(VoiceState::Disconnected, |v| v.state.voice);
vm::home::resume(self.state.settings.last_voice.as_ref(), &self.state.bookmarks, voice)
}
/// Home's "Continue where you left off", its server as the rail shows
@@ -253,7 +255,7 @@ impl App {
icon: server.icon.clone(),
channel: resume.title().into(),
open: resume.action == ResumeAction::Open,
connecting: server.status == "connecting",
connecting: &*server.status == "connecting",
}
}
@@ -273,17 +275,17 @@ impl App {
if self.demo_ui {
return false;
}
let Some(view) = self.sessions.get(&session) else { return false };
let Some(view) = self.state.sessions.get(&session) else { return false };
let (VoiceState::Connected, Some(cid)) = (view.state.voice, view.state.own_channel) else {
return false;
};
let channel = vm::tree::channel_path(&view.presence, cid);
let Some(b) = self.bookmark(session).filter(|_| !channel.is_empty()) else { return false };
let last = LastVoice { bookmark: session, address: b.address.clone(), channel };
if self.settings.last_voice.as_ref() == Some(&last) {
if self.state.settings.last_voice.as_ref() == Some(&last) {
return false;
}
self.settings.last_voice = Some(last);
self.state.settings.last_voice = Some(last);
self.store_settings();
true
}
@@ -304,7 +306,7 @@ impl App {
}
let dir = self.recordings_dir();
let items = recordings_in(&dir);
vm::list::sync(&self.models.social.recordings, &items);
self.models.social.recordings.sync(&items);
if let Some(ui) = self.ui.upgrade() {
ui.global::<Bridge>().set_recordings_dir(dir.display().to_string().into());
}
+1 -24
View File
@@ -2,23 +2,13 @@
//! `Store::default_identity`), chosen under Settings → Profiles, and the
//! import of the official clients' identities on start
//! (`voelin_core::ts::identity::import_new`, app.rs). The rest of the Profiles
//! page is in `settings_pages.rs`.
//! page is in `settings_pages/`.
use tracing::warn;
use voelin_core::settings::IDENTITY_IMPORT;
use voelin_store::IdentityOrigin;
use crate::app::App;
/// Where an identity came from, as Profiles says it.
pub(crate) fn origin_label(origin: IdentityOrigin) -> &'static str {
match origin {
IdentityOrigin::Created => "Made in Voelin",
IdentityOrigin::Imported => "Imported",
IdentityOrigin::User => "Chosen by you",
}
}
impl App {
/// The user's choice of the identity servers see us as, from the next
/// connection on; no import replaces it.
@@ -51,16 +41,3 @@ impl App {
self.refresh_identities();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rows_say_where_an_identity_came_from() {
assert_eq!(origin_label(IdentityOrigin::Created), "Made in Voelin");
assert_eq!(origin_label(IdentityOrigin::Imported), "Imported");
// Made by the app, then chosen: an import never replaces it.
assert_eq!(origin_label(IdentityOrigin::User), "Chosen by you");
}
}
+2 -2
View File
@@ -65,8 +65,8 @@ pub(crate) fn take() {
impl App {
fn share(&mut self, nav: &Nav<'_>, text: Option<String>, files: Vec<PathBuf>) {
let current = self.current.and_then(|id| {
let view = self.sessions.get(&id)?;
let current = self.state.current.and_then(|id| {
let view = self.state.sessions.get(&id)?;
let tab = &view.tabs[view.current_tab];
// Files go to the channel of the chat, else to ours.
let channel = match tab.target {
+3 -3
View File
@@ -6,7 +6,6 @@ mod bind;
mod camera;
mod chat;
mod dev;
mod emoji;
mod events;
mod home;
mod hotkey;
@@ -19,14 +18,15 @@ mod messages;
mod popout;
mod previews;
mod servers;
mod settings;
mod settings_page;
mod settings_pages;
mod social;
mod streams;
mod studio;
mod video;
mod vm;
// The view models live in their own crate; the modules keep their old paths.
use voelin_ui_vm::{self as vm, emoji, settings};
pub use app::{HostedEngine, RunOptions, run};
pub use inbox::{Request, request};
+9 -4
View File
@@ -29,9 +29,14 @@ impl App {
}
};
let in_voice = |id: i64| {
self.sessions.get(&id).is_some_and(|v| v.state.voice == VoiceState::Connected)
self.state.sessions.get(&id).is_some_and(|v| v.state.voice == VoiceState::Connected)
};
match vm::servers::link_server(&self.bookmarks, &link.address(), self.current, in_voice) {
match vm::servers::link_server(
&self.state.bookmarks,
&link.address(),
self.state.current,
in_voice,
) {
Some((id, true)) => self.move_by_link(id, &link),
saved => self.open_link_form(saved.map(|(id, _)| id), &link),
}
@@ -41,7 +46,7 @@ impl App {
fn move_by_link(&mut self, session: i64, link: &ServerLink) {
self.show_server(session);
let Some(path) = &link.channel else { return };
let Some(view) = self.sessions.get_mut(&session) else { return };
let Some(view) = self.state.sessions.get_mut(&session) else { return };
let Some(channel) = vm::servers::channel_by_path(&view.presence, path) else {
let server = self.bookmark(session).map(|b| b.name.clone()).unwrap_or_default();
self.set_status(format!("{server} has no channel \u{201c}{path}\u{201d}"));
@@ -64,7 +69,7 @@ impl App {
let form = vm::servers::link_form(link, form, &self.default_nickname());
let Some(ui) = self.ui.upgrade() else { return };
let nav = ui.global::<Nav>();
nav.set_bookmark_form(form);
nav.set_bookmark_form(form.into());
nav.set_bookmark_open(true);
}
}
+34 -22
View File
@@ -2,12 +2,15 @@
//! (private chat, poke, contacts, per-client volume). The rows themselves
//! are built in `vm::tree::members`.
use std::sync::Arc;
use slint::ComponentHandle;
use voelin_core::{Command, Contact, Relation};
use crate::app::{App, Bridge, MemberCard, Nav};
use crate::app::{App, Bridge, Nav};
use crate::settings::ClientPlayback;
use crate::vm;
use crate::vm::bridge::MemberCard;
impl App {
/// `VOELIN_OPEN=member`: the card of the first person that is not us.
@@ -43,10 +46,13 @@ impl App {
let id = view.member_card?;
let client = view.presence.clients.get(&id)?;
let uid = client.uid.clone();
let contact = uid.as_ref().and_then(|u| self.contacts.get(u));
let playback =
uid.as_ref().and_then(|u| self.playback.get(u)).copied().unwrap_or_default();
let groups: Vec<slint::SharedString> = client
let contact = uid.as_ref().and_then(|u| self.state.contacts.get(u));
let playback = uid
.as_ref()
.and_then(|u| self.state.playback.get(u))
.copied()
.unwrap_or_default();
let groups: Vec<Arc<str>> = client
.server_groups
.iter()
.filter_map(|g| view.server_groups.iter().find(|i| i.id == *g))
@@ -62,8 +68,8 @@ impl App {
avatar: vm::avatar::image(view.avatar(id)),
status: vm::tree::status_of(client, view.talking.contains(&id)).into(),
description: client.description.clone().unwrap_or_default().into(),
groups: crate::app::model(groups),
badges: crate::app::model(badges),
groups,
badges,
country: client.country.clone().unwrap_or_default().into(),
talk_power: client.talk_power,
friend: contact.is_some_and(|c| c.relation == Relation::Friend),
@@ -75,13 +81,13 @@ impl App {
})
})
.unwrap_or_default();
bridge.set_member_card(card);
bridge.set_member_card(card.into());
}
/// The card's buttons: "message", "poke", "friend", "blocked", "mute".
pub(crate) fn member_action(&mut self, action: &str) {
let Some(id) = self.current else { return };
let Some(view) = self.sessions.get(&id) else { return };
let Some(id) = self.state.current else { return };
let Some(view) = self.state.sessions.get(&id) else { return };
let Some(client) = view.member_card.and_then(|c| view.presence.clients.get(&c)) else {
return;
};
@@ -102,18 +108,22 @@ impl App {
"friend" | "blocked" => {
let Some(uid) = uid else { return };
let wanted = if action == "friend" { Relation::Friend } else { Relation::Blocked };
let current = self.contacts.get(&uid).map(|c| c.relation);
let mut contact =
self.contacts.get(&uid).cloned().unwrap_or_else(|| Contact::new(uid.clone()));
let current = self.state.contacts.get(&uid).map(|c| c.relation);
let mut contact = self
.state
.contacts
.get(&uid)
.cloned()
.unwrap_or_else(|| Contact::new(uid.clone()));
contact.nickname = nickname;
contact.relation = if current == Some(wanted) { Relation::Neutral } else { wanted };
self.contacts.insert(uid, contact.clone());
self.state.contacts.insert(uid, contact.clone());
self.engine.send(Command::SetContact { contact: Box::new(contact) });
self.refresh_member_card();
}
"mute" => {
let Some(uid) = uid else { return };
let mut playback = self.playback.get(&uid).copied().unwrap_or_default();
let mut playback = self.state.playback.get(&uid).copied().unwrap_or_default();
playback.muted = !playback.muted;
self.set_playback(&uid, client_id, playback);
}
@@ -123,9 +133,9 @@ impl App {
/// Open the poke dialog for a client (the member card, a contact).
pub(crate) fn ask_poke(&mut self, session: i64, client: u16) {
let Some(view) = self.sessions.get(&session) else { return };
let Some(view) = self.state.sessions.get(&session) else { return };
let name = view.nickname(client);
self.poke_target = Some((session, client, name.clone()));
self.state.poke_target = Some((session, client, name.clone()));
let Some(ui) = self.ui.upgrade() else { return };
let nav = ui.global::<Nav>();
nav.set_poke_name(name.into());
@@ -134,7 +144,7 @@ impl App {
/// The poke dialog's Send, with its message (may be empty).
pub(crate) fn send_poke(&mut self, text: &str) {
let Some((session, client, name)) = self.poke_target.take() else { return };
let Some((session, client, name)) = self.state.poke_target.take() else { return };
if !self.demo_ui {
self.engine.send(Command::Poke {
session: session as u64,
@@ -152,7 +162,7 @@ impl App {
return;
};
let (client_id, Some(uid)) = (client.id, client.uid.clone()) else { return };
let mut playback = self.playback.get(&uid).copied().unwrap_or_default();
let mut playback = self.state.playback.get(&uid).copied().unwrap_or_default();
playback.volume = (percent / 100.0).clamp(0.0, 4.0);
self.set_playback(&uid, client_id, playback);
}
@@ -160,11 +170,13 @@ impl App {
/// Store one client's playback and apply it to the session.
fn set_playback(&mut self, uid: &str, client: u16, playback: ClientPlayback) {
if playback.is_default() {
self.playback.remove(uid);
self.state.playback.remove(uid);
} else {
self.playback.insert(uid.to_owned(), playback);
self.state.playback.insert(uid.to_owned(), playback);
}
if let Err(e) = self.prefs.set(&crate::settings::CLIENT_PLAYBACK, self.playback.clone()) {
if let Err(e) =
self.prefs.set(&crate::settings::CLIENT_PLAYBACK, self.state.playback.clone())
{
tracing::warn!(%e, "could not store client volumes");
}
self.command(|session| Command::SetClientMuted { session, client, muted: playback.muted });
+114 -106
View File
@@ -14,32 +14,21 @@
//! read-only.
use std::collections::HashMap;
use std::sync::Arc;
use slint::{ComponentHandle, Image, SharedString};
use slint::ComponentHandle;
use voelin_core::{Command, HistoryMessage, OfflineMessage, OfflineMessageInfo, VoiceState};
use voelin_model::ChatTarget;
use voelin_store::PageQuery;
use crate::app::{
App, Bridge, ConversationItem, DmPeer, FileItem, Nav, OfflineForm, Page, SessionView, later,
};
use crate::app::{App, Bridge, Nav, Page, SessionView, later};
use crate::vm;
use crate::vm::social::{ago, list_time, matches, plain, preview};
use crate::vm::bridge::{ConversationItem, DmPeer, FileItem, OfflineForm};
use crate::vm::social::{ChatRef, ago, list_time, matches, plain, preview};
/// Keys of offline messages in the conversation list start here.
const MAIL: i32 = 10_000;
/// A chat of any server.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct ChatRef {
/// The bookmark (session) it belongs to, when known.
pub session: Option<i64>,
pub server_uid: Option<String>,
pub target: ChatTarget,
pub last: Option<HistoryMessage>,
pub unread: i32,
}
/// The open conversation.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Open {
@@ -81,7 +70,7 @@ impl App {
return;
}
self.social.dm.bookmark_of.clear();
for b in &self.bookmarks {
for b in &self.state.bookmarks {
let gateways = b.gateways().into_iter().chain(b.gateway_url.clone());
for alias in std::iter::once(format!("voice:{}", b.address))
.chain(gateways.map(|url| format!("gateway:{url}")))
@@ -107,7 +96,8 @@ impl App {
/// The session a server unique id belongs to.
fn session_of_server(&self, server_uid: &str) -> Option<i64> {
self.sessions
self.state
.sessions
.iter()
.find(|(_, v)| v.state.server_uid.as_deref() == Some(server_uid))
.map(|(id, _)| *id)
@@ -116,18 +106,18 @@ 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.contacts.get(uid).filter(|c| !c.nickname.is_empty()) {
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.sessions[&s.session].nickname(s.client);
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.sessions.values().flat_map(|v| &v.tabs).find_map(|t| {
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()
@@ -139,8 +129,8 @@ impl App {
/// Every chat, newest first; then the lists that show them.
pub(crate) fn refresh_chats(&mut self) {
let mut chats: Vec<ChatRef> = Vec::new();
for b in &self.bookmarks {
let Some(view) = self.sessions.get(&b.id) else { continue };
for b in &self.state.bookmarks {
let Some(view) = self.state.sessions.get(&b.id) else { continue };
for tab in &view.tabs {
let last = tab.messages.last().map(|m| m.message.clone());
if last.is_none() && !matches!(tab.target, ChatTarget::Private(_)) {
@@ -172,9 +162,10 @@ impl App {
chats.sort_by_key(|c| std::cmp::Reverse(c.last.as_ref().map_or(0, |m| m.message.ts_ms)));
self.social.dm.chats = chats;
self.social.dm.inbox = self
.state
.bookmarks
.iter()
.filter_map(|b| self.sessions.get(&b.id).map(|v| (b.id, v)))
.filter_map(|b| self.state.sessions.get(&b.id).map(|v| (b.id, v)))
.flat_map(|(id, v)| v.extra.inbox.iter().map(move |m| (id, m.clone())))
.collect();
self.social.dm.inbox.sort_by_key(|(_, m)| std::cmp::Reverse(m.ts_s));
@@ -196,15 +187,15 @@ impl App {
),
ChatTarget::Channel(cid) => {
let name = session
.and_then(|s| self.sessions.get(&s))
.and_then(|s| self.state.sessions.get(&s))
.and_then(|v| v.presence.channels.get(cid))
.map_or_else(
|| format!("Channel {cid}"),
|c| vm::tree::channel_title(c).0.to_owned(),
);
(name, slint::Image::default(), false, 1)
(name, vm::ImageRef::default(), false, 1)
}
ChatTarget::Server => (server.clone(), slint::Image::default(), false, 0),
ChatTarget::Server => (server.clone(), vm::ImageRef::default(), false, 0),
};
let (text, ts) = match &chat.last {
Some(m) => {
@@ -258,7 +249,7 @@ impl App {
.take(4)
.map(|(i, c)| self.conversation_item(i, c))
.collect();
vm::list::sync(&self.models.social.recent, &recent);
self.models.social.recent.sync(&recent);
// Shown beside other pages: none is the open one.
let sidebar: Vec<ConversationItem> = vm::social::sidebar_dms(&dm.chats, 5)
.into_iter()
@@ -267,7 +258,7 @@ impl App {
..self.conversation_item(i, &dm.chats[i])
})
.collect();
vm::list::sync(&self.models.social.sidebar_dms, &sidebar);
self.models.social.sidebar_dms.sync(&sidebar);
let private = |c: &&ChatRef| matches!(c.target, ChatTarget::Private(_));
let items: Vec<ConversationItem> = if dm.tab == 2 {
dm.inbox
@@ -286,9 +277,9 @@ impl App {
unread: i32::from(!m.read),
// A letter in the sender's colour, no initials or
// picture under it.
initials: SharedString::new(),
initials: Arc::default(),
tint: vm::avatar::tint(&name),
avatar: Image::default(),
avatar: vm::ImageRef::default(),
online: false,
selected: dm
.open
@@ -296,7 +287,7 @@ impl App {
.is_some_and(|o| o.mail == Some((*session, m.id))),
}
})
.filter(|c| matches(&dm.filter, &[&c.title, &c.preview]))
.filter(|c| matches(&dm.filter, &[&*c.title, &*c.preview]))
.collect()
} else {
dm.chats
@@ -304,10 +295,10 @@ impl App {
.enumerate()
.filter(|(_, c)| private(c) && (dm.tab == 0 || c.unread > 0))
.map(|(i, c)| self.conversation_item(i, c))
.filter(|c| matches(&dm.filter, &[&c.title, &c.preview]))
.filter(|c| matches(&dm.filter, &[&*c.title, &*c.preview]))
.collect()
};
vm::list::sync(&self.models.social.conversations, &items);
self.models.social.conversations.sync(&items);
bridge.set_dm_unread(self.dm_unread());
bridge.set_inbox_unread(dm.inbox.iter().filter(|(_, m)| !m.read).count() as i32);
}
@@ -315,9 +306,10 @@ impl App {
/// Unread messages in the private chats of every server (the rail and
/// the chat strip leave them out).
pub(crate) fn dm_unread(&self) -> i32 {
self.bookmarks
self.state
.bookmarks
.iter()
.filter_map(|b| self.sessions.get(&b.id))
.filter_map(|b| self.state.sessions.get(&b.id))
.map(SessionView::private_unread)
.sum()
}
@@ -332,9 +324,9 @@ impl App {
};
let target = ChatTarget::Private(uid);
// Not for a session that is gone (its server was deleted).
let Some(view) = self.sessions.get(&id) else { return };
let Some(view) = self.state.sessions.get(&id) else { return };
if !view.tabs.iter().any(|t| t.target == target)
|| (self.current == Some(id)
|| (self.state.current == Some(id)
&& view.tabs.get(view.current_tab).is_some_and(|t| t.target == target))
{
return;
@@ -347,8 +339,8 @@ impl App {
/// the chat it shows, which must not be the strip's.
fn focus_private(&mut self, id: i64, target: ChatTarget) {
let index = self.chat_tab(id, target.clone());
self.sessions.entry(id).or_default().set_current_tab(index);
if self.current != Some(id) {
self.state.sessions.entry(id).or_default().set_current_tab(index);
if self.state.current != Some(id) {
self.select_server(id);
}
self.open_chat(target, true);
@@ -359,7 +351,7 @@ impl App {
/// ([`SessionView::channel_tab`]).
pub(crate) fn close_messages(&mut self) {
let mut changed = false;
for view in self.sessions.values_mut() {
for view in self.state.sessions.values_mut() {
changed |= view.leave_private();
}
if !changed {
@@ -371,7 +363,7 @@ impl App {
// (`Nav.select-server` leaves the page first) is selected by then,
// and the chat that came back here was never on screen.
later(|app| {
if let Some(id) = app.current {
if let Some(id) = app.state.current {
app.fetch_previews(id);
}
app.prefetch_counts();
@@ -382,7 +374,7 @@ impl App {
pub(crate) fn dm_tab(&mut self, tab: i32) {
self.social.dm.tab = tab;
if tab == 2 {
for view in self.sessions.values_mut() {
for view in self.state.sessions.values_mut() {
view.extra.inbox_asked = false;
}
self.ask_inboxes();
@@ -443,7 +435,7 @@ impl App {
.find(|c| c.target == target && (session.is_none() || c.session == session));
let session = session.or_else(|| known.and_then(|c| c.session));
let server_uid = session
.and_then(|s| self.sessions.get(&s))
.and_then(|s| self.state.sessions.get(&s))
.and_then(|v| v.state.server_uid.clone())
.or_else(|| known.and_then(|c| c.server_uid.clone()));
self.open_dm(session, server_uid, uid);
@@ -453,7 +445,7 @@ impl App {
/// the store.
pub(crate) fn open_dm(&mut self, session: Option<i64>, server_uid: Option<String>, uid: &str) {
let live = session
.and_then(|s| self.sessions.get(&s))
.and_then(|s| self.state.sessions.get(&s))
.is_some_and(|v| v.has_history() || v.state.voice == VoiceState::Connected);
self.social.dm.open = Some(Open {
session,
@@ -463,7 +455,7 @@ impl App {
stored: !live,
});
self.social.dm.mail = None;
vm::list::sync(&self.models.social.dm_lines, &[]);
self.models.social.dm_lines.sync(&[]);
let target = ChatTarget::Private(uid.to_owned());
if let (true, Some(id)) = (live, session) {
self.focus_private(id, target);
@@ -505,7 +497,7 @@ impl App {
line
})
.collect();
vm::list::sync(&self.models.social.dm_lines, &lines);
self.models.social.dm_lines.sync(&lines);
self.refresh_dm();
}
@@ -526,15 +518,16 @@ impl App {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let Some(open) = &self.social.dm.open else {
bridge.set_dm(DmPeer::default());
bridge.set_dm(DmPeer::default().into());
return;
};
let uid = open.uid.as_str();
let contact = self.contacts.get(uid);
let contact = self.state.contacts.get(uid);
let spots = self.spots_of(uid);
let here = open.session.and_then(|s| spots.iter().find(|sp| sp.session == s));
let view = open.session.and_then(|s| self.sessions.get(&s));
let client = here.and_then(|s| self.sessions[&s.session].presence.clients.get(&s.client));
let view = open.session.and_then(|s| self.state.sessions.get(&s));
let client =
here.and_then(|s| self.state.sessions[&s.session].presence.clients.get(&s.client));
let tab =
view.and_then(|v| v.tabs.iter().find(|t| t.target == ChatTarget::Private(uid.into())));
let name = self.peer_name(uid, tab.and_then(|t| t.messages.last().map(|m| &m.message)));
@@ -554,7 +547,7 @@ impl App {
None => "Offline".into(),
},
};
let groups: Vec<SharedString> = match (client, view) {
let groups: Vec<Arc<str>> = match (client, view) {
(Some(c), Some(v)) => c
.server_groups
.iter()
@@ -563,7 +556,7 @@ impl App {
.collect(),
_ => Vec::new(),
};
let servers: Vec<SharedString> = if spots.is_empty() {
let servers: Vec<Arc<str>> = if spots.is_empty() {
contact
.and_then(|c| c.last_server.clone())
.map(|s| {
@@ -638,51 +631,60 @@ impl App {
.find(|(ms, m)| *ms == s && m.id == id)
.map(|(_, m)| m.clone())
});
bridge.set_dm(DmPeer {
open: true,
uid: uid.into(),
name: name.clone().into(),
initials: vm::avatar::initials(&name).into(),
tint: vm::avatar::tint(&name),
avatar: self.avatar_of(uid),
online: !spots.is_empty(),
status: status.into(),
description: client.and_then(|c| c.description.clone()).unwrap_or_default().into(),
groups: crate::app::model(groups),
note: contact.map(|c| c.note.clone()).unwrap_or_default().into(),
since: contact
.filter(|c| c.added_ms > 0)
.and_then(|c| chrono::DateTime::from_timestamp_millis(c.added_ms))
.map(|t| {
format!("Contact since {}", t.with_timezone(&chrono::Local).format("%-d %b %Y"))
})
.unwrap_or_default()
.into(),
servers: crate::app::model(servers),
media: crate::app::model(media),
media_more: media_more as i32,
files: crate::app::model(files),
friend: contact.is_some_and(|c| c.relation == voelin_core::Relation::Friend),
blocked,
volume: contact.map_or(100.0, |c| c.volume * 100.0),
muted: contact.is_some_and(|c| c.muted),
can_send,
notice: notice.into(),
offline,
can_connect: !voice && in_bookmarks,
stored: open.stored,
mail: open.mail.is_some(),
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))
.unwrap_or_default()
.into(),
mail_time: mail.map(|m| vm::chat::time_of(m.ts_s * 1000)).unwrap_or_default().into(),
});
bridge.set_dm(
DmPeer {
open: true,
uid: uid.into(),
name: name.clone().into(),
initials: vm::avatar::initials(&name).into(),
tint: vm::avatar::tint(&name),
avatar: self.avatar_of(uid),
online: !spots.is_empty(),
status: status.into(),
description: client.and_then(|c| c.description.clone()).unwrap_or_default().into(),
groups,
note: contact.map(|c| c.note.clone()).unwrap_or_default().into(),
since: contact
.filter(|c| c.added_ms > 0)
.and_then(|c| chrono::DateTime::from_timestamp_millis(c.added_ms))
.map(|t| {
format!(
"Contact since {}",
t.with_timezone(&chrono::Local).format("%-d %b %Y")
)
})
.unwrap_or_default()
.into(),
servers,
media,
media_more: media_more as i32,
files,
friend: contact.is_some_and(|c| c.relation == voelin_core::Relation::Friend),
blocked,
volume: contact.map_or(100.0, |c| c.volume * 100.0),
muted: contact.is_some_and(|c| c.muted),
can_send,
notice: notice.into(),
offline,
can_connect: !voice && in_bookmarks,
stored: open.stored,
mail: open.mail.is_some(),
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))
.unwrap_or_default()
.into(),
mail_time: mail
.map(|m| vm::chat::time_of(m.ts_s * 1000))
.unwrap_or_default()
.into(),
}
.into(),
);
}
/// The buttons of the open conversation.
@@ -692,7 +694,7 @@ impl App {
match action {
"poke" | "join" | "mute" => self.contact_action(&uid, action),
"friend" | "block" => {
let current = self.contacts.get(&uid).map(|c| c.relation);
let current = self.state.contacts.get(&uid).map(|c| c.relation);
let wanted = if action == "friend" {
voelin_core::Relation::Friend
} else {
@@ -750,9 +752,14 @@ impl App {
/// Send an offline message through the open conversation's server.
pub(crate) fn send_offline(&mut self, form: OfflineForm) {
let session =
self.social.dm.open.as_ref().and_then(|o| o.session).or(self.current).filter(|s| {
self.sessions.get(s).is_some_and(|v| v.state.voice == VoiceState::Connected)
});
self.social.dm.open.as_ref().and_then(|o| o.session).or(self.state.current).filter(
|s| {
self.state
.sessions
.get(s)
.is_some_and(|v| v.state.voice == VoiceState::Connected)
},
);
let Some(session) = session else {
self.set_status("Connect with voice to send an offline message.");
return;
@@ -798,7 +805,7 @@ impl App {
pub(crate) fn mail_arrived(&mut self, session: i64, result: Result<OfflineMessage, String>) {
match result {
Ok(m) => {
if let Some(view) = self.sessions.get_mut(&session)
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;
@@ -816,7 +823,7 @@ impl App {
("send", Err(e)) => self.set_status(format!("Could not send the offline message: {e}")),
(_, Err(e)) => self.set_status(format!("Offline messages: {e}")),
(_, Ok(())) => {
if let Some(view) = self.sessions.get_mut(&session) {
if let Some(view) = self.state.sessions.get_mut(&session) {
view.extra.inbox_asked = false;
}
self.ask_inboxes();
@@ -830,6 +837,7 @@ impl App {
return;
}
let ids: Vec<i64> = self
.state
.sessions
.iter()
.filter(|(_, v)| {
@@ -841,7 +849,7 @@ impl App {
.collect();
for id in ids {
let request = self.offline_request(id, "list");
if let Some(view) = self.sessions.get_mut(&id) {
if let Some(view) = self.state.sessions.get_mut(&id) {
view.extra.inbox_asked = true;
}
self.engine.send(Command::ListOfflineMessages { session: id as u64, request });
@@ -850,7 +858,7 @@ impl App {
/// 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, crate::app::ChatLine)> {
pub(crate) fn poke_lines(&self, session: i64, uid: &str) -> Vec<(i64, vm::bridge::ChatLine)> {
self.social
.pokes
.iter()
+6 -3
View File
@@ -94,10 +94,13 @@ impl App {
}
// The main window may have gone to another server meanwhile: else
// the stream would play on, unseen.
let session =
self.watch.as_ref().and_then(|w| w.session).filter(|id| self.sessions.contains_key(id));
let session = self
.watch
.as_ref()
.and_then(|w| w.session)
.filter(|id| self.state.sessions.contains_key(id));
if let Some(id) = session
&& self.current != Some(id)
&& self.state.current != Some(id)
{
self.select_server(id);
}
+13 -19
View File
@@ -9,24 +9,18 @@
//! message shows its address.
use std::borrow::Cow;
use std::sync::Arc;
use voelin_core::settings::CACHE_FETCH_IMAGES;
use voelin_core::{Bytes, Command, DownloadTo, TransferState, VoiceState};
use voelin_core::{Command, DownloadTo, TransferState, VoiceState};
use voelin_model::{ChatTarget, FileRef};
use crate::app::{App, SessionView};
use crate::bind::convert;
use crate::settings::UI_IMAGE_PREVIEW_KB;
use crate::vm;
/// A linked picture.
#[derive(Clone, Debug)]
pub(crate) enum Preview {
/// Downloading (transfer id).
Loading(u64),
Ready(Bytes),
/// Too large, not a picture, or the download failed.
Failed,
}
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 {
@@ -47,12 +41,12 @@ pub(crate) fn link_key(file: &FileRef) -> String {
/// 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<slint::Image> {
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 = crate::images::picture(&key, &bytes.0);
(image.size().width > 0).then_some(image)
let image = Arc::new(ImageSource::Memory { key: key.into(), bytes: bytes.0.clone() });
(!image.is_empty()).then_some(image)
}
_ => None,
}
@@ -70,7 +64,7 @@ impl App {
return;
}
self.fetch_web_pictures(session, limit);
let Some(view) = self.sessions.get_mut(&session) else { return };
let Some(view) = self.state.sessions.get_mut(&session) else { return };
if view.state.voice != VoiceState::Connected || !view.capabilities.file_transfer {
return;
}
@@ -108,7 +102,7 @@ impl App {
if !self.prefs.get(&CACHE_FETCH_IMAGES) {
return;
}
let Some(view) = self.sessions.get(&session) else { 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 {
@@ -142,7 +136,7 @@ impl App {
state: &TransferState,
) -> bool {
let limit = u64::from(self.prefs.get(&UI_IMAGE_PREVIEW_KB)) * 1024;
let Some(view) = self.sessions.get_mut(&session) else { return false };
let Some(view) = self.state.sessions.get_mut(&session) else { return false };
let Some(key) = view
.extra
.previews
@@ -161,7 +155,7 @@ impl App {
}
TransferState::Done { data: Some(data), .. } => {
view.extra.previews.insert(key, Preview::Ready(data.clone()));
if self.current == Some(session) {
if self.state.current == Some(session) {
self.refresh_chat();
}
}
@@ -188,7 +182,7 @@ impl App {
};
let index = index.max(0) as usize;
match message.file_refs().get(index) {
Some(file) => image_of(view, file).unwrap_or_default(),
Some(file) => 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))
+79 -62
View File
@@ -10,8 +10,10 @@ use voelin_core::{Command, JoinFailure, ObserveState, Source, VoiceOptions, Voic
use voelin_model::ChannelId;
use voelin_store::{Bookmark, QueryTransport};
use crate::app::{App, BookmarkForm, Bridge, Nav, SessionView, later};
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.
@@ -102,8 +104,11 @@ fn observing_stays(
impl App {
pub(crate) fn connect_voice(&mut self) {
let channel =
self.current.and_then(|id| self.bookmark(id)).and_then(|b| b.default_channel.clone());
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);
}
@@ -116,7 +121,9 @@ impl App {
channel_password: Option<String>,
token: Option<String>,
) -> bool {
let Some(b) = self.current.and_then(|id| self.bookmark(id)).cloned() else { return false };
let Some(b) = self.state.current.and_then(|id| self.bookmark(id)).cloned() else {
return false;
};
if self.demo_ui {
return false;
}
@@ -169,7 +176,7 @@ impl App {
/// (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.gateways_looked_up.insert(id) {
if self.demo_ui || !self.state.gateways_looked_up.insert(id) {
return;
}
let Some(b) = self.bookmark(id) else { return };
@@ -191,7 +198,8 @@ impl App {
/// 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.bookmarks.iter_mut().find(|b| b.id == id && b.address == address) else {
let Some(b) = self.state.bookmarks.iter_mut().find(|b| b.id == id && b.address == address)
else {
return;
};
let previous = b.gateways();
@@ -204,12 +212,12 @@ impl App {
warn!(%e, "could not keep the gateway found");
return;
}
let observe = self.sessions.get(&id).map(|v| v.state.observe).unwrap_or_default();
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.current == Some(id) && observe == ObserveState::Off {
if self.state.current == Some(id) && observe == ObserveState::Off {
self.observe(id);
}
return;
@@ -217,18 +225,18 @@ impl App {
// 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.sessions.get_mut(&id) {
if let Some(view) = self.state.sessions.get_mut(&id) {
view.state.observe = ObserveState::Off;
}
}
if self.current == Some(id) {
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.bookmarks.iter_mut().find(|b| b.id == id) else { return };
let Some(b) = self.state.bookmarks.iter_mut().find(|b| b.id == id) else { return };
if !b.gateway_in_use(url) {
return;
}
@@ -242,7 +250,8 @@ impl App {
/// 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.bookmarks.iter_mut().find(|b| b.id == id && b.name == b.address) else {
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 {
@@ -267,7 +276,7 @@ impl App {
return;
}
let session = b.id as u64;
let state = self.sessions.get(&b.id).map(|v| v.state.observe).unwrap_or_default();
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,
@@ -325,7 +334,7 @@ impl App {
/// Show a server, and observe it.
pub(crate) fn select_server(&mut self, id: i64) {
self.current = Some(id);
self.state.current = Some(id);
self.prefetch_counts();
self.track_reading();
self.refresh_all();
@@ -341,7 +350,7 @@ impl App {
};
};
let password = self.secrets.get(&b.server_password_key()).ok().flatten();
let state = self.sessions.get(&b.id).map(|view| &view.state);
let state = self.state.sessions.get(&b.id).map(|view| &view.state);
vm::servers::form(b, state, password.as_deref().unwrap_or_default())
}
@@ -374,13 +383,13 @@ impl App {
if old.query.is_some() {
let _ = self.secrets.delete(&old.query_password_key());
}
self.gateways_looked_up.remove(&bookmark.id);
self.state.gateways_looked_up.remove(&bookmark.id);
self.engine.send(Command::StopObserving { session: bookmark.id as u64 });
if let Some(view) = self.sessions.get_mut(&bookmark.id) {
if let Some(view) = self.state.sessions.get_mut(&bookmark.id) {
view.state.observe = ObserveState::Off;
}
}
self.bookmarks = self.store.bookmarks().unwrap_or_default();
self.state.bookmarks = self.store.bookmarks().unwrap_or_default();
self.select_server(bookmark.id);
Some(bookmark.id)
}
@@ -407,10 +416,10 @@ impl App {
}
let _ = self.store.delete_bookmark(id);
self.save_reads(id);
self.sessions.remove(&id);
self.gateways_looked_up.remove(&id);
self.bookmarks = self.store.bookmarks().unwrap_or_default();
self.current = self.bookmarks.first().map(|b| b.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();
@@ -418,11 +427,11 @@ impl App {
/// 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.bookmarks.iter_mut().find(|b| b.id == id) else {
let Some(bookmark) = self.state.bookmarks.iter_mut().find(|b| b.id == id) else {
return;
};
let changed =
apply_server_icon(bookmark, self.sessions.entry(id).or_default(), address, icon);
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)
@@ -431,8 +440,9 @@ impl App {
}
}
pub(crate) fn server_list_icon(&self, bookmark: &Bookmark) -> slint::Image {
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))
@@ -445,9 +455,9 @@ impl App {
}
/// A server's colour, as the rail shows it ([`vm::servers::tints`]).
pub(crate) fn server_tint(&self, id: i64) -> slint::Color {
let tints = vm::servers::tints(&self.bookmarks);
self.bookmarks.iter().position(|b| b.id == id).map(|i| tints[i]).unwrap_or_default()
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
@@ -456,13 +466,14 @@ impl App {
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.bookmarks);
let tints = vm::servers::tints(&self.state.bookmarks);
let items: Vec<_> = self
.state
.bookmarks
.iter()
.zip(tints)
.map(|(b, tint)| {
let view = self.sessions.get(&b.id);
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());
@@ -475,9 +486,9 @@ impl App {
vm::servers::item(b, &state, unread, live, detail, product, icon, tint)
})
.collect();
vm::list::sync(&self.models.servers, &items);
bridge.set_last_place(self.last_place(&items));
bridge.set_current_server(self.current.map_or(-1, |id| id as i32));
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());
@@ -487,10 +498,12 @@ impl App {
pub(crate) fn refresh_toolbar(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let bookmark = self.current.and_then(|id| self.bookmark(id));
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(bookmark.map(|b| self.server_list_icon(b)).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(),
);
@@ -504,12 +517,13 @@ impl App {
);
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(vm::avatar::image(own));
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(banner(details.map(|d| d.banner_gfx_url.as_str())));
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)));
@@ -519,8 +533,9 @@ impl App {
bridge.set_own_channel_topic(
own_channel.and_then(|c| c.topic.clone()).unwrap_or_default().into(),
);
bridge
.set_own_channel_banner(banner(own_channel.and_then(|c| c.banner_gfx_url.as_deref())));
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)),
);
@@ -552,16 +567,16 @@ impl App {
/// server.
pub(crate) fn refresh_tree(&self) {
let Some(view) = self.view() else {
vm::list::sync(&self.models.tree, &[]);
vm::list::sync(&self.models.members, &[]);
vm::list::sync(&self.models.server_members, &[]);
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.playback,
playback: &self.state.playback,
own_channel: view.state.own_channel,
own_client: view.state.own_client,
filter: "",
@@ -571,19 +586,19 @@ impl App {
groups: &view.server_groups,
channel_groups: &view.channel_groups,
};
vm::list::sync(&self.models.tree, &vm::tree::rows(&input));
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() };
vm::list::sync(&self.models.members, &members);
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.voice_view || watching);
let voice_first = connected && (self.state.voice_view || watching);
let everyone = vm::tree::server_members(&input, voice_first);
let filter = self.member_filter.trim().to_lowercase();
let filter = self.state.member_filter.trim().to_lowercase();
let shown =
if filter.is_empty() { everyone } else { vm::tree::matching(everyone, &filter) };
vm::list::sync(&self.models.server_members, &shown);
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);
@@ -592,8 +607,8 @@ impl App {
/// The members panel's search.
pub(crate) fn search_members(&mut self, text: String) {
if self.member_filter != text {
self.member_filter = text;
if self.state.member_filter != text {
self.state.member_filter = text;
self.refresh_tree();
}
}
@@ -601,7 +616,7 @@ impl App {
/// 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.voice_view = on;
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);
}
@@ -612,7 +627,8 @@ impl App {
/// 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.current.and_then(|id| self.bookmark(id)).map(|b| b.address.clone());
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)?;
@@ -629,7 +645,7 @@ impl App {
};
let path: Vec<&str> = path.iter().map(String::as_str).collect();
let link = vm::servers::invite_link(&address, &path);
self.copy_note = Some(format!("Copied an invite to {title}: {link}"));
self.state.copy_note = Some(format!("Copied an invite to {title}: {link}"));
link
}
@@ -637,7 +653,7 @@ impl App {
/// 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.sessions.get(&session) else { return };
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) {
@@ -648,11 +664,11 @@ impl App {
/// The password dialog's Join.
pub(crate) fn join_with_password(&mut self, password: String) {
let Some((session, channel)) = self.join_target.take() else { return };
let Some((session, channel)) = self.state.join_target.take() else { return };
if password.is_empty() {
return;
}
if let Some(view) = self.sessions.get_mut(&session) {
if let Some(view) = self.state.sessions.get_mut(&session) {
view.channel_passwords.insert(channel, password.clone());
}
self.enter_channel(session, channel, Some(password));
@@ -660,7 +676,7 @@ impl App {
/// 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.sessions.get_mut(&session) else { return };
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;
@@ -673,13 +689,13 @@ impl App {
}
return;
}
if self.current != Some(session) {
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.sessions.get_mut(&session)
&& let Some(view) = self.state.sessions.get_mut(&session)
{
view.join_after_connect = Some(channel);
}
@@ -691,7 +707,7 @@ impl App {
/// 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.sessions.get_mut(&session) else { return };
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;
@@ -711,12 +727,12 @@ impl App {
/// given was refused.
fn ask_channel_password(&mut self, session: i64, channel: ChannelId, wrong: bool) {
let Some(info) =
self.sessions.get(&session).and_then(|v| v.presence.channels.get(&channel))
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.join_target = Some((session, channel));
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());
@@ -731,6 +747,7 @@ impl App {
match reason {
JoinFailure::Password => {
let given = self
.state
.sessions
.get_mut(&session)
.and_then(|v| v.channel_passwords.remove(&channel))
-610
View File
@@ -1,610 +0,0 @@
//! The UI's settings keys (besides the engine's, in
//! `voelin_core::settings`), and their conversion to and from the forms of
//! the settings page.
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use voelin_audio::process::NoiseLevel;
use voelin_core::settings::{Key, Kind};
use voelin_core::{AudioSettings, TransmitMode};
use crate::app::AudioForm;
/// The window's settings, one value (the `ui` blob of earlier versions).
pub static UI: Key<UiSettings> = Key::new(
"ui",
Kind::Json,
"The window's settings: push-to-talk key, H.264, the share dialog's choices.",
UiSettings::default,
);
/// Volume and mute of clients, by unique id.
pub static CLIENT_PLAYBACK: Key<ClientPlaybackMap> = Key::new(
"client_playback",
Kind::Json,
"Volume and mute of clients, by unique id.",
ClientPlaybackMap::new,
);
/// Colours of the window.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ThemeChoice {
#[default]
Dark,
Light,
/// The system's light or dark scheme.
System,
}
impl ThemeChoice {
pub fn as_str(self) -> &'static str {
match self {
Self::Dark => "dark",
Self::Light => "light",
Self::System => "system",
}
}
pub fn parse(text: &str) -> Self {
match text {
"light" => Self::Light,
"system" => Self::System,
_ => Self::Dark,
}
}
}
/// `ui.theme`. (In a config file write `"ui.theme" = "light"` at the top:
/// a `[ui]` table would be read as the `ui` blob.)
pub static UI_THEME: Key<ThemeChoice> = Key::new(
"ui.theme",
Kind::Choice(&["dark", "light", "system"]),
"Colours of the window: dark, light, or the system's scheme.",
ThemeChoice::default,
);
fn positive_scale(v: &f32) -> Result<(), String> {
if v.is_finite() && *v > 0.0 { Ok(()) } else { Err("must be a number above 0".into()) }
}
/// `ui.font_scale`: text size, 1 = normal (no upper limit).
pub static UI_FONT_SCALE: Key<f32> =
Key::new("ui.font_scale", Kind::Json, "Text size as a factor (a number; 1 = normal).", || 1.0)
.validated(positive_scale);
/// `ui.narrow_breakpoint`: below this window width (logical pixels) the
/// phone layout is used.
pub static UI_NARROW_BREAKPOINT: Key<u32> = Key::new(
"ui.narrow_breakpoint",
Kind::UInt { min: 0 },
"Window width in pixels below which the phone layout is used.",
|| 800,
);
/// `ui.image_cache_mb`: memory for decoded images (avatars, icons, emoji).
pub static UI_IMAGE_CACHE_MB: Key<u32> = Key::new(
"ui.image_cache_mb",
Kind::UInt { min: 0 },
"Memory in MB for decoded images (avatars, icons, banners, emoji); 0 keeps none.",
|| 256,
);
/// `ui.members_width`: how wide the members and streams panel is, in
/// pixels. Dragging its handle stores it; there is no built-in maximum.
pub static UI_MEMBERS_WIDTH: Key<u32> = Key::new(
"ui.members_width",
Kind::UInt { min: 0 },
"Width of the members and streams panel in pixels.",
|| 280,
);
/// `ui.voice_compact`: the voice channel view's smaller stage (a strip of
/// people and stream rows, more room for the chat). Its toggle stores it.
pub static UI_VOICE_COMPACT: Key<bool> = Key::new(
"ui.voice_compact",
Kind::Bool,
"The voice channel view's smaller stage, leaving more room for the chat.",
|| false,
);
/// The UI's keys besides [`UI`] and [`CLIENT_PLAYBACK`], for registering.
pub fn appearance_keys() -> [&'static dyn voelin_core::settings::Setting; 6] {
[
&UI_THEME,
&UI_FONT_SCALE,
&UI_NARROW_BREAKPOINT,
&UI_IMAGE_CACHE_MB,
&UI_MEMBERS_WIDTH,
&UI_VOICE_COMPACT,
]
}
/// What a kind of notification does: nothing, the bell, or the bell and a
/// desktop notification.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum NotifyLevel {
Off,
App,
#[default]
Desktop,
}
impl NotifyLevel {
pub fn index(self) -> i32 {
self as i32
}
pub fn from_index(index: i32) -> Self {
match index {
0 => Self::Off,
1 => Self::App,
_ => Self::Desktop,
}
}
}
const NOTIFY_LEVELS: Kind = Kind::Choice(&["off", "app", "desktop"]);
/// `notify.*`: what the bell and the desktop say about each kind.
pub static NOTIFY_MENTIONS: Key<NotifyLevel> = Key::new(
"notify.mentions",
NOTIFY_LEVELS,
"Our name in a channel or server chat: off, app (the bell) or desktop.",
NotifyLevel::default,
);
pub static NOTIFY_MESSAGES: Key<NotifyLevel> = Key::new(
"notify.private_messages",
NOTIFY_LEVELS,
"Private messages: off, app (the bell) or desktop.",
NotifyLevel::default,
);
pub static NOTIFY_POKES: Key<NotifyLevel> =
Key::new("notify.pokes", NOTIFY_LEVELS, "Pokes: off, app (the bell) or desktop.", || {
NotifyLevel::Desktop
});
pub static NOTIFY_EVENTS: Key<NotifyLevel> = Key::new(
"notify.event_reminders",
NOTIFY_LEVELS,
"Reminders of scheduled events: off, app (the bell) or desktop.",
NotifyLevel::default,
);
pub static NOTIFY_FRIENDS: Key<NotifyLevel> = Key::new(
"notify.friends_online",
NOTIFY_LEVELS,
"Friends coming online: off, app (the bell) or desktop.",
|| NotifyLevel::App,
);
/// `video.camera`: the camera of the preview and the default of camera
/// sources (a device id; empty: the first camera).
pub static VIDEO_CAMERA: Key<String> = Key::new(
"video.camera",
Kind::Text { suggestions: &[] },
"Camera device (empty: the first one).",
String::new,
);
/// `video.background`: the camera's background effect.
pub static VIDEO_BACKGROUND: Key<String> = Key::new(
"video.background",
Kind::Choice(&["none", "blur"]),
"Background effect of the camera: none or blur.",
|| "none".into(),
);
/// `video.resolution`: the camera's capture size, `auto` or `WIDTHxHEIGHT`.
pub static VIDEO_RESOLUTION: Key<String> = Key::new(
"video.resolution",
Kind::Text { suggestions: &["auto", "1280x720", "1920x1080", "2560x1440"] },
"Camera resolution: auto or WIDTHxHEIGHT.",
|| "auto".into(),
)
.validated(valid_resolution);
/// `video.mirror`: show our camera mirrored, as in a mirror.
pub static VIDEO_MIRROR: Key<bool> =
Key::new("video.mirror", Kind::Bool, "Show our camera mirrored.", || true);
/// `ui.image_preview_kb`: linked pictures up to this size are downloaded
/// and shown in the chat (0: never). No maximum.
pub static UI_IMAGE_PREVIEW_KB: Key<u32> = Key::new(
"ui.image_preview_kb",
Kind::UInt { min: 0 },
"Show pictures linked in chat up to this size in KB (0: never).",
|| 8192,
);
#[allow(clippy::ptr_arg)] // a validation of `Key<String>` is `fn(&String)`
fn valid_resolution(text: &String) -> Result<(), String> {
if text == "auto" || parse_size(text).is_some() {
Ok(())
} else {
Err("auto or WIDTHxHEIGHT, e.g. 1280x720".into())
}
}
/// `1280x720` → (1280, 720), both above 0.
pub fn parse_size(text: &str) -> Option<(u32, u32)> {
let (w, h) = text.trim().split_once(['x', 'X', '×'])?;
let (w, h) = (w.trim().parse().ok()?, h.trim().parse().ok()?);
(w > 0 && h > 0).then_some((w, h))
}
/// The keys of the home, messages and settings pages, for registering.
pub fn page_keys() -> [&'static dyn voelin_core::settings::Setting; 10] {
[
&NOTIFY_MENTIONS,
&NOTIFY_MESSAGES,
&NOTIFY_POKES,
&NOTIFY_EVENTS,
&NOTIFY_FRIENDS,
&VIDEO_CAMERA,
&VIDEO_BACKGROUND,
&VIDEO_RESOLUTION,
&VIDEO_MIRROR,
&UI_IMAGE_PREVIEW_KB,
]
}
/// Frame rates and bitrates (kbit/s; 0: automatic) the share dialog
/// offers, in the order of its lists (`dialogs.slint`); any other value can
/// be typed in.
pub const FPS_CHOICES: [u32; 7] = [15, 30, 60, 120, 144, 240, 320];
pub const BITRATE_CHOICES: [u32; 8] = [0, 2500, 4608, 8000, 10_000, 20_000, 40_000, 60_000];
/// The share dialog's lists before they grew, which [`ShareDefaults`]
/// indexes for older versions.
pub const LEGACY_FPS_CHOICES: [u32; 3] = [15, 30, 60];
pub const LEGACY_BITRATE_CHOICES: [u32; 4] = [2500, 4608, 8000, 10_000];
/// The index of the choice closest to `value`.
pub fn nearest_choice(choices: &[u32], value: u32) -> usize {
(0..choices.len()).min_by_key(|&i| choices[i].abs_diff(value)).unwrap_or(0)
}
/// A whole number above 0 typed into a form field.
pub fn parse_positive(text: &str) -> Option<u32> {
text.trim().parse().ok().filter(|v| *v > 0)
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct UiSettings {
/// Global push-to-talk hotkey (besides the button in the window).
pub global_ptt: bool,
/// E.g. `Ctrl+Shift+T` (`voelin_platform::Hotkey` syntax).
pub ptt_key: String,
/// H.264 through Cisco's OpenH264, downloaded on request.
pub openh264: bool,
/// The ScreenCast portal's token for the last shared screen.
pub portal_restore_token: Option<String>,
pub share: ShareDefaults,
/// Write crash reports to disk (opt-in; never uploaded).
pub crash_reports: bool,
/// The voice channel we were in last (Home's "Continue where you left
/// off").
pub last_voice: Option<LastVoice>,
}
impl Default for UiSettings {
fn default() -> Self {
Self {
global_ptt: true,
ptt_key: "Ctrl+Shift+T".into(),
openh264: false,
portal_restore_token: None,
share: ShareDefaults::default(),
crash_reports: false,
last_voice: None,
}
}
}
/// Where we were with voice last: the bookmark with the address it had
/// then (one that now points elsewhere does not resume), and the channel's
/// path, its names from the top as the server has them.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct LastVoice {
pub bookmark: i64,
pub address: String,
pub channel: Vec<String>,
}
/// The last choices in the share dialog. Frame rate and bitrate are the
/// settings `stream.fps` and `stream.bitrate_kbps`; the indices of the
/// closest choices of the old lists ([`LEGACY_FPS_CHOICES`],
/// [`LEGACY_BITRATE_CHOICES`]) are kept for older versions.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct ShareDefaults {
pub fps_index: usize,
pub bitrate_index: usize,
pub audio: bool,
pub auto_accept: bool,
}
impl Default for ShareDefaults {
fn default() -> Self {
Self { fps_index: 1, bitrate_index: 1, audio: true, auto_accept: false }
}
}
/// Local playback of one client, kept by its unique id.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct ClientPlayback {
/// Linear, 1 = unchanged.
pub volume: f32,
pub muted: bool,
}
impl Default for ClientPlayback {
fn default() -> Self {
Self { volume: 1.0, muted: false }
}
}
impl ClientPlayback {
pub fn is_default(&self) -> bool {
*self == Self::default()
}
}
pub type ClientPlaybackMap = BTreeMap<String, ClientPlayback>;
/// Audio devices as listed in the settings: the system default first.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct DeviceChoices {
pub names: Vec<String>,
/// Device ids by index; `None` for the system default.
pub ids: Vec<Option<String>>,
}
impl DeviceChoices {
/// `devices` as `(id, name, is_default)`. A selected device that is not
/// connected stays in the list, so the choice survives.
pub fn new(devices: &[(String, String, bool)], selected: Option<&str>) -> Self {
let default_name = devices.iter().find(|d| d.2).map(|d| d.1.as_str());
let mut choices = Self {
names: vec![match default_name {
Some(name) => format!("System default ({name})"),
None => "System default".into(),
}],
ids: vec![None],
};
for (id, name, _) in devices {
choices.names.push(name.clone());
choices.ids.push(Some(id.clone()));
}
if let Some(id) = selected
&& !choices.ids.iter().any(|i| i.as_deref() == Some(id))
{
choices.names.push(format!("{id} (not connected)"));
choices.ids.push(Some(id.to_owned()));
}
choices
}
pub fn index_of(&self, id: Option<&str>) -> usize {
self.ids.iter().position(|i| i.as_deref() == id).unwrap_or(0)
}
pub fn id_at(&self, index: i32) -> Option<String> {
usize::try_from(index).ok().and_then(|i| self.ids.get(i).cloned()).flatten()
}
}
fn noise_index(level: NoiseLevel) -> i32 {
match level {
NoiseLevel::Low => 0,
NoiseLevel::Moderate => 1,
NoiseLevel::High => 2,
NoiseLevel::VeryHigh => 3,
}
}
fn noise_level(index: i32) -> NoiseLevel {
match index {
0 => NoiseLevel::Low,
2 => NoiseLevel::High,
3 => NoiseLevel::VeryHigh,
_ => NoiseLevel::Moderate,
}
}
/// The form's number for a transmit mode (`AudioForm.transmit`).
pub fn transmit_index(mode: TransmitMode) -> i32 {
match mode {
TransmitMode::PushToTalk => 0,
TransmitMode::VoiceActivation => 1,
TransmitMode::Continuous => 2,
}
}
fn transmit_mode(index: i32) -> TransmitMode {
match index {
1 => TransmitMode::VoiceActivation,
2 => TransmitMode::Continuous,
_ => TransmitMode::PushToTalk,
}
}
/// The settings page's form for `settings`.
pub fn audio_form(
settings: &AudioSettings,
inputs: &DeviceChoices,
outputs: &DeviceChoices,
) -> AudioForm {
let p = &settings.processing;
AudioForm {
input_index: inputs.index_of(settings.input_device.as_deref()) as i32,
output_index: outputs.index_of(settings.output_device.as_deref()) as i32,
transmit: transmit_index(settings.transmit),
vad_threshold: settings.vad.threshold_db,
echo_cancellation: p.echo_cancellation,
noise_suppression: p.noise_suppression,
noise_level: noise_index(p.noise_level),
auto_gain: p.auto_gain,
input_gain: p.input_gain_db,
output_volume: settings.output_volume * 100.0,
playback_buffer: settings.playback_buffer_ms as f32,
}
}
/// `settings` changed as the form says; what the form does not show stays.
pub fn apply_audio_form(
form: &AudioForm,
settings: &AudioSettings,
inputs: &DeviceChoices,
outputs: &DeviceChoices,
) -> AudioSettings {
let mut s = settings.clone();
s.input_device = inputs.id_at(form.input_index);
s.output_device = outputs.id_at(form.output_index);
s.transmit = transmit_mode(form.transmit);
s.vad.threshold_db = form.vad_threshold;
s.processing.echo_cancellation = form.echo_cancellation;
s.processing.noise_suppression = form.noise_suppression;
s.processing.noise_level = noise_level(form.noise_level);
s.processing.auto_gain = form.auto_gain;
s.processing.input_gain_db = form.input_gain;
s.output_volume = (form.output_volume / 100.0).clamp(0.0, 4.0);
s.playback_buffer_ms = form.playback_buffer.round().clamp(20.0, 180.0) as u32;
s
}
#[cfg(test)]
mod tests {
use super::*;
fn devices() -> Vec<(String, String, bool)> {
vec![
("alsa:hw:0,0".into(), "Built-in".into(), true),
("alsa:hw:1,0".into(), "Headset".into(), false),
]
}
#[test]
fn device_choices() {
let choices = DeviceChoices::new(&devices(), None);
assert_eq!(choices.names, ["System default (Built-in)", "Built-in", "Headset"]);
assert_eq!(choices.index_of(Some("alsa:hw:1,0")), 2);
assert_eq!(choices.id_at(0), None);
assert_eq!(choices.id_at(2).as_deref(), Some("alsa:hw:1,0"));
assert_eq!(choices.id_at(9), None);
// An unplugged device stays selectable.
let choices = DeviceChoices::new(&devices(), Some("usb:mic"));
assert_eq!(choices.names.last().unwrap(), "usb:mic (not connected)");
assert_eq!(choices.index_of(Some("usb:mic")), 3);
}
#[test]
fn audio_form_roundtrip() {
let inputs = DeviceChoices::new(&devices(), None);
let outputs = DeviceChoices::new(&devices(), None);
let mut settings = AudioSettings {
transmit: TransmitMode::VoiceActivation,
input_device: Some("alsa:hw:1,0".into()),
output_volume: 0.5,
playback_buffer_ms: 80,
..Default::default()
};
settings.vad.threshold_db = -35.0;
settings.processing.noise_level = NoiseLevel::High;
settings.processing.input_gain_db = 6.0;
let form = audio_form(&settings, &inputs, &outputs);
assert_eq!((form.input_index, form.output_index, form.transmit), (2, 0, 1));
assert_eq!(form.output_volume, 50.0);
assert_eq!(apply_audio_form(&form, &settings, &inputs, &outputs), settings);
let form =
AudioForm { transmit: 2, echo_cancellation: false, playback_buffer: 500.0, ..form };
let changed = apply_audio_form(&form, &settings, &inputs, &outputs);
assert_eq!(changed.transmit, TransmitMode::Continuous);
assert!(!changed.processing.echo_cancellation);
assert_eq!(changed.playback_buffer_ms, 180);
}
#[test]
fn transmit_modes() {
for (mode, index) in [
(TransmitMode::PushToTalk, 0),
(TransmitMode::VoiceActivation, 1),
(TransmitMode::Continuous, 2),
] {
assert_eq!(transmit_index(mode), index);
assert_eq!(transmit_mode(index), mode);
}
// Any other number is the default, push-to-talk (Hold to talk shows).
assert_eq!(transmit_mode(7), TransmitMode::PushToTalk);
assert_eq!(transmit_mode(-1), TransmitMode::PushToTalk);
assert_eq!(transmit_index(AudioSettings::default().transmit), 0);
}
#[test]
fn free_values() {
assert_eq!(nearest_choice(&FPS_CHOICES, 60), 2);
assert_eq!(nearest_choice(&FPS_CHOICES, 144), 4);
assert_eq!(nearest_choice(&FPS_CHOICES, 1000), 6);
assert_eq!(nearest_choice(&BITRATE_CHOICES, 0), 0, "automatic");
assert_eq!(nearest_choice(&BITRATE_CHOICES, 3000), 1);
assert_eq!(nearest_choice(&BITRATE_CHOICES, 55_000), 7);
assert_eq!(nearest_choice(&BITRATE_CHOICES, 120_000), 7);
assert_eq!(parse_positive(" 144 "), Some(144));
assert_eq!(parse_positive("0"), None);
assert_eq!(parse_positive("fast"), None);
}
#[test]
fn page_keys() {
assert_eq!(parse_size("1280x720"), Some((1280, 720)));
assert_eq!(parse_size(" 1920 × 1080 "), Some((1920, 1080)));
assert_eq!(parse_size("0x720"), None);
assert_eq!(parse_size("big"), None);
assert!(VIDEO_RESOLUTION.validate(&"auto".into()).is_ok());
assert!(VIDEO_RESOLUTION.validate(&"wide".into()).is_err());
assert_eq!(serde_json::to_value(NotifyLevel::App).unwrap(), "app");
assert_eq!(NotifyLevel::from_index(NotifyLevel::Off.index()), NotifyLevel::Off);
assert_eq!(NotifyLevel::from_index(7), NotifyLevel::Desktop);
}
#[test]
fn voice_compact_key() {
let settings = voelin_core::settings::Settings::in_memory();
for key in appearance_keys() {
settings.register(key);
}
assert_eq!(settings.get_json("ui.voice_compact"), Some(false.into()), "the full stage");
assert!(settings.apply_overrides(["ui.voice_compact=true"]).is_empty());
assert!(settings.get(&UI_VOICE_COMPACT));
assert!(settings.set_json("ui.voice_compact", "small".into()).is_err());
}
#[test]
fn ui_settings_defaults() {
let parsed: UiSettings = serde_json::from_str(r#"{"openh264":true}"#).unwrap();
assert!(parsed.openh264);
assert!(!parsed.crash_reports, "crash reports are opt-in");
assert_eq!(parsed.ptt_key, "Ctrl+Shift+T");
assert_eq!(parsed.share, ShareDefaults::default());
assert_eq!(parsed.last_voice, None, "older settings have no last channel");
let last = LastVoice {
bookmark: 3,
address: "ts.example".into(),
channel: vec!["Games".into(), "Chess".into()],
};
let settings = UiSettings { last_voice: Some(last.clone()), ..UiSettings::default() };
let json = serde_json::to_string(&settings).unwrap();
assert_eq!(serde_json::from_str::<UiSettings>(&json).unwrap().last_voice, Some(last));
assert_eq!(serde_json::to_value(ThemeChoice::System).unwrap(), "system");
assert_eq!(ThemeChoice::parse("light"), ThemeChoice::Light);
assert_eq!(ThemeChoice::parse("??"), ThemeChoice::Dark);
assert!(UI_FONT_SCALE.validate(&0.0).is_err());
assert!(UI_FONT_SCALE.validate(&3.5).is_ok());
let map: ClientPlaybackMap =
serde_json::from_str(r#"{"uid=":{"volume":0.5,"muted":false}}"#).unwrap();
assert_eq!(map["uid="].volume, 0.5);
}
}
+60 -44
View File
@@ -7,8 +7,9 @@ use voelin_core::settings::{AUDIO, CRASH_REPORTS};
use voelin_core::{Command, Source, VoiceState};
use voelin_platform::{crash, notices};
use crate::app::{App, AudioForm, Bridge, ClientAudio, later, model};
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) {
@@ -28,17 +29,20 @@ impl App {
};
let inputs = list(voelin_audio::device::input_devices(), true);
let outputs = list(voelin_audio::device::output_devices(), false);
self.inputs = DeviceChoices::new(&inputs, self.audio.input_device.as_deref());
self.outputs = DeviceChoices::new(&outputs, self.audio.output_device.as_deref());
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.inputs));
bridge.set_output_devices(names(&self.outputs));
bridge.set_audio(settings::audio_form(&self.audio, &self.inputs, &self.outputs));
bridge.set_global_ptt(self.settings.global_ptt);
bridge.set_ptt_key(self.settings.ptt_key.clone().into());
bridge.set_h264_enabled(self.settings.openh264);
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();
@@ -50,30 +54,35 @@ impl App {
}
pub(crate) fn audio_changed(&mut self, form: &AudioForm) {
let audio = settings::apply_audio_form(form, &self.audio, &self.inputs, &self.outputs);
if audio == self.audio {
let audio = settings::apply_audio_form(
form,
&self.state.audio,
&self.state.inputs,
&self.state.outputs,
);
if audio == self.state.audio {
return;
}
self.audio = audio;
self.audio_dirty = true;
self.engine.send(Command::SetAudioSettings(Box::new(self.audio.clone())));
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.audio_dirty {
if !self.state.audio_dirty {
return;
}
self.audio_dirty = false;
if let Err(e) = self.prefs.set(&AUDIO, self.audio.clone()) {
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.mic_test == on {
if self.state.mic_test == on {
return;
}
self.mic_test = on;
self.state.mic_test = on;
self.engine.send(Command::TestMicrophone { on });
if let Some(ui) = self.ui.upgrade() {
let bridge = ui.global::<Bridge>();
@@ -86,9 +95,9 @@ impl App {
pub(crate) fn apply_ptt(&mut self, enabled: bool, key: String) {
let key = key.trim().to_owned();
self.settings.global_ptt = enabled;
self.state.settings.global_ptt = enabled;
if !key.is_empty() {
self.settings.ptt_key = key.clone();
self.state.settings.ptt_key = key.clone();
}
self.store_settings();
self.ptt.set((enabled && !key.is_empty()).then_some(key));
@@ -101,7 +110,7 @@ impl App {
}
pub(crate) fn set_h264(&mut self, enabled: bool) {
self.settings.openh264 = enabled;
self.state.settings.openh264 = enabled;
self.store_settings();
self.video.set_h264(enabled);
self.refresh_h264();
@@ -111,7 +120,7 @@ impl App {
let runtime = self.engine.runtime().clone();
self.video.download_h264(&runtime, |download| {
later(move |app| {
app.video.downloaded(download, app.settings.openh264);
app.video.downloaded(download, app.state.settings.openh264);
app.refresh_h264();
});
});
@@ -131,9 +140,9 @@ impl App {
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.settings.openh264);
bridge.set_h264_enabled(self.state.settings.openh264);
bridge.set_h264_attribution(notices::OPENH264_ATTRIBUTION.into());
bridge.set_crash_reports(self.settings.crash_reports);
bridge.set_crash_reports(self.state.settings.crash_reports);
}
/// The transmit mode for the voice controls (Hold to talk shows for
@@ -143,12 +152,12 @@ impl App {
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.audio.transmit);
form.transmit = settings::transmit_index(self.state.audio.transmit);
bridge.set_audio(form);
}
pub(crate) fn set_crash_reports(&mut self, enabled: bool) {
self.settings.crash_reports = enabled;
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) {
@@ -206,27 +215,34 @@ impl App {
/// Fill the volume dialog for `client` of the current session.
pub(crate) fn open_client(&mut self, client: u16) -> bool {
let Some(id) = self.current else { return false };
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.playback.get(uid)).copied().unwrap_or_default();
self.playback_dialog = Some((id, client, info.uid.clone()));
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),
});
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.playback_dialog.clone() else { return };
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;
@@ -235,11 +251,11 @@ impl App {
// Kept by unique id; clients without one only for this connection.
if let Some(uid) = uid {
if playback.is_default() {
self.playback.remove(&uid);
self.state.playback.remove(&uid);
} else {
self.playback.insert(uid, playback);
self.state.playback.insert(uid, playback);
}
if let Err(e) = self.prefs.set(&CLIENT_PLAYBACK, self.playback.clone()) {
if let Err(e) = self.prefs.set(&CLIENT_PLAYBACK, self.state.playback.clone()) {
warn!(%e, "could not store client volumes");
}
}
@@ -264,7 +280,7 @@ impl App {
/// 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.sessions.get_mut(&session) else { return };
let Some(view) = self.state.sessions.get_mut(&session) else { return };
if view.state.voice != VoiceState::Connected
|| view.state.presence_source != Some(Source::Voice)
{
@@ -276,7 +292,7 @@ impl App {
if !view.applied_playback.insert(client.id) {
continue;
}
let stored = client.uid.as_ref().and_then(|uid| self.playback.get(uid));
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 {
File diff suppressed because it is too large. Load diff
+801
View File
@@ -0,0 +1,801 @@
//! The settings pages on the Bridge: the forms and models are filled from
//! the settings (`voelin_ui_vm::settings_pages::logic`), the controls' values
//! go back through it, and what a change sets going (the camera, the engine,
//! the identity store, threads) runs here.
use std::collections::HashSet;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use slint::{ComponentHandle, Model, SharedString};
use tracing::warn;
use voelin_core::settings::{
IDENTITY_IMPORT, STREAM_CODEC, STREAM_ENCODER_BACKEND, STREAM_HARDWARE_ACCELERATION,
STREAM_SRTP_PROFILES,
};
use voelin_core::{Command, GatewayRequest};
use voelin_gateway_proto::{Action, PermRule, UniqueIds};
use crate::app::{App, Bridge, later, model};
use crate::bind::convert;
use crate::settings::{
VIDEO_BACKGROUND, VIDEO_CAMERA, VIDEO_MIRROR, VIDEO_RESOLUTION, page_keys, parse_size,
};
use crate::vm::bridge::{
AdvancedForm, AudioSourceItem, LayerItem, NotifyForm, PrivacyForm, StreamingForm, VideoForm,
};
use crate::vm::settings_pages::logic::{
self, Discovered, IdentityFacts, Improving, group_ids, json_of,
};
impl App {
/// What storing settings had to say (a refusal, something typed wrong):
/// the status line shows it.
fn said(&mut self, messages: Vec<String>) {
for message in messages {
warn!(%message, "setting refused");
self.set_status(message);
}
}
/// A section of the settings was shown: load what it needs.
pub(crate) fn settings_section(&mut self, section: i32) {
for key in page_keys() {
self.prefs.register(key);
}
match section {
0 | 7 => {
self.load_cameras();
if section == 7 {
self.load_capture_sources();
}
}
2 => self.watch_audio_apps(),
5 | 6 => self.refresh_identities(),
9 => {
if self.pages.state.encoders_loading
|| self
.ui
.upgrade()
.is_some_and(|ui| ui.global::<Bridge>().get_encoders().row_count() == 0)
{
self.refresh_encoders();
}
self.refresh_gateways();
}
10 => self.refresh_all_settings(),
_ => {}
}
if section != 0 && section != 7 {
self.stop_camera();
}
if section != 2 {
self.pages.audio_apps = None;
}
self.refresh_pages();
}
/// Every form of the settings pages, from the settings.
pub(crate) fn refresh_pages(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let p = &self.prefs;
let video = logic::video_form(p, &self.pages.state.cameras, self.pages.camera.is_some());
bridge.set_video(video.into());
bridge.set_streaming(logic::streaming_form(p).into());
self.models.layers.sync(&logic::layer_items(p));
self.models.audio_sources.sync(&logic::audio_source_items(p, voelin_platform::APP_NAME));
bridge.set_has_studio(true);
bridge.set_notify(logic::notify_form(p).into());
bridge.set_privacy(logic::privacy_form(p).into());
let srtp = p.get(&STREAM_SRTP_PROFILES);
bridge.set_srtp_profiles(model(srtp.iter().map(SharedString::from).collect()));
bridge.set_srtp_unused(model(
logic::srtp_unused(&srtp).into_iter().map(SharedString::from).collect(),
));
let crash_dir = voelin_platform::crash::dir().map(|d| d.display().to_string());
bridge.set_advanced(
logic::advanced_form(p, &log_text(), &crash_dir.unwrap_or_default()).into(),
);
self.refresh_account();
}
/// A setting changed anywhere: fill the forms, apply what the engine
/// does not read itself.
pub(crate) fn page_setting_changed(&mut self, key: &str) {
if key == STREAM_SRTP_PROFILES.name() {
self.apply_srtp();
}
if [STREAM_HARDWARE_ACCELERATION.name(), STREAM_ENCODER_BACKEND.name(), STREAM_CODEC.name()]
.contains(&key)
{
self.video.set_encoder_preference(
voelin_core::media::encoder_preference(&self.prefs),
voelin_core::media::configured_codec(&self.prefs),
);
}
if key == VIDEO_CAMERA.name()
|| key == VIDEO_BACKGROUND.name()
|| key == VIDEO_RESOLUTION.name()
{
self.restart_camera();
}
self.refresh_pages();
if key.starts_with("stream.")
|| key.starts_with("privacy.")
|| key.starts_with("chat.")
|| key.starts_with("cache.")
{
self.refresh_all_settings();
}
}
/// The SRTP profiles of the setting, for the engine (it does not read
/// the setting itself; it takes the names and leaves out the ones its
/// stream transport does not know).
pub(crate) fn apply_srtp(&self) {
let profiles = self.prefs.get(&STREAM_SRTP_PROFILES);
self.engine.send(Command::SetSrtpProfiles(profiles.to_vec()));
}
pub(crate) fn video_changed(&mut self, form: &VideoForm) {
let messages = logic::apply_video(&self.prefs, &self.pages.state.cameras, form);
self.said(messages);
self.refresh_pages();
}
pub(crate) fn streaming_changed(&mut self, form: &StreamingForm) {
let messages = logic::apply_streaming(&self.prefs, form);
self.said(messages);
self.refresh_pages();
}
pub(crate) fn layer_changed(&mut self, index: i32, item: &LayerItem) {
let Some(messages) = logic::apply_layer(&self.prefs, index, item) else { return };
self.said(messages);
self.refresh_pages();
}
pub(crate) fn add_layer(&mut self) {
let messages = logic::add_layer(&self.prefs);
self.said(messages);
self.refresh_pages();
}
pub(crate) fn remove_layer(&mut self, index: i32) {
let messages = logic::remove_layer(&self.prefs, index);
self.said(messages);
self.refresh_pages();
}
pub(crate) fn audio_source_changed(&mut self, index: i32, item: &AudioSourceItem) {
let messages = logic::apply_audio_source(&self.prefs, index, item);
self.said(messages);
self.refresh_pages();
}
pub(crate) fn add_audio_source(&mut self, kind: &str, name: &str) {
let Some(messages) = logic::add_audio_source(&self.prefs, kind, name) else { return };
self.said(messages);
self.refresh_pages();
}
pub(crate) fn remove_audio_source(&mut self, index: i32) {
let messages = logic::remove_audio_source(&self.prefs, index);
self.said(messages);
self.refresh_pages();
}
/// Follow the applications that play audio while the Streaming page is
/// open (`tick` checks for changes).
fn watch_audio_apps(&mut self) {
if self.pages.audio_apps.is_none() && !self.demo_ui {
match voelin_core::media::audio_apps() {
Ok(apps) => self.pages.audio_apps = Some(apps),
Err(e) => warn!("cannot list applications that play audio: {e}"),
}
}
self.refresh_audio_apps();
}
pub(crate) fn refresh_audio_apps(&mut self) {
let Some(apps) = self.pages.audio_apps.as_mut() else { return };
let names: Vec<SharedString> = apps
.current()
.into_iter()
.map(|a| SharedString::from(a.binary.unwrap_or(a.name)))
.collect();
if let Some(ui) = self.ui.upgrade() {
ui.global::<Bridge>().set_audio_apps(model(names));
}
}
/// Called once a second: a changed list of audio applications.
pub(crate) fn tick_pages(&mut self) {
if self.pages.audio_apps.as_ref().is_some_and(|a| a.has_changed()) {
self.refresh_audio_apps();
}
}
pub(crate) fn notify_changed(&mut self, form: &NotifyForm) {
let messages = logic::apply_notify(&self.prefs, form);
self.said(messages);
self.refresh_pages();
}
pub(crate) fn test_notification(&mut self) {
let n =
voelin_platform::Notification::new(voelin_platform::APP_NAME, "Notifications work.");
self.engine.runtime().spawn(async move {
let result = voelin_platform::notify(&n).await;
later(move |app| {
app.set_status(match result {
Ok(()) => "A desktop notification was sent.".to_owned(),
Err(e) => format!("No desktop notification: {e}"),
});
});
});
}
pub(crate) fn privacy_changed(&mut self, form: &PrivacyForm) {
let messages = logic::apply_privacy(&self.prefs, form);
self.said(messages);
self.refresh_pages();
}
pub(crate) fn advanced_changed(&mut self, form: &AdvancedForm) {
let messages = logic::apply_advanced(&self.prefs, form);
self.said(messages);
self.refresh_pages();
}
/// Move an SRTP profile up (`-1`) or down (`1`).
pub(crate) fn srtp_move(&mut self, index: i32, by: i32) {
let Some(messages) = logic::srtp_move(&self.prefs, index, by) else { return };
self.said(messages);
self.refresh_pages();
}
/// Offer a profile, or stop offering it (one stays).
pub(crate) fn srtp_toggle(&mut self, name: &str) {
let Some(messages) = logic::srtp_toggle(&self.prefs, name) else { return };
self.said(messages);
self.refresh_pages();
}
/// Every registered setting (Advanced), filtered.
pub(crate) fn refresh_all_settings(&self) {
let filter = self.pages.state.settings_filter.trim().to_lowercase();
self.models.all_settings.sync(&logic::setting_items(&self.prefs, &filter));
}
pub(crate) fn search_settings(&mut self, text: String) {
self.pages.state.settings_filter = text;
self.refresh_all_settings();
}
/// Set a key from its JSON text; why not, when it is refused.
pub(crate) fn setting_set(&mut self, key: &str, text: &str) -> String {
match self.prefs.set_json(key, json_of(text)) {
Ok(()) => {
self.refresh_all_settings();
String::new()
}
Err(e) => {
let message = e.to_string();
self.set_status(message.clone());
message
}
}
}
pub(crate) fn setting_reset(&mut self, key: &str) {
if let Err(e) = self.prefs.reset(key) {
self.set_status(e.to_string());
}
self.refresh_all_settings();
self.refresh_pages();
}
/// The folder with the log files.
pub(crate) fn open_logs(&mut self) {
let dir = voelin_platform::logs::current().and_then(std::path::Path::parent);
let result = dir.ok_or_else(|| "no log file".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 log folder: {e}"));
}
}
// Integrations.
/// The gateways of our servers and the one being administered.
pub(crate) fn refresh_gateways(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
bridge.set_gateways(convert::model(&logic::gateway_items(&self.state)));
bridge.set_admin_session(self.pages.state.admin.map_or(-1, |s| s as i32));
let extra =
self.pages.state.admin.and_then(|s| self.state.sessions.get(&s)).map(|v| &v.extra);
self.models.gateway_config.sync(&logic::config_items(extra));
self.models.gateway_perms.sync(&logic::perm_items(extra));
}
/// Administer a gateway (`-1`: close).
pub(crate) fn gateway_admin(&mut self, session: i32) {
self.pages.state.admin = (session >= 0).then_some(i64::from(session));
if let Some(id) = self.pages.state.admin {
self.gateway_to(id, GatewayRequest::ConfigList);
self.gateway_to(id, GatewayRequest::PermList);
}
self.refresh_gateways();
}
pub(crate) fn config_set(&mut self, key: &str, text: &str) {
if let Some(id) = self.pages.state.admin {
self.gateway_to(
id,
GatewayRequest::ConfigSet { key: key.to_owned(), value: json_of(text) },
);
}
}
pub(crate) fn config_reset(&mut self, key: &str) {
if let Some(id) = self.pages.state.admin {
self.gateway_to(id, GatewayRequest::ConfigReset { key: key.to_owned() });
}
}
pub(crate) fn config_reload(&mut self) {
if let Some(id) = self.pages.state.admin {
self.gateway_to(id, GatewayRequest::ConfigReload);
}
}
pub(crate) fn perm_set(&mut self, action: &str, everyone: bool, server: &str, channel: &str) {
let (Some(id), Some(action)) = (self.pages.state.admin, Action::parse(action)) else {
return;
};
let rule = PermRule {
everyone,
server_groups: group_ids(server),
channel_groups: group_ids(channel),
};
self.gateway_to(id, GatewayRequest::PermSet { action, rule });
self.gateway_to(id, GatewayRequest::PermList);
}
pub(crate) fn perm_reset(&mut self, action: &str) {
let (Some(id), Some(action)) = (self.pages.state.admin, Action::parse(action)) else {
return;
};
self.gateway_to(id, GatewayRequest::PermReset { action });
self.gateway_to(id, GatewayRequest::PermList);
}
/// Probe the encoders off the UI thread (FFmpeg's probe can take a
/// while).
pub(crate) fn refresh_encoders(&mut self) {
self.pages.state.encoders_loading = true;
if let Some(ui) = self.ui.upgrade() {
ui.global::<Bridge>().set_encoders_loading(true);
}
let codecs = self.video.codecs();
std::thread::spawn(move || {
let report = codecs.report();
later(move |app| app.encoders_ready(report));
});
}
fn encoders_ready(&mut self, report: voelin_core::media::voelin_media::EncoderReport) {
self.pages.state.encoders_loading = false;
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
bridge.set_encoders_loading(false);
bridge.set_ffmpeg_status(logic::ffmpeg_status(&report.ffmpeg).into());
bridge.set_zero_copy_status(logic::zero_copy_status(&report.zero_copy).into());
bridge.set_encoders(convert::model(&logic::encoder_items(&report.encoders)));
bridge.set_decoders(convert::model(&logic::encoder_items(&report.decoders)));
}
/// The screens and windows that can be shared (Devices).
fn load_capture_sources(&mut self) {
let names: Vec<SharedString> =
logic::capture_source_names(self.video.sources(false, false))
.into_iter()
.map(SharedString::from)
.collect();
if let Some(ui) = self.ui.upgrade() {
ui.global::<Bridge>().set_capture_sources(model(names));
}
}
// Identities (My Account, Profiles).
/// Our unique ids (every identity, both server generations), to tell
/// our own messages.
pub(crate) fn load_own_uids(&mut self) {
let mut uids = std::collections::HashSet::new();
for e in self.store.identities().unwrap_or_default() {
if let Ok(identity) = self.store.identity(e.id) {
let ids = UniqueIds::from_omega(&identity.key().to_pub().to_ts());
uids.insert(ids.ts3);
uids.insert(ids.ts6);
}
}
self.social.own_uids = uids;
}
/// The identity servers see us as on `bookmark` (the one place that
/// picks it): the bookmark's own if it names one that exists, else the
/// store's default.
fn identity_id_for(&self, bookmark: Option<i64>) -> Option<i64> {
let entries = self.store.identities().unwrap_or_default();
bookmark
.and_then(|b| self.bookmark(b))
.and_then(|b| b.identity)
.filter(|id| entries.iter().any(|e| e.id == *id))
.or_else(|| self.default_identity_id())
}
/// The identity a connection to `bookmark` uses ([`Self::identity_id_for`]).
pub(crate) fn identity_for(&self, bookmark: Option<i64>) -> tsclientlib::Identity {
self.identity_id_for(bookmark)
.and_then(|id| self.store.identity(id).ok())
.unwrap_or_else(|| self.identity.clone())
}
/// The store's default identity (`Store::default_identity`).
fn default_identity_id(&self) -> Option<i64> {
self.store.default_identity().ok().flatten().map(|e| e.id)
}
pub(crate) fn refresh_account(&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 identity = self.identity_for(self.state.current);
let ids = UniqueIds::from_omega(&identity.key().to_pub().to_ts());
let entry_id = self.identity_id_for(self.state.current);
let name = self
.store
.identities()
.unwrap_or_default()
.into_iter()
.find(|e| Some(e.id) == entry_id)
.map(|e| e.name)
.unwrap_or_default();
bridge.set_account(
logic::account_form(bookmark, &name, &ids.ts3, &ids.ts6, identity.level()).into(),
);
}
/// The identities, the bookmarks' choices, what an import found.
pub(crate) fn refresh_identities(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let entries = self.store.identities().unwrap_or_default();
let default = self.default_identity_id();
let picks: Vec<(&str, Option<i64>)> = self
.state
.bookmarks
.iter()
.map(|b| (b.name.as_str(), self.identity_id_for(Some(b.id))))
.collect();
// What each key says: its unique id on TeamSpeak 6 servers and its level.
let keys: Vec<Option<(String, u8)>> = entries
.iter()
.map(|e| {
let identity = self.store.identity(e.id).ok()?;
let ids = UniqueIds::from_omega(&identity.key().to_pub().to_ts());
Some((ids.ts6, identity.level()))
})
.collect();
let facts: Vec<IdentityFacts> =
entries.iter().zip(keys).map(|(entry, key)| IdentityFacts { entry, key }).collect();
let improving =
|id: i64| self.pages.state.improving.get(&id).map(|i| (i.target, i.reached));
self.models.identities.sync(&logic::identity_items(&facts, default, &picks, improving));
let names: Vec<SharedString> =
logic::identity_names(&entries).into_iter().map(SharedString::from).collect();
bridge.set_identity_names(model(names));
bridge.set_bookmark_identities(convert::model(&logic::bookmark_identities(
&self.state.bookmarks,
&entries,
)));
let known: HashSet<&str> = entries.iter().map(|e| e.uid.as_str()).collect();
let found: Vec<Discovered> = self
.pages
.state
.found
.iter()
.map(|(f, picked)| Discovered {
nickname: f.nickname.clone(),
uid: f.uid(),
level: f.level(),
source: f.source.display().to_string(),
picked: *picked,
})
.collect();
bridge.set_found_identities(convert::model(&logic::found_items(&found, &known)));
bridge.set_identity_import(self.prefs.get(&IDENTITY_IMPORT));
self.refresh_account();
}
/// "delete", "export", "stop" (the default: [`Self::use_identity`]).
pub(crate) fn identity_action(&mut self, id: i32, action: &str) {
let id = i64::from(id);
match action {
"delete" => {
if self.default_identity_id() == Some(id) {
self.set_status(
"The default identity cannot be deleted; make another one the default first.",
);
return;
}
if let Err(e) = self.store.delete_identity(id) {
self.set_status(format!("Could not delete the identity: {e}"));
}
self.load_own_uids();
}
"export" => self.export_identity(id),
"stop" => {
if let Some(i) = self.pages.state.improving.remove(&id) {
i.cancel.store(true, Ordering::Relaxed);
}
}
_ => {}
}
self.refresh_identities();
}
fn export_identity(&mut self, id: i64) {
let entries = self.store.identities().unwrap_or_default();
let (Some(entry), Ok(identity)) =
(entries.iter().find(|e| e.id == id), self.store.identity(id))
else {
return;
};
let dir = dirs::download_dir().or_else(dirs::home_dir).unwrap_or_else(|| ".".into());
let file = logic::export_file_stem(&entry.name);
let path = dir.join(format!("{file}.ini"));
match voelin_core::ts::identity::write_export(&path, &entry.name, &identity) {
Ok(()) => self.set_identity_status(format!(
"Exported to {} (it holds the private key: keep it safe).",
path.display()
)),
Err(e) => self.set_identity_status(format!("Could not export: {e}")),
}
}
fn set_identity_status(&mut self, text: String) {
if let Some(ui) = self.ui.upgrade() {
ui.global::<Bridge>().set_identity_status(text.clone().into());
}
self.set_status(text);
}
pub(crate) fn rename_identity(&mut self, id: i32, name: &str) {
let name = name.trim();
if name.is_empty() {
return;
}
if let Err(e) = self.store.rename_identity(i64::from(id), name) {
self.set_status(format!("Could not rename: {e}"));
}
self.refresh_identities();
}
/// Raise an identity's level to `target` on every core, in the
/// background.
pub(crate) fn improve_identity(&mut self, id: i32, target: i32) {
let id = i64::from(id);
let Ok(identity) = self.store.identity(id) else { return };
let Ok(target) = u8::try_from(target) else { return };
if target <= identity.level() || self.pages.state.improving.contains_key(&id) {
self.set_identity_status(format!(
"The identity is at level {} already.",
identity.level()
));
return;
}
let cancel = Arc::new(AtomicBool::new(false));
self.pages
.state
.improving
.insert(id, Improving { target, reached: identity.level(), cancel: cancel.clone() });
std::thread::Builder::new()
.name("identity-level".into())
.spawn(move || {
let better =
voelin_core::ts::identity::improve_level(&identity, target, &cancel, |level| {
later(move |app| {
if let Some(i) = app.pages.state.improving.get_mut(&id) {
i.reached = i.reached.max(level);
}
app.refresh_identities();
});
});
later(move |app| app.level_reached(id, better));
})
.ok();
self.refresh_identities();
}
fn level_reached(&mut self, id: i64, better: Option<tsclientlib::Identity>) {
self.pages.state.improving.remove(&id);
if let Some(identity) = better {
match self.store.update_identity(id, &identity) {
Ok(()) => {
self.set_identity_status(format!(
"Security level {} reached.",
identity.level()
));
if self.default_identity_id() == Some(id) {
self.identity = identity;
}
}
Err(e) => self.set_identity_status(format!("Could not store the identity: {e}")),
}
}
self.refresh_identities();
}
/// Look for identities in the official clients' files.
pub(crate) fn find_identities(&mut self) {
let mut found = Vec::new();
let mut errors = Vec::new();
for path in voelin_core::ts::identity::discover() {
match voelin_core::ts::identity::read(&path) {
Ok(list) => found.extend(list),
Err(e) => errors.push(e.to_string()),
}
}
let known: std::collections::HashSet<String> =
self.store.identities().unwrap_or_default().into_iter().map(|e| e.uid).collect();
let status = logic::found_status(found.len(), errors.first().map(String::as_str));
self.pages.state.found = found
.into_iter()
.map(|f| {
let new = !known.contains(&f.uid());
(f, new)
})
.collect();
self.set_identity_status(status);
self.refresh_identities();
}
pub(crate) fn pick_found(&mut self, index: i32, on: bool) {
if let Some(f) = usize::try_from(index).ok().and_then(|i| self.pages.state.found.get_mut(i))
{
f.1 = on;
}
self.refresh_identities();
}
pub(crate) fn import_identities(&mut self) {
let picked: Vec<_> =
self.pages.state.found.iter().filter(|(_, p)| *p).map(|(f, _)| f.clone()).collect();
match voelin_core::ts::identity::import(&self.store, &picked) {
Ok(results) => {
let added = results
.iter()
.filter(|r| matches!(r, voelin_core::ts::identity::Imported::Added(_)))
.count();
self.set_identity_status(format!("{added} identities imported."));
}
Err(e) => self.set_identity_status(format!("Could not import: {e}")),
}
self.pages.state.found.clear();
self.load_own_uids();
self.refresh_identities();
}
/// The identity a bookmark connects with (0: the default).
pub(crate) fn bookmark_identity(&mut self, bookmark: i32, index: i32) {
let entries = self.store.identities().unwrap_or_default();
let identity = usize::try_from(index - 1).ok().and_then(|i| entries.get(i)).map(|e| e.id);
let Some(mut b) = self.bookmark(i64::from(bookmark)).cloned() else { return };
b.identity = identity;
if let Err(e) = self.store.update_bookmark(&b) {
self.set_status(format!("Could not save: {e}"));
return;
}
self.state.bookmarks = self.store.bookmarks().unwrap_or_default();
self.refresh_identities();
}
// Camera (Voice & Video, Devices).
fn load_cameras(&mut self) {
let mut cameras = crate::camera::list();
// Sample data never opens a real camera.
if self.demo_ui {
cameras.retain(|(id, _)| id == "synthetic");
}
self.pages.state.cameras = cameras.iter().map(|(id, _)| id.clone()).collect();
let names: Vec<SharedString> =
cameras.into_iter().map(|(_, n)| SharedString::from(n)).collect();
if let Some(ui) = self.ui.upgrade() {
ui.global::<Bridge>().set_cameras(model(names));
}
}
pub(crate) fn toggle_camera_preview(&mut self) {
if self.pages.camera.is_some() {
self.stop_camera();
} else {
self.start_camera();
}
self.refresh_pages();
}
pub(crate) fn start_camera(&mut self) {
let device =
if self.demo_ui { "synthetic".to_owned() } else { self.prefs.get(&VIDEO_CAMERA) };
let size = parse_size(&self.prefs.get(&VIDEO_RESOLUTION));
let blur = self.prefs.get(&VIDEO_BACKGROUND) == "blur";
let mirror = self.prefs.get(&VIDEO_MIRROR);
self.pages.camera =
Some(crate::camera::Preview::start(self.engine.runtime(), &device, size, blur, mirror));
if let Some(ui) = self.ui.upgrade() {
ui.global::<Bridge>().set_camera_status("Starting the camera…".into());
}
}
pub(crate) fn stop_camera(&mut self) {
if self.pages.camera.take().is_some()
&& let Some(ui) = self.ui.upgrade()
{
let bridge = ui.global::<Bridge>();
bridge.set_camera_frame(slint::Image::default());
bridge.set_camera_status(SharedString::new());
}
}
fn restart_camera(&mut self) {
if self.pages.camera.is_some() {
self.stop_camera();
self.start_camera();
}
}
/// The camera preview's newest picture (called by its timer).
pub(crate) fn camera_frame(&mut self) {
let Some(preview) = &self.pages.camera else { return };
let (frame, status) = (preview.take_picture(), preview.status());
if let Some(ui) = self.ui.upgrade() {
let bridge = ui.global::<Bridge>();
if let Some(frame) = frame {
bridge.set_camera_frame(frame);
}
bridge.set_camera_status(status.into());
}
}
/// Play a short tone on the speakers (the Test Sound button).
pub(crate) fn test_sound(&mut self) {
let device = self.state.audio.output_device.clone();
let volume = self.state.audio.output_volume;
std::thread::spawn(move || {
let result = crate::camera::play_tone(device.as_deref(), volume);
if let Err(e) = result {
later(move |app| app.set_status(format!("Cannot play the test sound: {e}")));
}
});
}
}
/// Where the logs go, for the Advanced page.
fn log_text() -> String {
match voelin_platform::logs::current() {
Some(path) => format!(
"This run logs to {} (the previous runs' next to it, the last as voelin.1.log). \
VOELIN_LOG=voelin_core=debug,voelin_ui=debug logs more; warnings also go to the terminal.",
path.display()
),
None => "Logs go to the terminal the app was started from (standard error); \
RUST_LOG=voelin_core=debug,voelin_ui=debug shows more."
.into(),
}
}
@@ -0,0 +1,27 @@
//! The settings pages added with the new design: My Account, Profiles
//! (identities), the camera and stream quality of Voice & Video, Streaming,
//! Devices, Notifications, Privacy & Safety, Integrations (gateways,
//! gateway administration, encoders) and Advanced. Every control reads and
//! writes a setting (`voelin_core::settings`, `crate::settings`) and
//! applies at once; the forms are filled again when a setting changes
//! anywhere ([`App::page_setting_changed`](crate::app::App)).
//!
//! What the pages show and what the controls change is
//! `voelin_ui_vm::settings_pages::logic`; `bind.rs` puts it on the Bridge
//! and runs the side effects (the camera, the engine, the identity store).
mod bind;
use crate::vm::settings_pages::logic::PagesState;
/// State of the settings pages.
#[derive(Default)]
pub(crate) struct Pages {
/// What needs no toolkit.
pub state: PagesState,
/// The camera preview of Voice & Video and Devices.
pub camera: Option<crate::camera::Preview>,
/// Applications playing audio (the audio sources picker), while the
/// Streaming page is open.
pub audio_apps: Option<voelin_core::media::AudioApps>,
}
+110 -156
View File
@@ -8,59 +8,24 @@
//! [`Event::FriendPresence`] adds when a friend came online, for "12m ago"
//! and the notification.
use slint::ComponentHandle;
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use slint::{ComponentHandle, ModelRc, SharedString, VecModel};
use std::sync::Arc;
use tracing::debug;
use voelin_core::{
Command, Contact, Event, FriendSpot, HistoryMessage, HistorySource, Relation, VoiceState,
};
use voelin_gateway_proto::{
Action, ActivityEntry, ConfigEntry, EventInfo, PermRuleInfo, StreamEntry,
};
use voelin_model::{ChatMessage, ChatTarget};
use crate::app::{
App, Bridge, ChatLine, ContactItem, ConversationItem, HappeningItem, LiveItem, Nav, NoticeItem,
Page, RecordingItem, SearchItem, SettingsSection,
};
use crate::app::{App, Bridge, Nav, Page, SettingsSection};
use crate::bind::rows::Rows;
use crate::settings::{
NOTIFY_EVENTS, NOTIFY_FRIENDS, NOTIFY_MENTIONS, NOTIFY_MESSAGES, NOTIFY_POKES, NotifyLevel,
};
use crate::vm;
use crate::vm::bridge::{ContactItem, NoticeItem, SearchItem};
use crate::vm::social::{ago, matches, mentions, plain};
/// What a session's gateway and voice connection add for these screens.
#[derive(Default)]
pub(crate) struct SessionExtra {
/// The gateway's stream directory.
pub directory: Vec<StreamEntry>,
/// The gateway's events by start time, and those whose answers are shown.
pub events: Vec<EventInfo>,
pub events_loaded: bool,
pub expanded: HashSet<i64>,
/// The activity feed, newest first.
pub activity: Vec<ActivityEntry>,
/// Our unique id at the gateway, and what we may do there.
pub gateway_uid: Option<String>,
pub actions: Vec<Action>,
/// Gateway administration: its keys and permission rules.
pub config: Vec<ConfigEntry>,
pub perms: Vec<PermRuleInfo>,
/// Offline messages (voice), and whether they were asked for.
pub inbox: Vec<voelin_core::OfflineMessageInfo>,
pub inbox_asked: bool,
/// Pictures linked in chat, by link (`previews.rs`).
pub previews: HashMap<String, crate::previews::Preview>,
/// When this session's presence first came (ms): friends found in it
/// then are not "coming online".
pub presence_since: i64,
/// "TeamSpeak 6", "TeamSpeak 3" once the server told what it runs;
/// empty before that, and for software nobody recognised.
pub product: String,
}
/// A poke we got.
pub(crate) struct Poke {
pub session: i64,
@@ -164,57 +129,57 @@ pub(crate) struct Social {
/// The models of these screens, set on the Bridge once.
pub(crate) struct SocialModels {
pub friends_online: Rc<VecModel<ContactItem>>,
pub friend_activity: Rc<VecModel<ContactItem>>,
pub contacts: Rc<VecModel<ContactItem>>,
pub blocked: Rc<VecModel<ContactItem>>,
pub live: Rc<VecModel<LiveItem>>,
pub recent: Rc<VecModel<ConversationItem>>,
pub sidebar_dms: Rc<VecModel<ConversationItem>>,
pub conversations: Rc<VecModel<ConversationItem>>,
pub dm_lines: Rc<VecModel<ChatLine>>,
pub happenings: Rc<VecModel<HappeningItem>>,
pub recordings: Rc<VecModel<RecordingItem>>,
pub notices: Rc<VecModel<NoticeItem>>,
pub mentions: Rc<VecModel<NoticeItem>>,
pub search: Rc<VecModel<SearchItem>>,
pub events: Rc<VecModel<crate::app::EventItem>>,
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: Rc::default(),
friend_activity: Rc::default(),
contacts: Rc::default(),
blocked: Rc::default(),
live: Rc::default(),
recent: Rc::default(),
sidebar_dms: Rc::default(),
conversations: Rc::default(),
dm_lines: Rc::default(),
happenings: Rc::default(),
recordings: Rc::default(),
notices: Rc::default(),
mentions: Rc::default(),
search: Rc::default(),
events: Rc::default(),
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(ModelRc::from(m.friends_online.clone()));
bridge.set_friend_activity(ModelRc::from(m.friend_activity.clone()));
bridge.set_contacts(ModelRc::from(m.contacts.clone()));
bridge.set_blocked(ModelRc::from(m.blocked.clone()));
bridge.set_live_rooms(ModelRc::from(m.live.clone()));
bridge.set_recent_chats(ModelRc::from(m.recent.clone()));
bridge.set_sidebar_dms(ModelRc::from(m.sidebar_dms.clone()));
bridge.set_conversations(ModelRc::from(m.conversations.clone()));
bridge.set_dm_messages(ModelRc::from(m.dm_lines.clone()));
bridge.set_happenings(ModelRc::from(m.happenings.clone()));
bridge.set_recordings(ModelRc::from(m.recordings.clone()));
bridge.set_notifications(ModelRc::from(m.notices.clone()));
bridge.set_home_mentions(ModelRc::from(m.mentions.clone()));
bridge.set_search_results(ModelRc::from(m.search.clone()));
bridge.set_events(ModelRc::from(m.events.clone()));
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
}
}
@@ -271,25 +236,31 @@ const SETTING_PAGES: [(&str, &str, SettingsSection); 11] = [
impl App {
/// The avatar picture of someone by unique id, from any session.
pub(crate) fn avatar_of(&self, uid: &str) -> slint::Image {
vm::avatar::image(self.sessions.values().find_map(|v| v.avatars.get(uid)))
pub(crate) fn avatar_of(&self, uid: &str) -> vm::ImageRef {
vm::avatar::image(self.state.sessions.values().find_map(|v| v.avatars.get(uid)))
}
/// A server's name: its bookmark's, else what the session calls it.
pub(crate) fn server_name(&self, session: i64) -> String {
self.bookmark(session).map(|b| b.name.clone()).unwrap_or_else(|| {
self.sessions.get(&session).map(|v| v.presence.server_name.clone()).unwrap_or_default()
self.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(crate) fn spots_of(&self, uid: &str) -> Vec<Spot> {
let mut ids: Vec<i64> = self.sessions.keys().copied().collect();
ids.sort_by_key(|id| self.bookmarks.iter().position(|b| b.id == *id).unwrap_or(usize::MAX));
let mut ids: Vec<i64> = self.state.sessions.keys().copied().collect();
ids.sort_by_key(|id| {
self.state.bookmarks.iter().position(|b| b.id == *id).unwrap_or(usize::MAX)
});
let mut spots = Vec::new();
for id in ids {
let view = &self.sessions[&id];
let view = &self.state.sessions[&id];
let Some(c) = view.presence.clients.values().find(|c| c.uid.as_deref() == Some(uid))
else {
continue;
@@ -314,7 +285,7 @@ impl App {
/// The title of what someone streams, if a directory or the voice
/// connection says.
fn stream_title(&self, spot: &Spot, uid: &str) -> Option<String> {
let view = self.sessions.get(&spot.session)?;
let view = self.state.sessions.get(&spot.session)?;
view.streams
.iter()
.find(|s| s.streamer == spot.client)
@@ -331,7 +302,7 @@ impl App {
let first = spots.first();
let name = if contact.nickname.is_empty() {
first
.map(|s| self.sessions[&s.session].nickname(s.client))
.map(|s| self.state.sessions[&s.session].nickname(s.client))
.unwrap_or_else(|| contact.uid.chars().take(8).collect())
} else {
contact.nickname.clone()
@@ -370,7 +341,7 @@ impl App {
format!("Contact since {}", t.with_timezone(&chrono::Local).format("%-d %b %Y"))
})
.unwrap_or_default();
let spot_texts: Vec<SharedString> = spots
let spot_texts: Vec<Arc<str>> = spots
.iter()
.map(|s| {
if s.channel_title.is_empty() {
@@ -397,7 +368,7 @@ impl App {
volume: contact.volume * 100.0,
muted: contact.muted,
since: since.into(),
spots: crate::app::model(spot_texts),
spots: spot_texts,
reachable: spots.iter().any(|s| s.voice),
selected: self.social.selected.as_deref() == Some(contact.uid.as_str()),
}
@@ -407,7 +378,7 @@ impl App {
/// then away), then by name.
fn sorted_contacts(&self, items: &mut [ContactItem]) {
items.sort_by_key(|c| {
(!c.online, !c.streaming, c.away, c.relation != "friend", c.name.to_lowercase())
(!c.online, !c.streaming, c.away, &*c.relation != "friend", c.name.to_lowercase())
});
}
@@ -417,25 +388,25 @@ impl App {
let bridge = ui.global::<Bridge>();
let m = &self.models.social;
let mut all: Vec<ContactItem> =
self.contacts.values().map(|c| self.contact_item(c)).collect();
self.state.contacts.values().map(|c| self.contact_item(c)).collect();
self.sorted_contacts(&mut all);
let friends: Vec<ContactItem> =
all.iter().filter(|c| c.relation == "friend").cloned().collect();
all.iter().filter(|c| &*c.relation == "friend").cloned().collect();
let online: Vec<ContactItem> = friends.iter().filter(|c| c.online).cloned().collect();
vm::list::sync(&m.friends_online, &online[..online.len().min(20)]);
m.friends_online.sync(&online[..online.len().min(20)]);
// Online friends first, then the others by when they were seen.
let mut activity = friends.clone();
activity.sort_by_key(|c| {
let seen = self.contacts.get(c.uid.as_str()).map_or(0, |c| c.last_seen_ms);
let since = self.social.online_since.get(c.uid.as_str()).copied().unwrap_or(0);
let seen = self.state.contacts.get(c.uid.as_ref()).map_or(0, |c| c.last_seen_ms);
let since = self.social.online_since.get(c.uid.as_ref()).copied().unwrap_or(0);
(!c.online, !c.streaming, std::cmp::Reverse(if c.online { since } else { seen }))
});
vm::list::sync(&m.friend_activity, &activity[..activity.len().min(7)]);
m.friend_activity.sync(&activity[..activity.len().min(7)]);
let blocked: Vec<ContactItem> =
all.iter().filter(|c| c.relation == "blocked").cloned().collect();
vm::list::sync(&m.blocked, &blocked);
all.iter().filter(|c| &*c.relation == "blocked").cloned().collect();
m.blocked.sync(&blocked);
bridge.set_contacts_online(
all.iter().filter(|c| c.online && c.relation != "blocked").count() as i32,
all.iter().filter(|c| c.online && &*c.relation != "blocked").count() as i32,
);
bridge.set_contacts_all(all.len() as i32);
bridge.set_contacts_blocked(blocked.len() as i32);
@@ -443,22 +414,22 @@ impl App {
let shown: Vec<ContactItem> = all
.iter()
.filter(|c| match self.social.friends_tab {
0 => c.online && c.relation != "blocked",
2 => c.relation == "blocked",
0 => c.online && &*c.relation != "blocked",
2 => &*c.relation == "blocked",
_ => true,
})
.filter(|c| matches(filter, &[&c.name, &c.uid, &c.note]))
.cloned()
.collect();
vm::list::sync(&m.contacts, &shown);
m.contacts.sync(&shown);
let selected = self
.social
.selected
.as_ref()
.and_then(|uid| all.iter().find(|c| c.uid.as_str() == uid))
.and_then(|uid| all.iter().find(|c| c.uid.as_ref() == uid))
.cloned()
.unwrap_or_default();
bridge.set_contact(selected);
bridge.set_contact(selected.into());
}
pub(crate) fn friends_tab(&mut self, tab: i32) {
@@ -478,15 +449,15 @@ impl App {
/// Change a contact (or make one of someone we see).
fn update_contact(&mut self, uid: &str, f: impl FnOnce(&mut Contact)) {
let mut contact = self.contacts.get(uid).cloned().unwrap_or_else(|| {
let mut contact = self.state.contacts.get(uid).cloned().unwrap_or_else(|| {
let mut c = Contact::new(uid);
if let Some(s) = self.spots_of(uid).first() {
c.nickname = self.sessions[&s.session].nickname(s.client);
c.nickname = self.state.sessions[&s.session].nickname(s.client);
}
c
});
f(&mut contact);
self.contacts.insert(uid.to_owned(), contact.clone());
self.state.contacts.insert(uid.to_owned(), contact.clone());
if !self.demo_ui {
self.engine.send(Command::SetContact { contact: Box::new(contact) });
}
@@ -516,7 +487,7 @@ impl App {
"neutral" => self.update_contact(uid, |c| c.relation = Relation::Neutral),
"mute" => self.update_contact(uid, |c| c.muted = !c.muted),
"remove" => {
self.contacts.remove(uid);
self.state.contacts.remove(uid);
if self.social.selected.as_deref() == Some(uid) {
self.social.selected = None;
}
@@ -558,14 +529,14 @@ impl App {
if s.voice {
self.watch_client(s.client);
} else {
self.pending_watch = Some((s.session, s.client));
self.state.pending_watch = Some((s.session, s.client));
self.join_person(&[s]);
}
}
/// The server page of a session.
pub(crate) fn show_server(&mut self, session: i64) {
if self.current != Some(session) {
if self.state.current != Some(session) {
self.select_server(session);
}
self.navigate(|nav| nav.invoke_show(Page::Server));
@@ -653,14 +624,14 @@ impl App {
};
let notices = &self.social.notices;
let items: Vec<NoticeItem> = notices.iter().map(item).collect();
vm::list::sync(&self.models.social.notices, &items);
self.models.social.notices.sync(&items);
let mentions: Vec<NoticeItem> = notices
.iter()
.filter(|n| n.unread && n.kind == NoticeKind::Mention)
.take(3)
.map(item)
.collect();
vm::list::sync(&self.models.social.mentions, &mentions);
self.models.social.mentions.sync(&mentions);
let unread = notices.iter().filter(|n| n.unread).count();
ui.global::<Bridge>().set_notifications_unread(unread as i32);
}
@@ -703,7 +674,7 @@ impl App {
/// Our nickname in a session.
fn own_nick(&self, session: i64) -> String {
let view = self.sessions.get(&session);
let view = self.state.sessions.get(&session);
view.and_then(|v| v.state.own_client.map(|c| v.nickname(c)))
.or_else(|| self.bookmark(session).map(|b| b.nickname.clone()))
.unwrap_or_default()
@@ -711,7 +682,7 @@ impl App {
/// Whether a message is ours.
pub(crate) fn is_own(&self, session: i64, message: &ChatMessage) -> bool {
let own_client = self.sessions.get(&session).and_then(|v| v.state.own_client);
let own_client = self.state.sessions.get(&session).and_then(|v| v.state.own_client);
own_message(&self.social.own_uids, own_client, message)
}
@@ -741,6 +712,7 @@ impl App {
}
let place = match target {
ChatTarget::Channel(cid) => self
.state
.sessions
.get(&session)
.and_then(|v| v.presence.channels.get(cid))
@@ -766,7 +738,7 @@ impl App {
let mut touched = Touched::default();
match event {
Event::Presence { session, .. } => {
let view = self.sessions.entry(*session as i64).or_default();
let view = self.state.sessions.entry(*session as i64).or_default();
if view.extra.presence_since == 0 {
view.extra.presence_since = now_ms();
}
@@ -775,9 +747,9 @@ impl App {
}
Event::State { session, state } => {
let id = *session as i64;
let was = self.sessions.get(&id).map(|v| v.state.voice);
let was = self.state.sessions.get(&id).map(|v| v.state.voice);
if state.voice != VoiceState::Connected {
if let Some(view) = self.sessions.get_mut(&id) {
if let Some(view) = self.state.sessions.get_mut(&id) {
view.extra.inbox_asked = false;
}
} else if was != Some(VoiceState::Connected) {
@@ -787,7 +759,7 @@ impl App {
touched.home = true;
}
Event::ServerInfo { session, backend, .. } => {
self.sessions.entry(*session as i64).or_default().extra.product =
self.state.sessions.entry(*session as i64).or_default().extra.product =
backend.product.clone();
touched.people = true;
touched.home = true;
@@ -832,7 +804,7 @@ impl App {
}
Event::Chat { session, message } => {
let id = *session as i64;
if !self.sessions.get(&id).is_some_and(|v| v.has_history()) {
if !self.state.sessions.get(&id).is_some_and(|v| v.has_history()) {
self.chat_notice(id, message);
touched.chats = true;
}
@@ -841,6 +813,7 @@ impl App {
let id = *session as i64;
if *source == HistorySource::Live {
let known: HashSet<i64> = self
.state
.sessions
.get(&id)
.and_then(|v| v.tabs.iter().find(|t| t.target == *target))
@@ -857,7 +830,7 @@ impl App {
Event::OfflineMessages { session, result, .. } => {
match result {
Ok(list) => {
self.sessions.entry(*session as i64).or_default().extra.inbox =
self.state.sessions.entry(*session as i64).or_default().extra.inbox =
list.clone();
}
Err(e) => debug!("offline messages: {e}"),
@@ -899,13 +872,14 @@ impl App {
self.social.online_since.insert(uid.to_owned(), now);
// Friends found in a session's first presence were there before.
let new = sessions.iter().all(|s| {
self.sessions.get(&(s.session as i64)).is_some_and(|v| {
self.state.sessions.get(&(s.session as i64)).is_some_and(|v| {
v.extra.presence_since > 0 && now - v.extra.presence_since > 10_000
})
});
if new {
let s = &sessions[0];
let channel = self
.state
.sessions
.get(&(s.session as i64))
.and_then(|v| v.presence.channels.get(&s.channel))
@@ -951,9 +925,10 @@ impl App {
};
if !people_only {
let servers = self
.state
.bookmarks
.iter()
.zip(vm::servers::tints(&self.bookmarks))
.zip(vm::servers::tints(&self.state.bookmarks))
.filter(|(b, _)| matches(&query, &[&b.name, &b.address]))
.map(|(b, tint)| {
(
@@ -974,8 +949,8 @@ impl App {
}
if !query.is_empty() && !people_only {
let mut channels = Vec::new();
for b in &self.bookmarks {
let Some(view) = self.sessions.get(&b.id) else { continue };
for b in &self.state.bookmarks {
let Some(view) = self.state.sessions.get(&b.id) else { continue };
for (channel, title) in
vm::social::found_channels(view.presence.channels.values(), &query)
{
@@ -995,8 +970,8 @@ impl App {
if !query.is_empty() || people_only {
let mut people = Vec::new();
let mut seen: HashSet<String> = HashSet::new();
for b in &self.bookmarks {
let Some(view) = self.sessions.get(&b.id) else { continue };
for b in &self.state.bookmarks {
let Some(view) = self.state.sessions.get(&b.id) else { continue };
for c in view.presence.clients.values() {
if c.is_query || Some(c.id) == view.state.own_client {
continue;
@@ -1026,7 +1001,7 @@ impl App {
));
}
}
for c in self.contacts.values() {
for c in self.state.contacts.values() {
if seen.contains(&c.uid) || !matches(&query, &[&c.nickname, &c.note]) {
continue;
}
@@ -1069,7 +1044,7 @@ impl App {
group(&mut items, "Settings", pages);
}
self.social.found = found;
vm::list::sync(&self.models.social.search, &items);
self.models.social.search.sync(&items);
}
/// Open a search result.
@@ -1103,33 +1078,12 @@ impl App {
}
}
/// What a privacy or notification choice is as an index, and back.
pub(crate) fn allowed_index(a: voelin_core::settings::Allowed) -> i32 {
match a {
voelin_core::settings::Allowed::Everyone => 0,
voelin_core::settings::Allowed::Friends => 1,
voelin_core::settings::Allowed::Nobody => 2,
}
}
pub(crate) fn allowed_of(index: i32) -> voelin_core::settings::Allowed {
match index {
1 => voelin_core::settings::Allowed::Friends,
2 => voelin_core::settings::Allowed::Nobody,
_ => voelin_core::settings::Allowed::Everyone,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn privacy_indices() {
for i in 0..3 {
assert_eq!(allowed_index(allowed_of(i)), i);
}
assert_eq!(allowed_of(9), voelin_core::settings::Allowed::Everyone);
fn notice_names_and_setting_pages() {
assert_eq!(NoticeKind::Poke.name(), "poke");
assert!(SETTING_PAGES.iter().any(|(t, _, _)| *t == "Voice & Video"));
}
+60 -58
View File
@@ -2,6 +2,7 @@
//! viewer. The engine runs the stream sessions; `video.rs` captures,
//! encodes and decodes.
use std::sync::Arc;
use std::time::Duration;
use slint::{ComponentHandle, Model};
@@ -15,14 +16,14 @@ use voelin_core::stream::{
};
use voelin_core::{Command, Event, StreamState, WatchState};
use crate::app::{
App, Bridge, ShareForm, SourceItem, StreamItem, ViewerItem, later, model, with_app,
};
use crate::app::{App, Bridge, later, with_app};
use crate::bind::convert;
use crate::settings::{
BITRATE_CHOICES, FPS_CHOICES, LEGACY_BITRATE_CHOICES, LEGACY_FPS_CHOICES, ShareDefaults,
nearest_choice, parse_positive,
};
use crate::video::{self, Capture, CaptureRequest, Decoder};
use crate::vm::bridge::{ShareForm, SourceItem, StreamItem, ViewerItem};
/// Our stream.
pub(crate) struct Share {
@@ -111,11 +112,11 @@ impl Watch {
}
/// "Auto" and one entry per layer the streamer offers.
fn qualities(&self) -> Vec<slint::SharedString> {
fn qualities(&self) -> Vec<Arc<str>> {
if self.layers.len() < 2 {
return Vec::new();
}
let mut names = vec![slint::SharedString::from("Auto")];
let mut names: Vec<Arc<str>> = vec!["Auto".into()];
names.extend(self.layers.iter().map(|l| layer_name(l).into()));
names
}
@@ -184,17 +185,18 @@ impl App {
pub(crate) fn stream_event(&mut self, event: Event) {
match event {
Event::StreamsChanged { session, streams } => {
let view = self.sessions.entry(session as i64).or_default();
let view = self.state.sessions.entry(session as i64).or_default();
// Development switch: watch the first stream that shows up.
let autowatch = std::env::var("VOELIN_AUTOWATCH").is_ok_and(|v| v == "1")
&& self.watch.is_none()
&& self.current == Some(session as i64);
&& self.state.current == Some(session as i64);
let first = streams
.iter()
.find(|s| view.state.own_client != Some(s.streamer))
.map(|s| s.id.clone());
// A client whose stream was asked for while it was looked up.
let pending = self
.state
.pending_watch
.filter(|(s, _)| *s == session as i64)
.and_then(|(_, client)| streams.iter().find(|s| s.streamer == client))
@@ -203,7 +205,7 @@ impl App {
self.refresh_streams();
self.refresh_servers();
if let Some(id) = pending {
self.pending_watch = None;
self.state.pending_watch = None;
self.watch_stream(id);
} else if autowatch && let Some(id) = first {
self.watch_stream(id);
@@ -211,7 +213,7 @@ impl App {
}
Event::StreamState { session, state } => self.share_state(session as i64, state),
Event::StreamViewerRequest { session, viewer, .. } => {
let name = self.sessions.entry(session as i64).or_default().nickname(viewer);
let name = self.state.sessions.entry(session as i64).or_default().nickname(viewer);
self.set_status(format!("{name} wants to watch your stream"));
}
Event::StreamViewers { session, viewers } => {
@@ -252,7 +254,8 @@ impl App {
StreamState::Ended(reason) => {
let local = reason == EndReason::Local || share.stopping;
self.share = None;
self.share_error = if local { String::new() } else { share_end_text(&reason) };
self.state.share_error =
if local { String::new() } else { share_end_text(&reason) };
self.set_status(if local {
"You stopped sharing".into()
} else {
@@ -300,7 +303,7 @@ impl App {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let view = self.view();
let current = self.current;
let current = self.state.current;
let mut items: Vec<StreamItem> = Vec::new();
if let Some(view) = view.filter(|v| v.streams_available()) {
// Every channel's streams (they can be watched from anywhere),
@@ -362,19 +365,19 @@ impl App {
});
}
bridge.set_streams_available(self.demo || view.is_some_and(|v| v.streams_available()));
crate::vm::list::sync(&self.models.streams, &items);
self.models.streams.sync(&items);
bridge.set_can_share(video::AVAILABLE);
let share = self.share.as_ref().filter(|s| Some(s.session) == current);
let state = match share {
Some(s) if s.live => "live",
Some(_) => "starting",
None if self.share_busy => "starting",
None if self.state.share_busy => "starting",
None => "",
};
bridge.set_share_state(state.into());
bridge.set_share_busy(self.share_busy);
bridge.set_share_error(self.share_error.clone().into());
bridge.set_share_busy(self.state.share_busy);
bridge.set_share_error(self.state.share_error.clone().into());
bridge.set_share_audio(share.is_some_and(|s| s.capture.has_audio()));
let viewers: Vec<ViewerItem> = share
.map(|s| {
@@ -397,13 +400,13 @@ impl App {
.collect()
})
.unwrap_or_default();
let requests = viewers.iter().filter(|v| v.state == "requested").count();
let requests = viewers.iter().filter(|v| &*v.state == "requested").count();
bridge.set_share_requests(requests as i32);
crate::vm::list::sync(&self.models.viewers, &viewers);
self.models.viewers.sync(&viewers);
let status = match share {
Some(s) if s.live => s.capture.status(),
Some(s) => format!("Starting the stream of {}…", s.capture.source_name()),
None if self.share_busy => "Starting the capture…".into(),
None if self.state.share_busy => "Starting the capture…".into(),
None => String::new(),
};
bridge.set_share_status(status.into());
@@ -437,7 +440,7 @@ impl App {
// The watched stream's server, which the main window may have left
// while the stream plays in its own.
let view = match watch.session {
Some(id) => self.sessions.get(&id),
Some(id) => self.state.sessions.get(&id),
None => self.view(),
};
let decoded = watch.decoder.as_ref().map(Decoder::info).unwrap_or_default();
@@ -455,10 +458,7 @@ impl App {
);
// The members are the current server's.
let members = &self.models.members;
let admin = self.watch_here()
&& (0..members.row_count())
.filter_map(|i| members.row_data(i))
.any(|m| m.id == streamer && m.admin);
let admin = self.watch_here() && members.rows().iter().any(|m| m.id == streamer && m.admin);
let channel = u16::try_from(streamer).ok().and_then(|id| {
let view = view?;
let channel = view.presence.channels.get(&view.channel_of(id)?)?;
@@ -472,19 +472,19 @@ impl App {
.layer
.and_then(|id| watch.layers.iter().position(|l| l.id == id))
.map_or(0, |i| i as i32 + 1);
crate::vm::list::sync(&self.models.qualities, &qualities);
self.models.qualities.sync(&qualities);
self.viewer_each(|bridge| {
bridge.set_viewer_popped(popped);
bridge.set_viewer_title(watch.title.as_str().into());
bridge.set_viewer_status(watch.status.as_str().into());
bridge.set_viewer_ended(watch.ended);
bridge.set_viewer_has_frame(watch.has_frame);
bridge.set_viewer_volume(self.stream_volume);
bridge.set_viewer_volume(self.state.stream_volume);
bridge.set_viewer_info(info.as_str().into());
bridge.set_viewer_streamer(watch.streamer.as_str().into());
bridge.set_viewer_streamer_avatar(face.avatar.clone());
bridge.set_viewer_streamer_initials(face.initials.clone());
bridge.set_viewer_streamer_tint(face.tint);
bridge.set_viewer_streamer_avatar(convert::image(&face.avatar));
bridge.set_viewer_streamer_initials(face.initials.as_ref().into());
bridge.set_viewer_streamer_tint(convert::color(face.tint));
bridge.set_viewer_streamer_admin(admin);
bridge.set_viewer_channel(channel.clone());
bridge.set_viewer_elapsed(elapsed.clone());
@@ -499,7 +499,7 @@ impl App {
/// The watched stream is on the server on screen (or is the local test
/// stream).
pub(crate) fn watch_here(&self) -> bool {
self.watch.as_ref().is_some_and(|w| w.session.is_none() || w.session == self.current)
self.watch.as_ref().is_some_and(|w| w.session.is_none() || w.session == self.state.current)
}
/// A simulcast layer of the watched stream (0: follow the bandwidth
@@ -543,7 +543,7 @@ impl App {
if self.share.is_some() {
self.refresh_streams();
}
// The share dialog's audio mixer (studio.rs).
// The share dialog's audio mixer (studio/).
self.mixer_tick();
if self.watch.is_some() {
self.refresh_viewer();
@@ -557,16 +557,16 @@ impl App {
let test_pattern = cfg!(debug_assertions)
|| self.demo
|| std::env::var("VOELIN_TEST_PATTERN").is_ok_and(|v| v == "1");
let restorable = self.settings.portal_restore_token.is_some();
let restorable = self.state.settings.portal_restore_token.is_some();
let sources = match self.video.sources(test_pattern, restorable) {
Ok(sources) => {
if self.share.is_none() {
self.share_error.clear();
self.state.share_error.clear();
}
sources
}
Err(e) => {
self.share_error = e;
self.state.share_error = e;
Vec::new()
}
};
@@ -575,13 +575,14 @@ impl App {
.into_iter()
.map(|(name, detail)| SourceItem { name: name.into(), detail: detail.into() })
.collect();
ui.global::<Bridge>().set_share_sources(model(items));
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 defaults = &self.settings.share;
let nickname = self.current.and_then(|id| self.bookmark(id)).map(|b| b.nickname.clone());
let defaults = &self.state.settings.share;
let nickname =
self.state.current.and_then(|id| self.bookmark(id)).map(|b| b.nickname.clone());
let (fps, bitrate) = (self.prefs.get(&STREAM_FPS), self.prefs.get(&STREAM_BITRATE_KBPS));
ShareForm {
source: 0,
@@ -630,12 +631,13 @@ impl App {
}
pub(crate) fn start_share(&mut self, form: ShareForm) {
let Some(session) = self.current else { return };
if self.share_busy || self.share.is_some() {
let Some(session) = self.state.current else { return };
if self.state.share_busy || self.share.is_some() {
return;
}
if self.studio_streams_to(session) {
self.share_error = "The Stream Studio is live here: end that stream first.".into();
self.state.share_error =
"The Stream Studio is live here: end that stream first.".into();
self.refresh_streams();
return;
}
@@ -663,12 +665,12 @@ impl App {
};
// The mixer's sources (the sample studio's with VOELIN_DEMO_UI).
let sources = self.studio_settings().get(&STREAM_AUDIO_SOURCES);
let token = self.settings.portal_restore_token.clone();
let token = self.state.settings.portal_restore_token.clone();
let request = capture_request(fps, bitrate, form.audio, &sources, token);
self.settings.share = defaults;
self.state.settings.share = defaults;
self.store_settings();
self.share_busy = true;
self.share_error.clear();
self.state.share_busy = true;
self.state.share_error.clear();
self.refresh_streams();
let setup = StreamSetup {
name: form.name.trim().to_owned(),
@@ -692,16 +694,16 @@ impl App {
auto_accept: bool,
result: Result<Capture, String>,
) {
self.share_busy = false;
self.state.share_busy = false;
match result {
Err(e) => {
self.share_error = format!("Could not start the capture: {e}");
self.state.share_error = format!("Could not start the capture: {e}");
}
Ok(capture) => {
if let Some(token) = capture.restore_token()
&& self.settings.portal_restore_token.as_ref() != Some(&token)
&& self.state.settings.portal_restore_token.as_ref() != Some(&token)
{
self.settings.portal_restore_token = Some(token);
self.state.settings.portal_restore_token = Some(token);
self.store_settings();
}
if setup.bitrate == 0 {
@@ -753,7 +755,7 @@ impl App {
}
}
/// The running share's streamer (the mixer's rows, studio.rs).
/// 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())
}
@@ -793,8 +795,8 @@ impl App {
self.start_demo();
return;
}
let Some(session) = self.current else { return };
let Some(view) = self.sessions.get(&session) else { return };
let Some(session) = self.state.current else { return };
let Some(view) = self.state.sessions.get(&session) else { return };
let Some(info) = view.streams.iter().find(|s| s.id == stream_id) else { return };
let streamer = view.nickname(info.streamer);
let title =
@@ -803,11 +805,11 @@ impl App {
self.stop_watching();
self.engine
.send(Command::WatchStream { session: session as u64, stream_id: stream_id.clone() });
if self.stream_volume != 100.0 {
if self.state.stream_volume != 100.0 {
self.engine.send(Command::SetStreamVolume {
session: session as u64,
stream_id: stream_id.clone(),
volume: self.stream_volume / 100.0,
volume: self.state.stream_volume / 100.0,
});
}
let wake = || later(|app| app.show_picture());
@@ -838,17 +840,17 @@ impl App {
/// the lookup brings it (it may have started in another channel or
/// before we joined).
pub(crate) fn watch_client(&mut self, client: u16) {
let Some(session) = self.current else { return };
let Some(view) = self.sessions.get(&session) else { return };
let Some(session) = self.state.current else { return };
let Some(view) = self.state.sessions.get(&session) else { return };
if view.state.own_client == Some(client) {
return;
}
if let Some(id) = view.streams.iter().find(|s| s.streamer == client).map(|s| s.id.clone()) {
self.pending_watch = None;
self.state.pending_watch = None;
self.watch_stream(id);
} else if view.presence.clients.get(&client).is_some_and(|c| c.streaming == Some(true)) {
let name = view.nickname(client);
self.pending_watch = Some((session, client));
self.state.pending_watch = Some((session, client));
self.set_status(format!("Looking up {name}'s stream…"));
}
}
@@ -974,14 +976,14 @@ impl App {
}
pub(crate) fn set_stream_volume(&mut self, percent: f32) {
self.stream_volume = percent.round().clamp(0.0, 200.0);
self.state.stream_volume = percent.round().clamp(0.0, 200.0);
if let Some(watch) = &self.watch
&& let Some(session) = watch.session
{
self.engine.send(Command::SetStreamVolume {
session: session as u64,
stream_id: watch.stream_id.clone(),
volume: self.stream_volume / 100.0,
volume: self.state.stream_volume / 100.0,
});
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+103
View File
@@ -0,0 +1,103 @@
//! The Stream Studio: the controller behind its page in the main window, its
//! window of its own and the phone layout (ui/screens/studio*.slint,
//! ui/studio-window.slint).
//!
//! The engine's studio (`voelin_core::studio`) composites the scenes; a
//! `Streamer` started for it encodes the composite from the start, so the
//! recording and the replay buffer need no live stream, and going live
//! attaches it to a TeamSpeak stream of our voice channel like any share.
//! The studio runs while it is shown, live or recording.
//!
//! Both windows' StudioBridge globals show the same models (shared
//! rows) and get the same values; their callbacks come here
//! (bind/studio.rs). Commands go to the studio through one task, in order.
//!
//! What the studio decides (where the stream goes, what the header says,
//! what the controls change) is `voelin_ui_vm::studio::logic`; `bind.rs` runs
//! the studio and puts the rows and values on the two windows.
mod bind;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use slint::{Rgba8Pixel, SharedPixelBuffer};
use tokio::sync::mpsc;
use voelin_core::media::voelin_media::mix::SourceHandle;
use voelin_core::media::{AudioApps, Latest, Streamer};
use voelin_core::studio::scene::Source;
use voelin_core::studio::{self, Studio};
use crate::app::StudioWindow;
use crate::bind::rows::Rows;
use crate::vm;
use crate::vm::studio::Overlay;
use crate::vm::studio::logic::StudioData;
type Picture = SharedPixelBuffer<Rgba8Pixel>;
/// The models both windows show.
#[derive(Default)]
struct Models {
scenes: Rows<vm::studio_bridge::StudioScene>,
sources: Rows<vm::studio_bridge::StudioSource>,
audio: Rows<vm::studio_bridge::StudioAudio>,
layers: Rows<vm::studio_bridge::StudioLayer>,
viewers: Rows<vm::studio_bridge::StudioViewer>,
destinations: Rows<vm::studio_bridge::StudioPick>,
picks: Rows<vm::studio_bridge::StudioPick>,
/// The destination channel's chat (`studio_sync_chat`).
chat: Rows<vm::bridge::ChatLine>,
}
/// A change of the scene graph, applied in order by one task.
enum Op {
Apply(studio::Command),
/// A source for the live scene (a new scene if there is none).
Add(Source),
/// Keep the overlay sources as asked.
Overlays(Vec<Overlay>),
}
/// A running studio.
struct Running {
studio: Arc<Studio>,
/// Encodes the composite; `None` until it started (or if it failed).
streamer: Option<Streamer>,
ops: mpsc::UnboundedSender<Op>,
/// The newest preview picture, for the UI thread.
pictures: Arc<Latest<Picture>>,
/// Stops the preview thread.
stop: Arc<AtomicBool>,
tasks: Vec<tokio::task::JoinHandle<()>>,
/// The mixer's meters, about 15 times a second.
_meters: slint::Timer,
}
impl Drop for Running {
fn drop(&mut self) {
self.stop.store(true, Ordering::Relaxed);
for task in &self.tasks {
task.abort();
}
}
}
/// The studio's state on the UI thread (`App::studio`).
#[derive(Default)]
pub(crate) struct StudioState {
models: Models,
/// The main window's globals have the models.
attached: bool,
/// The studio in a window of its own.
pub(crate) window: Option<StudioWindow>,
run: Option<Running>,
starting: bool,
/// What the studio knows apart from its running parts.
data: StudioData,
/// Applications that play audio, for the audio picker.
apps: Option<AudioApps>,
/// The mixer source of each audio row.
meters: Vec<Option<SourceHandle>>,
has_preview: bool,
}
-95
View File
@@ -1,95 +0,0 @@
//! Avatars without pictures: initials on a colour from the name.
use slint::Color;
use unicode_segmentation::UnicodeSegmentation;
/// Background colours for initials; white text reads on all of them.
const TINTS: [u32; 10] = [
0x2d6bff, 0x7c4dff, 0xc2379a, 0xe0572e, 0xd08a00, 0x1f9d6b, 0x0c93b8, 0x5865f2, 0xa0439e,
0x3a7d44,
];
/// Up to two letters: the first letters of the first two words, or the
/// first two of a single word ("Nova Star" → "NS", "dex" → "DE").
pub fn initials(name: &str) -> String {
let words: Vec<&str> = name
.split(|c: char| c.is_whitespace() || c == '_' || c == '-' || c == '.')
.filter(|w| w.chars().any(char::is_alphanumeric))
.collect();
let first = |w: &str| w.chars().find(|c| c.is_alphanumeric());
let letters: String = match words.as_slice() {
[] => String::new(),
[one] => one.chars().filter(|c| c.is_alphanumeric()).take(2).collect(),
[a, b, ..] => first(a).into_iter().chain(first(b)).collect(),
};
letters.to_uppercase()
}
/// The first letter of `initials`, for avatars too small for two ("NS" →
/// "N").
pub fn first_letter(initials: &str) -> String {
initials.graphemes(true).next().unwrap_or_default().to_owned()
}
/// A picture from the engine's cache (an avatar, a group icon), decoded
/// once; an empty image when there is none.
pub fn image(path: Option<&std::path::PathBuf>) -> slint::Image {
path.map(|p| crate::images::file(p)).unwrap_or_default()
}
/// A stable number for a name, in any case (FNV-1a).
pub fn name_hash(name: &str) -> u32 {
let mut hash: u32 = 0x811c_9dc5;
for b in name.to_lowercase().bytes() {
hash ^= u32::from(b);
hash = hash.wrapping_mul(0x0100_0193);
}
hash
}
/// `0xrrggbb` as a colour.
pub fn rgb(rgb: u32) -> Color {
Color::from_rgb_u8((rgb >> 16) as u8, (rgb >> 8) as u8, rgb as u8)
}
/// A stable colour for a name.
pub fn tint(name: &str) -> Color {
rgb(TINTS[(name_hash(name) % TINTS.len() as u32) as usize])
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn initials_of_names() {
assert_eq!(initials("Nova Star"), "NS");
assert_eq!(initials("dex"), "DE");
assert_eq!(initials("x"), "X");
assert_eq!(initials("dark_knight"), "DK");
assert_eq!(initials(" "), "");
assert_eq!(initials("[Bot] Relay"), "BR");
assert_eq!(initials("Ärger über"), "ÄÜ");
}
#[test]
fn first_letter_of_initials() {
assert_eq!(first_letter("NS"), "N");
assert_eq!(first_letter("ÄÜ"), "Ä");
assert_eq!(first_letter(""), "");
assert_eq!(first_letter("X"), "X");
// A letter with a combining mark stays whole.
assert_eq!(first_letter("A\u{308}B"), "A\u{308}");
}
#[test]
fn tints_are_stable() {
assert_eq!(tint("Alice"), tint("alice"));
let distinct: std::collections::HashSet<_> =
["Alice", "Bob", "Carol", "Dave", "Eve", "Mallory"]
.iter()
.map(|n| tint(n).as_argb_encoded())
.collect();
assert!(distinct.len() > 2);
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
-114
View File
@@ -1,114 +0,0 @@
//! Home's "Continue where you left off": the voice channel we were in last,
//! if it can still be reached.
use voelin_core::VoiceState;
use voelin_store::Bookmark;
use crate::settings::LastVoice;
/// What the card's button does.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ResumeAction {
/// Voice is connected there: show the server.
Open,
/// Connect into the channel.
Join,
}
/// The card: the server, the channel and the button.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Resume {
pub bookmark: i64,
/// The channel's path, its names from the top as the server has them.
pub path: Vec<String>,
pub action: ResumeAction,
}
impl Resume {
/// The channel's name as the tree shows it (a spacer's text).
pub fn title(&self) -> &str {
match self.path.as_slice() {
[top] => voelin_model::parse_spacer(top).map_or(top.as_str(), |(_, text)| text),
[.., last] => last,
[] => "",
}
}
}
/// Where to continue: the last voice channel, unless its bookmark is gone
/// or points at another address now. Open while `voice` says a bookmark is
/// connected, else Join.
pub fn resume(
last: Option<&LastVoice>,
bookmarks: &[Bookmark],
voice: impl Fn(i64) -> VoiceState,
) -> Option<Resume> {
let last = last.filter(|l| !l.channel.is_empty())?;
bookmarks.iter().find(|b| b.id == last.bookmark && b.address == last.address)?;
let action = match voice(last.bookmark) {
VoiceState::Connected => ResumeAction::Open,
_ => ResumeAction::Join,
};
Some(Resume { bookmark: last.bookmark, path: last.channel.clone(), action })
}
#[cfg(test)]
mod tests {
use super::*;
fn bookmark(id: i64, address: &str) -> Bookmark {
Bookmark { id, address: address.into(), ..Default::default() }
}
fn last(bookmark: i64, address: &str, channel: &[&str]) -> LastVoice {
LastVoice {
bookmark,
address: address.into(),
channel: channel.iter().map(|n| n.to_string()).collect(),
}
}
#[test]
fn resume_cases() {
let bookmarks = [bookmark(1, "ts.example"), bookmark(2, "pixel.example:9988")];
let offline = |_| VoiceState::Disconnected;
assert_eq!(resume(None, &bookmarks, offline), None, "nothing stored");
assert_eq!(
resume(Some(&last(3, "gone.example", &["Lobby"])), &bookmarks, offline),
None,
"the bookmark was deleted"
);
assert_eq!(
resume(Some(&last(1, "old.example", &["Lobby"])), &bookmarks, offline),
None,
"the bookmark has another address now"
);
assert_eq!(resume(Some(&last(1, "ts.example", &[])), &bookmarks, offline), None);
let place = last(2, "pixel.example:9988", &["Games", "Chess"]);
let joined = resume(Some(&place), &bookmarks, offline).unwrap();
assert_eq!(joined.bookmark, 2);
assert_eq!(joined.path, ["Games", "Chess"]);
assert_eq!(joined.action, ResumeAction::Join);
assert_eq!(joined.title(), "Chess");
let connecting = resume(Some(&place), &bookmarks, |_| VoiceState::Connecting);
assert_eq!(connecting.unwrap().action, ResumeAction::Join);
// Connected elsewhere is not connected there.
let connected = |id| if id == 2 { VoiceState::Connected } else { VoiceState::Disconnected };
assert_eq!(resume(Some(&place), &bookmarks, connected).unwrap().action, ResumeAction::Open);
let elsewhere = |id| if id == 1 { VoiceState::Connected } else { VoiceState::Disconnected };
assert_eq!(resume(Some(&place), &bookmarks, elsewhere).unwrap().action, ResumeAction::Join);
}
#[test]
fn resume_titles() {
let title = |path: &[&str]| {
let path = path.iter().map(|n| n.to_string()).collect();
Resume { bookmark: 1, path, action: ResumeAction::Join }.title().to_owned()
};
assert_eq!(title(&["Lobby"]), "Lobby");
assert_eq!(title(&["[cspacer0]Gaming"]), "Gaming", "a spacer by its text");
// Only channels at the top are spacers.
assert_eq!(title(&["Games", "[cspacer]Chess"]), "[cspacer]Chess");
}
}
-77
View File
@@ -1,77 +0,0 @@
//! Incremental model updates.
use slint::{Model, VecModel};
/// Row operations [`sync`] applied (for tests and tracing).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Changes {
pub set: usize,
pub inserted: usize,
pub removed: usize,
}
/// Make `model` hold `new` with few row operations: the rows both share at
/// the start and the end stay, rows in between are changed in place where
/// they differ, and the rest inserted or removed. Views redraw only the
/// rows that changed (a client that starts talking is one `set_row_data`).
pub fn sync<T: Clone + PartialEq + 'static>(model: &VecModel<T>, new: &[T]) -> Changes {
let old_len = model.row_count();
let new_len = new.len();
let min = old_len.min(new_len);
let mut prefix = 0;
while prefix < min && model.row_data(prefix).as_ref() == Some(&new[prefix]) {
prefix += 1;
}
let mut suffix = 0;
while suffix < min - prefix
&& model.row_data(old_len - 1 - suffix).as_ref() == Some(&new[new_len - 1 - suffix])
{
suffix += 1;
}
let old_mid = old_len - prefix - suffix;
let new_mid = new_len - prefix - suffix;
let common = old_mid.min(new_mid);
let mut changes = Changes::default();
for (i, row) in new.iter().enumerate().skip(prefix).take(common) {
if model.row_data(i).as_ref() != Some(row) {
model.set_row_data(i, row.clone());
changes.set += 1;
}
}
let at = prefix + common;
for _ in new_mid..old_mid {
model.remove(at);
changes.removed += 1;
}
for (k, row) in new[at..at + new_mid.saturating_sub(old_mid)].iter().enumerate() {
model.insert(at + k, row.clone());
changes.inserted += 1;
}
changes
}
#[cfg(test)]
mod tests {
use super::*;
fn run(old: &[i32], new: &[i32]) -> Changes {
let model = VecModel::from(old.to_vec());
let changes = sync(&model, new);
assert_eq!(model.iter().collect::<Vec<_>>(), new, "{old:?} -> {new:?}");
changes
}
#[test]
fn minimal_changes() {
assert_eq!(run(&[1, 2, 3], &[1, 2, 3]), Changes::default());
assert_eq!(run(&[1, 2, 3], &[1, 9, 3]), Changes { set: 1, ..Default::default() });
assert_eq!(run(&[1, 2, 3], &[1, 2, 7, 3]), Changes { inserted: 1, ..Default::default() });
assert_eq!(run(&[1, 2, 3], &[1, 3]), Changes { removed: 1, ..Default::default() });
assert_eq!(run(&[], &[1, 2]), Changes { inserted: 2, ..Default::default() });
assert_eq!(run(&[1, 2], &[]), Changes { removed: 2, ..Default::default() });
assert_eq!(run(&[1, 2, 3, 4], &[5, 6]).set, 2);
run(&[1, 1, 1], &[1, 1]);
run(&[1, 2, 1], &[1, 1, 2, 1]);
run(&[4, 5, 6], &[1, 2, 3, 4, 5, 6, 7]);
}
}
-15
View File
@@ -1,15 +0,0 @@
//! View models: engine state turned into the Slint structs the screens
//! show. Pure functions (no window, no engine), unit-tested here; the
//! models live in `crate::models` and are updated row by row with
//! [`list::sync`], so a small change redraws only what changed.
pub mod avatar;
pub mod bbcode;
pub mod chat;
pub mod home;
pub mod list;
pub mod servers;
pub mod social;
pub mod streams;
pub mod studio;
pub mod tree;
-637
View File
@@ -1,637 +0,0 @@
//! The server rail, the server dialog, and joining a channel.
use slint::{Color, SharedString};
use voelin_core::{ObserveState, SessionState, VoiceState};
use voelin_model::{ChannelId, ChannelInfo, Presence, ServerLink};
use voelin_store::Bookmark;
use crate::app::{BookmarkForm, ServerItem};
use crate::vm::avatar;
/// Restore a known server icon before any session exists. A missing/evicted
/// cache file falls back to initials; the bookmark stores no filesystem path.
pub fn cached_icon(bookmark: &Bookmark, cache: &voelin_core::Cache) -> slint::Image {
avatar::image(bookmark.server_icon_id().and_then(|id| cache.icon(id)).as_ref())
}
/// Server colours: hues around the wheel, each far from the one before it
/// (where a server goes when its own is taken). White initials read on all.
const SERVER_TINTS: [u32; 10] = [
0x2d6bff, // blue
0xc2379a, // magenta
0xc08400, // gold
0x0c8fb0, // teal
0x9c3fd1, // purple
0xe0652a, // orange
0x1f9d55, // green
0x7c4dff, // violet
0xd63a3a, // red
0x6e8f1c, // olive
];
/// A colour for each server, in `bookmarks` order: its name picks one, and
/// when an earlier server has it, it takes the next free one. So no two
/// share a colour until there are more servers than colours (then they
/// start over), and adding a server leaves the others' colours.
pub fn tints(bookmarks: &[Bookmark]) -> Vec<Color> {
let n = SERVER_TINTS.len();
let mut taken = [false; SERVER_TINTS.len()];
bookmarks
.iter()
.enumerate()
.map(|(i, bookmark)| {
if i % n == 0 {
taken = [false; SERVER_TINTS.len()];
}
let start = avatar::name_hash(&bookmark.name) as usize % n;
let slot = (0..n).map(|k| (start + k) % n).find(|&s| !taken[s]).unwrap_or(start);
taken[slot] = true;
avatar::rgb(SERVER_TINTS[slot])
})
.collect()
}
/// "offline", "connecting", "observing" or "connected". "connecting" is
/// voice only: observing that is not there yet (a gateway that is away and
/// tried again) is "offline", as users never hear of the gateway.
pub fn status(state: &SessionState) -> &'static str {
match (state.voice, state.observe) {
(VoiceState::Connected, _) => "connected",
(VoiceState::Connecting, _) => "connecting",
(_, ObserveState::Observing) => "observing",
_ => "offline",
}
}
/// A server of the rail and the home page. `unread`: messages in its
/// chats; `live`: streams on it; `detail`: who is there ("9 online · 7
/// channels"), empty for its address; `product`: "TeamSpeak 6" once
/// reached; `icon`: the server's icon (empty: its initials) on `tint`
/// ([`tints`]).
#[allow(clippy::too_many_arguments)]
pub fn item(
bookmark: &Bookmark,
state: &SessionState,
unread: i32,
live: bool,
detail: String,
product: String,
icon: slint::Image,
tint: Color,
) -> ServerItem {
ServerItem {
id: bookmark.id as i32,
name: bookmark.name.clone().into(),
address: bookmark.address.clone().into(),
status: status(state).into(),
initials: avatar::initials(&bookmark.name).into(),
tint,
icon,
unread,
live,
detail: if detail.is_empty() { bookmark.address.clone() } else { detail }.into(),
product: product.into(),
gateway: bookmark.gateway_url.is_some() || bookmark.query.is_some(),
}
}
/// The server dialog's form for `bookmark`, with its stored password:
/// `connected` while `state` has voice, which hides Connect. A server still
/// named by its address shows no name, so a new address names it again.
pub fn form(
bookmark: &Bookmark,
state: Option<&SessionState>,
server_password: &str,
) -> BookmarkForm {
BookmarkForm {
id: bookmark.id as i32,
name: if bookmark.name == bookmark.address {
SharedString::new()
} else {
bookmark.name.clone().into()
},
address: bookmark.address.clone().into(),
nickname: bookmark.nickname.clone().into(),
server_password: server_password.into(),
connected: state.is_some_and(|s| s.voice == VoiceState::Connected),
..Default::default()
}
}
/// Where the server dialog's Connect goes ([`connect_to`]).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ConnectTo {
/// A channel path, or `/<id>`.
pub channel: Option<String>,
pub channel_password: Option<String>,
/// A privilege key.
pub token: Option<String>,
}
/// What the server dialog's Connect connects with, once the form was saved
/// as `saved` (none: saving failed, and nothing connects): the form's
/// channel (a link's) with its password, else the server's default
/// channel; and the link's privilege key.
pub fn connect_to(form: &BookmarkForm, saved: Option<&Bookmark>) -> Option<ConnectTo> {
let saved = saved?;
let given = |text: &SharedString| Some(text.to_string()).filter(|t| !t.is_empty());
let channel = given(&form.channel);
Some(ConnectTo {
channel_password: channel.as_ref().and_then(|_| given(&form.channel_password)),
channel: channel.or_else(|| saved.default_channel.clone()),
token: given(&form.token),
})
}
/// A `ts3server://` link that joins the channel at `path` (its names from
/// the top) on the server at `address` (`host`, `host:port` or
/// `[v6]:port`), as TeamSpeak clients open them.
pub fn invite_link(address: &str, path: &[&str]) -> String {
let mut link = ServerLink::new(address);
link.channel = (!path.is_empty()).then(|| voelin_model::join_channel_path(path));
link.to_url()
}
/// TeamSpeak's voice port, of an address without one.
const DEFAULT_PORT: u16 = 9987;
/// Whether two addresses name the same server: the host in any case, an
/// IPv6 address with or without its brackets, no port as 9987 (a port a
/// DNS record gives is not looked up).
pub fn same_address(a: &str, b: &str) -> bool {
let key = |address: &str| {
let link = ServerLink::new(address);
(link.host.trim_end_matches('.').to_lowercase(), link.port.unwrap_or(DEFAULT_PORT))
};
let a = key(a);
!a.0.is_empty() && a == key(b)
}
/// The saved server a link to `address` opens, and whether it has voice
/// (`in_voice`): of those at that address ([`same_address`]; two can be,
/// with other identities), the one in voice, else the one shown
/// (`current`), else the first.
pub fn link_server(
bookmarks: &[Bookmark],
address: &str,
current: Option<i64>,
in_voice: impl Fn(i64) -> bool,
) -> Option<(i64, bool)> {
let saved: Vec<i64> =
bookmarks.iter().filter(|b| same_address(&b.address, address)).map(|b| b.id).collect();
if let Some(id) = saved.iter().copied().find(|id| in_voice(*id)) {
return Some((id, true));
}
let shown = saved.iter().copied().find(|id| Some(*id) == current);
shown.or_else(|| saved.first().copied()).map(|id| (id, false))
}
/// The channel a link's path names (`/<id>`, or names from the top as the
/// server has them, [`voelin_model::split_channel_path`]). Of siblings with
/// the same name, the first in the tree's order that has the rest of the
/// path.
pub fn channel_by_path(presence: &Presence, path: &str) -> Option<ChannelId> {
fn below(presence: &Presence, parent: ChannelId, names: &[String]) -> Option<ChannelId> {
let (name, rest) = names.split_first()?;
let siblings = presence.channels.values().filter(|c| c.parent == parent).collect();
voelin_model::order_siblings(siblings)
.into_iter()
.filter(|c| c.name == *name)
.find_map(|c| if rest.is_empty() { Some(c.id) } else { below(presence, c.id, rest) })
}
match voelin_model::channel_path_id(path) {
Some(id) => presence.channels.contains_key(&id).then_some(id),
None => below(presence, 0, &voelin_model::split_channel_path(path)),
}
}
/// The server dialog's form for a link, over `form`: a saved server's
/// keeps its address, name and nickname (a link never changes it), and its
/// stored password unless the link has one; a new server's takes the
/// link's address, nickname (else `default_nickname`) and password. The
/// link's channel, its password and privilege key come along, for Connect.
pub fn link_form(
link: &ServerLink,
mut form: BookmarkForm,
default_nickname: &str,
) -> BookmarkForm {
let text = |value: &Option<String>| SharedString::from(value.as_deref().unwrap_or_default());
if form.id < 0 {
form.address = link.address().into();
}
if form.id < 0 || form.nickname.is_empty() {
form.nickname = link.nickname.as_deref().unwrap_or(default_nickname).into();
}
if let Some(password) = &link.password {
form.server_password = password.into();
}
form.channel = text(&link.channel);
form.channel_password = text(&link.channel_password);
form.token = text(&link.token);
form
}
/// What joining a channel takes ([`join_password`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum JoinStep {
/// Move there, with this password.
Send(Option<String>),
/// Ask for the channel's password first.
Ask,
}
/// How to join `channel`, given the password remembered for it this
/// connection: a locked channel asks for one unless it was given before,
/// as TeamSpeak does. A password given before goes along even when the
/// channel shows no lock: one locked since then still lets us in.
pub fn join_password(channel: &ChannelInfo, remembered: Option<&str>) -> JoinStep {
match remembered.filter(|p| !p.is_empty()) {
Some(password) => JoinStep::Send(Some(password.to_owned())),
None if channel.has_password => JoinStep::Ask,
None => JoinStep::Send(None),
}
}
/// Where a voice connection asked into a channel stands ([`after_connect`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AfterConnect {
/// Not known yet.
Wait,
/// In it.
Joined,
/// Put elsewhere without a word (a wrong password, for one): joining
/// it again says why.
JoinAgain,
}
/// A connection asked into `asked`, connected with voice: `own` is our
/// channel once known, `known` whether `asked` shows in the presence yet
/// (it can come after our own channel).
pub fn after_connect(own: Option<ChannelId>, asked: ChannelId, known: bool) -> AfterConnect {
match own {
Some(own) if own == asked => AfterConnect::Joined,
Some(_) if known => AfterConnect::JoinAgain,
_ => AfterConnect::Wait,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn server_icon_is_visible_before_connection_and_missing_files_fall_back() {
let dir =
std::env::temp_dir().join(format!("voelin-server-icon-model-{}", std::process::id()));
std::fs::create_dir_all(dir.join("icons")).unwrap();
let path = dir.join("icons/1234");
let mut bytes = Vec::new();
let mut encoder = png::Encoder::new(&mut bytes, 4, 4);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
encoder.write_header().unwrap().write_image_data(&[200; 64]).unwrap();
std::fs::write(&path, bytes).unwrap();
let cache = voelin_core::Cache::new(&dir);
let mut bookmark = Bookmark { address: "example.test".into(), ..Default::default() };
bookmark.remember_server_icon(1234);
let server = item(
&bookmark,
&SessionState::default(),
0,
false,
String::new(),
String::new(),
cached_icon(&bookmark, &cache),
Color::default(),
);
assert_eq!(server.status.as_str(), "offline");
assert_eq!(server.icon.size().width, 4);
bookmark.address = "different.test".into();
assert_eq!(cached_icon(&bookmark, &cache).size().width, 0);
bookmark.address = "example.test".into();
std::fs::remove_file(path).unwrap();
assert_eq!(cached_icon(&bookmark, &cache).size().width, 0);
std::fs::remove_dir_all(dir).unwrap();
}
/// The chip of a server reads the product its session reported.
#[test]
fn a_server_shows_the_product_it_runs() {
let bookmark = Bookmark { address: "example.test".into(), ..Default::default() };
let state = SessionState::default();
let on = |product: &str| {
item(
&bookmark,
&state,
0,
false,
String::new(),
product.into(),
Default::default(),
Color::default(),
)
};
assert_eq!(on("TeamSpeak 6").product.as_str(), "TeamSpeak 6");
// Before the server answered, and for software nobody recognised: none.
assert_eq!(on("").product.as_str(), "");
}
fn named(names: &[&str]) -> Vec<Bookmark> {
names.iter().map(|n| Bookmark { name: (*n).into(), ..Default::default() }).collect()
}
/// The colour a name picks.
fn own_tint(name: &str, step: usize) -> Color {
let n = SERVER_TINTS.len();
avatar::rgb(SERVER_TINTS[(avatar::name_hash(name) as usize + step) % n])
}
#[test]
fn tints_are_distinct_up_to_the_palette_size() {
let names: Vec<String> = (0..SERVER_TINTS.len()).map(|i| format!("Server {i}")).collect();
let mut bookmarks = named(&names.iter().map(String::as_str).collect::<Vec<_>>());
let distinct: std::collections::HashSet<_> =
tints(&bookmarks).iter().map(|t| t.as_argb_encoded()).collect();
assert_eq!(distinct.len(), SERVER_TINTS.len());
// One more starts over with its name's colour.
bookmarks.extend(named(&["One more"]));
assert_eq!(tints(&bookmarks)[SERVER_TINTS.len()], own_tint("One more", 0));
// The sample servers, two of which shared a blue.
let sample = tints(&named(&["Nightfall Guild", "Pixel Lounge", "Dev TS3"]));
assert!(sample[0] != sample[1] && sample[1] != sample[2] && sample[0] != sample[2]);
}
#[test]
fn tints_follow_the_name_and_stay_when_a_server_is_added() {
let names = ["Nightfall Guild", "Pixel Lounge", "Dev TS3", "Home", "Raid"];
let before = tints(&named(&names));
let mut more = named(&names);
more.extend(named(&["New one"]));
assert_eq!(tints(&more)[..names.len()], before[..]);
// Alone, a server has its name's colour, in any case.
assert_eq!(tints(&named(&["pixel lounge"])), [own_tint("Pixel Lounge", 0)]);
// A second server with the name takes the next colour.
assert_eq!(tints(&named(&["Raid", "Raid"])), [own_tint("Raid", 0), own_tint("Raid", 1)]);
}
#[test]
fn connect_shows_only_without_voice() {
let b = Bookmark {
id: 3,
name: "ts.example.test".into(),
address: "ts.example.test".into(),
nickname: "Nova".into(),
..Default::default()
};
let mut state = SessionState::default();
let f = form(&b, None, "pw");
assert_eq!((f.id, f.name.as_str(), f.address.as_str()), (3, "", "ts.example.test"));
assert_eq!((f.nickname.as_str(), f.server_password.as_str()), ("Nova", "pw"));
assert!(!f.connected);
for (voice, connected) in [
(VoiceState::Disconnected, false),
// Connect again with another address.
(VoiceState::Connecting, false),
(VoiceState::Connected, true),
] {
state.voice = voice;
assert_eq!(form(&b, Some(&state), "").connected, connected, "{voice:?}");
}
// Observing is not voice.
state.voice = VoiceState::Disconnected;
state.observe = ObserveState::Observing;
assert!(!form(&b, Some(&state), "").connected);
let named = Bookmark { name: "Nightfall".into(), ..b };
assert_eq!(form(&named, None, "").name.as_str(), "Nightfall");
}
#[test]
fn connect_only_what_was_saved() {
let saved = Bookmark { id: 3, default_channel: Some("Lobby".into()), ..Default::default() };
let plain = BookmarkForm { address: "ts.example.test".into(), ..Default::default() };
// Saving failed: nothing connects (not the server shown before).
assert_eq!(connect_to(&plain, None), None);
assert_eq!(
connect_to(&plain, Some(&saved)),
Some(ConnectTo { channel: Some("Lobby".into()), ..Default::default() })
);
// A link's channel, its password and privilege key.
let link = BookmarkForm {
channel: "Gaming/Raid Night".into(),
channel_password: "raid".into(),
token: "key".into(),
..plain.clone()
};
assert_eq!(connect_to(&link, None), None);
assert_eq!(
connect_to(&link, Some(&saved)),
Some(ConnectTo {
channel: Some("Gaming/Raid Night".into()),
channel_password: Some("raid".into()),
token: Some("key".into()),
})
);
// A password goes only with the link's channel.
let token = BookmarkForm { channel_password: "raid".into(), token: "key".into(), ..plain };
assert_eq!(
connect_to(&token, Some(&saved)),
Some(ConnectTo {
channel: Some("Lobby".into()),
channel_password: None,
token: Some("key".into()),
})
);
}
#[test]
fn invite_links() {
assert_eq!(
invite_link("ts.example.com:9988", &["Gaming", "Raid Night"]),
"ts3server://ts.example.com?port=9988&channel=Gaming/Raid%20Night"
);
assert_eq!(invite_link(" ts.example.com ", &[]), "ts3server://ts.example.com");
assert_eq!(
invite_link("[2001:db8::1]:9987", &["Chill & Co"]),
"ts3server://[2001:db8::1]?port=9987&channel=Chill%20%26%20Co"
);
// A bare IPv6 address has no port.
assert_eq!(invite_link("2001:db8::1", &[]), "ts3server://2001:db8::1");
assert_eq!(invite_link("h:x", &["Ä/b"]), "ts3server://h:x?channel=%C3%84%2Fb");
// Read back, they name the same server and channel.
let Some(voelin_model::Link::Server(link)) =
voelin_model::Link::parse(&invite_link("[2001:db8::1]:9987", &["Games", "Ä/b"]))
else {
panic!("not a server link");
};
assert!(same_address(&link.address(), "[2001:db8::1]:9987"));
assert_eq!(voelin_model::split_channel_path(&link.channel.unwrap()), ["Games", "Ä/b"]);
}
#[test]
fn same_addresses() {
for (a, b) in [
("ts.example.org", "TS.Example.org"),
(" ts.example.org ", "ts.example.org:9987"),
("ts.example.org.", "ts.example.org"),
("[2001:db8::1]:9987", "2001:db8::1"),
("[2001:db8::1]", "[2001:DB8::1]:9987"),
("127.0.0.1:9988", "127.0.0.1:9988"),
] {
assert!(same_address(a, b), "{a} = {b}");
}
for (a, b) in [
("ts.example.org", "ts.example.org:9988"),
("ts.example.org", "example.org"),
("[2001:db8::1]:9988", "2001:db8::1"),
("", ""),
] {
assert!(!same_address(a, b), "{a} != {b}");
}
}
#[test]
fn servers_of_links() {
let saved =
|id, address: &str| Bookmark { id, address: address.into(), ..Default::default() };
let bookmarks = [
saved(1, "other.example"),
saved(2, "ts.example.org"),
saved(3, "TS.example.org:9987"),
saved(4, "ts.example.org:9988"),
];
let voice = |ids: &'static [i64]| move |id| ids.contains(&id);
// Not in voice: the one shown, else the first.
assert_eq!(link_server(&bookmarks, "ts.example.org", None, voice(&[])), Some((2, false)));
assert_eq!(
link_server(&bookmarks, "ts.example.org", Some(3), voice(&[])),
Some((3, false))
);
// In voice on one of them, also when another is shown.
assert_eq!(
link_server(&bookmarks, "ts.example.org:9987", Some(2), voice(&[1, 3])),
Some((3, true))
);
// Voice on the server at another port does not count.
assert_eq!(
link_server(&bookmarks, "ts.example.org:9988", None, voice(&[2])),
Some((4, false))
);
assert_eq!(link_server(&bookmarks, "new.example", Some(1), voice(&[1])), None);
}
#[test]
fn channels_by_path() {
let channel = |id, parent, order, name: &str| ChannelInfo {
id,
parent,
order,
name: name.into(),
..Default::default()
};
let mut p = Presence::default();
for c in [
channel(1, 0, 0, "Lobby"),
// Two of the same name, the first in the tree with the higher id.
channel(4, 0, 1, "Games"),
channel(3, 4, 0, "Chess"),
channel(7, 0, 4, "AC/DC"),
channel(2, 0, 7, "Games"),
channel(5, 2, 0, "Go"),
channel(6, 2, 5, "Chess"),
] {
p.channels.insert(c.id, c);
}
assert_eq!(channel_by_path(&p, "Lobby"), Some(1), "at the top");
assert_eq!(channel_by_path(&p, "Games/Chess"), Some(3), "nested");
// The same name: the first, unless only another has the rest.
assert_eq!(channel_by_path(&p, "Games"), Some(4));
assert_eq!(channel_by_path(&p, "Games/Go"), Some(5));
assert_eq!(channel_by_path(&p, "AC\\/DC"), Some(7), "a / in a name");
assert_eq!(channel_by_path(&p, "/6"), Some(6), "by id");
for missing in ["Chess", "Games/Poker", "Lobby/Games", "/99", "", "lobby"] {
assert_eq!(channel_by_path(&p, missing), None, "{missing}");
}
}
#[test]
fn forms_from_links() {
let link = ServerLink {
host: "ts.example.org".into(),
port: Some(9988),
nickname: Some("Link".into()),
password: Some("pw".into()),
channel: Some("Gaming/Raid Night".into()),
channel_password: Some("raid".into()),
token: Some("key".into()),
};
let bare = ServerLink::new("ts.example.org");
// A new server: the link's address, nickname and password.
let new = BookmarkForm { id: -1, nickname: "Me".into(), ..Default::default() };
let f = link_form(&link, new.clone(), "Me");
assert_eq!((f.id, f.name.as_str(), f.address.as_str()), (-1, "", "ts.example.org:9988"));
assert_eq!((f.nickname.as_str(), f.server_password.as_str()), ("Link", "pw"));
assert_eq!(
(f.channel.as_str(), f.channel_password.as_str(), f.token.as_str()),
("Gaming/Raid Night", "raid", "key")
);
let f = link_form(&bare, new, "Me");
assert_eq!((f.address.as_str(), f.nickname.as_str()), ("ts.example.org", "Me"));
assert_eq!(
(f.server_password.as_str(), f.channel.as_str(), f.token.as_str()),
("", "", "")
);
// A saved server keeps its address, name, nickname and password...
let saved = BookmarkForm {
id: 3,
name: "Nightfall".into(),
address: "TS.example.org:9988".into(),
nickname: "Nova".into(),
server_password: "stored".into(),
..Default::default()
};
let f = link_form(&bare, saved.clone(), "Me");
assert_eq!(
(f.id, f.name.as_str(), f.address.as_str()),
(3, "Nightfall", "TS.example.org:9988")
);
assert_eq!((f.nickname.as_str(), f.server_password.as_str()), ("Nova", "stored"));
// ...the link's password in place of the stored one.
let f = link_form(&link, saved, "Me");
assert_eq!((f.nickname.as_str(), f.server_password.as_str()), ("Nova", "pw"));
assert_eq!((f.channel.as_str(), f.token.as_str()), ("Gaming/Raid Night", "key"));
}
#[test]
fn locked_channels_ask_for_their_password_once() {
let open = ChannelInfo { id: 1, name: "Lobby".into(), ..Default::default() };
let locked = ChannelInfo { has_password: true, ..open.clone() };
assert_eq!(join_password(&open, None), JoinStep::Send(None));
assert_eq!(join_password(&locked, None), JoinStep::Ask);
assert_eq!(join_password(&locked, Some("")), JoinStep::Ask);
assert_eq!(join_password(&locked, Some("pw")), JoinStep::Send(Some("pw".into())));
assert_eq!(join_password(&open, Some("pw")), JoinStep::Send(Some("pw".into())));
}
#[test]
fn connecting_into_a_channel() {
assert_eq!(after_connect(None, 4, true), AfterConnect::Wait);
assert_eq!(after_connect(Some(4), 4, false), AfterConnect::Joined);
// Put into the default channel: once the channel is known, again.
assert_eq!(after_connect(Some(1), 4, false), AfterConnect::Wait);
assert_eq!(after_connect(Some(1), 4, true), AfterConnect::JoinAgain);
}
#[test]
fn states() {
let mut s = SessionState::default();
assert_eq!(status(&s), "offline");
s.observe = ObserveState::Connecting;
assert_eq!(status(&s), "offline");
s.observe = ObserveState::Observing;
assert_eq!(status(&s), "observing");
s.voice = VoiceState::Connecting;
assert_eq!(status(&s), "connecting");
s.voice = VoiceState::Connected;
assert_eq!(status(&s), "connected");
}
}
-329
View File
@@ -1,329 +0,0 @@
//! Texts of the home, friends, messages, bell and events screens: times
//! ("12m ago", "Yesterday"), message previews without BBCode (read by
//! `vm::bbcode`), mentions, event dates, a poke's message, the private
//! chats of the home sidebar; pure, so they are tested here.
use chrono::{DateTime, Local, NaiveDateTime, TimeZone};
fn local(ts_ms: i64) -> Option<NaiveDateTime> {
DateTime::from_timestamp_millis(ts_ms).map(|t| t.with_timezone(&Local).naive_local())
}
fn now_local() -> NaiveDateTime {
Local::now().naive_local()
}
/// "now", "5m ago", "2h ago", "3d ago", else the date ("12 Mar").
pub fn ago(ts_ms: i64) -> String {
ago_at(ts_ms, chrono::Utc::now().timestamp_millis())
}
pub fn ago_at(ts_ms: i64, now_ms: i64) -> String {
if ts_ms <= 0 {
return String::new();
}
let minutes = (now_ms - ts_ms) / 60_000;
match minutes {
i64::MIN..=0 => "now".into(),
1..=59 => format!("{minutes}m ago"),
60..=1439 => format!("{}h ago", minutes / 60),
1440..=10079 => format!("{}d ago", minutes / 1440),
_ => local(ts_ms).map(|t| t.format("%-d %b").to_string()).unwrap_or_default(),
}
}
/// The time of a conversation in a list: "11:42" today, "Yesterday", the
/// weekday within a week ("Mon"), else the date ("12 Mar", with the year
/// when it is another).
pub fn list_time(ts_ms: i64) -> String {
local(ts_ms).map(|t| list_time_at(t, now_local())).unwrap_or_default()
}
pub fn list_time_at(then: NaiveDateTime, now: NaiveDateTime) -> String {
use chrono::Datelike;
let days = (now.date() - then.date()).num_days();
match days {
i64::MIN..=0 => then.format("%H:%M").to_string(),
1 => "Yesterday".into(),
2..=6 => then.format("%a").to_string(),
_ if then.year() == now.year() => then.format("%-d %b").to_string(),
_ => then.format("%-d %b %Y").to_string(),
}
}
/// Chat text without BBCode (`[b]`, `[URL=…]`, `[/URL]`), on one line.
pub fn plain(text: &str) -> String {
without_emoji(&crate::vm::bbcode::parse(text).one_line())
}
/// Text without emoji, runs of spaces as one: one line of text draws no
/// emoji (they are pictures in the chat).
pub fn without_emoji(text: &str) -> String {
let mut words = String::with_capacity(text.len());
for run in crate::emoji::split(text).into_iter().filter(|r| r.emoji.is_none()) {
words.extend(run.text.chars().filter(|c| !is_emoji(*c)));
}
words.split_whitespace().collect::<Vec<_>>().join(" ")
}
/// Pictographs, symbols and their joiners and variation selectors.
fn is_emoji(c: char) -> bool {
matches!(u32::from(c), 0x1F000..=0x1FAFF | 0x2600..=0x27BF | 0xFE0F | 0x200D)
}
/// A one-line preview of a message: "You: …" for our own, "Sent a
/// picture" / "Sent a file" for links without text.
pub fn preview(text: &str, mine: bool, files: &[voelin_model::FileRef]) -> String {
let body = if files.is_empty() { plain(text) } else { String::new() };
let body = if body.is_empty() && !files.is_empty() {
if files.iter().any(|f| crate::vm::chat::is_picture(&f.name)) {
"Sent a picture".to_owned()
} else {
"Sent a file".to_owned()
}
} else {
body
};
if mine { format!("You: {body}") } else { body }
}
/// Whether `text` names `nick` as a word (case does not matter): a mention.
pub fn mentions(text: &str, nick: &str) -> bool {
let nick = nick.trim().to_lowercase();
if nick.is_empty() {
return false;
}
let text = text.to_lowercase();
text.match_indices(&nick).any(|(at, _)| {
let before = text[..at].chars().next_back();
let after = text[at + nick.len()..].chars().next();
!before.is_some_and(char::is_alphanumeric) && !after.is_some_and(char::is_alphanumeric)
})
}
/// Case-insensitive search in any of `fields`.
pub fn matches(query: &str, fields: &[&str]) -> bool {
let q = query.trim().to_lowercase();
q.is_empty() || fields.iter().any(|f| f.to_lowercase().contains(&q))
}
/// A poke's message as it is sent: trimmed, and cut to the
/// [`voelin_core::POKE_MESSAGE_MAX`] characters servers take.
pub fn poke_message(text: &str) -> String {
let cut: String = text.trim().chars().take(voelin_core::POKE_MESSAGE_MAX).collect();
cut.trim_end().to_owned()
}
/// The private chats of the home sidebar, by their index in `chats`
/// (newest first): at most `n`, those with unread messages first.
pub fn sidebar_dms(chats: &[crate::messages::ChatRef], n: usize) -> Vec<usize> {
let mut private: Vec<usize> = (0..chats.len())
.filter(|&i| matches!(chats[i].target, voelin_model::ChatTarget::Private(_)))
.collect();
private.sort_by_key(|&i| chats[i].unread == 0);
private.truncate(n);
private
}
/// The channels the search (Ctrl+K) finds for `query`, with their titles:
/// a spacer by its text, never a line or an empty spacer.
pub fn found_channels<'a>(
channels: impl IntoIterator<Item = &'a voelin_model::ChannelInfo>,
query: &str,
) -> Vec<(u64, &'a str)> {
channels
.into_iter()
.filter_map(|c| Some((c.id, crate::vm::tree::listed_title(c)?)))
.filter(|(_, title)| matches(query, &[*title]))
.collect()
}
/// The date block of an event: "SAT", "26", "APR".
pub fn date_block(ts_ms: i64) -> (String, String, String) {
local(ts_ms)
.map(|t| {
(
t.format("%a").to_string().to_uppercase(),
t.format("%-d").to_string(),
t.format("%b").to_string().to_uppercase(),
)
})
.unwrap_or_default()
}
/// "Sat 26 Apr, 19:00 – 21:00" (the end's date too when it is another day).
pub fn event_when(start_ms: i64, end_ms: Option<i64>) -> String {
let Some(start) = local(start_ms) else { return String::new() };
let mut out = start.format("%a %-d %b, %H:%M").to_string();
if let Some(end) = end_ms.and_then(local) {
let end = if end.date() == start.date() {
end.format("%H:%M")
} else {
end.format("%a %-d %b, %H:%M")
};
out.push_str(&format!(" – {end}"));
}
out
}
/// "Starts in 15 min", "Starts in 3 h", "Happening now", or nothing (more
/// than a day away, or over).
pub fn soon(start_ms: i64, end_ms: Option<i64>, now_ms: i64) -> String {
let minutes = (start_ms - now_ms) / 60_000;
let over = end_ms.map_or(now_ms - start_ms > 3 * 3_600_000, |end| now_ms > end);
match minutes {
_ if over => String::new(),
i64::MIN..=0 => "Happening now".into(),
1..=59 => format!("Starts in {minutes} min"),
60..=1439 => format!("Starts in {} h", minutes / 60),
_ => String::new(),
}
}
/// `2026-10-04 19:00` in local time → Unix milliseconds.
pub fn parse_local(text: &str) -> Option<i64> {
let t = NaiveDateTime::parse_from_str(text.trim(), "%Y-%m-%d %H:%M").ok()?;
Local.from_local_datetime(&t).earliest().map(|t| t.timestamp_millis())
}
/// Unix milliseconds → `2026-10-04 19:00` in local time.
pub fn format_local(ts_ms: i64) -> String {
local(ts_ms).map(|t| t.format("%Y-%m-%d %H:%M").to_string()).unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
fn at(text: &str) -> NaiveDateTime {
NaiveDateTime::parse_from_str(text, "%Y-%m-%d %H:%M").unwrap()
}
#[test]
fn times() {
let now = 1_800_000_000_000;
assert_eq!(ago_at(now - 30_000, now), "now");
assert_eq!(ago_at(now - 12 * 60_000, now), "12m ago");
assert_eq!(ago_at(now - 2 * 3_600_000, now), "2h ago");
assert_eq!(ago_at(now - 3 * 86_400_000, now), "3d ago");
assert_eq!(ago_at(0, now), "");
let now = at("2026-10-03 14:00");
assert_eq!(list_time_at(at("2026-10-03 11:42"), now), "11:42");
assert_eq!(list_time_at(at("2026-10-02 23:00"), now), "Yesterday");
assert_eq!(list_time_at(at("2026-09-28 10:00"), now), "Mon");
assert_eq!(list_time_at(at("2026-03-12 10:00"), now), "12 Mar");
assert_eq!(list_time_at(at("2025-03-12 10:00"), now), "12 Mar 2025");
}
#[test]
fn previews() {
assert_eq!(plain("[b]Hi[/b] there"), "Hi there");
assert_eq!(plain("see [URL=https://x.org]this[/URL]"), "see this");
assert_eq!(plain("a [not a tag here] b"), "a [not a tag here] b");
assert_eq!(plain("[1] item"), "[1] item");
assert_eq!(plain("later? 👀 Posting ❤️"), "later? Posting");
// Only known tags go.
assert_eq!(plain("[nick] hi"), "[nick] hi");
assert_eq!(plain("[quote=Mira]raid?[/quote]\nyes [i]now[/i]"), "raid? yes now");
assert_eq!(preview("Hello", true, &[]), "You: Hello");
let file = |name: &str| voelin_model::FileRef { name: name.into(), ..Default::default() };
assert_eq!(
preview("[URL=ts3file://x]a.png[/URL]", false, &[file("a.png")]),
"Sent a picture"
);
assert_eq!(preview("x", true, &[file("notes.txt")]), "You: Sent a file");
}
#[test]
fn mention_words() {
assert!(mentions("hey Nova, raid?", "nova"));
assert!(mentions("@Nova", "Nova"));
assert!(!mentions("supernova", "Nova"));
assert!(!mentions("anything", ""));
assert!(matches("kai", &["Kairo", "x"]));
assert!(matches("", &[]));
assert!(!matches("zz", &["Kairo"]));
}
#[test]
fn poke_messages() {
assert_eq!(poke_message(" Raid in 5? "), "Raid in 5?");
assert_eq!(poke_message(""), "");
assert_eq!(poke_message(" \n "), "");
let exact = "x".repeat(100);
assert_eq!(poke_message(&exact), exact);
// Characters, not bytes: two bytes each.
assert_eq!(poke_message(&"ä".repeat(150)), "ä".repeat(100));
assert_eq!(poke_message(&format!("{}€!", "ü".repeat(99))), format!("{}€", "ü".repeat(99)));
// A cut that ends in a space leaves it out.
assert_eq!(poke_message(&format!("{} more", "a".repeat(99))), "a".repeat(99));
}
/// The search shows spacers by their text and leaves out lines.
#[test]
fn search_channels() {
let channel = |id, parent, name: &str| voelin_model::ChannelInfo {
id,
parent,
name: name.into(),
..Default::default()
};
let channels = [
channel(1, 0, "[cspacer0]Gaming"),
channel(2, 0, "[*spacer]---"),
channel(3, 0, "[spacer1]"),
// Only top-level channels are spacers.
channel(4, 1, "[cspacer]Game Night"),
channel(5, 0, "Lobby"),
];
assert_eq!(found_channels(&channels, "gam"), [(1, "Gaming"), (4, "[cspacer]Game Night")]);
assert!(found_channels(&channels, "-").is_empty());
// A spacer is not found by its prefix; a sub-channel's name is all
// its own.
assert_eq!(found_channels(&channels, "spacer"), [(4, "[cspacer]Game Night")]);
assert_eq!(found_channels(&channels, "").len(), 3);
}
#[test]
fn sidebar_chats() {
use voelin_model::ChatTarget;
let chat = |target: ChatTarget, unread| crate::messages::ChatRef {
session: Some(1),
server_uid: None,
target,
last: None,
unread,
};
let dm = |uid: &str, unread| chat(ChatTarget::Private(uid.into()), unread);
let chats = [
dm("a", 0),
chat(ChatTarget::Server, 4),
dm("b", 2),
chat(ChatTarget::Channel(3), 1),
dm("c", 0),
dm("d", 1),
dm("e", 0),
dm("f", 0),
];
// Private chats only, unread first, otherwise newest first; capped.
assert_eq!(sidebar_dms(&chats, 5), [2, 5, 0, 4, 6]);
assert_eq!(sidebar_dms(&chats, 1), [2]);
assert!(sidebar_dms(&chats[1..2], 5).is_empty());
}
#[test]
fn event_dates() {
let start = parse_local("2026-04-25 19:00").unwrap();
assert_eq!(format_local(start), "2026-04-25 19:00");
assert_eq!(date_block(start), ("SAT".into(), "25".into(), "APR".into()));
let end = parse_local("2026-04-25 21:30").unwrap();
assert_eq!(event_when(start, Some(end)), "Sat 25 Apr, 19:00 – 21:30");
assert_eq!(event_when(start, None), "Sat 25 Apr, 19:00");
assert!(parse_local("tomorrow").is_none());
assert_eq!(soon(start, Some(end), start - 15 * 60_000), "Starts in 15 min");
assert_eq!(soon(start, Some(end), start - 3 * 3_600_000), "Starts in 3 h");
assert_eq!(soon(start, Some(end), start + 60_000), "Happening now");
assert_eq!(soon(start, Some(end), end + 60_000), "");
assert_eq!(soon(start, None, start - 2 * 86_400_000), "");
}
}
-69
View File
@@ -1,69 +0,0 @@
//! Streams on the voice view, the phone's Activity tab and Home: what is
//! shared, and who shares it.
use std::path::PathBuf;
use voelin_core::stream::StreamKind;
use crate::app::StreamItem;
use crate::vm::avatar;
/// "Screen", "Window", "Camera"; "" for a kind we do not know.
pub fn kind_label(kind: &StreamKind) -> &'static str {
match kind {
StreamKind::Screen => "Screen",
StreamKind::Window => "Window",
StreamKind::Camera => "Camera",
StreamKind::Other(_) => "",
}
}
/// A gateway directory's kind as a label: "screen" → "Screen".
pub fn directory_kind_label(kind: &str) -> String {
let mut chars = kind.chars();
chars.next().map(|c| c.to_uppercase().chain(chars).collect()).unwrap_or_default()
}
/// A stream with its streamer: the name, and the avatar as the members
/// show it (the picture from the engine's cache, else the initials on the
/// name's colour). The caller fills in the rest.
pub fn streamer(name: &str, picture: Option<&PathBuf>) -> StreamItem {
StreamItem {
streamer: name.into(),
initials: avatar::initials(name).into(),
tint: avatar::tint(name),
avatar: avatar::image(picture),
..StreamItem::default()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn kinds_have_labels() {
assert_eq!(kind_label(&StreamKind::Screen), "Screen");
assert_eq!(kind_label(&StreamKind::Window), "Window");
assert_eq!(kind_label(&StreamKind::Camera), "Camera");
assert_eq!(kind_label(&StreamKind::Other(9)), "");
assert_eq!(kind_label(&StreamKind::from_u8(2)), "Camera");
}
#[test]
fn directory_kinds_are_capitalised() {
assert_eq!(directory_kind_label("screen"), "Screen");
assert_eq!(directory_kind_label("Camera"), "Camera");
assert_eq!(directory_kind_label(""), "");
}
#[test]
fn streamers_look_as_in_the_members() {
let item = streamer("Nova Star", None);
assert_eq!(item.streamer, "Nova Star");
assert_eq!(item.initials, "NS");
assert_eq!(item.tint, avatar::tint("Nova Star"));
assert_eq!(item.avatar.size(), slint::Image::default().size());
assert!(item.id.is_empty() && !item.own && !item.studio);
}
}
-734
View File
@@ -1,734 +0,0 @@
//! The Stream Studio's view models: scene, source, mixer and layer rows,
//! the header's numbers, the source dialog's form, where new sources go and
//! the overlay sources the stream settings' switches keep in the scenes.
use std::time::Duration;
use voelin_core::settings::{AudioSourceKindSetting, AudioSourceSetting, LayerSetting};
use voelin_core::studio::SourceChange;
use voelin_core::studio::SourceStats;
use voelin_core::studio::scene::{
Align, Background, Colour, Crop, Fit, Scene, Scenes, Source, SourceKind, Transform,
};
use crate::app::{StudioAudio, StudioLayer, StudioScene, StudioSource, StudioSourceForm};
/// The scenes; the live one marked, each with what it shows.
pub fn scenes(scenes: &Scenes) -> Vec<StudioScene> {
let live = scenes.active().map(|s| s.id);
scenes
.scenes
.iter()
.map(|scene| StudioScene {
id: scene.id as i32,
name: scene.name.clone().into(),
detail: summary(scene).into(),
live: Some(scene.id) == live,
kind: scene.sources.first().map_or("", |s| s.kind.label()).into(),
})
.collect()
}
/// "Screen + Camera": the names of the visible sources, back first (the
/// main picture, then what is over it).
fn summary(scene: &Scene) -> String {
let names: Vec<&str> = scene.sources.iter().filter(|s| s.visible).map(Source::label).collect();
if names.is_empty() { "Empty".into() } else { names.join(" + ") }
}
pub fn background_name(background: &Background) -> &'static str {
match background {
Background::Keep => "keep",
Background::Blur { .. } => "blur",
Background::Image { .. } => "image",
Background::Colour { .. } => "colour",
}
}
/// The sources of `scene`, front first, with what the studio reports.
pub fn sources(scene: Option<&Scene>, stats: &[SourceStats]) -> Vec<StudioSource> {
let Some(scene) = scene else { return Vec::new() };
let last = scene.sources.len().saturating_sub(1);
scene
.sources
.iter()
.enumerate()
.rev()
.map(|(i, s)| {
let stat = stats.iter().find(|st| st.id == s.id);
let info = stat
.filter(|st| st.width > 0)
.map(|st| format!("{}×{} · {:.0} fps", st.width, st.height, st.fps))
.unwrap_or_default();
StudioSource {
id: s.id as i32,
name: s.label().into(),
kind: s.kind.label().into(),
visible: s.visible,
locked: s.locked,
background: background_name(&s.background).into(),
error: stat.and_then(|st| st.error.clone()).unwrap_or_default().into(),
info: info.into(),
front: i == last,
back: i == 0,
}
})
.collect()
}
/// Linear gain as dB (silence: -60).
pub fn gain_db(gain: f32) -> f32 {
if gain > 0.001 { 20.0 * gain.log10() } else { -60.0 }
}
/// dB as linear gain.
pub fn gain_linear(db: f32) -> f32 {
10f32.powf(db / 20.0)
}
/// Name, detail and icon kind of an audio source.
pub fn audio_label(kind: &AudioSourceKindSetting) -> (String, String, &'static str) {
match kind {
AudioSourceKindSetting::Microphone => ("Microphone".into(), String::new(), "microphone"),
AudioSourceKindSetting::Desktop => {
("Desktop Audio".into(), "without Voelin".into(), "desktop")
}
AudioSourceKindSetting::App { name: Some(name), .. } => {
("App Audio".into(), name.clone(), "app")
}
AudioSourceKindSetting::App { pid, .. } => {
("App Audio".into(), pid.map(|p| format!("process {p}")).unwrap_or_default(), "app")
}
AudioSourceKindSetting::Window => {
("Window Audio".into(), "the shared window".into(), "window-audio")
}
AudioSourceKindSetting::Synthetic { frequency } => {
("Test Tone".into(), format!("{frequency} Hz"), "tone")
}
}
}
/// What the mixer says about one source now.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct AudioLive {
/// Peak in dBFS.
pub level: f32,
pub error: Option<String>,
}
/// The mixer rows: the stream's audio sources with their meters.
pub fn audio(sources: &[AudioSourceSetting], live: &[Option<AudioLive>]) -> Vec<StudioAudio> {
sources
.iter()
.enumerate()
.map(|(i, s)| {
let (name, detail, kind) = audio_label(&s.kind);
let live = live.get(i).cloned().flatten();
StudioAudio {
name: name.into(),
detail: detail.into(),
kind: kind.into(),
gain_db: gain_db(s.gain),
muted: s.muted,
level: live.as_ref().map_or(-100.0, |l| l.level),
error: live.and_then(|l| l.error).unwrap_or_default().into(),
}
})
.collect()
}
/// A number without trailing zeros ("0.5", "1").
fn short(value: f32) -> String {
let text = format!("{value:.3}");
text.trim_end_matches('0').trim_end_matches('.').to_owned()
}
/// The simulcast layers as rows (bitrates in kbit/s).
pub fn layers(layers: &[LayerSetting]) -> Vec<StudioLayer> {
layers
.iter()
.map(|l| StudioLayer {
size: l.size.map(|(w, h)| format!("{w}x{h}")).unwrap_or_default().into(),
scale: short(l.scale).into(),
fps: l.max_fps.map(|f| f.to_string()).unwrap_or_default().into(),
bitrate: (l.bitrate / 1000).to_string().into(),
min_bitrate: (l.min_bitrate / 1000).to_string().into(),
})
.collect()
}
/// A layer as typed into `old`: a size ("1280x720") or a scale ("0.5",
/// "0.5×", "50%"), a frame-rate cap (empty: none), kbit/s. Any numbers.
pub fn parse_layer(row: &StudioLayer, old: &LayerSetting) -> Result<LayerSetting, String> {
let mut layer = old.clone();
let size = row.size.trim();
let parts: Vec<&str> = size.split(['x', 'X', '×']).map(str::trim).collect();
match parts.as_slice() {
[w, h] if !w.is_empty() && !h.is_empty() => {
let (w, h) = (w.parse::<u32>(), h.parse::<u32>());
let (Ok(w), Ok(h)) = (w, h) else { return Err(format!("{size:?} is not a size")) };
layer.size = Some((w, h));
}
_ => {
let text = size.trim_end_matches(['x', 'X', '×', '%']).trim();
let mut scale: f32 = text.parse().map_err(|_| format!("{size:?} is not a size"))?;
if size.ends_with('%') {
scale /= 100.0;
}
layer.size = None;
layer.scale = scale;
}
}
let fps = row.fps.trim();
layer.max_fps =
if fps.is_empty() { None } else { Some(fps.parse().map_err(|_| "a frame rate")?) };
let kbps: u64 = row.bitrate.trim().parse().map_err(|_| "kbit/s as a number")?;
layer.bitrate = kbps * 1000;
Ok(layer)
}
/// A layer below the last one: half its size, a quarter of its bitrate.
pub fn next_layer(layers: &[LayerSetting], bitrate_kbps: u32) -> LayerSetting {
match layers.last() {
None => LayerSetting { bitrate: u64::from(bitrate_kbps) * 1000, ..LayerSetting::default() },
Some(last) => LayerSetting {
id: None,
scale: last.size.map_or(last.scale / 2.0, |_| 0.5),
size: last.size.map(|(w, h)| (w / 2, h / 2)),
bitrate: (last.bitrate / 4).max(100_000),
rid: None,
..last.clone()
},
}
}
/// 0: not live, 1 poor … 4 excellent; how the stream gets out. The worse
/// of the frame rate made (against the output's) and the bandwidth the
/// viewers have (their estimates against the bitrate sent).
pub fn quality(
live: bool,
wanted_fps: u32,
fps: f64,
bandwidth: Option<f64>,
) -> (i32, &'static str) {
if !live {
return (0, "Not live");
}
let rate = if wanted_fps == 0 { 1.0 } else { fps / f64::from(wanted_fps) };
let worst = rate.min(bandwidth.unwrap_or(1.0));
match worst {
w if w >= 0.9 => (4, "Excellent Connection"),
w if w >= 0.75 => (3, "Good Connection"),
w if w >= 0.5 => (2, "Fair Connection"),
_ => (1, "Poor Connection"),
}
}
/// 8250 → "8,250".
pub fn thousands(n: u64) -> String {
let digits = n.to_string();
let mut out = String::new();
for (i, c) in digits.chars().enumerate() {
if i > 0 && (digits.len() - i).is_multiple_of(3) {
out.push(',');
}
out.push(c);
}
out
}
/// "1080p • 60 FPS • 8,250 kbps".
pub fn format_line(height: u32, fps: u32, kbps: u64) -> String {
format!("{height}p • {fps} FPS • {} kbps", thousands(kbps))
}
/// "00:12:34".
pub fn clock(d: Duration) -> String {
let s = d.as_secs();
format!("{:02}:{:02}:{:02}", s / 3600, s / 60 % 60, s % 60)
}
/// "#rrggbb" or "#rrggbbaa" (the # optional).
pub fn parse_colour(text: &str) -> Option<Colour> {
let hex = text.trim().trim_start_matches('#');
if !matches!(hex.len(), 6 | 8) || !hex.is_ascii() {
return None;
}
let byte = |i: usize| u8::from_str_radix(&hex[i..i + 2], 16).ok();
let a = if hex.len() == 8 { byte(6)? } else { 255 };
Some(Colour::rgba(byte(0)?, byte(2)?, byte(4)?, a))
}
pub fn colour_text(c: Colour) -> String {
if c.a == 255 {
format!("#{:02x}{:02x}{:02x}", c.r, c.g, c.b)
} else {
format!("#{:02x}{:02x}{:02x}{:02x}", c.r, c.g, c.b, c.a)
}
}
fn number(value: f32) -> String {
short(value)
}
/// The source dialog's form for `source`.
pub fn form(source: &Source) -> StudioSourceForm {
let t = &source.transform;
let mut form = StudioSourceForm {
id: source.id as i32,
name: source.name.clone().into(),
kind: source.kind.label().into(),
x: number(t.x).into(),
y: number(t.y).into(),
width: t.width.map(number).unwrap_or_default().into(),
height: t.height.map(number).unwrap_or_default().into(),
scale: number(t.scale).into(),
fit: match t.fit {
Fit::Contain => "contain",
Fit::Cover => "cover",
Fit::Stretch => "stretch",
}
.into(),
crop_left: source.crop.left.to_string().into(),
crop_top: source.crop.top.to_string().into(),
crop_right: source.crop.right.to_string().into(),
crop_bottom: source.crop.bottom.to_string().into(),
opacity: source.opacity * 100.0,
locked: source.locked,
visible: source.visible,
background: background_name(&source.background).into(),
blur: "4".into(),
background_colour: "#00b140".into(),
..StudioSourceForm::default()
};
match &source.background {
Background::Blur { strength } => form.blur = number(strength * 100.0).into(),
Background::Image { path } => form.background_path = path.display().to_string().into(),
Background::Colour { colour } => form.background_colour = colour_text(*colour).into(),
Background::Keep => {}
}
match &source.kind {
SourceKind::Text { text, size_px, colour, .. } => {
form.text = text.replace('\n', "\\n").into();
form.text_size = number(*size_px).into();
form.colour = colour_text(*colour).into();
}
SourceKind::Colour { colour, .. } => form.colour = colour_text(*colour).into(),
SourceKind::Image { path } => form.path = path.display().to_string().into(),
SourceKind::Camera { mirror, .. } => form.mirror = *mirror,
_ => {}
}
form
}
fn parse_f32(text: &str, what: &str) -> Result<f32, String> {
text.trim()
.parse::<f32>()
.ok()
.filter(|v| v.is_finite())
.ok_or_else(|| format!("{what}: a number"))
}
/// An optional size: empty is `None`.
fn parse_size(text: &str, what: &str) -> Result<Option<f32>, String> {
if text.trim().is_empty() {
return Ok(None);
}
let v = parse_f32(text, what)?;
if v > 0.0 { Ok(Some(v)) } else { Err(format!("{what}: above 0")) }
}
fn parse_crop(text: &str) -> Result<u32, String> {
if text.trim().is_empty() {
return Ok(0);
}
text.trim().parse().map_err(|_| "crop: whole pixels".to_owned())
}
fn transform(form: &StudioSourceForm) -> Result<Transform, String> {
let scale = if form.scale.trim().is_empty() { 1.0 } else { parse_f32(&form.scale, "scale")? };
if scale <= 0.0 {
return Err("scale: above 0".into());
}
Ok(Transform {
x: parse_f32(&form.x, "X").unwrap_or(0.0),
y: parse_f32(&form.y, "Y").unwrap_or(0.0),
width: parse_size(&form.width, "width")?,
height: parse_size(&form.height, "height")?,
scale,
fit: match form.fit.as_str() {
"cover" => Fit::Cover,
"stretch" => Fit::Stretch,
_ => Fit::Contain,
},
})
}
fn background(form: &StudioSourceForm) -> Result<Background, String> {
Ok(match form.background.as_str() {
"blur" => Background::Blur { strength: parse_f32(&form.blur, "blur")?.max(0.0) / 100.0 },
"image" if !form.background_path.trim().is_empty() => {
Background::Image { path: form.background_path.trim().into() }
}
"image" => return Err("background image: a file".into()),
"colour" => Background::Colour {
colour: parse_colour(&form.background_colour).ok_or("background colour: #rrggbb")?,
},
_ => Background::Keep,
})
}
/// What `form` changes in `old` (only what differs).
pub fn change(form: &StudioSourceForm, old: &Source) -> Result<SourceChange, String> {
let transform = transform(form)?;
let crop = Crop {
left: parse_crop(&form.crop_left)?,
top: parse_crop(&form.crop_top)?,
right: parse_crop(&form.crop_right)?,
bottom: parse_crop(&form.crop_bottom)?,
};
let kind = kind(form, Some(&old.kind))?;
let background = background(form)?;
let opacity = (form.opacity / 100.0).clamp(0.0, 1.0);
let differs = |a: bool| a.then_some(());
Ok(SourceChange {
name: differs(form.name.as_str() != old.name).map(|_| form.name.to_string()),
kind: differs(kind != old.kind).map(|_| kind),
transform: differs(transform != old.transform).map(|_| transform),
crop: differs(crop != old.crop).map(|_| crop),
opacity: differs((opacity - old.opacity).abs() > f32::EPSILON).map(|_| opacity),
visible: differs(form.visible != old.visible).map(|_| form.visible),
locked: differs(form.locked != old.locked).map(|_| form.locked),
background: differs(background != old.background).map(|_| background),
})
}
/// The kind as the form says: text, colour and image from their fields, a
/// camera's mirroring, anything else as it was.
fn kind(form: &StudioSourceForm, old: Option<&SourceKind>) -> Result<SourceKind, String> {
Ok(match (form.kind.as_str(), old) {
("text", old) => {
let (font, backdrop, align, padding) = match old {
Some(SourceKind::Text { font, backdrop, align, padding, .. }) => {
(font.clone(), *backdrop, *align, *padding)
}
_ => (None, Colour::CLEAR, Align::Left, 0),
};
let size_px = parse_f32(&form.text_size, "text size")?;
if size_px <= 0.0 {
return Err("text size: above 0".into());
}
SourceKind::Text {
text: form.text.replace("\\n", "\n"),
font,
size_px,
colour: parse_colour(&form.colour).ok_or("colour: #rrggbb")?,
backdrop,
align,
padding,
}
}
("colour", old) => SourceKind::Colour {
colour: parse_colour(&form.colour).ok_or("colour: #rrggbb")?,
size: match old {
Some(SourceKind::Colour { size, .. }) => *size,
_ => (1920, 1080),
},
},
("image", _) if form.path.trim().is_empty() => return Err("image: a file".into()),
("image", _) => SourceKind::Image { path: form.path.trim().into() },
(_, Some(SourceKind::Camera { device, size, fps, .. })) => SourceKind::Camera {
device: device.clone(),
size: *size,
fps: *fps,
mirror: form.mirror,
},
(_, Some(old)) => old.clone(),
(other, None) => return Err(format!("cannot add a {other} source here")),
})
}
/// A new text, colour or image source from the dialog (id 0: the
/// controller gives it one).
pub fn new_source(form: &StudioSourceForm, output: (u32, u32)) -> Result<Source, String> {
let kind = kind(form, None)?;
let mut source = Source::new(0, kind);
source.name = form.name.trim().to_owned();
source.transform = if form.kind == "colour" {
Transform::full(output.0, output.1)
} else {
let mut t = placement(&source.kind, output);
if let Ok(x) = parse_f32(&form.x, "X") {
t.x = x;
}
if let Ok(y) = parse_f32(&form.y, "Y") {
t.y = y;
}
t
};
source.opacity = (form.opacity / 100.0).clamp(0.0, 1.0);
Ok(source)
}
/// Where a new source goes in a `w` x `h` picture: captures fill it
/// (cropping what does not fit), a camera sits in the bottom right corner,
/// text at the bottom left, images at their own size in the top left.
pub fn placement(kind: &SourceKind, (w, h): (u32, u32)) -> Transform {
let (w, h) = (w as f32, h as f32);
match kind {
SourceKind::Camera { .. } => {
let width = (w * 0.25).round();
let height = (width * 9.0 / 16.0).round();
let margin = (h * 0.03).round();
Transform {
fit: Fit::Cover,
..Transform::box_at(w - width - margin, h - height - margin, width, height)
}
}
SourceKind::Text { .. } => {
Transform { x: (w * 0.03).round(), y: (h * 0.8).round(), ..Transform::default() }
}
SourceKind::Image { .. } => Transform::default(),
_ => Transform { fit: Fit::Cover, ..Transform::box_at(0.0, 0.0, w, h) },
}
}
/// A source the stream settings' switches keep: its name, and its text
/// (`None`: switched off, so it is removed).
#[derive(Clone, Debug, PartialEq)]
pub struct Overlay {
pub name: &'static str,
pub text: Option<String>,
}
pub const OVERLAY_VIEWERS: &str = "Viewer count";
pub const OVERLAY_CHAT: &str = "Chat overlay";
pub const OVERLAY_NOW_PLAYING: &str = "Now playing";
fn overlay_kind(name: &str, text: &str) -> SourceKind {
SourceKind::Text {
text: text.to_owned(),
font: None,
size_px: if name == OVERLAY_CHAT { 26.0 } else { 34.0 },
colour: Colour::WHITE,
backdrop: Colour::rgba(6, 10, 24, 170),
align: Align::Left,
padding: 14,
}
}
/// Where an overlay starts (people can move it): the viewer count at the
/// top right (by an estimate of its width), the chat at the left, what is
/// on above the bottom left. Clear of the corners the studio's own badges
/// cover in the preview.
fn overlay_place(name: &str, text: &str, (w, h): (u32, u32)) -> Transform {
let (w, h) = (w as f32, h as f32);
let margin = (w * 0.025).round();
let (x, y) = match name {
OVERLAY_VIEWERS => {
let wide = text.chars().count() as f32 * 34.0 * 0.58 + 28.0;
(w - margin - wide, h * 0.14)
}
OVERLAY_CHAT => (margin, h * 0.3),
_ => (margin, h * 0.7),
};
Transform { x: x.max(0.0).round(), y: y.round(), ..Transform::default() }
}
/// Make the scenes hold `wanted`: an overlay that is on is added to the live
/// scene if it has none, and its text follows in every scene; one that is
/// off is removed everywhere. Overlays are found by their names, so a
/// person can move them like any source. Returns whether anything changed.
pub fn apply_overlays(scenes: &mut Scenes, wanted: &[Overlay]) -> bool {
let size = scenes.size();
let live = scenes.active().map(|s| s.id);
let mut changed = false;
for overlay in wanted {
match &overlay.text {
None => {
for scene in &mut scenes.scenes {
let before = scene.sources.len();
scene.sources.retain(|s| s.name != overlay.name);
changed |= scene.sources.len() != before;
}
}
Some(text) => {
for scene in &mut scenes.scenes {
for source in scene.sources.iter_mut().filter(|s| s.name == overlay.name) {
if let SourceKind::Text { text: shown, .. } = &mut source.kind
&& shown != text
{
shown.clone_from(text);
changed = true;
}
}
}
let Some(scene) = live.and_then(|id| scenes.scene_mut(id)) else { continue };
if !scene.sources.iter().any(|s| s.name == overlay.name) {
let id = scene.next_source_id();
scene.sources.push(Source {
name: overlay.name.into(),
transform: overlay_place(overlay.name, text, size),
..Source::new(id, overlay_kind(overlay.name, text))
});
changed = true;
}
}
}
}
changed
}
#[cfg(test)]
mod tests {
use super::*;
fn scene_with(names: &[&str]) -> Scenes {
let mut scene = Scene::new(1, "Main");
for (i, name) in names.iter().enumerate() {
let kind = SourceKind::Colour { colour: Colour::BLACK, size: (16, 16) };
scene.sources.push(Source { name: (*name).into(), ..Source::new(i as u64 + 1, kind) });
}
Scenes { scenes: vec![scene, Scene::new(2, "Break")], active: 1, ..Scenes::default() }
}
#[test]
fn rows_show_scenes_and_sources_front_first() {
let scenes = scene_with(&["Screen", "Camera"]);
let rows = super::scenes(&scenes);
assert_eq!(rows.len(), 2);
assert!(rows[0].live && !rows[1].live);
assert_eq!(rows[0].detail, "Screen + Camera");
assert_eq!(rows[1].detail, "Empty");
let sources = super::sources(scenes.active(), &[]);
assert_eq!(
sources.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(),
["Camera", "Screen"]
);
assert!(sources[0].front && !sources[0].back && sources[1].back);
}
#[test]
fn numbers_for_the_header() {
assert_eq!(thousands(8250), "8,250");
assert_eq!(thousands(1_234_567), "1,234,567");
assert_eq!(thousands(999), "999");
assert_eq!(format_line(1080, 60, 8250), "1080p • 60 FPS • 8,250 kbps");
assert_eq!(clock(Duration::from_secs(12 * 60 + 34)), "00:12:34");
assert_eq!(clock(Duration::from_secs(3 * 3600 + 5)), "03:00:05");
assert_eq!(quality(false, 60, 60.0, None).0, 0);
assert_eq!(quality(true, 60, 59.0, None).0, 4);
assert_eq!(quality(true, 60, 59.0, Some(0.6)).0, 2);
assert_eq!(quality(true, 60, 20.0, Some(1.0)).0, 1);
}
#[test]
fn gains_and_colours_round_trip() {
assert!((gain_db(1.0)).abs() < 1e-6);
assert!((gain_db(gain_linear(-6.0)) + 6.0).abs() < 1e-4);
assert_eq!(gain_db(0.0), -60.0);
let c = parse_colour("#ff8000").unwrap();
assert_eq!(c, Colour::rgb(255, 128, 0));
assert_eq!(colour_text(c), "#ff8000");
assert_eq!(parse_colour("10203040"), Some(Colour::rgba(16, 32, 48, 64)));
assert_eq!(parse_colour("#ff80"), None);
assert_eq!(parse_colour("#gg0000"), None);
}
#[test]
fn layers_as_typed() {
let old = LayerSetting::default();
let row = |size: &str, fps: &str, kbps: &str| StudioLayer {
size: size.into(),
fps: fps.into(),
bitrate: kbps.into(),
..StudioLayer::default()
};
let l = parse_layer(&row("1280x720", "30", "2500"), &old).unwrap();
assert_eq!((l.size, l.max_fps, l.bitrate), (Some((1280, 720)), Some(30), 2_500_000));
let l = parse_layer(&row("0.5×", "", "800"), &old).unwrap();
assert_eq!((l.size, l.scale, l.max_fps), (None, 0.5, None));
assert_eq!(parse_layer(&row("50%", "", "800"), &old).unwrap().scale, 0.5);
assert!(parse_layer(&row("big", "", "800"), &old).is_err());
assert!(parse_layer(&row("1", "", "fast"), &old).is_err());
let rows = layers(&[l]);
assert_eq!((rows[0].scale.as_str(), rows[0].bitrate.as_str()), ("0.5", "800"));
let below = next_layer(&[LayerSetting { bitrate: 8_000_000, ..old.clone() }], 8000);
assert_eq!((below.scale, below.bitrate), (0.5, 2_000_000));
}
#[test]
fn the_source_form_changes_only_what_differs() {
let mut source = Source::new(
3,
SourceKind::Text {
text: "Hello\nthere".into(),
font: None,
size_px: 48.0,
colour: Colour::WHITE,
backdrop: Colour::CLEAR,
align: Align::Center,
padding: 4,
},
);
source.transform = Transform::box_at(10.0, 20.0, 300.0, 100.0);
let mut f = form(&source);
assert_eq!(f.text, "Hello\\nthere");
assert_eq!((f.x.as_str(), f.width.as_str()), ("10", "300"));
assert_eq!(change(&f, &source).unwrap(), SourceChange::default());
f.x = "40".into();
f.opacity = 50.0;
f.text = "Bye".into();
let c = change(&f, &source).unwrap();
assert_eq!(c.transform.unwrap().x, 40.0);
assert_eq!(c.opacity, Some(0.5));
let Some(SourceKind::Text { text, align, padding, .. }) = c.kind else { panic!() };
assert_eq!((text.as_str(), align, padding), ("Bye", Align::Center, 4));
f.width = "-1".into();
assert!(change(&f, &source).is_err());
}
#[test]
fn new_sources_are_placed_by_kind() {
let camera =
SourceKind::Camera { device: String::new(), size: None, fps: None, mirror: false };
let t = placement(&camera, (1920, 1080));
assert_eq!((t.width, t.height, t.fit), (Some(480.0), Some(270.0), Fit::Cover));
assert!(t.x + 480.0 < 1920.0 && t.y + 270.0 < 1080.0);
let screen = SourceKind::Screen { monitor: 0, backend: None, cursor: true };
assert_eq!(placement(&screen, (1920, 1080)).width, Some(1920.0));
let form = StudioSourceForm {
kind: "colour".into(),
name: "Slate".into(),
colour: "#101a3c".into(),
opacity: 100.0,
..Default::default()
};
let s = new_source(&form, (1280, 720)).unwrap();
assert_eq!((s.name.as_str(), s.transform.width), ("Slate", Some(1280.0)));
assert!(new_source(&StudioSourceForm { kind: "image".into(), ..form }, (1, 1)).is_err());
}
#[test]
fn overlays_follow_the_switches() {
let mut scenes = scene_with(&["Screen"]);
let on = |text: &str| Overlay { name: OVERLAY_VIEWERS, text: Some(text.into()) };
assert!(apply_overlays(&mut scenes, &[on("3 watching")]));
let live = &scenes.scenes[0];
assert_eq!(live.sources.len(), 2);
assert_eq!(live.sources[1].name, OVERLAY_VIEWERS);
// Nothing to do the second time; the text follows.
assert!(!apply_overlays(&mut scenes, &[on("3 watching")]));
assert!(apply_overlays(&mut scenes, &[on("4 watching")]));
let SourceKind::Text { text, .. } = &scenes.scenes[0].sources[1].kind else { panic!() };
assert_eq!(text, "4 watching");
// A scene switch adds it to the new live scene too; off removes all.
scenes.active = 2;
assert!(apply_overlays(&mut scenes, &[on("4 watching")]));
assert_eq!(scenes.scenes[1].sources.len(), 1);
assert!(apply_overlays(&mut scenes, &[Overlay { name: OVERLAY_VIEWERS, text: None }]));
assert_eq!(scenes.scenes[0].sources.len(), 1);
assert!(scenes.scenes[1].sources.is_empty());
assert!(scenes.check().is_ok());
}
}
-905
View File
@@ -1,905 +0,0 @@
//! The channel tree, the members of our channel and everyone on the
//! server for the members panel.
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
pub use voelin_model::channel_title;
use voelin_model::{
BannerMode, ChannelId, ChannelInfo, ClientInfo, GroupInfo, Presence, Spacer, TreeRow, badges,
tree_rows,
};
use crate::app::{BadgeItem, MemberItem, TreeItem};
use crate::settings::ClientPlaybackMap;
use crate::vm::avatar;
/// A banner mode as the UI takes it (`TreeItem.banner-mode`).
pub fn banner_mode(mode: BannerMode) -> i32 {
match mode {
BannerMode::NoAdjust => 0,
BannerMode::IgnoreAspect => 1,
BannerMode::KeepAspect => 2,
}
}
/// The picture of a banner address, if the engine fetched it.
pub fn banner(pictures: &HashMap<String, PathBuf>, url: Option<&str>) -> slint::Image {
avatar::image(url.and_then(|u| pictures.get(u)))
}
/// A badge's picture, if the engine fetched it.
fn badge_icon(pictures: &HashMap<String, PathBuf>, guid: &str) -> slint::Image {
avatar::image(badges::icon_url(guid).and_then(|url| pictures.get(&url)))
}
/// A client's badges for the member card: the first three in its order.
/// One the app does not know is "Badge", with its GUID as description.
pub fn badge_items(guids: &[String], pictures: &HashMap<String, PathBuf>) -> Vec<BadgeItem> {
guids
.iter()
.take(badges::SHOWN)
.map(|guid| {
let (name, description) = match badges::info(guid) {
Some(info) => (info.name.as_str(), info.description.as_str()),
None => ("Badge", guid.as_str()),
};
BadgeItem {
name: name.into(),
description: description.into(),
icon: badge_icon(pictures, guid),
}
})
.collect()
}
/// What the tree shows besides the presence.
pub struct TreeInput<'a> {
pub presence: &'a Presence,
pub collapsed: &'a HashSet<ChannelId>,
pub talking: &'a HashSet<u16>,
pub playback: &'a ClientPlaybackMap,
pub own_channel: Option<ChannelId>,
pub own_client: Option<u16>,
/// Search text: only matching channels and clients (and the channels
/// above them) are shown. Empty: everything.
pub filter: &'a str,
/// Avatar pictures in the engine's cache, by unique id.
pub avatars: &'a HashMap<String, PathBuf>,
/// Icons in the engine's cache, by icon id (channel, group and client
/// icons).
pub icons: &'a HashMap<u32, PathBuf>,
/// Banners and badges in the engine's cache, by address.
pub pictures: &'a HashMap<String, PathBuf>,
/// The server groups in display order; members are grouped by the
/// first one each client is in.
pub groups: &'a [GroupInfo],
/// The channel groups (their icons).
pub channel_groups: &'a [GroupInfo],
}
impl TreeInput<'_> {
fn avatar(&self, client: &ClientInfo) -> slint::Image {
avatar::image(client.uid.as_ref().and_then(|uid| self.avatars.get(uid)))
}
/// An icon by id, if the engine fetched it (0: none).
fn icon(&self, id: u32) -> Option<slint::Image> {
let path = self.icons.get(&id).filter(|_| id != 0)?;
Some(avatar::image(Some(path))).filter(|i| i.size().width > 0)
}
/// The icons beside a client, as TeamSpeak shows them: its server
/// groups' in display order, its channel group's, its own.
fn client_icons(&self, client: &ClientInfo) -> Vec<slint::Image> {
let groups = self.groups.iter().filter(|g| client.server_groups.contains(&g.id));
let channel_group =
self.channel_groups.iter().filter(|g| client.channel_group == Some(g.id));
groups
.chain(channel_group)
.map(|g| g.icon)
.chain([client.icon])
.filter_map(|id| self.icon(id))
.collect()
}
/// The pictures of the badges a client shows that arrived, in its
/// order; empty slots last.
fn badges(&self, client: &ClientInfo) -> [slint::Image; badges::SHOWN] {
let mut icons = client
.badges
.iter()
.take(badges::SHOWN)
.map(|guid| badge_icon(self.pictures, guid))
.filter(|i| i.size().width > 0);
std::array::from_fn(|_| icons.next().unwrap_or_default())
}
/// The group a client is sorted under: the first of its server groups
/// in display order.
fn group_of(&self, client: &ClientInfo) -> Option<&GroupInfo> {
self.groups.iter().find(|g| client.server_groups.contains(&g.id))
}
}
/// "Speaking", "Away: brb", "Muted", …
pub fn status_of(client: &ClientInfo, talking: bool) -> String {
if talking {
"Speaking".to_owned()
} else if client.streaming == Some(true) {
"Streaming".to_owned()
} else if let Some(message) = &client.away {
if message.is_empty() { "Away".to_owned() } else { format!("Away: {message}") }
} else if client.output_muted {
"Sound off".to_owned()
} else if client.input_muted {
"Muted".to_owned()
} else {
"Listening".to_owned()
}
}
fn talking(input: &TreeInput, client: &ClientInfo) -> bool {
input.talking.contains(&client.id) || client.talking == Some(true)
}
/// A spacer kind as the UI takes it (`TreeItem.spacer`, 0: no spacer).
fn spacer_index(kind: Spacer) -> i32 {
match kind {
Spacer::Left => 1,
Spacer::Center => 2,
Spacer::Right => 3,
Spacer::Fill => 4,
}
}
/// A channel's title for lists and pickers (the search, the event form);
/// none for a spacer that only separates.
pub fn listed_title(channel: &ChannelInfo) -> Option<&str> {
match channel_title(channel) {
(text, Some(kind)) if kind.separates(text) => None,
(text, _) => Some(text),
}
}
/// Channels deeper than this are not followed up (a broken presence could
/// loop).
const PATH_DEPTH: usize = 64;
/// The path of a channel, its names from the top as the server has them
/// (what an invite link names, what connecting into it takes); empty for a
/// channel the presence does not know.
pub fn channel_path(presence: &Presence, channel: ChannelId) -> Vec<String> {
let mut names = Vec::new();
let mut next = presence.channels.get(&channel);
while let Some(c) = next.filter(|_| names.len() < PATH_DEPTH) {
names.push(c.name.clone());
next = presence.channels.get(&c.parent).filter(|_| c.parent != 0);
}
names.reverse();
names
}
/// About as many characters as a fill spacer's row holds: more than the
/// widest tree shows.
const FILL_CHARS: usize = 200;
/// A spacer's text as its row shows it: a fill pattern repeated across the
/// row, a blank text empty.
fn spacer_text(kind: Spacer, text: &str) -> String {
match kind {
Spacer::Fill => match text.chars().count() {
0 => String::new(),
n => text.repeat((FILL_CHARS / n).max(1)),
},
_ if text.trim().is_empty() => String::new(),
_ => text.to_owned(),
}
}
/// The rows of the tree, channels with their clients below.
pub fn rows(input: &TreeInput) -> Vec<TreeItem> {
let p = input.presence;
let rows: Vec<TreeItem> = tree_rows(p, &|cid| input.collapsed.contains(&cid))
.into_iter()
.map(|row| match row {
TreeRow::Channel { depth, channel } => {
let (name, spacer) = match channel_title(channel) {
(text, Some(kind)) => (spacer_text(kind, text), spacer_index(kind)),
(name, None) => (name.to_owned(), 0),
};
TreeItem {
spacer,
is_channel: true,
depth: depth as i32,
id: channel.id as i32,
name: name.into(),
own: input.own_channel == Some(channel.id),
locked: channel.has_password,
collapsed: input.collapsed.contains(&channel.id),
local_volume: 100,
members: p.members(channel.id).count() as i32,
max_members: channel.max_clients.filter(|m| *m >= 0).unwrap_or(-1),
icon: input.icon(channel.icon).unwrap_or_default(),
banner: banner(input.pictures, channel.banner_gfx_url.as_deref()),
banner_mode: banner_mode(channel.banner_mode),
..Default::default()
}
}
TreeRow::Client { depth, client } => {
let playback = client
.uid
.as_ref()
.and_then(|uid| input.playback.get(uid))
.copied()
.unwrap_or_default();
let mut icons = input.client_icons(client).into_iter();
let [badge, badge_2, badge_3] = input.badges(client);
TreeItem {
is_channel: false,
depth: depth as i32,
id: client.id as i32,
name: client.nickname.clone().into(),
talking: talking(input, client),
muted: client.input_muted,
sound_off: client.output_muted,
away: client.away.is_some(),
streaming: client.streaming == Some(true),
local_muted: playback.muted,
local_volume: (playback.volume * 100.0).round() as i32,
myself: input.own_client == Some(client.id),
initials: avatar::initials(&client.nickname).into(),
tint: avatar::tint(&client.nickname),
avatar: input.avatar(client),
icon: icons.next().unwrap_or_default(),
icon_2: icons.next().unwrap_or_default(),
icon_3: icons.next().unwrap_or_default(),
badge,
badge_2,
badge_3,
..Default::default()
}
}
})
.collect();
filter(rows, input.filter)
}
/// A spacer row that only separates: a line, or no text.
fn separator(row: &TreeItem) -> bool {
row.is_channel
&& (row.spacer == spacer_index(Spacer::Fill) || (row.spacer != 0 && row.name.is_empty()))
}
/// Rows that match `query`, and the channels above them. A separator
/// never matches (`---` is no channel to look for), but stays above what
/// does.
fn filter(rows: Vec<TreeItem>, query: &str) -> Vec<TreeItem> {
let query = query.trim().to_lowercase();
if query.is_empty() {
return rows;
}
let matches: Vec<bool> = rows
.iter()
.map(|r| !separator(r) && r.name.to_lowercase().contains(query.as_str()))
.collect();
let mut keep = matches.clone();
// A channel stays if anything below it matches.
for i in 0..rows.len() {
if !rows[i].is_channel || keep[i] {
continue;
}
let depth = rows[i].depth;
keep[i] = rows[i + 1..]
.iter()
.zip(&matches[i + 1..])
.take_while(|(r, _)| r.depth > depth)
.any(|(_, m)| *m);
}
rows.into_iter().zip(keep).filter_map(|(r, k)| k.then_some(r)).collect()
}
/// "12 online · 8 channels"
pub fn stats(p: &Presence) -> String {
let online = p.clients.values().filter(|c| !c.is_query).count();
let channels = p.channels.len();
format!("{online} online · {channels} {}", if channels == 1 { "channel" } else { "channels" })
}
/// Names of server groups whose members wear the crown (the server's
/// admins). TeamSpeak has no flag for it, so the usual names are matched.
fn is_admin_group(name: &str) -> bool {
let lower = name.to_lowercase();
["admin", "owner", "operator", "leiter"].iter().any(|w| lower.contains(w))
}
/// Moderator groups, shown as a role next to the name.
fn is_moderator_group(name: &str) -> bool {
name.to_lowercase().contains("mod")
}
/// Whether a client cannot speak in its channel: the channel needs more
/// talk power than it has, and it was not made a talker.
pub fn cannot_talk(channel: Option<&ChannelInfo>, client: &ClientInfo) -> bool {
channel.is_some_and(|c| {
c.needed_talk_power > 0 && client.talk_power < c.needed_talk_power && !client.talker
})
}
impl TreeInput<'_> {
/// The position of a client's group in display order (no group last).
fn group_rank(&self, client: &ClientInfo) -> usize {
self.groups.iter().position(|g| client.server_groups.contains(&g.id)).unwrap_or(usize::MAX)
}
/// One row of the members panel or the voice channel, under `section`.
fn member(&self, c: &ClientInfo, section: &Section) -> MemberItem {
let talking = talking(self, c);
let group = self.group_of(c).map_or("", |g| g.name.as_str());
let admin = is_admin_group(group);
// Someone elsewhere on the server: where they are says more than
// "Listening".
let elsewhere = self.own_channel != Some(c.channel)
&& !talking
&& c.streaming != Some(true)
&& c.away.is_none();
let channel = self.presence.channels.get(&c.channel);
let status = match channel {
Some(channel) if elsewhere => format!("In {}", channel_title(channel).0),
_ => status_of(c, talking),
};
let [badge, badge_2, badge_3] = self.badges(c);
MemberItem {
id: c.id as i32,
name: c.nickname.clone().into(),
initials: avatar::initials(&c.nickname).into(),
tint: avatar::tint(&c.nickname),
avatar: self.avatar(c),
talking,
muted: c.input_muted,
sound_off: c.output_muted,
away: c.away.is_some(),
streaming: c.streaming == Some(true),
myself: self.own_client == Some(c.id),
status: status.into(),
away_message: c.away.clone().unwrap_or_default().into(),
group: section.title.clone().into(),
group_icon: section.icon.clone(),
first_in_group: false,
group_count: 0,
admin,
role: if !admin && is_moderator_group(group) { group.into() } else { "".into() },
priority: c.priority_speaker,
commander: c.channel_commander,
recording: c.recording,
cannot_talk: cannot_talk(channel, c),
badge,
badge_2,
badge_3,
}
}
}
/// A heading of the members panel.
#[derive(Clone, Default)]
struct Section {
title: String,
icon: slint::Image,
}
/// Rows in sections: each section's first row carries the heading and how
/// many rows follow.
fn sectioned(
input: &TreeInput,
mut clients: Vec<(Section, usize, &ClientInfo)>,
) -> Vec<MemberItem> {
clients.sort_by_key(|(_, rank, c)| (*rank, c.nickname.to_lowercase(), c.id));
let mut rows: Vec<MemberItem> = clients.iter().map(|(s, _, c)| input.member(c, s)).collect();
let mut start = 0;
while start < rows.len() {
let rank = clients[start].1;
let count = clients[start..].iter().take_while(|(_, r, _)| *r == rank).count();
rows[start].first_in_group = true;
rows[start].group_count = count as i32;
start += count;
}
rows
}
/// The section of a client's server group.
fn group_section(input: &TreeInput, client: &ClientInfo) -> (Section, usize) {
match input.group_of(client) {
Some(g) => (
Section { title: g.name.clone(), icon: input.icon(g.icon).unwrap_or_default() },
1 + input.group_rank(client),
),
None => (Section { title: "Online".into(), ..Default::default() }, usize::MAX),
}
}
/// The clients in our channel, grouped by server group (in the server's
/// display order) and by name inside a group.
pub fn members(input: &TreeInput) -> Vec<MemberItem> {
let Some(channel) = input.own_channel else { return Vec::new() };
let clients = input
.presence
.members(channel)
.map(|c| {
let (section, rank) = group_section(input, c);
(section, rank, c)
})
.collect();
sectioned(input, clients)
}
/// The rows whose name contains `filter` (lower case), in sections
/// counted again.
pub fn matching(rows: Vec<MemberItem>, filter: &str) -> Vec<MemberItem> {
let mut rows: Vec<MemberItem> =
rows.into_iter().filter(|m| m.name.to_lowercase().contains(filter)).collect();
let mut start = 0;
while start < rows.len() {
let group = rows[start].group.clone();
let count = rows[start..].iter().take_while(|m| m.group == group).count();
for (i, row) in rows[start..start + count].iter_mut().enumerate() {
row.first_in_group = i == 0;
row.group_count = if i == 0 { count as i32 } else { 0 };
}
start += count;
}
rows
}
/// Everyone on the server for the members panel: first the people in our
/// voice channel (`voice_first`, in the voice channel and stream views) or
/// those streaming, then each server group in the server's order.
pub fn server_members(input: &TreeInput, voice_first: bool) -> Vec<MemberItem> {
let first = Section {
title: if voice_first { "In Voice" } else { "Streaming" }.into(),
icon: slint::Image::default(),
};
let clients = input
.presence
.clients
.values()
.filter(|c| !c.is_query)
.map(|c| {
let lead = if voice_first {
input.own_channel == Some(c.channel)
} else {
c.streaming == Some(true)
};
if lead {
(first.clone(), 0, c)
} else {
let (section, rank) = group_section(input, c);
(section, rank, c)
}
})
.collect();
sectioned(input, clients)
}
#[cfg(test)]
mod tests {
use voelin_model::ChannelInfo;
use super::*;
fn presence() -> Presence {
let channel = |id, parent, order, name: &str| ChannelInfo {
id,
parent,
order,
name: name.into(),
max_clients: if id == 2 { Some(5) } else { None },
..Default::default()
};
let client = |id, channel, name: &str| ClientInfo {
id,
channel,
nickname: name.into(),
..Default::default()
};
let mut p = Presence::default();
for c in [channel(1, 0, 0, "Lobby"), channel(2, 0, 1, "Games"), channel(3, 2, 0, "Chess")] {
p.channels.insert(c.id, c);
}
for c in [client(10, 1, "Alice"), client(11, 2, "bob"), client(12, 3, "Carol")] {
p.clients.insert(c.id, c);
}
let mut query = client(13, 1, "serveradmin");
query.is_query = true;
p.clients.insert(13, query);
p
}
/// Empty caches and no groups, for the tests below.
#[derive(Default)]
struct Extras {
avatars: HashMap<String, PathBuf>,
icons: HashMap<u32, PathBuf>,
pictures: HashMap<String, PathBuf>,
groups: Vec<GroupInfo>,
channel_groups: Vec<GroupInfo>,
}
fn input<'a>(
p: &'a Presence,
talking: &'a HashSet<u16>,
collapsed: &'a HashSet<ChannelId>,
playback: &'a ClientPlaybackMap,
filter: &'a str,
extras: &'a Extras,
) -> TreeInput<'a> {
TreeInput {
presence: p,
collapsed,
talking,
playback,
own_channel: Some(2),
own_client: Some(11),
filter,
avatars: &extras.avatars,
icons: &extras.icons,
pictures: &extras.pictures,
groups: &extras.groups,
channel_groups: &extras.channel_groups,
}
}
/// A PNG of this width in a file (the engine's cache names them without
/// an extension).
fn picture_file(dir: &std::path::Path, name: &str, width: u32) -> PathBuf {
let mut png = Vec::new();
let mut encoder = png::Encoder::new(&mut png, width, 2);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
encoder.write_header().unwrap().write_image_data(&vec![120; width as usize * 8]).unwrap();
let path = dir.join(name);
std::fs::write(&path, png).unwrap();
path
}
/// Avatars, channel icons and banners, group and client icons (in
/// TeamSpeak's order, those that arrived) reach the rows.
#[test]
fn pictures_in_rows() {
let dir = std::env::temp_dir().join(format!("voelin-tree-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let mut p = presence();
let lobby = p.channels.get_mut(&1).unwrap();
lobby.icon = 2001;
lobby.banner_gfx_url = Some("https://e.com/lobby.png".into());
lobby.banner_mode = BannerMode::KeepAspect;
let alice = p.clients.get_mut(&10).unwrap();
alice.uid = Some("alice=".into());
alice.server_groups = vec![7, 6];
alice.channel_group = Some(5);
alice.icon = 4004;
let group = |id, sort_id, icon| GroupInfo { id, icon, sort_id, ..Default::default() };
let e = Extras {
avatars: HashMap::from([("alice=".into(), picture_file(&dir, "avatar", 5))]),
icons: HashMap::from([
(2001, picture_file(&dir, "2001", 7)),
(3003, picture_file(&dir, "3003", 3)),
(4004, picture_file(&dir, "4004", 4)),
(5005, picture_file(&dir, "5005", 6)),
]),
pictures: HashMap::from([(
"https://e.com/lobby.png".into(),
picture_file(&dir, "banner", 9),
)]),
// Group 7 sorts first; group 6's icon has not arrived.
groups: vec![group(7, 10, 3003), group(6, 20, 9999)],
channel_groups: vec![group(5, 0, 5005)],
};
let (t, c, pb) = (HashSet::new(), HashSet::new(), ClientPlaybackMap::new());
let rows = rows(&input(&p, &t, &c, &pb, "", &e));
let width = |i: &slint::Image| i.size().width;
let lobby = &rows[0];
assert_eq!((width(&lobby.icon), width(&lobby.banner), lobby.banner_mode), (7, 9, 2));
let alice = &rows[1];
assert_eq!(width(&alice.avatar), 5);
assert_eq!([&alice.icon, &alice.icon_2, &alice.icon_3].map(width), [3, 6, 4]);
// Nothing for the others.
let games = &rows[2];
assert_eq!((width(&games.icon), width(&games.banner), games.banner_mode), (0, 0, 0));
assert_eq!(width(&rows[3].avatar), 0);
std::fs::remove_dir_all(dir).unwrap();
}
/// A client's badges: the first three in its order, on the card by name
/// ("Badge" for one the app does not know), in the rows the pictures
/// that arrived.
#[test]
fn badges_on_the_card_and_in_rows() {
let dir = std::env::temp_dir().join(format!("voelin-tree-badges-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let guids: Vec<String> = [
"4b27be5a-b92a-4b30-8b2d-14b59653f427",
"00000000-0000-0000-0000-000000000000",
"05114019-6b46-4b13-b5a1-e5179ef69fb5",
"2bf80270-8efe-46dc-a472-3280a0479145",
]
.map(String::from)
.into();
let picture = |i: usize, width| {
(badges::icon_url(&guids[i]).unwrap(), picture_file(&dir, &format!("badge-{i}"), width))
};
let e = Extras {
pictures: HashMap::from([picture(0, 3), picture(2, 5), picture(3, 7)]),
..Default::default()
};
let width = |i: &slint::Image| i.size().width;
let card = badge_items(&guids, &e.pictures);
let names: Vec<_> = card.iter().map(|b| b.name.as_str()).collect();
assert_eq!(names, ["20th Anniversary", "Badge", "April Fools!"]);
assert_eq!(card[1].description.as_str(), guids[1]);
assert_eq!(card.iter().map(|b| width(&b.icon)).collect::<Vec<_>>(), [3, 0, 5]);
let mut p = presence();
p.clients.get_mut(&11).unwrap().badges = guids;
let (t, c, pb) = (HashSet::new(), HashSet::new(), ClientPlaybackMap::new());
let tree = input(&p, &t, &c, &pb, "", &e);
let bob = rows(&tree).into_iter().find(|r| !r.is_channel && r.id == 11).unwrap();
assert_eq!([&bob.badge, &bob.badge_2, &bob.badge_3].map(width), [3, 5, 0]);
let bob = members(&tree).into_iter().find(|m| m.id == 11).unwrap();
assert_eq!([&bob.badge, &bob.badge_2, &bob.badge_3].map(width), [3, 5, 0]);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn spacer_rows_keep_tree_identity() {
let mut p = presence();
p.channels.get_mut(&2).unwrap().name = "[cspacer12]Гамесы".into();
let more = |id, order, name: &str| ChannelInfo {
id,
order,
name: name.into(),
has_password: id == 5,
..Default::default()
};
for c in
[more(4, 2, "[*spacer1]-="), more(5, 4, "[rspacer2]Staff"), more(6, 5, "[spacer3]")]
{
p.channels.insert(c.id, c);
}
let (t, c, pb) = (HashSet::new(), HashSet::from([2]), ClientPlaybackMap::new());
let e = Extras::default();
let rows = rows(&input(&p, &t, &c, &pb, "", &e));
let channels: Vec<_> = rows
.iter()
.filter(|r| r.is_channel)
.map(|r| (r.id, r.spacer, r.name.chars().take(6).collect::<String>()))
.collect();
let row = |id, spacer, name: &str| (id, spacer, name.to_owned());
assert_eq!(
channels,
[
row(1, 0, "Lobby"),
row(2, 2, "Гамесы"),
row(4, 4, "-=-=-="),
row(5, 3, "Staff"),
row(6, 1, ""),
]
);
// A fill line repeats its pattern across the row.
let fill = &rows.iter().find(|r| r.id == 4 && r.is_channel).unwrap().name;
assert_eq!(fill.chars().count(), FILL_CHARS);
assert_eq!(spacer_text(Spacer::Fill, ""), "");
assert_eq!(spacer_text(Spacer::Fill, "x".repeat(300).as_str()).len(), 300);
let games = rows.iter().find(|r| r.id == 2 && r.is_channel).unwrap();
assert!(games.collapsed && games.members == 1);
assert!(rows.iter().any(|r| r.id == 5 && r.is_channel && r.locked));
// Only top-level channels are spacers: a sub-channel keeps its name.
p.channels.get_mut(&3).unwrap().name = "[cspacer1]Chess".into();
let c = HashSet::new();
let rows = super::rows(&input(&p, &t, &c, &pb, "", &e));
let chess = rows.iter().find(|r| r.is_channel && r.id == 3).unwrap();
assert_eq!((chess.name.as_str(), chess.spacer), ("[cspacer1]Chess", 0));
assert_eq!(channel_title(&p.channels[&2]), ("Гамесы", Some(Spacer::Center)));
assert_eq!(channel_title(&p.channels[&3]), ("[cspacer1]Chess", None));
// Lists and pickers leave out what only separates.
let listed: Vec<_> = p.channels.values().filter_map(listed_title).collect();
assert_eq!(listed, ["Lobby", "Гамесы", "[cspacer1]Chess", "Staff"]);
}
/// The search finds a spacer by its text, never a separator, but keeps
/// separators above what it finds.
#[test]
fn search_skips_separators() {
let mut p = presence();
p.channels.get_mut(&2).unwrap().name = "[*spacer1]---".into();
p.channels.get_mut(&1).unwrap().name = "[cspacer]Lobby".into();
p.channels.insert(
4,
ChannelInfo { id: 4, order: 2, name: "[spacer4]".into(), ..Default::default() },
);
let (t, c, pb) = (HashSet::new(), HashSet::new(), ClientPlaybackMap::new());
let e = Extras::default();
let names = |filter| {
super::rows(&input(&p, &t, &c, &pb, filter, &e))
.iter()
.map(|r| r.name.chars().take(3).collect::<String>())
.collect::<Vec<_>>()
};
assert!(names("-").is_empty());
assert!(names("spacer").is_empty());
assert_eq!(names("lob"), ["Lob"]);
// The line stays as the parent of Chess.
assert_eq!(names("chess"), ["---", "Che"]);
}
#[test]
fn tree_rows_and_counts() {
let p = presence();
let (t, c, pb) = (HashSet::from([11]), HashSet::new(), ClientPlaybackMap::new());
let e = Extras::default();
let rows = rows(&input(&p, &t, &c, &pb, "", &e));
let names: Vec<_> = rows.iter().map(|r| r.name.as_str()).collect();
assert_eq!(names, ["Lobby", "Alice", "Games", "bob", "Chess", "Carol"]);
assert_eq!((rows[0].members, rows[0].max_members), (1, -1));
assert_eq!((rows[2].members, rows[2].max_members, rows[2].own), (1, 5, true));
assert!(rows[3].talking && rows[3].myself);
assert_eq!(rows[3].initials, "BO");
assert_eq!(stats(&p), "3 online · 3 channels");
}
#[test]
fn search_keeps_parents() {
let p = presence();
let (t, c, pb) = (HashSet::new(), HashSet::new(), ClientPlaybackMap::new());
let e = Extras::default();
let rows = rows(&input(&p, &t, &c, &pb, "car", &e));
let names: Vec<_> = rows.iter().map(|r| r.name.as_str()).collect();
assert_eq!(names, ["Games", "Chess", "Carol"]);
let rows = super::rows(&input(&p, &t, &c, &pb, "LOBBY", &e));
assert_eq!(rows.len(), 1);
}
#[test]
fn members_of_our_channel() {
let mut p = presence();
p.clients.get_mut(&12).unwrap().channel = 2;
p.clients.get_mut(&12).unwrap().away = Some(String::new());
let (t, c, pb) = (HashSet::new(), HashSet::new(), ClientPlaybackMap::new());
let e = Extras::default();
let members = members(&input(&p, &t, &c, &pb, "", &e));
let names: Vec<_> = members.iter().map(|m| (m.name.as_str(), m.status.as_str())).collect();
assert_eq!(names, [("bob", "Listening"), ("Carol", "Away")]);
}
#[test]
fn members_are_grouped_by_server_group() {
let mut p = presence();
p.clients.get_mut(&12).unwrap().channel = 2;
p.clients.get_mut(&12).unwrap().server_groups = vec![6];
p.clients.get_mut(&11).unwrap().server_groups = vec![7];
let group = |id, sort_id, name: &str| GroupInfo {
id,
name: name.into(),
icon: 0,
sort_id,
..Default::default()
};
let e = Extras {
groups: vec![group(6, 10, "Server Admin"), group(7, 20, "Guest")],
..Default::default()
};
let (t, c, pb) = (HashSet::new(), HashSet::new(), ClientPlaybackMap::new());
let members = members(&input(&p, &t, &c, &pb, "", &e));
let rows: Vec<_> =
members.iter().map(|m| (m.name.as_str(), m.group.as_str(), m.first_in_group)).collect();
assert_eq!(rows, [("Carol", "Server Admin", true), ("bob", "Guest", true)]);
assert!(members[0].admin && !members[1].admin);
}
#[test]
fn members_who_cannot_talk() {
let channel = |needed| ChannelInfo { needed_talk_power: needed, ..Default::default() };
let client = |talk_power, talker| ClientInfo { talk_power, talker, ..Default::default() };
for (needed, power, talker, cannot) in [
(50, 75, false, false),
(50, 50, false, false),
(50, 0, false, true),
(50, 49, false, true),
// A talker speaks without talk power.
(50, 0, true, false),
// The channel needs none.
(0, 0, false, false),
] {
let case = format!("needed {needed}, power {power}, talker {talker}");
assert_eq!(
cannot_talk(Some(&channel(needed)), &client(power, talker)),
cannot,
"{case}"
);
}
assert!(!cannot_talk(None, &client(0, false)));
// In the members panel: bob (talk power 75) speaks in Games, which
// needs 50; Carol (none) cannot.
let mut p = presence();
p.channels.get_mut(&2).unwrap().needed_talk_power = 50;
p.clients.get_mut(&11).unwrap().talk_power = 75;
p.clients.get_mut(&12).unwrap().channel = 2;
let (t, c, pb) = (HashSet::new(), HashSet::new(), ClientPlaybackMap::new());
let e = Extras::default();
let rows: Vec<_> = members(&input(&p, &t, &c, &pb, "", &e))
.iter()
.map(|m| (m.name.to_string(), m.cannot_talk))
.collect();
assert_eq!(rows, [("bob".to_owned(), false), ("Carol".to_owned(), true)]);
}
#[test]
fn everyone_in_sections() {
let mut p = presence();
p.clients.get_mut(&10).unwrap().server_groups = vec![7];
p.clients.get_mut(&12).unwrap().server_groups = vec![7];
p.clients.get_mut(&12).unwrap().streaming = Some(true);
p.clients.get_mut(&11).unwrap().server_groups = vec![6];
let group = |id, sort_id, name: &str| GroupInfo {
id,
name: name.into(),
icon: 0,
sort_id,
..Default::default()
};
let e = Extras {
groups: vec![group(6, 10, "Moderator"), group(7, 20, "Guest")],
..Default::default()
};
let (t, c, pb) = (HashSet::new(), HashSet::new(), ClientPlaybackMap::new());
let rows = |voice_first| {
server_members(&input(&p, &t, &c, &pb, "", &e), voice_first)
.iter()
.map(|m| {
(
m.name.to_string(),
m.first_in_group.then(|| format!("{} — {}", m.group, m.group_count)),
m.status.to_string(),
)
})
.collect::<Vec<_>>()
};
let row = |name: &str, head: Option<&str>, status: &str| {
(name.to_owned(), head.map(str::to_owned), status.to_owned())
};
// The query client is left out; people elsewhere show their channel.
assert_eq!(
rows(false),
[
row("Carol", Some("Streaming — 1"), "Streaming"),
row("bob", Some("Moderator — 1"), "Listening"),
row("Alice", Some("Guest — 1"), "In Lobby"),
]
);
assert_eq!(
rows(true),
[
row("bob", Some("In Voice — 1"), "Listening"),
row("Alice", Some("Guest — 2"), "In Lobby"),
row("Carol", None, "Streaming"),
]
);
let all = server_members(&input(&p, &t, &c, &pb, "", &e), false);
assert_eq!(all[1].role, "Moderator");
assert!(!all[1].admin);
// The search keeps the sections of what it finds.
let found = matching(all, "al");
assert_eq!(found.len(), 1);
assert!(found[0].first_in_group && found[0].group == "Guest" && found[0].group_count == 1);
}
#[test]
fn channel_paths() {
let mut p = presence();
assert_eq!(channel_path(&p, 1), ["Lobby"], "a channel at the top");
assert_eq!(channel_path(&p, 3), ["Games", "Chess"], "the names from the top");
assert!(channel_path(&p, 99).is_empty(), "an unknown channel");
// Two channels each other's parent: the path stops.
p.channels.get_mut(&2).unwrap().parent = 3;
assert_eq!(channel_path(&p, 3).len(), PATH_DEPTH);
}
}