feat(client): add RU/EN localization and native capture preview

This commit is contained in:
Loki 2026-10-24 15:04:50 +02:00
parent 8e5ab56611
commit 8460fb28fd
Signed by: boba
GPG key ID: 253067914055423B
43 changed files with 4103 additions and 275 deletions

56
src/bin/screen_probe.rs Normal file
View file

@ -0,0 +1,56 @@
//! Opt-in diagnostic. Never chooses a desktop source without --choose and portal consent.
#[cfg(all(target_os = "linux", feature = "screen-capture"))]
#[tokio::main]
async fn main() -> anyhow::Result<()> {
use std::time::{Duration, Instant};
use vnox_client::media::{AudioChoice, CaptureOptions, CaptureSession, audio_sources};
let args: Vec<String> = std::env::args().skip(1).collect();
if args.as_slice() == ["--list-audio"] {
for source in audio_sources().await.map_err(anyhow::Error::msg)? {
println!("{:?}\t{}\t{}", source.kind, source.serial, source.name);
}
return Ok(());
}
if args.first().map(String::as_str) != Some("--choose") {
println!(
"Usage: cargo run --bin screen_probe -- --list-audio\n cargo run --bin screen_probe -- --choose [--audio-app SERIAL | --audio-system SERIAL]\nChoose explicitly in the portal; this previews for 15 seconds, writes no files and broadcasts nothing."
);
return Ok(());
}
let audio = match args.as_slice() {
[_] => AudioChoice::Disabled,
[_, mode, serial] if mode == "--audio-app" => AudioChoice::Application(serial.parse()?),
[_, mode, serial] if mode == "--audio-system" => AudioChoice::System(serial.parse()?),
_ => anyhow::bail!("Invalid options; choose one explicit audio source or omit audio"),
};
let session = CaptureSession::choose(CaptureOptions {
audio,
..Default::default()
})
.await
.map_err(anyhow::Error::msg)?;
let deadline = Instant::now() + Duration::from_secs(15);
let mut frames = 0u32;
while Instant::now() < deadline {
session.check().map_err(anyhow::Error::msg)?;
if let Some(frame) = session.feed.take_frame() {
frames += 1;
if frames == 1 {
println!(
"First local frame: {}×{} RGBA. Nothing is broadcast.",
frame.width, frame.height
);
}
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
drop(session);
anyhow::ensure!(frames > 0, "No video frames received");
println!("Stopped and revoked local capture after {frames} frames.");
Ok(())
}
#[cfg(not(all(target_os = "linux", feature = "screen-capture")))]
fn main() {
eprintln!("Native screen capture requires Linux and the screen-capture feature.");
}

View file

@ -4,3 +4,5 @@ pub mod identity;
pub mod identity_vault;
pub mod jitter;
pub mod net;
pub mod media;

View file

@ -28,6 +28,7 @@ pub struct AppState {
}
fn main() -> Result<()> {
ui::i18n::initialize();
let filter = EnvFilter::try_from_default_env()
.unwrap_or_else(|_| EnvFilter::new("info,wgpu=warn,wgpu_hal=warn,naga=warn"));
tracing_subscriber::fmt().with_env_filter(filter).init();
@ -67,6 +68,7 @@ fn main() -> Result<()> {
refresh_devices(&window);
wire_signals(&window, &state);
ui::media::wire(&window)?;
let timer = slint::Timer::default();
{
@ -101,6 +103,7 @@ fn load_identity() -> Result<Option<identity::Identity>> {
if let Ok(spec) = appearance.resolve() {
crate::ui::appearance::apply_unlock(&dialog, &spec);
}
ui::i18n::set_language(ui::i18n::current());
let unlocked = Rc::new(RefCell::new(None));
let result = unlocked.clone();
let weak = dialog.as_weak();
@ -111,9 +114,12 @@ fn load_identity() -> Result<Option<identity::Identity>> {
*result.borrow_mut() = Some(identity);
let _ = dialog.hide();
}
Err(_) => {
dialog.set_error("Не удалось открыть профиль. Проверь пароль.".into())
}
Err(_) => dialog.set_error(
crate::ui::i18n::text(
"Could not unlock your profile. Check your passphrase.",
)
.into(),
),
}
}
});
@ -129,7 +135,7 @@ fn refresh_devices(window: &MainWindow) {
let devices = vnox_client::audio::devices::enumerate().unwrap_or_default();
let model = |mut items: Vec<String>| {
if items.is_empty() {
items.push("Default".into());
items.push(crate::ui::i18n::text("Default"));
}
Rc::new(slint::VecModel::from(
items
@ -145,6 +151,7 @@ fn refresh_devices(window: &MainWindow) {
fn wire_signals(window: &MainWindow, state: &Rc<RefCell<AppState>>) {
crate::ui::appearance::wire(window, state, !cfg!(test));
ui::i18n::wire(window, !cfg!(test));
crate::ui::avatar::wire(window, state, !cfg!(test));
{
let state = state.clone();
@ -200,7 +207,10 @@ fn wire_signals(window: &MainWindow, state: &Rc<RefCell<AppState>>) {
s.ui.vad_mode = mode.clamp(0, 2) as usize;
s.ui.output_volume = volume.clamp(0.0, 100.0);
if let Err(error) = crate::ui::preferences::save(&s.ui) {
s.ui.status_msg = Some(format!("Cannot save audio settings: {error}"));
s.ui.status_msg = Some(ui::i18n::Message::with(
"Cannot save audio settings: {error}",
vec![("error", error.to_string())],
));
}
});
}
@ -288,7 +298,7 @@ fn wire_signals(window: &MainWindow, state: &Rc<RefCell<AppState>>) {
let mut s = state.borrow_mut();
s.ui.conn = ConnState::Connecting;
s.ui.connect_input = addr.clone();
s.ui.status_msg = Some("connecting...".into());
s.ui.status_msg = Some("Connecting…".into());
let auto_reconnect = s.ui.auto_reconnect;
let net = s.net.clone();
drop(s);
@ -324,13 +334,13 @@ fn wire_signals(window: &MainWindow, state: &Rc<RefCell<AppState>>) {
}
let mut s = state.borrow_mut();
if !matches!(s.ui.conn, ConnState::Connected { .. }) {
s.ui.status_msg = Some("Нет соединения с сервером. Черновик сохранён.".into());
s.ui.status_msg = Some("Not connected to a server. Your draft has been kept.".into());
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)
{
s.ui.status_msg = Some("Зашифрованные сообщения временно недоступны. Черновик сохранён; сообщение не отправлено.".into());
s.ui.status_msg = Some("Encrypted messaging is temporarily unavailable. Your draft has been kept; the message was not sent.".into());
return;
}
@ -531,12 +541,12 @@ fn wire_signals(window: &MainWindow, state: &Rc<RefCell<AppState>>) {
window.on_set_passphrase(move |pass, confirm| {
let mut s = state.borrow_mut();
if pass != confirm {
s.ui.settings_passphrase_error = Some("Passphrases do not match".to_string());
s.ui.settings_passphrase_error = Some("Passphrases do not match".into());
return;
}
if pass.len() < 8 {
s.ui.settings_passphrase_error =
Some("Passphrase must be at least 8 characters".to_string());
Some("Passphrase must be at least 8 characters".into());
return;
}
s.ui.settings_passphrase_error = None;
@ -544,7 +554,12 @@ fn wire_signals(window: &MainWindow, state: &Rc<RefCell<AppState>>) {
drop(s);
match identity::save(&identity, Some(pass.as_str())) {
Ok(()) => state.borrow_mut().ui.vault_enabled = true,
Err(e) => state.borrow_mut().ui.settings_passphrase_error = Some(format!("{e}")),
Err(e) => {
state.borrow_mut().ui.settings_passphrase_error = Some(ui::i18n::Message::with(
"Could not update profile: {error}",
vec![("error", e.to_string())],
))
}
}
});
}
@ -557,7 +572,12 @@ fn wire_signals(window: &MainWindow, state: &Rc<RefCell<AppState>>) {
drop(s);
match identity::save(&identity, None) {
Ok(()) => state.borrow_mut().ui.vault_enabled = false,
Err(e) => state.borrow_mut().ui.settings_passphrase_error = Some(format!("{e}")),
Err(e) => {
state.borrow_mut().ui.settings_passphrase_error = Some(ui::i18n::Message::with(
"Could not update profile: {error}",
vec![("error", e.to_string())],
))
}
}
});
}
@ -567,7 +587,7 @@ fn wire_signals(window: &MainWindow, state: &Rc<RefCell<AppState>>) {
window.on_export_keyfile(move |pass, confirm| {
let mut s = state.borrow_mut();
if pass != confirm {
s.ui.settings_export_error = Some("Passphrases do not match".to_string());
s.ui.settings_export_error = Some("Passphrases do not match".into());
return;
}
let passphrase = if pass.is_empty() {
@ -585,7 +605,10 @@ fn wire_signals(window: &MainWindow, state: &Rc<RefCell<AppState>>) {
}
Err(e) => {
let mut s = state.borrow_mut();
s.ui.settings_export_error = Some(format!("{e}"));
s.ui.settings_export_error = Some(ui::i18n::Message::with(
"Could not update profile: {error}",
vec![("error", e.to_string())],
));
}
}
});
@ -604,18 +627,22 @@ fn wire_signals(window: &MainWindow, state: &Rc<RefCell<AppState>>) {
match identity::import_keyfile(&input, passphrase) {
Ok(identity) => {
if let Err(e) = identity::save(&identity, None) {
s.ui.settings_import_error = Some(format!("{e}"));
s.ui.settings_import_error = Some(ui::i18n::Message::with(
"Could not update profile: {error}",
vec![("error", e.to_string())],
));
} else {
s.ui.settings_import_error = None;
s.ui.vault_enabled = false;
s.ui.status_msg = Some(
"Профиль импортирован. Перезапусти Vnox, чтобы войти с новыми ключами."
.into(),
);
s.ui.status_msg =
Some("Profile imported. Restart Vnox to use your new keys.".into());
}
}
Err(e) => {
s.ui.settings_import_error = Some(format!("{e}"));
s.ui.settings_import_error = Some(ui::i18n::Message::with(
"Could not update profile: {error}",
vec![("error", e.to_string())],
));
}
}
});

398
src/media/capture.rs Normal file
View file

@ -0,0 +1,398 @@
use super::portal::PortalSession;
use super::{AudioChoice, CaptureOptions, VideoFrame, audio_sources, validate_audio_choice};
use gst::prelude::*;
use gstreamer as gst;
use std::{
os::fd::AsRawFd,
sync::{
Arc, Mutex,
atomic::{AtomicBool, Ordering},
},
time::{Duration, Instant},
};
/// Latest owned preview frame and selected audio level; queues never grow.
#[derive(Clone, Default)]
pub struct CaptureFeed {
video: Arc<Mutex<Option<VideoFrame>>>,
audio: Arc<Mutex<f32>>,
received_audio: Arc<AtomicBool>,
}
impl CaptureFeed {
pub fn take_frame(&self) -> Option<VideoFrame> {
self.video.lock().ok()?.take()
}
pub fn audio_level(&self) -> f32 {
self.audio.lock().map(|v| *v).unwrap_or(0.0)
}
}
/// Live local capture. Dropping it stops both pipelines and revokes portal access.
pub struct CaptureSession {
pipelines: Vec<gst::Pipeline>,
portal: Option<PortalSession>,
pub feed: CaptureFeed,
started: Instant,
expects_audio: bool,
}
pub fn check_backend() -> Result<(), String> {
gst::init().map_err(error)?;
for name in [
"pipewiresrc",
"videoconvert",
"videoscale",
"videorate",
"audioconvert",
"audioresample",
"appsink",
] {
if gst::ElementFactory::find(name).is_none() {
return Err(format!(
"Missing GStreamer plugin: {name}. Install the PipeWire and base plugins."
));
}
}
Ok(())
}
impl CaptureSession {
pub async fn choose(options: CaptureOptions) -> Result<Self, String> {
options.validate()?;
check_backend()?;
if options.audio != AudioChoice::Disabled {
validate_audio_choice(options.audio, &audio_sources().await?)?;
}
let portal = PortalSession::choose().await?;
Self::from_portal(portal, options)
}
fn from_portal(portal: PortalSession, options: CaptureOptions) -> Result<Self, String> {
let feed = CaptureFeed::default();
let mut session = Self {
pipelines: Vec::new(),
portal: Some(portal),
feed,
started: Instant::now(),
expects_audio: options.audio != AudioChoice::Disabled,
};
let portal = session.portal.as_ref().ok_or("Missing portal session")?;
let source = gst::ElementFactory::make("pipewiresrc")
.property("fd", portal.remote.as_raw_fd())
.build()
.map_err(error)?;
if let Some(serial) = portal.serial {
source.set_property("target-object", serial.to_string());
} else {
source.set_property("path", portal.node.to_string());
}
strict_source(&source);
let pipeline = video_pipeline(source, &session.feed, options)?;
session.pipelines.push(pipeline);
if let AudioChoice::Application(serial) | AudioChoice::System(serial) = options.audio {
let source = gst::ElementFactory::make("pipewiresrc")
.property("target-object", serial.to_string())
.build()
.map_err(error)?;
strict_source(&source);
// A monitor stream targets exactly this serial. It must neither move nor
// connect to a default source if that application/device vanishes.
let props = gst::Structure::builder("properties")
.field("stream.capture.sink", true)
.field("stream.monitor", true)
.field("node.dont-reconnect", true)
.field("node.dont-fallback", true)
.field("node.dont-move", true)
.field("media.name", "VNOX selected audio preview")
.build();
source.set_property("stream-properties", props);
session
.pipelines
.push(audio_pipeline(source, &session.feed)?);
}
for pipeline in &session.pipelines {
pipeline.set_state(gst::State::Playing).map_err(error)?;
}
Ok(session)
}
/// Polling drains bus errors and EOS. Callers must stop the session on Err.
pub fn check(&self) -> Result<(), String> {
if self.expects_audio
&& !self.feed.received_audio.load(Ordering::Relaxed)
&& self.started.elapsed() > Duration::from_secs(10)
{
return Err("Selected audio source produced no samples. Capture stopped; no fallback source was enabled.".into());
}
for pipeline in &self.pipelines {
if let Some(bus) = pipeline.bus() {
while let Some(message) = bus.pop() {
match message.view() {
gst::MessageView::Error(e) => {
return Err(format!("Capture stopped: {}", e.error()));
}
gst::MessageView::Eos(..) => {
return Err("Capture source closed. Choose it again to resume.".into());
}
_ => {}
}
}
}
}
Ok(())
}
}
impl Drop for CaptureSession {
fn drop(&mut self) {
for pipeline in &self.pipelines {
let _ = pipeline.set_state(gst::State::Null);
}
// The descriptor remains alive until all pipeline streams have stopped.
drop(self.portal.take());
if let Ok(mut frame) = self.feed.video.lock() {
*frame = None;
}
if let Ok(mut level) = self.feed.audio.lock() {
*level = 0.0;
}
}
}
fn strict_source(source: &gst::Element) {
source.set_property_from_str("on-disconnect", "error");
if source.find_property("dont-reconnect").is_some() {
source.set_property("dont-reconnect", true);
}
}
fn video_pipeline(
source: gst::Element,
feed: &CaptureFeed,
options: CaptureOptions,
) -> Result<gst::Pipeline, String> {
let sink = gstreamer_app::AppSink::builder()
.max_buffers(1)
.drop(true)
.sync(false)
.build();
let latest = feed.video.clone();
sink.set_callbacks(
gstreamer_app::AppSinkCallbacks::builder()
.new_sample(move |sink| {
let sample = sink.pull_sample().map_err(|_| gst::FlowError::Eos)?;
let frame = copy_video(&sample).map_err(|_| gst::FlowError::Error)?;
*latest.lock().map_err(|_| gst::FlowError::Error)? = Some(frame);
Ok(gst::FlowSuccess::Ok)
})
.build(),
);
let convert = gst::ElementFactory::make("videoconvert")
.build()
.map_err(error)?;
let scale = gst::ElementFactory::make("videoscale")
.build()
.map_err(error)?;
let rate = gst::ElementFactory::make("videorate")
.property("drop-only", true)
.build()
.map_err(error)?;
let caps: gst::Caps = format!(
"video/x-raw,format=RGBA,width=[1,{}],height=[1,{}],framerate=[1/1,{}/1]",
options.max_width, options.max_height, options.max_fps
)
.parse()
.map_err(error)?;
let filter = gst::ElementFactory::make("capsfilter")
.property("caps", caps)
.build()
.map_err(error)?;
let pipeline = gst::Pipeline::new();
let elements = [&source, &convert, &scale, &rate, &filter, sink.upcast_ref()];
pipeline.add_many(elements).map_err(error)?;
gst::Element::link_many(elements).map_err(error)?;
Ok(pipeline)
}
fn copy_video(sample: &gst::Sample) -> Result<VideoFrame, String> {
let caps = sample.caps().ok_or("Missing video caps")?;
let info = gstreamer_video::VideoInfo::from_caps(caps).map_err(error)?;
if info.format() != gstreamer_video::VideoFormat::Rgba
|| info.width() > 1920
|| info.height() > 1080
{
return Err("Unbounded or invalid video frame".into());
}
let buffer = sample.buffer().ok_or("Missing video buffer")?;
let frame =
gstreamer_video::VideoFrameRef::from_buffer_ref_readable(buffer, &info).map_err(error)?;
use gstreamer_video::prelude::VideoFrameExt;
let stride = usize::try_from(frame.plane_stride()[0]).map_err(error)?;
let bytes = frame.plane_data(0).map_err(error)?;
let width = info.width() as usize * 4;
let height = info.height() as usize;
if stride < width
|| bytes.len()
< stride
.saturating_mul(height.saturating_sub(1))
.saturating_add(width)
{
return Err("Invalid video stride".into());
}
let mut rgba = Vec::with_capacity(width * height);
for row in 0..height {
rgba.extend_from_slice(&bytes[row * stride..row * stride + width]);
}
let result = VideoFrame {
width: info.width(),
height: info.height(),
rgba,
timestamp_ns: buffer.pts().map(|v| v.nseconds()),
};
result.validate()?;
Ok(result)
}
fn audio_pipeline(source: gst::Element, feed: &CaptureFeed) -> Result<gst::Pipeline, String> {
let sink = gstreamer_app::AppSink::builder()
.max_buffers(2)
.drop(true)
.sync(false)
.build();
let level = feed.audio.clone();
let received = feed.received_audio.clone();
sink.set_callbacks(
gstreamer_app::AppSinkCallbacks::builder()
.new_sample(move |sink| {
let sample = sink.pull_sample().map_err(|_| gst::FlowError::Eos)?;
let map = sample
.buffer()
.ok_or(gst::FlowError::Error)?
.map_readable()
.map_err(|_| gst::FlowError::Error)?;
if map.len() > 48_000 * 8 {
return Err(gst::FlowError::Error);
}
let mut sum = 0.0f64;
let mut count = 0u32;
for bytes in map.as_slice().as_chunks::<4>().0 {
let value = f32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
if value.is_finite() {
sum += f64::from(value) * f64::from(value);
count += 1;
}
}
received.store(true, Ordering::Relaxed);
*level.lock().map_err(|_| gst::FlowError::Error)? = if count == 0 {
0.0
} else {
(sum / f64::from(count)).sqrt().min(1.0) as f32
};
Ok(gst::FlowSuccess::Ok)
})
.build(),
);
let convert = gst::ElementFactory::make("audioconvert")
.build()
.map_err(error)?;
let resample = gst::ElementFactory::make("audioresample")
.build()
.map_err(error)?;
let caps = gst::Caps::builder("audio/x-raw")
.field("format", "F32LE")
.field("rate", 48_000i32)
.field("channels", 2i32)
.field("layout", "interleaved")
.build();
let filter = gst::ElementFactory::make("capsfilter")
.property("caps", caps)
.build()
.map_err(error)?;
let pipeline = gst::Pipeline::new();
let elements = [&source, &convert, &resample, &filter, sink.upcast_ref()];
pipeline.add_many(elements).map_err(error)?;
gst::Element::link_many(elements).map_err(error)?;
Ok(pipeline)
}
fn error(e: impl std::fmt::Display) -> String {
e.to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn silent_unavailable_source_times_out_and_drop_clears_preview() {
let feed = CaptureFeed::default();
*feed.video.lock().expect("frame lock") = Some(VideoFrame {
width: 1,
height: 1,
rgba: vec![1, 2, 3, 255],
timestamp_ns: None,
});
*feed.audio.lock().expect("level lock") = 0.5;
let session = CaptureSession {
pipelines: Vec::new(),
portal: None,
feed: feed.clone(),
started: Instant::now() - Duration::from_secs(11),
expects_audio: true,
};
assert!(
session
.check()
.expect_err("no audio was received")
.contains("no fallback")
);
drop(session);
assert!(feed.take_frame().is_none());
assert_eq!(feed.audio_level(), 0.0);
}
#[test]
fn synthetic_video_and_audio_reach_bounded_owned_sinks() {
gst::init().expect("GStreamer initialization");
let feed = CaptureFeed::default();
let source = gst::ElementFactory::make("videotestsrc")
.property("num-buffers", 3i32)
.build()
.expect("fixture");
let video = video_pipeline(
source,
&feed,
CaptureOptions {
max_width: 64,
max_height: 48,
..Default::default()
},
)
.expect("video pipeline");
let source = gst::ElementFactory::make("audiotestsrc")
.property("num-buffers", 3i32)
.build()
.expect("fixture");
let audio = audio_pipeline(source, &feed).expect("audio pipeline");
for pipeline in [&video, &audio] {
pipeline
.set_state(gst::State::Playing)
.expect("play fixture");
let message = pipeline
.bus()
.expect("bus")
.timed_pop_filtered(
gst::ClockTime::from_seconds(5),
&[gst::MessageType::Eos, gst::MessageType::Error],
)
.expect("fixture completes");
pipeline.set_state(gst::State::Null).expect("stop fixture");
assert!(
matches!(message.view(), gst::MessageView::Eos(..)),
"{message:?}"
);
}
let frame = feed.take_frame().expect("actual fixture frame");
frame.validate().expect("bounded frame");
assert!(frame.width <= 64 && frame.height <= 48);
assert!(feed.audio_level() > 0.01);
}
}

31
src/media/mod.rs Normal file
View file

@ -0,0 +1,31 @@
//! User-consented local screen preview and explicitly selected application audio.
//!
//! Microphone capture remains owned by the voice pipeline. These types never
//! substitute a system monitor for an unavailable application stream.
mod policy;
mod sources;
pub use policy::{AudioChoice, AudioKind, AudioSource, CaptureOptions, VideoFrame};
pub use sources::{audio_sources, parse_audio_sources, validate_audio_choice};
#[cfg(all(target_os = "linux", feature = "screen-capture"))]
mod capture;
#[cfg(all(target_os = "linux", feature = "screen-capture"))]
mod portal;
#[cfg(all(target_os = "linux", feature = "screen-capture"))]
pub use capture::{CaptureFeed, CaptureSession, check_backend};
/// User-visible reason when this build cannot open a native screen preview.
pub fn unavailable_reason() -> Option<&'static str> {
#[cfg(all(target_os = "linux", feature = "screen-capture"))]
{
None
}
#[cfg(not(all(target_os = "linux", feature = "screen-capture")))]
{
Some(
"Native capture requires a Linux build with the screen-capture feature. Other platform adapters are not implemented yet.",
)
}
}

109
src/media/policy.rs Normal file
View file

@ -0,0 +1,109 @@
use serde::{Deserialize, Serialize};
/// A selected audio endpoint is identified by its stable PipeWire object serial,
/// not a reusable node ID. There is deliberately no default-device choice.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AudioChoice {
Disabled,
Application(u64),
System(u64),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AudioKind {
Application,
System,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AudioSource {
pub serial: u64,
pub name: String,
pub kind: AudioKind,
}
/// Local preview limits. Microphone configuration is intentionally absent.
#[derive(Debug, Clone, Copy)]
pub struct CaptureOptions {
pub audio: AudioChoice,
pub max_width: u32,
pub max_height: u32,
pub max_fps: u32,
}
impl Default for CaptureOptions {
fn default() -> Self {
Self {
audio: AudioChoice::Disabled,
max_width: 1920,
max_height: 1080,
max_fps: 30,
}
}
}
impl CaptureOptions {
pub fn validate(&self) -> Result<(), String> {
if !(1..=1920).contains(&self.max_width)
|| !(1..=1080).contains(&self.max_height)
|| !(1..=30).contains(&self.max_fps)
{
return Err("Preview must fit within 1920×1080 at 1–30 frames/s.".into());
}
Ok(())
}
}
/// Tightly packed RGBA pixels; no PipeWire/GStreamer memory escapes a callback.
#[derive(Clone)]
pub struct VideoFrame {
pub width: u32,
pub height: u32,
pub rgba: Vec<u8>,
pub timestamp_ns: Option<u64>,
}
impl VideoFrame {
pub fn validate(&self) -> Result<(), String> {
let expected = (self.width as usize)
.checked_mul(self.height as usize)
.and_then(|pixels| pixels.checked_mul(4));
if self.width == 0
|| self.height == 0
|| self.width > 1920
|| self.height > 1080
|| expected != Some(self.rgba.len())
{
return Err("Invalid preview frame dimensions or payload.".into());
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn preview_defaults_to_no_audio_and_rejects_unbounded_frames() {
assert_eq!(CaptureOptions::default().audio, AudioChoice::Disabled);
assert!(
CaptureOptions {
max_width: u32::MAX,
..Default::default()
}
.validate()
.is_err()
);
assert!(
VideoFrame {
width: u32::MAX,
height: u32::MAX,
rgba: vec![],
timestamp_ns: None
}
.validate()
.is_err()
);
}
}

228
src/media/portal.rs Normal file
View file

@ -0,0 +1,228 @@
//! ScreenCast portal session. The portal, rather than VNOX, owns source consent.
use std::{collections::HashMap, os::fd::OwnedFd};
use zbus::{
Connection, OwnedObjectPath, OwnedVariant as OwnedValue, Proxy, Variant as Value,
export::futures_core::Stream,
};
type Options<'a> = HashMap<&'a str, Value<'a>>;
type Results = HashMap<String, OwnedValue>;
pub struct PortalSession {
_lease: SessionLease,
pub remote: OwnedFd,
pub node: u32,
pub serial: Option<u64>,
}
impl PortalSession {
pub async fn choose() -> Result<Self, String> {
let connection = Connection::session().await.map_err(err)?;
let proxy = Proxy::new(
&connection,
"org.freedesktop.portal.Desktop",
"/org/freedesktop/portal/desktop",
"org.freedesktop.portal.ScreenCast",
)
.await
.map_err(err)?;
let available: u32 = proxy
.get_property("AvailableSourceTypes")
.await
.map_err(err)?;
let source_types = available & 3;
if source_types == 0 {
return Err("Desktop portal offers no screen or window sources".into());
}
let cursor_modes: u32 = proxy
.get_property("AvailableCursorModes")
.await
.unwrap_or(1);
let version: u32 = proxy.get_property("version").await.unwrap_or(1);
let session_token = format!("vnox_{}", uuid::Uuid::new_v4().simple());
let mut options = Options::new();
options.insert("session_handle_token", Value::from(session_token.as_str()));
let result = request(&connection, &proxy, "CreateSession", None, None, options).await?;
let path = result
.get("session_handle")
.ok_or("Portal omitted session handle")?;
let path = OwnedObjectPath::try_from(path.try_clone().map_err(err)?).map_err(err)?;
let lease = SessionLease {
connection: connection.clone(),
path: path.clone(),
};
let result = async {
let mut options = Options::new();
options.insert("types", Value::from(source_types));
options.insert("multiple", Value::from(false));
if cursor_modes & 2 != 0 {
options.insert("cursor_mode", Value::from(2u32));
} else if cursor_modes & 1 != 0 {
options.insert("cursor_mode", Value::from(1u32));
}
if version >= 4 {
options.insert("persist_mode", Value::from(0u32));
}
request(
&connection,
&proxy,
"SelectSources",
Some(&path),
None,
options,
)
.await?;
let mut results = request(
&connection,
&proxy,
"Start",
Some(&path),
Some(""),
Options::new(),
)
.await?;
let streams = results
.remove("streams")
.ok_or("Portal omitted video stream")?;
let streams: Vec<(u32, Results)> = streams.try_into().map_err(err)?;
if streams.len() != 1 {
return Err("Choose exactly one screen or window".into());
}
let (node, properties) = streams
.into_iter()
.next()
.ok_or("Portal omitted video stream")?;
let serial = properties
.get("pipewire-serial")
.and_then(|v| u64::try_from(v).ok());
let fd: zbus::OwnedFd = proxy
.call("OpenPipeWireRemote", &(&path, Options::new()))
.await
.map_err(err)?;
Ok((node, serial, fd.into()))
}
.await;
match result {
Ok((node, serial, remote)) => Ok(Self {
_lease: lease,
remote,
node,
serial,
}),
Err(error) => {
close(&connection, &path).await;
Err(error)
}
}
}
}
struct SessionLease {
connection: Connection,
path: OwnedObjectPath,
}
impl Drop for SessionLease {
fn drop(&mut self) {
let connection = self.connection.clone();
let path = self.path.clone();
if let Ok(runtime) = tokio::runtime::Handle::try_current() {
runtime.spawn(async move {
close(&connection, &path).await;
});
}
}
}
struct RequestLease {
connection: Connection,
path: String,
pending: bool,
}
impl Drop for RequestLease {
fn drop(&mut self) {
if !self.pending {
return;
}
let connection = self.connection.clone();
let path = self.path.clone();
if let Ok(runtime) = tokio::runtime::Handle::try_current() {
runtime.spawn(async move {
if let Ok(proxy) = Proxy::new(
&connection,
"org.freedesktop.portal.Desktop",
path.as_str(),
"org.freedesktop.portal.Request",
)
.await
{
let _: Result<(), _> = proxy.call("Close", &()).await;
}
});
}
}
}
async fn close(connection: &Connection, path: &OwnedObjectPath) {
if let Ok(proxy) = Proxy::new(
connection,
"org.freedesktop.portal.Desktop",
path,
"org.freedesktop.portal.Session",
)
.await
{
let _: Result<(), _> = proxy.call("Close", &()).await;
}
}
async fn request(
connection: &Connection,
proxy: &Proxy<'_>,
method: &str,
session: Option<&OwnedObjectPath>,
parent: Option<&str>,
mut options: Options<'_>,
) -> Result<Results, String> {
let token = format!("vnox_{}", uuid::Uuid::new_v4().simple());
let sender = connection
.unique_name()
.ok_or("D-Bus has no unique name")?
.as_str()
.trim_start_matches(':')
.replace('.', "_");
let path = format!("/org/freedesktop/portal/desktop/request/{sender}/{token}");
let mut lease = RequestLease {
connection: connection.clone(),
path: path.clone(),
pending: true,
};
let response = Proxy::new(
connection,
"org.freedesktop.portal.Desktop",
path.as_str(),
"org.freedesktop.portal.Request",
)
.await
.map_err(err)?;
let mut signals = response.receive_signal("Response").await.map_err(err)?;
options.insert("handle_token", Value::from(token));
let _: OwnedObjectPath = match (session, parent) {
(None, _) => proxy.call(method, &(options,)).await,
(Some(session), None) => proxy.call(method, &(session, options)).await,
(Some(session), Some(parent)) => proxy.call(method, &(session, parent, options)).await,
}
.map_err(err)?;
let message = std::future::poll_fn(|cx| std::pin::Pin::new(&mut signals).poll_next(cx))
.await
.ok_or("Portal response stream ended")?;
lease.pending = false;
let (code, result): (u32, Results) = message.body().deserialize().map_err(err)?;
match code {
0 => Ok(result),
1 => Err("Screen selection cancelled".into()),
_ => Err("Desktop portal rejected capture".into()),
}
}
fn err(error: impl std::fmt::Display) -> String {
error.to_string()
}

175
src/media/sources.rs Normal file
View file

@ -0,0 +1,175 @@
use super::{AudioChoice, AudioKind, AudioSource};
const MAX_GRAPH_BYTES: usize = 2 * 1024 * 1024;
/// Parse only playback applications and output sinks. Input/microphone nodes
/// never appear in the screen-audio selector.
pub fn parse_audio_sources(json: &[u8], own_pid: u32) -> Result<Vec<AudioSource>, String> {
if json.len() > MAX_GRAPH_BYTES {
return Err("Audio source inventory exceeds the supported size.".into());
}
let graph: Vec<serde_json::Value> = serde_json::from_slice(json)
.map_err(|_| "Unable to read PipeWire audio source inventory.".to_string())?;
let mut result = Vec::new();
for item in graph {
if item["type"] != "PipeWire:Interface:Node" {
continue;
}
let props = &item["info"]["props"];
let kind = match props["media.class"].as_str() {
Some("Stream/Output/Audio") => AudioKind::Application,
Some("Audio/Sink") => AudioKind::System,
_ => continue,
};
let pid = number(&props["application.process.id"]);
let application = props["application.name"].as_str().unwrap_or("");
let node_name = props["node.name"].as_str().unwrap_or("");
if pid == Some(u64::from(own_pid))
|| application.to_lowercase().contains("vnox")
|| node_name.to_lowercase().contains("vnox")
{
continue;
}
let Some(serial) = number(&props["object.serial"]).filter(|serial| *serial > 0) else {
continue;
};
let name = if kind == AudioKind::Application {
props["application.name"]
.as_str()
.or_else(|| props["media.name"].as_str())
} else {
props["node.description"].as_str()
}
.unwrap_or(node_name)
.chars()
.filter(|c| !c.is_control())
.take(100)
.collect::<String>();
if name.trim().is_empty() {
continue;
}
result.push(AudioSource { serial, name, kind });
}
result.sort_by(|a, b| a.name.cmp(&b.name).then(a.serial.cmp(&b.serial)));
let mut seen = std::collections::HashSet::new();
result.retain(|source| seen.insert(source.serial));
Ok(result)
}
fn number(value: &serde_json::Value) -> Option<u64> {
value.as_u64().or_else(|| value.as_str()?.parse().ok())
}
/// Check against a fresh inventory. Missing application audio is an error,
/// never an instruction to use a different endpoint or the system monitor.
pub fn validate_audio_choice(choice: AudioChoice, current: &[AudioSource]) -> Result<(), String> {
let (serial, kind) = match choice {
AudioChoice::Disabled => return Ok(()),
AudioChoice::Application(serial) => (serial, AudioKind::Application),
AudioChoice::System(serial) => (serial, AudioKind::System),
};
if current
.iter()
.any(|source| source.serial == serial && source.kind == kind)
{
Ok(())
} else {
Err("The selected audio source is no longer available. Choose it again; system audio was not enabled.".into())
}
}
/// Enumerate metadata only. This function does not record or play audio.
#[cfg(target_os = "linux")]
pub async fn audio_sources() -> Result<Vec<AudioSource>, String> {
use std::{process::Stdio, time::Duration};
use tokio::{io::AsyncReadExt, process::Command};
let scan = async {
let mut child = Command::new("pw-dump")
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.kill_on_drop(true)
.spawn()
.map_err(|_| "PipeWire source discovery requires pw-dump.".to_string())?;
let mut bytes = Vec::new();
child
.stdout
.take()
.ok_or("Audio inventory pipe unavailable.")?
.take(MAX_GRAPH_BYTES as u64 + 1)
.read_to_end(&mut bytes)
.await
.map_err(|_| "Unable to read audio inventory.".to_string())?;
if bytes.len() > MAX_GRAPH_BYTES {
return Err("Audio inventory exceeds the supported size.".into());
}
let status = child
.wait()
.await
.map_err(|_| "Audio inventory process failed.".to_string())?;
if !status.success() {
return Err("PipeWire audio inventory is unavailable.".into());
}
parse_audio_sources(&bytes, std::process::id())
};
tokio::time::timeout(Duration::from_secs(3), scan)
.await
.map_err(|_| "PipeWire audio source discovery timed out.".to_string())?
}
#[cfg(not(target_os = "linux"))]
pub async fn audio_sources() -> Result<Vec<AudioSource>, String> {
Err("Application-audio selection is not implemented on this platform yet.".into())
}
#[cfg(test)]
mod tests {
use super::*;
fn node(class: &str, serial: u64, pid: u32, name: &str) -> serde_json::Value {
serde_json::json!({"type":"PipeWire:Interface:Node","info":{"props":{
"media.class":class,"object.serial":serial,"application.process.id":pid,
"application.name":name,"node.description":name,"node.name":name
}}})
}
#[test]
fn inventory_excludes_microphones_own_audio_and_unstable_ids() {
let graph = serde_json::to_vec(&vec![
node("Stream/Output/Audio", 10, 100, "Game"),
node("Audio/Source", 11, 200, "Microphone"),
node("Stream/Output/Audio", 12, 999, "Own capture"),
node("Stream/Output/Audio", 13, 1, "Vnox playback"),
node("Audio/Sink", 14, 1, "Headphones"),
node("Stream/Output/Audio", 0, 2, "No serial"),
])
.unwrap();
let sources = parse_audio_sources(&graph, 999).unwrap();
assert_eq!(
sources
.iter()
.map(|source| source.serial)
.collect::<Vec<_>>(),
vec![10, 14]
);
}
#[test]
fn unavailable_application_never_becomes_system_capture() {
let system = AudioSource {
serial: 14,
name: "Headphones".into(),
kind: AudioKind::System,
};
assert!(
validate_audio_choice(AudioChoice::Application(99), std::slice::from_ref(&system))
.is_err()
);
assert!(
validate_audio_choice(AudioChoice::Application(14), std::slice::from_ref(&system))
.is_err()
);
assert!(validate_audio_choice(AudioChoice::System(14), &[system]).is_ok());
assert!(validate_audio_choice(AudioChoice::Disabled, &[]).is_ok());
}
}

View file

@ -85,9 +85,12 @@ fn commit(
) -> Result<(), String> {
let spec = prefs.resolve()?;
if persist {
prefs
.save()
.map_err(|error| format!("Не удалось сохранить настройки темы: {error}"))?;
prefs.save().map_err(|error| {
crate::ui::i18n::format(
"Could not save theme preferences: {error}",
&[("error", error.to_string())],
)
})?;
}
state.borrow_mut().ui.appearance = prefs.clone();
apply_main(window, &spec);
@ -95,7 +98,9 @@ fn commit(
window.set_text_size(spec.font_size);
window.set_theme_preview(false);
window.set_theme_error("".into());
window.set_theme_status("Тема сохранена и применяется ко всему приложению.".into());
window.set_theme_status(
crate::ui::i18n::text("Theme saved and applied throughout the app.").into(),
);
Ok(())
}
@ -105,7 +110,12 @@ fn preview(window: &MainWindow, css: &str) -> Result<(), String> {
window.set_text_size(spec.font_size);
window.set_theme_preview(true);
window.set_theme_error("".into());
window.set_theme_status("Предпросмотр. Нажми «Применить», чтобы сохранить. Закрытие настроек вернёт сохранённую тему.".into());
window.set_theme_status(
crate::ui::i18n::text(
"Previewing. Select Apply to save. Closing settings restores your saved theme.",
)
.into(),
);
Ok(())
}
@ -123,7 +133,8 @@ pub fn wire(window: &MainWindow, state: &Rc<RefCell<AppState>>, persist: bool) {
window.set_theme_mode("custom".into());
window.set_theme_error("".into());
window.set_theme_status(
"Измени CSS, затем открой предпросмотр или примени тему.".into(),
crate::ui::i18n::text("Edit the CSS, then preview or apply your theme.")
.into(),
);
} else {
let mut prefs = state.borrow().ui.appearance.clone();
@ -141,7 +152,9 @@ pub fn wire(window: &MainWindow, state: &Rc<RefCell<AppState>>, persist: bool) {
if !size.is_finite() || !(12.0..=22.0).contains(&size) {
report(
&window,
Err("Размер текста должен быть от 12px до 22px.".into()),
Err(crate::ui::i18n::text(
"Text size must be between 12px and 22px.",
)),
);
return;
}
@ -229,7 +242,9 @@ pub fn wire(window: &MainWindow, state: &Rc<RefCell<AppState>>, persist: bool) {
.and_then(|spec| super::storage::export_css(Path::new(path.as_str()), &spec));
if result.is_ok() {
window.set_theme_error("".into());
window.set_theme_status("CSS сохранён в указанный локальный файл.".into());
window.set_theme_status(
crate::ui::i18n::text("CSS exported to the specified local file.").into(),
);
}
report(&window, result);
}

View file

@ -7,12 +7,18 @@ pub const MAX_CSS_BYTES: usize = 16 * 1024;
pub(super) fn parse_color(text: &str) -> Result<Rgba, String> {
let hex = text
.strip_prefix('#')
.ok_or("Цвет должен начинаться с #.")?;
.ok_or(crate::ui::i18n::text("A colour must start with #."))?;
if !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
return Err(format!("Некорректный цвет: {text}"));
return Err(crate::ui::i18n::format(
"Invalid colour: {text}",
&[("text", text.to_string())],
));
}
let byte =
|s: &str| u8::from_str_radix(s, 16).map_err(|_| format!("Некорректный цвет: {text}"));
let byte = |s: &str| {
u8::from_str_radix(s, 16).map_err(|_| {
crate::ui::i18n::format("Invalid colour: {text}", &[("text", text.to_string())])
})
};
match hex.len() {
3 | 4 => {
let values = hex
@ -39,8 +45,9 @@ pub(super) fn parse_color(text: &str) -> Result<Rgba, String> {
255
},
)),
_ => Err(format!(
"Цвет {text}: нужны 3, 4, 6 или 8 шестнадцатеричных цифр."
_ => Err(crate::ui::i18n::format(
"Colour {text} requires 3, 4, 6 or 8 hexadecimal digits.",
&[("text", text.to_string())],
)),
}
}
@ -51,7 +58,9 @@ fn strip_comments(css: &str) -> Result<String, String> {
while let Some(start) = rest.find("/*") {
result.push_str(&rest[..start]);
let tail = &rest[start + 2..];
let end = tail.find("*/").ok_or("Комментарий CSS не закрыт.")?;
let end = tail
.find("*/")
.ok_or(crate::ui::i18n::text("Unclosed CSS comment."))?;
result.push(' ');
rest = &tail[end + 2..];
}
@ -62,53 +71,67 @@ fn strip_comments(css: &str) -> Result<String, String> {
/// Parse the deliberately restricted native-theme CSS format; never fetch or execute CSS.
pub fn parse_css(css: &str) -> Result<ThemeSpec, String> {
if css.len() > MAX_CSS_BYTES {
return Err("Файл темы слишком большой: максимум 16 КБ.".into());
return Err(crate::ui::i18n::text(
"Theme file is too large: maximum 16 KB.",
));
}
let stripped = strip_comments(css)?;
let root = stripped
.trim()
.strip_prefix(":root")
.ok_or("Тема должна содержать один блок :root { … }. ")?
.ok_or(crate::ui::i18n::text(
"A theme must contain one :root { … } block. ",
))?
.trim();
let body = root
.strip_prefix('{')
.and_then(|s| s.strip_suffix('}'))
.ok_or("Ожидается один блок :root { … }. ")?;
.ok_or(crate::ui::i18n::text("Expected one :root { … } block. "))?;
if body.contains(['{', '}']) {
return Err("Поддерживается только один блок :root без вложенных правил.".into());
return Err(crate::ui::i18n::text(
"Only one :root block without nested rules is supported.",
));
}
let mut theme = ThemeSpec::builtin("dark");
let mut seen = HashSet::new();
for declaration in body.split(';').map(str::trim).filter(|s| !s.is_empty()) {
let (name, value) = declaration
.split_once(':')
.ok_or("После имени переменной нужен знак :.")?;
let (name, value) = declaration.split_once(':').ok_or(crate::ui::i18n::text(
"A variable name must be followed by :.",
))?;
let (name, value) = (name.trim(), value.trim());
if !seen.insert(name) {
return Err(format!("Переменная {name} указана дважды."));
return Err(crate::ui::i18n::format(
"Variable {name} is defined twice.",
&[("name", name.to_string())],
));
}
if name == "--vnox-font-size" {
let number = value
.strip_suffix("px")
.ok_or("Размер текста задаётся в px, например 16px.")?;
let number = value.strip_suffix("px").ok_or(crate::ui::i18n::text(
"Text size must use px, for example 16px.",
))?;
let size: f32 = number
.trim()
.parse()
.map_err(|_| "Некорректный размер текста.")?;
.map_err(|_| crate::ui::i18n::text("Invalid text size."))?;
if !size.is_finite() || !(12.0..=22.0).contains(&size) {
return Err("Размер текста должен быть от 12px до 22px.".into());
return Err(crate::ui::i18n::text(
"Text size must be between 12px and 22px.",
));
}
theme.font_size = size;
} else if let Some(index) = COLOR_TOKENS.iter().position(|token| *token == name) {
theme.colors[index] = parse_color(value).map_err(|e| format!("{name}: {e}"))?;
} else {
return Err(format!(
"Неподдерживаемая переменная {name}. Веб-селекторы, url() и @import не поддерживаются."
return Err(crate::ui::i18n::format(
"Unsupported variable {name}. CSS selectors, url() and @import are not supported.",
&[("name", name.to_string())],
));
}
}
if seen.is_empty() {
return Err("Добавь хотя бы одну переменную --vnox-… в блок :root.".into());
return Err(crate::ui::i18n::text(
"Add at least one --vnox-… variable to :root.",
));
}
Ok(theme)
}

View file

@ -49,10 +49,12 @@ impl AppearancePreferences {
pub fn resolve(&self) -> Result<ThemeSpec, String> {
if !["light", "dark", "black", "custom"].contains(&self.mode.as_str()) {
return Err("Неизвестная тема.".into());
return Err(crate::ui::i18n::text("Unknown theme."));
}
if !self.font_size.is_finite() || !(12.0..=22.0).contains(&self.font_size) {
return Err("Размер текста должен быть от 12px до 22px.".into());
return Err(crate::ui::i18n::text(
"Text size must be between 12px and 22px.",
));
}
let mut theme = if self.mode == "custom" {
parse_css(&self.custom_css)?
@ -88,19 +90,28 @@ fn check_css_path(path: &Path) -> Result<(), String> {
.and_then(|s| s.to_str())
.is_none_or(|ext| !ext.eq_ignore_ascii_case("css"))
{
return Err("Укажи путь к файлу с расширением .css.".into());
return Err(crate::ui::i18n::text("Enter a file path ending in .css."));
}
Ok(())
}
pub fn import_css(path: &Path) -> Result<String, String> {
check_css_path(path)?;
let file =
std::fs::File::open(path).map_err(|error| format!("Не удалось открыть тему: {error}"))?;
let file = std::fs::File::open(path).map_err(|error| {
crate::ui::i18n::format(
"Could not open theme: {error}",
&[("error", error.to_string())],
)
})?;
let mut css = String::new();
file.take(MAX_CSS_BYTES as u64 + 1)
.read_to_string(&mut css)
.map_err(|error| format!("Не удалось прочитать CSS: {error}"))?;
.map_err(|error| {
crate::ui::i18n::format(
"Could not read CSS: {error}",
&[("error", error.to_string())],
)
})?;
parse_css(&css)?;
Ok(css)
}
@ -109,11 +120,19 @@ pub fn export_css(path: &Path, theme: &ThemeSpec) -> Result<(), String> {
check_css_path(path)?;
// The path is explicitly provided by the local export action. No network I/O.
if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
std::fs::create_dir_all(parent)
.map_err(|e| format!("Не удалось создать папку темы: {e}"))?;
std::fs::create_dir_all(parent).map_err(|e| {
crate::ui::i18n::format(
"Could not create theme directory: {e}",
&[("e", e.to_string())],
)
})?;
}
std::fs::write(path, theme.to_css())
.map_err(|error| format!("Не удалось сохранить CSS: {error}"))
std::fs::write(path, theme.to_css()).map_err(|error| {
crate::ui::i18n::format(
"Could not save CSS: {error}",
&[("error", error.to_string())],
)
})
}
#[cfg(test)]

View file

@ -64,8 +64,11 @@ pub fn wire(window: &MainWindow, state: &Rc<RefCell<AppState>>, persist: bool) {
let task_window = weak.clone();
let result = slint::spawn_local(async move {
let Some(file) = rfd::AsyncFileDialog::new()
.set_title("Выбрать фото профиля")
.add_filter("Фото (PNG, JPEG, WebP)", &["png", "jpg", "jpeg", "webp"])
.set_title(crate::ui::i18n::text("Choose profile photo"))
.add_filter(
crate::ui::i18n::text("Photos (PNG, JPEG, WebP)"),
&["png", "jpg", "jpeg", "webp"],
)
.pick_file()
.await
else {
@ -78,7 +81,10 @@ pub fn wire(window: &MainWindow, state: &Rc<RefCell<AppState>>, persist: bool) {
Ok(Ok(source)) => begin_crop(&window, &pending, source),
Ok(Err(error)) => window.set_avatar_error(error.into()),
Err(_) => window.set_avatar_error(
"Не удалось обработать фото. Попробуй другое изображение.".into(),
crate::ui::i18n::text(
"Could not process this photo. Try another image.",
)
.into(),
),
}
}
@ -86,7 +92,10 @@ pub fn wire(window: &MainWindow, state: &Rc<RefCell<AppState>>, persist: bool) {
if result.is_err()
&& let Some(window) = weak.upgrade()
{
window.set_avatar_error("Не удалось открыть выбор файла в этом окружении.".into());
window.set_avatar_error(
crate::ui::i18n::text("The file picker is unavailable in this environment.")
.into(),
);
}
});
}
@ -162,7 +171,13 @@ pub fn wire(window: &MainWindow, state: &Rc<RefCell<AppState>>, persist: bool) {
&& let Err(error) = std::fs::remove_file(&path)
&& error.kind() != std::io::ErrorKind::NotFound
{
window.set_avatar_error(format!("Не удалось удалить фото: {error}").into());
window.set_avatar_error(
crate::ui::i18n::format(
"Could not remove photo: {error}",
&[("error", error.to_string())],
)
.into(),
);
return;
}
window.set_own_avatar(slint::Image::default());

View file

@ -17,10 +17,11 @@ pub struct CropSource {
impl CropSource {
pub fn load(path: &Path) -> Result<Self, String> {
let file =
std::fs::File::open(path).map_err(|e| format!("Не удалось открыть фото: {e}"))?;
let file = std::fs::File::open(path).map_err(|e| {
crate::ui::i18n::format("Could not open photo: {e}", &[("e", e.to_string())])
})?;
if file.metadata().map_err(|e| e.to_string())?.len() > MAX_FILE_BYTES as u64 {
return Err("Фото слишком большое: максимум 10 МБ.".into());
return Err(crate::ui::i18n::text("Photo is too large: maximum 10 MB."));
}
let mut bytes = Vec::new();
file.take(MAX_FILE_BYTES as u64 + 1)
@ -31,14 +32,15 @@ impl CropSource {
fn decode(bytes: &[u8]) -> Result<Self, String> {
if bytes.len() > MAX_FILE_BYTES {
return Err("Фото слишком большое: максимум 10 МБ.".into());
return Err(crate::ui::i18n::text("Photo is too large: maximum 10 MB."));
}
let format = image::guess_format(bytes)
.map_err(|_| "Не удалось распознать изображение. Выбери PNG, JPEG или WebP.")?;
let format = image::guess_format(bytes).map_err(|_| {
crate::ui::i18n::text("Could not recognise the image. Choose PNG, JPEG or WebP.")
})?;
if ![ImageFormat::Png, ImageFormat::Jpeg, ImageFormat::WebP].contains(&format) {
return Err(
"Поддерживаются только PNG, JPEG и WebP. Анимации и SVG не поддерживаются.".into(),
);
return Err(crate::ui::i18n::text(
"Only PNG, JPEG and WebP are supported. Animations and SVG are not supported.",
));
}
reject_animation(bytes, format)?;
let mut limits = image::Limits::default();
@ -47,20 +49,26 @@ impl CropSource {
limits.max_alloc = Some(64 * 1024 * 1024);
let mut reader = ImageReader::with_format(Cursor::new(bytes), format);
reader.limits(limits);
let mut decoder = reader
.into_decoder()
.map_err(|e| format!("Не удалось прочитать фото: {e}"))?;
let mut decoder = reader.into_decoder().map_err(|e| {
crate::ui::i18n::format("Could not read photo: {e}", &[("e", e.to_string())])
})?;
if decoder.dimensions().0 > MAX_DIMENSION || decoder.dimensions().1 > MAX_DIMENSION {
return Err("Сторона изображения должна быть не больше 4096 пикселей.".into());
return Err(crate::ui::i18n::text(
"Image dimensions must not exceed 4096 pixels.",
));
}
let orientation = decoder
.orientation()
.map_err(|e| format!("Не удалось прочитать ориентацию фото: {e}"))?;
let mut image = DynamicImage::from_decoder(decoder)
.map_err(|e| format!("Не удалось декодировать фото: {e}"))?;
let orientation = decoder.orientation().map_err(|e| {
crate::ui::i18n::format(
"Could not read photo orientation: {e}",
&[("e", e.to_string())],
)
})?;
let mut image = DynamicImage::from_decoder(decoder).map_err(|e| {
crate::ui::i18n::format("Could not decode photo: {e}", &[("e", e.to_string())])
})?;
image.apply_orientation(orientation);
if image.width() == 0 || image.height() == 0 {
return Err("Изображение пустое.".into());
return Err(crate::ui::i18n::text("The image is empty."));
}
Ok(Self {
image,
@ -119,16 +127,22 @@ impl CropSource {
let mut encoded = Cursor::new(Vec::new());
image
.write_to(&mut encoded, ImageFormat::Png)
.map_err(|e| format!("Не удалось подготовить аватар: {e}"))?;
.map_err(|e| {
crate::ui::i18n::format("Could not prepare avatar: {e}", &[("e", e.to_string())])
})?;
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
}
let temporary = path.with_extension(format!("{}.tmp", uuid::Uuid::new_v4()));
std::fs::write(&temporary, encoded.into_inner())
.map_err(|e| format!("Не удалось сохранить фото: {e}"))?;
std::fs::write(&temporary, encoded.into_inner()).map_err(|e| {
crate::ui::i18n::format("Could not save photo: {e}", &[("e", e.to_string())])
})?;
if let Err(error) = std::fs::rename(&temporary, path) {
let _ = std::fs::remove_file(&temporary);
return Err(format!("Не удалось применить аватар: {error}"));
return Err(crate::ui::i18n::format(
"Could not apply avatar: {error}",
&[("error", error.to_string())],
));
}
Ok(to_ui_image(&image))
}
@ -145,24 +159,26 @@ fn reject_animation(bytes: &[u8], format: ImageFormat) -> Result<(), String> {
let size = u32::from_be_bytes(
bytes[offset..offset + 4]
.try_into()
.map_err(|_| "Повреждённый PNG.")?,
.map_err(|_| crate::ui::i18n::text("Corrupt PNG."))?,
) as usize;
(size, &bytes[offset + 4..offset + 8], 12usize)
} else {
let size = u32::from_le_bytes(
bytes[offset + 4..offset + 8]
.try_into()
.map_err(|_| "Повреждённый WebP.")?,
.map_err(|_| crate::ui::i18n::text("Corrupt WebP."))?,
) as usize;
(size, &bytes[offset..offset + 4], 8usize + size % 2)
};
if kind == b"acTL" || kind == b"ANIM" || kind == b"ANMF" {
return Err("Анимированные изображения не поддерживаются. Выбери обычное фото.".into());
return Err(crate::ui::i18n::text(
"Animated images are not supported. Choose a still photo.",
));
}
offset = offset
.checked_add(length)
.and_then(|n| n.checked_add(padding))
.ok_or("Повреждённое изображение.")?;
.ok_or(crate::ui::i18n::text("Corrupt image."))?;
if offset > bytes.len() {
break;
} // The decoder reports truncated image details.

View file

@ -4,6 +4,16 @@ use slint::{Model, ModelRc, SharedString, VecModel};
use crate::ui::state::{ConnState, UiState};
fn presence_label(status: &str) -> String {
crate::ui::i18n::text(match status.to_ascii_lowercase().as_str() {
"online" => "Online",
"idle" | "away" => "Idle",
"dnd" | "busy" => "Do not disturb",
"pending" => "Pending",
_ => "Offline",
})
}
type MainWindow = crate::ui::slint::MainWindow;
type BookmarkItem = crate::ui::slint::BookmarkItem;
type ChannelItem = crate::ui::slint::ChannelItem;
@ -68,7 +78,9 @@ fn set_messages(
other.content.chars().take(90).collect::<String>()
)
})
.unwrap_or_else(|| "Original message unavailable".into())
.unwrap_or_else(|| {
crate::ui::i18n::text("Original message unavailable")
})
})
.unwrap_or_default(),
),
@ -100,7 +112,7 @@ fn set_members_state(window: &MainWindow, state: &UiState, ch_id: &str) {
avatar_text: nick.chars().take(2).collect::<String>().into(),
user_id: SharedString::from(user_id),
nickname: SharedString::from(nick.as_str()),
status: SharedString::from(status),
status: presence_label(status).into(),
}
})
.collect();
@ -161,7 +173,7 @@ fn sync_sidebar(window: &MainWindow, state: &UiState, own_nickname: &str) {
});
window.set_username(SharedString::from(own_nickname));
window.set_user_status(SharedString::from("online"));
window.set_user_status(crate::ui::i18n::text("Online").into());
window.set_show_dms(state.browsing_dms);
window.set_active_dm_id(state.active_dm_id.as_deref().unwrap_or("").into());
window.set_replying_to_message(SharedString::from(
@ -240,6 +252,14 @@ fn sync_friends(window: &MainWindow, state: &UiState) {
.map(|f| FriendItem {
user_id: SharedString::from(f.user_id.as_str()),
nickname: SharedString::from(f.nickname.as_str()),
status_label: presence_label(
state
.presences
.get(&f.user_id)
.map(|p| p.status.as_str())
.unwrap_or("offline"),
)
.into(),
status: SharedString::from(
state
.presences
@ -259,7 +279,8 @@ fn sync_friends(window: &MainWindow, state: &UiState) {
.map(|f| FriendItem {
user_id: SharedString::from(f.user_id.as_str()),
nickname: SharedString::from(f.nickname.as_str()),
status: SharedString::from("pending"),
status: "pending".into(),
status_label: presence_label("pending").into(),
})
.collect();
replace_model(window.get_pending_requests(), pending, |model| {
@ -323,11 +344,14 @@ pub fn sync_voice(window: &MainWindow, state: &UiState) {
));
let banner = match (state.local_speaking, state.remote_speaking) {
(true, true) => "you and others are talking".to_string(),
(true, false) => "you are talking".to_string(),
(false, true) => format!(
"{} is talking",
state.nick_for(&state.last_remote_speaker_id)
(true, true) => crate::ui::i18n::text("You and others are talking"),
(true, false) => crate::ui::i18n::text("You are talking"),
(false, true) => crate::ui::i18n::format(
"{name} is talking",
&[(
"name",
state.nick_for(&state.last_remote_speaker_id).to_string(),
)],
),
_ => String::new(),
};
@ -347,7 +371,11 @@ pub fn sync_connect(window: &MainWindow, state: &UiState) {
window.set_bookmarks(model)
});
window.set_status_text(SharedString::from(
state.status_msg.as_deref().unwrap_or(""),
state
.status_msg
.as_ref()
.map(ToString::to_string)
.unwrap_or_default(),
));
window.set_connecting(matches!(
state.conn,
@ -372,18 +400,30 @@ pub fn sync_settings(window: &MainWindow, state: &UiState, own_pubkey: &str) {
window.set_output_device_index(state.output_device as i32);
window.set_passphrase_error(SharedString::from(
state.settings_passphrase_error.as_deref().unwrap_or(""),
state
.settings_passphrase_error
.as_ref()
.map(ToString::to_string)
.unwrap_or_default(),
));
window.set_export_output(SharedString::from(
state.settings_export_output.as_deref().unwrap_or(""),
));
window.set_export_error(SharedString::from(
state.settings_export_error.as_deref().unwrap_or(""),
state
.settings_export_error
.as_ref()
.map(ToString::to_string)
.unwrap_or_default(),
));
window.set_import_error(SharedString::from(
state.settings_import_error.as_deref().unwrap_or(""),
state
.settings_import_error
.as_ref()
.map(ToString::to_string)
.unwrap_or_default(),
));
}

237
src/ui/i18n/mod.rs Normal file
View file

@ -0,0 +1,237 @@
//! App-owned messages and bundled Slint translations. User content is never translated.
use std::collections::BTreeMap;
use std::sync::{
OnceLock,
atomic::{AtomicU8, Ordering},
};
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Language {
English,
Russian,
}
static LANGUAGE: AtomicU8 = AtomicU8::new(0);
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct Preferences {
pub language: String,
}
impl Preferences {
pub fn load() -> Self {
preference_path()
.and_then(|p| std::fs::read(p).ok())
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
.unwrap_or_default()
}
pub fn choice(&self) -> &str {
match self.language.as_str() {
"ru" => "ru",
"en" => "en",
_ => "system",
}
}
pub fn resolve(&self) -> Language {
match self.choice() {
"ru" => Language::Russian,
"en" => Language::English,
_ => system_language(),
}
}
pub fn save(&self) -> std::io::Result<()> {
let Some(path) = preference_path() else {
return Ok(());
};
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let temporary = path.with_extension("tmp");
std::fs::write(&temporary, serde_json::to_vec(self)?)?;
std::fs::rename(temporary, path)
}
}
fn preference_path() -> Option<std::path::PathBuf> {
dirs::config_dir().map(|p| p.join("vnox/language.json"))
}
fn language_from_locale(value: &str) -> Language {
let language = value.split(['_', '-', '.', ':']).next().unwrap_or_default();
if language.eq_ignore_ascii_case("ru") {
Language::Russian
} else {
Language::English
}
}
fn system_language() -> Language {
sys_locale::get_locale()
.map(|value| language_from_locale(&value))
.unwrap_or(Language::English)
}
pub fn initialize() {
set_language(Preferences::load().resolve());
}
pub fn current() -> Language {
if LANGUAGE.load(Ordering::Relaxed) == 1 {
Language::Russian
} else {
Language::English
}
}
pub fn set_language(language: Language) {
LANGUAGE.store(u8::from(language == Language::Russian), Ordering::Relaxed);
// Components may not have registered their catalogs before the first window is created.
let _ = slint::select_bundled_translation(if language == Language::Russian {
"ru"
} else {
"en"
});
}
fn catalog() -> &'static BTreeMap<String, serde_json::Value> {
static CATALOG: OnceLock<BTreeMap<String, serde_json::Value>> = OnceLock::new();
CATALOG.get_or_init(|| {
serde_json::from_str(include_str!("../../../translations/ru.json"))
.expect("validated bundled translation catalog")
})
}
pub fn text_in(language: Language, source: &str) -> String {
if language == Language::Russian {
catalog()
.get(source)
.and_then(|v| v.as_str())
.unwrap_or(source)
.into()
} else {
source.into()
}
}
pub fn text(source: &str) -> String {
text_in(current(), source)
}
/// Substitute only placeholders in an app-owned template, never recurse into arguments.
pub fn format_in(language: Language, source: &str, args: &[(&str, String)]) -> String {
let template = text_in(language, source);
let mut out = String::with_capacity(template.len());
let mut rest = template.as_str();
while let Some(start) = rest.find('{') {
out.push_str(&rest[..start]);
let tail = &rest[start..];
if let Some(end) = tail.find('}') {
let key = &tail[1..end];
if let Some((_, value)) = args.iter().find(|(name, _)| *name == key) {
out.push_str(value);
} else {
out.push_str(&tail[..=end]);
}
rest = &tail[end + 1..];
} else {
out.push_str(tail);
rest = "";
break;
}
}
out.push_str(rest);
out
}
pub fn format(source: &str, args: &[(&str, String)]) -> String {
format_in(current(), source, args)
}
/// A semantic app message retains its key and parameters across language changes.
#[derive(Clone, Debug)]
pub enum Message {
App(&'static str, Vec<(&'static str, String)>),
Raw(String),
}
impl Message {
pub fn with(source: &'static str, args: Vec<(&'static str, String)>) -> Self {
Self::App(source, args)
}
}
impl From<&'static str> for Message {
fn from(source: &'static str) -> Self {
Self::App(source, Vec::new())
}
}
impl From<String> for Message {
fn from(value: String) -> Self {
Self::Raw(value)
}
}
impl std::fmt::Display for Message {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::App(source, args) => f.write_str(&format(source, args)),
Self::Raw(value) => f.write_str(value),
}
}
}
pub fn wire(window: &super::slint::MainWindow, persist: bool) {
use slint::ComponentHandle;
window.set_language_choice(Preferences::load().choice().into());
set_language(current());
let weak = window.as_weak();
window.on_language_selected(move |choice| {
let prefs = Preferences {
language: choice.to_string(),
};
if !matches!(choice.as_str(), "system" | "ru" | "en") {
return;
}
if persist && let Err(error) = prefs.save() {
tracing::warn!(%error, "could not save language preference");
if let Some(window) = weak.upgrade() {
window.set_theme_error(
format(
"Could not save language preference: {error}",
&[("error", error.to_string())],
)
.into(),
);
}
return;
}
set_language(prefs.resolve());
if let Some(window) = weak.upgrade() {
window.set_language_choice(prefs.choice().into());
// Transient validation messages belong to the previous edit. Drafts and inputs stay intact.
window.set_theme_error("".into());
window.set_theme_status("".into());
window.set_avatar_error("".into());
}
});
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn locale_resolution_and_invalid_preferences_fall_back() {
assert_eq!(language_from_locale("ru_RU.UTF-8"), Language::Russian);
assert_eq!(language_from_locale("ru-UA"), Language::Russian);
assert_eq!(language_from_locale("pl_PL.UTF-8"), Language::English);
assert_eq!(
Preferences {
language: "uk".into()
}
.choice(),
"system"
);
assert_eq!(
serde_json::from_str::<Preferences>("{}").unwrap().choice(),
"system"
);
}
#[test]
fn interpolation_does_not_translate_or_reprocess_untrusted_values() {
assert_eq!(
format_in(
Language::Russian,
"Connection lost: {reason}",
&[("reason", "{reason} Reply online".into())]
),
"Соединение потеряно: {reason} Reply online"
);
assert_eq!(text_in(Language::English, "Settings"), "Settings");
assert_eq!(text_in(Language::Russian, "Settings"), "Настройки");
}
}

422
src/ui/media.rs Normal file
View file

@ -0,0 +1,422 @@
//! Native local screen preview. Captured pixels never enter chat/UI persistence.
use crate::ui::slint::{MainWindow, ScreenShareWindow};
use slint::ComponentHandle;
/// Register the screen preview window; unsupported builds explain their capability.
pub fn wire(main: &MainWindow) -> Result<(), slint::PlatformError> {
let dialog = ScreenShareWindow::new()?;
#[cfg(all(target_os = "linux", feature = "screen-capture"))]
let controller = native::Controller::new(dialog.clone_strong());
let main_weak = main.as_weak();
main.on_open_screen_share(move || {
if let Some(main) = main_weak.upgrade() {
sync_palette(&main, &dialog);
}
#[cfg(all(target_os = "linux", feature = "screen-capture"))]
controller.refresh();
if let Err(error) = dialog.show() {
tracing::warn!(%error, "Cannot open capture window");
}
});
Ok(())
}
#[cfg(any(test, all(target_os = "linux", feature = "screen-capture")))]
/// Keep the app-owned message semantic until render; diagnostic arguments remain untouched.
fn media_message(error: &str) -> crate::ui::i18n::Message {
use crate::ui::i18n::Message;
match error {
"Audio source inventory exceeds the supported size." => {
Message::with("Audio source inventory exceeds the supported size.", vec![])
}
"Unable to read PipeWire audio source inventory." => {
Message::with("Unable to read PipeWire audio source inventory.", vec![])
}
"The selected audio source is no longer available. Choose it again; system audio was not enabled." => {
Message::with(
"The selected audio source is no longer available. Choose it again; system audio was not enabled.",
vec![],
)
}
"PipeWire source discovery requires pw-dump." => {
Message::with("PipeWire source discovery requires pw-dump.", vec![])
}
"Audio inventory pipe unavailable." => {
Message::with("Audio inventory pipe unavailable.", vec![])
}
"Unable to read audio inventory." => {
Message::with("Unable to read audio inventory.", vec![])
}
"Audio inventory exceeds the supported size." => {
Message::with("Audio inventory exceeds the supported size.", vec![])
}
"Audio inventory process failed." => {
Message::with("Audio inventory process failed.", vec![])
}
"PipeWire audio inventory is unavailable." => {
Message::with("PipeWire audio inventory is unavailable.", vec![])
}
"PipeWire audio source discovery timed out." => {
Message::with("PipeWire audio source discovery timed out.", vec![])
}
"Application-audio selection is not implemented on this platform yet." => Message::with(
"Application-audio selection is not implemented on this platform yet.",
vec![],
),
"Preview must fit within 1920×1080 at 1–30 frames/s." => Message::with(
"Preview must fit within 1920×1080 at 1–30 frames/s.",
vec![],
),
"Invalid preview frame dimensions or payload." => {
Message::with("Invalid preview frame dimensions or payload.", vec![])
}
"Desktop portal offers no screen or window sources" => {
Message::with("Desktop portal offers no screen or window sources", vec![])
}
"Portal omitted session handle" => Message::with("Portal omitted session handle", vec![]),
"Portal omitted video stream" => Message::with("Portal omitted video stream", vec![]),
"Choose exactly one screen or window" => {
Message::with("Choose exactly one screen or window", vec![])
}
"D-Bus has no unique name" => Message::with("D-Bus has no unique name", vec![]),
"Portal response stream ended" => Message::with("Portal response stream ended", vec![]),
"Screen selection cancelled" => Message::with("Screen selection cancelled", vec![]),
"Desktop portal rejected capture" => {
Message::with("Desktop portal rejected capture", vec![])
}
"Missing portal session" => Message::with("Missing portal session", vec![]),
"Selected audio source produced no samples. Capture stopped; no fallback source was enabled." => {
Message::with(
"Selected audio source produced no samples. Capture stopped; no fallback source was enabled.",
vec![],
)
}
"Capture source closed. Choose it again to resume." => {
Message::with("Capture source closed. Choose it again to resume.", vec![])
}
"Missing video caps" => Message::with("Missing video caps", vec![]),
"Unbounded or invalid video frame" => {
Message::with("Unbounded or invalid video frame", vec![])
}
"Missing video buffer" => Message::with("Missing video buffer", vec![]),
"Invalid video stride" => Message::with("Invalid video stride", vec![]),
"Select an available audio source first." => {
Message::with("Select an available audio source first.", vec![])
}
"No frames received. Capture stopped; select the source again." => Message::with(
"No frames received. Capture stopped; select the source again.",
vec![],
),
_ => {
if let Some(name) = error
.strip_prefix("Missing GStreamer plugin: ")
.and_then(|tail| tail.strip_suffix(". Install the PipeWire and base plugins."))
{
Message::with(
"Missing GStreamer plugin: {name}. Install the PipeWire and base plugins.",
vec![("name", name.into())],
)
} else if let Some(detail) = error.strip_prefix("Capture stopped: ") {
Message::with("Capture stopped: {error}", vec![("error", detail.into())])
} else {
Message::with("Capture failed: {error}", vec![("error", error.into())])
}
}
}
}
#[cfg(all(target_os = "linux", feature = "screen-capture"))]
mod native {
use super::*;
use std::{
cell::{Cell, RefCell},
rc::Rc,
sync::mpsc,
time::{Duration, Instant},
};
use vnox_client::media::{
self, AudioChoice, AudioKind, AudioSource, CaptureOptions, CaptureSession,
};
enum Event {
Sources(Result<Vec<AudioSource>, String>),
Capture(u64, Result<CaptureSession, String>),
}
pub struct Controller {
window: ScreenShareWindow,
sources: RefCell<Vec<AudioSource>>,
selected: RefCell<Vec<AudioSource>>,
session: RefCell<Option<CaptureSession>>,
pending: RefCell<Option<tokio::task::JoinHandle<()>>>,
tx: mpsc::Sender<Event>,
rx: RefCell<mpsc::Receiver<Event>>,
timer: slint::Timer,
started: RefCell<Option<Instant>>,
generation: Cell<u64>,
error: RefCell<Option<crate::ui::i18n::Message>>,
}
impl Controller {
pub fn new(window: ScreenShareWindow) -> Rc<Self> {
window.set_capable(true);
let (tx, rx) = mpsc::channel();
let this = Rc::new(Self {
window,
sources: RefCell::new(Vec::new()),
selected: RefCell::new(Vec::new()),
session: RefCell::new(None),
pending: RefCell::new(None),
tx,
rx: RefCell::new(rx),
timer: slint::Timer::default(),
started: RefCell::new(None),
generation: Cell::new(0),
error: RefCell::new(None),
});
let weak = Rc::downgrade(&this);
this.timer.start(
slint::TimerMode::Repeated,
Duration::from_millis(50),
move || {
if let Some(this) = weak.upgrade() {
this.tick();
}
},
);
let weak = Rc::downgrade(&this);
this.window.on_refresh_audio(move || {
if let Some(this) = weak.upgrade() {
this.refresh();
}
});
let weak = Rc::downgrade(&this);
this.window.on_audio_mode_changed(move || {
if let Some(this) = weak.upgrade() {
this.filter_sources();
}
});
let weak = Rc::downgrade(&this);
this.window.on_choose_source(move || {
if let Some(this) = weak.upgrade() {
this.start();
}
});
let weak = Rc::downgrade(&this);
this.window.on_stop_capture(move || {
if let Some(this) = weak.upgrade() {
this.stop();
}
});
let weak = Rc::downgrade(&this);
this.window.window().on_close_requested(move || {
if let Some(this) = weak.upgrade() {
this.stop();
}
slint::CloseRequestResponse::HideWindow
});
this
}
pub fn refresh(&self) {
let tx = self.tx.clone();
tokio::spawn(async move {
let _ = tx.send(Event::Sources(media::audio_sources().await));
});
}
fn filter_sources(&self) {
let kind = match self.window.get_audio_mode() {
1 => Some(AudioKind::Application),
2 => Some(AudioKind::System),
_ => None,
};
let selected: Vec<_> = self
.sources
.borrow()
.iter()
.filter(|source| Some(source.kind) == kind)
.cloned()
.collect();
let labels: Vec<slint::SharedString> =
selected.iter().map(|s| s.name.as_str().into()).collect();
self.window
.set_audio_sources(Rc::new(slint::VecModel::from(labels)).into());
self.window.set_source_index(0);
*self.selected.borrow_mut() = selected;
}
fn report_error(&self, error: &str) {
let message = media_message(error);
self.window.set_error(message.to_string().into());
*self.error.borrow_mut() = Some(message);
}
fn start(&self) {
self.stop();
self.window.set_error("".into());
let audio = match self.window.get_audio_mode() {
1 | 2 => {
let index = usize::try_from(self.window.get_source_index()).ok();
let selected = self.selected.borrow();
let Some(source) = index.and_then(|index| selected.get(index)) else {
self.report_error("Select an available audio source first.");
return;
};
match source.kind {
AudioKind::Application => AudioChoice::Application(source.serial),
AudioKind::System => AudioChoice::System(source.serial),
}
}
_ => AudioChoice::Disabled,
};
self.window.set_busy(true);
let tx = self.tx.clone();
let generation = self.generation.get();
*self.pending.borrow_mut() = Some(tokio::spawn(async move {
let result = CaptureSession::choose(CaptureOptions {
audio,
..Default::default()
})
.await;
let _ = tx.send(Event::Capture(generation, result));
}));
}
fn stop(&self) {
self.generation.set(self.generation.get().wrapping_add(1));
if let Some(task) = self.pending.borrow_mut().take() {
task.abort();
}
self.session.borrow_mut().take();
// Discard late completion before another selection can start.
while self.rx.borrow_mut().try_recv().is_ok() {}
*self.started.borrow_mut() = None;
self.error.borrow_mut().take();
self.window.set_error("".into());
self.window.set_running(false);
self.window.set_busy(false);
self.window.set_has_frame(false);
self.window.set_preview(slint::Image::default());
self.window.set_audio_level(0.0);
}
fn tick(&self) {
while let Ok(event) = self.rx.borrow_mut().try_recv() {
match event {
Event::Sources(Ok(sources)) => {
*self.sources.borrow_mut() = sources;
self.filter_sources();
}
Event::Sources(Err(error)) => self.report_error(&error),
Event::Capture(generation, result) => {
if generation != self.generation.get() {
continue;
}
self.pending.borrow_mut().take();
self.window.set_busy(false);
match result {
Ok(session) => {
*self.session.borrow_mut() = Some(session);
*self.started.borrow_mut() = Some(Instant::now());
self.window.set_running(true);
}
Err(error) => self.report_error(&error),
}
}
}
}
let mut error = None;
if let Some(session) = self.session.borrow().as_ref() {
if let Err(message) = session.check() {
error = Some(message);
}
if let Some(frame) = session.feed.take_frame() {
let buffer = slint::SharedPixelBuffer::<slint::Rgba8Pixel>::clone_from_slice(
&frame.rgba,
frame.width,
frame.height,
);
self.window.set_preview(slint::Image::from_rgba8(buffer));
self.window.set_has_frame(true);
*self.started.borrow_mut() = None;
}
self.window.set_audio_level(session.feed.audio_level());
if self
.started
.borrow()
.is_some_and(|time| time.elapsed() > Duration::from_secs(10))
{
error = Some(
"No frames received. Capture stopped; select the source again.".into(),
);
}
}
if let Some(error) = error {
self.stop();
self.report_error(&error);
}
if let Some(message) = self.error.borrow().as_ref() {
self.window.set_error(message.to_string().into());
}
}
}
impl Drop for Controller {
fn drop(&mut self) {
self.stop();
}
}
}
fn sync_palette(main: &MainWindow, dialog: &ScreenShareWindow) {
use crate::ui::slint::Theme;
let source = main.global::<Theme>();
let target = dialog.global::<Theme>();
target.set_bg_base(source.get_bg_base());
target.set_bg_surface(source.get_bg_surface());
target.set_bg_rail(source.get_bg_rail());
target.set_bg_hover(source.get_bg_hover());
target.set_bg_interactive(source.get_bg_interactive());
target.set_bg_elevated(source.get_bg_elevated());
target.set_selected(source.get_selected());
target.set_border(source.get_border());
target.set_accent(source.get_accent());
target.set_text_primary(source.get_text_primary());
target.set_text_secondary(source.get_text_secondary());
target.set_text_muted(source.get_text_muted());
target.set_text_disabled(source.get_text_disabled());
target.set_danger(source.get_danger());
target.set_success(source.get_success());
target.set_font_size(source.get_font_size());
target.set_on_accent(source.get_on_accent());
}
#[cfg(test)]
mod message_tests {
use super::*;
use crate::ui::i18n::{Language, Message, format_in};
fn render(language: Language, error: &str) -> String {
match media_message(error) {
Message::App(source, args) => format_in(language, source, &args),
Message::Raw(_) => panic!("capture errors retain a semantic key"),
}
}
#[test]
fn media_errors_translate_without_reprocessing_external_details() {
assert_eq!(
render(Language::Russian, "Screen selection cancelled"),
"Выбор экрана отменён."
);
assert_eq!(
render(Language::English, "Screen selection cancelled"),
"Screen selection cancelled"
);
assert_eq!(
render(Language::Russian, "Capture stopped: plugin {error} failed"),
"Захват остановлен: plugin {error} failed"
);
assert_eq!(
render(
Language::Russian,
"Missing GStreamer plugin: pipewiresrc. Install the PipeWire and base plugins."
),
"Отсутствует плагин GStreamer: pipewiresrc. Установи плагины PipeWire и базовый набор."
);
assert_eq!(
render(Language::Russian, "org.example.Error {error}"),
"Ошибка захвата: org.example.Error {error}"
);
}
}

View file

@ -1,6 +1,8 @@
pub mod appearance;
pub mod avatar;
pub mod bridge;
pub mod i18n;
pub mod media;
pub mod preferences;
pub mod slint;
pub mod state;

View file

@ -37,10 +37,10 @@ export component AvatarCropper inherits Rectangle {
VerticalLayout {
padding: 18px; spacing: 8px; alignment: start;
HorizontalLayout {
Text { text: "Выбрать область фото"; color: Theme.text-primary; font-size: Theme.font-size + 5px; font-weight: 600; horizontal-stretch: 1; vertical-alignment: center; }
Text { text: @tr("Crop photo"); color: Theme.text-primary; font-size: Theme.font-size + 5px; font-weight: 600; horizontal-stretch: 1; vertical-alignment: center; }
ActionButton { text: "×"; width: 30px; quiet: true; clicked => { root.cancel(); } }
}
Text { text: "Перетащи фото и выбери масштаб."; color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); }
Text { text: @tr("Drag the photo and adjust the zoom."); color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); }
Rectangle { height: 4px; }
HorizontalLayout {
Rectangle { horizontal-stretch: 1; }
@ -48,7 +48,7 @@ export component AvatarCropper inherits Rectangle {
width: root.frame-size; height: root.frame-size;
clip: true; background: Theme.bg-surface;
accessible-role: image;
accessible-label: "Область фото. Перетаскивай изображение, чтобы изменить кадрирование.";
accessible-label: @tr("Photo crop area. Drag the image to adjust the crop.");
Image {
source: root.avatar-source;
width: root.source-width * root.cover-scale * 1px;
@ -100,16 +100,16 @@ export component AvatarCropper inherits Rectangle {
ActionButton { text: "+"; width: 32px; clicked => { root.set-zoom(root.zoom + 0.1); } }
}
HorizontalLayout {
Text { text: "Масштаб " + Math.round(root.zoom * 100) + "%"; color: Theme.text-muted; font-size: Math.max(Theme.font-size - 4px, 11px); vertical-alignment: center; horizontal-stretch: 1; }
ActionButton { text: "Сбросить кадр"; quiet: true; clicked => { root.crop-moved(0,0); root.set-zoom(1); } }
Text { text: @tr("Zoom {}%", Math.round(root.zoom * 100)); color: Theme.text-muted; font-size: Math.max(Theme.font-size - 4px, 11px); vertical-alignment: center; horizontal-stretch: 1; }
ActionButton { text: @tr("Reset crop"); quiet: true; clicked => { root.crop-moved(0,0); root.set-zoom(1); } }
}
if root.error != "" : Text { text: root.error; color: Theme.danger; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; }
Rectangle { vertical-stretch: 1; }
HorizontalLayout {
spacing: 9px;
ActionButton { text: "Отмена"; quiet: true; clicked => { root.cancel(); } }
ActionButton { text: @tr("Cancel"); quiet: true; clicked => { root.cancel(); } }
Rectangle { horizontal-stretch: 1; }
ActionButton { text: "Использовать фото"; active: true; clicked => { root.confirm(); } }
ActionButton { text: @tr("Use photo"); active: true; clicked => { root.confirm(); } }
}
}
}

View file

@ -43,7 +43,7 @@ component MessageRow inherits Rectangle {
if root.message.show_author : HorizontalLayout {
spacing: 9px;
Text { text: root.message.sender_name; color: Theme.accent; font-size: Math.max(11px, Theme.font-size * 0.875); font-weight: 600; overflow: elide; }
Text { text: root.message.timestamp + (root.message.edited ? " · изменено" : ""); color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.6875); }
Text { text: root.message.timestamp + (root.message.edited ? @tr(" · edited") : ""); color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.6875); }
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; }
@ -57,9 +57,9 @@ component MessageRow inherits Rectangle {
HorizontalLayout {
spacing: 3px;
ActionButton { text: "👍"; quiet: true; clicked => { root.react(root.message.message_id, "👍"); } }
ActionButton { text: "Ответить"; quiet: true; clicked => { root.reply-to-msg(root.message.message_id); } }
if root.message.is_own : ActionButton { text: "Править"; quiet: true; clicked => { root.edit-msg(root.message.message_id); } }
if root.message.is_own : ActionButton { text: "Удалить"; danger: true; quiet: true; clicked => { root.delete-msg(root.message.message_id); } }
ActionButton { text: @tr("Reply"); quiet: true; clicked => { root.reply-to-msg(root.message.message_id); } }
if root.message.is_own : ActionButton { text: @tr("Edit"); quiet: true; clicked => { root.edit-msg(root.message.message_id); } }
if root.message.is_own : ActionButton { text: @tr("Delete"); danger: true; quiet: true; clicked => { root.delete-msg(root.message.message_id); } }
}
}
}
@ -97,9 +97,9 @@ export component ChatPanel inherits Rectangle {
padding-left: 22px; padding-right: 16px; spacing: 12px;
Text { text: root.is-dm ? "@" : "#"; color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 1.4375); width: 20px; vertical-alignment: center; }
Text { text: root.is-dm ? root.dm-partner-name : root.active-channel-name; color: Theme.text-primary; font-size: Math.max(11px, Theme.font-size * 1.0); font-weight: 600; overflow: elide; vertical-alignment: center; }
if root.e2ee-enabled : Text { text: "Сквозное шифрование"; color: Theme.success; font-size: Math.max(11px, Theme.font-size * 0.6875); }
if root.e2ee-enabled : Text { text: @tr("End-to-end encrypted"); color: Theme.success; font-size: Math.max(11px, Theme.font-size * 0.6875); }
Rectangle { horizontal-stretch: 1; }
if !root.is-dm : ActionButton { text: "Участники"; active: root.members-visible; clicked => { root.toggle-members(); } }
if !root.is-dm : ActionButton { text: @tr("Members"); active: root.members-visible; clicked => { root.toggle-members(); } }
}
}
HorizontalLayout {
@ -111,7 +111,7 @@ export component ChatPanel inherits Rectangle {
VerticalLayout {
spacing: 0;
if root.messages.length == 0 : Text {
text: root.is-dm ? "Сообщений пока нет. Напиши первым." : "В этом канале пока нет сообщений.";
text: root.is-dm ? @tr("No messages yet. Say hello.") : @tr("No messages in this channel yet.");
color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.875); wrap: word-wrap;
}
for msg in root.messages: MessageRow {
@ -131,7 +131,7 @@ export component ChatPanel inherits Rectangle {
height: 34px; background: Theme.bg-elevated;
HorizontalLayout {
padding-left: 16px; padding-right: 16px; spacing: 9px;
Text { text: "Ответ " + root.replying-to-sender; color: Theme.accent; font-size: Math.max(11px, Theme.font-size * 0.75); }
Text { text: @tr("Reply to {}", root.replying-to-sender); color: Theme.accent; font-size: Math.max(11px, Theme.font-size * 0.75); }
Text { text: root.replying-to-content; color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.75); horizontal-stretch: 1; overflow: elide; }
ActionButton { text: "×"; quiet: true; width: 28px; clicked => { root.cancel-reply(); } }
}
@ -160,12 +160,12 @@ export component ChatPanel inherits Rectangle {
}
}
ActionButton {
text: "Отправить";
text: @tr("Send");
clicked => { root.send-message(root.is-dm ? "" : root.active-channel-id, root.input-text); }
}
}
}
Text { text: "Enter — отправить · Shift+Enter — новая строка"; color: Theme.text-disabled; font-size: Math.max(11px, Theme.font-size * 0.6875); height: 18px; }
Text { text: @tr("Enter to send · Shift+Enter for a new line"); color: Theme.text-disabled; font-size: Math.max(11px, Theme.font-size * 0.6875); height: 18px; }
}
}
}
@ -175,7 +175,7 @@ export component ChatPanel inherits Rectangle {
content-width: self.width;
VerticalLayout {
padding: 16px; spacing: 12px;
Text { text: "Участники — " + root.members.length; color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.75); height: 28px; }
Text { text: @tr("Members — {}", root.members.length); color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.75); height: 28px; }
for member in root.members: HorizontalLayout {
height: 38px; spacing: 9px;
Rectangle { width: 28px; height: 28px; background: Theme.avatar-bg; border-radius: 11px; Text { text: member.avatar_text; color: Theme.accent; font-size: Math.max(11px, Theme.font-size * 0.6875); horizontal-alignment: center; vertical-alignment: center; } }

View file

@ -23,7 +23,7 @@ export component ConnectScreen inherits Rectangle {
Image { source: @image-url("assets/vnox-mark.svg"); width: 32px; height: 32px; image-fit: contain; }
Text { text: "Vnox"; color: Theme.text-primary; font-size: Math.max(11px, Theme.font-size * 1.1875); font-weight: 700; }
Rectangle { horizontal-stretch: 1; }
ActionButton { text: "Настройки"; quiet: true; clicked => { root.open-settings(); } }
ActionButton { text: @tr("Settings"); quiet: true; clicked => { root.open-settings(); } }
}
Rectangle { vertical-stretch: 1; }
HorizontalLayout {
@ -33,9 +33,9 @@ export component ConnectScreen inherits Rectangle {
background: Theme.bg-surface; border-radius: 14px;
VerticalLayout {
padding: 28px; spacing: 15px;
Text { text: "Подключиться к серверу"; color: Theme.text-primary; font-size: Math.max(11px, Theme.font-size * 1.5); font-weight: 600; }
Text { text: "Введи адрес своего сервера или выбери сохранённый."; color: Theme.text-secondary; font-size: Math.max(11px, Theme.font-size * 0.8125); wrap: word-wrap; }
Text { text: "Адрес сервера"; color: Theme.text-secondary; font-size: Math.max(11px, Theme.font-size * 0.75); }
Text { text: @tr("Connect to a server"); color: Theme.text-primary; font-size: Math.max(11px, Theme.font-size * 1.5); font-weight: 600; }
Text { text: @tr("Enter your server address or choose a saved server."); color: Theme.text-secondary; font-size: Math.max(11px, Theme.font-size * 0.8125); wrap: word-wrap; }
Text { text: @tr("Server address"); color: Theme.text-secondary; font-size: Math.max(11px, Theme.font-size * 0.75); }
HorizontalLayout {
spacing: 9px;
Rectangle {
@ -51,23 +51,23 @@ export component ConnectScreen inherits Rectangle {
}
}
}
if !root.connecting : ActionButton { text: "Подключиться"; height: 40px; clicked => { root.connect(root.address-input); } }
if root.connecting : ActionButton { text: "Отмена"; height: 40px; clicked => { root.disconnect(); } }
if !root.connecting : ActionButton { text: @tr("Connect"); height: 40px; clicked => { root.connect(root.address-input); } }
if root.connecting : ActionButton { text: @tr("Cancel"); height: 40px; clicked => { root.disconnect(); } }
}
HorizontalLayout {
ActionButton { text: root.auto-reconnect ? "✓" : "○"; width: 30px; quiet: true; clicked => { root.auto-reconnect = !root.auto-reconnect; root.auto-reconnect-changed(root.auto-reconnect); } }
Text { text: "Переподключаться при потере связи"; color: Theme.text-secondary; font-size: Math.max(11px, Theme.font-size * 0.75); }
Text { text: @tr("Reconnect automatically"); color: Theme.text-secondary; font-size: Math.max(11px, Theme.font-size * 0.75); }
Rectangle { horizontal-stretch: 1; }
}
if root.connecting : Text { text: "Подключение…"; color: Theme.accent; font-size: Math.max(11px, Theme.font-size * 0.8125); }
if root.connecting : Text { text: @tr("Connecting…"); color: Theme.accent; font-size: Math.max(11px, Theme.font-size * 0.8125); }
if root.status-text != "" : Text { text: root.status-text; color: Theme.text-secondary; font-size: Math.max(11px, Theme.font-size * 0.8125); wrap: word-wrap; }
Rectangle { height: 1px; background: Theme.border; }
HorizontalLayout {
Text { text: "Сохранённые серверы"; color: Theme.text-primary; font-size: Math.max(11px, Theme.font-size * 0.875); font-weight: 600; }
Text { text: @tr("Saved servers"); color: Theme.text-primary; font-size: Math.max(11px, Theme.font-size * 0.875); font-weight: 600; }
Rectangle { horizontal-stretch: 1; }
ActionButton { text: "+ Сохранить адрес"; quiet: true; clicked => { root.add-bookmark(root.address-input); } }
ActionButton { text: @tr("+ Save address"); quiet: true; clicked => { root.add-bookmark(root.address-input); } }
}
if root.bookmarks.length == 0 : Text { text: "Сохранённых серверов пока нет."; color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.75); }
if root.bookmarks.length == 0 : Text { text: @tr("No saved servers yet."); color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.75); }
for server in root.bookmarks: HorizontalLayout {
height: 48px; spacing: 8px;
VerticalLayout {
@ -75,7 +75,7 @@ export component ConnectScreen inherits Rectangle {
Text { text: server.name; color: Theme.text-primary; font-size: Math.max(11px, Theme.font-size * 0.875); overflow: elide; }
Text { text: server.address; color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.6875); overflow: elide; }
}
ActionButton { text: "Войти"; quiet: true; clicked => { if !root.connecting { root.connect(server.address); } } }
ActionButton { text: @tr("Join"); quiet: true; clicked => { if !root.connecting { root.connect(server.address); } } }
ActionButton { text: "×"; width: 28px; quiet: true; clicked => { root.remove-bookmark(server.address); } }
}
}
@ -83,6 +83,6 @@ export component ConnectScreen inherits Rectangle {
Rectangle { horizontal-stretch: 1; }
}
Rectangle { vertical-stretch: 1; }
Text { text: "Твой сервер. Твоё сообщество."; color: Theme.text-disabled; font-size: Math.max(11px, Theme.font-size * 0.75); horizontal-alignment: center; }
Text { text: @tr("Your server. Your community."); color: Theme.text-disabled; font-size: Math.max(11px, Theme.font-size * 0.75); horizontal-alignment: center; }
}
}

View file

@ -1,6 +1,6 @@
import { Theme, ActionButton } from "theme.slint";
export struct FriendItem { user_id: string, nickname: string, status: string }
export struct FriendItem { user_id: string, nickname: string, status: string, status_label: string }
export component FriendsPanel inherits Rectangle {
in-out property <[FriendItem]> friends;
@ -22,11 +22,11 @@ export component FriendsPanel inherits Rectangle {
height: 56px; border-width: 1px; border-color: Theme.border;
HorizontalLayout {
padding-left: 22px; padding-right: 16px; spacing: 10px;
Text { text: "Друзья"; color: Theme.text-primary; font-size: Math.max(11px, Theme.font-size * 1.0); font-weight: 600; }
ActionButton { text: "В сети"; active: root.active-tab == "online"; quiet: true; clicked => { root.tab-changed("online"); } }
ActionButton { text: "Все"; active: root.active-tab == "all"; quiet: true; clicked => { root.tab-changed("all"); } }
ActionButton { text: "Запросы"; active: root.active-tab == "pending"; quiet: true; clicked => { root.tab-changed("pending"); } }
ActionButton { text: "Блокировки"; active: root.active-tab == "blocked"; quiet: true; clicked => { root.tab-changed("blocked"); } }
Text { text: @tr("Friends"); color: Theme.text-primary; font-size: Math.max(11px, Theme.font-size * 1.0); font-weight: 600; }
ActionButton { text: @tr("Online"); active: root.active-tab == "online"; quiet: true; clicked => { root.tab-changed("online"); } }
ActionButton { text: @tr("All"); active: root.active-tab == "all"; quiet: true; clicked => { root.tab-changed("all"); } }
ActionButton { text: @tr("Requests"); active: root.active-tab == "pending"; quiet: true; clicked => { root.tab-changed("pending"); } }
ActionButton { text: @tr("Blocked"); active: root.active-tab == "blocked"; quiet: true; clicked => { root.tab-changed("blocked"); } }
Rectangle { horizontal-stretch: 1; }
}
}
@ -41,9 +41,9 @@ export component FriendsPanel inherits Rectangle {
TextInput { text <=> root.add-friend-input; color: Theme.text-primary; font-size: Math.max(11px, Theme.font-size * 0.875); single-line: true; edited => { root.input-edited(self.text); } accepted => { root.add-friend(root.add-friend-input); } }
}
}
ActionButton { text: "Добавить по ID"; height: 38px; clicked => { root.add-friend(root.add-friend-input); } }
ActionButton { text: @tr("Add by ID"); height: 38px; clicked => { root.add-friend(root.add-friend-input); } }
}
Text { text: root.active-tab == "pending" ? "Входящие запросы" : root.active-tab == "blocked" ? "Заблокированные пользователи" : root.active-tab == "online" ? "Друзья в сети" : "Все друзья"; color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.75); }
Text { text: root.active-tab == "pending" ? @tr("Incoming requests") : root.active-tab == "blocked" ? @tr("Blocked users") : root.active-tab == "online" ? @tr("Online friends") : @tr("All friends"); color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.75); }
Flickable {
content-width: self.width;
VerticalLayout {
@ -59,10 +59,10 @@ export component FriendsPanel inherits Rectangle {
VerticalLayout {
spacing: 2px; horizontal-stretch: 1;
Text { text: friend.nickname; color: Theme.text-primary; font-size: Math.max(11px, Theme.font-size * 0.875); }
Text { text: friend.status; color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.6875); }
Text { text: friend.status_label; color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.6875); }
}
ActionButton { text: "Написать"; quiet: true; clicked => { root.start-dm(friend.user_id); } }
ActionButton { text: "Удалить"; quiet: true; danger: true; clicked => { root.remove-friend(friend.user_id); } }
ActionButton { text: @tr("Message"); quiet: true; clicked => { root.start-dm(friend.user_id); } }
ActionButton { text: @tr("Delete"); quiet: true; danger: true; clicked => { root.remove-friend(friend.user_id); } }
}
}
for friend in root.pending-requests: Rectangle {
@ -71,8 +71,8 @@ export component FriendsPanel inherits Rectangle {
HorizontalLayout {
padding: 10px; spacing: 10px;
Text { text: friend.nickname; color: Theme.text-primary; font-size: Math.max(11px, Theme.font-size * 0.875); horizontal-stretch: 1; }
ActionButton { text: "Принять"; clicked => { root.accept-friend(friend.user_id); } }
ActionButton { text: "Отклонить"; danger: true; quiet: true; clicked => { root.decline-friend(friend.user_id); } }
ActionButton { text: @tr("Accept"); clicked => { root.accept-friend(friend.user_id); } }
ActionButton { text: @tr("Decline"); danger: true; quiet: true; clicked => { root.decline-friend(friend.user_id); } }
}
}
for user in root.blocked-users: Rectangle {
@ -80,9 +80,9 @@ export component FriendsPanel inherits Rectangle {
height: 40px;
Text { text: user; color: Theme.text-secondary; font-size: Math.max(11px, Theme.font-size * 0.8125); overflow: elide; }
}
if root.friends.length == 0 && (root.active-tab == "all" || root.active-tab == "online") : Text { text: "Список друзей пока пуст. Добавь друга по его ID."; color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.875); wrap: word-wrap; }
if root.pending-requests.length == 0 && root.active-tab == "pending" : Text { text: "Новых запросов нет."; color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.875); }
if root.blocked-users.length == 0 && root.active-tab == "blocked" : Text { text: "Список блокировок пуст."; color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.875); }
if root.friends.length == 0 && (root.active-tab == "all" || root.active-tab == "online") : Text { text: @tr("No friends yet. Add someone using their ID."); color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.875); wrap: word-wrap; }
if root.pending-requests.length == 0 && root.active-tab == "pending" : Text { text: @tr("No new requests."); color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.875); }
if root.blocked-users.length == 0 && root.active-tab == "blocked" : Text { text: @tr("No blocked users."); color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.875); }
Rectangle { vertical-stretch: 1; }
}
}

View file

@ -1,3 +1,4 @@
export { ScreenShareWindow } from "screen-share.slint";
export { UnlockWindow } from "unlock.slint";
export { Theme } from "theme.slint";
import { Theme, ActionButton } from "theme.slint";
@ -77,6 +78,8 @@ export component MainWindow inherits Window {
in-out property <float> voice-bitrate: 64.0;
in-out property <int> vad-mode: 0;
in-out property <float> volume: 100.0;
in-out property <string> language-choice: "system";
callback language-selected(string);
in-out property <string> theme-mode: "dark";
in-out property <string> theme-css;
in-out property <string> theme-file-path;
@ -124,6 +127,7 @@ export component MainWindow inherits Window {
callback friends-tab-changed(string);
callback friend-input-edited(string);
callback open-settings();
callback open-screen-share();
callback show-voice-view();
callback show-friends-view();
callback audio-settings-changed(int, int, float, int, float);
@ -258,6 +262,7 @@ export component MainWindow inherits Window {
start-dm(id) => { root.start-dm(id); }
}
if root.show-voice : VoicePanel {
preview-screen => { root.open-screen-share(); }
members: root.voice-members;
mic-enabled: root.mic-enabled;
deafened: root.deafened;
@ -273,6 +278,8 @@ export component MainWindow inherits Window {
}
}
if root.settings-open : SettingsWindow {
language-choice <=> root.language-choice;
language-selected(choice) => { root.language-selected(choice); }
own-avatar: root.own-avatar;
has-avatar: root.has-avatar;
avatar-error: root.avatar-error;
@ -338,11 +345,11 @@ export component MainWindow inherits Window {
background: Theme.bg-surface; border-radius: 10px;
VerticalLayout {
padding: 22px; spacing: 12px;
Text { text: "Удалить сообщение?"; font-size: Math.max(11px, Theme.font-size * 1.1875); color: Theme.text-primary; }
Text { text: "Это действие нельзя отменить."; font-size: Math.max(11px, Theme.font-size * 0.8125); color: Theme.text-muted; }
Text { text: @tr("Delete message?"); font-size: Math.max(11px, Theme.font-size * 1.1875); color: Theme.text-primary; }
Text { text: @tr("This cannot be undone."); font-size: Math.max(11px, Theme.font-size * 0.8125); color: Theme.text-muted; }
HorizontalLayout {
ActionButton { text: "Отмена"; clicked => { root.pending-delete-id = ""; } }
ActionButton { text: "Удалить"; danger: true; clicked => { root.delete-msg(root.pending-delete-id); root.pending-delete-id = ""; } }
ActionButton { text: @tr("Cancel"); clicked => { root.pending-delete-id = ""; } }
ActionButton { text: @tr("Delete"); danger: true; clicked => { root.delete-msg(root.pending-delete-id); root.pending-delete-id = ""; } }
}
}
}

View file

@ -0,0 +1,58 @@
import { DeviceSelect } from "controls.slint";
import { Theme, ActionButton } from "theme.slint";
export component ScreenShareWindow inherits Window {
title: @tr("Screen preview");
preferred-width: 820px; preferred-height: 740px; min-width: 640px; min-height: 650px;
background: Theme.bg-base;
in-out property <image> preview;
in-out property <bool> has-frame;
in-out property <bool> capable;
in-out property <bool> busy;
in-out property <bool> running;
in-out property <string> error;
in-out property <[string]> audio-sources;
in-out property <int> source-index;
in-out property <int> audio-mode;
in-out property <float> audio-level;
callback refresh-audio();
callback choose-source();
callback stop-capture();
callback audio-mode-changed();
VerticalLayout {
padding: 28px; spacing: 14px;
Text { text: @tr("Choose what you share"); color: Theme.text-primary; font-size: 24px; font-weight: 600; }
Text { text: @tr("Video, application audio and your microphone stay separate."); color: Theme.text-secondary; wrap: word-wrap; }
Rectangle {
min-height: 270px; vertical-stretch: 1; background: Theme.bg-rail; border-radius: 10px;
Image { visible: root.has-frame; source: root.preview; image-fit: contain; }
if !root.has-frame : Text { text: root.busy ? @tr("Choose a screen or window in the system dialog…") : @tr("Your preview appears here after you choose a source."); color: Theme.text-muted; wrap: word-wrap; horizontal-alignment: center; vertical-alignment: center; }
if root.running : Rectangle {
x: 12px; y: 12px; width: 132px; height: 28px; border-radius: 5px; background: Theme.bg-surface;
Text { text: @tr("LOCAL PREVIEW"); color: Theme.accent; font-size: 11px; horizontal-alignment: center; vertical-alignment: center; }
}
}
Text { text: @tr("Share audio"); color: Theme.text-primary; font-weight: 600; }
if root.capable && !root.running && !root.busy : HorizontalLayout {
mode := DeviceSelect { model: [@tr("No audio"), @tr("One application"), @tr("System output")]; current-index <=> root.audio-mode; selected => { root.audio-mode-changed(); } }
source := DeviceSelect { visible: root.audio-mode > 0; model: root.audio-sources; current-index <=> root.source-index; horizontal-stretch: 1; }
ActionButton { text: @tr("Refresh"); clicked => { root.refresh-audio(); } }
}
if root.audio-mode == 2 : Text { text: @tr("System output includes notifications and other applications. Select it only if you intend to share all of that output."); color: Theme.danger; wrap: word-wrap; }
if root.audio-mode == 1 : Text { text: @tr("Only a currently playing application can be selected. If it closes, capture stops without switching sources."); color: Theme.text-muted; wrap: word-wrap; }
if root.running && root.audio-mode > 0 : Rectangle {
height: 5px; background: Theme.bg-interactive; border-radius: 2px;
Rectangle { width: parent.width * root.audio-level; background: Theme.success; border-radius: 2px; }
}
Text { text: @tr("Microphone uses your existing voice controls. This preview never enables or mixes it."); color: Theme.text-secondary; wrap: word-wrap; }
Rectangle {
height: note.preferred-height + 24px; background: Theme.bg-surface; border-radius: 8px;
note := Text { x: 12px; y: 12px; width: parent.width - 24px; text: root.capable ? @tr("Local capture is available. Broadcasting to other members is not available until the media transport is connected.") : @tr("Screen capture is not available in this build."); color: Theme.text-muted; wrap: word-wrap; }
}
if root.error != "" : Text { text: root.error; color: Theme.danger; wrap: word-wrap; }
HorizontalLayout {
Text { text: root.running && root.has-frame ? @tr("Preview active · not broadcasting") : @tr("Nothing is being broadcast"); color: Theme.text-muted; vertical-alignment: center; horizontal-stretch: 1; }
if root.capable : ActionButton { text: root.running || root.busy ? @tr("Stop") : @tr("Choose screen or window"); clicked => { if root.running || root.busy { root.stop-capture(); } else { root.choose-source(); } } }
}
}
}

View file

@ -60,6 +60,8 @@ export component SettingsWindow inherits Rectangle {
in-out property <string> import-keyfile-input;
in-out property <string> import-pass-input;
in-out property <string> import-error;
in-out property <string> language-choice: "system";
callback language-selected(string);
in-out property <string> theme-mode;
in-out property <string> theme-css;
in-out property <string> theme-file-path;
@ -88,15 +90,15 @@ export component SettingsWindow inherits Rectangle {
width: 236px; background: Theme.bg-surface;
VerticalLayout {
padding-left: 16px; padding-right: 16px; padding-top: 32px; padding-bottom: 20px; spacing: 7px;
Text { text: "Настройки"; color: Theme.text-primary; font-size: Theme.font-size + 6px; font-weight: 700; height: 46px; }
SettingsNav { label: "Звук и микрофон"; detail: "Устройства и передача"; mark: "◖"; active: root.active-tab == "audio"; clicked => { root.active-tab = "audio"; } }
SettingsNav { label: "Внешний вид"; detail: "Темы, цвета и текст"; mark: "Aa"; active: root.active-tab == "appearance"; clicked => { root.active-tab = "appearance"; } }
SettingsNav { label: "Профиль и ключи"; detail: "Защита и резервная копия"; mark: "◇"; active: root.active-tab == "identity"; clicked => { root.active-tab = "identity"; } }
Text { text: @tr("Settings"); color: Theme.text-primary; font-size: Theme.font-size + 6px; font-weight: 700; height: 46px; }
SettingsNav { label: @tr("Audio & microphone"); detail: @tr("Devices and voice input"); mark: "◖"; active: root.active-tab == "audio"; clicked => { root.active-tab = "audio"; } }
SettingsNav { label: @tr("Appearance"); detail: @tr("Themes, colours and text"); mark: "Aa"; active: root.active-tab == "appearance"; clicked => { root.active-tab = "appearance"; } }
SettingsNav { label: @tr("Profile and keys"); detail: @tr("Security and backup"); mark: "◇"; active: root.active-tab == "identity"; clicked => { root.active-tab = "identity"; } }
Rectangle { vertical-stretch: 1; }
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: "Настройки этого устройства"; color: Theme.text-disabled; font-size: Math.max(Theme.font-size - 5px, 11px); }
ActionButton { text: "Вернуться в приложение"; quiet: true; clicked => { root.close(); } }
Text { text: @tr("Settings for this device"); color: Theme.text-disabled; font-size: Math.max(Theme.font-size - 5px, 11px); }
ActionButton { text: @tr("Back to the app"); quiet: true; clicked => { root.close(); } }
}
}
Rectangle { width: 1px; background: Theme.border; }
@ -108,8 +110,8 @@ export component SettingsWindow inherits Rectangle {
padding-left: 34px; padding-right: 28px; padding-top: 29px; padding-bottom: 20px; spacing: 18px;
VerticalLayout {
spacing: 6px;
Text { text: root.active-tab == "appearance" ? "Внешний вид" : root.active-tab == "identity" ? "Профиль и ключи" : "Звук и микрофон"; color: Theme.text-primary; font-size: Theme.font-size + 12px; font-weight: 700; }
Text { text: root.active-tab == "appearance" ? "Сделай Vnox своим." : root.active-tab == "identity" ? "Твой профиль и его сохранность." : "Голос должен звучать так, как тебе удобно."; color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); }
Text { text: root.active-tab == "appearance" ? @tr("Appearance") : root.active-tab == "identity" ? @tr("Profile and keys") : @tr("Audio & microphone"); color: Theme.text-primary; font-size: Theme.font-size + 12px; font-weight: 700; }
Text { text: root.active-tab == "appearance" ? @tr("Make Vnox yours.") : root.active-tab == "identity" ? @tr("Your profile, kept safe.") : @tr("Make yourself heard, your way."); color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); }
}
Rectangle { horizontal-stretch: 1; }
ActionButton { text: "×"; width: 34px; text-size: 21px; quiet: true; clicked => { root.close(); } }
@ -131,6 +133,8 @@ export component SettingsWindow inherits Rectangle {
audio-changed => { root.audio-changed(); }
}
if root.active-tab == "appearance" : AppearanceSettings {
language-choice <=> root.language-choice;
language-selected(choice) => { root.language-selected(choice); }
theme-mode <=> root.theme-mode;
theme-css <=> root.theme-css;
theme-file-path <=> root.theme-file-path;

View file

@ -35,6 +35,8 @@ component ThemeChoice inherits Rectangle {
}
export component AppearanceSettings inherits Rectangle {
in-out property <string> language-choice: "system";
callback language-selected(string);
in-out property <string> theme-mode;
in-out property <string> theme-css;
in-out property <string> theme-file-path;
@ -51,55 +53,66 @@ export component AppearanceSettings inherits Rectangle {
callback export-theme(string);
VerticalLayout {
spacing: 0; alignment: start;
Text { text: "Тема приложения"; color: Theme.text-primary; font-size: Theme.font-size + 2px; font-weight: 600; }
Text { text: "Один выбор для чата, комнат и настроек. Можно изменить в любой момент."; color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; }
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; }
Rectangle { height: 10px; }
HorizontalLayout {
spacing: 9px;
ActionButton { text: @tr("System default"); active: root.language-choice == "system"; clicked => { root.language-selected("system"); } }
ActionButton { text: "Русский"; active: root.language-choice == "ru"; clicked => { root.language-selected("ru"); } }
ActionButton { text: "English"; active: root.language-choice == "en"; clicked => { root.language-selected("en"); } }
Rectangle { horizontal-stretch: 1; }
}
Rectangle { height: 24px; }
Text { text: @tr("App theme"); color: Theme.text-primary; font-size: Theme.font-size + 2px; font-weight: 600; }
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: "Светлая"; selected: root.theme-mode == "light"; preview-background: #f5f4f2; preview-sidebar: #e6e4e0; preview-ink: #353330; clicked => { root.theme-selected("light"); } }
ThemeChoice { label: "Тёмная"; selected: root.theme-mode == "dark"; preview-background: #272729; preview-sidebar: #202022; preview-ink: #e9e7e4; clicked => { root.theme-selected("dark"); } }
ThemeChoice { label: "Мега-тёмная"; selected: root.theme-mode == "black"; preview-background: #080808; preview-sidebar: #131313; preview-ink: #dedbd5; clicked => { root.theme-selected("black"); } }
ThemeChoice { label: "Своя тема"; selected: root.theme-mode == "custom"; preview-background: Theme.bg-base; preview-sidebar: Theme.bg-surface; preview-ink: Theme.accent; clicked => { root.theme-selected("custom"); } }
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.accent; clicked => { root.theme-selected("custom"); } }
}
Rectangle { height: 29px; }
Rectangle { height: 1px; background: Theme.border; }
Rectangle { height: 24px; }
HorizontalLayout {
Text { text: "Размер текста"; color: Theme.text-primary; font-size: Theme.font-size - 1px; font-weight: 600; horizontal-stretch: 1; }
Text { text: @tr("Text size"); color: Theme.text-primary; font-size: Theme.font-size - 1px; font-weight: 600; horizontal-stretch: 1; }
Text { text: Math.round(root.text-size) + " px"; color: Theme.text-secondary; font-size: Math.max(Theme.font-size - 2px, 11px); horizontal-alignment: right; }
}
Rectangle { height: 9px; }
AudioSlider { minimum: 12; maximum: 22; value <=> root.text-size; changed(value) => { root.text-size-changed(value); } }
Text { text: "Меняет масштаб текста во всём приложении."; color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; }
Text { text: @tr("Adjust text size throughout the app."); color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; }
Rectangle { height: 29px; }
if root.theme-mode == "custom" : VerticalLayout {
spacing: 12px; alignment: start;
Rectangle { height: 1px; background: Theme.border; }
Rectangle { height: 8px; }
HorizontalLayout {
Text { text: "Редактор темы"; color: Theme.text-primary; font-size: Theme.font-size + 2px; font-weight: 600; horizontal-stretch: 1; }
if root.theme-preview : Text { text: "Предпросмотр"; color: Theme.accent; font-size: Math.max(Theme.font-size - 3px, 11px); }
Text { text: @tr("Theme editor"); color: Theme.text-primary; font-size: Theme.font-size + 2px; font-weight: 600; horizontal-stretch: 1; }
if root.theme-preview : Text { text: @tr("Preview"); color: Theme.accent; font-size: Math.max(Theme.font-size - 3px, 11px); }
}
Text { text: "CSS-переменные в блоке :root меняют цвета и размер текста. Обычные CSS-селекторы, стили размещения и внешние ресурсы не поддерживаются."; color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; }
Text { text: @tr("CSS variables in :root control colours and text size. CSS selectors, layout rules and external resources are not supported."); color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; }
ThemeEditor { text <=> root.theme-css; height: 220px; }
HorizontalLayout {
spacing: 9px;
ActionButton { text: "Предпросмотр"; clicked => { root.preview-theme(root.theme-css); } }
ActionButton { text: "Применить"; active: true; clicked => { root.apply-theme(root.theme-css); } }
ActionButton { text: @tr("Preview"); clicked => { root.preview-theme(root.theme-css); } }
ActionButton { text: @tr("Apply"); active: true; clicked => { root.apply-theme(root.theme-css); } }
Rectangle { horizontal-stretch: 1; }
ActionButton { text: "Сбросить"; quiet: true; clicked => { root.reset-theme(); } }
ActionButton { text: @tr("Reset"); quiet: true; clicked => { root.reset-theme(); } }
}
Text { text: "Основные переменные: --vnox-bg, --vnox-surface, --vnox-text, --vnox-accent, --vnox-font-size. Полный список описан в документации тем."; color: Theme.text-muted; font-size: Math.max(Theme.font-size - 4px, 11px); wrap: word-wrap; }
Text { text: @tr("Main variables: --vnox-bg, --vnox-surface, --vnox-text, --vnox-accent, --vnox-font-size. See the theme documentation for the full list."); color: Theme.text-muted; font-size: Math.max(Theme.font-size - 4px, 11px); wrap: word-wrap; }
Rectangle { height: 8px; }
Rectangle { height: 1px; background: Theme.border; }
Rectangle { height: 8px; }
Text { text: "Файл темы"; color: Theme.text-primary; font-size: Theme.font-size - 1px; font-weight: 600; }
Text { text: "Введи локальный путь к .css, чтобы импортировать тему или сохранить её в файл."; color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; }
ThemeInput { text <=> root.theme-file-path; placeholder-text: "Например: /home/user/themes/my-vnox.css"; accepted => { root.import-theme(root.theme-file-path); } }
Text { text: @tr("Theme file"); color: Theme.text-primary; font-size: Theme.font-size - 1px; font-weight: 600; }
Text { text: @tr("Enter a local .css path to import or export a theme."); color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; }
ThemeInput { text <=> root.theme-file-path; placeholder-text: @tr("For example: /home/user/themes/my-vnox.css"); accepted => { root.import-theme(root.theme-file-path); } }
HorizontalLayout {
spacing: 9px;
ActionButton { text: "Импортировать"; clicked => { root.import-theme(root.theme-file-path); } }
ActionButton { text: "Экспортировать"; clicked => { root.export-theme(root.theme-file-path); } }
ActionButton { text: @tr("Import"); clicked => { root.import-theme(root.theme-file-path); } }
ActionButton { text: @tr("Export"); clicked => { root.export-theme(root.theme-file-path); } }
Rectangle { horizontal-stretch: 1; }
}
}

View file

@ -13,10 +13,10 @@ export component AudioSettings inherits Rectangle {
VerticalLayout {
spacing: 0;
alignment: start;
Text { text: "Устройства"; color: Theme.text-primary; font-size: Theme.font-size + 2px; font-weight: 600; }
Text { text: "Выбери, откуда брать голос и куда выводить звук."; color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; }
Text { text: @tr("Devices"); color: Theme.text-primary; font-size: Theme.font-size + 2px; font-weight: 600; }
Text { text: @tr("Choose your microphone and audio output."); color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; }
Rectangle { height: 24px; }
Text { text: "Микрофон"; color: Theme.text-primary; font-size: Math.max(Theme.font-size - 2px, 11px); }
Text { text: @tr("Microphone"); color: Theme.text-primary; font-size: Math.max(Theme.font-size - 2px, 11px); }
Rectangle { height: 9px; }
DeviceSelect {
model: root.input-devices;
@ -24,7 +24,7 @@ export component AudioSettings inherits Rectangle {
selected(value) => { root.audio-changed(); }
}
Rectangle { height: 19px; }
Text { text: "Наушники или колонки"; color: Theme.text-primary; font-size: Math.max(Theme.font-size - 2px, 11px); }
Text { text: @tr("Headphones or speakers"); color: Theme.text-primary; font-size: Math.max(Theme.font-size - 2px, 11px); }
Rectangle { height: 9px; }
DeviceSelect {
model: root.output-devices;
@ -36,36 +36,36 @@ export component AudioSettings inherits Rectangle {
Rectangle { height: 26px; }
HorizontalLayout {
spacing: 20px;
Text { text: "Громкость"; color: Theme.text-primary; font-size: Theme.font-size - 1px; font-weight: 600; horizontal-stretch: 1; }
Text { text: @tr("Volume"); color: Theme.text-primary; font-size: Theme.font-size - 1px; font-weight: 600; horizontal-stretch: 1; }
Text { text: Math.round(root.volume) + "%"; color: Theme.text-secondary; font-size: Math.max(Theme.font-size - 2px, 11px); horizontal-alignment: right; }
}
Text { text: "Общий уровень воспроизведения голосовых комнат."; color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; }
Text { text: @tr("Playback volume for voice rooms."); color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; }
Rectangle { height: 10px; }
AudioSlider { minimum: 0; maximum: 100; value <=> root.volume; changed(value) => { root.audio-changed(); } }
Rectangle { height: 25px; }
Rectangle { height: 1px; background: Theme.border; }
Rectangle { height: 26px; }
Text { text: "Передача голоса"; color: Theme.text-primary; font-size: Theme.font-size + 2px; font-weight: 600; }
Text { text: "Определи, когда тебя слышат остальные."; color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; }
Text { text: @tr("Voice input"); color: Theme.text-primary; font-size: Theme.font-size + 2px; font-weight: 600; }
Text { text: @tr("Choose when others can hear you."); color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; }
Rectangle { height: 18px; }
DeviceSelect {
model: ["Нажми и говори", "Активация голосом", "Открытый микрофон"];
model: [@tr("Push to talk"), @tr("Voice activation"), @tr("Open microphone")];
current-index <=> root.vad-mode;
selected(value) => { root.audio-changed(); }
}
Rectangle { height: 10px; }
Text {
text: root.vad-mode == 0 ? "Удерживай кнопку разговора в голосовой комнате. Отпусти — микрофон перестанет передавать звук." : root.vad-mode == 1 ? "Микрофон передаёт звук, когда обнаружен голос." : "Звук передаётся постоянно, пока микрофон включён.";
text: root.vad-mode == 0 ? @tr("Hold the talk button in a voice room. Release it to stop transmitting.") : root.vad-mode == 1 ? @tr("Your microphone transmits when speech is detected.") : @tr("Audio transmits continuously while the microphone is enabled.");
color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap;
}
Rectangle { height: 24px; }
HorizontalLayout {
Text { text: "Качество голоса"; color: Theme.text-primary; font-size: Theme.font-size - 1px; font-weight: 600; horizontal-stretch: 1; }
Text { text: Math.round(root.voice-bitrate) + " кбит/с"; color: Theme.text-secondary; font-size: Math.max(Theme.font-size - 2px, 11px); horizontal-alignment: right; }
Text { text: @tr("Voice quality"); color: Theme.text-primary; font-size: Theme.font-size - 1px; font-weight: 600; horizontal-stretch: 1; }
Text { text: @tr("{} kbps", Math.round(root.voice-bitrate)); color: Theme.text-secondary; font-size: Math.max(Theme.font-size - 2px, 11px); horizontal-alignment: right; }
}
Rectangle { height: 9px; }
AudioSlider { minimum: 8; maximum: 128; value <=> root.voice-bitrate; changed(value) => { root.audio-changed(); } }
Text { text: "Меньше трафика"; color: Theme.text-disabled; font-size: Math.max(Theme.font-size - 4px, 11px); }
Text { text: @tr("Less bandwidth"); color: Theme.text-disabled; font-size: Math.max(Theme.font-size - 4px, 11px); }
Rectangle { height: 26px; }
}
}

View file

@ -30,28 +30,28 @@ export component IdentitySettings inherits Rectangle {
callback import-keyfile(string, string);
VerticalLayout {
spacing: 0; alignment: start;
Text { text: "Фото профиля"; color: Theme.text-primary; font-size: Theme.font-size + 2px; font-weight: 600; }
Text { text: "Выбери изображение и обрежь его под аватар."; color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; }
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: "Фото"; mask: Theme.bg-base; }
AvatarView { width: 82px; height: 82px; source: root.own-avatar; has-source: root.has-avatar; initials: @tr("Photo"); mask: Theme.bg-base; }
VerticalLayout {
spacing: 9px; alignment: center;
HorizontalLayout {
spacing: 9px;
ActionButton { text: root.has-avatar ? "Изменить фото" : "Выбрать фото"; clicked => { root.choose-avatar(); } }
if root.has-avatar : ActionButton { text: "Удалить"; quiet: true; danger: true; clicked => { root.remove-avatar(); } }
ActionButton { text: 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: "Пока хранится только на этом устройстве."; color: Theme.text-muted; font-size: Math.max(Theme.font-size - 4px, 11px); wrap: word-wrap; }
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; }
}
}
Rectangle { height: 26px; }
Rectangle { height: 1px; background: Theme.border; }
Rectangle { height: 24px; }
Text { text: "Твой ключ"; color: Theme.text-primary; font-size: Theme.font-size + 2px; font-weight: 600; }
Text { text: "Открытый ключ определяет твой профиль. Им можно поделиться; секретный ключ остаётся на устройстве."; color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; }
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; }
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; }
@ -59,86 +59,86 @@ export component IdentitySettings inherits Rectangle {
Rectangle { height: 1px; background: Theme.border; }
Rectangle { height: 24px; }
HorizontalLayout {
Text { text: "Защита на устройстве"; color: Theme.text-primary; font-size: Theme.font-size + 2px; font-weight: 600; horizontal-stretch: 1; }
Text { text: root.vault-enabled ? "● Защищено паролем" : "Без пароля"; color: root.vault-enabled ? Theme.success : Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); vertical-alignment: center; }
Text { text: @tr("Device security"); color: Theme.text-primary; font-size: Theme.font-size + 2px; font-weight: 600; horizontal-stretch: 1; }
Text { text: root.vault-enabled ? @tr("● Passphrase protected") : @tr("No passphrase"); color: root.vault-enabled ? Theme.success : Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); vertical-alignment: center; }
}
Rectangle { height: 6px; }
Text { text: root.vault-enabled ? "При запуске Vnox потребуется пароль для доступа к ключам." : "Добавь пароль, чтобы зашифровать сохранённый секретный ключ."; color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; }
Text { text: root.vault-enabled ? @tr("Vnox will ask for your passphrase to unlock your keys on startup.") : @tr("Add a passphrase to encrypt your saved secret key."); color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; }
Rectangle { height: 15px; }
HorizontalLayout {
spacing: 9px;
ActionButton {
text: root.vault-enabled ? "Изменить пароль" : "Добавить пароль";
text: root.vault-enabled ? @tr("Change passphrase") : @tr("Add passphrase");
clicked => { root.passphrase-modal-open = !root.passphrase-modal-open; root.export-modal-open = false; root.import-modal-open = false; }
}
if root.vault-enabled : ActionButton { text: "Убрать пароль"; danger: true; quiet: true; clicked => { root.confirm-remove = true; } }
if root.vault-enabled : ActionButton { text: @tr("Remove passphrase"); danger: true; quiet: true; clicked => { root.confirm-remove = true; } }
Rectangle { horizontal-stretch: 1; }
}
if root.confirm-remove : VerticalLayout {
spacing: 10px; alignment: start;
Text { text: "Ключ будет сохранён без шифрования. Убрать пароль?"; color: Theme.danger; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; }
Text { text: @tr("Your key will be stored without encryption. Remove the passphrase?"); color: Theme.danger; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; }
HorizontalLayout {
spacing: 9px;
ActionButton { text: "Отмена"; quiet: true; clicked => { root.confirm-remove = false; } }
ActionButton { text: "Убрать пароль"; danger: true; clicked => { root.remove-passphrase(); root.confirm-remove = false; } }
ActionButton { text: @tr("Cancel"); quiet: true; clicked => { root.confirm-remove = false; } }
ActionButton { text: @tr("Remove passphrase"); danger: true; clicked => { root.remove-passphrase(); root.confirm-remove = false; } }
Rectangle { horizontal-stretch: 1; }
}
}
if root.passphrase-modal-open : VerticalLayout {
spacing: 10px; alignment: start;
Rectangle { height: 8px; }
ThemeInput { input-type: InputType.password; text <=> root.passphrase-input; placeholder-text: "Новый пароль · минимум 8 символов"; }
ThemeInput { input-type: InputType.password; text <=> root.passphrase-confirm; placeholder-text: "Повтори пароль"; accepted => { root.set-passphrase(root.passphrase-input, root.passphrase-confirm); } }
ThemeInput { input-type: InputType.password; text <=> root.passphrase-input; placeholder-text: @tr("New passphrase · at least 8 characters"); }
ThemeInput { input-type: InputType.password; text <=> root.passphrase-confirm; placeholder-text: @tr("Repeat passphrase"); accepted => { root.set-passphrase(root.passphrase-input, root.passphrase-confirm); } }
if root.passphrase-error != "" : Text { text: root.passphrase-error; color: Theme.danger; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; }
HorizontalLayout {
spacing: 9px;
ActionButton { text: "Сохранить пароль"; active: true; clicked => { root.set-passphrase(root.passphrase-input, root.passphrase-confirm); } }
ActionButton { text: "Свернуть"; quiet: true; clicked => { root.passphrase-modal-open = false; } }
ActionButton { text: @tr("Save passphrase"); active: true; clicked => { root.set-passphrase(root.passphrase-input, root.passphrase-confirm); } }
ActionButton { text: @tr("Collapse"); quiet: true; clicked => { root.passphrase-modal-open = false; } }
Rectangle { horizontal-stretch: 1; }
}
}
Rectangle { height: 28px; }
Rectangle { height: 1px; background: Theme.border; }
Rectangle { height: 24px; }
Text { text: "Резервная копия"; color: Theme.text-primary; font-size: Theme.font-size + 2px; font-weight: 600; }
Text { text: "Сохрани ключи в безопасном месте, чтобы восстановить профиль на другом устройстве."; color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; }
Text { text: @tr("Backup"); color: Theme.text-primary; font-size: Theme.font-size + 2px; font-weight: 600; }
Text { text: @tr("Keep your keys in a safe place to restore your profile on another device."); color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; }
Rectangle { height: 15px; }
HorizontalLayout {
spacing: 9px;
ActionButton { text: "Экспортировать ключи"; clicked => { root.export-modal-open = !root.export-modal-open; root.passphrase-modal-open = false; root.import-modal-open = false; } }
ActionButton { text: "Импортировать"; quiet: true; clicked => { root.import-modal-open = !root.import-modal-open; root.passphrase-modal-open = false; root.export-modal-open = false; } }
ActionButton { text: @tr("Export keys"); clicked => { root.export-modal-open = !root.export-modal-open; root.passphrase-modal-open = false; root.import-modal-open = false; } }
ActionButton { text: @tr("Import"); quiet: true; clicked => { root.import-modal-open = !root.import-modal-open; root.passphrase-modal-open = false; root.export-modal-open = false; } }
Rectangle { horizontal-stretch: 1; }
}
if root.export-modal-open : VerticalLayout {
spacing: 10px; alignment: start;
Rectangle { height: 8px; }
Text { text: "Пароль резервной копии можно оставить пустым. Такая копия содержит секретный ключ без защиты."; color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; }
ThemeInput { input-type: InputType.password; text <=> root.export-pass-input; placeholder-text: "Пароль копии · необязательно"; }
ThemeInput { input-type: InputType.password; text <=> root.export-pass-confirm; placeholder-text: "Повтори пароль копии"; }
Text { text: @tr("The backup passphrase is optional. Without it, your backup contains an unprotected secret key."); color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; }
ThemeInput { input-type: InputType.password; text <=> root.export-pass-input; placeholder-text: @tr("Backup passphrase · optional"); }
ThemeInput { input-type: InputType.password; text <=> root.export-pass-confirm; placeholder-text: @tr("Repeat backup passphrase"); }
if root.export-error != "" : Text { text: root.export-error; color: Theme.danger; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; }
HorizontalLayout {
spacing: 9px;
ActionButton { text: "Создать копию"; active: true; clicked => { root.export-keyfile(root.export-pass-input, root.export-pass-confirm); } }
ActionButton { text: "Свернуть"; quiet: true; clicked => { root.export-modal-open = false; } }
ActionButton { text: @tr("Create backup"); active: true; clicked => { root.export-keyfile(root.export-pass-input, root.export-pass-confirm); } }
ActionButton { text: @tr("Collapse"); quiet: true; clicked => { root.export-modal-open = false; } }
Rectangle { horizontal-stretch: 1; }
}
if root.export-output != "" : VerticalLayout {
spacing: 8px;
Text { text: "Скопируй содержимое в файл и сохрани отдельно от устройства."; color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; }
Text { text: @tr("Copy this content into a file and keep it separately from this device."); color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; }
ThemeEditor { text: root.export-output; read-only: true; height: 180px; }
}
}
if root.import-modal-open : VerticalLayout {
spacing: 10px; alignment: start;
Rectangle { height: 8px; }
Text { text: "Импорт заменит сохранённый профиль. Сначала сделай резервную копию текущих ключей."; color: Theme.danger; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; }
Text { text: @tr("Importing replaces your saved profile. Back up your current keys first."); color: Theme.danger; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; }
ThemeEditor { text <=> root.import-keyfile-input; height: 150px; }
ThemeInput { input-type: InputType.password; text <=> root.import-pass-input; placeholder-text: "Пароль резервной копии, если он задан"; }
ThemeInput { input-type: InputType.password; text <=> root.import-pass-input; placeholder-text: @tr("Backup passphrase, if set"); }
if root.import-error != "" : Text { text: root.import-error; color: Theme.danger; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; }
HorizontalLayout {
spacing: 9px;
ActionButton { text: "Импортировать и заменить"; danger: true; clicked => { root.import-keyfile(root.import-keyfile-input, root.import-pass-input); } }
ActionButton { text: "Свернуть"; quiet: true; clicked => { root.import-modal-open = false; } }
ActionButton { text: @tr("Import and replace"); danger: true; clicked => { root.import-keyfile(root.import-keyfile-input, root.import-pass-input); } }
ActionButton { text: @tr("Collapse"); quiet: true; clicked => { root.import-modal-open = false; } }
Rectangle { horizontal-stretch: 1; }
}
}

View file

@ -69,7 +69,7 @@ export component Sidebar inherits Rectangle {
background: Theme.bg-rail;
VerticalLayout {
padding: 9px; spacing: 11px;
ActionButton { text: "Личные сообщения"; icon: "home"; height: 44px; text-size: 20px; active: root.show-dms; clicked => { root.show-friends(); } }
ActionButton { text: @tr("Direct messages"); icon: "home"; height: 44px; text-size: 20px; active: root.show-dms; clicked => { root.show-friends(); } }
Rectangle { height: 1px; background: Theme.border; }
ActionButton { text: "V"; height: 44px; text-size: 19px; active: !root.show-dms && root.active-guild-idx < 0; clicked => { root.guild-selected(-1); } }
for guild[index] in root.guilds: ActionButton {
@ -79,7 +79,7 @@ export component Sidebar inherits Rectangle {
clicked => { root.guild-selected(index); }
}
Rectangle { vertical-stretch: 1; }
ActionButton { text: "Настройки"; icon: "settings"; quiet: true; text-size: 19px; clicked => { root.open-settings(); } }
ActionButton { text: @tr("Settings"); icon: "settings"; quiet: true; text-size: 19px; clicked => { root.open-settings(); } }
}
}
Rectangle {
@ -91,31 +91,31 @@ 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 ? "Личные сообщения" : 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; }
ActionButton { text: "Отключиться"; icon: "power"; width: 30px; quiet: true; clicked => { root.disconnect(); } }
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; }
ActionButton { text: @tr("Disconnect"); icon: "power"; width: 30px; quiet: true; clicked => { root.disconnect(); } }
}
}
Flickable {
content-width: self.width;
VerticalLayout {
padding: 10px; spacing: 3px;
if root.show-dms : NavRow { label: "Друзья"; symbol: "@"; clicked => { root.show-friends(); } }
if root.show-dms : Text { text: "Личные сообщения"; color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.75); height: 32px; vertical-alignment: bottom; }
if root.show-dms && root.dm-conversations.length == 0 : Text { text: "Открой профиль друга, чтобы написать ему."; wrap: word-wrap; color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.75); }
if root.show-dms : NavRow { label: @tr("Friends"); symbol: "@"; clicked => { root.show-friends(); } }
if root.show-dms : Text { text: @tr("Direct messages"); color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.75); height: 32px; vertical-alignment: bottom; }
if root.show-dms && root.dm-conversations.length == 0 : Text { text: @tr("Open a friend's profile to send a message."); wrap: word-wrap; color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.75); }
for dm in root.dm-conversations: NavRow {
visible: root.show-dms;
label: dm.name; symbol: "@"; unread: dm.unread;
selected: root.active-dm-id == dm.dm_id;
clicked => { root.dm-selected(dm.dm_id); }
}
if !root.show-dms : Text { text: "Текстовые каналы"; color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.75); height: 32px; vertical-alignment: bottom; }
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 : Text { text: "Голосовые комнаты"; color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.75); height: 40px; vertical-alignment: bottom; }
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: "◖";
@ -132,12 +132,12 @@ export component Sidebar inherits Rectangle {
border-width: 1px; border-color: Theme.border;
VerticalLayout {
padding: 10px; spacing: 5px;
Text { text: "● Голос подключён"; color: Theme.success; font-size: Math.max(11px, Theme.font-size * 0.8125); font-weight: 600; }
Text { text: @tr("● Voice connected"); color: Theme.success; font-size: Math.max(11px, Theme.font-size * 0.8125); font-weight: 600; }
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: "Открыть"; clicked => { root.show-voice(); } }
ActionButton { text: "Выйти"; danger: true; clicked => { root.leave-voice(); } }
ActionButton { text: @tr("Open"); clicked => { root.show-voice(); } }
ActionButton { text: @tr("Leave"); danger: true; clicked => { root.leave-voice(); } }
}
}
}
@ -152,9 +152,9 @@ 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.625); overflow: elide; }
}
ActionButton { text: root.mic-enabled ? "Выключить микрофон" : "Включить микрофон"; icon: "mic"; width: 30px; danger: !root.mic-enabled; quiet: true; clicked => { root.toggle-mic(); } }
ActionButton { text: root.deafened ? "Включить звук" : "Выключить звук"; icon: "headphones"; width: 30px; danger: root.deafened; quiet: true; clicked => { root.toggle-deafen(); } }
ActionButton { text: "Настройки"; icon: "settings"; width: 30px; quiet: true; clicked => { root.open-settings(); } }
ActionButton { text: root.mic-enabled ? @tr("Mute microphone") : @tr("Unmute microphone"); icon: "mic"; width: 30px; danger: !root.mic-enabled; quiet: true; clicked => { root.toggle-mic(); } }
ActionButton { text: root.deafened ? @tr("Undeafen") : @tr("Deafen"); icon: "headphones"; width: 30px; danger: root.deafened; quiet: true; clicked => { root.toggle-deafen(); } }
ActionButton { text: @tr("Settings"); icon: "settings"; width: 30px; quiet: true; clicked => { root.open-settings(); } }
}
}
}

