Files
VoelinClient/crates/voelin-gpui/src/shell/tree_model.rs
T

294 lines
9.7 KiB
Rust

//! The narrow entity behind the channel tree and the members panel: what
//! `voelin_ui_vm::servers::logic::tree_view` makes of the state, kept between
//! one change and the next so that the two panes can be told what changed.
//!
//! It listens to the tree, toolbar and member-card signals
//! ([`crate::signals`]), builds the rows once for both panes, compares them
//! with the rows it had ([`voelin_ui_vm::list::diff`], the row operations the
//! Slint front end applies to its `VecModel`) and emits what differs
//! ([`TreeEvent`], with the rows the operations lead to): a pane applies the
//! operations to its list state, so a person who joins is a row that is
//! inserted, not a list that starts again at the top. A change that moves none
//! of what a pane shows emits nothing.
//!
//! **The tree marks who is talking**, as the Slint tree does (the ring on the
//! avatar and the speaking bars on the row): someone who starts or stops
//! talking changes one row of the tree and one of the members panel, so each
//! of the two panes is drawn again once for it, and no other pane is
//! (docs/ui.md, "What a change costs").
use std::sync::Arc;
use gpui_kit::{App, Context, Entity, EventEmitter, Subscription};
use voelin_core::{ObserveState, VoiceState};
use voelin_ui_vm::bridge::{MemberCard, MemberItem, TreeItem};
use voelin_ui_vm::list::{Changes, diff};
use voelin_ui_vm::servers::logic;
use voelin_ui_vm::tree::{ChannelId, member_card};
use crate::app::{AppState, VmState};
use crate::signals::Area;
/// Why a list has no rows, which the pane says in words.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Emptiness {
/// No server is on screen.
NoServer,
/// The server is observed or being connected to, and its presence is on
/// the way.
Loading,
/// Nothing is known of the server until it is connected.
Connect,
/// The server has people and the members' search matches none of them (the
/// members panel's only: the tree is not searched).
NoMatch,
}
impl Emptiness {
/// Why the lists of the server on screen are empty: never
/// [`Emptiness::NoMatch`], which is [`Emptiness::of_people`]'s.
pub fn of(vm: &VmState) -> Self {
match vm.current {
None => Self::NoServer,
Some(id) => match vm.sessions.get(&id) {
Some(view)
if view.state.observe != ObserveState::Off
|| view.state.voice == VoiceState::Connecting =>
{
Self::Loading
}
_ => Self::Connect,
},
}
}
/// Why the members panel is empty: as [`Emptiness::of`], except that a
/// search that leaves nobody of the `total` on the server (`shown` rows
/// are left) is [`Emptiness::NoMatch`], where "Connect to see who is here"
/// would be false.
pub fn of_people(vm: &VmState, shown: usize, total: i32) -> Self {
if shown == 0 && total > 0 && !vm.member_filter.trim().is_empty() {
Self::NoMatch
} else {
Self::of(vm)
}
}
}
/// What changed in the model, as the panes need it.
///
/// The list events carry the rows their operations lead to. A model that
/// refreshed twice before the first event is delivered (an observer that
/// changes the state inside a flush makes it) holds the second rows by the
/// time a pane hears of the first operations, and operations applied to rows
/// they were not made for index past their end. A pane applies them to the
/// rows it has and keeps the rows the event carries, so the events, in the
/// order they are delivered, lead from the rows the pane started with to the
/// model's last.
#[derive(Clone, Debug, PartialEq)]
pub enum TreeEvent {
/// The tree's rows: the operations from the rows the pane has to the rows
/// carried (the model's [`TreeModel::rows`] when it made them).
Rows(Changes, Arc<Vec<TreeItem>>),
/// The members panel's rows: the operations from the rows the pane has to
/// the rows carried (the model's [`TreeModel::people`] when it made them).
People(Changes, Arc<Vec<MemberItem>>),
/// The card over a member row opened, changed or closed
/// ([`TreeModel::card`]).
Card,
/// The selected channel ([`TreeModel::selected`]).
Selection,
/// Why the lists are empty, or how many people there are
/// ([`TreeModel::emptiness`], [`TreeModel::people_emptiness`],
/// [`TreeModel::total`]).
Lists,
}
/// The areas the model listens to.
const AREAS: [Area; 3] = [Area::Tree, Area::Toolbar, Area::MemberCard];
/// How many times each of [`AREAS`] was raised.
fn generations(app: &Entity<AppState>, cx: &App) -> [u64; 3] {
let signals = app.read(cx).signals();
AREAS.map(|area| signals.of(area).read(cx).generation())
}
/// The rows of the tree and of the members panel, the member card and the
/// selection of the server on screen.
pub struct TreeModel {
app: Entity<AppState>,
/// The generations of its signals it last built the rows at: a batch that
/// raises several of them (a picture that arrives raises three) has them
/// all raised before the first is heard, so the first refresh builds the
/// rows and the others find nothing new.
seen: [u64; 3],
refreshes: u64,
rows: Arc<Vec<TreeItem>>,
people: Arc<Vec<MemberItem>>,
total: i32,
card: Option<MemberCard>,
selected: Option<ChannelId>,
emptiness: Emptiness,
people_emptiness: Emptiness,
_subscriptions: Vec<Subscription>,
}
impl EventEmitter<TreeEvent> for TreeModel {}
/// Check that `changes` lead from a list of `old` rows to one of `new` rows
/// (debug builds): a pane that applies operations to rows they were not made
/// for finds the counts out of step, where a release build would index past
/// the end or leave its list state out of step with its rows.
pub(super) fn debug_check(old: usize, changes: &Changes, new: usize) {
debug_assert_eq!(
old + changes.inserted(),
new + changes.removed(),
"{changes:?} do not lead from {old} rows to {new}: applied to rows they were not made \
for? (docs/ui.md, \"For the next slices\": no state change from a signal's observer \
inside a flush)"
);
}
/// Everything the model keeps, as the state gives it now.
struct Snapshot {
rows: Vec<TreeItem>,
people: Vec<MemberItem>,
total: i32,
card: Option<MemberCard>,
selected: Option<ChannelId>,
emptiness: Emptiness,
people_emptiness: Emptiness,
}
impl Snapshot {
fn of(app: &AppState) -> Self {
let vm = &app.vm;
let view = vm.current.and_then(|id| vm.sessions.get(&id));
let (rows, people, total) = match logic::tree_view(vm, false) {
Some(tree) => (tree.rows, tree.server_members, tree.member_total),
None => (Vec::new(), Vec::new(), 0),
};
Self {
people_emptiness: Emptiness::of_people(vm, people.len(), total),
rows,
people,
total,
card: view
.and_then(|view| view.member_card.map(|id| (view, id)))
.and_then(|(view, id)| member_card(view, id, &vm.contacts, &vm.playback)),
selected: app.selected_channel(),
emptiness: Emptiness::of(vm),
}
}
}
impl TreeModel {
/// A model of what `app` shows now, following its tree signals.
pub fn new(app: &Entity<AppState>, cx: &mut Context<Self>) -> Self {
let (snapshot, signals) = {
let state = app.read(cx);
(Snapshot::of(state), state.signals().clone())
};
let subscriptions =
signals.watch(app, &AREAS, cx, |this: &mut Self, _, cx| this.refresh(cx));
Self {
app: app.clone(),
seen: generations(app, cx),
refreshes: 0,
rows: Arc::new(snapshot.rows),
people: Arc::new(snapshot.people),
total: snapshot.total,
card: snapshot.card,
selected: snapshot.selected,
emptiness: snapshot.emptiness,
people_emptiness: snapshot.people_emptiness,
_subscriptions: subscriptions,
}
}
/// The rows of the channel tree: channels with the clients in them.
pub fn rows(&self) -> &Arc<Vec<TreeItem>> {
&self.rows
}
/// The rows of the members panel: everyone on the server, in sections.
pub fn people(&self) -> &Arc<Vec<MemberItem>> {
&self.people
}
/// How many are on the server (the query clients not counted).
pub fn total(&self) -> i32 {
self.total
}
/// The card over a member row, when one is open.
pub fn card(&self) -> Option<&MemberCard> {
self.card.as_ref()
}
/// The channel selected in the tree.
pub fn selected(&self) -> Option<ChannelId> {
self.selected
}
/// Why the tree is empty, were it.
pub fn emptiness(&self) -> Emptiness {
self.emptiness
}
/// Why the members panel is empty, were it: the same as
/// [`TreeModel::emptiness`], or that the search matches nobody.
pub fn people_emptiness(&self) -> Emptiness {
self.people_emptiness
}
/// How many times the rows were built again since the model was made: one
/// for each batch of changes, not one for each signal it raised.
pub fn refreshes(&self) -> u64 {
self.refreshes
}
/// Build the rows again, and tell the panes what differs. Nothing, when
/// none of the signals was raised since the last time.
fn refresh(&mut self, cx: &mut Context<Self>) {
let now = generations(&self.app, cx);
if now == self.seen {
return;
}
self.seen = now;
self.refreshes += 1;
let new = Snapshot::of(self.app.read(cx));
let rows = diff(&self.rows, &new.rows);
let people = diff(&self.people, &new.people);
if !rows.is_empty() {
self.rows = Arc::new(new.rows);
}
if !people.is_empty() {
self.people = Arc::new(new.people);
}
let lists = (self.emptiness, self.people_emptiness, self.total)
!= (new.emptiness, new.people_emptiness, new.total);
(self.emptiness, self.people_emptiness, self.total) =
(new.emptiness, new.people_emptiness, new.total);
let card = self.card != new.card;
self.card = new.card;
let selection = self.selected != new.selected;
self.selected = new.selected;
if !rows.is_empty() {
cx.emit(TreeEvent::Rows(rows, self.rows.clone()));
}
if !people.is_empty() {
cx.emit(TreeEvent::People(people, self.people.clone()));
}
if lists {
cx.emit(TreeEvent::Lists);
}
if card {
cx.emit(TreeEvent::Card);
}
if selection {
cx.emit(TreeEvent::Selection);
}
}
}