feat(client): redesign native UI, themes, settings and avatars
Separate conversation drafts and voice view state, add native settings and restricted CSS themes, implement validated avatar cropping, and refresh dependencies with documented desktop compatibility backports.
This commit is contained in:
parent
44d284a568
commit
8e5ab56611
276 changed files with 53546 additions and 3399 deletions
174
src/ui/avatar/bindings.rs
Normal file
174
src/ui/avatar/bindings.rs
Normal file
|
|
@ -0,0 +1,174 @@
|
|||
use std::cell::RefCell;
|
||||
use std::path::PathBuf;
|
||||
use std::rc::Rc;
|
||||
|
||||
use sha2::{Digest, Sha256};
|
||||
use slint::ComponentHandle;
|
||||
|
||||
use super::CropSource;
|
||||
use crate::AppState;
|
||||
use crate::ui::slint::MainWindow;
|
||||
|
||||
fn avatar_path(identity: &str) -> PathBuf {
|
||||
// Scope local photos by account; never place untrusted identity text in a path.
|
||||
let name = hex::encode(Sha256::digest(identity.as_bytes()));
|
||||
dirs::config_dir()
|
||||
.unwrap_or_else(|| PathBuf::from("."))
|
||||
.join("vnox/avatars")
|
||||
.join(format!("{name}.png"))
|
||||
}
|
||||
|
||||
fn sync_crop(window: &MainWindow, source: &CropSource) {
|
||||
window.set_avatar_zoom(source.zoom);
|
||||
window.set_avatar_offset_x(source.offset_x);
|
||||
window.set_avatar_offset_y(source.offset_y);
|
||||
}
|
||||
|
||||
fn begin_crop(window: &MainWindow, pending: &Rc<RefCell<Option<CropSource>>>, source: CropSource) {
|
||||
window.set_avatar_source(source.ui_image());
|
||||
window.set_avatar_source_width(source.width() as f32);
|
||||
window.set_avatar_source_height(source.height() as f32);
|
||||
sync_crop(window, &source);
|
||||
window.set_avatar_error("".into());
|
||||
*pending.borrow_mut() = Some(source);
|
||||
window.set_avatar_crop_open(true);
|
||||
}
|
||||
|
||||
fn discard_crop(window: &MainWindow, pending: &Rc<RefCell<Option<CropSource>>>) {
|
||||
window.set_avatar_crop_open(false);
|
||||
window.set_avatar_source(slint::Image::default());
|
||||
*pending.borrow_mut() = None;
|
||||
}
|
||||
|
||||
pub fn wire(window: &MainWindow, state: &Rc<RefCell<AppState>>, persist: bool) {
|
||||
let pending = Rc::new(RefCell::new(None::<CropSource>));
|
||||
let path = avatar_path(&state.borrow().identity.pubkey_hex);
|
||||
if persist && path.exists() {
|
||||
match CropSource::load(&path) {
|
||||
Ok(source) => {
|
||||
window.set_own_avatar(source.ui_image());
|
||||
window.set_has_avatar(true);
|
||||
}
|
||||
Err(error) => window.set_avatar_error(error.into()),
|
||||
}
|
||||
}
|
||||
{
|
||||
let weak = window.as_weak();
|
||||
let pending = pending.clone();
|
||||
window.on_choose_avatar(move || {
|
||||
let weak = weak.clone();
|
||||
let pending = pending.clone();
|
||||
if let Some(window) = weak.upgrade() {
|
||||
window.set_avatar_error("".into());
|
||||
}
|
||||
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"])
|
||||
.pick_file()
|
||||
.await
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let path = file.path().to_owned();
|
||||
let result = tokio::task::spawn_blocking(move || CropSource::load(&path)).await;
|
||||
if let Some(window) = task_window.upgrade() {
|
||||
match result {
|
||||
Ok(Ok(source)) => begin_crop(&window, &pending, source),
|
||||
Ok(Err(error)) => window.set_avatar_error(error.into()),
|
||||
Err(_) => window.set_avatar_error(
|
||||
"Не удалось обработать фото. Попробуй другое изображение.".into(),
|
||||
),
|
||||
}
|
||||
}
|
||||
});
|
||||
if result.is_err()
|
||||
&& let Some(window) = weak.upgrade()
|
||||
{
|
||||
window.set_avatar_error("Не удалось открыть выбор файла в этом окружении.".into());
|
||||
}
|
||||
});
|
||||
}
|
||||
{
|
||||
let weak = window.as_weak();
|
||||
let pending = pending.clone();
|
||||
window.on_avatar_crop_moved(move |x, y| {
|
||||
if let Some(window) = weak.upgrade()
|
||||
&& let Some(source) = pending.borrow_mut().as_mut()
|
||||
{
|
||||
source.adjust(source.zoom, x, y);
|
||||
sync_crop(&window, source);
|
||||
}
|
||||
});
|
||||
}
|
||||
{
|
||||
let weak = window.as_weak();
|
||||
let pending = pending.clone();
|
||||
window.on_avatar_zoom_changed(move |zoom| {
|
||||
if let Some(window) = weak.upgrade()
|
||||
&& let Some(source) = pending.borrow_mut().as_mut()
|
||||
{
|
||||
source.adjust(zoom, source.offset_x, source.offset_y);
|
||||
sync_crop(&window, source);
|
||||
}
|
||||
});
|
||||
}
|
||||
{
|
||||
let weak = window.as_weak();
|
||||
let pending = pending.clone();
|
||||
let path = path.clone();
|
||||
window.on_confirm_avatar(move || {
|
||||
if let Some(window) = weak.upgrade() {
|
||||
let result = {
|
||||
let source = pending.borrow();
|
||||
source.as_ref().map(|source| {
|
||||
if persist {
|
||||
source.save_to(&path)
|
||||
} else {
|
||||
Ok(source.cropped_ui_image())
|
||||
}
|
||||
})
|
||||
};
|
||||
if let Some(result) = result {
|
||||
match result {
|
||||
Ok(image) => {
|
||||
window.set_own_avatar(image);
|
||||
window.set_has_avatar(true);
|
||||
window.set_avatar_error("".into());
|
||||
discard_crop(&window, &pending);
|
||||
}
|
||||
Err(error) => window.set_avatar_error(error.into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
{
|
||||
let weak = window.as_weak();
|
||||
let pending = pending.clone();
|
||||
window.on_cancel_avatar(move || {
|
||||
if let Some(window) = weak.upgrade() {
|
||||
discard_crop(&window, &pending);
|
||||
window.set_avatar_error("".into());
|
||||
}
|
||||
});
|
||||
}
|
||||
{
|
||||
let weak = window.as_weak();
|
||||
window.on_remove_avatar(move || {
|
||||
if let Some(window) = weak.upgrade() {
|
||||
if persist
|
||||
&& let Err(error) = std::fs::remove_file(&path)
|
||||
&& error.kind() != std::io::ErrorKind::NotFound
|
||||
{
|
||||
window.set_avatar_error(format!("Не удалось удалить фото: {error}").into());
|
||||
return;
|
||||
}
|
||||
window.set_own_avatar(slint::Image::default());
|
||||
window.set_has_avatar(false);
|
||||
window.set_avatar_error("".into());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
261
src/ui/avatar/crop.rs
Normal file
261
src/ui/avatar/crop.rs
Normal file
|
|
@ -0,0 +1,261 @@
|
|||
use std::io::{Cursor, Read};
|
||||
use std::path::Path;
|
||||
|
||||
use image::{DynamicImage, ImageDecoder, ImageFormat, ImageReader};
|
||||
|
||||
const MAX_FILE_BYTES: usize = 10 * 1024 * 1024;
|
||||
const MAX_DIMENSION: u32 = 4096;
|
||||
const OUTPUT_SIZE: u32 = 256;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct CropSource {
|
||||
image: DynamicImage,
|
||||
pub zoom: f32,
|
||||
pub offset_x: f32,
|
||||
pub offset_y: f32,
|
||||
}
|
||||
|
||||
impl CropSource {
|
||||
pub fn load(path: &Path) -> Result<Self, String> {
|
||||
let file =
|
||||
std::fs::File::open(path).map_err(|e| format!("Не удалось открыть фото: {e}"))?;
|
||||
if file.metadata().map_err(|e| e.to_string())?.len() > MAX_FILE_BYTES as u64 {
|
||||
return Err("Фото слишком большое: максимум 10 МБ.".into());
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
file.take(MAX_FILE_BYTES as u64 + 1)
|
||||
.read_to_end(&mut bytes)
|
||||
.map_err(|e| e.to_string())?;
|
||||
Self::decode(&bytes)
|
||||
}
|
||||
|
||||
fn decode(bytes: &[u8]) -> Result<Self, String> {
|
||||
if bytes.len() > MAX_FILE_BYTES {
|
||||
return Err("Фото слишком большое: максимум 10 МБ.".into());
|
||||
}
|
||||
let format = image::guess_format(bytes)
|
||||
.map_err(|_| "Не удалось распознать изображение. Выбери PNG, JPEG или WebP.")?;
|
||||
if ![ImageFormat::Png, ImageFormat::Jpeg, ImageFormat::WebP].contains(&format) {
|
||||
return Err(
|
||||
"Поддерживаются только PNG, JPEG и WebP. Анимации и SVG не поддерживаются.".into(),
|
||||
);
|
||||
}
|
||||
reject_animation(bytes, format)?;
|
||||
let mut limits = image::Limits::default();
|
||||
limits.max_image_width = Some(MAX_DIMENSION);
|
||||
limits.max_image_height = Some(MAX_DIMENSION);
|
||||
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}"))?;
|
||||
if decoder.dimensions().0 > MAX_DIMENSION || decoder.dimensions().1 > MAX_DIMENSION {
|
||||
return Err("Сторона изображения должна быть не больше 4096 пикселей.".into());
|
||||
}
|
||||
let orientation = decoder
|
||||
.orientation()
|
||||
.map_err(|e| format!("Не удалось прочитать ориентацию фото: {e}"))?;
|
||||
let mut image = DynamicImage::from_decoder(decoder)
|
||||
.map_err(|e| format!("Не удалось декодировать фото: {e}"))?;
|
||||
image.apply_orientation(orientation);
|
||||
if image.width() == 0 || image.height() == 0 {
|
||||
return Err("Изображение пустое.".into());
|
||||
}
|
||||
Ok(Self {
|
||||
image,
|
||||
zoom: 1.0,
|
||||
offset_x: 0.0,
|
||||
offset_y: 0.0,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn width(&self) -> u32 {
|
||||
self.image.width()
|
||||
}
|
||||
pub fn height(&self) -> u32 {
|
||||
self.image.height()
|
||||
}
|
||||
|
||||
pub fn ui_image(&self) -> slint::Image {
|
||||
to_ui_image(&self.image)
|
||||
}
|
||||
|
||||
pub fn adjust(&mut self, zoom: f32, x: f32, y: f32) {
|
||||
if !zoom.is_finite() || !x.is_finite() || !y.is_finite() {
|
||||
return;
|
||||
}
|
||||
self.zoom = zoom.clamp(1.0, 3.0);
|
||||
let side = self.width().min(self.height()) as f32 / self.zoom;
|
||||
let max_x = (self.width() as f32 / side - 1.0) / 2.0;
|
||||
let max_y = (self.height() as f32 / side - 1.0) / 2.0;
|
||||
self.offset_x = x.clamp(-max_x, max_x);
|
||||
self.offset_y = y.clamp(-max_y, max_y);
|
||||
}
|
||||
|
||||
pub fn cropped_ui_image(&self) -> slint::Image {
|
||||
to_ui_image(&self.cropped())
|
||||
}
|
||||
|
||||
pub fn cropped(&self) -> DynamicImage {
|
||||
let side = (self.width().min(self.height()) as f32 / self.zoom)
|
||||
.round()
|
||||
.max(1.0) as u32;
|
||||
let left = ((self.width() - side) as f32 / 2.0 - self.offset_x * side as f32)
|
||||
.round()
|
||||
.clamp(0.0, (self.width() - side) as f32) as u32;
|
||||
let top = ((self.height() - side) as f32 / 2.0 - self.offset_y * side as f32)
|
||||
.round()
|
||||
.clamp(0.0, (self.height() - side) as f32) as u32;
|
||||
self.image.crop_imm(left, top, side, side).resize_exact(
|
||||
OUTPUT_SIZE,
|
||||
OUTPUT_SIZE,
|
||||
image::imageops::FilterType::Lanczos3,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn save_to(&self, path: &Path) -> Result<slint::Image, String> {
|
||||
let image = self.cropped();
|
||||
let mut encoded = Cursor::new(Vec::new());
|
||||
image
|
||||
.write_to(&mut encoded, ImageFormat::Png)
|
||||
.map_err(|e| format!("Не удалось подготовить аватар: {e}"))?;
|
||||
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}"))?;
|
||||
if let Err(error) = std::fs::rename(&temporary, path) {
|
||||
let _ = std::fs::remove_file(&temporary);
|
||||
return Err(format!("Не удалось применить аватар: {error}"));
|
||||
}
|
||||
Ok(to_ui_image(&image))
|
||||
}
|
||||
}
|
||||
|
||||
fn reject_animation(bytes: &[u8], format: ImageFormat) -> Result<(), String> {
|
||||
let (mut offset, big_endian) = match format {
|
||||
ImageFormat::Png => (8usize, true),
|
||||
ImageFormat::WebP => (12usize, false),
|
||||
_ => return Ok(()),
|
||||
};
|
||||
while offset.checked_add(8).is_some_and(|end| end <= bytes.len()) {
|
||||
let (length, kind, padding) = if big_endian {
|
||||
let size = u32::from_be_bytes(
|
||||
bytes[offset..offset + 4]
|
||||
.try_into()
|
||||
.map_err(|_| "Повреждённый 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.")?,
|
||||
) as usize;
|
||||
(size, &bytes[offset..offset + 4], 8usize + size % 2)
|
||||
};
|
||||
if kind == b"acTL" || kind == b"ANIM" || kind == b"ANMF" {
|
||||
return Err("Анимированные изображения не поддерживаются. Выбери обычное фото.".into());
|
||||
}
|
||||
offset = offset
|
||||
.checked_add(length)
|
||||
.and_then(|n| n.checked_add(padding))
|
||||
.ok_or("Повреждённое изображение.")?;
|
||||
if offset > bytes.len() {
|
||||
break;
|
||||
} // The decoder reports truncated image details.
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn to_ui_image(image: &DynamicImage) -> slint::Image {
|
||||
let rgba = image.to_rgba8();
|
||||
let pixels = slint::SharedPixelBuffer::<slint::Rgba8Pixel>::clone_from_slice(
|
||||
rgba.as_raw(),
|
||||
rgba.width(),
|
||||
rgba.height(),
|
||||
);
|
||||
slint::Image::from_rgba8(pixels)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use image::{GenericImageView, Rgba};
|
||||
|
||||
fn encoded(image: &DynamicImage) -> Vec<u8> {
|
||||
let mut bytes = Cursor::new(Vec::new());
|
||||
image.write_to(&mut bytes, ImageFormat::Png).unwrap();
|
||||
bytes.into_inner()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounded_crop_covers_square_and_pan_direction_matches_preview() {
|
||||
let pixels = image::RgbaImage::from_fn(400, 200, |x, _| {
|
||||
if x < 200 {
|
||||
Rgba([255, 0, 0, 255])
|
||||
} else {
|
||||
Rgba([0, 0, 255, 255])
|
||||
}
|
||||
});
|
||||
let mut source = CropSource::decode(&encoded(&DynamicImage::ImageRgba8(pixels))).unwrap();
|
||||
source.adjust(2.0, 999.0, 999.0);
|
||||
assert_eq!(source.offset_x, 1.5);
|
||||
assert_eq!(source.offset_y, 0.5);
|
||||
let cropped = source.cropped();
|
||||
assert_eq!(cropped.dimensions(), (256, 256));
|
||||
assert_eq!(cropped.get_pixel(128, 128), Rgba([255, 0, 0, 255]));
|
||||
source.adjust(2.0, -999.0, 0.0);
|
||||
assert_eq!(source.cropped().get_pixel(128, 128), Rgba([0, 0, 255, 255]));
|
||||
let before = source.zoom;
|
||||
source.adjust(f32::NAN, 0.0, 0.0);
|
||||
assert_eq!(source.zoom, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_oversized_dimensions_bad_images_and_unsupported_formats() {
|
||||
assert!(CropSource::decode(b"not an image").is_err());
|
||||
assert!(CropSource::decode(b"<svg xmlns='http://www.w3.org/2000/svg'/>").is_err());
|
||||
assert!(CropSource::decode(b"GIF89a").is_err());
|
||||
assert!(
|
||||
CropSource::decode(&vec![0; MAX_FILE_BYTES + 1])
|
||||
.unwrap_err()
|
||||
.contains("10")
|
||||
);
|
||||
let image = DynamicImage::new_rgba8(MAX_DIMENSION + 1, 1);
|
||||
assert!(CropSource::decode(&encoded(&image)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jpeg_exif_orientation_is_applied_before_crop() {
|
||||
let mut jpeg = Cursor::new(Vec::new());
|
||||
DynamicImage::new_rgb8(2, 3)
|
||||
.write_to(&mut jpeg, ImageFormat::Jpeg)
|
||||
.unwrap();
|
||||
let exif = b"Exif\0\0II\x2a\0\x08\0\0\0\x01\0\x12\x01\x03\0\x01\0\0\0\x06\0\0\0\0\0\0\0";
|
||||
let original = jpeg.into_inner();
|
||||
let mut oriented = original[..2].to_vec();
|
||||
oriented.extend_from_slice(&[0xff, 0xe1]);
|
||||
oriented.extend_from_slice(&((exif.len() + 2) as u16).to_be_bytes());
|
||||
oriented.extend_from_slice(exif);
|
||||
oriented.extend_from_slice(&original[2..]);
|
||||
let source = CropSource::decode(&oriented).unwrap();
|
||||
assert_eq!((source.width(), source.height()), (3, 2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_decode_and_cancel_do_not_replace_existing_avatar() {
|
||||
let path = std::env::temp_dir().join(format!("vnox-avatar-{}.png", uuid::Uuid::new_v4()));
|
||||
let initial = CropSource::decode(&encoded(&DynamicImage::new_rgba8(16, 16))).unwrap();
|
||||
initial.save_to(&path).unwrap();
|
||||
let old = std::fs::read(&path).unwrap();
|
||||
assert!(CropSource::decode(b"broken").is_err());
|
||||
let pending = CropSource::decode(&encoded(&DynamicImage::new_rgba8(32, 32))).unwrap();
|
||||
drop(pending); // Cancel discards pending image without a write.
|
||||
assert_eq!(std::fs::read(&path).unwrap(), old);
|
||||
assert_eq!(image::open(&path).unwrap().dimensions(), (256, 256));
|
||||
std::fs::remove_file(path).unwrap();
|
||||
}
|
||||
}
|
||||
5
src/ui/avatar/mod.rs
Normal file
5
src/ui/avatar/mod.rs
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
mod bindings;
|
||||
mod crop;
|
||||
|
||||
pub use bindings::wire;
|
||||
pub use crop::CropSource;
|
||||
Loading…
Add table
Add a link
Reference in a new issue