Move the view models into voelin-ui-vm; the Slint models take plain rows

vm/{avatar,tree,servers,streams,home,chat,social,studio} and the UI
settings (settings.rs: keys, UiSettings, LastVoice, ClientPlaybackMap,
the audio form) move into voelin-ui-vm with their tests (102 there now;
the 86 view-model tests of voelin-ui all survive, the old list::sync test
became the list::diff tests). They produce the plain bridge structs, with
Rgb for colours and ImageRef for pictures:

- a file picture is ImageSource::File { path, stamp }: the engine writes
  a picture that arrives again into the same file, so the length and
  write time are part of the reference and a changed file redraws its
  row; size() reads the header once per stamp (no toolkit decoder);
- pictures held in memory (chat previews) are ImageSource::Memory;
- the line cache of the chat no longer keeps Slint models alive for
  pointer equality: plain lines compare by value, so an unchanged
  message makes the same line with or without the cache.

voelin-ui keeps every model as bind::rows::Rows<T>: the plain rows last
shown plus the VecModel, synced with list::diff, converting only the rows
that changed (bind/convert has the From impls). The controllers hand the
view-model rows to Rows::sync and convert forms at the bridge
(`.into()`); crate::vm is now `voelin_ui_vm as vm`, so paths stay.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Sonnet 5.5 committed 2026-10-20 10:20:55 +03:00
1 parent 8e6838a00f
commit ce7ec3afb7
41 files changed
+1154 -780

No files matched your search

