Files
VoelinClient/crates/voelin-ui-vm/src/host.rs
T
faumarayandClaude Fable 5.1 785bbd050b docs: the three minors of the Opus gate of phase5/ui-vm-2
docs/ui.md: the app.rs row of the step-3 table points the toolbar and
tree refreshes at servers/bind.rs, where they live; app.rs only calls them.
voelin-ui-vm host.rs: the doc of Update::rest matches the events module
(the Studio's stream, a changed setting, the offline-message answers; the
watched and shared streams are state and go through the stream effects).
CHANGELOG: the two visible fixes of the branch are named instead of
"nothing changes on screen".

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-25 10:45:33 +03:00

445 lines
13 KiB
Rust

//! What the transitions of the client's state need from the front end and
//! tell it. A transition (`events::apply`, the functions of `chat::logic`)
//! changes the [`AppState`](crate::state::AppState) it is given and puts
//! everything else into an [`Update`]: what to redraw, the status line, the
//! engine commands to send, what to keep; the little it must ask a front end
//! for while it runs (is the chat on screen, what the store knows) goes
//! through [`Host`]. Neither the engine nor the store nor a toolkit is
//! touched here, so the transitions are tested with a fake host
//! (`events::tests`).
use std::path::PathBuf;
use voelin_core::{Command, Event, GatewayRequest, StreamSink};
use voelin_model::ChatTarget;
use voelin_store::{ChatRead, ChatTarget as StoredTarget};
use crate::social::NoticeRequest;
/// What a transition asks of its front end while it runs.
pub trait Host {
/// The sample data of `VOELIN_DEMO_UI` is shown: nothing is sent to the
/// engine or kept in the store.
fn demo_ui(&self) -> bool;
/// The current chat's messages are on screen (a page shows the chat).
fn chat_shown(&self) -> bool;
/// A stream is in the viewer.
fn watching(&self) -> bool;
/// The development switch `VOELIN_AUTOWATCH=1`: watch the first stream
/// that shows up.
fn autowatch(&self) -> bool;
/// The Stream Studio streams to this session: the events of that stream
/// are its own.
fn studio_streams_to(&self, session: i64) -> bool;
/// The largest picture previewed in chats, in bytes (0: none), from
/// `ui.image_preview_kb`.
fn preview_limit(&self) -> u64;
/// Pictures on the web are fetched and shown (`cache.fetch_images`).
fn fetch_images(&self) -> bool;
/// The private chat with this peer (unique id) of this session is on
/// screen, in the messages page.
fn dm_shown(&self, session: i64, uid: &str) -> bool;
/// Now, in milliseconds since the epoch.
fn now_ms(&self) -> i64 {
crate::social::now_ms()
}
/// How far the chats of a server were read, from the store.
fn chat_reads(&self, server_uid: &str) -> Result<Vec<(StoredTarget, ChatRead)>, String>;
/// Keep how far a chat of a server was read.
fn set_chat_read(
&self,
server_uid: &str,
target: &StoredTarget,
read: &ChatRead,
) -> Result<(), String>;
}
/// The parts of the screen to draw again. Each is a function of the state,
/// so a front end draws each flagged part once, however many events set it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Refresh {
/// The server rail.
pub servers: bool,
/// The top bar of the server page.
pub toolbar: bool,
/// The channel tree and the members.
pub tree: bool,
/// The chat tabs, the lines and what belongs to them (pins, topics).
pub chat: bool,
/// The streams panel and the voice card's streams.
pub streams: bool,
/// The stream viewer's header.
pub viewer: bool,
/// The open member card.
pub member_card: bool,
/// The home page.
pub home: bool,
/// The events page.
pub events: bool,
/// The gateway pages of the settings.
pub gateways: bool,
/// The friends page, home's friends and activity, the block list.
pub people: bool,
/// The lists of direct messages and the offline messages (asked for
/// again when a voice connection came up).
pub conversations: bool,
/// The peer card of the open direct message.
pub dm: bool,
}
impl Refresh {
/// Every part.
pub const ALL: Self = Self {
servers: true,
toolbar: true,
tree: true,
chat: true,
streams: true,
viewer: true,
member_card: true,
home: true,
events: true,
gateways: true,
people: true,
conversations: true,
dm: true,
};
/// Whether nothing is to be drawn.
pub fn is_empty(&self) -> bool {
*self == Self::default()
}
}
/// What a transition wants kept.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Persist {
/// The bookmark with this id changed (the store has the old one).
Bookmark {
/// The bookmark.
id: i64,
/// What it was changed for, for the log.
what: &'static str,
},
/// The UI's own settings changed (`AppState::settings`).
Settings,
/// The audio settings changed (`AppState::audio`).
Audio,
/// The clients' local volumes changed (`AppState::playback`).
Playback,
}
/// The password dialog of a locked channel is to open
/// (`AppState::join_target` names the channel).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PasswordPrompt {
/// The channel's name as the tree shows it.
pub name: String,
/// The password given before was refused.
pub wrong: bool,
}
/// What the streams we share and watch need of the front end, which owns the
/// capture and the decoder.
#[derive(Debug, Default)]
pub struct StreamEffects {
/// Encode into the live stream: the sink of our stream.
pub attach: Option<StreamSink>,
/// Our stream is over: the capture stops.
pub drop_share: bool,
/// The watched stream is over, or left: its decoder stops.
pub drop_decoder: bool,
/// The audio mixer's rows follow the capture again.
pub mixer: bool,
/// The player leaves full screen.
pub leave_fullscreen: bool,
}
/// What a transition tells its front end, besides the changed state.
#[derive(Debug, Default)]
pub struct Update {
/// What to draw again.
pub refresh: Refresh,
/// The status line's new text.
pub status: Option<String>,
/// Commands for the engine, in order.
pub commands: Vec<Command>,
/// What to keep, in order.
pub persist: Vec<Persist>,
/// Pictures the engine wrote again: a front end drops what it decoded
/// of them.
pub reloaded: Vec<PathBuf>,
/// The microphone meter: level in dBFS, and whether voice is sent.
pub input_level: Option<(f32, bool)>,
/// Open the password dialog.
pub password: Option<PasswordPrompt>,
/// Notices for the bell, in order.
pub notices: Vec<NoticeRequest>,
/// What went wrong that nothing else shows, for the log.
pub warnings: Vec<String>,
/// Chats whose messages changed (session, chat): the Stream Studio
/// follows the chat of its channel.
pub chats: Vec<(i64, ChatTarget)>,
/// A stream to watch (its id): the one a lookup was waiting for, or the
/// development switch's.
pub watch: Option<String>,
/// The capture and the decoder.
pub stream: StreamEffects,
/// A server connected or answered: the development switch that shares
/// the test pattern may start now.
pub autoshare: bool,
/// The session on screen got its state or its presence: the development
/// switch that opens the volume dialog of the first client may act.
pub first_client: bool,
/// The event, when its state is not in the [`AppState`]: the Stream
/// Studio's stream (`Host::studio_streams_to`), a setting that changed (the
/// settings service) and the answers to the offline message requests, which
/// the messages page keeps. The watched and shared streams are not among
/// them: they are state here and go through the stream effects. The front
/// end handles these itself ([`crate::events`] lists them), before it draws
/// what `refresh` names, as what it keeps may be on screen.
pub rest: Option<Event>,
}
/// The host and the update of a transition in progress.
pub struct Cx<'a> {
/// What the front end answers.
pub host: &'a dyn Host,
/// What is collected.
pub update: Update,
}
impl<'a> Cx<'a> {
/// A transition that starts with nothing to tell.
pub fn new(host: &'a dyn Host) -> Self {
Self { host, update: Update::default() }
}
/// The status line says this from now on.
pub fn status(&mut self, text: impl Into<String>) {
self.update.status = Some(text.into());
}
/// A command for the engine.
pub fn send(&mut self, command: Command) {
self.update.commands.push(command);
}
/// A command for the engine, but not for the sample sessions of
/// `VOELIN_DEMO_UI`: the engine would open them for real.
pub fn send_real(&mut self, command: Command) {
if !self.host.demo_ui() {
self.send(command);
}
}
/// A request to a session's gateway (not for the sample sessions).
pub fn gateway_to(&mut self, session: i64, request: GatewayRequest) {
self.send_real(Command::Gateway { session: session as u64, request });
}
/// Something went wrong that nothing else shows: it is logged.
pub fn warn(&mut self, text: impl Into<String>) {
self.update.warnings.push(text.into());
}
/// Keep this.
pub fn persist(&mut self, what: Persist) {
self.update.persist.push(what);
}
/// The password dialog of a locked channel opens.
pub fn ask_password(&mut self, channel_name: String, wrong: bool) {
self.update.password = Some(PasswordPrompt { name: channel_name, wrong });
}
/// The chat `target` of session `id` changed.
pub fn chat_changed(&mut self, id: i64, target: &ChatTarget) {
self.update.chats.push((id, target.clone()));
}
}
/// A front end for the tests of the transitions.
#[cfg(test)]
pub(crate) mod testing {
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use voelin_store::{ChatRead, ChatTarget as StoredTarget};
use super::Host;
use std::sync::Arc;
use voelin_core::{
AudioSettings, HistoryMessage, ObserveState, SessionState, Source, VoiceState,
};
use voelin_model::{ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence, ServerDetails};
use voelin_store::{Bookmark, MessageSource};
use crate::bridge::ChatLine;
use crate::settings::{ClientPlaybackMap, UiSettings};
use crate::state::AppState;
/// The front end of the tests: answers what the transitions ask and keeps
/// what they store.
#[derive(Default)]
pub(crate) struct Fake {
pub(crate) demo: bool,
pub(crate) shown: Cell<bool>,
pub(crate) watching: bool,
pub(crate) autowatch: bool,
/// The session the Stream Studio streams to.
pub(crate) studio: Option<i64>,
pub(crate) limit: u64,
/// The private chat on screen: session and peer.
pub(crate) dm: Option<(i64, String)>,
/// What time it is.
pub(crate) now: Cell<i64>,
/// What the store has: server unique id, its chats' reads.
pub(crate) reads: HashMap<String, Vec<(StoredTarget, ChatRead)>>,
/// What was stored.
pub(crate) written: RefCell<Vec<(String, StoredTarget, ChatRead)>>,
}
impl Host for Fake {
fn demo_ui(&self) -> bool {
self.demo
}
fn chat_shown(&self) -> bool {
self.shown.get()
}
fn watching(&self) -> bool {
self.watching
}
fn autowatch(&self) -> bool {
self.autowatch
}
fn studio_streams_to(&self, session: i64) -> bool {
self.studio == Some(session)
}
fn preview_limit(&self) -> u64 {
self.limit
}
fn fetch_images(&self) -> bool {
false
}
fn dm_shown(&self, session: i64, uid: &str) -> bool {
self.dm.as_ref().is_some_and(|(s, u)| *s == session && u == uid)
}
fn now_ms(&self) -> i64 {
self.now.get()
}
fn chat_reads(&self, server_uid: &str) -> Result<Vec<(StoredTarget, ChatRead)>, String> {
Ok(self.reads.get(server_uid).cloned().unwrap_or_default())
}
fn set_chat_read(
&self,
server_uid: &str,
target: &StoredTarget,
read: &ChatRead,
) -> Result<(), String> {
self.written.borrow_mut().push((server_uid.to_owned(), target.clone(), *read));
Ok(())
}
}
pub(crate) type State = AppState<Vec<ChatLine>>;
pub(crate) fn state() -> State {
let bookmark = Bookmark {
id: 1,
name: "ts.example".into(),
address: "ts.example".into(),
nickname: "Me".into(),
..Default::default()
};
AppState::new(
vec![bookmark],
UiSettings::default(),
AudioSettings::default(),
ClientPlaybackMap::new(),
)
}
pub(crate) fn session(voice: VoiceState, own_channel: Option<u64>) -> SessionState {
let connected = voice == VoiceState::Connected;
SessionState {
voice,
observe: ObserveState::Off,
presence_source: connected.then_some(Source::Voice),
own_channel,
own_client: connected.then_some(10),
server_uid: connected.then(|| "srv=".to_owned()),
..Default::default()
}
}
/// Lobby (1) and Games (2), with Me (10, in Games) and Alice (11, in
/// Games).
pub(crate) fn presence() -> Arc<Presence> {
let mut p = Presence { server_name: "Nightfall Guild".into(), ..Default::default() };
for (id, order, name) in [(1, 0, "Lobby"), (2, 1, "Games")] {
p.channels
.insert(id, ChannelInfo { id, order, name: name.into(), ..Default::default() });
}
for (id, name, uid) in [(10, "Me", "me="), (11, "Alice", "alice=")] {
p.clients.insert(
id,
ClientInfo {
id,
channel: 2,
nickname: name.into(),
uid: Some(uid.into()),
..Default::default()
},
);
}
p.server = ServerDetails { welcome_message: "Welcome".into(), ..Default::default() };
Arc::new(p)
}
/// A message of Games, by Alice unless `mine`.
pub(crate) fn said(id: i64, ts_ms: i64, mine: bool, text: &str) -> HistoryMessage {
HistoryMessage {
id,
message: ChatMessage {
target: ChatTarget::Channel(2),
author_name: if mine { "Me" } else { "Alice" }.into(),
author_uid: Some(if mine { "me=" } else { "alice=" }.into()),
author_id: Some(if mine { 10 } else { 11 }),
text: text.into(),
ts_ms,
via_relay: false,
blocked: false,
},
source: MessageSource::Voice,
remote_id: Some(id + 1000),
topic_id: None,
reactions: Vec::new(),
pinned: false,
rev: 0,
}
}
}