Split the chat controller: the chat view, the user's moves and the lines into voelin-ui-vm
chat/logic.rs now has what the chat view shows (the strip, the lines with their divider and downloads, the pins, the topics and the counts, as plain data), the lines of a tab or of an open topic (lines_of, also for the Stream Studio's chat, with the pokes of a private chat's peer), and what the user's moves do: select and close a tab, send, ask for older messages, mark read, react, pin, the topics, download, attach and upload. The Slint side (chat/bind.rs) writes the Bridge and the models from it and calls the transitions. Poke and its lines moved to voelin_ui_vm::social. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0d2ad3f250
commit
02a3b3eab0
10 files changed
+1437
-867
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -9,97 +9,19 @@ use voelin_core::StreamState;
|
||||
use voelin_core::gateway::Pin;
|
||||
use voelin_core::stream::StreamInfo;
|
||||
use voelin_core::{
|
||||
AudioSettings, BackendInfo, Command, Event, GatewayRequest, GatewayUpdate, HistoryMessage,
|
||||
HistorySource, JoinFailure, ObserveState, SessionState, Source, TransferState, VoiceState,
|
||||
BackendInfo, Command, Event, GatewayRequest, GatewayUpdate, HistoryMessage, HistorySource,
|
||||
JoinFailure, TransferState, VoiceState,
|
||||
};
|
||||
use voelin_gateway_proto::{UserRef, feature};
|
||||
use voelin_model::{
|
||||
Capabilities, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence, ServerDetails,
|
||||
};
|
||||
use voelin_store::{Bookmark, ChatRead, ChatTarget as StoredTarget, MessageSource};
|
||||
use voelin_model::{Capabilities, ChatMessage, ChatTarget};
|
||||
use voelin_store::{Bookmark, ChatRead, ChatTarget as StoredTarget};
|
||||
|
||||
use super::*;
|
||||
use crate::bridge::ChatLine;
|
||||
use crate::host::Refresh;
|
||||
use crate::host::testing::Fake;
|
||||
use crate::settings::{ClientPlayback, ClientPlaybackMap, LastVoice, UiSettings};
|
||||
use crate::settings::{ClientPlayback, LastVoice};
|
||||
|
||||
type State = AppState<Vec<ChatLine>>;
|
||||
|
||||
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(),
|
||||
)
|
||||
}
|
||||
|
||||
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).
|
||||
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`.
|
||||
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,
|
||||
}
|
||||
}
|
||||
use crate::host::testing::{State, presence, said, session, state};
|
||||
|
||||
fn games(messages: Vec<HistoryMessage>, source: HistorySource) -> Event {
|
||||
Event::ChatHistory {
|
||||
|
||||
@@ -252,6 +252,18 @@ pub(crate) mod testing {
|
||||
|
||||
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)]
|
||||
@@ -312,4 +324,82 @@ pub(crate) mod testing {
|
||||
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -81,6 +81,62 @@ pub fn own_message(
|
||||
|| (own_client.is_some() && message.author_id == own_client)
|
||||
}
|
||||
|
||||
/// A poke we got.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Poke {
|
||||
/// The session it came in.
|
||||
pub session: i64,
|
||||
/// Who poked, by unique id, when known.
|
||||
pub uid: Option<String>,
|
||||
/// Who poked, by name.
|
||||
pub name: String,
|
||||
/// What they wrote with it.
|
||||
pub message: String,
|
||||
/// When, in milliseconds since the epoch.
|
||||
pub ts_ms: i64,
|
||||
}
|
||||
|
||||
/// The avatar picture of someone by unique id, from any session.
|
||||
pub fn avatar_of<L>(state: &AppState<L>, uid: &str) -> crate::image::ImageRef {
|
||||
crate::avatar::image(state.sessions.values().find_map(|v| v.avatars.get(uid)))
|
||||
}
|
||||
|
||||
/// Pokes from `uid` as lines of their private chat, among its messages
|
||||
/// (with the time of each, oldest first).
|
||||
pub fn poke_lines<L>(
|
||||
state: &AppState<L>,
|
||||
pokes: &[Poke],
|
||||
session: i64,
|
||||
uid: &str,
|
||||
) -> Vec<(i64, crate::bridge::ChatLine)> {
|
||||
pokes
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, p)| p.session == session && p.uid.as_deref() == Some(uid))
|
||||
.map(|(i, p)| {
|
||||
let text = if p.message.is_empty() {
|
||||
"👋 poked you".to_owned()
|
||||
} else {
|
||||
format!("👋 poked you: {}", p.message)
|
||||
};
|
||||
let message = ChatMessage {
|
||||
target: ChatTarget::Private(uid.to_owned()),
|
||||
author_name: p.name.clone(),
|
||||
author_uid: p.uid.clone(),
|
||||
author_id: None,
|
||||
text,
|
||||
ts_ms: p.ts_ms,
|
||||
via_relay: false,
|
||||
blocked: false,
|
||||
};
|
||||
let mut line = crate::chat::line(&message, None);
|
||||
line.key = -1_000_000 - i as i32;
|
||||
line.avatar = avatar_of(state, uid);
|
||||
(p.ts_ms, line)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether a message of a session is ours.
|
||||
pub fn is_own<L>(state: &AppState<L>, session: i64, message: &ChatMessage) -> bool {
|
||||
let own_client = state.sessions.get(&session).and_then(|v| v.state.own_client);
|
||||
|
||||
@@ -1,730 +0,0 @@
|
||||
//! Chat: tabs per session (server, channels, private chats), their
|
||||
//! messages, and what a gateway adds to them (pins, reactions, topics).
|
||||
//! The chat strip shows the server's and the channels' tabs; a private chat
|
||||
//! is the current tab only while the messages page shows it (messages.rs).
|
||||
//!
|
||||
//! 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 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`].
|
||||
//!
|
||||
//! Messages are read while their tab is on screen in the focused window
|
||||
//! ([`App::track_reading`]). A tab remembers the newest message read
|
||||
//! (`Tab::read`, kept in the store's `chat_reads`), counts what came after
|
||||
//! it, and when it comes on screen shows a "New" divider above the first
|
||||
//! of those until it is left.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use slint::ComponentHandle;
|
||||
use voelin_core::settings::CACHE_FETCH_IMAGES;
|
||||
use voelin_core::{
|
||||
Command, DownloadTo, GatewayRequest, HistoryMessage, HistorySource, TransferState,
|
||||
};
|
||||
use voelin_gateway_proto::feature;
|
||||
use voelin_model::{ChatMessage, ChatTarget};
|
||||
|
||||
use crate::app::{App, Bridge, Nav, SessionView, Tab};
|
||||
use crate::settings::UI_IMAGE_PREVIEW_KB;
|
||||
use crate::vm;
|
||||
use crate::vm::bbcode::LinkKind;
|
||||
use crate::vm::bridge::{ChatLine, ChatTab, FileItem, PinItem};
|
||||
use crate::vm::chat::{LineCache, LineCtx, Previous};
|
||||
use crate::vm::state::Download;
|
||||
|
||||
/// "3 min ago", "yesterday", "12 Mar".
|
||||
fn ago(ts_ms: i64) -> String {
|
||||
let Some(then) = chrono::DateTime::from_timestamp_millis(ts_ms) else { return String::new() };
|
||||
let minutes = (chrono::Utc::now() - then).num_minutes();
|
||||
match minutes {
|
||||
i64::MIN..=0 => "just now".into(),
|
||||
1 => "1 min ago".into(),
|
||||
2..=59 => format!("{minutes} min ago"),
|
||||
60..=119 => "1 hour ago".into(),
|
||||
120..=1439 => format!("{} hours ago", minutes / 60),
|
||||
1440..=2879 => "yesterday".into(),
|
||||
_ => then.with_timezone(&chrono::Local).format("%e %b").to_string().trim().into(),
|
||||
}
|
||||
}
|
||||
|
||||
impl App {
|
||||
/// Open the chat `target` of the current session, and with `focus` show
|
||||
/// it ([`vm::chat::logic::open_chat`]).
|
||||
pub(crate) fn open_chat(&mut self, target: ChatTarget, focus: bool) {
|
||||
self.transition(|state, cx| vm::chat::logic::open_chat(state, cx, target, focus));
|
||||
}
|
||||
|
||||
/// The index of `target`'s tab in session `id`, opened if new (the
|
||||
/// engine then sends its history).
|
||||
pub(crate) fn chat_tab(&mut self, id: i64, target: ChatTarget) -> usize {
|
||||
self.transition(|state, cx| vm::chat::logic::chat_tab(state, cx, id, target))
|
||||
}
|
||||
|
||||
/// The session's tab that tab `index` of the chat strip is
|
||||
/// (`Bridge.tabs`, [`vm::chat::strip`]).
|
||||
pub(crate) fn strip_tab(&self, index: i32) -> Option<usize> {
|
||||
self.models.strip.borrow().get(usize::try_from(index).ok()?).copied()
|
||||
}
|
||||
|
||||
pub(crate) fn select_tab(&mut self, index: usize) {
|
||||
if let Some(view) = self.view_mut()
|
||||
&& index < view.tabs.len()
|
||||
{
|
||||
view.set_current_tab(index);
|
||||
view.tabs[index].topic = None;
|
||||
}
|
||||
if let Some(id) = self.state.current {
|
||||
self.fetch_previews(id);
|
||||
}
|
||||
self.prefetch_counts();
|
||||
self.track_reading();
|
||||
self.refresh_chat();
|
||||
self.refresh_servers();
|
||||
}
|
||||
|
||||
pub(crate) fn close_tab(&mut self, index: usize) {
|
||||
let Some(id) = self.state.current else { return };
|
||||
let view = self.state.sessions.entry(id).or_default();
|
||||
if index == 0 || index >= view.tabs.len() {
|
||||
return;
|
||||
}
|
||||
self.save_read(id, index);
|
||||
let tab = self.state.sessions.entry(id).or_default().remove_tab(index);
|
||||
self.engine.send(Command::CloseChat { session: id as u64, target: tab.target });
|
||||
self.prefetch_counts();
|
||||
self.track_reading();
|
||||
self.refresh_chat();
|
||||
self.refresh_servers();
|
||||
}
|
||||
|
||||
pub(crate) fn send_message(&mut self, text: String) {
|
||||
let Some(id) = self.state.current else { return };
|
||||
let Some(view) = self.state.sessions.get(&id) else { return };
|
||||
let target = view.tabs[view.current_tab].target.clone();
|
||||
self.engine.send(Command::SendChat { session: id as u64, target, text });
|
||||
}
|
||||
|
||||
/// A live message of a session without stored history.
|
||||
pub(crate) fn add_message(&mut self, id: i64, message: ChatMessage) {
|
||||
self.transition(|state, cx| vm::chat::logic::add_message(state, cx, id, message));
|
||||
}
|
||||
|
||||
/// Messages the engine stored: added or updated by their local id.
|
||||
pub(crate) fn history_batch(
|
||||
&mut self,
|
||||
id: i64,
|
||||
target: &ChatTarget,
|
||||
messages: Vec<HistoryMessage>,
|
||||
source: HistorySource,
|
||||
complete: bool,
|
||||
) {
|
||||
self.transition(|state, cx| {
|
||||
vm::chat::logic::history_batch(state, cx, id, target, messages, source, complete);
|
||||
});
|
||||
}
|
||||
|
||||
/// The page of messages before the oldest one shown.
|
||||
pub(crate) fn load_older(&mut self) {
|
||||
let Some(id) = self.state.current else { return };
|
||||
let Some(view) = self.state.sessions.get_mut(&id) else { return };
|
||||
let tab = &mut view.tabs[view.current_tab];
|
||||
if tab.loading || tab.complete {
|
||||
return;
|
||||
}
|
||||
tab.loading = true;
|
||||
let target = tab.target.clone();
|
||||
let oldest = tab.messages.first().map(|m| &m.message);
|
||||
if self.demo_ui {
|
||||
// No engine answers in demo mode.
|
||||
crate::dev::answer_older(id, target, oldest.cloned());
|
||||
} else {
|
||||
let before = oldest.map(|m| m.id);
|
||||
self.engine.send(Command::LoadOlderHistory { session: id as u64, target, before });
|
||||
}
|
||||
self.refresh_chat();
|
||||
}
|
||||
|
||||
/// The lines of a tab's messages (`main`) or of its open topic, grouped
|
||||
/// and with everything the row shows (also the stream chat of the
|
||||
/// Stream Studio, studio/). The server chat starts with what the
|
||||
/// server says to everyone who connects ([`Self::server_lines`]).
|
||||
pub(crate) fn lines_of(&self, view: &SessionView, tab: &Tab, main: bool) -> Vec<ChatLine> {
|
||||
let messages = if main { &tab.messages } else { &tab.topic_messages };
|
||||
let gateway = view.gateway_has(feature::PINS)
|
||||
|| view.gateway_has(feature::REACTIONS)
|
||||
|| view.gateway_has(feature::TOPICS);
|
||||
// Pictures on the web show only while pictures are fetched and
|
||||
// shown.
|
||||
let shown = self.prefs.get(&CACHE_FETCH_IMAGES) && self.prefs.get(&UI_IMAGE_PREVIEW_KB) > 0;
|
||||
let pictures = shown.then_some(&view.pictures);
|
||||
let cache = main.then_some(&tab.cache);
|
||||
let mut previous: Option<Previous> = None;
|
||||
let mut lines: Vec<(i64, ChatLine)> = Vec::with_capacity(messages.len());
|
||||
for m in messages {
|
||||
let avatar =
|
||||
m.message.message.author_uid.as_ref().and_then(|uid| view.avatars.get(uid));
|
||||
let topic = m
|
||||
.message
|
||||
.topic_id
|
||||
.filter(|_| tab.topic.is_none())
|
||||
.and_then(|t| tab.topics.iter().find(|i| i.id == t))
|
||||
.map(|t| t.title.clone())
|
||||
.unwrap_or_default();
|
||||
let previews = m
|
||||
.message
|
||||
.message
|
||||
.file_refs()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, f)| vm::previews::image_of(view, f).map(|image| (i, image)))
|
||||
.collect();
|
||||
let ctx = LineCtx {
|
||||
key: m.key,
|
||||
avatar: vm::avatar::image(avatar),
|
||||
gateway,
|
||||
marked: tab.marked == Some(m.message.id),
|
||||
topic,
|
||||
downloads: self.downloads_of(view, m.key),
|
||||
previews,
|
||||
pictures,
|
||||
cache,
|
||||
unread_start: main && tab.divider == Some(m.message.id),
|
||||
};
|
||||
lines.push((
|
||||
m.message.message.ts_ms,
|
||||
vm::chat::history_line(&m.message, previous.as_ref(), &ctx),
|
||||
));
|
||||
previous = Some(Previous::of(&m.message.message));
|
||||
}
|
||||
if let Some(cache) = cache {
|
||||
let ids = messages.iter().map(|m| m.message.id).chain(vm::chat::SERVER_LINES);
|
||||
cache.keep(ids, messages.len());
|
||||
}
|
||||
// Pokes of a private chat's peer show among its messages.
|
||||
if let (ChatTarget::Private(uid), Some(session)) = (&tab.target, self.state.current) {
|
||||
lines.extend(self.poke_lines(session, uid));
|
||||
lines.sort_by_key(|(ts, _)| *ts);
|
||||
}
|
||||
let server = if main && tab.target == ChatTarget::Server {
|
||||
Self::server_lines(view, pictures, cache)
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
server.into_iter().chain(lines.into_iter().map(|(_, line)| line)).collect()
|
||||
}
|
||||
|
||||
/// What the server says to everyone who connects ([`server_texts`]) as
|
||||
/// the first lines of the server chat: by the server, without reactions
|
||||
/// or pins.
|
||||
fn server_lines(
|
||||
view: &SessionView,
|
||||
pictures: Option<&HashMap<String, PathBuf>>,
|
||||
cache: Option<&LineCache>,
|
||||
) -> Vec<ChatLine> {
|
||||
let name = match view.presence.server_name.as_str() {
|
||||
"" => "Server",
|
||||
name => name,
|
||||
};
|
||||
vm::chat::server_texts(&view.presence.server)
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(i, (text, id))| {
|
||||
let ctx = LineCtx { key: -1 - i as i32, pictures, cache, ..Default::default() };
|
||||
vm::chat::server_line(name, text, id, i > 0, &ctx)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The file cards of a message that has downloads running.
|
||||
fn downloads_of(&self, view: &SessionView, key: i32) -> Vec<(usize, FileItem)> {
|
||||
view.downloads
|
||||
.values()
|
||||
.filter(|d| d.key == key)
|
||||
.map(|d| {
|
||||
let (detail, status, progress) = match &d.state {
|
||||
TransferState::Requested => ("Starting…".to_owned(), "running", 0.0),
|
||||
TransferState::Started { size, offset } => (
|
||||
format!(
|
||||
"{} of {}",
|
||||
vm::chat::size_text(*offset),
|
||||
vm::chat::size_text(*size)
|
||||
),
|
||||
"running",
|
||||
if *size > 0 { *offset as f32 / *size as f32 } else { 0.0 },
|
||||
),
|
||||
TransferState::Progress { done, size } => (
|
||||
format!("{} of {}", vm::chat::size_text(*done), vm::chat::size_text(*size)),
|
||||
"running",
|
||||
if *size > 0 { *done as f32 / *size as f32 } else { 0.0 },
|
||||
),
|
||||
TransferState::Done { size, .. } => {
|
||||
(format!("Downloaded · {}", vm::chat::size_text(*size)), "done", 1.0)
|
||||
}
|
||||
TransferState::Failed(e) => (e.clone(), "failed", 0.0),
|
||||
TransferState::Cancelled => ("Cancelled".to_owned(), "failed", 0.0),
|
||||
};
|
||||
(
|
||||
d.index,
|
||||
FileItem {
|
||||
name: d.name.clone().into(),
|
||||
detail: detail.into(),
|
||||
index: d.index as i32,
|
||||
state: status.into(),
|
||||
progress,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Tabs and the shown tab's messages.
|
||||
pub(crate) fn refresh_chat(&self) {
|
||||
let Some(ui) = self.ui.upgrade() else { return };
|
||||
let bridge = ui.global::<Bridge>();
|
||||
let Some(view) = self.view() else {
|
||||
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 = self.models.no_chat.model();
|
||||
if bridge.get_messages() != empty {
|
||||
bridge.set_messages(empty);
|
||||
}
|
||||
bridge.set_unread_index(-1);
|
||||
return;
|
||||
};
|
||||
// Private chats are on the messages page, not in the strip.
|
||||
let (strip, current) =
|
||||
vm::chat::strip(view.tabs.iter().map(|t| &t.target), view.current_tab);
|
||||
let tabs: Vec<ChatTab> = strip
|
||||
.iter()
|
||||
.map(|&i| &view.tabs[i])
|
||||
.map(|t| {
|
||||
let (last, time) = t
|
||||
.messages
|
||||
.last()
|
||||
.map(|m| vm::chat::preview(&m.message.message))
|
||||
.unwrap_or_default();
|
||||
(t, last, time)
|
||||
})
|
||||
.map(|(t, last, time)| {
|
||||
let channel = match t.target {
|
||||
ChatTarget::Channel(cid) => view.presence.channels.get(&cid),
|
||||
_ => None,
|
||||
};
|
||||
ChatTab {
|
||||
last: last.into(),
|
||||
time: time.into(),
|
||||
title: t.title.clone().into(),
|
||||
name: vm::chat::tab_name(&t.title, &t.target).into(),
|
||||
kind: match t.target {
|
||||
ChatTarget::Server => 0,
|
||||
ChatTarget::Channel(_) => 1,
|
||||
ChatTarget::Private(_) => 2,
|
||||
},
|
||||
id: match t.target {
|
||||
ChatTarget::Channel(cid) => cid as i32,
|
||||
_ => 0,
|
||||
},
|
||||
unread: t.unread,
|
||||
topic: channel.and_then(|c| c.topic.clone()).unwrap_or_default().into(),
|
||||
banner: vm::tree::banner(
|
||||
&view.pictures,
|
||||
channel.and_then(|c| c.banner_gfx_url.as_deref()),
|
||||
),
|
||||
banner_mode: channel.map_or(0, |c| vm::tree::banner_mode(c.banner_mode)),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
self.models.tabs.sync(&tabs);
|
||||
*self.models.strip.borrow_mut() = strip;
|
||||
if bridge.get_current_tab() != current {
|
||||
bridge.set_current_tab(current);
|
||||
}
|
||||
bridge.set_current_chat(view.current_tab as i32);
|
||||
let tab = &view.tabs[view.current_tab];
|
||||
// Sessions without stored history push their lines themselves.
|
||||
let mut divider = None;
|
||||
if view.has_history() {
|
||||
let lines = self.lines_of(view, tab, true);
|
||||
divider = lines.iter().position(|l| l.unread_start);
|
||||
tab.lines.sync(&lines);
|
||||
}
|
||||
let lines = tab.lines.model();
|
||||
if bridge.get_messages() != lines {
|
||||
bridge.set_messages(lines);
|
||||
}
|
||||
// The "New" divider: how many came from there on, and when.
|
||||
let new = tab
|
||||
.divider
|
||||
.and_then(|d| tab.messages.iter().position(|m| m.message.id == d))
|
||||
.map_or(&[][..], |i| &tab.messages[i..]);
|
||||
let session = self.state.current.unwrap_or_default();
|
||||
let count = new.iter().filter(|m| !self.is_own(session, &m.message.message)).count();
|
||||
bridge.set_unread_index(divider.map_or(-1, |i| i as i32));
|
||||
bridge.set_unread_count(count as i32);
|
||||
bridge.set_unread_since(
|
||||
new.first()
|
||||
.map(|m| vm::chat::since_time(m.message.message.ts_ms))
|
||||
.unwrap_or_default()
|
||||
.into(),
|
||||
);
|
||||
bridge.set_more_history(view.has_history() && !tab.complete);
|
||||
bridge.set_loading_history(tab.loading);
|
||||
bridge.set_local_history(
|
||||
view.has_history() && !tab.synced && view.gateway_has(feature::HISTORY),
|
||||
);
|
||||
bridge.set_has_pins(view.gateway_has(feature::PINS));
|
||||
bridge.set_has_reactions(view.gateway_has(feature::REACTIONS));
|
||||
bridge.set_has_topics(view.gateway_has(feature::TOPICS));
|
||||
bridge.set_pins_loading(!tab.pins_loaded && view.gateway_has(feature::PINS));
|
||||
bridge.set_topics_loading(!tab.topics_loaded && view.gateway_has(feature::TOPICS));
|
||||
bridge.set_pins_count(vm::chat::known_count(tab.pins_loaded, tab.pins.len()));
|
||||
bridge.set_topics_count(vm::chat::known_count(tab.topics_loaded, tab.topics.len()));
|
||||
let pins: Vec<PinItem> = tab
|
||||
.pins
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let avatar =
|
||||
p.message.message.author_uid.as_ref().and_then(|u| view.avatars.get(u));
|
||||
let ctx = LineCtx {
|
||||
key: p.key,
|
||||
avatar: vm::avatar::image(avatar),
|
||||
gateway: true,
|
||||
..Default::default()
|
||||
};
|
||||
PinItem {
|
||||
line: vm::chat::history_line(&p.message, None, &ctx),
|
||||
by: format!("Pinned by {} · {}", p.by, vm::chat::time_of(p.ts_ms)).into(),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
self.models.pins.sync(&pins);
|
||||
let filter = self.state.topic_filter.trim().to_lowercase();
|
||||
let now = chrono::Utc::now().timestamp_millis();
|
||||
let topics: Vec<vm::bridge::TopicItem> = tab
|
||||
.topics
|
||||
.iter()
|
||||
.filter(|t| filter.is_empty() || t.title.to_lowercase().contains(&filter))
|
||||
.map(|t| vm::bridge::TopicItem {
|
||||
id: t.id as i32,
|
||||
title: t.title.clone().into(),
|
||||
creator: t.creator.name.clone().into(),
|
||||
detail: format!(
|
||||
"{} {} · by {}",
|
||||
t.message_count,
|
||||
if t.message_count == 1 { "message" } else { "messages" },
|
||||
t.creator.name
|
||||
)
|
||||
.into(),
|
||||
activity: format!("Last active {}", ago(t.last_activity_ms)).into(),
|
||||
recent: now - t.last_activity_ms < 3_600_000,
|
||||
archived: t.archived,
|
||||
})
|
||||
.collect();
|
||||
self.models.topics.sync(&topics);
|
||||
bridge.set_current_topic(tab.topic.map_or(-1, |t| t as i32));
|
||||
bridge.set_topic_title(
|
||||
tab.topic
|
||||
.and_then(|t| tab.topics.iter().find(|i| i.id == t))
|
||||
.map(|t| t.title.clone())
|
||||
.unwrap_or_default()
|
||||
.into(),
|
||||
);
|
||||
self.models.topic_messages.sync(&self.lines_of(view, tab, false));
|
||||
}
|
||||
|
||||
/// A link in a message was clicked (`masked`: its text shows something
|
||||
/// else, [`vm::bbcode::is_masked`]). A page on the web opens in the
|
||||
/// browser, a masked one once the user saw where it goes (Nav.link-open);
|
||||
/// a TeamSpeak link in Voelin ([`App::open_link`]).
|
||||
pub(crate) fn open_link_text(&mut self, link: &str, masked: bool) {
|
||||
match vm::bbcode::classify_link(link) {
|
||||
LinkKind::Web(url) if masked => {
|
||||
if let Some(ui) = self.ui.upgrade() {
|
||||
let nav = ui.global::<Nav>();
|
||||
nav.set_link_host(vm::bbcode::link_host(&url).into());
|
||||
nav.set_link_url(url.into());
|
||||
nav.set_link_open(true);
|
||||
}
|
||||
}
|
||||
LinkKind::Web(url) => {
|
||||
if let Err(e) = self.open_url(&url) {
|
||||
self.set_status(format!("Cannot open the link: {e}"));
|
||||
}
|
||||
}
|
||||
LinkKind::Server(url) => self.open_link(&url),
|
||||
// A file opens from its card.
|
||||
LinkKind::File | LinkKind::Refused => {}
|
||||
}
|
||||
}
|
||||
|
||||
// What is read.
|
||||
|
||||
/// After anything that can change which chat is on screen (a tab, a
|
||||
/// server, the page, the window's focus): the chat left is stored and
|
||||
/// loses its divider; the one on screen, in the focused window, is read.
|
||||
/// `true` if a tab changed ([`vm::chat::logic::track_reading`]).
|
||||
pub(crate) fn track_reading(&mut self) -> bool {
|
||||
self.transition(vm::chat::logic::track_reading)
|
||||
}
|
||||
|
||||
/// The current chat came on screen or left it (`Nav.chat-shown`).
|
||||
pub(crate) fn chat_shown_changed(&mut self) {
|
||||
if self.track_reading() {
|
||||
self.refresh_chat();
|
||||
self.refresh_servers();
|
||||
}
|
||||
}
|
||||
|
||||
/// The window gained or lost the focus (winit's events: the desktop
|
||||
/// only).
|
||||
#[cfg(not(target_os = "android"))]
|
||||
pub(crate) fn window_focused(&mut self, focused: bool) {
|
||||
self.state.focused = focused;
|
||||
if self.track_reading() {
|
||||
self.refresh_chat();
|
||||
self.refresh_servers();
|
||||
}
|
||||
}
|
||||
|
||||
/// The current chat is read (the bar over its messages): the divider
|
||||
/// goes.
|
||||
pub(crate) fn mark_read(&mut self) {
|
||||
let Some(id) = self.state.current else { return };
|
||||
let Some(view) = self.state.sessions.get_mut(&id) else { return };
|
||||
let index = view.current_tab;
|
||||
let tab = &mut view.tabs[index];
|
||||
tab.divider = None;
|
||||
tab.catch_up();
|
||||
self.save_read(id, index);
|
||||
self.refresh_chat();
|
||||
self.refresh_servers();
|
||||
}
|
||||
|
||||
/// Store where tab `index` of session `id` was read, if that moved.
|
||||
pub(crate) fn save_read(&mut self, id: i64, index: usize) {
|
||||
self.transition(|state, cx| vm::chat::logic::save_read(state, cx, id, index));
|
||||
}
|
||||
|
||||
/// Store where every chat of session `id` was read (it ended, or the
|
||||
/// app exits).
|
||||
pub(crate) fn save_reads(&mut self, id: i64) {
|
||||
self.transition(|state, cx| vm::chat::logic::save_reads(state, cx, id));
|
||||
}
|
||||
|
||||
// Gateway features of a chat.
|
||||
|
||||
/// A request to the current session's gateway.
|
||||
fn gateway(&self, request: GatewayRequest) {
|
||||
self.command(|session| Command::Gateway { session, request });
|
||||
}
|
||||
|
||||
/// The message a Slint row stands for, in the current chat.
|
||||
fn message_of(&self, key: i32) -> Option<&HistoryMessage> {
|
||||
let view = self.view()?;
|
||||
view.tabs.get(view.current_tab)?.message(key)
|
||||
}
|
||||
|
||||
/// Add or remove our reaction to a message.
|
||||
pub(crate) fn react(&mut self, key: i32, emoji: String) {
|
||||
let Some(message) = self.message_of(key) else { return };
|
||||
let Some(message_id) = message.remote_id else { return };
|
||||
let had = message.reactions.iter().any(|r| r.emoji == emoji && r.me);
|
||||
self.gateway(if had {
|
||||
GatewayRequest::Unreact { message_id, emoji }
|
||||
} else {
|
||||
GatewayRequest::React { message_id, emoji }
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) fn pin(&mut self, key: i32, on: bool) {
|
||||
let Some(message) = self.message_of(key) else { return };
|
||||
let Some(message_id) = message.remote_id else { return };
|
||||
self.gateway(if on {
|
||||
GatewayRequest::Pin { message_id }
|
||||
} else {
|
||||
GatewayRequest::Unpin { message_id }
|
||||
});
|
||||
}
|
||||
|
||||
/// Ask the gateway for the current chat's pins and topics until it sent
|
||||
/// them, so the header counts them before their drawers are opened.
|
||||
pub(crate) fn prefetch_counts(&mut self) {
|
||||
self.transition(|state, cx| vm::chat::logic::prefetch_counts(state, cx));
|
||||
}
|
||||
|
||||
/// Open the pins of the current chat (loading them once).
|
||||
pub(crate) fn open_pins(&mut self) {
|
||||
let Some(view) = self.view() else { return };
|
||||
let tab = &view.tabs[view.current_tab];
|
||||
if !tab.pins_loaded {
|
||||
let target = tab.target.clone();
|
||||
self.gateway(GatewayRequest::Pins { target });
|
||||
}
|
||||
self.refresh_chat();
|
||||
}
|
||||
|
||||
/// Highlight a pinned message in the chat.
|
||||
pub(crate) fn jump_to_pin(&mut self, key: i32) {
|
||||
let Some(view) = self.view_mut() else { return };
|
||||
let tab = &mut view.tabs[view.current_tab];
|
||||
tab.marked = tab.pins.iter().find(|p| p.key == key).map(|p| p.message.id);
|
||||
// The message is in the chat, not in an open topic.
|
||||
if tab.topic.take().is_some() {
|
||||
tab.topic_messages.clear();
|
||||
}
|
||||
// Older than what is loaded: only highlighted once it is. The server
|
||||
// chat's first lines are the server's.
|
||||
let row = tab.marked.and_then(|id| tab.messages.iter().position(|m| m.message.id == id));
|
||||
let first = match tab.target {
|
||||
ChatTarget::Server => vm::chat::server_texts(&view.presence.server).len(),
|
||||
_ => 0,
|
||||
};
|
||||
let row = row.map(|row| row + first);
|
||||
self.refresh_chat();
|
||||
if let (Some(row), Some(ui)) = (row, self.ui.upgrade()) {
|
||||
let bridge = ui.global::<Bridge>();
|
||||
bridge.set_jump_index(row as i32);
|
||||
bridge.set_jump_requests(bridge.get_jump_requests().wrapping_add(1));
|
||||
}
|
||||
}
|
||||
|
||||
/// The topics drawer's search.
|
||||
pub(crate) fn search_topics(&mut self, text: String) {
|
||||
if self.state.topic_filter != text {
|
||||
self.state.topic_filter = text;
|
||||
self.refresh_chat();
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn open_topics(&mut self) {
|
||||
let Some(view) = self.view() else { return };
|
||||
let tab = &view.tabs[view.current_tab];
|
||||
if !tab.topics_loaded {
|
||||
let target = tab.target.clone();
|
||||
self.gateway(GatewayRequest::Topics { target, include_archived: false });
|
||||
}
|
||||
self.refresh_chat();
|
||||
}
|
||||
|
||||
/// Show a topic's messages (`-1` goes back to the chat).
|
||||
pub(crate) fn open_topic(&mut self, id: i32) {
|
||||
let Some(view) = self.view_mut() else { return };
|
||||
let tab = &mut view.tabs[view.current_tab];
|
||||
tab.topic_messages.clear();
|
||||
tab.topic = (id >= 0).then_some(id as i64);
|
||||
let target = tab.target.clone();
|
||||
if let Some(topic) = tab.topic {
|
||||
self.gateway(GatewayRequest::TopicHistory { target, topic, before: None, limit: None });
|
||||
}
|
||||
self.refresh_chat();
|
||||
}
|
||||
|
||||
pub(crate) fn send_topic_message(&mut self, text: String) {
|
||||
let Some(view) = self.view() else { return };
|
||||
let tab = &view.tabs[view.current_tab];
|
||||
let (Some(topic), target) = (tab.topic, tab.target.clone()) else { return };
|
||||
self.gateway(GatewayRequest::Post { target, text, topic: Some(topic) });
|
||||
}
|
||||
|
||||
/// Start a topic from a message (`key` < 0: a standalone topic).
|
||||
pub(crate) fn create_topic(&mut self, key: i32, title: String) {
|
||||
let Some(view) = self.view() else { return };
|
||||
let target = view.tabs[view.current_tab].target.clone();
|
||||
let message_id = self.message_of(key).and_then(|m| m.remote_id);
|
||||
self.gateway(GatewayRequest::CreateTopic { target, title, message_id });
|
||||
}
|
||||
|
||||
// Files in chat.
|
||||
|
||||
/// Download a file a message links, into the download folder.
|
||||
pub(crate) fn download_file(&mut self, key: i32, index: i32) {
|
||||
let Some(id) = self.state.current else { return };
|
||||
let index = index.max(0) as usize;
|
||||
let Some(file) =
|
||||
self.message_of(key).and_then(|m| m.message.file_refs().into_iter().nth(index))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let dir = dirs::download_dir().unwrap_or_else(|| PathBuf::from("."));
|
||||
let path = dir.join(&file.name);
|
||||
let view = self.state.sessions.entry(id).or_default();
|
||||
let transfer = view.next_transfer;
|
||||
view.next_transfer += 1;
|
||||
view.downloads.insert(
|
||||
transfer,
|
||||
Download { key, index, name: file.name.clone(), state: TransferState::Requested },
|
||||
);
|
||||
self.engine.send(Command::DownloadChatFile {
|
||||
session: id as u64,
|
||||
transfer,
|
||||
file,
|
||||
password: None,
|
||||
to: DownloadTo::Path { path, resume: false },
|
||||
});
|
||||
self.refresh_chat();
|
||||
}
|
||||
|
||||
/// Attach a file to the current channel chat: ask for one, upload it
|
||||
/// into the channel and post its link.
|
||||
pub(crate) fn attach_file(&mut self) {
|
||||
let Some(id) = self.state.current else { return };
|
||||
let Some(view) = self.state.sessions.get(&id) else { return };
|
||||
let ChatTarget::Channel(channel) = view.tabs[view.current_tab].target else {
|
||||
self.set_status("Files can be attached to a channel's chat.");
|
||||
return;
|
||||
};
|
||||
if !voelin_platform::files::available() {
|
||||
self.set_status("No file chooser on this platform.");
|
||||
return;
|
||||
}
|
||||
let runtime = self.engine.runtime().clone();
|
||||
runtime.spawn(async move {
|
||||
let picked = voelin_platform::files::pick_file("Attach a file").await;
|
||||
crate::app::later(move |app| match picked {
|
||||
Ok(Some(path)) => app.upload(id, channel, path),
|
||||
Ok(None) => {}
|
||||
Err(e) => app.set_status(format!("Could not open the file chooser: {e}")),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// Upload a file into a channel and link it in the chat once it is up.
|
||||
pub(crate) fn upload(&mut self, id: i64, channel: u64, from: PathBuf) {
|
||||
let Some(name) = from.file_name().map(|n| n.to_string_lossy().to_string()) else { return };
|
||||
let view = self.state.sessions.entry(id).or_default();
|
||||
let transfer = view.next_transfer;
|
||||
view.next_transfer += 1;
|
||||
self.state.uploads.insert(transfer, (id, channel, name.clone()));
|
||||
self.engine.send(Command::UploadFile {
|
||||
session: id as u64,
|
||||
transfer,
|
||||
channel,
|
||||
password: None,
|
||||
path: format!("/{name}"),
|
||||
from,
|
||||
overwrite: true,
|
||||
resume: false,
|
||||
});
|
||||
self.set_status(format!("Uploading {name}…"));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn relative_times() {
|
||||
let now = chrono::Utc::now().timestamp_millis();
|
||||
assert_eq!(ago(now), "just now");
|
||||
assert_eq!(ago(now - 3 * 60_000), "3 min ago");
|
||||
assert_eq!(ago(now - 3 * 3_600_000), "3 hours ago");
|
||||
assert_eq!(ago(now - 36 * 3_600_000), "yesterday");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
//! The Slint side of the chat: the Bridge writes of the tabs, the lines and
|
||||
//! the drawers, and the callbacks' ways into the transitions of
|
||||
//! `voelin_ui_vm::chat::logic`.
|
||||
|
||||
use slint::ComponentHandle;
|
||||
use voelin_core::{HistoryMessage, HistorySource};
|
||||
use voelin_model::{ChatMessage, ChatTarget};
|
||||
|
||||
use crate::app::{App, Bridge, Nav, SessionView, Tab};
|
||||
use crate::settings::UI_IMAGE_PREVIEW_KB;
|
||||
use crate::vm;
|
||||
use crate::vm::bbcode::LinkKind;
|
||||
use crate::vm::bridge::{ChatLine, ChatTab};
|
||||
use crate::vm::chat::logic::{self as logic, LinesFacts};
|
||||
use voelin_core::settings::CACHE_FETCH_IMAGES;
|
||||
|
||||
impl App {
|
||||
/// Open the chat `target` of the current session, and with `focus` show
|
||||
/// it ([`logic::open_chat`]).
|
||||
pub(crate) fn open_chat(&mut self, target: ChatTarget, focus: bool) {
|
||||
self.transition(|state, cx| logic::open_chat(state, cx, target, focus));
|
||||
}
|
||||
|
||||
/// The index of `target`'s tab in session `id`, opened if new (the
|
||||
/// engine then sends its history).
|
||||
pub(crate) fn chat_tab(&mut self, id: i64, target: ChatTarget) -> usize {
|
||||
self.transition(|state, cx| logic::chat_tab(state, cx, id, target))
|
||||
}
|
||||
|
||||
/// The session's tab that tab `index` of the chat strip is
|
||||
/// (`Bridge.tabs`, [`vm::chat::strip`]).
|
||||
pub(crate) fn strip_tab(&self, index: i32) -> Option<usize> {
|
||||
self.models.strip.borrow().get(usize::try_from(index).ok()?).copied()
|
||||
}
|
||||
|
||||
pub(crate) fn select_tab(&mut self, index: usize) {
|
||||
self.transition(|state, cx| logic::select_tab(state, cx, index));
|
||||
}
|
||||
|
||||
pub(crate) fn close_tab(&mut self, index: usize) {
|
||||
self.transition(|state, cx| logic::close_tab(state, cx, index));
|
||||
}
|
||||
|
||||
pub(crate) fn send_message(&mut self, text: String) {
|
||||
self.transition(|state, cx| logic::send_message(state, cx, text));
|
||||
}
|
||||
|
||||
/// A live message of a session without stored history.
|
||||
pub(crate) fn add_message(&mut self, id: i64, message: ChatMessage) {
|
||||
self.transition(|state, cx| logic::add_message(state, cx, id, message));
|
||||
}
|
||||
|
||||
/// Messages the engine stored: added or updated by their local id.
|
||||
pub(crate) fn history_batch(
|
||||
&mut self,
|
||||
id: i64,
|
||||
target: &ChatTarget,
|
||||
messages: Vec<HistoryMessage>,
|
||||
source: HistorySource,
|
||||
complete: bool,
|
||||
) {
|
||||
self.transition(|state, cx| {
|
||||
logic::history_batch(state, cx, id, target, messages, source, complete);
|
||||
});
|
||||
}
|
||||
|
||||
/// The page of messages before the oldest one shown.
|
||||
pub(crate) fn load_older(&mut self) {
|
||||
if let Some(sample) = self.transition(logic::load_older) {
|
||||
// No engine answers in demo mode.
|
||||
crate::dev::answer_older(sample.session, sample.target, sample.oldest);
|
||||
}
|
||||
}
|
||||
|
||||
/// What the lines of a chat need besides the state.
|
||||
fn lines_facts(&self) -> LinesFacts<'_> {
|
||||
LinesFacts {
|
||||
// Pictures on the web show only while pictures are fetched and
|
||||
// shown.
|
||||
pictures_shown: self.prefs.get(&CACHE_FETCH_IMAGES)
|
||||
&& self.prefs.get(&UI_IMAGE_PREVIEW_KB) > 0,
|
||||
pokes: &self.social.pokes,
|
||||
}
|
||||
}
|
||||
|
||||
/// The lines of a tab's messages (`main`) or of its open topic, grouped
|
||||
/// and with everything the row shows (also the stream chat of the
|
||||
/// Stream Studio, studio/).
|
||||
pub(crate) fn lines_of(&self, view: &SessionView, tab: &Tab, main: bool) -> Vec<ChatLine> {
|
||||
logic::lines_of(&self.state, view, tab, main, &self.lines_facts())
|
||||
}
|
||||
|
||||
/// Tabs and the shown tab's messages.
|
||||
pub(crate) fn refresh_chat(&self) {
|
||||
let Some(ui) = self.ui.upgrade() else { return };
|
||||
let bridge = ui.global::<Bridge>();
|
||||
let Some(chat) = logic::chat_view(&self.state, &self.lines_facts()) else {
|
||||
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 = self.models.no_chat.model();
|
||||
if bridge.get_messages() != empty {
|
||||
bridge.set_messages(empty);
|
||||
}
|
||||
bridge.set_unread_index(-1);
|
||||
return;
|
||||
};
|
||||
self.models.tabs.sync(&chat.tabs);
|
||||
*self.models.strip.borrow_mut() = chat.strip;
|
||||
if bridge.get_current_tab() != chat.current {
|
||||
bridge.set_current_tab(chat.current);
|
||||
}
|
||||
bridge.set_current_chat(chat.current_chat);
|
||||
// The tab on screen: its lines are what the chat view shows.
|
||||
if let Some(view) = self.view() {
|
||||
let tab = &view.tabs[view.current_tab];
|
||||
if let Some(lines) = &chat.lines {
|
||||
tab.lines.sync(lines);
|
||||
}
|
||||
let lines = tab.lines.model();
|
||||
if bridge.get_messages() != lines {
|
||||
bridge.set_messages(lines);
|
||||
}
|
||||
}
|
||||
bridge.set_unread_index(chat.unread_index);
|
||||
bridge.set_unread_count(chat.unread_count);
|
||||
bridge.set_unread_since(chat.unread_since.into());
|
||||
bridge.set_more_history(chat.more_history);
|
||||
bridge.set_loading_history(chat.loading_history);
|
||||
bridge.set_local_history(chat.local_history);
|
||||
bridge.set_has_pins(chat.has_pins);
|
||||
bridge.set_has_reactions(chat.has_reactions);
|
||||
bridge.set_has_topics(chat.has_topics);
|
||||
bridge.set_pins_loading(chat.pins_loading);
|
||||
bridge.set_topics_loading(chat.topics_loading);
|
||||
bridge.set_pins_count(chat.pins_count);
|
||||
bridge.set_topics_count(chat.topics_count);
|
||||
self.models.pins.sync(&chat.pins);
|
||||
self.models.topics.sync(&chat.topics);
|
||||
bridge.set_current_topic(chat.current_topic);
|
||||
bridge.set_topic_title(chat.topic_title.into());
|
||||
self.models.topic_messages.sync(&chat.topic_lines);
|
||||
}
|
||||
|
||||
/// A link in a message was clicked (`masked`: its text shows something
|
||||
/// else, [`vm::bbcode::is_masked`]). A page on the web opens in the
|
||||
/// browser, a masked one once the user saw where it goes (Nav.link-open);
|
||||
/// a TeamSpeak link in Voelin ([`App::open_link`]).
|
||||
pub(crate) fn open_link_text(&mut self, link: &str, masked: bool) {
|
||||
match vm::bbcode::classify_link(link) {
|
||||
LinkKind::Web(url) if masked => {
|
||||
if let Some(ui) = self.ui.upgrade() {
|
||||
let nav = ui.global::<Nav>();
|
||||
nav.set_link_host(vm::bbcode::link_host(&url).into());
|
||||
nav.set_link_url(url.into());
|
||||
nav.set_link_open(true);
|
||||
}
|
||||
}
|
||||
LinkKind::Web(url) => {
|
||||
if let Err(e) = self.open_url(&url) {
|
||||
self.set_status(format!("Cannot open the link: {e}"));
|
||||
}
|
||||
}
|
||||
LinkKind::Server(url) => self.open_link(&url),
|
||||
// A file opens from its card.
|
||||
LinkKind::File | LinkKind::Refused => {}
|
||||
}
|
||||
}
|
||||
|
||||
// What is read.
|
||||
|
||||
/// After anything that can change which chat is on screen (a tab, a
|
||||
/// server, the page, the window's focus): the chat left is stored and
|
||||
/// loses its divider; the one on screen, in the focused window, is read.
|
||||
/// `true` if a tab changed ([`logic::track_reading`]).
|
||||
pub(crate) fn track_reading(&mut self) -> bool {
|
||||
self.transition(logic::track_reading)
|
||||
}
|
||||
|
||||
/// The current chat came on screen or left it (`Nav.chat-shown`).
|
||||
pub(crate) fn chat_shown_changed(&mut self) {
|
||||
self.transition(logic::chat_shown_changed);
|
||||
}
|
||||
|
||||
/// The window gained or lost the focus (winit's events: the desktop
|
||||
/// only).
|
||||
#[cfg(not(target_os = "android"))]
|
||||
pub(crate) fn window_focused(&mut self, focused: bool) {
|
||||
self.transition(|state, cx| logic::window_focused(state, cx, focused));
|
||||
}
|
||||
|
||||
/// The current chat is read (the bar over its messages): the divider
|
||||
/// goes.
|
||||
pub(crate) fn mark_read(&mut self) {
|
||||
self.transition(logic::mark_read);
|
||||
}
|
||||
|
||||
/// Store where every chat of session `id` was read (it ended, or the
|
||||
/// app exits).
|
||||
pub(crate) fn save_reads(&mut self, id: i64) {
|
||||
self.transition(|state, cx| logic::save_reads(state, cx, id));
|
||||
}
|
||||
|
||||
// Gateway features of a chat.
|
||||
|
||||
/// Add or remove our reaction to a message.
|
||||
pub(crate) fn react(&mut self, key: i32, emoji: String) {
|
||||
self.transition(|state, cx| logic::react(state, cx, key, emoji));
|
||||
}
|
||||
|
||||
pub(crate) fn pin(&mut self, key: i32, on: bool) {
|
||||
self.transition(|state, cx| logic::pin(state, cx, key, on));
|
||||
}
|
||||
|
||||
/// Ask the gateway for the current chat's pins and topics until it sent
|
||||
/// them, so the header counts them before their drawers are opened.
|
||||
pub(crate) fn prefetch_counts(&mut self) {
|
||||
self.transition(|state, cx| logic::prefetch_counts(state, cx));
|
||||
}
|
||||
|
||||
/// Open the pins of the current chat (loading them once).
|
||||
pub(crate) fn open_pins(&mut self) {
|
||||
self.transition(|state, cx| logic::open_pins(state, cx));
|
||||
}
|
||||
|
||||
/// Highlight a pinned message in the chat.
|
||||
pub(crate) fn jump_to_pin(&mut self, key: i32) {
|
||||
let row = self.transition(|state, cx| logic::jump_to_pin(state, cx, key));
|
||||
if let (Some(row), Some(ui)) = (row, self.ui.upgrade()) {
|
||||
let bridge = ui.global::<Bridge>();
|
||||
bridge.set_jump_index(row as i32);
|
||||
bridge.set_jump_requests(bridge.get_jump_requests().wrapping_add(1));
|
||||
}
|
||||
}
|
||||
|
||||
/// The topics drawer's search.
|
||||
pub(crate) fn search_topics(&mut self, text: String) {
|
||||
self.transition(|state, cx| logic::search_topics(state, cx, text));
|
||||
}
|
||||
|
||||
pub(crate) fn open_topics(&mut self) {
|
||||
self.transition(|state, cx| logic::open_topics(state, cx));
|
||||
}
|
||||
|
||||
/// Show a topic's messages (`-1` goes back to the chat).
|
||||
pub(crate) fn open_topic(&mut self, id: i32) {
|
||||
self.transition(|state, cx| logic::open_topic(state, cx, id));
|
||||
}
|
||||
|
||||
pub(crate) fn send_topic_message(&mut self, text: String) {
|
||||
self.transition(|state, cx| logic::send_topic_message(state, cx, text));
|
||||
}
|
||||
|
||||
/// Start a topic from a message (`key` < 0: a standalone topic).
|
||||
pub(crate) fn create_topic(&mut self, key: i32, title: String) {
|
||||
self.transition(|state, cx| logic::create_topic(state, cx, key, title));
|
||||
}
|
||||
|
||||
// Files in chat.
|
||||
|
||||
/// Download a file a message links, into the download folder.
|
||||
pub(crate) fn download_file(&mut self, key: i32, index: i32) {
|
||||
let dir = dirs::download_dir().unwrap_or_else(|| std::path::PathBuf::from("."));
|
||||
self.transition(|state, cx| logic::download_file(state, cx, key, index, &dir));
|
||||
}
|
||||
|
||||
/// Attach a file to the current channel chat: ask for one, upload it
|
||||
/// into the channel and post its link.
|
||||
pub(crate) fn attach_file(&mut self) {
|
||||
let (id, channel) = match logic::attach_target(&self.state) {
|
||||
Ok(Some(target)) => target,
|
||||
Ok(None) => return,
|
||||
Err(reason) => {
|
||||
self.set_status(reason);
|
||||
return;
|
||||
}
|
||||
};
|
||||
if !voelin_platform::files::available() {
|
||||
self.set_status("No file chooser on this platform.");
|
||||
return;
|
||||
}
|
||||
let runtime = self.engine.runtime().clone();
|
||||
runtime.spawn(async move {
|
||||
let picked = voelin_platform::files::pick_file("Attach a file").await;
|
||||
crate::app::later(move |app| match picked {
|
||||
Ok(Some(path)) => app.upload(id, channel, path),
|
||||
Ok(None) => {}
|
||||
Err(e) => app.set_status(format!("Could not open the file chooser: {e}")),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// Upload a file into a channel and link it in the chat once it is up.
|
||||
pub(crate) fn upload(&mut self, id: i64, channel: u64, from: std::path::PathBuf) {
|
||||
self.transition(|state, cx| logic::upload(state, cx, id, channel, from));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
//! Chat: tabs per session (server, channels, private chats), their
|
||||
//! messages, and what a gateway adds to them (pins, reactions, topics).
|
||||
//! What the state does is in `voelin_ui_vm::chat::logic`; `bind` has the
|
||||
//! Bridge writes and the models.
|
||||
//!
|
||||
//! The chat strip shows the server's and the channels' tabs; a private chat
|
||||
//! is the current tab only while the messages page shows it (messages.rs).
|
||||
//! The engine keeps the history: a tab holds the messages it was given,
|
||||
//! ordered by `(ts_ms, id)`, and the lines of the selected tab are rebuilt
|
||||
//! from them and synced ([`crate::bind::rows::Rows::sync`]), which touches
|
||||
//! only the rows that changed.
|
||||
|
||||
mod bind;
|
||||
@@ -840,36 +840,4 @@ impl App {
|
||||
self.engine.send(Command::ListOfflineMessages { session: id as u64, request });
|
||||
}
|
||||
}
|
||||
|
||||
/// 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, vm::bridge::ChatLine)> {
|
||||
self.social
|
||||
.pokes
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, p)| p.session == session && p.uid.as_deref() == Some(uid))
|
||||
.map(|(i, p)| {
|
||||
let text = if p.message.is_empty() {
|
||||
"👋 poked you".to_owned()
|
||||
} else {
|
||||
format!("👋 poked you: {}", p.message)
|
||||
};
|
||||
let message = voelin_model::ChatMessage {
|
||||
target: ChatTarget::Private(uid.to_owned()),
|
||||
author_name: p.name.clone(),
|
||||
author_uid: p.uid.clone(),
|
||||
author_id: None,
|
||||
text,
|
||||
ts_ms: p.ts_ms,
|
||||
via_relay: false,
|
||||
blocked: false,
|
||||
};
|
||||
let mut line = vm::chat::line(&message, None);
|
||||
line.key = -1_000_000 - i as i32;
|
||||
line.avatar = self.avatar_of(uid);
|
||||
(p.ts_ms, line)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
@@ -26,16 +26,7 @@ use crate::vm;
|
||||
use crate::vm::bridge::{ContactItem, NoticeItem, SearchItem};
|
||||
use crate::vm::social::{ago, matches, mentions, plain};
|
||||
|
||||
/// A poke we got.
|
||||
pub(crate) struct Poke {
|
||||
pub session: i64,
|
||||
pub uid: Option<String>,
|
||||
pub name: String,
|
||||
pub message: String,
|
||||
pub ts_ms: i64,
|
||||
}
|
||||
|
||||
pub(crate) use vm::social::{NoticeKind, NoticeTarget, Spot};
|
||||
pub(crate) use vm::social::{NoticeKind, NoticeTarget, Poke, Spot};
|
||||
|
||||
/// A notification of the bell.
|
||||
pub(crate) struct Notice {
|
||||
@@ -181,7 +172,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) -> vm::ImageRef {
|
||||
vm::avatar::image(self.state.sessions.values().find_map(|v| v.avatars.get(uid)))
|
||||
vm::social::avatar_of(&self.state, uid)
|
||||
}
|
||||
|
||||
/// A server's name: its bookmark's, else what the session calls it.
|
||||
|
||||
+7
-5
@@ -29,7 +29,8 @@ crates/voelin-ui-vm/ view models and state, no UI toolkit
|
||||
previews.rs pictures linked in chat: which to fetch, the transfers
|
||||
servers.rs tree.rs chat/mod.rs social.rs home.rs streams/mod.rs avatar.rs studio/mod.rs
|
||||
pure view models (engine state → bridge structs), unit-tested
|
||||
chat/logic.rs chat tabs, messages and what is read, pins and topics, files
|
||||
chat/logic.rs chat tabs, messages and what is read, pins and topics, files; the
|
||||
chat view (tabs, lines, divider, drawers) and the user's moves
|
||||
streams/logic.rs the streams we share and watch: their state, the events and the
|
||||
user's choices, the streams panel's, the share card's and the
|
||||
viewer's rows and texts
|
||||
@@ -66,11 +67,12 @@ crates/voelin-ui/ the Slint front end
|
||||
a `voelin_ui_vm::state::AppState` and the window
|
||||
host.rs SlintHost (the answers the transitions ask for), `App::apply_event`,
|
||||
`transition` and `perform`: doing what an `Update` says
|
||||
servers.rs chat.rs members.rs settings_page.rs appearance.rs
|
||||
servers.rs members.rs settings_page.rs appearance.rs
|
||||
home.rs social.rs messages.rs events.rs previews.rs popout.rs
|
||||
the Slint side of each area (social.rs: contacts, the bell and the
|
||||
search; previews.rs: pictures in chat; popout.rs: the stream's own
|
||||
window)
|
||||
chat/ mod.rs, bind.rs: the chat view's Bridge writes and models
|
||||
settings_pages/ mod.rs (Pages), bind.rs: the settings pages on the Bridge
|
||||
streams/ mod.rs (Share: the capture), bind.rs: the streams panel, the share
|
||||
dialog and the viewer on the Bridge, the capture and the decoder
|
||||
@@ -148,7 +150,7 @@ this file is `voelin_ui_vm::chat`. The boundary:
|
||||
settings service, the `AppState` and plain rows; they return rows,
|
||||
commands or messages for the status line, and write no Bridge) and
|
||||
`<area>/bind.rs` in `voelin-ui` (the Bridge and model writes, windows,
|
||||
timers, threads, engine commands). Done: `settings_pages`, `studio` and `streams`.
|
||||
timers, threads, engine commands). Done: `settings_pages`, `studio`, `streams` and `chat`.
|
||||
|
||||
The pure code is tested in `voelin-ui-vm` (`cargo test -p voelin-ui-vm`,
|
||||
no display); the Slint crate's tests are what needs the window types.
|
||||
@@ -169,7 +171,6 @@ the same shape as `settings_pages` and `studio`: move the decisions into
|
||||
|
||||
| File | `.set_` calls | What it mixes |
|
||||
|---|---|---|
|
||||
| `chat.rs` | 33 | the chat view: lines, the unread divider, pins, topics and downloads (the engine's history batches, the reads and the gateway's pins and topics are in `chat/logic.rs`) |
|
||||
| `app.rs` | 31 | setup, the status line, the toolbar and tree refreshes (the event dispatch is `vm::events::apply`) |
|
||||
| `servers.rs` | 32 | the rail, the server dialog and the channel tree's refresh (the server's name, icon and gateway, joining again and the password are in `events`) |
|
||||
| `settings_page.rs` | 26 | the audio settings page and the devices |
|
||||
@@ -185,7 +186,8 @@ Before the work on `voelin-ui-vm` began, `studio.rs` had 64 `.set_` calls
|
||||
and `settings_pages.rs` 52 (the two with the most, then `streams.rs` with 45;
|
||||
62 was `studio.rs` once the view models had moved, two setters having
|
||||
gone with them). Their `bind.rs` files still show 58 and 51 (and
|
||||
`streams/bind.rs`, split from the 45 of `streams.rs`, 38): the Bridge and
|
||||
`streams/bind.rs`, split from the 45 of `streams.rs`, 38, and
|
||||
`chat/bind.rs`, from the 38 of `chat.rs`, 31): the Bridge and
|
||||
model writes stay where the toolkit is, and what each write says now comes
|
||||
from `logic.rs`, which has tests of its own.
|
||||
|
||||
|
||||
Reference in new issue
Block a user