+59 -60
View File
@@ -38,6 +38,7 @@ use crate::settings::{
};
use crate::streams::{Share, Watch};
use crate::video::Video;
use crate::vm;
use crate::vm::chat::Previous;
slint::include_modules!();
@@ -131,7 +132,7 @@ pub(crate) struct Msg {
pub(crate) struct Tab {
pub target: ChatTarget,
pub title: String,
pub lines: Rc<VecModel<ChatLine>>,
pub lines: Rows<vm::bridge::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
@@ -175,7 +176,7 @@ impl Tab {
Self {
target,
title,
lines: Rc::new(VecModel::default()),
lines: Rows::default(),
messages: Vec::new(),
last: None,
unread: 0,
@@ -462,77 +463,75 @@ impl SessionView {
}
/// 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),
)
pub fn server_icon(&self) -> vm::ImageRef {
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 {
pub fn server_icon_for(&self, address: &str) -> vm::ImageRef {
if self.icon_address.as_deref() == Some(address) {
self.server_icon()
} else {
slint::Image::default()
vm::ImageRef::default()
}
}
}
/// 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: 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(),
streams: Rows::default(),
viewers: Rows::default(),
pins: Rows::default(),
topics: Rows::default(),
topic_messages: Rows::default(),
qualities: Rows::default(),
no_chat: Rc::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
@@ -541,24 +540,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_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(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_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());
}
}
+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();
}
+1 -1
View File
@@ -36,7 +36,7 @@ pub(crate) fn unink(c: Color) -> Option<Rgb> {
pub(crate) fn image(picture: &ImageRef) -> Image {
match &**picture {
ImageSource::None => Image::default(),
ImageSource::File(path) => crate::images::file(path),
ImageSource::File { path, .. } => crate::images::file(path),
ImageSource::Rgba { w, h, bytes } => {
Image::from_rgba8(SharedPixelBuffer::<Rgba8Pixel>::clone_from_slice(bytes, *w, *h))
}
+366
View File
@@ -32,6 +32,12 @@ impl From<&vm::ServerItem> for ServerItem {
}
}
impl From<vm::ServerItem> for ServerItem {
fn from(v: vm::ServerItem) -> Self {
Self::from(&v)
}
}
impl Row for vm::ServerItem {
type Shown = ServerItem;
@@ -76,6 +82,12 @@ impl From<&vm::TreeItem> for TreeItem {
}
}
impl From<vm::TreeItem> for TreeItem {
fn from(v: vm::TreeItem) -> Self {
Self::from(&v)
}
}
impl Row for vm::TreeItem {
type Shown = TreeItem;
@@ -117,6 +129,12 @@ impl From<&vm::MemberItem> for MemberItem {
}
}
impl From<vm::MemberItem> for MemberItem {
fn from(v: vm::MemberItem) -> Self {
Self::from(&v)
}
}
impl Row for vm::MemberItem {
type Shown = MemberItem;
@@ -135,6 +153,12 @@ impl From<&vm::BadgeItem> for BadgeItem {
}
}
impl From<vm::BadgeItem> for BadgeItem {
fn from(v: vm::BadgeItem) -> Self {
Self::from(&v)
}
}
impl Row for vm::BadgeItem {
type Shown = BadgeItem;
@@ -168,6 +192,12 @@ impl From<&vm::MemberCard> for MemberCard {
}
}
impl From<vm::MemberCard> for MemberCard {
fn from(v: vm::MemberCard) -> Self {
Self::from(&v)
}
}
impl Row for vm::MemberCard {
type Shown = MemberCard;
@@ -193,6 +223,12 @@ impl From<&vm::ChatTab> for ChatTab {
}
}
impl From<vm::ChatTab> for ChatTab {
fn from(v: vm::ChatTab) -> Self {
Self::from(&v)
}
}
impl Row for vm::ChatTab {
type Shown = ChatTab;
@@ -219,6 +255,12 @@ impl From<&vm::TextRun> for TextRun {
}
}
impl From<vm::TextRun> for TextRun {
fn from(v: vm::TextRun) -> Self {
Self::from(&v)
}
}
impl Row for vm::TextRun {
type Shown = TextRun;
@@ -251,6 +293,12 @@ impl From<&vm::TextBlock> for TextBlock {
}
}
impl From<vm::TextBlock> for TextBlock {
fn from(v: vm::TextBlock) -> Self {
Self::from(&v)
}
}
impl Row for vm::TextBlock {
type Shown = TextBlock;
@@ -276,6 +324,12 @@ impl From<&vm::ReactionItem> for ReactionItem {
}
}
impl From<vm::ReactionItem> for ReactionItem {
fn from(v: vm::ReactionItem) -> Self {
Self::from(&v)
}
}
impl Row for vm::ReactionItem {
type Shown = ReactionItem;
@@ -309,6 +363,12 @@ impl From<&vm::FileItem> for FileItem {
}
}
impl From<vm::FileItem> for FileItem {
fn from(v: vm::FileItem) -> Self {
Self::from(&v)
}
}
impl Row for vm::FileItem {
type Shown = FileItem;
@@ -344,6 +404,12 @@ impl From<&vm::ChatLine> for ChatLine {
}
}
impl From<vm::ChatLine> for ChatLine {
fn from(v: vm::ChatLine) -> Self {
Self::from(&v)
}
}
impl Row for vm::ChatLine {
type Shown = ChatLine;
@@ -358,6 +424,12 @@ impl From<&vm::PinItem> for PinItem {
}
}
impl From<vm::PinItem> for PinItem {
fn from(v: vm::PinItem) -> Self {
Self::from(&v)
}
}
impl Row for vm::PinItem {
type Shown = PinItem;
@@ -380,6 +452,12 @@ impl From<&vm::TopicItem> for TopicItem {
}
}
impl From<vm::TopicItem> for TopicItem {
fn from(v: vm::TopicItem) -> Self {
Self::from(&v)
}
}
impl Row for vm::TopicItem {
type Shown = TopicItem;
@@ -418,6 +496,12 @@ impl From<&vm::BookmarkForm> for BookmarkForm {
}
}
impl From<vm::BookmarkForm> for BookmarkForm {
fn from(v: vm::BookmarkForm) -> Self {
Self::from(&v)
}
}
impl Row for vm::BookmarkForm {
type Shown = BookmarkForm;
@@ -464,6 +548,12 @@ impl From<&vm::StreamItem> for StreamItem {
}
}
impl From<vm::StreamItem> for StreamItem {
fn from(v: vm::StreamItem) -> Self {
Self::from(&v)
}
}
impl Row for vm::StreamItem {
type Shown = StreamItem;
@@ -484,6 +574,12 @@ impl From<&vm::ViewerItem> for ViewerItem {
}
}
impl From<vm::ViewerItem> for ViewerItem {
fn from(v: vm::ViewerItem) -> Self {
Self::from(&v)
}
}
impl Row for vm::ViewerItem {
type Shown = ViewerItem;
@@ -498,6 +594,12 @@ impl From<&vm::SourceItem> for SourceItem {
}
}
impl From<vm::SourceItem> for SourceItem {
fn from(v: vm::SourceItem) -> Self {
Self::from(&v)
}
}
impl Row for vm::SourceItem {
type Shown = SourceItem;
@@ -527,6 +629,12 @@ impl From<&vm::ShareForm> for ShareForm {
}
}
impl From<vm::ShareForm> for ShareForm {
fn from(v: vm::ShareForm) -> Self {
Self::from(&v)
}
}
impl Row for vm::ShareForm {
type Shown = ShareForm;
@@ -568,6 +676,12 @@ impl From<&vm::AudioForm> for AudioForm {
}
}
impl From<vm::AudioForm> for AudioForm {
fn from(v: vm::AudioForm) -> Self {
Self::from(&v)
}
}
impl Row for vm::AudioForm {
type Shown = AudioForm;
@@ -606,6 +720,12 @@ impl From<&vm::ClientAudio> for ClientAudio {
}
}
impl From<vm::ClientAudio> for ClientAudio {
fn from(v: vm::ClientAudio) -> Self {
Self::from(&v)
}
}
impl Row for vm::ClientAudio {
type Shown = ClientAudio;
@@ -637,6 +757,12 @@ impl From<&vm::AppearanceForm> for AppearanceForm {
}
}
impl From<vm::AppearanceForm> for AppearanceForm {
fn from(v: vm::AppearanceForm) -> Self {
Self::from(&v)
}
}
impl Row for vm::AppearanceForm {
type Shown = AppearanceForm;
@@ -682,6 +808,12 @@ impl From<&vm::ContactItem> for ContactItem {
}
}
impl From<vm::ContactItem> for ContactItem {
fn from(v: vm::ContactItem) -> Self {
Self::from(&v)
}
}
impl Row for vm::ContactItem {
type Shown = ContactItem;
@@ -710,6 +842,12 @@ impl From<&vm::LiveItem> for LiveItem {
}
}
impl From<vm::LiveItem> for LiveItem {
fn from(v: vm::LiveItem) -> Self {
Self::from(&v)
}
}
impl Row for vm::LiveItem {
type Shown = LiveItem;
@@ -738,6 +876,12 @@ impl From<&vm::ConversationItem> for ConversationItem {
}
}
impl From<vm::ConversationItem> for ConversationItem {
fn from(v: vm::ConversationItem) -> Self {
Self::from(&v)
}
}
impl Row for vm::ConversationItem {
type Shown = ConversationItem;
@@ -762,6 +906,12 @@ impl From<&vm::NoticeItem> for NoticeItem {
}
}
impl From<vm::NoticeItem> for NoticeItem {
fn from(v: vm::NoticeItem) -> Self {
Self::from(&v)
}
}
impl Row for vm::NoticeItem {
type Shown = NoticeItem;
@@ -784,6 +934,12 @@ impl From<&vm::SearchItem> for SearchItem {
}
}
impl From<vm::SearchItem> for SearchItem {
fn from(v: vm::SearchItem) -> Self {
Self::from(&v)
}
}
impl Row for vm::SearchItem {
type Shown = SearchItem;
@@ -806,6 +962,12 @@ impl From<&vm::HappeningItem> for HappeningItem {
}
}
impl From<vm::HappeningItem> for HappeningItem {
fn from(v: vm::HappeningItem) -> Self {
Self::from(&v)
}
}
impl Row for vm::HappeningItem {
type Shown = HappeningItem;
@@ -844,6 +1006,12 @@ impl From<&vm::ResumeItem> for ResumeItem {
}
}
impl From<vm::ResumeItem> for ResumeItem {
fn from(v: vm::ResumeItem) -> Self {
Self::from(&v)
}
}
impl Row for vm::ResumeItem {
type Shown = ResumeItem;
@@ -878,6 +1046,12 @@ impl From<&vm::EventItem> for EventItem {
}
}
impl From<vm::EventItem> for EventItem {
fn from(v: vm::EventItem) -> Self {
Self::from(&v)
}
}
impl Row for vm::EventItem {
type Shown = EventItem;
@@ -928,6 +1102,12 @@ impl From<&vm::EventForm> for EventForm {
}
}
impl From<vm::EventForm> for EventForm {
fn from(v: vm::EventForm) -> Self {
Self::from(&v)
}
}
impl Row for vm::EventForm {
type Shown = EventForm;
@@ -963,6 +1143,12 @@ impl From<&vm::OfflineForm> for OfflineForm {
}
}
impl From<vm::OfflineForm> for OfflineForm {
fn from(v: vm::OfflineForm) -> Self {
Self::from(&v)
}
}
impl Row for vm::OfflineForm {
type Shown = OfflineForm;
@@ -1018,6 +1204,12 @@ impl From<&vm::DmPeer> for DmPeer {
}
}
impl From<vm::DmPeer> for DmPeer {
fn from(v: vm::DmPeer) -> Self {
Self::from(&v)
}
}
impl Row for vm::DmPeer {
type Shown = DmPeer;
@@ -1043,6 +1235,12 @@ impl From<&vm::IdentityItem> for IdentityItem {
}
}
impl From<vm::IdentityItem> for IdentityItem {
fn from(v: vm::IdentityItem) -> Self {
Self::from(&v)
}
}
impl Row for vm::IdentityItem {
type Shown = IdentityItem;
@@ -1081,6 +1279,12 @@ impl From<&vm::FoundIdentity> for FoundIdentity {
}
}
impl From<vm::FoundIdentity> for FoundIdentity {
fn from(v: vm::FoundIdentity) -> Self {
Self::from(&v)
}
}
impl Row for vm::FoundIdentity {
type Shown = FoundIdentity;
@@ -1108,6 +1312,12 @@ impl From<&vm::BookmarkIdentity> for BookmarkIdentity {
}
}
impl From<vm::BookmarkIdentity> for BookmarkIdentity {
fn from(v: vm::BookmarkIdentity) -> Self {
Self::from(&v)
}
}
impl Row for vm::BookmarkIdentity {
type Shown = BookmarkIdentity;
@@ -1140,6 +1350,12 @@ impl From<&vm::VideoForm> for VideoForm {
}
}
impl From<vm::VideoForm> for VideoForm {
fn from(v: vm::VideoForm) -> Self {
Self::from(&v)
}
}
impl Row for vm::VideoForm {
type Shown = VideoForm;
@@ -1178,6 +1394,12 @@ impl From<&vm::LayerItem> for LayerItem {
}
}
impl From<vm::LayerItem> for LayerItem {
fn from(v: vm::LayerItem) -> Self {
Self::from(&v)
}
}
impl Row for vm::LayerItem {
type Shown = LayerItem;
@@ -1210,6 +1432,12 @@ impl From<&vm::AudioSourceItem> for AudioSourceItem {
}
}
impl From<vm::AudioSourceItem> for AudioSourceItem {
fn from(v: vm::AudioSourceItem) -> Self {
Self::from(&v)
}
}
impl Row for vm::AudioSourceItem {
type Shown = AudioSourceItem;
@@ -1244,6 +1472,12 @@ impl From<&vm::StreamingForm> for StreamingForm {
}
}
impl From<vm::StreamingForm> for StreamingForm {
fn from(v: vm::StreamingForm) -> Self {
Self::from(&v)
}
}
impl Row for vm::StreamingForm {
type Shown = StreamingForm;
@@ -1278,6 +1512,12 @@ impl From<&vm::NotifyForm> for NotifyForm {
}
}
impl From<vm::NotifyForm> for NotifyForm {
fn from(v: vm::NotifyForm) -> Self {
Self::from(&v)
}
}
impl Row for vm::NotifyForm {
type Shown = NotifyForm;
@@ -1304,6 +1544,12 @@ impl From<&vm::PrivacyForm> for PrivacyForm {
}
}
impl From<vm::PrivacyForm> for PrivacyForm {
fn from(v: vm::PrivacyForm) -> Self {
Self::from(&v)
}
}
impl Row for vm::PrivacyForm {
type Shown = PrivacyForm;
@@ -1331,6 +1577,12 @@ impl From<&vm::GatewayItem> for GatewayItem {
}
}
impl From<vm::GatewayItem> for GatewayItem {
fn from(v: vm::GatewayItem) -> Self {
Self::from(&v)
}
}
impl Row for vm::GatewayItem {
type Shown = GatewayItem;
@@ -1365,6 +1617,12 @@ impl From<&vm::ConfigItem> for ConfigItem {
}
}
impl From<vm::ConfigItem> for ConfigItem {
fn from(v: vm::ConfigItem) -> Self {
Self::from(&v)
}
}
impl Row for vm::ConfigItem {
type Shown = ConfigItem;
@@ -1399,6 +1657,12 @@ impl From<&vm::PermItem> for PermItem {
}
}
impl From<vm::PermItem> for PermItem {
fn from(v: vm::PermItem) -> Self {
Self::from(&v)
}
}
impl Row for vm::PermItem {
type Shown = PermItem;
@@ -1433,6 +1697,12 @@ impl From<&vm::EncoderItem> for EncoderItem {
}
}
impl From<vm::EncoderItem> for EncoderItem {
fn from(v: vm::EncoderItem) -> Self {
Self::from(&v)
}
}
impl Row for vm::EncoderItem {
type Shown = EncoderItem;
@@ -1465,6 +1735,12 @@ impl From<&vm::SettingItem> for SettingItem {
}
}
impl From<vm::SettingItem> for SettingItem {
fn from(v: vm::SettingItem) -> Self {
Self::from(&v)
}
}
impl Row for vm::SettingItem {
type Shown = SettingItem;
@@ -1495,6 +1771,12 @@ impl From<&vm::RecordingItem> for RecordingItem {
}
}
impl From<vm::RecordingItem> for RecordingItem {
fn from(v: vm::RecordingItem) -> Self {
Self::from(&v)
}
}
impl Row for vm::RecordingItem {
type Shown = RecordingItem;
@@ -1535,6 +1817,12 @@ impl From<&vm::AdvancedForm> for AdvancedForm {
}
}
impl From<vm::AdvancedForm> for AdvancedForm {
fn from(v: vm::AdvancedForm) -> Self {
Self::from(&v)
}
}
impl Row for vm::AdvancedForm {
type Shown = AdvancedForm;
@@ -1577,6 +1865,12 @@ impl From<&vm::AccountForm> for AccountForm {
}
}
impl From<vm::AccountForm> for AccountForm {
fn from(v: vm::AccountForm) -> Self {
Self::from(&v)
}
}
impl Row for vm::AccountForm {
type Shown = AccountForm;
@@ -1608,6 +1902,12 @@ impl From<&vm::EmojiCell> for EmojiCell {
}
}
impl From<vm::EmojiCell> for EmojiCell {
fn from(v: vm::EmojiCell) -> Self {
Self::from(&v)
}
}
impl Row for vm::EmojiCell {
type Shown = EmojiCell;
@@ -1632,6 +1932,12 @@ impl From<&vm::EmojiRow> for EmojiRow {
}
}
impl From<vm::EmojiRow> for EmojiRow {
fn from(v: vm::EmojiRow) -> Self {
Self::from(&v)
}
}
impl Row for vm::EmojiRow {
type Shown = EmojiRow;
@@ -1658,6 +1964,12 @@ impl From<&studio::StudioScene> for StudioScene {
}
}
impl From<studio::StudioScene> for StudioScene {
fn from(v: studio::StudioScene) -> Self {
Self::from(&v)
}
}
impl Row for studio::StudioScene {
type Shown = StudioScene;
@@ -1695,6 +2007,12 @@ impl From<&studio::StudioSource> for StudioSource {
}
}
impl From<studio::StudioSource> for StudioSource {
fn from(v: studio::StudioSource) -> Self {
Self::from(&v)
}
}
impl Row for studio::StudioSource {
type Shown = StudioSource;
@@ -1734,6 +2052,12 @@ impl From<&studio::StudioAudio> for StudioAudio {
}
}
impl From<studio::StudioAudio> for StudioAudio {
fn from(v: studio::StudioAudio) -> Self {
Self::from(&v)
}
}
impl Row for studio::StudioAudio {
type Shown = StudioAudio;
@@ -1768,6 +2092,12 @@ impl From<&studio::StudioLayer> for StudioLayer {
}
}
impl From<studio::StudioLayer> for StudioLayer {
fn from(v: studio::StudioLayer) -> Self {
Self::from(&v)
}
}
impl Row for studio::StudioLayer {
type Shown = StudioLayer;
@@ -1798,6 +2128,12 @@ impl From<&studio::StudioViewer> for StudioViewer {
}
}
impl From<studio::StudioViewer> for StudioViewer {
fn from(v: studio::StudioViewer) -> Self {
Self::from(&v)
}
}
impl Row for studio::StudioViewer {
type Shown = StudioViewer;
@@ -1828,6 +2164,12 @@ impl From<&studio::StudioPick> for StudioPick {
}
}
impl From<studio::StudioPick> for StudioPick {
fn from(v: studio::StudioPick) -> Self {
Self::from(&v)
}
}
impl Row for studio::StudioPick {
type Shown = StudioPick;
@@ -1868,6 +2210,12 @@ impl From<&studio::StudioStatus> for StudioStatus {
}
}
impl From<studio::StudioStatus> for StudioStatus {
fn from(v: studio::StudioStatus) -> Self {
Self::from(&v)
}
}
impl Row for studio::StudioStatus {
type Shown = StudioStatus;
@@ -1924,6 +2272,12 @@ impl From<&studio::StudioForm> for StudioForm {
}
}
impl From<studio::StudioForm> for StudioForm {
fn from(v: studio::StudioForm) -> Self {
Self::from(&v)
}
}
impl Row for studio::StudioForm {
type Shown = StudioForm;
@@ -1980,6 +2334,12 @@ impl From<&studio::StudioSourceForm> for StudioSourceForm {
}
}
impl From<studio::StudioSourceForm> for StudioSourceForm {
fn from(v: studio::StudioSourceForm) -> Self {
Self::from(&v)
}
}
impl Row for studio::StudioSourceForm {
type Shown = StudioSourceForm;
@@ -2032,6 +2392,12 @@ impl From<&studio::StudioSettingsForm> for StudioSettingsForm {
}
}
impl From<studio::StudioSettingsForm> for StudioSettingsForm {
fn from(v: studio::StudioSettingsForm) -> Self {
Self::from(&v)
}
}
impl Row for studio::StudioSettingsForm {
type Shown = StudioSettingsForm;
+7 -7
View File
@@ -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));
+26 -1
View File
@@ -4,7 +4,7 @@
//! `VecModel` (views redraw only the rows that changed: a client that
//! starts talking is one `set_row_data`).
use std::cell::RefCell;
use std::cell::{Ref, RefCell};
use std::rc::Rc;
use std::sync::Arc;
@@ -48,6 +48,31 @@ impl<T: Row> Rows<T> {
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();
+8 -4
View File
@@ -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.
+2 -2
View File
@@ -13,7 +13,7 @@ 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));
@@ -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| {
+14 -16
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,10 +30,11 @@ 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, Msg, 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};
/// Where the server's welcome and host message keep what their lines were
@@ -466,14 +467,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 +521,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 +533,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);
}
@@ -586,14 +584,14 @@ impl App {
}
})
.collect();
vm::list::sync(&self.models.pins, &pins);
self.models.pins.sync(&pins);
let filter = self.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 +607,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 +616,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
+8 -12
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)]
@@ -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();
+19 -17
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 {
@@ -205,27 +208,26 @@ 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).
@@ -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(),
+7 -8
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};
@@ -45,7 +44,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,
@@ -184,9 +183,9 @@ 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
@@ -253,7 +252,7 @@ impl App {
icon: server.icon.clone(),
channel: resume.title().into(),
open: resume.action == ResumeAction::Open,
connecting: server.status == "connecting",
connecting: &*server.status == "connecting",
}
}
@@ -304,7 +303,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());
}
+2 -4
View File
@@ -18,17 +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 Twemoji archive and text splitting live with the view models.
use voelin_ui_vm::emoji;
// 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};
+1 -1
View File
@@ -64,7 +64,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);
}
}
+8 -5
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.
@@ -46,7 +49,7 @@ impl App {
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 groups: Vec<Arc<str>> = client
.server_groups
.iter()
.filter_map(|g| view.server_groups.iter().find(|i| i.id == *g))
@@ -62,8 +65,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,7 +78,7 @@ 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".
+74 -76
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 {
@@ -202,9 +191,9 @@ impl App {
|| 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 +247,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 +256,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 +275,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 +285,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 +293,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);
}
@@ -463,7 +452,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 +494,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,7 +515,7 @@ 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();
@@ -554,7 +543,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 +552,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 +627,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.
@@ -850,7 +848,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()
+7 -4
View File
@@ -9,14 +9,17 @@
//! 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_model::{ChatTarget, FileRef};
use crate::app::{App, SessionView};
use crate::bind::convert;
use crate::settings::UI_IMAGE_PREVIEW_KB;
use crate::vm;
use crate::vm::{ImageRef, ImageSource};
/// A linked picture.
#[derive(Clone, Debug)]
@@ -47,12 +50,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,
}
@@ -188,7 +191,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))
+22 -16
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.
@@ -427,7 +429,7 @@ 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
.sessions
.get(&bookmark.id)
@@ -441,7 +443,7 @@ impl App {
}
/// A server's colour, as the rail shows it ([`vm::servers::tints`]).
pub(crate) fn server_tint(&self, id: i64) -> slint::Color {
pub(crate) fn server_tint(&self, id: i64) -> vm::Rgb {
let tints = vm::servers::tints(&self.bookmarks);
self.bookmarks.iter().position(|b| b.id == id).map(|i| tints[i]).unwrap_or_default()
}
@@ -471,8 +473,8 @@ 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));
self.models.servers.sync(&items);
bridge.set_last_place(self.last_place(&items).into());
bridge.set_current_server(self.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));
@@ -486,7 +488,9 @@ impl App {
let bookmark = self.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(),
);
@@ -500,12 +504,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)));
@@ -515,8 +520,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)),
);
@@ -548,9 +554,9 @@ 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 {
@@ -567,10 +573,10 @@ 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();
@@ -579,7 +585,7 @@ impl App {
let filter = self.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);
-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);
}
}
+13 -9
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) {
@@ -35,7 +36,7 @@ impl App {
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_audio(settings::audio_form(&self.audio, &self.inputs, &self.outputs).into());
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);
@@ -214,13 +215,16 @@ impl App {
info.uid.as_ref().and_then(|uid| self.playback.get(uid)).copied().unwrap_or_default();
self.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
}
+109 -92
View File
@@ -27,17 +27,19 @@ use voelin_core::settings::{
use voelin_core::{Command, GatewayRequest};
use voelin_gateway_proto::{Action, ConfigSource, PermRule, UniqueIds, feature};
use crate::app::{
AccountForm, AdvancedForm, App, AudioSourceItem, BookmarkIdentity, Bridge, ConfigItem,
EncoderItem, FoundIdentity, GatewayItem, IdentityItem, LayerItem, NotifyForm, PermItem,
PrivacyForm, SettingItem, StreamingForm, VideoForm, later, model,
};
use crate::app::{App, Bridge, later, model};
use crate::bind::convert;
use crate::settings::{
NOTIFY_EVENTS, NOTIFY_FRIENDS, NOTIFY_MENTIONS, NOTIFY_MESSAGES, NOTIFY_POKES, NotifyLevel,
UI_IMAGE_PREVIEW_KB, VIDEO_BACKGROUND, VIDEO_CAMERA, VIDEO_MIRROR, VIDEO_RESOLUTION, page_keys,
parse_size,
};
use crate::social::{allowed_index, allowed_of};
use crate::vm::bridge::{
AccountForm, AdvancedForm, AudioSourceItem, BookmarkIdentity, ConfigItem, EncoderItem,
FoundIdentity, GatewayItem, IdentityItem, LayerItem, NotifyForm, PermItem, PrivacyForm,
SettingItem, StreamingForm, VideoForm,
};
/// Sizes of the stream quality presets (Auto: the source's size).
const PRESETS: [(u32, u32); 5] =
@@ -256,61 +258,70 @@ impl App {
let p = &self.prefs;
let layers = p.get(&STREAM_LAYERS);
let camera = p.get(&VIDEO_CAMERA);
bridge.set_video(VideoForm {
camera: self.pages.cameras.iter().position(|c| *c == camera).unwrap_or(0) as i32,
background: i32::from(p.get(&VIDEO_BACKGROUND) == "blur"),
resolution: p.get(&VIDEO_RESOLUTION).into(),
fps: p.get(&STREAM_FPS).to_string().into(),
codec: codec_index(p.get(&STREAM_CODEC)),
hardware: p.get(&STREAM_HARDWARE_ACCELERATION),
mirror: p.get(&VIDEO_MIRROR),
permissions: match p.get(&STREAM_PERMISSIONS) {
StreamPermissions::Everyone => 0,
StreamPermissions::Friends => 1,
StreamPermissions::Channel => 2,
StreamPermissions::Nobody => 3,
},
quality: quality_of(&layers),
bitrate: p.get(&STREAM_BITRATE_KBPS) as f32,
preview: self.pages.camera.is_some(),
});
bridge.set_streaming(StreamingForm {
fps: p.get(&STREAM_FPS).to_string().into(),
bitrate: p.get(&STREAM_BITRATE_KBPS).to_string().into(),
codec: codec_index(p.get(&STREAM_CODEC)),
capture: match p.get(&STREAM_CAPTURE_BACKEND) {
CaptureChoice::Auto => 0,
CaptureChoice::Portal => 1,
CaptureChoice::Wlroots => 2,
CaptureChoice::X11 => 3,
},
replay_seconds: p.get(&STUDIO_REPLAY_SECONDS).to_string().into(),
replay_memory: p.get(&STUDIO_REPLAY_MEMORY_MB).to_string().into(),
recording_dir: p.get(&STUDIO_RECORDING_DIR).into(),
});
crate::vm::list::sync(
&self.models.layers,
&layers.iter().map(layer_item).collect::<Vec<_>>(),
bridge.set_video(
VideoForm {
camera: self.pages.cameras.iter().position(|c| *c == camera).unwrap_or(0) as i32,
background: i32::from(p.get(&VIDEO_BACKGROUND) == "blur"),
resolution: p.get(&VIDEO_RESOLUTION).into(),
fps: p.get(&STREAM_FPS).to_string().into(),
codec: codec_index(p.get(&STREAM_CODEC)),
hardware: p.get(&STREAM_HARDWARE_ACCELERATION),
mirror: p.get(&VIDEO_MIRROR),
permissions: match p.get(&STREAM_PERMISSIONS) {
StreamPermissions::Everyone => 0,
StreamPermissions::Friends => 1,
StreamPermissions::Channel => 2,
StreamPermissions::Nobody => 3,
},
quality: quality_of(&layers),
bitrate: p.get(&STREAM_BITRATE_KBPS) as f32,
preview: self.pages.camera.is_some(),
}
.into(),
);
bridge.set_streaming(
StreamingForm {
fps: p.get(&STREAM_FPS).to_string().into(),
bitrate: p.get(&STREAM_BITRATE_KBPS).to_string().into(),
codec: codec_index(p.get(&STREAM_CODEC)),
capture: match p.get(&STREAM_CAPTURE_BACKEND) {
CaptureChoice::Auto => 0,
CaptureChoice::Portal => 1,
CaptureChoice::Wlroots => 2,
CaptureChoice::X11 => 3,
},
replay_seconds: p.get(&STUDIO_REPLAY_SECONDS).to_string().into(),
replay_memory: p.get(&STUDIO_REPLAY_MEMORY_MB).to_string().into(),
recording_dir: p.get(&STUDIO_RECORDING_DIR).into(),
}
.into(),
);
self.models.layers.sync(&layers.iter().map(layer_item).collect::<Vec<_>>());
let sources: Vec<AudioSourceItem> = p
.get(&STREAM_AUDIO_SOURCES)
.iter()
.map(|s| source_item(s, voelin_platform::APP_NAME))
.collect();
crate::vm::list::sync(&self.models.audio_sources, &sources);
self.models.audio_sources.sync(&sources);
bridge.set_has_studio(true);
bridge.set_notify(NotifyForm {
mentions: p.get(&NOTIFY_MENTIONS).index(),
pokes: p.get(&NOTIFY_POKES).index(),
messages: p.get(&NOTIFY_MESSAGES).index(),
events: p.get(&NOTIFY_EVENTS).index(),
friends: p.get(&NOTIFY_FRIENDS).index(),
});
bridge.set_privacy(PrivacyForm {
block_mode: i32::from(p.get(&PRIVACY_BLOCK_MODE) == BlockMode::Flag),
messages: allowed_index(p.get(&PRIVACY_PRIVATE_MESSAGES)),
pokes: allowed_index(p.get(&PRIVACY_POKES)),
});
bridge.set_notify(
NotifyForm {
mentions: p.get(&NOTIFY_MENTIONS).index(),
pokes: p.get(&NOTIFY_POKES).index(),
messages: p.get(&NOTIFY_MESSAGES).index(),
events: p.get(&NOTIFY_EVENTS).index(),
friends: p.get(&NOTIFY_FRIENDS).index(),
}
.into(),
);
bridge.set_privacy(
PrivacyForm {
block_mode: i32::from(p.get(&PRIVACY_BLOCK_MODE) == BlockMode::Flag),
messages: allowed_index(p.get(&PRIVACY_PRIVATE_MESSAGES)),
pokes: allowed_index(p.get(&PRIVACY_POKES)),
}
.into(),
);
let srtp = p.get(&STREAM_SRTP_PROFILES);
bridge.set_srtp_profiles(model(srtp.iter().map(SharedString::from).collect()));
bridge.set_srtp_unused(model(
@@ -320,25 +331,28 @@ impl App {
.map(|n| SharedString::from(*n))
.collect(),
));
bridge.set_advanced(AdvancedForm {
encoder: p.get(&STREAM_ENCODER_BACKEND).into(),
hardware: p.get(&STREAM_HARDWARE_ACCELERATION),
decoder: p.get(&STREAM_DECODER_BACKEND).into(),
hardware_decoding: p.get(&STREAM_HARDWARE_DECODING),
store_history: p.get(&CHAT_STORE_HISTORY),
history_page: p.get(&CHAT_HISTORY_PAGE).to_string().into(),
dedupe_ms: p.get(&CHAT_DEDUPE_TOLERANCE_MS).to_string().into(),
retention_days: p.get(&CHAT_RETENTION_DAYS).to_string().into(),
cache_mb: p.get(&CACHE_MAX_MB).to_string().into(),
fetch_images: p.get(&CACHE_FETCH_IMAGES),
progress_ms: p.get(&FILES_PROGRESS_MS).to_string().into(),
preview_kb: p.get(&UI_IMAGE_PREVIEW_KB).to_string().into(),
logs: log_text().into(),
crash_dir: voelin_platform::crash::dir()
.map(|d| d.display().to_string())
.unwrap_or_default()
.into(),
});
bridge.set_advanced(
AdvancedForm {
encoder: p.get(&STREAM_ENCODER_BACKEND).into(),
hardware: p.get(&STREAM_HARDWARE_ACCELERATION),
decoder: p.get(&STREAM_DECODER_BACKEND).into(),
hardware_decoding: p.get(&STREAM_HARDWARE_DECODING),
store_history: p.get(&CHAT_STORE_HISTORY),
history_page: p.get(&CHAT_HISTORY_PAGE).to_string().into(),
dedupe_ms: p.get(&CHAT_DEDUPE_TOLERANCE_MS).to_string().into(),
retention_days: p.get(&CHAT_RETENTION_DAYS).to_string().into(),
cache_mb: p.get(&CACHE_MAX_MB).to_string().into(),
fetch_images: p.get(&CACHE_FETCH_IMAGES),
progress_ms: p.get(&FILES_PROGRESS_MS).to_string().into(),
preview_kb: p.get(&UI_IMAGE_PREVIEW_KB).to_string().into(),
logs: log_text().into(),
crash_dir: voelin_platform::crash::dir()
.map(|d| d.display().to_string())
.unwrap_or_default()
.into(),
}
.into(),
);
self.refresh_account();
}
@@ -380,7 +394,7 @@ impl App {
self.engine.send(Command::SetSrtpProfiles(profiles.to_vec()));
}
pub(crate) fn video_changed(&mut self, form: &crate::app::VideoForm) {
pub(crate) fn video_changed(&mut self, form: &crate::vm::bridge::VideoForm) {
if let Some(id) =
usize::try_from(form.camera).ok().and_then(|i| self.pages.cameras.get(i)).cloned()
&& self.prefs.get(&VIDEO_CAMERA) != id
@@ -391,7 +405,7 @@ impl App {
if self.prefs.get(&VIDEO_BACKGROUND) != background {
self.put(&VIDEO_BACKGROUND, background.to_owned());
}
if self.prefs.get(&VIDEO_RESOLUTION) != form.resolution.as_str() {
if self.prefs.get(&VIDEO_RESOLUTION) != form.resolution.as_ref() {
self.put(&VIDEO_RESOLUTION, form.resolution.to_string());
}
if let Some(fps) = crate::settings::parse_positive(&form.fps)
@@ -601,7 +615,7 @@ impl App {
}
pub(crate) fn advanced_changed(&mut self, form: &AdvancedForm) {
let number = |t: &SharedString| t.trim().parse::<u64>().ok();
let number = |t: &Arc<str>| t.trim().parse::<u64>().ok();
if !form.encoder.trim().is_empty() {
self.put(&STREAM_ENCODER_BACKEND, form.encoder.trim().to_owned());
}
@@ -690,7 +704,7 @@ impl App {
.into(),
})
.collect();
crate::vm::list::sync(&self.models.all_settings, &items);
self.models.all_settings.sync(&items);
}
pub(crate) fn search_settings(&mut self, text: String) {
@@ -755,11 +769,11 @@ impl App {
url: url.into(),
status: status.into(),
admin: caps.iter().any(|c| c == feature::ADMIN),
features: model(caps.into_iter().map(SharedString::from).collect()),
features: caps.into_iter().map(Arc::<str>::from).collect(),
})
})
.collect();
bridge.set_gateways(model(items));
bridge.set_gateways(convert::model(&items));
bridge.set_admin_session(self.pages.admin.map_or(-1, |s| s as i32));
let extra = self.pages.admin.and_then(|s| self.sessions.get(&s)).map(|v| &v.extra);
let config: Vec<ConfigItem> = extra
@@ -777,7 +791,7 @@ impl App {
.collect()
})
.unwrap_or_default();
crate::vm::list::sync(&self.models.gateway_config, &config);
self.models.gateway_config.sync(&config);
let perms: Vec<PermItem> = extra
.map(|e| {
e.perms
@@ -803,7 +817,7 @@ impl App {
.collect()
})
.unwrap_or_default();
crate::vm::list::sync(&self.models.gateway_perms, &perms);
self.models.gateway_perms.sync(&perms);
}
/// Administer a gateway (`-1`: close).
@@ -907,7 +921,7 @@ impl App {
.into(),
})
.collect();
model(items)
convert::model(&items)
};
bridge.set_encoders(items(&report.encoders));
bridge.set_decoders(items(&report.decoders));
@@ -984,14 +998,17 @@ impl App {
.find(|e| Some(e.id) == entry_id)
.map(|e| e.name)
.unwrap_or_default();
bridge.set_account(AccountForm {
nickname: bookmark.map(|b| b.nickname.clone()).unwrap_or_default().into(),
identity: name.into(),
uid: ids.ts3.into(),
uid6: ids.ts6.into(),
level: i32::from(identity.level()),
server: bookmark.map(|b| b.name.clone()).unwrap_or_default().into(),
});
bridge.set_account(
AccountForm {
nickname: bookmark.map(|b| b.nickname.clone()).unwrap_or_default().into(),
identity: name.into(),
uid: ids.ts3.into(),
uid6: ids.ts6.into(),
level: i32::from(identity.level()),
server: bookmark.map(|b| b.name.clone()).unwrap_or_default().into(),
}
.into(),
);
}
/// The identities, the bookmarks' choices, what an import found.
@@ -1031,7 +1048,7 @@ impl App {
}
})
.collect();
crate::vm::list::sync(&self.models.identities, &items);
self.models.identities.sync(&items);
let mut names = vec![SharedString::from("Default identity")];
names.extend(entries.iter().map(|e| SharedString::from(e.name.as_str())));
bridge.set_identity_names(model(names));
@@ -1047,7 +1064,7 @@ impl App {
.map_or(0, |i| i as i32 + 1),
})
.collect();
bridge.set_bookmark_identities(model(choices));
bridge.set_bookmark_identities(convert::model(&choices));
let known: std::collections::HashSet<&str> =
entries.iter().map(|e| e.uid.as_str()).collect();
let found: Vec<FoundIdentity> = self
@@ -1066,7 +1083,7 @@ impl App {
}
})
.collect();
bridge.set_found_identities(model(found));
bridge.set_found_identities(convert::model(&found));
bridge.set_identity_import(self.prefs.get(&IDENTITY_IMPORT));
self.refresh_account();
}
+70 -72
View File
@@ -8,10 +8,9 @@
//! [`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,
@@ -21,14 +20,13 @@ use voelin_gateway_proto::{
};
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.
@@ -164,57 +162,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,7 +269,7 @@ 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 {
pub(crate) fn avatar_of(&self, uid: &str) -> vm::ImageRef {
vm::avatar::image(self.sessions.values().find_map(|v| v.avatars.get(uid)))
}
@@ -370,7 +368,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 +395,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 +405,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())
});
}
@@ -420,22 +418,22 @@ impl App {
self.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.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 +441,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) {
@@ -653,14 +651,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);
}
@@ -1069,7 +1067,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.
+11 -14
View File
@@ -16,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 {
@@ -363,7 +363,7 @@ 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);
@@ -398,9 +398,9 @@ 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()),
@@ -456,10 +456,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)?)?;
@@ -483,9 +480,9 @@ impl App {
bridge.set_viewer_volume(self.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());
@@ -576,7 +573,7 @@ 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.
+51 -51
View File
@@ -9,17 +9,16 @@
//! The studio runs while it is shown, live or recording.
//!
//! Both windows' StudioBridge globals show the same models (shared
//! VecModels) and get the same values; their callbacks come here
//! rows) and get the same values; their callbacks come here
//! (bind/studio.rs). Commands go to the studio through one task, in order.
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Weak};
use std::time::Duration;
use serde::{Deserialize, Serialize};
use slint::{ComponentHandle, Model, ModelRc, Rgba8Pixel, SharedPixelBuffer, VecModel};
use slint::{ComponentHandle, Rgba8Pixel, SharedPixelBuffer};
use tokio::sync::broadcast::error::RecvError;
use tokio::sync::{broadcast, mpsc};
use tracing::warn;
@@ -47,15 +46,17 @@ use voelin_core::{Command, HistoryMessage, HistorySource, StreamState};
use voelin_model::{ChatMessage, ChatTarget};
use voelin_store::MessageSource;
use crate::app::{
App, ChatLine, Nav, Page, StudioAudio, StudioBridge, StudioForm, StudioLayer, StudioNav,
StudioPick, StudioScene, StudioSettingsForm, StudioSource, StudioSourceForm, StudioStatus,
StudioViewer, StudioWindow, later, with_app,
};
use crate::app::{App, Nav, Page, StudioBridge, StudioNav, StudioWindow, later, with_app};
use crate::bind::rows::Rows;
use crate::settings::parse_positive;
use crate::video::CaptureRequest;
use crate::vm;
use crate::vm::bridge::ChatLine;
use crate::vm::studio::{OVERLAY_CHAT, OVERLAY_NOW_PLAYING, OVERLAY_VIEWERS, Overlay};
use crate::vm::studio_bridge::{
StudioForm, StudioLayer, StudioPick, StudioSettingsForm, StudioSourceForm, StudioStatus,
StudioViewer,
};
type Picture = SharedPixelBuffer<Rgba8Pixel>;
@@ -106,15 +107,15 @@ impl Default for StudioUi {
/// The models both windows show.
#[derive(Default)]
struct Models {
scenes: Rc<VecModel<StudioScene>>,
sources: Rc<VecModel<StudioSource>>,
audio: Rc<VecModel<StudioAudio>>,
layers: Rc<VecModel<StudioLayer>>,
viewers: Rc<VecModel<StudioViewer>>,
destinations: Rc<VecModel<StudioPick>>,
picks: Rc<VecModel<StudioPick>>,
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: Rc<VecModel<ChatLine>>,
chat: Rows<vm::bridge::ChatLine>,
}
/// What a picker row adds.
@@ -489,14 +490,14 @@ impl App {
fn studio_attach(&self, bridge: &StudioBridge) {
let m = &self.studio.models;
bridge.set_scenes(ModelRc::from(m.scenes.clone()));
bridge.set_sources(ModelRc::from(m.sources.clone()));
bridge.set_audio(ModelRc::from(m.audio.clone()));
bridge.set_layers(ModelRc::from(m.layers.clone()));
bridge.set_viewers(ModelRc::from(m.viewers.clone()));
bridge.set_destinations(ModelRc::from(m.destinations.clone()));
bridge.set_picks(ModelRc::from(m.picks.clone()));
bridge.set_chat(ModelRc::from(m.chat.clone()));
bridge.set_scenes(m.scenes.model());
bridge.set_sources(m.sources.model());
bridge.set_audio(m.audio.model());
bridge.set_layers(m.layers.model());
bridge.set_viewers(m.viewers.model());
bridge.set_destinations(m.destinations.model());
bridge.set_picks(m.picks.model());
bridge.set_chat(m.chat.model());
}
/// Whether a studio page or window is on screen.
@@ -753,9 +754,9 @@ impl App {
fn studio_refresh_scenes(&self) {
let m = &self.studio.models;
vm::list::sync(&m.scenes, &vm::studio::scenes(&self.studio.scenes));
m.scenes.sync(&vm::studio::scenes(&self.studio.scenes));
let stats = self.studio.stats.as_ref().map_or(&[][..], |s| &s.sources[..]);
vm::list::sync(&m.sources, &vm::studio::sources(self.studio.scenes.active(), stats));
m.sources.sync(&vm::studio::sources(self.studio.scenes.active(), stats));
}
/// The streamer whose mixer the audio rows show: a quick share's while
@@ -801,7 +802,7 @@ impl App {
Some(vm::studio::AudioLive { level: level.max(-100.0), error })
})
.collect();
vm::list::sync(&self.studio.models.audio, &vm::studio::audio(&sources, &live));
self.studio.models.audio.sync(&vm::studio::audio(&sources, &live));
}
/// The share dialog's audio: the studio's mixer rows and picker in the
@@ -839,21 +840,18 @@ impl App {
let model = &self.studio.models.audio;
for (i, meter) in self.studio.meters.iter().enumerate() {
let level = meter.as_ref().map_or(-100.0, |m| m.level().peak_db().max(-100.0));
if let Some(mut row) = model.row_data(i)
if let Some(mut row) = model.get(i)
&& (row.level - level).abs() >= 0.5
{
row.level = level;
model.set_row_data(i, row);
model.set(i, row);
}
}
}
fn studio_refresh_layers(&mut self) {
let settings = self.studio_settings();
vm::list::sync(
&self.studio.models.layers,
&vm::studio::layers(&settings.get(&STREAM_LAYERS)),
);
self.studio.models.layers.sync(&vm::studio::layers(&settings.get(&STREAM_LAYERS)));
}
/// Sessions the stream can go to: TeamSpeak 6 with voice, the current
@@ -912,7 +910,7 @@ impl App {
}
})
.collect();
vm::list::sync(&self.studio.models.destinations, &rows);
self.studio.models.destinations.sync(&rows);
self.studio_bind_chat();
self.studio_refresh_form();
}
@@ -964,10 +962,10 @@ impl App {
let lines: Vec<ChatLine> = match tab {
Some((view, tab)) if view.has_history() => self.lines_of(view, tab, true),
// Without stored history the tab's lines are pushed as they come.
Some((_, tab)) => tab.lines.iter().collect(),
Some((_, tab)) => tab.lines.rows().to_vec(),
None => Vec::new(),
};
vm::list::sync(&self.studio.models.chat, &lines);
self.studio.models.chat.sync(&lines);
}
/// A chat of session `id` changed (chat.rs): follow it if it is the
@@ -1005,9 +1003,10 @@ impl App {
audio: ui.audio,
bitrate: bitrate.into(),
};
let shown = crate::app::StudioForm::from(&form);
self.studio_each(|b| {
if b.get_form() != form {
b.set_form(form.clone());
if b.get_form() != shown {
b.set_form(shown.clone());
}
});
}
@@ -1137,10 +1136,11 @@ impl App {
state: "requested".into(),
})
.collect();
vm::list::sync(&self.studio.models.viewers, &requests);
self.studio.models.viewers.sync(&requests);
let shown = crate::app::StudioStatus::from(&status);
self.studio_each(|b| {
if b.get_status() != status {
b.set_status(status.clone());
if b.get_status() != shown {
b.set_status(shown.clone());
}
});
}
@@ -1180,10 +1180,10 @@ impl App {
/// The last lines of the stream's chat, for the chat overlay.
fn studio_chat_tail(&self, lines: usize) -> Option<String> {
let chat = &self.studio.models.chat;
let count = chat.row_count();
let text: Vec<String> = (count.saturating_sub(lines)..count)
.filter_map(|i| chat.row_data(i))
let chat = self.studio.models.chat.rows();
let count = chat.len();
let text: Vec<String> = chat[count.saturating_sub(lines)..]
.iter()
.map(|l| {
let line = format!("{}: {}", l.author, l.text);
match line.char_indices().nth(64) {
@@ -1535,7 +1535,7 @@ impl App {
fn studio_set_picks(&mut self, picks: Vec<(Pick, StudioPick)>) {
let rows: Vec<StudioPick> = picks.iter().map(|(_, row)| row.clone()).collect();
self.studio.picks = picks.into_iter().map(|(pick, _)| pick).collect();
vm::list::sync(&self.studio.models.picks, &rows);
self.studio.models.picks.sync(&rows);
}
/// What a screen, window or camera source can show. False when there is
@@ -1717,7 +1717,7 @@ impl App {
icon: icon
.map(Path::new)
.filter(|p| p.is_absolute())
.map(crate::images::file)
.map(vm::ImageSource::file)
.unwrap_or_default(),
selected: current.iter().any(|s| s.kind == setting.kind),
};
@@ -1805,9 +1805,9 @@ impl App {
meter.set_gain(gain);
}
let model = &self.studio.models.audio;
if let Some(mut row) = model.row_data(index) {
if let Some(mut row) = model.get(index) {
row.gain_db = db;
model.set_row_data(index, row);
model.set(index, row);
}
if done {
self.studio_audio_sources(|sources| {
@@ -2179,7 +2179,7 @@ impl App {
self.studio.scenes.active().and_then(|s| s.sources.first()).map(|s| s.id);
let form = front.map(|id| self.studio_source_form(id)).unwrap_or_default();
self.studio_nav(|nav| {
nav.set_source_form(form);
nav.set_source_form(form.into());
nav.set_dialog("source".into());
});
}
@@ -2206,7 +2206,7 @@ impl App {
"settings" => {
let form = self.studio_settings_form();
self.studio_nav(|nav| {
nav.set_settings_form(form);
nav.set_settings_form(form.into());
nav.set_dialog("settings".into());
});
}
-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
-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 use voelin_ui_vm::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);
}
}