From 424db6eee94a9c2cac0f37c701b9eade08786a1f Mon Sep 17 00:00:00 2001 From: selikhov Date: Tue, 29 Sep 2026 13:33:52 +0300 Subject: [PATCH 01/35] voelin-media: record the AVFrame offsets of libavutil 61 instead of guessing The DMA-BUF import reads AVFrame.buf[0] and hw_frames_ctx at offsets the loader keeps in a table per libavutil major. The table ended in an open range that answered every major from 60 up with 60's offsets, so on this machine (libavutil 61) the import ran on an unverified guess, and a future major would get the same treatment. Compiled offsetof from the headers installed next to the library: libavutil 61 puts buf at 184 and hw_frames_ctx at 328, which is what 60 uses, so the guess happened to hold. Record 61 explicitly and stop answering unknown majors: AVFrame has shrunk between majors (424 bytes in 61 against 536 in 56), so an offset guessed for an unknown layout can point past the end of the struct. An unlisted major now turns the import off with a reason and leaves everything else working. Co-Authored-By: Claude Opus 5 --- crates/voelin-media/src/ffmpeg/layout.rs | 63 +++++++++++++++++++++--- 1 file changed, 55 insertions(+), 8 deletions(-) diff --git a/crates/voelin-media/src/ffmpeg/layout.rs b/crates/voelin-media/src/ffmpeg/layout.rs index 3947825..9856eb5 100644 --- a/crates/voelin-media/src/ffmpeg/layout.rs +++ b/crates/voelin-media/src/ffmpeg/layout.rs @@ -13,11 +13,14 @@ //! | `AVFrame.pict_type`, `AVFrame.pts` | forcing a keyframe, timestamps | right after the leading fields: `key_frame` (removed in libavutil 60), `pict_type`, `sample_aspect_ratio`, `pts` | a fresh frame must read `pict_type` 0, `sample_aspect_ratio` {0, 1}, `pts` `AV_NOPTS_VALUE` in exactly one of the two layouts | //! | `AVCodecContext.hw_frames_ctx` | VA-API input frames | next to fields that have AVOptions, whose offsets `av_opt_find` reports: before `hw_device_ctx`, `hwaccel_flags` (libavcodec 61 and later, after `err_recognition`), or two fields before `max_pixels` (up to 60) | the neighbours' option offsets must match the layout, and the field must be NULL in a new context | //! | `AVHWFramesContext` `initial_pool_size`, `format`, `sw_format`, `width`, `height` | creating a frame pool | after seven pointers (eight up to libavutil 58: `internal`) | `device_ctx` must equal the device and both formats must be `AV_PIX_FMT_NONE` in a new context | -//! | `AVFrame.buf[0]`, `AVFrame.hw_frames_ctx` | importing DMA-BUFs (zero-copy) | a table per libavutil major (56-60, 64-bit only) | `buf[0]` of a frame from `av_frame_get_buffer` must hold that frame's `data[0]`; `hw_frames_ctx` of a frame from `av_hwframe_get_buffer` must reference the pool | +//! | `AVFrame.buf[0]`, `AVFrame.hw_frames_ctx` | importing DMA-BUFs (zero-copy) | a table per libavutil major (56-61, 64-bit only; an unlisted major disables the import) | `buf[0]` of a frame from `av_frame_get_buffer` must hold that frame's `data[0]`; `hw_frames_ctx` of a frame from `av_hwframe_get_buffer` must reference the pool | //! //! A check that fails disables only what needs the field (VA-API, or the -//! DMA-BUF import), with the reason in the probe results; a new major whose -//! layout matches keeps working without a change here. +//! DMA-BUF import), with the reason in the probe results. The first three +//! rows are found by searching, so a new major whose layout matches keeps +//! working without a change here; the last one is a table, because there is +//! nothing to anchor those offsets to, and an unlisted major turns the +//! DMA-BUF import off rather than guess (see [`frame_refs_table`]). #![allow(unsafe_code)] use std::ffi::c_int; @@ -324,8 +327,19 @@ pub struct FrameRefs { pub hw_frames_ctx: usize, } -/// The table of [`FrameRefs`] per libavutil major (64-bit targets). A newer -/// major is tried with the newest entry and must pass the checks. +/// The table of [`FrameRefs`] per libavutil major (64-bit targets). +/// +/// Every entry is `offsetof` compiled from that release's own +/// `libavutil/frame.h`; libavutil 61's was measured against the headers +/// installed next to the library it describes (FFmpeg 9.0.1: `buf` 184, +/// `hw_frames_ctx` 328, `sizeof(AVFrame)` 424). +/// +/// A major that is not listed returns `None`, which disables the DMA-BUF +/// import (and nothing else) with the reason in the probe results. It +/// deliberately does not fall back to the newest entry: `AVFrame` has both +/// grown and shrunk between majors (424 bytes in 61 against 536 in 56), so +/// an offset guessed for an unknown layout could read past the end of the +/// struct. Adding a major here needs its `offsetof` values, not a guess. fn frame_refs_table(avutil_major: u32) -> Option { if size_of::() != 8 { return None; @@ -334,7 +348,7 @@ fn frame_refs_table(avutil_major: u32) -> Option { 56 => (288, 480), 57 | 58 => (224, 392), 59 => (200, 352), - 60.. => (184, 328), + 60 | 61 => (184, 328), _ => return None, }; Some(FrameRefs { buf, hw_frames_ctx }) @@ -346,8 +360,12 @@ fn frame_refs_table(avutil_major: u32) -> Option { pub fn frame_refs(api: &Api, yuv420p: c_int) -> Result { // SAFETY: no arguments. let major = unsafe { (api.avutil_version)() } >> 16; - let refs = frame_refs_table(major) - .ok_or_else(|| format!("AVFrame references not known for libavutil {major} here"))?; + let refs = frame_refs_table(major).ok_or_else(|| { + format!( + "AVFrame.buf / hw_frames_ctx offsets are not recorded for libavutil {major} (see \ + frame_refs_table); the import stays off until they are measured" + ) + })?; // SAFETY: a frame of 16x16 yuv420p pixels; the head fields are set // before av_frame_get_buffer as its documentation asks; the offsets are // inside AVFrame for this major (the table), pointer-aligned. @@ -410,4 +428,33 @@ mod tests { assert_eq!(frame_refs_table(58), Some(FrameRefs { buf: 224, hw_frames_ctx: 392 })); assert_eq!(frame_refs_table(55), None); } + + /// libavutil 61 (FFmpeg 9), compiled from the installed headers on + /// x86-64: `AVFrame` `pict_type` 120, `pts` 136, `buf` 184, + /// `hw_frames_ctx` 328, `sizeof` 424; `AVCodecContext` + /// `err_recognition` 528, `hw_frames_ctx` 552, `hw_device_ctx` 560, + /// `hwaccel_flags` 568, `extra_hw_frames` 572; `AVHWFramesContext` + /// `pool` 48, `initial_pool_size` 56, `format` 60, `sw_format` 64, + /// `width` 68, `height` 72. + #[cfg(target_pointer_width = "64")] + #[test] + fn libavutil_61_matches_the_headers() { + assert_eq!(frame_refs_table(61), Some(FrameRefs { buf: 184, hw_frames_ctx: 328 })); + assert_eq!(offset_of!(FrameWithoutKeyFrame, pict_type), 120); + assert_eq!(offset_of!(FrameWithoutKeyFrame, pts), 136); + let base = 528; + assert_eq!(base + offset_of!(HwFieldsNew, hw_frames_ctx), 552); + assert_eq!(base + offset_of!(HwFieldsNew, hw_device_ctx), 560); + assert_eq!(base + offset_of!(HwFieldsNew, hwaccel_flags), 568); + assert_eq!(base + offset_of!(HwFieldsNew, extra_hw_frames), 572); + assert_eq!(offset_of!(HwFramesPublic, pool), 48); + assert_eq!(offset_of!(HwFramesPublic, initial_pool_size), 56); + assert_eq!(offset_of!(HwFramesPublic, sw_format), 64); + assert_eq!(offset_of!(HwFramesPublic, height), 72); + // A major nobody measured must disable the import, not reuse 61's + // offsets: AVFrame has shrunk between majors (424 bytes in 61 + // against 536 in 56), so reading at a guessed offset could leave + // the struct. + assert_eq!(frame_refs_table(62), None); + } } From dc5ce8a80072744f27194eb3db1abc48692e8967 Mon Sep 17 00:00:00 2001 From: selikhov Date: Tue, 29 Sep 2026 13:39:37 +0300 Subject: [PATCH 02/35] voelin-media: tell the H.264 encoders the level the offer advertises The signalling computes profile-level-id from the stream's size, frame rate and bitrate, but nothing told the encoder, so every wrapper picked its own level. Measured on this GPU: h264_amf writes level 4.2 into the SPS of a 720p30 stream whose offer says 3.1, and 5.0 for a 1440p60 stream offered as 5.1. A viewer that sizes its decoder from our SDP can refuse a stream that declares more than the offer did, which is what breaks official clients. Compute the level from ITU-T Table A-1 and set it on both the codec context and the wrapper's private option. A new test parses the SPS of every usable H.264 backend at two sizes and both profiles and asserts profile_idc against the offer and level_idc never above it; with the level set, all three backends now emit exactly the offered level. The level table is a second copy of the one in voelin-stream, because neither crate can depend on the other, so a unit test pins them together over a spread of sizes, rates, bitrates and profiles. Remaining difference, only in the constraint-flag byte and left alone: the offer claims Constrained High (0c) and Constrained Baseline (e0) as WebRTC implementations conventionally do; the VA-API and AMF encoders emit 0c for the former, libx264 emits 00, and all three emit 40 or c0 for the latter. The bits do not change what a decoder can decode. Co-Authored-By: Claude Opus 5 --- crates/voelin-media/Cargo.toml | 4 + crates/voelin-media/src/ffmpeg/encoder.rs | 107 ++++++++++++++++++++++ crates/voelin-media/tests/ffmpeg.rs | 103 ++++++++++++++++++++- 3 files changed, 212 insertions(+), 2 deletions(-) diff --git a/crates/voelin-media/Cargo.toml b/crates/voelin-media/Cargo.toml index 2d3fde2..59e1878 100644 --- a/crates/voelin-media/Cargo.toml +++ b/crates/voelin-media/Cargo.toml @@ -71,6 +71,10 @@ windows-capture = "2.0.1" [dev-dependencies] criterion = "0.8" +# The H.264 `profile-level-id` the signalling offers, to check it against the +# SPS the encoders really emit (`tests/ffmpeg.rs`). No cycle: voelin-stream +# does not depend on this crate. +voelin-stream = { path = "../voelin-stream" } # Logs of integration tests (`RUST_LOG`). tracing-subscriber = { version = "0.3", features = ["env-filter"] } tokio = { version = "1", features = ["macros", "rt", "rt-multi-thread", "time"] } diff --git a/crates/voelin-media/src/ffmpeg/encoder.rs b/crates/voelin-media/src/ffmpeg/encoder.rs index 53a3bfb..241d53e 100644 --- a/crates/voelin-media/src/ffmpeg/encoder.rs +++ b/crates/voelin-media/src/ffmpeg/encoder.rs @@ -189,6 +189,61 @@ const X264_PRESETS: [&str; 10] = [ const PROFILE_H264_HIGH: i64 = 100; const PROFILE_H264_CONSTRAINED_BASELINE: i64 = 66 | 1 << 9; +/// H.264 level limits (ITU-T H.264 Table A-1): `level_idc`, macroblocks per +/// second, macroblocks per frame, bitrate in kbit/s for Baseline (High +/// allows 1.25 times that). +const H264_LEVELS: [(i64, u64, u64, u64); 19] = [ + (10, 1_485, 99, 64), + (11, 3_000, 396, 192), + (12, 6_000, 396, 384), + (13, 11_880, 396, 768), + (20, 11_880, 396, 2_000), + (21, 19_800, 792, 4_000), + (22, 20_250, 1_620, 4_000), + (30, 40_500, 1_620, 10_000), + (31, 108_000, 3_600, 14_000), + (32, 216_000, 5_120, 20_000), + (40, 245_760, 8_192, 20_000), + (41, 245_760, 8_192, 50_000), + (42, 522_240, 8_704, 50_000), + (50, 589_824, 22_080, 135_000), + (51, 983_040, 36_864, 240_000), + (52, 2_073_600, 36_864, 240_000), + (60, 4_177_920, 139_264, 240_000), + (61, 8_355_840, 139_264, 480_000), + (62, 16_711_680, 139_264, 800_000), +]; + +/// The lowest `level_idc` whose limits hold this stream, or the highest +/// level defined if none does. +/// +/// The signalling offers the same level to the viewer +/// (`voelin_stream::h264::level_idc`, which this mirrors — a test pins the +/// two together). It has to be told to the encoder, because wrappers that +/// pick a level themselves pick a generous one: AMF writes level 4.2 into +/// the SPS of a 720p30 stream whose offer says 3.1, and a decoder set up +/// from that offer may refuse it. +fn h264_level(profile: H264Profile, width: u32, height: u32, fps: u32, bitrate: u32) -> i64 { + let (mbs_w, mbs_h) = (u64::from(width.div_ceil(16)), u64::from(height.div_ceil(16))); + let frame = mbs_w * mbs_h; + let rate = frame * u64::from(fps.max(1)); + let factor = match profile { + H264Profile::ConstrainedHigh => 1250, + H264Profile::ConstrainedBaseline => 1000, + }; + H264_LEVELS + .iter() + .find(|&&(_, max_rate, max_frame, max_kbps)| { + rate <= max_rate + && frame <= max_frame + // Neither side may exceed sqrt(8 * MaxFS) macroblocks. + && mbs_w * mbs_w <= 8 * max_frame + && mbs_h * mbs_h <= 8 * max_frame + && u64::from(bitrate) <= max_kbps * factor + }) + .map_or(H264_LEVELS[H264_LEVELS.len() - 1].0, |l| l.0) +} + /// The backend's realtime settings (besides size, format, time base and /// rate, which every backend gets). fn settings(spec: &BackendSpec, config: &EncoderConfig, low_power: bool) -> Vec { @@ -688,6 +743,16 @@ impl FfmpegEncoder { if !self.spec.is_hardware() { list.push(generic("threads", self.config.threads_for(width, height))); } + if self.spec.codec == Codec::H264 { + // The level the signalling offers, so the SPS cannot claim a + // higher one than the viewer's decoder was set up for. Both + // targets: the wrappers that have a private `level` read that + // one, the rest `AVCodecContext.level`. + let level = + h264_level(self.config.h264_profile, width, height, fps, bitrate).to_string(); + list.push(generic("level", &level)); + list.push(Setting { values: vec![level], ..opt("level", &[]) }); + } list.extend(settings(self.spec, &self.config, low_power)); for setting in &list { self.apply(ctx, private, setting)?; @@ -1400,6 +1465,48 @@ mod tests { assert_eq!(t.pending.len(), 64, "bounded"); } + /// [`h264_level`] must agree with the level the signalling offers + /// (`voelin_stream::h264::level_idc`) for every stream, or the SPS and + /// the SDP would disagree again. Two copies of ITU-T Table A-1, pinned + /// to each other: this crate cannot depend on voelin-stream (it is the + /// lower one), and voelin-stream must not pull in the codecs. + #[test] + fn levels_agree_with_the_signalling() { + for (w, h) in [ + (320u32, 240u32), + (640, 360), + (1280, 720), + (1920, 1080), + (2560, 1440), + (3840, 2160), + (4096, 64), + (16384, 16384), + ] { + for fps in [1u32, 15, 30, 60, 120] { + for kbps in [200u32, 4_000, 8_000, 30_000] { + for (mine, theirs) in [ + (H264Profile::ConstrainedHigh, voelin_stream::H264Profile::ConstrainedHigh), + ( + H264Profile::ConstrainedBaseline, + voelin_stream::H264Profile::ConstrainedBaseline, + ), + ] { + let bitrate = kbps * 1000; + let ours = h264_level(mine, w, h, fps, bitrate); + let signalled = + voelin_stream::h264::level_idc(theirs, w, h, fps, u64::from(bitrate)); + assert_eq!( + ours, + i64::from(signalled), + "{w}x{h}@{fps} {kbps}k {mine:?}: encoder level {ours}, offer \ + {signalled}" + ); + } + } + } + } + } + #[test] fn settings_per_backend() { let config = EncoderConfig::default(); diff --git a/crates/voelin-media/tests/ffmpeg.rs b/crates/voelin-media/tests/ffmpeg.rs index 4f8e2ad..a614d4f 100644 --- a/crates/voelin-media/tests/ffmpeg.rs +++ b/crates/voelin-media/tests/ffmpeg.rs @@ -183,11 +183,24 @@ fn x264_is_constrained_high_and_changes_size() { /// `profile_idc` of the first SPS in an Annex B stream. fn h264_profile(data: &[u8]) -> Option { + sps(data).map(|(profile, _, _)| profile) +} + +/// `profile_idc`, the constraint-flag byte (`constraint_set0..5` in the top +/// six bits) and `level_idc` of the first SPS in an Annex B stream: the very +/// three bytes of `profile-level-id` in the SDP `a=fmtp` line. +/// +/// They are the first three bytes of the SPS payload, so no bit reading is +/// needed. Emulation prevention cannot touch them either: it only ever +/// inserts a byte after two zeros, and no valid SPS starts +/// `profile_idc == 0`. +fn sps(data: &[u8]) -> Option<(u8, u8, u8)> { let mut i = 0; - while i + 4 < data.len() { + while i + 3 < data.len() { if data[i..i + 3] == [0, 0, 1] { if data[i + 3] & 0x1f == 7 { - return data.get(i + 4).copied(); + let p = data.get(i + 4..i + 7)?; + return Some((p[0], p[1], p[2])); } i += 3; } else { @@ -197,6 +210,92 @@ fn h264_profile(data: &[u8]) -> Option { None } +/// What every usable H.264 backend puts in the SPS against the +/// `profile-level-id` the signalling offers for the same stream. A decoder +/// set up from our offer must be able to decode what we send, so the +/// emitted `level_idc` may never exceed the offered one, and `profile_idc` +/// has to be the profile we claim. +/// +/// The constraint-flag byte is only reported, not asserted: VA-API has no +/// Constrained High profile at all (`h264_vaapi` offers `main`, `high`, +/// `high10`, `constrained_baseline`), so it emits plain High with the flags +/// clear, while AMF's `constrained_high` sets `constraint_set4` and +/// `constraint_set5` as the offer says. See `docs/media.md`. +#[test] +fn sps_carries_the_offered_profile_and_level() { + use voelin_media::H264Profile; + if ffmpeg().is_none() { + return; + } + // 720p30 (offered level 3.1) and 1080p60 (4.2). + const CASES: [(u32, u32, u32, u32); 2] = + [(1280, 720, 30, 4_000_000), (1920, 1080, 60, 6_000_000)]; + let mut tested = 0; + for status in probe().iter().filter(|s| s.available.is_ok()) { + if status.spec.codec != Codec::H264 { + continue; + } + for profile in [H264Profile::ConstrainedHigh, H264Profile::ConstrainedBaseline] { + let (offered_profile, want_idc) = match profile { + H264Profile::ConstrainedHigh => (voelin_stream::H264Profile::ConstrainedHigh, 100), + H264Profile::ConstrainedBaseline => { + (voelin_stream::H264Profile::ConstrainedBaseline, 66) + } + }; + for (w, h, fps, bitrate) in CASES { + let config = EncoderConfig { + fps, + bitrate_bps: bitrate, + h264_profile: profile, + ..EncoderConfig::default() + }; + let mut encoder = FfmpegEncoder::new(status.spec.name, config).unwrap(); + let screen = SyntheticScreen::new(w, h); + // Hardware encoders hold a frame or two before the first packet. + let mut packets = Vec::new(); + for n in 0..8 { + packets.extend(encoder.encode(&screen.frame(n, fps), n == 0).unwrap()); + if !packets.is_empty() { + break; + } + } + let Some(first) = packets.first() else { + panic!("{} produced no packet at {w}x{h}", status.spec.name) + }; + let Some((idc, flags, level)) = sps(&first.data) else { + panic!("{} sent no SPS at {w}x{h}", status.spec.name) + }; + let offered = voelin_stream::h264::offer_profile_level_id( + offered_profile, + w, + h, + fps, + u64::from(bitrate), + ); + let offered_level = (offered & 0xff) as u8; + eprintln!( + "{:<12} {profile:?} {w}x{h}@{fps}: SPS {idc:02x} {flags:02x} {level:02x}, \ + offer {:06x}", + status.spec.name, offered + ); + assert_eq!( + idc, want_idc, + "{} emits profile_idc {idc}, the offer claims {want_idc}", + status.spec.name + ); + assert!( + level <= offered_level, + "{} emits level_idc {level} at {w}x{h}@{fps}, above the offered {offered_level}: \ + a decoder set up from our SDP could refuse it", + status.spec.name + ); + tested += 1; + } + } + } + assert!(tested > 0, "no usable H.264 backend to check"); +} + #[test] fn codecs_prefer_ffmpeg_h264_over_nothing() { if ffmpeg().is_none() || !available("libx264") { From 0f6d866e8b4aed18ae9bbed0a9e2907c9cf48a93 Mon Sep 17 00:00:00 2001 From: selikhov Date: Tue, 29 Sep 2026 13:40:44 +0300 Subject: [PATCH 03/35] voelin-ui: take chat, avatars and groups from the engine's history The chat view showed what `Event::Chat` reported: no ids, so nothing could be pinned, reacted to or grouped into topics, and avatars were always initials. Drive it from `Event::ChatHistory` instead, which upserts messages by their local id, and keep the old path only for sessions the engine stores no history for (it does not know the server yet). Each tab now holds its messages and rebuilds its lines with `vm::list::sync`, so a reaction changes one row. Around that: the image cache decodes avatars and icons from the engine's cache (`AvatarReady`, `IconReady`), members are grouped by server group with badges and talk power, the member card carries contacts and per-client volume, and file links in a message become cards that can be downloaded. The composer's attach uses xdg-desktop-portal's file chooser, which `voelin-platform` already had ashpd for. Co-Authored-By: Claude Opus 5 --- Cargo.lock | 1 + crates/voelin-platform/Cargo.toml | 5 +- crates/voelin-platform/src/files.rs | 84 ++++ crates/voelin-platform/src/lib.rs | 2 + crates/voelin-ui/Cargo.toml | 2 + crates/voelin-ui/src/app.rs | 170 ++++++- crates/voelin-ui/src/bind/chat.rs | 46 +- crates/voelin-ui/src/chat.rs | 696 +++++++++++++++++++++++++--- crates/voelin-ui/src/emoji.rs | 6 + crates/voelin-ui/src/images.rs | 15 + crates/voelin-ui/src/lib.rs | 1 + crates/voelin-ui/src/members.rs | 139 ++++++ crates/voelin-ui/src/servers.rs | 3 + crates/voelin-ui/src/vm/avatar.rs | 6 + crates/voelin-ui/src/vm/chat.rs | 203 +++++++- crates/voelin-ui/src/vm/tree.rs | 141 +++++- crates/voelin-ui/ui/bridge.slint | 154 +++++- 17 files changed, 1561 insertions(+), 113 deletions(-) create mode 100644 crates/voelin-platform/src/files.rs create mode 100644 crates/voelin-ui/src/members.rs diff --git a/Cargo.lock b/Cargo.lock index 2c2b55e..72b7548 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9297,6 +9297,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..ea2591c 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,9 @@ pub(crate) struct Models { pub tabs: Rc>, pub streams: Rc>, pub viewers: Rc>, + pub pins: Rc>, + pub topics: Rc>, + pub topic_messages: Rc>, /// Shown when there is no chat. pub no_chat: Rc>, } @@ -200,6 +301,9 @@ impl Models { tabs: Rc::default(), streams: Rc::default(), viewers: Rc::default(), + pins: Rc::default(), + topics: Rc::default(), + topic_messages: Rc::default(), no_chat: Rc::default(), }; bridge.set_servers(ModelRc::from(models.servers.clone())); @@ -208,6 +312,9 @@ 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_messages(ModelRc::from(models.no_chat.clone())); models } @@ -236,6 +343,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 +369,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 +482,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 +547,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 +562,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 +782,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/bind/chat.rs b/crates/voelin-ui/src/bind/chat.rs index e52aef7..88c7b39 100644 --- a/crates/voelin-ui/src/bind/chat.rs +++ b/crates/voelin-ui/src/bind/chat.rs @@ -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::(); @@ -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)); + }); } diff --git a/crates/voelin-ui/src/chat.rs b/crates/voelin-ui/src/chat.rs index 1dcccf3..0d4fab0 100644 --- a/crates/voelin-ui/src/chat.rs +++ b/crates/voelin-ui/src/chat.rs @@ -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, + 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 { + let gateway = view.gateway_has(feature::PINS) + || view.gateway_has(feature::REACTIONS) + || view.gateway_has(feature::TOPICS); + let mut previous: Option = 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::(); - 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 = 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 = 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 = 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 = 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, 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"); } } diff --git a/crates/voelin-ui/src/emoji.rs b/crates/voelin-ui/src/emoji.rs index 97d6a0f..43e0906 100644 --- a/crates/voelin-ui/src/emoji.rs +++ b/crates/voelin-ui/src/emoji.rs @@ -294,6 +294,12 @@ pub fn key_for(grapheme: &str) -> Option { 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 { + 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 { diff --git a/crates/voelin-ui/src/images.rs b/crates/voelin-ui/src/images.rs index b7ee79c..c7af2cf 100644 --- a/crates/voelin-ui/src/images.rs +++ b/crates/voelin-ui/src/images.rs @@ -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() { diff --git a/crates/voelin-ui/src/lib.rs b/crates/voelin-ui/src/lib.rs index d6e2eab..14ce7be 100644 --- a/crates/voelin-ui/src/lib.rs +++ b/crates/voelin-ui/src/lib.rs @@ -8,6 +8,7 @@ mod dev; mod emoji; mod hotkey; mod images; +mod members; mod servers; mod settings; mod settings_page; diff --git a/crates/voelin-ui/src/members.rs b/crates/voelin-ui/src/members.rs new file mode 100644 index 0000000..d878f31 --- /dev/null +++ b/crates/voelin-ui/src/members.rs @@ -0,0 +1,139 @@ +//! 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 { + /// 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::(); + 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 = 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(); + } +} diff --git a/crates/voelin-ui/src/servers.rs b/crates/voelin-ui/src/servers.rs index 216a2ea..3235e9e 100644 --- a/crates/voelin-ui/src/servers.rs +++ b/crates/voelin-ui/src/servers.rs @@ -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 { diff --git a/crates/voelin-ui/src/vm/avatar.rs b/crates/voelin-ui/src/vm/avatar.rs index 4f3d060..2b09d8d 100644 --- a/crates/voelin-ui/src/vm/avatar.rs +++ b/crates/voelin-ui/src/vm/avatar.rs @@ -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; diff --git a/crates/voelin-ui/src/vm/chat.rs b/crates/voelin-ui/src/vm/chat.rs index d4268be..f60d832 100644 --- a/crates/voelin-ui/src/vm/chat.rs +++ b/crates/voelin-ui/src/vm/chat.rs @@ -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 { + 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::>(), + ))) +} + +/// 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::>(), + ))); + 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::>(), - ))), - None => ModelRc::default(), - }; + let cards: Vec = 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"); + } } diff --git a/crates/voelin-ui/src/vm/tree.rs b/crates/voelin-ui/src/vm/tree.rs index 2f789c4..0d79ae5 100644 --- a/crates/voelin-ui/src/vm/tree.rs +++ b/crates/voelin-ui/src/vm/tree.rs @@ -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, + /// Icons in the engine's cache, by icon id (group icons). + pub icons: &'a HashMap, + /// 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 { 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 { 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 = 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, + icons: HashMap, + groups: Vec, + } + fn input<'a>( p: &'a Presence, talking: &'a HashSet, collapsed: &'a HashSet, 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); + } } diff --git a/crates/voelin-ui/ui/bridge.slint b/crates/voelin-ui/ui/bridge.slint index 5164a5a..ecf2560 100644 --- a/crates/voelin-ui/ui/bridge.slint +++ b/crates/voelin-ui/ui/bridge.slint @@ -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 current-tab: 0; in property <[ChatLine]> messages; + // Older messages can still be loaded in the current chat. + in property more-history; + in property loading-history; + // The current chat holds only what this device saw (no gateway sync). + in property local-history; + // Features of the session's gateway: hide what is missing. + in property has-pins; + in property has-reactions; + in property has-topics; + // The pins drawer. + in property <[PinItem]> pins; + in property pins-loading; + // The topics drawer, and the open topic. + in property <[TopicItem]> topics; + in property topics-loading; + in-out property current-topic: -1; + in property topic-title; + in property <[ChatLine]> topic-messages; + // The member card over the members panel. + in-out property member-card; in property status-text; // Unread messages in all chats of the current server. in property unread-total; @@ -242,6 +361,16 @@ export global Bridge { in property viewer-ended; in-out property viewer-volume: 100; in property viewer-fullscreen; + // The viewer fills the window without the shell ("pop out"). + in-out property viewer-popped; + // "12:34" since the stream was joined. + in property viewer-elapsed; + in property viewer-count; + // Simulcast layers the streamer offers, "Auto" first. + in property <[string]> viewer-qualities; + in-out property viewer-quality: 0; + // What "Auto" picked ("720p · 2.4 Mbit/s"). + in property 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(); From 50cbdae57d491f3da153cbcb0961dfb193b817e6 Mon Sep 17 00:00:00 2001 From: selikhov Date: Tue, 29 Sep 2026 18:35:39 +0300 Subject: [PATCH 04/35] voelin-media: stop probing absent GPUs and keep the encoder libraries quiet The startup probe opened every encoder in the table, which took 1.77 s here and froze the app's first use for that long, and it let the libraries behind them print about thirty lines to standard error on every run. Most of the time went on hardware that is not in the machine: a self-test of a family whose vendor is absent still runs its driver's initialisation before failing, 1.7 s for av1_nvenc and 1.2 s for vp9_qsv here. Read the PCI vendors of the DRM render nodes once and skip those families outright; when the vendors cannot be read nothing is skipped, so an unusual setup only pays what it paid before. The report gains a plain reason ("no NVIDIA GPU in this machine") in place of a CUDA error code. FFmpeg's own log already goes to tracing, but SVT-AV1's build banner, AMF's GetProperty warnings and Mesa's RADV_PERFTEST notice are written to the descriptor by the libraries themselves. Point standard error at a temporary file while the self-tests run and log what landed there as one debug record; VOELIN_FFMPEG_PROBE_STDERR=1 leaves it alone. Measured with `voelinctl stream encoders` (release): 1.77 s before, 0.93-1.12 s after, 12 backends tested instead of 20, and nothing on standard error. Co-Authored-By: Claude Opus 5 --- crates/voelin-media/Cargo.toml | 4 +- crates/voelin-media/src/ffmpeg/encoder.rs | 186 ++++++++++++++++++++-- 2 files changed, 173 insertions(+), 17 deletions(-) diff --git a/crates/voelin-media/Cargo.toml b/crates/voelin-media/Cargo.toml index 59e1878..1585f53 100644 --- a/crates/voelin-media/Cargo.toml +++ b/crates/voelin-media/Cargo.toml @@ -20,7 +20,7 @@ openh264-download = ["openh264", "dep:reqwest", "dep:bzip2", "dep:sha2"] # Video encoders through FFmpeg loaded at runtime (never linked or shipped): # VA-API, NVENC, Quick Sync, AMF, Media Foundation, VideoToolbox, x264, # SVT-AV1, ... whatever the installed FFmpeg has (see docs/media.md). -ffmpeg = ["dep:libloading"] +ffmpeg = ["dep:libloading", "dep:rustix"] # AV1 decoding through the system libdav1d (pkg-config `dav1d` >= 1.3). av1 = ["dep:dav1d"] # X11 screen capture (Linux). @@ -54,7 +54,7 @@ yuv = "0.8.19" ashpd = { version = "0.13.13", default-features = false, features = ["screencast", "tokio"], optional = true } memmap2 = { version = "0.9.11", optional = true } pipewire = { version = "0.10.1", optional = true } -rustix = { version = "1.1.5", features = ["event", "fs"], optional = true } +rustix = { version = "1.1.5", features = ["event", "fs", "stdio"], optional = true } wayland-client = { version = "0.31.15", optional = true } wayland-protocols = { version = "0.32.13", features = ["client", "staging"], optional = true } wayland-protocols-wlr = { version = "0.3.12", features = ["client"], optional = true } diff --git a/crates/voelin-media/src/ffmpeg/encoder.rs b/crates/voelin-media/src/ffmpeg/encoder.rs index 241d53e..c92b3ac 100644 --- a/crates/voelin-media/src/ffmpeg/encoder.rs +++ b/crates/voelin-media/src/ffmpeg/encoder.rs @@ -1316,6 +1316,9 @@ pub struct BackendStatus { pub spec: &'static BackendSpec, /// `Ok` if it encoded the test frame, else why not. pub available: std::result::Result<(), String>, + /// How long its self-test took (the probe runs them in parallel, so the + /// startup cost is the slowest one). + pub took: Duration, } /// Size of the self-test frame. @@ -1341,42 +1344,195 @@ fn in_build(ffmpeg: &Ffmpeg, name: &str) -> bool { !unsafe { (ffmpeg.api.avcodec_find_encoder_by_name)(name.as_ptr()) }.is_null() } +/// PCI vendor of a GPU, as `/sys/class/drm/*/device/vendor` gives it. +#[cfg(target_os = "linux")] +mod vendor { + pub const AMD: u32 = 0x1002; + pub const NVIDIA: u32 = 0x10de; + pub const INTEL: u32 = 0x8086; +} + +/// The PCI vendors of this machine's DRM render nodes, read once; empty if +/// `/sys/class/drm` says nothing (a container without it, say), which is +/// taken as "unknown" and skips nothing. +#[cfg(target_os = "linux")] +fn drm_vendors() -> &'static [u32] { + static VENDORS: OnceLock> = OnceLock::new(); + VENDORS.get_or_init(|| { + let Ok(entries) = std::fs::read_dir("/sys/class/drm") else { return Vec::new() }; + let mut found: Vec = entries + .flatten() + .filter(|e| e.file_name().to_string_lossy().starts_with("renderD")) + .filter_map(|e| std::fs::read_to_string(e.path().join("device/vendor")).ok()) + .filter_map(|text| u32::from_str_radix(text.trim().trim_start_matches("0x"), 16).ok()) + .collect(); + found.sort_unstable(); + found.dedup(); + found + }) +} + +/// Sends the process's standard error to a temporary file while it lives, +/// and logs whatever landed there when it is dropped. +/// +/// FFmpeg's own messages already go to `tracing` (see +/// [`Ffmpeg::capture_log`](super::Ffmpeg::capture_log)), but the libraries +/// behind the encoders write to the descriptor themselves and cannot be +/// asked not to: SVT-AV1 prints a build banner and its allocation totals, +/// AMD's AMF runtime prints `GetProperty(...) not found` warnings, and Mesa +/// prints a `RADV_PERFTEST` deprecation notice when AMF brings up Vulkan. +/// Opening every encoder at startup meant about thirty such lines on every +/// run of the app. +/// +/// This moves the descriptor, so anything else the process writes to +/// standard error meanwhile lands in the file too and comes back as one +/// `debug` record. `VOELIN_FFMPEG_PROBE_STDERR=1` leaves it alone. +struct QuietStderr { + #[cfg(unix)] + saved: std::os::fd::OwnedFd, + #[cfg(unix)] + file: std::path::PathBuf, +} + +impl QuietStderr { + #[cfg(unix)] + fn start() -> Option { + use std::os::fd::AsFd; + + if std::env::var_os("VOELIN_FFMPEG_PROBE_STDERR").is_some() { + return None; + } + let file = + std::env::temp_dir().join(format!("voelin-encoder-probe-{}.log", std::process::id())); + let sink = std::fs::File::create(&file).ok()?; + let stderr = std::io::stderr(); + let saved = rustix::io::dup(stderr.as_fd()).ok()?; + // Anything already buffered belongs on the real descriptor. + let _ = std::io::Write::flush(&mut std::io::stderr()); + rustix::stdio::dup2_stderr(sink.as_fd()).ok()?; + Some(Self { saved, file }) + } + + #[cfg(not(unix))] + fn start() -> Option { + None + } +} + +#[cfg(unix)] +impl Drop for QuietStderr { + fn drop(&mut self) { + use std::os::fd::AsFd; + + let _ = std::io::Write::flush(&mut std::io::stderr()); + let _ = rustix::stdio::dup2_stderr(self.saved.as_fd()); + if let Ok(text) = std::fs::read_to_string(&self.file) { + let text = text.trim(); + if !text.is_empty() { + tracing::debug!(target: "ffmpeg", "the encoder libraries wrote:\n{text}"); + } + } + let _ = std::fs::remove_file(&self.file); + } +} + +/// Whether the hardware `spec` needs can be in this machine at all. +/// +/// A self-test of a family whose vendor is absent still costs 0.4-1.7 s of +/// driver initialisation before it fails (measured here: `av1_nvenc` 1.7 s, +/// `vp9_qsv` 1.2 s), and the probe's wall time is its slowest test. Nothing +/// is skipped when the vendors cannot be read, so an unusual setup only +/// pays the time it used to. +fn vendor_may_be_present(spec: &BackendSpec) -> std::result::Result<(), String> { + #[cfg(target_os = "linux")] + { + let vendors = drm_vendors(); + if vendors.is_empty() { + return Ok(()); + } + let (wanted, what) = match spec.family() { + "nvenc" => (vendor::NVIDIA, "no NVIDIA GPU"), + "qsv" => (vendor::INTEL, "no Intel GPU"), + "amf" => (vendor::AMD, "no AMD GPU"), + _ => return Ok(()), + }; + // NVIDIA's driver can run without a DRM node (`nvidia-drm.modeset=0`). + if wanted == vendor::NVIDIA && std::path::Path::new("/dev/nvidiactl").exists() { + return Ok(()); + } + if !vendors.contains(&wanted) { + return Err(format!("{what} in this machine")); + } + } + let _ = spec; + Ok(()) +} + /// Every backend with its self-test result (run once per process, the /// backends in parallel). Empty without FFmpeg. +/// +/// A backend whose vendor is not in the machine is not opened at all +/// ([`vendor_may_be_present`]): its driver would spend up to 1.7 s failing, +/// and the probe costs as much as its slowest test. pub fn probe() -> &'static [BackendStatus] { static PROBE: OnceLock> = OnceLock::new(); PROBE.get_or_init(|| { let Ok(ffmpeg) = Ffmpeg::get() else { return Vec::new() }; + let started = Instant::now(); + let quiet = QuietStderr::start(); let statuses: Vec = std::thread::scope(|scope| { let tests: Vec<_> = BACKENDS .iter() .map(|spec| { - let present = in_build(ffmpeg, spec.name); - let test = present.then(|| scope.spawn(move || test_backend(spec))); - (spec, test) + let absent = vendor_may_be_present(spec).err(); + let present = absent.is_none() && in_build(ffmpeg, spec.name); + let test = present.then(|| { + scope.spawn(move || { + let started = Instant::now(); + (test_backend(spec), started.elapsed()) + }) + }); + (spec, absent, test) }) .collect(); tests .into_iter() - .map(|(spec, test)| BackendStatus { - spec, - available: match test { - None => Err("not in this FFmpeg build".into()), - Some(handle) => { - handle.join().unwrap_or_else(|_| Err("the self-test panicked".into())) - } - }, + .map(|(spec, absent, test)| { + let (available, took) = match test { + None => ( + Err(absent.unwrap_or_else(|| "not in this FFmpeg build".into())), + Duration::ZERO, + ), + Some(handle) => handle.join().unwrap_or_else(|_| { + (Err("the self-test panicked".into()), Duration::ZERO) + }), + }; + BackendStatus { spec, available, took } }) .collect() }); + // Standard error comes back (and what the libraries wrote is logged) + // before our own report. + drop(quiet); for status in &statuses { match &status.available { - Ok(()) => tracing::info!(backend = status.spec.name, "FFmpeg encoder available"), - Err(e) => { - tracing::debug!(backend = status.spec.name, "FFmpeg encoder unusable: {e}") - } + Ok(()) => tracing::info!( + backend = status.spec.name, + ms = status.took.as_millis() as u64, + "FFmpeg encoder available" + ), + Err(e) => tracing::debug!( + backend = status.spec.name, + ms = status.took.as_millis() as u64, + "FFmpeg encoder unusable: {e}" + ), } } + tracing::info!( + ms = started.elapsed().as_millis() as u64, + tested = statuses.iter().filter(|s| !s.took.is_zero()).count(), + "FFmpeg encoders probed" + ); statuses }) } From e219a38c4670104efdbe589305c189ae4e2aa3c3 Mon Sep 17 00:00:00 2001 From: selikhov Date: Tue, 29 Sep 2026 18:38:04 +0300 Subject: [PATCH 05/35] voelin-ui: the server screens of the new design The server page had one layout: a channel tree, a chat and a panel of members and streams. The design asks for more of it at once, so the same page now carries the pieces it was missing. The chat shows reactions, a pin marker, file cards and older messages, and every message can be reacted to, pinned or made into a topic where the gateway offers it. A compact voice bar sits over it with the connected channel, who is talking and the voice controls, so the sidebar card is no longer the only way to leave or mute. The members panel groups people by server group with the group's icon, shows the badges and talk power a TeamSpeak client expects, and opens a card with the person's description, groups, private chat, poke, contact and volume. Its width is the setting `ui.members_width`, so dragging the handle keeps it. Pins and topics are drawers over the chat, the voice channel can be seen as a grid of tiles with the streams in it, and the stream viewer gained the elapsed time, the viewer count, a quality picker, a mute button, the chat beside the player and a pop-out that hides the shell. The quality picker stays hidden for now: the engine tells a viewer neither which simulcast layers a streamer offers nor lets it ask for one, so there is nothing to choose between. Co-Authored-By: Claude Opus 5 --- crates/voelin-ui/src/app.rs | 4 + crates/voelin-ui/src/appearance.rs | 21 +- crates/voelin-ui/src/bind/emoji.rs | 4 +- crates/voelin-ui/src/bind/settings.rs | 3 + crates/voelin-ui/src/bind/streams.rs | 3 + crates/voelin-ui/src/emoji.rs | 2 +- crates/voelin-ui/src/settings.rs | 13 +- crates/voelin-ui/src/streams.rs | 85 +++- crates/voelin-ui/ui/app.slint | 59 ++- crates/voelin-ui/ui/bridge.slint | 4 + crates/voelin-ui/ui/nav.slint | 35 ++ crates/voelin-ui/ui/screens/chat.slint | 590 +++++++++++++++++++--- crates/voelin-ui/ui/screens/drawers.slint | 290 +++++++++++ crates/voelin-ui/ui/screens/members.slint | 571 +++++++++++++++++++++ crates/voelin-ui/ui/screens/streams.slint | 295 +++++++---- 15 files changed, 1795 insertions(+), 184 deletions(-) create mode 100644 crates/voelin-ui/ui/screens/drawers.slint create mode 100644 crates/voelin-ui/ui/screens/members.slint diff --git a/crates/voelin-ui/src/app.rs b/crates/voelin-ui/src/app.rs index ea2591c..7d2456b 100644 --- a/crates/voelin-ui/src/app.rs +++ b/crates/voelin-ui/src/app.rs @@ -288,6 +288,8 @@ pub(crate) struct Models { 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>, } @@ -304,6 +306,7 @@ impl Models { 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())); @@ -315,6 +318,7 @@ impl Models { 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 } 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::