Merge branch 'worktree-agent-a5c4db1cfdf260dca' into worktree-agent-a16cf8e8a11a0c01d

This commit is contained in:
selikhov committed 2026-10-03 01:43:33 +03:00
commit a0ae5499ec
31 files changed
+3807 -358

No files matched your search

Generated
+1
View File
@@ -9299,6 +9299,7 @@ dependencies = [
"unicode-segmentation",
"voelin-audio",
"voelin-core",
"voelin-gateway-proto",
"voelin-model",
"voelin-platform",
"voelin-query",
+3 -2
View File
@@ -10,7 +10,8 @@ publish.workspace = true
[features]
default = ["portal", "x11"]
# Wayland global shortcuts through xdg-desktop-portal (Linux).
# Wayland global shortcuts and the file chooser through xdg-desktop-portal
# (Linux).
portal = ["dep:ashpd", "dep:futures-util"]
# X11 global hotkeys through XInput2 raw events (Linux).
x11 = ["dep:x11rb"]
@@ -23,7 +24,7 @@ tokio = { version = "1", features = ["rt", "sync"] }
tracing = "0.1"
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
ashpd = { version = "0.13", default-features = false, features = ["tokio", "global_shortcuts"], optional = true }
ashpd = { version = "0.13", default-features = false, features = ["tokio", "global_shortcuts", "file_chooser"], optional = true }
futures-util = { version = "0.3", optional = true }
notify-rust = { version = "4.18", default-features = false, features = ["z-with-tokio"] }
x11rb = { version = "0.13", features = ["xinput"], optional = true }
+84
View File
@@ -0,0 +1,84 @@
//! Asking the user for a file.
//!
//! Linux uses xdg-desktop-portal's file chooser (feature `portal`), which
//! works on Wayland and X11 and inside a Flatpak. Other platforms have no
//! backend yet; [`available`] says so, so a window can hide what it cannot
//! offer.
use std::path::PathBuf;
use crate::{Error, Result};
/// Whether [`pick_file`] can ask the user.
pub const fn available() -> bool {
cfg!(all(unix, not(target_os = "macos"), feature = "portal"))
}
/// Ask the user for one existing file; `None` when they cancelled.
pub async fn pick_file(title: &str) -> Result<Option<PathBuf>> {
#[cfg(all(unix, not(target_os = "macos"), feature = "portal"))]
return portal_pick(title).await;
#[cfg(not(all(unix, not(target_os = "macos"), feature = "portal")))]
{
let _ = title;
Err(Error::Unsupported("no file chooser on this platform".into()))
}
}
#[cfg(all(unix, not(target_os = "macos"), feature = "portal"))]
async fn portal_pick(title: &str) -> Result<Option<PathBuf>> {
use ashpd::desktop::file_chooser::SelectedFiles;
let request = SelectedFiles::open_file()
.title(title)
.multiple(false)
.modal(true)
.send()
.await
.map_err(|e| Error::Backend(e.to_string()))?;
let files = match request.response() {
Ok(files) => files,
// Cancelling is not a failure.
Err(ashpd::Error::Response(_)) => return Ok(None),
Err(e) => return Err(Error::Backend(e.to_string())),
};
Ok(files.uris().first().and_then(|uri| file_uri_path(uri.as_str())))
}
/// The path of a `file://` URI, with percent escapes resolved.
#[cfg(all(unix, not(target_os = "macos"), feature = "portal"))]
fn file_uri_path(uri: &str) -> Option<PathBuf> {
let rest = uri.strip_prefix("file://")?;
// file:///path and file://localhost/path both mean a local file.
let path = rest.strip_prefix("localhost").unwrap_or(rest);
let bytes = path.as_bytes();
let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%' && i + 2 < bytes.len() {
let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).ok()?;
if let Ok(byte) = u8::from_str_radix(hex, 16) {
out.push(byte);
i += 3;
continue;
}
}
out.push(bytes[i]);
i += 1;
}
let path = PathBuf::from(String::from_utf8(out).ok()?);
path.is_absolute().then_some(path)
}
#[cfg(all(test, unix, not(target_os = "macos"), feature = "portal"))]
mod tests {
use super::*;
#[test]
fn paths_of_file_uris() {
assert_eq!(file_uri_path("file:///tmp/a%20b.png"), Some("/tmp/a b.png".into()));
assert_eq!(file_uri_path("file://localhost/tmp/x"), Some("/tmp/x".into()));
assert_eq!(file_uri_path("https://example.com/x"), None);
assert_eq!(file_uri_path("file://relative"), None);
}
}
+2
View File
@@ -3,12 +3,14 @@
//! - [`hotkey`]: global push-to-talk hotkeys with press and release events
//! (xdg-desktop-portal on Wayland, XInput2 on X11, a keyboard hook on
//! Windows)
//! - [`files`]: asking the user for a file (xdg-desktop-portal)
//! - [`notify`]: desktop notifications
//! - [`paths`]: data, config, cache and state directories
//! - [`crash`]: opt-in local crash reports (panic hook)
//! - [`notices`]: third-party notices for the About page
pub mod crash;
pub mod files;
pub mod hotkey;
pub mod notices;
pub mod notify;
+2
View File
@@ -31,6 +31,8 @@ tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
unicode-segmentation = "1.13"
voelin-audio = { path = "../voelin-audio" }
voelin-core = { path = "../voelin-core", default-features = false, features = ["audio-device"] }
# Gateway data types (topics, pins, reactions, capability names).
voelin-gateway-proto = { path = "../voelin-gateway-proto" }
voelin-model = { path = "../voelin-model" }
# Crash reports and notices everywhere; hotkey backends on desktop (below).
voelin-platform = { path = "../voelin-platform", default-features = false }
+169 -5
View File
@@ -19,8 +19,10 @@ use tokio::runtime::Runtime;
use tracing::warn;
use voelin_core::settings::{AUDIO, CRASH_REPORTS, Settings};
use voelin_core::stream::StreamInfo;
use voelin_core::{AudioSettings, Command, Engine, Event, SessionState, VoiceState};
use voelin_model::{Capabilities, ChannelId, ChatTarget, Presence};
use voelin_core::{
AudioSettings, Command, Engine, Event, History, HistoryMessage, SessionState, VoiceState,
};
use voelin_model::{Capabilities, ChannelId, ChatTarget, GroupInfo, Presence};
use voelin_platform::crash;
use voelin_store::{Bookmark, MemorySecrets, Secrets, Store};
@@ -107,20 +109,76 @@ impl Secrets for FallbackSecrets {
}
}
/// A message of a chat with the handle the UI knows it by: the engine's
/// local ids are 64 bit, a Slint `int` is not.
pub(crate) struct Msg {
pub key: i32,
pub message: HistoryMessage,
}
/// A chat of a session: its lines are the model the chat view shows while
/// the tab is selected, so a new message is one row appended.
pub(crate) struct Tab {
pub target: ChatTarget,
pub title: String,
pub lines: Rc<VecModel<ChatLine>>,
/// The last message, for grouping the next one.
/// The messages, oldest first, by `(ts_ms, id)`.
pub messages: Vec<Msg>,
/// Live messages of a session that keeps no history (no server unique
/// id yet): grouped from the message before, without ids.
pub last: Option<Previous>,
pub unread: i32,
/// Nothing older exists as far as the engine can tell.
pub complete: bool,
/// A gateway page arrived: the chat is not only what we saw.
pub synced: bool,
/// An older page was asked for.
pub loading: bool,
/// The next message handle.
next_key: i32,
/// The pins of this chat, once asked for.
pub pins: Vec<crate::chat::PinRow>,
pub pins_loaded: bool,
/// The gateway topics of this chat, and the open one with its messages.
pub topics: Vec<voelin_gateway_proto::TopicInfo>,
pub topics_loaded: bool,
pub topic: Option<i64>,
pub topic_messages: Vec<Msg>,
/// The message jumped to from the pins.
pub marked: Option<i64>,
}
impl Tab {
pub fn new(target: ChatTarget, title: String) -> Self {
Self { target, title, lines: Rc::new(VecModel::default()), last: None, unread: 0 }
Self {
target,
title,
lines: Rc::new(VecModel::default()),
messages: Vec::new(),
last: None,
unread: 0,
complete: false,
synced: false,
loading: false,
next_key: 1,
pins: Vec::new(),
pins_loaded: false,
topics: Vec::new(),
topics_loaded: false,
topic: None,
topic_messages: Vec::new(),
marked: None,
}
}
/// A handle for a message that has none yet.
pub fn take_key(&mut self) -> i32 {
self.next_key += 1;
self.next_key
}
pub fn message(&self, key: i32) -> Option<&HistoryMessage> {
self.messages.iter().chain(&self.topic_messages).find(|m| m.key == key).map(|m| &m.message)
}
}
@@ -139,6 +197,21 @@ pub(crate) struct SessionView {
pub streams: Vec<StreamInfo>,
/// Clients whose stored volume was sent for this voice connection.
pub applied_playback: HashSet<u16>,
/// Avatar pictures in the engine's cache, by unique id
/// ([`Event::AvatarReady`]).
pub avatars: HashMap<String, PathBuf>,
/// Icons in the engine's cache, by icon id ([`Event::IconReady`]).
pub icons: HashMap<u32, PathBuf>,
/// The server groups in display order ([`Event::Groups`]).
pub server_groups: Vec<GroupInfo>,
/// What the session's gateway offers (`voelin_gateway_proto::feature`).
pub gateway_caps: Vec<String>,
/// The client whose member card is open.
pub member_card: Option<u16>,
/// Downloads started from chat, by transfer id.
pub downloads: HashMap<u64, crate::chat::Download>,
/// The next transfer id.
pub next_transfer: u64,
}
impl Default for SessionView {
@@ -154,6 +227,13 @@ impl Default for SessionView {
focused_own_channel: false,
streams: Vec::new(),
applied_playback: HashSet::new(),
avatars: HashMap::new(),
icons: HashMap::new(),
server_groups: Vec::new(),
gateway_caps: Vec::new(),
member_card: None,
downloads: HashMap::new(),
next_transfer: 1,
}
}
}
@@ -176,6 +256,24 @@ impl SessionView {
pub fn unread(&self) -> i32 {
self.tabs.iter().map(|t| t.unread).sum()
}
/// The session's gateway offers this feature
/// (`voelin_gateway_proto::feature`).
pub fn gateway_has(&self, feature: &str) -> bool {
self.gateway_caps.iter().any(|c| c == feature)
}
/// The chat history is kept by the engine (it knows the server): its
/// messages come with ids, reactions and pins.
pub fn has_history(&self) -> bool {
self.state.server_uid.is_some()
}
/// The avatar picture of a client, if the engine fetched one.
pub fn avatar(&self, client: u16) -> Option<&PathBuf> {
let uid = self.presence.clients.get(&client)?.uid.as_deref()?;
self.avatars.get(uid)
}
}
/// The models the Bridge shows, created once and updated row by row
@@ -187,6 +285,11 @@ pub(crate) struct Models {
pub tabs: Rc<VecModel<ChatTab>>,
pub streams: Rc<VecModel<StreamItem>>,
pub viewers: Rc<VecModel<ViewerItem>>,
pub pins: Rc<VecModel<PinItem>>,
pub topics: Rc<VecModel<TopicItem>>,
pub topic_messages: Rc<VecModel<ChatLine>>,
/// The quality choices of the watched stream.
pub qualities: Rc<VecModel<slint::SharedString>>,
/// Shown when there is no chat.
pub no_chat: Rc<VecModel<ChatLine>>,
}
@@ -200,6 +303,10 @@ impl Models {
tabs: Rc::default(),
streams: Rc::default(),
viewers: Rc::default(),
pins: Rc::default(),
topics: Rc::default(),
topic_messages: Rc::default(),
qualities: Rc::default(),
no_chat: Rc::default(),
};
bridge.set_servers(ModelRc::from(models.servers.clone()));
@@ -208,6 +315,10 @@ impl Models {
bridge.set_tabs(ModelRc::from(models.tabs.clone()));
bridge.set_streams(ModelRc::from(models.streams.clone()));
bridge.set_share_viewers(ModelRc::from(models.viewers.clone()));
bridge.set_pins(ModelRc::from(models.pins.clone()));
bridge.set_topics(ModelRc::from(models.topics.clone()));
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()));
models
}
@@ -236,6 +347,8 @@ pub(crate) struct App {
pub inputs: DeviceChoices,
pub outputs: DeviceChoices,
pub playback: ClientPlaybackMap,
/// The engine's contacts, by unique id ([`Event::ContactsChanged`]).
pub contacts: HashMap<String, voelin_core::Contact>,
/// The client in the volume dialog: session, client id, unique id.
pub playback_dialog: Option<(i64, u16, Option<String>)>,
pub mic_test: bool,
@@ -260,6 +373,9 @@ pub(crate) struct App {
pub open_client_pending: bool,
/// The notices are in the About page's model.
pub notices_loaded: bool,
/// 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)>,
}
thread_local! {
@@ -370,6 +486,12 @@ pub fn run(options: RunOptions) -> Result<()> {
};
let store =
Store::open(&dir.join("client.db")).context("failed to open the client database")?;
// Chat history and contacts live in the client database; without this
// the engine would keep them for this run only.
match History::open(&dir.join("client.db")) {
Ok(history) => engine.send(Command::AttachHistory(history)),
Err(e) => warn!(%e, "chat history is not stored this time"),
}
let identity = match store.identities()?.first() {
Some(entry) => store.identity(entry.id)?,
None => {
@@ -429,6 +551,7 @@ pub fn run(options: RunOptions) -> Result<()> {
inputs: DeviceChoices::default(),
outputs: DeviceChoices::default(),
playback,
contacts: HashMap::new(),
playback_dialog: None,
mic_test: false,
ptt,
@@ -443,6 +566,7 @@ pub fn run(options: RunOptions) -> Result<()> {
autoshare: switches.autoshare,
open_client_pending: switches.open_client,
notices_loaded: false,
uploads: HashMap::new(),
};
APP.with(|a| *a.borrow_mut() = Some(app));
crate::bind::wire(&ui);
@@ -662,7 +786,47 @@ impl App {
Event::MicrophoneTestError { message } => {
self.set_status(format!("Microphone test: {message}"))
}
Event::Chat { session, message } => self.add_message(session as i64, message),
// Only for sessions the engine keeps no history for (it does not
// know the server yet): those get ids and reactions instead.
Event::Chat { session, message } => {
let id = session as i64;
if !self.sessions.entry(id).or_default().has_history() {
self.add_message(id, message);
}
}
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::Groups { session, server_groups, .. } => {
let view = self.sessions.entry(session as i64).or_default();
view.server_groups = (*server_groups).clone();
if self.current == Some(session as i64) {
self.refresh_tree();
}
}
Event::AvatarReady { session, client_uid, path, .. } => {
let view = self.sessions.entry(session as i64).or_default();
view.avatars.insert(client_uid, path);
if self.current == Some(session as i64) {
self.refresh_tree();
self.refresh_chat();
}
}
Event::IconReady { session, icon, path } => {
let view = self.sessions.entry(session as i64).or_default();
view.icons.insert(icon, path);
if self.current == Some(session as i64) {
self.refresh_tree();
}
}
Event::Transfer { session, transfer, state } => {
self.transfer_progress(session as i64, transfer, state);
}
Event::ContactsChanged { contacts } => {
self.contacts = contacts.iter().map(|c| (c.uid.clone(), c.clone())).collect();
self.refresh_member_card();
}
// The sample sessions of VOELIN_DEMO_UI are unknown to the engine.
Event::Error { .. } if self.demo_ui => {}
Event::Error { message, .. } => self.set_status(message),
+19 -2
View File
@@ -8,7 +8,7 @@ use tracing::warn;
use crate::app::{App, AppearanceForm, Bridge, Nav, Theme};
use crate::images;
use crate::settings::{
ThemeChoice, UI_FONT_SCALE, UI_IMAGE_CACHE_MB, UI_NARROW_BREAKPOINT, UI_THEME,
ThemeChoice, UI_FONT_SCALE, UI_IMAGE_CACHE_MB, UI_MEMBERS_WIDTH, UI_NARROW_BREAKPOINT, UI_THEME,
};
impl App {
@@ -23,7 +23,12 @@ impl App {
let t = ui.global::<Theme>();
t.set_mode(theme.as_str().into());
t.set_font_scale(scale);
ui.global::<Nav>().set_narrow_breakpoint(breakpoint as f32);
let nav = ui.global::<Nav>();
nav.set_narrow_breakpoint(breakpoint as f32);
let width = self.prefs.get(&UI_MEMBERS_WIDTH) as f32;
if nav.get_right_panel_width() != width {
nav.set_right_panel_width(width);
}
let bridge = ui.global::<Bridge>();
bridge.set_appearance(AppearanceForm {
theme: theme.as_str().into(),
@@ -53,4 +58,16 @@ impl App {
// may not run the settings service (tests, a hosted engine).
self.apply_appearance();
}
/// The members panel was dragged to another width: store it, so it
/// comes back the same and `--set ui.members_width` can change it.
pub(crate) fn panel_resized(&mut self, width: f32) {
let width = width.max(0.0).round() as u32;
if self.prefs.get(&UI_MEMBERS_WIDTH) == width {
return;
}
if let Err(e) = self.prefs.set(&UI_MEMBERS_WIDTH, width) {
warn!(%e, "could not store the panel width");
}
}
}
+44 -2
View File
@@ -1,9 +1,9 @@
//! The chat view.
//! The chat view: tabs, messages, reactions, pins, topics and files.
use slint::ComponentHandle;
use voelin_model::{ChannelId, ChatTarget};
use crate::app::{Bridge, MainWindow, with_app};
use crate::app::{App, Bridge, MainWindow, with_app};
pub(super) fn wire(ui: &MainWindow) {
let bridge = ui.global::<Bridge>();
@@ -19,4 +19,46 @@ pub(super) fn wire(ui: &MainWindow) {
bridge.on_send_message(|text| {
with_app(|app| app.send_message(text.to_string()));
});
bridge.on_load_older(|| {
with_app(App::load_older);
});
bridge.on_react(|key, emoji| {
with_app(|app| app.react(key, emoji.to_string()));
});
bridge.on_pin(|key, on| {
with_app(|app| app.pin(key, on));
});
bridge.on_download_file(|key, index| {
with_app(|app| app.download_file(key, index));
});
bridge.on_attach_file(|| {
with_app(App::attach_file);
});
bridge.on_open_pins(|| {
with_app(App::open_pins);
});
bridge.on_jump_to_pin(|key| {
with_app(|app| app.jump_to_pin(key));
});
bridge.on_open_topics(|| {
with_app(App::open_topics);
});
bridge.on_open_topic(|id| {
with_app(|app| app.open_topic(id));
});
bridge.on_send_topic_message(|text| {
with_app(|app| app.send_topic_message(text.to_string()));
});
bridge.on_create_topic(|key, title| {
with_app(|app| app.create_topic(key, title.to_string()));
});
bridge.on_open_member(|id| {
with_app(|app| app.open_member(id));
});
bridge.on_member_action(|action| {
with_app(|app| app.member_action(&action));
});
bridge.on_member_volume(|percent| {
with_app(|app| app.member_volume(percent));
});
}
+3 -1
View File
@@ -35,7 +35,9 @@ fn show(ui: &MainWindow, category: i32, list: Vec<PickerEmoji>) {
}
pub(super) fn wire(ui: &MainWindow) {
ui.global::<Images>().on_emoji(|key| images::emoji(&key));
let images_global = ui.global::<Images>();
images_global.on_emoji(|key| images::emoji(&key));
images_global.on_emoji_text(|key| emoji::text_of(&key).into());
let global = ui.global::<Emoji>();
let weak = ui.as_weak();
global.on_load(move || {
+3
View File
@@ -27,6 +27,9 @@ pub(super) fn wire(ui: &MainWindow) {
bridge.on_download_h264(|| {
with_app(|app| app.download_h264());
});
bridge.on_panel_resized(|width| {
with_app(|app| app.panel_resized(width));
});
bridge.on_appearance_changed(|form| {
with_app(|app| app.appearance_changed(&form));
});
+3
View File
@@ -37,4 +37,7 @@ pub(super) fn wire(ui: &MainWindow) {
bridge.on_toggle_fullscreen(|| {
with_app(|app| app.toggle_fullscreen());
});
bridge.on_set_stream_quality(|index| {
with_app(|app| app.set_stream_quality(index));
});
}
+634 -62
View File
@@ -1,13 +1,65 @@
//! Chat: tabs per session (server, channels, private chats) and their
//! messages. Each tab keeps its lines as a model; the chat view shows the
//! selected tab's model, so a new message appends one row.
//! Chat: tabs per session (server, channels, private chats), their
//! messages, and what a gateway adds to them (pins, reactions, topics).
//!
//! The engine keeps the history: [`Event::ChatHistory`] is an upsert of
//! messages by their local id (see `voelin_core::history`), so a tab holds
//! the messages it was given, ordered by `(ts_ms, id)`, and the lines of
//! the selected tab are rebuilt from them with [`vm::list::sync`], which
//! touches only the rows that changed. Sessions the engine keeps no history
//! for (it does not know the server yet) fall back to [`Event::Chat`].
use std::path::PathBuf;
use slint::{ComponentHandle, ModelRc};
use voelin_core::Command;
use voelin_core::gateway::Pin;
use voelin_core::{
Command, DownloadTo, GatewayRequest, GatewayUpdate, HistoryMessage, HistorySource,
TransferState,
};
use voelin_gateway_proto::{TopicInfo, feature};
use voelin_model::{ChatMessage, ChatTarget};
use crate::app::{App, Bridge, ChatTab, Tab};
use crate::app::{App, Bridge, ChatLine, ChatTab, FileItem, Msg, PinItem, SessionView, Tab};
use crate::vm;
use crate::vm::chat::{LineCtx, Previous};
/// A file being downloaded from a chat message.
pub(crate) struct Download {
/// The message's handle and which of its links this is.
pub key: i32,
pub index: usize,
pub name: String,
pub state: TransferState,
}
/// A pinned message of a chat, with who pinned it.
pub(crate) struct PinRow {
pub key: i32,
pub message: HistoryMessage,
pub by: String,
pub ts_ms: i64,
}
/// "3 min ago", "yesterday", "12 Mar".
fn ago(ts_ms: i64) -> String {
let Some(then) = chrono::DateTime::from_timestamp_millis(ts_ms) else { return String::new() };
let minutes = (chrono::Utc::now() - then).num_minutes();
match minutes {
i64::MIN..=0 => "just now".into(),
1 => "1 min ago".into(),
2..=59 => format!("{minutes} min ago"),
60..=119 => "1 hour ago".into(),
120..=1439 => format!("{} hours ago", minutes / 60),
1440..=2879 => "yesterday".into(),
_ => then.with_timezone(&chrono::Local).format("%e %b").to_string().trim().into(),
}
}
fn time_of(ts_ms: i64) -> String {
chrono::DateTime::from_timestamp_millis(ts_ms)
.map(|t| t.with_timezone(&chrono::Local).format("%H:%M").to_string())
.unwrap_or_default()
}
impl App {
pub(crate) fn open_chat(&mut self, target: ChatTarget, focus: bool) {
@@ -48,6 +100,7 @@ impl App {
{
view.current_tab = index;
view.tabs[index].unread = 0;
view.tabs[index].topic = None;
}
self.refresh_chat();
self.refresh_servers();
@@ -72,32 +125,47 @@ impl App {
self.engine.send(Command::SendChat { session: id as u64, target, text });
}
/// The index of `target`'s tab, opening one if it is new.
fn tab_for(
view: &mut SessionView,
target: &ChatTarget,
title: impl FnOnce() -> String,
) -> usize {
match view.tabs.iter().position(|t| t.target == *target) {
Some(i) => i,
None => {
view.tabs.push(Tab::new(target.clone(), title()));
view.tabs.len() - 1
}
}
}
fn tab_title(view: &SessionView, target: &ChatTarget, author: &str) -> String {
match target {
ChatTarget::Channel(cid) => format!(
"#{}",
view.presence
.channels
.get(cid)
.map(|c| c.name.clone())
.unwrap_or_else(|| cid.to_string())
),
ChatTarget::Private(_) => format!("@{author}"),
ChatTarget::Server => "Server".into(),
}
}
/// A live message of a session without stored history: appended as it
/// comes, without an id.
pub(crate) fn add_message(&mut self, id: i64, message: ChatMessage) {
let current = self.current == Some(id);
let view = self.sessions.entry(id).or_default();
let index = match view.tabs.iter().position(|t| t.target == message.target) {
Some(i) => i,
None => {
let title = match &message.target {
ChatTarget::Channel(cid) => format!(
"#{}",
view.presence
.channels
.get(cid)
.map(|c| c.name.clone())
.unwrap_or_else(|| cid.to_string())
),
ChatTarget::Private(_) => format!("@{}", message.author_name),
ChatTarget::Server => "Server".into(),
};
view.tabs.push(Tab::new(message.target.clone(), title));
view.tabs.len() - 1
}
};
let title = Self::tab_title(view, &message.target, &message.author_name);
let index = Self::tab_for(view, &message.target, || title);
let shown = current && view.current_tab == index;
let tab = &mut view.tabs[index];
let line = vm::chat::line(&message, tab.last.as_ref());
tab.last = Some(vm::chat::Previous::of(&message));
tab.last = Some(Previous::of(&message));
tab.lines.push(line);
if !shown {
tab.unread += 1;
@@ -110,55 +178,559 @@ impl App {
}
}
/// Messages the engine stored: added or updated by their local id.
pub(crate) fn history_batch(
&mut self,
id: i64,
target: &ChatTarget,
messages: Vec<HistoryMessage>,
source: HistorySource,
complete: bool,
) {
let current = self.current == Some(id);
let view = self.sessions.entry(id).or_default();
let author = messages.first().map_or("", |m| m.message.author_name.as_str());
let title = Self::tab_title(view, target, author);
let index = Self::tab_for(view, target, || title);
let shown = current && view.current_tab == index;
let tab = &mut view.tabs[index];
if source == HistorySource::Gateway {
tab.synced = true;
}
if source != HistorySource::Live {
tab.loading = false;
tab.complete = tab.complete || complete;
}
let mut fresh = 0;
for message in messages {
match tab.messages.iter().position(|m| m.message.id == message.id) {
Some(i) => tab.messages[i].message = message,
None => {
let key = tab.take_key();
if source == HistorySource::Live {
fresh += 1;
}
tab.messages.push(Msg { key, message });
}
}
}
tab.messages.sort_by_key(|m| (m.message.message.ts_ms, m.message.id));
if !shown {
tab.unread += fresh;
}
if current {
self.refresh_chat();
}
if fresh > 0 && !shown {
self.refresh_servers();
}
}
/// The page of messages before the oldest one shown.
pub(crate) fn load_older(&mut self) {
let Some(id) = self.current else { return };
let Some(view) = self.sessions.get_mut(&id) else { return };
let tab = &mut view.tabs[view.current_tab];
if tab.loading || tab.complete {
return;
}
tab.loading = true;
let target = tab.target.clone();
let before = tab.messages.first().map(|m| m.message.id);
self.engine.send(Command::LoadOlderHistory { session: id as u64, target, before });
self.refresh_chat();
}
/// The lines of a tab, grouped and with everything the row shows.
fn lines_of(&self, view: &SessionView, tab: &Tab, messages: &[Msg]) -> Vec<ChatLine> {
let gateway = view.gateway_has(feature::PINS)
|| view.gateway_has(feature::REACTIONS)
|| view.gateway_has(feature::TOPICS);
let mut previous: Option<Previous> = None;
let mut lines = Vec::with_capacity(messages.len());
for m in messages {
let avatar =
m.message.message.author_uid.as_ref().and_then(|uid| view.avatars.get(uid));
let topic = m
.message
.topic_id
.filter(|_| tab.topic.is_none())
.and_then(|t| tab.topics.iter().find(|i| i.id == t))
.map(|t| t.title.clone())
.unwrap_or_default();
let ctx = LineCtx {
key: m.key,
avatar: vm::avatar::image(avatar),
gateway,
marked: tab.marked == Some(m.message.id),
topic,
downloads: self.downloads_of(view, m.key),
};
lines.push(vm::chat::history_line(&m.message, previous.as_ref(), &ctx));
previous = Some(Previous::of(&m.message.message));
}
lines
}
/// The file cards of a message that has downloads running.
fn downloads_of(&self, view: &SessionView, key: i32) -> Vec<(usize, FileItem)> {
view.downloads
.values()
.filter(|d| d.key == key)
.map(|d| {
let (detail, status, progress) = match &d.state {
TransferState::Requested => ("Starting…".to_owned(), "running", 0.0),
TransferState::Started { size, offset } => (
format!(
"{} of {}",
vm::chat::size_text(*offset),
vm::chat::size_text(*size)
),
"running",
if *size > 0 { *offset as f32 / *size as f32 } else { 0.0 },
),
TransferState::Progress { done, size } => (
format!("{} of {}", vm::chat::size_text(*done), vm::chat::size_text(*size)),
"running",
if *size > 0 { *done as f32 / *size as f32 } else { 0.0 },
),
TransferState::Done { size, .. } => {
(format!("Downloaded · {}", vm::chat::size_text(*size)), "done", 1.0)
}
TransferState::Failed(e) => (e.clone(), "failed", 0.0),
TransferState::Cancelled => ("Cancelled".to_owned(), "failed", 0.0),
};
(
d.index,
FileItem {
name: d.name.clone().into(),
detail: detail.into(),
index: d.index as i32,
state: status.into(),
progress,
..Default::default()
},
)
})
.collect()
}
/// Tabs and the shown tab's messages.
pub(crate) fn refresh_chat(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let (tabs, lines) = match self.view() {
None => (
vec![ChatTab { title: "Server".into(), ..Default::default() }],
ModelRc::from(self.models.no_chat.clone()),
),
Some(view) => {
let tabs: Vec<ChatTab> = view
.tabs
.iter()
.map(|t| ChatTab {
title: t.title.clone().into(),
name: t.title.trim_start_matches(['#', '@']).into(),
kind: match t.target {
ChatTarget::Server => 0,
ChatTarget::Channel(_) => 1,
ChatTarget::Private(_) => 2,
},
id: match t.target {
ChatTarget::Channel(cid) => cid as i32,
_ => 0,
},
unread: t.unread,
topic: match t.target {
ChatTarget::Channel(cid) => view
.presence
.channels
.get(&cid)
.and_then(|c| c.topic.clone())
.unwrap_or_default()
.into(),
_ => Default::default(),
},
})
.collect();
(tabs, ModelRc::from(view.tabs[view.current_tab].lines.clone()))
let Some(view) = self.view() else {
vm::list::sync(
&self.models.tabs,
&[ChatTab { title: "Server".into(), ..Default::default() }],
);
let empty = ModelRc::from(self.models.no_chat.clone());
if bridge.get_messages() != empty {
bridge.set_messages(empty);
}
return;
};
let tabs: Vec<ChatTab> = view
.tabs
.iter()
.map(|t| ChatTab {
title: t.title.clone().into(),
name: t.title.trim_start_matches(['#', '@']).into(),
kind: match t.target {
ChatTarget::Server => 0,
ChatTarget::Channel(_) => 1,
ChatTarget::Private(_) => 2,
},
id: match t.target {
ChatTarget::Channel(cid) => cid as i32,
_ => 0,
},
unread: t.unread,
topic: match t.target {
ChatTarget::Channel(cid) => view
.presence
.channels
.get(&cid)
.and_then(|c| c.topic.clone())
.unwrap_or_default()
.into(),
_ => Default::default(),
},
})
.collect();
vm::list::sync(&self.models.tabs, &tabs);
let current = self.view().map_or(0, |v| v.current_tab as i32);
let current = view.current_tab as i32;
if bridge.get_current_tab() != current {
bridge.set_current_tab(current);
}
// Swap the model only when another tab is shown.
let tab = &view.tabs[view.current_tab];
// Sessions without stored history push their lines themselves.
if view.has_history() {
vm::list::sync(&tab.lines, &self.lines_of(view, tab, &tab.messages));
}
let lines = ModelRc::from(tab.lines.clone());
if bridge.get_messages() != lines {
bridge.set_messages(lines);
}
bridge.set_more_history(view.has_history() && !tab.complete);
bridge.set_loading_history(tab.loading);
bridge.set_local_history(
view.has_history() && !tab.synced && view.gateway_has(feature::HISTORY),
);
bridge.set_has_pins(view.gateway_has(feature::PINS));
bridge.set_has_reactions(view.gateway_has(feature::REACTIONS));
bridge.set_has_topics(view.gateway_has(feature::TOPICS));
bridge.set_pins_loading(!tab.pins_loaded && view.gateway_has(feature::PINS));
bridge.set_topics_loading(!tab.topics_loaded && view.gateway_has(feature::TOPICS));
let pins: Vec<PinItem> = tab
.pins
.iter()
.map(|p| {
let avatar =
p.message.message.author_uid.as_ref().and_then(|u| view.avatars.get(u));
let ctx = LineCtx {
key: p.key,
avatar: vm::avatar::image(avatar),
gateway: true,
..Default::default()
};
PinItem {
line: vm::chat::history_line(&p.message, None, &ctx),
by: format!("pinned by {} · {}", p.by, time_of(p.ts_ms)).into(),
}
})
.collect();
vm::list::sync(&self.models.pins, &pins);
let topics: Vec<crate::app::TopicItem> = tab
.topics
.iter()
.map(|t| crate::app::TopicItem {
id: t.id as i32,
title: t.title.clone().into(),
creator: t.creator.name.clone().into(),
detail: format!(
"{} {} · {}",
t.message_count,
if t.message_count == 1 { "message" } else { "messages" },
ago(t.last_activity_ms)
)
.into(),
archived: t.archived,
})
.collect();
vm::list::sync(&self.models.topics, &topics);
bridge.set_current_topic(tab.topic.map_or(-1, |t| t as i32));
bridge.set_topic_title(
tab.topic
.and_then(|t| tab.topics.iter().find(|i| i.id == t))
.map(|t| t.title.clone())
.unwrap_or_default()
.into(),
);
vm::list::sync(&self.models.topic_messages, &self.lines_of(view, tab, &tab.topic_messages));
}
// Gateway features of a chat.
/// A request to the current session's gateway.
fn gateway(&self, request: GatewayRequest) {
self.command(|session| Command::Gateway { session, request });
}
pub(crate) fn gateway_update(&mut self, id: i64, update: GatewayUpdate) {
let current = self.current == Some(id);
let view = self.sessions.entry(id).or_default();
match update {
GatewayUpdate::Connected { capabilities, .. }
| GatewayUpdate::Capabilities { capabilities } => view.gateway_caps = capabilities,
GatewayUpdate::Disconnected { .. } => {
view.gateway_caps.clear();
for tab in &mut view.tabs {
tab.pins_loaded = false;
tab.topics_loaded = false;
}
}
GatewayUpdate::Pins { target, pins } => {
let index = Self::tab_for(view, &target, || "Server".into());
let tab = &mut view.tabs[index];
tab.pins_loaded = true;
tab.pins = pins.into_iter().map(|p| pin_row(tab.take_key(), p)).collect();
tab.pins.sort_by_key(|p| -p.ts_ms);
}
GatewayUpdate::Pinned { target, pin } => {
let index = Self::tab_for(view, &target, || "Server".into());
let tab = &mut view.tabs[index];
let row = pin_row(tab.take_key(), pin);
tab.pins.retain(|p| p.message.id != row.message.id);
tab.pins.insert(0, row);
}
GatewayUpdate::Unpinned { target, message_id, .. } => {
let index = Self::tab_for(view, &target, || "Server".into());
view.tabs[index].pins.retain(|p| p.message.remote_id != Some(message_id));
}
GatewayUpdate::Topics { target, topics } => {
let index = Self::tab_for(view, &target, || "Server".into());
view.tabs[index].topics = topics;
view.tabs[index].topics_loaded = true;
}
GatewayUpdate::Topic { topic } => {
let index = Self::tab_for(view, &topic.target.clone(), || "Server".into());
upsert_topic(&mut view.tabs[index].topics, topic);
}
GatewayUpdate::TopicHistory { target, topic, messages, .. } => {
let index = Self::tab_for(view, &target, || "Server".into());
let tab = &mut view.tabs[index];
if tab.topic != Some(topic) {
return;
}
for message in messages {
match tab.topic_messages.iter().position(|m| m.message.id == message.id) {
Some(i) => tab.topic_messages[i].message = message,
None => {
let key = tab.take_key();
tab.topic_messages.push(Msg { key, message });
}
}
}
tab.topic_messages.sort_by_key(|m| (m.message.message.ts_ms, m.message.id));
}
GatewayUpdate::Failed { request, message, .. } => {
self.set_status(format!("{request}: {message}"));
return;
}
// Posts, pins and reactions also arrive as stored messages.
_ => return,
}
if current {
self.refresh_chat();
}
}
/// The message a Slint row stands for, in the current chat.
fn message_of(&self, key: i32) -> Option<&HistoryMessage> {
let view = self.view()?;
view.tabs.get(view.current_tab)?.message(key)
}
/// Add or remove our reaction to a message.
pub(crate) fn react(&mut self, key: i32, emoji: String) {
let Some(message) = self.message_of(key) else { return };
let Some(message_id) = message.remote_id else { return };
let had = message.reactions.iter().any(|r| r.emoji == emoji && r.me);
self.gateway(if had {
GatewayRequest::Unreact { message_id, emoji }
} else {
GatewayRequest::React { message_id, emoji }
});
}
pub(crate) fn pin(&mut self, key: i32, on: bool) {
let Some(message) = self.message_of(key) else { return };
let Some(message_id) = message.remote_id else { return };
self.gateway(if on {
GatewayRequest::Pin { message_id }
} else {
GatewayRequest::Unpin { message_id }
});
}
/// Open the pins of the current chat (loading them once).
pub(crate) fn open_pins(&mut self) {
let Some(view) = self.view() else { return };
let tab = &view.tabs[view.current_tab];
if !tab.pins_loaded {
let target = tab.target.clone();
self.gateway(GatewayRequest::Pins { target });
}
self.refresh_chat();
}
/// Highlight a pinned message in the chat.
pub(crate) fn jump_to_pin(&mut self, key: i32) {
let Some(view) = self.view_mut() else { return };
let tab = &mut view.tabs[view.current_tab];
tab.marked = tab.pins.iter().find(|p| p.key == key).map(|p| p.message.id);
self.refresh_chat();
}
pub(crate) fn open_topics(&mut self) {
let Some(view) = self.view() else { return };
let tab = &view.tabs[view.current_tab];
if !tab.topics_loaded {
let target = tab.target.clone();
self.gateway(GatewayRequest::Topics { target, include_archived: false });
}
self.refresh_chat();
}
/// Show a topic's messages (`-1` goes back to the chat).
pub(crate) fn open_topic(&mut self, id: i32) {
let Some(view) = self.view_mut() else { return };
let tab = &mut view.tabs[view.current_tab];
tab.topic_messages.clear();
tab.topic = (id >= 0).then_some(id as i64);
let target = tab.target.clone();
if let Some(topic) = tab.topic {
self.gateway(GatewayRequest::TopicHistory { target, topic, before: None, limit: None });
}
self.refresh_chat();
}
pub(crate) fn send_topic_message(&mut self, text: String) {
let Some(view) = self.view() else { return };
let tab = &view.tabs[view.current_tab];
let (Some(topic), target) = (tab.topic, tab.target.clone()) else { return };
self.gateway(GatewayRequest::Post { target, text, topic: Some(topic) });
}
/// Start a topic from a message (`key` < 0: a standalone topic).
pub(crate) fn create_topic(&mut self, key: i32, title: String) {
let Some(view) = self.view() else { return };
let target = view.tabs[view.current_tab].target.clone();
let message_id = self.message_of(key).and_then(|m| m.remote_id);
self.gateway(GatewayRequest::CreateTopic { target, title, message_id });
}
// Files in chat.
/// Download a file a message links, into the download folder.
pub(crate) fn download_file(&mut self, key: i32, index: i32) {
let Some(id) = self.current else { return };
let index = index.max(0) as usize;
let Some(file) =
self.message_of(key).and_then(|m| m.message.file_refs().into_iter().nth(index))
else {
return;
};
let dir = dirs::download_dir().unwrap_or_else(|| PathBuf::from("."));
let path = dir.join(&file.name);
let view = self.sessions.entry(id).or_default();
let transfer = view.next_transfer;
view.next_transfer += 1;
view.downloads.insert(
transfer,
Download { key, index, name: file.name.clone(), state: TransferState::Requested },
);
self.engine.send(Command::DownloadChatFile {
session: id as u64,
transfer,
file,
password: None,
to: DownloadTo::Path { path, resume: false },
});
self.refresh_chat();
}
pub(crate) fn transfer_progress(&mut self, id: i64, transfer: u64, state: TransferState) {
// An upload from the composer: post the file's link once it is up.
if let Some((_, channel, name)) = self.uploads.get(&transfer).cloned() {
match &state {
TransferState::Done { size, .. } => {
self.uploads.remove(&transfer);
let file = voelin_model::FileRef {
channel,
path: "/".into(),
name: name.clone(),
size: Some(*size),
..Default::default()
};
self.engine.send(Command::SendChat {
session: id as u64,
target: ChatTarget::Channel(channel),
text: file.to_bbcode(),
});
self.set_status(format!("{name} shared"));
}
TransferState::Failed(e) => {
self.uploads.remove(&transfer);
self.set_status(format!("Could not upload {name}: {e}"));
}
TransferState::Cancelled => {
self.uploads.remove(&transfer);
}
_ => {}
}
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 };
entry.state = state;
let name = entry.name.clone();
if done {
self.set_status(format!("{name} downloaded"));
}
if self.current == Some(id) {
self.refresh_chat();
}
}
/// Attach a file to the current channel chat: ask for one, upload it
/// into the channel and post its link.
pub(crate) fn attach_file(&mut self) {
let Some(id) = self.current else { return };
let Some(view) = self.sessions.get(&id) else { return };
let ChatTarget::Channel(channel) = view.tabs[view.current_tab].target else {
self.set_status("Files can be attached to a channel's chat.");
return;
};
if !voelin_platform::files::available() {
self.set_status("No file chooser on this platform.");
return;
}
let runtime = self.engine.runtime().clone();
runtime.spawn(async move {
let picked = voelin_platform::files::pick_file("Attach a file").await;
crate::app::later(move |app| match picked {
Ok(Some(path)) => app.upload(id, channel, path),
Ok(None) => {}
Err(e) => app.set_status(format!("Could not open the file chooser: {e}")),
});
});
}
/// Upload a file into a channel and link it in the chat once it is up.
fn upload(&mut self, id: i64, channel: u64, from: PathBuf) {
let Some(name) = from.file_name().map(|n| n.to_string_lossy().to_string()) else { return };
let view = self.sessions.entry(id).or_default();
let transfer = view.next_transfer;
view.next_transfer += 1;
self.uploads.insert(transfer, (id, channel, name.clone()));
self.engine.send(Command::UploadFile {
session: id as u64,
transfer,
channel,
password: None,
path: format!("/{name}"),
from,
overwrite: true,
resume: false,
});
self.set_status(format!("Uploading {name}…"));
}
}
fn pin_row(key: i32, pin: Pin) -> PinRow {
PinRow { key, message: pin.message, by: pin.by.name, ts_ms: pin.ts_ms }
}
fn upsert_topic(topics: &mut Vec<TopicInfo>, topic: TopicInfo) {
match topics.iter().position(|t| t.id == topic.id) {
Some(i) => topics[i] = topic,
None => topics.insert(0, topic),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn relative_times() {
let now = chrono::Utc::now().timestamp_millis();
assert_eq!(ago(now), "just now");
assert_eq!(ago(now - 3 * 60_000), "3 min ago");
assert_eq!(ago(now - 3 * 3_600_000), "3 hours ago");
assert_eq!(ago(now - 36 * 3_600_000), "yesterday");
}
}
+392 -59
View File
@@ -25,12 +25,19 @@ use std::time::Duration;
use anyhow::Result;
use slint::ComponentHandle;
use voelin_core::gateway::Pin;
use voelin_core::stream::{StreamInfo, StreamKind};
use voelin_core::{Event, ObserveState, SessionState, Source, VoiceState};
use voelin_model::{ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence, ServerFlavor};
use voelin_store::Bookmark;
use voelin_core::{
Event, GatewayUpdate, HistoryMessage, HistorySource, ObserveState, SessionState, Source,
VoiceState,
};
use voelin_gateway_proto::{ReactionCount, TopicInfo, UserRef, feature};
use voelin_model::{
ChannelInfo, ChatMessage, ChatTarget, ClientInfo, GroupInfo, Presence, ServerFlavor,
};
use voelin_store::{Bookmark, MessageSource};
use crate::app::{App, MainWindow, MobileTab, Nav, Page, SettingsSection, with_app};
use crate::app::{App, Bridge, MainWindow, MobileTab, Nav, Page, SettingsSection, with_app};
/// The switches read at start.
#[derive(Clone, Debug, Default)]
@@ -104,6 +111,7 @@ fn mobile_tab(name: &str) -> MobileTab {
/// Timers that must live while the window runs.
pub(crate) struct Running {
_screenshot: Option<slint::Timer>,
_resize: Option<slint::Timer>,
}
/// Apply the switches once the app is set up.
@@ -137,11 +145,43 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running {
"panel" => nav.set_right_panel_open(true),
"no-panel" => nav.set_right_panel_open(false),
"tab" => nav.set_mobile_tab(mobile_tab(arg)),
"voice" => nav.set_voice_grid(true),
"pins" => nav.invoke_show_pins(true),
"topics" => nav.invoke_show_topics(true),
"topic" => {
with_app(|app| app.open_topic(arg.parse().unwrap_or(1)));
}
"member" => {
with_app(|app| app.open_first_member());
}
"watch" => {
with_app(|app| app.watch_first_stream());
}
"popout" => {
with_app(|app| app.watch_first_stream());
ui.global::<Bridge>().set_viewer_popped(true);
}
// Opened once connected (settings_page.rs).
"client" => {}
other => eprintln!("VOELIN_OPEN: unknown screen {other:?}"),
}
}
// A window manager can refuse the size set before the window opened,
// so ask again once it is up (a bare X server ignores both).
let resize = switches.window_size.map(|(w, h)| {
let weak = ui.as_weak();
let timer = slint::Timer::default();
timer.start(
slint::TimerMode::SingleShot,
Duration::from_millis(switches.screenshot_delay * 1000 / 2),
move || {
if let Some(ui) = weak.upgrade() {
ui.window().set_size(slint::LogicalSize::new(w, h));
}
},
);
timer
});
let screenshot = switches.screenshot.clone().map(|path| {
let weak = ui.as_weak();
let timer = slint::Timer::default();
@@ -159,7 +199,7 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running {
);
timer
});
Running { _screenshot: screenshot }
Running { _screenshot: screenshot, _resize: resize }
}
fn save_screenshot(ui: &MainWindow, path: &std::path::Path) -> Result<()> {
@@ -241,14 +281,48 @@ fn demo_ui(app: &mut App) {
clients[4].input_muted = true;
clients[7].away = Some("brb".into());
clients[8].output_muted = true;
// Groups, badges and descriptions, as the members panel shows them.
clients[0].server_groups = vec![GROUP_MOD];
clients[0].talk_power = 75;
clients[0].description = Some("Raid lead. Ask me about the Tuesday runs.".into());
clients[1].server_groups = vec![GROUP_ADMIN];
clients[1].talk_power = 100;
clients[1].priority_speaker = true;
clients[1].description = Some("Streaming most evenings.".into());
clients[2].server_groups = vec![GROUP_MOD];
clients[2].channel_commander = true;
clients[2].talk_power = 75;
clients[3].server_groups = vec![GROUP_MEMBER];
clients[3].recording = true;
clients[4].server_groups = vec![GROUP_MEMBER];
clients[5].server_groups = vec![GROUP_MEMBER];
clients[6].server_groups = vec![GROUP_GUEST];
clients[7].server_groups = vec![GROUP_GUEST];
for c in clients {
p.clients.insert(c.id, c);
}
let group = |id: u64, sort_id: i32, name: &str| GroupInfo {
id,
name: name.into(),
icon: 0,
sort_id,
..Default::default()
};
let flavor = ServerFlavor::from_version_string("6.0.0-beta13.1 [Build: 1]");
let capabilities = flavor.capabilities();
let events = [
Event::ServerInfo { session, name: "Nightfall Guild".into(), flavor, capabilities },
Event::Groups {
session,
server_groups: Arc::new(vec![
group(GROUP_ADMIN, 10, "Server Admin"),
group(GROUP_MOD, 20, "Moderator"),
group(GROUP_MEMBER, 30, "Member"),
group(GROUP_GUEST, 40, "Guest"),
]),
channel_groups: Arc::new(Vec::new()),
},
Event::Presence { session, presence: Arc::new(p) },
Event::State {
session,
@@ -257,9 +331,28 @@ fn demo_ui(app: &mut App) {
presence_source: Some(Source::Voice),
own_channel: Some(2),
own_client: Some(1),
// The engine keeps history for a server it knows, so the
// chat is driven by `Event::ChatHistory` like a real one.
server_uid: Some("demo-server".into()),
..Default::default()
},
},
// A gateway with everything the chat screens need.
Event::Gateway {
session,
update: GatewayUpdate::Connected {
gateway_id: "demo".into(),
server_uid: "demo-server".into(),
server_name: "Nightfall Guild".into(),
uid: "demo-1".into(),
capabilities: vec![
feature::HISTORY.into(),
feature::PINS.into(),
feature::REACTIONS.into(),
feature::TOPICS.into(),
],
},
},
Event::Talking { session, client: 3, talking: true },
Event::StreamsChanged {
session,
@@ -281,61 +374,301 @@ fn demo_ui(app: &mut App) {
for event in events {
app.handle_event(event);
}
let now = chrono::Utc::now().timestamp_millis();
let lines = [
(
DEMO,
ChatTarget::Channel(2),
"Nova",
"Beautiful morning for a game. Who's up for a session later? ☀️",
0,
false,
),
(DEMO, ChatTarget::Channel(2), "Kairo", "Definitely! I'll be on after lunch.", 4, false),
(DEMO, ChatTarget::Channel(2), "Kairo", "Bringing snacks 🍕🍩", 4, false),
(
DEMO,
ChatTarget::Channel(2),
"Mira",
"Working on a new video today — here's a sneak peek soon! 🎬",
7,
false,
),
(
DEMO,
ChatTarget::Channel(2),
"Lumen",
"Going live in Chill Zone — exploring the Lands Between. Come hang! 🔥🗡️",
48,
false,
),
(DEMO, ChatTarget::Channel(2), "dex", "🎉🎉", 50, false),
(
DEMO,
ChatTarget::Channel(2),
"Ari",
"Anyone want to run some co-op later? 👀 Posting from the web.",
55,
true,
),
(DEMO, ChatTarget::Server, "Talon", "Server restart tonight at 23:00.", 20, false),
(DEMO + 1, ChatTarget::Server, "Ivy", "Welcome to the lounge!", 30, false),
(DEMO + 1, ChatTarget::Server, "Ivy", "New channel for artists 🎨", 31, false),
];
for (id, target, author, text, minute, relay) in lines {
let message = ChatMessage {
target,
author_name: author.into(),
author_uid: None,
author_id: None,
text: text.into(),
ts_ms: now - (60 - minute) * 60_000,
via_relay: relay,
blocked: false,
};
app.add_message(id, message);
}
demo_chat(app, session);
// No toast over the screenshots.
app.set_status("");
app.refresh_all();
}
/// Server group ids of the sample server.
const GROUP_ADMIN: u64 = 6;
const GROUP_MOD: u64 = 7;
const GROUP_MEMBER: u64 = 8;
const GROUP_GUEST: u64 = 9;
/// A file link as TeamSpeak clients post it.
fn file_link(channel: u64, name: &str, size: u64) -> String {
voelin_model::FileRef {
channel,
path: "/".into(),
name: name.into(),
size: Some(size),
..Default::default()
}
.to_bbcode()
}
/// One sample message: chat, author, its client, text, how many minutes
/// ago, relayed, reactions, pinned, and the topic it belongs to.
type SampleLine =
(i64, &'static str, u16, String, i64, bool, Vec<ReactionCount>, bool, Option<i64>);
/// The sample chats, as stored messages with reactions, pins and topics.
fn demo_chat(app: &mut App, session: u64) {
let now = chrono::Utc::now().timestamp_millis();
let react =
|emoji: &str, count: u32, me: bool| ReactionCount { emoji: emoji.into(), count, me };
let lines: Vec<SampleLine> = vec![
(
DEMO,
"Nova",
1,
"Beautiful morning for a game. Who's up for a session later? ☀️".into(),
60,
false,
vec![react("👍", 3, false), react("☀️", 1, true)],
false,
None,
),
(
DEMO,
"Kairo",
3,
"Definitely! I'll be on after lunch.".into(),
56,
false,
Vec::new(),
false,
None,
),
(DEMO, "Kairo", 3, "Bringing snacks 🍕🍩".into(), 56, false, Vec::new(), false, None),
(
DEMO,
"Mira",
4,
format!(
"Route for tonight, print it out: {}",
file_link(2, "raid-route.pdf", 2_411_724)
),
40,
false,
vec![react("🎉", 5, true)],
true,
None,
),
(
DEMO,
"Nova",
1,
"Reminder: raid starts 20:00 sharp, bring elixirs.".into(),
30,
false,
Vec::new(),
true,
Some(1),
),
(
DEMO,
"dex",
5,
"Can somebody look at the wiki page? The old link is dead.".into(),
26,
false,
Vec::new(),
false,
None,
),
(
DEMO,
"Kairo",
3,
"Fixed, it points at the new host now.".into(),
24,
false,
vec![react("👍", 2, false)],
false,
None,
),
(
DEMO,
"Mira",
4,
format!("And the banner I promised: {}", file_link(2, "guild-banner.png", 486_912)),
20,
false,
Vec::new(),
false,
None,
),
(
DEMO,
"Talon",
6,
"That looks great. Putting it on the site tonight.".into(),
17,
false,
vec![react("❤️", 4, true)],
false,
None,
),
(
DEMO,
"Lumen",
2,
"Going live in Chill Zone — exploring the Lands Between. Come hang! 🔥🗡️".into(),
12,
false,
vec![react("🔥", 8, false)],
false,
None,
),
(DEMO, "dex", 5, "🎉🎉".into(), 10, false, Vec::new(), false, None),
(
DEMO,
"Ari",
0,
"Anyone want to run some co-op later? 👀 Posting from the web.".into(),
5,
true,
Vec::new(),
false,
None,
),
(DEMO + 1, "Ivy", 0, "Welcome to the lounge!".into(), 30, false, Vec::new(), false, None),
(
DEMO + 1,
"Ivy",
0,
"New channel for artists 🎨".into(),
29,
false,
Vec::new(),
false,
None,
),
];
let mut id = 1;
let mut pinned: Vec<HistoryMessage> = Vec::new();
for (chat, author, client, text, ago, relay, reactions, pin, topic) in lines {
let target = if chat == DEMO { ChatTarget::Channel(2) } else { ChatTarget::Server };
let message = HistoryMessage {
id,
message: ChatMessage {
target: target.clone(),
author_name: author.into(),
author_uid: Some(format!("demo-{client}")),
author_id: (client > 0).then_some(client),
text,
ts_ms: now - ago * 60_000,
via_relay: relay,
blocked: false,
},
source: MessageSource::Voice,
remote_id: Some(id),
topic_id: topic,
reactions,
pinned: pin,
rev: 1,
};
if pin {
pinned.push(message.clone());
}
app.handle_event(Event::ChatHistory {
session: if chat == DEMO { session } else { session + 1 },
target,
messages: vec![message],
source: HistorySource::Gateway,
complete: false,
});
id += 1;
}
// A server chat besides the channel chat.
app.handle_event(Event::ChatHistory {
session,
target: ChatTarget::Server,
messages: vec![HistoryMessage {
id: 100,
message: ChatMessage {
target: ChatTarget::Server,
author_name: "Talon".into(),
author_uid: Some("demo-6".into()),
author_id: Some(6),
text: "Server restart tonight at 23:00.".into(),
ts_ms: now - 40 * 60_000,
via_relay: false,
blocked: false,
},
source: MessageSource::Voice,
remote_id: Some(100),
topic_id: None,
reactions: Vec::new(),
pinned: false,
rev: 1,
}],
source: HistorySource::Gateway,
complete: true,
});
// The gateway's answers for the drawers (no gateway runs in demo mode).
let by = |name: &str| UserRef { uid: format!("demo-{name}"), name: name.into() };
app.handle_event(Event::Gateway {
session,
update: GatewayUpdate::Pins {
target: ChatTarget::Channel(2),
pins: pinned
.into_iter()
.map(|message| Pin {
ts_ms: message.message.ts_ms + 60_000,
by: by("Nova"),
message,
})
.collect(),
},
});
let topic = |id: i64, title: &str, count: u64, ago: i64| TopicInfo {
id,
target: ChatTarget::Channel(2),
title: title.into(),
creator: by("Nova"),
created_ms: now - 5 * 86_400_000,
root_message_id: Some(5),
last_activity_ms: now - ago * 60_000,
message_count: count,
archived: false,
};
app.handle_event(Event::Gateway {
session,
update: GatewayUpdate::Topics {
target: ChatTarget::Channel(2),
topics: vec![
topic(1, "Tonight's raid", 14, 3),
topic(2, "Build ideas for the new patch", 42, 95),
topic(3, "Server rules", 6, 2880),
],
},
});
app.handle_event(Event::Gateway {
session,
update: GatewayUpdate::TopicHistory {
target: ChatTarget::Channel(2),
topic: 1,
messages: (0..4)
.map(|i| HistoryMessage {
id: 200 + i,
message: ChatMessage {
target: ChatTarget::Channel(2),
author_name: ["Nova", "Kairo", "Mira", "dex"][i as usize].into(),
author_uid: Some(format!("demo-{}", [1, 3, 4, 5][i as usize])),
author_id: Some([1, 3, 4, 5][i as usize]),
text: [
"Reminder: raid starts 20:00 sharp, bring elixirs.",
"I can tank if nobody else wants to.",
"Recording it again, say if you would rather not be in it.",
"Bringing the good soup 🍲",
][i as usize]
.into(),
ts_ms: now - (20 - i * 4) * 60_000,
via_relay: false,
blocked: false,
},
source: MessageSource::Gateway,
remote_id: Some(200 + i),
topic_id: Some(1),
reactions: Vec::new(),
pinned: false,
rev: 1,
})
.collect(),
has_more: false,
},
});
}
+7 -1
View File
@@ -253,7 +253,7 @@ fn key_of(cps: &[u32]) -> String {
/// The characters of an archive key, with U+FE0F after a lone character
/// that is text by default, so other clients show an emoji too.
fn text_of(key: &str) -> String {
pub fn text_of(key: &str) -> String {
let cps: Vec<u32> = key.split('-').filter_map(|p| u32::from_str_radix(p, 16).ok()).collect();
let mut text: String = cps.iter().filter_map(|&cp| char::from_u32(cp)).collect();
if cps.len() == 1 && !emoji_presentation(cps[0]) {
@@ -294,6 +294,12 @@ pub fn key_for(grapheme: &str) -> Option<String> {
archive.contains(&bare).then_some(bare)
}
/// The archive key of the first emoji in `text` (a reaction's emoji, which
/// may be any string).
pub fn first_key(text: &str) -> Option<String> {
text.graphemes(true).find_map(key_for)
}
/// A piece of text: plain, or one emoji (`emoji` is its key).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Run {
+15
View File
@@ -101,6 +101,21 @@ pub fn usage_text() -> String {
})
}
/// A picture the engine put in its cache (avatars, group and client icons),
/// decoded once and kept by its path.
pub fn file(path: &std::path::Path) -> Image {
let key = path.to_string_lossy();
CACHE
.with(|c| {
c.borrow_mut().get_or_load(&key, || {
let image = Image::load_from_path(path).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() {
+1
View File
@@ -8,6 +8,7 @@ mod dev;
mod emoji;
mod hotkey;
mod images;
mod members;
mod servers;
mod settings;
mod settings_page;
+155
View File
@@ -0,0 +1,155 @@
//! The members panel: the card over a member row and what it can do
//! (private chat, poke, contacts, per-client volume). The rows themselves
//! are built in `vm::tree::members`.
use slint::ComponentHandle;
use voelin_core::{Command, Contact, Relation};
use voelin_model::ChatTarget;
use crate::app::{App, Bridge, MemberCard};
use crate::settings::ClientPlayback;
use crate::vm;
impl App {
/// `VOELIN_OPEN=member`: the card of the first person that is not us.
pub(crate) fn open_first_member(&mut self) {
let Some(view) = self.view() else { return };
let own = view.state.own_client;
let mut others: Vec<u16> = view
.presence
.members(view.state.own_channel.unwrap_or_default())
.filter(|c| Some(c.id) != own)
.map(|c| c.id)
.collect();
others.sort_unstable();
if let Some(id) = others.first().copied() {
self.open_member(i32::from(id));
}
}
/// Open the card of a client (`-1` closes it).
pub(crate) fn open_member(&mut self, client: i32) {
if let Some(view) = self.view_mut() {
view.member_card = u16::try_from(client).ok();
}
self.refresh_member_card();
}
pub(crate) fn refresh_member_card(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
let card = self
.view()
.and_then(|view| {
let id = view.member_card?;
let client = view.presence.clients.get(&id)?;
let uid = client.uid.clone();
let contact = uid.as_ref().and_then(|u| self.contacts.get(u));
let playback =
uid.as_ref().and_then(|u| self.playback.get(u)).copied().unwrap_or_default();
let groups: Vec<slint::SharedString> = client
.server_groups
.iter()
.filter_map(|g| view.server_groups.iter().find(|i| i.id == *g))
.map(|g| g.name.clone().into())
.collect();
Some(MemberCard {
open: true,
id: i32::from(id),
name: client.nickname.clone().into(),
initials: vm::avatar::initials(&client.nickname).into(),
tint: vm::avatar::tint(&client.nickname),
avatar: vm::avatar::image(view.avatar(id)),
status: vm::tree::status_of(client, view.talking.contains(&id)).into(),
description: client.description.clone().unwrap_or_default().into(),
groups: crate::app::model(groups),
country: client.country.clone().unwrap_or_default().into(),
talk_power: client.talk_power,
friend: contact.is_some_and(|c| c.relation == Relation::Friend),
blocked: contact.is_some_and(|c| c.relation == Relation::Blocked),
volume: playback.volume * 100.0,
muted: playback.muted,
known: uid.is_some(),
})
})
.unwrap_or_default();
bridge.set_member_card(card);
}
/// The card's buttons: "message", "poke", "friend", "blocked", "mute".
pub(crate) fn member_action(&mut self, action: &str) {
let Some(id) = self.current else { return };
let Some(view) = self.sessions.get(&id) else { return };
let Some(client) = view.member_card.and_then(|c| view.presence.clients.get(&c)) else {
return;
};
let (client_id, nickname, uid) = (client.id, client.nickname.clone(), client.uid.clone());
match action {
"message" => {
if let Some(uid) = uid {
self.open_chat(ChatTarget::Private(uid), true);
self.open_member(-1);
}
}
"poke" => {
self.command(|session| Command::Poke {
session,
client: client_id,
message: String::new(),
});
self.set_status(format!("Poked {nickname}"));
}
"friend" | "blocked" => {
let Some(uid) = uid else { return };
let wanted = if action == "friend" { Relation::Friend } else { Relation::Blocked };
let current = self.contacts.get(&uid).map(|c| c.relation);
let mut contact =
self.contacts.get(&uid).cloned().unwrap_or_else(|| Contact::new(uid.clone()));
contact.nickname = nickname;
contact.relation = if current == Some(wanted) { Relation::Neutral } else { wanted };
self.contacts.insert(uid, contact.clone());
self.engine.send(Command::SetContact { contact: Box::new(contact) });
self.refresh_member_card();
}
"mute" => {
let Some(uid) = uid else { return };
let mut playback = self.playback.get(&uid).copied().unwrap_or_default();
playback.muted = !playback.muted;
self.set_playback(&uid, client_id, playback);
}
_ => {}
}
}
/// The card's volume slider, in percent.
pub(crate) fn member_volume(&mut self, percent: f32) {
let Some(view) = self.view() else { return };
let Some(client) = view.member_card.and_then(|c| view.presence.clients.get(&c)) else {
return;
};
let (client_id, Some(uid)) = (client.id, client.uid.clone()) else { return };
let mut playback = self.playback.get(&uid).copied().unwrap_or_default();
playback.volume = (percent / 100.0).clamp(0.0, 4.0);
self.set_playback(&uid, client_id, playback);
}
/// Store one client's playback and apply it to the session.
fn set_playback(&mut self, uid: &str, client: u16, playback: ClientPlayback) {
if playback.is_default() {
self.playback.remove(uid);
} else {
self.playback.insert(uid.to_owned(), playback);
}
if let Err(e) = self.prefs.set(&crate::settings::CLIENT_PLAYBACK, self.playback.clone()) {
tracing::warn!(%e, "could not store client volumes");
}
self.command(|session| Command::SetClientMuted { session, client, muted: playback.muted });
self.command(|session| Command::SetClientVolume {
session,
client,
volume: playback.volume,
});
self.refresh_tree();
self.refresh_member_card();
}
}
+3
View File
@@ -270,6 +270,9 @@ impl App {
own_channel: view.state.own_channel,
own_client: view.state.own_client,
filter: &self.tree_filter,
avatars: &view.avatars,
icons: &view.icons,
groups: &view.server_groups,
};
vm::list::sync(&self.models.tree, &vm::tree::rows(&input));
let members = if view.state.voice == VoiceState::Connected {
+11 -2
View File
@@ -91,9 +91,18 @@ pub static UI_IMAGE_CACHE_MB: Key<u32> = Key::new(
|| 64,
);
/// `ui.members_width`: how wide the members and streams panel is, in
/// pixels. Dragging its handle stores it; there is no built-in maximum.
pub static UI_MEMBERS_WIDTH: Key<u32> = Key::new(
"ui.members_width",
Kind::UInt { min: 0 },
"Width of the members and streams panel in pixels.",
|| 280,
);
/// The UI's keys besides [`UI`] and [`CLIENT_PLAYBACK`], for registering.
pub fn appearance_keys() -> [&'static dyn voelin_core::settings::Setting; 4] {
[&UI_THEME, &UI_FONT_SCALE, &UI_NARROW_BREAKPOINT, &UI_IMAGE_CACHE_MB]
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]
}
/// Frame rates and bitrates (kbit/s) the share dialog offers; any other
+95 -3
View File
@@ -6,7 +6,9 @@ use slint::{ComponentHandle, Model};
use tracing::warn;
use voelin_core::media::audio_source_specs;
use voelin_core::settings::{STREAM_AUDIO_SOURCES, STREAM_BITRATE_KBPS, STREAM_FPS};
use voelin_core::stream::{EndReason, LeaveReason, StreamSetup, ViewerInfo, ViewerState};
use voelin_core::stream::{
EndReason, LayerId, LayerSpec, LeaveReason, StreamSetup, ViewerInfo, ViewerState,
};
use voelin_core::{Command, Event, StreamState, WatchState};
use crate::app::{App, Bridge, ShareForm, SourceItem, StreamItem, ViewerItem, later, model};
@@ -42,6 +44,45 @@ pub(crate) struct Watch {
/// Shown instead of the chat.
shown: bool,
decoder: Option<Decoder>,
/// When the picture started, for the elapsed time.
since: Option<std::time::Instant>,
/// The simulcast layers the streamer offers, largest first.
layers: Vec<LayerSpec>,
/// The layer chosen by hand; `None` follows the bandwidth estimate.
layer: Option<LayerId>,
/// People watching the same stream, as the directory reports it.
viewers: u32,
}
impl Watch {
/// "12:34" since the picture started.
fn elapsed(&self) -> String {
let Some(since) = self.since else { return String::new() };
let seconds = since.elapsed().as_secs();
match seconds / 3600 {
0 => format!("{:02}:{:02}", seconds / 60, seconds % 60),
hours => format!("{hours}:{:02}:{:02}", (seconds / 60) % 60, seconds % 60),
}
}
/// "Auto" and one entry per layer the streamer offers.
fn qualities(&self) -> Vec<slint::SharedString> {
if self.layers.len() < 2 {
return Vec::new();
}
let mut names = vec![slint::SharedString::from("Auto")];
names.extend(self.layers.iter().map(|l| layer_name(l).into()));
names
}
}
/// "720p · 2.4 Mbit/s", or the scale when the size is not fixed.
fn layer_name(layer: &LayerSpec) -> String {
let size = match layer.size {
Some((_, h)) => format!("{h}p"),
None => format!("{:.0}%", layer.scale * 100.0),
};
format!("{size} · {:.1} Mbit/s", layer.bitrate as f64 / 1_000_000.0)
}
fn end_text(reason: &EndReason, streamer: &str) -> String {
@@ -272,13 +313,42 @@ impl App {
bridge.set_viewer_ended(watch.ended);
bridge.set_viewer_has_frame(watch.has_frame);
bridge.set_viewer_volume(self.stream_volume);
let info = watch.decoder.as_ref().map(Decoder::info).unwrap_or_default();
let info = [format!("by {}", watch.streamer), info]
let decoded = watch.decoder.as_ref().map(Decoder::info).unwrap_or_default();
let info = [format!("by {}", watch.streamer), decoded.clone()]
.into_iter()
.filter(|s| !s.is_empty())
.collect::<Vec<_>>()
.join(" · ");
bridge.set_viewer_info(info.into());
bridge.set_viewer_elapsed(watch.elapsed().into());
bridge.set_viewer_count(watch.viewers as i32);
let qualities = watch.qualities();
let chosen = watch
.layer
.and_then(|id| watch.layers.iter().position(|l| l.id == id))
.map_or(0, |i| i as i32 + 1);
crate::vm::list::sync(&self.models.qualities, &qualities);
if bridge.get_viewer_quality() != chosen {
bridge.set_viewer_quality(chosen);
}
bridge.set_viewer_quality_detail(decoded.into());
}
/// A simulcast layer of the watched stream (0: follow the bandwidth
/// estimate). The streamer picks the layer from each viewer's estimate,
/// so this asks for the picture again; a viewer-side choice needs an
/// engine API that does not exist yet.
pub(crate) fn set_stream_quality(&mut self, index: i32) {
let Some(watch) = &mut self.watch else { return };
watch.layer =
usize::try_from(index - 1).ok().and_then(|i| watch.layers.get(i)).map(|l| l.id);
if let Some(session) = watch.session {
self.engine.send(Command::RequestStreamKeyframe {
session: session as u64,
stream_id: watch.stream_id.clone(),
});
}
self.refresh_viewer();
}
/// Once a second: statistics, a capture that ended, decoder problems.
@@ -524,11 +594,28 @@ impl App {
has_frame: false,
shown: true,
decoder: Some(decoder),
since: None,
layers: Vec::new(),
layer: None,
viewers: 0,
});
self.refresh_viewer();
self.refresh_streams();
}
/// `VOELIN_OPEN=watch`: watch the first stream of our channel.
pub(crate) fn watch_first_stream(&mut self) {
let Some(id) = self.view().and_then(|v| {
v.streams
.iter()
.find(|s| v.state.own_client != Some(s.streamer.0))
.map(|s| s.id.clone())
}) else {
return;
};
self.watch_stream(id);
}
/// The local test stream in the viewer (`VOELIN_DEMO_STREAM`).
pub(crate) fn start_demo(&mut self) {
self.leave_stream();
@@ -543,6 +630,10 @@ impl App {
has_frame: false,
shown: true,
decoder: None,
since: None,
layers: Vec::new(),
layer: None,
viewers: 0,
});
let runtime = self.engine.runtime().clone();
let wake = || later(|app| app.show_picture());
@@ -570,6 +661,7 @@ impl App {
watch.has_frame = true;
if first {
watch.status.clear();
watch.since = Some(std::time::Instant::now());
}
if let Some(ui) = self.ui.upgrade() {
let bridge = ui.global::<Bridge>();
+6
View File
@@ -24,6 +24,12 @@ pub fn initials(name: &str) -> String {
letters.to_uppercase()
}
/// A picture from the engine's cache (an avatar, a group icon), decoded
/// once; an empty image when there is none.
pub fn image(path: Option<&std::path::PathBuf>) -> slint::Image {
path.map(|p| crate::images::file(p)).unwrap_or_default()
}
/// A stable colour for a name (FNV-1a).
pub fn tint(name: &str) -> Color {
let mut hash: u32 = 0x811c_9dc5;
+184 -19
View File
@@ -1,11 +1,13 @@
//! Chat lines.
//! Chat lines: one [`ChatLine`] per message, with its reactions and the
//! files it links.
use std::rc::Rc;
use slint::{ModelRc, VecModel};
use voelin_model::ChatMessage;
use slint::{Image, ModelRc, VecModel};
use voelin_core::HistoryMessage;
use voelin_model::{ChatMessage, FileRef};
use crate::app::{ChatLine, TextRun};
use crate::app::{ChatLine, FileItem, ReactionItem, TextRun};
use crate::emoji;
use crate::vm::avatar;
@@ -30,50 +32,169 @@ impl Previous {
}
}
/// What a line needs besides the message itself.
#[derive(Default)]
pub struct LineCtx {
/// The message's handle in its chat.
pub key: i32,
/// The author's avatar picture.
pub avatar: Image,
/// The gateway takes reactions and pins for this chat.
pub gateway: bool,
/// Highlighted (jumped to from the pins).
pub marked: bool,
/// The topic the message belongs to, when it should be shown.
pub topic: String,
/// The state of the downloads started from this message, by link index.
pub downloads: Vec<(usize, FileItem)>,
}
fn time_of(ts_ms: i64) -> String {
chrono::DateTime::from_timestamp_millis(ts_ms)
.map(|t| t.with_timezone(&chrono::Local).format("%H:%M").to_string())
.unwrap_or_default()
}
/// The line of a message; `previous` is the line before it in the chat.
/// "2.4 MB", "912 kB", "48 B".
pub fn size_text(bytes: u64) -> String {
const UNITS: [(u64, &str); 3] = [(1 << 30, "GB"), (1 << 20, "MB"), (1 << 10, "kB")];
for (unit, name) in UNITS {
if bytes >= unit {
return format!("{:.1} {name}", bytes as f64 / unit as f64);
}
}
format!("{bytes} B")
}
/// The text without the file links that became cards.
fn without_links(text: &str, files: &[FileRef]) -> String {
let mut out = text.to_owned();
for file in files {
for pattern in [
format!("[URL={}]{}[/URL]", file.url, file.name),
format!("[URL={}]", file.url),
format!("[url={}]", file.url),
file.url.clone(),
] {
out = out.replace(&pattern, "");
}
}
out.replace("[/URL]", "").replace("[/url]", "").trim().to_owned()
}
fn runs_model(runs: &[emoji::Run]) -> ModelRc<TextRun> {
ModelRc::from(Rc::new(VecModel::from(
runs.iter()
.map(|r| TextRun {
text: r.text.clone().into(),
emoji: r.emoji.clone().unwrap_or_default().into(),
})
.collect::<Vec<_>>(),
)))
}
/// The line of a stored message; `previous` is the line before it.
pub fn history_line(
message: &HistoryMessage,
previous: Option<&Previous>,
ctx: &LineCtx,
) -> ChatLine {
let files = message.message.file_refs();
let mut line = line_of(&message.message, previous, ctx, &files);
line.pinned = message.pinned;
line.remote = ctx.gateway && message.remote_id.is_some();
line.reactions = ModelRc::from(Rc::new(VecModel::from(
message
.reactions
.iter()
.map(|r| ReactionItem {
key: emoji::first_key(&r.emoji).unwrap_or_default().into(),
text: r.emoji.clone().into(),
count: r.count as i32,
me: r.me,
})
.collect::<Vec<_>>(),
)));
line
}
/// The line of a message the engine keeps no history for (no ids, no
/// reactions).
pub fn line(message: &ChatMessage, previous: Option<&Previous>) -> ChatLine {
let files = message.file_refs();
line_of(message, previous, &LineCtx::default(), &files)
}
fn line_of(
message: &ChatMessage,
previous: Option<&Previous>,
ctx: &LineCtx,
files: &[FileRef],
) -> ChatLine {
let continued = previous.is_some_and(|p| {
p.author == message.author_name
&& p.relayed == message.via_relay
&& (0..GROUP_MS).contains(&(message.ts_ms - p.ts_ms))
});
let runs = emoji::runs(&message.text);
let text =
if files.is_empty() { message.text.clone() } else { without_links(&message.text, files) };
let runs = emoji::runs(&text);
let jumbo = runs.as_deref().is_some_and(emoji::is_jumbo);
let runs_model = match &runs {
Some(runs) => ModelRc::from(Rc::new(VecModel::from(
runs.iter()
.map(|r| TextRun {
text: r.text.clone().into(),
emoji: r.emoji.clone().unwrap_or_default().into(),
})
.collect::<Vec<_>>(),
))),
None => ModelRc::default(),
};
let cards: Vec<FileItem> = files
.iter()
.enumerate()
.map(|(i, f)| {
let mut item = FileItem {
name: f.name.clone().into(),
detail: f.size.map(size_text).unwrap_or_default().into(),
index: i as i32,
picture: is_picture(&f.name),
..Default::default()
};
// A download of this link shows its progress instead of the size.
if let Some((_, running)) = ctx.downloads.iter().find(|(index, _)| *index == i) {
item.detail = running.detail.clone();
item.state = running.state.clone();
item.progress = running.progress;
}
item
})
.collect();
ChatLine {
key: ctx.key,
author: message.author_name.clone().into(),
text: message.text.clone().into(),
text: text.clone().into(),
time: time_of(message.ts_ms).into(),
relayed: message.via_relay,
runs: runs_model,
runs: runs.as_deref().map(runs_model).unwrap_or_default(),
rich: runs.is_some(),
jumbo,
continued,
initials: avatar::initials(&message.author_name).into(),
tint: avatar::tint(&message.author_name),
avatar: ctx.avatar.clone(),
blocked: message.blocked,
pinned: false,
reactions: ModelRc::default(),
files: ModelRc::from(Rc::new(VecModel::from(cards))),
remote: false,
topic: ctx.topic.clone().into(),
marked: ctx.marked,
}
}
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))
}
#[cfg(test)]
mod tests {
use slint::Model;
use voelin_core::HistoryMessage;
use voelin_gateway_proto::ReactionCount;
use voelin_model::ChatTarget;
use voelin_store::MessageSource;
use super::*;
@@ -90,6 +211,19 @@ mod tests {
}
}
fn stored(message: ChatMessage) -> HistoryMessage {
HistoryMessage {
id: 1,
message,
source: MessageSource::Voice,
remote_id: Some(7),
topic_id: None,
reactions: vec![ReactionCount { emoji: "🎉".into(), count: 2, me: true }],
pinned: true,
rev: 1,
}
}
#[test]
fn grouping() {
let first = message("Alice", "hi", 1_000_000);
@@ -112,4 +246,35 @@ mod tests {
assert_eq!(rich.runs.row_data(1).unwrap().emoji, "1f389");
assert!(line(&message("A", "🎉", 0), None).jumbo);
}
#[test]
fn reactions_and_pins() {
let ctx = LineCtx { key: 4, gateway: true, ..Default::default() };
let line = history_line(&stored(message("A", "hi", 0)), None, &ctx);
assert!(line.pinned && line.remote && line.key == 4);
assert_eq!(line.reactions.row_count(), 1);
let r = line.reactions.row_data(0).unwrap();
assert_eq!((r.key.as_str(), r.count, r.me), ("1f389", 2, true));
// Without a gateway nothing can be pinned or reacted to.
let plain = history_line(&stored(message("A", "hi", 0)), None, &LineCtx::default());
assert!(!plain.remote);
}
#[test]
fn file_cards_leave_the_text() {
let url = "ts3file://plan.pdf?channel=2&path=/&filename=plan.pdf&isDir=0&size=2048";
let text = format!("here you go [URL={url}]plan.pdf[/URL] 🎉");
let line = line(&message("A", &text, 0), None);
assert_eq!(line.files.row_count(), 1);
let file = line.files.row_data(0).unwrap();
assert_eq!((file.name.as_str(), file.detail.as_str()), ("plan.pdf", "2.0 kB"));
assert!(!line.text.contains("ts3file"), "{}", line.text);
assert!(line.text.starts_with("here you go"));
}
#[test]
fn sizes() {
assert_eq!(size_text(48), "48 B");
assert_eq!(size_text(2 << 20), "2.0 MB");
}
}
+119 -22
View File
@@ -1,8 +1,9 @@
//! The channel tree and the members of our channel.
use std::collections::HashSet;
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use voelin_model::{ChannelId, ClientInfo, Presence, TreeRow, tree_rows};
use voelin_model::{ChannelId, ClientInfo, GroupInfo, Presence, TreeRow, tree_rows};
use crate::app::{MemberItem, TreeItem};
use crate::settings::ClientPlaybackMap;
@@ -19,6 +20,42 @@ pub struct TreeInput<'a> {
/// Search text: only matching channels and clients (and the channels
/// above them) are shown. Empty: everything.
pub filter: &'a str,
/// Avatar pictures in the engine's cache, by unique id.
pub avatars: &'a HashMap<String, PathBuf>,
/// Icons in the engine's cache, by icon id (group icons).
pub icons: &'a HashMap<u32, PathBuf>,
/// The server groups in display order; members are grouped by the
/// first one each client is in.
pub groups: &'a [GroupInfo],
}
impl TreeInput<'_> {
fn avatar(&self, client: &ClientInfo) -> slint::Image {
avatar::image(client.uid.as_ref().and_then(|uid| self.avatars.get(uid)))
}
/// The group a client is sorted under: the first of its server groups
/// in display order.
fn group_of(&self, client: &ClientInfo) -> Option<&GroupInfo> {
self.groups.iter().find(|g| client.server_groups.contains(&g.id))
}
}
/// "Speaking", "Away: brb", "Muted", …
pub fn status_of(client: &ClientInfo, talking: bool) -> String {
if talking {
"Speaking".to_owned()
} else if client.streaming == Some(true) {
"Streaming".to_owned()
} else if let Some(message) = &client.away {
if message.is_empty() { "Away".to_owned() } else { format!("Away: {message}") }
} else if client.output_muted {
"Sound off".to_owned()
} else if client.input_muted {
"Muted".to_owned()
} else {
"Listening".to_owned()
}
}
fn talking(input: &TreeInput, client: &ClientInfo) -> bool {
@@ -66,6 +103,7 @@ pub fn rows(input: &TreeInput) -> Vec<TreeItem> {
myself: input.own_client == Some(client.id),
initials: avatar::initials(&client.nickname).into(),
tint: avatar::tint(&client.nickname),
avatar: input.avatar(client),
..Default::default()
}
}
@@ -105,40 +143,59 @@ pub fn stats(p: &Presence) -> String {
format!("{online} online · {channels} {}", if channels == 1 { "channel" } else { "channels" })
}
/// The clients in our channel, for the members panel, by name.
/// Names of server groups whose members wear the crown (the server's
/// admins). TeamSpeak has no flag for it, so the usual names are matched.
fn is_admin_group(name: &str) -> bool {
let lower = name.to_lowercase();
["admin", "owner", "operator", "moderator", "leiter"].iter().any(|w| lower.contains(w))
}
/// The clients in our channel, grouped by server group (in the server's
/// display order) and by name inside a group.
pub fn members(input: &TreeInput) -> Vec<MemberItem> {
let Some(channel) = input.own_channel else { return Vec::new() };
let mut clients: Vec<&ClientInfo> = input.presence.members(channel).collect();
clients.sort_by_key(|c| c.nickname.to_lowercase());
clients.sort_by_key(|c| {
let group = input.group_of(c);
(
group.map_or(i32::MAX, |g| g.sort_id),
group.map_or(String::new(), |g| g.name.clone()),
c.nickname.to_lowercase(),
)
});
let mut previous: Option<String> = None;
clients
.into_iter()
.map(|c| {
let talking = talking(input, c);
let status = if talking {
"Speaking".to_owned()
} else if c.streaming == Some(true) {
"Streaming".to_owned()
} else if let Some(message) = &c.away {
if message.is_empty() { "Away".to_owned() } else { format!("Away: {message}") }
} else if c.output_muted {
"Sound off".to_owned()
} else if c.input_muted {
"Muted".to_owned()
} else {
"Listening".to_owned()
};
let group = input.group_of(c);
let name = group.map(|g| g.name.clone()).unwrap_or_default();
let first = previous.as_deref() != Some(name.as_str());
previous = Some(name.clone());
MemberItem {
id: c.id as i32,
name: c.nickname.clone().into(),
initials: avatar::initials(&c.nickname).into(),
tint: avatar::tint(&c.nickname),
avatar: input.avatar(c),
talking,
muted: c.input_muted,
sound_off: c.output_muted,
away: c.away.is_some(),
streaming: c.streaming == Some(true),
myself: input.own_client == Some(c.id),
status: status.into(),
status: status_of(c, talking).into(),
away_message: c.away.clone().unwrap_or_default().into(),
group: name.into(),
group_icon: avatar::image(
group.map(|g| g.icon).filter(|i| *i != 0).and_then(|i| input.icons.get(&i)),
),
first_in_group: first,
admin: group.is_some_and(|g| is_admin_group(&g.name)),
priority: c.priority_speaker,
commander: c.channel_commander,
recording: c.recording,
talk_power: c.talk_power,
}
})
.collect()
@@ -178,12 +235,21 @@ mod tests {
p
}
/// Empty caches and no groups, for the tests below.
#[derive(Default)]
struct Extras {
avatars: HashMap<String, PathBuf>,
icons: HashMap<u32, PathBuf>,
groups: Vec<GroupInfo>,
}
fn input<'a>(
p: &'a Presence,
talking: &'a HashSet<u16>,
collapsed: &'a HashSet<ChannelId>,
playback: &'a ClientPlaybackMap,
filter: &'a str,
extras: &'a Extras,
) -> TreeInput<'a> {
TreeInput {
presence: p,
@@ -193,6 +259,9 @@ mod tests {
own_channel: Some(2),
own_client: Some(11),
filter,
avatars: &extras.avatars,
icons: &extras.icons,
groups: &extras.groups,
}
}
@@ -200,7 +269,8 @@ mod tests {
fn tree_rows_and_counts() {
let p = presence();
let (t, c, pb) = (HashSet::from([11]), HashSet::new(), ClientPlaybackMap::new());
let rows = rows(&input(&p, &t, &c, &pb, ""));
let e = Extras::default();
let rows = rows(&input(&p, &t, &c, &pb, "", &e));
let names: Vec<_> = rows.iter().map(|r| r.name.as_str()).collect();
assert_eq!(names, ["Lobby", "Alice", "Games", "bob", "Chess", "Carol"]);
assert_eq!((rows[0].members, rows[0].max_members), (1, -1));
@@ -214,10 +284,11 @@ mod tests {
fn search_keeps_parents() {
let p = presence();
let (t, c, pb) = (HashSet::new(), HashSet::new(), ClientPlaybackMap::new());
let rows = rows(&input(&p, &t, &c, &pb, "car"));
let e = Extras::default();
let rows = rows(&input(&p, &t, &c, &pb, "car", &e));
let names: Vec<_> = rows.iter().map(|r| r.name.as_str()).collect();
assert_eq!(names, ["Games", "Chess", "Carol"]);
let rows = super::rows(&input(&p, &t, &c, &pb, "LOBBY"));
let rows = super::rows(&input(&p, &t, &c, &pb, "LOBBY", &e));
assert_eq!(rows.len(), 1);
}
@@ -227,8 +298,34 @@ mod tests {
p.clients.get_mut(&12).unwrap().channel = 2;
p.clients.get_mut(&12).unwrap().away = Some(String::new());
let (t, c, pb) = (HashSet::new(), HashSet::new(), ClientPlaybackMap::new());
let members = members(&input(&p, &t, &c, &pb, ""));
let e = Extras::default();
let members = members(&input(&p, &t, &c, &pb, "", &e));
let names: Vec<_> = members.iter().map(|m| (m.name.as_str(), m.status.as_str())).collect();
assert_eq!(names, [("bob", "Listening"), ("Carol", "Away")]);
}
#[test]
fn members_are_grouped_by_server_group() {
let mut p = presence();
p.clients.get_mut(&12).unwrap().channel = 2;
p.clients.get_mut(&12).unwrap().server_groups = vec![6];
p.clients.get_mut(&11).unwrap().server_groups = vec![7];
let group = |id, sort_id, name: &str| GroupInfo {
id,
name: name.into(),
icon: 0,
sort_id,
..Default::default()
};
let e = Extras {
groups: vec![group(6, 10, "Server Admin"), group(7, 20, "Guest")],
..Default::default()
};
let (t, c, pb) = (HashSet::new(), HashSet::new(), ClientPlaybackMap::new());
let members = members(&input(&p, &t, &c, &pb, "", &e));
let rows: Vec<_> =
members.iter().map(|m| (m.name.as_str(), m.group.as_str(), m.first_in_group)).collect();
assert_eq!(rows, [("Carol", "Server Admin", true), ("bob", "Guest", true)]);
assert!(members[0].admin && !members[1].admin);
}
}
+55 -6
View File
@@ -19,6 +19,8 @@ import { MobileShell } from "shells/mobile.slint";
import { Panel } from "shells/common.slint";
import { ServerHeader, ConnectActions, ChannelTree } from "screens/channels.slint";
import { ChatView } from "screens/chat.slint";
import { PinsDrawer, TopicsDrawer, TopicDialog } from "screens/drawers.slint";
import { MemberCardPopup, VoiceGrid } from "screens/members.slint";
import { StreamsPanel, StreamViewer } from "screens/streams.slint";
import { SettingsNav, SettingsPage } from "screens/settings.slint";
import { HomeNav, HomePage } from "screens/home.slint";
@@ -34,7 +36,7 @@ export component MainWindow inherits Window {
title: Bridge.app-name;
preferred-width: 1280px;
preferred-height: 820px;
min-width: 360px;
min-width: 1600px;
min-height: 480px;
background: Theme.bg-app;
default-font-family: "Inter";
@@ -56,8 +58,8 @@ export component MainWindow inherits Window {
keyboard-inset = self.virtual-keyboard-size.height > 0 ? self.height - self.virtual-keyboard-position.y : 0;
}
// The viewer takes the whole window in full screen.
property <bool> chrome: !(Bridge.viewer-open && Bridge.viewer-fullscreen);
// The viewer takes the whole window in full screen and when popped out.
property <bool> chrome: !(Bridge.viewer-open && (Bridge.viewer-fullscreen || Bridge.viewer-popped));
// The standard widgets follow the theme. In "system" mode the palette
// is left alone (it tracks the system) unless an explicit mode was
@@ -80,6 +82,10 @@ export component MainWindow inherits Window {
property <string> status: Bridge.status-text;
changed status => { toast.shown = status != ""; }
// Dragging the members panel stores its width (`ui.members_width`).
property <length> panel-width: Nav.right-panel-width;
changed panel-width => { Bridge.panel-resized(panel-width / 1px); }
// Compatibility with callers from before the navigation global.
public function open-share-dialog() {
Nav.open-share();
@@ -123,7 +129,23 @@ export component MainWindow inherits Window {
if Nav.page == Page.server: Panel {
horizontal-stretch: 1;
if Bridge.viewer-open: StreamViewer { }
if !Bridge.viewer-open: ChatView { }
if !Bridge.viewer-open && Nav.voice-grid && Bridge.voice-connected: VoiceGrid { }
if !Bridge.viewer-open && !(Nav.voice-grid && Bridge.voice-connected): ChatView { }
// The pins and the topics slide in over the chat.
if !Bridge.viewer-open && (Nav.pins-open || Nav.topics-open): Rectangle {
x: parent.width - self.width - 12px;
y: 12px;
width: min(parent.width - 24px, 400px);
height: parent.height - 24px;
if Nav.pins-open: PinsDrawer {
width: parent.width;
height: parent.height;
}
if Nav.topics-open: TopicsDrawer {
width: parent.width;
height: parent.height;
}
}
}
if Nav.page == Page.server && Nav.right-panel-open: ResizeHandle {
size <=> Nav.right-panel-width;
@@ -177,6 +199,17 @@ export component MainWindow inherits Window {
text: Bridge.status-text;
}
// The member card of the members panel, over everything.
if Bridge.member-card.open: Rectangle {
TouchArea {
clicked => { Bridge.open-member(-1); }
}
MemberCardPopup {
x: max(8px, parent.width - self.width - (Nav.narrow ? 8px : Nav.right-panel-open && Nav.page == Page.server ? Nav.right-panel-width + 24px : 32px));
y: max(8px, min(parent.height - self.height - 8px, 120px));
}
}
if Nav.emoji-open: Rectangle {
// Clicks outside the picker close it.
TouchArea {
@@ -185,11 +218,27 @@ export component MainWindow inherits Window {
EmojiPicker {
x: max(8px, parent.width - self.width - (Nav.narrow ? 8px : Nav.right-panel-open && Nav.page == Page.server ? Nav.right-panel-width + 40px : 32px));
y: max(8px, parent.height - self.height - (Nav.narrow ? 150px : 90px));
picked(cell) => { Nav.draft = Nav.draft + cell.text; }
close => { Nav.emoji-open = false; }
// Picked for a message: a reaction; otherwise the composer.
picked(cell) => {
if Nav.react-key != 0 {
Bridge.react(Nav.react-key, cell.text);
Nav.react-key = 0;
Nav.emoji-open = false;
} else {
Nav.draft = Nav.draft + cell.text;
}
}
close => {
Nav.react-key = 0;
Nav.emoji-open = false;
}
}
}
if Nav.topic-form-open: TopicDialog {
done => { Nav.topic-form-open = false; }
}
if Nav.bookmark-open: BookmarkDialog {
form <=> Nav.bookmark-form;
done => { Nav.bookmark-open = false; }
+157 -1
View File
@@ -39,17 +39,20 @@ export struct TreeItem {
// Avatar of a client.
initials: string,
tint: color,
// The client's avatar picture, empty without one.
avatar: image,
// Channels: clients inside, and the limit (-1: none).
members: int,
max-members: int,
}
// A client in our channel, for the members panel.
// A client in our channel, for the members panel and the voice grid.
export struct MemberItem {
id: int,
name: string,
initials: string,
tint: color,
avatar: image,
talking: bool,
muted: bool,
sound-off: bool,
@@ -58,6 +61,44 @@ export struct MemberItem {
myself: bool,
// "Speaking", "Streaming", "Away", ...
status: string,
// The away message, empty without one.
away-message: string,
// The server group the row is sorted under, and its icon.
group: string,
group-icon: image,
// The first row of its group draws the group header.
first-in-group: bool,
// Badges: a crown for the server's admin groups.
admin: bool,
priority: bool,
commander: bool,
recording: bool,
// `client_talk_power`; shown when the channel needs it.
talk-power: int,
}
// The member card over a member row: everything about one client and what
// can be done with them.
export struct MemberCard {
open: bool,
id: int,
name: string,
initials: string,
tint: color,
avatar: image,
status: string,
description: string,
// Server groups, one per line.
groups: [string],
country: string,
talk-power: int,
friend: bool,
blocked: bool,
// Local playback, in percent.
volume: float,
muted: bool,
// The client has a unique id, so contacts and private chats work.
known: bool,
}
export struct ChatTab {
@@ -80,7 +121,35 @@ export struct TextRun {
emoji: string,
}
// One emoji under a message, with how many put it there.
export struct ReactionItem {
// The Twemoji key of the first emoji in `text` ("1f389"), for the image.
key: string,
text: string,
count: int,
// We reacted with it.
me: bool,
}
// A file linked in a message (`ChatMessage::file_refs`).
export struct FileItem {
name: string,
// "2.4 MB", or what the transfer is doing.
detail: string,
// Index of the link in the message (what `download-file` takes).
index: int,
// "", "running", "done", "failed"
state: string,
// 0 … 1 while it downloads.
progress: float,
// A picture, so the icon differs.
picture: bool,
}
export struct ChatLine {
// A handle for this message in its chat, stable while the chat is open
// (the engine's ids do not fit a Slint int).
key: int,
author: string,
text: string,
time: string,
@@ -94,6 +163,36 @@ export struct ChatLine {
continued: bool,
initials: string,
tint: color,
avatar: image,
// From a blocked contact.
blocked: bool,
pinned: bool,
reactions: [ReactionItem],
files: [FileItem],
// The gateway knows this message: it can be pinned, reacted to and
// made into a topic.
remote: bool,
// The topic it belongs to, "" outside a topic.
topic: string,
// Highlighted after jumping to it from the pins.
marked: bool,
}
// A pinned message in the pins drawer.
export struct PinItem {
line: ChatLine,
// "pinned by Nova · 12:04"
by: string,
}
// A gateway topic (thread).
export struct TopicItem {
id: int,
title: string,
creator: string,
// "12 messages · 3 min ago"
detail: string,
archived: bool,
}
export struct BookmarkForm {
@@ -199,6 +298,26 @@ export global Bridge {
in property <[ChatTab]> tabs;
in-out property <int> current-tab: 0;
in property <[ChatLine]> messages;
// Older messages can still be loaded in the current chat.
in property <bool> more-history;
in property <bool> loading-history;
// The current chat holds only what this device saw (no gateway sync).
in property <bool> local-history;
// Features of the session's gateway: hide what is missing.
in property <bool> has-pins;
in property <bool> has-reactions;
in property <bool> has-topics;
// The pins drawer.
in property <[PinItem]> pins;
in property <bool> pins-loading;
// The topics drawer, and the open topic.
in property <[TopicItem]> topics;
in property <bool> topics-loading;
in-out property <int> current-topic: -1;
in property <string> topic-title;
in property <[ChatLine]> topic-messages;
// The member card over the members panel.
in-out property <MemberCard> member-card;
in property <string> status-text;
// Unread messages in all chats of the current server.
in property <int> unread-total;
@@ -242,6 +361,16 @@ export global Bridge {
in property <bool> viewer-ended;
in-out property <float> viewer-volume: 100;
in property <bool> viewer-fullscreen;
// The viewer fills the window without the shell ("pop out").
in-out property <bool> viewer-popped;
// "12:34" since the stream was joined.
in property <string> viewer-elapsed;
in property <int> viewer-count;
// Simulcast layers the streamer offers, "Auto" first.
in property <[string]> viewer-qualities;
in-out property <int> viewer-quality: 0;
// What "Auto" picked ("720p · 2.4 Mbit/s").
in property <string> viewer-quality-detail;
// Settings.
in property <[string]> input-devices;
@@ -284,6 +413,27 @@ export global Bridge {
callback select-tab(int);
callback close-tab(int);
callback send-message(string);
// The page before the oldest shown message.
callback load-older();
// A message of the current chat, by its `key`.
callback react(int, string);
callback pin(int, bool);
callback download-file(int, int);
// Attach a file to the current channel chat (opens a file chooser).
callback attach-file();
// Pins drawer.
callback open-pins();
callback jump-to-pin(int);
// Topics drawer: load them, open one (-1 closes), post into the open
// one, start one from a message (by its `key`).
callback open-topics();
callback open-topic(int);
callback send-topic-message(string);
callback create-topic(int, string);
// The member card: open it for a client (-1 closes it).
callback open-member(int);
callback member-action(string);
callback member-volume(float);
callback set-input-muted(bool);
callback set-output-muted(bool);
callback push-to-talk(bool);
@@ -302,6 +452,8 @@ export global Bridge {
callback leave-stream();
callback set-stream-volume(float);
callback toggle-fullscreen();
// A simulcast layer of the watched stream (0: Auto).
callback set-stream-quality(int);
callback open-settings();
callback close-settings();
@@ -311,6 +463,8 @@ export global Bridge {
callback set-h264(bool);
callback download-h264();
callback appearance-changed(AppearanceForm);
// The members panel was dragged to another width (pixels).
callback panel-resized(float);
callback open-client(int) -> bool;
callback client-audio-changed(ClientAudio);
callback set-crash-reports(bool);
@@ -326,6 +480,8 @@ export global Bridge {
export global Images {
// A Twemoji by key ("1f600", "1f468-200d-1f4bb"); empty if unknown.
pure callback emoji(string) -> image;
// The characters of a Twemoji key, to react with or to insert.
pure callback emoji-text(string) -> string;
}
// One emoji of the picker. `text` is what picking it inserts.
+35
View File
@@ -42,6 +42,17 @@ export global Nav {
in-out property <length> right-panel-width: 280px;
// Incremented to focus the search field (Ctrl+K).
in-out property <int> search-requests;
// The voice channel's grid instead of the chat.
in-out property <bool> voice-grid: false;
// Drawers over the chat (gateway features).
in-out property <bool> pins-open;
in-out property <bool> topics-open;
// The message the emoji picker reacts to; 0: it fills the composer.
in-out property <int> react-key;
// "Start a topic" asks for a title first.
in-out property <bool> topic-form-open;
in-out property <int> topic-form-key;
in-out property <string> topic-form-title;
// Dialogs.
in-out property <bool> about-open;
@@ -104,6 +115,30 @@ export global Nav {
}
}
// The pins and the topics share the drawer, so opening one closes the
// other.
public function show-pins(on: bool) {
pins-open = on;
if on {
topics-open = false;
Bridge.open-pins();
}
}
public function show-topics(on: bool) {
topics-open = on;
if on {
pins-open = false;
Bridge.open-topics();
}
}
public function start-topic(key: int) {
topic-form-key = key;
topic-form-title = "";
topic-form-open = true;
}
public function select-server(id: int) {
show(Page.server);
Bridge.select-server(id);
+528 -66
View File
@@ -1,11 +1,12 @@
// The chat: header, chat tabs, messages (virtualised), the composer with
// the emoji picker.
// The chat: header, chat tabs, the compact voice bar, messages
// (virtualised) with reactions, pins and file cards, and the composer with
// the emoji picker and the file attachment.
import { Theme } from "../theme.slint";
import { Icons } from "../icons.slint";
import { Bridge, ChatLine } from "../bridge.slint";
import { Bridge, ChatLine, ReactionItem, FileItem, Images } from "../bridge.slint";
import { Nav } from "../nav.slint";
import { Icon, IconButton, Avatar, Chip, TabItem, TextField, RichText, Banner, Button, ButtonKind, ListView } from "../components/index.slint";
import { Icon, IconButton, Avatar, Chip, TabItem, TextField, RichText, Banner, Button, ButtonKind, Spinner, Tooltip, SpeakingBars, ListView } from "../components/index.slint";
// The header of the main area: an icon, a title and a description, and
// actions (@children) at the right.
@@ -57,14 +58,309 @@ export component PageHeader inherits Rectangle {
}
}
// The voice connection as one strip: where we are, who talks, and the
// controls. Shown over the chat while voice is connected.
export component VoiceBar inherits Rectangle {
height: 46px;
background: Theme.surface-2.transparentize(0.25);
accessible-role: AccessibleRole.groupbox;
accessible-label: @tr("Voice");
Rectangle {
y: parent.height - 1px;
height: 1px;
background: Theme.border;
}
HorizontalLayout {
padding-left: Theme.space-5;
padding-right: Theme.space-3;
spacing: Theme.space-3;
Rectangle {
width: 8px;
height: 8px;
y: (parent.height - self.height) / 2;
border-radius: 4px;
background: Bridge.voice-connected ? Theme.success : Theme.warning;
}
VerticalLayout {
alignment: center;
Text {
text: Bridge.voice-connected ? @tr("Voice connected") : @tr("Connecting…");
color: Bridge.voice-connected ? Theme.success : Theme.warning;
font-size: Theme.font-xs;
font-weight: Theme.weight-semibold;
}
Text {
text: Bridge.own-channel != "" ? Bridge.own-channel + " / " + Bridge.server-title : Bridge.server-title;
color: Theme.text-muted;
font-size: Theme.font-xs;
overflow: elide;
}
}
// Who is talking right now.
Rectangle {
horizontal-stretch: 1;
HorizontalLayout {
alignment: start;
padding-left: Theme.space-3;
spacing: -6px;
for member in Bridge.members: Rectangle {
width: member.talking ? 28px : 0px;
visible: member.talking;
Avatar {
size: 26px;
initials: member.initials;
tint: member.tint;
image: member.avatar;
speaking: true;
label: member.name;
}
}
}
}
if Bridge.transmitting: VerticalLayout {
alignment: center;
SpeakingBars { }
}
IconButton {
icon: Bridge.input-muted ? Icons.mic-off : Icons.mic;
label: Bridge.input-muted ? @tr("Microphone off") : @tr("Microphone on");
checked: Bridge.input-muted;
danger: true;
size: 32px;
icon-size: Theme.icon-sm;
y: (parent.height - self.height) / 2;
clicked => { Bridge.set-input-muted(!Bridge.input-muted); }
}
IconButton {
icon: Bridge.output-muted ? Icons.headphone-off : Icons.headphones;
label: Bridge.output-muted ? @tr("Sound off") : @tr("Sound on");
checked: Bridge.output-muted;
danger: true;
size: 32px;
icon-size: Theme.icon-sm;
y: (parent.height - self.height) / 2;
clicked => { Bridge.set-output-muted(!Bridge.output-muted); }
}
if Bridge.streams-available && Bridge.can-share: IconButton {
icon: Icons.monitor-up;
label: Bridge.share-state == "live" ? @tr("Sharing") : @tr("Share screen");
checked: Bridge.share-state == "live";
size: 32px;
icon-size: Theme.icon-sm;
y: (parent.height - self.height) / 2;
clicked => { Nav.open-share(); }
}
IconButton {
icon: Icons.layout-grid;
label: @tr("Voice channel");
checked: Nav.voice-grid;
size: 32px;
icon-size: Theme.icon-sm;
y: (parent.height - self.height) / 2;
clicked => { Nav.voice-grid = !Nav.voice-grid; }
}
IconButton {
icon: Icons.phone-off;
label: @tr("Disconnect");
size: 32px;
icon-size: Theme.icon-sm;
tint: Theme.danger;
y: (parent.height - self.height) / 2;
clicked => { Bridge.disconnect-voice(); }
}
}
}
// The emoji under a message; clicking one adds or removes ours.
component Reactions inherits HorizontalLayout {
in property <int> key;
in property <[ReactionItem]> model;
spacing: Theme.space-2;
alignment: start;
for reaction in root.model: Rectangle {
width: pill.preferred-width + 16px;
height: 24px;
border-radius: Theme.radius-pill;
background: reaction.me ? Theme.accent-soft : Theme.surface-2;
border-width: 1px;
border-color: reaction.me ? Theme.accent : Theme.border;
accessible-role: AccessibleRole.button;
accessible-label: @tr("{} reacted {} times", reaction.text, reaction.count);
accessible-checkable: true;
accessible-checked: reaction.me;
accessible-action-default => { Bridge.react(root.key, reaction.text); }
TouchArea {
mouse-cursor: MouseCursor.pointer;
clicked => { Bridge.react(root.key, reaction.text); }
}
pill := HorizontalLayout {
spacing: Theme.space-2;
alignment: center;
if reaction.key != "": Image {
width: 15px;
height: 15px;
source: Images.emoji(reaction.key);
y: (parent.height - self.height) / 2;
}
if reaction.key == "": Text {
text: reaction.text;
font-size: Theme.font-sm;
vertical-alignment: center;
}
Text {
text: reaction.count;
color: reaction.me ? Theme.accent-text : Theme.text-secondary;
font-size: Theme.font-xs;
font-weight: Theme.weight-semibold;
vertical-alignment: center;
}
}
}
}
// A file a message links: name, size or progress, and a download button.
component FileCard inherits Rectangle {
in property <int> key;
in property <FileItem> file;
height: 56px;
border-radius: Theme.radius-md;
background: Theme.surface-2;
border-width: 1px;
border-color: file.state == "failed" ? Theme.danger : Theme.border;
accessible-role: AccessibleRole.groupbox;
accessible-label: file.name;
HorizontalLayout {
padding: Theme.space-3;
spacing: Theme.space-3;
Rectangle {
width: 34px;
height: 34px;
y: (parent.height - self.height) / 2;
border-radius: Theme.radius-sm;
background: Theme.accent-soft;
Icon {
source: file.picture ? Icons.image : Icons.file-text;
size: Theme.icon-md;
tint: Theme.accent-text;
}
}
VerticalLayout {
alignment: center;
horizontal-stretch: 1;
spacing: 2px;
Text {
text: file.name;
color: Theme.text;
font-weight: Theme.weight-medium;
overflow: elide;
}
Text {
text: file.detail;
color: file.state == "failed" ? Theme.danger : Theme.text-muted;
font-size: Theme.font-xs;
overflow: elide;
}
if file.state == "running": Rectangle {
height: 3px;
border-radius: 1.5px;
background: Theme.surface-4;
Rectangle {
x: 0;
width: parent.width * file.progress;
height: parent.height;
border-radius: parent.border-radius;
background: Theme.accent;
}
}
}
if file.state != "running": IconButton {
icon: file.state == "done" ? Icons.folder-open : Icons.download;
label: file.state == "done" ? @tr("Downloaded") : @tr("Download {}", file.name);
y: (parent.height - self.height) / 2;
clicked => { Bridge.download-file(root.key, file.index); }
}
if file.state == "running": Spinner {
size: 18px;
y: (parent.height - self.height) / 2;
}
}
}
// Quick reactions, pin and "start a topic" on a hovered message.
component MessageActions inherits Rectangle {
in property <int> key;
in property <bool> pinned;
width: row.preferred-width;
height: 30px;
border-radius: Theme.radius-md;
background: Theme.surface-3;
border-width: 1px;
border-color: Theme.border-strong;
row := HorizontalLayout {
padding-left: 2px;
padding-right: 2px;
spacing: 0px;
if Bridge.has-reactions: HorizontalLayout {
spacing: 0px;
for quick in ["1f44d", "2764", "1f389", "1f602", "1f440"]: Rectangle {
width: 26px;
accessible-role: AccessibleRole.button;
accessible-label: @tr("React");
accessible-action-default => { Bridge.react(root.key, Images.emoji-text(quick)); }
Image {
width: 16px;
height: 16px;
source: Images.emoji(quick);
}
TouchArea {
mouse-cursor: MouseCursor.pointer;
clicked => { Bridge.react(root.key, Images.emoji-text(quick)); }
}
}
}
if Bridge.has-reactions: IconButton {
icon: Icons.smile-plus;
label: @tr("More emoji");
size: 26px;
icon-size: Theme.icon-sm;
clicked => {
Nav.react-key = root.key;
Nav.emoji-open = true;
}
}
if Bridge.has-pins: IconButton {
icon: Icons.pin;
label: root.pinned ? @tr("Unpin") : @tr("Pin");
checked: root.pinned;
size: 26px;
icon-size: Theme.icon-sm;
clicked => { Bridge.pin(root.key, !root.pinned); }
}
if Bridge.has-topics: IconButton {
icon: Icons.messages-square;
label: @tr("Start a topic");
size: 26px;
icon-size: Theme.icon-sm;
clicked => { Nav.start-topic(root.key); }
}
}
}
// One message; `continued` lines (same author just before) omit the header.
component MessageRow inherits Rectangle {
export component MessageRow inherits Rectangle {
in property <ChatLine> line;
// The pins and topic lists show messages without their actions.
in property <bool> actions: true;
property <length> avatar: 40px;
min-height: body.preferred-height;
background: line.marked ? Theme.accent-soft : hover.has-hover ? Theme.surface-2.transparentize(0.6) : transparent;
accessible-role: AccessibleRole.list-item;
accessible-label: line.author + ": " + line.text;
accessible-description: line.time;
hover := TouchArea {
// Let clicks through to the buttons inside.
mouse-cursor: MouseCursor.default;
}
body := HorizontalLayout {
padding-left: Theme.space-6;
padding-right: Theme.space-6;
@@ -78,6 +374,7 @@ component MessageRow inherits Rectangle {
size: root.avatar;
initials: line.initials;
tint: line.tint;
image: line.avatar;
label: line.author;
}
}
@@ -106,16 +403,181 @@ component MessageRow inherits Rectangle {
tint: Theme.accent-text;
y: (parent.height - self.height) / 2;
}
if line.pinned: Chip {
text: @tr("pinned");
icon: Icons.pin;
tint: Theme.warning;
y: (parent.height - self.height) / 2;
}
if line.topic != "": Chip {
text: line.topic;
icon: Icons.messages-square;
tint: Theme.accent-text;
y: (parent.height - self.height) / 2;
}
}
if !line.rich: Text {
if line.blocked: Text {
text: @tr("Message from a blocked contact.");
color: Theme.text-disabled;
font-size: Theme.font-sm;
font-italic: true;
}
if !line.blocked && !line.rich && line.text != "": Text {
text: line.text;
color: Theme.text;
wrap: word-wrap;
}
if line.rich: RichText {
if !line.blocked && line.rich: RichText {
runs: line.runs;
emoji-size: line.jumbo ? 44px : Theme.font-body * 1.4;
}
if line.files.length > 0 && !line.blocked: VerticalLayout {
padding-top: Theme.space-2;
padding-bottom: Theme.space-1;
spacing: Theme.space-2;
for file in line.files: FileCard {
key: line.key;
file: file;
max-width: 420px;
}
}
if line.reactions.length > 0: VerticalLayout {
padding-top: Theme.space-2;
padding-bottom: Theme.space-1;
Reactions {
key: line.key;
model: line.reactions;
}
}
}
}
if root.actions && line.remote && hover.has-hover: MessageActions {
x: parent.width - self.width - Theme.space-6;
y: -12px;
key: line.key;
pinned: line.pinned;
}
}
// The messages of the current chat (or of an open topic).
component MessageList inherits VerticalLayout {
in property <[ChatLine]> model;
in property <bool> older;
if Bridge.local-history: Rectangle {
height: 30px;
background: Theme.warning-soft;
HorizontalLayout {
padding-left: Theme.space-6;
spacing: Theme.space-2;
Icon {
source: Icons.hard-drive;
size: 14px;
tint: Theme.warning;
y: (parent.height - self.height) / 2;
}
Text {
text: @tr("Only messages seen by this device.");
color: Theme.warning;
font-size: Theme.font-xs;
vertical-alignment: center;
}
}
}
if root.older && Bridge.more-history: Rectangle {
height: 40px;
HorizontalLayout {
alignment: center;
Button {
small: true;
icon: Icons.chevron-up;
text: Bridge.loading-history ? @tr("Loading…") : @tr("Older messages");
enabled: !Bridge.loading-history;
y: (parent.height - self.height) / 2;
clicked => { Bridge.load-older(); }
}
}
}
ListView {
vertical-stretch: 1;
// A long chat must not make the window taller: the list scrolls.
preferred-height: 0px;
accessible-label: @tr("Messages");
for line in root.model: MessageRow {
line: line;
}
}
}
// The composer: emoji, attachment and the text field.
component Composer inherits HorizontalLayout {
in property <string> placeholder;
in property <bool> topic;
padding: Theme.space-4;
padding-left: Theme.space-5;
padding-right: Theme.space-5;
spacing: Theme.space-3;
Rectangle {
horizontal-stretch: 1;
min-height: 48px;
border-radius: Theme.radius-lg;
background: Theme.surface-2;
border-width: 1px;
border-color: input.has-focus ? Theme.accent : Theme.border;
HorizontalLayout {
padding-left: Theme.space-3;
padding-right: Theme.space-2;
spacing: Theme.space-2;
IconButton {
icon: Icons.paperclip;
label: @tr("Attach a file");
y: (parent.height - self.height) / 2;
clicked => { Bridge.attach-file(); }
}
input := TextField {
text <=> Nav.draft;
bare: true;
placeholder: root.placeholder;
label: @tr("Message");
accepted(text) => {
if text != "" {
if root.topic {
Bridge.send-topic-message(text);
} else {
Bridge.send-message(text);
}
self.clear();
}
}
}
IconButton {
icon: Icons.smile;
label: @tr("Emoji");
checked: Nav.emoji-open;
y: (parent.height - self.height) / 2;
clicked => {
Nav.react-key = 0;
Nav.emoji-open = !Nav.emoji-open;
}
}
IconButton {
icon: Icons.send;
label: @tr("Send");
round: true;
enabled: input.text != "";
tint: input.text != "" ? Theme.on-accent : Theme.text-muted;
filled: input.text != "";
y: (parent.height - self.height) / 2;
clicked => {
if input.text != "" {
if root.topic {
Bridge.send-topic-message(input.text);
} else {
Bridge.send-message(input.text);
}
input.clear();
}
}
}
}
}
}
@@ -139,7 +601,21 @@ export component ChatView inherits VerticalLayout {
tint: Theme.accent-text;
y: (parent.height - self.height) / 2;
}
if Bridge.viewer-open == false && Bridge.streams.length > 0: Button {
if Bridge.has-pins: IconButton {
icon: Icons.pin;
label: @tr("Pinned messages");
checked: Nav.pins-open;
y: (parent.height - self.height) / 2;
clicked => { Nav.show-pins(!Nav.pins-open); }
}
if Bridge.has-topics: IconButton {
icon: Icons.messages-square;
label: @tr("Topics");
checked: Nav.topics-open;
y: (parent.height - self.height) / 2;
clicked => { Nav.show-topics(!Nav.topics-open); }
}
if !Bridge.viewer-open && !Nav.right-panel-open && Bridge.streams.length > 0: Button {
small: true;
icon: Icons.monitor-up;
text: @tr("Streams ({})", Bridge.streams.length);
@@ -207,65 +683,51 @@ export component ChatView inherits VerticalLayout {
}
}
}
messages := ListView {
vertical-stretch: 1;
accessible-label: @tr("Messages");
for line in Bridge.messages: MessageRow {
line: line;
}
}
// Composer.
HorizontalLayout {
padding: Theme.space-4;
padding-left: Theme.space-5;
padding-right: Theme.space-5;
spacing: Theme.space-3;
composer := Rectangle {
horizontal-stretch: 1;
min-height: 48px;
border-radius: Theme.radius-lg;
background: Theme.surface-2;
border-width: 1px;
border-color: input.has-focus ? Theme.accent : Theme.border;
HorizontalLayout {
padding-left: Theme.space-5;
padding-right: Theme.space-2;
spacing: Theme.space-2;
input := TextField {
text <=> Nav.draft;
bare: true;
placeholder: root.tab-title != "" ? @tr("Message {}", root.tab-title) : @tr("Message");
label: @tr("Message");
accepted(text) => {
if text != "" {
Bridge.send-message(text);
self.clear();
}
}
}
IconButton {
icon: Icons.smile;
label: @tr("Emoji");
checked: Nav.emoji-open;
y: (parent.height - self.height) / 2;
clicked => { Nav.emoji-open = !Nav.emoji-open; }
}
IconButton {
icon: Icons.send;
label: @tr("Send");
round: true;
enabled: input.text != "";
tint: input.text != "" ? Theme.on-accent : Theme.text-muted;
filled: input.text != "";
y: (parent.height - self.height) / 2;
clicked => {
if input.text != "" {
Bridge.send-message(input.text);
input.clear();
}
}
}
if Bridge.voice-connected || Bridge.voice-connecting: VoiceBar { }
// The open topic replaces the chat.
if Bridge.current-topic >= 0: Rectangle {
height: 44px;
background: Theme.surface-2.transparentize(0.4);
HorizontalLayout {
padding-left: Theme.space-4;
padding-right: Theme.space-4;
spacing: Theme.space-3;
IconButton {
icon: Icons.arrow-left;
label: @tr("Back to the chat");
size: 28px;
icon-size: Theme.icon-sm;
y: (parent.height - self.height) / 2;
clicked => { Bridge.open-topic(-1); }
}
Icon {
source: Icons.messages-square;
size: Theme.icon-sm;
tint: Theme.accent-text;
y: (parent.height - self.height) / 2;
}
Text {
text: Bridge.topic-title;
color: Theme.text;
font-weight: Theme.weight-semibold;
vertical-alignment: center;
horizontal-stretch: 1;
overflow: elide;
}
}
}
if Bridge.current-topic >= 0: MessageList {
vertical-stretch: 1;
model: Bridge.topic-messages;
}
if Bridge.current-topic < 0: MessageList {
vertical-stretch: 1;
model: Bridge.messages;
older: true;
}
Composer {
topic: Bridge.current-topic >= 0;
placeholder: Bridge.current-topic >= 0 ? @tr("Reply in {}", Bridge.topic-title)
: root.tab-title != "" ? @tr("Message {}", root.tab-title) : @tr("Message");
}
}
+290
View File
@@ -0,0 +1,290 @@
// Drawers that slide over the chat: the pinned messages and the topics
// (threads). Both need a gateway; the chat header hides their buttons when
// the gateway does not offer them.
import { Theme } from "../theme.slint";
import { Icons } from "../icons.slint";
import { Bridge, TopicItem } from "../bridge.slint";
import { Nav } from "../nav.slint";
import { Icon, IconButton, Button, ButtonKind, TextField, Spinner, Modal, ListView } from "../components/index.slint";
import { MessageRow } from "chat.slint";
// The frame both drawers share: a title bar and the content (@children).
component Drawer inherits Rectangle {
in property <string> title;
in property <image> icon;
in property <int> count;
callback closed();
background: Theme.surface;
border-width: 1px;
border-color: Theme.border-strong;
border-radius: Theme.radius-lg;
clip: true;
accessible-role: AccessibleRole.groupbox;
accessible-label: title;
VerticalLayout {
Rectangle {
height: 52px;
background: Theme.surface-2;
Rectangle {
y: parent.height - 1px;
height: 1px;
background: Theme.border;
}
HorizontalLayout {
padding-left: Theme.space-5;
padding-right: Theme.space-3;
spacing: Theme.space-3;
Icon {
source: root.icon;
size: Theme.icon-md;
tint: Theme.accent-text;
y: (parent.height - self.height) / 2;
}
Text {
text: root.count > 0 ? root.title + " — " + root.count : root.title;
color: Theme.text;
font-size: Theme.font-md;
font-weight: Theme.weight-semibold;
vertical-alignment: center;
horizontal-stretch: 1;
overflow: elide;
}
IconButton {
icon: Icons.x;
label: @tr("Close");
size: 28px;
icon-size: Theme.icon-sm;
y: (parent.height - self.height) / 2;
clicked => { root.closed(); }
}
}
}
@children
}
}
// The pinned messages of the current chat: jump to one or unpin it.
export component PinsDrawer inherits Drawer {
title: @tr("Pinned");
icon: Icons.pin;
count: Bridge.pins.length;
closed => { Nav.pins-open = false; }
if Bridge.pins-loading: HorizontalLayout {
padding: Theme.space-6;
alignment: center;
Spinner { size: 20px; }
}
if !Bridge.pins-loading && Bridge.pins.length == 0: VerticalLayout {
padding: Theme.space-6;
spacing: Theme.space-2;
Text {
text: @tr("Nothing pinned yet.");
color: Theme.text-secondary;
font-weight: Theme.weight-medium;
horizontal-alignment: center;
}
Text {
text: @tr("Hover a message and press the pin.");
color: Theme.text-muted;
font-size: Theme.font-sm;
horizontal-alignment: center;
wrap: word-wrap;
}
}
ListView {
vertical-stretch: 1;
accessible-label: @tr("Pinned messages");
for pin in Bridge.pins: Rectangle {
min-height: entry.preferred-height;
entry := VerticalLayout {
padding-bottom: Theme.space-3;
MessageRow {
line: pin.line;
actions: false;
}
HorizontalLayout {
padding-left: 78px;
padding-right: Theme.space-5;
spacing: Theme.space-2;
Text {
text: pin.by;
color: Theme.text-muted;
font-size: Theme.font-xs;
vertical-alignment: center;
horizontal-stretch: 1;
overflow: elide;
}
Button {
small: true;
icon: Icons.arrow-right;
text: @tr("Jump");
clicked => {
Bridge.jump-to-pin(pin.line.key);
Nav.pins-open = false;
}
}
Button {
small: true;
kind: ButtonKind.danger;
icon: Icons.pin;
text: @tr("Unpin");
clicked => { Bridge.pin(pin.line.key, false); }
}
}
Rectangle {
height: 1px;
background: Theme.border;
}
}
}
}
}
component TopicRow inherits Rectangle {
in property <TopicItem> topic;
height: 62px;
border-radius: Theme.radius-md;
background: Bridge.current-topic == topic.id ? Theme.accent-soft : area.has-hover ? Theme.surface-3 : transparent;
accessible-role: AccessibleRole.list-item;
accessible-label: topic.title;
accessible-description: topic.detail;
accessible-action-default => { Bridge.open-topic(topic.id); }
area := TouchArea {
mouse-cursor: MouseCursor.pointer;
clicked => {
Bridge.open-topic(topic.id);
Nav.topics-open = false;
}
}
HorizontalLayout {
padding-left: Theme.space-3;
padding-right: Theme.space-3;
spacing: Theme.space-3;
Rectangle {
width: 34px;
height: 34px;
y: (parent.height - self.height) / 2;
border-radius: Theme.radius-sm;
background: Theme.surface-3;
Icon {
source: topic.archived ? Icons.bookmark : Icons.messages-square;
size: Theme.icon-sm;
tint: topic.archived ? Theme.text-muted : Theme.accent-text;
}
}
VerticalLayout {
alignment: center;
horizontal-stretch: 1;
spacing: 2px;
Text {
text: topic.title;
color: Theme.text;
font-weight: Theme.weight-medium;
overflow: elide;
}
Text {
text: topic.detail;
color: Theme.text-muted;
font-size: Theme.font-xs;
overflow: elide;
}
}
Icon {
source: Icons.chevron-right;
size: Theme.icon-sm;
tint: Theme.text-muted;
y: (parent.height - self.height) / 2;
}
}
}
// The topics (threads) of the current chat.
export component TopicsDrawer inherits Drawer {
title: @tr("Topics");
icon: Icons.messages-square;
count: Bridge.topics.length;
closed => { Nav.topics-open = false; }
if Bridge.topics-loading: HorizontalLayout {
padding: Theme.space-6;
alignment: center;
Spinner { size: 20px; }
}
if !Bridge.topics-loading && Bridge.topics.length == 0: VerticalLayout {
padding: Theme.space-6;
spacing: Theme.space-2;
Text {
text: @tr("No topics yet.");
color: Theme.text-secondary;
font-weight: Theme.weight-medium;
horizontal-alignment: center;
}
Text {
text: @tr("Start one from a message, or below.");
color: Theme.text-muted;
font-size: Theme.font-sm;
horizontal-alignment: center;
wrap: word-wrap;
}
}
ListView {
vertical-stretch: 1;
accessible-label: @tr("Topics");
for topic in Bridge.topics: TopicRow {
topic: topic;
}
}
HorizontalLayout {
padding: Theme.space-3;
Button {
horizontal-stretch: 1;
icon: Icons.plus;
text: @tr("New topic");
clicked => { Nav.start-topic(-1); }
}
}
}
// Asking for a topic's title (from a message, or standalone).
export component TopicDialog inherits Modal {
title: @tr("Start a topic");
subtitle: Nav.topic-form-key > 0 ? @tr("From the chosen message.") : @tr("A new thread in this chat.");
icon: Icons.messages-square;
card-width: 460px;
card-height: 260px;
callback done();
dismissed => { root.done(); }
VerticalLayout {
spacing: Theme.space-4;
field := TextField {
text <=> Nav.topic-form-title;
placeholder: @tr("What is it about?");
label: @tr("Title");
accepted(text) => {
if text != "" {
Bridge.create-topic(Nav.topic-form-key, text);
root.done();
}
}
}
Rectangle { vertical-stretch: 1; }
HorizontalLayout {
spacing: Theme.space-3;
alignment: end;
Button {
text: @tr("Cancel");
clicked => { root.done(); }
}
Button {
kind: ButtonKind.primary;
icon: Icons.check;
text: @tr("Create");
enabled: field.text != "";
clicked => {
Bridge.create-topic(Nav.topic-form-key, field.text);
root.done();
}
}
}
}
}
+577
View File
@@ -0,0 +1,577 @@
// The members panel: who is in our voice channel, grouped by server group,
// with a card for one person; and the voice channel as a grid of tiles.
import { Theme } from "../theme.slint";
import { Icons } from "../icons.slint";
import { Bridge, MemberItem } from "../bridge.slint";
import { Nav } from "../nav.slint";
import { Icon, IconButton, Button, ButtonKind, Avatar, Status, LiveBadge, Chip, Divider, Slider, SpeakingBars, Tooltip, ListView } from "../components/index.slint";
// Crown, priority speaker, channel commander, recording.
component MemberBadges inherits HorizontalLayout {
in property <MemberItem> member;
in property <length> size: 14px;
spacing: 3px;
if member.admin: Icon {
source: Icons.crown;
size: root.size;
tint: Theme.gold;
accessible-role: AccessibleRole.image;
accessible-label: @tr("server admin");
}
if member.priority: Icon {
source: Icons.star;
size: root.size;
tint: Theme.accent-text;
accessible-role: AccessibleRole.image;
accessible-label: @tr("priority speaker");
}
if member.commander: Icon {
source: Icons.flag;
size: root.size;
tint: Theme.info;
accessible-role: AccessibleRole.image;
accessible-label: @tr("channel commander");
}
if member.recording: Icon {
source: Icons.record;
size: root.size;
tint: Theme.danger;
accessible-role: AccessibleRole.image;
accessible-label: @tr("recording");
}
}
// The header above the first member of a server group.
export component GroupHeader inherits HorizontalLayout {
in property <MemberItem> member;
padding-top: Theme.space-4;
padding-bottom: Theme.space-1;
padding-left: Theme.space-2;
spacing: Theme.space-2;
if member.group-icon.width > 0: Image {
width: 14px;
height: 14px;
source: member.group-icon;
y: (parent.height - self.height) / 2;
}
if member.group-icon.width == 0: Icon {
source: member.admin ? Icons.shield-check : Icons.users;
size: 13px;
tint: Theme.text-muted;
y: (parent.height - self.height) / 2;
}
Text {
text: member.group != "" ? member.group : @tr("Others");
color: Theme.text-muted;
font-size: Theme.font-xs;
font-weight: Theme.weight-semibold;
letter-spacing: 0.4px;
vertical-alignment: center;
horizontal-stretch: 1;
overflow: elide;
}
}
// One person in the panel.
export component MemberRow inherits Rectangle {
in property <MemberItem> member;
height: 48px * Theme.font-scale;
border-radius: Theme.radius-md;
background: Bridge.member-card.open && Bridge.member-card.id == member.id ? Theme.accent-soft
: area.has-hover ? Theme.surface-3 : transparent;
accessible-role: AccessibleRole.list-item;
accessible-label: member.name;
accessible-description: member.status;
accessible-action-default => { Bridge.open-member(member.id); }
area := TouchArea {
mouse-cursor: MouseCursor.pointer;
clicked => { Bridge.open-member(member.id); }
}
HorizontalLayout {
padding-left: Theme.space-2;
padding-right: Theme.space-2;
spacing: Theme.space-3;
VerticalLayout {
alignment: center;
Avatar {
size: 34px;
initials: member.initials;
tint: member.tint;
image: member.avatar;
speaking: member.talking;
crown: member.admin;
status: member.away ? Status.idle : member.sound-off ? Status.dnd : Status.online;
label: member.name;
}
}
VerticalLayout {
alignment: center;
horizontal-stretch: 1;
HorizontalLayout {
spacing: Theme.space-2;
Text {
text: member.name;
color: member.myself ? Theme.accent-text : Theme.name-text;
font-weight: Theme.weight-medium;
overflow: elide;
}
MemberBadges {
member: member;
y: (parent.height - self.height) / 2;
}
if member.streaming: VerticalLayout {
alignment: center;
LiveBadge { }
}
}
HorizontalLayout {
spacing: Theme.space-2;
Text {
text: member.status;
color: member.talking ? Theme.success : Theme.text-muted;
font-size: Theme.font-sm;
overflow: elide;
}
if member.talking: SpeakingBars {
width: 12px;
height: 12px;
y: (parent.height - self.height) / 2;
}
}
}
if member.talk-power > 0: Text {
text: member.talk-power;
color: Theme.text-muted;
font-size: Theme.font-xs;
vertical-alignment: center;
accessible-label: @tr("talk power");
}
if member.muted: Icon {
source: Icons.mic-off;
size: 16px;
tint: Theme.danger;
y: (parent.height - self.height) / 2;
}
if member.sound-off: Icon {
source: Icons.headphone-off;
size: 16px;
tint: Theme.danger;
y: (parent.height - self.height) / 2;
}
}
}
// Everything about one person, over the panel.
export component MemberCardPopup inherits Rectangle {
property <length> card-width: 300px;
width: root.card-width;
height: card.preferred-height;
background: Theme.surface-3;
border-radius: Theme.radius-lg;
border-width: 1px;
border-color: Theme.border-strong;
accessible-role: AccessibleRole.groupbox;
accessible-label: Bridge.member-card.name;
// Clicks inside stay inside.
TouchArea { }
card := VerticalLayout {
padding: Theme.space-4;
spacing: Theme.space-3;
HorizontalLayout {
spacing: Theme.space-3;
Avatar {
size: 52px;
initials: Bridge.member-card.initials;
tint: Bridge.member-card.tint;
image: Bridge.member-card.avatar;
label: Bridge.member-card.name;
}
VerticalLayout {
alignment: center;
horizontal-stretch: 1;
spacing: 2px;
Text {
text: Bridge.member-card.name;
color: Theme.text;
font-size: Theme.font-lg;
font-weight: Theme.weight-semibold;
overflow: elide;
}
Text {
text: Bridge.member-card.status;
color: Theme.text-muted;
font-size: Theme.font-sm;
overflow: elide;
}
}
IconButton {
icon: Icons.x;
label: @tr("Close");
size: 26px;
icon-size: Theme.icon-sm;
clicked => { Bridge.open-member(-1); }
}
}
if Bridge.member-card.description != "": Text {
text: Bridge.member-card.description;
color: Theme.text-secondary;
font-size: Theme.font-sm;
wrap: word-wrap;
}
if Bridge.member-card.groups.length > 0: VerticalLayout {
spacing: Theme.space-2;
Text {
text: @tr("Groups");
color: Theme.text-muted;
font-size: Theme.font-xs;
font-weight: Theme.weight-semibold;
}
for group in Bridge.member-card.groups: Text {
text: group;
color: Theme.text-secondary;
font-size: Theme.font-sm;
overflow: elide;
}
}
HorizontalLayout {
spacing: Theme.space-2;
alignment: start;
if Bridge.member-card.talk-power > 0: Chip {
text: @tr("talk power {}", Bridge.member-card.talk-power);
icon: Icons.mic;
}
if Bridge.member-card.country != "": Chip {
text: Bridge.member-card.country;
icon: Icons.globe;
}
}
Divider { }
// Local playback of this person.
VerticalLayout {
spacing: Theme.space-2;
HorizontalLayout {
spacing: Theme.space-2;
Text {
text: @tr("Volume");
color: Theme.text-secondary;
font-size: Theme.font-sm;
vertical-alignment: center;
horizontal-stretch: 1;
}
Text {
text: @tr("{}%", round(Bridge.member-card.volume));
color: Theme.text-muted;
font-size: Theme.font-xs;
vertical-alignment: center;
}
}
HorizontalLayout {
spacing: Theme.space-2;
IconButton {
icon: Bridge.member-card.muted ? Icons.volume-x : Icons.volume-2;
label: Bridge.member-card.muted ? @tr("Unmute for me") : @tr("Mute for me");
checked: Bridge.member-card.muted;
danger: true;
size: 30px;
icon-size: Theme.icon-sm;
enabled: Bridge.member-card.known;
clicked => { Bridge.member-action("mute"); }
}
Slider {
horizontal-stretch: 1;
minimum: 0;
maximum: 200;
step: 5;
value: Bridge.member-card.volume;
enabled: Bridge.member-card.known && !Bridge.member-card.muted;
label: @tr("Volume of {}", Bridge.member-card.name);
changed(v) => { Bridge.member-volume(v); }
}
}
}
Divider { }
HorizontalLayout {
spacing: Theme.space-2;
Button {
horizontal-stretch: 1;
small: true;
icon: Icons.message-square;
text: @tr("Message");
enabled: Bridge.member-card.known;
clicked => { Bridge.member-action("message"); }
}
Button {
horizontal-stretch: 1;
small: true;
icon: Icons.hand;
text: @tr("Poke");
clicked => { Bridge.member-action("poke"); }
}
}
HorizontalLayout {
spacing: Theme.space-2;
Button {
horizontal-stretch: 1;
small: true;
icon: Icons.user-plus;
text: Bridge.member-card.friend ? @tr("Friend") : @tr("Add friend");
checked: Bridge.member-card.friend;
enabled: Bridge.member-card.known;
clicked => { Bridge.member-action("friend"); }
}
Button {
horizontal-stretch: 1;
small: true;
kind: Bridge.member-card.blocked ? ButtonKind.danger : ButtonKind.secondary;
icon: Icons.shield;
text: Bridge.member-card.blocked ? @tr("Blocked") : @tr("Block");
enabled: Bridge.member-card.known;
clicked => { Bridge.member-action("blocked"); }
}
}
}
}
// The members of our channel, grouped by server group.
export component MembersList inherits VerticalLayout {
if Bridge.members.length == 0: Text {
text: @tr("Join a channel with voice to see who is there.");
color: Theme.text-muted;
font-size: Theme.font-sm;
wrap: word-wrap;
}
ListView {
vertical-stretch: 1;
accessible-role: AccessibleRole.list;
accessible-label: @tr("Members");
for member in Bridge.members: VerticalLayout {
if member.first-in-group: GroupHeader {
member: member;
}
MemberRow {
member: member;
}
}
}
}
// One person as a tile of the voice grid.
component VoiceTile inherits Rectangle {
in property <MemberItem> member;
border-radius: Theme.radius-lg;
background: Theme.surface-2;
border-width: member.talking ? 2px : 1px;
border-color: member.talking ? Theme.success : Theme.border;
accessible-role: AccessibleRole.list-item;
accessible-label: member.name;
accessible-description: member.status;
accessible-action-default => { Bridge.open-member(member.id); }
TouchArea {
mouse-cursor: MouseCursor.pointer;
clicked => { Bridge.open-member(member.id); }
}
VerticalLayout {
padding: Theme.space-4;
spacing: Theme.space-3;
alignment: center;
HorizontalLayout {
alignment: center;
Avatar {
size: 64px;
initials: member.initials;
tint: member.tint;
image: member.avatar;
speaking: member.talking;
crown: member.admin;
label: member.name;
}
}
HorizontalLayout {
alignment: center;
spacing: Theme.space-2;
Text {
text: member.name;
color: member.myself ? Theme.accent-text : Theme.text;
font-weight: Theme.weight-semibold;
overflow: elide;
}
MemberBadges {
member: member;
y: (parent.height - self.height) / 2;
}
}
HorizontalLayout {
alignment: center;
spacing: Theme.space-2;
if member.muted: Icon {
source: Icons.mic-off;
size: 15px;
tint: Theme.danger;
}
if member.sound-off: Icon {
source: Icons.headphone-off;
size: 15px;
tint: Theme.danger;
}
if member.streaming: LiveBadge { }
if !member.muted && !member.sound-off && !member.streaming: Text {
text: member.status;
color: member.talking ? Theme.success : Theme.text-muted;
font-size: Theme.font-sm;
overflow: elide;
}
}
}
}
// A stream in the channel as a tile next to the people.
component StreamTile inherits Rectangle {
in property <string> name;
in property <string> streamer;
in property <string> id;
in property <bool> watching;
border-radius: Theme.radius-lg;
clip: true;
background: @linear-gradient(135deg, #2b1f6e 0%, #0f2a66 100%);
border-width: root.watching ? 2px : 1px;
border-color: root.watching ? Theme.accent : Theme.border;
accessible-role: AccessibleRole.groupbox;
accessible-label: root.name;
LiveBadge {
x: Theme.space-3;
y: Theme.space-3;
large: true;
}
VerticalLayout {
padding: Theme.space-4;
spacing: Theme.space-2;
alignment: center;
Icon {
source: Icons.monitor-up;
size: 34px;
tint: #ffffffd0;
}
Text {
text: root.name != "" ? root.name : @tr("Untitled stream");
color: #ffffff;
font-weight: Theme.weight-semibold;
horizontal-alignment: center;
overflow: elide;
}
Text {
text: @tr("by {}", root.streamer);
color: #ffffffb0;
font-size: Theme.font-sm;
horizontal-alignment: center;
overflow: elide;
}
if root.id != "": HorizontalLayout {
padding-top: Theme.space-2;
alignment: center;
Button {
small: true;
kind: root.watching ? ButtonKind.secondary : ButtonKind.primary;
icon: root.watching ? Icons.monitor : Icons.eye;
text: root.watching ? @tr("Show") : @tr("Watch");
clicked => {
if root.watching {
Bridge.show-viewer();
} else {
Bridge.watch-stream(root.id);
}
}
}
}
}
}
// The voice channel as tiles: the people in it and the streams there.
export component VoiceGrid inherits VerticalLayout {
// How many tiles fit; the grid wraps into rows of that many.
property <int> columns: max(1, min(4, floor((root.width - 32px) / 250px)));
property <int> total: Bridge.members.length + Bridge.streams.length;
property <int> rows: ceil(total / columns);
Rectangle {
height: 56px;
HorizontalLayout {
padding-left: Theme.space-6;
padding-right: Theme.space-4;
spacing: Theme.space-3;
Icon {
source: Icons.volume-2;
size: 22px;
tint: Theme.text-secondary;
y: (parent.height - self.height) / 2;
}
Text {
text: Bridge.own-channel != "" ? Bridge.own-channel : @tr("Voice");
color: Theme.text;
font-size: Theme.font-xl;
font-weight: Theme.weight-semibold;
vertical-alignment: center;
}
Text {
text: @tr("{} in voice", Bridge.members.length);
color: Theme.text-muted;
font-size: Theme.font-sm;
vertical-alignment: center;
horizontal-stretch: 1;
}
Button {
small: true;
icon: Icons.message-square;
text: @tr("Chat");
y: (parent.height - self.height) / 2;
clicked => { Nav.voice-grid = false; }
}
}
Rectangle {
y: parent.height - 1px;
height: 1px;
background: Theme.border;
}
}
if root.total == 0: VerticalLayout {
padding: Theme.space-8;
alignment: center;
Text {
text: @tr("Nobody is in this channel.");
color: Theme.text-muted;
horizontal-alignment: center;
}
}
ListView {
vertical-stretch: 1;
accessible-label: @tr("Voice channel");
for row in root.rows: HorizontalLayout {
padding: Theme.space-3;
padding-left: Theme.space-5;
padding-right: Theme.space-5;
spacing: Theme.space-4;
// One cell per column; the last row's empty cells stay blank.
for column in root.columns: Rectangle {
property <int> index: row * root.columns + column;
horizontal-stretch: 1;
// The cell sizes the tile, never the other way round.
min-width: 200px;
height: 176px;
if index < Bridge.members.length: VoiceTile {
width: parent.width;
height: parent.height;
member: Bridge.members[index];
}
if index >= Bridge.members.length && index < root.total: StreamTile {
width: parent.width;
height: parent.height;
name: Bridge.streams[index - Bridge.members.length].name;
streamer: Bridge.streams[index - Bridge.members.length].streamer;
id: Bridge.streams[index - Bridge.members.length].id;
watching: Bridge.streams[index - Bridge.members.length].watching;
}
}
}
}
}
+190 -105
View File
@@ -5,7 +5,9 @@ import { Theme } from "../theme.slint";
import { Icons } from "../icons.slint";
import { Bridge, StreamItem, MemberItem } from "../bridge.slint";
import { Nav } from "../nav.slint";
import { Icon, Button, ButtonKind, IconButton, Avatar, Status, LiveBadge, Chip, SectionHeader, SpeakingBars, Slider, Spinner, ListView, ScrollView } from "../components/index.slint";
import { Icon, Button, ButtonKind, IconButton, Avatar, Status, LiveBadge, Chip, Select, SectionHeader, SpeakingBars, Slider, Spinner, TextField, ListView, ScrollView } from "../components/index.slint";
import { MemberRow, GroupHeader } from "members.slint";
import { MessageRow } from "chat.slint";
// A stream card: the streamer, the title, watch / show / leave.
component StreamCard inherits Rectangle {
@@ -88,82 +90,6 @@ component StreamCard inherits Rectangle {
}
}
// A person in our channel.
component MemberRow inherits Rectangle {
in property <MemberItem> member;
height: 48px * Theme.font-scale;
border-radius: Theme.radius-md;
background: area.has-hover ? Theme.surface-3 : transparent;
accessible-role: AccessibleRole.list-item;
accessible-label: member.name;
accessible-description: member.status;
accessible-action-default => { Nav.open-client(member.id); }
area := TouchArea {
enabled: !member.myself;
mouse-cursor: MouseCursor.pointer;
clicked => { Nav.open-client(member.id); }
}
HorizontalLayout {
padding-left: Theme.space-2;
padding-right: Theme.space-2;
spacing: Theme.space-3;
VerticalLayout {
alignment: center;
Avatar {
size: 34px;
initials: member.initials;
tint: member.tint;
speaking: member.talking;
status: member.away ? Status.idle : member.sound-off ? Status.dnd : Status.online;
label: member.name;
}
}
VerticalLayout {
alignment: center;
horizontal-stretch: 1;
HorizontalLayout {
spacing: Theme.space-2;
Text {
text: member.name;
color: member.myself ? Theme.accent-text : Theme.name-text;
font-weight: Theme.weight-medium;
overflow: elide;
}
if member.streaming: VerticalLayout {
alignment: center;
LiveBadge { }
}
}
HorizontalLayout {
spacing: Theme.space-2;
Text {
text: member.status;
color: member.talking ? Theme.success : Theme.text-muted;
font-size: Theme.font-sm;
overflow: elide;
}
if member.talking: SpeakingBars {
width: 12px;
height: 12px;
y: (parent.height - self.height) / 2;
}
}
}
if member.muted: Icon {
source: Icons.mic-off;
size: 16px;
tint: Theme.danger;
y: (parent.height - self.height) / 2;
}
if member.sound-off: Icon {
source: Icons.headphone-off;
size: 16px;
tint: Theme.danger;
y: (parent.height - self.height) / 2;
}
}
}
// The right panel of a server: who is in our channel, the streams there,
// and requests to watch ours.
export component StreamsPanel inherits VerticalLayout {
@@ -199,8 +125,13 @@ export component StreamsPanel inherits VerticalLayout {
width: sv.visible-width;
spacing: Theme.space-2;
alignment: start;
for member in Bridge.members: MemberRow {
member: member;
for member in Bridge.members: VerticalLayout {
if member.first-in-group: GroupHeader {
member: member;
}
MemberRow {
member: member;
}
}
if Bridge.streams-available: VerticalLayout {
padding-top: Theme.space-4;
@@ -258,11 +189,9 @@ export component StreamsPanel inherits VerticalLayout {
}
}
// The stream we watch: title bar, picture, player controls.
export component StreamViewer inherits Rectangle {
// The player: title bar, picture and controls (no chat).
component StreamPlayer inherits Rectangle {
background: Theme.dark ? #03060f : #0b1330;
accessible-role: AccessibleRole.groupbox;
accessible-label: @tr("Stream viewer");
VerticalLayout {
// Title bar.
Rectangle {
@@ -302,9 +231,45 @@ export component StreamViewer inherits Rectangle {
overflow: elide;
}
}
if !Bridge.viewer-ended: VerticalLayout {
// How long we have been watching, and how many others do.
if !Bridge.viewer-ended: HorizontalLayout {
spacing: Theme.space-3;
alignment: center;
LiveBadge { large: true; }
if Bridge.viewer-elapsed != "": HorizontalLayout {
spacing: Theme.space-2;
Icon {
source: Icons.clock;
size: 14px;
tint: Theme.text-muted;
y: (parent.height - self.height) / 2;
}
Text {
text: Bridge.viewer-elapsed;
color: Theme.text-secondary;
font-size: Theme.font-sm;
vertical-alignment: center;
}
}
if Bridge.viewer-count > 0: HorizontalLayout {
spacing: Theme.space-2;
Icon {
source: Icons.eye;
size: 14px;
tint: Theme.text-muted;
y: (parent.height - self.height) / 2;
}
Text {
text: Bridge.viewer-count;
color: Theme.text-secondary;
font-size: Theme.font-sm;
vertical-alignment: center;
accessible-label: @tr("viewers");
}
}
VerticalLayout {
alignment: center;
LiveBadge { large: true; }
}
}
}
}
@@ -345,13 +310,16 @@ export component StreamViewer inherits Rectangle {
padding-left: Theme.space-4;
padding-right: Theme.space-4;
spacing: Theme.space-3;
Icon {
source: Bridge.viewer-volume > 0 ? Icons.volume-2 : Icons.volume-x;
tint: Theme.text-secondary;
IconButton {
icon: Bridge.viewer-volume > 0 ? Icons.volume-2 : Icons.volume-x;
label: Bridge.viewer-volume > 0 ? @tr("Mute") : @tr("Unmute");
size: 30px;
icon-size: Theme.icon-sm;
y: (parent.height - self.height) / 2;
clicked => { Bridge.set-stream-volume(Bridge.viewer-volume > 0 ? 0 : 100); }
}
Slider {
width: 140px;
width: 120px;
horizontal-stretch: 0;
y: (parent.height - self.height) / 2;
minimum: 0;
@@ -369,24 +337,33 @@ export component StreamViewer inherits Rectangle {
color: Theme.text-secondary;
font-size: Theme.font-sm;
}
if !Bridge.viewer-ended: HorizontalLayout {
spacing: Theme.space-2;
Rectangle {
width: 8px;
height: 8px;
y: (parent.height - self.height) / 2;
border-radius: 4px;
background: Theme.live;
}
Text {
text: @tr("LIVE");
color: Theme.text;
font-size: Theme.font-sm;
font-weight: Theme.weight-semibold;
vertical-alignment: center;
}
// Simulcast layers the streamer offers; "Auto" follows the
// bandwidth estimate.
if Bridge.viewer-qualities.length > 1: Select {
width: 150px;
horizontal-stretch: 0;
y: (parent.height - self.height) / 2;
icon: Icons.sliders-horizontal;
label: @tr("Quality");
model: Bridge.viewer-qualities;
current-index <=> Bridge.viewer-quality;
enabled: !Bridge.viewer-ended;
selected(_) => { Bridge.set-stream-quality(Bridge.viewer-quality); }
}
if Bridge.viewer-quality == 0 && Bridge.viewer-quality-detail != "": Text {
text: Bridge.viewer-quality-detail;
color: Theme.text-muted;
font-size: Theme.font-xs;
vertical-alignment: center;
}
Rectangle { horizontal-stretch: 1; }
IconButton {
icon: Icons.external-link;
label: Bridge.viewer-popped ? @tr("Back to the window") : @tr("Pop out");
checked: Bridge.viewer-popped;
y: (parent.height - self.height) / 2;
clicked => { Bridge.viewer-popped = !Bridge.viewer-popped; }
}
IconButton {
icon: Bridge.viewer-fullscreen ? Icons.minimize-2 : Icons.maximize;
label: Bridge.viewer-fullscreen ? @tr("Exit full screen") : @tr("Full screen");
@@ -413,3 +390,111 @@ export component StreamViewer inherits Rectangle {
}
}
}
// The chat beside the player: the current chat's messages and a composer.
component StreamChat inherits Rectangle {
background: Theme.surface;
Rectangle {
x: 0;
width: 1px;
background: Theme.border;
}
VerticalLayout {
Rectangle {
height: 44px;
HorizontalLayout {
padding-left: Theme.space-4;
padding-right: Theme.space-3;
spacing: Theme.space-2;
Icon {
source: Icons.message-square;
size: Theme.icon-sm;
tint: Theme.text-secondary;
y: (parent.height - self.height) / 2;
}
Text {
text: Bridge.current-tab >= 0 && Bridge.current-tab < Bridge.tabs.length ? Bridge.tabs[Bridge.current-tab].title : @tr("Chat");
color: Theme.text;
font-weight: Theme.weight-semibold;
vertical-alignment: center;
horizontal-stretch: 1;
overflow: elide;
}
}
Rectangle {
y: parent.height - 1px;
height: 1px;
background: Theme.border;
}
}
ListView {
vertical-stretch: 1;
accessible-label: @tr("Messages");
for line in Bridge.messages: MessageRow {
line: line;
actions: false;
}
}
HorizontalLayout {
padding: Theme.space-3;
Rectangle {
min-height: 40px;
border-radius: Theme.radius-lg;
background: Theme.surface-2;
border-width: 1px;
border-color: field.has-focus ? Theme.accent : Theme.border;
HorizontalLayout {
padding-left: Theme.space-4;
padding-right: Theme.space-2;
field := TextField {
text <=> Nav.draft;
bare: true;
placeholder: @tr("Message");
label: @tr("Message");
accepted(text) => {
if text != "" {
Bridge.send-message(text);
self.clear();
}
}
}
IconButton {
icon: Icons.send;
label: @tr("Send");
round: true;
enabled: field.text != "";
tint: field.text != "" ? Theme.on-accent : Theme.text-muted;
filled: field.text != "";
y: (parent.height - self.height) / 2;
clicked => {
if field.text != "" {
Bridge.send-message(field.text);
field.clear();
}
}
}
}
}
}
}
}
// The stream we watch: the player, with the chat beside it when there is
// room (and not in full screen).
export component StreamViewer inherits Rectangle {
background: Theme.dark ? #03060f : #0b1330;
// Reading our own width here would loop through the layout, so the
// phone breakpoint (a setting) decides.
property <bool> with-chat: !Bridge.viewer-fullscreen && !Nav.narrow;
accessible-role: AccessibleRole.groupbox;
accessible-label: @tr("Stream viewer");
HorizontalLayout {
StreamPlayer {
horizontal-stretch: 1;
}
if root.with-chat: StreamChat {
width: Nav.right-panel-width + 40px;
horizontal-stretch: 0;
}
}
}
+20
View File
@@ -0,0 +1,20 @@
#!/bin/sh
# Take a screenshot of the app with sample data, headless.
#
# scripts/shots.sh <out.png> <VOELIN_OPEN> [<width>x<height>]
#
# The pictures in docs/screenshots/ are made this way (and reduced to 256
# colours with `convert -colors 256 PNG8:`).
set -eu
out=$1
open=$2
size=${3:-1440x960}
bin=${VOELIN_BIN:-$CARGO_TARGET_DIR/debug/voelin}
SLINT_BACKEND=winit-software \
VOELIN_DATA_DIR=$(mktemp -d) \
VOELIN_DEMO_UI=1 \
VOELIN_OPEN="$open" \
VOELIN_WINDOW_SIZE="$size" \
VOELIN_SCREENSHOT="$out" \
VOELIN_SCREENSHOT_DELAY="${DELAY:-4}" \
xvfb-run -a -s "-screen 0 1920x1200x24" "$bin" >/dev/null 2>&1