diff --git a/Cargo.lock b/Cargo.lock index dbd6239..7d23381 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1350,6 +1350,7 @@ name = "client" version = "0.1.0" dependencies = [ "ashpd 0.14.3", + "bitcode", "bytes", "clap", "common", @@ -1392,7 +1393,6 @@ dependencies = [ "spectrum", "sys-locale", "sysinfo 0.40.4", - "thiserror 2.0.21", "tokio", "toml 1.2.3+spec-1.1.0", "tracing", diff --git a/Cargo.toml b/Cargo.toml index 0921568..a79ccd9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,9 +15,6 @@ opt-level = 3 [profile.dev.package.spectrum] opt-level = 3 -[profile.dev.package.rustfft] -opt-level = 3 - [profile.harness] inherits = "dev" opt-level = 3 @@ -28,14 +25,11 @@ overflow-checks = false debug-assertions = true [profile.release] -opt-level = 3 lto = "fat" codegen-units = 1 panic = "abort" debug = false strip = true -overflow-checks = false -incremental = false [workspace.lints.rust] unsafe_code = "forbid" @@ -44,12 +38,35 @@ unsafe_code = "forbid" common = { path = "crates/common" } pixel = { path = "crates/pixel" } spectrum = { path = "crates/spectrum" } +usage = { path = "crates/usage" } tokio = { version = "1.54.1", features = ["full"] } bitcode = "0.6.9" -quinn = { version = "0.11.12", default-features = false, features = [ - "runtime-tokio", -] } +quinn = { version = "0.11.12", default-features = false, features = ["runtime-tokio"] } rustls = "0.23.45" +bytes = "1.12.2" +tracing = "0.1.44" +tracing-subscriber = "0.3.23" +thiserror = "2.0.21" +reed-solomon-simd = "3.1.0" +sha2 = "0.11.2" +serde = { version = "1.0.229", features = ["derive"] } +serde_json = "1.0.154" +image = { version = "0.25.10", default-features = false, features = ["jpeg", "png", "webp", "gif"] } +ureq = "3.5.2" +resvg = "0.50.0" +sysinfo = { version = "0.40.4", default-features = false } +winreg = "0.56.0" +ec-opus = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "9b677004" } +ec-core = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "9b677004" } +ec-probe = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "9b677004" } +ec-ogg = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "9b677004" } +ec-h264 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "9b677004" } +ec-vp8 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "9b677004" } +ec-flac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "9b677004" } +ec-h265 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "9b677004" } +ec-hw = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "9b677004" } +ec-vp9 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "9b677004" } +ec-av1 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "9b677004" } [patch.crates-io] gpui-pre-windows = { path = "vendor/gpui-pre-windows" } diff --git a/ci/build.sh b/ci/build.sh index 4622c1b..5b7f5b1 100755 --- a/ci/build.sh +++ b/ci/build.sh @@ -43,12 +43,12 @@ echo "::endgroup::" echo "::group::Build" if [ "$os" = windows ]; then sha256sum -c --quiet ci/shaders.sha256 - export XWIN_ACCEPT_LICENSE=1 XWIN_CACHE_DIR="$CARGO_HOME/xwin" GPUI_SHADERS_BYTES="$PWD/ci/shaders_bytes.rs" + export XWIN_ACCEPT_LICENSE=1 XWIN_CACHE_DIR="$CARGO_HOME/xwin" GPUI_SHADERS_BYTES="$PWD/ci/shaders_bytes.rs" YUMUSH_TARGET="$target" export CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUSTFLAGS="-C target-cpu=$cpu" cargo xwin build --release -p client --target "$windows" --target-dir "target/$level" built="target/$level/$windows/release/client.exe" else - export CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUSTFLAGS="-C target-cpu=$cpu" + export CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUSTFLAGS="-C target-cpu=$cpu" YUMUSH_TARGET="$target" cargo build --release -p "$package" --target-dir "target/$level" built="target/$level/release/$package" fi @@ -57,4 +57,7 @@ echo "::endgroup::" echo "::group::Package" cp "$built" "$target" sha256sum "$target" +if [ "$os" = windows ]; then + bash harness/imports.sh "$built" +fi echo "::endgroup::" diff --git a/configs/client_config.toml b/configs/client_config.toml deleted file mode 100644 index aa919b1..0000000 --- a/configs/client_config.toml +++ /dev/null @@ -1,2 +0,0 @@ -[client_config] -server_address = "127.0.0.1:2026" diff --git a/crates/client/Cargo.toml b/crates/client/Cargo.toml index 9733ab3..07284c5 100644 --- a/crates/client/Cargo.toml +++ b/crates/client/Cargo.toml @@ -4,36 +4,36 @@ version = "0.1.0" edition = "2024" [dependencies] -usage = { path = "../usage" } +usage.workspace = true common.workspace = true +bitcode.workspace = true pixel.workspace = true spectrum.workspace = true -reed-solomon-simd = "3.1.0" +reed-solomon-simd.workspace = true tokio.workspace = true quinn = { workspace = true, features = ["rustls-ring"] } - +ec-opus.workspace = true +ec-core.workspace = true +ec-probe.workspace = true +ec-ogg.workspace = true +ec-h264.workspace = true +ec-vp8.workspace = true +ec-flac.workspace = true +ec-h265.workspace = true +ec-hw.workspace = true +ec-vp9.workspace = true +ec-av1.workspace = true gpui-kit = { version = "0.11.0", features = ["syntect"] } -ec-opus = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "9b677004" } -ec-core = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "9b677004" } -ec-probe = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "9b677004" } -ec-ogg = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "9b677004" } -ec-h264 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "9b677004" } -ec-vp8 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "9b677004" } -ec-flac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "9b677004" } -ec-h265 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "9b677004" } -ec-hw = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "9b677004" } -ec-vp9 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "9b677004" } -ec-av1 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "9b677004" } -ureq = "3.5.2" -serde = { version = "1.0.229", features = ["derive"] } -serde_json = "1.0.154" -bytes = "1.12.2" -tracing = "0.1.44" -tracing-subscriber = "0.3.23" +ureq.workspace = true +serde.workspace = true +serde_json.workspace = true +bytes.workspace = true +tracing.workspace = true +tracing-subscriber.workspace = true jiff = "1.0.2" dirs = "7.0.0" sys-locale = "0.3.2" -image = { version = "0.25.10", default-features = false, features = ["jpeg", "png", "webp", "gif"] } +image.workspace = true rtrb = "0.4.1" gethostname = "1.1.0" self-replace = "1.5.1" @@ -41,8 +41,7 @@ ruzstd = "0.9.1" rustls-platform-verifier = "0.7.1" flate2 = "1.1.11" emojis = "0.9.1" -resvg = "0.50.0" -thiserror = "2.0.21" +resvg.workspace = true [target.'cfg(any(target_os = "linux", target_os = "windows"))'.dependencies] nokhwa = { version = "0.10.11", default-features = false, features = ["input-native"] } @@ -60,8 +59,8 @@ wasapi = "0.27.0" windows-capture = "2.0.1" xcap = { version = "0.9.11", default-features = false } tray-icon = { version = "0.27.0", default-features = false } -winreg = "0.56.0" -sysinfo = { version = "0.40.4", default-features = false, features = ["system"] } +winreg.workspace = true +sysinfo = { workspace = true, features = ["system"] } [target.'cfg(target_os = "macos")'.dependencies] coreaudio-rs = "0.14.2" @@ -70,7 +69,7 @@ coreaudio-rs = "0.14.2" embed-resource = "3.0.12" icns = "0.5.0" ico = "0.6.0" -resvg = "0.50.0" +resvg.workspace = true toml = "1.2.3" [lints] diff --git a/crates/client/build.rs b/crates/client/build.rs index 5e7a9f1..d344e89 100644 --- a/crates/client/build.rs +++ b/crates/client/build.rs @@ -20,41 +20,28 @@ const COLORS: [&str; 10] = [ "ground", "raise", "hov", "press", "thread", "off", "faint", "dim", "paper", "bad", ]; const SCALES: [&str; 6] = ["space", "radius", "stroke", "text", "size", "leading"]; -const V1: &[&str] = &["fxsr", "sse", "sse2"]; -const V1_WINDOWS: &[&str] = &["cmpxchg16b", "fxsr", "sse", "sse2", "sse3"]; -const V3: &[&str] = &[ - "avx", - "avx2", - "bmi1", - "bmi2", - "cmpxchg16b", - "f16c", - "fma", - "fxsr", - "lzcnt", - "movbe", - "popcnt", - "sse", - "sse2", - "sse3", - "sse4.1", - "sse4.2", - "ssse3", - "xsave", -]; const MEDIA_FOUNDATION: [&str; 3] = ["mf.dll", "mfplat.dll", "mfreadwrite.dll"]; fn main() { println!("cargo::rerun-if-changed={SOURCE}"); icons(); words(); + tokens(); target(); + commit(); + link_args(); +} + +fn link_args() { if env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("msvc") { for dll in MEDIA_FOUNDATION { println!("cargo::rustc-link-arg-bins=/DELAYLOAD:{dll}"); } println!("cargo::rustc-link-arg-bins=delayimp.lib"); } +} + +fn tokens() { let tokens: Table = fs::read_to_string(SOURCE) .expect("read tokens") .parse() @@ -72,21 +59,22 @@ fn main() { let themes = tokens["theme"].as_table().expect("theme table"); writeln!( out, - "#[derive(Debug, Clone, Copy, PartialEq, Eq)]\npub enum Theme {{ {} }}", + "common::string_enum! {{ #[derive(Debug, Clone, Copy, PartialEq, Eq)] Theme {{ {} }} }}", themes .keys() - .map(|name| camel(name)) + .map(|name| format!("{} => {name:?}", camel(name))) .collect::>() .join(", ") ) .unwrap(); writeln!( out, - "impl Theme {{\n pub const ALL: [Theme; {}] = [{}];\n pub const fn as_str(self) -> &'static str {{ match self {{ {} }} }}\n pub fn parse(text: &str) -> Option {{ Self::ALL.into_iter().find(|theme| theme.as_str() == text) }}\n pub const fn colors(self) -> &'static Colors {{ match self {{ {} }} }}\n}}", - themes.len(), - themes.keys().map(|name| format!("Theme::{}", camel(name))).collect::>().join(", "), - themes.keys().map(|name| format!("Theme::{} => \"{name}\"", camel(name))).collect::>().join(", "), - themes.keys().map(|name| format!("Theme::{} => &{}", camel(name), name.to_uppercase())).collect::>().join(", "), + "impl Theme {{ pub const fn colors(self) -> &'static Colors {{ match self {{ {} }} }} }}", + themes + .keys() + .map(|name| format!("Theme::{} => &{}", camel(name), name.to_uppercase())) + .collect::>() + .join(", ") ) .unwrap(); @@ -371,23 +359,17 @@ fn holes(text: &str) -> Vec { } fn target() { - let arch = env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default(); - let os = env::var("CARGO_CFG_TARGET_OS").unwrap_or_default(); - let features = env::var("CARGO_CFG_TARGET_FEATURE").unwrap_or_default(); - let mut features: Vec<&str> = features - .split(',') - .filter(|feature| !feature.is_empty() && *feature != "crt-static") - .collect(); - features.sort_unstable(); - let target = match (arch.as_str(), features.as_slice()) { - ("x86_64", V1) if os != "windows" => format!("x86_64_v1-{os}"), - ("x86_64", V1_WINDOWS) if os == "windows" => format!("x86_64_v1-{os}"), - ("x86_64", V3) => format!("x86_64_v3-{os}"), - ("x86_64", _) => "custom".to_string(), - _ => format!("{arch}-{os}"), - }; + println!("cargo::rerun-if-env-changed=YUMUSH_TARGET"); + let target = env::var("YUMUSH_TARGET").unwrap_or_else(|_| { + let arch = env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default(); + let os = env::var("CARGO_CFG_TARGET_OS").unwrap_or_default(); + if arch == "x86_64" { + "custom".to_string() + } else { + format!("{arch}-{os}") + } + }); println!("cargo::rustc-env=YUMUSH_TARGET={target}"); - commit(); } fn commit() { diff --git a/crates/client/src/accounts.rs b/crates/client/src/accounts.rs index 133545d..e26c477 100644 --- a/crates/client/src/accounts.rs +++ b/crates/client/src/accounts.rs @@ -29,6 +29,12 @@ impl Accounts { self.list.iter().find(|account| account.user_id == user_id) } + fn get_mut(&mut self, user_id: Id) -> Option<&mut Account> { + self.list + .iter_mut() + .find(|account| account.user_id == user_id) + } + pub fn recent(&self) -> Vec<&Account> { let mut list: Vec<&Account> = self.list.iter().collect(); list.sort_by_key(|account| Reverse(account.used_ms)); @@ -49,11 +55,7 @@ impl Accounts { } pub fn rename(&mut self, user: &User) { - if let Some(account) = self - .list - .iter_mut() - .find(|account| account.user_id == user.id) - { + if let Some(account) = self.get_mut(user.id) { account.username = user.username.clone(); save(self); } @@ -74,11 +76,7 @@ impl Accounts { Some(bytes) => write_config(&name, bytes), None => remove_config(&name), } - if let Some(account) = self - .list - .iter_mut() - .find(|account| account.user_id == user_id) - { + if let Some(account) = self.get_mut(user_id) { account.picture = bytes.map(|bytes| Arc::new(Image::from_bytes(ImageFormat::Jpeg, bytes))); } @@ -126,21 +124,21 @@ pub fn load(server: &str) -> Accounts { server: server.to_string(), ..Accounts::default() }; - let Some(content) = read_config(&file(server)).or_else(|| read_config("accounts")) else { + let Some(content) = read_config(&file(server)) else { return accounts; }; for line in content.lines() { match line.split('\t').collect::>().as_slice() { ["active", user_id] => accounts.active = user_id.parse().ok(), - [user_id, username, token, rest @ ..] => { - if let Ok(user_id) = user_id.parse() { + [user_id, username, token, used] => { + if let (Ok(user_id), Ok(used_ms)) = (user_id.parse(), used.parse()) { accounts.list.push(Account { user_id, username: username.to_string(), token: token.to_string(), picture: picture(server, user_id), - used_ms: rest.first().and_then(|used| used.parse().ok()).unwrap_or(0), + used_ms, }); } } diff --git a/crates/client/src/ci.rs b/crates/client/src/ci.rs index f05b137..ac47267 100644 --- a/crates/client/src/ci.rs +++ b/crates/client/src/ci.rs @@ -121,16 +121,18 @@ impl Repo { } fn poll(repo: &Repo, send: &UnboundedSender, stop: &AtomicBool) { - let mut followed = None; + let mut last = None; while !stop.load(Ordering::Relaxed) && !send.is_closed() { if let Some(run) = latest(repo) { - let fresh = followed != Some(run.number); - let live = !State::of(&run.state).finished(); - if fresh || live { - followed = Some(run.number); - let _ = send.send(Event::Run(run.clone())); - if live { - follow(repo, run.number, send, stop); + let state = State::of(&run.state); + let number = run.number; + if last != Some((number, state)) || !state.finished() { + last = Some((number, state)); + let _ = send.send(Event::Run(run)); + if !state.finished() + && let Some(state) = follow(repo, number, send, stop) + { + last = Some((number, state)); } } } @@ -160,11 +162,17 @@ fn latest(repo: &Repo) -> Option { .next() } -fn follow(repo: &Repo, number: u64, send: &UnboundedSender, stop: &AtomicBool) { +fn follow( + repo: &Repo, + number: u64, + send: &UnboundedSender, + stop: &AtomicBool, +) -> Option { let Ok(response) = ureq::get(format!("{}/ci/runs/{number}/events", repo.api)).call() else { - return; + return None; }; let mut streaming = HashSet::new(); + let mut last = None; let finished = Arc::new(std::sync::Mutex::new(HashSet::new())); events(response.into_body().into_reader(), |event, data| { if event != "run" { @@ -183,10 +191,12 @@ fn follow(repo: &Repo, number: u64, send: &UnboundedSender, stop: &Atomic std::thread::spawn(move || log(&url, &job, &send, &finished)); } } - let done = State::of(&run.state).finished(); + let state = State::of(&run.state); + last = Some(state); let _ = send.send(Event::Run(run)); - !done && !stop.load(Ordering::Relaxed) + !state.finished() && !stop.load(Ordering::Relaxed) }); + last } fn log( diff --git a/crates/client/src/cli.rs b/crates/client/src/cli.rs index 4bc411c..721200a 100644 --- a/crates/client/src/cli.rs +++ b/crates/client/src/cli.rs @@ -3,7 +3,7 @@ use std::{collections::HashMap, io::Read, process::exit, time::Duration}; use clap::{Parser, Subcommand}; use common::{ call::{ - CreateMessage, CreateTag, GetForge, ImportRelease, ListCommunities, ListMembers, + Call, CreateMessage, CreateTag, GetForge, ImportRelease, ListCommunities, ListMembers, ListMessages, OpenNotes, PublishRelease, }, event::Event, @@ -99,13 +99,11 @@ async fn execute(command: Command) -> Result<(), String> { let community = session.chat(&chat).await?; let names = session.names(community.id).await?; let messages = session - .network .call(ListMessages { community_id: community.id, before: None, }) - .await - .map_err(text)?; + .await?; let skip = messages.len().saturating_sub(count); for message in &messages[skip..] { print_message(message, &names, None); @@ -125,26 +123,20 @@ async fn execute(command: Command) -> Result<(), String> { let session = open().await?; let community = session.chat(&chat).await?; session - .network .call(CreateMessage { community_id: community.id, body, attachments: Vec::new(), reply_to: None, }) - .await - .map_err(text)?; + .await?; Ok(()) } Command::Tail { chat } => tail(open().await?, chat).await, Command::Ci { tag } => follow(&open().await?, tag.as_deref()).await, Command::Build { tag } => { let session = open().await?; - session - .network - .call(CreateTag { tag: tag.clone() }) - .await - .map_err(text)?; + session.call(CreateTag { tag: tag.clone() }).await?; println!("tag {tag} created"); follow(&session, Some(&tag)).await } @@ -160,17 +152,16 @@ fn text(fail: Fail) -> String { fail.to_string() } -fn start() -> (NetworkHandle, Receiver, accounts::Accounts) { +fn start() -> (Session, accounts::Accounts) { let server = Server::load(); let accounts = accounts::load(&server.address); let (network, events) = net::start(server); - (network, events, accounts) + (Session { network, events }, accounts) } async fn login(username: &str) -> Result<(), String> { let password = rpassword::prompt_password("password: ").map_err(|error| error.to_string())?; - let (network, events, mut accounts) = start(); - let session = Session { network, events }; + let (session, mut accounts) = start(); let (user, token) = session .connect(session.network.login(username, &password)) .await?; @@ -190,13 +181,12 @@ async fn logout() -> Result<(), String> { } async fn open() -> Result { - let (network, events, accounts) = start(); + let (session, accounts) = start(); let token = accounts .active .and_then(|user_id| accounts.get(user_id)) .map(|account| account.token.clone()) .ok_or("not signed in: yumush login ")?; - let session = Session { network, events }; session.connect(session.network.resume(&token)).await?; Ok(session) } @@ -212,31 +202,29 @@ impl Session { .map_err(text) } + async fn call(&self, call: C) -> Result { + self.network.call(call).await.map_err(text) + } + async fn communities(&self) -> Result, String> { - let mut communities = self.network.call(ListCommunities).await.map_err(text)?; + let mut communities = self.call(ListCommunities).await?; if !communities .iter() .any(|community| matches!(community.kind, CommunityKind::Notes)) { - communities.push(self.network.call(OpenNotes).await.map_err(text)?); + communities.push(self.call(OpenNotes).await?); } Ok(communities) } async fn chat(&self, chat: &str) -> Result { - self.communities() - .await? - .into_iter() - .find(|community| title(community).eq_ignore_ascii_case(chat)) - .ok_or_else(|| format!("no chat named {chat}; see yumush chats")) + find_chat(&self.communities().await?, chat).cloned() } async fn names(&self, community_id: Id) -> Result, String> { Ok(self - .network .call(ListMembers { community_id }) - .await - .map_err(text)? + .await? .into_iter() .map(|member| (member.user.id, member.user.username)) .collect()) @@ -254,6 +242,13 @@ impl Session { } } +fn find_chat<'a>(communities: &'a [Community], chat: &str) -> Result<&'a Community, String> { + communities + .iter() + .find(|community| title(community).eq_ignore_ascii_case(chat)) + .ok_or_else(|| format!("no chat named {chat}; see yumush chats")) +} + fn title(community: &Community) -> String { match &community.kind { CommunityKind::Group => community.name.clone(), @@ -290,7 +285,7 @@ fn print_message(message: &Message, names: &HashMap, chat: Option<&s async fn tail(mut session: Session, chat: Option) -> Result<(), String> { let communities = session.communities().await?; let only = match &chat { - Some(chat) => Some(session.chat(chat).await?.id), + Some(chat) => Some(find_chat(&communities, chat)?.id), None => None, }; let titles: HashMap = communities @@ -319,10 +314,8 @@ async fn tail(mut session: Session, chat: Option) -> Result<(), String> async fn follow(session: &Session, tag: Option<&str>) -> Result<(), String> { let repo = session - .network .call(GetForge) - .await - .map_err(text)? + .await? .ok_or("the server has no forge set")?; let (_watch, mut events) = ci::watch(repo); let mut states: HashMap = HashMap::new(); @@ -373,11 +366,7 @@ async fn import( publish: Option, required: bool, ) -> Result<(), String> { - session - .network - .call(ImportRelease { tag: tag.clone() }) - .await - .map_err(text)?; + session.call(ImportRelease { tag: tag.clone() }).await?; println!("importing {tag}"); let staged = loop { if let Event::Imported { tag: done, result } = session.event().await? @@ -401,11 +390,7 @@ async fn import( .filter(|file| side.takes(&file.target)) .map(|file| file.file) .collect(); - let release = session - .network - .call(PublishRelease { files, required }) - .await - .map_err(text)?; + let release = session.call(PublishRelease { files, required }).await?; println!("published release #{}", release.seq); Ok(()) } diff --git a/crates/client/src/embed.rs b/crates/client/src/embed.rs index 544a2f5..4ce20bd 100644 --- a/crates/client/src/embed.rs +++ b/crates/client/src/embed.rs @@ -1,10 +1,12 @@ use std::io::Read; +use std::net::{IpAddr, ToSocketAddrs}; use std::time::Duration; -use ureq::http::Uri; +use ureq::http::{Uri, header::LOCATION}; use ureq::{Agent, Body, ResponseExt}; const MAX_LINKS: usize = 3; +const MAX_REDIRECTS: usize = 5; const MAX_IMAGE: u64 = 5 * 1024 * 1024; const MAX_HTML: u64 = 512 * 1024; const MAX_TITLE: usize = 256; @@ -56,10 +58,10 @@ pub fn urls(text: &str) -> Vec { } fn find_scheme(s: &str) -> Option { - match (s.find("http://"), s.find("https://")) { - (Some(a), Some(b)) => Some(a.min(b)), - (a, b) => a.or(b), - } + s.find("http://") + .into_iter() + .chain(s.find("https://")) + .min() } fn trim_link(s: &str) -> &str { @@ -79,18 +81,15 @@ fn trim_link(s: &str) -> &str { } pub fn fetch(url: &str) -> Option { - if !is_web(url) { - return None; - } let agent = Agent::new_with_config( Agent::config_builder() .timeout_global(Some(Duration::from_secs(5))) - .max_redirects(5) + .max_redirects(0) .user_agent("yumush") .http_status_as_error(true) .build(), ); - let mut resp = agent.get(url).call().ok()?; + let mut resp = get(&agent, url)?; let final_url = resp.get_uri().to_string(); let mime = mime_of(&resp)?; @@ -139,9 +138,71 @@ pub fn fetch(url: &str) -> Option { }) } -fn is_web(url: &str) -> bool { - url.parse::() - .is_ok_and(|u| matches!(u.scheme_str(), Some("http" | "https"))) +fn get(agent: &Agent, url: &str) -> Option> { + let mut url = url.to_owned(); + for _ in 0..=MAX_REDIRECTS { + if !public(&url) { + return None; + } + let resp = agent.get(&url).call().ok()?; + if !resp.status().is_redirection() { + return Some(resp); + } + let location = resp.headers().get(LOCATION)?.to_str().ok()?; + url = resolve(&url, location)?; + } + None +} + +fn public(url: &str) -> bool { + let Ok(uri) = url.parse::() else { + return false; + }; + let default_port = match uri.scheme_str() { + Some("http") => 80, + Some("https") => 443, + _ => return false, + }; + let Some(host) = uri.host() else { + return false; + }; + let host = host.trim_start_matches('[').trim_end_matches(']'); + let Ok(addrs) = (host, uri.port_u16().unwrap_or(default_port)).to_socket_addrs() else { + return false; + }; + let addrs: Vec<_> = addrs.collect(); + !addrs.is_empty() && addrs.iter().all(|addr| routable(addr.ip())) +} + +fn routable(ip: IpAddr) -> bool { + match ip { + IpAddr::V4(ip) => { + let [a, b, ..] = ip.octets(); + let shared = a == 100 && (b & 0xc0) == 64; + !(a == 0 + || shared + || ip.is_private() + || ip.is_loopback() + || ip.is_link_local() + || ip.is_broadcast() + || ip.is_unspecified() + || ip.is_multicast() + || ip.is_documentation()) + } + IpAddr::V6(ip) => { + if let Some(mapped) = ip.to_ipv4_mapped() { + return routable(IpAddr::V4(mapped)); + } + let first = ip.segments()[0]; + let unique_local = (first & 0xfe00) == 0xfc00; + let link_local = (first & 0xffc0) == 0xfe80; + !(ip.is_loopback() + || ip.is_unspecified() + || ip.is_multicast() + || unique_local + || link_local) + } + } } fn mime_of(resp: &ureq::http::Response) -> Option { @@ -165,10 +226,7 @@ fn read_image(resp: &mut ureq::http::Response) -> Option> { } fn fetch_image(agent: &Agent, url: &str) -> Option> { - if !is_web(url) { - return None; - } - let mut resp = agent.get(url).call().ok()?; + let mut resp = get(agent, url)?; if !is_image(&mime_of(&resp)?) { return None; } diff --git a/crates/client/src/emoji.rs b/crates/client/src/emoji.rs index b2e50e8..b3e9385 100644 --- a/crates/client/src/emoji.rs +++ b/crates/client/src/emoji.rs @@ -63,7 +63,7 @@ pub fn key(emoji: &str) -> String { .join("-") } -pub fn known(emoji: &str) -> bool { +fn known(emoji: &str) -> bool { PACKED.index.contains_key(&key(emoji)) } diff --git a/crates/client/src/gui.rs b/crates/client/src/gui.rs index b1ea1b2..e3a636c 100644 --- a/crates/client/src/gui.rs +++ b/crates/client/src/gui.rs @@ -1,16 +1,16 @@ use crate::gui::glyph::Fill as _; -use crate::lang::{Label as _, w}; +use crate::lang::w; use common::model::{Hue, Id}; use std::{collections::HashMap, fmt::Display, rc::Rc, sync::Arc, time::Instant}; use common::{ call::{GetAvatar, GetSettings, MarkRead}, constant::{MAXIMUM_AVATAR_BYTES, MAXIMUM_MESSAGE_LENGTH}, - error::Error, + error::{Error, ReleaseProblem}, event::Event, model::{ - BackupInfo, CallLog, Community, CommunityKind, Message, Presence, Rank, Sanction, - ServerSettings, Unread, User, mentions, + CallLog, Community, CommunityKind, Message, Presence, Rank, Sanction, ServerSettings, + Staged, Unread, User, mentions, }, }; use gpui_kit::{ @@ -18,10 +18,9 @@ use gpui_kit::{ Entity, FontWeight, Hsla, Image, ImageFormat, InteractiveElement, IntoElement, KeyBinding, KeyDownEvent, KeyUpEvent, ModifiersChangedEvent, ParentElement, Pixels, Rems, Render, RenderOnce, Stateful, StatefulInteractiveElement, Styled, WeakEntity, Window, actions, - assets::IconName, base::Selectable, component::{ - Icon, Sizable, Theme, ThemeRegistry, WindowExt, + Sizable, Theme, ThemeRegistry, WindowExt, input::{Input, InputEvent, InputState}, notification::Notification, spinner::Spinner, @@ -37,7 +36,8 @@ use crate::{ accounts::{self, Accounts}, marks::{self, Mark}, net::{Fail, LinkError, NetworkEvent, NetworkHandle}, - settings::{Scale, Settings}, + settings::Settings, + voice::{self, Sound}, }; mod account_list; @@ -54,6 +54,7 @@ mod forward; pub mod gallery; pub mod glyph; mod jump; +mod keys; mod media_view; mod message_actions; mod parts; @@ -86,56 +87,6 @@ pub fn text(size: f32) -> Rems { rems(size / style::text::UI) } -#[derive(Clone, Copy)] -pub struct Palette { - pub window: Hsla, - pub panel: Hsla, - pub field: Hsla, - pub border: Hsla, - pub text: Hsla, - pub body: Hsla, - pub muted: Hsla, - pub hover: Hsla, - pub accent: Hsla, - pub on_accent: Hsla, - pub ok: Hsla, - pub danger: Hsla, - pub alert: Hsla, - pub screen: Hsla, - pub camera: Hsla, - pub dark: bool, - pub tokens: Tokens, -} - -impl Palette { - pub fn tinted(self, id: Id) -> Hsla { - self.tokens.person(id) - } -} - -pub fn palette(cx: &App) -> Palette { - let tokens = Tokens::of(cx); - Palette { - window: tokens.ground(), - panel: tokens.ground(), - field: tokens.raise(), - border: tokens.thread(), - text: tokens.paper(), - body: tokens.paper(), - muted: tokens.dim(), - hover: tokens.hov(), - accent: tokens.paper(), - on_accent: tokens.ground(), - ok: tokens.hue(Hue::Mint), - danger: tokens.bad(), - alert: tokens.bad(), - screen: tokens.hue(Hue::Sky), - camera: tokens.hue(Hue::Amber), - dark: tokens.dark(), - tokens, - } -} - const FONT: &str = "Onest"; const MONO_FONT: &str = "Adwaita Mono"; @@ -168,35 +119,35 @@ pub fn init(cx: &mut App) { } pub fn sync_theme(cx: &mut App) { - let palette = palette(cx); - let font_size = cx.global::().0.pixels(); + let t = Tokens::of(cx); + let font_size = Tokens::of(cx).size.pixels(); let theme = Theme::global_mut(cx); theme.font_family = FONT.into(); theme.mono_font_family = MONO_FONT.into(); let colors = &mut theme.colors; - colors.background = palette.panel; - colors.foreground = palette.text; - colors.popover = palette.panel; - colors.popover_foreground = palette.text; - colors.border = palette.border; - colors.input = palette.border; - colors.muted = palette.field; - colors.muted_foreground = palette.muted; - colors.accent = palette.hover; - colors.accent_foreground = palette.text; - colors.list_hover = palette.hover; - colors.secondary = palette.field; - colors.secondary_foreground = palette.text; - colors.primary = palette.accent; - colors.primary_hover = palette.accent; - colors.primary_active = palette.accent; - colors.primary_foreground = palette.on_accent; - colors.ring = palette.accent; - colors.caret = palette.accent; - colors.danger = palette.danger; - colors.slider_bar = palette.text; - colors.slider_thumb = palette.text; + colors.background = t.ground(); + colors.foreground = t.paper(); + colors.popover = t.ground(); + colors.popover_foreground = t.paper(); + colors.border = t.thread(); + colors.input = t.thread(); + colors.muted = t.raise(); + colors.muted_foreground = t.dim(); + colors.accent = t.hov(); + colors.accent_foreground = t.paper(); + colors.list_hover = t.hov(); + colors.secondary = t.raise(); + colors.secondary_foreground = t.paper(); + colors.primary = t.paper(); + colors.primary_hover = t.paper(); + colors.primary_active = t.paper(); + colors.primary_foreground = t.ground(); + colors.ring = t.paper(); + colors.caret = t.paper(); + colors.danger = t.bad(); + colors.slider_bar = t.paper(); + colors.slider_thumb = t.paper(); theme.tokens = (&theme.colors).into(); theme.radius = px(radius::SM); theme.radius_lg = px(radius::LG); @@ -204,10 +155,7 @@ pub fn sync_theme(cx: &mut App) { theme.focus_ring = false; } -const FIND_KEY: &str = "ctrl-k"; -pub const JUMP_HINT: &str = "Ctrl K"; - -pub fn badge(palette: Palette, id: Id, name: &str, size: Pixels, font: Rems) -> Div { +pub fn badge(t: Tokens, id: Id, name: &str, size: Pixels, font: Rems) -> Div { let initial = name .chars() .next() @@ -221,22 +169,22 @@ pub fn badge(palette: Palette, id: Id, name: &str, size: Pixels, font: Rems) -> .flex() .items_center() .justify_center() - .bg(palette.tinted(id)) - .text_color(palette.on_accent) + .bg(t.person(id)) + .text_color(t.ground()) .text_size(font) .font_weight(FontWeight::SEMIBOLD) .child(initial) } pub fn avatar( - palette: Palette, + t: Tokens, user: &User, size: Pixels, font: Rems, avatars: &HashMap>, ) -> Div { let Some(image) = user.avatar_id.as_ref().and_then(|id| avatars.get(id)) else { - return badge(palette, user.id, &user.username, size, font).rounded_full(); + return badge(t, user.id, &user.username, size, font).rounded_full(); }; div() @@ -331,7 +279,7 @@ pub fn community_name(community: &Community) -> &str { } pub fn community_icon( - palette: Palette, + t: Tokens, community: &Community, size: Pixels, font: Rems, @@ -345,34 +293,22 @@ pub fn community_icon( .rounded(px(radius::SM)) .overflow_hidden() .child(img(image.clone()).size_full().rounded(px(radius::SM))), - None => { - badge(palette, community.id, &community.name, size, font).rounded(px(radius::SM)) - } + None => badge(t, community.id, &community.name, size, font).rounded(px(radius::SM)), }, - CommunityKind::Direct { peer } => avatar(palette, peer, size, font, avatars), + CommunityKind::Direct { peer } => avatar(t, peer, size, font, avatars), CommunityKind::Notes => { - badge(palette, community.id, w().gui.notes, size, font).rounded(px(radius::SM)) + badge(t, community.id, w().gui.notes, size, font).rounded(px(radius::SM)) } } } pub const KB: f64 = 1024.0; pub const MB: f64 = KB * 1024.0; -const GB: f64 = MB * 1024.0; pub const CLOCK: &str = "%H:%M"; pub const CLOCK_SECONDS: &str = "%H:%M:%S"; -pub fn storage(bytes: u64) -> String { - let bytes = bytes as f64; - if bytes >= GB { - format!("{:.1} GB", bytes / GB) - } else if bytes >= MB { - format!("{:.1} MB", bytes / MB) - } else { - format!("{:.1} KB", bytes / KB) - } -} +pub use common::error::size_text as storage; pub fn millis_time(millis: u64, format: &str) -> String { let Ok(timestamp) = Timestamp::from_millisecond(millis as i64) else { @@ -395,13 +331,8 @@ pub fn month_named(format: &str, month: i8) -> String { format.replace("%b", name) } -pub use parts::motion; - -pub fn hoverable(id: impl Into, element: Div, palette: Palette) -> Stateful
{ - hoverable_with(id, element, palette.hover) -} - -pub fn hoverable_with(id: impl Into, element: Div, hover: Hsla) -> Stateful
{ +pub fn hoverable(id: impl Into, element: Div, t: Tokens) -> Stateful
{ + let hover = t.hov(); element .id(id) .cursor_pointer() @@ -410,10 +341,10 @@ pub fn hoverable_with(id: impl Into, element: Div, hover: Hsla) -> St pub fn clickable( id: impl Into, - palette: Palette, + t: Tokens, on_click: impl Fn(&mut Window, &mut App) + 'static, ) -> Stateful
{ - hoverable(id, div(), palette).on_click(move |_, window, cx| on_click(window, cx)) + hoverable(id, div(), t).on_click(move |_, window, cx| on_click(window, cx)) } pub fn entity_action( @@ -429,15 +360,15 @@ pub struct Tip(&'static str); impl Render for Tip { fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { - let palette = palette(cx); + let t = Tokens::of(cx); div() .px(px(space::SM)) .py(px(space::XS)) .rounded(px(radius::SM)) .border_1() - .border_color(palette.border) - .bg(palette.field) - .text_color(palette.text) + .border_color(t.thread()) + .bg(t.raise()) + .text_color(t.paper()) .font_family(FONT) .text_size(text(style::text::LABEL)) .child(self.0) @@ -479,26 +410,11 @@ impl RenderOnce for Trigger { } } -pub fn rank_tag(rank: Option, palette: Palette) -> Option
{ - let tag = div() - .flex_shrink_0() - .text_size(text(style::text::CAPTION)) - .text_color(palette.muted); - match rank? { - Rank::Member => None, - Rank::Builder => Some( - tag.text_color(palette.accent) - .child(Icon::new(IconName::Shield).size(px(size::ICON_SM))), - ), - rank => Some(tag.child(rank.label())), - } -} - -pub fn presence_color(presence: Presence, palette: Palette) -> Hsla { +pub fn presence_color(presence: Presence, t: Tokens) -> Hsla { match presence { - Presence::Online => palette.ok, - Presence::Busy => palette.danger, - Presence::Offline => palette.muted, + Presence::Online => t.hue(Hue::Mint), + Presence::Busy => t.bad(), + Presence::Offline => t.dim(), } } @@ -506,7 +422,7 @@ pub fn presence_avatar( avatar: impl IntoElement, presence: Presence, size: Pixels, - palette: Palette, + t: Tokens, ) -> Div { let dot = if size > px(size::CHIP) { px(space::SM + space::XXS) @@ -522,14 +438,14 @@ pub fn presence_avatar( .size(dot) .rounded_full() .border_2() - .border_color(palette.window) - .bg(presence_color(presence, palette)), + .border_color(t.ground()) + .bg(presence_color(presence, t)), ) } pub fn bind_keys(cx: &mut App) { cx.bind_keys([ - KeyBinding::new(FIND_KEY, FocusFind, None), + KeyBinding::new(keys::bind!("k"), FocusFind, None), KeyBinding::new("escape", CloseSettings, None), ]); composer::bind_keys(cx); @@ -571,14 +487,14 @@ impl Connection { } } -fn connection_notice(connection: &Connection, palette: Palette) -> Option
{ +fn connection_notice(connection: &Connection, t: Tokens) -> Option
{ let (label, color, busy) = match connection { - Connection::Connecting => (w().gui.connecting.to_string(), palette.muted, true), + Connection::Connecting => (w().gui.connecting.to_string(), t.dim(), true), Connection::Connected => return None, Connection::Lost { error, attempts } => { - (w().gui.reconnecting(attempts, error), palette.alert, true) + (w().gui.reconnecting(attempts, error), t.bad(), true) } - Connection::Failed(error) => (error.clone(), palette.alert, false), + Connection::Failed(error) => (error.clone(), t.bad(), false), }; Some( div() @@ -594,6 +510,14 @@ fn connection_notice(connection: &Connection, palette: Palette) -> Option
{ ) } +#[derive(Default)] +struct Missed { + resume: bool, + stale: bool, + notices: Vec, + imports: Vec<(String, Result, ReleaseProblem>)>, +} + pub struct Yumush { user: Option, current_route: Route, @@ -609,9 +533,7 @@ pub struct Yumush { voice: VoiceControls, focus: gpui_kit::FocusHandle, window: Option, - deferred: Vec, - backups: Vec, - pending_backup_delete: Option, + missed: Missed, update: crate::update::Phase, desk: builder::releases::Desk, release_tag: Entity, @@ -689,7 +611,7 @@ impl Yumush { .detach(); sidebar::wander(cx); - let voice = VoiceControls::new(&settings.voice, window, cx); + let voice = VoiceControls::new(&settings.voice, cx); let server = network.server(); let account_filter = new_input(w().auth.find_account, window, cx); @@ -716,9 +638,7 @@ impl Yumush { account_filter, voice, window: None, - deferred: Vec::new(), - backups: Vec::new(), - pending_backup_delete: None, + missed: Missed::default(), update: crate::update::Phase::Idle, desk: builder::releases::Desk::default(), release_tag, @@ -741,7 +661,7 @@ impl Yumush { pumped: Instant::now(), send_order: Default::default(), }; - yumush.chat.camera_task = Some(camera_view::ticker(cx)); + yumush.chat.session.camera_task = Some(camera_view::ticker(cx)); yumush } @@ -766,8 +686,41 @@ impl Yumush { }) .detach(); - for event in std::mem::take(&mut self.deferred) { - self.handle_network_event(event, Some(window), cx); + self.fullscreen = false; + if let Some(viewer) = self.chat.session.viewer.as_mut() { + viewer.fullscreen = false; + } + + let missed = std::mem::take(&mut self.missed); + if missed.resume { + self.resume(window, cx); + } + for notice in missed.notices { + window.push_notification(notice, cx); + } + for (tag, result) in missed.imports { + self.release_imported(&tag, result, window, cx); + } + if missed.stale { + self.releases_changed(window, cx); + self.report_created(window, cx); + self.voice_changed(window, cx); + } + self.focus_page(window, cx); + } + + fn notify(&mut self, window: Option<&mut Window>, notice: Notification, cx: &mut App) { + match window { + Some(window) => window.push_notification(notice, cx), + None => self.missed.notices.push(notice), + } + } + + fn resume(&mut self, window: &mut Window, cx: &mut Context) { + if self.user.is_some() { + self.reload(window, cx); + } else if let Some(active) = self.accounts.active { + self.switch_account(active, window, cx); } } @@ -789,8 +742,8 @@ impl Yumush { ) { self.accounts.sign_in(&user, token); self.request_user_avatar(&user, cx); - self.chat.muted = marks::load(Mark::Mute, user.id); - self.chat.pinned = marks::load(Mark::Pin, user.id); + self.chat.session.muted = marks::load(Mark::Mute, user.id); + self.chat.session.pinned = marks::load(Mark::Pin, user.id); style::remember(&[&user]); style::remember_me(user.id); self.user = Some(user); @@ -860,8 +813,8 @@ impl Yumush { return; }; let ids = match mark { - Mark::Mute => &mut self.chat.muted, - Mark::Pin => &mut self.chat.pinned, + Mark::Mute => &mut self.chat.session.muted, + Mark::Pin => &mut self.chat.session.pinned, }; if !ids.remove(&community_id) { ids.insert(community_id); @@ -871,7 +824,7 @@ impl Yumush { } pub(super) fn armed(&self, armed: chat::Armed) -> bool { - self.chat.armed == Some(armed) + self.chat.session.armed.as_ref() == Some(&armed) } pub(super) fn armed_label(&self, armed: chat::Armed, label: &'static str) -> &'static str { @@ -883,17 +836,17 @@ impl Yumush { } pub(super) fn arm(&mut self, armed: chat::Armed, cx: &mut Context) -> bool { - if self.armed(armed) { - self.chat.armed = None; + if self.armed(armed.clone()) { + self.chat.session.armed = None; return true; } - self.chat.armed = Some(armed); + self.chat.session.armed = Some(armed); cx.notify(); false } pub(super) fn disarm(&mut self, cx: &mut Context) { - if self.chat.armed.take().is_some() { + if self.chat.session.armed.take().is_some() { cx.notify(); } } @@ -917,20 +870,23 @@ impl Yumush { fn change_page(&mut self, route: Route, window: &mut Window, cx: &mut Context) { self.current_route = route; cx.notify(); + self.focus_page(window, cx); + } - match route { + fn focus_page(&self, window: &mut Window, cx: &mut Context) { + match self.current_route { Route::Login | Route::Register => self.auth.focus(window, cx), Route::Chat => self.chat.focus(window, cx), } } fn show_view(&mut self, view: View, window: &mut Window, cx: &mut Context) { - self.chat.section = None; - if self.chat.view == View::Settings && view != View::Settings { + self.chat.session.section = None; + if self.chat.session.view == View::Settings && view != View::Settings { self.leave_settings(); } if view == View::Settings { - self.enter_settings(window, cx); + self.enter_settings(cx); let (username, status) = self .user .as_ref() @@ -958,8 +914,8 @@ impl Yumush { self.load_bans(window, cx); } - self.chat.view = view; - self.chat.armed = None; + self.chat.session.view = view; + self.chat.session.armed = None; if view == View::Chat { self.chat.focus(window, cx); } @@ -975,11 +931,11 @@ impl Yumush { community: &Community, size: Pixels, font: Rems, - palette: Palette, + t: Tokens, ) -> Div { - let icon = community_icon(palette, community, size, font, &self.chat.avatars); + let icon = community_icon(t, community, size, font, &self.chat.session.avatars); match community.kind.peer() { - Some(peer) => presence_avatar(icon, self.presence_of(peer.id), size, palette), + Some(peer) => presence_avatar(icon, self.presence_of(peer.id), size, t), None => icon, } } @@ -989,6 +945,7 @@ impl Yumush { return Presence::Offline; } self.chat + .session .presences .get(&user_id) .copied() @@ -1000,19 +957,19 @@ impl Yumush { } pub fn request_avatar(&mut self, avatar_id: Id, cx: &mut Context) { - if self.chat.avatars.contains_key(&avatar_id) - || self.chat.avatar_requests.contains(&avatar_id) + if self.chat.session.avatars.contains_key(&avatar_id) + || self.chat.session.avatar_requests.contains(&avatar_id) { return; } - self.chat.avatar_requests.insert(avatar_id); + self.chat.session.avatar_requests.insert(avatar_id); let network = self.network.clone(); cx.spawn(async move |this, cx| { let result = network.call(GetAvatar { avatar_id }).await; let _ = this.update(cx, |yumush, cx| { - yumush.chat.avatar_requests.remove(&avatar_id); + yumush.chat.session.avatar_requests.remove(&avatar_id); if let Ok(bytes) = result { style::picture(avatar_id, &bytes); if let Some(me) = yumush @@ -1022,7 +979,7 @@ impl Yumush { { yumush.accounts.set_picture(me.id, Some(bytes.clone())); } - yumush.chat.avatars.insert( + yumush.chat.session.avatars.insert( avatar_id, Arc::new(Image::from_bytes(ImageFormat::Jpeg, bytes)), ); @@ -1054,8 +1011,8 @@ impl Yumush { if self.is_me(user.id) { self.user = Some(user.clone()); self.accounts.rename(user); - if !self.is_builder() && self.chat.view == View::Builder { - self.chat.view = View::Chat; + if !self.is_builder() && self.chat.session.view == View::Builder { + self.chat.session.view = View::Chat; } } self.request_user_avatar(user, cx); @@ -1073,7 +1030,7 @@ impl Yumush { self.close_viewer(cx) } Event::StatsWanted(true) => self.start_stats_push(cx), - Event::StatsWanted(false) => self.chat.stats_task = None, + Event::StatsWanted(false) => self.chat.session.stats_task = None, Event::Typing { .. } => { cx.spawn(async move |this, cx| { cx.background_executor().timer(chat::TYPING_TTL).await; @@ -1107,14 +1064,15 @@ impl Yumush { } fn read_selected(&mut self, cx: &mut Context) { - let Some(community_id) = self.chat.selected_community_id else { + let Some(community_id) = self.chat.session.selected_community_id else { return; }; - let Some(message_id) = self.chat.messages.last().map(|message| message.id) else { + let Some(message_id) = self.chat.session.messages.last().map(|message| message.id) else { return; }; if self .chat + .session .unread .get(&community_id) .is_some_and(|unread| unread.messages > 0) @@ -1136,6 +1094,7 @@ impl Yumush { } let unread = self .chat + .session .unread .entry(message.community_id) .or_insert_with(|| Unread { @@ -1156,7 +1115,7 @@ impl Yumush { message.user_id != me.id && message.call.is_none() - && !self.chat.muted.contains(&message.community_id) + && !self.chat.session.muted.contains(&message.community_id) && self.presence_of(me.id) == Presence::Online && !viewing } @@ -1188,13 +1147,17 @@ impl Yumush { self.user.as_ref().is_some_and(|me| me.id == user_id) } - fn end_session(&mut self, window: &mut Window, cx: &mut Context) { + fn clear_session(&mut self, cx: &mut Context) { self.end_voice(cx); self.leave_settings(); self.stop_playing(cx); self.user = None; self.desk = builder::releases::Desk::default(); self.chat.reset(); + } + + fn end_session(&mut self, window: &mut Window, cx: &mut Context) { + self.clear_session(cx); self.change_page(Route::Login, window, cx); } @@ -1229,10 +1192,10 @@ impl Yumush { cx.notify(); } - fn load_server_settings(&self, window: &mut Window, cx: &mut Context) { + fn load_server_settings(&self, cx: &mut Context) { let network = self.network.clone(); - cx.spawn_in(window, async move |this, cx| { + cx.spawn(async move |this, cx| { let Ok(settings) = network.call(GetSettings).await else { return; }; @@ -1257,19 +1220,14 @@ impl Yumush { self.before_pushed(pushed, active, cx); } - let Some(window) = window else { - self.handle_hidden(event, cx); - return; - }; - match event { NetworkEvent::Connected => { self.connection = Connection::Connected; - self.load_server_settings(window, cx); - if self.user.is_some() { - self.reload(window, cx); - } else if let Some(active) = self.accounts.active { - self.switch_account(active, window, cx); + self.desk.connected(); + self.load_server_settings(cx); + match window { + Some(window) => self.resume(window, cx), + None => self.missed.resume = true, } } NetworkEvent::Disconnected(error) => self.connection.lost(&error), @@ -1279,7 +1237,11 @@ impl Yumush { if let Some(user) = &self.user { self.accounts.forget(user.id); } - self.end_session(window, cx); + self.clear_session(cx); + match window { + Some(window) => self.change_page(Route::Login, window, cx), + None => self.current_route = Route::Login, + } } NetworkEvent::Pushed(event) => match *event { Event::MemberLeft { @@ -1307,15 +1269,24 @@ impl Yumush { } (Sanction::Kick, None) => w().gui.kicked(community_name), }; - window.push_notification(Notification::warning(text), cx); + self.notify(window, Notification::warning(text), cx); } Event::CommunityDeleted { community_id } => { self.leave_voice_in(community_id, cx); self.apply_pushed(Event::CommunityDeleted { community_id }, cx); } - Event::ReportCreated => self.report_created(window, cx), - Event::Release => self.releases_changed(window, cx), - Event::Imported { result, .. } => self.release_imported(result, window, cx), + Event::ReportCreated => match window { + Some(window) => self.report_created(window, cx), + None => self.missed.stale = true, + }, + Event::Release => match window { + Some(window) => self.releases_changed(window, cx), + None => self.missed.stale = true, + }, + Event::Imported { tag, result } => match window { + Some(window) => self.release_imported(&tag, result, window, cx), + None => self.missed.imports.push((tag, result)), + }, Event::SettingsUpdated(settings) => self.server = Some(settings), event => { let voice = matches!( @@ -1326,7 +1297,10 @@ impl Yumush { ); self.apply_pushed(event, cx); if voice { - self.voice_changed(window, cx); + match window { + Some(window) => self.voice_changed(window, cx), + None => self.missed.stale = true, + } } } }, @@ -1340,11 +1314,12 @@ impl Yumush { match event { Event::MessageCreated(message) => { if self.should_notify(message, active) { - self.network.play_notification(&self.settings.voice); + voice::play_sound(Sound::Notification, &self.settings.voice); } self.count_message(message, active, cx); if !self .chat + .session .communities .iter() .any(|community| community.id == message.community_id) @@ -1361,7 +1336,7 @@ impl Yumush { community_id, user_id, } if self.starts_call(*community_id, *user_id) => { - self.chat.ringing.insert(*community_id); + self.chat.session.ringing.insert(*community_id); } Event::VoiceLeft { community_id, @@ -1372,30 +1347,6 @@ impl Yumush { _ => {} } } - - fn handle_hidden(&mut self, event: NetworkEvent, cx: &mut Context) { - match event { - NetworkEvent::Connected => { - self.connection = Connection::Connected; - self.deferred.push(NetworkEvent::Connected); - } - NetworkEvent::Disconnected(error) => self.connection.lost(&error), - NetworkEvent::VoiceRejoined => self.refresh_voice(cx), - NetworkEvent::VoiceEnded => self.chat.set_voice_off(), - NetworkEvent::SessionLost => self.deferred.push(NetworkEvent::SessionLost), - NetworkEvent::Pushed(event) => match *event { - Event::MemberLeft { .. } - | Event::Removed { .. } - | Event::CommunityDeleted { .. } - | Event::ReportCreated => self.deferred.push(NetworkEvent::Pushed(event)), - Event::SettingsUpdated(settings) => self.server = Some(settings), - event => self.apply_pushed(event, cx), - }, - } - - self.update_ringing(cx); - cx.notify(); - } } pub fn input_dialog( @@ -1421,7 +1372,7 @@ pub fn input_dialog( let entity = cx.entity(); let dialog_input = input.clone(); window.open_dialog(cx, move |dialog, _, cx| { - let palette = palette(cx); + let t = Tokens::of(cx); let entity = entity.clone(); let on_submit = on_submit.clone(); let button_input = dialog_input.clone(); @@ -1436,7 +1387,7 @@ pub fn input_dialog( .items_center() .gap(px(space::MD)) .child( - widget::frame(palette, Input::new(&dialog_input).token(glyph::token)) + widget::frame(t, Input::new(&dialog_input).token(glyph::token)) .flex_1() .min_w_0(), ) @@ -1444,7 +1395,7 @@ pub fn input_dialog( "input_dialog_submit", action, parts::Press::Primary, - palette.tokens, + t, move |window, cx| { let text = button_input.read(cx).text().to_string(); entity.update(cx, |this, cx| on_submit(this, text, window, cx)); @@ -1492,6 +1443,7 @@ impl Render for Yumush { crate::usage::tick(crate::usage::Group::Gui); let fullscreen = self .chat + .session .viewer .as_ref() .is_some_and(|viewer| viewer.fullscreen); @@ -1504,16 +1456,16 @@ impl Render for Yumush { } self.hide_idle_cursor(window, cx); self.schedule_pump(window, cx); - let palette = palette(cx); + let t = Tokens::of(cx); let route = self.current_route; let required = self.update.required(); let page = match route { - _ if required => self.update_required(palette).into_any_element(), + _ if required => self.update_required(t).into_any_element(), Route::Login | Route::Register => self.auth_page(route, cx).into_any_element(), Route::Chat => self.chat_page(cx).into_any_element(), }; let banner = (route == Route::Chat && !required) - .then(|| connection_notice(&self.connection, palette)) + .then(|| connection_notice(&self.connection, t)) .flatten(); div() @@ -1521,8 +1473,8 @@ impl Render for Yumush { .flex() .flex_col() .size_full() - .bg(palette.window) - .text_color(palette.text) + .bg(t.ground()) + .text_color(t.paper()) .text_size(text(style::text::UI)) .track_focus(&self.focus) .on_action(cx.listener(|this, _: &FocusFind, window, cx| this.open_jump(window, cx))) @@ -1530,38 +1482,46 @@ impl Render for Yumush { if this.zoom.is_some() { this.zoom = None; cx.notify(); - } else if this.chat.friends_open { + } else if this.chat.session.friends_open { this.close_friends(window, cx); } else if this.chat.goto.open { this.close_jump(window, cx); - } else if this.fullscreen { + } else if this + .chat + .session + .viewer + .as_ref() + .is_some_and(|v| v.fullscreen) + { this.toggle_fullscreen(cx); - } else if this.chat.view != View::Chat { + } else if this.chat.session.view != View::Chat { this.show_view(View::Chat, window, cx); } else { this.cancel_composer(window, cx); } })) - .on_key_down(cx.listener(|this, event: &KeyDownEvent, _, cx| { - this.voice_key_down(event, cx); + .on_key_down(cx.listener(|this, event: &KeyDownEvent, window, cx| { + this.voice_key_down(event, window, cx); })) .on_key_up(cx.listener(|this, event: &KeyUpEvent, _, cx| { this.voice_key_up(event, cx); })) - .on_modifiers_changed(cx.listener(|this, event: &ModifiersChangedEvent, _, cx| { - this.voice_modifiers(event, cx); - })) + .on_modifiers_changed( + cx.listener(|this, event: &ModifiersChangedEvent, window, cx| { + this.voice_modifiers(event, window, cx); + }), + ) .children(banner) .child(div().flex_1().min_h_0().child(page)) .children( (route == Route::Chat && !required) - .then(|| self.jump_box(palette, cx)) + .then(|| self.jump_box(t, cx)) .flatten(), ) .children( self.zoom .as_ref() - .map(|zoom| zoom_view(zoom, &cx.entity(), palette.tokens)), + .map(|zoom| zoom_view(zoom, &cx.entity(), t)), ) } } diff --git a/crates/client/src/gui/account_list.rs b/crates/client/src/gui/account_list.rs index 542a529..b057781 100644 --- a/crates/client/src/gui/account_list.rs +++ b/crates/client/src/gui/account_list.rs @@ -5,45 +5,46 @@ use gpui_kit::{ }; use super::{ - Palette, Tooltip as _, Yumush, badge, clickable, hoverable, parts, + Tooltip as _, Yumush, badge, clickable, hoverable, parts, sidebar::input_box, - style::{radius, size, space, text}, + style::{Tokens, radius, size, space, text}, text, }; use crate::accounts::Account; use crate::lang::w; -const SHOWN: f32 = 3.; +const SHOWN: usize = 3; pub(super) fn account_list( yumush: &Yumush, entity: &Entity, - skip_active: bool, popover: Option>, - palette: Palette, + t: Tokens, cx: &App, ) -> Div { let mut accounts = yumush.accounts.recent(); - if skip_active { + if popover.is_some() { accounts.retain(|account| Some(account.user_id) != yumush.accounts.active); } - let filtered = accounts.len() > SHOWN as usize; + let searchable = accounts.len() > SHOWN; let query = super::widget::search_text(&yumush.account_filter, cx); let rows: Vec = accounts .into_iter() - .filter(|account| !filtered || account.username.to_lowercase().contains(query.as_str())) - .map(|account| row(account, entity, popover.clone(), palette)) + .filter(|account| !searchable || account.username.to_lowercase().contains(query.as_str())) + .map(|account| row(account, entity, popover.clone(), t)) .collect(); div() .flex() .flex_col() .gap(px(space::XXS)) - .children(filtered.then(|| input_box(&yumush.account_filter, palette).px(px(space::SM)))) + .children(searchable.then(|| input_box(&yumush.account_filter, t).px(px(space::SM)))) .child( div() .id("account_rows") - .max_h(px(SHOWN * size::CONTROL + (SHOWN - 1.) * space::XXS)) + .max_h(px( + SHOWN as f32 * size::CONTROL + (SHOWN - 1) as f32 * space::XXS + )) .overflow_y_scroll() .flex() .flex_col() @@ -56,7 +57,7 @@ fn row( account: &Account, entity: &Entity, popover: Option>, - palette: Palette, + t: Tokens, ) -> AnyElement { let user_id = account.user_id; let switch_entity = entity.clone(); @@ -80,7 +81,7 @@ fn row( .overflow_hidden() .child(gpui_kit::img(picture.clone()).size_full()), None => badge( - palette, + t, user_id, &account.username, px(size::CHIP), @@ -90,7 +91,7 @@ fn row( }) .child(div().flex_1().truncate().child(account.username.clone())) .child( - clickable(format!("forget_{user_id}"), palette, move |_, cx| { + clickable(format!("forget_{user_id}"), t, move |_, cx| { cx.stop_propagation(); forget_entity.update(cx, |yumush, cx| yumush.forget_account(user_id, cx)); }) @@ -100,10 +101,10 @@ fn row( .items_center() .justify_center() .rounded(px(radius::SM)) - .text_color(palette.muted) + .text_color(t.dim()) .child(parts::small_icon(IconName::X)), ), - palette, + t, ) .on_click(move |_, window, cx| { if let Some(popover) = &popover { diff --git a/crates/client/src/gui/auth.rs b/crates/client/src/gui/auth.rs index 5051993..cfdae15 100644 --- a/crates/client/src/gui/auth.rs +++ b/crates/client/src/gui/auth.rs @@ -8,12 +8,11 @@ use gpui_kit::{ }; use super::{ - Palette, Route, Yumush, + Route, Yumush, account_list::account_list, - clickable, connection_notice, new_input, notify_error, palette, parts, + clickable, connection_notice, new_input, notify_error, parts, settings_page::{segment, segment_track}, - style::{radius, size, space, text}, - text, + style::{Tokens, radius, size, space, text}, widget::{field, frame}, }; use crate::lang::w; @@ -94,14 +93,13 @@ fn submit(this: &mut Yumush, window: &mut Window, cx: &mut Context) { let network = this.network.clone(); cx.spawn_in(window, async move |this, cx| { - let result = match route { - Route::Register => { - let invite = (!invite.is_empty()).then_some(invite); - network - .register(&username, &password, invite.as_deref()) - .await - } - Route::Login | Route::Chat => network.login(&username, &password).await, + let result = if route == Route::Register { + let invite = (!invite.is_empty()).then_some(invite); + network + .register(&username, &password, invite.as_deref()) + .await + } else { + network.login(&username, &password).await }; match result { @@ -124,10 +122,10 @@ fn server_toggle( entity: &Entity, address: &str, open: bool, - palette: Palette, + t: Tokens, ) -> impl IntoElement { let entity = entity.clone(); - clickable("server_toggle", palette, move |_, cx| { + clickable("server_toggle", t, move |_, cx| { entity.update(cx, |yumush, cx| { yumush.auth.server_open = !yumush.auth.server_open; cx.notify(); @@ -140,8 +138,8 @@ fn server_toggle( .flex() .items_center() .gap(px(space::XS)) - .text_size(text(text::CAPTION)) - .text_color(palette.muted) + .text_size(t.text(text::CAPTION)) + .text_color(t.dim()) .child(host(address).to_string()) .child( super::parts::small_icon(IconName::ChevronRight).with_animation( @@ -164,16 +162,17 @@ fn host(address: &str) -> &str { } } -fn password_field(palette: Palette, input: &Entity) -> Div { - frame(palette, Input::new(input).mask_toggle()) +fn password_field(t: Tokens, input: &Entity) -> Div { + frame(t, Input::new(input).mask_toggle()) } impl Yumush { pub(super) fn auth_page(&self, route: Route, cx: &mut Context) -> impl IntoElement { - let palette = palette(cx); - let action_label = match route { - Route::Register => w().auth.register, - Route::Login | Route::Chat => w().auth.log_in, + let t = Tokens::of(cx); + let action_label = if route == Route::Register { + w().auth.register + } else { + w().auth.log_in }; let entity = cx.entity(); @@ -182,7 +181,7 @@ impl Yumush { "auth_button", action_label, parts::Press::Primary, - palette.tokens, + t, move |window, cx| { submit_entity.update(cx, |this, cx| submit(this, window, cx)); }, @@ -194,17 +193,11 @@ impl Yumush { let maintenance = server.is_some_and(|settings| settings.maintenance); let title = server.map_or_else(|| "yumush".to_string(), |settings| settings.name.clone()); - let tabs = segment_track(palette) - .child(tab(palette, &entity, Route::Login, w().auth.log_in, route)) - .child(tab( - palette, - &entity, - Route::Register, - w().auth.register, - route, - )); + let tabs = segment_track(t) + .child(tab(t, &entity, Route::Login, w().auth.log_in, route)) + .child(tab(t, &entity, Route::Register, w().auth.register, route)); let invite = (route == Route::Register && !registration_open) - .then(|| field(palette, &self.auth.invite_input)); + .then(|| field(t, &self.auth.invite_input)); div() .flex() @@ -221,28 +214,28 @@ impl Yumush { .gap(px(space::MD)) .child( div() - .text_size(text(text::BODY)) + .text_size(t.text(text::BODY)) .font_weight(FontWeight::SEMIBOLD) .child(title), ) .children(maintenance.then(|| { div() - .text_size(text(text::CAPTION)) - .text_color(palette.muted) + .text_size(t.text(text::CAPTION)) + .text_color(t.dim()) .child(w().auth.maintenance) })) - .children(self.saved_accounts(&entity, palette, cx)) + .children(self.saved_accounts(&entity, t, cx)) .child(tabs) - .child(field(palette, &self.auth.username_input)) - .child(password_field(palette, &self.auth.password_input)) + .child(field(t, &self.auth.username_input)) + .child(password_field(t, &self.auth.password_input)) .children(invite) .child(action_button) - .children(connection_notice(&self.connection, palette)) + .children(connection_notice(&self.connection, t)) .child(server_toggle( &entity, &self.network.server().address, self.auth.server_open, - palette, + t, )) .child( div() @@ -251,19 +244,19 @@ impl Yumush { .flex() .flex_col() .gap(px(space::SM)) - .child(field(palette, &self.auth.server_input)) + .child(field(t, &self.auth.server_input)) .child( div() .flex() .items_center() .justify_between() - .text_size(text(text::CAPTION)) - .text_color(palette.muted) + .text_size(t.text(text::CAPTION)) + .text_color(t.dim()) .child(w().auth.accept_any_cert) .child(super::parts::toggle( "any_cert_switch", self.auth.any_cert, - palette.tokens, + t, { let entity = entity.clone(); move |_, cx| { @@ -287,21 +280,21 @@ impl Yumush { ) } - fn saved_accounts(&self, entity: &Entity, palette: Palette, cx: &App) -> Option
{ + fn saved_accounts(&self, entity: &Entity, t: Tokens, cx: &App) -> Option
{ (!self.accounts.list.is_empty()).then(|| { div() .flex() .flex_col() .gap(px(space::XS)) .pb(px(space::LG)) - .child(super::parts::caption_head(w().auth.saved, palette.tokens)) - .child(account_list(self, entity, false, None, palette, cx)) + .child(super::parts::caption_head(w().auth.saved, t)) + .child(account_list(self, entity, None, t, cx)) }) } } fn tab( - palette: Palette, + t: Tokens, entity: &Entity, target: Route, label: &'static str, @@ -309,13 +302,13 @@ fn tab( ) -> impl IntoElement { let entity = entity.clone(); segment( - clickable(label, palette, move |window, cx| { + clickable(label, t, move |window, cx| { entity.update(cx, |this, cx| this.change_page(target, window, cx)); }), route == target, - palette, + t, ) .flex_1() - .text_size(text(text::CAPTION)) + .text_size(t.text(text::CAPTION)) .child(label) } diff --git a/crates/client/src/gui/builder.rs b/crates/client/src/gui/builder.rs index 26ec3a2..d73490a 100644 --- a/crates/client/src/gui/builder.rs +++ b/crates/client/src/gui/builder.rs @@ -29,16 +29,22 @@ use gpui_kit::{ use self::ui::icon_button; use super::{ - Palette, Yumush, + Yumush, chat::View, entity_action, notify_error, parts::{self, Press}, settings_page::{frame, heading}, - style::{size, space, text}, - text, + style::{Tokens, size, space, text}, widget::search_text, }; use crate::net::NetworkHandle; +use common::share::Kind; + +pub(super) struct Transfer { + pub(super) community_id: Id, + pub(super) members: Vec, + pub(super) pending: Option, +} pub(super) fn save_directory() -> PathBuf { dirs::download_dir().unwrap_or_else(std::env::temp_dir) @@ -108,56 +114,46 @@ impl BuilderTab { } } -pub(super) struct Transfer { - pub(super) community_id: Id, - pub(super) members: Vec, - pub(super) pending: Option, -} - impl Yumush { pub(super) fn builder_page( &self, entity: &Entity, - palette: Palette, + t: Tokens, cx: &App, ) -> impl IntoElement { - let tab = self.chat.builder_tab; + let tab = self.chat.admin.builder_tab; let title = tab.label(); let body = match tab { BuilderTab::Overview => self - .overview_rows(palette) + .overview_rows(t) .into_iter() .map(IntoElement::into_any_element) .collect(), - BuilderTab::Users => self.users_body(entity, palette, cx), - BuilderTab::Communities => self.communities_body(entity, palette, cx), - BuilderTab::Messages => self.messages_body(entity, palette), - BuilderTab::Voice => self.voice_body(entity, palette), - BuilderTab::Storage => self.storage_body(entity, palette), - BuilderTab::Access => self.access_body(entity, palette), - BuilderTab::Reports => self.reports_body(entity, palette), - BuilderTab::Server => self.server_body(entity, palette), - BuilderTab::Releases => self.releases_body(entity, palette), - BuilderTab::Log => self.log_body(entity, palette), + BuilderTab::Users => self.users_body(entity, t, cx), + BuilderTab::Communities => self.communities_body(entity, t, cx), + BuilderTab::Messages => self.messages_body(entity, t), + BuilderTab::Voice => self.voice_body(entity, t), + BuilderTab::Storage => self.storage_body(entity, t), + BuilderTab::Access => self.access_body(entity, t), + BuilderTab::Reports => self.reports_body(entity, t), + BuilderTab::Server => self.server_body(entity, t), + BuilderTab::Releases => self.releases_body(entity, t), + BuilderTab::Log => self.log_body(entity, t), }; - let mut sections = vec![ - heading(title, self.tab_actions(tab, entity, palette, cx), palette).into_any_element(), - ]; + let mut sections = + vec![heading(title, self.tab_actions(tab, entity, t, cx), t).into_any_element()]; sections.extend(body); frame( "builder_scroll", entity, - palette, + t, Role::Builder.label(), BuilderTab::ALL - .map(|tab| { - self.builder_nav_item(tab, entity, palette) - .into_any_element() - }) + .map(|tab| self.builder_nav_item(tab, entity, t).into_any_element()) .into_iter() .collect(), - vec![self.ghost_toggle(entity, palette).into_any_element()], + vec![self.ghost_toggle(entity, t).into_any_element()], sections, ) } @@ -166,7 +162,7 @@ impl Yumush { &self, tab: BuilderTab, entity: &Entity, - palette: Palette, + t: Tokens, cx: &App, ) -> Vec { match tab { @@ -175,7 +171,7 @@ impl Yumush { "refresh_voice_button".to_string(), w().builder.refresh, Press::Plain, - palette.tokens, + t, entity_action(entity, |yumush, window, cx| { yumush.load_voice_rooms(window, cx) }), @@ -183,11 +179,11 @@ impl Yumush { .into_any_element(), ], BuilderTab::Server if self.server_form(cx) != self.server => vec![ - crate::gui::parts::button( + parts::button( "save_server", w().builder.save, - crate::gui::parts::Press::Plain, - palette.tokens, + Press::Plain, + t, entity_action(entity, |yumush, window, cx| { yumush.save_server_settings(window, cx) }), @@ -199,7 +195,7 @@ impl Yumush { "add_release_files".to_string(), w().builder_release.add_files, Press::Plain, - palette.tokens, + t, entity_action(entity, |yumush, window, cx| { yumush.pick_release_files(window, cx) }), @@ -211,8 +207,8 @@ impl Yumush { "export_builder_log".to_string(), IconName::Download, w().builder.export, - palette.muted, - palette, + t.dim(), + t, entity_action(entity, |yumush, window, cx| { yumush.export_builder_log(window, cx) }), @@ -227,17 +223,17 @@ impl Yumush { &self, tab: BuilderTab, entity: &Entity, - palette: Palette, + t: Tokens, ) -> impl IntoElement { let open = (tab == BuilderTab::Reports) - .then_some(self.chat.open_reports) + .then_some(self.chat.admin.open_reports) .filter(|count| *count > 0); - super::parts::index_item( + parts::index_item( format!("builder_tab_{}", tab.id()), tab.label(), - self.chat.builder_tab == tab, - palette.tokens, + self.chat.admin.builder_tab == tab, + t, entity_action(entity, move |yumush, window, cx| { yumush.select_builder_tab(tab, window, cx) }), @@ -245,14 +241,14 @@ impl Yumush { .children(open.map(|count| { div() .ml(px(space::SM)) - .text_size(text(text::CAPTION)) - .text_color(palette.danger) + .text_size(t.text(text::CAPTION)) + .text_color(t.bad()) .child(count.to_string()) })) } - fn ghost_toggle(&self, entity: &Entity, palette: Palette) -> impl IntoElement { - let enabled = self.chat.ghost; + fn ghost_toggle(&self, entity: &Entity, t: Tokens) -> impl IntoElement { + let enabled = self.chat.session.ghost; let toggle = entity_action(entity, move |yumush, window, cx| { yumush.set_ghost(!enabled, window, cx) }); @@ -262,15 +258,10 @@ impl Yumush { .flex() .items_center() .justify_between() - .text_size(text(text::LABEL)) - .text_color(palette.muted) + .text_size(t.text(text::LABEL)) + .text_color(t.dim()) .child(w().builder.ghost) - .child(super::parts::toggle( - "ghost_switch", - enabled, - palette.tokens, - toggle, - )) + .child(parts::toggle("ghost_switch", enabled, t, toggle)) } pub(super) fn is_builder(&self) -> bool { @@ -281,7 +272,7 @@ impl Yumush { pub(super) fn load_builder(&mut self, window: &mut Window, cx: &mut Context) { self.load_open_reports(window, cx); - match self.chat.builder_tab { + match self.chat.admin.builder_tab { BuilderTab::Overview => self.load_overview(window, cx), BuilderTab::Users => self.load_users(window, cx), BuilderTab::Communities => self.load_builder_communities(window, cx), @@ -309,9 +300,13 @@ impl Yumush { } } + pub(super) fn on_builder_tab(&self, tab: BuilderTab) -> bool { + self.chat.session.view == View::Builder && self.chat.admin.builder_tab == tab + } + pub(super) fn report_created(&self, window: &mut Window, cx: &mut Context) { self.load_open_reports(window, cx); - if self.chat.view == View::Builder && self.chat.builder_tab == BuilderTab::Reports { + if self.on_builder_tab(BuilderTab::Reports) { self.load_reports(window, cx); } } @@ -322,7 +317,7 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) { - self.chat.builder_tab = tab; + self.chat.admin.builder_tab = tab; if tab == BuilderTab::Server { self.fill_server_form(window, cx); } @@ -374,7 +369,7 @@ impl Yumush { .as_ref() .and_then(|me| accounts.iter().find(|account| account.user.id == me.id)) .is_some_and(|account| account.ghost); - yumush.chat.builder_users = accounts; + yumush.chat.admin.builder_users = accounts; yumush.set_ghost_state(ghost); cx.notify(); }, @@ -382,19 +377,20 @@ impl Yumush { } pub(super) fn releases_changed(&mut self, window: &mut Window, cx: &mut Context) { - if self.chat.view == View::Builder && self.chat.builder_tab == BuilderTab::Releases { + if self.on_builder_tab(BuilderTab::Releases) { self.load_releases(window, cx); } } pub(super) fn voice_changed(&self, window: &mut Window, cx: &mut Context) { - if self.chat.view == View::Builder && self.chat.builder_tab == BuilderTab::Voice { + if self.on_builder_tab(BuilderTab::Voice) { self.load_voice_rooms(window, cx); } } fn resolve_user(&self, username: &str) -> Option { self.chat + .admin .builder_users .iter() .find(|account| account.user.username.to_lowercase() == username) @@ -403,6 +399,7 @@ impl Yumush { fn resolve_community(&self, name: &str) -> Option { self.chat + .admin .builder_communities .iter() .find(|summary| { @@ -432,12 +429,13 @@ impl Yumush { } fn set_ghost_state(&mut self, ghost: bool) { - self.chat.ghost = ghost; + self.chat.session.ghost = ghost; let Some(me) = self.user.as_ref() else { return; }; if let Some(account) = self .chat + .admin .builder_users .iter_mut() .find(|account| account.user.id == me.id) @@ -451,8 +449,8 @@ impl Yumush { cx.spawn_in(window, async move |this, cx| { if enabled { - let _ = network.stop_share().await; - let _ = network.stop_camera().await; + let _ = network.stop(Kind::Screen).await; + let _ = network.stop(Kind::Camera).await; } match network.call(SetGhost { enabled }).await { Ok(()) => { diff --git a/crates/client/src/gui/builder/access.rs b/crates/client/src/gui/builder/access.rs index 206a682..d1ac2e8 100644 --- a/crates/client/src/gui/builder/access.rs +++ b/crates/client/src/gui/builder/access.rs @@ -9,28 +9,15 @@ use gpui_kit::{ }; use super::ui::{ - card, card_header, confirmed, delete_icon_button, fixed, icon_button, list_row, pill, toolbar, + card, card_header, delete_icon_button, fixed, icon_button, list_card, list_row, number, pill, + rows_body, toolbar, }; -use crate::gui::style::{size, space, text}; -use crate::gui::{Palette, Yumush, entity_action, millis_time, notify_error, text, widget::field}; +use crate::gui::chat::Armed; +use crate::gui::style::{Tokens, size, space, text}; +use crate::gui::{Yumush, entity_action, millis_time, notify_error, text, widget::field}; use crate::lang::w; -fn list_card(header: Div, rows: Vec
, none: &str, palette: Palette) -> Div { - let body = if rows.is_empty() { - crate::gui::parts::empty(none, palette.tokens) - } else { - div().flex().flex_col().children(rows) - }; - - card(palette).child(header).child(body) -} - -fn invite_row( - invite: &InviteCode, - pending: bool, - entity: &Entity, - palette: Palette, -) -> Div { +fn invite_row(invite: &InviteCode, pending: bool, entity: &Entity, t: Tokens) -> Div { let copy_code = invite.code.clone(); let delete_code = invite.code.clone(); let expiry = invite.expires_at.map_or_else( @@ -62,7 +49,7 @@ fn invite_row( .child( div() .text_size(text(text::CAPTION)) - .text_color(palette.muted) + .text_color(t.dim()) .truncate() .child(format!("{left} · {expiry}")), ), @@ -71,23 +58,21 @@ fn invite_row( format!("copy_invite_{}", invite.code), IconName::Copy, w().builder_access.copy, - palette.muted, - palette, - entity_action(entity, move |yumush, _, cx| { - yumush.copy_invite(©_code, cx) - }), + t.dim(), + t, + move |_, cx| cx.write_to_clipboard(ClipboardItem::new_string(copy_code.clone())), )) .child(delete_icon_button( format!("delete_invite_{}", invite.code), pending, - palette, + t, entity_action(entity, move |yumush, window, cx| { yumush.delete_invite(&delete_code, window, cx) }), )) } -fn ban_row(ban: &ServerBan, entity: &Entity, palette: Palette) -> Div { +fn ban_row(ban: &ServerBan, entity: &Entity, t: Tokens) -> Div { let remove_id = ban.id; let kind = match ban.kind { ServerBanKind::Ip => "IP", @@ -96,7 +81,7 @@ fn ban_row(ban: &ServerBan, entity: &Entity, palette: Palette) -> Div { list_row() .px(px(space::LG)) - .child(pill(kind, palette.text, palette)) + .child(pill(kind, t.paper())) .child( div() .flex_1() @@ -112,7 +97,7 @@ fn ban_row(ban: &ServerBan, entity: &Entity, palette: Palette) -> Div { .children(ban.reason.as_ref().map(|reason| { div() .text_size(text(text::CAPTION)) - .text_color(palette.muted) + .text_color(t.dim()) .min_w_0() .child(super::super::glyph::line( reason.clone().into(), @@ -124,8 +109,8 @@ fn ban_row(ban: &ServerBan, entity: &Entity, palette: Palette) -> Div { format!("remove_ban_{}", ban.id), IconName::X, w().builder_access.remove, - palette.muted, - palette, + t.dim(), + t, entity_action(entity, move |yumush, window, cx| { yumush.remove_ban(remove_id, window, cx) }), @@ -144,7 +129,7 @@ impl Yumush { cx, |network| async move { network.call(ListInviteCodes).await }, |yumush, codes, cx| { - yumush.chat.builder_invites = codes; + yumush.chat.admin.builder_invites = codes; cx.notify(); }, ); @@ -156,24 +141,25 @@ impl Yumush { cx, |network| async move { network.call(ListServerBans).await }, |yumush, bans, cx| { - yumush.chat.builder_bans = bans; + yumush.chat.admin.builder_bans = bans; cx.notify(); }, ); } pub(super) fn create_invite(&mut self, window: &mut Window, cx: &mut Context) { - let uses = self.chat.invite_uses.read(cx).text().to_string(); - let Ok(uses) = uses.trim().parse::() else { + let uses = self.chat.admin.invite_uses.read(cx).text().to_string(); + let Some(uses) = number(&uses) else { return; }; - let hours = self.chat.invite_hours.read(cx).text().to_string(); - let hours = match hours.trim() { - "" => None, - text => match text.parse::() { - Ok(hours) => Some(hours), - Err(_) => return, - }, + let hours = self.chat.admin.invite_hours.read(cx).text().to_string(); + let hours = if hours.trim().is_empty() { + None + } else { + let Some(hours) = number(&hours) else { + return; + }; + Some(hours) }; let network = self.network.clone(); @@ -195,8 +181,7 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) { - if !confirmed(&mut self.chat.pending_invite_delete, code.to_string()) { - cx.notify(); + if !self.arm(Armed::DeleteInvite(code.to_string()), cx) { return; } let network = self.network.clone(); @@ -214,10 +199,6 @@ impl Yumush { .detach(); } - pub(super) fn copy_invite(&self, code: &str, cx: &mut Context) { - cx.write_to_clipboard(ClipboardItem::new_string(code.to_string())); - } - pub(super) fn remove_ban(&mut self, id: Id, window: &mut Window, cx: &mut Context) { let network = self.network.clone(); @@ -233,15 +214,15 @@ impl Yumush { .detach(); } - pub(super) fn access_body(&self, entity: &Entity, palette: Palette) -> Vec { + pub(super) fn access_body(&self, entity: &Entity, t: Tokens) -> Vec { let controls = toolbar(vec![ - fixed(80., field(palette, &self.chat.invite_uses)), - fixed(size::THUMB, field(palette, &self.chat.invite_hours)), + fixed(80., field(t, &self.chat.admin.invite_uses)), + fixed(size::THUMB, field(t, &self.chat.admin.invite_hours)), crate::gui::parts::button( "create_invite", w().builder_access.create, crate::gui::parts::Press::Plain, - palette.tokens, + t, entity_action(entity, |yumush, window, cx| { yumush.create_invite(window, cx) }), @@ -249,27 +230,30 @@ impl Yumush { .into_any_element(), ]) .into_any_element(); - let invite_header = card_header(w().builder_access.invite_codes, vec![controls], palette); - let invites = self.chat.builder_invites.iter().map(|invite| { - let pending = self.chat.pending_invite_delete.as_deref() == Some(invite.code.as_str()); - invite_row(invite, pending, entity, palette) + let invite_header = card_header(w().builder_access.invite_codes, vec![controls], t); + let invites = self.chat.admin.builder_invites.iter().map(|invite| { + let pending = self.armed(Armed::DeleteInvite(invite.code.clone())); + invite_row(invite, pending, entity, t) }); let bans = self .chat + .admin .builder_bans .iter() - .map(|ban| ban_row(ban, entity, palette)); - let ban_header = card_header(w().builder_access.bans, Vec::new(), palette); + .map(|ban| ban_row(ban, entity, t)) + .collect(); vec![ - list_card( - invite_header, - invites.collect(), - w().builder_access.no_invite_codes, - palette, - ) - .into_any_element(), - list_card(ban_header, bans.collect(), w().common.no_bans, palette).into_any_element(), + card() + .child(invite_header) + .child(rows_body( + invites.collect(), + w().builder_access.no_invite_codes, + t, + )) + .into_any_element(), + list_card(Some(w().builder_access.bans), bans, w().common.no_bans, t) + .into_any_element(), ] } } diff --git a/crates/client/src/gui/builder/backups.rs b/crates/client/src/gui/builder/backups.rs index 5a30b93..2d8881f 100644 --- a/crates/client/src/gui/builder/backups.rs +++ b/crates/client/src/gui/builder/backups.rs @@ -9,25 +9,24 @@ use gpui_kit::{ use super::{ save_directory, - ui::{card, card_header, confirmed, delete_icon_button, icon_button, list_row}, + ui::{card, card_header, confirmed, delete_icon_button, icon_button, list_row, rows_body}, }; use crate::gui::{ - Palette, Yumush, entity_action, millis_time, notify_error, storage, - style::{size, text}, - text, + Yumush, entity_action, millis_time, notify_error, storage, + style::{Tokens, size, text}, }; use crate::lang::w; const STORAGE_WIDTH: f32 = 72.; -fn backup_row(info: &BackupInfo, pending: bool, entity: &Entity, palette: Palette) -> Div { +fn backup_row(info: &BackupInfo, pending: bool, entity: &Entity, t: Tokens) -> Div { let export_name = info.name.clone(); let export = icon_button( format!("export_backup_{}", info.name), IconName::Download, w().builder_backups.export, - palette.muted, - palette, + t.dim(), + t, entity_action(entity, move |yumush, window, cx| { yumush.export_backup(&export_name, window, cx) }), @@ -37,7 +36,7 @@ fn backup_row(info: &BackupInfo, pending: bool, entity: &Entity, palette let delete = delete_icon_button( format!("delete_backup_{}", info.name), pending, - palette, + t, entity_action(entity, move |yumush, window, cx| { yumush.delete_backup(&delete_name, window, cx) }), @@ -48,22 +47,22 @@ fn backup_row(info: &BackupInfo, pending: bool, entity: &Entity, palette Icon::new(IconName::HardDrive) .size(px(size::ICON)) .flex_shrink_0() - .text_color(palette.muted), + .text_color(t.dim()), ) .child( div() .flex_1() .min_w_0() .truncate() - .text_size(text(text::LABEL)) - .text_color(palette.text) + .text_size(t.text(text::LABEL)) + .text_color(t.paper()) .child(info.name.clone()), ) .child( div() .flex_shrink_0() - .text_size(text(text::CAPTION)) - .text_color(palette.muted) + .text_size(t.text(text::CAPTION)) + .text_color(t.dim()) .child(millis_time(info.created_ms, crate::lang::w().common.date)), ) .child( @@ -72,8 +71,8 @@ fn backup_row(info: &BackupInfo, pending: bool, entity: &Entity, palette .flex_shrink_0() .flex() .justify_end() - .text_size(text(text::CAPTION)) - .text_color(palette.muted) + .text_size(t.text(text::CAPTION)) + .text_color(t.dim()) .child(storage(info.size_bytes)), ) .child(export) @@ -81,38 +80,30 @@ fn backup_row(info: &BackupInfo, pending: bool, entity: &Entity, palette } impl Yumush { - pub(super) fn backups_card(&self, entity: &Entity, palette: Palette) -> Div { + pub(super) fn backups_card(&self, entity: &Entity, t: Tokens) -> Div { let create = crate::gui::parts::button( "create_backup", w().builder_backups.create, crate::gui::parts::Press::Plain, - palette.tokens, + t, entity_action(entity, |yumush, window, cx| { yumush.create_backup(window, cx) }), ) .into_any_element(); let rows: Vec
= self + .desk .backups .iter() .map(|info| { - let pending = self.pending_backup_delete.as_deref() == Some(info.name.as_str()); - backup_row(info, pending, entity, palette) + let pending = self.desk.pending_backup.as_deref() == Some(info.name.as_str()); + backup_row(info, pending, entity, t) }) .collect(); - let body = if rows.is_empty() { - crate::gui::parts::empty(w().builder_backups.no_backups, palette.tokens) - } else { - div().flex().flex_col().children(rows) - }; - card(palette) - .child(card_header( - w().builder_backups.backups, - vec![create], - palette, - )) - .child(body) + card() + .child(card_header(w().builder_backups.backups, vec![create], t)) + .child(rows_body(rows, w().builder_backups.no_backups, t)) } pub(super) fn load_backups(&self, window: &mut Window, cx: &mut Context) { @@ -121,7 +112,7 @@ impl Yumush { cx, |network| async move { network.call(ListBackups).await }, |yumush, backups, cx| { - yumush.backups = backups; + yumush.desk.backups = backups; cx.notify(); }, ); @@ -143,7 +134,7 @@ impl Yumush { } fn delete_backup(&mut self, name: &str, window: &mut Window, cx: &mut Context) { - if !confirmed(&mut self.pending_backup_delete, name.to_string()) { + if !confirmed(&mut self.desk.pending_backup, name.to_string()) { cx.notify(); return; } diff --git a/crates/client/src/gui/builder/ci_view.rs b/crates/client/src/gui/builder/ci_view.rs index 8077400..6c5ebd2 100644 --- a/crates/client/src/gui/builder/ci_view.rs +++ b/crates/client/src/gui/builder/ci_view.rs @@ -1,23 +1,25 @@ use std::{collections::HashMap, rc::Rc, time::Duration}; -use common::call::{CreateTag, GetForge}; +use common::{ + call::{CreateTag, GetForge}, + model::Hue, +}; use gpui_kit::{ Anchor, AnyElement, App, Context, Div, Entity, Focusable, InteractiveElement, IntoElement, - ListHorizontalSizingBehavior, ParentElement, ScrollStrategy, Styled, Window, + ListHorizontalSizingBehavior, ParentElement, ScrollStrategy, Styled, Task, Window, component::popover::{Popover, PopoverState}, div, px, uniform_list, }; -use super::releases::caption_text; -use super::ui::{card, list_row}; +use super::ui::{caption_text, card, list_row}; use crate::ci::{self, Event, Job, Run, State}; use crate::gui::builder::BuilderTab; use crate::gui::chat::View; use crate::gui::{ - Palette, Trigger, Yumush, entity_action, hoverable, notify_error, + Trigger, Yumush, entity_action, hoverable, notify_error, parts::{self, Fill, Press}, profile::yumush_action, - style::{radius, size, space, text}, + style::{Tokens, radius, size, space, text}, text, }; use crate::lang::w; @@ -26,16 +28,23 @@ const LOG_LINE: f32 = 18.; const LOG_MAX: usize = 50_000; const TICK: Duration = Duration::from_secs(1); +#[derive(Default, PartialEq, Eq)] +enum Banner { + #[default] + Hidden, + Shown, + Dismissed, +} + #[derive(Default)] pub(crate) struct Live { repo: Option, watch: Option, + ticks: Option>, run: Option, logs: HashMap>, log_open: Option, - seen_live: bool, - dismissed: bool, - tagging: bool, + banner: Banner, } impl Live { @@ -48,7 +57,7 @@ impl Live { } fn shown(&self) -> bool { - self.run.is_some() && self.seen_live && !self.dismissed + self.banner == Banner::Shown } fn done(&self) -> usize { @@ -65,12 +74,13 @@ impl Live { self.done() as f32 / total.max(1) as f32 } - fn failed(&self) -> bool { - self.state() == Some(State::Failed) + fn tally(&self) -> String { + let total = self.run.as_ref().map_or(0, |run| run.jobs.len()); + format!("{} / {total}", self.done()) } - pub(super) fn tagging(&self) -> bool { - self.tagging + fn failed(&self) -> bool { + self.state() == Some(State::Failed) } } @@ -99,14 +109,14 @@ fn run_label(state: State) -> &'static str { } } -fn job_status(state: State, palette: Palette) -> Div { +fn job_status(state: State, t: Tokens) -> Div { let w = &w().builder_release; match state { - State::Waiting => caption_text(w.waiting, palette.muted), - State::Running => caption_text(w.running, palette.text), - State::Success => caption_text(w.done, palette.ok), - State::Skipped => caption_text(w.skipped, palette.muted), - State::Failed => caption_text(w.failed, palette.danger), + State::Waiting => caption_text(w.waiting, t.dim()), + State::Running => caption_text(w.running, t.paper()), + State::Success => caption_text(w.done, t.hue(Hue::Mint)), + State::Skipped => caption_text(w.skipped, t.dim()), + State::Failed => caption_text(w.failed, t.bad()), } } @@ -115,7 +125,7 @@ fn job_row( log: Option<&Vec>, seconds: bool, entity: &Entity, - palette: Palette, + t: Tokens, ) -> Div { let state = State::of(&job.state); let step = job.steps.last().map(|step| step.name.as_str()); @@ -134,10 +144,10 @@ fn job_row( .child( div() .text_size(text(text::LABEL)) - .text_color(palette.text) + .text_color(t.paper()) .child(job.label().to_string()), ) - .children(detail.map(|detail| caption_text(detail, palette.muted).truncate())); + .children(detail.map(|detail| caption_text(detail, t.dim()).truncate())); let id = job.id.clone(); let entity = entity.clone(); list_row() @@ -150,19 +160,19 @@ fn job_row( .content(move |_, window, cx| log_sheet(&id, &entity, window, cx)), ), ) - .child(job_status(state, palette)) + .child(job_status(state, t)) .children( span( job.started_at.as_deref(), job.finished_at.as_deref(), seconds, ) - .map(|time| caption_text(time, palette.muted)), + .map(|time| caption_text(time, t.dim())), ) } fn log_sheet(job: &str, entity: &Entity, window: &mut Window, cx: &mut App) -> Div { - let palette = crate::gui::palette(cx); + let t = Tokens::of(cx); let input = entity.read(cx).log_search.clone(); if !input.read(cx).focus_handle(cx).contains_focused(window, cx) { input.update(cx, |state, cx| state.focus(window, cx)); @@ -191,16 +201,16 @@ fn log_sheet(job: &str, entity: &Entity, window: &mut Window, cx: &mut A } let job = job.to_string(); let entity = entity.clone(); - crate::gui::widget::panel(palette) + parts::surface(t) .w(px(size::PAGE - space::XL)) .p(px(space::XS)) .flex() .flex_col() .gap(px(space::XS)) - .child(crate::gui::sidebar::input_box(&input, palette)) + .child(crate::gui::sidebar::input_box(&input, t)) .child( uniform_list(format!("ci_log_lines_{job}"), count, move |range, _, cx| { - let palette = crate::gui::palette(cx); + let t = Tokens::of(cx); let Some(log) = entity.read(cx).desk.live.logs.get(&job) else { return Vec::new(); }; @@ -213,7 +223,7 @@ fn log_sheet(job: &str, entity: &Entity, window: &mut Window, cx: &mut A .px(px(space::XS)) .whitespace_nowrap() .text_size(text(text::CAPTION)) - .text_color(palette.muted) + .text_color(t.dim()) .child(line.clone()) }) .collect() @@ -235,9 +245,27 @@ impl Yumush { return; }; let (watch, mut events) = ci::watch(repo.clone()); + let ticks = cx.spawn({ + let this = this.clone(); + async move |cx| { + loop { + cx.background_executor().timer(TICK).await; + let ticked = this.update_in(cx, |yumush, window, cx| { + if yumush.desk.live.live() { + window.refresh(); + cx.notify(); + } + }); + if ticked.is_err() { + break; + } + } + } + }); let started = this.update(cx, |yumush, _| { yumush.desk.live.repo = Some(repo); yumush.desk.live.watch = Some(watch); + yumush.desk.live.ticks = Some(ticks); }); if started.is_err() { return; @@ -255,24 +283,6 @@ impl Yumush { .detach(); }) .detach(); - cx.spawn_in(window, async move |this, cx| { - loop { - cx.background_executor().timer(TICK).await; - let Ok(watching) = this.update_in(cx, |yumush, window, cx| { - if yumush.desk.live.live() { - window.refresh(); - cx.notify(); - } - yumush.desk.live.watch.is_some() - }) else { - break; - }; - if !watching { - break; - } - } - }) - .detach(); } fn ci_event(&mut self, event: Event, cx: &mut Context) { @@ -281,11 +291,10 @@ impl Yumush { Event::Run(run) => { if live.run.as_ref().map(|old| old.number) != Some(run.number) { live.logs.clear(); - live.dismissed = false; - live.seen_live = false; + live.banner = Banner::Hidden; } - if !State::of(&run.state).finished() { - live.seen_live = true; + if live.banner == Banner::Hidden && !State::of(&run.state).finished() { + live.banner = Banner::Shown; } live.run = Some(run); } @@ -341,16 +350,16 @@ impl Yumush { pub(super) fn create_tag(&mut self, window: &mut Window, cx: &mut Context) { let tag = self.release_tag_text(cx); - if tag.is_empty() || self.desk.live.tagging { + if tag.is_empty() || self.desk.tagging { return; } - self.desk.live.tagging = true; + self.desk.tagging = true; cx.notify(); let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { let result = network.call(CreateTag { tag }).await; let _ = this.update(cx, |yumush, cx| { - yumush.desk.live.tagging = false; + yumush.desk.tagging = false; cx.notify(); }); if let Err(error) = result { @@ -360,7 +369,7 @@ impl Yumush { .detach(); } - fn run_head(&self, palette: Palette) -> Option
{ + fn run_head(&self, t: Tokens) -> Option
{ let live = &self.desk.live; let run = live.run.as_ref()?; let state = State::of(&run.state); @@ -374,7 +383,7 @@ impl Yumush { let aside = if state.finished() { time } else { - format!("{} / {} · {time}", live.done(), run.jobs.len()) + format!("{} · {time}", live.tally()) }; Some( div() @@ -384,42 +393,32 @@ impl Yumush { .text_size(text(text::LABEL)) .child( div() - .text_color(if live.failed() { - palette.danger - } else { - palette.text - }) + .text_color(if live.failed() { t.bad() } else { t.paper() }) .child(format!("#{} · {name} · {}", run.number, run_label(state))), ) - .child(div().text_color(palette.muted).child(aside)), + .child(div().text_color(t.dim()).child(aside)), ) } - fn ci_rows( - &self, - entity: &Entity, - fit: impl Fn(Div) -> Div, - palette: Palette, - ) -> Vec
{ + fn ci_rows(&self, entity: &Entity, compact: bool, t: Tokens) -> Vec
{ let live = &self.desk.live; let seconds = self.settings.clock_seconds; live.run.as_ref().map_or_else(Vec::new, |run| { run.jobs .iter() .map(|job| { - fit(job_row( - job, - live.logs.get(&job.id), - seconds, - entity, - palette, - )) + let row = job_row(job, live.logs.get(&job.id), seconds, entity, t); + if compact { + row.min_h(px(size::CONTROL)).py(px(space::XXS)) + } else { + row + } }) .collect() }) } - fn import_run_button(&self, entity: &Entity, palette: Palette) -> Option { + fn import_run_button(&self, entity: &Entity, t: Tokens) -> Option { let run = self.desk.live.run.as_ref()?; let tag = run.tag()?.to_string(); (State::of(&run.state) == State::Success).then(|| { @@ -427,7 +426,7 @@ impl Yumush { "ci_import", w().builder_release.import, Press::Primary, - palette.tokens, + t, entity_action(entity, move |yumush, window, cx| { yumush.import_tag(tag.clone(), window, cx) }), @@ -436,19 +435,19 @@ impl Yumush { }) } - pub(super) fn ci_card(&self, entity: &Entity, palette: Palette) -> Option
{ - let head = self.run_head(palette)?; + pub(super) fn ci_card(&self, entity: &Entity, t: Tokens) -> Option
{ + let head = self.run_head(t)?; Some( - card(palette) + card() .child(head) .child(parts::track( Fill::Part(self.desk.live.share()), self.desk.live.failed(), - palette.tokens, + t, )) - .children(self.ci_rows(entity, |row| row, palette)) + .children(self.ci_rows(entity, false, t)) .children( - self.import_run_button(entity, palette) + self.import_run_button(entity, t) .map(|button| list_row().justify_end().child(button)), ), ) @@ -457,7 +456,7 @@ impl Yumush { pub(in crate::gui) fn build_control( &self, entity: &Entity, - palette: Palette, + t: Tokens, ) -> Option { let live = &self.desk.live; if !live.shown() { @@ -473,7 +472,7 @@ impl Yumush { ) .unwrap_or_default() } else { - format!("{} / {}", live.done(), run.jobs.len()) + live.tally() }; let failed = live.failed(); let trigger = hoverable( @@ -492,17 +491,13 @@ impl Yumush { .text_size(text(text::LABEL)) .child( div() - .text_color(if failed { palette.danger } else { palette.text }) + .text_color(if failed { t.bad() } else { t.paper() }) .child(run_label(state)), ) - .child(div().text_color(palette.muted).child(aside)), + .child(div().text_color(t.dim()).child(aside)), ) - .child(parts::track( - Fill::Part(live.share()), - failed, - palette.tokens, - )), - palette, + .child(parts::track(Fill::Part(live.share()), failed, t)), + t, ); let entity = entity.clone(); Some( @@ -512,25 +507,20 @@ impl Yumush { .trigger(Trigger::new(trigger)) .content(move |_, _, cx| { let popover = cx.entity(); - let palette = crate::gui::palette(cx); - entity.read(cx).build_sheet(&entity, &popover, palette) + let t = Tokens::of(cx); + entity.read(cx).build_sheet(&entity, &popover, t) }) .into_any_element(), ) } - fn build_sheet( - &self, - entity: &Entity, - popover: &Entity, - palette: Palette, - ) -> Div { + fn build_sheet(&self, entity: &Entity, popover: &Entity, t: Tokens) -> Div { let w = &w().builder_release; let open = parts::button( "build_open_releases", w.open_releases, Press::Plain, - palette.tokens, + t, yumush_action(entity, popover, |yumush, window, cx| { yumush.show_view(View::Builder, window, cx); yumush.select_builder_tab(BuilderTab::Releases, window, cx); @@ -541,29 +531,25 @@ impl Yumush { "build_sheet_dismiss", w.dismiss, Press::Plain, - palette.tokens, + t, yumush_action(entity, popover, |yumush, _, cx| { - yumush.desk.live.dismissed = true; + yumush.desk.live.banner = Banner::Dismissed; cx.notify(); }), ) }); - parts::popover(palette.tokens) + parts::popover(t) .w(px(size::SHEET)) .p(px(space::MD)) - .children(self.run_head(palette)) - .children(self.ci_rows( - entity, - |row| row.min_h(px(size::CONTROL)).py(px(space::XXS)), - palette, - )) + .children(self.run_head(t)) + .children(self.ci_rows(entity, true, t)) .child( div() .pt(px(space::SM)) .flex() .justify_between() .child(open) - .children(self.import_run_button(entity, palette)) + .children(self.import_run_button(entity, t)) .children(dismiss), ) } diff --git a/crates/client/src/gui/builder/communities.rs b/crates/client/src/gui/builder/communities.rs index d0657f0..cb1d722 100644 --- a/crates/client/src/gui/builder/communities.rs +++ b/crates/client/src/gui/builder/communities.rs @@ -1,60 +1,33 @@ use common::model::Id; use common::{ - call::{ - DeleteCommunity, GetCommunity, ListAllCommunities, ListMembers, SetCommunityVoice, - TransferOwnership, - }, + call::{DeleteCommunity, GetCommunity, ListAllCommunities, ListMembers, TransferOwnership}, model::{Community, CommunitySummary, Member, Rank}, }; use gpui_kit::{ AnyElement, App, Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window, - assets::IconName, div, prelude::FluentBuilder as _, px, + assets::IconName, div, px, }; -use super::{ - Transfer, - ui::{card, confirmed, icon_button, list_row, pill, rows_body}, -}; +use super::Transfer; +use super::ui::{card, delete_icon_button, icon_button, list_row, pill, rows_body}; use crate::gui::{ - Palette, Yumush, avatar, community_icon, entity_action, notify_error, + Yumush, avatar, + chat::Armed, + community_icon, entity_action, notify_error, parts::{self, Press}, profile::user_link, - style::{radius, size, space, text}, + style::{Tokens, radius, size, space, text}, text, widget::search_text, }; use crate::lang::w; impl Yumush { - pub(super) fn set_builder_community_voice( - &mut self, - community_id: Id, - enabled: bool, + pub(in crate::gui) fn load_builder_communities( + &self, window: &mut Window, cx: &mut Context, ) { - let network = self.network.clone(); - - cx.spawn_in(window, async move |this, cx| { - match network - .call(SetCommunityVoice { - community_id, - enabled, - }) - .await - { - Ok(_) => { - let _ = this.update_in(cx, |yumush, window, cx| { - yumush.load_builder_communities(window, cx) - }); - } - Err(error) => notify_error(&this, cx, error), - } - }) - .detach(); - } - - pub(super) fn load_builder_communities(&self, window: &mut Window, cx: &mut Context) { self.fetch_builder( window, cx, @@ -68,7 +41,7 @@ impl Yumush { yumush.request_user_avatar(owner, cx); } } - yumush.chat.builder_communities = summaries; + yumush.chat.admin.builder_communities = summaries; cx.notify(); }, ); @@ -80,8 +53,7 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) { - if !confirmed(&mut self.chat.pending_community_delete, community_id) { - cx.notify(); + if !self.arm(Armed::BuilderDeleteCommunity(community_id), cx) { return; } let network = self.network.clone(); @@ -90,7 +62,7 @@ impl Yumush { match network.call(DeleteCommunity { community_id }).await { Ok(()) => { let _ = this.update_in(cx, |yumush, window, cx| { - yumush.chat.remove_community(community_id); + yumush.forget_community(community_id, cx); yumush.load_builder_communities(window, cx); }); } @@ -108,15 +80,16 @@ impl Yumush { ) { if self .chat + .admin .transfer .as_ref() .is_some_and(|transfer| transfer.community_id == community_id) { - self.chat.transfer = None; + self.chat.admin.transfer = None; cx.notify(); return; } - self.chat.transfer = Some(Transfer { + self.chat.admin.transfer = Some(Transfer { community_id, members: Vec::new(), pending: None, @@ -146,7 +119,7 @@ impl Yumush { for member in &members { yumush.request_user_avatar(&member.user, cx); } - let Some(transfer) = yumush.chat.transfer.as_mut() else { + let Some(transfer) = yumush.chat.admin.transfer.as_mut() else { return; }; if transfer.community_id == community_id { @@ -159,8 +132,8 @@ impl Yumush { .detach(); } - pub(super) fn transfer_rows(&self, entity: &Entity, palette: Palette) -> Vec { - let Some(transfer) = &self.chat.transfer else { + pub(super) fn transfer_rows(&self, entity: &Entity, t: Tokens) -> Vec { + let Some(transfer) = &self.chat.admin.transfer else { return Vec::new(); }; @@ -170,17 +143,18 @@ impl Yumush { .filter(|member| member.rank != Rank::Owner) .map(|member| { let pending = transfer.pending == Some(member.user.id); - self.transfer_row(member, pending, entity, palette) + self.transfer_row(member, pending, entity, t) .into_any_element() }) .collect() } pub(super) fn transfer_to(&mut self, user_id: Id, window: &mut Window, cx: &mut Context) { - let Some(transfer) = self.chat.transfer.as_mut() else { + let Some(transfer) = self.chat.admin.transfer.as_mut() else { return; }; - if !confirmed(&mut transfer.pending, user_id) { + if transfer.pending.take() != Some(user_id) { + transfer.pending = Some(user_id); window.refresh(); cx.notify(); return; @@ -198,7 +172,7 @@ impl Yumush { { Ok(()) => { let _ = this.update_in(cx, |yumush, window, cx| { - yumush.chat.transfer = None; + yumush.chat.admin.transfer = None; yumush.load_builder_communities(window, cx); }); } @@ -248,11 +222,7 @@ impl Yumush { cx: &mut Context, ) { let community_id = community.id; - if self.chat.joined(community_id) { - self.select_community(community_id, window, cx); - } else { - self.open_builder_community(community, window, cx); - } + self.open_builder_community(community, window, cx); if voice && !self.chat.in_voice(community_id) { self.toggle_voice(community_id, window, cx); } @@ -266,7 +236,7 @@ impl Yumush { ) { let community_id = community.id; if !self.chat.joined(community_id) { - self.chat.opened = Some(community); + self.chat.session.opened = Some(community); } self.select_community(community_id, window, cx); } @@ -274,12 +244,13 @@ impl Yumush { pub(super) fn communities_body( &self, entity: &Entity, - palette: Palette, + t: Tokens, cx: &App, ) -> Vec { - let query = search_text(&self.chat.builder_search, cx); + let query = search_text(&self.chat.admin.builder_search, cx); let rows: Vec
= self .chat + .admin .builder_communities .iter() .filter(|summary| { @@ -289,22 +260,22 @@ impl Yumush { .to_lowercase() .contains(query.as_str()) }) - .map(|summary| self.community_row(summary, entity, palette)) + .map(|summary| self.community_row(summary, entity, t)) .collect(); vec![ - card(palette) + card() .child( div().pb(px(space::SM)).flex().items_center().child( div() .w(px(size::SIDEBAR)) .child(crate::gui::sidebar::input_box( - &self.chat.builder_search, - palette, + &self.chat.admin.builder_search, + t, )), ), ) - .child(rows_body(rows, w().builder_communities.empty, palette)) + .child(rows_body(rows, w().builder_communities.empty, t)) .into_any_element(), ] } @@ -314,7 +285,7 @@ impl Yumush { member: &Member, pending: bool, entity: &Entity, - palette: Palette, + t: Tokens, ) -> Div { let user_id = member.user.id; @@ -334,11 +305,11 @@ impl Yumush { .items_center() .gap(px(space::SM)) .child(avatar( - palette, + t, &member.user, px(size::AVATAR), text(text::CAPTION), - &self.chat.avatars, + &self.chat.session.avatars, )) .child( div() @@ -356,7 +327,7 @@ impl Yumush { w().builder_communities.transfer }, Press::Plain, - palette.tokens, + t, entity_action(entity, move |yumush, window, cx| { yumush.transfer_to(user_id, window, cx) }), @@ -367,19 +338,16 @@ impl Yumush { &self, summary: &CommunitySummary, entity: &Entity, - palette: Palette, + t: Tokens, ) -> Div { let community = &summary.community; - let opened = community.clone(); let id = community.id; - let log_id = id; - let transfer_id = id; - let delete_id = id; - let voice_id = id; + let opened = community.clone(); let voice_enabled = community.voice_enabled; - let pending_delete = self.chat.pending_community_delete == Some(id); + let pending_delete = self.armed(Armed::BuilderDeleteCommunity(id)); let expanded = self .chat + .admin .transfer .as_ref() .is_some_and(|transfer| transfer.community_id == id); @@ -394,11 +362,11 @@ impl Yumush { let row = list_row() .px(px(space::LG)) .child(community_icon( - palette, + t, community, px(size::AVATAR), text(text::CAPTION), - &self.chat.avatars, + &self.chat.session.avatars, )) .child( div() @@ -410,28 +378,25 @@ impl Yumush { div() .text_size(text(text::LABEL)) .font_weight(FontWeight::MEDIUM) - .text_color(palette.text) + .text_color(t.paper()) .truncate() .child(community.name.clone()), ) .child( div() .text_size(text(text::CAPTION)) - .text_color(palette.muted) + .text_color(t.dim()) .truncate() .child(meta), ), ) - .children( - (!voice_enabled) - .then(|| pill(w().builder_communities.voice_off, palette.muted, palette)), - ) + .children((!voice_enabled).then(|| pill(w().builder_communities.voice_off, t.dim()))) .child(icon_button( format!("open_community_{id}"), IconName::ArrowUpRight, w().builder_communities.open, - palette.muted, - palette, + t.dim(), + t, entity_action(entity, move |yumush, window, cx| { yumush.open_builder_community(opened.clone(), window, cx) }), @@ -440,10 +405,10 @@ impl Yumush { format!("log_community_{id}"), IconName::ScrollText, w().builder_communities.log, - palette.muted, - palette, + t.dim(), + t, entity_action(entity, move |yumush, window, cx| { - yumush.show_logs(log_id, window, cx) + yumush.show_logs(id, window, cx) }), )) .child(icon_button( @@ -458,47 +423,30 @@ impl Yumush { } else { w().builder_communities.voice_off }, - palette.muted, - palette, + t.dim(), + t, entity_action(entity, move |yumush, window, cx| { - yumush.set_builder_community_voice(voice_id, !voice_enabled, window, cx) + yumush.set_community_voice(id, !voice_enabled, window, cx) }), )) .child(icon_button( format!("transfer_community_{id}"), IconName::ArrowRightLeft, w().builder_communities.transfer, - if expanded { - palette.text - } else { - palette.muted - }, - palette, + if expanded { t.paper() } else { t.dim() }, + t, entity_action(entity, move |yumush, window, cx| { - yumush.open_transfer(transfer_id, window, cx) + yumush.open_transfer(id, window, cx) }), )) - .child( - icon_button( - format!("delete_community_{id}_{pending_delete}"), - IconName::Trash, - if pending_delete { - w().builder_communities.confirm_delete - } else { - w().builder_communities.delete - }, - if pending_delete { - palette.on_accent - } else { - palette.danger - }, - palette, - entity_action(entity, move |yumush, window, cx| { - yumush.delete_builder_community(delete_id, window, cx) - }), - ) - .when(pending_delete, |this| this.bg(palette.danger)), - ); + .child(delete_icon_button( + format!("delete_community_{id}"), + pending_delete, + t, + entity_action(entity, move |yumush, window, cx| { + yumush.delete_builder_community(id, window, cx) + }), + )); div() .flex() @@ -510,7 +458,7 @@ impl Yumush { .flex() .flex_col() .rounded(px(radius::MD)) - .children(self.transfer_rows(entity, palette)), + .children(self.transfer_rows(entity, t)), ) })) } diff --git a/crates/client/src/gui/builder/log.rs b/crates/client/src/gui/builder/log.rs index 95651d8..a335331 100644 --- a/crates/client/src/gui/builder/log.rs +++ b/crates/client/src/gui/builder/log.rs @@ -13,13 +13,16 @@ use jiff::Timestamp; use super::{ save_directory, - ui::{card, end_of_day_ms, fixed, list_row, pill, start_of_day_ms, toolbar}, + ui::{ + caption_text, card, end_of_day_ms, fixed, list_row, pill, rows_body, start_of_day_ms, + toolbar, + }, }; use crate::gui::{ - Palette, Yumush, + Yumush, community_settings::user_name, entity_action, millis_time, notify_error, - style::{size, space, text}, + style::{Tokens, size, space, text}, text, widget::{field, search_text}, }; @@ -113,7 +116,12 @@ fn action_detail(action: &AdminAction) -> Option { } fn csv_field(text: &str) -> String { - format!("\"{}\"", text.replace('"', "\"\"")) + let guarded = if text.starts_with(['=', '+', '-', '@', '\t', '\r']) { + format!("'{text}") + } else { + text.to_string() + }; + format!("\"{}\"", guarded.replace('"', "\"\"")) } fn builder_log_csv(entries: &[AdminLogEntry]) -> String { @@ -188,9 +196,9 @@ fn action_icon(action: &AdminAction) -> IconName { } } -fn builder_log_row(entry: &AdminLogEntry, palette: Palette) -> Div { +fn builder_log_row(entry: &AdminLogEntry, t: Tokens) -> Div { list_row() - .child(crate::gui::parts::small_icon(action_icon(&entry.action)).text_color(palette.muted)) + .child(crate::gui::parts::small_icon(action_icon(&entry.action)).text_color(t.dim())) .child( div() .flex_1() @@ -202,46 +210,41 @@ fn builder_log_row(entry: &AdminLogEntry, palette: Palette) -> Div { div() .truncate() .text_size(text(text::LABEL)) - .text_color(palette.text) + .text_color(t.paper()) .child(builder_log_text(entry)), ) - .child( - div() - .text_size(text(text::CAPTION)) - .text_color(palette.muted) - .child(millis_time(entry.created_at, crate::lang::w().common.stamp)), - ), + .child(caption_text( + millis_time(entry.created_at, crate::lang::w().common.stamp), + t.dim(), + )), ) .children( entry .community .as_deref() - .map(|community| pill(community, palette.accent, palette)), + .map(|community| pill(community, t.paper())), ) } impl Yumush { pub(super) fn load_builder_logs(&self, window: &mut Window, cx: &mut Context) { - if !self.is_builder() { - return; - } let (Some(actor_id), Some(target_id)) = ( - self.filter_user(&self.chat.builder_log_actor, cx), - self.filter_user(&self.chat.builder_log_target, cx), + self.filter_user(&self.chat.admin.builder_log_actor, cx), + self.filter_user(&self.chat.admin.builder_log_target, cx), ) else { window.push_notification(Notification::error(w().builder_log.unknown_user), cx); return; }; let action = self .chat + .admin .builder_log_action .read(cx) .selected_value() .copied() - .filter(|name| *name != "All") .and_then(AdminActionKind::parse); - let after_ms = start_of_day_ms(&search_text(&self.chat.builder_log_from, cx)); - let before_ms = end_of_day_ms(&search_text(&self.chat.builder_log_to, cx)); + let after_ms = start_of_day_ms(&search_text(&self.chat.admin.builder_log_from, cx)); + let before_ms = end_of_day_ms(&search_text(&self.chat.admin.builder_log_to, cx)); self.fetch_builder( window, cx, @@ -257,7 +260,7 @@ impl Yumush { .await }, |yumush, entries, cx| { - yumush.chat.builder_logs = entries; + yumush.chat.admin.builder_logs = entries; cx.notify(); }, ); @@ -269,7 +272,7 @@ impl Yumush { millis_time(now_ms(), "%Y%m%d-%H%M%S") ); let target = cx.prompt_for_new_path(&save_directory(), Some(&name)); - let csv = builder_log_csv(&self.chat.builder_logs); + let csv = builder_log_csv(&self.chat.admin.builder_logs); cx.spawn_in(window, async move |this, cx| { let target = match target.await { @@ -287,24 +290,25 @@ impl Yumush { .detach(); } - pub(super) fn log_body(&self, entity: &Entity, palette: Palette) -> Vec { + pub(super) fn log_body(&self, entity: &Entity, t: Tokens) -> Vec { let filters = toolbar(vec![ - fixed(size::THUMB, field(palette, &self.chat.builder_log_actor)), - fixed(size::THUMB, field(palette, &self.chat.builder_log_target)), + fixed(size::THUMB, field(t, &self.chat.admin.builder_log_actor)), + fixed(size::THUMB, field(t, &self.chat.admin.builder_log_target)), fixed( size::THUMB, crate::gui::widget::underline( - palette, - Select::new(&self.chat.builder_log_action).appearance(false), + t, + size::CONTROL, + Select::new(&self.chat.admin.builder_log_action).appearance(false), ), ), - fixed(size::THUMB, field(palette, &self.chat.builder_log_from)), - fixed(size::THUMB, field(palette, &self.chat.builder_log_to)), + fixed(size::THUMB, field(t, &self.chat.admin.builder_log_from)), + fixed(size::THUMB, field(t, &self.chat.admin.builder_log_to)), crate::gui::parts::button( "apply_builder_log", w().builder_log.apply, crate::gui::parts::Press::Plain, - palette.tokens, + t, entity_action(entity, |yumush, window, cx| { yumush.load_builder_logs(window, cx) }), @@ -313,20 +317,15 @@ impl Yumush { ]); let rows: Vec
= self .chat + .admin .builder_logs .iter() - .map(|entry| builder_log_row(entry, palette)) + .map(|entry| builder_log_row(entry, t)) .collect(); - let body = if rows.is_empty() { - crate::gui::parts::empty(w().builder_log.no_entries, palette.tokens) - } else { - div().flex().flex_col().children(rows) - }; - vec![ - card(palette) + card() .child(div().pb(px(space::SM)).child(filters)) - .child(body) + .child(rows_body(rows, w().builder_log.no_entries, t)) .into_any_element(), ] } diff --git a/crates/client/src/gui/builder/messages.rs b/crates/client/src/gui/builder/messages.rs index 29dbd02..2399c30 100644 --- a/crates/client/src/gui/builder/messages.rs +++ b/crates/client/src/gui/builder/messages.rs @@ -13,12 +13,13 @@ use gpui_kit::{ px, }; -use super::ui::{card, confirmed, delete_icon_button, end_of_day_ms, icon_button, start_of_day_ms}; -use crate::gui::style::{size, space, stroke, text}; +use super::ui::{card, delete_icon_button, end_of_day_ms, icon_button, start_of_day_ms}; +use crate::gui::chat::Armed; +use crate::gui::style::{Tokens, size, space, stroke, text}; use crate::gui::{ - Palette, Yumush, + Yumush, community_settings::user_name, - entity_action, millis_time, notify_error, + entity_action, glyph, millis_time, notify_error, profile::user_link, text, widget::{field, search_text}, @@ -30,7 +31,7 @@ fn message_hit_row( pending: bool, purge_pending: bool, entity: &Entity, - palette: Palette, + t: Tokens, ) -> Div { let message_id = hit.message.id; let community_id = hit.message.community_id; @@ -38,15 +39,13 @@ fn message_hit_row( let hue = hit .author .as_ref() - .map_or(palette.tokens.faint(), |author| { - palette.tokens.person(author.id) - }); + .map_or(t.faint(), |author| t.person(author.id)); let open = icon_button( format!("open_message_{}", hit.message.id), IconName::MessageSquare, w().builder_messages.open_chat, - palette.muted, - palette, + t.dim(), + t, entity_action(entity, move |yumush, window, cx| { yumush.jump_to(community_id, false, window, cx) }), @@ -54,7 +53,7 @@ fn message_hit_row( let delete = delete_icon_button( format!("delete_message_{}", hit.message.id), pending, - palette, + t, entity_action(entity, move |yumush, window, cx| { yumush.delete_builder_message(message_id, window, cx) }), @@ -69,14 +68,14 @@ fn message_hit_row( } else { w().builder_messages.purge_user }, - palette.danger, - palette, + t.bad(), + t, entity_action(entity, move |yumush, window, cx| { yumush.purge_builder_user(user_id, window, cx) }), ) .when(purge_pending, |this| { - this.bg(palette.danger).text_color(palette.on_accent) + this.bg(t.bad()).text_color(t.ground()) }) }); @@ -98,7 +97,7 @@ fn message_hit_row( .py(px(space::SM)) .pl(px(space::XL + space::LG)) .pr(px(space::LG)) - .hover(|style| style.bg(palette.hover)) + .hover(|style| style.bg(t.hov())) .child(dot) .child( div() @@ -128,7 +127,7 @@ fn message_hit_row( div() .flex_shrink_0() .text_size(text(text::CAPTION)) - .text_color(palette.muted) + .text_color(t.dim()) .child(millis_time( hit.message.created_at, crate::lang::w().common.year_stamp, @@ -139,21 +138,21 @@ fn message_hit_row( .min_w_0() .truncate() .text_size(text(text::CAPTION)) - .text_color(palette.tokens.faint()) + .text_color(t.faint()) .child(hit.community.clone()), ), ) .child(match hit.message.call { Some(call) => { - crate::gui::chat::call_line(call, user_name(&hit.author), false, palette) + crate::gui::chat::call_line(call, user_name(&hit.author), false, t) } None => div() .text_size(text(text::BODY)) - .text_color(palette.body) + .text_color(t.paper()) .line_clamp(2) - .child(super::super::glyph::wrapped( + .child(glyph::wrapped( hit.message.body.clone().into(), - super::super::text(super::super::style::text::BODY), + text(text::BODY), )), }), ) @@ -173,7 +172,7 @@ fn message_hit_row( } impl Yumush { - pub(super) fn messages_body(&self, entity: &Entity, palette: Palette) -> Vec { + pub(super) fn messages_body(&self, entity: &Entity, t: Tokens) -> Vec { let filters = div() .px(px(space::LG)) .py(px(space::MD)) @@ -185,7 +184,7 @@ impl Yumush { div() .flex_1() .min_w_0() - .child(field(palette, &self.chat.builder_message_text)), + .child(field(t, &self.chat.admin.builder_message_text)), ), ) .child( @@ -196,23 +195,18 @@ impl Yumush { .gap(px(space::SM)) .children( [ - &self.chat.builder_message_user, - &self.chat.builder_message_community, - &self.chat.builder_message_from, - &self.chat.builder_message_to, + &self.chat.admin.builder_message_user, + &self.chat.admin.builder_message_community, + &self.chat.admin.builder_message_from, + &self.chat.admin.builder_message_to, ] - .map(|input| { - div() - .flex_1() - .min_w(px(size::THUMB)) - .child(field(palette, input)) - }), + .map(|input| div().flex_1().min_w(px(size::THUMB)).child(field(t, input))), ) .child(crate::gui::parts::button( "search_messages", w().builder_messages.search, crate::gui::parts::Press::Plain, - palette.tokens, + t, entity_action(entity, |yumush, window, cx| { yumush.search_messages(window, cx) }), @@ -220,19 +214,20 @@ impl Yumush { ); let rows: Vec
= self .chat + .admin .builder_messages .iter() .map(|hit| { - let pending = self.chat.pending_message_delete == Some(hit.message.id); + let pending = self.armed(Armed::DeleteMessage(hit.message.id)); let purge_pending = hit .author .as_ref() - .is_some_and(|author| self.chat.pending_builder_purge == Some(author.id)); - message_hit_row(hit, pending, purge_pending, entity, palette) + .is_some_and(|author| self.armed(Armed::PurgeUser(author.id))); + message_hit_row(hit, pending, purge_pending, entity, t) }) .collect(); let list = if rows.is_empty() { - crate::gui::parts::empty(w().builder_messages.no_messages, palette.tokens) + crate::gui::parts::empty(w().builder_messages.no_messages, t) } else { div() .relative() @@ -245,24 +240,25 @@ impl Yumush { .top_0() .bottom_0() .w(px(stroke::LINE)) - .bg(palette.tokens.thread()), + .bg(t.thread()), ) .children(rows) }; vec![ - card(palette).child(filters).into_any_element(), - card(palette).child(list).into_any_element(), + card().child(filters).into_any_element(), + card().child(list).into_any_element(), ] } pub(super) fn search_messages(&mut self, window: &mut Window, cx: &mut Context) { - let text = search_text(&self.chat.builder_message_text, cx); - let Some(user_id) = self.filter_user(&self.chat.builder_message_user, cx) else { + let text = search_text(&self.chat.admin.builder_message_text, cx); + let Some(user_id) = self.filter_user(&self.chat.admin.builder_message_user, cx) else { window.push_notification(Notification::error(w().builder_messages.unknown_user), cx); return; }; - let Some(community_id) = self.filter_community(&self.chat.builder_message_community, cx) + let Some(community_id) = + self.filter_community(&self.chat.admin.builder_message_community, cx) else { window.push_notification( Notification::error(w().builder_messages.unknown_community), @@ -270,8 +266,8 @@ impl Yumush { ); return; }; - let after_ms = start_of_day_ms(&search_text(&self.chat.builder_message_from, cx)); - let before_ms = end_of_day_ms(&search_text(&self.chat.builder_message_to, cx)); + let after_ms = start_of_day_ms(&search_text(&self.chat.admin.builder_message_from, cx)); + let before_ms = end_of_day_ms(&search_text(&self.chat.admin.builder_message_to, cx)); let text = (!text.is_empty()).then_some(text); let network = self.network.clone(); @@ -294,7 +290,7 @@ impl Yumush { }; let _ = this.update(cx, |yumush, cx| { - yumush.chat.builder_messages = hits; + yumush.chat.admin.builder_messages = hits; cx.notify(); }); }) @@ -307,8 +303,7 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) { - if !confirmed(&mut self.chat.pending_message_delete, message_id) { - cx.notify(); + if !self.arm(Armed::DeleteMessage(message_id), cx) { return; } let network = self.network.clone(); @@ -319,6 +314,7 @@ impl Yumush { let _ = this.update(cx, |yumush, cx| { yumush .chat + .admin .builder_messages .retain(|hit| hit.message.id != message_id); cx.notify(); diff --git a/crates/client/src/gui/builder/overview.rs b/crates/client/src/gui/builder/overview.rs index 41c24ca..64cbbac 100644 --- a/crates/client/src/gui/builder/overview.rs +++ b/crates/client/src/gui/builder/overview.rs @@ -8,14 +8,14 @@ use gpui_kit::{Context, Div, IntoElement, ParentElement, Styled, Window, div, px use jiff::Timestamp; use std::time::Duration; -use super::ui::{card, card_header, stat_tile}; +use super::ui::{caption_text, card, card_header, stat_tile}; use crate::gui::{ - Palette, Yumush, + Yumush, builder::BuilderTab, chat::View, storage, - style::{radius, size, space, text}, - text, voice_stats, + style::{Tokens, radius, size, space}, + voice_stats, }; use crate::lang::w; @@ -35,15 +35,12 @@ fn day_label(day: u64) -> String { .unwrap_or_default() } -fn tile_row(tiles: &[(&str, String)], palette: Palette) -> Div { - div() - .flex() - .gap(px(space::MD)) - .children(tiles.iter().map(|(label, value)| { - stat_tile(label, value, palette) - .flex_1() - .min_w(px(size::SIDEBAR)) - })) +fn tile_row(tiles: &[(&str, String)], t: Tokens) -> Div { + div().flex().gap(px(space::MD)).children( + tiles + .iter() + .map(|(label, value)| stat_tile(label, value, t).flex_1().min_w(px(size::SIDEBAR))), + ) } fn bar_chart( @@ -51,7 +48,7 @@ fn bar_chart( stats: &[DayStat], value: fn(&DayStat) -> u64, summary: u64, - palette: Palette, + t: Tokens, ) -> Div { let values: Vec = stats.iter().map(value).collect(); let maximum = values.iter().copied().max().unwrap_or_default(); @@ -64,19 +61,13 @@ fn bar_chart( .map(|stat| day_label(stat.day)) .unwrap_or_default(); - card(palette) + card() .flex_1() .min_w_0() .child(card_header( title, - vec![ - div() - .text_size(text(text::CAPTION)) - .text_color(palette.muted) - .child(summary.to_string()) - .into_any_element(), - ], - palette, + vec![caption_text(summary.to_string(), t.dim()).into_any_element()], + t, )) .child( div() @@ -85,12 +76,7 @@ fn bar_chart( .flex() .flex_col() .gap(px(space::XS)) - .child( - div() - .text_size(text(text::CAPTION)) - .text_color(palette.muted) - .child(maximum.to_string()), - ) + .child(caption_text(maximum.to_string(), t.dim())) .child( div() .h(px(CHART_HEIGHT)) @@ -99,11 +85,11 @@ fn bar_chart( .gap(px(space::XXS)) .children(values.iter().map(|&value| { let (height, color) = if value == 0 { - (space::XXS, palette.hover) + (space::XXS, t.hov()) } else { ( (CHART_HEIGHT * value as f32 / maximum as f32).max(space::XXS), - palette.accent, + t.paper(), ) }; @@ -118,38 +104,36 @@ fn bar_chart( div() .pt(px(space::XS)) .border_t_1() - .border_color(palette.border) + .border_color(t.thread()) .flex() .justify_between() - .text_size(text(text::CAPTION)) - .text_color(palette.muted) - .child(first) - .child(last), + .child(caption_text(first, t.dim())) + .child(caption_text(last, t.dim())), ), ) } impl Yumush { fn watch_server_stats(&mut self, cx: &mut Context) { - if self.chat.server_stats_task.is_some() { + if self.chat.admin.server_stats_task.is_some() { return; } let network = self.network.clone(); - self.chat.server_stats_task = Some(cx.spawn(async move |this, cx| { + self.chat.admin.server_stats_task = Some(cx.spawn(async move |this, cx| { loop { let open = this .update(cx, |yumush, _| { - yumush.chat.view == View::Builder - && yumush.chat.builder_tab == BuilderTab::Overview + yumush.chat.session.view == View::Builder + && yumush.chat.admin.builder_tab == BuilderTab::Overview }) .unwrap_or(false); if !open { - let _ = this.update(cx, |yumush, _| yumush.chat.server_stats_task = None); + let _ = this.update(cx, |yumush, _| yumush.chat.admin.server_stats_task = None); break; } if let Ok(stats) = network.call(GetServerStats).await { let _ = this.update(cx, |yumush, cx| { - yumush.chat.server_stats = Some(stats); + yumush.chat.admin.server_stats = Some(stats); cx.notify(); }); } @@ -170,18 +154,18 @@ impl Yumush { )) }, |yumush, (overview, stats), cx| { - yumush.chat.builder_overview = Some(overview); - yumush.chat.builder_stats = stats; + yumush.chat.admin.builder_overview = Some(overview); + yumush.chat.admin.builder_stats = stats; cx.notify(); }, ); } - pub(super) fn overview_rows(&self, palette: Palette) -> Vec
{ - let Some(overview) = &self.chat.builder_overview else { + pub(super) fn overview_rows(&self, t: Tokens) -> Vec
{ + let Some(overview) = &self.chat.admin.builder_overview else { return Vec::new(); }; - let stats = &self.chat.builder_stats; + let stats = &self.chat.admin.builder_stats; let active = stats.last().map_or(0, |stat| stat.active_users); let messages = stats.iter().map(|stat| stat.messages).sum::(); @@ -200,10 +184,7 @@ impl Yumush { ), ]; - let mut rows: Vec
= tiles - .chunks(3) - .map(|chunk| tile_row(chunk, palette)) - .collect(); + let mut rows: Vec
= tiles.chunks(3).map(|chunk| tile_row(chunk, t)).collect(); rows.push( div() .flex() @@ -213,29 +194,25 @@ impl Yumush { stats, |stat| stat.active_users, active, - palette, + t, )) .child(bar_chart( w().common.messages, stats, |stat| stat.messages, messages, - palette, + t, )), ); - if let Some(stats) = &self.chat.server_stats { + if let Some(stats) = &self.chat.admin.server_stats { rows.push( - card(palette) - .child(card_header( - w().builder_overview.server, - Vec::new(), - palette, - )) + card() + .child(card_header(w().builder_overview.server, Vec::new(), t)) .child(div().pt(px(space::SM)).child(voice_stats::stats_panel( stats, &|id| self.chat.name_of(id), voice_stats::Detail::Full, - palette, + t, ))), ); } diff --git a/crates/client/src/gui/builder/releases.rs b/crates/client/src/gui/builder/releases.rs index b30ddb6..6e46cc0 100644 --- a/crates/client/src/gui/builder/releases.rs +++ b/crates/client/src/gui/builder/releases.rs @@ -1,23 +1,26 @@ use common::{ call::{ImportRelease, ListReleases, PublishRelease, SetReleaseRequired}, error::ReleaseProblem, - model::{ReleaseInfo, Staged}, + model::{BackupInfo, ReleaseInfo, Staged}, update::{Sha, Side}, }; use gpui_kit::{ - AnyElement, Context, Div, Entity, Hsla, IntoElement, ParentElement, PathPromptOptions, Styled, + AnyElement, Context, Div, Entity, IntoElement, ParentElement, PathPromptOptions, Styled, Window, component::{WindowExt as _, notification::Notification}, div, px, uniform_list, }; use std::path::PathBuf; -use super::ui::{card, card_header, confirmed, delete_icon_button, list_row, rows_body}; +use super::{ + reports::Punish, + ui::{caption_text, card, card_header, delete_icon_button, list_row, rows_body}, +}; use crate::gui::{ - Palette, Yumush, entity_action, millis_time, notify_error, + Yumush, entity_action, millis_time, notify_error, parts::{self, Fill, Press}, storage, - style::{size, space, text}, + style::{Tokens, size, space, text}, text, widget::field, }; @@ -31,9 +34,13 @@ pub(crate) struct Desk { next: u64, required: bool, publishing: bool, + pub(super) tagging: bool, releases: Vec, - pending_required: Option, - importing: Option, + pub(super) pending_required: Option, + pub(super) importing: Option, + pub(super) backups: Vec, + pub(super) pending_backup: Option, + pub(super) punish: Option, pub(super) live: super::ci_view::Live, } @@ -88,30 +95,17 @@ impl Desk { fn draft(&mut self, id: u64) -> Option<&mut Draft> { self.drafts.iter_mut().find(|draft| draft.id == id) } -} - -pub(super) fn caption_text(value: impl Into, color: Hsla) -> Div { - div() - .text_size(text(text::CAPTION)) - .text_color(color) - .child(value.into()) -} -pub(super) fn meter(share: f32, label: String, palette: Palette) -> Div { - div() - .w(px(METER)) - .flex() - .items_center() - .gap(px(space::SM)) - .child(parts::track(Fill::Part(share), false, palette.tokens)) - .child(caption_text(label, palette.muted)) + pub(in crate::gui) fn connected(&mut self) { + self.importing = None; + } } -fn draft_row(draft: &Draft, duplicate: bool, entity: &Entity, palette: Palette) -> Div { +fn draft_row(draft: &Draft, duplicate: bool, entity: &Entity, t: Tokens) -> Div { let id = draft.id; let status = match &draft.stage { Stage::Uploading(sent) if *sent >= draft.size => { - caption_text(w().builder_release.compressing, palette.muted) + caption_text(w().builder_release.compressing, t.dim()) } Stage::Uploading(sent) => { let share = *sent as f32 / draft.size.max(1) as f32; @@ -119,10 +113,10 @@ fn draft_row(draft: &Draft, duplicate: bool, entity: &Entity, palette: P .flex() .items_center() .gap(px(space::SM)) - .child(parts::track(Fill::Part(share), false, palette.tokens)) - .child(caption_text(format!("{:.0}%", share * 100.), palette.muted)) + .child(parts::track(Fill::Part(share), false, t)) + .child(caption_text(format!("{:.0}%", share * 100.), t.dim())) } - Stage::Ready(_) if duplicate => caption_text(w().builder_release.duplicate, palette.danger), + Stage::Ready(_) if duplicate => caption_text(w().builder_release.duplicate, t.bad()), Stage::Ready(staged) => caption_text( format!( "{} · {} → {}", @@ -130,9 +124,9 @@ fn draft_row(draft: &Draft, duplicate: bool, entity: &Entity, palette: P storage(staged.size), storage(staged.packed) ), - palette.muted, + t.dim(), ), - Stage::Failed(error) => caption_text(error.clone(), palette.danger), + Stage::Failed(error) => caption_text(error.clone(), t.bad()), }; list_row() @@ -146,7 +140,7 @@ fn draft_row(draft: &Draft, duplicate: bool, entity: &Entity, palette: P div() .truncate() .text_size(text(text::LABEL)) - .text_color(palette.text) + .text_color(t.paper()) .child(draft.name.clone()), ) .child(status), @@ -154,17 +148,12 @@ fn draft_row(draft: &Draft, duplicate: bool, entity: &Entity, palette: P .child(delete_icon_button( format!("remove_draft_{id}"), false, - palette, + t, entity_action(entity, move |yumush, _, cx| yumush.remove_draft(id, cx)), )) } -fn release_row( - release: &ReleaseInfo, - pending: bool, - entity: &Entity, - palette: Palette, -) -> Div { +fn release_row(release: &ReleaseInfo, pending: bool, entity: &Entity, t: Tokens) -> Div { let seq = release.seq; let required = release.required; let targets = release @@ -178,7 +167,7 @@ fn release_row( format!("confirm_release_{seq}"), w().builder_release.confirm, Press::Danger, - palette.tokens, + t, entity_action(entity, move |yumush, window, cx| { yumush.set_release_required(seq, true, window, cx) }), @@ -189,7 +178,7 @@ fn release_row( format!("release_required_{seq}"), w().builder_release.required, required, - palette.tokens, + t, entity_action(entity, move |yumush, window, cx| { yumush.toggle_release_required(seq, !required, window, cx) }), @@ -203,43 +192,35 @@ fn release_row( div() .w(px(size::CONTROL * 1.5)) .text_size(text(text::LABEL)) - .text_color(palette.text) + .text_color(t.paper()) .child(format!("#{seq}")), ) .child(caption_text( millis_time(release.created_ms, w().common.date), - palette.muted, + t.dim(), )) - .child( - caption_text(targets, palette.muted) - .flex_1() - .min_w_0() - .truncate(), - ) + .child(caption_text(targets, t.dim()).flex_1().min_w_0().truncate()) .child(control) } impl Yumush { - pub(super) fn releases_body(&self, entity: &Entity, palette: Palette) -> Vec { - let mut body = vec![self.import_card(entity, palette).into_any_element()]; - body.extend( - self.ci_card(entity, palette) - .map(IntoElement::into_any_element), - ); + pub(super) fn releases_body(&self, entity: &Entity, t: Tokens) -> Vec { + let mut body = vec![self.import_card(entity, t).into_any_element()]; + body.extend(self.ci_card(entity, t).map(IntoElement::into_any_element)); if !self.desk.drafts.is_empty() { - body.push(self.draft_card(entity, palette).into_any_element()); + body.push(self.draft_card(entity, t).into_any_element()); } - body.push(self.releases_card(entity, palette).into_any_element()); + body.push(self.releases_card(entity, t).into_any_element()); body } - fn import_card(&self, entity: &Entity, palette: Palette) -> Div { + fn import_card(&self, entity: &Entity, t: Tokens) -> Div { let w = &w().builder_release; let import = parts::button( "import_release", w.import, Press::Plain, - palette.tokens, + t, entity_action(entity, |yumush, window, cx| { let tag = yumush.release_tag_text(cx); yumush.import_tag(tag, window, cx) @@ -249,38 +230,38 @@ impl Yumush { "build_release", w.build, Press::Primary, - palette.tokens, + t, entity_action(entity, |yumush, window, cx| yumush.create_tag(window, cx)), ); let status = self .desk .importing .as_ref() - .map(|tag| caption_text(format!("{} {tag}", w.importing), palette.muted)); - card(palette).child( + .map(|tag| caption_text(format!("{} {tag}", w.importing), t.dim())); + card().child( list_row() - .child(field(palette, &self.release_tag).w(px(METER))) + .child(field(t, &self.release_tag).w(px(METER))) .children(status) .child(div().flex_1()) .child(if self.desk.importing.is_none() { import } else { - import.opacity(0.4) + import.opacity(parts::DISABLED) }) - .child(if self.desk.live.tagging() { - build.opacity(0.4) + .child(if self.desk.tagging { + build.opacity(parts::DISABLED) } else { build }), ) } - fn required_toggle(&self, entity: &Entity, palette: Palette) -> impl IntoElement { + fn required_toggle(&self, entity: &Entity, t: Tokens) -> impl IntoElement { parts::labeled_toggle( "release_required", w().builder_release.required, self.desk.required, - palette.tokens, + t, entity_action(entity, |yumush, window, cx| { yumush.desk.required = !yumush.desk.required; window.refresh(); @@ -289,13 +270,13 @@ impl Yumush { ) } - fn draft_card(&self, entity: &Entity, palette: Palette) -> Div { + fn draft_card(&self, entity: &Entity, t: Tokens) -> Div { let w = &w().builder_release; let drafts = &self.desk.drafts; let rows: Vec
= drafts .iter() .enumerate() - .map(|(index, draft)| draft_row(draft, is_duplicate(drafts, index), entity, palette)) + .map(|(index, draft)| draft_row(draft, is_duplicate(drafts, index), entity, t)) .collect(); let publish = [ ("publish_server", w.server, Side::Server), @@ -307,7 +288,7 @@ impl Yumush { id, label, Press::Primary, - palette.tokens, + t, entity_action(entity, move |yumush, window, cx| { yumush.publish_release(side, window, cx) }), @@ -315,44 +296,44 @@ impl Yumush { if self.desk.picked(side).is_some() { button } else { - button.opacity(0.4) + button.opacity(parts::DISABLED) } }); let discard = parts::button( "discard_release", w.discard, Press::Plain, - palette.tokens, + t, entity_action(entity, |yumush, _, cx| { yumush.desk.drafts.clear(); yumush.desk.required = false; cx.notify(); }), ); - card(palette) + card() .child(card_header( &format!("#{} · {}", self.desk.next_seq(), w.ready), Vec::new(), - palette, + t, )) .child(div().flex().flex_col().children(rows)) .child( list_row() - .child(self.required_toggle(entity, palette)) + .child(self.required_toggle(entity, t)) .child(div().flex_1()) .child(discard) .children(publish), ) } - fn releases_card(&self, entity: &Entity, palette: Palette) -> Div { + fn releases_card(&self, entity: &Entity, t: Tokens) -> Div { let count = self.desk.releases.len(); - let header = card_header(w().builder_release.published, Vec::new(), palette); + let header = card_header(w().builder_release.published, Vec::new(), t); if count == 0 { - return card(palette).child(header).child(rows_body( + return card().child(header).child(rows_body( Vec::new(), w().builder_release.no_releases, - palette, + t, )); } let list = { @@ -360,17 +341,15 @@ impl Yumush { uniform_list("published_releases", count, move |range, _, cx| { let yumush = entity.read(cx); let pending = yumush.desk.pending_required; - let palette = crate::gui::palette(cx); + let t = Tokens::of(cx); yumush.desk.releases[range] .iter() - .map(|release| { - release_row(release, pending == Some(release.seq), &entity, palette) - }) + .map(|release| release_row(release, pending == Some(release.seq), &entity, t)) .collect() }) .h(px((count as f32 * size::ROW).min(size::PAGE))) }; - card(palette).child(header).child(list) + card().child(header).child(list) } pub(super) fn load_releases(&mut self, window: &mut Window, cx: &mut Context) { @@ -492,10 +471,14 @@ impl Yumush { pub(in crate::gui) fn release_imported( &mut self, + tag: &str, result: Result, ReleaseProblem>, window: &mut Window, cx: &mut Context, ) { + if self.desk.importing.as_deref() != Some(tag) { + return; + } self.desk.importing = None; match result { Ok(staged) if staged.is_empty() => { @@ -541,6 +524,7 @@ impl Yumush { yumush.desk.required = false; yumush.desk.publishing = false; yumush.load_releases(window, cx); + cx.notify(); }); } Err(error) => { @@ -562,11 +546,12 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) { - if required && !confirmed(&mut self.desk.pending_required, seq) { + if required { + self.desk.pending_required = Some(seq); cx.notify(); - return; + } else { + self.set_release_required(seq, false, window, cx); } - self.set_release_required(seq, required, window, cx); } fn set_release_required( diff --git a/crates/client/src/gui/builder/reports.rs b/crates/client/src/gui/builder/reports.rs index 0ffbc92..88c1c7e 100644 --- a/crates/client/src/gui/builder/reports.rs +++ b/crates/client/src/gui/builder/reports.rs @@ -4,23 +4,23 @@ use std::future::Future; use common::{ call::{BanUser, DeleteMessage, HandleReport, ListReports, TimeoutUser}, - model::{BanScope, Report, ReportStatus}, + model::{BanScope, Hue, Report, ReportStatus}, }; use gpui_kit::{ AnyElement, Context, Div, Entity, FontWeight, Hsla, IntoElement, ParentElement, Styled, Window, div, px, }; -use super::ui::{list_card, pill}; +use super::ui::{caption_text, confirmed, list_card, pill}; use crate::{ gui::{ - Palette, Yumush, avatar, badge, clickable, + Yumush, avatar, badge, clickable, community_settings::user_name, - entity_action, millis_time, notify_error, + entity_action, glyph, millis_time, notify_error, parts::{self, Press}, profile::user_link, settings_page::{segment, segment_track}, - style::{radius, size, space, text}, + style::{Tokens, radius, size, space, text}, text as text_fn, }, net::{Fail, NetworkHandle}, @@ -33,11 +33,17 @@ const REPORT_FILTERS: [Option; 4] = [ None, ]; -fn status_color(status: ReportStatus, palette: Palette) -> Hsla { +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) enum Punish { + Timeout(Id), + Ban(Id), +} + +fn status_color(status: ReportStatus, t: Tokens) -> Hsla { match status { - ReportStatus::Open => palette.accent, - ReportStatus::Resolved => palette.ok, - ReportStatus::Dismissed => palette.muted, + ReportStatus::Open => t.paper(), + ReportStatus::Resolved => t.hue(Hue::Mint), + ReportStatus::Dismissed => t.dim(), } } @@ -55,42 +61,42 @@ impl Yumush { .map(|reports| reports.len()) }, |yumush, count, cx| { - yumush.chat.open_reports = count; + yumush.chat.admin.open_reports = count; cx.notify(); }, ); } pub(super) fn load_reports(&self, window: &mut Window, cx: &mut Context) { - let status = self.chat.report_filter; + let status = self.chat.admin.report_filter; self.fetch_builder( window, cx, move |network| async move { network.call(ListReports { status }).await }, |yumush, reports, cx| { - yumush.chat.builder_reports = reports; + yumush.chat.admin.builder_reports = reports; cx.notify(); }, ); } - pub(super) fn refresh_reports(&self, window: &mut Window, cx: &mut Context) { + fn refresh_reports(&self, window: &mut Window, cx: &mut Context) { self.load_reports(window, cx); self.load_open_reports(window, cx); } - pub(super) fn select_report_filter( + fn select_report_filter( &mut self, status: Option, window: &mut Window, cx: &mut Context, ) { - self.chat.report_filter = status; + self.chat.admin.report_filter = status; self.load_reports(window, cx); cx.notify(); } - pub(super) fn report_action( + fn report_action( &mut self, window: &mut Window, cx: &mut Context, @@ -109,7 +115,7 @@ impl Yumush { .detach(); } - pub(super) fn handle_report( + fn handle_report( &mut self, report_id: Id, status: ReportStatus, @@ -121,7 +127,7 @@ impl Yumush { }); } - pub(super) fn delete_report_message( + fn delete_report_message( &mut self, message_id: Id, window: &mut Window, @@ -132,93 +138,89 @@ impl Yumush { }); } - pub(super) fn timeout_report_target( + fn punish_report( &mut self, - user_id: Id, - window: &mut Window, - cx: &mut Context, - ) { - self.report_action(window, cx, move |network| async move { - network - .call(TimeoutUser { - user_id, - minutes: 60, - }) - .await - }); - } - - pub(super) fn ban_report_target( - &mut self, - user_id: Id, + punish: Punish, reason: &str, window: &mut Window, cx: &mut Context, ) { - let reason = reason.to_string(); - self.report_action(window, cx, move |network| async move { - network - .call(BanUser { - user_id, - reason: Some(reason), - scope: BanScope::Account, - }) - .await - }); + if !confirmed(&mut self.desk.punish, punish) { + cx.notify(); + return; + } + match punish { + Punish::Timeout(user_id) => self.report_action(window, cx, move |network| async move { + network + .call(TimeoutUser { + user_id, + minutes: 60, + }) + .await + }), + Punish::Ban(user_id) => { + let reason = reason.to_string(); + self.report_action(window, cx, move |network| async move { + network + .call(BanUser { + user_id, + reason: Some(reason), + scope: BanScope::Account, + }) + .await + }); + } + } } - pub(super) fn report_filters(&self, entity: &Entity, palette: Palette) -> Div { - div().flex().child( - segment_track(palette).children(REPORT_FILTERS.map(|status| { + fn report_filters(&self, entity: &Entity, t: Tokens) -> Div { + div() + .flex() + .child(segment_track(t).children(REPORT_FILTERS.map(|status| { let label = status.map_or(w().builder_reports.all, ReportStatus::label); segment( clickable( label, - palette, + t, entity_action(entity, move |yumush, window, cx| { yumush.select_report_filter(status, window, cx) }), ), - self.chat.report_filter == status, - palette, + self.chat.admin.report_filter == status, + t, ) .px(px(space::MD)) .child(label) - })), - ) + }))) } - pub(super) fn reports_body(&self, entity: &Entity, palette: Palette) -> Vec { + pub(super) fn reports_body(&self, entity: &Entity, t: Tokens) -> Vec { let rows: Vec
= self .chat + .admin .builder_reports .iter() - .map(|report| self.report_row(report, entity, palette)) + .map(|report| self.report_row(report, entity, t)) .collect(); vec![ - self.report_filters(entity, palette).into_any_element(), - list_card(None, rows, w().builder_reports.no_reports, palette).into_any_element(), + self.report_filters(entity, t).into_any_element(), + list_card(None, rows, w().builder_reports.no_reports, t).into_any_element(), ] } - pub(super) fn report_row( - &self, - report: &Report, - entity: &Entity, - palette: Palette, - ) -> Div { + fn report_row(&self, report: &Report, entity: &Entity, t: Tokens) -> Div { let target_avatar = match &report.target { Some(user) => avatar( - palette, + t, user, px(size::AVATAR), text_fn(text::CAPTION), - &self.chat.avatars, + &self.chat.session.avatars, ) .into_any_element(), None => badge( - palette, + t, report.id, w().builder_reports.someone, px(size::AVATAR), @@ -248,42 +250,36 @@ impl Yumush { .child(user_name(&report.target).to_string()), ), )) - .child(pill( - report.status.label(), - status_color(report.status, palette), - palette, - )) + .child(pill(report.status.label(), status_color(report.status, t))) .child(user_link( format!("report_reporter_{}", report.id), report.reporter.as_ref(), entity, div() .text_size(text_fn(text::CAPTION)) - .text_color(palette.muted) + .text_color(t.dim()) .truncate() .child(w().builder_reports.reported_by(user_name(&report.reporter))), )); - let meta = div() - .flex_shrink_0() - .text_size(text_fn(text::CAPTION)) - .text_color(palette.muted) - .child(format!( + let meta = caption_text( + format!( "{} · {}", report .community .as_deref() .unwrap_or(w().builder_reports.deleted_community), millis_time(report.created_at, crate::lang::w().common.stamp) - )); - let actions = self.report_actions(report, entity, palette); + ), + t.dim(), + ) + .flex_shrink_0(); + let actions = self.report_actions(report, entity, t); let handled = (report.status != ReportStatus::Open).then(|| { - div() - .text_size(text_fn(text::CAPTION)) - .text_color(palette.muted) - .child( - w().builder_reports - .handled_by(user_name(&report.handled_by)), - ) + caption_text( + w().builder_reports + .handled_by(user_name(&report.handled_by)), + t.dim(), + ) }); div() @@ -303,10 +299,10 @@ impl Yumush { .child( div() .text_size(text_fn(text::LABEL)) - .text_color(palette.body) - .child(super::super::glyph::wrapped( + .text_color(t.paper()) + .child(glyph::wrapped( report.reason.clone().into(), - super::super::text(super::super::style::text::LABEL), + text_fn(text::LABEL), )), ) .children(report.body.as_ref().map(|body| { @@ -314,14 +310,11 @@ impl Yumush { .px(px(space::SM)) .py(px(space::SM)) .rounded(px(radius::MD)) - .bg(palette.window) + .bg(t.ground()) .text_size(text_fn(text::CAPTION)) - .text_color(palette.muted) + .text_color(t.dim()) .line_clamp(2) - .child(super::super::glyph::wrapped( - body.clone().into(), - super::super::text(super::super::style::text::CAPTION), - )) + .child(glyph::wrapped(body.clone().into(), text_fn(text::CAPTION))) })) .children(handled) .children((!actions.is_empty()).then(|| { @@ -334,35 +327,30 @@ impl Yumush { })) } - pub(super) fn report_actions( - &self, - report: &Report, - entity: &Entity, - palette: Palette, - ) -> Vec { + fn report_actions(&self, report: &Report, entity: &Entity, t: Tokens) -> Vec { if report.status != ReportStatus::Open { return Vec::new(); } - let resolve_id = report.id; - let dismiss_id = report.id; + let report_id = report.id; + let words = &w().builder_reports; let mut buttons = vec![ parts::button( - format!("resolve_report_{}", report.id), - w().builder_reports.resolve, + format!("resolve_report_{report_id}"), + words.resolve, Press::Plain, - palette.tokens, + t, entity_action(entity, move |yumush, window, cx| { - yumush.handle_report(resolve_id, ReportStatus::Resolved, window, cx) + yumush.handle_report(report_id, ReportStatus::Resolved, window, cx) }), ) .into_any_element(), parts::button( - format!("dismiss_report_{}", report.id), - w().builder_reports.dismiss, + format!("dismiss_report_{report_id}"), + words.dismiss, Press::Plain, - palette.tokens, + t, entity_action(entity, move |yumush, window, cx| { - yumush.handle_report(dismiss_id, ReportStatus::Dismissed, window, cx) + yumush.handle_report(report_id, ReportStatus::Dismissed, window, cx) }), ) .into_any_element(), @@ -370,10 +358,10 @@ impl Yumush { if let (Some(message_id), Some(_)) = (report.message_id, report.community_id) { buttons.push( parts::button( - format!("delete_report_message_{}", report.id), - w().builder_reports.delete_message, + format!("delete_report_message_{report_id}"), + words.delete_message, Press::Plain, - palette.tokens, + t, entity_action(entity, move |yumush, window, cx| { yumush.delete_report_message(message_id, window, cx) }), @@ -382,29 +370,40 @@ impl Yumush { ); } if let Some(target) = &report.target { - let timeout_id = target.id; - let ban_id = target.id; - let ban_reason = report.reason.clone(); + let user_id = target.id; + let reason = report.reason.clone(); + let armed = self.desk.punish; + let timeout = Punish::Timeout(user_id); + let ban = Punish::Ban(user_id); + let timeout_reason = reason.clone(); buttons.push( parts::button( - format!("timeout_report_{}", report.id), - w().builder_reports.timeout, + format!("timeout_report_{report_id}_{}", armed == Some(timeout)), + if armed == Some(timeout) { + w().builder_ui.confirm + } else { + words.timeout + }, Press::Plain, - palette.tokens, + t, entity_action(entity, move |yumush, window, cx| { - yumush.timeout_report_target(timeout_id, window, cx) + yumush.punish_report(timeout, &timeout_reason, window, cx) }), ) .into_any_element(), ); buttons.push( parts::button( - format!("ban_report_{}", report.id), - w().builder_reports.ban, + format!("ban_report_{report_id}_{}", armed == Some(ban)), + if armed == Some(ban) { + w().builder_ui.confirm + } else { + words.ban + }, Press::Danger, - palette.tokens, + t, entity_action(entity, move |yumush, window, cx| { - yumush.ban_report_target(ban_id, &ban_reason, window, cx) + yumush.punish_report(ban, &reason, window, cx) }), ) .into_any_element(), diff --git a/crates/client/src/gui/builder/server.rs b/crates/client/src/gui/builder/server.rs index 26cd394..975bf08 100644 --- a/crates/client/src/gui/builder/server.rs +++ b/crates/client/src/gui/builder/server.rs @@ -1,4 +1,5 @@ use crate::gui::glyph::Fill as _; +use crate::gui::style::Tokens; use common::{ call::{RestartServer, UpdateServerSettings}, model::ServerSettings, @@ -8,9 +9,12 @@ use gpui_kit::{ component::{WindowExt, input::InputState, notification::Notification}, }; -use super::ui::{field_row, list_card, number, to_bytes, to_units}; +use super::{ + BuilderTab, + ui::{field_row, list_card, number, to_bytes, to_units}, +}; use crate::gui::{ - KB, MB, Palette, Yumush, + KB, MB, Yumush, chat::Armed, notify_error, settings_page::{delete_control, segmented}, @@ -39,95 +43,93 @@ impl Yumush { let Some(settings) = self.server.clone() else { return; }; - self.chat.server_registration_open = settings.registration_open; - self.chat.server_maintenance = settings.maintenance; + self.chat.admin.server_registration_open = settings.registration_open; + self.chat.admin.server_maintenance = settings.maintenance; let chat = &self.chat; - set_input(&chat.server_name, &settings.name, window, cx); - set_input( - &chat.server_limit, - &to_units(settings.max_attachment_bytes, MB as u64), - window, - cx, - ); - set_input( - &chat.server_user_quota, - &to_units(settings.user_quota_bytes, MB as u64), - window, - cx, - ); - set_input( - &chat.server_community_quota, - &to_units(settings.community_quota_bytes, MB as u64), - window, - cx, - ); - set_input( - &chat.server_message_retention, - &settings.message_retention_days.to_string(), - window, - cx, - ); - set_input( - &chat.server_attachment_retention, - &settings.attachment_retention_days.to_string(), - window, - cx, - ); - set_input( - &chat.server_announcement, - &settings.announcement, - window, - cx, - ); - set_input( - &chat.server_max_communities, - &settings.max_communities_per_user.to_string(), - window, - cx, - ); - set_input( - &chat.server_max_message_length, - &settings.max_message_length.to_string(), - window, - cx, - ); - set_input( - &chat.server_max_avatar, - &to_units(settings.max_avatar_bytes, KB as u64), - window, - cx, - ); - set_input( - &chat.server_messages_per_minute, - &settings.messages_per_minute.to_string(), - window, - cx, - ); - set_input( - &chat.server_logins_per_minute, - &settings.logins_per_minute.to_string(), - window, - cx, - ); + let fields = [ + (&chat.admin.server_name, settings.name.clone()), + ( + &chat.admin.server_limit, + to_units(settings.max_attachment_bytes, MB as u64), + ), + ( + &chat.admin.server_user_quota, + to_units(settings.user_quota_bytes, MB as u64), + ), + ( + &chat.admin.server_community_quota, + to_units(settings.community_quota_bytes, MB as u64), + ), + ( + &chat.admin.server_message_retention, + settings.message_retention_days.to_string(), + ), + ( + &chat.admin.server_attachment_retention, + settings.attachment_retention_days.to_string(), + ), + ( + &chat.admin.server_announcement, + settings.announcement.clone(), + ), + ( + &chat.admin.server_max_communities, + settings.max_communities_per_user.to_string(), + ), + ( + &chat.admin.server_max_message_length, + settings.max_message_length.to_string(), + ), + ( + &chat.admin.server_max_avatar, + to_units(settings.max_avatar_bytes, KB as u64), + ), + ( + &chat.admin.server_messages_per_minute, + settings.messages_per_minute.to_string(), + ), + ( + &chat.admin.server_logins_per_minute, + settings.logins_per_minute.to_string(), + ), + ]; + for (input, text) in fields { + set_input(input, &text, window, cx); + } + } + + pub(in crate::gui) fn set_server( + &mut self, + settings: ServerSettings, + window: Option<&mut Window>, + cx: &mut Context, + ) { + self.server = Some(settings); + if let Some(window) = window + && self.chat.admin.builder_tab == BuilderTab::Server + { + self.fill_server_form(window, cx); + } + cx.notify(); } pub(super) fn server_form(&self, cx: &App) -> Option { let chat = &self.chat; Some(ServerSettings { - name: input_text(&chat.server_name, cx), - registration_open: chat.server_registration_open, - max_attachment_bytes: input_bytes(&chat.server_limit, MB as u64, cx)?, - maintenance: chat.server_maintenance, - user_quota_bytes: input_bytes(&chat.server_user_quota, MB as u64, cx)?, - community_quota_bytes: input_bytes(&chat.server_community_quota, MB as u64, cx)?, - message_retention_days: input_number(&chat.server_message_retention, cx)?, - attachment_retention_days: input_number(&chat.server_attachment_retention, cx)?, - announcement: input_text(&chat.server_announcement, cx), - max_communities_per_user: input_number(&chat.server_max_communities, cx)?, - max_message_length: input_number(&chat.server_max_message_length, cx)?, - max_avatar_bytes: input_bytes(&chat.server_max_avatar, KB as u64, cx)?, - messages_per_minute: input_number(&chat.server_messages_per_minute, cx)?, - logins_per_minute: input_number(&chat.server_logins_per_minute, cx)?, + name: input_text(&chat.admin.server_name, cx), + registration_open: chat.admin.server_registration_open, + max_attachment_bytes: input_bytes(&chat.admin.server_limit, MB as u64, cx)?, + maintenance: chat.admin.server_maintenance, + user_quota_bytes: input_bytes(&chat.admin.server_user_quota, MB as u64, cx)?, + community_quota_bytes: input_bytes(&chat.admin.server_community_quota, MB as u64, cx)?, + message_retention_days: input_number(&chat.admin.server_message_retention, cx)?, + attachment_retention_days: input_number(&chat.admin.server_attachment_retention, cx)?, + announcement: input_text(&chat.admin.server_announcement, cx), + max_communities_per_user: input_number(&chat.admin.server_max_communities, cx)?, + max_message_length: input_number(&chat.admin.server_max_message_length, cx)?, + max_avatar_bytes: input_bytes(&chat.admin.server_max_avatar, KB as u64, cx)?, + messages_per_minute: input_number(&chat.admin.server_messages_per_minute, cx)?, + logins_per_minute: input_number(&chat.admin.server_logins_per_minute, cx)?, }) } @@ -141,9 +143,8 @@ impl Yumush { cx.spawn_in(window, async move |this, cx| { match network.call(UpdateServerSettings { settings }).await { Ok(settings) => { - let _ = this.update(cx, |yumush, cx| { - yumush.server = Some(settings); - cx.notify(); + let _ = this.update_in(cx, |yumush, window, cx| { + yumush.set_server(settings, Some(window), cx) }); } Err(error) => notify_error(&this, cx, error), @@ -166,13 +167,13 @@ impl Yumush { cx.notify(); } - pub(super) fn server_body(&self, entity: &Entity, palette: Palette) -> Vec { + pub(super) fn server_body(&self, entity: &Entity, t: Tokens) -> Vec { let general = vec![ field_row( w().builder_server.name, None, - field(palette, &self.chat.server_name), - palette, + field(t, &self.chat.admin.server_name), + t, ), field_row( w().builder_server.registration, @@ -182,12 +183,12 @@ impl Yumush { (true, w().builder_server.open), (false, w().builder_server.closed), ], - self.chat.server_registration_open, + self.chat.admin.server_registration_open, entity, - palette, - |yumush, open, _| yumush.chat.server_registration_open = open, + t, + |yumush, open, _| yumush.chat.admin.server_registration_open = open, ), - palette, + t, ), field_row( w().builder_server.maintenance, @@ -197,92 +198,92 @@ impl Yumush { (false, w().builder_server.off), (true, w().builder_server.on), ], - self.chat.server_maintenance, + self.chat.admin.server_maintenance, entity, - palette, - |yumush, on, _| yumush.chat.server_maintenance = on, + t, + |yumush, on, _| yumush.chat.admin.server_maintenance = on, ), - palette, + t, ), field_row( w().builder_server.announcement, None, - field(palette, &self.chat.server_announcement), - palette, + field(t, &self.chat.admin.server_announcement), + t, ), ]; let limits = vec![ field_row( w().builder_server.max_attachment, None, - field(palette, &self.chat.server_limit), - palette, + field(t, &self.chat.admin.server_limit), + t, ), field_row( w().builder_server.max_avatar, None, - field(palette, &self.chat.server_max_avatar), - palette, + field(t, &self.chat.admin.server_max_avatar), + t, ), field_row( w().builder_server.max_message_length, None, - field(palette, &self.chat.server_max_message_length), - palette, + field(t, &self.chat.admin.server_max_message_length), + t, ), field_row( w().builder_server.communities_per_user, Some(w().builder_server.zero_unlimited), - field(palette, &self.chat.server_max_communities), - palette, + field(t, &self.chat.admin.server_max_communities), + t, ), ]; let storage = vec![ field_row( w().builder_server.user_quota, Some(w().builder_server.zero_unlimited), - field(palette, &self.chat.server_user_quota), - palette, + field(t, &self.chat.admin.server_user_quota), + t, ), field_row( w().builder_server.community_quota, Some(w().builder_server.zero_unlimited), - field(palette, &self.chat.server_community_quota), - palette, + field(t, &self.chat.admin.server_community_quota), + t, ), field_row( w().builder_server.message_retention, Some(w().builder_server.zero_off), - field(palette, &self.chat.server_message_retention), - palette, + field(t, &self.chat.admin.server_message_retention), + t, ), field_row( w().builder_server.attachment_retention, Some(w().builder_server.zero_off), - field(palette, &self.chat.server_attachment_retention), - palette, + field(t, &self.chat.admin.server_attachment_retention), + t, ), ]; let rate = vec![ field_row( w().builder_server.messages_per_minute, Some(w().builder_server.zero_off), - field(palette, &self.chat.server_messages_per_minute), - palette, + field(t, &self.chat.admin.server_messages_per_minute), + t, ), field_row( w().builder_server.logins_per_minute, Some(w().builder_server.zero_off), - field(palette, &self.chat.server_logins_per_minute), - palette, + field(t, &self.chat.admin.server_logins_per_minute), + t, ), ]; vec![ - list_card(Some(w().builder_server.general), general, "", palette).into_any_element(), - list_card(Some(w().builder_server.limits), limits, "", palette).into_any_element(), - list_card(Some(w().builder_server.storage), storage, "", palette).into_any_element(), - list_card(Some(w().builder_server.rate_limits), rate, "", palette).into_any_element(), + list_card(Some(w().builder_server.general), general, "", t).into_any_element(), + list_card(Some(w().builder_server.limits), limits, "", t).into_any_element(), + list_card(Some(w().builder_server.storage), storage, "", t).into_any_element(), + list_card(Some(w().builder_server.rate_limits), rate, "", t).into_any_element(), list_card( Some(w().builder_server.process), vec![field_row( @@ -293,13 +294,13 @@ impl Yumush { w().update.restart, self.armed(Armed::RestartServer), entity, - palette, + t, Yumush::restart_server, ), - palette, + t, )], "", - palette, + t, ) .into_any_element(), ] diff --git a/crates/client/src/gui/builder/storage.rs b/crates/client/src/gui/builder/storage.rs index 7bd63d3..c743bd4 100644 --- a/crates/client/src/gui/builder/storage.rs +++ b/crates/client/src/gui/builder/storage.rs @@ -10,28 +10,19 @@ use gpui_kit::{ div, px, relative, }; -use super::ui::{ - card, card_header, confirmed, delete_icon_button, fixed, list_card, list_row, toolbar, -}; +use super::ui::{card, card_header, delete_icon_button, fixed, list_card, list_row, toolbar}; +use crate::gui::chat::Armed; use crate::gui::{ - Palette, Yumush, + Yumush, community_settings::user_name, entity_action, millis_time, notify_error, storage, - style::{radius, size, space, text}, + style::{Tokens, radius, size, space, text}, text, widget::field, }; use crate::lang::w; -fn share(bytes: u64, max: u64) -> f32 { - if max == 0 { - 0. - } else { - bytes as f32 / max as f32 - } -} - -fn usage_row(name: &str, bytes: u64, count: u64, fraction: f32, palette: Palette) -> Div { +fn usage_row(name: &str, bytes: u64, count: u64, fraction: f32, t: Tokens) -> Div { div() .px(px(space::LG)) .py(px(space::SM)) @@ -49,7 +40,7 @@ fn usage_row(name: &str, bytes: u64, count: u64, fraction: f32, palette: Palette .min_w_0() .truncate() .text_size(text(text::LABEL)) - .text_color(palette.text) + .text_color(t.paper()) .child(name.to_string()), ) .child( @@ -57,7 +48,7 @@ fn usage_row(name: &str, bytes: u64, count: u64, fraction: f32, palette: Palette .flex_shrink_0() .text_size(text(text::LABEL)) .font_weight(FontWeight::MEDIUM) - .text_color(palette.text) + .text_color(t.paper()) .child(storage(bytes)), ) .child( @@ -67,7 +58,7 @@ fn usage_row(name: &str, bytes: u64, count: u64, fraction: f32, palette: Palette .flex() .justify_end() .text_size(text(text::CAPTION)) - .text_color(palette.muted) + .text_color(t.dim()) .child(count.to_string()), ), ) @@ -75,28 +66,37 @@ fn usage_row(name: &str, bytes: u64, count: u64, fraction: f32, palette: Palette div() .h(px(space::XXS)) .rounded(px(radius::SM)) - .bg(palette.hover) + .bg(t.hov()) .child( div() .h_full() .w(relative(fraction)) .rounded(px(radius::SM)) - .bg(palette.accent), + .bg(t.paper()), ), ) } -fn attachment_row( - info: &AttachmentInfo, - pending: bool, - entity: &Entity, - palette: Palette, -) -> Div { +fn usage_card(title: &'static str, rows: Vec<(&str, u64, u64)>, t: Tokens) -> Div { + let max = rows.iter().map(|&(_, bytes, _)| bytes).max().unwrap_or(0); + let rows = rows + .into_iter() + .map(|(name, bytes, count)| { + usage_row(name, bytes, count, bytes as f32 / max.max(1) as f32, t) + }) + .collect(); + div() + .flex_1() + .min_w_0() + .child(list_card(Some(title), rows, w().builder_storage.no_data, t).h_full()) +} + +fn attachment_row(info: &AttachmentInfo, pending: bool, entity: &Entity, t: Tokens) -> Div { let attachment_id = info.attachment.id; let delete = delete_icon_button( format!("delete_attachment_{}", info.attachment.id), pending, - palette, + t, entity_action(entity, move |yumush, window, cx| { yumush.delete_builder_attachment(attachment_id, window, cx) }), @@ -107,7 +107,7 @@ fn attachment_row( Icon::new(IconName::File) .size(px(size::ICON)) .flex_shrink_0() - .text_color(palette.muted), + .text_color(t.dim()), ) .child( div() @@ -120,7 +120,7 @@ fn attachment_row( div() .min_w_0() .text_size(text(text::LABEL)) - .text_color(palette.text) + .text_color(t.paper()) .child(super::super::glyph::line( info.attachment.name.clone().into(), super::super::text(super::super::style::text::LABEL), @@ -130,7 +130,7 @@ fn attachment_row( div() .truncate() .text_size(text(text::CAPTION)) - .text_color(palette.muted) + .text_color(t.dim()) .child(format!( "{} · {} · {}", user_name(&info.uploader), @@ -143,96 +143,52 @@ fn attachment_row( div() .flex_shrink_0() .text_size(text(text::CAPTION)) - .text_color(palette.muted) + .text_color(t.dim()) .child(storage(info.attachment.size)), ) .child(delete) } impl Yumush { - pub(super) fn storage_body(&self, entity: &Entity, palette: Palette) -> Vec { - let user_max = self - .chat - .builder_usage_users - .iter() - .map(|usage| usage.bytes) - .max() - .unwrap_or(0); - let community_max = self - .chat - .builder_usage_communities - .iter() - .map(|usage| usage.bytes) - .max() - .unwrap_or(0); - let users: Vec
= self - .chat - .builder_usage_users - .iter() - .map(|usage| { - usage_row( - &usage.user.username, - usage.bytes, - usage.count, - share(usage.bytes, user_max), - palette, - ) - }) - .collect(); - let communities: Vec
= self - .chat - .builder_usage_communities - .iter() - .map(|usage| { - usage_row( - &usage.community, - usage.bytes, - usage.count, - share(usage.bytes, community_max), - palette, - ) - }) - .collect(); + pub(super) fn storage_body(&self, entity: &Entity, t: Tokens) -> Vec { let usage = div() .flex() .gap(px(space::XL)) - .child( - div().flex_1().min_w_0().child( - list_card( - Some(w().builder_storage.users), - users, - w().builder_storage.no_data, - palette, - ) - .h_full(), - ), - ) - .child( - div().flex_1().min_w_0().child( - list_card( - Some(w().builder_storage.communities), - communities, - w().builder_storage.no_data, - palette, - ) - .h_full(), - ), - ); + .child(usage_card( + w().builder_storage.users, + self.chat + .admin + .builder_usage_users + .iter() + .map(|usage| (usage.user.username.as_str(), usage.bytes, usage.count)) + .collect(), + t, + )) + .child(usage_card( + w().builder_storage.communities, + self.chat + .admin + .builder_usage_communities + .iter() + .map(|usage| (usage.community.as_str(), usage.bytes, usage.count)) + .collect(), + t, + )); let controls = toolbar(vec![ fixed( size::THUMB, - field(palette, &self.chat.builder_attachment_user), + field(t, &self.chat.admin.builder_attachment_user), ), fixed( size::THUMB, - field(palette, &self.chat.builder_attachment_community), + field(t, &self.chat.admin.builder_attachment_community), ), crate::gui::parts::button( "search_attachments", w().builder_storage.search, crate::gui::parts::Press::Plain, - palette.tokens, + t, entity_action(entity, |yumush, window, cx| { yumush.search_attachments(window, cx) }), @@ -242,37 +198,35 @@ impl Yumush { .into_any_element(); let rows: Vec
= self .chat + .admin .builder_attachments .iter() .map(|info| { - let pending = self.chat.pending_attachment_delete == Some(info.attachment.id); - attachment_row(info, pending, entity, palette) + let pending = self.armed(Armed::DeleteAttachment(info.attachment.id)); + attachment_row(info, pending, entity, t) }) .collect(); let body = if rows.is_empty() { - crate::gui::parts::empty(w().builder_storage.no_attachments, palette.tokens) + crate::gui::parts::empty(w().builder_storage.no_attachments, t) } else { div().flex().flex_col().children(rows) }; - let attachments = card(palette) + let attachments = card() .child(card_header( w().builder_storage.attachments, vec![controls], - palette, + t, )) .child(body); vec![ usage.into_any_element(), attachments.into_any_element(), - self.backups_card(entity, palette).into_any_element(), + self.backups_card(entity, t).into_any_element(), ] } pub(super) fn load_storage(&self, window: &mut Window, cx: &mut Context) { - if !self.is_builder() { - return; - } self.search_attachments(window, cx); self.load_backups(window, cx); self.fetch_builder( @@ -280,19 +234,20 @@ impl Yumush { cx, |network| async move { network.storage_usage().await }, |yumush, (users, communities), cx| { - yumush.chat.builder_usage_users = users; - yumush.chat.builder_usage_communities = communities; + yumush.chat.admin.builder_usage_users = users; + yumush.chat.admin.builder_usage_communities = communities; cx.notify(); }, ); } pub(super) fn search_attachments(&self, window: &mut Window, cx: &mut Context) { - let Some(user_id) = self.filter_user(&self.chat.builder_attachment_user, cx) else { + let Some(user_id) = self.filter_user(&self.chat.admin.builder_attachment_user, cx) else { window.push_notification(Notification::error(w().builder_storage.unknown_user), cx); return; }; - let Some(community_id) = self.filter_community(&self.chat.builder_attachment_community, cx) + let Some(community_id) = + self.filter_community(&self.chat.admin.builder_attachment_community, cx) else { window.push_notification( Notification::error(w().builder_storage.unknown_community), @@ -318,7 +273,7 @@ impl Yumush { }; let _ = this.update(cx, |yumush, cx| { - yumush.chat.builder_attachments = attachments; + yumush.chat.admin.builder_attachments = attachments; cx.notify(); }); }) @@ -331,8 +286,7 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) { - if !confirmed(&mut self.chat.pending_attachment_delete, attachment_id) { - cx.notify(); + if !self.arm(Armed::DeleteAttachment(attachment_id), cx) { return; } let network = self.network.clone(); diff --git a/crates/client/src/gui/builder/ui.rs b/crates/client/src/gui/builder/ui.rs index 7642fa7..f0736d7 100644 --- a/crates/client/src/gui/builder/ui.rs +++ b/crates/client/src/gui/builder/ui.rs @@ -1,9 +1,6 @@ -use crate::gui::style::{size, space, text}; -use crate::gui::{ - Palette, Tooltip as _, - parts::{self, Scale, Tone}, - text, -}; +use crate::gui::parts::{self, Fill, Scale, Tone}; +use crate::gui::style::{Tokens, size, space, text}; +use crate::gui::{Tooltip as _, text}; use crate::lang::w; use gpui_kit::{ AnyElement, App, Div, FontWeight, Hsla, IntoElement, ParentElement, Stateful, Styled, Window, @@ -12,6 +9,7 @@ use gpui_kit::{ use jiff::{civil::Date, tz::TimeZone}; const LABEL_WIDTH: f32 = 88.; +const METER: f32 = 140.; pub(super) fn to_bytes(text: &str, unit: u64) -> Option { text.trim().parse::().ok()?.checked_mul(unit) @@ -43,30 +41,38 @@ pub(super) fn number(text: &str) -> Option { text.trim().parse().ok() } +pub(super) fn caption_text(value: impl Into, color: Hsla) -> Div { + div() + .text_size(text(text::CAPTION)) + .text_color(color) + .child(value.into()) +} + +pub(super) fn meter(share: f32, label: String, t: Tokens) -> Div { + div() + .w(px(METER)) + .flex() + .items_center() + .gap(px(space::SM)) + .child(parts::track(Fill::Part(share), false, t)) + .child(caption_text(label, t.dim())) +} + pub(super) fn icon_button( id: String, icon: IconName, tip: &'static str, color: Hsla, - palette: Palette, + t: Tokens, action: impl Fn(&mut Window, &mut App) + 'static, ) -> Stateful
{ - parts::icon_button( - id, - icon, - tip, - Tone::Idle, - Scale::Small, - palette.tokens, - action, - ) - .text_color(color) + parts::icon_button(id, icon, tip, Tone::Idle, Scale::Small, t, action).text_color(color) } pub(super) fn delete_icon_button( id: String, pending: bool, - palette: Palette, + t: Tokens, action: impl Fn(&mut Window, &mut App) + 'static, ) -> Stateful
{ icon_button( @@ -77,13 +83,11 @@ pub(super) fn delete_icon_button( } else { w().builder_ui.delete }, - palette.danger, - palette, + t.bad(), + t, action, ) - .when(pending, |this| { - this.bg(palette.danger).text_color(palette.on_accent) - }) + .when(pending, |this| this.bg(t.bad()).text_color(t.ground())) } pub(super) fn action_button( @@ -92,17 +96,17 @@ pub(super) fn action_button( label: &'static str, tip: &'static str, color: Hsla, - palette: Palette, + t: Tokens, action: impl Fn(&mut Window, &mut App) + 'static, ) -> Stateful
{ - parts::press(id, palette.tokens, action) + parts::press(id, t, action) .tip(tip) .px_0() .min_w(px(size::THUMB)) .text_size(text(text::CAPTION)) .font_weight(FontWeight::MEDIUM) .text_color(color) - .child(crate::gui::parts::small_icon(icon)) + .child(parts::small_icon(icon)) .child(label) } @@ -112,7 +116,7 @@ pub(super) fn confirm_button( label: &'static str, tip: &'static str, pending: bool, - palette: Palette, + t: Tokens, action: impl Fn(&mut Window, &mut App) + 'static, ) -> Stateful
{ action_button( @@ -128,8 +132,8 @@ pub(super) fn confirm_button( } else { tip }, - palette.danger, - palette, + t.bad(), + t, action, ) .when(pending, |this| this.font_weight(FontWeight::SEMIBOLD)) @@ -137,7 +141,7 @@ pub(super) fn confirm_button( pub(super) fn action_group( title: &'static str, - palette: Palette, + t: Tokens, children: Vec, ) -> Option
{ if children.is_empty() { @@ -158,7 +162,7 @@ pub(super) fn action_group( .items_center() .text_size(text(text::CAPTION)) .font_weight(FontWeight::MEDIUM) - .text_color(palette.muted) + .text_color(t.dim()) .child(title), ) .child( @@ -198,41 +202,32 @@ pub(super) fn end_of_day_ms(text: &str) -> Option { epoch_ms(date.tomorrow().ok()?)?.checked_sub(1) } -pub(super) fn rows_body(rows: Vec
, none: &str, palette: Palette) -> Div { +pub(super) fn rows_body(rows: Vec
, none: &str, t: Tokens) -> Div { if rows.is_empty() { - return crate::gui::parts::empty(none, palette.tokens); + return parts::empty(none, t); } div().flex().flex_col().children(rows) } -pub(super) fn card(_palette: Palette) -> Div { +pub(super) fn card() -> Div { div().flex().flex_col() } -pub(super) fn card_header(title: &str, actions: Vec, palette: Palette) -> Div { +pub(super) fn card_header(title: &str, actions: Vec, t: Tokens) -> Div { div() .pb(px(space::XS)) .flex() .items_center() .justify_between() .gap(px(space::SM)) - .child(crate::gui::parts::section( - title.to_string(), - palette.tokens, - )) + .child(parts::section(title.to_string(), t)) .children(actions) } -pub(super) fn list_card(title: Option<&str>, rows: Vec
, none: &str, palette: Palette) -> Div { - let body = if rows.is_empty() { - crate::gui::parts::empty(none, palette.tokens) - } else { - div().flex().flex_col().children(rows) - }; - - card(palette) - .children(title.map(|title| card_header(title, Vec::new(), palette))) - .child(body) +pub(super) fn list_card(title: Option<&str>, rows: Vec
, none: &str, t: Tokens) -> Div { + card() + .children(title.map(|title| card_header(title, Vec::new(), t))) + .child(rows_body(rows, none, t)) } pub(super) fn list_row() -> Div { @@ -253,28 +248,23 @@ pub(super) fn toolbar(items: Vec) -> Div { .children(items) } -pub(super) fn stat_tile(label: &str, value: &str, palette: Palette) -> Div { - card(palette) +pub(super) fn stat_tile(label: &str, value: &str, t: Tokens) -> Div { + card() .gap(px(space::XXS)) .child( div() .text_size(text(text::DISPLAY)) - .text_color(palette.text) + .text_color(t.paper()) .child(value.to_string()), ) - .child( - div() - .text_size(text(text::CAPTION)) - .text_color(palette.muted) - .child(label.to_string()), - ) + .child(caption_text(label.to_string(), t.dim())) } pub(super) fn field_row( label: &str, hint: Option<&str>, control: impl IntoElement, - palette: Palette, + t: Tokens, ) -> Div { list_row() .justify_between() @@ -287,23 +277,14 @@ pub(super) fn field_row( .child( div() .text_size(text(text::LABEL)) - .text_color(palette.text) + .text_color(t.paper()) .child(label.to_string()), ) - .children(hint.map(|hint| { - div() - .text_size(text(text::CAPTION)) - .text_color(palette.muted) - .child(hint.to_string()) - })), + .children(hint.map(|hint| caption_text(hint.to_string(), t.dim()))), ) .child(div().w(px(size::SIDEBAR)).flex_shrink_0().child(control)) } -pub(super) fn pill(label: &str, color: Hsla, palette: Palette) -> Div { - let _ = palette; - div() - .text_size(text(text::CAPTION)) - .text_color(color) - .child(label.to_string()) +pub(super) fn pill(label: &str, color: Hsla) -> Div { + caption_text(label.to_string(), color) } diff --git a/crates/client/src/gui/builder/users.rs b/crates/client/src/gui/builder/users.rs index 21941ac..a99b77f 100644 --- a/crates/client/src/gui/builder/users.rs +++ b/crates/client/src/gui/builder/users.rs @@ -7,7 +7,9 @@ use common::{ ListUpdateClients, PurgeUser, RenameUser, ResetPassword, RevokeSession, RevokeSessions, SuspendUser, TimeoutUser, }, - model::{Account, BanScope, Role, SessionInfo, UpdateClient, UpdateState, User}, + model::{ + Account, BanScope, Hue, Role, SessionInfo, Suspension, UpdateClient, UpdateState, User, + }, permission, stats::Stats, time::{DAY_MILLIS, HOUR_MILLIS, MINUTE_MILLIS, now_ms}, @@ -23,17 +25,17 @@ use gpui_kit::{ }; use super::BuilderTab; -use super::releases::{caption_text, meter}; -use super::ui::{action_button, action_group, card, confirm_button, confirmed, pill}; +use super::ui::{ + action_button, action_group, caption_text, card, confirm_button, meter, number, pill, rows_body, +}; +use crate::gui::chat::{Armed, admin::UserEdit}; use crate::lang::w; use crate::{ gui::{ - Palette, Tooltip as _, Yumush, avatar, - chat::View, - clickable, entity_action, millis_time, notify_error, + Tooltip as _, Yumush, avatar, clickable, entity_action, millis_time, notify_error, parts::{self, Press}, profile::user_link, - style::{radius, size, space, text}, + style::{Tokens, radius, size, space, text}, text, widget::{field, search_text}, }, @@ -61,15 +63,31 @@ fn seen_text(last_seen: Option) -> String { } } -fn status(label: &str, color: gpui_kit::Hsla, palette: Palette) -> Div { - div().flex_shrink_0().child(pill(label, color, palette)) +fn status(label: &str, color: gpui_kit::Hsla) -> Div { + div().flex_shrink_0().child(pill(label, color)) +} + +fn form_row( + input: &Entity, + t: Tokens, + actions: impl IntoIterator, +) -> Div { + div() + .h(px(size::ROW)) + .px(px(space::MD)) + .flex() + .items_center() + .gap(px(space::SM)) + .child(div().flex_1().min_w_0().child(field(t, input))) + .children(actions) } impl Yumush { pub(super) fn submit_new_user(&mut self, window: &mut Window, cx: &mut Context) { - let username = self.chat.new_username.read(cx).text().to_string(); - let password = self.chat.new_password.read(cx).text().to_string(); + let username = self.chat.admin.new_username.read(cx).text().to_string(); + let password = self.chat.admin.new_password.read(cx).text().to_string(); self.chat + .admin .new_password .update(cx, |input, cx| input.set_value("", window, cx)); let network = self.network.clone(); @@ -80,6 +98,7 @@ impl Yumush { let _ = this.update_in(cx, |yumush, window, cx| { yumush .chat + .admin .new_username .update(cx, |input, cx| input.set_value("", window, cx)); yumush.load_users(window, cx); @@ -97,8 +116,7 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) { - if !confirmed(&mut self.chat.pending_builder_delete, user_id) { - cx.notify(); + if !self.arm(Armed::BuilderDeleteUser(user_id), cx) { return; } let network = self.network.clone(); @@ -109,8 +127,12 @@ impl Yumush { let _ = this.update(cx, |yumush, cx| { yumush .chat + .admin .builder_users .retain(|account| account.user.id != user_id); + if yumush.sessions_open(user_id) { + yumush.close_builder_sessions(); + } cx.notify(); }); } @@ -125,6 +147,7 @@ impl Yumush { window: &mut Window, cx: &mut Context, action: impl FnOnce(NetworkHandle) -> Fut + 'static, + done: impl FnOnce(&mut Self, &mut Window, &mut Context) + 'static, ) where Fut: Future> + 'static, { @@ -132,7 +155,10 @@ impl Yumush { cx.spawn_in(window, async move |this, cx| match action(network).await { Ok(()) => { - let _ = this.update_in(cx, |yumush, window, cx| yumush.load_users(window, cx)); + let _ = this.update_in(cx, |yumush, window, cx| { + done(yumush, window, cx); + yumush.load_users(window, cx); + }); } Err(error) => notify_error(&this, cx, error), }) @@ -146,9 +172,12 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) { - self.builder_user_action(window, cx, move |network| async move { - network.call(SuspendUser { user_id, suspended }).await - }); + self.builder_user_action( + window, + cx, + move |network| async move { network.call(SuspendUser { user_id, suspended }).await }, + |_, _, _| {}, + ); } pub(super) fn revoke_builder_sessions( @@ -157,9 +186,12 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) { - self.builder_user_action(window, cx, move |network| async move { - network.call(RevokeSessions { user_id }).await - }); + self.builder_user_action( + window, + cx, + move |network| async move { network.call(RevokeSessions { user_id }).await }, + |_, _, _| {}, + ); } pub(super) fn clear_builder_profile( @@ -168,22 +200,26 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) { - self.builder_user_action(window, cx, move |network| async move { - network.call(ClearProfile { user_id }).await.map(|_| ()) - }); + self.builder_user_action( + window, + cx, + move |network| async move { network.call(ClearProfile { user_id }).await.map(|_| ()) }, + |_, _, _| {}, + ); } pub(super) fn toggle_builder_stats(&mut self, user_id: Id, cx: &mut Context) { - let target = match self.chat.followed { + let target = match self.chat.session.followed { Some((id, _)) if id == user_id => None, _ => Some(user_id), }; - self.chat.followed = target.map(|id| (id, Stats::default())); + self.chat.session.followed = target.map(|id| (id, Stats::default())); let network = self.network.clone(); cx.spawn(async move |this, cx| { let latest = network.call(FollowStats { user_id: target }).await; let _ = this.update(cx, |yumush, cx| { - if let (Ok(Some(stats)), Some(followed)) = (latest, yumush.chat.followed.as_mut()) + if let (Ok(Some(stats)), Some(followed)) = + (latest, yumush.chat.session.followed.as_mut()) && Some(followed.0) == target { followed.1 = stats; @@ -195,26 +231,38 @@ impl Yumush { cx.notify(); } - pub(super) fn toggle_builder_password(&mut self, user_id: Id, cx: &mut Context) { - if self.chat.pending_builder_password == Some(user_id) { - self.chat.pending_builder_password = None; + pub(super) fn toggle_user_edit(&mut self, user_id: Id, edit: UserEdit, cx: &mut Context) { + let target = Some((user_id, edit)); + self.chat.admin.editing = if self.chat.admin.editing == target { + None } else { - self.chat.pending_builder_password = Some(user_id); - } + target + }; cx.notify(); } + fn edit_open(&self, user_id: Id, edit: UserEdit) -> bool { + self.chat.admin.editing == Some((user_id, edit)) + } + pub(super) fn reset_builder_password(&mut self, window: &mut Window, cx: &mut Context) { - let Some(user_id) = self.chat.pending_builder_password.take() else { + let Some((user_id, UserEdit::Password)) = self.chat.admin.editing else { return; }; - let password = self.chat.builder_password.read(cx).text().to_string(); - self.chat - .builder_password - .update(cx, |input, cx| input.set_value("", window, cx)); - self.builder_user_action(window, cx, move |network| async move { - network.call(ResetPassword { user_id, password }).await - }); + let password = self.chat.admin.builder_password.read(cx).text().to_string(); + self.builder_user_action( + window, + cx, + move |network| async move { network.call(ResetPassword { user_id, password }).await }, + |yumush, window, cx| { + yumush.chat.admin.editing = None; + yumush + .chat + .admin + .builder_password + .update(cx, |input, cx| input.set_value("", window, cx)); + }, + ); } pub(super) fn load_sessions(&self, user_id: Id, window: &mut Window, cx: &mut Context) { @@ -228,8 +276,8 @@ impl Yumush { match network.call(ListSessions { user_id }).await { Ok(sessions) => { let _ = this.update(cx, |yumush, cx| { - yumush.chat.builder_sessions = Some((user_id, sessions)); - yumush.chat.builder_friends = friends; + yumush.chat.admin.builder_sessions = Some((user_id, sessions)); + yumush.chat.admin.builder_friends = friends; cx.notify(); }); } @@ -239,45 +287,51 @@ impl Yumush { .detach(); } + fn sessions_open(&self, user_id: Id) -> bool { + self.chat + .admin + .builder_sessions + .as_ref() + .is_some_and(|(open, _)| *open == user_id) + } + + fn close_builder_sessions(&mut self) { + self.chat.admin.builder_sessions = None; + self.chat.admin.builder_clients.clear(); + self.chat.admin.builder_clients_task = None; + } + pub(super) fn toggle_builder_sessions( &mut self, user_id: Id, window: &mut Window, cx: &mut Context, ) { - if let Some((followed, _)) = self.chat.followed { + if let Some((followed, _)) = self.chat.session.followed { self.toggle_builder_stats(followed, cx); } - if self - .chat - .builder_sessions - .as_ref() - .is_some_and(|(open, _)| *open == user_id) - { - self.chat.builder_sessions = None; - self.chat.builder_clients.clear(); - self.chat.builder_clients_task = None; + if self.sessions_open(user_id) { + self.close_builder_sessions(); cx.notify(); return; } self.load_sessions(user_id, window, cx); - self.chat.builder_clients.clear(); + self.chat.admin.builder_clients.clear(); self.watch_builder_clients(user_id, cx); } fn watch_builder_clients(&mut self, user_id: Id, cx: &mut Context) { let network = self.network.clone(); - self.chat.builder_clients_task = Some(cx.spawn(async move |this, cx| { + self.chat.admin.builder_clients_task = Some(cx.spawn(async move |this, cx| { loop { - let Ok(visible) = this.update(cx, |yumush, _| { - yumush.chat.view == View::Builder - && yumush.chat.builder_tab == BuilderTab::Users - }) else { + let Ok(visible) = + this.update(cx, |yumush, _| yumush.on_builder_tab(BuilderTab::Users)) + else { break; }; if visible && let Ok(clients) = network.call(ListUpdateClients { user_id }).await { let _ = this.update(cx, |yumush, cx| { - yumush.chat.builder_clients = clients; + yumush.chat.admin.builder_clients = clients; cx.notify(); }); } @@ -314,68 +368,56 @@ impl Yumush { .detach(); } - pub(super) fn toggle_builder_rename(&mut self, user_id: Id, cx: &mut Context) { - if self.chat.pending_builder_rename == Some(user_id) { - self.chat.pending_builder_rename = None; - } else { - self.chat.pending_builder_rename = Some(user_id); - } - cx.notify(); - } - pub(super) fn rename_builder_user(&mut self, window: &mut Window, cx: &mut Context) { - let Some(user_id) = self.chat.pending_builder_rename.take() else { + let Some((user_id, UserEdit::Rename)) = self.chat.admin.editing else { return; }; - let username = self.chat.builder_rename.read(cx).text().to_string(); - self.chat - .builder_rename - .update(cx, |input, cx| input.set_value("", window, cx)); - self.builder_user_action(window, cx, move |network| async move { - network - .call(RenameUser { user_id, username }) - .await - .map(|_| ()) - }); - } - - pub(super) fn toggle_builder_timeout(&mut self, user_id: Id, cx: &mut Context) { - if self.chat.pending_builder_timeout == Some(user_id) { - self.chat.pending_builder_timeout = None; - } else { - self.chat.pending_builder_timeout = Some(user_id); - } - cx.notify(); + let username = self.chat.admin.builder_rename.read(cx).text().to_string(); + self.builder_user_action( + window, + cx, + move |network| async move { + network + .call(RenameUser { user_id, username }) + .await + .map(|_| ()) + }, + |yumush, window, cx| { + yumush.chat.admin.editing = None; + yumush + .chat + .admin + .builder_rename + .update(cx, |input, cx| input.set_value("", window, cx)); + }, + ); } pub(super) fn confirm_builder_timeout(&mut self, window: &mut Window, cx: &mut Context) { - let Some(user_id) = self.chat.pending_builder_timeout else { + let Some((user_id, UserEdit::Timeout)) = self.chat.admin.editing else { return; }; - let minutes = self.chat.builder_timeout.read(cx).text().to_string(); - let Ok(minutes) = minutes.trim().parse::() else { + let minutes = self.chat.admin.builder_timeout.read(cx).text().to_string(); + let Some(minutes) = number(&minutes) else { return; }; - self.chat.pending_builder_timeout = None; - self.chat - .builder_timeout - .update(cx, |input, cx| input.set_value("", window, cx)); - self.builder_user_action(window, cx, move |network| async move { - network.call(TimeoutUser { user_id, minutes }).await - }); - } - - pub(super) fn toggle_builder_ban(&mut self, user_id: Id, cx: &mut Context) { - if self.chat.pending_builder_ban == Some(user_id) { - self.chat.pending_builder_ban = None; - } else { - self.chat.pending_builder_ban = Some(user_id); - } - cx.notify(); + self.builder_user_action( + window, + cx, + move |network| async move { network.call(TimeoutUser { user_id, minutes }).await }, + |yumush, window, cx| { + yumush.chat.admin.editing = None; + yumush + .chat + .admin + .builder_timeout + .update(cx, |input, cx| input.set_value("", window, cx)); + }, + ); } pub(super) fn toggle_builder_ban_ip(&mut self, cx: &mut Context) { - self.chat.builder_ban_scope = match self.chat.builder_ban_scope { + self.chat.admin.builder_ban_scope = match self.chat.admin.builder_ban_scope { BanScope::Account => BanScope::AccountAndIp, BanScope::AccountAndIp => BanScope::Account, }; @@ -383,25 +425,40 @@ impl Yumush { } pub(super) fn confirm_builder_ban(&mut self, window: &mut Window, cx: &mut Context) { - let Some(user_id) = self.chat.pending_builder_ban.take() else { + let Some((user_id, UserEdit::Ban)) = self.chat.admin.editing else { return; }; - let reason = self.chat.builder_ban_reason.read(cx).text().to_string(); + let reason = self + .chat + .admin + .builder_ban_reason + .read(cx) + .text() + .to_string(); let reason = reason.trim().to_string(); let reason = (!reason.is_empty()).then_some(reason); - let scope = self.chat.builder_ban_scope; - self.chat - .builder_ban_reason - .update(cx, |input, cx| input.set_value("", window, cx)); - self.builder_user_action(window, cx, move |network| async move { - network - .call(BanUser { - user_id, - reason, - scope, - }) - .await - }); + let scope = self.chat.admin.builder_ban_scope; + self.builder_user_action( + window, + cx, + move |network| async move { + network + .call(BanUser { + user_id, + reason, + scope, + }) + .await + }, + |yumush, window, cx| { + yumush.chat.admin.editing = None; + yumush + .chat + .admin + .builder_ban_reason + .update(cx, |input, cx| input.set_value("", window, cx)); + }, + ); } pub(super) fn purge_builder_user( @@ -410,8 +467,7 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) { - if !confirmed(&mut self.chat.pending_builder_purge, user_id) { - cx.notify(); + if !self.arm(Armed::PurgeUser(user_id), cx) { return; } let network = self.network.clone(); @@ -422,6 +478,7 @@ impl Yumush { let _ = this.update_in(cx, |yumush, window, cx| { yumush .chat + .admin .builder_messages .retain(|hit| hit.message.user_id != user_id); yumush.load_users(window, cx); @@ -433,16 +490,12 @@ impl Yumush { .detach(); } - pub(super) fn users_body( - &self, - entity: &Entity, - palette: Palette, - cx: &App, - ) -> Vec { - let query = search_text(&self.chat.builder_search, cx); + pub(super) fn users_body(&self, entity: &Entity, t: Tokens, cx: &App) -> Vec { + let query = search_text(&self.chat.admin.builder_search, cx); let rows: Vec
= match self.user.as_ref() { Some(me) => self .chat + .admin .builder_users .iter() .filter(|account| { @@ -452,204 +505,170 @@ impl Yumush { .to_lowercase() .contains(query.as_str()) }) - .map(|account| self.builder_row(account, me, entity, palette, cx)) + .map(|account| self.builder_row(account, me, entity, t, cx)) .collect(), None => Vec::new(), }; + let grow = |control: AnyElement| div().flex_1().min_w(px(size::THUMB)).child(control); let toolbar = div() .pb(px(space::SM)) .flex() .flex_wrap() .items_center() .gap(px(space::SM)) - .child( - div() - .flex_1() - .min_w(px(size::THUMB)) - .child(crate::gui::sidebar::input_box( - &self.chat.builder_search, - palette, - )), - ) - .child( - div() - .flex_1() - .min_w(px(size::THUMB)) - .child(field(palette, &self.chat.new_username)), - ) - .child( - div() - .flex_1() - .min_w(px(size::THUMB)) - .child(field(palette, &self.chat.new_password)), - ) - .child(crate::gui::parts::button( + .child(grow( + crate::gui::sidebar::input_box(&self.chat.admin.builder_search, t) + .into_any_element(), + )) + .child(grow( + field(t, &self.chat.admin.new_username).into_any_element(), + )) + .child(grow( + field(t, &self.chat.admin.new_password).into_any_element(), + )) + .child(parts::button( "create_user", w().builder_users.create, - crate::gui::parts::Press::Plain, - palette.tokens, + Press::Plain, + t, entity_action(entity, |yumush, window, cx| { yumush.submit_new_user(window, cx) }), )); - let body = if rows.is_empty() { - crate::gui::parts::empty(w().common.no_users, palette.tokens) - } else { - div().flex().flex_col().children(rows) - }; - - vec![card(palette).child(toolbar).child(body).into_any_element()] + vec![ + card() + .child(toolbar) + .child(rows_body(rows, w().common.no_users, t)) + .into_any_element(), + ] } - pub(super) fn builder_timeout_row( - &self, - user_id: Id, - entity: &Entity, - palette: Palette, - ) -> Div { - div() - .h(px(size::ROW)) - .px(px(space::MD)) - .flex() - .items_center() - .gap(px(space::SM)) - .child( - div() - .flex_1() - .min_w_0() - .child(field(palette, &self.chat.builder_timeout)), - ) - .child(parts::button( + pub(super) fn builder_timeout_row(&self, user_id: Id, entity: &Entity, t: Tokens) -> Div { + form_row( + &self.chat.admin.builder_timeout, + t, + [parts::button( format!("confirm_timeout_{user_id}"), w().builder_users.confirm, Press::Plain, - palette.tokens, + t, entity_action(entity, |yumush, window, cx| { yumush.confirm_builder_timeout(window, cx) }), - )) + ) + .into_any_element()], + ) } - pub(super) fn builder_ban_row( - &self, - user_id: Id, - entity: &Entity, - palette: Palette, - ) -> Div { - let ip_label = if self.chat.builder_ban_scope == BanScope::AccountAndIp { + pub(super) fn builder_ban_row(&self, user_id: Id, entity: &Entity, t: Tokens) -> Div { + let ip_label = if self.chat.admin.builder_ban_scope == BanScope::AccountAndIp { w().builder_users.ip_on } else { w().builder_users.ip_off }; - div() - .h(px(size::ROW)) - .px(px(space::MD)) - .flex() - .items_center() - .gap(px(space::SM)) - .child( - div() - .flex_1() - .min_w_0() - .child(field(palette, &self.chat.builder_ban_reason)), - ) - .child(parts::button( - format!("ban_ip_{user_id}"), - ip_label, - Press::Plain, - palette.tokens, - entity_action(entity, |yumush, _, cx| yumush.toggle_builder_ban_ip(cx)), - )) - .child(parts::button( - format!("confirm_ban_{user_id}"), - w().builder_users.confirm, - Press::Plain, - palette.tokens, - entity_action(entity, |yumush, window, cx| { - yumush.confirm_builder_ban(window, cx) - }), - )) + form_row( + &self.chat.admin.builder_ban_reason, + t, + [ + parts::button( + format!("ban_ip_{user_id}"), + ip_label, + Press::Plain, + t, + entity_action(entity, |yumush, _, cx| yumush.toggle_builder_ban_ip(cx)), + ) + .into_any_element(), + parts::button( + format!("confirm_ban_{user_id}"), + w().builder_users.confirm, + Press::Plain, + t, + entity_action(entity, |yumush, window, cx| { + yumush.confirm_builder_ban(window, cx) + }), + ) + .into_any_element(), + ], + ) } - fn builder_friend_list(&self, palette: Palette) -> Vec { - let friends = self.chat.builder_friends.clone(); - let search = self.chat.builder_friend_search.clone(); - let avatars = self.chat.avatars.clone(); + fn builder_friend_list(&self, t: Tokens) -> AnyElement { + let friends = self.chat.admin.builder_friends.clone(); + let search = self.chat.admin.builder_friend_search.clone(); + let avatars = self.chat.session.avatars.clone(); let label = w().builder_users.friends_count(friends.len()); - vec![ - Popover::new("builder_friends") - .anchor(Anchor::TopLeft) - .appearance(false) - .trigger(crate::gui::Trigger::new( - clickable("builder_friends_trigger", palette, |_, _| {}) - .h(px(size::CONTROL_SM)) - .flex() - .items_center() - .gap(px(space::SM)) - .rounded(px(radius::MD)) - .text_size(text(text::CAPTION)) - .font_weight(FontWeight::MEDIUM) - .text_color(palette.text) - .child(crate::gui::parts::small_icon(IconName::Users)) - .child(label) - .child(crate::gui::parts::small_icon(IconName::ChevronDown)), - )) - .content(move |_, _, cx| { - let query = crate::gui::widget::search_text(&search, cx); - crate::gui::parts::popover(palette.tokens) - .w(px(size::POPOVER)) - .p(px(space::SM)) - .gap(px(space::XS)) - .child(crate::gui::sidebar::input_box(&search, palette)) - .child( - div() - .id("builder_friends_list") - .max_h(px(FRIENDS_MAX_H)) - .overflow_y_scroll() - .flex() - .flex_col() - .when(friends.is_empty(), |list| { - list.child( + Popover::new("builder_friends") + .anchor(Anchor::TopLeft) + .appearance(false) + .trigger(crate::gui::Trigger::new( + clickable("builder_friends_trigger", t, |_, _| {}) + .h(px(size::CONTROL_SM)) + .flex() + .items_center() + .gap(px(space::SM)) + .rounded(px(radius::MD)) + .text_size(text(text::CAPTION)) + .font_weight(FontWeight::MEDIUM) + .text_color(t.paper()) + .child(parts::small_icon(IconName::Users)) + .child(label) + .child(parts::small_icon(IconName::ChevronDown)), + )) + .content(move |_, _, cx| { + let query = search_text(&search, cx); + parts::popover(t) + .w(px(size::POPOVER)) + .p(px(space::SM)) + .gap(px(space::XS)) + .child(crate::gui::sidebar::input_box(&search, t)) + .child( + div() + .id("builder_friends_list") + .max_h(px(FRIENDS_MAX_H)) + .overflow_y_scroll() + .flex() + .flex_col() + .when(friends.is_empty(), |list| { + list.child( + div() + .text_size(text(text::CAPTION)) + .text_color(t.dim()) + .child(w().builder_users.no_friends), + ) + }) + .children( + friends + .iter() + .filter(|friend| { + friend.username.to_lowercase().contains(&query) + }) + .map(|friend| { div() - .text_size(text(text::CAPTION)) - .text_color(palette.muted) - .child(w().builder_users.no_friends), - ) - }) - .children( - friends - .iter() - .filter(|friend| { - friend.username.to_lowercase().contains(&query) - }) - .map(|friend| { - div() - .h(px(size::CONTROL_SM)) - .flex() - .items_center() - .gap(px(space::SM)) - .child(crate::gui::avatar( - palette, - friend, - px(size::ICON), - text(text::CAPTION), - &avatars, - )) - .child( - div() - .text_size(text(text::CAPTION)) - .child(friend.username.clone()), - ) - }), - ), - ) - }) - .into_any_element(), - ] + .h(px(size::CONTROL_SM)) + .flex() + .items_center() + .gap(px(space::SM)) + .child(avatar( + t, + friend, + px(size::ICON), + text(text::CAPTION), + &avatars, + )) + .child( + div() + .text_size(text(text::CAPTION)) + .child(friend.username.clone()), + ) + }), + ), + ) + }) + .into_any_element() } pub(super) fn builder_session_row( @@ -657,19 +676,18 @@ impl Yumush { user_id: Id, session: &SessionInfo, entity: &Entity, - palette: Palette, + t: Tokens, ) -> Div { - let revoke_user_id = user_id; let session_id = session.id; let revoke_button = action_button( format!("revoke_session_{}", session.id), IconName::LogOut, w().builder_users.revoke, w().builder_users.end_session, - palette.muted, - palette, + t.dim(), + t, entity_action(entity, move |yumush, window, cx| { - yumush.revoke_builder_session(revoke_user_id, session_id, window, cx) + yumush.revoke_builder_session(user_id, session_id, window, cx) }), ); let device = if session.device.is_empty() { @@ -684,7 +702,7 @@ impl Yumush { .flex() .items_center() .gap(px(space::SM)) - .child(crate::gui::parts::small_icon(IconName::Monitor).text_color(palette.muted)) + .child(parts::small_icon(IconName::Monitor).text_color(t.dim())) .child( div() .flex_1() @@ -697,20 +715,20 @@ impl Yumush { div() .flex_shrink_0() .text_size(text(text::CAPTION)) - .text_color(palette.muted) + .text_color(t.dim()) .child(seen_text(session.last_seen)), ) .child(revoke_button) } - fn builder_client_row(&self, client: &UpdateClient, palette: Palette) -> Div { + fn builder_client_row(&self, client: &UpdateClient, t: Tokens) -> Div { let release = match (client.release, client.target.as_deref()) { (Some(seq), Some(target)) => format!("#{seq} · {target}"), _ => w().builder_users.unknown.to_string(), }; let state = match client.state { - UpdateState::Unknown => caption_text(w().builder_users.dev, palette.muted), - UpdateState::Latest => caption_text(w().builder_users.latest, palette.ok), + UpdateState::Unknown => caption_text(w().builder_users.dev, t.dim()), + UpdateState::Latest => caption_text(w().builder_users.latest, t.hue(Hue::Mint)), UpdateState::Available { required, .. } => caption_text( if required { format!( @@ -721,28 +739,25 @@ impl Yumush { } else { w().builder_users.available.to_string() }, - palette.muted, + t.dim(), ), UpdateState::Downloading { percent, .. } => { - meter(f32::from(percent) / 100., format!("{percent}%"), palette) + meter(f32::from(percent) / 100., format!("{percent}%"), t) } - UpdateState::Installing { .. } => { - caption_text(w().builder_users.installing, palette.muted) - } - UpdateState::Ready { .. } => caption_text(w().builder_users.ready, palette.ok), - UpdateState::Failed { .. } => caption_text(w().builder_users.failed, palette.danger), + UpdateState::Installing { .. } => caption_text(w().builder_users.installing, t.dim()), + UpdateState::Ready { .. } => caption_text(w().builder_users.ready, t.hue(Hue::Mint)), + UpdateState::Failed { .. } => caption_text(w().builder_users.failed, t.bad()), }; let dot = div() .size(px(space::SM)) .flex_shrink_0() .rounded_full() .bg(if client.online { - palette.ok + t.hue(Hue::Mint) } else { - palette.muted + t.dim() }); - let seen = - (!client.online).then(|| caption_text(seen_text(Some(client.seen_ms)), palette.muted)); + let seen = (!client.online).then(|| caption_text(seen_text(Some(client.seen_ms)), t.dim())); div() .w_full() @@ -750,7 +765,7 @@ impl Yumush { .flex() .items_center() .gap(px(space::SM)) - .child(crate::gui::parts::small_icon(IconName::Monitor).text_color(palette.muted)) + .child(parts::small_icon(IconName::Monitor).text_color(t.dim())) .child( div() .flex_1() @@ -759,7 +774,7 @@ impl Yumush { .truncate() .child(client.device.clone()), ) - .child(caption_text(release, palette.muted)) + .child(caption_text(release, t.dim())) .child(state) .child(dot) .children(seen) @@ -769,74 +784,67 @@ impl Yumush { &self, user_id: Id, entity: &Entity, - palette: Palette, + t: Tokens, cx: &App, ) -> Div { - let value = self.chat.builder_rename.read(cx).text().to_string(); + let value = self.chat.admin.builder_rename.read(cx).text().to_string(); let current = self .chat + .admin .builder_users .iter() .find(|account| account.user.id == user_id) .map_or("", |account| account.user.username.as_str()); let ready = !value.is_empty() && value != current; - div() - .h(px(size::ROW)) - .px(px(space::MD)) - .flex() - .items_center() - .gap(px(space::SM)) - .child( - div() - .flex_1() - .min_w_0() - .child(field(palette, &self.chat.builder_rename)), - ) - .when(ready, |row| { - row.child(parts::button( + form_row( + &self.chat.admin.builder_rename, + t, + ready.then(|| { + parts::button( format!("confirm_rename_{user_id}"), w().builder_users.confirm, Press::Plain, - palette.tokens, + t, entity_action(entity, |yumush, window, cx| { yumush.rename_builder_user(window, cx) }), - )) - }) + ) + .into_any_element() + }), + ) } pub(super) fn builder_password_row( &self, user_id: Id, entity: &Entity, - palette: Palette, + t: Tokens, cx: &App, ) -> Div { - let value = self.chat.builder_password.read(cx).text().to_string(); - let ready = !value.is_empty(); - div() - .h(px(size::ROW)) - .px(px(space::MD)) - .flex() - .items_center() - .gap(px(space::SM)) - .child( - div() - .flex_1() - .min_w_0() - .child(field(palette, &self.chat.builder_password)), - ) - .when(ready, |row| { - row.child(parts::button( + let ready = !self + .chat + .admin + .builder_password + .read(cx) + .text() + .to_string() + .is_empty(); + form_row( + &self.chat.admin.builder_password, + t, + ready.then(|| { + parts::button( format!("confirm_password_{user_id}"), w().builder_users.confirm, Press::Plain, - palette.tokens, + t, entity_action(entity, |yumush, window, cx| { yumush.reset_builder_password(window, cx) }), - )) - }) + ) + .into_any_element() + }), + ) } pub(super) fn builder_row( @@ -844,113 +852,29 @@ impl Yumush { account: &Account, me: &User, entity: &Entity, - palette: Palette, + t: Tokens, cx: &App, ) -> Div { let user = &account.user; - let is_self = user.id == me.id; - let manage = permission::can_manage_user(me.role, is_self, user.role); - let can_delete = !is_self && permission::can_delete_user(me.role, is_self, user.role); - let has_actions = manage || can_delete; - let suspended = account.suspended; - let timed_out = account - .suspended_until - .is_some_and(|until| until > now_ms()); + let id = user.id; + let manage = permission::can_manage_user(me.role, user.id == me.id, user.role); + let timed_out = matches!(account.suspension, Suspension::Until(until) if until > now_ms()); + let suspended = matches!(account.suspension, Suspension::Indefinite); let expanded_sessions = self .chat + .admin .builder_sessions .as_ref() - .filter(|(open, _)| *open == user.id) + .filter(|(open, _)| *open == id) .map(|(_, sessions)| sessions); - let expanded = expanded_sessions.is_some(); - let pending_delete = self.chat.pending_builder_delete == Some(user.id); - let pending_purge = self.chat.pending_builder_purge == Some(user.id); - let delete_id = user.id; - let suspend_id = user.id; - let sessions_id = user.id; - let password_id = user.id; - let profile_id = user.id; - let sessions_list_id = user.id; - let rename_id = user.id; - let timeout_id = user.id; - let ban_id = user.id; - let purge_id = user.id; let joined = millis_time(user.created_at, crate::lang::w().common.date); let seen = seen_text(account.last_seen); - let tone = palette.text; - let suspend_button = action_button( - format!("suspend_user_{}_{suspended}", user.id), - IconName::CirclePause, - if suspended { - w().builder_users.unsuspend - } else { - w().builder_users.suspend - }, - if suspended { - w().builder_users.allow_sign_in - } else { - w().builder_users.block_until_lifted - }, - tone, - palette, - entity_action(entity, move |yumush, window, cx| { - yumush.suspend_builder_user(suspend_id, !suspended, window, cx) - }), - ); - - let sessions_button = action_button( - format!("sessions_user_{}", user.id), - IconName::LogOut, - w().builder_users.sign_out, - w().builder_users.end_all_sessions, - tone, - palette, - entity_action(entity, move |yumush, window, cx| { - yumush.revoke_builder_sessions(sessions_id, window, cx) - }), - ); - - let stats_id = user.id; - let stats_open = self - .chat - .followed - .as_ref() - .filter(|(id, _)| *id == user.id) - .map(|(_, stats)| stats); - let stats_button = action_button( - format!("stats_user_{}", user.id), - IconName::Activity, - w().builder_users.stats, - w().builder_users.stats_tip, - if stats_open.is_some() { - palette.text - } else { - tone - }, - palette, - entity_action(entity, move |yumush, _, cx| { - yumush.toggle_builder_stats(stats_id, cx) - }), - ); - - let password_button = action_button( - format!("password_user_{}", user.id), - IconName::KeyRound, - w().builder_users.password, - w().builder_users.password_tip, - tone, - palette, - entity_action(entity, move |yumush, _, cx| { - yumush.toggle_builder_password(password_id, cx) - }), - ); - let toggle_button = clickable( - format!("sessions_list_user_{}", user.id), - palette, + format!("sessions_list_user_{id}"), + t, entity_action(entity, move |yumush, window, cx| { - yumush.toggle_builder_sessions(sessions_list_id, window, cx) + yumush.toggle_builder_sessions(id, window, cx) }), ) .tip(w().builder_users.manage) @@ -960,82 +884,10 @@ impl Yumush { .items_center() .justify_center() .rounded(px(radius::MD)) - .text_color(palette.muted) - .when(expanded, |this| this.bg(palette.hover)) + .text_color(t.dim()) + .when(expanded_sessions.is_some(), |this| this.bg(t.hov())) .child(Icon::new(IconName::Ellipsis).size(px(size::ICON))); - let rename_button = action_button( - format!("rename_user_{}", user.id), - IconName::Pencil, - w().builder_users.rename, - w().builder_users.rename_tip, - tone, - palette, - entity_action(entity, move |yumush, _, cx| { - yumush.toggle_builder_rename(rename_id, cx) - }), - ); - - let timeout_button = action_button( - format!("timeout_user_{}", user.id), - IconName::Timer, - w().builder_users.timeout, - w().builder_users.timeout_tip, - tone, - palette, - entity_action(entity, move |yumush, _, cx| { - yumush.toggle_builder_timeout(timeout_id, cx) - }), - ); - - let ban_button = action_button( - format!("ban_user_{}", user.id), - IconName::Ban, - w().builder_users.ban, - w().builder_users.ban_tip, - tone, - palette, - entity_action(entity, move |yumush, _, cx| { - yumush.toggle_builder_ban(ban_id, cx) - }), - ); - - let profile_button = action_button( - format!("profile_user_{}", user.id), - IconName::Eraser, - w().builder_users.clear_profile, - w().builder_users.clear_profile_tip, - palette.danger, - palette, - entity_action(entity, move |yumush, window, cx| { - yumush.clear_builder_profile(profile_id, window, cx) - }), - ); - - let purge_button = confirm_button( - format!("purge_user_{}", user.id), - IconName::MessageSquareX, - w().builder_users.purge, - w().builder_users.purge_tip, - pending_purge, - palette, - entity_action(entity, move |yumush, window, cx| { - yumush.purge_builder_user(purge_id, window, cx) - }), - ); - - let delete_button = confirm_button( - format!("delete_user_{}", user.id), - IconName::UserX, - w().builder_users.delete, - w().builder_users.delete_tip, - pending_delete, - palette, - entity_action(entity, move |yumush, window, cx| { - yumush.delete_builder_user(delete_id, window, cx) - }), - ); - let row = div() .px(px(space::LG)) .py(px(space::MD)) @@ -1043,15 +895,15 @@ impl Yumush { .items_center() .gap(px(space::MD)) .child(user_link( - format!("builder_user_avatar_{}", user.id), + format!("builder_user_avatar_{id}"), Some(user), entity, avatar( - palette, + t, user, px(size::AVATAR), text(text::CAPTION), - &self.chat.avatars, + &self.chat.session.avatars, ), )) .child( @@ -1068,43 +920,27 @@ impl Yumush { .items_center() .gap(px(space::SM)) .child(user_link( - format!("builder_user_name_{}", user.id), + format!("builder_user_name_{id}"), Some(user), entity, div() .truncate() .text_size(text(text::LABEL)) .font_weight(FontWeight::MEDIUM) - .text_color(palette.text) + .text_color(t.paper()) .child(user.username.clone()), )) .when(user.role == Role::Builder, |this| { - this.child(status( - w().builder_users.tag_builder, - palette.accent, - palette, - )) + this.child(status(w().builder_users.tag_builder, t.paper())) }) .when(suspended, |this| { - this.child(status( - w().builder_users.tag_suspended, - palette.danger, - palette, - )) + this.child(status(w().builder_users.tag_suspended, t.bad())) }) .when(timed_out, |this| { - this.child(status( - w().builder_users.tag_timed_out, - palette.danger, - palette, - )) + this.child(status(w().builder_users.tag_timed_out, t.bad())) }) .when(account.ghost, |this| { - this.child(status( - w().builder_users.tag_ghost, - palette.muted, - palette, - )) + this.child(status(w().builder_users.tag_ghost, t.dim())) }), ) .child( @@ -1112,111 +948,248 @@ impl Yumush { .min_w_0() .truncate() .text_size(text(text::CAPTION)) - .text_color(palette.muted) + .text_color(t.dim()) .child(w().builder_users.joined_seen(joined, seen)), ), ) - .children(has_actions.then_some(toggle_button)); + .children(manage.then_some(toggle_button)); - let panel = expanded_sessions.map(|sessions| { - let open_id = user.id; - let password_open = self.chat.pending_builder_password == Some(open_id); - let rename_open = self.chat.pending_builder_rename == Some(open_id); - let timeout_open = self.chat.pending_builder_timeout == Some(open_id); - let ban_open = self.chat.pending_builder_ban == Some(open_id); + let panel = expanded_sessions + .map(|sessions| self.builder_panel(account, sessions, manage, entity, t, cx)); - let account_actions = [ - manage.then(|| rename_button.into_any_element()), - manage.then(|| password_button.into_any_element()), - Some(stats_button.into_any_element()), - ]; - let moderation_actions = [ - manage.then(|| timeout_button.into_any_element()), - manage.then(|| suspend_button.into_any_element()), - manage.then(|| ban_button.into_any_element()), - manage.then(|| sessions_button.into_any_element()), - ]; - let danger_actions = [ - manage.then(|| profile_button.into_any_element()), - manage.then(|| purge_button.into_any_element()), - can_delete.then(|| delete_button.into_any_element()), - ]; - let sessions: Vec = sessions - .iter() - .map(|session| { - self.builder_session_row(user.id, session, entity, palette) - .into_any_element() - }) - .collect(); - let clients: Vec = if self.chat.builder_clients.is_empty() { - vec![caption_text(w().builder_users.no_clients, palette.muted).into_any_element()] + div().flex().flex_col().child(row).children(panel) + } + + fn builder_panel( + &self, + account: &Account, + sessions: &[SessionInfo], + manage: bool, + entity: &Entity, + t: Tokens, + cx: &App, + ) -> Div { + let user = &account.user; + let id = user.id; + let suspended = matches!(account.suspension, Suspension::Indefinite); + let manage_only = |button: AnyElement| manage.then_some(button); + + let rename = action_button( + format!("rename_user_{id}"), + IconName::Pencil, + w().builder_users.rename, + w().builder_users.rename_tip, + t.paper(), + t, + entity_action(entity, move |yumush, _, cx| { + yumush.toggle_user_edit(id, UserEdit::Rename, cx) + }), + ); + let password = action_button( + format!("password_user_{id}"), + IconName::KeyRound, + w().builder_users.password, + w().builder_users.password_tip, + t.paper(), + t, + entity_action(entity, move |yumush, _, cx| { + yumush.toggle_user_edit(id, UserEdit::Password, cx) + }), + ); + let stats = action_button( + format!("stats_user_{id}"), + IconName::Activity, + w().builder_users.stats, + w().builder_users.stats_tip, + t.paper(), + t, + entity_action(entity, move |yumush, _, cx| { + yumush.toggle_builder_stats(id, cx) + }), + ); + let timeout = action_button( + format!("timeout_user_{id}"), + IconName::Timer, + w().builder_users.timeout, + w().builder_users.timeout_tip, + t.paper(), + t, + entity_action(entity, move |yumush, _, cx| { + yumush.toggle_user_edit(id, UserEdit::Timeout, cx) + }), + ); + let suspend = action_button( + format!("suspend_user_{id}_{suspended}"), + IconName::CirclePause, + if suspended { + w().builder_users.unsuspend + } else { + w().builder_users.suspend + }, + if suspended { + w().builder_users.allow_sign_in } else { - self.chat - .builder_clients - .iter() - .map(|client| self.builder_client_row(client, palette).into_any_element()) - .collect() - }; + w().builder_users.block_until_lifted + }, + t.paper(), + t, + entity_action(entity, move |yumush, window, cx| { + yumush.suspend_builder_user(id, !suspended, window, cx) + }), + ); + let sign_out = action_button( + format!("sessions_user_{id}"), + IconName::LogOut, + w().builder_users.sign_out, + w().builder_users.end_all_sessions, + t.paper(), + t, + entity_action(entity, move |yumush, window, cx| { + yumush.revoke_builder_sessions(id, window, cx) + }), + ); + let ban = action_button( + format!("ban_user_{id}"), + IconName::Ban, + w().builder_users.ban, + w().builder_users.ban_tip, + t.paper(), + t, + entity_action(entity, move |yumush, _, cx| { + yumush.toggle_user_edit(id, UserEdit::Ban, cx) + }), + ); + let profile = action_button( + format!("profile_user_{id}"), + IconName::Eraser, + w().builder_users.clear_profile, + w().builder_users.clear_profile_tip, + t.bad(), + t, + entity_action(entity, move |yumush, window, cx| { + yumush.clear_builder_profile(id, window, cx) + }), + ); + let purge = confirm_button( + format!("purge_user_{id}"), + IconName::MessageSquareX, + w().builder_users.purge, + w().builder_users.purge_tip, + self.armed(Armed::PurgeUser(id)), + t, + entity_action(entity, move |yumush, window, cx| { + yumush.purge_builder_user(id, window, cx) + }), + ); + let delete = confirm_button( + format!("delete_user_{id}"), + IconName::UserX, + w().builder_users.delete, + w().builder_users.delete_tip, + self.armed(Armed::BuilderDeleteUser(id)), + t, + entity_action(entity, move |yumush, window, cx| { + yumush.delete_builder_user(id, window, cx) + }), + ); - div() - .flex() - .flex_col() - .gap(px(space::SM)) - .ml(px(space::MD)) - .mb(px(space::MD)) - .pl(px(space::XL)) - .py(px(space::SM)) - .border_l(px(crate::gui::style::stroke::LINE)) - .border_color(palette.tokens.person(user.id)) - .children(action_group( - w().builder_users.group_account, - palette, - account_actions.into_iter().flatten().collect(), - )) - .children( - password_open.then(|| self.builder_password_row(user.id, entity, palette, cx)), - ) - .children( - rename_open.then(|| self.builder_rename_row(user.id, entity, palette, cx)), - ) - .children(action_group( - w().builder_users.group_moderation, - palette, - moderation_actions.into_iter().flatten().collect(), - )) - .children(timeout_open.then(|| self.builder_timeout_row(user.id, entity, palette))) - .children(ban_open.then(|| self.builder_ban_row(user.id, entity, palette))) - .children(action_group( - w().builder_users.group_danger, - palette, - danger_actions.into_iter().flatten().collect(), - )) - .children(action_group( - w().builder_users.group_sessions, - palette, - sessions, - )) - .children(action_group( - w().builder_users.group_clients, - palette, - clients, - )) - .children(action_group( - w().builder_users.group_friends, - palette, - self.builder_friend_list(palette), - )) - .children(stats_open.map(|stats| { - super::super::voice_stats::stats_panel( - stats, - &|id| self.chat.name_of(id), - super::super::voice_stats::Detail::Full, - palette, - ) - .pt(px(space::MD)) - })) - }); + let account_actions = [ + manage_only(rename.into_any_element()), + manage_only(password.into_any_element()), + Some(stats.into_any_element()), + ]; + let moderation_actions = [ + manage_only(timeout.into_any_element()), + manage_only(suspend.into_any_element()), + manage_only(ban.into_any_element()), + manage_only(sign_out.into_any_element()), + ]; + let danger_actions = [ + manage_only(profile.into_any_element()), + manage_only(purge.into_any_element()), + manage_only(delete.into_any_element()), + ]; + let sessions: Vec = sessions + .iter() + .map(|session| { + self.builder_session_row(id, session, entity, t) + .into_any_element() + }) + .collect(); + let clients: Vec = if self.chat.admin.builder_clients.is_empty() { + vec![caption_text(w().builder_users.no_clients, t.dim()).into_any_element()] + } else { + self.chat + .admin + .builder_clients + .iter() + .map(|client| self.builder_client_row(client, t).into_any_element()) + .collect() + }; + let stats_open = self + .chat + .session + .followed + .as_ref() + .filter(|(followed, _)| *followed == id) + .map(|(_, stats)| stats); - div().flex().flex_col().child(row).children(panel) + div() + .flex() + .flex_col() + .gap(px(space::SM)) + .ml(px(space::MD)) + .mb(px(space::MD)) + .pl(px(space::XL)) + .py(px(space::SM)) + .border_l(px(crate::gui::style::stroke::LINE)) + .border_color(t.person(id)) + .children(action_group( + w().builder_users.group_account, + t, + account_actions.into_iter().flatten().collect(), + )) + .children( + self.edit_open(id, UserEdit::Password) + .then(|| self.builder_password_row(id, entity, t, cx)), + ) + .children( + self.edit_open(id, UserEdit::Rename) + .then(|| self.builder_rename_row(id, entity, t, cx)), + ) + .children(action_group( + w().builder_users.group_moderation, + t, + moderation_actions.into_iter().flatten().collect(), + )) + .children( + self.edit_open(id, UserEdit::Timeout) + .then(|| self.builder_timeout_row(id, entity, t)), + ) + .children( + self.edit_open(id, UserEdit::Ban) + .then(|| self.builder_ban_row(id, entity, t)), + ) + .children(action_group( + w().builder_users.group_danger, + t, + danger_actions.into_iter().flatten().collect(), + )) + .children(action_group(w().builder_users.group_sessions, t, sessions)) + .children(action_group(w().builder_users.group_clients, t, clients)) + .children(action_group( + w().builder_users.group_friends, + t, + vec![self.builder_friend_list(t)], + )) + .children(stats_open.map(|stats| { + crate::gui::voice_stats::stats_panel( + stats, + &|id| self.chat.name_of(id), + crate::gui::voice_stats::Detail::Full, + t, + ) + .pt(px(space::MD)) + })) } } diff --git a/crates/client/src/gui/builder/voice.rs b/crates/client/src/gui/builder/voice.rs index c00ce81..302e14f 100644 --- a/crates/client/src/gui/builder/voice.rs +++ b/crates/client/src/gui/builder/voice.rs @@ -3,7 +3,7 @@ use std::future::Future; use common::{ call::{KickFromVoice, ListVoiceRooms, ServerMute}, - model::{User, VoiceRoom}, + model::{Hue, User, VoiceRoom}, }; use gpui_kit::{ AnyElement, Context, Div, Entity, IntoElement, ParentElement, Styled, Window, assets::IconName, @@ -13,9 +13,9 @@ use gpui_kit::{ use super::ui::{card, card_header, icon_button, list_card, list_row, pill, rows_body}; use crate::{ gui::{ - Palette, Yumush, avatar, entity_action, notify_error, + Yumush, avatar, entity_action, notify_error, profile::user_link, - style::{self, size, space}, + style::{self, Tokens, size, space}, text, }, lang::w, @@ -29,13 +29,13 @@ impl Yumush { cx, |network| async move { network.call(ListVoiceRooms).await }, |yumush, rooms, cx| { - yumush.chat.builder_voice_rooms = rooms; + yumush.chat.admin.builder_voice_rooms = rooms; cx.notify(); }, ); } - pub(super) fn voice_action( + fn voice_action( &mut self, window: &mut Window, cx: &mut Context, @@ -55,7 +55,7 @@ impl Yumush { .detach(); } - pub(super) fn set_server_mute( + fn set_server_mute( &mut self, user_id: Id, muted: bool, @@ -67,61 +67,53 @@ impl Yumush { }); } - pub(super) fn kick_from_voice( - &mut self, - user_id: Id, - window: &mut Window, - cx: &mut Context, - ) { + fn kick_from_voice(&mut self, user_id: Id, window: &mut Window, cx: &mut Context) { self.voice_action(window, cx, move |network| async move { network.call(KickFromVoice { user_id }).await }); } - pub(super) fn voice_body(&self, entity: &Entity, palette: Palette) -> Vec { + pub(super) fn voice_body(&self, entity: &Entity, t: Tokens) -> Vec { let mut body = Vec::new(); - if self.chat.builder_voice_rooms.is_empty() { + if self.chat.admin.builder_voice_rooms.is_empty() { body.push( - list_card(None, Vec::new(), w().builder_voice.no_rooms, palette).into_any_element(), + list_card(None, Vec::new(), w().builder_voice.no_rooms, t).into_any_element(), ); } - body.extend(self.chat.builder_voice_rooms.iter().map(|room| { - self.voice_room_card(room, entity, palette) - .into_any_element() - })); + body.extend( + self.chat + .admin + .builder_voice_rooms + .iter() + .map(|room| self.voice_room_card(room, entity, t).into_any_element()), + ); body } - pub(super) fn voice_room_card( - &self, - room: &VoiceRoom, - entity: &Entity, - palette: Palette, - ) -> Div { + fn voice_room_card(&self, room: &VoiceRoom, entity: &Entity, t: Tokens) -> Div { let id = room.community_id; let voice = self .chat + .admin .builder_communities .iter() .find(|summary| summary.community.id == id) .map(|summary| summary.community.voice_enabled); let joined = self.chat.in_voice(id); - let join_id = id; - let mut actions = - vec![pill(&room.users.len().to_string(), palette.muted, palette).into_any_element()]; + let mut actions = vec![pill(&room.users.len().to_string(), t.dim()).into_any_element()]; if !joined { actions.push( icon_button( format!("room_join_{id}"), IconName::Headphones, w().builder_voice.join, - palette.ok, - palette, + t.hue(Hue::Mint), + t, entity_action(entity, move |yumush, window, cx| { - yumush.jump_to(join_id, true, window, cx) + yumush.jump_to(id, true, window, cx) }), ) .into_any_element(), @@ -141,10 +133,10 @@ impl Yumush { } else { w().builder_voice.voice_off }, - palette.muted, - palette, + t.dim(), + t, entity_action(entity, move |yumush, window, cx| { - yumush.set_builder_community_voice(id, !enabled, window, cx) + yumush.set_community_voice(id, !enabled, window, cx) }), ) .into_any_element(), @@ -160,27 +152,25 @@ impl Yumush { room.muted.contains(&user.id), room.ghosts.contains(&user.id), entity, - palette, + t, ) }) .collect(); - card(palette) - .child(card_header(&room.community, actions, palette)) - .child(rows_body(rows, w().common.no_users, palette)) + card() + .child(card_header(&room.community, actions, t)) + .child(rows_body(rows, w().common.no_users, t)) } - pub(super) fn voice_user_row( + fn voice_user_row( &self, user: &User, muted: bool, ghost: bool, entity: &Entity, - palette: Palette, + t: Tokens, ) -> Div { let id = user.id; - let mute_id = id; - let kick_id = id; list_row() .px(px(space::LG)) @@ -194,24 +184,24 @@ impl Yumush { .items_center() .gap(px(space::MD)) .child(avatar( - palette, + t, user, px(size::AVATAR), text(style::text::CAPTION), - &self.chat.avatars, + &self.chat.session.avatars, )) .child( div() .min_w_0() .truncate() .text_size(text(style::text::LABEL)) - .text_color(palette.text) + .text_color(t.paper()) .child(user.username.clone()), ), )), ) - .children(muted.then(|| pill(w().builder_voice.muted, palette.danger, palette))) - .children(ghost.then(|| pill(w().builder_voice.ghost, palette.muted, palette))) + .children(muted.then(|| pill(w().builder_voice.muted, t.bad()))) + .children(ghost.then(|| pill(w().builder_voice.ghost, t.dim()))) .child(icon_button( format!("voice_mute_{id}_{muted}"), if muted { @@ -224,20 +214,20 @@ impl Yumush { } else { w().builder_voice.mute }, - palette.muted, - palette, + t.dim(), + t, entity_action(entity, move |yumush, window, cx| { - yumush.set_server_mute(mute_id, !muted, window, cx) + yumush.set_server_mute(id, !muted, window, cx) }), )) .child(icon_button( format!("voice_kick_{id}"), IconName::UserX, w().builder_voice.kick, - palette.danger, - palette, + t.bad(), + t, entity_action(entity, move |yumush, window, cx| { - yumush.kick_from_voice(kick_id, window, cx) + yumush.kick_from_voice(id, window, cx) }), )) } diff --git a/crates/client/src/gui/call_bar.rs b/crates/client/src/gui/call_bar.rs index b991839..2732178 100644 --- a/crates/client/src/gui/call_bar.rs +++ b/crates/client/src/gui/call_bar.rs @@ -1,5 +1,5 @@ use gpui_kit::prelude::FluentBuilder as _; -use std::{collections::VecDeque, rc::Rc}; +use std::collections::VecDeque; use gpui_kit::{ AnyElement, App, Div, FontWeight, InteractiveElement, ParentElement, SharedString, @@ -13,7 +13,7 @@ use super::{ }; use crate::lang::w; -pub type Action = Rc; +pub type Action = Box; pub struct CallBar { pub place: SharedString, @@ -24,7 +24,6 @@ pub struct CallBar { pub muted: bool, pub deafened: bool, pub camera: bool, - pub screen: bool, pub share: Option<(Option>, gpui_kit::Hsla)>, pub stats: bool, pub ghost: bool, @@ -44,11 +43,6 @@ pub struct CallActions { pub screen_more: AnyElement, } -fn run(action: &Action) -> impl Fn(&mut Window, &mut App) + 'static { - let action = action.clone(); - move |window, cx| action(window, cx) -} - pub fn view(bar: CallBar, actions: CallActions, t: Tokens) -> Div { let tone = |on: bool| if on { Tone::On } else { Tone::Idle }; let alarm = |on: bool| if on { Tone::Danger } else { Tone::Idle }; @@ -68,7 +62,7 @@ pub fn view(bar: CallBar, actions: CallActions, t: Tokens) -> Div { .pings .last() .map_or_else(|| "–".to_string(), |ping| format!("{ping:.0} ms")); - let stats = run(&actions.stats); + let screen = bar.share.is_some(); let controls = band(space::XS) .flex_none() .child(icon_button( @@ -86,7 +80,7 @@ pub fn view(bar: CallBar, actions: CallActions, t: Tokens) -> Div { alarm(bar.muted), Scale::Normal, t, - run(&actions.mute), + actions.mute, )) .child(actions.mic_more) .child(icon_button( @@ -104,7 +98,7 @@ pub fn view(bar: CallBar, actions: CallActions, t: Tokens) -> Div { alarm(bar.deafened), Scale::Normal, t, - run(&actions.deafen), + actions.deafen, )) .child(actions.speaker_more) .when(!bar.ghost, |row| { @@ -119,21 +113,21 @@ pub fn view(bar: CallBar, actions: CallActions, t: Tokens) -> Div { tone(bar.camera), Scale::Normal, t, - run(&actions.camera), + actions.camera, )) .child(actions.camera_more) .child(icon_button( - format!("bar_screen_{}", bar.screen), + format!("bar_screen_{screen}"), IconName::ScreenShare, - if bar.screen { + if screen { w().call_bar.stop_sharing } else { w().call_bar.share_screen }, - tone(bar.screen), + tone(screen), Scale::Normal, t, - run(&actions.screen), + actions.screen, )) .child(actions.screen_more) }) @@ -144,7 +138,7 @@ pub fn view(bar: CallBar, actions: CallActions, t: Tokens) -> Div { Tone::Danger, Scale::Normal, t, - run(&actions.leave), + actions.leave, )); div().flex_none().child(thread(t)).child( band(space::LG) @@ -165,10 +159,7 @@ pub fn view(bar: CallBar, actions: CallActions, t: Tokens) -> Div { }) .cursor_pointer() .tip(w().call_bar.go_to_call) - .on_click({ - let go = run(&actions.go); - move |_, window, cx| go(window, cx) - }) + .on_click(move |_, window, cx| (actions.go)(window, cx)) .child(super::parts::small_icon(IconName::Phone).text_color(t.dim())) .child( words(bar.place, Text::Ui, Ink::Paper, t) @@ -202,7 +193,7 @@ pub fn view(bar: CallBar, actions: CallActions, t: Tokens) -> Div { }) .cursor_pointer() .tip(w().call_bar.connection_stats) - .on_click(move |_, window, cx| stats(window, cx)) + .on_click(move |_, window, cx| (actions.stats)(window, cx)) .child( div() .w(px(size::ROW)) diff --git a/crates/client/src/gui/camera_view.rs b/crates/client/src/gui/camera_view.rs index aed1d55..866a89e 100644 --- a/crates/client/src/gui/camera_view.rs +++ b/crates/client/src/gui/camera_view.rs @@ -1,25 +1,25 @@ +use std::collections::VecDeque; use std::time::{Duration, Instant}; use common::model::Id; - use common::share::{Fps, Kind, Quality, Resolution}; use gpui_kit::{ AnyElement, AppContext as _, Context, Div, Entity, InteractiveElement, IntoElement, ParentElement, StatefulInteractiveElement, Styled, Task, Window, assets::IconName, div, prelude::FluentBuilder as _, px, }; +use std::sync::atomic::{AtomicBool, Ordering}; use super::{ - Palette, Tooltip as _, Yumush, + Tooltip as _, Yumush, media_view::into_render_image, notify_error, parts::{Ink, Text, Voice, caption, scrim, voice_line, words}, - style::{radius, size, space}, + style::{Tokens, radius, size, space}, surface::Surface, - widget::spawn_warn, }; use crate::lang::w; -use crate::share::session::WatchQuality; +use crate::share::watch::WatchQuality; const SLOTS: usize = 6; const IDLE_TICK: Duration = Duration::from_millis(250); @@ -27,11 +27,12 @@ const FRAME_TICK: Duration = Duration::from_millis(16); const PUMP_STALL: Duration = Duration::from_millis(50); const TILE_W: f32 = size::THUMB * 1.5; const TILE_H: f32 = TILE_W * 9. / 16.; - -pub(super) const TILE_QUALITY: WatchQuality = WatchQuality::Fixed(Quality { +const TILE_QUALITY: WatchQuality = WatchQuality::Fixed(Quality { resolution: Resolution::P360, fps: Fps::F15, }); +const WIDE: f32 = 16. / 9.; +const GRID_GAP: f32 = super::style::stroke::LINE; #[derive(Clone, Copy, PartialEq, Eq)] pub(super) enum Stage { @@ -40,29 +41,81 @@ pub(super) enum Stage { Hidden, } -pub(super) fn tile_quality(stage: Stage) -> WatchQuality { - match stage { - Stage::Grid => WatchQuality::Auto, - Stage::Strip | Stage::Hidden => TILE_QUALITY, +impl Stage { + pub(super) fn quality(self) -> WatchQuality { + match self { + Stage::Grid => WatchQuality::Auto, + Stage::Strip | Stage::Hidden => TILE_QUALITY, + } + } + + fn cover(self) -> bool { + self != Stage::Grid } } pub(super) struct Tile { pub(super) shown: bool, + pub(super) live: bool, pub(super) surface: Entity, } -fn tile_cover(stage: Stage) -> bool { - stage != Stage::Grid -} - impl Yumush { fn tile_sources(&self) -> Vec<(Id, Kind)> { - let shown = self.chat.stage != Stage::Hidden; + if self.chat.stage == Stage::Hidden { + return Vec::new(); + } self.stage_sources() - .into_iter() - .filter(|(_, kind)| shown || *kind == Kind::Camera) - .collect() + } + + fn watch_quality(&self, source: (Id, Kind)) -> WatchQuality { + if self.viewing() == Some(source) { + WatchQuality::Auto + } else { + self.chat.stage.quality() + } + } + + fn watch_tile(&self, source: (Id, Kind), cx: &mut Context) { + let (user_id, kind) = source; + let network = self.network.clone(); + let quality = self.chat.stage.quality(); + let volume = self.settings.share.volume; + let choice = self.settings.voice.choice.clone(); + let top = self.share_top(user_id, kind); + cx.spawn(async move |this, cx| { + let watched = network + .watch_share(user_id, kind, quality, top, volume, choice) + .await; + let live = watched.is_ok(); + if let Err(error) = &watched { + tracing::warn!("tile watch failed: {error}"); + } + let orphaned = this.update(cx, |yumush, _| { + let Some(tile) = yumush.chat.session.tiles.get_mut(&source) else { + return live && yumush.viewing() != Some(source); + }; + tile.live = live; + if live { + yumush + .network + .set_watch_quality(user_id, kind, yumush.watch_quality(source)); + } + false + }); + if let Ok(true) = orphaned { + let _ = network.unwatch_share(user_id, kind).await; + } + }) + .detach(); + } + + pub(super) fn unwatch_tile(&self, (user_id, kind): (Id, Kind), cx: &mut Context) { + let network = self.network.clone(); + cx.spawn(async move |_, _| { + let _ = network.unwatch_share(user_id, kind).await; + }) + .detach(); } pub(super) fn tick_tiles( @@ -72,70 +125,59 @@ impl Yumush { ) -> bool { let wanted = self.tile_sources(); let viewing = self.viewing(); - let quality = tile_quality(self.chat.stage); let mut changed = false; for &source in &wanted { - if self.chat.tiles.contains_key(&source) { + if self.chat.session.tiles.contains_key(&source) { continue; } - let cover = tile_cover(self.chat.stage); let network = self.network.clone(); + let cover = self.chat.stage.cover(); let surface = cx.new(|cx| Surface::new(cover, network, source, cx)); - self.chat.tiles.insert( + let live = viewing == Some(source); + self.chat.session.tiles.insert( source, Tile { shown: false, + live, surface, }, ); changed = true; - if viewing == Some(source) { - continue; + if !live { + self.watch_tile(source, cx); } - let (user_id, kind) = source; - let network = self.network.clone(); - let volume = self.settings.share.volume; - let choice = self.settings.voice.choice.clone(); - let top = self.share_top(user_id, kind); - spawn_warn(cx, "tile watch", async move { - network - .watch_share(user_id, kind, quality, top, volume, choice) - .await - }); } let gone: Vec<(Id, Kind)> = self .chat + .session .tiles .keys() .filter(|source| !wanted.contains(source)) .copied() .collect(); for source in gone { - if let Some(tile) = self.chat.tiles.remove(&source) - && let Some(frame) = tile - .surface - .update(cx, |surface, cx| surface.replace(None, cx)) + let Some(tile) = self.chat.session.tiles.remove(&source) else { + continue; + }; + if let Some(frame) = tile + .surface + .update(cx, |surface, cx| surface.replace(None, cx)) { cx.drop_image(frame, window.as_deref_mut()); } - if viewing != Some(source) { - let network = self.network.clone(); - let (user_id, kind) = source; - cx.spawn(async move |_, _| { - let _ = network.unwatch_share(user_id, kind).await; - }) - .detach(); + if tile.live && viewing != Some(source) { + self.unwatch_tile(source, cx); } changed = true; } - for (&(user_id, kind), tile) in self.chat.tiles.iter_mut() { - if viewing == Some((user_id, kind)) { + for (&source, tile) in self.chat.session.tiles.iter_mut() { + if viewing == Some(source) { continue; } - let Some(frame) = self.network.share_frame(user_id, kind) else { + let Some(frame) = self.network.share_frame(source.0, source.1) else { continue; }; let next = into_render_image(frame); @@ -152,42 +194,48 @@ impl Yumush { if changed { cx.notify(); } - !self.chat.tiles.is_empty() + !self.chat.session.tiles.is_empty() } pub(super) fn set_stage(&mut self, stage: Stage, cx: &mut Context) { self.chat.stage = stage; - let viewing = self.viewing(); - let quality = tile_quality(stage); - for (&(user_id, kind), tile) in &self.chat.tiles { - if viewing != Some((user_id, kind)) { - self.network.set_watch_quality(user_id, kind, quality); - } + for (&source, tile) in &self.chat.session.tiles { + self.network + .set_watch_quality(source.0, source.1, self.watch_quality(source)); tile.surface - .update(cx, |surface, cx| surface.set_cover(tile_cover(stage), cx)); + .update(cx, |surface, cx| surface.set_cover(stage.cover(), cx)); } cx.notify(); } pub(super) fn toggle_camera(&mut self, window: &mut Window, cx: &mut Context) { + if CAMERA_BUSY.load(Ordering::Relaxed) { + return; + } + CAMERA_BUSY.store(true, Ordering::Relaxed); let network = self.network.clone(); - let on = network.camera_on(); + let on = network.share_source(Kind::Camera).is_some(); let settings = self.settings.share.clone(); + let device = settings.camera_device.clone(); cx.spawn_in(window, async move |this, cx| { - if on { - let _ = network.stop_camera().await; - } else if let Err(error) = network.start_camera(&settings).await { + let started = if on { + let _ = network.stop(Kind::Camera).await; + Ok(()) + } else { + network.start(Kind::Camera, &settings, None).await + }; + if let Err(error) = started { notify_error(&this, cx, error); } - let _ = this.update(cx, |_, cx| cx.notify()); + let _ = this.update(cx, |yumush, cx| yumush.settle_camera(device, cx)); }) .detach(); } pub(super) fn in_stage_chat(&self) -> bool { self.chat.voice_community().is_some() - && self.chat.selected_community_id == self.chat.voice_community() + && self.chat.session.selected_community_id == self.chat.voice_community() } pub(super) fn stage_sources(&self) -> Vec<(Id, Kind)> { @@ -196,6 +244,7 @@ impl Yumush { }; let mut shares: Vec<&common::share::Share> = self .chat + .session .shares .get(&community_id) .into_iter() @@ -208,21 +257,17 @@ impl Yumush { .collect() } - pub(super) fn stage_strip( - &self, - entity: &Entity, - palette: Palette, - ) -> Option { - let shown = match self.chat.stage { + pub(super) fn stage_strip(&self, entity: &Entity, t: Tokens) -> Option { + let visible = match self.chat.stage { Stage::Strip => true, - Stage::Grid => self.chat.viewer.is_some(), + Stage::Grid => self.chat.session.viewer.is_some(), Stage::Hidden => false, }; - if !shown || !self.in_stage_chat() { + if !visible || !self.in_stage_chat() { return None; } let sources = self.stage_sources(); - let (shown, more) = strip_slots(self.chat.strip_size.0, sources.len()); + let (count, more) = strip_slots(self.chat.strip_size.0, sources.len()); (!sources.is_empty()).then(|| { div() .id("stage_strip") @@ -237,15 +282,15 @@ impl Yumush { .children( sources .into_iter() - .take(shown) - .map(|source| stage_tile(entity, self, palette, source).into_any_element()), + .take(count) + .map(|source| stage_tile(entity, self, t, source).into_any_element()), ) - .children((more > 0).then(|| more_tile(entity, more, palette).into_any_element())) + .children((more > 0).then(|| more_tile(entity, more, t).into_any_element())) }) } fn slots(&self, ids: &[Id]) -> (Vec, usize) { - let speaking = |id: &Id| self.chat.waves.audible(*id); + let speaking = |id: &Id| self.chat.session.waves.audible(*id); let mut shown: Vec = ids .iter() .filter(|id| speaking(id)) @@ -263,14 +308,25 @@ impl Yumush { (shown, more) } - fn voice_captions(&self, ids: &[Id], palette: Palette) -> Vec
{ - let t = palette.tokens; + fn voice_captions(&self, ids: &[Id], t: Tokens) -> Vec
{ let (shown, more) = self.slots(ids); shown .into_iter() .filter_map(|id| self.chat.author(id)) .map(|user| { - let voice = if self.chat.waves.speaking.contains(&user.id) { + let bands = self + .chat + .session + .waves + .voice(user.id) + .map(|bands| bands.iter().copied().collect::>()); + let share = self + .chat + .session + .waves + .share(user.id) + .map(|bands| bands.iter().copied().collect::>()); + let voice = if self.chat.session.waves.speaking.contains(&user.id) { Voice::Live(t.person(user.id)) } else { Voice::Quiet @@ -284,17 +340,15 @@ impl Yumush { .is_some(); caption( user.username.clone(), - voice_line(self.chat.waves.voice(user.id), voice, t), + voice_line(bands.as_ref(), voice, t), t, ) .h(px(size::CONTROL_SM)) - .children(screen.then(|| { - super::call_bar::share_meter( - self.chat.waves.share(user.id), - t.person(user.id), - t, - ) - })) + .children( + screen.then(|| { + super::call_bar::share_meter(share.as_ref(), t.person(user.id), t) + }), + ) }) .chain( (more > 0) @@ -303,7 +357,7 @@ impl Yumush { .collect() } - pub(super) fn voice_band(&self, palette: Palette) -> Div { + pub(super) fn voice_band(&self, t: Tokens) -> Div { let ids = self .chat .voice_community() @@ -316,7 +370,7 @@ impl Yumush { .px(px(space::XL)) .py(px(space::LG)) .children( - self.voice_captions(&ids, palette) + self.voice_captions(&ids, t) .into_iter() .map(|caption| caption.flex_1().min_w_0()), ) @@ -325,20 +379,20 @@ impl Yumush { pub(super) fn stage_grid( &self, entity: &Entity, - palette: Palette, + t: Tokens, cx: &gpui_kit::App, ) -> Option { if self.chat.stage != Stage::Grid || !self.in_stage_chat() || self .chat + .session .viewer .as_ref() .is_some_and(|viewer| !viewer.fullscreen) { return None; } - self.chat.voice_community()?; let sources = self.stage_sources(); if sources.is_empty() { return None; @@ -347,6 +401,7 @@ impl Yumush { .iter() .map(|source| { self.chat + .session .tiles .get(source) .map_or(WIDE, |tile| tile.surface.read(cx).aspect()) @@ -357,9 +412,9 @@ impl Yumush { let (cell_w, cell_h) = cell_size(sources.len(), columns, size); let mut cells = sources.into_iter().zip(aspects).map(|(source, aspect)| { let width = cell_w.min(cell_h * aspect); - grid_cell(entity, self, palette, source, (width, width / aspect)) + grid_cell(entity, self, t, source, (width, width / aspect)) }); - let rows = (0..sources_rows(columns, cells.len())) + let rows = (0..row_count(columns, cells.len())) .map(|_| { div() .flex() @@ -369,7 +424,6 @@ impl Yumush { .children(cells.by_ref().take(columns).collect::>()) }) .collect::>(); - let measure = entity.clone(); Some( div() @@ -380,7 +434,7 @@ impl Yumush { .flex_col() .justify_center() .gap(px(GRID_GAP)) - .child(probe(measure, |yumush| &mut yumush.chat.grid_size)) + .child(probe(entity.clone(), |yumush| &mut yumush.chat.grid_size)) .children(rows), ) } @@ -415,15 +469,12 @@ fn strip_slots(width: f32, count: usize) -> (usize, usize) { } } -const WIDE: f32 = 16. / 9.; -const GRID_GAP: f32 = super::style::stroke::LINE; - -fn sources_rows(columns: usize, count: usize) -> usize { +fn row_count(columns: usize, count: usize) -> usize { count.div_ceil(columns.max(1)) } fn cell_size(count: usize, columns: usize, (width, height): (f32, f32)) -> (f32, f32) { - let rows = sources_rows(columns, count); + let rows = row_count(columns, count); ( (width - GRID_GAP * (columns - 1) as f32) / columns as f32, (height - GRID_GAP * (rows - 1) as f32) / rows as f32, @@ -464,7 +515,9 @@ pub(super) fn ticker(cx: &mut Context) -> Task<()> { impl Yumush { fn streaming(&self) -> bool { - self.chat.viewer.is_some() || !self.chat.tiles.is_empty() || self.media_playing() + self.chat.session.viewer.is_some() + || !self.chat.session.tiles.is_empty() + || self.media_playing() } fn pump(&mut self, window: &mut Window, cx: &mut Context) { @@ -496,21 +549,25 @@ impl Yumush { } } +fn tile_surface(yumush: &Yumush, source: (Id, Kind)) -> Option> { + yumush + .chat + .session + .tiles + .get(&source) + .filter(|tile| tile.shown) + .map(|tile| tile.surface.clone()) +} + fn stage_tile( entity: &Entity, yumush: &Yumush, - palette: Palette, + t: Tokens, (user_id, kind): (Id, Kind), ) -> impl IntoElement { - let t = palette.tokens; let entity = entity.clone(); let focused = yumush.is_watching(user_id, kind); - let surface = yumush - .chat - .tiles - .get(&(user_id, kind)) - .filter(|tile| tile.shown) - .map(|tile| tile.surface.clone()); + let surface = tile_surface(yumush, (user_id, kind)); div() .id(format!("stage_{user_id}_{kind:?}")) @@ -537,8 +594,7 @@ fn stage_tile( ) } -fn more_tile(entity: &Entity, more: usize, palette: Palette) -> impl IntoElement { - let t = palette.tokens; +fn more_tile(entity: &Entity, more: usize, t: Tokens) -> impl IntoElement { let entity = entity.clone(); div() .id("stage_more") @@ -575,17 +631,12 @@ fn more_tile(entity: &Entity, more: usize, palette: Palette) -> impl Int fn grid_cell( entity: &Entity, yumush: &Yumush, - palette: Palette, + t: Tokens, (user_id, kind): (Id, Kind), (width, height): (f32, f32), ) -> AnyElement { let entity = entity.clone(); - let surface = yumush - .chat - .tiles - .get(&(user_id, kind)) - .filter(|tile| tile.shown) - .map(|tile| tile.surface.clone()); + let surface = tile_surface(yumush, (user_id, kind)); div() .id(format!("grid_{user_id}_{kind:?}")) .w(px(width)) @@ -602,7 +653,7 @@ fn grid_cell( }) .child(div().absolute().inset_0().children(surface)) .child( - tile_label(yumush, palette, (user_id, kind)) + tile_label(yumush, t, (user_id, kind)) .absolute() .left(px(space::MD)) .top(px(space::MD)), @@ -610,10 +661,9 @@ fn grid_cell( .into_any_element() } -pub(super) fn tile_label(yumush: &Yumush, palette: Palette, source: (Id, Kind)) -> Div { - let t = palette.tokens; +pub(super) fn tile_label(yumush: &Yumush, t: Tokens, source: (Id, Kind)) -> Div { let user_id = source.0; - let muted = yumush.chat.server_muted.contains(&user_id) + let muted = yumush.chat.session.server_muted.contains(&user_id) || (yumush.is_me(user_id) && yumush.chat.voice_flags().is_some_and(|(muted, _)| muted)); scrim(t) @@ -631,7 +681,7 @@ fn tile_name( .chat .author(user_id) .map_or_else(|| user_id.to_string(), |user| user.username.clone()); - let audible = yumush.chat.waves.audible(user_id); + let audible = yumush.chat.session.waves.audible(user_id); let ink = if audible || focused { Ink::Paper } else { @@ -653,6 +703,8 @@ fn tile_name( ) } +pub(super) static CAMERA_BUSY: AtomicBool = AtomicBool::new(false); + #[cfg(test)] mod tests { use super::{WIDE, grid_columns}; diff --git a/crates/client/src/gui/chat.rs b/crates/client/src/gui/chat.rs index 1227325..fb7c150 100644 --- a/crates/client/src/gui/chat.rs +++ b/crates/client/src/gui/chat.rs @@ -1,36 +1,35 @@ -use super::style::{self, radius, size, space, stroke, text}; +pub(super) mod admin; +pub(super) mod poll_draft; +pub(super) mod session; + +use self::admin::Admin; +use self::poll_draft::PollDraft; +use self::session::Session; +use super::style::{self, Tokens, radius, size, space, stroke, text}; use super::text; use crate::gui::glyph::Fill as _; use crate::lang::w; use std::{ - collections::{BTreeMap, HashMap, HashSet, VecDeque}, - sync::Arc, + collections::{HashSet, VecDeque}, time::{Duration, Instant}, }; -use crate::gui::camera_view::{Stage, Tile}; -use crate::gui::social::InviteLookup; +use crate::gui::camera_view::Stage; use crate::gui::voice_stats::{self, SAMPLE_HISTORY}; -use crate::gui::wave::Waves; use crate::gui::{ - JUMP_HINT, Palette, Tooltip as _, Yumush, avatar, - builder::{BuilderTab, Transfer}, - clickable, community_name, + Tooltip as _, Yumush, avatar, clickable, community_name, community_settings::{BanSort, LogSort}, composer::{self, Composer}, - entity_action, hoverable, - media_view::{self, Media}, - message_actions, millis_time, new_input, notify_error, palette, parts, poll, presence_avatar, + entity_action, hoverable, media_view, message_actions, millis_time, new_input, notify_error, + parts, poll, presence_avatar, profile::profile_popover, - share_view::Viewer, sidebar::unread_badge, snippet, voice_note::{self, VoiceNote}, widget::{ok_or_notify, search_text, spawn_done}, }; -use crate::net::Levels; +use crate::net::{Fail, Levels}; use crate::settings::VOLUME; -use crate::share::session::ShareSample; use common::{ call::{ CreateCommunity, DeclineCall, DeleteMessage, GetUser, LeaveCommunity, ListBans, @@ -40,26 +39,22 @@ use common::{ constant::MESSAGE_PAGE_LIMIT, event::Event, model::{ - Account, AdminActionKind, AdminLogEntry, AttachmentInfo, Ban, BanScope, CallLog, Community, - CommunityKind, CommunitySummary, CommunityUsage, DayStat, Edit, Friends, Id, Invitation, - InviteCode, LogEntry, Member, Message, MessageHit, Overview, Presence, Rank, Reply, Report, - ReportStatus, ServerBan, SessionInfo, Unread, UpdateClient, Usage, User, VoiceRoom, - mentions, + CallLog, Community, CommunityKind, Hue, Id, Member, Message, Presence, Rank, Reply, Unread, + User, mentions, }, permission, share::{Kind, Share}, + stats::ShareSample, }; use gpui_kit::{ - Anchor, AnimationExt, AnyElement, App, AppContext, Context, Div, Entity, FontWeight, Image, + Anchor, AnimationExt, AnyElement, App, AppContext, Context, Div, Entity, FontWeight, InteractiveElement, IntoElement, ParentElement, ScrollHandle, StatefulInteractiveElement, - Styled, Subscription, Task, Window, + Styled, Subscription, Window, assets::IconName, component::{ - Icon, IndexPath, WindowExt, + Icon, WindowExt, input::{InputEvent, InputState, Textarea, TextareaState}, resizable::{h_resizable, resizable_panel, v_resizable}, - searchable_list::SearchableVec, - select::SelectState, slider::{SliderEvent, SliderState}, text::TextView, }, @@ -74,15 +69,16 @@ pub enum StatsAt { Dock, } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum View { + #[default] Chat, Settings, CommunitySettings, Builder, } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq)] pub enum Armed { LogOut, Leave(Id), @@ -91,10 +87,17 @@ pub enum Armed { DeleteAccount, DeleteCommunity, RestartServer, + DeleteMessage(Id), + DeleteAttachment(Id), + BuilderDeleteUser(Id), + PurgeUser(Id), + BuilderDeleteCommunity(Id), + DeleteInvite(String), } -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, Default)] pub enum VoiceState { + #[default] Off, In { community_id: Id, @@ -104,10 +107,11 @@ pub enum VoiceState { }, } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum History { - More, +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub(super) enum History { + #[default] End, + More, } impl History { @@ -126,177 +130,39 @@ pub enum ReportTarget { User(Id), } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum CardMenu { + #[default] Main, More, Status, } pub struct Chat { - pub(super) communities: Vec, - pub(super) selected_community_id: Option, - pub(super) opened: Option, - pub(super) ghost: bool, - pub(super) members: Vec, - pub(super) messages: Vec, - pub(super) pins: Vec, - history: History, - pub(super) unread: HashMap, - pub(super) unread_anchor: Option<(Id, u32)>, - unseen: u32, - pub(super) muted: HashSet, - pub(super) pinned: HashSet, - pub(super) edits: HashMap>, - pub(super) revealed: HashSet, + pub(super) session: Session, + pub(super) admin: Admin, + pub(super) poll: PollDraft, + pub(super) composer: Composer, pub(super) message_input: Entity, pub(super) search_input: Entity, - pub(super) friends_open: bool, - pub(super) open_calls: HashSet, pub(super) community_search: Entity, - pub(super) community_hits: Vec, - pub(super) found: Option, - pub(super) invite: InviteLookup, - pub(super) sidebar_collapsed: bool, - pub(super) sidebar_toggled: Option, - pub(super) composer: Composer, - pub(super) drafts: HashMap, - pub(super) poll_question: Entity, - pub(super) poll_options: Vec>, - pub(super) poll_multiple: bool, - pub(super) poll_public: bool, - pub(super) poll_duration: Option, - pub(super) plus_menu: composer::PlusMenu, - pub(super) my_votes: HashMap>, - pub(super) poll_expanded: bool, - pub(super) poll_page: usize, - scroll: ScrollHandle, - pub(super) jump: Option, - highlight: Option<(Id, Instant)>, - glide: Option<(Id, gpui_kit::Pixels, Instant)>, - pub(super) view: View, - pub(super) section: Option<&'static str>, pub(super) username_input: Entity, pub(super) community_name_input: Entity, pub(super) status_input: Entity, - pub(super) avatars: HashMap>, - pub(super) avatar_requests: HashSet, - pub(super) users: HashMap, - user_requests: HashSet, - pub(super) armed: Option, - pub(super) bans: Vec, pub(super) ban_search: Entity, pub(super) ban_sort: BanSort, - pub(super) logs: Vec, pub(super) log_search: Entity, pub(super) log_sort: LogSort, - pub(super) friends: Friends, - pub(super) invitations: Vec, - pub(super) card_menu: CardMenu, - pub(super) presences: HashMap, - pub(super) slowed_until: Option, - pub(super) pending_builder_delete: Option, - pub(super) builder_users: Vec, - pub(super) pending_builder_password: Option, - pub(super) builder_password: Entity, - pub(super) builder_sessions: Option<(Id, Vec)>, - pub(super) builder_clients: Vec, - pub(super) builder_clients_task: Option>, - pub(super) builder_friends: Vec, - pub(super) pending_builder_rename: Option, - pub(super) builder_rename: Entity, - pub(super) server_name: Entity, - pub(super) server_limit: Entity, - pub(super) server_user_quota: Entity, - pub(super) server_community_quota: Entity, - pub(super) server_message_retention: Entity, - pub(super) server_attachment_retention: Entity, - pub(super) server_announcement: Entity, - pub(super) server_max_communities: Entity, - pub(super) server_max_message_length: Entity, - pub(super) server_max_avatar: Entity, - pub(super) server_messages_per_minute: Entity, - pub(super) server_logins_per_minute: Entity, - pub(super) server_registration_open: bool, - pub(super) server_maintenance: bool, - pub(super) pending_builder_timeout: Option, - pub(super) builder_timeout: Entity, - pub(super) pending_builder_ban: Option, - pub(super) builder_ban_reason: Entity, - pub(super) builder_ban_scope: BanScope, - pub(super) builder_bans: Vec, - pub(super) builder_invites: Vec, - pub(super) invite_uses: Entity, - pub(super) invite_hours: Entity, - pub(super) pending_invite_delete: Option, - pub(super) new_username: Entity, - pub(super) new_password: Entity, - pub(super) builder_tab: BuilderTab, - pub(super) builder_overview: Option, - pub(super) builder_logs: Vec, - pub(super) builder_stats: Vec, - pub(super) builder_log_actor: Entity, - pub(super) builder_log_target: Entity, - pub(super) builder_log_action: Entity>>, - pub(super) builder_log_from: Entity, - pub(super) builder_log_to: Entity, - pub(super) builder_search: Entity, - pub(super) builder_friend_search: Entity, - pub(super) builder_communities: Vec, - pub(super) builder_reports: Vec, - pub(super) report_filter: Option, - pub(super) open_reports: usize, - pub(super) report: Option, pub(super) report_reason: Entity, - pub(super) pending_community_delete: Option, - pub(super) builder_message_text: Entity, - pub(super) builder_message_user: Entity, - pub(super) builder_message_community: Entity, - pub(super) builder_message_from: Entity, - pub(super) builder_message_to: Entity, - pub(super) builder_messages: Vec, - pub(super) builder_attachment_user: Entity, - pub(super) builder_attachment_community: Entity, - pub(super) builder_usage_users: Vec, - pub(super) builder_usage_communities: Vec, - pub(super) builder_attachments: Vec, - pub(super) pending_attachment_delete: Option, - pub(super) pending_message_delete: Option, - pub(super) hover_row: Option, - pub(super) hover_bar: Option, - pub(super) reacting: Option, - pub(super) pending_builder_purge: Option, - pub(super) transfer: Option, - pub(super) voice: HashMap>, - pub(super) voice_state: VoiceState, - pub(super) waves: Waves, - pub(super) server_muted: HashSet, - pub(super) builder_voice_rooms: Vec, - pub(super) voice_task: Option>, - pub(super) stats_task: Option>, - pub(super) goto: super::jump::Jump, - pub(super) server_stats: Option, - pub(super) server_stats_task: Option>, - pub(super) user_volume: Option, - pub(super) stats: common::stats::Stats, - pub(super) followed: Option<(Id, common::stats::Stats)>, - pub(super) share_loss: HashMap<(Id, Kind), VecDeque<(u64, f32)>>, + pub(super) sidebar_collapsed: bool, + pub(super) sidebar_toggled: Option, pub(super) stats_at: Option, - pub(super) usage_monitor: crate::usage::Monitor, - pub(super) storage: Vec<(crate::storage::Store, u64)>, - pub(super) ringing: HashSet, - pub(super) ring_task: Option>, - pub(super) media: Media, - pub(super) shares: HashMap>, - pub(super) viewer: Option, - pub(super) float: super::share_view::Float, - pub(super) tiles: BTreeMap<(Id, Kind), Tile>, - pub(super) camera_task: Option>, pub(super) stage: Stage, pub(super) grid_size: (f32, f32), pub(super) strip_size: (f32, f32), - pub(super) typing: HashMap>, - pub(super) typing_sent: HashMap, + pub(super) goto: super::jump::Jump, + pub(super) usage_monitor: crate::usage::Monitor, + scroll: ScrollHandle, } const RING_LIMIT: usize = 15; @@ -382,17 +248,12 @@ impl Chat { let ban_search = new_input(w().chat.search, window, cx); let log_search = new_input(w().chat.search, window, cx); - let builder_search = new_input(w().chat.search, window, cx); - let builder_friend_search = new_input(w().chat.search, window, cx); - let builder_password = new_input(w().chat.new_password, window, cx); - builder_password.update(cx, |input, cx| input.set_masked(true, window, cx)); - let new_password = new_input(w().chat.password, window, cx); - new_password.update(cx, |input, cx| input.set_masked(true, window, cx)); + let admin = Admin::new(window, cx); for search in [ &ban_search, &log_search, - &builder_search, - &builder_friend_search, + &admin.builder_search, + &admin.builder_friend_search, ] { cx.subscribe_in(search, window, |_, _, event, window, cx| { if matches!(event, InputEvent::Change) { @@ -404,57 +265,13 @@ impl Chat { } Self { - communities: vec![], - selected_community_id: None, - opened: None, - ghost: false, - members: vec![], - bans: vec![], - ban_search, - ban_sort: BanSort::Newest, - logs: vec![], - log_search, - log_sort: LogSort::Newest, - friends: Friends::default(), - invitations: vec![], - messages: vec![], - pins: vec![], - poll_question: new_input(w().chat.question, window, cx), - poll_options: vec![ - composer::new_poll_option(window, cx), - composer::new_poll_option(window, cx), - ], - poll_multiple: false, - poll_public: true, - poll_duration: None, - plus_menu: composer::PlusMenu::Menu, - my_votes: HashMap::new(), - poll_expanded: false, - poll_page: 0, - history: History::End, - scroll: ScrollHandle::new(), - jump: None, - highlight: None, - glide: None, - unread: HashMap::new(), - unread_anchor: None, - unseen: 0, - muted: HashSet::new(), - pinned: HashSet::new(), - edits: HashMap::new(), - revealed: HashSet::new(), + session: Session::default(), + admin, + poll: PollDraft::new(window, cx), + composer: Composer::Compose { reply: None }, message_input, search_input, - friends_open: false, - open_calls: HashSet::new(), community_search, - community_hits: vec![], - found: None, - invite: InviteLookup::Idle, - sidebar_collapsed: false, - sidebar_toggled: None, - view: View::Chat, - section: None, username_input: editable_input(w().chat.username, Yumush::save_username, window, cx), community_name_input: editable_input( w().chat.community_name, @@ -463,152 +280,38 @@ impl Chat { cx, ), status_input: editable_input(w().chat.status, Yumush::save_status, window, cx), - avatars: HashMap::new(), - avatar_requests: HashSet::new(), - users: HashMap::new(), - user_requests: HashSet::new(), - armed: None, - card_menu: CardMenu::Main, - presences: HashMap::new(), - slowed_until: None, - pending_builder_delete: None, - builder_users: vec![], - builder_tab: BuilderTab::Overview, - builder_overview: None, - builder_logs: vec![], - builder_stats: vec![], - builder_log_actor: new_input(w().chat.actor, window, cx), - builder_log_target: new_input(w().chat.target, window, cx), - builder_log_action: cx.new(|cx| { - SelectState::new( - SearchableVec::new( - std::iter::once(w().chat.all) - .chain( - AdminActionKind::ALL - .into_iter() - .map(AdminActionKind::as_str), - ) - .collect::>(), - ), - Some(IndexPath::new(0)), - window, - cx, - ) - }), - builder_log_from: new_input(w().chat.date_from, window, cx), - builder_log_to: new_input(w().chat.date_to, window, cx), - builder_search, - builder_friend_search, - builder_communities: vec![], - pending_community_delete: None, - builder_message_text: new_input(w().chat.text, window, cx), - builder_message_user: new_input(w().chat.user, window, cx), - builder_message_community: new_input(w().chat.community, window, cx), - builder_message_from: new_input(w().chat.date_from, window, cx), - builder_message_to: new_input(w().chat.date_to, window, cx), - builder_messages: vec![], - builder_attachment_user: new_input(w().chat.user, window, cx), - builder_attachment_community: new_input(w().chat.community, window, cx), - builder_usage_users: vec![], - builder_usage_communities: vec![], - builder_attachments: vec![], - pending_attachment_delete: None, - pending_message_delete: None, - hover_row: None, - hover_bar: None, - reacting: None, - pending_builder_purge: None, - transfer: None, - builder_password, - server_name: new_input(w().chat.server_name, window, cx), - server_limit: new_input("", window, cx), - server_user_quota: new_input("", window, cx), - server_community_quota: new_input("", window, cx), - server_message_retention: new_input("", window, cx), - server_attachment_retention: new_input("", window, cx), - server_announcement: new_input(w().chat.announcement, window, cx), - server_max_communities: new_input("", window, cx), - server_max_message_length: new_input(w().chat.max_message_length, window, cx), - server_max_avatar: new_input("", window, cx), - server_messages_per_minute: new_input("", window, cx), - server_logins_per_minute: new_input("", window, cx), - server_registration_open: true, - server_maintenance: false, - pending_builder_timeout: None, - builder_timeout: new_input(w().chat.minutes, window, cx), - pending_builder_ban: None, - builder_ban_reason: new_input(w().chat.reason, window, cx), - builder_ban_scope: BanScope::Account, - builder_bans: vec![], - builder_invites: vec![], - invite_uses: new_input(w().chat.uses, window, cx), - invite_hours: new_input(w().chat.hours, window, cx), - pending_invite_delete: None, - new_username: new_input(w().chat.username, window, cx), - new_password, - pending_builder_password: None, - builder_sessions: None, - builder_clients: Vec::new(), - builder_clients_task: None, - builder_friends: Vec::new(), - pending_builder_rename: None, - builder_rename: new_input(w().chat.new_username, window, cx), - builder_reports: vec![], - report_filter: Some(ReportStatus::Open), - open_reports: 0, - report: None, + ban_search, + ban_sort: BanSort::Newest, + log_search, + log_sort: LogSort::Newest, report_reason: new_input(w().chat.reason, window, cx), - voice: HashMap::new(), - drafts: HashMap::new(), - voice_state: VoiceState::Off, - waves: Waves::default(), - user_volume: None, - server_muted: HashSet::new(), - builder_voice_rooms: Vec::new(), - voice_task: None, - stats_task: None, + sidebar_collapsed: false, + sidebar_toggled: None, + stats_at: None, + stage: Stage::Strip, + grid_size: (1280., 720.), + strip_size: (1280., 0.), goto: super::jump::Jump { open: false, cursor: 0, input: jump_input, scroll: ScrollHandle::new(), }, - server_stats: None, - server_stats_task: None, - stats: common::stats::Stats::default(), - followed: None, - share_loss: HashMap::new(), - stats_at: None, - storage: Vec::new(), usage_monitor: { - let monitor = crate::usage::Monitor::default(); - if let Some(dir) = crate::config_dir() { - monitor.watch_disk(dir); - } - monitor + crate::usage::Monitor::new(crate::usage::Wake::OnDemand, crate::config_dir()) }, - ringing: HashSet::new(), - ring_task: None, - typing: HashMap::new(), - typing_sent: HashMap::new(), - media: Media::default(), - shares: HashMap::new(), - viewer: None, - float: Default::default(), - tiles: BTreeMap::new(), - camera_task: None, - stage: Stage::Strip, - grid_size: (1280., 720.), - strip_size: (1280., 0.), - composer: Composer::Compose { reply: None }, + scroll: ScrollHandle::new(), } } fn unread_where(&self, keep: impl Fn(&CommunityKind) -> bool) -> Unread { - self.communities + self.session + .communities .iter() - .filter(|community| !self.muted.contains(&community.id) && keep(&community.kind)) - .filter_map(|community| self.unread.get(&community.id)) + .filter(|community| { + !self.session.muted.contains(&community.id) && keep(&community.kind) + }) + .filter_map(|community| self.session.unread.get(&community.id)) .fold(Unread::default(), |total, unread| Unread { messages: total.messages + unread.messages, mentions: total.mentions + unread.mentions, @@ -625,7 +328,7 @@ impl Chat { } pub fn focus(&self, window: &mut Window, cx: &mut Context) { - match self.selected_community_id { + match self.session.selected_community_id { Some(_) => self .message_input .update(cx, |input, cx| input.focus(window, cx)), @@ -635,28 +338,23 @@ impl Chat { } } - pub(super) fn call_run_end(&self, index: usize) -> Id { - let calls = self.messages[index..] - .iter() - .take_while(|message| message.call.is_some()) - .count(); - self.messages[index + calls.max(1) - 1].id - } - pub fn name_of(&self, user_id: Id) -> String { self.author(user_id) .map_or_else(|| user_id.to_string(), |user| user.username.clone()) } pub fn slow_seconds(&self) -> Option { - let remaining = self.slowed_until?.saturating_sub(common::time::now_ms()); + let remaining = self + .session + .slowed_until? + .saturating_sub(common::time::now_ms()); (remaining > 0).then(|| remaining.div_ceil(1000)) } pub fn apply_event(&mut self, event: Event, me: Option, builder: bool) { match event { Event::MessageCreated(message) => { - if let Some(users) = self.typing.get_mut(&message.community_id) { + if let Some(users) = self.session.typing.get_mut(&message.community_id) { users.remove(&message.user_id); } if self.is_selected(message.community_id) { @@ -667,6 +365,7 @@ impl Chat { if self.is_selected(message.community_id) { self.update_pin(&message); if let Some(existing) = self + .session .messages .iter_mut() .find(|existing| existing.id == message.id) @@ -686,7 +385,7 @@ impl Chat { message_id, positions, } => { - self.my_votes.insert(message_id, positions); + self.session.my_votes.insert(message_id, positions); } Event::MessagesDeleted { community_id, ids } => { if self.is_selected(community_id) { @@ -732,25 +431,25 @@ impl Chat { .chain(&friends.outgoing) .collect::>(), ); - self.friends = friends; - } - Event::InvitationsUpdated(invitations) => self.invitations = invitations, - Event::CommunityDeleted { community_id } | Event::Removed { community_id, .. } => { - self.remove_community(community_id) + self.session.friends = friends; } + Event::InvitationsUpdated(invitations) => self.session.invitations = invitations, + Event::CommunityDeleted { community_id } => self.remove_community(community_id), Event::UserDeleted { user_id } => { self.remove_member(user_id); - self.messages.retain(|message| message.user_id != user_id); + self.session + .messages + .retain(|message| message.user_id != user_id); } Event::UserUpdated(user) => self.update_member(&user), Event::PresenceChanged { user_id, presence } => { - self.presences.insert(user_id, presence); + self.session.presences.insert(user_id, presence); } Event::VoiceJoined { community_id, user_id, } => { - let ids = self.voice.entry(community_id).or_default(); + let ids = self.session.voice.entry(community_id).or_default(); if !ids.contains(&user_id) { ids.push(user_id); } @@ -759,25 +458,26 @@ impl Chat { community_id, user_id, } => { - if let Some(ids) = self.voice.get_mut(&community_id) { + if let Some(ids) = self.session.voice.get_mut(&community_id) { ids.retain(|id| *id != user_id); if ids.is_empty() { - self.ringing.remove(&community_id); + self.session.ringing.remove(&community_id); } } } Event::VoiceMuted { user_id, muted, .. } => { if muted { - self.server_muted.insert(user_id); + self.session.server_muted.insert(user_id); } else { - self.server_muted.remove(&user_id); + self.session.server_muted.remove(&user_id); } } Event::Typing { community_id, user_id, } => { - self.typing + self.session + .typing .entry(community_id) .or_default() .insert(user_id, Instant::now()); @@ -786,7 +486,7 @@ impl Chat { community_id, share, } => { - let shares = self.shares.entry(community_id).or_default(); + let shares = self.session.shares.entry(community_id).or_default(); shares.retain(|existing| { existing.user_id != share.user_id || existing.kind != share.kind }); @@ -797,17 +497,23 @@ impl Chat { user_id, kind, } => { - if let Some(shares) = self.shares.get_mut(&community_id) { + if let Some(shares) = self.session.shares.get_mut(&community_id) { shares.retain(|share| share.user_id != user_id || share.kind != kind); } } Event::StatsWanted(_) => {} Event::StatsOf { user_id, stats } => { - if let Some(followed) = self.followed.as_mut().filter(|(id, _)| *id == user_id) { + if let Some(followed) = self + .session + .followed + .as_mut() + .filter(|(id, _)| *id == user_id) + { followed.1 = stats; } } Event::ReportCreated + | Event::Removed { .. } | Event::SettingsUpdated(_) | Event::Release | Event::Imported { .. } => {} @@ -815,12 +521,13 @@ impl Chat { } pub(super) fn is_selected(&self, community_id: Id) -> bool { - self.selected_community_id == Some(community_id) + self.session.selected_community_id == Some(community_id) } pub fn typing_label(&self) -> Option { - let community_id = self.selected_community_id.as_ref()?; + let community_id = self.session.selected_community_id.as_ref()?; let names: Vec<&str> = self + .session .typing .get(community_id)? .iter() @@ -838,51 +545,53 @@ impl Chat { } fn select(&mut self, community_id: Option) { - if community_id != self.selected_community_id { - self.unread_anchor = community_id + if community_id != self.session.selected_community_id { + self.session.unread_anchor = community_id .as_ref() - .and_then(|community_id| self.unread.get(community_id)) + .and_then(|community_id| self.session.unread.get(community_id)) .filter(|unread| unread.messages > 0) .and_then(|unread| { unread .last_read .map(|last_read| (last_read, unread.messages)) }); - self.unseen = 0; + self.session.unseen = 0; } - if self.opened.as_ref().map(|opened| &opened.id) != community_id.as_ref() { - self.opened = None; + if self.session.opened.as_ref().map(|opened| &opened.id) != community_id.as_ref() { + self.session.opened = None; } - if self.view == View::CommunitySettings { - self.view = View::Chat; - self.armed = None; + if self.session.view == View::CommunitySettings { + self.session.view = View::Chat; } - self.selected_community_id = community_id; - self.users.extend( - self.members + self.session.selected_community_id = community_id; + self.session.users.extend( + self.session + .members .drain(..) .map(|member| (member.user.id, member.user)), ); - self.bans.clear(); - self.logs.clear(); - self.armed = None; - self.messages.clear(); - self.jump = None; - self.pins.clear(); - self.poll_expanded = false; - self.poll_page = 0; - self.my_votes.clear(); - self.community_hits.clear(); - self.history = History::End; - self.media.leave(); + self.session.bans.clear(); + self.session.logs.clear(); + self.session.armed = None; + self.session.messages.clear(); + self.session.jump = None; + self.session.pins.clear(); + self.poll.expanded = false; + self.poll.page = 0; + self.session.my_votes.clear(); + self.session.community_hits.clear(); + self.session.history = History::End; + self.session.media.leave(); self.composer = Composer::Compose { reply: None }; } pub fn joined(&self, community_id: Id) -> bool { - self.communities + self.session + .communities .iter() .chain( - self.opened + self.session + .opened .as_ref() .filter(|opened| opened.kind.is_direct()), ) @@ -890,7 +599,8 @@ impl Chat { } fn quotes_of(&mut self, message_id: Id) -> impl Iterator { - self.messages + self.session + .messages .iter_mut() .filter_map(move |message| match &mut message.reply { Some(Reply::Quote(quote)) if quote.message_id == message_id => Some(quote), @@ -901,6 +611,7 @@ impl Chat { fn remove_message(&mut self, message_id: Id, builder: bool) { if builder { if let Some(message) = self + .session .messages .iter_mut() .find(|existing| existing.id == message_id) @@ -909,9 +620,11 @@ impl Chat { message.pinned = false; } } else { - self.messages.retain(|existing| existing.id != message_id); + self.session + .messages + .retain(|existing| existing.id != message_id); } - for message in &mut self.messages { + for message in &mut self.session.messages { message.reply = match message.reply.take() { Some(Reply::Quote(quote)) if quote.message_id == message_id => { Some(Reply::Deleted(builder.then_some(quote))) @@ -925,7 +638,9 @@ impl Chat { Composer::Compose { reply } if *reply == Some(message_id) => { self.composer = Composer::Compose { reply: None }; } - Composer::Edit { message_id: edited } if *edited == message_id => { + Composer::Edit { + message_id: edited, .. + } if *edited == message_id => { self.composer = Composer::Compose { reply: None }; } _ => {} @@ -933,24 +648,28 @@ impl Chat { } pub fn communities(&self) -> &[Community] { - &self.communities + &self.session.communities } pub fn notes(&self) -> Option<&Community> { - self.communities + self.session + .communities .iter() .find(|community| matches!(community.kind, CommunityKind::Notes)) } fn insert_messages(&mut self, messages: impl IntoIterator, me: Option) { - let newest = self.messages.last().map(|message| message.id); + let newest = self.session.messages.last().map(|message| message.id); for message in messages { - self.messages.retain(|existing| existing.id != message.id); - self.messages.push(message); + self.session + .messages + .retain(|existing| existing.id != message.id); + self.session.messages.push(message); } - self.messages.sort_by_key(|message| message.id); - if self.messages.last().map(|message| message.id) != newest { + self.session.messages.sort_by_key(|message| message.id); + if self.session.messages.last().map(|message| message.id) != newest { let mine = self + .session .messages .last() .is_some_and(|message| Some(message.user_id) == me); @@ -960,23 +679,24 @@ impl Chat { None => self.scroll.scroll_to_bottom(), } } else if !self.away() { - let newest = self.messages.last().map_or(0, |message| message.id); - self.glide = Some((newest, self.scroll.offset().y, Instant::now())); - self.unseen = 0; + let newest = self.session.messages.last().map_or(0, |message| message.id); + self.session.glide = Some((newest, self.scroll.offset().y, Instant::now())); + self.session.unseen = 0; } else if mine { self.jump_to_bottom(); } else { - self.unseen += 1; + self.session.unseen += 1; } } self.reveal_jump(); } fn reveal_jump(&mut self) { - let Some(message_id) = self.jump.as_ref() else { + let Some(message_id) = self.session.jump.as_ref() else { return; }; let Some(position) = self + .session .messages .iter() .position(|message| &message.id == message_id) @@ -984,7 +704,8 @@ impl Chat { return; }; self.scroll_to_index(position); - self.highlight = self + self.session.highlight = self + .session .jump .take() .map(|message_id| (message_id, Instant::now())); @@ -992,7 +713,7 @@ impl Chat { fn scroll_to_index(&self, position: usize) { let spacer = 1; - let older = usize::from(self.history == History::More); + let older = usize::from(self.session.history == History::More); self.scroll.scroll_to_item(spacer + older + position); } @@ -1001,72 +722,81 @@ impl Chat { } pub(super) fn engaged(&self, message_id: Id) -> bool { - self.hover_bar == Some(message_id) || self.reacting == Some(message_id) + self.session.hover_bar == Some(message_id) || self.session.reacting == Some(message_id) } pub(super) fn jump_to_bottom(&mut self) { self.scroll.scroll_to_bottom(); - self.unseen = 0; + self.session.unseen = 0; } pub(super) fn settle_scroll(&mut self) { if !self.away() { - self.unseen = 0; + self.session.unseen = 0; } } fn unread_covered(&self) -> bool { - match (&self.unread_anchor, self.messages.first()) { - (Some((anchor, _)), Some(first)) => self.history == History::End || first.id <= *anchor, + match (&self.session.unread_anchor, self.session.messages.first()) { + (Some((anchor, _)), Some(first)) => { + self.session.history == History::End || first.id <= *anchor + } _ => true, } } fn unread_divider(&self, me: Option) -> Option { - let (anchor, _) = self.unread_anchor?; + let (anchor, _) = self.session.unread_anchor?; if !self.unread_covered() { return None; } - self.messages + self.session + .messages .iter() .position(|message| message.id > anchor && Some(message.user_id) != me) } pub(super) fn mark_read(&mut self, community_id: Id, message_id: Id) { - let unread = self.unread.entry(community_id).or_insert_with(|| Unread { - community_id, - ..Default::default() - }); + let unread = self + .session + .unread + .entry(community_id) + .or_insert_with(|| Unread { + community_id, + ..Default::default() + }); unread.messages = 0; unread.mentions = 0; unread.last_read = Some(message_id); } fn add_page(&mut self, page: Vec, me: Option) { - self.history = History::of_page(page.len()); + self.session.history = History::of_page(page.len()); self.insert_messages(page, me); } fn insert_member(&mut self, member: Member) { style::remember(&[&member.user]); self.remove_member(member.user.id); - self.members.push(member); - self.members.sort_by_key(|member| member.user.id); + self.session.members.push(member); + self.session.members.sort_by_key(|member| member.user.id); } pub(super) fn remove_member(&mut self, user_id: Id) { if let Some(index) = self + .session .members .iter() .position(|member| member.user.id == user_id) { - let member = self.members.remove(index); - self.users.insert(member.user.id, member.user); + let member = self.session.members.remove(index); + self.session.users.insert(member.user.id, member.user); } } fn set_rank(&mut self, user_id: Id, rank: Rank) { if let Some(member) = self + .session .members .iter_mut() .find(|member| member.user.id == user_id) @@ -1076,18 +806,22 @@ impl Chat { } pub fn community(&self, community_id: Id) -> Option<&Community> { - self.communities + self.session + .communities .iter() - .chain(self.opened.as_ref()) + .chain(self.session.opened.as_ref()) .find(|community| community.id == community_id) } pub fn selected_community(&self) -> Option<&Community> { - self.community(self.selected_community_id?) + self.community(self.session.selected_community_id?) } fn member_entry(&self, user_id: Id) -> Option<&Member> { - self.members.iter().find(|member| member.user.id == user_id) + self.session + .members + .iter() + .find(|member| member.user.id == user_id) } pub fn member(&self, user_id: Id) -> Option<&User> { @@ -1095,16 +829,18 @@ impl Chat { } pub fn author(&self, user_id: Id) -> Option<&User> { - self.member(user_id).or_else(|| self.users.get(&user_id)) + self.member(user_id) + .or_else(|| self.session.users.get(&user_id)) } fn missing_authors(&self) -> Vec { - let mut ids: Vec = if self.members.is_empty() { + let mut ids: Vec = if self.session.members.is_empty() { vec![] } else { - self.messages + self.session + .messages .iter() - .chain(&self.pins) + .chain(&self.session.pins) .flat_map(|message| { std::iter::once(message.user_id) .chain( @@ -1127,7 +863,7 @@ impl Chat { } let mut missing: Vec = ids .into_iter() - .filter(|id| self.author(*id).is_none() && !self.user_requests.contains(id)) + .filter(|id| self.author(*id).is_none() && !self.session.user_requests.contains(id)) .collect(); missing.sort(); missing.dedup(); @@ -1152,10 +888,12 @@ impl Chat { } fn update_pin(&mut self, message: &Message) { - self.pins.retain(|pin| pin.id != message.id); + self.session.pins.retain(|pin| pin.id != message.id); if message.pinned { - self.pins.push(message.clone()); - self.pins.sort_by_key(|pin| std::cmp::Reverse(pin.id)); + self.session.pins.push(message.clone()); + self.session + .pins + .sort_by_key(|pin| std::cmp::Reverse(pin.id)); } } @@ -1169,26 +907,34 @@ impl Chat { pub fn update_member(&mut self, user: &User) { style::remember(&[user]); - let peers = self - .communities - .iter_mut() - .filter_map(|community| match &mut community.kind { - CommunityKind::Direct { peer } => Some(peer), - CommunityKind::Group | CommunityKind::Notes => None, - }); + let peers = + self.session + .communities + .iter_mut() + .filter_map(|community| match &mut community.kind { + CommunityKind::Direct { peer } => Some(peer), + CommunityKind::Group | CommunityKind::Notes => None, + }); let known = self + .session .friends .friends .iter_mut() - .chain(self.friends.incoming.iter_mut()) - .chain(self.friends.outgoing.iter_mut()) + .chain(self.session.friends.incoming.iter_mut()) + .chain(self.session.friends.outgoing.iter_mut()) .chain( - self.invitations + self.session + .invitations .iter_mut() .map(|invitation| &mut invitation.inviter), ) - .chain(self.members.iter_mut().map(|member| &mut member.user)) - .chain(self.users.values_mut()) + .chain( + self.session + .members + .iter_mut() + .map(|member| &mut member.user), + ) + .chain(self.session.users.values_mut()) .chain(peers); for existing in known.filter(|existing| existing.id == user.id) { *existing = user.clone(); @@ -1196,104 +942,43 @@ impl Chat { } pub(super) fn insert_community(&mut self, community: Community) { - self.communities + self.session + .communities .retain(|existing| existing.id != community.id); - self.communities.push(community); - self.communities.sort_by_key(|community| community.id); + self.session.communities.push(community); + self.session + .communities + .sort_by_key(|community| community.id); } pub(super) fn remove_community(&mut self, community_id: Id) { - self.communities + self.session + .communities .retain(|community| community.id != community_id); - self.unread.remove(&community_id); - self.voice.remove(&community_id); - if self.in_voice(community_id) { - self.set_voice_off(); - } + self.session.unread.remove(&community_id); + self.session.voice.remove(&community_id); if self.is_selected(community_id) { self.select(None); } } fn replace_communities(&mut self, communities: Vec) { - self.communities = communities; - - let selected_present = self - .communities - .iter() - .chain(self.opened.as_ref()) - .any(|community| self.is_selected(community.id)); - if !selected_present { + self.session.communities = communities; + if self.selected_community().is_none() { self.select(None); } - - if self.voice_community().is_some_and(|id| !self.joined(id)) { - self.set_voice_off(); - } } pub fn reset(&mut self) { - self.communities.clear(); - self.presences.clear(); - self.slowed_until = None; - self.friends = Friends::default(); - self.invitations.clear(); - self.found = None; self.select(None); - self.unread.clear(); - self.muted.clear(); - self.builder_users.clear(); - self.builder_tab = BuilderTab::Overview; - self.builder_overview = None; - self.builder_logs.clear(); - self.builder_stats.clear(); - self.builder_communities.clear(); - self.builder_reports.clear(); - self.report_filter = Some(ReportStatus::Open); - self.open_reports = 0; - self.report = None; - self.pending_community_delete = None; - self.builder_messages.clear(); - self.builder_usage_users.clear(); - self.builder_usage_communities.clear(); - self.builder_attachments.clear(); - self.pending_attachment_delete = None; - self.pending_message_delete = None; - self.pending_builder_purge = None; - self.transfer = None; - self.pending_builder_delete = None; - self.pending_builder_password = None; - self.builder_sessions = None; - self.builder_clients.clear(); - self.builder_clients_task = None; - self.pending_builder_rename = None; - self.pending_builder_timeout = None; - self.pending_builder_ban = None; - self.builder_ban_scope = BanScope::Account; - self.builder_bans.clear(); - self.builder_invites.clear(); - self.pending_invite_delete = None; - self.view = View::Chat; - self.armed = None; - self.voice.clear(); - self.server_muted.clear(); - self.builder_voice_rooms.clear(); - self.ringing.clear(); - self.ring_task = None; - self.ghost = false; - self.drafts.clear(); - self.shares.clear(); - self.typing.clear(); - self.typing_sent.clear(); - self.users.clear(); - self.user_requests.clear(); - self.user_volume = None; - self.card_menu = CardMenu::Main; - self.set_voice_off(); + let camera_task = self.session.camera_task.take(); + self.session = Session::default(); + self.session.camera_task = camera_task; + self.admin.clear(); } pub fn voice_community(&self) -> Option { - match &self.voice_state { + match &self.session.voice_state { VoiceState::Off => None, VoiceState::In { community_id, .. } => Some(*community_id), } @@ -1308,7 +993,7 @@ impl Chat { } pub fn voice_flags(&self) -> Option<(bool, bool)> { - match &self.voice_state { + match &self.session.voice_state { VoiceState::Off => None, VoiceState::In { muted, deafened, .. @@ -1322,27 +1007,29 @@ impl Chat { } pub fn share_of(&self, community_id: Id, user_id: Id, kind: Kind) -> Option<&Share> { - self.shares + self.session + .shares .get(&community_id)? .iter() .find(|share| share.user_id == user_id && share.kind == kind) } pub fn voice_ids(&self, community_id: Id) -> &[Id] { - self.voice + self.session + .voice .get(&community_id) .map(Vec::as_slice) .unwrap_or_default() } pub fn set_voice_off(&mut self) { - self.voice_state = VoiceState::Off; - self.waves.clear(); - self.voice_task = None; - self.stats.voice.clear(); - self.stats.traffic.clear(); - self.stats.share = ShareSample::default(); - self.share_loss.clear(); + self.session.voice_state = VoiceState::Off; + self.session.waves.clear(); + self.session.voice_task = None; + self.session.stats.voice.clear(); + self.session.stats.traffic.clear(); + self.session.stats.share = ShareSample::default(); + self.session.share_loss.clear(); } pub fn record_share(&mut self, sample: ShareSample) { @@ -1376,39 +1063,43 @@ impl Chat { "watch" ); } - self.share_loss.retain(|key, _| { + self.session.share_loss.retain(|key, _| { sample .watching .iter() .any(|(user_id, kind, _)| (*user_id, *kind) == *key) }); for (user_id, kind, stats) in &sample.watching { - let history = self.share_loss.entry((*user_id, *kind)).or_default(); + let history = self + .session + .share_loss + .entry((*user_id, *kind)) + .or_default(); history.push_back((common::time::now_ms(), stats.loss)); while history.len() > SAMPLE_HISTORY { history.pop_front(); } } - self.stats.share = sample; + self.session.stats.share = sample; } } -fn empty_state(palette: Palette) -> impl IntoElement { +fn empty_state(t: Tokens) -> impl IntoElement { div() .flex_1() .flex() .items_center() .justify_center() .gap(px(space::SM)) - .text_color(palette.muted) + .text_color(t.dim()) .child( div() .px(px(space::XS)) .rounded(px(radius::SM)) .border_1() - .border_color(palette.border) + .border_color(t.thread()) .text_size(text(text::CAPTION)) - .child(JUMP_HINT), + .child(super::keys::label("K")), ) .child(w().jump.placeholder) } @@ -1443,20 +1134,20 @@ impl Yumush { pub(super) fn refresh_usage(&mut self) { if let Some(usage) = self.chat.usage_monitor.latest() { - self.chat.stats.usage = Some(usage); + self.chat.session.stats.usage = Some(usage); } } pub(super) fn chat_page(&self, cx: &mut Context) -> impl IntoElement { - let palette = palette(cx); + let t = Tokens::of(cx); let entity = cx.entity(); div() .flex() .flex_row() .size_full() - .when(self.chat.view == View::Chat, |page| { - page.child(self.sidebar(&entity, palette)) + .when(self.chat.session.view == View::Chat, |page| { + page.child(self.sidebar(&entity, t)) }) .relative() .on_mouse_move({ @@ -1465,58 +1156,54 @@ impl Yumush { entity.update(cx, |yumush, cx| yumush.float_moved(event, window, cx)) } }) - .child(self.main_panel(&entity, palette, cx)) - .children(self.floating_viewer(&entity, palette)) - .children(self.fullscreen_viewer(&entity, palette)) + .child(self.main_panel(&entity, t, cx)) + .children(self.floating_viewer(&entity, t)) + .children(self.fullscreen_viewer(&entity, t)) } - fn main_panel(&self, entity: &Entity, palette: Palette, cx: &App) -> impl IntoElement { - let themed = palette; - + fn main_panel(&self, entity: &Entity, t: Tokens, cx: &App) -> impl IntoElement { div() .flex_1() .min_w_0() .flex() .flex_col() .relative() - .bg(palette.window) + .bg(t.ground()) .overflow_hidden() - .children(self.announcement_banner(entity, palette)) - .children(self.call_banner(entity, palette)) - .map(|panel| match self.chat.view { - View::Settings => panel.child(self.settings_page(entity, palette, cx)), - View::Builder => panel.child(self.builder_page(entity, palette, cx)), - View::CommunitySettings => { - panel.child(self.community_settings_page(entity, palette, cx)) - } - View::Chat => match self.chat.selected_community_id { + .children(self.announcement_banner(entity, t)) + .children(self.call_banner(entity, t)) + .map(|panel| match self.chat.session.view { + View::Settings => panel.child(self.settings_page(entity, t, cx)), + View::Builder => panel.child(self.builder_page(entity, t, cx)), + View::CommunitySettings => panel.child(self.community_settings_page(entity, t, cx)), + View::Chat => match self.chat.session.selected_community_id { Some(_) => { - let viewer = self.inline_viewer(entity, themed); + let viewer = self.inline_viewer(entity, t); let grid = viewer .is_none() .then(|| { - self.stage_grid(entity, themed, cx) + self.stage_grid(entity, t, cx) .map(IntoElement::into_any_element) }) .flatten(); panel - .child(self.header(entity, themed)) - .children(self.stage_strip(entity, themed)) - .children(self.unread_bar(entity, themed)) - .children(self.poll_banner(entity, themed)) - .child(self.chat_body(entity, themed, viewer, grid, cx)) + .child(self.header(entity, t)) + .children(self.stage_strip(entity, t)) + .children(self.unread_bar(entity, t)) + .children(self.poll_banner(entity, t)) + .child(self.chat_body(entity, t, viewer, grid, cx)) } - None => panel.child(empty_state(palette)), + None => panel.child(empty_state(t)), }, }) - .children(self.stats_sheet(palette)) - .children(self.dock(entity, palette, cx)) + .children(self.stats_sheet(t)) + .children(self.dock(entity, t, cx)) } fn chat_body( &self, entity: &Entity, - palette: Palette, + t: Tokens, viewer: Option
, grid: Option, cx: &App, @@ -1526,10 +1213,10 @@ impl Yumush { .size_full() .flex() .flex_col() - .child(self.message_area(entity, palette)) - .child(self.composer(entity, palette, cx)) + .child(self.message_area(entity, t)) + .child(self.composer(entity, t, cx)) }; - let members = members_column(entity, self, palette); + let members = members_column(entity, self, t); match (viewer, grid, members) { (None, Some(grid), Some(members)) => div() .flex_1() @@ -1585,20 +1272,20 @@ impl Yumush { .flex() .flex_col() .border_l_1() - .border_color(palette.border) + .border_color(t.thread()) .child(members.flex_1().min_h_0()) })) .into_any_element(), } } - fn stats_sheet(&self, palette: Palette) -> Option { + fn stats_sheet(&self, t: Tokens) -> Option { let at = self .chat .stats_at .filter(|_| self.chat.voice_community().is_some())?; Some( - super::parts::surface(palette.tokens) + super::parts::surface(t) .id("stats_sheet") .absolute() .right(px(space::LG)) @@ -1614,22 +1301,22 @@ impl Yumush { StatsAt::Dock => space::LG, })) .child(voice_stats::stats_panel( - &self.chat.stats, + &self.chat.session.stats, &|id| self.chat.name_of(id), match at { StatsAt::Header => voice_stats::Detail::Full, StatsAt::Dock => voice_stats::Detail::Connection, }, - palette, + t, )), ) } - fn announcement_banner(&self, entity: &Entity, palette: Palette) -> Option
{ + fn announcement_banner(&self, entity: &Entity, t: Tokens) -> Option
{ let text = self.announcement()?; Some( - accent_bar(palette) + accent_bar(t) .child(super::glyph::line( text.to_string().into(), super::text(super::style::text::UI), @@ -1637,7 +1324,7 @@ impl Yumush { .child( clickable( "dismiss_announcement", - palette, + t, entity_action(entity, |yumush, _, cx| yumush.dismiss_announcement(cx)), ) .child("×"), @@ -1645,11 +1332,11 @@ impl Yumush { ) } - fn header(&self, entity: &Entity, palette: Palette) -> impl IntoElement { + fn header(&self, entity: &Entity, t: Tokens) -> impl IntoElement { let community = self.chat.selected_community(); let name = community.map(community_name).unwrap_or_default(); let group = community.is_some_and(|community| community.kind.is_group()); - let voice = self.voice_toggle(entity, palette); + let voice = self.voice_toggle(entity, t); let peer = community.and_then(|community| match &community.kind { CommunityKind::Direct { peer } => Some(self.chat.author(peer.id).unwrap_or(peer)), _ => None, @@ -1659,7 +1346,7 @@ impl Yumush { name.to_string(), super::parts::Text::Title, super::parts::Ink::Paper, - palette.tokens, + t, ); div() @@ -1680,11 +1367,11 @@ impl Yumush { .items_center() .gap(px(space::SM)) .child(super::avatar( - palette, + t, peer, px(size::AVATAR), super::text(super::style::text::CAPTION), - &self.chat.avatars, + &self.chat.session.avatars, )) .child(title), ) @@ -1698,11 +1385,11 @@ impl Yumush { .items_center() .gap(px(space::SM)) .child(super::community_icon( - palette, + t, room, px(size::AVATAR), super::text(super::style::text::CAPTION), - &self.chat.avatars, + &self.chat.session.avatars, )) .child(title), ) @@ -1716,14 +1403,14 @@ impl Yumush { entity, "header_picture", super::community_icon( - palette, + t, community, px(size::AVATAR), super::text(super::style::text::CAPTION), - &self.chat.avatars, + &self.chat.session.avatars, ), super::Zoom::new( - super::picture_of(community, &self.chat.avatars), + super::picture_of(community, &self.chat.session.avatars), !community.kind.is_group(), name.to_string(), ), @@ -1736,7 +1423,7 @@ impl Yumush { .children( community .is_some() - .then(|| self.stage_controls(entity, palette)) + .then(|| self.stage_controls(entity, t)) .flatten(), ) .children( @@ -1747,26 +1434,26 @@ impl Yumush { &self.chat, self.settings.clock(), entity, - palette, + t, ) }), ) .children( - (community.is_some() && !self.chat.pins.is_empty()) - .then(|| message_actions::pins_popover(&self.chat, entity, palette)), + (community.is_some() && !self.chat.session.pins.is_empty()) + .then(|| message_actions::pins_popover(&self.chat, entity, t)), ) - .children(self.calling_hint(palette)) + .children(self.calling_hint(t)) .children(voice.is_some().then(|| { div() .w(px(stroke::LINE)) .h(px(size::CHIP)) .flex_none() - .bg(palette.tokens.thread()) + .bg(t.thread()) })) .children(voice) } - fn message_area(&self, entity: &Entity, palette: Palette) -> impl IntoElement { + fn message_area(&self, entity: &Entity, t: Tokens) -> impl IntoElement { div() .flex() .flex_col() @@ -1780,58 +1467,56 @@ impl Yumush { .top_0() .bottom_0() .w(px(stroke::LINE)) - .bg(palette.border), + .bg(t.thread()), ) - .child(self.message_list(entity, palette)) - .children(self.jump_bottom(entity, palette)) + .child(self.message_list(entity, t)) + .children(self.jump_bottom(entity, t)) } - fn unread_bar(&self, entity: &Entity, palette: Palette) -> Option { - let (anchor, count) = self.chat.unread_anchor?; + fn unread_bar(&self, entity: &Entity, t: Tokens) -> Option { + let (anchor, count) = self.chat.session.unread_anchor?; if self.chat.unread_covered() { return None; } Some( - accent_bar(palette) - .child(w().chat.new_messages(count)) - .child( - div() - .flex() - .gap(px(space::SM)) - .child( - clickable( - "jump_unread", - palette, - entity_action(entity, move |yumush, window, cx| { - yumush.go_to_message(anchor, window, cx) - }), - ) - .child("↑"), + accent_bar(t).child(w().chat.new_messages(count)).child( + div() + .flex() + .gap(px(space::SM)) + .child( + clickable( + "jump_unread", + t, + entity_action(entity, move |yumush, window, cx| { + yumush.go_to_message(anchor, window, cx) + }), ) - .child( - clickable( - "dismiss_unread", - palette, - entity_action(entity, |yumush, _, cx| { - yumush.chat.unread_anchor = None; - cx.notify(); - }), - ) - .child("×"), - ), - ), + .child("↑"), + ) + .child( + clickable( + "dismiss_unread", + t, + entity_action(entity, |yumush, _, cx| { + yumush.chat.session.unread_anchor = None; + cx.notify(); + }), + ) + .child("×"), + ), + ), ) } - fn jump_bottom(&self, entity: &Entity, palette: Palette) -> Option { + fn jump_bottom(&self, entity: &Entity, t: Tokens) -> Option { if !self.chat.away() { return None; } - let unseen = self.chat.unseen; + let unseen = self.chat.session.unseen; Some( clickable( "jump_bottom", - palette, + t, entity_action(entity, |yumush, _, cx| { yumush.chat.jump_to_bottom(); cx.notify(); @@ -1846,8 +1531,8 @@ impl Yumush { .justify_center() .rounded_full() .border_1() - .border_color(palette.border) - .bg(palette.window) + .border_color(t.thread()) + .bg(t.ground()) .child(Icon::new(IconName::ArrowDown).size(px(size::ICON))) .children((unseen > 0).then(|| { div() @@ -1855,7 +1540,7 @@ impl Yumush { .top(px(-space::SM)) .right(px(-space::SM)) .children(unread_badge( - palette, + t, false, Some(&Unread { messages: unseen, @@ -1866,13 +1551,14 @@ impl Yumush { ) } - fn message_list(&self, entity: &Entity, palette: Palette) -> AnyElement { + fn message_list(&self, entity: &Entity, t: Tokens) -> AnyElement { let divider = self .chat .unread_divider(self.user.as_ref().map(|user| user.id)); let entity_scroll = entity.clone(); let glide = self .chat + .session .glide .filter(|(_, _, at)| at.elapsed() < GLIDE + GLIDE_SLACK); let list = div() @@ -1897,101 +1583,48 @@ impl Yumush { }); }) .child(div().flex_1()) - .children((self.chat.history == History::More).then(|| older_button(entity, palette))) + .children((self.chat.session.history == History::More).then(|| older_button(entity, t))) .children( - self.chat - .messages - .iter() - .enumerate() - .filter(|(index, message)| { - message.call.is_none() - || divider == Some(*index) - || self - .chat - .messages - .get(index + 1) - .is_none_or(|next| next.call.is_none()) - || self - .chat - .open_calls - .contains(&self.chat.call_run_end(*index)) - }) - .map(|(index, message)| { - let calls = self.chat.messages[..=index] - .iter() - .rev() - .take_while(|message| message.call.is_some()) - .count(); - let start = index + 1 - calls.max(1); - let calls = self.chat.messages[start..=index] - .iter() - .filter(|message| message.call == Some(CallLog::Started)) - .count(); - let first = start == 0 || { - let previous = &self.chat.messages[start - 1]; - match message.call { - Some(_) => previous.call.is_none(), - None => { - previous.user_id != message.user_id || previous.call.is_some() - } - } - }; - let run = match message.call { - Some(_) - if self - .chat - .open_calls - .contains(&self.chat.call_run_end(index)) => - { - if self.chat.call_run_end(index) == message.id { - CallRun::Open - } else { - CallRun::Single - } - } - _ if calls > 1 => CallRun::Folded(calls), - _ => CallRun::Single, - }; - let first = first - && !(message.call.is_some() - && index != start - && self - .chat - .open_calls - .contains(&self.chat.call_run_end(index))); - let row = render_message( - message, - first, - start > 0, - run, - &self.chat, - self.user.as_ref(), - self.settings.clock(), - entity, - palette, - ); - let row = match glide { - Some((id, _, _)) if id == message.id => div() - .child(row) - .with_animation( - format!("chat_arrive_{id}"), - gpui_kit::Animation::new(GLIDE), - |row, delta| row.opacity(delta), - ) - .into_any_element(), - _ => row, - }; - if divider == Some(index) { - div() - .flex() - .flex_col() - .child(new_divider(palette)) - .child(row) - .into_any_element() - } else { - row - } - }), + message_rows( + &self.chat.session.messages, + &self.chat.session.open_calls, + divider, + ) + .into_iter() + .map(|(index, message, first, run)| { + let row = render_message( + message, + first, + index > 0, + run, + &self.chat, + self.user.as_ref(), + self.settings.clock(), + entity, + t, + ); + let row = match glide { + Some((id, _, _)) if id == message.id => div() + .child(row) + .with_animation( + format!("chat_arrive_{id}"), + gpui_kit::Animation::new(GLIDE), + |row, delta| row.opacity(delta), + ) + .into_any_element(), + _ => row, + }; + if divider == Some(index) { + div() + .flex() + .flex_col() + .child(new_divider(t)) + .child(row) + .into_any_element() + } else { + row + } + }), ); let Some((id, from, _)) = glide else { return list.into_any_element(); @@ -2010,41 +1643,36 @@ impl Yumush { .into_any_element() } - fn composer(&self, entity: &Entity, palette: Palette, cx: &App) -> AnyElement { + fn composer(&self, entity: &Entity, t: Tokens, cx: &App) -> AnyElement { if let Composer::Select { ids } = &self.chat.composer { return div() .p(px(space::LG)) - .child(composer::selection_bar(ids, entity, palette)) + .child(composer::selection_bar(ids, entity, t)) .into_any_element(); } let input = self.chat.message_input.clone(); - let pending = media_view::pending_row(&self.chat.media, entity, palette); - let bar = composer::mode_bar(&self.chat, entity, palette); + let pending = media_view::pending_row(&self.chat.session.media, entity, t); + let bar = composer::mode_bar(&self.chat, entity, t); let entity = entity.clone(); if let VoiceNote::Recording { started, levels, .. - } = &self.chat.media.voice_note + } = &self.chat.session.media.voice_note { return div() .p(px(space::LG)) .children(pending) - .child(voice_note::recording_row( - *started, levels, &entity, palette, - )) + .child(voice_note::recording_row(*started, levels, &entity, t)) .into_any_element(); } let ready = self.chat.message_input.read(cx).text().len() > 0 - || !self.chat.media.pending.is_empty(); + || !self.chat.session.media.pending.is_empty(); composer::format_actions( &self.chat.message_input, - div() - .p(px(space::LG)) - .border_t_1() - .border_color(palette.border), + div().p(px(space::LG)).border_t_1().border_color(t.thread()), ) .children(pending) .children(bar) @@ -2053,7 +1681,7 @@ impl Yumush { .pl(px(space::XS)) .pb(px(space::XS)) .text_size(text(text::CAPTION)) - .text_color(palette.muted) + .text_color(t.dim()) .child(label) })) .child( @@ -2065,7 +1693,7 @@ impl Yumush { .flex() .items_center() .gap(px(space::SM)) - .child(composer::plus_popover(&self.chat, &entity, palette)) + .child(composer::plus_popover(&entity, t)) .child( Textarea::new(&self.chat.message_input) .token(super::glyph::token) @@ -2077,22 +1705,22 @@ impl Yumush { }) .appearance(false) .text_size(text(text::BODY)) - .text_color(palette.text) + .text_color(t.paper()) .flex_1() .min_w_0(), ) .child(super::glyph::picker_button( "composer_emoji", &entity, - palette, + t, super::glyph::insert_into(self.chat.message_input.clone()), )) .when(!ready, |this| { - this.child(voice_note::mic_button(&entity, palette)) + this.child(voice_note::mic_button(&entity, t)) }) .when(ready, |this| { this.child( - clickable("send_button", palette, move |window, cx| { + clickable("send_button", t, move |window, cx| { entity .update(cx, |yumush, cx| yumush.submit_composer(&input, window, cx)) }) @@ -2101,7 +1729,7 @@ impl Yumush { .flex() .items_center() .justify_center() - .text_color(palette.text) + .text_color(t.paper()) .child(super::parts::small_icon(IconName::ArrowUp)), ) }), @@ -2115,7 +1743,7 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) { - if self.chat.view == View::Chat && self.chat.is_selected(community_id) { + if self.chat.session.view == View::Chat && self.chat.is_selected(community_id) { return; } self.show_view(View::Chat, window, cx); @@ -2144,15 +1772,16 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) { - self.chat.friends_open = false; + self.chat.session.friends_open = false; let community_id = community.id; let listed = self .chat + .session .communities .iter() .any(|known| known.id == community_id); if community.kind.is_direct() && !listed { - self.chat.opened = Some(community); + self.chat.session.opened = Some(community); } else { self.chat.insert_community(community); } @@ -2161,14 +1790,15 @@ impl Yumush { } pub(super) fn reload(&mut self, window: &mut Window, cx: &mut Context) { - self.chat.voice.clear(); - self.chat.shares.clear(); + self.chat.session.voice.clear(); + self.chat.session.shares.clear(); self.load_communities(window, cx); self.load_social(window, cx); - if let Some(community_id) = self.chat.selected_community_id { + if let Some(community_id) = self.chat.session.selected_community_id { self.load_members(window, cx); - self.chat.messages.clear(); + self.load_pins(window, cx); + self.chat.session.messages.clear(); self.load_messages(None, window, cx); self.load_voice(community_id, cx); self.load_shares(community_id, cx); @@ -2182,10 +1812,18 @@ impl Yumush { return; }; let _ = this.update(cx, |yumush, cx| { - let known: HashSet = yumush.chat.communities.iter().map(|c| c.id).collect(); + let known: HashSet = yumush + .chat + .session + .communities + .iter() + .map(|c| c.id) + .collect(); yumush.chat.replace_communities(communities); + yumush.end_voice_if_unjoined(cx); let calls: Vec = yumush .chat + .session .communities .iter() .filter(|community| !known.contains(&community.id)) @@ -2200,7 +1838,7 @@ impl Yumush { }) .map(|community| community.id) .collect(); - yumush.chat.ringing.extend(calls); + yumush.chat.session.ringing.extend(calls); yumush.update_ringing(cx); yumush.request_social_avatars(cx); cx.notify(); @@ -2220,20 +1858,21 @@ impl Yumush { let unreads = network.call(ListUnreads).await.unwrap_or_default(); let _ = this.update_in(cx, |yumush, window, cx| { - yumush.chat.unread = unreads + yumush.chat.session.unread = unreads .into_iter() .map(|unread| (unread.community_id, unread)) .collect(); yumush.chat.replace_communities(communities); + yumush.end_voice_if_unjoined(cx); yumush.request_social_avatars(cx); - if yumush.chat.selected_community_id.is_none() { + if yumush.chat.session.selected_community_id.is_none() { let last = yumush .user .as_ref() .and_then(|me| yumush.settings.last_chats.get(&me.id)) .copied(); - let communities = &yumush.chat.communities; + let communities = &yumush.chat.session.communities; let start = last .filter(|last| communities.iter().any(|community| community.id == *last)) .or_else(|| communities.first().map(|community| community.id)); @@ -2248,7 +1887,7 @@ impl Yumush { } fn search_community(&self, window: &mut Window, cx: &mut Context) { - let Some(community_id) = self.chat.selected_community_id else { + let Some(community_id) = self.chat.session.selected_community_id else { return; }; let text = search_text(&self.chat.community_search, cx); @@ -2268,7 +1907,7 @@ impl Yumush { let _ = this.update(cx, |yumush, cx| { if yumush.chat.is_selected(community_id) { - yumush.chat.community_hits = hits; + yumush.chat.session.community_hits = hits; cx.notify(); } }); @@ -2277,7 +1916,7 @@ impl Yumush { } fn load_pins(&self, window: &mut Window, cx: &mut Context) { - let Some(community_id) = self.chat.selected_community_id else { + let Some(community_id) = self.chat.session.selected_community_id else { return; }; let network = self.network.clone(); @@ -2290,7 +1929,7 @@ impl Yumush { let _ = this.update(cx, |yumush, cx| { if yumush.chat.is_selected(community_id) { - yumush.chat.pins = pins; + yumush.chat.session.pins = pins; yumush.request_poll_votes(cx); cx.notify(); } @@ -2300,7 +1939,7 @@ impl Yumush { } fn load_members(&self, window: &mut Window, cx: &mut Context) { - let Some(community_id) = self.chat.selected_community_id else { + let Some(community_id) = self.chat.session.selected_community_id else { return; }; let network = self.network.clone(); @@ -2318,6 +1957,7 @@ impl Yumush { yumush.request_user_avatar(&member.user, cx); yumush .chat + .session .users .insert(member.user.id, member.user.clone()); } @@ -2327,9 +1967,10 @@ impl Yumush { .map(|member| &member.user) .collect::>(), ); - let old = std::mem::replace(&mut yumush.chat.members, members); + let old = std::mem::replace(&mut yumush.chat.session.members, members); yumush .chat + .session .users .extend(old.into_iter().map(|member| (member.user.id, member.user))); yumush.load_bans(window, cx); @@ -2346,18 +1987,29 @@ impl Yumush { if missing.is_empty() { return; } - self.chat.user_requests.extend(missing.iter().copied()); + self.chat + .session + .user_requests + .extend(missing.iter().copied()); let network = self.network.clone(); cx.spawn(async move |this, cx| { for user_id in missing { - let Ok(user) = network.call(GetUser { user_id }).await else { - continue; + let user = match network.call(GetUser { user_id }).await { + Ok(user) => user, + Err(error) => { + if !matches!(error, Fail::Server(_)) { + let _ = this.update(cx, |yumush, _| { + yumush.chat.session.user_requests.remove(&user_id); + }); + } + continue; + } }; let _ = this.update(cx, |yumush, cx| { yumush.request_user_avatar(&user, cx); style::remember(&[&user]); - yumush.chat.users.insert(user.id, user); + yumush.chat.session.users.insert(user.id, user); cx.notify(); }); } @@ -2366,10 +2018,10 @@ impl Yumush { } pub(super) fn load_bans(&self, window: &mut Window, cx: &mut Context) { - if !permission::can_unban(self.actor_rank()) { + if !permission::is_moderator(self.actor_rank()) { return; } - let Some(community_id) = self.chat.selected_community_id else { + let Some(community_id) = self.chat.session.selected_community_id else { return; }; let network = self.network.clone(); @@ -2385,7 +2037,7 @@ impl Yumush { for ban in &bans { yumush.request_user_avatar(&ban.user, cx); } - yumush.chat.bans = bans; + yumush.chat.session.bans = bans; cx.notify(); } }); @@ -2399,19 +2051,19 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) { - self.chat.jump = Some(message_id); + self.chat.session.jump = Some(message_id); self.chat.reveal_jump(); self.continue_jump(window, cx); cx.notify(); } fn continue_jump(&mut self, window: &mut Window, cx: &mut Context) { - if self.chat.jump.is_none() { + if self.chat.session.jump.is_none() { Self::fade_highlight(cx); - } else if self.chat.history == History::More { + } else if self.chat.session.history == History::More { self.load_older_messages(window, cx); } else { - self.chat.jump = None; + self.chat.session.jump = None; } } @@ -2424,14 +2076,14 @@ impl Yumush { } fn load_older_messages(&self, window: &mut Window, cx: &mut Context) { - let Some(oldest_id) = self.chat.messages.first().map(|message| message.id) else { + let Some(oldest_id) = self.chat.session.messages.first().map(|message| message.id) else { return; }; self.load_messages(Some(oldest_id), window, cx); } fn load_messages(&self, before: Option, window: &mut Window, cx: &mut Context) { - let Some(community_id) = self.chat.selected_community_id else { + let Some(community_id) = self.chat.session.selected_community_id else { return; }; let network = self.network.clone(); @@ -2461,7 +2113,7 @@ impl Yumush { let _ = this.update_in(cx, |yumush, window, cx| { if yumush.chat.is_selected(community_id) { let newest = page.last().map(|message| message.id); - let seeking = yumush.chat.jump.is_some(); + let seeking = yumush.chat.session.jump.is_some(); yumush .chat .add_page(page, yumush.user.as_ref().map(|user| user.id)); @@ -2487,16 +2139,17 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) { - if self.chat.pending_message_delete.as_ref() == Some(&message_id) { - self.chat.pending_message_delete = None; + let armed = Armed::DeleteMessage(message_id); + if self.chat.session.armed.as_ref() == Some(&armed) { + self.chat.session.armed = None; self.delete_message(message_id, window, cx); } else { - self.chat.pending_message_delete = Some(message_id); + self.chat.session.armed = Some(armed.clone()); cx.spawn(async move |this, cx| { cx.background_executor().timer(DELETE_CONFIRM).await; let _ = this.update(cx, |yumush, cx| { - if yumush.chat.pending_message_delete.as_ref() == Some(&message_id) { - yumush.chat.pending_message_delete = None; + if yumush.chat.session.armed.as_ref() == Some(&armed) { + yumush.chat.session.armed = None; cx.notify(); } }); @@ -2529,7 +2182,7 @@ impl Yumush { } }; let _ = this.update(cx, |yumush, cx| { - yumush.chat.edits.insert(message_id, edits); + yumush.chat.session.edits.insert(message_id, edits); cx.notify(); }); }) @@ -2551,8 +2204,7 @@ impl Yumush { } let _ = this.update(cx, |yumush, cx| { - yumush.leave_voice_in(community_id, cx); - yumush.chat.remove_community(community_id); + yumush.forget_community(community_id, cx); cx.notify(); }); }) @@ -2569,7 +2221,7 @@ impl Yumush { }; let _ = this.update(cx, |yumush, cx| { - yumush.chat.voice.insert(community_id, participants); + yumush.chat.session.voice.insert(community_id, participants); yumush.request_authors(cx); cx.notify(); }); @@ -2619,10 +2271,10 @@ impl Yumush { let muted = muted || yumush.is_server_muted() || yumush.hidden_in(community_id); yumush.network.set_muted(muted); - yumush.chat.voice.insert(community_id, participants); + yumush.chat.session.voice.insert(community_id, participants); yumush.request_authors(cx); yumush.load_shares(community_id, cx); - yumush.chat.voice_state = VoiceState::In { + yumush.chat.session.voice_state = VoiceState::In { community_id, muted, deafened, @@ -2675,14 +2327,27 @@ impl Yumush { } } + pub(super) fn forget_community(&mut self, community_id: Id, cx: &mut Context) { + self.leave_voice_in(community_id, cx); + self.chat.remove_community(community_id); + } + + pub(super) fn end_voice_if_unjoined(&mut self, cx: &mut Context) { + if let Some(community_id) = self.chat.voice_community() + && !self.chat.joined(community_id) + { + self.end_voice(cx); + } + } + pub(super) fn is_server_muted(&self) -> bool { self.user .as_ref() - .is_some_and(|me| self.chat.server_muted.contains(&me.id)) + .is_some_and(|me| self.chat.session.server_muted.contains(&me.id)) } fn hidden_in(&self, community_id: Id) -> bool { - self.chat.ghost || !self.chat.joined(community_id) + self.chat.session.ghost || !self.chat.joined(community_id) } pub(super) fn hidden_in_voice(&self) -> bool { @@ -2711,7 +2376,7 @@ impl Yumush { } pub(super) fn set_call_muted(&mut self, value: bool) { - if let VoiceState::In { muted, .. } = &mut self.chat.voice_state { + if let VoiceState::In { muted, .. } = &mut self.chat.session.voice_state { *muted = value; self.network.set_muted(value); } @@ -2720,7 +2385,7 @@ impl Yumush { fn confirm_ghost_speak(&mut self, window: &mut Window, cx: &mut Context) { let entity = cx.entity(); window.open_dialog(cx, move |dialog, _, cx| { - let palette = super::palette(cx); + let t = Tokens::of(cx); let speak = entity.clone(); dialog.title(w().chat.ghost_title).child( @@ -2731,7 +2396,7 @@ impl Yumush { .child( div() .text_size(text(text::LABEL)) - .text_color(palette.muted) + .text_color(t.dim()) .child(w().chat.ghost_hint), ) .child( @@ -2743,14 +2408,14 @@ impl Yumush { "ghost_speak_cancel", w().chat.cancel, parts::Press::Plain, - palette.tokens, + t, |window, cx| window.close_dialog(cx), )) .child(parts::button( "ghost_speak_confirm", w().chat.speak, parts::Press::Primary, - palette.tokens, + t, move |window, cx| { window.close_dialog(cx); speak.update(cx, |yumush, cx| yumush.set_muted(false, cx)); @@ -2762,7 +2427,7 @@ impl Yumush { } pub(super) fn toggle_deafen(&mut self, cx: &mut Context) { - if let VoiceState::In { deafened, .. } = &mut self.chat.voice_state { + if let VoiceState::In { deafened, .. } = &mut self.chat.session.voice_state { *deafened = !*deafened; self.network.set_deafened(*deafened); } @@ -2771,11 +2436,11 @@ impl Yumush { pub(super) fn start_stats_push(&mut self, cx: &mut Context) { let network = self.network.clone(); - self.chat.stats_task = Some(cx.spawn(async move |this, cx| { + self.chat.session.stats_task = Some(cx.spawn(async move |this, cx| { loop { let Ok(stats) = this.update(cx, |yumush, _| { yumush.refresh_usage(); - yumush.chat.stats.clone() + yumush.chat.session.stats.clone() }) else { break; }; @@ -2788,7 +2453,7 @@ impl Yumush { fn start_voice_poll(&mut self, cx: &mut Context) { let network = self.network.clone(); - self.chat.voice_task = Some(cx.spawn(async move |this, cx| { + self.chat.session.voice_task = Some(cx.spawn(async move |this, cx| { let mut sampled = Instant::now(); loop { cx.background_executor().timer(WAVE_INTERVAL).await; @@ -2803,30 +2468,33 @@ impl Yumush { if yumush.chat.voice_community().is_none() { return false; } - if let (Some(sample), Some(share)) = (&sample, &share) { - let up = sample.traffic.up_kbps - + share - .sending - .iter() - .map(|(_, layer)| layer.kbps as f32) - .sum::(); - let down = sample.traffic.down_kbps - + share - .watching - .iter() - .map(|(_, _, stats)| stats.kbps as f32) - .sum::(); - let traffic = &mut yumush.chat.stats.traffic; - traffic.push_back((sample.at_ms, up, down)); - while traffic.len() > SAMPLE_HISTORY { - traffic.pop_front(); - } - } - if sample.is_some() { + if due { yumush.refresh_usage(); } + if let Some(share) = share { + if let Some(sample) = &sample { + let up = sample.traffic.up_kbps + + share + .sending + .iter() + .map(|(_, layer)| layer.kbps as f32) + .sum::(); + let down = sample.traffic.down_kbps + + share + .watching + .iter() + .map(|(_, _, stats)| stats.kbps as f32) + .sum::(); + let traffic = &mut yumush.chat.session.stats.traffic; + traffic.push_back((sample.at_ms, up, down)); + while traffic.len() > SAMPLE_HISTORY { + traffic.pop_front(); + } + } + yumush.chat.record_share(share); + } if let Some(sample) = sample { - let samples = &mut yumush.chat.stats.voice; + let samples = &mut yumush.chat.session.stats.voice; tracing::debug!( target: "metrics", up = sample.traffic.up_kbps, @@ -2839,15 +2507,10 @@ impl Yumush { while samples.len() > SAMPLE_HISTORY { samples.pop_front(); } - cx.notify(); } - if let Some(share) = share { - yumush.chat.record_share(share); + if due { cx.notify(); } - if due && yumush.chat.stats_at.is_some() { - yumush.refresh_usage(); - } yumush.update_waves(levels, cx); true }); @@ -2864,7 +2527,7 @@ impl Yumush { .voice_community() .is_some_and(|community_id| self.chat.voice_ids(community_id).contains(&user_id)); if !in_call || self.is_me(user_id) { - self.chat.user_volume = None; + self.chat.session.volume_popover = None; return; } let volume = self.user_volume(user_id); @@ -2878,14 +2541,10 @@ impl Yumush { let SliderEvent::Change(value) = event else { return; }; - let volumes = &mut this.settings.voice.user_volumes; - match value.start() { - volume if volume == DEFAULT_USER_VOLUME => volumes.remove(&user_id), - volume => volumes.insert(user_id, volume), - }; + this.set_user_volume(user_id, value.start()); this.commit_settings(cx); }); - self.chat.user_volume = Some(UserVolume { + self.chat.session.volume_popover = Some(UserVolume { user_id, slider, _subscription: subscription, @@ -2903,12 +2562,8 @@ impl Yumush { } else { 0. }; - let volumes = &mut self.settings.voice.user_volumes; - match volume { - DEFAULT_USER_VOLUME => volumes.remove(&user_id), - volume => volumes.insert(user_id, volume), - }; - if let Some(user_volume) = self.chat.user_volume.as_ref() { + self.set_user_volume(user_id, volume); + if let Some(user_volume) = self.chat.session.volume_popover.as_ref() { user_volume .slider .update(cx, |slider, cx| slider.set_value(volume, window, cx)); @@ -2916,6 +2571,15 @@ impl Yumush { self.commit_settings(cx); } + fn set_user_volume(&mut self, user_id: Id, volume: f32) { + let volumes = &mut self.settings.voice.user_volumes; + if volume == DEFAULT_USER_VOLUME { + volumes.remove(&user_id); + } else { + volumes.insert(user_id, volume); + } + } + pub(super) fn user_volume(&self, user_id: Id) -> f32 { self.settings .voice @@ -2931,26 +2595,24 @@ impl Yumush { .voice_flags() .is_some_and(|(_, deafened)| deafened); let me = self.user.as_ref().map(|user| user.id); - if self.chat.waves.update(levels, me, deafened) { + if self.chat.session.waves.update(levels, me, deafened) { cx.notify(); } } - fn voice_toggle(&self, entity: &Entity, palette: Palette) -> Option { - let community_id = self.chat.selected_community_id?; + fn voice_toggle(&self, entity: &Entity, t: Tokens) -> Option { + let community_id = self.chat.session.selected_community_id?; let direct = self.is_direct(community_id); let in_voice = self.chat.in_voice(community_id); if !direct || !(in_voice || self.can_join_voice(community_id)) { return None; } - let t = palette.tokens; let users = self.voice_users(community_id); - let (icon, label) = match (direct, in_voice) { - (true, false) => (IconName::Phone, w().chat.call), - (true, true) => (IconName::PhoneOff, w().chat.hang_up), - (false, false) => (IconName::Headphones, w().chat.join), - (false, true) => (IconName::Headphones, w().chat.leave), + let (icon, label) = if in_voice { + (IconName::PhoneOff, w().chat.hang_up) + } else { + (IconName::Phone, w().chat.call) }; let ink = if in_voice { super::parts::Ink::Bad @@ -2969,7 +2631,7 @@ impl Yumush { Some( div() - .id(format!("voice_toggle_{direct}_{in_voice}")) + .id(format!("voice_toggle_{in_voice}")) .h(px(size::CONTROL_SM)) .px(px(space::MD)) .flex() @@ -2986,7 +2648,7 @@ impl Yumush { } fn can_join_voice(&self, community_id: Id) -> bool { - permission::can_join_voice(self.actor_rank()) + permission::is_member(self.actor_rank()) && (self.is_builder() || self.chat.voice_enabled(community_id)) && self .chat @@ -2998,12 +2660,12 @@ impl Yumush { self.chat .voice_ids(community_id) .iter() - .filter(|id| !(self.chat.ghost && self.is_me(**id))) + .filter(|id| !(self.chat.session.ghost && self.is_me(**id))) .filter_map(|id| self.chat.member(*id)) .collect() } - fn calling_hint(&self, palette: Palette) -> Option
{ + fn calling_hint(&self, t: Tokens) -> Option
{ let community = self.chat.selected_community()?; let direct = self.is_direct(community.id); let alone = self.chat.in_voice(community.id) @@ -3015,18 +2677,16 @@ impl Yumush { (direct && alone).then(|| { div() - .text_color(palette.muted) + .text_color(t.dim()) .text_size(text(text::CAPTION)) .child(w().chat.calling) }) } - fn call_banner(&self, entity: &Entity, palette: Palette) -> Option
{ + fn call_banner(&self, entity: &Entity, t: Tokens) -> Option
{ let (community_id, caller) = self.incoming_call()?; - let accept_id = community_id; - Some( - accent_bar(palette) + accent_bar(t) .child( div() .flex() @@ -3042,12 +2702,12 @@ impl Yumush { .child( clickable( "accept_call", - palette, + t, entity_action(entity, move |yumush, window, cx| { - yumush.accept_call(accept_id, window, cx) + yumush.accept_call(community_id, window, cx) }), ) - .text_color(palette.ok) + .text_color(t.hue(Hue::Mint)) .font_weight(FontWeight::MEDIUM) .px(px(space::SM)) .rounded(px(radius::SM)) @@ -3056,12 +2716,12 @@ impl Yumush { .child( clickable( "decline_call", - palette, + t, entity_action(entity, move |yumush, window, cx| { yumush.decline_call(community_id, window, cx) }), ) - .text_color(palette.danger) + .text_color(t.bad()) .font_weight(FontWeight::MEDIUM) .px(px(space::SM)) .rounded(px(radius::SM)) @@ -3084,7 +2744,7 @@ impl Yumush { .any(|id| !self.is_me(*id)); let ringing = calling && !self.chat.in_voice(community.id) - && self.chat.ringing.contains(&community.id); + && self.chat.session.ringing.contains(&community.id); ringing.then(|| (community.id, peer.clone())) }) } @@ -3093,24 +2753,27 @@ impl Yumush { self.user .as_ref() .is_some_and(|me| self.presence_of(me.id) == Presence::Online) - && !self.chat.muted.contains(&community_id) + && !self.chat.session.muted.contains(&community_id) } pub(super) fn update_ringing(&mut self, cx: &mut Context) { if self.incoming_call().is_none() { - self.chat.ring_task = None; + self.chat.session.ring_task = None; return; } - if self.chat.ring_task.is_some() { + if self.chat.session.ring_task.is_some() { return; } - self.chat.ring_task = Some(cx.spawn(async move |this, cx| { + self.chat.session.ring_task = Some(cx.spawn(async move |this, cx| { for _ in 0..RING_LIMIT { let ringing = this.update(cx, |yumush, _| match yumush.incoming_call() { Some((community_id, _)) => { if yumush.ring_allowed(community_id) { - yumush.network.play_ring(&yumush.settings.voice); + crate::voice::play_sound( + crate::voice::Sound::Ring, + &yumush.settings.voice, + ); } true } @@ -3125,14 +2788,14 @@ impl Yumush { } fn accept_call(&mut self, community_id: Id, window: &mut Window, cx: &mut Context) { - self.chat.ringing.remove(&community_id); + self.chat.session.ringing.remove(&community_id); self.select_community(community_id, window, cx); self.toggle_voice(community_id, window, cx); self.update_ringing(cx); } fn decline_call(&mut self, community_id: Id, window: &mut Window, cx: &mut Context) { - self.chat.ringing.remove(&community_id); + self.chat.session.ringing.remove(&community_id); self.update_ringing(cx); cx.notify(); @@ -3142,8 +2805,8 @@ impl Yumush { }); } - fn stage_controls(&self, entity: &Entity, palette: Palette) -> Option { - let community_id = self.chat.selected_community_id?; + fn stage_controls(&self, entity: &Entity, t: Tokens) -> Option { + let community_id = self.chat.session.selected_community_id?; if self.voice_users(community_id).is_empty() || !self.in_stage_chat() { return None; } @@ -3157,7 +2820,7 @@ impl Yumush { .gap(px(space::XXS)) .child(stage_button( entity, - palette, + t, Stage::Strip, current == Stage::Strip, IconName::GalleryHorizontal, @@ -3166,7 +2829,7 @@ impl Yumush { )) .child(stage_button( entity, - palette, + t, Stage::Grid, current == Stage::Grid, IconName::LayoutGrid, @@ -3175,7 +2838,7 @@ impl Yumush { )) .child(stats_button( entity, - palette, + t, self.chat.stats_at == Some(StatsAt::Header), )), ) @@ -3192,10 +2855,10 @@ struct MemberRow { fn members_column( entity: &Entity, yumush: &Yumush, - palette: Palette, + t: Tokens, ) -> Option> { let chat = &yumush.chat; - let community_id = chat.selected_community_id?; + let community_id = chat.session.selected_community_id?; let group = chat .selected_community() .is_some_and(|community| community.kind.is_group()); @@ -3204,16 +2867,17 @@ fn members_column( } let voice = chat.voice_ids(community_id); let members: Vec = chat + .session .members .iter() .map(|member| MemberRow { user: member.user.clone(), in_voice: voice.contains(&member.user.id), - muted: chat.server_muted.contains(&member.user.id), + muted: chat.session.server_muted.contains(&member.user.id), presence: yumush.presence_of(member.user.id), }) .collect(); - let avatars = &chat.avatars; + let avatars = &chat.session.avatars; let entity = entity.clone(); let row = |MemberRow { user, @@ -3228,27 +2892,27 @@ fn members_column( user.id, kind, yumush.is_watching(user.id, kind), - (kind == Kind::Screen && chat.waves.share_audible(user.id)) - .then(|| chat.waves.share(user.id)) + (kind == Kind::Screen && chat.session.waves.share_audible(user.id)) + .then(|| chat.session.waves.share(user.id).map(to_bands)) .flatten(), - palette, + t, ) }) }; let line = in_voice.then(|| { - let speaking = chat.waves.speaking.contains(&user.id); + let speaking = chat.session.waves.speaking.contains(&user.id); div() .flex_1() .min_w(px(size::CONTROL)) .h(px(space::LG)) .child(super::parts::voice_line( - chat.waves.voice(user.id), + chat.session.waves.voice(user.id).map(to_bands).as_ref(), if speaking { - super::parts::Voice::Live(palette.tokens.person(user.id)) + super::parts::Voice::Live(t.person(user.id)) } else { super::parts::Voice::Quiet }, - palette.tokens, + t, )) }); div() @@ -3274,16 +2938,10 @@ fn members_column( .gap(px(space::SM)) .rounded(px(radius::MD)) .child(presence_avatar( - avatar( - palette, - user, - px(size::ICON), - text(text::CAPTION), - avatars, - ), + avatar(t, user, px(size::ICON), text(text::CAPTION), avatars), *presence, px(size::ICON), - palette, + t, )) .child( div() @@ -3299,14 +2957,14 @@ fn members_column( .child(user.username.clone()) .children(muted.then(|| { super::parts::small_icon(IconName::MicOff) - .text_color(palette.danger) + .text_color(t.bad()) })), ) .children((!user.status.is_empty() && !in_voice).then( || { div() .text_size(text(text::CAPTION)) - .text_color(palette.muted) + .text_color(t.dim()) .min_w_0() .child(super::glyph::line( user.status.clone().into(), @@ -3315,7 +2973,7 @@ fn members_column( }, )), ), - palette, + t, ), )), ) @@ -3329,7 +2987,7 @@ fn members_column( .flex() .flex_col() .child( - super::parts::caption_head(format!("{title} · {}", rows.len()), palette.tokens) + super::parts::caption_head(format!("{title} · {}", rows.len()), t) .pb(px(space::XS)), ) .children(rows.into_iter().map(row)) @@ -3340,10 +2998,10 @@ fn members_column( let action = entity_action(&entity, move |yumush, window, cx| { yumush.toggle_voice(community_id, window, cx) }); - super::parts::pill("margin_join", palette.tokens, action) + super::parts::pill("margin_join", t, action) .self_start() .gap(px(space::SM)) - .text_color(palette.tokens.ground()) + .text_color(t.ground()) .font_weight(FontWeight::SEMIBOLD) .child(super::parts::small_icon(IconName::Headphones)) .child(w().chat.join_voice) @@ -3374,7 +3032,7 @@ fn members_column( .flex() .flex_col() .gap(px(space::LG)) - .child(room_head(yumush, palette)) + .child(room_head(yumush, t)) .children(call) .children(section(w().common.presence_online, online)) .children(section(w().common.presence_offline, offline)), @@ -3384,23 +3042,25 @@ fn members_column( const GLIDE: Duration = Duration::from_millis(240); const GLIDE_SLACK: Duration = Duration::from_millis(100); -fn room_head(yumush: &Yumush, palette: Palette) -> Div { +fn room_head(yumush: &Yumush, t: Tokens) -> Div { let chat = &yumush.chat; let online = chat + .session .members .iter() .filter(|member| yumush.is_online(member.user.id)) .count(); div().px(px(space::SM)).child(super::parts::words( - w().community_card.people(chat.members.len(), online), + w().community_card + .people(chat.session.members.len(), online), super::parts::Text::Caption, super::parts::Ink::Dim, - palette.tokens, + t, )) } -fn accent_bar(palette: Palette) -> Div { +fn accent_bar(t: Tokens) -> Div { div() .flex() .items_center() @@ -3409,12 +3069,12 @@ fn accent_bar(palette: Palette) -> Div { .px(px(space::MD)) .py(px(space::XS)) .text_size(text(text::LABEL)) - .text_color(palette.text) + .text_color(t.paper()) .border_b_1() - .border_color(palette.border) + .border_color(t.thread()) } -fn thread_dot(mine: bool, palette: Palette) -> Div { +fn thread_dot(mine: bool, t: Tokens) -> Div { let dot = div() .absolute() .left(px(-(space::LG + space::XS))) @@ -3422,33 +3082,31 @@ fn thread_dot(mine: bool, palette: Palette) -> Div { .size(px(space::SM)) .rounded_full(); if mine { - dot.bg(palette.text) + dot.bg(t.paper()) } else { - dot.border_1() - .border_color(palette.tokens.faint()) - .bg(palette.window) + dot.border_1().border_color(t.faint()).bg(t.ground()) } } -fn new_divider(palette: Palette) -> impl IntoElement { +fn new_divider(t: Tokens) -> impl IntoElement { div() .flex() .items_center() .gap(px(space::SM)) .my(px(space::SM)) - .child(div().flex_1().h(px(stroke::LINE)).bg(palette.accent)) + .child(div().flex_1().h(px(stroke::LINE)).bg(t.paper())) .child( div() .text_size(text(text::CAPTION)) - .text_color(palette.accent) + .text_color(t.paper()) .child(w().chat.new), ) } -fn older_button(entity: &Entity, palette: Palette) -> impl IntoElement { +fn older_button(entity: &Entity, t: Tokens) -> impl IntoElement { let entity = entity.clone(); - clickable("load_older_button", palette, move |window, cx| { + clickable("load_older_button", t, move |window, cx| { entity.update(cx, |yumush, cx| yumush.load_older_messages(window, cx)); }) .self_center() @@ -3457,7 +3115,7 @@ fn older_button(entity: &Entity, palette: Palette) -> impl IntoElement { .flex() .items_center() .rounded(px(radius::MD)) - .text_color(palette.muted) + .text_color(t.dim()) .child("↑") } @@ -3479,6 +3137,56 @@ enum CallRun { Open, } +pub(super) fn to_bands(bars: &[f32]) -> VecDeque { + bars.iter().copied().collect() +} + +fn message_rows<'a>( + messages: &'a [Message], + open_calls: &HashSet, + divider: Option, +) -> Vec<(usize, &'a Message, bool, CallRun)> { + let mut rows = Vec::new(); + let mut start = 0; + for run in messages.chunk_by(|a, b| a.call.is_some() == b.call.is_some()) { + let is_call = run[0].call.is_some(); + let open = is_call && open_calls.contains(&run[run.len() - 1].id); + let started = run + .iter() + .filter(|message| message.call == Some(CallLog::Started)) + .count(); + for (offset, message) in run.iter().enumerate() { + let index = start + offset; + let last = offset + 1 == run.len(); + if is_call && !open && !last && divider != Some(index) { + continue; + } + let first = match message.call { + Some(_) => { + (index == start || !open) + && start + .checked_sub(1) + .is_some_and(|previous| messages[previous].call.is_none()) + } + None => match index.checked_sub(1).map(|previous| &messages[previous]) { + None => true, + Some(previous) => { + previous.user_id != message.user_id || previous.call.is_some() + } + }, + }; + let kind = match (is_call, last, open, started) { + (true, true, true, _) => CallRun::Open, + (true, true, false, 2..) => CallRun::Folded(started), + _ => CallRun::Single, + }; + rows.push((index, message, first, kind)); + } + start += run.len(); + } + rows +} + fn render_call( message: &Message, call: CallLog, @@ -3487,7 +3195,7 @@ fn render_call( chat: &Chat, me: Option<&User>, entity: &Entity, - palette: Palette, + t: Tokens, ) -> AnyElement { let mine = me.is_some_and(|me| me.id == message.user_id); let author = chat @@ -3508,16 +3216,16 @@ fn render_call( .child(super::parts::small_icon(IconName::ChevronUp)), ), }; - call_line(call, author, mine, palette) + call_line(call, author, mine, t) .children(toggle.map(|toggle| { toggle .id(format!("calls_{message_id}")) .cursor_pointer() - .text_color(palette.tokens.faint()) + .text_color(t.faint()) .on_click(move |_, _, cx| { entity.update(cx, |yumush, cx| { - if !yumush.chat.open_calls.remove(&message_id) { - yumush.chat.open_calls.insert(message_id); + if !yumush.chat.session.open_calls.remove(&message_id) { + yumush.chat.session.open_calls.insert(message_id); } if !yumush.chat.away() { yumush.chat.jump_to_bottom(); @@ -3532,12 +3240,12 @@ fn render_call( .into_any_element() } -pub(super) fn call_line(call: CallLog, author: &str, mine: bool, palette: Palette) -> Div { +pub(super) fn call_line(call: CallLog, author: &str, mine: bool, t: Tokens) -> Div { let w = &w().chat; let (icon, color) = match call { - CallLog::Started | CallLog::Ended { .. } => (IconName::Phone, palette.muted), - CallLog::Declined => (IconName::PhoneOff, palette.danger), - CallLog::Missed => (IconName::PhoneMissed, palette.danger), + CallLog::Started | CallLog::Ended { .. } => (IconName::Phone, t.dim()), + CallLog::Declined => (IconName::PhoneOff, t.bad()), + CallLog::Missed => (IconName::PhoneMissed, t.bad()), }; let label = match call { CallLog::Started if mine => w.call_started_mine.to_string(), @@ -3553,14 +3261,14 @@ pub(super) fn call_line(call: CallLog, author: &str, mine: bool, palette: Palett .flex() .items_center() .text_size(text(text::CAPTION)) - .text_color(palette.muted) + .text_color(t.dim()) .child( div() .absolute() .left(px( -(space::LG + space::XS) - (size::ICON_SM - space::SM) / 2. )) - .bg(palette.window) + .bg(t.ground()) .child(super::parts::small_icon(icon).text_color(color)), ) .child(label) @@ -3575,29 +3283,21 @@ fn render_message( me: Option<&User>, clock: &'static str, entity: &Entity, - palette: Palette, + t: Tokens, ) -> AnyElement { if let Some(call) = message.call { - return render_call( - message, - call, - run, - first && spaced, - chat, - me, - entity, - palette, - ); + return render_call(message, call, run, first && spaced, chat, me, entity, t); } let builder = me.is_some_and(|me| permission::is_builder(me.role)); - let collapsed = message.deleted && !chat.revealed.contains(&message.id); + let code = message.body.contains("```"); + let collapsed = message.deleted && !chat.session.revealed.contains(&message.id); let author = chat.author(message.user_id); let username = author.map_or(w().chat.unknown, |user| user.username.as_str()); let name = div().flex().items_center().gap(px(space::SM)).child( div() .id(format!("author_name_{}", message.id)) .font_weight(FontWeight::SEMIBOLD) - .text_color(palette.text) + .text_color(t.paper()) .when(author.is_some(), |this| { this.hover(|style| style.underline()) }) @@ -3609,6 +3309,7 @@ fn render_message( let selecting = matches!(chat.composer, Composer::Select { .. }); let selected = matches!(&chat.composer, Composer::Select { ids } if ids.contains(&message.id)); let highlighted = chat + .session .highlight .as_ref() .is_some_and(|(id, at)| id == &message.id && at.elapsed() < HIGHLIGHT_TTL); @@ -3621,7 +3322,7 @@ fn render_message( let id = message.id; move |hovered, _, cx| { entity.update(cx, |yumush, cx| { - if message_actions::track(&mut yumush.chat.hover_row, id, *hovered) { + if message_actions::track(&mut yumush.chat.session.hover_row, id, *hovered) { cx.notify(); } }); @@ -3631,16 +3332,12 @@ fn render_message( .flex() .flex_col() .min_w_0() - .hover(|style| style.bg(palette.hover)) - .when(chat.engaged(message.id), |this| this.bg(palette.hover)) - .when(message.deleted, |this| { - this.text_color(palette.tokens.faint()) - }) + .hover(|style| style.bg(t.hov())) + .when(chat.engaged(message.id), |this| this.bg(t.hov())) + .when(message.deleted, |this| this.text_color(t.faint())) .when(first && spaced && !selecting, |this| this.mt(px(space::LG))) - .when(highlighted, |this| this.bg(palette.tokens.press())) - .when(mentioned, |this| { - this.border_l_2().border_color(palette.accent) - }) + .when(highlighted, |this| this.bg(t.press())) + .when(mentioned, |this| this.border_l_2().border_color(t.paper())) .when(first, |this| { let author = match author { Some(user) => profile_popover( @@ -3661,12 +3358,12 @@ fn render_message( .items_center() .gap(px(space::SM)) .mb(px(space::XXS)) - .child(thread_dot(if selecting { selected } else { mine }, palette)) + .child(thread_dot(if selecting { selected } else { mine }, t)) .child(author) .child( div() .text_size(text(text::CAPTION)) - .text_color(palette.muted) + .text_color(t.dim()) .child(millis_time(message.created_at, clock)), ), ) @@ -3679,110 +3376,108 @@ fn render_message( .items_center() .gap(px(space::SM)) .when(selecting && !first, |this| { - this.child(thread_dot(selected, palette)) + this.child(thread_dot(selected, t)) }) .child( div() .min_w_0() .max_w(px(size::PAGE)) - .when(message.body.contains("```"), |this| this.w_full()) + .when(code, |this| this.w_full()) .flex() .flex_col() .gap(px(space::SM)) .when(collapsed, |this| { - this.child(message_actions::reveal_deleted(message.id, entity, palette)) + this.child(message_actions::reveal_deleted(message.id, entity, t)) }) .when(!collapsed, |this| { - this.children(message_actions::quote_line( - message, chat, entity, palette, - )) - .when(!message.body.is_empty(), |this| { - this.child( - div() - .min_w_0() - .when(message.body.contains("```"), |this| this.w_full()) - .flex() - .flex_wrap() - .items_baseline() - .gap(px(space::XS)) - .text_size(text(text::BODY)) - .line_height(relative(1.55)) - .text_color(palette.body) - .child( - div() - .min_w_0() - .when(message.body.contains("```"), |this| { - this.w_full() - }) - .child( - TextView::markdown( - format!("message-body-{}", message.id), - crate::emoji::markdown(&hard_breaks( - &message.body, - )), - ) - .markdown_extensions(super::glyph::extensions()) - .selectable(true), - ), - ) - .when(message.edited || message.deleted, |this| { - this.child( + this.children(message_actions::quote_line(message, chat, entity, t)) + .when(!message.body.is_empty(), |this| { + this.child( + div() + .min_w_0() + .when(code, |this| this.w_full()) + .flex() + .flex_wrap() + .items_baseline() + .gap(px(space::XS)) + .text_size(text(text::BODY)) + .line_height(relative(1.55)) + .text_color(t.paper()) + .child( div() - .flex() - .gap(px(space::SM)) - .text_size(text(text::CAPTION)) - .text_color(palette.muted) - .children(message.edited.then(|| { - message_actions::edited_mark( - message, builder, entity, palette, + .min_w_0() + .when(code, |this| this.w_full()) + .child( + TextView::markdown( + format!("message-body-{}", message.id), + crate::emoji::markdown(&hard_breaks( + &message.body, + )), ) - })) - .children(message.deleted.then(|| { - message_actions::collapse_deleted( - message.id, entity, + .markdown_extensions( + super::glyph::extensions(), ) - })), + .selectable(true), + ), ) - }), - ) - }) - .children(media_view::attachments( - &message.attachments, - &chat.media, - entity, - palette, - )) - .children(snippet::snippet_card(message, clock, chat, entity, palette)) - .children(message.poll.as_ref().map(|poll| { - poll::poll_card( - poll, - poll::PollMode::Live(message), - me, - chat, + .when(message.edited || message.deleted, |this| { + this.child( + div() + .flex() + .gap(px(space::SM)) + .text_size(text(text::CAPTION)) + .text_color(t.dim()) + .children(message.edited.then(|| { + message_actions::edited_mark( + message, builder, entity, t, + ) + })) + .children(message.deleted.then(|| { + message_actions::collapse_deleted( + message.id, entity, + ) + })), + ) + }), + ) + }) + .children(media_view::attachments( + &message.attachments, + &chat.session.media, entity, - palette, + t, + )) + .children(snippet::snippet_card(message, clock, chat, entity, t)) + .children(message.poll.as_ref().map(|poll| { + poll::poll_card( + poll, + poll::PollMode::Live(message), + me, + chat, + entity, + t, + ) + })) + .children(media_view::embeds(message, &chat.session.media, t)) + .children( + (!message.reactions.is_empty()).then(|| { + message_actions::reactions(message, me, entity, t) + }), ) - })) - .children(media_view::embeds(message, &chat.media, palette)) - .children( - (!message.reactions.is_empty()).then(|| { - message_actions::reactions(message, me, entity, palette) - }), - ) }), ) - .children(message.pinned.then(|| message_actions::pin_mark(palette))) + .children(message.pinned.then(|| message_actions::pin_mark(t))) .children((!selecting && !message.deleted).then(|| { div() .absolute() .right_0() .bottom(gpui_kit::relative(1.)) - .child(message_actions::actions(message, chat, me, entity, palette)) + .child(message_actions::actions(message, chat, me, entity, t)) })), ) .children( - (chat.report == Some(ReportTarget::Message(message.id))) - .then(|| message_actions::report_bar(&chat.report_reason, entity, palette)), + (chat.session.report == Some(ReportTarget::Message(message.id))) + .then(|| message_actions::report_bar(&chat.report_reason, entity, t)), ); if !selecting { @@ -3842,10 +3537,10 @@ fn hard_breaks(body: &str) -> String { lines.join("\n") } -fn stats_button(entity: &Entity, palette: Palette, open: bool) -> impl IntoElement { +fn stats_button(entity: &Entity, t: Tokens, open: bool) -> impl IntoElement { clickable( format!("stats_toggle_{open}"), - palette, + t, entity_action(entity, |yumush: &mut Yumush, _, cx| { yumush.toggle_stats(StatsAt::Header); cx.notify(); @@ -3861,14 +3556,14 @@ fn stats_button(entity: &Entity, palette: Palette, open: bool) -> impl I .items_center() .justify_center() .rounded(px(radius::MD)) - .when(open, |this| this.bg(palette.tokens.press())) - .text_color(if open { palette.text } else { palette.muted }) + .when(open, |this| this.bg(t.press())) + .text_color(if open { t.paper() } else { t.dim() }) .child(super::parts::small_icon(IconName::Activity)) } fn stage_button( entity: &Entity, - palette: Palette, + t: Tokens, layout: Stage, active: bool, icon: IconName, @@ -3877,7 +3572,7 @@ fn stage_button( ) -> impl IntoElement { clickable( format!("stage_{name}_{active}"), - palette, + t, entity_action(entity, move |yumush: &mut Yumush, _, cx| { let next = if active { Stage::Hidden } else { layout }; yumush.set_stage(next, cx) @@ -3889,11 +3584,7 @@ fn stage_button( .items_center() .justify_center() .rounded(px(radius::MD)) - .when(active, |this| this.bg(palette.tokens.press())) - .text_color(if active { - palette.accent - } else { - palette.muted - }) + .when(active, |this| this.bg(t.press())) + .text_color(if active { t.paper() } else { t.dim() }) .child(super::parts::small_icon(icon)) } diff --git a/crates/client/src/gui/chat/admin.rs b/crates/client/src/gui/chat/admin.rs new file mode 100644 index 0000000..b466b32 --- /dev/null +++ b/crates/client/src/gui/chat/admin.rs @@ -0,0 +1,205 @@ +use crate::gui::builder::{BuilderTab, Transfer}; +use crate::gui::{Yumush, new_input}; +use crate::lang::w; +use common::model::{ + Account, AdminActionKind, AdminLogEntry, AttachmentInfo, BanScope, CommunitySummary, + CommunityUsage, DayStat, Id, InviteCode, MessageHit, Overview, Report, ReportStatus, ServerBan, + SessionInfo, UpdateClient, User, UserUsage, VoiceRoom, +}; +use common::stats::Stats; +use gpui_kit::{ + AppContext, Context, Entity, Task, Window, + component::{ + IndexPath, input::InputState, searchable_list::SearchableVec, select::SelectState, + }, +}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum UserEdit { + Password, + Rename, + Timeout, + Ban, +} + +pub struct Admin { + pub builder_password: Entity, + pub builder_rename: Entity, + pub builder_timeout: Entity, + pub builder_ban_reason: Entity, + pub new_username: Entity, + pub new_password: Entity, + pub server_name: Entity, + pub server_limit: Entity, + pub server_user_quota: Entity, + pub server_community_quota: Entity, + pub server_message_retention: Entity, + pub server_attachment_retention: Entity, + pub server_announcement: Entity, + pub server_max_communities: Entity, + pub server_max_message_length: Entity, + pub server_max_avatar: Entity, + pub server_messages_per_minute: Entity, + pub server_logins_per_minute: Entity, + pub invite_uses: Entity, + pub invite_hours: Entity, + pub builder_log_actor: Entity, + pub builder_log_target: Entity, + pub builder_log_action: Entity>>, + pub builder_log_from: Entity, + pub builder_log_to: Entity, + pub builder_search: Entity, + pub builder_friend_search: Entity, + pub builder_message_text: Entity, + pub builder_message_user: Entity, + pub builder_message_community: Entity, + pub builder_message_from: Entity, + pub builder_message_to: Entity, + pub builder_attachment_user: Entity, + pub builder_attachment_community: Entity, + pub builder_tab: BuilderTab, + pub builder_users: Vec, + pub builder_overview: Option, + pub builder_logs: Vec, + pub builder_stats: Vec, + pub builder_communities: Vec, + pub builder_reports: Vec, + pub report_filter: Option, + pub open_reports: usize, + pub builder_messages: Vec, + pub builder_usage_users: Vec, + pub builder_usage_communities: Vec, + pub builder_attachments: Vec, + pub transfer: Option, + pub editing: Option<(Id, UserEdit)>, + pub builder_sessions: Option<(Id, Vec)>, + pub builder_clients: Vec, + pub builder_clients_task: Option>, + pub builder_friends: Vec, + pub builder_bans: Vec, + pub builder_ban_scope: BanScope, + pub builder_invites: Vec, + pub builder_voice_rooms: Vec, + pub server_registration_open: bool, + pub server_maintenance: bool, + pub server_stats: Option, + pub server_stats_task: Option>, +} + +impl Admin { + pub fn new(window: &mut Window, cx: &mut Context) -> Self { + let builder_password = new_input(w().chat.new_password, window, cx); + builder_password.update(cx, |input, cx| input.set_masked(true, window, cx)); + let new_password = new_input(w().chat.password, window, cx); + new_password.update(cx, |input, cx| input.set_masked(true, window, cx)); + + Self { + builder_password, + builder_rename: new_input(w().chat.new_username, window, cx), + builder_timeout: new_input(w().chat.minutes, window, cx), + builder_ban_reason: new_input(w().chat.reason, window, cx), + new_username: new_input(w().chat.username, window, cx), + new_password, + server_name: new_input(w().chat.server_name, window, cx), + server_limit: new_input("", window, cx), + server_user_quota: new_input("", window, cx), + server_community_quota: new_input("", window, cx), + server_message_retention: new_input("", window, cx), + server_attachment_retention: new_input("", window, cx), + server_announcement: new_input(w().chat.announcement, window, cx), + server_max_communities: new_input("", window, cx), + server_max_message_length: new_input(w().chat.max_message_length, window, cx), + server_max_avatar: new_input("", window, cx), + server_messages_per_minute: new_input("", window, cx), + server_logins_per_minute: new_input("", window, cx), + invite_uses: new_input(w().chat.uses, window, cx), + invite_hours: new_input(w().chat.hours, window, cx), + builder_log_actor: new_input(w().chat.actor, window, cx), + builder_log_target: new_input(w().chat.target, window, cx), + builder_log_action: cx.new(|cx| { + SelectState::new( + SearchableVec::new( + std::iter::once(w().chat.all) + .chain( + AdminActionKind::ALL + .into_iter() + .map(AdminActionKind::as_str), + ) + .collect::>(), + ), + Some(IndexPath::new(0)), + window, + cx, + ) + }), + builder_log_from: new_input(w().chat.date_from, window, cx), + builder_log_to: new_input(w().chat.date_to, window, cx), + builder_search: new_input(w().chat.search, window, cx), + builder_friend_search: new_input(w().chat.search, window, cx), + builder_message_text: new_input(w().chat.text, window, cx), + builder_message_user: new_input(w().chat.user, window, cx), + builder_message_community: new_input(w().chat.community, window, cx), + builder_message_from: new_input(w().chat.date_from, window, cx), + builder_message_to: new_input(w().chat.date_to, window, cx), + builder_attachment_user: new_input(w().chat.user, window, cx), + builder_attachment_community: new_input(w().chat.community, window, cx), + builder_tab: BuilderTab::Overview, + builder_users: vec![], + builder_overview: None, + builder_logs: vec![], + builder_stats: vec![], + builder_communities: vec![], + builder_reports: vec![], + report_filter: Some(ReportStatus::Open), + open_reports: 0, + builder_messages: vec![], + builder_usage_users: vec![], + builder_usage_communities: vec![], + builder_attachments: vec![], + transfer: None, + editing: None, + builder_sessions: None, + builder_clients: vec![], + builder_clients_task: None, + builder_friends: vec![], + builder_bans: vec![], + builder_ban_scope: BanScope::Account, + builder_invites: vec![], + builder_voice_rooms: vec![], + server_registration_open: true, + server_maintenance: false, + server_stats: None, + server_stats_task: None, + } + } + + pub fn clear(&mut self) { + self.builder_tab = BuilderTab::Overview; + self.builder_users.clear(); + self.builder_overview = None; + self.builder_logs.clear(); + self.builder_stats.clear(); + self.builder_communities.clear(); + self.builder_reports.clear(); + self.report_filter = Some(ReportStatus::Open); + self.open_reports = 0; + self.builder_messages.clear(); + self.builder_usage_users.clear(); + self.builder_usage_communities.clear(); + self.builder_attachments.clear(); + self.transfer = None; + self.editing = None; + self.builder_sessions = None; + self.builder_clients.clear(); + self.builder_clients_task = None; + self.builder_friends.clear(); + self.builder_bans.clear(); + self.builder_ban_scope = BanScope::Account; + self.builder_invites.clear(); + self.builder_voice_rooms.clear(); + self.server_registration_open = true; + self.server_maintenance = false; + self.server_stats = None; + self.server_stats_task = None; + } +} diff --git a/crates/client/src/gui/chat/poll_draft.rs b/crates/client/src/gui/chat/poll_draft.rs new file mode 100644 index 0000000..2cb2537 --- /dev/null +++ b/crates/client/src/gui/chat/poll_draft.rs @@ -0,0 +1,45 @@ +use crate::gui::composer::{self, PlusMenu}; +use crate::gui::{Yumush, new_input}; +use crate::lang::w; +use common::constant::MINIMUM_POLL_OPTIONS; +use gpui_kit::{Context, Entity, Window, component::input::InputState}; + +pub struct PollDraft { + pub question: Entity, + pub options: Vec>, + pub multiple: bool, + pub public: bool, + pub duration: Option, + pub plus_menu: PlusMenu, + pub expanded: bool, + pub page: usize, +} + +impl PollDraft { + pub fn new(window: &mut Window, cx: &mut Context) -> Self { + Self { + question: new_input(w().chat.question, window, cx), + options: (0..MINIMUM_POLL_OPTIONS) + .map(|_| composer::new_poll_option(window, cx)) + .collect(), + multiple: false, + public: true, + duration: None, + plus_menu: PlusMenu::Menu, + expanded: false, + page: 0, + } + } + + pub fn clear(&mut self, window: &mut Window, cx: &mut Context) { + self.question + .update(cx, |state, cx| state.set_value("", window, cx)); + self.options.truncate(MINIMUM_POLL_OPTIONS); + for input in &self.options { + input.update(cx, |state, cx| state.set_value("", window, cx)); + } + self.multiple = false; + self.public = true; + self.duration = None; + } +} diff --git a/crates/client/src/gui/chat/session.rs b/crates/client/src/gui/chat/session.rs new file mode 100644 index 0000000..284b7f6 --- /dev/null +++ b/crates/client/src/gui/chat/session.rs @@ -0,0 +1,86 @@ +use super::{Armed, CardMenu, History, ReportTarget, UserVolume, View, VoiceState}; +use crate::gui::camera_view::Tile; +use crate::gui::media_view::Media; +use crate::gui::share_view::{Float, Viewer}; +use crate::gui::social::InviteLookup; +use crate::gui::wave::Waves; +use common::model::{ + Ban, Community, Edit, Friends, Id, Invitation, LogEntry, Member, Message, MessageHit, Presence, + Unread, User, +}; +use common::share::Kind; +use common::stats::Stats; +use gpui_kit::{Image, Task}; +use std::{ + collections::{BTreeMap, HashMap, HashSet, VecDeque}, + sync::Arc, + time::Instant, +}; + +#[derive(Default)] +pub struct Session { + pub communities: Vec, + pub selected_community_id: Option, + pub opened: Option, + pub ghost: bool, + pub members: Vec, + pub messages: Vec, + pub pins: Vec, + pub history: History, + pub unread: HashMap, + pub unread_anchor: Option<(Id, u32)>, + pub unseen: u32, + pub muted: HashSet, + pub pinned: HashSet, + pub edits: HashMap>, + pub revealed: HashSet, + pub friends_open: bool, + pub open_calls: HashSet, + pub community_hits: Vec, + pub found: Option, + pub invite: InviteLookup, + pub drafts: HashMap, + pub my_votes: HashMap>, + pub jump: Option, + pub highlight: Option<(Id, Instant)>, + pub glide: Option<(Id, gpui_kit::Pixels, Instant)>, + pub view: View, + pub section: Option<&'static str>, + pub avatars: HashMap>, + pub avatar_requests: HashSet, + pub users: HashMap, + pub user_requests: HashSet, + pub armed: Option, + pub bans: Vec, + pub logs: Vec, + pub friends: Friends, + pub invitations: Vec, + pub card_menu: CardMenu, + pub presences: HashMap, + pub slowed_until: Option, + pub voice: HashMap>, + pub voice_state: VoiceState, + pub server_muted: HashSet, + pub ringing: HashSet, + pub ring_task: Option>, + pub voice_task: Option>, + pub waves: Waves, + pub typing: HashMap>, + pub typing_sent: HashMap, + pub shares: HashMap>, + pub media: Media, + pub viewer: Option, + pub float: Float, + pub tiles: BTreeMap<(Id, Kind), Tile>, + pub camera_task: Option>, + pub storage: Vec<(crate::storage::Store, u64)>, + pub volume_popover: Option, + pub stats_task: Option>, + pub stats: Stats, + pub followed: Option<(Id, Stats)>, + pub share_loss: HashMap<(Id, Kind), VecDeque<(u64, f32)>>, + pub report: Option, + pub hover_row: Option, + pub hover_bar: Option, + pub reacting: Option, +} diff --git a/crates/client/src/gui/community_card.rs b/crates/client/src/gui/community_card.rs index 8a4e1a2..96ff775 100644 --- a/crates/client/src/gui/community_card.rs +++ b/crates/client/src/gui/community_card.rs @@ -6,16 +6,15 @@ use gpui_kit::{ Anchor, Context, Div, Entity, FontWeight, Hsla, IntoElement, ParentElement, Styled, Window, assets::IconName, component::popover::{Popover, PopoverState}, - div, prelude::FluentBuilder as _, px, }; use super::chat::Armed; -use super::parts::{Ink, Text, band, small_icon, stack, words}; +use super::parts::{Ink, Text, band, small_icon, stack, thread, words}; use super::profile::{armed_action, menu_row, yumush_action}; -use super::style::{size, space, stroke, text}; -use super::{Palette, Trigger, Yumush, text}; +use super::style::{Tokens, size, space, text}; +use super::{Trigger, Yumush, text}; use crate::lang::w; use crate::marks::Mark; @@ -36,13 +35,13 @@ pub(super) fn community_popover( .content(move |_, _, cx| { let popover = cx.entity(); let yumush = entity.read(cx); - let palette = super::palette(cx); - let t = palette.tokens; + let t = Tokens::of(cx); let id = community.id; let name = super::community_name(&community).to_string(); - let members = yumush.chat.members.len(); + let members = yumush.chat.session.members.len(); let online = yumush .chat + .session .members .iter() .filter(|member| yumush.is_online(member.user.id)) @@ -56,14 +55,14 @@ pub(super) fn community_popover( &entity, "community_picture", super::community_icon( - palette, + t, &community, px(size::AVATAR_LG), text(text::BODY), - &yumush.chat.avatars, + &yumush.chat.session.avatars, ), super::Zoom::new( - super::picture_of(&community, &yumush.chat.avatars), + super::picture_of(&community, &yumush.chat.session.avatars), false, name.clone(), ), @@ -85,16 +84,16 @@ pub(super) fn community_popover( )), ), ) - .child(div().w_full().h(px(stroke::LINE)).bg(t.thread())) + .child(thread(t)) .child(room_rows( id, true, permission::can_leave(yumush.actor_rank()), - permission::can_manage_community(yumush.actor_rank()), + permission::is_moderator(yumush.actor_rank()), yumush, &entity, &popover, - palette, + t, )) }) } @@ -107,10 +106,10 @@ pub(super) fn room_rows( yumush: &Yumush, entity: &Entity, popover: &Entity, - palette: Palette, + t: Tokens, ) -> Div { - let pinned = yumush.chat.pinned.contains(&id); - let muted = yumush.chat.muted.contains(&id); + let pinned = yumush.chat.session.pinned.contains(&id); + let muted = yumush.chat.session.muted.contains(&id); let words = &w().sidebar; let row = |key: &'static str, label: &'static str, @@ -122,7 +121,7 @@ pub(super) fn room_rows( label, small_icon(icon), color, - palette, + t, yumush_action(entity, popover, move |yumush, window, cx| { run(yumush, id, window, cx) }), @@ -135,7 +134,7 @@ pub(super) fn room_rows( "room_invite", words.invite, IconName::UserPlus, - palette.text, + t.paper(), |yumush, id, window, cx| yumush.open_invite(id, window, cx), )) }) @@ -144,7 +143,7 @@ pub(super) fn room_rows( "room_settings", words.settings, IconName::Settings, - palette.text, + t.paper(), |yumush, id, window, cx| yumush.open_community_settings(id, window, cx), )) }) @@ -152,7 +151,7 @@ pub(super) fn room_rows( "room_pin", if pinned { words.unpin } else { words.pin }, IconName::Pin, - palette.text, + t.paper(), |yumush, id, _, cx| yumush.toggle_mark(Mark::Pin, id, cx), )) .child(row( @@ -163,17 +162,17 @@ pub(super) fn room_rows( } else { IconName::BellOff }, - palette.text, + t.paper(), |yumush, id, _, cx| yumush.toggle_mark(Mark::Mute, id, cx), )) .when(can_leave, |this| { let armed = Armed::Leave(id); this.child(menu_row( ("room_leave", id as usize), - yumush.armed_label(armed, words.leave), + yumush.armed_label(armed.clone(), words.leave), small_icon(IconName::LogOut), - palette.danger, - palette, + t.bad(), + t, armed_action(armed, entity, popover, move |yumush, window, cx| { yumush.leave_community(id, window, cx) }), diff --git a/crates/client/src/gui/community_settings.rs b/crates/client/src/gui/community_settings.rs index 8071420..1cc91b3 100644 --- a/crates/client/src/gui/community_settings.rs +++ b/crates/client/src/gui/community_settings.rs @@ -19,7 +19,8 @@ use gpui_kit::{ }; use super::{ - Palette, Yumush, avatar, + Yumush, avatar, + builder::BuilderTab, chat::{Armed, View}, clickable, community_icon, entity_action, millis_time, notify_error, profile::user_link, @@ -27,7 +28,7 @@ use super::{ Editable, Picture, Section, danger, delete_control, page, picked_avatar, picture_card, row, section, small_button, text_row, }, - style::{radius, size, space, text as text_token}, + style::{Tokens, radius, size, space, text as text_token}, text, widget::search_text, }; @@ -69,8 +70,23 @@ fn apply_community( ) { match result { Ok(community) => { - let _ = this.update(cx, |yumush, cx| { - yumush.chat.insert_community(community); + let _ = this.update_in(cx, |yumush, window, cx| { + let id = community.id; + let known = yumush + .chat + .session + .communities + .iter_mut() + .chain(yumush.chat.session.opened.as_mut()) + .find(|known| known.id == id); + if let Some(known) = known { + *known = community; + } + if yumush.on_builder_tab(BuilderTab::Communities) + || yumush.on_builder_tab(BuilderTab::Voice) + { + yumush.load_builder_communities(window, cx); + } yumush.request_social_avatars(cx); cx.notify(); }); @@ -83,7 +99,7 @@ impl Yumush { pub(super) fn community_settings_page( &self, entity: &Entity, - palette: Palette, + t: Tokens, cx: &App, ) -> impl IntoElement { let community = self.chat.selected_community(); @@ -91,40 +107,40 @@ impl Yumush { .map(|community| community.name.clone()) .unwrap_or_default(); let actor = self.actor_rank(); - let bans_count = self.chat.bans.len(); + let bans_count = self.chat.session.bans.len(); let mut sections = Vec::new(); - if let Some(community) = community.filter(|_| permission::can_rename_community(actor)) { - sections.push(Section::new( - "profile", - w().community_settings.profile, - picture_card( - Picture { - id: "community_picture_picker", - image: community_icon( - palette, - community, - px(size::AVATAR_LG), - text(text_token::TITLE), - &self.chat.avatars, - ), - title: community.name.clone(), - subtitle: String::new(), - removable: community.avatar_id.is_some(), - upload: Yumush::upload_community_picture, - remove: Yumush::remove_community_picture, - }, - entity, - palette, - ) - .into_any_element(), - )); - } - if permission::can_rename_community(actor) { + if permission::is_admin(actor) { + if let Some(community) = community { + sections.push(Section::new( + "profile", + w().community_settings.profile, + picture_card( + Picture { + id: "community_picture_picker", + image: community_icon( + t, + community, + px(size::AVATAR_LG), + text(text_token::TITLE), + &self.chat.session.avatars, + ), + title: community.name.clone(), + subtitle: String::new(), + removable: community.avatar_id.is_some(), + upload: Yumush::upload_community_picture, + remove: Yumush::remove_community_picture, + }, + entity, + t, + ) + .into_any_element(), + )); + } sections.push(section( "general", w().community_settings.general, - palette, + t, vec![text_row( Editable { id: "save_community_name_button", @@ -135,24 +151,24 @@ impl Yumush { emoji: None, }, entity, - palette, + t, cx, )], )); } - if let Some(community) = community.filter(|_| permission::can_manage_voice(actor)) { + if let Some(community) = community.filter(|_| permission::is_owner(actor)) { sections.push(section( "voice", w().community_settings.voice, - palette, + t, vec![row( w().community_settings.voice, - voice_control(entity, community.id, community.voice_enabled, palette), + voice_control(entity, community.id, community.voice_enabled, t), )], )); } let mut moderation = Vec::new(); - if permission::can_unban(actor) { + if permission::is_moderator(actor) { moderation.push(row( w().community_settings.bans, div() @@ -162,32 +178,32 @@ impl Yumush { .child( div() .text_size(text(text_token::CAPTION)) - .text_color(palette.muted) + .text_color(t.dim()) .child(bans_count.to_string()), ) .child(view_control( "view_bans_button", entity, - palette, + t, Yumush::open_bans, )), )); } - if permission::can_read_logs(actor) { + if permission::is_moderator(actor) { moderation.push(row( w().community_settings.logs, - view_control("view_logs_button", entity, palette, Yumush::open_logs), + view_control("view_logs_button", entity, t, Yumush::open_logs), )); } if !moderation.is_empty() { sections.push(section( "moderation", w().community_settings.moderation, - palette, + t, moderation, )); } - if permission::can_delete_community(actor) { + if permission::is_owner(actor) { sections.push(danger( "danger_zone", vec![ @@ -196,7 +212,7 @@ impl Yumush { w().community_settings.delete_community, self.armed(Armed::DeleteCommunity), entity, - palette, + t, Yumush::delete_community, ) .into_any_element(), @@ -207,7 +223,7 @@ impl Yumush { sections.push(section( "general", w().community_settings.general, - palette, + t, Vec::new(), )); } @@ -215,14 +231,14 @@ impl Yumush { page( "community_settings_scroll", entity, - palette, + t, name, sections, - self.chat.section, + self.chat.session.section, ) } - fn set_community_voice( + pub(super) fn set_community_voice( &mut self, community_id: Id, enabled: bool, @@ -244,7 +260,7 @@ impl Yumush { } pub(super) fn save_community_name(&mut self, window: &mut Window, cx: &mut Context) { - let Some(community_id) = self.chat.selected_community_id else { + let Some(community_id) = self.chat.session.selected_community_id else { return; }; let name = self @@ -271,7 +287,7 @@ impl Yumush { } fn upload_community_picture(&mut self, window: &mut Window, cx: &mut Context) { - let Some(community_id) = self.chat.selected_community_id else { + let Some(community_id) = self.chat.session.selected_community_id else { return; }; let picked = picked_avatar(cx, self.max_avatar_bytes()); @@ -298,7 +314,7 @@ impl Yumush { } fn remove_community_picture(&mut self, window: &mut Window, cx: &mut Context) { - let Some(community_id) = self.chat.selected_community_id else { + let Some(community_id) = self.chat.session.selected_community_id else { return; }; let network = self.network.clone(); @@ -319,7 +335,7 @@ impl Yumush { if !self.arm(Armed::DeleteCommunity, cx) { return; } - let Some(community_id) = self.chat.selected_community_id else { + let Some(community_id) = self.chat.session.selected_community_id else { return; }; let network = self.network.clone(); @@ -329,7 +345,7 @@ impl Yumush { match network.call(call).await { Ok(()) => { let _ = this.update_in(cx, |yumush, window, cx| { - yumush.chat.remove_community(community_id); + yumush.forget_community(community_id, cx); yumush.show_view(View::Chat, window, cx); }); } @@ -340,7 +356,7 @@ impl Yumush { } pub(super) fn unban(&self, user_id: Id, window: &mut Window, cx: &mut Context) { - let Some(community_id) = self.chat.selected_community_id else { + let Some(community_id) = self.chat.session.selected_community_id else { return; }; let network = self.network.clone(); @@ -353,7 +369,11 @@ impl Yumush { match network.call(call).await { Ok(()) => { let _ = this.update_in(cx, |yumush, window, cx| { - yumush.chat.bans.retain(|ban| ban.user.id != user_id); + yumush + .chat + .session + .bans + .retain(|ban| ban.user.id != user_id); window.refresh(); cx.notify(); }); @@ -368,12 +388,15 @@ impl Yumush { let entity = cx.entity(); window.open_dialog(cx, move |dialog, _, cx| { let yumush = entity.read(cx); - let palette = super::palette(cx); + let t = Tokens::of(cx); let query = search_text(&yumush.chat.ban_search, cx); - let rows: Vec = ban_list(&yumush.chat.bans, &query, yumush.chat.ban_sort) - .into_iter() - .map(|ban| ban_row(ban, &entity, palette, &yumush.chat.avatars).into_any_element()) - .collect(); + let rows: Vec = + ban_list(&yumush.chat.session.bans, &query, yumush.chat.ban_sort) + .into_iter() + .map(|ban| { + ban_row(ban, &entity, t, &yumush.chat.session.avatars).into_any_element() + }) + .collect(); dialog .title(w().community_settings.bans) @@ -384,18 +407,18 @@ impl Yumush { ban_sorts(), yumush.chat.ban_sort, &entity, - palette, + t, Yumush::set_ban_sort, ), rows, w().common.no_bans, - palette, + t, )) }); } fn open_logs(&mut self, window: &mut Window, cx: &mut Context) { - let Some(community_id) = self.chat.selected_community_id else { + let Some(community_id) = self.chat.session.selected_community_id else { return; }; self.show_logs(community_id, window, cx); @@ -407,16 +430,18 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) { + self.chat.session.logs.clear(); self.load_logs(community_id, window, cx); let entity = cx.entity(); window.open_dialog(cx, move |dialog, _, cx| { let yumush = entity.read(cx); - let palette = super::palette(cx); + let t = Tokens::of(cx); let query = search_text(&yumush.chat.log_search, cx); - let rows: Vec = log_list(&yumush.chat.logs, &query, yumush.chat.log_sort) - .into_iter() - .map(|entry| log_row(entry, palette, &yumush.chat.avatars).into_any_element()) - .collect(); + let rows: Vec = + log_list(&yumush.chat.session.logs, &query, yumush.chat.log_sort) + .into_iter() + .map(|entry| log_row(entry, t, &yumush.chat.session.avatars).into_any_element()) + .collect(); dialog .title(w().community_settings.logs) @@ -427,12 +452,12 @@ impl Yumush { log_sorts(), yumush.chat.log_sort, &entity, - palette, + t, Yumush::set_log_sort, ), rows, w().community_settings.no_logs, - palette, + t, )) }); } @@ -470,7 +495,7 @@ impl Yumush { yumush.request_user_avatar(target, cx); } } - yumush.chat.logs = logs; + yumush.chat.session.logs = logs; window.refresh(); cx.notify(); }); @@ -483,20 +508,15 @@ fn voice_control( entity: &Entity, community_id: Id, enabled: bool, - palette: Palette, + t: Tokens, ) -> impl IntoElement { let entity = entity.clone(); - small_button( - "community_voice_button", - palette, - palette.text, - move |window, cx| { - entity.update(cx, |yumush, cx| { - yumush.set_community_voice(community_id, !enabled, window, cx) - }); - }, - ) + small_button("community_voice_button", t, t.paper(), move |window, cx| { + entity.update(cx, |yumush, cx| { + yumush.set_community_voice(community_id, !enabled, window, cx) + }); + }) .child(if enabled { w().community_settings.on } else { @@ -507,18 +527,17 @@ fn voice_control( fn view_control( id: &'static str, entity: &Entity, - palette: Palette, + t: Tokens, open: fn(&mut Yumush, &mut Window, &mut Context), ) -> impl IntoElement { - small_button(id, palette, palette.text, entity_action(entity, open)) - .child(w().community_settings.view) + small_button(id, t, t.paper(), entity_action(entity, open)).child(w().community_settings.view) } fn sort_control( options: [(T, &'static str, &'static str); N], selected: T, entity: &Entity, - palette: Palette, + t: Tokens, select: fn(&mut Yumush, T, &mut Window, &mut Context), ) -> impl IntoElement { div() @@ -531,7 +550,7 @@ fn sort_control( clickable( id, - palette, + t, entity_action(entity, move |yumush, window, cx| { select(yumush, choice, window, cx) }), @@ -541,10 +560,10 @@ fn sort_control( .items_center() .rounded(px(radius::SM)) .text_size(text(text_token::CAPTION)) - .text_color(if active { palette.text } else { palette.muted }) + .text_color(if active { t.paper() } else { t.dim() }) .border_b(px(super::style::stroke::LINE)) .border_color(if active { - palette.tokens.paper() + t.paper() } else { gpui_kit::transparent_black() }) @@ -558,10 +577,10 @@ fn moderation_body( sort: impl IntoElement, rows: Vec, empty: &'static str, - palette: Palette, + t: Tokens, ) -> impl IntoElement { let list = if rows.is_empty() { - crate::gui::parts::empty(empty, palette.tokens).into_any_element() + crate::gui::parts::empty(empty, t).into_any_element() } else { div().flex().flex_col().children(rows).into_any_element() }; @@ -570,7 +589,7 @@ fn moderation_body( .flex() .flex_col() .gap(px(space::MD)) - .child(super::sidebar::input_box(search, palette)) + .child(super::sidebar::input_box(search, t)) .child(sort) .child( div() @@ -648,7 +667,7 @@ pub(super) fn community_log_text(actor: &str, target: &str, action: &LogAction) } } -fn log_row(entry: &LogEntry, palette: Palette, avatars: &HashMap>) -> Div { +fn log_row(entry: &LogEntry, t: Tokens, avatars: &HashMap>) -> Div { div() .min_h(px(size::ROW)) .px(px(space::MD)) @@ -657,7 +676,7 @@ fn log_row(entry: &LogEntry, palette: Palette, avatars: &HashMap> .gap(px(space::SM)) .children(entry.actor.as_ref().map(|actor| { avatar( - palette, + t, actor, px(size::AVATAR), text(text_token::CAPTION), @@ -669,7 +688,7 @@ fn log_row(entry: &LogEntry, palette: Palette, avatars: &HashMap> div() .flex_shrink_0() .text_size(text(text_token::CAPTION)) - .text_color(palette.muted) + .text_color(t.dim()) .child(millis_time(entry.created_at, crate::lang::w().common.stamp)), ) } @@ -677,7 +696,7 @@ fn log_row(entry: &LogEntry, palette: Palette, avatars: &HashMap> fn ban_row( ban: &Ban, entity: &Entity, - palette: Palette, + t: Tokens, avatars: &HashMap>, ) -> Div { let entity = entity.clone(); @@ -695,7 +714,7 @@ fn ban_row( Some(user), &entity, avatar( - palette, + t, user, px(size::AVATAR), text(text_token::CAPTION), @@ -717,7 +736,7 @@ fn ban_row( .children(ban.reason.clone().map(|reason| { div() .text_size(text(text_token::CAPTION)) - .text_color(palette.muted) + .text_color(t.dim()) .min_w_0() .child(super::glyph::line( reason.into(), @@ -726,7 +745,7 @@ fn ban_row( })), ) .child( - clickable(format!("unban_{}", user.id), palette, move |window, cx| { + clickable(format!("unban_{}", user.id), t, move |window, cx| { entity.update(cx, |yumush, cx| yumush.unban(user_id, window, cx)); }) .h(px(size::CONTROL_SM)) @@ -734,7 +753,7 @@ fn ban_row( .flex() .items_center() .rounded(px(radius::MD)) - .text_color(palette.danger) + .text_color(t.bad()) .child(w().community_settings.unban), ) } diff --git a/crates/client/src/gui/composer.rs b/crates/client/src/gui/composer.rs index c06c2e9..44ba41c 100644 --- a/crates/client/src/gui/composer.rs +++ b/crates/client/src/gui/composer.rs @@ -1,11 +1,12 @@ use super::parts::{Scale, Tone, icon_button}; -use super::style::{radius, size, space, stroke, text}; +use super::style::{Tokens, radius, size, space, stroke, text}; use super::text; -use super::widget::{compact_field, panel, spawn_done}; +use super::widget::{compact_field, spawn_done}; use crate::gui::glyph::Fill as _; use common::model::Id; use std::time::{Duration, Instant}; +use super::keys; use crate::lang::w; use crate::net::Fail; use common::{ @@ -17,15 +18,15 @@ use common::{ validate::{validate_new_message, validate_poll}, }; use gpui_kit::{ - Anchor, AnyElement, App, Context, Div, ElementId, Entity, FontWeight, InteractiveElement, - IntoElement, KeyBinding, MouseButton, ParentElement, StatefulInteractiveElement as _, Styled, - Window, actions, + Action, Anchor, AnyElement, App, Context, Div, ElementId, Entity, FontWeight, + InteractiveElement, IntoElement, KeyBinding, MouseButton, ParentElement, + StatefulInteractiveElement as _, Styled, Window, actions, assets::IconName, component::{ WindowExt, input::{InputEvent, InputState, TextareaState}, notification::Notification, - popover::Popover, + popover::{Popover, PopoverState}, text::TextView, }, div, @@ -34,7 +35,7 @@ use gpui_kit::{ }; use super::{ - Palette, Trigger, Yumush, + Trigger, Yumush, chat::{Chat, TYPING_SEND_INTERVAL}, clickable, hoverable, new_input, notify_error, parts, }; @@ -43,12 +44,6 @@ actions!(composer, [Bold, Italic, Code, Strike]); const CONTEXT: &str = "MessageComposer"; -const MOD: &str = if cfg!(target_os = "macos") { - "Cmd" -} else { - "Ctrl" -}; - const FORMAT_ROWS: [(&str, &str); 6] = [ ("**bold**", "B"), ("*italic*", "I"), @@ -58,38 +53,30 @@ const FORMAT_ROWS: [(&str, &str); 6] = [ ("- list", ""), ]; -fn shortcut_label(keys: &str) -> String { - if keys.is_empty() { - String::new() - } else { - format!("{MOD}+{keys}") - } -} - #[derive(Debug, Clone, PartialEq, Eq)] pub enum Composer { Compose { reply: Option }, - Edit { message_id: Id }, + Edit { message_id: Id, stash: String }, Select { ids: Vec }, } const SLOW_TICK: Duration = Duration::from_secs(1); -pub fn mode_bar(chat: &Chat, entity: &Entity, palette: Palette) -> Option { +pub fn mode_bar(chat: &Chat, entity: &Entity, t: Tokens) -> Option { if let Some(seconds) = chat.slow_seconds() { - return Some(slow_bar(seconds, palette).into_any_element()); + return Some(slow_bar(seconds, t).into_any_element()); } match &chat.composer { Composer::Compose { reply: Some(message_id), - } => Some(reply_bar(chat, *message_id, entity, palette).into_any_element()), - Composer::Edit { .. } => Some(edit_bar(entity, palette).into_any_element()), + } => Some(reply_bar(chat, *message_id, entity, t).into_any_element()), + Composer::Edit { .. } => Some(edit_bar(entity, t).into_any_element()), Composer::Compose { reply: None } | Composer::Select { .. } => None, } } -pub fn selection_bar(ids: &[Id], entity: &Entity, palette: Palette) -> impl IntoElement { +pub fn selection_bar(ids: &[Id], entity: &Entity, t: Tokens) -> impl IntoElement { let count = ids.len(); let selected = ids.to_vec(); let forward_entity = entity.clone(); @@ -103,23 +90,23 @@ pub fn selection_bar(ids: &[Id], entity: &Entity, palette: Palette) -> i .gap(px(space::SM)) .rounded(px(radius::MD)) .border_1() - .border_color(palette.border) - .bg(palette.field) + .border_color(t.thread()) + .bg(t.raise()) .child(div().flex_1().child(w().composer.selected(count))) .child(parts::button( "forward_selected", w().composer.forward, parts::Press::Primary, - palette.tokens, + t, move |window, cx| { let selected = selected.clone(); forward_entity.update(cx, |yumush, cx| yumush.open_forward(selected, window, cx)); }, )) - .child(cancel_button(entity, palette)) + .child(cancel_button(entity, t)) } -fn bar(palette: Palette) -> Div { +fn bar(t: Tokens) -> Div { div() .h(px(size::CONTROL_SM)) .mb(px(space::SM)) @@ -128,18 +115,14 @@ fn bar(palette: Palette) -> Div { .items_center() .gap(px(space::SM)) .border_l(px(stroke::LINE)) - .border_color(palette.border) + .border_color(t.thread()) .text_size(text(text::CAPTION)) - .text_color(palette.muted) + .text_color(t.dim()) } -fn reply_bar( - chat: &Chat, - message_id: Id, - entity: &Entity, - palette: Palette, -) -> impl IntoElement { +fn reply_bar(chat: &Chat, message_id: Id, entity: &Entity, t: Tokens) -> impl IntoElement { let message = chat + .session .messages .iter() .find(|message| message.id == message_id); @@ -153,7 +136,7 @@ fn reply_bar( let jump = entity.clone(); - bar(palette) + bar(t) .child( div() .id("reply_jump") @@ -172,30 +155,30 @@ fn reply_bar( .child( div() .font_weight(FontWeight::SEMIBOLD) - .text_color(palette.text) + .text_color(t.paper()) .child(author), ) .child(div().flex_1().min_w_0().truncate().child(quote)), ) - .child(cancel_button(entity, palette)) + .child(cancel_button(entity, t)) } -fn slow_bar(seconds: u64, palette: Palette) -> impl IntoElement { - bar(palette) - .text_color(palette.danger) +fn slow_bar(seconds: u64, t: Tokens) -> impl IntoElement { + bar(t) + .text_color(t.bad()) .child(super::parts::small_icon(IconName::Hourglass)) .child(w().composer.slow_down(seconds)) } -fn edit_bar(entity: &Entity, palette: Palette) -> impl IntoElement { - bar(palette) +fn edit_bar(entity: &Entity, t: Tokens) -> impl IntoElement { + bar(t) .child(super::parts::small_icon(IconName::Pencil)) .child(w().composer.editing) .child(div().flex_1()) - .child(cancel_button(entity, palette)) + .child(cancel_button(entity, t)) } -fn cancel_button(entity: &Entity, palette: Palette) -> impl IntoElement { +fn cancel_button(entity: &Entity, t: Tokens) -> impl IntoElement { let entity = entity.clone(); icon_button( @@ -204,7 +187,7 @@ fn cancel_button(entity: &Entity, palette: Palette) -> impl IntoElement w().composer.cancel, Tone::Idle, Scale::Small, - palette.tokens, + t, move |window, cx| { entity.update(cx, |yumush, cx| yumush.cancel_composer(window, cx)); }, @@ -218,7 +201,7 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) { - if self.chat.media.uploading() { + if self.chat.session.media.uploading() { return; } let body = input @@ -231,33 +214,31 @@ impl Yumush { match self.chat.composer.clone() { Composer::Compose { reply } => self.create_message(reply, body, input, window, cx), - Composer::Edit { message_id } => { - self.update_message(message_id, body, input, window, cx) + Composer::Edit { message_id, stash } => { + self.update_message(message_id, body, stash, input, window, cx) } Composer::Select { .. } => {} } } pub(super) fn send_typing(&mut self, cx: &mut Context) { - let Some(community_id) = self.chat.selected_community_id else { + let Some(community_id) = self.chat.session.selected_community_id else { return; }; - if self - .chat - .message_input - .read(cx) - .text() - .to_string() - .is_empty() + if self.chat.message_input.read(cx).text().len() == 0 || self .chat + .session .typing_sent .get(&community_id) .is_some_and(|at| at.elapsed() < TYPING_SEND_INTERVAL) { return; } - self.chat.typing_sent.insert(community_id, Instant::now()); + self.chat + .session + .typing_sent + .insert(community_id, Instant::now()); let network = self.network.clone(); cx.spawn(async move |_, _| { let _ = network.call(Typing { community_id }).await; @@ -275,6 +256,7 @@ impl Yumush { ) { let attachments: Vec = self .chat + .session .media .pending .iter() @@ -289,15 +271,15 @@ impl Yumush { window.push_notification(Notification::error(error.to_string()), cx); return; } - let Some(community_id) = self.chat.selected_community_id else { + let Some(community_id) = self.chat.session.selected_community_id else { window.push_notification(Notification::error(w().composer.no_community), cx); return; }; let network = self.network.clone(); let restore = input.clone(); - let pending = self.chat.media.pending.clone(); + let pending = self.chat.session.media.pending.clone(); let order = self.send_order.clone(); - self.chat.drafts.remove(&community_id); + self.chat.session.drafts.remove(&community_id); cx.spawn_in(window, async move |this, cx| { let _turn = order.lock().await; @@ -315,13 +297,29 @@ impl Yumush { retry_after_seconds, })) => { let _ = this.update_in(cx, |yumush, window, cx| { - yumush.restore_message(&restore, community_id, body, pending, window, cx); + yumush.restore_message( + &restore, + community_id, + body, + pending, + reply, + window, + cx, + ); yumush.slow_down(retry_after_seconds, window, cx) }); } Err(error) => { let _ = this.update_in(cx, |yumush, window, cx| { - yumush.restore_message(&restore, community_id, body, pending, window, cx) + yumush.restore_message( + &restore, + community_id, + body, + pending, + reply, + window, + cx, + ) }); notify_error(&this, cx, error); } @@ -330,7 +328,7 @@ impl Yumush { .detach(); input.update(cx, |state, cx| state.set_value("", window, cx)); - self.chat.media.pending.clear(); + self.chat.session.media.pending.clear(); self.chat.composer = Composer::Compose { reply: None }; } @@ -340,24 +338,28 @@ impl Yumush { community_id: Id, body: String, pending: Vec, + reply: Option, window: &mut Window, cx: &mut Context, ) { - if self.chat.selected_community_id != Some(community_id) { - self.chat.drafts.insert(community_id, body); + if self.chat.session.selected_community_id != Some(community_id) { + self.chat.session.drafts.insert(community_id, body); return; } if input.read(cx).text().len() == 0 { input.update(cx, |state, cx| state.fill(body, window, cx)); } - if self.chat.media.pending.is_empty() { - self.chat.media.pending = pending; + if self.chat.session.media.pending.is_empty() { + self.chat.session.media.pending = pending; + } + if self.chat.composer == (Composer::Compose { reply: None }) { + self.chat.composer = Composer::Compose { reply }; } cx.notify(); } fn slow_down(&mut self, seconds: u64, window: &mut Window, cx: &mut Context) { - self.chat.slowed_until = Some(now_ms() + seconds * 1000); + self.chat.session.slowed_until = Some(now_ms() + seconds * 1000); cx.spawn_in(window, async move |this, cx| { loop { @@ -378,6 +380,7 @@ impl Yumush { &mut self, message_id: Id, body: String, + stash: String, input: &Entity, window: &mut Window, cx: &mut Context, @@ -390,21 +393,30 @@ impl Yumush { let restore = input.clone(); cx.spawn_in(window, async move |this, cx| { - if let Err(error) = network + match network .call(UpdateMessage { message_id, body: body.clone(), }) .await { - let _ = this.update_in(cx, |yumush, window, cx| { - if restore.read(cx).text().len() == 0 { - restore.update(cx, |state, cx| state.fill(body, window, cx)); - yumush.chat.composer = Composer::Edit { message_id }; - cx.notify(); - } - }); - notify_error(&this, cx, error); + Ok(_) => { + let _ = this.update_in(cx, |_, window, cx| { + if restore.read(cx).text().len() == 0 { + restore.update(cx, |state, cx| state.fill(stash, window, cx)); + } + }); + } + Err(error) => { + let _ = this.update_in(cx, |yumush, window, cx| { + if restore.read(cx).text().len() == 0 { + restore.update(cx, |state, cx| state.fill(body, window, cx)); + yumush.chat.composer = Composer::Edit { message_id, stash }; + cx.notify(); + } + }); + notify_error(&this, cx, error); + } } }) .detach(); @@ -415,14 +427,14 @@ impl Yumush { } pub(super) fn save_draft(&mut self, cx: &mut Context) { - let Some(community_id) = self.chat.selected_community_id else { + let Some(community_id) = self.chat.session.selected_community_id else { return; }; let text = self.chat.message_input.read(cx).text().to_string(); if text.is_empty() || !matches!(self.chat.composer, Composer::Compose { .. }) { - self.chat.drafts.remove(&community_id); + self.chat.session.drafts.remove(&community_id); } else { - self.chat.drafts.insert(community_id, text); + self.chat.session.drafts.insert(community_id, text); } } @@ -434,6 +446,7 @@ impl Yumush { ) { let text = self .chat + .session .drafts .get(&community_id) .cloned() @@ -454,6 +467,7 @@ impl Yumush { pub(super) fn edit(&mut self, message_id: Id, window: &mut Window, cx: &mut Context) { let Some(body) = self .chat + .session .messages .iter() .find(|message| message.id == message_id) @@ -462,10 +476,16 @@ impl Yumush { return; }; + let previous = + std::mem::replace(&mut self.chat.composer, Composer::Compose { reply: None }); + let stash = match previous { + Composer::Edit { stash, .. } => stash, + _ => self.chat.message_input.read(cx).text().to_string(), + }; self.chat .message_input .update(cx, |input, cx| input.fill(body, window, cx)); - self.chat.composer = Composer::Edit { message_id }; + self.chat.composer = Composer::Edit { message_id, stash }; self.chat.focus(window, cx); cx.notify(); } @@ -492,19 +512,21 @@ impl Yumush { } else if ids.len() < MAXIMUM_FORWARD_MESSAGES { ids.push(message_id); } + if ids.is_empty() { + self.chat.composer = Composer::Compose { reply: None }; + } cx.notify(); } pub(super) fn cancel_composer(&mut self, window: &mut Window, cx: &mut Context) { - match self.chat.composer.clone() { + match std::mem::replace(&mut self.chat.composer, Composer::Compose { reply: None }) { Composer::Compose { reply: None } => return, Composer::Compose { reply: Some(_) } | Composer::Select { .. } => {} - Composer::Edit { .. } => self + Composer::Edit { stash, .. } => self .chat .message_input - .update(cx, |input, cx| input.set_value("", window, cx)), + .update(cx, |input, cx| input.fill(stash, window, cx)), } - self.chat.composer = Composer::Compose { reply: None }; self.chat.focus(window, cx); cx.notify(); } @@ -513,20 +535,27 @@ impl Yumush { pub fn bind_keys(cx: &mut App) { let scope = format!("{CONTEXT} > Input"); cx.bind_keys([ - KeyBinding::new("ctrl-b", Bold, Some(scope.as_str())), - KeyBinding::new("ctrl-i", Italic, Some(scope.as_str())), - KeyBinding::new("ctrl-e", Code, Some(scope.as_str())), - KeyBinding::new("ctrl-shift-x", Strike, Some(scope.as_str())), + KeyBinding::new(keys::bind!("b"), Bold, Some(scope.as_str())), + KeyBinding::new(keys::bind!("i"), Italic, Some(scope.as_str())), + KeyBinding::new(keys::bind!("e"), Code, Some(scope.as_str())), + KeyBinding::new(keys::bind!("shift-x"), Strike, Some(scope.as_str())), ]); } pub fn format_actions(input: &Entity, row: Div) -> Div { - let (bold, italic, code, strike) = (input.clone(), input.clone(), input.clone(), input.clone()); row.key_context(CONTEXT) - .on_action(move |_: &Bold, window, cx| wrap(&bold, "**", window, cx)) - .on_action(move |_: &Italic, window, cx| wrap(&italic, "*", window, cx)) - .on_action(move |_: &Code, window, cx| wrap(&code, "`", window, cx)) - .on_action(move |_: &Strike, window, cx| wrap(&strike, "~~", window, cx)) + .on_action(mark_action::(input, "**")) + .on_action(mark_action::(input, "*")) + .on_action(mark_action::(input, "`")) + .on_action(mark_action::(input, "~~")) +} + +fn mark_action( + input: &Entity, + mark: &'static str, +) -> impl Fn(&A, &mut Window, &mut App) + 'static { + let input = input.clone(); + move |_: &A, window, cx| wrap(&input, mark, window, cx) } fn wrap(input: &Entity, mark: &str, window: &mut Window, cx: &mut App) { @@ -542,7 +571,7 @@ pub(super) fn trigger_icon( id: impl Into, icon: IconName, size: f32, - palette: Palette, + t: Tokens, ) -> Trigger { Trigger::new(hoverable( id, @@ -552,14 +581,14 @@ pub(super) fn trigger_icon( .items_center() .justify_center() .rounded(px(radius::MD)) - .text_color(palette.muted) + .text_color(t.dim()) .child(super::parts::small_icon(icon)), - palette, + t, )) } -fn format_panel(palette: Palette) -> impl IntoElement { - panel(palette) +fn format_panel(t: Tokens) -> impl IntoElement { + parts::surface(t) .w(px(size::SHEET)) .p(px(space::SM)) .flex() @@ -571,18 +600,13 @@ fn format_panel(palette: Palette) -> impl IntoElement { .flex() .items_center() .gap(px(space::MD)) - .child( - div() - .w(px(size::THUMB)) - .text_color(palette.muted) - .child(syntax), - ) + .child(div().w(px(size::THUMB)).text_color(t.dim()).child(syntax)) .child(div().flex_1().child(TextView::markdown(syntax, syntax))) - .child( - div() - .text_color(palette.muted) - .child(shortcut_label(shortcut)), - ) + .child(div().text_color(t.dim()).child(if shortcut.is_empty() { + String::new() + } else { + keys::label(shortcut) + })) })) } @@ -598,10 +622,10 @@ fn plus_row( id: &'static str, icon: IconName, label: &'static str, - palette: Palette, + t: Tokens, on_click: impl Fn(&mut Window, &mut App) + 'static, ) -> impl IntoElement { - clickable(id, palette, on_click) + clickable(id, t, on_click) .h(px(size::CONTROL)) .px(px(space::SM)) .gap(px(space::SM)) @@ -610,18 +634,13 @@ fn plus_row( .items_center() .child( div() - .text_color(palette.muted) + .text_color(t.dim()) .child(super::parts::small_icon(icon)), ) .child(label) } -pub fn plus_popover(chat: &Chat, entity: &Entity, palette: Palette) -> impl IntoElement { - let question = chat.poll_question.clone(); - let options = chat.poll_options.clone(); - let multiple = chat.poll_multiple; - let public = chat.poll_public; - let duration = chat.poll_duration; +pub fn plus_popover(entity: &Entity, t: Tokens) -> impl IntoElement { let reset = entity.clone(); let entity = entity.clone(); @@ -637,180 +656,189 @@ pub fn plus_popover(chat: &Chat, entity: &Entity, palette: Palette) -> i .items_center() .justify_center() .rounded(px(radius::MD)) - .text_color(palette.muted) + .text_color(t.dim()) .child(super::parts::small_icon(IconName::Plus)), - palette, + t, ) .on_mouse_down(MouseButton::Left, move |_, _, cx| { - reset.update(cx, |yumush, _| yumush.chat.plus_menu = PlusMenu::Menu) + reset.update(cx, |yumush, _| yumush.chat.poll.plus_menu = PlusMenu::Menu) }), )) .content(move |_, _, cx| { let popover = cx.entity(); - if entity.read(cx).chat.plus_menu == PlusMenu::Format { - return format_panel(palette).into_any_element(); + match entity.read(cx).chat.poll.plus_menu { + PlusMenu::Format => format_panel(t).into_any_element(), + PlusMenu::Menu => menu_panel(&entity, &popover, t).into_any_element(), + PlusMenu::Poll => poll_panel(&entity, &popover, t, cx).into_any_element(), } - if entity.read(cx).chat.plus_menu == PlusMenu::Menu { - let file = entity.clone(); - let poll = entity.clone(); - let format = entity.clone(); - return panel(palette) - .w(px(size::SIDEBAR)) - .p(px(space::XS)) + }) +} + +fn menu_panel( + entity: &Entity, + popover: &Entity, + t: Tokens, +) -> impl IntoElement { + let file = entity.clone(); + let poll = entity.clone(); + let format = entity.clone(); + let dismiss = popover.clone(); + + parts::surface(t) + .w(px(size::SIDEBAR)) + .p(px(space::XS)) + .flex() + .flex_col() + .gap(px(space::XS)) + .child(plus_row( + "plus_file", + IconName::File, + w().composer.file, + t, + move |window, cx| { + dismiss.update(cx, |state, cx| state.dismiss(window, cx)); + file.update(cx, |yumush, cx| yumush.attach_files(window, cx)); + }, + )) + .child(plus_row( + "plus_poll", + IconName::ChartBar, + w().composer.poll, + t, + move |_, cx| { + poll.update(cx, |yumush, cx| { + yumush.chat.poll.plus_menu = PlusMenu::Poll; + cx.notify(); + }) + }, + )) + .child(plus_row( + "plus_format", + IconName::Type, + w().composer.format, + t, + move |_, cx| { + format.update(cx, |yumush, cx| { + yumush.chat.poll.plus_menu = PlusMenu::Format; + cx.notify(); + }) + }, + )) +} + +fn poll_panel( + entity: &Entity, + popover: &Entity, + t: Tokens, + cx: &App, +) -> impl IntoElement { + let draft = &entity.read(cx).chat.poll; + let duration = draft.duration; + let toggle = entity.clone(); + let toggle_public = entity.clone(); + let duration_entity = entity.clone(); + let submit = entity.clone(); + let submit_popover = popover.clone(); + let options = draft.options.len(); + + parts::surface(t) + .w(px(size::POPOVER)) + .p(px(space::SM)) + .flex() + .flex_col() + .gap(px(space::SM)) + .text_size(text(text::CAPTION)) + .child(compact_field(t, &draft.question)) + .children(draft.options.iter().enumerate().map(|(index, option)| { + let remove = entity.clone(); + let trailing_blank = index + 1 == options && option_text(option, cx).is_empty(); + div() + .flex() + .items_center() + .gap(px(space::SM)) + .child(div().flex_1().min_w_0().child(compact_field(t, option))) + .children( + (options > MINIMUM_POLL_OPTIONS && !trailing_blank).then(|| { + icon_button( + format!("poll_remove_{index}"), + IconName::Close, + w().composer.remove_option, + Tone::Idle, + Scale::Small, + t, + move |window, cx| { + remove.update(cx, |yumush, cx| { + yumush.remove_poll_option(index, window, cx) + }); + }, + ) + }), + ) + })) + .child( + div() + .flex() + .items_center() + .gap(px(space::XS)) + .text_color(t.dim()) + .child(super::parts::small_icon(IconName::Timer)) + .children(poll_durations().map(|(label, seconds)| { + let set = duration_entity.clone(); + let active = duration == seconds; + clickable(label, t, move |_, cx| { + set.update(cx, |yumush, cx| { + yumush.chat.poll.duration = seconds; + cx.notify(); + }) + }) + .px(px(space::SM)) + .py(px(space::XXS)) + .rounded(px(radius::SM)) + .text_color(if active { t.paper() } else { t.dim() }) + .when(active, |this| this.bg(t.press())) + .child(label) + })), + ) + .child( + div().flex().items_center().justify_between().child( + div() .flex() - .flex_col() - .gap(px(space::XS)) - .child(plus_row( - "plus_file", - IconName::File, - w().composer.file, - palette, - move |window, cx| { - popover.update(cx, |state, cx| state.dismiss(window, cx)); - file.update(cx, |yumush, cx| yumush.attach_files(window, cx)); - }, - )) - .child(plus_row( - "plus_poll", - IconName::ChartBar, - w().composer.poll, - palette, + .items_center() + .gap(px(space::MD)) + .child(super::parts::labeled_toggle( + "poll_multiple", + w().composer.multiple_answers, + draft.multiple, + t, move |_, cx| { - poll.update(cx, |yumush, cx| { - yumush.chat.plus_menu = PlusMenu::Poll; + toggle.update(cx, |yumush, cx| { + yumush.chat.poll.multiple = !yumush.chat.poll.multiple; cx.notify(); }) }, )) - .child(plus_row( - "plus_format", - IconName::Type, - w().composer.format, - palette, + .child(super::parts::labeled_toggle( + "poll_public", + w().composer.show_voters, + draft.public, + t, move |_, cx| { - format.update(cx, |yumush, cx| { - yumush.chat.plus_menu = PlusMenu::Format; - cx.notify(); - }) + toggle_public.update(cx, |yumush, cx| yumush.toggle_poll_public(cx)) }, - )) - .into_any_element(); - } - let toggle = entity.clone(); - let toggle_public = entity.clone(); - let duration_entity = entity.clone(); - let submit = entity.clone(); - panel(palette) - .w(px(size::POPOVER)) - .p(px(space::SM)) - .flex() - .flex_col() - .gap(px(space::SM)) - .text_size(text(text::CAPTION)) - .child(compact_field(palette, &question)) - .children(options.iter().enumerate().map(|(index, option)| { - let remove = entity.clone(); - let trailing_blank = - index + 1 == options.len() && option_text(option, cx).is_empty(); - div() - .flex() - .items_center() - .gap(px(space::SM)) - .child( - div() - .flex_1() - .min_w_0() - .child(compact_field(palette, option)), - ) - .children( - (options.len() > MINIMUM_POLL_OPTIONS && !trailing_blank).then(|| { - icon_button( - format!("poll_remove_{index}"), - IconName::Close, - w().composer.remove_option, - Tone::Idle, - Scale::Small, - palette.tokens, - move |_, cx| { - remove.update(cx, |yumush, cx| { - yumush.remove_poll_option(index, cx) - }); - }, - ) - }), - ) - })) - .child( - div() - .flex() - .items_center() - .gap(px(space::XS)) - .text_color(palette.muted) - .child(super::parts::small_icon(IconName::Timer)) - .children(poll_durations().map(|(label, seconds)| { - let set = duration_entity.clone(); - let active = duration == seconds; - clickable(label, palette, move |_, cx| { - set.update(cx, |yumush, cx| { - yumush.chat.poll_duration = seconds; - cx.notify(); - }) - }) - .px(px(space::SM)) - .py(px(space::XXS)) - .rounded(px(radius::SM)) - .text_color(if active { - palette.accent - } else { - palette.muted - }) - .when(active, |this| this.bg(palette.tokens.press())) - .child(label) - })), - ) - .child( - div().flex().items_center().justify_between().child( - div() - .flex() - .items_center() - .gap(px(space::MD)) - .child(super::parts::labeled_toggle( - "poll_multiple", - w().composer.multiple_answers, - multiple, - palette.tokens, - move |_, cx| { - toggle.update(cx, |yumush, cx| { - yumush.chat.poll_multiple = !yumush.chat.poll_multiple; - cx.notify(); - }) - }, - )) - .child(super::parts::labeled_toggle( - "poll_public", - w().composer.show_voters, - public, - palette.tokens, - move |_, cx| { - toggle_public - .update(cx, |yumush, cx| yumush.toggle_poll_public(cx)) - }, - )), - ), - ) - .child(parts::button( - "poll_create", - w().composer.create, - parts::Press::Primary, - palette.tokens, - move |window, cx| { - if submit.update(cx, |yumush, cx| yumush.send_poll(window, cx)) { - popover.update(cx, |state, cx| state.dismiss(window, cx)); - } - }, - )) - .into_any_element() - }) + )), + ), + ) + .child(parts::button( + "poll_create", + w().composer.create, + parts::Press::Primary, + t, + move |window, cx| { + if submit.update(cx, |yumush, cx| yumush.send_poll(window, cx)) { + submit_popover.update(cx, |state, cx| state.dismiss(window, cx)); + } + }, + )) } fn poll_durations() -> [(&'static str, Option); 4] { @@ -844,37 +872,47 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) { - let last = self.chat.poll_options.last() == Some(input); + let last = self.chat.poll.options.last() == Some(input); if last && !option_text(input, cx).is_empty() { self.add_poll_option(window, cx); } } - pub(super) fn add_poll_option(&mut self, window: &mut Window, cx: &mut Context) { - if self.chat.poll_options.len() < MAXIMUM_POLL_OPTIONS { + fn add_poll_option(&mut self, window: &mut Window, cx: &mut Context) { + if self.chat.poll.options.len() < MAXIMUM_POLL_OPTIONS { let input = new_poll_option(window, cx); - self.chat.poll_options.push(input); + self.chat.poll.options.push(input); cx.notify(); } } - pub(super) fn remove_poll_option(&mut self, index: usize, cx: &mut Context) { - if self.chat.poll_options.len() > MINIMUM_POLL_OPTIONS - && index < self.chat.poll_options.len() + fn remove_poll_option(&mut self, index: usize, window: &mut Window, cx: &mut Context) { + if self.chat.poll.options.len() > MINIMUM_POLL_OPTIONS + && index < self.chat.poll.options.len() { - self.chat.poll_options.remove(index); + self.chat.poll.options.remove(index); + let last_filled = self + .chat + .poll + .options + .last() + .is_some_and(|input| !option_text(input, cx).is_empty()); + if last_filled { + self.add_poll_option(window, cx); + } cx.notify(); } } pub(super) fn send_poll(&mut self, window: &mut Window, cx: &mut Context) -> bool { - let Some(community_id) = self.chat.selected_community_id else { + let Some(community_id) = self.chat.session.selected_community_id else { return false; }; - let question = self.chat.poll_question.read(cx).text().to_string(); + let question = self.chat.poll.question.read(cx).text().to_string(); let options: Vec = self .chat - .poll_options + .poll + .options .iter() .map(|input| option_text(input, cx)) .filter(|text| !text.is_empty()) @@ -883,9 +921,9 @@ impl Yumush { window.push_notification(Notification::error(error.to_string()), cx); return false; } - let multiple = self.chat.poll_multiple; - let public = self.chat.poll_public; - let duration = self.chat.poll_duration; + let multiple = self.chat.poll.multiple; + let public = self.chat.poll.public; + let duration = self.chat.poll.duration; let network = self.network.clone(); spawn_done(window, cx, async move { @@ -901,22 +939,13 @@ impl Yumush { .await }); - self.chat - .poll_question - .update(cx, |state, cx| state.set_value("", window, cx)); - self.chat.poll_options.truncate(MINIMUM_POLL_OPTIONS); - for input in &self.chat.poll_options { - input.update(cx, |state, cx| state.set_value("", window, cx)); - } - self.chat.poll_multiple = false; - self.chat.poll_public = true; - self.chat.poll_duration = None; + self.chat.poll.clear(window, cx); cx.notify(); true } pub(super) fn toggle_poll_public(&mut self, cx: &mut Context) { - self.chat.poll_public = !self.chat.poll_public; + self.chat.poll.public = !self.chat.poll.public; cx.notify(); } } diff --git a/crates/client/src/gui/dock.rs b/crates/client/src/gui/dock.rs index d93d996..9adefed 100644 --- a/crates/client/src/gui/dock.rs +++ b/crates/client/src/gui/dock.rs @@ -1,12 +1,9 @@ -use std::rc::Rc; - use common::share::Kind; use gpui_kit::{App, Entity, IntoElement}; use super::{ - Palette, Yumush, + Yumush, call_bar::{self, CallActions, CallBar}, - chat::VoiceState, entity_action, parts::Voice, style::Tokens, @@ -17,32 +14,31 @@ impl Yumush { pub(super) fn dock( &self, entity: &Entity, - palette: Palette, + t: Tokens, cx: &App, ) -> Option { let community = self.chat.voice_room()?; - let VoiceState::In { .. } = &self.chat.voice_state else { - return None; - }; let (muted, deafened) = self.chat.voice_flags()?; let user = self.user.as_ref()?; let me = user.id; - let t = Tokens::of(cx); - let frayed = voice_stats::quality(&self.chat.stats.voice) == Some(Quality::Poor); + let quality = voice_stats::quality(&self.chat.session.stats.voice); + let frayed = quality == Some(Quality::Poor); + let screen = self.network.share_source(Kind::Screen).is_some(); let voice = if frayed { Voice::Frayed - } else if !muted && self.chat.waves.speaking.contains(&me) { + } else if !muted && self.chat.session.waves.speaking.contains(&me) { Voice::Live(t.person(me)) } else { Voice::Quiet }; let bar = CallBar { place: super::community_name(community).to_string().into(), - bands: self.chat.waves.voice(me).cloned(), + bands: self.chat.session.waves.voice(me).map(super::chat::to_bands), voice, - quality: super::voice_stats::quality(&self.chat.stats.voice), + quality, pings: self .chat + .session .stats .voice .iter() @@ -51,51 +47,52 @@ impl Yumush { muted, deafened, camera: self.network.share_source(Kind::Camera).is_some(), - screen: self.network.share_source(Kind::Screen).is_some(), - ghost: self.chat.ghost, - share: self - .network - .share_source(Kind::Screen) - .map(|_| (self.chat.waves.share(me).cloned(), t.person(me))), + ghost: self.chat.session.ghost, + share: screen.then(|| { + ( + self.chat.session.waves.share(me).map(super::chat::to_bands), + t.person(me), + ) + }), stats: self.chat.stats_at == Some(super::chat::StatsAt::Dock), }; let go_id = community.id; let actions = CallActions { - go: Rc::new(entity_action(entity, move |yumush, window, cx| { + go: Box::new(entity_action(entity, move |yumush, window, cx| { yumush.select_community(go_id, window, cx); })), - mute: Rc::new(entity_action(entity, |yumush, window, cx| { + mute: Box::new(entity_action(entity, |yumush, window, cx| { yumush.toggle_mute(window, cx) })), - deafen: Rc::new(entity_action(entity, |yumush, _, cx| { + deafen: Box::new(entity_action(entity, |yumush, _, cx| { yumush.toggle_deafen(cx) })), - camera: Rc::new(entity_action(entity, |yumush, window, cx| { + camera: Box::new(entity_action(entity, |yumush, window, cx| { yumush.toggle_camera(window, cx) })), - screen: Rc::new(entity_action(entity, |yumush, window, cx| { + screen: Box::new(entity_action(entity, |yumush, window, cx| { yumush.toggle_share(window, cx) })), - leave: Rc::new(entity_action(entity, |yumush, _, cx| { + leave: Box::new(entity_action(entity, |yumush, _, cx| { yumush.end_voice(cx); cx.notify(); })), - stats: Rc::new(entity_action(entity, move |yumush, window, cx| { + stats: Box::new(entity_action(entity, move |yumush, window, cx| { yumush.select_community(go_id, window, cx); yumush.toggle_stats(super::chat::StatsAt::Dock); cx.notify(); })), mic_more: self - .audio_button(entity, palette, super::voice_settings::Side::Input, cx) + .audio_button(entity, t, super::voice_settings::Side::Input, cx) .into_any_element(), speaker_more: self - .audio_button(entity, palette, super::voice_settings::Side::Output, cx) + .audio_button(entity, t, super::voice_settings::Side::Output, cx) .into_any_element(), camera_more: self - .share_settings_button(entity, palette, Kind::Camera, cx) + .share_settings_button(entity, t, Kind::Camera, cx) .into_any_element(), screen_more: self - .share_settings_button(entity, palette, Kind::Screen, cx) + .share_settings_button(entity, t, Kind::Screen, cx) .into_any_element(), }; Some(call_bar::view(bar, actions, t)) diff --git a/crates/client/src/gui/forward.rs b/crates/client/src/gui/forward.rs index 4cfffb4..ba54487 100644 --- a/crates/client/src/gui/forward.rs +++ b/crates/client/src/gui/forward.rs @@ -1,4 +1,4 @@ -use super::style::{radius, size, space, text}; +use super::style::{Tokens, radius, size, space, text}; use crate::lang::w; use common::call::ForwardMessages; use common::model::Id; @@ -15,7 +15,6 @@ use gpui_kit::{ use super::{ Yumush, clickable, community_name, composer::Composer, - palette, widget::{compact_field, search_text, spawn_done}, }; @@ -57,7 +56,7 @@ impl Forward { impl Render for Forward { fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { - let palette = palette(cx); + let t = Tokens::of(cx); let query = search_text(&self.filter, cx); let entity = cx.entity(); let keep_authors = self.keep_authors; @@ -74,7 +73,7 @@ impl Render for Forward { let selected = self.selected.clone(); let forward_entity = self.yumush.clone(); - clickable(("forward_to", index), palette, move |window, cx| { + clickable(("forward_to", index), t, move |window, cx| { let selected = selected.clone(); forward_entity.update(cx, |yumush, cx| { yumush.forward_to(selected, community_id, keep_authors, window, cx) @@ -90,7 +89,7 @@ impl Render for Forward { community, px(size::ICON), super::text(text::CAPTION), - palette, + t, )) .child( div() @@ -107,12 +106,12 @@ impl Render for Forward { .flex() .flex_col() .gap(px(space::MD)) - .child(compact_field(palette, &self.filter)) + .child(compact_field(t, &self.filter)) .child(super::parts::labeled_toggle( "keep_authors", w().forward.keep_authors, keep_authors, - palette.tokens, + t, move |_, cx| { entity.update(cx, |this, cx| { this.keep_authors = !this.keep_authors; @@ -169,6 +168,7 @@ impl Yumush { let ids: Vec = self .chat + .session .messages .iter() .filter(|message| selected.contains(&message.id)) diff --git a/crates/client/src/gui/gallery.rs b/crates/client/src/gui/gallery.rs index 921bfbe..cd62daa 100644 --- a/crates/client/src/gui/gallery.rs +++ b/crates/client/src/gui/gallery.rs @@ -15,7 +15,6 @@ use super::{ style::{Theme, Tokens, size, space}, }; use crate::settings::FontSize; -use std::rc::Rc; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum State { @@ -80,13 +79,29 @@ impl State { } } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Page { + Parts, + Call, +} + +impl Page { + pub fn parse(text: &str) -> Option { + match text { + "parts" => Some(Page::Parts), + "call" => Some(Page::Call), + _ => None, + } + } +} + pub struct Gallery { - page: String, + page: Page, state: State, } impl Gallery { - pub fn new(page: String, state: State) -> Self { + pub fn new(page: Page, state: State) -> Self { Self { page, state } } } @@ -94,11 +109,9 @@ impl Gallery { impl Render for Gallery { fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { let t = Tokens::of(cx); - let page = match self.page.as_str() { - "parts" => parts_page(self.state, t).into_any_element(), - "call" => call_page(self.state, t).into_any_element(), - other => words(format!("no gallery page {other}"), Text::Body, Ink::Bad, t) - .into_any_element(), + let page = match self.page { + Page::Parts => parts_page(self.state, t).into_any_element(), + Page::Call => call_page(self.state, t).into_any_element(), }; div() .size_full() @@ -341,12 +354,11 @@ fn call_page(state: State, t: Tokens) -> impl IntoElement { muted: bad, deafened: false, camera: state == State::Many, - screen: state == State::Many, share: (state == State::Many).then(|| (Some(bands(2.)), t.hue(Hue::Amber))), stats: false, ghost: false, }; - let none = || -> call_bar::Action { Rc::new(|_, _| {}) }; + let none = || -> call_bar::Action { Box::new(|_, _| {}) }; let actions = CallActions { go: none(), mute: none(), diff --git a/crates/client/src/gui/glyph.rs b/crates/client/src/gui/glyph.rs index 4cbb6c9..1a2d12c 100644 --- a/crates/client/src/gui/glyph.rs +++ b/crates/client/src/gui/glyph.rs @@ -15,8 +15,8 @@ use gpui_kit::{ }; use super::{ - Palette, Yumush, clickable, - style::{radius, size, space}, + Yumush, clickable, + style::{Tokens, radius, size, space}, }; use crate::emoji::{self, Piece}; @@ -30,13 +30,13 @@ pub fn picture(emoji: &str, size: impl Into + Copy) -> } } -pub fn sized(text: Rems) -> Rems { +fn sized(text: Rems) -> Rems { rems(text.0 * SCALE) } pub fn line(content: SharedString, text: Rems) -> Div { let row = div().flex().items_center().min_w_0().overflow_hidden(); - if emoji::plain(&content) { + if content.is_ascii() { return row.child(div().min_w_0().truncate().child(content)); } let size = sized(text); @@ -54,30 +54,31 @@ pub fn line(content: SharedString, text: Rems) -> Div { } pub fn wrapped(content: SharedString, text: Rems) -> Div { - let flow = div().flex().flex_wrap().items_center().min_w_0(); - if emoji::plain(&content) { + if content.is_ascii() { return div().min_w_0().child(content); } let size = sized(text); - flow.children(emoji::pieces(&content).into_iter().flat_map(|piece| { - match piece { - Piece::Text(text) => text - .split_inclusive(' ') - .map(|word| { - div() - .whitespace_nowrap() - .child(word.replace(' ', "\u{a0}")) - .into_any_element() - }) - .collect::>(), - Piece::Emoji(emoji) => vec![picture(emoji, size)], - } - })) + div().flex().flex_wrap().items_center().min_w_0().children( + emoji::pieces(&content) + .into_iter() + .flat_map(|piece| match piece { + Piece::Text(text) => text + .split_inclusive(' ') + .map(|word| { + div() + .whitespace_nowrap() + .child(word.replace(' ', "\u{a0}")) + .into_any_element() + }) + .collect::>(), + Piece::Emoji(emoji) => vec![picture(emoji, size)], + }), + ) } const TOKEN: f32 = 0.85; -pub fn content(text: &str) -> InputContent { +fn content(text: &str) -> InputContent { let base = text.as_ptr() as usize; emoji::pieces(text) .into_iter() @@ -88,13 +89,10 @@ pub fn content(text: &str) -> InputContent { .fold(InputContent::new(text.to_string()), |content, emoji| { let start = emoji.as_ptr() as usize - base; let token = InlineToken::new(emoji::key(emoji), emoji.to_string()); - match content + content .clone() .with_token(start..start + emoji.len(), token) - { - Ok(content) => content, - Err(_) => content, - } + .unwrap_or(content) }) } @@ -103,16 +101,10 @@ pub fn token(context: &InlineTokenContext, _: &mut Window, _: &mut App) -> AnyEl picture(context.token().text(), size) } -pub trait Fill { - fn fill(&mut self, text: impl Into, window: &mut Window, cx: &mut Context) - where - Self: Sized; - fn mark(&mut self, cx: &mut Context) - where - Self: Sized; - fn put(&mut self, emoji: &'static str, window: &mut Window, cx: &mut Context) - where - Self: Sized; +pub trait Fill: Sized { + fn fill(&mut self, text: impl Into, window: &mut Window, cx: &mut Context); + fn mark(&mut self, cx: &mut Context); + fn put(&mut self, emoji: &'static str, window: &mut Window, cx: &mut Context); } macro_rules! fill { @@ -182,15 +174,17 @@ pub type Pick = std::rc::Rc; pub fn insert_into(input: Entity) -> Pick { std::rc::Rc::new(move |emoji, window, cx| { - input.update(cx, |state, cx| state.put(emoji, window, cx)); - input.update(cx, |state, cx| state.mark(cx)); + input.update(cx, |state, cx| { + state.put(emoji, window, cx); + state.mark(cx); + }); }) } pub fn picker_button( id: &'static str, entity: &Entity, - palette: Palette, + t: Tokens, pick: Pick, ) -> impl IntoElement { let entity = entity.clone(); @@ -201,7 +195,7 @@ pub fn picker_button( SharedString::from(format!("{id}_trigger")), IconName::FaceSlightlySmiling, size::CONTROL_SM, - palette, + t, )) .content(move |_, _, cx| { let popover = cx.entity(); @@ -210,16 +204,15 @@ pub fn picker_button( popover.update(cx, |state, cx| state.dismiss(window, cx)); pick(emoji, window, cx); }); - picker(&entity, entity.read(cx).emoji_group, palette, close) + picker(&entity, entity.read(cx).emoji_group, t, close) }) } -pub fn picker(entity: &Entity, group: usize, palette: Palette, pick: Pick) -> Div { - let t = palette.tokens; +fn picker(entity: &Entity, group: usize, t: Tokens, pick: Pick) -> Div { let tabs = emoji::GROUPS.iter().enumerate().map(|(index, _)| { let entity = entity.clone(); let face = emoji::group(index).first().copied().unwrap_or_default(); - clickable(("emoji_group", index), palette, move |_, cx| { + clickable(("emoji_group", index), t, move |_, cx| { entity.update(cx, |yumush, cx| { yumush.emoji_group = index; cx.notify(); @@ -238,7 +231,7 @@ pub fn picker(entity: &Entity, group: usize, palette: Palette, pick: Pic let emoji: &'static str = emoji; clickable( SharedString::from(format!("emoji_{emoji}")), - palette, + t, move |window, cx| pick(emoji, window, cx), ) .size(px(size::CONTROL_SM)) @@ -266,7 +259,7 @@ pub fn picker(entity: &Entity, group: usize, palette: Palette, pick: Pic .child( div() .text_size(super::text(super::style::text::CAPTION)) - .text_color(palette.muted) + .text_color(t.dim()) .child("Twemoji · CC-BY 4.0"), ) } diff --git a/crates/client/src/gui/jump.rs b/crates/client/src/gui/jump.rs index 8b52724..6badb92 100644 --- a/crates/client/src/gui/jump.rs +++ b/crates/client/src/gui/jump.rs @@ -1,6 +1,7 @@ use crate::lang::{Label as _, Lang, w}; use crate::settings::{Activation, FontSize}; use common::model::{Community, CommunityKind, Id, Presence, User}; +use common::share::Kind; use gpui_kit::{ Context, Div, Entity, FontWeight, InteractiveElement, KeyDownEvent, ParentElement, ScrollHandle, StatefulInteractiveElement, Styled, Window, @@ -12,7 +13,7 @@ use gpui_kit::{ }; use super::{ - Palette, Yumush, avatar, + Yumush, avatar, builder::BuilderTab, chat::{Armed, View}, community_icon, community_name, @@ -123,12 +124,14 @@ impl Yumush { let call = self.chat.voice_community(); let unread = |id: Id| { self.chat + .session .unread .get(&id) .is_some_and(|unread| unread.messages > 0) }; let mut rooms: Vec<_> = self .chat + .session .communities .iter() .filter(|community| !matches!(community.kind, CommunityKind::Notes)) @@ -143,6 +146,7 @@ impl Yumush { }); let directs: Vec = self .chat + .session .communities .iter() .filter_map(|community| community.kind.peer().map(|peer| peer.id)) @@ -150,10 +154,11 @@ impl Yumush { let mut seen = std::collections::HashSet::new(); let people = self .chat + .session .friends .friends .iter() - .chain(self.chat.members.iter().map(|member| &member.user)) + .chain(self.chat.session.members.iter().map(|member| &member.user)) .filter(|user| { !directs.contains(&user.id) && self.user.as_ref().is_none_or(|me| me.id != user.id) @@ -217,36 +222,22 @@ impl Yumush { Row::new(place, label.to_string(), Glyph::Icon(icon)) }; let call = self.chat.voice_flags().map(|(muted, deafened)| { + let (mute, mute_icon) = if muted { + (w().jump.unmute, IconName::MicOff) + } else { + (w().jump.mute, IconName::Mic) + }; + let (deafen, deafen_icon) = if deafened { + (w().jump.undeafen, IconName::HeadphoneOff) + } else { + (w().jump.deafen, IconName::Headphones) + }; [ - action( - Place::Mute, - if muted { - w().jump.unmute - } else { - w().jump.mute - }, - if muted { - IconName::MicOff - } else { - IconName::Mic - }, - ), - action( - Place::Deafen, - if deafened { - w().jump.undeafen - } else { - w().jump.deafen - }, - if deafened { - IconName::HeadphoneOff - } else { - IconName::Headphones - }, - ), + action(Place::Mute, mute, mute_icon), + action(Place::Deafen, deafen, deafen_icon), action( Place::Share, - if self.network.sharing() { + if self.network.share_source(Kind::Screen).is_some() { w().jump.stop_sharing } else { w().jump.share_screen @@ -255,7 +246,7 @@ impl Yumush { ), action( Place::Camera, - if self.network.camera_on() { + if self.network.share_source(Kind::Camera).is_some() { w().jump.camera_off } else { w().jump.camera_on @@ -363,7 +354,7 @@ impl Yumush { pub(super) fn close_jump(&mut self, window: &mut Window, cx: &mut Context) { self.chat.goto.open = false; - self.chat.armed = None; + self.chat.session.armed = None; window.focus(&self.focus, cx); cx.notify(); } @@ -411,11 +402,11 @@ impl Yumush { Place::Friends => self.open_friends(window, cx), Place::Settings(section) => { self.show_view(View::Settings, window, cx); - self.chat.section = Some(section.id()); + self.chat.session.section = Some(section.id()); } Place::Setting(index) => { self.show_view(View::Settings, window, cx); - self.chat.section = Some(setting_rows()[index].0.id()); + self.chat.session.section = Some(setting_rows()[index].0.id()); } Place::Builder(tab) => { self.show_view(View::Builder, window, cx); @@ -439,30 +430,29 @@ impl Yumush { cx.notify(); } - fn glyph(&self, glyph: Glyph, palette: Palette) -> Div { - let t = palette.tokens; + fn glyph(&self, glyph: Glyph, t: Tokens) -> Div { let face = match glyph { Glyph::Icon(icon) => div() .text_color(t.faint()) .child(Icon::new(icon).size(px(size::ICON))), Glyph::Person(user) => presence_avatar( avatar( - palette, + t, &user, px(size::CHIP), t.text(text::CAPTION), - &self.chat.avatars, + &self.chat.session.avatars, ), self.presence_of(user.id), px(size::CHIP), - palette, + t, ), Glyph::Room(community) => community_icon( - palette, + t, &community, px(size::CHIP), t.text(text::CAPTION), - &self.chat.avatars, + &self.chat.session.avatars, ), }; div() @@ -474,11 +464,10 @@ impl Yumush { .child(face) } - pub(super) fn jump_box(&self, palette: Palette, cx: &mut Context) -> Option
{ + pub(super) fn jump_box(&self, t: Tokens, cx: &mut Context) -> Option
{ if !self.chat.goto.open { return None; } - let t = palette.tokens; let query = self.chat.goto.input.read(cx).value().trim().to_lowercase(); let places = self.places(cx); let cursor = self.chat.goto.cursor.min(places.len().saturating_sub(1)); @@ -534,7 +523,7 @@ impl Yumush { .min_w_0() .text_size(t.text(text::BODY)) .child(bare_input( - palette, + t, Input::new(&self.chat.goto.input) .token(super::glyph::token), )), @@ -568,7 +557,7 @@ impl Yumush { yumush.pick(place, window, cx) }) }) - .child(self.glyph(row.glyph, palette)) + .child(self.glyph(row.glyph, t)) .child(label_line(&row.label, &query, selected, t)) .when_some(row.hint, |line, hint| { line.child(words(hint, Text::Caption, Ink::Faint, t)) diff --git a/crates/client/src/gui/keys.rs b/crates/client/src/gui/keys.rs new file mode 100644 index 0000000..36fc53a --- /dev/null +++ b/crates/client/src/gui/keys.rs @@ -0,0 +1,21 @@ +const MOD_LABEL: &str = if cfg!(target_os = "macos") { + "Cmd" +} else { + "Ctrl" +}; + +macro_rules! bind { + ($keys:literal) => { + if cfg!(target_os = "macos") { + concat!("cmd-", $keys) + } else { + concat!("ctrl-", $keys) + } + }; +} + +pub(crate) use bind; + +pub fn label(keys: &str) -> String { + format!("{MOD_LABEL}+{keys}") +} diff --git a/crates/client/src/gui/media_view.rs b/crates/client/src/gui/media_view.rs index 3336f35..33e6768 100644 --- a/crates/client/src/gui/media_view.rs +++ b/crates/client/src/gui/media_view.rs @@ -1,4 +1,4 @@ -use super::style::{radius, size, space, text}; +use super::style::{Tokens, radius, size, space, text}; use super::text; use crate::lang::w; use crate::storage::Store; @@ -6,16 +6,18 @@ use common::model::Id; use std::{ collections::{HashMap, HashSet}, path::PathBuf, - sync::Arc, + sync::{ + Arc, + atomic::{AtomicU64, Ordering}, + }, time::Duration, }; use common::model::{Attachment, AttachmentKind, Message}; use gpui_kit::{ - App, AppContext, AsyncWindowContext, ClipboardEntry, ClipboardItem, Context, Entity, - FontWeight, Image, ImageFormat, InteractiveElement, IntoElement, ParentElement, - PathPromptOptions, RenderImage, StatefulInteractiveElement, Styled, Subscription, Task, - WeakEntity, Window, + App, AppContext, ClipboardEntry, ClipboardItem, Context, Entity, FontWeight, Image, + ImageFormat, InteractiveElement, IntoElement, ParentElement, PathPromptOptions, RenderImage, + StatefulInteractiveElement, Styled, Subscription, Task, Window, assets::IconName, component::{ Icon, WindowExt, @@ -28,13 +30,13 @@ use gpui_kit::{ }; use super::{ - Palette, Tooltip as _, Yumush, clickable, notify_error, storage, + Tooltip as _, Yumush, clickable, notify_error, storage, voice_note::{VoiceNote, bars}, }; use crate::{ embed::{self, Embed, EmbedKind}, media::{Player, voice_note as note}, - net::{Fail, NetworkHandle}, + net::Fail, }; const IMAGE_BOX: (f32, f32) = (size::MEDIA, 300.); @@ -46,9 +48,13 @@ pub struct LoadedEmbed { image: Option>, } -pub enum PlayState { - Loading, +#[derive(Default)] +pub enum Playing { + #[default] + Idle, + Loading(Id), Ready { + id: Id, player: Player, frame: Option>, generation: u64, @@ -57,9 +63,20 @@ pub enum PlayState { }, } -pub struct Playing { - attachment_id: Id, - state: PlayState, +impl Playing { + fn id(&self) -> Option { + match self { + Playing::Idle => None, + Playing::Loading(id) | Playing::Ready { id, .. } => Some(*id), + } + } + + fn player(&self) -> Option<&Player> { + match self { + Playing::Ready { player, .. } => Some(player), + Playing::Idle | Playing::Loading(_) => None, + } + } } #[derive(Default)] @@ -72,7 +89,8 @@ pub struct Media { embeds: HashMap, requested: HashSet, requested_links: HashSet, - playing: Option, + playing: Playing, + retired: Vec>, } impl Media { @@ -82,8 +100,25 @@ impl Media { pub fn leave(&mut self) { self.pending.clear(); - self.playing = None; + self.stop(); self.voice_note = VoiceNote::Idle; + self.requested + .retain(|id| self.thumbnails.contains_key(id) || self.waveforms.contains_key(id)); + self.requested_links + .retain(|url| self.embeds.contains_key(url)); + } + + fn stop(&mut self) { + if let Playing::Ready { + frame: Some(frame), .. + } = std::mem::take(&mut self.playing) + { + self.retired.push(frame); + } + } + + fn drain_retired(&mut self) -> std::vec::Drain<'_, Arc> { + self.retired.drain(..) } } @@ -124,12 +159,21 @@ fn fit(width: Option, height: Option, limit: (f32, f32)) -> (f32, f32) (width * scale, height * scale) } +const SAFE_EXTENSIONS: [&str; 16] = [ + "png", "jpg", "jpeg", "gif", "webp", "mp4", "webm", "mkv", "mov", "mp3", "m4a", "aac", "ogg", + "opus", "wav", "flac", +]; + +static TEMP: AtomicU64 = AtomicU64::new(0); + fn cache_path(attachment: &Attachment) -> Option { let directory = crate::storage::media_dir()?; let extension = attachment .name .rsplit_once('.') - .map(|(_, extension)| format!(".{extension}")) + .map(|(_, extension)| extension.to_ascii_lowercase()) + .filter(|extension| SAFE_EXTENSIONS.contains(&extension.as_str())) + .map(|extension| format!(".{extension}")) .unwrap_or_default(); Some(directory.join(format!("{}{extension}", attachment.id))) } @@ -148,26 +192,6 @@ fn duration_secs(player: &Player) -> f32 { .max(0.1) } -pub(super) async fn upload_file( - this: &WeakEntity, - network: &NetworkHandle, - community_id: Id, - path: PathBuf, - maximum: Option, - cx: &mut AsyncWindowContext, -) -> Result { - let _ = this.update(cx, |yumush, cx| { - yumush.chat.media.uploading += 1; - cx.notify(); - }); - let uploaded = network.upload_attachment(community_id, path, maximum).await; - let _ = this.update(cx, |yumush, cx| { - yumush.chat.media.uploading -= 1; - cx.notify(); - }); - uploaded -} - fn save_pasted(image: &Image) -> Option { let path = crate::storage::media_dir()?.join(format!( "paste-{}.{}", @@ -184,18 +208,13 @@ pub(super) fn into_render_image(frame: crate::media::Frame) -> Option Option> { - let buffer = image::RgbaImage::from_raw(frame.width, frame.height, frame.bgra.to_vec())?; - Some(Arc::new(RenderImage::new(vec![image::Frame::new(buffer)]))) -} - impl Yumush { pub(super) fn request_media(&mut self, cx: &mut Context) { let mut thumbnails = Vec::new(); let mut links = Vec::new(); let mut avatars = Vec::new(); let mut voices = Vec::new(); - for message in &self.chat.messages { + for message in &self.chat.session.messages { let forwarded = message.snippet.iter().flat_map(|snippet| &snippet.messages); for item in forwarded.clone() { if let Some(avatar_id) = item.avatar_id { @@ -208,18 +227,18 @@ impl Yumush { .chain(forwarded.flat_map(|item| &item.attachments)) { if attachment.kind == AttachmentKind::Image - && self.chat.media.requested.insert(attachment.id) + && self.chat.session.media.requested.insert(attachment.id) { thumbnails.push(attachment.id); } if note::is_voice_note(attachment) - && self.chat.media.requested.insert(attachment.id) + && self.chat.session.media.requested.insert(attachment.id) { voices.push(attachment.clone()); } } for url in embed::urls(&message.body) { - if self.chat.media.requested_links.insert(url.clone()) { + if self.chat.session.media.requested_links.insert(url.clone()) { links.push(url); } } @@ -237,7 +256,12 @@ impl Yumush { }; let _ = this.update(cx, |yumush, cx| { if let Some(image) = to_image(bytes) { - yumush.chat.media.thumbnails.insert(attachment_id, image); + yumush + .chat + .session + .media + .thumbnails + .insert(attachment_id, image); cx.notify(); } }); @@ -260,7 +284,12 @@ impl Yumush { return; }; let _ = this.update(cx, |yumush, cx| { - yumush.chat.media.waveforms.insert(attachment_id, waveform); + yumush + .chat + .session + .media + .waveforms + .insert(attachment_id, waveform); cx.notify(); }); }) @@ -283,6 +312,7 @@ impl Yumush { let _ = this.update(cx, |yumush, cx| { yumush .chat + .session .media .embeds .insert(url, LoadedEmbed { embed, image }); @@ -335,25 +365,25 @@ impl Yumush { } fn attach_paths(&mut self, paths: Vec, window: &mut Window, cx: &mut Context) { - let Some(community_id) = self.chat.selected_community_id else { + let Some(community_id) = self.chat.session.selected_community_id else { return; }; - let network = self.network.clone(); - let maximum = self - .server - .as_ref() - .map(|settings| settings.max_attachment_bytes); + let uploads: Vec<_> = paths + .into_iter() + .map(|path| (path.clone(), self.upload(community_id, path, cx))) + .collect(); cx.spawn_in(window, async move |this, cx| { - for path in paths { - let result = - upload_file(&this, &network, community_id, path.clone(), maximum, cx).await; + for (path, upload) in uploads { + let result = upload.await; if Store::Media.holds(&path) { let _ = std::fs::remove_file(&path); } let _ = this.update(cx, |yumush, cx| { - if let Ok(attachment) = &result { - yumush.chat.media.pending.push(attachment.clone()); + if let Ok(attachment) = &result + && yumush.chat.session.selected_community_id == Some(community_id) + { + yumush.chat.session.media.pending.push(attachment.clone()); } cx.notify(); }); @@ -365,8 +395,32 @@ impl Yumush { .detach(); } + pub(super) fn upload( + &mut self, + community_id: Id, + path: PathBuf, + cx: &mut Context, + ) -> Task> { + let network = self.network.clone(); + let maximum = self + .server + .as_ref() + .map(|settings| settings.max_attachment_bytes); + self.chat.session.media.uploading += 1; + cx.notify(); + cx.spawn(async move |this, cx| { + let uploaded = network.upload_attachment(community_id, path, maximum).await; + let _ = this.update(cx, |yumush, cx| { + yumush.chat.session.media.uploading -= 1; + cx.notify(); + }); + uploaded + }) + } + fn remove_pending(&mut self, attachment_id: Id, cx: &mut Context) { self.chat + .session .media .pending .retain(|attachment| attachment.id != attachment_id); @@ -386,10 +440,14 @@ impl Yumush { return Ok(path); } let bytes = network.download_attachment(attachment.id, false).await?; + let temp = + path.with_extension(format!("{}.part", TEMP.fetch_add(1, Ordering::Relaxed))); cx.background_executor() .spawn({ let path = path.clone(); - async move { std::fs::write(&path, bytes) } + async move { + std::fs::write(&temp, bytes).and_then(|()| std::fs::rename(&temp, &path)) + } }) .await .map_err(|_| Fail::Protocol)?; @@ -398,7 +456,7 @@ impl Yumush { } fn open_attachment( - &self, + &mut self, attachment: &Attachment, window: &mut Window, cx: &mut Context, @@ -414,7 +472,7 @@ impl Yumush { } fn save_attachment( - &self, + &mut self, attachment: &Attachment, window: &mut Window, cx: &mut Context, @@ -437,20 +495,16 @@ impl Yumush { } fn play(&mut self, attachment: &Attachment, window: &mut Window, cx: &mut Context) { - if let Some(playing) = &self.chat.media.playing - && playing.attachment_id == attachment.id - { - if let PlayState::Ready { player, .. } = &playing.state { + let playing = &self.chat.session.media.playing; + if playing.id() == Some(attachment.id) { + if let Some(player) = playing.player() { player.toggle(); } cx.notify(); return; } self.stop_playing(cx); - self.chat.media.playing = Some(Playing { - attachment_id: attachment.id, - state: PlayState::Loading, - }); + self.chat.session.media.playing = Playing::Loading(attachment.id); cx.notify(); let fetched = self.fetch_file(attachment, cx); @@ -466,19 +520,14 @@ impl Yumush { Err(error) => Err(error.to_string()), }; let _ = this.update_in(cx, |yumush, window, cx| { - let current = yumush - .chat - .media - .playing - .as_ref() - .is_some_and(|playing| playing.attachment_id == attachment_id); - if !current { + if !matches!(yumush.chat.session.media.playing, Playing::Loading(id) if id == attachment_id) + { return; } match opened { Ok(player) => yumush.start_player(attachment_id, player, cx), Err(error) => { - yumush.chat.media.playing = None; + yumush.chat.session.media.playing = Playing::Idle; window.push_notification(Notification::error(error), cx); } } @@ -498,40 +547,36 @@ impl Yumush { yumush.seek_playing(value.start(), cx); }); player.play(); - self.chat.media.playing = Some(Playing { - attachment_id, - state: PlayState::Ready { - player, - frame: None, - generation: 0, - seek, - _subscription: subscription, - }, - }); + self.chat.session.media.playing = Playing::Ready { + id: attachment_id, + player, + frame: None, + generation: 0, + seek, + _subscription: subscription, + }; } pub(super) fn media_playing(&self) -> bool { - matches!( - &self.chat.media.playing, - Some(Playing { - state: PlayState::Ready { player, .. }, - .. - }) if player.playing() - ) + self.chat + .session + .media + .playing + .player() + .is_some_and(|player| player.playing()) } pub(super) fn tick_player(&mut self, window: &mut Window, cx: &mut Context) { - let Some(Playing { - state: - PlayState::Ready { - player, - frame, - generation, - seek, - .. - }, + for frame in self.chat.session.media.drain_retired() { + cx.drop_image(frame, Some(&mut *window)); + } + let Playing::Ready { + player, + frame, + generation, + seek, .. - }) = &mut self.chat.media.playing + } = &mut self.chat.session.media.playing else { return; }; @@ -542,8 +587,9 @@ impl Yumush { && next.generation != *generation { *generation = next.generation; - if let Some(old) = std::mem::replace(frame, to_render_image(&next)) { - cx.drop_image(old, Some(window)); + let image = into_render_image(next); + if let Some(old) = std::mem::replace(frame, image) { + cx.drop_image(old, Some(&mut *window)); } } let position = player.position().as_secs_f32(); @@ -552,24 +598,15 @@ impl Yumush { } fn seek_playing(&mut self, seconds: f32, cx: &mut Context) { - if let Some(Playing { - state: PlayState::Ready { player, .. }, - .. - }) = &self.chat.media.playing - { + if let Some(player) = self.chat.session.media.playing.player() { player.seek(Duration::from_secs_f32(seconds.max(0.))); } cx.notify(); } pub(super) fn stop_playing(&mut self, cx: &mut Context) { - if let Some(Playing { - state: PlayState::Ready { - frame: Some(frame), .. - }, - .. - }) = self.chat.media.playing.take() - { + self.chat.session.media.stop(); + for frame in self.chat.session.media.drain_retired() { cx.defer(move |cx| cx.drop_image(frame, None)); } } @@ -579,7 +616,7 @@ pub fn attachments( attachments: &[Attachment], media: &Media, entity: &Entity, - palette: Palette, + t: Tokens, ) -> Option { if attachments.is_empty() { return None; @@ -588,7 +625,7 @@ pub fn attachments( div().flex().flex_col().gap(px(space::SM)).children( attachments .iter() - .map(|attachment| attachment_view(attachment, media, entity, palette)), + .map(|attachment| attachment_view(attachment, media, entity, t)), ), ) } @@ -597,14 +634,14 @@ fn attachment_view( attachment: &Attachment, media: &Media, entity: &Entity, - palette: Palette, + t: Tokens, ) -> gpui_kit::AnyElement { match attachment.kind { - AttachmentKind::Image => image_view(attachment, media, entity, palette).into_any_element(), + AttachmentKind::Image => image_view(attachment, media, entity, t).into_any_element(), AttachmentKind::Video | AttachmentKind::Audio => { - player_view(attachment, media, entity, palette).into_any_element() + player_view(attachment, media, entity, t).into_any_element() } - AttachmentKind::File => file_view(attachment, entity, palette).into_any_element(), + AttachmentKind::File => file_view(attachment, entity, t).into_any_element(), } } @@ -624,19 +661,17 @@ fn image_view( attachment: &Attachment, media: &Media, entity: &Entity, - palette: Palette, + t: Tokens, ) -> impl IntoElement { let (width, height) = fit(attachment.width, attachment.height, IMAGE_BOX); - let open = on_attachment(entity, attachment, |yumush, attachment, window, cx| { - yumush.open_attachment(attachment, window, cx) - }); + let open = on_attachment(entity, attachment, Yumush::open_attachment); div() .id(format!("attachment_{}", attachment.id)) .w(px(width)) .h(px(height)) .rounded(px(radius::MD)) .overflow_hidden() - .bg(palette.field) + .bg(t.raise()) .cursor_pointer() .on_click(move |_, window, cx| open(window, cx)) .children( @@ -647,7 +682,7 @@ fn image_view( ) } -fn card(palette: Palette) -> gpui_kit::Div { +fn card(t: Tokens) -> gpui_kit::Div { div() .max_w(px(VIDEO_BOX.0)) .flex() @@ -656,10 +691,10 @@ fn card(palette: Palette) -> gpui_kit::Div { .px(px(space::MD)) .py(px(space::MD)) .rounded(px(radius::MD)) - .bg(palette.panel) + .bg(t.ground()) } -fn name_block(attachment: &Attachment, detail: String, palette: Palette) -> impl IntoElement { +fn name_block(attachment: &Attachment, detail: String, t: Tokens) -> impl IntoElement { div() .flex_1() .min_w_0() @@ -668,7 +703,7 @@ fn name_block(attachment: &Attachment, detail: String, palette: Palette) -> impl .child( div() .min_w_0() - .text_color(palette.text) + .text_color(t.paper()) .child(super::glyph::line( attachment.name.clone().into(), super::text(super::style::text::UI), @@ -677,7 +712,7 @@ fn name_block(attachment: &Attachment, detail: String, palette: Palette) -> impl .child( div() .text_size(text(text::CAPTION)) - .text_color(palette.muted) + .text_color(t.dim()) .child(detail), ) } @@ -686,7 +721,7 @@ fn icon_button( id: String, icon: IconName, tip: &'static str, - palette: Palette, + t: Tokens, on_click: impl Fn(&mut Window, &mut App) + 'static, ) -> impl IntoElement { super::parts::icon_button( @@ -695,31 +730,25 @@ fn icon_button( tip, super::parts::Tone::Idle, super::parts::Scale::Normal, - palette.tokens, + t, on_click, ) } -fn file_view( - attachment: &Attachment, - entity: &Entity, - palette: Palette, -) -> impl IntoElement { - card(palette) +fn file_view(attachment: &Attachment, entity: &Entity, t: Tokens) -> impl IntoElement { + card(t) .child( Icon::new(IconName::File) .size(px(size::ICON)) - .text_color(palette.muted), + .text_color(t.dim()), ) - .child(name_block(attachment, storage(attachment.size), palette)) + .child(name_block(attachment, storage(attachment.size), t)) .child(icon_button( format!("save_{}", attachment.id), IconName::ArrowDown, w().media_view.save, - palette, - on_attachment(entity, attachment, |yumush, attachment, window, cx| { - yumush.save_attachment(attachment, window, cx) - }), + t, + on_attachment(entity, attachment, Yumush::save_attachment), )) } @@ -727,14 +756,12 @@ fn player_view( attachment: &Attachment, media: &Media, entity: &Entity, - palette: Palette, + t: Tokens, ) -> impl IntoElement { - let state = media - .playing - .as_ref() - .filter(|playing| playing.attachment_id == attachment.id) - .map(|playing| &playing.state); - let playing = matches!(state, Some(PlayState::Ready { player, .. }) if player.playing()); + let state = Some(&media.playing).filter(|playing| playing.id() == Some(attachment.id)); + let playing = state + .and_then(Playing::player) + .is_some_and(|player| player.playing()); let toggle = icon_button( format!("play_{}_{playing}", attachment.id), if playing { @@ -747,55 +774,52 @@ fn player_view( } else { w().media_view.play }, - palette, - on_attachment(entity, attachment, |yumush, attachment, window, cx| { - yumush.play(attachment, window, cx) - }), + t, + on_attachment(entity, attachment, Yumush::play), ); let voice = note::is_voice_note(attachment); let detail = match state { - Some(PlayState::Loading) => "…".to_string(), - Some(PlayState::Ready { player, .. }) => format!( + Some(Playing::Loading(_)) => "…".to_string(), + Some(Playing::Ready { player, .. }) => format!( "{} / {}", time_text(player.position()), time_text(player.info().duration.unwrap_or_default()) ), - None if voice => media + Some(Playing::Idle) | None if voice => media .waveforms .get(&attachment.id) .map_or("…".to_string(), |waveform| time_text(waveform.duration)), - None => storage(attachment.size), + Some(Playing::Idle) | None => storage(attachment.size), }; - let controls = card(palette) - .child(toggle) - .when(voice, |this| { - this.child(waveform_view(attachment, media, entity, state, palette)) - .child( - div() - .text_size(text(text::CAPTION)) - .text_color(palette.muted) - .child(detail.clone()), - ) - }) - .when(!voice, |this| { - this.child(name_block(attachment, detail, palette)) - }) - .when_some( - match state { - Some(PlayState::Ready { seek, .. }) if !voice => Some(seek), - _ => None, - }, - |this, seek| { + let controls = if voice { + card(t) + .child(toggle) + .child(waveform_view(attachment, media, entity, state, t)) + .child( + div() + .text_size(text(text::CAPTION)) + .text_color(t.dim()) + .child(detail), + ) + } else { + let seek = match state { + Some(Playing::Ready { seek, .. }) => Some(seek), + _ => None, + }; + card(t) + .child(toggle) + .child(name_block(attachment, detail, t)) + .when_some(seek, |this, seek| { this.child( div() .w(px(size::THUMB)) - .child(super::parts::slider(seek, palette.tokens)), + .child(super::parts::slider(seek, t)), ) - }, - ); + }) + }; let video = match state { - Some(PlayState::Ready { player, frame, .. }) => player + Some(Playing::Ready { player, frame, .. }) => player .info() .video .map(|(width, height)| (frame, width, height)), @@ -814,7 +838,7 @@ fn player_view( .h(px(height)) .rounded(px(radius::MD)) .overflow_hidden() - .bg(palette.tokens.ground()) + .bg(t.ground()) .children(frame.clone().map(|frame| img(frame).size_full())), ) }) @@ -825,42 +849,40 @@ fn waveform_view( attachment: &Attachment, media: &Media, entity: &Entity, - state: Option<&PlayState>, - palette: Palette, + state: Option<&Playing>, + t: Tokens, ) -> impl IntoElement { let levels = media .waveforms .get(&attachment.id) .map_or(&[][..], |waveform| waveform.peaks.as_slice()); match state { - Some(PlayState::Ready { player, .. }) => { + Some(Playing::Ready { player, .. }) => { let duration = duration_secs(player); let progress = player.position().as_secs_f32() / duration; let entity = entity.clone(); - bars(levels, progress, palette, move |index, _, cx| { + bars(levels, progress, t, true, move |index, _, cx| { entity.update(cx, |yumush, cx| { yumush.seek_playing(index as f32 / note::BARS as f32 * duration, cx) }) }) } _ => { - let play = on_attachment(entity, attachment, |yumush, attachment, window, cx| { - yumush.play(attachment, window, cx) - }); - bars(levels, 0., palette, move |_, window, cx| play(window, cx)) + let play = on_attachment(entity, attachment, Yumush::play); + bars(levels, 0., t, false, move |_, window, cx| play(window, cx)) } } } -pub fn embeds(message: &Message, media: &Media, palette: Palette) -> Vec { +pub fn embeds(message: &Message, media: &Media, t: Tokens) -> Vec { embed::urls(&message.body) .into_iter() .filter_map(|url| media.embeds.get(&url)) - .map(|loaded| embed_view(loaded, palette)) + .map(|loaded| embed_view(loaded, t)) .collect() } -fn embed_view(loaded: &LoadedEmbed, palette: Palette) -> impl IntoElement { +fn embed_view(loaded: &LoadedEmbed, t: Tokens) -> impl IntoElement { let embed = &loaded.embed; let url = embed.url.clone(); let image = loaded.image.clone().map(|image| { @@ -890,19 +912,19 @@ fn embed_view(loaded: &LoadedEmbed, palette: Palette) -> impl IntoElement { .py(px(space::MD)) .rounded(px(radius::MD)) .border_l_2() - .border_color(palette.border) - .bg(palette.panel) + .border_color(t.thread()) + .bg(t.ground()) .children(embed.site.clone().map(|site| { div() .text_size(text(text::CAPTION)) - .text_color(palette.muted) + .text_color(t.dim()) .child(site) })) .children(embed.title.clone().map(|title| { div() .id(format!("embed_{url}")) .font_weight(FontWeight::SEMIBOLD) - .text_color(palette.text) + .text_color(t.paper()) .cursor_pointer() .hover(|style| style.underline()) .on_click(move |_, _, cx| cx.open_url(&url)) @@ -914,7 +936,7 @@ fn embed_view(loaded: &LoadedEmbed, palette: Palette) -> impl IntoElement { .children(embed.description.clone().map(|description| { div() .text_size(text(text::LABEL)) - .text_color(palette.body) + .text_color(t.paper()) .line_clamp(3) .child(super::glyph::wrapped( description.into(), @@ -924,11 +946,7 @@ fn embed_view(loaded: &LoadedEmbed, palette: Palette) -> impl IntoElement { .children(image) } -pub fn pending_row( - media: &Media, - entity: &Entity, - palette: Palette, -) -> Option { +pub fn pending_row(media: &Media, entity: &Entity, t: Tokens) -> Option { if media.pending.is_empty() && !media.uploading() { return None; } @@ -949,22 +967,16 @@ pub fn pending_row( .pr(px(space::XS)) .py(px(space::XS)) .rounded(px(radius::MD)) - .bg(palette.hover) + .bg(t.hov()) .text_size(text(text::CAPTION)) .child(div().max_w(px(size::SIDEBAR)).child(super::glyph::line( attachment.name.clone().into(), super::text(super::style::text::CAPTION), ))) .child( - clickable( - format!("unattach_{}", attachment.id), - palette, - move |_, cx| { - entity.update(cx, |yumush, cx| { - yumush.remove_pending(attachment_id, cx) - }) - }, - ) + clickable(format!("unattach_{}", attachment.id), t, move |_, cx| { + entity.update(cx, |yumush, cx| yumush.remove_pending(attachment_id, cx)) + }) .tip(w().media_view.remove) .size(px(size::CHIP)) .flex() @@ -980,7 +992,7 @@ pub fn pending_row( .px(px(space::MD)) .py(px(space::XS)) .text_size(text(text::CAPTION)) - .text_color(palette.muted) + .text_color(t.dim()) .child("…"), ) }), diff --git a/crates/client/src/gui/message_actions.rs b/crates/client/src/gui/message_actions.rs index a9c6dc9..59d06cd 100644 --- a/crates/client/src/gui/message_actions.rs +++ b/crates/client/src/gui/message_actions.rs @@ -20,22 +20,22 @@ use gpui_kit::{ }; use super::{ - Palette, Trigger, Yumush, avatar, - chat::{Chat, ReportTarget}, + Trigger, Yumush, avatar, + chat::{Armed, Chat, ReportTarget}, clickable, composer::trigger_icon, entity_action, millis_time, notify_error, - parts::{Press, Scale, Tone, button, icon_button}, + parts::{Press, Scale, Tone, button, icon_button, surface}, sidebar, - style::{radius, size, space, text}, - widget::{field, panel, search_text, spawn_done}, + style::{Tokens, radius, size, space, text}, + widget::{field, search_text, spawn_done}, }; pub fn reactions( message: &Message, me: Option<&User>, entity: &Entity, - palette: Palette, + t: Tokens, ) -> impl IntoElement { let me_id = me.map(|me| me.id); @@ -56,7 +56,7 @@ pub fn reactions( clickable( format!("reaction_{}_{}", message.id, reaction.emoji), - palette, + t, move |window, cx| { let emoji = emoji.clone(); entity.update(cx, |yumush, cx| { @@ -71,23 +71,15 @@ pub fn reactions( .px(px(space::SM)) .rounded_full() .border_1() - .border_color(if mine { palette.accent } else { palette.border }) - .bg(if mine { - palette.tokens.press() - } else { - palette.panel - }) + .border_color(if mine { t.paper() } else { t.thread() }) + .bg(if mine { t.press() } else { t.ground() }) .text_size(text(text::CAPTION)) .child(super::glyph::picture(&chip_emoji, px(size::ICON_SM))) - .child(div().text_color(palette.muted).child(count.to_string())) + .child(div().text_color(t.dim()).child(count.to_string())) })) } -pub fn react_popover( - message: &Message, - entity: &Entity, - palette: Palette, -) -> impl IntoElement { +pub fn react_popover(message: &Message, entity: &Entity, t: Tokens) -> impl IntoElement { let message_id = message.id; let entity = entity.clone(); let reacting = entity.clone(); @@ -96,7 +88,7 @@ pub fn react_popover( .anchor(Anchor::BottomRight) .on_open_change(move |open, _, cx| { reacting.update(cx, |yumush, cx| { - if track(&mut yumush.chat.reacting, message_id, *open) { + if track(&mut yumush.chat.session.reacting, message_id, *open) { cx.notify(); } }); @@ -106,11 +98,11 @@ pub fn react_popover( format!("react_trigger_{}", message.id), IconName::FaceSlightlySmiling, 24., - palette, + t, )) .content(move |_, _, cx| { let popover = cx.entity(); - panel(palette) + surface(t) .flex() .gap(px(space::XXS)) .p(px(space::XS)) @@ -119,7 +111,7 @@ pub fn react_popover( let popover = popover.clone(); clickable( format!("react_{emoji}_{message_id}"), - palette, + t, move |window, cx| { popover.update(cx, |state, cx| state.dismiss(window, cx)); entity.update(cx, |yumush, cx| { @@ -156,7 +148,7 @@ pub fn quote_line( message: &Message, chat: &Chat, entity: &Entity, - palette: Palette, + t: Tokens, ) -> Option { let frame = div() .id(format!("quote_{}", message.id)) @@ -165,12 +157,14 @@ pub fn quote_line( .gap(px(space::SM)) .pl(px(space::SM)) .border_l_2() - .border_color(palette.border) + .border_color(t.thread()) .text_size(text(text::CAPTION)) - .text_color(palette.muted); + .text_color(t.dim()); let (quote, deleted) = match message.reply.as_ref()? { Reply::Quote(quote) => (quote, false), - Reply::Deleted(Some(quote)) if chat.revealed.contains("e.message_id) => (quote, true), + Reply::Deleted(Some(quote)) if chat.session.revealed.contains("e.message_id) => { + (quote, true) + } Reply::Deleted(Some(quote)) => { return Some(reveal(frame.italic(), quote.message_id, entity)); } @@ -191,18 +185,18 @@ pub fn quote_line( }) .children(author.map(|user| { avatar( - palette, + t, user, px(size::ICON_SM), text(text::CAPTION), - &chat.avatars, + &chat.session.avatars, ) })) .children(author.map(|user| { div() .flex_shrink_0() .font_weight(FontWeight::SEMIBOLD) - .text_color(palette.tinted(user.id)) + .text_color(t.person(user.id)) .child(user.username.clone()) })) .child(div().flex_1().min_w_0().child(super::glyph::line( @@ -218,19 +212,19 @@ fn reveal(frame: Stateful
, message_id: Id, entity: &Entity) -> Stat .cursor_pointer() .on_click(move |_, _, cx| { entity.update(cx, |yumush, cx| { - yumush.chat.revealed.insert(message_id); + yumush.chat.session.revealed.insert(message_id); cx.notify(); }) }) .child(w().message_actions.deleted) } -pub fn reveal_deleted(message_id: Id, entity: &Entity, palette: Palette) -> Stateful
{ +pub fn reveal_deleted(message_id: Id, entity: &Entity, t: Tokens) -> Stateful
{ reveal( div() .id(format!("reveal_{message_id}")) .italic() - .text_color(palette.muted), + .text_color(t.dim()), message_id, entity, ) @@ -243,7 +237,7 @@ pub fn collapse_deleted(message_id: Id, entity: &Entity) -> Stateful
, - palette: Palette, + t: Tokens, ) -> AnyElement { let message_id = message.id; if !builder { @@ -282,12 +276,13 @@ pub fn edited_mark( let clock = yumush.settings.clock(); let mut edits = yumush .chat + .session .edits .get(&message_id) .cloned() .unwrap_or_default(); edits.sort_by_key(|edit| std::cmp::Reverse(edit.edited_at)); - panel(palette) + surface(t) .flex() .flex_col() .gap(px(space::XS)) @@ -301,7 +296,7 @@ pub fn edited_mark( .child( div() .flex_shrink_0() - .text_color(palette.muted) + .text_color(t.dim()) .child(millis_time(edit.edited_at, clock)), ) .child(div().min_w_0().child(edit.body)) @@ -310,10 +305,10 @@ pub fn edited_mark( .into_any_element() } -pub fn pin_mark(palette: Palette) -> impl IntoElement { +pub fn pin_mark(t: Tokens) -> impl IntoElement { div() .flex_shrink_0() - .text_color(palette.muted) + .text_color(t.dim()) .child(super::parts::small_icon(IconName::Pin)) } @@ -329,22 +324,18 @@ fn jump_row( hit: &Hit, entity: &Entity, popover: &Entity, - palette: Palette, + t: Tokens, ) -> Stateful
{ let entity = entity.clone(); let popover = popover.clone(); let message_id = hit.message_id; - clickable( - format!("{prefix}_{message_id}"), - palette, - move |window, cx| { - popover.update(cx, |state, cx| state.dismiss(window, cx)); - entity.update(cx, |yumush, cx| { - yumush.go_to_message(message_id, window, cx) - }); - }, - ) + clickable(format!("{prefix}_{message_id}"), t, move |window, cx| { + popover.update(cx, |state, cx| state.dismiss(window, cx)); + entity.update(cx, |yumush, cx| { + yumush.go_to_message(message_id, window, cx) + }); + }) .flex() .gap(px(space::SM)) .px(px(space::SM)) @@ -363,20 +354,16 @@ fn person_row( user: &User, entity: &Entity, popover: &Entity, - palette: Palette, + t: Tokens, ) -> Stateful
{ let entity = entity.clone(); let popover = popover.clone(); let user_id = user.id; - clickable( - format!("search_person_{user_id}"), - palette, - move |window, cx| { - popover.update(cx, |state, cx| state.dismiss(window, cx)); - entity.update(cx, |yumush, cx| yumush.open_direct(user_id, window, cx)); - }, - ) + clickable(format!("search_person_{user_id}"), t, move |window, cx| { + popover.update(cx, |state, cx| state.dismiss(window, cx)); + entity.update(cx, |yumush, cx| yumush.open_direct(user_id, window, cx)); + }) .flex() .items_center() .gap(px(space::SM)) @@ -390,24 +377,10 @@ pub fn search_popover( chat: &Chat, clock: &'static str, entity: &Entity, - palette: Palette, + t: Tokens, ) -> impl IntoElement { let entity = entity.clone(); let input = chat.community_search.clone(); - let hits: Vec = chat - .community_hits - .iter() - .map(|hit| Hit { - message_id: hit.message.id, - name: hit - .author - .as_ref() - .map(|user| user.username.clone()) - .unwrap_or_default(), - time: Some(millis_time(hit.message.created_at, clock)), - body: message_text(&hit.message), - }) - .collect(); Popover::new("search_popover") .anchor(Anchor::TopRight) @@ -423,10 +396,10 @@ pub fn search_popover( .items_center() .gap(px(space::SM)) .rounded(px(radius::MD)) - .bg(palette.tokens.raise()) + .bg(t.raise()) .cursor_pointer() .text_size(text(text::UI)) - .text_color(palette.tokens.faint()) + .text_color(t.faint()) .child(super::parts::small_icon(IconName::Search)) .child(w().chat.find), )) @@ -437,11 +410,32 @@ pub fn search_popover( } let query = search_text(&input, cx); let yumush = entity.read(cx); + let hits: Vec = if query.is_empty() { + Vec::new() + } else { + yumush + .chat + .session + .community_hits + .iter() + .map(|hit| Hit { + message_id: hit.message.id, + name: hit + .author + .as_ref() + .map(|user| user.username.clone()) + .unwrap_or_default(), + time: Some(millis_time(hit.message.created_at, clock)), + body: message_text(&hit.message), + }) + .collect() + }; let people: Vec<&User> = if query.is_empty() { vec![] } else { yumush .chat + .session .members .iter() .map(|member| &member.user) @@ -451,24 +445,25 @@ pub fn search_popover( .take(5) .collect() }; - panel(palette) + surface(t) .w(px(size::POPOVER)) .p(px(space::XS)) .flex() .flex_col() .gap(px(space::XS)) - .child(sidebar::input_box(&input, palette)) - .children((!people.is_empty()).then(|| { - super::parts::caption_head(w().message_actions.people, palette.tokens) - })) + .child(sidebar::input_box(&input, t)) + .children( + (!people.is_empty()) + .then(|| super::parts::caption_head(w().message_actions.people, t)), + ) .children(people.iter().map(|user| { - person_row(user, &entity, &popover, palette) + person_row(user, &entity, &popover, t) .child(avatar( - palette, + t, user, px(size::ICON_SM), text(text::CAPTION), - &yumush.chat.avatars, + &yumush.chat.session.avatars, )) .child( div() @@ -478,15 +473,14 @@ pub fn search_popover( ) })) .children( - (!query.is_empty() && !hits.is_empty()) - .then(|| super::parts::caption_head(w().common.messages, palette.tokens)), + (!hits.is_empty()).then(|| super::parts::caption_head(w().common.messages, t)), ) .children(hits.iter().map(|hit| { - jump_row("search_hit", hit, &entity, &popover, palette) + jump_row("search_hit", hit, &entity, &popover, t) .children(hit.time.as_ref().map(|time| { div() .flex_shrink_0() - .text_color(palette.muted) + .text_color(t.dim()) .child(time.clone()) })) .child(div().flex_1().min_w_0().child(super::glyph::line( @@ -497,9 +491,10 @@ pub fn search_popover( }) } -pub fn pins_popover(chat: &Chat, entity: &Entity, palette: Palette) -> impl IntoElement { +pub fn pins_popover(chat: &Chat, entity: &Entity, t: Tokens) -> impl IntoElement { let entity = entity.clone(); let pins: Vec = chat + .session .pins .iter() .map(|pin| Hit { @@ -516,23 +511,25 @@ pub fn pins_popover(chat: &Chat, entity: &Entity, palette: Palette) -> i Popover::new("pins_popover") .anchor(Anchor::TopRight) .appearance(false) - .trigger(trigger_icon("pins_trigger", IconName::Pin, 24., palette)) + .trigger(trigger_icon("pins_trigger", IconName::Pin, 24., t)) .content(move |_, _, cx| { let popover = cx.entity(); - panel(palette) + surface(t) .w(px(size::POPOVER)) .p(px(space::XS)) .flex() .flex_col() .gap(px(space::XXS)) .children(pins.iter().map(|hit| { - jump_row("pin_hit", hit, &entity, &popover, palette).child( - div().flex_1().min_w_0().text_color(palette.muted).child( - super::glyph::line( + jump_row("pin_hit", hit, &entity, &popover, t).child( + div() + .flex_1() + .min_w_0() + .text_color(t.dim()) + .child(super::glyph::line( hit.body.clone().into(), super::text(super::style::text::UI), - ), - ), + )), ) })) }) @@ -543,7 +540,7 @@ pub fn actions( chat: &Chat, me: Option<&User>, entity: &Entity, - palette: Palette, + t: Tokens, ) -> impl IntoElement { let mine = me.is_some_and(|me| me.id == message.user_id); let editable = mine && !message.body.is_empty() && message.snippet.is_none(); @@ -551,11 +548,22 @@ pub fn actions( let pinnable = me.is_some_and(|me| chat.can_pin(me)); let reportable = me.is_some_and(|me| me.id != message.user_id); let id = message.id; - let armed = chat.pending_message_delete == Some(id); - let shown = armed || chat.hover_row == Some(id) || chat.engaged(id); + let armed = chat.session.armed == Some(Armed::DeleteMessage(id)); + let shown = armed || chat.session.hover_row == Some(id) || chat.engaged(id); let hover = entity.clone(); + let (pin_tip, pin_icon) = if message.pinned { + (w().message_actions.unpin, IconName::PinOff) + } else { + (w().message_actions.pin, IconName::Pin) + }; + let button = |name: &'static str, + tip: &'static str, + icon: IconName, + run: fn(&mut Yumush, Id, &mut Window, &mut Context)| { + action(entity, t, id, name, tip, icon, run) + }; - panel(palette) + surface(t) .id(format!("message_actions_{id}")) .flex() .items_center() @@ -571,75 +579,46 @@ pub fn actions( .on_hover(move |hovered, _, cx| { if shown || !*hovered { hover.update(cx, |yumush, cx| { - if track(&mut yumush.chat.hover_bar, id, *hovered) { + if track(&mut yumush.chat.session.hover_bar, id, *hovered) { cx.notify(); } }); } }) - .child(action( - entity, - palette, - id, + .child(button( "reply", w().message_actions.reply, IconName::Reply, |yumush, id, window, cx| yumush.reply(id, window, cx), )) - .child(react_popover(message, entity, palette)) + .child(react_popover(message, entity, t)) .children(editable.then(|| { - action( - entity, - palette, - id, + button( "edit", w().message_actions.edit, IconName::Pencil, |yumush, id, window, cx| yumush.edit(id, window, cx), ) })) - .child(action( - entity, - palette, - id, + .child(button( "forward", w().message_actions.forward, IconName::Forward, |yumush, id, window, cx| yumush.open_forward(vec![id], window, cx), )) - .child(action( - entity, - palette, - id, + .child(button( "select", w().message_actions.select, IconName::ListChecks, |yumush, id, window, cx| yumush.start_select(id, window, cx), )) .children(pinnable.then(|| { - action( - entity, - palette, - id, - "pin", - if message.pinned { - w().message_actions.unpin - } else { - w().message_actions.pin - }, - if message.pinned { - IconName::PinOff - } else { - IconName::Pin - }, - |yumush, id, window, cx| yumush.toggle_pin(id, window, cx), - ) + button("pin", pin_tip, pin_icon, |yumush, id, window, cx| { + yumush.toggle_pin(id, window, cx) + }) })) .children(reportable.then(|| { - action( - entity, - palette, - id, + button( "report", w().message_actions.report, IconName::TriangleAlert, @@ -647,10 +626,7 @@ pub fn actions( ) })) .children(deletable.then(|| { - action( - entity, - palette, - id, + button( "delete", if armed { w().message_actions.confirm @@ -660,27 +636,25 @@ pub fn actions( IconName::Trash, |yumush, id, window, cx| yumush.request_message_delete(id, window, cx), ) - .when(armed, |this| { - this.text_color(palette.danger).bg(palette.tokens.press()) - }) + .when(armed, |this| this.text_color(t.bad()).bg(t.press())) })) } pub fn report_bar( reason: &Entity, entity: &Entity, - palette: Palette, + t: Tokens, ) -> impl IntoElement { div() .flex() .items_center() .gap(px(space::SM)) - .child(div().flex_1().min_w_0().child(field(palette, reason))) + .child(div().flex_1().min_w_0().child(field(t, reason))) .child(button( "send_report", w().message_actions.send, Press::Primary, - palette.tokens, + t, entity_action(entity, |yumush, window, cx| yumush.send_report(window, cx)), )) } @@ -694,6 +668,7 @@ impl Yumush { ) { let pinned = self .chat + .session .messages .iter() .any(|message| message.id == message_id && message.pinned); @@ -729,10 +704,10 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) { - if self.chat.report.as_ref() == Some(&target) { - self.chat.report = None; + if self.chat.session.report.as_ref() == Some(&target) { + self.chat.session.report = None; } else { - self.chat.report = Some(target); + self.chat.session.report = Some(target); self.chat .report_reason .update(cx, |input, cx| input.focus(window, cx)); @@ -741,7 +716,7 @@ impl Yumush { } pub(super) fn send_report(&mut self, window: &mut Window, cx: &mut Context) { - let Some(target) = self.chat.report.clone() else { + let Some(target) = self.chat.session.report.clone() else { return; }; let reason = self.chat.report_reason.read(cx).text().to_string(); @@ -758,7 +733,7 @@ impl Yumush { match result { Ok(()) => { let _ = this.update_in(cx, |yumush, window, cx| { - yumush.chat.report = None; + yumush.chat.session.report = None; yumush .chat .report_reason @@ -775,7 +750,7 @@ impl Yumush { fn action( entity: &Entity, - palette: Palette, + t: Tokens, message_id: Id, name: &'static str, tip: &'static str, @@ -790,7 +765,7 @@ fn action( tip, Tone::Idle, Scale::Small, - palette.tokens, + t, move |window, cx| { entity.update(cx, |yumush, cx| run(yumush, message_id, window, cx)); }, diff --git a/crates/client/src/gui/parts.rs b/crates/client/src/gui/parts.rs index 001f74a..1e2cca5 100644 --- a/crates/client/src/gui/parts.rs +++ b/crates/client/src/gui/parts.rs @@ -261,15 +261,20 @@ pub fn button( ) -> Stateful
{ let label = label.into(); match kind { - Press::Plain => press(id, t, on_click) - .child(words(label, Text::Ui, Ink::Paper, t).font_weight(FontWeight::MEDIUM)), - Press::Danger => press(id, t, on_click) - .child(words(label, Text::Ui, Ink::Bad, t).font_weight(FontWeight::MEDIUM)), Press::Primary => pill(id, t, on_click).child( words(label, Text::Ui, Ink::Paper, t) .font_weight(FontWeight::SEMIBOLD) .text_color(t.ground()), ), + Press::Plain | Press::Danger => { + let ink = if kind == Press::Danger { + Ink::Bad + } else { + Ink::Paper + }; + press(id, t, on_click) + .child(words(label, Text::Ui, ink, t).font_weight(FontWeight::MEDIUM)) + } } } @@ -406,7 +411,7 @@ pub fn popover(t: Tokens) -> Div { .py(px(space::LG)) } -pub const QUICK_LABEL: f32 = size::ROW + space::XL; +const QUICK_LABEL: f32 = size::ROW + space::XL; pub fn quick(t: Tokens) -> Div { popover(t).gap(px(space::XS)) @@ -639,6 +644,8 @@ pub fn motion() -> gpui_kit::Animation { gpui_kit::Animation::new(Duration::from_millis(160)).with_easing(gpui_kit::ease_out_quint()) } +pub const DISABLED: f32 = 0.4; + const SLIDER_DOT: f32 = 10.; #[derive(gpui_kit::IntoElement)] diff --git a/crates/client/src/gui/poll.rs b/crates/client/src/gui/poll.rs index 81d161a..73e1269 100644 --- a/crates/client/src/gui/poll.rs +++ b/crates/client/src/gui/poll.rs @@ -10,19 +10,15 @@ use gpui_kit::{ }; use super::{ - Palette, Tooltip as _, Trigger, Yumush, avatar, + Tooltip as _, Trigger, Yumush, avatar, chat::Chat, - clickable, hoverable, - parts::{Scale, Tone, icon_button}, - style::{radius, size, space, text}, + clickable, hoverable, notify_error, + parts::{Scale, Tone, icon_button, surface}, + style::{Tokens, radius, size, space, text}, text, - widget::{panel, spawn_done}, + widget::spawn_done, }; -pub fn voter_count(poll: &Poll) -> usize { - poll.voters as usize -} - fn my_positions(poll: &Poll, user_id: Id) -> Vec { poll.options .iter() @@ -54,17 +50,12 @@ pub enum PollMode<'a> { Snapshot(Id), } -fn status_icon( - id: String, - icon: IconName, - tip: &'static str, - palette: Palette, -) -> impl IntoElement { +fn status_icon(id: String, icon: IconName, tip: &'static str, t: Tokens) -> impl IntoElement { div() .id(id) .tip(tip) .flex_shrink_0() - .text_color(palette.muted) + .text_color(t.dim()) .child(super::parts::small_icon(icon)) } @@ -77,7 +68,7 @@ fn voters_label(voters: usize) -> Div { .child(format!("{voters}")) } -fn voters_popover(key: &str, poll: &Poll, entity: &Entity, palette: Palette) -> AnyElement { +fn voters_popover(key: &str, poll: &Poll, entity: &Entity, t: Tokens) -> AnyElement { let options = poll.options.clone(); let list = format!("poll_voters_list_{key}"); let open = entity.clone(); @@ -86,8 +77,8 @@ fn voters_popover(key: &str, poll: &Poll, entity: &Entity, palette: Pale .appearance(false) .trigger(Trigger::new(hoverable( format!("poll_voters_trigger_{key}"), - voters_label(voter_count(poll)), - palette, + voters_label(poll.voters as usize), + t, ))) .content(move |_, _, cx| { let yumush = open.read(cx); @@ -106,7 +97,7 @@ fn voters_popover(key: &str, poll: &Poll, entity: &Entity, palette: Pale .items_center() .gap(px(space::SM)) .text_size(text(text::CAPTION)) - .text_color(palette.muted) + .text_color(t.dim()) .child(div().flex_1().min_w_0().child(super::glyph::line( option.text.clone().into(), super::text(super::style::text::UI), @@ -126,11 +117,11 @@ fn voters_popover(key: &str, poll: &Poll, entity: &Entity, palette: Pale .gap(px(space::SM)) .text_size(text(text::CAPTION)) .child(avatar( - palette, + t, user, px(size::AVATAR), text(text::CAPTION), - &chat.avatars, + &chat.session.avatars, )) .child( div() @@ -142,7 +133,7 @@ fn voters_popover(key: &str, poll: &Poll, entity: &Entity, palette: Pale }) })) }); - panel(palette) + surface(t) .w(px(size::SIDEBAR)) .id(list.clone()) .max_h(px(size::POPOVER)) @@ -176,45 +167,41 @@ pub fn poll_card( me: Option<&User>, chat: &Chat, entity: &Entity, - palette: Palette, + t: Tokens, ) -> impl IntoElement { - let voters = voter_count(poll); + let voters = poll.voters as usize; let closed = is_closed(poll); - let me_id = me.map(|me| me.id); - let (key, live) = match mode { - PollMode::Live(message) => (message.id.to_string(), Some(message)), - PollMode::Snapshot(id) => (format!("snapshot_{id}"), None), - }; - let mine = match me_id { - Some(id) if poll.public => my_positions(poll, id), - _ => live - .and_then(|message| chat.my_votes.get(&message.id)) - .cloned() - .unwrap_or_default(), - }; - let vote_id = live - .filter(|_| !closed && me_id.is_some()) - .map(|message| message.id); - let close_id = live - .filter(|message| { - !closed + let (key, mine, vote_id, close_id) = match mode { + PollMode::Live(message) => { + let mine = match me { + Some(me) if poll.public => my_positions(poll, me.id), + _ => chat + .session + .my_votes + .get(&message.id) + .cloned() + .unwrap_or_default(), + }; + let vote_id = (!closed && me.is_some()).then_some(message.id); + let close_id = (!closed && me.is_some_and(|me| { me.id == message.user_id || chat.rank_of(me) >= Some(Rank::Moderator) - }) - }) - .map(|message| message.id); + })) + .then_some(message.id); + (message.id.to_string(), mine, vote_id, close_id) + } + PollMode::Snapshot(id) => (format!("snapshot_{id}"), Vec::new(), None, None), + }; let rows = poll.options.iter().enumerate().map(|(position, option)| { let share = percent(option.votes as usize, voters); let picked = mine.contains(&(position as u32)); - let next = me_id - .map(|_| next_votes(&mine, position as u32, poll.multiple)) - .unwrap_or_default(); + let next = next_votes(&mine, position as u32, poll.multiple); let voters_here: &[Id] = if poll.public { &option.voter_ids } else { &[] }; let entity = entity.clone(); let id = format!("poll_option_{key}_{position}"); match vote_id { - Some(message_id) => clickable(id, palette, move |window, cx| { + Some(message_id) => clickable(id, t, move |window, cx| { let next = next.clone(); entity.update(cx, |yumush, cx| yumush.vote(message_id, next, window, cx)); }), @@ -228,13 +215,9 @@ pub fn poll_card( .gap(px(space::SM)) .rounded(px(radius::MD)) .border_1() - .border_color(if picked { - palette.accent - } else { - palette.field - }) + .border_color(if picked { t.paper() } else { t.raise() }) .overflow_hidden() - .bg(palette.field) + .bg(t.raise()) .child( div() .absolute() @@ -242,11 +225,7 @@ pub fn poll_card( .top_0() .h_full() .w(relative(share as f32 / 100.)) - .bg(if picked { - palette.tokens.press() - } else { - palette.hover - }), + .bg(if picked { t.press() } else { t.hov() }), ) .child( div() @@ -257,15 +236,11 @@ pub fn poll_card( .justify_center() .rounded_full() .border_1() - .border_color(if picked { - palette.accent - } else { - palette.muted - }) + .border_color(if picked { t.paper() } else { t.dim() }) .when(picked, |marker| { marker - .bg(palette.accent) - .text_color(palette.on_accent) + .bg(t.paper()) + .text_color(t.ground()) .child(super::parts::small_icon(IconName::Check)) }), ) @@ -285,14 +260,14 @@ pub fn poll_card( .filter_map(|(index, id)| { chat.author(*id).map(|user| { avatar( - palette, + t, user, px(size::AVATAR), text(text::CAPTION), - &chat.avatars, + &chat.session.avatars, ) .border_2() - .border_color(palette.panel) + .border_color(t.ground()) .when(index > 0, |el| el.ml(px(-space::SM))) }) }), @@ -301,7 +276,7 @@ pub fn poll_card( div() .ml(px(space::XS)) .text_size(text(text::CAPTION)) - .text_color(palette.muted) + .text_color(t.dim()) .child(format!("+{}", voters_here.len() - 3)) })) })) @@ -310,13 +285,13 @@ pub fn poll_card( .flex_shrink_0() .text_size(text(text::CAPTION)) .font_weight(FontWeight::SEMIBOLD) - .text_color(if picked { palette.text } else { palette.muted }) + .text_color(if picked { t.paper() } else { t.dim() }) .child(format!("{share}%")), ) }); let voters_view = if poll.public { - voters_popover(&key, poll, entity, palette) + voters_popover(&key, poll, entity, t) } else { voters_label(voters).into_any_element() }; @@ -335,7 +310,7 @@ pub fn poll_card( .items_center() .justify_between() .text_size(text(text::CAPTION)) - .text_color(palette.muted) + .text_color(t.dim()) .child(voters_view) .child( div() @@ -351,7 +326,7 @@ pub fn poll_card( w().poll.end_poll, Tone::Idle, Scale::Small, - palette.tokens, + t, move |window, cx| { close_entity .update(cx, |yumush, cx| yumush.close_poll(close_id, window, cx)); @@ -374,7 +349,7 @@ pub fn poll_card( .w(px(size::SHEET)) .max_w_full() .rounded(px(radius::LG)) - .bg(palette.panel) + .bg(t.ground()) .child( div() .flex() @@ -401,14 +376,14 @@ pub fn poll_card( format!("poll_public_{key}_{}", poll.public), visibility, visibility_tip, - palette, + t, )) .children(poll.multiple.then(|| { status_icon( format!("poll_multiple_{key}"), IconName::ListChecks, w().poll.multiple_choice, - palette, + t, ) })) .children(closed.then(|| { @@ -416,7 +391,7 @@ pub fn poll_card( format!("poll_closed_{key}"), IconName::Lock, w().poll.closed, - palette, + t, ) })), ), @@ -426,9 +401,9 @@ pub fn poll_card( } impl Yumush { - pub(super) fn poll_banner(&self, entity: &Entity, palette: Palette) -> Option
{ - let open: Vec<(&Message, &Poll)> = self - .chat + fn open_polls(&self) -> Vec<(&Message, &Poll)> { + self.chat + .session .pins .iter() .filter_map(|pin| { @@ -437,12 +412,16 @@ impl Yumush { .filter(|poll| !is_closed(poll)) .map(|poll| (pin, poll)) }) - .collect(); + .collect() + } + + pub(super) fn poll_banner(&self, entity: &Entity, t: Tokens) -> Option
{ + let open = self.open_polls(); let count = open.len(); - let page = self.chat.poll_page % count.max(1); + let page = self.chat.poll.page % count.max(1); let (message, poll) = *open.get(page)?; let me = self.user.as_ref(); - let expanded = self.chat.poll_expanded; + let expanded = self.chat.poll.expanded; let toggle = entity.clone(); let jump = entity.clone(); let message_id = message.id; @@ -455,17 +434,17 @@ impl Yumush { .px(px(space::LG)) .py(px(space::SM)) .border_b_1() - .border_color(palette.border) - .bg(palette.panel) + .border_color(t.thread()) + .bg(t.ground()) .child( div() .flex() .items_center() .gap(px(space::SM)) .child( - clickable("poll_banner_toggle", palette, move |_, cx| { + clickable("poll_banner_toggle", t, move |_, cx| { toggle.update(cx, |yumush, cx| { - yumush.chat.poll_expanded = !yumush.chat.poll_expanded; + yumush.chat.poll.expanded = !yumush.chat.poll.expanded; cx.notify(); }) }) @@ -478,7 +457,7 @@ impl Yumush { .child( div() .flex_shrink_0() - .text_color(palette.muted) + .text_color(t.dim()) .child(super::parts::small_icon(IconName::ChartBar)), ) .child(div().min_w_0().font_weight(FontWeight::SEMIBOLD).child( @@ -490,11 +469,11 @@ impl Yumush { .child( div() .flex_shrink_0() - .text_color(palette.muted) - .child(w().poll.votes(voter_count(poll))), + .text_color(t.dim()) + .child(w().poll.votes(poll.voters as usize)), ) .child( - div().flex_shrink_0().text_color(palette.muted).child( + div().flex_shrink_0().text_color(t.dim()).child( super::parts::small_icon(if expanded { IconName::ChevronUp } else { @@ -509,14 +488,14 @@ impl Yumush { .items_center() .gap(px(space::XXS)) .text_size(text(text::CAPTION)) - .text_color(palette.muted) + .text_color(t.dim()) .child(page_button( "poll_page_back", IconName::ChevronLeft, w().poll.previous, - count - 1, + -1, entity, - palette, + t, )) .child(format!("{}/{count}", page + 1)) .child(page_button( @@ -525,7 +504,7 @@ impl Yumush { w().poll.next, 1, entity, - palette, + t, )) })) .child(icon_button( @@ -534,7 +513,7 @@ impl Yumush { w().poll.jump_to_message, Tone::Idle, Scale::Small, - palette.tokens, + t, move |window, cx| { jump.update(cx, |yumush, cx| { yumush.go_to_message(message_id, window, cx) @@ -542,25 +521,21 @@ impl Yumush { }, )), ) - .children(expanded.then(|| { - poll_card( - poll, - PollMode::Live(message), - me, - &self.chat, - entity, - palette, - ) - })), + .children( + expanded.then(|| { + poll_card(poll, PollMode::Live(message), me, &self.chat, entity, t) + }), + ), ) } pub(super) fn request_poll_votes(&mut self, cx: &mut Context) { let anonymous: Vec = self .chat + .session .messages .iter() - .chain(&self.chat.pins) + .chain(&self.chat.session.pins) .filter(|message| message.poll.as_ref().is_some_and(|poll| !poll.public)) .map(|message| message.id) .collect(); @@ -570,19 +545,24 @@ impl Yumush { } pub(super) fn request_my_votes(&mut self, message_id: Id, cx: &mut Context) { - if self.chat.my_votes.contains_key(&message_id) { + if self.chat.session.my_votes.contains_key(&message_id) { return; } - self.chat.my_votes.insert(message_id, Vec::new()); + self.chat.session.my_votes.insert(message_id, Vec::new()); let network = self.network.clone(); cx.spawn(async move |this, cx| { - let Ok(positions) = network.call(MyVotes { message_id }).await else { - return; - }; + let positions = network.call(MyVotes { message_id }).await; let _ = this.update(cx, |yumush, cx| { - yumush.chat.my_votes.insert(message_id, positions); + match positions { + Ok(positions) => { + yumush.chat.session.my_votes.insert(message_id, positions); + } + Err(_) => { + yumush.chat.session.my_votes.remove(&message_id); + } + } cx.notify(); }); }) @@ -596,17 +576,36 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) { - self.chat.my_votes.insert(message_id, positions.clone()); + let previous = self + .chat + .session + .my_votes + .insert(message_id, positions.clone()); let network = self.network.clone(); - spawn_done(window, cx, async move { - network + cx.spawn_in(window, async move |this, cx| { + if let Err(error) = network .call(Vote { message_id, positions, }) .await - }); + { + let _ = this.update_in(cx, |yumush, _, cx| { + match previous { + Some(previous) => { + yumush.chat.session.my_votes.insert(message_id, previous); + } + None => { + yumush.chat.session.my_votes.remove(&message_id); + } + } + cx.notify(); + }); + notify_error(&this, cx, error); + } + }) + .detach(); } pub(super) fn close_poll( @@ -627,23 +626,17 @@ fn page_button( id: &'static str, icon: IconName, tip: &'static str, - step: usize, + step: isize, entity: &Entity, - palette: Palette, + t: Tokens, ) -> impl IntoElement { let entity = entity.clone(); - icon_button( - id, - icon, - tip, - Tone::Idle, - Scale::Small, - palette.tokens, - move |_, cx| { - entity.update(cx, |yumush, cx| { - yumush.chat.poll_page = yumush.chat.poll_page.wrapping_add(step); - cx.notify(); - }); - }, - ) + icon_button(id, icon, tip, Tone::Idle, Scale::Small, t, move |_, cx| { + entity.update(cx, |yumush, cx| { + let count = yumush.open_polls().len().max(1) as isize; + yumush.chat.poll.page = + (yumush.chat.poll.page as isize + step).rem_euclid(count) as usize; + cx.notify(); + }); + }) } diff --git a/crates/client/src/gui/profile.rs b/crates/client/src/gui/profile.rs index d01ed69..62d3319 100644 --- a/crates/client/src/gui/profile.rs +++ b/crates/client/src/gui/profile.rs @@ -3,8 +3,10 @@ use crate::gui::glyph::Fill as _; use crate::lang::{Label as _, w}; use common::model::Id; use gpui_kit::prelude::FluentBuilder as _; -use std::collections::VecDeque; -use std::{collections::HashMap, sync::Arc}; +use std::{ + collections::{HashMap, VecDeque}, + sync::Arc, +}; use common::{ call::{BanMember, DeleteUser, Kick, SetRank, UpdatePresence}, @@ -31,11 +33,11 @@ use super::parts::{ Ink, Scale, Text, Tone, Voice, band, icon_button, small_icon, stack, voice_line, words, }; use super::social::Relation; -use super::style::{radius, size, space, stroke, text}; +use super::style::{Tokens, radius, size, space, stroke, text}; use super::widget::spawn_done; use super::{ - Palette, Tooltip as _, Trigger, Yumush, avatar, clickable, entity_action, input_dialog, - millis_time, notify_error, palette, text, + Tooltip as _, Trigger, Yumush, avatar, clickable, entity_action, input_dialog, millis_time, + notify_error, text, }; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -91,8 +93,8 @@ pub(super) fn profile_popover( .appearance(false) .on_open_change(move |_, _, cx| { notify_entity.update(cx, |yumush, cx| { - yumush.chat.card_menu = CardMenu::Main; - yumush.chat.armed = None; + yumush.chat.session.card_menu = CardMenu::Main; + yumush.chat.session.armed = None; yumush.open_user_volume(volume_user_id, cx); cx.notify() }) @@ -101,19 +103,26 @@ pub(super) fn profile_popover( .content(move |_, _, cx| { let yumush = entity.read(cx); let card = Card { - viewer: yumush.user.clone(), + is_self: yumush + .user + .as_ref() + .is_some_and(|viewer| viewer.id == user.id), + deletable: yumush.user.as_ref().is_some_and(|viewer| { + permission::can_delete_user(viewer.role, false, user.role) + }), actor: yumush.actor_rank(), target: yumush.chat.rank_of(&user), relation: yumush.relation(user.id), - card_menu: yumush.chat.card_menu, + card_menu: yumush.chat.session.card_menu, presence: yumush.presence_of(user.id), - armed: yumush.chat.armed, - reporting: yumush.chat.report == Some(ReportTarget::User(user.id)), + armed: yumush.chat.session.armed.clone(), + reporting: yumush.chat.session.report == Some(ReportTarget::User(user.id)), reason: yumush.chat.report_reason.clone(), status: yumush.chat.status_input.clone(), volume: yumush .chat - .user_volume + .session + .volume_popover .as_ref() .filter(|volume| volume.user_id == user.id) .map(|volume| (volume.slider.clone(), yumush.user_volume(user.id))), @@ -124,12 +133,22 @@ pub(super) fn profile_popover( community.name.clone() } }), - wave: yumush.chat.waves.voice(user.id).cloned(), - speaking: yumush.chat.waves.speaking.contains(&user.id), + wave: yumush + .chat + .session + .waves + .voice(user.id) + .map(|bars| bars.iter().copied().collect()), + speaking: yumush.chat.session.waves.speaking.contains(&user.id), user: user.clone(), }; - card.render(&entity, cx.entity(), palette(cx), &yumush.chat.avatars) + card.render( + &entity, + cx.entity(), + Tokens::of(cx), + &yumush.chat.session.avatars, + ) }) } @@ -138,7 +157,8 @@ struct Card { call: Option, wave: Option>, speaking: bool, - viewer: Option, + is_self: bool, + deletable: bool, actor: Option, target: Option, relation: Relation, @@ -156,7 +176,7 @@ impl Card { &self, entity: &Entity, popover: &Entity, - palette: Palette, + t: Tokens, ) -> Vec { let user_id = self.user.id; let message_id = user_id; @@ -165,8 +185,8 @@ impl Card { "profile_message", w().profile.message, small_icon(IconName::MessageSquare), - palette.text, - palette, + t.paper(), + t, yumush_action(entity, popover, move |yumush, window, cx| { yumush.open_direct(message_id, window, cx) }), @@ -176,8 +196,8 @@ impl Card { "profile_call", w().profile.call, small_icon(IconName::Phone), - palette.text, - palette, + t.paper(), + t, yumush_action(entity, popover, move |yumush, window, cx| { yumush.call_direct(message_id, window, cx) }), @@ -191,8 +211,8 @@ impl Card { "profile_report", w().profile.report, small_icon(IconName::TriangleAlert), - palette.danger, - palette, + t.bad(), + t, entity_action(entity, move |yumush, window, cx| { yumush.start_report(ReportTarget::User(report_user_id), window, cx) }), @@ -207,8 +227,8 @@ impl Card { "profile_friend", label, small_icon(icon), - palette.text, - palette, + t.paper(), + t, yumush_action(entity, popover, move |yumush, window, cx| { yumush.friend_action(relation, user_id, window, cx) }), @@ -224,25 +244,21 @@ impl Card { self, entity: &Entity, popover: Entity, - palette: Palette, + t: Tokens, avatars: &HashMap>, ) -> Div { - let is_self = self - .viewer - .as_ref() - .is_some_and(|viewer| viewer.id == self.user.id); - let t = palette.tokens; + let is_self = self.is_self; let actions = if is_self { div() .flex() .flex_col() .gap(px(space::XS)) - .children(main_self_rows(self.armed, entity, &popover, palette)) + .children(main_self_rows(self.armed, entity, &popover, t)) .into_any_element() } else { - let mut rows = self.social_rows(entity, &popover, palette); - rows.extend(self.moderation_rows(entity, &popover, palette)); - if self.card_menu == CardMenu::More || rows.len() < 3 { + let mut rows = self.social_rows(entity, &popover, t); + rows.extend(self.moderation_rows(entity, &popover, t)); + if self.card_menu == CardMenu::More { div() .flex() .flex_col() @@ -275,15 +291,15 @@ impl Card { let place = match self.target { Some(Rank::Builder) => { let badge = band(space::XXS) - .child(small_icon(IconName::Shield).text_color(palette.accent)) + .child(small_icon(IconName::Shield).text_color(t.paper())) .child( words(Rank::Builder.label(), Text::Caption, Ink::Faint, t) - .text_color(palette.accent), + .text_color(t.paper()), ); if is_self { clickable( "profile_builder", - palette, + t, yumush_action(entity, &popover, |yumush, window, cx| { yumush.show_view(View::Builder, window, cx) }), @@ -341,7 +357,7 @@ impl Card { entity, "profile_picture", avatar( - palette, + t, &self.user, px(size::AVATAR_LG), text(text::BODY), @@ -366,14 +382,14 @@ impl Card { .absolute() .right(px(-space::XXS)) .bottom(px(-space::XXS)) - .child(presence_menu(self.presence, entity, palette)), + .child(presence_menu(self.presence, entity, t)), ) } else { super::presence_avatar( picture, self.presence, px(size::AVATAR_LG), - palette, + t, ) } }), @@ -396,7 +412,7 @@ impl Card { .truncate(), ) .when(is_self, |name| { - name.child(account_menu(entity, &popover, palette)) + name.child(account_menu(entity, &popover, t)) }), ) .map(|names| { @@ -422,7 +438,7 @@ impl Card { .border_color(t.paper()) .child( super::widget::bare_input( - palette, + t, gpui_kit::component::input::Input::new( &self.status, ) @@ -435,7 +451,7 @@ impl Card { .child(super::glyph::picker_button( "status_emoji", entity, - palette, + t, super::glyph::insert_into(status), )), ); @@ -452,7 +468,7 @@ impl Card { .min_w_0() .truncate() })) - .child(edit_status(entity, &self.user.status, palette)), + .child(edit_status(entity, &self.user.status, t)), ) }), ), @@ -483,10 +499,7 @@ impl Card { .text_right(), ) })) - .children( - self.reporting - .then(|| report_bar(&self.reason, entity, palette)), - ) + .children(self.reporting.then(|| report_bar(&self.reason, entity, t))) .child(actions) } @@ -494,7 +507,7 @@ impl Card { &self, entity: &Entity, popover: &Entity, - palette: Palette, + t: Tokens, ) -> Vec { let actor = self.actor; let target = self.target; @@ -509,8 +522,8 @@ impl Card { label.clone(), label, small_icon(IconName::Shield), - palette.text, - palette, + t.paper(), + t, yumush_action(entity, popover, move |yumush, window, cx| { yumush.set_member_rank(user_id, rank, window, cx) }), @@ -521,43 +534,29 @@ impl Card { } if permission::can_moderate(actor, target) { - let kick_id = user_id; - let ban_id = user_id; - rows.push( - menu_row( - "kick", - w().profile.kick, - small_icon(IconName::Close), - palette.danger, - palette, - yumush_action(entity, popover, move |yumush, window, cx| { - yumush.open_removal(kick_id, Removal::Kick, window, cx) - }), - ) - .into_any_element(), - ); - rows.push( - menu_row( - "ban", - w().profile.ban, - small_icon(IconName::Ban), - palette.danger, - palette, - yumush_action(entity, popover, move |yumush, window, cx| { - yumush.open_removal(ban_id, Removal::Ban, window, cx) - }), - ) - .into_any_element(), - ); + for (id, removal, icon) in [ + ("kick", Removal::Kick, IconName::Close), + ("ban", Removal::Ban, IconName::Ban), + ] { + rows.push( + menu_row( + id, + removal.title(), + small_icon(icon), + t.bad(), + t, + yumush_action(entity, popover, move |yumush, window, cx| { + yumush.open_removal(user_id, removal, window, cx) + }), + ) + .into_any_element(), + ); + } } - let deletable = self - .viewer - .as_ref() - .is_some_and(|viewer| permission::can_delete_user(viewer.role, false, self.user.role)); - if deletable { + if self.deletable { let armed = Armed::DeleteUser(user_id); - let label = if self.armed == Some(armed) { + let label = if self.armed == Some(armed.clone()) { w().common.confirm } else { w().profile.delete_user @@ -568,8 +567,8 @@ impl Card { "delete_user", label, small_icon(IconName::Trash), - palette.danger, - palette, + t.bad(), + t, armed_action(armed, entity, popover, move |yumush, window, cx| { yumush.delete_member_account(user_id, window, cx) }), @@ -586,22 +585,20 @@ fn main_self_rows( armed: Option, entity: &Entity, popover: &Entity, - palette: Palette, + t: Tokens, ) -> Vec { - let mut rows = vec![ + vec![ menu_row( "profile_settings", w().profile.settings, small_icon(IconName::Settings), - palette.text, - palette, + t.paper(), + t, yumush_action(entity, popover, |yumush, window, cx| { yumush.show_view(View::Settings, window, cx) }), ) .into_any_element(), - ]; - rows.push( menu_row( "profile_logout", if armed == Some(Armed::LogOut) { @@ -610,49 +607,41 @@ fn main_self_rows( w().profile.log_out }, small_icon(IconName::LogOut), - palette.danger, - palette, + t.bad(), + t, armed_action(Armed::LogOut, entity, popover, |yumush, window, cx| { yumush.logout(window, cx) }), ) .into_any_element(), - ); - rows + ] } -fn account_menu(entity: &Entity, card: &Entity, palette: Palette) -> Popover { +fn account_menu(entity: &Entity, card: &Entity, t: Tokens) -> Popover { let entity = entity.clone(); let card = card.clone(); Popover::new("account_menu") .anchor(Anchor::TopLeft) .appearance(false) .trigger(Trigger::new( - clickable("profile_accounts", palette, |_, _| {}) + clickable("profile_accounts", t, |_, _| {}) .tip(w().profile.accounts) .rounded(px(radius::SM)) .flex_shrink_0() - .child(small_icon(IconName::ChevronDown).text_color(palette.muted)), + .child(small_icon(IconName::ChevronDown).text_color(t.dim())), )) .content(move |_, _, cx| { let yumush = entity.read(cx); - super::parts::popover(palette.tokens) + super::parts::popover(t) .p(px(space::XS)) .w(px(size::SIDEBAR)) - .child(account_list( - yumush, - &entity, - true, - Some(card.clone()), - palette, - cx, - )) + .child(account_list(yumush, &entity, Some(card.clone()), t, cx)) .child(menu_row( "profile_add_account", w().profile.add_account, small_icon(IconName::UserPlus), - palette.text, - palette, + t.paper(), + t, yumush_action(&entity, &card, |yumush, window, cx| { yumush.add_account(window, cx) }), @@ -660,13 +649,13 @@ fn account_menu(entity: &Entity, card: &Entity, palette: P }) } -fn edit_status(entity: &Entity, status: &str, palette: Palette) -> impl IntoElement { +fn edit_status(entity: &Entity, status: &str, t: Tokens) -> impl IntoElement { let status = status.to_string(); clickable( "edit_status", - palette, + t, entity_action(entity, move |yumush, window, cx| { - yumush.chat.card_menu = CardMenu::Status; + yumush.chat.session.card_menu = CardMenu::Status; yumush.chat.status_input.update(cx, |input, cx| { input.fill(status.clone(), window, cx); input.focus(window, cx); @@ -678,7 +667,7 @@ fn edit_status(entity: &Entity, status: &str, palette: Palette) -> impl .flex_none() .p(px(space::XXS)) .rounded(px(radius::SM)) - .child(small_icon(IconName::Pencil).text_color(palette.tokens.faint())) + .child(small_icon(IconName::Pencil).text_color(t.faint())) } fn card_menu_action( @@ -686,7 +675,7 @@ fn card_menu_action( menu: CardMenu, ) -> impl Fn(&mut Window, &mut App) + 'static { entity_action(entity, move |yumush, _, cx| { - yumush.chat.card_menu = menu; + yumush.chat.session.card_menu = menu; cx.notify(); }) } @@ -715,35 +704,35 @@ pub(super) fn armed_action( let popover = popover.clone(); move |window, cx| { - if entity.update(cx, |yumush, cx| yumush.arm(armed, cx)) { + if entity.update(cx, |yumush, cx| yumush.arm(armed.clone(), cx)) { popover.update(cx, |state, cx| state.dismiss(window, cx)); entity.update(cx, |yumush, cx| run(yumush, window, cx)); } } } -fn presence_dot(presence: Presence, palette: Palette) -> Div { +fn presence_dot(presence: Presence, t: Tokens) -> Div { div() .size(px(space::LG)) .rounded_full() .border_2() - .border_color(palette.tokens.raise()) - .bg(super::presence_color(presence, palette)) + .border_color(t.raise()) + .bg(super::presence_color(presence, t)) } -fn presence_menu(current: Presence, entity: &Entity, palette: Palette) -> Popover { +fn presence_menu(current: Presence, entity: &Entity, t: Tokens) -> Popover { let entity = entity.clone(); Popover::new("presence_menu") .anchor(Anchor::TopLeft) .appearance(false) .trigger(Trigger::new( - clickable("presence_dot", palette, |_, _| {}) + clickable("presence_dot", t, |_, _| {}) .rounded_full() - .child(presence_dot(current, palette)), + .child(presence_dot(current, t)), )) .content(move |_, _, cx| { let popover = cx.entity(); - super::parts::popover(palette.tokens) + super::parts::popover(t) .p(px(space::XS)) .children(Presence::ALL.into_iter().map(|presence| { let popover = popover.clone(); @@ -759,14 +748,14 @@ fn presence_menu(current: Presence, entity: &Entity, palette: Palette) - div() .size(px(space::SM)) .rounded_full() - .bg(super::presence_color(presence, palette)), + .bg(super::presence_color(presence, t)), ), if presence == current { - palette.text + t.paper() } else { - palette.muted + t.dim() }, - palette, + t, { let entity = entity.clone(); move |window, cx| { @@ -786,10 +775,10 @@ pub(super) fn menu_row( label: impl Into, leading: impl IntoElement, color: Hsla, - palette: Palette, + t: Tokens, on_click: impl Fn(&mut Window, &mut App) + 'static, ) -> Stateful
{ - clickable(id, palette, on_click) + clickable(id, t, on_click) .h(px(size::CONTROL)) .px(px(space::SM)) .flex() @@ -809,7 +798,7 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) { - let Some(community_id) = self.chat.selected_community_id else { + let Some(community_id) = self.chat.session.selected_community_id else { return; }; input_dialog( @@ -880,7 +869,7 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) { - let Some(community_id) = self.chat.selected_community_id else { + let Some(community_id) = self.chat.session.selected_community_id else { return; }; let network = self.network.clone(); @@ -902,17 +891,28 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) { - if let Some(me) = &self.user { - self.chat.presences.insert(me.id, presence); + let me = self.user.as_ref().map(|me| me.id); + let before = me.map(|me| self.presence_of(me)); + if let Some(me) = me { + self.chat.session.presences.insert(me, presence); } - self.chat.card_menu = CardMenu::Main; + self.chat.session.card_menu = CardMenu::Main; cx.notify(); let network = self.network.clone(); - spawn_done(window, cx, async move { - network.call(UpdatePresence { presence }).await - }); + cx.spawn_in(window, async move |this, cx| { + if let Err(error) = network.call(UpdatePresence { presence }).await { + let _ = this.update(cx, |yumush, cx| { + if let (Some(me), Some(before)) = (me, before) { + yumush.chat.session.presences.insert(me, before); + } + cx.notify(); + }); + notify_error(&this, cx, error); + } + }) + .detach(); } pub(super) fn delete_member_account( diff --git a/crates/client/src/gui/settings_page.rs b/crates/client/src/gui/settings_page.rs index 9d5cfac..ae659b6 100644 --- a/crates/client/src/gui/settings_page.rs +++ b/crates/client/src/gui/settings_page.rs @@ -15,7 +15,7 @@ use gpui_kit::{ }; use super::{ - Palette, Tooltip as _, Yumush, avatar, + Tooltip as _, Yumush, avatar, chat::Armed, chat::View, clickable, notify_error, parts, @@ -24,7 +24,7 @@ use super::{ widget::field, }; use crate::{ - gui::style::{self, Theme, radius, size, space, stroke, text}, + gui::style::{self, Theme, Tokens, radius, size, space, stroke, text}, settings::{self, FontSize, Launch, ShareAudio, ShareCodec}, share::encode::capabilities, storage::Store, @@ -78,10 +78,10 @@ impl SettingsSection { } } -pub(super) fn setting_rows() -> [(SettingsSection, &'static str); 30] { +pub(super) fn setting_rows() -> Vec<(SettingsSection, &'static str)> { let s = &w().settings_page; let v = &w().voice_settings; - [ + vec![ (SettingsSection::Profile, s.name), (SettingsSection::Profile, s.status), (SettingsSection::Profile, s.presence), @@ -92,8 +92,8 @@ pub(super) fn setting_rows() -> [(SettingsSection, &'static str); 30] { (SettingsSection::Voice, v.input_volume), (SettingsSection::Voice, v.output_volume), (SettingsSection::Voice, v.mode), - (SettingsSection::Voice, v.hear_yourself), - (SettingsSection::Voice, v.play_sound), + (SettingsSection::Voice, v.profile), + (SettingsSection::Voice, v.test), (SettingsSection::Voice, v.sensitivity), (SettingsSection::Voice, v.key), (SettingsSection::CameraShare, s.camera), @@ -119,7 +119,7 @@ impl Yumush { pub(super) fn settings_page( &self, entity: &Entity, - palette: Palette, + t: Tokens, cx: &App, ) -> impl IntoElement { let mut sections = Vec::new(); @@ -136,11 +136,11 @@ impl Yumush { Picture { id: "avatar_picker", image: avatar( - palette, + t, user, px(size::AVATAR_LG), text(text::TITLE), - &self.chat.avatars, + &self.chat.session.avatars, ), title: user.username.clone(), subtitle: user.status.clone(), @@ -149,13 +149,13 @@ impl Yumush { remove: Yumush::remove_avatar, }, entity, - palette, + t, )) .child(titled( w().settings_page.identity, - palette, + t, rows_column( - palette, + t, vec![ text_row( Editable { @@ -167,7 +167,7 @@ impl Yumush { emoji: None, }, entity, - palette, + t, cx, ), text_row( @@ -180,7 +180,7 @@ impl Yumush { emoji: Some("status_settings_emoji"), }, entity, - palette, + t, cx, ), row( @@ -189,7 +189,7 @@ impl Yumush { "presence", Presence::ALL.map(|presence| (presence, presence.label())), self.presence_of(user.id), - palette.tokens, + t, move |presence, window, cx| { presence_entity.update(cx, |yumush, cx| { yumush.set_presence(presence, window, cx) @@ -206,13 +206,13 @@ impl Yumush { sections.push(section( SettingsSection::Voice.id(), SettingsSection::Voice.label(), - palette, - self.voice_rows(entity, palette, cx), + t, + self.voice_rows(entity, t, cx), )); sections.push(Section::new( SettingsSection::CameraShare.id(), SettingsSection::CameraShare.label(), - camera_share(self, entity, palette), + camera_share(self, entity, t), )); let mut appearance = vec![ row( @@ -221,7 +221,7 @@ impl Yumush { Theme::ALL.map(|choice| (choice, choice.label())), self.settings.theme, entity, - palette, + t, Yumush::set_theme, ), ), @@ -231,7 +231,7 @@ impl Yumush { FontSize::ALL.map(|size| (size, size.label())), self.settings.font_size, entity, - palette, + t, Yumush::set_font_size, ), ), @@ -241,21 +241,16 @@ impl Yumush { Lang::ALL.map(|lang| (lang, lang.words().common.language)), self.settings.language, entity, - palette, + t, Yumush::set_language, ), ), row( w().settings_page.close_to_tray, - super::parts::toggle( - "close_to_tray_switch", - self.settings.close_to_tray, - palette.tokens, - { - let entity = entity.clone(); - move |_, cx| entity.update(cx, |yumush, cx| yumush.toggle_close_to_tray(cx)) - }, - ), + super::parts::toggle("close_to_tray_switch", self.settings.close_to_tray, t, { + let entity = entity.clone(); + move |_, cx| entity.update(cx, |yumush, cx| yumush.toggle_close_to_tray(cx)) + }), ), row( w().settings_page.launch, @@ -263,56 +258,52 @@ impl Yumush { Launch::options().map(|launch| (launch, launch.label())), self.settings.launch, entity, - palette, + t, Yumush::set_launch, ), ), row( w().settings_page.clock_seconds, - super::parts::toggle( - "clock_seconds_switch", - self.settings.clock_seconds, - palette.tokens, - { - let entity = entity.clone(); - move |_, cx| entity.update(cx, |yumush, cx| yumush.toggle_clock_seconds(cx)) - }, - ), + super::parts::toggle("clock_seconds_switch", self.settings.clock_seconds, t, { + let entity = entity.clone(); + move |_, cx| entity.update(cx, |yumush, cx| yumush.toggle_clock_seconds(cx)) + }), ), ]; if let Some(user) = self.user.as_ref() { appearance.push(row( w().settings_page.your_hue, - hue_picker(Some(style::hue_of(user.id)), entity, palette), + hue_picker(style::hue_of(user.id), entity, t), )); } sections.push(section( SettingsSection::Appearance.id(), SettingsSection::Appearance.label(), - palette, + t, appearance, )); sections.push(section( SettingsSection::Storage.id(), SettingsSection::Storage.label(), - palette, + t, self.chat + .session .storage .iter() - .map(|&(store, bytes)| storage_row(store, bytes, entity, palette)) + .map(|&(store, bytes)| storage_row(store, bytes, entity, t)) .collect(), )); sections.push(section( SettingsSection::About.id(), SettingsSection::About.label(), - palette, + t, [ (w().settings_page.version, crate::VERSION), (w().settings_page.commit, crate::COMMIT), (w().settings_page.target, crate::TARGET), ] .into_iter() - .map(|(label, value)| row(label, div().text_color(palette.muted).child(value))) + .map(|(label, value)| row(label, div().text_color(t.dim()).child(value))) .collect(), )); if self.user.is_some() { @@ -324,7 +315,7 @@ impl Yumush { w().settings_page.delete_account, self.armed(Armed::DeleteAccount), entity, - palette, + t, Yumush::delete_account, ) .into_any_element(), @@ -335,10 +326,10 @@ impl Yumush { page( "settings_scroll", entity, - palette, + t, w().settings_page.title, sections, - self.chat.section, + self.chat.session.section, ) } @@ -373,7 +364,7 @@ impl Yumush { pub(super) fn save_status(&mut self, window: &mut Window, cx: &mut Context) { let status = self.chat.status_input.read(cx).text().to_string(); let network = self.network.clone(); - self.chat.card_menu = super::chat::CardMenu::Main; + self.chat.session.card_menu = super::chat::CardMenu::Main; cx.notify(); cx.spawn_in(window, async move |this, cx| { @@ -423,6 +414,7 @@ impl Yumush { match network.call(DeleteUser { user_id }).await { Ok(()) => { let _ = this.update_in(cx, |yumush, window, cx| { + yumush.accounts.forget(user_id); yumush.end_session(window, cx); }); if let Err(error) = network.detach().await { @@ -477,7 +469,7 @@ impl Yumush { .spawn(async { Store::ALL.map(|store| (store, store.size())).to_vec() }) .await; let _ = this.update(cx, |yumush, cx| { - yumush.chat.storage = storage; + yumush.chat.session.storage = storage; cx.notify(); }); }) @@ -510,7 +502,7 @@ fn apply_user(this: &WeakEntity, cx: &mut AsyncWindowContext, result: Re } } -fn storage_row(store: Store, bytes: u64, entity: &Entity, palette: Palette) -> Div { +fn storage_row(store: Store, bytes: u64, entity: &Entity, t: Tokens) -> Div { let w = &w().settings_page; let (label, id) = match store { Store::Media => (w.media, "clear_media"), @@ -523,10 +515,10 @@ fn storage_row(store: Store, bytes: u64, entity: &Entity, palette: Palet .flex() .items_center() .gap(px(space::SM)) - .child(div().text_color(palette.muted).child(super::storage(bytes))) + .child(div().text_color(t.dim()).child(super::storage(bytes))) .when(store.clearable() && bytes > 0, |this| { this.child( - small_button(id, palette, palette.danger, move |_, cx| { + small_button(id, t, t.bad(), move |_, cx| { entity.update(cx, |yumush, cx| yumush.clear_storage(store, cx)); }) .child(w.clear), @@ -535,8 +527,7 @@ fn storage_row(store: Store, bytes: u64, entity: &Entity, palette: Palet ) } -fn hue_picker(current: Option, entity: &Entity, palette: Palette) -> Div { - let t = palette.tokens; +fn hue_picker(current: Hue, entity: &Entity, t: Tokens) -> Div { div() .flex() .items_center() @@ -551,7 +542,7 @@ fn hue_picker(current: Option, entity: &Entity, palette: Palette) - .justify_center() .rounded(px(radius::FULL)) .border(px(stroke::LINE)) - .border_color(if current == Some(hue) { + .border_color(if current == hue { t.paper() } else { transparent_black() @@ -569,25 +560,25 @@ fn hue_picker(current: Option, entity: &Entity, palette: Palette) - })) } -fn camera_share(yumush: &Yumush, entity: &Entity, palette: Palette) -> AnyElement { +fn camera_share(yumush: &Yumush, entity: &Entity, t: Tokens) -> AnyElement { div() .flex() .flex_col() .gap(px(space::XL)) .child(titled( w().settings_page.camera, - palette, - rows_column(palette, camera_rows(yumush, entity, palette)), + t, + rows_column(t, camera_rows(yumush, entity, t)), )) .child(titled( w().settings_page.screen_share, - palette, - rows_column(palette, screen_rows(yumush, entity, palette)), + t, + rows_column(t, screen_rows(yumush, entity, t)), )) .into_any_element() } -fn camera_rows(yumush: &Yumush, entity: &Entity, palette: Palette) -> Vec
{ +fn camera_rows(yumush: &Yumush, entity: &Entity, t: Tokens) -> Vec
{ let modes = share_modes(yumush, Kind::Camera); let max_height = capabilities().max_height; let top = share::clamp(yumush.settings.share.top(Kind::Camera), &modes, max_height); @@ -601,7 +592,7 @@ fn camera_rows(yumush: &Yumush, entity: &Entity, palette: Palette) -> Ve .into_iter() .filter(|(resolution, _)| resolutions.contains(resolution)), top.resolution, - palette.tokens, + t, share_pick(entity, Kind::Camera, Yumush::set_share_resolution), ), ), @@ -611,14 +602,14 @@ fn camera_rows(yumush: &Yumush, entity: &Entity, palette: Palette) -> Ve "camera_fps", FPS.into_iter().filter(|(value, _)| fps.contains(value)), top.fps, - palette.tokens, + t, share_pick(entity, Kind::Camera, Yumush::set_share_fps), ), ), ] } -fn screen_rows(yumush: &Yumush, entity: &Entity, palette: Palette) -> Vec
{ +fn screen_rows(yumush: &Yumush, entity: &Entity, t: Tokens) -> Vec
{ let settings = &yumush.settings.share; let modes = share_modes(yumush, Kind::Screen); let max_height = capabilities().max_height; @@ -635,7 +626,7 @@ fn screen_rows(yumush: &Yumush, entity: &Entity, palette: Palette) -> Ve .into_iter() .filter(|(resolution, _)| resolutions.contains(resolution)), top.resolution, - palette.tokens, + t, share_pick(entity, Kind::Screen, Yumush::set_share_resolution), ), ), @@ -645,7 +636,7 @@ fn screen_rows(yumush: &Yumush, entity: &Entity, palette: Palette) -> Ve "screen_fps", FPS.into_iter().filter(|(value, _)| fps.contains(value)), top.fps, - palette.tokens, + t, share_pick(entity, Kind::Screen, Yumush::set_share_fps), ), ), @@ -658,27 +649,28 @@ fn screen_rows(yumush: &Yumush, entity: &Entity, palette: Palette) -> Ve ShareCodec::Only(codec) => capabilities().encode.contains(codec), }), settings.codec, - palette.tokens, - share_pick(entity, Kind::Screen, Yumush::set_share_codec), + t, + share_pick( + entity, + Kind::Screen, + |yumush: &mut Yumush, _: Kind, codec: ShareCodec, cx: &mut Context| { + yumush.set_share_codec(codec, cx) + }, + ), ), ), row( w().settings_page.share_audio, - parts::toggle( - "share_audio_switch", - audio_on, - palette.tokens, - move |_, cx| { - audio_entity.update(cx, |yumush, cx| { - let mode = if audio_on { - AudioMode::Off - } else { - AudioMode::Everything - }; - yumush.set_share_audio_mode(mode, cx) - }) - }, - ), + parts::toggle("share_audio_switch", audio_on, t, move |_, cx| { + audio_entity.update(cx, |yumush, cx| { + let mode = if audio_on { + AudioMode::Off + } else { + AudioMode::Everything + }; + yumush.set_share_audio_mode(mode, cx) + }) + }), ), ] } @@ -686,16 +678,10 @@ fn screen_rows(yumush: &Yumush, entity: &Entity, palette: Palette) -> Ve fn share_pick( entity: &Entity, kind: Kind, - set: fn(&mut Yumush, T, &mut Context), + set: fn(&mut Yumush, Kind, T, &mut Context), ) -> impl Fn(T, &mut Window, &mut App) + Clone + 'static { let entity = entity.clone(); - move |value, _, cx| { - entity.update(cx, |yumush, cx| { - let tab = std::mem::replace(&mut yumush.share_tab, kind); - set(yumush, value, cx); - yumush.share_tab = tab; - }) - } + move |value, _, cx| entity.update(cx, |yumush, cx| set(yumush, kind, value, cx)) } pub(super) fn picked_avatar( @@ -738,7 +724,7 @@ impl Section { pub(super) fn page( id: &'static str, entity: &Entity, - palette: Palette, + t: Tokens, title: impl IntoElement, sections: Vec
, selected: Option<&'static str>, @@ -757,11 +743,11 @@ pub(super) fn page( gpui_kit::ElementId::Name(format!("{id}_index_{key}").into()), section.title, position == selected, - palette.tokens, + t, move |_, cx| { entity.update(cx, |yumush, cx| { - yumush.chat.section = Some(key); - yumush.chat.armed = None; + yumush.chat.session.section = Some(key); + yumush.chat.session.armed = None; cx.notify(); }) }, @@ -773,21 +759,21 @@ pub(super) fn page( title: name, body, .. }) = sections.into_iter().nth(selected) else { - return frame(id, entity, palette, title, index, Vec::new(), Vec::new()); + return frame(id, entity, t, title, index, Vec::new(), Vec::new()); }; frame( id, entity, - palette, + t, title, index, Vec::new(), - vec![heading(name, Vec::new(), palette).into_any_element(), body], + vec![heading(name, Vec::new(), t).into_any_element(), body], ) } -pub(super) fn heading(title: &str, actions: Vec, palette: Palette) -> Div { +pub(super) fn heading(title: &str, actions: Vec, t: Tokens) -> Div { div() .h(px(size::CONTROL)) .flex() @@ -800,7 +786,7 @@ pub(super) fn heading(title: &str, actions: Vec, palette: Palette) - .truncate() .text_size(text(text::TITLE)) .font_weight(FontWeight::SEMIBOLD) - .text_color(palette.tokens.paper()) + .text_color(t.paper()) .child(title.to_string()), ) .children(actions) @@ -809,7 +795,7 @@ pub(super) fn heading(title: &str, actions: Vec, palette: Palette) - pub(super) fn frame( id: &'static str, entity: &Entity, - palette: Palette, + t: Tokens, title: impl IntoElement, index: Vec, footer: Vec, @@ -834,7 +820,7 @@ pub(super) fn frame( .flex() .flex_col() .child( - clickable("page_back", palette, move |window, cx| { + clickable("page_back", t, move |window, cx| { back.update(cx, |yumush, cx| yumush.show_view(View::Chat, window, cx)); }) .tip(w().settings_page.back_esc) @@ -848,7 +834,7 @@ pub(super) fn frame( .gap(px(space::SM)) .min_w_0() .text_size(text(text::UI)) - .text_color(palette.muted) + .text_color(t.dim()) .child( super::parts::small_icon(gpui_kit::assets::IconName::ArrowLeft) .flex_shrink_0(), @@ -881,13 +867,8 @@ pub(super) fn frame( ) } -pub(super) fn section( - id: &'static str, - title: &'static str, - palette: Palette, - rows: Vec
, -) -> Section { - Section::new(id, title, rows_column(palette, rows).into_any_element()) +pub(super) fn section(id: &'static str, title: &'static str, t: Tokens, rows: Vec
) -> Section { + Section::new(id, title, rows_column(t, rows).into_any_element()) } pub(super) fn danger(id: &'static str, actions: Vec) -> Section { @@ -904,15 +885,15 @@ pub(super) fn danger(id: &'static str, actions: Vec) -> Section { ) } -fn titled(title: &'static str, palette: Palette, rows: impl IntoElement) -> Div { +fn titled(title: &'static str, t: Tokens, rows: impl IntoElement) -> Div { div() .flex() .flex_col() - .child(parts::section(title, palette.tokens)) + .child(parts::section(title, t)) .child(rows) } -fn rows_column(_palette: Palette, rows: Vec
) -> AnyElement { +fn rows_column(_t: Tokens, rows: Vec
) -> AnyElement { div().flex().flex_col().children(rows).into_any_element() } @@ -925,18 +906,13 @@ pub(super) struct Editable<'a> { pub emoji: Option<&'static str>, } -pub(super) fn text_row( - editable: Editable, - entity: &Entity, - palette: Palette, - cx: &App, -) -> Div { +pub(super) fn text_row(editable: Editable, entity: &Entity, t: Tokens, cx: &App) -> Div { let dirty = editable.input.read(cx).text() != editable.current; let picker = editable.emoji.map(|id| { super::glyph::picker_button( id, entity, - palette, + t, super::glyph::insert_into(editable.input.clone()), ) }); @@ -958,18 +934,18 @@ pub(super) fn text_row( .flex() .items_center() .gap(px(space::SM)) - .child(field(palette, editable.input).flex_1()) + .child(field(t, editable.input).flex_1()) .children(picker) .when(dirty, |this| { this.child( - clickable(editable.id, palette, move |window, cx| { + clickable(editable.id, t, move |window, cx| { entity.update(cx, |yumush, cx| save(yumush, window, cx)); }) .tip(w().settings_page.save) .px(px(space::XS)) .rounded(px(radius::SM)) .text_size(text(text::CAPTION)) - .text_color(palette.tokens.paper()) + .text_color(t.paper()) .child("↵"), ) }), @@ -986,7 +962,7 @@ pub(super) struct Picture { pub remove: fn(&mut Yumush, &mut Window, &mut Context), } -pub(super) fn picture_card(picture: Picture, entity: &Entity, palette: Palette) -> Div { +pub(super) fn picture_card(picture: Picture, entity: &Entity, t: Tokens) -> Div { let Picture { id, image, @@ -1031,7 +1007,7 @@ pub(super) fn picture_card(picture: Picture, entity: &Entity, palette: P this.child( div() .text_size(text(text::CAPTION)) - .text_color(palette.muted) + .text_color(t.dim()) .min_w_0() .child(super::glyph::line( subtitle.into(), @@ -1041,25 +1017,20 @@ pub(super) fn picture_card(picture: Picture, entity: &Entity, palette: P }), ) .children(removable.then(|| { - small_button( - "remove_picture_button", - palette, - palette.danger, - move |window, cx| { - remove_entity.update(cx, |yumush, cx| remove(yumush, window, cx)); - }, - ) + small_button("remove_picture_button", t, t.bad(), move |window, cx| { + remove_entity.update(cx, |yumush, cx| remove(yumush, window, cx)); + }) .child(w().settings_page.remove) })) } pub(super) fn small_button( id: &'static str, - palette: Palette, + t: Tokens, color: Hsla, on_click: impl Fn(&mut Window, &mut App) + 'static, ) -> Stateful
{ - super::parts::press(id, palette.tokens, on_click) + super::parts::press(id, t, on_click) .px(px(space::SM)) .text_size(text(text::UI)) .text_color(color) @@ -1070,11 +1041,11 @@ pub(super) fn delete_control( label: &'static str, confirming: bool, entity: &Entity, - palette: Palette, + t: Tokens, action: fn(&mut Yumush, &mut Window, &mut Context), ) -> impl IntoElement { let entity = entity.clone(); - small_button(id, palette, palette.danger, move |window, cx| { + small_button(id, t, t.bad(), move |window, cx| { entity.update(cx, |yumush, cx| action(yumush, window, cx)); }) .when(confirming, |this| this.font_weight(FontWeight::MEDIUM)) @@ -1097,15 +1068,15 @@ pub(super) fn row(label: &'static str, control: impl IntoElement) -> Div { .child(control) } -pub(super) fn segment_track(_palette: Palette) -> Div { +pub(super) fn segment_track(_t: Tokens) -> Div { div().h(px(size::CONTROL)).flex().gap(px(space::LG)) } -pub(super) fn segment(item: E, active: bool, palette: Palette) -> E { +pub(super) fn segment(item: E, active: bool, t: Tokens) -> E { let (border, text) = if active { - (palette.tokens.paper(), palette.tokens.paper()) + (t.paper(), t.paper()) } else { - (transparent_black(), palette.muted) + (transparent_black(), t.dim()) }; item.flex() @@ -1120,7 +1091,7 @@ pub(super) fn segmented( options: impl IntoIterator, selected: T, entity: &Entity, - palette: Palette, + t: Tokens, select: fn(&mut Yumush, T, &mut Context), ) -> impl IntoElement { div() @@ -1138,17 +1109,13 @@ pub(super) fn segmented( .gap(px(space::XXS)) .text_size(text(text::UI)) .font_weight(FontWeight::MEDIUM) - .text_color(if on { - palette.tokens.paper() - } else { - palette.muted - }) + .text_color(if on { t.paper() } else { t.dim() }) .on_click(move |_, _, cx| { entity.update(cx, |yumush, cx| select(yumush, choice, cx)); }) .child(label) .child(div().h(px(stroke::LINE)).bg(if on { - palette.tokens.paper() + t.paper() } else { transparent_black() })) diff --git a/crates/client/src/gui/share_view.rs b/crates/client/src/gui/share_view.rs index ebe1a32..eecd6d1 100644 --- a/crates/client/src/gui/share_view.rs +++ b/crates/client/src/gui/share_view.rs @@ -1,34 +1,17 @@ -use common::model::Id; use std::{ collections::HashMap, sync::Arc, time::{Duration, Instant}, }; +use super::camera_view::CAMERA_BUSY; +use common::model::Id; use common::share::{Codec, Fps, Kind, Mode, Quality, Resolution, clamp, options}; +use std::sync::atomic::Ordering; use crate::lang::w; use crate::share::Target; -const FULL_VOLUME: f32 = 100.; -const VOLUME_WIDTH: f32 = 80.; -const APPS_HEIGHT: f32 = 160.; -const PICK_COLUMNS: usize = 3; -const PICK_REFRESH: Duration = Duration::from_millis(1500); - -const PICK_ROW: f32 = size::THUMB + size::ROW; -const PREVIEW_AGE: Duration = Duration::from_secs(3); - -#[derive(Default)] -struct Picker { - sources: Vec<(Target, String)>, - previews: HashMap)>, -} - -const TOP_QUALITY: Quality = Quality { - resolution: Resolution::P2160, - fps: Fps::F60, -}; use gpui_kit::{ Anchor, AnyElement, App, AppContext, Context, Div, Entity, InteractiveElement, IntoElement, KeyDownEvent, Keystroke, Modifiers, MouseButton, ObjectFit, ParentElement, PlatformInput, @@ -45,7 +28,7 @@ use gpui_kit::{ }; use super::{ - Palette, Tooltip as _, Trigger, Yumush, camera_view, + Tooltip as _, Trigger, Yumush, camera_view, chat::View, clickable, entity_action, media_view::into_render_image, @@ -53,7 +36,7 @@ use super::{ parts::{self, Scale, Tone, icon_button, scrim}, settings_page::segmented, stream_stats::{stream_card, watch_stats}, - style::{radius, size, space, text}, + style::{Tokens, radius, size, space, text}, surface::Surface, text, widget::spawn_warn, @@ -63,27 +46,65 @@ use crate::{ share::{ audio::{AudioApp, AudioKind, is_excluded, is_picked}, encode::capabilities, - session::WatchQuality, + watch::WatchQuality, }, }; +const FULL_VOLUME: f32 = 100.; +const VOLUME_WIDTH: f32 = 80.; +const APPS_HEIGHT: f32 = 160.; +const PICK_COLUMNS: usize = 3; +const PICK_REFRESH: Duration = Duration::from_millis(1500); +const PICK_ROW: f32 = size::THUMB + size::ROW; +const PREVIEW_AGE: Duration = Duration::from_secs(3); +const TOP_QUALITY: Quality = Quality { + resolution: Resolution::P2160, + fps: Fps::F60, +}; const FLOAT_RIGHT: f32 = space::LG; const FLOAT_BOTTOM: f32 = size::ROW * 2. + space::XL; const FLOAT_WIDTH: f32 = size::MEDIA; const FLOAT_HEIGHT: f32 = size::MEDIA * 9. / 16.; const DRAG_SLOP: f32 = 4.; +const BAR_TTL: Duration = Duration::from_millis(2500); +const APPS_REFRESH: Duration = Duration::from_secs(2); +const APPS_IDLE: Duration = Duration::from_secs(5); + +#[derive(Default)] +struct Picker { + sources: Vec<(Target, String)>, + previews: HashMap)>, +} + +#[derive(Default, Clone, Copy)] +enum Drag { + #[default] + Idle, + Pressed { + start: gpui_kit::Point, + from: (f32, f32), + }, + Dragging { + start: gpui_kit::Point, + from: (f32, f32), + }, +} + +impl Drag { + fn grab(self) -> Option<(gpui_kit::Point, (f32, f32))> { + match self { + Drag::Idle => None, + Drag::Pressed { start, from } | Drag::Dragging { start, from } => Some((start, from)), + } + } +} #[derive(Default)] pub(super) struct Float { shift: (f32, f32), - grab: Option<(gpui_kit::Point, (f32, f32))>, - moved: bool, + drag: Drag, } -const BAR_TTL: Duration = Duration::from_millis(2500); -const APPS_REFRESH: Duration = Duration::from_secs(2); -const APPS_IDLE: Duration = Duration::from_secs(5); - pub(super) const RESOLUTIONS: [(Resolution, &str); 6] = [ (Resolution::P360, "360"), (Resolution::P480, "480"), @@ -128,7 +149,7 @@ impl AudioMode { } } -fn pick(app: &AudioApp) -> ShareAudio { +fn audio_choice(app: &AudioApp) -> ShareAudio { match app.kind { AudioKind::App => ShareAudio::App { name: app.name.clone(), @@ -138,7 +159,7 @@ fn pick(app: &AudioApp) -> ShareAudio { } } -fn chosen(audio: &ShareAudio, app: &AudioApp) -> bool { +fn is_chosen(audio: &ShareAudio, app: &AudioApp) -> bool { match audio { ShareAudio::App { name, pid } => { app.kind == AudioKind::App && is_picked((name, *pid), &app.name, app.pid) @@ -196,10 +217,10 @@ fn pick_tile( name: String, preview: Option>, entity: &Entity, - palette: Palette, + t: Tokens, ) -> impl IntoElement { let entity = entity.clone(); - clickable(("share_target", index), palette, move |window, cx| { + clickable(("share_target", index), t, move |window, cx| { window.close_dialog(cx); entity.update(cx, |yumush, cx| yumush.share_to(Some(target), window, cx)); }) @@ -215,7 +236,7 @@ fn pick_tile( .h(px(size::THUMB)) .rounded(px(radius::SM)) .overflow_hidden() - .bg(palette.field) + .bg(t.raise()) .children(preview.map(|image| img(image).size_full().object_fit(ObjectFit::Contain))), ) .child(div().truncate().text_size(px(text::LABEL)).child(name)) @@ -230,7 +251,7 @@ impl Yumush { return; }; let _ = this.update(cx, |yumush, cx| { - yumush.chat.shares.insert(community_id, shares); + yumush.chat.session.shares.insert(community_id, shares); cx.notify(); }); }) @@ -241,7 +262,7 @@ impl Yumush { if self.share_busy { return; } - if self.network.sharing() || !crate::share::capture::PICKS { + if self.network.share_source(Kind::Screen).is_some() || !crate::share::capture::PICKS { self.share_to(None, window, cx); return; } @@ -250,7 +271,7 @@ impl Yumush { fn pick_share(&mut self, window: &mut Window, cx: &mut Context) { let entity = cx.entity(); - let palette = super::palette(cx); + let t = Tokens::of(cx); let picker: Entity = cx.new(|_| Picker::default()); let weak = picker.downgrade(); window.open_dialog(cx, move |dialog, _, cx| { @@ -268,7 +289,7 @@ impl Yumush { let (target, name) = &picker.sources[index]; let preview = picker.previews.get(target).map(|(_, image)| image.clone()); - pick_tile(index, *target, name.clone(), preview, &entity, palette) + pick_tile(index, *target, name.clone(), preview, &entity, t) }); let fillers = (end..start + PICK_COLUMNS).map(|_| div().flex_1()); div() @@ -305,7 +326,7 @@ impl Yumush { ages.get(&target) .is_none_or(|taken| taken.elapsed() >= PREVIEW_AGE) }; - crate::share::capture::targets(&stale).unwrap_or_default() + crate::share::capture::targets(&stale) }) .await; let Some(picker) = weak.upgrade() else { @@ -330,14 +351,14 @@ impl Yumush { fn share_to(&mut self, target: Option, window: &mut Window, cx: &mut Context) { let network = self.network.clone(); - let sharing = network.sharing(); + let sharing = network.share_source(Kind::Screen).is_some(); let settings = self.settings.share.clone(); self.share_busy = true; cx.spawn_in(window, async move |this, cx| { if sharing { - let _ = network.stop_share().await; - } else if let Err(error) = network.start_share(&settings, target).await { + let _ = network.stop(Kind::Screen).await; + } else if let Err(error) = network.start(Kind::Screen, &settings, target).await { notify_error(&this, cx, error); } let _ = this.update(cx, |yumush, cx| { @@ -350,7 +371,7 @@ impl Yumush { fn toggle_share_mute(&mut self, window: &mut Window, cx: &mut Context) { let current = self.settings.share.volume; - let Some(viewer) = self.chat.viewer.as_mut() else { + let Some(viewer) = self.chat.session.viewer.as_mut() else { return; }; let next = if current > 0. { @@ -384,13 +405,16 @@ impl Yumush { if self.share_apps_task.is_some() { return; } - let network = self.network.clone(); self.share_apps_task = Some(cx.spawn(async move |this, cx| { loop { - let network = network.clone(); let (apps, cameras) = cx .background_executor() - .spawn(async move { (network.audio_apps(), crate::share::camera::devices()) }) + .spawn(async move { + ( + crate::share::audio_capture::apps(), + crate::share::camera::devices(), + ) + }) .await; let shown = this .update(cx, |yumush, cx| { @@ -413,15 +437,11 @@ impl Yumush { let device = self.settings.share.camera_device.clone(); let fresh = self.network.share_modes(Kind::Camera).is_none(); cx.spawn(async move |this, cx| { - let (devices, modes) = cx + let modes = cx .background_executor() - .spawn(async move { - let modes = fresh.then(|| crate::share::camera::list(device.as_deref())); - (crate::share::camera::devices(), modes) - }) + .spawn(async move { fresh.then(|| crate::share::camera::list(device.as_deref())) }) .await; let _ = this.update(cx, |yumush, cx| { - yumush.camera_devices = devices; if let Some(modes) = modes { yumush.camera_modes = modes; } @@ -434,18 +454,48 @@ impl Yumush { pub(super) fn set_camera_device(&mut self, device: String, cx: &mut Context) { self.update_share(cx, |settings| settings.camera_device = Some(device)); self.refresh_camera_modes(cx); - if self.network.camera_on() { - let network = self.network.clone(); - let settings = self.settings.share.clone(); - spawn_warn(cx, "camera switch", async move { - network.stop_camera().await?; - network.start_camera(&settings).await - }); + if !CAMERA_BUSY.load(Ordering::Relaxed) && self.network.share_source(Kind::Camera).is_some() + { + self.switch_camera(cx); + } + } + + fn switch_camera(&mut self, cx: &mut Context) { + CAMERA_BUSY.store(true, Ordering::Relaxed); + let network = self.network.clone(); + let settings = self.settings.share.clone(); + let device = settings.camera_device.clone(); + cx.spawn(async move |this, cx| { + let switched = async { + network.stop(Kind::Camera).await?; + network.start(Kind::Camera, &settings, None).await + } + .await; + if let Err(error) = switched { + tracing::warn!("camera switch failed: {error}"); + } + let _ = this.update(cx, |yumush, cx| yumush.settle_camera(device, cx)); + }) + .detach(); + } + + pub(super) fn settle_camera(&mut self, device: Option, cx: &mut Context) { + CAMERA_BUSY.store(false, Ordering::Relaxed); + if self.network.share_source(Kind::Camera).is_some() + && self.settings.share.camera_device != device + { + self.switch_camera(cx); + } else { + cx.notify(); } } - pub(super) fn set_share_resolution(&mut self, resolution: Resolution, cx: &mut Context) { - let kind = self.share_tab; + pub(super) fn set_share_resolution( + &mut self, + kind: Kind, + resolution: Resolution, + cx: &mut Context, + ) { self.update_share(cx, |settings| match kind { Kind::Screen => settings.top.resolution = resolution, Kind::Camera => settings.camera.resolution = resolution, @@ -456,8 +506,7 @@ impl Yumush { self.update_share(cx, |settings| settings.codec = codec); } - pub(super) fn set_share_fps(&mut self, fps: Fps, cx: &mut Context) { - let kind = self.share_tab; + pub(super) fn set_share_fps(&mut self, kind: Kind, fps: Fps, cx: &mut Context) { self.update_share(cx, |settings| match kind { Kind::Screen => settings.top.fps = fps, Kind::Camera => settings.camera.fps = fps, @@ -469,14 +518,14 @@ impl Yumush { let audio = match (mode, self.share_apps.first()) { (AudioMode::Off, _) => ShareAudio::Off, (AudioMode::Everything, _) => ShareAudio::Everything, - (AudioMode::App, Some(app)) => pick(app), + (AudioMode::App, Some(app)) => audio_choice(app), (AudioMode::App, None) => return, }; self.update_share(cx, |settings| settings.audio = audio); } pub(super) fn set_share_source(&mut self, app: &AudioApp, cx: &mut Context) { - let audio = pick(app); + let audio = audio_choice(app); self.update_share(cx, |settings| settings.audio = audio); } @@ -522,6 +571,7 @@ impl Yumush { pub(super) fn is_watching(&self, user_id: Id, kind: Kind) -> bool { self.chat + .session .viewer .as_ref() .is_some_and(|viewer| viewer.user_id == user_id && viewer.kind == kind) @@ -529,6 +579,7 @@ impl Yumush { pub(super) fn viewing(&self) -> Option<(Id, Kind)> { self.chat + .session .viewer .as_ref() .map(|viewer| (viewer.user_id, viewer.kind)) @@ -561,7 +612,7 @@ impl Yumush { } })]; - self.chat.viewer = Some(Viewer { + self.chat.session.viewer = Some(Viewer { user_id, kind, shown: false, @@ -580,7 +631,7 @@ impl Yumush { let volume = self.settings.share.volume; let choice = self.settings.voice.choice.clone(); let top = self.share_top(user_id, kind); - if self.chat.tiles.contains_key(&(user_id, kind)) { + if self.chat.session.tiles.contains_key(&(user_id, kind)) { network.set_watch_quality(user_id, kind, watch); } else { cx.spawn_in(window, async move |this, cx| { @@ -602,7 +653,7 @@ impl Yumush { } pub(super) fn close_viewer(&mut self, cx: &mut Context) { - let Some(viewer) = self.chat.viewer.take() else { + let Some(viewer) = self.chat.session.viewer.take() else { return; }; let surface = viewer.surface.clone(); @@ -611,26 +662,18 @@ impl Yumush { cx.drop_image(frame, None); } }); - let network = self.network.clone(); - if self.chat.tiles.contains_key(&(viewer.user_id, viewer.kind)) { - network.set_watch_quality( - viewer.user_id, - viewer.kind, - camera_view::tile_quality(self.chat.stage), - ); + let source = (viewer.user_id, viewer.kind); + if self.chat.session.tiles.contains_key(&source) { + self.network + .set_watch_quality(source.0, source.1, self.chat.stage.quality()); } else { - let user_id = viewer.user_id; - let kind = viewer.kind; - cx.spawn(async move |_, _| { - let _ = network.unwatch_share(user_id, kind).await; - }) - .detach(); + self.unwatch_tile(source, cx); } cx.notify(); } pub(super) fn tick_viewer(&mut self, mut window: Option<&mut Window>, cx: &mut Context) { - let Some(viewer) = self.chat.viewer.as_mut() else { + let Some(viewer) = self.chat.session.viewer.as_mut() else { return; }; let Some(frame) = self.network.share_frame(viewer.user_id, viewer.kind) else { @@ -642,7 +685,12 @@ impl Yumush { let previous = viewer .surface .update(cx, |surface, cx| surface.replace(next.clone(), cx)); - if let Some(tile) = self.chat.tiles.get_mut(&(viewer.user_id, viewer.kind)) { + if let Some(tile) = self + .chat + .session + .tiles + .get_mut(&(viewer.user_id, viewer.kind)) + { tile.shown |= next.is_some(); if let Some(old) = tile .surface @@ -663,7 +711,7 @@ impl Yumush { } pub(super) fn toggle_fullscreen(&mut self, cx: &mut Context) { - if let Some(viewer) = self.chat.viewer.as_mut() { + if let Some(viewer) = self.chat.session.viewer.as_mut() { viewer.fullscreen = !viewer.fullscreen; } cx.notify(); @@ -672,7 +720,7 @@ impl Yumush { pub(super) fn share_settings_button( &self, entity: &Entity, - palette: Palette, + t: Tokens, kind: Kind, cx: &App, ) -> impl IntoElement { @@ -711,36 +759,49 @@ impl Yumush { )) .content(move |_, _, cx| { let entity = settings.clone(); - settings_card(&entity, entity.read(cx), palette) + settings_card(&entity, entity.read(cx), t) }) } - pub(super) fn inline_viewer(&self, entity: &Entity, palette: Palette) -> Option
{ + pub(super) fn inline_viewer(&self, entity: &Entity, t: Tokens) -> Option
{ let viewer = self .chat + .session .viewer .as_ref() .filter(|viewer| !viewer.fullscreen) - .filter(|_| self.chat.selected_community_id == self.chat.voice_community())?; - Some(self.viewer_pane(viewer, entity, palette)) + .filter(|_| self.chat.session.selected_community_id == self.chat.voice_community())?; + Some(self.viewer_pane(viewer, entity, t)) } fn drag_float(&mut self, position: gpui_kit::Point, window: &Window) -> bool { - let Some((start, from)) = self.chat.float.grab else { + let Some((start, from)) = self.chat.session.float.drag.grab() else { return false; }; let viewport = window.viewport_size(); let (width, height) = (f32::from(viewport.width), f32::from(viewport.height)); let x = (from.0 + f32::from(position.x - start.x)) - .clamp(FLOAT_RIGHT - (width - FLOAT_WIDTH), FLOAT_RIGHT); + .max(FLOAT_RIGHT - (width - FLOAT_WIDTH)) + .min(FLOAT_RIGHT); let y = (from.1 + f32::from(position.y - start.y)) - .clamp(FLOAT_BOTTOM - (height - FLOAT_HEIGHT), FLOAT_BOTTOM); + .max(FLOAT_BOTTOM - (height - FLOAT_HEIGHT)) + .min(FLOAT_BOTTOM); let moved = (x - from.0).abs() + (y - from.1).abs() > DRAG_SLOP; - self.chat.float.moved |= moved; - self.chat.float.shift = (x, y); + let float = &mut self.chat.session.float; + float.shift = (x, y); + if moved { + float.drag = Drag::Dragging { start, from }; + } true } + fn release_float(&mut self) { + let float = &mut self.chat.session.float; + if let Drag::Pressed { .. } = float.drag { + float.drag = Drag::Idle; + } + } + pub(super) fn float_moved( &mut self, event: &gpui_kit::MouseMoveEvent, @@ -748,7 +809,7 @@ impl Yumush { cx: &mut Context, ) { if event.pressed_button != Some(MouseButton::Left) { - self.chat.float.grab = None; + self.release_float(); return; } if self.drag_float(event.position, window) { @@ -756,17 +817,20 @@ impl Yumush { } } - pub(super) fn floating_viewer(&self, entity: &Entity, palette: Palette) -> Option
{ + pub(super) fn floating_viewer(&self, entity: &Entity, t: Tokens) -> Option
{ let viewer = self .chat + .session .viewer .as_ref() .filter(|viewer| !viewer.fullscreen)?; let community = self.chat.voice_community()?; - if self.chat.view == View::Chat && self.chat.selected_community_id == Some(community) { + if self.chat.session.view == View::Chat + && self.chat.session.selected_community_id == Some(community) + { return None; } - let (dx, dy) = self.chat.float.shift; + let (dx, dy) = self.chat.session.float.shift; let (grab, drag, release) = (entity.clone(), entity.clone(), entity.clone()); let entity = entity.clone(); Some( @@ -787,20 +851,23 @@ impl Yumush { .cursor_pointer() .on_mouse_down(MouseButton::Left, move |event, _, cx| { grab.update(cx, |yumush, _| { - let float = &mut yumush.chat.float; - float.grab = Some((event.position, float.shift)); - float.moved = false; + let float = &mut yumush.chat.session.float; + float.drag = Drag::Pressed { + start: event.position, + from: float.shift, + }; }) }) .on_mouse_move(move |event, window, cx| { drag.update(cx, |yumush, cx| yumush.float_moved(event, window, cx)) }) .on_mouse_up(MouseButton::Left, move |_, _, cx| { - release.update(cx, |yumush, _| yumush.chat.float.grab = None) + release.update(cx, |yumush, _| yumush.release_float()) }) .on_click(move |_, window, cx| { entity.update(cx, |yumush, cx| { - if std::mem::take(&mut yumush.chat.float.moved) { + let dragged = std::mem::take(&mut yumush.chat.session.float.drag); + if matches!(dragged, Drag::Dragging { .. }) { return; } yumush.select_community(community, window, cx); @@ -809,7 +876,7 @@ impl Yumush { .when(viewer.shown, |video| video.child(viewer.surface.clone())), ) .child( - camera_view::tile_label(self, palette, (viewer.user_id, viewer.kind)) + camera_view::tile_label(self, t, (viewer.user_id, viewer.kind)) .absolute() .left(px(space::SM)) .top(px(space::SM)), @@ -818,7 +885,7 @@ impl Yumush { } pub(super) fn hide_idle_cursor(&mut self, window: &mut Window, cx: &mut App) { - let Some(viewer) = self.chat.viewer.as_mut().filter(|viewer| { + let Some(viewer) = self.chat.session.viewer.as_mut().filter(|viewer| { viewer.fullscreen && !viewer.cursor_hidden && viewer.active.elapsed() >= BAR_TTL }) else { return; @@ -840,12 +907,13 @@ impl Yumush { }); } - pub(super) fn fullscreen_viewer(&self, entity: &Entity, palette: Palette) -> Option
{ + pub(super) fn fullscreen_viewer(&self, entity: &Entity, t: Tokens) -> Option
{ let viewer = self .chat + .session .viewer .as_ref() - .filter(|viewer| viewer.fullscreen && self.chat.view == View::Chat)?; + .filter(|viewer| viewer.fullscreen && self.chat.session.view == View::Chat)?; let bar = viewer.active.elapsed() < BAR_TTL; Some( div() @@ -853,7 +921,7 @@ impl Yumush { .inset_0() .flex() .bg(gpui_kit::black()) - .child(self.viewer_pane(viewer, entity, palette)) + .child(self.viewer_pane(viewer, entity, t)) .when(bar, |this| { this.child( div() @@ -861,7 +929,7 @@ impl Yumush { .left_0() .right_0() .bottom(px(size::CONTROL + space::LG)) - .child(self.voice_band(palette).bg(palette.tokens.ground())), + .child(self.voice_band(t).bg(t.ground())), ) .child( div() @@ -871,25 +939,24 @@ impl Yumush { .right_0() .flex() .justify_center() - .child(scrim(palette.tokens).child(parts::words( + .child(scrim(t).child(parts::words( w().share_view.esc_exit, parts::Text::Label, parts::Ink::Dim, - palette.tokens, + t, ))), ) }), ) } - fn viewer_pane(&self, viewer: &Viewer, entity: &Entity, palette: Palette) -> Div { + fn viewer_pane(&self, viewer: &Viewer, entity: &Entity, t: Tokens) -> Div { let (fullscreen_icon, fullscreen_tip) = if viewer.fullscreen { (IconName::Minimize, w().share_view.exit_fullscreen) } else { (IconName::Maximize, w().share_view.fullscreen) }; let audio = viewer.kind == Kind::Screen; - let t = palette.tokens; let (user_id, kind) = (viewer.user_id, viewer.kind); let stats = watch_stats(self, user_id, kind); let bar = viewer.active.elapsed() < BAR_TTL; @@ -899,12 +966,12 @@ impl Yumush { .min_h_0() .relative() .occlude() - .when(!viewer.fullscreen, |this| this.bg(palette.window)) + .when(!viewer.fullscreen, |this| this.bg(t.ground())) .on_mouse_move({ let entity = entity.clone(); move |_, _, cx| { entity.update(cx, |yumush, cx| { - if let Some(viewer) = yumush.chat.viewer.as_mut() { + if let Some(viewer) = yumush.chat.session.viewer.as_mut() { let hidden = viewer.active.elapsed() >= BAR_TTL; viewer.active = Instant::now(); viewer.cursor_hidden = false; @@ -928,7 +995,7 @@ impl Yumush { .when(viewer.shown, |video| video.child(viewer.surface.clone())), ) .child( - camera_view::tile_label(self, palette, (viewer.user_id, viewer.kind)) + camera_view::tile_label(self, t, (viewer.user_id, viewer.kind)) .absolute() .left(px(space::MD)) .top(px(space::MD)) @@ -945,7 +1012,7 @@ impl Yumush { t, move |_, cx| { entity.update(cx, |yumush, cx| { - if let Some(viewer) = yumush.chat.viewer.as_mut() { + if let Some(viewer) = yumush.chat.session.viewer.as_mut() { viewer.stats = !viewer.stats; } cx.notify(); @@ -965,7 +1032,7 @@ impl Yumush { .absolute() .right(px(space::MD)) .top(px(space::XXL)) - .child(stream_card(self, user_id, kind, palette)), + .child(stream_card(self, user_id, kind, t)), ) }) .child( @@ -999,7 +1066,7 @@ impl Yumush { }, Tone::Idle, Scale::Small, - palette.tokens, + t, entity_action(entity, |yumush, window, cx| { yumush.toggle_share_mute(window, cx) }), @@ -1016,7 +1083,7 @@ impl Yumush { fullscreen_tip, Tone::Idle, Scale::Small, - palette.tokens, + t, entity_action(entity, |yumush, _, cx| yumush.toggle_fullscreen(cx)), )) .child(icon_button( @@ -1025,7 +1092,7 @@ impl Yumush { w().share_view.close, Tone::Idle, Scale::Small, - palette.tokens, + t, entity_action(entity, |yumush, _, cx| yumush.close_viewer(cx)), )), ), @@ -1033,30 +1100,29 @@ impl Yumush { } } -fn settings_card(entity: &Entity, yumush: &Yumush, palette: Palette) -> Div { +fn settings_card(entity: &Entity, yumush: &Yumush, t: Tokens) -> Div { let settings = &yumush.settings.share; - let t = palette.tokens; let card = super::parts::quick(t).min_w(px(size::POPOVER)); let card = match yumush.share_tab { - Kind::Camera => card.child(camera_devices(entity, yumush, palette)), + Kind::Camera => card.child(camera_devices(entity, yumush, t)), Kind::Screen => card .child(div().px(px(space::SM)).child(segmented( AudioMode::all(), AudioMode::of(&settings.audio), entity, - palette, + t, Yumush::set_share_audio_mode, ))) - .children(audio_list(entity, yumush, palette)), + .children(audio_list(entity, yumush, t)), }; card.child(super::parts::thread(t)) - .child(quality_toggle(entity, yumush, palette)) + .child(quality_toggle(entity, yumush, t)) .when(yumush.share_more, |card| { - card.children(quality_rows(entity, yumush, palette)) + card.children(quality_rows(entity, yumush, t)) }) } -fn camera_devices(entity: &Entity, yumush: &Yumush, palette: Palette) -> Div { +fn camera_devices(entity: &Entity, yumush: &Yumush, t: Tokens) -> Div { let chosen = yumush .settings .share @@ -1067,7 +1133,7 @@ fn camera_devices(entity: &Entity, yumush: &Yumush, palette: Palette) -> if yumush.camera_devices.is_empty() { return div() .px(px(space::SM)) - .text_color(palette.muted) + .text_color(t.dim()) .child(w().share_view.no_camera); } div().flex().flex_col().gap(px(space::XXS)).children( @@ -1078,14 +1144,10 @@ fn camera_devices(entity: &Entity, yumush: &Yumush, palette: Palette) -> .map(|(index, name)| { let entity = entity.clone(); let device = name.clone(); - row_style(clickable( - ("camera_device", index), - palette, - move |_, cx| { - let device = device.clone(); - entity.update(cx, |yumush, cx| yumush.set_camera_device(device, cx)); - }, - )) + row_style(clickable(("camera_device", index), t, move |_, cx| { + let device = device.clone(); + entity.update(cx, |yumush, cx| yumush.set_camera_device(device, cx)); + })) .child( div() .flex_1() @@ -1096,7 +1158,7 @@ fn camera_devices(entity: &Entity, yumush: &Yumush, palette: Palette) -> .children((chosen.as_ref() == Some(name)).then(|| { super::parts::small_icon(IconName::Check) .flex_shrink_0() - .text_color(palette.text) + .text_color(t.paper()) })) }), ) @@ -1108,15 +1170,19 @@ fn label(list: &[(T, &'static str)], value: T) -> &'static str { .map_or("", |(_, name)| *name) } -fn quality_toggle(entity: &Entity, yumush: &Yumush, palette: Palette) -> impl IntoElement { - let open = yumush.share_more; - let kind = yumush.share_tab; +fn shown_top(yumush: &Yumush, kind: Kind) -> (Vec, Quality) { let modes = share_modes(yumush, kind); let top = clamp( yumush.settings.share.top(kind), &modes, capabilities().max_height, ); + (modes, top) +} + +fn quality_toggle(entity: &Entity, yumush: &Yumush, t: Tokens) -> impl IntoElement { + let open = yumush.share_more; + let (_, top) = shown_top(yumush, yumush.share_tab); let summary = format!( "{} · {} fps · {}", label(&RESOLUTIONS, top.resolution), @@ -1124,13 +1190,13 @@ fn quality_toggle(entity: &Entity, yumush: &Yumush, palette: Palette) -> label(&codecs(), yumush.settings.share.codec), ); let entity = entity.clone(); - row_style(clickable("share_quality", palette, move |_, cx| { + row_style(clickable("share_quality", t, move |_, cx| { entity.update(cx, |yumush, cx| { yumush.share_more = !yumush.share_more; cx.notify(); }) })) - .text_color(palette.muted) + .text_color(t.dim()) .child(div().flex_1().child(summary)) .child(super::parts::small_icon(if open { IconName::ChevronUp @@ -1139,14 +1205,25 @@ fn quality_toggle(entity: &Entity, yumush: &Yumush, palette: Palette) -> })) } -fn quality_rows(entity: &Entity, yumush: &Yumush, palette: Palette) -> [Div; 3] { +fn quality_rows(entity: &Entity, yumush: &Yumush, t: Tokens) -> [Div; 3] { let settings = &yumush.settings.share; let kind = yumush.share_tab; - let modes = share_modes(yumush, kind); + let (modes, top) = shown_top(yumush, kind); let max_height = capabilities().max_height; - let top = clamp(settings.top(kind), &modes, max_height); let (resolutions, fps) = options(&modes, top.resolution, max_height); - let t = palette.tokens; + let (set_resolution, set_fps): ( + fn(&mut Yumush, Resolution, &mut Context), + fn(&mut Yumush, Fps, &mut Context), + ) = match kind { + Kind::Screen => ( + |yumush, resolution, cx| yumush.set_share_resolution(Kind::Screen, resolution, cx), + |yumush, fps, cx| yumush.set_share_fps(Kind::Screen, fps, cx), + ), + Kind::Camera => ( + |yumush, resolution, cx| yumush.set_share_resolution(Kind::Camera, resolution, cx), + |yumush, fps, cx| yumush.set_share_fps(Kind::Camera, fps, cx), + ), + }; [ super::parts::quick_row( w().share_view.resolution, @@ -1156,8 +1233,8 @@ fn quality_rows(entity: &Entity, yumush: &Yumush, palette: Palette) -> [ .filter(|(resolution, _)| resolutions.contains(resolution)), top.resolution, entity, - palette, - Yumush::set_share_resolution, + t, + set_resolution, ), t, ), @@ -1167,8 +1244,8 @@ fn quality_rows(entity: &Entity, yumush: &Yumush, palette: Palette) -> [ FPS.into_iter().filter(|(value, _)| fps.contains(value)), top.fps, entity, - palette, - Yumush::set_share_fps, + t, + set_fps, ), t, ), @@ -1181,7 +1258,7 @@ fn quality_rows(entity: &Entity, yumush: &Yumush, palette: Palette) -> [ }), settings.codec, entity, - palette, + t, Yumush::set_share_codec, ), t, @@ -1198,7 +1275,7 @@ pub(super) fn share_modes(yumush: &Yumush, kind: Kind) -> Vec { .unwrap_or_else(|| vec![(u32::MAX, u32::MAX)]) } -fn audio_list(entity: &Entity, yumush: &Yumush, palette: Palette) -> Option { +fn audio_list(entity: &Entity, yumush: &Yumush, t: Tokens) -> Option { yumush.share_apps_seen.set(Instant::now()); let settings = &yumush.settings.share; @@ -1214,14 +1291,12 @@ fn audio_list(entity: &Entity, yumush: &Yumush, palette: Palette) -> Opt (!apps.is_empty()).then(|| { let rows = div().flex().flex_col().gap(px(space::XXS)).children( apps.into_iter() - .map(|app| include_row(entity, settings, app, palette)), + .map(|app| include_row(entity, settings, app, t)), ); - field(w().share_view.sound_from, app_list(rows), palette).into_any_element() + field(w().share_view.sound_from, app_list(rows), t).into_any_element() }) } - audio => { - Some(app_list(pick_list(entity, audio, &yumush.share_apps, palette)).into_any_element()) - } + audio => Some(app_list(pick_list(entity, audio, &yumush.share_apps, t)).into_any_element()), } } @@ -1233,12 +1308,7 @@ fn app_list(rows: impl IntoElement) -> impl IntoElement { .child(rows) } -fn pick_list( - entity: &Entity, - audio: &ShareAudio, - apps: &[AudioApp], - palette: Palette, -) -> Div { +fn pick_list(entity: &Entity, audio: &ShareAudio, apps: &[AudioApp], t: Tokens) -> Div { let groups = [ (AudioKind::App, w().share_view.apps), (AudioKind::Output, w().share_view.outputs), @@ -1253,22 +1323,22 @@ fn pick_list( let rows: Vec<_> = apps .iter() .filter(|app| app.kind == kind) - .map(|app| pick_row(entity, chosen(audio, app), app, palette)) + .map(|app| pick_row(entity, is_chosen(audio, app), app, t)) .collect(); - (!rows.is_empty()).then(|| group(label, rows, palette)) + (!rows.is_empty()).then(|| group(label, rows, t)) })) } -fn group(label: &'static str, rows: Vec, palette: Palette) -> Div { +fn group(label: &'static str, rows: Vec, t: Tokens) -> Div { div() .flex() .flex_col() .gap(px(space::XXS)) - .child(parts::caption_head(label, palette.tokens)) + .child(parts::caption_head(label, t)) .children(rows) } -fn field(label: &'static str, control: impl IntoElement, palette: Palette) -> Div { +fn field(label: &'static str, control: impl IntoElement, t: Tokens) -> Div { div() .flex() .flex_col() @@ -1276,7 +1346,7 @@ fn field(label: &'static str, control: impl IntoElement, palette: Palette) -> Di .child( div() .text_size(text(text::CAPTION)) - .text_color(palette.muted) + .text_color(t.dim()) .child(label), ) .child(control) @@ -1291,7 +1361,7 @@ pub(super) fn row_style(item: E) -> E { .rounded(px(radius::MD)) } -fn name_cell(app: &AudioApp, palette: Palette) -> Div { +fn name_cell(app: &AudioApp, t: Tokens) -> Div { div() .flex_1() .min_w_0() @@ -1304,7 +1374,7 @@ fn name_cell(app: &AudioApp, palette: Palette) -> Div { .min_w_0() .truncate() .text_size(text(text::CAPTION)) - .text_color(palette.muted) + .text_color(t.dim()) .child(app.detail.clone()), ) } @@ -1313,18 +1383,18 @@ fn include_row( entity: &Entity, settings: &ShareSettings, app: &AudioApp, - palette: Palette, + t: Tokens, ) -> impl IntoElement { let entity = entity.clone(); let included = !is_excluded(&settings.excluded, &app.name, app.pid); let target = app.clone(); row_style(div()) - .child(name_cell(app, palette)) + .child(name_cell(app, t)) .child(div().flex_shrink_0().child(super::parts::toggle( gpui_kit::ElementId::Name(format!("share_app_{}", app.key()).into()), included, - palette.tokens, + t, move |_, cx| { entity.update(cx, |yumush, cx| { yumush.set_share_included(&target, !included, cx) @@ -1333,26 +1403,21 @@ fn include_row( ))) } -fn pick_row( - entity: &Entity, - chosen: bool, - app: &AudioApp, - palette: Palette, -) -> impl IntoElement { +fn pick_row(entity: &Entity, chosen: bool, app: &AudioApp, t: Tokens) -> impl IntoElement { let entity = entity.clone(); let target = app.clone(); row_style(clickable( format!("share_app_{}", app.key()), - palette, + t, move |_, cx| { entity.update(cx, |yumush, cx| yumush.set_share_source(&target, cx)); }, )) - .child(name_cell(app, palette)) + .child(name_cell(app, t)) .children(chosen.then(|| { super::parts::small_icon(IconName::Check) .flex_shrink_0() - .text_color(palette.text) + .text_color(t.paper()) })) } diff --git a/crates/client/src/gui/sidebar.rs b/crates/client/src/gui/sidebar.rs index 0d6ae31..1a913e7 100644 --- a/crates/client/src/gui/sidebar.rs +++ b/crates/client/src/gui/sidebar.rs @@ -22,15 +22,15 @@ use gpui_kit::{ }; use super::{ - Palette, Tooltip as _, Yumush, avatar, + Tooltip as _, Yumush, avatar, chat::{Armed, View, create_community}, clickable, community_icon, community_name, entity_action, hoverable, input_dialog, parts::{Scale, Tone, icon_button}, presence_avatar, profile::profile_popover, social::Relation, - style::{radius, size, space, text}, - widget::{bare_input, compact_frame}, + style::{Tokens, radius, size, space, text}, + widget::{bare_input, underline}, }; const SLIDE: std::time::Duration = std::time::Duration::from_millis(320); @@ -40,11 +40,11 @@ fn slide() -> gpui_kit::Animation { } impl Yumush { - pub(super) fn sidebar(&self, entity: &Entity, palette: Palette) -> impl IntoElement { + pub(super) fn sidebar(&self, entity: &Entity, t: Tokens) -> impl IntoElement { let content = if self.chat.sidebar_collapsed && !self.sliding() { - self.collapsed_sidebar(entity, palette).into_any_element() + self.collapsed_sidebar(entity, t).into_any_element() } else { - self.expanded_sidebar(entity, palette) + self.expanded_sidebar(entity, t) }; self.folding( @@ -88,7 +88,7 @@ impl Yumush { } } - fn collapsed_sidebar(&self, entity: &Entity, palette: Palette) -> Div { + fn collapsed_sidebar(&self, entity: &Entity, t: Tokens) -> Div { div() .h_full() .w(px(size::RAIL)) @@ -104,11 +104,7 @@ impl Yumush { .flex_col() .items_center() .gap(px(space::MD)) - .child(self.logo_toggle( - entity, - palette, - logo_mark(palette).size(px(size::CONTROL)), - )), + .child(self.logo_toggle(entity, t, logo_mark(t).size(px(size::CONTROL)))), ) .child( div() @@ -119,14 +115,14 @@ impl Yumush { .children( self.user .as_ref() - .map(|user| self.account_trigger(entity, user, false, palette)), + .map(|user| self.account_trigger(entity, user, false, t)), ), ) } - fn expanded_sidebar(&self, entity: &Entity, palette: Palette) -> AnyElement { - let friends_alert = - !self.chat.friends.incoming.is_empty() || !self.chat.invitations.is_empty(); + fn expanded_sidebar(&self, entity: &Entity, t: Tokens) -> AnyElement { + let friends_alert = !self.chat.session.friends.incoming.is_empty() + || !self.chat.session.invitations.is_empty(); div() .relative() @@ -147,10 +143,10 @@ impl Yumush { "logo", div().relative().child(self.logo_toggle( entity, - palette, + t, self.folding( "logo_mark", - logo_mark(palette).when(towing(self.wordmark_flipped), |mark| { + logo_mark(t).when(towing(self.wordmark_flipped), |mark| { mark.path(crate::logo::NEEDLE) }), |mark, f| mark.size(px(lerp(size::CHIP, size::CONTROL, f))), @@ -172,7 +168,7 @@ impl Yumush { .text_size(text(text::TITLE)) .line_height(gpui_kit::relative(LEADING)) .font_weight(FontWeight::SEMIBOLD) - .text_color(palette.text) + .text_color(t.paper()) .cursor_pointer() .on_click({ let entity = entity.clone(); @@ -186,7 +182,7 @@ impl Yumush { .child(wordmark_tail( self.wordmark_flips, self.wordmark_flipped, - palette, + t, )), |word, f| { word.relative() @@ -197,11 +193,11 @@ impl Yumush { ) .child(self.folding( "friends_fold", - div().child(self.friends_button(entity, friends_alert, palette)), + div().child(self.friends_button(entity, friends_alert, t)), fade, )), ) - .children(self.update_control(palette)) + .children(self.update_control(t)) .child( self.folding( "list_fold", @@ -213,18 +209,17 @@ impl Yumush { .flex() .flex_col() .gap(px(space::MD)) - .children(self.sections(entity, palette)), + .children(self.sections(entity, t)), |list, f| fade(list, f).flex_1().min_h_0(), ), ) - .children(self.build_control(entity, palette)) - .children(self.account_row(entity, palette)) + .children(self.build_control(entity, t)) + .children(self.account_row(entity, t)) .into_any_element() } - fn voice_chip(&self, community_id: Id, palette: Palette) -> AnyElement { + fn voice_chip(&self, community_id: Id, t: Tokens) -> AnyElement { let ids = self.chat.voice_ids(community_id); - let t = palette.tokens; let direct = self.is_direct(community_id); let heard: Vec = ids .iter() @@ -233,13 +228,18 @@ impl Yumush { .collect(); let mut speakers = heard .iter() - .filter(|id| self.chat.waves.speaking.contains(id)); + .filter(|id| self.chat.session.waves.speaking.contains(id)); let voice = match (speakers.next(), speakers.next()) { (Some(id), None) => super::parts::Voice::Live(t.person(*id)), (Some(_), Some(_)) => super::parts::Voice::Live(t.paper()), _ => super::parts::Voice::Quiet, }; - let total = self.chat.waves.total(&heard); + let total = self + .chat + .session + .waves + .total(&heard) + .map(|bars| super::chat::to_bands(&bars)); div() .id(format!("voice_chip_{community_id}")) .tip(w().sidebar.in_call) @@ -258,7 +258,7 @@ impl Yumush { this.child( div() .text_size(text(text::CAPTION)) - .text_color(palette.muted) + .text_color(t.dim()) .child(ids.len().to_string()), ) }) @@ -281,12 +281,7 @@ impl Yumush { ); } - fn logo_toggle( - &self, - entity: &Entity, - palette: Palette, - mark: impl IntoElement, - ) -> AnyElement { + fn logo_toggle(&self, entity: &Entity, t: Tokens, mark: impl IntoElement) -> AnyElement { let tip = if self.chat.sidebar_collapsed { w().sidebar.expand } else { @@ -294,7 +289,7 @@ impl Yumush { }; clickable( "sidebar_toggle", - palette, + t, entity_action(entity, |yumush, _, cx| { yumush.toggle_sidebar(); cx.notify(); @@ -309,7 +304,7 @@ impl Yumush { } pub(super) fn open_friends(&mut self, window: &mut Window, cx: &mut Context) { - self.chat.friends_open = true; + self.chat.session.friends_open = true; self.chat .search_input .update(cx, |input, cx| input.focus(window, cx)); @@ -317,30 +312,31 @@ impl Yumush { } pub(super) fn close_friends(&mut self, window: &mut Window, cx: &mut Context) { - self.chat.friends_open = false; + self.chat.session.friends_open = false; window.focus(&self.focus, cx); cx.notify(); } - fn friends_sheet(&self, entity: &Entity, cx: &App, palette: Palette) -> Div { + fn friends_sheet(&self, entity: &Entity, cx: &App, t: Tokens) -> Div { let query = super::widget::search_text(&self.chat.search_input, cx); - let found = self.chat.found.as_ref().filter(|found| { + let found = self.chat.session.found.as_ref().filter(|found| { !self .chat + .session .friends .friends .iter() .any(|user| user.id == found.id) }); - let friends = self.friend_list(entity, &query, palette); - super::parts::popover(palette.tokens) + let friends = self.friend_list(entity, &query, t); + super::parts::popover(t) .w(px(size::POPOVER)) .px(px(space::MD)) .py(px(space::MD)) .gap(px(space::MD)) - .child(input_box(&self.chat.search_input, palette)) - .children(found.map(|user| self.found_row(entity, user, palette))) - .children(self.requests(entity, palette)) + .child(input_box(&self.chat.search_input, t)) + .children(found.map(|user| self.found_row(entity, user, t))) + .children(self.requests(entity, t)) .when(!friends.is_empty(), |sheet| { sheet.child( div() @@ -355,18 +351,13 @@ impl Yumush { }) } - fn friends_button( - &self, - entity: &Entity, - alert: bool, - palette: Palette, - ) -> impl IntoElement { + fn friends_button(&self, entity: &Entity, alert: bool, t: Tokens) -> impl IntoElement { let opened = entity.clone(); let content = entity.clone(); gpui_kit::component::popover::Popover::new("friends_sheet") .anchor(Anchor::TopLeft) .appearance(false) - .open(self.chat.friends_open) + .open(self.chat.session.friends_open) .on_open_change(move |open, window, cx| { let open = *open; opened.update(cx, |yumush, cx| { @@ -386,7 +377,7 @@ impl Yumush { .items_center() .justify_center() .rounded_full() - .text_color(palette.muted) + .text_color(t.dim()) .child(super::parts::small_icon(IconName::Users)) .children(alert.then(|| { div() @@ -395,23 +386,24 @@ impl Yumush { .right(px(space::XXS)) .size(px(space::XS + space::XXS)) .rounded_full() - .bg(palette.text) + .bg(t.paper()) })), - palette, + t, ))) .content(move |_, _, cx| { let yumush = content.read(cx); - yumush.friends_sheet(&content, cx, palette) + yumush.friends_sheet(&content, cx, t) }) } - fn friend_list(&self, entity: &Entity, query: &str, palette: Palette) -> Vec { + fn friend_list(&self, entity: &Entity, query: &str, t: Tokens) -> Vec { let mut friends: Vec<&User> = self .chat + .session .friends .friends .iter() - .filter(|user| matches_query(&user.username, query)) + .filter(|user| user.username.to_lowercase().contains(query)) .collect(); friends.sort_by_key(|user| (self.doing(user.id), user.username.to_lowercase())); friends @@ -422,8 +414,8 @@ impl Yumush { let remove = entity.clone(); let row = hoverable( format!("friend_{}", user.id), - self.user_row(palette, user, None), - palette, + self.user_row(t, user, None), + t, ) .on_click(move |_, window, cx| { open.update(cx, |yumush, cx| { @@ -441,12 +433,12 @@ impl Yumush { ("remove_friend", user_id as usize), remove .read(cx) - .armed_label(armed, w().sidebar.remove_friend), + .armed_label(armed.clone(), w().sidebar.remove_friend), super::parts::small_icon(IconName::UserMinus), - palette.danger, - palette, + t.bad(), + t, super::profile::armed_action( - armed, + armed.clone(), &remove, popover, move |yumush, window, cx| yumush.remove_friend(user_id, window, cx), @@ -459,8 +451,8 @@ impl Yumush { .collect() } - fn sections(&self, entity: &Entity, palette: Palette) -> Vec { - let pinned = &self.chat.pinned; + fn sections(&self, entity: &Entity, t: Tokens) -> Vec { + let pinned = &self.chat.session.pinned; let list = |rows: Vec| { div() .flex() @@ -469,12 +461,12 @@ impl Yumush { .children(rows) .into_any_element() }; - let pins = self.rooms(entity, palette, |room| pinned.contains(&room.id)); - let groups = self.rooms(entity, palette, |room| { + let pins = self.rooms(entity, t, |room| pinned.contains(&room.id)); + let groups = self.rooms(entity, t, |room| { room.kind.is_group() && !pinned.contains(&room.id) }); - let people = std::iter::once(self.notes_row(entity, palette)) - .chain(self.rooms(entity, palette, |room| { + let people = std::iter::once(self.notes_row(entity, t)) + .chain(self.rooms(entity, t, |room| { room.kind.is_direct() && !pinned.contains(&room.id) })) .collect(); @@ -488,31 +480,30 @@ impl Yumush { .into_iter() .enumerate() .flat_map(|(index, section)| { - std::iter::once(section).chain((index + 1 < count).then(|| { - super::parts::thread(palette.tokens) - .mx(px(space::SM)) - .into_any_element() - })) + std::iter::once(section).chain( + (index + 1 < count) + .then(|| super::parts::thread(t).mx(px(space::SM)).into_any_element()), + ) }) .collect() } - fn notes_row(&self, entity: &Entity, palette: Palette) -> AnyElement { + fn notes_row(&self, entity: &Entity, t: Tokens) -> AnyElement { let notes = self.chat.notes(); let active = notes.is_some_and(|notes| self.chat.is_selected(notes.id)); - let unread = notes.and_then(|notes| self.chat.unread.get(¬es.id)); + let unread = notes.and_then(|notes| self.chat.session.unread.get(¬es.id)); let open = entity.clone(); hoverable( "notes", room_row( - palette, + t, active, - Some(notes_tile(palette)), + notes_tile(t), w().sidebar.notes.to_string(), - unread_badge(palette, false, unread), + unread_badge(t, false, unread), ), - palette, + t, ) .on_click(move |_, window, cx| open.update(cx, |yumush, cx| yumush.open_notes(window, cx))) .into_any_element() @@ -521,15 +512,17 @@ impl Yumush { fn rooms( &self, entity: &Entity, - palette: Palette, + t: Tokens, keep: impl Fn(&Community) -> bool, ) -> Vec { self.unread_first( self.chat + .session .communities .iter() .chain( self.chat + .session .opened .as_ref() .filter(|opened| opened.kind.is_group()) @@ -539,84 +532,50 @@ impl Yumush { .filter(|community| keep(community)), ) .into_iter() - .map(|community| self.room_entry(entity, community, palette)) + .map(|community| self.sidebar_community_row(entity, community, t)) .collect() } - fn room_entry( - &self, - entity: &Entity, - community: &Community, - palette: Palette, - ) -> AnyElement { - self.sidebar_community_row(entity, community, palette) - } - fn sidebar_community_row( &self, entity: &Entity, community: &Community, - palette: Palette, + t: Tokens, ) -> AnyElement { let active = self.chat.is_selected(community.id); let group = community.kind.is_group(); let can_leave = group && (!active || permission::can_leave(self.actor_rank())); - let can_manage = !active || permission::can_manage_community(self.actor_rank()); - let muted = self.chat.muted.contains(&community.id); - let unread = self.chat.unread.get(&community.id); + let can_manage = !active || permission::is_moderator(self.actor_rank()); + let muted = self.chat.session.muted.contains(&community.id); + let unread = self.chat.session.unread.get(&community.id); let community_id = community.id; let select = entity.clone(); - let pinned = self.chat.pinned.contains(&community.id); + let pinned = self.chat.session.pinned.contains(&community.id); let trailing = if self.chat.voice_ids(community_id).is_empty() { - unread_badge(palette, muted, unread).or_else(|| { + unread_badge(t, muted, unread).or_else(|| { pinned.then(|| { super::parts::small_icon(IconName::Pin) - .text_color(palette.muted) + .text_color(t.dim()) .into_any_element() }) }) } else { - Some(self.voice_chip(community_id, palette)) - }; - let face = match &community.kind { - CommunityKind::Direct { peer } => Some( - presence_avatar( - avatar( - palette, - peer, - px(size::AVATAR), - text(text::CAPTION), - &self.chat.avatars, - ), - self.presence_of(peer.id), - px(size::AVATAR), - palette, - ) - .into_any_element(), - ), - CommunityKind::Group => Some( - community_icon( - palette, - community, - px(size::AVATAR), - text(text::CAPTION), - &self.chat.avatars, - ) - .into_any_element(), - ), - CommunityKind::Notes => Some(notes_tile(palette)), + Some(self.voice_chip(community_id, t)) }; + let face = self + .community_badge(community, px(size::AVATAR), text(text::CAPTION), t) + .into_any_element(); let row = hoverable( format!("room_{}", community.id), room_row( - palette, + t, active, face, community_name(community).to_string(), trailing, ), - palette, + t, ) .on_click(move |_, window, cx| { select.update(cx, |yumush, cx| { @@ -638,40 +597,49 @@ impl Yumush { yumush, &menu, popover, - palette, + t, ) }, ) .into_any_element() } - fn requests(&self, entity: &Entity, palette: Palette) -> Option
{ - let friends = &self.chat.friends; + fn requests(&self, entity: &Entity, t: Tokens) -> Option
{ + let friends = &self.chat.session.friends; let rows: Vec = friends .incoming .iter() - .map(|user| self.incoming_row(entity, user, palette)) + .map(|user| self.incoming_row(entity, user, t)) .chain( friends .outgoing .iter() - .map(|user| self.outgoing_row(entity, user, palette)), + .map(|user| self.outgoing_row(entity, user, t)), ) .chain( self.chat + .session .invitations .iter() - .map(|invitation| self.invitation_row(entity, invitation, palette)), + .map(|invitation| self.invitation_row(entity, invitation, t)), ) .collect(); - group(w().sidebar.requests, palette, rows) + (!rows.is_empty()).then(|| { + div() + .flex() + .flex_col() + .gap(px(space::XXS)) + .child(super::parts::caption_head(w().sidebar.requests, t)) + .children(rows) + }) } fn unread_first<'a>(&self, rooms: impl Iterator) -> Vec<&'a Community> { let mut rooms: Vec<&Community> = rooms.collect(); rooms.sort_by_key(|community| { self.chat + .session .unread .get(&community.id) .map_or((true, true), |unread| { @@ -684,11 +652,13 @@ impl Yumush { pub(super) fn call_of(&self, user_id: Id) -> Option<&Community> { let community_id = self .chat + .session .voice .iter() .find(|(_, ids)| ids.contains(&user_id)) .map(|(community_id, _)| *community_id)?; self.chat + .session .communities .iter() .find(|community| community.id == community_id) @@ -704,7 +674,7 @@ impl Yumush { } } - fn found_row(&self, entity: &Entity, user: &User, palette: Palette) -> AnyElement { + fn found_row(&self, entity: &Entity, user: &User, t: Tokens) -> AnyElement { let relation = self.relation(user.id); let mut trailing = Vec::new(); @@ -713,7 +683,7 @@ impl Yumush { entity, "message", user.id, - palette, + t, IconName::MessageSquare, w().sidebar.message, |yumush, id, window, cx| { @@ -731,43 +701,42 @@ impl Yumush { entity, "friend_action", user.id, - palette, + t, icon, label, move |yumush, id, window, cx| yumush.friend_action(relation, id, window, cx), )); } - self.user_row(palette, user, trailing).into_any_element() + self.user_row(t, user, trailing).into_any_element() } fn user_row( &self, - palette: Palette, + t: Tokens, user: &User, trailing: impl IntoIterator, ) -> Div { entry( - palette, - false, + t, presence_avatar( avatar( - palette, + t, user, px(size::AVATAR), text(text::CAPTION), - &self.chat.avatars, + &self.chat.session.avatars, ), self.presence_of(user.id), px(size::AVATAR), - palette, + t, ), div().flex().flex_col().child(user.username.clone()).when( !user.status.is_empty(), |this| { this.child( div() - .text_color(palette.muted) + .text_color(t.dim()) .child(super::glyph::line( user.status.clone().into(), text(text::CAPTION), @@ -780,16 +749,16 @@ impl Yumush { ) } - fn incoming_row(&self, entity: &Entity, user: &User, palette: Palette) -> AnyElement { + fn incoming_row(&self, entity: &Entity, user: &User, t: Tokens) -> AnyElement { self.user_row( - palette, + t, user, [ row_button( entity, "accept_friend", user.id, - palette, + t, IconName::Check, w().sidebar.accept, |yumush, id, window, cx| yumush.accept_friend(id, window, cx), @@ -798,7 +767,7 @@ impl Yumush { entity, "decline_friend", user.id, - palette, + t, IconName::X, w().sidebar.decline, |yumush, id, window, cx| yumush.remove_friend(id, window, cx), @@ -808,15 +777,15 @@ impl Yumush { .into_any_element() } - fn outgoing_row(&self, entity: &Entity, user: &User, palette: Palette) -> AnyElement { + fn outgoing_row(&self, entity: &Entity, user: &User, t: Tokens) -> AnyElement { self.user_row( - palette, + t, user, [row_button( entity, "cancel_friend", user.id, - palette, + t, IconName::X, w().sidebar.cancel, |yumush, id, window, cx| yumush.remove_friend(id, window, cx), @@ -829,25 +798,24 @@ impl Yumush { &self, entity: &Entity, invitation: &Invitation, - palette: Palette, + t: Tokens, ) -> AnyElement { let community = &invitation.community; let label = div().flex().flex_col().child(community.name.clone()).child( div() .text_size(text(text::CAPTION)) - .text_color(palette.muted) + .text_color(t.dim()) .child(w().sidebar.from_user(&invitation.inviter.username)), ); entry( - palette, - false, + t, community_icon( - palette, + t, community, px(size::ICON), text(text::CAPTION), - &self.chat.avatars, + &self.chat.session.avatars, ), label, [ @@ -855,7 +823,7 @@ impl Yumush { entity, "accept_invitation", community.id, - palette, + t, IconName::Check, w().sidebar.accept, |yumush, id, window, cx| yumush.accept_invitation(id, window, cx), @@ -864,7 +832,7 @@ impl Yumush { entity, "decline_invitation", community.id, - palette, + t, IconName::X, w().sidebar.decline, |yumush, id, window, cx| yumush.decline_invitation(id, window, cx), @@ -874,7 +842,7 @@ impl Yumush { .into_any_element() } - fn account_row(&self, entity: &Entity, palette: Palette) -> Option { + fn account_row(&self, entity: &Entity, t: Tokens) -> Option { let user = self.user.as_ref()?; Some( div() @@ -882,8 +850,8 @@ impl Yumush { .flex() .items_center() .gap(px(space::XS)) - .child(self.account_trigger(entity, user, true, palette)) - .children((self.is_builder() && self.chat.ghost).then(|| { + .child(self.account_trigger(entity, user, true, t)) + .children((self.is_builder() && self.chat.session.ghost).then(|| { self.folding( "builder_fold", div().child( @@ -893,12 +861,12 @@ impl Yumush { w().sidebar.ghost_on, Tone::Idle, Scale::Small, - palette.tokens, + t, entity_action(entity, |yumush, window, cx| { yumush.show_view(View::Builder, window, cx) }), ) - .text_color(palette.tokens.hue(super::style::my_hue())), + .text_color(t.hue(super::style::my_hue())), ), fade, ) @@ -911,15 +879,15 @@ impl Yumush { entity: &Entity, user: &User, named: bool, - palette: Palette, + t: Tokens, ) -> impl IntoElement { let face = if named { size::AVATAR } else { size::CONTROL }; let picture = avatar( - palette, + t, user, px(face), text(text::CAPTION), - &self.chat.avatars, + &self.chat.session.avatars, ); let picture = if named { self.folding("avatar_face", picture, |picture, f| { @@ -928,7 +896,7 @@ impl Yumush { } else { picture.into_any_element() }; - let picture = presence_avatar(picture, self.presence_of(user.id), px(face), palette); + let picture = presence_avatar(picture, self.presence_of(user.id), px(face), t); let picture = if named { self.folding("avatar", picture, |picture, f| { picture @@ -963,13 +931,13 @@ impl Yumush { div() .min_w_0() .truncate() - .text_color(palette.muted) + .text_color(t.dim()) .child(user.username.clone()), fade, ), ) }), - palette, + t, ), ) .when(named, |trigger| trigger.flex_1().min_w_0()) @@ -991,8 +959,8 @@ pub(super) fn watch_pill( user_id: Id, kind: Kind, watching: bool, - audio: Option<&std::collections::VecDeque>, - palette: Palette, + audio: Option>, + t: Tokens, ) -> impl IntoElement { let icon = match kind { Kind::Camera => IconName::Video, @@ -1005,7 +973,7 @@ pub(super) fn watch_pill( }; clickable( format!("voice_watch_{user_id}_{kind:?}"), - palette, + t, entity_action(entity, move |yumush, window, cx| { yumush.toggle_viewer(user_id, kind, window, cx) }), @@ -1022,27 +990,19 @@ pub(super) fn watch_pill( .w(px(size::CONTROL)) .h(px(space::LG)) .child(super::parts::voice_line( - Some(audio), - super::parts::Voice::Live(palette.tokens.person(user_id)), - palette.tokens, + Some(&audio), + super::parts::Voice::Live(t.person(user_id)), + t, )) })) - .child(super::parts::small_icon(icon).text_color(if watching { - palette.text - } else { - palette.muted - })) + .child(super::parts::small_icon(icon).text_color(if watching { t.paper() } else { t.dim() })) } -pub(super) fn unread_badge( - palette: Palette, - muted: bool, - unread: Option<&Unread>, -) -> Option { +pub(super) fn unread_badge(t: Tokens, muted: bool, unread: Option<&Unread>) -> Option { if muted { return Some( div() - .text_color(palette.muted) + .text_color(t.dim()) .child(super::parts::small_icon(IconName::BellOff)) .into_any_element(), ); @@ -1053,7 +1013,7 @@ pub(super) fn unread_badge( div() .size(px(space::XS + space::XXS)) .rounded_full() - .bg(palette.text) + .bg(t.paper()) .into_any_element(), ); } @@ -1064,39 +1024,27 @@ pub(super) fn unread_badge( Some( div() .text_size(text(text::CAPTION)) - .text_color(palette.text) + .text_color(t.paper()) .child(count) .into_any_element(), ) } -fn matches_query(name: &str, query: &str) -> bool { - name.to_lowercase().contains(query) -} - -pub(super) fn input_box(input: &Entity, palette: Palette) -> Div { - compact_frame(palette) - .gap(px(space::SM)) - .text_color(palette.muted) - .child(super::parts::small_icon(IconName::Search)) - .child(bare_input( - palette, - Input::new(input).token(super::glyph::token), - )) -} - -fn group(title: &'static str, palette: Palette, rows: Vec) -> Option
{ - (!rows.is_empty()).then(|| { +pub(super) fn input_box(input: &Entity, t: Tokens) -> Div { + underline( + t, + size::CONTROL_SM + space::XS, div() .flex() - .flex_col() - .gap(px(space::XXS)) - .child(super::parts::caption_head(title, palette.tokens)) - .children(rows) - }) + .items_center() + .gap(px(space::SM)) + .text_color(t.dim()) + .child(super::parts::small_icon(IconName::Search)) + .child(bare_input(t, Input::new(input).token(super::glyph::token))), + ) } -fn notes_tile(palette: Palette) -> AnyElement { +fn notes_tile(t: Tokens) -> AnyElement { div() .size(px(size::AVATAR)) .flex_none() @@ -1104,15 +1052,15 @@ fn notes_tile(palette: Palette) -> AnyElement { .items_center() .justify_center() .rounded(px(radius::SM)) - .bg(palette.tokens.press()) - .child(super::parts::small_icon(IconName::Bookmark).text_color(palette.muted)) + .bg(t.press()) + .child(super::parts::small_icon(IconName::Bookmark).text_color(t.dim())) .into_any_element() } fn room_row( - palette: Palette, + t: Tokens, active: bool, - face: Option, + face: AnyElement, label: String, trailing: Option, ) -> Div { @@ -1123,16 +1071,15 @@ fn room_row( .flex() .items_center() .gap(px(space::SM)) - .text_color(if active { palette.text } else { palette.muted }) + .text_color(if active { t.paper() } else { t.dim() }) .when(active, |row| row.font_weight(FontWeight::MEDIUM)) - .children(face) + .child(face) .child(div().flex_1().min_w_0().truncate().child(label)) .children(trailing) } fn entry( - palette: Palette, - active: bool, + t: Tokens, leading: impl IntoElement, label: impl IntoElement, trailing: impl IntoIterator, @@ -1145,8 +1092,7 @@ fn entry( .items_center() .gap(px(space::SM)) .rounded(px(radius::MD)) - .text_color(if active { palette.text } else { palette.body }) - .when(active, |this| this.bg(palette.tokens.press())) + .text_color(t.paper()) .child(leading) .child(div().flex_1().min_w_0().truncate().child(label)) .children(trailing) @@ -1156,7 +1102,7 @@ fn row_button( entity: &Entity, key: &str, id: Id, - palette: Palette, + t: Tokens, icon: IconName, tip: &'static str, run: impl Fn(&mut Yumush, Id, &mut Window, &mut Context) + 'static, @@ -1167,7 +1113,7 @@ fn row_button( tip, Tone::Idle, Scale::Small, - palette.tokens, + t, entity_action(entity, move |yumush, window, cx| { run(yumush, id, window, cx) }), @@ -1190,8 +1136,8 @@ fn right_menu( .trigger(super::Trigger::new(trigger)) .content(move |_, _, cx| { let popover = cx.entity(); - let palette = super::palette(cx); - super::parts::popover(palette.tokens) + let t = Tokens::of(cx); + super::parts::popover(t) .w(px(size::SIDEBAR)) .p(px(space::XS)) .child(rows(&popover, cx)) @@ -1215,21 +1161,21 @@ const WANDER: std::time::Duration = std::time::Duration::from_secs(10); const LINGER: std::time::Duration = std::time::Duration::from_secs(6); const TOW: std::time::Duration = std::time::Duration::from_millis(2300); -fn lerp(from: f32, to: f32, f: f32) -> f32 { - from + (to - from) * f -} - fn fade(element: E, f: f32) -> E { let shown = 1. - f; element.opacity(shown) } -fn logo_mark(palette: Palette) -> gpui_kit::Svg { +fn lerp(from: f32, to: f32, f: f32) -> f32 { + from + (to - from) * f +} + +fn logo_mark(t: Tokens) -> gpui_kit::Svg { gpui_kit::svg() .path(crate::logo::PATH) .size(px(size::CHIP)) .flex_none() - .text_color(palette.text) + .text_color(t.paper()) } pub(super) fn wander(cx: &mut Context) { @@ -1254,7 +1200,7 @@ fn towing(flipped: Option) -> bool { flipped.is_some_and(|at| at.elapsed() < TOW) } -fn wordmark_tail(flips: u32, flipped: Option, palette: Palette) -> AnyElement { +fn wordmark_tail(flips: u32, flipped: Option, t: Tokens) -> AnyElement { let turkish = flips % 2 == 1; let em = super::style::text::TITLE / super::style::text::UI; if !towing(flipped) { @@ -1271,7 +1217,7 @@ fn wordmark_tail(flips: u32, flipped: Option, palette: Palet } .into_any_element(); } - let (ink, ground) = (palette.text, palette.panel); + let (ink, ground) = (t.paper(), t.ground()); div() .relative() .child("s") diff --git a/crates/client/src/gui/snippet.rs b/crates/client/src/gui/snippet.rs index 9e2ef07..f4f1000 100644 --- a/crates/client/src/gui/snippet.rs +++ b/crates/client/src/gui/snippet.rs @@ -1,4 +1,4 @@ -use super::style::{size, space, text}; +use super::style::{Tokens, size, space, text}; use crate::lang::w; use common::model::{Message, Role, SnippetMessage, User}; use gpui_kit::{ @@ -7,8 +7,7 @@ use gpui_kit::{ }; use super::{ - Palette, Yumush, avatar, chat::Chat, media_view, millis_time, poll, profile::user_link, - widget::panel, + Yumush, avatar, chat::Chat, media_view, millis_time, parts::surface, poll, profile::user_link, }; pub fn snippet_card( @@ -16,7 +15,7 @@ pub fn snippet_card( clock: &'static str, chat: &Chat, entity: &Entity, - palette: Palette, + t: Tokens, ) -> Option { let snippet = message.snippet.as_ref()?; let header = match &snippet.origin { @@ -25,7 +24,7 @@ pub fn snippet_card( }; Some( - panel(palette) + surface(t) .flex() .flex_col() .gap(px(space::MD)) @@ -33,14 +32,14 @@ pub fn snippet_card( .child( div() .text_size(super::text(text::CAPTION)) - .text_color(palette.muted) + .text_color(t.dim()) .child(header), ) .children( snippet .messages .iter() - .map(|item| snippet_row(item, clock, chat, entity, palette)), + .map(|item| snippet_row(item, clock, chat, entity, t)), ), ) } @@ -50,7 +49,7 @@ fn snippet_row( clock: &'static str, chat: &Chat, entity: &Entity, - palette: Palette, + t: Tokens, ) -> impl IntoElement { let user = chat.author(item.user_id).cloned().unwrap_or_else(|| User { id: item.user_id, @@ -70,11 +69,11 @@ fn snippet_row( Some(&user), entity, avatar( - palette, + t, &user, px(size::AVATAR), super::text(text::CAPTION), - &chat.avatars, + &chat.session.avatars, ), )) .child( @@ -95,13 +94,13 @@ fn snippet_row( entity, div() .font_weight(FontWeight::SEMIBOLD) - .text_color(palette.tinted(item.user_id)) + .text_color(t.person(item.user_id)) .child(item.username.clone()), )) .child( div() .text_size(super::text(text::CAPTION)) - .text_color(palette.muted) + .text_color(t.dim()) .child(millis_time(item.created_at, clock)), ), ) @@ -109,7 +108,7 @@ fn snippet_row( this.child( div() .line_height(relative(1.5)) - .text_color(palette.body) + .text_color(t.paper()) .child(super::glyph::wrapped( item.body.clone().into(), super::text(super::style::text::UI), @@ -118,9 +117,9 @@ fn snippet_row( }) .children(media_view::attachments( &item.attachments, - &chat.media, + &chat.session.media, entity, - palette, + t, )) .children(item.poll.as_ref().map(|poll| { poll::poll_card( @@ -129,7 +128,7 @@ fn snippet_row( None, chat, entity, - palette, + t, ) })), ) diff --git a/crates/client/src/gui/social.rs b/crates/client/src/gui/social.rs index f698d2e..fd6e04a 100644 --- a/crates/client/src/gui/social.rs +++ b/crates/client/src/gui/social.rs @@ -22,8 +22,8 @@ use gpui_kit::{ }; use super::{ - Palette, Yumush, avatar, new_input, notify_error, parts, - style::{size, space}, + Yumush, avatar, new_input, notify_error, parts, + style::{Tokens, size, space}, text, widget::{search_text, spawn_done}, }; @@ -61,12 +61,17 @@ impl Relation { fn spawn_community( window: &mut Window, cx: &mut Context, + join_voice: bool, call: impl Future> + 'static, ) { cx.spawn_in(window, async move |this, cx| match call.await { Ok(community) => { let _ = this.update_in(cx, |yumush, window, cx| { + let community_id = community.id; yumush.enter_community(community, window, cx); + if join_voice && !yumush.chat.in_voice(community_id) { + yumush.toggle_voice(community_id, window, cx); + } }); } Err(error) => notify_error(&this, cx, error), @@ -76,7 +81,7 @@ fn spawn_community( impl Yumush { pub(super) fn relation(&self, user_id: Id) -> Relation { - let friends = &self.chat.friends; + let friends = &self.chat.session.friends; if self.is_me(user_id) { Relation::Myself @@ -94,25 +99,27 @@ impl Yumush { pub(super) fn request_social_avatars(&mut self, cx: &mut Context) { let chat = &self.chat; let users = chat + .session .friends .friends .iter() - .chain(&chat.friends.incoming) - .chain(&chat.friends.outgoing) + .chain(&chat.session.friends.incoming) + .chain(&chat.session.friends.outgoing) .chain( - chat.invitations + chat.session + .invitations .iter() .map(|invitation| &invitation.inviter), ) .chain( - chat.communities + chat.communities() .iter() .filter_map(|community| community.kind.peer()), ); let avatar_ids: Vec = users .filter_map(|user| user.avatar_id) .chain( - chat.communities + chat.communities() .iter() .filter_map(|community| community.avatar_id), ) @@ -148,9 +155,9 @@ impl Yumush { .chain(&friends.outgoing) .collect::>(), ); - yumush.chat.friends = friends; - yumush.chat.invitations = invitations; - yumush.chat.presences = presences.into_iter().collect(); + yumush.chat.session.friends = friends; + yumush.chat.session.invitations = invitations; + yumush.chat.session.presences = presences.into_iter().collect(); yumush.request_social_avatars(cx); cx.notify(); }); @@ -159,7 +166,7 @@ impl Yumush { } pub(super) fn search_user(&mut self, window: &mut Window, cx: &mut Context) { - self.chat.found = None; + self.chat.session.found = None; cx.notify(); let username = search_text(&self.chat.search_input, cx); if validate_username(&username).is_err() { @@ -181,7 +188,7 @@ impl Yumush { if let Some(user) = &found { yumush.request_user_avatar(user, cx); } - yumush.chat.found = found; + yumush.chat.session.found = found; cx.notify(); }); }) @@ -189,9 +196,15 @@ impl Yumush { } pub(super) fn open_found(&mut self, window: &mut Window, cx: &mut Context) { - if let Some(user) = &self.chat.found { - self.chat.friends_open = false; - self.open_direct(user.id, window, cx); + let Some(user) = &self.chat.session.found else { + return; + }; + let user_id = user.id; + self.close_friends(window, cx); + if self.relation(user_id) == Relation::Myself { + self.open_notes(window, cx); + } else { + self.open_direct(user_id, window, cx); } } @@ -203,34 +216,28 @@ impl Yumush { } let network = self.network.clone(); - spawn_community(window, cx, async move { network.call(OpenNotes).await }); + spawn_community( + window, + cx, + false, + async move { network.call(OpenNotes).await }, + ); } pub(super) fn open_direct(&self, user_id: Id, window: &mut Window, cx: &mut Context) { let network = self.network.clone(); - spawn_community(window, cx, async move { + spawn_community(window, cx, false, async move { network.call(OpenDirect { user_id }).await }); } pub(super) fn call_direct(&self, user_id: Id, window: &mut Window, cx: &mut Context) { let network = self.network.clone(); - cx.spawn_in(window, async move |this, cx| { - match network.call(OpenDirect { user_id }).await { - Ok(community) => { - let _ = this.update_in(cx, |yumush, window, cx| { - let community_id = community.id; - yumush.enter_community(community, window, cx); - if !yumush.chat.in_voice(community_id) { - yumush.toggle_voice(community_id, window, cx); - } - }); - } - Err(error) => notify_error(&this, cx, error), - } - }) - .detach(); + + spawn_community(window, cx, true, async move { + network.call(OpenDirect { user_id }).await + }); } pub(super) fn friend_action( @@ -280,7 +287,7 @@ impl Yumush { ) { let network = self.network.clone(); - spawn_community(window, cx, async move { + spawn_community(window, cx, false, async move { network.call(AcceptInvitation { community_id }).await }); } @@ -304,17 +311,15 @@ impl Yumush { window: &mut Window, cx: &mut Context, ) { - self.chat.invite = InviteLookup::Idle; + self.chat.session.invite = InviteLookup::Idle; let input = new_input(w().social.username_placeholder, window, cx); - let enter_id = community_id; - let lookup_id = community_id; cx.subscribe_in( &input, window, move |this, input, event, window, cx| match event { - InputEvent::Change => this.lookup_invite(lookup_id, input, window, cx), - InputEvent::PressEnter { .. } => this.send_invite(enter_id, window, cx), + InputEvent::Change => this.lookup_invite(community_id, input, window, cx), + InputEvent::PressEnter { .. } => this.send_invite(community_id, window, cx), _ => {} }, ) @@ -324,15 +329,21 @@ impl Yumush { let dialog_input = input.clone(); window.open_dialog(cx, move |dialog, _, cx| { let yumush = entity.read(cx); - let palette = super::palette(cx); - let result = invite_result(&yumush.chat.invite, community_id, &entity, yumush, palette); + let t = Tokens::of(cx); + let result = invite_result( + &yumush.chat.session.invite, + community_id, + &entity, + yumush, + t, + ); dialog.title(w().social.invite).child( div() .flex() .flex_col() .gap(px(space::MD)) - .child(super::sidebar::input_box(&dialog_input, palette)) + .child(super::sidebar::input_box(&dialog_input, t)) .children(result), ) }); @@ -349,7 +360,7 @@ impl Yumush { cx: &mut Context, ) { let username = search_text(input, cx); - self.chat.invite = InviteLookup::Idle; + self.chat.session.invite = InviteLookup::Idle; window.refresh(); if validate_username(&username).is_err() { return; @@ -384,7 +395,7 @@ impl Yumush { if let InviteLookup::Found(user) | InviteLookup::Member(user) = &lookup { yumush.request_user_avatar(user, cx); } - yumush.chat.invite = lookup; + yumush.chat.session.invite = lookup; window.refresh(); }); }) @@ -392,7 +403,7 @@ impl Yumush { } fn send_invite(&self, community_id: Id, window: &mut Window, cx: &mut Context) { - let InviteLookup::Found(user) = &self.chat.invite else { + let InviteLookup::Found(user) = &self.chat.session.invite else { return; }; let network = self.network.clone(); @@ -421,23 +432,23 @@ fn invite_result( community_id: Id, entity: &Entity, yumush: &Yumush, - palette: Palette, + t: Tokens, ) -> Option { match lookup { InviteLookup::Idle => None, InviteLookup::Missing => Some( div() .text_size(text(super::style::text::LABEL)) - .text_color(palette.muted) + .text_color(t.dim()) .child(w().social.no_such_user) .into_any_element(), ), InviteLookup::Member(user) => Some( - user_row(user, yumush, palette) + user_row(user, yumush, t) .child( div() .text_size(text(super::style::text::LABEL)) - .text_color(palette.muted) + .text_color(t.dim()) .child(Rank::Member.label()), ) .into_any_element(), @@ -446,12 +457,12 @@ fn invite_result( let entity = entity.clone(); Some( - user_row(user, yumush, palette) + user_row(user, yumush, t) .child(parts::button( "invite_send", w().social.invite, parts::Press::Primary, - palette.tokens, + t, move |window, cx| { entity.update(cx, |yumush, cx| { yumush.send_invite(community_id, window, cx) @@ -464,17 +475,17 @@ fn invite_result( } } -fn user_row(user: &User, yumush: &Yumush, palette: Palette) -> Div { +fn user_row(user: &User, yumush: &Yumush, t: Tokens) -> Div { div() .flex() .items_center() .gap(px(space::MD)) .child(avatar( - palette, + t, user, px(size::AVATAR), text(super::style::text::UI), - &yumush.chat.avatars, + &yumush.chat.session.avatars, )) .child( div() diff --git a/crates/client/src/gui/stream_stats.rs b/crates/client/src/gui/stream_stats.rs index 1e7c155..5a7c553 100644 --- a/crates/client/src/gui/stream_stats.rs +++ b/crates/client/src/gui/stream_stats.rs @@ -3,18 +3,17 @@ use common::{model::Id, share::Kind}; use gpui_kit::{Div, FontWeight, ParentElement, Styled, div, px}; use super::{ - Palette, Yumush, + Yumush, parts::{Ink, Text, band, chart, popover, words}, - style::{size, space}, - voice_stats::{ - GOOD_LOSS, SAMPLE_HISTORY, engine_label, kind_word, number, resolution_text, stamp, - }, + style::{Tokens, size, space}, + voice_stats::{GOOD_LOSS, SAMPLE_HISTORY, kind_word, number, stamp, stream_detail}, }; -use crate::share::session::WatchStats; +use common::stats::WatchStats; pub(super) fn watch_stats(yumush: &Yumush, user_id: Id, kind: Kind) -> Option<&WatchStats> { yumush .chat + .session .stats .share .watching @@ -23,8 +22,7 @@ pub(super) fn watch_stats(yumush: &Yumush, user_id: Id, kind: Kind) -> Option<&W .map(|(_, _, stats)| stats) } -pub(super) fn stream_card(yumush: &Yumush, user_id: Id, kind: Kind, palette: Palette) -> Div { - let t = palette.tokens; +pub(super) fn stream_card(yumush: &Yumush, user_id: Id, kind: Kind, t: Tokens) -> Div { let name = yumush .chat .author(user_id) @@ -32,6 +30,7 @@ pub(super) fn stream_card(yumush: &Yumush, user_id: Id, kind: Kind, palette: Pal let stats = watch_stats(yumush, user_id, kind); let losses: Vec<(u64, f32)> = yumush .chat + .session .share_loss .get(&(user_id, kind)) .into_iter() @@ -44,19 +43,7 @@ pub(super) fn stream_card(yumush: &Yumush, user_id: Id, kind: Kind, palette: Pal let loss = stats.map(|stats| stats.loss * 100.); let bad = loss.is_some_and(|loss| loss > GOOD_LOSS); let field = |value: Option| value.unwrap_or_else(|| "…".into()); - let detail = stats.map_or("…".to_string(), |stats| { - let layer = stats.layer.map_or("…".to_string(), |layer| { - format!( - "{} · {}", - resolution_text(layer, stats.fps), - layer.codec.name() - ) - }); - match stats.engine { - Some(engine) => format!("{layer} · {}", engine_label(engine)), - None => layer, - } - }); + let detail = stats.map_or("…".to_string(), stream_detail); popover(t) .w(px(size::POPOVER)) diff --git a/crates/client/src/gui/style.rs b/crates/client/src/gui/style.rs index 0b28f36..68d1192 100644 --- a/crates/client/src/gui/style.rs +++ b/crates/client/src/gui/style.rs @@ -1,4 +1,7 @@ -use std::{cell::RefCell, collections::HashMap}; +use std::{ + cell::{Cell, RefCell}, + collections::HashMap, +}; use common::model::{Hue, Id, User}; use gpui_kit::{App, Global, Hsla, Rems, rems, rgb}; @@ -16,31 +19,26 @@ impl Theme { } } -pub struct Look { - pub theme: Theme, - pub size: FontSize, -} - -impl Global for Look {} - #[derive(Clone, Copy)] pub struct Tokens { pub theme: Theme, pub size: FontSize, } +impl Default for Tokens { + fn default() -> Self { + Tokens { + theme: Theme::Gece, + size: FontSize::Medium, + } + } +} + +impl Global for Tokens {} + impl Tokens { pub fn of(cx: &App) -> Self { - cx.try_global::().map_or( - Tokens { - theme: Theme::Gece, - size: FontSize::Medium, - }, - |look| Tokens { - theme: look.theme, - size: look.size, - }, - ) + cx.try_global::().copied().unwrap_or_default() } fn colors(self) -> &'static Colors { @@ -122,7 +120,7 @@ thread_local! { static CHOSEN: RefCell> = RefCell::default(); static AVATAR: RefCell> = RefCell::default(); static PICTURED: RefCell> = RefCell::default(); - static ME: std::cell::Cell> = const { std::cell::Cell::new(None) }; + static ME: Cell> = const { Cell::new(None) }; } pub fn remember_me(id: Id) { @@ -231,7 +229,6 @@ mod tests { assert_eq!(names, HUE_NAMES); } - const UNMIGRATED: [&str; 0] = []; const FREE: [&str; 2] = ["gui/style.rs", "gui/parts.rs"]; fn sources(dir: &std::path::Path, out: &mut Vec) { @@ -279,7 +276,7 @@ mod tests { .expect("under src") .to_string_lossy() .replace('\\', "/"); - if FREE.contains(&name.as_str()) || UNMIGRATED.contains(&name.as_str()) { + if FREE.contains(&name.as_str()) { continue; } let content = std::fs::read_to_string(&file).expect("read source"); diff --git a/crates/client/src/gui/tow.rs b/crates/client/src/gui/tow.rs index 9943ad5..ceaf19e 100644 --- a/crates/client/src/gui/tow.rs +++ b/crates/client/src/gui/tow.rs @@ -110,6 +110,13 @@ pub fn scene(rig: &Rig, progress: f32, turkish: bool, time: f32) -> Scene { } } +#[derive(PartialEq)] +enum Stage { + Reach, + Pull, + Return, +} + struct Beat { out: f32, back: f32, @@ -117,14 +124,20 @@ struct Beat { lift: f32, settle: f32, ahead: f32, - pulling: bool, - reaching: bool, + stage: Stage, } impl Beat { fn new(progress: f32) -> Self { let v = ease(0., 1., progress); let pull = clamp(0.32, 0.78, v); + let stage = if v < 0.32 { + Stage::Reach + } else if v < 0.78 { + Stage::Pull + } else { + Stage::Return + }; Beat { out: ease(0., 0.3, v), back: ease(0.78, 1., v), @@ -132,13 +145,12 @@ impl Beat { lift: heave(0.18, 0.82, pull), settle: clamp(0.82, 1., pull), ahead: heave(0.18, 0.82, pull + 0.02).min(1.), - pulling: (0.32..0.78).contains(&v), - reaching: v < 0.32, + stage, } } fn amp(&self, grown: f32) -> f32 { - if self.pulling { + if self.stage == Stage::Pull { 45. * (1. - self.slack) } else { 80. * (PI * grown).sin() @@ -150,37 +162,34 @@ impl Beat { } } +fn pull_speed(beat: &Beat, anchor: Point, path: impl Fn(f32) -> Point) -> f32 { + if beat.stage == Stage::Pull { + (path(beat.ahead)[0] - anchor[0]) / 0.02 / 3000. + } else { + 0. + } +} + fn over(rig: &Rig, beat: &Beat, time: f32) -> (Vec, Vec, Vec) { let top = [H_X + STEM, H_TOP]; let grab = [S_X + 380., 140.]; let load = |t: f32| cubic(&[grab, [H_X + 54., 150.], [H_X + STEM, -200.], top], t); let bounce = 0.06 * (beat.settle * PI * 2.).sin() * (1. - beat.settle); - let t = if beat.reaching { - 0. - } else if beat.pulling { - if beat.settle > 0. { - 1. - bounce - } else { - beat.lift - } - } else { - 1. + let t = match beat.stage { + Stage::Reach => 0., + Stage::Pull if beat.settle > 0. => 1. - bounce, + Stage::Pull => beat.lift, + Stage::Return => 1., }; let anchor = load(t); - let speed = if beat.pulling { - (load(beat.ahead)[0] - anchor[0]) / 0.02 / 3000. - } else { - 0. - }; - let (curl, grown) = if beat.reaching { - (ease(0., 0.45, beat.out), ease(0.35, 1., beat.out)) - } else if beat.pulling { - (1., 1.) - } else { - ( + let speed = pull_speed(beat, anchor, load); + let (curl, grown) = match beat.stage { + Stage::Reach => (ease(0., 0.45, beat.out), ease(0.35, 1., beat.out)), + Stage::Pull => (1., 1.), + Stage::Return => ( 1. - ease(0.55, 1., beat.back), 1. - ease(0., 0.6, beat.back), - ) + ), }; let [first, low] = rig.strand(); let looped = [ @@ -222,29 +231,21 @@ fn under(rig: &Rig, beat: &Beat, time: f32) -> (Vec, Vec, Vec 0., + Stage::Pull => beat.lift, + Stage::Return => 1., }; let anchor = drop(t); - let speed = if beat.pulling { - (drop(beat.ahead)[0] - anchor[0]) / 0.02 / 3000. - } else { - 0. - }; + let speed = pull_speed(beat, anchor, drop); let mut segments = rig.strand().to_vec(); segments.extend(rig.below(anchor)); let route = Route::new(&segments); let rest = route.marks[1]; - let grown = if beat.reaching { - beat.out - } else if beat.pulling { - 1. - } else { - 1. - beat.back + let grown = match beat.stage { + Stage::Reach => beat.out, + Stage::Pull => 1., + Stage::Return => 1. - beat.back, }; let thread = route.wave( rest + (route.end() - rest) * grown, diff --git a/crates/client/src/gui/update_view.rs b/crates/client/src/gui/update_view.rs index eba6b95..d08dda2 100644 --- a/crates/client/src/gui/update_view.rs +++ b/crates/client/src/gui/update_view.rs @@ -3,8 +3,8 @@ use crate::update::Phase; use gpui_kit::{AnyElement, IntoElement, ParentElement, Styled, div, px}; use super::{ - Palette, Yumush, parts, - style::{size, space, text}, + Yumush, parts, + style::{Tokens, size, space, text}, }; fn percent(fraction: f32) -> String { @@ -21,16 +21,15 @@ fn status(phase: Phase) -> &'static str { } impl Yumush { - pub(super) fn update_control(&self, palette: Palette) -> Option { + pub(super) fn update_control(&self, t: Tokens) -> Option { if self.update.required() { return None; } - let t = palette.tokens; - let (label, restart) = match self.update { + let (label, action): (&str, fn()) = match self.update { Phase::Idle => return None, - Phase::Available(_) => (w().update.update, false), - Phase::Ready(_) => (w().update.restart, true), - Phase::Failed(_) => (w().update.retry, false), + Phase::Available(_) => (w().update.update, crate::update::install), + Phase::Ready(_) => (w().update.restart, crate::update::restart), + Phase::Failed(_) => (w().update.retry, crate::update::install), Phase::Downloading { .. } | Phase::Installing { .. } => { let fraction = self.update.progress().unwrap_or_default(); return Some( @@ -43,7 +42,7 @@ impl Yumush { .flex() .justify_between() .text_size(t.text(text::CAPTION)) - .text_color(palette.muted) + .text_color(t.dim()) .child(status(self.update)) .child(percent(fraction)), ) @@ -58,20 +57,13 @@ impl Yumush { label, parts::Press::Plain, t, - move |_, _| { - if restart { - crate::update::restart(); - } else { - crate::update::install(); - } - }, + move |_, _| action(), ) .into_any_element(), ) } - pub(super) fn update_required(&self, palette: Palette) -> impl IntoElement { - let t = palette.tokens; + pub(super) fn update_required(&self, t: Tokens) -> impl IntoElement { let status = status(self.update); let label = match self.update.progress() { Some(fraction) => format!("{status} {}", percent(fraction)), diff --git a/crates/client/src/gui/voice_note.rs b/crates/client/src/gui/voice_note.rs index 4484dc7..9b864ac 100644 --- a/crates/client/src/gui/voice_note.rs +++ b/crates/client/src/gui/voice_note.rs @@ -12,17 +12,19 @@ use gpui_kit::{ Task, Window, assets::IconName, component::{Icon, WindowExt, notification::Notification}, - div, px, + div, + prelude::FluentBuilder as _, + px, }; use rtrb::{Consumer, RingBuffer}; use super::{ - Palette, Tooltip as _, Yumush, + Tooltip as _, Yumush, chat::VoiceState, clickable, - media_view::{time_text, upload_file}, + media_view::time_text, notify_error, parts, - style::{self, radius, size, space}, + style::{self, Tokens, radius, size, space}, text, widget::ok_or_notify, }; @@ -68,7 +70,8 @@ fn drain(consumer: &mut Consumer, samples: &mut Vec) { pub fn bars( levels: &[f32], progress: f32, - palette: Palette, + t: Tokens, + scrub: bool, on_pick: impl Fn(usize, &mut Window, &mut App) + 'static, ) -> Div { let on_pick = Rc::new(on_pick); @@ -85,9 +88,9 @@ pub fn bars( .copied() .unwrap_or(0.); let color = if (index as f32) < progress * BARS as f32 { - palette.accent + t.paper() } else { - palette.muted + t.dim() }; let (down, drag) = (on_pick.clone(), on_pick.clone()); div() @@ -99,10 +102,12 @@ pub fn bars( .on_mouse_down(MouseButton::Left, move |_, window, cx| { down(index, window, cx) }) - .on_mouse_move(move |event, window, cx| { - if event.pressed_button == Some(MouseButton::Left) { - drag(index, window, cx); - } + .when(scrub, |slot| { + slot.on_mouse_move(move |event, window, cx| { + if event.pressed_button == Some(MouseButton::Left) { + drag(index, window, cx); + } + }) }) .child( div() @@ -118,7 +123,7 @@ pub fn recording_row( started: Instant, levels: &[f32], entity: &Entity, - palette: Palette, + t: Tokens, ) -> impl IntoElement { let cancel = entity.clone(); let send = entity.clone(); @@ -132,9 +137,9 @@ pub fn recording_row( .items_center() .gap(px(space::SM)) .rounded(px(radius::MD)) - .bg(palette.field) + .bg(t.raise()) .child( - clickable("cancel_voice_note", palette, move |_, cx| { + clickable("cancel_voice_note", t, move |_, cx| { cancel.update(cx, |yumush, cx| yumush.cancel_voice_note(cx)) }) .tip(w().voice_note.cancel) @@ -143,7 +148,7 @@ pub fn recording_row( .items_center() .justify_center() .rounded(px(radius::MD)) - .text_color(palette.muted) + .text_color(t.dim()) .child(Icon::new(IconName::X).size(px(size::ICON))), ) .child( @@ -153,17 +158,17 @@ pub fn recording_row( .items_center() .gap(px(space::SM)) .text_size(text(style::text::LABEL)) - .text_color(palette.text) + .text_color(t.paper()) .child(super::parts::small_icon(IconName::Mic)) .child(time_text( started .elapsed() .min(Duration::from_secs(MAX_SECONDS as u64)), )) - .child(bars(levels, 1., palette, |_, _, _| {})), + .child(bars(levels, 1., t, false, |_, _, _| {})), ) .child( - parts::pill("send_voice_note", palette.tokens, move |window, cx| { + parts::pill("send_voice_note", t, move |window, cx| { send.update(cx, |yumush, cx| yumush.send_voice_note(window, cx)) }) .tip(w().voice_note.send) @@ -173,10 +178,10 @@ pub fn recording_row( ) } -pub fn mic_button(entity: &Entity, palette: Palette) -> impl IntoElement { +pub fn mic_button(entity: &Entity, t: Tokens) -> impl IntoElement { let entity = entity.clone(); - clickable("voice_note_button", palette, move |window, cx| { + clickable("voice_note_button", t, move |window, cx| { entity.update(cx, |yumush, cx| yumush.start_voice_note(window, cx)) }) .tip(w().voice_note.voice_message) @@ -185,13 +190,13 @@ pub fn mic_button(entity: &Entity, palette: Palette) -> impl IntoElement .items_center() .justify_center() .rounded(px(radius::MD)) - .text_color(palette.muted) + .text_color(t.dim()) .child(Icon::new(IconName::Mic).size(px(size::ICON))) } impl Yumush { fn start_voice_note(&mut self, window: &mut Window, cx: &mut Context) { - if !matches!(self.chat.voice_state, VoiceState::Off) { + if !matches!(self.chat.session.voice_state, VoiceState::Off) { window.push_notification(Notification::error(w().voice_note.leave_call_first), cx); return; } @@ -211,7 +216,7 @@ impl Yumush { } } }); - self.chat.media.voice_note = VoiceNote::Recording { + self.chat.session.media.voice_note = VoiceNote::Recording { started: Instant::now(), _audio: audio, consumer, @@ -223,12 +228,15 @@ impl Yumush { } fn tick_voice_note(&mut self, cx: &mut Context) { + if !matches!(self.chat.session.voice_state, VoiceState::Off) { + self.chat.session.media.voice_note = VoiceNote::Idle; + } if let VoiceNote::Recording { consumer, samples, levels, .. - } = &mut self.chat.media.voice_note + } = &mut self.chat.session.media.voice_note { let start = samples.len(); drain(consumer, samples); @@ -241,7 +249,7 @@ impl Yumush { } fn cancel_voice_note(&mut self, cx: &mut Context) { - self.chat.media.voice_note = VoiceNote::Idle; + self.chat.session.media.voice_note = VoiceNote::Idle; cx.notify(); } @@ -250,19 +258,15 @@ impl Yumush { mut consumer, mut samples, .. - } = std::mem::take(&mut self.chat.media.voice_note) + } = std::mem::take(&mut self.chat.session.media.voice_note) else { return; }; drain(&mut consumer, &mut samples); - let Some(community_id) = self.chat.selected_community_id else { + let Some(community_id) = self.chat.session.selected_community_id else { return; }; let network = self.network.clone(); - let maximum = self - .server - .as_ref() - .map(|settings| settings.max_attachment_bytes); cx.notify(); let order = self.send_order.clone(); @@ -274,8 +278,12 @@ impl Yumush { else { return; }; - let uploaded = - upload_file(&this, &network, community_id, path.clone(), maximum, cx).await; + let Ok(upload) = this.update(cx, |yumush, cx| { + yumush.upload(community_id, path.clone(), cx) + }) else { + return; + }; + let uploaded = upload.await; let _ = std::fs::remove_file(&path); let attachment = match uploaded { Ok(attachment) => attachment, diff --git a/crates/client/src/gui/voice_settings.rs b/crates/client/src/gui/voice_settings.rs index 3434449..2214821 100644 --- a/crates/client/src/gui/voice_settings.rs +++ b/crates/client/src/gui/voice_settings.rs @@ -1,33 +1,34 @@ use std::time::Duration; use gpui_kit::{ - Anchor, App, AppContext, Context, Div, Entity, InteractiveElement, IntoElement, KeyDownEvent, - KeyUpEvent, Keystroke, ModifiersChangedEvent, MouseButton, ParentElement, SharedString, - Stateful, Styled, Subscription, Task, Window, + Anchor, AnyElement, App, AppContext, Context, Div, Entity, InteractiveElement, IntoElement, + KeyDownEvent, KeyUpEvent, Keystroke, ModifiersChangedEvent, MouseButton, ParentElement, + SharedString, Stateful, Styled, Subscription, Task, Window, assets::IconName, component::{ - IndexPath, kbd::Kbd, popover::Popover, - searchable_list::{SearchableListItem, SearchableVec}, - select::{Select, SelectEvent, SelectState}, slider::{SliderEvent, SliderState}, }, div, px, relative, }; use super::{ - Palette, Tooltip as _, Trigger, Yumush, clickable, + Tooltip as _, Trigger, Yumush, clickable, settings_page::{row, segmented}, - style::{radius, size, space}, + style::{Tokens, radius, size, space}, }; use crate::{ lang::w, settings::{Activation, Profile, SENSITIVITY_DB, VOLUME, VoiceSettings}, - voice::audio::{self, Device, Devices}, + voice::{ + self, Sound, + audio::{self, Device, Devices}, + }, }; const LEVEL_INTERVAL: Duration = Duration::from_millis(50); + pub(super) fn modes() -> [(Activation, &'static str); 2] { [ (Activation::VoiceActivity, w().voice_settings.voice_activity), @@ -52,7 +53,6 @@ pub(super) enum Side { pub(super) enum MicTest { Off, On, - MutingCall, } #[derive(Clone, Copy, PartialEq, Eq)] @@ -76,28 +76,12 @@ impl DeviceItem { } } -impl SearchableListItem for DeviceItem { - type Value = Option; - - fn title(&self) -> SharedString { - self.name.clone() - } - - fn value(&self) -> &Option { - &self.id - } -} - -type DeviceList = SearchableVec; - pub(super) struct VoiceControls { - pub(super) inputs: Entity>, - pub(super) outputs: Entity>, pub(super) sensitivity: Entity, pub(super) input_volume: Entity, pub(super) output_volume: Entity, - pub(super) input_items: Vec, - pub(super) output_items: Vec, + pub(super) inputs: Vec, + pub(super) outputs: Vec, pub(super) mic_test: MicTest, pub(super) key: KeyCapture, level_poll: Option>, @@ -105,28 +89,12 @@ pub(super) struct VoiceControls { } impl VoiceControls { - pub(super) fn new( - settings: &VoiceSettings, - window: &mut Window, - cx: &mut Context, - ) -> Self { - let inputs = device_select(window, cx); - let outputs = device_select(window, cx); + pub(super) fn new(settings: &VoiceSettings, cx: &mut Context) -> Self { let sensitivity = slider(&SENSITIVITY_DB, settings.sensitivity_db, cx); let input_volume = slider(&VOLUME, settings.input_volume, cx); let output_volume = slider(&VOLUME, settings.output_volume, cx); let subscriptions = vec![ - cx.subscribe(&inputs, |this, _, event: &SelectEvent, cx| { - if let SelectEvent::Confirm(Some(id)) = event { - this.set_voice_device(Side::Input, id.clone(), cx); - } - }), - cx.subscribe(&outputs, |this, _, event: &SelectEvent, cx| { - if let SelectEvent::Confirm(Some(id)) = event { - this.set_voice_device(Side::Output, id.clone(), cx); - } - }), cx.subscribe(&sensitivity, |this, _, event: &SliderEvent, cx| { this.slider_changed(event, |voice, value| voice.sensitivity_db = value, cx); }), @@ -139,13 +107,11 @@ impl VoiceControls { ]; Self { - inputs, - outputs, sensitivity, input_volume, output_volume, - input_items: vec![DeviceItem::default_choice()], - output_items: vec![DeviceItem::default_choice()], + inputs: vec![DeviceItem::default_choice()], + outputs: vec![DeviceItem::default_choice()], mic_test: MicTest::Off, key: KeyCapture::Idle, level_poll: None, @@ -154,17 +120,6 @@ impl VoiceControls { } } -fn device_select(window: &mut Window, cx: &mut Context) -> Entity> { - cx.new(|cx| { - SelectState::new( - SearchableVec::new(vec![DeviceItem::default_choice()]), - Some(IndexPath::new(0)), - window, - cx, - ) - }) -} - fn slider( range: &std::ops::RangeInclusive, value: f32, @@ -193,7 +148,47 @@ fn device_list(devices: Vec) -> Vec { items } -fn volume_control(state: &Entity, value: f32, palette: Palette) -> Div { +fn device_rows(entity: &Entity, yumush: &Yumush, side: Side, t: Tokens) -> Vec { + let (items, chosen) = match side { + Side::Input => (&yumush.voice.inputs, &yumush.settings.voice.choice.input), + Side::Output => (&yumush.voice.outputs, &yumush.settings.voice.choice.output), + }; + let chosen = in_use(items, chosen); + items + .iter() + .enumerate() + .map(|(index, item)| { + let entity = entity.clone(); + let id = item.id.clone(); + super::share_view::row_style(clickable( + SharedString::from(format!("audio_device_{index}")), + t, + move |_, cx| { + let id = id.clone(); + entity.update(cx, |yumush, cx| yumush.set_voice_device(side, id, cx)); + }, + )) + .child(div().flex_1().min_w_0().truncate().child(item.name.clone())) + .children((item.id == chosen).then(|| { + super::parts::small_icon(IconName::Check) + .flex_shrink_0() + .text_color(t.paper()) + })) + .into_any_element() + }) + .collect() +} + +fn percent(value: f32, t: Tokens) -> Div { + div() + .w(px(size::ROW)) + .flex_none() + .text_right() + .text_color(t.dim()) + .child(format!("{value:.0}%")) +} + +fn volume_control(state: &Entity, value: f32, t: Tokens) -> Div { div() .flex() .items_center() @@ -201,18 +196,12 @@ fn volume_control(state: &Entity, value: f32, palette: Palette) -> .child( div() .w(px(size::THUMB)) - .child(super::parts::slider(state, palette.tokens)), - ) - .child( - div() - .w(px(size::ROW)) - .text_right() - .text_color(palette.muted) - .child(format!("{value:.0}%")), + .child(super::parts::slider(state, t)), ) + .child(percent(value, t)) } -fn level_bar(level: Option, threshold: f32, hue: gpui_kit::Hsla, palette: Palette) -> Div { +fn level_bar(level: Option, threshold: f32, hue: gpui_kit::Hsla, t: Tokens) -> Div { let range = SENSITIVITY_DB; let fraction = level.map_or(0.0, |db| { ((db - range.start()) / (range.end() - range.start())).clamp(0.0, 1.0) @@ -220,14 +209,14 @@ fn level_bar(level: Option, threshold: f32, hue: gpui_kit::Hsla, palette: P let color = if level.is_some_and(|db| db >= threshold) { hue } else { - palette.muted + t.dim() }; div() .h(px(space::XS)) .w_full() .rounded(px(radius::SM)) - .bg(palette.border) + .bg(t.thread()) .child( div() .h_full() @@ -238,38 +227,30 @@ fn level_bar(level: Option, threshold: f32, hue: gpui_kit::Hsla, palette: P } impl Yumush { - pub(super) fn voice_rows(&self, entity: &Entity, palette: Palette, cx: &App) -> Vec
{ + pub(super) fn voice_rows(&self, entity: &Entity, t: Tokens, cx: &App) -> Vec
{ let voice = &self.settings.voice; let controls = &self.voice; let mut rows = vec![ row( w().voice_settings.input_device, - super::widget::underline(palette, Select::new(&controls.inputs).appearance(false)) - .w(px(size::SIDEBAR)), + self.device_column(entity, Side::Input, t), ), row( w().voice_settings.output_device, - super::widget::underline(palette, Select::new(&controls.outputs).appearance(false)) - .w(px(size::SIDEBAR)), + self.device_column(entity, Side::Output, t), ), row( w().voice_settings.input_volume, - volume_control(&controls.input_volume, voice.input_volume, palette), + volume_control(&controls.input_volume, voice.input_volume, t), ), row( w().voice_settings.output_volume, - volume_control(&controls.output_volume, voice.output_volume, palette), + volume_control(&controls.output_volume, voice.output_volume, t), ), row( w().voice_settings.mode, - segmented( - modes(), - voice.activation, - entity, - palette, - Yumush::set_voice_mode, - ), + segmented(modes(), voice.activation, entity, t, Yumush::set_voice_mode), ), row( w().voice_settings.profile, @@ -277,32 +258,39 @@ impl Yumush { profiles(), voice.profile, entity, - palette, + t, Yumush::set_voice_profile, ), ), ]; - rows.push(row( - w().voice_settings.test, - self.test_control(entity, palette), - )); + if self.chat.voice_flags().is_none() { + rows.push(row(w().voice_settings.test, self.test_control(entity, t))); + } match voice.activation { Activation::VoiceActivity => rows.push(row( w().voice_settings.sensitivity, - self.sensitivity_control(palette), + self.sensitivity_control(t), )), Activation::PushToTalk => rows.push(row( w().voice_settings.key, - self.key_control(&voice.push_to_talk_key, entity, palette, cx), + self.key_control(&voice.push_to_talk_key, entity, t, cx), )), } rows } - fn test_control(&self, entity: &Entity, palette: Palette) -> Div { - let testing = self.voice.mic_test != MicTest::Off; + fn device_column(&self, entity: &Entity, side: Side, t: Tokens) -> Div { + div() + .w(px(size::SIDEBAR)) + .flex() + .flex_col() + .children(device_rows(entity, self, side, t)) + } + + fn test_control(&self, entity: &Entity, t: Tokens) -> Div { + let testing = self.voice.mic_test == MicTest::On; let mic = entity.clone(); let speaker = entity.clone(); @@ -311,7 +299,7 @@ impl Yumush { .items_center() .gap(px(space::SM)) .child( - test_button("mic_test_button", palette, testing, move |_, cx| { + test_button("mic_test_button", t, testing, move |_, cx| { mic.update(cx, |yumush, cx| yumush.toggle_mic_test(cx)); }) .child(super::parts::small_icon(IconName::Mic)) @@ -322,9 +310,9 @@ impl Yumush { }), ) .child( - test_button("speaker_test_button", palette, false, move |_, cx| { + test_button("speaker_test_button", t, false, move |_, cx| { speaker.update(cx, |yumush, _| { - yumush.network.play_chime(&yumush.settings.voice) + voice::play_sound(Sound::Chime, &yumush.settings.voice) }); }) .child(super::parts::small_icon(IconName::Volume2)) @@ -332,7 +320,7 @@ impl Yumush { ) } - fn sensitivity_control(&self, palette: Palette) -> Div { + fn sensitivity_control(&self, t: Tokens) -> Div { let level = self.network.voice_level_db(); div().flex().items_center().gap(px(space::SM)).child( @@ -341,15 +329,12 @@ impl Yumush { .flex() .flex_col() .gap(px(space::SM)) - .child(super::parts::slider( - &self.voice.sensitivity, - palette.tokens, - )) + .child(super::parts::slider(&self.voice.sensitivity, t)) .child(level_bar( level, self.settings.voice.sensitivity_db, - palette.tokens.hue(super::style::my_hue()), - palette, + t.hue(super::style::my_hue()), + t, )), ) } @@ -358,7 +343,7 @@ impl Yumush { &self, key: &str, entity: &Entity, - palette: Palette, + t: Tokens, cx: &App, ) -> impl IntoElement { let content = match self.voice.key { @@ -370,7 +355,7 @@ impl Yumush { }; let entity = entity.clone(); - clickable("ptt_key_button", palette, move |window, cx| { + clickable("ptt_key_button", t, move |window, cx| { entity.update(cx, |yumush, cx| yumush.capture_key(window, cx)); }) .h(px(size::CONTROL_SM)) @@ -436,7 +421,20 @@ impl Yumush { cx.notify(); } - pub(super) fn voice_key_down(&mut self, event: &KeyDownEvent, cx: &mut Context) { + fn cancel_stale_capture(&mut self, window: &Window, cx: &mut Context) { + if self.voice.key == KeyCapture::Waiting && !self.focus.is_focused(window) { + self.voice.key = KeyCapture::Idle; + cx.notify(); + } + } + + pub(super) fn voice_key_down( + &mut self, + event: &KeyDownEvent, + window: &Window, + cx: &mut Context, + ) { + self.cancel_stale_capture(window, cx); let key = event.keystroke.key.clone(); match self.voice.key { @@ -466,8 +464,10 @@ impl Yumush { pub(super) fn voice_modifiers( &mut self, event: &ModifiersChangedEvent, + window: &Window, cx: &mut Context, ) { + self.cancel_stale_capture(window, cx); let modifiers = event.modifiers; let held = [ ("ctrl", modifiers.control), @@ -493,16 +493,10 @@ impl Yumush { pub(super) fn toggle_mic_test(&mut self, cx: &mut Context) { match self.voice.mic_test { - MicTest::On | MicTest::MutingCall => self.stop_mic_test(), + MicTest::On => self.stop_mic_test(), MicTest::Off => { self.network.start_mic_test(&self.settings.voice); - self.voice.mic_test = if self.chat.voice_flags().is_some_and(|(muted, _)| !muted) { - self.set_call_muted(true); - MicTest::MutingCall - } else { - MicTest::On - }; - self.start_level_poll(cx); + self.voice.mic_test = MicTest::On; } } cx.notify(); @@ -510,91 +504,73 @@ impl Yumush { pub(super) fn stop_mic_test(&mut self) { self.network.stop_mic_test(); - if self.voice.mic_test == MicTest::MutingCall { - self.set_call_muted(false); - } self.voice.mic_test = MicTest::Off; - self.voice.level_poll = None; } pub(super) fn leave_settings(&mut self) { self.stop_mic_test(); self.voice.key = KeyCapture::Idle; + self.voice.level_poll = None; } - pub(super) fn enter_settings(&mut self, window: &mut Window, cx: &mut Context) { - self.load_audio_devices(window, cx); + pub(super) fn enter_settings(&mut self, cx: &mut Context) { + self.load_audio_devices(cx); self.measure_storage(cx); - if self.network.voice_level_db().is_some() { - self.start_level_poll(cx); - } + self.start_level_poll(cx); } fn start_level_poll(&mut self, cx: &mut Context) { self.voice.level_poll = Some(cx.spawn(async move |this, cx| { loop { cx.background_executor().timer(LEVEL_INTERVAL).await; - let live = this.update(cx, |yumush, cx| { - let live = yumush.network.voice_level_db().is_some(); - cx.notify(); - live - }); - if !matches!(live, Ok(true)) { + if this.update(cx, |yumush, cx| yumush.tick_level(cx)).is_err() { break; } } })); } - pub(super) fn load_audio_devices(&self, window: &mut Window, cx: &mut Context) { - cx.spawn_in(window, async move |this, cx| { + fn tick_level(&mut self, cx: &mut Context) { + if self.voice.mic_test == MicTest::On && self.chat.voice_flags().is_some() { + self.stop_mic_test(); + } + cx.notify(); + } + + pub(super) fn load_audio_devices(&self, cx: &mut Context) { + cx.spawn(async move |this, cx| { let devices = cx .background_executor() .spawn(async { audio::devices() }) .await; - let _ = this.update_in(cx, |yumush, window, cx| { - yumush.apply_devices(devices, window, cx); - }); + let _ = this.update(cx, |yumush, cx| yumush.apply_devices(devices, cx)); }) .detach(); } - fn apply_devices(&mut self, devices: Devices, window: &mut Window, cx: &mut Context) { - let choice = self.settings.voice.choice.clone(); - - let inputs = device_list(devices.inputs); - let outputs = device_list(devices.outputs); - self.voice.input_items = inputs.clone(); - self.voice.output_items = outputs.clone(); - self.voice.inputs.update(cx, |state, cx| { - let chosen = in_use(&inputs, &choice.input); - state.set_items(SearchableVec::new(inputs), window, cx); - state.set_selected_value(&chosen, window, cx); - }); - self.voice.outputs.update(cx, |state, cx| { - let chosen = in_use(&outputs, &choice.output); - state.set_items(SearchableVec::new(outputs), window, cx); - state.set_selected_value(&chosen, window, cx); - }); + fn apply_devices(&mut self, devices: Devices, cx: &mut Context) { + self.voice.inputs = device_list(devices.inputs); + self.voice.outputs = device_list(devices.outputs); + cx.notify(); } } fn test_button( id: &'static str, - palette: Palette, + t: Tokens, active: bool, on_click: impl Fn(&mut Window, &mut App) + 'static, ) -> Stateful
{ - super::parts::press(id, palette.tokens, on_click) + super::parts::press(id, t, on_click) .font_weight(gpui_kit::FontWeight::MEDIUM) - .text_color(if active { palette.text } else { palette.muted }) + .text_color(if active { t.paper() } else { t.dim() }) } impl Yumush { pub(super) fn audio_button( &self, entity: &Entity, - palette: Palette, + t: Tokens, side: Side, cx: &App, ) -> impl IntoElement { @@ -616,63 +592,26 @@ impl Yumush { .anchor(Anchor::BottomRight) .appearance(false) .trigger(Trigger::new( - super::parts::chevron_face(false, super::style::Tokens::of(cx)) + super::parts::chevron_face(false, Tokens::of(cx)) .id(button) - .on_mouse_down(MouseButton::Left, move |_, window, cx| { - refresh.update(cx, |yumush, cx| yumush.load_audio_devices(window, cx)); + .on_mouse_down(MouseButton::Left, move |_, _, cx| { + refresh.update(cx, |yumush, cx| yumush.load_audio_devices(cx)); }) .tip(tip), )) - .content(move |_, _, cx| audio_card(&content, content.read(cx), side, palette)) + .content(move |_, _, cx| audio_card(&content, content.read(cx), side, t)) } } -fn audio_card(entity: &Entity, yumush: &Yumush, side: Side, palette: Palette) -> Div { - let t = palette.tokens; +fn audio_card(entity: &Entity, yumush: &Yumush, side: Side, t: Tokens) -> Div { let voice = &yumush.settings.voice; - let controls = &yumush.voice; - let (items, chosen, volume, value) = match side { - Side::Input => ( - &controls.input_items, - &voice.choice.input, - &controls.input_volume, - voice.input_volume, - ), - Side::Output => ( - &controls.output_items, - &voice.choice.output, - &controls.output_volume, - voice.output_volume, - ), + let (volume, value) = match side { + Side::Input => (&yumush.voice.input_volume, voice.input_volume), + Side::Output => (&yumush.voice.output_volume, voice.output_volume), }; - let chosen = in_use(items, chosen); super::parts::quick(t) .w(px(size::POPOVER)) - .children(items.iter().enumerate().map(|(index, item)| { - let entity = entity.clone(); - let id = item.id.clone(); - super::share_view::row_style(clickable( - SharedString::from(format!("audio_device_{index}")), - palette, - move |window, cx| { - let id = id.clone(); - entity.update(cx, |yumush, cx| { - let select = match side { - Side::Input => yumush.voice.inputs.clone(), - Side::Output => yumush.voice.outputs.clone(), - }; - select.update(cx, |state, cx| state.set_selected_value(&id, window, cx)); - yumush.set_voice_device(side, id, cx); - }); - }, - )) - .child(div().flex_1().min_w_0().truncate().child(item.name.clone())) - .children((item.id == chosen).then(|| { - super::parts::small_icon(IconName::Check) - .flex_shrink_0() - .text_color(palette.text) - })) - })) + .children(device_rows(entity, yumush, side, t)) .child(super::parts::thread(t)) .child( div() @@ -681,22 +620,11 @@ fn audio_card(entity: &Entity, yumush: &Yumush, side: Side, palette: Pal .gap(px(space::SM)) .px(px(space::SM)) .child(super::parts::slider(volume, t).live(audio_line(yumush, side, t))) - .child( - div() - .w(px(size::ROW)) - .flex_none() - .text_right() - .text_color(palette.muted) - .child(format!("{value:.0}%")), - ), + .child(percent(value, t)), ) } -fn audio_line( - yumush: &Yumush, - side: Side, - t: super::style::Tokens, -) -> Option { +fn audio_line(yumush: &Yumush, side: Side, t: Tokens) -> Option { let me = yumush.user.as_ref().map(|user| user.id); let heard: Vec = yumush .chat @@ -708,14 +636,20 @@ fn audio_line( .collect(); let speaking = heard .iter() - .any(|id| yumush.chat.waves.speaking.contains(id)); + .any(|id| yumush.chat.session.waves.speaking.contains(id)); let hue = match (side, me) { (Side::Input, Some(me)) => t.person(me), _ => t.paper(), }; speaking.then(|| { super::parts::voice_line( - yumush.chat.waves.total(&heard).as_ref(), + yumush + .chat + .session + .waves + .total(&heard) + .map(std::collections::VecDeque::from) + .as_ref(), super::parts::Voice::Live(hue), t, ) diff --git a/crates/client/src/gui/voice_stats.rs b/crates/client/src/gui/voice_stats.rs index b695574..9d20c77 100644 --- a/crates/client/src/gui/voice_stats.rs +++ b/crates/client/src/gui/voice_stats.rs @@ -3,6 +3,7 @@ use std::collections::VecDeque; use common::{ model::Id, share::{Kind, Layer}, + stats::{Engine, LayerStats, Stats, WatchStats}, }; use gpui_kit::{ AnyElement, Div, FontWeight, Hsla, IntoElement, ParentElement, Styled, div, @@ -10,22 +11,22 @@ use gpui_kit::{ }; use super::{ - Palette, parts::{Fill, Ink, Text, band, chart, grow, stack, track, words}, style::{Tokens, size, space}, }; use crate::lang::w; -use crate::media::decode::Engine; -use crate::share::session::{LayerStats, WatchStats}; use crate::usage::Usage; use crate::voice::VoiceSample; -use common::stats::Stats; pub const SAMPLE_HISTORY: usize = 60; const LABEL_W: f32 = size::ROW + space::LG; const VALUE_W: f32 = size::THUMB; const COLUMN_W: f32 = size::TALK + size::ROW * 2.; pub const PING_SCALE: f32 = 150.; +const GOOD_PING: f32 = 100.; +const FAIR_PING: f32 = 200.; +const GOOD_JITTER: f32 = 30.; +const FAIR_JITTER: f32 = 60.; pub(super) const GOOD_LOSS: f32 = 2.; const FAIR_LOSS: f32 = 8.; @@ -40,16 +41,27 @@ impl Quality { pub fn of(sample: &VoiceSample) -> Self { let loss = sample.traffic.loss * 100.; let jitter = sample.traffic.jitter_ms; - if sample.ping_ms < 100. && loss < GOOD_LOSS && jitter < 30. { + let ping = Self::of_ping(sample.ping_ms); + if ping == Self::Good && loss < GOOD_LOSS && jitter < GOOD_JITTER { Self::Good - } else if sample.ping_ms < 200. && loss < FAIR_LOSS && jitter < 60. { + } else if ping != Self::Poor && loss < FAIR_LOSS && jitter < FAIR_JITTER { Self::Fair } else { Self::Poor } } - fn of_loss(percent: f32) -> Self { + fn of_ping(ms: f32) -> Self { + if ms < GOOD_PING { + Self::Good + } else if ms < FAIR_PING { + Self::Fair + } else { + Self::Poor + } + } + + pub(super) fn of_loss(percent: f32) -> Self { if percent < GOOD_LOSS { Self::Good } else if percent < FAIR_LOSS { @@ -94,13 +106,7 @@ pub fn stamp(at_ms: u64, value: String) -> gpui_kit::SharedString { .into() } -pub fn stats_panel( - stats: &Stats, - name: &dyn Fn(Id) -> String, - detail: Detail, - palette: Palette, -) -> Div { - let t = palette.tokens; +pub fn stats_panel(stats: &Stats, name: &dyn Fn(Id) -> String, detail: Detail, t: Tokens) -> Div { let share = &stats.share; if detail == Detail::Connection { return stack(space::LG) @@ -486,21 +492,7 @@ fn watching( )) .children(watching.iter().map(|(user_id, kind, stats)| { let name = name(*user_id); - let detail = format!( - "{} · {}{}", - kind_word(*kind), - stats - .layer - .map_or("…".to_string(), |layer| resolution_text(layer, stats.fps)), - stats - .layer - .zip(stats.engine) - .map_or(String::new(), |(layer, engine)| format!( - " · {} · {}", - layer.codec.name(), - engine_label(engine) - )) - ); + let detail = format!("{} · {}", kind_word(*kind), stream_detail(stats)); let bad = Quality::of_loss(stats.loss * 100.) == Quality::Poor; stack(space::XXS) .child( @@ -582,6 +574,20 @@ pub fn rate(kbps: u32) -> String { } } +pub(super) fn stream_detail(stats: &WatchStats) -> String { + let layer = stats.layer.map_or("…".to_string(), |layer| { + format!( + "{} · {}", + resolution_text(layer, stats.fps), + layer.codec.name() + ) + }); + match stats.engine { + Some(engine) => format!("{layer} · {}", engine_label(engine)), + None => layer, + } +} + pub(super) fn engine_label(engine: Engine) -> &'static str { match engine { Engine::Hardware => w().voice_stats.hardware, diff --git a/crates/client/src/gui/wave.rs b/crates/client/src/gui/wave.rs index 38d0f52..9cd5921 100644 --- a/crates/client/src/gui/wave.rs +++ b/crates/client/src/gui/wave.rs @@ -1,4 +1,4 @@ -use std::collections::{HashMap, HashSet, VecDeque}; +use std::collections::{HashMap, HashSet}; use common::model::Id; use gpui_kit::{Hsla, IntoElement, PathBuilder, Styled, canvas, point, px}; @@ -13,7 +13,7 @@ const HOLD_TICKS: u8 = 3; const GONE: f32 = 0.02; pub struct Wave { - bars: VecDeque, + bars: Vec, falls: Vec, target: Vec, stale: u8, @@ -22,7 +22,7 @@ pub struct Wave { impl Wave { fn new() -> Self { Self { - bars: VecDeque::from(vec![0.0; spectrum::BANDS]), + bars: vec![0.0; spectrum::BANDS], falls: vec![0.0; spectrum::BANDS], target: vec![0.0; spectrum::BANDS], stale: 0, @@ -75,7 +75,6 @@ fn soften(bands: &[f32]) -> Vec { #[derive(Default)] pub struct Waves { pub speaking: HashSet, - pub own_live: bool, voice: HashMap, share: HashMap, } @@ -98,18 +97,16 @@ impl Waves { pub fn update(&mut self, levels: Levels, me: Option, deafened: bool) -> bool { let mut voice = levels.voice; let mut speaking: HashSet = voice.iter().map(|(id, _)| *id).collect(); - let own_live = levels.own_sending && !deafened; if let Some(me) = me && !deafened { voice.push((me, levels.own)); - if own_live { + if levels.own_sending { speaking.insert(me); } } - let mut changed = speaking != self.speaking || own_live != self.own_live; + let mut changed = speaking != self.speaking; self.speaking = speaking; - self.own_live = own_live; let had = !self.voice.is_empty() || !self.share.is_empty(); changed |= advance(&mut self.voice, voice); @@ -123,13 +120,13 @@ impl Waves { *self = Self::default(); } - pub fn voice(&self, id: Id) -> Option<&VecDeque> { - self.voice.get(&id).map(|wave| &wave.bars) + pub fn voice(&self, id: Id) -> Option<&[f32]> { + self.voice.get(&id).map(|wave| wave.bars.as_slice()) } - pub fn total(&self, ids: &[Id]) -> Option> { + pub fn total(&self, ids: &[Id]) -> Option> { let mut waves = ids.iter().filter_map(|id| self.voice(*id)); - let first = waves.next()?.clone(); + let first = waves.next()?.to_vec(); Some(waves.fold(first, |mut sum, bars| { sum.iter_mut() .zip(bars) @@ -148,8 +145,8 @@ impl Waves { .is_some_and(|wave| wave.bars.iter().any(|bar| *bar >= GONE)) } - pub fn share(&self, id: Id) -> Option<&VecDeque> { - self.share.get(&id).map(|wave| &wave.bars) + pub fn share(&self, id: Id) -> Option<&[f32]> { + self.share.get(&id).map(|wave| wave.bars.as_slice()) } } diff --git a/crates/client/src/gui/widget.rs b/crates/client/src/gui/widget.rs index 73edc08..40d2dbd 100644 --- a/crates/client/src/gui/widget.rs +++ b/crates/client/src/gui/widget.rs @@ -7,58 +7,40 @@ use gpui_kit::{ }; use super::{ - Palette, Yumush, notify_error, - style::{size, space}, + Yumush, notify_error, + style::{Tokens, size, space}, }; -pub(super) fn panel(palette: Palette) -> Div { - super::parts::surface(palette.tokens) -} - -pub(super) fn field(palette: Palette, input: &Entity) -> Div { - frame(palette, Input::new(input).token(super::glyph::token)) -} - -pub(super) fn compact_frame(palette: Palette) -> Div { +pub(super) fn underline(t: Tokens, height: f32, child: impl gpui_kit::IntoElement) -> Div { div() - .h(px(size::CONTROL_SM + space::XS)) + .h(px(height)) .flex() .items_center() .border_b_1() - .border_color(palette.border) + .border_color(t.thread()) + .child(div().flex_1().min_w_0().child(child)) } -pub(super) fn compact_field(palette: Palette, input: &Entity) -> Div { - compact_frame(palette).child(bare_input( - palette, - Input::new(input).token(super::glyph::token), - )) +pub(super) fn field(t: Tokens, input: &Entity) -> Div { + frame(t, Input::new(input).token(super::glyph::token)) } -pub(super) fn frame(palette: Palette, input: Input) -> Div { - div() - .h(px(size::CONTROL)) - .flex() - .items_center() - .border_b_1() - .border_color(palette.border) - .child(bare_input(palette, input)) +pub(super) fn compact_field(t: Tokens, input: &Entity) -> Div { + underline( + t, + size::CONTROL_SM + space::XS, + bare_input(t, Input::new(input).token(super::glyph::token)), + ) } -pub(super) fn underline(palette: Palette, child: impl gpui_kit::IntoElement) -> Div { - div() - .h(px(size::CONTROL)) - .flex() - .items_center() - .border_b_1() - .border_color(palette.border) - .child(div().flex_1().min_w_0().child(child)) +pub(super) fn frame(t: Tokens, input: Input) -> Div { + underline(t, size::CONTROL, bare_input(t, input)) } -pub(super) fn bare_input(palette: Palette, input: Input) -> Input { +pub(super) fn bare_input(t: Tokens, input: Input) -> Input { input .appearance(false) - .text_color(palette.text) + .text_color(t.paper()) .flex_1() .min_w_0() } diff --git a/crates/client/src/instance.rs b/crates/client/src/instance.rs index 6a6d46b..bdce096 100644 --- a/crates/client/src/instance.rs +++ b/crates/client/src/instance.rs @@ -31,13 +31,30 @@ fn alone() -> Instance { #[cfg(unix)] fn claim_in(dir: std::path::PathBuf) -> Instance { + use std::fs::{OpenOptions, TryLockError}; use std::os::unix::net::{UnixListener, UnixStream}; - let path = dir.join("instance.sock"); - if UnixStream::connect(&path).is_ok() { - return Instance::Running; - } let _ = std::fs::create_dir_all(&dir); + let Ok(lock) = OpenOptions::new() + .create(true) + .write(true) + .truncate(false) + .open(dir.join("instance.lock")) + else { + return alone(); + }; + match lock.try_lock() { + Ok(()) => {} + Err(TryLockError::WouldBlock) => { + let _ = UnixStream::connect(dir.join("instance.sock")); + return Instance::Running; + } + Err(TryLockError::Error(error)) => { + tracing::warn!("instance: {error}"); + return alone(); + } + } + let path = dir.join("instance.sock"); let _ = std::fs::remove_file(&path); let listener = match UnixListener::bind(&path) { Ok(listener) => listener, @@ -50,6 +67,7 @@ fn claim_in(dir: std::path::PathBuf) -> Instance { let _ = std::thread::Builder::new() .name("instance".to_string()) .spawn(move || { + let _lock = lock; for stream in listener.incoming() { if stream.is_ok() && sender.send(()).is_err() { break; diff --git a/crates/client/src/lang.rs b/crates/client/src/lang.rs index 34e2cbc..6fa3999 100644 --- a/crates/client/src/lang.rs +++ b/crates/client/src/lang.rs @@ -37,12 +37,11 @@ pub fn set(lang: Lang) { } pub fn w() -> &'static Words { - let current = CURRENT.load(Ordering::Relaxed); - Lang::ALL - .into_iter() - .find(|lang| *lang as u8 == current) - .unwrap_or(Lang::En) - .words() + if CURRENT.load(Ordering::Relaxed) == Lang::Tr as u8 { + &TR + } else { + &EN + } } pub trait Label { diff --git a/crates/client/src/lib.rs b/crates/client/src/lib.rs index c377f35..64cb557 100644 --- a/crates/client/src/lib.rs +++ b/crates/client/src/lib.rs @@ -1,6 +1,5 @@ -use std::{fs, io::Write, path::PathBuf}; +use std::{fs, future::Future, io::Write, path::PathBuf}; -use common::config::Config; use tracing::warn; pub mod accounts; @@ -25,11 +24,13 @@ pub mod tray; pub mod update; pub use usage; pub mod voice; +pub mod worker; pub const NAME: &str = "Yumush"; pub const VERSION: &str = env!("CARGO_PKG_VERSION"); pub const COMMIT: &str = env!("YUMUSH_COMMIT"); pub const TARGET: &str = env!("YUMUSH_TARGET"); +const DEFAULT_SERVER: &str = "127.0.0.1:2026"; static EXE: std::sync::LazyLock> = std::sync::LazyLock::new(|| std::env::current_exe().ok()); @@ -66,15 +67,20 @@ pub fn write_config(name: &str, content: impl AsRef<[u8]>) { let Some(path) = config_file(name) else { return; }; + let temp = path.with_file_name(format!("{name}.tmp")); let result = path .parent() .map_or(Ok(()), fs::create_dir_all) .and_then(|()| { + let _ = fs::remove_file(&temp); let mut options = fs::OpenOptions::new(); - options.write(true).create(true).truncate(true); + options.write(true).create_new(true); #[cfg(unix)] std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); - options.open(&path)?.write_all(content.as_ref()) + let mut file = options.open(&temp)?; + file.write_all(content.as_ref())?; + file.sync_all()?; + fs::rename(&temp, &path) }); if let Err(error) = result { @@ -82,10 +88,23 @@ pub fn write_config(name: &str, content: impl AsRef<[u8]>) { } } -const CLIENT_CONFIG_FILE_CONTENT: &str = include_str!(concat!( - env!("CARGO_MANIFEST_DIR"), - "/../../configs/client_config.toml" -)); +pub fn spawn_runtime>( + name: &str, + task: impl FnOnce() -> F + Send + 'static, +) { + let name = name.to_string(); + let _ = std::thread::Builder::new() + .name(name.clone()) + .spawn(move || { + match tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + { + Ok(runtime) => runtime.block_on(task()), + Err(error) => warn!("{name} runtime: {error}"), + } + }); +} #[derive(Debug, Clone, PartialEq, Eq)] pub struct Server { @@ -102,11 +121,7 @@ impl Server { .ok() .or_else(|| saved_address.map(str::to_string)) .filter(|address| !address.is_empty()) - .unwrap_or_else(|| { - Config::parse(CLIENT_CONFIG_FILE_CONTENT) - .and_then(|config| config.get("server_address")) - .expect("client config server_address") - }); + .unwrap_or_else(|| DEFAULT_SERVER.to_string()); let any_cert = std::env::var_os("YUMUSH_ANY_CERT").is_some() || lines.next() == Some("any_cert"); Self { address, any_cert } @@ -118,10 +133,11 @@ impl Server { } pub fn host(&self) -> &str { + if let Some(bracketed) = self.address.strip_prefix('[') { + return bracketed.split(']').next().unwrap_or(bracketed); + } match self.address.rsplit_once(':') { - Some((host, port)) if !host.ends_with(':') && port.parse::().is_ok() => { - host.trim_start_matches('[').trim_end_matches(']') - } + Some((host, port)) if !host.contains(':') && port.parse::().is_ok() => host, _ => &self.address, } } diff --git a/crates/client/src/logo.rs b/crates/client/src/logo.rs index d9c44f0..e7691c9 100644 --- a/crates/client/src/logo.rs +++ b/crates/client/src/logo.rs @@ -8,7 +8,9 @@ const WINDOW_ICON: u32 = 256; mod svg; -pub use svg::{NAME, icon, mark, needle, rgba}; +pub use svg::{NAME, rgba}; + +use svg::{icon, mark, needle}; pub fn window_icon() -> std::sync::Arc { std::sync::Arc::new( diff --git a/crates/client/src/main.rs b/crates/client/src/main.rs index b798eac..5a252bf 100644 --- a/crates/client/src/main.rs +++ b/crates/client/src/main.rs @@ -4,7 +4,7 @@ use client::{ NAME, Server, gui::{ self, Yumush, - gallery::{Gallery, State}, + gallery::{Gallery, Page, State}, }, net, settings, tray::{self, TrayAction, TrayState}, @@ -137,7 +137,10 @@ fn hide(view: &Entity, cx: &mut App) { fn gallery(spec: String) { let (page, state) = spec.split_once(':').unwrap_or((&spec, "base")); - let page = page.to_string(); + let Some(page) = Page::parse(page) else { + eprintln!("unknown gallery page {page}"); + return; + }; let Some(state) = State::parse(state) else { eprintln!("unknown gallery state {state}"); return; diff --git a/crates/client/src/media/convert.rs b/crates/client/src/media/convert.rs deleted file mode 100644 index af28a93..0000000 --- a/crates/client/src/media/convert.rs +++ /dev/null @@ -1,4 +0,0 @@ -pub use pixel::yuv_to_bgra; - -pub const ATTACHMENT_WIDTH: u32 = 1280; -pub const SHARE_WIDTH: u32 = 3840; diff --git a/crates/client/src/media/decode.rs b/crates/client/src/media/decode.rs index 5fe41fb..d098b11 100644 --- a/crates/client/src/media/decode.rs +++ b/crates/client/src/media/decode.rs @@ -15,11 +15,12 @@ use ec_core::registry::{CodecId, CodecParameters, Decoder as CodecDecoder, SeekM use ec_core::timebase::{TimeBase, Timestamp}; use ec_h264::H264Decoder; use ec_probe::{Reader, decoder::AudioDecoder}; +use pixel::yuv_to_bgra; use rtrb::Producer; use tracing::warn; use super::{ - Frame, Tracks, convert, + ATTACHMENT_WIDTH, Frame, SHARE_WIDTH, Tracks, resample::{self, Resampler, Stereo}, }; use crate::voice::{PLAYBACK_CHANNELS, Playback}; @@ -144,16 +145,9 @@ pub enum Picture { } impl Picture { - pub fn size(&self) -> (u32, u32) { - match self { - Picture::Planes(planes) => (planes.width, planes.height), - Picture::Bgra { width, height, .. } => (*width, *height), - } - } - pub fn into_frame(self, max_width: u32) -> Option { let (width, height, bgra) = match self { - Picture::Planes(planes) => convert::yuv_to_bgra( + Picture::Planes(planes) => yuv_to_bgra( &planes.y, planes.y_stride, &planes.u, @@ -238,16 +232,8 @@ impl VideoDecoder { } drain_h264(decoder) } - VideoDecoder::Vp8(decoder) => { - let Some(pts) = packet - .pts - .map(|ticks| Timestamp::new(ticks, packet.time_base).as_secs_f64()) - else { - return Vec::new(); - }; - skipped(decoder.decode(&packet.data)) - .map_or_else(Vec::new, |picture| vec![(pts, vp8_picture(picture))]) - } + VideoDecoder::Vp8(decoder) => skipped(decoder.decode(&packet.data)) + .map_or_else(Vec::new, |picture| vec![(seconds, vp8_picture(picture))]), VideoDecoder::H265(decoder) => { if let Err(error) = decoder.decode_annex_b(&packet.data) { warn!("video packet skipped: {error}"); @@ -347,7 +333,7 @@ fn rgb_output(max_width: u32) -> ec_hw::RgbOutput { } fn open_hardware(codec: Codec) -> Option { - ec_hw::HwDecoder::open_rgb(hardware_codec(codec)?, rgb_output(convert::SHARE_WIDTH)).ok() + ec_hw::HwDecoder::open_rgb(hardware_codec(codec)?, rgb_output(SHARE_WIDTH)).ok() } fn hardware(codec: Codec) -> Option { @@ -481,6 +467,8 @@ pub struct Worker { skip: usize, scratch: Vec, eof: bool, + duration: Option, + audio_end: f64, } impl Worker { @@ -491,6 +479,7 @@ impl Worker { playback: Playback, producer: Option>, tracks: Tracks, + duration: Option, ) -> Worker { Worker { shared, @@ -507,6 +496,8 @@ impl Worker { skip: 0, scratch: Vec::new(), eof: false, + duration, + audio_end: 0.0, } } @@ -603,12 +594,17 @@ impl Worker { fn finish(&self) { let mut clock = lock(&self.shared.clock); + let length = self + .duration + .map_or(self.audio_end, |length| length.as_secs_f64()); + let elapsed = clock.audio || clock.position(0) >= length; if clock.state == State::Playing && self.pending.is_empty() && self.ring_empty() && self.backlog.is_empty() && lock(&self.shared.seek).is_none() && lock(&self.shared.video).queue.is_empty() + && elapsed { clock.set(State::Finished); } @@ -669,6 +665,10 @@ impl Worker { } fn audio_packet(&mut self, packet: &Packet) { + let pts = packet + .pts + .map(|ticks| Timestamp::new(ticks, packet.time_base).as_secs_f64()); + self.audio_end = self.audio_end.max(pts.unwrap_or(0.0)); if self.producer.is_none() { return; } @@ -680,9 +680,6 @@ impl Worker { warn!("audio packet skipped: {error}"); } else { let (rate, channels) = (audio.sample_rate(), audio.channels()); - let pts = packet - .pts - .map(|ticks| Timestamp::new(ticks, packet.time_base).as_secs_f64()); self.queue_audio(&samples, channels, rate, pts); } self.scratch = samples; @@ -792,7 +789,7 @@ pub fn position(shared: &Shared, playback: &Playback) -> f64 { } fn show(shared: &Shared, pts: f64, picture: Picture) { - let Some(frame) = picture.into_frame(convert::ATTACHMENT_WIDTH) else { + let Some(frame) = picture.into_frame(ATTACHMENT_WIDTH) else { return; }; lock(&shared.video).queue.push_back((pts, frame)); diff --git a/crates/client/src/media/meter.rs b/crates/client/src/media/meter.rs index 37deb59..4e20baa 100644 --- a/crates/client/src/media/meter.rs +++ b/crates/client/src/media/meter.rs @@ -40,14 +40,6 @@ impl Spectrum { self.fresh = true; } - pub fn absorb(&mut self, other: &mut Spectrum) { - if other.fresh { - let samples: Vec = other.samples.iter().copied().collect(); - self.record(&samples, 1); - other.fresh = false; - } - } - pub fn take(&mut self) -> Vec { if !std::mem::take(&mut self.fresh) { return Vec::new(); diff --git a/crates/client/src/media/mod.rs b/crates/client/src/media/mod.rs index 4147820..7d46ce8 100644 --- a/crates/client/src/media/mod.rs +++ b/crates/client/src/media/mod.rs @@ -1,4 +1,3 @@ -pub mod convert; pub mod decode; pub mod meter; mod resample; @@ -15,7 +14,6 @@ use std::{ use ec_core::registry::MediaType; use ec_probe::{Reader, decoder::AudioDecoder}; use rtrb::RingBuffer; -use tracing::warn; use crate::lang::w; use crate::voice::{ @@ -24,6 +22,9 @@ use crate::voice::{ }; use decode::{RING_SAMPLES, Shared, State, VideoDecoder, Worker, lock}; +pub const ATTACHMENT_WIDTH: u32 = 1280; +pub const SHARE_WIDTH: u32 = 3840; + #[derive(Debug, Clone)] pub struct Frame { pub width: u32, @@ -110,9 +111,7 @@ impl Info { let scanned = || tracks.video.is_none().then(|| flac_end(path)).flatten(); Info { - duration: stated - .or_else(scanned) - .map(|seconds| Duration::from_secs_f64(seconds.max(0.0))), + duration: stated.or_else(scanned).map(Duration::from_secs_f64), video: tracks.video.as_ref().map(|(_, size, _)| *size), audio: tracks.audio.is_some(), } @@ -129,10 +128,6 @@ fn open_tracks(path: &Path) -> Result<(Reader, Tracks, Info), MediaError> { Ok((reader, tracks, info)) } -pub fn probe(path: &Path) -> Result { - open_tracks(path).map(|(_, _, info)| info) -} - const FLAC_TAIL: u64 = 256 * 1024; fn flac_end(path: &Path) -> Option { @@ -175,24 +170,25 @@ pub struct Player { impl Player { pub fn open(path: &Path, choice: Choice) -> Result { - let info = probe(path)?; + let (_, _, info) = open_tracks(path)?; let (producer, consumer) = RingBuffer::new(RING_SAMPLES); let playback: Playback = Arc::new(Mutex::new(consumer)); let audio = if info.audio { audio::start(None, playback.clone(), choice) } else { - Audio::Silent + Audio::default() }; - let audio_on = info.audio && !matches!(audio, Audio::Silent); + let audio_on = !audio.is_silent(); let shared = Arc::new(Shared::new(audio_on)); let worker_shared = shared.clone(); let worker_path = path.to_path_buf(); let worker_playback = playback.clone(); + let duration = info.duration; let handle = std::thread::Builder::new() .name("media-decode".to_string()) .spawn(move || { let Ok((reader, tracks, _)) = open_tracks(&worker_path) else { - warn!("media reopen failed: {}", worker_path.display()); + tracing::warn!("media reopen failed: {}", worker_path.display()); return; }; Worker::new( @@ -202,6 +198,7 @@ impl Player { worker_playback, audio_on.then_some(producer), tracks, + duration, ) .run() })?; @@ -313,7 +310,7 @@ mod tests { let path = std::env::temp_dir().join(format!("yumush-media-probe-{}.bin", std::process::id())); std::fs::write(&path, &bytes).unwrap(); - let result = probe(&path); + let result = open_tracks(&path); let _ = std::fs::remove_file(&path); assert!(matches!(result, Err(MediaError::Unsupported))); } diff --git a/crates/client/src/net/datagram.rs b/crates/client/src/net/datagram.rs deleted file mode 100644 index 54adcc9..0000000 --- a/crates/client/src/net/datagram.rs +++ /dev/null @@ -1,23 +0,0 @@ -use common::datagram::{Packet, split}; - -use super::*; - -pub(super) async fn datagram_receive_loop(connection: quinn::Connection, media: Arc) { - let loss: u64 = std::env::var("YUMUSH_TEST_LOSS") - .ok() - .and_then(|value| value.parse().ok()) - .unwrap_or(0); - let mut received: u64 = 0; - while let Ok(datagram) = connection.read_datagram().await { - let Some((from, packet)) = split(&datagram) else { - continue; - }; - if matches!(packet, Packet::Video { .. }) { - received += 1; - if received * 37 % 100 < loss { - continue; - } - } - media.receive(&datagram, from, packet); - } -} diff --git a/crates/client/src/net/events.rs b/crates/client/src/net/events.rs deleted file mode 100644 index 197541e..0000000 --- a/crates/client/src/net/events.rs +++ /dev/null @@ -1,40 +0,0 @@ -use common::{ - event::Down, - frame::{self, DOWN_MAX}, -}; -use tokio::sync::mpsc; - -use super::*; - -pub(super) async fn event_receive_loop( - connection: quinn::Connection, - event_sender: mpsc::Sender, - media: Arc, -) { - let Ok(mut receive_stream) = connection.accept_uni().await else { - return; - }; - - while let Ok(down) = frame::read::(&mut receive_stream, DOWN_MAX).await { - match down { - Down::Event(event) => { - if matches!(*event, common::event::Event::Release) { - crate::update::recheck(); - } - media.pushed(&event); - if event_sender - .send(NetworkEvent::Pushed(event)) - .await - .is_err() - { - return; - } - } - Down::Media(down) => { - if media.down(&down) && event_sender.send(NetworkEvent::VoiceEnded).await.is_err() { - return; - } - } - } - } -} diff --git a/crates/client/src/net/fetch.rs b/crates/client/src/net/fetch.rs index b4b0612..b033194 100644 --- a/crates/client/src/net/fetch.rs +++ b/crates/client/src/net/fetch.rs @@ -34,7 +34,7 @@ impl Fetches { .expect("semaphore never closes") } - pub(super) async fn memory( + pub(super) async fn download( &self, connection: &quinn::Connection, blob: Blob, diff --git a/crates/client/src/net/link.rs b/crates/client/src/net/link.rs index 4e9c2ac..0b31dff 100644 --- a/crates/client/src/net/link.rs +++ b/crates/client/src/net/link.rs @@ -1,10 +1,11 @@ -use std::{future::Future, net::SocketAddr, path::Path, sync::Arc, time::Duration}; +use std::{net::SocketAddr, path::Path, sync::Arc, time::Duration}; +use bitcode::{DecodeOwned, Encode}; use common::{ call::Call, constant::{ATTACHMENT_CHUNK_BYTES, MAXIMUM_ATTACHMENT_LIMIT_BYTES}, error::{Error, ReleaseProblem}, - frame::{self, DOWN_MAX, DecodeOwned, Encode, Sending, UP_MAX}, + frame::{self, DOWN_MAX, Sending, UP_MAX}, model::{Attachment, Id, Staged, User}, open::{Blob, Open, Stage, Upload}, session::{Hello, Welcome}, @@ -24,46 +25,44 @@ use tokio::{ }; use tracing::{info, warn}; -use super::{datagram::datagram_receive_loop, events::event_receive_loop, *}; +use super::{Fail, LinkError, NetworkEvent, SignIn, media::Media, receive}; const CHANNEL_SIZE: usize = 32; const BACKOFF_BASE_MILLIS: u64 = 250; const BACKOFF_CAP_MILLIS: u64 = 8_000; const UPDATE_CHECK: Duration = Duration::from_secs(5); -pub fn start(server: crate::Server) -> (NetworkHandle, mpsc::Receiver) { - let (command_sender, command_receiver) = mpsc::channel(CHANNEL_SIZE); +pub fn start(server: crate::Server) -> (super::NetworkHandle, mpsc::Receiver) { + let (sign_in, sign_in_receiver) = mpsc::channel(CHANNEL_SIZE); let (server, server_receiver) = watch::channel(server); let (event_sender, event_receiver) = mpsc::channel(CHANNEL_SIZE); let runtime = tokio::runtime::Builder::new_current_thread() .enable_all() .build() .expect("network runtime"); - let shared = Shared { - media: Media::new(runtime.handle().clone()), - fetches: Arc::default(), - }; + let media = Media::new(runtime.handle().clone()); std::thread::Builder::new() .name("network".to_string()) .spawn({ - let shared = shared.clone(); + let media = media.clone(); move || { runtime.block_on(actor( server_receiver, - command_receiver, + sign_in_receiver, event_sender, - shared, + media, )) } }) .expect("network thread"); ( - NetworkHandle { - command_sender, + super::NetworkHandle { + sign_in, server, - shared, + media, + fetches: Arc::default(), }, event_receiver, ) @@ -266,6 +265,30 @@ async fn exchange( Ok((reply, receive_stream)) } +async fn send_body( + connection: &quinn::Connection, + header: &impl Encode, + body: impl AsyncFnOnce(&mut Sending) -> Result<(), Fail>, +) -> Result { + let (send_stream, mut receive_stream) = connection.open_bi().await?; + let mut send_stream = Sending::new(send_stream); + frame::write(&mut send_stream, header, UP_MAX).await?; + + let write = async move { + body(&mut send_stream).await?; + send_stream.finish()?; + Ok::<(), Fail>(()) + }; + let read = frame::read::>(&mut receive_stream, DOWN_MAX); + let (sent, reply) = tokio::join!(write, read); + + match (sent, reply) { + (_, Ok(reply)) => Ok(reply?), + (Err(error), _) => Err(error), + (_, Err(error)) => Err(error.into()), + } +} + pub(super) async fn call( connection: &quinn::Connection, call: C, @@ -280,8 +303,7 @@ pub(super) async fn call( async fn hello(connection: &quinn::Connection, token: Option) -> Result { let hello = Hello { token, - device: device_name(), - build: crate::update::build(), + device: super::device_name(), install: crate::update::install_id(), }; @@ -306,36 +328,22 @@ pub(super) async fn upload( validate_attachment_size(size, maximum)?; } - let (send_stream, mut receive_stream) = connection.open_bi().await?; - let mut send_stream = Sending::new(send_stream); - let header = Upload { + let header = Open::Upload(Upload { community_id, name, size, - }; - frame::write(&mut send_stream, &Open::Upload(header), UP_MAX).await?; - - let write = async move { + }); + send_body(connection, &header, async |sending: &mut Sending| { let mut buffer = vec![0u8; ATTACHMENT_CHUNK_BYTES]; loop { let read = file.read(&mut buffer).await?; if read == 0 { - break; + return Ok(()); } - - send_stream.get().write_all(&buffer[..read]).await?; + sending.get().write_all(&buffer[..read]).await?; } - - Ok(send_stream.finish()?) - }; - let read = frame::read::>(&mut receive_stream, DOWN_MAX); - let (sent, reply) = tokio::join!(write, read); - - match (sent, reply) { - (_, Ok(reply)) => Ok(reply?), - (Err(error), _) => Err(error), - (_, Err(error)) => Err(error.into()), - } + }) + .await } pub(super) async fn stage( @@ -357,28 +365,17 @@ pub(super) async fn stage( return Err(Error::Release(ReleaseProblem::NotClient).into()); } - let (send_stream, mut receive_stream) = connection.open_bi().await?; - let mut send_stream = Sending::new(send_stream); - let header = Stage { + let header = Open::Stage(Stage { size: bytes.len() as u64, - }; - frame::write(&mut send_stream, &Open::Stage(header), UP_MAX).await?; - - let write = async move { + }); + send_body(connection, &header, async |sending: &mut Sending| { for (index, chunk) in bytes.chunks(ATTACHMENT_CHUNK_BYTES).enumerate() { - send_stream.get().write_all(chunk).await?; + sending.get().write_all(chunk).await?; progress.send_replace(((index * ATTACHMENT_CHUNK_BYTES) + chunk.len()) as u64); } - Ok(send_stream.finish()?) - }; - let read = frame::read::>(&mut receive_stream, DOWN_MAX); - let (sent, reply) = tokio::join!(write, read); - - match (sent, reply) { - (_, Ok(reply)) => Ok(reply?), - (Err(error), _) => Err(error), - (_, Err(error)) => Err(error.into()), - } + Ok(()) + }) + .await } pub(super) async fn backup_download( @@ -423,20 +420,23 @@ pub(super) async fn download(connection: &quinn::Connection, blob: &Blob) -> Res Ok(bytes) } -pub(super) fn answer( - reply: oneshot::Sender>, - work: impl Future> + Send + 'static, -) { - tokio::spawn(async move { - let _ = reply.send(work.await); - }); +fn rejects(token: &Option, pending: bool, error: &Fail) -> bool { + let Fail::Server(error) = error else { + return false; + }; + + token.is_some() && (pending || matches!(error, Error::Unauthenticated | Error::NotFound)) +} + +async fn halt(sign_in: &mut mpsc::Receiver) { + while sign_in.recv().await.is_some() {} } async fn actor( mut server: watch::Receiver, - mut command_receiver: mpsc::Receiver, - event_sender: mpsc::Sender, - shared: Shared, + mut sign_in: mpsc::Receiver, + events: mpsc::Sender, + media: Arc, ) { let mut token: Option = None; let mut pending: Option, Fail>>> = None; @@ -462,7 +462,7 @@ async fn actor( Err(error) => { warn!("connect failed: {error}"); - if event_sender + if events .send(NetworkEvent::Disconnected(error)) .await .is_err() @@ -483,39 +483,45 @@ async fn actor( let welcome = match hello(&connection, token.clone()).await { Ok(welcome) => welcome, - Err(Fail::Server(error)) - if token.is_some() - && (pending.is_some() - || matches!(error, Error::Unauthenticated | Error::NotFound)) => - { - warn!("session rejected: {error}"); - token = None; - connection.close(Close::Normal.code(), Close::Normal.reason().as_bytes()); - match pending.take() { - Some(reply) => { - let _ = reply.send(Err(Fail::Server(error))); - } - None => { - shared.media.reset(); - if event_sender.send(NetworkEvent::SessionLost).await.is_err() { - return; + Err(error) => { + warn!("hello failed: {error}"); + if rejects(&token, pending.is_some(), &error) { + token = None; + Close::Normal.on(&connection); + match pending.take() { + Some(reply) => { + let _ = reply.send(Err(error)); + } + None => { + media.reset(); + if events.send(NetworkEvent::SessionLost).await.is_err() { + return; + } } } + continue 'session; } - continue 'session; - } - Err(error) => { - warn!("hello failed: {error}"); - if let Some(reason) = connection + + let reason = connection .close_reason() - .map(LinkError::from) - .filter(|reason| reason.terminal()) - { - let _ = event_sender.send(NetworkEvent::Disconnected(reason)).await; - while command_receiver.recv().await.is_some() {} + .map_or(LinkError::Reset, LinkError::from); + Close::Protocol.on(&connection); + if reason.terminal() { + if let Some(reply) = pending.take() { + let _ = reply.send(Err(error)); + } + let _ = events.send(NetworkEvent::Disconnected(reason)).await; + halt(&mut sign_in).await; return; } - backoff(&mut attempt).await; + + tokio::select! { + _ = backoff(&mut attempt) => {} + _ = server.changed() => { + attempt = 0; + token = None; + } + } continue 'session; } }; @@ -524,90 +530,59 @@ async fn actor( info!("connected"); crate::update::set_token(token.clone().filter(|_| welcome.user.is_some())); tokio::spawn(crate::update::check(server.borrow().clone(), false)); - shared.media.ready(connection.clone(), event_sender.clone()); - if event_sender.send(NetworkEvent::Connected).await.is_err() { + media.ready(connection.clone(), events.clone()); + if events.send(NetworkEvent::Connected).await.is_err() { return; } if let Some(reply) = pending.take() { let _ = reply.send(Ok(welcome.user)); } - tokio::spawn(event_receive_loop( - connection.clone(), - event_sender.clone(), - shared.media.clone(), - )); - tokio::spawn(datagram_receive_loop( + tokio::spawn(receive::events( connection.clone(), - shared.media.clone(), + events.clone(), + media.clone(), )); - - loop { - tokio::select! { - command = command_receiver.recv() => match command { - Some(Command::Call(run)) => run(connection.clone()), - Some(Command::SignIn { token: next, reply }) => { - token = next; - pending = Some(reply); - shared.media.reset(); - connection.close(Close::Normal.code(), Close::Normal.reason().as_bytes()); - break; - } - Some(Command::Upload { community_id, path, maximum, reply }) => { - let connection = connection.clone(); - - answer(reply, async move { upload(&connection, community_id, &path, maximum).await }); - } - Some(Command::Download { blob, reply }) => { - let connection = connection.clone(); - let fetches = shared.fetches.clone(); - - answer(reply, async move { fetches.memory(&connection, blob).await }); - } - Some(Command::Stage { path, progress, reply }) => { - let connection = connection.clone(); - - answer(reply, async move { stage(&connection, &path, &progress).await }); - } - Some(Command::BackupDownload { name, path, reply }) => { - let connection = connection.clone(); - let fetches = shared.fetches.clone(); - - answer(reply, async move { - let _permit = fetches.permit().await; - backup_download(&connection, &name, &path).await - }); - } - None => break 'session, - }, - - _ = server.changed() => { - attempt = 0; - token = None; - shared.media.reset(); - connection.close(Close::Normal.code(), Close::Normal.reason().as_bytes()); - break; + tokio::spawn(receive::datagrams(connection.clone(), media.clone())); + + tokio::select! { + sign = sign_in.recv() => match sign { + Some(SignIn { token: next, reply }) => { + token = next; + pending = Some(reply); + media.reset(); + Close::Normal.on(&connection); + continue 'session; } + None => break 'session, + }, - error = connection.closed() => { - warn!("disconnected: {error}"); - shared.media.lost(); + _ = server.changed() => { + attempt = 0; + token = None; + media.reset(); + Close::Normal.on(&connection); + continue 'session; + } - let event = LinkError::from(error); - let terminal = event.terminal(); + error = connection.closed() => { + warn!("disconnected: {error}"); + media.lost(); - if event_sender.send(NetworkEvent::Disconnected(event)).await.is_err() { - return; - } + let event = LinkError::from(error); + let terminal = event.terminal(); - if terminal { - while command_receiver.recv().await.is_some() {} - return; - } + if events.send(NetworkEvent::Disconnected(event)).await.is_err() { + return; + } - backoff(&mut attempt).await; - break; + if terminal { + halt(&mut sign_in).await; + return; } + + backoff(&mut attempt).await; + continue 'session; } } } diff --git a/crates/client/src/net/media.rs b/crates/client/src/net/media.rs index c7282af..47cdd93 100644 --- a/crates/client/src/net/media.rs +++ b/crates/client/src/net/media.rs @@ -1,5 +1,7 @@ use std::{ collections::HashMap, + future::Future, + mem, sync::{Arc, Mutex, MutexGuard}, time::Duration, }; @@ -10,32 +12,33 @@ use common::{ Call, JoinVoice, LeaveVoice, ListShares, ReportLoss, RequestKeyframe, StartShare, StopShare, UnwatchShare, WatchShare, }, - datagram::{Packet, RELAY_PREFIX}, + datagram::Packet, event::{Event, Media as Down}, model::Id, - share::{Kind, Mode, Quality, Source}, + share::{Codec, Kind, Mode, Quality, Source}, + stats::ShareSample, }; use quinn::Connection; -use tokio::{runtime::Handle, sync::mpsc}; +use tokio::{ + runtime::Handle, + sync::{mpsc, watch}, +}; use tracing::warn; use crate::{ settings::{ShareSettings, VoiceSettings}, share::{ Target, - audio::AudioApp, - audio_capture, - encode::capabilities, - session::{ShareSample, Sharing, Tick, WatchQuality, Watching}, + send::Sharing, + watch::{Tick, WatchQuality, Watching}, }, - voice::{self, Voice, VoiceSample, audio::Choice}, + voice::{self, VoiceSample, audio::Choice}, }; -use super::{link::call, *}; +use super::{Fail, Levels, NetworkEvent, NetworkHandle, link::call}; const TICK: Duration = Duration::from_secs(1); -const WAIT_STEP: Duration = Duration::from_millis(100); -const WAIT_STEPS: u32 = 50; +const WAIT: Duration = Duration::from_secs(5); #[derive(Clone)] struct Want { @@ -46,42 +49,157 @@ struct Want { } #[derive(Default)] -struct Inner { - epoch: u64, - connection: Option, - want_voice: Option, - voice: Option, - joining: u32, - mic_test: Option, - sharing: HashMap, - reopening: HashMap)>, - watching: HashMap<(Id, Kind), Watching>, +enum VoiceState { + #[default] + Off, + MicTest(voice::Voice), + Joining(Want), + Joined { + want: Want, + live: Option, + }, } -impl Inner { - fn current(&self, epoch: u64) -> bool { - self.connection.is_some() && self.epoch == epoch +impl VoiceState { + fn idle(&self) -> bool { + matches!(self, Self::Off | Self::MicTest(_)) } - fn drop_calls(&mut self) { - self.voice = None; - self.sharing.clear(); - self.reopening.clear(); + fn joining(&self) -> Option { + match self { + Self::Joining(want) => Some(want.clone()), + _ => None, + } } - fn end_voice(&mut self) { - self.drop_calls(); - self.want_voice = None; - self.watching.clear(); + fn want_mut(&mut self) -> Option<&mut Want> { + match self { + Self::Joining(want) | Self::Joined { want, .. } => Some(want), + _ => None, + } + } + + fn live(&self) -> Option<&voice::Voice> { + match self { + Self::Joined { live, .. } => live.as_ref(), + _ => None, + } + } + + fn live_mut(&mut self) -> Option<&mut voice::Voice> { + match self { + Self::Joined { live, .. } => live.as_mut(), + _ => None, + } + } + + fn any(&self) -> Option<&voice::Voice> { + match self { + Self::MicTest(voice) => Some(voice), + _ => self.live(), + } + } + + fn any_mut(&mut self) -> Option<&mut voice::Voice> { + match self { + Self::MicTest(voice) => Some(voice), + _ => self.live_mut(), + } + } + + fn rejoin(&mut self) -> Option { + let want = self.want_mut()?.clone(); + *self = Self::Joining(want.clone()); + + Some(want) + } + + fn lose(&mut self) -> Option { + match self { + Self::Joined { live, .. } => live.take(), + _ => None, + } + } + + fn leave(&mut self) -> Option { + match self { + Self::MicTest(_) => None, + _ => match mem::take(self) { + Self::Joined { live, .. } => live, + _ => None, + }, + } + } +} + +enum Share { + Live(Sharing), + Reopening { source: Source, modes: Vec }, +} + +impl Share { + fn live(&self) -> Option<&Sharing> { + match self { + Self::Live(sharing) => Some(sharing), + Self::Reopening { .. } => None, + } + } + + fn live_mut(&mut self) -> Option<&mut Sharing> { + match self { + Self::Live(sharing) => Some(sharing), + Self::Reopening { .. } => None, + } + } + + fn source(&self) -> Source { + match self { + Self::Live(sharing) => sharing.source(), + Self::Reopening { source, .. } => source.clone(), + } + } + + fn modes(&self) -> Vec { + match self { + Self::Live(sharing) => sharing.modes(), + Self::Reopening { modes, .. } => modes.clone(), + } + } +} + +#[derive(Default)] +struct Inner { + voice: VoiceState, + sharing: HashMap, + watching: HashMap<(Id, Kind), Watching>, +} + +#[derive(Default)] +struct Dropped { + _voice: Option, + _shares: Vec, + _watches: Vec, +} + +impl Inner { + fn lose(&mut self) -> Dropped { + Dropped { + _voice: self.voice.lose(), + _shares: self.sharing.drain().map(|(_, share)| share).collect(), + _watches: Vec::new(), + } } - fn install_voice(&mut self, mut voice: Voice, want: Want) { - voice.apply(&want.settings); - voice.set_muted(want.muted); - voice.set_deafened(want.deafened); - self.mic_test = None; - self.voice = Some(voice); - self.want_voice = Some(want); + fn end_call(&mut self) -> Dropped { + Dropped { + _voice: self.voice.leave(), + _shares: self.sharing.drain().map(|(_, share)| share).collect(), + _watches: self + .watching + .drain() + .map(|(_, watching)| watching) + .collect(), + } } fn watch_requests(&self, connection: &Connection) -> Vec<((Id, Kind), WatchShare)> { @@ -98,6 +216,7 @@ impl Inner { pub(super) struct Media { handle: Handle, + link: watch::Sender>, inner: Mutex, } @@ -105,6 +224,7 @@ impl Media { pub(super) fn new(handle: Handle) -> Arc { let media = Arc::new(Media { handle: handle.clone(), + link: watch::Sender::new(None), inner: Mutex::default(), }); handle.spawn(tick_loop(media.clone())); @@ -116,28 +236,36 @@ impl Media { self.inner.lock().unwrap() } - fn current(&self) -> Result<(Connection, u64), Fail> { - let inner = self.lock(); - let connection = inner.connection.clone().ok_or(Fail::Offline)?; + fn discard(&self, value: impl Send + 'static) { + self.handle.spawn_blocking(move || drop(value)); + } - Ok((connection, inner.epoch)) + fn live_connection(&self) -> Option { + (*self.link.borrow()).clone() } - async fn current_wait(&self) -> Result<(Connection, u64), Fail> { - for _ in 0..WAIT_STEPS { - if let Ok(current) = self.current() { - return Ok(current); - } - tokio::time::sleep(WAIT_STEP).await; - } + fn is_current(&self, connection: &Connection) -> bool { + self.link + .borrow() + .as_ref() + .is_some_and(|current| current.stable_id() == connection.stable_id()) + } + + pub(super) async fn connection(&self) -> Result { + let mut link = self.link.subscribe(); + let ready = tokio::time::timeout(WAIT, link.wait_for(Option::is_some)) + .await + .map_err(|_| Fail::Offline)? + .map_err(|_| Fail::Offline)?; - self.current() + (*ready).clone().ok_or(Fail::Offline) } - async fn run( - &self, - work: impl Future> + Send + 'static, - ) -> Result { + pub(super) async fn run(&self, work: Fut) -> Result + where + T: Send + 'static, + Fut: Future> + Send + 'static, + { self.handle.spawn(work).await.map_err(|_| Fail::Offline)? } @@ -146,107 +274,75 @@ impl Media { connection: Connection, events: mpsc::Sender, ) { - let (epoch, want) = { + let rejoin = { let mut inner = self.lock(); - inner.epoch += 1; - inner.connection = Some(connection.clone()); - (inner.epoch, inner.want_voice.clone()) + self.link.send_replace(Some(connection.clone())); + inner.voice.rejoin() }; - if let Some(want) = want { - tokio::spawn(self.clone().rejoin(connection, epoch, want, events)); + if let Some(want) = rejoin { + tokio::spawn(self.clone().rejoin(connection, want, events)); } } pub(super) fn lost(&self) { - let mut inner = self.lock(); - inner.connection = None; - inner.drop_calls(); + self.link.send_replace(None); + let dropped = self.lock().lose(); + self.discard(dropped); } pub(super) fn reset(&self) { - let mut inner = self.lock(); - inner.connection = None; - inner.end_voice(); + self.link.send_replace(None); + let dropped = self.lock().end_call(); + self.discard(dropped); } async fn rejoin( self: Arc, connection: Connection, - epoch: u64, want: Want, events: mpsc::Sender, ) { - let joined = join(&connection, want.community_id).await; - let next = { - let mut inner = self.lock(); - if !inner.current(epoch) { - return; - } - let ours = inner - .want_voice - .as_ref() - .is_some_and(|wanted| wanted.community_id == want.community_id) - && inner.voice.is_none(); - match joined { - Ok(_) if ours => Rejoin::Install, - Ok(_) => { - if inner.want_voice.is_none() && inner.joining == 0 { - tokio::spawn(send_quietly(connection.clone(), LeaveVoice)); - } - Rejoin::Skip - } - Err(error) if ours => { - warn!("voice rejoin failed: {error}"); - inner.want_voice = None; - inner.watching.clear(); - Rejoin::Ended - } - Err(_) => Rejoin::Skip, - } - }; - - let watches = match next { - Rejoin::Skip => return, - Rejoin::Ended => None, - Rejoin::Install => { - let voice = voice::start(Some(connection.clone()), &want.settings); - let mut inner = self.lock(); - let wanted = inner.want_voice.clone(); - match wanted { - Some(wanted) - if inner.current(epoch) - && wanted.community_id == want.community_id - && inner.voice.is_none() => - { - inner.install_voice(voice, wanted); - Some(inner.watch_requests(&connection)) - } - _ => return, - } - } - }; - - let event = match watches { - Some(requests) => { + let event = match self + .clone() + .join_call(connection.clone(), want.community_id, want.settings) + .await + { + Ok(_) => { + let requests = self.lock().watch_requests(&connection); for (key, request) in requests { let media = self.clone(); let connection = connection.clone(); tokio::spawn(async move { if call(&connection, request).await.is_err() { - media.lock().watching.remove(&key); + let removed = media.lock().watching.remove(&key); + media.discard(removed); } }); } NetworkEvent::VoiceRejoined } - None => NetworkEvent::VoiceEnded, + Err(error) => { + if !self.is_current(&connection) { + return; + } + warn!("voice rejoin failed: {error}"); + let watches: Vec = self + .lock() + .watching + .drain() + .map(|(_, watching)| watching) + .collect(); + self.discard(watches); + NetworkEvent::VoiceEnded + } }; let _ = events.send(event).await; } pub(super) fn pushed(&self, event: &Event) { if let Event::ShareStopped { user_id, kind, .. } = event { - self.lock().watching.remove(&(*user_id, *kind)); + let removed = self.lock().watching.remove(&(*user_id, *kind)); + self.discard(removed); } } @@ -254,38 +350,41 @@ impl Media { let mut inner = self.lock(); match media { Down::Layers { kind, layers } => { - if let Some(sharing) = inner.sharing.get_mut(kind) { + if let Some(sharing) = inner.sharing.get_mut(kind).and_then(Share::live_mut) { sharing.set_layers(layers); } + false } Down::Keyframe { kind, layer, recover, } => { - if let Some(sharing) = inner.sharing.get(kind) { + if let Some(sharing) = inner.sharing.get(kind).and_then(Share::live) { sharing.keyframe(*layer, *recover); } + false } Down::Loss { kind, permille } => { - if let Some(sharing) = inner.sharing.get(kind) { + if let Some(sharing) = inner.sharing.get(kind).and_then(Share::live) { sharing.report_loss(*permille); } + false } Down::VoiceEnded => { - inner.end_voice(); - return true; + let dropped = inner.end_call(); + drop(inner); + self.discard(dropped); + true } } - - false } - pub(super) fn receive(&self, datagram: &Bytes, from: &[u8; RELAY_PREFIX], packet: Packet<'_>) { + pub(super) fn receive(&self, datagram: &Bytes, from: Id, packet: Packet<'_>) { let inner = self.lock(); let kind = match packet { Packet::Voice { seq, opus } => { - if let Some(voice) = &inner.voice { + if let Some(voice) = inner.voice.live() { voice.receive(from, seq, opus); } return; @@ -296,14 +395,13 @@ impl Media { Packet::Ack { kind, layer, ts_ms, .. } => { - if let Some(sharing) = inner.sharing.get(&kind) { + if let Some(sharing) = inner.sharing.get(&kind).and_then(Share::live) { sharing.ack(layer, ts_ms); } return; } }; - let key = (Id::from_be_bytes(*from), kind); - if let Some(watching) = inner.watching.get(&key) { + if let Some(watching) = inner.watching.get(&(from, kind)) { watching.receive(datagram, &packet); } } @@ -313,42 +411,92 @@ impl Media { community_id: Id, settings: VoiceSettings, ) -> Result, Fail> { - self.lock().joining += 1; - let result = self.join_voice_inner(community_id, settings).await; - self.lock().joining -= 1; - - result - } - - async fn join_voice_inner( - &self, - community_id: Id, - settings: VoiceSettings, - ) -> Result, Fail> { - let (connection, epoch) = self.current_wait().await?; + let connection = self.connection().await?; let participants = join(&connection, community_id).await?; - let voice = voice::start(Some(connection), &settings); - let mut inner = self.lock(); - if !inner.current(epoch) { - return Err(Fail::Offline); - } + let mut voice = voice::start(Some(connection.clone()), &settings); let want = Want { community_id, settings, muted: false, deafened: false, }; - inner.install_voice(voice, want); + tune(&mut voice, &want); + let mut inner = self.lock(); + if !self.is_current(&connection) { + drop(inner); + self.discard(voice); + return Err(Fail::Offline); + } + let replaced = mem::replace( + &mut inner.voice, + VoiceState::Joined { + want, + live: Some(voice), + }, + ); + drop(inner); + self.discard(replaced); Ok(participants) } - async fn leave_voice(self: Arc) -> Result<(), Fail> { - let connection = { - let mut inner = self.lock(); - inner.end_voice(); - inner.connection.clone().ok_or(Fail::Offline)? + async fn join_call( + self: Arc, + connection: Connection, + community_id: Id, + settings: VoiceSettings, + ) -> Result, Fail> { + let participants = match join(&connection, community_id).await { + Ok(participants) => participants, + Err(error) => { + self.unjoin(&connection, community_id); + return Err(error); + } }; + let mut voice = voice::start(Some(connection.clone()), &settings); + + let mut inner = self.lock(); + let current = self.is_current(&connection); + if let Some(want) = inner + .voice + .joining() + .filter(|want| want.community_id == community_id && current) + { + tune(&mut voice, &want); + inner.voice = VoiceState::Joined { + want, + live: Some(voice), + }; + return Ok(participants); + } + let left = current && inner.voice.idle(); + drop(inner); + self.discard(voice); + if left { + tokio::spawn(send_quietly(connection, LeaveVoice)); + } + + Err(Fail::Offline) + } + + fn unjoin(&self, connection: &Connection, community_id: Id) { + if !self.is_current(connection) { + return; + } + let mut inner = self.lock(); + if inner + .voice + .joining() + .is_some_and(|want| want.community_id == community_id) + { + inner.voice = VoiceState::Off; + } + } + + async fn leave_voice(self: Arc) -> Result<(), Fail> { + let dropped = self.lock().end_call(); + self.discard(dropped); + let connection = self.live_connection().ok_or(Fail::Offline)?; call(&connection, LeaveVoice).await } @@ -359,12 +507,11 @@ impl Media { settings: ShareSettings, target: Option, ) -> Result<(), Fail> { - let (connection, epoch) = self.current_wait().await?; - let top = settings.top(kind); + let connection = self.connection().await?; let sharing = Sharing::start( connection.clone(), kind, - top, + settings.top(kind), settings.encode(), settings.audio_mode(), target, @@ -373,75 +520,137 @@ impl Media { .await .map_err(Fail::Io)?; let source = sharing.source(); - { + let replaced = { let mut inner = self.lock(); - if !inner.current(epoch) { + if !self.is_current(&connection) { + self.discard(sharing); return Err(Fail::Offline); } - inner.sharing.insert(kind, sharing); - } + inner.sharing.insert(kind, Share::Live(sharing)) + }; + self.discard(replaced); let result = call(&connection, StartShare { kind, source }).await; if result.is_err() { - self.lock().sharing.remove(&kind); + let removed = self.lock().sharing.remove(&kind); + self.discard(removed); } result } async fn update_share(self: Arc, settings: ShareSettings) -> Result<(), Fail> { - let (connection, _) = self.current_wait().await?; - let reopen: Vec = { - let mut inner = self.lock(); - let reopen: Vec = inner - .sharing - .iter() - .filter(|(kind, sharing)| sharing.reopens(settings.top(**kind))) - .map(|(kind, _)| *kind) - .collect(); - for kind in &reopen { - if let Some(sharing) = inner.sharing.remove(kind) { - inner - .reopening - .insert(*kind, (sharing.source(), sharing.modes())); - } - } - reopen - }; + let connection = self.connection().await?; + let reopen: Vec = self + .lock() + .sharing + .iter() + .filter(|(kind, share)| { + share + .live() + .is_some_and(|sharing| sharing.reopens(settings.top(**kind))) + }) + .map(|(kind, _)| *kind) + .collect(); + + let mut failure = None; for kind in reopen { - let started = self.clone().start_share(kind, settings.clone(), None).await; - self.lock().reopening.remove(&kind); - started?; + let replaced = { + let mut inner = self.lock(); + let Some(sharing) = inner.sharing.get(&kind).and_then(Share::live) else { + continue; + }; + let reopening = Share::Reopening { + source: sharing.source(), + modes: sharing.modes(), + }; + inner.sharing.insert(kind, reopening) + }; + self.discard(replaced); + + if let Err(error) = self.clone().start_share(kind, settings.clone(), None).await { + let removed = self.lock().sharing.remove(&kind); + self.discard(removed); + tokio::spawn(send_quietly(connection.clone(), StopShare { kind })); + failure.get_or_insert(error); + } } - let sources = { + + let mut retired = Vec::new(); + let sources: Vec<(Kind, Result)> = { let mut inner = self.lock(); - let mut sources = Vec::new(); - for (kind, sharing) in &mut inner.sharing { - let source = sharing - .update( - &connection, - settings.top(*kind), - settings.encode(), - settings.audio_mode(), - ) - .map_err(Fail::Io)?; - sources.push((*kind, source)); - } - sources + inner + .sharing + .iter_mut() + .filter_map(|(kind, share)| { + share.live_mut().map(|sharing| { + let source = sharing + .update( + &connection, + settings.top(*kind), + settings.encode(), + settings.audio_mode(), + ) + .map(|(source, old)| { + retired.push(old); + source + }) + .map_err(Fail::Io); + (*kind, source) + }) + }) + .collect() }; + self.discard(retired); for (kind, source) in sources { - call(&connection, StartShare { kind, source }).await?; + let result = match source { + Ok(source) => call(&connection, StartShare { kind, source }).await, + Err(error) => Err(error), + }; + if let Err(error) = result { + failure.get_or_insert(error); + } } - Ok(()) + failure.map_or(Ok(()), Err) } async fn stop_share(self: Arc, kind: Kind) -> Result<(), Fail> { - self.lock().sharing.remove(&kind); - let (connection, _) = self.current_wait().await?; + let removed = self.lock().sharing.remove(&kind); + self.discard(removed); + let connection = self.connection().await?; call(&connection, StopShare { kind }).await } + + async fn watch(self: Arc, key: (Id, Kind), watching: Watching) -> Result<(), Fail> { + let connection = self.connection().await?; + let quality = watching.wanted(); + let replaced = { + let mut inner = self.lock(); + if !self.is_current(&connection) { + self.discard(watching); + return Err(Fail::Offline); + } + watching.connect(connection.clone()); + inner.watching.insert(key, watching) + }; + self.discard(replaced); + + let result = call(&connection, watch_request(key.0, key.1, quality)).await; + if result.is_err() { + let removed = self.lock().watching.remove(&key); + self.discard(removed); + } + + result + } +} + +fn tune(voice: &mut voice::Voice, want: &Want) { + voice.apply(&want.settings); + voice.set_muted(want.muted); + voice.set_deafened(want.deafened); } fn watch_request(user_id: Id, kind: Kind, quality: Quality) -> WatchShare { @@ -449,29 +658,17 @@ fn watch_request(user_id: Id, kind: Kind, quality: Quality) -> WatchShare { user_id, kind, quality, - decode: capabilities().decode.clone(), + decode: Codec::ALL.to_vec(), } } -enum Rejoin { - Install, - Ended, - Skip, -} - async fn join(connection: &Connection, community_id: Id) -> Result, Fail> { - let request = JoinVoice { community_id }; - - call(connection, request).await + call(connection, JoinVoice { community_id }).await } async fn send_quietly(connection: Connection, request: C) { if let Err(error) = call(&connection, request).await { - let name = std::any::type_name::() - .rsplit("::") - .next() - .unwrap_or_default(); - warn!("media request {name} failed: {error}"); + warn!("media request failed: {error}"); } } @@ -480,20 +677,19 @@ async fn tick_loop(media: Arc) { loop { ticker.tick().await; end_lost_shares(&media); + let Some(connection) = media.live_connection() else { + continue; + }; let mut inner = media.lock(); - let connection = inner.connection.clone(); for ((user_id, kind), watching) in inner.watching.iter_mut() { for tick in watching.tick() { - let Some(connection) = connection.clone() else { - continue; - }; match tick { Tick::Quality(quality) => tokio::spawn(send_quietly( - connection, + connection.clone(), watch_request(*user_id, *kind, quality), )), Tick::Keyframe { recover } => tokio::spawn(send_quietly( - connection, + connection.clone(), RequestKeyframe { user_id: *user_id, kind: *kind, @@ -501,7 +697,7 @@ async fn tick_loop(media: Arc) { }, )), Tick::Loss(permille) => tokio::spawn(send_quietly( - connection, + connection.clone(), ReportLoss { user_id: *user_id, kind: *kind, @@ -515,23 +711,18 @@ async fn tick_loop(media: Arc) { } fn end_lost_shares(media: &Media) { - let (lost, connection) = { - let mut inner = media.lock(); - let kinds: Vec = inner - .sharing - .iter() - .filter(|(_, sharing)| sharing.ended()) - .map(|(kind, _)| *kind) - .collect(); - let lost: Vec<(Kind, Sharing)> = kinds - .into_iter() - .filter_map(|kind| Some((kind, inner.sharing.remove(&kind)?))) - .collect(); - (lost, inner.connection.clone()) - }; - for (kind, sharing) in lost { + let lost: Vec = media + .lock() + .sharing + .iter() + .filter(|(_, share)| share.live().is_some_and(Sharing::ended)) + .map(|(kind, _)| *kind) + .collect(); + let connection = media.live_connection(); + for kind in lost { warn!(?kind, "share source lost"); - tokio::task::spawn_blocking(move || drop(sharing)); + let removed = media.lock().sharing.remove(&kind); + media.discard(removed); if let Some(connection) = connection.clone() { tokio::spawn(send_quietly(connection, StopShare { kind })); } @@ -539,18 +730,14 @@ fn end_lost_shares(media: &Media) { } impl NetworkHandle { - fn media(&self) -> &Arc { - &self.shared.media - } - pub async fn join_voice( &self, community_id: Id, settings: &VoiceSettings, ) -> Result, Fail> { - self.media() + self.media .run( - self.media() + self.media .clone() .join_voice(community_id, settings.clone()), ) @@ -558,130 +745,116 @@ impl NetworkHandle { } pub async fn leave_voice(&self) -> Result<(), Fail> { - self.media().run(self.media().clone().leave_voice()).await + self.media.run(self.media.clone().leave_voice()).await } pub fn set_voice_settings(&self, settings: &VoiceSettings) { - let mut inner = self.media().lock(); - if let Some(want) = inner.want_voice.as_mut() { + let mut inner = self.media.lock(); + if let Some(want) = inner.voice.want_mut() { want.settings = settings.clone(); } - if let Some(voice) = inner.voice.as_mut() { - voice.apply(settings); - } - if let Some(voice) = inner.mic_test.as_mut() { + if let Some(voice) = inner.voice.any_mut() { voice.apply(settings); } } pub fn start_mic_test(&self, settings: &VoiceSettings) { - if self.media().lock().voice.is_some() { + if !self.media.lock().voice.idle() { return; } let voice = voice::start(None, settings); - let mut inner = self.media().lock(); - if inner.voice.is_none() { - inner.mic_test = Some(voice); + let mut inner = self.media.lock(); + if !inner.voice.idle() { + drop(inner); + self.media.discard(voice); + return; } + let replaced = mem::replace(&mut inner.voice, VoiceState::MicTest(voice)); + drop(inner); + self.media.discard(replaced); } pub fn stop_mic_test(&self) { - self.media().lock().mic_test = None; - } - - pub fn play_chime(&self, settings: &VoiceSettings) { - voice::play_chime(settings); - } - - pub fn play_notification(&self, settings: &VoiceSettings) { - voice::play_yumush(settings); - } - - pub fn play_ring(&self, settings: &VoiceSettings) { - voice::play_ring(settings); + let mut inner = self.media.lock(); + if !matches!(inner.voice, VoiceState::MicTest(_)) { + return; + } + let stopped = mem::take(&mut inner.voice); + drop(inner); + self.media.discard(stopped); } pub fn voice_level_db(&self) -> Option { - let inner = self.media().lock(); - - inner - .voice - .as_ref() - .or(inner.mic_test.as_ref()) - .map(Voice::level_db) + self.media.lock().voice.any().map(voice::Voice::level_db) } pub fn voice_sample(&self) -> Option { - self.media().lock().voice.as_ref().map(Voice::sample) + self.media.lock().voice.live().map(voice::Voice::sample) } pub fn set_talking(&self, talking: bool) { - if let Some(voice) = &self.media().lock().voice { + if let Some(voice) = self.media.lock().voice.live() { voice.set_talking(talking); } } pub fn set_muted(&self, muted: bool) { - let mut inner = self.media().lock(); - if let Some(want) = inner.want_voice.as_mut() { + let mut inner = self.media.lock(); + if let Some(want) = inner.voice.want_mut() { want.muted = muted; } - if let Some(voice) = &inner.voice { + if let Some(voice) = inner.voice.live() { voice.set_muted(muted); } } pub fn set_deafened(&self, deafened: bool) { - let mut inner = self.media().lock(); - if let Some(want) = inner.want_voice.as_mut() { + let mut inner = self.media.lock(); + if let Some(want) = inner.voice.want_mut() { want.deafened = deafened; } - if let Some(voice) = &inner.voice { + if let Some(voice) = inner.voice.live() { voice.set_deafened(deafened); } } pub fn levels(&self) -> Levels { - let inner = self.media().lock(); + let inner = self.media.lock(); Levels { - voice: inner.voice.as_ref().map(Voice::levels).unwrap_or_default(), + voice: inner + .voice + .live() + .map(voice::Voice::levels) + .unwrap_or_default(), own: inner .voice - .as_ref() - .map(Voice::own_level) + .live() + .map(voice::Voice::own_level) .unwrap_or_default(), - own_sending: inner.voice.as_ref().is_some_and(Voice::own_sending), + own_sending: inner.voice.live().is_some_and(voice::Voice::own_sending), watching: inner .watching .iter() .filter(|((_, kind), _)| *kind == Kind::Screen) .map(|((user_id, _), watching)| (*user_id, watching.level())) .collect(), - sharing: inner.sharing.get(&Kind::Screen).map(Sharing::level), + sharing: inner + .sharing + .get(&Kind::Screen) + .and_then(Share::live) + .map(Sharing::level), } } - pub async fn start_share( - &self, - settings: &ShareSettings, - target: Option, - ) -> Result<(), Fail> { - self.start(Kind::Screen, settings, target).await - } - - pub async fn start_camera(&self, settings: &ShareSettings) -> Result<(), Fail> { - self.start(Kind::Camera, settings, None).await - } - - async fn start( + pub async fn start( &self, kind: Kind, settings: &ShareSettings, target: Option, ) -> Result<(), Fail> { - self.media() + self.media .run( - self.media() + self.media .clone() .start_share(kind, settings.clone(), target), ) @@ -689,53 +862,25 @@ impl NetworkHandle { } pub async fn update_share(&self, settings: &ShareSettings) -> Result<(), Fail> { - self.media() - .run(self.media().clone().update_share(settings.clone())) - .await - } - - pub async fn stop_share(&self) -> Result<(), Fail> { - self.stop(Kind::Screen).await - } - - pub async fn stop_camera(&self) -> Result<(), Fail> { - self.stop(Kind::Camera).await - } - - async fn stop(&self, kind: Kind) -> Result<(), Fail> { - self.media() - .run(self.media().clone().stop_share(kind)) + self.media + .run(self.media.clone().update_share(settings.clone())) .await } - pub fn sharing(&self) -> bool { - self.media().lock().sharing.contains_key(&Kind::Screen) + pub async fn stop(&self, kind: Kind) -> Result<(), Fail> { + self.media.run(self.media.clone().stop_share(kind)).await } - pub fn camera_on(&self) -> bool { - self.share_source(Kind::Camera).is_some() + pub fn sharing_any(&self) -> bool { + !self.media.lock().sharing.is_empty() } pub fn share_source(&self, kind: Kind) -> Option { - let inner = self.media().lock(); - inner - .sharing - .get(&kind) - .map(Sharing::source) - .or_else(|| inner.reopening.get(&kind).map(|(source, _)| source.clone())) + self.media.lock().sharing.get(&kind).map(Share::source) } pub fn share_modes(&self, kind: Kind) -> Option> { - let inner = self.media().lock(); - inner - .sharing - .get(&kind) - .map(Sharing::modes) - .or_else(|| inner.reopening.get(&kind).map(|(_, modes)| modes.clone())) - } - - pub fn sharing_any(&self) -> bool { - !self.media().lock().sharing.is_empty() + self.media.lock().sharing.get(&kind).map(Share::modes) } pub async fn shares(&self, community_id: Id) -> Result, Fail> { @@ -751,46 +896,28 @@ impl NetworkHandle { volume: f32, choice: Choice, ) -> Result<(), Fail> { - let media = self.media().clone(); - let key = (user_id, kind); let watching = Watching::new(user_id, kind, watch, top, volume, choice); - let quality = watching.wanted(); - self.media() - .run(async move { - let (connection, epoch) = media.current_wait().await?; - { - let mut inner = media.lock(); - if !inner.current(epoch) { - return Err(Fail::Offline); - } - watching.connect(connection.clone()); - inner.watching.insert(key, watching); - } - let result = call(&connection, watch_request(key.0, kind, quality)).await; - if result.is_err() { - media.lock().watching.remove(&key); - } - - result - }) + self.media + .run(self.media.clone().watch((user_id, kind), watching)) .await } pub async fn unwatch_share(&self, user_id: Id, kind: Kind) -> Result<(), Fail> { - self.media().lock().watching.remove(&(user_id, kind)); + let removed = self.media.lock().watching.remove(&(user_id, kind)); + self.media.discard(removed); self.call(UnwatchShare { user_id, kind }).await } pub fn set_watch_quality(&self, user_id: Id, kind: Kind, quality: WatchQuality) { - if let Some(watching) = self.media().lock().watching.get_mut(&(user_id, kind)) { + if let Some(watching) = self.media.lock().watching.get_mut(&(user_id, kind)) { watching.set_quality(quality); } } pub fn set_share_settings(&self, settings: &ShareSettings) { - for ((_, kind), watching) in self.media().lock().watching.iter_mut() { + for ((_, kind), watching) in self.media.lock().watching.iter_mut() { if *kind == Kind::Screen { watching.set_volume(settings.volume); } @@ -798,11 +925,12 @@ impl NetworkHandle { } pub fn share_sample(&self) -> ShareSample { - let mut inner = self.media().lock(); + let mut inner = self.media.lock(); let mut sending: Vec<_> = inner .sharing .iter() - .flat_map(|(kind, sharing)| sharing.stats().into_iter().map(|stat| (*kind, stat))) + .filter_map(|(kind, share)| share.live().map(|sharing| (*kind, sharing))) + .flat_map(|(kind, sharing)| sharing.stats().into_iter().map(move |stat| (kind, stat))) .collect(); sending.sort_by_key(|(kind, _)| *kind == Kind::Camera); let mut watching: Vec<_> = inner @@ -811,20 +939,17 @@ impl NetworkHandle { .map(|((user_id, kind), watching)| (*user_id, *kind, watching.stats())) .collect(); watching.sort_by_key(|(user_id, kind, _)| (*kind == Kind::Camera, *user_id)); + ShareSample { sending, watching } } pub fn show_share(&self, user_id: Id, kind: Kind, surface: u64, width: Option) { - if let Some(watching) = self.media().lock().watching.get(&(user_id, kind)) { + if let Some(watching) = self.media.lock().watching.get(&(user_id, kind)) { watching.show(surface, width); } } pub fn share_frame(&self, user_id: Id, kind: Kind) -> Option { - self.media().lock().watching.get(&(user_id, kind))?.frame() - } - - pub fn audio_apps(&self) -> Vec { - audio_capture::apps() + self.media.lock().watching.get(&(user_id, kind))?.frame() } } diff --git a/crates/client/src/net/mod.rs b/crates/client/src/net/mod.rs index bb27ccb..18074e1 100644 --- a/crates/client/src/net/mod.rs +++ b/crates/client/src/net/mod.rs @@ -1,19 +1,19 @@ -use std::{path::PathBuf, sync::Arc}; +use std::{future::Future, path::PathBuf, sync::Arc}; use common::{ - call::{Call, GetStorageUsage, Login, Logout, Register, Session}, + call::{Call, GetStorageUsage, Login, Logout, Register}, event::Event, - model::{Attachment, CommunityUsage, Id, Usage, User}, + model::{Attachment, CommunityUsage, Id, Staged, User, UserUsage}, open::Blob, }; -use tokio::sync::{mpsc, oneshot}; +use quinn::Connection; +use tokio::sync::{mpsc, oneshot, watch}; -mod datagram; -mod events; mod fail; mod fetch; mod link; mod media; +mod receive; pub use fail::{Fail, LinkError}; pub(crate) use link::dial; @@ -34,12 +34,6 @@ pub(crate) fn device_name() -> String { format!("{host} {}", std::env::consts::OS) } -#[derive(Clone)] -struct Shared { - media: Arc, - fetches: Arc, -} - #[derive(Default)] pub struct Levels { pub voice: Vec<(Id, Vec)>, @@ -59,39 +53,17 @@ pub enum NetworkEvent { Pushed(Box), } -enum Command { - Call(Box), - SignIn { - token: Option, - reply: oneshot::Sender, Fail>>, - }, - Upload { - community_id: Id, - path: PathBuf, - maximum: Option, - reply: oneshot::Sender>, - }, - Download { - blob: Blob, - reply: oneshot::Sender, Fail>>, - }, - Stage { - path: PathBuf, - progress: tokio::sync::watch::Sender, - reply: oneshot::Sender>, - }, - BackupDownload { - name: String, - path: PathBuf, - reply: oneshot::Sender>, - }, +pub(super) struct SignIn { + token: Option, + reply: oneshot::Sender, Fail>>, } #[derive(Clone)] pub struct NetworkHandle { - command_sender: mpsc::Sender, - server: tokio::sync::watch::Sender, - shared: Shared, + sign_in: mpsc::Sender, + server: watch::Sender, + media: Arc, + fetches: Arc, } impl NetworkHandle { @@ -107,46 +79,47 @@ impl NetworkHandle { }) } - async fn ask( - &self, - build: impl FnOnce(oneshot::Sender>) -> Command, - ) -> Result { + async fn switch(&self, token: Option) -> Result, Fail> { let (reply, response) = oneshot::channel(); - - self.command_sender - .send(build(reply)) + self.sign_in + .send(SignIn { token, reply }) .await .map_err(|_| Fail::Offline)?; response.await.map_err(|_| Fail::Offline)? } - pub async fn call(&self, call: C) -> Result { - call.validate()?; - - self.ask(|reply| { - Command::Call(Box::new(move |connection| { - link::answer(reply, async move { link::call(&connection, call).await }); - })) - }) - .await + async fn sign_in(&self, token: String) -> Result { + self.switch(Some(token)).await?.ok_or(Fail::Protocol) } - async fn switch(&self, token: Option) -> Result, Fail> { - self.ask(|reply| Command::SignIn { token, reply }).await + async fn on_connection( + &self, + work: impl FnOnce(Connection) -> Fut + Send + 'static, + ) -> Result + where + T: Send + 'static, + Fut: Future> + Send + 'static, + { + let media = self.media.clone(); + + self.media + .run(async move { + let connection = media.connection().await?; + work(connection).await + }) + .await } - async fn sign_in(&self, session: Session) -> Result<(User, String), Fail> { - self.switch(Some(session.token.clone())).await?; + pub async fn call(&self, call: C) -> Result { + call.validate()?; - Ok((session.user, session.token)) + self.on_connection(move |connection| async move { link::call(&connection, call).await }) + .await } pub async fn resume(&self, token: &str) -> Result<(User, String), Fail> { - let user = self - .switch(Some(token.to_string())) - .await? - .ok_or(Fail::Protocol)?; + let user = self.sign_in(token.to_string()).await?; Ok((user, token.to_string())) } @@ -168,8 +141,9 @@ impl NetworkHandle { invite: invite.map(str::to_string), }) .await?; + let user = self.sign_in(session.token.clone()).await?; - self.sign_in(session).await + Ok((user, session.token)) } pub async fn login(&self, username: &str, password: &str) -> Result<(User, String), Fail> { @@ -179,8 +153,9 @@ impl NetworkHandle { password: password.to_string(), }) .await?; + let user = self.sign_in(session.token.clone()).await?; - self.sign_in(session).await + Ok((user, session.token)) } pub async fn logout(&self) -> Result<(), Fail> { @@ -189,7 +164,7 @@ impl NetworkHandle { result } - pub async fn storage_usage(&self) -> Result<(Vec, Vec), Fail> { + pub async fn storage_usage(&self) -> Result<(Vec, Vec), Fail> { let usage = self.call(GetStorageUsage).await?; Ok((usage.users, usage.communities)) @@ -201,11 +176,8 @@ impl NetworkHandle { path: PathBuf, maximum: Option, ) -> Result { - self.ask(|reply| Command::Upload { - community_id, - path, - maximum, - reply, + self.on_connection(move |connection| async move { + link::upload(&connection, community_id, &path, maximum).await }) .await } @@ -220,27 +192,32 @@ impl NetworkHandle { } else { Blob::Attachment(attachment_id) }; - self.ask(|reply| Command::Download { blob, reply }).await + let fetches = self.fetches.clone(); + + self.on_connection( + move |connection| async move { fetches.download(&connection, blob).await }, + ) + .await } pub async fn stage_release( &self, path: PathBuf, - progress: tokio::sync::watch::Sender, - ) -> Result { - self.ask(|reply| Command::Stage { - path, - progress, - reply, + progress: watch::Sender, + ) -> Result { + self.on_connection(move |connection| async move { + link::stage(&connection, &path, &progress).await }) .await } pub async fn download_backup(&self, name: &str, path: PathBuf) -> Result<(), Fail> { - self.ask(|reply| Command::BackupDownload { - name: name.to_string(), - path, - reply, + let name = name.to_string(); + let fetches = self.fetches.clone(); + + self.on_connection(move |connection| async move { + let _permit = fetches.permit().await; + link::backup_download(&connection, &name, &path).await }) .await } diff --git a/crates/client/src/net/receive.rs b/crates/client/src/net/receive.rs new file mode 100644 index 0000000..07b8e02 --- /dev/null +++ b/crates/client/src/net/receive.rs @@ -0,0 +1,57 @@ +use std::sync::Arc; + +use common::{ + datagram::split, + event::Down, + frame::{self, DOWN_MAX, FrameError}, + transport::Close, +}; +use quinn::Connection; +use tokio::sync::mpsc; +use tracing::warn; + +use super::{NetworkEvent, media::Media}; + +pub(super) async fn events( + connection: Connection, + sender: mpsc::Sender, + media: Arc, +) { + let Ok(mut stream) = connection.accept_uni().await else { + return; + }; + + loop { + match frame::read::(&mut stream, DOWN_MAX).await { + Ok(Down::Event(event)) => { + if matches!(*event, common::event::Event::Release) { + crate::update::recheck(); + } + media.pushed(&event); + if sender.send(NetworkEvent::Pushed(event)).await.is_err() { + return; + } + } + Ok(Down::Media(down)) => { + if media.down(&down) && sender.send(NetworkEvent::VoiceEnded).await.is_err() { + return; + } + } + Err(error) => { + if matches!(error, FrameError::TooLarge { .. } | FrameError::Decode(_)) { + warn!("event stream broken: {error}"); + Close::Protocol.on(&connection); + } + return; + } + } + } +} + +pub(super) async fn datagrams(connection: Connection, media: Arc) { + while let Ok(datagram) = connection.read_datagram().await { + if let Some((from, packet)) = split(&datagram) { + media.receive(&datagram, from, packet); + } + } +} diff --git a/crates/client/src/settings.rs b/crates/client/src/settings.rs index 0c81538..1d5b12d 100644 --- a/crates/client/src/settings.rs +++ b/crates/client/src/settings.rs @@ -7,13 +7,13 @@ use common::{ string_enum, }; use gpui_kit::{ - App, Global, Pixels, + App, Pixels, component::{Theme as KitTheme, ThemeMode}, px, }; use crate::{ - gui::style::{Look, Theme}, + gui::style::{Theme, Tokens}, lang::{Lang, w}, read_config, share::{audio::AudioMode, encode::capabilities}, @@ -43,10 +43,6 @@ string_enum! { } } -pub struct Scale(pub FontSize); - -impl Global for Scale {} - impl FontSize { pub fn label(self) -> &'static str { match self { @@ -485,8 +481,7 @@ pub fn save(settings: &Settings) { } pub fn apply(theme: Theme, size: FontSize, cx: &mut App) { - cx.set_global(Look { theme, size }); - cx.set_global(Scale(size)); + cx.set_global(Tokens { theme, size }); let mode = if theme.colors().dark { ThemeMode::Dark } else { diff --git a/crates/client/src/share/audio_capture.rs b/crates/client/src/share/audio_capture.rs index 352c479..4de7e2f 100644 --- a/crates/client/src/share/audio_capture.rs +++ b/crates/client/src/share/audio_capture.rs @@ -4,29 +4,33 @@ use std::{ error::Error, process, rc::Rc, - sync::atomic::{AtomicBool, Ordering}, - time::Duration, + sync::{ + Arc, Mutex, + atomic::{AtomicBool, Ordering}, + }, }; -use common::constant::{SHARE_AUDIO_CHANNELS, VOICE_SAMPLE_RATE}; +use common::constant::SHARE_AUDIO_CHANNELS; use pipewire as pw; use pw::{ - core::CoreRc, - link::Link, - loop_::Timeout, - properties::properties, - registry::GlobalObject, - spa, - stream::{StreamBox, StreamFlags, StreamState}, - types::ObjectType, + core::CoreRc, link::Link, loop_::Timeout, properties::properties, registry::GlobalObject, spa, + stream::StreamBox, stream::StreamFlags, types::ObjectType, }; use spa::{pod::Pod, utils::dict::DictRef}; use tracing::warn; use super::audio::{AudioApp, AudioKind, AudioMode, is_excluded, is_picked}; -use crate::voice::audio::{Worker, supervise}; +use crate::{ + voice::{ + Capture, + audio::{ + pw::{self as helpers, Node}, + record, + }, + }, + worker::{STOP_CHECK, Worker, supervise}, +}; -const STOP_CHECK: Duration = Duration::from_millis(100); const OWN_PREFIX: &str = "yumush"; const APP_CLASS: &str = "Stream/Output/Audio"; const SKIPPED_ROLES: [&str; 2] = ["Communication", "Phone"]; @@ -44,17 +48,6 @@ impl AudioKind { pub type AudioCapture = Worker; -#[derive(Default)] -struct Node { - id: u32, - name: String, - class: String, - role: String, - process: String, - app: String, - media: String, -} - impl Node { fn pid(&self) -> Option { self.process.parse().ok() @@ -76,7 +69,7 @@ struct Routing { } pub fn apps() -> Vec { - let nodes = nodes().unwrap_or_default(); + let nodes = helpers::nodes().unwrap_or_default(); let own = process::id().to_string(); let mut instances: BTreeMap<(String, Option), Vec> = BTreeMap::new(); let mut devices = Vec::new(); @@ -118,9 +111,9 @@ pub fn apps() -> Vec { pub fn start(mode: AudioMode, output: rtrb::Producer) -> AudioCapture { Worker::spawn("share-audio", move |stop| { - let output = Rc::new(RefCell::new(output)); + let output: Capture = Arc::new(Mutex::new(output)); let is_sink = match &mode { - AudioMode::Device(name) => nodes() + AudioMode::Device(name) => helpers::nodes() .unwrap_or_default() .iter() .any(|node| &node.name == name && node.class == "Audio/Sink"), @@ -130,98 +123,6 @@ pub fn start(mode: AudioMode, output: rtrb::Producer) -> AudioCapture { }) } -fn nodes() -> Result, Box> { - pw::init(); - let mainloop = pw::main_loop::MainLoopRc::new(None)?; - let context = pw::context::ContextRc::new(&mainloop, None)?; - let core = context.connect_rc(None)?; - let registry = core.get_registry_rc()?; - - let found = Rc::new(RefCell::new(Vec::new())); - let done = Rc::new(Cell::new(false)); - let failed = Rc::new(Cell::new(false)); - - let pending = core.sync(0)?; - - let _core_listener = core - .add_listener_local() - .done({ - let done = done.clone(); - let mainloop = mainloop.clone(); - move |id, seq| { - if id == pw::core::PW_ID_CORE && seq == pending { - done.set(true); - mainloop.quit(); - } - } - }) - .error({ - let done = done.clone(); - let failed = failed.clone(); - let mainloop = mainloop.clone(); - move |_, _, _, _| { - failed.set(true); - done.set(true); - mainloop.quit(); - } - }) - .register(); - - let _registry_listener = registry - .add_listener_local() - .global({ - let found = found.clone(); - move |global| { - if let Some(node) = node_of(global) { - found.borrow_mut().push(node); - } - } - }) - .register(); - - while !done.get() { - mainloop.run(); - } - - if failed.get() { - return Err("pipewire share scan".into()); - } - Ok(found.take()) -} - -fn node_of(global: &GlobalObject<&DictRef>) -> Option { - if !matches!(global.type_, ObjectType::Node) { - return None; - } - let props = global.props?; - let name = props.get(*pw::keys::NODE_NAME)?; - let description = props.get(*pw::keys::NODE_DESCRIPTION).unwrap_or(name); - Some(Node { - id: global.id, - name: name.to_string(), - class: props - .get(*pw::keys::MEDIA_CLASS) - .unwrap_or_default() - .to_string(), - role: props - .get(*pw::keys::MEDIA_ROLE) - .unwrap_or_default() - .to_string(), - process: props - .get(*pw::keys::APP_PROCESS_ID) - .unwrap_or_default() - .to_string(), - app: props - .get(*pw::keys::APP_NAME) - .unwrap_or(description) - .to_string(), - media: props - .get(*pw::keys::MEDIA_NAME) - .unwrap_or_default() - .to_string(), - }) -} - fn port_of(global: &GlobalObject<&DictRef>) -> Option { if !matches!(global.type_, ObjectType::Port) { return None; @@ -236,7 +137,7 @@ fn port_of(global: &GlobalObject<&DictRef>) -> Option { impl Routing { fn add(&mut self, global: &GlobalObject<&DictRef>) { - if let Some(node) = node_of(global).filter(|node| node.class == APP_CLASS) { + if let Some(node) = helpers::node_of(global).filter(|node| node.class == APP_CLASS) { self.streams.insert(node.id, node); } if let Some(port) = port_of(global) { @@ -249,17 +150,20 @@ impl Routing { self.ports.remove(&id); } - fn sync(&mut self, own: u32, mode: &AudioMode, core: &CoreRc) { + fn sync(&mut self, own: u32, own_pid: &str, mode: &AudioMode, core: &CoreRc) { self.links.retain(|(output, input), _| { self.ports.contains_key(output) && self.ports.contains_key(input) }); + self.failed.retain(|(output, input)| { + self.ports.contains_key(output) && self.ports.contains_key(input) + }); let mut wanted = Vec::new(); for (output_id, output) in self.ports.iter().filter(|(_, port)| port.output) { let eligible = self .streams .get(&output.node) - .is_some_and(|node| eligible(node, mode)); + .is_some_and(|node| eligible(node, own_pid, mode)); if !eligible { continue; } @@ -292,10 +196,9 @@ impl Routing { } } -fn eligible(node: &Node, mode: &AudioMode) -> bool { - let own_process = process::id().to_string(); +fn eligible(node: &Node, own_pid: &str, mode: &AudioMode) -> bool { let foreign = !(SKIPPED_ROLES.contains(&node.role.as_str()) - || node.process == own_process + || node.process == own_pid || node.name.starts_with(OWN_PREFIX) || node.name.contains("echo-cancel")); foreign @@ -331,42 +234,16 @@ fn create_link( Ok(core.create_object::("link-factory", &props)?) } -fn format_values() -> Option> { - let mut info = spa::param::audio::AudioInfoRaw::new(); - info.set_format(spa::param::audio::AudioFormat::F32LE); - info.set_rate(VOICE_SAMPLE_RATE); - info.set_channels(SHARE_AUDIO_CHANNELS as u32); - let mut position = [0; spa::sys::SPA_AUDIO_MAX_CHANNELS as usize]; - position[0] = spa::sys::SPA_AUDIO_CHANNEL_FL; - position[1] = spa::sys::SPA_AUDIO_CHANNEL_FR; - info.set_position(position); - - let object = spa::pod::Object { - type_: spa::utils::SpaTypes::ObjectParamFormat.as_raw(), - id: spa::param::ParamType::EnumFormat.as_raw(), - properties: info.into(), - }; - let (cursor, _) = spa::pod::serialize::PodSerializer::serialize( - std::io::Cursor::new(Vec::new()), - &spa::pod::Value::Object(object), - ) - .ok()?; - - Some(cursor.into_inner()) -} - fn run( mode: &AudioMode, - output: &Rc>>, + output: &Capture, is_sink: bool, stop: &AtomicBool, ) -> Result<(), Box> { - pw::init(); - let mainloop = pw::main_loop::MainLoopRc::new(None)?; - let context = pw::context::ContextRc::new(&mainloop, None)?; - let core = context.connect_rc(None)?; + let (mainloop, _context, core) = helpers::connect()?; let registry = core.get_registry_rc()?; let failed = Rc::new(Cell::new(false)); + let own_pid = process::id().to_string(); let error_failed = failed.clone(); let _core_listener = core @@ -416,7 +293,7 @@ fn run( let samples = output.clone(); let _stream_listener = stream .add_local_listener_with_user_data(()) - .state_changed(state_watch(&failed)) + .state_changed(helpers::state_watch(&failed)) .process(move |stream, _| { let Some(mut buffer) = stream.dequeue_buffer() else { return; @@ -429,20 +306,17 @@ fn run( return; }; let bytes = &bytes[..size.min(bytes.len())]; - let mut samples = samples.borrow_mut(); - for sample in bytes + let samples_in = bytes .as_chunks::<4>() .0 .iter() .copied() - .map(f32::from_le_bytes) - { - let _ = samples.push(sample); - } + .map(f32::from_le_bytes); + record(&samples, samples_in); }) .register()?; - let values = format_values().ok_or("pipewire format")?; + let values = helpers::format(SHARE_AUDIO_CHANNELS as u32).ok_or("pipewire format")?; let mut params = [Pod::from_bytes(&values).ok_or("pipewire format")?]; stream.connect(spa::utils::Direction::Input, None, flags, &mut params)?; @@ -451,22 +325,12 @@ fn run( return Err("pipewire connection lost".into()); } if target.is_none() { - routing.borrow_mut().sync(stream.node_id(), mode, &core); + routing + .borrow_mut() + .sync(stream.node_id(), &own_pid, mode, &core); } mainloop.loop_().iterate(Timeout::Finite(STOP_CHECK)); } Ok(()) } - -fn state_watch( - failed: &Rc>, -) -> impl FnMut(&pw::stream::Stream, &mut (), StreamState, StreamState) + 'static { - let failed = failed.clone(); - move |_, _, _, new| { - if let StreamState::Error(message) = new { - warn!("share audio stream: {message}"); - failed.set(true); - } - } -} diff --git a/crates/client/src/share/audio_capture_windows.rs b/crates/client/src/share/audio_capture_windows.rs index 85194a6..e9205dd 100644 --- a/crates/client/src/share/audio_capture_windows.rs +++ b/crates/client/src/share/audio_capture_windows.rs @@ -3,37 +3,26 @@ use std::{ error::Error, process, sync::atomic::{AtomicBool, Ordering}, - time::Duration, }; -use common::constant::VOICE_SAMPLE_RATE; use rtrb::Producer; use tracing::warn; use wasapi::{ - AudioCaptureClient, AudioClient, DeviceEnumerator, Direction, Handle, Role, SampleType, - StreamMode, WaveFormat, deinitialize, initialize_mta, + AudioCaptureClient, AudioClient, DeviceEnumerator, Direction, Handle, Role, StreamMode, }; use super::audio::{AudioApp, AudioKind, AudioMode, is_picked}; -use crate::lang::w; -use crate::voice::audio::{Worker, supervise}; +use crate::{ + lang::w, + voice::audio::{wave_format, with_com}, + worker::{STOP_CHECK, Worker, supervise}, +}; -const STOP_CHECK: Duration = Duration::from_millis(100); const BUFFER_HNS: i64 = 200_000; const BYTES_PER_SAMPLE: usize = 4; pub type AudioCapture = Worker; -fn with_com(body: impl FnOnce() -> T) -> T { - if let Err(error) = initialize_mta().ok() { - warn!("COM not initialized: {error}"); - return T::default(); - } - let value = body(); - deinitialize(); - value -} - pub fn apps() -> Vec { std::thread::spawn(|| { with_com(|| { @@ -106,17 +95,6 @@ pub fn start(mode: AudioMode, output: Producer) -> AudioCapture { }) } -fn wave_format() -> WaveFormat { - WaveFormat::new( - 32, - 32, - SampleType::Float, - VOICE_SAMPLE_RATE as usize, - 2, - None, - ) -} - fn run( mode: &AudioMode, output: &mut Producer, @@ -150,7 +128,7 @@ fn run( client.start_stream()?; let result = capture(&event, &reader, output, stop); - client.stop_stream()?; + let _ = client.stop_stream(); result } diff --git a/crates/client/src/share/camera.rs b/crates/client/src/share/camera.rs index aa1f8ee..74ac321 100644 --- a/crates/client/src/share/camera.rs +++ b/crates/client/src/share/camera.rs @@ -16,10 +16,7 @@ use nokhwa::{ utils::{CameraFormat, CameraIndex, FrameFormat, RequestedFormat, RequestedFormatType}, }; -use super::{ - fake, - frame::{BYTES_PER_PIXEL, FRAME_QUEUE, Frame}, -}; +use super::frame::{FRAME_QUEUE, Feed, Frame, elapsed_ms}; const OPEN_TIMEOUT: Duration = Duration::from_secs(10); const RETRY_DELAY: Duration = Duration::from_millis(5); @@ -37,21 +34,30 @@ const WANTED_FORMATS: [RequestedFormatType; 4] = [ const DECODABLE: [FrameFormat; 3] = [FrameFormat::NV12, FrameFormat::YUYV, FrameFormat::MJPEG]; -type Negotiated = (u32, u32, u32, (u32, u32), Vec); +struct Negotiated { + width: u32, + height: u32, + largest: (u32, u32), + modes: Vec, +} -pub struct Camera { - pub width: u32, - pub height: u32, - pub refresh: u32, - pub size: (u32, u32), - pub modes: Vec, - pub frames: Receiver, - pub fps: Arc, - alive: Arc, +struct Shared { + stop: AtomicBool, + fps: AtomicU32, + alive: AtomicU32, opened: Instant, - stop: Arc, - thread: Option<(JoinHandle<()>, Receiver<()>)>, - _fake: Option, +} + +impl Shared { + fn beat(&self) { + self.alive.store(elapsed_ms(self.opened), Ordering::Relaxed); + } +} + +pub struct Camera { + shared: Arc, + thread: Option>, + done: Receiver<()>, } static HELD: Mutex> = Mutex::new(Vec::new()); @@ -63,9 +69,9 @@ fn held() -> std::sync::MutexGuard<'static, Vec> { impl Drop for Camera { fn drop(&mut self) { - self.stop.store(true, Ordering::Relaxed); - if let Some((thread, done)) = self.thread.take() - && done.recv_timeout(JOIN_TIMEOUT) != Err(RecvTimeoutError::Timeout) + self.shared.stop.store(true, Ordering::Relaxed); + if let Some(thread) = self.thread.take() + && self.done.recv_timeout(JOIN_TIMEOUT) != Err(RecvTimeoutError::Timeout) { let _ = thread.join(); } @@ -93,8 +99,12 @@ impl Drop for Hold { impl Camera { pub fn stalled(&self) -> bool { - let alive = Duration::from_millis(self.alive.load(Ordering::Relaxed).into()); - self.thread.is_some() && self.opened.elapsed().saturating_sub(alive) > STALL + let alive = Duration::from_millis(self.shared.alive.load(Ordering::Relaxed).into()); + self.shared.opened.elapsed().saturating_sub(alive) > STALL + } + + pub fn set_fps(&self, fps: u32) { + self.shared.fps.store(fps, Ordering::Relaxed); } } @@ -120,16 +130,30 @@ pub fn devices() -> Vec { if !available() { return Vec::new(); } - let mut names: Vec = nodes().into_iter().map(|info| info.human_name()).collect(); - names.dedup(); - names + named().into_iter().map(|(name, _)| name).collect() } -fn nodes() -> Vec { - nokhwa::query(nokhwa::utils::ApiBackend::Auto) +fn named() -> Vec<(String, CameraIndex)> { + let nodes: Vec<(String, CameraIndex)> = nokhwa::query(nokhwa::utils::ApiBackend::Auto) .unwrap_or_default() .into_iter() .filter(|info| captures(info.index())) + .map(|info| (info.human_name(), info.index().clone())) + .collect(); + nodes + .iter() + .enumerate() + .map(|(position, (name, index))| { + let earlier = nodes[..position] + .iter() + .filter(|(other, _)| other == name) + .count(); + let name = match earlier { + 0 => name.clone(), + copies => format!("{name} ({})", copies + 1), + }; + (name, index.clone()) + }) .collect() } @@ -141,12 +165,12 @@ pub fn label(name: &str) -> &str { } fn index(device: Option<&str>) -> Option { - let nodes = nodes(); + let nodes = named(); let index = nodes .iter() - .find(|info| Some(info.human_name().as_str()) == device) + .find(|(name, _)| Some(name.as_str()) == device) .or(nodes.first()) - .map_or(CameraIndex::Index(0), |info| info.index().clone()); + .map_or(CameraIndex::Index(0), |(_, index)| index.clone()); if held().contains(&index) { tracing::warn!(?index, "camera still held by our capture thread"); return None; @@ -235,24 +259,7 @@ fn format_count(_: &CameraIndex) -> u64 { 0 } -pub fn open(top: Quality, device: Option) -> Result { - if let Ok(spec) = std::env::var("YUMUSH_TEST_CAMERA") { - let (width, height, refresh, frames, generator) = fake::start(&spec); - return Ok(Camera { - width, - height, - refresh, - size: (width, height), - modes: vec![(height, refresh)], - frames, - fps: Arc::new(AtomicU32::new(refresh)), - alive: Arc::new(AtomicU32::new(0)), - opened: Instant::now(), - stop: Arc::new(AtomicBool::new(false)), - thread: None, - _fake: Some(generator), - }); - } +pub fn open(top: Quality, device: Option) -> Result<(Feed, Camera), String> { if !available() { return Err(w().camera.needs_media_pack.to_string()); } @@ -260,54 +267,53 @@ pub fn open(top: Quality, device: Option) -> Result { let hold = Hold::take(index.clone()).ok_or_else(|| w().camera.no_response.to_string())?; let (negotiated_tx, negotiated_rx) = sync_channel::>(1); let (frames_tx, frames_rx) = sync_channel(FRAME_QUEUE); - let stop = Arc::new(AtomicBool::new(false)); - let fps = Arc::new(AtomicU32::new(u32::MAX)); - let alive = Arc::new(AtomicU32::new(0)); - let opened = Instant::now(); + let shared = Arc::new(Shared { + stop: AtomicBool::new(false), + fps: AtomicU32::new(u32::MAX), + alive: AtomicU32::new(0), + opened: Instant::now(), + }); let (done_tx, done) = sync_channel::<()>(0); let thread = { - let (stop, fps, alive) = (stop.clone(), fps.clone(), alive.clone()); + let shared = shared.clone(); std::thread::Builder::new() .name("camera-capture".to_string()) .spawn(move || { let _done = done_tx; let _hold = hold; - let clock = Clock { - opened, - alive: &alive, - }; - run(top, &index, &stop, &fps, &clock, negotiated_tx, frames_tx) + run(top, &index, &shared, negotiated_tx, frames_tx) }) .map_err(|error| error.to_string())? }; let negotiated = match negotiated_rx.recv_timeout(OPEN_TIMEOUT) { Ok(negotiated) => negotiated, Err(_) => { - stop.store(true, Ordering::Relaxed); + shared.stop.store(true, Ordering::Relaxed); return Err(w().camera.no_response.to_string()); } }; - let (width, height, refresh, size, modes) = match negotiated { + let negotiated = match negotiated { Ok(negotiated) => negotiated, Err(error) => { let _ = thread.join(); return Err(error); } }; - Ok(Camera { - width, - height, - refresh, - size, - modes, + let feed = Feed { + width: negotiated.width, + height: negotiated.height, + largest: negotiated.largest, + modes: negotiated.modes, frames: frames_rx, - fps, - alive, - opened, - stop, - thread: Some((thread, done)), - _fake: None, - }) + }; + Ok(( + feed, + Camera { + shared, + thread: Some(thread), + done, + }, + )) } pub fn list(device: Option<&str>) -> Vec { @@ -394,31 +400,20 @@ fn open_device(top: Quality, index: &CameraIndex) -> Result<(Device, Vec return Ok((camera, Vec::new())), + Ok(camera) => { + let format = camera.camera_format(); + return Ok((camera, vec![format])); + } Err(error) => tracing::warn!(%error, "camera open failed"), } } Err(w().camera.not_found.to_string()) } -struct Clock<'a> { - opened: Instant, - alive: &'a AtomicU32, -} - -impl Clock<'_> { - fn beat(&self) { - let elapsed = u32::try_from(self.opened.elapsed().as_millis()).unwrap_or(u32::MAX); - self.alive.store(elapsed, Ordering::Relaxed); - } -} - fn run( top: Quality, index: &CameraIndex, - stop: &AtomicBool, - fps: &AtomicU32, - clock: &Clock, + shared: &Shared, negotiated: SyncSender>, frames: SyncSender, ) { @@ -430,24 +425,18 @@ fn run( } }; let format = camera.camera_format(); - let formats = if formats.is_empty() { - vec![format] - } else { - formats - }; tracing::info!(?format, "camera opened"); - clock.beat(); - let _ = negotiated.send(Ok(( - format.width(), - format.height(), - format.frame_rate(), - size(&formats).unwrap_or((format.width(), format.height())), - modes(&formats), - ))); + shared.beat(); + let _ = negotiated.send(Ok(Negotiated { + width: format.width(), + height: format.height(), + largest: size(&formats).unwrap_or((format.width(), format.height())), + modes: modes(&formats), + })); let started = Instant::now(); let mut failures = 0; let mut due = 0u32; - while !stop.load(Ordering::Relaxed) { + while !shared.stop.load(Ordering::Relaxed) { crate::usage::tick(crate::usage::Group::Camera); let buffer = match camera.frame() { Ok(buffer) => buffer, @@ -462,9 +451,9 @@ fn run( } }; failures = 0; - clock.beat(); - let timestamp_ms = u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX); - let wanted = fps.load(Ordering::Relaxed); + shared.beat(); + let timestamp_ms = elapsed_ms(started); + let wanted = shared.fps.load(Ordering::Relaxed); if wanted == 0 || timestamp_ms + SLACK_MS < due { continue; } @@ -472,15 +461,7 @@ fn run( let Some((width, height, bgra)) = to_bgra(&buffer) else { continue; }; - let frame = Frame { - width, - height, - stride: width * BYTES_PER_PIXEL as u32, - timestamp_ms, - bgra, - gpu: None, - }; - let _ = frames.try_send(frame); + let _ = frames.try_send(Frame::cpu(width, height, timestamp_ms, bgra)); } let _ = camera.stop_stream(); } @@ -496,17 +477,3 @@ fn to_bgra(buffer: &Buffer) -> Option<(u32, u32, Vec)> { _ => None, } } - -#[cfg(test)] -mod tests { - use super::*; - - #[cfg(target_os = "linux")] - #[test] - fn loopback_ranges_exceed_limit() { - let sizes = steps(2, 8192, 1).min(steps(1, 8192, 1)); - let intervals = steps(1, i32::MAX as u32, 1); - assert!(sizes * intervals > MAX_FORMATS); - assert_eq!(steps(640, 640, 0), 1); - } -} diff --git a/crates/client/src/share/capture.rs b/crates/client/src/share/capture.rs index 01b974b..4edc826 100644 --- a/crates/client/src/share/capture.rs +++ b/crates/client/src/share/capture.rs @@ -36,27 +36,26 @@ use spa::{ use crate::lang::w; -use super::{ - fake, - frame::{BYTES_PER_PIXEL, DEFAULT_REFRESH, FRAME_QUEUE, Frame, Gpu, Release, take_gpu_failed}, +use super::frame::{ + BYTES_PER_PIXEL, DEFAULT_REFRESH, FRAME_QUEUE, Feed, Frame, Gpu, Release, elapsed_ms, + pack_rows, take_gpu_failed, }; const NEGOTIATE_TIMEOUT: Duration = Duration::from_secs(10); const STOP_CHECK: Duration = Duration::from_millis(100); const RELEASE_CHECK: Duration = Duration::from_millis(20); -type Negotiated = (u32, u32, u32); +struct Negotiated { + width: u32, + height: u32, + refresh: u32, +} pub struct Capture { - pub width: u32, - pub height: u32, - pub refresh: u32, - pub frames: Receiver, stop: Arc, thread: Option>, session: Option>, runtime: tokio::runtime::Handle, - _fake: Option, } impl Drop for Capture { @@ -75,26 +74,12 @@ impl Drop for Capture { pub const PICKS: bool = false; -pub fn targets(_: &dyn Fn(super::Target) -> bool) -> Option> { - None +pub fn targets(_: &dyn Fn(super::Target) -> bool) -> Vec { + Vec::new() } -pub async fn open(_: Option) -> Result { +pub async fn open(_: Option) -> Result<(Feed, Capture), String> { let runtime = tokio::runtime::Handle::current(); - if let Ok(spec) = std::env::var("YUMUSH_TEST_CAPTURE") { - let (width, height, refresh, frames, generator) = fake::start(&spec); - return Ok(Capture { - width, - height, - refresh, - frames, - stop: Arc::new(AtomicBool::new(false)), - thread: None, - session: None, - runtime, - _fake: Some(generator), - }); - } let screencast = Screencast::new().await.map_err(text)?; let session = screencast .create_session(Default::default()) @@ -108,17 +93,21 @@ pub async fn open(_: Option) -> Result { } }; match launch(fd, node_id).await { - Ok(((width, height, refresh), frames, stop, thread)) => Ok(Capture { - width, - height, - refresh, - frames, - stop, - thread: Some(thread), - session: Some(session), - runtime, - _fake: None, - }), + Ok((size, frames, stop, thread)) => Ok(( + Feed { + width: size.width, + height: size.height, + largest: (size.width, size.height), + modes: vec![(size.height, size.refresh)], + frames, + }, + Capture { + stop, + thread: Some(thread), + session: Some(session), + runtime, + }, + )), Err(error) => { let _ = session.close().await; Err(error) @@ -196,7 +185,14 @@ fn text(error: impl std::fmt::Display) -> String { error.to_string() } -type Applied = (bool, u64, u32, u32, u32); +#[derive(Clone, Copy, PartialEq)] +struct Applied { + gpu: bool, + modifier: u64, + format: u32, + width: u32, + height: u32, +} struct State { format: VideoInfoRaw, @@ -452,31 +448,32 @@ fn on_param(stream: &pw::stream::Stream, state: &mut State, id: u32, param: Opti } let offered = offered_modifier(param); if let Some((offered, true)) = &offered { - let Some(chosen) = offered + let fixed = offered .iter() .find(|modifier| state.modifiers.contains(modifier)) - else { - return; - }; - let fixed = format_values(Some(&[*chosen])); + .and_then(|chosen| format_values(Some(&[*chosen]))); let shm = format_values(None); - if let (Some(fixed), Some(shm)) = (fixed, shm) - && let (Some(fixed), Some(shm)) = (Pod::from_bytes(&fixed), Pod::from_bytes(&shm)) - { - let _ = stream.update_params(&mut [fixed, shm]); + if let Some(shm) = shm.as_deref().and_then(Pod::from_bytes) { + let mut params: Vec<&Pod> = fixed + .as_deref() + .and_then(Pod::from_bytes) + .into_iter() + .chain(std::iter::once(shm)) + .collect(); + let _ = stream.update_params(&mut params); } return; } let gpu = offered.is_some(); let size = state.format.size(); let modifier = if gpu { state.format.modifier() } else { 0 }; - let applied = ( + let applied = Applied { gpu, modifier, - state.format.format().as_raw(), - size.width, - size.height, - ); + format: state.format.format().as_raw(), + width: size.width, + height: size.height, + }; if state.applied == Some(applied) { return; } @@ -496,9 +493,11 @@ fn on_param(stream: &pw::stream::Stream, state: &mut State, id: u32, param: Opti .unwrap_or(DEFAULT_REFRESH); tracing::info!(refresh, "share capture refresh"); state.size = (size.width, size.height); - let _ = state - .negotiated - .try_send((size.width, size.height, refresh)); + let _ = state.negotiated.try_send(Negotiated { + width: size.width, + height: size.height, + refresh, + }); } fn on_process(stream: &pw::stream::Stream, state: &mut State) { @@ -520,7 +519,7 @@ fn on_process(stream: &pw::stream::Stream, state: &mut State) { width, height, stride: width * BYTES_PER_PIXEL as u32, - timestamp_ms: u32::try_from(state.started.elapsed().as_millis()).unwrap_or(u32::MAX), + timestamp_ms: elapsed_ms(state.started), bgra: Vec::new(), gpu: Some(Gpu { fd: plane.fd(), @@ -555,21 +554,10 @@ fn on_process(stream: &pw::stream::Stream, state: &mut State) { return; }; - let mut bgra = Vec::with_capacity(row * height as usize); - for line in 0..height as usize { - let Some(pixels) = source.get(line * stride..line * stride + row) else { - return; - }; - bgra.extend_from_slice(pixels); - } - - let frame = Frame { - width, - height, - stride: row as u32, - timestamp_ms: u32::try_from(state.started.elapsed().as_millis()).unwrap_or(u32::MAX), - bgra, - gpu: None, + let Some(bgra) = pack_rows(source, stride, row, height) else { + return; }; - let _ = state.frames.try_send(frame); + let _ = state + .frames + .try_send(Frame::cpu(width, height, elapsed_ms(state.started), bgra)); } diff --git a/crates/client/src/share/capture_windows.rs b/crates/client/src/share/capture_windows.rs index d90c8cd..a66480a 100644 --- a/crates/client/src/share/capture_windows.rs +++ b/crates/client/src/share/capture_windows.rs @@ -20,8 +20,11 @@ use windows_capture::{ }; use super::{ - Source, Target, fake, - frame::{BYTES_PER_PIXEL, DEFAULT_REFRESH, FRAME_QUEUE, Frame, Gpu, Release, take_gpu_failed}, + Source, Target, + frame::{ + BYTES_PER_PIXEL, DEFAULT_REFRESH, FRAME_QUEUE, Feed, Frame, Gpu, Release, elapsed_ms, + pack_rows, take_gpu_failed, + }, }; const IN_FLIGHT: usize = 3; @@ -29,12 +32,7 @@ const PREVIEW_WIDTH: u32 = 320; const PREVIEW_BUDGET: std::time::Duration = std::time::Duration::from_millis(100); pub struct Capture { - pub width: u32, - pub height: u32, - pub refresh: u32, - pub frames: Receiver, control: Option>, - _fake: Option, } impl Drop for Capture { @@ -47,7 +45,7 @@ impl Drop for Capture { pub const PICKS: bool = true; -pub fn targets(stale: &dyn Fn(Target) -> bool) -> Option> { +pub fn targets(stale: &dyn Fn(Target) -> bool) -> Vec { let started = Instant::now(); let due = |target: Target| stale(target) && started.elapsed() < PREVIEW_BUDGET; let screens = xcap::Monitor::all().unwrap_or_default(); @@ -90,7 +88,7 @@ pub fn targets(stale: &dyn Fn(Target) -> bool) -> Option> { preview, }); } - Some(sources) + sources } fn raw(id: u32) -> usize { @@ -106,18 +104,7 @@ fn shrink(image: image::RgbaImage) -> image::RgbaImage { image } -pub async fn open(target: Option) -> Result { - if let Ok(spec) = std::env::var("YUMUSH_TEST_CAPTURE") { - let (width, height, refresh, frames, generator) = fake::start(&spec); - return Ok(Capture { - width, - height, - refresh, - frames, - control: None, - _fake: Some(generator), - }); - } +pub async fn open(target: Option) -> Result<(Feed, Capture), String> { match target { Some(Target::Window(handle)) => { let window = Window::from_raw_hwnd(handle as *mut std::ffi::c_void); @@ -137,7 +124,7 @@ pub async fn open(target: Option) -> Result { } } -fn screen(monitor: Monitor) -> Result { +fn screen(monitor: Monitor) -> Result<(Feed, Capture), String> { let width = monitor.width().map_err(text)?; let height = monitor.height().map_err(text)?; start(monitor, width, height, refresh_of(monitor)) @@ -156,7 +143,7 @@ fn start + Send + 'static>( width: u32, height: u32, refresh: u32, -) -> Result { +) -> Result<(Feed, Capture), String> { let border = match GraphicsCaptureApi::is_border_settings_supported() { Ok(true) => DrawBorderSettings::WithoutBorder, _ => DrawBorderSettings::Default, @@ -173,15 +160,20 @@ fn start + Send + 'static>( (frames_tx, Instant::now()), ); let control = Handler::start_free_threaded(settings).map_err(text)?; - - Ok(Capture { - width: width.max(2), - height: height.max(2), - refresh, + let (width, height) = (width.max(2), height.max(2)); + let feed = Feed { + width, + height, + largest: (width, height), + modes: vec![(height, refresh)], frames: frames_rx, - control: Some(control), - _fake: None, - }) + }; + Ok(( + feed, + Capture { + control: Some(control), + }, + )) } fn text(error: impl std::fmt::Display) -> String { @@ -195,7 +187,7 @@ enum Path { } struct Handler { - frames: SyncSender, + frames: Option>, started: Instant, path: Path, release: SyncSender<()>, @@ -203,10 +195,6 @@ struct Handler { } impl Handler { - fn timestamp(&self) -> u32 { - u32::try_from(self.started.elapsed().as_millis()).unwrap_or(u32::MAX) - } - fn pick_path(&mut self, frame: &CaptureFrame) { if take_gpu_failed() && matches!(self.path, Path::Gpu(_)) { tracing::warn!("share capture falls back to cpu copies"); @@ -228,7 +216,7 @@ impl Handler { } fn send_gpu(&mut self, frame: &CaptureFrame) -> bool { - let timestamp_ms = self.timestamp(); + let timestamp_ms = elapsed_ms(self.started); let Path::Gpu(pool) = &mut self.path else { return false; }; @@ -252,19 +240,21 @@ impl Handler { return false; } }; - let _ = self.frames.try_send(Frame { - width, - height, - stride: width * BYTES_PER_PIXEL as u32, - timestamp_ms, - bgra: Vec::new(), - gpu: Some(Gpu { - handle, - id, - bgra: order == RgbOrder::Bgra, - release, - }), - }); + if let Some(frames) = &self.frames { + let _ = frames.try_send(Frame { + width, + height, + stride: width * BYTES_PER_PIXEL as u32, + timestamp_ms, + bgra: Vec::new(), + gpu: Some(Gpu { + handle, + id, + bgra: order == RgbOrder::Bgra, + release, + }), + }); + } true } } @@ -280,7 +270,7 @@ impl GraphicsCaptureApiHandler for Handler { let _ = release.try_send(()); } Ok(Self { - frames, + frames: Some(frames), started, path: Path::Untried, release, @@ -302,29 +292,17 @@ impl GraphicsCaptureApiHandler for Handler { let mut buffer = frame.buffer().map_err(text)?; let pitch = buffer.row_pitch() as usize; let row = width as usize * BYTES_PER_PIXEL; - let raw = buffer.as_raw_buffer(); - - let mut bgra = Vec::with_capacity(row * height as usize); - for line in 0..height as usize { - let Some(pixels) = raw.get(line * pitch..line * pitch + row) else { - return Ok(()); - }; - bgra.extend_from_slice(pixels); + let Some(bgra) = pack_rows(buffer.as_raw_buffer(), pitch, row, height) else { + return Ok(()); + }; + if let Some(frames) = &self.frames { + let _ = frames.try_send(Frame::cpu(width, height, elapsed_ms(self.started), bgra)); } - - let _ = self.frames.try_send(Frame { - width, - height, - stride: row as u32, - timestamp_ms: self.timestamp(), - bgra, - gpu: None, - }); Ok(()) } fn on_closed(&mut self) -> Result<(), Self::Error> { - self.frames = sync_channel(0).0; + self.frames = None; Ok(()) } } diff --git a/crates/client/src/share/congestion.rs b/crates/client/src/share/congestion.rs index a0235cf..2c75ba2 100644 --- a/crates/client/src/share/congestion.rs +++ b/crates/client/src/share/congestion.rs @@ -1,4 +1,5 @@ use std::{ + collections::VecDeque, sync::atomic::{AtomicU32, Ordering}, time::Duration, }; @@ -7,6 +8,7 @@ use common::{datagram::parity_for, transport::heavy_loss}; use quinn::Connection; pub const PERIOD: Duration = Duration::from_millis(500); +const WINDOW: usize = 60; const MIN_SCALE: f32 = 0.25; const DECREASE: f32 = 0.75; const INCREASE: f32 = 0.05; @@ -31,8 +33,11 @@ impl Loss { } pub fn decay(&self) { - let loss = f32::from_bits(self.0.load(Ordering::Relaxed)) * LOSS_DECAY; - self.0.store(loss.to_bits(), Ordering::Relaxed); + let _ = self + .0 + .try_update(Ordering::Relaxed, Ordering::Relaxed, |bits| { + Some((f32::from_bits(bits) * LOSS_DECAY).to_bits()) + }); } pub fn parity(&self, length: u32, keyframe: bool) -> u16 { @@ -64,8 +69,7 @@ impl Uplink { pub struct Controller { scale: f32, - loss: f32, - base_rtt: Option, + rtts: VecDeque, last: Uplink, } @@ -73,31 +77,29 @@ impl Default for Controller { fn default() -> Self { Self { scale: 1.0, - loss: 0.0, - base_rtt: None, + rtts: VecDeque::new(), last: Uplink::default(), } } } impl Controller { - pub fn observe(&mut self, now: Uplink) -> f32 { - let base = self.base_rtt.map_or(now.rtt, |base| base.min(now.rtt)); - self.base_rtt = Some(base); + pub fn observe(&mut self, now: Uplink) -> (f32, f32) { + self.rtts.push_back(now.rtt); + if self.rtts.len() > WINDOW { + self.rtts.pop_front(); + } + let base = self.rtts.iter().copied().min().unwrap_or(now.rtt); let sent = now.sent.saturating_sub(self.last.sent); let lost = now.lost.saturating_sub(self.last.lost); self.last = now; - self.loss = lost as f32 / sent.max(1) as f32; + let loss = lost as f32 / sent.max(1) as f32; let congested = heavy_loss(lost, sent) || now.buffer_low || now.rtt > base + QUEUE_DELAY; self.scale = match congested { true => (self.scale * DECREASE).max(MIN_SCALE), false => (self.scale + INCREASE).min(1.0), }; - self.scale - } - - pub fn loss(&self) -> f32 { - self.loss + (self.scale, loss) } } @@ -112,13 +114,13 @@ mod tests { rtt: Duration::from_millis(20), ..Uplink::default() }; - assert_eq!(controller.observe(uplink), 1.0); + assert_eq!(controller.observe(uplink).0, 1.0); uplink.rtt = Duration::from_millis(200); uplink.sent = 100; uplink.lost = 10; - assert_eq!(controller.observe(uplink), DECREASE); + assert_eq!(controller.observe(uplink).0, DECREASE); uplink.rtt = Duration::from_millis(20); uplink.sent = 200; - assert!(controller.observe(uplink) > DECREASE); + assert!(controller.observe(uplink).0 > DECREASE); } } diff --git a/crates/client/src/share/encode.rs b/crates/client/src/share/encode.rs index c370ea0..3013f86 100644 --- a/crates/client/src/share/encode.rs +++ b/crates/client/src/share/encode.rs @@ -20,10 +20,10 @@ const GAIN: f32 = 0.8; const SETTLE_FRAMES: u32 = 4; const MIN_FPS: u32 = 30; const MIN_HEIGHT: u32 = 360; +const REOPEN_STEP: f32 = 0.25; pub struct Capabilities { pub encode: Vec, - pub decode: Vec, pub max_height: u32, } @@ -48,11 +48,7 @@ fn probe() -> &'static Probe { .filter(|codec| *codec == SOFTWARE || codecs.contains(codec)) .collect(); Probe { - capabilities: Capabilities { - encode, - decode: Codec::ALL.to_vec(), - max_height, - }, + capabilities: Capabilities { encode, max_height }, hardware: codecs, vulkan, } @@ -110,16 +106,29 @@ impl Control { } } +struct Coded { + data: Vec, + keyframe: bool, + recovery: bool, +} + struct Settings { codec: Codec, width: u32, height: u32, fps: u32, bitrate: u32, - gop: u32, } impl Settings { + fn gop(&self) -> u32 { + self.fps * KEYFRAME_SECONDS + } + + fn bitrate_at(&self, scale: f32) -> u32 { + (self.bitrate as f32 * scale) as u32 + } + fn rate(&self) -> u64 { u64::from(self.width) * u64::from(self.height) * u64::from(self.fps) } @@ -151,7 +160,6 @@ impl Settings { height, fps, bitrate: self.bitrate, - gop: fps * KEYFRAME_SECONDS, }) } } @@ -172,18 +180,18 @@ impl Backend { .map(|encoder| Self::Hardware(Box::new(encoder))) .or_else(|| { tracing::warn!(codec = ?settings.codec, "share encode falls back to software"); - Self::software(settings) + Self::software(settings, settings.bitrate) }) } - fn software(settings: &Settings) -> Option { + fn software(settings: &Settings, bitrate: u32) -> Option { let (width, height) = (settings.width, settings.height); match settings.codec { Codec::H264 => { let mut config = ec_h264::EncoderConfig::new(width, height); config.framerate = settings.fps as f32; - config.bitrate = settings.bitrate; - config.gop_size = settings.gop; + config.bitrate = bitrate; + config.gop_size = settings.gop(); config.threads = 4; report(ec_h264::Encoder::new(config)).map(|encoder| Self::H264(Box::new(encoder))) } @@ -191,10 +199,17 @@ impl Backend { } } - fn tune(&mut self, bitrate: u32, fps: u32) { - if let Self::Hardware(encoder) = self { - encoder.tune(bitrate, fps); + fn retune(&mut self, settings: &Settings, applied: f32, wanted: f32) -> bool { + match self { + Self::Hardware(encoder) => encoder.tune(settings.bitrate_at(wanted), settings.fps), + Self::H264(_) if (wanted - applied).abs() < REOPEN_STEP => return false, + Self::H264(_) => { + if let Some(reopened) = Self::software(settings, settings.bitrate_at(wanted)) { + *self = reopened; + } + } } + true } fn ack(&mut self, timestamp_ms: u32) { @@ -210,12 +225,7 @@ impl Backend { } } - fn encode( - &mut self, - frame: &Frame, - settings: &Settings, - request: Request, - ) -> Option<(Vec, bool, bool)> { + fn encode(&mut self, frame: &Frame, settings: &Settings, request: Request) -> Option { match self { Self::Hardware(encoder) => encoder.encode(frame, settings, request), Self::H264(_) if frame.gpu.is_some() => { @@ -231,8 +241,13 @@ impl Backend { &planes.u, &planes.v, ); - report(encoder.encode_with(&picture, request != Request::Nothing)) - .map(|picture| (picture.au, picture.key_frame, false)) + report(encoder.encode_with(&picture, request != Request::Nothing)).map(|picture| { + Coded { + data: picture.au, + keyframe: picture.key_frame, + recovery: false, + } + }) } } } @@ -257,11 +272,30 @@ mod hardware { use common::share::Codec; - use super::{Request, Settings, report}; - use crate::share::frame::Frame; + use super::{Coded, Request, Settings, report}; + use crate::share::frame::{Frame, gpu_failed}; pub struct Encoder(ec_hw::HwEncoder); + fn order(bgra: bool) -> ec_hw::RgbOrder { + if bgra { + ec_hw::RgbOrder::Bgra + } else { + ec_hw::RgbOrder::Rgba + } + } + + fn coded(result: Result, gpu: bool) -> Option { + if gpu && result.is_err() { + gpu_failed(); + } + report(result).map(|coded| Coded { + data: coded.data, + keyframe: coded.is_keyframe, + recovery: coded.recovery, + }) + } + impl Encoder { pub fn tune(&mut self, bitrate: u32, fps: u32) { report(self.0.tune(ec_hw::Tunings { @@ -279,7 +313,7 @@ mod hardware { frame: &Frame, settings: &Settings, request: Request, - ) -> Option<(Vec, bool, bool)> { + ) -> Option { if request == Request::Recover { self.0.recover(); } @@ -291,7 +325,7 @@ mod hardware { if let Some(dmabuf) = &frame.gpu { use std::os::fd::AsFd; let Some(fd) = report(ec_hw::dup_fd(dmabuf.fd)) else { - crate::share::frame::gpu_failed(); + gpu_failed(); return None; }; let source = ec_hw::DmaBufFrame { @@ -301,17 +335,9 @@ mod hardware { stride: dmabuf.stride, offset: dmabuf.offset, modifier: dmabuf.modifier, - order: if dmabuf.bgra { - ec_hw::RgbOrder::Bgra - } else { - ec_hw::RgbOrder::Rgba - }, + order: order(dmabuf.bgra), }; - let coded = self.0.encode_dmabuf(&source, meta); - if coded.is_err() { - crate::share::frame::gpu_failed(); - } - return report(coded).map(|coded| (coded.data, coded.is_keyframe, coded.recovery)); + return coded(self.0.encode_dmabuf(&source, meta), true); } #[cfg(target_os = "windows")] if let Some(gpu) = &frame.gpu { @@ -321,19 +347,11 @@ mod hardware { id: gpu.id, width: frame.width, height: frame.height, - order: if gpu.bgra { - ec_hw::RgbOrder::Bgra - } else { - ec_hw::RgbOrder::Rgba - }, + order: order(gpu.bgra), }; - let coded = self.0.encode_d3d11(&source, meta); - if coded.is_err() { - crate::share::frame::gpu_failed(); - } - return report(coded).map(|coded| (coded.data, coded.is_keyframe, coded.recovery)); + return coded(self.0.encode_d3d11(&source, meta), true); } - let coded = if frame.width.is_multiple_of(2) + let result = if frame.width.is_multiple_of(2) && frame.height.is_multiple_of(2) && frame.stride.is_multiple_of(4) { @@ -356,7 +374,7 @@ mod hardware { }; self.0.encode(&picture, meta) }; - report(coded).map(|coded| (coded.data, coded.is_keyframe, coded.recovery)) + coded(result, false) } } @@ -414,7 +432,7 @@ mod hardware { let mut config = ec_hw::EncoderConfig::new(codec, settings.width, settings.height); config.framerate = (settings.fps, 1); config.bitrate = settings.bitrate; - config.gop_size = settings.gop; + config.gop_size = settings.gop(); config.rate_control = ec_hw::RateControlMode::VariableBitrate; config.buffer_ms = Some(RATE_BUFFER_MS); config.colour = Some(BT709_LIMITED); @@ -425,14 +443,18 @@ mod hardware { } } +struct Shared { + scale: AtomicU32, + budget: AtomicU64, + output: Sender, +} + fn run( layer: Layer, settings: Settings, input: Receiver>, control: Arc, - scale: Arc, - budget: Arc, - output: Sender, + shared: Arc, ) { let mut acked = None; let Some(mut backend) = Backend::open(&settings) else { @@ -451,10 +473,9 @@ fn run( continue; } due = due.max(frame.timestamp_ms.saturating_sub(SLACK_MS)) + interval; - let wanted = f32::from_bits(scale.load(Ordering::Relaxed)); - if wanted != applied { + let wanted = f32::from_bits(shared.scale.load(Ordering::Relaxed)); + if wanted != applied && backend.retune(&settings, applied, wanted) { applied = wanted; - backend.tune((settings.bitrate as f32 * wanted) as u32, settings.fps); } let ack = control.acked(); if ack != acked { @@ -464,11 +485,12 @@ fn run( } } let started = Instant::now(); - let Some((data, keyframe, recovery)) = backend.encode(&frame, &settings, control.take()) - else { + let request = control.take(); + let Some(coded) = backend.encode(&frame, &settings, request) else { + control.ask(request); continue; }; - if !keyframe { + if !coded.keyframe { let spent = started.elapsed().as_secs_f32() * 1000.0; busy_ms = if settled == 0 { spent @@ -490,7 +512,7 @@ fn run( fps = lighter.fps, "share encoder overloaded" ); - budget.fetch_min(lighter.rate(), Ordering::Relaxed); + shared.budget.fetch_min(lighter.rate(), Ordering::Relaxed); backend = opened; settings = lighter; interval = 1000 / settings.fps; @@ -501,12 +523,13 @@ fn run( let encoded = Encoded { layer, engine: backend.engine(), - data, - keyframe, - recovery, + data: coded.data, + keyframe: coded.keyframe, + recovery: coded.recovery, timestamp_ms: frame.timestamp_ms, + bitrate: settings.bitrate_at(applied), }; - if output.send(encoded).is_err() { + if shared.output.send(encoded).is_err() { break; } } @@ -520,10 +543,8 @@ struct Lane { pub struct Encoders { source_width: u32, source_height: u32, - output: Sender, lanes: HashMap, - scale: Arc, - budget: Arc, + shared: Arc, resized: Option<((u32, u32), Instant)>, } @@ -532,10 +553,12 @@ impl Encoders { Self { source_width, source_height, - output, lanes: HashMap::new(), - scale: Arc::new(AtomicU32::new(1f32.to_bits())), - budget: Arc::new(AtomicU64::new(u64::MAX)), + shared: Arc::new(Shared { + scale: AtomicU32::new(1f32.to_bits()), + budget: AtomicU64::new(u64::MAX), + output, + }), resized: None, } } @@ -570,12 +593,8 @@ impl Encoders { self.lanes.values().any(|lane| lane.control.pending()) } - pub fn layer_bitrate(&self, layer: Layer) -> u32 { - layer.bitrate(self.source_width, self.source_height) - } - pub fn set_scale(&self, scale: f32) { - self.scale.store(scale.to_bits(), Ordering::Relaxed); + self.shared.scale.store(scale.to_bits(), Ordering::Relaxed); } pub fn push(&mut self, frame: Arc) { @@ -621,31 +640,121 @@ impl Encoders { height, fps, bitrate: layer.bitrate(self.source_width, self.source_height), - gop: fps * KEYFRAME_SECONDS, } - .within(self.budget.load(Ordering::Relaxed)); + .within(self.shared.budget.load(Ordering::Relaxed)); let (input, receiver) = sync_channel(1); let control = Arc::new(Control::default()); let thread_control = Arc::clone(&control); - let output = self.output.clone(); - let scale = Arc::clone(&self.scale); - let budget = Arc::clone(&self.budget); + let shared = Arc::clone(&self.shared); let spawned = thread::Builder::new() .name("share-encode".into()) - .spawn(move || { - run( - layer, - settings, - receiver, - thread_control, - scale, - budget, - output, - ) - }); + .spawn(move || run(layer, settings, receiver, thread_control, shared)); if let Err(error) = spawned { tracing::warn!(?error, "share encode thread failed to start"); } Lane { input, control } } } + +#[cfg(test)] +mod tests { + use std::sync::mpsc; + + use common::{ + datagram::{FrameInfo, Packet, fragments}, + share::{Fps, Kind, Quality, Resolution}, + }; + + use super::*; + use crate::media::{self, decode::VideoDecoder}; + use crate::share::reassembly::Reassembler; + + #[test] + fn every_codec_round_trips() { + let capabilities = capabilities(); + let (width, height) = (1280, 720); + for codec in capabilities.encode.clone() { + let layer = Layer { + quality: Quality { + resolution: Resolution::P720, + fps: Fps::F30, + }, + codec, + }; + let (tx, rx) = mpsc::channel(); + let mut encoders = Encoders::new(width, height, tx); + encoders.set_layers(&[layer]); + for index in 0..10u32 { + let bgra = (0..width * height * 4) + .map(|byte| (byte / 4 % width + index * 8) as u8) + .collect(); + encoders.push(Arc::new(Frame { + width, + height, + stride: width * 4, + timestamp_ms: index * 34, + bgra, + gpu: None, + })); + std::thread::sleep(Duration::from_millis(40)); + } + std::thread::sleep(Duration::from_millis(300)); + drop(encoders); + + let encoded: Vec = rx.try_iter().collect(); + let mut decoders = vec![VideoDecoder::for_codec(codec).expect("decoder")]; + decoders.push(crate::media::decode::software(codec).expect("software decoder")); + let pixels: Vec> = decoders + .into_iter() + .map(|mut decoder| { + let mut reassembler = Reassembler::new(); + let mut pictures = Vec::new(); + for (number, encoded) in encoded.iter().enumerate() { + let info = FrameInfo { + kind: Kind::Screen, + layer: encoded.layer, + frame: number as u32, + keyframe: encoded.keyframe, + recovery: false, + ts_ms: encoded.timestamp_ms, + parity: 1, + }; + fragments(info, &encoded.data, |packet| { + let Some(packet) = Packet::decode(packet) else { + panic!("fragment"); + }; + for assembled in reassembler.push(&packet, Instant::now()) { + pictures.extend( + decoder.decode(&assembled.data, assembled.timestamp_ms), + ); + } + }); + } + assert_eq!(pictures.len(), 10, "{codec:?} {:?}", decoder.engine()); + let frame = pictures + .pop() + .expect("picture") + .into_frame(media::SHARE_WIDTH) + .expect("frame"); + assert_eq!( + (frame.width, frame.height), + (width, height), + "{codec:?} {:?}", + decoder.engine() + ); + frame.bgra.to_vec() + }) + .collect(); + let difference = pixels[0] + .iter() + .zip(pixels.last().expect("pixels")) + .map(|(a, b)| u64::from(a.abs_diff(*b))) + .sum::() + / pixels[0].len() as u64; + assert!( + difference < 4, + "{codec:?} hardware vs software pixels differ by {difference}" + ); + } + } +} diff --git a/crates/client/src/share/fake.rs b/crates/client/src/share/fake.rs index c8798b9..89f8373 100644 --- a/crates/client/src/share/fake.rs +++ b/crates/client/src/share/fake.rs @@ -2,13 +2,13 @@ use std::{ sync::{ Arc, atomic::{AtomicBool, Ordering}, - mpsc::{Receiver, sync_channel}, + mpsc::sync_channel, }, thread::JoinHandle, time::{Duration, Instant}, }; -use super::frame::{BYTES_PER_PIXEL, DEFAULT_REFRESH, FRAME_QUEUE, Frame}; +use super::frame::{BYTES_PER_PIXEL, DEFAULT_REFRESH, FRAME_QUEUE, Feed, Frame, elapsed_ms}; pub struct Generator { stop: Arc, @@ -24,7 +24,7 @@ impl Drop for Generator { } } -pub fn start(spec: &str) -> (u32, u32, u32, Receiver, Generator) { +pub fn start(spec: &str) -> (Feed, Generator) { let parsed: Option<(u32, u32, u32)> = spec.split_once('@').and_then(|(size, fps)| { let (width, height) = size.split_once('x')?; Some((width.parse().ok()?, height.parse().ok()?, fps.parse().ok()?)) @@ -72,27 +72,20 @@ pub fn start(spec: &str) -> (u32, u32, u32, Receiver, Generator) { } } } - let frame = Frame { - width, - height, - stride: width * BYTES_PER_PIXEL as u32, - timestamp_ms: u32::try_from(started.elapsed().as_millis()) - .unwrap_or(u32::MAX), - bgra, - gpu: None, - }; - let _ = frames_tx.try_send(frame); + let _ = + frames_tx.try_send(Frame::cpu(width, height, elapsed_ms(started), bgra)); number += 1; std::thread::sleep(interval); } }) .ok() }; - ( + let feed = Feed { width, height, - refresh, - frames_rx, - Generator { stop, thread }, - ) + largest: (width, height), + modes: vec![(height, refresh)], + frames: frames_rx, + }; + (feed, Generator { stop, thread }) } diff --git a/crates/client/src/share/frame.rs b/crates/client/src/share/frame.rs index 6852096..f8070ab 100644 --- a/crates/client/src/share/frame.rs +++ b/crates/client/src/share/frame.rs @@ -1,9 +1,12 @@ -use std::sync::{ - atomic::{AtomicBool, Ordering}, - mpsc::SyncSender, +use std::{ + sync::{ + atomic::{AtomicBool, Ordering}, + mpsc::{Receiver, SyncSender}, + }, + time::Instant, }; -use common::share::Layer; +use common::share::{Layer, Mode}; use crate::media::decode::Engine; @@ -11,6 +14,14 @@ pub const DEFAULT_REFRESH: u32 = 60; pub const FRAME_QUEUE: usize = 2; pub const BYTES_PER_PIXEL: usize = 4; +pub struct Feed { + pub width: u32, + pub height: u32, + pub largest: (u32, u32), + pub modes: Vec, + pub frames: Receiver, +} + pub struct Frame { pub width: u32, pub height: u32, @@ -59,7 +70,30 @@ pub fn take_gpu_failed() -> bool { GPU_FAILED.swap(false, Ordering::Relaxed) } +pub fn elapsed_ms(since: Instant) -> u32 { + u32::try_from(since.elapsed().as_millis()).unwrap_or(u32::MAX) +} + +pub fn pack_rows(source: &[u8], stride: usize, row: usize, height: u32) -> Option> { + let mut packed = Vec::with_capacity(row * height as usize); + for line in 0..height as usize { + packed.extend_from_slice(source.get(line * stride..line * stride + row)?); + } + Some(packed) +} + impl Frame { + pub fn cpu(width: u32, height: u32, timestamp_ms: u32, bgra: Vec) -> Self { + Self { + width, + height, + stride: width * BYTES_PER_PIXEL as u32, + timestamp_ms, + bgra, + gpu: None, + } + } + pub fn to_i420(&self, width: u32, height: u32) -> Option { let source = pixel::Bgra { data: &self.bgra, @@ -78,4 +112,5 @@ pub struct Encoded { pub keyframe: bool, pub recovery: bool, pub timestamp_ms: u32, + pub bitrate: u32, } diff --git a/crates/client/src/share/mod.rs b/crates/client/src/share/mod.rs index d985b56..ad4dc91 100644 --- a/crates/client/src/share/mod.rs +++ b/crates/client/src/share/mod.rs @@ -12,6 +12,23 @@ pub mod capture; #[path = "capture_windows.rs"] pub mod capture; pub mod congestion; +pub mod encode; +pub mod fake; +pub mod frame; +pub mod pacer; +pub mod reassembly; +pub mod send; +#[cfg(not(any(target_os = "linux", target_os = "windows")))] +mod unsupported; +pub mod watch; +#[cfg(not(any(target_os = "linux", target_os = "windows")))] +pub use unsupported::{audio_capture, camera, capture}; + +pub mod session { + pub use super::send::Sharing; + pub use super::watch::{Tick, WatchQuality, Watching}; + pub use common::stats::{LayerStats, ShareSample, WatchStats}; +} #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] pub enum Target { @@ -24,14 +41,3 @@ pub struct Source { pub name: String, pub preview: Option, } -pub mod encode; -#[cfg(any(target_os = "linux", target_os = "windows"))] -pub mod fake; -pub mod frame; -pub mod pacer; -pub mod reassembly; -pub mod session; -#[cfg(not(any(target_os = "linux", target_os = "windows")))] -mod unsupported; -#[cfg(not(any(target_os = "linux", target_os = "windows")))] -pub use unsupported::{audio_capture, camera, capture}; diff --git a/crates/client/src/share/reassembly.rs b/crates/client/src/share/reassembly.rs index fa0bb1a..a911ad4 100644 --- a/crates/client/src/share/reassembly.rs +++ b/crates/client/src/share/reassembly.rs @@ -15,8 +15,16 @@ const NACK_SPAN: u32 = 32; #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Phase { - WaitingKeyframe, + Fresh, Streaming, + Broken, +} + +#[derive(Debug, Clone, Copy)] +struct Header { + keyframe: bool, + recovery: bool, + timestamp_ms: u32, } #[derive(Debug)] @@ -35,18 +43,12 @@ pub struct Nack { } struct Ready { - layer: Layer, - keyframe: bool, - recovery: bool, - timestamp_ms: u32, + header: Header, data: Option>, } struct Pending { - layer: Layer, - keyframe: bool, - recovery: bool, - timestamp_ms: u32, + header: Header, data: usize, length: usize, present: usize, @@ -60,14 +62,10 @@ struct Pending { } impl Pending { - fn new(packet: (Layer, bool, bool, u32, u32, u16), now: Instant) -> Pending { - let (layer, keyframe, recovery, timestamp_ms, length, parity) = packet; + fn new(header: Header, length: u32, parity: u16, now: Instant) -> Pending { let layout = layout(length, parity); Pending { - layer, - keyframe, - recovery, - timestamp_ms, + header, data: layout.data, length: length as usize, present: 0, @@ -139,7 +137,6 @@ pub struct Reassembler { newest: Option, gap: Option<(u32, Instant)>, phase: Phase, - streamed: bool, received_frames: u32, lost_frames: u32, expected_shards: u32, @@ -163,8 +160,7 @@ impl Reassembler { last: None, newest: None, gap: None, - phase: Phase::WaitingKeyframe, - streamed: false, + phase: Phase::Fresh, received_frames: 0, lost_frames: 0, expected_shards: 0, @@ -197,8 +193,7 @@ impl Reassembler { self.last = None; self.newest = None; self.gap = None; - self.phase = Phase::WaitingKeyframe; - self.streamed = false; + self.phase = Phase::Fresh; } if self.last.is_some_and(|last| !seq_newer(frame, last)) || self.ready.contains_key(&frame) { @@ -214,14 +209,19 @@ impl Reassembler { self.vanished.clear(); self.gap = None; self.last = Some(frame.wrapping_sub(1)); - self.phase = Phase::WaitingKeyframe; + self.stall(); } if self.newest.is_none_or(|newest| seq_newer(frame, newest)) { self.newest = Some(frame); } let accounted = self.vanished.contains_key(&frame); + let header = Header { + keyframe, + recovery, + timestamp_ms: ts_ms, + }; let pending = self.pending.entry(frame).or_insert_with(|| { - let mut pending = Pending::new((layer, keyframe, recovery, ts_ms, length, parity), now); + let mut pending = Pending::new(header, length, parity, now); pending.accounted = accounted; pending }); @@ -232,13 +232,11 @@ impl Reassembler { self.account(&complete); self.last_count = complete.shards.len() as u32; let ready = Ready { - layer: complete.layer, - keyframe: complete.keyframe, - recovery: complete.recovery, - timestamp_ms: complete.timestamp_ms, + header: complete.header, data: complete.assemble(), }; - let fresh = ready.keyframe || (ready.recovery && self.streamed); + let fresh = + ready.header.keyframe || (ready.header.recovery && self.phase != Phase::Fresh); self.ready.insert(frame, ready); if fresh { self.skip_to(frame); @@ -281,7 +279,7 @@ impl Reassembler { } self.vanished.remove(&frame); self.lost_frames += 1; - self.phase = Phase::WaitingKeyframe; + self.stall(); self.last = Some(frame); self.gap = None; out.extend(self.flush(since)); @@ -320,7 +318,7 @@ impl Reassembler { pending.nacks += 1; pending.nacked = Some(now); out.push(Nack { - layer: pending.layer, + layer, frame, indices: pending.missing(), }); @@ -381,25 +379,31 @@ impl Reassembler { .reduce(|a, b| if seq_newer(a, b) { b } else { a }) } + fn stall(&mut self) { + if self.phase == Phase::Streaming { + self.phase = Phase::Broken; + } + } + fn deliver(&mut self, ready: Ready) -> Option { let Some(data) = ready.data else { self.lost_frames += 1; - self.phase = Phase::WaitingKeyframe; + self.stall(); return None; }; self.received_frames += 1; - if ready.keyframe || (ready.recovery && self.streamed) { + let header = ready.header; + if header.keyframe || (header.recovery && self.phase != Phase::Fresh) { self.phase = Phase::Streaming; } - if self.phase == Phase::WaitingKeyframe { + if self.phase != Phase::Streaming { return None; } - self.streamed = true; Some(Assembled { - layer: ready.layer, + layer: self.layer?, data, - keyframe: ready.keyframe, - timestamp_ms: ready.timestamp_ms, + keyframe: header.keyframe, + timestamp_ms: header.timestamp_ms, }) } @@ -443,12 +447,12 @@ impl Reassembler { ratio } - pub fn needs_keyframe(&self) -> bool { - self.phase == Phase::WaitingKeyframe - } - - pub fn can_recover(&self) -> bool { - self.streamed + pub fn need(&self) -> Option { + match self.phase { + Phase::Streaming => None, + Phase::Fresh => Some(false), + Phase::Broken => Some(true), + } } pub fn loss_ratio(&mut self) -> f32 { @@ -558,7 +562,7 @@ mod tests { .expire(now + Duration::from_secs(1), Duration::from_millis(50)) .is_empty() ); - assert!(!reassembler.needs_keyframe()); + assert_eq!(reassembler.need(), None); } #[test] diff --git a/crates/client/src/share/send.rs b/crates/client/src/share/send.rs new file mode 100644 index 0000000..2ecc1b4 --- /dev/null +++ b/crates/client/src/share/send.rs @@ -0,0 +1,537 @@ +use std::{ + collections::HashMap, + sync::{ + Arc, Mutex, + atomic::{AtomicBool, Ordering}, + mpsc::{self, Receiver, RecvTimeoutError}, + }, + time::{Duration, Instant}, +}; + +use bytes::Bytes; +use common::{ + constant::{ + SHARE_AUDIO_BITRATE, SHARE_AUDIO_CHANNELS, VOICE_FRAME_SAMPLES, VOICE_MAX_PAYLOAD, + VOICE_SAMPLE_RATE, + }, + datagram::{self, FrameInfo, Link, Pace, Packet, fragments, warn_if_small}, + share::{Codec, Kind, Layer, Mode, Quality, Source, clamp}, +}; +use ec_opus::{Application, Encoder}; +use quinn::Connection; +use rtrb::{Consumer, RingBuffer}; +use tracing::warn; + +use super::{ + Target, + audio::AudioMode, + audio_capture::{self, AudioCapture}, + camera::{self, Camera}, + capture::{self, Capture}, + congestion::{self, Controller, Loss, Uplink}, + encode::{self, Encoders}, + fake, + frame::{Encoded, Feed, Frame}, + pacer::Pacer, +}; +use crate::lang::w; +use crate::media::{ + decode::{Engine, lock}, + meter::Meter, +}; +use crate::worker::{Worker, wait}; + +const CHUNK_MS: u32 = VOICE_FRAME_SAMPLES as u32 * 1000 / VOICE_SAMPLE_RATE; +const STOP_CHECK: Duration = Duration::from_millis(100); +const CHUNK_SAMPLES: usize = VOICE_FRAME_SAMPLES * SHARE_AUDIO_CHANNELS; +pub(super) const AUDIO_STEP: Duration = Duration::from_millis(5); +pub(super) const AUDIO_RING: usize = VOICE_SAMPLE_RATE as usize * SHARE_AUDIO_CHANNELS / 2; + +struct Tally { + engine: Engine, + bytes: u64, + frames: u32, + last_ms: Option, + gaps: Vec, +} + +struct Output { + since: Instant, + tallies: HashMap, +} + +impl Output { + fn record(&mut self, encoded: &Encoded) { + let tally = self.tallies.entry(encoded.layer).or_insert(Tally { + engine: encoded.engine, + bytes: 0, + frames: 0, + last_ms: None, + gaps: Vec::new(), + }); + tally.bytes += encoded.data.len() as u64; + tally.frames += 1; + if let Some(last) = tally.last_ms.replace(encoded.timestamp_ms) { + tally + .gaps + .push(i64::from(encoded.timestamp_ms) - i64::from(last)); + } + } + + fn take(&mut self) -> Vec { + let seconds = std::mem::replace(&mut self.since, Instant::now()) + .elapsed() + .as_secs_f32() + .max(f32::EPSILON); + let mut stats: Vec = std::mem::take(&mut self.tallies) + .into_iter() + .map(|(layer, mut tally)| common::stats::LayerStats { + layer, + engine: tally.engine, + kbps: (tally.bytes as f32 * 8. / 1000. / seconds) as u32, + fps: tally.frames as f32 / seconds, + gap_ms: spread(&mut tally.gaps), + }) + .collect(); + stats.sort_by_key(|stat| stat.layer.to_byte()); + stats + } +} + +pub(super) fn spread(values: &mut [i64]) -> (i64, i64) { + values.sort_unstable(); + let at = |part: usize| values.get(values.len() * part / 100).copied().unwrap_or(0); + (at(50), at(95)) +} + +fn next(rx: &Receiver, stop: &AtomicBool) -> Option { + while !stop.load(Ordering::Relaxed) { + match rx.recv_timeout(STOP_CHECK) { + Ok(item) => return Some(item), + Err(RecvTimeoutError::Timeout) => {} + Err(RecvTimeoutError::Disconnected) => return None, + } + } + None +} + +enum Input { + Screen { _capture: Capture }, + Camera(Camera), + Fake { _generator: fake::Generator }, +} + +async fn open( + kind: Kind, + top: Quality, + target: Option, + camera_device: Option, +) -> Result<(Feed, Input), String> { + let spec = std::env::var(match kind { + Kind::Screen => "YUMUSH_TEST_CAPTURE", + Kind::Camera => "YUMUSH_TEST_CAMERA", + }); + if let Ok(spec) = spec { + let (feed, generator) = fake::start(&spec); + return Ok(( + feed, + Input::Fake { + _generator: generator, + }, + )); + } + match kind { + Kind::Screen => { + let (feed, capture) = capture::open(target).await?; + Ok((feed, Input::Screen { _capture: capture })) + } + Kind::Camera => { + let (feed, camera) = + tokio::task::spawn_blocking(move || camera::open(top, camera_device)) + .await + .map_err(|error| error.to_string())??; + Ok((feed, Input::Camera(camera))) + } + } +} + +pub struct ShareAudio { + mode: AudioMode, + _capture: AudioCapture, + _encode: Worker, +} + +pub struct Sharing { + kind: Kind, + encoders: Arc>, + _feed: Worker, + ended: Arc, + input: Input, + modes: Vec, + source: Source, + started: Instant, + audio: Option, + meter: Meter, + _sender: Worker, + _congestion: Worker, + loss: Arc, + sent: Arc>, +} + +impl Sharing { + fn clamp(top: Quality, modes: &[Mode]) -> Quality { + clamp(top, modes, encode::capabilities().max_height) + } + + pub async fn start( + connection: Connection, + kind: Kind, + top: Quality, + encode: Vec, + audio: Option, + target: Option, + camera_device: Option, + ) -> Result { + if encode.is_empty() { + return Err(w().session.codec_unavailable.into()); + } + let audio = audio.filter(|_| kind == Kind::Screen); + warn_if_small(&connection); + let (frame_feed, input) = open(kind, top, target, camera_device).await?; + let Feed { + width, + height, + largest: (largest_width, largest_height), + modes, + frames, + } = frame_feed; + let source = Source { + width: largest_width, + height: largest_height, + top: Self::clamp(top, &modes), + encode, + }; + + let (output, encoded) = mpsc::channel(); + let encoders = Arc::new(Mutex::new(Encoders::new(width, height, output))); + let started = Instant::now(); + let ended = Arc::new(AtomicBool::new(false)); + let feed = { + let (encoders, ended) = (encoders.clone(), ended.clone()); + Worker::spawn("share-feed", move |stop| { + feed(frames, encoders, started, stop); + ended.store(true, Ordering::Relaxed); + }) + }; + + let meter = Meter::default(); + let audio = start_audio(&connection, started, audio, meter.clone()); + + let sent = Arc::new(Mutex::new(Output { + since: Instant::now(), + tallies: HashMap::new(), + })); + let loss = Arc::new(Loss::default()); + let congestion = { + let (connection, encoders, loss) = (connection.clone(), encoders.clone(), loss.clone()); + Worker::spawn("share-congestion", move |stop| { + control(&connection, &encoders, &loss, stop) + }) + }; + let sender = { + let (sent, encoders, loss) = (sent.clone(), encoders.clone(), loss.clone()); + Worker::spawn("share-send", move |stop| { + send(kind, encoded, connection, encoders, loss, sent, stop) + }) + }; + + Ok(Sharing { + kind, + encoders, + _feed: feed, + ended, + input, + modes, + source, + started, + audio, + meter, + _sender: sender, + _congestion: congestion, + sent, + loss, + }) + } + + pub fn source(&self) -> Source { + self.source.clone() + } + + pub fn modes(&self) -> Vec { + self.modes.clone() + } + + pub fn ended(&self) -> bool { + self.ended.load(Ordering::Relaxed) + || matches!(&self.input, Input::Camera(camera) if camera.stalled()) + } + + pub fn reopens(&self, top: Quality) -> bool { + self.kind == Kind::Camera && Self::clamp(top, &self.modes) != self.source.top + } + + pub fn update( + &mut self, + connection: &Connection, + top: Quality, + encode: Vec, + audio: Option, + ) -> Result<(Source, Option), String> { + if encode.is_empty() { + return Err(w().session.codec_unavailable.into()); + } + self.source.top = Self::clamp(top, &self.modes); + self.source.encode = encode; + let audio = audio.filter(|_| self.kind == Kind::Screen); + let retired = if self.audio.as_ref().map(|shared| &shared.mode) != audio.as_ref() { + std::mem::replace( + &mut self.audio, + start_audio(connection, self.started, audio, self.meter.clone()), + ) + } else { + None + }; + Ok((self.source.clone(), retired)) + } + + pub fn set_layers(&mut self, layers: &[Layer]) { + lock(&self.encoders).set_layers(layers); + if let Input::Camera(camera) = &self.input { + let fps = layers + .iter() + .map(|layer| layer.quality.fps.value()) + .max() + .unwrap_or(0); + camera.set_fps(fps); + } + } + + pub fn keyframe(&self, layer: Layer, recover: bool) { + lock(&self.encoders).keyframe(layer, recover); + } + + pub fn ack(&self, layer: Layer, timestamp_ms: u32) { + lock(&self.encoders).ack(layer, timestamp_ms); + } + + pub fn report_loss(&self, permille: u16) { + self.loss.report(f32::from(permille) / 1000.0); + } + + pub fn stats(&self) -> Vec { + lock(&self.sent).take() + } + + pub fn level(&self) -> Vec { + self.meter.take() + } +} + +fn start_audio( + connection: &Connection, + started: Instant, + mode: Option, + meter: Meter, +) -> Option { + let mode = mode?; + let (producer, consumer) = RingBuffer::new(AUDIO_RING); + let audio_connection = connection.clone(); + let encode = Worker::spawn("share-audio-encode", move |stop| { + encode_audio(consumer, audio_connection, started, &meter, stop) + }); + Some(ShareAudio { + _capture: audio_capture::start(mode.clone(), producer), + _encode: encode, + mode, + }) +} + +fn feed( + frames: Receiver, + encoders: Arc>, + started: Instant, + stop: &AtomicBool, +) { + let mut previous: Option> = None; + let mut skipped = 0u32; + let mut logged = Instant::now(); + while let Some(mut frame) = next(&frames, stop) { + frame.timestamp_ms = started.elapsed().as_millis() as u32; + let unchanged = frame.gpu.is_none() + && previous.as_ref().is_some_and(|last| { + last.width == frame.width + && last.height == frame.height + && last.bgra == frame.bgra + && frame.timestamp_ms.saturating_sub(last.timestamp_ms) < 1000 + }); + let mut encoders = lock(&encoders); + if unchanged && !encoders.keyframe_pending() { + skipped += 1; + } else { + let gpu = frame.gpu.is_some(); + let frame = Arc::new(frame); + encoders.push(frame.clone()); + drop(encoders); + previous = (!gpu).then_some(frame); + } + if logged.elapsed() >= Duration::from_secs(10) { + tracing::debug!(target: "metrics", skipped, "feed"); + skipped = 0; + logged = Instant::now(); + } + } +} + +fn control(connection: &Connection, encoders: &Mutex, loss: &Loss, stop: &AtomicBool) { + let mut controller = Controller::default(); + let mut scale = 1.0; + while wait(stop, congestion::PERIOD) { + let (next, loss_now) = controller.observe(Uplink::read(connection)); + loss.decay(); + loss.report(loss_now); + if next < scale { + tracing::info!(scale = next, "share uplink congested"); + } + if next != scale { + scale = next; + lock(encoders).set_scale(scale); + } + } +} + +fn send( + kind: Kind, + rx: Receiver, + connection: Connection, + encoders: Arc>, + loss: Arc, + sent: Arc>, + stop: &AtomicBool, +) { + let seed = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |since| since.as_millis() as u32); + let mut lanes: HashMap> = HashMap::new(); + while let Some(item) = next(&rx, stop) { + lock(&sent).record(&item); + let lane = lanes.entry(item.layer).or_insert_with(|| { + let (tx, rx) = mpsc::channel(); + let (connection, loss, encoders) = (connection.clone(), loss.clone(), encoders.clone()); + let _ = std::thread::Builder::new() + .name("share-send".to_string()) + .spawn(move || send_layer(kind, rx, &connection, &encoders, &loss, seed)); + tx + }); + let _ = lane.send(item); + } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Flow { + Flowing, + AwaitingFresh, +} + +fn send_layer( + kind: Kind, + rx: Receiver, + connection: &Connection, + encoders: &Mutex, + loss: &Loss, + seed: u32, +) { + let mut pacer = Pacer::default(); + let mut number = seed; + let mut link = Link::default(); + let mut flow = Flow::Flowing; + for item in rx { + let fresh = item.keyframe || item.recovery; + let send = match link.pace(connection, fresh) { + Pace::Send => { + if fresh { + flow = Flow::Flowing; + } + flow == Flow::Flowing + } + Pace::Pause => { + tracing::info!(?kind, "uplink congested, pausing until it drains"); + flow = Flow::AwaitingFresh; + false + } + Pace::Drop => false, + Pace::Resume => { + lock(encoders).keyframe(item.layer, true); + false + } + }; + if !send { + number = number.wrapping_add(1); + continue; + } + let info = FrameInfo { + kind, + layer: item.layer, + frame: number, + keyframe: item.keyframe, + recovery: item.recovery, + ts_ms: item.timestamp_ms, + parity: loss.parity(item.data.len() as u32, item.keyframe), + }; + number = number.wrapping_add(1); + fragments(info, &item.data, |packet| { + pacer.wait(packet.len(), item.bitrate); + datagram::send(connection, Bytes::copy_from_slice(packet)); + }); + } +} + +fn encode_audio( + mut samples: Consumer, + connection: Connection, + started: Instant, + meter: &Meter, + stop: &AtomicBool, +) { + let Ok(mut encoder) = Encoder::new(VOICE_SAMPLE_RATE, SHARE_AUDIO_CHANNELS, Application::Audio) + else { + warn!("share audio encoder not started"); + return; + }; + encoder.set_bitrate(SHARE_AUDIO_BITRATE as u32); + let mut pcm = vec![0.0; CHUNK_SAMPLES]; + let mut payload = [0u8; VOICE_MAX_PAYLOAD]; + let mut packet = Vec::new(); + let mut sequence = 0u32; + while !stop.load(Ordering::Relaxed) { + if samples.slots() < CHUNK_SAMPLES { + wait(stop, AUDIO_STEP); + continue; + } + for sample in pcm.iter_mut() { + *sample = samples.pop().unwrap_or(0.0); + } + meter.record(&pcm, SHARE_AUDIO_CHANNELS); + let Ok(length) = encoder.encode_float(&pcm, VOICE_FRAME_SAMPLES, &mut payload) else { + continue; + }; + packet.clear(); + Packet::ScreenAudio { + seq: sequence, + ts_ms: (started.elapsed().as_millis() as u32).saturating_sub(CHUNK_MS), + opus: &payload[..length], + } + .encode(&mut packet); + datagram::send(&connection, Bytes::copy_from_slice(&packet)); + sequence = sequence.wrapping_add(1); + } +} diff --git a/crates/client/src/share/unsupported.rs b/crates/client/src/share/unsupported.rs index 372ff53..0556c04 100644 --- a/crates/client/src/share/unsupported.rs +++ b/crates/client/src/share/unsupported.rs @@ -1,29 +1,22 @@ -use std::sync::mpsc::Receiver; - use crate::lang::w; use super::{ audio::{AudioApp, AudioMode}, - frame::Frame, + frame::Feed, }; pub mod capture { use super::*; - pub struct Capture { - pub width: u32, - pub height: u32, - pub refresh: u32, - pub frames: Receiver, - } + pub struct Capture; pub const PICKS: bool = false; - pub fn targets(_: &dyn Fn(crate::share::Target) -> bool) -> Option> { - None + pub fn targets(_: &dyn Fn(crate::share::Target) -> bool) -> Vec { + Vec::new() } - pub async fn open(_: Option) -> Result { + pub async fn open(_: Option) -> Result<(Feed, Capture), String> { Err(w().unsupported.not_supported.into()) } } @@ -31,18 +24,16 @@ pub mod capture { pub mod camera { use super::*; - use std::sync::{Arc, atomic::AtomicU32}; - use common::share::{Mode, Quality}; - pub struct Camera { - pub width: u32, - pub height: u32, - pub refresh: u32, - pub size: (u32, u32), - pub modes: Vec, - pub frames: Receiver, - pub fps: Arc, + pub struct Camera; + + impl Camera { + pub fn stalled(&self) -> bool { + false + } + + pub fn set_fps(&self, _: u32) {} } pub fn devices() -> Vec { @@ -53,7 +44,7 @@ pub mod camera { name } - pub fn open(_: Quality, _: Option) -> Result { + pub fn open(_: Quality, _: Option) -> Result<(Feed, Camera), String> { Err(w().unsupported.not_supported.into()) } diff --git a/crates/client/src/share/session.rs b/crates/client/src/share/watch.rs similarity index 52% rename from crates/client/src/share/session.rs rename to crates/client/src/share/watch.rs index 3bfe2d8..6abb2e1 100644 --- a/crates/client/src/share/session.rs +++ b/crates/client/src/share/watch.rs @@ -11,33 +11,20 @@ use std::{ use bytes::Bytes; use common::{ - constant::{ - SHARE_AUDIO_BITRATE, SHARE_AUDIO_CHANNELS, VOICE_FRAME_SAMPLES, VOICE_MAX_PAYLOAD, - VOICE_SAMPLE_RATE, - }, - datagram::{ - self, FrameInfo, Gate, Link, Packet, RELAY_PREFIX, fragments, split, warn_if_small, - }, + constant::{SHARE_AUDIO_CHANNELS, VOICE_SAMPLE_RATE}, + datagram::{self, Packet, RELAY_PREFIX, split}, model::Id, - share::{Codec, Fps, Kind, Layer, Mode, Quality, Resolution, Source, clamp}, + share::{Codec, Fps, Kind, Layer, Quality, Resolution}, }; -use ec_opus::{Application, Decoder, Encoder}; +use ec_opus::Decoder; use quinn::Connection; -use rtrb::{Consumer, Producer, RingBuffer}; +use rtrb::{Producer, RingBuffer}; use tracing::warn; use super::{ - audio::AudioMode, - audio_capture::{self, AudioCapture}, - camera::{self, Camera}, - capture::{self, Capture}, - congestion::{self, Controller, Loss, Uplink}, - encode::{self, Encoders}, - frame::{Encoded, Frame}, - pacer::Pacer, reassembly::{Assembled, Nack, Reassembler}, + send::{AUDIO_RING, AUDIO_STEP, spread}, }; -use crate::lang::w; use crate::media::{ self, decode::{Engine, VideoDecoder, lock}, @@ -45,17 +32,15 @@ use crate::media::{ }; use crate::voice::{ Playback, - audio::{self, Audio, Choice, Worker, wait}, + audio::{self, Audio, Choice}, }; +use crate::worker::Worker; -const CHUNK_MS: u32 = VOICE_FRAME_SAMPLES as u32 * 1000 / VOICE_SAMPLE_RATE; -const STOP_CHECK: Duration = Duration::from_millis(100); const NACK_TICK: Duration = Duration::from_millis(5); const NACK_SLACK: Duration = Duration::from_millis(40); const NACK_GIVE_UP: Duration = Duration::from_millis(250); const DEFAULT_RTT: Duration = Duration::from_millis(50); const ACK_INTERVAL: Duration = Duration::from_millis(250); -const AUDIO_STEP: Duration = Duration::from_millis(5); const SAMPLE: Duration = Duration::from_secs(1); const INITIAL_DELAY_MS: i64 = 100; const MIN_DELAY_MS: i64 = 20; @@ -86,9 +71,8 @@ const QUEUING_LIMIT_MS: i64 = 60; const QUEUING_CLEAN_MS: i64 = 20; const QUEUING_WINDOW_MS: i64 = 1000; const QUEUING_FLOOR_SECONDS: i64 = 30; -const CHUNK_SAMPLES: usize = VOICE_FRAME_SAMPLES * SHARE_AUDIO_CHANNELS; const DECODE_SAMPLES: usize = VOICE_SAMPLE_RATE as usize * 120 / 1000 * SHARE_AUDIO_CHANNELS; -const AUDIO_RING: usize = VOICE_SAMPLE_RATE as usize * SHARE_AUDIO_CHANNELS / 2; +const REFERENCE: (u32, u32) = (3840, 2160); #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum WatchQuality { @@ -103,472 +87,6 @@ pub enum Tick { Loss(u16), } -pub use common::stats::{LayerStats, ShareSample, WatchStats}; - -struct Tally { - engine: Engine, - bytes: u64, - frames: u32, - last_ms: Option, - gaps: Vec, -} - -struct Sent { - since: Instant, - tallies: HashMap, -} - -impl Sent { - fn record(&mut self, encoded: &Encoded) { - let tally = self.tallies.entry(encoded.layer).or_insert(Tally { - engine: encoded.engine, - bytes: 0, - frames: 0, - last_ms: None, - gaps: Vec::new(), - }); - tally.bytes += encoded.data.len() as u64; - tally.frames += 1; - if let Some(last) = tally.last_ms.replace(encoded.timestamp_ms) { - tally - .gaps - .push(i64::from(encoded.timestamp_ms) - i64::from(last)); - } - } - - fn take(&mut self) -> Vec { - let seconds = std::mem::replace(&mut self.since, Instant::now()) - .elapsed() - .as_secs_f32() - .max(f32::EPSILON); - let mut stats: Vec = std::mem::take(&mut self.tallies) - .into_iter() - .map(|(layer, mut tally)| LayerStats { - layer, - engine: tally.engine, - kbps: (tally.bytes as f32 * 8. / 1000. / seconds) as u32, - fps: tally.frames as f32 / seconds, - gap_ms: spread(&mut tally.gaps), - }) - .collect(); - stats.sort_by_key(|stat| stat.layer.to_byte()); - stats - } -} - -fn spread(values: &mut [i64]) -> (i64, i64) { - values.sort_unstable(); - let at = |part: usize| values.get(values.len() * part / 100).copied().unwrap_or(0); - (at(50), at(95)) -} - -fn next(rx: &Receiver, stop: &AtomicBool) -> Option { - while !stop.load(Ordering::Relaxed) { - match rx.recv_timeout(STOP_CHECK) { - Ok(item) => return Some(item), - Err(RecvTimeoutError::Timeout) => {} - Err(RecvTimeoutError::Disconnected) => return None, - } - } - None -} - -enum Input { - Screen(Capture), - Camera(Camera), -} - -impl Input { - fn size(&self) -> (u32, u32, u32) { - match self { - Self::Screen(capture) => (capture.width, capture.height, capture.refresh), - Self::Camera(camera) => (camera.width, camera.height, camera.refresh), - } - } - - fn size_and_modes(&self) -> ((u32, u32), Vec) { - match self { - Self::Screen(capture) => ( - (capture.width, capture.height), - vec![(capture.height, capture.refresh)], - ), - Self::Camera(camera) => (camera.size, camera.modes.clone()), - } - } - - fn take(&mut self) -> Receiver { - let frames = match self { - Self::Screen(capture) => &mut capture.frames, - Self::Camera(camera) => &mut camera.frames, - }; - std::mem::replace(frames, mpsc::channel().1) - } -} - -pub struct Sharing { - encoders: Arc>, - _feed: Worker, - ended: Arc, - _input: Input, - modes: Vec, - source: Source, - started: Instant, - audio: Option, - _audio: Option, - _audio_encode: Option, - meter: Meter, - _sender: Worker, - _congestion: Worker, - loss: Arc, - sent: Arc>, -} - -impl Sharing { - fn clamp(top: Quality, modes: &[Mode]) -> Quality { - clamp(top, modes, encode::capabilities().max_height) - } - - pub async fn start( - connection: Connection, - kind: Kind, - top: Quality, - encode: Vec, - audio: Option, - target: Option, - camera_device: Option, - ) -> Result { - if encode.is_empty() { - return Err(w().session.codec_unavailable.into()); - } - let audio = audio.filter(|_| kind == Kind::Screen); - warn_if_small(&connection); - let mut input = match kind { - Kind::Screen => Input::Screen(capture::open(target).await?), - Kind::Camera => Input::Camera( - tokio::task::spawn_blocking(move || camera::open(top, camera_device)) - .await - .map_err(|error| error.to_string())??, - ), - }; - let (width, height, _) = input.size(); - let ((largest_width, largest_height), modes) = input.size_and_modes(); - let source = Source { - width: largest_width, - height: largest_height, - top: Self::clamp(top, &modes), - encode, - }; - - let frames = input.take(); - let (output, encoded) = mpsc::channel(); - let encoders = Arc::new(Mutex::new(Encoders::new(width, height, output))); - let started = Instant::now(); - let ended = Arc::new(AtomicBool::new(false)); - let feed = { - let (encoders, ended) = (encoders.clone(), ended.clone()); - Worker::spawn("share-feed", move |stop| { - feed(frames, encoders, started, stop); - ended.store(true, Ordering::Relaxed); - }) - }; - - let meter = Meter::default(); - let (audio_capture, audio_encode) = - start_audio(&connection, started, audio.clone(), meter.clone()); - - let sent = Arc::new(Mutex::new(Sent { - since: Instant::now(), - tallies: HashMap::new(), - })); - let loss = Arc::new(Loss::default()); - let congestion = { - let (connection, encoders, loss) = (connection.clone(), encoders.clone(), loss.clone()); - Worker::spawn("share-congestion", move |stop| { - control(&connection, &encoders, &loss, stop) - }) - }; - let sender = { - let (sent, encoders, loss) = (sent.clone(), encoders.clone(), loss.clone()); - Worker::spawn("share-send", move |stop| { - send(kind, encoded, connection, encoders, loss, sent, stop) - }) - }; - - Ok(Sharing { - encoders, - _feed: feed, - ended, - _input: input, - modes, - source, - started, - audio, - _audio: audio_capture, - _audio_encode: audio_encode, - meter, - _sender: sender, - _congestion: congestion, - sent, - loss, - }) - } - - pub fn source(&self) -> Source { - self.source.clone() - } - - pub fn modes(&self) -> Vec { - self.modes.clone() - } - - pub fn ended(&self) -> bool { - self.ended.load(Ordering::Relaxed) - || matches!(&self._input, Input::Camera(camera) if camera.stalled()) - } - - pub fn reopens(&self, top: Quality) -> bool { - matches!(self._input, Input::Camera(_)) && Self::clamp(top, &self.modes) != self.source.top - } - - pub fn update( - &mut self, - connection: &Connection, - top: Quality, - encode: Vec, - audio: Option, - ) -> Result { - if encode.is_empty() { - return Err(w().session.codec_unavailable.into()); - } - self.source.top = Self::clamp(top, &self.modes); - self.source.encode = encode; - if self.audio != audio { - self.audio = audio.clone(); - (self._audio, self._audio_encode) = - start_audio(connection, self.started, audio, self.meter.clone()); - } - - Ok(self.source.clone()) - } - - pub fn set_layers(&mut self, layers: &[Layer]) { - lock(&self.encoders).set_layers(layers); - if let Input::Camera(camera) = &self._input { - let fps = layers - .iter() - .map(|layer| layer.quality.fps.value()) - .max() - .unwrap_or(0); - camera.fps.store(fps, Ordering::Relaxed); - } - } - - pub fn keyframe(&self, layer: Layer, recover: bool) { - lock(&self.encoders).keyframe(layer, recover); - } - - pub fn ack(&self, layer: Layer, timestamp_ms: u32) { - lock(&self.encoders).ack(layer, timestamp_ms); - } - - pub fn report_loss(&self, permille: u16) { - self.loss.report(f32::from(permille) / 1000.0); - } - - pub fn stats(&self) -> Vec { - lock(&self.sent).take() - } - - pub fn level(&self) -> Vec { - self.meter.take() - } -} - -fn start_audio( - connection: &Connection, - started: Instant, - mode: Option, - meter: Meter, -) -> (Option, Option) { - let Some(mode) = mode else { - return (None, None); - }; - let (producer, consumer) = RingBuffer::new(AUDIO_RING); - let audio_connection = connection.clone(); - let encode = Worker::spawn("share-audio-encode", move |stop| { - encode_audio(consumer, audio_connection, started, &meter, stop) - }); - (Some(audio_capture::start(mode, producer)), Some(encode)) -} - -fn feed( - frames: Receiver, - encoders: Arc>, - started: Instant, - stop: &AtomicBool, -) { - let mut previous: Option> = None; - let mut skipped = 0u32; - let mut logged = Instant::now(); - while let Some(mut frame) = next(&frames, stop) { - frame.timestamp_ms = started.elapsed().as_millis() as u32; - let unchanged = frame.gpu.is_none() - && previous.as_ref().is_some_and(|last| { - last.width == frame.width - && last.height == frame.height - && last.bgra == frame.bgra - && frame.timestamp_ms.saturating_sub(last.timestamp_ms) < 1000 - }); - let mut encoders = lock(&encoders); - if unchanged && !encoders.keyframe_pending() { - skipped += 1; - } else { - let gpu = frame.gpu.is_some(); - let frame = Arc::new(frame); - encoders.push(frame.clone()); - drop(encoders); - previous = (!gpu).then_some(frame); - } - if logged.elapsed() >= Duration::from_secs(10) { - tracing::debug!(target: "metrics", skipped, "feed"); - skipped = 0; - logged = Instant::now(); - } - } -} - -fn control(connection: &Connection, encoders: &Mutex, loss: &Loss, stop: &AtomicBool) { - let mut controller = Controller::default(); - let mut scale = 1.0; - while wait(stop, congestion::PERIOD) { - let next = controller.observe(Uplink::read(connection)); - loss.decay(); - loss.report(controller.loss()); - if next < scale { - tracing::info!(scale = next, "share uplink congested"); - } - if next != scale { - scale = next; - lock(encoders).set_scale(scale); - } - } -} - -fn send( - kind: Kind, - rx: Receiver, - connection: Connection, - encoders: Arc>, - loss: Arc, - sent: Arc>, - stop: &AtomicBool, -) { - let seed = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map_or(0, |since| since.as_millis() as u32); - let mut lanes: HashMap> = HashMap::new(); - while let Some(item) = next(&rx, stop) { - lock(&sent).record(&item); - let lane = lanes.entry(item.layer).or_insert_with(|| { - let (tx, rx) = mpsc::channel(); - let bitrate = lock(&encoders).layer_bitrate(item.layer); - let (connection, loss, encoders) = (connection.clone(), loss.clone(), encoders.clone()); - let _ = std::thread::Builder::new() - .name("share-send".to_string()) - .spawn(move || send_layer(kind, rx, &connection, &encoders, &loss, bitrate, seed)); - tx - }); - let _ = lane.send(item); - } -} - -fn send_layer( - kind: Kind, - rx: Receiver, - connection: &Connection, - encoders: &Mutex, - loss: &Loss, - bitrate: u32, - seed: u32, -) { - let mut pacer = Pacer::default(); - let mut number = seed; - let mut link = Link::default(); - let mut stalled = false; - for item in rx { - let fresh = item.keyframe || item.recovery; - let gate = link.gate(connection, fresh); - match gate { - Gate::Send => stalled &= !fresh, - Gate::Pause => { - tracing::info!(?kind, "uplink congested, pausing until it drains"); - stalled = true; - } - Gate::Drop => {} - Gate::Resume => lock(encoders).keyframe(item.layer, true), - } - if stalled || gate != Gate::Send { - number = number.wrapping_add(1); - continue; - } - let info = FrameInfo { - kind, - layer: item.layer, - frame: number, - keyframe: item.keyframe, - recovery: item.recovery, - ts_ms: item.timestamp_ms, - parity: loss.parity(item.data.len() as u32, item.keyframe), - }; - number = number.wrapping_add(1); - fragments(info, &item.data, |packet| { - pacer.wait(packet.len(), bitrate); - datagram::send(connection, Bytes::copy_from_slice(packet)); - }); - } -} - -fn encode_audio( - mut samples: Consumer, - connection: Connection, - started: Instant, - meter: &Meter, - stop: &AtomicBool, -) { - let Ok(mut encoder) = Encoder::new(VOICE_SAMPLE_RATE, SHARE_AUDIO_CHANNELS, Application::Audio) - else { - warn!("share audio encoder not started"); - return; - }; - encoder.set_bitrate(SHARE_AUDIO_BITRATE as u32); - let mut pcm = vec![0.0; CHUNK_SAMPLES]; - let mut payload = [0u8; VOICE_MAX_PAYLOAD]; - let mut packet = Vec::new(); - let mut sequence = 0u32; - while !stop.load(Ordering::Relaxed) { - if samples.slots() < CHUNK_SAMPLES { - wait(stop, AUDIO_STEP); - continue; - } - for sample in pcm.iter_mut() { - *sample = samples.pop().unwrap_or(0.0); - } - meter.record(&pcm, SHARE_AUDIO_CHANNELS); - let Ok(length) = encoder.encode_float(&pcm, VOICE_FRAME_SAMPLES, &mut payload) else { - continue; - }; - packet.clear(); - Packet::ScreenAudio { - seq: sequence, - ts_ms: (started.elapsed().as_millis() as u32).saturating_sub(CHUNK_MS), - opus: &payload[..length], - } - .encode(&mut packet); - datagram::send(&connection, Bytes::copy_from_slice(&packet)); - sequence = sequence.wrapping_add(1); - } -} - struct Clock { started: Instant, offset: AtomicI64, @@ -718,8 +236,8 @@ impl Video { .values() .copied() .max() - .unwrap_or(media::convert::SHARE_WIDTH) - .clamp(MIN_SHOWN_WIDTH, media::convert::SHARE_WIDTH) + .unwrap_or(media::SHARE_WIDTH) + .clamp(MIN_SHOWN_WIDTH, media::SHARE_WIDTH) } } @@ -728,13 +246,27 @@ struct Health { loss: f32, queuing_ms: i64, packet_loss: Option, - lost: bool, - recover: bool, + need: Option, served: Option, keyframes: u32, nacks: u32, } +#[derive(Clone, Copy, PartialEq, Eq)] +enum Probe { + Idle, + Since(u32), +} + +impl Probe { + fn tick(self) -> Self { + match self { + Self::Idle => Self::Idle, + Self::Since(ticks) => Self::Since(ticks.saturating_add(1)), + } + } +} + pub struct Watching { link: Arc>>, clock: Arc, @@ -744,9 +276,9 @@ pub struct Watching { video_tx: Sender<(Instant, Bytes)>, audio_tx: Option>, meter: Meter, - received: AtomicU64, - goodput: AtomicU64, - goodputs: VecDeque, + stats_bytes: AtomicU64, + adapt_bytes: AtomicU64, + adapt_window: VecDeque, kind: Kind, since: Instant, ticked: Instant, @@ -761,7 +293,7 @@ pub struct Watching { hold: u32, losses: VecDeque, patience: u32, - probed: u32, + probe: Probe, requested: Instant, } @@ -825,9 +357,9 @@ impl Watching { video_tx, audio_tx, meter, - received: AtomicU64::new(0), - goodput: AtomicU64::new(0), - goodputs: VecDeque::new(), + stats_bytes: AtomicU64::new(0), + adapt_bytes: AtomicU64::new(0), + adapt_window: VecDeque::new(), kind, since: Instant::now(), ticked: Instant::now(), @@ -843,7 +375,7 @@ impl Watching { hold: 0, losses: VecDeque::new(), patience: CLEAN_SECONDS, - probed: u32::MAX, + probe: Probe::Idle, requested: Instant::now(), }; watching.emitted = Some(watching.wanted()); @@ -863,11 +395,11 @@ impl Watching { Packet::Voice { .. } | Packet::Nack { .. } | Packet::Ack { .. } => return, }; self.clock.observe(ts_ms); - self.received + self.stats_bytes .fetch_add((datagram.len() - RELAY_PREFIX) as u64, Ordering::Relaxed); match packet { Packet::Video { .. } => { - self.goodput + self.adapt_bytes .fetch_add(datagram.len() as u64, Ordering::Relaxed); let _ = self.video_tx.send((Instant::now(), datagram.clone())); } @@ -883,12 +415,12 @@ impl Watching { *lock(&self.link) = Some(connection); } - pub fn stats(&mut self) -> WatchStats { + pub fn stats(&mut self) -> common::stats::WatchStats { let seconds = std::mem::replace(&mut self.since, Instant::now()) .elapsed() .as_secs_f32() .max(f32::EPSILON); - let bytes = self.received.swap(0, Ordering::Relaxed); + let bytes = self.stats_bytes.swap(0, Ordering::Relaxed); let (decoded, engine, buffer_ms, latency_ms, presented, dropped, interval_ms) = { let mut video = lock(&self.video); let buffer_ms = match (video.queue.front(), video.queue.back()) { @@ -912,7 +444,7 @@ impl Watching { ) }; let health = lock(&self.health); - WatchStats { + common::stats::WatchStats { layer: health.served, engine, kbps: (bytes as f32 * 8. / 1000. / seconds) as u32, @@ -976,14 +508,16 @@ impl Watching { } pub fn tick(&mut self) -> Vec { - let (loss, queuing_ms, served, lost, packet_loss) = { + let (loss, queuing_ms, served, keyframe, packet_loss) = { let mut health = lock(&self.health); - let lost = health.lost && self.requested.elapsed() >= KEYFRAME_INTERVAL; + let keyframe = health + .need + .filter(|_| self.requested.elapsed() >= KEYFRAME_INTERVAL); ( health.loss, health.queuing_ms, health.served, - lost.then_some(health.recover), + keyframe, health.packet_loss.take(), ) }; @@ -991,7 +525,7 @@ impl Watching { if let Some(packet_loss) = packet_loss.filter(|loss| *loss > 0.0) { ticks.push(Tick::Loss((packet_loss * 1000.0).ceil() as u16)); } - if let Some(recover) = lost { + if let Some(recover) = keyframe { self.requested = Instant::now(); ticks.push(Tick::Keyframe { recover }); } @@ -999,12 +533,12 @@ impl Watching { .elapsed() .as_secs_f32() .max(f32::EPSILON); - if self.goodputs.len() >= GOODPUT_TICKS { - self.goodputs.pop_front(); + if self.adapt_window.len() >= GOODPUT_TICKS { + self.adapt_window.pop_front(); } - self.goodputs - .push_back(self.goodput.swap(0, Ordering::Relaxed) as f32 * 8. / seconds); - let goodput = self.goodputs.iter().copied().fold(0., f32::max); + self.adapt_window + .push_back(self.adapt_bytes.swap(0, Ordering::Relaxed) as f32 * 8. / seconds); + let goodput = self.adapt_window.iter().copied().fold(0., f32::max); if self.quality == WatchQuality::Auto { self.adapt(loss, queuing_ms, served, goodput); } @@ -1018,7 +552,7 @@ impl Watching { fn adapt(&mut self, loss: f32, queuing_ms: i64, served: Option, goodput: f32) { let rung = self.rung; - self.probed = self.probed.saturating_add(1); + self.probe = self.probe.tick(); if self.losses.len() >= LOSS_TICKS { self.losses.pop_front(); } @@ -1035,23 +569,25 @@ impl Watching { let fit = served.map_or(self.rung + 1, |layer| { (self.rung + 1..self.ladder.len()) .find(|&index| { - let rung = Layer { + let candidate = Layer { quality: self.ladder[index], codec: layer.codec, }; - rung.bitrate(3840, 2160) as f32 <= goodput * FIT + candidate.bitrate(REFERENCE.0, REFERENCE.1) as f32 <= goodput * FIT }) .unwrap_or(self.ladder.len() - 1) }); self.rung = fit.max(self.rung + 1).min(self.ladder.len() - 1); - if self.probed <= PROBE_SECONDS { + if let Probe::Since(ticks) = self.probe + && ticks <= PROBE_SECONDS + { self.patience = (self.patience * 2).min(MAX_PATIENCE); - self.probed = u32::MAX; } + self.probe = Probe::Idle; self.clean = 0; } else if loss < CLEAN_LOSS && queuing_ms < QUEUING_CLEAN_MS { self.clean += 1; - if self.probed == PROBE_SECONDS + 1 { + if self.probe == Probe::Since(PROBE_SECONDS + 1) { self.patience = CLEAN_SECONDS; } if self.clean >= self.patience @@ -1059,7 +595,7 @@ impl Watching { { self.rung = self.rung.saturating_sub(1); self.clean = 0; - self.probed = 0; + self.probe = Probe::Since(0); } } else { self.clean = 0; @@ -1110,40 +646,37 @@ impl Feedback { .map_or(DEFAULT_RTT, Connection::rtt) } - fn ack(&self, (layer, ts_ms): (Layer, u32)) { + fn emit(&self, packet: Packet<'_>) { let Some(connection) = lock(&self.link).clone() else { return; }; let mut out = Vec::new(); - Packet::Ack { + packet.encode(&mut out); + datagram::send(&connection, Bytes::from(out)); + } + + fn ack(&self, (layer, ts_ms): (Layer, u32)) { + self.emit(Packet::Ack { kind: self.kind, user_id: self.user_id, layer, ts_ms, - } - .encode(&mut out); - datagram::send(&connection, Bytes::from(out)); + }); } fn send(&self, nack: &Nack) { - let Some(connection) = lock(&self.link).clone() else { - return; - }; let indices: Vec = nack .indices .iter() .flat_map(|index| index.to_le_bytes()) .collect(); - let mut out = Vec::new(); - Packet::Nack { + self.emit(Packet::Nack { kind: self.kind, user_id: self.user_id, layer: nack.layer, frame: nack.frame, indices: &indices, - } - .encode(&mut out); - datagram::send(&connection, Bytes::from(out)); + }); } } @@ -1159,9 +692,8 @@ fn watch_video( let mut decoder: Option<(Codec, VideoDecoder, u32)> = None; let mut sampled = Instant::now(); let mut playout = Playout::default(); - let mut decoded: Option<(Layer, u32)> = None; let mut acked_at = Instant::now(); - let mut show = |assembled: Assembled| { + let mut show = |decoded: &mut Option<(Layer, u32)>, assembled: Assembled| { { let mut health = lock(health); health.served = Some(assembled.layer); @@ -1169,25 +701,22 @@ fn watch_video( } decode_video(&mut decoder, &assembled, clock, &mut playout, video); lock(health).queuing_ms = playout.queuing(); - (assembled.layer, assembled.timestamp_ms) + *decoded = Some((assembled.layer, assembled.timestamp_ms)); }; + let mut decoded = None; while !stop.load(Ordering::Relaxed) { match rx.recv_timeout(NACK_TICK) { Ok((arrived, bytes)) => { if arrived.elapsed() > CATCH_UP { while rx.try_recv().is_ok() {} reassembler = Reassembler::new(); - tracing::warn!("share watch fell behind, skipping to the next keyframe"); + warn!("share watch fell behind, skipping to the next keyframe"); continue; } - if let Some((_, packet)) = split(&bytes) - && let Some(last) = reassembler - .push(&packet, Instant::now()) - .into_iter() - .map(&mut show) - .last() - { - decoded = Some(last); + if let Some((_, packet)) = split(&bytes) { + for assembled in reassembler.push(&packet, Instant::now()) { + show(&mut decoded, assembled); + } } } Err(RecvTimeoutError::Timeout) => {} @@ -1196,23 +725,22 @@ fn watch_video( let now = Instant::now(); let rtt = feedback.rtt(); let wait = (rtt * 2 + NACK_SLACK).clamp(NACK_SLACK, NACK_GIVE_UP); - if let Some(last) = reassembler - .expire(now, wait) - .into_iter() - .map(&mut show) - .last() - { - decoded = Some(last); + for assembled in reassembler.expire(now, wait) { + show(&mut decoded, assembled); } let nacks = reassembler.nacks(now, rtt); - lock(health).nacks += nacks.len() as u32; for nack in &nacks { feedback.send(nack); } { let mut health = lock(health); - health.lost = reassembler.needs_keyframe(); - health.recover = reassembler.can_recover(); + health.nacks += nacks.len() as u32; + health.need = reassembler.need(); + if sampled.elapsed() >= SAMPLE { + health.loss = reassembler.loss_ratio(); + health.packet_loss = Some(reassembler.packet_loss()); + sampled = Instant::now(); + } } if acked_at.elapsed() >= ACK_INTERVAL && let Some(ack) = decoded.take() @@ -1220,12 +748,6 @@ fn watch_video( feedback.ack(ack); acked_at = Instant::now(); } - if sampled.elapsed() >= SAMPLE { - let mut health = lock(health); - health.loss = reassembler.loss_ratio(); - health.packet_loss = Some(reassembler.packet_loss()); - sampled = Instant::now(); - } } } @@ -1356,90 +878,4 @@ mod tests { } assert_eq!(delay, 60 + DELAY_MARGIN_MS); } - - #[test] - fn every_codec_round_trips() { - let capabilities = encode::capabilities(); - let (width, height) = (1280, 720); - for codec in capabilities.encode.clone() { - let layer = Layer { - quality: Quality { - resolution: Resolution::P720, - fps: Fps::F30, - }, - codec, - }; - let (tx, rx) = mpsc::channel(); - let mut encoders = Encoders::new(width, height, tx); - encoders.set_layers(&[layer]); - for index in 0..10u32 { - let bgra = (0..width * height * 4) - .map(|byte| (byte / 4 % width + index * 8) as u8) - .collect(); - encoders.push(Arc::new(Frame { - width, - height, - stride: width * 4, - timestamp_ms: index * 34, - bgra, - gpu: None, - })); - std::thread::sleep(Duration::from_millis(40)); - } - std::thread::sleep(Duration::from_millis(300)); - drop(encoders); - - let encoded: Vec = rx.try_iter().collect(); - let mut decoders = vec![VideoDecoder::for_codec(codec).expect("decoder")]; - decoders.push(crate::media::decode::software(codec).expect("software decoder")); - let pixels: Vec> = decoders - .into_iter() - .map(|mut decoder| { - let mut reassembler = Reassembler::new(); - let mut pictures = Vec::new(); - for (number, encoded) in encoded.iter().enumerate() { - let info = FrameInfo { - kind: Kind::Screen, - layer: encoded.layer, - frame: number as u32, - keyframe: encoded.keyframe, - recovery: false, - ts_ms: encoded.timestamp_ms, - parity: 1, - }; - fragments(info, &encoded.data, |packet| { - let Some(packet) = Packet::decode(packet) else { - panic!("fragment"); - }; - for assembled in reassembler.push(&packet, Instant::now()) { - pictures.extend( - decoder.decode(&assembled.data, assembled.timestamp_ms), - ); - } - }); - } - assert_eq!(pictures.len(), 10, "{codec:?} {:?}", decoder.engine()); - let last = pictures.pop().expect("picture"); - assert_eq!( - last.size(), - (width, height), - "{codec:?} {:?}", - decoder.engine() - ); - let frame = last.into_frame(media::convert::SHARE_WIDTH).expect("frame"); - frame.bgra.to_vec() - }) - .collect(); - let difference = pixels[0] - .iter() - .zip(pixels.last().expect("pixels")) - .map(|(a, b)| u64::from(a.abs_diff(*b))) - .sum::() - / pixels[0].len() as u64; - assert!( - difference < 4, - "{codec:?} hardware vs software pixels differ by {difference}" - ); - } - } } diff --git a/crates/client/src/tray.rs b/crates/client/src/tray.rs index 3809ace..77dc186 100644 --- a/crates/client/src/tray.rs +++ b/crates/client/src/tray.rs @@ -124,31 +124,17 @@ mod linux { state: TrayState::default(), }; - let _ = std::thread::Builder::new() - .name("tray".to_string()) - .spawn(move || { - let runtime = match tokio::runtime::Builder::new_current_thread() - .enable_all() - .build() - { - Ok(runtime) => runtime, - Err(error) => { - warn!("tray runtime: {error}"); - return; + crate::spawn_runtime("tray", move || async move { + match tray.assume_sni_available(true).spawn().await { + Ok(handle) => { + while let Some(state) = state_receiver.recv().await { + handle.update(|tray| tray.state = state).await; } - }; - runtime.block_on(async move { - match tray.assume_sni_available(true).spawn().await { - Ok(handle) => { - while let Some(state) = state_receiver.recv().await { - handle.update(|tray| tray.state = state).await; - } - std::future::pending::<()>().await - } - Err(error) => warn!("tray: {error}"), - } - }); - }); + std::future::pending::<()>().await + } + Err(error) => warn!("tray: {error}"), + } + }); ( receiver, diff --git a/crates/client/src/update.rs b/crates/client/src/update.rs index 9074c24..65a5dcb 100644 --- a/crates/client/src/update.rs +++ b/crates/client/src/update.rs @@ -12,7 +12,6 @@ use tokio::sync::watch; use tracing::{info, warn}; pub const RESTART: &str = "--restart"; -pub const TARGET: &str = env!("YUMUSH_TARGET"); const MARK: &str = concat!("yumush-target:", env!("YUMUSH_TARGET"), ";"); const CHUNK: usize = 256 << 10; @@ -63,11 +62,8 @@ static PHASE: LazyLock> = LazyLock::new(|| watch::channel(P static SERVER: Mutex> = Mutex::new(None); static TOKEN: Mutex> = Mutex::new(None); static INSTALL: LazyLock = LazyLock::new(|| { - let path = crate::config_dir().map(|dir| dir.join("install")); - if let Some(saved) = path - .as_ref() - .and_then(|path| std::fs::read(path).ok()) - .and_then(|bytes| Install::try_from(bytes).ok()) + if let Some(saved) = + crate::read_config_bytes("install").and_then(|bytes| Install::try_from(bytes).ok()) { return saved; } @@ -79,10 +75,7 @@ static INSTALL: LazyLock = LazyLock::new(|| { let mut fresh = [0u8; 16]; fresh[..8].copy_from_slice(&random(1).to_le_bytes()); fresh[8..].copy_from_slice(&random(2).to_le_bytes()); - if let Some(path) = path { - let _ = path.parent().map(std::fs::create_dir_all); - let _ = std::fs::write(path, fresh); - } + crate::write_config("install", fresh); fresh }); static BUILD: LazyLock> = LazyLock::new(|| { @@ -133,7 +126,7 @@ fn targets() -> Vec { let os = std::env::consts::OS; let arch = std::env::consts::ARCH; if arch != "x86_64" { - return vec![TARGET.to_string()]; + return vec![crate::TARGET.to_string()]; } let mut targets = Vec::new(); if v3() { @@ -193,10 +186,11 @@ pub(crate) async fn check(server: crate::Server, outdated: bool) { match status { Status::Offer(mut offer) => { offer.required |= outdated; - if phase() != Phase::Failed(offer) { + let failed = matches!(phase(), Phase::Failed(old) if old.file == offer.file); + if !failed { set(Phase::Available(offer)); } - if offer.required { + if offer.required && !failed { install(); } } @@ -208,21 +202,10 @@ pub fn recheck() { let Some(server) = SERVER.lock().unwrap().clone() else { return; }; - std::thread::spawn(move || { - if let Ok(runtime) = tokio::runtime::Builder::new_current_thread() - .enable_all() - .build() - { - runtime.block_on(check(server, false)); - } - }); + crate::spawn_runtime("update", move || check(server, false)); } pub fn install() { - let offer = match phase() { - Phase::Available(offer) | Phase::Failed(offer) => offer, - _ => return, - }; let Some(server) = SERVER.lock().unwrap().clone() else { return; }; @@ -232,7 +215,18 @@ pub fn install() { let Some(me) = me() else { return; }; - set(Phase::Downloading { offer, done: 0 }); + let mut claimed = None; + PHASE.send_if_modified(|phase| { + let (Phase::Available(offer) | Phase::Failed(offer)) = *phase else { + return false; + }; + claimed = Some(offer); + *phase = Phase::Downloading { offer, done: 0 }; + true + }); + let Some(offer) = claimed else { + return; + }; std::thread::spawn(move || { let Ok(runtime) = tokio::runtime::Builder::new_current_thread() .enable_all() diff --git a/crates/client/src/voice/audio.rs b/crates/client/src/voice/audio.rs index 04672f6..4e3a344 100644 --- a/crates/client/src/voice/audio.rs +++ b/crates/client/src/voice/audio.rs @@ -1,17 +1,10 @@ -use std::{ - error::Error, - sync::{ - Arc, - atomic::{AtomicBool, Ordering}, - }, - thread::JoinHandle, - time::Duration, -}; +use std::{sync::atomic::AtomicBool, time::Duration}; use common::constant::{VOICE_FRAME_SAMPLES, VOICE_SAMPLE_RATE}; -use tracing::{info, warn}; +use tracing::info; use super::{Capture, PLAYBACK_CHANNELS, Playback}; +use crate::worker::{Worker, wait}; #[cfg(target_os = "macos")] #[path = "audio/coreaudio.rs"] @@ -22,10 +15,11 @@ mod backend; #[cfg(target_os = "windows")] #[path = "audio/wasapi.rs"] mod backend; +#[cfg(target_os = "linux")] +pub mod pw; +#[cfg(target_os = "windows")] +pub(crate) use backend::{wave_format, with_com}; -const RETRY_AFTER_ERROR: Duration = Duration::from_secs(1); -const RETRY_AFTER_CHANGE: Duration = Duration::from_millis(100); -const STOP_CHECK: Duration = Duration::from_millis(100); const BYTES_PER_FRAME: usize = size_of::<[f32; 2]>(); const REPORT_FRAMES: usize = VOICE_SAMPLE_RATE as usize / VOICE_FRAME_SAMPLES; @@ -47,10 +41,13 @@ pub struct Choice { pub output: Option, } -pub enum Audio { - Silent, - Tone(Worker), - Device(backend::Backend), +#[derive(Default)] +pub struct Audio(Vec); + +impl Audio { + pub fn is_silent(&self) -> bool { + self.0.is_empty() + } } enum Mode { @@ -69,11 +66,11 @@ fn mode() -> Mode { pub fn start(capture: Option, playback: Playback, choice: Choice) -> Audio { match mode() { - Mode::Off => Audio::Silent, - Mode::Tone => Audio::Tone(Worker::spawn("voice-tone", move |stop| { + Mode::Off => Audio::default(), + Mode::Tone => Audio(vec![Worker::spawn("voice-tone", move |stop| { tone(capture.as_ref(), &playback, stop) - })), - Mode::Device => Audio::Device(backend::start(capture, playback, choice)), + })]), + Mode::Device => Audio(backend::start(capture, playback, choice)), } } @@ -153,77 +150,6 @@ pub fn play(playback: &Playback, count: usize, mut write: impl FnMut(usize, (f32 } } -pub struct Worker { - stop: Arc, - thread: Option>, -} - -impl Worker { - pub fn spawn(name: &str, body: impl FnOnce(&AtomicBool) + Send + 'static) -> Self { - let stop = Arc::new(AtomicBool::new(false)); - let thread = { - let stop = stop.clone(); - std::thread::Builder::new() - .name(name.to_string()) - .spawn(move || body(&stop)) - .inspect_err(|error| warn!("audio thread not started: {error}")) - .ok() - }; - - Self { stop, thread } - } -} - -impl Drop for Worker { - fn drop(&mut self) { - self.stop.store(true, Ordering::Relaxed); - if let Some(thread) = self.thread.take() { - let _ = thread.join(); - } - } -} - -pub fn supervise( - name: &str, - stop: &AtomicBool, - mut attempt: impl FnMut() -> Result<(), Box>, -) { - let mut last: Option = None; - while !stop.load(Ordering::Relaxed) { - let pause = match attempt() { - Ok(()) => { - last = None; - RETRY_AFTER_CHANGE - } - Err(error) => { - let message = error.to_string(); - if last.as_deref() == Some(message.as_str()) { - tracing::debug!("{name}: {message}, retrying"); - } else { - warn!("{name}: {message}, retrying"); - last = Some(message); - } - RETRY_AFTER_ERROR - } - }; - wait(stop, pause); - } -} - -pub fn wait(stop: &AtomicBool, duration: Duration) -> bool { - let mut waited = Duration::ZERO; - while waited < duration { - if stop.load(Ordering::Relaxed) { - return false; - } - let step = STOP_CHECK.min(duration - waited); - std::thread::sleep(step); - waited += step; - } - - !stop.load(Ordering::Relaxed) -} - fn tone(capture: Option<&Capture>, playback: &Playback, stop: &AtomicBool) { let step = 440.0 * std::f32::consts::TAU / VOICE_SAMPLE_RATE as f32; let mut phase = 0.0f32; diff --git a/crates/client/src/voice/audio/coreaudio.rs b/crates/client/src/voice/audio/coreaudio.rs index 4c52e6c..20d36b2 100644 --- a/crates/client/src/voice/audio/coreaudio.rs +++ b/crates/client/src/voice/audio/coreaudio.rs @@ -12,15 +12,16 @@ use coreaudio::audio_unit::render_callback::{self, data}; use coreaudio::audio_unit::{AudioUnit, Element, IOType, SampleFormat, Scope, StreamFormat}; use tracing::warn; -use super::{Choice, Device, Devices, Downmix, Worker, play, record, supervise, wait}; -use crate::voice::{Capture, Playback}; +use super::{Choice, Device, Devices, Downmix, play, record}; +use crate::{ + voice::{Capture, Playback}, + worker::{Worker, supervise, wait}, +}; type Args = render_callback::Args>; const DEVICE_CHECK: Duration = Duration::from_millis(500); -pub type Backend = Worker; - pub fn devices() -> Devices { list_devices().unwrap_or_default() } @@ -44,12 +45,12 @@ fn list(scope: Scope) -> Result, Error> { .collect()) } -pub fn start(capture: Option, playback: Playback, choice: Choice) -> Backend { - Worker::spawn("voice audio", move |stop| { +pub fn start(capture: Option, playback: Playback, choice: Choice) -> Vec { + vec![Worker::spawn("voice audio", move |stop| { supervise("voice audio", stop, || { attempt(capture.as_ref(), &playback, &choice, stop) }) - }) + })] } fn input_device(choice: &Choice) -> Option { @@ -60,13 +61,11 @@ fn input_device(choice: &Choice) -> Option { .or_else(|| get_default_device_id(true)) } -fn output_device(choice: &Choice) -> (Option, Option) { - let chosen = choice +fn output_device(choice: &Choice) -> Option { + choice .output .as_deref() - .and_then(|name| get_device_id_from_name(name, false)); - - (chosen, chosen.and_then(|_| get_default_device_id(false))) + .and_then(|name| get_device_id_from_name(name, false)) } fn attempt( @@ -76,38 +75,16 @@ fn attempt( stop: &AtomicBool, ) -> Result<(), Box> { let output_id = output_device(choice); - let _output = playback_unit(playback.clone(), output_id.0)?; + let _output = playback_unit(playback.clone(), output_id)?; let device = capture.and_then(|_| input_device(choice)); - let input = capture.zip(device).and_then(|(capture, device)| { - capture_unit(device, capture.clone()) - .inspect_err(|error| warn!("voice capture unavailable: {error}")) - .ok() - }); - watch( - stop, - choice, - capture.is_some(), - input.as_ref(), - device, - output_id, - )?; - Ok(()) -} - -fn watch( - stop: &AtomicBool, - choice: &Choice, - capturing: bool, - input: Option<&(AudioUnit, f64)>, - device: Option, - output: (Option, Option), -) -> Result<(), Error> { + let mut input = open_input(capture, device); while wait(stop, DEVICE_CHECK) { - let input_moved = capturing && input_device(choice) != device; - if input_moved || output_device(choice) != output { + let input_moved = capture.is_some() && input_device(choice) != device; + if input_moved || output_device(choice) != output_id { break; } - let Some((unit, rate)) = input else { + let Some((unit, rate)) = &input else { + input = open_input(capture, device); continue; }; if unit @@ -121,6 +98,13 @@ fn watch( Ok(()) } +fn open_input(capture: Option<&Capture>, device: Option) -> Option<(AudioUnit, f64)> { + let (capture, device) = capture.zip(device)?; + capture_unit(device, capture.clone()) + .inspect_err(|error| warn!("voice capture unavailable: {error}")) + .ok() +} + fn format(sample_rate: f64, channels: u32) -> StreamFormat { StreamFormat { sample_rate, diff --git a/crates/client/src/voice/audio/pipewire.rs b/crates/client/src/voice/audio/pipewire.rs index cd517d9..c9d53ae 100644 --- a/crates/client/src/voice/audio/pipewire.rs +++ b/crates/client/src/voice/audio/pipewire.rs @@ -1,5 +1,5 @@ use std::{ - cell::{Cell, RefCell}, + cell::Cell, error::Error, rc::Rc, sync::atomic::{AtomicBool, Ordering}, @@ -11,100 +11,38 @@ use pw::{ loop_::Timeout, properties::properties, spa, - stream::{StreamBox, StreamListener, StreamState}, - types::ObjectType, + stream::{StreamBox, StreamListener}, }; use spa::pod::Pod; -use super::{ - BYTES_PER_FRAME, Choice, Device, Devices, STOP_CHECK, Worker, frame_bytes, play, record, - supervise, +use super::{BYTES_PER_FRAME, Choice, Device, Devices, frame_bytes, play, pw as shared, record}; +use crate::{ + voice::{Capture, Playback}, + worker::{STOP_CHECK, Worker, supervise}, }; -use crate::voice::{Capture, Playback}; - -pub type Backend = Worker; pub fn devices() -> Devices { - collect_devices().unwrap_or_default() -} - -fn collect_devices() -> Result> { - pw::init(); - let mainloop = pw::main_loop::MainLoopRc::new(None)?; - let context = pw::context::ContextRc::new(&mainloop, None)?; - let core = context.connect_rc(None)?; - let registry = core.get_registry_rc()?; - - let devices = Rc::new(RefCell::new(Devices::default())); - let failed = Rc::new(Cell::new(false)); - - let pending = core.sync(0)?; - - let _core_listener = core - .add_listener_local() - .done({ - let mainloop = mainloop.clone(); - move |id, seq| { - if id == pw::core::PW_ID_CORE && seq == pending { - mainloop.quit(); - } - } - }) - .error({ - let failed = failed.clone(); - let mainloop = mainloop.clone(); - move |_, _, _, _| { - failed.set(true); - mainloop.quit(); - } - }) - .register(); - - let _registry_listener = registry - .add_listener_local() - .global({ - let devices = devices.clone(); - move |global| { - if !matches!(global.type_, ObjectType::Node) { - return; - } - let Some(props) = global.props else { - return; - }; - let Some(node) = props.get(*pw::keys::NODE_NAME) else { - return; - }; - let device = Device { - id: node.to_string(), - name: props - .get(*pw::keys::NODE_DESCRIPTION) - .or_else(|| props.get(*pw::keys::NODE_NICK)) - .unwrap_or(node) - .to_string(), - }; - match props.get(*pw::keys::MEDIA_CLASS) { - Some("Audio/Source") => devices.borrow_mut().inputs.push(device), - Some("Audio/Sink") => devices.borrow_mut().outputs.push(device), - _ => {} - } - } - }) - .register(); - - mainloop.run(); - - if failed.get() { - return Err("pipewire devices".into()); + let mut devices = Devices::default(); + for node in shared::nodes().unwrap_or_default() { + let device = Device { + id: node.name, + name: node.description, + }; + match node.class.as_str() { + "Audio/Source" => devices.inputs.push(device), + "Audio/Sink" => devices.outputs.push(device), + _ => {} + } } - Ok(devices.take()) + devices } -pub fn start(capture: Option, playback: Playback, choice: Choice) -> Backend { - Worker::spawn("voice-audio", move |stop| { +pub fn start(capture: Option, playback: Playback, choice: Choice) -> Vec { + vec![Worker::spawn("voice-audio", move |stop| { supervise("voice audio", stop, || { run(capture.as_ref(), &playback, &choice, stop) }) - }) + })] } fn stream_properties(category: &str, target: Option<&str>) -> pw::properties::PropertiesBox { @@ -122,44 +60,13 @@ fn stream_properties(category: &str, target: Option<&str>) -> pw::properties::Pr props } -fn format_values(channels: u32) -> Option> { - let mut info = spa::param::audio::AudioInfoRaw::new(); - info.set_format(spa::param::audio::AudioFormat::F32LE); - info.set_rate(VOICE_SAMPLE_RATE); - let mut position = [0; spa::sys::SPA_AUDIO_MAX_CHANNELS as usize]; - if channels == 1 { - position[0] = spa::sys::SPA_AUDIO_CHANNEL_MONO; - } else { - position[0] = spa::sys::SPA_AUDIO_CHANNEL_FL; - position[1] = spa::sys::SPA_AUDIO_CHANNEL_FR; - } - info.set_channels(channels); - info.set_position(position); - - let object = spa::pod::Object { - type_: spa::utils::SpaTypes::ObjectParamFormat.as_raw(), - id: spa::param::ParamType::EnumFormat.as_raw(), - properties: info.into(), - }; - let (cursor, _) = spa::pod::serialize::PodSerializer::serialize( - std::io::Cursor::new(Vec::new()), - &spa::pod::Value::Object(object), - ) - .ok()?; - - Some(cursor.into_inner()) -} - fn run( capture: Option<&Capture>, playback: &Playback, choice: &Choice, stop: &AtomicBool, ) -> Result<(), Box> { - pw::init(); - let mainloop = pw::main_loop::MainLoopRc::new(None)?; - let context = pw::context::ContextRc::new(&mainloop, None)?; - let core = context.connect_rc(None)?; + let (mainloop, _context, core) = shared::connect()?; let failed = Rc::new(Cell::new(false)); let error_failed = failed.clone(); @@ -171,8 +78,8 @@ fn run( }) .register(); - let capture_values = format_values(1).ok_or("pipewire format")?; - let playback_values = format_values(2).ok_or("pipewire format")?; + let capture_values = shared::format(1).ok_or("pipewire format")?; + let playback_values = shared::format(2).ok_or("pipewire format")?; let flags = pw::stream::StreamFlags::AUTOCONNECT | pw::stream::StreamFlags::MAP_BUFFERS | pw::stream::StreamFlags::RT_PROCESS; @@ -182,7 +89,7 @@ fn run( .map(|capture| capture_stream(&core, capture, choice, &failed, &capture_values, flags)) .transpose()?; - let playback_stream = pw::stream::StreamBox::new( + let playback_stream = StreamBox::new( &core, "yumush-playback", stream_properties("Playback", choice.output.as_deref()), @@ -190,7 +97,7 @@ fn run( let playback = playback.clone(); let _playback_listener = playback_stream .add_local_listener_with_user_data(()) - .state_changed(state_watch(&failed)) + .state_changed(shared::state_watch(&failed)) .process(move |stream, _| { let Some(mut buffer) = stream.dequeue_buffer() else { return; @@ -251,7 +158,7 @@ fn capture_stream<'c>( )?; let listener = stream .add_local_listener_with_user_data(()) - .state_changed(state_watch(failed)) + .state_changed(shared::state_watch(failed)) .process(move |stream, _| { let Some(mut buffer) = stream.dequeue_buffer() else { return; @@ -277,15 +184,3 @@ fn capture_stream<'c>( stream.connect(spa::utils::Direction::Input, None, flags, &mut params)?; Ok((listener, stream)) } - -fn state_watch( - failed: &Rc>, -) -> impl FnMut(&pw::stream::Stream, &mut (), StreamState, StreamState) + 'static { - let failed = failed.clone(); - move |_, _, _, new| { - if let StreamState::Error(message) = new { - tracing::warn!("pipewire stream: {message}"); - failed.set(true); - } - } -} diff --git a/crates/client/src/voice/audio/pw.rs b/crates/client/src/voice/audio/pw.rs new file mode 100644 index 0000000..01e9080 --- /dev/null +++ b/crates/client/src/voice/audio/pw.rs @@ -0,0 +1,154 @@ +use std::{ + cell::{Cell, RefCell}, + error::Error, + rc::Rc, +}; + +use common::constant::VOICE_SAMPLE_RATE; +use pipewire as pw; +use pw::{ + context::ContextRc, + core::CoreRc, + main_loop::MainLoopRc, + registry::GlobalObject, + spa, + stream::{Stream, StreamState}, + types::ObjectType, +}; +use spa::utils::dict::DictRef; +use tracing::warn; + +#[derive(Default)] +pub struct Node { + pub id: u32, + pub name: String, + pub description: String, + pub class: String, + pub role: String, + pub process: String, + pub app: String, + pub media: String, +} + +pub fn connect() -> Result<(MainLoopRc, ContextRc, CoreRc), Box> { + pw::init(); + let mainloop = MainLoopRc::new(None)?; + let context = ContextRc::new(&mainloop, None)?; + let core = context.connect_rc(None)?; + Ok((mainloop, context, core)) +} + +pub fn nodes() -> Result, Box> { + let (mainloop, _context, core) = connect()?; + let registry = core.get_registry_rc()?; + + let found = Rc::new(RefCell::new(Vec::new())); + let failed = Rc::new(Cell::new(false)); + let pending = core.sync(0)?; + + let _core_listener = core + .add_listener_local() + .done({ + let mainloop = mainloop.clone(); + move |id, seq| { + if id == pw::core::PW_ID_CORE && seq == pending { + mainloop.quit(); + } + } + }) + .error({ + let failed = failed.clone(); + let mainloop = mainloop.clone(); + move |_, _, _, message| { + warn!("pipewire: {message}"); + failed.set(true); + mainloop.quit(); + } + }) + .register(); + + let _registry_listener = registry + .add_listener_local() + .global({ + let found = found.clone(); + move |global| { + if let Some(node) = node_of(global) { + found.borrow_mut().push(node); + } + } + }) + .register(); + + mainloop.run(); + + if failed.get() { + return Err("pipewire nodes".into()); + } + Ok(found.take()) +} + +pub fn node_of(global: &GlobalObject<&DictRef>) -> Option { + if !matches!(global.type_, ObjectType::Node) { + return None; + } + let props = global.props?; + let name = props.get(*pw::keys::NODE_NAME)?; + let description = props + .get(*pw::keys::NODE_DESCRIPTION) + .or_else(|| props.get(*pw::keys::NODE_NICK)) + .unwrap_or(name); + let text = |key: &str| props.get(key).unwrap_or_default().to_string(); + Some(Node { + id: global.id, + name: name.to_string(), + description: description.to_string(), + class: text(*pw::keys::MEDIA_CLASS), + role: text(*pw::keys::MEDIA_ROLE), + process: text(*pw::keys::APP_PROCESS_ID), + app: props + .get(*pw::keys::APP_NAME) + .unwrap_or(description) + .to_string(), + media: text(*pw::keys::MEDIA_NAME), + }) +} + +pub fn format(channels: u32) -> Option> { + let mut info = spa::param::audio::AudioInfoRaw::new(); + info.set_format(spa::param::audio::AudioFormat::F32LE); + info.set_rate(VOICE_SAMPLE_RATE); + let mut position = [0; spa::sys::SPA_AUDIO_MAX_CHANNELS as usize]; + if channels == 1 { + position[0] = spa::sys::SPA_AUDIO_CHANNEL_MONO; + } else { + position[0] = spa::sys::SPA_AUDIO_CHANNEL_FL; + position[1] = spa::sys::SPA_AUDIO_CHANNEL_FR; + } + info.set_channels(channels); + info.set_position(position); + + let object = spa::pod::Object { + type_: spa::utils::SpaTypes::ObjectParamFormat.as_raw(), + id: spa::param::ParamType::EnumFormat.as_raw(), + properties: info.into(), + }; + let (cursor, _) = spa::pod::serialize::PodSerializer::serialize( + std::io::Cursor::new(Vec::new()), + &spa::pod::Value::Object(object), + ) + .ok()?; + + Some(cursor.into_inner()) +} + +pub fn state_watch( + failed: &Rc>, +) -> impl FnMut(&Stream, &mut (), StreamState, StreamState) + 'static { + let failed = failed.clone(); + move |_, _, _, new| { + if let StreamState::Error(message) = new { + warn!("pipewire stream: {message}"); + failed.set(true); + } + } +} diff --git a/crates/client/src/voice/audio/wasapi.rs b/crates/client/src/voice/audio/wasapi.rs index 851b75e..f8ee117 100644 --- a/crates/client/src/voice/audio/wasapi.rs +++ b/crates/client/src/voice/audio/wasapi.rs @@ -13,15 +13,15 @@ use wasapi::{ }; use super::{ - BYTES_PER_FRAME, Choice, Device, Devices, Downmix, STOP_CHECK, Worker, frame_bytes, play, - record, stereo_frame, supervise, + BYTES_PER_FRAME, Choice, Device, Devices, Downmix, frame_bytes, play, record, stereo_frame, +}; +use crate::{ + voice::{Capture, Playback}, + worker::{STOP_CHECK, Worker, supervise}, }; -use crate::voice::{Capture, Playback}; const CHECK_DEFAULT_EVERY: Duration = Duration::from_secs(1); -pub type Backend = Vec; - struct Target<'a> { enumerator: DeviceEnumerator, direction: Direction, @@ -67,7 +67,7 @@ fn list( Ok(devices) } -pub fn start(capture: Option, playback: Playback, choice: Choice) -> Backend { +pub fn start(capture: Option, playback: Playback, choice: Choice) -> Vec { let input = choice.input; let output = choice.output; let mut workers = vec![worker("voice render", move |stop| { @@ -90,7 +90,7 @@ fn worker( }) } -fn with_com(body: impl FnOnce() -> T) -> T { +pub(crate) fn with_com(body: impl FnOnce() -> T) -> T { if let Err(error) = initialize_mta().ok() { warn!("COM not initialized: {error}"); return T::default(); @@ -100,7 +100,7 @@ fn with_com(body: impl FnOnce() -> T) -> T { value } -fn wave_format() -> WaveFormat { +pub(crate) fn wave_format() -> WaveFormat { WaveFormat::new( 32, 32, diff --git a/crates/client/src/voice/engine.rs b/crates/client/src/voice/engine.rs index 8c724b1..16e9320 100644 --- a/crates/client/src/voice/engine.rs +++ b/crates/client/src/voice/engine.rs @@ -26,6 +26,7 @@ const DRIFT_MARGIN: usize = 2; const QUIET: f32 = 0.01; const SPEAKING_WINDOW: Duration = Duration::from_millis(300); const RESTART_AFTER: Duration = Duration::from_secs(1); +const RESTART_FRAMES: u32 = 50; const MAX_DECODE_SAMPLES: usize = VOICE_SAMPLE_RATE as usize * 120 / 1000; const HANGOVER_FRAMES: u32 = 15; const FADE_SAMPLES: usize = VOICE_SAMPLE_RATE as usize * 5 / 1000; @@ -43,6 +44,11 @@ fn soft_clip(sample: f32) -> f32 { sample.signum() * (KNEE + (1.0 - KNEE) * over.tanh()) } +fn behind(next: u32, sequence: u32) -> u32 { + let distance = next.wrapping_sub(sequence); + if distance < u32::MAX / 2 { distance } else { 0 } +} + fn bitrate(profile: Profile) -> u32 { match profile { Profile::Voice => VOICE_BITRATE as u32, @@ -267,7 +273,7 @@ impl Engine { continue; }; - let mut packet = Vec::with_capacity(length + 5); + let mut packet = Vec::with_capacity(length + VOICE_HEADER); Packet::Voice { seq: self.sequence, opus: &payload[..length], @@ -281,27 +287,29 @@ impl Engine { packets } - pub fn receive(&mut self, from: &[u8; RELAY_PREFIX], sequence: u32, payload: &[u8]) { - let user_id = Id::from_be_bytes(*from); + pub fn receive(&mut self, from: Id, sequence: u32, payload: &[u8]) { let now = Instant::now(); self.received_bytes += RELAY_PREFIX + VOICE_HEADER + payload.len(); + let restart = self.speakers.get(&from).is_some_and(|speaker| { + now.duration_since(speaker.last_heard) > RESTART_AFTER + || behind(speaker.next, sequence) > RESTART_FRAMES + }); + if restart { + self.speakers.remove(&from); + } let speaker = self .speakers - .entry(user_id) + .entry(from) .or_insert_with(|| Speaker::new(sequence, now)); - if now.duration_since(speaker.last_heard) > RESTART_AFTER { - *speaker = Speaker::new(sequence, now); - } speaker.last_heard = now; - if payload.is_empty() { - return; - } - if sequence < speaker.next { + if payload.is_empty() || behind(speaker.next, sequence) > 0 { return; } if sequence.wrapping_sub(speaker.highest) < u32::MAX / 2 { - self.expected += sequence.wrapping_sub(speaker.highest); + self.expected = self + .expected + .saturating_add(sequence.wrapping_sub(speaker.highest)); speaker.highest = sequence; } self.arrived += 1; @@ -323,6 +331,9 @@ impl Engine { } pub fn playback(&mut self, out: &mut [f32]) { + let now = Instant::now(); + self.speakers + .retain(|_, speaker| now.duration_since(speaker.last_heard) <= RESTART_AFTER); out.fill(0.0); for (user_id, speaker) in &mut self.speakers { if speaker.started { @@ -456,7 +467,7 @@ mod tests { fn voice_round_trip() { let mut sender = Engine::new(); let mut receiver = Engine::new(); - let user_id = [7u8; RELAY_PREFIX]; + let user_id: Id = 7; let frames = 10; let tone: Vec = (0..VOICE_FRAME_SAMPLES * frames) @@ -467,7 +478,7 @@ mod tests { let Some(Packet::Voice { seq, opus }) = Packet::decode(&packet) else { panic!("not voice"); }; - receiver.receive(&user_id, seq, opus); + receiver.receive(user_id, seq, opus); } let mut out = vec![0.0; VOICE_FRAME_SAMPLES * frames]; diff --git a/crates/client/src/voice/mod.rs b/crates/client/src/voice/mod.rs index 63d7fea..72a9baa 100644 --- a/crates/client/src/voice/mod.rs +++ b/crates/client/src/voice/mod.rs @@ -9,7 +9,7 @@ use std::{ use bytes::Bytes; use common::{ constant::{VOICE_FRAME_SAMPLES, VOICE_SAMPLE_RATE}, - datagram::{self, Packet, RELAY_PREFIX}, + datagram::{self, Packet}, model::Id, }; use quinn::Connection; @@ -17,17 +17,18 @@ use rtrb::{Consumer, Producer, RingBuffer}; pub mod audio; pub mod engine; +pub mod sound; -use crate::settings::VoiceSettings; -use audio::{Audio, Choice, Worker}; -use engine::{Engine, SILENT_DB}; +use crate::{media::decode::lock, settings::VoiceSettings, worker::Worker}; +use audio::{Audio, Choice}; +use engine::Engine; +pub use sound::Sound; const RING_SAMPLES: usize = VOICE_SAMPLE_RATE as usize / 2; const PLAYBACK_RING: usize = RING_SAMPLES * PLAYBACK_CHANNELS; const PLAYBACK_AHEAD: usize = VOICE_FRAME_SAMPLES * 2 * PLAYBACK_CHANNELS; const TICK: Duration = Duration::from_millis(5); -const LOOPBACK: [u8; RELAY_PREFIX] = [0; RELAY_PREFIX]; -const CHIME: [(f32, f32); 2] = [(660.0, 0.18), (880.0, 0.32)]; +const LOOPBACK: Id = 0; pub const PLAYBACK_CHANNELS: usize = 2; @@ -89,112 +90,8 @@ pub fn start(connection: Option, settings: &VoiceSettings) -> Voice voice } -pub fn play_chime(settings: &VoiceSettings) { - let rate = VOICE_SAMPLE_RATE as f32; - let mut samples = Vec::new(); - for (frequency, seconds) in CHIME { - let length = (rate * seconds) as usize; - samples.extend((0..length).map(|index| { - let time = index as f32 / rate; - let fade = (1.0 - index as f32 / length as f32).powi(2); - (std::f32::consts::TAU * frequency * time).sin() * fade - })); - } - play(samples, 0.3, settings); -} - -pub fn play_yumush(settings: &VoiceSettings) { - play(plops(&YUMUSH, YUMUSH_SECONDS), 0.35, settings); -} - -pub fn play_ring(settings: &VoiceSettings) { - play(plops(&RING, RING_SECONDS), 0.35, settings); -} - -fn plops(plops: &[Plop], seconds: f32) -> Vec { - let rate = VOICE_SAMPLE_RATE as f32; - let mut dry = vec![0.0; (rate * seconds) as usize]; - for plop in plops { - plop.add(&mut dry, rate); - } - reverb(dry, rate) -} - -const DETUNE: [f32; 2] = [0.998, 1.002]; -const PITCH_SETTLE: f32 = 0.04; -const ATTACK: f32 = 0.004; -const COMB_SECONDS: [f32; 4] = [0.0297, 0.0371, 0.0411, 0.0437]; -const COMB_FEEDBACK: f32 = 0.72; -const COMB_DAMPING: f32 = 0.35; -const REVERB_WET: f32 = 0.25; - -struct Plop { - start: f32, - from: f32, - rise: f32, - decay: f32, - gain: f32, -} - -const fn plop(start: f32, from: f32, rise: f32, decay: f32, gain: f32) -> Plop { - Plop { - start, - from, - rise, - decay, - gain, - } -} - -const YUMUSH_SECONDS: f32 = 0.9; -const YUMUSH: [Plop; 2] = [ - plop(0.0, 620.0, 0.6, 0.07, 1.0), - plop(0.13, 400.0, 0.45, 0.14, 0.9), -]; - -const RING_SECONDS: f32 = 1.3; -const RING: [Plop; 4] = [ - plop(0.0, 400.0, 0.45, 0.1, 0.9), - plop(0.14, 500.0, 0.45, 0.1, 0.9), - plop(0.28, 620.0, 0.6, 0.12, 1.0), - plop(0.5, 620.0, 0.6, 0.2, 0.8), -]; - -impl Plop { - fn add(&self, out: &mut [f32], rate: f32) { - let start = (self.start * rate) as usize; - for detune in DETUNE { - let mut phase = 0.0; - for (index, sample) in out.iter_mut().enumerate().skip(start) { - let time = (index - start) as f32 / rate; - let frequency = - self.from * detune * (1.0 + self.rise * (1.0 - (-time / PITCH_SETTLE).exp())); - phase += std::f32::consts::TAU * frequency / rate; - let envelope = (time / ATTACK).min(1.0) * (-time / self.decay).exp(); - *sample += phase.sin() * envelope * self.gain / DETUNE.len() as f32; - } - } - } -} - -fn reverb(dry: Vec, rate: f32) -> Vec { - let mut wet = vec![0.0; dry.len()]; - for seconds in COMB_SECONDS { - let mut buffer = vec![0.0; (rate * seconds) as usize]; - let mut filtered = 0.0; - for (index, (input, output)) in dry.iter().zip(wet.iter_mut()).enumerate() { - let slot = index % buffer.len(); - let delayed = buffer[slot]; - filtered = delayed * (1.0 - COMB_DAMPING) + filtered * COMB_DAMPING; - buffer[slot] = input + filtered * COMB_FEEDBACK; - *output += delayed / COMB_SECONDS.len() as f32; - } - } - - dry.iter() - .zip(wet) - .map(|(dry, wet)| dry + wet * REVERB_WET) - .collect() +pub fn play_sound(sound: Sound, settings: &VoiceSettings) { + play(sound.render(), sound.gain(), settings); } fn play(samples: Vec, gain: f32, settings: &VoiceSettings) { @@ -232,9 +129,7 @@ fn work( while let Ok(sample) = from_capture.pop() { captured.push(sample); } - let Ok(mut locked) = engine.lock() else { - return; - }; + let mut locked = lock(engine); for packet in locked.capture(&captured) { match connection { Some(connection) => { @@ -242,7 +137,7 @@ fn work( } None => { if let Some(Packet::Voice { seq, opus }) = Packet::decode(&packet) { - locked.receive(&LOOPBACK, seq, opus); + locked.receive(LOOPBACK, seq, opus); } } } @@ -262,7 +157,7 @@ fn work( impl Voice { pub fn apply(&mut self, settings: &VoiceSettings) { if settings.choice != self.choice { - self.audio = Audio::Silent; + self.audio = Audio::default(); self.audio = audio::start( Some(self.capture.clone()), self.playback.clone(), @@ -271,51 +166,44 @@ impl Voice { self.choice = settings.choice.clone(); } - self.with_engine((), |engine| { - engine.configure( - settings.sensitivity_db, - settings.input_volume, - settings.output_volume, - settings.activation, - settings.profile, - &settings.user_volumes, - ) - }); + lock(&self.engine).configure( + settings.sensitivity_db, + settings.input_volume, + settings.output_volume, + settings.activation, + settings.profile, + &settings.user_volumes, + ); } - fn with_engine(&self, default: T, f: impl FnOnce(&mut Engine) -> T) -> T { - self.engine - .lock() - .map_or(default, |mut engine| f(&mut engine)) - } - - pub fn receive(&self, from: &[u8; RELAY_PREFIX], seq: u32, opus: &[u8]) { - self.with_engine((), |engine| engine.receive(from, seq, opus)); + pub fn receive(&self, from: Id, seq: u32, opus: &[u8]) { + lock(&self.engine).receive(from, seq, opus); } pub fn levels(&self) -> Vec<(Id, Vec)> { - self.with_engine(Vec::new(), Engine::levels) + lock(&self.engine).levels() } pub fn own_level(&self) -> Vec { - self.with_engine(Vec::new(), Engine::own_level) + lock(&self.engine).own_level() } pub fn own_sending(&self) -> bool { - self.with_engine(false, |engine| engine.sending()) + lock(&self.engine).sending() } pub fn level_db(&self) -> f32 { - self.with_engine(SILENT_DB, |engine| engine.level_db()) + lock(&self.engine).level_db() } pub fn sample(&self) -> VoiceSample { + let stats = self.connection.as_ref().map(Connection::stats); + let received = stats.as_ref().map_or(0, |stats| stats.udp_rx.datagrams); + let (lost, sent) = stats.as_ref().map_or((0, 0), |stats| { + (stats.path.lost_packets, stats.path.sent_packets) + }); let ping_ms = self.connection.as_ref().map_or(0.0, |connection| { - let received = connection.stats().udp_rx.datagrams; - let mut heard = self - .last_heard - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()); + let mut heard = lock(&self.last_heard); if received != heard.0 { *heard = (received, Instant::now()); } @@ -327,40 +215,32 @@ impl Voice { rtt.as_secs_f32() * 1000.0 } }); - let (lost, sent) = self.connection.as_ref().map_or((0, 0), |connection| { - let path = connection.stats().path; - (path.lost_packets, path.sent_packets) - }); let loss = { - let mut last = self - .last_path - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()); + let mut last = lock(&self.last_path); let lost_delta = lost.saturating_sub(last.0); let sent_delta = sent.saturating_sub(last.1); *last = (lost, sent); lost_delta as f32 / sent_delta.max(1) as f32 }; - self.with_engine(VoiceSample::default(), |engine| { - engine.set_uplink_loss(loss); - VoiceSample { - at_ms: common::time::now_ms(), - ping_ms, - traffic: engine.take_traffic(), - bitrate_kbps: engine.bitrate_kbps(), - } - }) + let mut engine = lock(&self.engine); + engine.set_uplink_loss(loss); + VoiceSample { + at_ms: common::time::now_ms(), + ping_ms, + traffic: engine.take_traffic(), + bitrate_kbps: engine.bitrate_kbps(), + } } pub fn set_muted(&self, muted: bool) { - self.with_engine((), |engine| engine.set_muted(muted)); + lock(&self.engine).set_muted(muted); } pub fn set_deafened(&self, deafened: bool) { - self.with_engine((), |engine| engine.set_deafened(deafened)); + lock(&self.engine).set_deafened(deafened); } pub fn set_talking(&self, talking: bool) { - self.with_engine((), |engine| engine.set_talking(talking)); + lock(&self.engine).set_talking(talking); } } diff --git a/crates/client/src/voice/sound.rs b/crates/client/src/voice/sound.rs new file mode 100644 index 0000000..f7da9e6 --- /dev/null +++ b/crates/client/src/voice/sound.rs @@ -0,0 +1,127 @@ +use common::constant::VOICE_SAMPLE_RATE; + +#[derive(Clone, Copy)] +pub enum Sound { + Chime, + Notification, + Ring, +} + +impl Sound { + pub fn gain(self) -> f32 { + match self { + Self::Chime => 0.3, + Self::Notification | Self::Ring => 0.35, + } + } + + pub fn render(self) -> Vec { + match self { + Self::Chime => chime(), + Self::Notification => plops(&YUMUSH, YUMUSH_SECONDS), + Self::Ring => plops(&RING, RING_SECONDS), + } + } +} + +const CHIME: [(f32, f32); 2] = [(660.0, 0.18), (880.0, 0.32)]; + +fn chime() -> Vec { + let rate = VOICE_SAMPLE_RATE as f32; + let mut samples = Vec::new(); + for (frequency, seconds) in CHIME { + let length = (rate * seconds) as usize; + samples.extend((0..length).map(|index| { + let time = index as f32 / rate; + let fade = (1.0 - index as f32 / length as f32).powi(2); + (std::f32::consts::TAU * frequency * time).sin() * fade + })); + } + samples +} + +const DETUNE: [f32; 2] = [0.998, 1.002]; +const PITCH_SETTLE: f32 = 0.04; +const ATTACK: f32 = 0.004; +const COMB_SECONDS: [f32; 4] = [0.0297, 0.0371, 0.0411, 0.0437]; +const COMB_FEEDBACK: f32 = 0.72; +const COMB_DAMPING: f32 = 0.35; +const REVERB_WET: f32 = 0.25; + +struct Plop { + start: f32, + from: f32, + rise: f32, + decay: f32, + gain: f32, +} + +const fn plop(start: f32, from: f32, rise: f32, decay: f32, gain: f32) -> Plop { + Plop { + start, + from, + rise, + decay, + gain, + } +} + +const YUMUSH_SECONDS: f32 = 0.9; +const YUMUSH: [Plop; 2] = [ + plop(0.0, 620.0, 0.6, 0.07, 1.0), + plop(0.13, 400.0, 0.45, 0.14, 0.9), +]; + +const RING_SECONDS: f32 = 1.3; +const RING: [Plop; 4] = [ + plop(0.0, 400.0, 0.45, 0.1, 0.9), + plop(0.14, 500.0, 0.45, 0.1, 0.9), + plop(0.28, 620.0, 0.6, 0.12, 1.0), + plop(0.5, 620.0, 0.6, 0.2, 0.8), +]; + +fn plops(plops: &[Plop], seconds: f32) -> Vec { + let rate = VOICE_SAMPLE_RATE as f32; + let mut dry = vec![0.0; (rate * seconds) as usize]; + for plop in plops { + plop.add(&mut dry, rate); + } + reverb(dry, rate) +} + +impl Plop { + fn add(&self, out: &mut [f32], rate: f32) { + let start = (self.start * rate) as usize; + for detune in DETUNE { + let mut phase = 0.0; + for (index, sample) in out.iter_mut().enumerate().skip(start) { + let time = (index - start) as f32 / rate; + let frequency = + self.from * detune * (1.0 + self.rise * (1.0 - (-time / PITCH_SETTLE).exp())); + phase += std::f32::consts::TAU * frequency / rate; + let envelope = (time / ATTACK).min(1.0) * (-time / self.decay).exp(); + *sample += phase.sin() * envelope * self.gain / DETUNE.len() as f32; + } + } + } +} + +fn reverb(dry: Vec, rate: f32) -> Vec { + let mut wet = vec![0.0; dry.len()]; + for seconds in COMB_SECONDS { + let mut buffer = vec![0.0; (rate * seconds) as usize]; + let mut filtered = 0.0; + for (index, (input, output)) in dry.iter().zip(wet.iter_mut()).enumerate() { + let slot = index % buffer.len(); + let delayed = buffer[slot]; + filtered = delayed * (1.0 - COMB_DAMPING) + filtered * COMB_DAMPING; + buffer[slot] = input + filtered * COMB_FEEDBACK; + *output += delayed / COMB_SECONDS.len() as f32; + } + } + + dry.iter() + .zip(wet) + .map(|(dry, wet)| dry + wet * REVERB_WET) + .collect() +} diff --git a/crates/client/src/worker.rs b/crates/client/src/worker.rs new file mode 100644 index 0000000..ccb4c9b --- /dev/null +++ b/crates/client/src/worker.rs @@ -0,0 +1,86 @@ +use std::{ + error::Error, + sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }, + thread::JoinHandle, + time::Duration, +}; + +use tracing::{debug, warn}; + +pub const STOP_CHECK: Duration = Duration::from_millis(100); +const RETRY_AFTER_ERROR: Duration = Duration::from_secs(1); +const RETRY_AFTER_CHANGE: Duration = Duration::from_millis(100); + +pub struct Worker { + stop: Arc, + thread: Option>, +} + +impl Worker { + pub fn spawn(name: &str, body: impl FnOnce(&AtomicBool) + Send + 'static) -> Self { + let stop = Arc::new(AtomicBool::new(false)); + let thread = { + let stop = stop.clone(); + std::thread::Builder::new() + .name(name.to_string()) + .spawn(move || body(&stop)) + .inspect_err(|error| warn!("{name} not started: {error}")) + .ok() + }; + + Self { stop, thread } + } +} + +impl Drop for Worker { + fn drop(&mut self) { + self.stop.store(true, Ordering::Relaxed); + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } +} + +pub fn supervise( + name: &str, + stop: &AtomicBool, + mut attempt: impl FnMut() -> Result<(), Box>, +) { + let mut last: Option = None; + while !stop.load(Ordering::Relaxed) { + let pause = match attempt() { + Ok(()) => { + last = None; + RETRY_AFTER_CHANGE + } + Err(error) => { + let message = error.to_string(); + if last.as_deref() == Some(message.as_str()) { + debug!("{name}: {message}, retrying"); + } else { + warn!("{name}: {message}, retrying"); + last = Some(message); + } + RETRY_AFTER_ERROR + } + }; + wait(stop, pause); + } +} + +pub fn wait(stop: &AtomicBool, duration: Duration) -> bool { + let mut waited = Duration::ZERO; + while waited < duration { + if stop.load(Ordering::Relaxed) { + return false; + } + let step = STOP_CHECK.min(duration - waited); + std::thread::sleep(step); + waited += step; + } + + !stop.load(Ordering::Relaxed) +} diff --git a/crates/common/Cargo.toml b/crates/common/Cargo.toml index a9d03fd..7a7fd38 100644 --- a/crates/common/Cargo.toml +++ b/crates/common/Cargo.toml @@ -7,12 +7,12 @@ edition = "2024" bitcode.workspace = true quinn.workspace = true quinn-proto = { version = "0.11.19", default-features = false } -bytes = "1.12.2" -tracing = "0.1.44" -thiserror = "2.0.21" -reed-solomon-simd = "3.1.0" +bytes.workspace = true +tracing.workspace = true +thiserror.workspace = true +reed-solomon-simd.workspace = true socket2 = "0.6.5" -sha2 = "0.11.2" +sha2.workspace = true [lints] workspace = true diff --git a/crates/common/src/call.rs b/crates/common/src/call.rs index 3a5a676..9f40524 100644 --- a/crates/common/src/call.rs +++ b/crates/common/src/call.rs @@ -8,14 +8,14 @@ use crate::{ Account, AdminActionKind, AdminLogEntry, AttachmentInfo, BackupInfo, Ban, BanScope, Community, CommunitySummary, CommunityUsage, DayStat, Edit, Friends, Id, Invitation, InviteCode, LogEntry, Member, Message, MessageHit, Overview, Presence, Rank, ReleaseInfo, - Report, ReportStatus, ServerBan, ServerSettings, SessionInfo, Unread, UpdateClient, Usage, - User, VoiceRoom, + Report, ReportStatus, ServerBan, ServerSettings, SessionInfo, Unread, UpdateClient, User, + UserUsage, VoiceRoom, }, share::{Codec, Kind, Quality, Share, Source}, stats::Stats, validate::{ - validate_avatar_size, validate_community_name, validate_forward, validate_new_message, - validate_password, validate_poll, validate_reaction, validate_reason, + validate_avatar_size, validate_community_name, validate_forward, validate_message_edit, + validate_new_message, validate_password, validate_poll, validate_reaction, validate_reason, validate_server_settings, validate_status, validate_username, }, }; @@ -687,7 +687,7 @@ pub struct Session { #[derive(Debug, Clone, Encode, Decode)] pub struct StorageUsage { - pub users: Vec, + pub users: Vec, pub communities: Vec, } @@ -702,8 +702,8 @@ calls! { UpdateAvatar: User -> User, |c| validate_avatar_size(&c.image, MAXIMUM_AVATAR_BYTES as u64); RemoveAvatar: User -> User; GetAvatar: User -> Vec; - ListSessions: User -> Vec; - RevokeSession: User -> (); + ListSessions: Builder -> Vec; + RevokeSession: Builder -> (); CreateCommunity: User -> Community, |c| validate_community_name(&c.name); GetCommunity: User -> Community; UpdateCommunity: User -> Community, |c| validate_community_name(&c.name); @@ -720,9 +720,9 @@ calls! { ListLogs: User -> Vec; CreateMessage: User -> Message, |c| validate_new_message(&c.body, c.attachments.len(), MAXIMUM_MESSAGE_LENGTH); ForwardMessages: User -> Vec, |c| validate_forward(c.message_ids.len()); - UpdateMessage: User -> Message, |c| validate_new_message(&c.body, 0, MAXIMUM_MESSAGE_LENGTH); + UpdateMessage: User -> Message, |c| validate_message_edit(&c.body, MAXIMUM_MESSAGE_LENGTH); DeleteMessage: User -> (); - ListEdits: User -> Vec; + ListEdits: Builder -> Vec; CreatePoll: User -> Message, |c| validate_poll(&c.question, &c.options); Vote: User -> (); ClosePoll: User -> (); @@ -748,7 +748,7 @@ calls! { ReportMessage: User -> (), |c| validate_reason(Some(&c.reason)); ReportUser: User -> (), |c| validate_reason(Some(&c.reason)); ListReports: Builder -> Vec; - HandleReport: User -> (); + HandleReport: Builder -> (), |c| if c.status == ReportStatus::Open { Err(Error::Forbidden) } else { Ok(()) }; JoinVoice: User -> Vec; LeaveVoice: User -> (); StartShare: User -> (); @@ -761,8 +761,8 @@ calls! { DeclineCall: User -> (); ListVoiceParticipants: User -> Vec; ListVoiceRooms: Builder -> Vec; - KickFromVoice: User -> (); - ServerMute: User -> (); + KickFromVoice: Builder -> (); + ServerMute: Builder -> (); Register: Guest -> Session, |c| validate_username(&c.username).and(validate_password(&c.password)); Login: Guest -> Session, |c| validate_password(&c.password); Logout: User -> (); @@ -772,25 +772,25 @@ calls! { ListAdminLogs: Builder -> Vec; ListUserFriends: Builder -> Vec; GetOverview: Builder -> Overview; - SuspendUser: User -> (); - RevokeSessions: User -> (); - ResetPassword: User -> (), |c| validate_password(&c.password); - ClearProfile: User -> User; + SuspendUser: Builder -> (); + RevokeSessions: Builder -> (); + ResetPassword: Builder -> (), |c| validate_password(&c.password); + ClearProfile: Builder -> User; ListAllCommunities: Builder -> Vec; TransferOwnership: User -> (); UpdateServerSettings: Builder -> ServerSettings, |c| validate_server_settings(&c.settings); CreateUser: Builder -> User, |c| validate_username(&c.username).and(validate_password(&c.password)); - RenameUser: User -> User, |c| validate_username(&c.username); - TimeoutUser: User -> (); - BanUser: User -> (), |c| validate_reason(c.reason.as_deref()); + RenameUser: Builder -> User, |c| validate_username(&c.username); + TimeoutUser: Builder -> (); + BanUser: Builder -> (), |c| validate_reason(c.reason.as_deref()); ListServerBans: Builder -> Vec; RemoveServerBan: Builder -> (); - CreateInviteCode: User -> InviteCode; + CreateInviteCode: Builder -> InviteCode, |c| if c.uses == 0 { Err(Error::Forbidden) } else { Ok(()) }; ListInviteCodes: Builder -> Vec; DeleteInviteCode: Builder -> (); SearchMessages: Builder -> Vec; SearchCommunity: User -> Vec; - PurgeUser: User -> (); + PurgeUser: Builder -> (); SetCommunityVoice: User -> Community; ListAttachments: Builder -> Vec; DeleteAttachment: Builder -> (); diff --git a/crates/common/src/datagram.rs b/crates/common/src/datagram.rs index c594279..7760a0b 100644 --- a/crates/common/src/datagram.rs +++ b/crates/common/src/datagram.rs @@ -12,6 +12,7 @@ use tracing::warn; use crate::{ constant::{MAX_FRAME_BYTES, VIDEO_FRAGMENT_BYTES, VOICE_MAX_PAYLOAD}, + model::Id, share::{Kind, Layer}, transport::DATAGRAM_BUFFER_BYTES, }; @@ -62,14 +63,14 @@ pub enum Packet<'a> { }, Nack { kind: Kind, - user_id: i64, + user_id: Id, layer: Layer, frame: u32, indices: &'a [u8], }, Ack { kind: Kind, - user_id: i64, + user_id: Id, layer: Layer, ts_ms: u32, }, @@ -94,7 +95,7 @@ pub fn layout(length: u32, parity: u16) -> Layout { Layout { shard: length.div_ceil(data).max(2).next_multiple_of(2), data, - parity: usize::from(parity), + parity: usize::from(parity.max(1)), } } @@ -142,6 +143,29 @@ fn video_kind(tag: u8) -> Option { } } +fn put_feedback(out: &mut Vec, tag: u8, kind: Kind, user_id: Id, layer: Layer) { + out.push(tag); + out.push(video_tag(kind)); + out.extend_from_slice(&user_id.to_be_bytes()); + out.push(layer.to_byte()); +} + +fn parse_feedback(b: &[u8]) -> Option<(Kind, Id, Layer)> { + Some(( + video_kind(*b.get(1)?)?, + Id::from_be_bytes(b.get(2..10)?.try_into().ok()?), + Layer::from_byte(*b.get(10)?)?, + )) +} + +pub fn nack_indices(indices: &[u8]) -> impl Iterator + '_ { + indices + .as_chunks::<2>() + .0 + .iter() + .map(|pair| u16::from_le_bytes(*pair)) +} + impl<'a> Packet<'a> { pub fn encode(&self, out: &mut Vec) { match self { @@ -188,10 +212,7 @@ impl<'a> Packet<'a> { frame, indices, } => { - out.push(TAG_NACK); - out.push(video_tag(*kind)); - out.extend_from_slice(&user_id.to_be_bytes()); - out.push(layer.to_byte()); + put_feedback(out, TAG_NACK, *kind, *user_id, *layer); out.extend_from_slice(&frame.to_le_bytes()); out.extend_from_slice(indices); } @@ -201,23 +222,12 @@ impl<'a> Packet<'a> { layer, ts_ms, } => { - out.push(TAG_ACK); - out.push(video_tag(*kind)); - out.extend_from_slice(&user_id.to_be_bytes()); - out.push(layer.to_byte()); + put_feedback(out, TAG_ACK, *kind, *user_id, *layer); out.extend_from_slice(&ts_ms.to_le_bytes()); } } } - pub fn nack_indices(indices: &[u8]) -> impl Iterator + '_ { - indices - .as_chunks::<2>() - .0 - .iter() - .map(|pair| u16::from_le_bytes(*pair)) - } - pub fn decode(b: &'a [u8]) -> Option { match *b.first()? { TAG_VOICE => { @@ -237,23 +247,30 @@ impl<'a> Packet<'a> { } TAG_NACK => { let indices = b.get(NACK_HEADER..)?; - (indices.len() % 2 == 0 && indices.len() <= NACK_MAX * 2).then_some(())?; + if indices.len() % 2 != 0 || indices.len() > NACK_MAX * 2 { + return None; + } + let (kind, user_id, layer) = parse_feedback(b)?; Some(Self::Nack { - kind: video_kind(*b.get(1)?)?, - user_id: i64::from_be_bytes(b[2..10].try_into().ok()?), - layer: Layer::from_byte(b[10])?, + kind, + user_id, + layer, frame: u32_at(b, 11), indices, }) } - TAG_ACK => (b.len() == NACK_HEADER).then(|| { + TAG_ACK => { + if b.len() != NACK_HEADER { + return None; + } + let (kind, user_id, layer) = parse_feedback(b)?; Some(Self::Ack { - kind: video_kind(b[1])?, - user_id: i64::from_be_bytes(b[2..10].try_into().ok()?), - layer: Layer::from_byte(b[10])?, + kind, + user_id, + layer, ts_ms: u32_at(b, 11), }) - })?, + } tag => { let kind = video_kind(tag)?; let shard = b.get(VIDEO_HEADER..)?; @@ -291,13 +308,16 @@ impl<'a> Packet<'a> { } } -pub fn relayed(from: &[u8; RELAY_PREFIX], uplink: &[u8]) -> Bytes { - Bytes::from([from.as_slice(), uplink].concat()) +pub fn relayed(from: Id, uplink: &[u8]) -> Bytes { + let mut out = Vec::with_capacity(RELAY_PREFIX + uplink.len()); + out.extend_from_slice(&from.to_be_bytes()); + out.extend_from_slice(uplink); + out.into() } -pub fn split(b: &[u8]) -> Option<(&[u8; RELAY_PREFIX], Packet<'_>)> { +pub fn split(b: &[u8]) -> Option<(Id, Packet<'_>)> { let (from, rest) = b.split_first_chunk::()?; - Some((from, Packet::decode(rest)?)) + Some((Id::from_be_bytes(*from), Packet::decode(rest)?)) } #[derive(Debug, Clone, Copy)] @@ -331,6 +351,7 @@ pub fn fragments(info: FrameInfo, data: &[u8], mut emit: impl FnMut(&[u8])) { padded.resize(data_count * shard, 0); let Ok(repair) = reed_solomon_simd::encode(data_count, parity_count, padded.chunks(shard)) else { + warn!("fec encode failed, frame dropped"); return; }; let mut out = Vec::with_capacity(VIDEO_HEADER + shard); @@ -394,7 +415,7 @@ fn backlog(connection: &Connection) -> Duration { } #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Gate { +pub enum Pace { Send, Pause, Drop, @@ -412,25 +433,25 @@ impl Link { self.paused.is_some() } - pub fn gate(&mut self, connection: &Connection, keyframe: bool) -> Gate { + pub fn pace(&mut self, connection: &Connection, keyframe: bool) -> Pace { let rtt = connection.rtt(); let base = self.base.map_or(rtt, |base| base.min(rtt)); self.base = Some(base); let congested = rtt > base + RTT_SLACK || backlog(connection) > BACKLOG_LIMIT; match self.paused { - Some(since) if congested && since.elapsed() < PAUSE_MAX => Gate::Drop, + Some(since) if congested && since.elapsed() < PAUSE_MAX => Pace::Drop, Some(since) => { if since.elapsed() >= PAUSE_MAX { self.base = None; } self.paused = None; - Gate::Resume + Pace::Resume } None if congested && !keyframe => { self.paused = Some(Instant::now()); - Gate::Pause + Pace::Pause } - None => Gate::Send, + None => Pace::Send, } } } @@ -525,9 +546,9 @@ mod tests { Packet::peek_video(packet), Some((Kind::Camera, layer, true)) ); - let relay = relayed(&[9; RELAY_PREFIX], packet); + let relay = relayed(9, packet); let (from, _) = split(&relay).unwrap(); - assert_eq!(from, &[9; RELAY_PREFIX]); + assert_eq!(from, 9); count += 1; }); assert_eq!(count, 3); diff --git a/crates/common/src/error.rs b/crates/common/src/error.rs index f751b8e..207c31c 100644 --- a/crates/common/src/error.rs +++ b/crates/common/src/error.rs @@ -14,6 +14,7 @@ pub enum Problem { pub fn size_text(size: u64) -> String { match size { + size if size >= 1 << 30 => format!("{:.1} GB", size as f64 / (1 << 30) as f64), size if size >= 1 << 20 => format!("{:.1} MB", size as f64 / (1 << 20) as f64), size if size >= 1 << 10 => format!("{:.0} KB", size as f64 / (1 << 10) as f64), size => format!("{size} B"), @@ -64,6 +65,7 @@ pub enum Field { Password, Community, Message, + Attachments, Status, Avatar, Attachment, @@ -95,6 +97,7 @@ impl Display for Field { Field::Password => "password:", Field::Community => "community name:", Field::Message => "message:", + Field::Attachments => "attachments:", Field::Status => "status:", Field::Avatar => "avatar:", Field::Attachment => "file", diff --git a/crates/common/src/frame.rs b/crates/common/src/frame.rs index be16a2f..8a55bd9 100644 --- a/crates/common/src/frame.rs +++ b/crates/common/src/frame.rs @@ -1,4 +1,4 @@ -pub use bitcode::{DecodeOwned, Encode}; +use bitcode::{DecodeOwned, Encode}; use quinn::{RecvStream, SendStream}; use crate::constant::MAXIMUM_AVATAR_BYTES; diff --git a/crates/common/src/model.rs b/crates/common/src/model.rs index 8e1ede0..5685b3c 100644 --- a/crates/common/src/model.rs +++ b/crates/common/src/model.rs @@ -101,12 +101,18 @@ pub struct User { pub created_at: u64, } +#[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)] +pub enum Suspension { + None, + Until(u64), + Indefinite, +} + #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] pub struct Account { pub user: User, - pub suspended: bool, + pub suspension: Suspension, pub last_seen: Option, - pub suspended_until: Option, pub ghost: bool, } @@ -232,123 +238,63 @@ pub struct LogEntry { pub action: LogAction, } -#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] -pub enum AdminAction { - RoleChanged { role: Role }, - UserDeleted, - UserSuspended, - UserUnsuspended, - SessionsRevoked, - PasswordReset, - ProfileCleared, - UserCreated, - CommunityDeleted, - OwnershipTransferred, - SettingsChanged, - UserRenamed { from: String }, - UserTimedOut { minutes: u32 }, - UserBanned { reason: Option }, - BanRemoved, - InviteCreated, - InviteDeleted, - ReportHandled { status: ReportStatus }, - MessageDeleted, - UserPurged { messages: u64 }, - VoiceKicked, - VoiceMuted { muted: bool }, - CommunityVoiceSet { enabled: bool }, - AttachmentDeleted, - GhostEnabled, - GhostDisabled, - GhostVisit, - GhostVoice { seconds: u64 }, - BackupCreated { name: String }, - BackupDeleted { name: String }, - BackupDownloaded { name: String }, - ReleasePublished { seq: u64, required: bool }, - ReleaseRequired { seq: u64, required: bool }, - Community(LogAction), -} +macro_rules! admin_actions { + ($($variant:ident $(($inner:ty))? $({ $($field:ident: $ty:ty),* })? => $text:literal),* $(,)?) => { + #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] + pub enum AdminAction { + $($variant $(($inner))? $({ $($field: $ty),* })?),* + } -string_enum! { - #[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)] - AdminActionKind { - RoleChanged => "role_changed", - UserDeleted => "user_deleted", - UserSuspended => "user_suspended", - UserUnsuspended => "user_unsuspended", - SessionsRevoked => "sessions_revoked", - PasswordReset => "password_reset", - ProfileCleared => "profile_cleared", - UserCreated => "user_created", - CommunityDeleted => "community_deleted", - OwnershipTransferred => "ownership_transferred", - SettingsChanged => "settings_changed", - UserRenamed => "user_renamed", - UserTimedOut => "user_timed_out", - UserBanned => "user_banned", - BanRemoved => "ban_removed", - InviteCreated => "invite_created", - InviteDeleted => "invite_deleted", - ReportHandled => "report_handled", - MessageDeleted => "message_deleted", - UserPurged => "user_purged", - VoiceKicked => "voice_kicked", - VoiceMuted => "voice_muted", - CommunityVoiceSet => "community_voice_set", - AttachmentDeleted => "attachment_deleted", - GhostEnabled => "ghost_enabled", - GhostDisabled => "ghost_disabled", - GhostVisit => "ghost_visit", - GhostVoice => "ghost_voice", - BackupCreated => "backup_created", - BackupDeleted => "backup_deleted", - BackupDownloaded => "backup_downloaded", - ReleasePublished => "release_published", - ReleaseRequired => "release_required", - Community => "community", - } -} + string_enum! { + #[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)] + AdminActionKind { $($variant => $text),* } + } -impl AdminAction { - pub fn kind(&self) -> AdminActionKind { - match self { - AdminAction::RoleChanged { .. } => AdminActionKind::RoleChanged, - AdminAction::UserDeleted => AdminActionKind::UserDeleted, - AdminAction::UserSuspended => AdminActionKind::UserSuspended, - AdminAction::UserUnsuspended => AdminActionKind::UserUnsuspended, - AdminAction::SessionsRevoked => AdminActionKind::SessionsRevoked, - AdminAction::PasswordReset => AdminActionKind::PasswordReset, - AdminAction::ProfileCleared => AdminActionKind::ProfileCleared, - AdminAction::UserCreated => AdminActionKind::UserCreated, - AdminAction::CommunityDeleted => AdminActionKind::CommunityDeleted, - AdminAction::OwnershipTransferred => AdminActionKind::OwnershipTransferred, - AdminAction::SettingsChanged => AdminActionKind::SettingsChanged, - AdminAction::UserRenamed { .. } => AdminActionKind::UserRenamed, - AdminAction::UserTimedOut { .. } => AdminActionKind::UserTimedOut, - AdminAction::UserBanned { .. } => AdminActionKind::UserBanned, - AdminAction::BanRemoved => AdminActionKind::BanRemoved, - AdminAction::InviteCreated => AdminActionKind::InviteCreated, - AdminAction::InviteDeleted => AdminActionKind::InviteDeleted, - AdminAction::ReportHandled { .. } => AdminActionKind::ReportHandled, - AdminAction::MessageDeleted => AdminActionKind::MessageDeleted, - AdminAction::UserPurged { .. } => AdminActionKind::UserPurged, - AdminAction::VoiceKicked => AdminActionKind::VoiceKicked, - AdminAction::VoiceMuted { .. } => AdminActionKind::VoiceMuted, - AdminAction::CommunityVoiceSet { .. } => AdminActionKind::CommunityVoiceSet, - AdminAction::AttachmentDeleted => AdminActionKind::AttachmentDeleted, - AdminAction::GhostEnabled => AdminActionKind::GhostEnabled, - AdminAction::GhostDisabled => AdminActionKind::GhostDisabled, - AdminAction::GhostVisit => AdminActionKind::GhostVisit, - AdminAction::GhostVoice { .. } => AdminActionKind::GhostVoice, - AdminAction::BackupCreated { .. } => AdminActionKind::BackupCreated, - AdminAction::BackupDeleted { .. } => AdminActionKind::BackupDeleted, - AdminAction::BackupDownloaded { .. } => AdminActionKind::BackupDownloaded, - AdminAction::ReleasePublished { .. } => AdminActionKind::ReleasePublished, - AdminAction::ReleaseRequired { .. } => AdminActionKind::ReleaseRequired, - AdminAction::Community(_) => AdminActionKind::Community, + impl AdminAction { + pub fn kind(&self) -> AdminActionKind { + match self { + $(AdminAction::$variant { .. } => AdminActionKind::$variant),* + } + } } - } + }; +} + +admin_actions! { + RoleChanged { role: Role } => "role_changed", + UserDeleted => "user_deleted", + UserSuspended => "user_suspended", + UserUnsuspended => "user_unsuspended", + SessionsRevoked => "sessions_revoked", + PasswordReset => "password_reset", + ProfileCleared => "profile_cleared", + UserCreated => "user_created", + CommunityDeleted => "community_deleted", + OwnershipTransferred => "ownership_transferred", + SettingsChanged => "settings_changed", + UserRenamed { from: String } => "user_renamed", + UserTimedOut { minutes: u32 } => "user_timed_out", + UserBanned { reason: Option } => "user_banned", + BanRemoved => "ban_removed", + InviteCreated => "invite_created", + InviteDeleted => "invite_deleted", + ReportHandled { status: ReportStatus } => "report_handled", + MessageDeleted => "message_deleted", + UserPurged { messages: u64 } => "user_purged", + VoiceKicked => "voice_kicked", + VoiceMuted { muted: bool } => "voice_muted", + CommunityVoiceSet { enabled: bool } => "community_voice_set", + AttachmentDeleted => "attachment_deleted", + GhostEnabled => "ghost_enabled", + GhostDisabled => "ghost_disabled", + GhostVisit => "ghost_visit", + GhostVoice { seconds: u64 } => "ghost_voice", + BackupCreated { name: String } => "backup_created", + BackupDeleted { name: String } => "backup_deleted", + BackupDownloaded { name: String } => "backup_downloaded", + ReleasePublished { seq: u64, required: bool } => "release_published", + ReleaseRequired { seq: u64, required: bool } => "release_required", + Community(LogAction) => "community", } #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] @@ -483,7 +429,7 @@ pub struct BackupInfo { } #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] -pub struct Usage { +pub struct UserUsage { pub user: User, pub bytes: u64, pub count: u64, diff --git a/crates/common/src/permission.rs b/crates/common/src/permission.rs index e025e07..74c849a 100644 --- a/crates/common/src/permission.rs +++ b/crates/common/src/permission.rs @@ -11,20 +11,20 @@ pub fn effective_rank(role: Role, rank: Option) -> Option { } } -pub fn can_read(actor: Option) -> bool { +pub fn is_member(actor: Option) -> bool { actor.is_some() } -pub fn can_join_voice(actor: Option) -> bool { - actor.is_some() +pub fn is_moderator(actor: Option) -> bool { + actor >= Some(Rank::Moderator) } -pub fn can_share(actor: Option) -> bool { - actor.is_some() +pub fn is_admin(actor: Option) -> bool { + actor >= Some(Rank::Admin) } -pub fn can_post(actor: Option) -> bool { - actor.is_some() +pub fn is_owner(actor: Option) -> bool { + actor >= Some(Rank::Owner) } pub fn can_join(role: Role, banned: bool) -> bool { @@ -32,31 +32,23 @@ pub fn can_join(role: Role, banned: bool) -> bool { } pub fn can_pin(actor: Option, direct: bool) -> bool { - actor >= Some(Rank::Moderator) || (direct && actor.is_some()) + is_moderator(actor) || (direct && is_member(actor)) } pub fn can_close_poll(actor: Option, is_author: bool) -> bool { - is_author || actor >= Some(Rank::Moderator) + is_author || is_moderator(actor) } pub fn can_delete_message(actor: Option, author: Option, is_author: bool) -> bool { - is_author || (actor >= Some(Rank::Moderator) && actor > author) + is_author || (is_moderator(actor) && actor > author) } pub fn can_moderate(actor: Option, target: Option) -> bool { - actor >= Some(Rank::Moderator) && actor > target && target != Some(Rank::Owner) -} - -pub fn can_unban(actor: Option) -> bool { - actor >= Some(Rank::Moderator) -} - -pub fn can_read_logs(actor: Option) -> bool { - actor >= Some(Rank::Moderator) + is_moderator(actor) && actor > target && target != Some(Rank::Owner) } pub fn can_set_rank(actor: Option, target: Option, new: Rank) -> bool { - actor >= Some(Rank::Admin) + is_admin(actor) && actor > target && Some(new) < actor && new != Rank::Owner @@ -65,38 +57,14 @@ pub fn can_set_rank(actor: Option, target: Option, new: Rank) -> boo && target != Some(Rank::Owner) } -pub fn can_rename_community(actor: Option) -> bool { - actor >= Some(Rank::Admin) -} - -pub fn can_delete_community(actor: Option) -> bool { - actor >= Some(Rank::Owner) -} - -pub fn can_transfer_ownership(actor: Option) -> bool { - actor >= Some(Rank::Owner) -} - -pub fn can_manage_community(actor: Option) -> bool { - can_rename_community(actor) - || can_manage_voice(actor) - || can_unban(actor) - || can_read_logs(actor) - || can_delete_community(actor) -} - pub fn can_leave(actor: Option) -> bool { - actor.is_some() && actor != Some(Rank::Owner) + is_member(actor) && actor != Some(Rank::Owner) } pub fn can_delete_user(actor: Role, is_self: bool, target: Role) -> bool { is_self || can_manage_user(actor, false, target) } -pub fn can_manage_voice(actor: Option) -> bool { - actor >= Some(Rank::Owner) -} - pub fn can_manage_user(actor: Role, is_self: bool, target: Role) -> bool { is_builder(actor) && !is_self && !is_builder(target) } diff --git a/crates/common/src/session.rs b/crates/common/src/session.rs index 6bf68b8..453ac0b 100644 --- a/crates/common/src/session.rs +++ b/crates/common/src/session.rs @@ -6,7 +6,6 @@ use crate::model::User; pub struct Hello { pub token: Option, pub device: String, - pub build: Option, pub install: crate::update::Install, } diff --git a/crates/common/src/transport.rs b/crates/common/src/transport.rs index 6ccde18..f1b0f52 100644 --- a/crates/common/src/transport.rs +++ b/crates/common/src/transport.rs @@ -7,7 +7,7 @@ use std::{ }; use quinn::{ - Endpoint, EndpointConfig, ServerConfig, TokioRuntime, TransportConfig, VarInt, + Connection, Endpoint, EndpointConfig, ServerConfig, TokioRuntime, TransportConfig, VarInt, congestion::{Controller, ControllerFactory, ControllerMetrics, CubicConfig}, }; use quinn_proto::RttEstimator; @@ -15,7 +15,7 @@ use socket2::{Domain, Protocol, Socket, Type}; macro_rules! protocol { () => { - "yumush/8" + "yumush/9" }; } @@ -54,36 +54,48 @@ impl ControllerFactory for TolerantConfig { inner: Arc::new(CubicConfig::default()).build(now, current_mtu), rtt: Duration::ZERO, min_rtt: Duration::ZERO, - sent: 0, - lost: 0, + current: Window::default(), + prev: Window::default(), since: now, }) } } +#[derive(Clone, Copy, Default)] +struct Window { + sent: u64, + lost: u64, +} + struct Tolerant { inner: Box, rtt: Duration, min_rtt: Duration, - sent: u64, - lost: u64, + current: Window, + prev: Window, since: Instant, } impl Tolerant { fn roll(&mut self, now: Instant) { - if now.saturating_duration_since(self.since) >= LOSS_WINDOW { - self.sent = 0; - self.lost = 0; - self.since = now; + let age = now.saturating_duration_since(self.since); + if age < LOSS_WINDOW { + return; } + self.prev = if age > LOSS_WINDOW * 2 { + Window::default() + } else { + self.current + }; + self.current = Window::default(); + self.since = now; } } impl Controller for Tolerant { fn on_sent(&mut self, now: Instant, bytes: u64, last_packet_number: u64) { self.roll(now); - self.sent += bytes; + self.current.sent += bytes; self.inner.on_sent(now, bytes, last_packet_number); } @@ -119,9 +131,12 @@ impl Controller for Tolerant { lost_bytes: u64, ) { self.roll(now); - self.lost += lost_bytes; + self.current.lost += lost_bytes; let queued = self.rtt > self.min_rtt + QUEUE_SLACK; - let heavy = heavy_loss(self.lost, self.sent); + let heavy = heavy_loss( + self.current.lost + self.prev.lost, + self.current.sent + self.prev.sent, + ); if is_persistent_congestion || queued || heavy { self.inner .on_congestion_event(now, sent, is_persistent_congestion, lost_bytes); @@ -145,8 +160,8 @@ impl Controller for Tolerant { inner: self.inner.clone_box(), rtt: self.rtt, min_rtt: self.min_rtt, - sent: self.sent, - lost: self.lost, + current: self.current, + prev: self.prev, since: self.since, }) } @@ -176,7 +191,6 @@ pub fn endpoint( #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Close { Normal = 0, - SignedOut = 1, Revoked = 2, Banned = 3, Maintenance = 4, @@ -186,25 +200,22 @@ pub enum Close { } impl Close { - pub const ALL: [Self; 8] = [ - Self::Normal, - Self::SignedOut, - Self::Revoked, - Self::Banned, - Self::Maintenance, - Self::Slow, - Self::Protocol, - Self::Restart, - ]; - pub fn of(code: VarInt) -> Option { - Self::ALL.into_iter().find(|close| close.code() == code) + match code.into_inner() { + 0 => Some(Self::Normal), + 2 => Some(Self::Revoked), + 3 => Some(Self::Banned), + 4 => Some(Self::Maintenance), + 5 => Some(Self::Slow), + 6 => Some(Self::Protocol), + 7 => Some(Self::Restart), + _ => None, + } } pub fn reason(self) -> &'static str { match self { Self::Normal => "closed", - Self::SignedOut => "signed out", Self::Revoked => "session revoked", Self::Banned => "banned", Self::Maintenance => "maintenance", @@ -217,4 +228,8 @@ impl Close { pub fn code(self) -> VarInt { VarInt::from_u32(self as u32) } + + pub fn on(self, connection: &Connection) { + connection.close(self.code(), self.reason().as_bytes()); + } } diff --git a/crates/common/src/update.rs b/crates/common/src/update.rs index 9e3ccd9..d1c2f90 100644 --- a/crates/common/src/update.rs +++ b/crates/common/src/update.rs @@ -4,8 +4,13 @@ pub const ALPN: &[u8] = b"yumush-update/1"; pub const FILE_MAX: u64 = 512 << 20; pub const MARK: &str = "yumush-target:"; pub const PROTOCOL_MARK_PREFIX: &str = "yumush-protocol:"; -pub const SERVER_TARGET: &str = "server-x86_64-linux"; -pub const SERVER_MARK: &str = "yumush-target:server-x86_64-linux;"; +macro_rules! server_target { + () => { + "server-x86_64-linux" + }; +} +pub const SERVER_TARGET: &str = server_target!(); +pub const SERVER_MARK: &str = concat!("yumush-target:", server_target!(), ";"); pub const SERVER_VERSION: &str = "yumush-server"; const TARGET_MAX: usize = 32; @@ -113,6 +118,36 @@ pub fn protocol_of(bytes: &[u8]) -> Option { }) } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Side { + Server, + Client, + Both, +} + +impl Side { + pub fn takes(self, target: &str) -> bool { + match self { + Self::Server => target == SERVER_TARGET, + Self::Client => target != SERVER_TARGET, + Self::Both => true, + } + } +} + +impl std::str::FromStr for Side { + type Err = &'static str; + + fn from_str(side: &str) -> Result { + match side { + "server" => Ok(Self::Server), + "client" => Ok(Self::Client), + "both" => Ok(Self::Both), + _ => Err("server, client or both"), + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -143,33 +178,3 @@ mod tests { ); } } - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Side { - Server, - Client, - Both, -} - -impl Side { - pub fn takes(self, target: &str) -> bool { - match self { - Self::Server => target == SERVER_TARGET, - Self::Client => target != SERVER_TARGET, - Self::Both => true, - } - } -} - -impl std::str::FromStr for Side { - type Err = &'static str; - - fn from_str(side: &str) -> Result { - match side { - "server" => Ok(Self::Server), - "client" => Ok(Self::Client), - "both" => Ok(Self::Both), - _ => Err("server, client or both"), - } - } -} diff --git a/crates/common/src/validate.rs b/crates/common/src/validate.rs index 6c3b4d8..8fe7fb3 100644 --- a/crates/common/src/validate.rs +++ b/crates/common/src/validate.rs @@ -3,13 +3,13 @@ use std::collections::BTreeSet; use crate::{ constant::{ MAXIMUM_ANNOUNCEMENT_LENGTH, MAXIMUM_ATTACHMENT_LIMIT_BYTES, - MAXIMUM_ATTACHMENT_NAME_LENGTH, MAXIMUM_AVATAR_BYTES, MAXIMUM_COMMUNITY_NAME_LENGTH, - MAXIMUM_DEVICE_NAME_LENGTH, MAXIMUM_FORWARD_MESSAGES, MAXIMUM_MESSAGE_LENGTH, - MAXIMUM_PASSWORD_LENGTH, MAXIMUM_POLL_OPTION_LENGTH, MAXIMUM_POLL_OPTIONS, - MAXIMUM_POLL_QUESTION_LENGTH, MAXIMUM_REASON_LENGTH, MAXIMUM_STATUS_LENGTH, - MAXIMUM_USERNAME_LENGTH, MINIMUM_ATTACHMENT_LIMIT_BYTES, MINIMUM_COMMUNITY_NAME_LENGTH, - MINIMUM_MESSAGE_LENGTH, MINIMUM_PASSWORD_LENGTH, MINIMUM_POLL_OPTIONS, - MINIMUM_USERNAME_LENGTH, REACTIONS, + MAXIMUM_ATTACHMENT_NAME_LENGTH, MAXIMUM_ATTACHMENTS_PER_MESSAGE, MAXIMUM_AVATAR_BYTES, + MAXIMUM_COMMUNITY_NAME_LENGTH, MAXIMUM_DEVICE_NAME_LENGTH, MAXIMUM_FORWARD_MESSAGES, + MAXIMUM_MESSAGE_LENGTH, MAXIMUM_PASSWORD_LENGTH, MAXIMUM_POLL_OPTION_LENGTH, + MAXIMUM_POLL_OPTIONS, MAXIMUM_POLL_QUESTION_LENGTH, MAXIMUM_REASON_LENGTH, + MAXIMUM_STATUS_LENGTH, MAXIMUM_USERNAME_LENGTH, MINIMUM_ATTACHMENT_LIMIT_BYTES, + MINIMUM_COMMUNITY_NAME_LENGTH, MINIMUM_MESSAGE_LENGTH, MINIMUM_PASSWORD_LENGTH, + MINIMUM_POLL_OPTIONS, MINIMUM_USERNAME_LENGTH, REACTIONS, }, error::{Error, Field, Problem}, model::{Poll, ServerSettings}, @@ -70,12 +70,18 @@ pub fn validate_community_name(name: &str) -> Result<(), Error> { } pub fn validate_new_message(body: &str, attachments: usize, maximum: usize) -> Result<(), Error> { + check_length(attachments, 0, MAXIMUM_ATTACHMENTS_PER_MESSAGE) + .map_err(invalid(Field::Attachments))?; let minimum = if attachments == 0 { MINIMUM_MESSAGE_LENGTH } else { 0 }; - check_length(body.len(), minimum, maximum).map_err(invalid(Field::Message)) + check_text(body, minimum, maximum).map_err(invalid(Field::Message)) +} + +pub fn validate_message_edit(body: &str, maximum: usize) -> Result<(), Error> { + check_text(body, 0, maximum).map_err(invalid(Field::Message)) } pub fn validate_poll(question: &str, options: &[String]) -> Result<(), Error> { diff --git a/crates/pixel/src/lib.rs b/crates/pixel/src/lib.rs index bf9d384..bc37331 100644 --- a/crates/pixel/src/lib.rs +++ b/crates/pixel/src/lib.rs @@ -122,14 +122,12 @@ pub fn nv12_to_bgra(data: &[u8], width: u32, height: u32) -> Option> { } pub fn bgra_to_i420(source: &Bgra, width: u32, height: u32) -> Option { - let resized = if (source.width, source.height) != (width, height) { - Some(scale(source, width, height)?) + let scaled; + let (data, stride) = if (source.width, source.height) == (width, height) { + (source.data, source.stride) } else { - None - }; - let (data, stride) = match &resized { - Some(pixels) => (pixels.as_slice(), width * BYTES_PER_PIXEL), - None => (source.data, source.stride), + scaled = scale(source, width, height)?; + (scaled.as_slice(), width * BYTES_PER_PIXEL) }; let mut planes = YuvPlanarImageMut::alloc(width, height, YuvChromaSubsampling::Yuv420); yuv::bgra_to_yuv420( diff --git a/crates/server/Cargo.toml b/crates/server/Cargo.toml index fdd8f83..2ca0c23 100644 --- a/crates/server/Cargo.toml +++ b/crates/server/Cargo.toml @@ -4,7 +4,7 @@ version = "0.1.0" edition = "2024" [dependencies] -usage = { path = "../usage" } +usage.workspace = true common.workspace = true tokio.workspace = true quinn = { workspace = true, features = ["rustls-aws-lc-rs"] } @@ -12,17 +12,17 @@ rcgen = "0.14.10" bitcode.workspace = true rustls.workspace = true turso = { version = "0.9.0-pre.6", default-features = false } -sha2 = "0.11.2" -bytes = "1.12.2" +sha2.workspace = true +bytes.workspace = true argon2 = "0.6.0" getrandom = "0.4.3" -image = { version = "0.25.10", default-features = false, features = ["jpeg", "png", "webp", "gif"] } -thiserror = "2.0.21" -tracing = "0.1.44" -tracing-subscriber = "0.3.23" -ureq = { version = "3.5.2", features = ["json"] } -serde = { version = "1.0.229", features = ["derive"] } -serde_json = "1.0.154" +image.workspace = true +thiserror.workspace = true +tracing.workspace = true +tracing-subscriber.workspace = true +ureq = { workspace = true, features = ["json"] } +serde.workspace = true +serde_json.workspace = true zstd = { version = "0.14.5", features = ["zstdmt"] } [lints] diff --git a/crates/server/src/authentication.rs b/crates/server/src/authentication.rs index 1d12596..e74a7ca 100644 --- a/crates/server/src/authentication.rs +++ b/crates/server/src/authentication.rs @@ -2,7 +2,7 @@ use argon2::{Argon2, PasswordHasher, PasswordVerifier}; use common::{ call::{Call, Login, Register, Session}, error::Error as CommonError, - model::{Id, Role, ServerSettings, User}, + model::{Id, Role, ServerBanKind, ServerSettings, Suspension, User}, permission, transport::Close, }; @@ -13,7 +13,7 @@ use crate::{ error::{ServerError, ensure_with}, hub::{Client, Hub}, network::Shared, - request::limit_logins, + rate_limit::RateLimit, }; const SALT_LENGTH: usize = 16; @@ -65,6 +65,21 @@ async fn open_session(user_id: Id, db: &Connection) -> Result Result<(), ServerError> { + let limit = db::settings::read(db).await?.logins_per_minute; + let ip = client + .conn + .as_ref() + .map(|conn| conn.remote_address().ip().to_string()) + .unwrap_or_default(); + + Ok(rate_limit.allow(&ip, limit)?) +} + pub async fn create_account( username: &str, password: &str, @@ -81,16 +96,13 @@ pub(crate) async fn register( call.validate()?; shared .db - .run(async |db| limit_logins(&shared.services.rate_limit, client.conn.as_ref(), db).await) + .run(async |db| limit_logins(&shared.services.rate_limit, client, db).await) .await?; let password_hash = hash_blocking(call.password.clone()).await?; shared .db .run(async |db| { - if db::server_ban::username_banned(&call.username, db).await? { - return Err(CommonError::Banned.into()); - } let settings = db::settings::read(db).await?; let first = !db::user::any(db).await?; if !settings.registration_open && !first { @@ -119,7 +131,7 @@ pub(crate) async fn login( let (user, password_hash) = shared .db .run(async |db| { - limit_logins(&shared.services.rate_limit, client.conn.as_ref(), db).await?; + limit_logins(&shared.services.rate_limit, client, db).await?; db::user::password_hash_of(&call.username, db) .await? .ok_or(CommonError::WrongCredentials.into()) @@ -140,11 +152,20 @@ pub(crate) async fn login( } async fn admit(user: &User, settings: &ServerSettings, db: &Connection) -> Result<(), ServerError> { - if db::server_ban::username_banned(&user.username, db).await? { + if db::server_ban::banned(ServerBanKind::Username, &user.username, db).await? { return Err(CommonError::Banned.into()); } - if let Some(until_ms) = db::user::suspended(user.id, db).await? { - return Err(CommonError::Suspended { until_ms }.into()); + match db::user::suspension_of(user.id, db).await? { + Suspension::None => {} + Suspension::Until(until_ms) => { + return Err(CommonError::Suspended { + until_ms: Some(until_ms), + } + .into()); + } + Suspension::Indefinite => { + return Err(CommonError::Suspended { until_ms: None }.into()); + } } if !permission::is_builder(user.role) && settings.maintenance { return Err(CommonError::Maintenance.into()); @@ -172,14 +193,6 @@ pub async fn recheck(session_id: Id, db: &Connection) -> Result Result<(), ServerError> { - db::session::delete(session_id, db).await -} - -pub(crate) async fn revoke_sessions(user_id: Id, db: &Connection) -> Result<(), ServerError> { - db::session::delete_all(user_id, db).await -} - pub async fn reset_password( user_id: Id, password: &str, @@ -188,26 +201,22 @@ pub async fn reset_password( db::user::set_password_hash(user_id, &hash(password)?, db).await } -pub enum Revoke { - User(Id), - Session { user_id: Id, session_id: Id }, +pub async fn revoke_user(hub: &Hub, user_id: Id, db: &Connection) -> Result<(), ServerError> { + db::session::delete_all(user_id, db).await?; + hub.kick_user(user_id, Close::Revoked); + + Ok(()) } -pub async fn revoke(hub: &Hub, target: Revoke, db: &Connection) -> Result<(), ServerError> { - match target { - Revoke::User(user_id) => { - revoke_sessions(user_id, db).await?; - hub.kick_user(user_id, Close::Revoked); - } - Revoke::Session { - user_id, - session_id, - } => { - let deleted = db::session::delete_of(user_id, session_id, db).await?; - ensure_with(deleted == 1, CommonError::NotFound)?; - hub.kick_session(session_id, Close::Revoked); - } - } +pub async fn revoke_session( + hub: &Hub, + user_id: Id, + session_id: Id, + db: &Connection, +) -> Result<(), ServerError> { + let deleted = db::session::delete_of(user_id, session_id, db).await?; + ensure_with(deleted == 1, CommonError::NotFound)?; + hub.kick_session(session_id, Close::Revoked); Ok(()) } @@ -219,23 +228,11 @@ mod tests { error::Error as CommonError, }; - use crate::{ - authentication, - error::ServerError, - hub::Client, - network::{Services, Shared}, - test, - }; + use crate::{authentication, error::ServerError, hub::Client, network::Services, test}; #[tokio::test] async fn register_and_login() { - let shared = Shared { - db: test::db().await, - services: Services::default(), - directory: test::directory(), - backups: test::directory(), - releases: Default::default(), - }; + let shared = test::shared(test::db().await, Services::new(test::directory())); let client = Client::detached(None); let registered = authentication::register( diff --git a/crates/server/src/backup.rs b/crates/server/src/backup.rs index 21a7f4e..568656d 100644 --- a/crates/server/src/backup.rs +++ b/crates/server/src/backup.rs @@ -14,8 +14,9 @@ use crate::{ const PREFIX: &str = "yumush-"; const EXTENSION: &str = ".db"; +const LEGACY_SECS_LIMIT: u64 = 100_000_000_000; -fn created_secs(name: &str) -> Option { +fn parse(name: &str) -> Option { name.strip_prefix(PREFIX)? .strip_suffix(EXTENSION)? .parse() @@ -23,38 +24,42 @@ fn created_secs(name: &str) -> Option { } fn info(directory: &Path, name: &str) -> Result { - let created_secs = created_secs(name).ok_or(CommonError::NotFound)?; + let stamp = parse(name).ok_or(CommonError::NotFound)?; + let created_ms = if stamp < LEGACY_SECS_LIMIT { + stamp * 1000 + } else { + stamp + }; let size_bytes = std::fs::metadata(directory.join(name))?.len(); Ok(BackupInfo { name: name.to_string(), size_bytes, - created_ms: created_secs * 1000, + created_ms, }) } fn path_of(directory: &Path, name: &str) -> Result { validate_backup_name(name)?; - created_secs(name).ok_or(CommonError::NotFound)?; + parse(name).ok_or(CommonError::NotFound)?; Ok(directory.join(name)) } pub async fn create(db: &Db, directory: &Path) -> Result { - let name = format!("{PREFIX}{}{EXTENSION}", time::now_ms() / 1000); + let name = format!("{PREFIX}{}{EXTENSION}", time::now_ms()); db.backup(&directory.join(&name).to_string_lossy()).await?; info(directory, &name) } pub fn list(directory: &Path) -> Result, ServerError> { - let mut backups = Vec::new(); - for entry in std::fs::read_dir(directory)? { - let name = entry?.file_name().to_string_lossy().into_owned(); - if created_secs(&name).is_some() { - backups.push(info(directory, &name)?); - } - } + let mut backups: Vec = std::fs::read_dir(directory)? + .filter_map(|entry| { + let name = entry.ok()?.file_name().to_string_lossy().into_owned(); + info(directory, &name).ok() + }) + .collect(); backups.sort_by_key(|backup| std::cmp::Reverse(backup.created_ms)); Ok(backups) diff --git a/crates/server/src/call/admin.rs b/crates/server/src/call/admin.rs index bcb6b67..eee898b 100644 --- a/crates/server/src/call/admin.rs +++ b/crates/server/src/call/admin.rs @@ -1,19 +1,22 @@ +use std::cmp::Reverse; + use common::{ call::{ BanUser, ClearProfile, CreateBackup, CreateInviteCode, CreateUser, DeleteAttachment, DeleteBackup, DeleteInviteCode, DeleteUser, GetDailyStats, GetOverview, GetStorageUsage, ListAdminLogs, ListAllCommunities, ListAttachments, ListBackups, ListInviteCodes, - ListServerBans, ListUsers, Logout, PurgeUser, RemoveServerBan, RenameUser, ResetPassword, - RestartServer, RevokeSessions, SearchCommunity, SearchMessages, SetCommunityVoice, - SetGhost, StorageUsage, SuspendUser, TimeoutUser, TransferOwnership, UpdateServerSettings, - WatchCommunity, + ListServerBans, ListUserFriends, ListUsers, Logout, PurgeUser, RemoveServerBan, RenameUser, + ResetPassword, RestartServer, RevokeSessions, SearchCommunity, SearchMessages, + SetCommunityVoice, SetGhost, StorageUsage, SuspendUser, TimeoutUser, TransferOwnership, + UpdateServerSettings, WatchCommunity, }, + constant::LOG_PAGE_LIMIT, error::Error, event::Event, model::{ - Account, AdminAction, AdminLogEntry, AttachmentInfo, BackupInfo, BanScope, Community, - CommunitySummary, DayStat, InviteCode, LogAction, MessageHit, Overview, Rank, ServerBan, - ServerBanKind, ServerSettings, User, + Account, AdminAction, AdminActionKind, AdminLogEntry, AttachmentInfo, BackupInfo, BanScope, + Community, CommunitySummary, DayStat, InviteCode, LogAction, MessageHit, Overview, Rank, + ServerBan, ServerBanKind, ServerSettings, User, }, permission, time::{self, MINUTE_MILLIS}, @@ -21,21 +24,22 @@ use common::{ }; use crate::{ - authentication::{self, Revoke}, - backup, + authentication, backup, + call::shared::{ + allowed, call_ended, delete_community, departed_all, ensure_editable, is_outsider, managed, + message_event, messages_deleted, record_ghost_voice, shares_ended, voice_joined, + }, call::user::user_updated, - call::{Cx, Handle, Me}, + call::{Cx, Handle}, db::{ - attachment, avatar, community, log, member, message, registration_code, server_ban, - session, settings, stats, user, + attachment, + avatar::{self, Owner}, + community, direct, friend, log, member, message, registration_code, server_ban, session, + settings, stats, user, }, error::{ServerError, ensure}, - publish::{Broadcast, To}, - request::{ - allowed, call_ended, delete_community, ensure_editable, is_outsider, leave_room_voice, - leave_user_voice, managed, message_event, messages_deleted, record_ghost_voice, - shares_ended, voice_joined, - }, + publish::To, + rooms::Left, }; const CODE_ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; @@ -51,18 +55,16 @@ fn generate_code() -> Result { } impl Handle for Logout { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - me.user()?; + async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { let signed = cx.client.me.as_ref().ok_or(Error::Unauthenticated)?; - authentication::logout(signed.session_id, cx.db).await?; + session::delete(signed.session_id, cx.db).await?; Ok(()) } } impl Handle for UpdateServerSettings { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result { let settings = self.settings; settings::update(&settings, cx.db).await?; log::record_admin( @@ -87,10 +89,9 @@ impl Handle for UpdateServerSettings { } impl Handle for RenameUser { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result { let target = managed(&me, self.user_id, cx.db).await?; - let user = user::update(self.user_id, &self.username, cx.db).await?; + let user = user::rename(self.user_id, &self.username, cx.db).await?; log::record_admin( Some(me.id), Some(self.user_id), @@ -108,8 +109,7 @@ impl Handle for RenameUser { } impl Handle for CreateUser { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result { let user = authentication::create_account(&self.username, &self.password, cx.db).await?; log::record_admin( Some(me.id), @@ -125,15 +125,15 @@ impl Handle for CreateUser { } impl Handle for ListUsers { - async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result, ServerError> { user::all_accounts(cx.db).await } } impl Handle for ListAdminLogs { - async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { - let mut entries = match self.action { - Some(common::model::AdminActionKind::Community) => Vec::new(), + async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result, ServerError> { + let admin = match self.action { + Some(AdminActionKind::Community) => Vec::new(), action => { log::list_admin( self.actor_id, @@ -146,11 +146,8 @@ impl Handle for ListAdminLogs { .await? } }; - if matches!( - self.action, - None | Some(common::model::AdminActionKind::Community) - ) { - entries.extend( + let communities = match self.action { + None | Some(AdminActionKind::Community) => { log::list_communities( self.actor_id, self.target_id, @@ -158,29 +155,33 @@ impl Handle for ListAdminLogs { self.before_ms, cx.db, ) - .await?, - ); - } - entries.sort_by_key(|entry| std::cmp::Reverse(entry.created_at)); - entries.truncate(common::constant::LOG_PAGE_LIMIT as usize); + .await? + } + Some(_) => Vec::new(), + }; + let mut entries = admin; + entries.extend(communities); + entries.sort_by_key(|entry| Reverse(entry.created_at)); + entries.truncate(LOG_PAGE_LIMIT as usize); + Ok(entries) } } -impl Handle for common::call::ListUserFriends { - async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { - Ok(crate::db::friend::state(self.user_id, cx.db).await?.friends) +impl Handle for ListUserFriends { + async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result, ServerError> { + Ok(friend::state(self.user_id, cx.db).await?.friends) } } impl Handle for GetDailyStats { - async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result, ServerError> { stats::daily(self.days, cx.db).await } } impl Handle for GetOverview { - async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result { + async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result { let (users, builders, communities, storage_bytes) = stats::counts(cx.db).await?; Ok(Overview { @@ -195,8 +196,7 @@ impl Handle for GetOverview { } impl Handle for SuspendUser { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { managed(&me, self.user_id, cx.db).await?; user::set_suspended(self.user_id, self.suspended, cx.db).await?; let action = if self.suspended { @@ -206,7 +206,7 @@ impl Handle for SuspendUser { }; log::record_admin(Some(me.id), Some(self.user_id), None, &action, cx.db).await?; if self.suspended { - authentication::revoke(&cx.sh.services.hub, Revoke::User(self.user_id), cx.db).await?; + authentication::revoke_user(&cx.sh.services.hub, self.user_id, cx.db).await?; } Ok(()) @@ -214,10 +214,9 @@ impl Handle for SuspendUser { } impl Handle for RevokeSessions { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { managed(&me, self.user_id, cx.db).await?; - authentication::revoke(&cx.sh.services.hub, Revoke::User(self.user_id), cx.db).await?; + authentication::revoke_user(&cx.sh.services.hub, self.user_id, cx.db).await?; log::record_admin( Some(me.id), Some(self.user_id), @@ -232,11 +231,10 @@ impl Handle for RevokeSessions { } impl Handle for ResetPassword { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { managed(&me, self.user_id, cx.db).await?; authentication::reset_password(self.user_id, &self.password, cx.db).await?; - authentication::revoke(&cx.sh.services.hub, Revoke::User(self.user_id), cx.db).await?; + authentication::revoke_user(&cx.sh.services.hub, self.user_id, cx.db).await?; log::record_admin( Some(me.id), Some(self.user_id), @@ -251,11 +249,10 @@ impl Handle for ResetPassword { } impl Handle for ClearProfile { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result { managed(&me, self.user_id, cx.db).await?; - avatar::set_user(self.user_id, None, cx.db).await?; - let user = user::update_status(self.user_id, "", cx.db).await?; + avatar::set(Owner::User(self.user_id), None, cx.db).await?; + let user = user::set_status(self.user_id, "", cx.db).await?; log::record_admin( Some(me.id), Some(self.user_id), @@ -271,8 +268,7 @@ impl Handle for ClearProfile { } impl Handle for DeleteUser { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { let user_id = self.user_id; let target = user::read(user_id, cx.db).await?; ensure(permission::can_delete_user( @@ -290,18 +286,19 @@ impl Handle for DeleteUser { ) .await?; } - let departed = leave_user_voice(&cx.sh.services.rooms, user_id, cx.db).await?; - cx.out.extend(departed); + cx.out + .extend(departed_all(cx.sh.services.rooms.leave_user(user_id), cx.db).await?); for community_id in member::owned(user_id, cx.db).await? { delete_community(community_id, cx).await?; } + for community_id in direct::communities_of(user_id, cx.db).await? { + let member_ids = member::member_ids(community_id, cx.db).await?; + delete_community(community_id, cx).await?; + cx.emit(To::Users(member_ids), Event::UserDeleted { user_id }); + } for community in community::communities_of(user_id, cx.db).await? { let member_ids = member::member_ids(community.id, cx.db).await?; - if community.kind.is_direct() { - delete_community(community.id, cx).await?; - } - let event = Event::UserDeleted { user_id }; - cx.out.push(Broadcast::new(To::Users(member_ids), event)); + cx.emit(To::Users(member_ids), Event::UserDeleted { user_id }); } user::delete(user_id, cx.db).await?; if me.id != user_id { @@ -313,13 +310,12 @@ impl Handle for DeleteUser { } impl Handle for WatchCommunity { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { let Some(community_id) = self.community_id else { cx.client.watch(None); return Ok(()); }; - allowed(&me, community_id, cx.db, permission::can_read).await?; + allowed(&me, community_id, cx.db, permission::is_member).await?; let outsider = is_outsider(me.id, community_id, cx.db).await?; cx.client.watch(outsider.then_some(community_id)); let visit = @@ -341,7 +337,7 @@ impl Handle for WatchCommunity { } impl Handle for ListAllCommunities { - async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result, ServerError> { let mut summaries = Vec::new(); for community in community::groups(cx.db).await? { let members = member::members(community.id, cx.db).await?; @@ -361,14 +357,13 @@ impl Handle for ListAllCommunities { } impl Handle for TransferOwnership { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { let Self { community_id, user_id, } = self; ensure_editable(community_id, cx.db).await?; - allowed(&me, community_id, cx.db, permission::can_transfer_ownership).await?; + allowed(&me, community_id, cx.db, permission::is_owner).await?; let members = member::members(community_id, cx.db).await?; let target = members .iter() @@ -424,14 +419,13 @@ impl Handle for TransferOwnership { } impl Handle for TimeoutUser { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { let Self { user_id, minutes } = self; managed(&me, user_id, cx.db).await?; let until = (minutes > 0).then(|| time::now_ms() + u64::from(minutes) * MINUTE_MILLIS); user::set_timeout(user_id, until, cx.db).await?; if until.is_some() { - authentication::revoke(&cx.sh.services.hub, Revoke::User(user_id), cx.db).await?; + authentication::revoke_user(&cx.sh.services.hub, user_id, cx.db).await?; } log::record_admin( Some(me.id), @@ -447,8 +441,7 @@ impl Handle for TimeoutUser { } impl Handle for BanUser { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { let Self { user_id, reason, @@ -484,14 +477,13 @@ impl Handle for BanUser { } impl Handle for ListServerBans { - async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result, ServerError> { server_ban::list(cx.db).await } } impl Handle for RemoveServerBan { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { server_ban::remove(self.id, cx.db).await?; log::record_admin(Some(me.id), None, None, &AdminAction::BanRemoved, cx.db).await?; @@ -500,9 +492,7 @@ impl Handle for RemoveServerBan { } impl Handle for CreateInviteCode { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { - let me = me.user()?; - ensure(permission::is_builder(me.role) && self.uses > 0)?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result { let code = registration_code::create(&generate_code()?, self.uses, self.hours, cx.db).await?; log::record_admin(Some(me.id), None, None, &AdminAction::InviteCreated, cx.db).await?; @@ -512,14 +502,13 @@ impl Handle for CreateInviteCode { } impl Handle for ListInviteCodes { - async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result, ServerError> { registration_code::list(cx.db).await } } impl Handle for DeleteInviteCode { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { registration_code::delete(&self.code, cx.db).await?; log::record_admin(Some(me.id), None, None, &AdminAction::InviteDeleted, cx.db).await?; @@ -528,7 +517,7 @@ impl Handle for DeleteInviteCode { } impl Handle for SearchMessages { - async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result, ServerError> { message::search( self.text.as_deref(), self.user_id, @@ -542,9 +531,8 @@ impl Handle for SearchMessages { } impl Handle for SearchCommunity { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { - let me = me.user()?; - allowed(&me, self.community_id, cx.db, permission::can_read).await?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result, ServerError> { + allowed(&me, self.community_id, cx.db, permission::is_member).await?; message::search( Some(&self.text), @@ -559,8 +547,7 @@ impl Handle for SearchCommunity { } impl Handle for PurgeUser { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { let user_id = self.user_id; managed(&me, user_id, cx.db).await?; let deleted = message::delete_where_user(user_id, cx.db).await?; @@ -582,17 +569,16 @@ impl Handle for PurgeUser { } impl Handle for ListAttachments { - async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { - attachment::all(self.user_id, self.community_id, cx.db).await + async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result, ServerError> { + attachment::list(self.user_id, self.community_id, cx.db).await } } impl Handle for DeleteAttachment { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { let stored = attachment::read(self.attachment_id, cx.db).await?; let community = community::label(stored.community_id, cx.db).await?; - attachment::delete(self.attachment_id, cx.db).await?; + let mut message_ids = attachment::delete_file(self.attachment_id, cx.db).await?; log::record_admin( Some(me.id), Some(stored.uploader_id), @@ -601,7 +587,9 @@ impl Handle for DeleteAttachment { cx.db, ) .await?; - if let Some(message_id) = stored.message_id { + message_ids.sort_unstable(); + message_ids.dedup(); + for message_id in message_ids { let updated = message::read(message_id, cx.db).await?; cx.out.push(message_event(&updated, Event::MessageUpdated)); } @@ -611,7 +599,7 @@ impl Handle for DeleteAttachment { } impl Handle for GetStorageUsage { - async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result { + async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result { let (users, communities) = attachment::usage(cx.db).await?; Ok(StorageUsage { users, communities }) @@ -619,8 +607,7 @@ impl Handle for GetStorageUsage { } impl Handle for CreateBackup { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result { let backup = backup::create(&cx.sh.db, &cx.sh.backups).await?; let action = AdminAction::BackupCreated { name: backup.name.clone(), @@ -632,14 +619,13 @@ impl Handle for CreateBackup { } impl Handle for ListBackups { - async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result, ServerError> { backup::list(&cx.sh.backups) } } impl Handle for DeleteBackup { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { backup::delete(&self.name, &cx.sh.backups)?; let action = AdminAction::BackupDeleted { name: self.name }; log::record_admin(Some(me.id), None, None, &action, cx.db).await?; @@ -649,13 +635,12 @@ impl Handle for DeleteBackup { } impl Handle for SetCommunityVoice { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result { let Self { community_id, enabled, } = self; - allowed(&me, community_id, cx.db, permission::can_manage_voice).await?; + allowed(&me, community_id, cx.db, permission::is_owner).await?; community::set_voice_enabled(community_id, enabled, cx.db).await?; let updated = community::read(community_id, me.id, cx.db).await?; if permission::is_builder(me.role) { @@ -672,8 +657,9 @@ impl Handle for SetCommunityVoice { let rooms = &cx.sh.services.rooms; for user_id in rooms.room_users(community_id) { if !permission::is_builder(user::read(user_id, cx.db).await?.role) { - cx.out - .extend(leave_room_voice(rooms, community_id, user_id, cx.db).await?); + cx.out.extend( + departed_all(rooms.leave_room(community_id, user_id), cx.db).await?, + ); } } } @@ -687,8 +673,7 @@ impl Handle for SetCommunityVoice { } impl Handle for RestartServer { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { tracing::info!("restart requested by {}", me.username); cx.sh.services.restart_soon(); Ok(()) @@ -696,8 +681,7 @@ impl Handle for RestartServer { } impl Handle for SetGhost { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { let enabled = self.enabled; let rooms = &cx.sh.services.rooms; user::set_ghost(me.id, enabled, cx.db).await?; @@ -707,7 +691,6 @@ impl Handle for SetGhost { AdminAction::GhostDisabled }; log::record_admin(Some(me.id), None, None, &action, cx.db).await?; - let mut broadcasts = Vec::new(); let outsider = match rooms.room_of(me.id) { Some(community_id) => is_outsider(me.id, community_id, cx.db).await?, None => false, @@ -715,26 +698,26 @@ impl Handle for SetGhost { if !outsider && let Some(mut departure) = rooms.set_ghost(me.id, enabled) { let community_id = departure.community_id; if enabled { - broadcasts.extend(shares_ended(&mut departure)); - broadcasts - .extend(call_ended(community_id, me.id, departure.call_log, cx.db).await?); - let event = Event::VoiceLeft { - community_id, - user_id: me.id, - }; - broadcasts.push(Broadcast::new( + cx.out.extend(shares_ended(&mut departure)); + if let Left::Seated { call_log } = departure.left { + cx.out + .extend(call_ended(community_id, me.id, call_log, cx.db).await?); + } + cx.emit( To::CommunityExcept(community_id, me.id), - event, - )); + Event::VoiceLeft { + community_id, + user_id: me.id, + }, + ); } else { let muted = user::voice_muted(me.id, cx.db).await?; - broadcasts.extend(voice_joined(community_id, me.id, muted)); - if let Some(seconds) = departure.ghost_seconds { + cx.out.extend(voice_joined(community_id, me.id, muted)); + if let Left::Ghost { seconds } = departure.left { record_ghost_voice(me.id, community_id, seconds, cx.db).await?; } } } - cx.out.extend(broadcasts); Ok(()) } diff --git a/crates/server/src/call/community.rs b/crates/server/src/call/community.rs index 1c5e66c..76290ba 100644 --- a/crates/server/src/call/community.rs +++ b/crates/server/src/call/community.rs @@ -12,12 +12,12 @@ use common::{ }; use crate::{ - call::{Cx, Handle, Me}, - db::{self, community::Kind}, + call::shared::{actor_rank, allowed, delete_community, departed_all, ensure_editable}, + call::{Cx, Handle}, + db::{self, avatar::Owner, community::Kind}, error::{ServerError, ensure, ensure_with}, files, publish::To, - request::{actor_rank, allowed, delete_community, ensure_editable, leave_room_voice}, }; async fn remove_member( @@ -53,7 +53,7 @@ async fn remove_member( }; db::log::record(community_id, Some(me.id), Some(user_id), &action, db).await?; cx.out - .extend(leave_room_voice(&cx.sh.services.rooms, community_id, user_id, db).await?); + .extend(departed_all(cx.sh.services.rooms.leave_room(community_id, user_id), db).await?); cx.emit( To::User(user_id), Event::Removed { @@ -75,8 +75,7 @@ async fn remove_member( } impl Handle for CreateCommunity { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result { let db = cx.db; let limit = db::settings::read(db).await?.max_communities_per_user; let owned = db::member::owned_groups(me.id, db).await?; @@ -90,20 +89,18 @@ impl Handle for CreateCommunity { } impl Handle for GetCommunity { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { - let me = me.user()?; - allowed(&me, self.community_id, cx.db, permission::can_read).await?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result { + allowed(&me, self.community_id, cx.db, permission::is_member).await?; db::community::read(self.community_id, me.id, cx.db).await } } impl Handle for UpdateCommunity { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result { let db = cx.db; ensure_editable(self.community_id, db).await?; - allowed(&me, self.community_id, db, permission::can_rename_community).await?; + allowed(&me, self.community_id, db, permission::is_admin).await?; let updated = db::community::update(self.community_id, &self.name, me.id, db).await?; let action = LogAction::Renamed { name: updated.name.clone(), @@ -119,16 +116,20 @@ impl Handle for UpdateCommunity { } impl Handle for UpdateCommunityAvatar { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result { let db = cx.db; ensure_editable(self.community_id, db).await?; - allowed(&me, self.community_id, db, permission::can_rename_community).await?; + allowed(&me, self.community_id, db, permission::is_admin).await?; if let Some(bytes) = &self.image { validate_avatar_size(bytes, db::settings::read(db).await?.max_avatar_bytes)?; files::check_avatar(bytes)?; } - db::avatar::set_community(self.community_id, self.image.as_deref(), db).await?; + db::avatar::set( + Owner::Community(self.community_id), + self.image.as_deref(), + db, + ) + .await?; let updated = db::community::read(self.community_id, me.id, db).await?; let action = if self.image.is_some() { LogAction::AvatarChanged @@ -146,11 +147,10 @@ impl Handle for UpdateCommunityAvatar { } impl Handle for DeleteCommunity { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { let db = cx.db; ensure_editable(self.community_id, db).await?; - allowed(&me, self.community_id, db, permission::can_delete_community).await?; + allowed(&me, self.community_id, db, permission::is_owner).await?; let owned = db::member::rank(me.id, self.community_id, db).await? == Some(Rank::Owner); let deleted = db::community::read(self.community_id, me.id, db).await?; if permission::is_builder(me.role) && !owned { @@ -170,8 +170,7 @@ impl Handle for DeleteCommunity { } impl Handle for LeaveCommunity { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { let db = cx.db; ensure_editable(self.community_id, db).await?; let rank = db::member::rank(me.id, self.community_id, db).await?; @@ -179,16 +178,13 @@ impl Handle for LeaveCommunity { let left = db::member::leave(me.id, self.community_id, db).await?; ensure_with(left == 1, Error::NotFound)?; db::log::record(self.community_id, Some(me.id), None, &LogAction::Left, db).await?; - if db::member::member_ids(self.community_id, db) - .await? - .is_empty() - { - delete_community(self.community_id, cx).await?; - } else { - let broadcasts = - leave_room_voice(&cx.sh.services.rooms, self.community_id, me.id, db).await?; - cx.out.extend(broadcasts); - } + cx.out.extend( + departed_all( + cx.sh.services.rooms.leave_room(self.community_id, me.id), + db, + ) + .await?, + ); cx.emit( To::Community(self.community_id), Event::MemberLeft { @@ -202,25 +198,21 @@ impl Handle for LeaveCommunity { } impl Handle for ListCommunities { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { - let me = me.user()?; - + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result, ServerError> { db::community::communities_of(me.id, cx.db).await } } impl Handle for ListMembers { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { - let me = me.user()?; - allowed(&me, self.community_id, cx.db, permission::can_read).await?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result, ServerError> { + allowed(&me, self.community_id, cx.db, permission::is_member).await?; db::member::members(self.community_id, cx.db).await } } impl Handle for Kick { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { remove_member( &me, self.community_id, @@ -234,8 +226,7 @@ impl Handle for Kick { } impl Handle for BanMember { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { remove_member( &me, self.community_id, @@ -249,10 +240,9 @@ impl Handle for BanMember { } impl Handle for Unban { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { let db = cx.db; - allowed(&me, self.community_id, db, permission::can_unban).await?; + allowed(&me, self.community_id, db, permission::is_moderator).await?; db::member::unban(self.user_id, self.community_id, db).await?; db::log::record( self.community_id, @@ -268,17 +258,15 @@ impl Handle for Unban { } impl Handle for ListBans { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { - let me = me.user()?; - allowed(&me, self.community_id, cx.db, permission::can_unban).await?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result, ServerError> { + allowed(&me, self.community_id, cx.db, permission::is_moderator).await?; db::member::bans(self.community_id, cx.db).await } } impl Handle for SetRank { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { let db = cx.db; ensure_editable(self.community_id, db).await?; let target = db::user::read(self.user_id, db).await?; @@ -310,9 +298,8 @@ impl Handle for SetRank { } impl Handle for ListLogs { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { - let me = me.user()?; - allowed(&me, self.community_id, cx.db, permission::can_read_logs).await?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result, ServerError> { + allowed(&me, self.community_id, cx.db, permission::is_moderator).await?; db::log::list(self.community_id, cx.db).await } diff --git a/crates/server/src/call/message.rs b/crates/server/src/call/message.rs index 92596de..0555679 100644 --- a/crates/server/src/call/message.rs +++ b/crates/server/src/call/message.rs @@ -4,6 +4,7 @@ use common::{ ListMessages, ListPins, ListUnreads, MarkRead, MyVotes, Pin, React, Typing, UpdateMessage, Vote, }, + constant::MAXIMUM_FORWARD_MESSAGES, error::Error, event::Event, model::{AdminAction, Edit, Id, LogAction, Message, ServerSettings, Unread, User}, @@ -12,11 +13,11 @@ use common::{ }; use crate::{ - call::{Cx, Handle, Me}, - db::{self, community::Kind, message::ForwardMode}, + call::shared::{actor_rank, allowed, is_outsider, message_event}, + call::{Cx, Handle}, + db::{self, community::Kind}, error::{ServerError, ensure, ensure_with}, publish::To, - request::{actor_rank, allowed, is_outsider, message_event}, }; fn limit_messages(me: &User, settings: &ServerSettings, cx: &Cx<'_>) -> Result<(), ServerError> { @@ -31,6 +32,13 @@ fn limit_messages(me: &User, settings: &ServerSettings, cx: &Cx<'_>) -> Result<( .allow(&me.id.to_string(), settings.messages_per_minute)?) } +async fn readable(me: &User, message_id: Id, cx: &Cx<'_>) -> Result { + let message = db::message::read(message_id, cx.db).await?; + allowed(me, message.community_id, cx.db, permission::is_member).await?; + + Ok(message) +} + fn redact_replies(messages: &mut [Message], me: &User) { if permission::is_builder(me.role) { return; @@ -44,8 +52,7 @@ fn redact_replies(messages: &mut [Message], me: &User) { } impl Handle for CreateMessage { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result { let settings = db::settings::read(cx.db).await?; limit_messages(&me, &settings, cx)?; validate_new_message( @@ -53,7 +60,7 @@ impl Handle for CreateMessage { self.attachments.len(), settings.max_message_length as usize, )?; - allowed(&me, self.community_id, cx.db, permission::can_post).await?; + allowed(&me, self.community_id, cx.db, permission::is_member).await?; if let Some(reply_to) = self.reply_to { ensure_with( db::message::community_of(reply_to, cx.db).await? == self.community_id, @@ -77,26 +84,22 @@ impl Handle for CreateMessage { } impl Handle for ForwardMessages { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result, ServerError> { limit_messages(&me, &db::settings::read(cx.db).await?, cx)?; - ensure(permission::can_post( - actor_rank(&me, self.community_id, cx.db).await?, - ))?; + ensure(self.message_ids.len() <= MAXIMUM_FORWARD_MESSAGES)?; + allowed(&me, self.community_id, cx.db, permission::is_member).await?; let mut sources = Vec::new(); for message_id in &self.message_ids { - let source = db::message::read(*message_id, cx.db).await?; - ensure(permission::can_read( - actor_rank(&me, source.community_id, cx.db).await?, - ))?; + let source = readable(&me, *message_id, cx).await?; + ensure(source.call.is_none())?; sources.push(source); } - let mode = if self.snippet { - ForwardMode::Snippet + let snippet = self.snippet || sources.iter().any(|source| source.poll.is_some()); + let created = if snippet { + db::message::forward_snippet(me.id, self.community_id, &sources, cx.db).await? } else { - ForwardMode::Copy + db::message::forward_copies(me.id, self.community_id, &sources, cx.db).await? }; - let created = db::message::forward(me.id, self.community_id, &sources, mode, cx.db).await?; for message in &created { cx.out.push(message_event(message, Event::MessageCreated)); } @@ -106,14 +109,13 @@ impl Handle for ForwardMessages { } impl Handle for UpdateMessage { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result { let existing = db::message::read(self.message_id, cx.db).await?; - allowed(&me, existing.community_id, cx.db, permission::can_post).await?; + allowed(&me, existing.community_id, cx.db, permission::is_member).await?; ensure(existing.user_id == me.id)?; validate_new_message( &self.body, - 0, + existing.attachments.len(), db::settings::read(cx.db).await?.max_message_length as usize, )?; let updated = db::message::update(self.message_id, &self.body, cx.db).await?; @@ -124,8 +126,7 @@ impl Handle for UpdateMessage { } impl Handle for DeleteMessage { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { let existing = db::message::read(self.message_id, cx.db).await?; let author = db::user::read(existing.user_id, cx.db).await?; ensure(permission::can_delete_message( @@ -168,11 +169,10 @@ impl Handle for DeleteMessage { } impl Handle for CreatePoll { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result { let settings = db::settings::read(cx.db).await?; limit_messages(&me, &settings, cx)?; - allowed(&me, self.community_id, cx.db, permission::can_post).await?; + allowed(&me, self.community_id, cx.db, permission::is_member).await?; let created = db::message::create_poll(me.id, &self, cx.db).await?; db::stats::mark_active(me.id, cx.db).await?; cx.out.push(message_event(&created, Event::MessageCreated)); @@ -182,12 +182,8 @@ impl Handle for CreatePoll { } impl Handle for Vote { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; - let existing = db::message::read(self.message_id, cx.db).await?; - ensure(permission::can_read( - actor_rank(&me, existing.community_id, cx.db).await?, - ))?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let existing = readable(&me, self.message_id, cx).await?; let poll = existing.poll.as_ref().ok_or(Error::NotFound)?; validate_vote(poll, &self.positions)?; let updated = db::message::vote(self.message_id, me.id, &self.positions, cx.db).await?; @@ -205,19 +201,14 @@ impl Handle for Vote { } impl Handle for MyVotes { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { - let me = me.user()?; - let existing = db::message::read(self.message_id, cx.db).await?; - ensure(permission::can_read( - actor_rank(&me, existing.community_id, cx.db).await?, - ))?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result, ServerError> { + readable(&me, self.message_id, cx).await?; db::poll::my_votes(self.message_id, me.id, cx.db).await } } impl Handle for ClosePoll { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { let existing = db::message::read(self.message_id, cx.db).await?; ensure(permission::can_close_poll( actor_rank(&me, existing.community_id, cx.db).await?, @@ -231,12 +222,8 @@ impl Handle for ClosePoll { } impl Handle for React { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; - let existing = db::message::read(self.message_id, cx.db).await?; - ensure(permission::can_read( - actor_rank(&me, existing.community_id, cx.db).await?, - ))?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { + readable(&me, self.message_id, cx).await?; let updated = db::message::react(self.message_id, me.id, &self.emoji, cx.db).await?; cx.out.push(message_event(&updated, Event::MessageUpdated)); @@ -245,8 +232,7 @@ impl Handle for React { } impl Handle for Pin { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { let existing = db::message::read(self.message_id, cx.db).await?; let direct = db::community::kind_of(existing.community_id, cx.db).await? == Some(Kind::Direct); @@ -262,9 +248,8 @@ impl Handle for Pin { } impl Handle for ListPins { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { - let me = me.user()?; - allowed(&me, self.community_id, cx.db, permission::can_read).await?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result, ServerError> { + allowed(&me, self.community_id, cx.db, permission::is_member).await?; let mut pins = db::message::pinned(self.community_id, cx.db).await?; redact_replies(&mut pins, &me); @@ -274,9 +259,8 @@ impl Handle for ListPins { } impl Handle for ListMessages { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { - let me = me.user()?; - allowed(&me, self.community_id, cx.db, permission::can_read).await?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result, ServerError> { + allowed(&me, self.community_id, cx.db, permission::is_member).await?; let builder = permission::is_builder(me.role); let mut messages = @@ -288,25 +272,19 @@ impl Handle for ListMessages { } impl Handle for ListEdits { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { - let me = me.user()?; - ensure(permission::is_builder(me.role))?; - + async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result, ServerError> { db::message::edits(self.message_id, cx.db).await } } impl Handle for ListUnreads { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { - let me = me.user()?; - + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result, ServerError> { db::member::unreads(me.id, &me.username, cx.db).await } } impl Handle for MarkRead { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { ensure(!is_outsider(me.id, self.community_id, cx.db).await?)?; ensure_with( db::message::community_of(self.message_id, cx.db).await? == self.community_id, @@ -319,9 +297,8 @@ impl Handle for MarkRead { } impl Handle for Typing { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; - allowed(&me, self.community_id, cx.db, permission::can_read).await?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { + allowed(&me, self.community_id, cx.db, permission::is_member).await?; if db::user::is_ghost(me.id, cx.db).await? { return Ok(()); } diff --git a/crates/server/src/call/mod.rs b/crates/server/src/call/mod.rs index 33347df..2b9ee92 100644 --- a/crates/server/src/call/mod.rs +++ b/crates/server/src/call/mod.rs @@ -2,6 +2,7 @@ mod admin; mod community; mod message; mod release; +pub(crate) mod shared; mod social; mod stats; mod user; @@ -10,7 +11,7 @@ mod voice; use std::{future::Future, sync::Arc}; use common::{ - call::{Call, Gate, Login, Register, Request}, + call::{Call, Gate, GetSettings, Login, Register, Request}, error::Error, event::Event, frame::{self, DOWN_MAX}, @@ -24,9 +25,10 @@ use crate::{ hub::Client, network::Shared, publish::{Broadcast, To}, - request, }; +use shared::authenticated; + pub(crate) struct Cx<'a> { pub client: &'a Arc, pub sh: &'a Shared, @@ -49,49 +51,38 @@ impl<'a> Cx<'a> { } } -pub(crate) enum Me { - Guest, - User(User), -} - -impl Me { - pub fn user(self) -> Result { - match self { - Me::User(user) => Ok(user), - Me::Guest => Err(Error::Unauthenticated.into()), - } - } -} - pub(crate) trait Handle: Call { fn handle( self, - me: Me, + me: User, cx: &mut Cx<'_>, ) -> impl Future> + Send; } -async fn gate(gate: Gate, cx: &Cx<'_>) -> Result { +async fn gate(gate: Gate, cx: &Cx<'_>) -> Result { + let user = authenticated(cx.client, cx.db).await?; match gate { - Gate::Guest => Ok(Me::Guest), - Gate::User => Ok(Me::User(request::authenticated(cx.client, cx.db).await?)), + Gate::Guest => Err(Error::Server.into()), + Gate::User => Ok(user), Gate::Builder => { - let user = request::authenticated(cx.client, cx.db).await?; ensure(permission::is_builder(user.role))?; - - Ok(Me::User(user)) + Ok(user) } } } async fn serve(call: C, cx: &mut Cx<'_>) -> Vec { let db = cx.db; - let reply = db::atomic(db, async { - call.validate()?; - let me = gate(C::GATE, cx).await?; - call.handle(me, cx).await - }) - .await; + let reply = match call.validate() { + Ok(()) => { + db::atomic(db, async { + let me = gate(C::GATE, cx).await?; + call.handle(me, cx).await + }) + .await + } + Err(error) => Err(error.into()), + }; if reply.is_err() { cx.out.clear(); } @@ -108,7 +99,7 @@ pub(crate) fn encode(reply: Result) -> Vec { pub(crate) async fn dispatch(request: Request, cx: &mut Cx<'_>) -> Vec { match request { - Request::GetSettings(call) => serve(call, cx).await, + Request::GetSettings(_) => encode::(db::settings::read(cx.db).await), Request::GetUser(call) => serve(call, cx).await, Request::UpdateUser(call) => serve(call, cx).await, Request::UpdateStatus(call) => serve(call, cx).await, @@ -229,3 +220,327 @@ pub(crate) async fn dispatch(request: Request, cx: &mut Cx<'_>) -> Vec { Request::SetReleaseRequired(call) => serve(call, cx).await, } } + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use common::{ + call::{ + AcceptFriend, AcceptInvitation, AddFriend, CreateCommunity, CreateMessage, + DeleteCommunity, FindUser, Invite, Kick, LeaveCommunity, ListCommunities, ListFriends, + UpdateCommunity, + }, + error::Error as CommonError, + model::{Id, Role}, + }; + + use crate::{ + authentication::token_hash, + call::{Cx, Handle, shared::authenticated}, + db::{self, Db}, + hub::{Client, Signed}, + network::{Services, Shared}, + test, + }; + + fn shared(db: &Db, services: &Services) -> Shared { + Shared { + db: db.clone(), + services: services.clone(), + attachments: test::directory(), + backups: test::directory(), + releases: Default::default(), + } + } + + async fn call( + call: C, + client: &Arc, + db: &Db, + services: &Services, + ) -> Result { + let shared = shared(db, services); + let conn = db.lock().await.unwrap(); + let me = authenticated(client, &conn).await?; + let mut cx = Cx::new(client, &shared, &conn); + + Ok(call.handle(me, &mut cx).await?) + } + + async fn signed_in(username: &str, db: &Db) -> Arc { + signed_in_as(username, Role::User, db).await + } + + async fn signed_in_as(username: &str, role: Role, db: &Db) -> Arc { + let conn = db.lock().await.unwrap(); + let user = db::user::create(username, "hash", role, &conn) + .await + .unwrap(); + let session_id = db::session::insert(&token_hash(username), user.id, &conn) + .await + .unwrap(); + + Client::detached(Some(Signed { + user_id: user.id, + session_id, + })) + } + + async fn invite_and_accept( + community_id: Id, + owner: &Arc, + member: &Arc, + username: &str, + db: &Db, + services: &Services, + ) { + let member_user = call( + FindUser { + username: username.to_string(), + }, + owner, + db, + services, + ) + .await + .unwrap(); + call( + Invite { + community_id, + user_id: member_user.id, + }, + owner, + db, + services, + ) + .await + .unwrap(); + call(AcceptInvitation { community_id }, member, db, services) + .await + .unwrap(); + } + + #[tokio::test] + async fn plain_member_cannot_rename() { + let db = test::db().await; + let services = Services::new(test::directory()); + let owner = signed_in("Owner", &db).await; + let member = signed_in("Member", &db).await; + let community = call( + CreateCommunity { + name: "The Community".to_string(), + }, + &owner, + &db, + &services, + ) + .await + .unwrap(); + invite_and_accept(community.id, &owner, &member, "Member", &db, &services).await; + + let response = call( + UpdateCommunity { + community_id: community.id, + name: "Renamed".to_string(), + }, + &member, + &db, + &services, + ) + .await; + + assert!(matches!(response, Err(CommonError::Forbidden))); + } + + #[tokio::test] + async fn accepted_friend_request_befriends_both() { + let db = test::db().await; + let services = Services::new(test::directory()); + let first = signed_in("First", &db).await; + let second = signed_in("Second", &db).await; + let first_user = call( + FindUser { + username: "First".to_string(), + }, + &second, + &db, + &services, + ) + .await + .unwrap(); + let second_user = call( + FindUser { + username: "Second".to_string(), + }, + &first, + &db, + &services, + ) + .await + .unwrap(); + call( + AddFriend { + user_id: second_user.id, + }, + &first, + &db, + &services, + ) + .await + .unwrap(); + call( + AcceptFriend { + user_id: first_user.id, + }, + &second, + &db, + &services, + ) + .await + .unwrap(); + + let first_friends = call(ListFriends, &first, &db, &services).await.unwrap(); + let second_friends = call(ListFriends, &second, &db, &services).await.unwrap(); + + assert_eq!(vec![second_user], first_friends.friends); + assert_eq!(vec![first_user], second_friends.friends); + } + + #[tokio::test] + async fn invite_and_accept_makes_member() { + let db = test::db().await; + let services = Services::new(test::directory()); + let owner = signed_in("Owner", &db).await; + let member = signed_in("Member", &db).await; + let community = call( + CreateCommunity { + name: "The Community".to_string(), + }, + &owner, + &db, + &services, + ) + .await + .unwrap(); + + invite_and_accept(community.id, &owner, &member, "Member", &db, &services).await; + + let communities = call(ListCommunities, &member, &db, &services) + .await + .unwrap(); + assert_eq!(vec![community], communities); + } + + #[tokio::test] + async fn delete_community_removes_messages() { + let db = test::db().await; + let services = Services::new(test::directory()); + let owner = signed_in("Owner", &db).await; + let community = call( + CreateCommunity { + name: "The Community".to_string(), + }, + &owner, + &db, + &services, + ) + .await + .unwrap(); + call( + CreateMessage { + community_id: community.id, + body: "Tahinli".to_string(), + attachments: Vec::new(), + reply_to: None, + }, + &owner, + &db, + &services, + ) + .await + .unwrap(); + + call( + DeleteCommunity { + community_id: community.id, + }, + &owner, + &db, + &services, + ) + .await + .unwrap(); + + let conn = db.lock().await.unwrap(); + let remaining = db::message::read_page(community.id, None, false, &conn) + .await + .unwrap(); + + assert!(remaining.is_empty()); + } + + async fn group(owner: &Arc, db: &Db, services: &Services) -> Id { + call( + CreateCommunity { + name: "The Community".to_string(), + }, + owner, + db, + services, + ) + .await + .unwrap() + .id + } + + async fn user_id(username: &str, by: &Arc, db: &Db, services: &Services) -> Id { + call( + FindUser { + username: username.to_string(), + }, + by, + db, + services, + ) + .await + .unwrap() + .id + } + + #[tokio::test] + async fn kick_of_non_member_is_not_found() { + let db = test::db().await; + let services = Services::new(test::directory()); + let owner = signed_in("Owner", &db).await; + signed_in("Outsider", &db).await; + let community_id = group(&owner, &db, &services).await; + let outsider = user_id("Outsider", &owner, &db, &services).await; + + let kick = Kick { + community_id, + user_id: outsider, + reason: None, + }; + + assert!(matches!( + call(kick, &owner, &db, &services).await, + Err(CommonError::NotFound) + )); + } + + #[tokio::test] + async fn builder_cannot_leave_owned_group() { + let db = test::db().await; + let services = Services::new(test::directory()); + let builder = signed_in_as("Builder", Role::Builder, &db).await; + let community_id = group(&builder, &db, &services).await; + + let leave = LeaveCommunity { community_id }; + + assert!(matches!( + call(leave, &builder, &db, &services).await, + Err(CommonError::Forbidden) + )); + } +} diff --git a/crates/server/src/call/release.rs b/crates/server/src/call/release.rs index 7d42e1f..af438a4 100644 --- a/crates/server/src/call/release.rs +++ b/crates/server/src/call/release.rs @@ -5,16 +5,17 @@ use common::{ }, error::{Error, ReleaseProblem}, event::Event, - model::{AdminAction, ReleaseFile, ReleaseInfo, UpdateClient}, + model::{AdminAction, ReleaseFile, ReleaseInfo, UpdateClient, User}, transport::PROTOCOL, update::{SERVER_TARGET, Sha}, }; +use tracing::info; -use super::{Cx, Handle, Me}; use crate::{ + call::{Cx, Handle}, db::{self, log}, error::{ServerError, ensure_with}, - publish::To, + publish::{self, Broadcast, To}, }; fn info(entry: db::release::Entry) -> ReleaseInfo { @@ -35,7 +36,7 @@ fn info(entry: db::release::Entry) -> ReleaseInfo { } impl Handle for ListReleases { - async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result, ServerError> { let entries = db::release::entries(cx.db).await?; Ok(entries.into_iter().map(info).collect()) @@ -43,16 +44,14 @@ impl Handle for ListReleases { } impl Handle for ListUpdateClients { - async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result, ServerError> { let online = cx.sh.services.hub.installs(); let mut clients = Vec::new(); for (install, seen) in cx.sh.releases.recent() { if seen.user != Some(self.user_id) { continue; } - let (release, target) = db::release::of_file(&seen.build, cx.db) - .await? - .map_or((None, None), |(seq, target)| (Some(seq), Some(target))); + let (release, target) = db::release::of_file(&seen.build, cx.db).await?.unzip(); clients.push(UpdateClient { device: seen.device, release, @@ -69,10 +68,9 @@ impl Handle for ListUpdateClients { } impl Handle for PublishRelease { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { - let me = me.user()?; - let files = cx.sh.releases.staged(&self.files)?; - if cx.sh.releases.protocol(&self.files)? != PROTOCOL { + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result { + let (files, protocol) = cx.sh.releases.pick(&self.files)?; + if protocol != PROTOCOL { let released = db::release::targets(cx.db).await?; let has = |target: &str| files.iter().any(|file| file.target == target); ensure_with( @@ -80,9 +78,6 @@ impl Handle for PublishRelease { Error::Release(ReleaseProblem::ProtocolSplit), )?; } - let releases = cx.sh.releases.clone(); - let picked = files.clone(); - let next = tokio::task::spawn_blocking(move || releases.prepare_server(&picked)).await??; let before = db::release::live(cx.db).await?; let seq = db::release::insert(self.required, &files, cx.db).await?; let after = db::release::live(cx.db).await?; @@ -93,26 +88,25 @@ impl Handle for PublishRelease { log::record_admin(Some(me.id), None, None, &action, cx.db).await?; let entry = db::release::entry(seq, cx.db).await?; - cx.sh.releases.unstage(&self.files); let stopped: Vec = before .into_iter() .filter(|file| !after.contains(file)) .collect(); cx.sh.releases.discard(&stopped); - cx.emit(To::Everyone, Event::Release); - if let Some(next) = next { - next.swap()?; - tracing::info!("server binary replaced by release {seq}"); + if let Some(server) = files.iter().find(|file| file.target == SERVER_TARGET) { + cx.sh.releases.swap(&server.file)?; + info!("server binary replaced by release {seq}"); cx.sh.services.restart_soon(); } + cx.sh.releases.unstage(&self.files); + cx.emit(To::Everyone, Event::Release); Ok(info(entry)) } } impl Handle for SetReleaseRequired { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { db::release::set_required(self.seq, self.required, cx.db).await?; let action = AdminAction::ReleaseRequired { seq: self.seq, @@ -126,15 +120,14 @@ impl Handle for SetReleaseRequired { } impl Handle for ImportRelease { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { let shared = cx.sh.clone(); tokio::spawn(async move { let result = shared .releases .import(self.tag.clone(), &shared.db) .await - .map_err(|error| match common::error::Error::from(error) { + .map_err(|error| match Error::from(error) { Error::Release(problem) => problem, _ => ReleaseProblem::Forge, }); @@ -142,8 +135,8 @@ impl Handle for ImportRelease { tag: self.tag, result, }; - let _ = crate::publish::job(&shared, async |_| { - Ok(vec![crate::publish::Broadcast::new(To::Builders, event)]) + let _ = publish::job(&shared, async |_| { + Ok(vec![Broadcast::new(To::User(me.id), event)]) }) .await; }); @@ -152,15 +145,13 @@ impl Handle for ImportRelease { } impl Handle for GetForge { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { - me.user()?; + async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result, ServerError> { Ok(cx.sh.releases.forge().map(|forge| forge.repo().to_string())) } } impl Handle for CreateTag { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - me.user()?; + async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { let forge = cx .sh .releases diff --git a/crates/server/src/call/shared.rs b/crates/server/src/call/shared.rs new file mode 100644 index 0000000..30d4211 --- /dev/null +++ b/crates/server/src/call/shared.rs @@ -0,0 +1,311 @@ +use std::collections::BTreeMap; + +use common::{ + error::Error as CommonError, + event::Event, + model::{AdminAction, CallLog, Id, Message, Presence, Rank, User}, + permission, + share::Kind as ShareKind, +}; + +use crate::{ + call::Cx, + db::{self, Connection, community::Kind}, + error::{ServerError, ensure}, + hub::{Client, Hub}, + publish::{Broadcast, To}, + rooms::{Departure, Left, Rooms}, +}; + +pub(crate) async fn effective_presence( + hub: &Hub, + user_id: Id, + db: &Connection, +) -> Result { + if !hub.is_online(user_id) { + return Ok(Presence::Offline); + } + + db::user::presence(user_id, db).await +} + +pub(crate) async fn presence_changed( + hub: &Hub, + user_id: Id, + db: &Connection, +) -> Result, ServerError> { + let presence = effective_presence(hub, user_id, db).await?; + let event = Event::PresenceChanged { user_id, presence }; + + Ok(vec![Broadcast::new(To::Related(user_id), event)]) +} + +pub(crate) async fn introduce( + user_id: Id, + others: &[Id], + cx: &mut Cx<'_>, +) -> Result<(), ServerError> { + let hub = &cx.sh.services.hub; + let presence = effective_presence(hub, user_id, cx.db).await?; + for &other in others { + if other == user_id { + continue; + } + let theirs = effective_presence(hub, other, cx.db).await?; + cx.emit( + To::User(other), + Event::PresenceChanged { user_id, presence }, + ); + cx.emit( + To::User(user_id), + Event::PresenceChanged { + user_id: other, + presence: theirs, + }, + ); + } + + Ok(()) +} + +pub(crate) async fn voice_muted( + community_id: Option, + user_id: Id, + muted: bool, + db: &Connection, +) -> Result { + let mut user_ids = vec![user_id]; + if let Some(community_id) = community_id + && !db::user::is_ghost(user_id, db).await? + { + user_ids.extend(db::member::member_ids(community_id, db).await?); + } + let event = Event::VoiceMuted { + community_id, + user_id, + muted, + }; + + Ok(Broadcast::new(To::Users(user_ids), event)) +} + +pub(crate) async fn voice_closed( + rooms: &Rooms, + community_id: Id, + db: &Connection, +) -> Result, ServerError> { + departed_all(rooms.close_room(community_id), db).await +} + +pub(crate) async fn delete_community(community_id: Id, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let member_ids = db::member::member_ids(community_id, cx.db).await?; + let closed = voice_closed(&cx.sh.services.rooms, community_id, cx.db).await?; + cx.out.extend(closed); + db::community::delete(community_id, cx.db).await?; + cx.emit( + To::Users(member_ids), + Event::CommunityDeleted { community_id }, + ); + + Ok(()) +} + +pub(crate) async fn call_ended( + community_id: Id, + user_id: Id, + call: Option, + db: &Connection, +) -> Result, ServerError> { + let Some(call) = call else { + return Ok(Vec::new()); + }; + if db::community::kind_of(community_id, db).await? != Some(Kind::Direct) { + return Ok(Vec::new()); + } + let created = db::message::create_call_log(community_id, user_id, call, db).await?; + + Ok(vec![message_event(&created, Event::MessageCreated)]) +} + +pub(crate) async fn departed( + mut departure: Departure, + db: &Connection, +) -> Result, ServerError> { + let mut broadcasts = shares_ended(&mut departure); + let Departure { + community_id, + user_id, + left, + .. + } = departure; + let to = match left { + Left::Transferred => return Ok(broadcasts), + Left::Ghost { seconds } => { + record_ghost_voice(user_id, community_id, seconds, db).await?; + To::User(user_id) + } + Left::Seated { call_log } => { + broadcasts.extend(call_ended(community_id, user_id, call_log, db).await?); + To::Community(community_id) + } + }; + broadcasts.push(Broadcast::new( + to, + Event::VoiceLeft { + community_id, + user_id, + }, + )); + + Ok(broadcasts) +} + +pub(crate) async fn departed_all( + departures: impl IntoIterator, + db: &Connection, +) -> Result, ServerError> { + let mut broadcasts = Vec::new(); + for departure in departures { + broadcasts.extend(departed(departure, db).await?); + } + + Ok(broadcasts) +} + +pub(crate) fn share_ended(community_id: Id, user_id: Id, kind: ShareKind) -> Broadcast { + let event = Event::ShareStopped { + community_id, + user_id, + kind, + }; + + Broadcast::new(To::Community(community_id), event) +} + +pub(crate) fn shares_ended(departure: &mut Departure) -> Vec { + let mut broadcasts: Vec = departure + .shares + .iter() + .map(|kind| share_ended(departure.community_id, departure.user_id, *kind)) + .collect(); + broadcasts.append(&mut departure.media); + + broadcasts +} + +pub(crate) fn messages_deleted(rows: Vec<(Id, Id)>) -> Vec { + let mut deleted: BTreeMap> = BTreeMap::new(); + for (community_id, message_id) in rows { + deleted.entry(community_id).or_default().push(message_id); + } + + deleted + .into_iter() + .map(|(community_id, ids)| { + let event = Event::MessagesDeleted { community_id, ids }; + Broadcast::new(To::Community(community_id), event) + }) + .collect() +} + +pub(crate) async fn authenticated(client: &Client, db: &Connection) -> Result { + let me = client.me.as_ref().ok_or(CommonError::Unauthenticated)?; + + Ok(db::session::user_of(me.session_id, db) + .await? + .ok_or(CommonError::Unauthenticated)?) +} + +pub(crate) async fn actor_rank( + me: &User, + community_id: Id, + db: &Connection, +) -> Result, ServerError> { + let rank = db::member::rank(me.id, community_id, db).await?; + + Ok(permission::effective_rank(me.role, rank)) +} + +pub(crate) async fn managed(me: &User, user_id: Id, db: &Connection) -> Result { + let target = db::user::read(user_id, db).await?; + ensure(permission::can_manage_user( + me.role, + me.id == user_id, + target.role, + ))?; + + Ok(target) +} + +pub(crate) async fn allowed( + me: &User, + community_id: Id, + db: &Connection, + check: fn(Option) -> bool, +) -> Result<(), ServerError> { + ensure(check(actor_rank(me, community_id, db).await?)) +} + +pub(crate) async fn is_outsider( + user_id: Id, + community_id: Id, + db: &Connection, +) -> Result { + Ok(db::member::rank(user_id, community_id, db).await?.is_none()) +} + +pub(crate) async fn ensure_editable(community_id: Id, db: &Connection) -> Result<(), ServerError> { + let kind = db::community::kind_of(community_id, db) + .await? + .ok_or(CommonError::NotFound)?; + + ensure(kind == Kind::Group) +} + +pub(crate) fn message_event(message: &Message, event: fn(Message) -> Event) -> Broadcast { + let mut message = message.clone(); + if let Some(reply) = &mut message.reply { + reply.redact(); + } + + Broadcast::new(To::Community(message.community_id), event(message)) +} + +pub(crate) fn voice_joined(community_id: Id, user_id: Id, muted: bool) -> Vec { + let mut broadcasts = vec![Broadcast::new( + To::Community(community_id), + Event::VoiceJoined { + community_id, + user_id, + }, + )]; + if muted { + broadcasts.push(Broadcast::new( + To::Community(community_id), + Event::VoiceMuted { + community_id: Some(community_id), + user_id, + muted, + }, + )); + } + + broadcasts +} + +pub(crate) async fn record_ghost_voice( + user_id: Id, + community_id: Id, + seconds: u64, + db: &Connection, +) -> Result<(), ServerError> { + let community = db::community::label(community_id, db).await?; + db::log::record_admin( + Some(user_id), + None, + Some(&community), + &AdminAction::GhostVoice { seconds }, + db, + ) + .await +} diff --git a/crates/server/src/call/social.rs b/crates/server/src/call/social.rs index 65218bd..8ef6f84 100644 --- a/crates/server/src/call/social.rs +++ b/crates/server/src/call/social.rs @@ -7,18 +7,17 @@ use common::{ error::Error, event::Event, model::{ - AdminAction, Community, Friends, Id, Invitation, LogAction, Member, Rank, Report, - ReportStatus, User, + AdminAction, Community, Friends, Id, Invitation, LogAction, Member, Rank, Report, User, }, permission, }; use crate::{ - call::{Cx, Handle, Me}, + call::shared::{actor_rank, allowed, ensure_editable, introduce}, + call::{Cx, Handle}, db::{self, direct::Opening, friend::FriendState}, error::{ServerError, ensure, ensure_with}, publish::To, - request::{actor_rank, allowed, ensure_editable, introduce}, }; async fn friends_updated(user_ids: [Id; 2], cx: &mut Cx<'_>) -> Result<(), ServerError> { @@ -38,9 +37,7 @@ async fn invitations_updated(user_id: Id, cx: &mut Cx<'_>) -> Result<(), ServerE } impl Handle for FindUser { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { - let me = me.user()?; - + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result { db::user::by_username(&self.username, cx.db) .await? .filter(|found| found.id != me.id) @@ -49,8 +46,7 @@ impl Handle for FindUser { } impl Handle for OpenDirect { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result { ensure(me.id != self.user_id)?; match db::direct::open(me.id, self.user_id, cx.db).await? { Opening::Created(community) => { @@ -64,8 +60,7 @@ impl Handle for OpenDirect { } impl Handle for OpenNotes { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result { match db::direct::open(me.id, me.id, cx.db).await? { Opening::Created(community) | Opening::Existing(community) => Ok(community), } @@ -73,16 +68,13 @@ impl Handle for OpenNotes { } impl Handle for ListFriends { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { - let me = me.user()?; - + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result { db::friend::state(me.id, cx.db).await } } impl Handle for AddFriend { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { let db = cx.db; ensure_with(me.id != self.user_id, Error::Forbidden)?; ensure_with( @@ -102,8 +94,7 @@ impl Handle for AddFriend { } impl Handle for AcceptFriend { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { db::friend::accept(me.id, self.user_id, cx.db).await?; introduce(me.id, &[self.user_id], cx).await?; @@ -112,8 +103,7 @@ impl Handle for AcceptFriend { } impl Handle for RemoveFriend { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { db::friend::remove(me.id, self.user_id, cx.db).await?; friends_updated([me.id, self.user_id], cx).await @@ -121,11 +111,10 @@ impl Handle for RemoveFriend { } impl Handle for Invite { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { let db = cx.db; ensure_editable(self.community_id, db).await?; - allowed(&me, self.community_id, db, permission::can_read).await?; + allowed(&me, self.community_id, db, permission::is_member).await?; let target = db::user::read(self.user_id, db).await?; if db::member::rank(self.user_id, self.community_id, db) .await? @@ -153,16 +142,13 @@ impl Handle for Invite { } impl Handle for ListInvitations { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { - let me = me.user()?; - + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result, ServerError> { db::invitation::of(me.id, cx.db).await } } impl Handle for AcceptInvitation { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result { let db = cx.db; db::invitation::take(self.community_id, me.id, db).await?; let banned = db::member::is_banned(me.id, self.community_id, db).await?; @@ -187,8 +173,7 @@ impl Handle for AcceptInvitation { } impl Handle for DeclineInvitation { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { db::invitation::take(self.community_id, me.id, cx.db).await?; invitations_updated(me.id, cx).await @@ -196,12 +181,11 @@ impl Handle for DeclineInvitation { } impl Handle for ReportMessage { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { let db = cx.db; let message = db::message::read(self.message_id, db).await?; let actor = actor_rank(&me, message.community_id, db).await?; - ensure(permission::can_read(actor) && me.id != message.user_id)?; + ensure(permission::is_member(actor) && me.id != message.user_id)?; ensure_with( !db::report::is_open(me.id, message.user_id, Some(self.message_id), db).await?, Error::Taken, @@ -223,8 +207,7 @@ impl Handle for ReportMessage { } impl Handle for ReportUser { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { let db = cx.db; db::user::read(self.user_id, db).await?; ensure(me.id != self.user_id)?; @@ -240,16 +223,14 @@ impl Handle for ReportUser { } impl Handle for ListReports { - async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result, ServerError> { db::report::list(self.status, cx.db).await } } impl Handle for HandleReport { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { let db = cx.db; - ensure(permission::is_builder(me.role) && self.status != ReportStatus::Open)?; let target = db::report::handle(self.report_id, self.status, me.id, db).await?; db::log::record_admin( Some(me.id), diff --git a/crates/server/src/call/stats.rs b/crates/server/src/call/stats.rs index 5ee0356..90dc5bb 100644 --- a/crates/server/src/call/stats.rs +++ b/crates/server/src/call/stats.rs @@ -1,17 +1,18 @@ use common::{ call::{FollowStats, GetServerStats, PushStats}, event::Event, + model::User, stats::Stats, }; use crate::{ - call::{Cx, Handle, Me}, + call::{Cx, Handle}, error::ServerError, publish::To, }; impl Handle for FollowStats { - async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result, ServerError> { let change = cx.sh.services.stats.follow(cx.client.id, self.user_id); if let Some(user_id) = change.stopped { cx.emit(To::User(user_id), Event::StatsWanted(false)); @@ -25,8 +26,8 @@ impl Handle for FollowStats { } impl Handle for PushStats { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let user_id = me.user()?.id; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { + let user_id = me.id; for conn in cx.sh.services.stats.push(user_id, self.stats.clone()) { cx.emit( To::Conn(conn), @@ -42,7 +43,7 @@ impl Handle for PushStats { } impl Handle for GetServerStats { - async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result { + async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result { let services = &cx.sh.services; Ok(services.machine.sample(services.hub.bytes())) } diff --git a/crates/server/src/call/user.rs b/crates/server/src/call/user.rs index 699290a..3ea3596 100644 --- a/crates/server/src/call/user.rs +++ b/crates/server/src/call/user.rs @@ -1,43 +1,36 @@ use common::{ call::{ - GetAvatar, GetSettings, GetUser, ListPresences, ListSessions, RemoveAvatar, RevokeSession, - UpdateAvatar, UpdateHue, UpdatePresence, UpdateStatus, UpdateUser, + GetAvatar, GetUser, ListPresences, ListSessions, RemoveAvatar, RevokeSession, UpdateAvatar, + UpdateHue, UpdatePresence, UpdateStatus, UpdateUser, }, event::Event, - model::{AdminAction, Id, Presence, ServerSettings, SessionInfo, User}, + model::{AdminAction, Id, Presence, SessionInfo, User}, validate::validate_avatar_size, }; use crate::{ authentication, - call::{Cx, Handle, Me}, - db, + call::shared::{effective_presence, managed, presence_changed}, + call::{Cx, Handle}, + db::{self, avatar::Owner, community::Kind}, error::ServerError, files, publish::{To, related_user_ids}, - request::{effective_presence, managed, presence_changed}, }; pub(super) fn user_updated(user: &User, cx: &mut Cx<'_>) { cx.emit(To::Related(user.id), Event::UserUpdated(user.clone())); } -impl Handle for GetSettings { - async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result { - db::settings::read(cx.db).await - } -} - impl Handle for GetUser { - async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result { + async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result { db::user::read(self.user_id, cx.db).await } } impl Handle for UpdateUser { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { - let me = me.user()?; - let user = db::user::update(me.id, &self.username, cx.db).await?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result { + let user = db::user::rename(me.id, &self.username, cx.db).await?; user_updated(&user, cx); Ok(user) @@ -45,9 +38,8 @@ impl Handle for UpdateUser { } impl Handle for UpdateStatus { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { - let me = me.user()?; - let user = db::user::update_status(me.id, &self.status, cx.db).await?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result { + let user = db::user::set_status(me.id, &self.status, cx.db).await?; user_updated(&user, cx); Ok(user) @@ -55,9 +47,8 @@ impl Handle for UpdateStatus { } impl Handle for UpdateHue { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { - let me = me.user()?; - let user = db::user::update_hue(me.id, self.hue, cx.db).await?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result { + let user = db::user::set_hue(me.id, self.hue, cx.db).await?; user_updated(&user, cx); Ok(user) @@ -65,60 +56,77 @@ impl Handle for UpdateHue { } impl Handle for UpdatePresence { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { let was_offline = db::user::presence(me.id, cx.db).await? == Presence::Offline; - db::user::update_presence(me.id, self.presence, cx.db).await?; + db::user::set_presence(me.id, self.presence, cx.db).await?; cx.out .extend(presence_changed(&cx.sh.services.hub, me.id, cx.db).await?); let hiding = self.presence == Presence::Offline; + if was_offline == hiding { + return Ok(()); + } let rooms = &cx.sh.services.rooms; - let direct = match rooms.room_of(me.id) { - Some(community_id) => matches!( - db::community::kind_of(community_id, cx.db).await?, - Some(db::community::Kind::Direct) - ), - None => false, + let Some(community_id) = rooms.room_of(me.id) else { + return Ok(()); }; - if let Some(community_id) = rooms - .room_of(me.id) - .filter(|_| was_offline != hiding && !direct) - && rooms.participants(community_id).contains(&me.id) - { - let shares = rooms - .shares(community_id) - .into_iter() - .filter(|share| share.user_id == me.id); - let mut events = Vec::new(); - if hiding { - events.extend(shares.map(|share| Event::ShareStopped { - community_id, - user_id: me.id, - kind: share.kind, - })); - events.push(Event::VoiceLeft { + if !rooms.participants(community_id).contains(&me.id) { + return Ok(()); + } + if matches!( + db::community::kind_of(community_id, cx.db).await?, + Some(Kind::Direct) + ) { + return Ok(()); + } + let shares: Vec<_> = rooms + .shares(community_id) + .into_iter() + .filter(|share| share.user_id == me.id) + .collect(); + if hiding { + for share in shares { + cx.emit( + To::Outsiders(community_id), + Event::ShareStopped { + community_id, + user_id: me.id, + kind: share.kind, + }, + ); + } + cx.emit( + To::Outsiders(community_id), + Event::VoiceLeft { community_id, user_id: me.id, - }); - } else { - events.push(Event::VoiceJoined { + }, + ); + } else { + cx.emit( + To::Outsiders(community_id), + Event::VoiceJoined { community_id, user_id: me.id, - }); - if db::user::voice_muted(me.id, cx.db).await? { - events.push(Event::VoiceMuted { + }, + ); + if db::user::voice_muted(me.id, cx.db).await? { + cx.emit( + To::Outsiders(community_id), + Event::VoiceMuted { community_id: Some(community_id), user_id: me.id, muted: true, - }); - } - events.extend(shares.map(|share| Event::ShareStarted { - community_id, - share, - })); + }, + ); } - for event in events { - cx.emit(To::Outsiders(community_id), event); + for share in shares { + cx.emit( + To::Outsiders(community_id), + Event::ShareStarted { + community_id, + share, + }, + ); } } @@ -127,8 +135,7 @@ impl Handle for UpdatePresence { } impl Handle for ListPresences { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result, ServerError> { let hub = &cx.sh.services.hub; let mut presences = Vec::new(); for user_id in related_user_ids(me.id, cx.db).await? { @@ -143,12 +150,11 @@ impl Handle for ListPresences { } impl Handle for UpdateAvatar { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result { let maximum = db::settings::read(cx.db).await?.max_avatar_bytes; validate_avatar_size(&self.image, maximum)?; files::check_avatar(&self.image)?; - db::avatar::set_user(me.id, Some(&self.image), cx.db).await?; + db::avatar::set(Owner::User(me.id), Some(&self.image), cx.db).await?; let user = db::user::read(me.id, cx.db).await?; user_updated(&user, cx); @@ -157,9 +163,8 @@ impl Handle for UpdateAvatar { } impl Handle for RemoveAvatar { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result { - let me = me.user()?; - db::avatar::set_user(me.id, None, cx.db).await?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result { + db::avatar::set(Owner::User(me.id), None, cx.db).await?; let user = db::user::read(me.id, cx.db).await?; user_updated(&user, cx); @@ -168,14 +173,13 @@ impl Handle for RemoveAvatar { } impl Handle for GetAvatar { - async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result, ServerError> { db::avatar::read(self.avatar_id, cx.db).await } } impl Handle for ListSessions { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result, ServerError> { managed(&me, self.user_id, cx.db).await?; db::session::list(self.user_id, cx.db).await @@ -183,18 +187,10 @@ impl Handle for ListSessions { } impl Handle for RevokeSession { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { managed(&me, self.user_id, cx.db).await?; - authentication::revoke( - &cx.sh.services.hub, - authentication::Revoke::Session { - user_id: self.user_id, - session_id: self.session_id, - }, - cx.db, - ) - .await?; + authentication::revoke_session(&cx.sh.services.hub, self.user_id, self.session_id, cx.db) + .await?; db::log::record_admin( Some(me.id), Some(self.user_id), diff --git a/crates/server/src/call/voice.rs b/crates/server/src/call/voice.rs index 57a74c8..c276c3e 100644 --- a/crates/server/src/call/voice.rs +++ b/crates/server/src/call/voice.rs @@ -6,28 +6,38 @@ use common::{ }, error::Error, event::Event, - model::{AdminAction, CallLog, Id, VoiceRoom}, + model::{AdminAction, CallLog, Id, User, VoiceRoom}, permission, share::Share, }; use crate::{ - call::{Cx, Handle, Me}, - db::{self, community::Kind}, - error::{ServerError, ensure}, - publish::To, - request::{ - allowed, departed, is_outsider, leave_user_voice, managed, message_event, share_ended, + call::shared::{ + allowed, departed, departed_all, is_outsider, managed, message_event, share_ended, voice_joined, voice_muted, }, + call::{Cx, Handle}, + db::{self, Connection, community::Kind}, + error::{ServerError, ensure}, + publish::{To, hidden}, + rooms::{Departure, Left, Rooms}, }; +async fn visible( + rooms: &Rooms, + viewer: Id, + community_id: Id, + user_id: Id, + db: &Connection, +) -> bool { + rooms.room_of(viewer) == Some(community_id) || !hidden(user_id, community_id, db).await +} + impl Handle for JoinVoice { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result, ServerError> { let community_id = self.community_id; let rooms = &cx.sh.services.rooms; - allowed(&me, community_id, cx.db, permission::can_join_voice).await?; + allowed(&me, community_id, cx.db, permission::is_member).await?; let kind = db::community::kind_of(community_id, cx.db) .await? .ok_or(Error::NotFound)?; @@ -41,17 +51,21 @@ impl Handle for JoinVoice { let ghost = outsider || db::user::is_ghost(me.id, cx.db).await?; let starts_call = !ghost && kind == Kind::Direct && rooms.participants(community_id).is_empty(); - let joined = rooms.join(cx.client, community_id, muted, ghost)?; - let mut broadcasts = match joined.departure { - Some(departure) => departed(departure, cx.db).await?, - None => Vec::new(), - }; + let departure = rooms.join(cx.client, community_id, muted, ghost)?; + let transferred = matches!( + departure, + Some(Departure { + left: Left::Transferred, + .. + }) + ); + let mut broadcasts = departed_all(departure, cx.db).await?; if starts_call { let created = db::message::create_call_log(community_id, me.id, CallLog::Started, cx.db).await?; broadcasts.push(message_event(&created, Event::MessageCreated)); } - if !ghost && !joined.transferred { + if !ghost && !transferred { broadcasts.extend(voice_joined(community_id, me.id, muted)); } cx.out.extend(broadcasts); @@ -61,26 +75,22 @@ impl Handle for JoinVoice { } impl Handle for LeaveVoice { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - me.user()?; - if let Some(departure) = cx.sh.services.rooms.leave(cx.client.id) { - cx.out.extend(departed(departure, cx.db).await?); - } + async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { + cx.out + .extend(departed_all(cx.sh.services.rooms.leave(cx.client.id), cx.db).await?); Ok(()) } } impl Handle for StartShare { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { let rooms = &cx.sh.services.rooms; let Some(community_id) = rooms.room_of_conn(cx.client.id) else { return Err(Error::NotFound.into()); }; - allowed(&me, community_id, cx.db, permission::can_share).await?; + allowed(&me, community_id, cx.db, permission::is_member).await?; ensure(!self.source.encode.is_empty())?; - ensure(!db::user::is_ghost(me.id, cx.db).await?)?; let (share, media) = rooms .start_share(cx.client.id, self.kind, self.source) .ok_or(Error::NotFound)?; @@ -98,8 +108,7 @@ impl Handle for StartShare { } impl Handle for StopShare { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { if let Some(community_id) = cx.sh.services.rooms.stop_share(cx.client.id, self.kind) { cx.out.push(share_ended(community_id, me.id, self.kind)); } @@ -109,14 +118,12 @@ impl Handle for StopShare { } impl Handle for ListShares { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { - let me = me.user()?; - allowed(&me, self.community_id, cx.db, permission::can_read).await?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result, ServerError> { + allowed(&me, self.community_id, cx.db, permission::is_member).await?; let rooms = &cx.sh.services.rooms; - let inside = rooms.room_of(me.id) == Some(self.community_id); let mut shares = Vec::new(); for share in rooms.shares(self.community_id) { - if inside || !crate::publish::hidden(share.user_id, self.community_id, cx.db).await { + if visible(rooms, me.id, self.community_id, share.user_id, cx.db).await { shares.push(share); } } @@ -126,8 +133,7 @@ impl Handle for ListShares { } impl Handle for WatchShare { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - me.user()?; + async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { let media = cx .sh .services @@ -147,8 +153,7 @@ impl Handle for WatchShare { } impl Handle for UnwatchShare { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - me.user()?; + async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { cx.out.extend( cx.sh .services @@ -161,8 +166,7 @@ impl Handle for UnwatchShare { } impl Handle for RequestKeyframe { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - me.user()?; + async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { let keyframe = cx .sh .services @@ -176,8 +180,7 @@ impl Handle for RequestKeyframe { } impl Handle for ReportLoss { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - me.user()?; + async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { let loss = cx .sh .services @@ -191,15 +194,14 @@ impl Handle for ReportLoss { } impl Handle for DeclineCall { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { let community_id = self.community_id; let rooms = &cx.sh.services.rooms; let kind = db::community::kind_of(community_id, cx.db) .await? .ok_or(Error::NotFound)?; ensure(kind == Kind::Direct)?; - allowed(&me, community_id, cx.db, permission::can_read).await?; + allowed(&me, community_id, cx.db, permission::is_member).await?; let participants = rooms.participants(community_id); ensure(!participants.is_empty() && !participants.contains(&me.id))?; rooms.decline(community_id); @@ -212,14 +214,12 @@ impl Handle for DeclineCall { } impl Handle for ListVoiceParticipants { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result, ServerError> { - let me = me.user()?; - allowed(&me, self.community_id, cx.db, permission::can_read).await?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result, ServerError> { + allowed(&me, self.community_id, cx.db, permission::is_member).await?; let rooms = &cx.sh.services.rooms; - let inside = rooms.room_of(me.id) == Some(self.community_id); let mut ids = Vec::new(); for user_id in rooms.participants(self.community_id) { - if inside || !crate::publish::hidden(user_id, self.community_id, cx.db).await { + if visible(rooms, me.id, self.community_id, user_id, cx.db).await { ids.push(user_id); } } @@ -229,13 +229,13 @@ impl Handle for ListVoiceParticipants { } impl Handle for ListVoiceRooms { - async fn handle(self, _: Me, cx: &mut Cx<'_>) -> Result, ServerError> { + async fn handle(self, _: User, cx: &mut Cx<'_>) -> Result, ServerError> { let mut rooms = Vec::new(); - for (community_id, user_ids, ghosts) in cx.sh.services.rooms.list() { - let community = db::community::label(community_id, cx.db).await?; + for room in cx.sh.services.rooms.list() { + let community = db::community::label(room.community_id, cx.db).await?; let mut users = Vec::new(); let mut muted = Vec::new(); - for user_id in user_ids { + for user_id in room.users { let user = db::user::read(user_id, cx.db).await?; if db::user::voice_muted(user_id, cx.db).await? { muted.push(user_id); @@ -243,11 +243,11 @@ impl Handle for ListVoiceRooms { users.push(user); } rooms.push(VoiceRoom { - community_id, + community_id: room.community_id, community, users, muted, - ghosts, + ghosts: room.ghosts, }); } rooms.sort_by(|a, b| a.community.cmp(&b.community)); @@ -257,29 +257,27 @@ impl Handle for ListVoiceRooms { } impl Handle for KickFromVoice { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { managed(&me, self.user_id, cx.db).await?; - let broadcasts = leave_user_voice(&cx.sh.services.rooms, self.user_id, cx.db).await?; - if !broadcasts.is_empty() { - db::log::record_admin( - Some(me.id), - Some(self.user_id), - None, - &AdminAction::VoiceKicked, - cx.db, - ) - .await?; - } - cx.out.extend(broadcasts); + let Some(departure) = cx.sh.services.rooms.leave_user(self.user_id) else { + return Ok(()); + }; + db::log::record_admin( + Some(me.id), + Some(self.user_id), + None, + &AdminAction::VoiceKicked, + cx.db, + ) + .await?; + cx.out.extend(departed(departure, cx.db).await?); Ok(()) } } impl Handle for ServerMute { - async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let me = me.user()?; + async fn handle(self, me: User, cx: &mut Cx<'_>) -> Result<(), ServerError> { managed(&me, self.user_id, cx.db).await?; db::user::set_voice_muted(self.user_id, self.muted, cx.db).await?; db::log::record_admin( @@ -290,7 +288,11 @@ impl Handle for ServerMute { cx.db, ) .await?; - let community_id = cx.sh.services.rooms.set_muted(self.user_id, self.muted); + let community_id = cx + .sh + .services + .rooms + .set_server_muted(self.user_id, self.muted); let broadcast = voice_muted(community_id, self.user_id, self.muted, cx.db).await?; cx.out.push(broadcast); diff --git a/crates/server/src/certificate.rs b/crates/server/src/certificate.rs index 6f96aa9..3b031d3 100644 --- a/crates/server/src/certificate.rs +++ b/crates/server/src/certificate.rs @@ -19,16 +19,11 @@ const RELOAD_INTERVAL: Duration = Duration::from_secs(600); const SUBJECT_ALT_NAME: &str = "localhost"; #[derive(Debug)] -struct Reloader { - certified_key: RwLock>, -} +struct Reloader(RwLock>); impl ResolvesServerCert for Reloader { fn resolve(&self, _client_hello: ClientHello<'_>) -> Option> { - let key = self - .certified_key - .read() - .unwrap_or_else(PoisonError::into_inner); + let key = self.0.read().unwrap_or_else(PoisonError::into_inner); Some(Arc::clone(&key)) } @@ -89,10 +84,7 @@ async fn watch(reloader: Arc, certificate_path: String, key_path: Stri match certified_key(&certificate_path, &key_path) { Ok(key) => { - *reloader - .certified_key - .write() - .unwrap_or_else(PoisonError::into_inner) = Arc::new(key); + *reloader.0.write().unwrap_or_else(PoisonError::into_inner) = Arc::new(key); last = current; info!("certificate reloaded"); } @@ -102,19 +94,24 @@ async fn watch(reloader: Arc, certificate_path: String, key_path: Stri } pub fn load(certificate_path: &str, key_path: &str) -> Result { - if !Path::new(certificate_path).exists() || !Path::new(key_path).exists() { + if !Path::new(certificate_path).exists() && !Path::new(key_path).exists() { generate(certificate_path, key_path)?; warn!("certificate not found, generated a self-signed one for {SUBJECT_ALT_NAME}"); } + for path in [certificate_path, key_path] { + if !Path::new(path).exists() { + return Err(certificate_error(format!("{path} is missing"))); + } + } - let reloader = Arc::new(Reloader { - certified_key: RwLock::new(Arc::new(certified_key(certificate_path, key_path)?)), - }); + let reloader = Arc::new(Reloader(RwLock::new(Arc::new(certified_key( + certificate_path, + key_path, + )?)))); let mut tls = rustls::ServerConfig::builder() .with_no_client_auth() .with_cert_resolver(reloader.clone()); - tls.max_early_data_size = u32::MAX; tls.alpn_protocols = vec![ common::transport::ALPN.to_vec(), common::update::ALPN.to_vec(), diff --git a/crates/server/src/datagram.rs b/crates/server/src/datagram.rs deleted file mode 100644 index b8f1ebd..0000000 --- a/crates/server/src/datagram.rs +++ /dev/null @@ -1,18 +0,0 @@ -use std::sync::Arc; - -use quinn::Connection; -use tracing::warn; - -use crate::{hub::Client, network::Shared, publish}; - -pub(crate) async fn relay_datagrams(connection: Connection, client: Arc, shared: Shared) { - while let Ok(bytes) = connection.read_datagram().await { - let broadcasts = shared.services.rooms.relay(&client, &bytes); - if broadcasts.is_empty() { - continue; - } - if let Err(error) = publish::job(&shared, async |_| Ok(broadcasts)).await { - warn!("relay: {error}"); - } - } -} diff --git a/crates/server/src/db/attachment.rs b/crates/server/src/db/attachment.rs index 902de2a..b5a47d1 100644 --- a/crates/server/src/db/attachment.rs +++ b/crates/server/src/db/attachment.rs @@ -1,19 +1,18 @@ use std::collections::HashSet; use common::{ - constant::MAXIMUM_ATTACHMENTS_PER_MESSAGE, error::Error, - model::{Attachment, AttachmentInfo, AttachmentKind, CommunityUsage, Id, Usage}, + model::{Attachment, AttachmentInfo, AttachmentKind, CommunityUsage, Id, UserUsage}, time::now_ms, }; -use super::{Connection, Reader, community, one, run, user}; +use super::{Connection, Reader, all, community, one, run, user}; use crate::error::{ServerError, ensure_with}; const LIST_LIMIT: u32 = 200; const USAGE_LIMIT: u32 = 50; -pub const COLUMNS: &str = "attachment.id, attachment.name, attachment.size, attachment.kind, attachment.width, attachment.height, attachment.created_at"; +const COLUMNS: &str = "attachment.id, attachment.name, attachment.size, attachment.kind, attachment.width, attachment.height, attachment.created_at"; pub struct Stored { pub attachment: Attachment, @@ -23,7 +22,7 @@ pub struct Stored { pub message_id: Option, } -pub fn row(r: &mut Reader) -> Result { +fn row(r: &mut Reader) -> Result { Ok(Attachment { id: r.get()?, name: r.get()?, @@ -40,7 +39,7 @@ pub async fn of_message( snippet_position: Option, db: &Connection, ) -> Result, ServerError> { - super::all( + all( db, &format!( "SELECT {COLUMNS} FROM attachment WHERE message_id = ?1 AND snippet_position IS ?2 ORDER BY id" @@ -58,10 +57,6 @@ pub async fn bind( attachment_ids: &[Id], db: &Connection, ) -> Result<(), ServerError> { - ensure_with( - attachment_ids.len() <= MAXIMUM_ATTACHMENTS_PER_MESSAGE, - Error::NotFound, - )?; for attachment_id in attachment_ids { let bound = run( db, @@ -145,10 +140,16 @@ pub async fn read(id: Id, db: &Connection) -> Result { .await } -pub async fn delete(id: Id, db: &Connection) -> Result<(), ServerError> { - run(db, "DELETE FROM attachment WHERE id = ?1", (id,)).await?; +pub async fn delete_file(id: Id, db: &Connection) -> Result, ServerError> { + let message_ids: Vec> = all( + db, + "DELETE FROM attachment WHERE file = (SELECT file FROM attachment WHERE id = ?1) RETURNING message_id", + (id,), + |r| r.get(), + ) + .await?; - Ok(()) + Ok(message_ids.into_iter().flatten().collect()) } pub async fn delete_uploads(user_id: Id, db: &Connection) -> Result<(), ServerError> { @@ -183,7 +184,7 @@ pub async fn delete_before(cutoff: u64, limit: u32, db: &Connection) -> Result Result, ServerError> { - let files = super::all(db, "SELECT file FROM attachment", (), |r| r.get()).await?; + let files = all(db, "SELECT file FROM attachment", (), |r| r.get()).await?; Ok(files.into_iter().collect()) } @@ -195,19 +196,19 @@ pub async fn quota( ) -> Result<(u64, u64), ServerError> { one( db, - "SELECT (SELECT COALESCE(SUM(size), 0) FROM attachment WHERE uploader_id = ?1), (SELECT COALESCE(SUM(size), 0) FROM attachment WHERE community_id = ?2)", + "SELECT (SELECT COALESCE(SUM(size), 0) FROM (SELECT DISTINCT file, size FROM attachment WHERE uploader_id = ?1)), (SELECT COALESCE(SUM(size), 0) FROM (SELECT DISTINCT file, size FROM attachment WHERE community_id = ?2))", (user_id, community_id), |r| Ok((r.get()?, r.get()?)), ) .await } -pub async fn all( +pub async fn list( user_id: Option, community_id: Option, db: &Connection, ) -> Result, ServerError> { - let rows = super::all( + let rows = all( db, &format!( "SELECT {COLUMNS}, attachment.uploader_id, attachment.community_id FROM attachment WHERE (?1 IS NULL OR attachment.uploader_id = ?1) AND (?2 IS NULL OR attachment.community_id = ?2) ORDER BY attachment.size DESC LIMIT ?3" @@ -229,17 +230,17 @@ pub async fn all( Ok(infos) } -pub async fn usage(db: &Connection) -> Result<(Vec, Vec), ServerError> { - let by_user: Vec<(Id, u64, u64)> = super::all( +pub async fn usage(db: &Connection) -> Result<(Vec, Vec), ServerError> { + let by_user: Vec<(Id, u64, u64)> = all( db, - "SELECT uploader_id, SUM(size), COUNT(*) FROM attachment GROUP BY uploader_id ORDER BY SUM(size) DESC LIMIT ?1", + "SELECT uploader_id, SUM(size), COUNT(*) FROM (SELECT DISTINCT uploader_id, file, size FROM attachment) GROUP BY uploader_id ORDER BY SUM(size) DESC LIMIT ?1", (USAGE_LIMIT,), |r| Ok((r.get()?, r.get()?, r.get()?)), ) .await?; - let by_community: Vec<(Id, u64, u64)> = super::all( + let by_community: Vec<(Id, u64, u64)> = all( db, - "SELECT community_id, SUM(size), COUNT(*) FROM attachment GROUP BY community_id ORDER BY SUM(size) DESC LIMIT ?1", + "SELECT community_id, SUM(size), COUNT(*) FROM (SELECT DISTINCT community_id, file, size FROM attachment) GROUP BY community_id ORDER BY SUM(size) DESC LIMIT ?1", (USAGE_LIMIT,), |r| Ok((r.get()?, r.get()?, r.get()?)), ) @@ -247,7 +248,7 @@ pub async fn usage(db: &Connection) -> Result<(Vec, Vec), let mut users = Vec::new(); for (user_id, bytes, count) in by_user { - users.push(Usage { + users.push(UserUsage { user: user::read(user_id, db).await?, bytes, count, diff --git a/crates/server/src/db/avatar.rs b/crates/server/src/db/avatar.rs index 2889e86..9bff6f7 100644 --- a/crates/server/src/db/avatar.rs +++ b/crates/server/src/db/avatar.rs @@ -1,8 +1,13 @@ use common::model::Id; -use super::{Connection, one, run}; +use super::{Connection, exec, one}; use crate::error::ServerError; +pub enum Owner { + User(Id), + Community(Id), +} + pub async fn read(id: Id, db: &Connection) -> Result, ServerError> { one(db, "SELECT data FROM avatar WHERE id = ?1", (id,), |r| { r.get() @@ -10,40 +15,22 @@ pub async fn read(id: Id, db: &Connection) -> Result, ServerError> { .await } -pub async fn set_user( - user_id: Id, - avatar: Option<&[u8]>, - db: &Connection, -) -> Result<(), ServerError> { - run(db, "DELETE FROM avatar WHERE user_id = ?1", (user_id,)).await?; - if let Some(bytes) = avatar { - run( - db, - "INSERT INTO avatar (user_id, data) VALUES (?1, ?2)", - (user_id, bytes), - ) - .await?; - } - - Ok(()) -} - -pub async fn set_community( - community_id: Id, - avatar: Option<&[u8]>, - db: &Connection, -) -> Result<(), ServerError> { - run( +pub async fn set(owner: Owner, avatar: Option<&[u8]>, db: &Connection) -> Result<(), ServerError> { + let (column, id) = match owner { + Owner::User(id) => ("user_id", id), + Owner::Community(id) => ("community_id", id), + }; + exec( db, - "DELETE FROM avatar WHERE community_id = ?1", - (community_id,), + &format!("DELETE FROM avatar WHERE {column} = ?1"), + (id,), ) .await?; if let Some(bytes) = avatar { - run( + exec( db, - "INSERT INTO avatar (community_id, data) VALUES (?1, ?2)", - (community_id, bytes), + &format!("INSERT INTO avatar ({column}, data) VALUES (?1, ?2)"), + (id, bytes), ) .await?; } diff --git a/crates/server/src/db/community.rs b/crates/server/src/db/community.rs index 64a285b..90c3e86 100644 --- a/crates/server/src/db/community.rs +++ b/crates/server/src/db/community.rs @@ -39,10 +39,7 @@ fn raw(r: &mut Reader) -> Result { } pub async fn read(id: Id, viewer: Id, db: &Connection) -> Result { - community(one(db, READ, (id, viewer), raw).await?, db).await -} - -async fn community(raw: Raw, db: &Connection) -> Result { + let raw = one(db, READ, (id, viewer), raw).await?; let kind = match raw.kind { Kind::Group => CommunityKind::Group, Kind::Direct => CommunityKind::Direct { @@ -73,8 +70,8 @@ pub async fn create(kind: Kind, name: &str, db: &Connection) -> Result Result, ServerError> { let ids: Vec = all( db, - "SELECT m.community_id FROM member m JOIN community c ON c.id = m.community_id WHERE m.user_id = ?1 AND (c.kind != 'direct' OR EXISTS (SELECT 1 FROM message WHERE message.community_id = c.id AND message.deleted_at IS NULL)) ORDER BY m.community_id", - (user_id,), + "SELECT m.community_id FROM member m JOIN community c ON c.id = m.community_id WHERE m.user_id = ?1 AND (c.kind != ?2 OR EXISTS (SELECT 1 FROM message WHERE message.community_id = c.id AND message.deleted_at IS NULL)) ORDER BY m.community_id", + (user_id, Kind::Direct.as_str()), |r| r.get(), ) .await?; @@ -88,17 +85,17 @@ pub async fn communities_of(user_id: Id, db: &Connection) -> Result Result, ServerError> { - let raws = all( + let ids: Vec = all( db, - "SELECT id, name, kind, (SELECT avatar.id FROM avatar WHERE avatar.community_id = community.id), voice_enabled, NULL FROM community WHERE kind = ?1 ORDER BY name", + "SELECT id FROM community WHERE kind = ?1 ORDER BY name", (Kind::Group.as_str(),), - raw, + |r| r.get(), ) .await?; let mut groups = Vec::new(); - for raw in raws { - groups.push(community(raw, db).await?); + for id in ids { + groups.push(read(id, 0, db).await?); } Ok(groups) diff --git a/crates/server/src/db/direct.rs b/crates/server/src/db/direct.rs index 49129ec..1184af7 100644 --- a/crates/server/src/db/direct.rs +++ b/crates/server/src/db/direct.rs @@ -1,6 +1,6 @@ use common::model::{Community, Id, Rank}; -use super::{Connection, community, maybe, member, run}; +use super::{Connection, all, community, maybe, member, run}; use crate::error::ServerError; pub enum Opening { @@ -45,3 +45,13 @@ pub async fn open(me: Id, other: Id, db: &Connection) -> Result Result, ServerError> { + all( + db, + "SELECT community_id FROM direct WHERE user_a = ?1 OR user_b = ?1", + (user_id,), + |r| r.get(), + ) + .await +} diff --git a/crates/server/src/db/friend.rs b/crates/server/src/db/friend.rs index 64e761e..7fa3c7c 100644 --- a/crates/server/src/db/friend.rs +++ b/crates/server/src/db/friend.rs @@ -1,11 +1,10 @@ use common::{ - error::Error, model::{Friends, Id, User}, string_enum, }; -use super::{Connection, all, maybe, run, user}; -use crate::error::{ServerError, ensure_with}; +use super::{Connection, all, exec, exec_one, maybe, user}; +use crate::error::ServerError; string_enum! { #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -63,42 +62,35 @@ pub async fn pair(me: Id, other: Id, db: &Connection) -> Result Result<(), ServerError> { - run( + exec( db, "INSERT INTO friend (user_id, friend_id, state) VALUES (?1, ?2, ?3)", (me, other, FriendState::Requested.as_str()), ) - .await?; - - Ok(()) + .await } pub async fn accept(me: Id, other: Id, db: &Connection) -> Result<(), ServerError> { let accepted = FriendState::Accepted.as_str(); - let updated = run( + exec_one( db, "UPDATE friend SET state = ?3 WHERE user_id = ?1 AND friend_id = ?2 AND state = ?4", (other, me, accepted, FriendState::Requested.as_str()), ) .await?; - ensure_with(updated == 1, Error::NotFound)?; - run( + exec( db, "INSERT OR REPLACE INTO friend (user_id, friend_id, state) VALUES (?1, ?2, ?3)", (me, other, accepted), ) - .await?; - - Ok(()) + .await } pub async fn remove(me: Id, other: Id, db: &Connection) -> Result<(), ServerError> { - run( + exec( db, "DELETE FROM friend WHERE (user_id = ?1 AND friend_id = ?2) OR (user_id = ?2 AND friend_id = ?1)", (me, other), ) - .await?; - - Ok(()) + .await } diff --git a/crates/server/src/db/invitation.rs b/crates/server/src/db/invitation.rs index 3949ff0..f0f7a86 100644 --- a/crates/server/src/db/invitation.rs +++ b/crates/server/src/db/invitation.rs @@ -1,10 +1,7 @@ -use common::{ - error::Error, - model::{Id, Invitation}, -}; +use common::model::{Id, Invitation}; -use super::{Connection, all, community, one, run, user}; -use crate::error::{ServerError, ensure_with}; +use super::{Connection, all, community, exec, exec_one, one, user}; +use crate::error::ServerError; pub async fn of(user_id: Id, db: &Connection) -> Result, ServerError> { let pairs: Vec<(Id, Id)> = all( @@ -42,22 +39,19 @@ pub async fn insert( inviter_id: Id, db: &Connection, ) -> Result<(), ServerError> { - run( + exec( db, "INSERT INTO invitation (community_id, user_id, inviter_id) VALUES (?1, ?2, ?3)", (community_id, user_id, inviter_id), ) - .await?; - - Ok(()) + .await } pub async fn take(community_id: Id, user_id: Id, db: &Connection) -> Result<(), ServerError> { - let deleted = run( + exec_one( db, "DELETE FROM invitation WHERE community_id = ?1 AND user_id = ?2", (community_id, user_id), ) - .await?; - ensure_with(deleted == 1, Error::NotFound) + .await } diff --git a/crates/server/src/db/log.rs b/crates/server/src/db/log.rs index 7798126..7eef9ce 100644 --- a/crates/server/src/db/log.rs +++ b/crates/server/src/db/log.rs @@ -1,19 +1,12 @@ use common::{ constant::LOG_PAGE_LIMIT, - model::{AdminAction, AdminActionKind, AdminLogEntry, Id, LogAction, LogEntry, User}, + model::{AdminAction, AdminActionKind, AdminLogEntry, Id, LogAction, LogEntry}, time::now_ms, }; -use super::{Connection, all, run, user}; +use super::{Connection, all, community, exec, user}; use crate::error::ServerError; -pub async fn optional_user(id: Option, db: &Connection) -> Result, ServerError> { - match id { - Some(id) => Ok(Some(user::read(id, db).await?)), - None => Ok(None), - } -} - pub async fn record( community_id: Id, actor_id: Option, @@ -21,14 +14,12 @@ pub async fn record( action: &LogAction, db: &Connection, ) -> Result<(), ServerError> { - run( + exec( db, "INSERT INTO community_log (community_id, created_at, actor_id, target_id, action) VALUES (?1, ?2, ?3, ?4, ?5)", (community_id, now_ms(), actor_id, target_id, bitcode::encode(action)), ) - .await?; - - Ok(()) + .await } pub async fn list(community_id: Id, db: &Connection) -> Result, ServerError> { @@ -53,8 +44,8 @@ pub async fn list(community_id: Id, db: &Connection) -> Result, Se entries.push(LogEntry { id, created_at, - actor: optional_user(actor_id, db).await?, - target: optional_user(target_id, db).await?, + actor: user::read_optional(actor_id, db).await?, + target: user::read_optional(target_id, db).await?, action, }); } @@ -69,7 +60,7 @@ pub async fn record_admin( action: &AdminAction, db: &Connection, ) -> Result<(), ServerError> { - run( + exec( db, "INSERT INTO admin_log (created_at, actor_id, target_id, community, kind, action) VALUES (?1, ?2, ?3, ?4, ?5, ?6)", ( @@ -81,9 +72,7 @@ pub async fn record_admin( bitcode::encode(action), ), ) - .await?; - - Ok(()) + .await } pub async fn list_admin( @@ -122,8 +111,8 @@ pub async fn list_admin( for (id, created_at, actor_id, target_id, community, action) in raws { entries.push(AdminLogEntry { id, - actor: optional_user(actor_id, db).await?, - target: optional_user(target_id, db).await?, + actor: user::read_optional(actor_id, db).await?, + target: user::read_optional(target_id, db).await?, created_at, community, action, @@ -142,7 +131,7 @@ pub async fn list_communities( ) -> Result, ServerError> { let raws = all( db, - "SELECT l.id, l.created_at, l.actor_id, l.target_id, c.name, l.action FROM community_log l JOIN community c ON c.id = l.community_id WHERE (?1 IS NULL OR l.actor_id = ?1) AND (?2 IS NULL OR l.target_id = ?2) AND (?3 IS NULL OR l.created_at >= ?3) AND (?4 IS NULL OR l.created_at < ?4) ORDER BY l.id DESC LIMIT ?5", + "SELECT l.id, l.created_at, l.actor_id, l.target_id, l.community_id, l.action FROM community_log l JOIN community c ON c.id = l.community_id WHERE (?1 IS NULL OR l.actor_id = ?1) AND (?2 IS NULL OR l.target_id = ?2) AND (?3 IS NULL OR l.created_at >= ?3) AND (?4 IS NULL OR l.created_at < ?4) ORDER BY l.id DESC LIMIT ?5", ( actor_id, target_id, @@ -156,7 +145,7 @@ pub async fn list_communities( r.get::()?, r.get::>()?, r.get::>()?, - r.get::()?, + r.get::()?, r.blob::()?, )) }, @@ -164,13 +153,13 @@ pub async fn list_communities( .await?; let mut entries = Vec::new(); - for (id, created_at, actor_id, target_id, community, action) in raws { + for (id, created_at, actor_id, target_id, community_id, action) in raws { entries.push(AdminLogEntry { id, - actor: optional_user(actor_id, db).await?, - target: optional_user(target_id, db).await?, + actor: user::read_optional(actor_id, db).await?, + target: user::read_optional(target_id, db).await?, created_at, - community: Some(community), + community: Some(community::label(community_id, db).await?), action: AdminAction::Community(action), }); } diff --git a/crates/server/src/db/member.rs b/crates/server/src/db/member.rs index a686af4..1be709e 100644 --- a/crates/server/src/db/member.rs +++ b/crates/server/src/db/member.rs @@ -2,7 +2,7 @@ use std::collections::HashMap; use common::model::{Ban, Id, Member, Rank, Unread, mentions}; -use super::{Connection, all, community, maybe, one, run, user}; +use super::{Connection, all, community, exec, maybe, one, run, user}; use crate::error::ServerError; pub async fn join( @@ -11,14 +11,12 @@ pub async fn join( rank: Rank, db: &Connection, ) -> Result<(), ServerError> { - run( + exec( db, "INSERT INTO member (user_id, community_id, rank) VALUES (?1, ?2, ?3)", (user_id, community_id, rank.as_str()), ) - .await?; - - Ok(()) + .await } pub async fn leave(user_id: Id, community_id: Id, db: &Connection) -> Result { @@ -50,14 +48,12 @@ pub async fn set_rank( rank: Rank, db: &Connection, ) -> Result<(), ServerError> { - run( + exec( db, "UPDATE member SET rank = ?3 WHERE user_id = ?1 AND community_id = ?2", (user_id, community_id, rank.as_str()), ) - .await?; - - Ok(()) + .await } pub async fn mark_read( @@ -66,14 +62,12 @@ pub async fn mark_read( message_id: Id, db: &Connection, ) -> Result<(), ServerError> { - run( + exec( db, "UPDATE member SET last_read = ?3 WHERE user_id = ?1 AND community_id = ?2 AND (last_read IS NULL OR last_read < ?3)", (user_id, community_id, message_id), ) - .await?; - - Ok(()) + .await } pub async fn unreads( @@ -180,25 +174,21 @@ pub async fn ban( reason: Option<&str>, db: &Connection, ) -> Result<(), ServerError> { - run( + exec( db, "INSERT OR REPLACE INTO community_ban (user_id, community_id, reason) VALUES (?1, ?2, ?3)", (user_id, community_id, reason), ) - .await?; - - Ok(()) + .await } pub async fn unban(user_id: Id, community_id: Id, db: &Connection) -> Result<(), ServerError> { - run( + exec( db, "DELETE FROM community_ban WHERE user_id = ?1 AND community_id = ?2", (user_id, community_id), ) - .await?; - - Ok(()) + .await } pub async fn is_banned( diff --git a/crates/server/src/db/message.rs b/crates/server/src/db/message.rs index 0cef531..baea4f0 100644 --- a/crates/server/src/db/message.rs +++ b/crates/server/src/db/message.rs @@ -150,13 +150,13 @@ pub async fn create( } pub async fn read(id: Id, db: &Connection) -> Result { - let message = read_any(id, db).await?; + let message = load(id, db).await?; ensure_with(!message.deleted, Error::NotFound)?; Ok(message) } -pub async fn read_any(id: Id, db: &Connection) -> Result { +async fn load(id: Id, db: &Connection) -> Result { let mut message = one(db, &format!("{SELECT} WHERE m.id = ?1"), (id,), row).await?; message.reactions = reactions(id, db).await?; message.poll = poll::of(id, db).await?; @@ -169,7 +169,7 @@ pub async fn read_any(id: Id, db: &Connection) -> Result { async fn read_all(ids: Vec, db: &Connection) -> Result, ServerError> { let mut messages = Vec::new(); for id in ids { - messages.push(read_any(id, db).await?); + messages.push(load(id, db).await?); } Ok(messages) @@ -414,43 +414,41 @@ async fn entry(source: &Message, db: &Connection) -> Result Result, ServerError> { - if mode == ForwardMode::Copy { - let mut created = Vec::new(); - for source in sources { - let id = insert(user_id, community_id, &source.body, None, db).await?; - for attachment in &source.attachments { - attachment::copy_row(attachment.id, id, user_id, community_id, None, db).await?; - } - if let Some(inner) = &source.snippet { - snippet::write( - id, - user_id, - community_id, - inner.origin.as_deref(), - &inner.messages, - db, - ) - .await?; - } - created.push(read(id, db).await?); + let mut created = Vec::new(); + for source in sources { + let id = insert(user_id, community_id, &source.body, None, db).await?; + for attachment in &source.attachments { + attachment::copy_row(attachment.id, id, user_id, community_id, None, db).await?; } - - return Ok(created); + if let Some(inner) = &source.snippet { + snippet::write( + id, + user_id, + community_id, + inner.origin.as_deref(), + &inner.messages, + db, + ) + .await?; + } + created.push(read(id, db).await?); } + Ok(created) +} + +pub async fn forward_snippet( + user_id: Id, + community_id: Id, + sources: &[Message], + db: &Connection, +) -> Result, ServerError> { let mut entries = Vec::new(); for source in sources { match &source.snippet { @@ -483,7 +481,7 @@ mod tests { use common::model::Reply; - use super::{ForwardMode, create, delete, edits, forward, read, read_page, update}; + use super::{create, delete, edits, forward_snippet, read, read_page, update}; use crate::{ db::{community, user}, test, @@ -592,15 +590,9 @@ mod tests { .await .unwrap(); - let created = forward( - user.id, - community, - &[first, second], - ForwardMode::Snippet, - &conn, - ) - .await - .unwrap(); + let created = forward_snippet(user.id, community, &[first, second], &conn) + .await + .unwrap(); assert_eq!(1, created.len()); assert_eq!(2, created[0].snippet.as_ref().unwrap().messages.len()); diff --git a/crates/server/src/db/mod.rs b/crates/server/src/db/mod.rs index ec291ff..5b7be94 100644 --- a/crates/server/src/db/mod.rs +++ b/crates/server/src/db/mod.rs @@ -27,7 +27,7 @@ use turso::{Builder, Database, IntoParams, Row, core::types::FromValue}; pub use turso::Connection; -use crate::error::ServerError; +use crate::error::{ServerError, ensure_with}; const SCHEMA: &str = include_str!("schema.sql"); @@ -149,7 +149,11 @@ pub async fn maybe( params: impl IntoParams, read: impl Fn(&mut Reader) -> Result, ) -> Result, ServerError> { - Ok(all(db, sql, params, read).await?.into_iter().next()) + let mut rows = db.prepare_cached(sql).await?.query(params).await?; + rows.next() + .await? + .map(|row| read(&mut Reader { row: &row, at: 0 })) + .transpose() } pub async fn one( @@ -166,3 +170,16 @@ pub async fn one( pub async fn run(db: &Connection, sql: &str, params: impl IntoParams) -> Result { Ok(db.prepare_cached(sql).await?.execute(params).await?) } + +pub async fn exec(db: &Connection, sql: &str, params: impl IntoParams) -> Result<(), ServerError> { + run(db, sql, params).await?; + Ok(()) +} + +pub async fn exec_one( + db: &Connection, + sql: &str, + params: impl IntoParams, +) -> Result<(), ServerError> { + ensure_with(run(db, sql, params).await? == 1, Error::NotFound) +} diff --git a/crates/server/src/db/registration_code.rs b/crates/server/src/db/registration_code.rs index 5869fa4..0952912 100644 --- a/crates/server/src/db/registration_code.rs +++ b/crates/server/src/db/registration_code.rs @@ -4,7 +4,7 @@ use common::{ time::{HOUR_MILLIS, now_ms}, }; -use super::{Connection, all, run}; +use super::{Connection, all, exec, exec_one, run}; use crate::error::{ServerError, ensure_with}; pub async fn create( @@ -14,7 +14,7 @@ pub async fn create( db: &Connection, ) -> Result { let expires_at = hours.map(|hours| now_ms() + u64::from(hours) * HOUR_MILLIS); - run( + exec( db, "INSERT INTO registration_code (code, uses_left, expires_at) VALUES (?1, ?2, ?3)", (code, uses, expires_at.map(|ms| ms as i64)), @@ -45,8 +45,7 @@ pub async fn list(db: &Connection) -> Result, ServerError> { } pub async fn delete(code: &str, db: &Connection) -> Result<(), ServerError> { - let deleted = run(db, "DELETE FROM registration_code WHERE code = ?1", (code,)).await?; - ensure_with(deleted == 1, Error::NotFound) + exec_one(db, "DELETE FROM registration_code WHERE code = ?1", (code,)).await } pub async fn consume(code: &str, db: &Connection) -> Result<(), ServerError> { diff --git a/crates/server/src/db/release.rs b/crates/server/src/db/release.rs index cfd2e0f..9c81aea 100644 --- a/crates/server/src/db/release.rs +++ b/crates/server/src/db/release.rs @@ -1,6 +1,6 @@ use common::{model::Staged, time::now_ms, update::Sha}; -use super::{Connection, all, maybe, one, run}; +use super::{Connection, all, exec, exec_one, maybe, one}; use crate::error::ServerError; pub struct Entry { @@ -25,16 +25,6 @@ fn staged(r: &mut super::Reader) -> Result { }) } -pub async fn seq_of(file: &Sha, db: &Connection) -> Result, ServerError> { - maybe( - db, - "SELECT seq FROM release_file WHERE file = ?1", - (&file[..],), - |r| r.get(), - ) - .await -} - pub async fn of_file(file: &Sha, db: &Connection) -> Result, ServerError> { maybe( db, @@ -91,7 +81,7 @@ pub async fn insert(required: bool, files: &[Staged], db: &Connection) -> Result ) .await?; for file in files { - run( + exec( db, "INSERT INTO release_file (file, seq, target, size, packed) VALUES (?1, ?2, ?3, ?4, ?5)", (&file.file[..], seq, file.target.as_str(), file.size, file.packed), @@ -103,17 +93,12 @@ pub async fn insert(required: bool, files: &[Staged], db: &Connection) -> Result } pub async fn set_required(seq: u64, required: bool, db: &Connection) -> Result<(), ServerError> { - let changed = run( + exec_one( db, "UPDATE release SET required = ?2 WHERE seq = ?1", (seq, required), ) - .await?; - if changed == 0 { - return Err(common::error::Error::NotFound.into()); - } - - Ok(()) + .await } pub async fn entry(seq: u64, db: &Connection) -> Result { diff --git a/crates/server/src/db/report.rs b/crates/server/src/db/report.rs index a941746..0da1a38 100644 --- a/crates/server/src/db/report.rs +++ b/crates/server/src/db/report.rs @@ -1,10 +1,11 @@ use common::{ constant::LOG_PAGE_LIMIT, + error::Error, model::{Id, Report, ReportStatus}, time::now_ms, }; -use super::{Connection, all, log::optional_user, one, run}; +use super::{Connection, all, community, exec, one, user}; use crate::error::ServerError; struct Raw { @@ -12,7 +13,6 @@ struct Raw { created_at: u64, reporter_id: Option, target_id: Option, - community: Option, message_id: Option, community_id: Option, body: Option, @@ -45,7 +45,7 @@ pub async fn insert( reason: &str, db: &Connection, ) -> Result<(), ServerError> { - run( + exec( db, "INSERT INTO report (created_at, reporter_id, target_id, message_id, community_id, body, reason, status) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", ( @@ -59,9 +59,7 @@ pub async fn insert( ReportStatus::Open.as_str(), ), ) - .await?; - - Ok(()) + .await } pub async fn list( @@ -70,7 +68,7 @@ pub async fn list( ) -> Result, ServerError> { let raws = all( db, - "SELECT r.id, r.created_at, r.reporter_id, r.target_id, c.name, r.message_id, r.community_id, r.body, r.reason, r.status, r.handled_by FROM report r LEFT JOIN community c ON c.id = r.community_id WHERE ?1 IS NULL OR r.status = ?1 ORDER BY r.id DESC LIMIT ?2", + "SELECT id, created_at, reporter_id, target_id, message_id, community_id, body, reason, status, handled_by FROM report WHERE ?1 IS NULL OR status = ?1 ORDER BY id DESC LIMIT ?2", (status.map(ReportStatus::as_str), LOG_PAGE_LIMIT), |r| { Ok(Raw { @@ -78,7 +76,6 @@ pub async fn list( created_at: r.get()?, reporter_id: r.get()?, target_id: r.get()?, - community: r.get()?, message_id: r.get()?, community_id: r.get()?, body: r.get()?, @@ -92,18 +89,26 @@ pub async fn list( let mut reports = Vec::new(); for raw in raws { + let community = match raw.community_id { + Some(id) => match community::label(id, db).await { + Ok(label) => Some(label), + Err(ServerError::Wire(Error::NotFound)) => None, + Err(error) => return Err(error), + }, + None => None, + }; reports.push(Report { id: raw.id, created_at: raw.created_at, - reporter: optional_user(raw.reporter_id, db).await?, - target: optional_user(raw.target_id, db).await?, + reporter: user::read_optional(raw.reporter_id, db).await?, + target: user::read_optional(raw.target_id, db).await?, message_id: raw.message_id, community_id: raw.community_id, - community: raw.community, + community, body: raw.body, reason: raw.reason, status: raw.status, - handled_by: optional_user(raw.handled_by, db).await?, + handled_by: user::read_optional(raw.handled_by, db).await?, }); } diff --git a/crates/server/src/db/server_ban.rs b/crates/server/src/db/server_ban.rs index 580adf0..1f72a6e 100644 --- a/crates/server/src/db/server_ban.rs +++ b/crates/server/src/db/server_ban.rs @@ -1,10 +1,7 @@ -use common::{ - error::Error, - model::{Id, ServerBan, ServerBanKind}, -}; +use common::model::{Id, ServerBan, ServerBanKind}; -use super::{Connection, all, one, run}; -use crate::error::{ServerError, ensure_with}; +use super::{Connection, all, exec, exec_one, one}; +use crate::error::ServerError; pub async fn insert( kind: ServerBanKind, @@ -12,14 +9,12 @@ pub async fn insert( reason: Option<&str>, db: &Connection, ) -> Result<(), ServerError> { - run( + exec( db, "INSERT OR IGNORE INTO server_ban (kind, value, reason) VALUES (?1, ?2, ?3)", (kind.as_str(), value, reason), ) - .await?; - - Ok(()) + .await } pub async fn list(db: &Connection) -> Result, ServerError> { @@ -39,7 +34,11 @@ pub async fn list(db: &Connection) -> Result, ServerError> { .await } -async fn exists(kind: ServerBanKind, value: &str, db: &Connection) -> Result { +pub async fn banned( + kind: ServerBanKind, + value: &str, + db: &Connection, +) -> Result { one( db, "SELECT EXISTS (SELECT 1 FROM server_ban WHERE kind = ?1 AND value = ?2)", @@ -49,15 +48,6 @@ async fn exists(kind: ServerBanKind, value: &str, db: &Connection) -> Result Result { - exists(ServerBanKind::Username, username, db).await -} - -pub async fn ip_banned(ip: &str, db: &Connection) -> Result { - exists(ServerBanKind::Ip, ip, db).await -} - pub async fn remove(id: Id, db: &Connection) -> Result<(), ServerError> { - let deleted = run(db, "DELETE FROM server_ban WHERE id = ?1", (id,)).await?; - ensure_with(deleted == 1, Error::NotFound) + exec_one(db, "DELETE FROM server_ban WHERE id = ?1", (id,)).await } diff --git a/crates/server/src/db/session.rs b/crates/server/src/db/session.rs index d856e9c..e45b93c 100644 --- a/crates/server/src/db/session.rs +++ b/crates/server/src/db/session.rs @@ -3,7 +3,7 @@ use common::{ time::now_ms, }; -use super::{Connection, all, maybe, one, run, user}; +use super::{Connection, all, exec, maybe, one, run, user}; use crate::error::ServerError; pub async fn insert(token_hash: &[u8], user_id: Id, db: &Connection) -> Result { @@ -44,31 +44,27 @@ pub async fn user_of(session_id: Id, db: &Connection) -> Result, Se pub async fn seen(session_id: Id, db: &Connection) -> Result<(), ServerError> { let now = now_ms(); - run( + exec( db, "UPDATE user SET last_seen = ?2 WHERE id = (SELECT user_id FROM session WHERE id = ?1) AND ghost = 0", (session_id, now), ) .await?; - run( + exec( db, "UPDATE session SET last_seen = ?2 WHERE id = ?1 AND user_id IN (SELECT id FROM user WHERE ghost = 0)", (session_id, now), ) - .await?; - - Ok(()) + .await } pub async fn set_device(session_id: Id, device: &str, db: &Connection) -> Result<(), ServerError> { - run( + exec( db, "UPDATE session SET device = ?2 WHERE id = ?1", (session_id, device), ) - .await?; - - Ok(()) + .await } pub async fn list(user_id: Id, db: &Connection) -> Result, ServerError> { @@ -88,9 +84,7 @@ pub async fn list(user_id: Id, db: &Connection) -> Result, Serv } pub async fn delete(session_id: Id, db: &Connection) -> Result<(), ServerError> { - run(db, "DELETE FROM session WHERE id = ?1", (session_id,)).await?; - - Ok(()) + exec(db, "DELETE FROM session WHERE id = ?1", (session_id,)).await } pub async fn delete_of(user_id: Id, session_id: Id, db: &Connection) -> Result { @@ -103,7 +97,5 @@ pub async fn delete_of(user_id: Id, session_id: Id, db: &Connection) -> Result Result<(), ServerError> { - run(db, "DELETE FROM session WHERE user_id = ?1", (user_id,)).await?; - - Ok(()) + exec(db, "DELETE FROM session WHERE user_id = ?1", (user_id,)).await } diff --git a/crates/server/src/db/settings.rs b/crates/server/src/db/settings.rs index 3880a9e..26dc58c 100644 --- a/crates/server/src/db/settings.rs +++ b/crates/server/src/db/settings.rs @@ -1,6 +1,6 @@ use common::model::ServerSettings; -use super::{Connection, maybe, run}; +use super::{Connection, exec, maybe}; use crate::error::ServerError; pub async fn read(db: &Connection) -> Result { @@ -15,12 +15,10 @@ pub async fn read(db: &Connection) -> Result { } pub async fn update(settings: &ServerSettings, db: &Connection) -> Result<(), ServerError> { - run( + exec( db, "INSERT OR REPLACE INTO server_settings (id, data) VALUES (1, ?1)", (bitcode::encode(settings),), ) - .await?; - - Ok(()) + .await } diff --git a/crates/server/src/db/stats.rs b/crates/server/src/db/stats.rs index b9e9bb8..e92b6fc 100644 --- a/crates/server/src/db/stats.rs +++ b/crates/server/src/db/stats.rs @@ -5,20 +5,18 @@ use common::{ time::{DAY_MILLIS, now_ms}, }; -use super::{Connection, all, community::Kind, one, run}; +use super::{Connection, all, community::Kind, exec, one}; use crate::error::ServerError; const MAXIMUM_DAYS: u32 = 90; pub async fn mark_active(user_id: Id, db: &Connection) -> Result<(), ServerError> { - run( + exec( db, "INSERT OR IGNORE INTO daily_active (day, user_id) SELECT ?1, id FROM user WHERE id = ?2 AND ghost = 0", (now_ms() / DAY_MILLIS, user_id), ) - .await?; - - Ok(()) + .await } pub async fn daily(days: u32, db: &Connection) -> Result, ServerError> { diff --git a/crates/server/src/db/user.rs b/crates/server/src/db/user.rs index 87948ac..54a45cd 100644 --- a/crates/server/src/db/user.rs +++ b/crates/server/src/db/user.rs @@ -1,12 +1,11 @@ use common::{ - error::Error, - model::{Account, Hue, Id, Presence, Role, User}, + model::{Account, Hue, Id, Presence, Role, Suspension, User}, permission, time::now_ms, }; -use super::{Connection, Reader, all, maybe, one, run}; -use crate::error::{ServerError, ensure_with}; +use super::{Connection, Reader, all, exec, exec_one, maybe, one}; +use crate::error::ServerError; pub const COLUMNS: &str = "user.id, user.username, user.role, user.status, user.hue, (SELECT avatar.id FROM avatar WHERE avatar.user_id = user.id), user.created_at"; @@ -34,6 +33,13 @@ pub async fn read(id: Id, db: &Connection) -> Result { .await } +pub async fn read_optional(id: Option, db: &Connection) -> Result, ServerError> { + match id { + Some(id) => read(id, db).await.map(Some), + None => Ok(None), + } +} + pub async fn create( username: &str, password_hash: &str, @@ -84,8 +90,8 @@ pub async fn password_hash_of( .await } -pub async fn update(id: Id, username: &str, db: &Connection) -> Result { - run( +pub async fn rename(id: Id, username: &str, db: &Connection) -> Result { + exec_one( db, "UPDATE user SET username = ?2 WHERE id = ?1", (id, username), @@ -95,8 +101,8 @@ pub async fn update(id: Id, username: &str, db: &Connection) -> Result, db: &Connection) -> Result { - run( +pub async fn set_hue(id: Id, hue: Option, db: &Connection) -> Result { + exec_one( db, "UPDATE user SET hue = ?2 WHERE id = ?1", (id, hue.map(|hue| hue.as_str())), @@ -106,8 +112,8 @@ pub async fn update_hue(id: Id, hue: Option, db: &Connection) -> Result Result { - run( +pub async fn set_status(id: Id, status: &str, db: &Connection) -> Result { + exec_one( db, "UPDATE user SET status = ?2 WHERE id = ?1", (id, status), @@ -117,8 +123,8 @@ pub async fn update_status(id: Id, status: &str, db: &Connection) -> Result Result { - run( +pub async fn set_role(id: Id, role: Role, db: &Connection) -> Result { + exec_one( db, "UPDATE user SET role = ?2 WHERE id = ?1", (id, role.as_str()), @@ -128,7 +134,15 @@ pub async fn set_role_by_id(id: Id, role: Role, db: &Connection) -> Result Result>, ServerError> { +fn suspension(suspended: bool, until: Option) -> Suspension { + match (suspended, until) { + (true, _) => Suspension::Indefinite, + (false, Some(until)) => Suspension::Until(until), + (false, None) => Suspension::None, + } +} + +pub async fn suspension_of(id: Id, db: &Connection) -> Result { let (suspended, until): (bool, Option) = one( db, "SELECT suspended, suspended_until FROM user WHERE id = ?1", @@ -137,28 +151,23 @@ pub async fn suspended(id: Id, db: &Connection) -> Result>, S ) .await?; - if suspended { - return Ok(Some(None)); - } - - Ok(until.filter(|until| *until > now_ms()).map(Some)) + Ok(suspension( + suspended, + until.filter(|until| *until > now_ms()), + )) } pub async fn set_timeout(id: Id, until: Option, db: &Connection) -> Result<(), ServerError> { - run( + exec( db, - "UPDATE user SET suspended_until = ?2 WHERE id = ?1", + "UPDATE user SET suspended = 0, suspended_until = ?2 WHERE id = ?1", (id, until.map(|ms| ms as i64)), ) - .await?; - - Ok(()) + .await } pub async fn set_last_ip(id: Id, ip: &str, db: &Connection) -> Result<(), ServerError> { - run(db, "UPDATE user SET last_ip = ?2 WHERE id = ?1", (id, ip)).await?; - - Ok(()) + exec(db, "UPDATE user SET last_ip = ?2 WHERE id = ?1", (id, ip)).await } pub async fn last_ip(id: Id, db: &Connection) -> Result, ServerError> { @@ -169,13 +178,13 @@ pub async fn last_ip(id: Id, db: &Connection) -> Result, ServerEr } pub async fn make_builder(id: Id, db: &Connection) -> Result { - run( + exec( db, - "UPDATE user SET role = ?2 WHERE role = ?1 AND id != ?3", - (Role::Builder.as_str(), Role::User.as_str(), id), + "UPDATE user SET role = ?1 WHERE role = ?2 AND id != ?3", + (Role::User.as_str(), Role::Builder.as_str(), id), ) .await?; - set_role_by_id(id, Role::Builder, db).await + set_role(id, Role::Builder, db).await } pub async fn builder_ids(db: &Connection) -> Result, ServerError> { @@ -189,41 +198,32 @@ pub async fn builder_ids(db: &Connection) -> Result, ServerError> { } pub async fn set_suspended(id: Id, suspended: bool, db: &Connection) -> Result<(), ServerError> { - run( + exec( db, - "UPDATE user SET suspended = ?2 WHERE id = ?1", + "UPDATE user SET suspended = ?2, suspended_until = NULL WHERE id = ?1", (id, suspended), ) - .await?; - - Ok(()) + .await } pub async fn set_voice_muted(id: Id, muted: bool, db: &Connection) -> Result<(), ServerError> { - run( + exec( db, "UPDATE user SET voice_muted = ?2 WHERE id = ?1", (id, muted), ) - .await?; - - Ok(()) + .await } pub async fn set_ghost(id: Id, ghost: bool, db: &Connection) -> Result<(), ServerError> { - run(db, "UPDATE user SET ghost = ?2 WHERE id = ?1", (id, ghost)).await?; - - Ok(()) + exec(db, "UPDATE user SET ghost = ?2 WHERE id = ?1", (id, ghost)).await } pub async fn is_ghost(id: Id, db: &Connection) -> Result { - Ok( - maybe(db, "SELECT ghost FROM user WHERE id = ?1", (id,), |r| { - r.get() - }) - .await? - .unwrap_or(false), - ) + one(db, "SELECT ghost FROM user WHERE id = ?1", (id,), |r| { + r.get() + }) + .await } pub async fn presence(id: Id, db: &Connection) -> Result { @@ -233,19 +233,13 @@ pub async fn presence(id: Id, db: &Connection) -> Result .await } -pub async fn update_presence( - id: Id, - presence: Presence, - db: &Connection, -) -> Result<(), ServerError> { - run( +pub async fn set_presence(id: Id, presence: Presence, db: &Connection) -> Result<(), ServerError> { + exec( db, "UPDATE user SET presence = ?2 WHERE id = ?1", (id, presence.as_str()), ) - .await?; - - Ok(()) + .await } pub async fn voice_muted(id: Id, db: &Connection) -> Result { @@ -265,14 +259,12 @@ pub async fn set_password_hash( password_hash: &str, db: &Connection, ) -> Result<(), ServerError> { - run( + exec( db, "UPDATE user SET password_hash = ?2 WHERE id = ?1", (id, password_hash), ) - .await?; - - Ok(()) + .await } pub async fn all_accounts(db: &Connection) -> Result, ServerError> { @@ -281,11 +273,14 @@ pub async fn all_accounts(db: &Connection) -> Result, ServerError> &format!("SELECT {COLUMNS}, user.suspended, user.last_seen, user.suspended_until, user.ghost FROM user ORDER BY user.username"), (), |r| { + let user = row(r)?; + let suspended: bool = r.get()?; + let last_seen: Option = r.get()?; + let until: Option = r.get()?; Ok(Account { - user: row(r)?, - suspended: r.get()?, - last_seen: r.get()?, - suspended_until: r.get()?, + user, + suspension: suspension(suspended, until), + last_seen, ghost: r.get()?, }) }, @@ -294,10 +289,7 @@ pub async fn all_accounts(db: &Connection) -> Result, ServerError> } pub async fn delete(id: Id, db: &Connection) -> Result<(), ServerError> { - ensure_with( - run(db, "DELETE FROM user WHERE id = ?1", (id,)).await? == 1, - Error::NotFound, - ) + exec_one(db, "DELETE FROM user WHERE id = ?1", (id,)).await } #[cfg(test)] @@ -328,7 +320,7 @@ mod tests { let db = test::db().await; let conn = db.lock().await.unwrap(); - let updated_user = user::update(404, "Not Tahinli", &conn).await; + let updated_user = user::rename(404, "Not Tahinli", &conn).await; assert!(matches!( updated_user, diff --git a/crates/server/src/error.rs b/crates/server/src/error.rs index 073ee1f..56e62dc 100644 --- a/crates/server/src/error.rs +++ b/crates/server/src/error.rs @@ -75,5 +75,4 @@ internal_from! { bitcode::Error, common::config::ConfigError, common::frame::FrameError, - tokio::time::error::Elapsed, } diff --git a/crates/server/src/files.rs b/crates/server/src/files.rs index affed8e..ef78952 100644 --- a/crates/server/src/files.rs +++ b/crates/server/src/files.rs @@ -4,6 +4,7 @@ use std::{ time::{Duration, SystemTime}, }; +use bitcode::Encode; use common::{ constant::{ ATTACHMENT_CHUNK_BYTES, ATTACHMENT_HEAD_BYTES, AVATAR_SIZE, MAXIMUM_AVATAR_BYTES, @@ -217,7 +218,7 @@ pub async fn store( user.role, db::member::rank(user.id, header.community_id, conn).await?, ); - ensure(permission::can_post(rank))?; + ensure(permission::is_member(rank))?; validate_attachment_name(&header.name)?; let settings = db::settings::read(conn).await?; validate_attachment_size(header.size, settings.max_attachment_bytes)?; @@ -265,11 +266,28 @@ pub async fn store( stored } +pub(crate) async fn reply_upload( + result: Result, + mut send_stream: Sending, + mut receive_stream: RecvStream, +) -> Result<(), ServerError> { + let rejected = result.is_err(); + let reply = result.map_err(CommonError::from); + + frame::write(&mut send_stream, &reply, DOWN_MAX).await?; + send_stream.finish()?; + if rejected { + let _ = receive_stream.stop(VarInt::from_u32(0)); + } + + Ok(()) +} + pub async fn upload( user: Option<&User>, header: Upload, mut receive_stream: RecvStream, - mut send_stream: Sending, + send_stream: Sending, db: &Db, directory: &Path, ) -> Result<(), ServerError> { @@ -277,16 +295,8 @@ pub async fn upload( Some(user) => store(user, &header, &mut receive_stream, db, directory).await, None => Err(CommonError::Unauthenticated.into()), }; - let rejected = stored.is_err(); - let reply = stored.map_err(CommonError::from); - frame::write(&mut send_stream, &reply, DOWN_MAX).await?; - send_stream.finish()?; - if rejected { - let _ = receive_stream.stop(VarInt::from_u32(0)); - } - - Ok(()) + reply_upload(stored, send_stream, receive_stream).await } async fn locate( @@ -304,7 +314,7 @@ async fn locate( user.role, db::member::rank(user.id, stored.community_id, conn).await?, ); - ensure(permission::can_read(rank))?; + ensure(permission::is_member(rank))?; ensure(stored.message_id.is_some() || stored.uploader_id == user.id)?; Ok(stored) @@ -346,14 +356,7 @@ pub async fn fetch( if let Ok((path, _)) = located { let mut file = File::open(path).await?; - let mut buffer = vec![0u8; ATTACHMENT_CHUNK_BYTES]; - loop { - let read = file.read(&mut buffer).await?; - if read == 0 { - break; - } - send_stream.get().write_all(&buffer[..read]).await?; - } + tokio::io::copy(&mut file, send_stream.get()).await?; } send_stream.finish()?; diff --git a/crates/server/src/forge.rs b/crates/server/src/forge.rs index fe86eec..2e2650e 100644 --- a/crates/server/src/forge.rs +++ b/crates/server/src/forge.rs @@ -1,49 +1,48 @@ -use std::io::Read; +use std::{io::Read, time::Duration}; use common::{error::ReleaseProblem, update::FILE_MAX}; use serde::Deserialize; +const TIMEOUT: Duration = Duration::from_secs(300); + pub struct Forge { repo: String, api: String, token: Option, + agent: ureq::Agent, } +#[derive(Deserialize)] pub struct Asset { - pub name: String, + #[serde(rename = "browser_download_url")] pub url: String, pub sha256: String, } #[derive(Deserialize)] struct Release { - assets: Vec, -} - -#[derive(Deserialize)] -struct AssetJson { - name: String, - browser_download_url: String, - sha256: String, + assets: Vec, } impl Forge { pub fn new(repo: &str, token: Option) -> Option { - let (host, path) = repo - .trim_end_matches('/') - .split_once("://")? - .1 - .split_once('/')?; - let scheme = repo.split_once("://")?.0; + let repo = repo.trim_end_matches('/'); + let (scheme, rest) = repo.split_once("://")?; + let (host, path) = rest.split_once('/')?; Some(Self { - repo: repo.trim_end_matches('/').to_string(), + repo: repo.to_string(), api: format!("{scheme}://{host}/api/v1/repos/{path}"), token, + agent: ureq::Agent::new_with_config( + ureq::Agent::config_builder() + .timeout_global(Some(TIMEOUT)) + .build(), + ), }) } fn get(&self, url: &str) -> ureq::RequestBuilder { - let request = ureq::get(url); + let request = self.agent.get(url); match &self.token { Some(token) => request.header("Authorization", format!("token {token}")), None => request, @@ -56,7 +55,9 @@ impl Forge { pub fn create_tag(&self, tag: &str) -> Result<(), ReleaseProblem> { let token = self.token.as_ref().ok_or(ReleaseProblem::TagRefused)?; - let response = ureq::post(format!("{}/tags", self.api)) + let response = self + .agent + .post(format!("{}/tags", self.api)) .header("Authorization", format!("token {token}")) .config() .http_status_as_error(false) @@ -76,15 +77,8 @@ impl Forge { .call() .and_then(|mut response| response.body_mut().read_json()) .map_err(|_| ReleaseProblem::Forge)?; - Ok(release - .assets - .into_iter() - .map(|asset| Asset { - name: asset.name, - url: asset.browser_download_url, - sha256: asset.sha256, - }) - .collect()) + + Ok(release.assets) } pub fn download(&self, asset: &Asset) -> Result, ReleaseProblem> { diff --git a/crates/server/src/hub.rs b/crates/server/src/hub.rs index 3b15eb4..b925022 100644 --- a/crates/server/src/hub.rs +++ b/crates/server/src/hub.rs @@ -7,11 +7,7 @@ use std::{ }; use bytes::Bytes; -use common::{ - model::Id, - transport::Close, - update::{Install, Sha}, -}; +use common::{model::Id, transport::Close, update::Install}; use quinn::Connection; use tokio::sync::mpsc::{self, error::TrySendError}; use tracing::warn; @@ -31,7 +27,6 @@ pub struct Client { pub id: ConnId, pub conn: Option, pub me: Option, - pub build: Option, pub install: Install, tx: mpsc::Sender, pub closed: AtomicBool, @@ -43,7 +38,6 @@ impl Client { pub fn new( conn: Option, me: Option, - build: Option, install: Install, ) -> (Arc, mpsc::Receiver) { let (tx, rx) = mpsc::channel(QUEUE_LENGTH); @@ -51,7 +45,6 @@ impl Client { id: NEXT_ID.fetch_add(1, Ordering::Relaxed), conn, me, - build, install, tx, closed: AtomicBool::new(false), @@ -62,8 +55,9 @@ impl Client { (client, rx) } + #[cfg(test)] pub fn detached(me: Option) -> Arc { - Self::new(None, me, None, Install::default()).0 + Self::new(None, me, Install::default()).0 } pub fn user_id(&self) -> Option { @@ -72,7 +66,7 @@ impl Client { pub fn close(&self, close: Close) { if let Some(conn) = &self.conn { - conn.close(close.code(), close.reason().as_bytes()); + close.on(conn); } } @@ -85,38 +79,24 @@ impl Client { } } -pub enum Presence { - None, - Online(Id), - Offline(Id), -} - #[derive(Clone, Default)] pub struct Hub(Arc>>>); impl Hub { - pub fn add(&self, client: Arc) -> Presence { + pub fn add(&self, client: Arc) -> Option { let mut clients = self.0.lock().unwrap(); let user_id = client.user_id(); let was_online = user_id.is_some_and(|user_id| Self::online_in(&clients, user_id)); clients.insert(client.id, client); - match user_id { - Some(user_id) if !was_online => Presence::Online(user_id), - _ => Presence::None, - } + user_id.filter(|_| !was_online) } - pub fn remove(&self, id: ConnId) -> Presence { + pub fn remove(&self, id: ConnId) -> Option { let mut clients = self.0.lock().unwrap(); - let Some(client) = clients.remove(&id) else { - return Presence::None; - }; + let user_id = clients.remove(&id)?.user_id()?; - match client.user_id() { - Some(user_id) if !Self::online_in(&clients, user_id) => Presence::Offline(user_id), - _ => Presence::None, - } + (!Self::online_in(&clients, user_id)).then_some(user_id) } fn online_in(clients: &HashMap>, user_id: Id) -> bool { diff --git a/crates/server/src/lib.rs b/crates/server/src/lib.rs index bd0325d..3616e16 100644 --- a/crates/server/src/lib.rs +++ b/crates/server/src/lib.rs @@ -2,7 +2,6 @@ pub mod authentication; pub mod backup; pub mod call; pub mod certificate; -pub mod datagram; pub mod db; pub mod error; pub mod files; @@ -11,7 +10,6 @@ pub mod hub; pub mod network; pub mod publish; pub mod rate_limit; -pub mod request; pub mod retention; pub mod rooms; pub mod stats; @@ -26,24 +24,20 @@ use common::{config::Config, error::Error as CommonError, model::Role}; use crate::{db::Db, error::ServerError}; -const SERVER_CONFIG_FILE_PATH: &str = concat!( - env!("CARGO_MANIFEST_DIR"), - "/../../configs/server_config.toml" -); - fn config_path() -> PathBuf { std::env::var_os("YUMUSH_CONFIG_DIR") - .map(|dir| PathBuf::from(dir).join("server_config.toml")) - .unwrap_or_else(|| PathBuf::from(SERVER_CONFIG_FILE_PATH)) + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from("configs")) + .join("server_config.toml") } -pub struct ServerConfig { - pub database_path: String, - pub server_address: String, - pub certificate_path: String, - pub key_path: String, - pub forge: Option, - pub forge_token: Option, +struct ServerConfig { + database_path: String, + server_address: String, + certificate_path: String, + key_path: String, + forge: Option, + forge_token: Option, } fn load_config() -> Result { @@ -70,9 +64,8 @@ fn sibling_directory(database_path: &str, name: &str) -> Result Result { +pub async fn run() -> Result { let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); - update::remember_exe(); let config = load_config()?; @@ -89,7 +82,6 @@ pub async fn showtime() -> Result { &database, ) .await?; - tokio::spawn(files::collect(database.clone(), attachments.clone())); network::serve( &config.server_address, @@ -112,7 +104,7 @@ pub async fn set_role(username: &str, role: Role) -> Result<(), ServerError> { .ok_or(CommonError::NotFound)?; match role { Role::Builder => db::user::make_builder(user.id, db).await?, - role => db::user::set_role_by_id(user.id, role, db).await?, + role => db::user::set_role(user.id, role, db).await?, }; Ok(()) diff --git a/crates/server/src/main.rs b/crates/server/src/main.rs index d60dbbb..47bfbf7 100644 --- a/crates/server/src/main.rs +++ b/crates/server/src/main.rs @@ -1,5 +1,5 @@ use common::model::Role; -use server::{network::Exit, set_role, showtime}; +use server::{network::Exit, run, set_role}; use std::os::unix::process::CommandExt; #[tokio::main] @@ -28,7 +28,7 @@ async fn main() -> Result<(), server::error::ServerError> { ["builder", username] => set_role(username, Role::Builder).await?, ["unbuilder", username] => set_role(username, Role::User).await?, _ => { - if let Exit::Restart = showtime().await? { + if let Exit::Restart = run().await? { let mut args = std::env::args_os(); let program = args.next().unwrap_or_default(); return Err(std::process::Command::new(program).args(args).exec().into()); diff --git a/crates/server/src/network.rs b/crates/server/src/network.rs index c85ef21..6de5898 100644 --- a/crates/server/src/network.rs +++ b/crates/server/src/network.rs @@ -1,12 +1,11 @@ -use crate::publish::{Broadcast, To}; -use common::event::Event; use std::{path::PathBuf, sync::Arc, sync::atomic::Ordering, time::Duration}; use bytes::Bytes; use common::{ call::{Login, Register, Request}, + event::Event, frame::{self, DOWN_MAX, Sending, UP_MAX}, - model::User, + model::{Id, ServerBanKind, User}, open::Open, session::{Hello, Welcome}, transport::{self, Close}, @@ -19,39 +18,36 @@ use tracing::{info, warn}; use crate::{ authentication, call::{self, Cx}, - datagram, db::{self, Db}, error::ServerError, files, - hub::{Client, Hub, Presence, Signed}, - publish, + hub::{Client, Hub, Signed}, + publish::{self, Broadcast, To}, rate_limit::RateLimit, - request, retention, + retention, rooms::Rooms, stats::{Follows, Machine}, }; const HELLO_DEADLINE: Duration = Duration::from_secs(5); const RESTART_DRAIN: Duration = Duration::from_secs(2); - const RESTART_DELAY: Duration = Duration::from_millis(300); -impl Services { - pub fn restart_soon(&self) { - let restart = self.restart.clone(); - tokio::spawn(async move { - tokio::time::sleep(RESTART_DELAY).await; - restart.notify_one(); - }); - } -} - pub enum Exit { Stopped, Restart, } -#[derive(Clone, Default)] +#[derive(Clone)] +pub(crate) struct Shared { + pub(crate) db: Db, + pub(crate) services: Services, + pub(crate) attachments: PathBuf, + pub(crate) backups: PathBuf, + pub(crate) releases: crate::update::Releases, +} + +#[derive(Clone)] pub struct Services { pub rooms: Rooms, pub hub: Hub, @@ -61,27 +57,38 @@ pub struct Services { pub restart: Arc, } -#[derive(Clone)] -pub(crate) struct Shared { - pub(crate) db: Db, - pub(crate) services: Services, - pub(crate) directory: PathBuf, - pub(crate) backups: PathBuf, - pub(crate) releases: crate::update::Releases, +impl Services { + pub fn new(attachments: PathBuf) -> Self { + Self { + rooms: Rooms::default(), + hub: Hub::default(), + rate_limit: RateLimit::default(), + stats: Follows::default(), + machine: Machine::new(attachments), + restart: Arc::default(), + } + } + + pub fn restart_soon(&self) { + let restart = self.restart.clone(); + tokio::spawn(async move { + tokio::time::sleep(RESTART_DELAY).await; + restart.notify_one(); + }); + } } struct Pending { client: Arc, events: mpsc::Receiver, reply_stream: Sending, - user: Option, } pub async fn serve( server_address: &str, server_config: quinn::ServerConfig, db: Db, - directory: PathBuf, + attachments: PathBuf, backups: PathBuf, releases: crate::update::Releases, ) -> Result { @@ -94,14 +101,18 @@ pub async fn serve( let shared = Shared { db, - services: Services::default(), - directory, + services: Services::new(attachments.clone()), + attachments, backups, releases, }; - shared.services.machine.watch(shared.directory.clone()); - - tokio::spawn(retention::collect(shared.clone())); + let runtime = tokio::runtime::Handle::current(); + let sweeper = shared.clone(); + std::thread::spawn(move || runtime.block_on(retention::collect(sweeper))); + tokio::spawn(files::collect( + shared.db.clone(), + shared.attachments.clone(), + )); let restart = shared.services.restart.clone(); loop { @@ -131,13 +142,10 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Serv let ip = incoming.remote_address().ip().to_string(); let banned = shared .db - .run(async |db| db::server_ban::ip_banned(&ip, db).await) + .run(async |db| db::server_ban::banned(ServerBanKind::Ip, &ip, db).await) .await?; if banned { - incoming - .accept()? - .await? - .close(Close::Banned.code(), Close::Banned.reason().as_bytes()); + Close::Banned.on(&incoming.accept()?.await?); return Ok(()); } let connection = incoming.await?; @@ -153,11 +161,11 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Serv Ok(Ok(Some(pending))) => pending, Ok(Ok(None)) => return Ok(()), Ok(Err(error)) => { - close(&connection, Close::Protocol); + Close::Protocol.on(&connection); return Err(error); } Err(_) => { - close(&connection, Close::Protocol); + Close::Protocol.on(&connection); return Ok(()); } }; @@ -165,48 +173,33 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Serv client, events, reply_stream, - user, } = pending; let hub = &shared.services.hub; - let presence = hub.add(Arc::clone(&client)); - match welcome(&client, reply_stream, user, &shared).await { - Ok(true) => {} + let joined = hub.add(Arc::clone(&client)); + match establish(&client, &connection, reply_stream, events, &shared).await { + Ok(true) => publish_presence(&shared, joined).await, Ok(false) => { - publish_presence(&shared, first_named(presence, hub.remove(client.id))).await; + publish_presence(&shared, joined.or(hub.remove(client.id))).await; let _ = tokio::time::timeout(HELLO_DEADLINE, connection.closed()).await; return Ok(()); } Err(error) => { - publish_presence(&shared, first_named(presence, hub.remove(client.id))).await; - close(&connection, Close::Protocol); + publish_presence(&shared, joined.or(hub.remove(client.id))).await; + Close::Protocol.on(&connection); return Err(error); } } - let send_stream = match connection.open_uni().await { - Ok(stream) => stream, - Err(error) => { - publish_presence(&shared, first_named(presence, hub.remove(client.id))).await; - return Err(error.into()); - } - }; - tokio::spawn(write_events(events, send_stream)); - publish_presence(&shared, presence).await; + if client .user_id() .is_some_and(|user_id| shared.services.stats.is_followed(user_id)) { - let conn = client.id; - publish::job(&shared, async |_| { - Ok(vec![Broadcast::new( - To::Conn(conn), - Event::StatsWanted(true), - )]) - }) - .await?; + let to = To::Conn(client.id); + publish::direct(hub, vec![Broadcast::new(to, Event::StatsWanted(true))]); } - tokio::spawn(datagram::relay_datagrams( + tokio::spawn(relay_datagrams( connection.clone(), Arc::clone(&client), shared.clone(), @@ -222,55 +215,48 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Serv } client.closed.store(true, Ordering::Release); - let presence = hub.remove(client.id); + let left = hub.remove(client.id); + let departure = shared.services.rooms.leave(client.id); if let Some(user_id) = shared.services.stats.leave(client.id) { - publish::job(&shared, async |_| { - Ok(vec![Broadcast::new( - To::User(user_id), - Event::StatsWanted(false), - )]) - }) - .await?; + let to = To::User(user_id); + publish::direct(hub, vec![Broadcast::new(to, Event::StatsWanted(false))]); } + let session_id = client.me.as_ref().map(|me| me.session_id); + let cleanup = publish::job(&shared, async |db| { + let mut broadcasts = match departure { + Some(departure) => call::shared::departed(departure, db).await?, + None => Vec::new(), + }; + if let Some(user_id) = left { + broadcasts.extend(call::shared::presence_changed(hub, user_id, db).await?); + } + if let Some(session_id) = session_id { + db::session::seen(session_id, db).await?; + } - if let Some(me) = &client.me { - publish::job(&shared, async |db| { - let mut broadcasts = match shared.services.rooms.leave(client.id) { - Some(departure) => request::departed(departure, db).await?, - None => Vec::new(), - }; - if let Presence::Offline(user_id) = presence { - broadcasts.extend(request::presence_changed(hub, user_id, db).await?); - } - db::session::seen(me.session_id, db).await?; - - Ok(broadcasts) - }) - .await?; + Ok(broadcasts) + }) + .await; + if let Err(error) = cleanup { + warn!("disconnect: {error}"); } Ok(()) } -fn close(connection: &Connection, close: Close) { - connection.close(close.code(), close.reason().as_bytes()); -} - async fn greet(connection: &Connection, shared: &Shared) -> Result, ServerError> { let (send_stream, mut receive_stream) = connection.accept_bi().await?; let mut reply_stream = Sending::new(send_stream); let hello: Hello = frame::read(&mut receive_stream, UP_MAX).await?; - let build = hello.build; let install = hello.install; match admit(hello, connection, shared).await { - Ok((me, user)) => { - let (client, events) = Client::new(Some(connection.clone()), me, build, install); + Ok(me) => { + let (client, events) = Client::new(Some(connection.clone()), me, install); Ok(Some(Pending { client, events, reply_stream, - user, })) } Err(error) => { @@ -288,12 +274,12 @@ async fn admit( hello: Hello, connection: &Connection, shared: &Shared, -) -> Result<(Option, Option), ServerError> { +) -> Result, ServerError> { let Some(token) = hello.token else { - return Ok((None, None)); + return Ok(None); }; let ip = connection.remote_address().ip().to_string(); - let (session_id, user) = shared + let me = shared .db .run(async |db| { let (session_id, user) = authentication::resume(&token, db).await?; @@ -308,21 +294,35 @@ async fn admit( warn!("device: {error}"); } - Ok((session_id, user)) + Ok(Signed { + user_id: user.id, + session_id, + }) }) .await?; - let me = Signed { - user_id: user.id, - session_id, - }; - Ok((Some(me), Some(user))) + Ok(Some(me)) +} + +async fn establish( + client: &Client, + connection: &Connection, + reply_stream: Sending, + events: mpsc::Receiver, + shared: &Shared, +) -> Result { + if !welcome(client, reply_stream, shared).await? { + return Ok(false); + } + let send_stream = connection.open_uni().await?; + tokio::spawn(write_events(events, send_stream, connection.clone())); + + Ok(true) } async fn welcome( client: &Client, mut reply_stream: Sending, - user: Option, shared: &Shared, ) -> Result { let checked = match &client.me { @@ -331,13 +331,11 @@ async fn welcome( .run(async |db| authentication::recheck(me.session_id, db).await) .await .map(Some), - None => Ok(user.clone()), + None => Ok(None), }; let accepted = checked.is_ok(); - let reply: Result = match checked { - Ok(_) => Ok(Welcome { user }), - Err(error) => Err(error.into()), - }; + let reply: Result = + checked.map(|user| Welcome { user }).map_err(Into::into); frame::write(&mut reply_stream, &reply, DOWN_MAX).await?; reply_stream.finish()?; @@ -361,7 +359,7 @@ async fn route( receive_stream, send_stream, &shared.db, - &shared.directory, + &shared.attachments, ) .await } @@ -385,7 +383,7 @@ async fn route( blob, send_stream, &shared.db, - &shared.directory, + &shared.attachments, &shared.backups, ) .await @@ -399,7 +397,7 @@ async fn signed_user(client: &Client, shared: &Shared) -> Result, S } let user = shared .db - .run(async |db| request::authenticated(client, db).await) + .run(async |db| call::shared::authenticated(client, db).await) .await?; Ok(Some(user)) @@ -433,20 +431,13 @@ async fn answer( Ok(()) } -fn first_named(first: Presence, second: Presence) -> Presence { - match first { - Presence::None => second, - named => named, - } -} - -async fn publish_presence(shared: &Shared, presence: Presence) { - let (Presence::Online(user_id) | Presence::Offline(user_id)) = presence else { +async fn publish_presence(shared: &Shared, flipped: Option) { + let Some(user_id) = flipped else { return; }; let hub = &shared.services.hub; if let Err(error) = publish::job(shared, async |db| { - request::presence_changed(hub, user_id, db).await + call::shared::presence_changed(hub, user_id, db).await }) .await { @@ -454,12 +445,24 @@ async fn publish_presence(shared: &Shared, presence: Presence) { } } -async fn write_events(mut events: mpsc::Receiver, send_stream: SendStream) { +async fn relay_datagrams(connection: Connection, client: Arc, shared: Shared) { + while let Ok(bytes) = connection.read_datagram().await { + let broadcasts = shared.services.rooms.relay(&client, &bytes); + publish::direct(&shared.services.hub, broadcasts); + } +} + +async fn write_events( + mut events: mpsc::Receiver, + send_stream: SendStream, + connection: Connection, +) { let mut send_stream = Sending::new(send_stream); while let Some(bytes) = events.recv().await { if let Err(error) = send_stream.get().write_all(&bytes).await { warn!("event write: {error}"); - break; + Close::Protocol.on(&connection); + return; } } } diff --git a/crates/server/src/publish.rs b/crates/server/src/publish.rs index 6456ab3..c316e45 100644 --- a/crates/server/src/publish.rs +++ b/crates/server/src/publish.rs @@ -11,7 +11,7 @@ use tracing::warn; use crate::{ db::{self, Connection}, error::ServerError, - hub::ConnId, + hub::{ConnId, Hub}, network::Shared, }; @@ -50,29 +50,25 @@ impl Broadcast { pub(crate) async fn publish(shared: &Shared, db: &Connection, broadcasts: Vec) { for broadcast in broadcasts { - let mut ids = match resolve(shared, &broadcast.to, db).await { - Ok(ids) => ids, - Err(error) => { - warn!("resolve: {error}"); + match resolve(shared, &broadcast, db).await { + Ok(ids) => deliver(&shared.services.hub, &ids, &broadcast.down), + Err(error) => warn!("resolve: {error}"), + } + } +} + +pub(crate) fn direct(hub: &Hub, broadcasts: Vec) { + for broadcast in broadcasts { + let ids = match &broadcast.to { + To::Conn(id) => vec![*id], + To::User(user_id) => hub.conns_of(std::slice::from_ref(user_id)), + To::Users(user_ids) => hub.conns_of(user_ids), + _ => { + warn!("direct: target needs the database"); continue; } }; - let community = matches!(broadcast.to, To::Community(_) | To::CommunityExcept(..)); - if let Some((community_id, user_id)) = voice_subject(&broadcast.down).filter(|_| community) - && hidden(user_id, community_id, db).await - { - let mut insiders = shared.services.rooms.room_users(community_id); - insiders.push(user_id); - let keep = shared.services.hub.conns_of(&insiders); - ids.retain(|id| keep.contains(id)); - } - let droppable = matches!(&broadcast.down, Down::Event(event) if matches!(**event, Event::Typing { .. })); - let Ok(framed) = frame::encode(&broadcast.down, DOWN_MAX) else { - warn!("event too large"); - continue; - }; - let bytes = Bytes::from(framed); - shared.services.hub.send(&ids, &bytes, droppable); + deliver(hub, &ids, &broadcast.down); } } @@ -87,9 +83,22 @@ pub(crate) async fn job( Ok(()) } -async fn resolve(shared: &Shared, to: &To, db: &Connection) -> Result, ServerError> { +fn deliver(hub: &Hub, ids: &[ConnId], down: &Down) { + let Ok(framed) = frame::encode(down, DOWN_MAX) else { + warn!("event too large"); + return; + }; + let droppable = matches!(down, Down::Event(event) if matches!(**event, Event::Typing { .. })); + hub.send(ids, &Bytes::from(framed), droppable); +} + +async fn resolve( + shared: &Shared, + broadcast: &Broadcast, + db: &Connection, +) -> Result, ServerError> { let hub = &shared.services.hub; - let ids = match to { + let mut ids = match &broadcast.to { To::Conn(id) => vec![*id], To::Everyone => hub.all(), To::User(user_id) => hub.conns_of(std::slice::from_ref(user_id)), @@ -110,6 +119,15 @@ async fn resolve(shared: &Shared, to: &To, db: &Connection) -> Result, - db: &Connection, -) -> Result<(), ServerError> { - let limit = db::settings::read(db).await?.logins_per_minute; - - let ip = connection - .map(|connection| connection.remote_address().ip().to_string()) - .unwrap_or_default(); - - Ok(rate_limit.allow(&ip, limit)?) -} - -pub(crate) async fn effective_presence( - hub: &Hub, - user_id: Id, - db: &Connection, -) -> Result { - if !hub.is_online(user_id) { - return Ok(Presence::Offline); - } - - db::user::presence(user_id, db).await -} - -pub async fn presence_changed( - hub: &Hub, - user_id: Id, - db: &Connection, -) -> Result, ServerError> { - let presence = effective_presence(hub, user_id, db).await?; - let event = Event::PresenceChanged { user_id, presence }; - - Ok(vec![Broadcast::new(To::Related(user_id), event)]) -} - -pub(crate) async fn introduce( - user_id: Id, - others: &[Id], - cx: &mut Cx<'_>, -) -> Result<(), ServerError> { - let hub = &cx.sh.services.hub; - let presence = effective_presence(hub, user_id, cx.db).await?; - for &other in others { - if other == user_id { - continue; - } - let theirs = effective_presence(hub, other, cx.db).await?; - cx.emit( - To::User(other), - Event::PresenceChanged { user_id, presence }, - ); - cx.emit( - To::User(user_id), - Event::PresenceChanged { - user_id: other, - presence: theirs, - }, - ); - } - - Ok(()) -} - -pub(crate) async fn leave_user_voice( - rooms: &Rooms, - user_id: Id, - db: &Connection, -) -> Result, ServerError> { - match rooms.leave_user(user_id) { - Some(departure) => departed(departure, db).await, - None => Ok(Vec::new()), - } -} - -pub(crate) async fn leave_room_voice( - rooms: &Rooms, - community_id: Id, - user_id: Id, - db: &Connection, -) -> Result, ServerError> { - match rooms.leave_room(community_id, user_id) { - Some(departure) => departed(departure, db).await, - None => Ok(Vec::new()), - } -} - -pub(crate) async fn voice_muted( - community_id: Option, - user_id: Id, - muted: bool, - db: &Connection, -) -> Result { - let mut user_ids = vec![user_id]; - if let Some(community_id) = community_id - && !db::user::is_ghost(user_id, db).await? - { - user_ids.extend(db::member::member_ids(community_id, db).await?); - } - let event = Event::VoiceMuted { - community_id, - user_id, - muted, - }; - - Ok(Broadcast::new(To::Users(user_ids), event)) -} - -pub(crate) async fn voice_closed( - rooms: &Rooms, - community_id: Id, - db: &Connection, -) -> Result, ServerError> { - let mut broadcasts = Vec::new(); - for departure in rooms.close_room(community_id) { - broadcasts.extend(departed(departure, db).await?); - } - - Ok(broadcasts) -} - -pub(crate) async fn delete_community(community_id: Id, cx: &mut Cx<'_>) -> Result<(), ServerError> { - let member_ids = db::member::member_ids(community_id, cx.db).await?; - let closed = voice_closed(&cx.sh.services.rooms, community_id, cx.db).await?; - cx.out.extend(closed); - db::community::delete(community_id, cx.db).await?; - cx.emit( - To::Users(member_ids), - Event::CommunityDeleted { community_id }, - ); - - Ok(()) -} - -pub(crate) async fn call_ended( - community_id: Id, - user_id: Id, - call: Option, - db: &Connection, -) -> Result, ServerError> { - let Some(call) = call else { - return Ok(Vec::new()); - }; - if db::community::kind_of(community_id, db).await? != Some(Kind::Direct) { - return Ok(Vec::new()); - } - let created = db::message::create_call_log(community_id, user_id, call, db).await?; - - Ok(vec![message_event(&created, Event::MessageCreated)]) -} - -pub async fn departed( - mut departure: Departure, - db: &Connection, -) -> Result, ServerError> { - let mut broadcasts = shares_ended(&mut departure); - if departure.quiet { - return Ok(broadcasts); - } - let Departure { - community_id, - user_id, - ghost_seconds, - call_log, - .. - } = departure; - let Some(seconds) = ghost_seconds else { - broadcasts.extend(call_ended(community_id, user_id, call_log, db).await?); - let event = Event::VoiceLeft { - community_id, - user_id, - }; - broadcasts.push(Broadcast::new(To::Community(community_id), event)); - - return Ok(broadcasts); - }; - record_ghost_voice(user_id, community_id, seconds, db).await?; - let event = Event::VoiceLeft { - community_id, - user_id, - }; - broadcasts.push(Broadcast::new(To::User(user_id), event)); - - Ok(broadcasts) -} - -pub(crate) fn share_ended(community_id: Id, user_id: Id, kind: ShareKind) -> Broadcast { - let event = Event::ShareStopped { - community_id, - user_id, - kind, - }; - - Broadcast::new(To::Community(community_id), event) -} - -pub(crate) fn shares_ended(departure: &mut Departure) -> Vec { - let mut broadcasts: Vec = departure - .shares - .iter() - .map(|kind| share_ended(departure.community_id, departure.user_id, *kind)) - .collect(); - broadcasts.append(&mut departure.media); - - broadcasts -} - -pub(crate) fn messages_deleted(rows: Vec<(Id, Id)>) -> Vec { - let mut deleted: BTreeMap> = BTreeMap::new(); - for (community_id, message_id) in rows { - deleted.entry(community_id).or_default().push(message_id); - } - - deleted - .into_iter() - .map(|(community_id, ids)| { - let event = Event::MessagesDeleted { community_id, ids }; - Broadcast::new(To::Community(community_id), event) - }) - .collect() -} - -pub(crate) async fn authenticated(client: &Client, db: &Connection) -> Result { - let me = client.me.as_ref().ok_or(CommonError::Unauthenticated)?; - - Ok(db::session::user_of(me.session_id, db) - .await? - .ok_or(CommonError::Unauthenticated)?) -} - -pub async fn actor_rank( - me: &User, - community_id: Id, - db: &Connection, -) -> Result, ServerError> { - let rank = db::member::rank(me.id, community_id, db).await?; - - Ok(permission::effective_rank(me.role, rank)) -} - -pub(crate) async fn managed(me: &User, user_id: Id, db: &Connection) -> Result { - let target = db::user::read(user_id, db).await?; - ensure(permission::can_manage_user( - me.role, - me.id == user_id, - target.role, - ))?; - - Ok(target) -} - -pub(crate) async fn allowed( - me: &User, - community_id: Id, - db: &Connection, - check: fn(Option) -> bool, -) -> Result<(), ServerError> { - ensure(check(actor_rank(me, community_id, db).await?)) -} - -pub(crate) async fn is_outsider( - user_id: Id, - community_id: Id, - db: &Connection, -) -> Result { - Ok(db::member::rank(user_id, community_id, db).await?.is_none()) -} - -pub(crate) async fn ensure_editable(community_id: Id, db: &Connection) -> Result<(), ServerError> { - let kind = db::community::kind_of(community_id, db) - .await? - .ok_or(CommonError::NotFound)?; - - ensure(kind == Kind::Group) -} - -pub(crate) fn message_event(message: &Message, event: fn(Message) -> Event) -> Broadcast { - let mut message = message.clone(); - if let Some(reply) = &mut message.reply { - reply.redact(); - } - - Broadcast::new(To::Community(message.community_id), event(message)) -} - -pub(crate) fn voice_joined(community_id: Id, user_id: Id, muted: bool) -> Vec { - let mut broadcasts = vec![Broadcast::new( - To::Community(community_id), - Event::VoiceJoined { - community_id, - user_id, - }, - )]; - if muted { - broadcasts.push(Broadcast::new( - To::Community(community_id), - Event::VoiceMuted { - community_id: Some(community_id), - user_id, - muted, - }, - )); - } - - broadcasts -} - -pub(crate) async fn record_ghost_voice( - user_id: Id, - community_id: Id, - seconds: u64, - db: &Connection, -) -> Result<(), ServerError> { - let community = db::community::label(community_id, db).await?; - db::log::record_admin( - Some(user_id), - None, - Some(&community), - &AdminAction::GhostVoice { seconds }, - db, - ) - .await -} - -#[cfg(test)] -mod tests { - use std::sync::Arc; - - use common::{ - call::{ - AcceptFriend, AcceptInvitation, AddFriend, CreateCommunity, CreateMessage, - DeleteCommunity, FindUser, Invite, Kick, LeaveCommunity, ListCommunities, ListFriends, - UpdateCommunity, - }, - error::Error as CommonError, - model::{Id, Role}, - }; - - use crate::{ - authentication::token_hash, - call::{Cx, Handle, Me}, - db::{self, Db}, - hub::{Client, Signed}, - network::{Services, Shared}, - request::authenticated, - test, - }; - - fn shared(db: &Db, services: &Services) -> Shared { - Shared { - db: db.clone(), - services: services.clone(), - directory: test::directory(), - backups: test::directory(), - releases: Default::default(), - } - } - - async fn call( - call: C, - client: &Arc, - db: &Db, - services: &Services, - ) -> Result { - let shared = shared(db, services); - let conn = db.lock().await.unwrap(); - let me = authenticated(client, &conn).await?; - let mut cx = Cx::new(client, &shared, &conn); - - Ok(call.handle(Me::User(me), &mut cx).await?) - } - - async fn signed_in(username: &str, db: &Db) -> Arc { - signed_in_as(username, Role::User, db).await - } - - async fn signed_in_as(username: &str, role: Role, db: &Db) -> Arc { - let conn = db.lock().await.unwrap(); - let user = db::user::create(username, "hash", role, &conn) - .await - .unwrap(); - let session_id = db::session::insert(&token_hash(username), user.id, &conn) - .await - .unwrap(); - - Client::detached(Some(Signed { - user_id: user.id, - session_id, - })) - } - - async fn invite_and_accept( - community_id: Id, - owner: &Arc, - member: &Arc, - username: &str, - db: &Db, - services: &Services, - ) { - let member_user = call( - FindUser { - username: username.to_string(), - }, - owner, - db, - services, - ) - .await - .unwrap(); - call( - Invite { - community_id, - user_id: member_user.id, - }, - owner, - db, - services, - ) - .await - .unwrap(); - call(AcceptInvitation { community_id }, member, db, services) - .await - .unwrap(); - } - - #[tokio::test] - async fn plain_member_cannot_rename() { - let db = test::db().await; - let services = Services::default(); - let owner = signed_in("Owner", &db).await; - let member = signed_in("Member", &db).await; - let community = call( - CreateCommunity { - name: "The Community".to_string(), - }, - &owner, - &db, - &services, - ) - .await - .unwrap(); - invite_and_accept(community.id, &owner, &member, "Member", &db, &services).await; - - let response = call( - UpdateCommunity { - community_id: community.id, - name: "Renamed".to_string(), - }, - &member, - &db, - &services, - ) - .await; - - assert!(matches!(response, Err(CommonError::Forbidden))); - } - - #[tokio::test] - async fn accepted_friend_request_befriends_both() { - let db = test::db().await; - let services = Services::default(); - let first = signed_in("First", &db).await; - let second = signed_in("Second", &db).await; - let first_user = call( - FindUser { - username: "First".to_string(), - }, - &second, - &db, - &services, - ) - .await - .unwrap(); - let second_user = call( - FindUser { - username: "Second".to_string(), - }, - &first, - &db, - &services, - ) - .await - .unwrap(); - call( - AddFriend { - user_id: second_user.id, - }, - &first, - &db, - &services, - ) - .await - .unwrap(); - call( - AcceptFriend { - user_id: first_user.id, - }, - &second, - &db, - &services, - ) - .await - .unwrap(); - - let first_friends = call(ListFriends, &first, &db, &services).await.unwrap(); - let second_friends = call(ListFriends, &second, &db, &services).await.unwrap(); - - assert_eq!(vec![second_user], first_friends.friends); - assert_eq!(vec![first_user], second_friends.friends); - } - - #[tokio::test] - async fn invite_and_accept_makes_member() { - let db = test::db().await; - let services = Services::default(); - let owner = signed_in("Owner", &db).await; - let member = signed_in("Member", &db).await; - let community = call( - CreateCommunity { - name: "The Community".to_string(), - }, - &owner, - &db, - &services, - ) - .await - .unwrap(); - - invite_and_accept(community.id, &owner, &member, "Member", &db, &services).await; - - let communities = call(ListCommunities, &member, &db, &services) - .await - .unwrap(); - assert_eq!(vec![community], communities); - } - - #[tokio::test] - async fn delete_community_removes_messages() { - let db = test::db().await; - let services = Services::default(); - let owner = signed_in("Owner", &db).await; - let community = call( - CreateCommunity { - name: "The Community".to_string(), - }, - &owner, - &db, - &services, - ) - .await - .unwrap(); - call( - CreateMessage { - community_id: community.id, - body: "Tahinli".to_string(), - attachments: Vec::new(), - reply_to: None, - }, - &owner, - &db, - &services, - ) - .await - .unwrap(); - - call( - DeleteCommunity { - community_id: community.id, - }, - &owner, - &db, - &services, - ) - .await - .unwrap(); - - let conn = db.lock().await.unwrap(); - let remaining = db::message::read_page(community.id, None, false, &conn) - .await - .unwrap(); - - assert!(remaining.is_empty()); - } - - async fn group(owner: &Arc, db: &Db, services: &Services) -> Id { - call( - CreateCommunity { - name: "The Community".to_string(), - }, - owner, - db, - services, - ) - .await - .unwrap() - .id - } - - async fn user_id(username: &str, by: &Arc, db: &Db, services: &Services) -> Id { - call( - FindUser { - username: username.to_string(), - }, - by, - db, - services, - ) - .await - .unwrap() - .id - } - - #[tokio::test] - async fn kick_of_non_member_is_not_found() { - let db = test::db().await; - let services = Services::default(); - let owner = signed_in("Owner", &db).await; - signed_in("Outsider", &db).await; - let community_id = group(&owner, &db, &services).await; - let outsider = user_id("Outsider", &owner, &db, &services).await; - - let kick = Kick { - community_id, - user_id: outsider, - reason: None, - }; - - assert!(matches!( - call(kick, &owner, &db, &services).await, - Err(CommonError::NotFound) - )); - } - - #[tokio::test] - async fn builder_cannot_leave_owned_group() { - let db = test::db().await; - let services = Services::default(); - let builder = signed_in_as("Builder", Role::Builder, &db).await; - let community_id = group(&builder, &db, &services).await; - - let leave = LeaveCommunity { community_id }; - - assert!(matches!( - call(leave, &builder, &db, &services).await, - Err(CommonError::Forbidden) - )); - } -} diff --git a/crates/server/src/retention.rs b/crates/server/src/retention.rs index 745304d..a0e5af8 100644 --- a/crates/server/src/retention.rs +++ b/crates/server/src/retention.rs @@ -3,7 +3,13 @@ use std::time::Duration; use common::time; use tracing::{error, info}; -use crate::{db, error::ServerError, network::Shared, publish::job, request::messages_deleted}; +use crate::{ + call::shared::messages_deleted, + db::{self, Connection}, + error::ServerError, + network::Shared, + publish::{Broadcast, job}, +}; const SWEEP_INTERVAL: Duration = Duration::from_millis(time::HOUR_MILLIS); const BATCH_SIZE: u32 = 500; @@ -22,32 +28,18 @@ fn cutoff(days: u32) -> u64 { time::now_ms().saturating_sub(u64::from(days) * time::DAY_MILLIS) } -async fn purge_messages(cutoff: u64, shared: &Shared) -> Result { +async fn purge( + shared: &Shared, + batch: impl AsyncFn(&Connection) -> Result<(u64, Vec), ServerError>, +) -> Result { let mut purged = 0; loop { let mut deleted = 0; job(shared, async |db| { - let rows = db::message::delete_before(cutoff, BATCH_SIZE, db).await?; - deleted = rows.len() as u64; + let (count, broadcasts) = batch(db).await?; + deleted = count; - Ok(messages_deleted(rows)) - }) - .await?; - if deleted == 0 { - return Ok(purged); - } - purged += deleted; - } -} - -async fn purge_attachments(cutoff: u64, shared: &Shared) -> Result { - let mut purged = 0; - loop { - let mut deleted = 0; - job(shared, async |db| { - deleted = db::attachment::delete_before(cutoff, BATCH_SIZE, db).await?; - - Ok(Vec::new()) + Ok(broadcasts) }) .await?; if deleted == 0 { @@ -62,11 +54,25 @@ async fn sweep(shared: &Shared) -> Result<(), ServerError> { let messages = match settings.message_retention_days { 0 => 0, - days => purge_messages(cutoff(days), shared).await?, + days => { + let cutoff = cutoff(days); + purge(shared, async |db| { + let rows = db::message::delete_before(cutoff, BATCH_SIZE, db).await?; + Ok((rows.len() as u64, messages_deleted(rows))) + }) + .await? + } }; let attachments = match settings.attachment_retention_days { 0 => 0, - days => purge_attachments(cutoff(days), shared).await?, + days => { + let cutoff = cutoff(days); + purge(shared, async |db| { + let deleted = db::attachment::delete_before(cutoff, BATCH_SIZE, db).await?; + Ok((deleted, Vec::new())) + }) + .await? + } }; if messages + attachments > 0 { diff --git a/crates/server/src/rooms.rs b/crates/server/src/rooms.rs index fb7e86e..37a0b11 100644 --- a/crates/server/src/rooms.rs +++ b/crates/server/src/rooms.rs @@ -6,7 +6,7 @@ use std::{ use bytes::Bytes; use common::{ - datagram::{self, Gate, Link, Packet, RELAY_PREFIX, relayed}, + datagram::{self, Link, Pace, Packet, relayed}, error::Error, event::{Event, Media}, model::{CallLog, Id}, @@ -248,9 +248,8 @@ fn remove_viewer( struct Seat { user_id: Id, - prefix: [u8; RELAY_PREFIX], connection: Connection, - muted: bool, + server_muted: bool, ghost: bool, joined_at: Instant, shares: BTreeMap, @@ -320,19 +319,31 @@ impl Room { } } +pub enum Left { + Transferred, + Ghost { seconds: u64 }, + Seated { call_log: Option }, +} + pub struct Departure { pub community_id: Id, pub user_id: Id, - pub ghost_seconds: Option, - pub call_log: Option, pub shares: Vec, pub media: Vec, - pub quiet: bool, + pub left: Left, +} + +pub struct RoomSummary { + pub community_id: Id, + pub users: Vec, + pub ghosts: Vec, } -pub struct Joined { - pub departure: Option, - pub transferred: bool, +enum Why { + Leave, + Removed, + Rejoin, + Takeover, } #[derive(Default)] @@ -347,38 +358,63 @@ impl Inner { self.conn_of_user.get(&user_id).copied() } + fn seat(&self, id: ConnId) -> Option<&Seat> { + let community_id = self.seat_of.get(&id)?; + + self.rooms.get(community_id)?.seats.get(&id) + } + fn seat_mut(&mut self, id: ConnId) -> Option<(Id, &mut Room)> { let community_id = *self.seat_of.get(&id)?; Some((community_id, self.rooms.get_mut(&community_id)?)) } - fn take(&mut self, id: ConnId, notify: bool, quiet: bool) -> Option { + fn sharing(&mut self, id: ConnId, sharer_id: Id, kind: Kind) -> Option<(ConnId, &mut Sharing)> { + let sharer_conn = self.seat_conn(sharer_id)?; + let (_, room) = self.seat_mut(id)?; + let sharing = room.seats.get_mut(&sharer_conn)?.shares.get_mut(&kind)?; + + Some((sharer_conn, sharing)) + } + + fn take(&mut self, id: ConnId, why: Why) -> Option { let community_id = self.seat_of.remove(&id)?; let room = self.rooms.get_mut(&community_id)?; let seat = room.seats.remove(&id)?; if self.conn_of_user.get(&seat.user_id) == Some(&id) { self.conn_of_user.remove(&seat.user_id); } + let quiet = matches!(why, Why::Rejoin | Why::Takeover); let mut media = room.drop_viewer(seat.user_id); - let call_log = (!quiet && !seat.ghost && !room.occupied()) - .then(|| room.call_log()) - .flatten(); + let left = if quiet { + Left::Transferred + } else if seat.ghost { + Left::Ghost { + seconds: seat.joined_at.elapsed().as_secs(), + } + } else { + Left::Seated { + call_log: if room.occupied() { + None + } else { + room.call_log() + }, + } + }; if !quiet && room.seats.is_empty() { self.rooms.remove(&community_id); } - if notify { + if matches!(why, Why::Removed | Why::Takeover) { media.push(Broadcast::media(id, Media::VoiceEnded)); } Some(Departure { community_id, - ghost_seconds: seat.ghost.then(|| seat.joined_at.elapsed().as_secs()), user_id: seat.user_id, - call_log, shares: seat.shares.keys().copied().collect(), media, - quiet, + left, }) } } @@ -393,62 +429,57 @@ impl Rooms { community_id: Id, muted: bool, ghost: bool, - ) -> Result { + ) -> Result, Error> { let connection = client.conn.clone().ok_or(Error::Server)?; let user_id = client.user_id().ok_or(Error::Unauthenticated)?; - let prefix = user_id.to_be_bytes(); let mut inner = self.0.lock().unwrap(); if client.closed.load(Ordering::Acquire) { return Err(Error::Server); } - let mut departure = None; - let mut transferred = false; - let mut joined_at = Instant::now(); - if let Some(previous) = inner.seat_conn(user_id) { - let kept = inner - .rooms - .get(&community_id) - .and_then(|room| room.seats.get(&previous)) - .filter(|seat| seat.ghost == ghost) - .map(|seat| seat.joined_at); - transferred = kept.is_some(); - joined_at = kept.unwrap_or(joined_at); - departure = inner.take(previous, previous != client.id, transferred); - } + let previous = inner.seat_conn(user_id); + let kept = previous + .and_then(|conn| inner.rooms.get(&community_id)?.seats.get(&conn)) + .filter(|seat| seat.ghost == ghost) + .map(|seat| seat.joined_at); + let departure = previous.and_then(|conn| { + let why = match (conn == client.id, kept.is_some()) { + (true, true) => Why::Rejoin, + (true, false) => Why::Leave, + (false, true) => Why::Takeover, + (false, false) => Why::Removed, + }; + inner.take(conn, why) + }); let room = inner.rooms.entry(community_id).or_insert_with(Room::new); - if !ghost && !transferred { + if !ghost && kept.is_none() { room.admit(); } room.seats.insert( client.id, Seat { user_id, - prefix, connection, - muted, + server_muted: muted, ghost, - joined_at, + joined_at: kept.unwrap_or_else(Instant::now), shares: BTreeMap::new(), }, ); inner.seat_of.insert(client.id, community_id); inner.conn_of_user.insert(user_id, client.id); - Ok(Joined { - departure, - transferred, - }) + Ok(departure) } pub fn leave(&self, id: ConnId) -> Option { - self.0.lock().unwrap().take(id, false, false) + self.0.lock().unwrap().take(id, Why::Leave) } pub fn leave_user(&self, user_id: Id) -> Option { let mut inner = self.0.lock().unwrap(); let id = inner.seat_conn(user_id)?; - inner.take(id, true, false) + inner.take(id, Why::Removed) } pub fn leave_room(&self, community_id: Id, user_id: Id) -> Option { @@ -458,7 +489,7 @@ impl Rooms { return None; } - inner.take(id, true, false) + inner.take(id, Why::Removed) } pub fn close_room(&self, community_id: Id) -> Vec { @@ -470,10 +501,12 @@ impl Rooms { .unwrap_or_default(); ids.into_iter() - .filter_map(|id| inner.take(id, true, false)) - .map(|departure| Departure { - call_log: None, - ..departure + .filter_map(|id| inner.take(id, Why::Removed)) + .map(|mut departure| { + if let Left::Seated { call_log } = &mut departure.left { + *call_log = None; + } + departure }) .collect() } @@ -486,11 +519,11 @@ impl Rooms { } } - pub fn set_muted(&self, user_id: Id, muted: bool) -> Option { + pub fn set_server_muted(&self, user_id: Id, muted: bool) -> Option { let mut inner = self.0.lock().unwrap(); let id = inner.seat_conn(user_id)?; let (community_id, room) = inner.seat_mut(id)?; - room.seats.get_mut(&id)?.muted = muted; + room.seats.get_mut(&id)?.server_muted = muted; Some(community_id) } @@ -506,29 +539,37 @@ impl Rooms { room.admit(); } let seat = room.seats.get_mut(&id)?; - let ghost_seconds = seat.ghost.then(|| seat.joined_at.elapsed().as_secs()); + let elapsed = seat.joined_at.elapsed().as_secs(); + let shares: Vec = if ghost { + std::mem::take(&mut seat.shares).into_keys().collect() + } else { + Vec::new() + }; seat.ghost = ghost; seat.joined_at = Instant::now(); - let (shares, media) = if ghost { - ( - std::mem::take(&mut seat.shares).into_keys().collect(), - room.drop_viewer(user_id), - ) + let media = if ghost { + room.drop_viewer(user_id) + } else { + Vec::new() + }; + let left = if ghost { + Left::Seated { + call_log: if room.occupied() { + None + } else { + room.call_log() + }, + } } else { - (Vec::new(), Vec::new()) + Left::Ghost { seconds: elapsed } }; - let call_log = (ghost && !room.occupied()) - .then(|| room.call_log()) - .flatten(); Some(Departure { community_id, user_id, - ghost_seconds, - call_log, shares, media, - quiet: false, + left, }) } @@ -566,18 +607,16 @@ impl Rooms { self.0.lock().unwrap().seat_of.len() } - pub fn list(&self) -> Vec<(Id, Vec, Vec)> { + pub fn list(&self) -> Vec { self.0 .lock() .unwrap() .rooms .iter() - .map(|(community_id, room)| { - ( - *community_id, - room.user_ids(|_| true), - room.user_ids(|seat| seat.ghost), - ) + .map(|(community_id, room)| RoomSummary { + community_id: *community_id, + users: room.user_ids(|_| true), + ghosts: room.user_ids(|seat| seat.ghost), }) .collect() } @@ -607,6 +646,9 @@ impl Rooms { let mut inner = self.0.lock().unwrap(); let (community_id, room) = inner.seat_mut(id)?; let seat = room.seats.get_mut(&id)?; + if seat.ghost { + return None; + } let sharer = Sharer { conn: id, user_id: seat.user_id, @@ -615,7 +657,7 @@ impl Rooms { }; let sharing = seat.shares.entry(kind).or_insert_with(|| Sharing { source: source.clone(), - started_ms: common::time::now_ms(), + started_ms: time::now_ms(), viewers: Vec::new(), recent: Recent::default(), acked: HashMap::new(), @@ -645,11 +687,10 @@ impl Rooms { decode: &[Codec], ) -> Option> { let mut inner = self.0.lock().unwrap(); - let sharer_conn = inner.seat_conn(sharer_id)?; - let (_, room) = inner.seat_mut(id)?; - let viewer_seat = room.seats.get(&id)?; - let (viewer_id, connection) = (viewer_seat.user_id, viewer_seat.connection.clone()); - let sharing = room.seats.get_mut(&sharer_conn)?.shares.get_mut(&kind)?; + let (viewer_id, connection) = inner + .seat(id) + .map(|seat| (seat.user_id, seat.connection.clone()))?; + let (sharer_conn, sharing) = inner.sharing(id, sharer_id, kind)?; let before = sharing.layers(); let used: Vec = before.iter().copied().collect(); let layer = choose(&sharing.source, quality, decode, &used)?; @@ -683,10 +724,8 @@ impl Rooms { pub fn unwatch(&self, id: ConnId, sharer_id: Id, kind: Kind) -> Option { let mut inner = self.0.lock().unwrap(); - let sharer_conn = inner.seat_conn(sharer_id)?; - let (_, room) = inner.seat_mut(id)?; - let viewer_id = room.seats.get(&id)?.user_id; - let sharing = room.seats.get_mut(&sharer_conn)?.shares.get_mut(&kind)?; + let viewer_id = inner.seat(id)?.user_id; + let (sharer_conn, sharing) = inner.sharing(id, sharer_id, kind)?; remove_viewer(sharer_conn, kind, sharing, viewer_id) } @@ -699,15 +738,9 @@ impl Rooms { recover: bool, ) -> Option { let mut inner = self.0.lock().unwrap(); - let sharer_conn = inner.seat_conn(sharer_id)?; - let (_, room) = inner.seat_mut(id)?; - let viewer_id = room.seats.get(&id)?.user_id; - let viewer = room - .seats - .get(&sharer_conn)? - .shares - .get(&kind)? - .viewer(viewer_id)?; + let viewer_id = inner.seat(id)?.user_id; + let (sharer_conn, sharing) = inner.sharing(id, sharer_id, kind)?; + let viewer = sharing.viewer(viewer_id)?; Some(Broadcast::media( sharer_conn, @@ -721,14 +754,9 @@ impl Rooms { pub fn loss(&self, id: ConnId, sharer_id: Id, kind: Kind, permille: u16) -> Option { let mut inner = self.0.lock().unwrap(); - let sharer_conn = inner.seat_conn(sharer_id)?; - let (_, room) = inner.seat_mut(id)?; - let viewer_id = room.seats.get(&id)?.user_id; - room.seats - .get(&sharer_conn)? - .shares - .get(&kind)? - .viewer(viewer_id)?; + let viewer_id = inner.seat(id)?.user_id; + let (sharer_conn, sharing) = inner.sharing(id, sharer_id, kind)?; + sharing.viewer(viewer_id)?; Some(Broadcast::media( sharer_conn, @@ -771,10 +799,10 @@ fn relay_voice(room: &Room, id: ConnId, packet: &[u8]) { let Some(sender) = room.seats.get(&id) else { return; }; - if sender.muted { + if sender.server_muted { return; } - let bytes = relayed(&sender.prefix, packet); + let bytes = relayed(sender.user_id, packet); for (other_id, seat) in &room.seats { if *other_id != id { datagram::send(&seat.connection, bytes.clone()); @@ -793,7 +821,7 @@ fn ack(room: &mut Room, id: ConnId, sharer_id: Id, kind: Kind, layer: Layer, ts_ else { return; }; - let (connection, prefix) = (seat.connection.clone(), seat.prefix); + let connection = seat.connection.clone(); let Some(sharing) = seat.shares.get_mut(&kind) else { return; }; @@ -831,7 +859,7 @@ fn ack(room: &mut Room, id: ConnId, sharer_id: Id, kind: Kind, layer: Layer, ts_ ts_ms: lowest, } .encode(&mut out); - datagram::send(&connection, relayed(&prefix, &out)); + datagram::send(&connection, relayed(sharer_id, &out)); } fn resend( @@ -866,7 +894,7 @@ fn resend( } return; } - for index in Packet::nack_indices(indices) { + for index in datagram::nack_indices(indices) { if let Some(bytes) = sharing.recent.packets.get(&(layer, frame, index)) { datagram::send(&viewer.connection, bytes.clone()); } @@ -880,7 +908,7 @@ fn relay_share_audio(room: &Room, id: ConnId, packet: &[u8]) { let Some(sharing) = seat.shares.get(&Kind::Screen) else { return; }; - let bytes = relayed(&seat.prefix, packet); + let bytes = relayed(seat.user_id, packet); for viewer in &sharing.viewers { datagram::send(&viewer.connection, bytes.clone()); } @@ -900,7 +928,7 @@ fn relay_video( let Some(sharing) = seat.shares.get_mut(&kind) else { return Vec::new(); }; - let bytes = relayed(&seat.prefix, packet); + let bytes = relayed(seat.user_id, packet); let mut recovery = false; if let Some(Packet::Video { frame, @@ -912,13 +940,13 @@ fn relay_video( sharing.recent.insert((layer, frame, index), bytes.clone()); recovery = flagged; } - let before = keyframe.then(|| sharing.layers()); - let mut stalled = None; + let before = sharing.layers(); + let mut stalled = BTreeSet::new(); for viewer in &mut sharing.viewers { if viewer.link.paused() { - if viewer.link.gate(&viewer.connection, keyframe || recovery) == Gate::Resume { + if viewer.link.pace(&viewer.connection, keyframe || recovery) == Pace::Resume { let recover = matches!(viewer.forward, Forward::Held(_)); - stalled = Some((viewer.forward.target(), recover)); + stalled.insert((viewer.forward.target(), recover)); } continue; } @@ -931,7 +959,7 @@ fn relay_video( if !viewer.forward.sending(layer) { continue; } - if viewer.link.gate(&viewer.connection, keyframe || recovery) == Gate::Pause { + if viewer.link.pace(&viewer.connection, keyframe || recovery) == Pace::Pause { tracing::info!(?kind, "viewer link congested, pausing until it drains"); viewer.forward = viewer.forward.hold(); continue; @@ -939,17 +967,16 @@ fn relay_video( datagram::send(&viewer.connection, bytes.clone()); } - let mut broadcasts = - Vec::from_iter(before.and_then(|before| layers_changed(id, kind, sharing, before))); - if let Some((layer, recover)) = stalled { - broadcasts.push(Broadcast::media( + let mut broadcasts = Vec::from_iter(layers_changed(id, kind, sharing, before)); + broadcasts.extend(stalled.into_iter().map(|(layer, recover)| { + Broadcast::media( id, Media::Keyframe { kind, layer, recover, }, - )); - } + ) + })); broadcasts } diff --git a/crates/server/src/stats.rs b/crates/server/src/stats.rs index 82ab6fd..636f56e 100644 --- a/crates/server/src/stats.rs +++ b/crates/server/src/stats.rs @@ -1,13 +1,13 @@ -use std::path::PathBuf; use std::{ collections::{HashMap, VecDeque}, + path::PathBuf, sync::{Arc, Mutex}, time::Instant, }; use common::{model::Id, stats::Stats}; -use usage::Monitor; +use usage::{Monitor, Wake}; use crate::hub::ConnId; @@ -33,9 +33,12 @@ impl Follows { if let Some(target) = target { inner.following.insert(conn, target); } - let followed = |user: Id| inner.following.values().any(|id| *id == user); + let stopped = old.filter(|old| !inner.following.values().any(|id| id == old)); + if let Some(stopped) = stopped { + inner.latest.remove(&stopped); + } Change { - stopped: old.filter(|old| !followed(*old)), + stopped, started: target.filter(|target| { old != Some(*target) && inner.following.values().filter(|id| *id == target).count() == 1 @@ -77,16 +80,18 @@ struct Rates { history: VecDeque<(u64, f32, f32)>, } -#[derive(Clone, Default)] +#[derive(Clone)] pub struct Machine { monitor: Arc, rates: Arc>, } impl Machine { - pub fn watch(&self, directory: PathBuf) { - self.monitor.watch_disk(directory); - self.monitor.stay_awake(); + pub fn new(directory: PathBuf) -> Self { + Self { + monitor: Arc::new(Monitor::new(Wake::Always, Some(directory))), + rates: Arc::default(), + } } pub fn sample(&self, (sent, received): (u64, u64)) -> Stats { diff --git a/crates/server/src/test.rs b/crates/server/src/test.rs index 7fca0b7..6309112 100644 --- a/crates/server/src/test.rs +++ b/crates/server/src/test.rs @@ -1,6 +1,9 @@ use std::path::PathBuf; -use crate::db::Db; +use crate::{ + db::Db, + network::{Services, Shared}, +}; pub async fn db() -> Db { Db::open(":memory:").await.unwrap() @@ -15,3 +18,13 @@ pub fn directory() -> PathBuf { directory } + +pub fn shared(db: Db, services: Services) -> Shared { + Shared { + db, + services, + attachments: directory(), + backups: directory(), + releases: Default::default(), + } +} diff --git a/crates/server/src/update.rs b/crates/server/src/update.rs index 2ab32f0..829161d 100644 --- a/crates/server/src/update.rs +++ b/crates/server/src/update.rs @@ -1,8 +1,11 @@ use std::{ - collections::HashMap, + collections::{HashMap, HashSet}, io::Write, + os::unix::fs::PermissionsExt, path::{Path, PathBuf}, + process::{Command, Stdio}, sync::{Arc, Mutex}, + time::{Duration, Instant}, }; use common::{ @@ -11,7 +14,7 @@ use common::{ model::{Id, Staged, UpdateState, User}, open::Stage, permission, - time::now_ms, + time::{DAY_MILLIS, now_ms}, update::{ Ask, FILE_MAX, Install, Me, Offer, Progress, SERVER_TARGET, SERVER_VERSION, Sha, Status, hex, protocol_of, sha256, target_of, @@ -29,14 +32,9 @@ use crate::{ }; const PACK_LEVEL: i32 = 19; -const PROBE: std::time::Duration = std::time::Duration::from_secs(5); - -static EXE: std::sync::LazyLock> = - std::sync::LazyLock::new(|| std::env::current_exe().ok()); - -pub fn remember_exe() { - std::sync::LazyLock::force(&EXE); -} +const PROBE: Duration = Duration::from_secs(5); +const BOARD_KEEP_MS: u64 = 7 * DAY_MILLIS; +const CHUNK: usize = 64 << 10; fn broken(why: impl std::fmt::Display) -> ServerError { warn!("new server binary rejected: {why}"); @@ -44,19 +42,19 @@ fn broken(why: impl std::fmt::Display) -> ServerError { } fn probe(path: &Path) -> Result<(), ServerError> { - let mut child = std::process::Command::new(path) + let mut child = Command::new(path) .arg("--version") - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) .spawn() .map_err(broken)?; - let start = std::time::Instant::now(); + let start = Instant::now(); while child.try_wait().map_err(broken)?.is_none() { if start.elapsed() > PROBE { let _ = child.kill(); return Err(broken("timed out")); } - std::thread::sleep(std::time::Duration::from_millis(50)); + std::thread::sleep(Duration::from_millis(50)); } let output = child.wait_with_output().map_err(broken)?; let said = String::from_utf8_lossy(&output.stdout); @@ -66,21 +64,6 @@ fn probe(path: &Path) -> Result<(), ServerError> { Err(broken(said.trim())) } -pub struct NextServer { - next: PathBuf, - exe: PathBuf, -} - -impl NextServer { - pub fn swap(self) -> Result<(), ServerError> { - std::fs::rename(&self.exe, self.exe.with_extension("old"))?; - std::fs::rename(&self.next, &self.exe)?; - Ok(()) - } -} -const BOARD_KEEP_MS: u64 = 7 * 24 * 60 * 60 * 1000; -const CHUNK: usize = 64 << 10; - fn path_of(directory: &Path, file: &Sha) -> PathBuf { directory.join(format!("{}.zst", hex(file))) } @@ -93,6 +76,19 @@ fn pack(bytes: &[u8], path: &Path) -> std::io::Result { Ok(encoder.finish()?.metadata()?.len()) } +fn stage(bytes: &[u8], path: &Path, next: Option<&Path>) -> Result { + let packed = pack(bytes, path)?; + if let Some(next) = next { + std::fs::write(next, bytes)?; + std::fs::set_permissions(next, std::fs::Permissions::from_mode(0o755))?; + probe(next).inspect_err(|_| { + let _ = std::fs::remove_file(next); + })?; + } + + Ok(packed) +} + #[derive(Clone)] pub struct Seen { pub user: Option, @@ -102,11 +98,18 @@ pub struct Seen { pub seen_ms: u64, } +#[derive(Clone)] +struct Pending { + staged: Staged, + protocol: String, +} + #[derive(Clone, Default)] pub struct Releases { directory: PathBuf, + exe: Option, forge: Option>, - staged: Arc>>, + staged: Arc>>, board: Arc>>, } @@ -124,9 +127,27 @@ impl Releases { let _ = std::fs::remove_file(&path); } } + let exe = std::env::current_exe().ok(); + if let Some(exe) = &exe { + let dir = exe.parent().unwrap_or(Path::new(".")); + for entry in std::fs::read_dir(dir)? { + let path = entry?.path(); + let staged_server = path.file_stem() == exe.file_stem() + && path + .extension() + .and_then(|ext| ext.to_str()) + .is_some_and(|ext| { + ext.len() == 64 && ext.bytes().all(|byte| byte.is_ascii_hexdigit()) + }); + if staged_server { + let _ = std::fs::remove_file(&path); + } + } + } Ok(Self { directory, + exe, forge: forge.map(Arc::new), staged: Default::default(), board: Default::default(), @@ -134,8 +155,10 @@ impl Releases { } pub fn record(&self, me: &Me, user: Option, state: UpdateState) { + let now = now_ms(); let mut board = self.board.lock().unwrap(); let user = user.or_else(|| board.get(&me.install).and_then(|seen| seen.user)); + board.retain(|_, seen| seen.seen_ms >= now.saturating_sub(BOARD_KEEP_MS)); board.insert( me.install, Seen { @@ -143,18 +166,19 @@ impl Releases { device: me.device.clone(), build: me.build, state, - seen_ms: now_ms(), + seen_ms: now, }, ); } pub fn recent(&self) -> Vec<(Install, Seen)> { let since = now_ms().saturating_sub(BOARD_KEEP_MS); - let mut board = self.board.lock().unwrap(); - board.retain(|_, seen| seen.seen_ms >= since); - board + self.board + .lock() + .unwrap() .iter() + .filter(|(_, seen)| seen.seen_ms >= since) .map(|(install, seen)| (*install, seen.clone())) .collect() } @@ -239,19 +263,19 @@ impl Releases { let target = target_of(&bytes).ok_or(CommonError::Release(ReleaseProblem::NotClient))?; let protocol = protocol_of(&bytes).ok_or(CommonError::Release(ReleaseProblem::NotClient))?; - if let Some(seq) = db - .run(async |conn| db::release::seq_of(&file, conn).await) + if let Some((seq, _)) = db + .run(async |conn| db::release::of_file(&file, conn).await) .await? { return Err(CommonError::Release(ReleaseProblem::Released(seq)).into()); } let path = path_of(&self.directory, &file); - let job = path.clone(); - let packed = tokio::task::spawn_blocking(move || pack(&bytes, &job)).await?; - let packed = packed.inspect_err(|_| { - let _ = std::fs::remove_file(&path); - })?; + let next = (target == SERVER_TARGET) + .then(|| self.next_exe(&file)) + .transpose()?; + let packed = + tokio::task::spawn_blocking(move || stage(&bytes, &path, next.as_deref())).await??; let staged = Staged { file, @@ -259,15 +283,18 @@ impl Releases { size, packed, }; - self.staged - .lock() - .unwrap() - .insert(file, (staged.clone(), protocol)); + self.staged.lock().unwrap().insert( + file, + Pending { + staged: staged.clone(), + protocol, + }, + ); Ok(staged) } - pub fn staged(&self, files: &[Sha]) -> Result, ServerError> { + pub fn pick(&self, files: &[Sha]) -> Result<(Vec, String), ServerError> { ensure_with( !files.is_empty(), CommonError::Release(ReleaseProblem::Empty), @@ -277,56 +304,64 @@ impl Releases { .iter() .map(|file| { map.get(file) - .map(|(staged, _)| staged.clone()) + .cloned() .ok_or(CommonError::Release(ReleaseProblem::NotStaged)) }) .collect::, _>>()?; - let targets: std::collections::HashSet<&str> = - picked.iter().map(|staged| staged.target.as_str()).collect(); + let targets: HashSet<&str> = picked + .iter() + .map(|pending| pending.staged.target.as_str()) + .collect(); ensure_with( targets.len() == picked.len(), CommonError::Release(ReleaseProblem::SameTarget), )?; + let protocols: HashSet<&str> = picked + .iter() + .map(|pending| pending.protocol.as_str()) + .collect(); + let [protocol] = protocols.into_iter().collect::>()[..] else { + return Err(CommonError::Release(ReleaseProblem::ProtocolSplit).into()); + }; + let protocol = protocol.to_string(); - Ok(picked) + Ok(( + picked.into_iter().map(|pending| pending.staged).collect(), + protocol, + )) } - pub fn protocol(&self, files: &[Sha]) -> Result { - let map = self.staged.lock().unwrap(); - let protocols: std::collections::HashSet<&str> = files - .iter() - .filter_map(|file| map.get(file)) - .map(|(_, protocol)| protocol.as_str()) - .collect(); - match protocols.into_iter().collect::>()[..] { - [protocol] => Ok(protocol.to_string()), - _ => Err(CommonError::Release(ReleaseProblem::ProtocolSplit).into()), - } + fn next_exe(&self, file: &Sha) -> Result { + let exe = self + .exe + .as_ref() + .ok_or_else(|| broken("own path unknown"))?; + Ok(exe.with_extension(hex(file))) } - pub fn prepare_server(&self, staged: &[Staged]) -> Result, ServerError> { - let Some(server) = staged.iter().find(|staged| staged.target == SERVER_TARGET) else { - return Ok(None); - }; - let exe = EXE.clone().ok_or_else(|| broken("own path unknown"))?; - let next = exe.with_extension("new"); - let packed = std::fs::File::open(path_of(&self.directory, &server.file))?; - let mut decoder = zstd::Decoder::new(packed)?; - let mut out = std::fs::File::create(&next)?; - std::io::copy(&mut decoder, &mut out)?; - drop(out); - use std::os::unix::fs::PermissionsExt; - std::fs::set_permissions(&next, std::fs::Permissions::from_mode(0o755))?; - probe(&next).inspect_err(|_| { - let _ = std::fs::remove_file(&next); - })?; - Ok(Some(NextServer { next, exe })) + pub fn swap(&self, file: &Sha) -> Result<(), ServerError> { + let exe = self + .exe + .as_ref() + .ok_or_else(|| broken("own path unknown"))?; + let next = self.next_exe(file)?; + let old = exe.with_extension("old"); + std::fs::rename(exe, &old)?; + if let Err(error) = std::fs::rename(&next, exe) { + let _ = std::fs::rename(&old, exe); + return Err(error.into()); + } + + Ok(()) } pub fn unstage(&self, files: &[Sha]) { let mut map = self.staged.lock().unwrap(); for file in files { map.remove(file); + if let Ok(next) = self.next_exe(file) { + let _ = std::fs::remove_file(next); + } } } @@ -357,35 +392,7 @@ impl Releases { self.record(&me, who(&me, db).await, state_of(status)); frame::write(&mut send, &status, DOWN_MAX).await?; } - Ask::Download { me, file } => { - let live = db.run(async |conn| db::release::live(conn).await).await?; - if live.contains(&file) { - let user = who(&me, db).await; - let seq = db - .run(async |conn| db::release::seq_of(&file, conn).await) - .await? - .unwrap_or_default(); - let mut packed = tokio::fs::File::open(path_of(&self.directory, &file)).await?; - let total = packed.metadata().await?.len().max(1); - let mut buffer = vec![0u8; CHUNK]; - let mut sent = 0; - let mut shown = 0; - loop { - let read = packed.read(&mut buffer).await?; - if read == 0 { - break; - } - send.get().write_all(&buffer[..read]).await?; - sent += read as u64; - let percent = (sent * 100 / total) as u8; - if percent != shown { - shown = percent; - let state = UpdateState::Downloading { seq, percent }; - self.record(&me, user, state); - } - } - } - } + Ask::Download { me, file } => self.send_release(&me, file, db, &mut send).await?, Ask::Report { me, progress } => { let seq = self .board @@ -405,6 +412,52 @@ impl Releases { Ok(()) } + + async fn send_release( + &self, + me: &Me, + file: Sha, + db: &Db, + send: &mut Sending, + ) -> Result<(), ServerError> { + let seq = db + .run(async |conn| { + if !db::release::live(conn).await?.contains(&file) { + return Ok(None); + } + Ok(Some( + db::release::of_file(&file, conn) + .await? + .map(|(seq, _)| seq) + .unwrap_or_default(), + )) + }) + .await?; + let Some(seq) = seq else { + return Ok(()); + }; + let user = who(me, db).await; + let mut packed = tokio::fs::File::open(path_of(&self.directory, &file)).await?; + let total = packed.metadata().await?.len().max(1); + let mut buffer = vec![0u8; CHUNK]; + let mut sent = 0; + let mut shown = 0; + loop { + let read = packed.read(&mut buffer).await?; + if read == 0 { + break; + } + send.get().write_all(&buffer[..read]).await?; + sent += read as u64; + let percent = (sent * 100 / total) as u8; + if percent != shown { + shown = percent; + self.record(me, user, UpdateState::Downloading { seq, percent }); + } + } + + Ok(()) + } } async fn who(me: &Me, db: &Db) -> Option { @@ -439,7 +492,7 @@ fn seq_in(state: &UpdateState) -> u64 { } async fn status(build: Sha, targets: &[String], db: &DbConnection) -> Result { - let Some(current) = db::release::seq_of(&build, db).await? else { + let Some((current, _)) = db::release::of_file(&build, db).await? else { return Ok(Status::Unknown); }; let mut offered = None; diff --git a/crates/usage/Cargo.toml b/crates/usage/Cargo.toml index 4e7f6a7..128ae7a 100644 --- a/crates/usage/Cargo.toml +++ b/crates/usage/Cargo.toml @@ -6,15 +6,15 @@ edition = "2024" [dependencies] common.workspace = true cpu-time = "1.0.0" -sysinfo = { version = "0.40.4", default-features = false, features = ["system", "disk"] } +sysinfo = { workspace = true, features = ["system", "disk"] } [target.'cfg(any(target_os = "linux", target_os = "windows"))'.dependencies] nvml-wrapper = "0.13.0" [target.'cfg(target_os = "windows")'.dependencies] wmi = "0.18.4" -winreg = "0.56.0" -serde = { version = "1.0.229", features = ["derive"] } +winreg.workspace = true +serde.workspace = true [lints] workspace = true diff --git a/crates/usage/src/drm.rs b/crates/usage/src/drm.rs index a3ce2f5..d2928a6 100644 --- a/crates/usage/src/drm.rs +++ b/crates/usage/src/drm.rs @@ -1,11 +1,12 @@ use std::{ collections::{HashMap, HashSet}, fs, - sync::Arc, + iter::Sum, + ops::Add, time::Instant, }; -use super::{Gpu, GpuMachine}; +use super::{Gpu, GpuMachine, mb}; #[derive(Clone, Copy, Default)] struct Group { @@ -13,7 +14,9 @@ struct Group { cycles: u64, } -impl Group { +impl Add for Group { + type Output = Self; + fn add(self, other: Self) -> Self { Self { busy: self.busy + other.busy, @@ -22,14 +25,6 @@ impl Group { } } -struct Client { - id: Option, - pdev: String, - gfx: Group, - video: Group, - vram_kib: u64, -} - #[derive(Clone, Copy, Default)] struct Totals { gfx: Group, @@ -37,24 +32,30 @@ struct Totals { vram_kib: u64, } -impl Totals { +impl Add for Totals { + type Output = Self; + fn add(self, other: Self) -> Self { Self { - gfx: self.gfx.add(other.gfx), - video: self.video.add(other.video), + gfx: self.gfx + other.gfx, + video: self.video + other.video, vram_kib: self.vram_kib + other.vram_kib, } } +} - fn of<'a>(clients: impl Iterator) -> Self { - clients.fold(Self::default(), |sum, client| Self { - gfx: sum.gfx.add(client.gfx), - video: sum.video.add(client.video), - vram_kib: sum.vram_kib + client.vram_kib, - }) +impl Sum for Totals { + fn sum>(iter: I) -> Self { + iter.fold(Self::default(), Add::add) } } +struct Client { + id: Option, + pdev: String, + totals: Totals, +} + #[derive(Clone)] struct Snapshot { at: Instant, @@ -67,10 +68,14 @@ impl Snapshot { fn read() -> Option { let own = dedupe(own_clients()); let pdev = own.first()?.pdev.clone(); - let own = Totals::of(own.iter().filter(|client| client.pdev == pdev)); + let own: Totals = own + .iter() + .filter(|client| client.pdev == pdev) + .map(|client| client.totals) + .sum(); let machine = machine_clients(&pdev) .into_iter() - .filter_map(|client| Some((client.id?, Totals::of([&client].into_iter())))) + .filter_map(|client| Some((client.id?, client.totals))) .collect(); Some(Self { at: Instant::now(), @@ -84,7 +89,7 @@ impl Snapshot { #[derive(Default)] pub struct Sampler { previous: Option, - model: Option>, + model: Option, } impl Sampler { @@ -96,22 +101,21 @@ impl Sampler { .model .get_or_insert_with(|| read_gpu_model(¤t.pdev)) .clone(); - let (machine_now, machine_before) = current.machine.iter().fold( - (Totals::default(), Totals::default()), - |(now_sum, before_sum), (id, now)| { - let before = previous.machine.get(id).copied().unwrap_or_default(); - (now_sum.add(*now), before_sum.add(before)) - }, - ); + let machine_now: Totals = current.machine.values().copied().sum(); + let machine_before: Totals = current + .machine + .iter() + .map(|(id, now)| previous.machine.get(id).copied().unwrap_or(*now)) + .sum(); Some(Gpu { - model: model.to_string(), + model, gfx: percent(current.own.gfx, previous.own.gfx, wall), video: percent(current.own.video, previous.own.video, wall), - vram_mb: (current.own.vram_kib >> 10) as u32, + vram_mb: mb(current.own.vram_kib << 10), machine: GpuMachine { gfx: percent(machine_now.gfx, machine_before.gfx, wall), video: percent(machine_now.video, machine_before.video, wall), - vram_used_mb: (machine_now.vram_kib >> 10) as u32, + vram_used_mb: mb(machine_now.vram_kib << 10), vram_total_mb: vram_total_mb(¤t.pdev), }, }) @@ -187,16 +191,18 @@ fn client(info: &str) -> Option { Some(Client { id: value(&fields, "drm-client-id"), pdev: fields.get("drm-pdev")?.to_string(), - gfx: group(&fields, &["gfx", "render"], &["rcs"]), - video: group( - &fields, - &["enc", "dec", "video", "video-enhance"], - &["vcs", "vecs"], - ), - vram_kib: ["drm-memory-vram", "drm-total-vram0", "drm-total-local0"] - .iter() - .find_map(|key| value(&fields, key)) - .unwrap_or(0), + totals: Totals { + gfx: group(&fields, &["gfx", "render"], &["rcs"]), + video: group( + &fields, + &["enc", "dec", "video", "video-enhance"], + &["vcs", "vecs"], + ), + vram_kib: ["drm-memory-vram", "drm-total-vram0", "drm-total-local0"] + .iter() + .find_map(|key| value(&fields, key)) + .unwrap_or(0), + }, }) } @@ -239,7 +245,7 @@ fn group(fields: &HashMap<&str, &str>, engines: &[&str], classes: &[&str]) -> Gr fn vram_total_mb(pdev: &str) -> u32 { device_file(pdev, "mem_info_vram_total") .and_then(|value| value.parse::().ok()) - .map_or(0, |bytes| (bytes >> 20) as u32) + .map_or(0, mb) } fn device_file(pdev: &str, name: &str) -> Option { @@ -248,16 +254,14 @@ fn device_file(pdev: &str, name: &str) -> Option { .map(|value| value.trim().to_string()) } -fn read_gpu_model(pdev: &str) -> Arc { +fn read_gpu_model(pdev: &str) -> String { let id = |name: &str| { device_file(pdev, name).map(|value| value.trim_start_matches("0x").to_lowercase()) }; let (Some(vendor), Some(device)) = (id("vendor"), id("device")) else { - return Arc::from(""); + return String::new(); }; - pci_name(&vendor, &device) - .unwrap_or_else(|| format!("{vendor}:{device}")) - .into() + pci_name(&vendor, &device).unwrap_or_else(|| format!("{vendor}:{device}")) } fn pci_name(vendor: &str, device: &str) -> Option { diff --git a/crates/usage/src/lib.rs b/crates/usage/src/lib.rs index d772410..2af9ddc 100644 --- a/crates/usage/src/lib.rs +++ b/crates/usage/src/lib.rs @@ -1,6 +1,6 @@ use std::{ path::{Path, PathBuf}, - sync::{Arc, Mutex}, + sync::{Arc, Mutex, Weak}, thread, time::{Duration, Instant}, }; @@ -26,45 +26,33 @@ const IDLE_AFTER: Duration = Duration::from_secs(3); pub use common::stats::{Gpu, GpuMachine, Memory, Storage, Threads, Usage}; pub use threads::{Group, tick}; +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum Wake { + Always, + OnDemand, +} + struct Shared { latest: Option, requested: Instant, - awake: bool, - disk: Option, } pub struct Monitor { shared: Arc>, } -impl Default for Monitor { - fn default() -> Self { +impl Monitor { + pub fn new(wake: Wake, disk: Option) -> Self { let shared = Arc::new(Mutex::new(Shared { latest: None, requested: Instant::now(), - awake: false, - disk: None, })); let worker = Arc::downgrade(&shared); let _ = thread::Builder::new() .name("usage".to_string()) - .spawn(move || run(worker)); + .spawn(move || run(worker, wake, disk)); Self { shared } } -} - -impl Monitor { - pub fn watch_disk(&self, path: PathBuf) { - if let Ok(mut shared) = self.shared.lock() { - shared.disk = Some(path); - } - } - - pub fn stay_awake(&self) { - if let Ok(mut shared) = self.shared.lock() { - shared.awake = true; - } - } pub fn latest(&self) -> Option { let mut shared = self.shared.lock().ok()?; @@ -73,21 +61,21 @@ impl Monitor { } } -fn run(shared: std::sync::Weak>) { +pub(crate) fn mb(bytes: u64) -> u32 { + (bytes / (1024 * 1024)) as u32 +} + +fn run(shared: Weak>, wake: Wake, disk: Option) { let mut sampler: Option = None; loop { thread::sleep(INTERVAL); let Some(shared) = shared.upgrade() else { return; }; - let Some((wanted, disk)) = shared.lock().ok().map(|shared| { - ( - shared.awake || shared.requested.elapsed() < IDLE_AFTER, - shared.disk.clone(), - ) - }) else { + let Ok(requested) = shared.lock().map(|shared| shared.requested) else { return; }; + let wanted = wake == Wake::Always || requested.elapsed() < IDLE_AFTER; let usage = if wanted { if sampler.is_none() { sampler = Sampler::new(); @@ -111,7 +99,7 @@ struct Sampler { cores: f32, host: String, os: String, - cpu_model: Arc, + cpu_model: String, primed: bool, gpu: GpuSampler, threads: threads::Sampler, @@ -127,8 +115,7 @@ impl Sampler { .cpus() .first() .map(|cpu| cpu.brand().trim().to_string()) - .unwrap_or_default() - .into(); + .unwrap_or_default(); Some(Self { host: System::host_name().unwrap_or_default(), os: os(), @@ -155,13 +142,12 @@ impl Sampler { return None; } let process = self.system.process(self.pid)?; - let mb = |bytes: u64| (bytes / (1024 * 1024)) as u32; let total = self.system.total_memory(); let threads = self.threads.sample(self.cores); Some(Usage { host: self.host.clone(), os: self.os.clone(), - cpu_model: self.cpu_model.to_string(), + cpu_model: self.cpu_model.clone(), machine: self.system.global_cpu_usage(), total: process.cpu_usage() / self.cores, threads, @@ -224,7 +210,6 @@ fn storage(path: &Path) -> Option { .iter() .filter(|disk| path.starts_with(disk.mount_point())) .max_by_key(|disk| disk.mount_point().as_os_str().len())?; - let mb = |bytes: u64| (bytes / (1024 * 1024)) as u32; Some(Storage { used_mb: mb(disk.total_space().saturating_sub(disk.available_space())), total_mb: mb(disk.total_space()), diff --git a/crates/usage/src/mac.rs b/crates/usage/src/mac.rs index 974f0f0..41b98d9 100644 --- a/crates/usage/src/mac.rs +++ b/crates/usage/src/mac.rs @@ -1,6 +1,6 @@ use std::process::Command; -use super::{Gpu, GpuMachine}; +use super::{Gpu, GpuMachine, mb}; #[derive(Default)] pub struct Sampler; @@ -26,7 +26,6 @@ impl Sampler { .and_then(|at| text[at..].split('"').next()) .unwrap_or_default() .to_string(); - let mb = |bytes: u64| (bytes / (1024 * 1024)) as u32; Some(Gpu { model, machine: GpuMachine { diff --git a/crates/usage/src/nvidia.rs b/crates/usage/src/nvidia.rs index bfcade2..1ad7833 100644 --- a/crates/usage/src/nvidia.rs +++ b/crates/usage/src/nvidia.rs @@ -1,10 +1,8 @@ -use std::{process, sync::Arc}; +use std::process; use nvml_wrapper::{Nvml, enums::device::UsedGpuMemory}; -use super::{Gpu, GpuMachine}; - -const MIB: u64 = 1024 * 1024; +use super::{Gpu, GpuMachine, mb}; #[derive(Default)] enum State { @@ -18,7 +16,7 @@ enum State { pub struct Sampler { state: State, last_seen: Option, - model: Option>, + model: Option, } impl Sampler { @@ -64,7 +62,7 @@ impl Sampler { }, ); let vram_mb = match process.used_gpu_memory { - UsedGpuMemory::Used(bytes) => (bytes / MIB) as u32, + UsedGpuMemory::Used(bytes) => mb(bytes), UsedGpuMemory::Unavailable => 0, }; let machine_gfx = device.utilization_rates().map_or(0, |rates| rates.gpu); @@ -76,22 +74,22 @@ impl Sampler { .decoder_utilization() .map_or(0, |info| info.utilization), ); - let (vram_used_mb, vram_total_mb) = device.memory_info().map_or((0, 0), |memory| { - ((memory.used / MIB) as u32, (memory.total / MIB) as u32) - }); + let (vram_used_mb, vram_total_mb) = device + .memory_info() + .map_or((0, 0), |memory| (mb(memory.used), mb(memory.total))); let model = self .model .get_or_insert_with(|| { let name = device.name().unwrap_or_default(); if name.contains("NVIDIA") { - name.into() + name } else { - format!("NVIDIA {name}").into() + format!("NVIDIA {name}") } }) .clone(); return Some(Gpu { - model: model.to_string(), + model, gfx: gfx as f32, video: video as f32, vram_mb, diff --git a/crates/usage/src/threads.rs b/crates/usage/src/threads.rs index a02828d..1bd5a33 100644 --- a/crates/usage/src/threads.rs +++ b/crates/usage/src/threads.rs @@ -1,7 +1,6 @@ use std::{ - collections::HashMap, - sync::{LazyLock, Mutex}, - thread::{self, ThreadId}, + cell::Cell, + sync::Mutex, time::{Duration, Instant}, }; @@ -17,27 +16,28 @@ pub enum Group { Decode, } -type Spent = [Duration; 4]; +const GROUPS: usize = 4; +type Spent = [Duration; GROUPS]; -static SPENT: LazyLock>> = - LazyLock::new(Default::default); +static SPENT: Mutex = Mutex::new([Duration::ZERO; GROUPS]); + +thread_local! { + static LAST: Cell = const { Cell::new(Duration::ZERO) }; +} pub fn tick(group: Group) { let Ok(time) = ThreadTime::try_now() else { return; }; + let time = time.as_duration(); + let delta = time.saturating_sub(LAST.with(|last| last.replace(time))); if let Ok(mut spent) = SPENT.lock() { - spent.insert(thread::current().id(), (group, time.as_duration())); + spent[group as usize] += delta; } } fn spent() -> Option { - let spent = SPENT.lock().ok()?; - let mut total = Spent::default(); - for (group, time) in spent.values() { - total[*group as usize] += *time; - } - Some(total) + SPENT.lock().ok().map(|spent| *spent) } #[derive(Default)] diff --git a/crates/usage/src/windows.rs b/crates/usage/src/windows.rs index 26d35dc..0981db2 100644 --- a/crates/usage/src/windows.rs +++ b/crates/usage/src/windows.rs @@ -1,10 +1,10 @@ -use std::{collections::HashMap, sync::Arc, time::Instant}; +use std::{collections::HashMap, mem, time::Instant}; use serde::{Deserialize, Deserializer}; use winreg::{RegKey, enums::HKEY_LOCAL_MACHINE}; use wmi::WMIConnection; -use super::{Gpu, GpuMachine}; +use super::{Gpu, GpuMachine, mb}; #[derive(Deserialize)] #[serde(untagged)] @@ -66,7 +66,7 @@ pub struct Sampler { conn: Option, last: Option, prev: HashMap<(u32, String, u32), u64>, - adapters: HashMap, u32)>, + adapters: HashMap, } impl Sampler { @@ -90,10 +90,21 @@ impl Sampler { .collect(); let me = std::process::id(); let now = Instant::now(); - let wall = self.last.map_or(0.0, |last| { + let wall = self.last.replace(now).map_or(0.0, |last| { now.duration_since(last).as_nanos() as f64 / 100.0 }); - self.last = Some(now); + let prev = mem::replace( + &mut self.prev, + engines + .iter() + .map(|engine| { + ( + (engine.pid, engine.luid.clone(), engine.index), + engine.running, + ) + }) + .collect(), + ); let mut totals: HashMap<&str, u64> = HashMap::new(); for engine in engines.iter().filter(|engine| engine.pid == me) { @@ -110,7 +121,7 @@ impl Sampler { .filter(|engine| engine.luid == luid) .map(|engine| { let key = (engine.pid, engine.luid.clone(), engine.index); - let before = self.prev.get(&key).copied().unwrap_or(engine.running); + let before = prev.get(&key).copied().unwrap_or(engine.running); let delta = engine.running.saturating_sub(before) as f64; ( engine, @@ -135,15 +146,6 @@ impl Sampler { .map(|(engine, util)| (engine.kind.as_str(), *util)) .collect(); let machine: Vec<(&str, f64)> = machine_by_engine.values().copied().collect(); - self.prev = engines - .iter() - .map(|engine| { - ( - (engine.pid, engine.luid.clone(), engine.index), - engine.running, - ) - }) - .collect(); let processes: Vec = conn.query().ok()?; let vram_mb = processes @@ -163,14 +165,10 @@ impl Sampler { self.adapters.insert(luid.clone(), info); } } - let (model, vram_total_mb) = self - .adapters - .get(&luid) - .cloned() - .unwrap_or_else(|| (Arc::from(""), 0)); + let (model, vram_total_mb) = self.adapters.get(&luid).cloned().unwrap_or_default(); Some(Gpu { - model: model.to_string(), + model, gfx: peak(&own, is_gfx), video: peak(&own, is_video), vram_mb, @@ -219,11 +217,7 @@ fn kind_of(name: &str) -> Option<&str> { name.split("_engtype_").nth(1) } -fn mb(bytes: u64) -> u32 { - (bytes / (1024 * 1024)) as u32 -} - -fn adapter_info(luid: &str) -> Option<(Arc, u32)> { +fn adapter_info(luid: &str) -> Option<(String, u32)> { let directx = RegKey::predef(HKEY_LOCAL_MACHINE) .open_subkey("SOFTWARE\\Microsoft\\DirectX") .ok()?; @@ -234,7 +228,7 @@ fn adapter_info(luid: &str) -> Option<(Arc, u32)> { (key_luid == luid).then(|| { let model: String = key.get_value("Description").unwrap_or_default(); let total: u64 = key.get_value("DedicatedVideoMemory").unwrap_or_default(); - (Arc::from(model), mb(total)) + (model, mb(total)) }) }) } diff --git a/harness/audio.sh b/harness/audio.sh index 1204e9a..e14dafb 100755 --- a/harness/audio.sh +++ b/harness/audio.sh @@ -1,6 +1,7 @@ #!/usr/bin/env bash set -euo pipefail -STATE="${HARNESS_STATE:-/tmp/claude-1000/yumush-harness}" +HERE="$(cd "$(dirname "$0")" && pwd)" +source "$HERE/lib.sh" source "$STATE/env" out="$STATE/audio" mkdir -p "$out" diff --git a/harness/bench.sh b/harness/bench.sh index 5f8485b..9233913 100755 --- a/harness/bench.sh +++ b/harness/bench.sh @@ -1,22 +1,21 @@ #!/usr/bin/env bash set -euo pipefail HERE="$(cd "$(dirname "$0")" && pwd)" -STATE="${HARNESS_STATE:-/tmp/claude-1000/yumush-harness}" +source "$HERE/lib.sh" CAPTURE="${CAPTURE:-2560x1440@60}" MODE="${MODE:-share}" DROP="${DROP:-0}" WARM="${WARM:-60}" SPAN="${SPAN:-20}" -export HARNESS_STATE="$STATE" export YUMUSH_METRICS=1 E="$STATE/env2" lo() { awk '/^ *lo:/ {print $2}' /proc/net/dev; } drops() { awk '/^Udp:/ {v=$6} END {print v}' /proc/net/snmp; } -pid() { awk -v n="$1" '$1 == n {print $2}' "$STATE/pids" | tail -1; } -ticks() { awk '{print $14 + $15}' "/proc/$1/stat"; } plain() { sed 's/\x1b\[[0-9;]*m//g' "$1" | tail -n "+$2"; } avg() { grep "metrics: $2 " | grep -o "$1=[0-9.]*" | cut -d= -f2 | awk '{s+=$1; n++} END {printf "%.1f", n ? s/n : 0}'; } +talker="" +trap '{ kill "${talker:-}" 2>/dev/null || true; "$HERE/down.sh" >/dev/null 2>&1 || true; }' EXIT "$HERE/up.sh" >/dev/null YUMUSH_TEST_DROP="$DROP" YUMUSH_TEST_CAMERA=1 YUMUSH_TEST_CAPTURE="$CAPTURE" "$HERE/client.sh" alice >/dev/null YUMUSH_TEST_DROP="$DROP" ENV_FILE="$E" "$HERE/client.sh" bob >/dev/null @@ -31,7 +30,6 @@ sleep 2 sleep 2 ENV_FILE="$E" "$HERE/ui.sh" click 1820 29 sleep 3 -talker="" if [ "$MODE" = voice ]; then "$HERE/talk.sh" >/dev/null 2>&1 & talker=$! @@ -48,7 +46,7 @@ b=$(lo); d=$(drops); ta=$(ticks "$A"); tb=$(ticks "$B"); ts=$(ticks "$S") sleep "$SPAN" a=$(lo); D=$(drops); TA=$(ticks "$A"); TB=$(ticks "$B"); TS=$(ticks "$S") alice=$(plain "$STATE/alice.log" "$la"); bob=$(plain "$STATE/bob.log" "$lb") -cpu() { echo $(( ($2 - $1) * 100 / 100 / SPAN )); } +cpu() { echo $(( ($2 - $1) / SPAN )); } echo "mode=$MODE drop=$DROP capture=$CAPTURE span=${SPAN}s" echo "loopback kbps: $(( (a - b) * 8 / 1000 / SPAN )) udp drops: $((D - d))" echo "cpu %: alice $(cpu "$ta" "$TA") bob $(cpu "$tb" "$TB") server $(cpu "$ts" "$TS")" @@ -60,6 +58,4 @@ if [ "$MODE" = share ]; then echo "watch: kbps $(echo "$bob" | avg kbps watch) fps $(echo "$bob" | avg fps watch) latency ms $(echo "$bob" | avg latency watch) frame loss $(echo "$bob" | avg loss watch) keyframes $k" grep -h "share watch quality" "$STATE/bob.log" | sed 's/\x1b\[[0-9;]*m//g' | tail -1 || true fi -[ -n "$talker" ] && kill "$talker" 2>/dev/null ENV_FILE="$E" "$HERE/shot.sh" bench >/dev/null -"$HERE/down.sh" >/dev/null 2>&1 diff --git a/harness/client.sh b/harness/client.sh index 60a92b4..0364c24 100755 --- a/harness/client.sh +++ b/harness/client.sh @@ -1,11 +1,10 @@ #!/usr/bin/env bash set -euo pipefail HERE="$(cd "$(dirname "$0")" && pwd)" -ROOT="$(dirname "$HERE")" -STATE="${HARNESS_STATE:-/tmp/claude-1000/yumush-harness}" +source "$HERE/lib.sh" NAME="$1" source "${ENV_FILE:-$STATE/env}" mkdir -p "$STATE/clients/$NAME" -YUMUSH_ANY_CERT=1 YUMUSH_SERVER_ADDRESS="127.0.0.1:${HARNESS_PORT:-2027}" XDG_CONFIG_HOME="$STATE/clients/$NAME" XDG_DATA_HOME="$STATE/clients/$NAME/data" XDG_CACHE_HOME="$STATE/clients/$NAME/cache" RUST_LOG="${RUST_LOG:-info}" "$ROOT/target/${PROFILE:-harness}/client" >"$STATE/$NAME.log" 2>&1 & +YUMUSH_ANY_CERT=1 YUMUSH_SERVER_ADDRESS="127.0.0.1:$PORT" XDG_CONFIG_HOME="$STATE/clients/$NAME" XDG_DATA_HOME="$STATE/clients/$NAME/data" XDG_CACHE_HOME="$STATE/clients/$NAME/cache" RUST_LOG="${RUST_LOG:-info}" "$BIN/client" >"$STATE/$NAME.log" 2>&1 & echo "$NAME $!" >> "$STATE/pids" echo "$NAME $!" diff --git a/harness/codec.sh b/harness/codec.sh index 53f68d6..247759f 100755 --- a/harness/codec.sh +++ b/harness/codec.sh @@ -1,11 +1,13 @@ #!/usr/bin/env bash set -euo pipefail -cd "$(dirname "$0")" +HERE="$(cd "$(dirname "$0")" && pwd)" +source "$HERE/lib.sh" +cd "$HERE" ./ui.sh click 600 400 ./ui.sh click 172 981; sleep 0.8; ./ui.sh click "$1" 882; sleep 0.5; ./ui.sh click 600 400 ./ui.sh click 144 980; sleep 2; ./ui.sh click 144 980; sleep 3 ./ui.sh click 1740 28; sleep 6 ./ui.sh click 1020 1000 right; sleep 0.6; ./ui.sh click 1087 598; sleep 2.5 ./shot.sh "codec-$2" >/dev/null -magick "/tmp/claude-1000/yumush-harness/shots/codec-$2.png" -crop 300x200+970+600 "/tmp/claude-1000/yumush-harness/shots/c-$2.png" +magick "$STATE/shots/codec-$2.png" -crop 300x200+970+600 "$STATE/shots/c-$2.png" ./ui.sh click 1500 300 diff --git a/harness/compare.sh b/harness/compare.sh index 3eede32..0271345 100755 --- a/harness/compare.sh +++ b/harness/compare.sh @@ -1,14 +1,14 @@ #!/usr/bin/env bash set -euo pipefail -STATE="${HARNESS_STATE:-/tmp/claude-1000/yumush-harness}" +HERE="$(cd "$(dirname "$0")" && pwd)" +source "$HERE/lib.sh" page="$1" state="$2" artifact="$3" out="$STATE/shots/gallery" -size=1120,720 -[ "$state" = narrow ] && size=800,600 +size="$(window_size "$state")" profile="$(mktemp -d -p "$STATE")" -firefox --headless --profile "$profile" --window-size "$size" --screenshot "$out/$page-$state-artifact.png" "file://$artifact#$page:$state" >/dev/null 2>&1 +firefox --headless --profile "$profile" --window-size "${size/x/,}" --screenshot "$out/$page-$state-artifact.png" "file://$artifact#$page:$state" >/dev/null 2>&1 rm -rf "$profile" magick montage "$out/$page-$state-artifact.png" "$out/$page-$state.png" -tile 2x1 -geometry +8+8 -background '#808080' "$out/$page-$state-compare.png" echo "$out/$page-$state-compare.png" diff --git a/harness/down.sh b/harness/down.sh index 30508a6..f163bb8 100755 --- a/harness/down.sh +++ b/harness/down.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash -STATE="${HARNESS_STATE:-/tmp/claude-1000/yumush-harness}" +source "$(dirname "$0")/lib.sh" [ -f "$STATE/pids" ] || exit 0 tac "$STATE/pids" | while read -r name pid; do kill "$pid" 2>/dev/null && echo "stopped $name $pid"; done -systemctl --user stop yumush-harness-session.scope 2>/dev/null +systemctl --user stop "yumush-harness-$PORT.scope" 2>/dev/null rm -f "$STATE/pids" "$STATE/env" "$STATE/env2" diff --git a/harness/fps.py b/harness/fps.py index a502f93..20129bd 100644 --- a/harness/fps.py +++ b/harness/fps.py @@ -14,6 +14,8 @@ def find_video(im): def read(path): im = Image.open(path).convert("RGB") top = find_video(im) + if top is None: + raise SystemExit("video area not found in shot") s = (x1 - x0) / src_w n = 0 for i in range(32): diff --git a/harness/gallery.sh b/harness/gallery.sh index 116593b..ebeb996 100755 --- a/harness/gallery.sh +++ b/harness/gallery.sh @@ -1,8 +1,7 @@ #!/usr/bin/env bash set -euo pipefail HERE="$(cd "$(dirname "$0")" && pwd)" -ROOT="$(dirname "$HERE")" -STATE="${HARNESS_STATE:-/tmp/claude-1000/yumush-harness}" +source "$HERE/lib.sh" source "${ENV_FILE:-$STATE/env}" page="$1" shift @@ -11,9 +10,8 @@ states=("$@") out="$STATE/shots/gallery" mkdir -p "$out" for state in "${states[@]}"; do - size=1120x720 - [ "$state" = narrow ] && size=800x600 - YUMUSH_GALLERY="$page:$state" "$ROOT/target/${PROFILE:-harness}/client" >"$STATE/gallery.log" 2>&1 & + size="$(window_size "$state")" + YUMUSH_GALLERY="$page:$state" "$BIN/client" >"$STATE/gallery.log" 2>&1 & pid=$! sleep "${GALLERY_WAIT:-2}" grim "$out/full.png" diff --git a/harness/imports.sh b/harness/imports.sh index 2b3c25e..8755622 100755 --- a/harness/imports.sh +++ b/harness/imports.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash set -euo pipefail -exe="${1:-$(dirname "$0")/../target/windows/yumush.exe}" +exe="$1" core="advapi32 api-ms-win-core-synch-l1-2-0 api-ms-win-core-winrt-error-l1-1-0 api-ms-win-core-winrt-l1-1-0 api-ms-win-shcore-scaling-l1-1-1 bcrypt bcryptprimitives combase comctl32 coremessaging crypt32 d3d11 dcomp dwmapi dwrite dxgi gdi32 gdiplus icuuc imm32 kernel32 mmdevapi msimg32 ntdll ole32 oleaut32 pdh powrprof diff --git a/harness/lib.sh b/harness/lib.sh new file mode 100644 index 0000000..5bfb7c3 --- /dev/null +++ b/harness/lib.sh @@ -0,0 +1,10 @@ +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +STATE="${HARNESS_STATE:-/tmp/claude-1000/yumush-harness}" +PORT="${HARNESS_PORT:-2027}" +PROFILE="${PROFILE:-harness}" +BIN="$ROOT/target/$PROFILE" +export HARNESS_STATE="$STATE" +[ "${#STATE}" -le 80 ] || { echo "HARNESS_STATE too long (${#STATE} > 80): pipewire/instance sockets exceed 108 bytes" >&2; exit 1; } +pid() { awk -v n="$1" '$1 == n {print $2}' "$STATE/pids" | tail -1; } +ticks() { awk '{print $14 + $15}' "/proc/$1/stat"; } +window_size() { if [ "$1" = narrow ]; then echo 800x600; else echo 1120x720; fi; } diff --git a/harness/niri.kdl b/harness/niri.kdl index 7aa85a9..55e409e 100644 --- a/harness/niri.kdl +++ b/harness/niri.kdl @@ -11,6 +11,12 @@ prefer-no-csd screenshot-path null layout { gaps 0 + focus-ring { + off + } + border { + off + } default-column-width { proportion 0.5; } } gestures { diff --git a/harness/session.sh b/harness/session.sh index 3cde21c..eda6304 100755 --- a/harness/session.sh +++ b/harness/session.sh @@ -14,17 +14,20 @@ echo "wireplumber $!" >> "$STATE/pids" sleep 0.5 dbus-update-activation-environment PIPEWIRE_RUNTIME_DIR="$PIPEWIRE_RUNTIME_DIR" XDG_CURRENT_DESKTOP=niri XDG_SESSION_TYPE=wayland XDG_CONFIG_HOME="$STATE/xdg" compositor() { - local socket="" + local socket="" pid ipc NO_COLOR=1 niri --headless -c "$HERE/niri.kdl" >"$STATE/$1.log" 2>&1 & - echo "$1 $!" >> "$STATE/pids" + pid=$! + echo "$1 $pid" >> "$STATE/pids" for _ in $(seq 100); do socket="$(grep -o 'listening on Wayland socket: wayland-[0-9]*' "$STATE/$1.log" | grep -o 'wayland-[0-9]*' || true)" - [ -n "$socket" ] && break + ipc="$XDG_RUNTIME_DIR/niri.$socket.$pid.sock" + [ -n "$socket" ] && [ -S "$ipc" ] && break sleep 0.1 done + [ -S "$ipc" ] || { echo "$1: niri did not come up" >&2; exit 1; } { echo "export WAYLAND_DISPLAY=$socket" - echo "export NIRI_SOCKET=$(ls "$XDG_RUNTIME_DIR"/niri.$socket.*.sock | head -1)" + echo "export NIRI_SOCKET=$ipc" echo "export DBUS_SESSION_BUS_ADDRESS=$DBUS_SESSION_BUS_ADDRESS" echo "export XDG_CURRENT_DESKTOP=niri" echo "export PIPEWIRE_RUNTIME_DIR=$PIPEWIRE_RUNTIME_DIR" diff --git a/harness/shot.sh b/harness/shot.sh index d7fe011..c140f27 100755 --- a/harness/shot.sh +++ b/harness/shot.sh @@ -1,5 +1,6 @@ #!/usr/bin/env bash -STATE="${HARNESS_STATE:-/tmp/claude-1000/yumush-harness}" +HERE="$(cd "$(dirname "$0")" && pwd)" +source "$HERE/lib.sh" source "${ENV_FILE:-$STATE/env}" out="$STATE/shots/${1:-shot}.png" grim "$out" && echo "$out" diff --git a/harness/talk.sh b/harness/talk.sh index b68e3e5..0229105 100755 --- a/harness/talk.sh +++ b/harness/talk.sh @@ -1,6 +1,7 @@ #!/usr/bin/env bash set -euo pipefail -STATE="${HARNESS_STATE:-/tmp/claude-1000/yumush-harness}" +HERE="$(cd "$(dirname "$0")" && pwd)" +source "$HERE/lib.sh" source "${ENV_FILE:-$STATE/env}" out="$STATE/audio/talk.wav" mkdir -p "$STATE/audio" @@ -22,6 +23,7 @@ for i in range(rate * seconds): frames.append(struct.pack("/dev/null || true; exit 0' TERM while true; do pw-play --target 0 -P '{ node.name = harness-talk }' "$out" & player=$! diff --git a/harness/ui.sh b/harness/ui.sh index 39b7f6f..b971cc9 100755 --- a/harness/ui.sh +++ b/harness/ui.sh @@ -1,17 +1,19 @@ #!/usr/bin/env bash set -euo pipefail -STATE="${HARNESS_STATE:-/tmp/claude-1000/yumush-harness}" +HERE="$(cd "$(dirname "$0")" && pwd)" +source "$HERE/lib.sh" source "${ENV_FILE:-$STATE/env}" to() { wlrctl pointer move -4000 -4000; wlrctl pointer move "$1" "$2"; sleep 0.1; } +backspaces() { local args=(); for _ in $(seq "$1"); do args+=(-k BackSpace); done; wtype "${args[@]}"; } case "$1" in click) to "$2" "$3"; wlrctl pointer click "${4:-left}";; move) to "$2" "$3";; type) wtype "$2";; key) wtype -k "$2";; chord) wtype -M "$2" -k "$3" -m "$2";; - clear) args=(); for _ in $(seq "${2:-30}"); do args+=(-k BackSpace); done; wtype "${args[@]}";; + clear) backspaces "${2:-30}";; field) to "$2" "$3"; wlrctl pointer click left; sleep 0.2; wlrctl pointer click left; sleep 0.2 - args=(); for _ in $(seq 30); do args+=(-k BackSpace); done; wtype "${args[@]}"; sleep 0.2; wtype "$4";; + backspaces 30; sleep 0.2; wtype "$4";; scroll) wlrctl pointer scroll "$2" "${3:-0}";; esac sleep "${UI_DELAY:-0.3}" diff --git a/harness/up.sh b/harness/up.sh index 4e9f7a1..0e32517 100755 --- a/harness/up.sh +++ b/harness/up.sh @@ -1,14 +1,12 @@ #!/usr/bin/env bash set -euo pipefail HERE="$(cd "$(dirname "$0")" && pwd)" -ROOT="$(dirname "$HERE")" -STATE="${HARNESS_STATE:-/tmp/claude-1000/yumush-harness}" +source "$HERE/lib.sh" [ -e "$STATE/pids" ] && { echo "harness already up: $STATE"; exit 1; } mkdir -p "$STATE/server" "$STATE/xdg/xdg-desktop-portal" "$STATE/shots" -cp "$ROOT/fullchain.pem" "$ROOT/privkey.pem" "$STATE/server/" -printf '[server_config]\ndatabase_path = "yumush.db"\nserver_address = "127.0.0.1:%s"\ncertificate_path = "fullchain.pem"\nkey_path = "privkey.pem"\n' "${HARNESS_PORT:-2027}" > "$STATE/server/server_config.toml" +sed "s/2026/$PORT/" "$ROOT/configs/server_config.example.toml" > "$STATE/server/server_config.toml" cp "$HERE/portals.conf" "$STATE/xdg/xdg-desktop-portal/niri-portals.conf" -(cd "$STATE/server" && YUMUSH_CONFIG_DIR="$STATE/server" exec "$ROOT/target/${PROFILE:-harness}/server" >"$STATE/server.log" 2>&1) & +(cd "$STATE/server" && YUMUSH_CONFIG_DIR="$STATE/server" exec "$BIN/server" >"$STATE/server.log" 2>&1) & echo "server $!" >> "$STATE/pids" mkdir -p "$STATE/dbus/services" for f in "$HOME"/.local/share/dbus-1/services/*.service /usr/share/dbus-1/services/*.service; do @@ -16,7 +14,7 @@ for f in "$HOME"/.local/share/dbus-1/services/*.service /usr/share/dbus-1/servic done rm -f "$STATE/dbus/services/org.freedesktop.portal.Documents.service" printf '\nsession\n\nunix:tmpdir=/tmp\nEXTERNAL\n%s\n\n\n' "$STATE/dbus/services" > "$STATE/dbus/session.conf" -systemd-run --user --scope --collect -q -u yumush-harness-session dbus-run-session --config-file="$STATE/dbus/session.conf" -- "$HERE/session.sh" "$STATE" >"$STATE/session.log" 2>&1 & +systemd-run --user --scope --collect -q -u "yumush-harness-$PORT" dbus-run-session --config-file="$STATE/dbus/session.conf" -- "$HERE/session.sh" "$STATE" >"$STATE/session.log" 2>&1 & echo "session $!" >> "$STATE/pids" for _ in $(seq 100); do [ -s "$STATE/env" ] && break; sleep 0.2; done cat "$STATE/env" diff --git a/harness/usage.sh b/harness/usage.sh index 4bc0a2f..2456839 100755 --- a/harness/usage.sh +++ b/harness/usage.sh @@ -1,15 +1,15 @@ #!/usr/bin/env bash set -euo pipefail -STATE="${HARNESS_STATE:-/tmp/claude-1000/yumush-harness}" +HERE="$(cd "$(dirname "$0")" && pwd)" +source "$HERE/lib.sh" NAME="${1:-alice}" SPAN="${SPAN:-10}" -PID=$(awk -v n="$NAME" '$1 == n {print $2}' "$STATE/pids" | tail -1) -ticks() { awk '{print $14 + $15}' "/proc/$PID/stat"; } +PID=$(pid "$NAME") engine() { cat /proc/"$PID"/fdinfo/* 2>/dev/null | awk -v e="drm-engine-$1:" '$1 == e {s += $2} END {print s + 0}'; } memory() { cat /proc/"$PID"/fdinfo/* 2>/dev/null | awk -v m="drm-memory-$1:" '$1 == m {s += $2} END {print s + 0}'; } kib() { awk -v k="$1:" '$1 == k {print $2}' "/proc/$PID/smaps_rollup"; } -t=$(ticks); g=$(engine gfx); e=$(engine enc); d=$(engine dec) +t=$(ticks "$PID"); g=$(engine gfx); e=$(engine enc); d=$(engine dec) sleep "$SPAN" -T=$(ticks); G=$(engine gfx); E=$(engine enc); D=$(engine dec) +T=$(ticks "$PID"); G=$(engine gfx); E=$(engine enc); D=$(engine dec) pct() { awk -v a="$1" -v b="$2" -v s="$SPAN" "BEGIN {printf \"%.1f\", (b - a) / s / $3}"; } echo "$NAME cpu $(pct "$t" "$T" 1)% gfx $(pct "$g" "$G" 1e7)% enc $(pct "$e" "$E" 1e7)% dec $(pct "$d" "$D" 1e7)% pss $(( $(kib Pss) / 1024 ))M rss $(( $(kib Rss) / 1024 ))M vram $(( $(memory vram) / 1024 ))M gtt $(( $(memory gtt) / 1024 ))M threads $(awk '/^Threads/ {print $2}' "/proc/$PID/status") disk $(du -sh "$STATE/clients/$NAME" | cut -f1)" diff --git a/harness/win.sh b/harness/win.sh index 11e9c02..0f8b64c 100755 --- a/harness/win.sh +++ b/harness/win.sh @@ -1,6 +1,8 @@ #!/usr/bin/env bash set -euo pipefail -SHOTS="${HARNESS_STATE:-/tmp/claude-1000/yumush-harness}/shots" +HERE="$(cd "$(dirname "$0")" && pwd)" +source "$HERE/lib.sh" +SHOTS="$STATE/shots" mkdir -p "$SHOTS" monitor() { podman exec yumush-win sh -c "printf '%s\n' \"$1\" | nc -q1 -U /run/shm/monitor.sock >/dev/null"; } ssh_win() { ssh -i ~/vm/yumush-win/id_ed25519 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ConnectTimeout=10 -o LogLevel=ERROR -p 2222 yumush@127.0.0.1 "$@"; } @@ -18,8 +20,8 @@ case "$1" in ssh) shift; ssh_win "$@";; sync) ssh_win 'Stop-Process -Name client,server -ErrorAction SilentlyContinue' || true - (cd .. && (git ls-files -co --exclude-standard; echo fullchain.pem; echo privkey.pem; echo configs/server_config.toml) | grep -v "^harness/" | tar czf /tmp/claude-1000/src.tgz -T -) - scp -q -i ~/vm/yumush-win/id_ed25519 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=ERROR -P 2222 /tmp/claude-1000/src.tgz yumush@127.0.0.1:src.tgz + (cd "$ROOT" && { git ls-files -co --exclude-standard; for f in fullchain.pem privkey.pem configs/server_config.toml; do if [ -e "$f" ]; then echo "$f"; fi; done; } | grep -v "^harness/" | tar czf "$STATE/src.tgz" -T -) + scp -q -i ~/vm/yumush-win/id_ed25519 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=ERROR -P 2222 "$STATE/src.tgz" yumush@127.0.0.1:src.tgz ssh_win 'tar xmzf src.tgz -C yumush; cd yumush; $env:Path += ";C:\Users\yumush\.cargo\bin"; cargo build --profile harness -p client -p server 2>&1 | Select-String -Pattern "^error|^warning|Finished|error\[" -Context 0,8 | Select -First 40';; esac sleep "${UI_DELAY:-0.3}"