View file

@ -2,7 +2,7 @@ import { Theme, ActionButton } from "theme.slint";
import { ThemeInput } from "controls.slint";
export component UnlockWindow inherits Window {
title: "Vnox — разблокировка";
title: @tr("Vnox — unlock");
icon: @image-url("assets/vnox-mark.svg");
preferred-width: 480px;
preferred-height: 300px;
@ -12,14 +12,14 @@ export component UnlockWindow inherits Window {
VerticalLayout {
padding: 30px; spacing: 14px; alignment: start;
Text { text: "Разблокировать профиль"; color: Theme.text-primary; font-size: Math.max(11px, Theme.font-size * 1.375); font-weight: 600; }
Text { text: "Ключи на этом устройстве защищены паролем."; color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.8125); wrap: word-wrap; }
Text { text: @tr("Unlock profile"); color: Theme.text-primary; font-size: Math.max(11px, Theme.font-size * 1.375); font-weight: 600; }
Text { text: @tr("Your keys on this device are protected by a passphrase."); color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.8125); wrap: word-wrap; }
password := ThemeInput {
input-type: InputType.password;
placeholder-text: "Пароль профиля";
placeholder-text: @tr("Profile passphrase");
accepted => { root.unlock(self.text); }
}
if root.error != "" : Text { text: root.error; color: Theme.danger; font-size: Math.max(11px, Theme.font-size * 0.75); wrap: word-wrap; }
ActionButton { text: "Разблокировать"; clicked => { root.unlock(password.text); } }
ActionButton { text: @tr("Unlock"); clicked => { root.unlock(password.text); } }
}
}

