ui: BBCode in chat, and the welcome message as the server chat's first line
Other clients format chat with BBCode, and it showed as raw tags; only file links were taken out. One parser, vm/bbcode.rs, now reads every message into a Doc of blocks (lines, quotes, code, list items, rules) of styled spans, which the chat draws with one MessageText (also in the pins drawer and the studio's chat), and which previews, notifications and the home's news show on one line. Only known tags are read, so relay prefixes such as [Nova] stay. Emoji are split per span, so a message with emoji keeps its line breaks. [img] pictures on the web come through the engine's picture cache (Command::FetchPicture), within ui.image_preview_kb and only with cache.fetch_images; otherwise they stay links. Built lines are kept per message and revision. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ
This commit is contained in:
22 files changed
+2350
-243
No files matched your search
@@ -78,6 +78,10 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
|
||||
empty.
|
||||
- While a priority speaker talks, everyone else (watched streams too) is
|
||||
dimmed by the server's setting, as in TeamSpeak; nobody was dimmed before.
|
||||
- BBCode from other clients shows as formatting (bold, colours, links,
|
||||
quotes, lists, code, pictures) instead of raw tags, and the server's
|
||||
welcome message opens the server chat. Messages with emoji keep their
|
||||
line breaks.
|
||||
- Joining a friend in a subchannel of a server without voice connects into
|
||||
that subchannel; it connected into the default channel.
|
||||
|
||||
|
||||
@@ -371,6 +371,14 @@ pub enum Command {
|
||||
session: SessionId,
|
||||
client_uid: String,
|
||||
},
|
||||
/// Get a picture on the web that a chat message shows (`[img]`) into
|
||||
/// the cache ([`Event::PictureReady`]) while `cache.fetch_images` is on;
|
||||
/// one larger than `max_bytes` is not reported.
|
||||
FetchPicture {
|
||||
session: SessionId,
|
||||
url: String,
|
||||
max_bytes: u64,
|
||||
},
|
||||
/// Our offline messages ([`Event::OfflineMessages`]); see [`offline`].
|
||||
ListOfflineMessages {
|
||||
session: SessionId,
|
||||
@@ -680,9 +688,10 @@ pub enum Event {
|
||||
},
|
||||
/// A picture on the web is in the cache: the host banner
|
||||
/// ([`ServerDetails::banner_gfx_url`]), a channel's
|
||||
/// ([`voelin_model::ChannelInfo::banner_gfx_url`]) or a badge's
|
||||
/// ([`voelin_model::badges::icon_url`]) at `url` (setting
|
||||
/// `cache.fetch_images`). Comes again when the host banner was reloaded
|
||||
/// ([`voelin_model::ChannelInfo::banner_gfx_url`]), a badge's
|
||||
/// ([`voelin_model::badges::icon_url`]) or one a chat message shows
|
||||
/// ([`Command::FetchPicture`]) at `url` (setting `cache.fetch_images`).
|
||||
/// Comes again when the host banner was reloaded
|
||||
/// (`banner_gfx_interval_s`, at least a minute): the file at `path`
|
||||
/// changed.
|
||||
PictureReady {
|
||||
@@ -1044,6 +1053,7 @@ fn command_session(command: &Command) -> SessionId {
|
||||
| Command::CreateDirectory { session, .. }
|
||||
| Command::SetAvatar { session, .. }
|
||||
| Command::FetchAvatar { session, .. }
|
||||
| Command::FetchPicture { session, .. }
|
||||
| Command::ListOfflineMessages { session, .. }
|
||||
| Command::GetOfflineMessage { session, .. }
|
||||
| Command::SendOfflineMessage { session, .. }
|
||||
|
||||
@@ -227,6 +227,10 @@ struct Session {
|
||||
/// Pictures on the web (banners, badges) reported or being fetched, by
|
||||
/// address.
|
||||
pictures: HashSet<String>,
|
||||
/// Pictures on the web that chat messages show, reported or being
|
||||
/// fetched, by address, with the size they may have
|
||||
/// ([`Command::FetchPicture`]).
|
||||
chat_pictures: HashMap<String, u64>,
|
||||
image_epoch: u64,
|
||||
images_enabled: bool,
|
||||
image_retries: HashMap<ImageRequest, ImageRetry>,
|
||||
@@ -265,6 +269,7 @@ impl Session {
|
||||
avatars: HashMap::new(),
|
||||
icons: HashSet::new(),
|
||||
pictures: HashSet::new(),
|
||||
chat_pictures: HashMap::new(),
|
||||
image_epoch: 0,
|
||||
images_enabled: settings.current().get(&CACHE_FETCH_IMAGES),
|
||||
image_retries: HashMap::new(),
|
||||
@@ -676,6 +681,15 @@ impl Session {
|
||||
self.fetch_avatar(&client_uid, &hash, true);
|
||||
}
|
||||
}
|
||||
Command::FetchPicture { url, max_bytes, .. } => {
|
||||
if self.settings.current().get(&CACHE_FETCH_IMAGES)
|
||||
&& cache::picture_key(&url).is_some()
|
||||
&& !self.chat_pictures.contains_key(&url)
|
||||
{
|
||||
self.chat_pictures.insert(url.clone(), max_bytes);
|
||||
self.fetch_picture(&url, false);
|
||||
}
|
||||
}
|
||||
Command::ListOfflineMessages { request, .. } => {
|
||||
if self.voice.is_none() {
|
||||
let result = Err(NO_VOICE.into());
|
||||
@@ -828,6 +842,7 @@ impl Session {
|
||||
self.avatars.clear();
|
||||
self.icons.clear();
|
||||
self.pictures.clear();
|
||||
self.chat_pictures.clear();
|
||||
self.contact_audio.clear();
|
||||
self.priority_audio = Default::default();
|
||||
self.stream_friends.clear();
|
||||
@@ -894,7 +909,18 @@ impl Session {
|
||||
self.voice.is_some() && self.avatars.get(uid) == Some(hash)
|
||||
}
|
||||
ImageRequest::Icon(id) => self.voice.is_some() && self.icons.contains(id),
|
||||
ImageRequest::Picture(url) => self.pictures.contains(url),
|
||||
ImageRequest::Picture(url) => {
|
||||
self.pictures.contains(url) || self.chat_pictures.contains_key(url)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How large the picture at `url` may be: a chat picture as large as
|
||||
/// it was asked for, unless it is also a banner or badge.
|
||||
fn picture_limit(&self, url: &str) -> u64 {
|
||||
match self.chat_pictures.get(url) {
|
||||
Some(max) if !self.pictures.contains(url) => (*max).min(cache::MAX_PICTURE_BYTES),
|
||||
_ => cache::MAX_PICTURE_BYTES,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -926,6 +952,13 @@ impl Session {
|
||||
if !requested && !self.settings.current().get(&CACHE_FETCH_IMAGES) {
|
||||
return;
|
||||
}
|
||||
// A chat picture already in the cache may be larger than
|
||||
// asked for now.
|
||||
if let ImageRequest::Picture(url) = &request
|
||||
&& std::fs::metadata(&path).is_ok_and(|m| m.len() > self.picture_limit(url))
|
||||
{
|
||||
return;
|
||||
}
|
||||
let session = self.id;
|
||||
self.emit(match request {
|
||||
ImageRequest::Avatar { uid: client_uid, hash } => {
|
||||
@@ -960,6 +993,7 @@ impl Session {
|
||||
self.avatars.clear();
|
||||
self.icons.clear();
|
||||
self.pictures.clear();
|
||||
self.chat_pictures.clear();
|
||||
self.image_retries.clear();
|
||||
if let Some((.., timer)) = self.banner_reload.take() {
|
||||
timer.abort();
|
||||
@@ -1069,7 +1103,8 @@ impl Session {
|
||||
let key = cache::server_picture_key(server, url);
|
||||
self.fetch_image(key, Some(file), fresh, waiter);
|
||||
} else {
|
||||
web::fetch(self.cache.current(), url, fresh, max_cache_bytes(&self.settings), waiter);
|
||||
let (max_cache, max) = (max_cache_bytes(&self.settings), self.picture_limit(url));
|
||||
web::fetch(self.cache.current(), url, fresh, max_cache, max, waiter);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2238,6 +2273,50 @@ mod banner_tests {
|
||||
std::fs::remove_dir_all(cache.dir()).unwrap();
|
||||
}
|
||||
|
||||
/// A picture a chat message shows comes only with `cache.fetch_images`,
|
||||
/// is fetched once, and is reported only while it is no larger than
|
||||
/// asked for.
|
||||
#[tokio::test]
|
||||
async fn chat_pictures_obey_policy_and_their_size() {
|
||||
let (mut session, mut events) = session("chat-pictures");
|
||||
let url = "https://example.com/meme.png";
|
||||
let cache = session.cache.current();
|
||||
let key = cache::picture_key(url).unwrap();
|
||||
let Fetch::Download(temp) = cache.fetch(&key, false, Box::new(|_| {})) else {
|
||||
panic!("first download");
|
||||
};
|
||||
std::fs::create_dir_all(temp.parent().unwrap()).unwrap();
|
||||
std::fs::write(&temp, b"cached image").unwrap();
|
||||
cache.finish(&key, &temp, Ok(()), 0);
|
||||
let fetch = |max_bytes| Command::FetchPicture { session: 1, url: url.into(), max_bytes };
|
||||
let ready = |events: &mut broadcast::Receiver<Event>| {
|
||||
let mut ready = false;
|
||||
while let Ok(event) = events.try_recv() {
|
||||
ready |=
|
||||
matches!(event, Event::PictureReady { url: address, .. } if address == url);
|
||||
}
|
||||
ready
|
||||
};
|
||||
session.settings.current().set(&CACHE_FETCH_IMAGES, false).unwrap();
|
||||
session.command(fetch(100));
|
||||
assert!(session.chat_pictures.is_empty());
|
||||
session.settings.current().set(&CACHE_FETCH_IMAGES, true).unwrap();
|
||||
session.command(fetch(100));
|
||||
let completion = session.sources_rx.as_mut().unwrap().recv().await.unwrap();
|
||||
session.source_event(completion);
|
||||
assert!(ready(&mut events));
|
||||
// Asked for again: nothing more.
|
||||
session.command(fetch(100));
|
||||
assert!(session.sources_rx.as_mut().unwrap().try_recv().is_err());
|
||||
// The file is larger than asked for now: not reported.
|
||||
session.forget_images();
|
||||
session.command(fetch(4));
|
||||
let completion = session.sources_rx.as_mut().unwrap().recv().await.unwrap();
|
||||
session.source_event(completion);
|
||||
assert!(!ready(&mut events));
|
||||
std::fs::remove_dir_all(cache.dir()).unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn enabling_images_replays_current_presence_without_server_updates() {
|
||||
let (mut session, mut events) = session("policy-enable");
|
||||
|
||||
@@ -1125,11 +1125,12 @@ pub static CACHE_MAX_MB: Key<u64> = Key::new(
|
||||
|| 256,
|
||||
);
|
||||
|
||||
/// Download the avatars, icons, banners and badges of servers we are on.
|
||||
/// Download the avatars, icons, banners and badges of servers we are on,
|
||||
/// and the pictures their chats show (`[img]`).
|
||||
pub static CACHE_FETCH_IMAGES: Key<bool> = Key::new(
|
||||
"cache.fetch_images",
|
||||
Kind::Bool,
|
||||
"Download avatars, icons, banners and badges of the servers we are on.",
|
||||
"Download avatars, icons, banners and badges of the servers we are on, and pictures in chat.",
|
||||
|| true,
|
||||
);
|
||||
|
||||
|
||||
@@ -54,17 +54,26 @@ static CLIENT: LazyLock<Result<reqwest::Client, String>> = LazyLock::new(|| {
|
||||
|
||||
/// Get the picture at `url` into `cache`, downloading it once however many
|
||||
/// ask (again with `fresh`: it changes at its address); `waiter` is told
|
||||
/// where it is. `max_cache_bytes`: `cache.max_mb` in bytes.
|
||||
pub(crate) fn fetch(cache: Cache, url: &str, fresh: bool, max_cache_bytes: u64, waiter: Waiter) {
|
||||
/// where it is. `max_cache_bytes`: `cache.max_mb` in bytes; `max_bytes`:
|
||||
/// the picture's size at most (up to [`cache::MAX_PICTURE_BYTES`]).
|
||||
pub(crate) fn fetch(
|
||||
cache: Cache,
|
||||
url: &str,
|
||||
fresh: bool,
|
||||
max_cache_bytes: u64,
|
||||
max_bytes: u64,
|
||||
waiter: Waiter,
|
||||
) {
|
||||
let Some(key) = cache::picture_key(url) else {
|
||||
waiter(Err("not an http or https address".into()));
|
||||
return;
|
||||
};
|
||||
let Fetch::Download(temp) = cache.fetch(&key, fresh, waiter) else { return };
|
||||
let url = url.to_owned();
|
||||
let limits = Limits { max_bytes: max_bytes.min(LIMITS.max_bytes), ..LIMITS };
|
||||
tokio::spawn(async move {
|
||||
let _permit = DOWNLOADS.acquire().await.expect("download semaphore stays open");
|
||||
let result = download(&url, &temp, &LIMITS).await;
|
||||
let result = download(&url, &temp, &limits).await;
|
||||
cache.finish(&key, &temp, result, max_cache_bytes);
|
||||
});
|
||||
}
|
||||
@@ -258,18 +267,24 @@ mod tests {
|
||||
Box::new(move |r| tx.send(r).unwrap())
|
||||
};
|
||||
let url = format!("{base}/banner");
|
||||
fetch(cache.clone(), &url, false, 0, waiter(&tx));
|
||||
let max = cache::MAX_PICTURE_BYTES;
|
||||
fetch(cache.clone(), &url, false, 0, max, waiter(&tx));
|
||||
let path = tokio::task::spawn_blocking(move || rx.recv().unwrap()).await.unwrap().unwrap();
|
||||
assert_eq!(path, dir.join(cache::picture_key(&url).unwrap()));
|
||||
assert_eq!(std::fs::read(&path).unwrap(), PNG);
|
||||
// Not on the web: refused at once, nothing cached.
|
||||
let (tx, rx) = mpsc::channel();
|
||||
fetch(cache.clone(), "file:///etc/hostname", false, 0, waiter(&tx));
|
||||
fetch(cache.clone(), "file:///etc/hostname", false, 0, max, waiter(&tx));
|
||||
assert!(rx.recv().unwrap().unwrap_err().contains("http"));
|
||||
// A failed download is reported and leaves nothing behind.
|
||||
fetch(cache.clone(), &format!("{base}/page"), false, 0, waiter(&tx));
|
||||
fetch(cache.clone(), &format!("{base}/page"), false, 0, max, waiter(&tx));
|
||||
let failed = tokio::task::spawn_blocking(move || rx.recv().unwrap()).await.unwrap();
|
||||
assert_eq!(failed, Err("not a picture".into()));
|
||||
// So does one larger than asked for (a chat picture).
|
||||
let (tx, rx) = mpsc::channel();
|
||||
fetch(cache.clone(), &format!("{base}/big"), false, 0, 1000, waiter(&tx));
|
||||
let failed = tokio::task::spawn_blocking(move || rx.recv().unwrap()).await.unwrap();
|
||||
assert!(failed.unwrap_err().contains("larger"));
|
||||
assert_eq!(cache.size(), PNG.len() as u64);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
@@ -340,6 +355,7 @@ mod tests {
|
||||
&format!("{base}/{path}"),
|
||||
false,
|
||||
0,
|
||||
cache::MAX_PICTURE_BYTES,
|
||||
Box::new(move |r| {
|
||||
completed.send(r).unwrap();
|
||||
}),
|
||||
|
||||
@@ -163,6 +163,8 @@ pub(crate) struct Tab {
|
||||
pub topic_messages: Vec<Msg>,
|
||||
/// The message jumped to from the pins.
|
||||
pub marked: Option<i64>,
|
||||
/// What the lines of `messages` were built from.
|
||||
pub cache: crate::vm::chat::LineCache,
|
||||
}
|
||||
|
||||
impl Tab {
|
||||
@@ -185,6 +187,7 @@ impl Tab {
|
||||
topic: None,
|
||||
topic_messages: Vec::new(),
|
||||
marked: None,
|
||||
cache: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -962,10 +965,18 @@ impl App {
|
||||
self.autoshare();
|
||||
}
|
||||
Event::Presence { session, presence } => {
|
||||
self.sessions.entry(session as i64).or_default().presence = presence;
|
||||
let view = self.sessions.entry(session as i64).or_default();
|
||||
// The server chat shows its welcome and host message, with
|
||||
// their pictures.
|
||||
let said = crate::chat::server_texts(&view.presence.server)
|
||||
!= crate::chat::server_texts(&presence.server);
|
||||
view.presence = presence;
|
||||
self.apply_client_playback(session as i64);
|
||||
self.join_after_connect(session as i64);
|
||||
if self.current == Some(session as i64) {
|
||||
if said {
|
||||
self.fetch_previews(session as i64);
|
||||
}
|
||||
self.refresh_toolbar();
|
||||
self.refresh_tree();
|
||||
self.refresh_chat();
|
||||
|
||||
@@ -8,20 +8,48 @@
|
||||
//! 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`].
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use slint::{ComponentHandle, ModelRc};
|
||||
use voelin_core::gateway::Pin;
|
||||
use voelin_core::settings::CACHE_FETCH_IMAGES;
|
||||
use voelin_core::{
|
||||
Command, DownloadTo, GatewayRequest, GatewayUpdate, HistoryMessage, HistorySource,
|
||||
TransferState,
|
||||
};
|
||||
use voelin_gateway_proto::{ErrorCode, TopicInfo, feature};
|
||||
use voelin_model::{ChatMessage, ChatTarget};
|
||||
use voelin_model::{ChatMessage, ChatTarget, HostMessageMode, ServerDetails};
|
||||
|
||||
use crate::app::{App, Bridge, ChatLine, ChatTab, FileItem, Msg, PinItem, SessionView, Tab};
|
||||
use crate::settings::UI_IMAGE_PREVIEW_KB;
|
||||
use crate::vm;
|
||||
use crate::vm::chat::{LineCtx, Previous};
|
||||
use crate::vm::chat::{LineCache, LineCtx, Previous};
|
||||
|
||||
/// Where the server's welcome and host message keep what their lines were
|
||||
/// built from (`LineCache`), apart from the messages' ids.
|
||||
const SERVER_LINES: [i64; 2] = [i64::MIN, i64::MIN + 1];
|
||||
|
||||
/// What the server says to everyone who connects, with where its line keeps
|
||||
/// its parts: its welcome message, and its host message when that goes to
|
||||
/// the chat log.
|
||||
pub(crate) fn server_texts(details: &ServerDetails) -> Vec<(&str, i64)> {
|
||||
let host = details.host_message_mode == HostMessageMode::Log;
|
||||
[Some(&details.welcome_message), host.then_some(&details.host_message)]
|
||||
.into_iter()
|
||||
.zip(SERVER_LINES)
|
||||
.filter_map(|(text, id)| Some((text.filter(|t| !t.trim().is_empty())?.as_str(), id)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The text of the server's line `key` (-1, -2, …) of a server chat
|
||||
/// ([`App::lines_of`]), if `tab` is one.
|
||||
pub(crate) fn server_text<'a>(view: &'a SessionView, tab: &Tab, key: i32) -> Option<&'a str> {
|
||||
if tab.target != ChatTarget::Server || key >= 0 {
|
||||
return None;
|
||||
}
|
||||
server_texts(&view.presence.server).get((-1 - key) as usize).map(|(text, _)| *text)
|
||||
}
|
||||
|
||||
/// A file being downloaded from a chat message.
|
||||
pub(crate) struct Download {
|
||||
@@ -253,17 +281,20 @@ impl App {
|
||||
self.refresh_chat();
|
||||
}
|
||||
|
||||
/// The lines of a tab, grouped and with everything the row shows (also
|
||||
/// the stream chat of the Stream Studio, studio.rs).
|
||||
pub(crate) fn lines_of(
|
||||
&self,
|
||||
view: &SessionView,
|
||||
tab: &Tab,
|
||||
messages: &[Msg],
|
||||
) -> Vec<ChatLine> {
|
||||
/// The lines of a tab's messages (`main`) or of its open topic, grouped
|
||||
/// and with everything the row shows (also the stream chat of the
|
||||
/// Stream Studio, studio.rs). The server chat starts with what the
|
||||
/// 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 {
|
||||
@@ -292,6 +323,8 @@ impl App {
|
||||
topic,
|
||||
downloads: self.downloads_of(view, m.key),
|
||||
previews,
|
||||
pictures,
|
||||
cache,
|
||||
};
|
||||
lines.push((
|
||||
m.message.message.ts_ms,
|
||||
@@ -299,12 +332,42 @@ impl App {
|
||||
));
|
||||
previous = Some(Previous::of(&m.message.message));
|
||||
}
|
||||
if let Some(cache) = cache {
|
||||
let ids = messages.iter().map(|m| m.message.id).chain(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.current) {
|
||||
lines.extend(self.poke_lines(session, uid));
|
||||
lines.sort_by_key(|(ts, _)| *ts);
|
||||
}
|
||||
lines.into_iter().map(|(_, line)| line).collect()
|
||||
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 actions.
|
||||
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,
|
||||
};
|
||||
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.
|
||||
@@ -413,7 +476,7 @@ impl App {
|
||||
let tab = &view.tabs[view.current_tab];
|
||||
// Sessions without stored history push their lines themselves.
|
||||
if view.has_history() {
|
||||
vm::list::sync(&tab.lines, &self.lines_of(view, tab, &tab.messages));
|
||||
vm::list::sync(&tab.lines, &self.lines_of(view, tab, true));
|
||||
}
|
||||
let lines = ModelRc::from(tab.lines.clone());
|
||||
if bridge.get_messages() != lines {
|
||||
@@ -479,7 +542,7 @@ impl App {
|
||||
.unwrap_or_default()
|
||||
.into(),
|
||||
);
|
||||
vm::list::sync(&self.models.topic_messages, &self.lines_of(view, tab, &tab.topic_messages));
|
||||
vm::list::sync(&self.models.topic_messages, &self.lines_of(view, tab, false));
|
||||
}
|
||||
|
||||
// Gateway features of a chat.
|
||||
@@ -633,8 +696,14 @@ impl App {
|
||||
if tab.topic.take().is_some() {
|
||||
tab.topic_messages.clear();
|
||||
}
|
||||
// Older than what is loaded: only highlighted once it is.
|
||||
// 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 => 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>();
|
||||
|
||||
@@ -11,8 +11,9 @@
|
||||
//! server needed (nothing is stored).
|
||||
//! - `VOELIN_DEMO_STREAM=1`: a local test stream in the viewer.
|
||||
//! - `VOELIN_OPEN=<what>[,<what>...]`: open screens on start: `home`,
|
||||
//! `server`, `settings[:<section>]` (voice, keybinds, streaming, privacy,
|
||||
//! appearance, or 0-4), `about`, `share`, `bookmark` (add a server;
|
||||
//! `server` (`server:chat`: its server chat), `settings[:<section>]`
|
||||
//! (voice, keybinds, streaming, privacy, appearance, or 0-4), `about`,
|
||||
//! `share`, `bookmark` (add a server;
|
||||
//! `bookmark:edit` the current one, Advanced open),
|
||||
//! `emoji` (the picker), `client` (the volume dialog of the first other
|
||||
//! client once connected), `panel` / `no-panel` (the members panel),
|
||||
@@ -214,7 +215,13 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running {
|
||||
bridge.set_myts(account);
|
||||
}
|
||||
"home" => nav.invoke_show(Page::Home),
|
||||
"server" => nav.invoke_show(Page::Server),
|
||||
"server" => {
|
||||
nav.invoke_show(Page::Server);
|
||||
// The server chat, which starts with the welcome message.
|
||||
if arg == "chat" {
|
||||
with_app(|app| app.select_tab(0));
|
||||
}
|
||||
}
|
||||
"settings" => nav.invoke_open_settings(section(arg)),
|
||||
"about" => nav.invoke_open_about(),
|
||||
"share" => {
|
||||
@@ -1094,6 +1101,8 @@ const DEMO_HOST_BANNER: &str = "https://nightfall.example/banner.png";
|
||||
const DEMO_CHILL_BANNER: &str = "https://nightfall.example/chill.png";
|
||||
const DEMO_MUSIC_BANNER: &str = "https://nightfall.example/music.png";
|
||||
const DEMO_RAID_BANNER: &str = "https://nightfall.example/raid.png";
|
||||
/// A picture a message shows (`[img]`).
|
||||
const DEMO_LOOT_PICTURE: &str = "https://nightfall.example/loot.png";
|
||||
const DEMO_SERVER_ICON: u32 = 3_120_211_001;
|
||||
const DEMO_ADMIN_ICON: u32 = 3_120_211_002;
|
||||
const DEMO_MOD_ICON: u32 = 3_120_211_003;
|
||||
@@ -1133,6 +1142,7 @@ fn demo_pictures(app: &mut App) {
|
||||
(DEMO_CHILL_BANNER, demo_picture(900, 120, 11)),
|
||||
(DEMO_RAID_BANNER, demo_picture(240, 240, 5)),
|
||||
(DEMO_MUSIC_BANNER, demo_picture(180, 36, 7)),
|
||||
(DEMO_LOOT_PICTURE, demo_picture(640, 300, 9)),
|
||||
] {
|
||||
let path = save(url.rsplit('/').next().unwrap_or(url), picture);
|
||||
events.push(Event::PictureReady { session, url: url.into(), path });
|
||||
@@ -1439,6 +1449,44 @@ fn demo_chat(app: &mut App, session: u64) {
|
||||
None,
|
||||
),
|
||||
(DEMO, "dex", 5, "🎉🎉".into(), 10, false, Vec::new(), false, None),
|
||||
// Formatting as TeamSpeak clients send it (BBCode).
|
||||
(
|
||||
DEMO,
|
||||
"Nova",
|
||||
1,
|
||||
"[b]Raid night[/b] moves from [s]20:00[/s] to [color=#ff8a3d]20:30[/color], sign up \
|
||||
on the [url=https://nightfall.example/raids]raid board[/url]."
|
||||
.into(),
|
||||
9,
|
||||
false,
|
||||
vec![react("👍", 4, true)],
|
||||
true,
|
||||
None,
|
||||
),
|
||||
(
|
||||
DEMO,
|
||||
"Kairo",
|
||||
3,
|
||||
"[quote=Nova]bring elixirs[/quote]\nAlready stocked up 🧪".into(),
|
||||
8,
|
||||
false,
|
||||
Vec::new(),
|
||||
false,
|
||||
None,
|
||||
),
|
||||
(
|
||||
DEMO,
|
||||
"Mira",
|
||||
4,
|
||||
"Roles for tonight:\n[list]\n[*][b]Tank:[/b] Kairo\n[*][b]Healer:[/b] Mira\n\
|
||||
[*][i]Everyone else:[/i] damage[/list]\nPull timer: [code]/pull 10[/code]"
|
||||
.into(),
|
||||
7,
|
||||
false,
|
||||
Vec::new(),
|
||||
false,
|
||||
None,
|
||||
),
|
||||
(
|
||||
DEMO,
|
||||
"Ari",
|
||||
@@ -1450,6 +1498,17 @@ fn demo_chat(app: &mut App, session: u64) {
|
||||
false,
|
||||
None,
|
||||
),
|
||||
(
|
||||
DEMO,
|
||||
"Talon",
|
||||
6,
|
||||
format!("Last week's loot [img]{DEMO_LOOT_PICTURE}[/img]"),
|
||||
6,
|
||||
false,
|
||||
Vec::new(),
|
||||
false,
|
||||
None,
|
||||
),
|
||||
(DEMO + 1, "Ivy", 0, "Welcome to the lounge!".into(), 30, false, Vec::new(), false, None),
|
||||
(
|
||||
DEMO + 1,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Twemoji as images. The software renderer draws no colour glyphs, so the
|
||||
//! UI shows emoji as pictures: this module reads the packed archive
|
||||
//! (`assets/twemoji.bin`, made by `scripts/pack-twemoji.py`), finds the
|
||||
//! picture of a grapheme cluster, splits text into runs of text and emoji,
|
||||
//! picture of a grapheme cluster, splits text into runs of words and emoji,
|
||||
//! and lists emoji for the picker. Decoding the SVGs into images is
|
||||
//! `images.rs`' job.
|
||||
|
||||
@@ -307,27 +307,22 @@ pub struct Run {
|
||||
pub emoji: Option<String>,
|
||||
}
|
||||
|
||||
/// Text split into runs for a wrapping layout: a run per word (with the
|
||||
/// space after it) and per emoji. `None` if the text has no emoji (show it
|
||||
/// as one text). Line breaks become spaces.
|
||||
pub fn runs(text: &str) -> Option<Vec<Run>> {
|
||||
if !text.chars().any(may_be_emoji) {
|
||||
return None;
|
||||
}
|
||||
/// A line of text split into runs for a wrapping layout: a run per word
|
||||
/// (with the space after it) and per emoji. A line break is a space: lines
|
||||
/// are blocks of their own (`vm::bbcode`).
|
||||
pub fn split(text: &str) -> Vec<Run> {
|
||||
let emoji = text.chars().any(may_be_emoji);
|
||||
let mut out: Vec<Run> = Vec::new();
|
||||
let mut word = String::new();
|
||||
let mut any = false;
|
||||
for g in text.graphemes(true) {
|
||||
if let Some(key) = key_for(g) {
|
||||
if let Some(key) = emoji.then(|| key_for(g)).flatten() {
|
||||
if !word.is_empty() {
|
||||
out.push(Run { text: std::mem::take(&mut word), emoji: None });
|
||||
}
|
||||
out.push(Run { text: g.to_owned(), emoji: Some(key) });
|
||||
any = true;
|
||||
continue;
|
||||
}
|
||||
let space = g.chars().all(char::is_whitespace);
|
||||
if space {
|
||||
if g.chars().all(char::is_whitespace) {
|
||||
// Spaces stay with the word before them (or stand alone after
|
||||
// an emoji).
|
||||
word.push(' ');
|
||||
@@ -339,7 +334,7 @@ pub fn runs(text: &str) -> Option<Vec<Run>> {
|
||||
if !word.is_empty() {
|
||||
out.push(Run { text: word, emoji: None });
|
||||
}
|
||||
any.then_some(out)
|
||||
out
|
||||
}
|
||||
|
||||
/// One to three emoji and nothing else but spaces: shown large.
|
||||
@@ -391,15 +386,21 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn text_runs() {
|
||||
assert_eq!(runs("plain text, no emoji"), None);
|
||||
assert_eq!(runs("em — dash"), None);
|
||||
let r = runs("hi 👋 there").unwrap();
|
||||
let texts: Vec<_> = r.iter().map(|r| (r.text.as_str(), r.emoji.as_deref())).collect();
|
||||
assert_eq!(texts, [("hi ", None), ("👋", Some("1f44b")), (" ", None), ("there", None)]);
|
||||
let texts = |text: &str| -> Vec<(String, Option<String>)> {
|
||||
split(text).into_iter().map(|r| (r.text, r.emoji)).collect()
|
||||
};
|
||||
let word = |w: &str| (w.to_owned(), None);
|
||||
assert_eq!(texts("plain text, no"), [word("plain "), word("text, "), word("no")]);
|
||||
assert_eq!(texts("em — dash"), [word("em "), word("— "), word("dash")]);
|
||||
let r = split("hi 👋 there");
|
||||
assert_eq!(
|
||||
texts("hi 👋 there"),
|
||||
[word("hi "), ("👋".into(), Some("1f44b".into())), word(" "), word("there")]
|
||||
);
|
||||
assert!(!is_jumbo(&r));
|
||||
let r = runs("🔥🔥 ").unwrap();
|
||||
assert!(is_jumbo(&r));
|
||||
assert!(!is_jumbo(&runs("🔥🔥🔥🔥").unwrap()));
|
||||
assert!(is_jumbo(&split("🔥🔥 ")));
|
||||
assert!(!is_jumbo(&split("🔥🔥🔥🔥")));
|
||||
assert!(!is_jumbo(&split("no emoji")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -3,13 +3,20 @@
|
||||
//! memory once (`Command::DownloadChatFile` with `DownloadTo::Memory`,
|
||||
//! voice connections only) and decoded once into the image cache
|
||||
//! (`images.rs`); the chat shows it as a picture card, and a click opens
|
||||
//! it larger.
|
||||
//! it larger. A picture on the web a message shows (`[img]`) comes the way
|
||||
//! banners do, into the engine's cache (`Command::FetchPicture`, up to the
|
||||
//! same size, only with `cache.fetch_images`), and until it is there the
|
||||
//! message shows its address.
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
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::settings::UI_IMAGE_PREVIEW_KB;
|
||||
use crate::vm;
|
||||
|
||||
/// A linked picture.
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -59,11 +66,12 @@ impl App {
|
||||
return;
|
||||
}
|
||||
let limit = u64::from(self.prefs.get(&UI_IMAGE_PREVIEW_KB)) * 1024;
|
||||
if limit == 0 {
|
||||
return;
|
||||
}
|
||||
self.fetch_web_pictures(session, limit);
|
||||
let Some(view) = self.sessions.get_mut(&session) else { return };
|
||||
if limit == 0
|
||||
|| view.state.voice != VoiceState::Connected
|
||||
|| !view.capabilities.file_transfer
|
||||
{
|
||||
if view.state.voice != VoiceState::Connected || !view.capabilities.file_transfer {
|
||||
return;
|
||||
}
|
||||
let Some(tab) = view.tabs.get(view.current_tab) else { return };
|
||||
@@ -94,6 +102,38 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
/// Ask the engine for the pictures on the web (`[img]`) of the current
|
||||
/// chat of `session` that it has not reported; it fetches each once.
|
||||
fn fetch_web_pictures(&self, session: i64, limit: u64) {
|
||||
if !self.prefs.get(&CACHE_FETCH_IMAGES) {
|
||||
return;
|
||||
}
|
||||
let Some(view) = self.sessions.get(&session) else { return };
|
||||
let Some(tab) = view.tabs.get(view.current_tab) else { return };
|
||||
// The server chat starts with the server's messages.
|
||||
let server = match tab.target {
|
||||
ChatTarget::Server => crate::chat::server_texts(&view.presence.server),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let wanted: Vec<String> = tab
|
||||
.messages
|
||||
.iter()
|
||||
.rev()
|
||||
.take(200)
|
||||
.map(|m| m.message.message.text.as_str())
|
||||
.chain(server.into_iter().map(|(text, _)| text))
|
||||
.flat_map(vm::chat::web_pictures)
|
||||
.filter(|url| !view.pictures.contains_key(url))
|
||||
.collect();
|
||||
for url in wanted {
|
||||
self.engine.send(Command::FetchPicture {
|
||||
session: session as u64,
|
||||
url,
|
||||
max_bytes: limit,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// A transfer of a picture: `true` if it was one.
|
||||
pub(crate) fn preview_progress(
|
||||
&mut self,
|
||||
@@ -133,15 +173,27 @@ impl App {
|
||||
true
|
||||
}
|
||||
|
||||
/// The picture of link `index` of a message of the current chat, for
|
||||
/// the large view.
|
||||
/// The picture of link `index` of a message of the current chat (its
|
||||
/// files, then its pictures on the web), for the large view.
|
||||
pub(crate) fn open_preview(&self, key: i32, index: i32) -> slint::Image {
|
||||
let Some(view) = self.view() else { return slint::Image::default() };
|
||||
let Some(tab) = view.tabs.get(view.current_tab) else { return slint::Image::default() };
|
||||
tab.message(key)
|
||||
.and_then(|m| m.message.file_refs().into_iter().nth(index.max(0) as usize))
|
||||
.and_then(|f| image_of(view, &f))
|
||||
.unwrap_or_default()
|
||||
let message = match tab.message(key) {
|
||||
Some(message) => Cow::Borrowed(&message.message),
|
||||
// A line of the server.
|
||||
None => match crate::chat::server_text(view, tab, key) {
|
||||
Some(text) => Cow::Owned(vm::chat::server_message("", text)),
|
||||
None => return slint::Image::default(),
|
||||
},
|
||||
};
|
||||
let index = index.max(0) as usize;
|
||||
match message.file_refs().get(index) {
|
||||
Some(file) => image_of(view, file).unwrap_or_default(),
|
||||
None => vm::chat::picture_link(&message, index)
|
||||
.and_then(|url| view.pictures.get(&url))
|
||||
.map(|path| crate::images::file(path))
|
||||
.unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -959,7 +959,7 @@ impl App {
|
||||
Some((view, tab))
|
||||
});
|
||||
let lines: Vec<ChatLine> = match tab {
|
||||
Some((view, tab)) if view.has_history() => self.lines_of(view, tab, &tab.messages),
|
||||
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(),
|
||||
None => Vec::new(),
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+543
-78
@@ -1,15 +1,22 @@
|
||||
//! Chat lines: one [`ChatLine`] per message, with its reactions and the
|
||||
//! files it links.
|
||||
//! Chat lines: one [`ChatLine`] per message, with its text in blocks of
|
||||
//! styled runs (`vm::bbcode`), its reactions and the files and pictures it
|
||||
//! links.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::rc::Rc;
|
||||
|
||||
use slint::{Image, ModelRc, VecModel};
|
||||
use slint::{Color, Image, ModelRc, VecModel};
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
use voelin_core::HistoryMessage;
|
||||
use voelin_model::{ChatMessage, FileRef};
|
||||
use voelin_model::{ChatMessage, ChatTarget, FileRef};
|
||||
|
||||
use crate::app::{ChatLine, FileItem, ReactionItem, TextRun};
|
||||
use crate::app::{ChatLine, FileItem, ReactionItem, TextBlock, TextRun};
|
||||
use crate::emoji;
|
||||
use crate::vm::avatar;
|
||||
use crate::vm::bbcode::{self, BlockKind, Doc, Span, Style};
|
||||
|
||||
/// Lines of the same author within this time are grouped (no header).
|
||||
const GROUP_MS: i64 = 5 * 60 * 1000;
|
||||
@@ -29,7 +36,7 @@ impl Previous {
|
||||
|
||||
/// What a line needs besides the message itself.
|
||||
#[derive(Default)]
|
||||
pub struct LineCtx {
|
||||
pub struct LineCtx<'a> {
|
||||
/// The message's handle in its chat.
|
||||
pub key: i32,
|
||||
/// The author's avatar picture.
|
||||
@@ -44,6 +51,12 @@ pub struct LineCtx {
|
||||
pub downloads: Vec<(usize, FileItem)>,
|
||||
/// Pictures of the links shown inline, by link index.
|
||||
pub previews: Vec<(usize, Image)>,
|
||||
/// Pictures on the web in the engine's cache, by address: the `[img]`
|
||||
/// pictures here show as picture cards, the others as links (`None`:
|
||||
/// all as links).
|
||||
pub pictures: Option<&'a HashMap<String, PathBuf>>,
|
||||
/// What earlier lines of the chat were built from, to reuse.
|
||||
pub cache: Option<&'a LineCache>,
|
||||
}
|
||||
|
||||
/// When a message was sent, for its header (see [`stamp`]).
|
||||
@@ -80,20 +93,269 @@ pub fn size_text(bytes: u64) -> String {
|
||||
format!("{bytes} B")
|
||||
}
|
||||
|
||||
/// The text without the file links that became cards.
|
||||
fn without_links(text: &str, files: &[FileRef]) -> String {
|
||||
let mut out = text.to_owned();
|
||||
for file in files {
|
||||
for pattern in [
|
||||
format!("[URL={}]{}[/URL]", file.url, file.name),
|
||||
format!("[URL={}]", file.url),
|
||||
format!("[url={}]", file.url),
|
||||
file.url.clone(),
|
||||
] {
|
||||
out = out.replace(&pattern, "");
|
||||
/// What a line shows of its message's text.
|
||||
#[derive(Clone, Default)]
|
||||
struct Body {
|
||||
text: String,
|
||||
blocks: ModelRc<TextBlock>,
|
||||
rich: bool,
|
||||
jumbo: bool,
|
||||
link: String,
|
||||
}
|
||||
|
||||
/// A message's text read: without the file links (cards), the files it
|
||||
/// links, and the addresses of its pictures on the web.
|
||||
struct Read {
|
||||
doc: Doc,
|
||||
files: Vec<FileRef>,
|
||||
images: Vec<String>,
|
||||
}
|
||||
|
||||
/// What lines of a chat were built from, by message id, kept between
|
||||
/// refreshes: a message whose text, reactions and cards did not change is
|
||||
/// not read again and gets the same models (they compare by pointer), so
|
||||
/// its line compares equal and `list::sync` leaves its row. (Not with an
|
||||
/// empty picture: Slint's empty `Image` equals nothing, not even itself.)
|
||||
#[derive(Default)]
|
||||
pub struct LineCache(RefCell<HashMap<i64, Parts>>);
|
||||
|
||||
#[derive(Default)]
|
||||
struct Parts {
|
||||
rev: i64,
|
||||
text: String,
|
||||
read: Option<Read>,
|
||||
/// The body last built, and which pictures were cards then.
|
||||
body: Option<(Vec<bool>, Body)>,
|
||||
reactions: (Vec<ReactionItem>, ModelRc<ReactionItem>),
|
||||
files: (Vec<FileItem>, ModelRc<FileItem>),
|
||||
}
|
||||
|
||||
impl LineCache {
|
||||
/// Forget the messages not among `ids` once there are many more.
|
||||
pub fn keep(&self, ids: impl IntoIterator<Item = i64>, count: usize) {
|
||||
let mut parts = self.0.borrow_mut();
|
||||
if parts.len() > count + 64 {
|
||||
let ids: std::collections::HashSet<i64> = ids.into_iter().collect();
|
||||
parts.retain(|id, _| ids.contains(id));
|
||||
}
|
||||
}
|
||||
out.replace("[/URL]", "").replace("[/url]", "").trim().to_owned()
|
||||
}
|
||||
|
||||
/// The parts of message `id`, started again when it changed.
|
||||
fn current<'a>(all: &'a mut HashMap<i64, Parts>, id: i64, rev: i64, text: &str) -> &'a mut Parts {
|
||||
let parts = all.entry(id).or_default();
|
||||
if parts.rev != rev || parts.text != text {
|
||||
*parts = Parts { rev, text: text.to_owned(), ..Parts::default() };
|
||||
}
|
||||
parts
|
||||
}
|
||||
|
||||
/// `rows` as a model: the one in `kept` when they are the same rows.
|
||||
fn model_of<T: Clone + PartialEq + 'static>(
|
||||
rows: Vec<T>,
|
||||
kept: Option<&mut (Vec<T>, ModelRc<T>)>,
|
||||
) -> ModelRc<T> {
|
||||
match kept {
|
||||
Some((old, model)) if *old == rows => model.clone(),
|
||||
Some(kept) => {
|
||||
let model = ModelRc::from(Rc::new(VecModel::from(rows.clone())));
|
||||
*kept = (rows, model.clone());
|
||||
model
|
||||
}
|
||||
None => ModelRc::from(Rc::new(VecModel::from(rows))),
|
||||
}
|
||||
}
|
||||
|
||||
/// A link to a channel's file, which the chat shows as a card.
|
||||
fn is_file(address: &str) -> bool {
|
||||
FileRef::parse(address).is_some()
|
||||
}
|
||||
|
||||
fn read(message: &ChatMessage) -> Read {
|
||||
let mut doc = bbcode::parse(&message.text);
|
||||
doc.retain(|span| match span {
|
||||
Span::Text { style, .. } => !style.link.as_deref().is_some_and(is_file),
|
||||
Span::Image { url } => !is_file(url),
|
||||
});
|
||||
let images = web_images(&doc);
|
||||
Read { doc, files: message.file_refs(), images }
|
||||
}
|
||||
|
||||
fn web_images(doc: &Doc) -> Vec<String> {
|
||||
doc.images().into_iter().filter(|u| bbcode::is_web(u)).map(str::to_owned).collect()
|
||||
}
|
||||
|
||||
/// The addresses of the pictures on the web a message's text shows
|
||||
/// (`[img]`).
|
||||
pub fn web_pictures(text: &str) -> Vec<String> {
|
||||
if !text.as_bytes().windows(5).any(|w| w.eq_ignore_ascii_case(b"[img]")) {
|
||||
return Vec::new();
|
||||
}
|
||||
web_images(&bbcode::parse(text))
|
||||
}
|
||||
|
||||
/// The colours of a span: the author's made readable on the dark and the
|
||||
/// light theme, or transparent for the text's own.
|
||||
fn inks(color: Option<[u8; 3]>) -> (Color, Color) {
|
||||
let rgb = |[r, g, b]: [u8; 3]| Color::from_rgb_u8(r, g, b);
|
||||
match color {
|
||||
Some(c) => (rgb(bbcode::readable(c, true)), rgb(bbcode::readable(c, false))),
|
||||
None => (Color::default(), Color::default()),
|
||||
}
|
||||
}
|
||||
|
||||
/// A run of `text` (or the emoji `emoji`) in `style`.
|
||||
fn run(text: &str, emoji: Option<String>, style: &Style, inks: (Color, Color)) -> TextRun {
|
||||
TextRun {
|
||||
text: text.into(),
|
||||
emoji: emoji.unwrap_or_default().into(),
|
||||
bold: style.bold,
|
||||
italic: style.italic,
|
||||
underline: style.underline,
|
||||
strike: style.strike,
|
||||
code: style.code,
|
||||
ink_dark: inks.0,
|
||||
ink_light: inks.1,
|
||||
link: style.link.clone().unwrap_or_default().into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Characters of a run at most: a longer word (an address) is cut into
|
||||
/// runs, so a line can break inside it (a run does not wrap).
|
||||
const LONG_WORD: usize = 24;
|
||||
|
||||
/// `word` in pieces of at most [`LONG_WORD`] characters.
|
||||
fn pieces(word: &str) -> Vec<&str> {
|
||||
let mut out = Vec::new();
|
||||
let mut start = 0;
|
||||
for (count, (at, _)) in word.grapheme_indices(true).enumerate() {
|
||||
if count > 0 && count % LONG_WORD == 0 {
|
||||
out.push(&word[start..at]);
|
||||
start = at;
|
||||
}
|
||||
}
|
||||
out.push(&word[start..]);
|
||||
out
|
||||
}
|
||||
|
||||
/// The runs of spans: a run per word and per emoji (short inline code in
|
||||
/// one piece, on one background), and whether a run is an emoji.
|
||||
fn runs_of(spans: &[Span]) -> (Vec<TextRun>, bool) {
|
||||
let mut runs: Vec<TextRun> = Vec::new();
|
||||
let mut any_emoji = false;
|
||||
for span in spans {
|
||||
match span {
|
||||
Span::Text { text, style } => {
|
||||
let inks = inks(style.color);
|
||||
let words = if style.code && text.graphemes(true).count() <= LONG_WORD {
|
||||
vec![emoji::Run { text: text.clone(), emoji: None }]
|
||||
} else {
|
||||
emoji::split(text)
|
||||
};
|
||||
for word in words {
|
||||
any_emoji |= word.emoji.is_some();
|
||||
match word.emoji {
|
||||
Some(key) => runs.push(run(&word.text, Some(key), style, inks)),
|
||||
None => runs.extend(
|
||||
pieces(&word.text).into_iter().map(|p| run(p, None, style, inks)),
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
// A picture that is not shown: its address, as a link.
|
||||
Span::Image { url } => {
|
||||
let style = Style { link: Some(url.clone()), ..Style::default() };
|
||||
runs.extend(pieces(url).into_iter().map(|p| run(p, None, &style, inks(None))));
|
||||
}
|
||||
}
|
||||
}
|
||||
(runs, any_emoji)
|
||||
}
|
||||
|
||||
/// The blocks of a doc for `RichText` (code a block per line), and whether
|
||||
/// a run is an emoji; `None` past [`bbcode::MAX_RUNS`] runs.
|
||||
fn blocks_of(doc: &Doc) -> Option<(Vec<TextBlock>, bool)> {
|
||||
let mut count = 0;
|
||||
let mut any_emoji = false;
|
||||
let mut blocks = Vec::with_capacity(doc.blocks.len());
|
||||
for block in &doc.blocks {
|
||||
let (kind, caption) = match &block.kind {
|
||||
BlockKind::Text => (0, ""),
|
||||
BlockKind::Quote { author } => (1, author.as_str()),
|
||||
BlockKind::Code => (2, ""),
|
||||
BlockKind::Bullet => (3, ""),
|
||||
BlockKind::Rule => (4, ""),
|
||||
};
|
||||
let lines: Vec<(Vec<TextRun>, bool)> = match &block.spans[..] {
|
||||
[Span::Text { text, .. }] if block.kind == BlockKind::Code => text
|
||||
.split('\n')
|
||||
.map(|line| runs_of(&[Span::Text { text: line.into(), style: Style::default() }]))
|
||||
.collect(),
|
||||
spans => vec![runs_of(spans)],
|
||||
};
|
||||
for (mut runs, emoji) in lines {
|
||||
any_emoji |= emoji;
|
||||
// An empty line keeps its height.
|
||||
if runs.is_empty() && block.kind != BlockKind::Rule {
|
||||
runs.push(TextRun { text: " ".into(), ..Default::default() });
|
||||
}
|
||||
count += runs.len();
|
||||
if count > bbcode::MAX_RUNS {
|
||||
return None;
|
||||
}
|
||||
blocks.push(TextBlock {
|
||||
runs: ModelRc::from(Rc::new(VecModel::from(runs))),
|
||||
kind,
|
||||
caption: caption.into(),
|
||||
});
|
||||
}
|
||||
}
|
||||
Some((blocks, any_emoji))
|
||||
}
|
||||
|
||||
/// What a line shows of `doc`, without the pictures that are cards
|
||||
/// (`cards[i]`: the doc's `i`th picture on the web).
|
||||
fn body_of(doc: &Doc, cards: &[bool]) -> Body {
|
||||
let mut doc = Cow::Borrowed(doc);
|
||||
if cards.contains(&true) {
|
||||
let mut i = 0;
|
||||
doc.to_mut().retain(|span| {
|
||||
let Span::Image { url } = span else { return true };
|
||||
if !bbcode::is_web(url) {
|
||||
return true;
|
||||
}
|
||||
i += 1;
|
||||
!cards.get(i - 1).copied().unwrap_or(false)
|
||||
});
|
||||
}
|
||||
let text = doc.plain();
|
||||
let words = emoji::split(&text);
|
||||
let jumbo = emoji::is_jumbo(&words);
|
||||
let link = doc.links().into_iter().find(|l| bbcode::is_web(l)).unwrap_or_default().to_owned();
|
||||
let rich = !doc.is_plain() || words.iter().any(|w| w.emoji.is_some());
|
||||
// Past the runs a line can have: its plain text.
|
||||
match rich.then(|| blocks_of(&doc)).flatten() {
|
||||
Some((blocks, _)) => Body {
|
||||
text,
|
||||
blocks: ModelRc::from(Rc::new(VecModel::from(blocks))),
|
||||
rich: true,
|
||||
jumbo,
|
||||
link,
|
||||
},
|
||||
None => Body { text, blocks: ModelRc::default(), rich: false, jumbo, link },
|
||||
}
|
||||
}
|
||||
|
||||
/// The picture at `url`, if the engine has it and it can be shown.
|
||||
fn picture(pictures: Option<&HashMap<String, PathBuf>>, url: &str) -> Option<Image> {
|
||||
let image = avatar::image(pictures?.get(url));
|
||||
(image.size().width > 0).then_some(image)
|
||||
}
|
||||
|
||||
/// A picture's name: the last part of its address's path.
|
||||
fn picture_name(url: &str) -> &str {
|
||||
let path = url.split(['?', '#']).next().unwrap_or(url);
|
||||
path.rsplit('/').find(|s| !s.is_empty()).unwrap_or(url)
|
||||
}
|
||||
|
||||
/// A chat's last message for a list of chats, on one line ("Mira: the
|
||||
@@ -102,80 +364,104 @@ pub fn preview(message: &ChatMessage) -> (String, String) {
|
||||
let text = if message.blocked {
|
||||
"Message from a blocked contact.".to_owned()
|
||||
} else {
|
||||
let files = message.file_refs();
|
||||
let names = files.iter().map(|f| f.name.as_str());
|
||||
let text = without_links(&message.text, &files);
|
||||
std::iter::once(text.as_str()).chain(names).collect::<Vec<_>>().join(" ")
|
||||
let read = read(message);
|
||||
let names = read.files.into_iter().map(|f| f.name);
|
||||
std::iter::once(read.doc.one_line()).chain(names).collect::<Vec<_>>().join(" ")
|
||||
};
|
||||
// A one-line text cannot show emoji (they are pictures): left out.
|
||||
let plain = match emoji::runs(&text) {
|
||||
Some(runs) => runs.into_iter().filter(|r| r.emoji.is_none()).map(|r| r.text).collect(),
|
||||
None => text,
|
||||
};
|
||||
let mut text = plain.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
let mut text = crate::vm::social::without_emoji(&text);
|
||||
if text.is_empty() {
|
||||
text = "sent an emoji".into();
|
||||
}
|
||||
(format!("{}: {text}", message.author_name), time_of(message.ts_ms))
|
||||
}
|
||||
|
||||
fn runs_model(runs: &[emoji::Run]) -> ModelRc<TextRun> {
|
||||
ModelRc::from(Rc::new(VecModel::from(
|
||||
runs.iter()
|
||||
.map(|r| TextRun {
|
||||
text: r.text.clone().into(),
|
||||
emoji: r.emoji.clone().unwrap_or_default().into(),
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
)))
|
||||
}
|
||||
|
||||
/// The line of a stored message; `previous` is the line before it.
|
||||
pub fn history_line(
|
||||
message: &HistoryMessage,
|
||||
previous: Option<&Previous>,
|
||||
ctx: &LineCtx,
|
||||
) -> ChatLine {
|
||||
let files = message.message.file_refs();
|
||||
let mut line = line_of(&message.message, previous, ctx, &files);
|
||||
let reactions = message
|
||||
.reactions
|
||||
.iter()
|
||||
.map(|r| ReactionItem {
|
||||
key: emoji::first_key(&r.emoji).unwrap_or_default().into(),
|
||||
text: r.emoji.clone().into(),
|
||||
count: r.count as i32,
|
||||
me: r.me,
|
||||
})
|
||||
.collect();
|
||||
let mut cache = ctx.cache.map(|c| c.0.borrow_mut());
|
||||
let parts =
|
||||
cache.as_mut().map(|all| current(all, message.id, message.rev, &message.message.text));
|
||||
let mut line = line_of(&message.message, previous, ctx, parts, reactions);
|
||||
line.pinned = message.pinned;
|
||||
line.remote = ctx.gateway && message.remote_id.is_some();
|
||||
line.reactions = ModelRc::from(Rc::new(VecModel::from(
|
||||
message
|
||||
.reactions
|
||||
.iter()
|
||||
.map(|r| ReactionItem {
|
||||
key: emoji::first_key(&r.emoji).unwrap_or_default().into(),
|
||||
text: r.emoji.clone().into(),
|
||||
count: r.count as i32,
|
||||
me: r.me,
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
)));
|
||||
line
|
||||
}
|
||||
|
||||
/// The line of a message the engine keeps no history for (no ids, no
|
||||
/// reactions).
|
||||
pub fn line(message: &ChatMessage, previous: Option<&Previous>) -> ChatLine {
|
||||
let files = message.file_refs();
|
||||
line_of(message, previous, &LineCtx::default(), &files)
|
||||
line_of(message, previous, &LineCtx::default(), None, Vec::new())
|
||||
}
|
||||
|
||||
/// A message of the server (its welcome or host message), by `server`.
|
||||
pub fn server_message(server: &str, text: &str) -> ChatMessage {
|
||||
ChatMessage {
|
||||
target: ChatTarget::Server,
|
||||
author_name: server.to_owned(),
|
||||
author_uid: None,
|
||||
author_id: None,
|
||||
text: text.to_owned(),
|
||||
ts_ms: 0,
|
||||
via_relay: false,
|
||||
blocked: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// A message of the server ([`server_message`]) as a line of the server
|
||||
/// chat: by the server, without a time or actions. `id` keeps what it was
|
||||
/// built from in the cache, apart from the messages'.
|
||||
pub fn server_line(server: &str, text: &str, id: i64, continued: bool, ctx: &LineCtx) -> ChatLine {
|
||||
let message = server_message(server, text);
|
||||
let previous = continued.then(|| Previous::of(&message));
|
||||
let mut cache = ctx.cache.map(|c| c.0.borrow_mut());
|
||||
let parts = cache.as_mut().map(|all| current(all, id, 0, text));
|
||||
let mut line = line_of(&message, previous.as_ref(), ctx, parts, Vec::new());
|
||||
line.time = Default::default();
|
||||
line
|
||||
}
|
||||
|
||||
fn line_of(
|
||||
message: &ChatMessage,
|
||||
previous: Option<&Previous>,
|
||||
ctx: &LineCtx,
|
||||
files: &[FileRef],
|
||||
parts: Option<&mut Parts>,
|
||||
reactions: Vec<ReactionItem>,
|
||||
) -> ChatLine {
|
||||
let continued = previous.is_some_and(|p| {
|
||||
p.author == message.author_name && (0..GROUP_MS).contains(&(message.ts_ms - p.ts_ms))
|
||||
});
|
||||
let text =
|
||||
if files.is_empty() { message.text.clone() } else { without_links(&message.text, files) };
|
||||
let runs = emoji::runs(&text);
|
||||
let jumbo = runs.as_deref().is_some_and(emoji::is_jumbo);
|
||||
let cards: Vec<FileItem> = files
|
||||
let cached = parts.is_some();
|
||||
let mut own = Parts::default();
|
||||
let parts = parts.unwrap_or(&mut own);
|
||||
let read = parts.read.get_or_insert_with(|| read(message));
|
||||
// Pictures on the web that are here are cards, after the files'.
|
||||
let pictures: Vec<Option<Image>> =
|
||||
read.images.iter().map(|url| picture(ctx.pictures, url)).collect();
|
||||
let shown: Vec<bool> = pictures.iter().map(Option::is_some).collect();
|
||||
let body = match &parts.body {
|
||||
Some((was, body)) if *was == shown => body.clone(),
|
||||
_ => {
|
||||
let body = body_of(&read.doc, &shown);
|
||||
parts.body = Some((shown, body.clone()));
|
||||
body
|
||||
}
|
||||
};
|
||||
let mut cards: Vec<FileItem> = read
|
||||
.files
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, f)| {
|
||||
@@ -198,28 +484,50 @@ fn line_of(
|
||||
item
|
||||
})
|
||||
.collect();
|
||||
let first = cards.len();
|
||||
for (i, (url, picture)) in read.images.iter().zip(pictures).enumerate() {
|
||||
if let Some(picture) = picture {
|
||||
cards.push(FileItem {
|
||||
name: picture_name(url).into(),
|
||||
index: (first + i) as i32,
|
||||
picture: true,
|
||||
preview: picture,
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
}
|
||||
let files = model_of(cards, cached.then_some(&mut parts.files));
|
||||
let reactions = model_of(reactions, cached.then_some(&mut parts.reactions));
|
||||
ChatLine {
|
||||
key: ctx.key,
|
||||
author: message.author_name.clone().into(),
|
||||
text: text.clone().into(),
|
||||
text: body.text.into(),
|
||||
time: time_of(message.ts_ms).into(),
|
||||
runs: runs.as_deref().map(runs_model).unwrap_or_default(),
|
||||
rich: runs.is_some(),
|
||||
jumbo,
|
||||
blocks: body.blocks,
|
||||
rich: body.rich,
|
||||
jumbo: body.jumbo,
|
||||
continued,
|
||||
initials: avatar::initials(&message.author_name).into(),
|
||||
tint: avatar::tint(&message.author_name),
|
||||
avatar: ctx.avatar.clone(),
|
||||
blocked: message.blocked,
|
||||
pinned: false,
|
||||
reactions: ModelRc::default(),
|
||||
files: ModelRc::from(Rc::new(VecModel::from(cards))),
|
||||
reactions,
|
||||
files,
|
||||
remote: false,
|
||||
topic: ctx.topic.clone().into(),
|
||||
marked: ctx.marked,
|
||||
link: body.link.into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The address of picture `index` of a message's links, counted as its
|
||||
/// line's cards are: its files first, then its pictures on the web.
|
||||
pub fn picture_link(message: &ChatMessage, index: usize) -> Option<String> {
|
||||
let read = read(message);
|
||||
index.checked_sub(read.files.len()).and_then(|i| read.images.into_iter().nth(i))
|
||||
}
|
||||
|
||||
pub fn is_picture(name: &str) -> bool {
|
||||
let lower = name.to_ascii_lowercase();
|
||||
[".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".svg"].iter().any(|e| lower.ends_with(e))
|
||||
@@ -230,7 +538,6 @@ mod tests {
|
||||
use slint::Model;
|
||||
use voelin_core::HistoryMessage;
|
||||
use voelin_gateway_proto::ReactionCount;
|
||||
use voelin_model::ChatTarget;
|
||||
use voelin_store::MessageSource;
|
||||
|
||||
use super::*;
|
||||
@@ -273,15 +580,165 @@ mod tests {
|
||||
assert!(!line(&message("Alice", "later", 1_000_000 + GROUP_MS), Some(&prev)).continued);
|
||||
}
|
||||
|
||||
/// The runs of block `i` of a line, as (text, emoji).
|
||||
fn runs(line: &ChatLine, i: usize) -> Vec<TextRun> {
|
||||
line.blocks.row_data(i).unwrap().runs.iter().collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emoji_runs() {
|
||||
let plain = line(&message("A", "no emoji here", 0), None);
|
||||
assert!(!plain.rich && plain.runs.row_count() == 0);
|
||||
let plain = line(&message("A", "no emoji here\nnor here", 0), None);
|
||||
assert!(!plain.rich && plain.blocks.row_count() == 0);
|
||||
assert_eq!(plain.text, "no emoji here\nnor here");
|
||||
let rich = line(&message("A", "gg 🎉", 0), None);
|
||||
assert!(rich.rich && !rich.jumbo);
|
||||
assert_eq!(rich.runs.row_count(), 2);
|
||||
assert_eq!(rich.runs.row_data(1).unwrap().emoji, "1f389");
|
||||
assert_eq!(rich.blocks.row_count(), 1);
|
||||
let r = runs(&rich, 0);
|
||||
assert_eq!((r.len(), r[0].text.as_str(), r[1].emoji.as_str()), (2, "gg ", "1f389"));
|
||||
assert!(line(&message("A", "🎉", 0), None).jumbo);
|
||||
// Formatting around it: still large.
|
||||
let jumbo = line(&message("A", "[b]🎉[/b]", 0), None);
|
||||
assert!(jumbo.rich && jumbo.jumbo);
|
||||
// Lines stay lines with emoji (they were run together).
|
||||
let lines = line(&message("A", "first 🎉\nsecond", 0), None);
|
||||
assert_eq!(lines.blocks.row_count(), 2);
|
||||
assert_eq!(lines.text, "first 🎉\nsecond");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bbcode_lines() {
|
||||
let text = "[b]Raid[/b] at [color=#f00]8[/color], see https://x.org/raid\n\
|
||||
[quote=Nova]bring elixirs[/quote]\n[list][*]one[*][u]two[/u][/list][hr]\
|
||||
[code]a\n\nb[/code]";
|
||||
let line = line(&message("A", text, 0), None);
|
||||
assert!(line.rich && !line.jumbo);
|
||||
assert_eq!(
|
||||
line.text,
|
||||
"Raid at 8, see https://x.org/raid\n> Nova: bring elixirs\n• one\n• two\n---\na\n\nb"
|
||||
);
|
||||
assert_eq!(line.link, "https://x.org/raid");
|
||||
let kinds: Vec<(i32, String)> =
|
||||
line.blocks.iter().map(|b| (b.kind, b.caption.to_string())).collect();
|
||||
let kind = |k: i32| (k, String::new());
|
||||
assert_eq!(
|
||||
kinds,
|
||||
[kind(0), (1, "Nova".into()), kind(3), kind(3), kind(4), kind(2), kind(2), kind(2)]
|
||||
);
|
||||
let first = runs(&line, 0);
|
||||
assert!(first[0].bold && first[0].text == "Raid");
|
||||
let eight = first.iter().find(|r| r.text.starts_with('8')).unwrap();
|
||||
// The author's red, readable on both themes.
|
||||
assert!(eight.ink_dark.alpha() == 255 && eight.ink_light.alpha() == 255);
|
||||
assert!(eight.ink_dark.red() > eight.ink_dark.green());
|
||||
assert_eq!(first[0].ink_dark.alpha(), 0, "the text's own colour");
|
||||
let address = first.iter().find(|r| !r.link.is_empty()).unwrap();
|
||||
assert_eq!(
|
||||
(address.text.as_str(), address.link.as_str()),
|
||||
("https://x.org/raid", "https://x.org/raid")
|
||||
);
|
||||
assert!(runs(&line, 3)[0].underline);
|
||||
assert!(runs(&line, 4).is_empty(), "a rule has no runs");
|
||||
// Code: a block per line, empty ones kept.
|
||||
let code: Vec<String> = (5..8).map(|i| runs(&line, i)[0].text.to_string()).collect();
|
||||
assert_eq!(code, ["a", " ", "b"]);
|
||||
// Inline code: one run.
|
||||
let inline = super::line(&message("A", "run [code]/pull 10[/code]", 0), None);
|
||||
let r = runs(&inline, 0);
|
||||
assert!(r[1].code && r[1].text == "/pull 10");
|
||||
// Not formatting: plain.
|
||||
let relayed = super::line(&message("A", "[Nova] hi [1]", 0), None);
|
||||
assert!(!relayed.rich && relayed.text == "[Nova] hi [1]" && relayed.link.is_empty());
|
||||
}
|
||||
|
||||
/// A run does not wrap: long words (addresses) and long inline code
|
||||
/// are cut so the line can break inside them.
|
||||
#[test]
|
||||
fn long_words_are_cut() {
|
||||
let url = format!("https://x.org/{}", "a".repeat(40));
|
||||
let line = line(&message("A", &format!("see {url}"), 0), None);
|
||||
let r = runs(&line, 0);
|
||||
let pieces: Vec<&str> = r[1..].iter().map(|r| r.text.as_str()).collect();
|
||||
assert_eq!(pieces.concat(), url);
|
||||
assert!(pieces.len() == 3 && pieces.iter().all(|p| p.chars().count() <= LONG_WORD));
|
||||
assert!(r[1..].iter().all(|r| r.link == url.as_str()));
|
||||
let code = "cargo build --release --locked -j 1";
|
||||
let line = super::line(&message("A", &format!("[code]{code}[/code]"), 0), None);
|
||||
let r = runs(&line, 0);
|
||||
assert!(r.len() > 1 && r.iter().all(|r| r.code));
|
||||
assert_eq!(r.iter().map(|r| r.text.as_str()).collect::<String>(), code);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pictures_on_the_web() {
|
||||
let url = "https://x.org/loot.png";
|
||||
let text = format!("loot [img]{url}[/img]");
|
||||
// Not here (or not fetched): the address, as a link.
|
||||
let link = line(&message("A", &text, 0), None);
|
||||
assert_eq!(link.files.row_count(), 0);
|
||||
let r = runs(&link, 0);
|
||||
assert_eq!((r[1].text.as_str(), r[1].link.as_str()), (url, url));
|
||||
// Here: a picture card after the files, and no address.
|
||||
let dir = std::env::temp_dir().join(format!("voelin-chat-picture-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("loot");
|
||||
let mut bytes = Vec::new();
|
||||
let mut encoder = png::Encoder::new(&mut bytes, 4, 2);
|
||||
encoder.set_color(png::ColorType::Rgba);
|
||||
encoder.set_depth(png::BitDepth::Eight);
|
||||
encoder.write_header().unwrap().write_image_data(&[200; 32]).unwrap();
|
||||
std::fs::write(&path, bytes).unwrap();
|
||||
let pictures = HashMap::from([(url.to_owned(), path)]);
|
||||
let file = "ts3file://plan.pdf?channel=2&path=/&filename=plan.pdf&isDir=0&size=2048";
|
||||
let stored = stored(message("A", &format!("{text} [URL={file}]plan.pdf[/URL]"), 0));
|
||||
let ctx = LineCtx { pictures: Some(&pictures), ..Default::default() };
|
||||
let shown = history_line(&stored, None, &ctx);
|
||||
assert_eq!(shown.text, "loot");
|
||||
assert_eq!(shown.files.row_count(), 2);
|
||||
let card = shown.files.row_data(1).unwrap();
|
||||
assert_eq!((card.name.as_str(), card.index, card.preview.size().width), ("loot.png", 1, 4));
|
||||
assert_eq!(picture_link(&stored.message, 1).as_deref(), Some(url));
|
||||
assert_eq!(picture_link(&stored.message, 0), None);
|
||||
assert_eq!(web_pictures(&text), [url]);
|
||||
assert!(web_pictures("[url]https://x.org/a.png[/url]").is_empty());
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
/// A line built again from an unchanged message is equal (its models
|
||||
/// are the same), so `list::sync` leaves its row; a change builds anew.
|
||||
#[test]
|
||||
fn unchanged_lines_compare_equal() {
|
||||
let cache = LineCache::default();
|
||||
// An avatar: an empty picture is never equal.
|
||||
let avatar = Image::from_rgba8(slint::SharedPixelBuffer::new(1, 1));
|
||||
let ctx = LineCtx { key: 3, avatar, cache: Some(&cache), ..Default::default() };
|
||||
let mut stored = stored(message("A", "[b]hi[/b] 🎉", 0));
|
||||
let first = history_line(&stored, None, &ctx);
|
||||
assert!(first == history_line(&stored, None, &ctx));
|
||||
// Without the cache, models are new each time.
|
||||
let plain = LineCtx { key: 3, avatar: ctx.avatar.clone(), ..Default::default() };
|
||||
assert!(history_line(&stored, None, &plain) != history_line(&stored, None, &plain));
|
||||
stored.reactions[0].count = 3;
|
||||
let reacted = history_line(&stored, None, &ctx);
|
||||
assert!(reacted != first && reacted.blocks == first.blocks);
|
||||
stored.message.text = "[i]edited[/i]".into();
|
||||
stored.rev = 2;
|
||||
let edited = history_line(&stored, None, &ctx);
|
||||
assert!(edited.blocks != first.blocks);
|
||||
assert_eq!(edited.text, "edited");
|
||||
cache.keep([], 0);
|
||||
assert_eq!(cache.0.borrow().len(), 1, "few: kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_lines() {
|
||||
let cache = LineCache::default();
|
||||
let ctx = LineCtx { key: -1, cache: Some(&cache), ..Default::default() };
|
||||
let welcome =
|
||||
server_line("Nightfall", "Welcome to [b]Nightfall[/b]!", i64::MIN, false, &ctx);
|
||||
assert_eq!((welcome.author.as_str(), welcome.time.as_str()), ("Nightfall", ""));
|
||||
assert!(welcome.rich && !welcome.continued && !welcome.remote && welcome.key == -1);
|
||||
assert_eq!(welcome.text, "Welcome to Nightfall!");
|
||||
assert!(server_line("Nightfall", "News", i64::MIN + 1, true, &ctx).continued);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -300,13 +757,21 @@ mod tests {
|
||||
#[test]
|
||||
fn file_cards_leave_the_text() {
|
||||
let url = "ts3file://plan.pdf?channel=2&path=/&filename=plan.pdf&isDir=0&size=2048";
|
||||
let text = format!("here you go [URL={url}]plan.pdf[/URL] 🎉");
|
||||
let line = line(&message("A", &text, 0), None);
|
||||
assert_eq!(line.files.row_count(), 1);
|
||||
let file = line.files.row_data(0).unwrap();
|
||||
assert_eq!((file.name.as_str(), file.detail.as_str()), ("plan.pdf", "2.0 kB"));
|
||||
assert!(!line.text.contains("ts3file"), "{}", line.text);
|
||||
assert!(line.text.starts_with("here you go"));
|
||||
for text in [
|
||||
format!("here you go [URL={url}]plan.pdf[/URL] 🎉"),
|
||||
format!("here you go [b][URL={url}]plan.pdf[/URL][/b] 🎉"),
|
||||
format!("here you go {url} 🎉"),
|
||||
] {
|
||||
let line = line(&message("A", &text, 0), None);
|
||||
assert_eq!(line.files.row_count(), 1);
|
||||
let file = line.files.row_data(0).unwrap();
|
||||
assert_eq!((file.name.as_str(), file.detail.as_str()), ("plan.pdf", "2.0 kB"));
|
||||
assert_eq!(line.text, "here you go 🎉");
|
||||
assert!(line.rich);
|
||||
}
|
||||
// Only the link: no text.
|
||||
let only = line(&message("A", &format!("[URL={url}]plan.pdf[/URL]"), 0), None);
|
||||
assert!(only.text.is_empty() && !only.rich);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
//! [`list::sync`], so a small change redraws only what changed.
|
||||
|
||||
pub mod avatar;
|
||||
pub mod bbcode;
|
||||
pub mod chat;
|
||||
pub mod list;
|
||||
pub mod servers;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Texts of the home, friends, messages, bell and events screens: times
|
||||
//! ("12m ago", "Yesterday"), message previews without BBCode, mentions,
|
||||
//! event dates, a poke's message; pure, so they are tested here.
|
||||
//! ("12m ago", "Yesterday"), message previews without BBCode (read by
|
||||
//! `vm::bbcode`), mentions, event dates, a poke's message; pure, so they
|
||||
//! are tested here.
|
||||
|
||||
use chrono::{DateTime, Local, NaiveDateTime, TimeZone};
|
||||
|
||||
@@ -50,26 +51,19 @@ pub fn list_time_at(then: NaiveDateTime, now: NaiveDateTime) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Chat text without BBCode tags (`[b]`, `[URL=…]`, `[/URL]`), on one line.
|
||||
/// Chat text without BBCode (`[b]`, `[URL=…]`, `[/URL]`), on one line.
|
||||
pub fn plain(text: &str) -> String {
|
||||
let mut out = String::with_capacity(text.len());
|
||||
let mut rest = text;
|
||||
while let Some(open) = rest.find('[') {
|
||||
out.push_str(&rest[..open]);
|
||||
let after = &rest[open + 1..];
|
||||
match after.find(']') {
|
||||
Some(close) if is_tag(&after[..close]) => rest = &after[close + 1..],
|
||||
_ => {
|
||||
out.push('[');
|
||||
rest = after;
|
||||
}
|
||||
}
|
||||
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)));
|
||||
}
|
||||
out.push_str(rest);
|
||||
// Plain text draws no emoji (they are pictures in the chat): leave
|
||||
// them out of one-line previews.
|
||||
let out: String = out.chars().filter(|c| !is_emoji(*c)).collect();
|
||||
out.split_whitespace().collect::<Vec<_>>().join(" ")
|
||||
words.split_whitespace().collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
/// Pictographs, symbols and their joiners and variation selectors.
|
||||
@@ -77,13 +71,6 @@ fn is_emoji(c: char) -> bool {
|
||||
matches!(u32::from(c), 0x1F000..=0x1FAFF | 0x2600..=0x27BF | 0xFE0F | 0x200D)
|
||||
}
|
||||
|
||||
/// `b`, `/url`, `URL=https://…`, `color=#f00`: a BBCode tag.
|
||||
fn is_tag(inside: &str) -> bool {
|
||||
let name = inside.strip_prefix('/').unwrap_or(inside);
|
||||
let name = name.split('=').next().unwrap_or_default();
|
||||
!name.is_empty() && name.len() <= 8 && name.chars().all(|c| c.is_ascii_alphabetic())
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
@@ -224,6 +211,9 @@ mod tests {
|
||||
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!(
|
||||
|
||||
@@ -169,11 +169,34 @@ export struct ChatTab {
|
||||
banner-mode: int,
|
||||
}
|
||||
|
||||
// A piece of a chat line: text, or an emoji shown as an image (`emoji` is
|
||||
// its Twemoji key, e.g. "1f600"; `text` then holds the characters).
|
||||
// A piece of a chat line: a word in its style, or an emoji shown as an
|
||||
// image (`emoji` is its Twemoji key, e.g. "1f600"; `text` then holds the
|
||||
// characters).
|
||||
export struct TextRun {
|
||||
text: string,
|
||||
emoji: string,
|
||||
bold: bool,
|
||||
italic: bool,
|
||||
underline: bool,
|
||||
strike: bool,
|
||||
// Code: on a background.
|
||||
code: bool,
|
||||
// The author's colour, made readable on each theme; transparent: the
|
||||
// text's own.
|
||||
ink-dark: color,
|
||||
ink-light: color,
|
||||
// Where it links to ("": nowhere).
|
||||
link: string,
|
||||
}
|
||||
|
||||
// A block of a chat line (`vm::bbcode`): its runs, and what it is.
|
||||
export struct TextBlock {
|
||||
runs: [TextRun],
|
||||
// 0 = a line, 1 = a quote's line, 2 = a line of code, 3 = a list item,
|
||||
// 4 = a rule (no runs)
|
||||
kind: int,
|
||||
// Who a quote quotes, on its first line.
|
||||
caption: string,
|
||||
}
|
||||
|
||||
// One emoji under a message, with how many put it there.
|
||||
@@ -208,10 +231,13 @@ export struct ChatLine {
|
||||
// (the engine's ids do not fit a Slint int).
|
||||
key: int,
|
||||
author: string,
|
||||
// The text without formatting, a line per block (shown as it is when
|
||||
// the message has neither formatting nor emoji, and read out).
|
||||
text: string,
|
||||
time: string,
|
||||
// The text split into runs; only filled when it has emoji (`rich`).
|
||||
runs: [TextRun],
|
||||
// The text in blocks of styled runs; only filled when it has
|
||||
// formatting or emoji (`rich`).
|
||||
blocks: [TextBlock],
|
||||
rich: bool,
|
||||
// Only one to three emoji: shown large.
|
||||
jumbo: bool,
|
||||
@@ -232,6 +258,8 @@ export struct ChatLine {
|
||||
topic: string,
|
||||
// Highlighted after jumping to it from the pins.
|
||||
marked: bool,
|
||||
// The first web address it links to, "" if none.
|
||||
link: string,
|
||||
}
|
||||
|
||||
// A pinned message in the pins drawer.
|
||||
|
||||
@@ -1,37 +1,168 @@
|
||||
// Emoji as images (Twemoji through Rust's image cache): chat text with
|
||||
// inline emoji, and the picker.
|
||||
// formatting and inline emoji, and the picker.
|
||||
|
||||
import { Theme } from "../theme.slint";
|
||||
import { Icons } from "../icons.slint";
|
||||
import { Images, Emoji, TextRun, EmojiCell } from "../bridge.slint";
|
||||
import { Images, Emoji, TextRun, TextBlock, ChatLine, EmojiCell } from "../bridge.slint";
|
||||
import { Icon } from "icon.slint";
|
||||
import { SearchBox } from "text-field.slint";
|
||||
import { ListView } from "std-widgets.slint";
|
||||
|
||||
// Text with inline emoji: the runs flow and wrap like text (a flexbox of
|
||||
// words and emoji). Plain text needs no runs: use a Text then (faster).
|
||||
export component RichText inherits FlexboxLayout {
|
||||
// A word in its style, or an emoji. A Text draws no lines, so underline
|
||||
// (links too) and strike-through are 1 px rectangles over it.
|
||||
component Run inherits Rectangle {
|
||||
in property <TextRun> run;
|
||||
in property <length> font-size;
|
||||
// The text's own colour.
|
||||
in property <color> text-color;
|
||||
in property <length> emoji-size;
|
||||
property <bool> emoji: run.emoji != "";
|
||||
property <length> pad: run.code ? 3px : 0px;
|
||||
property <color> ink: run.link != "" ? Theme.accent-text : run.ink-dark.alpha > 0 ? (Theme.dark ? run.ink-dark : run.ink-light) : root.text-color;
|
||||
min-width: self.preferred-width;
|
||||
preferred-width: (root.emoji ? root.emoji-size : label.preferred-width) + 2 * root.pad;
|
||||
preferred-height: root.emoji ? root.emoji-size : label.preferred-height;
|
||||
border-radius: Theme.radius-xs;
|
||||
background: run.code ? Theme.surface-3 : transparent;
|
||||
label := Text {
|
||||
x: root.pad;
|
||||
width: self.preferred-width;
|
||||
text: root.emoji ? "" : run.text;
|
||||
font-size: root.font-size;
|
||||
font-weight: run.bold ? Theme.weight-bold : Theme.weight-regular;
|
||||
font-italic: run.italic;
|
||||
color: root.ink;
|
||||
accessible-role: AccessibleRole.none;
|
||||
}
|
||||
if root.emoji: Image {
|
||||
width: root.emoji-size;
|
||||
height: root.emoji-size;
|
||||
source: Images.emoji(run.emoji);
|
||||
image-fit: contain;
|
||||
accessible-role: AccessibleRole.image;
|
||||
accessible-label: run.text;
|
||||
}
|
||||
if run.underline || run.link != "": Rectangle {
|
||||
x: label.x;
|
||||
y: label.y + root.font-size * 1.1;
|
||||
width: label.width;
|
||||
height: 1px;
|
||||
background: root.ink;
|
||||
}
|
||||
if run.strike: Rectangle {
|
||||
x: label.x;
|
||||
y: label.y + root.font-size * 0.62;
|
||||
width: label.width;
|
||||
height: 1px;
|
||||
background: root.ink;
|
||||
}
|
||||
}
|
||||
|
||||
// The words and emoji of a block flow and wrap like text.
|
||||
component Runs inherits FlexboxLayout {
|
||||
in property <[TextRun]> runs;
|
||||
in property <length> font-size;
|
||||
in property <color> color;
|
||||
in property <length> emoji-size;
|
||||
spacing: 0px;
|
||||
cross-axis-alignment: center;
|
||||
for run in root.runs: Run {
|
||||
run: run;
|
||||
font-size: root.font-size;
|
||||
text-color: root.color;
|
||||
emoji-size: root.emoji-size;
|
||||
}
|
||||
}
|
||||
|
||||
// One block of rich text (`TextBlock`): a line, a quote's line with its bar
|
||||
// (the first with who said it), a line of code on a background, a list item
|
||||
// or a rule. A component of its own: Slint measures a component's height at
|
||||
// its width, but a layout repeated by `for` at a guessed width.
|
||||
component Block inherits Rectangle {
|
||||
in property <TextBlock> block;
|
||||
in property <length> font-size;
|
||||
in property <color> text-color;
|
||||
in property <length> emoji-size;
|
||||
background: block.kind == 2 ? Theme.surface-3 : transparent;
|
||||
HorizontalLayout {
|
||||
spacing: Theme.space-3;
|
||||
padding-left: block.kind == 2 ? Theme.space-3 : 0px;
|
||||
padding-right: self.padding-left;
|
||||
padding-top: block.kind == 2 ? 2px : block.kind == 4 ? Theme.space-2 : 0px;
|
||||
padding-bottom: self.padding-top;
|
||||
// A quote's bar.
|
||||
if block.kind == 1: Rectangle {
|
||||
width: 3px;
|
||||
border-radius: 1.5px;
|
||||
background: Theme.border-strong;
|
||||
}
|
||||
if block.kind == 3: Text {
|
||||
text: "•";
|
||||
font-size: root.font-size;
|
||||
color: root.text-color;
|
||||
accessible-role: AccessibleRole.none;
|
||||
}
|
||||
VerticalLayout {
|
||||
if block.caption != "": Text {
|
||||
text: block.caption;
|
||||
font-size: Theme.font-sm;
|
||||
font-weight: Theme.weight-semibold;
|
||||
color: Theme.text-secondary;
|
||||
}
|
||||
Runs {
|
||||
runs: block.runs;
|
||||
font-size: root.font-size;
|
||||
color: root.text-color;
|
||||
emoji-size: root.emoji-size;
|
||||
}
|
||||
}
|
||||
}
|
||||
if block.kind == 4: Rectangle {
|
||||
y: (parent.height - self.height) / 2;
|
||||
height: 1px;
|
||||
background: Theme.border-strong;
|
||||
}
|
||||
}
|
||||
|
||||
// Text with formatting and inline emoji, in blocks (`TextBlock`): lines,
|
||||
// quotes with a bar, code on a background, list items and rules. Plain text
|
||||
// needs no blocks: use a Text then (faster).
|
||||
export component RichText inherits VerticalLayout {
|
||||
in property <[TextBlock]> blocks;
|
||||
in property <length> font-size: Theme.font-body;
|
||||
in property <color> color: Theme.text;
|
||||
in property <length> emoji-size: font-size * 1.4;
|
||||
spacing: 0px;
|
||||
cross-axis-alignment: center;
|
||||
for run in root.runs: HorizontalLayout {
|
||||
if run.emoji == "": Text {
|
||||
text: run.text;
|
||||
font-size: root.font-size;
|
||||
color: root.color;
|
||||
accessible-role: AccessibleRole.none;
|
||||
}
|
||||
if run.emoji != "": Image {
|
||||
width: root.emoji-size;
|
||||
height: root.emoji-size;
|
||||
source: Images.emoji(run.emoji);
|
||||
image-fit: contain;
|
||||
accessible-role: AccessibleRole.image;
|
||||
accessible-label: run.text;
|
||||
}
|
||||
for block in root.blocks: Block {
|
||||
block: block;
|
||||
font-size: root.font-size;
|
||||
text-color: root.color;
|
||||
emoji-size: root.emoji-size;
|
||||
}
|
||||
}
|
||||
|
||||
// A message's text: one Text when it has neither formatting nor emoji
|
||||
// (fast), else its blocks; a note in place of a blocked contact's.
|
||||
export component MessageText inherits VerticalLayout {
|
||||
in property <ChatLine> line;
|
||||
in property <length> font-size: Theme.font-body;
|
||||
// Emoji alone (`jumbo`) are this large.
|
||||
in property <length> jumbo-size: 44px;
|
||||
if line.blocked: Text {
|
||||
text: @tr("Message from a blocked contact.");
|
||||
color: Theme.text-disabled;
|
||||
font-size: Theme.font-sm;
|
||||
font-italic: true;
|
||||
}
|
||||
if !line.blocked && !line.rich && line.text != "": Text {
|
||||
text: line.text;
|
||||
color: Theme.text;
|
||||
font-size: root.font-size;
|
||||
wrap: word-wrap;
|
||||
}
|
||||
if !line.blocked && line.rich: RichText {
|
||||
blocks: line.blocks;
|
||||
font-size: root.font-size;
|
||||
emoji-size: line.jumbo ? root.jumbo-size : root.font-size * 1.4;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ export { Meter, SpeakingBars } from "meter.slint";
|
||||
export { NavItem, ListItem } from "list-item.slint";
|
||||
export { MenuEntry, PopupMenu, Tooltip, Modal, Toast, ResizeHandle } from "overlay.slint";
|
||||
export { TooltipBubble, HoverTooltip } from "tooltip.slint";
|
||||
export { RichText, EmojiPicker } from "emoji.slint";
|
||||
export { RichText, MessageText, EmojiPicker } from "emoji.slint";
|
||||
// Virtualised lists and scrolling come from the standard widgets (styled by
|
||||
// the fluent-dark style); ListView builds only the visible rows.
|
||||
export { ListView, ScrollView } from "std-widgets.slint";
|
||||
@@ -6,7 +6,7 @@ import { Theme } from "../theme.slint";
|
||||
import { Icons } from "../icons.slint";
|
||||
import { Bridge, ChatLine, ReactionItem, FileItem, Images } from "../bridge.slint";
|
||||
import { Nav } from "../nav.slint";
|
||||
import { Icon, IconButton, Avatar, Chip, TabItem, TextField, RichText, Banner, Button, ButtonKind, Spinner, Tooltip, ListView, BannerPicture } from "../components/index.slint";
|
||||
import { Icon, IconButton, Avatar, Chip, TabItem, TextField, MessageText, Banner, Button, ButtonKind, Spinner, Tooltip, ListView, BannerPicture } from "../components/index.slint";
|
||||
|
||||
// A compact title and actions over the optional channel background.
|
||||
export component PageHeader inherits Rectangle {
|
||||
@@ -361,22 +361,9 @@ export component MessageRow inherits Rectangle {
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
}
|
||||
if line.blocked: Text {
|
||||
text: @tr("Message from a blocked contact.");
|
||||
color: Theme.text-disabled;
|
||||
font-size: Theme.font-sm;
|
||||
font-italic: true;
|
||||
}
|
||||
if !line.blocked && !line.rich && line.text != "": Text {
|
||||
text: line.text;
|
||||
color: Theme.text;
|
||||
MessageText {
|
||||
line: line;
|
||||
font-size: Theme.font-md;
|
||||
wrap: word-wrap;
|
||||
}
|
||||
if !line.blocked && line.rich: RichText {
|
||||
runs: line.runs;
|
||||
font-size: Theme.font-md;
|
||||
emoji-size: line.jumbo ? 44px : Theme.font-md * 1.4;
|
||||
}
|
||||
if line.files.length > 0 && !line.blocked: VerticalLayout {
|
||||
padding-top: Theme.space-2;
|
||||
|
||||
@@ -6,7 +6,7 @@ import { Theme } from "../theme.slint";
|
||||
import { Icons } from "../icons.slint";
|
||||
import { Bridge, PinItem, TopicItem, Images } from "../bridge.slint";
|
||||
import { Nav } from "../nav.slint";
|
||||
import { Icon, IconButton, Button, ButtonKind, TextField, SearchBox, Avatar, RichText, Spinner, Modal, ListView } from "../components/index.slint";
|
||||
import { Icon, IconButton, Button, ButtonKind, TextField, SearchBox, Avatar, MessageText, Spinner, Modal, ListView } from "../components/index.slint";
|
||||
import { Reactions } from "chat.slint";
|
||||
|
||||
// The title row both drawers share, above their content (@children).
|
||||
@@ -112,13 +112,9 @@ component PinCard inherits Rectangle {
|
||||
clicked => { Bridge.pin(pin.line.key, false); }
|
||||
}
|
||||
}
|
||||
if !pin.line.rich && pin.line.text != "": Text {
|
||||
text: pin.line.text;
|
||||
color: Theme.text;
|
||||
wrap: word-wrap;
|
||||
}
|
||||
if pin.line.rich: RichText {
|
||||
runs: pin.line.runs;
|
||||
MessageText {
|
||||
line: pin.line;
|
||||
jumbo-size: Theme.font-body * 1.4;
|
||||
}
|
||||
for file in pin.line.files: HorizontalLayout {
|
||||
spacing: Theme.space-2;
|
||||
|
||||
@@ -8,7 +8,7 @@ import { Theme } from "../theme.slint";
|
||||
import { Icons } from "../icons.slint";
|
||||
import { ChatLine } from "../bridge.slint";
|
||||
import { StudioBridge, StudioNav, StudioScene, StudioSource, StudioAudio, StudioLayer, StudioPick, StudioSourceForm, StudioSettingsForm } from "../studio-bridge.slint";
|
||||
import { Icon, Button, ButtonKind, IconButton, Avatar, LiveBadge, Chip, Toggle, ToggleRow, TextField, Field, Select, Slider, Meter, SegmentedTabs, Divider, Spinner, PopupMenu, MenuEntry, Modal, Tooltip, RichText, ListView, ScrollView } from "../components/index.slint";
|
||||
import { Icon, Button, ButtonKind, IconButton, Avatar, LiveBadge, Chip, Toggle, ToggleRow, TextField, Field, Select, Slider, Meter, SegmentedTabs, Divider, Spinner, PopupMenu, MenuEntry, Modal, Tooltip, MessageText, ListView, ScrollView } from "../components/index.slint";
|
||||
|
||||
// Icons of source and audio kinds.
|
||||
export global StudioKinds {
|
||||
@@ -953,15 +953,9 @@ component ChatRow inherits Rectangle {
|
||||
vertical-alignment: center;
|
||||
}
|
||||
}
|
||||
if !line.rich: Text {
|
||||
text: line.text;
|
||||
color: Theme.text;
|
||||
font-size: Theme.font-body;
|
||||
wrap: word-wrap;
|
||||
}
|
||||
if line.rich: RichText {
|
||||
runs: line.runs;
|
||||
emoji-size: line.jumbo ? 32px : Theme.font-body * 1.35;
|
||||
MessageText {
|
||||
line: line;
|
||||
jumbo-size: 32px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+49
-12
@@ -129,7 +129,8 @@ puts them on an inner `face`).
|
||||
| `Modal` | overlay.slint | dialog with backdrop: `title`, `subtitle`, `icon`, `card-width`, `card-height`; `dismissed` (backdrop, Escape, ×) |
|
||||
| `Toast` | overlay.slint | `text`, `icon`, `timeout`, `shown` |
|
||||
| `ResizeHandle` | overlay.slint | drag to resize a side panel: `size` (two-way), `minimum`, `maximum`, `left` |
|
||||
| `RichText` | emoji.slint | text with inline emoji: `runs` ([TextRun]) flow and wrap in a FlexboxLayout |
|
||||
| `RichText` | emoji.slint | text with formatting and inline emoji: `blocks` ([TextBlock]) of lines, quotes (a bar and the author), code (on a background), list items and rules; a block's `runs` ([TextRun]: bold, italic, underline, strike, code, the author's colour per theme, links in the accent colour) flow and wrap in a FlexboxLayout |
|
||||
| `MessageText` | emoji.slint | a message's text (`line`: ChatLine): one `Text` when it has neither formatting nor emoji, else a `RichText`; a note for a blocked contact's. The chat, the pins drawer and the studio's chat use it |
|
||||
| `EmojiPicker` | emoji.slint | search, categories, virtualised grid; `picked(EmojiCell)`, `close` |
|
||||
| `ListView`, `ScrollView` | std-widgets | re-exported (virtualised lists) |
|
||||
|
||||
@@ -145,7 +146,7 @@ comes from the engine's events; what a gateway adds is hidden without it.
|
||||
|
||||
| Part | `VOELIN_OPEN` | What it shows | Engine data |
|
||||
|---|---|---|---|
|
||||
| Chat | `server` | Header with Pinned Messages, Topics, the voice channel and the members button; chat tabs; messages grouped by author ("Today at 10:14"), avatars, emoji, reactions with an add button, pin and topic marks, file cards with download; composer with attach, emoji and send. Opens at the newest message and follows new ones while at the end | `ChatHistory` (and `Chat` for servers without history), `AvatarReady`, `Transfer`, `Gateway` (pins; reactions arrive as stored messages); `Command::LoadOlderHistory`, `DownloadChatFile`, `UploadFile`, `GatewayRequest::React`, `Unreact`, `Pin`, `Unpin` |
|
||||
| Chat | `server` (`server:chat`: the server chat) | Header with Pinned Messages, Topics, the voice channel and the members button; chat tabs; messages grouped by author ("Today at 10:14"), avatars, BBCode formatting (see Formatting below), emoji, reactions with an add button, pin and topic marks, file cards with download; composer with attach, emoji and send. The server chat starts with the server's welcome message (and its host message when the server puts it in the chat log). Opens at the newest message and follows new ones while at the end | `ChatHistory` (and `Chat` for servers without history), `Presence` (welcome and host message), `AvatarReady`, `Transfer`, `Gateway` (pins; reactions arrive as stored messages); `Command::LoadOlderHistory`, `DownloadChatFile`, `UploadFile`, `GatewayRequest::React`, `Unreact`, `Pin`, `Unpin` |
|
||||
| Members panel | `server` (`panel`, `no-panel`) | "Members — N" and a search; those streaming first (the people in our channel while the voice channel or a stream is shown), then each server group in the server's order with its icon, then those without a group. Rows: avatar with status, name, crown (admin groups), priority speaker, channel commander, recording, up to three myTeamSpeak badges, moderator role, talk power, what they do or the channel they are in. Resizable: the width is `ui.members_width` | `Presence`, `Groups`, `Talking`, `IconReady`, `PictureReady` |
|
||||
| Member card | `member` | Description, groups, badges (up to three chips in the client's order, what each is for on hover; "Badge" for one the app does not know), talk power, country; private message, poke, friend, block; volume and mute for us | `ContactsChanged`, `PictureReady` (badges); `Command::SetContact`, `SetClientVolume`, `SetClientMuted`, `Poke` |
|
||||
| Poke | `poke` (the first other member's, card open; after `friends` a contact's) | `PokeDialog`, from the member card, a friend's row and the direct message header: an optional message with a "12/100" count, Send off above 100 characters, Enter sends, Escape cancels | `Command::Poke` (trimmed, cut to 100 characters; the engine cuts too) |
|
||||
@@ -180,7 +181,7 @@ where a server has it.
|
||||
| The bell | `notifications` | Mentions, pokes, private messages, event reminders and friends coming online, newest first, unread marked; Mark all read, clear, the settings. Each kind is off, in the app or also a desktop notification (`notify.*`) | `Chat` and `ChatHistory` (mentions, private messages), `Poke`, `GatewayUpdate::EventReminder`, `FriendPresence`; `voelin_platform::notify` |
|
||||
| Search | `search[:<text>]` | Ctrl+K: servers, channels of every server, people (on the servers and the contacts) and the settings pages; arrows choose, Enter opens | the sessions, contacts, bookmarks |
|
||||
| Events | `events`, `event-form` | Above the channel tree (gateway `events`): a server's events with date, time, channel, scheduled stream, Going, Maybe and Not going with counts, who answered, reminders, Watch while live; create, edit and delete. Members (above the tree too) opens the members panel | `Gateway` events; `GatewayRequest::Events`, `CreateEvent`, `UpdateEvent`, `DeleteEvent`, `Rsvp` |
|
||||
| Pictures in chat | `picture` | A linked png, jpg, gif or webp up to `ui.image_preview_kb` is downloaded into memory, decoded once into the image cache and shown as a card in the message; a click opens it larger | `Command::DownloadChatFile` with `DownloadTo::Memory`, `Transfer` |
|
||||
| Pictures in chat | `picture` | A linked png, jpg, gif or webp up to `ui.image_preview_kb` is downloaded into memory, decoded once into the image cache and shown as a card in the message; a click opens it larger. A picture on the web a message shows (`[img]`) comes into the engine's picture cache like banners, up to the same size and only with `cache.fetch_images`; until then, or without it, the message shows its address as a link | `Command::DownloadChatFile` with `DownloadTo::Memory`, `Transfer`; `Command::FetchPicture`, `PictureReady` |
|
||||
| Join by address | `join` | The add-server dialog that connects once saved | `Command::ConnectVoice` |
|
||||
|
||||
Settings sections (`settings:<section>`):
|
||||
@@ -353,7 +354,7 @@ live when they change (settings page, `--set`, another window):
|
||||
| `ui.narrow_breakpoint` | pixels | 800 | below this width the phone layout |
|
||||
| `ui.image_cache_mb` | megabytes | 64 | decoded images kept in memory (0: none) |
|
||||
| `ui.members_width` | pixels | 280 | width of the members panel (dragging its edge sets it) |
|
||||
| `ui.image_preview_kb` | kilobytes | 8192 | pictures linked in chat up to this size show as pictures (0: never) |
|
||||
| `ui.image_preview_kb` | kilobytes | 8192 | pictures linked in chat (files and `[img]`) up to this size show as pictures (0: never) |
|
||||
| `notify.mentions`, `notify.private_messages`, `notify.pokes`, `notify.event_reminders`, `notify.friends_online` | off / app / desktop | desktop (friends: app) | what the bell and the desktop say about each kind |
|
||||
| `video.camera`, `video.background`, `video.resolution`, `video.mirror` | device id; none / blur; auto or WxH; bool | first camera, none, auto, true | the camera of the preview and the default of camera sources |
|
||||
| `studio.ui` | JSON | see below | the Stream Studio's stream settings: `title`, `game`, `message` (go-live), `show_viewers`, `show_chat`, `show_now_playing`, `audio` (stream audio), `preview_width` (960), `preview_fps` (15) |
|
||||
@@ -370,22 +371,57 @@ picker names and categories; 1.9 MB) and embedded in the binary. `emoji.rs`
|
||||
splits chat text into grapheme clusters, maps emoji to Twemoji keys (code
|
||||
points in hex; U+FE0F dropped outside ZWJ sequences, as Twemoji names its
|
||||
files; text-default symbols such as © or digits only with U+FE0F) and makes
|
||||
runs: one per word and one per emoji. A message without emoji stays one
|
||||
`Text` (fast path); one with emoji is a `RichText`, whose runs wrap in a
|
||||
`FlexboxLayout` (lines break between words, not inside them). One to three
|
||||
emoji alone are shown large. `Images.emoji(key)` decodes an emoji once
|
||||
runs of each span of a message (see Formatting): one per word and one per
|
||||
emoji. A message without formatting or emoji stays one `Text` (fast path);
|
||||
any other is a `RichText`, whose runs wrap in a `FlexboxLayout` (lines break
|
||||
between words, not inside them; a run does not wrap, so a word longer than
|
||||
24 characters, such as an address, is cut into runs). One to three emoji
|
||||
alone are shown large. `Images.emoji(key)` decodes an emoji once
|
||||
(`images.rs`, LRU by bytes) when a visible row asks for it.
|
||||
|
||||
The picker lists the emoji without skin-tone variants by category (coarse
|
||||
code-point ranges) and searches Unicode names. There are no shortcodes yet.
|
||||
|
||||
## Formatting
|
||||
|
||||
TeamSpeak clients format chat with BBCode. `vm/bbcode.rs` reads a message
|
||||
into a `Doc`: blocks (lines, quote lines, code, list items, rules) of spans
|
||||
with a style (bold, italic, underline, strike, code, colour, link) or a
|
||||
picture. The Doc does not depend on BBCode, so Markdown (TeamSpeak 6) can be
|
||||
a second parser making the same Doc.
|
||||
|
||||
- Tags: `[b]`, `[i]`, `[u]`, `[s]`, `[color=#rgb|#rrggbb|name]`, `[url]`,
|
||||
`[url=…]`, `[img]`, `[quote]`, `[quote=Name]`, `[code]` (nothing inside is
|
||||
a tag; one line is inline code, more are a block), `[list]` with `[*]`,
|
||||
`[hr]`. `[left]`, `[center]`, `[right]`, `[size]`, `[table]`, `[th]` and
|
||||
`[td]` are dropped and their text kept; `[tr]` starts a line.
|
||||
- Tags are read in any case, and only known ones: `[Nova] hi` and `[1]`
|
||||
stay text. A tag left open ends with the message; a closing tag that
|
||||
closes nothing stays text.
|
||||
- A line break starts a block. Bare `http(s)://` and `www.` addresses are
|
||||
links, without the punctuation after them. Links go only to the web,
|
||||
TeamSpeak servers and channel files: `[url=javascript:…]` is no link.
|
||||
- Colours are honoured, made readable on each theme (a contrast of 4.5:1 to
|
||||
the chat's background, keeping the hue).
|
||||
- Past 16 tags open at once or 1500 spans (or runs), a message is plain
|
||||
text.
|
||||
|
||||
`vm::chat` turns a Doc into `TextBlock`s of `TextRun`s, leaves out the file
|
||||
links shown as cards, and shows `[img]` pictures that are in the engine's
|
||||
cache as picture cards (else their address as a link). `ChatLine.text` is
|
||||
the plain text (quotes as `> `, list items as `• `), for screen readers and
|
||||
copying; `ChatLine.link` is the first web address. Lists of chats,
|
||||
notifications and the home's news show the text on one line
|
||||
(`Doc::one_line`). Built lines are kept per message id and revision
|
||||
(`LineCache`), so a refresh leaves unchanged rows alone.
|
||||
|
||||
## Development switches and screenshots
|
||||
|
||||
Environment variables (see `src/dev.rs`):
|
||||
|
||||
- `VOELIN_DEMO_UI=1`: sample servers, channels, members, chat with emoji and
|
||||
a stream, without a server (nothing is stored).
|
||||
- `VOELIN_OPEN=<what>[,<what>...]`: `home`, `server`, `settings[:voice|keybinds|streaming|privacy|appearance|profiles]` (`identities` is the same as `profiles`),
|
||||
- `VOELIN_DEMO_UI=1`: sample servers, channels, members, chat with
|
||||
formatting and emoji, and a stream, without a server (nothing is stored).
|
||||
- `VOELIN_OPEN=<what>[,<what>...]`: `home`, `server` (`server:chat`: the server chat), `settings[:voice|keybinds|streaming|privacy|appearance|profiles]` (`identities` is the same as `profiles`),
|
||||
`about`, `share[:live]`, `bookmark[:edit]`, `emoji`, `client`, `panel`, `no-panel`,
|
||||
`voice`, `pins`, `topics`, `topic:<id>`, `member`, `poke`,
|
||||
`channel-password[:wrong]`, `watch`, `popout`
|
||||
@@ -506,7 +542,8 @@ client's tree row shows the pictures that arrived right after the name (its
|
||||
group and client icons stay at the end); so does its row in the members
|
||||
panel.
|
||||
|
||||
The engine downloads banners and badges only while `cache.fetch_images` is
|
||||
The engine downloads banners and badges, and the pictures chat messages
|
||||
show (`[img]`, `Command::FetchPicture`), only while `cache.fetch_images` is
|
||||
enabled.
|
||||
Banners on the web (`http`, `https`) come from their host; banners in the
|
||||
server's own files, linked as `ts3image://` (TeamSpeak 5 and 6:
|
||||
|
||||
Reference in new issue
Block a user