Home, friends, direct messages, the bell, search, events and settings pages
The screens of design mockups 01, 02, 03 (server sidebar links) and 11 on the existing pattern (Bridge models synced row by row, view models in vm/, callbacks in bind/), mapped onto what TeamSpeak has: - Home: a banner with Voelin and each server, friends online from the sessions' presence, live streams of our servers (our channel, the gateways' directories, clients flagged streaming), the servers with Join, the latest chats across servers (history store), friend activity, quick actions (add, join by address, find friends) and what is happening (gateway events, scheduled streams, server news). The Library lists the Stream Studio's recordings and clips. - Friends: contacts with where they are, message, poke, join, watch, relation, note, volume and mute. - Direct messages: private chats of every server and of the store, pokes among the messages, a clear state when the peer cannot be reached, TS3/TS6 offline messages (list, read, send, delete). - The bell (mentions, pokes, messages, event reminders, friends coming online; a setting per kind, desktop notifications), the Ctrl+K search (servers, channels, people, settings pages; keyboard). - A server's events page (RSVP, attendees, create/edit/delete, scheduled streams) and the Events/Members entries above the tree. - Inline pictures in chat (downloaded into memory up to ui.image_preview_kb, decoded once into the image cache). - Settings: My Account, Profiles (identities: default, rename, delete, export, import from the official clients, security level on every core, identity per bookmark), Appearance, Voice & Video (camera preview with blur, video and stream quality, streaming permissions), Streaming (defaults, simulcast layers, audio sources), Devices, Notifications, Privacy & Safety, Keybinds, Integrations (gateways, gateway administration, encoders) and Advanced (SRTP order, history, cache, every setting as JSON). The top bar's field now opens the search instead of filtering the channel tree; the search finds channels of every server. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
1cd45af7fb
commit
c0ea5a3e46
69 files changed
+11751
-487
No files matched your search
@@ -50,6 +50,9 @@ fn open_settings(dir: &Path, overrides: &[String]) -> Settings {
|
||||
for key in appearance_keys() {
|
||||
prefs.register(key);
|
||||
}
|
||||
for key in crate::settings::page_keys() {
|
||||
prefs.register(key);
|
||||
}
|
||||
let config = std::env::var_os("VOELIN_CONFIG")
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| Some(dir.join("config.toml")).filter(|p| p.exists()));
|
||||
@@ -214,6 +217,8 @@ pub(crate) struct SessionView {
|
||||
pub downloads: HashMap<u64, crate::chat::Download>,
|
||||
/// The next transfer id.
|
||||
pub next_transfer: u64,
|
||||
/// What the home, messages and events screens keep of the session.
|
||||
pub extra: crate::social::SessionExtra,
|
||||
}
|
||||
|
||||
impl Default for SessionView {
|
||||
@@ -237,6 +242,7 @@ impl Default for SessionView {
|
||||
stream_viewers: HashMap::new(),
|
||||
downloads: HashMap::new(),
|
||||
next_transfer: 1,
|
||||
extra: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -296,6 +302,15 @@ pub(crate) struct Models {
|
||||
pub qualities: Rc<VecModel<slint::SharedString>>,
|
||||
/// Shown when there is no chat.
|
||||
pub no_chat: Rc<VecModel<ChatLine>>,
|
||||
/// Home, friends, messages, the bell, the search, events.
|
||||
pub social: crate::social::SocialModels,
|
||||
/// Settings pages.
|
||||
pub layers: Rc<VecModel<LayerItem>>,
|
||||
pub audio_sources: Rc<VecModel<AudioSourceItem>>,
|
||||
pub identities: Rc<VecModel<IdentityItem>>,
|
||||
pub gateway_config: Rc<VecModel<ConfigItem>>,
|
||||
pub gateway_perms: Rc<VecModel<PermItem>>,
|
||||
pub all_settings: Rc<VecModel<SettingItem>>,
|
||||
}
|
||||
|
||||
impl Models {
|
||||
@@ -313,6 +328,13 @@ impl Models {
|
||||
topic_messages: Rc::default(),
|
||||
qualities: Rc::default(),
|
||||
no_chat: Rc::default(),
|
||||
social: crate::social::SocialModels::new(bridge),
|
||||
layers: Rc::default(),
|
||||
audio_sources: Rc::default(),
|
||||
identities: Rc::default(),
|
||||
gateway_config: Rc::default(),
|
||||
gateway_perms: Rc::default(),
|
||||
all_settings: Rc::default(),
|
||||
};
|
||||
bridge.set_servers(ModelRc::from(models.servers.clone()));
|
||||
bridge.set_tree(ModelRc::from(models.tree.clone()));
|
||||
@@ -326,6 +348,12 @@ impl Models {
|
||||
bridge.set_topic_messages(ModelRc::from(models.topic_messages.clone()));
|
||||
bridge.set_viewer_qualities(ModelRc::from(models.qualities.clone()));
|
||||
bridge.set_messages(ModelRc::from(models.no_chat.clone()));
|
||||
bridge.set_layers(ModelRc::from(models.layers.clone()));
|
||||
bridge.set_audio_sources(ModelRc::from(models.audio_sources.clone()));
|
||||
bridge.set_identities(ModelRc::from(models.identities.clone()));
|
||||
bridge.set_gateway_config(ModelRc::from(models.gateway_config.clone()));
|
||||
bridge.set_gateway_perms(ModelRc::from(models.gateway_perms.clone()));
|
||||
bridge.set_all_settings(ModelRc::from(models.all_settings.clone()));
|
||||
models
|
||||
}
|
||||
}
|
||||
@@ -341,8 +369,6 @@ pub(crate) struct App {
|
||||
pub sessions: HashMap<i64, SessionView>,
|
||||
pub models: Models,
|
||||
pub status: String,
|
||||
/// The top bar's search: filters the channel tree.
|
||||
pub tree_filter: String,
|
||||
/// The members panel's search.
|
||||
pub member_filter: String,
|
||||
/// The topics drawer's search.
|
||||
@@ -389,6 +415,10 @@ pub(crate) struct App {
|
||||
/// Files being uploaded to a channel from the composer: session,
|
||||
/// channel and name, so the link can be posted when they are up.
|
||||
pub uploads: HashMap<u64, (i64, u64, String)>,
|
||||
/// Home, friends, messages, the bell and the search.
|
||||
pub social: crate::social::Social,
|
||||
/// The settings pages of the new design.
|
||||
pub pages: crate::settings_pages::Pages,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
@@ -556,7 +586,6 @@ pub fn run(options: RunOptions) -> Result<()> {
|
||||
sessions: HashMap::new(),
|
||||
models,
|
||||
status: String::new(),
|
||||
tree_filter: String::new(),
|
||||
member_filter: String::new(),
|
||||
topic_filter: String::new(),
|
||||
voice_view: false,
|
||||
@@ -583,14 +612,23 @@ pub fn run(options: RunOptions) -> Result<()> {
|
||||
open_client_pending: switches.open_client,
|
||||
notices_loaded: false,
|
||||
uploads: HashMap::new(),
|
||||
social: Default::default(),
|
||||
pages: Default::default(),
|
||||
};
|
||||
APP.with(|a| *a.borrow_mut() = Some(app));
|
||||
crate::bind::wire(&ui);
|
||||
with_app(|app| {
|
||||
app.apply_appearance();
|
||||
app.load_default_identity();
|
||||
app.apply_srtp();
|
||||
app.refresh_all();
|
||||
app.refresh_settings_flags();
|
||||
app.refresh_crash_notice();
|
||||
app.load_recent_chats();
|
||||
app.refresh_people();
|
||||
app.refresh_home();
|
||||
app.refresh_notices();
|
||||
app.refresh_pages();
|
||||
if app.demo {
|
||||
app.start_demo();
|
||||
}
|
||||
@@ -714,9 +752,16 @@ impl App {
|
||||
} else if appearance_keys().iter().any(|k| k.name() == key) {
|
||||
self.apply_appearance();
|
||||
}
|
||||
self.page_setting_changed(key);
|
||||
}
|
||||
|
||||
pub(crate) fn handle_event(&mut self, event: Event) {
|
||||
let touched = self.social_event(&event);
|
||||
self.dispatch(event);
|
||||
self.social_refresh(touched);
|
||||
}
|
||||
|
||||
fn dispatch(&mut self, event: Event) {
|
||||
match event {
|
||||
Event::State { session, state } => {
|
||||
let id = session as i64;
|
||||
@@ -813,7 +858,10 @@ impl App {
|
||||
Event::ChatHistory { session, target, messages, source, complete } => {
|
||||
self.history_batch(session as i64, &target, messages, source, complete);
|
||||
}
|
||||
Event::Gateway { session, update } => self.gateway_update(session as i64, update),
|
||||
Event::Gateway { session, update } => {
|
||||
self.gateway_extra(session as i64, &update);
|
||||
self.gateway_update(session as i64, update);
|
||||
}
|
||||
Event::Groups { session, server_groups, .. } => {
|
||||
let view = self.sessions.entry(session as i64).or_default();
|
||||
view.server_groups = (*server_groups).clone();
|
||||
@@ -859,6 +907,7 @@ impl App {
|
||||
/// Once a second.
|
||||
fn tick(&mut self) {
|
||||
self.tick_streams();
|
||||
self.tick_pages();
|
||||
if self.audio_dirty {
|
||||
self.save_audio();
|
||||
}
|
||||
|
||||
@@ -3,8 +3,10 @@
|
||||
|
||||
mod chat;
|
||||
mod emoji;
|
||||
mod pages;
|
||||
mod servers;
|
||||
mod settings;
|
||||
mod social;
|
||||
mod streams;
|
||||
|
||||
use crate::app::MainWindow;
|
||||
@@ -16,4 +18,6 @@ pub(crate) fn wire(ui: &MainWindow) {
|
||||
streams::wire(ui);
|
||||
settings::wire(ui);
|
||||
emoji::wire(ui);
|
||||
social::wire(ui);
|
||||
pages::wire(ui);
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
//! The settings pages of the new design (settings_pages.rs).
|
||||
|
||||
use slint::ComponentHandle;
|
||||
|
||||
use crate::app::{Bridge, MainWindow, with_app};
|
||||
|
||||
pub(super) fn wire(ui: &MainWindow) {
|
||||
let bridge = ui.global::<Bridge>();
|
||||
bridge.on_settings_section(|section| {
|
||||
with_app(|app| app.settings_section(section));
|
||||
});
|
||||
// Profiles.
|
||||
bridge.on_identity_action(|id, action| {
|
||||
with_app(|app| app.identity_action(id, &action));
|
||||
});
|
||||
bridge.on_rename_identity(|id, name| {
|
||||
with_app(|app| app.rename_identity(id, &name));
|
||||
});
|
||||
bridge.on_improve_target(|id, target| {
|
||||
with_app(|app| app.improve_identity(id, target));
|
||||
});
|
||||
bridge.on_find_identities(|| {
|
||||
with_app(|app| app.find_identities());
|
||||
});
|
||||
bridge.on_pick_found(|index, on| {
|
||||
with_app(|app| app.pick_found(index, on));
|
||||
});
|
||||
bridge.on_import_identities(|| {
|
||||
with_app(|app| app.import_identities());
|
||||
});
|
||||
bridge.on_bookmark_identity(|bookmark, index| {
|
||||
with_app(|app| app.bookmark_identity(bookmark, index));
|
||||
});
|
||||
// Voice & Video.
|
||||
bridge.on_video_changed(|form| {
|
||||
with_app(|app| app.video_changed(&form));
|
||||
});
|
||||
bridge.on_toggle_camera_preview(|| {
|
||||
with_app(|app| app.toggle_camera_preview());
|
||||
});
|
||||
bridge.on_test_sound(|| {
|
||||
with_app(|app| app.test_sound());
|
||||
});
|
||||
// Streaming.
|
||||
bridge.on_streaming_changed(|form| {
|
||||
with_app(|app| app.streaming_changed(&form));
|
||||
});
|
||||
bridge.on_layer_changed(|index, item| {
|
||||
with_app(|app| app.layer_changed(index, &item));
|
||||
});
|
||||
bridge.on_add_layer(|| {
|
||||
with_app(|app| app.add_layer());
|
||||
});
|
||||
bridge.on_remove_layer(|index| {
|
||||
with_app(|app| app.remove_layer(index));
|
||||
});
|
||||
bridge.on_audio_source_changed(|index, item| {
|
||||
with_app(|app| app.audio_source_changed(index, &item));
|
||||
});
|
||||
bridge.on_add_audio_source(|kind, name| {
|
||||
with_app(|app| app.add_audio_source(&kind, &name));
|
||||
});
|
||||
bridge.on_remove_audio_source(|index| {
|
||||
with_app(|app| app.remove_audio_source(index));
|
||||
});
|
||||
// Notifications, privacy.
|
||||
bridge.on_notify_changed(|form| {
|
||||
with_app(|app| app.notify_changed(&form));
|
||||
});
|
||||
bridge.on_test_notification(|| {
|
||||
with_app(|app| app.test_notification());
|
||||
});
|
||||
bridge.on_privacy_changed(|form| {
|
||||
with_app(|app| app.privacy_changed(&form));
|
||||
});
|
||||
// Integrations.
|
||||
bridge.on_gateway_admin(|session| {
|
||||
with_app(|app| app.gateway_admin(session));
|
||||
});
|
||||
bridge.on_config_set(|key, value| {
|
||||
with_app(|app| app.config_set(&key, &value));
|
||||
});
|
||||
bridge.on_config_reset(|key| {
|
||||
with_app(|app| app.config_reset(&key));
|
||||
});
|
||||
bridge.on_config_reload(|| {
|
||||
with_app(|app| app.config_reload());
|
||||
});
|
||||
bridge.on_perm_set(|action, everyone, server, channel| {
|
||||
with_app(|app| app.perm_set(&action, everyone, &server, &channel));
|
||||
});
|
||||
bridge.on_perm_reset(|action| {
|
||||
with_app(|app| app.perm_reset(&action));
|
||||
});
|
||||
bridge.on_refresh_encoders(|| {
|
||||
with_app(|app| app.refresh_encoders());
|
||||
});
|
||||
// Advanced.
|
||||
bridge.on_advanced_changed(|form| {
|
||||
with_app(|app| app.advanced_changed(&form));
|
||||
});
|
||||
bridge.on_srtp_move(|index, by| {
|
||||
with_app(|app| app.srtp_move(index, by));
|
||||
});
|
||||
bridge.on_srtp_toggle(|name| {
|
||||
with_app(|app| app.srtp_toggle(&name));
|
||||
});
|
||||
bridge.on_setting_set(|key, value| {
|
||||
with_app(|app| app.setting_set(&key, &value)).unwrap_or_default().into()
|
||||
});
|
||||
bridge.on_setting_reset(|key| {
|
||||
with_app(|app| app.setting_reset(&key));
|
||||
});
|
||||
bridge.on_search_settings(|text| {
|
||||
with_app(|app| app.search_settings(text.to_string()));
|
||||
});
|
||||
bridge.on_open_logs(|| {
|
||||
with_app(|app| app.open_logs());
|
||||
});
|
||||
}
|
||||
@@ -11,9 +11,6 @@ pub(super) fn wire(ui: &MainWindow) {
|
||||
bridge.on_select_server(|id| {
|
||||
with_app(|app| app.select_server(id as i64));
|
||||
});
|
||||
bridge.on_search(|text| {
|
||||
with_app(|app| app.search(text.to_string()));
|
||||
});
|
||||
bridge.on_search_members(|text| {
|
||||
with_app(|app| app.search_members(text.to_string()));
|
||||
});
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
//! Home, friends, direct messages, the bell, the search, a server's events
|
||||
//! and pictures in chat.
|
||||
|
||||
use slint::ComponentHandle;
|
||||
|
||||
use crate::app::{Bridge, MainWindow, with_app};
|
||||
|
||||
pub(super) fn wire(ui: &MainWindow) {
|
||||
let bridge = ui.global::<Bridge>();
|
||||
// Home.
|
||||
bridge.on_open_conversation(|key| {
|
||||
with_app(|app| app.open_conversation(key));
|
||||
});
|
||||
bridge.on_watch_live(|session, id| {
|
||||
with_app(|app| app.watch_live(i64::from(session), &id));
|
||||
});
|
||||
bridge.on_open_happening(|index| {
|
||||
with_app(|app| app.open_happening(index));
|
||||
});
|
||||
bridge.on_open_recording(|path| {
|
||||
with_app(|app| app.open_recording(&path));
|
||||
});
|
||||
bridge.on_open_recordings_folder(|| {
|
||||
with_app(|app| app.open_recordings_folder());
|
||||
});
|
||||
bridge.on_connect_server(|id| {
|
||||
with_app(|app| app.connect_server(i64::from(id)));
|
||||
});
|
||||
|
||||
// Friends.
|
||||
bridge.on_friends_tab(|tab| {
|
||||
with_app(|app| app.friends_tab(tab));
|
||||
});
|
||||
bridge.on_search_contacts(|text| {
|
||||
with_app(|app| app.search_contacts(text.to_string()));
|
||||
});
|
||||
bridge.on_select_contact(|uid| {
|
||||
with_app(|app| app.select_contact(uid.to_string()));
|
||||
});
|
||||
bridge.on_contact_action(|uid, action| {
|
||||
with_app(|app| app.contact_action(&uid, &action));
|
||||
});
|
||||
bridge.on_contact_note(|uid, note| {
|
||||
with_app(|app| app.contact_note(&uid, note.to_string()));
|
||||
});
|
||||
bridge.on_contact_volume(|uid, percent| {
|
||||
with_app(|app| app.contact_volume(&uid, percent));
|
||||
});
|
||||
|
||||
// Direct messages.
|
||||
bridge.on_dm_tab(|tab| {
|
||||
with_app(|app| app.dm_tab(tab));
|
||||
});
|
||||
bridge.on_search_conversations(|text| {
|
||||
with_app(|app| app.search_conversations(text.to_string()));
|
||||
});
|
||||
bridge.on_dm_action(|action| {
|
||||
with_app(|app| app.dm_action(&action));
|
||||
});
|
||||
bridge.on_dm_volume(|percent| {
|
||||
with_app(|app| app.dm_volume(percent));
|
||||
});
|
||||
bridge.on_send_offline(|form| {
|
||||
with_app(|app| app.send_offline(form));
|
||||
});
|
||||
|
||||
// The bell.
|
||||
bridge.on_open_notice(|key| {
|
||||
with_app(|app| app.open_notice(key));
|
||||
});
|
||||
bridge.on_mark_notices_read(|| {
|
||||
with_app(|app| app.mark_notices_read());
|
||||
});
|
||||
bridge.on_clear_notices(|| {
|
||||
with_app(|app| app.clear_notices());
|
||||
});
|
||||
|
||||
// The search: the top bar's field used to filter the channel tree;
|
||||
// it now opens the search (Ctrl+K), whose results are everywhere.
|
||||
bridge.on_search(|text| {
|
||||
with_app(|app| app.search(text.to_string()));
|
||||
});
|
||||
bridge.on_search_activate(|index| {
|
||||
with_app(|app| app.search_activate(index));
|
||||
});
|
||||
|
||||
// Events.
|
||||
bridge.on_open_events(|| {
|
||||
with_app(|app| app.open_events());
|
||||
});
|
||||
bridge.on_rsvp(|id, status| {
|
||||
with_app(|app| app.rsvp(id, &status));
|
||||
});
|
||||
bridge.on_toggle_event(|id| {
|
||||
with_app(|app| app.toggle_event(id));
|
||||
});
|
||||
bridge.on_edit_event(|id| with_app(|app| app.edit_event(id)).unwrap_or_default());
|
||||
bridge.on_save_event(|form| with_app(|app| app.save_event(&form)).unwrap_or_default().into());
|
||||
bridge.on_delete_event(|id| {
|
||||
with_app(|app| app.delete_event(id));
|
||||
});
|
||||
bridge.on_watch_event(|id| {
|
||||
with_app(|app| app.watch_event(id));
|
||||
});
|
||||
|
||||
// Pictures in chat.
|
||||
bridge.on_open_preview(|key, index| {
|
||||
with_app(|app| app.open_preview(key, index)).unwrap_or_default()
|
||||
});
|
||||
|
||||
// Opening the messages or the Library loads what they list.
|
||||
bridge.on_open_messages(|| {
|
||||
with_app(|app| app.load_recent_chats());
|
||||
});
|
||||
bridge.on_open_library(|| {
|
||||
with_app(|app| app.load_library());
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
//! The camera preview of the Voice & Video settings (the Stream Studio's
|
||||
//! camera capture, with its background blur), and the speakers' test tone.
|
||||
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use std::time::Duration;
|
||||
|
||||
use slint::{Image, Rgba8Pixel, SharedPixelBuffer};
|
||||
use tokio::sync::oneshot;
|
||||
use voelin_core::media::voelin_media::convert;
|
||||
use voelin_core::studio::camera::{self, Capture};
|
||||
use voelin_core::studio::compose::Feed;
|
||||
use voelin_core::studio::scene::Background;
|
||||
|
||||
use crate::app::with_app;
|
||||
|
||||
/// The cameras as (id, name): the devices, then the test pattern.
|
||||
pub(crate) fn list() -> Vec<(String, String)> {
|
||||
camera::list().into_iter().map(|c| (c.id, c.name)).collect()
|
||||
}
|
||||
|
||||
/// A running preview; the camera stops when it is dropped.
|
||||
pub(crate) struct Preview {
|
||||
feed: Arc<Feed>,
|
||||
status: Arc<Mutex<String>>,
|
||||
mirror: bool,
|
||||
_stop: oneshot::Sender<()>,
|
||||
_timer: slint::Timer,
|
||||
}
|
||||
|
||||
impl Preview {
|
||||
/// Open `device` (empty: the first camera) at `size` if it has it.
|
||||
pub fn start(
|
||||
runtime: &tokio::runtime::Handle,
|
||||
device: &str,
|
||||
size: Option<(u32, u32)>,
|
||||
blur: bool,
|
||||
mirror: bool,
|
||||
) -> Self {
|
||||
let feed = Arc::new(Feed::new());
|
||||
let status = Arc::new(Mutex::new(String::new()));
|
||||
let (stop, stopped) = oneshot::channel::<()>();
|
||||
let background = if blur { Background::Blur { strength: 0.04 } } else { Background::Keep };
|
||||
let (device, task_feed, task_status) = (device.to_owned(), feed.clone(), status.clone());
|
||||
runtime.spawn(async move {
|
||||
match Capture::start(&device, size, 30, task_feed, background).await {
|
||||
Ok(capture) => {
|
||||
// Runs until the preview is dropped.
|
||||
let _ = stopped.await;
|
||||
drop(capture);
|
||||
}
|
||||
Err(e) => {
|
||||
*task_status.lock().unwrap_or_else(PoisonError::into_inner) =
|
||||
format!("The camera does not start: {e}");
|
||||
}
|
||||
}
|
||||
});
|
||||
let timer = slint::Timer::default();
|
||||
timer.start(slint::TimerMode::Repeated, Duration::from_millis(66), || {
|
||||
with_app(|app| app.camera_frame());
|
||||
});
|
||||
Self { feed, status, mirror, _stop: stop, _timer: timer }
|
||||
}
|
||||
|
||||
/// The newest picture since the last call.
|
||||
pub fn take_picture(&self) -> Option<Image> {
|
||||
let frame = self.feed.take()?;
|
||||
let mut buffer = SharedPixelBuffer::<Rgba8Pixel>::new(frame.width, frame.height);
|
||||
let stride = frame.width as usize * 4;
|
||||
convert::to_rgba(&frame, buffer.make_mut_bytes(), stride).ok()?;
|
||||
if self.mirror {
|
||||
for row in buffer.make_mut_slice().chunks_mut(frame.width as usize) {
|
||||
row.reverse();
|
||||
}
|
||||
}
|
||||
Some(Image::from_rgba8(buffer))
|
||||
}
|
||||
|
||||
/// What to show while there is no picture.
|
||||
pub fn status(&self) -> String {
|
||||
let status = self.status.lock().unwrap_or_else(PoisonError::into_inner).clone();
|
||||
if !status.is_empty() {
|
||||
return status;
|
||||
}
|
||||
match self.feed.error() {
|
||||
Some(e) => e,
|
||||
None if self.feed.delivered() == 0 => "Starting the camera…".into(),
|
||||
None => String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Play a short two-tone chime on `device` (the system default for
|
||||
/// `None`) at `volume` (linear). Blocks while it plays.
|
||||
pub(crate) fn play_tone(device: Option<&str>, volume: f32) -> Result<(), String> {
|
||||
let mut out = voelin_audio::device::Playback::open(device, 300).map_err(|e| e.to_string())?;
|
||||
let rate = out.rate as f32;
|
||||
let channels = out.channels.max(1);
|
||||
let samples: Vec<f32> = (0..(rate * 0.7) as usize)
|
||||
.flat_map(|i| {
|
||||
let t = i as f32 / rate;
|
||||
let freq = if t < 0.35 { 660.0 } else { 880.0 };
|
||||
// Fade in and out of each note.
|
||||
let local = t % 0.35;
|
||||
let envelope = (local / 0.02).min(1.0) * ((0.35 - local) / 0.05).min(1.0);
|
||||
let v = (t * freq * std::f32::consts::TAU).sin() * 0.3 * envelope * volume.min(2.0);
|
||||
std::iter::repeat_n(v, channels)
|
||||
})
|
||||
.collect();
|
||||
let mut written = 0;
|
||||
while written < samples.len() {
|
||||
written += out.write(&samples[written..]);
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
while out.queued() > 0 {
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -96,6 +96,9 @@ impl App {
|
||||
view.tabs[index].unread = 0;
|
||||
view.tabs[index].topic = None;
|
||||
}
|
||||
if let Some(id) = self.current {
|
||||
self.fetch_previews(id);
|
||||
}
|
||||
self.refresh_chat();
|
||||
self.refresh_servers();
|
||||
}
|
||||
@@ -213,6 +216,7 @@ impl App {
|
||||
tab.unread += fresh;
|
||||
}
|
||||
if current {
|
||||
self.fetch_previews(id);
|
||||
self.refresh_chat();
|
||||
}
|
||||
if fresh > 0 && !shown {
|
||||
@@ -241,7 +245,7 @@ impl App {
|
||||
|| view.gateway_has(feature::REACTIONS)
|
||||
|| view.gateway_has(feature::TOPICS);
|
||||
let mut previous: Option<Previous> = None;
|
||||
let mut lines = Vec::with_capacity(messages.len());
|
||||
let mut lines: Vec<(i64, ChatLine)> = Vec::with_capacity(messages.len());
|
||||
for m in messages {
|
||||
let avatar =
|
||||
m.message.message.author_uid.as_ref().and_then(|uid| view.avatars.get(uid));
|
||||
@@ -252,6 +256,14 @@ impl App {
|
||||
.and_then(|t| tab.topics.iter().find(|i| i.id == t))
|
||||
.map(|t| t.title.clone())
|
||||
.unwrap_or_default();
|
||||
let previews = m
|
||||
.message
|
||||
.message
|
||||
.file_refs()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, f)| crate::previews::image_of(view, f).map(|image| (i, image)))
|
||||
.collect();
|
||||
let ctx = LineCtx {
|
||||
key: m.key,
|
||||
avatar: vm::avatar::image(avatar),
|
||||
@@ -259,11 +271,20 @@ impl App {
|
||||
marked: tab.marked == Some(m.message.id),
|
||||
topic,
|
||||
downloads: self.downloads_of(view, m.key),
|
||||
previews,
|
||||
};
|
||||
lines.push(vm::chat::history_line(&m.message, previous.as_ref(), &ctx));
|
||||
lines.push((
|
||||
m.message.message.ts_ms,
|
||||
vm::chat::history_line(&m.message, previous.as_ref(), &ctx),
|
||||
));
|
||||
previous = Some(Previous::of(&m.message.message));
|
||||
}
|
||||
lines
|
||||
// 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()
|
||||
}
|
||||
|
||||
/// The file cards of a message that has downloads running.
|
||||
@@ -694,6 +715,9 @@ impl App {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if self.preview_progress(id, transfer, &state) {
|
||||
return;
|
||||
}
|
||||
let done = matches!(state, TransferState::Done { .. });
|
||||
let view = self.sessions.entry(id).or_default();
|
||||
let Some(entry) = view.downloads.get_mut(&transfer) else { return };
|
||||
|
||||
@@ -0,0 +1,328 @@
|
||||
//! What a server's gateway tells besides chat: its events (the events
|
||||
//! page, RSVP, reminders), the stream directory and the activity feed (the
|
||||
//! home page), our permissions there, its configuration (gateway
|
||||
//! administration). The pins, reactions and topics are in `chat.rs`.
|
||||
|
||||
use slint::{ComponentHandle, SharedString};
|
||||
use voelin_core::{Command, GatewayRequest, GatewayUpdate};
|
||||
use voelin_gateway_proto::{Action, EventKind, EventQuery, EventSpec, RsvpStatus, feature};
|
||||
|
||||
use crate::app::{App, Bridge, EventForm, EventItem};
|
||||
use crate::social::{NoticeKind, NoticeTarget, now_ms};
|
||||
use crate::vm;
|
||||
use crate::vm::social::{date_block, event_when, format_local, parse_local, soon};
|
||||
|
||||
impl App {
|
||||
/// A request to a session's gateway (not for the sample sessions).
|
||||
pub(crate) fn gateway_to(&self, session: i64, request: GatewayRequest) {
|
||||
if !self.demo_ui {
|
||||
self.engine.send(Command::Gateway { session: session as u64, request });
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep what a gateway update tells these screens (before the chat
|
||||
/// handles its part).
|
||||
pub(crate) fn gateway_extra(&mut self, id: i64, update: &GatewayUpdate) {
|
||||
use GatewayUpdate as U;
|
||||
let mut ask: Vec<GatewayRequest> = Vec::new();
|
||||
let mut remind = None;
|
||||
let extra = &mut self.sessions.entry(id).or_default().extra;
|
||||
match update {
|
||||
U::Connected { uid, capabilities, .. } => {
|
||||
extra.gateway_uid = Some(uid.clone());
|
||||
let has = |f: &str| capabilities.iter().any(|c| c == f);
|
||||
ask.push(GatewayRequest::Permissions { channel: None });
|
||||
if has(feature::EVENTS) {
|
||||
ask.push(GatewayRequest::Events { query: EventQuery::default() });
|
||||
}
|
||||
if has(feature::STREAMS) {
|
||||
ask.push(GatewayRequest::Streams);
|
||||
}
|
||||
if has(feature::ACTIVITY) {
|
||||
ask.push(GatewayRequest::Activity { before: None, limit: Some(30) });
|
||||
}
|
||||
}
|
||||
U::Disconnected { .. } => {
|
||||
extra.directory.clear();
|
||||
extra.events.clear();
|
||||
extra.events_loaded = false;
|
||||
extra.activity.clear();
|
||||
extra.actions.clear();
|
||||
extra.config.clear();
|
||||
extra.perms.clear();
|
||||
}
|
||||
U::Permissions { channel: None, actions } => extra.actions = actions.clone(),
|
||||
U::Events { events } => {
|
||||
extra.events = events.clone();
|
||||
extra.events.sort_by_key(|e| e.spec.start_ms);
|
||||
extra.events_loaded = true;
|
||||
}
|
||||
U::Event { event } => {
|
||||
match extra.events.iter().position(|e| e.id == event.id) {
|
||||
Some(i) => extra.events[i] = event.clone(),
|
||||
None => extra.events.push(event.clone()),
|
||||
}
|
||||
extra.events.sort_by_key(|e| e.spec.start_ms);
|
||||
}
|
||||
U::EventDeleted { id: event } => extra.events.retain(|e| e.id != *event),
|
||||
U::EventReminder { event, starts_in_ms } => {
|
||||
remind = Some((event.clone(), *starts_in_ms))
|
||||
}
|
||||
U::Streams { streams } => extra.directory = streams.clone(),
|
||||
U::StreamStarted { stream }
|
||||
| U::StreamUpdated { stream }
|
||||
| U::StreamRegistered { stream } => {
|
||||
extra.directory.retain(|e| e.id != stream.id);
|
||||
extra.directory.push(stream.clone());
|
||||
}
|
||||
U::StreamEnded { id: stream, .. } => extra.directory.retain(|e| e.id != *stream),
|
||||
U::Activity { entries, .. } => extra.activity = entries.clone(),
|
||||
U::ActivityAdded { entry } => {
|
||||
extra.activity.insert(0, entry.clone());
|
||||
extra.activity.truncate(100);
|
||||
}
|
||||
U::Config { entries } => extra.config = entries.clone(),
|
||||
U::ConfigValue { entry } => {
|
||||
match extra.config.iter().position(|e| e.key == entry.key) {
|
||||
Some(i) => extra.config[i] = entry.clone(),
|
||||
None => extra.config.push(entry.clone()),
|
||||
}
|
||||
}
|
||||
U::PermRules { rules } => extra.perms = rules.clone(),
|
||||
_ => return,
|
||||
}
|
||||
for request in ask {
|
||||
self.gateway_to(id, request);
|
||||
}
|
||||
if let Some((event, starts_in_ms)) = remind {
|
||||
let minutes = starts_in_ms / 60_000;
|
||||
let title = if minutes <= 0 {
|
||||
format!("{} starts now", event.spec.title)
|
||||
} else {
|
||||
format!("{} starts in {minutes} min", event.spec.title)
|
||||
};
|
||||
let body = format!("on {}", self.server_name(id));
|
||||
self.notify(
|
||||
NoticeKind::Event,
|
||||
title,
|
||||
body,
|
||||
NoticeTarget::Event(id, event.id),
|
||||
event.creator.name.clone(),
|
||||
Some(event.creator.uid.clone()),
|
||||
);
|
||||
}
|
||||
self.refresh_home();
|
||||
self.refresh_events();
|
||||
self.refresh_gateways();
|
||||
}
|
||||
|
||||
/// The events page of the current server was opened.
|
||||
pub(crate) fn open_events(&mut self) {
|
||||
let Some(id) = self.current else { return };
|
||||
let loaded = self.sessions.get(&id).is_some_and(|v| v.extra.events_loaded);
|
||||
if !loaded {
|
||||
self.gateway_to(id, GatewayRequest::Events { query: EventQuery::default() });
|
||||
}
|
||||
self.refresh_events();
|
||||
}
|
||||
|
||||
/// Channels an event can be in: server-wide first.
|
||||
fn event_channels(&self) -> Vec<(Option<u64>, String)> {
|
||||
let mut out = vec![(None, "Server-wide".to_owned())];
|
||||
if let Some(view) = self.view() {
|
||||
out.extend(
|
||||
view.presence.channels.values().map(|c| (Some(c.id), format!("#{}", c.name))),
|
||||
);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub(crate) fn refresh_events(&self) {
|
||||
let Some(ui) = self.ui.upgrade() else { return };
|
||||
let bridge = ui.global::<Bridge>();
|
||||
let view = self.view();
|
||||
let has = view.is_some_and(|v| v.gateway_has(feature::EVENTS));
|
||||
bridge.set_has_events(has);
|
||||
let extra = view.map(|v| &v.extra);
|
||||
let moderate = extra.is_some_and(|e| e.actions.contains(&Action::Moderate));
|
||||
bridge.set_can_create_events(
|
||||
has && extra
|
||||
.is_some_and(|e| e.actions.is_empty() || e.actions.contains(&Action::CreateEvent)),
|
||||
);
|
||||
bridge.set_events_loading(has && !extra.is_some_and(|e| e.events_loaded));
|
||||
let channels = self.event_channels();
|
||||
bridge.set_event_channels(crate::app::model(
|
||||
channels.iter().map(|(_, n)| SharedString::from(n.as_str())).collect(),
|
||||
));
|
||||
let now = now_ms();
|
||||
let items: Vec<EventItem> = extra
|
||||
.map(|extra| {
|
||||
extra
|
||||
.events
|
||||
.iter()
|
||||
.filter(|e| e.spec.end_ms.unwrap_or(e.spec.start_ms + 3 * 3_600_000) >= now)
|
||||
.map(|e| {
|
||||
let (weekday, day, month) = date_block(e.spec.start_ms);
|
||||
let place = channels
|
||||
.iter()
|
||||
.find(|(c, _)| *c == e.spec.channel)
|
||||
.map_or_else(|| "A channel".to_owned(), |(_, n)| n.clone());
|
||||
let stream = if e.spec.kind == EventKind::Stream {
|
||||
[e.spec.stream_title.clone(), e.spec.stream_game.clone()]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|s| !s.is_empty())
|
||||
.collect::<Vec<_>>()
|
||||
.join(" · ")
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
let stream = if e.spec.kind == EventKind::Stream && stream.is_empty() {
|
||||
"Scheduled stream".to_owned()
|
||||
} else {
|
||||
stream
|
||||
};
|
||||
EventItem {
|
||||
id: e.id as i32,
|
||||
title: e.spec.title.clone().into(),
|
||||
description: e.spec.description.clone().into(),
|
||||
weekday: weekday.into(),
|
||||
day: day.into(),
|
||||
month: month.into(),
|
||||
when: event_when(e.spec.start_ms, e.spec.end_ms).into(),
|
||||
place: place.into(),
|
||||
stream: stream.into(),
|
||||
live: e.live_stream.is_some(),
|
||||
going: e.going as i32,
|
||||
maybe: e.maybe as i32,
|
||||
not_going: e.not_going as i32,
|
||||
rsvp: e.my_rsvp.map(RsvpStatus::as_str).unwrap_or_default().into(),
|
||||
creator: e.creator.name.clone().into(),
|
||||
editable: moderate
|
||||
|| extra.gateway_uid.as_deref() == Some(e.creator.uid.as_str()),
|
||||
soon: soon(e.spec.start_ms, e.spec.end_ms, now).into(),
|
||||
attendees: crate::app::model(
|
||||
e.attendees
|
||||
.iter()
|
||||
.map(|a| {
|
||||
let status = match a.status {
|
||||
RsvpStatus::Going => "going",
|
||||
RsvpStatus::Maybe => "maybe",
|
||||
RsvpStatus::NotGoing => "not going",
|
||||
RsvpStatus::Unknown => "?",
|
||||
};
|
||||
SharedString::from(format!("{} ({status})", a.user.name))
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
expanded: extra.expanded.contains(&e.id),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
vm::list::sync(&self.models.social.events, &items);
|
||||
}
|
||||
|
||||
/// Answer an event ("" withdraws the answer).
|
||||
pub(crate) fn rsvp(&mut self, event_id: i32, status: &str) {
|
||||
let Some(id) = self.current else { return };
|
||||
let status = (!status.is_empty()).then(|| RsvpStatus::parse(status));
|
||||
self.gateway_to(id, GatewayRequest::Rsvp { event_id: i64::from(event_id), status });
|
||||
}
|
||||
|
||||
/// Show or hide who answered (fetching the event with its attendees).
|
||||
pub(crate) fn toggle_event(&mut self, event_id: i32) {
|
||||
let Some(id) = self.current else { return };
|
||||
let event_id = i64::from(event_id);
|
||||
let view = self.sessions.entry(id).or_default();
|
||||
if !view.extra.expanded.remove(&event_id) {
|
||||
view.extra.expanded.insert(event_id);
|
||||
self.gateway_to(id, GatewayRequest::GetEvent { id: event_id });
|
||||
}
|
||||
self.refresh_events();
|
||||
}
|
||||
|
||||
/// The form for a new event (`-1`) or an existing one.
|
||||
pub(crate) fn edit_event(&self, event_id: i32) -> EventForm {
|
||||
let channels = self.event_channels();
|
||||
let event =
|
||||
self.view().and_then(|v| v.extra.events.iter().find(|e| e.id == i64::from(event_id)));
|
||||
match event {
|
||||
Some(e) => EventForm {
|
||||
id: event_id,
|
||||
title: e.spec.title.clone().into(),
|
||||
description: e.spec.description.clone().into(),
|
||||
start: format_local(e.spec.start_ms).into(),
|
||||
end: e.spec.end_ms.map(format_local).unwrap_or_default().into(),
|
||||
channel: channels.iter().position(|(c, _)| *c == e.spec.channel).unwrap_or(0)
|
||||
as i32,
|
||||
stream: e.spec.kind == EventKind::Stream,
|
||||
stream_title: e.spec.stream_title.clone().unwrap_or_default().into(),
|
||||
game: e.spec.stream_game.clone().unwrap_or_default().into(),
|
||||
},
|
||||
None => {
|
||||
// The next full hour.
|
||||
let start = (now_ms() / 3_600_000 + 1) * 3_600_000;
|
||||
EventForm { id: -1, start: format_local(start).into(), ..Default::default() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Create or change an event; the reason when the form is not right.
|
||||
pub(crate) fn save_event(&mut self, form: &EventForm) -> String {
|
||||
let Some(id) = self.current else { return "No server selected.".into() };
|
||||
let Some(start_ms) = parse_local(&form.start) else {
|
||||
return "Write the start as YYYY-MM-DD HH:MM.".into();
|
||||
};
|
||||
let end_ms = if form.end.trim().is_empty() {
|
||||
None
|
||||
} else {
|
||||
match parse_local(&form.end) {
|
||||
Some(end) if end > start_ms => Some(end),
|
||||
Some(_) => return "The end must be after the start.".into(),
|
||||
None => return "Write the end as YYYY-MM-DD HH:MM, or leave it empty.".into(),
|
||||
}
|
||||
};
|
||||
let channels = self.event_channels();
|
||||
let text = |s: &slint::SharedString| Some(s.to_string()).filter(|s| !s.trim().is_empty());
|
||||
let spec = EventSpec {
|
||||
title: form.title.trim().to_owned(),
|
||||
description: form.description.to_string(),
|
||||
start_ms,
|
||||
end_ms,
|
||||
channel: channels.get(form.channel.max(0) as usize).and_then(|(c, _)| *c),
|
||||
kind: if form.stream { EventKind::Stream } else { EventKind::General },
|
||||
stream_title: text(&form.stream_title).filter(|_| form.stream),
|
||||
stream_game: text(&form.game).filter(|_| form.stream),
|
||||
host_uid: None,
|
||||
};
|
||||
self.gateway_to(
|
||||
id,
|
||||
if form.id < 0 {
|
||||
GatewayRequest::CreateEvent { event: spec }
|
||||
} else {
|
||||
GatewayRequest::UpdateEvent { id: i64::from(form.id), event: spec }
|
||||
},
|
||||
);
|
||||
String::new()
|
||||
}
|
||||
|
||||
pub(crate) fn delete_event(&mut self, event_id: i32) {
|
||||
if let Some(id) = self.current {
|
||||
self.gateway_to(id, GatewayRequest::DeleteEvent { id: i64::from(event_id) });
|
||||
}
|
||||
}
|
||||
|
||||
/// Watch the stream of a live scheduled stream.
|
||||
pub(crate) fn watch_event(&mut self, event_id: i32) {
|
||||
let Some(id) = self.current else { return };
|
||||
let stream = self
|
||||
.view()
|
||||
.and_then(|v| v.extra.events.iter().find(|e| e.id == i64::from(event_id)))
|
||||
.and_then(|e| e.live_stream.clone());
|
||||
if let Some(stream) = stream {
|
||||
self.watch_live(id, &stream);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
//! The home page (design mockup 01): live streams on our servers, what is
|
||||
//! happening there (events, scheduled streams, server news), and the
|
||||
//! Library of recordings and clips. Friends are in `social.rs`, the recent
|
||||
//! chats in `messages.rs`.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use slint::ComponentHandle;
|
||||
use voelin_core::VoiceState;
|
||||
|
||||
use crate::app::{App, Bridge, HappeningItem, LiveItem, Nav, Page, RecordingItem};
|
||||
use crate::vm;
|
||||
use crate::vm::social::{event_when, plain};
|
||||
|
||||
/// What a "What's Happening" entry opens.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) enum Happening {
|
||||
Event(i64, i64),
|
||||
News(i64),
|
||||
}
|
||||
|
||||
/// "screen" → "Screen".
|
||||
fn kind_label(kind: &str) -> String {
|
||||
let mut chars = kind.chars();
|
||||
chars.next().map(|c| c.to_uppercase().chain(chars).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
impl App {
|
||||
/// Streams on our servers: those in our channel (we can watch them at
|
||||
/// once), the gateways' directories, and clients flagged streaming.
|
||||
fn live_rooms(&self) -> Vec<LiveItem> {
|
||||
let mut rooms = Vec::new();
|
||||
for b in &self.bookmarks {
|
||||
let Some(view) = self.sessions.get(&b.id) else { continue };
|
||||
let channel_of = |cid: Option<u64>| {
|
||||
cid.and_then(|c| view.presence.channels.get(&c))
|
||||
.map(|c| c.name.clone())
|
||||
.unwrap_or_default()
|
||||
};
|
||||
let backdrop = vm::avatar::tint(&b.name);
|
||||
let item = |id: String,
|
||||
title: String,
|
||||
client: Option<u16>,
|
||||
uid: Option<&str>,
|
||||
name: String| {
|
||||
let avatar = match (client, uid) {
|
||||
(Some(c), _) if view.avatar(c).is_some() => vm::avatar::image(view.avatar(c)),
|
||||
(_, Some(uid)) => self.avatar_of(uid),
|
||||
_ => slint::Image::default(),
|
||||
};
|
||||
LiveItem {
|
||||
session: b.id as i32,
|
||||
id: id.into(),
|
||||
title: title.into(),
|
||||
initials: vm::avatar::initials(&name).into(),
|
||||
tint: vm::avatar::tint(&name),
|
||||
avatar,
|
||||
streamer: name.into(),
|
||||
server: b.name.clone().into(),
|
||||
backdrop,
|
||||
..Default::default()
|
||||
}
|
||||
};
|
||||
let mut covered: Vec<u16> = Vec::new();
|
||||
if view.streams_available() {
|
||||
for s in &view.streams {
|
||||
let name = view.nickname(s.streamer.0);
|
||||
let title =
|
||||
if s.name.is_empty() { format!("{name}'s stream") } else { s.name.clone() };
|
||||
let mut room = item(s.id.clone(), title, Some(s.streamer.0), None, name);
|
||||
room.channel = channel_of(view.state.own_channel).into();
|
||||
room.viewers = view.stream_viewers.get(&s.id).map_or(0, |v| *v as i32);
|
||||
room.kind = match s.kind {
|
||||
voelin_core::stream::StreamKind::Screen => "Screen",
|
||||
voelin_core::stream::StreamKind::Window => "Window",
|
||||
voelin_core::stream::StreamKind::Camera => "Camera",
|
||||
voelin_core::stream::StreamKind::Other(_) => "",
|
||||
}
|
||||
.into();
|
||||
room.watchable = view.state.own_client != Some(s.streamer.0);
|
||||
covered.push(s.streamer.0);
|
||||
rooms.push(room);
|
||||
}
|
||||
}
|
||||
for e in &view.extra.directory {
|
||||
if e.client_id.is_some_and(|c| covered.contains(&c)) {
|
||||
continue;
|
||||
}
|
||||
let title = if e.title.is_empty() {
|
||||
format!("{}'s stream", e.streamer.name)
|
||||
} else {
|
||||
e.title.clone()
|
||||
};
|
||||
let mut room = item(
|
||||
e.id.clone(),
|
||||
title,
|
||||
e.client_id,
|
||||
Some(&e.streamer.uid),
|
||||
e.streamer.name.clone(),
|
||||
);
|
||||
room.channel = channel_of(e.channel).into();
|
||||
room.viewers = e.viewers.map_or(0, |v| v as i32);
|
||||
room.kind = kind_label(&e.kind).into();
|
||||
covered.extend(e.client_id);
|
||||
rooms.push(room);
|
||||
}
|
||||
for c in view.presence.clients.values() {
|
||||
if c.streaming != Some(true)
|
||||
|| covered.contains(&c.id)
|
||||
|| Some(c.id) == view.state.own_client
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let mut room = item(
|
||||
format!("client/{}", c.id),
|
||||
format!("{} is live", c.nickname),
|
||||
Some(c.id),
|
||||
c.uid.as_deref(),
|
||||
c.nickname.clone(),
|
||||
);
|
||||
room.channel = channel_of(Some(c.channel)).into();
|
||||
rooms.push(room);
|
||||
}
|
||||
}
|
||||
rooms
|
||||
}
|
||||
|
||||
/// Events, scheduled streams and server news of our servers, what is
|
||||
/// soonest first.
|
||||
pub(crate) fn happenings(&self) -> Vec<(HappeningItem, Happening)> {
|
||||
let now = crate::social::now_ms();
|
||||
let mut events: Vec<(i64, HappeningItem, Happening)> = Vec::new();
|
||||
let mut news = Vec::new();
|
||||
for b in &self.bookmarks {
|
||||
let Some(view) = self.sessions.get(&b.id) else { continue };
|
||||
for e in &view.extra.events {
|
||||
let ends = e.spec.end_ms.unwrap_or(e.spec.start_ms + 3 * 3_600_000);
|
||||
if ends < now {
|
||||
continue;
|
||||
}
|
||||
let stream = e.spec.kind == voelin_gateway_proto::EventKind::Stream;
|
||||
events.push((
|
||||
e.spec.start_ms,
|
||||
HappeningItem {
|
||||
kind: if stream { "stream" } else { "event" }.into(),
|
||||
title: e.spec.title.clone().into(),
|
||||
subtitle: if stream {
|
||||
format!("Scheduled stream · {}", b.name)
|
||||
} else {
|
||||
format!("Event · {}", b.name)
|
||||
}
|
||||
.into(),
|
||||
when: event_when(e.spec.start_ms, e.spec.end_ms).into(),
|
||||
session: b.id as i32,
|
||||
id: e.id as i32,
|
||||
live: e.live_stream.is_some(),
|
||||
},
|
||||
Happening::Event(b.id, e.id),
|
||||
));
|
||||
}
|
||||
let details = &view.presence.server;
|
||||
for (title, text) in [
|
||||
(format!("Welcome to {}", b.name), &details.welcome_message),
|
||||
(format!("News of {}", b.name), &details.host_message),
|
||||
] {
|
||||
let text = plain(text);
|
||||
if !text.is_empty() {
|
||||
news.push((
|
||||
HappeningItem {
|
||||
kind: "news".into(),
|
||||
title: title.into(),
|
||||
subtitle: text.into(),
|
||||
session: b.id as i32,
|
||||
..Default::default()
|
||||
},
|
||||
Happening::News(b.id),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
events.sort_by_key(|(start, ..)| *start);
|
||||
events
|
||||
.into_iter()
|
||||
.map(|(_, item, h)| (item, h))
|
||||
.take(6)
|
||||
.chain(news.into_iter().take(3))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Live rooms and what is happening (friends: `refresh_people`, chats:
|
||||
/// `refresh_chats`).
|
||||
pub(crate) fn refresh_home(&self) {
|
||||
let m = &self.models.social;
|
||||
vm::list::sync(&m.live, &self.live_rooms());
|
||||
let items: Vec<HappeningItem> = self.happenings().into_iter().map(|(i, _)| i).collect();
|
||||
vm::list::sync(&m.happenings, &items);
|
||||
}
|
||||
|
||||
/// A live room's card: watch it at once in our channel, else go to its
|
||||
/// server (and the streamer's channel, watching once there).
|
||||
pub(crate) fn watch_live(&mut self, session: i64, id: &str) {
|
||||
self.show_server(session);
|
||||
let Some(view) = self.sessions.get(&session) else { return };
|
||||
if view.streams_available() && view.streams.iter().any(|s| s.id == id) {
|
||||
self.watch_stream(id.to_owned());
|
||||
return;
|
||||
}
|
||||
let client = view
|
||||
.extra
|
||||
.directory
|
||||
.iter()
|
||||
.find(|e| e.id == id)
|
||||
.and_then(|e| e.client_id)
|
||||
.or_else(|| id.strip_prefix("client/").and_then(|c| c.parse().ok()));
|
||||
let Some(uid) =
|
||||
client.and_then(|c| view.presence.clients.get(&c)).and_then(|c| c.uid.clone())
|
||||
else {
|
||||
self.set_status("Join the streamer's channel with voice to watch.");
|
||||
return;
|
||||
};
|
||||
if view.state.voice == VoiceState::Connected {
|
||||
self.contact_action(&uid, "watch");
|
||||
} else {
|
||||
self.set_status("Connect with voice and join the streamer's channel to watch.");
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn open_happening(&mut self, index: i32) {
|
||||
let Some((_, target)) =
|
||||
usize::try_from(index).ok().and_then(|i| self.happenings().into_iter().nth(i))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
match target {
|
||||
Happening::Event(session, _) => {
|
||||
self.select_server(session);
|
||||
if let Some(ui) = self.ui.upgrade() {
|
||||
ui.global::<Nav>().invoke_show(Page::Events);
|
||||
}
|
||||
}
|
||||
Happening::News(session) => self.show_server(session),
|
||||
}
|
||||
}
|
||||
|
||||
/// Connect a bookmark with voice (the Join buttons).
|
||||
pub(crate) fn connect_server(&mut self, id: i64) {
|
||||
self.select_server(id);
|
||||
self.connect_voice();
|
||||
}
|
||||
|
||||
/// The folder of recordings and clips.
|
||||
fn recordings_dir(&self) -> PathBuf {
|
||||
voelin_core::studio::recording_dir(&self.prefs)
|
||||
}
|
||||
|
||||
/// List the recordings and clips (when the Library opens).
|
||||
pub(crate) fn load_library(&mut self) {
|
||||
let dir = self.recordings_dir();
|
||||
let items = recordings_in(&dir);
|
||||
vm::list::sync(&self.models.social.recordings, &items);
|
||||
if let Some(ui) = self.ui.upgrade() {
|
||||
ui.global::<Bridge>().set_recordings_dir(dir.display().to_string().into());
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn open_recording(&mut self, path: &str) {
|
||||
if let Err(e) = crate::app::open_path(Path::new(path)) {
|
||||
self.set_status(format!("Cannot open {path}: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn open_recordings_folder(&mut self) {
|
||||
let dir = self.recordings_dir();
|
||||
if let Err(e) = std::fs::create_dir_all(&dir).and_then(|()| crate::app::open_path(&dir)) {
|
||||
self.set_status(format!("Cannot open {}: {e}", dir.display()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The videos in `dir`, newest first.
|
||||
pub(crate) fn recordings_in(dir: &Path) -> Vec<RecordingItem> {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() };
|
||||
let mut files: Vec<(std::time::SystemTime, RecordingItem)> = entries
|
||||
.flatten()
|
||||
.filter_map(|e| {
|
||||
let path = e.path();
|
||||
let ext = path.extension()?.to_str()?.to_ascii_lowercase();
|
||||
if !["webm", "mkv", "mp4", "mov"].contains(&ext.as_str()) {
|
||||
return None;
|
||||
}
|
||||
let meta = e.metadata().ok()?;
|
||||
let modified = meta.modified().ok()?;
|
||||
let name = path.file_name()?.to_string_lossy().to_string();
|
||||
let when = chrono::DateTime::<chrono::Local>::from(modified).format("%-d %b %H:%M");
|
||||
Some((
|
||||
modified,
|
||||
RecordingItem {
|
||||
clip: name.to_lowercase().contains("clip"),
|
||||
detail: format!("{} · {when}", vm::chat::size_text(meta.len())).into(),
|
||||
name: name.into(),
|
||||
path: path.display().to_string().into(),
|
||||
},
|
||||
))
|
||||
})
|
||||
.collect();
|
||||
files.sort_by_key(|(t, _)| std::cmp::Reverse(*t));
|
||||
files.into_iter().map(|(_, item)| item).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn library_lists_videos() {
|
||||
let dir = std::env::temp_dir().join(format!("voelin-library-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("raid.webm"), b"1234").unwrap();
|
||||
std::fs::write(dir.join("clip-boss.mkv"), b"12").unwrap();
|
||||
std::fs::write(dir.join("notes.txt"), b"x").unwrap();
|
||||
let items = recordings_in(&dir);
|
||||
let mut names: Vec<String> = items.iter().map(|i| i.name.to_string()).collect();
|
||||
names.sort();
|
||||
assert_eq!(names, ["clip-boss.mkv", "raid.webm"]);
|
||||
assert!(items.iter().any(|i| i.clip && i.detail.starts_with("2 B")));
|
||||
assert!(recordings_in(&dir.join("missing")).is_empty());
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
assert_eq!(kind_label("screen"), "Screen");
|
||||
assert_eq!(kind_label(""), "");
|
||||
}
|
||||
}
|
||||
@@ -116,6 +116,21 @@ pub fn file(path: &std::path::Path) -> Image {
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// A picture from encoded bytes (PNG, JPEG, GIF, WebP), decoded once and
|
||||
/// kept by `key`; an empty image if it cannot be decoded.
|
||||
pub fn picture(key: &str, bytes: &[u8]) -> Image {
|
||||
let cache_key = format!("picture:{key}");
|
||||
CACHE
|
||||
.with(|c| {
|
||||
c.borrow_mut().get_or_load(&cache_key, || {
|
||||
let image = Image::load_from_data(bytes, None).ok()?;
|
||||
let size = image.size();
|
||||
Some((image, size.width as usize * size.height as usize * 4))
|
||||
})
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// A Twemoji by key; an empty image if there is none.
|
||||
pub fn emoji(key: &str) -> Image {
|
||||
if key.is_empty() {
|
||||
|
||||
@@ -3,15 +3,22 @@
|
||||
mod app;
|
||||
mod appearance;
|
||||
mod bind;
|
||||
mod camera;
|
||||
mod chat;
|
||||
mod dev;
|
||||
mod emoji;
|
||||
mod events;
|
||||
mod home;
|
||||
mod hotkey;
|
||||
mod images;
|
||||
mod members;
|
||||
mod messages;
|
||||
mod previews;
|
||||
mod servers;
|
||||
mod settings;
|
||||
mod settings_page;
|
||||
mod settings_pages;
|
||||
mod social;
|
||||
mod streams;
|
||||
mod video;
|
||||
mod vm;
|
||||
|
||||
@@ -0,0 +1,782 @@
|
||||
//! Direct messages (design mockup 02) and the recent chats of the home
|
||||
//! page: every chat the sessions hold and the newest ones in the history
|
||||
//! store, across servers; the open private chat with who it is with; TS3
|
||||
//! and TS6 offline messages (mail the server keeps).
|
||||
//!
|
||||
//! A private chat is a chat tab of its session (`ChatTarget::Private`
|
||||
//! stored under the peer's unique id), so opening one selects its server
|
||||
//! and its tab: the chat view's machinery (history pages, the composer)
|
||||
//! serves it. A chat only in the store (its server is not connected, or no
|
||||
//! longer a bookmark) is read from there and shown read-only.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use slint::{ComponentHandle, SharedString};
|
||||
use voelin_core::{Command, HistoryMessage, OfflineMessage, OfflineMessageInfo, VoiceState};
|
||||
use voelin_model::ChatTarget;
|
||||
use voelin_store::PageQuery;
|
||||
|
||||
use crate::app::{App, Bridge, ConversationItem, DmPeer, Nav, OfflineForm, Page, later};
|
||||
use crate::vm;
|
||||
use crate::vm::social::{ago, list_time, matches, plain, preview};
|
||||
|
||||
/// Keys of offline messages in the conversation list start here.
|
||||
const MAIL: i32 = 10_000;
|
||||
|
||||
/// A chat of any server.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct ChatRef {
|
||||
/// The bookmark (session) it belongs to, when known.
|
||||
pub session: Option<i64>,
|
||||
pub server_uid: Option<String>,
|
||||
pub target: ChatTarget,
|
||||
pub last: Option<HistoryMessage>,
|
||||
pub unread: i32,
|
||||
}
|
||||
|
||||
/// The open conversation.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct Open {
|
||||
pub session: Option<i64>,
|
||||
pub server_uid: Option<String>,
|
||||
pub uid: String,
|
||||
/// An offline message (session, id) shown instead of the chat.
|
||||
pub mail: Option<(i64, u32)>,
|
||||
/// Read from the store: no session holds the chat.
|
||||
pub stored: bool,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Dms {
|
||||
/// The newest stored message of every chat, with its server's unique id.
|
||||
pub stored: Vec<(String, HistoryMessage)>,
|
||||
/// Bookmarks by the server unique id remembered for their address.
|
||||
pub bookmark_of: HashMap<String, i64>,
|
||||
/// Every chat, newest first (the keys of the lists).
|
||||
pub chats: Vec<ChatRef>,
|
||||
/// The Inbox tab's offline messages: session and message.
|
||||
pub inbox: Vec<(i64, OfflineMessageInfo)>,
|
||||
/// 0 all, 1 unread, 2 inbox.
|
||||
pub tab: i32,
|
||||
pub filter: String,
|
||||
pub open: Option<Open>,
|
||||
/// The text of the open offline message.
|
||||
pub mail: Option<OfflineMessage>,
|
||||
/// Offline message requests in flight: session and what for.
|
||||
pub requests: HashMap<u64, (i64, &'static str)>,
|
||||
pub next_request: u64,
|
||||
}
|
||||
|
||||
impl App {
|
||||
/// Read the newest chats of the history store (start, and when the
|
||||
/// lists are shown).
|
||||
pub(crate) fn load_recent_chats(&mut self) {
|
||||
if self.demo_ui {
|
||||
return;
|
||||
}
|
||||
self.social.dm.bookmark_of.clear();
|
||||
for b in &self.bookmarks {
|
||||
for alias in [
|
||||
Some(format!("voice:{}", b.address)),
|
||||
b.gateway_url.as_ref().map(|u| format!("gateway:{u}")),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
if let Ok(Some(uid)) = self.store.server_alias(&alias) {
|
||||
self.social.dm.bookmark_of.insert(uid, b.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
let history = self.engine.history();
|
||||
self.engine.runtime().spawn(async move {
|
||||
let result = history.recent_chats(60).await;
|
||||
later(move |app| match result {
|
||||
Ok(list) => {
|
||||
app.social.dm.stored = list;
|
||||
app.refresh_chats();
|
||||
app.refresh_home();
|
||||
}
|
||||
Err(e) => tracing::warn!("cannot read recent chats: {e}"),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// The session a server unique id belongs to.
|
||||
fn session_of_server(&self, server_uid: &str) -> Option<i64> {
|
||||
self.sessions
|
||||
.iter()
|
||||
.find(|(_, v)| v.state.server_uid.as_deref() == Some(server_uid))
|
||||
.map(|(id, _)| *id)
|
||||
.or_else(|| self.social.dm.bookmark_of.get(server_uid).copied())
|
||||
}
|
||||
|
||||
/// What we call the peer of a private chat.
|
||||
pub(crate) fn peer_name(&self, uid: &str, last: Option<&HistoryMessage>) -> String {
|
||||
if let Some(c) = self.contacts.get(uid).filter(|c| !c.nickname.is_empty()) {
|
||||
return c.nickname.clone();
|
||||
}
|
||||
if let Some(s) = self.spots_of(uid).first() {
|
||||
return self.sessions[&s.session].nickname(s.client);
|
||||
}
|
||||
let from_peer = |m: &HistoryMessage| {
|
||||
(m.message.author_uid.as_deref() == Some(uid)).then(|| m.message.author_name.clone())
|
||||
};
|
||||
last.and_then(from_peer)
|
||||
.or_else(|| {
|
||||
self.sessions.values().flat_map(|v| &v.tabs).find_map(|t| {
|
||||
(t.target == ChatTarget::Private(uid.to_owned()))
|
||||
.then(|| t.messages.iter().rev().find_map(|m| from_peer(&m.message)))
|
||||
.flatten()
|
||||
})
|
||||
})
|
||||
.unwrap_or_else(|| uid.chars().take(8).collect())
|
||||
}
|
||||
|
||||
/// Every chat, newest first; then the lists that show them.
|
||||
pub(crate) fn refresh_chats(&mut self) {
|
||||
let mut chats: Vec<ChatRef> = Vec::new();
|
||||
for b in &self.bookmarks {
|
||||
let Some(view) = self.sessions.get(&b.id) else { continue };
|
||||
for tab in &view.tabs {
|
||||
let last = tab.messages.last().map(|m| m.message.clone());
|
||||
if last.is_none() && !matches!(tab.target, ChatTarget::Private(_)) {
|
||||
continue;
|
||||
}
|
||||
chats.push(ChatRef {
|
||||
session: Some(b.id),
|
||||
server_uid: view.state.server_uid.clone(),
|
||||
target: tab.target.clone(),
|
||||
last,
|
||||
unread: tab.unread,
|
||||
});
|
||||
}
|
||||
}
|
||||
for (server_uid, m) in &self.social.dm.stored {
|
||||
let known = chats.iter().any(|c| {
|
||||
c.target == m.message.target && c.server_uid.as_deref() == Some(server_uid.as_str())
|
||||
});
|
||||
if !known {
|
||||
chats.push(ChatRef {
|
||||
session: self.session_of_server(server_uid),
|
||||
server_uid: Some(server_uid.clone()),
|
||||
target: m.message.target.clone(),
|
||||
last: Some(m.clone()),
|
||||
unread: 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
chats.sort_by_key(|c| std::cmp::Reverse(c.last.as_ref().map_or(0, |m| m.message.ts_ms)));
|
||||
self.social.dm.chats = chats;
|
||||
self.social.dm.inbox = self
|
||||
.bookmarks
|
||||
.iter()
|
||||
.filter_map(|b| self.sessions.get(&b.id).map(|v| (b.id, v)))
|
||||
.flat_map(|(id, v)| v.extra.inbox.iter().map(move |m| (id, m.clone())))
|
||||
.collect();
|
||||
self.social.dm.inbox.sort_by_key(|(_, m)| std::cmp::Reverse(m.ts_s));
|
||||
self.refresh_conversations();
|
||||
self.refresh_dm();
|
||||
}
|
||||
|
||||
/// One chat for a list.
|
||||
fn conversation_item(&self, key: usize, chat: &ChatRef) -> ConversationItem {
|
||||
let session = chat.session;
|
||||
let server =
|
||||
session.map(|s| self.server_name(s)).unwrap_or_else(|| "Another server".into());
|
||||
let (title, avatar, online, kind) = match &chat.target {
|
||||
ChatTarget::Private(uid) => (
|
||||
self.peer_name(uid, chat.last.as_ref()),
|
||||
self.avatar_of(uid),
|
||||
!self.spots_of(uid).is_empty(),
|
||||
2,
|
||||
),
|
||||
ChatTarget::Channel(cid) => {
|
||||
let name = session
|
||||
.and_then(|s| self.sessions.get(&s))
|
||||
.and_then(|v| v.presence.channels.get(cid))
|
||||
.map_or_else(|| format!("#channel {cid}"), |c| format!("#{}", c.name));
|
||||
(name, slint::Image::default(), false, 1)
|
||||
}
|
||||
ChatTarget::Server => (server.clone(), slint::Image::default(), false, 0),
|
||||
};
|
||||
let (text, ts) = match &chat.last {
|
||||
Some(m) => {
|
||||
let mine = session.is_some_and(|s| self.is_own(s, &m.message));
|
||||
let files = m.message.file_refs();
|
||||
let mut text = preview(&m.message.text, mine, &files);
|
||||
if kind != 2 && !mine {
|
||||
text = format!("{}: {text}", m.message.author_name);
|
||||
}
|
||||
(text, m.message.ts_ms)
|
||||
}
|
||||
None => (String::new(), 0),
|
||||
};
|
||||
let open = self.social.dm.open.as_ref();
|
||||
ConversationItem {
|
||||
key: key as i32,
|
||||
kind,
|
||||
title: title.clone().into(),
|
||||
server: server.into(),
|
||||
preview: text.into(),
|
||||
time: list_time(ts).into(),
|
||||
ago: ago(ts).into(),
|
||||
unread: chat.unread,
|
||||
initials: vm::avatar::initials(&title).into(),
|
||||
tint: vm::avatar::tint(&title),
|
||||
avatar,
|
||||
online,
|
||||
selected: open.is_some_and(|o| {
|
||||
o.mail.is_none()
|
||||
&& ChatTarget::Private(o.uid.clone()) == chat.target
|
||||
&& (o.session == chat.session || o.server_uid == chat.server_uid)
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// The DM list, the recent chats of home and the unread counts.
|
||||
fn refresh_conversations(&self) {
|
||||
let Some(ui) = self.ui.upgrade() else { return };
|
||||
let bridge = ui.global::<Bridge>();
|
||||
let dm = &self.social.dm;
|
||||
let recent: Vec<ConversationItem> = dm
|
||||
.chats
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, c)| c.last.is_some())
|
||||
.take(4)
|
||||
.map(|(i, c)| self.conversation_item(i, c))
|
||||
.collect();
|
||||
vm::list::sync(&self.models.social.recent, &recent);
|
||||
let private = |c: &&ChatRef| matches!(c.target, ChatTarget::Private(_));
|
||||
let items: Vec<ConversationItem> = if dm.tab == 2 {
|
||||
dm.inbox
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, (session, m))| {
|
||||
let name = self.peer_name(&m.from_uid, None);
|
||||
ConversationItem {
|
||||
key: MAIL + i as i32,
|
||||
kind: 3,
|
||||
title: name.clone().into(),
|
||||
server: self.server_name(*session).into(),
|
||||
preview: m.subject.clone().into(),
|
||||
time: list_time(m.ts_s * 1000).into(),
|
||||
ago: ago(m.ts_s * 1000).into(),
|
||||
unread: i32::from(!m.read),
|
||||
initials: vm::avatar::initials(&name).into(),
|
||||
tint: vm::avatar::tint(&name),
|
||||
avatar: self.avatar_of(&m.from_uid),
|
||||
online: false,
|
||||
selected: dm
|
||||
.open
|
||||
.as_ref()
|
||||
.is_some_and(|o| o.mail == Some((*session, m.id))),
|
||||
}
|
||||
})
|
||||
.filter(|c| matches(&dm.filter, &[&c.title, &c.preview]))
|
||||
.collect()
|
||||
} else {
|
||||
dm.chats
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, c)| private(c) && (dm.tab == 0 || c.unread > 0))
|
||||
.map(|(i, c)| self.conversation_item(i, c))
|
||||
.filter(|c| matches(&dm.filter, &[&c.title, &c.preview]))
|
||||
.collect()
|
||||
};
|
||||
vm::list::sync(&self.models.social.conversations, &items);
|
||||
let unread: i32 = dm.chats.iter().filter(private).map(|c| c.unread).sum();
|
||||
bridge.set_dm_unread(unread);
|
||||
bridge.set_inbox_unread(dm.inbox.iter().filter(|(_, m)| !m.read).count() as i32);
|
||||
}
|
||||
|
||||
pub(crate) fn dm_tab(&mut self, tab: i32) {
|
||||
self.social.dm.tab = tab;
|
||||
if tab == 2 {
|
||||
for view in self.sessions.values_mut() {
|
||||
view.extra.inbox_asked = false;
|
||||
}
|
||||
self.ask_inboxes();
|
||||
}
|
||||
self.refresh_conversations();
|
||||
}
|
||||
|
||||
pub(crate) fn search_conversations(&mut self, text: String) {
|
||||
self.social.dm.filter = text;
|
||||
self.refresh_conversations();
|
||||
}
|
||||
|
||||
/// Open a chat of the lists (`-1` closes the open one).
|
||||
pub(crate) fn open_conversation(&mut self, key: i32) {
|
||||
if key < 0 {
|
||||
self.social.dm.open = None;
|
||||
self.refresh_dm();
|
||||
return;
|
||||
}
|
||||
if key >= MAIL {
|
||||
let Some((session, m)) = self.social.dm.inbox.get((key - MAIL) as usize).cloned()
|
||||
else {
|
||||
return;
|
||||
};
|
||||
self.open_mail(session, &m);
|
||||
return;
|
||||
}
|
||||
let Some(chat) = self.social.dm.chats.get(key as usize).cloned() else { return };
|
||||
match &chat.target {
|
||||
ChatTarget::Private(uid) => self.open_dm(chat.session, chat.server_uid.clone(), uid),
|
||||
target => {
|
||||
let Some(session) = chat.session else {
|
||||
self.set_status("That server is not in your bookmarks.");
|
||||
return;
|
||||
};
|
||||
self.show_server(session);
|
||||
self.open_chat(target.clone(), true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Message someone: where they are with voice, else the newest
|
||||
/// conversation with them, else where they were seen.
|
||||
pub(crate) fn message_person(&mut self, uid: &str) {
|
||||
let spots = self.spots_of(uid);
|
||||
let session = spots.iter().find(|s| s.voice).or(spots.first()).map(|s| s.session);
|
||||
self.open_dm_with(session, uid);
|
||||
}
|
||||
|
||||
/// Open the private chat with `uid`, in `session` if given.
|
||||
pub(crate) fn open_dm_with(&mut self, session: Option<i64>, uid: &str) {
|
||||
let target = ChatTarget::Private(uid.to_owned());
|
||||
let known = self
|
||||
.social
|
||||
.dm
|
||||
.chats
|
||||
.iter()
|
||||
.find(|c| c.target == target && (session.is_none() || c.session == session));
|
||||
let session = session.or_else(|| known.and_then(|c| c.session));
|
||||
let server_uid = session
|
||||
.and_then(|s| self.sessions.get(&s))
|
||||
.and_then(|v| v.state.server_uid.clone())
|
||||
.or_else(|| known.and_then(|c| c.server_uid.clone()));
|
||||
self.open_dm(session, server_uid, uid);
|
||||
}
|
||||
|
||||
/// Open a private chat: in its session when one holds it, else from
|
||||
/// the store.
|
||||
pub(crate) fn open_dm(&mut self, session: Option<i64>, server_uid: Option<String>, uid: &str) {
|
||||
let live = session
|
||||
.and_then(|s| self.sessions.get(&s))
|
||||
.is_some_and(|v| v.has_history() || v.state.voice == VoiceState::Connected);
|
||||
self.social.dm.open = Some(Open {
|
||||
session,
|
||||
server_uid: server_uid.clone(),
|
||||
uid: uid.to_owned(),
|
||||
mail: None,
|
||||
stored: !live,
|
||||
});
|
||||
self.social.dm.mail = None;
|
||||
vm::list::sync(&self.models.social.dm_lines, &[]);
|
||||
let target = ChatTarget::Private(uid.to_owned());
|
||||
if let (true, Some(id)) = (live, session) {
|
||||
if self.current != Some(id) {
|
||||
self.select_server(id);
|
||||
}
|
||||
self.open_chat(target, true);
|
||||
} else if let Some(server_uid) = server_uid.filter(|_| !self.demo_ui) {
|
||||
let history = self.engine.history();
|
||||
let uid = uid.to_owned();
|
||||
self.engine.runtime().spawn(async move {
|
||||
let query = PageQuery { limit: Some(200), ..PageQuery::default() };
|
||||
let page = history.page(&server_uid, &target, query, false).await;
|
||||
later(move |app| app.stored_dm(&uid, page.unwrap_or_default()));
|
||||
});
|
||||
}
|
||||
if let Some(ui) = self.ui.upgrade() {
|
||||
ui.global::<Nav>().invoke_show(Page::Messages);
|
||||
}
|
||||
self.refresh_chats();
|
||||
}
|
||||
|
||||
/// The stored messages of a chat no session holds.
|
||||
pub(crate) fn stored_dm(&mut self, uid: &str, messages: Vec<HistoryMessage>) {
|
||||
if !self.social.dm.open.as_ref().is_some_and(|o| o.stored && o.uid == uid) {
|
||||
return;
|
||||
}
|
||||
let mut previous = None;
|
||||
let lines: Vec<_> = messages
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, m)| {
|
||||
let ctx = vm::chat::LineCtx {
|
||||
key: -1 - i as i32,
|
||||
avatar: m
|
||||
.message
|
||||
.author_uid
|
||||
.as_deref()
|
||||
.map(|u| self.avatar_of(u))
|
||||
.unwrap_or_default(),
|
||||
..Default::default()
|
||||
};
|
||||
let line = vm::chat::history_line(m, previous.as_ref(), &ctx);
|
||||
previous = Some(vm::chat::Previous::of(&m.message));
|
||||
line
|
||||
})
|
||||
.collect();
|
||||
vm::list::sync(&self.models.social.dm_lines, &lines);
|
||||
self.refresh_dm();
|
||||
}
|
||||
|
||||
/// Whether the private chat with `uid` in `session` is on screen.
|
||||
pub(crate) fn dm_shown(&self, session: i64, uid: &str) -> bool {
|
||||
let page = self.ui.upgrade().map(|ui| ui.global::<Nav>().get_page());
|
||||
page == Some(Page::Messages)
|
||||
&& self
|
||||
.social
|
||||
.dm
|
||||
.open
|
||||
.as_ref()
|
||||
.is_some_and(|o| o.mail.is_none() && o.uid == uid && o.session == Some(session))
|
||||
}
|
||||
|
||||
/// Who the open conversation is with, and what can be done.
|
||||
pub(crate) fn refresh_dm(&self) {
|
||||
let Some(ui) = self.ui.upgrade() else { return };
|
||||
let bridge = ui.global::<Bridge>();
|
||||
let Some(open) = &self.social.dm.open else {
|
||||
bridge.set_dm(DmPeer::default());
|
||||
return;
|
||||
};
|
||||
let uid = open.uid.as_str();
|
||||
let contact = self.contacts.get(uid);
|
||||
let spots = self.spots_of(uid);
|
||||
let here = open.session.and_then(|s| spots.iter().find(|sp| sp.session == s));
|
||||
let view = open.session.and_then(|s| self.sessions.get(&s));
|
||||
let client = here.and_then(|s| self.sessions[&s.session].presence.clients.get(&s.client));
|
||||
let tab =
|
||||
view.and_then(|v| v.tabs.iter().find(|t| t.target == ChatTarget::Private(uid.into())));
|
||||
let name = self.peer_name(uid, tab.and_then(|t| t.messages.last().map(|m| &m.message)));
|
||||
let server =
|
||||
open.session.map(|s| self.server_name(s)).unwrap_or_else(|| "another server".into());
|
||||
let voice = view.is_some_and(|v| v.state.voice == VoiceState::Connected);
|
||||
let blocked = contact.is_some_and(|c| c.relation == voelin_core::Relation::Blocked);
|
||||
let status = match here.or(spots.first()) {
|
||||
Some(s) => match &s.away {
|
||||
Some(m) if !m.is_empty() => format!("Away: {m} · {}", s.server),
|
||||
Some(_) => format!("Away · {}", s.server),
|
||||
None if s.channel_name.is_empty() => format!("Online · {}", s.server),
|
||||
None => format!("Online · {} · #{}", s.server, s.channel_name),
|
||||
},
|
||||
None => match contact.filter(|c| c.last_seen_ms > 0) {
|
||||
Some(c) => format!("Offline · last seen {}", ago(c.last_seen_ms)),
|
||||
None => "Offline".into(),
|
||||
},
|
||||
};
|
||||
let groups: Vec<SharedString> = match (client, view) {
|
||||
(Some(c), Some(v)) => c
|
||||
.server_groups
|
||||
.iter()
|
||||
.filter_map(|g| v.server_groups.iter().find(|i| i.id == *g))
|
||||
.map(|g| g.name.clone().into())
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let servers: Vec<SharedString> = if spots.is_empty() {
|
||||
contact
|
||||
.and_then(|c| c.last_server.clone())
|
||||
.map(|s| {
|
||||
vec![
|
||||
format!("{s} · last seen {}", ago(contact.map_or(0, |c| c.last_seen_ms)))
|
||||
.into(),
|
||||
]
|
||||
})
|
||||
.unwrap_or_default()
|
||||
} else {
|
||||
spots
|
||||
.iter()
|
||||
.map(|s| {
|
||||
if s.channel_name.is_empty() {
|
||||
s.server.clone().into()
|
||||
} else {
|
||||
format!("{} · #{}", s.server, s.channel_name).into()
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let files: Vec<SharedString> = tab
|
||||
.map(|t| {
|
||||
t.messages
|
||||
.iter()
|
||||
.flat_map(|m| m.message.message.file_refs())
|
||||
.map(|f| match f.size {
|
||||
Some(size) => format!("{} · {}", f.name, vm::chat::size_text(size)).into(),
|
||||
None => f.name.into(),
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let can_send = voice && here.is_some() && !blocked;
|
||||
let offline =
|
||||
voice && here.is_none() && view.is_some_and(|v| v.capabilities.offline_messages);
|
||||
let in_bookmarks = open.session.is_some_and(|s| self.bookmark(s).is_some());
|
||||
let notice = if open.session.is_none() {
|
||||
"This server is not in your bookmarks: the messages are the ones stored on this device."
|
||||
.to_owned()
|
||||
} else if !voice {
|
||||
format!("Connect to {server} with voice to send messages.")
|
||||
} else if here.is_none() {
|
||||
format!(
|
||||
"{name} is not on {server} now: TeamSpeak delivers private messages only to people online on the server."
|
||||
)
|
||||
} else if blocked {
|
||||
format!("You blocked {name}.")
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
let mail = open.mail.and_then(|(s, id)| {
|
||||
self.social
|
||||
.dm
|
||||
.inbox
|
||||
.iter()
|
||||
.find(|(ms, m)| *ms == s && m.id == id)
|
||||
.map(|(_, m)| m.clone())
|
||||
});
|
||||
bridge.set_dm(DmPeer {
|
||||
open: true,
|
||||
uid: uid.into(),
|
||||
name: name.clone().into(),
|
||||
initials: vm::avatar::initials(&name).into(),
|
||||
tint: vm::avatar::tint(&name),
|
||||
avatar: self.avatar_of(uid),
|
||||
online: !spots.is_empty(),
|
||||
status: status.into(),
|
||||
description: client.and_then(|c| c.description.clone()).unwrap_or_default().into(),
|
||||
groups: crate::app::model(groups),
|
||||
note: contact.map(|c| c.note.clone()).unwrap_or_default().into(),
|
||||
since: contact
|
||||
.filter(|c| c.added_ms > 0)
|
||||
.and_then(|c| chrono::DateTime::from_timestamp_millis(c.added_ms))
|
||||
.map(|t| {
|
||||
format!("Contact since {}", t.with_timezone(&chrono::Local).format("%-d %b %Y"))
|
||||
})
|
||||
.unwrap_or_default()
|
||||
.into(),
|
||||
servers: crate::app::model(servers),
|
||||
files: crate::app::model(files),
|
||||
friend: contact.is_some_and(|c| c.relation == voelin_core::Relation::Friend),
|
||||
blocked,
|
||||
volume: contact.map_or(100.0, |c| c.volume * 100.0),
|
||||
muted: contact.is_some_and(|c| c.muted),
|
||||
can_send,
|
||||
notice: notice.into(),
|
||||
offline,
|
||||
can_connect: !voice && in_bookmarks,
|
||||
stored: open.stored,
|
||||
mail: open.mail.is_some(),
|
||||
mail_subject: mail.as_ref().map(|m| m.subject.clone()).unwrap_or_default().into(),
|
||||
mail_text: self
|
||||
.social
|
||||
.dm
|
||||
.mail
|
||||
.as_ref()
|
||||
.map(|m| plain(&m.text))
|
||||
.unwrap_or_default()
|
||||
.into(),
|
||||
mail_time: mail.map(|m| vm::chat::time_of(m.ts_s * 1000)).unwrap_or_default().into(),
|
||||
});
|
||||
}
|
||||
|
||||
/// The buttons of the open conversation.
|
||||
pub(crate) fn dm_action(&mut self, action: &str) {
|
||||
let Some(open) = self.social.dm.open.clone() else { return };
|
||||
let uid = open.uid.clone();
|
||||
match action {
|
||||
"poke" | "join" | "mute" => self.contact_action(&uid, action),
|
||||
"friend" | "block" => {
|
||||
let current = self.contacts.get(&uid).map(|c| c.relation);
|
||||
let wanted = if action == "friend" {
|
||||
voelin_core::Relation::Friend
|
||||
} else {
|
||||
voelin_core::Relation::Blocked
|
||||
};
|
||||
let next = if current == Some(wanted) { "neutral" } else { action };
|
||||
self.contact_action(&uid, next);
|
||||
}
|
||||
"connect" => {
|
||||
if let Some(session) = open.session {
|
||||
self.select_server(session);
|
||||
self.connect_voice();
|
||||
}
|
||||
}
|
||||
"delete-mail" | "unread-mail" => {
|
||||
let Some((session, id)) = open.mail else { return };
|
||||
let request = self.offline_request(
|
||||
session,
|
||||
if action == "delete-mail" { "delete" } else { "unread" },
|
||||
);
|
||||
if !self.demo_ui {
|
||||
self.engine.send(if action == "delete-mail" {
|
||||
Command::DeleteOfflineMessage { session: session as u64, request, id }
|
||||
} else {
|
||||
Command::SetOfflineMessageRead {
|
||||
session: session as u64,
|
||||
request,
|
||||
id,
|
||||
read: false,
|
||||
}
|
||||
});
|
||||
}
|
||||
if action == "delete-mail" {
|
||||
self.social.dm.open = None;
|
||||
}
|
||||
self.refresh_chats();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn dm_volume(&mut self, percent: f32) {
|
||||
if let Some(uid) = self.social.dm.open.as_ref().map(|o| o.uid.clone()) {
|
||||
self.contact_volume(&uid, percent);
|
||||
}
|
||||
}
|
||||
|
||||
fn offline_request(&mut self, session: i64, what: &'static str) -> u64 {
|
||||
self.social.dm.next_request += 1;
|
||||
let request = self.social.dm.next_request;
|
||||
self.social.dm.requests.insert(request, (session, what));
|
||||
request
|
||||
}
|
||||
|
||||
/// Send an offline message through the open conversation's server.
|
||||
pub(crate) fn send_offline(&mut self, form: OfflineForm) {
|
||||
let session =
|
||||
self.social.dm.open.as_ref().and_then(|o| o.session).or(self.current).filter(|s| {
|
||||
self.sessions.get(s).is_some_and(|v| v.state.voice == VoiceState::Connected)
|
||||
});
|
||||
let Some(session) = session else {
|
||||
self.set_status("Connect with voice to send an offline message.");
|
||||
return;
|
||||
};
|
||||
let request = self.offline_request(session, "send");
|
||||
if !self.demo_ui {
|
||||
self.engine.send(Command::SendOfflineMessage {
|
||||
session: session as u64,
|
||||
request,
|
||||
to_uid: form.uid.to_string(),
|
||||
subject: if form.subject.is_empty() {
|
||||
"Message".into()
|
||||
} else {
|
||||
form.subject.to_string()
|
||||
},
|
||||
text: form.text.to_string(),
|
||||
});
|
||||
}
|
||||
self.set_status(format!("Sending an offline message to {}…", form.to));
|
||||
}
|
||||
|
||||
/// Show an offline message (and ask the server for its text).
|
||||
fn open_mail(&mut self, session: i64, m: &OfflineMessageInfo) {
|
||||
self.social.dm.open = Some(Open {
|
||||
session: Some(session),
|
||||
server_uid: None,
|
||||
uid: m.from_uid.clone(),
|
||||
mail: Some((session, m.id)),
|
||||
stored: false,
|
||||
});
|
||||
self.social.dm.mail = None;
|
||||
let request = self.offline_request(session, "get");
|
||||
if !self.demo_ui {
|
||||
self.engine.send(Command::GetOfflineMessage {
|
||||
session: session as u64,
|
||||
request,
|
||||
id: m.id,
|
||||
});
|
||||
}
|
||||
self.refresh_chats();
|
||||
}
|
||||
|
||||
pub(crate) fn mail_arrived(&mut self, session: i64, result: Result<OfflineMessage, String>) {
|
||||
match result {
|
||||
Ok(m) => {
|
||||
if let Some(view) = self.sessions.get_mut(&session)
|
||||
&& let Some(info) = view.extra.inbox.iter_mut().find(|i| i.id == m.id)
|
||||
{
|
||||
info.read = true;
|
||||
}
|
||||
self.social.dm.mail = Some(m);
|
||||
}
|
||||
Err(e) => self.set_status(format!("Could not read the offline message: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn request_done(&mut self, session: i64, request: u64, result: Result<(), String>) {
|
||||
let Some((_, what)) = self.social.dm.requests.remove(&request) else { return };
|
||||
match (what, result) {
|
||||
("send", Ok(())) => self.set_status("Offline message sent"),
|
||||
("send", Err(e)) => self.set_status(format!("Could not send the offline message: {e}")),
|
||||
(_, Err(e)) => self.set_status(format!("Offline messages: {e}")),
|
||||
(_, Ok(())) => {
|
||||
if let Some(view) = self.sessions.get_mut(&session) {
|
||||
view.extra.inbox_asked = false;
|
||||
}
|
||||
self.ask_inboxes();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// List the offline messages of voice sessions whose server keeps them.
|
||||
pub(crate) fn ask_inboxes(&mut self) {
|
||||
if self.demo_ui {
|
||||
return;
|
||||
}
|
||||
let ids: Vec<i64> = self
|
||||
.sessions
|
||||
.iter()
|
||||
.filter(|(_, v)| {
|
||||
v.state.voice == VoiceState::Connected
|
||||
&& v.capabilities.offline_messages
|
||||
&& !v.extra.inbox_asked
|
||||
})
|
||||
.map(|(id, _)| *id)
|
||||
.collect();
|
||||
for id in ids {
|
||||
let request = self.offline_request(id, "list");
|
||||
if let Some(view) = self.sessions.get_mut(&id) {
|
||||
view.extra.inbox_asked = true;
|
||||
}
|
||||
self.engine.send(Command::ListOfflineMessages { session: id as u64, request });
|
||||
}
|
||||
}
|
||||
|
||||
/// Pokes from `uid` as lines of their private chat, among its messages
|
||||
/// (`lines` and `times` in step, oldest first).
|
||||
pub(crate) fn poke_lines(&self, session: i64, uid: &str) -> Vec<(i64, crate::app::ChatLine)> {
|
||||
self.social
|
||||
.pokes
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, p)| p.session == session && p.uid.as_deref() == Some(uid))
|
||||
.map(|(i, p)| {
|
||||
let text = if p.message.is_empty() {
|
||||
"👋 poked you".to_owned()
|
||||
} else {
|
||||
format!("👋 poked you: {}", p.message)
|
||||
};
|
||||
let message = voelin_model::ChatMessage {
|
||||
target: ChatTarget::Private(uid.to_owned()),
|
||||
author_name: p.name.clone(),
|
||||
author_uid: p.uid.clone(),
|
||||
author_id: None,
|
||||
text,
|
||||
ts_ms: p.ts_ms,
|
||||
via_relay: false,
|
||||
blocked: false,
|
||||
};
|
||||
let mut line = vm::chat::line(&message, None);
|
||||
line.key = -1_000_000 - i as i32;
|
||||
line.avatar = self.avatar_of(uid);
|
||||
(p.ts_ms, line)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
//! Pictures linked in chat, shown inline: a link to a PNG, JPEG, GIF or
|
||||
//! WebP file (by name) up to `ui.image_preview_kb` is downloaded into
|
||||
//! 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.
|
||||
|
||||
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;
|
||||
|
||||
/// A linked picture.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) enum Preview {
|
||||
/// Downloading (transfer id).
|
||||
Loading(u64),
|
||||
Ready(Bytes),
|
||||
/// Too large, not a picture, or the download failed.
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// Whether a file name is a picture the chat shows inline.
|
||||
pub(crate) fn is_previewable(name: &str) -> bool {
|
||||
let lower = name.to_ascii_lowercase();
|
||||
[".png", ".jpg", ".jpeg", ".gif", ".webp"].iter().any(|e| lower.ends_with(e))
|
||||
}
|
||||
|
||||
/// The key of a link: where the file is.
|
||||
pub(crate) fn link_key(file: &FileRef) -> String {
|
||||
format!(
|
||||
"{}/{}{}{}",
|
||||
file.server_uid.as_deref().unwrap_or(""),
|
||||
file.channel,
|
||||
file.path,
|
||||
file.name
|
||||
)
|
||||
}
|
||||
|
||||
/// The decoded picture of a link, if it is there (decoded once, kept by
|
||||
/// the image cache).
|
||||
pub(crate) fn image_of(view: &SessionView, file: &FileRef) -> Option<slint::Image> {
|
||||
let key = link_key(file);
|
||||
match view.extra.previews.get(&key)? {
|
||||
Preview::Ready(bytes) => {
|
||||
let image = crate::images::picture(&key, &bytes.0);
|
||||
(image.size().width > 0).then_some(image)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
impl App {
|
||||
/// Download the pictures linked in the current chat of `session` that
|
||||
/// are not there yet.
|
||||
pub(crate) fn fetch_previews(&mut self, session: i64) {
|
||||
if self.demo_ui {
|
||||
return;
|
||||
}
|
||||
let limit = u64::from(self.prefs.get(&UI_IMAGE_PREVIEW_KB)) * 1024;
|
||||
let Some(view) = self.sessions.get_mut(&session) else { return };
|
||||
if limit == 0
|
||||
|| view.state.voice != VoiceState::Connected
|
||||
|| !view.capabilities.file_transfer
|
||||
{
|
||||
return;
|
||||
}
|
||||
let Some(tab) = view.tabs.get(view.current_tab) else { return };
|
||||
// Channel chats only: a link names its channel's file browser.
|
||||
if matches!(tab.target, ChatTarget::Private(_)) && tab.messages.is_empty() {
|
||||
return;
|
||||
}
|
||||
let wanted: Vec<FileRef> = tab
|
||||
.messages
|
||||
.iter()
|
||||
.rev()
|
||||
.take(200)
|
||||
.flat_map(|m| m.message.message.file_refs())
|
||||
.filter(|f| is_previewable(&f.name) && f.size.is_some_and(|s| s <= limit))
|
||||
.filter(|f| !view.extra.previews.contains_key(&link_key(f)))
|
||||
.collect();
|
||||
for file in wanted {
|
||||
let transfer = view.next_transfer;
|
||||
view.next_transfer += 1;
|
||||
view.extra.previews.insert(link_key(&file), Preview::Loading(transfer));
|
||||
self.engine.send(Command::DownloadChatFile {
|
||||
session: session as u64,
|
||||
transfer,
|
||||
file,
|
||||
password: None,
|
||||
to: DownloadTo::Memory,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// A transfer of a picture: `true` if it was one.
|
||||
pub(crate) fn preview_progress(
|
||||
&mut self,
|
||||
session: i64,
|
||||
transfer: u64,
|
||||
state: &TransferState,
|
||||
) -> bool {
|
||||
let limit = u64::from(self.prefs.get(&UI_IMAGE_PREVIEW_KB)) * 1024;
|
||||
let Some(view) = self.sessions.get_mut(&session) else { return false };
|
||||
let Some(key) = view
|
||||
.extra
|
||||
.previews
|
||||
.iter()
|
||||
.find(|(_, p)| matches!(p, Preview::Loading(t) if *t == transfer))
|
||||
.map(|(k, _)| k.clone())
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
match state {
|
||||
TransferState::Started { size, .. } if *size > limit => {
|
||||
view.extra.previews.insert(key, Preview::Failed);
|
||||
if !self.demo_ui {
|
||||
self.engine.send(Command::CancelTransfer { session: session as u64, transfer });
|
||||
}
|
||||
}
|
||||
TransferState::Done { data: Some(data), .. } => {
|
||||
view.extra.previews.insert(key, Preview::Ready(data.clone()));
|
||||
if self.current == Some(session) {
|
||||
self.refresh_chat();
|
||||
}
|
||||
}
|
||||
TransferState::Done { .. } | TransferState::Failed(_) | TransferState::Cancelled => {
|
||||
view.extra.previews.insert(key, Preview::Failed);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The picture of link `index` of a message of the current chat, 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()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn previewable_names() {
|
||||
assert!(is_previewable("Banner.PNG"));
|
||||
assert!(is_previewable("a.webp"));
|
||||
assert!(!is_previewable("notes.svg"));
|
||||
assert!(!is_previewable("route.pdf"));
|
||||
let file =
|
||||
FileRef { channel: 2, path: "/".into(), name: "a.png".into(), ..Default::default() };
|
||||
assert_eq!(link_key(&file), "/2/a.png");
|
||||
}
|
||||
}
|
||||
@@ -11,11 +11,22 @@ use crate::vm;
|
||||
|
||||
impl App {
|
||||
pub(crate) fn connect_voice(&mut self) {
|
||||
let channel =
|
||||
self.current.and_then(|id| self.bookmark(id)).and_then(|b| b.default_channel.clone());
|
||||
self.connect_voice_to(channel);
|
||||
}
|
||||
|
||||
/// Connect the current server with voice, into `channel` (a name or
|
||||
/// path) if given.
|
||||
pub(crate) fn connect_voice_to(&mut self, channel: Option<String>) {
|
||||
let Some(b) = self.current.and_then(|id| self.bookmark(id)).cloned() else { return };
|
||||
if self.demo_ui {
|
||||
return;
|
||||
}
|
||||
let mut options = VoiceOptions::new(&b.address, &b.nickname);
|
||||
options.identity = Some(self.identity.clone());
|
||||
options.identity = Some(self.identity_for(Some(b.id)));
|
||||
options.server_password = self.secrets.get(&b.server_password_key()).ok().flatten();
|
||||
options.channel = b.default_channel.clone();
|
||||
options.channel = channel;
|
||||
options.audio = true;
|
||||
options.stream_peer = self.video.peer_config(options.stream_peer);
|
||||
self.engine
|
||||
@@ -36,7 +47,7 @@ impl App {
|
||||
self.engine.send(Command::ObserveGateway {
|
||||
session,
|
||||
url: url.clone(),
|
||||
identity: Box::new(self.identity.clone()),
|
||||
identity: Box::new(self.identity_for(Some(b.id))),
|
||||
});
|
||||
} else if let Some(q) = &b.query {
|
||||
let secret = self.secrets.get(&b.query_password_key()).ok().flatten();
|
||||
@@ -141,7 +152,7 @@ impl App {
|
||||
},
|
||||
address: form.address.to_string(),
|
||||
nickname: form.nickname.to_string(),
|
||||
identity: None,
|
||||
identity: self.bookmark(form.id as i64).and_then(|b| b.identity),
|
||||
default_channel: None,
|
||||
gateway_url: Some(form.gateway_url.to_string()).filter(|u| !u.is_empty()),
|
||||
query,
|
||||
@@ -199,7 +210,12 @@ impl App {
|
||||
let state = view.map(|v| v.state.clone()).unwrap_or_default();
|
||||
let unread = view.map_or(0, |v| v.unread());
|
||||
let live = view.is_some_and(|v| v.streams_available() && !v.streams.is_empty());
|
||||
vm::servers::item(b, &state, unread, live)
|
||||
let detail = view
|
||||
.filter(|v| !v.presence.channels.is_empty())
|
||||
.map(|v| vm::tree::stats(&v.presence))
|
||||
.unwrap_or_default();
|
||||
let flavor = view.map(|v| v.extra.flavor.clone()).unwrap_or_default();
|
||||
vm::servers::item(b, &state, unread, live, detail, flavor)
|
||||
})
|
||||
.collect();
|
||||
vm::list::sync(&self.models.servers, &items);
|
||||
@@ -275,7 +291,7 @@ impl App {
|
||||
playback: &self.playback,
|
||||
own_channel: view.state.own_channel,
|
||||
own_client: view.state.own_client,
|
||||
filter: &self.tree_filter,
|
||||
filter: "",
|
||||
avatars: &view.avatars,
|
||||
icons: &view.icons,
|
||||
groups: &view.server_groups,
|
||||
@@ -324,12 +340,4 @@ impl App {
|
||||
}
|
||||
self.refresh_tree();
|
||||
}
|
||||
|
||||
/// The top bar's search.
|
||||
pub(crate) fn search(&mut self, text: String) {
|
||||
if self.tree_filter != text {
|
||||
self.tree_filter = text;
|
||||
self.refresh_tree();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -105,6 +105,144 @@ pub fn appearance_keys() -> [&'static dyn voelin_core::settings::Setting; 5] {
|
||||
[&UI_THEME, &UI_FONT_SCALE, &UI_NARROW_BREAKPOINT, &UI_IMAGE_CACHE_MB, &UI_MEMBERS_WIDTH]
|
||||
}
|
||||
|
||||
/// What a kind of notification does: nothing, the bell, or the bell and a
|
||||
/// desktop notification.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum NotifyLevel {
|
||||
Off,
|
||||
App,
|
||||
#[default]
|
||||
Desktop,
|
||||
}
|
||||
|
||||
impl NotifyLevel {
|
||||
pub fn index(self) -> i32 {
|
||||
self as i32
|
||||
}
|
||||
|
||||
pub fn from_index(index: i32) -> Self {
|
||||
match index {
|
||||
0 => Self::Off,
|
||||
1 => Self::App,
|
||||
_ => Self::Desktop,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const NOTIFY_LEVELS: Kind = Kind::Choice(&["off", "app", "desktop"]);
|
||||
|
||||
/// `notify.*`: what the bell and the desktop say about each kind.
|
||||
pub static NOTIFY_MENTIONS: Key<NotifyLevel> = Key::new(
|
||||
"notify.mentions",
|
||||
NOTIFY_LEVELS,
|
||||
"Our name in a channel or server chat: off, app (the bell) or desktop.",
|
||||
NotifyLevel::default,
|
||||
);
|
||||
pub static NOTIFY_MESSAGES: Key<NotifyLevel> = Key::new(
|
||||
"notify.private_messages",
|
||||
NOTIFY_LEVELS,
|
||||
"Private messages: off, app (the bell) or desktop.",
|
||||
NotifyLevel::default,
|
||||
);
|
||||
pub static NOTIFY_POKES: Key<NotifyLevel> =
|
||||
Key::new("notify.pokes", NOTIFY_LEVELS, "Pokes: off, app (the bell) or desktop.", || {
|
||||
NotifyLevel::Desktop
|
||||
});
|
||||
pub static NOTIFY_EVENTS: Key<NotifyLevel> = Key::new(
|
||||
"notify.event_reminders",
|
||||
NOTIFY_LEVELS,
|
||||
"Reminders of scheduled events: off, app (the bell) or desktop.",
|
||||
NotifyLevel::default,
|
||||
);
|
||||
pub static NOTIFY_FRIENDS: Key<NotifyLevel> = Key::new(
|
||||
"notify.friends_online",
|
||||
NOTIFY_LEVELS,
|
||||
"Friends coming online: off, app (the bell) or desktop.",
|
||||
|| NotifyLevel::App,
|
||||
);
|
||||
|
||||
/// `video.camera`: the camera of the preview and the default of camera
|
||||
/// sources (a device id; empty: the first camera).
|
||||
pub static VIDEO_CAMERA: Key<String> = Key::new(
|
||||
"video.camera",
|
||||
Kind::Text { suggestions: &[] },
|
||||
"Camera device (empty: the first one).",
|
||||
String::new,
|
||||
);
|
||||
|
||||
/// `video.background`: the camera's background effect.
|
||||
pub static VIDEO_BACKGROUND: Key<String> = Key::new(
|
||||
"video.background",
|
||||
Kind::Choice(&["none", "blur"]),
|
||||
"Background effect of the camera: none or blur.",
|
||||
|| "none".into(),
|
||||
);
|
||||
|
||||
/// `video.resolution`: the camera's capture size, `auto` or `WIDTHxHEIGHT`.
|
||||
pub static VIDEO_RESOLUTION: Key<String> = Key::new(
|
||||
"video.resolution",
|
||||
Kind::Text { suggestions: &["auto", "1280x720", "1920x1080", "2560x1440"] },
|
||||
"Camera resolution: auto or WIDTHxHEIGHT.",
|
||||
|| "auto".into(),
|
||||
)
|
||||
.validated(valid_resolution);
|
||||
|
||||
/// `video.mirror`: show our camera mirrored, as in a mirror.
|
||||
pub static VIDEO_MIRROR: Key<bool> =
|
||||
Key::new("video.mirror", Kind::Bool, "Show our camera mirrored.", || true);
|
||||
|
||||
/// `ui.image_preview_kb`: linked pictures up to this size are downloaded
|
||||
/// and shown in the chat (0: never). No maximum.
|
||||
pub static UI_IMAGE_PREVIEW_KB: Key<u32> = Key::new(
|
||||
"ui.image_preview_kb",
|
||||
Kind::UInt { min: 0 },
|
||||
"Show pictures linked in chat up to this size in KB (0: never).",
|
||||
|| 8192,
|
||||
);
|
||||
|
||||
/// `identity.default`: the identity used where a server names none (its
|
||||
/// id in the identities; 0: the first one).
|
||||
pub static IDENTITY_DEFAULT: Key<u64> = Key::new(
|
||||
"identity.default",
|
||||
Kind::UInt { min: 0 },
|
||||
"The identity servers see unless their bookmark names another (0: the first).",
|
||||
|| 0,
|
||||
);
|
||||
|
||||
#[allow(clippy::ptr_arg)] // a validation of `Key<String>` is `fn(&String)`
|
||||
fn valid_resolution(text: &String) -> Result<(), String> {
|
||||
if text == "auto" || parse_size(text).is_some() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err("auto or WIDTHxHEIGHT, e.g. 1280x720".into())
|
||||
}
|
||||
}
|
||||
|
||||
/// `1280x720` → (1280, 720), both above 0.
|
||||
pub fn parse_size(text: &str) -> Option<(u32, u32)> {
|
||||
let (w, h) = text.trim().split_once(['x', 'X', '×'])?;
|
||||
let (w, h) = (w.trim().parse().ok()?, h.trim().parse().ok()?);
|
||||
(w > 0 && h > 0).then_some((w, h))
|
||||
}
|
||||
|
||||
/// The keys of the home, messages and settings pages, for registering.
|
||||
pub fn page_keys() -> [&'static dyn voelin_core::settings::Setting; 11] {
|
||||
[
|
||||
&NOTIFY_MENTIONS,
|
||||
&NOTIFY_MESSAGES,
|
||||
&NOTIFY_POKES,
|
||||
&NOTIFY_EVENTS,
|
||||
&NOTIFY_FRIENDS,
|
||||
&VIDEO_CAMERA,
|
||||
&VIDEO_BACKGROUND,
|
||||
&VIDEO_RESOLUTION,
|
||||
&VIDEO_MIRROR,
|
||||
&UI_IMAGE_PREVIEW_KB,
|
||||
&IDENTITY_DEFAULT,
|
||||
]
|
||||
}
|
||||
|
||||
/// Frame rates and bitrates (kbit/s) the share dialog offers; any other
|
||||
/// value can be typed in.
|
||||
pub const FPS_CHOICES: [u32; 3] = [15, 30, 60];
|
||||
@@ -364,6 +502,19 @@ mod tests {
|
||||
assert_eq!(parse_positive("fast"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_keys() {
|
||||
assert_eq!(parse_size("1280x720"), Some((1280, 720)));
|
||||
assert_eq!(parse_size(" 1920 × 1080 "), Some((1920, 1080)));
|
||||
assert_eq!(parse_size("0x720"), None);
|
||||
assert_eq!(parse_size("big"), None);
|
||||
assert!(VIDEO_RESOLUTION.validate(&"auto".into()).is_ok());
|
||||
assert!(VIDEO_RESOLUTION.validate(&"wide".into()).is_err());
|
||||
assert_eq!(serde_json::to_value(NotifyLevel::App).unwrap(), "app");
|
||||
assert_eq!(NotifyLevel::from_index(NotifyLevel::Off.index()), NotifyLevel::Off);
|
||||
assert_eq!(NotifyLevel::from_index(7), NotifyLevel::Desktop);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ui_settings_defaults() {
|
||||
let parsed: UiSettings = serde_json::from_str(r#"{"openh264":true}"#).unwrap();
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -11,7 +11,7 @@ use slint::{Image, Rgba8Pixel, SharedPixelBuffer};
|
||||
use tokio::runtime::Handle;
|
||||
use tracing::warn;
|
||||
use voelin_core::media::voelin_media::capture::SourceId;
|
||||
use voelin_core::media::voelin_media::{Codec, Codecs, EncoderReport, VideoFrame, convert};
|
||||
use voelin_core::media::voelin_media::{Codec, Codecs, VideoFrame, convert};
|
||||
use voelin_core::media::{
|
||||
self, AudioSourceSpec, EncoderPreference, Latest, LocalPreview, Streamer, StreamerConfig,
|
||||
Viewer, peer_config, preferred_codec, stream_codec,
|
||||
@@ -98,7 +98,6 @@ impl Video {
|
||||
/// `stream.encoder_backend`) and stream codec (`stream.codec`, `None`:
|
||||
/// automatic). A running share follows through
|
||||
/// `Streamer::reconfigure` with `StreamerConfigUpdate::encoder`.
|
||||
#[allow(dead_code, reason = "for the settings page")]
|
||||
pub fn set_encoder_preference(&mut self, encoder: EncoderPreference, codec: Option<Codec>) {
|
||||
let mut codecs = (*self.codecs).clone();
|
||||
codecs.set_preference(encoder.clone());
|
||||
@@ -107,10 +106,10 @@ impl Video {
|
||||
self.codec = codec;
|
||||
}
|
||||
|
||||
/// Every encoder backend, what works and why the rest does not.
|
||||
#[allow(dead_code, reason = "for the integrations page")]
|
||||
pub fn encoder_report(&self) -> EncoderReport {
|
||||
self.codecs.report()
|
||||
/// The codecs in use, e.g. for `Codecs::report` (every encoder backend,
|
||||
/// what works and why the rest does not) off the UI thread.
|
||||
pub fn codecs(&self) -> Arc<Codecs> {
|
||||
self.codecs.clone()
|
||||
}
|
||||
|
||||
/// Whether H.264 works, and a line for the settings page.
|
||||
|
||||
@@ -47,6 +47,8 @@ pub struct LineCtx {
|
||||
pub topic: String,
|
||||
/// The state of the downloads started from this message, by link index.
|
||||
pub downloads: Vec<(usize, FileItem)>,
|
||||
/// Pictures of the links shown inline, by link index.
|
||||
pub previews: Vec<(usize, Image)>,
|
||||
}
|
||||
|
||||
/// When a message was sent, for its header (see [`stamp`]).
|
||||
@@ -174,6 +176,9 @@ fn line_of(
|
||||
item.state = running.state.clone();
|
||||
item.progress = running.progress;
|
||||
}
|
||||
if let Some((_, picture)) = ctx.previews.iter().find(|(index, _)| *index == i) {
|
||||
item.preview = picture.clone();
|
||||
}
|
||||
item
|
||||
})
|
||||
.collect();
|
||||
@@ -200,7 +205,7 @@ fn line_of(
|
||||
}
|
||||
}
|
||||
|
||||
fn is_picture(name: &str) -> bool {
|
||||
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))
|
||||
}
|
||||
|
||||
@@ -7,4 +7,5 @@ pub mod avatar;
|
||||
pub mod chat;
|
||||
pub mod list;
|
||||
pub mod servers;
|
||||
pub mod social;
|
||||
pub mod tree;
|
||||
@@ -16,9 +16,18 @@ pub fn status(state: &SessionState) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
/// A server of the rail. `unread`: messages in its chats; `live`:
|
||||
/// streams in our channel there.
|
||||
pub fn item(bookmark: &Bookmark, state: &SessionState, unread: i32, live: bool) -> ServerItem {
|
||||
/// A server of the rail and the home page. `unread`: messages in its
|
||||
/// chats; `live`: streams in our channel there; `detail`: who is there
|
||||
/// ("9 online · 7 channels"), empty for its address; `flavor`:
|
||||
/// "TeamSpeak 6" once reached.
|
||||
pub fn item(
|
||||
bookmark: &Bookmark,
|
||||
state: &SessionState,
|
||||
unread: i32,
|
||||
live: bool,
|
||||
detail: String,
|
||||
flavor: String,
|
||||
) -> ServerItem {
|
||||
ServerItem {
|
||||
id: bookmark.id as i32,
|
||||
name: bookmark.name.clone().into(),
|
||||
@@ -28,6 +37,9 @@ pub fn item(bookmark: &Bookmark, state: &SessionState, unread: i32, live: bool)
|
||||
tint: avatar::tint(&bookmark.name),
|
||||
unread,
|
||||
live,
|
||||
detail: if detail.is_empty() { bookmark.address.clone() } else { detail }.into(),
|
||||
flavor: flavor.into(),
|
||||
gateway: bookmark.gateway_url.is_some() || bookmark.query.is_some(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
//! Texts of the home, friends, messages, bell and events screens: times
|
||||
//! ("12m ago", "Yesterday"), message previews without BBCode, mentions,
|
||||
//! event dates; pure, so they are tested here.
|
||||
|
||||
use chrono::{DateTime, Local, NaiveDateTime, TimeZone};
|
||||
|
||||
fn local(ts_ms: i64) -> Option<NaiveDateTime> {
|
||||
DateTime::from_timestamp_millis(ts_ms).map(|t| t.with_timezone(&Local).naive_local())
|
||||
}
|
||||
|
||||
fn now_local() -> NaiveDateTime {
|
||||
Local::now().naive_local()
|
||||
}
|
||||
|
||||
/// "now", "5m ago", "2h ago", "3d ago", else the date ("12 Mar").
|
||||
pub fn ago(ts_ms: i64) -> String {
|
||||
ago_at(ts_ms, chrono::Utc::now().timestamp_millis())
|
||||
}
|
||||
|
||||
pub fn ago_at(ts_ms: i64, now_ms: i64) -> String {
|
||||
if ts_ms <= 0 {
|
||||
return String::new();
|
||||
}
|
||||
let minutes = (now_ms - ts_ms) / 60_000;
|
||||
match minutes {
|
||||
i64::MIN..=0 => "now".into(),
|
||||
1..=59 => format!("{minutes}m ago"),
|
||||
60..=1439 => format!("{}h ago", minutes / 60),
|
||||
1440..=10079 => format!("{}d ago", minutes / 1440),
|
||||
_ => local(ts_ms).map(|t| t.format("%-d %b").to_string()).unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The time of a conversation in a list: "11:42" today, "Yesterday", the
|
||||
/// weekday within a week ("Mon"), else the date ("12 Mar", with the year
|
||||
/// when it is another).
|
||||
pub fn list_time(ts_ms: i64) -> String {
|
||||
local(ts_ms).map(|t| list_time_at(t, now_local())).unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn list_time_at(then: NaiveDateTime, now: NaiveDateTime) -> String {
|
||||
use chrono::Datelike;
|
||||
let days = (now.date() - then.date()).num_days();
|
||||
match days {
|
||||
i64::MIN..=0 => then.format("%H:%M").to_string(),
|
||||
1 => "Yesterday".into(),
|
||||
2..=6 => then.format("%a").to_string(),
|
||||
_ if then.year() == now.year() => then.format("%-d %b").to_string(),
|
||||
_ => then.format("%-d %b %Y").to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Chat text without BBCode tags (`[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;
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push_str(rest);
|
||||
out.split_whitespace().collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
/// `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 {
|
||||
let body = if files.is_empty() { plain(text) } else { String::new() };
|
||||
let body = if body.is_empty() && !files.is_empty() {
|
||||
if files.iter().any(|f| crate::vm::chat::is_picture(&f.name)) {
|
||||
"Sent a picture".to_owned()
|
||||
} else {
|
||||
"Sent a file".to_owned()
|
||||
}
|
||||
} else {
|
||||
body
|
||||
};
|
||||
if mine { format!("You: {body}") } else { body }
|
||||
}
|
||||
|
||||
/// Whether `text` names `nick` as a word (case does not matter): a mention.
|
||||
pub fn mentions(text: &str, nick: &str) -> bool {
|
||||
let nick = nick.trim().to_lowercase();
|
||||
if nick.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let text = text.to_lowercase();
|
||||
text.match_indices(&nick).any(|(at, _)| {
|
||||
let before = text[..at].chars().next_back();
|
||||
let after = text[at + nick.len()..].chars().next();
|
||||
!before.is_some_and(char::is_alphanumeric) && !after.is_some_and(char::is_alphanumeric)
|
||||
})
|
||||
}
|
||||
|
||||
/// Case-insensitive search in any of `fields`.
|
||||
pub fn matches(query: &str, fields: &[&str]) -> bool {
|
||||
let q = query.trim().to_lowercase();
|
||||
q.is_empty() || fields.iter().any(|f| f.to_lowercase().contains(&q))
|
||||
}
|
||||
|
||||
/// The date block of an event: "SAT", "26", "APR".
|
||||
pub fn date_block(ts_ms: i64) -> (String, String, String) {
|
||||
local(ts_ms)
|
||||
.map(|t| {
|
||||
(
|
||||
t.format("%a").to_string().to_uppercase(),
|
||||
t.format("%-d").to_string(),
|
||||
t.format("%b").to_string().to_uppercase(),
|
||||
)
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// "Sat 26 Apr, 19:00 – 21:00" (the end's date too when it is another day).
|
||||
pub fn event_when(start_ms: i64, end_ms: Option<i64>) -> String {
|
||||
let Some(start) = local(start_ms) else { return String::new() };
|
||||
let mut out = start.format("%a %-d %b, %H:%M").to_string();
|
||||
if let Some(end) = end_ms.and_then(local) {
|
||||
let end = if end.date() == start.date() {
|
||||
end.format("%H:%M")
|
||||
} else {
|
||||
end.format("%a %-d %b, %H:%M")
|
||||
};
|
||||
out.push_str(&format!(" – {end}"));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// "Starts in 15 min", "Starts in 3 h", "Happening now", or nothing (more
|
||||
/// than a day away, or over).
|
||||
pub fn soon(start_ms: i64, end_ms: Option<i64>, now_ms: i64) -> String {
|
||||
let minutes = (start_ms - now_ms) / 60_000;
|
||||
let over = end_ms.map_or(now_ms - start_ms > 3 * 3_600_000, |end| now_ms > end);
|
||||
match minutes {
|
||||
_ if over => String::new(),
|
||||
i64::MIN..=0 => "Happening now".into(),
|
||||
1..=59 => format!("Starts in {minutes} min"),
|
||||
60..=1439 => format!("Starts in {} h", minutes / 60),
|
||||
_ => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `2026-10-04 19:00` in local time → Unix milliseconds.
|
||||
pub fn parse_local(text: &str) -> Option<i64> {
|
||||
let t = NaiveDateTime::parse_from_str(text.trim(), "%Y-%m-%d %H:%M").ok()?;
|
||||
Local.from_local_datetime(&t).earliest().map(|t| t.timestamp_millis())
|
||||
}
|
||||
|
||||
/// Unix milliseconds → `2026-10-04 19:00` in local time.
|
||||
pub fn format_local(ts_ms: i64) -> String {
|
||||
local(ts_ms).map(|t| t.format("%Y-%m-%d %H:%M").to_string()).unwrap_or_default()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn at(text: &str) -> NaiveDateTime {
|
||||
NaiveDateTime::parse_from_str(text, "%Y-%m-%d %H:%M").unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn times() {
|
||||
let now = 1_800_000_000_000;
|
||||
assert_eq!(ago_at(now - 30_000, now), "now");
|
||||
assert_eq!(ago_at(now - 12 * 60_000, now), "12m ago");
|
||||
assert_eq!(ago_at(now - 2 * 3_600_000, now), "2h ago");
|
||||
assert_eq!(ago_at(now - 3 * 86_400_000, now), "3d ago");
|
||||
assert_eq!(ago_at(0, now), "");
|
||||
let now = at("2026-10-03 14:00");
|
||||
assert_eq!(list_time_at(at("2026-10-03 11:42"), now), "11:42");
|
||||
assert_eq!(list_time_at(at("2026-10-02 23:00"), now), "Yesterday");
|
||||
assert_eq!(list_time_at(at("2026-09-28 10:00"), now), "Mon");
|
||||
assert_eq!(list_time_at(at("2026-03-12 10:00"), now), "12 Mar");
|
||||
assert_eq!(list_time_at(at("2025-03-12 10:00"), now), "12 Mar 2025");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn previews() {
|
||||
assert_eq!(plain("[b]Hi[/b] there"), "Hi there");
|
||||
assert_eq!(plain("see [URL=https://x.org]this[/URL]"), "see this");
|
||||
assert_eq!(plain("a [not a tag here] b"), "a [not a tag here] b");
|
||||
assert_eq!(plain("[1] item"), "[1] item");
|
||||
assert_eq!(preview("Hello", true, &[]), "You: Hello");
|
||||
let file = |name: &str| voelin_model::FileRef { name: name.into(), ..Default::default() };
|
||||
assert_eq!(
|
||||
preview("[URL=ts3file://x]a.png[/URL]", false, &[file("a.png")]),
|
||||
"Sent a picture"
|
||||
);
|
||||
assert_eq!(preview("x", true, &[file("notes.txt")]), "You: Sent a file");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mention_words() {
|
||||
assert!(mentions("hey Nova, raid?", "nova"));
|
||||
assert!(mentions("@Nova", "Nova"));
|
||||
assert!(!mentions("supernova", "Nova"));
|
||||
assert!(!mentions("anything", ""));
|
||||
assert!(matches("kai", &["Kairo", "x"]));
|
||||
assert!(matches("", &[]));
|
||||
assert!(!matches("zz", &["Kairo"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn event_dates() {
|
||||
let start = parse_local("2026-04-25 19:00").unwrap();
|
||||
assert_eq!(format_local(start), "2026-04-25 19:00");
|
||||
assert_eq!(date_block(start), ("SAT".into(), "25".into(), "APR".into()));
|
||||
let end = parse_local("2026-04-25 21:30").unwrap();
|
||||
assert_eq!(event_when(start, Some(end)), "Sat 25 Apr, 19:00 – 21:30");
|
||||
assert_eq!(event_when(start, None), "Sat 25 Apr, 19:00");
|
||||
assert!(parse_local("tomorrow").is_none());
|
||||
assert_eq!(soon(start, Some(end), start - 15 * 60_000), "Starts in 15 min");
|
||||
assert_eq!(soon(start, Some(end), start - 3 * 3_600_000), "Starts in 3 h");
|
||||
assert_eq!(soon(start, Some(end), start + 60_000), "Happening now");
|
||||
assert_eq!(soon(start, Some(end), end + 60_000), "");
|
||||
assert_eq!(soon(start, None, start - 2 * 86_400_000), "");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user