View file

@ -9,6 +9,7 @@ export component VoicePanel inherits Rectangle {
in-out property <string> channel-name;
in-out property <string> activity-banner;
in-out property <bool> push-to-talk;
callback preview-screen();
callback ptt-held(bool);
callback toggle-mic();
callback toggle-deafen();
@ -23,11 +24,12 @@ export component VoicePanel inherits Rectangle {
Text { text: "◖"; color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 1.4375); width: 20px; vertical-alignment: center; }
Text { text: root.channel-name; color: Theme.text-primary; font-size: Math.max(11px, Theme.font-size * 1.0); font-weight: 600; vertical-alignment: center; }
Rectangle { horizontal-stretch: 1; }
ActionButton { text: @tr("Screen preview"); clicked => { root.preview-screen(); } }
}
}
VerticalLayout {
padding: 24px; spacing: 16px;
Text { text: root.members.length + " участников"; color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.8125); }
Text { text: @tr("{n} participant" | "{n} participants" % root.members.length); color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.8125); }
Flickable {
content-width: self.width;
VerticalLayout {
@ -46,20 +48,20 @@ export component VoicePanel inherits Rectangle {
VerticalLayout {
spacing: 5px;
Text { text: member.nickname; color: Theme.text-primary; font-size: Math.max(11px, Theme.font-size * 1.0625); }
Text { text: member.speaking ? "Говорит" : "В голосовой комнате"; color: member.speaking ? Theme.success : Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.75); }
Text { text: member.speaking ? @tr("Speaking") : @tr("In voice"); color: member.speaking ? Theme.success : Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.75); }
}
Rectangle { horizontal-stretch: 1; }
}
}
if root.members.length == 0 : Text { text: "Подключение к голосовой комнате…"; color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.875); }
if root.members.length == 0 : Text { text: @tr("Joining voice…"); color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.875); }
Rectangle { vertical-stretch: 1; }
}
}
if root.push-to-talk : Rectangle {
height: 46px; background: ptt-area.pressed ? Theme.voice-bg : Theme.bg-interactive;
border-radius: 8px; border-width: ptt-focus.has-focus ? 1px : 0px; border-color: Theme.accent;
accessible-role: button; accessible-label: "Удерживать для разговора";
Text { text: ptt-area.pressed ? "Микрофон передаёт звук" : "Удерживай здесь, чтобы говорить"; color: Theme.text-primary; font-size: Math.max(11px, Theme.font-size * 0.875); horizontal-alignment: center; vertical-alignment: center; }
accessible-role: button; accessible-label: @tr("Push to talk");
Text { text: ptt-area.pressed ? @tr("Microphone is transmitting") : @tr("Hold here to talk"); color: Theme.text-primary; font-size: Math.max(11px, Theme.font-size * 0.875); horizontal-alignment: center; vertical-alignment: center; }
ptt-area := TouchArea {
clicked => { ptt-focus.focus(); }
changed pressed => { root.ptt-held(self.pressed); }
@ -74,9 +76,9 @@ export component VoicePanel inherits Rectangle {
HorizontalLayout {
spacing: 10px;
Rectangle { horizontal-stretch: 1; }
ActionButton { text: root.mic-enabled ? "Выключить микрофон" : "Включить микрофон"; danger: !root.mic-enabled; clicked => { root.toggle-mic(); } }
ActionButton { text: root.deafened ? "Включить звук" : "Выключить звук"; danger: root.deafened; clicked => { root.toggle-deafen(); } }
ActionButton { text: "Покинуть комнату"; danger: true; clicked => { root.leave-voice(); } }
ActionButton { text: root.mic-enabled ? @tr("Mute microphone") : @tr("Unmute microphone"); danger: !root.mic-enabled; clicked => { root.toggle-mic(); } }
ActionButton { text: root.deafened ? @tr("Undeafen") : @tr("Deafen"); danger: root.deafened; clicked => { root.toggle-deafen(); } }
ActionButton { text: @tr("Leave room"); danger: true; clicked => { root.leave-voice(); } }
Rectangle { horizontal-stretch: 1; }
}
}

View file

@ -30,7 +30,7 @@ pub struct UiState {
pub connect_input: String,
pub bookmarks: Vec<super::NodeBookmark>,
pub selected_bookmark: usize,
pub status_msg: Option<String>,
pub status_msg: Option<crate::ui::i18n::Message>,
pub channels: Vec<super::Channel>,
pub active_channel: Option<String>,
@ -98,10 +98,10 @@ pub struct UiState {
pub replying_to_content: String,
pub editing_message_id: Option<String>,
pub settings_passphrase_error: Option<String>,
pub settings_passphrase_error: Option<crate::ui::i18n::Message>,
pub settings_export_output: Option<String>,
pub settings_export_error: Option<String>,
pub settings_export_error: Option<crate::ui::i18n::Message>,
pub settings_import_error: Option<String>,
pub settings_import_error: Option<crate::ui::i18n::Message>,
}

View file

@ -22,7 +22,7 @@ pub fn process_net_events(state: &mut AppState) {
};
state.ui.private_mode = private_mode;
if restored {
state.ui.status_msg = Some("reconnected".into());
state.ui.status_msg = Some("Reconnected".into());
let text_channel = state.ui.active_channel.clone();
let voice_channel = state.ui.voice_target.clone();
let net = state.net.clone();
@ -51,7 +51,10 @@ pub fn process_net_events(state: &mut AppState) {
state.voice_channel = None;
state.last_pipeline_config = None;
if will_retry {
state.ui.status_msg = Some(format!("connection lost: {reason}"));
state.ui.status_msg = Some(crate::ui::i18n::Message::with(
"Connection lost: {reason}",
vec![("reason", reason.to_string())],
));
} else {
state.ui.conn = ConnState::Disconnected;
state.ui.voice_target = None;
@ -61,7 +64,10 @@ pub fn process_net_events(state: &mut AppState) {
state.ui.active_channel = None;
state.ui.user_names.clear();
state.ui.rtt_ms = None;
state.ui.status_msg = Some(format!("disconnected: {reason}"));
state.ui.status_msg = Some(crate::ui::i18n::Message::with(
"Disconnected: {reason}",
vec![("reason", reason.to_string())],
));
}
if !will_retry {
state.ui.dm_conversations.clear();
@ -80,8 +86,13 @@ pub fn process_net_events(state: &mut AppState) {
state.voice_channel = None;
state.last_pipeline_config = None;
state.ui.conn = ConnState::Reconnecting { attempt };
state.ui.status_msg =
Some(format!("reconnecting in {delay_secs}s (attempt {attempt})"));
state.ui.status_msg = Some(crate::ui::i18n::Message::with(
"Reconnecting in {delay_secs}s (attempt {attempt})",
vec![
("delay_secs", delay_secs.to_string()),
("attempt", attempt.to_string()),
],
));
}
NetEvent::VoicePacket {
channel_id,
@ -521,7 +532,10 @@ fn chat_handle(ui: &mut UiState, net: &NetHandle, event: NetEvent) {
ui.scroll_bottom = true;
}
NetEvent::Error { message, .. } => {
ui.status_msg = Some(format!("error: {message}"));
ui.status_msg = Some(crate::ui::i18n::Message::with(
"Server error: {message}",
vec![("message", message.to_string())],
));
}
NetEvent::ReactionAdded {
channel_id,
@ -810,7 +824,10 @@ pub fn start_voice(state: &mut AppState, channel_id: &str) {
state.voice_channel = None;
state.last_pipeline_config = Some(cfg);
state.ui.voice = VoiceUiState::Error(e.to_string());
state.ui.status_msg = Some(format!("microphone error: {e}"));
state.ui.status_msg = Some(crate::ui::i18n::Message::with(
"Microphone error: {e}",
vec![("e", e.to_string())],
));
}
}
}

View file

@ -155,6 +155,29 @@ fn native_shell_keeps_drafts_settings_and_models_between_ticks() {
assert!(window.get_settings_open());
assert_eq!(window.get_active_tab(), "identity");
assert_eq!(window.get_export_pass_input(), "not-clobbered");
// Switching native catalogs updates app messages without touching user data or drafts.
state.borrow_mut().ui.status_msg = Some(ui::i18n::Message::with(
"Connection lost: {reason}",
vec![("reason", "server {reason} Settings".into())],
));
let current_theme = window.get_theme_css();
for (locale, expected) in [
("ru", "Соединение потеряно: server {reason} Settings"),
("en", "Connection lost: server {reason} Settings"),
] {
slint::select_bundled_translation(locale).expect("native locale must be bundled");
window.invoke_language_selected(locale.into());
sync();
assert_eq!(window.get_status_text(), expected);
assert_eq!(window.get_input_text(), "черновик");
assert_eq!(window.get_export_pass_input(), "not-clobbered");
assert_eq!(window.get_theme_css(), current_theme);
render(&window, &surface, &format!("settings-identity-{locale}"));
window.set_active_tab("appearance".into());
render(&window, &surface, &format!("settings-appearance-{locale}"));
window.set_active_tab("identity".into());
}
state.borrow_mut().ui.status_msg = None;
window.set_active_tab("audio".into());
render(&window, &surface, "native-settings");
window.invoke_close_settings();
@ -231,6 +254,14 @@ fn native_shell_keeps_drafts_settings_and_models_between_ticks() {
window.set_avatar_zoom(1.2);
window.set_avatar_offset_x(0.1);
window.set_avatar_crop_open(true);
for locale in ["ru", "en"] {
window.invoke_language_selected(locale.into());
assert_eq!(window.get_avatar_zoom(), 1.2);
assert_eq!(window.get_avatar_offset_x(), 0.1);
assert_eq!(window.get_own_avatar(), photo);
assert!(window.get_avatar_crop_open());
render(&window, &surface, &format!("avatar-cropper-{locale}"));
}
render(&window, &surface, "avatar-cropper");
window.invoke_cancel_avatar();
assert!(!window.get_avatar_crop_open());