diff --git a/.gitignore b/.gitignore index 7f64eb8..aa2ed68 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ target/ .env .env.* !.env.example +TODO.md diff --git a/Cargo.lock b/Cargo.lock index 0276cb2..975e1b3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -242,9 +242,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aeb9553e62312c8756a5979254fc6d7da8bbeb5986a1e17037fab932f7037917" dependencies = [ "clipboard-win", + "image", "log", "objc2 0.6.5", "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-core-graphics", "objc2-foundation 0.3.2", "parking_lot", "percent-encoding", @@ -594,6 +597,12 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + [[package]] name = "byteorder-lite" version = "0.1.0" @@ -974,6 +983,7 @@ dependencies = [ "block2 0.6.2", "coreaudio-rs", "dasp_sample", + "futures", "jni", "js-sys", "libc", @@ -989,6 +999,8 @@ dependencies = [ "objc2-core-audio-types", "objc2-core-foundation", "objc2-foundation 0.3.2", + "portable-atomic", + "pulseaudio", "web-sys", "windows", "windows-core", @@ -1412,6 +1424,17 @@ version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" +[[package]] +name = "enum-primitive-derive" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba7795da175654fe16979af73f81f26a8ea27638d8d9823d317016888a63dc4c" +dependencies = [ + "num-traits", + "quote", + "syn 2.0.119", +] + [[package]] name = "enumflags2" version = "0.7.12" @@ -1489,6 +1512,12 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "fax" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a" + [[package]] name = "fdeflate" version = "0.3.7" @@ -1858,8 +1887,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" dependencies = [ "cfg-if", + "js-sys", "libc", "wasi", + "wasm-bindgen", ] [[package]] @@ -1881,9 +1912,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if", + "js-sys", "libc", "r-efi 6.0.0", "rand_core", + "wasm-bindgen", ] [[package]] @@ -2351,6 +2384,45 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "48ce8546b993eaf241d69ded33b1be6d205dd9857ec879d9d18bd05d3676e144" +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + [[package]] name = "hybrid-array" version = "0.4.15" @@ -2360,6 +2432,64 @@ dependencies = [ "typenum", ] +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + [[package]] name = "i-slint-backend-linuxkms" version = "1.18.1" @@ -2873,10 +3003,13 @@ checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" dependencies = [ "bytemuck", "byteorder-lite", + "color_quant", + "gif", "image-webp", "moxcms", "num-traits", "png", + "tiff", "zune-core", "zune-jpeg", ] @@ -2922,6 +3055,12 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + [[package]] name = "itertools" version = "0.13.0" @@ -3154,6 +3293,12 @@ version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + [[package]] name = "lyon_algorithms" version = "1.0.22" @@ -3267,6 +3412,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" dependencies = [ "libc", + "log", "wasi", "windows-sys 0.61.2", ] @@ -3919,6 +4065,12 @@ dependencies = [ "portable-atomic", ] +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + [[package]] name = "option-ext" version = "0.2.0" @@ -4405,6 +4557,22 @@ dependencies = [ "unicase", ] +[[package]] +name = "pulseaudio" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ba79a4c6904c987cc31fa50e9b750539404511c2dbd9ce95e5e58444177a21e" +dependencies = [ + "bitflags 2.13.2", + "byteorder", + "enum-primitive-derive", + "futures", + "log", + "mio", + "num-traits", + "thiserror 1.0.69", +] + [[package]] name = "pxfm" version = "0.1.30" @@ -4426,6 +4594,63 @@ dependencies = [ "memchr", ] +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash 2.1.3", + "rustls", + "socket2", + "thiserror 2.0.21", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "aws-lc-rs", + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand", + "rand_pcg", + "ring", + "rustc-hash 2.1.3", + "rustls", + "rustls-pki-types", + "slab", + "thiserror 2.0.21", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + [[package]] name = "quote" version = "1.0.47" @@ -4464,6 +4689,15 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core", +] + [[package]] name = "range-alloc" version = "0.1.5" @@ -4614,6 +4848,43 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832" +[[package]] +name = "reqwest" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" +dependencies = [ + "base64", + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "serde", + "serde_json", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + [[package]] name = "resvg" version = "0.48.1" @@ -4802,15 +5073,55 @@ dependencies = [ "zeroize", ] +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + [[package]] name = "rustls-pki-types" version = "1.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" dependencies = [ + "web-time", "zeroize", ] +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation 0.10.1", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + [[package]] name = "rustls-webpki" version = "0.103.16" @@ -4838,6 +5149,15 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "scoped-tls" version = "1.0.1" @@ -4866,6 +5186,29 @@ dependencies = [ "tiny-skia 0.11.4", ] +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.10.1", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "semver" version = "1.0.28" @@ -5359,6 +5702,15 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + [[package]] name = "synstructure" version = "0.13.2" @@ -5503,6 +5855,20 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "tiff" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52" +dependencies = [ + "fax", + "flate2", + "half", + "quick-error", + "weezl", + "zune-jpeg", +] + [[package]] name = "time" version = "0.3.55" @@ -5705,6 +6071,51 @@ version = "1.1.3+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags 2.13.2", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + [[package]] name = "tracing" version = "0.1.44" @@ -5788,6 +6199,12 @@ dependencies = [ "petgraph", ] +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + [[package]] name = "typed-index-collections" version = "3.2.3" @@ -5965,8 +6382,10 @@ name = "vnox-client" version = "0.1.0" dependencies = [ "anyhow", + "arboard", "argon2", "chacha20poly1305", + "chrono", "cpal", "dirs", "ed25519-dalek", @@ -5984,6 +6403,7 @@ dependencies = [ "prost-build", "rand", "rcgen", + "reqwest", "rfd", "rustls", "serde", @@ -6037,6 +6457,15 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" @@ -6253,6 +6682,15 @@ dependencies = [ "web-sys", ] +[[package]] +name = "webpki-root-certs" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "webpki-roots" version = "1.0.11" diff --git a/Cargo.toml b/Cargo.toml index 18f54db..8b818bd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,7 +9,7 @@ version = "0.1.0" edition = "2024" license = "GPL-3.0" authors = ["VNOX Contributors"] -repository = "https://github.com/loki5512344/Vnox" +repository = "https://git.wihuk.pro/boba/VNOX-Client.git" rust-version = "1.94" default-run = "vnox-client" @@ -33,6 +33,7 @@ typed-index-collections = "=3.2.3" [dependencies] prost = "0.14" +reqwest = { version = "0.13.5", default-features = false, features = ["rustls", "json"] } tokio-rustls = "0.26" rustls = "0.23" webpki-roots = "1" @@ -54,12 +55,14 @@ uuid = { version = "1", features = ["v4"] } argon2 = "0.6" opus = "0.4" cpal = "0.18" +chrono = { version = "0.4.45", default-features = false, features = ["clock"] } dirs = "7" sys-locale = "0.3" slint = { version = "=1.18.1", default-features = false, features = ["std", "backend-winit", "renderer-femtovg", "renderer-software", "accessibility", "compat-1-18"] } nnnoiseless = { version = "0.5.2", default-features = false, optional = true } -image = { version = "0.25.10", default-features = false, features = ["png", "jpeg", "webp"] } +image = { version = "0.25.10", default-features = false, features = ["png", "jpeg", "webp", "gif"] } +arboard = { version = "3.7", features = ["wayland-data-control"] } rfd = { version = "0.17.2", default-features = false, features = ["xdg-portal", "wayland"] } [dev-dependencies] @@ -68,12 +71,13 @@ rcgen = "0.14" rustls = { version = "0.23", features = ["tls12"] } [features] -default = ["screen-capture"] +default = ["screen-capture", "rnnoise"] rnnoise = ["dep:nnnoiseless"] screen-capture = ["dep:zbus", "dep:gstreamer", "dep:gstreamer-app", "dep:gstreamer-video", "dep:gstreamer-webrtc", "dep:gstreamer-sdp"] [target.'cfg(target_os = "linux")'.dependencies] +cpal = { version = "0.18", features = ["pulseaudio"] } zbus = { version = "6.1", optional = true } gstreamer = { version = "0.25.2", optional = true } gstreamer-app = { version = "0.25.2", optional = true } diff --git a/README.md b/README.md index 3ea82cb..10a134f 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ The official desktop client for [VNOX](https://github.com/loki5512344/Vnox) - a ### Implemented - **Auth:** Ed25519 keypair generation, challenge-response login, reconnect with exponential backoff +- **Server restoration:** The last successfully connected server is restored after Central sign-in when automatic reconnect is enabled. Manual disconnect suppresses restoration until the next successful explicit connection. Connection preferences live in `vnox/connection.json` under the system configuration directory; typed address drafts are never persisted. - **Encryption:** TLS 1.3 (rustls) on the control connection with certificate pinning (trust on first use), ChaCha20-Poly1305 on UDP voice - **Text chat:** Persistent history, reactions, replies, edit, delete, typing indicators, read receipts - **Channel management:** Join, leave, create, delete; text and voice channels @@ -47,6 +48,9 @@ The official desktop client for [VNOX](https://github.com/loki5512344/Vnox) - a ## Status +Current client work is tracked in [TODO.md](TODO.md), with the original +user-reported defects in [the UX checklist](docs/maintenance/ux-defects-2026-10-24.md). + Phase 1 is implemented. Not production ready. | Feature | Status | diff --git a/TODO.md b/TODO.md new file mode 100644 index 0000000..49bcaa8 --- /dev/null +++ b/TODO.md @@ -0,0 +1,338 @@ +# Задачи клиента + +## Текущий запрос: 2026-11-01 + +Сначала фиксируем задачи здесь; завершение отмечаем только после проверки. + +Проверка объединённого клиента 2026-11-01: 190 тестов прошли, 2 существующих +игнорируются; headless GUI с изолированным профилем проверяет 12 тем и модели. +Сервер с вложениями и профилями установлен; 164 теста релизного workspace прошли. +Живая проверка слышимости двумя людьми остаётся отдельной открытой задачей. + +### Форумы: отдельные темы и ответы через gateway + +- [ ] Сначала согласовать LNEx-контракт: список тем, создание, открытие, + история и ответы; capability старого gateway, права узла/сообщества и лимиты. +- [ ] Добавить сетевые команды/события и состояние форума с защитой от устаревших + ответов после смены сервера/канала и понятными состояниями загрузки/ошибки. +- [ ] Показывать настоящий список тем, создание темы с первым сообщением, + открытие истории и ответы, подтверждённые gateway; не подменять форум плоским чатом. +- [ ] Сохранить безопасное поведение аудио: форум и категория никогда не + инициируют voice join или захват микрофона; старый gateway не получает новые пакеты. +- [ ] Проверить wire/state регрессии, отсутствие ложного успеха при отказе, + контекст узла/сообщества и headless UI только в виртуальном display/профиле. + +### Дополнение: профили, присутствие, темы и виртуальная QA + +План палитр: тёмные Extra dark (`black`), Graphite (`dark`), Midnight, Pine, +Aubergine, Espresso; светлые Porcelain (`light`), Mist, Glacier, Sage, Rose, Sand. +Проверка: 12 сохраняемых пресетов, переключатель группы 6 карточек, точные +миниатюры, сохранение старых идентификаторов; WCAG 2.2 — текст ≥4.5:1, +значимые границы/фокус ≥3:1, выбранное состояние обозначено галочкой. +GUI QA — только виртуальный дисплей/изолированный профиль. + +- [x] Запоминать последний успешно подключённый сервер и восстанавливать + подключение при запуске после восстановления/подтверждения Central-сессии; + учитывать ручное отключение и настройку автоматического подключения. + План восстановления: отдельный `connection.json` хранит только нормализованный + адрес успешного подключения, auto-reconnect и явное ручное отключение. + Черновик адреса не сохраняется; запуск и завершение входа используют обычный + Connect с онлайн-проверкой Central и TLS. Отзыв входа возвращает панель входа. + Проверки: сериализация, черновик/успех, нормализация, выключенный auto-reconnect, + ручное отключение и отсутствие аккаунта; GUI — изолированный virtual display. +- [x] Исправить присутствие одного аккаунта с несколькими сессиями: не дублировать + участника, не удалять его при закрытии только одной сессии, корректно + учитывать последнюю сессию. Проверить две сессии и выход в обоих порядках. +- [x] Исправить отображение аватара Central в клиенте и данных профиля при входе; + отдельный локальный QA-профиль не должен подменять профиль пользователя. +- [x] Сделать Extra dark темой по умолчанию для новых профилей, сохранив явный + выбор существующего пользователя. Обновить миниатюры тем под реальные палитры. +- [x] Добавить 6 тёмных и 6 светлых тем, переключатель группы вместо показа всех + 12 одновременно, сохранение выбора и согласованное отображение настроек. +- [ ] Все дальнейшие GUI-проверки запускать в отдельном виртуальном display и + изолированном профиле. Не создавать тестовые окна в Hyprland пользователя, + не менять фокус/буфер/настройки рабочего стола и не использовать его аккаунт. + +### Плавный локальный тест микрофона + +- [x] Исправить задержку/рывки live-monitor: убрать callback-аллокации и + try_lock-потери, сохранять фазу ресемплера между callback, ограничить очередь + 60 мс с начальным заполнением 20 мс и удалением старого хвоста только consumer. +- [x] Запрашивать поддерживаемый CPAL buffer около 5 мс с fallback к default; + сгладить индикатор hold/decay. Проверить 44.1/48/96 kHz, произвольные размеры + callback, overflow/underrun/clock drift и отсутствие callback-аллокаций. +- [x] Сверить реализацию с официальными CPAL/PulseAudio/RNNoise; проверять + синтетически/в виртуальной среде. Физическую задержку и слышимость без + отдельной живой проверки не считать измеренными. + +### Трей и закрытие окна + +- [ ] При закрытии окна сворачивать приложение в системный трей, сохраняя + подключение и голос; полностью завершать процесс через явный пункт «Выйти». +- [ ] Меню трея: «Открыть», «Настройки», «О программе», разделитель, + «Перезапустить», «Выйти». Нажатие на значок возвращает существующее окно. +- [ ] Проверить поддержку Linux StatusNotifierItem и восстановление окна, + отсутствие второго экземпляра при повторном открытии, корректное отключение + голоса и сети при выходе/перезапуске. GUI-проверки только в виртуальной среде. +- [ ] Предусмотреть настройку «Сворачивать в трей при закрытии» и обычное + закрытие, если системный трей недоступен, чтобы окно не исчезало безвозвратно. + +### Медиа в чате + +- [x] Показывать изображения и анимированные GIF по прямым HTTPS-ссылкам в + сообщениях (включая пример пользователя `https://evolationstudios.ru/admindata/gifs/cuckoding2.gif`). +- [x] Добавить вставку картинки из системного буфера, предпросмотр, отмену и + отправку настоящего вложения, доступного другим участникам и после перезапуска. +- [x] Сначала описать хранение и передачу вложений, права доступа и лимиты; + проверить форматы, размер, декодирование и ограничения загрузок. +- [ ] Проверить GIF-анимацию, ошибки/отсутствие сети, вставку при русской + раскладке и отсутствие повторной загрузки при каждом обновлении UI. +- [ ] Отложено: голосовые сообщения. В текущий объём реализации не входят. +- [ ] Следующий этап вложений: очистка неиспользуемых файлов после удаления + сообщений и политика хранения; сейчас удаление сообщения не освобождает квоту + немедленно. Добавить отправку вложений в DM после отдельного контракта. + +Текущие вложения: PNG/JPEG/GIF до 3 MiB в текстовом канале, с явным +подтверждением отправки. Прямые HTTPS-ссылки отображаются отдельно. + +- [x] Перейти на нативные PipeWire/PulseAudio в Linux, показывать системные + входы/выходы без технических ALSA-дублей и с постоянным выбором по ID. +- [x] Добавить выбор микрофона/выхода по ПКМ на нижних кнопках, сохранив + обычное нажатие для mute/deafen. +- [x] Усилить контраст встроенных тем, кнопок и блока голосового подключения. +- [x] Добавить локальную проверку микрофона с уровнем и прослушиванием, + остановкой при закрытии настроек и без отправки теста собеседникам. +- [x] Добавить работающий переключатель RNNoise и сохранение настройки. +- [x] Показывать заметную обводку своего аватара при передаче голоса. +- [x] Обязать вход в Central до подключения; gateway должен проверять + подтверждение аккаунта, привязанное к ключу клиента. Сначала спецификация + авторизации desktop и LNEx; несовместимые изменения требуют новой версии. +- [x] Собрать и установить обновлённый клиент. Установленный release проверен + в отдельном Xvfb с пустым профилем: экран обязательного входа, открытие настроек, + переход к темам, переключение группы и выбор палитры настоящими X11-кликами. + Проверка слышимости с реальными устройствами остаётся отдельной задачей ниже. +- [x] Исследовать и исправить Ctrl+V из системного буфера в поля Slint + при русской и английской раскладке; сначала + проверить документацию/известные проблемы и воспроизвести в этой сборке. + Проверены реальные Wayland-события EN/RU, обычное поле, пароль и TextEdit; + причина и ограничения: [буфер Wayland](docs/maintenance/clipboard-wayland.md). + Shift+Insert штатно не поддерживается Slint 1.18.1; этот фикс его не добавляет. +- [x] Показывать дату и время у сообщений не за сегодняшний день; для + сегодняшних оставить короткое время. Проверить полночь и локальный часовой пояс. + +Связанные задачи сайта: сохраняемая серверная сессия, собственный аватар в +шапке, генерируемый VNOX-аватар вместо GitHub и его замена загрузкой. + +Актуальные локальные задачи. Подробности пользовательского теста и уже +исправленные дефекты: [UX-дефекты](docs/maintenance/ux-defects-2026-10-24.md). +Общий план платформы: [roadmap сервера](../VNOX-Server/docs/06-roadmap.md). +`docs/slint-migration-plan.md` является историческим планом миграции. + +## Отзывчивость и звук + +- [x] Перенести повторный опрос аудиоустройств при открытии настроек из потока + интерфейса. Сохранять текущий выбор по ID, объединять повторные запросы, + сохранять предыдущий список при ошибке. Проверить медленный опрос тестом. +- [ ] Проверить слышимость голоса между двумя реальными клиентами после + исправлений из потока B. Автоматический UDP-тест не проверяет микрофон, + устройства воспроизведения и слышимость речи человеком. + +## Central и аватары + +- [x] Реализовать вход клиента через Central после документирования серверного + контракта авторизации desktop/device enrollment и проверки доказательств + аккаунта на gateway. Наличие браузерной сессии Hub само по себе не решает + эту задачу. См. пункты 10d и 10e списка UX-дефектов. +- [x] Определить и реализовать получение профиля и аватара других участников, + обновление кэша и правила видимости после согласования LNEx-контракта. + Собственный аватар и аватары авторов сообщений загружаются из Central; профиль + хранится в UI без чтения аккаунта с диска на каждом обновлении. + См. пункты 2, 12b и 12c списка UX-дефектов. + +Изменения LNEx сначала описываются в документации протокола. Значительные +изменения аккаунтов и обязательного входа требуют обсуждения до реализации. + +## Сообщества и администрирование + +Аудит кода: [владение и админка](../VNOX-Server/docs/design/ownership-and-admin-audit.md). + +- [ ] Сохранять `owner_id` в `GuildState`, показывать владельца сообщества. +- [ ] Доделать создание сообщества и работу с приглашениями в Slint. +- [ ] Добавить управление участниками, ролями и каналами с обработкой + подтверждений/отказов gateway и изменения прав во время работы. +- [ ] Реализовать получение админки узла и передачу владения после утверждения + серверных контрактов. Запуск VPS и публикация в каталоге не выдают эти права. +- [ ] Добавить просмотр каталога серверов и удобный перенос адреса в подключение. + +## Account presence and Central member profiles (2026-11-01) + +- [x] Keep authenticated Central account IDs separate from Ed25519 device IDs. Channel subscriptions and voice routes remain session/device scoped; account member rows aggregate devices. Closing either of two sessions must retain the other session, member and online presence. +- [x] Distribute Central-signed display names and same-origin avatar paths in additive member metadata; fetch bounded PNGs without forwarding credentials, cache successful results, and retain initials on errors. Preserve guild ownership and historical device IDs. +- [x] Verify two-device and repeated-device lifecycle, profile propagation and rejected avatar origins with regression tests. + +- [x] Own Central profile is cached on startup/sign-in; Central avatar overrides local photo, clears at logout, and message authors use the same member avatar cache. Failed public PNG fetches retry after 30 seconds. + +## Установленная сборка — 2026-11-01 + +Release `20261101-45c6c964b447`, запускается через `~/.local/bin/vnox-client`. +Предыдущая сборка сохранена. GUI QA: `/tmp/vnox-virtual-release-eo95no3t`, +67 headless снимков: `/tmp/vnox-theme-qa/screens`. Рабочий стол пользователя +не использовался; его запущенный клиент не перезапускался. + +### Исправление сетки тем — 2026-11-01 + +- [x] Выровнять ширину карточек независимо от подписей и ограничить ширину + сетки, чтобы превью не растягивались на широком окне. Проверить 1024/1280/1920 px + в изолированном headless renderer, затем установить исправленную сборку. + +## Desktop Central avatar correction (2026-11-01) + +- [x] Refresh and persist the Central summary at admission and bounded background/profile-view refresh; deliver updates to UI without reading credentials every tick. Drop late results after logout or enrollment replacement. +- [x] Restore desktop photo choose/crop/upload/delete against Central enrollment-authenticated endpoints. Reuse normalized PNG storage/default avatar and account/IP budgets; no browser cookie or profile migration 6. +- [x] Verify website-avatar refresh, authenticated PNG upload/delete, device binding, expired/revoked secrets, invalid image limits, and summary/UI propagation. + +- [x] Add desktop editable Central display_name with signed enrollment-authorized profile mutation, existing 64-character/control validation, persisted summary/watch update and name-adjacent Save/status controls. Unique handle and ownership IDs remain unchanged. + +Desktop name/photo mutations update the own account UI and persisted enrollment immediately. Live signed profile propagation below supersedes the original admission-only peer refresh limitation; no forced reconnect is used. + +Проверка исправлений профиля/звука: 199 тестов клиента прошли, 2 существующих +пропущены. Новый Hub: 167 тестов; live endpoints требуют авторизацию (401 без неё). +Подробности звука и источники: [локальный монитор](docs/maintenance/microphone-monitor.md). + +Дополнительная причина пустого аватара: live Cloudflare возвращал 403 запросам +публичного PNG без User-Agent; с `VNOX-Desktop/0.1` тот же адрес возвращал +200 image/png. Загрузчик публичных аватаров теперь использует этот User-Agent. + +## Обновление профиля и звука установлено — 2026-11-01 + +Release `20261101-0cf5ad21b61a`: выбор/обрезка/загрузка/удаление фото Central, +редактирование имени, обновление профиля с сайта, исправление HTTP403 аватаров, +ровная сетка тем, новый локальный микрофонный монитор. 199 тестов клиента, +2 прежних ignored; all-target Clippy и форматирование проходят. Hub: 167 тестов. +Установленный бинарник проверен в Xvfb `/tmp/vnox-virtual-release-jfhth5xz`: +открытие профиля, поле имени, кнопки фото, успешная загрузка публичного PNG +через production Cloudflare. Использовался отдельный фиктивный кэш профиля +без действующей авторизации; реальные пользовательские учётные данные не +читались. Фиктивный файл удалён. Настоящая задержка гарнитуры не измерялась. + +## Live signed Central profile propagation (2026-11-01) + +- [x] Add documented device/account-bound signed ProfileUpdate/ProfileUpdated packets; gateway verifies claims, prevents older-timestamp downgrade and broadcasts only through current shared-channel visibility. +- [x] Forward existing refresh proofs; coalesce background refresh before new chat/voice join with five-second TTL while UDP/keepalives continue. Update member/message/voice profile maps without adding members or reconnecting. +- [x] Verify two-client old→new name/avatar after chat and voice rejoin, no membership duplication/disconnect, rejected forged/wrong-account/stale proof and visibility revocation. + +### Ник при регистрации и первое знакомство + +- [x] Генерировать дружелюбный русский `слово_0000` CSPRNG только при первом + создании email/GitHub-аккаунта; не брать имя провайдера, не менять handle и + существующие пользовательские имена. Сохранить JSON-словарь, источник и лицензию. +- [x] Предложить «Изменить сейчас / Позже» в веб-профиле; явное решение хранить + на сервере, существующим аккаунтам не навязывать onboarding. Новый независимый + endpoint имени не должен требовать отложенную миграцию профилей/handle. +- [x] Проверить регистрацию обоими способами, повторный вход/свой ник, формат, + CSRF/Origin, идемпотентное решение и Web-сборку/тесты в изолированной среде. + +## Живой профиль, первый ник и стандартные аватары — 2026-11-01 + +- [x] Передавать подтверждённый Central профиль без переподключения TCP: + обновлять при сообщении/повторном входе в войс и после изменения имени/фото. + Не доверять неподписанным именам, сохранять права и ключи устройств. +- [x] Первый ник: словарь JSON с источником/лицензией, слово_0000, назначение + только при создании аккаунта; предложение изменить сейчас/позже с сохранением + решения. Выбранные существующие имена не перезаписывать. +- [x] Стандартные аватары v2: стабильные пиксельные монстрики из публичного UUID, + новые versioned URL из-за immutable cache; прежний v1 продолжает работать. + Проверить разнообразие/детерминизм/PNG256, отсутствие запросов о наличии аккаунта. + +### Управление каналами администратором узла + +- [x] Принять server-advertised `Session.node_admin` и сбрасывать право при + отключении. Показать управление только глобальными каналами вне guild/DM. +- [x] Добавить создание text/voice, переименование и подтверждённое удаление; + повторно проверять capability/scope перед отправкой, ждать server ack/error + с таймаутом, не менять список оптимистично. Gateway остаётся авторитетом. +- [x] Подключить существующий ChannelEdit (0x36), проверить не-admin/false-default, + потерю прав, input validation и headless create/rename/delete/error/confirm. + +## Explicit node administrator capability (2026-11-01) + +- [x] Advertise additive Session.node_admin; global channel controls require operator-configured verified Central account UUID, never first visitor/name/device alone. Guild permissions remain separate. +- [x] Verify account's second device, unlisted accounts, cross-guild denial, bootstrap protection and channel persistence across cache/bootstrap reload. + +- [x] Negotiate Session.live_profiles (field 5): legacy v4 gateways receive no ProfileUpdate packets and no profile-based activity delay; capable gateways retain proof-before-action ordering. + +### Завершение живого профиля и админки + +- [x] Неподдерживаемый старым V4-сервером ProfileUpdate не отправляется: + поддержка определяется `Session.live_profiles`; чат/голос продолжают работать. +- [x] Ошибка обновления профиля не отменяет вход в голос; выход отменяет также + ожидающий join, включая ожидание reconnect. Создание voice-канала не включает микрофон. +- [x] Команды администратора привязаны к конкретной сессии и отбрасываются после + смены узла; старый запрос не переносится на новый сервер. +- [x] На VPS аккаунту `loki` назначен `gateway.admin_account_ids`, сохранены + серверные ключи/данные, новый Hub и Web установлены. Финальные серверные + проверки: 181 тест, Clippy, fmt; Web: 28 тестов и сборка. + +Клиент: 218 тестов прошли, 2 существующих ignored; all-target Clippy и каталоги +297 native / 459 shared проверены. Графический тест — изолированный headless +renderer, включая настоящие software-click проверки создания/изменения/удаления. + +## Установлено — финальная сборка 2026-11-01 + +Release `20261101-f16a49f9c678`, запуск через `~/.local/bin/vnox-client`. +218 тестов, 2 ignored, Clippy/fmt/каталоги проходят. Виртуальная native-проверка +установленного бинарника: `/tmp/vnox-virtual-release-r1fnf8kh`, профиль с новым +монстриком загружается через production HTTP; тестовый кэш без действительной +авторизации удалён. Source snapshot и предыдущий бинарник сохранены рядом с release. +Реальный пользовательский процесс не перезапускался и экран не использовался. + +### Меню узла, настройки и категории + +- [ ] Добавить раскрытие меню по имени сервера и отдельные настройки узла + только по подтверждённым правам; настоящее сохранение имени сервера с ACK/error. +- [ ] По правой кнопке в списке каналов открыть меню «Текстовый / Голосовой / + Категория / Форум»; контекст категории сохранять, правая кнопка не входит в голос. +- [ ] Показать категории с дочерними каналами и сворачиванием; повторно проверять + capability и session fence для всех операций. Меню закрываются Escape/вне меню, + клавиатурные действия поддерживаются; никаких пустых страниц настроек. +- [ ] Проверить сохранение имени/категорий через сервер и виртуальные UI-сценарии + меню, outside click, Escape, запрет не-admin, создание внутри категории. + +## Версии, обновления и публичный релиз — запрос 2026-11-01 + +- [ ] Ввести согласованную версию клиента/протокола/релизных артефактов; + показывать установленную версию и состояние обновления в настройках. +- [ ] Проверка новых версий через Central и GitHub Releases; ручное обновление + и отключаемое автообновление. Проверять подписанный manifest/хеши, защищаться + от подмены, downgrade, опасной распаковки и запуска непроверенных файлов. +- [ ] Безопасное атомарное обновление с сохранением профиля и возможностью + отката; разделить проверку, загрузку и установку, не прерывать активный войс. +- [ ] После завершения настроек/категорий/форумов выполнить сквозную проверку + голосового чата в изолированной среде; не считать сетевой relay-тест + подтверждением слышимости реальной гарнитуры человеком. +- [ ] Настроить/проверить CI сборок Linux и Windows; выпустить GitHub Release + с бинарниками, подписанным manifest, контрольными суммами и changelog. + +Репозиторий публичных релизов подтверждён пользователем: +`https://git.wihuk.pro/boba/VNOX-Client.git`. Cargo.repository приведён к origin. +Проверка/публикация обновлений должна использовать этот сервис, а не GitHub. + +## Контрольная точка: остановлено по просьбе пользователя — 2026-11-01 + +Все три агента остановлены. Работающие версии оставлены установленными: +- Client: `20261101-f16a49f9c678` (218 тестов, 2 ignored, Clippy проходил). +- Gateway VPS: `20261101-live-capability-219376accf98`. +- Central: `20261101-live-admin-91595d45652a`; Web: `20261101-names-monsters-ff473f423565`. +- Аккаунт `loki` имеет права управления глобальными каналами узла. + +В коммитах сохранён НЕЗАВЕРШЁННЫЙ следующий этап, не опубликованный в production: +- меню заголовка/ПКМ, настройки имени/описания узла, категории и форумы; +- серверное хранилище уже имеет 6 проходивших focused-регрессий, но общий + финальный client/server build и интеграционная проверка ещё не завершены. +- версии/автообновление/релиз Linux+Windows пока только запланированы. + +Продолжение: сначала завершить сборку и общие тесты текущего черновика, затем +проверить voice relay/чат/форумы в изолированной среде, собрать и развернуть; +после этого реализовать updater с подписанным manifest и выпустить бинарники +в https://git.wihuk.pro/boba/VNOX-Client.git. Cargo.repository уже исправлен. +Не запускать тестовые приложения на рабочем столе пользователя. diff --git a/docs/channel-management.md b/docs/channel-management.md new file mode 100644 index 0000000..9a5ded9 --- /dev/null +++ b/docs/channel-management.md @@ -0,0 +1,29 @@ +# Global channel management + +The additive Session.node_admin flag (field 4, default false) advertises permission +for the connected Central account to manage this node's global channels. The +client never grants this permission itself and clears it on disconnect. + +The global sidebar offers text/voice creation, rename and explicit delete +confirmation only when advertised. Guild and direct-message views remain outside +this UI. Requests use existing ChannelCreate/Delete and ChannelEdit (0x0036); +server broadcasts acknowledge success. Errors remain visible in the dialog; +ten-second timeout reports uncertainty, and no channel list mutation is optimistic. +Channel IDs are client-generated UUIDs, names are trimmed and limited to 100 +characters without controls, and every Rust callback rechecks scope/capability. + +## Server settings and channel context menus + +Design: retain the current theme tokens and left sidebar hierarchy. Clicking the +server heading opens a compact menu; authorized node administrators can open real +server settings (server-name editor plus channel/category management). Right-click +on empty channel-list space or a channel opens a keyboard-accessible create menu; +a category establishes the parent context. Right-click never joins a voice room. +Menus dismiss with Escape or an outside click. + +Categories are presentation containers, never voice/text subscriptions. Children +retain their actual text/voice/forum kind, and collapsed categories hide children +without leaving an active voice room. Parent IDs and server display names persist +on the gateway; the native client waits for acknowledgements and fences operations +to the session that authorized them. Guild rights and direct messages are not +expanded by node-admin controls. Forum topic/reply content is handled separately. diff --git a/docs/chat-images.md b/docs/chat-images.md new file mode 100644 index 0000000..383312a --- /dev/null +++ b/docs/chat-images.md @@ -0,0 +1,11 @@ +# Images and GIFs in chat + +Direct HTTPS PNG, JPEG, WebP and GIF image links render inline in channel and direct-message chat. The first supported image link in a message is shown; the original text remains visible. GIFs animate with their original frame timing (minimum 20 ms). Animated previews are scaled to at most 384 pixels on the longest side while retaining every accepted frame. Voice messages are not part of this feature. + +Paste an actual clipboard image with Ctrl+V (including a Cyrillic keyboard layout) or use **Paste image** in the composer. An image preview appears before any upload. **Send image** explicitly uploads it to the selected original channel; **Cancel** discards it. Ordinary text paste continues to use the editor. Clipboard images are encoded as PNG, limited to 3 MiB, and only read after an explicit paste action. Images are not uploaded when the window gains focus. Channel changes and reconnects cannot redirect a pending upload into another conversation. Direct-message attachments are currently unavailable; direct image links still render there. + +Attachments use the existing authenticated LNEx TLS connection. The gateway validates and stores image bytes durably and posts a channel-scoped attachment marker in history. Other channel participants fetch those bytes through the same authenticated connection. There are no public upload URLs or added HTTP ports. See the server's `docs/02-protocol/chat-attachments.md` for access checks, protocol fields, storage quotas and retained attachment policy. + +Remote downloads allow HTTPS on port 443, without URL credentials, cookies, proxies or forwarded authentication. Each redirect is revalidated; DNS addresses must all be public and are pinned for the request. Loopback, private, link-local, reserved and special-purpose destinations are rejected. A direct URL preview contacts the external image host and therefore exposes the viewer's IP address to that host. + +Remote encoded files are limited to 16 MiB with a 30-second overall download timeout and three redirects. Decoding accepts dimensions at most 4096 per side and 4 megapixels per frame. GIFs are limited to 120 frames, 128 megapixels of source decoding work, and 64 MiB of preview pixels. The UI limits concurrent media operations, caches at most 24 sources and 64 MiB of decoded frames, and shows an error when a source exceeds its budget. An unavailable image does not prevent sending or reading text. The example `https://evolationstudios.ru/admindata/gifs/cuckoding2.gif` was verified through the safe downloader and decoder: 5,457,840 encoded bytes, 119 frames, 384×279 preview, 50 ms per frame. diff --git a/docs/maintenance/clipboard-wayland.md b/docs/maintenance/clipboard-wayland.md new file mode 100644 index 0000000..0afcd3e --- /dev/null +++ b/docs/maintenance/clipboard-wayland.md @@ -0,0 +1,69 @@ +# Clipboard shortcuts on Linux/Wayland + +## Diagnosis (2026-11-01) + +The reported failure follows the active keyboard layout: English Ctrl+V +works; Russian Ctrl+V fails in every Slint input. Slint 1.18.1's +`InternalKeyEvent::shortcut()` recognizes the literal Latin `v`. Winit sends +the Russian logical character `м`, with physical `KeyV`, and the backend +previously forwarded that character unchanged. Clipboard initialization is +not the cause of this layout-specific failure. + +The vendored winit backend now translates standard Ctrl shortcuts to Latin +letters using physical key positions only when the logical letter is +non-ASCII. Latin logical letters remain authoritative for AZERTY/Dvorak. +Regular Cyrillic input and Alt/Meta combinations retain their original text. +AltGr is tracked separately from Winit's Alt flag because Linux commonly +uses XKB Mod5 for it. Ctrl+AltGr key sequences therefore keep their text too. +If focus is acquired with AltGr already held and no AltGraph key event is +delivered, the aggregate modifier notification cannot identify Mod5; release +and press AltGr again in that case. +The backend also reconciles Wayland modifier notifications: virtual keyboards +and focus changes can supply modifier state without individual Ctrl events. +Previously `wtype -M ctrl -k v -m ctrl` inserted a plain `v` for this reason. + +Native clipboard access already uses arboard with `wayland-data-control`. +Both the installed October 25 binary and the current build contain the +arboard/Wayland clipboard backend; the installed binary predates this +keyboard-layout fix. + +References: + +- [Winit key-event documentation](https://docs.rs/winit/latest/winit/event/struct.KeyEvent.html) + distinguishes logical characters from layout-independent physical keys. +- [Arboard Linux backend documentation](https://docs.rs/crate/arboard/latest) + explains the required `wayland-data-control` feature. +- [Slint shortcut implementation at v1.18.1](https://github.com/slint-ui/slint/blob/v1.18.1/internal/core/input.rs) + matches Latin letters for standard shortcuts. + +## Verification + +Run policy regression tests with: + +```sh +cargo test --test clipboard_shortcuts --no-default-features +``` + +For a native GUI check: + +```sh +VNOX_CLIPBOARD_EXPECT=vnox-probe cargo run --example clipboard_probe +``` + +Copy `vnox-probe`, then paste with Ctrl+V in the ordinary, password, and +multiline fields (Tab moves between them). Repeat with English and Russian +keyboard layouts. Output reports field, character count, and equality only; +it never prints pasted text. Also check Ctrl+A/C/X/V in the ordinary field, +and ordinary Cyrillic typing without Ctrl. + +The automated workstation check used a separate temporary evdev keyboard, +with its own English/Russian layout selection, on real Hyprland/Wayland. +All three field types received the expected system clipboard text. Russian +Ctrl+A/C/X/V and ordinary Cyrillic input were checked through real key events. +English physical Ctrl+V and virtual-keyboard Ctrl+V were also checked. +The user's original clipboard was retained privately in process and restored; +their physical keyboard layouts were not changed. + +Shift+Insert is not a standard paste shortcut in Slint 1.18.1's native +shortcut matcher; use Ctrl+V. This patch keeps clipboard handling in Slint's +backend and does not add application-wide paste interception. diff --git a/docs/maintenance/forum-client.md b/docs/maintenance/forum-client.md new file mode 100644 index 0000000..209e893 --- /dev/null +++ b/docs/maintenance/forum-client.md @@ -0,0 +1,36 @@ +# Forum client interaction contract + +A forum is a channel containing separately addressable topics. It is not a text +channel with a different icon. Gateway owns the topic list, creation, history and +replies; the client displays successful results only after acknowledgement. +The matching LNEx specification must define the wire payloads and capability +before implementation of network commands. + +The main panel has two views: a topic list with title, author and reply count, +and an opened topic with its title, opening message and chronological replies. +Creating a topic requires a title and first message. Opening a topic fetches its +history. Returning to the list preserves unsent input within the same server; +disconnecting or changing server clears forum data and pending operations. +Loading, empty, denied and failed requests have explicit visible states. Failed +requests keep input, and provide retry instead of claiming success. + +Use existing Theme colors and font scale, left-aligned topic rows, the current +focus styles and normal sentence-case actions. Navigation remains in the sidebar. +The forum panel has no voice controls or membership side effects. Selecting a +category is navigation only. Only an explicit voice-channel selection may request +voice membership; arbitrary callbacks for categories or unknown channel kinds +must be rejected. Browsing a forum does not disconnect an existing voice session. + +Forum commands require the advertised server capability and an authenticated +session. Old servers receive no new forum packets. Requests carry correlation +IDs and the selected forum/topic context; stale responses cannot switch the +current topic or replace another server's data. Node and guild visibility and +write permissions are enforced by Gateway, with errors surfaced in the forum. +Retries use a new request ID; creation/reply input clears only on matching success. +Pagination is bounded by the server contract and must not silently truncate a +thread without a way to fetch further results. + +Regression checks cover wire encoding/dispatch, request correlation, failed +creation preserving drafts, stale results after selection/session changes, +capability gating, topic/reply history, and category/forum navigation without +voice capture. GUI checks use an isolated virtual display and profile only. diff --git a/docs/maintenance/microphone-monitor.md b/docs/maintenance/microphone-monitor.md new file mode 100644 index 0000000..0c34fa3 --- /dev/null +++ b/docs/maintenance/microphone-monitor.md @@ -0,0 +1,41 @@ +# Local microphone monitor + +The test opens the selected input and output for at most 30 seconds. It does not +send audio to a room. The live voice pipeline releases its devices before the +monitor starts; stop, settings close and device changes revoke the monitor. + +## Correction — 2026-11-01 + +The former callbacks allocated vectors, independently restarted linear resampling +for every chunk, and used `try_lock` to share samples. Lock contention could drop +input or silence an output callback. Its queue permitted 250 ms of backlog. + +The replacement uses preallocated atomic sample slots with one producer and one +consumer. Only the consumer advances the read position. A full producer drops +new samples and marks an overflow; playback discards stale queued audio before +prefilling fresh audio. Streaming resamplers retain phase across callbacks and a +bounded ±0.2% correction accommodates independent device clocks. Playback starts +with 20 ms, trims above 40 ms, and the ring holds at most 60 ms. Short gain ramps +smooth restart/underrun edges. The level meter holds and decays instead of resetting +visibly to zero on every UI poll. RNNoise reuses its 480-sample scratch buffers. + +The monitor requests approximately 5 ms callbacks only within the device's +reported supported buffer range. If the request cannot build the streams, both +are rebuilt with device defaults. This is a request, not a measurement or a +promise of 5 ms end-to-end latency. Driver/server/hardware buffering and RNNoise +framing add delay. No desktop audio configuration is changed. + +Synthetic checks exercise irregular 44.1/48/96 kHz callbacks, ±1000 ppm clocks, +concurrent ordered queue operations, overflow and stale-audio removal, underrun, +cancellation, and level hold/decay. They do not measure the user's headset or +establish human-perceived voice quality. + +## Primary references + +- [CPAL 0.18.2 BufferSize](https://docs.rs/cpal/0.18.2/cpal/enum.BufferSize.html) +- [PulseAudio stream buffering](https://freedesktop.org/software/pulseaudio/doxygen/streams.html#buffering) +- [PulseAudio client latency control](https://wiki.freedesktop.org/www/Software/PulseAudio/Documentation/Developer/Clients/LatencyControl/) +- [RNNoise frame API](https://github.com/xiph/rnnoise/blob/main/include/rnnoise.h) + +The installed CPAL 0.18.2 Pulse backend was also inspected: fixed buffer requests +set `ADJUST_LATENCY`; default buffers leave the backend's defaults in place. diff --git a/docs/maintenance/ux-defects-2026-10-24.md b/docs/maintenance/ux-defects-2026-10-24.md index 151d900..96eb1d9 100644 --- a/docs/maintenance/ux-defects-2026-10-24.md +++ b/docs/maintenance/ux-defects-2026-10-24.md @@ -20,7 +20,7 @@ | 10c | Голосовая комната | Верхняя строка «Подключение к голосовой комнате…» остаётся, хотя внизу «Голос подключён» | B исправлено: единый статус голоса (см. ниже) | | 10d | Аккаунт | Можно зайти на сервер без аккаунта; регистрация или вход в Central должны быть обязательными | C | открыто | | 10e | Аватары | Две буквы вместо аватара; при первой регистрации нужен случайный сгенерированный аватар | C | открыто | -| 10f | Отзывчивость | Приложение реагирует медленно; нажатие срабатывает не с одного клика, а со второго | A | исправлено (поток A). Причина: `FocusScope` лежал над `TouchArea` и по умолчанию забирал первое нажатие (`focus-on-click`), клик доходил до кнопки только со второго раза; плюс панель действий над сообщением пропадала при наведении на её кнопки. Тест `ui_smoke` шлёт реальные события указателя и падал до исправления. Отдельно остаётся: `refresh_devices` при открытии настроек опрашивает ALSA в потоке интерфейса (поток B) | +| 10f | Отзывчивость | Приложение реагирует медленно; нажатие срабатывает не с одного клика, а со второго | A | исправлено (поток A). Причина: `FocusScope` лежал над `TouchArea` и по умолчанию забирал первое нажатие (`focus-on-click`), клик доходил до кнопки только со второго раза; плюс панель действий над сообщением пропадала при наведении на её кнопки. Тест `ui_smoke` шлёт реальные события указателя и падал до исправления. Опрос устройств при открытии настроек вынесен из потока интерфейса (01.11.2026, поток B): один фоновый опрос, неблокирующее получение результата, сохранение выбора по ID и прежнего списка при ошибке. Проверено тестом с задержанным опросом и headless-тестом интерфейса | | 11a | Настройки звука | В списках устройств вывода и микрофона мусорные ALSA-пункты (Discard all samples, Rate Converter Plugin, JACK, Open Sound System) | B исправлено: фильтр устройств, выбор хранится по идентификатору | | 11b | Настройки | Те же двойные клики в настройках | A | исправлено (поток A): та же причина, что в 10f | | 12a | Темы | Тема работает странно (чёрная тема: части интерфейса остаются серыми, фон не везде одинаковый) | A | исправлено (поток A): все экраны проверены в светлой, тёмной, чёрной и своей теме по снимкам `ui_smoke`; захардкоженные цвета убраны, кнопка отправки и состояния берут цвета темы | diff --git a/examples/audio_devices.rs b/examples/audio_devices.rs new file mode 100644 index 0000000..7b06b8c --- /dev/null +++ b/examples/audio_devices.rs @@ -0,0 +1,12 @@ +//! Diagnostic inventory only: does not open streams or capture microphone audio. +fn main() -> anyhow::Result<()> { + let lists = vnox_client::audio::devices::enumerate()?; + println!("Audio backend: {}", cpal::default_host().id().name()); + for (kind, entries) in [("Input", lists.input), ("Output", lists.output)] { + println!("{kind}: system default"); + for entry in entries { + println!(" {} ({})", entry.label, entry.id); + } + } + Ok(()) +} diff --git a/examples/clipboard_probe.rs b/examples/clipboard_probe.rs new file mode 100644 index 0000000..6199f8e --- /dev/null +++ b/examples/clipboard_probe.rs @@ -0,0 +1,38 @@ +//! Native clipboard smoke test: `cargo run --example clipboard_probe`. +//! Focus starts in the ordinary field. Paste a non-sensitive test string with +//! Ctrl+V; Tab moves through password and multiline inputs. +//! Set VNOX_CLIPBOARD_EXPECT to report equality without logging clipboard data. +slint::slint! { + import { LineEdit, TextEdit, VerticalBox } from "std-widgets.slint"; + export component ClipboardProbe inherits Window { + title: "VNOX Clipboard Probe"; + width: 440px; + height: 260px; + callback changed(string, string); + init => { ordinary.focus(); } + VerticalBox { + ordinary := LineEdit { placeholder-text: "Ordinary input"; + edited(value) => { root.changed("ordinary", value); } + } + LineEdit { placeholder-text: "Password input"; input-type: password; + edited(value) => { root.changed("password", value); } + } + TextEdit { edited => { root.changed("multiline", self.text); } } + } + } +} + +fn main() -> Result<(), slint::PlatformError> { + let window = ClipboardProbe::new()?; + let expected = std::env::var("VNOX_CLIPBOARD_EXPECT").ok(); + window.on_changed(move |field, text| { + let matches = expected + .as_deref() + .map(|expected| expected == text.as_str()); + println!( + "field={field} chars={} matches_expected={matches:?}", + text.chars().count() + ); + }); + window.run() +} diff --git a/patches/i-slint-backend-winit/keyboard_shortcuts.rs b/patches/i-slint-backend-winit/keyboard_shortcuts.rs new file mode 100644 index 0000000..ff28f56 --- /dev/null +++ b/patches/i-slint-backend-winit/keyboard_shortcuts.rs @@ -0,0 +1,74 @@ +// Copyright © VNOX Contributors +// SPDX-License-Identifier: GPL-3.0-only + +/// Translate standard Ctrl shortcuts without replacing normal layout text. +/// Latin layouts retain their logical letters (including AZERTY/Dvorak). +pub(crate) fn shortcut_letter( + logical: &str, + physical: Option, + control: bool, + alt_or_altgr: bool, + meta: bool, +) -> Option { + if !control || alt_or_altgr || meta { + return None; + } + let mut chars = logical.chars(); + let letter = chars.next()?; + if chars.next().is_some() || !letter.is_alphabetic() { + return None; + } + let letter = if letter.is_ascii() { + letter.to_ascii_lowercase() + } else { + physical? + }; + "acvxyzfspr".contains(letter).then_some(letter) +} + +#[cfg(test)] +mod tests { + use super::shortcut_letter; + + #[test] + fn russian_control_shortcuts_use_physical_letters() { + for (logical, physical) in [("м", 'v'), ("с", 'c'), ("ч", 'x'), ("ф", 'a'), ("я", 'z')] + { + assert_eq!( + shortcut_letter(logical, Some(physical), true, false, false), + Some(physical) + ); + } + } + + #[test] + fn ordinary_cyrillic_and_altgr_are_untouched() { + assert_eq!(shortcut_letter("м", Some('v'), false, false, false), None); + assert_eq!(shortcut_letter("м", Some('v'), true, true, false), None); + assert_eq!(shortcut_letter("м", Some('v'), true, false, true), None); + } + + #[test] + fn latin_layouts_use_logical_shortcuts_and_ignore_physical_positions() { + assert_eq!( + shortcut_letter("a", Some('q'), true, false, false), + Some('a') + ); + assert_eq!(shortcut_letter("q", Some('a'), true, false, false), None); + assert_eq!( + shortcut_letter("V", Some('v'), true, false, false), + Some('v') + ); + } + + #[test] + fn dead_composed_and_non_letter_keys_are_untouched() { + for logical in ["", "´", "éa", "\u{0011}", ";"] { + assert_eq!( + shortcut_letter(logical, Some('v'), true, false, false), + None + ); + } + assert_eq!(shortcut_letter("м", None, true, false, false), None); + } +} diff --git a/patches/i-slint-backend-winit/lib.rs b/patches/i-slint-backend-winit/lib.rs index 597a56d..2878889 100644 --- a/patches/i-slint-backend-winit/lib.rs +++ b/patches/i-slint-backend-winit/lib.rs @@ -29,6 +29,8 @@ use winit::event_loop::ActiveEventLoop; #[cfg(not(target_arch = "wasm32"))] mod clipboard; +#[cfg(target_os = "linux")] +mod keyboard_shortcuts; mod drag_resize_window; mod winit_compat; mod winitwindowadapter; diff --git a/patches/i-slint-backend-winit/winitwindowadapter.rs b/patches/i-slint-backend-winit/winitwindowadapter.rs index df515ae..9921251 100644 --- a/patches/i-slint-backend-winit/winitwindowadapter.rs +++ b/patches/i-slint-backend-winit/winitwindowadapter.rs @@ -462,6 +462,10 @@ pub struct WinitWindowAdapter { current_resize_direction: Cell>, /// Allocates small i32 finger ids for winit's per-device u64 touch ids. touch_finger_ids: RefCell, + #[cfg(target_os = "linux")] + keyboard_modifiers: Cell, + #[cfg(target_os = "linux")] + alt_graph_pressed: Cell, } impl WinitWindowAdapter { @@ -516,6 +520,10 @@ impl WinitWindowAdapter { pressed: Default::default(), current_resize_direction: Default::default(), touch_finger_ids: Default::default(), + #[cfg(target_os = "linux")] + keyboard_modifiers: Default::default(), + #[cfg(target_os = "linux")] + alt_graph_pressed: Default::default(), }); self_rc.shared_backend_data.register_inactive_window((self_rc.clone()) as _); @@ -1314,13 +1322,76 @@ impl WinitWindowAdapter { .dispatch_event_with_result(corelib::platform::WindowEvent::CloseRequested)?; } WinitWindowEvent::Focused(have_focus) => { + #[cfg(target_os = "linux")] + if !have_focus { + self.keyboard_modifiers.set(Default::default()); + self.alt_graph_pressed.set(false); + } // Work around https://github.com/rust-windowing/winit/issues/4371 let have_focus = if cfg!(target_os = "macos") { winit_window.has_focus() } else { have_focus }; self.activation_changed(have_focus)?; } + #[cfg(target_os = "linux")] + WinitWindowEvent::ModifiersChanged(modifiers) => { + let next = modifiers.state(); + let previous = self.keyboard_modifiers.replace(next); + // Wayland may report modifiers without individual key events + // (virtual keyboards, or focus acquired with Ctrl held). + if self.shared_backend_data.is_wayland { + use corelib::input::key_codes; + for (was, now, left, right) in [ + ( + previous.control_key(), + next.control_key(), + key_codes::Control, + key_codes::ControlR, + ), + ( + previous.shift_key(), + next.shift_key(), + key_codes::Shift, + key_codes::ShiftR, + ), + ( + previous.alt_key(), + next.alt_key(), + key_codes::Alt, + key_codes::AltGr, + ), + ( + previous.super_key(), + next.super_key(), + key_codes::Meta, + key_codes::MetaR, + ), + ] { + if was != now { + let text = left.to_string().into(); + self.window().dispatch_event_with_result(if now { + WindowEvent::KeyPressed { text } + } else { + WindowEvent::KeyReleased { text } + })?; + if !now { + self.window().dispatch_event_with_result( + WindowEvent::KeyReleased { + text: right.to_string().into(), + }, + )?; + } + } + } + } + } + WinitWindowEvent::KeyboardInput { event, is_synthetic, .. } => { + #[cfg(target_os = "linux")] + if event.logical_key == Key::Named(winit::keyboard::NamedKey::AltGraph) { + // Linux AltGr is usually Mod5, absent from ModifiersState::ALT. + self.alt_graph_pressed.set(event.state == winit::event::ElementState::Pressed); + } let key_code = event.logical_key.clone(); // For now: Match Qt's behavior of mapping command to control and control to meta (LWin/RWin). let swap_cmd_ctrl = i_slint_core::is_apple_platform(); @@ -1366,6 +1437,34 @@ impl WinitWindowAdapter { #[allow(unused_mut)] let mut text = to_slint_key(&event, &key_code); + #[cfg(target_os = "linux")] + if matches!(key_code, Key::Character(_)) { + use winit::keyboard::{KeyCode, PhysicalKey}; + let physical = match event.physical_key { + PhysicalKey::Code(KeyCode::KeyA) => Some('a'), + PhysicalKey::Code(KeyCode::KeyC) => Some('c'), + PhysicalKey::Code(KeyCode::KeyV) => Some('v'), + PhysicalKey::Code(KeyCode::KeyX) => Some('x'), + PhysicalKey::Code(KeyCode::KeyY) => Some('y'), + PhysicalKey::Code(KeyCode::KeyZ) => Some('z'), + PhysicalKey::Code(KeyCode::KeyF) => Some('f'), + PhysicalKey::Code(KeyCode::KeyS) => Some('s'), + PhysicalKey::Code(KeyCode::KeyP) => Some('p'), + PhysicalKey::Code(KeyCode::KeyR) => Some('r'), + _ => None, + }; + let modifiers = self.keyboard_modifiers.get(); + if let Some(letter) = crate::keyboard_shortcuts::shortcut_letter( + text.as_str(), + physical, + modifiers.control_key(), + modifiers.alt_key() || self.alt_graph_pressed.get(), + modifiers.super_key(), + ) { + text = letter.to_string().into(); + } + } + #[cfg(target_os = "windows")] let text_without_modifiers = { use winit::platform::modifier_supplement::KeyEventExtModifierSupplement; diff --git a/protocol/lnex.proto b/protocol/lnex.proto index 84fb355..53c7a1d 100644 --- a/protocol/lnex.proto +++ b/protocol/lnex.proto @@ -12,7 +12,7 @@ message Hello { reserved 5; reserved "server_eph_pubkey"; bool private_mode = 6; - // Ed25519 over "VNOX-LNEx-v3-server-hello\0" || tls_exporter || Hello(signature empty). + // Ed25519 over "VNOX-LNEx-v4-server-hello\0" || tls_exporter || Hello(signature empty). bytes server_signature = 7; } @@ -24,12 +24,20 @@ message Auth { bytes signature = 4; reserved 5; reserved "client_eph_pubkey"; + // Mandatory Central account proof, bound to client_pubkey (LNEx v4). + bytes account_proof = 6; } message Session { string session_id = 1; string token = 2; int64 expires_at = 3; + bool node_admin = 4; + // Live ProfileUpdate/ProfileUpdated support. Absent on legacy v4 gateways. + bool live_profiles = 5; + bool node_settings = 6; + bool channel_structure = 7; + bool forums = 8; } // ─── KEEPALIVE ────────────────────────────────────────────────────────────── @@ -54,12 +62,16 @@ message ChannelState { repeated MemberInfo members = 4; string voice_endpoint = 5; optional string guild_id = 6; + optional string parent_id = 7; + int32 position = 8; } message MemberInfo { string user_id = 1; string nickname = 2; bool in_voice = 3; + string account_id = 4; + string avatar_url = 5; } message ChannelCreate { @@ -67,6 +79,8 @@ message ChannelCreate { string channel_name = 2; string kind = 3; optional string guild_id = 4; + optional string parent_id = 5; + int32 position = 6; } message ChannelDelete { string channel_id = 1; } @@ -74,6 +88,8 @@ message ChannelDelete { string channel_id = 1; } message ChannelEdit { string channel_id = 1; string channel_name = 2; + optional string parent_id = 3; + optional int32 position = 4; } message ChannelList { @@ -86,9 +102,11 @@ message ChannelListItem { string channel_name = 2; string kind = 3; optional string guild_id = 4; + optional string parent_id = 5; + int32 position = 6; } -message UserJoin { string channel_id = 1; string user_id = 2; string nickname = 3; } +message UserJoin { string channel_id = 1; string user_id = 2; string nickname = 3; string account_id = 4; string avatar_url = 5; } message UserLeave { string channel_id = 1; string user_id = 2; } // ─── CHAT ──────────────────────────────────────────────────────────────────── @@ -464,3 +482,45 @@ message VoiceFrame { bytes opus = 5; string sender_user_id = 6; } + +// Additive channel image attachment extension; see docs/02-protocol/chat-attachments.md. +message AttachmentUpload { string request_id = 1; string channel_id = 2; bytes data = 3; } +message AttachmentFetch { string request_id = 1; string channel_id = 2; string attachment_id = 3; } +message AttachmentResult { string request_id = 1; string channel_id = 2; string attachment_id = 3; string mime = 4; bytes data = 5; string error = 6; } + +// Additive live Central profile metadata, LNEx v4. Authorization is unchanged. +message ProfileUpdate { bytes account_proof = 1; } +message ProfileUpdated { + string user_id = 1; + string account_id = 2; + string nickname = 3; + string avatar_url = 4; + int64 issued_at = 5; +} + +// Optional post-SESSION feature report; no AUTH transcript extension. +message ClientFeatures { bool node_settings = 1; bool channel_structure = 2; bool forums = 3; } +message NodeSettingsRequest { string request_id = 1; bool update = 2; string display_name = 3; string description = 4; } +message NodeSettingsResult { string request_id = 1; string display_name = 2; string description = 3; uint32 error_code = 4; string error = 5; } +enum ForumOperation { + FORUM_OPERATION_UNSPECIFIED = 0; + FORUM_OPERATION_LIST = 1; + FORUM_OPERATION_CREATE = 2; + FORUM_OPERATION_OPEN = 3; + FORUM_OPERATION_REPLY = 4; +} +message ForumRequest { + string request_id = 1; + ForumOperation operation = 2; + string channel_id = 3; + string topic_id = 4; + string title = 5; + string content = 6; + uint32 offset = 7; + uint32 limit = 8; + string message_id = 9; +} +message ForumTopic { string topic_id = 1; string channel_id = 2; string title = 3; MemberInfo author = 4; int64 created_at = 5; int64 updated_at = 6; uint32 reply_count = 7; } +message ForumPost { ChatMessage message = 1; MemberInfo author = 2; string topic_id = 3; uint64 ordinal = 4; } +message ForumResult { string request_id = 1; ForumOperation operation = 2; string channel_id = 3; string topic_id = 4; repeated ForumTopic topics = 5; repeated ForumPost posts = 6; bool has_more = 7; uint32 error_code = 8; string error = 9; } +message ForumChanged { string channel_id = 1; ForumTopic topic = 2; ForumPost post = 3; } diff --git a/src/audio/devices/mod.rs b/src/audio/devices/mod.rs index 92ca71f..72e4a96 100644 --- a/src/audio/devices/mod.rs +++ b/src/audio/devices/mod.rs @@ -67,16 +67,17 @@ pub(crate) fn raw_device(device: &cpal::Device, alsa: bool) -> Option pub fn enumerate() -> Result { let host = cpal::default_host(); let alsa = is_alsa(&host); - let collect = |devices: Vec| { + let collect = |devices: Vec, input: bool| { let raw: Vec = devices .iter() .filter_map(|device| raw_device(device, alsa)) + .filter(|device| !input || !device.id.ends_with(".monitor")) .collect(); filter::visible_devices(&raw, alsa) }; Ok(DeviceLists { - input: collect(host.input_devices()?.collect()), - output: collect(host.output_devices()?.collect()), + input: collect(host.input_devices()?.collect(), true), + output: collect(host.output_devices()?.collect(), false), }) } diff --git a/src/audio/microphone_test.rs b/src/audio/microphone_test.rs new file mode 100644 index 0000000..8fdf337 --- /dev/null +++ b/src/audio/microphone_test.rs @@ -0,0 +1,628 @@ +//! Explicit, bounded local microphone monitoring. No network or voice-session access. +use super::{ + DenoiseState, + config::{AudioConfig, OPUS_RATE}, + devices, +}; +use anyhow::{Context, Result}; +use cpal::traits::{DeviceTrait, StreamTrait}; +use std::{ + sync::{ + Arc, Mutex, + atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering}, + }, + time::{Duration, Instant}, +}; + +const FRAME: usize = 480; +const PREFILL: usize = OPUS_RATE as usize / 50; // 20 ms absorbs callback scheduling variation. +const HIGH_WATER: usize = OPUS_RATE as usize / 25; // Trim at 40 ms, never accumulate old speech. +const CAPACITY: usize = OPUS_RATE as usize * 60 / 1000; + +/// One producer, one consumer. Only the consumer advances `read`; a full writer drops new +/// samples. Slots are atomic as well, so no unsafe shared memory or realtime mutex is needed. +struct MonitorQueue { + samples: Box<[AtomicU32]>, + read: AtomicUsize, + write: AtomicUsize, + overrun: AtomicBool, +} +impl MonitorQueue { + fn new(capacity: usize) -> Self { + Self { + samples: (0..capacity).map(|_| AtomicU32::new(0)).collect(), + read: AtomicUsize::new(0), + write: AtomicUsize::new(0), + overrun: AtomicBool::new(false), + } + } + fn push(&self, sample: f32) -> bool { + let write = self.write.load(Ordering::Relaxed); + if write.wrapping_sub(self.read.load(Ordering::Acquire)) >= self.samples.len() { + self.overrun.store(true, Ordering::Release); + return false; + } + self.samples[write % self.samples.len()].store(sample.to_bits(), Ordering::Relaxed); + self.write.store(write.wrapping_add(1), Ordering::Release); + true + } + fn pop(&self) -> Option { + let read = self.read.load(Ordering::Relaxed); + if read == self.write.load(Ordering::Acquire) { + return None; + } + let sample = + f32::from_bits(self.samples[read % self.samples.len()].load(Ordering::Relaxed)); + self.read.store(read.wrapping_add(1), Ordering::Release); + Some(sample) + } + fn len(&self) -> usize { + self.write + .load(Ordering::Acquire) + .wrapping_sub(self.read.load(Ordering::Acquire)) + } + fn trim_to(&self, target: usize) { + let read = self.read.load(Ordering::Relaxed); + let count = self.write.load(Ordering::Acquire).wrapping_sub(read); + if count > target { + self.read + .store(read.wrapping_add(count - target), Ordering::Release); + } + } +} + +/// Rational phase survives callback boundaries, including non-integral 44.1/48 kHz ratios. +struct InputResampler { + from: u64, + to: u64, + index: u64, + next: u64, + previous: Option, +} +impl InputResampler { + fn new(from: u32, to: u32) -> Self { + Self { + from: from.into(), + to: to.into(), + index: 0, + next: 0, + previous: None, + } + } + fn sample(&mut self, value: f32, mut emit: impl FnMut(f32)) { + if let Some(previous) = self.previous { + let end = self.index * self.to; + let start = (self.index - 1) * self.to; + while self.next <= end { + let fraction = (self.next - start) as f64 / self.to as f64; + emit(previous + (value - previous) * fraction as f32); + self.next += self.from; + } + } else { + emit(value); + self.next = self.from; + } + self.previous = Some(value); + self.index += 1; + } +} + +struct Playback { + current: f32, + next: f32, + phase: f64, + started: bool, + gain: f32, + last: f32, + filtered_depth: f64, + underruns: usize, + trims: usize, +} +impl Default for Playback { + fn default() -> Self { + Self { + current: 0.0, + next: 0.0, + phase: 0.0, + started: false, + gain: 0.0, + last: 0.0, + filtered_depth: PREFILL as f64, + underruns: 0, + trims: 0, + } + } +} +impl Playback { + fn render( + &mut self, + queue: &MonitorQueue, + data: &mut [f32], + channels: usize, + rate: u32, + volume: f32, + ) { + let depth = queue.len(); + let overrun = queue.overrun.swap(false, Ordering::AcqRel); + if overrun || depth > HIGH_WATER { + // A full writer drops new data. After a stalled output this queue may contain + // old speech of arbitrary age, so flush it and prefill fresh capture instead. + queue.trim_to(if overrun { 0 } else { PREFILL }); + self.trims += 1; + self.started = false; + self.gain = 0.0; + } + // Independent device clocks drift. A slow, bounded servo changes the resampling + // ratio by at most 0.2%, rather than periodically dropping whole 10 ms frames. + self.filtered_depth += (queue.len() as f64 - self.filtered_depth) * 0.02; + let correction = + ((self.filtered_depth - PREFILL as f64) / OPUS_RATE as f64 * 0.5).clamp(-0.002, 0.002); + let step = OPUS_RATE as f64 / rate as f64 * (1.0 + correction); + for frame in data.chunks_mut(channels) { + if !self.started && queue.len() >= PREFILL { + self.current = queue.pop().unwrap_or(0.0); + self.next = queue.pop().unwrap_or(0.0); + self.phase = 0.0; + self.started = true; + self.gain = 0.0; + } + let value = if self.started { + self.gain = (self.gain + 1.0 / 64.0).min(1.0); + let value = + (self.current + (self.next - self.current) * self.phase as f32) * self.gain; + self.phase += step; + while self.phase >= 1.0 { + self.phase -= 1.0; + self.current = self.next; + if let Some(next) = queue.pop() { + self.next = next; + } else { + self.started = false; + self.underruns += 1; + break; + } + } + self.last = value; + value + } else { + // A short release avoids discontinuities on an underrun; prefill before restart. + self.last *= 0.95; + if self.last.abs() < 0.00001 { + self.last = 0.0; + } + self.last + }; + frame.fill(value.clamp(-1.0, 1.0) * 0.5 * volume); + } + } +} + +struct Meter { + level: f32, + observed: Instant, + hold_until: Instant, +} +impl Default for Meter { + fn default() -> Self { + let now = Instant::now(); + Self { + level: 0.0, + observed: now, + hold_until: now, + } + } +} +impl Meter { + fn read(&mut self, peak: f32, now: Instant) -> f32 { + let decay_start = self.observed.max(self.hold_until); + if now > decay_start { + self.level *= (-(now - decay_start).as_secs_f32() / 0.18).exp(); + } + if peak >= self.level && peak > 0.0 { + self.level = peak; + self.hold_until = now + Duration::from_millis(60); + } + self.observed = now; + self.level.clamp(0.0, 1.0) + } +} + +#[derive(Default)] +struct Shared { + stopped: AtomicBool, + running: AtomicBool, + peak: AtomicU32, + denoise: AtomicBool, + volume: AtomicU32, + error: Mutex>, + meter: Mutex, +} + +/// A thirty-second local test, stopped immediately when its owner is dropped. +pub struct MicrophoneTest(Arc); +impl MicrophoneTest { + pub fn start( + input: String, + output: String, + denoise: bool, + volume: f32, + previous_workers: Option>, + ) -> Result { + let shared = Arc::new(Shared::default()); + shared.running.store(true, Ordering::Release); + shared.denoise.store(denoise, Ordering::Relaxed); + shared.volume.store( + (volume / 100.0).clamp(0.0, 1.0).to_bits(), + Ordering::Relaxed, + ); + let worker = shared.clone(); + std::thread::Builder::new() + .name("microphone-test".into()) + .spawn(move || { + if let Err(error) = wait_and_monitor(&input, &output, &worker, previous_workers) + && let Ok(mut slot) = worker.error.lock() + { + *slot = Some(format!("{error:#}")); + } + worker.running.store(false, Ordering::Release); + })?; + Ok(Self(shared)) + } + pub fn stop(&self) { + self.0.stopped.store(true, Ordering::Release); + } + pub fn set_volume(&self, value: f32) { + self.0 + .volume + .store((value / 100.0).clamp(0.0, 1.0).to_bits(), Ordering::Relaxed); + } + pub fn running(&self) -> bool { + self.0.running.load(Ordering::Acquire) + } + pub fn level(&self) -> f32 { + let peak = f32::from_bits(self.0.peak.swap(0, Ordering::Relaxed)); + self.0 + .meter + .lock() + .map(|mut meter| meter.read(peak, Instant::now())) + .unwrap_or(peak) + .clamp(0.0, 1.0) + } + pub fn set_denoise(&self, value: bool) { + self.0.denoise.store(value, Ordering::Relaxed); + } + pub fn take_error(&self) -> Option { + self.0.error.lock().ok()?.take() + } +} +impl Drop for MicrophoneTest { + fn drop(&mut self) { + self.0.stopped.store(true, Ordering::Release); + } +} + +fn wait_and_monitor( + input: &str, + output: &str, + shared: &Arc, + previous: Option>, +) -> Result<()> { + if let Some(previous) = previous { + let deadline = Instant::now() + Duration::from_secs(5); + while previous.load(Ordering::Acquire) != 0 { + if shared.stopped.load(Ordering::Acquire) { + return Ok(()); + } + anyhow::ensure!( + Instant::now() < deadline, + "previous audio streams are still closing; retry shortly" + ); + std::thread::sleep(Duration::from_millis(10)); + } + } + if shared.stopped.load(Ordering::Acquire) { + return Ok(()); + } + monitor(input, output, shared) +} + +fn monitor(input: &str, output: &str, shared: &Arc) -> Result<()> { + let microphone = devices::open_input(input)?; + let speakers = devices::open_output(output)?; + let streams = build_streams(µphone, &speakers, shared, true).or_else(|error| { + tracing::warn!(%error, "low-latency monitor configuration unavailable; retrying device defaults"); + build_streams(µphone, &speakers, shared, false) + })?; + if shared.stopped.load(Ordering::Acquire) { + return Ok(()); + } + streams.1.play()?; + streams.0.play()?; + let deadline = Instant::now() + Duration::from_secs(30); + while !shared.stopped.load(Ordering::Acquire) && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(10)); + } + Ok(()) +} + +fn request_small_buffer( + device: &cpal::Device, + config: &mut AudioConfig, + input: bool, +) -> Result<()> { + let ranges: Vec<_> = if input { + device.supported_input_configs()?.collect() + } else { + device.supported_output_configs()?.collect() + }; + if let Some(range) = ranges.iter().find(|range| { + range.sample_format() == cpal::SampleFormat::F32 + && range.channels() == config.stream.channels + && range.min_sample_rate() <= config.sample_rate + && range.max_sample_rate() >= config.sample_rate + }) && let cpal::SupportedBufferSize::Range { min, max } = *range.buffer_size() + { + config.stream.buffer_size = cpal::BufferSize::Fixed( + (config.sample_rate / 200).clamp(min.max(1), max.max(min).max(1)), + ); + } + Ok(()) +} + +fn build_streams( + microphone: &cpal::Device, + speakers: &cpal::Device, + shared: &Arc, + small_buffers: bool, +) -> Result<(cpal::Stream, cpal::Stream)> { + let mut capture = AudioConfig::find(microphone, true)?; + let mut playback = AudioConfig::find(speakers, false)?; + if small_buffers { + request_small_buffer(microphone, &mut capture, true)?; + request_small_buffer(speakers, &mut playback, false)?; + } + tracing::info!(input_buffer = ?capture.stream.buffer_size, output_buffer = ?playback.stream.buffer_size, "local monitor requested callback buffers (not measured round-trip latency)"); + let input_channels = capture.stream.channels as usize; + let output_channels = playback.stream.channels as usize; + let output_rate = playback.sample_rate; + let queue = Arc::new(MonitorQueue::new(CAPACITY)); + let captured = queue.clone(); + let metrics = shared.clone(); + let capture_error = shared.clone(); + let output_error = shared.clone(); + let monitor_volume = shared.clone(); + let mut denoise = DenoiseState::new()?; + let mut resampler = InputResampler::new(capture.sample_rate, OPUS_RATE); + let mut pending = [0.0; FRAME]; + let mut pending_len = 0; + let input_stream = microphone + .build_input_stream( + capture.stream, + move |data: &[f32], _| { + if metrics.stopped.load(Ordering::Acquire) { + return; + } + for channels in data.chunks_exact(input_channels) { + let mono = channels + .iter() + .copied() + .filter(|sample| sample.is_finite()) + .sum::() + / input_channels as f32; + resampler.sample(mono.clamp(-1.0, 1.0), |sample| { + pending[pending_len] = sample; + pending_len += 1; + if pending_len == FRAME { + if metrics.denoise.load(Ordering::Relaxed) { + denoise.process(&mut pending); + } + let peak = pending + .iter() + .fold(0.0_f32, |peak, sample| peak.max(sample.abs())) + .clamp(0.0, 1.0); + metrics.peak.fetch_max(peak.to_bits(), Ordering::Relaxed); + for sample in pending { + captured.push(sample); + } + pending_len = 0; + } + }); + } + }, + move |error| { + if let Ok(mut slot) = capture_error.error.lock() { + *slot = Some(error.to_string()); + } + capture_error.stopped.store(true, Ordering::Release); + }, + None, + ) + .context("cannot open microphone for local test")?; + let mut reader = Playback::default(); + let output_stream = speakers + .build_output_stream( + playback.stream, + move |data: &mut [f32], _| { + if monitor_volume.stopped.load(Ordering::Acquire) { + data.fill(0.0); + return; + } + let volume = f32::from_bits(monitor_volume.volume.load(Ordering::Relaxed)); + reader.render(&queue, data, output_channels, output_rate, volume); + }, + move |error| { + if let Ok(mut slot) = output_error.error.lock() { + *slot = Some(error.to_string()); + } + output_error.stopped.store(true, Ordering::Release); + }, + None, + ) + .context("cannot open output for local test")?; + Ok((input_stream, output_stream)) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn queue_is_bounded_and_only_consumer_discards_old_audio() { + let queue = MonitorQueue::new(3); + assert!(queue.push(1.0)); + assert!(queue.push(2.0)); + assert!(queue.push(3.0)); + assert!(!queue.push(4.0)); + queue.trim_to(2); + assert_eq!(queue.pop(), Some(2.0)); + assert!(queue.push(5.0)); + assert_eq!(queue.pop(), Some(3.0)); + assert_eq!(queue.pop(), Some(5.0)); + assert_eq!(queue.pop(), None); + } + #[test] + fn resampling_is_identical_across_irregular_callback_boundaries() { + for (from, to) in [(44100, 48000), (96000, 48000), (48000, 48000)] { + let samples: Vec<_> = (0..from).map(|i| (i as f32 * 0.01).sin()).collect(); + let mut whole = InputResampler::new(from, to); + let mut expected = Vec::new(); + for &sample in &samples { + whole.sample(sample, |sample| expected.push(sample)); + } + let mut split = InputResampler::new(from, to); + let mut actual = Vec::new(); + for chunk in samples.chunks(137) { + for &sample in chunk { + split.sample(sample, |sample| actual.push(sample)); + } + } + assert_eq!(actual, expected); + assert!((actual.len() as isize - to as isize).abs() <= 2); + } + } + #[test] + fn stalled_playback_trims_latency_and_underrun_rebuffers() { + let queue = MonitorQueue::new(CAPACITY); + for _ in 0..CAPACITY { + assert!(queue.push(0.5)); + } + let mut playback = Playback::default(); + let mut output = [0.0; 240]; + playback.render(&queue, &mut output, 1, OPUS_RATE, 1.0); + assert!(queue.len() < PREFILL); + assert!( + output + .iter() + .all(|sample| sample.is_finite() && *sample <= 0.25) + ); + for _ in 0..30 { + playback.render(&queue, &mut output, 1, OPUS_RATE, 1.0); + } + assert!(!playback.started); + assert!(output.iter().all(|sample| sample.abs() < 0.00001)); + } + #[test] + fn overflow_discards_stale_speech_and_waits_for_fresh_capture() { + let queue = MonitorQueue::new(CAPACITY); + for _ in 0..CAPACITY { + assert!(queue.push(0.9)); + } + for _ in 0..OPUS_RATE { + assert!(!queue.push(-0.2)); + } + let mut playback = Playback::default(); + let mut output = [0.0; 240]; + playback.render(&queue, &mut output, 1, OPUS_RATE, 1.0); + assert_eq!(queue.len(), 0); + assert!(output.iter().all(|sample| *sample == 0.0)); + for _ in 0..PREFILL { + assert!(queue.push(-0.2)); + } + playback.render(&queue, &mut output, 1, OPUS_RATE, 1.0); + assert!(output.iter().all(|sample| *sample < 0.0)); + } + + #[test] + fn independent_clocks_and_irregular_callbacks_do_not_accumulate_latency() { + for (rate, ppm) in [(44100_u32, -1000.0), (48000, 0.0), (96000, 1000.0)] { + let queue = MonitorQueue::new(CAPACITY); + let mut playback = Playback::default(); + let mut time = 0.0; + let mut capture_at = 0.0; + let mut output = [0.0; 2048]; + for callback in 0..12000 { + let frames = [137, 256, 91, 480][callback % 4]; + let next = time + frames as f64 / rate as f64; + while capture_at <= next { + for _ in 0..FRAME { + assert!(queue.push(0.2)); + } + capture_at += 0.01 / (1.0 + ppm / 1_000_000.0); + } + playback.render(&queue, &mut output[..frames], 1, rate, 1.0); + assert!(output[..frames].iter().all(|sample| sample.is_finite())); + assert!(queue.len() <= HIGH_WATER); + time = next; + } + assert_eq!(playback.underruns, 0, "rate {rate}, drift {ppm}"); + assert_eq!(playback.trims, 0, "rate {rate}, drift {ppm}"); + } + } + + #[test] + fn spsc_transfers_ordered_samples_across_threads_without_locks() { + let queue = Arc::new(MonitorQueue::new(127)); + let writer = queue.clone(); + let producer = std::thread::spawn(move || { + for sample in 0..100_000 { + while !writer.push(sample as f32) { + std::thread::yield_now(); + } + } + }); + for expected in 0..100_000 { + let sample = loop { + if let Some(sample) = queue.pop() { + break sample; + } + std::thread::yield_now(); + }; + assert_eq!(sample, expected as f32); + } + producer.join().unwrap(); + assert_eq!(queue.len(), 0); + } + + #[test] + fn meter_holds_peaks_and_releases_smoothly_without_callback_flicker() { + let now = Instant::now(); + let mut meter = Meter { + observed: now, + hold_until: now, + level: 0.0, + }; + assert_eq!(meter.read(0.8, now), 0.8); + assert_eq!(meter.read(0.0, now + Duration::from_millis(16)), 0.8); + let later = meter.read(0.0, now + Duration::from_millis(100)); + assert!(later > 0.5 && later < 0.8); + assert!(meter.read(0.0, now + Duration::from_secs(1)) < 0.01); + } + #[test] + fn dropping_test_revokes_capture_and_meter_consumes_peak() { + let shared = Arc::new(Shared::default()); + shared.peak.store(0.5_f32.to_bits(), Ordering::Relaxed); + let test = MicrophoneTest(shared.clone()); + assert_eq!(test.level(), 0.5); + assert!(test.level() >= 0.49); + drop(test); + assert!(shared.stopped.load(Ordering::Acquire)); + } + + #[test] + fn cancelling_while_old_streams_close_never_opens_new_devices() { + let shared = Arc::new(Shared::default()); + shared.stopped.store(true, Ordering::Release); + let previous = Arc::new(AtomicUsize::new(2)); + // No backend/stream access occurs on this cancellation path. + assert!(wait_and_monitor("missing", "missing", &shared, Some(previous)).is_ok()); + } +} diff --git a/src/audio/mod.rs b/src/audio/mod.rs index 1f272eb..3612c52 100644 --- a/src/audio/mod.rs +++ b/src/audio/mod.rs @@ -1,6 +1,7 @@ pub mod config; pub mod devices; pub mod diagnostics; +pub mod microphone_test; mod pipeline; mod processing; pub mod sounds; diff --git a/src/audio/pipeline/capture.rs b/src/audio/pipeline/capture.rs index 45b6977..57c5834 100644 --- a/src/audio/pipeline/capture.rs +++ b/src/audio/pipeline/capture.rs @@ -76,6 +76,7 @@ pub fn run( .context("cannot start the microphone stream")?; info!("capture started ({} Hz)", cfg.sample_rate); let mut vad = VoiceActivity::default(); + let mut speaking_indicator = VoiceActivity::default(); let mut silent_frames: u32 = 0; let mut silence_reported = false; @@ -121,9 +122,10 @@ pub fn run( if gate_snapshot.noise_suppress { denoise.process(&mut pcm); } - let speaking = gate_snapshot.decide(&pcm, &mut vad, frame_ms); + let transmitting = gate_snapshot.decide(&pcm, &mut vad, frame_ms); + let speaking = speech_indicator(&pcm, transmitting, &mut speaking_indicator, frame_ms); local_speaking.store(speaking, Ordering::Relaxed); - if !speaking { + if !transmitting { b = buf.lock().unwrap(); continue; } @@ -162,6 +164,16 @@ fn raw_peak(samples: &[f32]) -> f32 { samples.iter().fold(0.0f32, |peak, s| peak.max(s.abs())) } +fn speech_indicator( + pcm: &[f32], + transmitting: bool, + detector: &mut VoiceActivity, + frame_ms: u32, +) -> bool { + let speech = detector.update(crate::audio::processing::frame_rms(pcm), 0.02, frame_ms); + transmitting && speech +} + fn frame_samples_at(sample_rate: u32, frame_ms: u32) -> usize { (sample_rate as usize * frame_ms as usize) / 1000 } @@ -182,7 +194,15 @@ fn apply_bitrate( #[cfg(test)] mod tests { - use super::frame_samples_at; + use super::{VoiceActivity, frame_samples_at, speech_indicator}; + + #[test] + fn open_microphone_silence_does_not_light_the_speaking_ring() { + let mut detector = VoiceActivity::default(); + assert!(!speech_indicator(&[0.0; 960], true, &mut detector, 20)); + assert!(speech_indicator(&[0.1; 960], true, &mut detector, 20)); + assert!(!speech_indicator(&[0.1; 960], false, &mut detector, 20)); + } #[test] fn frame_sizes_scale_with_ms() { diff --git a/src/audio/pipeline/mod.rs b/src/audio/pipeline/mod.rs index 1a7f4f7..a1d97ec 100644 --- a/src/audio/pipeline/mod.rs +++ b/src/audio/pipeline/mod.rs @@ -6,7 +6,7 @@ mod playback; use std::sync::{ Arc, Mutex, - atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}, + atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering}, mpsc::{self, Receiver, Sender}, }; use tracing::info; @@ -19,7 +19,15 @@ use crate::audio::{ pub use playback::JitterConfig; +struct WorkerFinished(Arc); +impl Drop for WorkerFinished { + fn drop(&mut self) { + self.0.fetch_sub(1, Ordering::Release); + } +} + pub struct AudioPipeline { + workers: Arc, stopped: Arc, encoded_rx: Receiver, microphone_tap: media::MicrophoneTap, @@ -49,6 +57,18 @@ impl Drop for AudioPipeline { } impl AudioPipeline { + /// Completes only after both worker functions have released their audio streams. + pub fn shutdown_signal(&self) -> Arc { + self.workers.clone() + } + + /// Mutes outgoing capture before a separate local monitoring stream starts. + pub fn pause_microphone(&self) { + if let Ok(mut gate) = self.gate.lock() { + gate.mic_enabled = false; + } + self.local_speaking.store(false, Ordering::Relaxed); + } pub fn enable_media_microphone(&self, enabled: bool) { self.microphone_tap.enable(enabled); } @@ -158,7 +178,10 @@ pub fn start(cfg: PipelineConfig) -> anyhow::Result { let (encoded_tx, encoded_rx) = mpsc::channel::(); let (voice_tx, voice_rx) = mpsc::channel::(); - let gate = Arc::new(Mutex::new(TransmitGate::default())); + let gate = Arc::new(Mutex::new(TransmitGate { + mic_enabled: false, + ..Default::default() + })); let gate_cap = gate.clone(); let output_volume = Arc::new(Mutex::new(90.0f32)); let vol_play = output_volume.clone(); @@ -181,7 +204,11 @@ pub fn start(cfg: PipelineConfig) -> anyhow::Result { let capture_stopped = stopped.clone(); let channel_id = cfg.channel_key; let enc_tx = encoded_tx.clone(); + let workers = Arc::new(AtomicUsize::new(2)); + let capture_workers = workers.clone(); + let playback_workers = workers.clone(); std::thread::spawn(move || { + let _finished = WorkerFinished(capture_workers); if let Err(e) = capture::run( input, in_cfg, @@ -199,6 +226,7 @@ pub fn start(cfg: PipelineConfig) -> anyhow::Result { } }); std::thread::spawn(move || { + let _finished = WorkerFinished(playback_workers); if let Err(e) = playback::run( output, out_cfg, @@ -215,6 +243,7 @@ pub fn start(cfg: PipelineConfig) -> anyhow::Result { }); Ok(AudioPipeline { + workers, stopped, encoded_rx, microphone_tap, diff --git a/src/audio/processing/rnnoise.rs b/src/audio/processing/rnnoise.rs index 405c129..20d9e13 100644 --- a/src/audio/processing/rnnoise.rs +++ b/src/audio/processing/rnnoise.rs @@ -19,8 +19,8 @@ mod imp { } pub fn process(&mut self, pcm: &mut [f32]) { - for chunk in pcm.chunks_exact_mut(FRAME_SIZE) { - let input: Vec = chunk.iter().map(|&s| s * 32768.0).collect(); + for chunk in pcm.as_chunks_mut::().0 { + let input: [f32; FRAME_SIZE] = std::array::from_fn(|index| chunk[index] * 32768.0); self.inner.process_frame(&mut self.out_buf, &input); for (out, &denoised) in chunk.iter_mut().zip(self.out_buf.iter()) { *out = (denoised / 32768.0).clamp(-1.0, 1.0); @@ -28,6 +28,28 @@ mod imp { } } } + #[cfg(test)] + mod tests { + use super::*; + #[test] + fn repeated_frames_keep_scratch_storage_and_finite_normalized_output() { + let mut state = DenoiseState::new().unwrap(); + let scratch = state.out_buf.as_ptr(); + for index in 0..32 { + let mut frame = std::array::from_fn::<_, FRAME_SIZE, _>(|sample| { + ((sample + index * FRAME_SIZE) as f32 * 0.03).sin() * 0.2 + }); + state.process(&mut frame); + assert!( + frame + .iter() + .all(|sample| sample.is_finite() && sample.abs() <= 1.0) + ); + assert_eq!(state.out_buf.as_ptr(), scratch); + assert_eq!(state.out_buf.len(), FRAME_SIZE); + } + } + } } #[cfg(not(feature = "rnnoise"))] diff --git a/src/main.rs b/src/main.rs index 00e5527..343e397 100644 --- a/src/main.rs +++ b/src/main.rs @@ -20,6 +20,9 @@ use vnox_client::net::NetHandle; use crate::ui::state::{ConnState, UiState}; pub struct AppState { + pub(crate) audio_shutdown: Option>, + pub(crate) microphone_test: Option, + pub(crate) device_refresh: ui::devices::DeviceRefresh, pub(crate) webhooks: Option>, pub(crate) connection_generation: u64, pub(crate) identity: identity::Identity, @@ -49,6 +52,9 @@ fn main() -> Result<()> { let net = net::spawn(identity.clone()); let state = Rc::new(RefCell::new(AppState { + audio_shutdown: None, + microphone_test: None, + device_refresh: Default::default(), webhooks: None, connection_generation: 0, identity, @@ -62,6 +68,7 @@ fn main() -> Result<()> { { let mut s = state.borrow_mut(); crate::ui::preferences::load(&mut s.ui); + crate::ui::connection::load(&mut s.ui); s.ui.appearance = crate::ui::appearance::AppearancePreferences::load(); s.ui.vault_enabled = identity::is_vault_encrypted(); let user_id = s.identity.pubkey_hex.clone(); @@ -70,7 +77,7 @@ fn main() -> Result<()> { } let window = MainWindow::new()?; window.set_address_input(state.borrow().ui.connect_input.as_str().into()); - refresh_devices(&window, &mut state.borrow_mut().ui); + sync_device_models(&window, &state.borrow().ui); let webhook_net = state.borrow().net.clone(); state.borrow_mut().webhooks = Some(Rc::new(ui::webhooks::WebhookUi::new(Rc::new( @@ -82,7 +89,10 @@ fn main() -> Result<()> { }, ))?)); wire_signals(&window, &state); + ui::forum::wire(&window, &state); + let _account_timer = ui::account::wire(&window, &state); ui::media::wire(&window, &state)?; + ui::chat_media::wire(&window, &state); let timer = slint::Timer::default(); { @@ -94,11 +104,52 @@ fn main() -> Result<()> { move || { if let Some(win) = weak.upgrade() { let mut s = state.borrow_mut(); + if let Some(result) = s.device_refresh.take_ready() { + match result { + Ok(lists) => { + ui::devices::apply_refresh(&mut s.ui, lists); + sync_device_models(&win, &s.ui); + } + Err(error) => tracing::warn!(%error, "cannot enumerate audio devices"), + } + } + if !s.ui.settings_open + && let Some(test) = s.microphone_test.as_ref() + { + test.stop(); + } + if let Some(test) = s.microphone_test.as_ref() { + let running = test.running(); + let level = test.level(); + let error = test.take_error(); + test.set_denoise(s.ui.noise_suppress); + test.set_volume(s.ui.output_volume); + s.ui.mic_test_running = running; + s.ui.mic_test_level = level.max(s.ui.mic_test_level * 0.85); + if error.is_some() { + s.ui.mic_test_error = error; + } + if !running { + s.microphone_test = None; + } + } else { + s.ui.mic_test_running = false; + s.ui.mic_test_level = 0.0; + } + if s.audio_shutdown.as_ref().is_some_and(|workers| { + workers.load(std::sync::atomic::Ordering::Acquire) == 0 + }) { + s.audio_shutdown = None; + } crate::ui::update::process_net_events(&mut s); + if s.ui.connection.authentication_required { + win.set_account_authenticated(false); + } let own_id = s.identity.pubkey_hex.clone(); let own_nick = s.identity.nickname.clone(); let own_pubkey = s.identity.pubkey_hex.clone(); crate::ui::bridge::sync_ui(&win, &s.ui, &own_id, &own_nick, &own_pubkey); + crate::ui::chat_media::tick(&win, &s); } }, ); @@ -145,8 +196,7 @@ fn load_identity() -> Result> { } } -fn refresh_devices(window: &MainWindow, ui: &mut UiState) { - crate::ui::devices::refresh(ui); +fn sync_device_models(window: &MainWindow, ui: &UiState) { let model = |items: Vec| { Rc::new(slint::VecModel::from( items @@ -197,7 +247,66 @@ fn wire_signals(window: &MainWindow, state: &Rc>) { }); } + { + let state = state.clone(); + window.on_refresh_audio_devices(move || state.borrow_mut().device_refresh.request()); + } + { + let state = state.clone(); + window.on_device_selected(move |input, output| { + let mut s = state.borrow_mut(); + if let Some(test) = s.microphone_test.as_ref() { + test.stop(); + } + crate::ui::devices::select(&mut s.ui, input.max(0) as usize, output.max(0) as usize); + if let Err(error) = crate::ui::preferences::save(&s.ui) { + tracing::warn!(%error, "cannot save devices"); + } + }); + } + { + let state = state.clone(); + window.on_noise_suppression_changed(move |enabled| { + let mut s = state.borrow_mut(); + s.ui.noise_suppress = enabled && cfg!(feature = "rnnoise"); + if let Err(error) = crate::ui::preferences::save(&s.ui) { + tracing::warn!(%error, "cannot save noise suppression"); + } + }); + } + { + let state = state.clone(); + window.on_toggle_microphone_test(move || { + let mut s = state.borrow_mut(); + if let Some(test) = s.microphone_test.as_ref() { + test.stop(); + return; + } + s.ui.mic_test_error = None; + let previous_workers = s + .audio + .take() + .map(|audio| audio.shutdown_signal()) + .or_else(|| s.audio_shutdown.clone()); + s.audio_shutdown = previous_workers.clone(); + s.voice_channel = None; + match vnox_client::audio::microphone_test::MicrophoneTest::start( + s.ui.mic_device_id.clone(), + s.ui.output_device_id.clone(), + s.ui.noise_suppress, + s.ui.output_volume, + previous_workers, + ) { + Ok(test) => { + s.microphone_test = Some(test); + s.ui.mic_test_running = true; + } + Err(error) => s.ui.mic_test_error = Some(error.to_string()), + } + }); + } ui::emoji::wire(window); + ui::channel_admin::wire(window, state); crate::ui::appearance::wire(window, state, !cfg!(test)); ui::i18n::wire(window, !cfg!(test)); crate::ui::avatar::wire(window, state, !cfg!(test)); @@ -216,7 +325,9 @@ fn wire_signals(window: &MainWindow, state: &Rc>) { } { let state = state.clone(); - window.on_auto_reconnect_changed(move |value| state.borrow_mut().ui.auto_reconnect = value); + window.on_auto_reconnect_changed(move |value| { + ui::connection::set_auto_reconnect(&mut state.borrow_mut(), value) + }); } { let state = state.clone(); @@ -225,13 +336,10 @@ fn wire_signals(window: &MainWindow, state: &Rc>) { } { let state = state.clone(); - let weak = window.as_weak(); window.on_open_settings(move || { let mut s = state.borrow_mut(); s.ui.settings_open = true; - if let Some(window) = weak.upgrade() { - refresh_devices(&window, &mut s.ui); - } + s.device_refresh.request(); }); } { @@ -250,7 +358,13 @@ fn wire_signals(window: &MainWindow, state: &Rc>) { let state = state.clone(); window.on_audio_settings_changed(move |input, output, bitrate, mode, volume| { let mut s = state.borrow_mut(); + let old_devices = (s.ui.mic_device_id.clone(), s.ui.output_device_id.clone()); crate::ui::devices::select(&mut s.ui, input.max(0) as usize, output.max(0) as usize); + if old_devices != (s.ui.mic_device_id.clone(), s.ui.output_device_id.clone()) + && let Some(test) = s.microphone_test.as_ref() + { + test.stop(); + } s.ui.voice_bitrate = bitrate.clamp(8.0, 128.0); let mode = mode.clamp(0, 2) as usize; if mode != s.ui.vad_mode { @@ -273,15 +387,12 @@ fn wire_signals(window: &MainWindow, state: &Rc>) { window.on_channel_selected(move |id| { let id = id.to_string(); let mut s = state.borrow_mut(); - let is_voice = - s.ui.channels - .iter() - .any(|c| c.id == id && c.kind == "voice"); - let send_join = if is_voice { - s.ui.request_voice_join(&id) - } else { - s.ui.select_text_channel(id.clone()); - true + let kind = s.ui.channels.iter().find(|channel| channel.id == id && channel.guild_id == s.ui.active_guild_id).map(|channel|channel.kind.as_str()).unwrap_or("").to_owned(); + if kind == "forum" { ui::forum::select(&mut s, &id); return; } + let send_join = match kind.as_str() { + "voice" => s.ui.request_voice_join(&id), + "text" => { s.ui.select_text_channel(id.clone()); true }, + _ => return, }; let net = s.net.clone(); drop(s); @@ -349,21 +460,7 @@ fn wire_signals(window: &MainWindow, state: &Rc>) { { let state = state.clone(); window.on_connect(move |addr| { - let addr = addr.to_string(); - let mut s = state.borrow_mut(); - s.ui.conn = ConnState::Connecting; - s.ui.connect_input = addr.clone(); - s.ui.status_msg = Some("Connecting…".into()); - let auto_reconnect = s.ui.auto_reconnect; - let net = s.net.clone(); - drop(s); - tokio::spawn(async move { - net.send(NetCommand::Connect { - address: addr, - auto_reconnect, - }) - .await; - }); + ui::connection::connect(&mut state.borrow_mut(), addr.to_string()); }); } @@ -383,18 +480,7 @@ fn wire_signals(window: &MainWindow, state: &Rc>) { s.ui.status_msg = Some("Could not save the trusted fingerprint".into()); return; } - s.ui.conn = ConnState::Connecting; - s.ui.status_msg = Some("Connecting…".into()); - let auto_reconnect = s.ui.auto_reconnect; - let net = s.net.clone(); - drop(s); - tokio::spawn(async move { - net.send(NetCommand::Connect { - address: prompt.address, - auto_reconnect, - }) - .await; - }); + ui::connection::connect(&mut s, prompt.address); }); } @@ -424,7 +510,8 @@ fn wire_signals(window: &MainWindow, state: &Rc>) { { let state = state.clone(); window.on_disconnect(move || { - let s = state.borrow(); + let mut s = state.borrow_mut(); + ui::connection::disconnect(&mut s); let net = s.net.clone(); drop(s); tokio::spawn(async move { @@ -446,6 +533,7 @@ fn wire_signals(window: &MainWindow, state: &Rc>) { s.ui.status_msg = Some("Not connected to a server. Your draft has been kept.".into()); return; } + if s.ui.active_dm_id.is_none() && !s.ui.channels.iter().any(|channel| channel.id == ch_id && channel.kind == "text") { return; } if let Some(dm_id) = s.ui.active_dm_id.as_ref() && s.ui.dm_conversations.iter().any(|c| &c.dm_id == dm_id && c.e2ee_enabled) { @@ -628,7 +716,7 @@ fn wire_signals(window: &MainWindow, state: &Rc>) { let state = state.clone(); window.on_leave_voice(move || { let mut s = state.borrow_mut(); - let voice_channel = s.ui.voice_target.take(); + let voice_channels = s.ui.take_voice_leave_targets(); let was_in_voice = s.audio.is_some(); crate::ui::update::stop_voice(&mut s); if was_in_voice { @@ -637,9 +725,11 @@ fn wire_signals(window: &MainWindow, state: &Rc>) { s.ui.showing_voice = false; s.ui.ptt_held = false; let net = s.net.clone(); - if let Some(channel_id) = voice_channel { + if !voice_channels.is_empty() { tokio::spawn(async move { - net.send(NetCommand::LeaveChannel { channel_id }).await; + for channel_id in voice_channels { + net.send(NetCommand::LeaveChannel { channel_id }).await; + } }); } }); @@ -679,6 +769,10 @@ fn wire_signals(window: &MainWindow, state: &Rc>) { window.on_close_settings(move || { let mut state = state.borrow_mut(); state.ui.settings_open = false; + if let Some(test) = state.microphone_test.as_ref() { + test.stop(); + } + state.ui.mic_test_running = false; if let Some(window) = weak.upgrade() { crate::ui::appearance::bindings_restore(&window, &state.ui.appearance); } diff --git a/src/net/account.rs b/src/net/account.rs new file mode 100644 index 0000000..286d197 --- /dev/null +++ b/src/net/account.rs @@ -0,0 +1,845 @@ +//! Real Central browser sign-in and identity-bound account admission. +//! +//! Device/refresh secrets never enter browser URLs or logs. The identity private key +//! stays on this device; account proofs contain only the matching public key. +use crate::identity::Identity; +use anyhow::{Context, Result, bail, ensure}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use std::{ + path::PathBuf, + time::{Duration, SystemTime, UNIX_EPOCH}, +}; +use tokio::sync::{mpsc, watch}; + +pub const CENTRAL_ORIGIN: &str = "https://central.loki-code.dev"; +const MAX_RESPONSE: usize = 32 * 1024; + +/// Enrollment is missing or revoked: another browser approval is required. +#[derive(Debug)] +pub struct SignInRequired; +impl std::fmt::Display for SignInRequired { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("Central sign-in expired or was revoked; sign in again") + } +} +impl std::error::Error for SignInRequired {} + +/// Public account details safe to show in desktop UI. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct AccountSummary { + pub user_id: String, + pub handle: String, + pub display_name: String, + pub avatar_url: Option, + #[serde(default)] + pub profile_complete: bool, +} + +/// Non-secret, identity-scoped profile notification; credentials never enter UI events. +#[derive(Clone)] +pub struct ProfileUpdate { + pub proof: Option>, + pub epoch: u64, + pub public_key: String, + pub user: AccountSummary, +} +static ENROLLMENT_EPOCH: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +pub fn enrollment_epoch() -> u64 { + ENROLLMENT_EPOCH.load(std::sync::atomic::Ordering::SeqCst) +} +fn enrollment_changed() { + ENROLLMENT_EPOCH.fetch_add(1, std::sync::atomic::Ordering::SeqCst); +} +static PROFILE_UPDATES: std::sync::LazyLock>> = + std::sync::LazyLock::new(|| watch::channel(None).0); +static PROFILE_REQUESTS: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); +static STORE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); +pub fn subscribe_profiles() -> watch::Receiver> { + PROFILE_UPDATES.subscribe() +} +pub fn latest_profile() -> Option { + PROFILE_UPDATES.borrow().clone() +} + +/// A pending login contains a bearer secret. Intentionally does not implement Debug. +pub struct PendingLogin { + pub verification_uri: String, + pub public_key: String, + pub expires_at: i64, + device_secret: String, +} + +/// Sign-in progress, containing no device or refresh secret. +#[derive(Debug, Clone)] +pub enum LoginEvent { + ApprovalRequired { + verification_uri: String, + public_key: String, + expires_at: i64, + }, +} + +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct StoredAccount { + version: u32, + public_key: String, + refresh_secret: String, + user: AccountSummary, +} + +fn now() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs() as i64 +} +fn client() -> Result { + Ok(reqwest::Client::builder() + .https_only(true) + .redirect(reqwest::redirect::Policy::none()) + .connect_timeout(Duration::from_secs(10)) + .timeout(Duration::from_secs(10)) + .user_agent("VNOX-Desktop/0.1") + .build()?) +} +async fn response_json(response: reqwest::Response) -> Result { + ensure!( + response.content_length().unwrap_or(0) <= MAX_RESPONSE as u64, + "Central response exceeds size limit" + ); + let mut response = response; + let mut bytes = Vec::new(); + while let Some(chunk) = response.chunk().await? { + ensure!( + bytes.len() + chunk.len() <= MAX_RESPONSE, + "Central response exceeds size limit" + ); + bytes.extend_from_slice(&chunk); + } + serde_json::from_slice(&bytes).context("Invalid response from Central") +} +async fn post(path: &str, body: &Value) -> Result { + client()? + .post(format!("{CENTRAL_ORIGIN}{path}")) + .json(body) + .send() + .await + .context("Cannot reach Central; check your connection and retry") +} +fn field<'a>(value: &'a Value, key: &str) -> Result<&'a str> { + value + .get(key) + .and_then(Value::as_str) + .with_context(|| format!("Central response is missing {key}")) +} +fn validate_key(identity: &Identity) -> Result<()> { + let key = identity + .signing_key() + .context("Unlock your local identity before signing in")?; + ensure!( + hex::encode(key.verifying_key().to_bytes()) == identity.pubkey_hex, + "Local identity key mismatch" + ); + Ok(()) +} + +/// Start a 10-minute pairing request. Open only its verification_uri in the browser. +pub async fn begin(identity: &Identity) -> Result { + validate_key(identity)?; + let _ = tokio::time::timeout(Duration::from_secs(2), retry_revocations()).await; + let response = post( + "/v1/auth/desktop/start", + &json!({"public_key":identity.pubkey_hex}), + ) + .await?; + ensure!( + response.status().is_success(), + "Central could not start sign-in; retry shortly" + ); + let value = response_json(response).await?; + let uri = field(&value, "verification_uri")?.to_owned(); + let parsed = reqwest::Url::parse(&uri)?; + ensure!( + parsed.origin().ascii_serialization() == CENTRAL_ORIGIN + && parsed.path() == "/desktop" + && parsed.username().is_empty() + && parsed.password().is_none(), + "Central returned an invalid approval URL" + ); + let expires_at = value + .get("expires_at") + .and_then(Value::as_i64) + .context("Missing sign-in expiry")?; + ensure!( + expires_at > now() && expires_at <= now() + 610, + "Invalid sign-in expiry" + ); + let device_secret = field(&value, "device_secret")?.to_owned(); + ensure!( + device_secret.len() == 64 && hex::decode(&device_secret).is_ok(), + "Invalid device request" + ); + Ok(PendingLogin { + verification_uri: uri, + public_key: identity.pubkey_hex.clone(), + expires_at, + device_secret, + }) +} + +/// Poll once. Call at most once per five seconds. Approved requests are single-use. +pub async fn poll(pending: &PendingLogin, identity: &Identity) -> Result> { + ensure!( + pending.public_key == identity.pubkey_hex, + "Identity changed during sign-in" + ); + ensure!(pending.expires_at > now(), "Sign-in expired; start again"); + let response = post( + "/v1/auth/desktop/poll", + &json!({"device_secret":pending.device_secret}), + ) + .await?; + if response.status() == reqwest::StatusCode::ACCEPTED { + return Ok(None); + } + ensure!( + response.status().is_success(), + "Sign-in expired or was canceled; start again" + ); + let value = response_json(response).await?; + validate_proof(&value, identity)?; + let user: AccountSummary = serde_json::from_value( + value + .get("user") + .cloned() + .context("Missing Central account")?, + )?; + let refresh_secret = field(&value, "refresh_secret")?.to_owned(); + ensure!( + refresh_secret.len() == 64 && hex::decode(&refresh_secret).is_ok(), + "Invalid Central enrollment" + ); + save(&StoredAccount { + version: 1, + public_key: identity.pubkey_hex.clone(), + refresh_secret, + user: user.clone(), + })?; + Ok(Some(user)) +} + +/// Cancel a pending pairing. Expiry remains enforced if Central is unreachable. +pub async fn cancel(pending: &PendingLogin) -> Result<()> { + let response = post( + "/v1/auth/desktop/cancel", + &json!({"device_secret":pending.device_secret}), + ) + .await?; + ensure!( + response.status().is_success(), + "Could not cancel sign-in at Central" + ); + Ok(()) +} + +/// Run the complete cancellable device flow. The UI opens the URL from LoginEvent. +/// Sending true on cancel stops polling and attempts server-side cancellation. +pub async fn sign_in( + identity: &Identity, + updates: mpsc::UnboundedSender, + mut cancellation: watch::Receiver, +) -> Result { + ensure!(!*cancellation.borrow(), "Sign-in canceled"); + let pending = begin(identity).await?; + if updates + .send(LoginEvent::ApprovalRequired { + verification_uri: pending.verification_uri.clone(), + public_key: pending.public_key.clone(), + expires_at: pending.expires_at, + }) + .is_err() + { + let _ = cancel(&pending).await; + bail!("Sign-in window closed"); + } + loop { + tokio::select! { + _=tokio::time::sleep(Duration::from_secs(5))=>{}, + _=cancellation.changed()=>{ + let _=cancel(&pending).await; + bail!("Sign-in canceled"); + } + } + if *cancellation.borrow() { + let _ = cancel(&pending).await; + bail!("Sign-in canceled"); + } + // Cancel in-flight polls too. Hub cancellation also revokes a consumed + // enrollment if the approved HTTP reply was lost. + let approved = tokio::select! { + result=poll(&pending,identity)=>match result { + Ok(approved)=>approved, + Err(error)=>{let _=cancel(&pending).await;return Err(error)} + }, + _=cancellation.changed()=>{ + let _=cancel(&pending).await; + bail!("Sign-in canceled"); + } + }; + if let Some(user) = approved { + if *cancellation.borrow() { + let cleared = clear(); + let _ = cancel(&pending).await; + cleared?; + bail!("Sign-in canceled"); + } + return Ok(user); + } + } +} + +/// Locally enrolled account for UI startup. Admission always refreshes online. +pub fn current(identity: &Identity) -> Result> { + Ok(load(identity)?.map(|stored| stored.user)) +} + +/// Revoke enrollment and remove local credentials. Disconnect gateway sessions in UI +/// before calling this function; admission proofs expire within ten minutes. +pub async fn sign_out(identity: &Identity) -> Result<()> { + let stored = match load(identity) { + Ok(stored) => stored, + Err(error) => { + clear()?; + return Err(error); + } + }; + if let Some(stored) = stored { + // Rename atomically disables admission while preserving the secret needed to + // retry revocation after an outage. Tombstones are never loaded for admission. + let tombstone = { + let _guard = STORE_LOCK + .lock() + .map_err(|_| anyhow::anyhow!("Account state is unavailable"))?; + let current = load(identity)?.ok_or(SignInRequired)?; + ensure!( + current.refresh_secret == stored.refresh_secret, + "Central enrollment changed during sign-out" + ); + let tombstone = queue_revocation(&path())?; + enrollment_changed(); + tombstone + }; + revoke_secret(&stored.refresh_secret).await?; + std::fs::remove_file(tombstone)?; + } else { + clear()?; + } + Ok(()) +} + +async fn revoke_secret(secret: &str) -> Result<()> { + let response = post("/v1/auth/desktop/revoke", &json!({"refresh_secret":secret})).await?; + ensure!( + response.status().is_success(), + "Signed out locally; Central revocation is queued for retry" + ); + Ok(()) +} +fn queue_revocation(active: &std::path::Path) -> Result { + let directory = active.parent().context("Missing account directory")?; + let tombstone = directory.join(format!("pending-revocation-{}.json", uuid::Uuid::new_v4())); + std::fs::rename(active, &tombstone)?; + #[cfg(unix)] + std::fs::File::open(directory)?.sync_all()?; + Ok(tombstone) +} +/// Retry admission-disabled revocations left by a previous offline sign-out. Callers +/// bound the total attempt time; retries are safe because Hub revocation is idempotent. +pub async fn retry_revocations() -> Result<()> { + let active = path(); + let Some(directory) = active.parent() else { + return Ok(()); + }; + let entries = match std::fs::read_dir(directory) { + Ok(entries) => entries, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(error.into()), + }; + for entry in entries.take(64) { + let entry = entry?; + let name = entry.file_name(); + let Some(name) = name.to_str() else { continue }; + if !name.starts_with("pending-revocation-") || !name.ends_with(".json") { + continue; + } + let file = std::fs::File::open(entry.path())?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + ensure!( + file.metadata()?.permissions().mode() & 0o077 == 0, + "Revocation credentials must remain private" + ); + } + ensure!( + file.metadata()?.len() <= MAX_RESPONSE as u64, + "Revocation credentials too large" + ); + let stored: StoredAccount = serde_json::from_reader(file)?; + revoke_secret(&stored.refresh_secret).await?; + std::fs::remove_file(entry.path())?; + } + Ok(()) +} + +/// Obtain a fresh identity-bound signed proof for every gateway admission. Missing or +/// revoked enrollment and Central outage fail closed; no anonymous fallback exists. +pub async fn admission_proof(identity: &Identity) -> Result> { + validate_key(identity)?; + let _ = tokio::time::timeout(Duration::from_secs(2), retry_revocations()).await; + let value = refresh(identity).await?; + validate_proof(&value, identity) +} + +/// Refresh public profile at startup/settings entry and periodically; also refresh admission. +pub async fn refresh_profile(identity: &Identity) -> Result { + let value = refresh(identity).await?; + summary(&value, identity, true) +} +async fn refresh(identity: &Identity) -> Result { + let _request = PROFILE_REQUESTS.lock().await; + validate_key(identity)?; + let stored = load(identity)?.ok_or(SignInRequired)?; + let response = post( + "/v1/auth/desktop/refresh", + &json!({"refresh_secret":stored.refresh_secret}), + ) + .await?; + if response.status() == reqwest::StatusCode::UNAUTHORIZED { + return Err(SignInRequired.into()); + } + ensure!( + response.status().is_success(), + "Central could not refresh your profile; retry shortly" + ); + let value = response_json(response).await?; + let proof = validate_proof(&value, identity)?; + let user = summary(&value, identity, true)?; + update_summary(identity, &stored, user, Some(proof))?; + Ok(value) +} +fn summary(value: &Value, identity: &Identity, proof_required: bool) -> Result { + let user: AccountSummary = serde_json::from_value( + value + .get("user") + .cloned() + .context("Missing Central account")?, + )?; + ensure!( + uuid::Uuid::parse_str(&user.user_id).is_ok_and(|id| !id.is_nil()), + "Invalid Central account" + ); + ensure!( + !user.display_name.trim().is_empty() && user.display_name.chars().count() <= 64, + "Invalid Central profile name" + ); + if proof_required { + let claim: Value = serde_json::from_slice(&hex::decode(field( + value + .get("account_proof") + .context("Missing account proof")?, + "claims", + )?)?)?; + ensure!( + field(&claim, "subject")? == user.user_id + && field(&claim, "public_key")? == identity.pubkey_hex, + "Central profile does not match admission proof" + ); + } + Ok(user) +} +fn update_summary( + identity: &Identity, + enrolled: &StoredAccount, + user: AccountSummary, + proof: Option>, +) -> Result<()> { + let _guard = STORE_LOCK + .lock() + .map_err(|_| anyhow::anyhow!("Account state is unavailable"))?; + update_summary_at(&path(), identity, enrolled, user.clone())?; + PROFILE_UPDATES.send_replace(Some(ProfileUpdate { + proof, + epoch: enrollment_epoch(), + public_key: identity.pubkey_hex.clone(), + user, + })); + Ok(()) +} + +fn update_summary_at( + account_path: &std::path::Path, + identity: &Identity, + enrolled: &StoredAccount, + user: AccountSummary, +) -> Result<()> { + ensure!( + user.user_id == enrolled.user.user_id, + "Central account changed unexpectedly" + ); + let mut current = load_at(account_path, identity)?.ok_or(SignInRequired)?; + ensure!( + current.refresh_secret == enrolled.refresh_secret, + "Central enrollment changed during request" + ); + current.user = user; + save_at(account_path, ¤t) +} + +/// Save a cropped PNG to the enrolled Central account, or remove its custom photo. +pub async fn set_avatar( + identity: &Identity, + png: Option>, + epoch: u64, +) -> Result { + let method = if png.is_some() { + reqwest::Method::POST + } else { + reqwest::Method::DELETE + }; + mutation( + identity, + "/v1/auth/desktop/avatar", + method, + png.unwrap_or_default(), + "image/png", + epoch, + ) + .await +} +/// Set the account's display name without changing its unique handle or device keys. +pub async fn set_display_name( + identity: &Identity, + name: &str, + epoch: u64, +) -> Result { + mutation( + identity, + "/v1/auth/desktop/profile", + reqwest::Method::POST, + serde_json::to_vec(&json!({"display_name":name}))?, + "application/json", + epoch, + ) + .await +} +async fn mutation( + identity: &Identity, + path: &str, + method: reqwest::Method, + body: Vec, + content_type: &str, + epoch: u64, +) -> Result { + use ed25519_dalek::Signer; + use sha2::{Digest, Sha256}; + let _request = PROFILE_REQUESTS.lock().await; + ensure!( + epoch == enrollment_epoch(), + "Account changed; choose your profile again" + ); + validate_key(identity)?; + let stored = load(identity)?.ok_or(SignInRequired)?; + ensure!( + body.len() <= 2 * 1024 * 1024, + "Profile upload exceeds size limit" + ); + let timestamp = now().to_string(); + let mut transcript = b"VNOX-CENTRAL-PROFILE-v1\0".to_vec(); + transcript.extend_from_slice(method.as_str().as_bytes()); + transcript.push(0); + transcript.extend_from_slice(path.as_bytes()); + transcript.push(0); + transcript.extend_from_slice(timestamp.as_bytes()); + transcript.push(0); + transcript.extend_from_slice(&Sha256::digest(&body)); + let signature = identity + .signing_key() + .context("Unlock your identity to change your profile")? + .sign(&transcript); + let response = client()? + .request(method, format!("{CENTRAL_ORIGIN}{path}")) + .bearer_auth(&stored.refresh_secret) + .header("x-vnox-public-key", &identity.pubkey_hex) + .header("x-vnox-timestamp", timestamp) + .header("x-vnox-signature", hex::encode(signature.to_bytes())) + .header(reqwest::header::CONTENT_TYPE, content_type) + .body(body) + .send() + .await + .context("Cannot reach Central; profile was not changed")?; + if response.status() == reqwest::StatusCode::UNAUTHORIZED { + return Err(SignInRequired.into()); + } + if !response.status().is_success() { + let error = response_json(response).await.unwrap_or_default(); + bail!(match error.get("error").and_then(Value::as_str) { + Some("invalid_display_name") => + "Display name must contain 1–64 characters without control characters", + Some("too_large") => "Photo is too large to upload", + Some("invalid_image" | "unsupported_type") => + "Central could not read this photo; choose another PNG", + Some("try_later") => "Too many profile changes or Central is busy; retry shortly", + _ => "Central could not update your profile; retry shortly", + }); + } + let value = response_json(response).await?; + let user = summary(&value, identity, false)?; + update_summary(identity, &stored, user.clone(), None)?; + Ok(user) +} + +fn validate_proof(value: &Value, identity: &Identity) -> Result> { + let proof = value + .get("account_proof") + .context("Missing Central account proof")?; + let claims = hex::decode(field(proof, "claims")?).context("Invalid account proof")?; + ensure!(claims.len() <= 4096, "Account proof too large"); + let claim: Value = serde_json::from_slice(&claims)?; + ensure!( + field(&claim, "public_key")? == identity.pubkey_hex, + "Central proof belongs to another local identity" + ); + ensure!( + field(&claim, "audience")? == "vnox-gateway" + && claim.get("version").and_then(Value::as_u64) == Some(1), + "Invalid Central proof audience or version" + ); + ensure!( + uuid::Uuid::parse_str(field(&claim, "subject")?).is_ok() + && uuid::Uuid::parse_str(field(&claim, "issuer")?).is_ok(), + "Invalid Central proof identity" + ); + let issued = claim + .get("issued_at") + .and_then(Value::as_i64) + .context("Missing proof issue time")?; + let expires = claim + .get("expires_at") + .and_then(Value::as_i64) + .context("Missing proof expiry")?; + ensure!( + issued <= now() + && expires > now() + && expires + .checked_sub(issued) + .is_some_and(|ttl| ttl > 0 && ttl <= 600), + "Central account proof expired or has invalid lifetime" + ); + ensure!( + hex::decode(field(proof, "signature")?).is_ok_and(|s| s.len() == 64), + "Invalid account proof signature encoding" + ); + let bytes = serde_json::to_vec(proof)?; + ensure!(bytes.len() <= 8192, "Account proof too large"); + Ok(bytes) +} + +fn path() -> PathBuf { + dirs::data_dir() + .unwrap_or_else(|| PathBuf::from(".")) + .join("vnox") + .join("account") + .join("central.json") +} +fn load(identity: &Identity) -> Result> { + load_at(&path(), identity) +} +fn load_at(account_path: &std::path::Path, identity: &Identity) -> Result> { + let file = match std::fs::File::open(account_path) { + Ok(f) => f, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(e.into()), + }; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + ensure!( + file.metadata()?.permissions().mode() & 0o077 == 0, + "Central account credentials must use private 0600 permissions" + ); + } + ensure!( + file.metadata()?.len() <= MAX_RESPONSE as u64, + "Account credentials too large" + ); + let stored: StoredAccount = + serde_json::from_reader(file).context("Invalid saved Central account; sign in again")?; + ensure!(stored.version == 1, "Unsupported account credentials"); + if stored.public_key != identity.pubkey_hex { + return Ok(None); + } + Ok(Some(stored)) +} +fn save(stored: &StoredAccount) -> Result<()> { + let _guard = STORE_LOCK + .lock() + .map_err(|_| anyhow::anyhow!("Account state is unavailable"))?; + save_unlocked(stored)?; + enrollment_changed(); + Ok(()) +} +fn save_unlocked(stored: &StoredAccount) -> Result<()> { + save_at(&path(), stored) +} +fn save_at(path: &std::path::Path, stored: &StoredAccount) -> Result<()> { + let directory = path.parent().context("Missing credential directory")?; + let mut builder = std::fs::DirBuilder::new(); + builder.recursive(true); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt; + builder.mode(0o700); + } + builder.create(directory)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + ensure!( + std::fs::metadata(directory)?.permissions().mode() & 0o077 == 0, + "Central credential directory must use private 0700 permissions" + ); + } + let temporary = directory.join(format!("{}.tmp", uuid::Uuid::new_v4())); + let mut options = std::fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let result = (|| -> Result<()> { + use std::io::Write; + let mut file = options.open(&temporary)?; + file.write_all(&serde_json::to_vec(stored)?)?; + file.sync_all()?; + std::fs::rename(&temporary, path)?; + #[cfg(unix)] + std::fs::File::open(directory)?.sync_all()?; + Ok(()) + })(); + let _ = std::fs::remove_file(&temporary); + result +} +fn clear() -> Result<()> { + match std::fs::remove_file(path()) { + Ok(()) => { + enrollment_changed(); + Ok(()) + } + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(e) => Err(e.into()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + fn response(identity: &Identity, issued: i64, expires: i64) -> Value { + let claim = json!({"version":1,"issuer":uuid::Uuid::new_v4().to_string(),"subject":uuid::Uuid::new_v4().to_string(),"public_key":identity.pubkey_hex,"audience":"vnox-gateway","issued_at":issued,"expires_at":expires}); + json!({"account_proof":{"claims":hex::encode(serde_json::to_vec(&claim).unwrap()),"signature":"00".repeat(64)}}) + } + #[test] + fn refreshed_website_avatar_is_persisted_and_stale_enrollment_cannot_restore_it() { + let identity = crate::identity::generate("profile"); + let directory = + std::env::temp_dir().join(format!("vnox-profile-test-{}", uuid::Uuid::new_v4())); + let path = directory.join("central.json"); + let original = StoredAccount { + version: 1, + public_key: identity.pubkey_hex.clone(), + refresh_secret: "01".repeat(32), + user: AccountSummary { + user_id: uuid::Uuid::new_v4().to_string(), + handle: "profile".into(), + display_name: "Old Name".into(), + avatar_url: Some("/v1/avatars/old".into()), + profile_complete: false, + }, + }; + save_at(&path, &original).unwrap(); + let mut fresh = original.user.clone(); + fresh.avatar_url = Some("/v1/avatars/new".into()); + fresh.display_name = "New Name".into(); + update_summary_at(&path, &identity, &original, fresh.clone()).unwrap(); + assert_eq!(load_at(&path, &identity).unwrap().unwrap().user, fresh); + let mut replacement = original; + replacement.refresh_secret = "02".repeat(32); + save_at(&path, &replacement).unwrap(); + let mut old_request = replacement.user.clone(); + old_request.avatar_url = Some("/v1/avatars/stale".into()); + let mut stale = StoredAccount { + version: 1, + public_key: identity.pubkey_hex.clone(), + refresh_secret: "01".repeat(32), + user: replacement.user.clone(), + }; + assert!(update_summary_at(&path, &identity, &stale, old_request.clone()).is_err()); + assert_eq!( + load_at(&path, &identity).unwrap().unwrap().user, + replacement.user + ); + stale.refresh_secret = replacement.refresh_secret; + std::fs::remove_file(&path).unwrap(); + assert!(update_summary_at(&path, &identity, &stale, old_request).is_err()); + assert!( + !path.exists(), + "sign-out must not be undone by late refresh" + ); + std::fs::remove_dir(directory).unwrap(); + } + #[test] + fn queued_revocation_atomically_disables_admission_and_preserves_retry_secret() { + let directory = + std::env::temp_dir().join(format!("vnox-revoke-test-{}", uuid::Uuid::new_v4())); + std::fs::create_dir(&directory).unwrap(); + let active = directory.join("central.json"); + std::fs::write(&active, b"retry secret").unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&active, std::fs::Permissions::from_mode(0o600)).unwrap(); + } + let tombstone = queue_revocation(&active).unwrap(); + assert!(!active.exists()); + assert_eq!(std::fs::read(&tombstone).unwrap(), b"retry secret"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!( + std::fs::metadata(&tombstone).unwrap().permissions().mode() & 0o077, + 0 + ); + } + std::fs::remove_file(tombstone).unwrap(); + std::fs::remove_dir(directory).unwrap(); + } + #[test] + fn rejects_other_identity_expiry_and_overlong_proof() { + let identity = crate::identity::generate("test"); + let t = now(); + assert!(validate_proof(&response(&identity, t, t + 600), &identity).is_ok()); + assert!( + validate_proof( + &response(&identity, t, t + 600), + &crate::identity::generate("other") + ) + .is_err() + ); + assert!(validate_proof(&response(&identity, t - 601, t - 1), &identity).is_err()); + assert!(validate_proof(&response(&identity, t, t + 601), &identity).is_err()); + assert!(validate_proof(&response(&identity, t + 60, t + 600), &identity).is_err()); + } +} diff --git a/src/net/forum.rs b/src/net/forum.rs new file mode 100644 index 0000000..e31d80b --- /dev/null +++ b/src/net/forum.rs @@ -0,0 +1,47 @@ +//! Capability-gated forum packets. Errors retain request correlation and never cancel voice joins. +use super::{framing, payloads::PID_FORUM_REQUEST, types::NetEvent, wire}; +use tokio::io::AsyncWrite; +use tokio::sync::mpsc; + +pub fn is_mutation(request: &wire::ForumRequest) -> bool { + matches!(wire::ForumOperation::try_from(request.operation), Ok(wire::ForumOperation::Create | wire::ForumOperation::Reply)) +} + +pub async fn unsupported(request: &wire::ForumRequest, events: &mpsc::Sender) { + error(request, "This server does not support forums yet.", events).await; +} +pub async fn error(request: &wire::ForumRequest, message: &str, events: &mpsc::Sender) { + let _ = events.send(NetEvent::ForumResult(wire::ForumResult { + request_id: request.request_id.clone(), operation: request.operation, + channel_id: request.channel_id.clone(), topic_id: request.topic_id.clone(), + error_code: u32::MAX, error: message.into(), + ..Default::default() + })).await; +} + +pub async fn write(stream: &mut (impl AsyncWrite + Unpin), seq: &mut u32, request: &wire::ForumRequest) -> anyhow::Result<()> { + framing::write(stream, PID_FORUM_REQUEST, seq, &wire::encode(request)?).await +} + +#[cfg(test)] +mod tests { + use super::*; + #[tokio::test] + async fn unsupported_server_returns_correlated_forum_error_without_join_error() { + let (tx, mut rx) = mpsc::channel(1); + let request = wire::ForumRequest { request_id: "request".into(), channel_id: "forum".into(), topic_id: "topic".into(), operation: wire::ForumOperation::Open as i32, ..Default::default() }; + unsupported(&request, &tx).await; + let NetEvent::ForumResult(result) = rx.recv().await.unwrap() else { panic!("forum errors must stay separate from join errors") }; + assert_eq!(result.request_id, "request"); assert_eq!(result.channel_id, "forum"); assert_eq!(result.topic_id, "topic"); assert_ne!(result.error_code, 0); + } + #[tokio::test] + async fn request_wire_keeps_topic_message_and_pagination_fields() { + let request = wire::ForumRequest { request_id: "request".into(), operation: wire::ForumOperation::Create as i32, channel_id: "forum".into(), topic_id: "topic".into(), message_id: "message".into(), title: "Title".into(), content: "First post".into(), offset: 12, limit: 20 }; + let (mut sender, mut receiver) = tokio::io::duplex(4096); + write(&mut sender, &mut 0, &request).await.unwrap(); + let packet = framing::read(&mut receiver).await.unwrap(); + assert_eq!(packet.packet_id, PID_FORUM_REQUEST); + let decoded: wire::ForumRequest = wire::decode(&packet.payload).unwrap(); + assert_eq!(decoded, request); assert!(is_mutation(&decoded)); + } +} diff --git a/src/net/handshake.rs b/src/net/handshake.rs index 39abd57..581c530 100644 --- a/src/net/handshake.rs +++ b/src/net/handshake.rs @@ -8,8 +8,8 @@ use super::payloads::*; use super::trust::TransportError; use crate::identity::Identity; -const SERVER_HELLO_CONTEXT: &[u8] = b"VNOX-LNEx-v3-server-hello\0"; -const CLIENT_AUTH_CONTEXT: &[u8] = b"VNOX-LNEx-v3-client-auth\0"; +const SERVER_HELLO_CONTEXT: &[u8] = b"VNOX-LNEx-v4-server-hello\0"; +const CLIENT_AUTH_CONTEXT: &[u8] = b"VNOX-LNEx-v4-client-auth\0"; /// Bytes signed by the server identity: context, TLS exporter, HELLO without signature. pub fn server_hello_transcript(binding: &[u8], unsigned_hello: &[u8]) -> Vec { @@ -40,6 +40,11 @@ pub struct Outcome { pub session_id: String, pub node_name: String, pub private_mode: bool, + pub node_admin: bool, + pub live_profiles: bool, + pub node_settings: bool, + pub channel_structure: bool, + pub forums: bool, /// Lower-case hex Ed25519 identity of the server. pub server_identity: String, } @@ -56,6 +61,27 @@ pub async fn run( binding: &[u8], trust_key: &str, expected_identity: Option<&str>, +) -> Result { + run_inner( + stream, + identity, + seq, + binding, + trust_key, + expected_identity, + None, + ) + .await +} + +async fn run_inner( + stream: &mut (impl tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin), + identity: &Identity, + seq: &mut u32, + binding: &[u8], + trust_key: &str, + expected_identity: Option<&str>, + supplied_proof: Option>, ) -> Result { // HELLO let pkt = framing::read(stream).await?; @@ -117,11 +143,20 @@ pub async fn run( .ok_or_else(|| anyhow!("no signing key"))?; use ed25519_dalek::Signer; + let account_proof = match supplied_proof { + Some(proof) => proof, + None => crate::net::account::admission_proof(identity).await?, + }; + anyhow::ensure!( + !account_proof.is_empty(), + "Central account sign-in required" + ); let mut auth = AuthPayload { client_pubkey: sk.verifying_key().to_bytes().to_vec(), nickname: identity.nickname.clone(), lnex_version: LNEX_VERSION.into(), signature: Vec::new(), + account_proof, }; let transcript = client_auth_transcript(binding, &signed_hello, &wire::encode(&auth)?); auth.signature = sk.sign(&transcript).to_bytes().to_vec(); @@ -154,6 +189,11 @@ pub async fn run( session_id: sess.session_id, node_name: hello.node_name, private_mode: hello.private_mode, + node_admin: sess.node_admin, + live_profiles: sess.live_profiles, + node_settings: sess.node_settings, + channel_structure: sess.channel_structure, + forums: sess.forums, server_identity, }) } @@ -164,6 +204,26 @@ mod tests { use ed25519_dalek::{Signer, SigningKey}; use tokio::io::AsyncWriteExt; + async fn run_for_test( + stream: &mut (impl tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin), + identity: &Identity, + seq: &mut u32, + binding: &[u8], + trust_key: &str, + expected_identity: Option<&str>, + ) -> Result { + run_inner( + stream, + identity, + seq, + binding, + trust_key, + expected_identity, + Some(b"test-account-proof".to_vec()), + ) + .await + } + /// Scripted gateway: sends a HELLO signed over `hello_binding` and returns the AUTH it gets. async fn fake_server( mut stream: tokio::io::DuplexStream, @@ -199,6 +259,8 @@ mod tests { session_id: "session-1".into(), token: "token".into(), expires_at: 0, + node_admin: false, + live_profiles: false, }; framing::write( &mut stream, @@ -221,9 +283,9 @@ mod tests { async fn authenticated_handshake_returns_server_identity_and_binds_signature() { let server_key = SigningKey::generate(&mut rand::rng()); let (mut client, server) = tokio::io::duplex(8192); - let task = tokio::spawn(fake_server(server, server_key.clone(), [9; 32], "v3", true)); + let task = tokio::spawn(fake_server(server, server_key.clone(), [9; 32], "v4", true)); let mut seq = 0; - let outcome = run(&mut client, &identity(), &mut seq, &[9; 32], "h:7600", None) + let outcome = run_for_test(&mut client, &identity(), &mut seq, &[9; 32], "h:7600", None) .await .unwrap(); assert_eq!(outcome.session_id, "session-1"); @@ -233,6 +295,7 @@ mod tests { ); // The AUTH signature is valid for this connection and invalid for any other one. let (auth, signed_hello) = task.await.unwrap(); + assert_eq!(auth.account_proof, b"test-account-proof"); let client_public = ed25519_dalek::VerifyingKey::from_bytes( &auth.client_pubkey.clone().try_into().unwrap(), ) @@ -263,9 +326,9 @@ mod tests { let server_key = SigningKey::generate(&mut rand::rng()); let (mut client, server) = tokio::io::duplex(8192); // The relay forwards a HELLO signed for a different TLS session. - tokio::spawn(fake_server(server, server_key, [1; 32], "v3", false)); + tokio::spawn(fake_server(server, server_key, [1; 32], "v4", false)); let mut seq = 0; - let error = run(&mut client, &identity(), &mut seq, &[2; 32], "h:7600", None) + let error = run_for_test(&mut client, &identity(), &mut seq, &[2; 32], "h:7600", None) .await .unwrap_err(); assert!(error.to_string().contains("signature verification failed")); @@ -276,9 +339,9 @@ mod tests { async fn changed_server_identity_is_blocked_before_auth() { let server_key = SigningKey::generate(&mut rand::rng()); let (mut client, server) = tokio::io::duplex(8192); - tokio::spawn(fake_server(server, server_key, [3; 32], "v3", false)); + tokio::spawn(fake_server(server, server_key, [3; 32], "v4", false)); let mut seq = 0; - let error = run( + let error = run_for_test( &mut client, &identity(), &mut seq, @@ -301,12 +364,59 @@ mod tests { let (mut client, server) = tokio::io::duplex(8192); tokio::spawn(fake_server(server, server_key, [4; 32], "v2", false)); let mut seq = 0; - let error = run(&mut client, &identity(), &mut seq, &[4; 32], "h:7600", None) + let error = run_for_test(&mut client, &identity(), &mut seq, &[4; 32], "h:7600", None) .await .unwrap_err(); assert!(matches!( error.downcast_ref::(), - Some(TransportError::ProtocolMismatch(m)) if m.contains("v2") && m.contains("v3") + Some(TransportError::ProtocolMismatch(m)) if m.contains("v2") && m.contains("v4") )); } + #[tokio::test] + async fn empty_account_proof_is_rejected_before_auth() { + let key = SigningKey::generate(&mut rand::rng()); + let (mut client, server) = tokio::io::duplex(8192); + let task = tokio::spawn(fake_server(server, key, [9; 32], "v4", false)); + let mut seq = 0; + let error = run_inner( + &mut client, + &identity(), + &mut seq, + &[9; 32], + "h:7600", + None, + Some(Vec::new()), + ) + .await + .unwrap_err(); + assert!( + error + .to_string() + .contains("Central account sign-in required") + ); + assert_eq!(seq, 0); + drop(client); + task.await.unwrap(); + } +} + +#[cfg(test)] +mod capability_tests { + use super::*; + #[test] + fn legacy_sessions_do_not_advertise_admin_and_new_flag_roundtrips() { + let legacy: SessionPayload = wire::decode(&[10, 1, b's', 18, 1, b't']).unwrap(); + assert!(!legacy.node_admin); + assert!(!legacy.live_profiles); + let mut privileged = legacy; + privileged.node_admin = true; + privileged.live_profiles = true; + let bytes = wire::encode(&privileged).unwrap(); + assert!(wire::decode::(&bytes).unwrap().node_admin); + assert!( + wire::decode::(&bytes) + .unwrap() + .live_profiles + ); + } } diff --git a/src/net/internal/dispatch/channel.rs b/src/net/internal/dispatch/channel.rs index dfe8c2b..8d74adb 100644 --- a/src/net/internal/dispatch/channel.rs +++ b/src/net/internal/dispatch/channel.rs @@ -8,6 +8,11 @@ use super::super::super::types::{ChannelListItem as InfoChannelListItem, ChatMsg pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender) -> Result<()> { match pid { + PID_ATTACHMENT_RESULT => { + let _ = tx + .send(NetEvent::AttachmentResult(wire::decode(payload)?)) + .await; + } PID_CHANNEL_STATE => { let p: ChannelStatePayload = wire::decode(payload)?; let _ = tx @@ -22,10 +27,14 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender) -> Re user_id: m.user_id, nickname: m.nickname, in_voice: m.in_voice, + account_id: m.account_id, + avatar_url: m.avatar_url, }) .collect(), voice_endpoint: p.voice_endpoint, guild_id: p.guild_id, + parent_id: p.parent_id, + position: p.position, }) .await; } @@ -37,6 +46,18 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender) -> Re channel_name: p.channel_name, kind: p.kind, guild_id: p.guild_id, + parent_id: p.parent_id, + position: p.position, + }) + .await; + } + PID_CHANNEL_EDIT => { + let p: ChannelEditPayload = wire::decode(payload)?; + let _ = tx + .send(NetEvent::ChannelEdited { + channel_id: p.channel_id, + channel_name: p.channel_name, + parent_id: p.parent_id, position: p.position, }) .await; } @@ -60,6 +81,7 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender) -> Re channel_name: c.channel_name, kind: c.kind, guild_id: c.guild_id, + parent_id: c.parent_id, position: c.position, }) .collect(), }) @@ -102,6 +124,8 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender) -> Re let p: UserJoinPayload = wire::decode(payload)?; let _ = tx .send(NetEvent::UserJoin { + account_id: p.account_id, + avatar_url: p.avatar_url, channel_id: p.channel_id, user_id: p.user_id, nickname: p.nickname, @@ -160,3 +184,59 @@ pub async fn handle(pid: u16, payload: &[u8], tx: &mpsc::Sender) -> Re } Ok(()) } + +#[cfg(test)] +mod profile_tests { + use super::*; + use prost::Message; + + #[tokio::test] + async fn central_account_profile_reaches_client_join_event() { + let (tx, mut rx) = mpsc::channel(1); + let message = UserJoinPayload { + channel_id: "general".into(), + user_id: "device-key".into(), + nickname: "Central Name".into(), + account_id: "account-id".into(), + avatar_url: "/v1/avatars/default/account-id".into(), + }; + handle(PID_USER_JOIN, &message.encode_to_vec(), &tx) + .await + .unwrap(); + match rx.recv().await.unwrap() { + NetEvent::UserJoin { + user_id, + account_id, + avatar_url, + nickname, + .. + } => { + assert_eq!(user_id, "device-key"); + assert_eq!(account_id, "account-id"); + assert_eq!(nickname, "Central Name"); + assert_eq!(avatar_url, "/v1/avatars/default/account-id"); + } + other => panic!("unexpected {other:?}"), + } + } +} + +#[cfg(test)] +mod channel_edit_tests { + use super::*; + #[tokio::test] + async fn existing_channel_edit_packet_reaches_named_event() { + let (tx, mut rx) = mpsc::channel(1); + let bytes = wire::encode(&ChannelEditPayload { + channel_id: "global".into(), + channel_name: "Renamed".into(), + }) + .unwrap(); + super::super::incoming(PID_CHANNEL_EDIT, &bytes, &tx) + .await + .unwrap(); + assert!( + matches!(rx.recv().await.unwrap(),NetEvent::ChannelEdited{channel_id,channel_name} if channel_id=="global" && channel_name=="Renamed") + ); + } +} diff --git a/src/net/internal/dispatch/mod.rs b/src/net/internal/dispatch/mod.rs index 6e96216..3e19154 100644 --- a/src/net/internal/dispatch/mod.rs +++ b/src/net/internal/dispatch/mod.rs @@ -11,6 +11,13 @@ mod social; pub async fn incoming(pid: u16, payload: &[u8], tx: &mpsc::Sender) -> Result<()> { match pid { + PID_FORUM_RESULT => { let _ = tx.send(NetEvent::ForumResult(crate::net::wire::decode(payload)?)).await; } + PID_FORUM_CHANGED => { let _ = tx.send(NetEvent::ForumChanged(crate::net::wire::decode(payload)?)).await; } + PID_PROFILE_UPDATED => { + let _ = tx + .send(NetEvent::ProfileUpdated(crate::net::wire::decode(payload)?)) + .await; + } PID_MEDIA_EVENT => { let event = crate::net::wire::decode(payload)?; let _ = tx.send(NetEvent::MediaEvent(event)).await; @@ -36,7 +43,9 @@ pub async fn incoming(pid: u16, payload: &[u8], tx: &mpsc::Sender) -> .await; } - PID_CHANNEL_CREATE + PID_ATTACHMENT_RESULT + | PID_CHANNEL_CREATE + | PID_CHANNEL_EDIT | PID_CHANNEL_DELETE | PID_CHANNEL_LIST | PID_CHANNEL_STATE diff --git a/src/net/mod.rs b/src/net/mod.rs index 4db7a2d..11b5951 100644 --- a/src/net/mod.rs +++ b/src/net/mod.rs @@ -1,3 +1,5 @@ +pub mod account; +pub mod forum; pub mod framing; pub mod handshake; mod internal; diff --git a/src/net/payloads/channel.rs b/src/net/payloads/channel.rs index fb312fd..c040326 100644 --- a/src/net/payloads/channel.rs +++ b/src/net/payloads/channel.rs @@ -8,6 +8,7 @@ pub type JoinChannelPayload = crate::net::wire::JoinChannel; pub type LeaveChannelPayload = crate::net::wire::LeaveChannel; pub type ChannelStatePayload = crate::net::wire::ChannelState; pub type ChannelCreatePayload = crate::net::wire::ChannelCreate; +pub type ChannelEditPayload = crate::net::wire::ChannelEdit; pub type ChannelDeletePayload = crate::net::wire::ChannelDelete; pub type ChannelListPayload = crate::net::wire::ChannelList; pub type ChannelListItem = crate::net::wire::ChannelListItem; diff --git a/src/net/payloads/mod.rs b/src/net/payloads/mod.rs index 99f475e..f8c3e22 100644 --- a/src/net/payloads/mod.rs +++ b/src/net/payloads/mod.rs @@ -13,6 +13,7 @@ pub const PID_CHANNEL_STATE: u16 = 0x0032; pub const PID_CHANNEL_CREATE: u16 = 0x0033; pub const PID_CHANNEL_DELETE: u16 = 0x0034; pub const PID_CHANNEL_LIST: u16 = 0x0035; +pub const PID_CHANNEL_EDIT: u16 = 0x0036; pub const PID_USER_JOIN: u16 = 0x0040; pub const PID_USER_LEAVE: u16 = 0x0041; pub const PID_DM_START: u16 = 0x0060; @@ -67,7 +68,7 @@ pub const PID_FRIEND_EVENT: u16 = 0x0158; pub const PID_ERROR: u16 = 0x00F0; pub const PID_DISCONNECT: u16 = 0x00FF; -pub const LNEX_VERSION: &str = "v3"; +pub const LNEX_VERSION: &str = "v4"; pub const HDR_SIZE: usize = 12; pub const MAX_PAYLOAD: u32 = 4 * 1024 * 1024; @@ -93,3 +94,18 @@ pub const PID_WEBHOOK_ERROR_RESULT: u16 = 0x0206; pub const PID_VOICE_SESSION: u16 = 0x0012; pub const PID_VOICE_STATE: u16 = 0x0011; + +pub const PID_ATTACHMENT_UPLOAD: u16 = 0x0220; +pub const PID_ATTACHMENT_FETCH: u16 = 0x0221; +pub const PID_ATTACHMENT_RESULT: u16 = 0x0222; + +pub const PID_PROFILE_UPDATE: u16 = 0x0042; +pub const PID_PROFILE_UPDATED: u16 = 0x0043; + +pub const PID_FORUM_REQUEST: u16 = 0x0240; +pub const PID_FORUM_RESULT: u16 = 0x0241; +pub const PID_FORUM_CHANGED: u16 = 0x0242; + +pub const PID_NODE_SETTINGS_REQUEST: u16 = 0x0230; +pub const PID_NODE_SETTINGS_RESULT: u16 = 0x0231; +pub const PID_CLIENT_FEATURES: u16 = 0x0232; diff --git a/src/net/session/handlers/core.rs b/src/net/session/handlers/core.rs index b2ecff0..565ae9e 100644 --- a/src/net/session/handlers/core.rs +++ b/src/net/session/handlers/core.rs @@ -16,7 +16,7 @@ use crate::net::{ }; use super::super::switch::ReconnectRequested; -use super::{VoiceState, handle_cmd}; +use super::{VoiceState, handle_cmd, profile}; pub async fn session_loop( identity: &Identity, @@ -60,24 +60,62 @@ pub async fn session_loop( let session_id = outcome.session_id; let node_name = outcome.node_name; let private_mode = outcome.private_mode; + let live_profiles = outcome.live_profiles; + let forums = outcome.forums; let _ = event_tx .send(NetEvent::Connected { session_id: session_id.clone(), node_name, restored, private_mode, + node_admin: outcome.node_admin, + node_settings: outcome.node_settings, + channel_structure: outcome.channel_structure, + forums: outcome.forums, }) .await; - for channel_id in channels.clone() { - framing::write( + if outcome.node_settings || outcome.channel_structure || outcome.forums { + framing::write(&mut stream, PID_CLIENT_FEATURES, &mut seq, &wire::encode(&wire::ClientFeatures { + node_settings: outcome.node_settings, channel_structure: outcome.channel_structure, forums: outcome.forums, + })?).await?; + } + let node_settings = outcome.node_settings; + let mut profile_updates = crate::net::account::subscribe_profiles(); + let mut last_profile_proof = None; + let mut pending_profile_actions = std::collections::VecDeque::new(); + if live_profiles + && let Some(update) = crate::net::account::latest_profile() + && update.public_key == identity.pubkey_hex + && update.epoch == crate::net::account::enrollment_epoch() + && let Some(proof) = update.proof + { + profile::send( + live_profiles, &mut stream, - PID_JOIN_CHANNEL, &mut seq, - &wire::encode(&JoinChannelPayload { channel_id })?, + proof, + &mut last_profile_proof, ) .await?; } + let profile_ready = !live_profiles || last_profile_proof.is_some(); + for channel_id in channels.clone() { + if profile_ready { + framing::write( + &mut stream, + PID_JOIN_CHANNEL, + &mut seq, + &wire::encode(&JoinChannelPayload { channel_id })?, + ) + .await?; + } else { + profile::enqueue( + &mut pending_profile_actions, + NetCommand::JoinChannel { channel_id }, + ); + } + } let (reader, mut stream) = tokio::io::split(stream); let mut incoming = framing::io::Reader::new(reader); @@ -89,8 +127,48 @@ pub async fn session_loop( let mut ping_tick = interval(Duration::from_secs(2)); ping_tick.set_missed_tick_behavior(MissedTickBehavior::Delay); + let mut last_profile_refresh = profile_ready.then(std::time::Instant::now); + let mut profile_job = profile::RefreshTask::default(); + if live_profiles && !profile_ready { + profile_job.task = Some(profile::refresh(identity)); + } loop { tokio::select! { + changed = profile_updates.changed(), if live_profiles => { + if changed.is_ok() { + let update = profile_updates.borrow_and_update().clone(); + if let Some(update) = update + && update.public_key == identity.pubkey_hex && update.epoch == crate::net::account::enrollment_epoch() { + if let Some(proof) = update.proof { + profile::send(live_profiles, &mut stream,&mut seq,proof,&mut last_profile_proof).await?; + last_profile_refresh = Some(std::time::Instant::now()); + profile::actions(&mut stream,&mut seq,identity,channels,&mut pending_profile_actions).await?; + } else { + last_profile_refresh = None; + if profile_job.task.is_none() {profile_job.task=Some(profile::refresh(identity));} + } + } + } + } + result = async { profile_job.task.as_mut().expect("guarded profile job").await }, if live_profiles && profile_job.task.is_some() => { + profile_job.task = None; + let latest = crate::net::account::latest_profile().filter(|update|update.public_key == identity.pubkey_hex && update.epoch == crate::net::account::enrollment_epoch()); + match result { + Ok(Ok(proof)) => { + if latest.as_ref().is_some_and(|update|update.proof.is_none()) { + // A mutation committed after this HTTP refresh: obtain its newer proof. + last_profile_refresh=None;profile_job.task=Some(profile::refresh(identity));continue; + } + let proof = latest.and_then(|update|update.proof).unwrap_or(proof); + profile::send(live_profiles, &mut stream,&mut seq,proof,&mut last_profile_proof).await?; + } + _ => { + let _=event_tx.send(NetEvent::ProfileWarning {message:"Central profile refresh failed; using last verified profile".into(),rejected_join:None}).await; + } + } + last_profile_refresh=Some(std::time::Instant::now()); + profile::actions(&mut stream,&mut seq,identity,channels,&mut pending_profile_actions).await?; + } _ = voice_tick.tick() => { if let Some(voice)=voice_state.as_mut() {voice.keep_alive().await?;} } _ = ping_tick.tick() => { let ts = now_ms(); @@ -117,6 +195,11 @@ pub async fn session_loop( } continue; } + if pkt.packet_id == PID_NODE_SETTINGS_RESULT && node_settings { + let result = wire::decode(&pkt.payload)?; + let _ = event_tx.send(NetEvent::NodeSettingsResult { session_id: session_id.clone(), result }).await; + continue; + } if pkt.packet_id == PID_CHANNEL_STATE && let Ok(p) = wire::decode::(&pkt.payload) && p.kind == "voice" && !p.voice_endpoint.is_empty() @@ -129,13 +212,26 @@ pub async fn session_loop( internal::dispatch::incoming(pkt.packet_id, &pkt.payload, event_tx).await?; } cmd = cmd_rx.recv() => { + let cmd = match cmd { + Some(command) => match command_for_session(command, &session_id) { + Some(command) => Some(command), + None => continue, + }, + None => None, + }; match cmd { + Some(NetCommand::AttachmentFetch { request_id, channel_id, attachment_id }) => { + framing::write(&mut stream, PID_ATTACHMENT_FETCH, &mut seq, + &wire::encode(&wire::AttachmentFetch { request_id, channel_id, attachment_id })?).await?; + } None | Some(NetCommand::Disconnect) => { + profile::cancel(&mut profile_job, &mut pending_profile_actions); let _ = framing::write(&mut stream, PID_DISCONNECT, &mut seq, &wire::encode(&Disconnect {reason: "bye".into()})?).await; return Ok(()); } Some(NetCommand::Connect { address, auto_reconnect }) => { + profile::cancel(&mut profile_job, &mut pending_profile_actions); warn!("connect while connected to {address}, reconnecting"); if channels.is_empty() { *channels = vec!["general".into()]; @@ -145,43 +241,62 @@ pub async fn session_loop( auto_reconnect, })); } - Some(NetCommand::JoinChannel { channel_id }) => { - track_channel(channels, &channel_id); - framing::write(&mut stream, PID_JOIN_CHANNEL, &mut seq, - &wire::encode(&JoinChannelPayload { channel_id })?).await?; + Some(command @ (NetCommand::JoinChannel { .. } | NetCommand::SendChat { .. } | NetCommand::AttachmentUpload { .. } | NetCommand::ForumRequest(_))) => { + if let NetCommand::ForumRequest(request) = &command { + if !forums { crate::net::forum::unsupported(request, event_tx).await; continue; } + if !crate::net::forum::is_mutation(request) { crate::net::forum::write(&mut stream, &mut seq, request).await?; continue; } + } + let rejected_join = if let NetCommand::JoinChannel {channel_id}=&command {Some(channel_id.clone())} else {None}; + let upload = if let NetCommand::AttachmentUpload {request_id,channel_id,data}=&command { + if data.is_empty() || data.len()>3*1024*1024 || request_id.len()>128 || channel_id.len()>128 { + let _=event_tx.send(NetEvent::AttachmentResult(wire::AttachmentResult {request_id:request_id.clone(),channel_id:channel_id.clone(),error:"invalid image upload (maximum 3 MiB)".into(),..Default::default()})).await;continue; + } + Some((request_id.clone(),channel_id.clone())) + } else {None}; + let forum_request = if let NetCommand::ForumRequest(request) = &command { Some(wire::ForumRequest { request_id:request.request_id.clone(),operation:request.operation,channel_id:request.channel_id.clone(),topic_id:request.topic_id.clone(),..Default::default() }) } else { None }; + if !profile::enqueue(&mut pending_profile_actions, command) { + if let Some(request) = forum_request { crate::net::forum::error(&request, "Too many pending profile actions; retry shortly", event_tx).await; continue; } + if let Some((request_id,channel_id))=upload { + let _=event_tx.send(NetEvent::AttachmentResult(wire::AttachmentResult {request_id,channel_id,error:"Too many pending profile actions; retry shortly".into(),..Default::default()})).await; + } else {let _=event_tx.send(NetEvent::ProfileWarning {message:"Too many pending profile actions; retry shortly".into(),rejected_join}).await;} + continue; + } + if profile::due(live_profiles, last_profile_refresh) { + if profile_job.task.is_none() {profile_job.task=Some(profile::refresh(identity));} + } else { + profile::actions(&mut stream,&mut seq,identity,channels,&mut pending_profile_actions).await?; + } } Some(NetCommand::LeaveChannel { channel_id }) => { + profile::cancel_channel(&mut pending_profile_actions, &channel_id); channels.retain(|c| c != &channel_id); if voice_state.as_ref().and_then(|value|value.channel_id())==Some(channel_id.as_str()) {voice_state=None;voice_endpoint=None;} framing::write(&mut stream, PID_LEAVE_CHANNEL, &mut seq, &wire::encode(&LeaveChannelPayload { channel_id })?).await?; } - Some(NetCommand::ChannelCreate { channel_id, channel_name, kind, guild_id }) => { + Some(NetCommand::ChannelCreate { channel_id, channel_name, kind, guild_id, parent_id, position }) => { let payload = wire::encode(&ChannelCreatePayload { channel_id, channel_name, kind, - guild_id, + guild_id, parent_id, position, })?; framing::write(&mut stream, PID_CHANNEL_CREATE, &mut seq, &payload).await?; } + Some(NetCommand::ChannelEdit { channel_id, channel_name, parent_id, position }) => { + let payload = wire::encode(&ChannelEditPayload { channel_id, channel_name, parent_id, position })?; + framing::write(&mut stream, PID_CHANNEL_EDIT, &mut seq, &payload).await?; + } Some(NetCommand::ChannelDelete { channel_id }) => { let payload = wire::encode(&ChannelDeletePayload { channel_id })?; framing::write(&mut stream, PID_CHANNEL_DELETE, &mut seq, &payload).await?; } + Some(NetCommand::NodeSettingsRequest(request)) => { + if node_settings { framing::write(&mut stream, PID_NODE_SETTINGS_REQUEST, &mut seq, &wire::encode(&request)?).await?; } + } Some(NetCommand::ChannelList) => { framing::write(&mut stream, PID_CHANNEL_LIST, &mut seq, b"").await?; } - Some(NetCommand::SendChat { channel_id, content, reply_to }) => { - let msg = ChatMessagePayload { - message_id: uuid_v4(), channel_id, - sender_id: identity.pubkey_hex.clone(), - content, timestamp: now_ms(), - edited: false, - reply_to, - }; - framing::write(&mut stream, PID_CHAT_MESSAGE, &mut seq, &wire::encode(&msg)?).await?; - } Some(NetCommand::SendVoice { channel_id, voice_seq: voice_pkt_seq, timestamp, opus_data }) => { if let Some(voice)=voice_state.as_mut(){voice.send(Some(channel_id), voice_pkt_seq, timestamp, &opus_data).await?;} } @@ -207,8 +322,73 @@ pub(super) fn uuid_v4() -> String { uuid::Uuid::new_v4().to_string() } -fn track_channel(channels: &mut Vec, channel_id: &str) { +pub(super) fn track_channel(channels: &mut Vec, channel_id: &str) { if !channels.iter().any(|c| c == channel_id) { channels.push(channel_id.to_string()); } } + +/// UI tasks can outlive a node switch. Only the original authenticated session may +/// consume their channel mutation; wrappers cannot smuggle a connect or arbitrary command. +fn command_for_session(command: NetCommand, current: &str) -> Option { + match command { + NetCommand::ForSession { + session_id, + command, + } => (session_id == current + && matches!( + &*command, + NetCommand::ForumRequest(_) + | NetCommand::JoinChannel { .. } + | NetCommand::ChannelCreate { .. } + | NetCommand::ChannelEdit { .. } + | NetCommand::ChannelDelete { .. } + | NetCommand::NodeSettingsRequest(_) + )) + .then_some(*command), + command => Some(command), + } +} + +#[cfg(test)] +mod session_fence_tests { + use super::*; + #[test] + fn admin_mutations_survive_only_the_session_that_prepared_them() { + for current in ["original-session", "new-session-after-switch"] { + let commands = [ + NetCommand::ChannelCreate { + channel_id: "global".into(), + channel_name: "Global".into(), + kind: "text".into(), + guild_id: None, + }, + NetCommand::ChannelEdit { + channel_id: "global".into(), + channel_name: "Renamed".into(), + }, + NetCommand::ChannelDelete { + channel_id: "global".into(), + }, + ]; + for command in commands { + let command = NetCommand::ForSession { + session_id: "original-session".into(), + command: Box::new(command), + }; + assert_eq!( + command_for_session(command, current).is_some(), + current == "original-session" + ); + } + } + let command = NetCommand::ForSession { + session_id: "original-session".into(), + command: Box::new(NetCommand::Connect { + address: "another-node".into(), + auto_reconnect: true, + }), + }; + assert!(command_for_session(command, "original-session").is_none()); + } +} diff --git a/src/net/session/handlers/mod.rs b/src/net/session/handlers/mod.rs index ee32ce3..f8bd52b 100644 --- a/src/net/session/handlers/mod.rs +++ b/src/net/session/handlers/mod.rs @@ -1,4 +1,5 @@ mod core; +mod profile; mod social; mod voice; diff --git a/src/net/session/handlers/profile.rs b/src/net/session/handlers/profile.rs new file mode 100644 index 0000000..3723290 --- /dev/null +++ b/src/net/session/handlers/profile.rs @@ -0,0 +1,373 @@ +//! Coalesced profile refresh helpers. HTTP runs in a separate task, never in the UDP loop. +use crate::{ + identity::Identity, + net::{framing, payloads::*, types::NetCommand, wire}, +}; +use anyhow::{Context, Result}; +use std::collections::VecDeque; +use std::time::{Duration, Instant}; +use tokio::io::{AsyncWrite, AsyncWriteExt}; + +#[derive(Default)] +pub(super) struct RefreshTask { + pub task: Option>>>, +} +impl Drop for RefreshTask { + fn drop(&mut self) { + if let Some(task) = self.task.take() { + task.abort(); + } + } +} +pub(super) fn cancel(task: &mut RefreshTask, pending: &mut VecDeque) { + if let Some(task) = task.task.take() { + task.abort(); + } + pending.clear(); +} +pub(super) fn cancel_channel(pending: &mut VecDeque, channel: &str) { + pending.retain(|action| !matches!(action, NetCommand::JoinChannel {channel_id} | NetCommand::SendChat {channel_id,..} | NetCommand::AttachmentUpload {channel_id,..} if channel_id == channel)); +} +fn bytes(command: &NetCommand) -> usize { + match command { + NetCommand::AttachmentUpload { + data, + request_id, + channel_id, + } => data.len() + request_id.len() + channel_id.len(), + NetCommand::SendChat { + content, + channel_id, + reply_to, + } => content.len() + channel_id.len() + reply_to.as_ref().map_or(0, String::len), + NetCommand::JoinChannel { channel_id } => channel_id.len(), + NetCommand::ForumRequest(request) => request.request_id.len() + request.channel_id.len() + request.topic_id.len() + request.message_id.len() + request.title.len() + request.content.len(), + _ => 0, + } +} +pub(super) fn enqueue(pending: &mut VecDeque, command: NetCommand) -> bool { + if let NetCommand::JoinChannel {channel_id}=&command + && pending.iter().any(|action|matches!(action, NetCommand::JoinChannel {channel_id:queued} if queued==channel_id)) {return true;} + if pending.len() >= 32 + || pending + .iter() + .map(bytes) + .sum::() + .saturating_add(bytes(&command)) + > 4 * 1024 * 1024 + { + return false; + } + pending.push_back(command); + true +} +pub(super) const PROFILE_TTL: Duration = Duration::from_secs(5); +pub(super) fn due(enabled: bool, last: Option) -> bool { + enabled && last.is_none_or(|at| at.elapsed() >= PROFILE_TTL) +} +pub(super) fn refresh(identity: &Identity) -> tokio::task::JoinHandle>> { + let identity = identity.clone(); + tokio::spawn(async move { + tokio::time::timeout( + Duration::from_secs(12), + crate::net::account::admission_proof(&identity), + ) + .await + .context("Central profile refresh timed out")? + }) +} +pub(super) async fn send( + enabled: bool, + stream: &mut (impl AsyncWrite + Unpin), + seq: &mut u32, + proof: Vec, + last_sent: &mut Option>, +) -> Result<()> { + if enabled && last_sent.as_ref() != Some(&proof) { + framing::write( + stream, + PID_PROFILE_UPDATE, + seq, + &wire::encode(&wire::ProfileUpdate { + account_proof: proof.clone(), + })?, + ) + .await?; + *last_sent = Some(proof); + } + Ok(()) +} +pub(super) async fn actions( + stream: &mut (impl AsyncWrite + Unpin), + seq: &mut u32, + identity: &Identity, + channels: &mut Vec, + pending: &mut VecDeque, +) -> Result<()> { + while let Some(action) = pending.pop_front() { + match action { + NetCommand::ForumRequest(request) => { crate::net::forum::write(stream, seq, &request).await?; } + NetCommand::JoinChannel { channel_id } => { + super::core::track_channel(channels, &channel_id); + framing::write( + stream, + PID_JOIN_CHANNEL, + seq, + &wire::encode(&JoinChannelPayload { channel_id })?, + ) + .await?; + } + NetCommand::SendChat { + channel_id, + content, + reply_to, + } => { + let message = ChatMessagePayload { + message_id: super::core::uuid_v4(), + channel_id, + sender_id: identity.pubkey_hex.clone(), + content, + timestamp: super::core::now_ms(), + edited: false, + reply_to, + }; + framing::write(stream, PID_CHAT_MESSAGE, seq, &wire::encode(&message)?).await?; + } + NetCommand::AttachmentUpload { + request_id, + channel_id, + data, + } => { + framing::write( + stream, + PID_ATTACHMENT_UPLOAD, + seq, + &wire::encode(&wire::AttachmentUpload { + request_id, + channel_id, + data, + })?, + ) + .await?; + } + _ => unreachable!("only chat, image, forum mutation and join commands can wait for profile refresh"), + } + } + stream.flush().await?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + #[tokio::test] + async fn legacy_session_without_live_profiles_sends_chat_voice_and_image_without_profile_packet() + { + let legacy: wire::Session = wire::decode(&[10, 1, b's', 18, 1, b't']).unwrap(); + assert!(!legacy.live_profiles); + assert!( + !due(legacy.live_profiles, None), + "legacy actions never wait for profile HTTP" + ); + let identity = crate::identity::generate("legacy"); + let (mut stream, mut peer) = tokio::io::duplex(65536); + let mut seq = 2; + let mut sent = None; + send( + legacy.live_profiles, + &mut stream, + &mut seq, + b"not supported".to_vec(), + &mut sent, + ) + .await + .unwrap(); + assert!(sent.is_none()); + let mut pending = VecDeque::from([ + NetCommand::SendChat { + channel_id: "general".into(), + content: "legacy message".into(), + reply_to: None, + }, + NetCommand::JoinChannel { + channel_id: "voice".into(), + }, + NetCommand::AttachmentUpload { + request_id: "image".into(), + channel_id: "general".into(), + data: vec![1, 2, 3], + }, + ]); + actions( + &mut stream, + &mut seq, + &identity, + &mut vec!["general".into()], + &mut pending, + ) + .await + .unwrap(); + for expected in [PID_CHAT_MESSAGE, PID_JOIN_CHANNEL, PID_ATTACHMENT_UPLOAD] { + assert_eq!(framing::read(&mut peer).await.unwrap().packet_id, expected); + } + } + #[test] + fn image_actions_share_bounded_byte_budget_and_leave_cancels_upload() { + let mut pending = VecDeque::new(); + assert!(enqueue( + &mut pending, + NetCommand::AttachmentUpload { + request_id: "one".into(), + channel_id: "general".into(), + data: vec![0; 3 * 1024 * 1024] + } + )); + assert!(!enqueue( + &mut pending, + NetCommand::AttachmentUpload { + request_id: "two".into(), + channel_id: "general".into(), + data: vec![0; 3 * 1024 * 1024] + } + )); + assert_eq!(pending.len(), 1); + cancel_channel(&mut pending, "general"); + assert!(pending.is_empty()); + } + #[tokio::test] + async fn disconnect_switch_and_session_drop_cancel_refresh_and_never_replay_pending_actions() { + for session_end in [false, true] { + let identity = crate::identity::generate("test"); + let (mut stream, mut peer) = tokio::io::duplex(65536); + let mut pending = VecDeque::from([ + NetCommand::SendChat { + channel_id: "old-node-channel".into(), + content: "old message".into(), + reply_to: None, + }, + NetCommand::JoinChannel { + channel_id: "old-voice".into(), + }, + ]); + let mut job = RefreshTask { + task: Some(tokio::spawn(async { + std::future::pending::>>().await + })), + }; + let aborted = job.task.as_ref().unwrap().abort_handle(); + if session_end { + drop(job); + pending.clear(); + } else { + cancel(&mut job, &mut pending); + drop(job); + } + tokio::task::yield_now().await; + assert!(aborted.is_finished()); + let mut channels = vec!["new-node-channel".to_owned()]; + actions(&mut stream, &mut 2, &identity, &mut channels, &mut pending) + .await + .unwrap(); + assert_eq!(channels, vec!["new-node-channel"]); + assert!( + tokio::time::timeout(Duration::from_millis(5), framing::read(&mut peer)) + .await + .is_err() + ); + } + } + #[test] + fn pending_actions_are_bounded_coalesce_duplicate_joins_and_leave_cancels_channel() { + let mut pending = VecDeque::new(); + for _ in 0..100 { + assert!(enqueue( + &mut pending, + NetCommand::JoinChannel { + channel_id: "voice".into() + } + )); + } + assert_eq!(pending.len(), 1); + for _ in 0..31 { + assert!(enqueue( + &mut pending, + NetCommand::SendChat { + channel_id: "general".into(), + content: "message".into(), + reply_to: None + } + )); + } + assert!(!enqueue( + &mut pending, + NetCommand::JoinChannel { + channel_id: "overflow".into() + } + )); + cancel_channel(&mut pending, "voice"); + assert_eq!(pending.len(), 31); + cancel_channel(&mut pending, "general"); + assert!(pending.is_empty()); + } + #[tokio::test] + async fn fresh_proof_precedes_chat_and_voice_join_without_disconnect_or_duplicate_join() { + let identity = crate::identity::generate("old"); + let (mut stream, mut peer) = tokio::io::duplex(65536); + let mut pending = VecDeque::from([ + NetCommand::SendChat { + channel_id: "general".into(), + content: "new message".into(), + reply_to: None, + }, + NetCommand::JoinChannel { + channel_id: "voice-room".into(), + }, + NetCommand::AttachmentUpload { + request_id: "image".into(), + channel_id: "general".into(), + data: vec![1, 2, 3], + }, + ]); + let mut channels = vec!["general".to_owned()]; + let mut seq = 0; + let mut last = None; + send( + true, + &mut stream, + &mut seq, + b"signed fresh proof".to_vec(), + &mut last, + ) + .await + .unwrap(); + actions( + &mut stream, + &mut seq, + &identity, + &mut channels, + &mut pending, + ) + .await + .unwrap(); + assert_eq!( + framing::read(&mut peer).await.unwrap().packet_id, + PID_PROFILE_UPDATE + ); + assert_eq!( + framing::read(&mut peer).await.unwrap().packet_id, + PID_CHAT_MESSAGE + ); + assert_eq!( + framing::read(&mut peer).await.unwrap().packet_id, + PID_JOIN_CHANNEL + ); + assert_eq!( + framing::read(&mut peer).await.unwrap().packet_id, + PID_ATTACHMENT_UPLOAD + ); + assert!(pending.is_empty()); + assert_eq!(channels, vec!["general", "voice-room"]); + assert!(!due(true, Some(Instant::now()))); + assert!(due(true, None)); + } +} diff --git a/src/net/session/task.rs b/src/net/session/task.rs index bd65546..4212f0c 100644 --- a/src/net/session/task.rs +++ b/src/net/session/task.rs @@ -51,6 +51,9 @@ pub async fn net_task( session.address=address;session.auto_reconnect=auto_reconnect; failures=0;target=Some(session);continue 'session; } + Some(NetCommand::LeaveChannel {channel_id}) => { + forget_rejoin_channel(&mut session, &channel_id); + } Some(NetCommand::Disconnect) => { failures=0; let _=event_tx.send(NetEvent::Disconnected {reason:"disconnected".into(),will_retry:false}).await; @@ -105,7 +108,13 @@ pub async fn net_task( if let Some(problem) = transport.and_then(TransportError::trust_problem) { let _ = event_tx.send(NetEvent::TrustProblem(problem)).await; } - let retry = session.auto_reconnect && transport.is_none(); + let account_required = e + .downcast_ref::() + .is_some(); + if account_required { + let _ = event_tx.send(NetEvent::AccountRequired).await; + } + let retry = should_retry(&e, session.auto_reconnect); let _ = event_tx .send(NetEvent::Disconnected { reason: e.to_string(), @@ -123,6 +132,19 @@ pub async fn net_task( } } +/// An explicit leave during backoff must survive the next successful connection. +fn forget_rejoin_channel(target: &mut SessionTarget, channel_id: &str) { + target.channels.retain(|channel| channel != channel_id); +} + +fn should_retry(error: &anyhow::Error, enabled: bool) -> bool { + enabled + && error.downcast_ref::().is_none() + && error + .downcast_ref::() + .is_none() +} + async fn wait_for_connect(cmd_rx: &mut mpsc::Receiver) -> Option { loop { match cmd_rx.recv().await { @@ -146,6 +168,31 @@ async fn wait_for_connect(cmd_rx: &mut mpsc::Receiver) -> Option AsyncStream for T {} pub type Stream = Box; /// ALPN protocol id required from the gateway. -pub const ALPN: &[u8] = b"vnox-lnex/3"; +pub const ALPN: &[u8] = b"vnox-lnex/4"; /// TLS exporter label of the channel binding (must match the gateway). -pub const EXPORTER_LABEL: &[u8] = b"EXPORTER-VNOX-LNEx-v3-channel-binding"; +pub const EXPORTER_LABEL: &[u8] = b"EXPORTER-VNOX-LNEx-v4-channel-binding"; /// Length of the exported channel binding. pub const BINDING_LEN: usize = 32; @@ -220,7 +220,7 @@ pub async fn connect_with_peer(address: &str, trust: &TrustStore) -> Result Result, + }, + AttachmentUpload { + request_id: String, + channel_id: String, + data: Vec, + }, + AttachmentFetch { + request_id: String, + channel_id: String, + attachment_id: String, + }, MediaControl(crate::net::wire::MediaControl), Webhook { operation: WebhookOperation, @@ -15,11 +31,20 @@ pub enum NetCommand { LeaveChannel { channel_id: String, }, + NodeSettingsRequest(crate::net::wire::NodeSettingsRequest), ChannelCreate { channel_id: String, channel_name: String, kind: String, guild_id: Option, + parent_id: Option, + position: i32, + }, + ChannelEdit { + channel_id: String, + channel_name: String, + parent_id: Option, + position: Option, }, ChannelDelete { channel_id: String, diff --git a/src/net/types/event.rs b/src/net/types/event.rs index 17851b5..75b4f55 100644 --- a/src/net/types/event.rs +++ b/src/net/types/event.rs @@ -3,6 +3,17 @@ use std::net::SocketAddr; #[derive(Debug, Clone)] pub enum NetEvent { + ForumResult(crate::net::wire::ForumResult), + ForumChanged(crate::net::wire::ForumChanged), + /// A local profile refresh/activity warning; it is not a gateway join refusal. + ProfileWarning { + message: String, + rejected_join: Option, + }, + ProfileUpdated(crate::net::wire::ProfileUpdated), + /// Central enrollment must be approved again; retries cannot repair it. + AccountRequired, + AttachmentResult(crate::net::wire::AttachmentResult), VoiceRevoked { channel_id: String, }, @@ -10,11 +21,16 @@ pub enum NetEvent { WebhookResult(WebhookManagementResult), WebhookList(crate::net::wire::WebhookListResult), WebhookError(crate::net::wire::WebhookErrorResult), + NodeSettingsResult { session_id: String, result: crate::net::wire::NodeSettingsResult }, Connected { session_id: String, node_name: String, restored: bool, private_mode: bool, + node_admin: bool, + node_settings: bool, + channel_structure: bool, + forums: bool, }, Disconnected { reason: String, @@ -33,12 +49,22 @@ pub enum NetEvent { members: Vec, voice_endpoint: String, guild_id: Option, + parent_id: Option, + position: i32, }, ChannelCreated { channel_id: String, channel_name: String, kind: String, guild_id: Option, + parent_id: Option, + position: i32, + }, + ChannelEdited { + channel_id: String, + channel_name: String, + parent_id: Option, + position: Option, }, ChannelDeleted { channel_id: String, @@ -61,6 +87,8 @@ pub enum NetEvent { messages: Vec, }, UserJoin { + account_id: String, + avatar_url: String, channel_id: String, user_id: String, nickname: String, diff --git a/src/net/types/info.rs b/src/net/types/info.rs index 10c38ca..b7aad3b 100644 --- a/src/net/types/info.rs +++ b/src/net/types/info.rs @@ -3,6 +3,8 @@ pub struct MemberInfo { pub user_id: String, pub nickname: String, pub in_voice: bool, + pub account_id: String, + pub avatar_url: String, } #[derive(Debug, Clone)] @@ -11,6 +13,8 @@ pub struct ChannelListItem { pub channel_name: String, pub kind: String, pub guild_id: Option, + pub parent_id: Option, + pub position: i32, } #[derive(Debug, Clone)] diff --git a/src/ui/account.rs b/src/ui/account.rs new file mode 100644 index 0000000..669c6a3 --- /dev/null +++ b/src/ui/account.rs @@ -0,0 +1,359 @@ +//! Browser approval UI. Login secrets stay inside the network/account module. +use super::slint::MainWindow; +use crate::{ + AppState, + net::{ + self, + account::{self, LoginEvent}, + }, +}; +use slint::ComponentHandle; +use std::{cell::RefCell, rc::Rc, sync::mpsc, time::Duration}; + +#[derive(Default)] +struct Controls { + generation: u64, + busy: bool, + cancelled: bool, + flow_identity: Option, + cancel: Option>, + approval_uri: Option, +} +enum Update { + Approval { uri: String, key: String }, + SignedIn(Result), + SignedOut(Result<(), String>), +} +fn browser(uri: &str) { + // No shell and no device/refresh token in this public approval URL. + if let Err(error) = std::process::Command::new("xdg-open").arg(uri).spawn() { + tracing::warn!(%error, "could not open Central approval page"); + } +} + +/// Apply a fresh public profile without overwriting an unsaved name draft. +pub(super) fn apply_profile( + window: &MainWindow, + state: &mut AppState, + user: account::AccountSummary, +) { + let previous = state.ui.central_account.as_ref(); + if previous.is_none_or(|old| { + old.user_id != user.user_id + || window.get_profile_display_name().as_str() == old.display_name + }) || window.get_profile_display_name().is_empty() + { + window.set_profile_display_name(user.display_name.clone().into()); + } + window.set_profile_initials(user.display_name.chars().take(2).collect::().into()); + window.set_account_name(user.display_name.clone().into()); + state + .ui + .apply_central_profile(&state.identity.pubkey_hex, user); +} + +/// Returned timer must stay alive for the window lifetime. +pub fn wire(window: &MainWindow, state: &Rc>) -> slint::Timer { + let controls = Rc::new(RefCell::new(Controls::default())); + // Drop the Ref before any successful branch mutates UI profile state. + let current = { + let state = state.borrow(); + account::current(&state.identity) + }; + match current { + Ok(Some(user)) => { + window.set_account_authenticated(true); + apply_profile(window, &mut state.borrow_mut(), user); + } + Ok(None) => (), + Err(error) => window.set_account_status(error.to_string().into()), + } + super::connection::restore(&mut state.borrow_mut(), window.get_account_authenticated()); + let (sender, receiver) = mpsc::channel(); + { + let controls = controls.clone(); + let state = state.clone(); + let weak = window.as_weak(); + let sender = sender.clone(); + window.on_account_sign_in(move || { + let Some(window) = weak.upgrade() else { return }; + let mut control = controls.borrow_mut(); + if control.busy { + return; + } + control.busy = true; + control.cancelled = false; + control.generation += 1; + let generation = control.generation; + let (cancel, cancellation) = tokio::sync::watch::channel(false); + control.cancel = Some(cancel); + control.approval_uri = None; + window.set_account_signing_in(true); + window.set_account_status(super::i18n::text("Preparing browser sign-in...").into()); + window.set_account_public_key("".into()); + let identity = state.borrow().identity.clone(); + control.flow_identity = Some(identity.clone()); + let sender = sender.clone(); + tokio::spawn(async move { + let (updates, mut progress) = tokio::sync::mpsc::unbounded_channel(); + let forward = sender.clone(); + let forwarding = tokio::spawn(async move { + while let Some(LoginEvent::ApprovalRequired { + verification_uri, + public_key, + .. + }) = progress.recv().await + { + if forward + .send(( + generation, + Update::Approval { + uri: verification_uri, + key: public_key, + }, + )) + .is_err() + { + break; + } + } + }); + let result = account::sign_in(&identity, updates, cancellation) + .await + .map_err(|e| e.to_string()); + forwarding.abort(); + let _ = sender.send((generation, Update::SignedIn(result))); + }); + }); + } + { + let controls = controls.clone(); + let weak = window.as_weak(); + window.on_account_cancel(move || { + let mut control = controls.borrow_mut(); + let Some(cancel) = control.cancel.as_ref() else { + return; + }; + let _ = cancel.send(true); + control.cancelled = true; + control.approval_uri = None; + if let Some(window) = weak.upgrade() { + window.set_account_public_key("".into()); + window.set_account_status(super::i18n::text("Cancelling sign-in...").into()); + } + }); + } + { + let controls = controls.clone(); + window.on_account_open_browser(move || { + if let Some(uri) = controls.borrow().approval_uri.as_ref() { + browser(uri); + } + }); + } + { + let controls = controls.clone(); + let state = state.clone(); + let weak = window.as_weak(); + let sender = sender.clone(); + window.on_account_sign_out(move || { + let Some(window) = weak.upgrade() else { return }; + let mut control = controls.borrow_mut(); + if control.busy { + return; + } + control.busy = true; + control.generation += 1; + if let Some(cancel) = control.cancel.take() { + let _ = cancel.send(true); + } + let generation = control.generation; + state.borrow_mut().ui.central_account = None; + window.set_profile_display_name("".into()); + window.set_profile_error("".into()); + window.set_profile_saving(false); + window.set_avatar_saving(false); + window.set_profile_initials("".into()); + window.set_own_avatar(slint::Image::default()); + window.set_has_avatar(false); + let s = state.borrow(); + let identity = s.identity.clone(); + let net = s.net.clone(); + let sender = sender.clone(); + window.set_account_authenticated(false); + window.set_account_signing_in(true); + window.set_account_name("".into()); + window.set_account_status(super::i18n::text("Signing out...").into()); + tokio::spawn(async move { + net.send(net::NetCommand::Disconnect).await; + let result = account::sign_out(&identity) + .await + .map_err(|e| e.to_string()); + let _ = sender.send((generation, Update::SignedOut(result))); + }); + }); + } + { + let weak = window.as_weak(); + let state = state.clone(); + let controls = controls.clone(); + window.on_save_profile_name(move |name| { + let Some(window) = weak.upgrade() else { return }; + if window.get_profile_saving() + || controls.borrow().busy + || !window.get_account_authenticated() + { + return; + } + let identity = state.borrow().identity.clone(); + let user_id = state + .borrow() + .ui + .central_account + .as_ref() + .map(|user| user.user_id.clone()); + let generation = controls.borrow().generation; + let epoch = account::enrollment_epoch(); + window.set_profile_saving(true); + window.set_profile_error("".into()); + let state = state.clone(); + let controls = controls.clone(); + let weak = weak.clone(); + let result = slint::spawn_local(async move { + let request_identity = identity.clone(); + let submitted_name = name.to_string(); + let requested_name = submitted_name.clone(); + let result = tokio::spawn(async move { + account::set_display_name(&request_identity, &requested_name, epoch).await + }) + .await; + let Some(window) = weak.upgrade() else { return }; + if generation != controls.borrow().generation + || epoch != account::enrollment_epoch() + || !window.get_account_authenticated() + || state.borrow().identity.pubkey_hex != identity.pubkey_hex + || state + .borrow() + .ui + .central_account + .as_ref() + .map(|user| &user.user_id) + != user_id.as_ref() + { + return; + } + window.set_profile_saving(false); + match result { + Ok(Ok(user)) => { + if window.get_profile_display_name().as_str() == submitted_name { + window.set_profile_display_name(user.display_name.clone().into()); + } + apply_profile(&window, &mut state.borrow_mut(), user); + } + Ok(Err(error)) => { + window.set_profile_error(super::i18n::text(&error.to_string()).into()) + } + Err(_) => window.set_profile_error( + super::i18n::text("Could not save profile. Try again.").into(), + ), + } + }); + if result.is_err() { + window.set_profile_saving(false); + window.set_profile_error( + super::i18n::text("Could not save profile. Try again.").into(), + ); + } + }); + } + let mut profiles = account::subscribe_profiles(); + let mut last_profile_refresh: Option = None; + let mut refreshing: Option> = None; + let mut was_settings_open = false; + let timer = slint::Timer::default(); + let state = state.clone(); + let weak = window.as_weak(); + timer.start(slint::TimerMode::Repeated, Duration::from_millis(100), move || { + let Some(window) = weak.upgrade() else { return }; + if profiles.has_changed().unwrap_or(false) { + let update = profiles.borrow_and_update().clone(); + if let Some(update) = update { + let mut state = state.borrow_mut(); + if window.get_account_authenticated() && update.epoch == account::enrollment_epoch() && update.public_key == state.identity.pubkey_hex + && state.ui.central_account.as_ref().is_some_and(|current|current.user_id == update.user.user_id) { + apply_profile(&window, &mut state, update.user); + } + } + } + let settings_open = state.borrow().ui.settings_open; + let settings_just_opened = settings_open && !was_settings_open; + was_settings_open = settings_open; + if refreshing.as_ref().is_some_and(|task|task.is_finished()) {refreshing=None;} + let due = last_profile_refresh.is_none_or(|at|at.elapsed() >= Duration::from_secs(60)) + || (settings_just_opened && last_profile_refresh.is_none_or(|at|at.elapsed() >= Duration::from_secs(5))); + if due && refreshing.is_none() && !controls.borrow().busy && window.get_account_authenticated() + && state.borrow().ui.central_account.is_some() { + let identity = state.borrow().identity.clone(); + last_profile_refresh = Some(std::time::Instant::now()); + refreshing = Some(tokio::spawn(async move { let _ = account::refresh_profile(&identity).await; })); + } + while let Ok((generation, update)) = receiver.try_recv() { + let mut control = controls.borrow_mut(); + if generation != control.generation { continue; } + match update { + Update::Approval { uri, key } => { + if control.cancelled { continue; } + window.set_account_public_key(key.into()); + window.set_account_status(super::i18n::text("Confirm this device in your browser. Compare the public key before approving.").into()); + browser(&uri); + control.approval_uri = Some(uri); + } + Update::SignedIn(result) => { + control.cancel = None; + control.approval_uri = None; + if control.cancelled && result.is_ok() { + // Cancel can race an already queued successful result. Revoke what + // was saved before permitting any replacement login. + if let Some(identity) = control.flow_identity.take() { + let sender = sender.clone(); + tokio::spawn(async move { + let result = account::sign_out(&identity).await.map_err(|e| e.to_string()); + let _ = sender.send((generation, Update::SignedOut(result))); + }); + continue; + } + } + control.flow_identity = None; + control.busy = false; + window.set_account_signing_in(false); + if control.cancelled { + window.set_account_status(super::i18n::text("Sign-in cancelled.").into()); + continue; + } + match result { + Ok(user) => { + window.set_account_authenticated(true); + window.set_profile_display_name(user.display_name.clone().into()); + window.set_profile_saving(false); + window.set_avatar_saving(false); + window.set_avatar_error("".into()); + window.set_avatar_crop_open(false); + window.set_avatar_source(slint::Image::default()); + apply_profile(&window, &mut state.borrow_mut(), user); + window.set_account_status("".into()); + state.borrow_mut().ui.connection.authentication_required = false; + super::connection::restore(&mut state.borrow_mut(), true); + } + Err(error) => window.set_account_status(error.into()), + } + } + Update::SignedOut(result) => { + control.busy = false; + window.set_account_signing_in(false); + window.set_account_status(result.err().unwrap_or_default().into()); + } + } + } + }); + timer +} diff --git a/src/ui/appearance/css.rs b/src/ui/appearance/css.rs index be4eb73..a2c8e38 100644 --- a/src/ui/appearance/css.rs +++ b/src/ui/appearance/css.rs @@ -173,7 +173,7 @@ mod tests { #[test] fn built_in_themes_roundtrip_without_color_or_alpha_loss() { - for mode in ["light", "dark", "black"] { + for mode in super::super::BUILTIN_THEME_IDS { let theme = ThemeSpec::builtin(mode); assert_eq!(parse_css(&theme.to_css()).unwrap(), theme); } diff --git a/src/ui/appearance/mod.rs b/src/ui/appearance/mod.rs index 72c1619..f30a7f4 100644 --- a/src/ui/appearance/mod.rs +++ b/src/ui/appearance/mod.rs @@ -48,60 +48,86 @@ pub const COLOR_TOKENS: [&str; 15] = [ "--vnox-success", ]; +/// Stable persisted identifiers: six dark presets followed by six light presets. +pub const BUILTIN_THEME_IDS: [&str; 12] = [ + "black", + "dark", + "midnight", + "pine", + "aubergine", + "espresso", + "light", + "mist", + "glacier", + "sage", + "rose", + "sand", +]; + impl ThemeSpec { pub fn builtin(mode: &str) -> Self { let values = match mode { - "light" => [ - "#f5f4f2", - "#eae8e5", - "#dedbd6", - "#dfdcd7", - "#efede9", - "#ffffff", - "#d8d3cb", - "#0000001c", - "#78552d", - "#292622", - "#514b44", - "#6b645e", - "#756d65", - "#b43731", - "#3e704d", - ], "black" => [ - "#090909", - "#111111", - "#000000", - "#262626", - "#181818", - "#202020", - "#303030", - "#ffffff1c", - "#d5b58a", - "#f0eeee", - "#c3bdb7", - "#aba39b", - "#948a80", - "#ee948b", - "#a8c1a4", + "#090909", "#111111", "#000000", "#262626", "#181818", "#202020", "#303030", + "#9099a6", "#d5b58a", "#f8f6fa", "#e0dce5", "#ccc7d2", "#b9b2bf", "#ffb4b0", + "#9ce3b7", ], - _ => [ - "#272729", - "#202022", - "#151516", - "#38383c", - "#303033", - "#343336", - "#3a393c", - "#ffffff12", - "#d5b58a", - "#e9e7e4", - "#b8b4b1", - "#aaa29b", - "#85817f", - "#e58b85", - "#a8c1a4", + "dark" => [ + "#292b31", "#1d1f25", "#121419", "#373b45", "#30343e", "#323641", "#3b4251", + "#9099a6", "#d5b58a", "#f8f6fa", "#e0dce5", "#ccc7d2", "#b9b2bf", "#ffb4b0", + "#9ce3b7", ], + "midnight" => [ + "#151f32", "#10192a", "#0b1220", "#293952", "#202e45", "#25334b", "#30425c", + "#9099a6", "#9fc5ff", "#f8f6fa", "#e0dce5", "#ccc7d2", "#b9b2bf", "#ffb4b0", + "#9ce3b7", + ], + "pine" => [ + "#172b26", "#11231e", "#0b1915", "#294139", "#20372f", "#253c34", "#304b40", + "#9099a6", "#91d6af", "#f8f6fa", "#e0dce5", "#ccc7d2", "#b9b2bf", "#ffb4b0", + "#9ce3b7", + ], + "aubergine" => [ + "#2a2031", "#211827", "#170f1c", "#42314b", "#36293f", "#3b2d45", "#493650", + "#9099a6", "#dfb0eb", "#f8f6fa", "#e0dce5", "#ccc7d2", "#b9b2bf", "#ffb4b0", + "#9ce3b7", + ], + "espresso" => [ + "#2d241f", "#241c17", "#1b140f", "#45372e", "#392d25", "#3e3129", "#4b3b30", + "#9099a6", "#e8bd8d", "#f8f6fa", "#e0dce5", "#ccc7d2", "#b9b2bf", "#ffb4b0", + "#9ce3b7", + ], + "light" => [ + "#f5f4f2", "#eae8e5", "#dedbd6", "#e2ddd6", "#efede9", "#ffffff", "#d8d3cb", + "#737078", "#76532b", "#28252c", "#39353e", "#514c58", "#5d5663", "#a32436", + "#28613b", + ], + "mist" => [ + "#f2f3f7", "#e7e9f0", "#dadee9", "#dce0ec", "#eceef5", "#ffffff", "#cfd5e5", + "#737078", "#43578c", "#28252c", "#39353e", "#514c58", "#5d5663", "#a32436", + "#28613b", + ], + "glacier" => [ + "#eff6fa", "#e0edf4", "#d1e3ee", "#d5e7f1", "#e8f2f8", "#ffffff", "#c8e0ec", + "#737078", "#23617e", "#28252c", "#39353e", "#514c58", "#5d5663", "#a32436", + "#28613b", + ], + "sage" => [ + "#f0f6ef", "#e2ecdf", "#d3e1ce", "#d7e6d2", "#e9f2e5", "#ffffff", "#cbdcc4", + "#737078", "#3f653b", "#28252c", "#39353e", "#514c58", "#5d5663", "#a32436", + "#28613b", + ], + "rose" => [ + "#faf2f4", "#f0e3e8", "#e7d4dc", "#ecd9e1", "#f6eaf0", "#ffffff", "#e3ccd6", + "#737078", "#873e5a", "#28252c", "#39353e", "#514c58", "#5d5663", "#a32436", + "#28613b", + ], + "sand" => [ + "#faf5e9", "#f0e7d3", "#e6d9bd", "#eadebf", "#f6eedc", "#ffffff", "#dfd0ae", + "#737078", "#705018", "#28252c", "#39353e", "#514c58", "#5d5663", "#a32436", + "#28613b", + ], + _ => return Self::builtin("black"), }; Self { colors: values.map(|s| css::parse_color(s).expect("built-in hex color")), @@ -123,3 +149,96 @@ impl ThemeSpec { css } } + +#[cfg(test)] +mod tests { + use super::*; + + // WCAG 2.2 relative luminance in sRGB, not a brightness approximation. + fn luminance(color: Rgba) -> f64 { + let channel = |value: u8| { + let value = f64::from(value) / 255.0; + if value <= 0.04045 { + value / 12.92 + } else { + ((value + 0.055) / 1.055).powf(2.4) + } + }; + 0.2126 * channel(color.0) + 0.7152 * channel(color.1) + 0.0722 * channel(color.2) + } + + fn contrast(a: Rgba, b: Rgba) -> f64 { + let (a, b) = (luminance(a), luminance(b)); + (a.max(b) + 0.05) / (a.min(b) + 0.05) + } + + #[test] + fn every_builtin_keeps_text_status_selection_and_focus_readable() { + for id in BUILTIN_THEME_IDS { + let spec = ThemeSpec::builtin(id); + let c = spec.colors; + for background in 0..7 { + // Includes active selections, inputs, hover, muted text and error/success labels. + for foreground in [8, 9, 10, 11, 12, 13, 14] { + let ratio = contrast(c[foreground], c[background]); + assert!( + ratio >= 4.5, + "{id}: {foreground} on {background}: {ratio:.3}" + ); + } + let ratio = contrast(c[7], c[background]); + assert!( + ratio >= 3.0, + "{id}: control boundary on {background}: {ratio:.3}" + ); + } + let on_accent = if spec.is_light() { + Rgba(255, 255, 255, 255) + } else { + Rgba(35, 30, 25, 255) + }; + assert!(contrast(c[8], on_accent) >= 4.5, "{id}: primary action"); + } + } + + #[test] + fn theme_previews_use_the_actual_builtin_palette() { + let source = include_str!("../slint/settings/appearance.slint"); + for id in BUILTIN_THEME_IDS { + let card = source + .lines() + .find(|line| { + line.contains("ThemeChoice {") + && line.contains(&format!("theme-selected(\"{id}\")")) + }) + .unwrap_or_else(|| panic!("missing theme card {id}")); + let colors = ThemeSpec::builtin(id).colors; + for (name, index) in [ + ("background", 0), + ("sidebar", 1), + ("rail", 2), + ("selected", 6), + ("input", 5), + ("ink", 9), + ("accent", 8), + ] { + assert!( + card.contains(&format!("preview-{name}: {};", colors[index].css())), + "{id}: preview {name}" + ); + } + } + } + + #[test] + fn builtin_catalog_contains_six_light_and_six_dark_palettes() { + assert_eq!( + BUILTIN_THEME_IDS + .iter() + .filter(|id| ThemeSpec::builtin(id).is_light()) + .count(), + 6 + ); + assert_eq!(ThemeSpec::builtin("unknown"), ThemeSpec::builtin("black")); + } +} diff --git a/src/ui/appearance/storage.rs b/src/ui/appearance/storage.rs index 06455b9..f9e76c2 100644 --- a/src/ui/appearance/storage.rs +++ b/src/ui/appearance/storage.rs @@ -16,8 +16,8 @@ pub struct AppearancePreferences { impl Default for AppearancePreferences { fn default() -> Self { Self { - mode: "dark".into(), - custom_css: ThemeSpec::builtin("dark").to_css(), + mode: "black".into(), + custom_css: ThemeSpec::builtin("black").to_css(), font_size: 16.0, } } @@ -48,7 +48,7 @@ impl AppearancePreferences { } pub fn resolve(&self) -> Result { - if !["light", "dark", "black", "custom"].contains(&self.mode.as_str()) { + if self.mode != "custom" && !super::BUILTIN_THEME_IDS.contains(&self.mode.as_str()) { return Err(crate::ui::i18n::text("Unknown theme.")); } if !self.font_size.is_finite() || !(12.0..=22.0).contains(&self.font_size) { @@ -139,6 +139,26 @@ pub fn export_css(path: &Path, theme: &ThemeSpec) -> Result<(), String> { mod tests { use super::*; + #[test] + fn new_profiles_default_to_extra_dark_and_explicit_choices_survive() { + assert_eq!(AppearancePreferences::default().mode, "black"); + assert_eq!( + serde_json::from_str::("{}") + .unwrap() + .mode, + "black" + ); + for id in super::super::BUILTIN_THEME_IDS + .into_iter() + .chain(["custom"]) + { + let json = serde_json::json!({"mode": id}).to_string(); + let prefs: AppearancePreferences = serde_json::from_str(&json).unwrap(); + assert_eq!(prefs.mode, id); + assert!(prefs.resolve().is_ok(), "{id}"); + } + } + #[test] fn saved_custom_palette_and_text_size_survive_reload() { let directory = std::env::temp_dir().join(format!("vnox-theme-{}", uuid::Uuid::new_v4())); diff --git a/src/ui/avatar/bindings.rs b/src/ui/avatar/bindings.rs index aba5603..e4e9ff6 100644 --- a/src/ui/avatar/bindings.rs +++ b/src/ui/avatar/bindings.rs @@ -1,4 +1,4 @@ -use std::cell::RefCell; +use std::cell::{Cell, RefCell}; use std::path::PathBuf; use std::rc::Rc; @@ -9,6 +9,18 @@ use super::CropSource; use crate::AppState; use crate::ui::slint::MainWindow; +fn crop_context(state: &AppState) -> (String, Option, u64) { + ( + state.identity.pubkey_hex.clone(), + state + .ui + .central_account + .as_ref() + .map(|user| user.user_id.clone()), + crate::net::account::enrollment_epoch(), + ) +} + fn avatar_path(identity: &str) -> PathBuf { // Scope local photos by account; never place untrusted identity text in a path. let name = hex::encode(Sha256::digest(identity.as_bytes())); @@ -42,8 +54,10 @@ fn discard_crop(window: &MainWindow, pending: &Rc>>) pub fn wire(window: &MainWindow, state: &Rc>, persist: bool) { let pending = Rc::new(RefCell::new(None::)); + let busy = Rc::new(Cell::new(false)); + let crop_owner = Rc::new(RefCell::new(None)); let path = avatar_path(&state.borrow().identity.pubkey_hex); - if persist && path.exists() { + if persist && !window.get_account_authenticated() && path.exists() { match CropSource::load(&path) { Ok(source) => { window.set_own_avatar(source.ui_image()); @@ -55,13 +69,24 @@ pub fn wire(window: &MainWindow, state: &Rc>, persist: bool) { { let weak = window.as_weak(); let pending = pending.clone(); + let busy = busy.clone(); + let state = state.clone(); + let crop_owner = crop_owner.clone(); window.on_choose_avatar(move || { + if busy.get() { + return; + } let weak = weak.clone(); let pending = pending.clone(); if let Some(window) = weak.upgrade() { window.set_avatar_error("".into()); } let task_window = weak.clone(); + busy.set(true); + let task_busy = busy.clone(); + let owner = crop_context(&state.borrow()); + let state = state.clone(); + let crop_owner = crop_owner.clone(); let result = slint::spawn_local(async move { let Some(file) = rfd::AsyncFileDialog::new() .set_title(crate::ui::i18n::text("Choose profile photo")) @@ -72,13 +97,21 @@ pub fn wire(window: &MainWindow, state: &Rc>, persist: bool) { .pick_file() .await else { + task_busy.set(false); return; }; let path = file.path().to_owned(); let result = tokio::task::spawn_blocking(move || CropSource::load(&path)).await; + task_busy.set(false); if let Some(window) = task_window.upgrade() { match result { - Ok(Ok(source)) => begin_crop(&window, &pending, source), + Ok(Ok(source)) => { + if crop_context(&state.borrow()) != owner { + return; + } + *crop_owner.borrow_mut() = Some(owner); + begin_crop(&window, &pending, source); + } Ok(Err(error)) => window.set_avatar_error(error.into()), Err(_) => window.set_avatar_error( crate::ui::i18n::text( @@ -92,6 +125,7 @@ pub fn wire(window: &MainWindow, state: &Rc>, persist: bool) { if result.is_err() && let Some(window) = weak.upgrade() { + busy.set(false); window.set_avatar_error( crate::ui::i18n::text("The file picker is unavailable in this environment.") .into(), @@ -127,18 +161,35 @@ pub fn wire(window: &MainWindow, state: &Rc>, persist: bool) { let weak = window.as_weak(); let pending = pending.clone(); let path = path.clone(); + let state = state.clone(); + let busy = busy.clone(); + let crop_owner = crop_owner.clone(); window.on_confirm_avatar(move || { + if busy.get() { + return; + } if let Some(window) = weak.upgrade() { - let result = { - let source = pending.borrow(); - source.as_ref().map(|source| { - if persist { - source.save_to(&path) - } else { - Ok(source.cropped_ui_image()) - } - }) - }; + if crop_owner.borrow().as_ref() != Some(&crop_context(&state.borrow())) { + discard_crop(&window, &pending); + window.set_avatar_error( + crate::ui::i18n::text("Account changed. Choose your photo again.").into(), + ); + return; + } + if window.get_account_authenticated() { + let picture = pending.borrow().as_ref().map(CropSource::cropped); + if let Some(picture) = picture { + mutate_central(&window, &state, &pending, &busy, Some(picture)); + } + return; + } + let result = pending.borrow().as_ref().map(|source| { + if persist { + source.save_to(&path) + } else { + Ok(source.cropped_ui_image()) + } + }); if let Some(result) = result { match result { Ok(image) => { @@ -165,7 +216,18 @@ pub fn wire(window: &MainWindow, state: &Rc>, persist: bool) { } { let weak = window.as_weak(); + let state = state.clone(); + let pending = pending.clone(); window.on_remove_avatar(move || { + if busy.get() { + return; + } + if let Some(window) = weak.upgrade() + && window.get_account_authenticated() + { + mutate_central(&window, &state, &pending, &busy, None); + return; + } if let Some(window) = weak.upgrade() { if persist && let Err(error) = std::fs::remove_file(&path) @@ -187,3 +249,88 @@ pub fn wire(window: &MainWindow, state: &Rc>, persist: bool) { }); } } + +fn mutate_central( + window: &MainWindow, + state: &Rc>, + pending: &Rc>>, + busy: &Rc>, + picture: Option, +) { + if busy.replace(true) { + return; + } + window.set_avatar_saving(true); + window.set_avatar_error("".into()); + let weak = window.as_weak(); + let state = state.clone(); + let pending = pending.clone(); + let busy = busy.clone(); + let identity = state.borrow().identity.clone(); + let account_id = state + .borrow() + .ui + .central_account + .as_ref() + .map(|account| account.user_id.clone()); + let request_identity = identity.clone(); + let epoch = crate::net::account::enrollment_epoch(); + let task_busy = busy.clone(); + let task_window = weak.clone(); + let result = slint::spawn_local(async move { + let result = tokio::spawn(async move { + let png = if let Some(picture) = picture { + Some( + tokio::task::spawn_blocking(move || -> anyhow::Result> { + let mut output = std::io::Cursor::new(Vec::new()); + picture.write_to(&mut output, image::ImageFormat::Png)?; + Ok(output.into_inner()) + }) + .await??, + ) + } else { + None + }; + crate::net::account::set_avatar(&request_identity, png, epoch).await + }) + .await; + task_busy.set(false); + let Some(window) = task_window.upgrade() else { + return; + }; + let still_current = window.get_account_authenticated() + && epoch == crate::net::account::enrollment_epoch() + && state.borrow().identity.pubkey_hex == identity.pubkey_hex + && state + .borrow() + .ui + .central_account + .as_ref() + .map(|account| &account.user_id) + == account_id.as_ref(); + if !still_current { + return; + } + window.set_avatar_saving(false); + match result { + Ok(Ok(user)) => { + crate::ui::account::apply_profile(&window, &mut state.borrow_mut(), user); + window.set_avatar_error("".into()); + discard_crop(&window, &pending); + } + Ok(Err(error)) => { + window.set_avatar_error(crate::ui::i18n::text(&error.to_string()).into()) + } + Err(_) => window + .set_avatar_error(crate::ui::i18n::text("Could not save photo. Try again.").into()), + } + }); + if result.is_err() { + busy.set(false); + if let Some(window) = weak.upgrade() { + window.set_avatar_saving(false); + window + .set_avatar_error(crate::ui::i18n::text("Could not save photo. Try again.").into()); + } + } +} diff --git a/src/ui/avatar/central.rs b/src/ui/avatar/central.rs new file mode 100644 index 0000000..db833ec --- /dev/null +++ b/src/ui/avatar/central.rs @@ -0,0 +1,137 @@ +//! Public Central avatar fetching, without credentials or redirects. +use std::{ + cell::RefCell, + collections::HashMap, + time::{Duration, Instant}, +}; +const RETRY_AFTER: Duration = Duration::from_secs(30); +fn retry_due(failed_at: Instant) -> bool { + failed_at.elapsed() >= RETRY_AFTER +} +enum CachedAvatar { + Pending, + Ready(slint::Image), + Failed(Instant), +} +thread_local! { static CACHE: RefCell> = RefCell::new(HashMap::new()); } +pub fn url(path: &str) -> Option { + let path = path + .strip_prefix(crate::net::account::CENTRAL_ORIGIN) + .unwrap_or(path); + (path.len() <= 256 + && path.starts_with("/v1/avatars/") + && path + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"/-".contains(&b))) + .then(|| format!("{}{path}", crate::net::account::CENTRAL_ORIGIN)) +} +/// Poll from the UI bridge; failed requests retry after a bounded cooldown. +pub fn image(path: &str) -> slint::Image { + let Some(url) = url(path) else { + return slint::Image::default(); + }; + let cached = CACHE.with(|cache| { + let mut cache = cache.borrow_mut(); + match cache.get(&url) { + Some(CachedAvatar::Ready(image)) => return Some(image.clone()), + Some(CachedAvatar::Pending) => return Some(slint::Image::default()), + Some(CachedAvatar::Failed(at)) if !retry_due(*at) => { + return Some(slint::Image::default()); + } + Some(CachedAvatar::Failed(_)) => {} + None if cache.len() >= 256 => return Some(slint::Image::default()), + None => {} + } + cache.insert(url.clone(), CachedAvatar::Pending); + None + }); + if let Some(image) = cached { + return image; + } + let _ = slint::spawn_local(async move { + let request = url.clone(); + if let Ok(Ok((w, h, rgba))) = tokio::spawn(async move { fetch(&request).await }).await { + let buffer = + slint::SharedPixelBuffer::::clone_from_slice(&rgba, w, h); + CACHE.with(|c| { + c.borrow_mut() + .insert(url, CachedAvatar::Ready(slint::Image::from_rgba8(buffer))) + }); + } else { + CACHE.with(|cache| { + cache + .borrow_mut() + .insert(url, CachedAvatar::Failed(Instant::now())) + }); + } + }); + slint::Image::default() +} +async fn fetch(url: &str) -> anyhow::Result<(u32, u32, Vec)> { + anyhow::ensure!( + self::url(url).as_deref() == Some(url), + "invalid avatar origin" + ); + static REQUESTS: std::sync::OnceLock = std::sync::OnceLock::new(); + let _permit = REQUESTS + .get_or_init(|| tokio::sync::Semaphore::new(4)) + .acquire() + .await?; + let client = reqwest::Client::builder() + .user_agent("VNOX-Desktop/0.1") + .no_proxy() + .https_only(true) + .redirect(reqwest::redirect::Policy::none()) + .connect_timeout(Duration::from_secs(5)) + .timeout(Duration::from_secs(10)) + .build()?; + let mut response = client.get(url).send().await?.error_for_status()?; + anyhow::ensure!( + response + .headers() + .get(reqwest::header::CONTENT_TYPE) + .and_then(|v| v.to_str().ok()) + .is_some_and(|v| v.split(';').next() == Some("image/png")), + "expected PNG" + ); + let mut bytes = Vec::new(); + while let Some(chunk) = response.chunk().await? { + anyhow::ensure!(bytes.len() + chunk.len() <= 1024 * 1024, "avatar too large"); + bytes.extend_from_slice(&chunk); + } + tokio::task::spawn_blocking(move || { + let mut reader = + image::ImageReader::with_format(std::io::Cursor::new(bytes), image::ImageFormat::Png); + let mut limits = image::Limits::default(); + limits.max_image_width = Some(512); + limits.max_image_height = Some(512); + limits.max_alloc = Some(4 * 1024 * 1024); + reader.limits(limits); + let image = reader.decode()?.to_rgba8(); + Ok((image.width(), image.height(), image.into_raw())) + }) + .await? +} +#[cfg(test)] +mod tests { + #[test] + fn transient_failure_retries_only_after_cooldown() { + assert!(!super::retry_due(std::time::Instant::now())); + assert!(super::retry_due( + std::time::Instant::now() - std::time::Duration::from_secs(31) + )); + } + #[test] + fn only_same_origin_public_paths() { + assert!(super::url("/v1/avatars/default/abc-123").is_some()); + for path in [ + "https://github.com/x", + "//evil/v1/avatars/x", + "/v1/avatars/../x", + "/v1/avatars/x?token=s", + "https://central.loki-code.dev.evil/v1/avatars/x", + ] { + assert!(super::url(path).is_none()); + } + } +} diff --git a/src/ui/avatar/mod.rs b/src/ui/avatar/mod.rs index d30bf27..0d32a51 100644 --- a/src/ui/avatar/mod.rs +++ b/src/ui/avatar/mod.rs @@ -1,4 +1,5 @@ mod bindings; +pub mod central; mod crop; pub use bindings::wire; diff --git a/src/ui/bridge.rs b/src/ui/bridge.rs index bad8b98..a3c7a15 100644 --- a/src/ui/bridge.rs +++ b/src/ui/bridge.rs @@ -26,7 +26,6 @@ fn presence_key(status: &str) -> &'static str { type MainWindow = crate::ui::slint::MainWindow; type BookmarkItem = crate::ui::slint::BookmarkItem; -type ChannelItem = crate::ui::slint::ChannelItem; type DmItem = crate::ui::slint::DmItem; type GuildItem = crate::ui::slint::GuildItem; type MessageItem = crate::ui::slint::MessageItem; @@ -45,7 +44,7 @@ fn replace_model( } } -fn initials(name: &str) -> SharedString { +pub(crate) fn initials(name: &str) -> SharedString { name.chars().take(2).collect::().into() } @@ -74,23 +73,29 @@ fn reaction_items(m: &crate::ui::state::ChatMessage, own_user_id: &str) -> Vec bool { +pub(crate) fn same_message(a: &MessageItem, b: &MessageItem) -> bool { a.message_id == b.message_id && a.sender_id == b.sender_id && a.sender_name == b.sender_name && a.content == b.content + && a.media_source == b.media_source && a.timestamp == b.timestamp && a.is_own == b.is_own && a.edited == b.edited && a.reply_to == b.reply_to + && a.has_avatar == b.has_avatar + && (!a.has_avatar || a.avatar == b.avatar) && a.avatar_text == b.avatar_text && a.show_author == b.show_author && a.reactions.iter().eq(b.reactions.iter()) } -fn fmt_ts(ts: i64) -> String { - let secs = (ts / 1000).abs() % 86400; - format!("{:02}:{:02}", secs / 3600, (secs % 3600) / 60) +fn profile_avatar(state: &UiState, device: &str, own_device: &str) -> slint::Image { + state + .avatar_path_for(device, own_device) + .as_deref() + .map(super::avatar::central::image) + .unwrap_or_default() } fn set_messages( @@ -99,19 +104,39 @@ fn set_messages( msgs: &[crate::ui::state::ChatMessage], own_user_id: &str, ) { + let now = chrono::Local::now(); let items: Vec = msgs .iter() .enumerate() .map(|(index, m)| MessageItem { + media_image: Default::default(), + media_ready: false, + media_status: Default::default(), + media_ratio: 1.0, + avatar: profile_avatar(state, &m.sender_id, own_user_id), + has_avatar: profile_avatar(state, &m.sender_id, own_user_id) + .size() + .width + > 0, avatar_text: initials(state.nick_for(&m.sender_id)), show_author: index == 0 || msgs[index - 1].sender_id != m.sender_id + || !super::timestamps::same_day_at( + msgs[index - 1].timestamp, + m.timestamp, + &chrono::Local, + ) || m.timestamp.saturating_sub(msgs[index - 1].timestamp) > 300_000, message_id: SharedString::from(m.message_id.as_str()), sender_id: SharedString::from(m.sender_id.as_str()), sender_name: SharedString::from(state.nick_for(&m.sender_id)), - content: SharedString::from(m.content.as_str()), - timestamp: SharedString::from(fmt_ts(m.timestamp)), + media_source: m.content.as_str().into(), + content: if m.content.starts_with("vnox-attachment:") { + "".into() + } else { + m.content.as_str().into() + }, + timestamp: SharedString::from(super::timestamps::format_at(m.timestamp, &now)), is_own: m.sender_id == own_user_id, edited: m.edited, reactions: Rc::new(VecModel::from(reaction_items(m, own_user_id))).into(), @@ -147,19 +172,31 @@ fn set_messages( } } +fn same_member(a: &MemberItem, b: &MemberItem) -> bool { + a.user_id == b.user_id + && a.nickname == b.nickname + && a.status == b.status + && a.presence == b.presence + && a.avatar_text == b.avatar_text + && a.is_own == b.is_own + && a.has_avatar == b.has_avatar + && (!a.has_avatar || a.avatar == b.avatar) +} + fn set_members_state(window: &MainWindow, state: &UiState, ch_id: &str, own_user_id: &str) { if let Some(ch) = state.channels.iter().find(|c| c.id == ch_id) { - let items: Vec = ch - .members - .iter() - .map(|nick| { - let user_id = state - .user_names - .iter() - .find(|(_, n)| *n == nick) - .map(|(id, _)| id.clone()) - .unwrap_or_else(|| nick.clone()); - let is_own = user_id == own_user_id; + let items: Vec = state + .account_members(&ch.members) + .into_iter() + .map(|device| { + let user_id = device.clone(); + let nick = state.nick_for(device); + let is_own = user_id == own_user_id + || state + .member_profiles + .get(&user_id) + .zip(state.member_profiles.get(own_user_id)) + .is_some_and(|(member, own)| !member.0.is_empty() && member.0 == own.0); // This client is connected whenever the member list is shown, so the local user // is online even though the server sends no presence update about oneself. let status = if is_own { @@ -169,40 +206,38 @@ fn set_members_state(window: &MainWindow, state: &UiState, ch_id: &str, own_user .presences .get(&user_id) .map(|p| p.status.as_str()) - .unwrap_or("offline") + .unwrap_or("online") }; + let avatar = profile_avatar( + state, + if is_own { own_user_id } else { device }, + own_user_id, + ); MemberItem { + has_avatar: avatar.size().width > 0, + avatar, avatar_text: initials(nick), user_id: SharedString::from(user_id), - nickname: SharedString::from(nick.as_str()), + nickname: SharedString::from(nick), status: presence_label(status).into(), presence: presence_key(status).into(), is_own, } }) .collect(); - replace_model(window.get_members(), items, |model| { - window.set_members(model) - }); + let current = window.get_members(); + if current.row_count() != items.len() + || !current.iter().zip(&items).all(|(a, b)| same_member(&a, b)) + { + window.set_members(Rc::new(VecModel::from(items)).into()); + } } } fn sync_sidebar(window: &MainWindow, state: &UiState, own_nickname: &str) { + crate::ui::channel_admin::sync(window, state); let guild_id = state.active_guild_id.as_deref(); - - let channels: Vec = state - .channels - .iter() - .filter(|c| match guild_id { - None => true, - Some(gid) => c.guild_id.as_deref() == Some(gid) || c.guild_id.is_none(), - }) - .map(|c| ChannelItem { - channel_id: SharedString::from(c.id.as_str()), - name: SharedString::from(c.name.as_str()), - kind: SharedString::from(c.kind.as_str()), - }) - .collect(); + let channels = crate::ui::channel_admin::sidebar_channels(state); replace_model(window.get_channels(), channels, |model| { window.set_channels(model) }); @@ -273,7 +308,7 @@ fn sync_chat(window: &MainWindow, state: &UiState, own_user_id: &str) { window.set_e2ee_enabled(false); window.set_dm_partner_name(dm.map_or("", |c| c.other_nickname.as_str()).into()); window.set_show_voice(state.showing_voice); - window.set_show_chat(!state.showing_voice && (dm.is_some() || channel.is_some())); + window.set_show_chat(!state.showing_voice && (dm.is_some() || channel.is_some_and(|channel| channel.kind == "text"))); window.set_show_friends(!state.showing_voice && dm.is_none() && channel.is_none()); if let Some(dm) = dm { window.set_active_channel_name(dm.other_nickname.as_str().into()); @@ -324,7 +359,7 @@ fn sync_friends(window: &MainWindow, state: &UiState) { .presences .get(&f.user_id) .map(|p| p.status.as_str()) - .unwrap_or("offline"), + .unwrap_or("online"), ) .into(), status: SharedString::from( @@ -332,7 +367,7 @@ fn sync_friends(window: &MainWindow, state: &UiState) { .presences .get(&f.user_id) .map(|p| p.status.as_str()) - .unwrap_or("offline"), + .unwrap_or("online"), ), }) .collect(); @@ -378,25 +413,39 @@ pub fn sync_voice(window: &MainWindow, state: &UiState, own_user_id: &str) { ) }) .flat_map(|c| c.members.iter()) - .map(|nick| { - let user_id = state - .user_names - .iter() - .find(|(_, n)| *n == nick) - .map(|(id, _)| id.clone()) - .unwrap_or_else(|| nick.clone()); + .map(|device| { + let user_id = device.clone(); + let nick = state.nick_for(device); + let avatar = profile_avatar(state, device, own_user_id); VoiceMemberItem { + has_avatar: avatar.size().width > 0, + avatar, avatar_text: initials(nick), is_own: user_id == own_user_id, user_id: SharedString::from(user_id.clone()), - nickname: SharedString::from(nick.as_str()), - speaking: state.remote_speaking && state.last_remote_speaker_id == user_id, + nickname: SharedString::from(nick), + speaking: if user_id == own_user_id { + state.local_speaking + } else { + state.remote_speaking && state.last_remote_speaker_id == user_id + }, } }) .collect(); - replace_model(window.get_voice_members(), members, |model| { - window.set_voice_members(model) - }); + let current = window.get_voice_members(); + if current.row_count() != members.len() + || !current.iter().zip(&members).all(|(a, b)| { + a.user_id == b.user_id + && a.nickname == b.nickname + && a.speaking == b.speaking + && a.avatar_text == b.avatar_text + && a.is_own == b.is_own + && a.has_avatar == b.has_avatar + && (!a.has_avatar || a.avatar == b.avatar) + }) + { + window.set_voice_members(Rc::new(VecModel::from(members)).into()); + } window.set_mic_enabled(state.mic_enabled); window.set_deafened(state.deafen); @@ -487,6 +536,12 @@ pub fn sync_settings(window: &MainWindow, state: &UiState, own_pubkey: &str) { window.set_voice_bitrate(state.voice_bitrate); window.set_vad_mode(state.vad_mode as i32); window.set_volume(state.output_volume); + window.set_noise_suppress(state.noise_suppress); + window.set_noise_suppress_available(cfg!(feature = "rnnoise")); + window.set_mic_test_running(state.mic_test_running); + window.set_mic_test_level(state.mic_test_level); + window.set_mic_test_error(state.mic_test_error.as_deref().unwrap_or("").into()); + window.set_local_speaking(state.local_speaking); window.set_sounds_enabled(state.sounds.enabled); window.set_sounds_volume(state.sounds.volume); window.set_sounds_voice_room(state.sounds.voice_room); @@ -531,6 +586,26 @@ pub fn sync_ui( own_nickname: &str, own_pubkey: &str, ) { + crate::ui::forum::sync(window, state, own_user_id); + if let Some(account) = &state.central_account { + if window.get_profile_display_name() == window.get_account_name() { + window.set_profile_display_name(account.display_name.clone().into()); + } + window.set_account_name(account.display_name.clone().into()); + window.set_profile_initials(initials(&account.display_name)); + let image = super::avatar::central::image( + &state + .avatar_path_for(own_user_id, own_user_id) + .unwrap_or_default(), + ); + window.set_has_avatar(image.size().width > 0); + window.set_own_avatar(image); + } + let own_nickname = state + .central_account + .as_ref() + .map(|account| account.display_name.as_str()) + .unwrap_or(own_nickname); sync_sidebar(window, state, own_nickname); sync_chat(window, state, own_user_id); sync_friends(window, state); @@ -538,3 +613,22 @@ pub fn sync_ui( sync_connect(window, state); sync_settings(window, state, own_pubkey); } + +#[cfg(test)] +mod avatar_model_tests { + #[test] + fn empty_avatars_do_not_replace_unchanged_message_and_member_models() { + let message = super::MessageItem::default(); + assert!(super::same_message( + &message, + &super::MessageItem::default() + )); + let member = super::MemberItem::default(); + assert!(super::same_member(&member, &super::MemberItem::default())); + let changed = super::MemberItem { + has_avatar: true, + ..Default::default() + }; + assert!(!super::same_member(&member, &changed)); + } +} diff --git a/src/ui/channel_admin.rs b/src/ui/channel_admin.rs new file mode 100644 index 0000000..917889b --- /dev/null +++ b/src/ui/channel_admin.rs @@ -0,0 +1,853 @@ +//! Node-advertised global channel management. Gateway authorization remains authoritative. +use crate::{ + AppState, + net::{NetCommand, NetEvent}, + ui::{ + slint::MainWindow, + state::{ConnState, UiState}, + }, +}; +use slint::{ComponentHandle, Model}; +use std::{ + cell::RefCell, + rc::Rc, + time::{Duration, Instant}, +}; + +#[derive(Clone)] +enum Dialog { + Create { + parent_id: Option, + id: String, + name: String, + kind: String, + }, + Rename { + id: String, + name: String, + }, + Delete { + id: String, + name: String, + }, +} +impl Dialog { + fn id(&self) -> &str { + match self { + Self::Create { id, .. } | Self::Rename { id, .. } | Self::Delete { id, .. } => id, + } + } + fn name(&self) -> &str { + match self { + Self::Create { name, .. } | Self::Rename { name, .. } | Self::Delete { name, .. } => { + name + } + } + } + fn operation(&self) -> &str { + match self { + Self::Create { .. } => "create", + Self::Rename { .. } => "rename", + Self::Delete { .. } => "delete", + } + } +} +/// Unsaved dialog draft and at most one unacknowledged global channel operation. +#[derive(Default)] +pub struct AdminState { + menu: Option, + categories: Vec<(String, String)>, + dialog: Option, + pending: Option, + error: String, +} + +pub(super) fn allowed(ui: &UiState) -> bool { + ui.node_admin + && matches!(ui.conn, ConnState::Connected { .. }) + && !ui.connection.authentication_required + && ui.central_account.is_some() + && ui.active_guild_id.is_none() + && !ui.browsing_dms +} +fn open(ui: &mut UiState, operation: &str, id_or_kind: &str) { + if !allowed(ui) || ui.channel_admin.pending.is_some() { + return; + } + let dialog = if operation == "create" { + if !["text", "voice", "category", "forum"].contains(&id_or_kind) + || (id_or_kind == "category" && !ui.channel_structure_supported) + || (id_or_kind == "forum" && !ui.forum.supported) + { + return; + } + Dialog::Create { + parent_id: None, + id: uuid::Uuid::new_v4().to_string(), + name: String::new(), + kind: id_or_kind.to_owned(), + } + } else { + let Some(channel) = ui + .channels + .iter() + .find(|channel| channel.id == id_or_kind && channel.guild_id.is_none()) + else { + return; + }; + match operation { + "rename" => Dialog::Rename { + id: channel.id.clone(), + name: channel.name.clone(), + }, + "delete" => Dialog::Delete { + id: channel.id.clone(), + name: channel.name.clone(), + }, + _ => return, + } + }; + let categories = category_choices(ui); + ui.channel_admin = AdminState { + categories, + dialog: Some(dialog), + ..Default::default() + }; +} +fn prepare(ui: &mut UiState) -> Option { + if !allowed(ui) || ui.channel_admin.pending.is_some() { + return None; + } + let dialog = ui.channel_admin.dialog.clone()?; + if !matches!(dialog, Dialog::Create { .. }) + && !ui + .channels + .iter() + .any(|channel| channel.id == dialog.id() && channel.guild_id.is_none()) + { + ui.channel_admin.error = super::i18n::text("This global channel is no longer available."); + return None; + } + if let Dialog::Create { + kind, parent_id, .. + } = &dialog + { + if (kind == "category" && !ui.channel_structure_supported) + || (kind == "forum" && !ui.forum.supported) + || parent_id.as_ref().is_some_and(|parent| { + !ui.channels.iter().any(|channel| { + channel.id == *parent + && channel.kind == "category" + && channel.guild_id.is_none() + }) + }) + { + ui.channel_admin.error = + super::i18n::text("This channel type or category is no longer available."); + return None; + } + } + let name = dialog.name().trim(); + if !matches!(dialog, Dialog::Delete { .. }) + && (name.is_empty() || name.chars().count() > 100 || name.chars().any(char::is_control)) + { + ui.channel_admin.error = + super::i18n::text("Enter a channel name (1–100 characters, no control characters)."); + return None; + } + let command = match dialog { + Dialog::Create { + ref id, + ref kind, + ref parent_id, + .. + } => NetCommand::ChannelCreate { + channel_id: id.clone(), + channel_name: name.to_owned(), + kind: kind.clone(), + guild_id: None, + parent_id: parent_id.clone(), + position: 0, + }, + Dialog::Rename { ref id, .. } => NetCommand::ChannelEdit { + channel_id: id.clone(), + channel_name: name.to_owned(), + parent_id: None, + position: None, + }, + Dialog::Delete { ref id, .. } => NetCommand::ChannelDelete { + channel_id: id.clone(), + }, + }; + ui.channel_admin.pending = Some(Instant::now()); + ui.channel_admin.error.clear(); + Some(command) +} + +fn prepare_for_session(ui: &mut UiState) -> Option { + let session_id = match &ui.conn { + ConnState::Connected { session_id, .. } => session_id.clone(), + _ => return None, + }; + let command = prepare(ui)?; + Some(NetCommand::ForSession { + session_id, + command: Box::new(command), + }) +} + +/// Connect transient management callbacks; every submission rechecks server capability and scope. +pub fn wire(window: &MainWindow, state: &Rc>) { + super::server_settings::wire(window, state); + wire_menus(window, state); + for operation in ["create", "rename", "delete"] { + let state = state.clone(); + let handler = move |value: slint::SharedString| { + open(&mut state.borrow_mut().ui, operation, value.as_str()) + }; + match operation { + "create" => window.on_create_global_channel(handler), + "rename" => window.on_rename_global_channel(handler), + _ => window.on_delete_global_channel(handler), + } + } + { + let state = state.clone(); + window.on_channel_admin_name_edited(move |name| { + let mut state = state.borrow_mut(); + if state.ui.channel_admin.pending.is_some() { + return; + } + if let Some(Dialog::Create { name: value, .. } | Dialog::Rename { name: value, .. }) = + state.ui.channel_admin.dialog.as_mut() + { + *value = name.to_string(); + } + }); + } + { + let state = state.clone(); + window.on_channel_admin_cancel(move || { + // Cancellation closes the UI; it cannot recall a request already sent to the server. + state.borrow_mut().ui.channel_admin = AdminState::default(); + }); + } + { + let state = state.clone(); + window.on_channel_admin_submit(move || { + let (command, net) = { + let mut state = state.borrow_mut(); + (prepare_for_session(&mut state.ui), state.net.clone()) + }; + if let Some(command) = command { + tokio::spawn(async move { + net.send(command).await; + }); + } + }); + } +} + +/// Close unavailable management UI and report an unacknowledged request after ten seconds. +pub fn tick(ui: &mut UiState) { + if ui + .channel_admin + .menu + .as_ref() + .is_some_and(|menu| current_session(ui) != Some(menu.session_id.as_str())) + { + ui.channel_admin.menu = None; + } + if !allowed(ui) { + ui.channel_admin.dialog = None; + ui.channel_admin.pending = None; + return; + } + if ui + .channel_admin + .pending + .is_some_and(|started| started.elapsed() >= Duration::from_secs(10)) + { + ui.channel_admin.pending = None; + ui.channel_admin.error = super::i18n::text( + "No confirmation received. Close this dialog and check the channel list before trying again.", + ); + } +} +/// Consume matching server acknowledgements without changing channel membership optimistically. +pub fn receive(ui: &mut UiState, event: &NetEvent) { + if matches!( + event, + NetEvent::Disconnected { .. } | NetEvent::Reconnecting { .. } | NetEvent::AccountRequired + ) { + ui.node_admin = false; + ui.channel_admin = AdminState::default(); + return; + } + if ui.channel_admin.pending.is_none() { + return; + } + let Some(dialog) = &ui.channel_admin.dialog else { + return; + }; + let success = match (dialog, event) { + ( + Dialog::Create { id, name, .. }, + NetEvent::ChannelCreated { + channel_id, + channel_name, + guild_id, + .. + } + | NetEvent::ChannelState { + channel_id, + channel_name, + guild_id, + .. + }, + ) => id == channel_id && name.trim() == channel_name && guild_id.is_none(), + ( + Dialog::Rename { id, name }, + NetEvent::ChannelEdited { + channel_id, + channel_name, + .. + }, + ) => id == channel_id && name.trim() == channel_name, + (Dialog::Delete { id, .. }, NetEvent::ChannelDeleted { channel_id }) => id == channel_id, + _ => false, + }; + if success { + ui.channel_admin = AdminState::default(); + } else if let NetEvent::Error { message, .. } = event { + // LNEx generic errors do not carry a request ID. Keep the dialog and its draft; + // never infer success or roll back a server change from an uncorrelated error. + ui.channel_admin.pending = None; + ui.channel_admin.error = + super::i18n::format("Server error: {message}", &[("message", message.clone())]); + } +} +/// Copy the capability and transient management state into the native UI. +pub fn sync(window: &MainWindow, ui: &UiState) { + super::server_settings::sync(window, ui); + let menu = ui.channel_admin.menu.as_ref(); + window.set_management_menu_open(menu.is_some()); + window.set_management_menu_x(menu.map(|menu| menu.x).unwrap_or(0.0)); + window.set_management_menu_y(menu.map(|menu| menu.y).unwrap_or(0.0)); + let actions = menu + .map(|menu| { + menu.actions + .iter() + .map(|item| crate::ui::slint::ManagementAction { + text: item.text.clone().into(), + icon: item.icon.into(), + action: item.action.into(), + danger: item.action == "delete" || item.action == "disconnect", + }) + .collect::>() + }) + .unwrap_or_default(); + if !window + .get_management_actions() + .iter() + .eq(actions.iter().cloned()) + { + window.set_management_actions(std::rc::Rc::new(slint::VecModel::from(actions)).into()); + } + let mut names = vec![slint::SharedString::from(super::i18n::text("No category"))]; + names.extend( + ui.channel_admin + .categories + .iter() + .map(|(_, name)| name.as_str().into()), + ); + if !window + .get_channel_admin_parent_names() + .iter() + .eq(names.iter().cloned()) + { + window + .set_channel_admin_parent_names(std::rc::Rc::new(slint::VecModel::from(names)).into()); + } + let parent = match &ui.channel_admin.dialog { + Some(Dialog::Create { parent_id, .. }) => parent_id.as_deref(), + _ => None, + }; + window.set_channel_admin_parent_index( + parent + .and_then(|id| { + ui.channel_admin + .categories + .iter() + .position(|(value, _)| value == id) + }) + .map(|index| index + 1) + .unwrap_or(0) as i32, + ); + window.set_node_structure(ui.channel_structure_supported); + window.set_node_forums(ui.forum.supported); + + window.set_node_admin(allowed(ui)); + let dialog = ui.channel_admin.dialog.as_ref(); + window.set_channel_admin_open(dialog.is_some() && allowed(ui)); + window.set_channel_admin_operation(dialog.map(Dialog::operation).unwrap_or("").into()); + window.set_channel_admin_name(dialog.map(Dialog::name).unwrap_or("").into()); + window.set_channel_admin_kind( + match dialog { + Some(Dialog::Create { kind, .. }) => kind.as_str(), + _ => "", + } + .into(), + ); + window.set_channel_admin_busy(ui.channel_admin.pending.is_some()); + window.set_channel_admin_error(ui.channel_admin.error.as_str().into()); +} + +#[cfg(test)] +mod tests { + use super::*; + fn admin() -> UiState { + UiState { + node_admin: true, + conn: ConnState::Connected { + session_id: "fixture".into(), + node_name: "Fixture server".into(), + }, + central_account: Some(crate::net::account::AccountSummary { + user_id: "fixture-account".into(), + handle: "fixture".into(), + display_name: "Fixture".into(), + avatar_url: None, + profile_complete: false, + }), + channels: vec![ + crate::ui::state::Channel { + id: "global".into(), + name: "General".into(), + kind: "text".into(), + guild_id: None, + members: vec![], + }, + crate::ui::state::Channel { + id: "guild-channel".into(), + name: "Guild".into(), + kind: "voice".into(), + guild_id: Some("guild".into()), + members: vec![], + }, + ], + ..Default::default() + } + } + #[test] + fn every_management_command_is_scoped_to_the_session_that_prepared_it() { + for (operation, value) in [ + ("create", "text"), + ("rename", "global"), + ("delete", "global"), + ] { + let mut ui = admin(); + open(&mut ui, operation, value); + if let Some(Dialog::Create { name, .. }) = &mut ui.channel_admin.dialog { + *name = "New".into(); + } + let command = prepare_for_session(&mut ui).unwrap(); + ui.conn = ConnState::Connected { + session_id: "replacement-session".into(), + node_name: "Other node".into(), + }; + match command { + NetCommand::ForSession { + session_id, + command, + } => { + assert_eq!(session_id, "fixture"); + assert!(matches!( + *command, + NetCommand::ChannelCreate { .. } + | NetCommand::ChannelEdit { .. } + | NetCommand::ChannelDelete { .. } + )); + } + _ => panic!("management command escaped its original session"), + } + } + } + #[test] + fn capability_and_global_scope_are_rechecked_for_every_action() { + let mut ui = admin(); + ui.node_admin = false; + open(&mut ui, "create", "text"); + assert!(ui.channel_admin.dialog.is_none()); + ui.node_admin = true; + open(&mut ui, "rename", "guild-channel"); + assert!(ui.channel_admin.dialog.is_none()); + ui.active_guild_id = Some("guild".into()); + open(&mut ui, "create", "text"); + assert!(ui.channel_admin.dialog.is_none()); + ui.active_guild_id = None; + open(&mut ui, "create", "text"); + ui.node_admin = false; + assert!(prepare(&mut ui).is_none()); + tick(&mut ui); + assert!(ui.channel_admin.dialog.is_none()); + } + #[test] + fn create_keeps_stable_id_and_draft_until_matching_server_confirmation() { + let mut ui = admin(); + open(&mut ui, "create", "voice"); + if let Some(Dialog::Create { name, .. }) = &mut ui.channel_admin.dialog { + *name = " New room ".into(); + } + let before = ui.channels.len(); + let id = match prepare(&mut ui).unwrap() { + NetCommand::ChannelCreate { + channel_id, + channel_name, + kind, + guild_id, + } => { + assert_eq!(channel_name, "New room"); + assert_eq!(kind, "voice"); + assert!(guild_id.is_none()); + channel_id + } + _ => panic!(), + }; + assert_eq!(ui.channels.len(), before); + assert!(prepare(&mut ui).is_none()); + receive( + &mut ui, + &NetEvent::ChannelCreated { + channel_id: "unrelated".into(), + channel_name: "Other".into(), + kind: "voice".into(), + guild_id: None, + }, + ); + assert!(ui.channel_admin.pending.is_some()); + receive( + &mut ui, + &NetEvent::Error { + code: 1, + message: "permission denied".into(), + }, + ); + assert!(ui.channel_admin.pending.is_none()); + assert!(!ui.channel_admin.error.is_empty()); + assert_eq!(ui.channel_admin.dialog.as_ref().unwrap().id(), id); + assert!(prepare(&mut ui).is_some()); + receive( + &mut ui, + &NetEvent::ChannelState { + channel_id: id, + channel_name: "New room".into(), + kind: "voice".into(), + guild_id: None, + members: vec![], + voice_endpoint: String::new(), + }, + ); + assert!(ui.channel_admin.dialog.is_none()); + } + #[test] + fn rename_and_delete_require_submit_and_matching_ack_and_handle_disconnect() { + let mut ui = admin(); + open(&mut ui, "rename", "global"); + if let Some(Dialog::Rename { name, .. }) = &mut ui.channel_admin.dialog { + *name = "Renamed".into(); + } + assert!( + matches!(prepare(&mut ui),Some(NetCommand::ChannelEdit{channel_name,..}) if channel_name=="Renamed") + ); + receive( + &mut ui, + &NetEvent::ChannelEdited { + channel_id: "global".into(), + channel_name: "Renamed".into(), + }, + ); + assert!(ui.channel_admin.dialog.is_none()); + open(&mut ui, "delete", "global"); + assert!(ui.channel_admin.pending.is_none()); + assert_eq!(ui.channels.len(), 2); + assert!( + matches!(prepare(&mut ui),Some(NetCommand::ChannelDelete{channel_id}) if channel_id=="global") + ); + receive( + &mut ui, + &NetEvent::Disconnected { + reason: "fixture".into(), + will_retry: false, + }, + ); + assert!(!ui.node_admin); + assert!(ui.channel_admin.dialog.is_none()); + } + #[test] + fn invalid_names_and_timeout_do_not_mutate_channels_or_duplicate_requests() { + let mut ui = admin(); + open(&mut ui, "create", "text"); + assert!(prepare(&mut ui).is_none()); + if let Some(Dialog::Create { name, .. }) = &mut ui.channel_admin.dialog { + *name = "bad\nname".into(); + } + assert!(prepare(&mut ui).is_none()); + if let Some(Dialog::Create { name, .. }) = &mut ui.channel_admin.dialog { + *name = "Valid".into(); + } + assert!(prepare(&mut ui).is_some()); + ui.channel_admin.pending = Some(Instant::now() - Duration::from_secs(11)); + tick(&mut ui); + assert!(ui.channel_admin.pending.is_none()); + assert!(!ui.channel_admin.error.is_empty()); + assert_eq!(ui.channels.len(), 2); + } +} + +struct MenuAction { + text: String, + icon: &'static str, + action: &'static str, +} +struct Menu { + session_id: String, + context: String, + x: f32, + y: f32, + actions: Vec, +} +fn current_session(ui: &UiState) -> Option<&str> { + match &ui.conn { + ConnState::Connected { session_id, .. } => Some(session_id), + _ => None, + } +} +fn category_choices(ui: &UiState) -> Vec<(String, String)> { + let mut categories: Vec<_> = ui + .channels + .iter() + .filter(|channel| channel.kind == "category" && channel.guild_id.is_none()) + .collect(); + categories.sort_by_key(|channel| (channel.position, channel.name.clone(), channel.id.clone())); + categories + .into_iter() + .map(|channel| (channel.id.clone(), channel.name.clone())) + .collect() +} +fn create_in(ui: &mut UiState, kind: &str, context: &str) { + let parent = ui + .channels + .iter() + .find(|channel| channel.id == context && channel.guild_id.is_none()) + .and_then(|channel| { + if channel.kind == "category" { + Some(channel.id.clone()) + } else { + channel.parent_id.clone() + } + }); + open(ui, "create", kind); + if kind != "category" + && let Some(Dialog::Create { parent_id, .. }) = &mut ui.channel_admin.dialog + { + *parent_id = parent; + } +} +fn open_menu(ui: &mut UiState, server: bool, context: &str, x: f32, y: f32) { + let Some(session_id) = current_session(ui).map(str::to_owned) else { + return; + }; + if ui.active_guild_id.is_some() + || ui.browsing_dms + || ui.central_account.is_none() + || (!server && !allowed(ui)) + { + return; + } + let mut actions = Vec::new(); + let mut add = |text: &str, icon, action| { + actions.push(MenuAction { + text: super::i18n::text(text), + icon, + action, + }) + }; + if server { + if allowed(ui) && ui.node_settings_supported { + add("Server settings", "settings", "settings"); + } + add("Disconnect from server", "log-out", "disconnect"); + } else { + add("Create text channel", "hash", "text"); + add("Create voice room", "volume-2", "voice"); + if ui.channel_structure_supported { + add("Create category", "folder", "category"); + } + if ui.forum.supported { + add("Create forum", "messages-square", "forum"); + } + if ui + .channels + .iter() + .any(|channel| channel.id == context && channel.guild_id.is_none()) + { + add("Rename channel", "pencil", "rename"); + add("Delete channel", "trash-2", "delete"); + } + } + ui.channel_admin.menu = Some(Menu { + session_id, + context: context.to_owned(), + x, + y, + actions, + }); +} +fn wire_menus(window: &MainWindow, state: &Rc>) { + { + let state = state.clone(); + window.on_open_node_menu(move |x, y| open_menu(&mut state.borrow_mut().ui, true, "", x, y)); + } + { + let state = state.clone(); + window.on_open_channel_menu(move |id, x, y| { + open_menu(&mut state.borrow_mut().ui, false, id.as_str(), x, y) + }); + } + { + let state = state.clone(); + window.on_management_menu_close(move || { + state.borrow_mut().ui.channel_admin.menu = None; + }); + } + { + let state = state.clone(); + window.on_toggle_category(move |id| { + let mut state = state.borrow_mut(); + if state + .ui + .channels + .iter() + .any(|channel| channel.id == id.as_str() && channel.kind == "category") + && !state.ui.collapsed_categories.remove(id.as_str()) + { + state.ui.collapsed_categories.insert(id.to_string()); + } + }); + } + { + let state = state.clone(); + window.on_channel_admin_parent_selected(move |index| { + let mut state = state.borrow_mut(); + if state.ui.channel_admin.pending.is_some() { + return; + } + let parent = if index == 0 { + None + } else { + state + .ui + .channel_admin + .categories + .get(index.saturating_sub(1) as usize) + .map(|(id, _)| id.clone()) + }; + if let Some(Dialog::Create { + parent_id, kind, .. + }) = &mut state.ui.channel_admin.dialog + && kind != "category" + { + *parent_id = parent; + } + }); + } + { + let state = state.clone(); + let weak = window.as_weak(); + window.on_management_menu_chosen(move |action| { + let (command, net, disconnect) = { + let mut state = state.borrow_mut(); + let Some(menu) = state.ui.channel_admin.menu.take() else { + return; + }; + if current_session(&state.ui) != Some(menu.session_id.as_str()) + || !menu + .actions + .iter() + .any(|item| item.action == action.as_str()) + { + return; + } + let mut command = None; + let mut disconnect = false; + match action.as_str() { + "settings" => command = super::server_settings::open(&mut state.ui), + "disconnect" => disconnect = true, + "rename" | "delete" => open(&mut state.ui, action.as_str(), &menu.context), + kind => create_in(&mut state.ui, kind, &menu.context), + } + (command, state.net.clone(), disconnect) + }; + if let Some(command) = command { + tokio::spawn(async move { + net.send(command).await; + }); + } + if disconnect && let Some(window) = weak.upgrade() { + window.invoke_disconnect(); + } + }); + } +} + +/// Flatten one-level categories without turning containers into channel subscriptions. +pub fn sidebar_channels(ui: &UiState) -> Vec { + let mut visible: Vec<_> = ui + .channels + .iter() + .filter(|channel| match ui.active_guild_id.as_deref() { + None => channel.guild_id.is_none(), + Some(id) => channel.guild_id.is_none() || channel.guild_id.as_deref() == Some(id), + }) + .collect(); + visible.sort_by_key(|channel| (channel.position, channel.name.clone(), channel.id.clone())); + let categories: Vec<_> = visible + .iter() + .copied() + .filter(|channel| channel.kind == "category") + .collect(); + let mut result = Vec::new(); + let mut push = |channel: &crate::ui::state::Channel, indent| { + result.push(crate::ui::slint::ChannelItem { + channel_id: channel.id.as_str().into(), + name: channel.name.as_str().into(), + kind: channel.kind.as_str().into(), + is_global: channel.guild_id.is_none(), + indented: indent, + collapsed: ui.collapsed_categories.contains(&channel.id), + parent_id: channel.parent_id.as_deref().unwrap_or("").into(), + }) + }; + for channel in &visible { + if channel.kind != "category" + && (channel.parent_id.is_none() + || !categories + .iter() + .any(|parent| Some(parent.id.as_str()) == channel.parent_id.as_deref())) + { + push(channel, false); + } + } + for category in categories { + push(category, false); + if !ui.collapsed_categories.contains(&category.id) { + for channel in &visible { + if channel.parent_id.as_deref() == Some(category.id.as_str()) { + push(channel, true); + } + } + } + } + result +} diff --git a/src/ui/chat_images.rs b/src/ui/chat_images.rs new file mode 100644 index 0000000..e0f2058 --- /dev/null +++ b/src/ui/chat_images.rs @@ -0,0 +1,449 @@ +//! Bounded chat image decoding and public HTTPS image downloads. +//! +//! Decoding and clipboard reads belong on a blocking worker, never the UI thread. +use std::{io::Cursor, net::IpAddr, time::Duration}; + +use anyhow::{Context, Result, bail, ensure}; +use image::{AnimationDecoder, ImageDecoder, ImageEncoder, ImageFormat}; + +pub const MAX_ENCODED_BYTES: usize = 3 * 1024 * 1024; +pub const MAX_REMOTE_ENCODED_BYTES: usize = 16 * 1024 * 1024; +pub const MAX_RGBA_BYTES: usize = 64 * 1024 * 1024; +const MAX_SOURCE_PIXELS: u64 = 128 * 1024 * 1024; +const GIF_PREVIEW_SIDE: u32 = 384; +const MAX_PIXELS: u64 = 4 * 1024 * 1024; +const MAX_SIDE: u32 = 4096; +const MAX_FRAMES: usize = 120; + +#[derive(Debug)] +pub struct ImageFrame { + pub rgba: Vec, + pub delay_ms: u32, +} + +#[derive(Debug)] +pub struct DecodedImage { + pub width: u32, + pub height: u32, + pub frames: Vec, +} + +fn dimensions(width: u32, height: u32) -> Result<()> { + ensure!( + width > 0 + && height > 0 + && width <= MAX_SIDE + && height <= MAX_SIDE + && u64::from(width) * u64::from(height) <= MAX_PIXELS, + "Image dimensions exceed the 4096 px / 4 megapixel limit" + ); + Ok(()) +} + +fn limits() -> image::Limits { + let mut limits = image::Limits::default(); + limits.max_image_width = Some(MAX_SIDE); + limits.max_image_height = Some(MAX_SIDE); + limits.max_alloc = Some(64 * 1024 * 1024); + limits +} + +/// Decode supported raster formats, preserving composited GIF frames and timing. +pub fn decode(bytes: &[u8]) -> Result { + ensure!( + !bytes.is_empty() && bytes.len() <= MAX_REMOTE_ENCODED_BYTES, + "Image must be no larger than 16 MiB" + ); + let format = image::guess_format(bytes).context("Unsupported image")?; + ensure!( + matches!( + format, + ImageFormat::Png | ImageFormat::Jpeg | ImageFormat::WebP | ImageFormat::Gif + ), + "Use PNG, JPEG, WebP or GIF" + ); + let (mut width, mut height) = image::ImageReader::with_format(Cursor::new(bytes), format) + .into_dimensions() + .context("Invalid image header")?; + dimensions(width, height)?; + let mut frames = Vec::new(); + if format == ImageFormat::Gif { + let mut decoder = image::codecs::gif::GifDecoder::new(Cursor::new(bytes))?; + decoder.set_limits(limits())?; + let source_pixels = u64::from(width) * u64::from(height); + let longest = width.max(height); + if longest > GIF_PREVIEW_SIDE { + width = (width * GIF_PREVIEW_SIDE / longest).max(1); + height = (height * GIF_PREVIEW_SIDE / longest).max(1); + } + let frame_bytes = width as usize * height as usize * 4; + for frame in decoder.into_frames() { + ensure!( + frames.len() < MAX_FRAMES + && (frames.len() + 1) * frame_bytes <= MAX_RGBA_BYTES + && (frames.len() as u64 + 1) * source_pixels <= MAX_SOURCE_PIXELS, + "GIF exceeds the animation limit (120 frames / 64 MiB preview / 128 megapixels decoded)" + ); + let frame = frame.context("Invalid GIF frame")?; + let (numerator, denominator) = frame.delay().numer_denom_ms(); + let delay_ms = (numerator / denominator.max(1)).clamp(20, 10_000); + let original = frame.into_buffer(); + let buffer = if original.dimensions() == (width, height) { + original + } else { + image::imageops::resize( + &original, + width, + height, + image::imageops::FilterType::Triangle, + ) + }; + frames.push(ImageFrame { + rgba: buffer.into_raw(), + delay_ms, + }); + } + ensure!(!frames.is_empty(), "GIF has no frames"); + } else { + let mut reader = image::ImageReader::with_format(Cursor::new(bytes), format); + reader.limits(limits()); + let image = reader.decode().context("Invalid image data")?.into_rgba8(); + frames.push(ImageFrame { + rgba: image.into_raw(), + delay_ms: 100, + }); + } + Ok(DecodedImage { + width, + height, + frames, + }) +} + +/// Extract one direct HTTPS raster-image URL from ordinary message text. +pub fn image_url(body: &str) -> Option { + body.split_whitespace().find_map(|token| { + let token = token.trim_matches(|c: char| { + matches!( + c, + '<' | '>' | '"' | '\'' | '(' | ')' | '[' | ']' | ',' | ';' + ) + }); + let url = reqwest::Url::parse(token).ok()?; + validate_url(&url).ok()?; + let path = url.path().to_ascii_lowercase(); + [".png", ".jpg", ".jpeg", ".webp", ".gif"] + .iter() + .any(|ext| path.ends_with(ext)) + .then(|| url.to_string()) + }) +} + +fn validate_url(url: &reqwest::Url) -> Result<()> { + ensure!( + url.scheme() == "https" + && url.host_str().is_some() + && url.port_or_known_default() == Some(443) + && url.username().is_empty() + && url.password().is_none(), + "Only public HTTPS image URLs on port 443 are allowed" + ); + if let Ok(address) = url + .host_str() + .unwrap_or_default() + .trim_matches(['[', ']']) + .parse::() + { + ensure!( + public_ip(address), + "Private or reserved image address is blocked" + ); + } + Ok(()) +} + +fn public_ip(address: IpAddr) -> bool { + match address { + IpAddr::V4(ip) => { + let [a, b, c, _] = ip.octets(); + !(a == 0 + || a == 10 + || a == 127 + || a >= 224 + || (a == 100 && (64..=127).contains(&b)) + || (a == 169 && b == 254) + || (a == 172 && (16..=31).contains(&b)) + || (a == 192 && (b == 168 || b == 0 || (b == 88 && c == 99))) + || (a == 198 && (b == 18 || b == 19 || (b == 51 && c == 100))) + || (a == 203 && b == 0 && c == 113)) + } + IpAddr::V6(ip) => { + let s = ip.segments(); + // Only native global-unicast addresses; exclude special-purpose, + // documentation, NAT64 and transition networks conservatively. + (s[0] & 0xe000) == 0x2000 + && !(s[0] == 0x2001 && (s[1] < 0x0200 || s[1] == 0x0db8)) + && s[0] != 0x2002 + && !(s[0] == 0x3fff && s[1] < 0x1000) + } + } +} + +/// Download without ambient proxies, cookies or credentials. Every redirect is +/// revalidated and resolved once, then the verified addresses are pinned for TLS. +pub async fn fetch(url: &str) -> Result> { + tokio::time::timeout(Duration::from_secs(30), fetch_inner(url)) + .await + .context("Image download timed out")? +} + +async fn fetch_inner(url: &str) -> Result> { + let mut url = reqwest::Url::parse(url).context("Invalid image URL")?; + for redirect in 0..=3 { + validate_url(&url)?; + let host = url + .host_str() + .context("Image URL has no hostname")? + .trim_matches(['[', ']']); + let addresses: Vec<_> = + tokio::time::timeout(Duration::from_secs(5), tokio::net::lookup_host((host, 443))) + .await + .context("Image DNS lookup timed out")?? + .collect(); + ensure!( + !addresses.is_empty() + && addresses.len() <= 32 + && addresses.iter().all(|a| public_ip(a.ip())), + "Private or reserved image address is blocked" + ); + let client = reqwest::Client::builder() + .no_proxy() + .redirect(reqwest::redirect::Policy::none()) + .connect_timeout(Duration::from_secs(5)) + .timeout(Duration::from_secs(15)) + .resolve_to_addrs(host, &addresses) + .build()?; + let mut response = client + .get(url.clone()) + .header( + reqwest::header::ACCEPT, + "image/png,image/jpeg,image/webp,image/gif", + ) + .send() + .await?; + if response.status().is_redirection() { + ensure!(redirect < 3, "Too many image redirects"); + let location = response + .headers() + .get(reqwest::header::LOCATION) + .context("Image redirect has no location")? + .to_str()?; + url = url.join(location).context("Invalid image redirect")?; + continue; + } + ensure!( + response.status().is_success(), + "Image server returned {}", + response.status() + ); + ensure!( + response + .content_length() + .is_none_or(|length| length <= MAX_REMOTE_ENCODED_BYTES as u64), + "Image exceeds 16 MiB" + ); + let mut bytes = Vec::new(); + while let Some(chunk) = response.chunk().await? { + ensure!( + bytes.len().saturating_add(chunk.len()) <= MAX_REMOTE_ENCODED_BYTES, + "Image exceeds 16 MiB" + ); + bytes.extend_from_slice(&chunk); + } + ensure!(!bytes.is_empty(), "Image response is empty"); + return Ok(bytes); + } + bail!("Too many image redirects") +} + +/// Read an explicitly requested native clipboard image. This can block on the +/// clipboard owner; prefer a worker even when PNG encoding is split off. +pub fn clipboard_image() -> Result> { + let mut clipboard = arboard::Clipboard::new().context("Cannot open clipboard")?; + let image = clipboard.get_image().context("Clipboard has no image")?; + // Validation belongs to the preview worker so image errors are shown instead of + // falling through to ordinary text paste. + Ok(image) +} + +/// Encode a native clipboard image on a blocking worker for a preview draft. +pub fn encode_clipboard_png(image: arboard::ImageData<'_>) -> Result> { + let width = u32::try_from(image.width)?; + let height = u32::try_from(image.height)?; + dimensions(width, height)?; + ensure!( + image.bytes.len() == width as usize * height as usize * 4, + "Invalid clipboard image data" + ); + let mut bytes = Vec::new(); + image::codecs::png::PngEncoder::new(&mut bytes).write_image( + &image.bytes, + width, + height, + image::ExtendedColorType::Rgba8, + )?; + ensure!( + bytes.len() <= MAX_ENCODED_BYTES, + "Clipboard image exceeds 3 MiB; choose a smaller image" + ); + Ok(bytes) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn extracts_https_images_without_treating_paths_as_urls() { + assert_eq!( + image_url("look https://example.org/cat.GIF?x=1"), + Some("https://example.org/cat.GIF?x=1".into()) + ); + for body in [ + "file:///tmp/cat.png", + "/tmp/cat.png", + "http://example.org/a.png", + "https://example.org/page", + "https://user:secret@example.org/a.png", + "https://127.0.0.1/a.png", + ] { + assert!(image_url(body).is_none(), "{body}"); + } + } + + #[test] + fn blocks_private_reserved_and_transition_addresses() { + for address in [ + "0.0.0.0", + "10.0.0.1", + "100.64.0.1", + "127.0.0.1", + "169.254.169.254", + "172.16.1.1", + "192.168.0.1", + "192.0.2.1", + "198.18.0.1", + "198.51.100.1", + "203.0.113.1", + "224.0.0.1", + "240.0.0.1", + "::1", + "::ffff:8.8.8.8", + "fc00::1", + "fe80::1", + "2001:db8::1", + "2002:7f00:1::", + "3fff::1", + ] { + assert!(!public_ip(address.parse().unwrap()), "{address}"); + } + for address in [ + "8.8.8.8", + "1.1.1.1", + "2606:4700:4700::1111", + "2001:4860:4860::8888", + ] { + assert!(public_ip(address.parse().unwrap()), "{address}"); + } + } + + #[test] + fn validates_url_scheme_port_and_credentials() { + for url in [ + "http://example.org/a.png", + "https://example.org:8080/a.png", + "https://a:b@example.org/a.png", + "https://[::1]/a.gif", + ] { + assert!(validate_url(&reqwest::Url::parse(url).unwrap()).is_err()); + } + } + + #[test] + fn decodes_png_and_preserves_rgba() { + let mut png = Vec::new(); + image::codecs::png::PngEncoder::new(&mut png) + .write_image(&[1, 2, 3, 255], 1, 1, image::ExtendedColorType::Rgba8) + .unwrap(); + let decoded = decode(&png).unwrap(); + assert_eq!((decoded.width, decoded.height), (1, 1)); + assert_eq!(decoded.frames[0].rgba, [1, 2, 3, 255]); + } + + #[test] + fn rejects_oversized_encoded_data_and_dimensions() { + assert!(decode(&vec![0; MAX_REMOTE_ENCODED_BYTES + 1]).is_err()); + assert!(dimensions(4097, 1).is_err()); + assert!(dimensions(4096, 4096).is_err()); + assert!(dimensions(0, 1).is_err()); + } + + fn gif(frame_count: usize) -> Vec { + let mut bytes = Vec::new(); + { + let mut encoder = image::codecs::gif::GifEncoder::new(&mut bytes); + for i in 0..frame_count { + let buffer = image::RgbaImage::from_pixel(2, 2, image::Rgba([i as u8, 0, 0, 255])); + encoder + .encode_frame(image::Frame::from_parts( + buffer, + 0, + 0, + image::Delay::from_numer_denom_ms(50, 1), + )) + .unwrap(); + } + } + bytes + } + + #[test] + fn retains_animated_gif_frames_and_delay() { + let decoded = decode(&gif(2)).unwrap(); + assert_eq!(decoded.frames.len(), 2); + assert_eq!(decoded.frames[1].rgba[0], 1); + assert_eq!(decoded.frames[0].delay_ms, 50); + } + + #[test] + fn bounds_gif_preview_dimensions_without_dropping_frames() { + let mut bytes = Vec::new(); + { + let mut encoder = image::codecs::gif::GifEncoder::new(&mut bytes); + for _ in 0..2 { + encoder + .encode_frame(image::Frame::new(image::RgbaImage::new(400, 100))) + .unwrap(); + } + } + let decoded = decode(&bytes).unwrap(); + assert_eq!((decoded.width, decoded.height), (384, 96)); + assert_eq!(decoded.frames.len(), 2); + assert_eq!(decoded.frames[0].rgba.len(), 384 * 96 * 4); + } + + #[test] + fn clipboard_encoding_validates_raw_size() { + let image = arboard::ImageData { + width: 2, + height: 2, + bytes: std::borrow::Cow::Owned(vec![0; 3]), + }; + assert!(encode_clipboard_png(image).is_err()); + } + + #[test] + fn rejects_excessive_animation_frames() { + assert!(decode(&gif(MAX_FRAMES + 1)).is_err()); + } +} diff --git a/src/ui/chat_media.rs b/src/ui/chat_media.rs new file mode 100644 index 0000000..95887e1 --- /dev/null +++ b/src/ui/chat_media.rs @@ -0,0 +1,470 @@ +//! Native chat image presentation. Network/decode work runs away from the event loop. +use super::{chat_images, slint::MainWindow}; +use slint::{ComponentHandle, Model, SharedPixelBuffer}; +use std::{cell::RefCell, collections::HashMap, rc::Rc, sync::mpsc, time::Instant}; +use vnox_client::net::NetCommand; + +struct Animation { + frames: Vec<(slint::Image, u32)>, + ratio: f32, + started: Instant, + bytes: usize, +} +impl Animation { + fn new(image: chat_images::DecodedImage) -> Self { + let bytes = image.frames.iter().map(|f| f.rgba.len()).sum(); + Self { + frames: image + .frames + .into_iter() + .map(|f| { + ( + slint::Image::from_rgba8(SharedPixelBuffer::clone_from_slice( + &f.rgba, + image.width, + image.height, + )), + f.delay_ms.max(20), + ) + }) + .collect(), + ratio: image.width as f32 / image.height as f32, + started: Instant::now(), + bytes, + } + } + fn frame(&self) -> slint::Image { + let duration: u128 = self.frames.iter().map(|f| u128::from(f.1)).sum(); + let mut position = self.started.elapsed().as_millis() % duration.max(1); + for (image, delay) in &self.frames { + if position < u128::from(*delay) { + return image.clone(); + } + position -= u128::from(*delay); + } + self.frames[0].0.clone() + } +} +struct Entry { + image: Option, + error: String, + started: Instant, +} +struct Ready { + key: String, + result: Result, + clipboard: Option>, +} +struct Pending { + bytes: Vec, + image: Animation, + channel: String, + generation: u64, + request: Option, + started: Instant, +} +struct Media { + cache: HashMap, + tx: mpsc::Sender, + rx: mpsc::Receiver, + pending: Option, + clipboard_key: Option, + generation: u64, + workers: usize, +} +impl Default for Media { + fn default() -> Self { + let (tx, rx) = mpsc::channel(); + Self { + cache: HashMap::new(), + tx, + rx, + pending: None, + clipboard_key: None, + generation: 0, + workers: 0, + } + } +} +thread_local! { static MEDIA: RefCell = RefCell::new(Media::default()); } + +pub fn wire(window: &MainWindow, state: &Rc>) { + let weak = window.as_weak(); + let paste_state = state.clone(); + window.on_paste_image(move || { + let Some(win)=weak.upgrade() else { return false }; + let s=paste_state.borrow(); + // A failed image lookup must leave normal text paste to TextInput. + let Ok(clipboard)=chat_images::clipboard_image() else { return false }; + if MEDIA.with(|m| {let m=m.borrow();m.workers+m.cache.iter().filter(|(key,entry)|key.starts_with("attachment:") && entry.error=="Loading image…").count()>=3 || m.pending.as_ref().is_some_and(|p|p.request.is_some())}) {win.set_image_status("Wait for the current image operation to finish.".into());return true;} + if s.ui.active_dm_id.is_some() || s.ui.active_channel.is_none() { win.set_image_status("Image attachments are available in channels. You can send an HTTPS image link here.".into()); return true; } + let channel=s.ui.active_channel.clone().unwrap_or_default(); let generation=s.connection_generation; + MEDIA.with(|m| { let mut m=m.borrow_mut(); if m.pending.as_ref().is_some_and(|p|p.request.is_some()) {return} let tx=m.tx.clone(); m.workers+=1;let clipboard_key=format!("clipboard:{generation}:{channel}:{}",uuid::Uuid::new_v4());m.clipboard_key=Some(clipboard_key.clone()); + tokio::task::spawn_blocking(move || { let result=chat_images::encode_clipboard_png(clipboard).and_then(|bytes|chat_images::decode(&bytes).map(|image|(bytes,image))); match result {Ok((bytes,image))=>{let _=tx.send(Ready {key:clipboard_key,result:Ok(image),clipboard:Some(bytes)});},Err(error)=>{let _=tx.send(Ready {key:clipboard_key,result:Err(error.to_string()),clipboard:Some(Vec::new())});}} }); + }); + win.set_image_status("Preparing image…".into()); true + }); + let weak = window.as_weak(); + window.on_cancel_image(move || { + let cancelled = MEDIA.with(|m| { + let mut m = m.borrow_mut(); + if m.pending.as_ref().is_some_and(|p| p.request.is_some()) { + return false; + } + m.pending = None; + m.clipboard_key = None; + true + }); + if !cancelled { + return; + } + if let Some(w) = weak.upgrade() { + w.set_has_pending_image(false); + w.set_image_status("".into()); + } + }); + let state = state.clone(); + let weak = window.as_weak(); + window.on_send_image(move || { + let s = state.borrow(); + let net = s.net.clone(); + MEDIA.with(|m| { + let mut m = m.borrow_mut(); + let Some(p) = m.pending.as_mut() else { return }; + if p.request.is_some() { + return; + } + if p.generation != s.connection_generation + || s.ui.active_dm_id.is_some() + || s.ui.active_channel.as_deref() != Some(&p.channel) + || !matches!(s.ui.conn, super::state::ConnState::Connected { .. }) + { + if let Some(w) = weak.upgrade() { + w.set_image_status( + "Select the original channel and connect before sending this image.".into(), + ); + } + return; + } + let request_id = uuid::Uuid::new_v4().to_string(); + p.request = Some(request_id.clone()); + p.started = Instant::now(); + let channel_id = p.channel.clone(); + let data = p.bytes.clone(); + tokio::spawn(async move { + net.send(NetCommand::AttachmentUpload { + request_id, + channel_id, + data, + }) + .await; + }); + if let Some(w) = weak.upgrade() { + w.set_image_uploading(true); + w.set_image_status("Sending image…".into()); + } + }); + }); +} + +pub fn receive(result: vnox_client::net::wire::AttachmentResult) { + MEDIA.with(|m| { + let mut m = m.borrow_mut(); + if let Some(p) = m.pending.as_mut() + && p.request.as_deref() == Some(&result.request_id) + { + if result.error.is_empty() { + m.pending = None; + } else { + p.request = None; + } + // Display delivery state on the next UI tick. + let _ = m.tx.send(Ready { + key: "upload-status".into(), + result: Err(if result.error.is_empty() { + String::new() + } else { + result.error + }), + clipboard: None, + }); + return; + } + let key = result.request_id; + let expected = format!( + "attachment:{}:{}:{}", + m.generation, result.channel_id, result.attachment_id + ); + if key != expected + || !m + .cache + .get(&key) + .is_some_and(|entry| entry.error == "Loading image…") + { + return; + } + + if !result.error.is_empty() { + if let Some(e) = m.cache.get_mut(&key) { + e.error = result.error; + } + return; + } + if let Some(entry) = m.cache.get_mut(&key) { + entry.error = "Decoding image…".into(); + } + let tx = m.tx.clone(); + m.workers += 1; + tokio::task::spawn_blocking(move || { + let decoded = chat_images::decode(&result.data).map_err(|e| e.to_string()); + let _ = tx.send(Ready { + key, + result: decoded, + clipboard: None, + }); + }); + }); +} + +pub fn tick(window: &MainWindow, state: &crate::AppState) { + MEDIA.with(|m| { + let mut m = m.borrow_mut(); + if m.generation != state.connection_generation { + m.cache.clear(); + m.pending = None; + m.clipboard_key = None; + m.generation = state.connection_generation; + window.set_has_pending_image(false); + window.set_image_uploading(false); + window.set_image_status("".into()); + } + let visible_model = if window.get_show_forum() {window.get_forum_replies()} else {window.get_messages()}; + let visible: Vec = visible_model.iter() + .filter_map(|item| source_key(&item.media_source, state)) + .collect(); + m.cache.retain(|key, _| visible.contains(key)); + while let Ok(ready) = m.rx.try_recv() { + if ready.key == "upload-status" { + window.set_image_uploading(false); + window.set_image_status(ready.result.err().unwrap_or_default().into()); + window.set_has_pending_image(m.pending.is_some()); + continue; + } + m.workers = m.workers.saturating_sub(1); + if let Some(bytes) = ready.clipboard { + let expected = format!( + "clipboard:{}:{}", + state.connection_generation, + state.ui.active_channel.as_deref().unwrap_or("") + ); + if m.clipboard_key.as_deref() != Some(&ready.key) + || !ready.key.starts_with(&format!("{expected}:")) + || state.ui.active_dm_id.is_some() + { + continue; + } + m.clipboard_key = None; + match ready.result { + Ok(image) => { + let image = Animation::new(image); + window.set_pending_image(image.frame()); + window.set_has_pending_image(true); + window.set_image_status( + "Image ready. Send it to this channel or cancel.".into(), + ); + m.pending = Some(Pending { + bytes, + image, + channel: state.ui.active_channel.clone().unwrap_or_default(), + generation: state.connection_generation, + request: None, + started: Instant::now(), + }); + } + Err(e) => window.set_image_status(format!("Cannot paste image: {e}").into()), + } + continue; + } + if !m.cache.contains_key(&ready.key) { + continue; + } + match ready.result { + Ok(image) => { + let image = Animation::new(image); + let total: usize = m + .cache + .values() + .filter_map(|e| e.image.as_ref()) + .map(|a| a.bytes) + .sum(); + if total + image.bytes > 64 * 1024 * 1024 { + m.cache.insert( + ready.key, + Entry { + image: None, + error: + "Preview cache is full. Open another channel to release images." + .into(), + started: Instant::now(), + }, + ); + continue; + } + m.cache.insert( + ready.key, + Entry { + image: Some(image), + error: String::new(), + started: Instant::now(), + }, + ); + } + Err(e) => { + m.cache.insert( + ready.key, + Entry { + image: None, + error: format!("Image unavailable: {e}"), + started: Instant::now(), + }, + ); + } + } + } + if let Some(p) = m.pending.as_mut() { + if p.request.is_some() && p.started.elapsed().as_secs() > 35 { + p.request = None; + window.set_image_uploading(false); + window.set_image_status( + "Image delivery could not be confirmed. Check the channel before retrying." + .into(), + ); + } + window.set_pending_image(p.image.frame()); + } + for entry in m.cache.values_mut() { + if entry.image.is_none() + && entry.error == "Loading image…" + && entry.started.elapsed().as_secs() > 35 + { + entry.error = "Image request timed out".into(); + } + } + let pending_fetches = m + .cache + .iter() + .filter(|(k, e)| { + k.starts_with("attachment:") && e.image.is_none() && e.error == "Loading image…" + }) + .count(); + let model = if window.get_show_forum() {window.get_forum_replies()} else {window.get_messages()}; + let mut slots = 3usize.saturating_sub(m.workers + pending_fetches); + for row in 0..model.row_count() { + let Some(mut item) = model.row_data(row) else { + continue; + }; + let previous = item.clone(); + let body = item.media_source.to_string(); + let source = body.as_str(); + let attachment = if window.get_show_forum() { None } else { source + .strip_prefix("vnox-attachment:") + .filter(|id| uuid::Uuid::parse_str(id).is_ok()) }; + let remote = chat_images::image_url(source); + let key = if let Some(id) = attachment { + format!( + "attachment:{}:{}:{}", + state.connection_generation, + state.ui.active_channel.as_deref().unwrap_or(""), + id + ) + } else if let Some(url) = &remote { + format!("url:{url}") + } else { + continue; + }; + if !m.cache.contains_key(&key) && slots > 0 && m.cache.len() < 24 { + slots -= 1; + m.cache.insert( + key.clone(), + Entry { + image: None, + error: "Loading image…".into(), + started: Instant::now(), + }, + ); + if let Some(attachment_id) = attachment { + let net = state.net.clone(); + let channel_id = state.ui.active_channel.clone().unwrap_or_default(); + let attachment_id = attachment_id.to_string(); + let request_id = key.clone(); + tokio::spawn(async move { + net.send(NetCommand::AttachmentFetch { + request_id, + channel_id, + attachment_id, + }) + .await; + }); + } else if let Some(url) = remote { + m.workers += 1; + let tx = m.tx.clone(); + let request = key.clone(); + tokio::spawn(async move { + let result = async { + let bytes = chat_images::fetch(&url).await?; + tokio::task::spawn_blocking(move || chat_images::decode(&bytes)).await? + } + .await + .map_err(|e: anyhow::Error| e.to_string()); + let _ = tx.send(Ready { + key: request, + result, + clipboard: None, + }); + }); + } + } + item.media_ready = false; + item.media_image = Default::default(); + item.media_status = "Image queue is full".into(); + if let Some(entry) = m.cache.get(&key) { + if let Some(image) = &entry.image { + item.media_image = image.frame(); + item.media_ready = true; + item.media_ratio = image.ratio; + item.media_status = "".into(); + } else { + item.media_status = entry.error.as_str().into(); + } + } + if attachment.is_some() { + item.content = "".into(); + } + if item.media_ready != previous.media_ready + || item.media_image != previous.media_image + || item.media_status != previous.media_status + || item.media_ratio != previous.media_ratio + || item.content != previous.content + { + model.set_row_data(row, item); + } + } + }); +} + +fn source_key(source: &str, state: &crate::AppState) -> Option { + if super::forum::visible(&state.ui) && source.starts_with("vnox-attachment:") { return None; } + if let Some(id) = source + .strip_prefix("vnox-attachment:") + .filter(|id| uuid::Uuid::parse_str(id).is_ok()) + { + Some(format!( + "attachment:{}:{}:{}", + state.connection_generation, + state.ui.active_channel.as_deref().unwrap_or(""), + id + )) + } else { + chat_images::image_url(source).map(|url| format!("url:{url}")) + } +} diff --git a/src/ui/connection.rs b/src/ui/connection.rs new file mode 100644 index 0000000..c4b3ff3 --- /dev/null +++ b/src/ui/connection.rs @@ -0,0 +1,187 @@ +//! Successful server preference and account-gated restoration. Contains no credentials. +use super::state::ConnState; +use crate::{AppState, net::NetCommand}; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(default)] +pub struct Preferences { + last_server: Option, + auto_reconnect: bool, + manually_disconnected: bool, + #[serde(skip)] + pending: Option, + #[serde(skip)] + pub authentication_required: bool, +} +impl Default for Preferences { + fn default() -> Self { + Self { + last_server: None, + auto_reconnect: true, + manually_disconnected: false, + pending: None, + authentication_required: false, + } + } +} +impl Preferences { + fn restore_target(&self, authenticated: bool) -> Option { + (authenticated && self.auto_reconnect && !self.manually_disconnected) + .then(|| self.last_server.clone()) + .flatten() + } + fn successful(&mut self) { + if let Some(address) = self.pending.take() { + self.last_server = Some(address); + self.manually_disconnected = false; + } + } +} +fn path() -> std::path::PathBuf { + dirs::config_dir() + .unwrap_or_else(|| ".".into()) + .join("vnox/connection.json") +} +pub fn load(ui: &mut super::state::UiState) { + ui.connection = std::fs::read(path()) + .ok() + .and_then(|bytes| serde_json::from_slice::(&bytes).ok()) + .unwrap_or_default(); + // Never let an edited/corrupted file bypass the same target parser as transport. + ui.connection.last_server = ui + .connection + .last_server + .as_deref() + .and_then(|address| crate::net::trust::parse_address(address).ok()) + .map(|a| a.key); + ui.auto_reconnect = ui.connection.auto_reconnect; + if let Some(address) = &ui.connection.last_server { + ui.connect_input = address.clone(); + } +} +fn save(ui: &super::state::UiState) { + let result = (|| -> anyhow::Result<()> { + let path = path(); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + let mut prefs = ui.connection.clone(); + prefs.auto_reconnect = ui.auto_reconnect; + let temporary = path.with_extension("json.tmp"); + std::fs::write(&temporary, serde_json::to_vec_pretty(&prefs)?)?; + std::fs::rename(temporary, path)?; + Ok(()) + })(); + if let Err(error) = result { + tracing::warn!(%error, "could not save connection preferences"); + } +} +pub fn set_auto_reconnect(state: &mut AppState, value: bool) { + state.ui.auto_reconnect = value; + state.ui.connection.auto_reconnect = value; + save(&state.ui); +} +pub fn disconnect(state: &mut AppState) { + state.ui.connection.manually_disconnected = true; + state.ui.connection.pending = None; + save(&state.ui); +} +pub fn connected(state: &mut AppState) { + state.ui.connection.successful(); + save(&state.ui); +} +pub fn restore(state: &mut AppState, authenticated: bool) { + if !matches!(state.ui.conn, ConnState::Disconnected) { + return; + } + if let Some(address) = state.ui.connection.restore_target(authenticated) { + connect(state, address); + } +} +pub fn connect(state: &mut AppState, address: String) { + let address = match crate::net::trust::parse_address(&address) { + Ok(address) => address.key, + Err(error) => { + state.ui.status_msg = Some(error.to_string().into()); + return; + } + }; + state.ui.connection.pending = Some(address.clone()); + state.ui.connection.authentication_required = false; + state.ui.conn = ConnState::Connecting; + state.ui.connect_input = address.clone(); + state.ui.status_msg = Some("Connecting…".into()); + let auto_reconnect = state.ui.auto_reconnect; + let net = state.net.clone(); + tokio::spawn(async move { + net.send(NetCommand::Connect { + address, + auto_reconnect, + }) + .await; + }); +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn restoration_requires_account_and_auto_reconnect_and_no_manual_leave() { + let mut p = Preferences { + last_server: Some("example.org:7600".into()), + ..Default::default() + }; + assert!(p.restore_target(false).is_none()); + assert_eq!(p.restore_target(true).as_deref(), Some("example.org:7600")); + p.auto_reconnect = false; + assert!(p.restore_target(true).is_none()); + p.auto_reconnect = true; + p.manually_disconnected = true; + assert!(p.restore_target(true).is_none()); + } + #[test] + fn only_successful_address_survives_serialization() { + let mut p = Preferences { + last_server: Some("old.example:7600".into()), + pending: Some("new.example:7600".into()), + ..Default::default() + }; + let loaded: Preferences = serde_json::from_slice(&serde_json::to_vec(&p).unwrap()).unwrap(); + assert_eq!(loaded.last_server.as_deref(), Some("old.example:7600")); + assert!(loaded.pending.is_none()); + p.successful(); + let loaded: Preferences = serde_json::from_slice(&serde_json::to_vec(&p).unwrap()).unwrap(); + assert_eq!(loaded.last_server.as_deref(), Some("new.example:7600")); + } + #[test] + fn successful_target_uses_transport_normalization() { + assert_eq!( + crate::net::trust::parse_address("lnexs://Example.ORG") + .unwrap() + .key, + "example.org:7600" + ); + assert_eq!( + crate::net::trust::parse_address("[::1]").unwrap().key, + "[::1]:7600" + ); + assert!(crate::net::trust::parse_address("example.org:invalid").is_err()); + } + #[test] + fn manual_leave_survives_restart_and_failed_attempt() { + let mut p = Preferences { + last_server: Some("example.org:7600".into()), + manually_disconnected: true, + pending: Some("failed.example:7600".into()), + ..Default::default() + }; + let loaded: Preferences = serde_json::from_slice(&serde_json::to_vec(&p).unwrap()).unwrap(); + assert!(loaded.restore_target(true).is_none()); + p.successful(); + assert_eq!( + p.restore_target(true).as_deref(), + Some("failed.example:7600") + ); + } +} diff --git a/src/ui/devices.rs b/src/ui/devices.rs index 7661d62..d05509b 100644 --- a/src/ui/devices.rs +++ b/src/ui/devices.rs @@ -2,6 +2,47 @@ use vnox_client::audio::devices::{self, filter}; use super::state::UiState; +use std::sync::mpsc::{self, Receiver, TryRecvError}; +use vnox_client::audio::DeviceLists; + +/// One in-flight enumeration. Only owned device descriptions cross the thread boundary. +#[derive(Default)] +pub struct DeviceRefresh { + pending: Option>>, +} + +impl DeviceRefresh { + /// Starts an enumeration unless the previous request is still pending. + pub fn request(&mut self) { + self.start(devices::enumerate); + } + + fn start(&mut self, enumerate: impl FnOnce() -> anyhow::Result + Send + 'static) { + if self.pending.is_some() { + return; + } + let (sender, receiver) = mpsc::channel(); + match std::thread::Builder::new() + .name("audio-device-refresh".into()) + .spawn(move || { + let _ = sender.send(enumerate()); + }) { + Ok(_) => self.pending = Some(receiver), + Err(error) => tracing::warn!(%error, "cannot start audio device refresh"), + } + } + + /// Polls without waiting. Errors keep the last usable list and allow another request. + pub fn take_ready(&mut self) -> Option> { + let result = match self.pending.as_ref()?.try_recv() { + Ok(result) => result, + Err(TryRecvError::Empty) => return None, + Err(TryRecvError::Disconnected) => Err(anyhow::anyhow!("audio device worker stopped")), + }; + self.pending = None; + Some(result) + } +} /// Recomputes the picker positions from the persisted ids and the last enumeration. pub fn sync_indexes(ui: &mut UiState) { @@ -9,12 +50,9 @@ pub fn sync_indexes(ui: &mut UiState) { ui.output_device = filter::index_for_id(&ui.device_lists.output, &ui.output_device_id); } -/// Enumerates devices again (hardware may have changed) and keeps the saved choices. -pub fn refresh(ui: &mut UiState) { - match devices::enumerate() { - Ok(lists) => ui.device_lists = lists, - Err(error) => tracing::warn!(%error, "cannot enumerate audio devices"), - } +/// Applies a finished enumeration using the current selection, not a worker snapshot. +pub fn apply_refresh(ui: &mut UiState, lists: DeviceLists) { + ui.device_lists = lists; sync_indexes(ui); } @@ -66,4 +104,53 @@ mod tests { sync_indexes(&mut ui); assert_eq!(ui.mic_device, 0); } + + #[test] + fn slow_refresh_is_nonblocking_and_coalesces_requests() { + let mut refresh = DeviceRefresh::default(); + let (release, wait) = std::sync::mpsc::channel(); + refresh.start(move || { + wait.recv().unwrap(); + Ok(state().device_lists) + }); + assert!(refresh.take_ready().is_none()); + refresh.start(|| panic!("a second enumeration must not start")); + release.send(()).unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + let lists = loop { + if let Some(result) = refresh.take_ready() { + break result.unwrap(); + } + assert!(std::time::Instant::now() < deadline); + std::thread::yield_now(); + }; + assert_eq!(lists.input[1].id, "b"); + assert!(refresh.pending.is_none()); + } + + #[test] + fn failed_refresh_can_be_retried() { + let mut refresh = DeviceRefresh::default(); + let (sender, receiver) = std::sync::mpsc::channel(); + sender.send(Err(anyhow::anyhow!("unavailable"))).unwrap(); + refresh.pending = Some(receiver); + assert!(refresh.take_ready().unwrap().is_err()); + assert!(refresh.pending.is_none()); + refresh.start(|| Ok(DeviceLists::default())); + assert!(refresh.pending.is_some()); + } + + #[test] + fn applying_refresh_uses_the_latest_device_selection() { + let mut ui = state(); + select(&mut ui, 1, 1); + // The person changes the picker while enumeration is still running. + select(&mut ui, 2, 0); + let mut lists = state().device_lists; + lists.input.reverse(); + apply_refresh(&mut ui, lists); + assert_eq!(ui.mic_device_id, "b"); + assert_eq!(ui.mic_device, 1); + assert_eq!(ui.output_device, 0); + } } diff --git a/src/ui/forum/mod.rs b/src/ui/forum/mod.rs new file mode 100644 index 0000000..4b9477d --- /dev/null +++ b/src/ui/forum/mod.rs @@ -0,0 +1,126 @@ +//! Separate forum threads; all data and mutation acknowledgements come from Gateway. +mod state; +pub use state::ForumState; +use crate::{AppState, net::{NetCommand, NetEvent, NetHandle, wire}}; +use super::{slint::{MainWindow, ForumTopicItem, MessageItem}, state::{ConnState, UiState}}; +use slint::{Model, ModelRc, SharedString, VecModel}; +use std::{cell::RefCell, rc::Rc}; + +fn session(ui: &UiState) -> Option { + if ui.connection.authentication_required { return None; } + match &ui.conn { ConnState::Connected { session_id, .. } => Some(session_id.clone()), _ => None } +} +fn send(ui: &UiState, net: &NetHandle, command: NetCommand) { + let Some(session_id) = session(ui) else { return; }; + let net = net.clone(); tokio::spawn(async move { net.send(NetCommand::ForSession { session_id, command: Box::new(command) }).await; }); +} +fn request(ui: &mut UiState, net: &NetHandle, operation: wire::ForumOperation, offset: u32) { + if session(ui).is_none() || !visible(ui) { return; } + if let Some(request) = ui.forum.request(operation, offset) { send(ui, net, NetCommand::ForumRequest(request)); } +} +pub fn visible(ui: &UiState) -> bool { + !ui.browsing_dms && !ui.showing_voice && ui.active_channel.as_ref().is_some_and(|id| + ui.channels.iter().any(|channel| &channel.id == id && channel.kind == "forum" && channel.guild_id == ui.active_guild_id)) +} +/// Selection never touches voice membership, credentials, audio devices or capture. +pub fn select(state: &mut AppState, id: &str) { + let channel_exists = state.ui.channels.iter().any(|channel| channel.id == id && channel.kind == "forum" && channel.guild_id == state.ui.active_guild_id); + if !channel_exists || session(&state.ui).is_none() { return; } + state.ui.select_text_channel(id.to_owned()); + if !state.ui.forum.supported { + state.ui.forum.channel_id = Some(id.to_owned()); + state.ui.forum.error = super::i18n::text("This server does not support forums yet."); return; + } + if state.ui.forum.channel_id.as_deref() == Some(id) && state.ui.forum.pending() { return; } + state.ui.forum.select(id); + send(&state.ui, &state.net, NetCommand::JoinChannel { channel_id: id.to_owned() }); +} +pub fn tick(ui: &mut UiState) { ui.forum.timeout(); } +/// Observe lifecycle and a forum's view acknowledgement before issuing LIST/OPEN. +pub fn observe(ui: &mut UiState, net: &NetHandle, event: &NetEvent) { + match event { + NetEvent::Connected { forums, restored, .. } => { + if !restored { ui.forum = ForumState::default(); } + ui.forum.supported = *forums; + if *restored && let Some(id) = ui.forum.channel_id.clone() { ui.forum.select(&id); } + } + NetEvent::Disconnected { will_retry, .. } => { + if !will_retry { ui.forum = ForumState::default(); } + else { ui.forum.suspend(); } + } + NetEvent::ChannelState { channel_id, kind, members, .. } + if kind == "forum" && !members.is_empty() && ui.forum.channel_id.as_deref() == Some(channel_id) && ui.forum.waiting_join.is_some() => { + ui.forum.waiting_join = None; ui.forum.joined = true; + let operation = if ui.forum.topic_id.is_some() { wire::ForumOperation::Open } else { wire::ForumOperation::List }; + request(ui, net, operation, 0); + } + NetEvent::ChannelDeleted { channel_id } if ui.forum.channel_id.as_deref() == Some(channel_id) => { + ui.forum = ForumState::with_support(ui.forum.supported); + } + _ => (), + } +} +pub fn result(ui: &mut UiState, result: wire::ForumResult) { + ui.forum.result(result); remember_current_authors(ui); +} +pub fn changed(ui: &mut UiState, event: wire::ForumChanged) { + ui.forum.changed(event); remember_current_authors(ui); +} +fn remember_current_authors(ui: &mut UiState) { + let authors: Vec<_> = ui.forum.topics.iter().filter_map(|topic|topic.author.clone()).chain(ui.forum.posts.iter().filter_map(|post|post.author.clone())).collect(); + remember_authors(ui, authors.iter()); +} +fn remember_authors<'a>(ui: &mut UiState, authors: impl Iterator) { + for author in authors { + ui.user_names.entry(author.user_id.clone()).or_insert_with(|| author.nickname.clone()); + ui.member_profiles.entry(author.user_id.clone()).or_insert_with(|| (author.account_id.clone(), author.avatar_url.clone())); + } +} +fn author(ui: &UiState, snapshot: Option<&wire::MemberInfo>) -> String { + snapshot.map(|author|ui.user_names.get(&author.user_id).cloned().unwrap_or_else(||author.nickname.clone())).unwrap_or_default() +} +pub fn sync(window: &MainWindow, ui: &UiState, own_user_id: &str) { + let show = visible(ui); window.set_show_forum(show); + if !show { return; } + let forum = &ui.forum; + window.set_forum_channel_name(ui.channels.iter().find(|c|Some(&c.id)==ui.active_channel.as_ref()).map_or("", |c|c.name.as_str()).into()); + window.set_forum_supported(forum.supported); window.set_forum_loading(forum.loading()); window.set_forum_busy(forum.busy()); + window.set_forum_creating(forum.creating); window.set_forum_topic_open(forum.topic_id.is_some()); + window.set_forum_title_draft(forum.title_draft.as_str().into()); window.set_forum_body_draft(forum.body_draft.as_str().into()); window.set_forum_reply_draft(forum.reply_draft.as_str().into()); + window.set_forum_error(super::i18n::text(&forum.error).into()); + window.set_forum_more_topics(forum.topics_offset.is_some()); window.set_forum_more_replies(forum.posts_offset.is_some()); + window.set_forum_topic_title(forum.topics.iter().find(|t|Some(&t.topic_id)==forum.topic_id.as_ref()).map_or("", |t|t.title.as_str()).into()); + let now = chrono::Local::now(); + let topics: Vec = forum.topics.iter().map(|topic| ForumTopicItem { id:topic.topic_id.as_str().into(), title:topic.title.as_str().into(), author:author(ui,topic.author.as_ref()).into(), updated:super::timestamps::format_at(topic.updated_at,&now).into(), excerpt:SharedString::default(), replies:topic.reply_count.min(i32::MAX as u32) as i32 }).collect(); + let posts: Vec = forum.posts.iter().filter_map(|post|post.message.as_ref().map(|message| { + let avatar=ui.avatar_path_for(&message.sender_id,own_user_id).as_deref().map(super::avatar::central::image).unwrap_or_default(); + let name=author(ui,post.author.as_ref()); + MessageItem { message_id:message.message_id.as_str().into(), sender_id:message.sender_id.as_str().into(), sender_name:name.as_str().into(), timestamp:super::timestamps::format_at(message.timestamp,&now).into(), content:message.content.as_str().into(),media_source:message.content.as_str().into(),show_author:true,is_own:message.sender_id==own_user_id,avatar_text:super::bridge::initials(&name),has_avatar:avatar.size().width>0,avatar,media_ratio:1.0,..Default::default() } + })).collect(); + if !window.get_forum_topics().iter().eq(topics.iter().cloned()) { window.set_forum_topics(ModelRc::new(VecModel::from(topics))); } + let current=window.get_forum_replies(); + if current.row_count()!=posts.len() || !current.iter().zip(posts.iter()).all(|(a,b)|super::bridge::same_message(&a,b)) {window.set_forum_replies(ModelRc::new(VecModel::from(posts)));} + +} + +fn perform(state: &Rc>, operation: wire::ForumOperation, offset: u32) { + let mut s = state.borrow_mut(); let net = s.net.clone(); request(&mut s.ui,&net,operation,offset); +} +pub fn wire(window: &MainWindow, state: &Rc>) { + { let state=state.clone(); window.on_forum_create(move || { let mut s=state.borrow_mut(); if visible(&s.ui) { s.ui.forum.create(); } }); } + { let state=state.clone(); window.on_forum_cancel_create(move || { let mut s=state.borrow_mut(); if !s.ui.forum.pending() {s.ui.forum.creating=false;} }); } + { let state=state.clone(); window.on_forum_back(move || { let mut s=state.borrow_mut(); if !s.ui.forum.pending() {s.ui.forum.creating=false;s.ui.forum.topic_id=None;s.ui.forum.error.clear();} }); } + { let state=state.clone(); window.on_forum_refresh(move || { + let mut s=state.borrow_mut(); if !visible(&s.ui) || s.ui.forum.pending() { return; } + if !s.ui.forum.joined { if let Some(id)=s.ui.forum.channel_id.clone() {select(&mut s,&id);} return; } + let operation=if s.ui.forum.topic_id.is_some() {wire::ForumOperation::Open} else {wire::ForumOperation::List}; let net=s.net.clone();request(&mut s.ui,&net,operation,0); + }); } + { let state=state.clone(); window.on_forum_open_topic(move |id| { let mut s=state.borrow_mut(); if !visible(&s.ui) {return;} if let Some(request)=s.ui.forum.open(id.as_str()) {send(&s.ui,&s.net,NetCommand::ForumRequest(request));} }); } + { let state=state.clone(); window.on_forum_submit_topic(move ||perform(&state,wire::ForumOperation::Create,0)); } + { let state=state.clone(); window.on_forum_submit_reply(move ||perform(&state,wire::ForumOperation::Reply,0)); } + { let state=state.clone(); window.on_forum_load_more_topics(move || {let offset=state.borrow().ui.forum.topics_offset;if let Some(offset)=offset {perform(&state,wire::ForumOperation::List,offset);} }); } + { let state=state.clone(); window.on_forum_load_more_replies(move || {let offset=state.borrow().ui.forum.posts_offset;if let Some(offset)=offset {perform(&state,wire::ForumOperation::Open,offset);} }); } + { let state=state.clone(); window.on_forum_title_edited(move |value| state.borrow_mut().ui.forum.edit_title(value.to_string())); } + { let state=state.clone(); window.on_forum_body_edited(move |value| state.borrow_mut().ui.forum.edit_body(value.to_string())); } + { let state=state.clone(); window.on_forum_reply_edited(move |value| state.borrow_mut().ui.forum.edit_reply(value.to_string())); } +} diff --git a/src/ui/forum/state.rs b/src/ui/forum/state.rs new file mode 100644 index 0000000..1b4a927 --- /dev/null +++ b/src/ui/forum/state.rs @@ -0,0 +1,213 @@ +use crate::net::wire; +use std::time::{Duration, Instant}; + +const REQUEST_TIMEOUT: Duration = Duration::from_secs(20); + +struct Pending { request: wire::ForumRequest, started: Instant } + +/// View state belongs to one authenticated node session; mutations stay drafts until ACK. +#[derive(Default)] +pub struct ForumState { + pub supported: bool, + pub channel_id: Option, + pub joined: bool, + pub topics: Vec, + pub posts: Vec, + pub topic_id: Option, + pub creating: bool, + pub title_draft: String, + pub body_draft: String, + pub reply_draft: String, + pub error: String, + pub topics_offset: Option, + pub posts_offset: Option, + pub waiting_join: Option, + topic_draft_id: Option, + first_message_id: Option, + reply_message_id: Option, + pending: Option, +} +impl ForumState { + pub fn suspend(&mut self) { self.supported=false; self.joined=false; self.pending=None; self.waiting_join=None; } + pub fn with_support(supported: bool) -> Self { Self { supported, ..Default::default() } } + pub fn edit_title(&mut self, value: String) { if !self.busy() && self.title_draft != value { self.title_draft=value; self.topic_draft_id=None; self.first_message_id=None; } } + pub fn edit_body(&mut self, value: String) { if !self.busy() && self.body_draft != value { self.body_draft=value; self.topic_draft_id=None; self.first_message_id=None; } } + pub fn edit_reply(&mut self, value: String) { if !self.busy() && self.reply_draft != value { self.reply_draft=value; self.reply_message_id=None; } } + pub fn loading(&self) -> bool { + self.waiting_join.is_some() || self.pending.as_ref().is_some_and(|p| !crate::net::forum::is_mutation(&p.request)) + } + pub fn busy(&self) -> bool { self.pending.as_ref().is_some_and(|p| crate::net::forum::is_mutation(&p.request)) } + pub fn pending(&self) -> bool { self.pending.is_some() || self.waiting_join.is_some() } + pub fn select(&mut self, channel: &str) { + if self.channel_id.as_deref() != Some(channel) { *self = Self { supported: self.supported, ..Default::default() }; } + self.channel_id = Some(channel.to_owned()); self.joined = false; self.waiting_join = Some(Instant::now()); self.error.clear(); + } + pub fn create(&mut self) { + if self.pending() || !self.supported { return; } + self.creating = true; self.topic_id = None; self.posts.clear(); self.error.clear(); + } + pub fn request(&mut self, operation: wire::ForumOperation, offset: u32) -> Option { + if !self.supported || !self.joined || self.pending() { return None; } + let channel_id = self.channel_id.clone()?; + let mut request = wire::ForumRequest { request_id: uuid::Uuid::new_v4().to_string(), channel_id, operation: operation as i32, offset, limit: if operation == wire::ForumOperation::List { 20 } else { 50 }, ..Default::default() }; + match operation { + wire::ForumOperation::List => (), + wire::ForumOperation::Open => { request.topic_id = self.topic_id.clone()?; if offset == 0 { self.posts.clear(); self.posts_offset = None; } }, + wire::ForumOperation::Create => { + let title = self.title_draft.trim(); let content = self.body_draft.trim(); + if !valid_title(title) || !valid_body(content) { self.error = "Enter a title (1–160 characters) and a first message (1–16000 characters).".into(); return None; } + request.topic_id = self.topic_draft_id.get_or_insert_with(|| uuid::Uuid::new_v4().to_string()).clone(); + request.message_id = self.first_message_id.get_or_insert_with(|| uuid::Uuid::new_v4().to_string()).clone(); + request.title = title.to_owned(); request.content = content.to_owned(); + } + wire::ForumOperation::Reply => { + if !valid_body(self.reply_draft.trim()) { self.error = "Enter a reply (1–16000 characters).".into(); return None; } + request.topic_id = self.topic_id.clone()?; + request.message_id = self.reply_message_id.get_or_insert_with(|| uuid::Uuid::new_v4().to_string()).clone(); + request.content = self.reply_draft.trim().to_owned(); + } + _ => return None, + } + self.error.clear(); self.pending = Some(Pending { request: request.clone(), started: Instant::now() }); Some(request) + } + pub fn open(&mut self, id: &str) -> Option { + if self.pending() || !self.topics.iter().any(|topic| topic.topic_id == id) { return None; } + self.topic_id = Some(id.to_owned()); self.creating = false; self.posts.clear(); self.reply_draft.clear(); self.reply_message_id = None; self.posts_offset = None; + self.request(wire::ForumOperation::Open, 0) + } + pub fn timeout(&mut self) { + if self.waiting_join.is_some_and(|at| at.elapsed() >= REQUEST_TIMEOUT) + || self.pending.as_ref().is_some_and(|p| p.started.elapsed() >= REQUEST_TIMEOUT) { + self.waiting_join = None; self.pending = None; + self.error = "The forum request timed out. Your draft has been kept; refresh or retry.".into(); + } + } + pub fn result(&mut self, result: wire::ForumResult) { + let Some(pending) = self.pending.as_ref() else { return; }; + let request = &pending.request; + if result.request_id != request.request_id || result.operation != request.operation || result.channel_id != request.channel_id + || (!request.topic_id.is_empty() && result.topic_id != request.topic_id) { return; } + let request = request.clone(); self.pending = None; + if result.error_code != 0 || !result.error.is_empty() { + self.error = result.error.chars().take(500).collect(); + if self.error.is_empty() { self.error = "The server refused this forum request.".into(); } + return; + } + if result.topics.len() > 50 || result.posts.len() > 100 + || result.topics.iter().any(|t| t.channel_id != request.channel_id) + || result.posts.iter().any(|p| p.topic_id != result.topic_id || p.message.as_ref().is_none_or(|m| m.channel_id != request.channel_id)) { + self.error = "The server returned an invalid forum response.".into(); return; + } + let operation = wire::ForumOperation::try_from(request.operation).ok(); + if matches!(operation, Some(wire::ForumOperation::Create | wire::ForumOperation::Reply)) + && !result.posts.iter().any(|p| p.message.as_ref().is_some_and(|m| m.message_id == request.message_id)) { + self.error = "The server did not acknowledge this forum message.".into(); return; + } + self.error.clear(); + match operation { + Some(wire::ForumOperation::List) => { + if request.offset == 0 { self.topics.clear(); } + let count = result.topics.len() as u32; + for topic in result.topics { self.upsert_topic(topic); } + self.topics_offset = next_offset(request.offset, count, result.has_more); + } + Some(wire::ForumOperation::Open) => { + let count = result.posts.len() as u32; + if result.has_more && let Some(last) = result.posts.iter().map(|p| p.ordinal).max() { self.posts.retain(|p| p.ordinal <= last); } + for topic in result.topics { self.upsert_topic(topic); } + for post in result.posts { self.upsert_post(post); } + self.posts_offset = next_offset(request.offset, count, result.has_more); + } + Some(wire::ForumOperation::Create) => { + self.creating = false; self.topic_id = Some(request.topic_id); + self.title_draft.clear(); self.body_draft.clear(); self.topic_draft_id = None; self.first_message_id = None; + self.posts.clear(); self.posts_offset = None; + for topic in result.topics { self.upsert_topic(topic); } + for post in result.posts { self.upsert_post(post); } + } + Some(wire::ForumOperation::Reply) => { + self.reply_draft.clear(); self.reply_message_id = None; + for topic in result.topics { self.upsert_topic(topic); } + // When a thread is only partially loaded, do not insert a later reply ahead + // of unseen posts: refresh/page through its chronological history instead. + if self.posts_offset.is_none() { for post in result.posts { self.upsert_post(post); } } + } + _ => (), + } + } + pub fn changed(&mut self, event: wire::ForumChanged) { + if self.channel_id.as_deref() != Some(event.channel_id.as_str()) || !self.supported { return; } + if let Some(topic) = event.topic && topic.channel_id == event.channel_id { self.upsert_topic(topic); } + if self.posts_offset.is_none() && let Some(post) = event.post + && self.topic_id.as_deref() == Some(post.topic_id.as_str()) + && post.message.as_ref().is_some_and(|m| m.channel_id == event.channel_id) { self.upsert_post(post); } + } + fn upsert_topic(&mut self, topic: wire::ForumTopic) { + if let Some(current) = self.topics.iter_mut().find(|t| t.topic_id == topic.topic_id) { + if current.updated_at <= topic.updated_at { *current = topic; } + } else { self.topics.push(topic); } + self.topics.sort_by(|a,b| b.updated_at.cmp(&a.updated_at).then_with(|| a.topic_id.cmp(&b.topic_id))); + } + fn upsert_post(&mut self, post: wire::ForumPost) { + let Some(message) = &post.message else { return; }; + if !self.posts.iter().any(|p| p.message.as_ref().is_some_and(|m| m.message_id == message.message_id)) { self.posts.push(post); } + self.posts.sort_by_key(|post| post.ordinal); + } +} +fn next_offset(offset: u32, count: u32, has_more: bool) -> Option { (has_more && count > 0 && offset.saturating_add(count) <= 100_000).then_some(offset.saturating_add(count)) } +fn bidi_or_control(c: char) -> bool { c.is_control() || matches!(c, '\u{061c}'|'\u{200e}'|'\u{200f}'|'\u{202a}'..='\u{202e}'|'\u{2066}'..='\u{2069}') } +fn valid_title(value: &str) -> bool { !value.is_empty() && value.chars().count() <= 160 && !value.chars().any(bidi_or_control) } +fn valid_body(value: &str) -> bool { !value.is_empty() && value.chars().count() <= 16000 && value.len() <= 64*1024 && !value.chars().any(|c| bidi_or_control(c) && c != '\n' && c != '\t') } + +#[cfg(test)] +mod tests { + use super::*; + fn ready() -> ForumState { ForumState { supported: true, joined: true, channel_id: Some("forum".into()), ..Default::default() } } + fn topic(id: &str) -> wire::ForumTopic { wire::ForumTopic { topic_id:id.into(),channel_id:"forum".into(),title:"A real topic".into(),..Default::default() } } + fn post(id: &str, topic: &str, ordinal: u64) -> wire::ForumPost { wire::ForumPost { topic_id:topic.into(),ordinal,message:Some(wire::ChatMessage { message_id:id.into(),channel_id:"forum".into(),content:"A real reply".into(),timestamp:1000,..Default::default() }),..Default::default() } } + fn response(request: &wire::ForumRequest) -> wire::ForumResult { wire::ForumResult { request_id:request.request_id.clone(),operation:request.operation,channel_id:request.channel_id.clone(),topic_id:request.topic_id.clone(),..Default::default() } } + #[test] + fn old_server_or_unacknowledged_join_cannot_prepare_forum_packets() { + let mut state=ready();state.supported=false;assert!(state.request(wire::ForumOperation::List,0).is_none()); + state.supported=true;state.joined=false;assert!(state.request(wire::ForumOperation::List,0).is_none()); + } + #[test] + fn failed_create_keeps_draft_and_stable_mutation_ids_until_matching_ack() { + let mut state=ready();state.create();state.edit_title("Topic".into());state.edit_body("Opening post".into()); + let first=state.request(wire::ForumOperation::Create,0).unwrap();assert!(state.topic_id.is_none());assert_eq!(state.title_draft,"Topic"); + let mut denied=response(&first);denied.error_code=5;denied.error="Permission denied".into();state.result(denied); + assert_eq!(state.body_draft,"Opening post");assert!(!state.busy()); + let retry=state.request(wire::ForumOperation::Create,0).unwrap();assert_ne!(first.request_id,retry.request_id);assert_eq!(first.topic_id,retry.topic_id);assert_eq!(first.message_id,retry.message_id); + let mut stale=response(&first);stale.topics=vec![topic(&first.topic_id)];stale.posts=vec![post(&first.message_id,&first.topic_id,1)];state.result(stale);assert!(state.busy());assert_eq!(state.title_draft,"Topic"); + let mut accepted=response(&retry);accepted.topics=vec![topic(&retry.topic_id)];accepted.posts=vec![post(&retry.message_id,&retry.topic_id,1)];state.result(accepted); + assert_eq!(state.topic_id.as_deref(),Some(retry.topic_id.as_str()));assert_eq!(state.posts.len(),1);assert!(state.title_draft.is_empty());assert!(state.body_draft.is_empty());assert!(!state.creating); + } + #[test] + fn changing_failed_draft_allocates_new_object_ids_and_stale_node_results_are_ignored() { + let mut state=ready();state.edit_title("Topic".into());state.edit_body("First".into());let old=state.request(wire::ForumOperation::Create,0).unwrap(); + let mut failed=response(&old);failed.error="Denied".into();state.result(failed);state.edit_body("Changed".into());let new=state.request(wire::ForumOperation::Create,0).unwrap();assert_ne!(old.topic_id,new.topic_id);assert_ne!(old.message_id,new.message_id); + state.select("different-forum");state.result(response(&new));assert!(state.topics.is_empty());assert!(state.posts.is_empty());assert_eq!(state.channel_id.as_deref(),Some("different-forum")); + } + #[test] + fn pagination_uses_actual_byte_bounded_page_size_and_posts_sort_by_ordinal() { + let mut state=ready();state.topics.push(topic("topic"));let request=state.open("topic").unwrap();assert_eq!(request.limit,50); + let mut result=response(&request);result.topics=vec![topic("topic")];result.posts=vec![post("two","topic",2),post("one","topic",1)];result.has_more=true;state.result(result); + assert_eq!(state.posts_offset,Some(2));assert_eq!(state.posts.iter().map(|p|p.ordinal).collect::>(),vec![1,2]); + let request=state.request(wire::ForumOperation::Open,state.posts_offset.unwrap()).unwrap();assert_eq!(request.offset,2); + let mut last=response(&request);last.posts=vec![post("three","topic",3)];state.result(last);assert!(state.posts_offset.is_none());assert_eq!(state.posts.len(),3); + } + #[test] + fn changed_ack_and_page_overlap_deduplicate_even_with_equal_millisecond_timestamps() { + let mut state=ready();state.topics.push(topic("topic"));state.topic_id=Some("topic".into());state.posts.push(post("first","topic",1));state.edit_reply("Own reply".into());let request=state.request(wire::ForumOperation::Reply,0).unwrap(); + state.changed(wire::ForumChanged {channel_id:"forum".into(),topic:Some(topic("topic")),post:Some(post("third","topic",3))}); + let mut result=response(&request);result.topics=vec![topic("topic")];result.posts=vec![post(&request.message_id,"topic",2)];state.result(result); + state.changed(wire::ForumChanged {channel_id:"forum".into(),topic:Some(topic("topic")),post:Some(post(&request.message_id,"topic",2))}); + assert_eq!(state.posts.iter().map(|p|p.ordinal).collect::>(),vec![1,2,3]);assert!(state.reply_draft.is_empty()); + } + #[test] + fn timeout_keeps_text_and_retry_ids_and_invalid_reply_ack_cannot_clear_input() { + let mut state=ready();state.topic_id=Some("topic".into());state.edit_reply("Keep this".into());let request=state.request(wire::ForumOperation::Reply,0).unwrap(); + state.pending.as_mut().unwrap().started=Instant::now()-REQUEST_TIMEOUT;state.timeout();assert_eq!(state.reply_draft,"Keep this");assert!(!state.error.is_empty()); + let retry=state.request(wire::ForumOperation::Reply,0).unwrap();assert_eq!(request.message_id,retry.message_id);state.result(response(&retry));assert_eq!(state.reply_draft,"Keep this");assert!(!state.error.is_empty()); + } +} diff --git a/src/ui/mod.rs b/src/ui/mod.rs index a794b63..5d2773a 100644 --- a/src/ui/mod.rs +++ b/src/ui/mod.rs @@ -1,6 +1,9 @@ +pub mod account; +pub mod forum; pub mod appearance; pub mod avatar; pub mod bridge; +pub mod connection; pub mod devices; pub mod emoji; pub mod i18n; @@ -9,6 +12,13 @@ pub mod preferences; pub mod slint; pub mod sounds; pub mod state; +pub mod timestamps; pub mod update; pub mod webhooks; + +pub mod channel_admin; +pub mod chat_images; +pub mod chat_media; + +pub mod server_settings; diff --git a/src/ui/preferences.rs b/src/ui/preferences.rs index 53ecfd7..8eef044 100644 --- a/src/ui/preferences.rs +++ b/src/ui/preferences.rs @@ -23,6 +23,7 @@ struct AudioPreferences { /// True once the person picked the voice input mode explicitly. mode_chosen: bool, volume: Option, + noise_suppress: bool, /// Notification sound switches and volume. sounds: SoundSettings, } @@ -69,6 +70,7 @@ pub fn load(state: &mut UiState) { state.voice_bitrate = prefs.bitrate.unwrap_or(64.0).clamp(8.0, 128.0); (state.vad_mode, state.vad_mode_chosen) = resolve_mode(&prefs); state.output_volume = prefs.volume.unwrap_or(90.0).clamp(0.0, 100.0); + state.noise_suppress = prefs.noise_suppress && cfg!(feature = "rnnoise"); state.sounds = SoundSettings { volume: prefs.sounds.volume.clamp(0.0, 100.0), ..prefs.sounds @@ -89,6 +91,7 @@ pub fn save(state: &UiState) -> anyhow::Result<()> { mode: Some(state.vad_mode), mode_chosen: state.vad_mode_chosen, volume: Some(state.output_volume), + noise_suppress: state.noise_suppress, sounds: state.sounds, }; std::fs::write(path, serde_json::to_vec_pretty(&preferences)?)?; diff --git a/src/ui/server_settings.rs b/src/ui/server_settings.rs new file mode 100644 index 0000000..05ca15a --- /dev/null +++ b/src/ui/server_settings.rs @@ -0,0 +1,245 @@ +//! Real gateway metadata editing with correlated replies and session-fenced requests. +use crate::{ + AppState, + net::{NetCommand, NetEvent, wire}, + ui::{ + slint::MainWindow, + state::{ConnState, UiState}, + }, +}; +use std::{ + cell::RefCell, + rc::Rc, + time::{Duration, Instant}, +}; +#[derive(Clone)] +struct Metadata { + name: String, + description: String, +} +struct Pending { + id: String, + started: Instant, + update: bool, +} +/// Session-local metadata cache and unsaved server-settings draft. +#[derive(Default)] +pub struct ServerSettingsState { + open: bool, + metadata: Option, + name: String, + description: String, + dirty: bool, + pending: Option, + error: String, +} +fn allowed(ui: &UiState) -> bool { + super::channel_admin::allowed(ui) && ui.node_settings_supported +} +fn invalid_char(c: char) -> bool { + matches!(c, '\u{061c}' | '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}') +} +fn valid(name: &str, description: &str) -> bool { + (1..=100).contains(&name.trim().chars().count()) + && !name.chars().any(|c| c.is_control() || invalid_char(c)) + && description.trim().chars().count() <= 2000 + && !description + .chars() + .any(|c| (c.is_control() && c != '\n' && c != '\t') || invalid_char(c)) +} +fn request(ui: &mut UiState, update: bool) -> Option { + if !allowed(ui) || ui.server_settings.pending.is_some() { + return None; + } + if update && (!ui.server_settings.open || ui.server_settings.metadata.is_none()) { + return None; + } + let name = ui.server_settings.name.trim().to_owned(); + let description = ui.server_settings.description.trim().to_owned(); + if update && !valid(&name, &description) { + ui.server_settings.error = super::i18n::text( + "Use a server name of 1–100 characters and a description of at most 2000 characters.", + ); + return None; + } + let session_id = match &ui.conn { + ConnState::Connected { session_id, .. } => session_id.clone(), + _ => return None, + }; + let id = uuid::Uuid::new_v4().to_string(); + ui.server_settings.pending = Some(Pending { + id: id.clone(), + started: Instant::now(), + update, + }); + ui.server_settings.error.clear(); + Some(NetCommand::ForSession { + session_id, + command: Box::new(NetCommand::NodeSettingsRequest(wire::NodeSettingsRequest { + request_id: id, + update, + display_name: if update { name } else { String::new() }, + description: if update { description } else { String::new() }, + })), + }) +} +/// Open authorized node settings and retrieve current persisted metadata. +pub(super) fn open(ui: &mut UiState) -> Option { + if !allowed(ui) { + return None; + } + if !ui.server_settings.open { + if let Some(metadata) = &ui.server_settings.metadata { + ui.server_settings.name = metadata.name.clone(); + ui.server_settings.description = metadata.description.clone(); + } else if let ConnState::Connected { node_name, .. } = &ui.conn { + ui.server_settings.name = node_name.clone(); + } + ui.server_settings.open = true; + ui.server_settings.dirty = false; + } + request(ui, false) +} +/// Register name/description editor actions; never persist an optimistic server name. +pub fn wire(window: &MainWindow, state: &Rc>) { + for action in ["open", "reload", "save"] { + let state = state.clone(); + let handler = move || { + let (command, net) = { + let mut state = state.borrow_mut(); + let command = if action == "open" { + open(&mut state.ui) + } else { + request(&mut state.ui, action == "save") + }; + (command, state.net.clone()) + }; + if let Some(command) = command { + tokio::spawn(async move { + net.send(command).await; + }); + } + }; + match action { + "open" => window.on_open_server_settings(handler), + "reload" => window.on_server_settings_reload(handler), + _ => window.on_server_settings_save(handler), + } + } + { + let state = state.clone(); + window.on_server_settings_close(move || { + state.borrow_mut().ui.server_settings.open = false; + }); + } + for description in [false, true] { + let state = state.clone(); + let handler = move |value: slint::SharedString| { + let mut state = state.borrow_mut(); + if state.ui.server_settings.pending.is_none() { + if description { + state.ui.server_settings.description = value.to_string(); + } else { + state.ui.server_settings.name = value.to_string(); + } + state.ui.server_settings.dirty = true; + } + }; + if description { + window.on_server_description_edited(handler) + } else { + window.on_server_name_edited(handler) + } + } +} +/// Apply public broadcasts, and match administrative responses by request ID. +pub fn receive(ui: &mut UiState, event: &NetEvent) { + if matches!( + event, + NetEvent::Connected { .. } + | NetEvent::Disconnected { .. } + | NetEvent::Reconnecting { .. } + | NetEvent::AccountRequired + ) { + ui.server_settings = Default::default(); + return; + } + let NetEvent::NodeSettingsResult {session_id,result} = event else { + return; + }; + if !matches!(&ui.conn,ConnState::Connected{session_id:current,..} if current==session_id) { return; } + let matching = ui + .server_settings + .pending + .as_ref() + .is_some_and(|pending| pending.id == result.request_id); + if result.error_code != 0 || !result.error.is_empty() { + if matching { + ui.server_settings.pending = None; + ui.server_settings.error = result.error.chars().take(500).collect(); + } + return; + } + if !valid(&result.display_name, &result.description) { + if matching { + ui.server_settings.pending = None; + ui.server_settings.error = super::i18n::text("The server returned invalid settings."); + } + return; + } + let metadata = Metadata { + name: result.display_name.clone(), + description: result.description.clone(), + }; + if let ConnState::Connected { node_name, .. } = &mut ui.conn { + *node_name = metadata.name.clone(); + } else { + return; + } + let saved = matching + && ui + .server_settings + .pending + .as_ref() + .is_some_and(|pending| pending.update); + if !ui.server_settings.dirty || saved { + ui.server_settings.name = metadata.name.clone(); + ui.server_settings.description = metadata.description.clone(); + } + if matching { + ui.server_settings.pending = None; + ui.server_settings.error.clear(); + if saved { + ui.server_settings.dirty = false; + } + } + ui.server_settings.metadata = Some(metadata); +} +/// Time out unconfirmed requests and hide settings when their authorization/scope disappears. +pub fn tick(ui: &mut UiState) { + if !allowed(ui) { + ui.server_settings.open = false; + ui.server_settings.pending = None; + } + if ui + .server_settings + .pending + .as_ref() + .is_some_and(|pending| pending.started.elapsed() >= Duration::from_secs(10)) + { + ui.server_settings.pending = None; + ui.server_settings.error = super::i18n::text( + "No confirmation received. Reload server settings before trying again.", + ); + } +} +/// Synchronize the real editor and its loading/permission status with the native shell. +pub fn sync(window: &MainWindow, ui: &UiState) { + let settings = &ui.server_settings; + window.set_server_settings_open(settings.open && allowed(ui)); + window.set_server_name_draft(settings.name.as_str().into()); + window.set_server_description_draft(settings.description.as_str().into()); + window.set_server_settings_busy(settings.pending.is_some()); + window.set_server_settings_loaded(settings.metadata.is_some()); + window.set_server_settings_error(settings.error.as_str().into()); +} diff --git a/src/ui/slint/account-auth.slint b/src/ui/slint/account-auth.slint new file mode 100644 index 0000000..fd8a27c --- /dev/null +++ b/src/ui/slint/account-auth.slint @@ -0,0 +1,27 @@ +import { Theme, ActionButton } from "theme.slint"; + +export component AccountAuth inherits Rectangle { + in property signing-in; + in property status; + in property public-key; + callback sign-in(); + callback cancel(); + callback open-browser(); + callback settings(); + background: Theme.bg-base; + VerticalLayout { + padding: 40px; spacing: 18px; alignment: center; + Text { text: "VNOX"; font-size: 40px; font-weight: 700; color: Theme.text-primary; horizontal-alignment: center; } + Text { text: @tr("Sign in to Central"); font-size: 26px; font-weight: 600; color: Theme.text-primary; horizontal-alignment: center; } + Text { text: @tr("A Central account is required to connect to servers. Your private identity key stays on this device."); color: Theme.text-secondary; font-size: 15px; horizontal-alignment: center; wrap: word-wrap; } + if root.status != "" : Text { text: root.status; color: Theme.text-primary; font-size: 14px; horizontal-alignment: center; wrap: word-wrap; } + if root.public-key != "" : Text { text: root.public-key; color: Theme.accent; font-family: "monospace"; font-size: 13px; horizontal-alignment: center; wrap: char-wrap; } + HorizontalLayout { + alignment: center; spacing: 12px; + if !root.signing-in : ActionButton { text: @tr("Sign in through browser"); primary: true; clicked => { root.sign-in(); } } + if root.signing-in && root.public-key != "" : ActionButton { text: @tr("Open sign-in page"); primary: true; clicked => { root.open-browser(); } } + if root.signing-in : ActionButton { text: @tr("Cancel"); clicked => { root.cancel(); } } + ActionButton { text: @tr("Settings"); icon: "settings"; labeled: true; clicked => { root.settings(); } } + } + } +} diff --git a/src/ui/slint/assets/icons/folder.svg b/src/ui/slint/assets/icons/folder.svg new file mode 100644 index 0000000..ef69b34 --- /dev/null +++ b/src/ui/slint/assets/icons/folder.svg @@ -0,0 +1,13 @@ + + + diff --git a/src/ui/slint/assets/icons/messages-square.svg b/src/ui/slint/assets/icons/messages-square.svg new file mode 100644 index 0000000..b204725 --- /dev/null +++ b/src/ui/slint/assets/icons/messages-square.svg @@ -0,0 +1,14 @@ + + + + diff --git a/src/ui/slint/avatar-cropper.slint b/src/ui/slint/avatar-cropper.slint index 3f6371d..7396225 100644 --- a/src/ui/slint/avatar-cropper.slint +++ b/src/ui/slint/avatar-cropper.slint @@ -9,6 +9,7 @@ export component AvatarCropper inherits Rectangle { in property offset-y; in-out property zoom: 1; in property error; + in property saving; callback crop-moved(float, float); callback zoom-changed(float); callback confirm(); @@ -109,7 +110,7 @@ export component AvatarCropper inherits Rectangle { spacing: 9px; ActionButton { text: @tr("Cancel"); quiet: true; clicked => { root.cancel(); } } Rectangle { horizontal-stretch: 1; } - ActionButton { text: @tr("Use photo"); active: true; clicked => { root.confirm(); } } + ActionButton { text: root.saving ? @tr("Saving...") : @tr("Use photo"); active: true; clicked => { root.confirm(); } } } } } diff --git a/src/ui/slint/channel-admin.slint b/src/ui/slint/channel-admin.slint new file mode 100644 index 0000000..34d9589 --- /dev/null +++ b/src/ui/slint/channel-admin.slint @@ -0,0 +1,53 @@ +import { Theme, ActionButton } from "theme.slint"; +import { ThemeInput, DeviceSelect } from "controls.slint"; +export component ChannelAdminDialog inherits Rectangle { + in property <[string]> parent-names; + in-out property parent-index; + callback parent-selected(int); + in property operation; + in property kind; + in-out property name; + in property busy; + in property error; + callback name-edited(string); + callback submit(); + callback cancel(); + background: Theme.overlay; + TouchArea { } + keyboard := FocusScope { + init => { self.focus(); } + key-pressed(event) => { + if event.text == Key.Escape { root.cancel(); return accept; } + return reject; + } + Rectangle { + width: Math.min(440px, root.width - 32px); height: Math.min(root.operation == "create" && root.kind != "category" ? 430px : 360px, root.height - 32px); + x: (root.width - self.width) / 2; y: (root.height - self.height) / 2; + background: Theme.bg-surface; border-radius: 12px; border-width: 1px; border-color: Theme.border; + VerticalLayout { + padding: 22px; spacing: 14px; + Text { text: root.operation == "delete" ? @tr("Delete channel?") : root.operation == "rename" ? @tr("Rename channel") : root.kind == "voice" ? @tr("Create voice room") : root.kind == "category" ? @tr("Create category") : root.kind == "forum" ? @tr("Create forum") : @tr("Create text channel"); color: Theme.text-primary; font-size: Theme.font-size + 4px; font-weight: 600; wrap: word-wrap; } + if root.operation == "delete" : Text { text: @tr("Delete “{}”? This removes the channel for everyone on this server.", root.name); color: Theme.text-secondary; wrap: word-wrap; font-size: Theme.font-size - 1px; } + if root.operation != "delete" : VerticalLayout { + height: Theme.font-size + 55px; + spacing: 7px; alignment: start; + Text { text: @tr("Channel name"); color: Theme.text-secondary; font-size: Theme.font-size - 2px; } + ThemeInput { init => { self.focus(); } read-only: root.busy; text <=> root.name; placeholder-text: @tr("Channel name"); edited(value) => { root.name-edited(value); } accepted => { if !root.busy { root.submit(); } } } + } + if root.operation == "create" && root.kind != "category" :VerticalLayout { + height:Theme.font-size + 53px;spacing:7px;alignment:start; + Text{text:@tr("Category");color:Theme.text-secondary;font-size:Theme.font-size - 2px;} + if !root.busy :DeviceSelect{model:root.parent-names;current-index <=>root.parent-index;selected(value)=>{root.parent-selected(root.parent-index);}} + if root.busy :Text{text:root.parent-names[root.parent-index];color:Theme.text-primary;font-size:Theme.font-size - 2px;} + } + Text { text: root.busy ? @tr("Waiting for the server…") : root.error; color: root.error != "" ? Theme.danger : Theme.text-muted; wrap: word-wrap; font-size: Math.max(11px, Theme.font-size - 3px); vertical-stretch: 1; } + HorizontalLayout { + spacing: 10px; + ActionButton { text: root.busy ? @tr("Close") : @tr("Cancel"); clicked => { root.cancel(); } } + Rectangle { horizontal-stretch: 1; } + if !root.busy : ActionButton { text: root.operation == "delete" ? @tr("Delete channel") : root.operation == "rename" ? @tr("Save name") : @tr("Create channel"); icon: root.operation == "delete" ? "trash-2" : "check"; labeled: true; danger: root.operation == "delete"; primary: root.operation != "delete"; clicked => { root.submit(); } } + } + } + } + } +} diff --git a/src/ui/slint/chat.slint b/src/ui/slint/chat.slint index 8b2ca71..1a2a631 100644 --- a/src/ui/slint/chat.slint +++ b/src/ui/slint/chat.slint @@ -4,15 +4,17 @@ import { EmojiPicker } from "emoji-picker.slint"; export struct ReactionItem { emoji: string, image: image, has_image: bool, count: int, mine: bool } export struct MessageItem { + avatar: image, has_avatar: bool, message_id: string, sender_id: string, sender_name: string, - content: string, timestamp: string, is_own: bool, edited: bool, reply_to: string, avatar_text: string, show_author: bool, + media_source: string, content: string, timestamp: string, is_own: bool, edited: bool, reply_to: string, avatar_text: string, show_author: bool, reactions: [ReactionItem], + media_image: image, media_ready: bool, media_status: string, media_ratio: float, } export struct DmConversationItem { dm_id: string, other_user_id: string, other_nickname: string, e2ee_enabled: bool, messages: [MessageItem], } -export struct MemberItem { user_id: string, nickname: string, status: string, presence: string, avatar_text: string, is_own: bool } +export struct MemberItem { avatar: image, has_avatar: bool, user_id: string, nickname: string, status: string, presence: string, avatar_text: string, is_own: bool } component QuickReaction inherits Rectangle { in property glyph; @@ -47,7 +49,7 @@ component ReactionChip inherits Rectangle { touch := TouchArea { clicked => { root.clicked(); } } } -component MessageRow inherits Rectangle { +export component MessageRow inherits Rectangle { in property message; in property actions-enabled: true; in property own-avatar; @@ -69,7 +71,7 @@ component MessageRow inherits Rectangle { padding-top: root.message.show_author ? 9px : 2px; padding-bottom: root.message.show_author ? 9px : 2px; spacing: 13px; AvatarView { width: 34px; height: root.message.show_author ? 34px : 0px; visible: root.message.show_author; - source: root.own-avatar; has-source: root.has-own-avatar && root.message.is_own; + source: root.message.avatar; has-source: root.message.has_avatar; initials: root.message.avatar_text; mask: root.background; } VerticalLayout { @@ -86,6 +88,20 @@ component MessageRow inherits Rectangle { Rectangle { horizontal-stretch: 1; } } Text { text: root.message.content; color: Theme.text-primary; font-size: Math.max(11px, Theme.font-size * 1.0); wrap: word-wrap; } + if root.message.media_ready : Rectangle { + min-width: 0px; preferred-width: 300px; horizontal-stretch: 1; + height: Math.min(320px, 300px / Math.max(0.1, root.message.media_ratio)); + Image { + x: 0px; y: 0px; + source: root.message.media_image; + width: Math.min(300px, parent.width); height: parent.height; + image-fit: contain; + } + } + if root.message.media_status != "" : Text { + text: root.message.media_status; color: Theme.text-muted; + font-size: Math.max(11px, Theme.font-size * 0.75); wrap: word-wrap; + } if root.message.reactions.length > 0 : HorizontalLayout { spacing: 6px; alignment: start; padding-top: 2px; for reaction in root.message.reactions: ReactionChip { @@ -139,6 +155,13 @@ export component ChatPanel inherits Rectangle { in-out property replying-to-sender; in-out property replying-to-content; in-out property members-visible: true; + in property pending-image; + in property has-pending-image; + in property image-uploading; + in property image-status; + callback paste-image() -> bool; + callback cancel-image(); + callback send-image(); callback input-edited(string); callback toggle-members(); callback open-webhooks(); @@ -189,6 +212,19 @@ export component ChatPanel inherits Rectangle { Rectangle { vertical-stretch: 1; } } } + if root.has-pending-image || root.image-status != "" : Rectangle { + height: root.has-pending-image ? 132px : 36px; + background: Theme.bg-elevated; + HorizontalLayout { + padding: 10px; spacing: 12px; + if root.has-pending-image : Image { source: root.pending-image; width: 140px; image-fit: contain; } + Text { text: root.image-status; wrap: word-wrap; color: Theme.text-secondary; vertical-alignment: center; horizontal-stretch: 1; } + VerticalLayout { alignment: center; + if root.has-pending-image && !root.image-uploading : ActionButton { text: @tr("Send image"); icon: "send"; primary: true; clicked => { root.send-image(); } } + if !root.image-uploading : ActionButton { text: @tr("Cancel"); icon: "x"; quiet: true; clicked => { root.cancel-image(); } } + } + } + } if root.replying-to-message != "" : Rectangle { height: 34px; background: Theme.bg-elevated; HorizontalLayout { @@ -205,7 +241,7 @@ export component ChatPanel inherits Rectangle { width: parent.width - 40px; height: Math.min(150px, Math.max(48px, editor.preferred-height + 22px)); background: Theme.bg-interactive; border-radius: 9px; - border-width: 1px; border-color: editor.has-focus ? Theme.accent.with-alpha(0.6) : Theme.border; + border-width: 1px; border-color: editor.has-focus ? Theme.accent : Theme.border; HorizontalLayout { padding-left: 14px; padding-right: 8px; padding-top: 11px; padding-bottom: 11px; spacing: 6px; editor := TextInput { @@ -216,6 +252,9 @@ export component ChatPanel inherits Rectangle { selection-background-color: Theme.selected; selection-foreground-color: Theme.text-primary; edited => { root.input-edited(self.text); } key-pressed(event) => { + if event.modifiers.control && (event.text == "v" || event.text == "V" || event.text == "м" || event.text == "М") { + if root.paste-image() { return accept; } + } if event.text == "\n" && !event.modifiers.shift { root.send-message(root.is-dm ? "" : root.active-channel-id, root.input-text); return accept; @@ -223,6 +262,10 @@ export component ChatPanel inherits Rectangle { return reject; } } + VerticalLayout { + alignment: end; + ActionButton { text: @tr("Paste image"); icon: "image"; quiet: true; width: 32px; height: 30px; clicked => { root.paste-image(); } } + } VerticalLayout { alignment: end; ActionButton { text: @tr("Emoji"); icon: "smile"; quiet: true; width: 32px; height: 30px; clicked => { emoji-popup.show(); } } @@ -268,7 +311,7 @@ export component ChatPanel inherits Rectangle { width: 30px; AvatarView { width: 30px; height: 30px; y: (parent.height - self.height) / 2; - source: root.own-avatar; has-source: root.has-own-avatar && member.is_own; + source: member.avatar; has-source: member.has_avatar; initials: member.avatar_text; mask: Theme.bg-surface; } PresenceDot { x: 19px; y: parent.height / 2 + 4px; presence: member.presence; ring: Theme.bg-surface; } diff --git a/src/ui/slint/controls.slint b/src/ui/slint/controls.slint index 3b803a3..36adc76 100644 --- a/src/ui/slint/controls.slint +++ b/src/ui/slint/controls.slint @@ -1,10 +1,67 @@ import { Theme, ActionButton, Symbol } from "theme.slint"; +export component DeviceList inherits Rectangle { + in property <[string]> model; + in property current-index; + in property heading; + callback chosen(int); + background: Theme.bg-surface; + border-radius: 8px; + border-width: 1px; border-color: Theme.border; + VerticalLayout { + padding: 8px; spacing: 6px; + if root.heading != "" : Text { text: root.heading; height: 28px; color: Theme.text-primary; font-size: 14px; font-weight: 600; vertical-alignment: center; } + Flickable { + content-width: self.width; + VerticalLayout { + spacing: 3px; + for item[index] in root.model: Rectangle { + height: 36px; border-radius: 5px; + background: index == root.current-index ? Theme.selected : touch.has-hover ? Theme.bg-hover : transparent; + accessible-role: button; accessible-label: item; + HorizontalLayout { + padding-left: 10px; padding-right: 10px; spacing: 10px; + Text { text: item; horizontal-stretch: 1; overflow: elide; color: Theme.text-primary; font-size: 13px; vertical-alignment: center; } + Rectangle { width: 16px; VerticalLayout { alignment: center; Rectangle { height: 16px; border-radius: 8px; border-width: 1px; border-color: index == root.current-index ? Theme.accent : Theme.text-muted; background: index == root.current-index ? Theme.accent : transparent; } } } + } + touch := TouchArea { clicked => { root.chosen(index); } } + } + } + } + } +} + +export component AudioDeviceButton inherits Rectangle { + in property text; + in property icon; + in property danger; + in property <[string]> model; + in property current-index; + in property heading; + callback clicked(); + callback refresh(); + callback chosen(int); + width: 46px; height: 32px; + HorizontalLayout { + spacing: 0; + ActionButton { text: root.text; icon: root.icon; danger: root.danger; width: 30px; clicked => { root.clicked(); } right-clicked => { root.refresh(); devices.show(); } } + ActionButton { text: root.heading; icon: "chevron-down"; width: 16px; clicked => { root.refresh(); devices.show(); } right-clicked => { root.refresh(); devices.show(); } } + } + devices := PopupWindow { + width: 310px; + height: Math.min(root.model.length * 39px + 56px, 310px); + x: root.width - self.width; y: -self.height - 8px; + DeviceList { model: root.model; heading: root.heading; current-index: root.current-index; chosen(index) => { root.chosen(index); devices.close(); } } + } +} + export component DeviceSelect inherits Rectangle { in property <[string]> model; in-out property current-index; callback selected(string); height: 34px; + max-width: 560px; + horizontal-stretch: 0; background: Theme.bg-interactive; border-radius: 6px; border-width: 1px; @@ -32,20 +89,7 @@ export component DeviceSelect inherits Rectangle { x: 0px; y: root.height + 3px; width: root.width; height: Math.min(root.model.length * 36px + 12px, 264px); - Rectangle { - background: Theme.bg-surface; border-radius: 6px; - border-width: 1px; border-color: Theme.border; - Flickable { - content-width: self.width; - VerticalLayout { - padding: 6px; spacing: 3px; - for item[index] in root.model: ActionButton { - text: item; active: index == root.current-index; - clicked => { root.current-index = index; root.selected(item); popup.close(); } - } - } - } - } + DeviceList { model: root.model; current-index: root.current-index; chosen(index) => { root.current-index = index; root.selected(root.model[index]); popup.close(); } } } } diff --git a/src/ui/slint/forum.slint b/src/ui/slint/forum.slint new file mode 100644 index 0000000..758351a --- /dev/null +++ b/src/ui/slint/forum.slint @@ -0,0 +1,123 @@ +import { Theme, ActionButton } from "theme.slint"; +import { ThemeInput, ThemeEditor } from "controls.slint"; +import { MessageItem, MessageRow } from "chat.slint"; + +export struct ForumTopicItem { + id: string, title: string, author: string, updated: string, + excerpt: string, replies: int, +} +export component ForumPanel inherits Rectangle { + in property channel-name; + in property <[ForumTopicItem]> topics; + in property <[MessageItem]> replies; + in property topic-title; + in property topic-open; + in property creating; + in property loading; + in property busy; + in property supported; + in property more-topics; + in property more-replies; + in property error; + in-out property title-draft; + in-out property body-draft; + in-out property reply-draft; + callback refresh(); + callback create(); + callback cancel-create(); + callback open-topic(string); + callback back(); + callback submit-topic(); + callback submit-reply(); + callback load-more-topics(); + callback load-more-replies(); + callback title-edited(string); + callback body-edited(string); + callback reply-edited(string); + background: Theme.bg-base; + VerticalLayout { + spacing: 0; + Rectangle { + height: 58px; background: Theme.bg-surface; + HorizontalLayout { + padding-left: 20px; padding-right: 20px; spacing: 12px; + if root.topic-open || root.creating : VerticalLayout { + alignment: center; + ActionButton { text: @tr("Back to topics"); clicked => { if !root.busy { root.back(); } } } + } + Text { text: root.channel-name; color: Theme.text-primary; font-size: Theme.font-size + 2px; font-weight: 600; vertical-alignment: center; overflow: elide; horizontal-stretch: 1; } + VerticalLayout { alignment: center; ActionButton { text: @tr("Refresh"); clicked => { if root.supported && !root.busy { root.refresh(); } } } } + if !root.topic-open && !root.creating && root.supported : VerticalLayout { + alignment: center; + ActionButton { text: @tr("New topic"); primary: true; clicked => { if !root.busy { root.create(); } } } + } + } + } + Rectangle { height: 1px; background: Theme.border; } + if !root.supported : Text { text: @tr("This server does not support forums yet."); color: Theme.text-secondary; wrap: word-wrap; font-size: Theme.font-size; horizontal-alignment: center; vertical-alignment: center; } + if root.supported : VerticalLayout { + padding: 20px; spacing: 14px; + if root.error != "" : Text { text: root.error; color: Theme.danger; font-size: Theme.font-size - 1px; wrap: word-wrap; } + if root.loading : Text { text: @tr("Loading…"); color: Theme.text-muted; font-size: Theme.font-size - 1px; } + if root.creating : VerticalLayout { + spacing: 12px; + Text { text: @tr("Create topic"); color: Theme.text-primary; font-size: Theme.font-size + 5px; font-weight: 600; } + ThemeInput { text <=> root.title-draft; placeholder-text: @tr("Topic title"); read-only: root.busy; edited(value) => { root.title-edited(value); } } + Text { text: @tr("First message"); color: Theme.text-secondary; font-size: Theme.font-size - 2px; } + ThemeEditor { text <=> root.body-draft; monospace: false; read-only: root.busy; edited(value) => { root.body-edited(value); } } + HorizontalLayout { + alignment: end; spacing: 10px; + ActionButton { text: @tr("Cancel"); clicked => { if !root.busy { root.cancel-create(); } } } + ActionButton { text: root.busy ? @tr("Creating…") : @tr("Create topic"); primary: true; clicked => { if !root.busy { root.submit-topic(); } } } + } + } + if !root.creating && !root.topic-open : VerticalLayout { + spacing: 12px; + if root.topics.length == 0 && !root.loading && root.error == "" : Text { + text: @tr("No topics yet. Start the first discussion."); color: Theme.text-secondary; font-size: Theme.font-size; wrap: word-wrap; + } + Flickable { + content-width: self.width; + VerticalLayout { + spacing: 0; + for topic in root.topics : Rectangle { + height: 105px; background: touch.has-hover ? Theme.bg-hover : transparent; + accessible-role: button; accessible-label: topic.title; + VerticalLayout { + padding-top: 12px; padding-bottom: 12px; padding-left: 12px; padding-right: 12px; spacing: 6px; + Text { text: topic.title; color: Theme.text-primary; font-weight: 600; font-size: Theme.font-size + 1px; overflow: elide; } + Text { text: topic.excerpt; color: Theme.text-secondary; font-size: Theme.font-size - 1px; overflow: elide; } + HorizontalLayout { + spacing: 12px; + Text { text: topic.author; color: Theme.text-muted; font-size: Theme.font-size - 3px; horizontal-stretch: 1; overflow: elide; } + Text { text: @tr("{} replies", topic.replies); color: Theme.text-muted; font-size: Theme.font-size - 3px; } + Text { text: topic.updated; color: Theme.text-muted; font-size: Theme.font-size - 3px; } + } + } + Rectangle { height: 1px; y: parent.height - 1px; background: Theme.border; } + touch := TouchArea { clicked => { keyboard.focus(); if !root.busy { root.open-topic(topic.id); } } } + keyboard := FocusScope { focus-on-click: false; key-pressed(event) => { if event.text == "\n" || event.text == " " { if !root.busy { root.open-topic(topic.id); } return accept; } return reject; } } + if keyboard.has-focus : Rectangle { border-width: 2px; border-color: Theme.accent; background: transparent; } + } + } + } + if root.more-topics : ActionButton { text: @tr("More topics"); clicked => { if !root.loading && !root.busy { root.load-more-topics(); } } } + } + if !root.creating && root.topic-open : VerticalLayout { + spacing: 14px; + Text { text: root.topic-title; color: Theme.text-primary; font-size: Theme.font-size + 5px; font-weight: 600; wrap: word-wrap; } + Flickable { + content-width: self.width; + VerticalLayout { + spacing: 16px; + for reply in root.replies : MessageRow { message: reply; actions-enabled: false; } + } + } + if root.more-replies : ActionButton { text: @tr("More replies"); clicked => { if !root.loading && !root.busy { root.load-more-replies(); } } } + Text { text: @tr("Your reply"); color: Theme.text-secondary; font-size: Theme.font-size - 2px; } + ThemeEditor { text <=> root.reply-draft; monospace: false; preferred-height: 96px; read-only: root.busy; edited(value) => { root.reply-edited(value); } } + HorizontalLayout { alignment: end; ActionButton { text: root.busy ? @tr("Sending…") : @tr("Reply"); primary: true; clicked => { if !root.busy { root.submit-reply(); } } } } + } + } + } +} diff --git a/src/ui/slint/main.slint b/src/ui/slint/main.slint index 0dfd2e5..6bd6dc6 100644 --- a/src/ui/slint/main.slint +++ b/src/ui/slint/main.slint @@ -6,13 +6,99 @@ export { EmojiCatalog, EmojiItem } from "emoji-picker.slint"; import { Theme, ActionButton } from "theme.slint"; import { Sidebar, ChannelItem, GuildItem, DmItem } from "sidebar.slint"; import { ChatPanel, MessageItem, MemberItem } from "chat.slint"; +import { ForumPanel, ForumTopicItem } from "forum.slint"; import { FriendsPanel, FriendItem } from "friends.slint"; import { VoicePanel, VoiceMemberItem } from "voice.slint"; import { BookmarkItem, ConnectScreen } from "connect.slint"; import { SettingsWindow } from "settings.slint"; import { AvatarCropper } from "avatar-cropper.slint"; +import { AccountAuth } from "account-auth.slint"; +import { ChannelAdminDialog } from "channel-admin.slint"; +import { ServerSettingsDialog } from "server-settings.slint"; +import { ManagementMenu, ManagementAction } from "management-menu.slint"; export component MainWindow inherits Window { + in-out property show-forum; + in-out property forum-channel-name; + in-out property <[ForumTopicItem]> forum-topics; + in-out property <[MessageItem]> forum-replies; + in-out property forum-topic-title; + in-out property forum-topic-open; + in-out property forum-creating; + in-out property forum-loading; + in-out property forum-busy; + in-out property forum-supported; + in-out property forum-more-topics; + in-out property forum-more-replies; + in-out property forum-error; + in-out property forum-title-draft; + in-out property forum-body-draft; + in-out property forum-reply-draft; + callback forum-refresh(); + callback forum-create(); + callback forum-cancel-create(); + callback forum-open-topic(string); + callback forum-back(); + callback forum-submit-topic(); + callback forum-submit-reply(); + callback forum-load-more-topics(); + callback forum-load-more-replies(); + callback forum-title-edited(string); + callback forum-body-edited(string); + callback forum-reply-edited(string); + in-out property account-authenticated; + in-out property account-name; + in-out property profile-display-name; + in-out property profile-saving; + in-out property profile-initials; + in-out property profile-error; + callback save-profile-name(string); + in-out property account-status; + in-out property account-signing-in; + in-out property account-public-key; + callback account-sign-in(); + callback account-sign-out(); + callback account-cancel(); + callback account-open-browser(); + in-out property management-menu-open; + in-out property management-menu-x; + in-out property management-menu-y; + in-out property <[ManagementAction]> management-actions; + callback open-node-menu(float,float); + callback open-channel-menu(string,float,float); + callback management-menu-chosen(string); + callback management-menu-close(); + callback toggle-category(string); + in-out property node-structure; + in-out property node-forums; + in-out property <[string]> channel-admin-parent-names; + in-out property channel-admin-parent-index; + callback channel-admin-parent-selected(int); + in-out property server-settings-open; + in-out property server-settings-busy; + in-out property server-settings-loaded; + in-out property server-settings-error; + in-out property server-name-draft; + in-out property server-description-draft; + callback open-server-settings(); + callback server-settings-save(); + callback server-settings-reload(); + callback server-settings-close(); + callback server-name-edited(string); + callback server-description-edited(string); + in-out property node-admin; + in-out property channel-admin-open; + in-out property channel-admin-operation; + in-out property channel-admin-kind; + in-out property channel-admin-name; + in-out property channel-admin-busy; + in-out property channel-admin-error; + callback create-global-channel(string); + callback rename-global-channel(string); + callback delete-global-channel(string); + callback channel-admin-name-edited(string); + callback channel-admin-submit(); + callback channel-admin-cancel(); in-out property <[ChannelItem]> channels; in-out property <[GuildItem]> guilds; in-out property <[DmItem]> dm-conversations; @@ -33,6 +119,7 @@ export component MainWindow inherits Window { in-out property avatar-offset-x; in-out property avatar-offset-y; in-out property avatar-error; + in-out property avatar-saving; private property pending-delete-id; in-out property active-dm-id; in-out property voice-connected; @@ -84,6 +171,13 @@ export component MainWindow inherits Window { in-out property vault-enabled: false; in-out property voice-input-device: ""; in-out property voice-output-device: ""; + in-out property noise-suppress; + in property noise-suppress-available; + in property mic-test-running; + in property mic-test-level; + in property mic-test-error; + callback toggle-microphone-test(); + callback noise-suppression-changed(bool); in-out property voice-bitrate: 64.0; in-out property vad-mode: 1; in-out property volume: 100.0; @@ -96,7 +190,7 @@ export component MainWindow inherits Window { callback preview-sound(); in-out property language-choice: "system"; callback language-selected(string); - in-out property theme-mode: "dark"; + in-out property theme-mode: "black"; in-out property theme-css; in-out property theme-file-path; in-out property text-size: 16; @@ -147,11 +241,21 @@ export component MainWindow inherits Window { callback open-webhooks(); callback show-voice-view(); callback show-friends-view(); + in-out property local-speaking; + callback refresh-audio-devices(); + callback device-selected(int, int); callback audio-settings-changed(int, int, float, int, float); callback channel-selected(string); callback guild-selected(int); callback dm-selected(string); callback disconnect(); + in-out property pending-image; + in-out property has-pending-image; + in-out property image-uploading; + in-out property image-status; + callback paste-image() -> bool; + callback cancel-image(); + callback send-image(); callback send-message(string, string); callback load-more(string); callback react(string, string); @@ -188,7 +292,16 @@ export component MainWindow inherits Window { background: Theme.bg-base; - if node-name == "" : ConnectScreen { + if !root.account-authenticated : AccountAuth { + signing-in: root.account-signing-in; + status: root.account-status; + public-key: root.account-public-key; + sign-in => { root.account-sign-in(); } + cancel => { root.account-cancel(); } + open-browser => { root.account-open-browser(); } + settings => { root.open-settings(); } + } + if node-name == "" && root.account-authenticated : ConnectScreen { bookmarks: root.bookmarks; address-input <=> root.address-input; status-text: root.status-text; @@ -210,12 +323,24 @@ export component MainWindow inherits Window { remove-bookmark(address) => { root.remove-bookmark(address); } add-bookmark(address) => { root.add-bookmark(address); } } - if node-name != "" : HorizontalLayout { + if node-name != "" && root.account-authenticated : HorizontalLayout { sidebar := Sidebar { + local-speaking: root.local-speaking; + input-devices: root.input-devices; output-devices: root.output-devices; + input-device-index: root.input-device-index; output-device-index: root.output-device-index; + refresh-devices => { root.refresh-audio-devices(); } + device-selected(input, output) => { root.device-selected(input, output); } channels: root.channels; guilds: root.guilds; dm-conversations: root.dm-conversations; node-name: root.node-name; + node-admin: root.node-admin; + open-node-menu(x,y) => {root.open-node-menu(x,y);} + open-channel-menu(id,x,y) => {root.open-channel-menu(id,x,y);} + toggle-category(id) => {root.toggle-category(id);} + create-global-channel(kind) => { root.create-global-channel(kind); } + rename-global-channel(id) => { root.rename-global-channel(id); } + delete-global-channel(id) => { root.delete-global-channel(id); } active-dm-id: root.active-dm-id; voice-connected: root.voice-connected; voice-channel-name: root.voice-channel-name; @@ -250,7 +375,38 @@ export component MainWindow inherits Window { VerticalLayout { alignment: center; ActionButton { text: @tr("Dismiss"); icon: "x"; width: 28px; quiet: true; clicked => { root.dismiss-status(); } } } } } - if root.show-chat : ChatPanel { + if root.show-forum : ForumPanel { + channel-name: root.forum-channel-name; + topics: root.forum-topics; replies: root.forum-replies; + topic-title: root.forum-topic-title; topic-open: root.forum-topic-open; + creating: root.forum-creating; loading: root.forum-loading; + busy: root.forum-busy; supported: root.forum-supported; + more-topics: root.forum-more-topics; more-replies: root.forum-more-replies; + error: root.forum-error; + title-draft <=> root.forum-title-draft; + body-draft <=> root.forum-body-draft; + reply-draft <=> root.forum-reply-draft; + refresh => { root.forum-refresh(); } + create => { root.forum-create(); } + cancel-create => { root.forum-cancel-create(); } + open-topic(id) => { root.forum-open-topic(id); } + back => { root.forum-back(); } + submit-topic => { root.forum-submit-topic(); } + submit-reply => { root.forum-submit-reply(); } + load-more-topics => { root.forum-load-more-topics(); } + load-more-replies => { root.forum-load-more-replies(); } + title-edited(value) => { root.forum-title-edited(value); } + body-edited(value) => { root.forum-body-edited(value); } + reply-edited(value) => { root.forum-reply-edited(value); } + } + if root.show-chat && !root.show-forum : ChatPanel { + pending-image: root.pending-image; + has-pending-image: root.has-pending-image; + image-uploading: root.image-uploading; + image-status: root.image-status; + paste-image => { return root.paste-image(); } + cancel-image => { root.cancel-image(); } + send-image => { root.send-image(); } own-avatar: root.own-avatar; has-own-avatar: root.has-avatar; active-channel-id: root.is-dm ? "" : root.active-channel-id; @@ -315,6 +471,15 @@ export component MainWindow inherits Window { own-avatar: root.own-avatar; has-avatar: root.has-avatar; avatar-error: root.avatar-error; + avatar-saving: root.avatar-saving; + account-name: root.account-name; + central-authenticated: root.account-authenticated; + profile-display-name <=> root.profile-display-name; + profile-saving: root.profile-saving; + profile-initials: root.profile-initials; + profile-error: root.profile-error; + save-profile-name(name) => { root.save-profile-name(name); } + account-sign-out => { root.account-sign-out(); root.close-settings(); } choose-avatar => { root.choose-avatar(); } remove-avatar => { root.remove-avatar(); } theme-mode <=> root.theme-mode; @@ -340,6 +505,13 @@ export component MainWindow inherits Window { vault-enabled: root.vault-enabled; voice-input-device: root.voice-input-device; voice-output-device: root.voice-output-device; + noise-suppress <=> root.noise-suppress; + noise-suppress-available: root.noise-suppress-available; + mic-test-running: root.mic-test-running; + mic-test-level: root.mic-test-level; + mic-test-error: root.mic-test-error; + toggle-microphone-test => { root.toggle-microphone-test(); } + noise-suppression-changed(enabled) => { root.noise-suppression-changed(enabled); } voice-bitrate <=> root.voice-bitrate; vad-mode <=> root.vad-mode; volume <=> root.volume; @@ -375,6 +547,17 @@ export component MainWindow inherits Window { import-keyfile(input, pass) => { root.import-keyfile(input, pass); } } + if root.account-authenticated && node-name == "" && !root.settings-open : Rectangle { + x: parent.width - self.width - 12px; y: 6px; + width: Math.min(340px, parent.width / 3); height: 32px; + background: Theme.bg-elevated; border-radius: 6px; + HorizontalLayout { + padding-left: 10px; padding-right: 4px; spacing: 8px; + Text { text: root.account-name; color: Theme.text-primary; font-size: 12px; overflow: elide; vertical-alignment: center; horizontal-stretch: 1; } + ActionButton { text: @tr("Sign out of Central"); icon: "log-out"; width: 28px; clicked => { root.account-sign-out(); } } + } + } + if root.pending-delete-id != "" : Rectangle { background: Theme.overlay; TouchArea { } @@ -401,9 +584,38 @@ export component MainWindow inherits Window { offset-x: root.avatar-offset-x; offset-y: root.avatar-offset-y; error: root.avatar-error; + saving: root.avatar-saving; crop-moved(x,y) => { root.avatar-crop-moved(x,y); } zoom-changed(value) => { root.avatar-zoom-changed(value); } confirm => { root.confirm-avatar(); } cancel => { root.cancel-avatar(); } } + if root.server-settings-open && root.node-admin && root.account-authenticated : ServerSettingsDialog { + width:parent.width;height:parent.height; + name <=>root.server-name-draft;description <=>root.server-description-draft; + busy:root.server-settings-busy;loaded:root.server-settings-loaded;error:root.server-settings-error; + channels:root.channels;structure:root.node-structure;forums:root.node-forums; + name-edited(value)=>{root.server-name-edited(value);}description-edited(value)=>{root.server-description-edited(value);} + save=>{root.server-settings-save();}reload=>{root.server-settings-reload();}close=>{root.server-settings-close();} + create(kind)=>{root.create-global-channel(kind);}rename(id)=>{root.rename-global-channel(id);}remove(id)=>{root.delete-global-channel(id);} + } + if root.channel-admin-open && root.node-admin && root.account-authenticated : ChannelAdminDialog { + width: parent.width; height: parent.height; + parent-names:root.channel-admin-parent-names;parent-index <=>root.channel-admin-parent-index;parent-selected(index)=>{root.channel-admin-parent-selected(index);} + operation: root.channel-admin-operation; + kind: root.channel-admin-kind; + name <=> root.channel-admin-name; + busy: root.channel-admin-busy; + error: root.channel-admin-error; + name-edited(value) => { root.channel-admin-name-edited(value); } + submit => { root.channel-admin-submit(); } + cancel => { root.channel-admin-cancel(); } + } + + if root.management-menu-open :ManagementMenu { + width:parent.width;height:parent.height; + actions:root.management-actions;anchor-x:root.management-menu-x;anchor-y:root.management-menu-y; + chosen(action)=>{root.management-menu-chosen(action);}dismiss=>{root.management-menu-close();} + } + } diff --git a/src/ui/slint/management-menu.slint b/src/ui/slint/management-menu.slint new file mode 100644 index 0000000..350215b --- /dev/null +++ b/src/ui/slint/management-menu.slint @@ -0,0 +1,46 @@ +import { Theme, Symbol } from "theme.slint"; +export struct ManagementAction { text: string, icon: string, action: string, danger: bool } +/// Themed embedded menu: no host window is required, including on headless platforms. +export component ManagementMenu inherits Rectangle { + in property <[ManagementAction]> actions; + in property anchor-x; + in property anchor-y; + callback chosen(string); + callback dismiss(); + private property selected: 0; + TouchArea { clicked => {root.dismiss();} pointer-event(event) => {if event.button == PointerEventButton.right && event.kind == PointerEventKind.up {root.dismiss();}} } + keyboard := FocusScope { + init => { self.focus(); } + key-pressed(event) => { + if event.text == Key.Tab { root.dismiss(); return reject; } + if event.text == Key.Escape { root.dismiss(); return accept; } + if event.text == Key.DownArrow { root.selected = Math.min(root.selected + 1, root.actions.length - 1); return accept; } + if event.text == Key.UpArrow { root.selected = Math.max(root.selected - 1, 0); return accept; } + if event.text == Key.Home { root.selected = 0; return accept; } + if event.text == Key.End { root.selected = root.actions.length - 1; return accept; } + if event.text == "\n" || event.text == " " { if root.actions.length > 0 { root.chosen(root.actions[root.selected].action); } return accept; } + return reject; + } + Rectangle { + width: 264px; height: root.actions.length * 38px + 12px; + x: Math.clamp(root.anchor-x * 1px, 8px, root.width - self.width - 8px); + y: Math.clamp(root.anchor-y * 1px, 8px, root.height - self.height - 8px); + background: Theme.bg-elevated; border-radius: 8px; border-width: 1px; border-color: Theme.border; + TouchArea { } + VerticalLayout { + padding: 6px; spacing: 2px; + for action[index] in root.actions : Rectangle { + height: 36px; border-radius: 5px; + background: pointer.has-hover || index == root.selected ? Theme.selected : transparent; + accessible-role: button; accessible-label: action.text; + HorizontalLayout { + padding-left: 10px; padding-right: 10px; spacing: 10px; + Symbol { kind: action.icon; ink: action.danger ? Theme.danger : Theme.text-secondary; width: 18px; height: 18px; y: (parent.height - self.height) / 2; } + Text { text: action.text; color: action.danger ? Theme.danger : Theme.text-primary; font-size: Math.max(12px, Theme.font-size - 2px); overflow: elide; vertical-alignment: center; horizontal-stretch: 1; } + } + pointer := TouchArea { moved => { root.selected = index; } clicked => { root.chosen(action.action); } } + } + } + } + } +} diff --git a/src/ui/slint/server-settings.slint b/src/ui/slint/server-settings.slint new file mode 100644 index 0000000..d486334 --- /dev/null +++ b/src/ui/slint/server-settings.slint @@ -0,0 +1,73 @@ +import { Theme, ActionButton } from "theme.slint"; +import { ThemeInput, ThemeEditor } from "controls.slint"; +import { ChannelItem } from "sidebar.slint"; +export component ServerSettingsDialog inherits Rectangle { + in-out property name; + in-out property description; + in property busy; + in property loaded; + in property error; + in property structure; + in property forums; + in property <[ChannelItem]> channels; + callback name-edited(string); + callback description-edited(string); + callback save(); callback reload(); callback close(); + callback create(string); callback rename(string); callback remove(string); + background: Theme.overlay; + TouchArea { } + keyboard := FocusScope { + init => { self.focus(); } + key-pressed(event) => {if event.text == Key.Escape {root.close();return accept;} return reject;} + Rectangle { + x: (root.width - self.width) / 2; y: 24px; + width: Math.min(700px,root.width - 40px); height: root.height - 48px; + background: Theme.bg-surface; border-radius: 12px; border-width: 1px; border-color: Theme.border; + VerticalLayout { + padding: 22px; spacing: 14px; + HorizontalLayout { + Text {text:@tr("Server settings");color:Theme.text-primary;font-size:Theme.font-size + 5px;font-weight:600;horizontal-stretch:1;vertical-alignment:center;} + ActionButton{text:@tr("Close");icon:"x";quiet:true;clicked=>{root.close();}} + } + Text {text:@tr("Changes apply to everyone on this server.");color:Theme.text-muted;font-size:Theme.font-size - 3px;wrap:word-wrap;} + Flickable { + content-width:self.width; + VerticalLayout { + spacing:10px; + Text{text:@tr("Server name");color:Theme.text-secondary;font-size:Theme.font-size - 2px;} + ThemeInput {read-only:root.busy;text<=>root.name;edited(value)=>{root.name-edited(value);}accepted=>{if !root.busy && root.loaded {root.save();}}} + Text{text:@tr("Description");color:Theme.text-secondary;font-size:Theme.font-size - 2px;} + ThemeEditor {monospace:false;read-only:root.busy;text<=>root.description;height:100px;edited(value)=>{if !root.busy {root.description-edited(value);}}} + HorizontalLayout { + spacing:10px; + ActionButton{text:@tr("Reload");clicked=>{if !root.busy{root.reload();}}} + Rectangle{horizontal-stretch:1;} + if root.loaded && !root.busy :ActionButton{text:@tr("Save changes");icon:"check";labeled:true;primary:true;clicked=>{root.save();}} + } + Text{text:root.busy ? @tr("Waiting for the server…") :root.error;color:root.error!=""?Theme.danger:Theme.text-muted;font-size:Theme.font-size - 3px;wrap:word-wrap;} + Rectangle{height:1px;background:Theme.border;} + Text{text:@tr("Channels and categories");color:Theme.text-primary;font-size:Theme.font-size + 1px;font-weight:600;} + HorizontalLayout { + spacing:8px; + ActionButton{text:@tr("Text");icon:"hash";labeled:true;clicked=>{root.create("text");}} + ActionButton{text:@tr("Voice");icon:"volume-2";labeled:true;clicked=>{root.create("voice");}} + if root.structure:ActionButton{text:@tr("Category");icon:"folder";labeled:true;clicked=>{root.create("category");}} + if root.forums:ActionButton{text:@tr("Forum");icon:"messages-square";labeled:true;clicked=>{root.create("forum");}} + Rectangle{horizontal-stretch:1;} + } + for channel in root.channels:Rectangle { + visible:channel.is-global;height:self.visible?38px:0px; + background:Theme.bg-interactive;border-radius:5px; + HorizontalLayout { + padding-left:10px;padding-right:6px;spacing:8px; + Text{text:channel.name;color:Theme.text-primary;vertical-alignment:center;overflow:elide;horizontal-stretch:1;font-size:Theme.font-size - 2px;} + ActionButton{text:@tr("Rename channel");icon:"pencil";quiet:true;clicked=>{root.rename(channel.channel_id);}} + ActionButton{text:@tr("Delete channel");icon:"trash-2";danger:true;quiet:true;clicked=>{root.remove(channel.channel_id);}} + } + } + } + } + } + } + } +} diff --git a/src/ui/slint/settings.slint b/src/ui/slint/settings.slint index 07ae296..c2596e2 100644 --- a/src/ui/slint/settings.slint +++ b/src/ui/slint/settings.slint @@ -31,9 +31,18 @@ component SettingsNav inherits Rectangle { } export component SettingsWindow inherits Rectangle { + in property account-name; + in property central-authenticated; + in-out property profile-display-name; + in property profile-saving; + in property profile-initials; + in property profile-error; + callback save-profile-name(string); + callback account-sign-out(); in property own-avatar; in property has-avatar; in property avatar-error; + in property avatar-saving; callback choose-avatar(); callback remove-avatar(); in property <[string]> input-devices; @@ -44,6 +53,13 @@ export component SettingsWindow inherits Rectangle { in-out property vault-enabled; in-out property voice-input-device; in-out property voice-output-device; + in-out property noise-suppress; + in property noise-suppress-available; + in property mic-test-running; + in property mic-test-level; + in property mic-test-error; + callback toggle-microphone-test(); + callback noise-suppression-changed(bool); in-out property voice-bitrate; in-out property vad-mode; in-out property volume; @@ -106,6 +122,8 @@ export component SettingsWindow inherits Rectangle { Rectangle { height: 1px; background: Theme.border; } Text { text: "VNOX"; color: Theme.text-secondary; font-size: Math.max(Theme.font-size - 3px, 11px); font-weight: 700; height: 30px; vertical-alignment: bottom; } Text { text: @tr("Settings for this device"); color: Theme.text-disabled; font-size: Math.max(Theme.font-size - 5px, 11px); } + if root.account-name != "" : Text { text: root.account-name; color: Theme.text-primary; font-size: 13px; overflow: elide; } + if root.account-name != "" : ActionButton { text: @tr("Sign out of Central"); icon: "log-out"; labeled: true; clicked => { root.account-sign-out(); } } ActionButton { text: @tr("Back to the app"); quiet: true; clicked => { root.close(); } } } } @@ -135,6 +153,13 @@ export component SettingsWindow inherits Rectangle { output-devices: root.output-devices; input-device-index <=> root.input-device-index; output-device-index <=> root.output-device-index; + noise-suppress <=> root.noise-suppress; + noise-suppress-available: root.noise-suppress-available; + mic-test-running: root.mic-test-running; + mic-test-level: root.mic-test-level; + mic-test-error: root.mic-test-error; + toggle-microphone-test => { root.toggle-microphone-test(); } + noise-suppression-changed(enabled) => { root.noise-suppression-changed(enabled); } voice-bitrate <=> root.voice-bitrate; vad-mode <=> root.vad-mode; volume <=> root.volume; @@ -171,6 +196,13 @@ export component SettingsWindow inherits Rectangle { own-avatar: root.own-avatar; has-avatar: root.has-avatar; avatar-error: root.avatar-error; + avatar-saving: root.avatar-saving; + central-authenticated: root.central-authenticated; + profile-display-name <=> root.profile-display-name; + profile-saving: root.profile-saving; + profile-initials: root.profile-initials; + profile-error: root.profile-error; + save-profile-name(name) => { root.save-profile-name(name); } choose-avatar => { root.choose-avatar(); } remove-avatar => { root.remove-avatar(); } identity-pubkey: root.identity-pubkey; diff --git a/src/ui/slint/settings/appearance.slint b/src/ui/slint/settings/appearance.slint index 319cc2a..7cd8a76 100644 --- a/src/ui/slint/settings/appearance.slint +++ b/src/ui/slint/settings/appearance.slint @@ -6,15 +6,22 @@ component ThemeChoice inherits Rectangle { in property selected; in property preview-background; in property preview-sidebar; + in property preview-rail; + in property preview-selected; + in property preview-input; in property preview-ink; in property preview-accent: #bba583; callback clicked(); height: 160px; + min-width: 0px; + preferred-width: 0px; + horizontal-stretch: 1; border-radius: 9px; border-width: keyboard.has-focus || root.selected ? 2px : 1px; border-color: root.selected || keyboard.has-focus ? Theme.accent : Theme.border; background: pointer.has-hover ? Theme.bg-hover : Theme.bg-surface; - accessible-role: button; + accessible-role: radio-button; + accessible-checked: root.selected; accessible-label: root.label; VerticalLayout { padding: 8px; spacing: 10px; @@ -28,7 +35,7 @@ component ThemeChoice inherits Rectangle { // A miniature client: server rail, channel list, conversation and composer. rail := Rectangle { x: 0px; y: 0px; - width: 17px; height: parent.height; background: root.preview-sidebar.darker(8%); + width: 17px; height: parent.height; background: root.preview-rail; Rectangle { x: 4px; y: 8px; width: 9px; height: 9px; border-radius: 3px; background: root.preview-accent; Image { source: @image-url("../assets/vnox-mark.svg"); width: 9px; height: 9px; image-fit: contain; } } @@ -39,7 +46,7 @@ component ThemeChoice inherits Rectangle { side := Rectangle { x: 17px; y: 0px; width: parent.width * 0.27; height: parent.height; background: root.preview-sidebar; Text { x: 5px; y: 7px; text: "Vnox"; color: root.preview-ink; font-size: 7px; font-weight: 700; } - Rectangle { x: 3px; y: 24px; width: parent.width - 6px; height: 13px; border-radius: 2px; background: root.preview-accent.with-alpha(0.18); + Rectangle { x: 3px; y: 24px; width: parent.width - 6px; height: 13px; border-radius: 2px; background: root.preview-selected; Text { x: 4px; text: "#"; color: root.preview-accent; font-size: 9px; vertical-alignment: center; } Rectangle { x: 14px; y: 5px; width: Math.max(parent.width - 21px, 3px); height: 3px; border-radius: 1px; background: root.preview-ink.with-alpha(0.65); } } @@ -59,7 +66,7 @@ component ThemeChoice inherits Rectangle { Rectangle { x: 7px; y: 56px; width: 10px; height: 10px; border-radius: 4px; background: root.preview-ink.with-alpha(0.22); } Rectangle { x: 23px; y: 57px; width: parent.width * 0.25; height: 3px; border-radius: 1px; background: root.preview-ink.with-alpha(0.65); } Rectangle { x: 23px; y: 65px; width: parent.width * 0.4; height: 3px; border-radius: 1px; background: root.preview-ink.with-alpha(0.25); } - Rectangle { x: 6px; y: parent.height - 23px; width: parent.width - 12px; height: 16px; border-radius: 4px; background: root.preview-sidebar; + Rectangle { x: 6px; y: parent.height - 23px; width: parent.width - 12px; height: 16px; border-radius: 4px; background: root.preview-input; Text { x: 4px; text: "+"; color: root.preview-ink.with-alpha(0.45); font-size: 10px; vertical-alignment: center; } Rectangle { x: parent.width - 12px; y: 5px; width: 6px; height: 6px; border-radius: 2px; background: root.preview-accent; } } @@ -78,6 +85,12 @@ export component AppearanceSettings inherits Rectangle { in-out property language-choice: "system"; callback language-selected(string); in-out property theme-mode; + private property selected-theme-is-light: root.theme-mode == "light" || root.theme-mode == "mist" || root.theme-mode == "glacier" || root.theme-mode == "sage" || root.theme-mode == "rose" || root.theme-mode == "sand"; + private property light-group: root.selected-theme-is-light; + // Browsing a group does not apply a theme. Restores/reset still reveal the saved selection. + changed theme-mode => { + if root.theme-mode != "custom" { root.light-group = root.selected-theme-is-light; } + } in-out property theme-css; in-out property theme-file-path; in-out property text-size; @@ -92,6 +105,8 @@ export component AppearanceSettings inherits Rectangle { callback import-theme(string); callback export-theme(string); VerticalLayout { + x: 0px; + width: Math.min(root.width, 1080px); spacing: 0; alignment: start; Text { text: @tr("Language"); color: Theme.text-primary; font-size: Theme.font-size + 2px; font-weight: 600; } Text { text: @tr("Choose your language. Changes apply immediately."); color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; } @@ -108,11 +123,51 @@ export component AppearanceSettings inherits Rectangle { Text { text: @tr("One theme for chat, rooms and settings. Change it at any time."); color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; } Rectangle { height: 20px; } HorizontalLayout { - spacing: 12px; - ThemeChoice { label: @tr("Light"); selected: root.theme-mode == "light"; preview-background: #f5f4f2; preview-sidebar: #e6e4e0; preview-ink: #353330; clicked => { root.theme-selected("light"); } } - ThemeChoice { label: @tr("Dark"); selected: root.theme-mode == "dark"; preview-background: #272729; preview-sidebar: #202022; preview-ink: #e9e7e4; clicked => { root.theme-selected("dark"); } } - ThemeChoice { label: @tr("Extra dark"); selected: root.theme-mode == "black"; preview-background: #080808; preview-sidebar: #131313; preview-ink: #dedbd5; clicked => { root.theme-selected("black"); } } - ThemeChoice { label: @tr("Custom"); selected: root.theme-mode == "custom"; preview-background: Theme.bg-base; preview-sidebar: Theme.bg-surface; preview-ink: Theme.text-primary; preview-accent: Theme.accent; clicked => { root.theme-selected("custom"); } } + spacing: 9px; + ActionButton { text: @tr("Dark themes"); icon: root.light-group ? "circle" : "check"; labeled: true; active: !root.light-group; clicked => { root.light-group = false; } } + ActionButton { text: @tr("Light themes"); icon: root.light-group ? "check" : "circle"; labeled: true; active: root.light-group; clicked => { root.light-group = true; } } + Rectangle { horizontal-stretch: 1; } + ActionButton { text: @tr("Custom"); icon: "palette"; labeled: true; active: root.theme-mode == "custom"; clicked => { root.theme-selected("custom"); } } + } + Rectangle { height: 12px; } + Rectangle { + height: 332px; + if !root.light-group : VerticalLayout { + x: 0px; y: 0px; + width: Math.min(parent.width, 1080px); + height: parent.height; + spacing: 12px; + HorizontalLayout { + spacing: 12px; + ThemeChoice { label: @tr("Extra dark"); selected: root.theme-mode == "black"; preview-background: #090909; preview-sidebar: #111111; preview-rail: #000000; preview-selected: #303030; preview-input: #202020; preview-ink: #f8f6fa; preview-accent: #d5b58a; clicked => { root.theme-selected("black"); } } + ThemeChoice { label: @tr("Graphite"); selected: root.theme-mode == "dark"; preview-background: #292b31; preview-sidebar: #1d1f25; preview-rail: #121419; preview-selected: #3b4251; preview-input: #323641; preview-ink: #f8f6fa; preview-accent: #d5b58a; clicked => { root.theme-selected("dark"); } } + ThemeChoice { label: @tr("Midnight"); selected: root.theme-mode == "midnight"; preview-background: #151f32; preview-sidebar: #10192a; preview-rail: #0b1220; preview-selected: #30425c; preview-input: #25334b; preview-ink: #f8f6fa; preview-accent: #9fc5ff; clicked => { root.theme-selected("midnight"); } } + } + HorizontalLayout { + spacing: 12px; + ThemeChoice { label: @tr("Pine"); selected: root.theme-mode == "pine"; preview-background: #172b26; preview-sidebar: #11231e; preview-rail: #0b1915; preview-selected: #304b40; preview-input: #253c34; preview-ink: #f8f6fa; preview-accent: #91d6af; clicked => { root.theme-selected("pine"); } } + ThemeChoice { label: @tr("Aubergine"); selected: root.theme-mode == "aubergine"; preview-background: #2a2031; preview-sidebar: #211827; preview-rail: #170f1c; preview-selected: #493650; preview-input: #3b2d45; preview-ink: #f8f6fa; preview-accent: #dfb0eb; clicked => { root.theme-selected("aubergine"); } } + ThemeChoice { label: @tr("Espresso"); selected: root.theme-mode == "espresso"; preview-background: #2d241f; preview-sidebar: #241c17; preview-rail: #1b140f; preview-selected: #4b3b30; preview-input: #3e3129; preview-ink: #f8f6fa; preview-accent: #e8bd8d; clicked => { root.theme-selected("espresso"); } } + } + } + if root.light-group : VerticalLayout { + x: 0px; y: 0px; + width: Math.min(parent.width, 1080px); + height: parent.height; + spacing: 12px; + HorizontalLayout { + spacing: 12px; + ThemeChoice { label: @tr("Porcelain"); selected: root.theme-mode == "light"; preview-background: #f5f4f2; preview-sidebar: #eae8e5; preview-rail: #dedbd6; preview-selected: #d8d3cb; preview-input: #ffffff; preview-ink: #28252c; preview-accent: #76532b; clicked => { root.theme-selected("light"); } } + ThemeChoice { label: @tr("Mist"); selected: root.theme-mode == "mist"; preview-background: #f2f3f7; preview-sidebar: #e7e9f0; preview-rail: #dadee9; preview-selected: #cfd5e5; preview-input: #ffffff; preview-ink: #28252c; preview-accent: #43578c; clicked => { root.theme-selected("mist"); } } + ThemeChoice { label: @tr("Glacier"); selected: root.theme-mode == "glacier"; preview-background: #eff6fa; preview-sidebar: #e0edf4; preview-rail: #d1e3ee; preview-selected: #c8e0ec; preview-input: #ffffff; preview-ink: #28252c; preview-accent: #23617e; clicked => { root.theme-selected("glacier"); } } + } + HorizontalLayout { + spacing: 12px; + ThemeChoice { label: @tr("Sage"); selected: root.theme-mode == "sage"; preview-background: #f0f6ef; preview-sidebar: #e2ecdf; preview-rail: #d3e1ce; preview-selected: #cbdcc4; preview-input: #ffffff; preview-ink: #28252c; preview-accent: #3f653b; clicked => { root.theme-selected("sage"); } } + ThemeChoice { label: @tr("Rose"); selected: root.theme-mode == "rose"; preview-background: #faf2f4; preview-sidebar: #f0e3e8; preview-rail: #e7d4dc; preview-selected: #e3ccd6; preview-input: #ffffff; preview-ink: #28252c; preview-accent: #873e5a; clicked => { root.theme-selected("rose"); } } + ThemeChoice { label: @tr("Sand"); selected: root.theme-mode == "sand"; preview-background: #faf5e9; preview-sidebar: #f0e7d3; preview-rail: #e6d9bd; preview-selected: #dfd0ae; preview-input: #ffffff; preview-ink: #28252c; preview-accent: #705018; clicked => { root.theme-selected("sand"); } } + } + } } Rectangle { height: 29px; } Rectangle { height: 1px; background: Theme.border; } diff --git a/src/ui/slint/settings/audio.slint b/src/ui/slint/settings/audio.slint index 7d459b8..6e6ebf4 100644 --- a/src/ui/slint/settings/audio.slint +++ b/src/ui/slint/settings/audio.slint @@ -1,4 +1,4 @@ -import { Theme } from "../theme.slint"; +import { Theme, ActionButton } from "../theme.slint"; import { DeviceSelect, AudioSlider } from "../controls.slint"; export component AudioSettings inherits Rectangle { @@ -6,6 +6,13 @@ export component AudioSettings inherits Rectangle { in property <[string]> output-devices; in-out property input-device-index; in-out property output-device-index; + in-out property noise-suppress; + in property noise-suppress-available; + in property mic-test-running; + in property mic-test-level; + in property mic-test-error; + callback toggle-microphone-test(); + callback noise-suppression-changed(bool); in-out property voice-bitrate; in-out property vad-mode; in-out property volume; @@ -32,6 +39,27 @@ export component AudioSettings inherits Rectangle { selected(value) => { root.audio-changed(); } } Rectangle { height: 29px; } + Text { text: @tr("Microphone test"); color: Theme.text-primary; font-size: Theme.font-size + 2px; font-weight: 600; } + Text { text: @tr("Use headphones. Hear yourself locally for up to 30 seconds. Nothing is sent to the room; voice transmission is paused during the test."); color: Theme.text-secondary; font-size: 13px; wrap: word-wrap; } + Rectangle { height: 12px; } + ActionButton { text: root.mic-test-running ? @tr("Stop microphone test") : @tr("Test microphone"); icon: "mic"; labeled: true; primary: !root.mic-test-running; danger: root.mic-test-running; clicked => { root.toggle-microphone-test(); } } + Rectangle { height: 10px; } + Rectangle { + height: 10px; background: Theme.bg-rail; border-radius: 5px; + Rectangle { width: parent.width * Math.clamp(root.mic-test-level, 0, 1); height: parent.height; background: Theme.success; border-radius: 5px; } + } + if root.mic-test-error != "" : Text { text: @tr("Microphone test failed: {}", root.mic-test-error); color: Theme.danger; font-size: 13px; wrap: word-wrap; } + Rectangle { height: 22px; } + Text { text: @tr("Noise suppression"); color: Theme.text-primary; font-size: Theme.font-size - 1px; font-weight: 600; } + Text { text: @tr("RNNoise reduces steady background noise. Compare it with the microphone test."); color: Theme.text-secondary; font-size: 13px; wrap: word-wrap; } + Rectangle { height: 8px; } + if root.noise-suppress-available : DeviceSelect { + model: [@tr("Off"), "RNNoise"]; + current-index: root.noise-suppress ? 1 : 0; + selected(value) => { root.noise-suppress = self.current-index == 1; root.noise-suppression-changed(root.noise-suppress); } + } + if !root.noise-suppress-available : Text { text: @tr("Noise suppression is not included in this build."); color: Theme.text-muted; font-size: 13px; wrap: word-wrap; } + Rectangle { height: 26px; } Rectangle { height: 1px; background: Theme.border; } Rectangle { height: 26px; } HorizontalLayout { diff --git a/src/ui/slint/settings/identity.slint b/src/ui/slint/settings/identity.slint index 00f7431..66ebcd7 100644 --- a/src/ui/slint/settings/identity.slint +++ b/src/ui/slint/settings/identity.slint @@ -6,6 +6,13 @@ export component IdentitySettings inherits Rectangle { in property own-avatar; in property has-avatar; in property avatar-error; + in property avatar-saving; + in property central-authenticated; + in-out property profile-display-name; + in property profile-saving; + in property profile-initials; + in property profile-error; + callback save-profile-name(string); callback choose-avatar(); callback remove-avatar(); in-out property identity-pubkey; @@ -30,31 +37,43 @@ export component IdentitySettings inherits Rectangle { callback import-keyfile(string, string); VerticalLayout { spacing: 0; alignment: start; + if root.central-authenticated : VerticalLayout { + spacing: 9px; alignment: start; + Text { text: @tr("Display name"); color: Theme.text-primary; font-size: Theme.font-size + 2px; font-weight: 600; } + HorizontalLayout { + spacing: 9px; + ThemeInput { text <=> root.profile-display-name; placeholder-text: @tr("Your display name"); horizontal-stretch: 1; } + ActionButton { text: root.profile-saving ? @tr("Saving...") : @tr("Save"); clicked => { root.save-profile-name(root.profile-display-name); } } + } + Text { text: @tr("Saved to Central and synced with connected members."); color: Theme.text-muted; font-size: Math.max(Theme.font-size - 4px, 11px); wrap: word-wrap; } + if root.profile-error != "" : Text { text: root.profile-error; color: Theme.danger; font-size: Math.max(11px, Theme.font-size - 3px); wrap: word-wrap; } + Rectangle { height: 16px; } + } Text { text: @tr("Profile photo"); color: Theme.text-primary; font-size: Theme.font-size + 2px; font-weight: 600; } Text { text: @tr("Choose an image and crop it for your avatar."); color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; } Rectangle { height: 18px; } HorizontalLayout { spacing: 20px; - AvatarView { width: 82px; height: 82px; source: root.own-avatar; has-source: root.has-avatar; initials: @tr("Photo"); mask: Theme.bg-base; } + AvatarView { width: 82px; height: 82px; source: root.own-avatar; has-source: root.has-avatar; initials: root.profile-initials; mask: Theme.bg-base; } VerticalLayout { spacing: 9px; alignment: center; HorizontalLayout { spacing: 9px; - ActionButton { text: root.has-avatar ? @tr("Change photo") : @tr("Choose photo"); clicked => { root.choose-avatar(); } } + ActionButton { text: root.avatar-saving ? @tr("Saving...") : root.has-avatar ? @tr("Change photo") : @tr("Choose photo"); clicked => { root.choose-avatar(); } } if root.has-avatar : ActionButton { text: @tr("Delete"); quiet: true; danger: true; clicked => { root.remove-avatar(); } } Rectangle { horizontal-stretch: 1; } } - Text { text: @tr("Currently stored only on this device."); color: Theme.text-muted; font-size: Math.max(Theme.font-size - 4px, 11px); wrap: word-wrap; } + Text { text: root.central-authenticated ? @tr("Synced with your Central account and other devices.") : @tr("Currently stored only on this device."); color: Theme.text-muted; font-size: Math.max(Theme.font-size - 4px, 11px); wrap: word-wrap; } } } + if root.avatar-error != "" : Text { text: root.avatar-error; color: Theme.danger; font-size: Math.max(11px, Theme.font-size - 3px); wrap: word-wrap; } Rectangle { height: 26px; } Rectangle { height: 1px; background: Theme.border; } Rectangle { height: 24px; } Text { text: @tr("Your key"); color: Theme.text-primary; font-size: Theme.font-size + 2px; font-weight: 600; } - Text { text: @tr("Your public key identifies your profile. You can share it; your secret key stays on this device."); color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; } + Text { text: @tr("Your public key identifies this device. Your Central account keeps your name and photo in sync."); color: Theme.text-muted; font-size: Math.max(Theme.font-size - 3px, 11px); wrap: word-wrap; } Rectangle { height: 16px; } ThemeEditor { text: root.identity-pubkey; read-only: true; height: 78px; } - if root.avatar-error != "" : Text { text: root.avatar-error; color: Theme.danger; font-size: Math.max(11px, Theme.font-size - 3px); wrap: word-wrap; } Rectangle { height: 28px; } Rectangle { height: 1px; background: Theme.border; } Rectangle { height: 24px; } diff --git a/src/ui/slint/sidebar.slint b/src/ui/slint/sidebar.slint index c9105d6..08cf442 100644 --- a/src/ui/slint/sidebar.slint +++ b/src/ui/slint/sidebar.slint @@ -1,7 +1,8 @@ +import { AudioDeviceButton } from "controls.slint"; import { AvatarView, PresenceDot } from "avatar-view.slint"; import { Theme, ActionButton, Symbol } from "theme.slint"; -export struct ChannelItem { channel_id: string, name: string, kind: string } +export struct ChannelItem { channel_id: string, name: string, kind: string, is-global: bool, parent-id: string, indented: bool, collapsed: bool } export struct GuildItem { guild_id: string, name: string, short_name: string, selected: bool } export struct DmItem { dm_id: string, name: string, unread: int } @@ -11,6 +12,15 @@ component NavRow inherits Rectangle { in property selected; in property unread; callback clicked(); + in property manageable: false; + in property category: false; + in property collapsed: false; + in property indented: false; + callback context-menu(float,float); + callback add-child(); + private property context-click: false; + callback rename(); + callback remove(); height: root.visible ? 36px : 0px; border-radius: 6px; background: selected ? Theme.selected : touch.has-hover ? Theme.bg-hover : transparent; @@ -18,16 +28,29 @@ component NavRow inherits Rectangle { border-color: Theme.accent; accessible-role: button; accessible-label: label; + touch := TouchArea { + clicked => { if !root.context-click {keyboard.focus(); root.clicked();} } + pointer-event(event) => { + if event.kind == PointerEventKind.down {root.context-click = event.button == PointerEventButton.right;} + if event.button == PointerEventButton.right && event.kind == PointerEventKind.up { + keyboard.focus(); root.context-menu((self.absolute-position.x+self.mouse-x)/1px,(self.absolute-position.y+self.mouse-y)/1px); + } + } + } HorizontalLayout { - padding-left: 10px; padding-right: 10px; spacing: 10px; - Symbol { kind: root.symbol; ink: root.selected ? Theme.text-primary : Theme.text-muted; width: 17px; height: 17px; y: (parent.height - self.height) / 2; } - Text { text: root.label; color: root.selected || root.unread > 0 ? Theme.text-primary : Theme.text-secondary; font-size: Math.max(11px, Theme.font-size * 0.875); horizontal-stretch: 1; overflow: elide; vertical-alignment: center; } + padding-left: root.indented ? 24px : 10px; padding-right: 10px; spacing: 10px; + Symbol { kind: root.category ? (root.collapsed ? "plus" : "minus") : root.symbol; ink: root.selected ? Theme.text-primary : Theme.text-muted; width: 17px; height: 17px; y: (parent.height - self.height) / 2; } + Text { text: root.label; font-weight: root.category ? 600 : 400; color: root.selected || root.unread > 0 ? Theme.text-primary : Theme.text-secondary; font-size: Math.max(11px, Theme.font-size * 0.875); horizontal-stretch: 1; overflow: elide; vertical-alignment: center; } + if root.manageable && root.category :ActionButton{text:@tr("Create channel");icon:"plus";quiet:true;width:26px;height:26px;clicked=>{root.add-child();}} + if root.manageable : ActionButton { text: @tr("Rename channel"); icon: "pencil"; quiet: true; width: 26px; height: 26px; clicked => { root.rename(); } } + if root.manageable : ActionButton { text: @tr("Delete channel"); icon: "trash-2"; quiet: true; width: 26px; height: 26px; danger: true; clicked => { root.remove(); } } if root.unread > 0 : Text { text: root.unread; color: Theme.accent; font-size: Math.max(11px, Theme.font-size * 0.75); vertical-alignment: center; font-weight: 600; } } - touch := TouchArea { clicked => { keyboard.focus(); root.clicked(); } } + keyboard := FocusScope { focus-on-click: false; key-pressed(event) => { + if event.text == Key.F10 && event.modifiers.shift {root.context-menu(root.absolute-position.x/1px,(root.absolute-position.y+root.height)/1px);return accept;} if event.text == " " || event.text == "\n" { root.clicked(); return accept; } return reject; } @@ -52,6 +75,20 @@ export component Sidebar inherits Rectangle { in-out property mic-enabled; in-out property deafened; in-out property node-name; + in property node-admin; + callback open-node-menu(float,float); + callback open-channel-menu(string,float,float); + callback toggle-category(string); + callback create-global-channel(string); + callback rename-global-channel(string); + callback delete-global-channel(string); + in property local-speaking; + in property <[string]> input-devices; + in property <[string]> output-devices; + in property input-device-index; + in property output-device-index; + callback refresh-devices(); + callback device-selected(int, int); callback channel-selected(string); callback guild-selected(int); callback dm-selected(string); @@ -93,12 +130,24 @@ export component Sidebar inherits Rectangle { border-width: 1px; border-color: Theme.border; HorizontalLayout { padding-left: 17px; padding-right: 10px; spacing: 8px; - Text { text: root.show-dms ? @tr("Direct messages") : root.active-guild-idx >= 0 && root.active-guild-idx < root.guilds.length ? root.guilds[root.active-guild-idx].name : root.node-name; color: Theme.text-primary; font-size: Math.max(11px, Theme.font-size * 1.0); font-weight: 600; overflow: elide; horizontal-stretch: 1; vertical-alignment: center; } + if !root.show-dms && root.active-guild-idx < 0 :Rectangle { + horizontal-stretch:1;background:heading-pointer.has-hover?Theme.bg-hover:transparent; + border-radius:5px;border-width:heading-keyboard.has-focus?1px:0px;border-color:Theme.accent; + accessible-role:button;accessible-label:@tr("Server menu"); + HorizontalLayout{spacing:8px; + Text{text:root.node-name;color:Theme.text-primary;font-size:Theme.font-size;font-weight:600;overflow:elide;horizontal-stretch:1;vertical-alignment:center;} + Symbol{kind:"chevron-down";width:16px;height:16px;y:(parent.height - self.height)/2;ink:Theme.text-secondary;} + } + heading-pointer:=TouchArea{clicked=>{heading-keyboard.focus();root.open-node-menu(self.absolute-position.x/1px,(self.absolute-position.y+self.height)/1px);}} + heading-keyboard:=FocusScope{key-pressed(event)=>{if event.text==" "||event.text=="\n"||event.text==Key.DownArrow{root.open-node-menu(root.absolute-position.x/1px+80,(root.absolute-position.y+56px)/1px);return accept;}return reject;}} + } + if root.show-dms || root.active-guild-idx >= 0 :Text {text:root.show-dms?@tr("Direct messages"):root.active-guild-idx { root.disconnect(); } } } } } Flickable { content-width: self.width; + TouchArea{enabled:root.node-admin&&!root.show-dms&&root.active-guild-idx<0;pointer-event(event)=>{if event.button==PointerEventButton.right&&event.kind==PointerEventKind.up{root.open-channel-menu("",(self.absolute-position.x+self.mouse-x)/1px,(self.absolute-position.y+self.mouse-y)/1px);}}} VerticalLayout { padding: 10px; spacing: 3px; if root.show-dms : NavRow { label: @tr("Friends"); symbol: "at-sign"; clicked => { root.show-friends(); } } @@ -110,19 +159,21 @@ export component Sidebar inherits Rectangle { selected: root.active-dm-id == dm.dm_id; clicked => { root.dm-selected(dm.dm_id); } } - if !root.show-dms : Text { text: @tr("Text channels"); color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.75); height: 32px; vertical-alignment: bottom; } - for ch in root.channels: NavRow { - visible: !root.show-dms && ch.kind != "voice"; - label: ch.name; - selected: root.active-channel-id == ch.channel_id; - clicked => { root.channel-selected(ch.channel_id); } + if !root.show-dms : HorizontalLayout { + height:32px; + Text{text:@tr("Channels");color:Theme.text-muted;font-size:Math.max(11px,Theme.font-size*0.75);vertical-alignment:bottom;horizontal-stretch:1;} + if root.node-admin && root.active-guild-idx < 0 :ActionButton{text:@tr("Create channel");icon:"plus";quiet:true;width:28px;clicked=>{root.open-channel-menu("",self.absolute-position.x/1px,(self.absolute-position.y+self.height)/1px);}} } - if !root.show-dms : Text { text: @tr("Voice rooms"); color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.75); height: 40px; vertical-alignment: bottom; } - for ch in root.channels: NavRow { - visible: !root.show-dms && ch.kind == "voice"; - label: ch.name; symbol: "volume-2"; - selected: root.voice-connected && root.voice-channel-name == ch.name; - clicked => { root.channel-selected(ch.channel_id); } + for ch in root.channels:NavRow { + visible:!root.show-dms; + label:ch.name;category:ch.kind=="category";collapsed:ch.collapsed;indented:ch.indented; + symbol:ch.kind=="voice"?"volume-2":ch.kind=="forum"?"messages-square":"hash"; + manageable:ch.is-global && root.node-admin && root.active-guild-idx < 0; + selected:ch.kind=="voice"?root.voice-connected&&root.voice-channel-name==ch.name:root.active-channel-id==ch.channel_id; + clicked=>{if ch.kind=="category"{root.toggle-category(ch.channel_id);}else{root.channel-selected(ch.channel_id);}} + context-menu(x,y)=>{if root.node-admin&&root.active-guild-idx<0{root.open-channel-menu(ch.channel_id,x,y);}} + add-child=>{root.open-channel-menu(ch.channel_id,self.absolute-position.x/1px,(self.absolute-position.y+self.height)/1px);} + rename=>{root.rename-global-channel(ch.channel_id);}remove=>{root.delete-global-channel(ch.channel_id);} } Rectangle { vertical-stretch: 1; } } @@ -131,7 +182,7 @@ export component Sidebar inherits Rectangle { height: 88px; background: Theme.voice-bg; border-radius: 8px; - border-width: 1px; border-color: Theme.border; + border-width: 1px; border-color: Theme.success.with-alpha(0.65); VerticalLayout { padding: 10px; spacing: 5px; HorizontalLayout { @@ -142,8 +193,8 @@ export component Sidebar inherits Rectangle { Text { text: root.voice-channel-name; color: Theme.text-secondary; font-size: Math.max(11px, Theme.font-size * 0.6875); overflow: elide; } HorizontalLayout { spacing: 6px; - ActionButton { text: @tr("Open"); clicked => { root.show-voice(); } } - ActionButton { text: @tr("Leave"); danger: true; clicked => { root.leave-voice(); } } + ActionButton { text: @tr("Open"); primary: true; clicked => { root.show-voice(); } } + ActionButton { text: @tr("Leave"); icon: "phone-off"; labeled: true; danger: true; clicked => { root.leave-voice(); } } } } } @@ -154,7 +205,7 @@ export component Sidebar inherits Rectangle { padding: 9px; spacing: 5px; Rectangle { width: 34px; - AvatarView { width: 32px; height: 32px; y: (parent.height - self.height) / 2; source: root.own-avatar; has-source: root.has-avatar; initials: root.own-initials; mask: Theme.bg-elevated; } + AvatarView { width: 32px; height: 32px; y: (parent.height - self.height) / 2; source: root.own-avatar; has-source: root.has-avatar; initials: root.own-initials; speaking: root.local-speaking; mask: Theme.bg-elevated; } PresenceDot { x: 21px; y: parent.height / 2 + 6px; presence: "online"; ring: Theme.bg-elevated; } } VerticalLayout { @@ -162,8 +213,8 @@ export component Sidebar inherits Rectangle { Text { text: root.username; color: Theme.text-primary; font-size: Math.max(11px, Theme.font-size * 0.8125); font-weight: 600; overflow: elide; } Text { text: root.user-status; color: Theme.success; font-size: Math.max(11px, Theme.font-size * 0.6875); overflow: elide; } } - VerticalLayout { alignment: center; ActionButton { text: root.mic-enabled ? @tr("Mute microphone") : @tr("Unmute microphone"); icon: root.mic-enabled ? "mic" : "mic-off"; width: 30px; danger: !root.mic-enabled; quiet: true; clicked => { root.toggle-mic(); } } } - VerticalLayout { alignment: center; ActionButton { text: root.deafened ? @tr("Undeafen") : @tr("Deafen"); icon: root.deafened ? "headphone-off" : "headphones"; width: 30px; danger: root.deafened; quiet: true; clicked => { root.toggle-deafen(); } } } + VerticalLayout { alignment: center; AudioDeviceButton { text: root.mic-enabled ? @tr("Mute microphone") : @tr("Unmute microphone"); icon: root.mic-enabled ? "mic" : "mic-off"; danger: !root.mic-enabled; model: root.input-devices; current-index: root.input-device-index; heading: @tr("Microphone"); clicked => { root.toggle-mic(); } refresh => { root.refresh-devices(); } chosen(index) => { root.device-selected(index, root.output-device-index); } } } + VerticalLayout { alignment: center; AudioDeviceButton { text: root.deafened ? @tr("Undeafen") : @tr("Deafen"); icon: root.deafened ? "headphone-off" : "headphones"; danger: root.deafened; model: root.output-devices; current-index: root.output-device-index; heading: @tr("Headphones or speakers"); clicked => { root.toggle-deafen(); } refresh => { root.refresh-devices(); } chosen(index) => { root.device-selected(root.input-device-index, index); } } } VerticalLayout { alignment: center; ActionButton { text: @tr("Settings"); icon: "settings"; width: 30px; quiet: true; clicked => { root.open-settings(); } } } } } diff --git a/src/ui/slint/theme.slint b/src/ui/slint/theme.slint index 575b47d..4ca3d2d 100644 --- a/src/ui/slint/theme.slint +++ b/src/ui/slint/theme.slint @@ -1,25 +1,25 @@ export global Theme { - in-out property bg-base: #272729; - in-out property bg-surface: #202022; - in-out property bg-rail: #151516; - in-out property bg-hover: #38383c; - in-out property bg-elevated: #303033; - in-out property bg-interactive: #343336; - in-out property selected: #3a393c; - in-out property border: #ffffff12; + in-out property bg-base: #090909; + in-out property bg-surface: #111111; + in-out property bg-rail: #000000; + in-out property bg-hover: #262626; + in-out property bg-elevated: #181818; + in-out property bg-interactive: #202020; + in-out property selected: #303030; + in-out property border: #9099a6; in-out property accent: #d5b58a; - in-out property text-primary: #e9e7e4; - in-out property text-secondary: #b8b4b1; - in-out property text-muted: #aaa29b; - in-out property text-disabled: #85817f; - in-out property danger: #e58b85; - in-out property success: #a8c1a4; + in-out property text-primary: #f8f6fa; + in-out property text-secondary: #e0dce5; + in-out property text-muted: #ccc7d2; + in-out property text-disabled: #b9b2bf; + in-out property danger: #ffb4b0; + in-out property success: #9ce3b7; in-out property font-size: 16px; out property scale: font-size / 16px; - in-out property on-accent: #29221b; - in-out property avatar-bg: #49433d; - in-out property voice-bg: #282c28; - in-out property overlay: #00000080; + in-out property on-accent: #231e19; + in-out property avatar-bg: #2f2b26; + in-out property voice-bg: #222b25; + in-out property overlay: #00000091; in-out property radius: 7px; } @@ -62,6 +62,8 @@ export component Symbol inherits Image { kind == "circle" ? @image-url("assets/icons/circle.svg") : kind == "corner-down-right" ? @image-url("assets/icons/corner-down-right.svg") : kind == "audio-lines" ? @image-url("assets/icons/audio-lines.svg") : + kind == "folder" ? @image-url("assets/icons/folder.svg") : + kind == "messages-square" ? @image-url("assets/icons/messages-square.svg") : kind == "palette" ? @image-url("assets/icons/palette.svg") : kind == "key-round" ? @image-url("assets/icons/key-round.svg") : kind == "minus" ? @image-url("assets/icons/minus.svg") : @@ -104,14 +106,15 @@ export component ActionButton inherits Rectangle { // Bubble text. Icon-only buttons show their label here by default. in property tooltip: icon != "" && !labeled ? text : ""; callback clicked(); + callback right-clicked(); min-width: 30px; horizontal-stretch: 0; preferred-width: icon == "" ? label.preferred-width + 22px : labeled ? label.preferred-width + 48px : 32px; height: 32px; border-radius: 6px; background: primary ? (touch.has-hover ? Theme.accent.brighter(8%) : Theme.accent) : active ? Theme.selected : touch.has-hover ? Theme.bg-hover : quiet ? transparent : Theme.bg-interactive; - border-width: keyboard.has-focus ? 1px : 0px; - border-color: Theme.accent; + border-width: keyboard.has-focus || !quiet ? 1px : 0px; + border-color: keyboard.has-focus ? Theme.accent : Theme.border; accessible-role: button; accessible-label: text; Symbol { visible: root.icon != ""; kind: root.icon; ink: root.primary ? Theme.on-accent : root.danger ? Theme.danger : root.active ? Theme.text-primary : Theme.text-secondary; width: 18px; height: 18px; x: root.labeled ? 12px : (parent.width - self.width) / 2; y: (parent.height - self.height) / 2; } @@ -127,7 +130,7 @@ export component ActionButton inherits Rectangle { vertical-alignment: center; overflow: elide; } - touch := TouchArea { clicked => { keyboard.focus(); root.clicked(); } } + touch := TouchArea { clicked => { keyboard.focus(); root.clicked(); } pointer-event(event) => { if event.button == PointerEventButton.right && event.kind == PointerEventKind.up { root.right-clicked(); } } } keyboard := FocusScope { focus-on-click: false; key-pressed(event) => { diff --git a/src/ui/slint/voice.slint b/src/ui/slint/voice.slint index 60351e3..0a75b50 100644 --- a/src/ui/slint/voice.slint +++ b/src/ui/slint/voice.slint @@ -1,7 +1,7 @@ import { AvatarView } from "avatar-view.slint"; import { Theme, ActionButton, Symbol, TipBubble } from "theme.slint"; -export struct VoiceMemberItem { user_id: string, nickname: string, speaking: bool, avatar_text: string, is_own: bool } +export struct VoiceMemberItem { avatar: image, has_avatar: bool, user_id: string, nickname: string, speaking: bool, avatar_text: string, is_own: bool } /// Round control of the voice room bar. `off` shows the muted state highlighted in red. component RoundControl inherits Rectangle { @@ -42,7 +42,7 @@ component ParticipantCard inherits Rectangle { in property has-own-avatar; border-radius: 16px; background: Theme.bg-elevated; - border-width: root.member.speaking ? 2px : 1px; + border-width: root.member.speaking ? 3px : 1px; border-color: root.member.speaking ? Theme.success : Theme.border; VerticalLayout { padding: 18px; spacing: 10px; alignment: center; @@ -50,7 +50,7 @@ component ParticipantCard inherits Rectangle { alignment: center; AvatarView { width: 80px; height: 80px; - source: root.own-avatar; has-source: root.has-own-avatar && root.member.is_own; + source: root.member.avatar; has-source: root.member.has_avatar; initials: root.member.avatar_text; mask: Theme.bg-elevated; speaking: root.member.speaking; } diff --git a/src/ui/sounds.rs b/src/ui/sounds.rs index 758e2fa..33e1d75 100644 --- a/src/ui/sounds.rs +++ b/src/ui/sounds.rs @@ -173,6 +173,8 @@ mod tests { ..connected_ui() }; let join = |channel: &str, user: &str| NetEvent::UserJoin { + account_id: String::new(), + avatar_url: String::new(), channel_id: channel.into(), user_id: user.into(), nickname: user.into(), diff --git a/src/ui/state/default.rs b/src/ui/state/default.rs index f2f6f0a..84f20db 100644 --- a/src/ui/state/default.rs +++ b/src/ui/state/default.rs @@ -6,6 +6,7 @@ use super::types::{ConnState, UiState, VoiceUiState}; impl Default for UiState { fn default() -> Self { Self { + central_account: None, appearance: crate::ui::appearance::AppearancePreferences::default(), conn: ConnState::Disconnected, connect_input: "127.0.0.1:7600".into(), @@ -13,6 +14,7 @@ impl Default for UiState { selected_bookmark: 0, status_msg: None, trust_prompt: None, + forum: Default::default(), channels: Vec::new(), active_channel: None, messages: Default::default(), @@ -26,6 +28,7 @@ impl Default for UiState { scroll_bottom: false, voice: VoiceUiState::Off, voice_joined_at: None, + member_profiles: Default::default(), user_names: Default::default(), rtt_ms: None, @@ -43,11 +46,16 @@ impl Default for UiState { output_device: 0, output_device_id: String::new(), output_volume: 90.0, + noise_suppress: false, + mic_test_running: false, + mic_test_level: 0.0, + mic_test_error: None, sounds: Default::default(), device_lists: Default::default(), vad_mode_chosen: false, auto_reconnect: true, + connection: Default::default(), guilds: Vec::new(), active_guild_id: None, @@ -63,6 +71,12 @@ impl Default for UiState { user_colors: HashMap::new(), private_mode: false, + node_admin: false, + node_settings_supported: false, + channel_structure_supported: false, + server_settings: Default::default(), + collapsed_categories: Default::default(), + channel_admin: Default::default(), typing_users: HashMap::new(), read_receipts: HashMap::new(), diff --git a/src/ui/state/mod.rs b/src/ui/state/mod.rs index 82ab5ca..df3fd38 100644 --- a/src/ui/state/mod.rs +++ b/src/ui/state/mod.rs @@ -41,3 +41,216 @@ impl UiState { .unwrap_or(sender_id) } } + +impl UiState { + /// Account rows retain all device subscriptions internally for voice and leave events. + pub fn account_members<'a>(&self, devices: &'a [String]) -> Vec<&'a String> { + let mut accounts = std::collections::HashSet::new(); + devices + .iter() + .filter(|device| { + let account = self + .member_profiles + .get(*device) + .map(|profile| { + if profile.0.is_empty() { + (*device).clone() + } else { + profile.0.clone() + } + }) + .unwrap_or_else(|| (*device).clone()); + accounts.insert(account) + }) + .collect() + } +} +#[cfg(test)] +mod account_presence_tests { + #[test] + fn account_row_remains_until_last_device_leaves_in_both_orders() { + for reverse in [false, true] { + let mut state = super::UiState::default(); + state + .member_profiles + .insert("device-a".into(), ("account".into(), String::new())); + state + .member_profiles + .insert("device-b".into(), ("account".into(), String::new())); + let mut devices = vec!["device-a".to_owned(), "device-b".to_owned()]; + assert_eq!(state.account_members(&devices).len(), 1); + devices.remove(usize::from(reverse)); + assert_eq!(state.account_members(&devices).len(), 1); + devices.clear(); + assert!(state.account_members(&devices).is_empty()); + } + } +} + +impl UiState { + pub fn avatar_path_for(&self, device: &str, own_device: &str) -> Option { + if device == own_device { + if let Some(account) = &self.central_account { + return Some( + account + .avatar_url + .clone() + .unwrap_or_else(|| format!("/v1/avatars/default-v2/{}", account.user_id)), + ); + } + return None; + } + self.member_profiles + .get(device) + .map(|profile| profile.1.clone()) + } +} + +#[cfg(test)] +mod avatar_profile_tests { + #[test] + fn central_own_profile_wins_and_logout_removes_own_remote_path() { + let mut state = super::UiState::default(); + state.member_profiles.insert( + "own-device".into(), + ("account".into(), "/v1/avatars/stale".into()), + ); + state.member_profiles.insert( + "other-device".into(), + ("other-account".into(), "/v1/avatars/other".into()), + ); + state.central_account = Some(crate::net::account::AccountSummary { + user_id: "account".into(), + handle: "handle".into(), + display_name: "Central Name".into(), + avatar_url: Some("/v1/avatars/current".into()), + profile_complete: true, + }); + assert_eq!( + state.avatar_path_for("own-device", "own-device").as_deref(), + Some("/v1/avatars/current") + ); + assert_eq!( + state + .avatar_path_for("other-device", "own-device") + .as_deref(), + Some("/v1/avatars/other") + ); + state.central_account.as_mut().unwrap().avatar_url = None; + assert_eq!( + state.avatar_path_for("own-device", "own-device").as_deref(), + Some("/v1/avatars/default-v2/account") + ); + state.central_account = None; + assert!(state.avatar_path_for("own-device", "own-device").is_none()); + } +} + +impl UiState { + /// Update account-backed own labels and avatar lookup without changing device identity. + pub fn apply_central_profile( + &mut self, + device: &str, + user: crate::net::account::AccountSummary, + ) { + self.user_names + .insert(device.to_owned(), user.display_name.clone()); + self.member_profiles.insert( + device.to_owned(), + ( + user.user_id.clone(), + user.avatar_url + .clone() + .unwrap_or_else(|| format!("/v1/avatars/default-v2/{}", user.user_id)), + ), + ); + self.central_account = Some(user); + } +} +#[cfg(test)] +mod refreshed_profile_tests { + #[test] + fn website_and_desktop_profile_results_update_own_ui_name_and_avatar() { + let mut state = super::UiState::default(); + let mut user = crate::net::account::AccountSummary { + user_id: "account".into(), + handle: "handle".into(), + display_name: "Old Name".into(), + avatar_url: Some("/v1/avatars/old".into()), + profile_complete: false, + }; + state.apply_central_profile("device", user.clone()); + user.display_name = "Fresh Central Name".into(); + user.avatar_url = Some("/v1/avatars/fresh".into()); + state.apply_central_profile("device", user); + assert_eq!(state.nick_for("device"), "Fresh Central Name"); + assert_eq!( + state.avatar_path_for("device", "device").as_deref(), + Some("/v1/avatars/fresh") + ); + assert_eq!(state.member_profiles["device"].0, "account"); + state.central_account = None; + assert!(state.avatar_path_for("device", "device").is_none()); + } +} + +impl UiState { + /// Apply signed gateway metadata without changing any channel/device subscription. + pub fn apply_member_profile(&mut self, profile: crate::net::wire::ProfileUpdated) { + for (device, (account, avatar)) in &mut self.member_profiles { + if account == &profile.account_id { + self.user_names + .insert(device.clone(), profile.nickname.clone()); + *avatar = profile.avatar_url.clone(); + } + } + self.user_names + .insert(profile.user_id.clone(), profile.nickname.clone()); + self.member_profiles.insert( + profile.user_id, + (profile.account_id.clone(), profile.avatar_url.clone()), + ); + if let Some(own) = self.central_account.as_mut() + && own.user_id == profile.account_id + { + own.display_name = profile.nickname; + own.avatar_url = Some(profile.avatar_url); + } + } +} + +#[cfg(test)] +mod live_profile_tests { + #[test] + fn signed_profile_updates_existing_chat_voice_devices_without_duplicates() { + let mut state = super::UiState::default(); + state.channels.push(super::Channel { + id: "general".into(), + name: "General".into(), + kind: "text".into(), + guild_id: None, + members: vec!["device-a".into(), "device-b".into()], + }); + for device in ["device-a", "device-b"] { + state + .member_profiles + .insert(device.into(), ("account".into(), "/v1/avatars/old".into())); + state.user_names.insert(device.into(), "Old Name".into()); + } + let before = state.channels[0].members.clone(); + for device in ["device-a", "device-b"] { + state.apply_member_profile(crate::net::wire::ProfileUpdated { + user_id: device.into(), + account_id: "account".into(), + nickname: "New Name".into(), + avatar_url: "/v1/avatars/new".into(), + issued_at: 100, + }); + } + assert_eq!(state.channels[0].members, before); + assert_eq!(state.account_members(&state.channels[0].members).len(), 1); + assert_eq!(state.nick_for("device-a"), "New Name"); + assert_eq!(state.nick_for("device-b"), "New Name"); + assert_eq!(state.member_profiles["device-a"].1, "/v1/avatars/new"); + } +} diff --git a/src/ui/state/models.rs b/src/ui/state/models.rs index 57e0dfc..ff07442 100644 --- a/src/ui/state/models.rs +++ b/src/ui/state/models.rs @@ -6,6 +6,8 @@ pub struct Channel { pub name: String, pub kind: String, pub guild_id: Option, + pub parent_id: Option, + pub position: i32, pub members: Vec, } diff --git a/src/ui/state/types.rs b/src/ui/state/types.rs index 1c666c9..55f1768 100644 --- a/src/ui/state/types.rs +++ b/src/ui/state/types.rs @@ -44,6 +44,7 @@ pub enum TrustPromptKind { } pub struct UiState { + pub central_account: Option, pub appearance: crate::ui::appearance::AppearancePreferences, pub conn: ConnState, pub connect_input: String, @@ -52,6 +53,7 @@ pub struct UiState { pub status_msg: Option, pub trust_prompt: Option, + pub forum: crate::ui::forum::ForumState, pub channels: Vec, pub active_channel: Option, pub messages: HashMap>, @@ -69,6 +71,7 @@ pub struct UiState { pub voice: VoiceUiState, pub voice_joined_at: Option, + pub member_profiles: HashMap, pub user_names: HashMap, pub rtt_ms: Option, @@ -90,6 +93,10 @@ pub struct UiState { /// Persisted output device id; empty is the system default. pub output_device_id: String, pub output_volume: f32, + pub noise_suppress: bool, + pub mic_test_running: bool, + pub mic_test_level: f32, + pub mic_test_error: Option, pub sounds: vnox_client::audio::sounds::SoundSettings, /// Devices behind the picker positions, as of the last enumeration. pub device_lists: vnox_client::audio::DeviceLists, @@ -97,8 +104,15 @@ pub struct UiState { pub vad_mode_chosen: bool, pub auto_reconnect: bool, + pub connection: crate::ui::connection::Preferences, pub private_mode: bool, + pub node_admin: bool, + pub node_settings_supported: bool, + pub channel_structure_supported: bool, + pub server_settings: crate::ui::server_settings::ServerSettingsState, + pub collapsed_categories: std::collections::HashSet, + pub channel_admin: crate::ui::channel_admin::AdminState, pub guilds: Vec, pub active_guild_id: Option, diff --git a/src/ui/state/voice.rs b/src/ui/state/voice.rs index 2299853..4bef8a6 100644 --- a/src/ui/state/voice.rs +++ b/src/ui/state/voice.rs @@ -44,6 +44,20 @@ impl UiState { true } + /// Leaving also cancels a join waiting on an asynchronous profile refresh. + pub fn take_voice_leave_targets(&mut self) -> Vec { + let mut targets = Vec::new(); + for id in [self.voice_target.take(), self.pending_voice_join.take()] + .into_iter() + .flatten() + { + if !targets.contains(&id) { + targets.push(id); + } + } + targets + } + /// The server refused or lost a pending join: stop showing "joining". The current session /// is left untouched. pub fn cancel_pending_voice_join(&mut self) { @@ -55,6 +69,25 @@ impl UiState { mod tests { use super::*; + #[test] + fn leaving_cancels_pending_room_and_current_room_without_duplicate_requests() { + let mut ui = UiState { + voice_target: Some("current".into()), + pending_voice_join: Some("waiting-for-profile".into()), + ..Default::default() + }; + assert_eq!( + ui.take_voice_leave_targets(), + vec!["current", "waiting-for-profile"] + ); + assert!(ui.voice_target.is_none()); + assert!(ui.pending_voice_join.is_none()); + ui.voice_target = Some("same".into()); + ui.pending_voice_join = Some("same".into()); + assert_eq!(ui.take_voice_leave_targets(), vec!["same"]); + assert!(ui.take_voice_leave_targets().is_empty()); + } + fn connected() -> UiState { UiState { conn: ConnState::Connected { diff --git a/src/ui/timestamps.rs b/src/ui/timestamps.rs new file mode 100644 index 0000000..7f0e410 --- /dev/null +++ b/src/ui/timestamps.rs @@ -0,0 +1,67 @@ +//! Message timestamps are milliseconds since Unix epoch, displayed in the local timezone. +use chrono::{DateTime, TimeZone}; + +pub fn format_at(timestamp: i64, now: &DateTime) -> String +where + T::Offset: std::fmt::Display, +{ + let Some(message) = now.timezone().timestamp_millis_opt(timestamp).single() else { + return String::new(); + }; + let pattern = if message.date_naive() == now.date_naive() { + "%H:%M" + } else { + "%d.%m.%Y %H:%M" + }; + message.format(pattern).to_string() +} + +pub fn same_day_at(first: i64, second: i64, zone: &T) -> bool { + match ( + zone.timestamp_millis_opt(first).single(), + zone.timestamp_millis_opt(second).single(), + ) { + (Some(first), Some(second)) => first.date_naive() == second.date_naive(), + _ => false, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use chrono::FixedOffset; + fn date(value: &str) -> DateTime { + DateTime::parse_from_rfc3339(value).unwrap() + } + + #[test] + fn today_is_short_and_older_messages_include_date() { + let now = date("2026-11-01T15:00:00+01:00"); + assert_eq!( + format_at(date("2026-11-01T09:05:00+01:00").timestamp_millis(), &now), + "09:05" + ); + assert_eq!( + format_at(date("2026-10-31T09:05:00+01:00").timestamp_millis(), &now), + "31.10.2026 09:05" + ); + } + + #[test] + fn local_timezone_controls_the_day_and_midnight_breaks_grouping() { + let now = date("2026-11-01T00:10:00+02:00"); + let today = date("2026-10-31T22:05:00Z").timestamp_millis(); + let yesterday = date("2026-10-31T21:59:00Z").timestamp_millis(); + assert_eq!(format_at(today, &now), "00:05"); + assert_eq!(format_at(yesterday, &now), "31.10.2026 23:59"); + assert!(!same_day_at(yesterday, today, &now.timezone())); + assert!(same_day_at(today, now.timestamp_millis(), &now.timezone())); + } + + #[test] + fn malformed_timestamp_does_not_panic_or_invent_a_time() { + let now = date("2026-11-01T15:00:00+01:00"); + assert_eq!(format_at(i64::MIN, &now), ""); + assert_eq!(format_at(i64::MAX, &now), ""); + } +} diff --git a/src/ui/update.rs b/src/ui/update.rs index db35e28..aaab504 100644 --- a/src/ui/update.rs +++ b/src/ui/update.rs @@ -8,7 +8,12 @@ use crate::ui::state::{ChatMessage, ConnState, UiState, VoiceUiState}; use crate::AppState; pub fn process_net_events(state: &mut AppState) { + crate::ui::forum::tick(&mut state.ui); + crate::ui::channel_admin::tick(&mut state.ui); + crate::ui::server_settings::tick(&mut state.ui); while let Some(event) = state.net.try_recv() { + crate::ui::channel_admin::receive(&mut state.ui, &event); + crate::ui::server_settings::receive(&mut state.ui, &event); if let Some(sound) = crate::ui::sounds::sound_for_event( &state.ui, &state.identity.pubkey_hex, @@ -17,7 +22,15 @@ pub fn process_net_events(state: &mut AppState) { ) { crate::ui::sounds::play(state, sound); } + crate::ui::forum::observe(&mut state.ui, &state.net, &event); match event { + NetEvent::ForumResult(result) => crate::ui::forum::result(&mut state.ui, result), + NetEvent::ForumChanged(event) => crate::ui::forum::changed(&mut state.ui, event), + NetEvent::NodeSettingsResult{..} => {}, + NetEvent::AccountRequired => { + state.ui.connection.authentication_required = true; + } + NetEvent::AttachmentResult(result) => crate::ui::chat_media::receive(result), NetEvent::VoiceRevoked { channel_id } => { if state.voice_channel.as_deref() == Some(channel_id.as_str()) || state.ui.voice_target.as_deref() == Some(channel_id.as_str()) @@ -52,13 +65,22 @@ pub fn process_net_events(state: &mut AppState) { node_name, restored, private_mode, + node_admin, + node_settings, + channel_structure, + forums, } => { + crate::ui::connection::connected(state); state.connection_generation = state.connection_generation.wrapping_add(1); state.ui.conn = ConnState::Connected { session_id, node_name: node_name.clone(), }; state.ui.private_mode = private_mode; + state.ui.node_admin = node_admin; + state.ui.node_settings_supported = node_settings; + state.ui.channel_structure_supported = channel_structure; + state.ui.forum.supported = forums; if restored { state.ui.status_msg = Some("Reconnected".into()); let text_channel = state.ui.active_channel.clone(); @@ -139,6 +161,7 @@ pub fn process_net_events(state: &mut AppState) { state.ui.channels.clear(); state.ui.active_channel = None; state.ui.user_names.clear(); + state.ui.member_profiles.clear(); state.ui.rtt_ms = None; state.ui.status_msg = if state.ui.trust_prompt.is_some() { None @@ -316,7 +339,7 @@ pub fn process_net_events(state: &mut AppState) { log_audio_stats(state); if let Some(pipeline) = state.audio.as_ref() { pipeline.sync_controls(vnox_client::audio::AudioSync { - mic_enabled: state.ui.mic_enabled && !state.ui.deafen, + mic_enabled: state.ui.mic_enabled && !state.ui.deafen && !state.ui.mic_test_running, vad_mode: state.ui.vad_mode, vad_threshold: 15.0, input_volume: 100.0, @@ -329,7 +352,7 @@ pub fn process_net_events(state: &mut AppState) { jitter_size: 1, adaptive_buffer: true, voice_bitrate_kbps: state.ui.voice_bitrate, - noise_suppress: false, + noise_suppress: state.ui.noise_suppress, }); state.ui.local_speaking = pipeline.local_speaking(); state.ui.remote_speaking = pipeline.remote_speaking(500); @@ -344,8 +367,10 @@ pub fn process_net_events(state: &mut AppState) { fn process_net_event(ui: &mut UiState, net: &NetHandle, event: NetEvent) { match &event { - NetEvent::ChannelState { .. } + NetEvent::ProfileUpdated(_) + | NetEvent::ChannelState { .. } | NetEvent::ChannelCreated { .. } + | NetEvent::ChannelEdited { .. } | NetEvent::ChannelDeleted { .. } | NetEvent::ChannelListEvent { .. } | NetEvent::ChatMessage { .. } @@ -353,6 +378,7 @@ fn process_net_event(ui: &mut UiState, net: &NetHandle, event: NetEvent) { | NetEvent::UserJoin { .. } | NetEvent::UserLeave { .. } | NetEvent::Error { .. } + | NetEvent::ProfileWarning { .. } | NetEvent::ReactionAdded { .. } | NetEvent::ReactionRemoved { .. } | NetEvent::MessageEdited { .. } @@ -391,9 +417,14 @@ fn process_net_event(ui: &mut UiState, net: &NetHandle, event: NetEvent) { | NetEvent::PresenceUpdated { .. } => status_handle(ui, net, event), NetEvent::VoiceRevoked { .. } + | NetEvent::AttachmentResult(_) | NetEvent::MediaEvent(_) | NetEvent::WebhookResult(_) | NetEvent::WebhookList(_) + | NetEvent::ForumResult(_) + | NetEvent::ForumChanged(_) + | NetEvent::AccountRequired + | NetEvent::NodeSettingsResult{..} | NetEvent::WebhookError(_) => unreachable!("handled before generic UI dispatch"), NetEvent::Connected { .. } | NetEvent::Disconnected { .. } @@ -457,25 +488,45 @@ fn parse_hex_color(hex: &str) -> Option { Some(hex.to_string()) } +/// Empty ChannelState is also the create acknowledgement, not permission to join/capture. +fn channel_state_confirms_join(ui: &UiState, id: &str, kind: &str, has_members: bool) -> bool { + if kind == "voice" { + ui.pending_voice_join.as_deref() == Some(id) || ui.voice_target.as_deref() == Some(id) + } else { + has_members + } +} + fn chat_handle(ui: &mut UiState, net: &NetHandle, event: NetEvent) { match event { + NetEvent::ProfileUpdated(profile) => { + ui.apply_member_profile(profile); + } NetEvent::ChannelState { channel_id, channel_name, kind, members, - guild_id, + guild_id, parent_id, position, .. } => { + let joined = channel_state_confirms_join(ui, &channel_id, &kind, !members.is_empty()); let mems: Vec = members .iter() .map(|m| { ui.user_names.insert(m.user_id.clone(), m.nickname.clone()); - m.nickname.clone() + ui.member_profiles.insert( + m.user_id.clone(), + (m.account_id.clone(), m.avatar_url.clone()), + ); + m.user_id.clone() }) .collect(); if let Some(ch) = ui.channels.iter_mut().find(|c| c.id == channel_id) { ch.members = mems; + ch.name = channel_name.clone(); + ch.parent_id = parent_id.clone(); + ch.position = position; if guild_id.is_some() { ch.guild_id = guild_id.clone(); } @@ -485,10 +536,11 @@ fn chat_handle(ui: &mut UiState, net: &NetHandle, event: NetEvent) { name: channel_name, kind: kind.clone(), guild_id: guild_id.clone(), + parent_id, position, members: mems, }); } - if kind == "voice" { + if kind == "voice" && joined { ui.voice_target = Some(channel_id.clone()); if ui.pending_voice_join.as_deref() == Some(channel_id.as_str()) { ui.pending_voice_join = None; @@ -497,35 +549,55 @@ fn chat_handle(ui: &mut UiState, net: &NetHandle, event: NetEvent) { if matches!(ui.voice, VoiceUiState::Error(_)) { ui.voice = VoiceUiState::Off; } - } else if ui.active_channel.is_none() && ui.active_dm_id.is_none() { + } else if kind != "voice" + && joined + && ui.active_channel.is_none() + && ui.active_dm_id.is_none() + { ui.select_text_channel(channel_id.clone()); } - let net = net.clone(); - let ch_id = channel_id; - tokio::spawn(async move { - net.send(NetCommand::ReadReceipt { - channel_id: ch_id, - last_read_message_id: uuid::Uuid::new_v4().to_string(), - }) - .await; - }); + if joined { + let net = net.clone(); + let ch_id = channel_id; + tokio::spawn(async move { + net.send(NetCommand::ReadReceipt { + channel_id: ch_id, + last_read_message_id: uuid::Uuid::new_v4().to_string(), + }) + .await; + }); + } } NetEvent::ChannelCreated { channel_id, channel_name, kind, - guild_id, + guild_id, parent_id, position, } => { if !ui.channels.iter().any(|c| c.id == channel_id) { ui.channels.push(crate::ui::state::Channel { id: channel_id, name: channel_name, kind, - guild_id, + guild_id, parent_id, position, members: Vec::new(), }); } } + NetEvent::ChannelEdited { + channel_id, + channel_name, parent_id, position, + } => { + if let Some(channel) = ui + .channels + .iter_mut() + .find(|channel| channel.id == channel_id) + { + channel.name = channel_name; + if let Some(parent) = parent_id { channel.parent_id = (!parent.is_empty()).then_some(parent); } + if let Some(position) = position { channel.position = position; } + } + } NetEvent::ChannelDeleted { channel_id } => { ui.channels.retain(|c| c.id != channel_id); if ui.active_channel.as_deref() == Some(&channel_id) { @@ -555,6 +627,7 @@ fn chat_handle(ui: &mut UiState, net: &NetHandle, event: NetEvent) { name: c.channel_name, kind: c.kind, guild_id: c.guild_id, + parent_id: c.parent_id, position: c.position, members, } }) @@ -579,13 +652,16 @@ fn chat_handle(ui: &mut UiState, net: &NetHandle, event: NetEvent) { channel_id, user_id, nickname, - .. + account_id, + avatar_url, } => { - ui.user_names.insert(user_id, nickname.clone()); + ui.member_profiles + .insert(user_id.clone(), (account_id, avatar_url)); + ui.user_names.insert(user_id.clone(), nickname.clone()); if let Some(ch) = ui.channels.iter_mut().find(|c| c.id == channel_id) - && !ch.members.contains(&nickname) + && !ch.members.contains(&user_id) { - ch.members.push(nickname); + ch.members.push(user_id); } } NetEvent::UserLeave { @@ -593,10 +669,7 @@ fn chat_handle(ui: &mut UiState, net: &NetHandle, event: NetEvent) { user_id, } => { if let Some(ch) = ui.channels.iter_mut().find(|c| c.id == channel_id) { - let nickname = ui.user_names.remove(&user_id); - ch.members.retain(|m| { - m != &user_id && nickname.as_deref().map(|n| m != n).unwrap_or(true) - }); + ch.members.retain(|m| m != &user_id); } } NetEvent::DmStart { @@ -651,6 +724,20 @@ fn chat_handle(ui: &mut UiState, net: &NetHandle, event: NetEvent) { .insert(channel_id, messages.into_iter().map(into_msg).collect()); ui.scroll_bottom = true; } + NetEvent::ProfileWarning { + message, + rejected_join, + } => { + // A failed background refresh still sends the valid queued join using the + // last verified profile. Cancel only a join this warning explicitly rejected. + if rejected_join + .as_deref() + .is_some_and(|channel| ui.pending_voice_join.as_deref() == Some(channel)) + { + ui.cancel_pending_voice_join(); + } + ui.status_msg = Some(crate::ui::i18n::text(&message).into()); + } NetEvent::Error { message, .. } => { ui.cancel_pending_voice_join(); if message.starts_with("media:") { @@ -916,6 +1003,13 @@ pub fn pipeline_config(channel_id: &str, state: &AppState) -> PipelineConfig { } pub fn start_voice(state: &mut AppState, channel_id: &str) { + if state + .audio_shutdown + .as_ref() + .is_some_and(|workers| workers.load(std::sync::atomic::Ordering::Acquire) != 0) + { + return; + } let cfg = pipeline_config(channel_id, state); if matches!(state.ui.voice, VoiceUiState::Error(_)) && state.last_pipeline_config.as_ref() == Some(&cfg) @@ -928,7 +1022,11 @@ pub fn start_voice(state: &mut AppState, channel_id: &str) { { return; } - state.audio = None; + if let Some(audio) = state.audio.take() { + state.audio_shutdown = Some(audio.shutdown_signal()); + state.voice_channel = None; + return; + } match vnox_client::audio::start(cfg.clone()) { Ok(pipeline) => { tracing::info!("voice active on channel {channel_id}"); @@ -962,7 +1060,9 @@ pub fn start_voice(state: &mut AppState, channel_id: &str) { } pub fn stop_voice(state: &mut AppState) { - state.audio = None; + if let Some(audio) = state.audio.take() { + state.audio_shutdown = Some(audio.shutdown_signal()); + } state.voice_channel = None; state.last_pipeline_config = None; state.ui.voice = VoiceUiState::Off; @@ -970,6 +1070,16 @@ pub fn stop_voice(state: &mut AppState) { } pub fn sync_voice_audio(state: &mut AppState) { + if state + .audio_shutdown + .as_ref() + .is_some_and(|workers| workers.load(std::sync::atomic::Ordering::Acquire) != 0) + { + return; + } + if state.microphone_test.is_some() { + return; + } if !matches!(state.ui.conn, ConnState::Connected { .. }) { stop_voice(state); return; @@ -1138,3 +1248,154 @@ mod reaction_tests { assert!(matches!(command("😀"), NetCommand::ReactionAdd { .. })); } } + +#[cfg(test)] +mod channel_creation_regressions { + use super::*; + fn state_event(id: &str, kind: &str) -> NetEvent { + NetEvent::ChannelState { + channel_id: id.into(), + channel_name: "Created".into(), + kind: kind.into(), + members: vec![], + voice_endpoint: "127.0.0.1:7601".into(), + guild_id: None, + } + } + #[tokio::test] + async fn create_and_late_cancelled_create_never_join_select_or_request_receipts() { + let identity = crate::identity::generate("fixture"); + let trust = crate::net::trust::TrustStore::load( + std::env::temp_dir().join(format!("vnox-admin-fixture-{}.json", uuid::Uuid::new_v4())), + ); + let net = crate::net::spawn_with_trust(identity, trust); + let mut ui = UiState { + voice_target: Some("existing-room".into()), + voice: VoiceUiState::Active { + channel: "existing-room".into(), + }, + ..Default::default() + }; + assert!(!channel_state_confirms_join( + &ui, "new-room", "voice", false + )); + chat_handle(&mut ui, &net, state_event("new-room", "voice")); + assert_eq!(ui.voice_target.as_deref(), Some("existing-room")); + assert_eq!( + ui.voice, + VoiceUiState::Active { + channel: "existing-room".into() + } + ); + assert!(ui.pending_voice_join.is_none()); + assert!(ui.active_channel.is_none()); + assert!(!channel_state_confirms_join(&ui, "new-text", "text", false)); + chat_handle(&mut ui, &net, state_event("new-text", "text")); + assert!(ui.active_channel.is_none()); + // A cancelled create has no active dialog/pending join when its late ACK arrives. + ui.voice_target = None; + ui.voice = VoiceUiState::Off; + chat_handle(&mut ui, &net, state_event("late-room", "voice")); + assert!(ui.voice_target.is_none()); + assert_eq!(ui.voice, VoiceUiState::Off); + // An explicit click on Join remains sufficient, including an empty fixture snapshot. + assert!(ui.request_voice_join("new-room")); + assert!(channel_state_confirms_join(&ui, "new-room", "voice", false)); + chat_handle(&mut ui, &net, state_event("new-room", "voice")); + assert_eq!(ui.voice_target.as_deref(), Some("new-room")); + assert!(ui.pending_voice_join.is_none()); + } +} + +#[cfg(test)] +mod profile_warning_regressions { + use super::*; + + fn voice_ack(channel: &str) -> NetEvent { + NetEvent::ChannelState { + channel_id: channel.into(), + channel_name: "Voice room".into(), + kind: "voice".into(), + members: vec![], + voice_endpoint: "127.0.0.1:7601".into(), + guild_id: None, + } + } + + #[tokio::test] + async fn profile_outage_warning_preserves_pending_voice_until_valid_ack_but_server_denial_cancels() + { + let identity = crate::identity::generate("profile-warning-fixture"); + let trust = crate::net::trust::TrustStore::load(std::env::temp_dir().join(format!( + "vnox-profile-warning-{}.json", + uuid::Uuid::new_v4() + ))); + let net = crate::net::spawn_with_trust(identity, trust); + let mut ui = UiState::default(); + assert!(ui.request_voice_join("voice")); + process_net_event( + &mut ui, + &net, + NetEvent::ProfileWarning { + message: "Central profile refresh failed; using last verified profile".into(), + rejected_join: None, + }, + ); + assert_eq!(ui.pending_voice_join.as_deref(), Some("voice")); + assert!(channel_state_confirms_join(&ui, "voice", "voice", false)); + process_net_event(&mut ui, &net, voice_ack("voice")); + assert_eq!(ui.voice_target.as_deref(), Some("voice")); + assert!(ui.pending_voice_join.is_none()); + + ui.voice_target = None; + assert!(ui.request_voice_join("denied-room")); + process_net_event( + &mut ui, + &net, + NetEvent::Error { + code: 1, + message: "VOICE_SPEAK permission required".into(), + }, + ); + assert!(ui.pending_voice_join.is_none()); + assert!(!channel_state_confirms_join( + &ui, + "denied-room", + "voice", + false + )); + process_net_event(&mut ui, &net, voice_ack("denied-room")); + assert!(ui.voice_target.is_none()); + } + + #[tokio::test] + async fn full_profile_queue_warning_cancels_only_the_explicitly_rejected_join() { + let identity = crate::identity::generate("profile-queue-fixture"); + let trust = crate::net::trust::TrustStore::load( + std::env::temp_dir().join(format!("vnox-profile-queue-{}.json", uuid::Uuid::new_v4())), + ); + let net = crate::net::spawn_with_trust(identity, trust); + let mut ui = UiState::default(); + assert!(ui.request_voice_join("accepted-room")); + for rejected_join in [None, Some("another-room".into())] { + process_net_event( + &mut ui, + &net, + NetEvent::ProfileWarning { + message: "Too many pending profile actions; retry shortly".into(), + rejected_join, + }, + ); + assert_eq!(ui.pending_voice_join.as_deref(), Some("accepted-room")); + } + process_net_event( + &mut ui, + &net, + NetEvent::ProfileWarning { + message: "Too many pending profile actions; retry shortly".into(), + rejected_join: Some("accepted-room".into()), + }, + ); + assert!(ui.pending_voice_join.is_none()); + } +} diff --git a/src/ui_smoke.rs b/src/ui_smoke.rs index c12e630..38b0be1 100644 --- a/src/ui_smoke.rs +++ b/src/ui_smoke.rs @@ -23,8 +23,8 @@ fn snapshot_scale() -> u32 { fn render(window: &MainWindow, surface: &MinimalSoftwareWindow, name: &str) { window.window().request_redraw(); - let scale = snapshot_scale(); - let (width, height) = (1280 * scale, 800 * scale); + let size = window.window().size(); + let (width, height) = (size.width, size.height); let mut pixels = SharedPixelBuffer::::new(width, height); assert!(surface.draw_if_needed(|renderer| { renderer.render(pixels.make_mut_slice(), width as usize); @@ -81,14 +81,14 @@ fn native_shell_keeps_drafts_settings_and_models_between_ticks() { name: "общий".into(), kind: "text".into(), guild_id: None, - members: vec!["Локи".into()], + members: vec![identity.pubkey_hex.clone()], }, ui::state::Channel { id: "lounge".into(), name: "Общая".into(), kind: "voice".into(), guild_id: None, - members: vec!["Локи".into()], + members: vec![identity.pubkey_hex.clone()], }, ]; ui.user_names @@ -102,6 +102,9 @@ fn native_shell_keeps_drafts_settings_and_models_between_ticks() { reply_to: None, }]); let state = Rc::new(RefCell::new(AppState { + audio_shutdown: None, + microphone_test: None, + device_refresh: Default::default(), webhooks: None, connection_generation: 0, identity, @@ -112,7 +115,9 @@ fn native_shell_keeps_drafts_settings_and_models_between_ticks() { last_pipeline_config: None, })); let window = MainWindow::new().unwrap(); + window.set_account_authenticated(true); wire_signals(&window, &state); + ui::chat_media::wire(&window, &state); let sync = || { let s = state.borrow(); ui::bridge::sync_ui( @@ -140,6 +145,27 @@ fn native_shell_keeps_drafts_settings_and_models_between_ticks() { }); surface.set_size(PhysicalSize::new(1280 * scale, 800 * scale)); render(&window, &surface, "native-chat"); + // Render the actual native image row and an explicit composer preview together. + let photo_bytes: Vec = (0..160 * 100) + .flat_map(|pixel| [(pixel % 160) as u8, 90, (pixel / 160) as u8, 255]) + .collect(); + let chat_photo = + slint::Image::from_rgba8(SharedPixelBuffer::clone_from_slice(&photo_bytes, 160, 100)); + let original_row = window.get_messages().row_data(0).unwrap(); + let mut media_row = original_row.clone(); + media_row.media_image = chat_photo.clone(); + media_row.media_ready = true; + media_row.media_ratio = 1.6; + window.get_messages().set_row_data(0, media_row); + window.set_pending_image(chat_photo); + window.set_has_pending_image(true); + window.set_image_status("Image ready. Send it to this channel or cancel.".into()); + render(&window, &surface, "native-chat-image-preview"); + window.invoke_cancel_image(); + assert!(!window.get_has_pending_image()); + assert!(window.get_image_status().is_empty()); + window.get_messages().set_row_data(0, original_row); + sync(); // Hovering a message reveals the action bar with reply, edit, delete and reactions. window.window().dispatch_event(WindowEvent::PointerMoved { @@ -281,7 +307,7 @@ fn native_shell_keeps_drafts_settings_and_models_between_ticks() { window.invoke_open_settings(); sync(); window.set_active_tab("appearance".into()); - for mode in ["light", "dark", "black"] { + for mode in ui::appearance::BUILTIN_THEME_IDS { window.invoke_theme_selected(mode.into()); assert_eq!(state.borrow().ui.appearance.mode, mode); let expected = ui::appearance::ThemeSpec::builtin(mode).colors[0].color(); @@ -327,7 +353,7 @@ fn native_shell_keeps_drafts_settings_and_models_between_ticks() { "invalid CSS must leave the palette intact" ); window.invoke_reset_theme(); - assert_eq!(state.borrow().ui.appearance.mode, "dark"); + assert_eq!(state.borrow().ui.appearance.mode, "black"); window.set_active_tab("identity".into()); let rgba = (0..320 * 240) .flat_map(|i| { @@ -407,16 +433,27 @@ fn native_shell_keeps_drafts_settings_and_models_between_ticks() { state.ui.voice = ui::state::VoiceUiState::Active { channel: "lounge".into(), }; + state.ui.local_speaking = true; } window.invoke_show_voice_view(); sync(); assert!(window.get_show_voice()); assert!(window.get_voice_connected()); + assert!(window.get_local_speaking()); + let own_voice = window.get_voice_members().row_data(0).unwrap(); + assert!(own_voice.is_own); + assert!( + own_voice.speaking, + "local speaking must highlight our own voice card" + ); render(&window, &surface, "native-voice"); // Every screen must render with all built-in themes and the custom one, without leftovers // of the default palette (grey patches, wrong backgrounds). Snapshots are reviewed by eye. let forest = include_str!("../examples/themes/forest.css"); - for mode in ["light", "dark", "black", "custom"] { + for mode in ui::appearance::BUILTIN_THEME_IDS + .into_iter() + .chain(["custom"]) + { window.invoke_theme_selected(mode.into()); if mode == "custom" { window.set_theme_css(forest.into()); @@ -451,5 +488,96 @@ fn native_shell_keeps_drafts_settings_and_models_between_ticks() { sync(); window.set_address_input("127.0.0.1:7600".into()); render(&window, &surface, "native-connect"); + window.set_settings_open(true); + window.set_active_tab("appearance".into()); + for mode in ["black", "light"] { + window.invoke_theme_selected(mode.into()); + for width in [1024, 1280, 1920] { + surface.set_size(PhysicalSize::new(width * scale, 800 * scale)); + render(&window, &surface, &format!("theme-grid-{mode}-{width}")); + } + } + // Synthetic node administrator: no real Central account or gateway is used. + window.set_settings_open(false); + surface.set_size(PhysicalSize::new(1280 * scale, 800 * scale)); + { + let mut s = state.borrow_mut(); + s.ui.conn = ConnState::Connected { + session_id: "admin-fixture".into(), + node_name: "QA node".into(), + }; + s.ui.node_admin = true; + s.ui.central_account = Some(net::account::AccountSummary { + user_id: "f10ca6c3-296a-40f6-a420-8a097d401e26".into(), + handle: "qa_fixture".into(), + display_name: "QA fixture".into(), + avatar_url: Some("fixture-only-no-network".into()), + profile_complete: false, + }); + s.ui.active_guild_id = None; + s.ui.browsing_dms = false; + } + sync(); + assert!(window.get_node_admin()); + render(&window, &surface, "node-admin-sidebar"); + click(&window, 307.0, 163.0); + sync(); + assert!( + window.get_channel_admin_open(), + "voice plus must open on the first click" + ); + assert_eq!(window.get_channel_admin_kind(), "voice"); + window.invoke_channel_admin_name_edited("QA voice room".into()); + sync(); + render(&window, &surface, "node-admin-create-voice"); + window.invoke_channel_admin_submit(); + sync(); + assert!(window.get_channel_admin_busy()); + { + let mut s = state.borrow_mut(); + ui::channel_admin::receive( + &mut s.ui, + &net::NetEvent::Error { + code: 1, + message: "QA permission denied".into(), + }, + ); + } + sync(); + assert!(!window.get_channel_admin_busy()); + assert_eq!(window.get_channel_admin_name(), "QA voice room"); + assert!(!window.get_channel_admin_error().is_empty()); + render(&window, &surface, "node-admin-error"); + window.invoke_channel_admin_cancel(); + sync(); + render(&window, &surface, "node-admin-before-rename"); + click(&window, 263.0, 117.0); + sync(); + assert!(window.get_channel_admin_open()); + render(&window, &surface, "node-admin-rename"); + window.invoke_channel_admin_cancel(); + sync(); + render(&window, &surface, "node-admin-before-delete"); + click(&window, 299.0, 117.0); + sync(); + assert!(window.get_channel_admin_open()); + assert!( + !window.get_channel_admin_busy(), + "opening delete must only ask for confirmation" + ); + render(&window, &surface, "node-admin-delete-confirm"); + window.invoke_channel_admin_cancel(); + sync(); + render(&window, &surface, "node-admin-before-text"); + click(&window, 307.0, 85.0); + sync(); + assert!(window.get_channel_admin_open()); + assert_eq!(window.get_channel_admin_kind(), "text"); + render(&window, &surface, "node-admin-create-text"); + state.borrow_mut().ui.node_admin = false; + ui::channel_admin::tick(&mut state.borrow_mut().ui); + sync(); + assert!(!window.get_node_admin()); + assert!(!window.get_channel_admin_open()); window.hide().unwrap(); } diff --git a/tests/clipboard_shortcuts.rs b/tests/clipboard_shortcuts.rs new file mode 100644 index 0000000..4cb0737 --- /dev/null +++ b/tests/clipboard_shortcuts.rs @@ -0,0 +1,4 @@ +// Exercise the vendored backend's policy in ordinary workspace CI as well as +// its own unit tests; dependency unit tests are not run by cargo test here. +#[path = "../patches/i-slint-backend-winit/keyboard_shortcuts.rs"] +mod keyboard_shortcuts; diff --git a/translations/en/LC_MESSAGES/vnox-client.po b/translations/en/LC_MESSAGES/vnox-client.po index d9a49cf..df784df 100644 --- a/translations/en/LC_MESSAGES/vnox-client.po +++ b/translations/en/LC_MESSAGES/vnox-client.po @@ -5,6 +5,9 @@ msgstr "Content-Type: text/plain; charset=UTF-8\nLanguage: en\nPlural-Forms: npl msgid " · edited" msgstr " · edited" +msgid "A Central account is required to connect to servers. Your private identity key stays on this device." +msgstr "A Central account is required to connect to servers. Your private identity key stays on this device." + msgid "Accept" msgstr "Accept" @@ -47,6 +50,9 @@ msgstr "Appearance" msgid "Apply" msgstr "Apply" +msgid "Aubergine" +msgstr "Aubergine" + msgid "Audio & microphone" msgstr "Audio & microphone" @@ -97,6 +103,9 @@ msgstr "Change passphrase" msgid "Change photo" msgstr "Change photo" +msgid "Channel name" +msgstr "Channel name" + msgid "Channel webhooks" msgstr "Channel webhooks" @@ -154,6 +163,15 @@ msgstr "Copy this content into a file and keep it separately from this device." msgid "Create backup" msgstr "Create backup" +msgid "Create channel" +msgstr "Create channel" + +msgid "Create text channel" +msgstr "Create text channel" + +msgid "Create voice room" +msgstr "Create voice room" + msgid "Create webhook" msgstr "Create webhook" @@ -166,8 +184,8 @@ msgstr "Currently stored only on this device." msgid "Custom" msgstr "Custom" -msgid "Dark" -msgstr "Dark" +msgid "Dark themes" +msgstr "Dark themes" msgid "Deafen" msgstr "Deafen" @@ -178,9 +196,18 @@ msgstr "Decline" msgid "Delete" msgstr "Delete" +msgid "Delete channel" +msgstr "Delete channel" + +msgid "Delete channel?" +msgstr "Delete channel?" + msgid "Delete message?" msgstr "Delete message?" +msgid "Delete “{}”? This removes the channel for everyone on this server." +msgstr "Delete “{}”? This removes the channel for everyone on this server." + msgid "Device security" msgstr "Device security" @@ -199,6 +226,9 @@ msgstr "Disconnect from server" msgid "Dismiss" msgstr "Dismiss" +msgid "Display name" +msgstr "Display name" + msgid "Drag the photo and adjust the zoom." msgstr "Drag the photo and adjust the zoom." @@ -217,6 +247,9 @@ msgstr "Enter a local .css path to import or export a theme." msgid "Enter your server address or choose a saved server." msgstr "Enter your server address or choose a saved server." +msgid "Espresso" +msgstr "Espresso" + msgid "Export" msgstr "Export" @@ -247,6 +280,12 @@ msgstr "Gestures" msgid "GitHub updates" msgstr "GitHub updates" +msgid "Glacier" +msgstr "Glacier" + +msgid "Graphite" +msgstr "Graphite" + msgid "Headphones or speakers" msgstr "Headphones or speakers" @@ -322,8 +361,8 @@ msgstr "Leave room" msgid "Less bandwidth" msgstr "Less bandwidth" -msgid "Light" -msgstr "Light" +msgid "Light themes" +msgstr "Light themes" msgid "Like" msgstr "Like" @@ -358,9 +397,21 @@ msgstr "Microphone" msgid "Microphone is transmitting" msgstr "Microphone is transmitting" +msgid "Microphone test" +msgstr "Microphone test" + +msgid "Microphone test failed: {}" +msgstr "Microphone test failed: {}" + msgid "Microphone uses your existing voice controls. This preview never enables or mixes it." msgstr "Microphone uses your existing voice controls. This preview never enables or mixes it." +msgid "Midnight" +msgstr "Midnight" + +msgid "Mist" +msgstr "Mist" + msgid "Mute broadcast" msgstr "Mute broadcast" @@ -403,6 +454,12 @@ msgstr "No saved servers yet." msgid "No webhooks yet. Add an integration below." msgstr "No webhooks yet. Add an integration below." +msgid "Noise suppression" +msgstr "Noise suppression" + +msgid "Noise suppression is not included in this build." +msgstr "Noise suppression is not included in this build." + msgid "Nothing found" msgstr "Nothing found" @@ -412,6 +469,9 @@ msgstr "Nothing is being broadcast" msgid "Objects and activities" msgstr "Objects and activities" +msgid "Off" +msgstr "Off" + msgid "One application" msgstr "One application" @@ -442,18 +502,24 @@ msgstr "Open a friend's profile to send a message." msgid "Open microphone" msgstr "Open microphone" +msgid "Open sign-in page" +msgstr "Open sign-in page" + msgid "Outgoing events" msgstr "Outgoing events" msgid "Passphrase protected" msgstr "Passphrase protected" -msgid "Photo" -msgstr "Photo" +msgid "Paste image" +msgstr "Paste image" msgid "Photo crop area. Drag the image to adjust the crop." msgstr "Photo crop area. Drag the image to adjust the crop." +msgid "Pine" +msgstr "Pine" + msgid "Play a test sound" msgstr "Play a test sound" @@ -463,6 +529,9 @@ msgstr "Play sounds" msgid "Playback volume for voice rooms." msgstr "Playback volume for voice rooms." +msgid "Porcelain" +msgstr "Porcelain" + msgid "Preview" msgstr "Preview" @@ -487,6 +556,9 @@ msgstr "Profile photo" msgid "Push to talk" msgstr "Push to talk" +msgid "RNNoise reduces steady background noise. Compare it with the microphone test." +msgstr "RNNoise reduces steady background noise. Compare it with the microphone test." + msgid "Receive updates here, or send signed channel events to your own service." msgstr "Receive updates here, or send signed channel events to your own service." @@ -505,6 +577,9 @@ msgstr "Remove passphrase" msgid "Remove saved server" msgstr "Remove saved server" +msgid "Rename channel" +msgstr "Rename channel" + msgid "Repeat backup passphrase" msgstr "Repeat backup passphrase" @@ -535,6 +610,9 @@ msgstr "Revoke this webhook?" msgid "Revoke webhook" msgstr "Revoke webhook" +msgid "Rose" +msgstr "Rose" + msgid "Rotate" msgstr "Rotate" @@ -544,9 +622,21 @@ msgstr "Rotate secret" msgid "Rotate this secret?" msgstr "Rotate this secret?" +msgid "Sage" +msgstr "Sage" + +msgid "Sand" +msgstr "Sand" + +msgid "Save" +msgstr "Save" + msgid "Save address" msgstr "Save address" +msgid "Save name" +msgstr "Save name" + msgid "Save passphrase" msgstr "Save passphrase" @@ -556,6 +646,12 @@ msgstr "Save this secret now" msgid "Saved servers" msgstr "Saved servers" +msgid "Saved to Central and synced with connected members." +msgstr "Saved to Central and synced with connected members." + +msgid "Saving..." +msgstr "Saving..." + msgid "Screen capture is not available in this build." msgstr "Screen capture is not available in this build." @@ -571,6 +667,9 @@ msgstr "Security and backup" msgid "Send" msgstr "Send" +msgid "Send image" +msgstr "Send image" + msgid "Server address" msgstr "Server address" @@ -592,6 +691,15 @@ msgstr "Share audio" msgid "Short tones for voice rooms, messages and connection changes. They stay silent while you are deafened." msgstr "Short tones for voice rooms, messages and connection changes. They stay silent while you are deafened." +msgid "Sign in through browser" +msgstr "Sign in through browser" + +msgid "Sign in to Central" +msgstr "Sign in to Central" + +msgid "Sign out of Central" +msgstr "Sign out of Central" + msgid "Smileys" msgstr "Smileys" @@ -619,9 +727,15 @@ msgstr "Stop" msgid "Stop broadcast" msgstr "Stop broadcast" +msgid "Stop microphone test" +msgstr "Stop microphone test" + msgid "Stop watching" msgstr "Stop watching" +msgid "Synced with your Central account and other devices." +msgstr "Synced with your Central account and other devices." + msgid "System default" msgstr "System default" @@ -631,6 +745,9 @@ msgstr "System output" msgid "System output includes notifications and other applications. Select it only if you intend to share all of that output." msgstr "System output includes notifications and other applications. Select it only if you intend to share all of that output." +msgid "Test microphone" +msgstr "Test microphone" + msgid "Text channels" msgstr "Text channels" @@ -685,6 +802,9 @@ msgstr "Unmute broadcast" msgid "Unmute microphone" msgstr "Unmute microphone" +msgid "Use headphones. Hear yourself locally for up to 30 seconds. Nothing is sent to the room; voice transmission is paused during the test." +msgstr "Use headphones. Hear yourself locally for up to 30 seconds. Nothing is sent to the room; voice transmission is paused during the test." + msgid "Use photo" msgstr "Use photo" @@ -736,6 +856,9 @@ msgstr "Webhook secret" msgid "Webhooks" msgstr "Webhooks" +msgid "Your display name" +msgstr "Your display name" + msgid "Your key" msgstr "Your key" @@ -754,8 +877,8 @@ msgstr "Your preview appears here after you choose a source." msgid "Your profile, kept safe." msgstr "Your profile, kept safe." -msgid "Your public key identifies your profile. You can share it; your secret key stays on this device." -msgstr "Your public key identifies your profile. You can share it; your secret key stays on this device." +msgid "Your public key identifies this device. Your Central account keeps your name and photo in sync." +msgstr "Your public key identifies this device. Your Central account keeps your name and photo in sync." msgid "Your server. Your community." msgstr "Your server. Your community." diff --git a/translations/ru.json b/translations/ru.json index a06671c..7a50b7c 100644 --- a/translations/ru.json +++ b/translations/ru.json @@ -1,4 +1,23 @@ { + "Central profile refresh failed; using last verified profile": "Не удалось обновить профиль Central; используется последний проверенный профиль", + "Too many pending profile actions; retry shortly": "Слишком много ожидающих действий; повторите чуть позже", + "Saved to Central and synced with connected members.": "Сохраняется в Central и синхронизируется с подключёнными участниками.", + "Central could not update your profile; retry shortly": "Не удалось обновить профиль в Central; повторите чуть позже", + "Too many profile changes or Central is busy; retry shortly": "Слишком много изменений или Central занят; повторите чуть позже", + "Central could not read this photo; choose another PNG": "Central не удалось прочитать фото; выберите другой PNG", + "Photo is too large to upload": "Фото слишком велико для загрузки", + "Display name must contain 1–64 characters without control characters": "Имя должно содержать от 1 до 64 символов без управляющих знаков", + "Cannot reach Central; profile was not changed": "Central недоступен; профиль не изменён", + "Unlock your identity to change your profile": "Разблокируйте устройство для изменения профиля", + "Account changed. Choose your photo again.": "Аккаунт изменился. Выберите фото ещё раз.", + "Your public key identifies this device. Your Central account keeps your name and photo in sync.": "Открытый ключ идентифицирует это устройство. Имя и фото синхронизируются через аккаунт Central.", + "Synced with your Central account and other devices.": "Синхронизируется с аккаунтом Central и другими устройствами.", + "Saved to Central. Other members see the new name after you reconnect.": "Сохраняется в Central. Другие участники увидят новое имя после вашего переподключения.", + "Your display name": "Ваше отображаемое имя", + "Could not save photo. Try again.": "Не удалось сохранить фото. Попробуйте ещё раз.", + "Could not save profile. Try again.": "Не удалось сохранить профиль. Попробуйте ещё раз.", + "Saving...": "Сохранение…", + "Change your profile photo in Central.": "Измените фото профиля в Central.", " · edited": " · изменено", "Reply": "Ответить", "Edit": "Править", @@ -289,7 +308,7 @@ "Capture failed: {error}": "Ошибка захвата: {error}", "Channel webhooks": "Вебхуки канала", "Receive updates here, or send signed channel events to your own service.": "Получайте обновления в этом канале или отправляйте подписанные события в свой сервис.", - "Waiting for the server…": "Ожидание ответа сервера…", + "Waiting for the server…": "Ожидаем ответ сервера…", "Save this secret now": "Сохраните секрет сейчас", "It is shown once. Closing this window or hiding it removes it from the client.": "Секрет показывается один раз. После закрытия окна или скрытия он удаляется из клиента.", "Webhook secret": "Секрет вебхука", @@ -401,5 +420,54 @@ "{n} участника", "{n} участников" ], - "Friend ID": "ID друга" + "Friend ID": "ID друга", + "Microphone test": "Проверка микрофона", + "Use headphones. Hear yourself locally for up to 30 seconds. Nothing is sent to the room; voice transmission is paused during the test.": "Используйте наушники. До 30 секунд вы слышите себя локально. Звук не отправляется в комнату; передача голоса на время проверки приостанавливается.", + "Stop microphone test": "Остановить проверку", + "Test microphone": "Проверить микрофон", + "Microphone test failed: {}": "Ошибка проверки микрофона: {}", + "Noise suppression": "Шумоподавление", + "RNNoise reduces steady background noise. Compare it with the microphone test.": "RNNoise уменьшает постоянный фоновый шум. Сравните звук во время проверки микрофона.", + "Off": "Выключено", + "Noise suppression is not included in this build.": "Шумоподавление недоступно в этой сборке.", + "Sign in to Central": "Войдите в Central", + "A Central account is required to connect to servers. Your private identity key stays on this device.": "Для подключения к серверам нужен аккаунт Central. Секретный ключ вашей identity остаётся на этом устройстве.", + "Sign in through browser": "Войти через браузер", + "Open sign-in page": "Открыть страницу входа", + "Sign out of Central": "Выйти из Central", + "Preparing browser sign-in...": "Подготовка входа через браузер…", + "Sign-in cancelled.": "Вход отменён.", + "Confirm this device in your browser. Compare the public key before approving.": "Подтвердите устройство в браузере. Перед подтверждением сравните открытый ключ.", + "Cancelling sign-in...": "Отмена входа…", + "Signing out...": "Выход из аккаунта…", + "Dark themes": "Тёмные темы", + "Light themes": "Светлые темы", + "Graphite": "Графит", + "Midnight": "Полночь", + "Pine": "Хвоя", + "Aubergine": "Баклажан", + "Espresso": "Эспрессо", + "Porcelain": "Фарфор", + "Mist": "Дымка", + "Glacier": "Ледник", + "Sage": "Шалфей", + "Rose": "Роза", + "Sand": "Песок", + "Paste image": "Вставить изображение", + "Send image": "Отправить изображение", + "Display name": "Отображаемое имя", + "Save": "Сохранить", + "Delete channel?": "Удалить канал?", + "Rename channel": "Переименовать канал", + "Create voice room": "Создать голосовую комнату", + "Create text channel": "Создать текстовый канал", + "Delete “{}”? This removes the channel for everyone on this server.": "Удалить «{}»? Канал будет удалён для всех на этом сервере.", + "Channel name": "Название канала", + "Delete channel": "Удалить канал", + "Save name": "Сохранить название", + "Create channel": "Создать канал", + "This global channel is no longer available.": "Этот глобальный канал больше недоступен.", + "Enter a channel name (1–100 characters, no control characters).": "Введите название канала: 1–100 символов без управляющих символов.", + "No confirmation received. Close this dialog and check the channel list before trying again.": "Подтверждение не получено. Закройте диалог и проверьте список каналов перед повторной попыткой.", + "Your name and photo are saved to your Central account.": "Имя и фото сохраняются в твоём аккаунте Central." } diff --git a/translations/ru/LC_MESSAGES/vnox-client.po b/translations/ru/LC_MESSAGES/vnox-client.po index d22255f..ae5ae66 100644 --- a/translations/ru/LC_MESSAGES/vnox-client.po +++ b/translations/ru/LC_MESSAGES/vnox-client.po @@ -5,6 +5,9 @@ msgstr "Content-Type: text/plain; charset=UTF-8\nLanguage: ru\nPlural-Forms: npl msgid " · edited" msgstr " · изменено" +msgid "A Central account is required to connect to servers. Your private identity key stays on this device." +msgstr "Для подключения к серверам нужен аккаунт Central. Секретный ключ вашей identity остаётся на этом устройстве." + msgid "Accept" msgstr "Принять" @@ -47,6 +50,9 @@ msgstr "Внешний вид" msgid "Apply" msgstr "Применить" +msgid "Aubergine" +msgstr "Баклажан" + msgid "Audio & microphone" msgstr "Звук и микрофон" @@ -98,6 +104,9 @@ msgstr "Изменить пароль" msgid "Change photo" msgstr "Изменить фото" +msgid "Channel name" +msgstr "Название канала" + msgid "Channel webhooks" msgstr "Вебхуки канала" @@ -155,6 +164,15 @@ msgstr "Скопируй содержимое в файл и сохрани от msgid "Create backup" msgstr "Создать копию" +msgid "Create channel" +msgstr "Создать канал" + +msgid "Create text channel" +msgstr "Создать текстовый канал" + +msgid "Create voice room" +msgstr "Создать голосовую комнату" + msgid "Create webhook" msgstr "Создать вебхук" @@ -167,8 +185,8 @@ msgstr "Пока хранится только на этом устройств msgid "Custom" msgstr "Своя тема" -msgid "Dark" -msgstr "Тёмная" +msgid "Dark themes" +msgstr "Тёмные темы" msgid "Deafen" msgstr "Выключить звук" @@ -179,9 +197,18 @@ msgstr "Отклонить" msgid "Delete" msgstr "Удалить" +msgid "Delete channel" +msgstr "Удалить канал" + +msgid "Delete channel?" +msgstr "Удалить канал?" + msgid "Delete message?" msgstr "Удалить сообщение?" +msgid "Delete “{}”? This removes the channel for everyone on this server." +msgstr "Удалить «{}»? Канал будет удалён для всех на этом сервере." + msgid "Device security" msgstr "Защита на устройстве" @@ -200,6 +227,9 @@ msgstr "Отключиться от сервера" msgid "Dismiss" msgstr "Скрыть" +msgid "Display name" +msgstr "Отображаемое имя" + msgid "Drag the photo and adjust the zoom." msgstr "Перетащи фото и выбери масштаб." @@ -218,6 +248,9 @@ msgstr "Введи локальный путь к .css, чтобы импорт msgid "Enter your server address or choose a saved server." msgstr "Введи адрес своего сервера или выбери сохранённый." +msgid "Espresso" +msgstr "Эспрессо" + msgid "Export" msgstr "Экспортировать" @@ -248,6 +281,12 @@ msgstr "Жесты" msgid "GitHub updates" msgstr "Обновления GitHub" +msgid "Glacier" +msgstr "Ледник" + +msgid "Graphite" +msgstr "Графит" + msgid "Headphones or speakers" msgstr "Наушники или колонки" @@ -323,8 +362,8 @@ msgstr "Покинуть комнату" msgid "Less bandwidth" msgstr "Меньше трафика" -msgid "Light" -msgstr "Светлая" +msgid "Light themes" +msgstr "Светлые темы" msgid "Like" msgstr "Нравится" @@ -359,9 +398,21 @@ msgstr "Микрофон" msgid "Microphone is transmitting" msgstr "Микрофон передаёт звук" +msgid "Microphone test" +msgstr "Проверка микрофона" + +msgid "Microphone test failed: {}" +msgstr "Ошибка проверки микрофона: {}" + msgid "Microphone uses your existing voice controls. This preview never enables or mixes it." msgstr "Микрофон управляется обычными кнопками голосовой связи. Предпросмотр не включает и не подмешивает его." +msgid "Midnight" +msgstr "Полночь" + +msgid "Mist" +msgstr "Дымка" + msgid "Mute broadcast" msgstr "Выключить звук трансляции" @@ -404,6 +455,12 @@ msgstr "Сохранённых серверов пока нет." msgid "No webhooks yet. Add an integration below." msgstr "Вебхуков пока нет. Добавьте интеграцию ниже." +msgid "Noise suppression" +msgstr "Шумоподавление" + +msgid "Noise suppression is not included in this build." +msgstr "Шумоподавление недоступно в этой сборке." + msgid "Nothing found" msgstr "Ничего не найдено" @@ -413,6 +470,9 @@ msgstr "Трансляция не ведётся" msgid "Objects and activities" msgstr "Предметы и занятия" +msgid "Off" +msgstr "Выключено" + msgid "One application" msgstr "Одно приложение" @@ -443,18 +503,24 @@ msgstr "Открой профиль друга, чтобы написать ем msgid "Open microphone" msgstr "Открытый микрофон" +msgid "Open sign-in page" +msgstr "Открыть страницу входа" + msgid "Outgoing events" msgstr "Исходящие события" msgid "Passphrase protected" msgstr "Защищено паролем" -msgid "Photo" -msgstr "Фото" +msgid "Paste image" +msgstr "Вставить изображение" msgid "Photo crop area. Drag the image to adjust the crop." msgstr "Область фото. Перетаскивай изображение, чтобы изменить кадрирование." +msgid "Pine" +msgstr "Хвоя" + msgid "Play a test sound" msgstr "Проверить звук" @@ -464,6 +530,9 @@ msgstr "Воспроизводить звуки" msgid "Playback volume for voice rooms." msgstr "Общий уровень воспроизведения голосовых комнат." +msgid "Porcelain" +msgstr "Фарфор" + msgid "Preview" msgstr "Предпросмотр" @@ -488,6 +557,9 @@ msgstr "Фото профиля" msgid "Push to talk" msgstr "Нажми и говори" +msgid "RNNoise reduces steady background noise. Compare it with the microphone test." +msgstr "RNNoise уменьшает постоянный фоновый шум. Сравните звук во время проверки микрофона." + msgid "Receive updates here, or send signed channel events to your own service." msgstr "Получайте обновления в этом канале или отправляйте подписанные события в свой сервис." @@ -506,6 +578,9 @@ msgstr "Убрать пароль" msgid "Remove saved server" msgstr "Убрать сохранённый сервер" +msgid "Rename channel" +msgstr "Переименовать канал" + msgid "Repeat backup passphrase" msgstr "Повтори пароль копии" @@ -536,6 +611,9 @@ msgstr "Отозвать этот вебхук?" msgid "Revoke webhook" msgstr "Отозвать вебхук" +msgid "Rose" +msgstr "Роза" + msgid "Rotate" msgstr "Заменить секрет" @@ -545,9 +623,21 @@ msgstr "Заменить секрет" msgid "Rotate this secret?" msgstr "Заменить этот секрет?" +msgid "Sage" +msgstr "Шалфей" + +msgid "Sand" +msgstr "Песок" + +msgid "Save" +msgstr "Сохранить" + msgid "Save address" msgstr "Сохранить адрес" +msgid "Save name" +msgstr "Сохранить название" + msgid "Save passphrase" msgstr "Сохранить пароль" @@ -557,6 +647,12 @@ msgstr "Сохраните секрет сейчас" msgid "Saved servers" msgstr "Сохранённые серверы" +msgid "Saved to Central and synced with connected members." +msgstr "Сохраняется в Central и синхронизируется с подключёнными участниками." + +msgid "Saving..." +msgstr "Сохранение…" + msgid "Screen capture is not available in this build." msgstr "Захват экрана недоступен в этой сборке." @@ -572,6 +668,9 @@ msgstr "Защита и резервная копия" msgid "Send" msgstr "Отправить" +msgid "Send image" +msgstr "Отправить изображение" + msgid "Server address" msgstr "Адрес сервера" @@ -593,6 +692,15 @@ msgstr "Звук демонстрации" msgid "Short tones for voice rooms, messages and connection changes. They stay silent while you are deafened." msgstr "Короткие сигналы для голосовых комнат, сообщений и смены состояния связи. Пока звук выключен, они молчат." +msgid "Sign in through browser" +msgstr "Войти через браузер" + +msgid "Sign in to Central" +msgstr "Войдите в Central" + +msgid "Sign out of Central" +msgstr "Выйти из Central" + msgid "Smileys" msgstr "Смайлики" @@ -620,9 +728,15 @@ msgstr "Остановить" msgid "Stop broadcast" msgstr "Остановить трансляцию" +msgid "Stop microphone test" +msgstr "Остановить проверку" + msgid "Stop watching" msgstr "Закрыть просмотр" +msgid "Synced with your Central account and other devices." +msgstr "Синхронизируется с аккаунтом Central и другими устройствами." + msgid "System default" msgstr "Как в системе" @@ -632,6 +746,9 @@ msgstr "Системный звук" msgid "System output includes notifications and other applications. Select it only if you intend to share all of that output." msgstr "Системный звук включает уведомления и другие приложения. Выбирай его, только если хочешь передавать весь этот звук." +msgid "Test microphone" +msgstr "Проверить микрофон" + msgid "Text channels" msgstr "Текстовые каналы" @@ -686,6 +803,9 @@ msgstr "Включить звук трансляции" msgid "Unmute microphone" msgstr "Включить микрофон" +msgid "Use headphones. Hear yourself locally for up to 30 seconds. Nothing is sent to the room; voice transmission is paused during the test." +msgstr "Используйте наушники. До 30 секунд вы слышите себя локально. Звук не отправляется в комнату; передача голоса на время проверки приостанавливается." + msgid "Use photo" msgstr "Использовать фото" @@ -726,7 +846,7 @@ msgid "Volume" msgstr "Громкость" msgid "Waiting for the server…" -msgstr "Ожидание ответа сервера…" +msgstr "Ожидаем ответ сервера…" msgid "Watch broadcast" msgstr "Смотреть трансляцию" @@ -737,6 +857,9 @@ msgstr "Секрет вебхука" msgid "Webhooks" msgstr "Вебхуки" +msgid "Your display name" +msgstr "Ваше отображаемое имя" + msgid "Your key" msgstr "Твой ключ" @@ -755,8 +878,8 @@ msgstr "После выбора источника здесь появится msgid "Your profile, kept safe." msgstr "Твой профиль и его сохранность." -msgid "Your public key identifies your profile. You can share it; your secret key stays on this device." -msgstr "Открытый ключ определяет твой профиль. Им можно поделиться; секретный ключ остаётся на устройстве." +msgid "Your public key identifies this device. Your Central account keeps your name and photo in sync." +msgstr "Открытый ключ идентифицирует это устройство. Имя и фото синхронизируются через аккаунт Central." msgid "Your server. Your community." msgstr "Твой сервер. Твоё сообщество."