diff --git a/Cargo.lock b/Cargo.lock index 1275bef..1be54d0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9299,6 +9299,7 @@ dependencies = [ "unicode-segmentation", "voelin-audio", "voelin-core", + "voelin-gateway-proto", "voelin-model", "voelin-platform", "voelin-query", diff --git a/crates/voelin-platform/Cargo.toml b/crates/voelin-platform/Cargo.toml index d55c6cc..7f8a538 100644 --- a/crates/voelin-platform/Cargo.toml +++ b/crates/voelin-platform/Cargo.toml @@ -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 } diff --git a/crates/voelin-platform/src/files.rs b/crates/voelin-platform/src/files.rs new file mode 100644 index 0000000..c28bf91 --- /dev/null +++ b/crates/voelin-platform/src/files.rs @@ -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> { + #[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> { + 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 { + 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 = 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); + } +} diff --git a/crates/voelin-platform/src/lib.rs b/crates/voelin-platform/src/lib.rs index aa406ff..47a62f0 100644 --- a/crates/voelin-platform/src/lib.rs +++ b/crates/voelin-platform/src/lib.rs @@ -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; diff --git a/crates/voelin-ui/Cargo.toml b/crates/voelin-ui/Cargo.toml index c10e18b..f56c220 100644 --- a/crates/voelin-ui/Cargo.toml +++ b/crates/voelin-ui/Cargo.toml @@ -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 } diff --git a/crates/voelin-ui/src/app.rs b/crates/voelin-ui/src/app.rs index 578b06d..7d2456b 100644 --- a/crates/voelin-ui/src/app.rs +++ b/crates/voelin-ui/src/app.rs @@ -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>, - /// The last message, for grouping the next one. + /// The messages, oldest first, by `(ts_ms, id)`. + pub messages: Vec, + /// Live messages of a session that keeps no history (no server unique + /// id yet): grouped from the message before, without ids. pub last: Option, 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, + pub pins_loaded: bool, + /// The gateway topics of this chat, and the open one with its messages. + pub topics: Vec, + pub topics_loaded: bool, + pub topic: Option, + pub topic_messages: Vec, + /// The message jumped to from the pins. + pub marked: Option, } 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, /// Clients whose stored volume was sent for this voice connection. pub applied_playback: HashSet, + /// Avatar pictures in the engine's cache, by unique id + /// ([`Event::AvatarReady`]). + pub avatars: HashMap, + /// Icons in the engine's cache, by icon id ([`Event::IconReady`]). + pub icons: HashMap, + /// The server groups in display order ([`Event::Groups`]). + pub server_groups: Vec, + /// What the session's gateway offers (`voelin_gateway_proto::feature`). + pub gateway_caps: Vec, + /// The client whose member card is open. + pub member_card: Option, + /// Downloads started from chat, by transfer id. + pub downloads: HashMap, + /// 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>, pub streams: Rc>, pub viewers: Rc>, + pub pins: Rc>, + pub topics: Rc>, + pub topic_messages: Rc>, + /// The quality choices of the watched stream. + pub qualities: Rc>, /// Shown when there is no chat. pub no_chat: Rc>, } @@ -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, /// The client in the volume dialog: session, client id, unique id. pub playback_dialog: Option<(i64, u16, Option)>, 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, } 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), diff --git a/crates/voelin-ui/src/appearance.rs b/crates/voelin-ui/src/appearance.rs index 8f82162..ca53583 100644 --- a/crates/voelin-ui/src/appearance.rs +++ b/crates/voelin-ui/src/appearance.rs @@ -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::(); t.set_mode(theme.as_str().into()); t.set_font_scale(scale); - ui.global::