chore(client): checkpoint deployed features and unfinished server management

User requested a checkpoint and stopped all agents. Deployed artifacts remain the last verified releases; unfinished settings/categories/forums are preserved as WIP. See TODO/roadmap for verification and remaining release/updater work.
This commit is contained in:
Loki 2026-11-01 15:31:21 +01:00
parent 15f03bf8df
commit f04691c3cd
Signed by: boba
GPG key ID: 253067914055423B
90 changed files with 9599 additions and 371 deletions

View file

@ -67,16 +67,17 @@ pub(crate) fn raw_device(device: &cpal::Device, alsa: bool) -> Option<RawDevice>
pub fn enumerate() -> Result<DeviceLists> {
let host = cpal::default_host();
let alsa = is_alsa(&host);
let collect = |devices: Vec<cpal::Device>| {
let collect = |devices: Vec<cpal::Device>, input: bool| {
let raw: Vec<RawDevice> = devices
.iter()
.filter_map(|device| raw_device(device, alsa))
.filter(|device| !input || !device.id.ends_with(".monitor"))
.collect();
filter::visible_devices(&raw, alsa)
};
Ok(DeviceLists {
input: collect(host.input_devices()?.collect()),
output: collect(host.output_devices()?.collect()),
input: collect(host.input_devices()?.collect(), true),
output: collect(host.output_devices()?.collect(), false),
})
}

View file

@ -0,0 +1,628 @@
//! Explicit, bounded local microphone monitoring. No network or voice-session access.
use super::{
DenoiseState,
config::{AudioConfig, OPUS_RATE},
devices,
};
use anyhow::{Context, Result};
use cpal::traits::{DeviceTrait, StreamTrait};
use std::{
sync::{
Arc, Mutex,
atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering},
},
time::{Duration, Instant},
};
const FRAME: usize = 480;
const PREFILL: usize = OPUS_RATE as usize / 50; // 20 ms absorbs callback scheduling variation.
const HIGH_WATER: usize = OPUS_RATE as usize / 25; // Trim at 40 ms, never accumulate old speech.
const CAPACITY: usize = OPUS_RATE as usize * 60 / 1000;
/// One producer, one consumer. Only the consumer advances `read`; a full writer drops new
/// samples. Slots are atomic as well, so no unsafe shared memory or realtime mutex is needed.
struct MonitorQueue {
samples: Box<[AtomicU32]>,
read: AtomicUsize,
write: AtomicUsize,
overrun: AtomicBool,
}
impl MonitorQueue {
fn new(capacity: usize) -> Self {
Self {
samples: (0..capacity).map(|_| AtomicU32::new(0)).collect(),
read: AtomicUsize::new(0),
write: AtomicUsize::new(0),
overrun: AtomicBool::new(false),
}
}
fn push(&self, sample: f32) -> bool {
let write = self.write.load(Ordering::Relaxed);
if write.wrapping_sub(self.read.load(Ordering::Acquire)) >= self.samples.len() {
self.overrun.store(true, Ordering::Release);
return false;
}
self.samples[write % self.samples.len()].store(sample.to_bits(), Ordering::Relaxed);
self.write.store(write.wrapping_add(1), Ordering::Release);
true
}
fn pop(&self) -> Option<f32> {
let read = self.read.load(Ordering::Relaxed);
if read == self.write.load(Ordering::Acquire) {
return None;
}
let sample =
f32::from_bits(self.samples[read % self.samples.len()].load(Ordering::Relaxed));
self.read.store(read.wrapping_add(1), Ordering::Release);
Some(sample)
}
fn len(&self) -> usize {
self.write
.load(Ordering::Acquire)
.wrapping_sub(self.read.load(Ordering::Acquire))
}
fn trim_to(&self, target: usize) {
let read = self.read.load(Ordering::Relaxed);
let count = self.write.load(Ordering::Acquire).wrapping_sub(read);
if count > target {
self.read
.store(read.wrapping_add(count - target), Ordering::Release);
}
}
}
/// Rational phase survives callback boundaries, including non-integral 44.1/48 kHz ratios.
struct InputResampler {
from: u64,
to: u64,
index: u64,
next: u64,
previous: Option<f32>,
}
impl InputResampler {
fn new(from: u32, to: u32) -> Self {
Self {
from: from.into(),
to: to.into(),
index: 0,
next: 0,
previous: None,
}
}
fn sample(&mut self, value: f32, mut emit: impl FnMut(f32)) {
if let Some(previous) = self.previous {
let end = self.index * self.to;
let start = (self.index - 1) * self.to;
while self.next <= end {
let fraction = (self.next - start) as f64 / self.to as f64;
emit(previous + (value - previous) * fraction as f32);
self.next += self.from;
}
} else {
emit(value);
self.next = self.from;
}
self.previous = Some(value);
self.index += 1;
}
}
struct Playback {
current: f32,
next: f32,
phase: f64,
started: bool,
gain: f32,
last: f32,
filtered_depth: f64,
underruns: usize,
trims: usize,
}
impl Default for Playback {
fn default() -> Self {
Self {
current: 0.0,
next: 0.0,
phase: 0.0,
started: false,
gain: 0.0,
last: 0.0,
filtered_depth: PREFILL as f64,
underruns: 0,
trims: 0,
}
}
}
impl Playback {
fn render(
&mut self,
queue: &MonitorQueue,
data: &mut [f32],
channels: usize,
rate: u32,
volume: f32,
) {
let depth = queue.len();
let overrun = queue.overrun.swap(false, Ordering::AcqRel);
if overrun || depth > HIGH_WATER {
// A full writer drops new data. After a stalled output this queue may contain
// old speech of arbitrary age, so flush it and prefill fresh capture instead.
queue.trim_to(if overrun { 0 } else { PREFILL });
self.trims += 1;
self.started = false;
self.gain = 0.0;
}
// Independent device clocks drift. A slow, bounded servo changes the resampling
// ratio by at most 0.2%, rather than periodically dropping whole 10 ms frames.
self.filtered_depth += (queue.len() as f64 - self.filtered_depth) * 0.02;
let correction =
((self.filtered_depth - PREFILL as f64) / OPUS_RATE as f64 * 0.5).clamp(-0.002, 0.002);
let step = OPUS_RATE as f64 / rate as f64 * (1.0 + correction);
for frame in data.chunks_mut(channels) {
if !self.started && queue.len() >= PREFILL {
self.current = queue.pop().unwrap_or(0.0);
self.next = queue.pop().unwrap_or(0.0);
self.phase = 0.0;
self.started = true;
self.gain = 0.0;
}
let value = if self.started {
self.gain = (self.gain + 1.0 / 64.0).min(1.0);
let value =
(self.current + (self.next - self.current) * self.phase as f32) * self.gain;
self.phase += step;
while self.phase >= 1.0 {
self.phase -= 1.0;
self.current = self.next;
if let Some(next) = queue.pop() {
self.next = next;
} else {
self.started = false;
self.underruns += 1;
break;
}
}
self.last = value;
value
} else {
// A short release avoids discontinuities on an underrun; prefill before restart.
self.last *= 0.95;
if self.last.abs() < 0.00001 {
self.last = 0.0;
}
self.last
};
frame.fill(value.clamp(-1.0, 1.0) * 0.5 * volume);
}
}
}
struct Meter {
level: f32,
observed: Instant,
hold_until: Instant,
}
impl Default for Meter {
fn default() -> Self {
let now = Instant::now();
Self {
level: 0.0,
observed: now,
hold_until: now,
}
}
}
impl Meter {
fn read(&mut self, peak: f32, now: Instant) -> f32 {
let decay_start = self.observed.max(self.hold_until);
if now > decay_start {
self.level *= (-(now - decay_start).as_secs_f32() / 0.18).exp();
}
if peak >= self.level && peak > 0.0 {
self.level = peak;
self.hold_until = now + Duration::from_millis(60);
}
self.observed = now;
self.level.clamp(0.0, 1.0)
}
}
#[derive(Default)]
struct Shared {
stopped: AtomicBool,
running: AtomicBool,
peak: AtomicU32,
denoise: AtomicBool,
volume: AtomicU32,
error: Mutex<Option<String>>,
meter: Mutex<Meter>,
}
/// A thirty-second local test, stopped immediately when its owner is dropped.
pub struct MicrophoneTest(Arc<Shared>);
impl MicrophoneTest {
pub fn start(
input: String,
output: String,
denoise: bool,
volume: f32,
previous_workers: Option<Arc<AtomicUsize>>,
) -> Result<Self> {
let shared = Arc::new(Shared::default());
shared.running.store(true, Ordering::Release);
shared.denoise.store(denoise, Ordering::Relaxed);
shared.volume.store(
(volume / 100.0).clamp(0.0, 1.0).to_bits(),
Ordering::Relaxed,
);
let worker = shared.clone();
std::thread::Builder::new()
.name("microphone-test".into())
.spawn(move || {
if let Err(error) = wait_and_monitor(&input, &output, &worker, previous_workers)
&& let Ok(mut slot) = worker.error.lock()
{
*slot = Some(format!("{error:#}"));
}
worker.running.store(false, Ordering::Release);
})?;
Ok(Self(shared))
}
pub fn stop(&self) {
self.0.stopped.store(true, Ordering::Release);
}
pub fn set_volume(&self, value: f32) {
self.0
.volume
.store((value / 100.0).clamp(0.0, 1.0).to_bits(), Ordering::Relaxed);
}
pub fn running(&self) -> bool {
self.0.running.load(Ordering::Acquire)
}
pub fn level(&self) -> f32 {
let peak = f32::from_bits(self.0.peak.swap(0, Ordering::Relaxed));
self.0
.meter
.lock()
.map(|mut meter| meter.read(peak, Instant::now()))
.unwrap_or(peak)
.clamp(0.0, 1.0)
}
pub fn set_denoise(&self, value: bool) {
self.0.denoise.store(value, Ordering::Relaxed);
}
pub fn take_error(&self) -> Option<String> {
self.0.error.lock().ok()?.take()
}
}
impl Drop for MicrophoneTest {
fn drop(&mut self) {
self.0.stopped.store(true, Ordering::Release);
}
}
fn wait_and_monitor(
input: &str,
output: &str,
shared: &Arc<Shared>,
previous: Option<Arc<AtomicUsize>>,
) -> Result<()> {
if let Some(previous) = previous {
let deadline = Instant::now() + Duration::from_secs(5);
while previous.load(Ordering::Acquire) != 0 {
if shared.stopped.load(Ordering::Acquire) {
return Ok(());
}
anyhow::ensure!(
Instant::now() < deadline,
"previous audio streams are still closing; retry shortly"
);
std::thread::sleep(Duration::from_millis(10));
}
}
if shared.stopped.load(Ordering::Acquire) {
return Ok(());
}
monitor(input, output, shared)
}
fn monitor(input: &str, output: &str, shared: &Arc<Shared>) -> Result<()> {
let microphone = devices::open_input(input)?;
let speakers = devices::open_output(output)?;
let streams = build_streams(&microphone, &speakers, shared, true).or_else(|error| {
tracing::warn!(%error, "low-latency monitor configuration unavailable; retrying device defaults");
build_streams(&microphone, &speakers, shared, false)
})?;
if shared.stopped.load(Ordering::Acquire) {
return Ok(());
}
streams.1.play()?;
streams.0.play()?;
let deadline = Instant::now() + Duration::from_secs(30);
while !shared.stopped.load(Ordering::Acquire) && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(10));
}
Ok(())
}
fn request_small_buffer(
device: &cpal::Device,
config: &mut AudioConfig,
input: bool,
) -> Result<()> {
let ranges: Vec<_> = if input {
device.supported_input_configs()?.collect()
} else {
device.supported_output_configs()?.collect()
};
if let Some(range) = ranges.iter().find(|range| {
range.sample_format() == cpal::SampleFormat::F32
&& range.channels() == config.stream.channels
&& range.min_sample_rate() <= config.sample_rate
&& range.max_sample_rate() >= config.sample_rate
}) && let cpal::SupportedBufferSize::Range { min, max } = *range.buffer_size()
{
config.stream.buffer_size = cpal::BufferSize::Fixed(
(config.sample_rate / 200).clamp(min.max(1), max.max(min).max(1)),
);
}
Ok(())
}
fn build_streams(
microphone: &cpal::Device,
speakers: &cpal::Device,
shared: &Arc<Shared>,
small_buffers: bool,
) -> Result<(cpal::Stream, cpal::Stream)> {
let mut capture = AudioConfig::find(microphone, true)?;
let mut playback = AudioConfig::find(speakers, false)?;
if small_buffers {
request_small_buffer(microphone, &mut capture, true)?;
request_small_buffer(speakers, &mut playback, false)?;
}
tracing::info!(input_buffer = ?capture.stream.buffer_size, output_buffer = ?playback.stream.buffer_size, "local monitor requested callback buffers (not measured round-trip latency)");
let input_channels = capture.stream.channels as usize;
let output_channels = playback.stream.channels as usize;
let output_rate = playback.sample_rate;
let queue = Arc::new(MonitorQueue::new(CAPACITY));
let captured = queue.clone();
let metrics = shared.clone();
let capture_error = shared.clone();
let output_error = shared.clone();
let monitor_volume = shared.clone();
let mut denoise = DenoiseState::new()?;
let mut resampler = InputResampler::new(capture.sample_rate, OPUS_RATE);
let mut pending = [0.0; FRAME];
let mut pending_len = 0;
let input_stream = microphone
.build_input_stream(
capture.stream,
move |data: &[f32], _| {
if metrics.stopped.load(Ordering::Acquire) {
return;
}
for channels in data.chunks_exact(input_channels) {
let mono = channels
.iter()
.copied()
.filter(|sample| sample.is_finite())
.sum::<f32>()
/ input_channels as f32;
resampler.sample(mono.clamp(-1.0, 1.0), |sample| {
pending[pending_len] = sample;
pending_len += 1;
if pending_len == FRAME {
if metrics.denoise.load(Ordering::Relaxed) {
denoise.process(&mut pending);
}
let peak = pending
.iter()
.fold(0.0_f32, |peak, sample| peak.max(sample.abs()))
.clamp(0.0, 1.0);
metrics.peak.fetch_max(peak.to_bits(), Ordering::Relaxed);
for sample in pending {
captured.push(sample);
}
pending_len = 0;
}
});
}
},
move |error| {
if let Ok(mut slot) = capture_error.error.lock() {
*slot = Some(error.to_string());
}
capture_error.stopped.store(true, Ordering::Release);
},
None,
)
.context("cannot open microphone for local test")?;
let mut reader = Playback::default();
let output_stream = speakers
.build_output_stream(
playback.stream,
move |data: &mut [f32], _| {
if monitor_volume.stopped.load(Ordering::Acquire) {
data.fill(0.0);
return;
}
let volume = f32::from_bits(monitor_volume.volume.load(Ordering::Relaxed));
reader.render(&queue, data, output_channels, output_rate, volume);
},
move |error| {
if let Ok(mut slot) = output_error.error.lock() {
*slot = Some(error.to_string());
}
output_error.stopped.store(true, Ordering::Release);
},
None,
)
.context("cannot open output for local test")?;
Ok((input_stream, output_stream))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn queue_is_bounded_and_only_consumer_discards_old_audio() {
let queue = MonitorQueue::new(3);
assert!(queue.push(1.0));
assert!(queue.push(2.0));
assert!(queue.push(3.0));
assert!(!queue.push(4.0));
queue.trim_to(2);
assert_eq!(queue.pop(), Some(2.0));
assert!(queue.push(5.0));
assert_eq!(queue.pop(), Some(3.0));
assert_eq!(queue.pop(), Some(5.0));
assert_eq!(queue.pop(), None);
}
#[test]
fn resampling_is_identical_across_irregular_callback_boundaries() {
for (from, to) in [(44100, 48000), (96000, 48000), (48000, 48000)] {
let samples: Vec<_> = (0..from).map(|i| (i as f32 * 0.01).sin()).collect();
let mut whole = InputResampler::new(from, to);
let mut expected = Vec::new();
for &sample in &samples {
whole.sample(sample, |sample| expected.push(sample));
}
let mut split = InputResampler::new(from, to);
let mut actual = Vec::new();
for chunk in samples.chunks(137) {
for &sample in chunk {
split.sample(sample, |sample| actual.push(sample));
}
}
assert_eq!(actual, expected);
assert!((actual.len() as isize - to as isize).abs() <= 2);
}
}
#[test]
fn stalled_playback_trims_latency_and_underrun_rebuffers() {
let queue = MonitorQueue::new(CAPACITY);
for _ in 0..CAPACITY {
assert!(queue.push(0.5));
}
let mut playback = Playback::default();
let mut output = [0.0; 240];
playback.render(&queue, &mut output, 1, OPUS_RATE, 1.0);
assert!(queue.len() < PREFILL);
assert!(
output
.iter()
.all(|sample| sample.is_finite() && *sample <= 0.25)
);
for _ in 0..30 {
playback.render(&queue, &mut output, 1, OPUS_RATE, 1.0);
}
assert!(!playback.started);
assert!(output.iter().all(|sample| sample.abs() < 0.00001));
}
#[test]
fn overflow_discards_stale_speech_and_waits_for_fresh_capture() {
let queue = MonitorQueue::new(CAPACITY);
for _ in 0..CAPACITY {
assert!(queue.push(0.9));
}
for _ in 0..OPUS_RATE {
assert!(!queue.push(-0.2));
}
let mut playback = Playback::default();
let mut output = [0.0; 240];
playback.render(&queue, &mut output, 1, OPUS_RATE, 1.0);
assert_eq!(queue.len(), 0);
assert!(output.iter().all(|sample| *sample == 0.0));
for _ in 0..PREFILL {
assert!(queue.push(-0.2));
}
playback.render(&queue, &mut output, 1, OPUS_RATE, 1.0);
assert!(output.iter().all(|sample| *sample < 0.0));
}
#[test]
fn independent_clocks_and_irregular_callbacks_do_not_accumulate_latency() {
for (rate, ppm) in [(44100_u32, -1000.0), (48000, 0.0), (96000, 1000.0)] {
let queue = MonitorQueue::new(CAPACITY);
let mut playback = Playback::default();
let mut time = 0.0;
let mut capture_at = 0.0;
let mut output = [0.0; 2048];
for callback in 0..12000 {
let frames = [137, 256, 91, 480][callback % 4];
let next = time + frames as f64 / rate as f64;
while capture_at <= next {
for _ in 0..FRAME {
assert!(queue.push(0.2));
}
capture_at += 0.01 / (1.0 + ppm / 1_000_000.0);
}
playback.render(&queue, &mut output[..frames], 1, rate, 1.0);
assert!(output[..frames].iter().all(|sample| sample.is_finite()));
assert!(queue.len() <= HIGH_WATER);
time = next;
}
assert_eq!(playback.underruns, 0, "rate {rate}, drift {ppm}");
assert_eq!(playback.trims, 0, "rate {rate}, drift {ppm}");
}
}
#[test]
fn spsc_transfers_ordered_samples_across_threads_without_locks() {
let queue = Arc::new(MonitorQueue::new(127));
let writer = queue.clone();
let producer = std::thread::spawn(move || {
for sample in 0..100_000 {
while !writer.push(sample as f32) {
std::thread::yield_now();
}
}
});
for expected in 0..100_000 {
let sample = loop {
if let Some(sample) = queue.pop() {
break sample;
}
std::thread::yield_now();
};
assert_eq!(sample, expected as f32);
}
producer.join().unwrap();
assert_eq!(queue.len(), 0);
}
#[test]
fn meter_holds_peaks_and_releases_smoothly_without_callback_flicker() {
let now = Instant::now();
let mut meter = Meter {
observed: now,
hold_until: now,
level: 0.0,
};
assert_eq!(meter.read(0.8, now), 0.8);
assert_eq!(meter.read(0.0, now + Duration::from_millis(16)), 0.8);
let later = meter.read(0.0, now + Duration::from_millis(100));
assert!(later > 0.5 && later < 0.8);
assert!(meter.read(0.0, now + Duration::from_secs(1)) < 0.01);
}
#[test]
fn dropping_test_revokes_capture_and_meter_consumes_peak() {
let shared = Arc::new(Shared::default());
shared.peak.store(0.5_f32.to_bits(), Ordering::Relaxed);
let test = MicrophoneTest(shared.clone());
assert_eq!(test.level(), 0.5);
assert!(test.level() >= 0.49);
drop(test);
assert!(shared.stopped.load(Ordering::Acquire));
}
#[test]
fn cancelling_while_old_streams_close_never_opens_new_devices() {
let shared = Arc::new(Shared::default());
shared.stopped.store(true, Ordering::Release);
let previous = Arc::new(AtomicUsize::new(2));
// No backend/stream access occurs on this cancellation path.
assert!(wait_and_monitor("missing", "missing", &shared, Some(previous)).is_ok());
}
}

View file

@ -1,6 +1,7 @@
pub mod config;
pub mod devices;
pub mod diagnostics;
pub mod microphone_test;
mod pipeline;
mod processing;
pub mod sounds;

View file

@ -76,6 +76,7 @@ pub fn run(
.context("cannot start the microphone stream")?;
info!("capture started ({} Hz)", cfg.sample_rate);
let mut vad = VoiceActivity::default();
let mut speaking_indicator = VoiceActivity::default();
let mut silent_frames: u32 = 0;
let mut silence_reported = false;
@ -121,9 +122,10 @@ pub fn run(
if gate_snapshot.noise_suppress {
denoise.process(&mut pcm);
}
let speaking = gate_snapshot.decide(&pcm, &mut vad, frame_ms);
let transmitting = gate_snapshot.decide(&pcm, &mut vad, frame_ms);
let speaking = speech_indicator(&pcm, transmitting, &mut speaking_indicator, frame_ms);
local_speaking.store(speaking, Ordering::Relaxed);
if !speaking {
if !transmitting {
b = buf.lock().unwrap();
continue;
}
@ -162,6 +164,16 @@ fn raw_peak(samples: &[f32]) -> f32 {
samples.iter().fold(0.0f32, |peak, s| peak.max(s.abs()))
}
fn speech_indicator(
pcm: &[f32],
transmitting: bool,
detector: &mut VoiceActivity,
frame_ms: u32,
) -> bool {
let speech = detector.update(crate::audio::processing::frame_rms(pcm), 0.02, frame_ms);
transmitting && speech
}
fn frame_samples_at(sample_rate: u32, frame_ms: u32) -> usize {
(sample_rate as usize * frame_ms as usize) / 1000
}
@ -182,7 +194,15 @@ fn apply_bitrate(
#[cfg(test)]
mod tests {
use super::frame_samples_at;
use super::{VoiceActivity, frame_samples_at, speech_indicator};
#[test]
fn open_microphone_silence_does_not_light_the_speaking_ring() {
let mut detector = VoiceActivity::default();
assert!(!speech_indicator(&[0.0; 960], true, &mut detector, 20));
assert!(speech_indicator(&[0.1; 960], true, &mut detector, 20));
assert!(!speech_indicator(&[0.1; 960], false, &mut detector, 20));
}
#[test]
fn frame_sizes_scale_with_ms() {

View file

@ -6,7 +6,7 @@ mod playback;
use std::sync::{
Arc, Mutex,
atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering},
atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering},
mpsc::{self, Receiver, Sender},
};
use tracing::info;
@ -19,7 +19,15 @@ use crate::audio::{
pub use playback::JitterConfig;
struct WorkerFinished(Arc<AtomicUsize>);
impl Drop for WorkerFinished {
fn drop(&mut self) {
self.0.fetch_sub(1, Ordering::Release);
}
}
pub struct AudioPipeline {
workers: Arc<AtomicUsize>,
stopped: Arc<AtomicBool>,
encoded_rx: Receiver<EncodedFrame>,
microphone_tap: media::MicrophoneTap,
@ -49,6 +57,18 @@ impl Drop for AudioPipeline {
}
impl AudioPipeline {
/// Completes only after both worker functions have released their audio streams.
pub fn shutdown_signal(&self) -> Arc<AtomicUsize> {
self.workers.clone()
}
/// Mutes outgoing capture before a separate local monitoring stream starts.
pub fn pause_microphone(&self) {
if let Ok(mut gate) = self.gate.lock() {
gate.mic_enabled = false;
}
self.local_speaking.store(false, Ordering::Relaxed);
}
pub fn enable_media_microphone(&self, enabled: bool) {
self.microphone_tap.enable(enabled);
}
@ -158,7 +178,10 @@ pub fn start(cfg: PipelineConfig) -> anyhow::Result<AudioPipeline> {
let (encoded_tx, encoded_rx) = mpsc::channel::<EncodedFrame>();
let (voice_tx, voice_rx) = mpsc::channel::<IncomingVoice>();
let gate = Arc::new(Mutex::new(TransmitGate::default()));
let gate = Arc::new(Mutex::new(TransmitGate {
mic_enabled: false,
..Default::default()
}));
let gate_cap = gate.clone();
let output_volume = Arc::new(Mutex::new(90.0f32));
let vol_play = output_volume.clone();
@ -181,7 +204,11 @@ pub fn start(cfg: PipelineConfig) -> anyhow::Result<AudioPipeline> {
let capture_stopped = stopped.clone();
let channel_id = cfg.channel_key;
let enc_tx = encoded_tx.clone();
let workers = Arc::new(AtomicUsize::new(2));
let capture_workers = workers.clone();
let playback_workers = workers.clone();
std::thread::spawn(move || {
let _finished = WorkerFinished(capture_workers);
if let Err(e) = capture::run(
input,
in_cfg,
@ -199,6 +226,7 @@ pub fn start(cfg: PipelineConfig) -> anyhow::Result<AudioPipeline> {
}
});
std::thread::spawn(move || {
let _finished = WorkerFinished(playback_workers);
if let Err(e) = playback::run(
output,
out_cfg,
@ -215,6 +243,7 @@ pub fn start(cfg: PipelineConfig) -> anyhow::Result<AudioPipeline> {
});
Ok(AudioPipeline {
workers,
stopped,
encoded_rx,
microphone_tap,

View file

@ -19,8 +19,8 @@ mod imp {
}
pub fn process(&mut self, pcm: &mut [f32]) {
for chunk in pcm.chunks_exact_mut(FRAME_SIZE) {
let input: Vec<f32> = chunk.iter().map(|&s| s * 32768.0).collect();
for chunk in pcm.as_chunks_mut::<FRAME_SIZE>().0 {
let input: [f32; FRAME_SIZE] = std::array::from_fn(|index| chunk[index] * 32768.0);
self.inner.process_frame(&mut self.out_buf, &input);
for (out, &denoised) in chunk.iter_mut().zip(self.out_buf.iter()) {
*out = (denoised / 32768.0).clamp(-1.0, 1.0);
@ -28,6 +28,28 @@ mod imp {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn repeated_frames_keep_scratch_storage_and_finite_normalized_output() {
let mut state = DenoiseState::new().unwrap();
let scratch = state.out_buf.as_ptr();
for index in 0..32 {
let mut frame = std::array::from_fn::<_, FRAME_SIZE, _>(|sample| {
((sample + index * FRAME_SIZE) as f32 * 0.03).sin() * 0.2
});
state.process(&mut frame);
assert!(
frame
.iter()
.all(|sample| sample.is_finite() && sample.abs() <= 1.0)
);
assert_eq!(state.out_buf.as_ptr(), scratch);
assert_eq!(state.out_buf.len(), FRAME_SIZE);
}
}
}
}
#[cfg(not(feature = "rnnoise"))]

View file

@ -20,6 +20,9 @@ use vnox_client::net::NetHandle;
use crate::ui::state::{ConnState, UiState};
pub struct AppState {
pub(crate) audio_shutdown: Option<std::sync::Arc<std::sync::atomic::AtomicUsize>>,
pub(crate) microphone_test: Option<vnox_client::audio::microphone_test::MicrophoneTest>,
pub(crate) device_refresh: ui::devices::DeviceRefresh,
pub(crate) webhooks: Option<Rc<ui::webhooks::WebhookUi>>,
pub(crate) connection_generation: u64,
pub(crate) identity: identity::Identity,
@ -49,6 +52,9 @@ fn main() -> Result<()> {
let net = net::spawn(identity.clone());
let state = Rc::new(RefCell::new(AppState {
audio_shutdown: None,
microphone_test: None,
device_refresh: Default::default(),
webhooks: None,
connection_generation: 0,
identity,
@ -62,6 +68,7 @@ fn main() -> Result<()> {
{
let mut s = state.borrow_mut();
crate::ui::preferences::load(&mut s.ui);
crate::ui::connection::load(&mut s.ui);
s.ui.appearance = crate::ui::appearance::AppearancePreferences::load();
s.ui.vault_enabled = identity::is_vault_encrypted();
let user_id = s.identity.pubkey_hex.clone();
@ -70,7 +77,7 @@ fn main() -> Result<()> {
}
let window = MainWindow::new()?;
window.set_address_input(state.borrow().ui.connect_input.as_str().into());
refresh_devices(&window, &mut state.borrow_mut().ui);
sync_device_models(&window, &state.borrow().ui);
let webhook_net = state.borrow().net.clone();
state.borrow_mut().webhooks = Some(Rc::new(ui::webhooks::WebhookUi::new(Rc::new(
@ -82,7 +89,10 @@ fn main() -> Result<()> {
},
))?));
wire_signals(&window, &state);
ui::forum::wire(&window, &state);
let _account_timer = ui::account::wire(&window, &state);
ui::media::wire(&window, &state)?;
ui::chat_media::wire(&window, &state);
let timer = slint::Timer::default();
{
@ -94,11 +104,52 @@ fn main() -> Result<()> {
move || {
if let Some(win) = weak.upgrade() {
let mut s = state.borrow_mut();
if let Some(result) = s.device_refresh.take_ready() {
match result {
Ok(lists) => {
ui::devices::apply_refresh(&mut s.ui, lists);
sync_device_models(&win, &s.ui);
}
Err(error) => tracing::warn!(%error, "cannot enumerate audio devices"),
}
}
if !s.ui.settings_open
&& let Some(test) = s.microphone_test.as_ref()
{
test.stop();
}
if let Some(test) = s.microphone_test.as_ref() {
let running = test.running();
let level = test.level();
let error = test.take_error();
test.set_denoise(s.ui.noise_suppress);
test.set_volume(s.ui.output_volume);
s.ui.mic_test_running = running;
s.ui.mic_test_level = level.max(s.ui.mic_test_level * 0.85);
if error.is_some() {
s.ui.mic_test_error = error;
}
if !running {
s.microphone_test = None;
}
} else {
s.ui.mic_test_running = false;
s.ui.mic_test_level = 0.0;
}
if s.audio_shutdown.as_ref().is_some_and(|workers| {
workers.load(std::sync::atomic::Ordering::Acquire) == 0
}) {
s.audio_shutdown = None;
}
crate::ui::update::process_net_events(&mut s);
if s.ui.connection.authentication_required {
win.set_account_authenticated(false);
}
let own_id = s.identity.pubkey_hex.clone();
let own_nick = s.identity.nickname.clone();
let own_pubkey = s.identity.pubkey_hex.clone();
crate::ui::bridge::sync_ui(&win, &s.ui, &own_id, &own_nick, &own_pubkey);
crate::ui::chat_media::tick(&win, &s);
}
},
);
@ -145,8 +196,7 @@ fn load_identity() -> Result<Option<identity::Identity>> {
}
}
fn refresh_devices(window: &MainWindow, ui: &mut UiState) {
crate::ui::devices::refresh(ui);
fn sync_device_models(window: &MainWindow, ui: &UiState) {
let model = |items: Vec<String>| {
Rc::new(slint::VecModel::from(
items
@ -197,7 +247,66 @@ fn wire_signals(window: &MainWindow, state: &Rc<RefCell<AppState>>) {
});
}
{
let state = state.clone();
window.on_refresh_audio_devices(move || state.borrow_mut().device_refresh.request());
}
{
let state = state.clone();
window.on_device_selected(move |input, output| {
let mut s = state.borrow_mut();
if let Some(test) = s.microphone_test.as_ref() {
test.stop();
}
crate::ui::devices::select(&mut s.ui, input.max(0) as usize, output.max(0) as usize);
if let Err(error) = crate::ui::preferences::save(&s.ui) {
tracing::warn!(%error, "cannot save devices");
}
});
}
{
let state = state.clone();
window.on_noise_suppression_changed(move |enabled| {
let mut s = state.borrow_mut();
s.ui.noise_suppress = enabled && cfg!(feature = "rnnoise");
if let Err(error) = crate::ui::preferences::save(&s.ui) {
tracing::warn!(%error, "cannot save noise suppression");
}
});
}
{
let state = state.clone();
window.on_toggle_microphone_test(move || {
let mut s = state.borrow_mut();
if let Some(test) = s.microphone_test.as_ref() {
test.stop();
return;
}
s.ui.mic_test_error = None;
let previous_workers = s
.audio
.take()
.map(|audio| audio.shutdown_signal())
.or_else(|| s.audio_shutdown.clone());
s.audio_shutdown = previous_workers.clone();
s.voice_channel = None;
match vnox_client::audio::microphone_test::MicrophoneTest::start(
s.ui.mic_device_id.clone(),
s.ui.output_device_id.clone(),
s.ui.noise_suppress,
s.ui.output_volume,
previous_workers,
) {
Ok(test) => {
s.microphone_test = Some(test);
s.ui.mic_test_running = true;
}
Err(error) => s.ui.mic_test_error = Some(error.to_string()),
}
});
}
ui::emoji::wire(window);
ui::channel_admin::wire(window, state);
crate::ui::appearance::wire(window, state, !cfg!(test));
ui::i18n::wire(window, !cfg!(test));
crate::ui::avatar::wire(window, state, !cfg!(test));
@ -216,7 +325,9 @@ fn wire_signals(window: &MainWindow, state: &Rc<RefCell<AppState>>) {
}
{
let state = state.clone();
window.on_auto_reconnect_changed(move |value| state.borrow_mut().ui.auto_reconnect = value);
window.on_auto_reconnect_changed(move |value| {
ui::connection::set_auto_reconnect(&mut state.borrow_mut(), value)
});
}
{
let state = state.clone();
@ -225,13 +336,10 @@ fn wire_signals(window: &MainWindow, state: &Rc<RefCell<AppState>>) {
}
{
let state = state.clone();
let weak = window.as_weak();
window.on_open_settings(move || {
let mut s = state.borrow_mut();
s.ui.settings_open = true;
if let Some(window) = weak.upgrade() {
refresh_devices(&window, &mut s.ui);
}
s.device_refresh.request();
});
}
{
@ -250,7 +358,13 @@ fn wire_signals(window: &MainWindow, state: &Rc<RefCell<AppState>>) {
let state = state.clone();
window.on_audio_settings_changed(move |input, output, bitrate, mode, volume| {
let mut s = state.borrow_mut();
let old_devices = (s.ui.mic_device_id.clone(), s.ui.output_device_id.clone());
crate::ui::devices::select(&mut s.ui, input.max(0) as usize, output.max(0) as usize);
if old_devices != (s.ui.mic_device_id.clone(), s.ui.output_device_id.clone())
&& let Some(test) = s.microphone_test.as_ref()
{
test.stop();
}
s.ui.voice_bitrate = bitrate.clamp(8.0, 128.0);
let mode = mode.clamp(0, 2) as usize;
if mode != s.ui.vad_mode {
@ -273,15 +387,12 @@ fn wire_signals(window: &MainWindow, state: &Rc<RefCell<AppState>>) {
window.on_channel_selected(move |id| {
let id = id.to_string();
let mut s = state.borrow_mut();
let is_voice =
s.ui.channels
.iter()
.any(|c| c.id == id && c.kind == "voice");
let send_join = if is_voice {
s.ui.request_voice_join(&id)
} else {
s.ui.select_text_channel(id.clone());
true
let kind = s.ui.channels.iter().find(|channel| channel.id == id && channel.guild_id == s.ui.active_guild_id).map(|channel|channel.kind.as_str()).unwrap_or("").to_owned();
if kind == "forum" { ui::forum::select(&mut s, &id); return; }
let send_join = match kind.as_str() {
"voice" => s.ui.request_voice_join(&id),
"text" => { s.ui.select_text_channel(id.clone()); true },
_ => return,
};
let net = s.net.clone();
drop(s);
@ -349,21 +460,7 @@ fn wire_signals(window: &MainWindow, state: &Rc<RefCell<AppState>>) {
{
let state = state.clone();
window.on_connect(move |addr| {
let addr = addr.to_string();
let mut s = state.borrow_mut();
s.ui.conn = ConnState::Connecting;
s.ui.connect_input = addr.clone();
s.ui.status_msg = Some("Connecting…".into());
let auto_reconnect = s.ui.auto_reconnect;
let net = s.net.clone();
drop(s);
tokio::spawn(async move {
net.send(NetCommand::Connect {
address: addr,
auto_reconnect,
})
.await;
});
ui::connection::connect(&mut state.borrow_mut(), addr.to_string());
});
}
@ -383,18 +480,7 @@ fn wire_signals(window: &MainWindow, state: &Rc<RefCell<AppState>>) {
s.ui.status_msg = Some("Could not save the trusted fingerprint".into());
return;
}
s.ui.conn = ConnState::Connecting;
s.ui.status_msg = Some("Connecting…".into());
let auto_reconnect = s.ui.auto_reconnect;
let net = s.net.clone();
drop(s);
tokio::spawn(async move {
net.send(NetCommand::Connect {
address: prompt.address,
auto_reconnect,
})
.await;
});
ui::connection::connect(&mut s, prompt.address);
});
}
@ -424,7 +510,8 @@ fn wire_signals(window: &MainWindow, state: &Rc<RefCell<AppState>>) {
{
let state = state.clone();
window.on_disconnect(move || {
let s = state.borrow();
let mut s = state.borrow_mut();
ui::connection::disconnect(&mut s);
let net = s.net.clone();
drop(s);
tokio::spawn(async move {
@ -446,6 +533,7 @@ fn wire_signals(window: &MainWindow, state: &Rc<RefCell<AppState>>) {
s.ui.status_msg = Some("Not connected to a server. Your draft has been kept.".into());
return;
}
if s.ui.active_dm_id.is_none() && !s.ui.channels.iter().any(|channel| channel.id == ch_id && channel.kind == "text") { return; }
if let Some(dm_id) = s.ui.active_dm_id.as_ref()
&& s.ui.dm_conversations.iter().any(|c| &c.dm_id == dm_id && c.e2ee_enabled)
{
@ -628,7 +716,7 @@ fn wire_signals(window: &MainWindow, state: &Rc<RefCell<AppState>>) {
let state = state.clone();
window.on_leave_voice(move || {
let mut s = state.borrow_mut();
let voice_channel = s.ui.voice_target.take();
let voice_channels = s.ui.take_voice_leave_targets();
let was_in_voice = s.audio.is_some();
crate::ui::update::stop_voice(&mut s);
if was_in_voice {
@ -637,9 +725,11 @@ fn wire_signals(window: &MainWindow, state: &Rc<RefCell<AppState>>) {
s.ui.showing_voice = false;
s.ui.ptt_held = false;
let net = s.net.clone();
if let Some(channel_id) = voice_channel {
if !voice_channels.is_empty() {
tokio::spawn(async move {
net.send(NetCommand::LeaveChannel { channel_id }).await;
for channel_id in voice_channels {
net.send(NetCommand::LeaveChannel { channel_id }).await;
}
});
}
});
@ -679,6 +769,10 @@ fn wire_signals(window: &MainWindow, state: &Rc<RefCell<AppState>>) {
window.on_close_settings(move || {
let mut state = state.borrow_mut();
state.ui.settings_open = false;
if let Some(test) = state.microphone_test.as_ref() {
test.stop();
}
state.ui.mic_test_running = false;
if let Some(window) = weak.upgrade() {
crate::ui::appearance::bindings_restore(&window, &state.ui.appearance);
}

845
src/net/account.rs Normal file
View file

@ -0,0 +1,845 @@
//! Real Central browser sign-in and identity-bound account admission.
//!
//! Device/refresh secrets never enter browser URLs or logs. The identity private key
//! stays on this device; account proofs contain only the matching public key.
use crate::identity::Identity;
use anyhow::{Context, Result, bail, ensure};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::{
path::PathBuf,
time::{Duration, SystemTime, UNIX_EPOCH},
};
use tokio::sync::{mpsc, watch};
pub const CENTRAL_ORIGIN: &str = "https://central.loki-code.dev";
const MAX_RESPONSE: usize = 32 * 1024;
/// Enrollment is missing or revoked: another browser approval is required.
#[derive(Debug)]
pub struct SignInRequired;
impl std::fmt::Display for SignInRequired {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("Central sign-in expired or was revoked; sign in again")
}
}
impl std::error::Error for SignInRequired {}
/// Public account details safe to show in desktop UI.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AccountSummary {
pub user_id: String,
pub handle: String,
pub display_name: String,
pub avatar_url: Option<String>,
#[serde(default)]
pub profile_complete: bool,
}
/// Non-secret, identity-scoped profile notification; credentials never enter UI events.
#[derive(Clone)]
pub struct ProfileUpdate {
pub proof: Option<Vec<u8>>,
pub epoch: u64,
pub public_key: String,
pub user: AccountSummary,
}
static ENROLLMENT_EPOCH: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
pub fn enrollment_epoch() -> u64 {
ENROLLMENT_EPOCH.load(std::sync::atomic::Ordering::SeqCst)
}
fn enrollment_changed() {
ENROLLMENT_EPOCH.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
}
static PROFILE_UPDATES: std::sync::LazyLock<watch::Sender<Option<ProfileUpdate>>> =
std::sync::LazyLock::new(|| watch::channel(None).0);
static PROFILE_REQUESTS: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
static STORE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
pub fn subscribe_profiles() -> watch::Receiver<Option<ProfileUpdate>> {
PROFILE_UPDATES.subscribe()
}
pub fn latest_profile() -> Option<ProfileUpdate> {
PROFILE_UPDATES.borrow().clone()
}
/// A pending login contains a bearer secret. Intentionally does not implement Debug.
pub struct PendingLogin {
pub verification_uri: String,
pub public_key: String,
pub expires_at: i64,
device_secret: String,
}
/// Sign-in progress, containing no device or refresh secret.
#[derive(Debug, Clone)]
pub enum LoginEvent {
ApprovalRequired {
verification_uri: String,
public_key: String,
expires_at: i64,
},
}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct StoredAccount {
version: u32,
public_key: String,
refresh_secret: String,
user: AccountSummary,
}
fn now() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs() as i64
}
fn client() -> Result<reqwest::Client> {
Ok(reqwest::Client::builder()
.https_only(true)
.redirect(reqwest::redirect::Policy::none())
.connect_timeout(Duration::from_secs(10))
.timeout(Duration::from_secs(10))
.user_agent("VNOX-Desktop/0.1")
.build()?)
}
async fn response_json(response: reqwest::Response) -> Result<Value> {
ensure!(
response.content_length().unwrap_or(0) <= MAX_RESPONSE as u64,
"Central response exceeds size limit"
);
let mut response = response;
let mut bytes = Vec::new();
while let Some(chunk) = response.chunk().await? {
ensure!(
bytes.len() + chunk.len() <= MAX_RESPONSE,
"Central response exceeds size limit"
);
bytes.extend_from_slice(&chunk);
}
serde_json::from_slice(&bytes).context("Invalid response from Central")
}
async fn post(path: &str, body: &Value) -> Result<reqwest::Response> {
client()?
.post(format!("{CENTRAL_ORIGIN}{path}"))
.json(body)
.send()
.await
.context("Cannot reach Central; check your connection and retry")
}
fn field<'a>(value: &'a Value, key: &str) -> Result<&'a str> {
value
.get(key)
.and_then(Value::as_str)
.with_context(|| format!("Central response is missing {key}"))
}
fn validate_key(identity: &Identity) -> Result<()> {
let key = identity
.signing_key()
.context("Unlock your local identity before signing in")?;
ensure!(
hex::encode(key.verifying_key().to_bytes()) == identity.pubkey_hex,
"Local identity key mismatch"
);
Ok(())
}
/// Start a 10-minute pairing request. Open only its verification_uri in the browser.
pub async fn begin(identity: &Identity) -> Result<PendingLogin> {
validate_key(identity)?;
let _ = tokio::time::timeout(Duration::from_secs(2), retry_revocations()).await;
let response = post(
"/v1/auth/desktop/start",
&json!({"public_key":identity.pubkey_hex}),
)
.await?;
ensure!(
response.status().is_success(),
"Central could not start sign-in; retry shortly"
);
let value = response_json(response).await?;
let uri = field(&value, "verification_uri")?.to_owned();
let parsed = reqwest::Url::parse(&uri)?;
ensure!(
parsed.origin().ascii_serialization() == CENTRAL_ORIGIN
&& parsed.path() == "/desktop"
&& parsed.username().is_empty()
&& parsed.password().is_none(),
"Central returned an invalid approval URL"
);
let expires_at = value
.get("expires_at")
.and_then(Value::as_i64)
.context("Missing sign-in expiry")?;
ensure!(
expires_at > now() && expires_at <= now() + 610,
"Invalid sign-in expiry"
);
let device_secret = field(&value, "device_secret")?.to_owned();
ensure!(
device_secret.len() == 64 && hex::decode(&device_secret).is_ok(),
"Invalid device request"
);
Ok(PendingLogin {
verification_uri: uri,
public_key: identity.pubkey_hex.clone(),
expires_at,
device_secret,
})
}
/// Poll once. Call at most once per five seconds. Approved requests are single-use.
pub async fn poll(pending: &PendingLogin, identity: &Identity) -> Result<Option<AccountSummary>> {
ensure!(
pending.public_key == identity.pubkey_hex,
"Identity changed during sign-in"
);
ensure!(pending.expires_at > now(), "Sign-in expired; start again");
let response = post(
"/v1/auth/desktop/poll",
&json!({"device_secret":pending.device_secret}),
)
.await?;
if response.status() == reqwest::StatusCode::ACCEPTED {
return Ok(None);
}
ensure!(
response.status().is_success(),
"Sign-in expired or was canceled; start again"
);
let value = response_json(response).await?;
validate_proof(&value, identity)?;
let user: AccountSummary = serde_json::from_value(
value
.get("user")
.cloned()
.context("Missing Central account")?,
)?;
let refresh_secret = field(&value, "refresh_secret")?.to_owned();
ensure!(
refresh_secret.len() == 64 && hex::decode(&refresh_secret).is_ok(),
"Invalid Central enrollment"
);
save(&StoredAccount {
version: 1,
public_key: identity.pubkey_hex.clone(),
refresh_secret,
user: user.clone(),
})?;
Ok(Some(user))
}
/// Cancel a pending pairing. Expiry remains enforced if Central is unreachable.
pub async fn cancel(pending: &PendingLogin) -> Result<()> {
let response = post(
"/v1/auth/desktop/cancel",
&json!({"device_secret":pending.device_secret}),
)
.await?;
ensure!(
response.status().is_success(),
"Could not cancel sign-in at Central"
);
Ok(())
}
/// Run the complete cancellable device flow. The UI opens the URL from LoginEvent.
/// Sending true on cancel stops polling and attempts server-side cancellation.
pub async fn sign_in(
identity: &Identity,
updates: mpsc::UnboundedSender<LoginEvent>,
mut cancellation: watch::Receiver<bool>,
) -> Result<AccountSummary> {
ensure!(!*cancellation.borrow(), "Sign-in canceled");
let pending = begin(identity).await?;
if updates
.send(LoginEvent::ApprovalRequired {
verification_uri: pending.verification_uri.clone(),
public_key: pending.public_key.clone(),
expires_at: pending.expires_at,
})
.is_err()
{
let _ = cancel(&pending).await;
bail!("Sign-in window closed");
}
loop {
tokio::select! {
_=tokio::time::sleep(Duration::from_secs(5))=>{},
_=cancellation.changed()=>{
let _=cancel(&pending).await;
bail!("Sign-in canceled");
}
}
if *cancellation.borrow() {
let _ = cancel(&pending).await;
bail!("Sign-in canceled");
}
// Cancel in-flight polls too. Hub cancellation also revokes a consumed
// enrollment if the approved HTTP reply was lost.
let approved = tokio::select! {
result=poll(&pending,identity)=>match result {
Ok(approved)=>approved,
Err(error)=>{let _=cancel(&pending).await;return Err(error)}
},
_=cancellation.changed()=>{
let _=cancel(&pending).await;
bail!("Sign-in canceled");
}
};
if let Some(user) = approved {
if *cancellation.borrow() {
let cleared = clear();
let _ = cancel(&pending).await;
cleared?;
bail!("Sign-in canceled");
}
return Ok(user);
}
}
}
/// Locally enrolled account for UI startup. Admission always refreshes online.
pub fn current(identity: &Identity) -> Result<Option<AccountSummary>> {
Ok(load(identity)?.map(|stored| stored.user))
}
/// Revoke enrollment and remove local credentials. Disconnect gateway sessions in UI
/// before calling this function; admission proofs expire within ten minutes.
pub async fn sign_out(identity: &Identity) -> Result<()> {
let stored = match load(identity) {
Ok(stored) => stored,
Err(error) => {
clear()?;
return Err(error);
}
};
if let Some(stored) = stored {
// Rename atomically disables admission while preserving the secret needed to
// retry revocation after an outage. Tombstones are never loaded for admission.
let tombstone = {
let _guard = STORE_LOCK
.lock()
.map_err(|_| anyhow::anyhow!("Account state is unavailable"))?;
let current = load(identity)?.ok_or(SignInRequired)?;
ensure!(
current.refresh_secret == stored.refresh_secret,
"Central enrollment changed during sign-out"
);
let tombstone = queue_revocation(&path())?;
enrollment_changed();
tombstone
};
revoke_secret(&stored.refresh_secret).await?;
std::fs::remove_file(tombstone)?;
} else {
clear()?;
}
Ok(())
}
async fn revoke_secret(secret: &str) -> Result<()> {
let response = post("/v1/auth/desktop/revoke", &json!({"refresh_secret":secret})).await?;
ensure!(
response.status().is_success(),
"Signed out locally; Central revocation is queued for retry"
);
Ok(())
}
fn queue_revocation(active: &std::path::Path) -> Result<PathBuf> {
let directory = active.parent().context("Missing account directory")?;
let tombstone = directory.join(format!("pending-revocation-{}.json", uuid::Uuid::new_v4()));
std::fs::rename(active, &tombstone)?;
#[cfg(unix)]
std::fs::File::open(directory)?.sync_all()?;
Ok(tombstone)
}
/// Retry admission-disabled revocations left by a previous offline sign-out. Callers
/// bound the total attempt time; retries are safe because Hub revocation is idempotent.
pub async fn retry_revocations() -> Result<()> {
let active = path();
let Some(directory) = active.parent() else {
return Ok(());
};
let entries = match std::fs::read_dir(directory) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(error.into()),
};
for entry in entries.take(64) {
let entry = entry?;
let name = entry.file_name();
let Some(name) = name.to_str() else { continue };
if !name.starts_with("pending-revocation-") || !name.ends_with(".json") {
continue;
}
let file = std::fs::File::open(entry.path())?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
ensure!(
file.metadata()?.permissions().mode() & 0o077 == 0,
"Revocation credentials must remain private"
);
}
ensure!(
file.metadata()?.len() <= MAX_RESPONSE as u64,
"Revocation credentials too large"
);
let stored: StoredAccount = serde_json::from_reader(file)?;
revoke_secret(&stored.refresh_secret).await?;
std::fs::remove_file(entry.path())?;
}
Ok(())
}
/// Obtain a fresh identity-bound signed proof for every gateway admission. Missing or
/// revoked enrollment and Central outage fail closed; no anonymous fallback exists.
pub async fn admission_proof(identity: &Identity) -> Result<Vec<u8>> {
validate_key(identity)?;
let _ = tokio::time::timeout(Duration::from_secs(2), retry_revocations()).await;
let value = refresh(identity).await?;
validate_proof(&value, identity)
}
/// Refresh public profile at startup/settings entry and periodically; also refresh admission.
pub async fn refresh_profile(identity: &Identity) -> Result<AccountSummary> {
let value = refresh(identity).await?;
summary(&value, identity, true)
}
async fn refresh(identity: &Identity) -> Result<Value> {
let _request = PROFILE_REQUESTS.lock().await;
validate_key(identity)?;
let stored = load(identity)?.ok_or(SignInRequired)?;
let response = post(
"/v1/auth/desktop/refresh",
&json!({"refresh_secret":stored.refresh_secret}),
)
.await?;
if response.status() == reqwest::StatusCode::UNAUTHORIZED {
return Err(SignInRequired.into());
}
ensure!(
response.status().is_success(),
"Central could not refresh your profile; retry shortly"
);
let value = response_json(response).await?;
let proof = validate_proof(&value, identity)?;
let user = summary(&value, identity, true)?;
update_summary(identity, &stored, user, Some(proof))?;
Ok(value)
}
fn summary(value: &Value, identity: &Identity, proof_required: bool) -> Result<AccountSummary> {
let user: AccountSummary = serde_json::from_value(
value
.get("user")
.cloned()
.context("Missing Central account")?,
)?;
ensure!(
uuid::Uuid::parse_str(&user.user_id).is_ok_and(|id| !id.is_nil()),
"Invalid Central account"
);
ensure!(
!user.display_name.trim().is_empty() && user.display_name.chars().count() <= 64,
"Invalid Central profile name"
);
if proof_required {
let claim: Value = serde_json::from_slice(&hex::decode(field(
value
.get("account_proof")
.context("Missing account proof")?,
"claims",
)?)?)?;
ensure!(
field(&claim, "subject")? == user.user_id
&& field(&claim, "public_key")? == identity.pubkey_hex,
"Central profile does not match admission proof"
);
}
Ok(user)
}
fn update_summary(
identity: &Identity,
enrolled: &StoredAccount,
user: AccountSummary,
proof: Option<Vec<u8>>,
) -> Result<()> {
let _guard = STORE_LOCK
.lock()
.map_err(|_| anyhow::anyhow!("Account state is unavailable"))?;
update_summary_at(&path(), identity, enrolled, user.clone())?;
PROFILE_UPDATES.send_replace(Some(ProfileUpdate {
proof,
epoch: enrollment_epoch(),
public_key: identity.pubkey_hex.clone(),
user,
}));
Ok(())
}
fn update_summary_at(
account_path: &std::path::Path,
identity: &Identity,
enrolled: &StoredAccount,
user: AccountSummary,
) -> Result<()> {
ensure!(
user.user_id == enrolled.user.user_id,
"Central account changed unexpectedly"
);
let mut current = load_at(account_path, identity)?.ok_or(SignInRequired)?;
ensure!(
current.refresh_secret == enrolled.refresh_secret,
"Central enrollment changed during request"
);
current.user = user;
save_at(account_path, &current)
}
/// Save a cropped PNG to the enrolled Central account, or remove its custom photo.
pub async fn set_avatar(
identity: &Identity,
png: Option<Vec<u8>>,
epoch: u64,
) -> Result<AccountSummary> {
let method = if png.is_some() {
reqwest::Method::POST
} else {
reqwest::Method::DELETE
};
mutation(
identity,
"/v1/auth/desktop/avatar",
method,
png.unwrap_or_default(),
"image/png",
epoch,
)
.await
}
/// Set the account's display name without changing its unique handle or device keys.
pub async fn set_display_name(
identity: &Identity,
name: &str,
epoch: u64,
) -> Result<AccountSummary> {
mutation(
identity,
"/v1/auth/desktop/profile",
reqwest::Method::POST,
serde_json::to_vec(&json!({"display_name":name}))?,
"application/json",
epoch,
)
.await
}
async fn mutation(
identity: &Identity,
path: &str,
method: reqwest::Method,
body: Vec<u8>,
content_type: &str,
epoch: u64,
) -> Result<AccountSummary> {
use ed25519_dalek::Signer;
use sha2::{Digest, Sha256};
let _request = PROFILE_REQUESTS.lock().await;
ensure!(
epoch == enrollment_epoch(),
"Account changed; choose your profile again"
);
validate_key(identity)?;
let stored = load(identity)?.ok_or(SignInRequired)?;
ensure!(
body.len() <= 2 * 1024 * 1024,
"Profile upload exceeds size limit"
);
let timestamp = now().to_string();
let mut transcript = b"VNOX-CENTRAL-PROFILE-v1\0".to_vec();
transcript.extend_from_slice(method.as_str().as_bytes());
transcript.push(0);
transcript.extend_from_slice(path.as_bytes());
transcript.push(0);
transcript.extend_from_slice(timestamp.as_bytes());
transcript.push(0);
transcript.extend_from_slice(&Sha256::digest(&body));
let signature = identity
.signing_key()
.context("Unlock your identity to change your profile")?
.sign(&transcript);
let response = client()?
.request(method, format!("{CENTRAL_ORIGIN}{path}"))
.bearer_auth(&stored.refresh_secret)
.header("x-vnox-public-key", &identity.pubkey_hex)
.header("x-vnox-timestamp", timestamp)
.header("x-vnox-signature", hex::encode(signature.to_bytes()))
.header(reqwest::header::CONTENT_TYPE, content_type)
.body(body)
.send()
.await
.context("Cannot reach Central; profile was not changed")?;
if response.status() == reqwest::StatusCode::UNAUTHORIZED {
return Err(SignInRequired.into());
}
if !response.status().is_success() {
let error = response_json(response).await.unwrap_or_default();
bail!(match error.get("error").and_then(Value::as_str) {
Some("invalid_display_name") =>
"Display name must contain 1–64 characters without control characters",
Some("too_large") => "Photo is too large to upload",
Some("invalid_image" | "unsupported_type") =>
"Central could not read this photo; choose another PNG",
Some("try_later") => "Too many profile changes or Central is busy; retry shortly",
_ => "Central could not update your profile; retry shortly",
});
}
let value = response_json(response).await?;
let user = summary(&value, identity, false)?;
update_summary(identity, &stored, user.clone(), None)?;
Ok(user)
}
fn validate_proof(value: &Value, identity: &Identity) -> Result<Vec<u8>> {
let proof = value
.get("account_proof")
.context("Missing Central account proof")?;
let claims = hex::decode(field(proof, "claims")?).context("Invalid account proof")?;
ensure!(claims.len() <= 4096, "Account proof too large");
let claim: Value = serde_json::from_slice(&claims)?;
ensure!(
field(&claim, "public_key")? == identity.pubkey_hex,
"Central proof belongs to another local identity"
);
ensure!(
field(&claim, "audience")? == "vnox-gateway"
&& claim.get("version").and_then(Value::as_u64) == Some(1),
"Invalid Central proof audience or version"
);
ensure!(
uuid::Uuid::parse_str(field(&claim, "subject")?).is_ok()
&& uuid::Uuid::parse_str(field(&claim, "issuer")?).is_ok(),
"Invalid Central proof identity"
);
let issued = claim
.get("issued_at")
.and_then(Value::as_i64)
.context("Missing proof issue time")?;
let expires = claim
.get("expires_at")
.and_then(Value::as_i64)
.context("Missing proof expiry")?;
ensure!(
issued <= now()
&& expires > now()
&& expires
.checked_sub(issued)
.is_some_and(|ttl| ttl > 0 && ttl <= 600),
"Central account proof expired or has invalid lifetime"
);
ensure!(
hex::decode(field(proof, "signature")?).is_ok_and(|s| s.len() == 64),
"Invalid account proof signature encoding"
);
let bytes = serde_json::to_vec(proof)?;
ensure!(bytes.len() <= 8192, "Account proof too large");
Ok(bytes)
}
fn path() -> PathBuf {
dirs::data_dir()
.unwrap_or_else(|| PathBuf::from("."))
.join("vnox")
.join("account")
.join("central.json")
}
fn load(identity: &Identity) -> Result<Option<StoredAccount>> {
load_at(&path(), identity)
}
fn load_at(account_path: &std::path::Path, identity: &Identity) -> Result<Option<StoredAccount>> {
let file = match std::fs::File::open(account_path) {
Ok(f) => f,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(e.into()),
};
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
ensure!(
file.metadata()?.permissions().mode() & 0o077 == 0,
"Central account credentials must use private 0600 permissions"
);
}
ensure!(
file.metadata()?.len() <= MAX_RESPONSE as u64,
"Account credentials too large"
);
let stored: StoredAccount =
serde_json::from_reader(file).context("Invalid saved Central account; sign in again")?;
ensure!(stored.version == 1, "Unsupported account credentials");
if stored.public_key != identity.pubkey_hex {
return Ok(None);
}
Ok(Some(stored))
}
fn save(stored: &StoredAccount) -> Result<()> {
let _guard = STORE_LOCK
.lock()
.map_err(|_| anyhow::anyhow!("Account state is unavailable"))?;
save_unlocked(stored)?;
enrollment_changed();
Ok(())
}
fn save_unlocked(stored: &StoredAccount) -> Result<()> {
save_at(&path(), stored)
}
fn save_at(path: &std::path::Path, stored: &StoredAccount) -> Result<()> {
let directory = path.parent().context("Missing credential directory")?;
let mut builder = std::fs::DirBuilder::new();
builder.recursive(true);
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt;
builder.mode(0o700);
}
builder.create(directory)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
ensure!(
std::fs::metadata(directory)?.permissions().mode() & 0o077 == 0,
"Central credential directory must use private 0700 permissions"
);
}
let temporary = directory.join(format!("{}.tmp", uuid::Uuid::new_v4()));
let mut options = std::fs::OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let result = (|| -> Result<()> {
use std::io::Write;
let mut file = options.open(&temporary)?;
file.write_all(&serde_json::to_vec(stored)?)?;
file.sync_all()?;
std::fs::rename(&temporary, path)?;
#[cfg(unix)]
std::fs::File::open(directory)?.sync_all()?;
Ok(())
})();
let _ = std::fs::remove_file(&temporary);
result
}
fn clear() -> Result<()> {
match std::fs::remove_file(path()) {
Ok(()) => {
enrollment_changed();
Ok(())
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(e.into()),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn response(identity: &Identity, issued: i64, expires: i64) -> Value {
let claim = json!({"version":1,"issuer":uuid::Uuid::new_v4().to_string(),"subject":uuid::Uuid::new_v4().to_string(),"public_key":identity.pubkey_hex,"audience":"vnox-gateway","issued_at":issued,"expires_at":expires});
json!({"account_proof":{"claims":hex::encode(serde_json::to_vec(&claim).unwrap()),"signature":"00".repeat(64)}})
}
#[test]
fn refreshed_website_avatar_is_persisted_and_stale_enrollment_cannot_restore_it() {
let identity = crate::identity::generate("profile");
let directory =
std::env::temp_dir().join(format!("vnox-profile-test-{}", uuid::Uuid::new_v4()));
let path = directory.join("central.json");
let original = StoredAccount {
version: 1,
public_key: identity.pubkey_hex.clone(),
refresh_secret: "01".repeat(32),
user: AccountSummary {
user_id: uuid::Uuid::new_v4().to_string(),
handle: "profile".into(),
display_name: "Old Name".into(),
avatar_url: Some("/v1/avatars/old".into()),
profile_complete: false,
},
};
save_at(&path, &original).unwrap();
let mut fresh = original.user.clone();
fresh.avatar_url = Some("/v1/avatars/new".into());
fresh.display_name = "New Name".into();
update_summary_at(&path, &identity, &original, fresh.clone()).unwrap();
assert_eq!(load_at(&path, &identity).unwrap().unwrap().user, fresh);
let mut replacement = original;
replacement.refresh_secret = "02".repeat(32);
save_at(&path, &replacement).unwrap();
let mut old_request = replacement.user.clone();
old_request.avatar_url = Some("/v1/avatars/stale".into());
let mut stale = StoredAccount {
version: 1,
public_key: identity.pubkey_hex.clone(),
refresh_secret: "01".repeat(32),
user: replacement.user.clone(),
};
assert!(update_summary_at(&path, &identity, &stale, old_request.clone()).is_err());
assert_eq!(
load_at(&path, &identity).unwrap().unwrap().user,
replacement.user
);
stale.refresh_secret = replacement.refresh_secret;
std::fs::remove_file(&path).unwrap();
assert!(update_summary_at(&path, &identity, &stale, old_request).is_err());
assert!(
!path.exists(),
"sign-out must not be undone by late refresh"
);
std::fs::remove_dir(directory).unwrap();
}
#[test]
fn queued_revocation_atomically_disables_admission_and_preserves_retry_secret() {
let directory =
std::env::temp_dir().join(format!("vnox-revoke-test-{}", uuid::Uuid::new_v4()));
std::fs::create_dir(&directory).unwrap();
let active = directory.join("central.json");
std::fs::write(&active, b"retry secret").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&active, std::fs::Permissions::from_mode(0o600)).unwrap();
}
let tombstone = queue_revocation(&active).unwrap();
assert!(!active.exists());
assert_eq!(std::fs::read(&tombstone).unwrap(), b"retry secret");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(
std::fs::metadata(&tombstone).unwrap().permissions().mode() & 0o077,
0
);
}
std::fs::remove_file(tombstone).unwrap();
std::fs::remove_dir(directory).unwrap();
}
#[test]
fn rejects_other_identity_expiry_and_overlong_proof() {
let identity = crate::identity::generate("test");
let t = now();
assert!(validate_proof(&response(&identity, t, t + 600), &identity).is_ok());
assert!(
validate_proof(
&response(&identity, t, t + 600),
&crate::identity::generate("other")
)
.is_err()
);
assert!(validate_proof(&response(&identity, t - 601, t - 1), &identity).is_err());
assert!(validate_proof(&response(&identity, t, t + 601), &identity).is_err());
assert!(validate_proof(&response(&identity, t + 60, t + 600), &identity).is_err());
}
}

47
src/net/forum.rs Normal file
View file

@ -0,0 +1,47 @@
//! Capability-gated forum packets. Errors retain request correlation and never cancel voice joins.
use super::{framing, payloads::PID_FORUM_REQUEST, types::NetEvent, wire};
use tokio::io::AsyncWrite;
use tokio::sync::mpsc;
pub fn is_mutation(request: &wire::ForumRequest) -> bool {
matches!(wire::ForumOperation::try_from(request.operation), Ok(wire::ForumOperation::Create | wire::ForumOperation::Reply))
}
pub async fn unsupported(request: &wire::ForumRequest, events: &mpsc::Sender<NetEvent>) {
error(request, "This server does not support forums yet.", events).await;
}
pub async fn error(request: &wire::ForumRequest, message: &str, events: &mpsc::Sender<NetEvent>) {
let _ = events.send(NetEvent::ForumResult(wire::ForumResult {
request_id: request.request_id.clone(), operation: request.operation,
channel_id: request.channel_id.clone(), topic_id: request.topic_id.clone(),
error_code: u32::MAX, error: message.into(),
..Default::default()
})).await;
}
pub async fn write(stream: &mut (impl AsyncWrite + Unpin), seq: &mut u32, request: &wire::ForumRequest) -> anyhow::Result<()> {
framing::write(stream, PID_FORUM_REQUEST, seq, &wire::encode(request)?).await
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn unsupported_server_returns_correlated_forum_error_without_join_error() {
let (tx, mut rx) = mpsc::channel(1);
let request = wire::ForumRequest { request_id: "request".into(), channel_id: "forum".into(), topic_id: "topic".into(), operation: wire::ForumOperation::Open as i32, ..Default::default() };
unsupported(&request, &tx).await;
let NetEvent::ForumResult(result) = rx.recv().await.unwrap() else { panic!("forum errors must stay separate from join errors") };
assert_eq!(result.request_id, "request"); assert_eq!(result.channel_id, "forum"); assert_eq!(result.topic_id, "topic"); assert_ne!(result.error_code, 0);
}
#[tokio::test]
async fn request_wire_keeps_topic_message_and_pagination_fields() {
let request = wire::ForumRequest { request_id: "request".into(), operation: wire::ForumOperation::Create as i32, channel_id: "forum".into(), topic_id: "topic".into(), message_id: "message".into(), title: "Title".into(), content: "First post".into(), offset: 12, limit: 20 };
let (mut sender, mut receiver) = tokio::io::duplex(4096);
write(&mut sender, &mut 0, &request).await.unwrap();
let packet = framing::read(&mut receiver).await.unwrap();
assert_eq!(packet.packet_id, PID_FORUM_REQUEST);
let decoded: wire::ForumRequest = wire::decode(&packet.payload).unwrap();
assert_eq!(decoded, request); assert!(is_mutation(&decoded));
}
}

View file

@ -8,8 +8,8 @@ use super::payloads::*;
use super::trust::TransportError;
use crate::identity::Identity;
const SERVER_HELLO_CONTEXT: &[u8] = b"VNOX-LNEx-v3-server-hello\0";
const CLIENT_AUTH_CONTEXT: &[u8] = b"VNOX-LNEx-v3-client-auth\0";
const SERVER_HELLO_CONTEXT: &[u8] = b"VNOX-LNEx-v4-server-hello\0";
const CLIENT_AUTH_CONTEXT: &[u8] = b"VNOX-LNEx-v4-client-auth\0";
/// Bytes signed by the server identity: context, TLS exporter, HELLO without signature.
pub fn server_hello_transcript(binding: &[u8], unsigned_hello: &[u8]) -> Vec<u8> {
@ -40,6 +40,11 @@ pub struct Outcome {
pub session_id: String,
pub node_name: String,
pub private_mode: bool,
pub node_admin: bool,
pub live_profiles: bool,
pub node_settings: bool,
pub channel_structure: bool,
pub forums: bool,
/// Lower-case hex Ed25519 identity of the server.
pub server_identity: String,
}
@ -56,6 +61,27 @@ pub async fn run(
binding: &[u8],
trust_key: &str,
expected_identity: Option<&str>,
) -> Result<Outcome> {
run_inner(
stream,
identity,
seq,
binding,
trust_key,
expected_identity,
None,
)
.await
}
async fn run_inner(
stream: &mut (impl tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin),
identity: &Identity,
seq: &mut u32,
binding: &[u8],
trust_key: &str,
expected_identity: Option<&str>,
supplied_proof: Option<Vec<u8>>,
) -> Result<Outcome> {
// HELLO
let pkt = framing::read(stream).await?;
@ -117,11 +143,20 @@ pub async fn run(
.ok_or_else(|| anyhow!("no signing key"))?;
use ed25519_dalek::Signer;
let account_proof = match supplied_proof {
Some(proof) => proof,
None => crate::net::account::admission_proof(identity).await?,
};
anyhow::ensure!(
!account_proof.is_empty(),
"Central account sign-in required"
);
let mut auth = AuthPayload {
client_pubkey: sk.verifying_key().to_bytes().to_vec(),
nickname: identity.nickname.clone(),
lnex_version: LNEX_VERSION.into(),
signature: Vec::new(),
account_proof,
};
let transcript = client_auth_transcript(binding, &signed_hello, &wire::encode(&auth)?);
auth.signature = sk.sign(&transcript).to_bytes().to_vec();
@ -154,6 +189,11 @@ pub async fn run(
session_id: sess.session_id,
node_name: hello.node_name,
private_mode: hello.private_mode,
node_admin: sess.node_admin,
live_profiles: sess.live_profiles,
node_settings: sess.node_settings,
channel_structure: sess.channel_structure,
forums: sess.forums,
server_identity,
})
}
@ -164,6 +204,26 @@ mod tests {
use ed25519_dalek::{Signer, SigningKey};
use tokio::io::AsyncWriteExt;
async fn run_for_test(
stream: &mut (impl tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin),
identity: &Identity,
seq: &mut u32,
binding: &[u8],
trust_key: &str,
expected_identity: Option<&str>,
) -> Result<Outcome> {
run_inner(
stream,
identity,
seq,
binding,
trust_key,
expected_identity,
Some(b"test-account-proof".to_vec()),
)
.await
}
/// Scripted gateway: sends a HELLO signed over `hello_binding` and returns the AUTH it gets.
async fn fake_server(
mut stream: tokio::io::DuplexStream,
@ -199,6 +259,8 @@ mod tests {
session_id: "session-1".into(),
token: "token".into(),
expires_at: 0,
node_admin: false,
live_profiles: false,
};
framing::write(
&mut stream,
@ -221,9 +283,9 @@ mod tests {
async fn authenticated_handshake_returns_server_identity_and_binds_signature() {
let server_key = SigningKey::generate(&mut rand::rng());
let (mut client, server) = tokio::io::duplex(8192);
let task = tokio::spawn(fake_server(server, server_key.clone(), [9; 32], "v3", true));
let task = tokio::spawn(fake_server(server, server_key.clone(), [9; 32], "v4", true));
let mut seq = 0;
let outcome = run(&mut client, &identity(), &mut seq, &[9; 32], "h:7600", None)
let outcome = run_for_test(&mut client, &identity(), &mut seq, &[9; 32], "h:7600", None)
.await
.unwrap();
assert_eq!(outcome.session_id, "session-1");
@ -233,6 +295,7 @@ mod tests {
);
// The AUTH signature is valid for this connection and invalid for any other one.
let (auth, signed_hello) = task.await.unwrap();
assert_eq!(auth.account_proof, b"test-account-proof");
let client_public = ed25519_dalek::VerifyingKey::from_bytes(
&auth.client_pubkey.clone().try_into().unwrap(),
)
@ -263,9 +326,9 @@ mod tests {
let server_key = SigningKey::generate(&mut rand::rng());
let (mut client, server) = tokio::io::duplex(8192);
// The relay forwards a HELLO signed for a different TLS session.
tokio::spawn(fake_server(server, server_key, [1; 32], "v3", false));
tokio::spawn(fake_server(server, server_key, [1; 32], "v4", false));
let mut seq = 0;
let error = run(&mut client, &identity(), &mut seq, &[2; 32], "h:7600", None)
let error = run_for_test(&mut client, &identity(), &mut seq, &[2; 32], "h:7600", None)
.await
.unwrap_err();
assert!(error.to_string().contains("signature verification failed"));
@ -276,9 +339,9 @@ mod tests {
async fn changed_server_identity_is_blocked_before_auth() {
let server_key = SigningKey::generate(&mut rand::rng());
let (mut client, server) = tokio::io::duplex(8192);
tokio::spawn(fake_server(server, server_key, [3; 32], "v3", false));
tokio::spawn(fake_server(server, server_key, [3; 32], "v4", false));
let mut seq = 0;
let error = run(
let error = run_for_test(
&mut client,
&identity(),
&mut seq,
@ -301,12 +364,59 @@ mod tests {
let (mut client, server) = tokio::io::duplex(8192);
tokio::spawn(fake_server(server, server_key, [4; 32], "v2", false));
let mut seq = 0;
let error = run(&mut client, &identity(), &mut seq, &[4; 32], "h:7600", None)
let error = run_for_test(&mut client, &identity(), &mut seq, &[4; 32], "h:7600", None)
.await
.unwrap_err();
assert!(matches!(
error.downcast_ref::<TransportError>(),
Some(TransportError::ProtocolMismatch(m)) if m.contains("v2") && m.contains("v3")
Some(TransportError::ProtocolMismatch(m)) if m.contains("v2") && m.contains("v4")
));
}
#[tokio::test]
async fn empty_account_proof_is_rejected_before_auth() {
let key = SigningKey::generate(&mut rand::rng());
let (mut client, server) = tokio::io::duplex(8192);
let task = tokio::spawn(fake_server(server, key, [9; 32], "v4", false));
let mut seq = 0;
let error = run_inner(
&mut client,
&identity(),
&mut seq,
&[9; 32],
"h:7600",
None,
Some(Vec::new()),
)
.await
.unwrap_err();
assert!(
error
.to_string()
.contains("Central account sign-in required")
);
assert_eq!(seq, 0);
drop(client);
task.await.unwrap();
}
}
#[cfg(test)]
mod capability_tests {
use super::*;
#[test]
fn legacy_sessions_do_not_advertise_admin_and_new_flag_roundtrips() {
let legacy: SessionPayload = wire::decode(&[10, 1, b's', 18, 1, b't']).unwrap();
assert!(!legacy.node_admin);
assert!(!legacy.live_profiles);
let mut privileged = legacy;
privileged.node_admin = true;
privileged.live_profiles = true;
let bytes = wire::encode(&privileged).unwrap();
assert!(wire::decode::<SessionPayload>(&bytes).unwrap().node_admin);
assert!(
wire::decode::<SessionPayload>(&bytes)
.unwrap()
.live_profiles
);
}
}

View file

@ -8,6 +8,11 @@ use super::super::super::types::{ChannelListItem as InfoChannelListItem, ChatMsg
pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Result<()> {
match pid {
PID_ATTACHMENT_RESULT => {
let _ = tx
.send(NetEvent::AttachmentResult(wire::decode(payload)?))
.await;
}
PID_CHANNEL_STATE => {
let p: ChannelStatePayload = wire::decode(payload)?;
let _ = tx
@ -22,10 +27,14 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
user_id: m.user_id,
nickname: m.nickname,
in_voice: m.in_voice,
account_id: m.account_id,
avatar_url: m.avatar_url,
})
.collect(),
voice_endpoint: p.voice_endpoint,
guild_id: p.guild_id,
parent_id: p.parent_id,
position: p.position,
})
.await;
}
@ -37,6 +46,18 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
channel_name: p.channel_name,
kind: p.kind,
guild_id: p.guild_id,
parent_id: p.parent_id,
position: p.position,
})
.await;
}
PID_CHANNEL_EDIT => {
let p: ChannelEditPayload = wire::decode(payload)?;
let _ = tx
.send(NetEvent::ChannelEdited {
channel_id: p.channel_id,
channel_name: p.channel_name,
parent_id: p.parent_id, position: p.position,
})
.await;
}
@ -60,6 +81,7 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
channel_name: c.channel_name,
kind: c.kind,
guild_id: c.guild_id,
parent_id: c.parent_id, position: c.position,
})
.collect(),
})
@ -102,6 +124,8 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
let p: UserJoinPayload = wire::decode(payload)?;
let _ = tx
.send(NetEvent::UserJoin {
account_id: p.account_id,
avatar_url: p.avatar_url,
channel_id: p.channel_id,
user_id: p.user_id,
nickname: p.nickname,
@ -160,3 +184,59 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Re
}
Ok(())
}
#[cfg(test)]
mod profile_tests {
use super::*;
use prost::Message;
#[tokio::test]
async fn central_account_profile_reaches_client_join_event() {
let (tx, mut rx) = mpsc::channel(1);
let message = UserJoinPayload {
channel_id: "general".into(),
user_id: "device-key".into(),
nickname: "Central Name".into(),
account_id: "account-id".into(),
avatar_url: "/v1/avatars/default/account-id".into(),
};
handle(PID_USER_JOIN, &message.encode_to_vec(), &tx)
.await
.unwrap();
match rx.recv().await.unwrap() {
NetEvent::UserJoin {
user_id,
account_id,
avatar_url,
nickname,
..
} => {
assert_eq!(user_id, "device-key");
assert_eq!(account_id, "account-id");
assert_eq!(nickname, "Central Name");
assert_eq!(avatar_url, "/v1/avatars/default/account-id");
}
other => panic!("unexpected {other:?}"),
}
}
}
#[cfg(test)]
mod channel_edit_tests {
use super::*;
#[tokio::test]
async fn existing_channel_edit_packet_reaches_named_event() {
let (tx, mut rx) = mpsc::channel(1);
let bytes = wire::encode(&ChannelEditPayload {
channel_id: "global".into(),
channel_name: "Renamed".into(),
})
.unwrap();
super::super::incoming(PID_CHANNEL_EDIT, &bytes, &tx)
.await
.unwrap();
assert!(
matches!(rx.recv().await.unwrap(),NetEvent::ChannelEdited{channel_id,channel_name} if channel_id=="global" && channel_name=="Renamed")
);
}
}

View file

@ -11,6 +11,13 @@ mod social;
pub async fn incoming(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) -> Result<()> {
match pid {
PID_FORUM_RESULT => { let _ = tx.send(NetEvent::ForumResult(crate::net::wire::decode(payload)?)).await; }
PID_FORUM_CHANGED => { let _ = tx.send(NetEvent::ForumChanged(crate::net::wire::decode(payload)?)).await; }
PID_PROFILE_UPDATED => {
let _ = tx
.send(NetEvent::ProfileUpdated(crate::net::wire::decode(payload)?))
.await;
}
PID_MEDIA_EVENT => {
let event = crate::net::wire::decode(payload)?;
let _ = tx.send(NetEvent::MediaEvent(event)).await;
@ -36,7 +43,9 @@ pub async fn incoming(pid: u16, payload: &[u8], tx: &mpsc::Sender<NetEvent>) ->
.await;
}
PID_CHANNEL_CREATE
PID_ATTACHMENT_RESULT
| PID_CHANNEL_CREATE
| PID_CHANNEL_EDIT
| PID_CHANNEL_DELETE
| PID_CHANNEL_LIST
| PID_CHANNEL_STATE

View file

@ -1,3 +1,5 @@
pub mod account;
pub mod forum;
pub mod framing;
pub mod handshake;
mod internal;

View file

@ -8,6 +8,7 @@ pub type JoinChannelPayload = crate::net::wire::JoinChannel;
pub type LeaveChannelPayload = crate::net::wire::LeaveChannel;
pub type ChannelStatePayload = crate::net::wire::ChannelState;
pub type ChannelCreatePayload = crate::net::wire::ChannelCreate;
pub type ChannelEditPayload = crate::net::wire::ChannelEdit;
pub type ChannelDeletePayload = crate::net::wire::ChannelDelete;
pub type ChannelListPayload = crate::net::wire::ChannelList;
pub type ChannelListItem = crate::net::wire::ChannelListItem;

View file

@ -13,6 +13,7 @@ pub const PID_CHANNEL_STATE: u16 = 0x0032;
pub const PID_CHANNEL_CREATE: u16 = 0x0033;
pub const PID_CHANNEL_DELETE: u16 = 0x0034;
pub const PID_CHANNEL_LIST: u16 = 0x0035;
pub const PID_CHANNEL_EDIT: u16 = 0x0036;
pub const PID_USER_JOIN: u16 = 0x0040;
pub const PID_USER_LEAVE: u16 = 0x0041;
pub const PID_DM_START: u16 = 0x0060;
@ -67,7 +68,7 @@ pub const PID_FRIEND_EVENT: u16 = 0x0158;
pub const PID_ERROR: u16 = 0x00F0;
pub const PID_DISCONNECT: u16 = 0x00FF;
pub const LNEX_VERSION: &str = "v3";
pub const LNEX_VERSION: &str = "v4";
pub const HDR_SIZE: usize = 12;
pub const MAX_PAYLOAD: u32 = 4 * 1024 * 1024;
@ -93,3 +94,18 @@ pub const PID_WEBHOOK_ERROR_RESULT: u16 = 0x0206;
pub const PID_VOICE_SESSION: u16 = 0x0012;
pub const PID_VOICE_STATE: u16 = 0x0011;
pub const PID_ATTACHMENT_UPLOAD: u16 = 0x0220;
pub const PID_ATTACHMENT_FETCH: u16 = 0x0221;
pub const PID_ATTACHMENT_RESULT: u16 = 0x0222;
pub const PID_PROFILE_UPDATE: u16 = 0x0042;
pub const PID_PROFILE_UPDATED: u16 = 0x0043;
pub const PID_FORUM_REQUEST: u16 = 0x0240;
pub const PID_FORUM_RESULT: u16 = 0x0241;
pub const PID_FORUM_CHANGED: u16 = 0x0242;
pub const PID_NODE_SETTINGS_REQUEST: u16 = 0x0230;
pub const PID_NODE_SETTINGS_RESULT: u16 = 0x0231;
pub const PID_CLIENT_FEATURES: u16 = 0x0232;

View file

@ -16,7 +16,7 @@ use crate::net::{
};
use super::super::switch::ReconnectRequested;
use super::{VoiceState, handle_cmd};
use super::{VoiceState, handle_cmd, profile};
pub async fn session_loop(
identity: &Identity,
@ -60,24 +60,62 @@ pub async fn session_loop(
let session_id = outcome.session_id;
let node_name = outcome.node_name;
let private_mode = outcome.private_mode;
let live_profiles = outcome.live_profiles;
let forums = outcome.forums;
let _ = event_tx
.send(NetEvent::Connected {
session_id: session_id.clone(),
node_name,
restored,
private_mode,
node_admin: outcome.node_admin,
node_settings: outcome.node_settings,
channel_structure: outcome.channel_structure,
forums: outcome.forums,
})
.await;
for channel_id in channels.clone() {
framing::write(
if outcome.node_settings || outcome.channel_structure || outcome.forums {
framing::write(&mut stream, PID_CLIENT_FEATURES, &mut seq, &wire::encode(&wire::ClientFeatures {
node_settings: outcome.node_settings, channel_structure: outcome.channel_structure, forums: outcome.forums,
})?).await?;
}
let node_settings = outcome.node_settings;
let mut profile_updates = crate::net::account::subscribe_profiles();
let mut last_profile_proof = None;
let mut pending_profile_actions = std::collections::VecDeque::new();
if live_profiles
&& let Some(update) = crate::net::account::latest_profile()
&& update.public_key == identity.pubkey_hex
&& update.epoch == crate::net::account::enrollment_epoch()
&& let Some(proof) = update.proof
{
profile::send(
live_profiles,
&mut stream,
PID_JOIN_CHANNEL,
&mut seq,
&wire::encode(&JoinChannelPayload { channel_id })?,
proof,
&mut last_profile_proof,
)
.await?;
}
let profile_ready = !live_profiles || last_profile_proof.is_some();
for channel_id in channels.clone() {
if profile_ready {
framing::write(
&mut stream,
PID_JOIN_CHANNEL,
&mut seq,
&wire::encode(&JoinChannelPayload { channel_id })?,
)
.await?;
} else {
profile::enqueue(
&mut pending_profile_actions,
NetCommand::JoinChannel { channel_id },
);
}
}
let (reader, mut stream) = tokio::io::split(stream);
let mut incoming = framing::io::Reader::new(reader);
@ -89,8 +127,48 @@ pub async fn session_loop(
let mut ping_tick = interval(Duration::from_secs(2));
ping_tick.set_missed_tick_behavior(MissedTickBehavior::Delay);
let mut last_profile_refresh = profile_ready.then(std::time::Instant::now);
let mut profile_job = profile::RefreshTask::default();
if live_profiles && !profile_ready {
profile_job.task = Some(profile::refresh(identity));
}
loop {
tokio::select! {
changed = profile_updates.changed(), if live_profiles => {
if changed.is_ok() {
let update = profile_updates.borrow_and_update().clone();
if let Some(update) = update
&& update.public_key == identity.pubkey_hex && update.epoch == crate::net::account::enrollment_epoch() {
if let Some(proof) = update.proof {
profile::send(live_profiles, &mut stream,&mut seq,proof,&mut last_profile_proof).await?;
last_profile_refresh = Some(std::time::Instant::now());
profile::actions(&mut stream,&mut seq,identity,channels,&mut pending_profile_actions).await?;
} else {
last_profile_refresh = None;
if profile_job.task.is_none() {profile_job.task=Some(profile::refresh(identity));}
}
}
}
}
result = async { profile_job.task.as_mut().expect("guarded profile job").await }, if live_profiles && profile_job.task.is_some() => {
profile_job.task = None;
let latest = crate::net::account::latest_profile().filter(|update|update.public_key == identity.pubkey_hex && update.epoch == crate::net::account::enrollment_epoch());
match result {
Ok(Ok(proof)) => {
if latest.as_ref().is_some_and(|update|update.proof.is_none()) {
// A mutation committed after this HTTP refresh: obtain its newer proof.
last_profile_refresh=None;profile_job.task=Some(profile::refresh(identity));continue;
}
let proof = latest.and_then(|update|update.proof).unwrap_or(proof);
profile::send(live_profiles, &mut stream,&mut seq,proof,&mut last_profile_proof).await?;
}
_ => {
let _=event_tx.send(NetEvent::ProfileWarning {message:"Central profile refresh failed; using last verified profile".into(),rejected_join:None}).await;
}
}
last_profile_refresh=Some(std::time::Instant::now());
profile::actions(&mut stream,&mut seq,identity,channels,&mut pending_profile_actions).await?;
}
_ = voice_tick.tick() => { if let Some(voice)=voice_state.as_mut() {voice.keep_alive().await?;} }
_ = ping_tick.tick() => {
let ts = now_ms();
@ -117,6 +195,11 @@ pub async fn session_loop(
}
continue;
}
if pkt.packet_id == PID_NODE_SETTINGS_RESULT && node_settings {
let result = wire::decode(&pkt.payload)?;
let _ = event_tx.send(NetEvent::NodeSettingsResult { session_id: session_id.clone(), result }).await;
continue;
}
if pkt.packet_id == PID_CHANNEL_STATE
&& let Ok(p) = wire::decode::<ChannelStatePayload>(&pkt.payload)
&& p.kind == "voice" && !p.voice_endpoint.is_empty()
@ -129,13 +212,26 @@ pub async fn session_loop(
internal::dispatch::incoming(pkt.packet_id, &pkt.payload, event_tx).await?;
}
cmd = cmd_rx.recv() => {
let cmd = match cmd {
Some(command) => match command_for_session(command, &session_id) {
Some(command) => Some(command),
None => continue,
},
None => None,
};
match cmd {
Some(NetCommand::AttachmentFetch { request_id, channel_id, attachment_id }) => {
framing::write(&mut stream, PID_ATTACHMENT_FETCH, &mut seq,
&wire::encode(&wire::AttachmentFetch { request_id, channel_id, attachment_id })?).await?;
}
None | Some(NetCommand::Disconnect) => {
profile::cancel(&mut profile_job, &mut pending_profile_actions);
let _ = framing::write(&mut stream, PID_DISCONNECT, &mut seq,
&wire::encode(&Disconnect {reason: "bye".into()})?).await;
return Ok(());
}
Some(NetCommand::Connect { address, auto_reconnect }) => {
profile::cancel(&mut profile_job, &mut pending_profile_actions);
warn!("connect while connected to {address}, reconnecting");
if channels.is_empty() {
*channels = vec!["general".into()];
@ -145,43 +241,62 @@ pub async fn session_loop(
auto_reconnect,
}));
}
Some(NetCommand::JoinChannel { channel_id }) => {
track_channel(channels, &channel_id);
framing::write(&mut stream, PID_JOIN_CHANNEL, &mut seq,
&wire::encode(&JoinChannelPayload { channel_id })?).await?;
Some(command @ (NetCommand::JoinChannel { .. } | NetCommand::SendChat { .. } | NetCommand::AttachmentUpload { .. } | NetCommand::ForumRequest(_))) => {
if let NetCommand::ForumRequest(request) = &command {
if !forums { crate::net::forum::unsupported(request, event_tx).await; continue; }
if !crate::net::forum::is_mutation(request) { crate::net::forum::write(&mut stream, &mut seq, request).await?; continue; }
}
let rejected_join = if let NetCommand::JoinChannel {channel_id}=&command {Some(channel_id.clone())} else {None};
let upload = if let NetCommand::AttachmentUpload {request_id,channel_id,data}=&command {
if data.is_empty() || data.len()>3*1024*1024 || request_id.len()>128 || channel_id.len()>128 {
let _=event_tx.send(NetEvent::AttachmentResult(wire::AttachmentResult {request_id:request_id.clone(),channel_id:channel_id.clone(),error:"invalid image upload (maximum 3 MiB)".into(),..Default::default()})).await;continue;
}
Some((request_id.clone(),channel_id.clone()))
} else {None};
let forum_request = if let NetCommand::ForumRequest(request) = &command { Some(wire::ForumRequest { request_id:request.request_id.clone(),operation:request.operation,channel_id:request.channel_id.clone(),topic_id:request.topic_id.clone(),..Default::default() }) } else { None };
if !profile::enqueue(&mut pending_profile_actions, command) {
if let Some(request) = forum_request { crate::net::forum::error(&request, "Too many pending profile actions; retry shortly", event_tx).await; continue; }
if let Some((request_id,channel_id))=upload {
let _=event_tx.send(NetEvent::AttachmentResult(wire::AttachmentResult {request_id,channel_id,error:"Too many pending profile actions; retry shortly".into(),..Default::default()})).await;
} else {let _=event_tx.send(NetEvent::ProfileWarning {message:"Too many pending profile actions; retry shortly".into(),rejected_join}).await;}
continue;
}
if profile::due(live_profiles, last_profile_refresh) {
if profile_job.task.is_none() {profile_job.task=Some(profile::refresh(identity));}
} else {
profile::actions(&mut stream,&mut seq,identity,channels,&mut pending_profile_actions).await?;
}
}
Some(NetCommand::LeaveChannel { channel_id }) => {
profile::cancel_channel(&mut pending_profile_actions, &channel_id);
channels.retain(|c| c != &channel_id);
if voice_state.as_ref().and_then(|value|value.channel_id())==Some(channel_id.as_str()) {voice_state=None;voice_endpoint=None;}
framing::write(&mut stream, PID_LEAVE_CHANNEL, &mut seq,
&wire::encode(&LeaveChannelPayload { channel_id })?).await?;
}
Some(NetCommand::ChannelCreate { channel_id, channel_name, kind, guild_id }) => {
Some(NetCommand::ChannelCreate { channel_id, channel_name, kind, guild_id, parent_id, position }) => {
let payload = wire::encode(&ChannelCreatePayload {
channel_id,
channel_name,
kind,
guild_id,
guild_id, parent_id, position,
})?;
framing::write(&mut stream, PID_CHANNEL_CREATE, &mut seq, &payload).await?;
}
Some(NetCommand::ChannelEdit { channel_id, channel_name, parent_id, position }) => {
let payload = wire::encode(&ChannelEditPayload { channel_id, channel_name, parent_id, position })?;
framing::write(&mut stream, PID_CHANNEL_EDIT, &mut seq, &payload).await?;
}
Some(NetCommand::ChannelDelete { channel_id }) => {
let payload = wire::encode(&ChannelDeletePayload { channel_id })?;
framing::write(&mut stream, PID_CHANNEL_DELETE, &mut seq, &payload).await?;
}
Some(NetCommand::NodeSettingsRequest(request)) => {
if node_settings { framing::write(&mut stream, PID_NODE_SETTINGS_REQUEST, &mut seq, &wire::encode(&request)?).await?; }
}
Some(NetCommand::ChannelList) => {
framing::write(&mut stream, PID_CHANNEL_LIST, &mut seq, b"").await?;
}
Some(NetCommand::SendChat { channel_id, content, reply_to }) => {
let msg = ChatMessagePayload {
message_id: uuid_v4(), channel_id,
sender_id: identity.pubkey_hex.clone(),
content, timestamp: now_ms(),
edited: false,
reply_to,
};
framing::write(&mut stream, PID_CHAT_MESSAGE, &mut seq, &wire::encode(&msg)?).await?;
}
Some(NetCommand::SendVoice { channel_id, voice_seq: voice_pkt_seq, timestamp, opus_data }) => {
if let Some(voice)=voice_state.as_mut(){voice.send(Some(channel_id), voice_pkt_seq, timestamp, &opus_data).await?;}
}
@ -207,8 +322,73 @@ pub(super) fn uuid_v4() -> String {
uuid::Uuid::new_v4().to_string()
}
fn track_channel(channels: &mut Vec<String>, channel_id: &str) {
pub(super) fn track_channel(channels: &mut Vec<String>, channel_id: &str) {
if !channels.iter().any(|c| c == channel_id) {
channels.push(channel_id.to_string());
}
}
/// UI tasks can outlive a node switch. Only the original authenticated session may
/// consume their channel mutation; wrappers cannot smuggle a connect or arbitrary command.
fn command_for_session(command: NetCommand, current: &str) -> Option<NetCommand> {
match command {
NetCommand::ForSession {
session_id,
command,
} => (session_id == current
&& matches!(
&*command,
NetCommand::ForumRequest(_)
| NetCommand::JoinChannel { .. }
| NetCommand::ChannelCreate { .. }
| NetCommand::ChannelEdit { .. }
| NetCommand::ChannelDelete { .. }
| NetCommand::NodeSettingsRequest(_)
))
.then_some(*command),
command => Some(command),
}
}
#[cfg(test)]
mod session_fence_tests {
use super::*;
#[test]
fn admin_mutations_survive_only_the_session_that_prepared_them() {
for current in ["original-session", "new-session-after-switch"] {
let commands = [
NetCommand::ChannelCreate {
channel_id: "global".into(),
channel_name: "Global".into(),
kind: "text".into(),
guild_id: None,
},
NetCommand::ChannelEdit {
channel_id: "global".into(),
channel_name: "Renamed".into(),
},
NetCommand::ChannelDelete {
channel_id: "global".into(),
},
];
for command in commands {
let command = NetCommand::ForSession {
session_id: "original-session".into(),
command: Box::new(command),
};
assert_eq!(
command_for_session(command, current).is_some(),
current == "original-session"
);
}
}
let command = NetCommand::ForSession {
session_id: "original-session".into(),
command: Box::new(NetCommand::Connect {
address: "another-node".into(),
auto_reconnect: true,
}),
};
assert!(command_for_session(command, "original-session").is_none());
}
}

View file

@ -1,4 +1,5 @@
mod core;
mod profile;
mod social;
mod voice;

View file

@ -0,0 +1,373 @@
//! Coalesced profile refresh helpers. HTTP runs in a separate task, never in the UDP loop.
use crate::{
identity::Identity,
net::{framing, payloads::*, types::NetCommand, wire},
};
use anyhow::{Context, Result};
use std::collections::VecDeque;
use std::time::{Duration, Instant};
use tokio::io::{AsyncWrite, AsyncWriteExt};
#[derive(Default)]
pub(super) struct RefreshTask {
pub task: Option<tokio::task::JoinHandle<Result<Vec<u8>>>>,
}
impl Drop for RefreshTask {
fn drop(&mut self) {
if let Some(task) = self.task.take() {
task.abort();
}
}
}
pub(super) fn cancel(task: &mut RefreshTask, pending: &mut VecDeque<NetCommand>) {
if let Some(task) = task.task.take() {
task.abort();
}
pending.clear();
}
pub(super) fn cancel_channel(pending: &mut VecDeque<NetCommand>, channel: &str) {
pending.retain(|action| !matches!(action, NetCommand::JoinChannel {channel_id} | NetCommand::SendChat {channel_id,..} | NetCommand::AttachmentUpload {channel_id,..} if channel_id == channel));
}
fn bytes(command: &NetCommand) -> usize {
match command {
NetCommand::AttachmentUpload {
data,
request_id,
channel_id,
} => data.len() + request_id.len() + channel_id.len(),
NetCommand::SendChat {
content,
channel_id,
reply_to,
} => content.len() + channel_id.len() + reply_to.as_ref().map_or(0, String::len),
NetCommand::JoinChannel { channel_id } => channel_id.len(),
NetCommand::ForumRequest(request) => request.request_id.len() + request.channel_id.len() + request.topic_id.len() + request.message_id.len() + request.title.len() + request.content.len(),
_ => 0,
}
}
pub(super) fn enqueue(pending: &mut VecDeque<NetCommand>, command: NetCommand) -> bool {
if let NetCommand::JoinChannel {channel_id}=&command
&& pending.iter().any(|action|matches!(action, NetCommand::JoinChannel {channel_id:queued} if queued==channel_id)) {return true;}
if pending.len() >= 32
|| pending
.iter()
.map(bytes)
.sum::<usize>()
.saturating_add(bytes(&command))
> 4 * 1024 * 1024
{
return false;
}
pending.push_back(command);
true
}
pub(super) const PROFILE_TTL: Duration = Duration::from_secs(5);
pub(super) fn due(enabled: bool, last: Option<Instant>) -> bool {
enabled && last.is_none_or(|at| at.elapsed() >= PROFILE_TTL)
}
pub(super) fn refresh(identity: &Identity) -> tokio::task::JoinHandle<Result<Vec<u8>>> {
let identity = identity.clone();
tokio::spawn(async move {
tokio::time::timeout(
Duration::from_secs(12),
crate::net::account::admission_proof(&identity),
)
.await
.context("Central profile refresh timed out")?
})
}
pub(super) async fn send(
enabled: bool,
stream: &mut (impl AsyncWrite + Unpin),
seq: &mut u32,
proof: Vec<u8>,
last_sent: &mut Option<Vec<u8>>,
) -> Result<()> {
if enabled && last_sent.as_ref() != Some(&proof) {
framing::write(
stream,
PID_PROFILE_UPDATE,
seq,
&wire::encode(&wire::ProfileUpdate {
account_proof: proof.clone(),
})?,
)
.await?;
*last_sent = Some(proof);
}
Ok(())
}
pub(super) async fn actions(
stream: &mut (impl AsyncWrite + Unpin),
seq: &mut u32,
identity: &Identity,
channels: &mut Vec<String>,
pending: &mut VecDeque<NetCommand>,
) -> Result<()> {
while let Some(action) = pending.pop_front() {
match action {
NetCommand::ForumRequest(request) => { crate::net::forum::write(stream, seq, &request).await?; }
NetCommand::JoinChannel { channel_id } => {
super::core::track_channel(channels, &channel_id);
framing::write(
stream,
PID_JOIN_CHANNEL,
seq,
&wire::encode(&JoinChannelPayload { channel_id })?,
)
.await?;
}
NetCommand::SendChat {
channel_id,
content,
reply_to,
} => {
let message = ChatMessagePayload {
message_id: super::core::uuid_v4(),
channel_id,
sender_id: identity.pubkey_hex.clone(),
content,
timestamp: super::core::now_ms(),
edited: false,
reply_to,
};
framing::write(stream, PID_CHAT_MESSAGE, seq, &wire::encode(&message)?).await?;
}
NetCommand::AttachmentUpload {
request_id,
channel_id,
data,
} => {
framing::write(
stream,
PID_ATTACHMENT_UPLOAD,
seq,
&wire::encode(&wire::AttachmentUpload {
request_id,
channel_id,
data,
})?,
)
.await?;
}
_ => unreachable!("only chat, image, forum mutation and join commands can wait for profile refresh"),
}
}
stream.flush().await?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn legacy_session_without_live_profiles_sends_chat_voice_and_image_without_profile_packet()
{
let legacy: wire::Session = wire::decode(&[10, 1, b's', 18, 1, b't']).unwrap();
assert!(!legacy.live_profiles);
assert!(
!due(legacy.live_profiles, None),
"legacy actions never wait for profile HTTP"
);
let identity = crate::identity::generate("legacy");
let (mut stream, mut peer) = tokio::io::duplex(65536);
let mut seq = 2;
let mut sent = None;
send(
legacy.live_profiles,
&mut stream,
&mut seq,
b"not supported".to_vec(),
&mut sent,
)
.await
.unwrap();
assert!(sent.is_none());
let mut pending = VecDeque::from([
NetCommand::SendChat {
channel_id: "general".into(),
content: "legacy message".into(),
reply_to: None,
},
NetCommand::JoinChannel {
channel_id: "voice".into(),
},
NetCommand::AttachmentUpload {
request_id: "image".into(),
channel_id: "general".into(),
data: vec![1, 2, 3],
},
]);
actions(
&mut stream,
&mut seq,
&identity,
&mut vec!["general".into()],
&mut pending,
)
.await
.unwrap();
for expected in [PID_CHAT_MESSAGE, PID_JOIN_CHANNEL, PID_ATTACHMENT_UPLOAD] {
assert_eq!(framing::read(&mut peer).await.unwrap().packet_id, expected);
}
}
#[test]
fn image_actions_share_bounded_byte_budget_and_leave_cancels_upload() {
let mut pending = VecDeque::new();
assert!(enqueue(
&mut pending,
NetCommand::AttachmentUpload {
request_id: "one".into(),
channel_id: "general".into(),
data: vec![0; 3 * 1024 * 1024]
}
));
assert!(!enqueue(
&mut pending,
NetCommand::AttachmentUpload {
request_id: "two".into(),
channel_id: "general".into(),
data: vec![0; 3 * 1024 * 1024]
}
));
assert_eq!(pending.len(), 1);
cancel_channel(&mut pending, "general");
assert!(pending.is_empty());
}
#[tokio::test]
async fn disconnect_switch_and_session_drop_cancel_refresh_and_never_replay_pending_actions() {
for session_end in [false, true] {
let identity = crate::identity::generate("test");
let (mut stream, mut peer) = tokio::io::duplex(65536);
let mut pending = VecDeque::from([
NetCommand::SendChat {
channel_id: "old-node-channel".into(),
content: "old message".into(),
reply_to: None,
},
NetCommand::JoinChannel {
channel_id: "old-voice".into(),
},
]);
let mut job = RefreshTask {
task: Some(tokio::spawn(async {
std::future::pending::<Result<Vec<u8>>>().await
})),
};
let aborted = job.task.as_ref().unwrap().abort_handle();
if session_end {
drop(job);
pending.clear();
} else {
cancel(&mut job, &mut pending);
drop(job);
}
tokio::task::yield_now().await;
assert!(aborted.is_finished());
let mut channels = vec!["new-node-channel".to_owned()];
actions(&mut stream, &mut 2, &identity, &mut channels, &mut pending)
.await
.unwrap();
assert_eq!(channels, vec!["new-node-channel"]);
assert!(
tokio::time::timeout(Duration::from_millis(5), framing::read(&mut peer))
.await
.is_err()
);
}
}
#[test]
fn pending_actions_are_bounded_coalesce_duplicate_joins_and_leave_cancels_channel() {
let mut pending = VecDeque::new();
for _ in 0..100 {
assert!(enqueue(
&mut pending,
NetCommand::JoinChannel {
channel_id: "voice".into()
}
));
}
assert_eq!(pending.len(), 1);
for _ in 0..31 {
assert!(enqueue(
&mut pending,
NetCommand::SendChat {
channel_id: "general".into(),
content: "message".into(),
reply_to: None
}
));
}
assert!(!enqueue(
&mut pending,
NetCommand::JoinChannel {
channel_id: "overflow".into()
}
));
cancel_channel(&mut pending, "voice");
assert_eq!(pending.len(), 31);
cancel_channel(&mut pending, "general");
assert!(pending.is_empty());
}
#[tokio::test]
async fn fresh_proof_precedes_chat_and_voice_join_without_disconnect_or_duplicate_join() {
let identity = crate::identity::generate("old");
let (mut stream, mut peer) = tokio::io::duplex(65536);
let mut pending = VecDeque::from([
NetCommand::SendChat {
channel_id: "general".into(),
content: "new message".into(),
reply_to: None,
},
NetCommand::JoinChannel {
channel_id: "voice-room".into(),
},
NetCommand::AttachmentUpload {
request_id: "image".into(),
channel_id: "general".into(),
data: vec![1, 2, 3],
},
]);
let mut channels = vec!["general".to_owned()];
let mut seq = 0;
let mut last = None;
send(
true,
&mut stream,
&mut seq,
b"signed fresh proof".to_vec(),
&mut last,
)
.await
.unwrap();
actions(
&mut stream,
&mut seq,
&identity,
&mut channels,
&mut pending,
)
.await
.unwrap();
assert_eq!(
framing::read(&mut peer).await.unwrap().packet_id,
PID_PROFILE_UPDATE
);
assert_eq!(
framing::read(&mut peer).await.unwrap().packet_id,
PID_CHAT_MESSAGE
);
assert_eq!(
framing::read(&mut peer).await.unwrap().packet_id,
PID_JOIN_CHANNEL
);
assert_eq!(
framing::read(&mut peer).await.unwrap().packet_id,
PID_ATTACHMENT_UPLOAD
);
assert!(pending.is_empty());
assert_eq!(channels, vec!["general", "voice-room"]);
assert!(!due(true, Some(Instant::now())));
assert!(due(true, None));
}
}

View file

@ -51,6 +51,9 @@ pub async fn net_task(
session.address=address;session.auto_reconnect=auto_reconnect;
failures=0;target=Some(session);continue 'session;
}
Some(NetCommand::LeaveChannel {channel_id}) => {
forget_rejoin_channel(&mut session, &channel_id);
}
Some(NetCommand::Disconnect) => {
failures=0;
let _=event_tx.send(NetEvent::Disconnected {reason:"disconnected".into(),will_retry:false}).await;
@ -105,7 +108,13 @@ pub async fn net_task(
if let Some(problem) = transport.and_then(TransportError::trust_problem) {
let _ = event_tx.send(NetEvent::TrustProblem(problem)).await;
}
let retry = session.auto_reconnect && transport.is_none();
let account_required = e
.downcast_ref::<crate::net::account::SignInRequired>()
.is_some();
if account_required {
let _ = event_tx.send(NetEvent::AccountRequired).await;
}
let retry = should_retry(&e, session.auto_reconnect);
let _ = event_tx
.send(NetEvent::Disconnected {
reason: e.to_string(),
@ -123,6 +132,19 @@ pub async fn net_task(
}
}
/// An explicit leave during backoff must survive the next successful connection.
fn forget_rejoin_channel(target: &mut SessionTarget, channel_id: &str) {
target.channels.retain(|channel| channel != channel_id);
}
fn should_retry(error: &anyhow::Error, enabled: bool) -> bool {
enabled
&& error.downcast_ref::<TransportError>().is_none()
&& error
.downcast_ref::<crate::net::account::SignInRequired>()
.is_none()
}
async fn wait_for_connect(cmd_rx: &mut mpsc::Receiver<NetCommand>) -> Option<SessionTarget> {
loop {
match cmd_rx.recv().await {
@ -146,6 +168,31 @@ async fn wait_for_connect(cmd_rx: &mut mpsc::Receiver<NetCommand>) -> Option<Ses
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn leave_during_reconnect_backoff_prevents_voice_room_autorejoin() {
let mut target = SessionTarget {
address: "node.example:7600".into(),
auto_reconnect: true,
channels: vec!["general".into(), "voice-room".into(), "pending-room".into()],
};
for channel in ["voice-room", "pending-room"] {
forget_rejoin_channel(&mut target, channel);
}
assert_eq!(target.channels, vec!["general"]);
assert!(target.auto_reconnect);
assert_eq!(target.address, "node.example:7600");
}
#[test]
fn expired_account_stops_retry_but_outage_keeps_retry_policy() {
let account = anyhow::Error::new(crate::net::account::SignInRequired)
.context("gateway handshake failed");
assert!(!should_retry(&account, true));
let outage = anyhow::anyhow!("Central temporarily unavailable");
assert!(should_retry(&outage, true));
assert!(!should_retry(&outage, false));
}
#[tokio::test]
async fn disconnected_cancel_does_not_disable_later_connections() {
let (sender, mut receiver) = mpsc::channel(4);

View file

@ -18,9 +18,9 @@ impl<T: AsyncRead + AsyncWrite + Unpin + Send> AsyncStream for T {}
pub type Stream = Box<dyn AsyncStream>;
/// ALPN protocol id required from the gateway.
pub const ALPN: &[u8] = b"vnox-lnex/3";
pub const ALPN: &[u8] = b"vnox-lnex/4";
/// TLS exporter label of the channel binding (must match the gateway).
pub const EXPORTER_LABEL: &[u8] = b"EXPORTER-VNOX-LNEx-v3-channel-binding";
pub const EXPORTER_LABEL: &[u8] = b"EXPORTER-VNOX-LNEx-v4-channel-binding";
/// Length of the exported channel binding.
pub const BINDING_LEN: usize = 32;
@ -220,7 +220,7 @@ pub async fn connect_with_peer(address: &str, trust: &TrustStore) -> Result<Conn
|| connection.alpn_protocol() != Some(ALPN)
{
return Err(TransportError::ProtocolMismatch(
"The server did not negotiate TLS 1.3 with LNEx v3. Ask its owner to update the server."
"The server did not negotiate TLS 1.3 with LNEx v4. Ask its owner to update the server."
.into(),
)
.into());
@ -237,7 +237,7 @@ pub async fn connect_with_peer(address: &str, trust: &TrustStore) -> Result<Conn
})
}
const NOT_TLS13: &str = "The server does not speak TLS 1.3 (LNEx v3). It is probably an outdated server or a non-VNOX port, ask its owner to update it.";
const NOT_TLS13: &str = "The server does not speak TLS 1.3 (LNEx v4). It is probably an outdated server or a non-VNOX port, ask its owner to update it.";
fn map_tls_error(
error: std::io::Error,

View file

@ -1,4 +1,4 @@
//! Server trust for the TLS 1.3 control connection (LNEx v3).
//! Server trust for the TLS 1.3 control connection (LNEx v4).
//!
//! Model (see `VNOX-Server/docs/02-protocol/tls.md`):
//! * a stored **pin** (SHA-256 of the certificate SubjectPublicKeyInfo) always wins,
@ -39,7 +39,7 @@ pub enum TransportError {
},
/// A server marked as CA trusted no longer presents a valid public certificate.
CertificateInvalid { address: String, reason: String },
/// The peer does not speak TLS 1.3 / LNEx v3.
/// The peer does not speak TLS 1.3 / LNEx v4.
ProtocolMismatch(String),
}

View file

@ -1,5 +1,21 @@
#[derive(Debug)]
pub enum NetCommand {
ForumRequest(crate::net::wire::ForumRequest),
/// Fence an administrative channel mutation to the authenticated session that prepared it.
ForSession {
session_id: String,
command: Box<NetCommand>,
},
AttachmentUpload {
request_id: String,
channel_id: String,
data: Vec<u8>,
},
AttachmentFetch {
request_id: String,
channel_id: String,
attachment_id: String,
},
MediaControl(crate::net::wire::MediaControl),
Webhook {
operation: WebhookOperation,
@ -15,11 +31,20 @@ pub enum NetCommand {
LeaveChannel {
channel_id: String,
},
NodeSettingsRequest(crate::net::wire::NodeSettingsRequest),
ChannelCreate {
channel_id: String,
channel_name: String,
kind: String,
guild_id: Option<String>,
parent_id: Option<String>,
position: i32,
},
ChannelEdit {
channel_id: String,
channel_name: String,
parent_id: Option<String>,
position: Option<i32>,
},
ChannelDelete {
channel_id: String,

View file

@ -3,6 +3,17 @@ use std::net::SocketAddr;
#[derive(Debug, Clone)]
pub enum NetEvent {
ForumResult(crate::net::wire::ForumResult),
ForumChanged(crate::net::wire::ForumChanged),
/// A local profile refresh/activity warning; it is not a gateway join refusal.
ProfileWarning {
message: String,
rejected_join: Option<String>,
},
ProfileUpdated(crate::net::wire::ProfileUpdated),
/// Central enrollment must be approved again; retries cannot repair it.
AccountRequired,
AttachmentResult(crate::net::wire::AttachmentResult),
VoiceRevoked {
channel_id: String,
},
@ -10,11 +21,16 @@ pub enum NetEvent {
WebhookResult(WebhookManagementResult),
WebhookList(crate::net::wire::WebhookListResult),
WebhookError(crate::net::wire::WebhookErrorResult),
NodeSettingsResult { session_id: String, result: crate::net::wire::NodeSettingsResult },
Connected {
session_id: String,
node_name: String,
restored: bool,
private_mode: bool,
node_admin: bool,
node_settings: bool,
channel_structure: bool,
forums: bool,
},
Disconnected {
reason: String,
@ -33,12 +49,22 @@ pub enum NetEvent {
members: Vec<MemberInfo>,
voice_endpoint: String,
guild_id: Option<String>,
parent_id: Option<String>,
position: i32,
},
ChannelCreated {
channel_id: String,
channel_name: String,
kind: String,
guild_id: Option<String>,
parent_id: Option<String>,
position: i32,
},
ChannelEdited {
channel_id: String,
channel_name: String,
parent_id: Option<String>,
position: Option<i32>,
},
ChannelDeleted {
channel_id: String,
@ -61,6 +87,8 @@ pub enum NetEvent {
messages: Vec<ChatMsg>,
},
UserJoin {
account_id: String,
avatar_url: String,
channel_id: String,
user_id: String,
nickname: String,

View file

@ -3,6 +3,8 @@ pub struct MemberInfo {
pub user_id: String,
pub nickname: String,
pub in_voice: bool,
pub account_id: String,
pub avatar_url: String,
}
#[derive(Debug, Clone)]
@ -11,6 +13,8 @@ pub struct ChannelListItem {
pub channel_name: String,
pub kind: String,
pub guild_id: Option<String>,
pub parent_id: Option<String>,
pub position: i32,
}
#[derive(Debug, Clone)]

359
src/ui/account.rs Normal file
View file

@ -0,0 +1,359 @@
//! Browser approval UI. Login secrets stay inside the network/account module.
use super::slint::MainWindow;
use crate::{
AppState,
net::{
self,
account::{self, LoginEvent},
},
};
use slint::ComponentHandle;
use std::{cell::RefCell, rc::Rc, sync::mpsc, time::Duration};
#[derive(Default)]
struct Controls {
generation: u64,
busy: bool,
cancelled: bool,
flow_identity: Option<crate::identity::Identity>,
cancel: Option<tokio::sync::watch::Sender<bool>>,
approval_uri: Option<String>,
}
enum Update {
Approval { uri: String, key: String },
SignedIn(Result<account::AccountSummary, String>),
SignedOut(Result<(), String>),
}
fn browser(uri: &str) {
// No shell and no device/refresh token in this public approval URL.
if let Err(error) = std::process::Command::new("xdg-open").arg(uri).spawn() {
tracing::warn!(%error, "could not open Central approval page");
}
}
/// Apply a fresh public profile without overwriting an unsaved name draft.
pub(super) fn apply_profile(
window: &MainWindow,
state: &mut AppState,
user: account::AccountSummary,
) {
let previous = state.ui.central_account.as_ref();
if previous.is_none_or(|old| {
old.user_id != user.user_id
|| window.get_profile_display_name().as_str() == old.display_name
}) || window.get_profile_display_name().is_empty()
{
window.set_profile_display_name(user.display_name.clone().into());
}
window.set_profile_initials(user.display_name.chars().take(2).collect::<String>().into());
window.set_account_name(user.display_name.clone().into());
state
.ui
.apply_central_profile(&state.identity.pubkey_hex, user);
}
/// Returned timer must stay alive for the window lifetime.
pub fn wire(window: &MainWindow, state: &Rc<RefCell<AppState>>) -> slint::Timer {
let controls = Rc::new(RefCell::new(Controls::default()));
// Drop the Ref before any successful branch mutates UI profile state.
let current = {
let state = state.borrow();
account::current(&state.identity)
};
match current {
Ok(Some(user)) => {
window.set_account_authenticated(true);
apply_profile(window, &mut state.borrow_mut(), user);
}
Ok(None) => (),
Err(error) => window.set_account_status(error.to_string().into()),
}
super::connection::restore(&mut state.borrow_mut(), window.get_account_authenticated());
let (sender, receiver) = mpsc::channel();
{
let controls = controls.clone();
let state = state.clone();
let weak = window.as_weak();
let sender = sender.clone();
window.on_account_sign_in(move || {
let Some(window) = weak.upgrade() else { return };
let mut control = controls.borrow_mut();
if control.busy {
return;
}
control.busy = true;
control.cancelled = false;
control.generation += 1;
let generation = control.generation;
let (cancel, cancellation) = tokio::sync::watch::channel(false);
control.cancel = Some(cancel);
control.approval_uri = None;
window.set_account_signing_in(true);
window.set_account_status(super::i18n::text("Preparing browser sign-in...").into());
window.set_account_public_key("".into());
let identity = state.borrow().identity.clone();
control.flow_identity = Some(identity.clone());
let sender = sender.clone();
tokio::spawn(async move {
let (updates, mut progress) = tokio::sync::mpsc::unbounded_channel();
let forward = sender.clone();
let forwarding = tokio::spawn(async move {
while let Some(LoginEvent::ApprovalRequired {
verification_uri,
public_key,
..
}) = progress.recv().await
{
if forward
.send((
generation,
Update::Approval {
uri: verification_uri,
key: public_key,
},
))
.is_err()
{
break;
}
}
});
let result = account::sign_in(&identity, updates, cancellation)
.await
.map_err(|e| e.to_string());
forwarding.abort();
let _ = sender.send((generation, Update::SignedIn(result)));
});
});
}
{
let controls = controls.clone();
let weak = window.as_weak();
window.on_account_cancel(move || {
let mut control = controls.borrow_mut();
let Some(cancel) = control.cancel.as_ref() else {
return;
};
let _ = cancel.send(true);
control.cancelled = true;
control.approval_uri = None;
if let Some(window) = weak.upgrade() {
window.set_account_public_key("".into());
window.set_account_status(super::i18n::text("Cancelling sign-in...").into());
}
});
}
{
let controls = controls.clone();
window.on_account_open_browser(move || {
if let Some(uri) = controls.borrow().approval_uri.as_ref() {
browser(uri);
}
});
}
{
let controls = controls.clone();
let state = state.clone();
let weak = window.as_weak();
let sender = sender.clone();
window.on_account_sign_out(move || {
let Some(window) = weak.upgrade() else { return };
let mut control = controls.borrow_mut();
if control.busy {
return;
}
control.busy = true;
control.generation += 1;
if let Some(cancel) = control.cancel.take() {
let _ = cancel.send(true);
}
let generation = control.generation;
state.borrow_mut().ui.central_account = None;
window.set_profile_display_name("".into());
window.set_profile_error("".into());
window.set_profile_saving(false);
window.set_avatar_saving(false);
window.set_profile_initials("".into());
window.set_own_avatar(slint::Image::default());
window.set_has_avatar(false);
let s = state.borrow();
let identity = s.identity.clone();
let net = s.net.clone();
let sender = sender.clone();
window.set_account_authenticated(false);
window.set_account_signing_in(true);
window.set_account_name("".into());
window.set_account_status(super::i18n::text("Signing out...").into());
tokio::spawn(async move {
net.send(net::NetCommand::Disconnect).await;
let result = account::sign_out(&identity)
.await
.map_err(|e| e.to_string());
let _ = sender.send((generation, Update::SignedOut(result)));
});
});
}
{
let weak = window.as_weak();
let state = state.clone();
let controls = controls.clone();
window.on_save_profile_name(move |name| {
let Some(window) = weak.upgrade() else { return };
if window.get_profile_saving()
|| controls.borrow().busy
|| !window.get_account_authenticated()
{
return;
}
let identity = state.borrow().identity.clone();
let user_id = state
.borrow()
.ui
.central_account
.as_ref()
.map(|user| user.user_id.clone());
let generation = controls.borrow().generation;
let epoch = account::enrollment_epoch();
window.set_profile_saving(true);
window.set_profile_error("".into());
let state = state.clone();
let controls = controls.clone();
let weak = weak.clone();
let result = slint::spawn_local(async move {
let request_identity = identity.clone();
let submitted_name = name.to_string();
let requested_name = submitted_name.clone();
let result = tokio::spawn(async move {
account::set_display_name(&request_identity, &requested_name, epoch).await
})
.await;
let Some(window) = weak.upgrade() else { return };
if generation != controls.borrow().generation
|| epoch != account::enrollment_epoch()
|| !window.get_account_authenticated()
|| state.borrow().identity.pubkey_hex != identity.pubkey_hex
|| state
.borrow()
.ui
.central_account
.as_ref()
.map(|user| &user.user_id)
!= user_id.as_ref()
{
return;
}
window.set_profile_saving(false);
match result {
Ok(Ok(user)) => {
if window.get_profile_display_name().as_str() == submitted_name {
window.set_profile_display_name(user.display_name.clone().into());
}
apply_profile(&window, &mut state.borrow_mut(), user);
}
Ok(Err(error)) => {
window.set_profile_error(super::i18n::text(&error.to_string()).into())
}
Err(_) => window.set_profile_error(
super::i18n::text("Could not save profile. Try again.").into(),
),
}
});
if result.is_err() {
window.set_profile_saving(false);
window.set_profile_error(
super::i18n::text("Could not save profile. Try again.").into(),
);
}
});
}
let mut profiles = account::subscribe_profiles();
let mut last_profile_refresh: Option<std::time::Instant> = None;
let mut refreshing: Option<tokio::task::JoinHandle<()>> = None;
let mut was_settings_open = false;
let timer = slint::Timer::default();
let state = state.clone();
let weak = window.as_weak();
timer.start(slint::TimerMode::Repeated, Duration::from_millis(100), move || {
let Some(window) = weak.upgrade() else { return };
if profiles.has_changed().unwrap_or(false) {
let update = profiles.borrow_and_update().clone();
if let Some(update) = update {
let mut state = state.borrow_mut();
if window.get_account_authenticated() && update.epoch == account::enrollment_epoch() && update.public_key == state.identity.pubkey_hex
&& state.ui.central_account.as_ref().is_some_and(|current|current.user_id == update.user.user_id) {
apply_profile(&window, &mut state, update.user);
}
}
}
let settings_open = state.borrow().ui.settings_open;
let settings_just_opened = settings_open && !was_settings_open;
was_settings_open = settings_open;
if refreshing.as_ref().is_some_and(|task|task.is_finished()) {refreshing=None;}
let due = last_profile_refresh.is_none_or(|at|at.elapsed() >= Duration::from_secs(60))
|| (settings_just_opened && last_profile_refresh.is_none_or(|at|at.elapsed() >= Duration::from_secs(5)));
if due && refreshing.is_none() && !controls.borrow().busy && window.get_account_authenticated()
&& state.borrow().ui.central_account.is_some() {
let identity = state.borrow().identity.clone();
last_profile_refresh = Some(std::time::Instant::now());
refreshing = Some(tokio::spawn(async move { let _ = account::refresh_profile(&identity).await; }));
}
while let Ok((generation, update)) = receiver.try_recv() {
let mut control = controls.borrow_mut();
if generation != control.generation { continue; }
match update {
Update::Approval { uri, key } => {
if control.cancelled { continue; }
window.set_account_public_key(key.into());
window.set_account_status(super::i18n::text("Confirm this device in your browser. Compare the public key before approving.").into());
browser(&uri);
control.approval_uri = Some(uri);
}
Update::SignedIn(result) => {
control.cancel = None;
control.approval_uri = None;
if control.cancelled && result.is_ok() {
// Cancel can race an already queued successful result. Revoke what
// was saved before permitting any replacement login.
if let Some(identity) = control.flow_identity.take() {
let sender = sender.clone();
tokio::spawn(async move {
let result = account::sign_out(&identity).await.map_err(|e| e.to_string());
let _ = sender.send((generation, Update::SignedOut(result)));
});
continue;
}
}
control.flow_identity = None;
control.busy = false;
window.set_account_signing_in(false);
if control.cancelled {
window.set_account_status(super::i18n::text("Sign-in cancelled.").into());
continue;
}
match result {
Ok(user) => {
window.set_account_authenticated(true);
window.set_profile_display_name(user.display_name.clone().into());
window.set_profile_saving(false);
window.set_avatar_saving(false);
window.set_avatar_error("".into());
window.set_avatar_crop_open(false);
window.set_avatar_source(slint::Image::default());
apply_profile(&window, &mut state.borrow_mut(), user);
window.set_account_status("".into());
state.borrow_mut().ui.connection.authentication_required = false;
super::connection::restore(&mut state.borrow_mut(), true);
}
Err(error) => window.set_account_status(error.into()),
}
}
Update::SignedOut(result) => {
control.busy = false;
window.set_account_signing_in(false);
window.set_account_status(result.err().unwrap_or_default().into());
}
}
}
});
timer
}

View file

@ -173,7 +173,7 @@ mod tests {
#[test]
fn built_in_themes_roundtrip_without_color_or_alpha_loss() {
for mode in ["light", "dark", "black"] {
for mode in super::super::BUILTIN_THEME_IDS {
let theme = ThemeSpec::builtin(mode);
assert_eq!(parse_css(&theme.to_css()).unwrap(), theme);
}

View file

@ -48,60 +48,86 @@ pub const COLOR_TOKENS: [&str; 15] = [
"--vnox-success",
];
/// Stable persisted identifiers: six dark presets followed by six light presets.
pub const BUILTIN_THEME_IDS: [&str; 12] = [
"black",
"dark",
"midnight",
"pine",
"aubergine",
"espresso",
"light",
"mist",
"glacier",
"sage",
"rose",
"sand",
];
impl ThemeSpec {
pub fn builtin(mode: &str) -> Self {
let values = match mode {
"light" => [
"#f5f4f2",
"#eae8e5",
"#dedbd6",
"#dfdcd7",
"#efede9",
"#ffffff",
"#d8d3cb",
"#0000001c",
"#78552d",
"#292622",
"#514b44",
"#6b645e",
"#756d65",
"#b43731",
"#3e704d",
],
"black" => [
"#090909",
"#111111",
"#000000",
"#262626",
"#181818",
"#202020",
"#303030",
"#ffffff1c",
"#d5b58a",
"#f0eeee",
"#c3bdb7",
"#aba39b",
"#948a80",
"#ee948b",
"#a8c1a4",
"#090909", "#111111", "#000000", "#262626", "#181818", "#202020", "#303030",
"#9099a6", "#d5b58a", "#f8f6fa", "#e0dce5", "#ccc7d2", "#b9b2bf", "#ffb4b0",
"#9ce3b7",
],
_ => [
"#272729",
"#202022",
"#151516",
"#38383c",
"#303033",
"#343336",
"#3a393c",
"#ffffff12",
"#d5b58a",
"#e9e7e4",
"#b8b4b1",
"#aaa29b",
"#85817f",
"#e58b85",
"#a8c1a4",
"dark" => [
"#292b31", "#1d1f25", "#121419", "#373b45", "#30343e", "#323641", "#3b4251",
"#9099a6", "#d5b58a", "#f8f6fa", "#e0dce5", "#ccc7d2", "#b9b2bf", "#ffb4b0",
"#9ce3b7",
],
"midnight" => [
"#151f32", "#10192a", "#0b1220", "#293952", "#202e45", "#25334b", "#30425c",
"#9099a6", "#9fc5ff", "#f8f6fa", "#e0dce5", "#ccc7d2", "#b9b2bf", "#ffb4b0",
"#9ce3b7",
],
"pine" => [
"#172b26", "#11231e", "#0b1915", "#294139", "#20372f", "#253c34", "#304b40",
"#9099a6", "#91d6af", "#f8f6fa", "#e0dce5", "#ccc7d2", "#b9b2bf", "#ffb4b0",
"#9ce3b7",
],
"aubergine" => [
"#2a2031", "#211827", "#170f1c", "#42314b", "#36293f", "#3b2d45", "#493650",
"#9099a6", "#dfb0eb", "#f8f6fa", "#e0dce5", "#ccc7d2", "#b9b2bf", "#ffb4b0",
"#9ce3b7",
],
"espresso" => [
"#2d241f", "#241c17", "#1b140f", "#45372e", "#392d25", "#3e3129", "#4b3b30",
"#9099a6", "#e8bd8d", "#f8f6fa", "#e0dce5", "#ccc7d2", "#b9b2bf", "#ffb4b0",
"#9ce3b7",
],
"light" => [
"#f5f4f2", "#eae8e5", "#dedbd6", "#e2ddd6", "#efede9", "#ffffff", "#d8d3cb",
"#737078", "#76532b", "#28252c", "#39353e", "#514c58", "#5d5663", "#a32436",
"#28613b",
],
"mist" => [
"#f2f3f7", "#e7e9f0", "#dadee9", "#dce0ec", "#eceef5", "#ffffff", "#cfd5e5",
"#737078", "#43578c", "#28252c", "#39353e", "#514c58", "#5d5663", "#a32436",
"#28613b",
],
"glacier" => [
"#eff6fa", "#e0edf4", "#d1e3ee", "#d5e7f1", "#e8f2f8", "#ffffff", "#c8e0ec",
"#737078", "#23617e", "#28252c", "#39353e", "#514c58", "#5d5663", "#a32436",
"#28613b",
],
"sage" => [
"#f0f6ef", "#e2ecdf", "#d3e1ce", "#d7e6d2", "#e9f2e5", "#ffffff", "#cbdcc4",
"#737078", "#3f653b", "#28252c", "#39353e", "#514c58", "#5d5663", "#a32436",
"#28613b",
],
"rose" => [
"#faf2f4", "#f0e3e8", "#e7d4dc", "#ecd9e1", "#f6eaf0", "#ffffff", "#e3ccd6",
"#737078", "#873e5a", "#28252c", "#39353e", "#514c58", "#5d5663", "#a32436",
"#28613b",
],
"sand" => [
"#faf5e9", "#f0e7d3", "#e6d9bd", "#eadebf", "#f6eedc", "#ffffff", "#dfd0ae",
"#737078", "#705018", "#28252c", "#39353e", "#514c58", "#5d5663", "#a32436",
"#28613b",
],
_ => return Self::builtin("black"),
};
Self {
colors: values.map(|s| css::parse_color(s).expect("built-in hex color")),
@ -123,3 +149,96 @@ impl ThemeSpec {
css
}
}
#[cfg(test)]
mod tests {
use super::*;
// WCAG 2.2 relative luminance in sRGB, not a brightness approximation.
fn luminance(color: Rgba) -> f64 {
let channel = |value: u8| {
let value = f64::from(value) / 255.0;
if value <= 0.04045 {
value / 12.92
} else {
((value + 0.055) / 1.055).powf(2.4)
}
};
0.2126 * channel(color.0) + 0.7152 * channel(color.1) + 0.0722 * channel(color.2)
}
fn contrast(a: Rgba, b: Rgba) -> f64 {
let (a, b) = (luminance(a), luminance(b));
(a.max(b) + 0.05) / (a.min(b) + 0.05)
}
#[test]
fn every_builtin_keeps_text_status_selection_and_focus_readable() {
for id in BUILTIN_THEME_IDS {
let spec = ThemeSpec::builtin(id);
let c = spec.colors;
for background in 0..7 {
// Includes active selections, inputs, hover, muted text and error/success labels.
for foreground in [8, 9, 10, 11, 12, 13, 14] {
let ratio = contrast(c[foreground], c[background]);
assert!(
ratio >= 4.5,
"{id}: {foreground} on {background}: {ratio:.3}"
);
}
let ratio = contrast(c[7], c[background]);
assert!(
ratio >= 3.0,
"{id}: control boundary on {background}: {ratio:.3}"
);
}
let on_accent = if spec.is_light() {
Rgba(255, 255, 255, 255)
} else {
Rgba(35, 30, 25, 255)
};
assert!(contrast(c[8], on_accent) >= 4.5, "{id}: primary action");
}
}
#[test]
fn theme_previews_use_the_actual_builtin_palette() {
let source = include_str!("../slint/settings/appearance.slint");
for id in BUILTIN_THEME_IDS {
let card = source
.lines()
.find(|line| {
line.contains("ThemeChoice {")
&& line.contains(&format!("theme-selected(\"{id}\")"))
})
.unwrap_or_else(|| panic!("missing theme card {id}"));
let colors = ThemeSpec::builtin(id).colors;
for (name, index) in [
("background", 0),
("sidebar", 1),
("rail", 2),
("selected", 6),
("input", 5),
("ink", 9),
("accent", 8),
] {
assert!(
card.contains(&format!("preview-{name}: {};", colors[index].css())),
"{id}: preview {name}"
);
}
}
}
#[test]
fn builtin_catalog_contains_six_light_and_six_dark_palettes() {
assert_eq!(
BUILTIN_THEME_IDS
.iter()
.filter(|id| ThemeSpec::builtin(id).is_light())
.count(),
6
);
assert_eq!(ThemeSpec::builtin("unknown"), ThemeSpec::builtin("black"));
}
}

View file

@ -16,8 +16,8 @@ pub struct AppearancePreferences {
impl Default for AppearancePreferences {
fn default() -> Self {
Self {
mode: "dark".into(),
custom_css: ThemeSpec::builtin("dark").to_css(),
mode: "black".into(),
custom_css: ThemeSpec::builtin("black").to_css(),
font_size: 16.0,
}
}
@ -48,7 +48,7 @@ impl AppearancePreferences {
}
pub fn resolve(&self) -> Result<ThemeSpec, String> {
if !["light", "dark", "black", "custom"].contains(&self.mode.as_str()) {
if self.mode != "custom" && !super::BUILTIN_THEME_IDS.contains(&self.mode.as_str()) {
return Err(crate::ui::i18n::text("Unknown theme."));
}
if !self.font_size.is_finite() || !(12.0..=22.0).contains(&self.font_size) {
@ -139,6 +139,26 @@ pub fn export_css(path: &Path, theme: &ThemeSpec) -> Result<(), String> {
mod tests {
use super::*;
#[test]
fn new_profiles_default_to_extra_dark_and_explicit_choices_survive() {
assert_eq!(AppearancePreferences::default().mode, "black");
assert_eq!(
serde_json::from_str::<AppearancePreferences>("{}")
.unwrap()
.mode,
"black"
);
for id in super::super::BUILTIN_THEME_IDS
.into_iter()
.chain(["custom"])
{
let json = serde_json::json!({"mode": id}).to_string();
let prefs: AppearancePreferences = serde_json::from_str(&json).unwrap();
assert_eq!(prefs.mode, id);
assert!(prefs.resolve().is_ok(), "{id}");
}
}
#[test]
fn saved_custom_palette_and_text_size_survive_reload() {
let directory = std::env::temp_dir().join(format!("vnox-theme-{}", uuid::Uuid::new_v4()));

View file

@ -1,4 +1,4 @@
use std::cell::RefCell;
use std::cell::{Cell, RefCell};
use std::path::PathBuf;
use std::rc::Rc;
@ -9,6 +9,18 @@ use super::CropSource;
use crate::AppState;
use crate::ui::slint::MainWindow;
fn crop_context(state: &AppState) -> (String, Option<String>, u64) {
(
state.identity.pubkey_hex.clone(),
state
.ui
.central_account
.as_ref()
.map(|user| user.user_id.clone()),
crate::net::account::enrollment_epoch(),
)
}
fn avatar_path(identity: &str) -> PathBuf {
// Scope local photos by account; never place untrusted identity text in a path.
let name = hex::encode(Sha256::digest(identity.as_bytes()));
@ -42,8 +54,10 @@ fn discard_crop(window: &MainWindow, pending: &Rc<RefCell<Option<CropSource>>>)
pub fn wire(window: &MainWindow, state: &Rc<RefCell<AppState>>, persist: bool) {
let pending = Rc::new(RefCell::new(None::<CropSource>));
let busy = Rc::new(Cell::new(false));
let crop_owner = Rc::new(RefCell::new(None));
let path = avatar_path(&state.borrow().identity.pubkey_hex);
if persist && path.exists() {
if persist && !window.get_account_authenticated() && path.exists() {
match CropSource::load(&path) {
Ok(source) => {
window.set_own_avatar(source.ui_image());
@ -55,13 +69,24 @@ pub fn wire(window: &MainWindow, state: &Rc<RefCell<AppState>>, persist: bool) {
{
let weak = window.as_weak();
let pending = pending.clone();
let busy = busy.clone();
let state = state.clone();
let crop_owner = crop_owner.clone();
window.on_choose_avatar(move || {
if busy.get() {
return;
}
let weak = weak.clone();
let pending = pending.clone();
if let Some(window) = weak.upgrade() {
window.set_avatar_error("".into());
}
let task_window = weak.clone();
busy.set(true);
let task_busy = busy.clone();
let owner = crop_context(&state.borrow());
let state = state.clone();
let crop_owner = crop_owner.clone();
let result = slint::spawn_local(async move {
let Some(file) = rfd::AsyncFileDialog::new()
.set_title(crate::ui::i18n::text("Choose profile photo"))
@ -72,13 +97,21 @@ pub fn wire(window: &MainWindow, state: &Rc<RefCell<AppState>>, persist: bool) {
.pick_file()
.await
else {
task_busy.set(false);
return;
};
let path = file.path().to_owned();
let result = tokio::task::spawn_blocking(move || CropSource::load(&path)).await;
task_busy.set(false);
if let Some(window) = task_window.upgrade() {
match result {
Ok(Ok(source)) => begin_crop(&window, &pending, source),
Ok(Ok(source)) => {
if crop_context(&state.borrow()) != owner {
return;
}
*crop_owner.borrow_mut() = Some(owner);
begin_crop(&window, &pending, source);
}
Ok(Err(error)) => window.set_avatar_error(error.into()),
Err(_) => window.set_avatar_error(
crate::ui::i18n::text(
@ -92,6 +125,7 @@ pub fn wire(window: &MainWindow, state: &Rc<RefCell<AppState>>, persist: bool) {
if result.is_err()
&& let Some(window) = weak.upgrade()
{
busy.set(false);
window.set_avatar_error(
crate::ui::i18n::text("The file picker is unavailable in this environment.")
.into(),
@ -127,18 +161,35 @@ pub fn wire(window: &MainWindow, state: &Rc<RefCell<AppState>>, persist: bool) {
let weak = window.as_weak();
let pending = pending.clone();
let path = path.clone();
let state = state.clone();
let busy = busy.clone();
let crop_owner = crop_owner.clone();
window.on_confirm_avatar(move || {
if busy.get() {
return;
}
if let Some(window) = weak.upgrade() {
let result = {
let source = pending.borrow();
source.as_ref().map(|source| {
if persist {
source.save_to(&path)
} else {
Ok(source.cropped_ui_image())
}
})
};
if crop_owner.borrow().as_ref() != Some(&crop_context(&state.borrow())) {
discard_crop(&window, &pending);
window.set_avatar_error(
crate::ui::i18n::text("Account changed. Choose your photo again.").into(),
);
return;
}
if window.get_account_authenticated() {
let picture = pending.borrow().as_ref().map(CropSource::cropped);
if let Some(picture) = picture {
mutate_central(&window, &state, &pending, &busy, Some(picture));
}
return;
}
let result = pending.borrow().as_ref().map(|source| {
if persist {
source.save_to(&path)
} else {
Ok(source.cropped_ui_image())
}
});
if let Some(result) = result {
match result {
Ok(image) => {
@ -165,7 +216,18 @@ pub fn wire(window: &MainWindow, state: &Rc<RefCell<AppState>>, persist: bool) {
}
{
let weak = window.as_weak();
let state = state.clone();
let pending = pending.clone();
window.on_remove_avatar(move || {
if busy.get() {
return;
}
if let Some(window) = weak.upgrade()
&& window.get_account_authenticated()
{
mutate_central(&window, &state, &pending, &busy, None);
return;
}
if let Some(window) = weak.upgrade() {
if persist
&& let Err(error) = std::fs::remove_file(&path)
@ -187,3 +249,88 @@ pub fn wire(window: &MainWindow, state: &Rc<RefCell<AppState>>, persist: bool) {
});
}
}
fn mutate_central(
window: &MainWindow,
state: &Rc<RefCell<AppState>>,
pending: &Rc<RefCell<Option<CropSource>>>,
busy: &Rc<Cell<bool>>,
picture: Option<image::DynamicImage>,
) {
if busy.replace(true) {
return;
}
window.set_avatar_saving(true);
window.set_avatar_error("".into());
let weak = window.as_weak();
let state = state.clone();
let pending = pending.clone();
let busy = busy.clone();
let identity = state.borrow().identity.clone();
let account_id = state
.borrow()
.ui
.central_account
.as_ref()
.map(|account| account.user_id.clone());
let request_identity = identity.clone();
let epoch = crate::net::account::enrollment_epoch();
let task_busy = busy.clone();
let task_window = weak.clone();
let result = slint::spawn_local(async move {
let result = tokio::spawn(async move {
let png = if let Some(picture) = picture {
Some(
tokio::task::spawn_blocking(move || -> anyhow::Result<Vec<u8>> {
let mut output = std::io::Cursor::new(Vec::new());
picture.write_to(&mut output, image::ImageFormat::Png)?;
Ok(output.into_inner())
})
.await??,
)
} else {
None
};
crate::net::account::set_avatar(&request_identity, png, epoch).await
})
.await;
task_busy.set(false);
let Some(window) = task_window.upgrade() else {
return;
};
let still_current = window.get_account_authenticated()
&& epoch == crate::net::account::enrollment_epoch()
&& state.borrow().identity.pubkey_hex == identity.pubkey_hex
&& state
.borrow()
.ui
.central_account
.as_ref()
.map(|account| &account.user_id)
== account_id.as_ref();
if !still_current {
return;
}
window.set_avatar_saving(false);
match result {
Ok(Ok(user)) => {
crate::ui::account::apply_profile(&window, &mut state.borrow_mut(), user);
window.set_avatar_error("".into());
discard_crop(&window, &pending);
}
Ok(Err(error)) => {
window.set_avatar_error(crate::ui::i18n::text(&error.to_string()).into())
}
Err(_) => window
.set_avatar_error(crate::ui::i18n::text("Could not save photo. Try again.").into()),
}
});
if result.is_err() {
busy.set(false);
if let Some(window) = weak.upgrade() {
window.set_avatar_saving(false);
window
.set_avatar_error(crate::ui::i18n::text("Could not save photo. Try again.").into());
}
}
}

137
src/ui/avatar/central.rs Normal file
View file

@ -0,0 +1,137 @@
//! Public Central avatar fetching, without credentials or redirects.
use std::{
cell::RefCell,
collections::HashMap,
time::{Duration, Instant},
};
const RETRY_AFTER: Duration = Duration::from_secs(30);
fn retry_due(failed_at: Instant) -> bool {
failed_at.elapsed() >= RETRY_AFTER
}
enum CachedAvatar {
Pending,
Ready(slint::Image),
Failed(Instant),
}
thread_local! { static CACHE: RefCell<HashMap<String, CachedAvatar>> = RefCell::new(HashMap::new()); }
pub fn url(path: &str) -> Option<String> {
let path = path
.strip_prefix(crate::net::account::CENTRAL_ORIGIN)
.unwrap_or(path);
(path.len() <= 256
&& path.starts_with("/v1/avatars/")
&& path
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"/-".contains(&b)))
.then(|| format!("{}{path}", crate::net::account::CENTRAL_ORIGIN))
}
/// Poll from the UI bridge; failed requests retry after a bounded cooldown.
pub fn image(path: &str) -> slint::Image {
let Some(url) = url(path) else {
return slint::Image::default();
};
let cached = CACHE.with(|cache| {
let mut cache = cache.borrow_mut();
match cache.get(&url) {
Some(CachedAvatar::Ready(image)) => return Some(image.clone()),
Some(CachedAvatar::Pending) => return Some(slint::Image::default()),
Some(CachedAvatar::Failed(at)) if !retry_due(*at) => {
return Some(slint::Image::default());
}
Some(CachedAvatar::Failed(_)) => {}
None if cache.len() >= 256 => return Some(slint::Image::default()),
None => {}
}
cache.insert(url.clone(), CachedAvatar::Pending);
None
});
if let Some(image) = cached {
return image;
}
let _ = slint::spawn_local(async move {
let request = url.clone();
if let Ok(Ok((w, h, rgba))) = tokio::spawn(async move { fetch(&request).await }).await {
let buffer =
slint::SharedPixelBuffer::<slint::Rgba8Pixel>::clone_from_slice(&rgba, w, h);
CACHE.with(|c| {
c.borrow_mut()
.insert(url, CachedAvatar::Ready(slint::Image::from_rgba8(buffer)))
});
} else {
CACHE.with(|cache| {
cache
.borrow_mut()
.insert(url, CachedAvatar::Failed(Instant::now()))
});
}
});
slint::Image::default()
}
async fn fetch(url: &str) -> anyhow::Result<(u32, u32, Vec<u8>)> {
anyhow::ensure!(
self::url(url).as_deref() == Some(url),
"invalid avatar origin"
);
static REQUESTS: std::sync::OnceLock<tokio::sync::Semaphore> = std::sync::OnceLock::new();
let _permit = REQUESTS
.get_or_init(|| tokio::sync::Semaphore::new(4))
.acquire()
.await?;
let client = reqwest::Client::builder()
.user_agent("VNOX-Desktop/0.1")
.no_proxy()
.https_only(true)
.redirect(reqwest::redirect::Policy::none())
.connect_timeout(Duration::from_secs(5))
.timeout(Duration::from_secs(10))
.build()?;
let mut response = client.get(url).send().await?.error_for_status()?;
anyhow::ensure!(
response
.headers()
.get(reqwest::header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.is_some_and(|v| v.split(';').next() == Some("image/png")),
"expected PNG"
);
let mut bytes = Vec::new();
while let Some(chunk) = response.chunk().await? {
anyhow::ensure!(bytes.len() + chunk.len() <= 1024 * 1024, "avatar too large");
bytes.extend_from_slice(&chunk);
}
tokio::task::spawn_blocking(move || {
let mut reader =
image::ImageReader::with_format(std::io::Cursor::new(bytes), image::ImageFormat::Png);
let mut limits = image::Limits::default();
limits.max_image_width = Some(512);
limits.max_image_height = Some(512);
limits.max_alloc = Some(4 * 1024 * 1024);
reader.limits(limits);
let image = reader.decode()?.to_rgba8();
Ok((image.width(), image.height(), image.into_raw()))
})
.await?
}
#[cfg(test)]
mod tests {
#[test]
fn transient_failure_retries_only_after_cooldown() {
assert!(!super::retry_due(std::time::Instant::now()));
assert!(super::retry_due(
std::time::Instant::now() - std::time::Duration::from_secs(31)
));
}
#[test]
fn only_same_origin_public_paths() {
assert!(super::url("/v1/avatars/default/abc-123").is_some());
for path in [
"https://github.com/x",
"//evil/v1/avatars/x",
"/v1/avatars/../x",
"/v1/avatars/x?token=s",
"https://central.loki-code.dev.evil/v1/avatars/x",
] {
assert!(super::url(path).is_none());
}
}
}

View file

@ -1,4 +1,5 @@
mod bindings;
pub mod central;
mod crop;
pub use bindings::wire;

View file

@ -26,7 +26,6 @@ fn presence_key(status: &str) -> &'static str {
type MainWindow = crate::ui::slint::MainWindow;
type BookmarkItem = crate::ui::slint::BookmarkItem;
type ChannelItem = crate::ui::slint::ChannelItem;
type DmItem = crate::ui::slint::DmItem;
type GuildItem = crate::ui::slint::GuildItem;
type MessageItem = crate::ui::slint::MessageItem;
@ -45,7 +44,7 @@ fn replace_model<T: Clone + PartialEq + 'static>(
}
}
fn initials(name: &str) -> SharedString {
pub(crate) fn initials(name: &str) -> SharedString {
name.chars().take(2).collect::<String>().into()
}
@ -74,23 +73,29 @@ fn reaction_items(m: &crate::ui::state::ChatMessage, own_user_id: &str) -> Vec<R
/// Field by field comparison; `ModelRc` fields (reactions) compare by identity otherwise and
/// would make every refresh look like a change.
fn same_message(a: &MessageItem, b: &MessageItem) -> bool {
pub(crate) fn same_message(a: &MessageItem, b: &MessageItem) -> bool {
a.message_id == b.message_id
&& a.sender_id == b.sender_id
&& a.sender_name == b.sender_name
&& a.content == b.content
&& a.media_source == b.media_source
&& a.timestamp == b.timestamp
&& a.is_own == b.is_own
&& a.edited == b.edited
&& a.reply_to == b.reply_to
&& a.has_avatar == b.has_avatar
&& (!a.has_avatar || a.avatar == b.avatar)
&& a.avatar_text == b.avatar_text
&& a.show_author == b.show_author
&& a.reactions.iter().eq(b.reactions.iter())
}
fn fmt_ts(ts: i64) -> String {
let secs = (ts / 1000).abs() % 86400;
format!("{:02}:{:02}", secs / 3600, (secs % 3600) / 60)
fn profile_avatar(state: &UiState, device: &str, own_device: &str) -> slint::Image {
state
.avatar_path_for(device, own_device)
.as_deref()
.map(super::avatar::central::image)
.unwrap_or_default()
}
fn set_messages(
@ -99,19 +104,39 @@ fn set_messages(
msgs: &[crate::ui::state::ChatMessage],
own_user_id: &str,
) {
let now = chrono::Local::now();
let items: Vec<MessageItem> = msgs
.iter()
.enumerate()
.map(|(index, m)| MessageItem {
media_image: Default::default(),
media_ready: false,
media_status: Default::default(),
media_ratio: 1.0,
avatar: profile_avatar(state, &m.sender_id, own_user_id),
has_avatar: profile_avatar(state, &m.sender_id, own_user_id)
.size()
.width
> 0,
avatar_text: initials(state.nick_for(&m.sender_id)),
show_author: index == 0
|| msgs[index - 1].sender_id != m.sender_id
|| !super::timestamps::same_day_at(
msgs[index - 1].timestamp,
m.timestamp,
&chrono::Local,
)
|| m.timestamp.saturating_sub(msgs[index - 1].timestamp) > 300_000,
message_id: SharedString::from(m.message_id.as_str()),
sender_id: SharedString::from(m.sender_id.as_str()),
sender_name: SharedString::from(state.nick_for(&m.sender_id)),
content: SharedString::from(m.content.as_str()),
timestamp: SharedString::from(fmt_ts(m.timestamp)),
media_source: m.content.as_str().into(),
content: if m.content.starts_with("vnox-attachment:") {
"".into()
} else {
m.content.as_str().into()
},
timestamp: SharedString::from(super::timestamps::format_at(m.timestamp, &now)),
is_own: m.sender_id == own_user_id,
edited: m.edited,
reactions: Rc::new(VecModel::from(reaction_items(m, own_user_id))).into(),
@ -147,19 +172,31 @@ fn set_messages(
}
}
fn same_member(a: &MemberItem, b: &MemberItem) -> bool {
a.user_id == b.user_id
&& a.nickname == b.nickname
&& a.status == b.status
&& a.presence == b.presence
&& a.avatar_text == b.avatar_text
&& a.is_own == b.is_own
&& a.has_avatar == b.has_avatar
&& (!a.has_avatar || a.avatar == b.avatar)
}
fn set_members_state(window: &MainWindow, state: &UiState, ch_id: &str, own_user_id: &str) {
if let Some(ch) = state.channels.iter().find(|c| c.id == ch_id) {
let items: Vec<MemberItem> = ch
.members
.iter()
.map(|nick| {
let user_id = state
.user_names
.iter()
.find(|(_, n)| *n == nick)
.map(|(id, _)| id.clone())
.unwrap_or_else(|| nick.clone());
let is_own = user_id == own_user_id;
let items: Vec<MemberItem> = state
.account_members(&ch.members)
.into_iter()
.map(|device| {
let user_id = device.clone();
let nick = state.nick_for(device);
let is_own = user_id == own_user_id
|| state
.member_profiles
.get(&user_id)
.zip(state.member_profiles.get(own_user_id))
.is_some_and(|(member, own)| !member.0.is_empty() && member.0 == own.0);
// This client is connected whenever the member list is shown, so the local user
// is online even though the server sends no presence update about oneself.
let status = if is_own {
@ -169,40 +206,38 @@ fn set_members_state(window: &MainWindow, state: &UiState, ch_id: &str, own_user
.presences
.get(&user_id)
.map(|p| p.status.as_str())
.unwrap_or("offline")
.unwrap_or("online")
};
let avatar = profile_avatar(
state,
if is_own { own_user_id } else { device },
own_user_id,
);
MemberItem {
has_avatar: avatar.size().width > 0,
avatar,
avatar_text: initials(nick),
user_id: SharedString::from(user_id),
nickname: SharedString::from(nick.as_str()),
nickname: SharedString::from(nick),
status: presence_label(status).into(),
presence: presence_key(status).into(),
is_own,
}
})
.collect();
replace_model(window.get_members(), items, |model| {
window.set_members(model)
});
let current = window.get_members();
if current.row_count() != items.len()
|| !current.iter().zip(&items).all(|(a, b)| same_member(&a, b))
{
window.set_members(Rc::new(VecModel::from(items)).into());
}
}
}
fn sync_sidebar(window: &MainWindow, state: &UiState, own_nickname: &str) {
crate::ui::channel_admin::sync(window, state);
let guild_id = state.active_guild_id.as_deref();
let channels: Vec<ChannelItem> = state
.channels
.iter()
.filter(|c| match guild_id {
None => true,
Some(gid) => c.guild_id.as_deref() == Some(gid) || c.guild_id.is_none(),
})
.map(|c| ChannelItem {
channel_id: SharedString::from(c.id.as_str()),
name: SharedString::from(c.name.as_str()),
kind: SharedString::from(c.kind.as_str()),
})
.collect();
let channels = crate::ui::channel_admin::sidebar_channels(state);
replace_model(window.get_channels(), channels, |model| {
window.set_channels(model)
});
@ -273,7 +308,7 @@ fn sync_chat(window: &MainWindow, state: &UiState, own_user_id: &str) {
window.set_e2ee_enabled(false);
window.set_dm_partner_name(dm.map_or("", |c| c.other_nickname.as_str()).into());
window.set_show_voice(state.showing_voice);
window.set_show_chat(!state.showing_voice && (dm.is_some() || channel.is_some()));
window.set_show_chat(!state.showing_voice && (dm.is_some() || channel.is_some_and(|channel| channel.kind == "text")));
window.set_show_friends(!state.showing_voice && dm.is_none() && channel.is_none());
if let Some(dm) = dm {
window.set_active_channel_name(dm.other_nickname.as_str().into());
@ -324,7 +359,7 @@ fn sync_friends(window: &MainWindow, state: &UiState) {
.presences
.get(&f.user_id)
.map(|p| p.status.as_str())
.unwrap_or("offline"),
.unwrap_or("online"),
)
.into(),
status: SharedString::from(
@ -332,7 +367,7 @@ fn sync_friends(window: &MainWindow, state: &UiState) {
.presences
.get(&f.user_id)
.map(|p| p.status.as_str())
.unwrap_or("offline"),
.unwrap_or("online"),
),
})
.collect();
@ -378,25 +413,39 @@ pub fn sync_voice(window: &MainWindow, state: &UiState, own_user_id: &str) {
)
})
.flat_map(|c| c.members.iter())
.map(|nick| {
let user_id = state
.user_names
.iter()
.find(|(_, n)| *n == nick)
.map(|(id, _)| id.clone())
.unwrap_or_else(|| nick.clone());
.map(|device| {
let user_id = device.clone();
let nick = state.nick_for(device);
let avatar = profile_avatar(state, device, own_user_id);
VoiceMemberItem {
has_avatar: avatar.size().width > 0,
avatar,
avatar_text: initials(nick),
is_own: user_id == own_user_id,
user_id: SharedString::from(user_id.clone()),
nickname: SharedString::from(nick.as_str()),
speaking: state.remote_speaking && state.last_remote_speaker_id == user_id,
nickname: SharedString::from(nick),
speaking: if user_id == own_user_id {
state.local_speaking
} else {
state.remote_speaking && state.last_remote_speaker_id == user_id
},
}
})
.collect();
replace_model(window.get_voice_members(), members, |model| {
window.set_voice_members(model)
});
let current = window.get_voice_members();
if current.row_count() != members.len()
|| !current.iter().zip(&members).all(|(a, b)| {
a.user_id == b.user_id
&& a.nickname == b.nickname
&& a.speaking == b.speaking
&& a.avatar_text == b.avatar_text
&& a.is_own == b.is_own
&& a.has_avatar == b.has_avatar
&& (!a.has_avatar || a.avatar == b.avatar)
})
{
window.set_voice_members(Rc::new(VecModel::from(members)).into());
}
window.set_mic_enabled(state.mic_enabled);
window.set_deafened(state.deafen);
@ -487,6 +536,12 @@ pub fn sync_settings(window: &MainWindow, state: &UiState, own_pubkey: &str) {
window.set_voice_bitrate(state.voice_bitrate);
window.set_vad_mode(state.vad_mode as i32);
window.set_volume(state.output_volume);
window.set_noise_suppress(state.noise_suppress);
window.set_noise_suppress_available(cfg!(feature = "rnnoise"));
window.set_mic_test_running(state.mic_test_running);
window.set_mic_test_level(state.mic_test_level);
window.set_mic_test_error(state.mic_test_error.as_deref().unwrap_or("").into());
window.set_local_speaking(state.local_speaking);
window.set_sounds_enabled(state.sounds.enabled);
window.set_sounds_volume(state.sounds.volume);
window.set_sounds_voice_room(state.sounds.voice_room);
@ -531,6 +586,26 @@ pub fn sync_ui(
own_nickname: &str,
own_pubkey: &str,
) {
crate::ui::forum::sync(window, state, own_user_id);
if let Some(account) = &state.central_account {
if window.get_profile_display_name() == window.get_account_name() {
window.set_profile_display_name(account.display_name.clone().into());
}
window.set_account_name(account.display_name.clone().into());
window.set_profile_initials(initials(&account.display_name));
let image = super::avatar::central::image(
&state
.avatar_path_for(own_user_id, own_user_id)
.unwrap_or_default(),
);
window.set_has_avatar(image.size().width > 0);
window.set_own_avatar(image);
}
let own_nickname = state
.central_account
.as_ref()
.map(|account| account.display_name.as_str())
.unwrap_or(own_nickname);
sync_sidebar(window, state, own_nickname);
sync_chat(window, state, own_user_id);
sync_friends(window, state);
@ -538,3 +613,22 @@ pub fn sync_ui(
sync_connect(window, state);
sync_settings(window, state, own_pubkey);
}
#[cfg(test)]
mod avatar_model_tests {
#[test]
fn empty_avatars_do_not_replace_unchanged_message_and_member_models() {
let message = super::MessageItem::default();
assert!(super::same_message(
&message,
&super::MessageItem::default()
));
let member = super::MemberItem::default();
assert!(super::same_member(&member, &super::MemberItem::default()));
let changed = super::MemberItem {
has_avatar: true,
..Default::default()
};
assert!(!super::same_member(&member, &changed));
}
}

853
src/ui/channel_admin.rs Normal file
View file

@ -0,0 +1,853 @@
//! Node-advertised global channel management. Gateway authorization remains authoritative.
use crate::{
AppState,
net::{NetCommand, NetEvent},
ui::{
slint::MainWindow,
state::{ConnState, UiState},
},
};
use slint::{ComponentHandle, Model};
use std::{
cell::RefCell,
rc::Rc,
time::{Duration, Instant},
};
#[derive(Clone)]
enum Dialog {
Create {
parent_id: Option<String>,
id: String,
name: String,
kind: String,
},
Rename {
id: String,
name: String,
},
Delete {
id: String,
name: String,
},
}
impl Dialog {
fn id(&self) -> &str {
match self {
Self::Create { id, .. } | Self::Rename { id, .. } | Self::Delete { id, .. } => id,
}
}
fn name(&self) -> &str {
match self {
Self::Create { name, .. } | Self::Rename { name, .. } | Self::Delete { name, .. } => {
name
}
}
}
fn operation(&self) -> &str {
match self {
Self::Create { .. } => "create",
Self::Rename { .. } => "rename",
Self::Delete { .. } => "delete",
}
}
}
/// Unsaved dialog draft and at most one unacknowledged global channel operation.
#[derive(Default)]
pub struct AdminState {
menu: Option<Menu>,
categories: Vec<(String, String)>,
dialog: Option<Dialog>,
pending: Option<Instant>,
error: String,
}
pub(super) fn allowed(ui: &UiState) -> bool {
ui.node_admin
&& matches!(ui.conn, ConnState::Connected { .. })
&& !ui.connection.authentication_required
&& ui.central_account.is_some()
&& ui.active_guild_id.is_none()
&& !ui.browsing_dms
}
fn open(ui: &mut UiState, operation: &str, id_or_kind: &str) {
if !allowed(ui) || ui.channel_admin.pending.is_some() {
return;
}
let dialog = if operation == "create" {
if !["text", "voice", "category", "forum"].contains(&id_or_kind)
|| (id_or_kind == "category" && !ui.channel_structure_supported)
|| (id_or_kind == "forum" && !ui.forum.supported)
{
return;
}
Dialog::Create {
parent_id: None,
id: uuid::Uuid::new_v4().to_string(),
name: String::new(),
kind: id_or_kind.to_owned(),
}
} else {
let Some(channel) = ui
.channels
.iter()
.find(|channel| channel.id == id_or_kind && channel.guild_id.is_none())
else {
return;
};
match operation {
"rename" => Dialog::Rename {
id: channel.id.clone(),
name: channel.name.clone(),
},
"delete" => Dialog::Delete {
id: channel.id.clone(),
name: channel.name.clone(),
},
_ => return,
}
};
let categories = category_choices(ui);
ui.channel_admin = AdminState {
categories,
dialog: Some(dialog),
..Default::default()
};
}
fn prepare(ui: &mut UiState) -> Option<NetCommand> {
if !allowed(ui) || ui.channel_admin.pending.is_some() {
return None;
}
let dialog = ui.channel_admin.dialog.clone()?;
if !matches!(dialog, Dialog::Create { .. })
&& !ui
.channels
.iter()
.any(|channel| channel.id == dialog.id() && channel.guild_id.is_none())
{
ui.channel_admin.error = super::i18n::text("This global channel is no longer available.");
return None;
}
if let Dialog::Create {
kind, parent_id, ..
} = &dialog
{
if (kind == "category" && !ui.channel_structure_supported)
|| (kind == "forum" && !ui.forum.supported)
|| parent_id.as_ref().is_some_and(|parent| {
!ui.channels.iter().any(|channel| {
channel.id == *parent
&& channel.kind == "category"
&& channel.guild_id.is_none()
})
})
{
ui.channel_admin.error =
super::i18n::text("This channel type or category is no longer available.");
return None;
}
}
let name = dialog.name().trim();
if !matches!(dialog, Dialog::Delete { .. })
&& (name.is_empty() || name.chars().count() > 100 || name.chars().any(char::is_control))
{
ui.channel_admin.error =
super::i18n::text("Enter a channel name (1–100 characters, no control characters).");
return None;
}
let command = match dialog {
Dialog::Create {
ref id,
ref kind,
ref parent_id,
..
} => NetCommand::ChannelCreate {
channel_id: id.clone(),
channel_name: name.to_owned(),
kind: kind.clone(),
guild_id: None,
parent_id: parent_id.clone(),
position: 0,
},
Dialog::Rename { ref id, .. } => NetCommand::ChannelEdit {
channel_id: id.clone(),
channel_name: name.to_owned(),
parent_id: None,
position: None,
},
Dialog::Delete { ref id, .. } => NetCommand::ChannelDelete {
channel_id: id.clone(),
},
};
ui.channel_admin.pending = Some(Instant::now());
ui.channel_admin.error.clear();
Some(command)
}
fn prepare_for_session(ui: &mut UiState) -> Option<NetCommand> {
let session_id = match &ui.conn {
ConnState::Connected { session_id, .. } => session_id.clone(),
_ => return None,
};
let command = prepare(ui)?;
Some(NetCommand::ForSession {
session_id,
command: Box::new(command),
})
}
/// Connect transient management callbacks; every submission rechecks server capability and scope.
pub fn wire(window: &MainWindow, state: &Rc<RefCell<AppState>>) {
super::server_settings::wire(window, state);
wire_menus(window, state);
for operation in ["create", "rename", "delete"] {
let state = state.clone();
let handler = move |value: slint::SharedString| {
open(&mut state.borrow_mut().ui, operation, value.as_str())
};
match operation {
"create" => window.on_create_global_channel(handler),
"rename" => window.on_rename_global_channel(handler),
_ => window.on_delete_global_channel(handler),
}
}
{
let state = state.clone();
window.on_channel_admin_name_edited(move |name| {
let mut state = state.borrow_mut();
if state.ui.channel_admin.pending.is_some() {
return;
}
if let Some(Dialog::Create { name: value, .. } | Dialog::Rename { name: value, .. }) =
state.ui.channel_admin.dialog.as_mut()
{
*value = name.to_string();
}
});
}
{
let state = state.clone();
window.on_channel_admin_cancel(move || {
// Cancellation closes the UI; it cannot recall a request already sent to the server.
state.borrow_mut().ui.channel_admin = AdminState::default();
});
}
{
let state = state.clone();
window.on_channel_admin_submit(move || {
let (command, net) = {
let mut state = state.borrow_mut();
(prepare_for_session(&mut state.ui), state.net.clone())
};
if let Some(command) = command {
tokio::spawn(async move {
net.send(command).await;
});
}
});
}
}
/// Close unavailable management UI and report an unacknowledged request after ten seconds.
pub fn tick(ui: &mut UiState) {
if ui
.channel_admin
.menu
.as_ref()
.is_some_and(|menu| current_session(ui) != Some(menu.session_id.as_str()))
{
ui.channel_admin.menu = None;
}
if !allowed(ui) {
ui.channel_admin.dialog = None;
ui.channel_admin.pending = None;
return;
}
if ui
.channel_admin
.pending
.is_some_and(|started| started.elapsed() >= Duration::from_secs(10))
{
ui.channel_admin.pending = None;
ui.channel_admin.error = super::i18n::text(
"No confirmation received. Close this dialog and check the channel list before trying again.",
);
}
}
/// Consume matching server acknowledgements without changing channel membership optimistically.
pub fn receive(ui: &mut UiState, event: &NetEvent) {
if matches!(
event,
NetEvent::Disconnected { .. } | NetEvent::Reconnecting { .. } | NetEvent::AccountRequired
) {
ui.node_admin = false;
ui.channel_admin = AdminState::default();
return;
}
if ui.channel_admin.pending.is_none() {
return;
}
let Some(dialog) = &ui.channel_admin.dialog else {
return;
};
let success = match (dialog, event) {
(
Dialog::Create { id, name, .. },
NetEvent::ChannelCreated {
channel_id,
channel_name,
guild_id,
..
}
| NetEvent::ChannelState {
channel_id,
channel_name,
guild_id,
..
},
) => id == channel_id && name.trim() == channel_name && guild_id.is_none(),
(
Dialog::Rename { id, name },
NetEvent::ChannelEdited {
channel_id,
channel_name,
..
},
) => id == channel_id && name.trim() == channel_name,
(Dialog::Delete { id, .. }, NetEvent::ChannelDeleted { channel_id }) => id == channel_id,
_ => false,
};
if success {
ui.channel_admin = AdminState::default();
} else if let NetEvent::Error { message, .. } = event {
// LNEx generic errors do not carry a request ID. Keep the dialog and its draft;
// never infer success or roll back a server change from an uncorrelated error.
ui.channel_admin.pending = None;
ui.channel_admin.error =
super::i18n::format("Server error: {message}", &[("message", message.clone())]);
}
}
/// Copy the capability and transient management state into the native UI.
pub fn sync(window: &MainWindow, ui: &UiState) {
super::server_settings::sync(window, ui);
let menu = ui.channel_admin.menu.as_ref();
window.set_management_menu_open(menu.is_some());
window.set_management_menu_x(menu.map(|menu| menu.x).unwrap_or(0.0));
window.set_management_menu_y(menu.map(|menu| menu.y).unwrap_or(0.0));
let actions = menu
.map(|menu| {
menu.actions
.iter()
.map(|item| crate::ui::slint::ManagementAction {
text: item.text.clone().into(),
icon: item.icon.into(),
action: item.action.into(),
danger: item.action == "delete" || item.action == "disconnect",
})
.collect::<Vec<_>>()
})
.unwrap_or_default();
if !window
.get_management_actions()
.iter()
.eq(actions.iter().cloned())
{
window.set_management_actions(std::rc::Rc::new(slint::VecModel::from(actions)).into());
}
let mut names = vec![slint::SharedString::from(super::i18n::text("No category"))];
names.extend(
ui.channel_admin
.categories
.iter()
.map(|(_, name)| name.as_str().into()),
);
if !window
.get_channel_admin_parent_names()
.iter()
.eq(names.iter().cloned())
{
window
.set_channel_admin_parent_names(std::rc::Rc::new(slint::VecModel::from(names)).into());
}
let parent = match &ui.channel_admin.dialog {
Some(Dialog::Create { parent_id, .. }) => parent_id.as_deref(),
_ => None,
};
window.set_channel_admin_parent_index(
parent
.and_then(|id| {
ui.channel_admin
.categories
.iter()
.position(|(value, _)| value == id)
})
.map(|index| index + 1)
.unwrap_or(0) as i32,
);
window.set_node_structure(ui.channel_structure_supported);
window.set_node_forums(ui.forum.supported);
window.set_node_admin(allowed(ui));
let dialog = ui.channel_admin.dialog.as_ref();
window.set_channel_admin_open(dialog.is_some() && allowed(ui));
window.set_channel_admin_operation(dialog.map(Dialog::operation).unwrap_or("").into());
window.set_channel_admin_name(dialog.map(Dialog::name).unwrap_or("").into());
window.set_channel_admin_kind(
match dialog {
Some(Dialog::Create { kind, .. }) => kind.as_str(),
_ => "",
}
.into(),
);
window.set_channel_admin_busy(ui.channel_admin.pending.is_some());
window.set_channel_admin_error(ui.channel_admin.error.as_str().into());
}
#[cfg(test)]
mod tests {
use super::*;
fn admin() -> UiState {
UiState {
node_admin: true,
conn: ConnState::Connected {
session_id: "fixture".into(),
node_name: "Fixture server".into(),
},
central_account: Some(crate::net::account::AccountSummary {
user_id: "fixture-account".into(),
handle: "fixture".into(),
display_name: "Fixture".into(),
avatar_url: None,
profile_complete: false,
}),
channels: vec![
crate::ui::state::Channel {
id: "global".into(),
name: "General".into(),
kind: "text".into(),
guild_id: None,
members: vec![],
},
crate::ui::state::Channel {
id: "guild-channel".into(),
name: "Guild".into(),
kind: "voice".into(),
guild_id: Some("guild".into()),
members: vec![],
},
],
..Default::default()
}
}
#[test]
fn every_management_command_is_scoped_to_the_session_that_prepared_it() {
for (operation, value) in [
("create", "text"),
("rename", "global"),
("delete", "global"),
] {
let mut ui = admin();
open(&mut ui, operation, value);
if let Some(Dialog::Create { name, .. }) = &mut ui.channel_admin.dialog {
*name = "New".into();
}
let command = prepare_for_session(&mut ui).unwrap();
ui.conn = ConnState::Connected {
session_id: "replacement-session".into(),
node_name: "Other node".into(),
};
match command {
NetCommand::ForSession {
session_id,
command,
} => {
assert_eq!(session_id, "fixture");
assert!(matches!(
*command,
NetCommand::ChannelCreate { .. }
| NetCommand::ChannelEdit { .. }
| NetCommand::ChannelDelete { .. }
));
}
_ => panic!("management command escaped its original session"),
}
}
}
#[test]
fn capability_and_global_scope_are_rechecked_for_every_action() {
let mut ui = admin();
ui.node_admin = false;
open(&mut ui, "create", "text");
assert!(ui.channel_admin.dialog.is_none());
ui.node_admin = true;
open(&mut ui, "rename", "guild-channel");
assert!(ui.channel_admin.dialog.is_none());
ui.active_guild_id = Some("guild".into());
open(&mut ui, "create", "text");
assert!(ui.channel_admin.dialog.is_none());
ui.active_guild_id = None;
open(&mut ui, "create", "text");
ui.node_admin = false;
assert!(prepare(&mut ui).is_none());
tick(&mut ui);
assert!(ui.channel_admin.dialog.is_none());
}
#[test]
fn create_keeps_stable_id_and_draft_until_matching_server_confirmation() {
let mut ui = admin();
open(&mut ui, "create", "voice");
if let Some(Dialog::Create { name, .. }) = &mut ui.channel_admin.dialog {
*name = " New room ".into();
}
let before = ui.channels.len();
let id = match prepare(&mut ui).unwrap() {
NetCommand::ChannelCreate {
channel_id,
channel_name,
kind,
guild_id,
} => {
assert_eq!(channel_name, "New room");
assert_eq!(kind, "voice");
assert!(guild_id.is_none());
channel_id
}
_ => panic!(),
};
assert_eq!(ui.channels.len(), before);
assert!(prepare(&mut ui).is_none());
receive(
&mut ui,
&NetEvent::ChannelCreated {
channel_id: "unrelated".into(),
channel_name: "Other".into(),
kind: "voice".into(),
guild_id: None,
},
);
assert!(ui.channel_admin.pending.is_some());
receive(
&mut ui,
&NetEvent::Error {
code: 1,
message: "permission denied".into(),
},
);
assert!(ui.channel_admin.pending.is_none());
assert!(!ui.channel_admin.error.is_empty());
assert_eq!(ui.channel_admin.dialog.as_ref().unwrap().id(), id);
assert!(prepare(&mut ui).is_some());
receive(
&mut ui,
&NetEvent::ChannelState {
channel_id: id,
channel_name: "New room".into(),
kind: "voice".into(),
guild_id: None,
members: vec![],
voice_endpoint: String::new(),
},
);
assert!(ui.channel_admin.dialog.is_none());
}
#[test]
fn rename_and_delete_require_submit_and_matching_ack_and_handle_disconnect() {
let mut ui = admin();
open(&mut ui, "rename", "global");
if let Some(Dialog::Rename { name, .. }) = &mut ui.channel_admin.dialog {
*name = "Renamed".into();
}
assert!(
matches!(prepare(&mut ui),Some(NetCommand::ChannelEdit{channel_name,..}) if channel_name=="Renamed")
);
receive(
&mut ui,
&NetEvent::ChannelEdited {
channel_id: "global".into(),
channel_name: "Renamed".into(),
},
);
assert!(ui.channel_admin.dialog.is_none());
open(&mut ui, "delete", "global");
assert!(ui.channel_admin.pending.is_none());
assert_eq!(ui.channels.len(), 2);
assert!(
matches!(prepare(&mut ui),Some(NetCommand::ChannelDelete{channel_id}) if channel_id=="global")
);
receive(
&mut ui,
&NetEvent::Disconnected {
reason: "fixture".into(),
will_retry: false,
},
);
assert!(!ui.node_admin);
assert!(ui.channel_admin.dialog.is_none());
}
#[test]
fn invalid_names_and_timeout_do_not_mutate_channels_or_duplicate_requests() {
let mut ui = admin();
open(&mut ui, "create", "text");
assert!(prepare(&mut ui).is_none());
if let Some(Dialog::Create { name, .. }) = &mut ui.channel_admin.dialog {
*name = "bad\nname".into();
}
assert!(prepare(&mut ui).is_none());
if let Some(Dialog::Create { name, .. }) = &mut ui.channel_admin.dialog {
*name = "Valid".into();
}
assert!(prepare(&mut ui).is_some());
ui.channel_admin.pending = Some(Instant::now() - Duration::from_secs(11));
tick(&mut ui);
assert!(ui.channel_admin.pending.is_none());
assert!(!ui.channel_admin.error.is_empty());
assert_eq!(ui.channels.len(), 2);
}
}
struct MenuAction {
text: String,
icon: &'static str,
action: &'static str,
}
struct Menu {
session_id: String,
context: String,
x: f32,
y: f32,
actions: Vec<MenuAction>,
}
fn current_session(ui: &UiState) -> Option<&str> {
match &ui.conn {
ConnState::Connected { session_id, .. } => Some(session_id),
_ => None,
}
}
fn category_choices(ui: &UiState) -> Vec<(String, String)> {
let mut categories: Vec<_> = ui
.channels
.iter()
.filter(|channel| channel.kind == "category" && channel.guild_id.is_none())
.collect();
categories.sort_by_key(|channel| (channel.position, channel.name.clone(), channel.id.clone()));
categories
.into_iter()
.map(|channel| (channel.id.clone(), channel.name.clone()))
.collect()
}
fn create_in(ui: &mut UiState, kind: &str, context: &str) {
let parent = ui
.channels
.iter()
.find(|channel| channel.id == context && channel.guild_id.is_none())
.and_then(|channel| {
if channel.kind == "category" {
Some(channel.id.clone())
} else {
channel.parent_id.clone()
}
});
open(ui, "create", kind);
if kind != "category"
&& let Some(Dialog::Create { parent_id, .. }) = &mut ui.channel_admin.dialog
{
*parent_id = parent;
}
}
fn open_menu(ui: &mut UiState, server: bool, context: &str, x: f32, y: f32) {
let Some(session_id) = current_session(ui).map(str::to_owned) else {
return;
};
if ui.active_guild_id.is_some()
|| ui.browsing_dms
|| ui.central_account.is_none()
|| (!server && !allowed(ui))
{
return;
}
let mut actions = Vec::new();
let mut add = |text: &str, icon, action| {
actions.push(MenuAction {
text: super::i18n::text(text),
icon,
action,
})
};
if server {
if allowed(ui) && ui.node_settings_supported {
add("Server settings", "settings", "settings");
}
add("Disconnect from server", "log-out", "disconnect");
} else {
add("Create text channel", "hash", "text");
add("Create voice room", "volume-2", "voice");
if ui.channel_structure_supported {
add("Create category", "folder", "category");
}
if ui.forum.supported {
add("Create forum", "messages-square", "forum");
}
if ui
.channels
.iter()
.any(|channel| channel.id == context && channel.guild_id.is_none())
{
add("Rename channel", "pencil", "rename");
add("Delete channel", "trash-2", "delete");
}
}
ui.channel_admin.menu = Some(Menu {
session_id,
context: context.to_owned(),
x,
y,
actions,
});
}
fn wire_menus(window: &MainWindow, state: &Rc<RefCell<AppState>>) {
{
let state = state.clone();
window.on_open_node_menu(move |x, y| open_menu(&mut state.borrow_mut().ui, true, "", x, y));
}
{
let state = state.clone();
window.on_open_channel_menu(move |id, x, y| {
open_menu(&mut state.borrow_mut().ui, false, id.as_str(), x, y)
});
}
{
let state = state.clone();
window.on_management_menu_close(move || {
state.borrow_mut().ui.channel_admin.menu = None;
});
}
{
let state = state.clone();
window.on_toggle_category(move |id| {
let mut state = state.borrow_mut();
if state
.ui
.channels
.iter()
.any(|channel| channel.id == id.as_str() && channel.kind == "category")
&& !state.ui.collapsed_categories.remove(id.as_str())
{
state.ui.collapsed_categories.insert(id.to_string());
}
});
}
{
let state = state.clone();
window.on_channel_admin_parent_selected(move |index| {
let mut state = state.borrow_mut();
if state.ui.channel_admin.pending.is_some() {
return;
}
let parent = if index == 0 {
None
} else {
state
.ui
.channel_admin
.categories
.get(index.saturating_sub(1) as usize)
.map(|(id, _)| id.clone())
};
if let Some(Dialog::Create {
parent_id, kind, ..
}) = &mut state.ui.channel_admin.dialog
&& kind != "category"
{
*parent_id = parent;
}
});
}
{
let state = state.clone();
let weak = window.as_weak();
window.on_management_menu_chosen(move |action| {
let (command, net, disconnect) = {
let mut state = state.borrow_mut();
let Some(menu) = state.ui.channel_admin.menu.take() else {
return;
};
if current_session(&state.ui) != Some(menu.session_id.as_str())
|| !menu
.actions
.iter()
.any(|item| item.action == action.as_str())
{
return;
}
let mut command = None;
let mut disconnect = false;
match action.as_str() {
"settings" => command = super::server_settings::open(&mut state.ui),
"disconnect" => disconnect = true,
"rename" | "delete" => open(&mut state.ui, action.as_str(), &menu.context),
kind => create_in(&mut state.ui, kind, &menu.context),
}
(command, state.net.clone(), disconnect)
};
if let Some(command) = command {
tokio::spawn(async move {
net.send(command).await;
});
}
if disconnect && let Some(window) = weak.upgrade() {
window.invoke_disconnect();
}
});
}
}
/// Flatten one-level categories without turning containers into channel subscriptions.
pub fn sidebar_channels(ui: &UiState) -> Vec<crate::ui::slint::ChannelItem> {
let mut visible: Vec<_> = ui
.channels
.iter()
.filter(|channel| match ui.active_guild_id.as_deref() {
None => channel.guild_id.is_none(),
Some(id) => channel.guild_id.is_none() || channel.guild_id.as_deref() == Some(id),
})
.collect();
visible.sort_by_key(|channel| (channel.position, channel.name.clone(), channel.id.clone()));
let categories: Vec<_> = visible
.iter()
.copied()
.filter(|channel| channel.kind == "category")
.collect();
let mut result = Vec::new();
let mut push = |channel: &crate::ui::state::Channel, indent| {
result.push(crate::ui::slint::ChannelItem {
channel_id: channel.id.as_str().into(),
name: channel.name.as_str().into(),
kind: channel.kind.as_str().into(),
is_global: channel.guild_id.is_none(),
indented: indent,
collapsed: ui.collapsed_categories.contains(&channel.id),
parent_id: channel.parent_id.as_deref().unwrap_or("").into(),
})
};
for channel in &visible {
if channel.kind != "category"
&& (channel.parent_id.is_none()
|| !categories
.iter()
.any(|parent| Some(parent.id.as_str()) == channel.parent_id.as_deref()))
{
push(channel, false);
}
}
for category in categories {
push(category, false);
if !ui.collapsed_categories.contains(&category.id) {
for channel in &visible {
if channel.parent_id.as_deref() == Some(category.id.as_str()) {
push(channel, true);
}
}
}
}
result
}

449
src/ui/chat_images.rs Normal file
View file

@ -0,0 +1,449 @@
//! Bounded chat image decoding and public HTTPS image downloads.
//!
//! Decoding and clipboard reads belong on a blocking worker, never the UI thread.
use std::{io::Cursor, net::IpAddr, time::Duration};
use anyhow::{Context, Result, bail, ensure};
use image::{AnimationDecoder, ImageDecoder, ImageEncoder, ImageFormat};
pub const MAX_ENCODED_BYTES: usize = 3 * 1024 * 1024;
pub const MAX_REMOTE_ENCODED_BYTES: usize = 16 * 1024 * 1024;
pub const MAX_RGBA_BYTES: usize = 64 * 1024 * 1024;
const MAX_SOURCE_PIXELS: u64 = 128 * 1024 * 1024;
const GIF_PREVIEW_SIDE: u32 = 384;
const MAX_PIXELS: u64 = 4 * 1024 * 1024;
const MAX_SIDE: u32 = 4096;
const MAX_FRAMES: usize = 120;
#[derive(Debug)]
pub struct ImageFrame {
pub rgba: Vec<u8>,
pub delay_ms: u32,
}
#[derive(Debug)]
pub struct DecodedImage {
pub width: u32,
pub height: u32,
pub frames: Vec<ImageFrame>,
}
fn dimensions(width: u32, height: u32) -> Result<()> {
ensure!(
width > 0
&& height > 0
&& width <= MAX_SIDE
&& height <= MAX_SIDE
&& u64::from(width) * u64::from(height) <= MAX_PIXELS,
"Image dimensions exceed the 4096 px / 4 megapixel limit"
);
Ok(())
}
fn limits() -> image::Limits {
let mut limits = image::Limits::default();
limits.max_image_width = Some(MAX_SIDE);
limits.max_image_height = Some(MAX_SIDE);
limits.max_alloc = Some(64 * 1024 * 1024);
limits
}
/// Decode supported raster formats, preserving composited GIF frames and timing.
pub fn decode(bytes: &[u8]) -> Result<DecodedImage> {
ensure!(
!bytes.is_empty() && bytes.len() <= MAX_REMOTE_ENCODED_BYTES,
"Image must be no larger than 16 MiB"
);
let format = image::guess_format(bytes).context("Unsupported image")?;
ensure!(
matches!(
format,
ImageFormat::Png | ImageFormat::Jpeg | ImageFormat::WebP | ImageFormat::Gif
),
"Use PNG, JPEG, WebP or GIF"
);
let (mut width, mut height) = image::ImageReader::with_format(Cursor::new(bytes), format)
.into_dimensions()
.context("Invalid image header")?;
dimensions(width, height)?;
let mut frames = Vec::new();
if format == ImageFormat::Gif {
let mut decoder = image::codecs::gif::GifDecoder::new(Cursor::new(bytes))?;
decoder.set_limits(limits())?;
let source_pixels = u64::from(width) * u64::from(height);
let longest = width.max(height);
if longest > GIF_PREVIEW_SIDE {
width = (width * GIF_PREVIEW_SIDE / longest).max(1);
height = (height * GIF_PREVIEW_SIDE / longest).max(1);
}
let frame_bytes = width as usize * height as usize * 4;
for frame in decoder.into_frames() {
ensure!(
frames.len() < MAX_FRAMES
&& (frames.len() + 1) * frame_bytes <= MAX_RGBA_BYTES
&& (frames.len() as u64 + 1) * source_pixels <= MAX_SOURCE_PIXELS,
"GIF exceeds the animation limit (120 frames / 64 MiB preview / 128 megapixels decoded)"
);
let frame = frame.context("Invalid GIF frame")?;
let (numerator, denominator) = frame.delay().numer_denom_ms();
let delay_ms = (numerator / denominator.max(1)).clamp(20, 10_000);
let original = frame.into_buffer();
let buffer = if original.dimensions() == (width, height) {
original
} else {
image::imageops::resize(
&original,
width,
height,
image::imageops::FilterType::Triangle,
)
};
frames.push(ImageFrame {
rgba: buffer.into_raw(),
delay_ms,
});
}
ensure!(!frames.is_empty(), "GIF has no frames");
} else {
let mut reader = image::ImageReader::with_format(Cursor::new(bytes), format);
reader.limits(limits());
let image = reader.decode().context("Invalid image data")?.into_rgba8();
frames.push(ImageFrame {
rgba: image.into_raw(),
delay_ms: 100,
});
}
Ok(DecodedImage {
width,
height,
frames,
})
}
/// Extract one direct HTTPS raster-image URL from ordinary message text.
pub fn image_url(body: &str) -> Option<String> {
body.split_whitespace().find_map(|token| {
let token = token.trim_matches(|c: char| {
matches!(
c,
'<' | '>' | '"' | '\'' | '(' | ')' | '[' | ']' | ',' | ';'
)
});
let url = reqwest::Url::parse(token).ok()?;
validate_url(&url).ok()?;
let path = url.path().to_ascii_lowercase();
[".png", ".jpg", ".jpeg", ".webp", ".gif"]
.iter()
.any(|ext| path.ends_with(ext))
.then(|| url.to_string())
})
}
fn validate_url(url: &reqwest::Url) -> Result<()> {
ensure!(
url.scheme() == "https"
&& url.host_str().is_some()
&& url.port_or_known_default() == Some(443)
&& url.username().is_empty()
&& url.password().is_none(),
"Only public HTTPS image URLs on port 443 are allowed"
);
if let Ok(address) = url
.host_str()
.unwrap_or_default()
.trim_matches(['[', ']'])
.parse::<IpAddr>()
{
ensure!(
public_ip(address),
"Private or reserved image address is blocked"
);
}
Ok(())
}
fn public_ip(address: IpAddr) -> bool {
match address {
IpAddr::V4(ip) => {
let [a, b, c, _] = ip.octets();
!(a == 0
|| a == 10
|| a == 127
|| a >= 224
|| (a == 100 && (64..=127).contains(&b))
|| (a == 169 && b == 254)
|| (a == 172 && (16..=31).contains(&b))
|| (a == 192 && (b == 168 || b == 0 || (b == 88 && c == 99)))
|| (a == 198 && (b == 18 || b == 19 || (b == 51 && c == 100)))
|| (a == 203 && b == 0 && c == 113))
}
IpAddr::V6(ip) => {
let s = ip.segments();
// Only native global-unicast addresses; exclude special-purpose,
// documentation, NAT64 and transition networks conservatively.
(s[0] & 0xe000) == 0x2000
&& !(s[0] == 0x2001 && (s[1] < 0x0200 || s[1] == 0x0db8))
&& s[0] != 0x2002
&& !(s[0] == 0x3fff && s[1] < 0x1000)
}
}
}
/// Download without ambient proxies, cookies or credentials. Every redirect is
/// revalidated and resolved once, then the verified addresses are pinned for TLS.
pub async fn fetch(url: &str) -> Result<Vec<u8>> {
tokio::time::timeout(Duration::from_secs(30), fetch_inner(url))
.await
.context("Image download timed out")?
}
async fn fetch_inner(url: &str) -> Result<Vec<u8>> {
let mut url = reqwest::Url::parse(url).context("Invalid image URL")?;
for redirect in 0..=3 {
validate_url(&url)?;
let host = url
.host_str()
.context("Image URL has no hostname")?
.trim_matches(['[', ']']);
let addresses: Vec<_> =
tokio::time::timeout(Duration::from_secs(5), tokio::net::lookup_host((host, 443)))
.await
.context("Image DNS lookup timed out")??
.collect();
ensure!(
!addresses.is_empty()
&& addresses.len() <= 32
&& addresses.iter().all(|a| public_ip(a.ip())),
"Private or reserved image address is blocked"
);
let client = reqwest::Client::builder()
.no_proxy()
.redirect(reqwest::redirect::Policy::none())
.connect_timeout(Duration::from_secs(5))
.timeout(Duration::from_secs(15))
.resolve_to_addrs(host, &addresses)
.build()?;
let mut response = client
.get(url.clone())
.header(
reqwest::header::ACCEPT,
"image/png,image/jpeg,image/webp,image/gif",
)
.send()
.await?;
if response.status().is_redirection() {
ensure!(redirect < 3, "Too many image redirects");
let location = response
.headers()
.get(reqwest::header::LOCATION)
.context("Image redirect has no location")?
.to_str()?;
url = url.join(location).context("Invalid image redirect")?;
continue;
}
ensure!(
response.status().is_success(),
"Image server returned {}",
response.status()
);
ensure!(
response
.content_length()
.is_none_or(|length| length <= MAX_REMOTE_ENCODED_BYTES as u64),
"Image exceeds 16 MiB"
);
let mut bytes = Vec::new();
while let Some(chunk) = response.chunk().await? {
ensure!(
bytes.len().saturating_add(chunk.len()) <= MAX_REMOTE_ENCODED_BYTES,
"Image exceeds 16 MiB"
);
bytes.extend_from_slice(&chunk);
}
ensure!(!bytes.is_empty(), "Image response is empty");
return Ok(bytes);
}
bail!("Too many image redirects")
}
/// Read an explicitly requested native clipboard image. This can block on the
/// clipboard owner; prefer a worker even when PNG encoding is split off.
pub fn clipboard_image() -> Result<arboard::ImageData<'static>> {
let mut clipboard = arboard::Clipboard::new().context("Cannot open clipboard")?;
let image = clipboard.get_image().context("Clipboard has no image")?;
// Validation belongs to the preview worker so image errors are shown instead of
// falling through to ordinary text paste.
Ok(image)
}
/// Encode a native clipboard image on a blocking worker for a preview draft.
pub fn encode_clipboard_png(image: arboard::ImageData<'_>) -> Result<Vec<u8>> {
let width = u32::try_from(image.width)?;
let height = u32::try_from(image.height)?;
dimensions(width, height)?;
ensure!(
image.bytes.len() == width as usize * height as usize * 4,
"Invalid clipboard image data"
);
let mut bytes = Vec::new();
image::codecs::png::PngEncoder::new(&mut bytes).write_image(
&image.bytes,
width,
height,
image::ExtendedColorType::Rgba8,
)?;
ensure!(
bytes.len() <= MAX_ENCODED_BYTES,
"Clipboard image exceeds 3 MiB; choose a smaller image"
);
Ok(bytes)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn extracts_https_images_without_treating_paths_as_urls() {
assert_eq!(
image_url("look https://example.org/cat.GIF?x=1"),
Some("https://example.org/cat.GIF?x=1".into())
);
for body in [
"file:///tmp/cat.png",
"/tmp/cat.png",
"http://example.org/a.png",
"https://example.org/page",
"https://user:secret@example.org/a.png",
"https://127.0.0.1/a.png",
] {
assert!(image_url(body).is_none(), "{body}");
}
}
#[test]
fn blocks_private_reserved_and_transition_addresses() {
for address in [
"0.0.0.0",
"10.0.0.1",
"100.64.0.1",
"127.0.0.1",
"169.254.169.254",
"172.16.1.1",
"192.168.0.1",
"192.0.2.1",
"198.18.0.1",
"198.51.100.1",
"203.0.113.1",
"224.0.0.1",
"240.0.0.1",
"::1",
"::ffff:8.8.8.8",
"fc00::1",
"fe80::1",
"2001:db8::1",
"2002:7f00:1::",
"3fff::1",
] {
assert!(!public_ip(address.parse().unwrap()), "{address}");
}
for address in [
"8.8.8.8",
"1.1.1.1",
"2606:4700:4700::1111",
"2001:4860:4860::8888",
] {
assert!(public_ip(address.parse().unwrap()), "{address}");
}
}
#[test]
fn validates_url_scheme_port_and_credentials() {
for url in [
"http://example.org/a.png",
"https://example.org:8080/a.png",
"https://a:b@example.org/a.png",
"https://[::1]/a.gif",
] {
assert!(validate_url(&reqwest::Url::parse(url).unwrap()).is_err());
}
}
#[test]
fn decodes_png_and_preserves_rgba() {
let mut png = Vec::new();
image::codecs::png::PngEncoder::new(&mut png)
.write_image(&[1, 2, 3, 255], 1, 1, image::ExtendedColorType::Rgba8)
.unwrap();
let decoded = decode(&png).unwrap();
assert_eq!((decoded.width, decoded.height), (1, 1));
assert_eq!(decoded.frames[0].rgba, [1, 2, 3, 255]);
}
#[test]
fn rejects_oversized_encoded_data_and_dimensions() {
assert!(decode(&vec![0; MAX_REMOTE_ENCODED_BYTES + 1]).is_err());
assert!(dimensions(4097, 1).is_err());
assert!(dimensions(4096, 4096).is_err());
assert!(dimensions(0, 1).is_err());
}
fn gif(frame_count: usize) -> Vec<u8> {
let mut bytes = Vec::new();
{
let mut encoder = image::codecs::gif::GifEncoder::new(&mut bytes);
for i in 0..frame_count {
let buffer = image::RgbaImage::from_pixel(2, 2, image::Rgba([i as u8, 0, 0, 255]));
encoder
.encode_frame(image::Frame::from_parts(
buffer,
0,
0,
image::Delay::from_numer_denom_ms(50, 1),
))
.unwrap();
}
}
bytes
}
#[test]
fn retains_animated_gif_frames_and_delay() {
let decoded = decode(&gif(2)).unwrap();
assert_eq!(decoded.frames.len(), 2);
assert_eq!(decoded.frames[1].rgba[0], 1);
assert_eq!(decoded.frames[0].delay_ms, 50);
}
#[test]
fn bounds_gif_preview_dimensions_without_dropping_frames() {
let mut bytes = Vec::new();
{
let mut encoder = image::codecs::gif::GifEncoder::new(&mut bytes);
for _ in 0..2 {
encoder
.encode_frame(image::Frame::new(image::RgbaImage::new(400, 100)))
.unwrap();
}
}
let decoded = decode(&bytes).unwrap();
assert_eq!((decoded.width, decoded.height), (384, 96));
assert_eq!(decoded.frames.len(), 2);
assert_eq!(decoded.frames[0].rgba.len(), 384 * 96 * 4);
}
#[test]
fn clipboard_encoding_validates_raw_size() {
let image = arboard::ImageData {
width: 2,
height: 2,
bytes: std::borrow::Cow::Owned(vec![0; 3]),
};
assert!(encode_clipboard_png(image).is_err());
}
#[test]
fn rejects_excessive_animation_frames() {
assert!(decode(&gif(MAX_FRAMES + 1)).is_err());
}
}

470
src/ui/chat_media.rs Normal file
View file

@ -0,0 +1,470 @@
//! Native chat image presentation. Network/decode work runs away from the event loop.
use super::{chat_images, slint::MainWindow};
use slint::{ComponentHandle, Model, SharedPixelBuffer};
use std::{cell::RefCell, collections::HashMap, rc::Rc, sync::mpsc, time::Instant};
use vnox_client::net::NetCommand;
struct Animation {
frames: Vec<(slint::Image, u32)>,
ratio: f32,
started: Instant,
bytes: usize,
}
impl Animation {
fn new(image: chat_images::DecodedImage) -> Self {
let bytes = image.frames.iter().map(|f| f.rgba.len()).sum();
Self {
frames: image
.frames
.into_iter()
.map(|f| {
(
slint::Image::from_rgba8(SharedPixelBuffer::clone_from_slice(
&f.rgba,
image.width,
image.height,
)),
f.delay_ms.max(20),
)
})
.collect(),
ratio: image.width as f32 / image.height as f32,
started: Instant::now(),
bytes,
}
}
fn frame(&self) -> slint::Image {
let duration: u128 = self.frames.iter().map(|f| u128::from(f.1)).sum();
let mut position = self.started.elapsed().as_millis() % duration.max(1);
for (image, delay) in &self.frames {
if position < u128::from(*delay) {
return image.clone();
}
position -= u128::from(*delay);
}
self.frames[0].0.clone()
}
}
struct Entry {
image: Option<Animation>,
error: String,
started: Instant,
}
struct Ready {
key: String,
result: Result<chat_images::DecodedImage, String>,
clipboard: Option<Vec<u8>>,
}
struct Pending {
bytes: Vec<u8>,
image: Animation,
channel: String,
generation: u64,
request: Option<String>,
started: Instant,
}
struct Media {
cache: HashMap<String, Entry>,
tx: mpsc::Sender<Ready>,
rx: mpsc::Receiver<Ready>,
pending: Option<Pending>,
clipboard_key: Option<String>,
generation: u64,
workers: usize,
}
impl Default for Media {
fn default() -> Self {
let (tx, rx) = mpsc::channel();
Self {
cache: HashMap::new(),
tx,
rx,
pending: None,
clipboard_key: None,
generation: 0,
workers: 0,
}
}
}
thread_local! { static MEDIA: RefCell<Media> = RefCell::new(Media::default()); }
pub fn wire(window: &MainWindow, state: &Rc<RefCell<crate::AppState>>) {
let weak = window.as_weak();
let paste_state = state.clone();
window.on_paste_image(move || {
let Some(win)=weak.upgrade() else { return false };
let s=paste_state.borrow();
// A failed image lookup must leave normal text paste to TextInput.
let Ok(clipboard)=chat_images::clipboard_image() else { return false };
if MEDIA.with(|m| {let m=m.borrow();m.workers+m.cache.iter().filter(|(key,entry)|key.starts_with("attachment:") && entry.error=="Loading image…").count()>=3 || m.pending.as_ref().is_some_and(|p|p.request.is_some())}) {win.set_image_status("Wait for the current image operation to finish.".into());return true;}
if s.ui.active_dm_id.is_some() || s.ui.active_channel.is_none() { win.set_image_status("Image attachments are available in channels. You can send an HTTPS image link here.".into()); return true; }
let channel=s.ui.active_channel.clone().unwrap_or_default(); let generation=s.connection_generation;
MEDIA.with(|m| { let mut m=m.borrow_mut(); if m.pending.as_ref().is_some_and(|p|p.request.is_some()) {return} let tx=m.tx.clone(); m.workers+=1;let clipboard_key=format!("clipboard:{generation}:{channel}:{}",uuid::Uuid::new_v4());m.clipboard_key=Some(clipboard_key.clone());
tokio::task::spawn_blocking(move || { let result=chat_images::encode_clipboard_png(clipboard).and_then(|bytes|chat_images::decode(&bytes).map(|image|(bytes,image))); match result {Ok((bytes,image))=>{let _=tx.send(Ready {key:clipboard_key,result:Ok(image),clipboard:Some(bytes)});},Err(error)=>{let _=tx.send(Ready {key:clipboard_key,result:Err(error.to_string()),clipboard:Some(Vec::new())});}} });
});
win.set_image_status("Preparing image…".into()); true
});
let weak = window.as_weak();
window.on_cancel_image(move || {
let cancelled = MEDIA.with(|m| {
let mut m = m.borrow_mut();
if m.pending.as_ref().is_some_and(|p| p.request.is_some()) {
return false;
}
m.pending = None;
m.clipboard_key = None;
true
});
if !cancelled {
return;
}
if let Some(w) = weak.upgrade() {
w.set_has_pending_image(false);
w.set_image_status("".into());
}
});
let state = state.clone();
let weak = window.as_weak();
window.on_send_image(move || {
let s = state.borrow();
let net = s.net.clone();
MEDIA.with(|m| {
let mut m = m.borrow_mut();
let Some(p) = m.pending.as_mut() else { return };
if p.request.is_some() {
return;
}
if p.generation != s.connection_generation
|| s.ui.active_dm_id.is_some()
|| s.ui.active_channel.as_deref() != Some(&p.channel)
|| !matches!(s.ui.conn, super::state::ConnState::Connected { .. })
{
if let Some(w) = weak.upgrade() {
w.set_image_status(
"Select the original channel and connect before sending this image.".into(),
);
}
return;
}
let request_id = uuid::Uuid::new_v4().to_string();
p.request = Some(request_id.clone());
p.started = Instant::now();
let channel_id = p.channel.clone();
let data = p.bytes.clone();
tokio::spawn(async move {
net.send(NetCommand::AttachmentUpload {
request_id,
channel_id,
data,
})
.await;
});
if let Some(w) = weak.upgrade() {
w.set_image_uploading(true);
w.set_image_status("Sending image…".into());
}
});
});
}
pub fn receive(result: vnox_client::net::wire::AttachmentResult) {
MEDIA.with(|m| {
let mut m = m.borrow_mut();
if let Some(p) = m.pending.as_mut()
&& p.request.as_deref() == Some(&result.request_id)
{
if result.error.is_empty() {
m.pending = None;
} else {
p.request = None;
}
// Display delivery state on the next UI tick.
let _ = m.tx.send(Ready {
key: "upload-status".into(),
result: Err(if result.error.is_empty() {
String::new()
} else {
result.error
}),
clipboard: None,
});
return;
}
let key = result.request_id;
let expected = format!(
"attachment:{}:{}:{}",
m.generation, result.channel_id, result.attachment_id
);
if key != expected
|| !m
.cache
.get(&key)
.is_some_and(|entry| entry.error == "Loading image…")
{
return;
}
if !result.error.is_empty() {
if let Some(e) = m.cache.get_mut(&key) {
e.error = result.error;
}
return;
}
if let Some(entry) = m.cache.get_mut(&key) {
entry.error = "Decoding image…".into();
}
let tx = m.tx.clone();
m.workers += 1;
tokio::task::spawn_blocking(move || {
let decoded = chat_images::decode(&result.data).map_err(|e| e.to_string());
let _ = tx.send(Ready {
key,
result: decoded,
clipboard: None,
});
});
});
}
pub fn tick(window: &MainWindow, state: &crate::AppState) {
MEDIA.with(|m| {
let mut m = m.borrow_mut();
if m.generation != state.connection_generation {
m.cache.clear();
m.pending = None;
m.clipboard_key = None;
m.generation = state.connection_generation;
window.set_has_pending_image(false);
window.set_image_uploading(false);
window.set_image_status("".into());
}
let visible_model = if window.get_show_forum() {window.get_forum_replies()} else {window.get_messages()};
let visible: Vec<String> = visible_model.iter()
.filter_map(|item| source_key(&item.media_source, state))
.collect();
m.cache.retain(|key, _| visible.contains(key));
while let Ok(ready) = m.rx.try_recv() {
if ready.key == "upload-status" {
window.set_image_uploading(false);
window.set_image_status(ready.result.err().unwrap_or_default().into());
window.set_has_pending_image(m.pending.is_some());
continue;
}
m.workers = m.workers.saturating_sub(1);
if let Some(bytes) = ready.clipboard {
let expected = format!(
"clipboard:{}:{}",
state.connection_generation,
state.ui.active_channel.as_deref().unwrap_or("")
);
if m.clipboard_key.as_deref() != Some(&ready.key)
|| !ready.key.starts_with(&format!("{expected}:"))
|| state.ui.active_dm_id.is_some()
{
continue;
}
m.clipboard_key = None;
match ready.result {
Ok(image) => {
let image = Animation::new(image);
window.set_pending_image(image.frame());
window.set_has_pending_image(true);
window.set_image_status(
"Image ready. Send it to this channel or cancel.".into(),
);
m.pending = Some(Pending {
bytes,
image,
channel: state.ui.active_channel.clone().unwrap_or_default(),
generation: state.connection_generation,
request: None,
started: Instant::now(),
});
}
Err(e) => window.set_image_status(format!("Cannot paste image: {e}").into()),
}
continue;
}
if !m.cache.contains_key(&ready.key) {
continue;
}
match ready.result {
Ok(image) => {
let image = Animation::new(image);
let total: usize = m
.cache
.values()
.filter_map(|e| e.image.as_ref())
.map(|a| a.bytes)
.sum();
if total + image.bytes > 64 * 1024 * 1024 {
m.cache.insert(
ready.key,
Entry {
image: None,
error:
"Preview cache is full. Open another channel to release images."
.into(),
started: Instant::now(),
},
);
continue;
}
m.cache.insert(
ready.key,
Entry {
image: Some(image),
error: String::new(),
started: Instant::now(),
},
);
}
Err(e) => {
m.cache.insert(
ready.key,
Entry {
image: None,
error: format!("Image unavailable: {e}"),
started: Instant::now(),
},
);
}
}
}
if let Some(p) = m.pending.as_mut() {
if p.request.is_some() && p.started.elapsed().as_secs() > 35 {
p.request = None;
window.set_image_uploading(false);
window.set_image_status(
"Image delivery could not be confirmed. Check the channel before retrying."
.into(),
);
}
window.set_pending_image(p.image.frame());
}
for entry in m.cache.values_mut() {
if entry.image.is_none()
&& entry.error == "Loading image…"
&& entry.started.elapsed().as_secs() > 35
{
entry.error = "Image request timed out".into();
}
}
let pending_fetches = m
.cache
.iter()
.filter(|(k, e)| {
k.starts_with("attachment:") && e.image.is_none() && e.error == "Loading image…"
})
.count();
let model = if window.get_show_forum() {window.get_forum_replies()} else {window.get_messages()};
let mut slots = 3usize.saturating_sub(m.workers + pending_fetches);
for row in 0..model.row_count() {
let Some(mut item) = model.row_data(row) else {
continue;
};
let previous = item.clone();
let body = item.media_source.to_string();
let source = body.as_str();
let attachment = if window.get_show_forum() { None } else { source
.strip_prefix("vnox-attachment:")
.filter(|id| uuid::Uuid::parse_str(id).is_ok()) };
let remote = chat_images::image_url(source);
let key = if let Some(id) = attachment {
format!(
"attachment:{}:{}:{}",
state.connection_generation,
state.ui.active_channel.as_deref().unwrap_or(""),
id
)
} else if let Some(url) = &remote {
format!("url:{url}")
} else {
continue;
};
if !m.cache.contains_key(&key) && slots > 0 && m.cache.len() < 24 {
slots -= 1;
m.cache.insert(
key.clone(),
Entry {
image: None,
error: "Loading image…".into(),
started: Instant::now(),
},
);
if let Some(attachment_id) = attachment {
let net = state.net.clone();
let channel_id = state.ui.active_channel.clone().unwrap_or_default();
let attachment_id = attachment_id.to_string();
let request_id = key.clone();
tokio::spawn(async move {
net.send(NetCommand::AttachmentFetch {
request_id,
channel_id,
attachment_id,
})
.await;
});
} else if let Some(url) = remote {
m.workers += 1;
let tx = m.tx.clone();
let request = key.clone();
tokio::spawn(async move {
let result = async {
let bytes = chat_images::fetch(&url).await?;
tokio::task::spawn_blocking(move || chat_images::decode(&bytes)).await?
}
.await
.map_err(|e: anyhow::Error| e.to_string());
let _ = tx.send(Ready {
key: request,
result,
clipboard: None,
});
});
}
}
item.media_ready = false;
item.media_image = Default::default();
item.media_status = "Image queue is full".into();
if let Some(entry) = m.cache.get(&key) {
if let Some(image) = &entry.image {
item.media_image = image.frame();
item.media_ready = true;
item.media_ratio = image.ratio;
item.media_status = "".into();
} else {
item.media_status = entry.error.as_str().into();
}
}
if attachment.is_some() {
item.content = "".into();
}
if item.media_ready != previous.media_ready
|| item.media_image != previous.media_image
|| item.media_status != previous.media_status
|| item.media_ratio != previous.media_ratio
|| item.content != previous.content
{
model.set_row_data(row, item);
}
}
});
}
fn source_key(source: &str, state: &crate::AppState) -> Option<String> {
if super::forum::visible(&state.ui) && source.starts_with("vnox-attachment:") { return None; }
if let Some(id) = source
.strip_prefix("vnox-attachment:")
.filter(|id| uuid::Uuid::parse_str(id).is_ok())
{
Some(format!(
"attachment:{}:{}:{}",
state.connection_generation,
state.ui.active_channel.as_deref().unwrap_or(""),
id
))
} else {
chat_images::image_url(source).map(|url| format!("url:{url}"))
}
}

187
src/ui/connection.rs Normal file
View file

@ -0,0 +1,187 @@
//! Successful server preference and account-gated restoration. Contains no credentials.
use super::state::ConnState;
use crate::{AppState, net::NetCommand};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(default)]
pub struct Preferences {
last_server: Option<String>,
auto_reconnect: bool,
manually_disconnected: bool,
#[serde(skip)]
pending: Option<String>,
#[serde(skip)]
pub authentication_required: bool,
}
impl Default for Preferences {
fn default() -> Self {
Self {
last_server: None,
auto_reconnect: true,
manually_disconnected: false,
pending: None,
authentication_required: false,
}
}
}
impl Preferences {
fn restore_target(&self, authenticated: bool) -> Option<String> {
(authenticated && self.auto_reconnect && !self.manually_disconnected)
.then(|| self.last_server.clone())
.flatten()
}
fn successful(&mut self) {
if let Some(address) = self.pending.take() {
self.last_server = Some(address);
self.manually_disconnected = false;
}
}
}
fn path() -> std::path::PathBuf {
dirs::config_dir()
.unwrap_or_else(|| ".".into())
.join("vnox/connection.json")
}
pub fn load(ui: &mut super::state::UiState) {
ui.connection = std::fs::read(path())
.ok()
.and_then(|bytes| serde_json::from_slice::<Preferences>(&bytes).ok())
.unwrap_or_default();
// Never let an edited/corrupted file bypass the same target parser as transport.
ui.connection.last_server = ui
.connection
.last_server
.as_deref()
.and_then(|address| crate::net::trust::parse_address(address).ok())
.map(|a| a.key);
ui.auto_reconnect = ui.connection.auto_reconnect;
if let Some(address) = &ui.connection.last_server {
ui.connect_input = address.clone();
}
}
fn save(ui: &super::state::UiState) {
let result = (|| -> anyhow::Result<()> {
let path = path();
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let mut prefs = ui.connection.clone();
prefs.auto_reconnect = ui.auto_reconnect;
let temporary = path.with_extension("json.tmp");
std::fs::write(&temporary, serde_json::to_vec_pretty(&prefs)?)?;
std::fs::rename(temporary, path)?;
Ok(())
})();
if let Err(error) = result {
tracing::warn!(%error, "could not save connection preferences");
}
}
pub fn set_auto_reconnect(state: &mut AppState, value: bool) {
state.ui.auto_reconnect = value;
state.ui.connection.auto_reconnect = value;
save(&state.ui);
}
pub fn disconnect(state: &mut AppState) {
state.ui.connection.manually_disconnected = true;
state.ui.connection.pending = None;
save(&state.ui);
}
pub fn connected(state: &mut AppState) {
state.ui.connection.successful();
save(&state.ui);
}
pub fn restore(state: &mut AppState, authenticated: bool) {
if !matches!(state.ui.conn, ConnState::Disconnected) {
return;
}
if let Some(address) = state.ui.connection.restore_target(authenticated) {
connect(state, address);
}
}
pub fn connect(state: &mut AppState, address: String) {
let address = match crate::net::trust::parse_address(&address) {
Ok(address) => address.key,
Err(error) => {
state.ui.status_msg = Some(error.to_string().into());
return;
}
};
state.ui.connection.pending = Some(address.clone());
state.ui.connection.authentication_required = false;
state.ui.conn = ConnState::Connecting;
state.ui.connect_input = address.clone();
state.ui.status_msg = Some("Connecting…".into());
let auto_reconnect = state.ui.auto_reconnect;
let net = state.net.clone();
tokio::spawn(async move {
net.send(NetCommand::Connect {
address,
auto_reconnect,
})
.await;
});
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn restoration_requires_account_and_auto_reconnect_and_no_manual_leave() {
let mut p = Preferences {
last_server: Some("example.org:7600".into()),
..Default::default()
};
assert!(p.restore_target(false).is_none());
assert_eq!(p.restore_target(true).as_deref(), Some("example.org:7600"));
p.auto_reconnect = false;
assert!(p.restore_target(true).is_none());
p.auto_reconnect = true;
p.manually_disconnected = true;
assert!(p.restore_target(true).is_none());
}
#[test]
fn only_successful_address_survives_serialization() {
let mut p = Preferences {
last_server: Some("old.example:7600".into()),
pending: Some("new.example:7600".into()),
..Default::default()
};
let loaded: Preferences = serde_json::from_slice(&serde_json::to_vec(&p).unwrap()).unwrap();
assert_eq!(loaded.last_server.as_deref(), Some("old.example:7600"));
assert!(loaded.pending.is_none());
p.successful();
let loaded: Preferences = serde_json::from_slice(&serde_json::to_vec(&p).unwrap()).unwrap();
assert_eq!(loaded.last_server.as_deref(), Some("new.example:7600"));
}
#[test]
fn successful_target_uses_transport_normalization() {
assert_eq!(
crate::net::trust::parse_address("lnexs://Example.ORG")
.unwrap()
.key,
"example.org:7600"
);
assert_eq!(
crate::net::trust::parse_address("[::1]").unwrap().key,
"[::1]:7600"
);
assert!(crate::net::trust::parse_address("example.org:invalid").is_err());
}
#[test]
fn manual_leave_survives_restart_and_failed_attempt() {
let mut p = Preferences {
last_server: Some("example.org:7600".into()),
manually_disconnected: true,
pending: Some("failed.example:7600".into()),
..Default::default()
};
let loaded: Preferences = serde_json::from_slice(&serde_json::to_vec(&p).unwrap()).unwrap();
assert!(loaded.restore_target(true).is_none());
p.successful();
assert_eq!(
p.restore_target(true).as_deref(),
Some("failed.example:7600")
);
}
}

View file

@ -2,6 +2,47 @@
use vnox_client::audio::devices::{self, filter};
use super::state::UiState;
use std::sync::mpsc::{self, Receiver, TryRecvError};
use vnox_client::audio::DeviceLists;
/// One in-flight enumeration. Only owned device descriptions cross the thread boundary.
#[derive(Default)]
pub struct DeviceRefresh {
pending: Option<Receiver<anyhow::Result<DeviceLists>>>,
}
impl DeviceRefresh {
/// Starts an enumeration unless the previous request is still pending.
pub fn request(&mut self) {
self.start(devices::enumerate);
}
fn start(&mut self, enumerate: impl FnOnce() -> anyhow::Result<DeviceLists> + Send + 'static) {
if self.pending.is_some() {
return;
}
let (sender, receiver) = mpsc::channel();
match std::thread::Builder::new()
.name("audio-device-refresh".into())
.spawn(move || {
let _ = sender.send(enumerate());
}) {
Ok(_) => self.pending = Some(receiver),
Err(error) => tracing::warn!(%error, "cannot start audio device refresh"),
}
}
/// Polls without waiting. Errors keep the last usable list and allow another request.
pub fn take_ready(&mut self) -> Option<anyhow::Result<DeviceLists>> {
let result = match self.pending.as_ref()?.try_recv() {
Ok(result) => result,
Err(TryRecvError::Empty) => return None,
Err(TryRecvError::Disconnected) => Err(anyhow::anyhow!("audio device worker stopped")),
};
self.pending = None;
Some(result)
}
}
/// Recomputes the picker positions from the persisted ids and the last enumeration.
pub fn sync_indexes(ui: &mut UiState) {
@ -9,12 +50,9 @@ pub fn sync_indexes(ui: &mut UiState) {
ui.output_device = filter::index_for_id(&ui.device_lists.output, &ui.output_device_id);
}
/// Enumerates devices again (hardware may have changed) and keeps the saved choices.
pub fn refresh(ui: &mut UiState) {
match devices::enumerate() {
Ok(lists) => ui.device_lists = lists,
Err(error) => tracing::warn!(%error, "cannot enumerate audio devices"),
}
/// Applies a finished enumeration using the current selection, not a worker snapshot.
pub fn apply_refresh(ui: &mut UiState, lists: DeviceLists) {
ui.device_lists = lists;
sync_indexes(ui);
}
@ -66,4 +104,53 @@ mod tests {
sync_indexes(&mut ui);
assert_eq!(ui.mic_device, 0);
}
#[test]
fn slow_refresh_is_nonblocking_and_coalesces_requests() {
let mut refresh = DeviceRefresh::default();
let (release, wait) = std::sync::mpsc::channel();
refresh.start(move || {
wait.recv().unwrap();
Ok(state().device_lists)
});
assert!(refresh.take_ready().is_none());
refresh.start(|| panic!("a second enumeration must not start"));
release.send(()).unwrap();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
let lists = loop {
if let Some(result) = refresh.take_ready() {
break result.unwrap();
}
assert!(std::time::Instant::now() < deadline);
std::thread::yield_now();
};
assert_eq!(lists.input[1].id, "b");
assert!(refresh.pending.is_none());
}
#[test]
fn failed_refresh_can_be_retried() {
let mut refresh = DeviceRefresh::default();
let (sender, receiver) = std::sync::mpsc::channel();
sender.send(Err(anyhow::anyhow!("unavailable"))).unwrap();
refresh.pending = Some(receiver);
assert!(refresh.take_ready().unwrap().is_err());
assert!(refresh.pending.is_none());
refresh.start(|| Ok(DeviceLists::default()));
assert!(refresh.pending.is_some());
}
#[test]
fn applying_refresh_uses_the_latest_device_selection() {
let mut ui = state();
select(&mut ui, 1, 1);
// The person changes the picker while enumeration is still running.
select(&mut ui, 2, 0);
let mut lists = state().device_lists;
lists.input.reverse();
apply_refresh(&mut ui, lists);
assert_eq!(ui.mic_device_id, "b");
assert_eq!(ui.mic_device, 1);
assert_eq!(ui.output_device, 0);
}
}

126
src/ui/forum/mod.rs Normal file
View file

@ -0,0 +1,126 @@
//! Separate forum threads; all data and mutation acknowledgements come from Gateway.
mod state;
pub use state::ForumState;
use crate::{AppState, net::{NetCommand, NetEvent, NetHandle, wire}};
use super::{slint::{MainWindow, ForumTopicItem, MessageItem}, state::{ConnState, UiState}};
use slint::{Model, ModelRc, SharedString, VecModel};
use std::{cell::RefCell, rc::Rc};
fn session(ui: &UiState) -> Option<String> {
if ui.connection.authentication_required { return None; }
match &ui.conn { ConnState::Connected { session_id, .. } => Some(session_id.clone()), _ => None }
}
fn send(ui: &UiState, net: &NetHandle, command: NetCommand) {
let Some(session_id) = session(ui) else { return; };
let net = net.clone(); tokio::spawn(async move { net.send(NetCommand::ForSession { session_id, command: Box::new(command) }).await; });
}
fn request(ui: &mut UiState, net: &NetHandle, operation: wire::ForumOperation, offset: u32) {
if session(ui).is_none() || !visible(ui) { return; }
if let Some(request) = ui.forum.request(operation, offset) { send(ui, net, NetCommand::ForumRequest(request)); }
}
pub fn visible(ui: &UiState) -> bool {
!ui.browsing_dms && !ui.showing_voice && ui.active_channel.as_ref().is_some_and(|id|
ui.channels.iter().any(|channel| &channel.id == id && channel.kind == "forum" && channel.guild_id == ui.active_guild_id))
}
/// Selection never touches voice membership, credentials, audio devices or capture.
pub fn select(state: &mut AppState, id: &str) {
let channel_exists = state.ui.channels.iter().any(|channel| channel.id == id && channel.kind == "forum" && channel.guild_id == state.ui.active_guild_id);
if !channel_exists || session(&state.ui).is_none() { return; }
state.ui.select_text_channel(id.to_owned());
if !state.ui.forum.supported {
state.ui.forum.channel_id = Some(id.to_owned());
state.ui.forum.error = super::i18n::text("This server does not support forums yet."); return;
}
if state.ui.forum.channel_id.as_deref() == Some(id) && state.ui.forum.pending() { return; }
state.ui.forum.select(id);
send(&state.ui, &state.net, NetCommand::JoinChannel { channel_id: id.to_owned() });
}
pub fn tick(ui: &mut UiState) { ui.forum.timeout(); }
/// Observe lifecycle and a forum's view acknowledgement before issuing LIST/OPEN.
pub fn observe(ui: &mut UiState, net: &NetHandle, event: &NetEvent) {
match event {
NetEvent::Connected { forums, restored, .. } => {
if !restored { ui.forum = ForumState::default(); }
ui.forum.supported = *forums;
if *restored && let Some(id) = ui.forum.channel_id.clone() { ui.forum.select(&id); }
}
NetEvent::Disconnected { will_retry, .. } => {
if !will_retry { ui.forum = ForumState::default(); }
else { ui.forum.suspend(); }
}
NetEvent::ChannelState { channel_id, kind, members, .. }
if kind == "forum" && !members.is_empty() && ui.forum.channel_id.as_deref() == Some(channel_id) && ui.forum.waiting_join.is_some() => {
ui.forum.waiting_join = None; ui.forum.joined = true;
let operation = if ui.forum.topic_id.is_some() { wire::ForumOperation::Open } else { wire::ForumOperation::List };
request(ui, net, operation, 0);
}
NetEvent::ChannelDeleted { channel_id } if ui.forum.channel_id.as_deref() == Some(channel_id) => {
ui.forum = ForumState::with_support(ui.forum.supported);
}
_ => (),
}
}
pub fn result(ui: &mut UiState, result: wire::ForumResult) {
ui.forum.result(result); remember_current_authors(ui);
}
pub fn changed(ui: &mut UiState, event: wire::ForumChanged) {
ui.forum.changed(event); remember_current_authors(ui);
}
fn remember_current_authors(ui: &mut UiState) {
let authors: Vec<_> = ui.forum.topics.iter().filter_map(|topic|topic.author.clone()).chain(ui.forum.posts.iter().filter_map(|post|post.author.clone())).collect();
remember_authors(ui, authors.iter());
}
fn remember_authors<'a>(ui: &mut UiState, authors: impl Iterator<Item=&'a wire::MemberInfo>) {
for author in authors {
ui.user_names.entry(author.user_id.clone()).or_insert_with(|| author.nickname.clone());
ui.member_profiles.entry(author.user_id.clone()).or_insert_with(|| (author.account_id.clone(), author.avatar_url.clone()));
}
}
fn author(ui: &UiState, snapshot: Option<&wire::MemberInfo>) -> String {
snapshot.map(|author|ui.user_names.get(&author.user_id).cloned().unwrap_or_else(||author.nickname.clone())).unwrap_or_default()
}
pub fn sync(window: &MainWindow, ui: &UiState, own_user_id: &str) {
let show = visible(ui); window.set_show_forum(show);
if !show { return; }
let forum = &ui.forum;
window.set_forum_channel_name(ui.channels.iter().find(|c|Some(&c.id)==ui.active_channel.as_ref()).map_or("", |c|c.name.as_str()).into());
window.set_forum_supported(forum.supported); window.set_forum_loading(forum.loading()); window.set_forum_busy(forum.busy());
window.set_forum_creating(forum.creating); window.set_forum_topic_open(forum.topic_id.is_some());
window.set_forum_title_draft(forum.title_draft.as_str().into()); window.set_forum_body_draft(forum.body_draft.as_str().into()); window.set_forum_reply_draft(forum.reply_draft.as_str().into());
window.set_forum_error(super::i18n::text(&forum.error).into());
window.set_forum_more_topics(forum.topics_offset.is_some()); window.set_forum_more_replies(forum.posts_offset.is_some());
window.set_forum_topic_title(forum.topics.iter().find(|t|Some(&t.topic_id)==forum.topic_id.as_ref()).map_or("", |t|t.title.as_str()).into());
let now = chrono::Local::now();
let topics: Vec<ForumTopicItem> = forum.topics.iter().map(|topic| ForumTopicItem { id:topic.topic_id.as_str().into(), title:topic.title.as_str().into(), author:author(ui,topic.author.as_ref()).into(), updated:super::timestamps::format_at(topic.updated_at,&now).into(), excerpt:SharedString::default(), replies:topic.reply_count.min(i32::MAX as u32) as i32 }).collect();
let posts: Vec<MessageItem> = forum.posts.iter().filter_map(|post|post.message.as_ref().map(|message| {
let avatar=ui.avatar_path_for(&message.sender_id,own_user_id).as_deref().map(super::avatar::central::image).unwrap_or_default();
let name=author(ui,post.author.as_ref());
MessageItem { message_id:message.message_id.as_str().into(), sender_id:message.sender_id.as_str().into(), sender_name:name.as_str().into(), timestamp:super::timestamps::format_at(message.timestamp,&now).into(), content:message.content.as_str().into(),media_source:message.content.as_str().into(),show_author:true,is_own:message.sender_id==own_user_id,avatar_text:super::bridge::initials(&name),has_avatar:avatar.size().width>0,avatar,media_ratio:1.0,..Default::default() }
})).collect();
if !window.get_forum_topics().iter().eq(topics.iter().cloned()) { window.set_forum_topics(ModelRc::new(VecModel::from(topics))); }
let current=window.get_forum_replies();
if current.row_count()!=posts.len() || !current.iter().zip(posts.iter()).all(|(a,b)|super::bridge::same_message(&a,b)) {window.set_forum_replies(ModelRc::new(VecModel::from(posts)));}
}
fn perform(state: &Rc<RefCell<AppState>>, operation: wire::ForumOperation, offset: u32) {
let mut s = state.borrow_mut(); let net = s.net.clone(); request(&mut s.ui,&net,operation,offset);
}
pub fn wire(window: &MainWindow, state: &Rc<RefCell<AppState>>) {
{ let state=state.clone(); window.on_forum_create(move || { let mut s=state.borrow_mut(); if visible(&s.ui) { s.ui.forum.create(); } }); }
{ let state=state.clone(); window.on_forum_cancel_create(move || { let mut s=state.borrow_mut(); if !s.ui.forum.pending() {s.ui.forum.creating=false;} }); }
{ let state=state.clone(); window.on_forum_back(move || { let mut s=state.borrow_mut(); if !s.ui.forum.pending() {s.ui.forum.creating=false;s.ui.forum.topic_id=None;s.ui.forum.error.clear();} }); }
{ let state=state.clone(); window.on_forum_refresh(move || {
let mut s=state.borrow_mut(); if !visible(&s.ui) || s.ui.forum.pending() { return; }
if !s.ui.forum.joined { if let Some(id)=s.ui.forum.channel_id.clone() {select(&mut s,&id);} return; }
let operation=if s.ui.forum.topic_id.is_some() {wire::ForumOperation::Open} else {wire::ForumOperation::List}; let net=s.net.clone();request(&mut s.ui,&net,operation,0);
}); }
{ let state=state.clone(); window.on_forum_open_topic(move |id| { let mut s=state.borrow_mut(); if !visible(&s.ui) {return;} if let Some(request)=s.ui.forum.open(id.as_str()) {send(&s.ui,&s.net,NetCommand::ForumRequest(request));} }); }
{ let state=state.clone(); window.on_forum_submit_topic(move ||perform(&state,wire::ForumOperation::Create,0)); }
{ let state=state.clone(); window.on_forum_submit_reply(move ||perform(&state,wire::ForumOperation::Reply,0)); }
{ let state=state.clone(); window.on_forum_load_more_topics(move || {let offset=state.borrow().ui.forum.topics_offset;if let Some(offset)=offset {perform(&state,wire::ForumOperation::List,offset);} }); }
{ let state=state.clone(); window.on_forum_load_more_replies(move || {let offset=state.borrow().ui.forum.posts_offset;if let Some(offset)=offset {perform(&state,wire::ForumOperation::Open,offset);} }); }
{ let state=state.clone(); window.on_forum_title_edited(move |value| state.borrow_mut().ui.forum.edit_title(value.to_string())); }
{ let state=state.clone(); window.on_forum_body_edited(move |value| state.borrow_mut().ui.forum.edit_body(value.to_string())); }
{ let state=state.clone(); window.on_forum_reply_edited(move |value| state.borrow_mut().ui.forum.edit_reply(value.to_string())); }
}

213
src/ui/forum/state.rs Normal file
View file

@ -0,0 +1,213 @@
use crate::net::wire;
use std::time::{Duration, Instant};
const REQUEST_TIMEOUT: Duration = Duration::from_secs(20);
struct Pending { request: wire::ForumRequest, started: Instant }
/// View state belongs to one authenticated node session; mutations stay drafts until ACK.
#[derive(Default)]
pub struct ForumState {
pub supported: bool,
pub channel_id: Option<String>,
pub joined: bool,
pub topics: Vec<wire::ForumTopic>,
pub posts: Vec<wire::ForumPost>,
pub topic_id: Option<String>,
pub creating: bool,
pub title_draft: String,
pub body_draft: String,
pub reply_draft: String,
pub error: String,
pub topics_offset: Option<u32>,
pub posts_offset: Option<u32>,
pub waiting_join: Option<Instant>,
topic_draft_id: Option<String>,
first_message_id: Option<String>,
reply_message_id: Option<String>,
pending: Option<Pending>,
}
impl ForumState {
pub fn suspend(&mut self) { self.supported=false; self.joined=false; self.pending=None; self.waiting_join=None; }
pub fn with_support(supported: bool) -> Self { Self { supported, ..Default::default() } }
pub fn edit_title(&mut self, value: String) { if !self.busy() && self.title_draft != value { self.title_draft=value; self.topic_draft_id=None; self.first_message_id=None; } }
pub fn edit_body(&mut self, value: String) { if !self.busy() && self.body_draft != value { self.body_draft=value; self.topic_draft_id=None; self.first_message_id=None; } }
pub fn edit_reply(&mut self, value: String) { if !self.busy() && self.reply_draft != value { self.reply_draft=value; self.reply_message_id=None; } }
pub fn loading(&self) -> bool {
self.waiting_join.is_some() || self.pending.as_ref().is_some_and(|p| !crate::net::forum::is_mutation(&p.request))
}
pub fn busy(&self) -> bool { self.pending.as_ref().is_some_and(|p| crate::net::forum::is_mutation(&p.request)) }
pub fn pending(&self) -> bool { self.pending.is_some() || self.waiting_join.is_some() }
pub fn select(&mut self, channel: &str) {
if self.channel_id.as_deref() != Some(channel) { *self = Self { supported: self.supported, ..Default::default() }; }
self.channel_id = Some(channel.to_owned()); self.joined = false; self.waiting_join = Some(Instant::now()); self.error.clear();
}
pub fn create(&mut self) {
if self.pending() || !self.supported { return; }
self.creating = true; self.topic_id = None; self.posts.clear(); self.error.clear();
}
pub fn request(&mut self, operation: wire::ForumOperation, offset: u32) -> Option<wire::ForumRequest> {
if !self.supported || !self.joined || self.pending() { return None; }
let channel_id = self.channel_id.clone()?;
let mut request = wire::ForumRequest { request_id: uuid::Uuid::new_v4().to_string(), channel_id, operation: operation as i32, offset, limit: if operation == wire::ForumOperation::List { 20 } else { 50 }, ..Default::default() };
match operation {
wire::ForumOperation::List => (),
wire::ForumOperation::Open => { request.topic_id = self.topic_id.clone()?; if offset == 0 { self.posts.clear(); self.posts_offset = None; } },
wire::ForumOperation::Create => {
let title = self.title_draft.trim(); let content = self.body_draft.trim();
if !valid_title(title) || !valid_body(content) { self.error = "Enter a title (1–160 characters) and a first message (1–16000 characters).".into(); return None; }
request.topic_id = self.topic_draft_id.get_or_insert_with(|| uuid::Uuid::new_v4().to_string()).clone();
request.message_id = self.first_message_id.get_or_insert_with(|| uuid::Uuid::new_v4().to_string()).clone();
request.title = title.to_owned(); request.content = content.to_owned();
}
wire::ForumOperation::Reply => {
if !valid_body(self.reply_draft.trim()) { self.error = "Enter a reply (1–16000 characters).".into(); return None; }
request.topic_id = self.topic_id.clone()?;
request.message_id = self.reply_message_id.get_or_insert_with(|| uuid::Uuid::new_v4().to_string()).clone();
request.content = self.reply_draft.trim().to_owned();
}
_ => return None,
}
self.error.clear(); self.pending = Some(Pending { request: request.clone(), started: Instant::now() }); Some(request)
}
pub fn open(&mut self, id: &str) -> Option<wire::ForumRequest> {
if self.pending() || !self.topics.iter().any(|topic| topic.topic_id == id) { return None; }
self.topic_id = Some(id.to_owned()); self.creating = false; self.posts.clear(); self.reply_draft.clear(); self.reply_message_id = None; self.posts_offset = None;
self.request(wire::ForumOperation::Open, 0)
}
pub fn timeout(&mut self) {
if self.waiting_join.is_some_and(|at| at.elapsed() >= REQUEST_TIMEOUT)
|| self.pending.as_ref().is_some_and(|p| p.started.elapsed() >= REQUEST_TIMEOUT) {
self.waiting_join = None; self.pending = None;
self.error = "The forum request timed out. Your draft has been kept; refresh or retry.".into();
}
}
pub fn result(&mut self, result: wire::ForumResult) {
let Some(pending) = self.pending.as_ref() else { return; };
let request = &pending.request;
if result.request_id != request.request_id || result.operation != request.operation || result.channel_id != request.channel_id
|| (!request.topic_id.is_empty() && result.topic_id != request.topic_id) { return; }
let request = request.clone(); self.pending = None;
if result.error_code != 0 || !result.error.is_empty() {
self.error = result.error.chars().take(500).collect();
if self.error.is_empty() { self.error = "The server refused this forum request.".into(); }
return;
}
if result.topics.len() > 50 || result.posts.len() > 100
|| result.topics.iter().any(|t| t.channel_id != request.channel_id)
|| result.posts.iter().any(|p| p.topic_id != result.topic_id || p.message.as_ref().is_none_or(|m| m.channel_id != request.channel_id)) {
self.error = "The server returned an invalid forum response.".into(); return;
}
let operation = wire::ForumOperation::try_from(request.operation).ok();
if matches!(operation, Some(wire::ForumOperation::Create | wire::ForumOperation::Reply))
&& !result.posts.iter().any(|p| p.message.as_ref().is_some_and(|m| m.message_id == request.message_id)) {
self.error = "The server did not acknowledge this forum message.".into(); return;
}
self.error.clear();
match operation {
Some(wire::ForumOperation::List) => {
if request.offset == 0 { self.topics.clear(); }
let count = result.topics.len() as u32;
for topic in result.topics { self.upsert_topic(topic); }
self.topics_offset = next_offset(request.offset, count, result.has_more);
}
Some(wire::ForumOperation::Open) => {
let count = result.posts.len() as u32;
if result.has_more && let Some(last) = result.posts.iter().map(|p| p.ordinal).max() { self.posts.retain(|p| p.ordinal <= last); }
for topic in result.topics { self.upsert_topic(topic); }
for post in result.posts { self.upsert_post(post); }
self.posts_offset = next_offset(request.offset, count, result.has_more);
}
Some(wire::ForumOperation::Create) => {
self.creating = false; self.topic_id = Some(request.topic_id);
self.title_draft.clear(); self.body_draft.clear(); self.topic_draft_id = None; self.first_message_id = None;
self.posts.clear(); self.posts_offset = None;
for topic in result.topics { self.upsert_topic(topic); }
for post in result.posts { self.upsert_post(post); }
}
Some(wire::ForumOperation::Reply) => {
self.reply_draft.clear(); self.reply_message_id = None;
for topic in result.topics { self.upsert_topic(topic); }
// When a thread is only partially loaded, do not insert a later reply ahead
// of unseen posts: refresh/page through its chronological history instead.
if self.posts_offset.is_none() { for post in result.posts { self.upsert_post(post); } }
}
_ => (),
}
}
pub fn changed(&mut self, event: wire::ForumChanged) {
if self.channel_id.as_deref() != Some(event.channel_id.as_str()) || !self.supported { return; }
if let Some(topic) = event.topic && topic.channel_id == event.channel_id { self.upsert_topic(topic); }
if self.posts_offset.is_none() && let Some(post) = event.post
&& self.topic_id.as_deref() == Some(post.topic_id.as_str())
&& post.message.as_ref().is_some_and(|m| m.channel_id == event.channel_id) { self.upsert_post(post); }
}
fn upsert_topic(&mut self, topic: wire::ForumTopic) {
if let Some(current) = self.topics.iter_mut().find(|t| t.topic_id == topic.topic_id) {
if current.updated_at <= topic.updated_at { *current = topic; }
} else { self.topics.push(topic); }
self.topics.sort_by(|a,b| b.updated_at.cmp(&a.updated_at).then_with(|| a.topic_id.cmp(&b.topic_id)));
}
fn upsert_post(&mut self, post: wire::ForumPost) {
let Some(message) = &post.message else { return; };
if !self.posts.iter().any(|p| p.message.as_ref().is_some_and(|m| m.message_id == message.message_id)) { self.posts.push(post); }
self.posts.sort_by_key(|post| post.ordinal);
}
}
fn next_offset(offset: u32, count: u32, has_more: bool) -> Option<u32> { (has_more && count > 0 && offset.saturating_add(count) <= 100_000).then_some(offset.saturating_add(count)) }
fn bidi_or_control(c: char) -> bool { c.is_control() || matches!(c, '\u{061c}'|'\u{200e}'|'\u{200f}'|'\u{202a}'..='\u{202e}'|'\u{2066}'..='\u{2069}') }
fn valid_title(value: &str) -> bool { !value.is_empty() && value.chars().count() <= 160 && !value.chars().any(bidi_or_control) }
fn valid_body(value: &str) -> bool { !value.is_empty() && value.chars().count() <= 16000 && value.len() <= 64*1024 && !value.chars().any(|c| bidi_or_control(c) && c != '\n' && c != '\t') }
#[cfg(test)]
mod tests {
use super::*;
fn ready() -> ForumState { ForumState { supported: true, joined: true, channel_id: Some("forum".into()), ..Default::default() } }
fn topic(id: &str) -> wire::ForumTopic { wire::ForumTopic { topic_id:id.into(),channel_id:"forum".into(),title:"A real topic".into(),..Default::default() } }
fn post(id: &str, topic: &str, ordinal: u64) -> wire::ForumPost { wire::ForumPost { topic_id:topic.into(),ordinal,message:Some(wire::ChatMessage { message_id:id.into(),channel_id:"forum".into(),content:"A real reply".into(),timestamp:1000,..Default::default() }),..Default::default() } }
fn response(request: &wire::ForumRequest) -> wire::ForumResult { wire::ForumResult { request_id:request.request_id.clone(),operation:request.operation,channel_id:request.channel_id.clone(),topic_id:request.topic_id.clone(),..Default::default() } }
#[test]
fn old_server_or_unacknowledged_join_cannot_prepare_forum_packets() {
let mut state=ready();state.supported=false;assert!(state.request(wire::ForumOperation::List,0).is_none());
state.supported=true;state.joined=false;assert!(state.request(wire::ForumOperation::List,0).is_none());
}
#[test]
fn failed_create_keeps_draft_and_stable_mutation_ids_until_matching_ack() {
let mut state=ready();state.create();state.edit_title("Topic".into());state.edit_body("Opening post".into());
let first=state.request(wire::ForumOperation::Create,0).unwrap();assert!(state.topic_id.is_none());assert_eq!(state.title_draft,"Topic");
let mut denied=response(&first);denied.error_code=5;denied.error="Permission denied".into();state.result(denied);
assert_eq!(state.body_draft,"Opening post");assert!(!state.busy());
let retry=state.request(wire::ForumOperation::Create,0).unwrap();assert_ne!(first.request_id,retry.request_id);assert_eq!(first.topic_id,retry.topic_id);assert_eq!(first.message_id,retry.message_id);
let mut stale=response(&first);stale.topics=vec![topic(&first.topic_id)];stale.posts=vec![post(&first.message_id,&first.topic_id,1)];state.result(stale);assert!(state.busy());assert_eq!(state.title_draft,"Topic");
let mut accepted=response(&retry);accepted.topics=vec![topic(&retry.topic_id)];accepted.posts=vec![post(&retry.message_id,&retry.topic_id,1)];state.result(accepted);
assert_eq!(state.topic_id.as_deref(),Some(retry.topic_id.as_str()));assert_eq!(state.posts.len(),1);assert!(state.title_draft.is_empty());assert!(state.body_draft.is_empty());assert!(!state.creating);
}
#[test]
fn changing_failed_draft_allocates_new_object_ids_and_stale_node_results_are_ignored() {
let mut state=ready();state.edit_title("Topic".into());state.edit_body("First".into());let old=state.request(wire::ForumOperation::Create,0).unwrap();
let mut failed=response(&old);failed.error="Denied".into();state.result(failed);state.edit_body("Changed".into());let new=state.request(wire::ForumOperation::Create,0).unwrap();assert_ne!(old.topic_id,new.topic_id);assert_ne!(old.message_id,new.message_id);
state.select("different-forum");state.result(response(&new));assert!(state.topics.is_empty());assert!(state.posts.is_empty());assert_eq!(state.channel_id.as_deref(),Some("different-forum"));
}
#[test]
fn pagination_uses_actual_byte_bounded_page_size_and_posts_sort_by_ordinal() {
let mut state=ready();state.topics.push(topic("topic"));let request=state.open("topic").unwrap();assert_eq!(request.limit,50);
let mut result=response(&request);result.topics=vec![topic("topic")];result.posts=vec![post("two","topic",2),post("one","topic",1)];result.has_more=true;state.result(result);
assert_eq!(state.posts_offset,Some(2));assert_eq!(state.posts.iter().map(|p|p.ordinal).collect::<Vec<_>>(),vec![1,2]);
let request=state.request(wire::ForumOperation::Open,state.posts_offset.unwrap()).unwrap();assert_eq!(request.offset,2);
let mut last=response(&request);last.posts=vec![post("three","topic",3)];state.result(last);assert!(state.posts_offset.is_none());assert_eq!(state.posts.len(),3);
}
#[test]
fn changed_ack_and_page_overlap_deduplicate_even_with_equal_millisecond_timestamps() {
let mut state=ready();state.topics.push(topic("topic"));state.topic_id=Some("topic".into());state.posts.push(post("first","topic",1));state.edit_reply("Own reply".into());let request=state.request(wire::ForumOperation::Reply,0).unwrap();
state.changed(wire::ForumChanged {channel_id:"forum".into(),topic:Some(topic("topic")),post:Some(post("third","topic",3))});
let mut result=response(&request);result.topics=vec![topic("topic")];result.posts=vec![post(&request.message_id,"topic",2)];state.result(result);
state.changed(wire::ForumChanged {channel_id:"forum".into(),topic:Some(topic("topic")),post:Some(post(&request.message_id,"topic",2))});
assert_eq!(state.posts.iter().map(|p|p.ordinal).collect::<Vec<_>>(),vec![1,2,3]);assert!(state.reply_draft.is_empty());
}
#[test]
fn timeout_keeps_text_and_retry_ids_and_invalid_reply_ack_cannot_clear_input() {
let mut state=ready();state.topic_id=Some("topic".into());state.edit_reply("Keep this".into());let request=state.request(wire::ForumOperation::Reply,0).unwrap();
state.pending.as_mut().unwrap().started=Instant::now()-REQUEST_TIMEOUT;state.timeout();assert_eq!(state.reply_draft,"Keep this");assert!(!state.error.is_empty());
let retry=state.request(wire::ForumOperation::Reply,0).unwrap();assert_eq!(request.message_id,retry.message_id);state.result(response(&retry));assert_eq!(state.reply_draft,"Keep this");assert!(!state.error.is_empty());
}
}

View file

@ -1,6 +1,9 @@
pub mod account;
pub mod forum;
pub mod appearance;
pub mod avatar;
pub mod bridge;
pub mod connection;
pub mod devices;
pub mod emoji;
pub mod i18n;
@ -9,6 +12,13 @@ pub mod preferences;
pub mod slint;
pub mod sounds;
pub mod state;
pub mod timestamps;
pub mod update;
pub mod webhooks;
pub mod channel_admin;
pub mod chat_images;
pub mod chat_media;
pub mod server_settings;

View file

@ -23,6 +23,7 @@ struct AudioPreferences {
/// True once the person picked the voice input mode explicitly.
mode_chosen: bool,
volume: Option<f32>,
noise_suppress: bool,
/// Notification sound switches and volume.
sounds: SoundSettings,
}
@ -69,6 +70,7 @@ pub fn load(state: &mut UiState) {
state.voice_bitrate = prefs.bitrate.unwrap_or(64.0).clamp(8.0, 128.0);
(state.vad_mode, state.vad_mode_chosen) = resolve_mode(&prefs);
state.output_volume = prefs.volume.unwrap_or(90.0).clamp(0.0, 100.0);
state.noise_suppress = prefs.noise_suppress && cfg!(feature = "rnnoise");
state.sounds = SoundSettings {
volume: prefs.sounds.volume.clamp(0.0, 100.0),
..prefs.sounds
@ -89,6 +91,7 @@ pub fn save(state: &UiState) -> anyhow::Result<()> {
mode: Some(state.vad_mode),
mode_chosen: state.vad_mode_chosen,
volume: Some(state.output_volume),
noise_suppress: state.noise_suppress,
sounds: state.sounds,
};
std::fs::write(path, serde_json::to_vec_pretty(&preferences)?)?;

245
src/ui/server_settings.rs Normal file
View file

@ -0,0 +1,245 @@
//! Real gateway metadata editing with correlated replies and session-fenced requests.
use crate::{
AppState,
net::{NetCommand, NetEvent, wire},
ui::{
slint::MainWindow,
state::{ConnState, UiState},
},
};
use std::{
cell::RefCell,
rc::Rc,
time::{Duration, Instant},
};
#[derive(Clone)]
struct Metadata {
name: String,
description: String,
}
struct Pending {
id: String,
started: Instant,
update: bool,
}
/// Session-local metadata cache and unsaved server-settings draft.
#[derive(Default)]
pub struct ServerSettingsState {
open: bool,
metadata: Option<Metadata>,
name: String,
description: String,
dirty: bool,
pending: Option<Pending>,
error: String,
}
fn allowed(ui: &UiState) -> bool {
super::channel_admin::allowed(ui) && ui.node_settings_supported
}
fn invalid_char(c: char) -> bool {
matches!(c, '\u{061c}' | '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}')
}
fn valid(name: &str, description: &str) -> bool {
(1..=100).contains(&name.trim().chars().count())
&& !name.chars().any(|c| c.is_control() || invalid_char(c))
&& description.trim().chars().count() <= 2000
&& !description
.chars()
.any(|c| (c.is_control() && c != '\n' && c != '\t') || invalid_char(c))
}
fn request(ui: &mut UiState, update: bool) -> Option<NetCommand> {
if !allowed(ui) || ui.server_settings.pending.is_some() {
return None;
}
if update && (!ui.server_settings.open || ui.server_settings.metadata.is_none()) {
return None;
}
let name = ui.server_settings.name.trim().to_owned();
let description = ui.server_settings.description.trim().to_owned();
if update && !valid(&name, &description) {
ui.server_settings.error = super::i18n::text(
"Use a server name of 1–100 characters and a description of at most 2000 characters.",
);
return None;
}
let session_id = match &ui.conn {
ConnState::Connected { session_id, .. } => session_id.clone(),
_ => return None,
};
let id = uuid::Uuid::new_v4().to_string();
ui.server_settings.pending = Some(Pending {
id: id.clone(),
started: Instant::now(),
update,
});
ui.server_settings.error.clear();
Some(NetCommand::ForSession {
session_id,
command: Box::new(NetCommand::NodeSettingsRequest(wire::NodeSettingsRequest {
request_id: id,
update,
display_name: if update { name } else { String::new() },
description: if update { description } else { String::new() },
})),
})
}
/// Open authorized node settings and retrieve current persisted metadata.
pub(super) fn open(ui: &mut UiState) -> Option<NetCommand> {
if !allowed(ui) {
return None;
}
if !ui.server_settings.open {
if let Some(metadata) = &ui.server_settings.metadata {
ui.server_settings.name = metadata.name.clone();
ui.server_settings.description = metadata.description.clone();
} else if let ConnState::Connected { node_name, .. } = &ui.conn {
ui.server_settings.name = node_name.clone();
}
ui.server_settings.open = true;
ui.server_settings.dirty = false;
}
request(ui, false)
}
/// Register name/description editor actions; never persist an optimistic server name.
pub fn wire(window: &MainWindow, state: &Rc<RefCell<AppState>>) {
for action in ["open", "reload", "save"] {
let state = state.clone();
let handler = move || {
let (command, net) = {
let mut state = state.borrow_mut();
let command = if action == "open" {
open(&mut state.ui)
} else {
request(&mut state.ui, action == "save")
};
(command, state.net.clone())
};
if let Some(command) = command {
tokio::spawn(async move {
net.send(command).await;
});
}
};
match action {
"open" => window.on_open_server_settings(handler),
"reload" => window.on_server_settings_reload(handler),
_ => window.on_server_settings_save(handler),
}
}
{
let state = state.clone();
window.on_server_settings_close(move || {
state.borrow_mut().ui.server_settings.open = false;
});
}
for description in [false, true] {
let state = state.clone();
let handler = move |value: slint::SharedString| {
let mut state = state.borrow_mut();
if state.ui.server_settings.pending.is_none() {
if description {
state.ui.server_settings.description = value.to_string();
} else {
state.ui.server_settings.name = value.to_string();
}
state.ui.server_settings.dirty = true;
}
};
if description {
window.on_server_description_edited(handler)
} else {
window.on_server_name_edited(handler)
}
}
}
/// Apply public broadcasts, and match administrative responses by request ID.
pub fn receive(ui: &mut UiState, event: &NetEvent) {
if matches!(
event,
NetEvent::Connected { .. }
| NetEvent::Disconnected { .. }
| NetEvent::Reconnecting { .. }
| NetEvent::AccountRequired
) {
ui.server_settings = Default::default();
return;
}
let NetEvent::NodeSettingsResult {session_id,result} = event else {
return;
};
if !matches!(&ui.conn,ConnState::Connected{session_id:current,..} if current==session_id) { return; }
let matching = ui
.server_settings
.pending
.as_ref()
.is_some_and(|pending| pending.id == result.request_id);
if result.error_code != 0 || !result.error.is_empty() {
if matching {
ui.server_settings.pending = None;
ui.server_settings.error = result.error.chars().take(500).collect();
}
return;
}
if !valid(&result.display_name, &result.description) {
if matching {
ui.server_settings.pending = None;
ui.server_settings.error = super::i18n::text("The server returned invalid settings.");
}
return;
}
let metadata = Metadata {
name: result.display_name.clone(),
description: result.description.clone(),
};
if let ConnState::Connected { node_name, .. } = &mut ui.conn {
*node_name = metadata.name.clone();
} else {
return;
}
let saved = matching
&& ui
.server_settings
.pending
.as_ref()
.is_some_and(|pending| pending.update);
if !ui.server_settings.dirty || saved {
ui.server_settings.name = metadata.name.clone();
ui.server_settings.description = metadata.description.clone();
}
if matching {
ui.server_settings.pending = None;
ui.server_settings.error.clear();
if saved {
ui.server_settings.dirty = false;
}
}
ui.server_settings.metadata = Some(metadata);
}
/// Time out unconfirmed requests and hide settings when their authorization/scope disappears.
pub fn tick(ui: &mut UiState) {
if !allowed(ui) {
ui.server_settings.open = false;
ui.server_settings.pending = None;
}
if ui
.server_settings
.pending
.as_ref()
.is_some_and(|pending| pending.started.elapsed() >= Duration::from_secs(10))
{
ui.server_settings.pending = None;
ui.server_settings.error = super::i18n::text(
"No confirmation received. Reload server settings before trying again.",
);
}
}
/// Synchronize the real editor and its loading/permission status with the native shell.
pub fn sync(window: &MainWindow, ui: &UiState) {
let settings = &ui.server_settings;
window.set_server_settings_open(settings.open && allowed(ui));
window.set_server_name_draft(settings.name.as_str().into());
window.set_server_description_draft(settings.description.as_str().into());
window.set_server_settings_busy(settings.pending.is_some());
window.set_server_settings_loaded(settings.metadata.is_some());
window.set_server_settings_error(settings.error.as_str().into());
}

View file

@ -0,0 +1,27 @@
import { Theme, ActionButton } from "theme.slint";
export component AccountAuth inherits Rectangle {
in property <bool> signing-in;
in property <string> status;
in property <string> public-key;
callback sign-in();
callback cancel();
callback open-browser();
callback settings();
background: Theme.bg-base;
VerticalLayout {
padding: 40px; spacing: 18px; alignment: center;
Text { text: "VNOX"; font-size: 40px; font-weight: 700; color: Theme.text-primary; horizontal-alignment: center; }
Text { text: @tr("Sign in to Central"); font-size: 26px; font-weight: 600; color: Theme.text-primary; horizontal-alignment: center; }
Text { text: @tr("A Central account is required to connect to servers. Your private identity key stays on this device."); color: Theme.text-secondary; font-size: 15px; horizontal-alignment: center; wrap: word-wrap; }
if root.status != "" : Text { text: root.status; color: Theme.text-primary; font-size: 14px; horizontal-alignment: center; wrap: word-wrap; }
if root.public-key != "" : Text { text: root.public-key; color: Theme.accent; font-family: "monospace"; font-size: 13px; horizontal-alignment: center; wrap: char-wrap; }
HorizontalLayout {
alignment: center; spacing: 12px;
if !root.signing-in : ActionButton { text: @tr("Sign in through browser"); primary: true; clicked => { root.sign-in(); } }
if root.signing-in && root.public-key != "" : ActionButton { text: @tr("Open sign-in page"); primary: true; clicked => { root.open-browser(); } }
if root.signing-in : ActionButton { text: @tr("Cancel"); clicked => { root.cancel(); } }
ActionButton { text: @tr("Settings"); icon: "settings"; labeled: true; clicked => { root.settings(); } }
}
}
}

View file

@ -0,0 +1,13 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z" />
</svg>

After

Width:  |  Height:  |  Size: 342 B

View file

@ -0,0 +1,14 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M16 10a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 14.286V4a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z" />
<path d="M20 9a2 2 0 0 1 2 2v10.286a.71.71 0 0 1-1.212.502l-2.202-2.202A2 2 0 0 0 17.172 19H10a2 2 0 0 1-2-2v-1" />
</svg>

After

Width:  |  Height:  |  Size: 457 B

View file

@ -9,6 +9,7 @@ export component AvatarCropper inherits Rectangle {
in property <float> offset-y;
in-out property <float> zoom: 1;
in property <string> error;
in property <bool> saving;
callback crop-moved(float, float);
callback zoom-changed(float);
callback confirm();
@ -109,7 +110,7 @@ export component AvatarCropper inherits Rectangle {
spacing: 9px;
ActionButton { text: @tr("Cancel"); quiet: true; clicked => { root.cancel(); } }
Rectangle { horizontal-stretch: 1; }
ActionButton { text: @tr("Use photo"); active: true; clicked => { root.confirm(); } }
ActionButton { text: root.saving ? @tr("Saving...") : @tr("Use photo"); active: true; clicked => { root.confirm(); } }
}
}
}

View file

@ -0,0 +1,53 @@
import { Theme, ActionButton } from "theme.slint";
import { ThemeInput, DeviceSelect } from "controls.slint";
export component ChannelAdminDialog inherits Rectangle {
in property <[string]> parent-names;
in-out property <int> parent-index;
callback parent-selected(int);
in property <string> operation;
in property <string> kind;
in-out property <string> name;
in property <bool> busy;
in property <string> error;
callback name-edited(string);
callback submit();
callback cancel();
background: Theme.overlay;
TouchArea { }
keyboard := FocusScope {
init => { self.focus(); }
key-pressed(event) => {
if event.text == Key.Escape { root.cancel(); return accept; }
return reject;
}
Rectangle {
width: Math.min(440px, root.width - 32px); height: Math.min(root.operation == "create" && root.kind != "category" ? 430px : 360px, root.height - 32px);
x: (root.width - self.width) / 2; y: (root.height - self.height) / 2;
background: Theme.bg-surface; border-radius: 12px; border-width: 1px; border-color: Theme.border;
VerticalLayout {
padding: 22px; spacing: 14px;
Text { text: root.operation == "delete" ? @tr("Delete channel?") : root.operation == "rename" ? @tr("Rename channel") : root.kind == "voice" ? @tr("Create voice room") : root.kind == "category" ? @tr("Create category") : root.kind == "forum" ? @tr("Create forum") : @tr("Create text channel"); color: Theme.text-primary; font-size: Theme.font-size + 4px; font-weight: 600; wrap: word-wrap; }
if root.operation == "delete" : Text { text: @tr("Delete “{}”? This removes the channel for everyone on this server.", root.name); color: Theme.text-secondary; wrap: word-wrap; font-size: Theme.font-size - 1px; }
if root.operation != "delete" : VerticalLayout {
height: Theme.font-size + 55px;
spacing: 7px; alignment: start;
Text { text: @tr("Channel name"); color: Theme.text-secondary; font-size: Theme.font-size - 2px; }
ThemeInput { init => { self.focus(); } read-only: root.busy; text <=> root.name; placeholder-text: @tr("Channel name"); edited(value) => { root.name-edited(value); } accepted => { if !root.busy { root.submit(); } } }
}
if root.operation == "create" && root.kind != "category" :VerticalLayout {
height:Theme.font-size + 53px;spacing:7px;alignment:start;
Text{text:@tr("Category");color:Theme.text-secondary;font-size:Theme.font-size - 2px;}
if !root.busy :DeviceSelect{model:root.parent-names;current-index <=>root.parent-index;selected(value)=>{root.parent-selected(root.parent-index);}}
if root.busy :Text{text:root.parent-names[root.parent-index];color:Theme.text-primary;font-size:Theme.font-size - 2px;}
}
Text { text: root.busy ? @tr("Waiting for the server…") : root.error; color: root.error != "" ? Theme.danger : Theme.text-muted; wrap: word-wrap; font-size: Math.max(11px, Theme.font-size - 3px); vertical-stretch: 1; }
HorizontalLayout {
spacing: 10px;
ActionButton { text: root.busy ? @tr("Close") : @tr("Cancel"); clicked => { root.cancel(); } }
Rectangle { horizontal-stretch: 1; }
if !root.busy : ActionButton { text: root.operation == "delete" ? @tr("Delete channel") : root.operation == "rename" ? @tr("Save name") : @tr("Create channel"); icon: root.operation == "delete" ? "trash-2" : "check"; labeled: true; danger: root.operation == "delete"; primary: root.operation != "delete"; clicked => { root.submit(); } }
}
}
}
}
}

View file

@ -4,15 +4,17 @@ import { EmojiPicker } from "emoji-picker.slint";
export struct ReactionItem { emoji: string, image: image, has_image: bool, count: int, mine: bool }
export struct MessageItem {
avatar: image, has_avatar: bool,
message_id: string, sender_id: string, sender_name: string,
content: string, timestamp: string, is_own: bool, edited: bool, reply_to: string, avatar_text: string, show_author: bool,
media_source: string, content: string, timestamp: string, is_own: bool, edited: bool, reply_to: string, avatar_text: string, show_author: bool,
reactions: [ReactionItem],
media_image: image, media_ready: bool, media_status: string, media_ratio: float,
}
export struct DmConversationItem {
dm_id: string, other_user_id: string, other_nickname: string,
e2ee_enabled: bool, messages: [MessageItem],
}
export struct MemberItem { user_id: string, nickname: string, status: string, presence: string, avatar_text: string, is_own: bool }
export struct MemberItem { avatar: image, has_avatar: bool, user_id: string, nickname: string, status: string, presence: string, avatar_text: string, is_own: bool }
component QuickReaction inherits Rectangle {
in property <image> glyph;
@ -47,7 +49,7 @@ component ReactionChip inherits Rectangle {
touch := TouchArea { clicked => { root.clicked(); } }
}
component MessageRow inherits Rectangle {
export component MessageRow inherits Rectangle {
in property <MessageItem> message;
in property <bool> actions-enabled: true;
in property <image> own-avatar;
@ -69,7 +71,7 @@ component MessageRow inherits Rectangle {
padding-top: root.message.show_author ? 9px : 2px; padding-bottom: root.message.show_author ? 9px : 2px; spacing: 13px;
AvatarView {
width: 34px; height: root.message.show_author ? 34px : 0px; visible: root.message.show_author;
source: root.own-avatar; has-source: root.has-own-avatar && root.message.is_own;
source: root.message.avatar; has-source: root.message.has_avatar;
initials: root.message.avatar_text; mask: root.background;
}
VerticalLayout {
@ -86,6 +88,20 @@ component MessageRow inherits Rectangle {
Rectangle { horizontal-stretch: 1; }
}
Text { text: root.message.content; color: Theme.text-primary; font-size: Math.max(11px, Theme.font-size * 1.0); wrap: word-wrap; }
if root.message.media_ready : Rectangle {
min-width: 0px; preferred-width: 300px; horizontal-stretch: 1;
height: Math.min(320px, 300px / Math.max(0.1, root.message.media_ratio));
Image {
x: 0px; y: 0px;
source: root.message.media_image;
width: Math.min(300px, parent.width); height: parent.height;
image-fit: contain;
}
}
if root.message.media_status != "" : Text {
text: root.message.media_status; color: Theme.text-muted;
font-size: Math.max(11px, Theme.font-size * 0.75); wrap: word-wrap;
}
if root.message.reactions.length > 0 : HorizontalLayout {
spacing: 6px; alignment: start; padding-top: 2px;
for reaction in root.message.reactions: ReactionChip {
@ -139,6 +155,13 @@ export component ChatPanel inherits Rectangle {
in-out property <string> replying-to-sender;
in-out property <string> replying-to-content;
in-out property <bool> members-visible: true;
in property <image> pending-image;
in property <bool> has-pending-image;
in property <bool> image-uploading;
in property <string> image-status;
callback paste-image() -> bool;
callback cancel-image();
callback send-image();
callback input-edited(string);
callback toggle-members();
callback open-webhooks();
@ -189,6 +212,19 @@ export component ChatPanel inherits Rectangle {
Rectangle { vertical-stretch: 1; }
}
}
if root.has-pending-image || root.image-status != "" : Rectangle {
height: root.has-pending-image ? 132px : 36px;
background: Theme.bg-elevated;
HorizontalLayout {
padding: 10px; spacing: 12px;
if root.has-pending-image : Image { source: root.pending-image; width: 140px; image-fit: contain; }
Text { text: root.image-status; wrap: word-wrap; color: Theme.text-secondary; vertical-alignment: center; horizontal-stretch: 1; }
VerticalLayout { alignment: center;
if root.has-pending-image && !root.image-uploading : ActionButton { text: @tr("Send image"); icon: "send"; primary: true; clicked => { root.send-image(); } }
if !root.image-uploading : ActionButton { text: @tr("Cancel"); icon: "x"; quiet: true; clicked => { root.cancel-image(); } }
}
}
}
if root.replying-to-message != "" : Rectangle {
height: 34px; background: Theme.bg-elevated;
HorizontalLayout {
@ -205,7 +241,7 @@ export component ChatPanel inherits Rectangle {
width: parent.width - 40px;
height: Math.min(150px, Math.max(48px, editor.preferred-height + 22px));
background: Theme.bg-interactive; border-radius: 9px;
border-width: 1px; border-color: editor.has-focus ? Theme.accent.with-alpha(0.6) : Theme.border;
border-width: 1px; border-color: editor.has-focus ? Theme.accent : Theme.border;
HorizontalLayout {
padding-left: 14px; padding-right: 8px; padding-top: 11px; padding-bottom: 11px; spacing: 6px;
editor := TextInput {
@ -216,6 +252,9 @@ export component ChatPanel inherits Rectangle {
selection-background-color: Theme.selected; selection-foreground-color: Theme.text-primary;
edited => { root.input-edited(self.text); }
key-pressed(event) => {
if event.modifiers.control && (event.text == "v" || event.text == "V" || event.text == "м" || event.text == "М") {
if root.paste-image() { return accept; }
}
if event.text == "\n" && !event.modifiers.shift {
root.send-message(root.is-dm ? "" : root.active-channel-id, root.input-text);
return accept;
@ -223,6 +262,10 @@ export component ChatPanel inherits Rectangle {
return reject;
}
}
VerticalLayout {
alignment: end;
ActionButton { text: @tr("Paste image"); icon: "image"; quiet: true; width: 32px; height: 30px; clicked => { root.paste-image(); } }
}
VerticalLayout {
alignment: end;
ActionButton { text: @tr("Emoji"); icon: "smile"; quiet: true; width: 32px; height: 30px; clicked => { emoji-popup.show(); } }
@ -268,7 +311,7 @@ export component ChatPanel inherits Rectangle {
width: 30px;
AvatarView {
width: 30px; height: 30px; y: (parent.height - self.height) / 2;
source: root.own-avatar; has-source: root.has-own-avatar && member.is_own;
source: member.avatar; has-source: member.has_avatar;
initials: member.avatar_text; mask: Theme.bg-surface;
}
PresenceDot { x: 19px; y: parent.height / 2 + 4px; presence: member.presence; ring: Theme.bg-surface; }

View file

@ -1,10 +1,67 @@
import { Theme, ActionButton, Symbol } from "theme.slint";
export component DeviceList inherits Rectangle {
in property <[string]> model;
in property <int> current-index;
in property <string> heading;
callback chosen(int);
background: Theme.bg-surface;
border-radius: 8px;
border-width: 1px; border-color: Theme.border;
VerticalLayout {
padding: 8px; spacing: 6px;
if root.heading != "" : Text { text: root.heading; height: 28px; color: Theme.text-primary; font-size: 14px; font-weight: 600; vertical-alignment: center; }
Flickable {
content-width: self.width;
VerticalLayout {
spacing: 3px;
for item[index] in root.model: Rectangle {
height: 36px; border-radius: 5px;
background: index == root.current-index ? Theme.selected : touch.has-hover ? Theme.bg-hover : transparent;
accessible-role: button; accessible-label: item;
HorizontalLayout {
padding-left: 10px; padding-right: 10px; spacing: 10px;
Text { text: item; horizontal-stretch: 1; overflow: elide; color: Theme.text-primary; font-size: 13px; vertical-alignment: center; }
Rectangle { width: 16px; VerticalLayout { alignment: center; Rectangle { height: 16px; border-radius: 8px; border-width: 1px; border-color: index == root.current-index ? Theme.accent : Theme.text-muted; background: index == root.current-index ? Theme.accent : transparent; } } }
}
touch := TouchArea { clicked => { root.chosen(index); } }
}
}
}
}
}
export component AudioDeviceButton inherits Rectangle {
in property <string> text;
in property <string> icon;
in property <bool> danger;
in property <[string]> model;
in property <int> current-index;
in property <string> heading;
callback clicked();
callback refresh();
callback chosen(int);
width: 46px; height: 32px;
HorizontalLayout {
spacing: 0;
ActionButton { text: root.text; icon: root.icon; danger: root.danger; width: 30px; clicked => { root.clicked(); } right-clicked => { root.refresh(); devices.show(); } }
ActionButton { text: root.heading; icon: "chevron-down"; width: 16px; clicked => { root.refresh(); devices.show(); } right-clicked => { root.refresh(); devices.show(); } }
}
devices := PopupWindow {
width: 310px;
height: Math.min(root.model.length * 39px + 56px, 310px);
x: root.width - self.width; y: -self.height - 8px;
DeviceList { model: root.model; heading: root.heading; current-index: root.current-index; chosen(index) => { root.chosen(index); devices.close(); } }
}
}
export component DeviceSelect inherits Rectangle {
in property <[string]> model;
in-out property <int> current-index;
callback selected(string);
height: 34px;
max-width: 560px;
horizontal-stretch: 0;
background: Theme.bg-interactive;
border-radius: 6px;
border-width: 1px;
@ -32,20 +89,7 @@ export component DeviceSelect inherits Rectangle {
x: 0px; y: root.height + 3px;
width: root.width;
height: Math.min(root.model.length * 36px + 12px, 264px);
Rectangle {
background: Theme.bg-surface; border-radius: 6px;
border-width: 1px; border-color: Theme.border;
Flickable {
content-width: self.width;
VerticalLayout {
padding: 6px; spacing: 3px;
for item[index] in root.model: ActionButton {
text: item; active: index == root.current-index;
clicked => { root.current-index = index; root.selected(item); popup.close(); }
}
}
}
}
DeviceList { model: root.model; current-index: root.current-index; chosen(index) => { root.current-index = index; root.selected(root.model[index]); popup.close(); } }
}
}

123
src/ui/slint/forum.slint Normal file
View file

@ -0,0 +1,123 @@
import { Theme, ActionButton } from "theme.slint";
import { ThemeInput, ThemeEditor } from "controls.slint";
import { MessageItem, MessageRow } from "chat.slint";
export struct ForumTopicItem {
id: string, title: string, author: string, updated: string,
excerpt: string, replies: int,
}
export component ForumPanel inherits Rectangle {
in property <string> channel-name;
in property <[ForumTopicItem]> topics;
in property <[MessageItem]> replies;
in property <string> topic-title;
in property <bool> topic-open;
in property <bool> creating;
in property <bool> loading;
in property <bool> busy;
in property <bool> supported;
in property <bool> more-topics;
in property <bool> more-replies;
in property <string> error;
in-out property <string> title-draft;
in-out property <string> body-draft;
in-out property <string> reply-draft;
callback refresh();
callback create();
callback cancel-create();
callback open-topic(string);
callback back();
callback submit-topic();
callback submit-reply();
callback load-more-topics();
callback load-more-replies();
callback title-edited(string);
callback body-edited(string);
callback reply-edited(string);
background: Theme.bg-base;
VerticalLayout {
spacing: 0;
Rectangle {
height: 58px; background: Theme.bg-surface;
HorizontalLayout {
padding-left: 20px; padding-right: 20px; spacing: 12px;
if root.topic-open || root.creating : VerticalLayout {
alignment: center;
ActionButton { text: @tr("Back to topics"); clicked => { if !root.busy { root.back(); } } }
}
Text { text: root.channel-name; color: Theme.text-primary; font-size: Theme.font-size + 2px; font-weight: 600; vertical-alignment: center; overflow: elide; horizontal-stretch: 1; }
VerticalLayout { alignment: center; ActionButton { text: @tr("Refresh"); clicked => { if root.supported && !root.busy { root.refresh(); } } } }
if !root.topic-open && !root.creating && root.supported : VerticalLayout {
alignment: center;
ActionButton { text: @tr("New topic"); primary: true; clicked => { if !root.busy { root.create(); } } }
}
}
}
Rectangle { height: 1px; background: Theme.border; }
if !root.supported : Text { text: @tr("This server does not support forums yet."); color: Theme.text-secondary; wrap: word-wrap; font-size: Theme.font-size; horizontal-alignment: center; vertical-alignment: center; }
if root.supported : VerticalLayout {
padding: 20px; spacing: 14px;
if root.error != "" : Text { text: root.error; color: Theme.danger; font-size: Theme.font-size - 1px; wrap: word-wrap; }
if root.loading : Text { text: @tr("Loading…"); color: Theme.text-muted; font-size: Theme.font-size - 1px; }
if root.creating : VerticalLayout {
spacing: 12px;
Text { text: @tr("Create topic"); color: Theme.text-primary; font-size: Theme.font-size + 5px; font-weight: 600; }
ThemeInput { text <=> root.title-draft; placeholder-text: @tr("Topic title"); read-only: root.busy; edited(value) => { root.title-edited(value); } }
Text { text: @tr("First message"); color: Theme.text-secondary; font-size: Theme.font-size - 2px; }
ThemeEditor { text <=> root.body-draft; monospace: false; read-only: root.busy; edited(value) => { root.body-edited(value); } }
HorizontalLayout {
alignment: end; spacing: 10px;
ActionButton { text: @tr("Cancel"); clicked => { if !root.busy { root.cancel-create(); } } }
ActionButton { text: root.busy ? @tr("Creating…") : @tr("Create topic"); primary: true; clicked => { if !root.busy { root.submit-topic(); } } }
}
}
if !root.creating && !root.topic-open : VerticalLayout {
spacing: 12px;
if root.topics.length == 0 && !root.loading && root.error == "" : Text {
text: @tr("No topics yet. Start the first discussion."); color: Theme.text-secondary; font-size: Theme.font-size; wrap: word-wrap;
}
Flickable {
content-width: self.width;
VerticalLayout {
spacing: 0;
for topic in root.topics : Rectangle {
height: 105px; background: touch.has-hover ? Theme.bg-hover : transparent;
accessible-role: button; accessible-label: topic.title;
VerticalLayout {
padding-top: 12px; padding-bottom: 12px; padding-left: 12px; padding-right: 12px; spacing: 6px;
Text { text: topic.title; color: Theme.text-primary; font-weight: 600; font-size: Theme.font-size + 1px; overflow: elide; }
Text { text: topic.excerpt; color: Theme.text-secondary; font-size: Theme.font-size - 1px; overflow: elide; }
HorizontalLayout {
spacing: 12px;
Text { text: topic.author; color: Theme.text-muted; font-size: Theme.font-size - 3px; horizontal-stretch: 1; overflow: elide; }
Text { text: @tr("{} replies", topic.replies); color: Theme.text-muted; font-size: Theme.font-size - 3px; }
Text { text: topic.updated; color: Theme.text-muted; font-size: Theme.font-size - 3px; }
}
}
Rectangle { height: 1px; y: parent.height - 1px; background: Theme.border; }
touch := TouchArea { clicked => { keyboard.focus(); if !root.busy { root.open-topic(topic.id); } } }
keyboard := FocusScope { focus-on-click: false; key-pressed(event) => { if event.text == "\n" || event.text == " " { if !root.busy { root.open-topic(topic.id); } return accept; } return reject; } }
if keyboard.has-focus : Rectangle { border-width: 2px; border-color: Theme.accent; background: transparent; }
}
}
}
if root.more-topics : ActionButton { text: @tr("More topics"); clicked => { if !root.loading && !root.busy { root.load-more-topics(); } } }
}
if !root.creating && root.topic-open : VerticalLayout {
spacing: 14px;
Text { text: root.topic-title; color: Theme.text-primary; font-size: Theme.font-size + 5px; font-weight: 600; wrap: word-wrap; }
Flickable {
content-width: self.width;
VerticalLayout {
spacing: 16px;
for reply in root.replies : MessageRow { message: reply; actions-enabled: false; }
}
}
if root.more-replies : ActionButton { text: @tr("More replies"); clicked => { if !root.loading && !root.busy { root.load-more-replies(); } } }
Text { text: @tr("Your reply"); color: Theme.text-secondary; font-size: Theme.font-size - 2px; }
ThemeEditor { text <=> root.reply-draft; monospace: false; preferred-height: 96px; read-only: root.busy; edited(value) => { root.reply-edited(value); } }
HorizontalLayout { alignment: end; ActionButton { text: root.busy ? @tr("Sending…") : @tr("Reply"); primary: true; clicked => { if !root.busy { root.submit-reply(); } } } }
}
}
}
}

View file

@ -6,13 +6,99 @@ export { EmojiCatalog, EmojiItem } from "emoji-picker.slint";
import { Theme, ActionButton } from "theme.slint";
import { Sidebar, ChannelItem, GuildItem, DmItem } from "sidebar.slint";
import { ChatPanel, MessageItem, MemberItem } from "chat.slint";
import { ForumPanel, ForumTopicItem } from "forum.slint";
import { FriendsPanel, FriendItem } from "friends.slint";
import { VoicePanel, VoiceMemberItem } from "voice.slint";
import { BookmarkItem, ConnectScreen } from "connect.slint";
import { SettingsWindow } from "settings.slint";
import { AvatarCropper } from "avatar-cropper.slint";
import { AccountAuth } from "account-auth.slint";
import { ChannelAdminDialog } from "channel-admin.slint";
import { ServerSettingsDialog } from "server-settings.slint";
import { ManagementMenu, ManagementAction } from "management-menu.slint";
export component MainWindow inherits Window {
in-out property <bool> show-forum;
in-out property <string> forum-channel-name;
in-out property <[ForumTopicItem]> forum-topics;
in-out property <[MessageItem]> forum-replies;
in-out property <string> forum-topic-title;
in-out property <bool> forum-topic-open;
in-out property <bool> forum-creating;
in-out property <bool> forum-loading;
in-out property <bool> forum-busy;
in-out property <bool> forum-supported;
in-out property <bool> forum-more-topics;
in-out property <bool> forum-more-replies;
in-out property <string> forum-error;
in-out property <string> forum-title-draft;
in-out property <string> forum-body-draft;
in-out property <string> forum-reply-draft;
callback forum-refresh();
callback forum-create();
callback forum-cancel-create();
callback forum-open-topic(string);
callback forum-back();
callback forum-submit-topic();
callback forum-submit-reply();
callback forum-load-more-topics();
callback forum-load-more-replies();
callback forum-title-edited(string);
callback forum-body-edited(string);
callback forum-reply-edited(string);
in-out property <bool> account-authenticated;
in-out property <string> account-name;
in-out property <string> profile-display-name;
in-out property <bool> profile-saving;
in-out property <string> profile-initials;
in-out property <string> profile-error;
callback save-profile-name(string);
in-out property <string> account-status;
in-out property <bool> account-signing-in;
in-out property <string> account-public-key;
callback account-sign-in();
callback account-sign-out();
callback account-cancel();
callback account-open-browser();
in-out property <bool> management-menu-open;
in-out property <float> management-menu-x;
in-out property <float> management-menu-y;
in-out property <[ManagementAction]> management-actions;
callback open-node-menu(float,float);
callback open-channel-menu(string,float,float);
callback management-menu-chosen(string);
callback management-menu-close();
callback toggle-category(string);
in-out property <bool> node-structure;
in-out property <bool> node-forums;
in-out property <[string]> channel-admin-parent-names;
in-out property <int> channel-admin-parent-index;
callback channel-admin-parent-selected(int);
in-out property <bool> server-settings-open;
in-out property <bool> server-settings-busy;
in-out property <bool> server-settings-loaded;
in-out property <string> server-settings-error;
in-out property <string> server-name-draft;
in-out property <string> server-description-draft;
callback open-server-settings();
callback server-settings-save();
callback server-settings-reload();
callback server-settings-close();
callback server-name-edited(string);
callback server-description-edited(string);
in-out property <bool> node-admin;
in-out property <bool> channel-admin-open;
in-out property <string> channel-admin-operation;
in-out property <string> channel-admin-kind;
in-out property <string> channel-admin-name;
in-out property <bool> channel-admin-busy;
in-out property <string> channel-admin-error;
callback create-global-channel(string);
callback rename-global-channel(string);
callback delete-global-channel(string);
callback channel-admin-name-edited(string);
callback channel-admin-submit();
callback channel-admin-cancel();
in-out property <[ChannelItem]> channels;
in-out property <[GuildItem]> guilds;
in-out property <[DmItem]> dm-conversations;
@ -33,6 +119,7 @@ export component MainWindow inherits Window {
in-out property <float> avatar-offset-x;
in-out property <float> avatar-offset-y;
in-out property <string> avatar-error;
in-out property <bool> avatar-saving;
private property <string> pending-delete-id;
in-out property <string> active-dm-id;
in-out property <bool> voice-connected;
@ -84,6 +171,13 @@ export component MainWindow inherits Window {
in-out property <bool> vault-enabled: false;
in-out property <string> voice-input-device: "";
in-out property <string> voice-output-device: "";
in-out property <bool> noise-suppress;
in property <bool> noise-suppress-available;
in property <bool> mic-test-running;
in property <float> mic-test-level;
in property <string> mic-test-error;
callback toggle-microphone-test();
callback noise-suppression-changed(bool);
in-out property <float> voice-bitrate: 64.0;
in-out property <int> vad-mode: 1;
in-out property <float> volume: 100.0;
@ -96,7 +190,7 @@ export component MainWindow inherits Window {
callback preview-sound();
in-out property <string> language-choice: "system";
callback language-selected(string);
in-out property <string> theme-mode: "dark";
in-out property <string> theme-mode: "black";
in-out property <string> theme-css;
in-out property <string> theme-file-path;
in-out property <float> text-size: 16;
@ -147,11 +241,21 @@ export component MainWindow inherits Window {
callback open-webhooks();
callback show-voice-view();
callback show-friends-view();
in-out property <bool> local-speaking;
callback refresh-audio-devices();
callback device-selected(int, int);
callback audio-settings-changed(int, int, float, int, float);
callback channel-selected(string);
callback guild-selected(int);
callback dm-selected(string);
callback disconnect();
in-out property <image> pending-image;
in-out property <bool> has-pending-image;
in-out property <bool> image-uploading;
in-out property <string> image-status;
callback paste-image() -> bool;
callback cancel-image();
callback send-image();
callback send-message(string, string);
callback load-more(string);
callback react(string, string);
@ -188,7 +292,16 @@ export component MainWindow inherits Window {
background: Theme.bg-base;
if node-name == "" : ConnectScreen {
if !root.account-authenticated : AccountAuth {
signing-in: root.account-signing-in;
status: root.account-status;
public-key: root.account-public-key;
sign-in => { root.account-sign-in(); }
cancel => { root.account-cancel(); }
open-browser => { root.account-open-browser(); }
settings => { root.open-settings(); }
}
if node-name == "" && root.account-authenticated : ConnectScreen {
bookmarks: root.bookmarks;
address-input <=> root.address-input;
status-text: root.status-text;
@ -210,12 +323,24 @@ export component MainWindow inherits Window {
remove-bookmark(address) => { root.remove-bookmark(address); }
add-bookmark(address) => { root.add-bookmark(address); }
}
if node-name != "" : HorizontalLayout {
if node-name != "" && root.account-authenticated : HorizontalLayout {
sidebar := Sidebar {
local-speaking: root.local-speaking;
input-devices: root.input-devices; output-devices: root.output-devices;
input-device-index: root.input-device-index; output-device-index: root.output-device-index;
refresh-devices => { root.refresh-audio-devices(); }
device-selected(input, output) => { root.device-selected(input, output); }
channels: root.channels;
guilds: root.guilds;
dm-conversations: root.dm-conversations;
node-name: root.node-name;
node-admin: root.node-admin;
open-node-menu(x,y) => {root.open-node-menu(x,y);}
open-channel-menu(id,x,y) => {root.open-channel-menu(id,x,y);}
toggle-category(id) => {root.toggle-category(id);}
create-global-channel(kind) => { root.create-global-channel(kind); }
rename-global-channel(id) => { root.rename-global-channel(id); }
delete-global-channel(id) => { root.delete-global-channel(id); }
active-dm-id: root.active-dm-id;
voice-connected: root.voice-connected;
voice-channel-name: root.voice-channel-name;
@ -250,7 +375,38 @@ export component MainWindow inherits Window {
VerticalLayout { alignment: center; ActionButton { text: @tr("Dismiss"); icon: "x"; width: 28px; quiet: true; clicked => { root.dismiss-status(); } } }
}
}
if root.show-chat : ChatPanel {
if root.show-forum : ForumPanel {
channel-name: root.forum-channel-name;
topics: root.forum-topics; replies: root.forum-replies;
topic-title: root.forum-topic-title; topic-open: root.forum-topic-open;
creating: root.forum-creating; loading: root.forum-loading;
busy: root.forum-busy; supported: root.forum-supported;
more-topics: root.forum-more-topics; more-replies: root.forum-more-replies;
error: root.forum-error;
title-draft <=> root.forum-title-draft;
body-draft <=> root.forum-body-draft;
reply-draft <=> root.forum-reply-draft;
refresh => { root.forum-refresh(); }
create => { root.forum-create(); }
cancel-create => { root.forum-cancel-create(); }
open-topic(id) => { root.forum-open-topic(id); }
back => { root.forum-back(); }
submit-topic => { root.forum-submit-topic(); }
submit-reply => { root.forum-submit-reply(); }
load-more-topics => { root.forum-load-more-topics(); }
load-more-replies => { root.forum-load-more-replies(); }
title-edited(value) => { root.forum-title-edited(value); }
body-edited(value) => { root.forum-body-edited(value); }
reply-edited(value) => { root.forum-reply-edited(value); }
}
if root.show-chat && !root.show-forum : ChatPanel {
pending-image: root.pending-image;
has-pending-image: root.has-pending-image;
image-uploading: root.image-uploading;
image-status: root.image-status;
paste-image => { return root.paste-image(); }
cancel-image => { root.cancel-image(); }
send-image => { root.send-image(); }
own-avatar: root.own-avatar;
has-own-avatar: root.has-avatar;
active-channel-id: root.is-dm ? "" : root.active-channel-id;
@ -315,6 +471,15 @@ export component MainWindow inherits Window {
own-avatar: root.own-avatar;
has-avatar: root.has-avatar;
avatar-error: root.avatar-error;
avatar-saving: root.avatar-saving;
account-name: root.account-name;
central-authenticated: root.account-authenticated;
profile-display-name <=> root.profile-display-name;
profile-saving: root.profile-saving;
profile-initials: root.profile-initials;
profile-error: root.profile-error;
save-profile-name(name) => { root.save-profile-name(name); }
account-sign-out => { root.account-sign-out(); root.close-settings(); }
choose-avatar => { root.choose-avatar(); }
remove-avatar => { root.remove-avatar(); }
theme-mode <=> root.theme-mode;
@ -340,6 +505,13 @@ export component MainWindow inherits Window {
vault-enabled: root.vault-enabled;
voice-input-device: root.voice-input-device;
voice-output-device: root.voice-output-device;
noise-suppress <=> root.noise-suppress;
noise-suppress-available: root.noise-suppress-available;
mic-test-running: root.mic-test-running;
mic-test-level: root.mic-test-level;
mic-test-error: root.mic-test-error;
toggle-microphone-test => { root.toggle-microphone-test(); }
noise-suppression-changed(enabled) => { root.noise-suppression-changed(enabled); }
voice-bitrate <=> root.voice-bitrate;
vad-mode <=> root.vad-mode;
volume <=> root.volume;
@ -375,6 +547,17 @@ export component MainWindow inherits Window {
import-keyfile(input, pass) => { root.import-keyfile(input, pass); }
}
if root.account-authenticated && node-name == "" && !root.settings-open : Rectangle {
x: parent.width - self.width - 12px; y: 6px;
width: Math.min(340px, parent.width / 3); height: 32px;
background: Theme.bg-elevated; border-radius: 6px;
HorizontalLayout {
padding-left: 10px; padding-right: 4px; spacing: 8px;
Text { text: root.account-name; color: Theme.text-primary; font-size: 12px; overflow: elide; vertical-alignment: center; horizontal-stretch: 1; }
ActionButton { text: @tr("Sign out of Central"); icon: "log-out"; width: 28px; clicked => { root.account-sign-out(); } }
}
}
if root.pending-delete-id != "" : Rectangle {
background: Theme.overlay;
TouchArea { }
@ -401,9 +584,38 @@ export component MainWindow inherits Window {
offset-x: root.avatar-offset-x;
offset-y: root.avatar-offset-y;
error: root.avatar-error;
saving: root.avatar-saving;
crop-moved(x,y) => { root.avatar-crop-moved(x,y); }
zoom-changed(value) => { root.avatar-zoom-changed(value); }
confirm => { root.confirm-avatar(); }
cancel => { root.cancel-avatar(); }
}
if root.server-settings-open && root.node-admin && root.account-authenticated : ServerSettingsDialog {
width:parent.width;height:parent.height;
name <=>root.server-name-draft;description <=>root.server-description-draft;
busy:root.server-settings-busy;loaded:root.server-settings-loaded;error:root.server-settings-error;
channels:root.channels;structure:root.node-structure;forums:root.node-forums;
name-edited(value)=>{root.server-name-edited(value);}description-edited(value)=>{root.server-description-edited(value);}
save=>{root.server-settings-save();}reload=>{root.server-settings-reload();}close=>{root.server-settings-close();}
create(kind)=>{root.create-global-channel(kind);}rename(id)=>{root.rename-global-channel(id);}remove(id)=>{root.delete-global-channel(id);}
}
if root.channel-admin-open && root.node-admin && root.account-authenticated : ChannelAdminDialog {
width: parent.width; height: parent.height;
parent-names:root.channel-admin-parent-names;parent-index <=>root.channel-admin-parent-index;parent-selected(index)=>{root.channel-admin-parent-selected(index);}
operation: root.channel-admin-operation;
kind: root.channel-admin-kind;
name <=> root.channel-admin-name;
busy: root.channel-admin-busy;
error: root.channel-admin-error;
name-edited(value) => { root.channel-admin-name-edited(value); }
submit => { root.channel-admin-submit(); }
cancel => { root.channel-admin-cancel(); }
}
if root.management-menu-open :ManagementMenu {
width:parent.width;height:parent.height;
actions:root.management-actions;anchor-x:root.management-menu-x;anchor-y:root.management-menu-y;
chosen(action)=>{root.management-menu-chosen(action);}dismiss=>{root.management-menu-close();}
}
}

View file

@ -0,0 +1,46 @@
import { Theme, Symbol } from "theme.slint";
export struct ManagementAction { text: string, icon: string, action: string, danger: bool }
/// Themed embedded menu: no host window is required, including on headless platforms.
export component ManagementMenu inherits Rectangle {
in property <[ManagementAction]> actions;
in property <float> anchor-x;
in property <float> anchor-y;
callback chosen(string);
callback dismiss();
private property <int> selected: 0;
TouchArea { clicked => {root.dismiss();} pointer-event(event) => {if event.button == PointerEventButton.right && event.kind == PointerEventKind.up {root.dismiss();}} }
keyboard := FocusScope {
init => { self.focus(); }
key-pressed(event) => {
if event.text == Key.Tab { root.dismiss(); return reject; }
if event.text == Key.Escape { root.dismiss(); return accept; }
if event.text == Key.DownArrow { root.selected = Math.min(root.selected + 1, root.actions.length - 1); return accept; }
if event.text == Key.UpArrow { root.selected = Math.max(root.selected - 1, 0); return accept; }
if event.text == Key.Home { root.selected = 0; return accept; }
if event.text == Key.End { root.selected = root.actions.length - 1; return accept; }
if event.text == "\n" || event.text == " " { if root.actions.length > 0 { root.chosen(root.actions[root.selected].action); } return accept; }
return reject;
}
Rectangle {
width: 264px; height: root.actions.length * 38px + 12px;
x: Math.clamp(root.anchor-x * 1px, 8px, root.width - self.width - 8px);
y: Math.clamp(root.anchor-y * 1px, 8px, root.height - self.height - 8px);
background: Theme.bg-elevated; border-radius: 8px; border-width: 1px; border-color: Theme.border;
TouchArea { }
VerticalLayout {
padding: 6px; spacing: 2px;
for action[index] in root.actions : Rectangle {
height: 36px; border-radius: 5px;
background: pointer.has-hover || index == root.selected ? Theme.selected : transparent;
accessible-role: button; accessible-label: action.text;
HorizontalLayout {
padding-left: 10px; padding-right: 10px; spacing: 10px;
Symbol { kind: action.icon; ink: action.danger ? Theme.danger : Theme.text-secondary; width: 18px; height: 18px; y: (parent.height - self.height) / 2; }
Text { text: action.text; color: action.danger ? Theme.danger : Theme.text-primary; font-size: Math.max(12px, Theme.font-size - 2px); overflow: elide; vertical-alignment: center; horizontal-stretch: 1; }
}
pointer := TouchArea { moved => { root.selected = index; } clicked => { root.chosen(action.action); } }
}
}
}
}
}

View file

@ -0,0 +1,73 @@
import { Theme, ActionButton } from "theme.slint";
import { ThemeInput, ThemeEditor } from "controls.slint";
import { ChannelItem } from "sidebar.slint";
export component ServerSettingsDialog inherits Rectangle {
in-out property <string> name;
in-out property <string> description;
in property <bool> busy;
in property <bool> loaded;
in property <string> error;
in property <bool> structure;
in property <bool> forums;
in property <[ChannelItem]> channels;
callback name-edited(string);
callback description-edited(string);
callback save(); callback reload(); callback close();
callback create(string); callback rename(string); callback remove(string);
background: Theme.overlay;
TouchArea { }
keyboard := FocusScope {
init => { self.focus(); }
key-pressed(event) => {if event.text == Key.Escape {root.close();return accept;} return reject;}
Rectangle {
x: (root.width - self.width) / 2; y: 24px;
width: Math.min(700px,root.width - 40px); height: root.height - 48px;
background: Theme.bg-surface; border-radius: 12px; border-width: 1px; border-color: Theme.border;
VerticalLayout {
padding: 22px; spacing: 14px;
HorizontalLayout {
Text {text:@tr("Server settings");color:Theme.text-primary;font-size:Theme.font-size + 5px;font-weight:600;horizontal-stretch:1;vertical-alignment:center;}
ActionButton{text:@tr("Close");icon:"x";quiet:true;clicked=>{root.close();}}
}
Text {text:@tr("Changes apply to everyone on this server.");color:Theme.text-muted;font-size:Theme.font-size - 3px;wrap:word-wrap;}
Flickable {
content-width:self.width;
VerticalLayout {
spacing:10px;
Text{text:@tr("Server name");color:Theme.text-secondary;font-size:Theme.font-size - 2px;}
ThemeInput {read-only:root.busy;text<=>root.name;edited(value)=>{root.name-edited(value);}accepted=>{if !root.busy && root.loaded {root.save();}}}
Text{text:@tr("Description");color:Theme.text-secondary;font-size:Theme.font-size - 2px;}
ThemeEditor {monospace:false;read-only:root.busy;text<=>root.description;height:100px;edited(value)=>{if !root.busy {root.description-edited(value);}}}
HorizontalLayout {
spacing:10px;
ActionButton{text:@tr("Reload");clicked=>{if !root.busy{root.reload();}}}
Rectangle{horizontal-stretch:1;}
if root.loaded && !root.busy :ActionButton{text:@tr("Save changes");icon:"check";labeled:true;primary:true;clicked=>{root.save();}}
}
Text{text:root.busy ? @tr("Waiting for the server…") :root.error;color:root.error!=""?Theme.danger:Theme.text-muted;font-size:Theme.font-size - 3px;wrap:word-wrap;}
Rectangle{height:1px;background:Theme.border;}
Text{text:@tr("Channels and categories");color:Theme.text-primary;font-size:Theme.font-size + 1px;font-weight:600;}
HorizontalLayout {
spacing:8px;
ActionButton{text:@tr("Text");icon:"hash";labeled:true;clicked=>{root.create("text");}}
ActionButton{text:@tr("Voice");icon:"volume-2";labeled:true;clicked=>{root.create("voice");}}
if root.structure:ActionButton{text:@tr("Category");icon:"folder";labeled:true;clicked=>{root.create("category");}}
if root.forums:ActionButton{text:@tr("Forum");icon:"messages-square";labeled:true;clicked=>{root.create("forum");}}
Rectangle{horizontal-stretch:1;}
}
for channel in root.channels:Rectangle {
visible:channel.is-global;height:self.visible?38px:0px;
background:Theme.bg-interactive;border-radius:5px;
HorizontalLayout {
padding-left:10px;padding-right:6px;spacing:8px;
Text{text:channel.name;color:Theme.text-primary;vertical-alignment:center;overflow:elide;horizontal-stretch:1;font-size:Theme.font-size - 2px;}
ActionButton{text:@tr("Rename channel");icon:"pencil";quiet:true;clicked=>{root.rename(channel.channel_id);}}
ActionButton{text:@tr("Delete channel");icon:"trash-2";danger:true;quiet:true;clicked=>{root.remove(channel.channel_id);}}
}
}
}
}
}
}
}
}

View file

@ -31,9 +31,18 @@ component SettingsNav inherits Rectangle {
}
export component SettingsWindow inherits Rectangle {
in property <string> account-name;
in property <bool> central-authenticated;
in-out property <string> profile-display-name;
in property <bool> profile-saving;
in property <string> profile-initials;
in property <string> profile-error;
callback save-profile-name(string);
callback account-sign-out();
in property <image> own-avatar;
in property <bool> has-avatar;
in property <string> avatar-error;
in property <bool> avatar-saving;
callback choose-avatar();
callback remove-avatar();
in property <[string]> input-devices;
@ -44,6 +53,13 @@ export component SettingsWindow inherits Rectangle {
in-out property <bool> vault-enabled;
in-out property <string> voice-input-device;
in-out property <string> voice-output-device;
in-out property <bool> noise-suppress;
in property <bool> noise-suppress-available;
in property <bool> mic-test-running;
in property <float> mic-test-level;
in property <string> mic-test-error;
callback toggle-microphone-test();
callback noise-suppression-changed(bool);
in-out property <float> voice-bitrate;
in-out property <int> vad-mode;
in-out property <float> volume;
@ -106,6 +122,8 @@ export component SettingsWindow inherits Rectangle {
Rectangle { height: 1px; background: Theme.border; }
Text { text: "VNOX"; color: Theme.text-secondary; font-size: Math.max(Theme.font-size - 3px, 11px); font-weight: 700; height: 30px; vertical-alignment: bottom; }
Text { text: @tr("Settings for this device"); color: Theme.text-disabled; font-size: Math.max(Theme.font-size - 5px, 11px); }
if root.account-name != "" : Text { text: root.account-name; color: Theme.text-primary; font-size: 13px; overflow: elide; }
if root.account-name != "" : ActionButton { text: @tr("Sign out of Central"); icon: "log-out"; labeled: true; clicked => { root.account-sign-out(); } }
ActionButton { text: @tr("Back to the app"); quiet: true; clicked => { root.close(); } }
}
}
@ -135,6 +153,13 @@ export component SettingsWindow inherits Rectangle {
output-devices: root.output-devices;
input-device-index <=> root.input-device-index;
output-device-index <=> root.output-device-index;
noise-suppress <=> root.noise-suppress;
noise-suppress-available: root.noise-suppress-available;
mic-test-running: root.mic-test-running;
mic-test-level: root.mic-test-level;
mic-test-error: root.mic-test-error;
toggle-microphone-test => { root.toggle-microphone-test(); }
noise-suppression-changed(enabled) => { root.noise-suppression-changed(enabled); }
voice-bitrate <=> root.voice-bitrate;
vad-mode <=> root.vad-mode;
volume <=> root.volume;
@ -171,6 +196,13 @@ export component SettingsWindow inherits Rectangle {
own-avatar: root.own-avatar;
has-avatar: root.has-avatar;
avatar-error: root.avatar-error;
avatar-saving: root.avatar-saving;
central-authenticated: root.central-authenticated;
profile-display-name <=> root.profile-display-name;
profile-saving: root.profile-saving;
profile-initials: root.profile-initials;
profile-error: root.profile-error;
save-profile-name(name) => { root.save-profile-name(name); }
choose-avatar => { root.choose-avatar(); }
remove-avatar => { root.remove-avatar(); }
identity-pubkey: root.identity-pubkey;

View file

@ -6,15 +6,22 @@ component ThemeChoice inherits Rectangle {
in property <bool> selected;
in property <color> preview-background;
in property <color> preview-sidebar;
in property <color> preview-rail;
in property <color> preview-selected;
in property <color> preview-input;
in property <color> preview-ink;
in property <color> preview-accent: #bba583;
callback clicked();
height: 160px;
min-width: 0px;
preferred-width: 0px;
horizontal-stretch: 1;
border-radius: 9px;
border-width: keyboard.has-focus || root.selected ? 2px : 1px;
border-color: root.selected || keyboard.has-focus ? Theme.accent : Theme.border;
background: pointer.has-hover ? Theme.bg-hover : Theme.bg-surface;
accessible-role: button;
accessible-role: radio-button;
accessible-checked: root.selected;
accessible-label: root.label;
VerticalLayout {
padding: 8px; spacing: 10px;
@ -28,7 +35,7 @@ component ThemeChoice inherits Rectangle {
// A miniature client: server rail, channel list, conversation and composer.
rail := Rectangle {
x: 0px; y: 0px;
width: 17px; height: parent.height; background: root.preview-sidebar.darker(8%);
width: 17px; height: parent.height; background: root.preview-rail;
Rectangle { x: 4px; y: 8px; width: 9px; height: 9px; border-radius: 3px; background: root.preview-accent;
Image { source: @image-url("../assets/vnox-mark.svg"); width: 9px; height: 9px; image-fit: contain; }
}
@ -39,7 +46,7 @@ component ThemeChoice inherits Rectangle {
side := Rectangle {
x: 17px; y: 0px; width: parent.width * 0.27; height: parent.height; background: root.preview-sidebar;
Text { x: 5px; y: 7px; text: "Vnox"; color: root.preview-ink; font-size: 7px; font-weight: 700; }
Rectangle { x: 3px; y: 24px; width: parent.width - 6px; height: 13px; border-radius: 2px; background: root.preview-accent.with-alpha(0.18);
Rectangle { x: 3px; y: 24px; width: parent.width - 6px; height: 13px; border-radius: 2px; background: root.preview-selected;
Text { x: 4px; text: "#"; color: root.preview-accent; font-size: 9px; vertical-alignment: center; }
Rectangle { x: 14px; y: 5px; width: Math.max(parent.width - 21px, 3px); height: 3px; border-radius: 1px; background: root.preview-ink.with-alpha(0.65); }
}
@ -59,7 +66,7 @@ component ThemeChoice inherits Rectangle {
Rectangle { x: 7px; y: 56px; width: 10px; height: 10px; border-radius: 4px; background: root.preview-ink.with-alpha(0.22); }
Rectangle { x: 23px; y: 57px; width: parent.width * 0.25; height: 3px; border-radius: 1px; background: root.preview-ink.with-alpha(0.65); }
Rectangle { x: 23px; y: 65px; width: parent.width * 0.4; height: 3px; border-radius: 1px; background: root.preview-ink.with-alpha(0.25); }
Rectangle { x: 6px; y: parent.height - 23px; width: parent.width - 12px; height: 16px; border-radius: 4px; background: root.preview-sidebar;
Rectangle { x: 6px; y: parent.height - 23px; width: parent.width - 12px; height: 16px; border-radius: 4px; background: root.preview-input;
Text { x: 4px; text: "+"; color: root.preview-ink.with-alpha(0.45); font-size: 10px; vertical-alignment: center; }
Rectangle { x: parent.width - 12px; y: 5px; width: 6px; height: 6px; border-radius: 2px; background: root.preview-accent; }
}
@ -78,6 +85,12 @@ export component AppearanceSettings inherits Rectangle {
in-out property <string> language-choice: "system";
callback language-selected(string);
in-out property <string> theme-mode;
private property <bool> selected-theme-is-light: root.theme-mode == "light" || root.theme-mode == "mist" || root.theme-mode == "glacier" || root.theme-mode == "sage" || root.theme-mode == "rose" || root.theme-mode == "sand";
private property <bool> light-group: root.selected-theme-is-light;
// Browsing a group does not apply a theme. Restores/reset still reveal the saved selection.
changed theme-mode => {
if root.theme-mode != "custom" { root.light-group = root.selected-theme-is-light; }
}
in-out property <string> theme-css;
in-out property <string> theme-file-path;
in-out property <float> text-size;
@ -92,6 +105,8 @@ export component AppearanceSettings inherits Rectangle {
callback import-theme(string);
callback export-theme(string);
VerticalLayout {
x: 0px;
width: Math.min(root.width, 1080px);
spacing: 0; alignment: start;
Text { text: @tr("Language"); color: Theme.text-primary; font-size: Theme.font-size + 2px; font-weight: 600; }
Text { text: @tr("Choose your language. Changes apply immediately."); color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; }
@ -108,11 +123,51 @@ export component AppearanceSettings inherits Rectangle {
Text { text: @tr("One theme for chat, rooms and settings. Change it at any time."); color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; }
Rectangle { height: 20px; }
HorizontalLayout {
spacing: 12px;
ThemeChoice { label: @tr("Light"); selected: root.theme-mode == "light"; preview-background: #f5f4f2; preview-sidebar: #e6e4e0; preview-ink: #353330; clicked => { root.theme-selected("light"); } }
ThemeChoice { label: @tr("Dark"); selected: root.theme-mode == "dark"; preview-background: #272729; preview-sidebar: #202022; preview-ink: #e9e7e4; clicked => { root.theme-selected("dark"); } }
ThemeChoice { label: @tr("Extra dark"); selected: root.theme-mode == "black"; preview-background: #080808; preview-sidebar: #131313; preview-ink: #dedbd5; clicked => { root.theme-selected("black"); } }
ThemeChoice { label: @tr("Custom"); selected: root.theme-mode == "custom"; preview-background: Theme.bg-base; preview-sidebar: Theme.bg-surface; preview-ink: Theme.text-primary; preview-accent: Theme.accent; clicked => { root.theme-selected("custom"); } }
spacing: 9px;
ActionButton { text: @tr("Dark themes"); icon: root.light-group ? "circle" : "check"; labeled: true; active: !root.light-group; clicked => { root.light-group = false; } }
ActionButton { text: @tr("Light themes"); icon: root.light-group ? "check" : "circle"; labeled: true; active: root.light-group; clicked => { root.light-group = true; } }
Rectangle { horizontal-stretch: 1; }
ActionButton { text: @tr("Custom"); icon: "palette"; labeled: true; active: root.theme-mode == "custom"; clicked => { root.theme-selected("custom"); } }
}
Rectangle { height: 12px; }
Rectangle {
height: 332px;
if !root.light-group : VerticalLayout {
x: 0px; y: 0px;
width: Math.min(parent.width, 1080px);
height: parent.height;
spacing: 12px;
HorizontalLayout {
spacing: 12px;
ThemeChoice { label: @tr("Extra dark"); selected: root.theme-mode == "black"; preview-background: #090909; preview-sidebar: #111111; preview-rail: #000000; preview-selected: #303030; preview-input: #202020; preview-ink: #f8f6fa; preview-accent: #d5b58a; clicked => { root.theme-selected("black"); } }
ThemeChoice { label: @tr("Graphite"); selected: root.theme-mode == "dark"; preview-background: #292b31; preview-sidebar: #1d1f25; preview-rail: #121419; preview-selected: #3b4251; preview-input: #323641; preview-ink: #f8f6fa; preview-accent: #d5b58a; clicked => { root.theme-selected("dark"); } }
ThemeChoice { label: @tr("Midnight"); selected: root.theme-mode == "midnight"; preview-background: #151f32; preview-sidebar: #10192a; preview-rail: #0b1220; preview-selected: #30425c; preview-input: #25334b; preview-ink: #f8f6fa; preview-accent: #9fc5ff; clicked => { root.theme-selected("midnight"); } }
}
HorizontalLayout {
spacing: 12px;
ThemeChoice { label: @tr("Pine"); selected: root.theme-mode == "pine"; preview-background: #172b26; preview-sidebar: #11231e; preview-rail: #0b1915; preview-selected: #304b40; preview-input: #253c34; preview-ink: #f8f6fa; preview-accent: #91d6af; clicked => { root.theme-selected("pine"); } }
ThemeChoice { label: @tr("Aubergine"); selected: root.theme-mode == "aubergine"; preview-background: #2a2031; preview-sidebar: #211827; preview-rail: #170f1c; preview-selected: #493650; preview-input: #3b2d45; preview-ink: #f8f6fa; preview-accent: #dfb0eb; clicked => { root.theme-selected("aubergine"); } }
ThemeChoice { label: @tr("Espresso"); selected: root.theme-mode == "espresso"; preview-background: #2d241f; preview-sidebar: #241c17; preview-rail: #1b140f; preview-selected: #4b3b30; preview-input: #3e3129; preview-ink: #f8f6fa; preview-accent: #e8bd8d; clicked => { root.theme-selected("espresso"); } }
}
}
if root.light-group : VerticalLayout {
x: 0px; y: 0px;
width: Math.min(parent.width, 1080px);
height: parent.height;
spacing: 12px;
HorizontalLayout {
spacing: 12px;
ThemeChoice { label: @tr("Porcelain"); selected: root.theme-mode == "light"; preview-background: #f5f4f2; preview-sidebar: #eae8e5; preview-rail: #dedbd6; preview-selected: #d8d3cb; preview-input: #ffffff; preview-ink: #28252c; preview-accent: #76532b; clicked => { root.theme-selected("light"); } }
ThemeChoice { label: @tr("Mist"); selected: root.theme-mode == "mist"; preview-background: #f2f3f7; preview-sidebar: #e7e9f0; preview-rail: #dadee9; preview-selected: #cfd5e5; preview-input: #ffffff; preview-ink: #28252c; preview-accent: #43578c; clicked => { root.theme-selected("mist"); } }
ThemeChoice { label: @tr("Glacier"); selected: root.theme-mode == "glacier"; preview-background: #eff6fa; preview-sidebar: #e0edf4; preview-rail: #d1e3ee; preview-selected: #c8e0ec; preview-input: #ffffff; preview-ink: #28252c; preview-accent: #23617e; clicked => { root.theme-selected("glacier"); } }
}
HorizontalLayout {
spacing: 12px;
ThemeChoice { label: @tr("Sage"); selected: root.theme-mode == "sage"; preview-background: #f0f6ef; preview-sidebar: #e2ecdf; preview-rail: #d3e1ce; preview-selected: #cbdcc4; preview-input: #ffffff; preview-ink: #28252c; preview-accent: #3f653b; clicked => { root.theme-selected("sage"); } }
ThemeChoice { label: @tr("Rose"); selected: root.theme-mode == "rose"; preview-background: #faf2f4; preview-sidebar: #f0e3e8; preview-rail: #e7d4dc; preview-selected: #e3ccd6; preview-input: #ffffff; preview-ink: #28252c; preview-accent: #873e5a; clicked => { root.theme-selected("rose"); } }
ThemeChoice { label: @tr("Sand"); selected: root.theme-mode == "sand"; preview-background: #faf5e9; preview-sidebar: #f0e7d3; preview-rail: #e6d9bd; preview-selected: #dfd0ae; preview-input: #ffffff; preview-ink: #28252c; preview-accent: #705018; clicked => { root.theme-selected("sand"); } }
}
}
}
Rectangle { height: 29px; }
Rectangle { height: 1px; background: Theme.border; }

View file

@ -1,4 +1,4 @@
import { Theme } from "../theme.slint";
import { Theme, ActionButton } from "../theme.slint";
import { DeviceSelect, AudioSlider } from "../controls.slint";
export component AudioSettings inherits Rectangle {
@ -6,6 +6,13 @@ export component AudioSettings inherits Rectangle {
in property <[string]> output-devices;
in-out property <int> input-device-index;
in-out property <int> output-device-index;
in-out property <bool> noise-suppress;
in property <bool> noise-suppress-available;
in property <bool> mic-test-running;
in property <float> mic-test-level;
in property <string> mic-test-error;
callback toggle-microphone-test();
callback noise-suppression-changed(bool);
in-out property <float> voice-bitrate;
in-out property <int> vad-mode;
in-out property <float> volume;
@ -32,6 +39,27 @@ export component AudioSettings inherits Rectangle {
selected(value) => { root.audio-changed(); }
}
Rectangle { height: 29px; }
Text { text: @tr("Microphone test"); color: Theme.text-primary; font-size: Theme.font-size + 2px; font-weight: 600; }
Text { text: @tr("Use headphones. Hear yourself locally for up to 30 seconds. Nothing is sent to the room; voice transmission is paused during the test."); color: Theme.text-secondary; font-size: 13px; wrap: word-wrap; }
Rectangle { height: 12px; }
ActionButton { text: root.mic-test-running ? @tr("Stop microphone test") : @tr("Test microphone"); icon: "mic"; labeled: true; primary: !root.mic-test-running; danger: root.mic-test-running; clicked => { root.toggle-microphone-test(); } }
Rectangle { height: 10px; }
Rectangle {
height: 10px; background: Theme.bg-rail; border-radius: 5px;
Rectangle { width: parent.width * Math.clamp(root.mic-test-level, 0, 1); height: parent.height; background: Theme.success; border-radius: 5px; }
}
if root.mic-test-error != "" : Text { text: @tr("Microphone test failed: {}", root.mic-test-error); color: Theme.danger; font-size: 13px; wrap: word-wrap; }
Rectangle { height: 22px; }
Text { text: @tr("Noise suppression"); color: Theme.text-primary; font-size: Theme.font-size - 1px; font-weight: 600; }
Text { text: @tr("RNNoise reduces steady background noise. Compare it with the microphone test."); color: Theme.text-secondary; font-size: 13px; wrap: word-wrap; }
Rectangle { height: 8px; }
if root.noise-suppress-available : DeviceSelect {
model: [@tr("Off"), "RNNoise"];
current-index: root.noise-suppress ? 1 : 0;
selected(value) => { root.noise-suppress = self.current-index == 1; root.noise-suppression-changed(root.noise-suppress); }
}
if !root.noise-suppress-available : Text { text: @tr("Noise suppression is not included in this build."); color: Theme.text-muted; font-size: 13px; wrap: word-wrap; }
Rectangle { height: 26px; }
Rectangle { height: 1px; background: Theme.border; }
Rectangle { height: 26px; }
HorizontalLayout {

View file

@ -6,6 +6,13 @@ export component IdentitySettings inherits Rectangle {
in property <image> own-avatar;
in property <bool> has-avatar;
in property <string> avatar-error;
in property <bool> avatar-saving;
in property <bool> central-authenticated;
in-out property <string> profile-display-name;
in property <bool> profile-saving;
in property <string> profile-initials;
in property <string> profile-error;
callback save-profile-name(string);
callback choose-avatar();
callback remove-avatar();
in-out property <string> identity-pubkey;
@ -30,31 +37,43 @@ export component IdentitySettings inherits Rectangle {
callback import-keyfile(string, string);
VerticalLayout {
spacing: 0; alignment: start;
if root.central-authenticated : VerticalLayout {
spacing: 9px; alignment: start;
Text { text: @tr("Display name"); color: Theme.text-primary; font-size: Theme.font-size + 2px; font-weight: 600; }
HorizontalLayout {
spacing: 9px;
ThemeInput { text <=> root.profile-display-name; placeholder-text: @tr("Your display name"); horizontal-stretch: 1; }
ActionButton { text: root.profile-saving ? @tr("Saving...") : @tr("Save"); clicked => { root.save-profile-name(root.profile-display-name); } }
}
Text { text: @tr("Saved to Central and synced with connected members."); color: Theme.text-muted; font-size: Math.max(Theme.font-size - 4px, 11px); wrap: word-wrap; }
if root.profile-error != "" : Text { text: root.profile-error; color: Theme.danger; font-size: Math.max(11px, Theme.font-size - 3px); wrap: word-wrap; }
Rectangle { height: 16px; }
}
Text { text: @tr("Profile photo"); color: Theme.text-primary; font-size: Theme.font-size + 2px; font-weight: 600; }
Text { text: @tr("Choose an image and crop it for your avatar."); color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; }
Rectangle { height: 18px; }
HorizontalLayout {
spacing: 20px;
AvatarView { width: 82px; height: 82px; source: root.own-avatar; has-source: root.has-avatar; initials: @tr("Photo"); mask: Theme.bg-base; }
AvatarView { width: 82px; height: 82px; source: root.own-avatar; has-source: root.has-avatar; initials: root.profile-initials; mask: Theme.bg-base; }
VerticalLayout {
spacing: 9px; alignment: center;
HorizontalLayout {
spacing: 9px;
ActionButton { text: root.has-avatar ? @tr("Change photo") : @tr("Choose photo"); clicked => { root.choose-avatar(); } }
ActionButton { text: root.avatar-saving ? @tr("Saving...") : root.has-avatar ? @tr("Change photo") : @tr("Choose photo"); clicked => { root.choose-avatar(); } }
if root.has-avatar : ActionButton { text: @tr("Delete"); quiet: true; danger: true; clicked => { root.remove-avatar(); } }
Rectangle { horizontal-stretch: 1; }
}
Text { text: @tr("Currently stored only on this device."); color: Theme.text-muted; font-size: Math.max(Theme.font-size - 4px, 11px); wrap: word-wrap; }
Text { text: root.central-authenticated ? @tr("Synced with your Central account and other devices.") : @tr("Currently stored only on this device."); color: Theme.text-muted; font-size: Math.max(Theme.font-size - 4px, 11px); wrap: word-wrap; }
}
}
if root.avatar-error != "" : Text { text: root.avatar-error; color: Theme.danger; font-size: Math.max(11px, Theme.font-size - 3px); wrap: word-wrap; }
Rectangle { height: 26px; }
Rectangle { height: 1px; background: Theme.border; }
Rectangle { height: 24px; }
Text { text: @tr("Your key"); color: Theme.text-primary; font-size: Theme.font-size + 2px; font-weight: 600; }
Text { text: @tr("Your public key identifies your profile. You can share it; your secret key stays on this device."); color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; }
Text { text: @tr("Your public key identifies this device. Your Central account keeps your name and photo in sync."); color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; }
Rectangle { height: 16px; }
ThemeEditor { text: root.identity-pubkey; read-only: true; height: 78px; }
if root.avatar-error != "" : Text { text: root.avatar-error; color: Theme.danger; font-size: Math.max(11px, Theme.font-size - 3px); wrap: word-wrap; }
Rectangle { height: 28px; }
Rectangle { height: 1px; background: Theme.border; }
Rectangle { height: 24px; }

View file

@ -1,7 +1,8 @@
import { AudioDeviceButton } from "controls.slint";
import { AvatarView, PresenceDot } from "avatar-view.slint";
import { Theme, ActionButton, Symbol } from "theme.slint";
export struct ChannelItem { channel_id: string, name: string, kind: string }
export struct ChannelItem { channel_id: string, name: string, kind: string, is-global: bool, parent-id: string, indented: bool, collapsed: bool }
export struct GuildItem { guild_id: string, name: string, short_name: string, selected: bool }
export struct DmItem { dm_id: string, name: string, unread: int }
@ -11,6 +12,15 @@ component NavRow inherits Rectangle {
in property <bool> selected;
in property <int> unread;
callback clicked();
in property <bool> manageable: false;
in property <bool> category: false;
in property <bool> collapsed: false;
in property <bool> indented: false;
callback context-menu(float,float);
callback add-child();
private property <bool> context-click: false;
callback rename();
callback remove();
height: root.visible ? 36px : 0px;
border-radius: 6px;
background: selected ? Theme.selected : touch.has-hover ? Theme.bg-hover : transparent;
@ -18,16 +28,29 @@ component NavRow inherits Rectangle {
border-color: Theme.accent;
accessible-role: button;
accessible-label: label;
touch := TouchArea {
clicked => { if !root.context-click {keyboard.focus(); root.clicked();} }
pointer-event(event) => {
if event.kind == PointerEventKind.down {root.context-click = event.button == PointerEventButton.right;}
if event.button == PointerEventButton.right && event.kind == PointerEventKind.up {
keyboard.focus(); root.context-menu((self.absolute-position.x+self.mouse-x)/1px,(self.absolute-position.y+self.mouse-y)/1px);
}
}
}
HorizontalLayout {
padding-left: 10px; padding-right: 10px; spacing: 10px;
Symbol { kind: root.symbol; ink: root.selected ? Theme.text-primary : Theme.text-muted; width: 17px; height: 17px; y: (parent.height - self.height) / 2; }
Text { text: root.label; color: root.selected || root.unread > 0 ? Theme.text-primary : Theme.text-secondary; font-size: Math.max(11px, Theme.font-size * 0.875); horizontal-stretch: 1; overflow: elide; vertical-alignment: center; }
padding-left: root.indented ? 24px : 10px; padding-right: 10px; spacing: 10px;
Symbol { kind: root.category ? (root.collapsed ? "plus" : "minus") : root.symbol; ink: root.selected ? Theme.text-primary : Theme.text-muted; width: 17px; height: 17px; y: (parent.height - self.height) / 2; }
Text { text: root.label; font-weight: root.category ? 600 : 400; color: root.selected || root.unread > 0 ? Theme.text-primary : Theme.text-secondary; font-size: Math.max(11px, Theme.font-size * 0.875); horizontal-stretch: 1; overflow: elide; vertical-alignment: center; }
if root.manageable && root.category :ActionButton{text:@tr("Create channel");icon:"plus";quiet:true;width:26px;height:26px;clicked=>{root.add-child();}}
if root.manageable : ActionButton { text: @tr("Rename channel"); icon: "pencil"; quiet: true; width: 26px; height: 26px; clicked => { root.rename(); } }
if root.manageable : ActionButton { text: @tr("Delete channel"); icon: "trash-2"; quiet: true; width: 26px; height: 26px; danger: true; clicked => { root.remove(); } }
if root.unread > 0 : Text { text: root.unread; color: Theme.accent; font-size: Math.max(11px, Theme.font-size * 0.75); vertical-alignment: center; font-weight: 600; }
}
touch := TouchArea { clicked => { keyboard.focus(); root.clicked(); } }
keyboard := FocusScope {
focus-on-click: false;
key-pressed(event) => {
if event.text == Key.F10 && event.modifiers.shift {root.context-menu(root.absolute-position.x/1px,(root.absolute-position.y+root.height)/1px);return accept;}
if event.text == " " || event.text == "\n" { root.clicked(); return accept; }
return reject;
}
@ -52,6 +75,20 @@ export component Sidebar inherits Rectangle {
in-out property <bool> mic-enabled;
in-out property <bool> deafened;
in-out property <string> node-name;
in property <bool> node-admin;
callback open-node-menu(float,float);
callback open-channel-menu(string,float,float);
callback toggle-category(string);
callback create-global-channel(string);
callback rename-global-channel(string);
callback delete-global-channel(string);
in property <bool> local-speaking;
in property <[string]> input-devices;
in property <[string]> output-devices;
in property <int> input-device-index;
in property <int> output-device-index;
callback refresh-devices();
callback device-selected(int, int);
callback channel-selected(string);
callback guild-selected(int);
callback dm-selected(string);
@ -93,12 +130,24 @@ export component Sidebar inherits Rectangle {
border-width: 1px; border-color: Theme.border;
HorizontalLayout {
padding-left: 17px; padding-right: 10px; spacing: 8px;
Text { text: root.show-dms ? @tr("Direct messages") : root.active-guild-idx >= 0 && root.active-guild-idx < root.guilds.length ? root.guilds[root.active-guild-idx].name : root.node-name; color: Theme.text-primary; font-size: Math.max(11px, Theme.font-size * 1.0); font-weight: 600; overflow: elide; horizontal-stretch: 1; vertical-alignment: center; }
if !root.show-dms && root.active-guild-idx < 0 :Rectangle {
horizontal-stretch:1;background:heading-pointer.has-hover?Theme.bg-hover:transparent;
border-radius:5px;border-width:heading-keyboard.has-focus?1px:0px;border-color:Theme.accent;
accessible-role:button;accessible-label:@tr("Server menu");
HorizontalLayout{spacing:8px;
Text{text:root.node-name;color:Theme.text-primary;font-size:Theme.font-size;font-weight:600;overflow:elide;horizontal-stretch:1;vertical-alignment:center;}
Symbol{kind:"chevron-down";width:16px;height:16px;y:(parent.height - self.height)/2;ink:Theme.text-secondary;}
}
heading-pointer:=TouchArea{clicked=>{heading-keyboard.focus();root.open-node-menu(self.absolute-position.x/1px,(self.absolute-position.y+self.height)/1px);}}
heading-keyboard:=FocusScope{key-pressed(event)=>{if event.text==" "||event.text=="\n"||event.text==Key.DownArrow{root.open-node-menu(root.absolute-position.x/1px+80,(root.absolute-position.y+56px)/1px);return accept;}return reject;}}
}
if root.show-dms || root.active-guild-idx >= 0 :Text {text:root.show-dms?@tr("Direct messages"):root.active-guild-idx<root.guilds.length?root.guilds[root.active-guild-idx].name:"";color:Theme.text-primary;font-size:Theme.font-size;font-weight:600;overflow:elide;horizontal-stretch:1;vertical-alignment:center;}
VerticalLayout { alignment: center; ActionButton { text: @tr("Disconnect from server"); icon: "log-out"; width: 32px; quiet: true; clicked => { root.disconnect(); } } }
}
}
Flickable {
content-width: self.width;
TouchArea{enabled:root.node-admin&&!root.show-dms&&root.active-guild-idx<0;pointer-event(event)=>{if event.button==PointerEventButton.right&&event.kind==PointerEventKind.up{root.open-channel-menu("",(self.absolute-position.x+self.mouse-x)/1px,(self.absolute-position.y+self.mouse-y)/1px);}}}
VerticalLayout {
padding: 10px; spacing: 3px;
if root.show-dms : NavRow { label: @tr("Friends"); symbol: "at-sign"; clicked => { root.show-friends(); } }
@ -110,19 +159,21 @@ export component Sidebar inherits Rectangle {
selected: root.active-dm-id == dm.dm_id;
clicked => { root.dm-selected(dm.dm_id); }
}
if !root.show-dms : Text { text: @tr("Text channels"); color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.75); height: 32px; vertical-alignment: bottom; }
for ch in root.channels: NavRow {
visible: !root.show-dms && ch.kind != "voice";
label: ch.name;
selected: root.active-channel-id == ch.channel_id;
clicked => { root.channel-selected(ch.channel_id); }
if !root.show-dms : HorizontalLayout {
height:32px;
Text{text:@tr("Channels");color:Theme.text-muted;font-size:Math.max(11px,Theme.font-size*0.75);vertical-alignment:bottom;horizontal-stretch:1;}
if root.node-admin && root.active-guild-idx < 0 :ActionButton{text:@tr("Create channel");icon:"plus";quiet:true;width:28px;clicked=>{root.open-channel-menu("",self.absolute-position.x/1px,(self.absolute-position.y+self.height)/1px);}}
}
if !root.show-dms : Text { text: @tr("Voice rooms"); color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.75); height: 40px; vertical-alignment: bottom; }
for ch in root.channels: NavRow {
visible: !root.show-dms && ch.kind == "voice";
label: ch.name; symbol: "volume-2";
selected: root.voice-connected && root.voice-channel-name == ch.name;
clicked => { root.channel-selected(ch.channel_id); }
for ch in root.channels:NavRow {
visible:!root.show-dms;
label:ch.name;category:ch.kind=="category";collapsed:ch.collapsed;indented:ch.indented;
symbol:ch.kind=="voice"?"volume-2":ch.kind=="forum"?"messages-square":"hash";
manageable:ch.is-global && root.node-admin && root.active-guild-idx < 0;
selected:ch.kind=="voice"?root.voice-connected&&root.voice-channel-name==ch.name:root.active-channel-id==ch.channel_id;
clicked=>{if ch.kind=="category"{root.toggle-category(ch.channel_id);}else{root.channel-selected(ch.channel_id);}}
context-menu(x,y)=>{if root.node-admin&&root.active-guild-idx<0{root.open-channel-menu(ch.channel_id,x,y);}}
add-child=>{root.open-channel-menu(ch.channel_id,self.absolute-position.x/1px,(self.absolute-position.y+self.height)/1px);}
rename=>{root.rename-global-channel(ch.channel_id);}remove=>{root.delete-global-channel(ch.channel_id);}
}
Rectangle { vertical-stretch: 1; }
}
@ -131,7 +182,7 @@ export component Sidebar inherits Rectangle {
height: 88px;
background: Theme.voice-bg;
border-radius: 8px;
border-width: 1px; border-color: Theme.border;
border-width: 1px; border-color: Theme.success.with-alpha(0.65);
VerticalLayout {
padding: 10px; spacing: 5px;
HorizontalLayout {
@ -142,8 +193,8 @@ export component Sidebar inherits Rectangle {
Text { text: root.voice-channel-name; color: Theme.text-secondary; font-size: Math.max(11px, Theme.font-size * 0.6875); overflow: elide; }
HorizontalLayout {
spacing: 6px;
ActionButton { text: @tr("Open"); clicked => { root.show-voice(); } }
ActionButton { text: @tr("Leave"); danger: true; clicked => { root.leave-voice(); } }
ActionButton { text: @tr("Open"); primary: true; clicked => { root.show-voice(); } }
ActionButton { text: @tr("Leave"); icon: "phone-off"; labeled: true; danger: true; clicked => { root.leave-voice(); } }
}
}
}
@ -154,7 +205,7 @@ export component Sidebar inherits Rectangle {
padding: 9px; spacing: 5px;
Rectangle {
width: 34px;
AvatarView { width: 32px; height: 32px; y: (parent.height - self.height) / 2; source: root.own-avatar; has-source: root.has-avatar; initials: root.own-initials; mask: Theme.bg-elevated; }
AvatarView { width: 32px; height: 32px; y: (parent.height - self.height) / 2; source: root.own-avatar; has-source: root.has-avatar; initials: root.own-initials; speaking: root.local-speaking; mask: Theme.bg-elevated; }
PresenceDot { x: 21px; y: parent.height / 2 + 6px; presence: "online"; ring: Theme.bg-elevated; }
}
VerticalLayout {
@ -162,8 +213,8 @@ export component Sidebar inherits Rectangle {
Text { text: root.username; color: Theme.text-primary; font-size: Math.max(11px, Theme.font-size * 0.8125); font-weight: 600; overflow: elide; }
Text { text: root.user-status; color: Theme.success; font-size: Math.max(11px, Theme.font-size * 0.6875); overflow: elide; }
}
VerticalLayout { alignment: center; ActionButton { text: root.mic-enabled ? @tr("Mute microphone") : @tr("Unmute microphone"); icon: root.mic-enabled ? "mic" : "mic-off"; width: 30px; danger: !root.mic-enabled; quiet: true; clicked => { root.toggle-mic(); } } }
VerticalLayout { alignment: center; ActionButton { text: root.deafened ? @tr("Undeafen") : @tr("Deafen"); icon: root.deafened ? "headphone-off" : "headphones"; width: 30px; danger: root.deafened; quiet: true; clicked => { root.toggle-deafen(); } } }
VerticalLayout { alignment: center; AudioDeviceButton { text: root.mic-enabled ? @tr("Mute microphone") : @tr("Unmute microphone"); icon: root.mic-enabled ? "mic" : "mic-off"; danger: !root.mic-enabled; model: root.input-devices; current-index: root.input-device-index; heading: @tr("Microphone"); clicked => { root.toggle-mic(); } refresh => { root.refresh-devices(); } chosen(index) => { root.device-selected(index, root.output-device-index); } } }
VerticalLayout { alignment: center; AudioDeviceButton { text: root.deafened ? @tr("Undeafen") : @tr("Deafen"); icon: root.deafened ? "headphone-off" : "headphones"; danger: root.deafened; model: root.output-devices; current-index: root.output-device-index; heading: @tr("Headphones or speakers"); clicked => { root.toggle-deafen(); } refresh => { root.refresh-devices(); } chosen(index) => { root.device-selected(root.input-device-index, index); } } }
VerticalLayout { alignment: center; ActionButton { text: @tr("Settings"); icon: "settings"; width: 30px; quiet: true; clicked => { root.open-settings(); } } }
}
}

View file

@ -1,25 +1,25 @@
export global Theme {
in-out property <color> bg-base: #272729;
in-out property <color> bg-surface: #202022;
in-out property <color> bg-rail: #151516;
in-out property <color> bg-hover: #38383c;
in-out property <color> bg-elevated: #303033;
in-out property <color> bg-interactive: #343336;
in-out property <color> selected: #3a393c;
in-out property <color> border: #ffffff12;
in-out property <color> bg-base: #090909;
in-out property <color> bg-surface: #111111;
in-out property <color> bg-rail: #000000;
in-out property <color> bg-hover: #262626;
in-out property <color> bg-elevated: #181818;
in-out property <color> bg-interactive: #202020;
in-out property <color> selected: #303030;
in-out property <color> border: #9099a6;
in-out property <color> accent: #d5b58a;
in-out property <color> text-primary: #e9e7e4;
in-out property <color> text-secondary: #b8b4b1;
in-out property <color> text-muted: #aaa29b;
in-out property <color> text-disabled: #85817f;
in-out property <color> danger: #e58b85;
in-out property <color> success: #a8c1a4;
in-out property <color> text-primary: #f8f6fa;
in-out property <color> text-secondary: #e0dce5;
in-out property <color> text-muted: #ccc7d2;
in-out property <color> text-disabled: #b9b2bf;
in-out property <color> danger: #ffb4b0;
in-out property <color> success: #9ce3b7;
in-out property <length> font-size: 16px;
out property <float> scale: font-size / 16px;
in-out property <color> on-accent: #29221b;
in-out property <color> avatar-bg: #49433d;
in-out property <color> voice-bg: #282c28;
in-out property <color> overlay: #00000080;
in-out property <color> on-accent: #231e19;
in-out property <color> avatar-bg: #2f2b26;
in-out property <color> voice-bg: #222b25;
in-out property <color> overlay: #00000091;
in-out property <length> radius: 7px;
}
@ -62,6 +62,8 @@ export component Symbol inherits Image {
kind == "circle" ? @image-url("assets/icons/circle.svg") :
kind == "corner-down-right" ? @image-url("assets/icons/corner-down-right.svg") :
kind == "audio-lines" ? @image-url("assets/icons/audio-lines.svg") :
kind == "folder" ? @image-url("assets/icons/folder.svg") :
kind == "messages-square" ? @image-url("assets/icons/messages-square.svg") :
kind == "palette" ? @image-url("assets/icons/palette.svg") :
kind == "key-round" ? @image-url("assets/icons/key-round.svg") :
kind == "minus" ? @image-url("assets/icons/minus.svg") :
@ -104,14 +106,15 @@ export component ActionButton inherits Rectangle {
// Bubble text. Icon-only buttons show their label here by default.
in property <string> tooltip: icon != "" && !labeled ? text : "";
callback clicked();
callback right-clicked();
min-width: 30px;
horizontal-stretch: 0;
preferred-width: icon == "" ? label.preferred-width + 22px : labeled ? label.preferred-width + 48px : 32px;
height: 32px;
border-radius: 6px;
background: primary ? (touch.has-hover ? Theme.accent.brighter(8%) : Theme.accent) : active ? Theme.selected : touch.has-hover ? Theme.bg-hover : quiet ? transparent : Theme.bg-interactive;
border-width: keyboard.has-focus ? 1px : 0px;
border-color: Theme.accent;
border-width: keyboard.has-focus || !quiet ? 1px : 0px;
border-color: keyboard.has-focus ? Theme.accent : Theme.border;
accessible-role: button;
accessible-label: text;
Symbol { visible: root.icon != ""; kind: root.icon; ink: root.primary ? Theme.on-accent : root.danger ? Theme.danger : root.active ? Theme.text-primary : Theme.text-secondary; width: 18px; height: 18px; x: root.labeled ? 12px : (parent.width - self.width) / 2; y: (parent.height - self.height) / 2; }
@ -127,7 +130,7 @@ export component ActionButton inherits Rectangle {
vertical-alignment: center;
overflow: elide;
}
touch := TouchArea { clicked => { keyboard.focus(); root.clicked(); } }
touch := TouchArea { clicked => { keyboard.focus(); root.clicked(); } pointer-event(event) => { if event.button == PointerEventButton.right && event.kind == PointerEventKind.up { root.right-clicked(); } } }
keyboard := FocusScope {
focus-on-click: false;
key-pressed(event) => {

View file

@ -1,7 +1,7 @@
import { AvatarView } from "avatar-view.slint";
import { Theme, ActionButton, Symbol, TipBubble } from "theme.slint";
export struct VoiceMemberItem { user_id: string, nickname: string, speaking: bool, avatar_text: string, is_own: bool }
export struct VoiceMemberItem { avatar: image, has_avatar: bool, user_id: string, nickname: string, speaking: bool, avatar_text: string, is_own: bool }
/// Round control of the voice room bar. `off` shows the muted state highlighted in red.
component RoundControl inherits Rectangle {
@ -42,7 +42,7 @@ component ParticipantCard inherits Rectangle {
in property <bool> has-own-avatar;
border-radius: 16px;
background: Theme.bg-elevated;
border-width: root.member.speaking ? 2px : 1px;
border-width: root.member.speaking ? 3px : 1px;
border-color: root.member.speaking ? Theme.success : Theme.border;
VerticalLayout {
padding: 18px; spacing: 10px; alignment: center;
@ -50,7 +50,7 @@ component ParticipantCard inherits Rectangle {
alignment: center;
AvatarView {
width: 80px; height: 80px;
source: root.own-avatar; has-source: root.has-own-avatar && root.member.is_own;
source: root.member.avatar; has-source: root.member.has_avatar;
initials: root.member.avatar_text; mask: Theme.bg-elevated;
speaking: root.member.speaking;
}

View file

@ -173,6 +173,8 @@ mod tests {
..connected_ui()
};
let join = |channel: &str, user: &str| NetEvent::UserJoin {
account_id: String::new(),
avatar_url: String::new(),
channel_id: channel.into(),
user_id: user.into(),
nickname: user.into(),

View file

@ -6,6 +6,7 @@ use super::types::{ConnState, UiState, VoiceUiState};
impl Default for UiState {
fn default() -> Self {
Self {
central_account: None,
appearance: crate::ui::appearance::AppearancePreferences::default(),
conn: ConnState::Disconnected,
connect_input: "127.0.0.1:7600".into(),
@ -13,6 +14,7 @@ impl Default for UiState {
selected_bookmark: 0,
status_msg: None,
trust_prompt: None,
forum: Default::default(),
channels: Vec::new(),
active_channel: None,
messages: Default::default(),
@ -26,6 +28,7 @@ impl Default for UiState {
scroll_bottom: false,
voice: VoiceUiState::Off,
voice_joined_at: None,
member_profiles: Default::default(),
user_names: Default::default(),
rtt_ms: None,
@ -43,11 +46,16 @@ impl Default for UiState {
output_device: 0,
output_device_id: String::new(),
output_volume: 90.0,
noise_suppress: false,
mic_test_running: false,
mic_test_level: 0.0,
mic_test_error: None,
sounds: Default::default(),
device_lists: Default::default(),
vad_mode_chosen: false,
auto_reconnect: true,
connection: Default::default(),
guilds: Vec::new(),
active_guild_id: None,
@ -63,6 +71,12 @@ impl Default for UiState {
user_colors: HashMap::new(),
private_mode: false,
node_admin: false,
node_settings_supported: false,
channel_structure_supported: false,
server_settings: Default::default(),
collapsed_categories: Default::default(),
channel_admin: Default::default(),
typing_users: HashMap::new(),
read_receipts: HashMap::new(),

View file

@ -41,3 +41,216 @@ impl UiState {
.unwrap_or(sender_id)
}
}
impl UiState {
/// Account rows retain all device subscriptions internally for voice and leave events.
pub fn account_members<'a>(&self, devices: &'a [String]) -> Vec<&'a String> {
let mut accounts = std::collections::HashSet::new();
devices
.iter()
.filter(|device| {
let account = self
.member_profiles
.get(*device)
.map(|profile| {
if profile.0.is_empty() {
(*device).clone()
} else {
profile.0.clone()
}
})
.unwrap_or_else(|| (*device).clone());
accounts.insert(account)
})
.collect()
}
}
#[cfg(test)]
mod account_presence_tests {
#[test]
fn account_row_remains_until_last_device_leaves_in_both_orders() {
for reverse in [false, true] {
let mut state = super::UiState::default();
state
.member_profiles
.insert("device-a".into(), ("account".into(), String::new()));
state
.member_profiles
.insert("device-b".into(), ("account".into(), String::new()));
let mut devices = vec!["device-a".to_owned(), "device-b".to_owned()];
assert_eq!(state.account_members(&devices).len(), 1);
devices.remove(usize::from(reverse));
assert_eq!(state.account_members(&devices).len(), 1);
devices.clear();
assert!(state.account_members(&devices).is_empty());
}
}
}
impl UiState {
pub fn avatar_path_for(&self, device: &str, own_device: &str) -> Option<String> {
if device == own_device {
if let Some(account) = &self.central_account {
return Some(
account
.avatar_url
.clone()
.unwrap_or_else(|| format!("/v1/avatars/default-v2/{}", account.user_id)),
);
}
return None;
}
self.member_profiles
.get(device)
.map(|profile| profile.1.clone())
}
}
#[cfg(test)]
mod avatar_profile_tests {
#[test]
fn central_own_profile_wins_and_logout_removes_own_remote_path() {
let mut state = super::UiState::default();
state.member_profiles.insert(
"own-device".into(),
("account".into(), "/v1/avatars/stale".into()),
);
state.member_profiles.insert(
"other-device".into(),
("other-account".into(), "/v1/avatars/other".into()),
);
state.central_account = Some(crate::net::account::AccountSummary {
user_id: "account".into(),
handle: "handle".into(),
display_name: "Central Name".into(),
avatar_url: Some("/v1/avatars/current".into()),
profile_complete: true,
});
assert_eq!(
state.avatar_path_for("own-device", "own-device").as_deref(),
Some("/v1/avatars/current")
);
assert_eq!(
state
.avatar_path_for("other-device", "own-device")
.as_deref(),
Some("/v1/avatars/other")
);
state.central_account.as_mut().unwrap().avatar_url = None;
assert_eq!(
state.avatar_path_for("own-device", "own-device").as_deref(),
Some("/v1/avatars/default-v2/account")
);
state.central_account = None;
assert!(state.avatar_path_for("own-device", "own-device").is_none());
}
}
impl UiState {
/// Update account-backed own labels and avatar lookup without changing device identity.
pub fn apply_central_profile(
&mut self,
device: &str,
user: crate::net::account::AccountSummary,
) {
self.user_names
.insert(device.to_owned(), user.display_name.clone());
self.member_profiles.insert(
device.to_owned(),
(
user.user_id.clone(),
user.avatar_url
.clone()
.unwrap_or_else(|| format!("/v1/avatars/default-v2/{}", user.user_id)),
),
);
self.central_account = Some(user);
}
}
#[cfg(test)]
mod refreshed_profile_tests {
#[test]
fn website_and_desktop_profile_results_update_own_ui_name_and_avatar() {
let mut state = super::UiState::default();
let mut user = crate::net::account::AccountSummary {
user_id: "account".into(),
handle: "handle".into(),
display_name: "Old Name".into(),
avatar_url: Some("/v1/avatars/old".into()),
profile_complete: false,
};
state.apply_central_profile("device", user.clone());
user.display_name = "Fresh Central Name".into();
user.avatar_url = Some("/v1/avatars/fresh".into());
state.apply_central_profile("device", user);
assert_eq!(state.nick_for("device"), "Fresh Central Name");
assert_eq!(
state.avatar_path_for("device", "device").as_deref(),
Some("/v1/avatars/fresh")
);
assert_eq!(state.member_profiles["device"].0, "account");
state.central_account = None;
assert!(state.avatar_path_for("device", "device").is_none());
}
}
impl UiState {
/// Apply signed gateway metadata without changing any channel/device subscription.
pub fn apply_member_profile(&mut self, profile: crate::net::wire::ProfileUpdated) {
for (device, (account, avatar)) in &mut self.member_profiles {
if account == &profile.account_id {
self.user_names
.insert(device.clone(), profile.nickname.clone());
*avatar = profile.avatar_url.clone();
}
}
self.user_names
.insert(profile.user_id.clone(), profile.nickname.clone());
self.member_profiles.insert(
profile.user_id,
(profile.account_id.clone(), profile.avatar_url.clone()),
);
if let Some(own) = self.central_account.as_mut()
&& own.user_id == profile.account_id
{
own.display_name = profile.nickname;
own.avatar_url = Some(profile.avatar_url);
}
}
}
#[cfg(test)]
mod live_profile_tests {
#[test]
fn signed_profile_updates_existing_chat_voice_devices_without_duplicates() {
let mut state = super::UiState::default();
state.channels.push(super::Channel {
id: "general".into(),
name: "General".into(),
kind: "text".into(),
guild_id: None,
members: vec!["device-a".into(), "device-b".into()],
});
for device in ["device-a", "device-b"] {
state
.member_profiles
.insert(device.into(), ("account".into(), "/v1/avatars/old".into()));
state.user_names.insert(device.into(), "Old Name".into());
}
let before = state.channels[0].members.clone();
for device in ["device-a", "device-b"] {
state.apply_member_profile(crate::net::wire::ProfileUpdated {
user_id: device.into(),
account_id: "account".into(),
nickname: "New Name".into(),
avatar_url: "/v1/avatars/new".into(),
issued_at: 100,
});
}
assert_eq!(state.channels[0].members, before);
assert_eq!(state.account_members(&state.channels[0].members).len(), 1);
assert_eq!(state.nick_for("device-a"), "New Name");
assert_eq!(state.nick_for("device-b"), "New Name");
assert_eq!(state.member_profiles["device-a"].1, "/v1/avatars/new");
}
}

View file

@ -6,6 +6,8 @@ pub struct Channel {
pub name: String,
pub kind: String,
pub guild_id: Option<String>,
pub parent_id: Option<String>,
pub position: i32,
pub members: Vec<String>,
}

View file

@ -44,6 +44,7 @@ pub enum TrustPromptKind {
}
pub struct UiState {
pub central_account: Option<crate::net::account::AccountSummary>,
pub appearance: crate::ui::appearance::AppearancePreferences,
pub conn: ConnState,
pub connect_input: String,
@ -52,6 +53,7 @@ pub struct UiState {
pub status_msg: Option<crate::ui::i18n::Message>,
pub trust_prompt: Option<TrustPrompt>,
pub forum: crate::ui::forum::ForumState,
pub channels: Vec<super::Channel>,
pub active_channel: Option<String>,
pub messages: HashMap<String, Vec<super::ChatMessage>>,
@ -69,6 +71,7 @@ pub struct UiState {
pub voice: VoiceUiState,
pub voice_joined_at: Option<Instant>,
pub member_profiles: HashMap<String, (String, String)>,
pub user_names: HashMap<String, String>,
pub rtt_ms: Option<u32>,
@ -90,6 +93,10 @@ pub struct UiState {
/// Persisted output device id; empty is the system default.
pub output_device_id: String,
pub output_volume: f32,
pub noise_suppress: bool,
pub mic_test_running: bool,
pub mic_test_level: f32,
pub mic_test_error: Option<String>,
pub sounds: vnox_client::audio::sounds::SoundSettings,
/// Devices behind the picker positions, as of the last enumeration.
pub device_lists: vnox_client::audio::DeviceLists,
@ -97,8 +104,15 @@ pub struct UiState {
pub vad_mode_chosen: bool,
pub auto_reconnect: bool,
pub connection: crate::ui::connection::Preferences,
pub private_mode: bool,
pub node_admin: bool,
pub node_settings_supported: bool,
pub channel_structure_supported: bool,
pub server_settings: crate::ui::server_settings::ServerSettingsState,
pub collapsed_categories: std::collections::HashSet<String>,
pub channel_admin: crate::ui::channel_admin::AdminState,
pub guilds: Vec<super::GuildState>,
pub active_guild_id: Option<String>,

View file

@ -44,6 +44,20 @@ impl UiState {
true
}
/// Leaving also cancels a join waiting on an asynchronous profile refresh.
pub fn take_voice_leave_targets(&mut self) -> Vec<String> {
let mut targets = Vec::new();
for id in [self.voice_target.take(), self.pending_voice_join.take()]
.into_iter()
.flatten()
{
if !targets.contains(&id) {
targets.push(id);
}
}
targets
}
/// The server refused or lost a pending join: stop showing "joining". The current session
/// is left untouched.
pub fn cancel_pending_voice_join(&mut self) {
@ -55,6 +69,25 @@ impl UiState {
mod tests {
use super::*;
#[test]
fn leaving_cancels_pending_room_and_current_room_without_duplicate_requests() {
let mut ui = UiState {
voice_target: Some("current".into()),
pending_voice_join: Some("waiting-for-profile".into()),
..Default::default()
};
assert_eq!(
ui.take_voice_leave_targets(),
vec!["current", "waiting-for-profile"]
);
assert!(ui.voice_target.is_none());
assert!(ui.pending_voice_join.is_none());
ui.voice_target = Some("same".into());
ui.pending_voice_join = Some("same".into());
assert_eq!(ui.take_voice_leave_targets(), vec!["same"]);
assert!(ui.take_voice_leave_targets().is_empty());
}
fn connected() -> UiState {
UiState {
conn: ConnState::Connected {

67
src/ui/timestamps.rs Normal file
View file

@ -0,0 +1,67 @@
//! Message timestamps are milliseconds since Unix epoch, displayed in the local timezone.
use chrono::{DateTime, TimeZone};
pub fn format_at<T: TimeZone>(timestamp: i64, now: &DateTime<T>) -> String
where
T::Offset: std::fmt::Display,
{
let Some(message) = now.timezone().timestamp_millis_opt(timestamp).single() else {
return String::new();
};
let pattern = if message.date_naive() == now.date_naive() {
"%H:%M"
} else {
"%d.%m.%Y %H:%M"
};
message.format(pattern).to_string()
}
pub fn same_day_at<T: TimeZone>(first: i64, second: i64, zone: &T) -> bool {
match (
zone.timestamp_millis_opt(first).single(),
zone.timestamp_millis_opt(second).single(),
) {
(Some(first), Some(second)) => first.date_naive() == second.date_naive(),
_ => false,
}
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::FixedOffset;
fn date(value: &str) -> DateTime<FixedOffset> {
DateTime::parse_from_rfc3339(value).unwrap()
}
#[test]
fn today_is_short_and_older_messages_include_date() {
let now = date("2026-11-01T15:00:00+01:00");
assert_eq!(
format_at(date("2026-11-01T09:05:00+01:00").timestamp_millis(), &now),
"09:05"
);
assert_eq!(
format_at(date("2026-10-31T09:05:00+01:00").timestamp_millis(), &now),
"31.10.2026 09:05"
);
}
#[test]
fn local_timezone_controls_the_day_and_midnight_breaks_grouping() {
let now = date("2026-11-01T00:10:00+02:00");
let today = date("2026-10-31T22:05:00Z").timestamp_millis();
let yesterday = date("2026-10-31T21:59:00Z").timestamp_millis();
assert_eq!(format_at(today, &now), "00:05");
assert_eq!(format_at(yesterday, &now), "31.10.2026 23:59");
assert!(!same_day_at(yesterday, today, &now.timezone()));
assert!(same_day_at(today, now.timestamp_millis(), &now.timezone()));
}
#[test]
fn malformed_timestamp_does_not_panic_or_invent_a_time() {
let now = date("2026-11-01T15:00:00+01:00");
assert_eq!(format_at(i64::MIN, &now), "");
assert_eq!(format_at(i64::MAX, &now), "");
}
}

View file

@ -8,7 +8,12 @@ use crate::ui::state::{ChatMessage, ConnState, UiState, VoiceUiState};
use crate::AppState;
pub fn process_net_events(state: &mut AppState) {
crate::ui::forum::tick(&mut state.ui);
crate::ui::channel_admin::tick(&mut state.ui);
crate::ui::server_settings::tick(&mut state.ui);
while let Some(event) = state.net.try_recv() {
crate::ui::channel_admin::receive(&mut state.ui, &event);
crate::ui::server_settings::receive(&mut state.ui, &event);
if let Some(sound) = crate::ui::sounds::sound_for_event(
&state.ui,
&state.identity.pubkey_hex,
@ -17,7 +22,15 @@ pub fn process_net_events(state: &mut AppState) {
) {
crate::ui::sounds::play(state, sound);
}
crate::ui::forum::observe(&mut state.ui, &state.net, &event);
match event {
NetEvent::ForumResult(result) => crate::ui::forum::result(&mut state.ui, result),
NetEvent::ForumChanged(event) => crate::ui::forum::changed(&mut state.ui, event),
NetEvent::NodeSettingsResult{..} => {},
NetEvent::AccountRequired => {
state.ui.connection.authentication_required = true;
}
NetEvent::AttachmentResult(result) => crate::ui::chat_media::receive(result),
NetEvent::VoiceRevoked { channel_id } => {
if state.voice_channel.as_deref() == Some(channel_id.as_str())
|| state.ui.voice_target.as_deref() == Some(channel_id.as_str())
@ -52,13 +65,22 @@ pub fn process_net_events(state: &mut AppState) {
node_name,
restored,
private_mode,
node_admin,
node_settings,
channel_structure,
forums,
} => {
crate::ui::connection::connected(state);
state.connection_generation = state.connection_generation.wrapping_add(1);
state.ui.conn = ConnState::Connected {
session_id,
node_name: node_name.clone(),
};
state.ui.private_mode = private_mode;
state.ui.node_admin = node_admin;
state.ui.node_settings_supported = node_settings;
state.ui.channel_structure_supported = channel_structure;
state.ui.forum.supported = forums;
if restored {
state.ui.status_msg = Some("Reconnected".into());
let text_channel = state.ui.active_channel.clone();
@ -139,6 +161,7 @@ pub fn process_net_events(state: &mut AppState) {
state.ui.channels.clear();
state.ui.active_channel = None;
state.ui.user_names.clear();
state.ui.member_profiles.clear();
state.ui.rtt_ms = None;
state.ui.status_msg = if state.ui.trust_prompt.is_some() {
None
@ -316,7 +339,7 @@ pub fn process_net_events(state: &mut AppState) {
log_audio_stats(state);
if let Some(pipeline) = state.audio.as_ref() {
pipeline.sync_controls(vnox_client::audio::AudioSync {
mic_enabled: state.ui.mic_enabled && !state.ui.deafen,
mic_enabled: state.ui.mic_enabled && !state.ui.deafen && !state.ui.mic_test_running,
vad_mode: state.ui.vad_mode,
vad_threshold: 15.0,
input_volume: 100.0,
@ -329,7 +352,7 @@ pub fn process_net_events(state: &mut AppState) {
jitter_size: 1,
adaptive_buffer: true,
voice_bitrate_kbps: state.ui.voice_bitrate,
noise_suppress: false,
noise_suppress: state.ui.noise_suppress,
});
state.ui.local_speaking = pipeline.local_speaking();
state.ui.remote_speaking = pipeline.remote_speaking(500);
@ -344,8 +367,10 @@ pub fn process_net_events(state: &mut AppState) {
fn process_net_event(ui: &mut UiState, net: &NetHandle, event: NetEvent) {
match &event {
NetEvent::ChannelState { .. }
NetEvent::ProfileUpdated(_)
| NetEvent::ChannelState { .. }
| NetEvent::ChannelCreated { .. }
| NetEvent::ChannelEdited { .. }
| NetEvent::ChannelDeleted { .. }
| NetEvent::ChannelListEvent { .. }
| NetEvent::ChatMessage { .. }
@ -353,6 +378,7 @@ fn process_net_event(ui: &mut UiState, net: &NetHandle, event: NetEvent) {
| NetEvent::UserJoin { .. }
| NetEvent::UserLeave { .. }
| NetEvent::Error { .. }
| NetEvent::ProfileWarning { .. }
| NetEvent::ReactionAdded { .. }
| NetEvent::ReactionRemoved { .. }
| NetEvent::MessageEdited { .. }
@ -391,9 +417,14 @@ fn process_net_event(ui: &mut UiState, net: &NetHandle, event: NetEvent) {
| NetEvent::PresenceUpdated { .. } => status_handle(ui, net, event),
NetEvent::VoiceRevoked { .. }
| NetEvent::AttachmentResult(_)
| NetEvent::MediaEvent(_)
| NetEvent::WebhookResult(_)
| NetEvent::WebhookList(_)
| NetEvent::ForumResult(_)
| NetEvent::ForumChanged(_)
| NetEvent::AccountRequired
| NetEvent::NodeSettingsResult{..}
| NetEvent::WebhookError(_) => unreachable!("handled before generic UI dispatch"),
NetEvent::Connected { .. }
| NetEvent::Disconnected { .. }
@ -457,25 +488,45 @@ fn parse_hex_color(hex: &str) -> Option<String> {
Some(hex.to_string())
}
/// Empty ChannelState is also the create acknowledgement, not permission to join/capture.
fn channel_state_confirms_join(ui: &UiState, id: &str, kind: &str, has_members: bool) -> bool {
if kind == "voice" {
ui.pending_voice_join.as_deref() == Some(id) || ui.voice_target.as_deref() == Some(id)
} else {
has_members
}
}
fn chat_handle(ui: &mut UiState, net: &NetHandle, event: NetEvent) {
match event {
NetEvent::ProfileUpdated(profile) => {
ui.apply_member_profile(profile);
}
NetEvent::ChannelState {
channel_id,
channel_name,
kind,
members,
guild_id,
guild_id, parent_id, position,
..
} => {
let joined = channel_state_confirms_join(ui, &channel_id, &kind, !members.is_empty());
let mems: Vec<String> = members
.iter()
.map(|m| {
ui.user_names.insert(m.user_id.clone(), m.nickname.clone());
m.nickname.clone()
ui.member_profiles.insert(
m.user_id.clone(),
(m.account_id.clone(), m.avatar_url.clone()),
);
m.user_id.clone()
})
.collect();
if let Some(ch) = ui.channels.iter_mut().find(|c| c.id == channel_id) {
ch.members = mems;
ch.name = channel_name.clone();
ch.parent_id = parent_id.clone();
ch.position = position;
if guild_id.is_some() {
ch.guild_id = guild_id.clone();
}
@ -485,10 +536,11 @@ fn chat_handle(ui: &mut UiState, net: &NetHandle, event: NetEvent) {
name: channel_name,
kind: kind.clone(),
guild_id: guild_id.clone(),
parent_id, position,
members: mems,
});
}
if kind == "voice" {
if kind == "voice" && joined {
ui.voice_target = Some(channel_id.clone());
if ui.pending_voice_join.as_deref() == Some(channel_id.as_str()) {
ui.pending_voice_join = None;
@ -497,35 +549,55 @@ fn chat_handle(ui: &mut UiState, net: &NetHandle, event: NetEvent) {
if matches!(ui.voice, VoiceUiState::Error(_)) {
ui.voice = VoiceUiState::Off;
}
} else if ui.active_channel.is_none() && ui.active_dm_id.is_none() {
} else if kind != "voice"
&& joined
&& ui.active_channel.is_none()
&& ui.active_dm_id.is_none()
{
ui.select_text_channel(channel_id.clone());
}
let net = net.clone();
let ch_id = channel_id;
tokio::spawn(async move {
net.send(NetCommand::ReadReceipt {
channel_id: ch_id,
last_read_message_id: uuid::Uuid::new_v4().to_string(),
})
.await;
});
if joined {
let net = net.clone();
let ch_id = channel_id;
tokio::spawn(async move {
net.send(NetCommand::ReadReceipt {
channel_id: ch_id,
last_read_message_id: uuid::Uuid::new_v4().to_string(),
})
.await;
});
}
}
NetEvent::ChannelCreated {
channel_id,
channel_name,
kind,
guild_id,
guild_id, parent_id, position,
} => {
if !ui.channels.iter().any(|c| c.id == channel_id) {
ui.channels.push(crate::ui::state::Channel {
id: channel_id,
name: channel_name,
kind,
guild_id,
guild_id, parent_id, position,
members: Vec::new(),
});
}
}
NetEvent::ChannelEdited {
channel_id,
channel_name, parent_id, position,
} => {
if let Some(channel) = ui
.channels
.iter_mut()
.find(|channel| channel.id == channel_id)
{
channel.name = channel_name;
if let Some(parent) = parent_id { channel.parent_id = (!parent.is_empty()).then_some(parent); }
if let Some(position) = position { channel.position = position; }
}
}
NetEvent::ChannelDeleted { channel_id } => {
ui.channels.retain(|c| c.id != channel_id);
if ui.active_channel.as_deref() == Some(&channel_id) {
@ -555,6 +627,7 @@ fn chat_handle(ui: &mut UiState, net: &NetHandle, event: NetEvent) {
name: c.channel_name,
kind: c.kind,
guild_id: c.guild_id,
parent_id: c.parent_id, position: c.position,
members,
}
})
@ -579,13 +652,16 @@ fn chat_handle(ui: &mut UiState, net: &NetHandle, event: NetEvent) {
channel_id,
user_id,
nickname,
..
account_id,
avatar_url,
} => {
ui.user_names.insert(user_id, nickname.clone());
ui.member_profiles
.insert(user_id.clone(), (account_id, avatar_url));
ui.user_names.insert(user_id.clone(), nickname.clone());
if let Some(ch) = ui.channels.iter_mut().find(|c| c.id == channel_id)
&& !ch.members.contains(&nickname)
&& !ch.members.contains(&user_id)
{
ch.members.push(nickname);
ch.members.push(user_id);
}
}
NetEvent::UserLeave {
@ -593,10 +669,7 @@ fn chat_handle(ui: &mut UiState, net: &NetHandle, event: NetEvent) {
user_id,
} => {
if let Some(ch) = ui.channels.iter_mut().find(|c| c.id == channel_id) {
let nickname = ui.user_names.remove(&user_id);
ch.members.retain(|m| {
m != &user_id && nickname.as_deref().map(|n| m != n).unwrap_or(true)
});
ch.members.retain(|m| m != &user_id);
}
}
NetEvent::DmStart {
@ -651,6 +724,20 @@ fn chat_handle(ui: &mut UiState, net: &NetHandle, event: NetEvent) {
.insert(channel_id, messages.into_iter().map(into_msg).collect());
ui.scroll_bottom = true;
}
NetEvent::ProfileWarning {
message,
rejected_join,
} => {
// A failed background refresh still sends the valid queued join using the
// last verified profile. Cancel only a join this warning explicitly rejected.
if rejected_join
.as_deref()
.is_some_and(|channel| ui.pending_voice_join.as_deref() == Some(channel))
{
ui.cancel_pending_voice_join();
}
ui.status_msg = Some(crate::ui::i18n::text(&message).into());
}
NetEvent::Error { message, .. } => {
ui.cancel_pending_voice_join();
if message.starts_with("media:") {
@ -916,6 +1003,13 @@ pub fn pipeline_config(channel_id: &str, state: &AppState) -> PipelineConfig {
}
pub fn start_voice(state: &mut AppState, channel_id: &str) {
if state
.audio_shutdown
.as_ref()
.is_some_and(|workers| workers.load(std::sync::atomic::Ordering::Acquire) != 0)
{
return;
}
let cfg = pipeline_config(channel_id, state);
if matches!(state.ui.voice, VoiceUiState::Error(_))
&& state.last_pipeline_config.as_ref() == Some(&cfg)
@ -928,7 +1022,11 @@ pub fn start_voice(state: &mut AppState, channel_id: &str) {
{
return;
}
state.audio = None;
if let Some(audio) = state.audio.take() {
state.audio_shutdown = Some(audio.shutdown_signal());
state.voice_channel = None;
return;
}
match vnox_client::audio::start(cfg.clone()) {
Ok(pipeline) => {
tracing::info!("voice active on channel {channel_id}");
@ -962,7 +1060,9 @@ pub fn start_voice(state: &mut AppState, channel_id: &str) {
}
pub fn stop_voice(state: &mut AppState) {
state.audio = None;
if let Some(audio) = state.audio.take() {
state.audio_shutdown = Some(audio.shutdown_signal());
}
state.voice_channel = None;
state.last_pipeline_config = None;
state.ui.voice = VoiceUiState::Off;
@ -970,6 +1070,16 @@ pub fn stop_voice(state: &mut AppState) {
}
pub fn sync_voice_audio(state: &mut AppState) {
if state
.audio_shutdown
.as_ref()
.is_some_and(|workers| workers.load(std::sync::atomic::Ordering::Acquire) != 0)
{
return;
}
if state.microphone_test.is_some() {
return;
}
if !matches!(state.ui.conn, ConnState::Connected { .. }) {
stop_voice(state);
return;
@ -1138,3 +1248,154 @@ mod reaction_tests {
assert!(matches!(command("😀"), NetCommand::ReactionAdd { .. }));
}
}
#[cfg(test)]
mod channel_creation_regressions {
use super::*;
fn state_event(id: &str, kind: &str) -> NetEvent {
NetEvent::ChannelState {
channel_id: id.into(),
channel_name: "Created".into(),
kind: kind.into(),
members: vec![],
voice_endpoint: "127.0.0.1:7601".into(),
guild_id: None,
}
}
#[tokio::test]
async fn create_and_late_cancelled_create_never_join_select_or_request_receipts() {
let identity = crate::identity::generate("fixture");
let trust = crate::net::trust::TrustStore::load(
std::env::temp_dir().join(format!("vnox-admin-fixture-{}.json", uuid::Uuid::new_v4())),
);
let net = crate::net::spawn_with_trust(identity, trust);
let mut ui = UiState {
voice_target: Some("existing-room".into()),
voice: VoiceUiState::Active {
channel: "existing-room".into(),
},
..Default::default()
};
assert!(!channel_state_confirms_join(
&ui, "new-room", "voice", false
));
chat_handle(&mut ui, &net, state_event("new-room", "voice"));
assert_eq!(ui.voice_target.as_deref(), Some("existing-room"));
assert_eq!(
ui.voice,
VoiceUiState::Active {
channel: "existing-room".into()
}
);
assert!(ui.pending_voice_join.is_none());
assert!(ui.active_channel.is_none());
assert!(!channel_state_confirms_join(&ui, "new-text", "text", false));
chat_handle(&mut ui, &net, state_event("new-text", "text"));
assert!(ui.active_channel.is_none());
// A cancelled create has no active dialog/pending join when its late ACK arrives.
ui.voice_target = None;
ui.voice = VoiceUiState::Off;
chat_handle(&mut ui, &net, state_event("late-room", "voice"));
assert!(ui.voice_target.is_none());
assert_eq!(ui.voice, VoiceUiState::Off);
// An explicit click on Join remains sufficient, including an empty fixture snapshot.
assert!(ui.request_voice_join("new-room"));
assert!(channel_state_confirms_join(&ui, "new-room", "voice", false));
chat_handle(&mut ui, &net, state_event("new-room", "voice"));
assert_eq!(ui.voice_target.as_deref(), Some("new-room"));
assert!(ui.pending_voice_join.is_none());
}
}
#[cfg(test)]
mod profile_warning_regressions {
use super::*;
fn voice_ack(channel: &str) -> NetEvent {
NetEvent::ChannelState {
channel_id: channel.into(),
channel_name: "Voice room".into(),
kind: "voice".into(),
members: vec![],
voice_endpoint: "127.0.0.1:7601".into(),
guild_id: None,
}
}
#[tokio::test]
async fn profile_outage_warning_preserves_pending_voice_until_valid_ack_but_server_denial_cancels()
{
let identity = crate::identity::generate("profile-warning-fixture");
let trust = crate::net::trust::TrustStore::load(std::env::temp_dir().join(format!(
"vnox-profile-warning-{}.json",
uuid::Uuid::new_v4()
)));
let net = crate::net::spawn_with_trust(identity, trust);
let mut ui = UiState::default();
assert!(ui.request_voice_join("voice"));
process_net_event(
&mut ui,
&net,
NetEvent::ProfileWarning {
message: "Central profile refresh failed; using last verified profile".into(),
rejected_join: None,
},
);
assert_eq!(ui.pending_voice_join.as_deref(), Some("voice"));
assert!(channel_state_confirms_join(&ui, "voice", "voice", false));
process_net_event(&mut ui, &net, voice_ack("voice"));
assert_eq!(ui.voice_target.as_deref(), Some("voice"));
assert!(ui.pending_voice_join.is_none());
ui.voice_target = None;
assert!(ui.request_voice_join("denied-room"));
process_net_event(
&mut ui,
&net,
NetEvent::Error {
code: 1,
message: "VOICE_SPEAK permission required".into(),
},
);
assert!(ui.pending_voice_join.is_none());
assert!(!channel_state_confirms_join(
&ui,
"denied-room",
"voice",
false
));
process_net_event(&mut ui, &net, voice_ack("denied-room"));
assert!(ui.voice_target.is_none());
}
#[tokio::test]
async fn full_profile_queue_warning_cancels_only_the_explicitly_rejected_join() {
let identity = crate::identity::generate("profile-queue-fixture");
let trust = crate::net::trust::TrustStore::load(
std::env::temp_dir().join(format!("vnox-profile-queue-{}.json", uuid::Uuid::new_v4())),
);
let net = crate::net::spawn_with_trust(identity, trust);
let mut ui = UiState::default();
assert!(ui.request_voice_join("accepted-room"));
for rejected_join in [None, Some("another-room".into())] {
process_net_event(
&mut ui,
&net,
NetEvent::ProfileWarning {
message: "Too many pending profile actions; retry shortly".into(),
rejected_join,
},
);
assert_eq!(ui.pending_voice_join.as_deref(), Some("accepted-room"));
}
process_net_event(
&mut ui,
&net,
NetEvent::ProfileWarning {
message: "Too many pending profile actions; retry shortly".into(),
rejected_join: Some("accepted-room".into()),
},
);
assert!(ui.pending_voice_join.is_none());
}
}

View file

@ -23,8 +23,8 @@ fn snapshot_scale() -> u32 {
fn render(window: &MainWindow, surface: &MinimalSoftwareWindow, name: &str) {
window.window().request_redraw();
let scale = snapshot_scale();
let (width, height) = (1280 * scale, 800 * scale);
let size = window.window().size();
let (width, height) = (size.width, size.height);
let mut pixels = SharedPixelBuffer::<Rgb8Pixel>::new(width, height);
assert!(surface.draw_if_needed(|renderer| {
renderer.render(pixels.make_mut_slice(), width as usize);
@ -81,14 +81,14 @@ fn native_shell_keeps_drafts_settings_and_models_between_ticks() {
name: "общий".into(),
kind: "text".into(),
guild_id: None,
members: vec!["Локи".into()],
members: vec![identity.pubkey_hex.clone()],
},
ui::state::Channel {
id: "lounge".into(),
name: "Общая".into(),
kind: "voice".into(),
guild_id: None,
members: vec!["Локи".into()],
members: vec![identity.pubkey_hex.clone()],
},
];
ui.user_names
@ -102,6 +102,9 @@ fn native_shell_keeps_drafts_settings_and_models_between_ticks() {
reply_to: None,
}]);
let state = Rc::new(RefCell::new(AppState {
audio_shutdown: None,
microphone_test: None,
device_refresh: Default::default(),
webhooks: None,
connection_generation: 0,
identity,
@ -112,7 +115,9 @@ fn native_shell_keeps_drafts_settings_and_models_between_ticks() {
last_pipeline_config: None,
}));
let window = MainWindow::new().unwrap();
window.set_account_authenticated(true);
wire_signals(&window, &state);
ui::chat_media::wire(&window, &state);
let sync = || {
let s = state.borrow();
ui::bridge::sync_ui(
@ -140,6 +145,27 @@ fn native_shell_keeps_drafts_settings_and_models_between_ticks() {
});
surface.set_size(PhysicalSize::new(1280 * scale, 800 * scale));
render(&window, &surface, "native-chat");
// Render the actual native image row and an explicit composer preview together.
let photo_bytes: Vec<u8> = (0..160 * 100)
.flat_map(|pixel| [(pixel % 160) as u8, 90, (pixel / 160) as u8, 255])
.collect();
let chat_photo =
slint::Image::from_rgba8(SharedPixelBuffer::clone_from_slice(&photo_bytes, 160, 100));
let original_row = window.get_messages().row_data(0).unwrap();
let mut media_row = original_row.clone();
media_row.media_image = chat_photo.clone();
media_row.media_ready = true;
media_row.media_ratio = 1.6;
window.get_messages().set_row_data(0, media_row);
window.set_pending_image(chat_photo);
window.set_has_pending_image(true);
window.set_image_status("Image ready. Send it to this channel or cancel.".into());
render(&window, &surface, "native-chat-image-preview");
window.invoke_cancel_image();
assert!(!window.get_has_pending_image());
assert!(window.get_image_status().is_empty());
window.get_messages().set_row_data(0, original_row);
sync();
// Hovering a message reveals the action bar with reply, edit, delete and reactions.
window.window().dispatch_event(WindowEvent::PointerMoved {
@ -281,7 +307,7 @@ fn native_shell_keeps_drafts_settings_and_models_between_ticks() {
window.invoke_open_settings();
sync();
window.set_active_tab("appearance".into());
for mode in ["light", "dark", "black"] {
for mode in ui::appearance::BUILTIN_THEME_IDS {
window.invoke_theme_selected(mode.into());
assert_eq!(state.borrow().ui.appearance.mode, mode);
let expected = ui::appearance::ThemeSpec::builtin(mode).colors[0].color();
@ -327,7 +353,7 @@ fn native_shell_keeps_drafts_settings_and_models_between_ticks() {
"invalid CSS must leave the palette intact"
);
window.invoke_reset_theme();
assert_eq!(state.borrow().ui.appearance.mode, "dark");
assert_eq!(state.borrow().ui.appearance.mode, "black");
window.set_active_tab("identity".into());
let rgba = (0..320 * 240)
.flat_map(|i| {
@ -407,16 +433,27 @@ fn native_shell_keeps_drafts_settings_and_models_between_ticks() {
state.ui.voice = ui::state::VoiceUiState::Active {
channel: "lounge".into(),
};
state.ui.local_speaking = true;
}
window.invoke_show_voice_view();
sync();
assert!(window.get_show_voice());
assert!(window.get_voice_connected());
assert!(window.get_local_speaking());
let own_voice = window.get_voice_members().row_data(0).unwrap();
assert!(own_voice.is_own);
assert!(
own_voice.speaking,
"local speaking must highlight our own voice card"
);
render(&window, &surface, "native-voice");
// Every screen must render with all built-in themes and the custom one, without leftovers
// of the default palette (grey patches, wrong backgrounds). Snapshots are reviewed by eye.
let forest = include_str!("../examples/themes/forest.css");
for mode in ["light", "dark", "black", "custom"] {
for mode in ui::appearance::BUILTIN_THEME_IDS
.into_iter()
.chain(["custom"])
{
window.invoke_theme_selected(mode.into());
if mode == "custom" {
window.set_theme_css(forest.into());
@ -451,5 +488,96 @@ fn native_shell_keeps_drafts_settings_and_models_between_ticks() {
sync();
window.set_address_input("127.0.0.1:7600".into());
render(&window, &surface, "native-connect");
window.set_settings_open(true);
window.set_active_tab("appearance".into());
for mode in ["black", "light"] {
window.invoke_theme_selected(mode.into());
for width in [1024, 1280, 1920] {
surface.set_size(PhysicalSize::new(width * scale, 800 * scale));
render(&window, &surface, &format!("theme-grid-{mode}-{width}"));
}
}
// Synthetic node administrator: no real Central account or gateway is used.
window.set_settings_open(false);
surface.set_size(PhysicalSize::new(1280 * scale, 800 * scale));
{
let mut s = state.borrow_mut();
s.ui.conn = ConnState::Connected {
session_id: "admin-fixture".into(),
node_name: "QA node".into(),
};
s.ui.node_admin = true;
s.ui.central_account = Some(net::account::AccountSummary {
user_id: "f10ca6c3-296a-40f6-a420-8a097d401e26".into(),
handle: "qa_fixture".into(),
display_name: "QA fixture".into(),
avatar_url: Some("fixture-only-no-network".into()),
profile_complete: false,
});
s.ui.active_guild_id = None;
s.ui.browsing_dms = false;
}
sync();
assert!(window.get_node_admin());
render(&window, &surface, "node-admin-sidebar");
click(&window, 307.0, 163.0);
sync();
assert!(
window.get_channel_admin_open(),
"voice plus must open on the first click"
);
assert_eq!(window.get_channel_admin_kind(), "voice");
window.invoke_channel_admin_name_edited("QA voice room".into());
sync();
render(&window, &surface, "node-admin-create-voice");
window.invoke_channel_admin_submit();
sync();
assert!(window.get_channel_admin_busy());
{
let mut s = state.borrow_mut();
ui::channel_admin::receive(
&mut s.ui,
&net::NetEvent::Error {
code: 1,
message: "QA permission denied".into(),
},
);
}
sync();
assert!(!window.get_channel_admin_busy());
assert_eq!(window.get_channel_admin_name(), "QA voice room");
assert!(!window.get_channel_admin_error().is_empty());
render(&window, &surface, "node-admin-error");
window.invoke_channel_admin_cancel();
sync();
render(&window, &surface, "node-admin-before-rename");
click(&window, 263.0, 117.0);
sync();
assert!(window.get_channel_admin_open());
render(&window, &surface, "node-admin-rename");
window.invoke_channel_admin_cancel();
sync();
render(&window, &surface, "node-admin-before-delete");
click(&window, 299.0, 117.0);
sync();
assert!(window.get_channel_admin_open());
assert!(
!window.get_channel_admin_busy(),
"opening delete must only ask for confirmation"
);
render(&window, &surface, "node-admin-delete-confirm");
window.invoke_channel_admin_cancel();
sync();
render(&window, &surface, "node-admin-before-text");
click(&window, 307.0, 85.0);
sync();
assert!(window.get_channel_admin_open());
assert_eq!(window.get_channel_admin_kind(), "text");
render(&window, &surface, "node-admin-create-text");
state.borrow_mut().ui.node_admin = false;
ui::channel_admin::tick(&mut state.borrow_mut().ui);
sync();
assert!(!window.get_node_admin());
assert!(!window.get_channel_admin_open());
window.hide().unwrap();
}