From 543f6119de52765d7b05a5b1077f5041f84bdd95 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 24 Nov 2026 08:20:22 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20add=20voice,=20media,=20soc?= =?UTF-8?q?ial=20features,=20moderation=20and=20multiple=20accounts?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Voice: QUIC datagram voice with Opus, a jitter buffer and per-speaker mixing. Voice activity or push-to-talk (modifier keys included), input and output device selection, volume and sensitivity. Settings can loop the mic through the full call pipeline and play a speaker chime. Media: attachments with image, audio and video playback, snippets and message forwarding. FLAC files that do not state their length get it from the last frame instead of a full scan. Social: direct messages, friends, community invitations with a user lookup that shows existing members, and live user search. Messages from former members keep the original username. Moderation: member ranks with a single permission module, kick, ban with reason and unban. Bans and a new community log (renames, picture changes, invites, joins, leaves, kicks, bans, rank changes, moderator deletions) open in popups with search and sorting. Accounts: several saved accounts with session resume and auto login. A Detach request signs a connection out while keeping its session, and signing in leaves voice first. UI: settings pages for user and community, profile cards, community and user pictures that drive the accent colour of headers, dialogs and inputs, and New community in the Communities tab context menu. The README gets screenshots. New request, response and error variants are appended to keep wire indices stable. --- Cargo.toml | 3 + README.md | 14 +- crates/client/Cargo.toml | 28 + crates/client/src/accounts.rs | 132 ++ crates/client/src/avatar.rs | 88 ++ crates/client/src/embed.rs | 365 +++++ crates/client/src/gui.rs | 788 ++++++++- crates/client/src/gui/auth.rs | 213 ++- crates/client/src/gui/chat.rs | 1584 +++++++++++++++---- crates/client/src/gui/community_settings.rs | 660 ++++++++ crates/client/src/gui/composer.rs | 294 ++++ crates/client/src/gui/forward.rs | 196 +++ crates/client/src/gui/media_view.rs | 821 ++++++++++ crates/client/src/gui/message_actions.rs | 170 ++ crates/client/src/gui/profile.rs | 506 ++++++ crates/client/src/gui/settings_page.rs | 588 +++++++ crates/client/src/gui/sidebar.rs | 694 ++++++++ crates/client/src/gui/snippet.rs | 104 ++ crates/client/src/gui/social.rs | 461 ++++++ crates/client/src/gui/voice_settings.rs | 536 +++++++ crates/client/src/lib.rs | 6 + crates/client/src/main.rs | 70 +- crates/client/src/media/convert.rs | 59 + crates/client/src/media/decode.rs | 579 +++++++ crates/client/src/media/mod.rs | 307 ++++ crates/client/src/media/resample.rs | 40 + crates/client/src/network.rs | 773 ++++++++- crates/client/src/settings.rs | 183 +++ crates/client/src/voice/audio.rs | 245 +++ crates/client/src/voice/audio/coreaudio.rs | 264 ++++ crates/client/src/voice/audio/pipewire.rs | 291 ++++ crates/client/src/voice/audio/wasapi.rs | 286 ++++ crates/client/src/voice/engine.rs | 293 ++++ crates/client/src/voice/mod.rs | 225 +++ crates/common/Cargo.toml | 1 + crates/common/src/constant.rs | 16 + crates/common/src/error.rs | 47 + crates/common/src/event.rs | 42 +- crates/common/src/lib.rs | 2 + crates/common/src/model.rs | 183 ++- crates/common/src/network.rs | 154 +- crates/common/src/permission.rs | 97 ++ crates/common/src/request.rs | 168 +- crates/common/src/response.rs | 11 +- crates/common/src/validate.rs | 97 +- crates/common/src/voice.rs | 54 + crates/server/Cargo.toml | 4 +- crates/server/src/attachment.rs | 560 +++++++ crates/server/src/authentication.rs | 2 +- crates/server/src/certificate.rs | 3 +- crates/server/src/community.rs | 295 ++-- crates/server/src/database.rs | 124 +- crates/server/src/direct.rs | 51 + crates/server/src/friend.rs | 146 ++ crates/server/src/invitation.rs | 73 + crates/server/src/lib.rs | 30 +- crates/server/src/log.rs | 102 ++ crates/server/src/main.rs | 22 +- crates/server/src/message.rs | 376 ++++- crates/server/src/network.rs | 125 +- crates/server/src/request.rs | 972 +++++++++++- crates/server/src/test.rs | 12 + crates/server/src/user.rs | 165 +- crates/server/src/user_community.rs | 264 +++- crates/server/src/voice.rs | 142 ++ docs/screenshots/black.png | Bin 0 -> 87903 bytes docs/screenshots/community.png | Bin 0 -> 88484 bytes docs/screenshots/direct.png | Bin 0 -> 87543 bytes 68 files changed, 15307 insertions(+), 899 deletions(-) create mode 100644 crates/client/src/accounts.rs create mode 100644 crates/client/src/avatar.rs create mode 100644 crates/client/src/embed.rs create mode 100644 crates/client/src/gui/community_settings.rs create mode 100644 crates/client/src/gui/composer.rs create mode 100644 crates/client/src/gui/forward.rs create mode 100644 crates/client/src/gui/media_view.rs create mode 100644 crates/client/src/gui/message_actions.rs create mode 100644 crates/client/src/gui/profile.rs create mode 100644 crates/client/src/gui/settings_page.rs create mode 100644 crates/client/src/gui/sidebar.rs create mode 100644 crates/client/src/gui/snippet.rs create mode 100644 crates/client/src/gui/social.rs create mode 100644 crates/client/src/gui/voice_settings.rs create mode 100644 crates/client/src/media/convert.rs create mode 100644 crates/client/src/media/decode.rs create mode 100644 crates/client/src/media/mod.rs create mode 100644 crates/client/src/media/resample.rs create mode 100644 crates/client/src/settings.rs create mode 100644 crates/client/src/voice/audio.rs create mode 100644 crates/client/src/voice/audio/coreaudio.rs create mode 100644 crates/client/src/voice/audio/pipewire.rs create mode 100644 crates/client/src/voice/audio/wasapi.rs create mode 100644 crates/client/src/voice/engine.rs create mode 100644 crates/client/src/voice/mod.rs create mode 100644 crates/common/src/permission.rs create mode 100644 crates/common/src/voice.rs create mode 100644 crates/server/src/attachment.rs create mode 100644 crates/server/src/direct.rs create mode 100644 crates/server/src/friend.rs create mode 100644 crates/server/src/invitation.rs create mode 100644 crates/server/src/log.rs create mode 100644 crates/server/src/voice.rs create mode 100644 docs/screenshots/black.png create mode 100644 docs/screenshots/community.png create mode 100644 docs/screenshots/direct.png diff --git a/Cargo.toml b/Cargo.toml index 5960ca9..6b38424 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,6 +5,9 @@ members = ["crates/client", "crates/common", "crates/server"] [profile.dev] debug = "line-tables-only" +[profile.dev.package."*"] +opt-level = 3 + [profile.release] opt-level = 3 lto = "fat" diff --git a/README.md b/README.md index 7edba98..5094bce 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,16 @@ # Yumush(ju'muʃ) Yumush is based from a Turkish word "Yumuş" which means request, word, message. -In this project no AI auto-code is allowed. Only I code. Just passion. +Self-hosted chat with communities, direct messages and voice. Rust, QUIC, gpui. + +![Community](docs/screenshots/community.png) +![Direct messages](docs/screenshots/direct.png) +![Black theme](docs/screenshots/black.png) + +## Features +- Communities by invitation, with ranks, kick and ban with reasons, and pictures +- Direct messages and friends +- Reply, edit, forward, and forwarding multiple messages as one snippet +- Images, video, audio and file attachments +- Voice rooms +- Light, dark and black themes diff --git a/crates/client/Cargo.toml b/crates/client/Cargo.toml index 6a77607..97f3bae 100644 --- a/crates/client/Cargo.toml +++ b/crates/client/Cargo.toml @@ -9,8 +9,36 @@ tokio.workspace = true quinn = { workspace = true, features = ["rustls-ring", "platform-verifier"] } gpui-kit = "0.11.0" +ec-opus = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "a31973f3ff7fdfd036a98caa1f69422026b100ec" } +ec-core = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "a31973f3ff7fdfd036a98caa1f69422026b100ec" } +ec-probe = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "a31973f3ff7fdfd036a98caa1f69422026b100ec" } +ec-mp4 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "a31973f3ff7fdfd036a98caa1f69422026b100ec" } +ec-matroska = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "a31973f3ff7fdfd036a98caa1f69422026b100ec" } +ec-ogg = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "a31973f3ff7fdfd036a98caa1f69422026b100ec" } +ec-h264 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "a31973f3ff7fdfd036a98caa1f69422026b100ec" } +ec-vp8 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "a31973f3ff7fdfd036a98caa1f69422026b100ec" } +ec-aac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "a31973f3ff7fdfd036a98caa1f69422026b100ec" } +ec-mp3 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "a31973f3ff7fdfd036a98caa1f69422026b100ec" } +ec-vorbis = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "a31973f3ff7fdfd036a98caa1f69422026b100ec" } +ec-flac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "a31973f3ff7fdfd036a98caa1f69422026b100ec" } +ureq = "3.5.2" +bytes = "1.12.2" tracing = "0.1.44" tracing-subscriber = "0.3.23" +uuid = "1.29.3" +jiff = "1.0.2" +dirs = "7.0.0" +image = { version = "0.25.10", default-features = false, features = ["jpeg", "png", "webp", "gif"] } +rtrb = "0.4.1" + +[target.'cfg(target_os = "linux")'.dependencies] +pipewire = { version = "0.10.1", features = ["v0_3_49"] } + +[target.'cfg(target_os = "windows")'.dependencies] +wasapi = "0.27.0" + +[target.'cfg(target_os = "macos")'.dependencies] +coreaudio-rs = "0.14.2" [lints] workspace = true diff --git a/crates/client/src/accounts.rs b/crates/client/src/accounts.rs new file mode 100644 index 0000000..5eb187b --- /dev/null +++ b/crates/client/src/accounts.rs @@ -0,0 +1,132 @@ +use std::{fs, path::PathBuf}; + +use common::model::User; +use tracing::warn; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Account { + pub user_id: String, + pub username: String, + pub token: String, +} + +#[derive(Debug, Clone, Default)] +pub struct Accounts { + pub list: Vec, + pub active: Option, +} + +impl Accounts { + pub fn active(&self) -> Option<&Account> { + let active = self.active.as_deref()?; + self.list.iter().find(|account| account.user_id == active) + } + + pub fn get(&self, user_id: &str) -> Option<&Account> { + self.list.iter().find(|account| account.user_id == user_id) + } + + pub fn others(&self) -> impl Iterator { + self.list + .iter() + .filter(|account| Some(&account.user_id) != self.active.as_ref()) + } + + pub fn sign_in(&mut self, user: &User, token: String) { + self.remove(&user.id); + self.list.push(Account { + user_id: user.id.clone(), + username: user.username.clone(), + token, + }); + self.active = Some(user.id.clone()); + save(self); + } + + pub fn rename(&mut self, user: &User) { + if let Some(account) = self + .list + .iter_mut() + .find(|account| account.user_id == user.id) + { + account.username = user.username.clone(); + save(self); + } + } + + pub fn detach(&mut self) { + self.active = None; + save(self); + } + + pub fn forget(&mut self, user_id: &str) { + self.remove(user_id); + if self.active.as_deref() == Some(user_id) { + self.active = None; + } + save(self); + } + + fn remove(&mut self, user_id: &str) { + self.list.retain(|account| account.user_id != user_id); + } +} + +fn path() -> Option { + dirs::config_dir().map(|dir| dir.join("yumush").join("accounts")) +} + +pub fn load() -> Accounts { + let Some(content) = path().and_then(|path| fs::read_to_string(path).ok()) else { + return Accounts::default(); + }; + let mut accounts = Accounts::default(); + + for line in content.lines() { + match line.split('\t').collect::>().as_slice() { + ["active", user_id] => accounts.active = Some(user_id.to_string()), + [user_id, username, token] => accounts.list.push(Account { + user_id: user_id.to_string(), + username: username.to_string(), + token: token.to_string(), + }), + _ => {} + } + } + + accounts +} + +fn save(accounts: &Accounts) { + let Some(path) = path() else { + return; + }; + let mut content: String = accounts + .list + .iter() + .map(|account| { + format!( + "{}\t{}\t{}\n", + account.user_id, account.username, account.token + ) + }) + .collect(); + if let Some(active) = &accounts.active { + content.push_str(&format!("active\t{active}\n")); + } + + if let Err(error) = write_private(&path, &content) { + warn!("save accounts failed: {error}"); + } +} + +fn write_private(path: &PathBuf, content: &str) -> std::io::Result<()> { + if let Some(parent) = path.parent() { + fs::create_dir_all(parent)?; + } + let mut options = fs::OpenOptions::new(); + options.write(true).create(true).truncate(true); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); + std::io::Write::write_all(&mut options.open(path)?, content.as_bytes()) +} diff --git a/crates/client/src/avatar.rs b/crates/client/src/avatar.rs new file mode 100644 index 0000000..b76e806 --- /dev/null +++ b/crates/client/src/avatar.rs @@ -0,0 +1,88 @@ +use common::{ + constant::{AVATAR_SIZE, MAXIMUM_AVATAR_BYTES}, + error::{Error, InvalidInput}, +}; +use image::{DynamicImage, RgbImage, codecs::jpeg::JpegEncoder, imageops::FilterType}; + +const QUALITIES: [u8; 3] = [85, 60, 40]; + +pub fn prepare(bytes: &[u8]) -> Result, Error> { + let image = image::load_from_memory(bytes).map_err(decode_error)?; + let square = center_square(image) + .resize_exact(AVATAR_SIZE, AVATAR_SIZE, FilterType::Lanczos3) + .to_rgb8(); + + let mut encoded = Vec::new(); + for quality in QUALITIES { + encoded = encode(&square, quality)?; + if encoded.len() <= MAXIMUM_AVATAR_BYTES { + return Ok(encoded); + } + } + + Err(Error::Avatar(InvalidInput::TooLarge { + maximum: MAXIMUM_AVATAR_BYTES as u64, + actual: encoded.len() as u64, + })) +} + +fn center_square(image: DynamicImage) -> DynamicImage { + let side = image.width().min(image.height()); + let x = (image.width() - side) / 2; + let y = (image.height() - side) / 2; + + image.crop_imm(x, y, side, side) +} + +fn encode(image: &RgbImage, quality: u8) -> Result, Error> { + let mut bytes = Vec::new(); + JpegEncoder::new_with_quality(&mut bytes, quality) + .encode_image(image) + .map_err(decode_error)?; + + Ok(bytes) +} + +fn decode_error(error: image::ImageError) -> Error { + Error::Decode(error.to_string()) +} + +const HUE_BINS: usize = 24; + +pub fn dominant_hue(bytes: &[u8]) -> Option { + let image = image::load_from_memory(bytes) + .ok()? + .thumbnail(32, 32) + .to_rgb8(); + let mut bins = [(0.0f32, 0.0f32, 0.0f32); HUE_BINS]; + + for pixel in image.pixels() { + let [r, g, b] = pixel.0.map(|channel| channel as f32 / 255.); + let max = r.max(g).max(b); + let min = r.min(g).min(b); + let chroma = max - min; + if chroma < 0.15 { + continue; + } + let hue = if max == r { + ((g - b) / chroma).rem_euclid(6.) + } else if max == g { + (b - r) / chroma + 2. + } else { + (r - g) / chroma + 4. + } / 6.; + let angle = hue * std::f32::consts::TAU; + let bin = &mut bins[(hue * HUE_BINS as f32) as usize % HUE_BINS]; + bin.0 += chroma; + bin.1 += angle.cos() * chroma; + bin.2 += angle.sin() * chroma; + } + + let total: f32 = bins.iter().map(|bin| bin.0).sum(); + let (weight, x, y) = bins.into_iter().max_by(|a, b| a.0.total_cmp(&b.0))?; + if weight < total * 0.05 || total < (image.len() / 3) as f32 * 0.03 { + return None; + } + + Some(y.atan2(x).rem_euclid(std::f32::consts::TAU) / std::f32::consts::TAU) +} diff --git a/crates/client/src/embed.rs b/crates/client/src/embed.rs new file mode 100644 index 0000000..a941682 --- /dev/null +++ b/crates/client/src/embed.rs @@ -0,0 +1,365 @@ +use std::io::Read; +use std::time::Duration; + +use ureq::http::Uri; +use ureq::{Agent, Body, ResponseExt}; + +const MAX_LINKS: usize = 3; +const MAX_IMAGE: u64 = 5 * 1024 * 1024; +const MAX_HTML: u64 = 512 * 1024; +const MAX_TITLE: usize = 256; +const MAX_DESCRIPTION: usize = 512; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum EmbedKind { + Page, + Image, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Embed { + pub url: String, + pub kind: EmbedKind, + pub site: Option, + pub title: Option, + pub description: Option, + pub image: Option>, +} + +#[derive(Debug, PartialEq, Eq)] +struct Meta { + title: Option, + description: Option, + image: Option, + site: Option, +} + +pub fn urls(text: &str) -> Vec { + let mut out: Vec = Vec::new(); + let mut rest = text; + while out.len() < MAX_LINKS { + let Some(start) = find_scheme(rest) else { + break; + }; + let tail = &rest[start..]; + let end = tail + .find(|c: char| c.is_whitespace() || matches!(c, '<' | '>' | '"')) + .unwrap_or(tail.len()); + rest = &tail[end..]; + let link = trim_link(&tail[..end]); + let has_host = link.find("://").is_some_and(|i| link.len() > i + 3); + if has_host && !out.iter().any(|u| u == link) { + out.push(link.to_owned()); + } + } + out +} + +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), + } +} + +fn trim_link(s: &str) -> &str { + let mut s = s; + loop { + let t = s.trim_end_matches(['.', ',', ';', ':', '!', '?']); + let t = if t.ends_with(')') && t.matches(')').count() > t.matches('(').count() { + &t[..t.len() - 1] + } else { + t + }; + if t.len() == s.len() { + return s; + } + s = t; + } +} + +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) + .user_agent("yumush") + .http_status_as_error(true) + .build(), + ); + let mut resp = agent.get(url).call().ok()?; + let final_url = resp.get_uri().to_string(); + let mime = mime_of(&resp)?; + + if is_image(&mime) { + let image = read_image(&mut resp)?; + return Some(Embed { + url: url.to_owned(), + kind: EmbedKind::Image, + site: None, + title: last_segment(&final_url), + description: None, + image: Some(image), + }); + } + if mime != "text/html" { + return None; + } + + let mut bytes = Vec::new(); + resp.body_mut() + .as_reader() + .take(MAX_HTML) + .read_to_end(&mut bytes) + .ok()?; + let meta = parse_meta(&String::from_utf8_lossy(&bytes)); + + let image = meta + .image + .and_then(|src| resolve(&final_url, &src)) + .and_then(|img| fetch_image(&agent, &img)); + if meta.title.is_none() && image.is_none() { + return None; + } + + let host = final_url + .parse::() + .ok() + .and_then(|u| u.host().map(str::to_owned)); + Some(Embed { + url: url.to_owned(), + kind: EmbedKind::Page, + site: meta.site.or(host), + title: meta.title, + description: meta.description, + image, + }) +} + +fn is_web(url: &str) -> bool { + url.parse::() + .is_ok_and(|u| matches!(u.scheme_str(), Some("http" | "https"))) +} + +fn mime_of(resp: &ureq::http::Response) -> Option { + let mime = resp.body().mime_type()?; + Some(mime.trim().to_ascii_lowercase()) +} + +fn is_image(mime: &str) -> bool { + matches!( + mime, + "image/png" | "image/jpeg" | "image/gif" | "image/webp" + ) +} + +fn read_image(resp: &mut ureq::http::Response) -> Option> { + resp.body_mut() + .with_config() + .limit(MAX_IMAGE) + .read_to_vec() + .ok() +} + +fn fetch_image(agent: &Agent, url: &str) -> Option> { + if !is_web(url) { + return None; + } + let mut resp = agent.get(url).call().ok()?; + if !is_image(&mime_of(&resp)?) { + return None; + } + read_image(&mut resp) +} + +fn last_segment(url: &str) -> Option { + let path = url.parse::().ok()?.path().to_owned(); + path.rsplit('/').find(|s| !s.is_empty()).map(str::to_owned) +} + +fn resolve(base: &str, src: &str) -> Option { + let src = src.trim(); + if src.starts_with("http://") || src.starts_with("https://") { + return Some(src.to_owned()); + } + let base = base.parse::().ok()?; + let scheme = base.scheme_str()?; + let authority = base.authority()?.as_str(); + if let Some(rest) = src.strip_prefix("//") { + return Some(format!("{scheme}://{rest}")); + } + if src.starts_with('/') { + return Some(format!("{scheme}://{authority}{src}")); + } + let path = base.path(); + let dir = match path.rfind('/') { + Some(i) => &path[..=i], + None => "/", + }; + Some(format!("{scheme}://{authority}{dir}{src}")) +} + +fn parse_meta(html: &str) -> Meta { + let lower = html.to_ascii_lowercase(); + let mut tags: Vec<(String, String)> = Vec::new(); + for (pos, _) in lower.match_indices(" key = Some(value), + "content" => content = Some(value), + _ => {} + } + } + if let (Some(k), Some(c)) = (key, content) { + tags.push((k.to_ascii_lowercase(), c)); + } + } + + let found = |names: &[&str]| -> Option { + names.iter().find_map(|n| { + tags.iter() + .find(|(k, _)| k.as_str() == *n) + .map(|(_, v)| v.clone()) + }) + }; + + let title = found(&["og:title", "twitter:title"]) + .or_else(|| tag_text(html, &lower, " Option { + let start = lower.find(open)?; + let body = start + lower[start..].find('>')? + 1; + let end = body + lower[body..].find(close)?; + Some(html[body..end].to_owned()) +} + +fn attributes(tag: &str) -> Vec<(String, String)> { + let mut out = Vec::new(); + let mut rest = tag; + loop { + rest = rest.trim_start_matches(|c: char| c.is_whitespace() || c == '/'); + if rest.is_empty() || rest.starts_with('>') { + break; + } + let end = rest + .find(|c: char| c.is_whitespace() || c == '=' || c == '>') + .unwrap_or(rest.len()); + let name = rest[..end].to_ascii_lowercase(); + rest = rest[end..].trim_start(); + let mut value = String::new(); + if let Some(after) = rest.strip_prefix('=') { + let after = after.trim_start(); + match after.chars().next() { + Some(q @ ('"' | '\'')) => { + let body = &after[1..]; + let close = body.find(q).unwrap_or(body.len()); + value = body[..close].to_owned(); + rest = &body[(close + 1).min(body.len())..]; + } + _ => { + let close = after + .find(|c: char| c.is_whitespace() || c == '>') + .unwrap_or(after.len()); + value = after[..close].to_owned(); + rest = &after[close..]; + } + } + } + out.push((name, value)); + } + out +} + +fn clean(s: &str, max: usize) -> String { + decode(s) + .split_whitespace() + .collect::>() + .join(" ") + .chars() + .take(max) + .collect() +} + +fn decode(s: &str) -> String { + let mut out = String::new(); + let mut rest = s; + while let Some(i) = rest.find('&') { + out.push_str(&rest[..i]); + rest = &rest[i..]; + if let Some(semi) = rest.find(';').filter(|&j| j <= 10) + && let Some(c) = entity(&rest[1..semi]) + { + out.push(c); + rest = &rest[semi + 1..]; + continue; + } + out.push('&'); + rest = &rest[1..]; + } + out.push_str(rest); + out +} + +fn entity(e: &str) -> Option { + match e { + "amp" => Some('&'), + "lt" => Some('<'), + "gt" => Some('>'), + "quot" => Some('"'), + "#39" | "#x27" => Some('\''), + _ => match e.strip_prefix("#x") { + Some(hex) => char::from_u32(u32::from_str_radix(hex, 16).ok()?), + None => char::from_u32(e.strip_prefix('#')?.parse().ok()?), + }, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_meta_reads_mixed_attributes_and_entities() { + let html = r#"Ignored"#; + let meta = parse_meta(html); + assert_eq!(meta.title.as_deref(), Some("Og \"Title\"")); + assert_eq!(meta.description.as_deref(), Some("It's 'here'")); + assert_eq!(meta.image.as_deref(), Some("https://img.test/a.png")); + assert_eq!(meta.site.as_deref(), Some("Site")); + assert_eq!( + parse_meta(" A\n B & C ") + .title + .as_deref(), + Some("A B & C") + ); + } + + #[test] + fn urls_trims_punctuation_and_dedups() { + let text = "see (https://a.com/x), https://b.com/y. and ! https://a.com/x http://d.com/w?q=1 https://e.com"; + assert_eq!( + urls(text), + ["https://a.com/x", "https://b.com/y", "https://c.com/z"] + ); + assert_eq!(urls("https://w.org/a_(b)"), ["https://w.org/a_(b)"]); + } +} diff --git a/crates/client/src/gui.rs b/crates/client/src/gui.rs index aa88458..b821650 100644 --- a/crates/client/src/gui.rs +++ b/crates/client/src/gui.rs @@ -1,23 +1,411 @@ -use std::fmt::Display; +use std::{ + collections::HashMap, + fmt::Display, + hash::{DefaultHasher, Hash, Hasher}, + sync::Arc, +}; -use common::model::User; +use common::{ + error::Error, + event::Event, + model::{Community, CommunityKind, Rank, User}, +}; use gpui_kit::{ - AppContext, AsyncWindowContext, Context, Entity, IntoElement, ParentElement, Render, Styled, - WeakEntity, Window, + AnyElement, App, AppContext, AsyncWindowContext, Context, Div, ElementId, Entity, FontWeight, + Hsla, Image, ImageFormat, InteractiveElement, IntoElement, KeyBinding, KeyDownEvent, + KeyUpEvent, ModifiersChangedEvent, ParentElement, Pixels, Render, RenderOnce, Stateful, + StatefulInteractiveElement, Styled, WeakEntity, Window, actions, + base::Selectable, component::{ - ActiveTheme, WindowExt, button::Button, input::InputState, notification::Notification, + ActiveTheme, Theme, WindowExt, + input::{Input, InputEvent, InputState}, + notification::Notification, }, - div, rgb, + div, hsla, img, px, rgb, }; +use jiff::{Timestamp, tz::TimeZone}; use tokio::sync::mpsc; +use uuid::Uuid; -use crate::network::{NetworkEvent, NetworkHandle}; +use crate::{ + accounts::{self, Accounts}, + network::{NetworkEvent, NetworkHandle}, + settings::{Look, Settings, ThemeChoice}, +}; mod auth; mod chat; +mod community_settings; +mod composer; +mod forward; +mod media_view; +mod message_actions; +mod profile; +mod settings_page; +mod sidebar; +mod snippet; +mod social; +mod voice_settings; use auth::Auth; -use chat::Chat; +use chat::{Chat, View}; +use voice_settings::VoiceControls; + +actions!(yumush, [FocusFind, CloseSettings]); + +const TINTS: [u32; 10] = [ + 0x10b981, 0xa855f7, 0xf59e0b, 0xf97316, 0xec4899, 0x0ea5e9, 0x22c55e, 0xef4444, 0x06b6d4, + 0xd946ef, +]; + +#[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 dark: bool, +} + +impl Palette { + pub fn tinted(self, id: &str) -> Hsla { + let color = tint(id); + if self.dark { + color + } else { + hsla(color.h, color.s, color.l * 0.62, 1.) + } + } + + pub fn for_community(self, community: Option<&Community>, hues: &HashMap) -> Self { + let Some(community) = community else { + return self; + }; + let (id, avatar_id) = match &community.kind { + CommunityKind::Group => (&community.id, &community.avatar_id), + CommunityKind::Direct { peer } => (&peer.id, &peer.avatar_id), + }; + let accent = match avatar_id.as_ref().and_then(|avatar_id| hues.get(avatar_id)) { + Some(&hue) if self.dark => hsla(hue, 0.75, 0.55, 1.), + Some(&hue) => hsla(hue, 0.75, 0.4, 1.), + None => self.tinted(id), + }; + Palette { accent, ..self } + } +} + +pub fn palette(cx: &App) -> Palette { + let black = cx + .try_global::() + .is_some_and(|look| look.0 == ThemeChoice::Black); + let dark = cx.theme().is_dark(); + let (window, panel, field, border, text, body, muted, hover) = match (dark, black) { + (true, true) => ( + 0x000000, 0x000000, 0x0e0e11, 0x1d1d22, 0xececf0, 0xd4d4da, 0x8f8f99, 0x16161a, + ), + (true, false) => ( + 0x121419, 0x191c23, 0x20232b, 0x2a2e38, 0xececf0, 0xd4d6de, 0x9094a0, 0x232733, + ), + _ => ( + 0xf3f4f8, 0xffffff, 0xffffff, 0xe1e3ea, 0x1c1d24, 0x33353f, 0x6b6e7a, 0xe8eaf1, + ), + }; + let (accent, alert) = if dark { + (0xec4899, 0xef4444) + } else { + (0xdb2777, 0xdc2626) + }; + + Palette { + window: rgb(window).into(), + panel: rgb(panel).into(), + field: rgb(field).into(), + border: rgb(border).into(), + text: rgb(text).into(), + body: rgb(body).into(), + muted: rgb(muted).into(), + hover: rgb(hover).into(), + accent: rgb(accent).into(), + on_accent: rgb(0xffffff).into(), + ok: rgb(0x3fb950).into(), + danger: rgb(0xd1483f).into(), + alert: rgb(alert).into(), + dark, + } +} + +pub fn sync_accent(accent: Hsla, cx: &mut App) { + let theme = Theme::global_mut(cx); + if theme.colors.ring == accent { + return; + } + let colors = &mut theme.colors; + colors.primary = accent; + colors.primary_hover = accent.opacity(0.85); + colors.primary_active = accent; + colors.ring = accent; + colors.caret = accent; + theme.tokens = (&theme.colors).into(); +} + +pub fn sync_theme(cx: &mut App) { + let palette = palette(cx); + let theme = Theme::global_mut(cx); + 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.opacity(0.85); + colors.primary_active = palette.accent; + colors.primary_foreground = palette.on_accent; + colors.ring = palette.accent; + colors.caret = palette.accent; + colors.danger = palette.danger; + theme.tokens = (&theme.colors).into(); + theme.radius = px(6.); + theme.radius_lg = px(10.); + theme.font_size = px(14.); + theme.focus_ring = false; +} + +const FIND_KEY: &str = "ctrl-k"; +pub const FIND_HINT: &str = "Ctrl K"; + +pub fn tint(id: &str) -> Hsla { + let mut hasher = DefaultHasher::new(); + id.hash(&mut hasher); + rgb(TINTS[hasher.finish() as usize % TINTS.len()]).into() +} + +pub fn badge(palette: Palette, id: &str, name: &str, size: Pixels, font: Pixels) -> Div { + let initial = name + .chars() + .next() + .unwrap_or('?') + .to_uppercase() + .to_string(); + + div() + .size(size) + .flex_shrink_0() + .flex() + .items_center() + .justify_center() + .bg(tint(id)) + .text_color(palette.on_accent) + .text_size(font) + .font_weight(FontWeight::SEMIBOLD) + .child(initial) +} + +pub fn avatar( + palette: Palette, + user: &User, + size: Pixels, + font: Pixels, + 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(); + }; + + div() + .size(size) + .flex_shrink_0() + .rounded_full() + .overflow_hidden() + .child(img(image.clone()).size_full().rounded_full()) +} + +pub fn community_name(community: &Community) -> &str { + match &community.kind { + CommunityKind::Group => &community.name, + CommunityKind::Direct { peer } => &peer.username, + } +} + +pub fn community_icon( + palette: Palette, + community: &Community, + size: Pixels, + font: Pixels, + avatars: &HashMap>, +) -> Div { + match &community.kind { + CommunityKind::Group => match community.avatar_id.as_ref().and_then(|id| avatars.get(id)) { + Some(image) => div() + .size(size) + .flex_shrink_0() + .rounded(px(4.)) + .overflow_hidden() + .child(img(image.clone()).size_full()), + None => badge(palette, &community.id, &community.name, size, font).rounded(px(4.)), + }, + CommunityKind::Direct { peer } => avatar(palette, peer, size, font, avatars), + } +} + +pub fn id_time(id: &str, format: &str) -> String { + let Some((seconds, nanos)) = Uuid::parse_str(id) + .ok() + .and_then(|uuid| uuid.get_timestamp()) + .map(|timestamp| timestamp.to_unix()) + else { + return String::new(); + }; + let Ok(timestamp) = Timestamp::new(seconds as i64, nanos as i32) else { + return String::new(); + }; + + timestamp + .to_zoned_datetime(TimeZone::system()) + .strftime(format) + .to_string() +} + +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
{ + element + .id(id) + .cursor_pointer() + .hover(move |style| style.bg(hover)) +} + +pub fn clickable( + id: impl Into, + palette: Palette, + on_click: impl Fn(&mut Window, &mut App) + 'static, +) -> Stateful
{ + hoverable(id, div(), palette).on_click(move |_, window, cx| on_click(window, cx)) +} + +pub fn entity_action( + entity: &Entity, + run: impl Fn(&mut T, &mut Window, &mut Context) + 'static, +) -> impl Fn(&mut Window, &mut App) + 'static { + let entity = entity.clone(); + + move |window, cx| entity.update(cx, |state, cx| run(state, window, cx)) +} + +pub struct Tip(&'static str); + +impl Render for Tip { + fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { + let palette = palette(cx); + div() + .px(px(6.)) + .py(px(3.)) + .rounded(px(4.)) + .border_1() + .border_color(palette.border) + .bg(palette.panel) + .text_color(palette.text) + .text_size(px(12.)) + .child(self.0) + } +} + +pub trait Tooltip { + fn tip(self, text: &'static str) -> Self; +} + +impl Tooltip for Stateful
{ + fn tip(self, text: &'static str) -> Self { + self.tooltip(move |_, cx| cx.new(|_| Tip(text)).into()) + } +} + +pub fn primary_button( + id: impl Into, + palette: Palette, + on_click: impl Fn(&mut Window, &mut App) + 'static, +) -> Stateful
{ + div() + .id(id) + .cursor_pointer() + .on_click(move |_, window, cx| on_click(window, cx)) + .bg(palette.accent) + .text_color(palette.on_accent) + .hover(|style| style.opacity(0.85)) +} + +#[derive(IntoElement)] +pub struct Trigger(AnyElement); + +impl Trigger { + pub fn new(content: impl IntoElement) -> Self { + Self(content.into_any_element()) + } +} + +impl Selectable for Trigger { + fn selected(self, _: bool) -> Self { + self + } + + fn is_selected(&self) -> bool { + false + } +} + +impl RenderOnce for Trigger { + fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement { + self.0 + } +} + +pub fn rank_tag(rank: Option, palette: Palette) -> Option
{ + let (label, color) = match rank? { + Rank::Owner => ("Owner", palette.muted), + Rank::Admin => ("Admin", palette.muted), + Rank::Moderator => ("Mod", palette.muted), + Rank::Member => return None, + Rank::Staff => ("Staff", palette.text), + }; + + Some( + div() + .px(px(5.)) + .py(px(1.)) + .rounded(px(4.)) + .bg(palette.hover) + .text_size(px(11.)) + .text_color(color) + .child(label), + ) +} + +pub fn bind_keys(cx: &mut App) { + cx.bind_keys([ + KeyBinding::new(FIND_KEY, FocusFind, None), + KeyBinding::new("escape", CloseSettings, None), + ]); +} #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Route { @@ -33,15 +421,22 @@ pub struct Yumush { chat: Chat, network: NetworkHandle, connected: bool, + settings: Settings, + accounts: Accounts, + voice: VoiceControls, + focus: gpui_kit::FocusHandle, } impl Yumush { pub fn new( network: NetworkHandle, mut network_event_receiver: mpsc::Receiver, + settings: Settings, window: &mut Window, cx: &mut Context, ) -> Self { + network.set_voice_settings(settings.voice.clone()); + cx.spawn_in(window, async move |this, cx| { while let Some(event) = network_event_receiver.recv().await { let updated = this.update_in(cx, |yumush, window, cx| { @@ -55,20 +450,113 @@ impl Yumush { }) .detach(); + cx.observe_window_appearance(window, |yumush, window, cx| { + if yumush.settings.theme == ThemeChoice::System { + Theme::sync_system_appearance(Some(window), cx); + sync_theme(cx); + } + cx.notify(); + }) + .detach(); + + cx.observe_window_activation(window, |yumush, window, _| { + if !window.is_window_active() { + yumush.network.set_talking(false); + } + }) + .detach(); + + let voice = VoiceControls::new(&settings.voice, window, cx); + Self { user: None, + focus: cx.focus_handle(), current_route: Route::Login, auth: Auth::new(window, cx), chat: Chat::new(window, cx), network, connected: false, + settings, + accounts: accounts::load(), + voice, } } - fn logout(&mut self, window: &mut Window, cx: &mut Context) { - if self.user.take().is_none() { + pub(super) fn enter_session( + &mut self, + user: User, + token: String, + window: &mut Window, + cx: &mut Context, + ) { + self.accounts.sign_in(&user, token); + self.request_user_avatar(&user, cx); + self.user = Some(user); + self.change_page(Route::Chat, window, cx); + self.load_communities(window, cx); + self.load_social(window, cx); + } + + pub(super) fn switch_account( + &mut self, + user_id: String, + window: &mut Window, + cx: &mut Context, + ) { + let Some(account) = self.accounts.get(&user_id).cloned() else { + return; + }; + if !self.connected { + window.push_notification(Notification::error("Not connected"), cx); return; } + if self.user.is_some() { + self.end_session(window, cx); + } + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + let result = network.resume(&account.token).await; + let _ = this.update_in(cx, |yumush, window, cx| match result { + Ok((user, token)) => yumush.enter_session(user, token, window, cx), + Err(error @ (Error::NotFound | Error::Unauthenticated)) => { + yumush.accounts.forget(&account.user_id); + window.push_notification(Notification::error(error.to_string()), cx); + cx.notify(); + } + Err(error) => { + window.push_notification(Notification::error(error.to_string()), cx); + } + }); + }) + .detach(); + } + + pub(super) fn add_account(&mut self, window: &mut Window, cx: &mut Context) { + self.accounts.detach(); + self.end_session(window, cx); + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + if let Err(error) = network.detach().await { + notify_error(&this, cx, error); + } + }) + .detach(); + } + + pub(super) fn forget_account(&mut self, user_id: &str, cx: &mut Context) { + self.accounts.forget(user_id); + cx.notify(); + } + + fn logout(&mut self, window: &mut Window, cx: &mut Context) { + let Some(user) = self.user.take() else { + return; + }; + self.accounts.forget(&user.id); + self.end_voice(cx); + self.leave_settings(); let network = self.network.clone(); self.chat.reset(); @@ -92,6 +580,125 @@ impl Yumush { } } + fn show_view(&mut self, view: View, window: &mut Window, cx: &mut Context) { + if self.chat.view == View::Settings && view != View::Settings { + self.leave_settings(); + } + if view == View::Settings { + self.enter_settings(window, cx); + let (username, status) = self + .user + .as_ref() + .map(|user| (user.username.clone(), user.status.clone())) + .unwrap_or_default(); + self.chat + .username_input + .update(cx, |input, cx| input.set_value(username, window, cx)); + self.chat + .status_input + .update(cx, |input, cx| input.set_value(status, window, cx)); + } + if view == View::CommunitySettings { + let name = self + .chat + .selected_community() + .map(|community| community.name.clone()) + .unwrap_or_default(); + self.chat + .community_name_input + .update(cx, |input, cx| input.set_value(name, window, cx)); + self.load_bans(window, cx); + } + + self.chat.view = view; + self.chat.delete_step = chat::DeleteStep::Idle; + if view == View::Chat { + self.chat.focus(window, cx); + } + cx.notify(); + } + + pub fn themed(&self, cx: &App) -> Palette { + let community = match self.chat.view { + View::Settings => None, + _ => self.chat.selected_community(), + }; + palette(cx).for_community(community, &self.chat.hues) + } + + pub fn actor_rank(&self) -> Option { + self.user.as_ref().and_then(|me| self.chat.my_rank(me)) + } + + pub fn request_avatar(&mut self, avatar_id: &str, cx: &mut Context) { + if self.chat.avatars.contains_key(avatar_id) + || self.chat.avatar_requests.contains(avatar_id) + { + return; + } + self.chat.avatar_requests.insert(avatar_id.to_string()); + + let network = self.network.clone(); + let avatar_id = avatar_id.to_string(); + + cx.spawn(async move |this, cx| { + let result = network.read_avatar(&avatar_id).await; + let _ = this.update(cx, |yumush, cx| { + yumush.chat.avatar_requests.remove(&avatar_id); + if let Ok(bytes) = result { + if let Some(hue) = crate::avatar::dominant_hue(&bytes) { + yumush.chat.hues.insert(avatar_id.clone(), hue); + } + yumush.chat.avatars.insert( + avatar_id, + Arc::new(Image::from_bytes(ImageFormat::Jpeg, bytes)), + ); + } + cx.notify(); + }); + }) + .detach(); + } + + pub fn request_user_avatar(&mut self, user: &User, cx: &mut Context) { + if let Some(avatar_id) = &user.avatar_id { + self.request_avatar(avatar_id, cx); + } + } + + fn apply_pushed(&mut self, event: Event, cx: &mut Context) { + match &event { + Event::MemberJoined { member, .. } => self.request_user_avatar(&member.user, cx), + Event::UserUpdated(user) => { + if self.is_me(&user.id) { + self.user = Some(user.clone()); + self.accounts.rename(user); + } + self.request_user_avatar(user, cx); + } + Event::VoiceLeft { + community_id, + user_id, + } if self.is_me(user_id) => self.chat.clear_voice_in(community_id), + _ => {} + } + self.chat.apply_event(event); + self.request_social_avatars(cx); + self.request_media(cx); + } + + fn is_me(&self, user_id: &str) -> bool { + self.user.as_ref().is_some_and(|me| me.id == user_id) + } + + fn end_session(&mut self, window: &mut Window, cx: &mut Context) { + self.end_voice(cx); + self.leave_settings(); + self.user = None; + self.chat.reset(); + self.change_page(Route::Login, window, cx); + } + fn handle_network_event( &mut self, event: NetworkEvent, @@ -103,21 +710,107 @@ impl Yumush { self.connected = true; if self.user.is_some() { self.reload(window, cx); + } else if let Some(active) = self.accounts.active.clone() { + self.switch_account(active, window, cx); } } NetworkEvent::Disconnected(_) => self.connected = false, NetworkEvent::SessionLost => { - self.user = None; - self.chat.reset(); - self.change_page(Route::Login, window, cx); + if let Some(user) = &self.user { + self.accounts.forget(&user.id.clone()); + } + self.end_session(window, cx); } - NetworkEvent::Pushed(event) => self.chat.apply_event(event), + NetworkEvent::Pushed(event) => match *event { + Event::MemberLeft { + community_id, + user_id, + } if self.is_me(&user_id) => { + self.leave_voice_in(&community_id, cx); + self.chat.remove_community(&community_id); + } + Event::Removed { + community_id, + community_name, + banned, + reason, + } => { + self.leave_voice_in(&community_id, cx); + self.chat.remove_community(&community_id); + let action = if banned { "Banned from" } else { "Kicked from" }; + let text = match reason { + Some(reason) => format!("{action} {community_name}: {reason}"), + None => format!("{action} {community_name}"), + }; + window.push_notification(Notification::warning(text), cx); + } + Event::CommunityDeleted { community_id } => { + self.leave_voice_in(&community_id, cx); + self.apply_pushed(Event::CommunityDeleted { community_id }, cx); + } + event => self.apply_pushed(event, cx), + }, } cx.notify(); } } +pub fn input_dialog( + title: &'static str, + action: &'static str, + placeholder: &'static str, + window: &mut Window, + cx: &mut Context, + on_submit: impl Fn(&mut Yumush, String, &mut Window, &mut Context) + 'static, +) { + let input = new_input(placeholder, window, cx); + let on_submit = std::rc::Rc::new(on_submit); + let on_enter = on_submit.clone(); + + cx.subscribe_in(&input, window, move |this, input, event, window, cx| { + if matches!(event, InputEvent::PressEnter { .. }) { + let text = input.read(cx).text().to_string(); + on_enter(this, text, window, cx); + } + }) + .detach(); + + let entity = cx.entity(); + let dialog_input = input.clone(); + window.open_dialog(cx, move |dialog, _, cx| { + let palette = entity.read(cx).themed(cx); + let entity = entity.clone(); + let on_submit = on_submit.clone(); + let button_input = dialog_input.clone(); + + dialog.title(title).child( + div() + .flex() + .flex_col() + .gap(px(12.)) + .child(Input::new(&dialog_input)) + .child( + div().flex().justify_end().child( + primary_button("input_dialog_submit", palette, move |window, cx| { + let text = button_input.read(cx).text().to_string(); + entity.update(cx, |this, cx| on_submit(this, text, window, cx)); + }) + .h(px(30.)) + .px(px(14.)) + .flex() + .items_center() + .rounded(px(8.)) + .child(action), + ), + ), + ) + }); + window.defer(cx, move |window, cx| { + input.update(cx, |input, cx| input.focus(window, cx)); + }); +} + pub fn notify_error( this: &WeakEntity, cx: &mut AsyncWindowContext, @@ -128,7 +821,7 @@ pub fn notify_error( }); } -fn new_input( +pub(super) fn new_input( placeholder: &'static str, window: &mut Window, cx: &mut Context, @@ -143,54 +836,39 @@ fn new_input( impl Render for Yumush { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + let palette = palette(cx); + sync_accent(self.themed(cx).accent, cx); let route = self.current_route; let page = match route { Route::Login | Route::Register => self.auth_page(route, cx).into_any_element(), Route::Chat => self.chat_page(cx).into_any_element(), }; - let status_color = if self.connected { - rgb(0x22c55e) - } else { - rgb(0xef4444) - }; div() .size_full() - .relative() - .child( - div() - .flex() - .flex_col() - .justify_center() - .items_center() - .size_full() - .bg(rgb(0x1e1e1e)) - .text_color(cx.theme().foreground) - .child(page), - ) - .child( - div() - .absolute() - .top_2() - .right_2() - .flex() - .flex_row() - .items_center() - .gap_2() - .children( - self.user.as_ref().map(|user| { - div().text_color(status_color).child(user.username.clone()) - }), - ) - .children(self.user.is_some().then(|| { - let entity = cx.entity(); - - Button::new("logout_button").label("Logout").on_click( - move |_, window, cx| { - entity.update(cx, |yumush, cx| yumush.logout(window, cx)); - }, - ) - })), + .bg(palette.window) + .text_color(palette.text) + .text_size(px(13.)) + .track_focus(&self.focus) + .on_action( + cx.listener(|this, _: &FocusFind, window, cx| this.chat.focus_find(window, cx)), ) + .on_action(cx.listener(|this, _: &CloseSettings, window, cx| { + if this.chat.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_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); + })) + .child(page) } } diff --git a/crates/client/src/gui/auth.rs b/crates/client/src/gui/auth.rs index 110111e..874b86c 100644 --- a/crates/client/src/gui/auth.rs +++ b/crates/client/src/gui/auth.rs @@ -1,13 +1,17 @@ use gpui_kit::{ - Context, Entity, IntoElement, ParentElement, Styled, Window, - component::{ - button::Button, - input::{Input, InputEvent, InputState}, - }, + Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window, + component::input::{Input, InputEvent, InputState}, div, + prelude::FluentBuilder as _, + px, }; -use crate::gui::{Route, Yumush, new_input, notify_error}; +use gpui_kit::{AnyElement, StatefulInteractiveElement, assets::IconName, component::Icon}; + +use crate::gui::{ + Palette, Route, Yumush, badge, clickable, hoverable, new_input, notify_error, palette, + primary_button, +}; pub struct Auth { username_input: Entity, @@ -55,15 +59,13 @@ fn submit(this: &mut Yumush, window: &mut Window, cx: &mut Context) { }; match result { - Ok(user) => { + Ok((user, token)) => { let _ = this.update_in(cx, |yumush, window, cx| { yumush .auth .password_input .update(cx, |input, cx| input.set_value("", window, cx)); - yumush.user = Some(user); - yumush.change_page(Route::Chat, window, cx); - yumush.load_communities(window, cx); + yumush.enter_session(user, token, window, cx); }); } Err(error) => notify_error(&this, cx, error), @@ -72,33 +74,184 @@ fn submit(this: &mut Yumush, window: &mut Window, cx: &mut Context) { .detach(); } +pub(super) fn field(palette: Palette, input: &Entity) -> Div { + div() + .h(px(32.)) + .flex() + .items_center() + .rounded(px(8.)) + .border_1() + .border_color(palette.border) + .bg(palette.field) + .child( + Input::new(input) + .appearance(false) + .text_color(palette.text) + .flex_1() + .min_w_0(), + ) +} + impl Yumush { pub(super) fn auth_page(&self, route: Route, cx: &mut Context) -> impl IntoElement { - let (action_label, switch_route, switch_label) = match route { - Route::Register => ("Register", Route::Login, "Go to Login Page"), - _ => ("Login", Route::Register, "Go to Register Page"), + let palette = palette(cx); + let action_label = match route { + Route::Register => "Register", + _ => "Log in", }; let entity = cx.entity(); - let action_button = - Button::new("auth_button") - .label(action_label) - .on_click(move |_, window, cx| { - entity.update(cx, |this, cx| submit(this, window, cx)); - }); + let submit_entity = entity.clone(); + let action_button = primary_button("auth_button", palette, move |window, cx| { + submit_entity.update(cx, |this, cx| submit(this, window, cx)); + }) + .h(px(32.)) + .flex() + .items_center() + .justify_center() + .rounded(px(8.)) + .font_weight(FontWeight::MEDIUM) + .child(action_label); - let entity = cx.entity(); - let switch_button = Button::new("auth_switch_button") - .label(switch_label) - .on_click(move |_, window, cx| { - entity.update(cx, |this, cx| this.change_page(switch_route, window, cx)); - }); + let tabs = div() + .flex() + .p(px(3.)) + .gap(px(3.)) + .rounded(px(8.)) + .bg(palette.window) + .child(tab(palette, &entity, Route::Login, "Log in", route)) + .child(tab(palette, &entity, Route::Register, "Register", route)); div() - .w_1_5() - .child(Input::new(&self.auth.username_input)) - .child(Input::new(&self.auth.password_input)) - .child(action_button) - .child(switch_button) + .flex() + .flex_col() + .items_center() + .justify_center() + .size_full() + .child( + div() + .w(px(320.)) + .p(px(24.)) + .flex() + .flex_col() + .gap(px(12.)) + .rounded(px(10.)) + .border_1() + .border_color(palette.border) + .bg(palette.panel) + .child( + div() + .text_size(px(18.)) + .font_weight(FontWeight::SEMIBOLD) + .child("yumush"), + ) + .children(self.saved_accounts(&entity, palette)) + .child(tabs) + .child(field(palette, &self.auth.username_input)) + .child(field(palette, &self.auth.password_input)) + .child(action_button), + ) } } + +impl Yumush { + fn saved_accounts(&self, entity: &Entity, palette: Palette) -> Option
{ + if self.accounts.list.is_empty() { + return None; + } + let rows: Vec = self + .accounts + .list + .iter() + .map(|account| { + let switch_entity = entity.clone(); + let forget_entity = entity.clone(); + let switch_id = account.user_id.clone(); + let forget_id = account.user_id.clone(); + + hoverable( + format!("saved_{}", account.user_id), + div() + .h(px(36.)) + .px(px(8.)) + .flex() + .items_center() + .gap(px(8.)) + .rounded(px(6.)) + .child( + badge( + palette, + &account.user_id, + &account.username, + px(22.), + px(11.), + ) + .rounded_full(), + ) + .child(div().flex_1().truncate().child(account.username.clone())) + .child( + clickable( + format!("forget_{}", account.user_id), + palette, + move |_, cx| { + cx.stop_propagation(); + forget_entity.update(cx, |yumush, cx| { + yumush.forget_account(&forget_id, cx) + }); + }, + ) + .size(px(22.)) + .flex() + .items_center() + .justify_center() + .rounded(px(5.)) + .text_color(palette.muted) + .child(Icon::new(IconName::X).w(px(12.)).h(px(12.))), + ), + palette, + ) + .on_click(move |_, window, cx| { + switch_entity.update(cx, |yumush, cx| { + yumush.switch_account(switch_id.clone(), window, cx) + }) + }) + .into_any_element() + }) + .collect(); + + Some(div().flex().flex_col().gap(px(2.)).children(rows)) + } +} + +fn tab( + palette: Palette, + entity: &Entity, + target: Route, + label: &'static str, + route: Route, +) -> impl IntoElement { + let entity = entity.clone(); + let active = route == target; + clickable(label, palette, move |window, cx| { + entity.update(cx, |this, cx| this.change_page(target, window, cx)); + }) + .flex_1() + .flex() + .justify_center() + .py(px(4.)) + .rounded(px(6.)) + .text_size(px(12.)) + .when(active, |tab| { + tab.bg(palette.panel) + .border_1() + .border_color(palette.border) + .text_color(palette.text) + .font_weight(FontWeight::MEDIUM) + }) + .when(!active, |tab| { + tab.border_1() + .border_color(palette.window) + .text_color(palette.muted) + }) + .child(label) +} diff --git a/crates/client/src/gui/chat.rs b/crates/client/src/gui/chat.rs index 37438f7..b3d6d63 100644 --- a/crates/client/src/gui/chat.rs +++ b/crates/client/src/gui/chat.rs @@ -1,28 +1,67 @@ +use std::{ + collections::{HashMap, HashSet}, + sync::Arc, + time::Duration, +}; + +use crate::gui::social::InviteLookup; +use crate::gui::{ + FIND_HINT, Palette, Tooltip as _, Yumush, avatar, badge, clickable, community_icon, + community_name, + community_settings::{BanSort, LogSort}, + composer::{self, Composer}, + hoverable, id_time, + media_view::{self, Media}, + message_actions, new_input, notify_error, palette, primary_button, + profile::profile_popover, + rank_tag, + sidebar::SidebarTab, + snippet, +}; use common::{ constant::MESSAGE_PAGE_LIMIT, event::Event, - model::{Community, Message, User}, - validate::{validate_community_name, validate_message_body}, + model::{ + Ban, Community, CommunityKind, Friends, Invitation, LogEntry, Member, Message, Rank, User, + }, + permission, }; use gpui_kit::{ - Context, Entity, FontWeight, InteractiveElement, IntoElement, ParentElement, - StatefulInteractiveElement, Styled, Window, + Anchor, AnyElement, App, Context, Entity, FontWeight, Image, InteractiveElement, IntoElement, + ParentElement, RenderOnce, ScrollHandle, StatefulInteractiveElement, Styled, Task, Window, + assets::IconName, + base::Selectable, component::{ - WindowExt, - button::Button, + Icon, WindowExt, input::{Input, InputEvent, InputState}, - notification::Notification, + popover::Popover, }, - div, rgb, + div, + prelude::FluentBuilder as _, + px, relative, }; -use crate::gui::{Yumush, new_input, notify_error}; +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum View { + Chat, + Settings, + CommunitySettings, +} #[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum Panel { - None, - Create, - Join, +pub enum DeleteStep { + Idle, + Confirm, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum VoiceState { + Off, + In { + community_id: String, + muted: bool, + deafened: bool, + }, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -42,86 +81,171 @@ impl History { } pub struct Chat { - communities: Vec, - selected_community_id: Option, - members: Vec, - messages: Vec, + pub(super) communities: Vec, + pub(super) selected_community_id: Option, + members: Vec, + pub(super) messages: Vec, history: History, - panel: Panel, - message_input: Entity, - community_name_input: Entity, - community_search_input: Entity, - search_results: Vec, + pub(super) unread: HashSet, + pub(super) message_input: Entity, + pub(super) search_input: Entity, + pub(super) found: Option, + pub(super) invite: InviteLookup, + pub(super) tab: SidebarTab, + pub(super) composer: Composer, + scroll: ScrollHandle, + pub(super) view: View, + pub(super) username_input: Entity, + pub(super) community_name_input: Entity, + pub(super) status_input: Entity, + pub(super) avatars: HashMap>, + pub(super) hues: HashMap, + pub(super) avatar_requests: HashSet, + pub(super) users: HashMap, + user_requests: HashSet, + pub(super) delete_step: DeleteStep, + 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) pending_user_delete: Option, + pub(super) voice: HashMap>, + pub(super) voice_state: VoiceState, + pub(super) speaking: HashSet, + pub(super) voice_task: Option>, + pub(super) media: Media, } impl Chat { pub fn new(window: &mut Window, cx: &mut Context) -> Self { - let message_input = new_input("", window, cx); + let message_input = new_input("Message", window, cx); cx.subscribe_in(&message_input, window, |this, input, event, window, cx| { if matches!(event, InputEvent::PressEnter { .. }) { - send_message(this, input, window, cx); + this.submit_composer(input, window, cx); } }) .detach(); - let community_name_input = new_input("Community Name...", window, cx); + let username_input = editable_input("Username...", Yumush::save_username, window, cx); + let status_input = editable_input("Status...", Yumush::save_status, window, cx); + let community_name_input = + editable_input("Community name...", Yumush::save_community_name, window, cx); + + let search_input = new_input("Find user", window, cx); cx.subscribe_in( - &community_name_input, + &search_input, window, - |this, input, event, window, cx| { - if matches!(event, InputEvent::PressEnter { .. }) { - create_community(this, input, window, cx); - } + |this, _, event, window, cx| match event { + InputEvent::Change => this.search_user(window, cx), + InputEvent::PressEnter { .. } => this.open_found(window, cx), + _ => {} }, ) .detach(); - let community_search_input = new_input("Community Name...", window, cx); - cx.subscribe_in( - &community_search_input, - window, - |this, input, event, window, cx| { - if matches!(event, InputEvent::PressEnter { .. }) { - search_community(this, input, window, cx); + let ban_search = new_input("Search...", window, cx); + let log_search = new_input("Search...", window, cx); + for search in [&ban_search, &log_search] { + cx.subscribe_in(search, window, |_, _, event, window, cx| { + if matches!(event, InputEvent::Change) { + window.refresh(); + cx.notify(); } - }, - ) - .detach(); + }) + .detach(); + } Self { communities: vec![], selected_community_id: None, 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![], history: History::End, - panel: Panel::None, + scroll: ScrollHandle::new(), + unread: HashSet::new(), message_input, + search_input, + found: None, + invite: InviteLookup::Idle, + tab: SidebarTab::Communities, + view: View::Chat, + username_input, community_name_input, - community_search_input, - search_results: vec![], + status_input, + avatars: HashMap::new(), + hues: HashMap::new(), + avatar_requests: HashSet::new(), + users: HashMap::new(), + user_requests: HashSet::new(), + delete_step: DeleteStep::Idle, + pending_user_delete: None, + voice: HashMap::new(), + voice_state: VoiceState::Off, + speaking: HashSet::new(), + voice_task: None, + media: Media::default(), + composer: Composer::Compose { reply: None }, } } + pub(super) fn has_unread(&self, direct: bool) -> bool { + self.communities.iter().any(|community| { + self.unread.contains(&community.id) + && matches!(community.kind, CommunityKind::Direct { .. }) == direct + }) + } + pub fn focus(&self, window: &mut Window, cx: &mut Context) { - self.message_input + let input = match self.selected_community_id { + Some(_) => &self.message_input, + None => &self.search_input, + }; + input.update(cx, |input, cx| input.focus(window, cx)); + } + + pub fn focus_find(&mut self, window: &mut Window, cx: &mut Context) { + self.tab = SidebarTab::Messages; + self.search_input .update(cx, |input, cx| input.focus(window, cx)); } pub fn apply_event(&mut self, event: Event) { match event { - Event::MessageCreated(message) | Event::MessageUpdated(message) => { + Event::MessageCreated(message) => { + if self.is_selected(&message.community_id) { + self.insert_messages([message]); + } else { + self.unread.insert(message.community_id); + } + } + Event::MessageUpdated(message) => { if self.is_selected(&message.community_id) { self.insert_messages([message]); } } Event::MessageDeleted(message) => { if self.is_selected(&message.community_id) { - self.messages.retain(|existing| existing.id != message.id); + self.forget_message(&message.id); } } - Event::MemberJoined { community_id, user } => { + Event::MemberJoined { + community_id, + member, + } => { if self.is_selected(&community_id) { - self.insert_member(user); + self.insert_member(member); } } Event::MemberLeft { @@ -129,31 +253,110 @@ impl Chat { user_id, } => { if self.is_selected(&community_id) { - self.members.retain(|member| member.id != user_id); + self.remove_member(&user_id); + } + } + Event::RankChanged { + community_id, + user_id, + rank, + } => { + if self.is_selected(&community_id) { + self.set_rank(&user_id, rank); + } + } + Event::CommunityUpdated(community) | Event::CommunityAdded(community) => { + self.insert_community(community) + } + Event::FriendsUpdated(friends) => self.friends = friends, + Event::InvitationsUpdated(invitations) => self.invitations = invitations, + Event::CommunityDeleted { community_id } | Event::Removed { 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); + } + Event::UserUpdated(user) => self.update_member(&user), + Event::VoiceJoined { + community_id, + user_id, + } => { + let ids = self.voice.entry(community_id).or_default(); + if !ids.contains(&user_id) { + ids.push(user_id); + } + } + Event::VoiceLeft { + community_id, + user_id, + } => { + if let Some(ids) = self.voice.get_mut(&community_id) { + ids.retain(|id| *id != user_id); } } - Event::CommunityUpdated(community) => self.insert_community(community), - Event::CommunityDeleted { community_id } => self.remove_community(&community_id), } } - fn is_selected(&self, community_id: &str) -> bool { + pub(super) fn is_selected(&self, community_id: &str) -> bool { self.selected_community_id.as_deref() == Some(community_id) } fn select(&mut self, community_id: Option) { + if let Some(community_id) = &community_id { + self.unread.remove(community_id); + } + if self.view == View::CommunitySettings { + self.view = View::Chat; + self.delete_step = DeleteStep::Idle; + } self.selected_community_id = community_id; self.members.clear(); + self.bans.clear(); + self.logs.clear(); + self.pending_user_delete = None; self.messages.clear(); self.history = History::End; + self.media.leave(); + self.composer = Composer::Compose { reply: None }; + } + + fn joined(&self, community_id: &str) -> bool { + self.communities + .iter() + .any(|community| community.id == community_id) + } + + fn forget_message(&mut self, message_id: &str) { + self.messages.retain(|existing| existing.id != message_id); + + let stale = match &self.composer { + Composer::Compose { reply } => reply.as_deref() == Some(message_id), + Composer::Edit { message_id: edited } => edited == message_id, + Composer::Select { .. } => false, + }; + if stale { + self.composer = Composer::Compose { reply: None }; + } + if let Composer::Select { ids } = &mut self.composer { + ids.retain(|id| id != message_id); + } + } + + pub fn communities(&self) -> &[Community] { + &self.communities } fn insert_messages(&mut self, messages: impl IntoIterator) { + let newest = self.messages.last().map(|message| message.id.clone()); for message in messages { self.messages.retain(|existing| existing.id != message.id); self.messages.push(message); } self.messages.sort_by(|left, right| left.id.cmp(&right.id)); + if self.messages.last().map(|message| &message.id) != newest.as_ref() { + self.scroll.scroll_to_bottom(); + } } fn add_page(&mut self, page: Vec) { @@ -161,13 +364,130 @@ impl Chat { self.insert_messages(page); } - fn insert_member(&mut self, user: User) { - self.members.retain(|member| member.id != user.id); - self.members.push(user); - self.members.sort_by(|left, right| left.id.cmp(&right.id)); + fn insert_member(&mut self, member: Member) { + self.remove_member(&member.user.id); + self.members.push(member); + self.members + .sort_by(|left, right| left.user.id.cmp(&right.user.id)); + } + + pub(super) fn remove_member(&mut self, user_id: &str) { + if let Some(index) = self + .members + .iter() + .position(|member| member.user.id == user_id) + { + let member = self.members.remove(index); + self.users.insert(member.user.id.clone(), member.user); + } + } + + fn set_rank(&mut self, user_id: &str, rank: Rank) { + if let Some(member) = self + .members + .iter_mut() + .find(|member| member.user.id == user_id) + { + member.rank = rank; + } + } + + pub fn selected_community(&self) -> Option<&Community> { + self.communities + .iter() + .find(|community| self.is_selected(&community.id)) + } + + pub fn member(&self, user_id: &str) -> Option<&User> { + self.members + .iter() + .map(|member| &member.user) + .find(|user| user.id == user_id) + } + + pub fn author(&self, user_id: &str) -> Option<&User> { + self.member(user_id).or_else(|| self.users.get(user_id)) + } + + fn missing_authors(&self) -> Vec { + if self.members.is_empty() { + return vec![]; + } + let mut missing: Vec = self + .messages + .iter() + .flat_map(|message| { + std::iter::once(&message.user_id) + .chain(message.reply.as_ref().map(|quote| "e.user_id)) + }) + .filter(|id| self.author(id).is_none() && !self.user_requests.contains(*id)) + .cloned() + .collect(); + missing.sort(); + missing.dedup(); + missing + } + + pub fn rank_of(&self, user: &User) -> Option { + let rank = self + .members + .iter() + .find(|member| member.user.id == user.id) + .map(|member| member.rank); + + permission::effective_rank(user.role, rank) + } + + pub fn my_rank(&self, me: &User) -> Option { + self.rank_of(me) } - fn insert_community(&mut self, community: Community) { + pub fn rank_of_id(&self, user_id: &str) -> Option { + self.member(user_id).and_then(|user| self.rank_of(user)) + } + + pub fn can_delete(&self, message: &Message, me: &User) -> bool { + permission::can_delete_message( + self.my_rank(me), + self.rank_of_id(&message.user_id), + message.user_id == me.id, + ) + } + + pub fn update_member(&mut self, user: &User) { + if let Some(member) = self + .members + .iter_mut() + .find(|member| member.user.id == user.id) + { + member.user = user.clone(); + } + + let peers = self + .communities + .iter_mut() + .filter_map(|community| match &mut community.kind { + CommunityKind::Direct { peer } => Some(peer), + CommunityKind::Group => None, + }); + let known = self + .friends + .friends + .iter_mut() + .chain(self.friends.incoming.iter_mut()) + .chain(self.friends.outgoing.iter_mut()) + .chain( + self.invitations + .iter_mut() + .map(|invitation| &mut invitation.inviter), + ) + .chain(peers); + for existing in known.filter(|existing| existing.id == user.id) { + *existing = user.clone(); + } + } + + pub(super) fn insert_community(&mut self, community: Community) { self.communities .retain(|existing| existing.id != community.id); self.communities.push(community); @@ -175,9 +495,14 @@ impl Chat { .sort_by(|left, right| left.id.cmp(&right.id)); } - fn remove_community(&mut self, community_id: &str) { + pub(super) fn remove_community(&mut self, community_id: &str) { self.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(); + } if self.is_selected(community_id) { self.select(None); } @@ -193,66 +518,92 @@ impl Chat { if !selected_present { self.select(None); } - } - fn set_panel(&mut self, panel: Panel) { - if panel != Panel::Join { - self.search_results.clear(); + if self.voice_community().is_some_and(|id| !self.joined(id)) { + self.set_voice_off(); } - self.panel = panel; } pub fn reset(&mut self) { self.communities.clear(); + self.friends = Friends::default(); + self.invitations.clear(); + self.found = None; self.select(None); - self.set_panel(Panel::None); + self.unread.clear(); + self.view = View::Chat; + self.delete_step = DeleteStep::Idle; + self.voice.clear(); + self.set_voice_off(); } -} -fn send_message( - this: &mut Yumush, - input: &Entity, - window: &mut Window, - cx: &mut Context, -) { - let body = input.read(cx).text().to_string(); + pub fn voice_community(&self) -> Option<&str> { + match &self.voice_state { + VoiceState::Off => None, + VoiceState::In { community_id, .. } => Some(community_id), + } + } - if let Err(error) = validate_message_body(&body) { - window.push_notification(Notification::error(error.to_string()), cx); - return; + pub fn in_voice(&self, community_id: &str) -> bool { + self.voice_community() == Some(community_id) } - let Some(community_id) = this.chat.selected_community_id.clone() else { - window.push_notification(Notification::error("No Community Selected"), cx); - return; - }; - let network = this.network.clone(); + pub fn voice_flags(&self) -> Option<(bool, bool)> { + match &self.voice_state { + VoiceState::Off => None, + VoiceState::In { + muted, deafened, .. + } => Some((*muted, *deafened)), + } + } - cx.spawn_in(window, async move |this, cx| { - if let Err(error) = network.create_message(&community_id, &body).await { - notify_error(&this, cx, error); + pub fn voice_ids(&self, community_id: &str) -> &[String] { + self.voice + .get(community_id) + .map(Vec::as_slice) + .unwrap_or_default() + } + + pub fn set_voice_off(&mut self) { + self.voice_state = VoiceState::Off; + self.speaking.clear(); + self.voice_task = None; + } + + pub fn clear_voice_in(&mut self, community_id: &str) { + if self.in_voice(community_id) { + self.set_voice_off(); } - }) - .detach(); + } +} - input.update(cx, |state, cx| state.set_value("", window, cx)); +fn empty_state(palette: Palette) -> impl IntoElement { + div() + .flex_1() + .flex() + .items_center() + .justify_center() + .gap(px(8.)) + .text_color(palette.muted) + .child( + div() + .px(px(5.)) + .rounded(px(4.)) + .border_1() + .border_color(palette.border) + .text_size(px(11.)) + .child(FIND_HINT), + ) + .child("Find a user") } -fn create_community( +pub(super) fn create_community( this: &mut Yumush, - input: &Entity, + name: String, window: &mut Window, cx: &mut Context, ) { - let name = input.read(cx).text().to_string(); - - if let Err(error) = validate_community_name(&name) { - window.push_notification(Notification::error(error.to_string()), cx); - return; - } - let network = this.network.clone(); - input.update(cx, |state, cx| state.set_value("", window, cx)); cx.spawn_in(window, async move |this, cx| { let community = match network.create_community(&name).await { @@ -264,281 +615,273 @@ fn create_community( }; let _ = this.update_in(cx, |yumush, window, cx| { + window.close_dialog(cx); yumush.enter_community(community, window, cx); }); }) .detach(); } -fn search_community( - this: &mut Yumush, - input: &Entity, - window: &mut Window, - cx: &mut Context, -) { - let name = input.read(cx).text().to_string(); +#[derive(IntoElement)] +struct MembersTrigger { + palette: Palette, + members: Vec, + avatars: HashMap>, +} - if let Err(error) = validate_community_name(&name) { - window.push_notification(Notification::error(error.to_string()), cx); - return; +impl Selectable for MembersTrigger { + fn selected(self, _: bool) -> Self { + self } - let network = this.network.clone(); + fn is_selected(&self) -> bool { + false + } +} - cx.spawn_in(window, async move |this, cx| { - let communities = match network.search_community(&name).await { - Ok(communities) => communities, - Err(error) => { - notify_error(&this, cx, error); - return; - } - }; +impl RenderOnce for MembersTrigger { + fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement { + let palette = self.palette; + let avatars = self + .members + .iter() + .take(3) + .enumerate() + .map(|(index, user)| { + avatar(palette, user, px(18.), px(9.), &self.avatars) + .border_2() + .border_color(palette.panel) + .when(index > 0, |this| this.ml(px(-6.))) + }); - let _ = this.update(cx, |yumush, cx| { - yumush.chat.search_results = communities; - cx.notify(); - }); - }) - .detach(); + hoverable( + "members_trigger", + div() + .h(px(28.)) + .px(px(8.)) + .flex() + .items_center() + .gap(px(6.)) + .rounded(px(6.)) + .text_size(px(12.)) + .text_color(palette.muted) + .child(div().flex().children(avatars)) + .child(self.members.len().to_string()), + palette, + ) + } } impl Yumush { pub(super) fn chat_page(&self, cx: &mut Context) -> impl IntoElement { + let palette = palette(cx); let entity = cx.entity(); div() .flex() .flex_row() .size_full() - .child(self.community_list(&entity)) - .child( - div() - .flex() - .flex_col() - .flex_1() - .min_w_0() - .child(self.message_list(&entity)) - .child( - div() - .p_2() - .border_t_1() - .border_color(rgb(0x2f3136)) - .child(Input::new(&self.chat.message_input)), - ), - ) - .child(self.member_list(&entity)) + .child(self.sidebar(&entity, &self.search_query(cx), palette)) + .child(self.main_panel(&entity, palette, cx)) } - fn community_list(&self, entity: &Entity) -> impl IntoElement { + fn main_panel(&self, entity: &Entity, palette: Palette, cx: &App) -> impl IntoElement { + let themed = self.themed(cx); + div() - .id("community_list") - .h_full() + .flex_1() + .min_w_0() + .mt(px(8.)) + .mr(px(8.)) + .mb(px(8.)) .flex() .flex_col() - .flex_shrink_0() - .w_1_5() - .border_r_1() - .border_color(rgb(0x2f3136)) - .bg(rgb(0x2b2d31)) - .p_2() - .gap_1() + .rounded(px(10.)) + .border_1() + .border_color(palette.border) + .bg(palette.panel) + .map(|panel| match self.chat.view { + View::Settings => panel.child(self.settings_page(entity, palette, cx)), + View::CommunitySettings => { + panel.child(self.community_settings_page(entity, palette, cx)) + } + View::Chat => match self.chat.selected_community_id { + Some(_) => panel + .child(self.header(entity, themed)) + .child(self.message_list(entity, themed)) + .child(self.composer(entity, themed)), + None => panel.child(empty_state(palette)), + }, + }) + } + + fn header(&self, entity: &Entity, palette: Palette) -> impl IntoElement { + let community = self.chat.selected_community(); + let name = community.map(community_name).unwrap_or_default(); + let group = + community.is_some_and(|community| matches!(community.kind, CommunityKind::Group)); + + div() + .h(px(44.)) + .pl(px(20.)) + .pr(px(12.)) + .flex() + .items_center() + .gap(px(8.)) + .border_b_2() + .border_color(palette.accent) + .children(community.map(|community| { + community_icon(palette, community, px(20.), px(10.), &self.chat.avatars) + })) .child( div() - .flex() - .flex_row() - .items_center() - .justify_between() - .child( - div() - .text_color(rgb(0x949ba4)) - .font_weight(FontWeight::SEMIBOLD) - .child("Communities"), - ) - .child(panel_button( - entity, - "create_community_button", - "+", - Panel::Create, - )) - .child(panel_button( - entity, - "join_community_button", - "Join", - Panel::Join, - )), - ) - .children( - (self.chat.panel == Panel::Create) - .then(|| Input::new(&self.chat.community_name_input)), - ) - .children( - (self.chat.panel == Panel::Join) - .then(|| Input::new(&self.chat.community_search_input)), - ) - .children( - self.chat - .search_results - .iter() - .filter(|result| { - !self - .chat - .communities - .iter() - .any(|community| community.id == result.id) - }) - .enumerate() - .map(|(index, result)| { - let community_id = result.id.clone(); - let entity = entity.clone(); - - div() - .id(("community_search_result", index)) - .p_1() - .cursor_pointer() - .bg(rgb(0x1e1f22)) - .text_color(rgb(0x949ba4)) - .child(result.name.clone()) - .on_click(move |_, window, cx| { - entity.update(cx, |yumush, cx| { - yumush.join_community(&community_id, window, cx) - }) - }) - }), + .font_weight(FontWeight::SEMIBOLD) + .child(name.to_string()), ) + .child(div().flex_1()) .children( - self.chat - .communities - .iter() - .enumerate() - .map(|(index, community)| { - let community_id = community.id.clone(); - let selected = self.chat.is_selected(&community.id); - let entity = entity.clone(); - - div() - .id(("community", index)) - .p_1() - .cursor_pointer() - .bg(if selected { - rgb(0x404249) - } else { - rgb(0x2b2d31) - }) - .child(community.name.clone()) - .on_click(move |_, window, cx| { - entity.update(cx, |yumush, cx| { - yumush.select_community(community_id.clone(), window, cx) - }) - }) - }), + community + .is_some() + .then(|| self.voice_stack(entity, palette)) + .flatten(), ) + .children(self.voice_button(entity, palette)) + .children(group.then(|| members_popover(entity, &self.chat, palette))) } - fn message_list(&self, entity: &Entity) -> impl IntoElement { + fn message_list(&self, entity: &Entity, palette: Palette) -> impl IntoElement { div() .id("chat_messages") + .track_scroll(&self.chat.scroll) .flex() .flex_col() .flex_1() .min_w_0() .overflow_y_scroll() - .p_2() - .gap_1() - .children((self.chat.history == History::More).then(|| older_button(entity))) + .px(px(24.)) + .py(px(20.)) + .gap(px(2.)) + .child(div().flex_1()) + .children((self.chat.history == History::More).then(|| older_button(entity, palette))) .children( self.chat .messages .iter() - .map(|message| render_message(message, &self.chat.members)), + .enumerate() + .map(|(index, message)| { + let first = + index == 0 || self.chat.messages[index - 1].user_id != message.user_id; + render_message( + message, + first, + index > 0, + &self.chat, + self.user.as_ref(), + entity, + palette, + ) + }), ) } - fn member_list(&self, entity: &Entity) -> impl IntoElement { + fn composer(&self, entity: &Entity, palette: Palette) -> gpui_kit::AnyElement { + if let Composer::Select { ids } = &self.chat.composer { + return div() + .p(px(16.)) + .child(composer::selection_bar(ids, entity, palette)) + .into_any_element(); + } + + let input = self.chat.message_input.clone(); + let attach = entity.clone(); + let pending = media_view::pending_row(&self.chat.media, entity, palette); + let bar = composer::mode_bar(&self.chat, entity, palette); + let entity = entity.clone(); + div() - .id("member_list") - .h_full() - .flex() - .flex_col() - .flex_shrink_0() - .w_1_5() - .border_l_1() - .border_color(rgb(0x2f3136)) - .bg(rgb(0x2b2d31)) - .p_2() - .gap_1() + .p(px(16.)) + .children(pending) + .children(bar) .child( div() + .min_h(px(40.)) + .pl(px(4.)) + .pr(px(4.)) + .py(px(4.)) .flex() - .flex_row() .items_center() - .justify_between() + .gap(px(8.)) + .rounded(px(8.)) + .border_1() + .border_color(palette.border) + .bg(palette.field) .child( - div() - .text_color(rgb(0x949ba4)) - .font_weight(FontWeight::SEMIBOLD) - .child(format!("Members - {}", self.chat.members.len())), + clickable("attach_button", palette, move |window, cx| { + attach.update(cx, |yumush, cx| yumush.attach_files(window, cx)) + }) + .tip("Attach") + .size(px(28.)) + .flex() + .items_center() + .justify_center() + .rounded(px(6.)) + .text_color(palette.muted) + .child(Icon::new(IconName::Plus).w(px(16.)).h(px(16.))), ) - .children( - self.chat - .selected_community_id - .is_some() - .then(|| leave_button(entity)), + .child( + Input::new(&self.chat.message_input) + .appearance(false) + .text_color(palette.text) + .flex_1() + .min_w_0(), + ) + .child( + primary_button("send_button", palette, move |window, cx| { + entity + .update(cx, |yumush, cx| yumush.submit_composer(&input, window, cx)) + }) + .tip("Send") + .size(px(28.)) + .flex() + .items_center() + .justify_center() + .rounded(px(6.)) + .child(Icon::new(IconName::ArrowUp).w(px(14.)).h(px(14.))), ), ) - .children( - self.chat - .members - .iter() - .map(|user| div().p_1().child(user.username.clone())), - ) - } - - fn toggle_panel(&mut self, panel: Panel, window: &mut Window, cx: &mut Context) { - let panel = if self.chat.panel == panel { - Panel::None - } else { - panel - }; - self.chat.set_panel(panel); - - let input = match panel { - Panel::None => None, - Panel::Create => Some(&self.chat.community_name_input), - Panel::Join => Some(&self.chat.community_search_input), - }; - if let Some(input) = input { - input.update(cx, |state, cx| state.focus(window, cx)); - } - - cx.notify(); + .into_any_element() } - fn select_community( + pub(super) fn select_community( &mut self, community_id: String, window: &mut Window, cx: &mut Context, ) { + self.stop_playing(cx); self.chat.select(Some(community_id)); + self.chat.focus(window, cx); self.load_members(window, cx); + self.load_voice(window, cx); self.load_latest_messages(window, cx); cx.notify(); } - fn enter_community( + pub(super) fn enter_community( &mut self, community: Community, window: &mut Window, cx: &mut Context, ) { - self.chat.set_panel(Panel::None); let community_id = community.id.clone(); self.chat.insert_community(community); + self.request_social_avatars(cx); self.select_community(community_id, window, cx); } pub(super) fn reload(&self, window: &mut Window, cx: &mut Context) { self.load_communities(window, cx); + self.load_social(window, cx); if self.chat.selected_community_id.is_some() { self.load_members(window, cx); @@ -560,6 +903,7 @@ impl Yumush { let _ = this.update_in(cx, |yumush, window, cx| { yumush.chat.replace_communities(communities); + yumush.request_social_avatars(cx); if yumush.chat.selected_community_id.is_none() { let first = yumush @@ -592,9 +936,68 @@ impl Yumush { } }; - let _ = this.update(cx, |yumush, cx| { + let _ = this.update_in(cx, |yumush, window, cx| { if yumush.chat.is_selected(&community_id) { + for member in &members { + yumush.request_user_avatar(&member.user, cx); + } yumush.chat.members = members; + yumush.load_bans(window, cx); + yumush.request_authors(window, cx); + cx.notify(); + } + }); + }) + .detach(); + } + + fn request_authors(&mut self, window: &mut Window, cx: &mut Context) { + let missing = self.chat.missing_authors(); + if missing.is_empty() { + return; + } + self.chat.user_requests.extend(missing.iter().cloned()); + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + for user_id in missing { + let Ok(user) = network.read_user(&user_id).await else { + continue; + }; + let _ = this.update(cx, |yumush, cx| { + yumush.request_user_avatar(&user, cx); + yumush.chat.users.insert(user.id.clone(), user); + cx.notify(); + }); + } + }) + .detach(); + } + + pub(super) fn load_bans(&self, window: &mut Window, cx: &mut Context) { + if !permission::can_unban(self.actor_rank()) { + return; + } + let Some(community_id) = self.chat.selected_community_id.clone() else { + return; + }; + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + let bans = match network.bans(&community_id).await { + Ok(bans) => bans, + Err(error) => { + notify_error(&this, cx, error); + return; + } + }; + + let _ = this.update(cx, |yumush, cx| { + if yumush.chat.is_selected(&community_id) { + for ban in &bans { + yumush.request_user_avatar(&ban.user, cx); + } + yumush.chat.bans = bans; cx.notify(); } }); @@ -631,9 +1034,11 @@ impl Yumush { } }; - let _ = this.update(cx, |yumush, cx| { + let _ = this.update_in(cx, |yumush, window, cx| { if yumush.chat.is_selected(&community_id) { yumush.chat.add_page(page); + yumush.request_media(cx); + yumush.request_authors(window, cx); cx.notify(); } }); @@ -641,27 +1046,29 @@ impl Yumush { .detach(); } - fn join_community(&self, community_id: &str, window: &mut Window, cx: &mut Context) { + pub(super) fn delete_message( + &self, + message_id: &str, + window: &mut Window, + cx: &mut Context, + ) { let network = self.network.clone(); - let community_id = community_id.to_string(); + let message_id = message_id.to_string(); cx.spawn_in(window, async move |this, cx| { - match network.join_community(&community_id).await { - Ok(community) => { - let _ = this.update_in(cx, |yumush, window, cx| { - yumush.enter_community(community, window, cx); - }); - } - Err(error) => notify_error(&this, cx, error), + if let Err(error) = network.delete_message(&message_id).await { + notify_error(&this, cx, error); } }) .detach(); } - fn leave_community(&self, window: &mut Window, cx: &mut Context) { - let Some(community_id) = self.chat.selected_community_id.clone() else { - return; - }; + pub(super) fn leave_community( + &self, + community_id: String, + window: &mut Window, + cx: &mut Context, + ) { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { @@ -671,63 +1078,560 @@ impl Yumush { } let _ = this.update(cx, |yumush, cx| { + yumush.leave_voice_in(&community_id, cx); yumush.chat.remove_community(&community_id); cx.notify(); }); }) .detach(); } -} -fn panel_button( - entity: &Entity, - id: &'static str, - label: &'static str, - panel: Panel, -) -> impl IntoElement { - let entity = entity.clone(); + fn load_voice(&self, window: &mut Window, cx: &mut Context) { + let Some(community_id) = self.chat.selected_community_id.clone() else { + return; + }; + let network = self.network.clone(); - Button::new(id).label(label).on_click(move |_, window, cx| { - entity.update(cx, |yumush, cx| yumush.toggle_panel(panel, window, cx)); - }) + cx.spawn_in(window, async move |this, cx| { + let participants = match network.voice_participants(&community_id).await { + Ok(participants) => participants, + Err(error) => { + notify_error(&this, cx, error); + return; + } + }; + + let _ = this.update(cx, |yumush, cx| { + yumush.chat.voice.insert(community_id, participants); + cx.notify(); + }); + }) + .detach(); + } + + fn toggle_voice(&mut self, community_id: String, window: &mut Window, cx: &mut Context) { + if self.chat.in_voice(&community_id) { + self.end_voice(cx); + return; + } + + let (muted, deafened) = self.chat.voice_flags().unwrap_or((false, false)); + let was_in = self.chat.voice_community().is_some(); + if was_in { + self.chat.set_voice_off(); + } + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + if was_in { + let _ = network.leave_voice().await; + } + + match network.join_voice(&community_id).await { + Ok(participants) => { + network.set_muted(muted); + network.set_deafened(deafened); + let _ = this.update_in(cx, |yumush, _, cx| { + yumush.chat.voice.insert(community_id.clone(), participants); + yumush.chat.voice_state = VoiceState::In { + community_id, + muted, + deafened, + }; + yumush.start_voice_poll(cx); + cx.notify(); + }); + } + Err(error) => { + let _ = this.update(cx, |yumush, cx| { + yumush.chat.set_voice_off(); + cx.notify(); + }); + notify_error(&this, cx, error); + } + } + }) + .detach(); + } + + pub(super) fn end_voice(&mut self, cx: &mut Context) { + if self.chat.voice_community().is_none() { + return; + } + self.chat.set_voice_off(); + let network = self.network.clone(); + + cx.spawn(async move |_, _| { + let _ = network.leave_voice().await; + }) + .detach(); + } + + pub(super) fn leave_voice_in(&mut self, community_id: &str, cx: &mut Context) { + if self.chat.in_voice(community_id) { + self.end_voice(cx); + } + } + + fn toggle_mute(&mut self, cx: &mut Context) { + if let VoiceState::In { muted, .. } = &mut self.chat.voice_state { + *muted = !*muted; + self.network.set_muted(*muted); + } + cx.notify(); + } + + fn toggle_deafen(&mut self, cx: &mut Context) { + if let VoiceState::In { deafened, .. } = &mut self.chat.voice_state { + *deafened = !*deafened; + self.network.set_deafened(*deafened); + } + cx.notify(); + } + + 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| { + loop { + cx.background_executor() + .timer(Duration::from_millis(150)) + .await; + let speaking = network.speaking(); + let polling = this.update(cx, |yumush, cx| { + if yumush.chat.voice_community().is_none() { + return false; + } + yumush.update_speaking(speaking, cx); + true + }); + if !matches!(polling, Ok(true)) { + break; + } + } + })); + } + + fn update_speaking(&mut self, mut speaking: Vec, cx: &mut Context) { + let silent = self + .chat + .voice_flags() + .is_some_and(|(muted, deafened)| muted || deafened); + if silent { + speaking.retain(|id| !self.is_me(id)); + } + + let speaking: HashSet = speaking.into_iter().collect(); + if speaking != self.chat.speaking { + self.chat.speaking = speaking; + cx.notify(); + } + } + + fn voice_button(&self, entity: &Entity, palette: Palette) -> Option { + let community_id = self.chat.selected_community_id.clone()?; + let in_voice = self.chat.in_voice(&community_id); + if !in_voice && !permission::can_join_voice(self.actor_rank()) { + return None; + } + + let entity = entity.clone(); + let on_click = move |window: &mut Window, cx: &mut App| { + entity.update(cx, |yumush, cx| { + yumush.toggle_voice(community_id.clone(), window, cx) + }) + }; + let button = if in_voice { + primary_button("voice_button", palette, on_click) + } else { + clickable("voice_button", palette, on_click) + }; + + Some( + button + .tip(if in_voice { + "Leave voice" + } else { + "Join voice" + }) + .size(px(28.)) + .flex() + .items_center() + .justify_center() + .rounded(px(6.)) + .text_color(if in_voice { + palette.on_accent + } else { + palette.accent + }) + .child(Icon::new(IconName::Headphones).w(px(14.)).h(px(14.))), + ) + } + + fn voice_stack(&self, entity: &Entity, palette: Palette) -> Option { + let community_id = self.chat.selected_community_id.as_deref()?; + let users: Vec<&User> = self + .chat + .voice_ids(community_id) + .iter() + .filter_map(|id| self.chat.member(id)) + .collect(); + if users.is_empty() { + return None; + } + + Some( + div() + .flex() + .children(users.into_iter().take(3).enumerate().map(|(index, user)| { + let ring = if self.chat.speaking.contains(&user.id) { + palette.ok + } else { + palette.panel + }; + + profile_popover( + format!("voice_{}", user.id), + Anchor::TopRight, + user, + entity, + avatar(palette, user, px(20.), px(10.), &self.chat.avatars) + .border_2() + .border_color(ring) + .cursor_pointer() + .hover(move |style| style.border_color(palette.accent)) + .when(index > 0, |this| this.ml(px(-6.))), + ) + })), + ) + } + + pub(super) fn voice_controls( + &self, + entity: &Entity, + palette: Palette, + ) -> Option { + let (muted, deafened) = self.chat.voice_flags()?; + let mic_entity = entity.clone(); + let deafen_entity = entity.clone(); + let mic_icon = if muted { + IconName::MicOff + } else { + IconName::Mic + }; + let deafen_icon = if deafened { + IconName::VolumeX + } else { + IconName::Headphones + }; + + Some( + div() + .flex() + .items_center() + .child( + clickable("mic_button", palette, move |_, cx| { + mic_entity.update(cx, |yumush, cx| yumush.toggle_mute(cx)) + }) + .tip(if muted { "Unmute" } else { "Mute" }) + .size(px(26.)) + .flex() + .items_center() + .justify_center() + .rounded(px(6.)) + .text_color(if muted || deafened { + palette.danger + } else { + palette.muted + }) + .child(Icon::new(mic_icon).w(px(14.)).h(px(14.))), + ) + .child( + clickable("deafen_button", palette, move |_, cx| { + deafen_entity.update(cx, |yumush, cx| yumush.toggle_deafen(cx)) + }) + .tip(if deafened { "Undeafen" } else { "Deafen" }) + .size(px(26.)) + .flex() + .items_center() + .justify_center() + .rounded(px(6.)) + .text_color(if deafened { + palette.danger + } else { + palette.muted + }) + .child(Icon::new(deafen_icon).w(px(14.)).h(px(14.))), + ), + ) + } } -fn leave_button(entity: &Entity) -> impl IntoElement { +fn members_popover(entity: &Entity, chat: &Chat, palette: Palette) -> impl IntoElement { let entity = entity.clone(); + let voice: Vec = chat + .selected_community_id + .as_deref() + .map(|community_id| chat.voice_ids(community_id).to_vec()) + .unwrap_or_default(); + let members: Vec<(User, Option, bool)> = chat + .members + .iter() + .map(|member| { + ( + member.user.clone(), + chat.rank_of(&member.user), + voice.contains(&member.user.id), + ) + }) + .collect(); + let avatars = chat.avatars.clone(); + + Popover::new("members_popover") + .anchor(Anchor::TopRight) + .appearance(false) + .trigger(MembersTrigger { + palette, + members: members.iter().map(|(user, _, _)| user.clone()).collect(), + avatars: avatars.clone(), + }) + .content(move |_, _, _| { + let entity = entity.clone(); - Button::new("leave_community_button") - .label("Leave") - .on_click(move |_, window, cx| { - entity.update(cx, |yumush, cx| yumush.leave_community(window, cx)); + div() + .w(px(200.)) + .p(px(4.)) + .flex() + .flex_col() + .rounded(px(8.)) + .border_1() + .border_color(palette.border) + .bg(palette.panel) + .children(members.iter().map(|(user, rank, in_voice)| { + profile_popover( + format!("member_{}", user.id), + Anchor::TopRight, + user, + &entity, + hoverable( + format!("member_trigger_{}", user.id), + div() + .h(px(30.)) + .px(px(8.)) + .flex() + .items_center() + .gap(px(8.)) + .rounded(px(6.)) + .child(avatar(palette, user, px(18.), px(9.), &avatars)) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .child( + div() + .flex() + .items_center() + .gap(px(6.)) + .child(user.username.clone()) + .children(rank_tag(*rank, palette)) + .children(in_voice.then(|| { + Icon::new(IconName::Headphones) + .w(px(12.)) + .h(px(12.)) + .text_color(palette.muted) + })), + ) + .children((!user.status.is_empty()).then(|| { + div() + .text_size(px(11.)) + .text_color(palette.muted) + .truncate() + .child(user.status.clone()) + })), + ), + palette, + ), + ) + })) }) } -fn older_button(entity: &Entity) -> impl IntoElement { +fn older_button(entity: &Entity, palette: Palette) -> impl IntoElement { let entity = entity.clone(); - Button::new("load_older_button") - .label("↑") - .on_click(move |_, window, cx| { - entity.update(cx, |yumush, cx| yumush.load_older_messages(window, cx)); - }) + clickable("load_older_button", palette, move |window, cx| { + entity.update(cx, |yumush, cx| yumush.load_older_messages(window, cx)); + }) + .self_center() + .h(px(24.)) + .px(px(8.)) + .flex() + .items_center() + .rounded(px(6.)) + .text_color(palette.muted) + .child("↑") } -fn render_message(message: &Message, members: &[User]) -> impl IntoElement { - let username = members - .iter() - .find(|user| user.id == message.user_id) +fn render_message( + message: &Message, + first: bool, + spaced: bool, + chat: &Chat, + me: Option<&User>, + entity: &Entity, + palette: Palette, +) -> AnyElement { + let author = chat.author(&message.user_id); + let username = author .map(|user| user.username.as_str()) - .unwrap_or(message.user_id.as_str()); - - div() + .unwrap_or("unknown"); + let name = div() .flex() - .flex_col() - .p_1() + .items_center() + .gap(px(8.)) + .child(match author { + Some(user) => avatar(palette, user, px(20.), px(10.), &chat.avatars), + None => badge(palette, &message.user_id, username, px(20.), px(10.)).rounded_full(), + }) .child( div() - .text_color(rgb(0x7289da)) - .font_weight(FontWeight::BOLD) + .id(format!("author_name_{}", message.id)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(palette.tinted(&message.user_id)) + .when(author.is_some(), |this| { + this.hover(|style| style.underline()) + }) .child(username.to_string()), - ) - .child(div().pl_2().child(message.body.clone())) + ); + let group = format!("message_{}", message.id); + let selecting = matches!(chat.composer, Composer::Select { .. }); + let selected = matches!(&chat.composer, Composer::Select { ids } if ids.contains(&message.id)); + + let row = + div() + .id(format!("message_row_{}", message.id)) + .group(group.clone()) + .flex() + .flex_col() + .min_w_0() + .when(first && spaced, |this| this.mt(px(14.))) + .when(first, |this| { + let author = match author { + Some(user) => profile_popover( + format!("author_{}", message.id), + Anchor::TopLeft, + user, + entity, + name.cursor_pointer(), + ) + .into_any_element(), + None => name.into_any_element(), + }; + + this.child( + div() + .flex() + .items_center() + .gap(px(8.)) + .mb(px(2.)) + .child(author) + .child( + div() + .text_size(px(12.)) + .text_color(palette.muted) + .child(id_time(&message.id, "%H:%M")), + ), + ) + }) + .child( + div() + .pl(px(28.)) + .flex() + .items_center() + .gap(px(8.)) + .child( + div() + .max_w(px(720.)) + .flex() + .flex_col() + .gap(px(6.)) + .children(message_actions::quote_line(message, chat, palette)) + .when(!message.body.is_empty(), |this| { + this.child( + div() + .flex() + .flex_wrap() + .items_baseline() + .gap(px(4.)) + .line_height(relative(1.55)) + .text_color(palette.body) + .child(message.body.clone()) + .when(message.edited, |this| { + this.child( + div() + .text_size(px(11.)) + .text_color(palette.muted) + .child("(edited)"), + ) + }), + ) + }) + .children(media_view::attachments( + &message.attachments, + &chat.media, + entity, + palette, + )) + .children(snippet::snippet_card(message, chat, entity, palette)) + .children(media_view::embeds(message, &chat.media, palette)), + ) + .child(div().flex_1()) + .children((!selecting).then(|| { + message_actions::actions(message, chat, me, entity, palette, group) + })), + ); + + if !selecting { + return row.into_any_element(); + } + + let message_id = message.id.clone(); + let select_entity = entity.clone(); + let row = row + .flex_1() + .cursor_pointer() + .when(selected, |this| this.bg(palette.hover)) + .on_click(move |_, _, cx| { + select_entity.update(cx, |yumush, cx| yumush.toggle_select(&message_id, cx)); + }); + + div() + .flex() + .items_start() + .gap(px(8.)) + .child(message_actions::selection_mark(selected, palette)) + .child(row) + .into_any_element() +} + +fn editable_input( + placeholder: &'static str, + save: fn(&mut Yumush, &mut Window, &mut Context), + window: &mut Window, + cx: &mut Context, +) -> Entity { + let input = new_input(placeholder, window, cx); + cx.subscribe_in( + &input, + window, + move |this, _, event, window, cx| match event { + InputEvent::PressEnter { .. } => save(this, window, cx), + InputEvent::Change => cx.notify(), + _ => {} + }, + ) + .detach(); + input } diff --git a/crates/client/src/gui/community_settings.rs b/crates/client/src/gui/community_settings.rs new file mode 100644 index 0000000..8e0f6e6 --- /dev/null +++ b/crates/client/src/gui/community_settings.rs @@ -0,0 +1,660 @@ +use std::{collections::HashMap, sync::Arc}; + +use common::{ + error::Error, + model::{Ban, Community, LogAction, LogEntry, User}, + permission, + validate::validate_community_name, +}; +use gpui_kit::{ + AnyElement, App, AsyncWindowContext, Context, Div, Entity, Image, InteractiveElement, + IntoElement, ParentElement, PathPromptOptions, StatefulInteractiveElement, Styled, WeakEntity, + Window, + component::{ + WindowExt, + input::{Input, InputState}, + notification::Notification, + }, + div, + prelude::FluentBuilder as _, + px, +}; + +use super::{ + Palette, Yumush, avatar, + chat::{DeleteStep, View}, + clickable, community_icon, entity_action, id_time, notify_error, + settings_page::{ + Editable, Picture, danger_section, delete_control, page, picture_card, read_avatar_file, + row, section, text_row, + }, +}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum BanSort { + Newest, + Oldest, + Name, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum LogSort { + Newest, + Oldest, +} + +const BAN_SORTS: [(BanSort, &str); 3] = [ + (BanSort::Newest, "Newest"), + (BanSort::Oldest, "Oldest"), + (BanSort::Name, "Name"), +]; + +const LOG_SORTS: [(LogSort, &str); 2] = [(LogSort::Newest, "Newest"), (LogSort::Oldest, "Oldest")]; + +fn apply_community( + this: &WeakEntity, + cx: &mut AsyncWindowContext, + result: Result, +) { + match result { + Ok(community) => { + let _ = this.update(cx, |yumush, cx| { + yumush.chat.insert_community(community); + yumush.request_social_avatars(cx); + cx.notify(); + }); + } + Err(error) => notify_error(this, cx, error), + } +} + +impl Yumush { + pub(super) fn community_settings_page( + &self, + entity: &Entity, + palette: Palette, + cx: &App, + ) -> impl IntoElement { + let name = self + .chat + .selected_community() + .map(|community| community.name.clone()) + .unwrap_or_default(); + let actor = self.actor_rank(); + let community_id = self.chat.selected_community_id.clone().unwrap_or_default(); + let bans_count = self.chat.bans.len(); + let mut sections = Vec::new(); + + if let Some(community) = self + .chat + .selected_community() + .filter(|_| permission::can_rename_community(actor)) + { + sections.push( + picture_card( + Picture { + id: "community_picture_picker", + image: community_icon( + palette, + community, + px(64.), + px(24.), + &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) { + sections.push( + section( + "General", + palette, + vec![text_row( + Editable { + id: "save_community_name_button", + label: "Name", + input: &self.chat.community_name_input, + current: &name, + save: Yumush::save_community_name, + }, + entity, + palette, + cx, + )], + ) + .into_any_element(), + ); + } + let mut moderation = Vec::new(); + if permission::can_unban(actor) { + moderation.push(row( + "Bans", + div() + .flex() + .items_center() + .gap(px(8.)) + .child( + div() + .text_size(px(12.)) + .text_color(palette.muted) + .child(bans_count.to_string()), + ) + .child(view_control( + "view_bans_button", + entity, + palette, + Yumush::open_bans, + )), + )); + } + if permission::can_read_logs(actor) { + moderation.push(row( + "Logs", + view_control("view_logs_button", entity, palette, Yumush::open_logs), + )); + } + if !moderation.is_empty() { + sections.push(section("Moderation", palette, moderation).into_any_element()); + } + let mut danger = Vec::new(); + if permission::can_leave(actor) { + danger.push(row( + "Leave community", + leave_control(entity, community_id, palette), + )); + } + if permission::can_delete_community(actor) { + danger.push(row( + "Delete community", + delete_control( + "delete_community_button", + self.chat.delete_step, + entity, + palette, + Yumush::delete_community, + ), + )); + } + if !danger.is_empty() { + sections.push(danger_section(palette, danger).into_any_element()); + } + + page("community_settings_scroll", entity, palette, name, sections) + } + + pub(super) fn save_community_name(&mut self, window: &mut Window, cx: &mut Context) { + let Some(community_id) = self.chat.selected_community_id.clone() else { + return; + }; + let name = self.chat.community_name_input.read(cx).text().to_string(); + + if let Err(error) = validate_community_name(&name) { + window.push_notification(Notification::error(error.to_string()), cx); + return; + } + + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + match network.update_community(&community_id, &name).await { + Ok(community) => { + let _ = this.update(cx, |yumush, cx| { + yumush.chat.insert_community(community); + cx.notify(); + }); + } + Err(error) => notify_error(&this, cx, error), + } + }) + .detach(); + } + + fn upload_community_picture(&mut self, window: &mut Window, cx: &mut Context) { + let Some(community_id) = self.chat.selected_community_id.clone() else { + return; + }; + let picked = cx.prompt_for_paths(PathPromptOptions { + files: true, + directories: false, + multiple: false, + prompt: None, + }); + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + let Ok(Ok(Some(paths))) = picked.await else { + return; + }; + let Some(path) = paths.into_iter().next() else { + return; + }; + let prepared = cx + .background_executor() + .spawn(async move { read_avatar_file(&path) }) + .await; + let result = match prepared { + Ok(bytes) => { + network + .update_community_avatar(&community_id, Some(bytes)) + .await + } + Err(error) => Err(error), + }; + apply_community(&this, cx, result); + }) + .detach(); + } + + fn remove_community_picture(&mut self, window: &mut Window, cx: &mut Context) { + let Some(community_id) = self.chat.selected_community_id.clone() else { + return; + }; + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + let result = network.update_community_avatar(&community_id, None).await; + apply_community(&this, cx, result); + }) + .detach(); + } + + pub(super) fn delete_community(&mut self, window: &mut Window, cx: &mut Context) { + match self.chat.delete_step { + DeleteStep::Idle => { + self.chat.delete_step = DeleteStep::Confirm; + cx.notify(); + } + DeleteStep::Confirm => { + let Some(community_id) = self.chat.selected_community_id.clone() else { + return; + }; + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + match network.delete_community(&community_id).await { + Ok(()) => { + let _ = this.update_in(cx, |yumush, window, cx| { + yumush.chat.remove_community(&community_id); + yumush.show_view(View::Chat, window, cx); + }); + } + Err(error) => notify_error(&this, cx, error), + } + }) + .detach(); + } + } + } + + pub(super) fn unban(&self, user_id: &str, window: &mut Window, cx: &mut Context) { + let Some(community_id) = self.chat.selected_community_id.clone() else { + return; + }; + let network = self.network.clone(); + let user_id = user_id.to_string(); + + cx.spawn_in(window, async move |this, cx| { + match network.unban(&community_id, &user_id).await { + Ok(()) => { + let _ = this.update_in(cx, |yumush, window, cx| { + yumush.chat.bans.retain(|ban| ban.user.id != user_id); + window.refresh(); + cx.notify(); + }); + } + Err(error) => notify_error(&this, cx, error), + } + }) + .detach(); + } + + fn open_bans(&mut self, window: &mut Window, cx: &mut Context) { + let entity = cx.entity(); + window.open_dialog(cx, move |dialog, _, cx| { + let yumush = entity.read(cx); + let palette = yumush.themed(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(); + + dialog.title("Bans").child(moderation_body( + "bans_scroll", + &yumush.chat.ban_search, + sort_control( + BAN_SORTS, + yumush.chat.ban_sort, + &entity, + palette, + Yumush::set_ban_sort, + ), + rows, + "No bans", + palette, + )) + }); + } + + fn open_logs(&mut self, window: &mut Window, cx: &mut Context) { + self.load_logs(window, cx); + let entity = cx.entity(); + window.open_dialog(cx, move |dialog, _, cx| { + let yumush = entity.read(cx); + let palette = yumush.themed(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(); + + dialog.title("Logs").child(moderation_body( + "logs_scroll", + &yumush.chat.log_search, + sort_control( + LOG_SORTS, + yumush.chat.log_sort, + &entity, + palette, + Yumush::set_log_sort, + ), + rows, + "No logs", + palette, + )) + }); + } + + fn set_ban_sort(&mut self, sort: BanSort, window: &mut Window, cx: &mut Context) { + self.chat.ban_sort = sort; + window.refresh(); + cx.notify(); + } + + fn set_log_sort(&mut self, sort: LogSort, window: &mut Window, cx: &mut Context) { + self.chat.log_sort = sort; + window.refresh(); + cx.notify(); + } + + fn load_logs(&self, window: &mut Window, cx: &mut Context) { + let Some(community_id) = self.chat.selected_community_id.clone() else { + return; + }; + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + let logs = match network.logs(&community_id).await { + Ok(logs) => logs, + Err(error) => { + notify_error(&this, cx, error); + return; + } + }; + + let _ = this.update_in(cx, |yumush, window, cx| { + if yumush.chat.is_selected(&community_id) { + for entry in &logs { + if let Some(actor) = &entry.actor { + yumush.request_user_avatar(actor, cx); + } + if let Some(target) = &entry.target { + yumush.request_user_avatar(target, cx); + } + } + yumush.chat.logs = logs; + window.refresh(); + cx.notify(); + } + }); + }) + .detach(); + } +} + +fn view_control( + id: &'static str, + entity: &Entity, + palette: Palette, + open: fn(&mut Yumush, &mut Window, &mut Context), +) -> impl IntoElement { + clickable(id, palette, entity_action(entity, open)) + .h(px(28.)) + .px(px(10.)) + .flex() + .items_center() + .rounded(px(6.)) + .border_1() + .border_color(palette.border) + .text_size(px(13.)) + .child("View") +} + +fn sort_control( + options: [(T, &'static str); N], + selected: T, + entity: &Entity, + palette: Palette, + select: fn(&mut Yumush, T, &mut Window, &mut Context), +) -> impl IntoElement { + div() + .h(px(24.)) + .p(px(2.)) + .flex() + .gap(px(2.)) + .rounded(px(6.)) + .border_1() + .border_color(palette.border) + .bg(palette.field) + .children(options.map(|(choice, label)| { + let active = choice == selected; + + clickable( + label, + palette, + entity_action(entity, move |yumush, window, cx| { + select(yumush, choice, window, cx) + }), + ) + .px(px(8.)) + .flex() + .items_center() + .rounded(px(4.)) + .text_size(px(12.)) + .text_color(if active { palette.text } else { palette.muted }) + .when(active, |this| this.bg(palette.hover)) + .child(label) + })) +} + +fn moderation_body( + id: &'static str, + search: &Entity, + sort: impl IntoElement, + rows: Vec, + empty: &'static str, + palette: Palette, +) -> impl IntoElement { + let list = if rows.is_empty() { + div() + .text_size(px(13.)) + .text_color(palette.muted) + .child(empty) + .into_any_element() + } else { + div().flex().flex_col().children(rows).into_any_element() + }; + + div() + .flex() + .flex_col() + .gap(px(12.)) + .child(Input::new(search)) + .child(sort) + .child(div().id(id).max_h(px(360.)).overflow_y_scroll().child(list)) +} + +fn search_text(input: &Entity, cx: &App) -> String { + input.read(cx).text().to_string().trim().to_lowercase() +} + +fn ban_list<'a>(bans: &'a [Ban], query: &str, sort: BanSort) -> Vec<&'a Ban> { + let mut list: Vec<&Ban> = bans + .iter() + .filter(|ban| ban.user.username.to_lowercase().contains(query)) + .collect(); + match sort { + BanSort::Newest => {} + BanSort::Oldest => list.reverse(), + BanSort::Name => list.sort_by_key(|ban| ban.user.username.to_lowercase()), + } + list +} + +fn log_list<'a>(logs: &'a [LogEntry], query: &str, sort: LogSort) -> Vec<&'a LogEntry> { + let mut list: Vec<&LogEntry> = logs + .iter() + .filter(|entry| log_text(entry).to_lowercase().contains(query)) + .collect(); + match sort { + LogSort::Newest => {} + LogSort::Oldest => list.reverse(), + } + list +} + +fn user_name(user: &Option) -> &str { + user.as_ref() + .map_or("someone", |user| user.username.as_str()) +} + +fn with_reason(text: String, reason: &Option) -> String { + match reason { + Some(reason) => format!("{text} · {reason}"), + None => text, + } +} + +fn log_text(entry: &LogEntry) -> String { + let actor = user_name(&entry.actor); + let target = user_name(&entry.target); + + match &entry.action { + LogAction::Created => format!("{actor} created the community"), + LogAction::Renamed { name } => format!("{actor} renamed to {name}"), + LogAction::AvatarChanged => format!("{actor} changed the avatar"), + LogAction::AvatarRemoved => format!("{actor} removed the avatar"), + LogAction::Invited => format!("{actor} invited {target}"), + LogAction::Joined => format!("{actor} joined"), + LogAction::Left => format!("{actor} left"), + LogAction::Kicked { reason } => with_reason(format!("{actor} kicked {target}"), reason), + LogAction::Banned { reason } => with_reason(format!("{actor} banned {target}"), reason), + LogAction::Unbanned => format!("{actor} unbanned {target}"), + LogAction::RankChanged { rank } => { + format!("{actor} changed rank of {target} to {}", rank.as_str()) + } + LogAction::MessageDeleted => format!("{actor} deleted a message by {target}"), + } +} + +fn log_row(entry: &LogEntry, palette: Palette, avatars: &HashMap>) -> Div { + div() + .min_h(px(40.)) + .px(px(12.)) + .flex() + .items_center() + .gap(px(8.)) + .children( + entry + .actor + .as_ref() + .map(|actor| avatar(palette, actor, px(20.), px(10.), avatars)), + ) + .child(div().flex_1().min_w_0().truncate().child(log_text(entry))) + .child( + div() + .flex_shrink_0() + .text_size(px(11.)) + .text_color(palette.muted) + .child(id_time(&entry.id, "%b %-d, %H:%M")), + ) +} + +fn leave_control( + entity: &Entity, + community_id: String, + palette: Palette, +) -> impl IntoElement { + let entity = entity.clone(); + + clickable("leave_community_button", palette, move |window, cx| { + entity.update(cx, |yumush, cx| { + yumush.leave_community(community_id.clone(), window, cx) + }); + }) + .h(px(28.)) + .px(px(10.)) + .flex() + .items_center() + .rounded(px(6.)) + .border_1() + .border_color(palette.danger.opacity(0.5)) + .text_size(px(13.)) + .text_color(palette.danger) + .child("Leave") +} + +fn ban_row( + ban: &Ban, + entity: &Entity, + palette: Palette, + avatars: &HashMap>, +) -> Div { + let entity = entity.clone(); + let user = &ban.user; + let user_id = user.id.clone(); + + div() + .h(px(48.)) + .px(px(12.)) + .flex() + .items_center() + .gap(px(8.)) + .child(avatar(palette, user, px(20.), px(10.), avatars)) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .child(user.username.clone()) + .children(ban.reason.clone().map(|reason| { + div() + .text_size(px(11.)) + .text_color(palette.muted) + .truncate() + .child(reason) + })), + ) + .child( + clickable(format!("unban_{}", user.id), palette, move |window, cx| { + entity.update(cx, |yumush, cx| yumush.unban(&user_id, window, cx)); + }) + .h(px(28.)) + .px(px(8.)) + .flex() + .items_center() + .rounded(px(6.)) + .text_color(palette.danger) + .child("Unban"), + ) +} diff --git a/crates/client/src/gui/composer.rs b/crates/client/src/gui/composer.rs new file mode 100644 index 0000000..b3a78cb --- /dev/null +++ b/crates/client/src/gui/composer.rs @@ -0,0 +1,294 @@ +use common::{ + constant::MAXIMUM_FORWARD_MESSAGES, + validate::{validate_message_body, validate_new_message}, +}; +use gpui_kit::{ + AnyElement, Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window, + assets::IconName, + component::{Icon, WindowExt, input::InputState, notification::Notification}, + div, px, +}; + +use super::{Palette, Tooltip as _, Yumush, chat::Chat, clickable, notify_error, primary_button}; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Composer { + Compose { reply: Option }, + Edit { message_id: String }, + Select { ids: Vec }, +} + +pub fn mode_bar(chat: &Chat, entity: &Entity, palette: Palette) -> Option { + 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()), + Composer::Compose { reply: None } | Composer::Select { .. } => None, + } +} + +pub fn selection_bar( + ids: &[String], + entity: &Entity, + palette: Palette, +) -> impl IntoElement { + let count = ids.len(); + let selected = ids.to_vec(); + let forward_entity = entity.clone(); + + div() + .h(px(40.)) + .pl(px(14.)) + .pr(px(6.)) + .flex() + .items_center() + .gap(px(8.)) + .rounded(px(8.)) + .border_1() + .border_color(palette.border) + .bg(palette.field) + .child(div().flex_1().child(format!("{count} selected"))) + .child( + primary_button("forward_selected", palette, move |window, cx| { + let selected = selected.clone(); + forward_entity.update(cx, |yumush, cx| yumush.open_forward(selected, window, cx)); + }) + .h(px(28.)) + .px(px(10.)) + .flex() + .items_center() + .rounded(px(6.)) + .text_size(px(12.)) + .child("Forward"), + ) + .child(cancel_button(entity, palette)) +} + +fn bar(palette: Palette) -> Div { + div() + .h(px(28.)) + .mb(px(8.)) + .px(px(8.)) + .flex() + .items_center() + .gap(px(6.)) + .rounded(px(6.)) + .bg(palette.hover) + .text_size(px(12.)) + .text_color(palette.muted) +} + +fn reply_bar( + chat: &Chat, + message_id: &str, + entity: &Entity, + palette: Palette, +) -> impl IntoElement { + let message = chat + .messages + .iter() + .find(|message| message.id == message_id); + let author = message + .and_then(|message| chat.author(&message.user_id)) + .map_or("unknown", |user| user.username.as_str()) + .to_string(); + let quote = message + .map(|message| super::message_actions::quote_text(&message.body, message.attachments.len())) + .unwrap_or_default(); + + bar(palette) + .child("Replying to") + .child( + div() + .font_weight(FontWeight::SEMIBOLD) + .text_color(palette.text) + .child(author), + ) + .child(div().flex_1().min_w_0().truncate().child(quote)) + .child(cancel_button(entity, palette)) +} + +fn edit_bar(entity: &Entity, palette: Palette) -> impl IntoElement { + bar(palette) + .child(Icon::new(IconName::Pencil).w(px(12.)).h(px(12.))) + .child("Editing") + .child(div().flex_1()) + .child(cancel_button(entity, palette)) +} + +fn cancel_button(entity: &Entity, palette: Palette) -> impl IntoElement { + let entity = entity.clone(); + + clickable("cancel_composer", palette, move |window, cx| { + entity.update(cx, |yumush, cx| yumush.cancel_composer(window, cx)); + }) + .tip("Cancel") + .size(px(20.)) + .flex_shrink_0() + .flex() + .items_center() + .justify_center() + .rounded(px(4.)) + .child(Icon::new(IconName::Close).w(px(12.)).h(px(12.))) +} + +impl Yumush { + pub(super) fn submit_composer( + &mut self, + input: &Entity, + window: &mut Window, + cx: &mut Context, + ) { + if self.chat.media.uploading() { + return; + } + let body = input.read(cx).text().to_string(); + + 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::Select { .. } => {} + } + } + + fn create_message( + &mut self, + reply: Option, + body: String, + input: &Entity, + window: &mut Window, + cx: &mut Context, + ) { + let attachments: Vec = self + .chat + .media + .pending + .iter() + .map(|attachment| attachment.id.clone()) + .collect(); + + if let Err(error) = validate_new_message(&body, attachments.len()) { + window.push_notification(Notification::error(error.to_string()), cx); + return; + } + let Some(community_id) = self.chat.selected_community_id.clone() else { + window.push_notification(Notification::error("No Community Selected"), cx); + return; + }; + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + if let Err(error) = network + .create_message(&community_id, &body, attachments, reply) + .await + { + notify_error(&this, cx, error); + } + }) + .detach(); + + input.update(cx, |state, cx| state.set_value("", window, cx)); + self.chat.media.pending.clear(); + self.chat.composer = Composer::Compose { reply: None }; + } + + fn update_message( + &mut self, + message_id: String, + body: String, + input: &Entity, + window: &mut Window, + cx: &mut Context, + ) { + if let Err(error) = validate_message_body(&body) { + window.push_notification(Notification::error(error.to_string()), cx); + return; + } + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + if let Err(error) = network.update_message(&message_id, &body).await { + notify_error(&this, cx, error); + } + }) + .detach(); + + input.update(cx, |state, cx| state.set_value("", window, cx)); + self.chat.composer = Composer::Compose { reply: None }; + cx.notify(); + } + + pub(super) fn reply( + &mut self, + message_id: String, + window: &mut Window, + cx: &mut Context, + ) { + self.chat.composer = Composer::Compose { + reply: Some(message_id), + }; + self.chat.focus(window, cx); + cx.notify(); + } + + pub(super) fn edit(&mut self, message_id: String, window: &mut Window, cx: &mut Context) { + let Some(body) = self + .chat + .messages + .iter() + .find(|message| message.id == message_id) + .map(|message| message.body.clone()) + else { + return; + }; + + self.chat + .message_input + .update(cx, |input, cx| input.set_value(body, window, cx)); + self.chat.composer = Composer::Edit { message_id }; + self.chat.focus(window, cx); + cx.notify(); + } + + pub(super) fn start_select( + &mut self, + message_id: String, + window: &mut Window, + cx: &mut Context, + ) { + self.chat.composer = Composer::Select { + ids: vec![message_id], + }; + self.focus.focus(window, cx); + cx.notify(); + } + + pub(super) fn toggle_select(&mut self, message_id: &str, cx: &mut Context) { + let Composer::Select { ids } = &mut self.chat.composer else { + return; + }; + if let Some(index) = ids.iter().position(|id| id == message_id) { + ids.remove(index); + } else if ids.len() < MAXIMUM_FORWARD_MESSAGES { + ids.push(message_id.to_string()); + } + cx.notify(); + } + + pub(super) fn cancel_composer(&mut self, window: &mut Window, cx: &mut Context) { + match self.chat.composer.clone() { + Composer::Compose { reply: None } => return, + Composer::Compose { reply: Some(_) } | Composer::Select { .. } => {} + Composer::Edit { .. } => self + .chat + .message_input + .update(cx, |input, cx| input.set_value("", window, cx)), + } + self.chat.composer = Composer::Compose { reply: None }; + self.chat.focus(window, cx); + cx.notify(); + } +} diff --git a/crates/client/src/gui/forward.rs b/crates/client/src/gui/forward.rs new file mode 100644 index 0000000..6185dca --- /dev/null +++ b/crates/client/src/gui/forward.rs @@ -0,0 +1,196 @@ +use gpui_kit::{ + AppContext, Context, Entity, InteractiveElement, IntoElement, ParentElement, Render, + StatefulInteractiveElement, Styled, Window, + component::{ + WindowExt, + checkbox::Checkbox, + input::{Input, InputEvent, InputState}, + }, + div, px, +}; + +use super::{ + Yumush, clickable, community_icon, community_name, composer::Composer, notify_error, palette, +}; + +pub struct Forward { + yumush: Entity, + selected: Vec, + filter: Entity, + keep_authors: bool, +} + +impl Forward { + fn new( + yumush: Entity, + selected: Vec, + window: &mut Window, + cx: &mut Context, + ) -> Self { + let filter = cx.new(|cx| { + let mut state = InputState::new(window, cx); + state.set_placeholder("Filter", window, cx); + state + }); + cx.subscribe_in(&filter, window, |_, _, event, _, cx| { + if matches!(event, InputEvent::Change) { + cx.notify(); + } + }) + .detach(); + + let keep_authors = selected.len() > 1; + Self { + yumush, + selected, + filter, + keep_authors, + } + } +} + +impl Render for Forward { + fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { + let palette = palette(cx); + let query = self.filter.read(cx).text().to_string().to_lowercase(); + let entity = cx.entity(); + let keep_authors = self.keep_authors; + let rows: Vec<_> = { + let yumush = self.yumush.read(cx); + yumush + .chat + .communities() + .iter() + .filter(|community| community_name(community).to_lowercase().contains(&query)) + .enumerate() + .map(|(index, community)| { + let community_id = community.id.clone(); + let selected = self.selected.clone(); + let forward_entity = self.yumush.clone(); + + clickable(("forward_to", index), palette, move |window, cx| { + let community_id = community_id.clone(); + let selected = selected.clone(); + forward_entity.update(cx, |yumush, cx| { + yumush.forward_to(selected, community_id, keep_authors, window, cx) + }); + }) + .h(px(28.)) + .px(px(8.)) + .flex() + .items_center() + .gap(px(8.)) + .rounded(px(6.)) + .child(community_icon( + palette, + community, + px(16.), + px(9.), + &yumush.chat.avatars, + )) + .child( + div() + .flex_1() + .min_w_0() + .truncate() + .child(community_name(community).to_string()), + ) + }) + .collect() + }; + + div() + .flex() + .flex_col() + .gap(px(10.)) + .child( + div() + .h(px(30.)) + .px(px(10.)) + .flex() + .items_center() + .rounded(px(8.)) + .border_1() + .border_color(palette.border) + .bg(palette.field) + .child( + Input::new(&self.filter) + .appearance(false) + .text_color(palette.text) + .flex_1() + .min_w_0(), + ), + ) + .child( + Checkbox::new("keep_authors") + .label("Keep authors") + .checked(keep_authors) + .on_click(move |_, _, cx| { + entity.update(cx, |this, cx| { + this.keep_authors = !this.keep_authors; + cx.notify(); + }); + }), + ) + .child( + div() + .id("forward_list") + .max_h(px(320.)) + .flex() + .flex_col() + .gap(px(1.)) + .overflow_y_scroll() + .children(rows), + ) + } +} + +impl Yumush { + pub(super) fn open_forward( + &mut self, + selected: Vec, + window: &mut Window, + cx: &mut Context, + ) { + if selected.is_empty() { + return; + } + let yumush = cx.entity(); + let forward = cx.new(|cx| Forward::new(yumush, selected, window, cx)); + + window.open_dialog(cx, move |dialog, _, _| { + dialog.title("Forward").w(px(360.)).child(forward.clone()) + }); + } + + pub(super) fn forward_to( + &mut self, + selected: Vec, + community_id: String, + snippet: bool, + window: &mut Window, + cx: &mut Context, + ) { + window.close_dialog(cx); + if matches!(self.chat.composer, Composer::Select { .. }) { + self.chat.composer = Composer::Compose { reply: None }; + } + + let ids: Vec = self + .chat + .messages + .iter() + .filter(|message| selected.contains(&message.id)) + .map(|message| message.id.clone()) + .collect(); + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + if let Err(error) = network.forward_messages(ids, &community_id, snippet).await { + notify_error(&this, cx, error); + } + }) + .detach(); + cx.notify(); + } +} diff --git a/crates/client/src/gui/media_view.rs b/crates/client/src/gui/media_view.rs new file mode 100644 index 0000000..dcb7910 --- /dev/null +++ b/crates/client/src/gui/media_view.rs @@ -0,0 +1,821 @@ +use std::{ + collections::{HashMap, HashSet}, + path::PathBuf, + sync::Arc, + time::Duration, +}; + +use common::{ + error::size_text, + model::{Attachment, AttachmentKind, Message}, +}; +use gpui_kit::{ + App, AppContext, Context, Entity, FontWeight, Image, ImageFormat, InteractiveElement, + IntoElement, ParentElement, PathPromptOptions, RenderImage, StatefulInteractiveElement, Styled, + Subscription, Task, Window, + assets::IconName, + component::{ + Icon, WindowExt, + notification::Notification, + slider::{Slider, SliderEvent, SliderState}, + }, + div, img, + prelude::FluentBuilder as _, + px, +}; + +use super::{Palette, Tooltip as _, Yumush, clickable, notify_error}; +use crate::{ + embed::{self, Embed, EmbedKind}, + media::Player, +}; + +const FRAME_TICK: Duration = Duration::from_millis(16); +const IMAGE_BOX: (f32, f32) = (400., 300.); +const VIDEO_BOX: (f32, f32) = (480., 270.); +const EMBED_IMAGE_BOX: (f32, f32) = (400., 225.); + +pub struct LoadedEmbed { + embed: Embed, + image: Option>, +} + +pub enum PlayState { + Loading, + Ready { + player: Player, + frame: Option>, + generation: u64, + seek: Entity, + _subscription: Subscription, + _tick: Task<()>, + }, +} + +pub struct Playing { + attachment_id: String, + state: PlayState, +} + +#[derive(Default)] +pub struct Media { + pub pending: Vec, + uploading: usize, + thumbnails: HashMap>, + embeds: HashMap, + requested: HashSet, + playing: Option, +} + +impl Media { + pub fn uploading(&self) -> bool { + self.uploading > 0 + } + + pub fn leave(&mut self) { + self.pending.clear(); + self.playing = None; + } +} + +fn image_format(bytes: &[u8]) -> Option { + match bytes { + [0x89, b'P', b'N', b'G', ..] => Some(ImageFormat::Png), + [0xFF, 0xD8, 0xFF, ..] => Some(ImageFormat::Jpeg), + [b'G', b'I', b'F', b'8', ..] => Some(ImageFormat::Gif), + [ + b'R', + b'I', + b'F', + b'F', + _, + _, + _, + _, + b'W', + b'E', + b'B', + b'P', + .., + ] => Some(ImageFormat::Webp), + _ => None, + } +} + +fn to_image(bytes: Vec) -> Option> { + image_format(&bytes).map(|format| Arc::new(Image::from_bytes(format, bytes))) +} + +fn fit(width: Option, height: Option, limit: (f32, f32)) -> (f32, f32) { + let (Some(width), Some(height)) = (width, height) else { + return limit; + }; + let (width, height) = (width.max(1) as f32, height.max(1) as f32); + let scale = (limit.0 / width).min(limit.1 / height).min(1.); + (width * scale, height * scale) +} + +fn cache_path(attachment: &Attachment) -> Option { + let directory = dirs::cache_dir()?.join("yumush").join("media"); + std::fs::create_dir_all(&directory).ok()?; + let extension = attachment + .name + .rsplit_once('.') + .map(|(_, extension)| format!(".{extension}")) + .unwrap_or_default(); + Some(directory.join(format!("{}{extension}", attachment.id))) +} + +fn time_text(time: Duration) -> String { + let seconds = time.as_secs(); + format!("{}:{:02}", seconds / 60, seconds % 60) +} + +fn to_render_image(frame: &crate::media::Frame) -> 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(); + for message in &self.chat.messages { + let forwarded = message.snippet.iter().flat_map(|snippet| &snippet.messages); + for item in forwarded.clone() { + if let Some(avatar_id) = &item.avatar_id { + avatars.push(avatar_id.clone()); + } + } + for attachment in message + .attachments + .iter() + .chain(forwarded.flat_map(|item| &item.attachments)) + { + if attachment.kind == AttachmentKind::Image + && self.chat.media.requested.insert(attachment.id.clone()) + { + thumbnails.push(attachment.id.clone()); + } + } + for url in embed::urls(&message.body) { + if self.chat.media.requested.insert(url.clone()) { + links.push(url); + } + } + } + + for avatar_id in avatars { + self.request_avatar(&avatar_id, cx); + } + + for attachment_id in thumbnails { + let network = self.network.clone(); + cx.spawn(async move |this, cx| { + let Ok(bytes) = network.download_attachment(&attachment_id, true).await else { + return; + }; + let _ = this.update(cx, |yumush, cx| { + if let Some(image) = to_image(bytes) { + yumush.chat.media.thumbnails.insert(attachment_id, image); + cx.notify(); + } + }); + }) + .detach(); + } + + for url in links { + cx.spawn(async move |this, cx| { + let fetched = cx + .background_executor() + .spawn({ + let url = url.clone(); + async move { embed::fetch(&url) } + }) + .await; + let Some(mut embed) = fetched else { + return; + }; + let image = embed.image.take().and_then(to_image); + let _ = this.update(cx, |yumush, cx| { + yumush + .chat + .media + .embeds + .insert(url, LoadedEmbed { embed, image }); + cx.notify(); + }); + }) + .detach(); + } + } + + pub(super) fn attach_files(&mut self, window: &mut Window, cx: &mut Context) { + let Some(community_id) = self.chat.selected_community_id.clone() else { + return; + }; + let picked = cx.prompt_for_paths(PathPromptOptions { + files: true, + directories: false, + multiple: true, + prompt: None, + }); + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + let Ok(Ok(Some(paths))) = picked.await else { + return; + }; + for path in paths { + let _ = this.update(cx, |yumush, cx| { + yumush.chat.media.uploading += 1; + cx.notify(); + }); + let result = network.upload_attachment(&community_id, path).await; + let _ = this.update(cx, |yumush, cx| { + yumush.chat.media.uploading -= 1; + if let Ok(attachment) = &result { + yumush.chat.media.pending.push(attachment.clone()); + } + cx.notify(); + }); + if let Err(error) = result { + notify_error(&this, cx, error); + } + } + }) + .detach(); + } + + fn remove_pending(&mut self, attachment_id: &str, cx: &mut Context) { + self.chat + .media + .pending + .retain(|attachment| attachment.id != attachment_id); + cx.notify(); + } + + fn fetch_file( + &self, + attachment: &Attachment, + cx: &mut Context, + ) -> Task> { + let network = self.network.clone(); + let attachment = attachment.clone(); + cx.spawn(async move |_, cx| { + let path = cache_path(&attachment).ok_or(common::error::Error::Server)?; + if std::fs::metadata(&path).is_ok_and(|meta| meta.len() == attachment.size) { + return Ok(path); + } + let bytes = network.download_attachment(&attachment.id, false).await?; + cx.background_executor() + .spawn({ + let path = path.clone(); + async move { std::fs::write(&path, bytes) } + }) + .await + .map_err(|_| common::error::Error::Server)?; + Ok(path) + }) + } + + fn open_attachment( + &self, + attachment: &Attachment, + window: &mut Window, + cx: &mut Context, + ) { + let fetched = self.fetch_file(attachment, cx); + cx.spawn_in(window, async move |this, cx| match fetched.await { + Ok(path) => { + let _ = this.update(cx, |_, cx| cx.open_with_system(&path)); + } + Err(error) => notify_error(&this, cx, error), + }) + .detach(); + } + + fn save_attachment( + &self, + attachment: &Attachment, + window: &mut Window, + cx: &mut Context, + ) { + let directory = dirs::download_dir().unwrap_or_else(std::env::temp_dir); + let target = cx.prompt_for_new_path(&directory, Some(&attachment.name)); + let fetched = self.fetch_file(attachment, cx); + cx.spawn_in(window, async move |this, cx| { + let Ok(Ok(Some(target))) = target.await else { + return; + }; + match fetched.await { + Ok(path) => { + let _ = std::fs::copy(path, target); + } + Err(error) => notify_error(&this, cx, error), + } + }) + .detach(); + } + + 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 { + player.toggle(); + } + cx.notify(); + return; + } + self.stop_playing(cx); + self.chat.media.playing = Some(Playing { + attachment_id: attachment.id.clone(), + state: PlayState::Loading, + }); + cx.notify(); + + let fetched = self.fetch_file(attachment, cx); + let choice = self.settings.voice.choice.clone(); + let attachment_id = attachment.id.clone(); + cx.spawn_in(window, async move |this, cx| { + let opened = match fetched.await { + Ok(path) => cx + .background_executor() + .spawn(async move { Player::open(&path, choice) }) + .await + .map_err(|error| error.to_string()), + 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 { + return; + } + match opened { + Ok(player) => yumush.start_player(attachment_id, player, window, cx), + Err(error) => { + yumush.chat.media.playing = None; + window.push_notification(Notification::error(error), cx); + } + } + cx.notify(); + }); + }) + .detach(); + } + + fn start_player( + &mut self, + attachment_id: String, + player: Player, + window: &mut Window, + cx: &mut Context, + ) { + let duration = player.info().duration.unwrap_or_default().as_secs_f32(); + let seek = cx.new(|_| { + SliderState::new() + .min(0.) + .max(duration.max(0.1)) + .default_value(0.) + }); + let subscription = cx.subscribe(&seek, |yumush, _, event: &SliderEvent, cx| { + let SliderEvent::Release(value) = event else { + return; + }; + if let Some(Playing { + state: PlayState::Ready { player, .. }, + .. + }) = &yumush.chat.media.playing + { + player.seek(Duration::from_secs_f32(value.start().max(0.))); + } + cx.notify(); + }); + let tick = cx.spawn_in(window, async move |this, cx| { + loop { + cx.background_executor().timer(FRAME_TICK).await; + if this + .update_in(cx, |yumush, window, cx| yumush.tick_player(window, cx)) + .is_err() + { + break; + } + } + }); + player.play(); + self.chat.media.playing = Some(Playing { + attachment_id, + state: PlayState::Ready { + player, + frame: None, + generation: 0, + seek, + _subscription: subscription, + _tick: tick, + }, + }); + } + + fn tick_player(&mut self, window: &mut Window, cx: &mut Context) { + let Some(Playing { + state: + PlayState::Ready { + player, + frame, + generation, + seek, + .. + }, + .. + }) = &mut self.chat.media.playing + else { + return; + }; + if !player.playing() { + return; + } + if let Some(next) = player.frame() + && 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 position = player.position().as_secs_f32(); + seek.update(cx, |state, cx| state.set_value(position, window, cx)); + 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() + { + cx.drop_image(frame, None); + } + } +} + +pub fn attachments( + attachments: &[Attachment], + media: &Media, + entity: &Entity, + palette: Palette, +) -> Option { + if attachments.is_empty() { + return None; + } + Some( + div().flex().flex_col().gap(px(6.)).children( + attachments + .iter() + .map(|attachment| attachment_view(attachment, media, entity, palette)), + ), + ) +} + +fn attachment_view( + attachment: &Attachment, + media: &Media, + entity: &Entity, + palette: Palette, +) -> gpui_kit::AnyElement { + match attachment.kind { + AttachmentKind::Image => image_view(attachment, media, entity, palette).into_any_element(), + AttachmentKind::Video | AttachmentKind::Audio => { + player_view(attachment, media, entity, palette).into_any_element() + } + AttachmentKind::File => file_view(attachment, entity, palette).into_any_element(), + } +} + +fn on_attachment( + entity: &Entity, + attachment: &Attachment, + action: fn(&mut Yumush, &Attachment, &mut Window, &mut Context), +) -> impl Fn(&mut Window, &mut App) + 'static { + let entity = entity.clone(); + let attachment = attachment.clone(); + move |window, cx| { + entity.update(cx, |yumush, cx| action(yumush, &attachment, window, cx)); + } +} + +fn image_view( + attachment: &Attachment, + media: &Media, + entity: &Entity, + palette: Palette, +) -> 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) + }); + div() + .id(format!("attachment_{}", attachment.id)) + .w(px(width)) + .h(px(height)) + .rounded(px(8.)) + .overflow_hidden() + .bg(palette.field) + .cursor_pointer() + .on_click(move |_, window, cx| open(window, cx)) + .children( + media + .thumbnails + .get(&attachment.id) + .map(|image| img(image.clone()).size_full()), + ) +} + +fn card(palette: Palette) -> gpui_kit::Div { + div() + .max_w(px(VIDEO_BOX.0)) + .flex() + .items_center() + .gap(px(10.)) + .px(px(12.)) + .py(px(10.)) + .rounded(px(8.)) + .border_1() + .border_color(palette.border) + .bg(palette.panel) +} + +fn name_block(attachment: &Attachment, detail: String, palette: Palette) -> impl IntoElement { + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .child( + div() + .truncate() + .text_color(palette.text) + .child(attachment.name.clone()), + ) + .child( + div() + .text_size(px(12.)) + .text_color(palette.muted) + .child(detail), + ) +} + +fn icon_button( + id: String, + icon: IconName, + tip: &'static str, + palette: Palette, + on_click: impl Fn(&mut Window, &mut App) + 'static, +) -> impl IntoElement { + clickable(id, palette, on_click) + .tip(tip) + .size(px(32.)) + .flex_shrink_0() + .flex() + .items_center() + .justify_center() + .rounded(px(6.)) + .text_color(palette.text) + .child(Icon::new(icon).w(px(16.)).h(px(16.))) +} + +fn file_view( + attachment: &Attachment, + entity: &Entity, + palette: Palette, +) -> impl IntoElement { + card(palette) + .child( + Icon::new(IconName::File) + .w(px(20.)) + .h(px(20.)) + .text_color(palette.muted), + ) + .child(name_block(attachment, size_text(attachment.size), palette)) + .child(icon_button( + format!("save_{}", attachment.id), + IconName::ArrowDown, + "Save", + palette, + on_attachment(entity, attachment, |yumush, attachment, window, cx| { + yumush.save_attachment(attachment, window, cx) + }), + )) +} + +fn player_view( + attachment: &Attachment, + media: &Media, + entity: &Entity, + palette: Palette, +) -> 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 toggle = icon_button( + format!("play_{}", attachment.id), + if playing { + IconName::Pause + } else { + IconName::Play + }, + if playing { "Pause" } else { "Play" }, + palette, + on_attachment(entity, attachment, |yumush, attachment, window, cx| { + yumush.play(attachment, window, cx) + }), + ); + let detail = match state { + Some(PlayState::Loading) => "…".to_string(), + Some(PlayState::Ready { player, .. }) => format!( + "{} / {}", + time_text(player.position()), + time_text(player.info().duration.unwrap_or_default()) + ), + None => size_text(attachment.size), + }; + let controls = card(palette) + .child(toggle) + .child(name_block(attachment, detail, palette)) + .when_some( + match state { + Some(PlayState::Ready { seek, .. }) => Some(seek), + _ => None, + }, + |this, seek| this.child(div().w(px(140.)).child(Slider::new(seek))), + ); + + let video = match state { + Some(PlayState::Ready { player, frame, .. }) => player + .info() + .video + .map(|(width, height)| (frame, width, height)), + _ => None, + }; + + div() + .flex() + .flex_col() + .gap(px(4.)) + .when_some(video, |this, (frame, width, height)| { + let (width, height) = fit(Some(width), Some(height), VIDEO_BOX); + this.child( + div() + .w(px(width)) + .h(px(height)) + .rounded(px(8.)) + .overflow_hidden() + .bg(gpui_kit::black()) + .children(frame.clone().map(|frame| img(frame).size_full())), + ) + }) + .child(controls) +} + +pub fn embeds(message: &Message, media: &Media, palette: Palette) -> Vec { + embed::urls(&message.body) + .into_iter() + .filter_map(|url| media.embeds.get(&url)) + .map(|loaded| embed_view(loaded, palette)) + .collect() +} + +fn embed_view(loaded: &LoadedEmbed, palette: Palette) -> impl IntoElement { + let embed = &loaded.embed; + let url = embed.url.clone(); + let image = loaded.image.clone().map(|image| { + div() + .max_w(px(EMBED_IMAGE_BOX.0)) + .max_h(px(EMBED_IMAGE_BOX.1)) + .rounded(px(6.)) + .overflow_hidden() + .child( + img(image) + .max_w(px(EMBED_IMAGE_BOX.0)) + .max_h(px(EMBED_IMAGE_BOX.1)), + ) + }); + + if embed.kind == EmbedKind::Image { + return div().children(image); + } + + div() + .max_w(px(VIDEO_BOX.0)) + .flex() + .flex_col() + .gap(px(4.)) + .pl(px(12.)) + .pr(px(12.)) + .py(px(10.)) + .rounded(px(6.)) + .border_l_2() + .border_color(palette.border) + .bg(palette.panel) + .children(embed.site.clone().map(|site| { + div() + .text_size(px(12.)) + .text_color(palette.muted) + .child(site) + })) + .children(embed.title.clone().map(|title| { + div() + .id(format!("embed_{url}")) + .font_weight(FontWeight::SEMIBOLD) + .text_color(palette.text) + .cursor_pointer() + .hover(|style| style.underline()) + .on_click(move |_, _, cx| cx.open_url(&url)) + .child(title) + })) + .children(embed.description.clone().map(|description| { + div() + .text_size(px(13.)) + .text_color(palette.body) + .line_clamp(3) + .child(description) + })) + .children(image) +} + +pub fn pending_row( + media: &Media, + entity: &Entity, + palette: Palette, +) -> Option { + if media.pending.is_empty() && !media.uploading() { + return None; + } + Some( + div() + .flex() + .flex_wrap() + .gap(px(6.)) + .pb(px(8.)) + .children(media.pending.iter().map(|attachment| { + let entity = entity.clone(); + let attachment_id = attachment.id.clone(); + div() + .flex() + .items_center() + .gap(px(6.)) + .pl(px(10.)) + .pr(px(4.)) + .py(px(4.)) + .rounded(px(6.)) + .bg(palette.hover) + .text_size(px(12.)) + .child( + div() + .max_w(px(180.)) + .truncate() + .child(attachment.name.clone()), + ) + .child( + clickable( + format!("unattach_{}", attachment.id), + palette, + move |_, cx| { + entity.update(cx, |yumush, cx| { + yumush.remove_pending(&attachment_id, cx) + }) + }, + ) + .tip("Remove") + .size(px(18.)) + .flex() + .items_center() + .justify_center() + .rounded(px(4.)) + .child(Icon::new(IconName::Close).w(px(12.)).h(px(12.))), + ) + })) + .when(media.uploading(), |this| { + this.child( + div() + .px(px(10.)) + .py(px(4.)) + .text_size(px(12.)) + .text_color(palette.muted) + .child("…"), + ) + }), + ) +} diff --git a/crates/client/src/gui/message_actions.rs b/crates/client/src/gui/message_actions.rs new file mode 100644 index 0000000..f9c592d --- /dev/null +++ b/crates/client/src/gui/message_actions.rs @@ -0,0 +1,170 @@ +use common::model::{Message, User}; +use gpui_kit::{ + Context, Entity, FontWeight, InteractiveElement, IntoElement, ParentElement, Styled, Window, + assets::IconName, component::Icon, div, px, +}; + +use super::{Palette, Tooltip as _, Yumush, avatar, chat::Chat, clickable}; + +pub fn quote_text(body: &str, attachments: usize) -> String { + if body.is_empty() { + format!("{attachments} attachments") + } else { + body.to_string() + } +} + +pub fn quote_line(message: &Message, chat: &Chat, palette: Palette) -> Option { + let quote = message.reply.as_ref()?; + let author = chat.author("e.user_id); + + Some( + div() + .flex() + .items_center() + .gap(px(6.)) + .pl(px(8.)) + .border_l_2() + .border_color(palette.accent.opacity(0.6)) + .text_size(px(12.)) + .text_color(palette.muted) + .children(author.map(|user| avatar(palette, user, px(14.), px(7.), &chat.avatars))) + .children(author.map(|user| { + div() + .flex_shrink_0() + .font_weight(FontWeight::SEMIBOLD) + .text_color(palette.tinted(&user.id)) + .child(user.username.clone()) + })) + .child( + div() + .flex_1() + .min_w_0() + .truncate() + .child(quote_text("e.body, quote.attachments)), + ), + ) +} + +pub fn selection_mark(selected: bool, palette: Palette) -> impl IntoElement { + div() + .mt(px(3.)) + .size(px(16.)) + .flex_shrink_0() + .flex() + .items_center() + .justify_center() + .rounded_full() + .border_1() + .border_color(if selected { + palette.accent + } else { + palette.muted + }) + .bg(if selected { + palette.accent + } else { + palette.field + }) + .children(selected.then(|| { + Icon::new(IconName::Check) + .w(px(10.)) + .h(px(10.)) + .text_color(palette.on_accent) + })) +} + +pub fn actions( + message: &Message, + chat: &Chat, + me: Option<&User>, + entity: &Entity, + palette: Palette, + group: String, +) -> 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(); + let deletable = me.is_some_and(|me| chat.can_delete(message, me)); + let id = message.id.as_str(); + + div() + .flex() + .items_center() + .gap(px(2.)) + .p(px(2.)) + .rounded(px(8.)) + .border_1() + .border_color(palette.border) + .bg(palette.panel) + .invisible() + .group_hover(group, |style| style.visible()) + .child(action( + entity, + palette, + id, + "Reply", + IconName::Reply, + |yumush, id, window, cx| yumush.reply(id, window, cx), + )) + .children(editable.then(|| { + action( + entity, + palette, + id, + "Edit", + IconName::Pencil, + |yumush, id, window, cx| yumush.edit(id, window, cx), + ) + })) + .child(action( + entity, + palette, + id, + "Forward", + IconName::Forward, + |yumush, id, window, cx| yumush.open_forward(vec![id], window, cx), + )) + .child(action( + entity, + palette, + id, + "Select", + IconName::ListChecks, + |yumush, id, window, cx| yumush.start_select(id, window, cx), + )) + .children(deletable.then(|| { + action( + entity, + palette, + id, + "Delete", + IconName::Trash, + |yumush, id, window, cx| yumush.delete_message(&id, window, cx), + ) + })) +} + +fn action( + entity: &Entity, + palette: Palette, + message_id: &str, + tip: &'static str, + icon: IconName, + run: fn(&mut Yumush, String, &mut Window, &mut Context), +) -> impl IntoElement { + let entity = entity.clone(); + let message_id = message_id.to_string(); + + clickable(format!("{tip}_{message_id}"), palette, move |window, cx| { + let message_id = message_id.clone(); + entity.update(cx, |yumush, cx| run(yumush, message_id, window, cx)); + }) + .tip(tip) + .size(px(24.)) + .flex() + .items_center() + .justify_center() + .rounded(px(6.)) + .text_color(palette.muted) + .child(Icon::new(icon).w(px(14.)).h(px(14.))) +} diff --git a/crates/client/src/gui/profile.rs b/crates/client/src/gui/profile.rs new file mode 100644 index 0000000..17b93cf --- /dev/null +++ b/crates/client/src/gui/profile.rs @@ -0,0 +1,506 @@ +use std::{collections::HashMap, sync::Arc}; + +use common::{ + model::{Rank, User}, + permission, +}; +use gpui_kit::{ + Anchor, AnyElement, App, Context, Div, ElementId, Entity, FontWeight, Hsla, Image, IntoElement, + ParentElement, SharedString, Styled, Window, + assets::IconName, + component::{ + Icon, WindowExt, + popover::{Popover, PopoverState}, + }, + div, px, +}; + +use super::chat::View; +use super::social::Relation; +use super::{ + Palette, Trigger, Yumush, avatar, clickable, id_time, input_dialog, palette, rank_tag, +}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Removal { + Kick, + Ban, +} + +impl Removal { + fn title(self) -> &'static str { + match self { + Removal::Kick => "Kick", + Removal::Ban => "Ban", + } + } +} + +pub(super) fn profile_popover( + id: impl Into, + anchor: Anchor, + user: &User, + entity: &Entity, + trigger: impl IntoElement, +) -> Popover { + let user = user.clone(); + let entity = entity.clone(); + let notify_entity = entity.clone(); + + Popover::new(id) + .anchor(anchor) + .appearance(false) + .on_open_change(move |_, _, cx| notify_entity.update(cx, |_, cx| cx.notify())) + .trigger(Trigger::new(trigger)) + .content(move |_, _, cx| { + let yumush = entity.read(cx); + let card = Card { + viewer: yumush.user.clone(), + actor: yumush.actor_rank(), + target: yumush.chat.rank_of(&user), + relation: yumush.relation(&user.id), + confirming: yumush.chat.pending_user_delete.as_deref() == Some(user.id.as_str()), + others: yumush + .accounts + .others() + .map(|account| (account.user_id.clone(), account.username.clone())) + .collect(), + user: user.clone(), + }; + + card.render(&entity, cx.entity(), palette(cx), &yumush.chat.avatars) + }) +} + +struct Card { + user: User, + viewer: Option, + actor: Option, + target: Option, + relation: Relation, + confirming: bool, + others: Vec<(String, String)>, +} + +impl Card { + fn social_rows( + &self, + entity: &Entity, + popover: &Entity, + palette: Palette, + ) -> Vec { + let user_id = self.user.id.clone(); + let message_id = user_id.clone(); + let mut rows = vec![ + menu_row( + "profile_message", + "Message", + IconName::MessageSquare, + palette.text, + palette, + yumush_action(entity, popover, move |yumush, window, cx| { + yumush.open_direct(message_id.clone(), window, cx) + }), + ) + .into_any_element(), + ]; + + if let Some((label, icon)) = self.relation.action() { + let relation = self.relation; + rows.push( + menu_row( + "profile_friend", + label, + icon, + palette.text, + palette, + yumush_action(entity, popover, move |yumush, window, cx| { + yumush.friend_action(relation, user_id.clone(), window, cx) + }), + ) + .into_any_element(), + ); + } + + rows + } + + fn render( + self, + entity: &Entity, + popover: Entity, + palette: Palette, + avatars: &HashMap>, + ) -> Div { + let is_self = self + .viewer + .as_ref() + .is_some_and(|viewer| viewer.id == self.user.id); + let rows = if is_self { + self_rows(&self.others, entity, &popover, palette) + } else { + let mut rows = self.social_rows(entity, &popover, palette); + rows.extend(self.moderation_rows(entity, &popover, palette)); + rows + }; + let divider = (!rows.is_empty()).then(|| div().h(px(1.)).my(px(4.)).bg(palette.border)); + + div() + .w(px(260.)) + .p(px(16.)) + .flex() + .flex_col() + .gap(px(10.)) + .rounded(px(8.)) + .border_1() + .border_color(palette.border) + .bg(palette.panel) + .child(avatar(palette, &self.user, px(48.), px(18.), avatars)) + .child( + div() + .flex() + .items_center() + .gap(px(6.)) + .child( + div() + .text_size(px(15.)) + .font_weight(FontWeight::SEMIBOLD) + .child(self.user.username.clone()), + ) + .children(rank_tag(self.target, palette)), + ) + .children((!self.user.status.is_empty()).then(|| { + div() + .text_size(px(12.)) + .text_color(palette.muted) + .child(self.user.status.clone()) + })) + .child( + div() + .text_size(px(12.)) + .text_color(palette.muted) + .child(format!("Joined {}", id_time(&self.user.id, "%b %-d, %Y"))), + ) + .children(divider) + .children(rows) + } + + fn moderation_rows( + &self, + entity: &Entity, + popover: &Entity, + palette: Palette, + ) -> Vec { + let actor = self.actor; + let target = self.target; + let user_id = self.user.id.clone(); + let mut rows = Vec::new(); + + for (rank, label) in [ + (Rank::Member, "Make member"), + (Rank::Moderator, "Make moderator"), + (Rank::Admin, "Make admin"), + ] { + if target != Some(rank) && permission::can_set_rank(actor, target, rank) { + let user_id = user_id.clone(); + rows.push( + menu_row( + label, + label, + IconName::Shield, + palette.text, + palette, + yumush_action(entity, popover, move |yumush, window, cx| { + yumush.set_member_rank(&user_id, rank, window, cx) + }), + ) + .into_any_element(), + ); + } + } + + if permission::can_moderate(actor, target) { + let kick_id = user_id.clone(); + let ban_id = user_id.clone(); + rows.push( + menu_row( + "kick", + "Kick", + IconName::Close, + palette.danger, + palette, + yumush_action(entity, popover, move |yumush, window, cx| { + yumush.open_removal(kick_id.clone(), Removal::Kick, window, cx) + }), + ) + .into_any_element(), + ); + rows.push( + menu_row( + "ban", + "Ban", + IconName::Ban, + palette.danger, + palette, + yumush_action(entity, popover, move |yumush, window, cx| { + yumush.open_removal(ban_id.clone(), Removal::Ban, 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 { + let label = if self.confirming { + "Confirm" + } else { + "Delete user" + }; + + rows.push( + menu_row( + "delete_user", + label, + IconName::Trash, + palette.danger, + palette, + delete_user_action(&user_id, self.confirming, entity, popover), + ) + .into_any_element(), + ); + } + + rows + } +} + +fn self_rows( + others: &[(String, String)], + entity: &Entity, + popover: &Entity, + palette: Palette, +) -> Vec { + let mut rows: Vec = others + .iter() + .map(|(user_id, username)| { + let user_id = user_id.clone(); + menu_row( + format!("switch_{user_id}"), + username.clone(), + IconName::ArrowLeft, + palette.text, + palette, + yumush_action(entity, popover, move |yumush, window, cx| { + yumush.switch_account(user_id.clone(), window, cx) + }), + ) + .into_any_element() + }) + .collect(); + rows.push( + menu_row( + "profile_add_account", + "Add account", + IconName::UserPlus, + palette.text, + palette, + yumush_action(entity, popover, |yumush, window, cx| { + yumush.add_account(window, cx) + }), + ) + .into_any_element(), + ); + rows.extend([ + menu_row( + "profile_settings", + "Settings", + IconName::Settings, + palette.text, + palette, + yumush_action(entity, popover, |yumush, window, cx| { + yumush.show_view(View::Settings, window, cx) + }), + ) + .into_any_element(), + menu_row( + "profile_logout", + "Log out", + IconName::LogOut, + palette.danger, + palette, + yumush_action(entity, popover, |yumush, window, cx| { + yumush.logout(window, cx) + }), + ) + .into_any_element(), + ]); + rows +} + +fn yumush_action( + entity: &Entity, + popover: &Entity, + run: impl Fn(&mut Yumush, &mut Window, &mut Context) + 'static, +) -> impl Fn(&mut Window, &mut App) + 'static { + let entity = entity.clone(); + let popover = popover.clone(); + + move |window, cx| { + popover.update(cx, |state, cx| state.dismiss(window, cx)); + entity.update(cx, |yumush, cx| run(yumush, window, cx)); + } +} + +fn delete_user_action( + user_id: &str, + confirming: bool, + entity: &Entity, + popover: &Entity, +) -> impl Fn(&mut Window, &mut App) + 'static { + let user_id = user_id.to_string(); + let entity = entity.clone(); + let popover = popover.clone(); + + move |window, cx| { + if confirming { + popover.update(cx, |state, cx| state.dismiss(window, cx)); + entity.update(cx, |yumush, cx| { + yumush.delete_member_account(&user_id, window, cx) + }); + } else { + entity.update(cx, |yumush, cx| yumush.request_member_delete(&user_id, cx)); + } + } +} + +fn menu_row( + id: impl Into, + label: impl Into, + icon: IconName, + color: Hsla, + palette: Palette, + on_click: impl Fn(&mut Window, &mut App) + 'static, +) -> impl IntoElement { + clickable(id, palette, on_click) + .h(px(30.)) + .px(px(8.)) + .flex() + .items_center() + .gap(px(8.)) + .rounded(px(6.)) + .text_color(color) + .child(Icon::new(icon).w(px(14.)).h(px(14.))) + .child(label.into()) +} + +impl Yumush { + fn open_removal( + &self, + user_id: String, + removal: Removal, + window: &mut Window, + cx: &mut Context, + ) { + let Some(community_id) = self.chat.selected_community_id.clone() else { + return; + }; + input_dialog( + removal.title(), + removal.title(), + "Reason (optional)", + window, + cx, + move |this, text, window, cx| { + let reason = text.trim().to_string(); + let reason = (!reason.is_empty()).then_some(reason); + this.remove_member(&community_id, &user_id, removal, reason, window, cx); + }, + ); + } + + fn remove_member( + &self, + community_id: &str, + user_id: &str, + removal: Removal, + reason: Option, + window: &mut Window, + cx: &mut Context, + ) { + let network = self.network.clone(); + let community_id = community_id.to_string(); + let user_id = user_id.to_string(); + + cx.spawn_in(window, async move |this, cx| { + let reason = reason.as_deref(); + let result = match removal { + Removal::Kick => network.kick(&community_id, &user_id, reason).await, + Removal::Ban => network.ban(&community_id, &user_id, reason).await, + }; + match result { + Ok(()) => { + let _ = this.update_in(cx, |yumush, window, cx| { + window.close_dialog(cx); + yumush.load_bans(window, cx); + }); + } + Err(error) => super::notify_error(&this, cx, error), + } + }) + .detach(); + } + + pub(super) fn set_member_rank( + &self, + user_id: &str, + rank: Rank, + window: &mut Window, + cx: &mut Context, + ) { + let Some(community_id) = self.chat.selected_community_id.clone() else { + return; + }; + let network = self.network.clone(); + let user_id = user_id.to_string(); + + cx.spawn_in(window, async move |this, cx| { + if let Err(error) = network.set_rank(&community_id, &user_id, rank).await { + super::notify_error(&this, cx, error); + } + }) + .detach(); + } + + pub(super) fn request_member_delete(&mut self, user_id: &str, cx: &mut Context) { + self.chat.pending_user_delete = Some(user_id.to_string()); + cx.notify(); + } + + pub(super) fn delete_member_account( + &mut self, + user_id: &str, + window: &mut Window, + cx: &mut Context, + ) { + self.chat.pending_user_delete = None; + let network = self.network.clone(); + let user_id = user_id.to_string(); + + cx.spawn_in(window, async move |this, cx| { + match network.delete_user(&user_id).await { + Ok(()) => { + let _ = this.update(cx, |yumush, cx| { + yumush.chat.remove_member(&user_id); + cx.notify(); + }); + } + Err(error) => super::notify_error(&this, cx, error), + } + }) + .detach(); + } +} diff --git a/crates/client/src/gui/settings_page.rs b/crates/client/src/gui/settings_page.rs new file mode 100644 index 0000000..866ee3f --- /dev/null +++ b/crates/client/src/gui/settings_page.rs @@ -0,0 +1,588 @@ +use std::path::Path; + +use common::{error::Error, model::User}; +use gpui_kit::{ + AnyElement, App, Context, Div, Entity, FontWeight, Hsla, InteractiveElement, IntoElement, + ParentElement, PathPromptOptions, Stateful, StatefulInteractiveElement, Styled, Window, + assets::IconName, + component::{Icon, input::InputState}, + div, + prelude::FluentBuilder as _, + px, +}; + +use super::{ + Palette, Tooltip as _, Yumush, auth::field, avatar, chat::DeleteStep, chat::View, clickable, + notify_error, primary_button, +}; +use crate::settings::{self, ThemeChoice}; + +const THEMES: [(ThemeChoice, &str); 4] = [ + (ThemeChoice::System, "System"), + (ThemeChoice::Light, "Light"), + (ThemeChoice::Dark, "Dark"), + (ThemeChoice::Black, "Black"), +]; + +impl Yumush { + pub(super) fn settings_page( + &self, + entity: &Entity, + palette: Palette, + cx: &App, + ) -> impl IntoElement { + let mut sections = Vec::new(); + if let Some(user) = self.user.as_ref() { + sections.push( + picture_card( + Picture { + id: "avatar_picker", + image: avatar(palette, user, px(64.), px(24.), &self.chat.avatars), + title: user.username.clone(), + subtitle: user.status.clone(), + removable: user.avatar_id.is_some(), + upload: Yumush::upload_avatar, + remove: Yumush::remove_avatar, + }, + entity, + palette, + ) + .into_any_element(), + ); + sections.push( + section( + "Account", + palette, + vec![ + text_row( + Editable { + id: "save_username_button", + label: "Username", + input: &self.chat.username_input, + current: &user.username, + save: Yumush::save_username, + }, + entity, + palette, + cx, + ), + text_row( + Editable { + id: "save_status_button", + label: "Status", + input: &self.chat.status_input, + current: &user.status, + save: Yumush::save_status, + }, + entity, + palette, + cx, + ), + ], + ) + .into_any_element(), + ); + } + sections.push( + section("Voice", palette, self.voice_rows(entity, palette, cx)).into_any_element(), + ); + sections.push( + section( + "Appearance", + palette, + vec![row( + "Theme", + segmented( + THEMES, + self.settings.theme, + entity, + palette, + Yumush::set_theme, + ), + )], + ) + .into_any_element(), + ); + if self.user.is_some() { + sections.push( + danger_section( + palette, + vec![row( + "Delete account", + delete_control( + "delete_account_button", + self.chat.delete_step, + entity, + palette, + Yumush::delete_account, + ), + )], + ) + .into_any_element(), + ); + } + + page("settings_scroll", entity, palette, "Settings", sections) + } + + pub(super) fn set_user(&mut self, user: User, cx: &mut Context) { + self.chat.update_member(&user); + self.request_user_avatar(&user, cx); + self.user = Some(user); + cx.notify(); + } + + pub(super) fn save_username(&mut self, window: &mut Window, cx: &mut Context) { + let username = self.chat.username_input.read(cx).text().to_string(); + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + match network.update_user(&username).await { + Ok(user) => { + let _ = this.update(cx, |yumush, cx| yumush.set_user(user, cx)); + } + Err(error) => notify_error(&this, cx, error), + } + }) + .detach(); + } + + 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(); + + cx.spawn_in(window, async move |this, cx| { + match network.update_status(&status).await { + Ok(user) => { + let _ = this.update(cx, |yumush, cx| yumush.set_user(user, cx)); + } + Err(error) => notify_error(&this, cx, error), + } + }) + .detach(); + } + + pub(super) fn upload_avatar(&mut self, window: &mut Window, cx: &mut Context) { + let picked = cx.prompt_for_paths(PathPromptOptions { + files: true, + directories: false, + multiple: false, + prompt: None, + }); + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + let Ok(Ok(Some(paths))) = picked.await else { + return; + }; + let Some(path) = paths.into_iter().next() else { + return; + }; + + let prepared = cx + .background_executor() + .spawn(async move { read_avatar_file(&path) }) + .await; + let result = match prepared { + Ok(bytes) => network.update_avatar(bytes).await, + Err(error) => Err(error), + }; + + match result { + Ok(user) => { + let _ = this.update(cx, |yumush, cx| yumush.set_user(user, cx)); + } + Err(error) => notify_error(&this, cx, error), + } + }) + .detach(); + } + + pub(super) fn remove_avatar(&mut self, window: &mut Window, cx: &mut Context) { + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + match network.remove_avatar().await { + Ok(user) => { + let _ = this.update(cx, |yumush, cx| yumush.set_user(user, cx)); + } + Err(error) => notify_error(&this, cx, error), + } + }) + .detach(); + } + + pub(super) fn delete_account(&mut self, window: &mut Window, cx: &mut Context) { + match self.chat.delete_step { + DeleteStep::Idle => { + self.chat.delete_step = DeleteStep::Confirm; + cx.notify(); + } + DeleteStep::Confirm => { + let Some(user_id) = self.user.as_ref().map(|user| user.id.clone()) else { + return; + }; + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + match network.delete_user(&user_id).await { + Ok(()) => { + let _ = this.update_in(cx, |yumush, window, cx| { + yumush.end_session(window, cx); + }); + } + Err(error) => notify_error(&this, cx, error), + } + }) + .detach(); + } + } + } + + pub(super) fn set_theme(&mut self, theme: ThemeChoice, cx: &mut Context) { + self.settings.theme = theme; + settings::apply(theme, cx); + self.commit_settings(cx); + } + + pub(super) fn commit_settings(&mut self, cx: &mut Context) { + settings::save(&self.settings); + self.network.set_voice_settings(self.settings.voice.clone()); + cx.notify(); + } +} + +pub(super) fn header( + entity: &Entity, + palette: Palette, + title: impl IntoElement, +) -> impl IntoElement { + let entity = entity.clone(); + + div() + .h(px(44.)) + .px(px(12.)) + .flex() + .items_center() + .gap(px(8.)) + .border_b_1() + .border_color(palette.border) + .child( + clickable("settings_back_button", palette, move |window, cx| { + entity.update(cx, |yumush, cx| yumush.show_view(View::Chat, window, cx)); + }) + .tip("Back") + .size(px(26.)) + .flex() + .items_center() + .justify_center() + .rounded(px(6.)) + .text_color(palette.muted) + .child(Icon::new(IconName::ArrowLeft).w(px(14.)).h(px(14.))), + ) + .child(div().font_weight(FontWeight::SEMIBOLD).child(title)) +} + +pub(super) fn page( + id: &'static str, + entity: &Entity, + palette: Palette, + title: impl IntoElement, + sections: Vec, +) -> impl IntoElement { + div() + .flex_1() + .min_h_0() + .flex() + .flex_col() + .child(header(entity, palette, title)) + .child( + div() + .id(id) + .flex_1() + .min_h_0() + .overflow_y_scroll() + .flex() + .justify_center() + .child( + div() + .w_full() + .max_w(px(600.)) + .px(px(24.)) + .py(px(32.)) + .flex() + .flex_col() + .gap(px(28.)) + .children(sections), + ), + ) +} + +pub(super) fn section(title: &'static str, palette: Palette, rows: Vec
) -> impl IntoElement { + card(title, palette.muted, palette.border, palette, rows) +} + +pub(super) fn danger_section(palette: Palette, rows: Vec
) -> impl IntoElement { + card( + "Danger zone", + palette.danger, + palette.danger.opacity(0.35), + palette, + rows, + ) +} + +fn card( + title: &'static str, + title_color: Hsla, + border: Hsla, + palette: Palette, + rows: Vec
, +) -> impl IntoElement { + div() + .flex() + .flex_col() + .gap(px(8.)) + .child( + div() + .px(px(2.)) + .text_size(px(12.)) + .font_weight(FontWeight::MEDIUM) + .text_color(title_color) + .child(title), + ) + .child( + div() + .flex() + .flex_col() + .rounded(px(10.)) + .border_1() + .border_color(border) + .bg(palette.panel) + .children(rows.into_iter().enumerate().map(|(index, row)| { + row.when(index > 0, |row| { + row.border_t_1().border_color(palette.border) + }) + })), + ) +} + +pub(super) struct Editable<'a> { + pub id: &'static str, + pub label: &'static str, + pub input: &'a Entity, + pub current: &'a str, + pub save: fn(&mut Yumush, &mut Window, &mut Context), +} + +pub(super) fn text_row( + editable: Editable, + entity: &Entity, + palette: Palette, + cx: &App, +) -> Div { + let dirty = editable.input.read(cx).text() != editable.current; + let entity = entity.clone(); + let save = editable.save; + + div() + .p(px(12.)) + .flex() + .flex_col() + .gap(px(6.)) + .child( + div() + .text_size(px(12.)) + .text_color(palette.muted) + .child(editable.label), + ) + .child( + div() + .flex() + .items_center() + .gap(px(8.)) + .child(field(palette, editable.input).flex_1()) + .when(dirty, |this| { + this.child( + primary_button(editable.id, palette, move |window, cx| { + entity.update(cx, |yumush, cx| save(yumush, window, cx)); + }) + .h(px(32.)) + .px(px(14.)) + .flex() + .items_center() + .rounded(px(8.)) + .font_weight(FontWeight::MEDIUM) + .child("Save"), + ) + }), + ) +} + +pub(super) struct Picture { + pub id: &'static str, + pub image: Div, + pub title: String, + pub subtitle: String, + pub removable: bool, + pub upload: fn(&mut Yumush, &mut Window, &mut Context), + pub remove: fn(&mut Yumush, &mut Window, &mut Context), +} + +pub(super) fn picture_card(picture: Picture, entity: &Entity, palette: Palette) -> Div { + let Picture { + id, + image, + title, + subtitle, + removable, + upload, + remove, + } = picture; + let picture_entity = entity.clone(); + let remove_entity = entity.clone(); + + div() + .p(px(16.)) + .flex() + .items_center() + .gap(px(16.)) + .rounded(px(10.)) + .border_1() + .border_color(palette.border) + .bg(palette.panel) + .child( + div() + .id(id) + .cursor_pointer() + .hover(|style| style.opacity(0.8)) + .on_click(move |_, window, cx| { + picture_entity.update(cx, |yumush, cx| upload(yumush, window, cx)); + }) + .tip("Change picture") + .child(image), + ) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .gap(px(2.)) + .child( + div() + .text_size(px(16.)) + .font_weight(FontWeight::SEMIBOLD) + .truncate() + .child(title), + ) + .when(!subtitle.is_empty(), |this| { + this.child( + div() + .text_size(px(12.)) + .text_color(palette.muted) + .truncate() + .child(subtitle), + ) + }), + ) + .children(removable.then(|| { + small_button( + "remove_picture_button", + palette, + palette.danger, + move |window, cx| { + remove_entity.update(cx, |yumush, cx| remove(yumush, window, cx)); + }, + ) + .child("Remove") + })) +} + +fn small_button( + id: &'static str, + palette: Palette, + color: Hsla, + on_click: impl Fn(&mut Window, &mut App) + 'static, +) -> Stateful
{ + clickable(id, palette, on_click) + .h(px(28.)) + .px(px(10.)) + .flex() + .items_center() + .rounded(px(6.)) + .text_size(px(13.)) + .text_color(color) +} + +pub(super) fn delete_control( + id: &'static str, + step: DeleteStep, + entity: &Entity, + palette: Palette, + action: fn(&mut Yumush, &mut Window, &mut Context), +) -> impl IntoElement { + let entity = entity.clone(); + let confirming = step == DeleteStep::Confirm; + + small_button(id, palette, palette.danger, move |window, cx| { + entity.update(cx, |yumush, cx| action(yumush, window, cx)); + }) + .border_1() + .border_color(palette.danger.opacity(0.5)) + .when(confirming, |this| { + this.bg(palette.danger).text_color(palette.on_accent) + }) + .child(if confirming { "Confirm" } else { "Delete" }) +} + +pub(super) fn read_avatar_file(path: &Path) -> Result, Error> { + let bytes = std::fs::read(path)?; + + crate::avatar::prepare(&bytes) +} + +pub(super) fn row(label: &'static str, control: impl IntoElement) -> Div { + div() + .min_h(px(48.)) + .py(px(10.)) + .px(px(12.)) + .flex() + .items_center() + .justify_between() + .child(label) + .child(control) +} + +pub(super) fn segmented( + options: [(T, &'static str); N], + selected: T, + entity: &Entity, + palette: Palette, + select: fn(&mut Yumush, T, &mut Context), +) -> impl IntoElement { + div() + .h(px(28.)) + .p(px(2.)) + .flex() + .gap(px(2.)) + .rounded(px(6.)) + .border_1() + .border_color(palette.border) + .bg(palette.field) + .children(options.map(|(choice, label)| { + let entity = entity.clone(); + let active = choice == selected; + + clickable(label, palette, move |_, cx| { + entity.update(cx, |yumush, cx| select(yumush, choice, cx)); + }) + .px(px(10.)) + .flex() + .items_center() + .rounded(px(4.)) + .text_color(if active { palette.text } else { palette.muted }) + .when(active, |this| this.bg(palette.hover)) + .child(label) + })) +} diff --git a/crates/client/src/gui/sidebar.rs b/crates/client/src/gui/sidebar.rs new file mode 100644 index 0000000..d2feb7e --- /dev/null +++ b/crates/client/src/gui/sidebar.rs @@ -0,0 +1,694 @@ +use common::{ + model::{CommunityKind, Invitation, User}, + permission, + validate::validate_community_name, +}; +use gpui_kit::{ + Anchor, AnyElement, App, Context, Div, Entity, FontWeight, InteractiveElement, IntoElement, + ParentElement, StatefulInteractiveElement, Styled, Window, + assets::IconName, + component::{ + Icon, + input::{Input, InputState}, + menu::{ContextMenuExt, PopupMenu, PopupMenuItem}, + }, + div, + prelude::FluentBuilder as _, + px, +}; + +use super::{ + Palette, Tooltip as _, Yumush, avatar, + chat::{View, create_community}, + clickable, community_icon, community_name, entity_action, hoverable, hoverable_with, + input_dialog, + profile::profile_popover, + social::Relation, +}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SidebarTab { + Messages, + Communities, +} + +impl Yumush { + pub(super) fn sidebar( + &self, + entity: &Entity, + query: &str, + palette: Palette, + ) -> impl IntoElement { + let (top, list) = match self.chat.tab { + SidebarTab::Messages => ( + Some(input_box(&self.chat.search_input, palette)), + self.messages_list(entity, query, palette) + .into_any_element(), + ), + SidebarTab::Communities => ( + None, + self.communities_list(entity, palette).into_any_element(), + ), + }; + + div() + .h_full() + .w(px(232.)) + .flex_shrink_0() + .flex() + .flex_col() + .py(px(12.)) + .px(px(10.)) + .gap(px(14.)) + .child( + div() + .flex() + .items_center() + .child(self.tab_bar(entity, palette)), + ) + .children(top) + .child( + div() + .id("sidebar_list") + .flex_1() + .min_h_0() + .overflow_y_scroll() + .child(list), + ) + .children(self.account_row(entity, palette)) + } + + fn tab_bar(&self, entity: &Entity, palette: Palette) -> impl IntoElement { + let requests = !self.chat.friends.incoming.is_empty() || !self.chat.invitations.is_empty(); + let tabs = [ + ( + SidebarTab::Communities, + "Communities", + self.chat.has_unread(false), + ), + ( + SidebarTab::Messages, + "Messages", + requests || self.chat.has_unread(true), + ), + ]; + + div() + .flex_1() + .h(px(28.)) + .p(px(2.)) + .flex() + .gap(px(2.)) + .rounded(px(6.)) + .border_1() + .border_color(palette.border) + .bg(palette.field) + .children(tabs.map(|(tab, label, alert)| { + let active = self.chat.tab == tab; + + let item = clickable( + label, + palette, + entity_action(entity, move |yumush, window, cx| { + yumush.set_sidebar_tab(tab, window, cx) + }), + ) + .flex_1() + .flex() + .items_center() + .justify_center() + .gap(px(6.)) + .rounded(px(4.)) + .text_size(px(12.)) + .text_color(if active { palette.text } else { palette.muted }) + .when(active, |this| this.bg(palette.hover)) + .child(label) + .children(alert.then(|| dot(palette))); + + match tab { + SidebarTab::Communities => item + .context_menu(new_community_menu(entity)) + .into_any_element(), + SidebarTab::Messages => item.into_any_element(), + } + })) + } + + fn messages_list(&self, entity: &Entity, query: &str, palette: Palette) -> Div { + let found = self + .chat + .found + .as_ref() + .filter(|user| !self.is_listed(&user.id)); + + div() + .flex() + .flex_col() + .gap(px(14.)) + .children(found.map(|user| self.found_row(entity, user, palette))) + .children( + query + .is_empty() + .then(|| self.requests(entity, palette)) + .flatten(), + ) + .child( + div() + .flex() + .flex_col() + .gap(px(1.)) + .children(self.direct_rows(entity, query, palette)), + ) + .children(group( + "Friends", + palette, + self.friend_rows(entity, query, palette), + )) + } + + fn is_listed(&self, user_id: &str) -> bool { + self.chat + .friends + .friends + .iter() + .any(|user| user.id == user_id) + || self.has_direct(user_id) + } + + fn has_direct(&self, user_id: &str) -> bool { + self.chat.communities.iter().any(|community| { + matches!(&community.kind, CommunityKind::Direct { peer } if peer.id == user_id) + }) + } + + fn communities_list(&self, entity: &Entity, palette: Palette) -> Div { + div().flex().flex_col().gap(px(1.)).children( + self.chat + .communities + .iter() + .filter(|community| matches!(community.kind, CommunityKind::Group)) + .map(|community| { + let active = self.chat.is_selected(&community.id); + let alert = self.chat.unread.contains(&community.id); + let can_leave = !active || permission::can_leave(self.actor_rank()); + let community_id = community.id.clone(); + let select = entity.clone(); + + let themed = palette.for_community(Some(community), &self.chat.hues); + hoverable_with( + format!("community_{}", community.id), + entry( + themed, + active, + community_icon( + palette, + community, + px(16.), + px(10.), + &self.chat.avatars, + ), + community.name.clone(), + alert.then(|| dot(palette).into_any_element()), + ), + themed.accent.opacity(0.1), + ) + .on_click(move |_, window, cx| { + select.update(cx, |yumush, cx| { + yumush.select_community(community_id.clone(), window, cx) + }) + }) + .context_menu(community_menu(entity, community.id.clone(), can_leave)) + .into_any_element() + }), + ) + } + + fn requests(&self, entity: &Entity, palette: Palette) -> Option
{ + let friends = &self.chat.friends; + let rows: Vec = friends + .incoming + .iter() + .map(|user| self.incoming_row(entity, user, palette)) + .chain( + friends + .outgoing + .iter() + .map(|user| self.outgoing_row(entity, user, palette)), + ) + .chain( + self.chat + .invitations + .iter() + .map(|invitation| self.invitation_row(entity, invitation, palette)), + ) + .collect(); + + group("Requests", palette, rows) + } + + fn direct_rows(&self, entity: &Entity, query: &str, palette: Palette) -> Vec { + self.chat + .communities + .iter() + .filter(|community| matches!(community.kind, CommunityKind::Direct { .. })) + .filter(|community| matches_query(community_name(community), query)) + .map(|community| { + let active = self.chat.is_selected(&community.id); + let alert = self.chat.unread.contains(&community.id); + let community_id = community.id.clone(); + let select = entity.clone(); + + let themed = palette.for_community(Some(community), &self.chat.hues); + hoverable_with( + format!("direct_{}", community.id), + entry( + themed, + active, + community_icon(palette, community, px(20.), px(10.), &self.chat.avatars), + community_name(community).to_string(), + alert.then(|| dot(palette).into_any_element()), + ), + themed.accent.opacity(0.1), + ) + .on_click(move |_, window, cx| { + select.update(cx, |yumush, cx| { + yumush.select_community(community_id.clone(), window, cx) + }) + }) + .into_any_element() + }) + .collect() + } + + fn friend_rows(&self, entity: &Entity, query: &str, palette: Palette) -> Vec { + self.chat + .friends + .friends + .iter() + .filter(|user| matches_query(&user.username, query) && !self.has_direct(&user.id)) + .map(|user| { + let user_id = user.id.clone(); + let open = entity.clone(); + let remove = entity.clone(); + let remove_id = user.id.clone(); + + hoverable( + format!("friend_{}", user.id), + entry( + palette, + false, + avatar(palette, user, px(20.), px(10.), &self.chat.avatars), + user.username.clone(), + Vec::new(), + ), + palette, + ) + .on_click(move |_, window, cx| { + open.update(cx, |yumush, cx| { + yumush.open_direct(user_id.clone(), window, cx) + }) + }) + .context_menu(move |menu, _, _| { + let remove = remove.clone(); + let remove_id = remove_id.clone(); + + menu.item( + PopupMenuItem::new("Remove friend").on_click(move |_, window, cx| { + remove.update(cx, |yumush, cx| { + yumush.remove_friend(remove_id.clone(), window, cx) + }) + }), + ) + }) + .into_any_element() + }) + .collect() + } + + fn found_row(&self, entity: &Entity, user: &User, palette: Palette) -> AnyElement { + let relation = self.relation(&user.id); + let mut trailing = Vec::new(); + + if relation != Relation::Myself { + let user_id = user.id.clone(); + trailing.push(icon_button( + format!("message_{}", user.id), + palette, + IconName::MessageSquare, + "Message", + entity_action(entity, move |yumush, window, cx| { + yumush.open_direct(user_id.clone(), window, cx) + }), + )); + } + if let Some((label, icon)) = relation + .action() + .filter(|_| matches!(relation, Relation::Stranger | Relation::Incoming)) + { + let user_id = user.id.clone(); + trailing.push(icon_button( + format!("friend_action_{}", user.id), + palette, + icon, + label, + entity_action(entity, move |yumush, window, cx| { + yumush.friend_action(relation, user_id.clone(), window, cx) + }), + )); + } + + entry( + palette, + false, + avatar(palette, user, px(20.), px(10.), &self.chat.avatars), + user.username.clone(), + trailing, + ) + .into_any_element() + } + + fn incoming_row(&self, entity: &Entity, user: &User, palette: Palette) -> AnyElement { + let accept_id = user.id.clone(); + let decline_id = user.id.clone(); + + entry( + palette, + false, + avatar(palette, user, px(20.), px(10.), &self.chat.avatars), + user.username.clone(), + [ + icon_button( + format!("accept_friend_{}", user.id), + palette, + IconName::Check, + "Accept", + entity_action(entity, move |yumush, window, cx| { + yumush.accept_friend(accept_id.clone(), window, cx) + }), + ), + icon_button( + format!("decline_friend_{}", user.id), + palette, + IconName::X, + "Decline", + entity_action(entity, move |yumush, window, cx| { + yumush.remove_friend(decline_id.clone(), window, cx) + }), + ), + ], + ) + .into_any_element() + } + + fn outgoing_row(&self, entity: &Entity, user: &User, palette: Palette) -> AnyElement { + let cancel_id = user.id.clone(); + + entry( + palette, + false, + avatar(palette, user, px(20.), px(10.), &self.chat.avatars), + user.username.clone(), + [icon_button( + format!("cancel_friend_{}", user.id), + palette, + IconName::X, + "Cancel", + entity_action(entity, move |yumush, window, cx| { + yumush.remove_friend(cancel_id.clone(), window, cx) + }), + )], + ) + .into_any_element() + } + + fn invitation_row( + &self, + entity: &Entity, + invitation: &Invitation, + palette: Palette, + ) -> AnyElement { + let community = &invitation.community; + let accept_id = community.id.clone(); + let decline_id = community.id.clone(); + let label = div().flex().flex_col().child(community.name.clone()).child( + div() + .text_size(px(11.)) + .text_color(palette.muted) + .child(format!("from {}", invitation.inviter.username)), + ); + + entry( + palette, + false, + community_icon(palette, community, px(16.), px(10.), &self.chat.avatars), + label, + [ + icon_button( + format!("accept_invitation_{}", community.id), + palette, + IconName::Check, + "Accept", + entity_action(entity, move |yumush, window, cx| { + yumush.accept_invitation(accept_id.clone(), window, cx) + }), + ), + icon_button( + format!("decline_invitation_{}", community.id), + palette, + IconName::X, + "Decline", + entity_action(entity, move |yumush, window, cx| { + yumush.decline_invitation(decline_id.clone(), window, cx) + }), + ), + ], + ) + .into_any_element() + } + + fn account_row(&self, entity: &Entity, palette: Palette) -> Option { + let user = self.user.as_ref()?; + let status = if self.connected { + palette.ok + } else { + palette.danger + }; + + Some( + div() + .h(px(32.)) + .pl(px(8.)) + .pr(px(4.)) + .flex() + .items_center() + .gap(px(8.)) + .child( + profile_popover( + "account_profile", + Anchor::BottomLeft, + user, + entity, + hoverable( + "account_trigger", + div() + .flex() + .items_center() + .gap(px(8.)) + .px(px(4.)) + .rounded(px(6.)) + .child(avatar(palette, user, px(20.), px(11.), &self.chat.avatars)) + .child( + div() + .flex_1() + .min_w_0() + .font_weight(FontWeight::MEDIUM) + .child(user.username.clone()), + ), + palette, + ), + ) + .flex_1() + .min_w_0(), + ) + .child(div().size(px(6.)).rounded_full().bg(status)) + .children(self.voice_controls(entity, palette)), + ) + } + + fn set_sidebar_tab(&mut self, tab: SidebarTab, window: &mut Window, cx: &mut Context) { + self.chat.tab = tab; + if tab == SidebarTab::Messages { + self.chat + .search_input + .update(cx, |input, cx| input.focus(window, cx)); + } + cx.notify(); + } + + pub(super) fn open_community_settings( + &mut self, + community_id: String, + window: &mut Window, + cx: &mut Context, + ) { + self.select_community(community_id, window, cx); + self.show_view(View::CommunitySettings, window, cx); + } +} + +fn community_menu( + entity: &Entity, + community_id: String, + can_leave: bool, +) -> impl Fn(PopupMenu, &mut Window, &mut Context) -> PopupMenu + 'static { + let entity = entity.clone(); + + move |menu, _, _| { + let invite = entity.clone(); + let invite_id = community_id.clone(); + let settings = entity.clone(); + let settings_id = community_id.clone(); + let leave = entity.clone(); + let leave_id = community_id.clone(); + + let menu = menu + .item(PopupMenuItem::new("Invite").on_click(move |_, window, cx| { + invite.update(cx, |yumush, cx| { + yumush.open_invite(invite_id.clone(), window, cx) + }) + })) + .item( + PopupMenuItem::new("Settings").on_click(move |_, window, cx| { + settings.update(cx, |yumush, cx| { + yumush.open_community_settings(settings_id.clone(), window, cx) + }) + }), + ); + + if !can_leave { + return menu; + } + + menu.item(PopupMenuItem::new("Leave").on_click(move |_, window, cx| { + leave.update(cx, |yumush, cx| { + yumush.leave_community(leave_id.clone(), window, cx) + }) + })) + } +} + +fn matches_query(name: &str, query: &str) -> bool { + name.to_lowercase().contains(query) +} + +fn new_community_menu( + entity: &Entity, +) -> impl Fn(PopupMenu, &mut Window, &mut Context) -> PopupMenu + 'static { + let entity = entity.clone(); + + move |menu, _, _| { + let entity = entity.clone(); + + menu.item( + PopupMenuItem::new("New community").on_click(move |_, window, cx| { + entity.update(cx, |_, cx| { + input_dialog( + "New community", + "Create", + "Name...", + window, + cx, + |this, name, window, cx| { + if validate_community_name(&name).is_ok() { + create_community(this, name, window, cx); + } + }, + ); + }); + }), + ) + } +} + +fn input_box(input: &Entity, palette: Palette) -> Div { + div() + .h(px(30.)) + .px(px(10.)) + .flex() + .items_center() + .gap(px(8.)) + .rounded(px(8.)) + .border_1() + .border_color(palette.border) + .bg(palette.field) + .text_color(palette.muted) + .child(Icon::new(IconName::Search).w(px(14.)).h(px(14.))) + .child( + Input::new(input) + .appearance(false) + .text_color(palette.text) + .flex_1() + .min_w_0(), + ) +} + +fn group(title: &'static str, palette: Palette, rows: Vec) -> Option
{ + (!rows.is_empty()).then(|| { + div() + .flex() + .flex_col() + .gap(px(1.)) + .child( + div() + .px(px(8.)) + .text_size(px(11.)) + .text_color(palette.muted) + .child(title), + ) + .children(rows) + }) +} + +fn entry( + palette: Palette, + active: bool, + leading: impl IntoElement, + label: impl IntoElement, + trailing: impl IntoIterator, +) -> Div { + div() + .h(px(36.)) + .px(px(6.)) + .flex() + .items_center() + .gap(px(8.)) + .rounded(px(6.)) + .text_color(if active { palette.text } else { palette.body }) + .when(active, |this| this.bg(palette.accent.opacity(0.18))) + .child(leading) + .child(div().flex_1().min_w_0().truncate().child(label)) + .children(trailing) +} + +fn dot(palette: Palette) -> Div { + div().size(px(6.)).rounded_full().bg(palette.alert) +} + +fn icon_button( + id: String, + palette: Palette, + icon: IconName, + tip: &'static str, + on_click: impl Fn(&mut Window, &mut App) + 'static, +) -> AnyElement { + clickable(id, palette, on_click) + .tip(tip) + .size(px(24.)) + .flex() + .items_center() + .justify_center() + .rounded(px(6.)) + .text_color(palette.muted) + .child(Icon::new(icon).w(px(14.)).h(px(14.))) + .into_any_element() +} diff --git a/crates/client/src/gui/snippet.rs b/crates/client/src/gui/snippet.rs new file mode 100644 index 0000000..2857d13 --- /dev/null +++ b/crates/client/src/gui/snippet.rs @@ -0,0 +1,104 @@ +use common::model::{Message, Role, SnippetMessage, User}; +use gpui_kit::{ + Entity, FontWeight, IntoElement, ParentElement, Styled, div, prelude::FluentBuilder as _, px, + relative, +}; + +use super::{Palette, Yumush, avatar, chat::Chat, id_time, media_view}; + +pub fn snippet_card( + message: &Message, + chat: &Chat, + entity: &Entity, + palette: Palette, +) -> Option { + let snippet = message.snippet.as_ref()?; + let header = match &snippet.origin { + Some(origin) => format!("Forwarded · {origin}"), + None => "Forwarded".to_string(), + }; + + Some( + div() + .flex() + .flex_col() + .gap(px(10.)) + .p(px(10.)) + .rounded(px(8.)) + .border_1() + .border_color(palette.border) + .bg(palette.panel) + .child( + div() + .text_size(px(12.)) + .text_color(palette.muted) + .child(header), + ) + .children( + snippet + .messages + .iter() + .map(|item| snippet_row(item, chat, entity, palette)), + ), + ) +} + +fn snippet_row( + item: &SnippetMessage, + chat: &Chat, + entity: &Entity, + palette: Palette, +) -> impl IntoElement { + let user = User { + id: item.user_id.clone(), + username: item.username.clone(), + role: Role::User, + status: String::new(), + avatar_id: item.avatar_id.clone(), + }; + + div() + .flex() + .gap(px(8.)) + .child(avatar(palette, &user, px(20.), px(10.), &chat.avatars)) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .gap(px(4.)) + .child( + div() + .flex() + .items_center() + .gap(px(6.)) + .child( + div() + .font_weight(FontWeight::SEMIBOLD) + .text_color(palette.tinted(&item.user_id)) + .child(item.username.clone()), + ) + .child( + div() + .text_size(px(11.)) + .text_color(palette.muted) + .child(id_time(&item.id, "%H:%M")), + ), + ) + .when(!item.body.is_empty(), |this| { + this.child( + div() + .line_height(relative(1.5)) + .text_color(palette.body) + .child(item.body.clone()), + ) + }) + .children(media_view::attachments( + &item.attachments, + &chat.media, + entity, + palette, + )), + ) +} diff --git a/crates/client/src/gui/social.rs b/crates/client/src/gui/social.rs new file mode 100644 index 0000000..51e2fb5 --- /dev/null +++ b/crates/client/src/gui/social.rs @@ -0,0 +1,461 @@ +use std::{fmt::Display, future::Future}; + +use common::{ + model::{Community, CommunityKind}, + validate::validate_username, +}; +use gpui_kit::{ + Context, Entity, FontWeight, IntoElement, ParentElement, Styled, Window, + assets::IconName, + component::{ + WindowExt, + input::{Input, InputEvent, InputState}, + }, + div, px, +}; + +use super::{Palette, Yumush, avatar, new_input, notify_error, primary_button}; + +#[derive(Debug, Clone, Default)] +pub enum InviteLookup { + #[default] + Idle, + Found(common::model::User), + Member(common::model::User), + Missing, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Relation { + Myself, + Friend, + Outgoing, + Incoming, + Stranger, +} + +impl Relation { + pub fn action(self) -> Option<(&'static str, IconName)> { + match self { + Relation::Myself => None, + Relation::Friend => Some(("Remove friend", IconName::UserX)), + Relation::Outgoing => Some(("Cancel request", IconName::X)), + Relation::Incoming => Some(("Accept friend", IconName::UserCheck)), + Relation::Stranger => Some(("Add friend", IconName::UserPlus)), + } + } +} + +fn spawn_done( + window: &mut Window, + cx: &mut Context, + call: impl Future> + 'static, +) { + cx.spawn_in(window, async move |this, cx| { + if let Err(error) = call.await { + notify_error(&this, cx, error); + } + }) + .detach(); +} + +fn spawn_community( + window: &mut Window, + cx: &mut Context, + 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| { + yumush.enter_community(community, window, cx); + }); + } + Err(error) => notify_error(&this, cx, error), + }) + .detach(); +} + +impl Yumush { + pub(super) fn relation(&self, user_id: &str) -> Relation { + let friends = &self.chat.friends; + + if self.is_me(user_id) { + Relation::Myself + } else if friends.friends.iter().any(|user| user.id == user_id) { + Relation::Friend + } else if friends.outgoing.iter().any(|user| user.id == user_id) { + Relation::Outgoing + } else if friends.incoming.iter().any(|user| user.id == user_id) { + Relation::Incoming + } else { + Relation::Stranger + } + } + + pub(super) fn request_social_avatars(&mut self, cx: &mut Context) { + let chat = &self.chat; + let users = chat + .friends + .friends + .iter() + .chain(&chat.friends.incoming) + .chain(&chat.friends.outgoing) + .chain( + chat.invitations + .iter() + .map(|invitation| &invitation.inviter), + ) + .chain( + chat.communities + .iter() + .filter_map(|community| match &community.kind { + CommunityKind::Direct { peer } => Some(peer), + CommunityKind::Group => None, + }), + ); + let avatar_ids: Vec = users + .filter_map(|user| user.avatar_id.clone()) + .chain( + chat.communities + .iter() + .filter_map(|community| community.avatar_id.clone()), + ) + .collect(); + + for avatar_id in avatar_ids { + self.request_avatar(&avatar_id, cx); + } + } + + pub(super) fn load_social(&self, window: &mut Window, cx: &mut Context) { + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + let (friends, invitations) = + match (network.friends().await, network.invitations().await) { + (Ok(friends), Ok(invitations)) => (friends, invitations), + (Err(error), _) | (_, Err(error)) => { + notify_error(&this, cx, error); + return; + } + }; + + let _ = this.update(cx, |yumush, cx| { + yumush.chat.friends = friends; + yumush.chat.invitations = invitations; + yumush.request_social_avatars(cx); + cx.notify(); + }); + }) + .detach(); + } + + pub(super) fn search_query(&self, cx: &Context) -> String { + self.chat + .search_input + .read(cx) + .text() + .to_string() + .trim() + .to_lowercase() + } + + pub(super) fn search_user(&mut self, window: &mut Window, cx: &mut Context) { + self.chat.found = None; + cx.notify(); + let username = self.search_query(cx); + if validate_username(&username).is_err() { + return; + } + let network = self.network.clone(); + + cx.spawn_in(window, async move |this, cx| { + let found = network.find_user(&username).await.ok(); + let _ = this.update(cx, |yumush, cx| { + if yumush.search_query(cx) != username { + return; + } + if let Some(user) = &found { + yumush.request_user_avatar(user, cx); + } + yumush.chat.found = found; + cx.notify(); + }); + }) + .detach(); + } + + pub(super) fn open_found(&self, window: &mut Window, cx: &mut Context) { + if let Some(user) = &self.chat.found { + self.open_direct(user.id.clone(), window, cx); + } + } + + pub(super) fn open_direct(&self, user_id: String, window: &mut Window, cx: &mut Context) { + let network = self.network.clone(); + + spawn_community( + window, + cx, + async move { network.open_direct(&user_id).await }, + ); + } + + pub(super) fn friend_action( + &self, + relation: Relation, + user_id: String, + window: &mut Window, + cx: &mut Context, + ) { + match relation { + Relation::Myself => {} + Relation::Stranger => self.add_friend(user_id, window, cx), + Relation::Incoming => self.accept_friend(user_id, window, cx), + Relation::Friend | Relation::Outgoing => self.remove_friend(user_id, window, cx), + } + } + + pub(super) fn add_friend(&self, user_id: String, window: &mut Window, cx: &mut Context) { + let network = self.network.clone(); + + spawn_done( + window, + cx, + async move { network.add_friend(&user_id).await }, + ); + } + + pub(super) fn accept_friend( + &self, + user_id: String, + window: &mut Window, + cx: &mut Context, + ) { + let network = self.network.clone(); + + spawn_done( + window, + cx, + async move { network.accept_friend(&user_id).await }, + ); + } + + pub(super) fn remove_friend( + &self, + user_id: String, + window: &mut Window, + cx: &mut Context, + ) { + let network = self.network.clone(); + + spawn_done( + window, + cx, + async move { network.remove_friend(&user_id).await }, + ); + } + + pub(super) fn accept_invitation( + &self, + community_id: String, + window: &mut Window, + cx: &mut Context, + ) { + let network = self.network.clone(); + + spawn_community(window, cx, async move { + network.accept_invitation(&community_id).await + }); + } + + pub(super) fn decline_invitation( + &self, + community_id: String, + window: &mut Window, + cx: &mut Context, + ) { + let network = self.network.clone(); + + spawn_done(window, cx, async move { + network.decline_invitation(&community_id).await + }); + } + + pub(super) fn open_invite( + &mut self, + community_id: String, + window: &mut Window, + cx: &mut Context, + ) { + self.chat.invite = InviteLookup::Idle; + let input = new_input("Username...", window, cx); + let enter_id = community_id.clone(); + let lookup_id = community_id.clone(); + + cx.subscribe_in( + &input, + window, + move |this, input, event, window, cx| match event { + InputEvent::Change => this.lookup_invite(lookup_id.clone(), input, window, cx), + InputEvent::PressEnter { .. } => this.send_invite(enter_id.clone(), window, cx), + _ => {} + }, + ) + .detach(); + + let entity = cx.entity(); + let dialog_input = input.clone(); + window.open_dialog(cx, move |dialog, _, cx| { + let yumush = entity.read(cx); + let palette = yumush.themed(cx); + let result = + invite_result(&yumush.chat.invite, &community_id, &entity, yumush, palette); + + dialog.title("Invite").child( + div() + .flex() + .flex_col() + .gap(px(12.)) + .child(Input::new(&dialog_input)) + .children(result), + ) + }); + window.defer(cx, move |window, cx| { + input.update(cx, |input, cx| input.focus(window, cx)); + }); + } + + fn lookup_invite( + &mut self, + community_id: String, + input: &Entity, + window: &mut Window, + cx: &mut Context, + ) { + let username = input.read(cx).text().to_string().trim().to_string(); + self.chat.invite = InviteLookup::Idle; + window.refresh(); + if validate_username(&username).is_err() { + return; + } + let network = self.network.clone(); + let input = input.clone(); + + cx.spawn_in(window, async move |this, cx| { + let lookup = match network.find_user(&username).await { + Ok(user) => { + let members = network.members(&community_id).await.unwrap_or_default(); + if members.iter().any(|member| member.user.id == user.id) { + InviteLookup::Member(user) + } else { + InviteLookup::Found(user) + } + } + Err(_) => InviteLookup::Missing, + }; + let _ = this.update_in(cx, |yumush, window, cx| { + if input.read(cx).text().to_string().trim() != username { + return; + } + if let InviteLookup::Found(user) | InviteLookup::Member(user) = &lookup { + yumush.request_user_avatar(user, cx); + } + yumush.chat.invite = lookup; + window.refresh(); + }); + }) + .detach(); + } + + fn send_invite(&self, community_id: String, window: &mut Window, cx: &mut Context) { + let InviteLookup::Found(user) = &self.chat.invite else { + return; + }; + let network = self.network.clone(); + let user_id = user.id.clone(); + + cx.spawn_in(window, async move |this, cx| { + match network.invite(&community_id, &user_id).await { + Ok(()) => { + let _ = this.update_in(cx, |_, window, cx| window.close_dialog(cx)); + } + Err(error) => notify_error(&this, cx, error), + } + }) + .detach(); + } +} + +fn invite_result( + lookup: &InviteLookup, + community_id: &str, + entity: &Entity, + yumush: &Yumush, + palette: Palette, +) -> Option { + match lookup { + InviteLookup::Idle => None, + InviteLookup::Missing => Some( + div() + .text_size(px(13.)) + .text_color(palette.muted) + .child("No such user") + .into_any_element(), + ), + InviteLookup::Member(user) => Some( + user_row(user, yumush, palette) + .child( + div() + .text_size(px(13.)) + .text_color(palette.muted) + .child("Member"), + ) + .into_any_element(), + ), + InviteLookup::Found(user) => { + let entity = entity.clone(); + let community_id = community_id.to_string(); + + Some( + user_row(user, yumush, palette) + .child( + primary_button("invite_send", palette, move |window, cx| { + entity.update(cx, |yumush, cx| { + yumush.send_invite(community_id.clone(), window, cx) + }) + }) + .h(px(30.)) + .px(px(14.)) + .flex() + .items_center() + .rounded(px(8.)) + .child("Invite"), + ) + .into_any_element(), + ) + } + } +} + +fn user_row(user: &common::model::User, yumush: &Yumush, palette: Palette) -> gpui_kit::Div { + div() + .flex() + .items_center() + .gap(px(10.)) + .child(avatar( + palette, + user, + px(32.), + px(14.), + &yumush.chat.avatars, + )) + .child( + div() + .flex_1() + .min_w_0() + .truncate() + .font_weight(FontWeight::SEMIBOLD) + .child(user.username.clone()), + ) +} diff --git a/crates/client/src/gui/voice_settings.rs b/crates/client/src/gui/voice_settings.rs new file mode 100644 index 0000000..da7d13b --- /dev/null +++ b/crates/client/src/gui/voice_settings.rs @@ -0,0 +1,536 @@ +use std::time::Duration; + +use gpui_kit::{ + App, AppContext, Context, Div, Entity, IntoElement, KeyDownEvent, KeyUpEvent, Keystroke, + ModifiersChangedEvent, ParentElement, SharedString, Stateful, Styled, Subscription, Task, + Window, + assets::IconName, + component::{ + Icon, IndexPath, + kbd::Kbd, + searchable_list::{SearchableListItem, SearchableVec}, + select::{Select, SelectEvent, SelectState}, + slider::{Slider, SliderEvent, SliderState}, + }, + div, px, relative, +}; + +use super::{ + Palette, Yumush, clickable, + settings_page::{row, segmented}, +}; +use crate::{ + settings::{Activation, SENSITIVITY_DB, VOLUME, VoiceSettings}, + voice::audio::{self, Device, Devices}, +}; + +const LEVEL_INTERVAL: Duration = Duration::from_millis(50); +const MODES: [(Activation, &str); 2] = [ + (Activation::VoiceActivity, "Voice activity"), + (Activation::PushToTalk, "Push to talk"), +]; + +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) enum Side { + Input, + Output, +} + +#[derive(Clone, Copy)] +pub(super) enum VoiceField { + Sensitivity, + InputVolume, + OutputVolume, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) enum MicTest { + Off, + On, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) enum KeyCapture { + Idle, + Waiting, +} + +#[derive(Clone)] +pub(super) struct DeviceItem { + id: Option, + name: SharedString, +} + +impl DeviceItem { + fn default_choice() -> Self { + Self { + id: None, + name: "Default".into(), + } + } +} + +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) mic_test: MicTest, + pub(super) key: KeyCapture, + level_poll: Option>, + _subscriptions: Vec, +} + +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); + 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(VoiceField::Sensitivity, event, cx); + }), + cx.subscribe(&input_volume, |this, _, event: &SliderEvent, cx| { + this.slider_changed(VoiceField::InputVolume, event, cx); + }), + cx.subscribe(&output_volume, |this, _, event: &SliderEvent, cx| { + this.slider_changed(VoiceField::OutputVolume, event, cx); + }), + ]; + + Self { + inputs, + outputs, + sensitivity, + input_volume, + output_volume, + mic_test: MicTest::Off, + key: KeyCapture::Idle, + level_poll: None, + _subscriptions: subscriptions, + } + } +} + +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, + cx: &mut Context, +) -> Entity { + cx.new(|_| { + SliderState::new() + .min(*range.start()) + .max(*range.end()) + .default_value(value) + }) +} + +fn device_list(devices: Vec) -> DeviceList { + let mut items = vec![DeviceItem::default_choice()]; + items.extend(devices.into_iter().map(|device| DeviceItem { + id: Some(device.id), + name: device.name.into(), + })); + SearchableVec::new(items) +} + +fn volume_control(state: &Entity, value: f32, palette: Palette) -> Div { + div() + .flex() + .items_center() + .gap(px(8.)) + .child(Slider::new(state).w(px(160.))) + .child( + div() + .w(px(44.)) + .text_right() + .text_color(palette.muted) + .child(format!("{value:.0}%")), + ) +} + +fn level_bar(level: Option, threshold: f32, palette: Palette) -> 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) + }); + let color = if level.is_some_and(|db| db >= threshold) { + palette.ok + } else { + palette.muted + }; + + div() + .h(px(4.)) + .w_full() + .rounded(px(2.)) + .bg(palette.border) + .child( + div() + .h_full() + .w(relative(fraction)) + .rounded(px(2.)) + .bg(color), + ) +} + +impl Yumush { + pub(super) fn voice_rows(&self, entity: &Entity, palette: Palette, cx: &App) -> Vec
{ + let voice = &self.settings.voice; + let controls = &self.voice; + + let mut rows = vec![ + row( + "Input device", + div().child(Select::new(&controls.inputs).w(px(200.))), + ), + row( + "Output device", + div().child(Select::new(&controls.outputs).w(px(200.))), + ), + row( + "Input volume", + volume_control(&controls.input_volume, voice.input_volume, palette), + ), + row( + "Output volume", + volume_control(&controls.output_volume, voice.output_volume, palette), + ), + row( + "Mode", + segmented( + MODES, + voice.activation, + entity, + palette, + Yumush::set_voice_mode, + ), + ), + ]; + + if self.chat.voice_community().is_none() { + rows.push(row("Test", self.test_control(entity, palette))); + } + match voice.activation { + Activation::VoiceActivity => { + rows.push(row("Sensitivity", self.sensitivity_control(palette))) + } + Activation::PushToTalk => rows.push(row( + "Key", + self.key_control(&voice.push_to_talk_key, entity, palette, cx), + )), + } + + rows + } + + fn test_control(&self, entity: &Entity, palette: Palette) -> Div { + let testing = self.voice.mic_test == MicTest::On; + let mic = entity.clone(); + let speaker = entity.clone(); + + div() + .flex() + .items_center() + .gap(px(6.)) + .child( + test_button("mic_test_button", palette, testing, move |_, cx| { + mic.update(cx, |yumush, cx| yumush.toggle_mic_test(cx)); + }) + .child(Icon::new(IconName::Mic).w(px(14.)).h(px(14.))) + .child(if testing { "Stop" } else { "Hear yourself" }), + ) + .child( + test_button("speaker_test_button", palette, false, move |_, cx| { + speaker.update(cx, |yumush, _| yumush.network.play_chime()); + }) + .child(Icon::new(IconName::Volume2).w(px(14.)).h(px(14.))) + .child("Play sound"), + ) + } + + fn sensitivity_control(&self, palette: Palette) -> Div { + let level = self.network.voice_level_db(); + + div().flex().items_center().gap(px(8.)).child( + div() + .w(px(200.)) + .flex() + .flex_col() + .gap(px(6.)) + .child(Slider::new(&self.voice.sensitivity)) + .child(level_bar( + level, + self.settings.voice.sensitivity_db, + palette, + )), + ) + } + + fn key_control( + &self, + key: &str, + entity: &Entity, + palette: Palette, + cx: &App, + ) -> impl IntoElement { + let content = match self.voice.key { + KeyCapture::Waiting => div().child("Press key").into_any_element(), + KeyCapture::Idle => match Keystroke::parse_with_os(key, cx.platform_info().os) { + Ok(stroke) if !key.is_empty() => Kbd::new(stroke).into_any_element(), + _ => div().child("Set key").into_any_element(), + }, + }; + let entity = entity.clone(); + + clickable("ptt_key_button", palette, move |window, cx| { + entity.update(cx, |yumush, cx| yumush.capture_key(window, cx)); + }) + .h(px(28.)) + .px(px(8.)) + .flex() + .items_center() + .rounded(px(6.)) + .child(content) + } + + fn slider_changed(&mut self, field: VoiceField, event: &SliderEvent, cx: &mut Context) { + let SliderEvent::Change(value) = event else { + return; + }; + let value = value.start(); + let voice = &mut self.settings.voice; + + match field { + VoiceField::Sensitivity => voice.sensitivity_db = value, + VoiceField::InputVolume => voice.input_volume = value, + VoiceField::OutputVolume => voice.output_volume = value, + } + self.commit_settings(cx); + } + + pub(super) fn set_voice_device( + &mut self, + side: Side, + id: Option, + cx: &mut Context, + ) { + match side { + Side::Input => self.settings.voice.choice.input = id, + Side::Output => self.settings.voice.choice.output = id, + } + self.commit_settings(cx); + } + + pub(super) fn set_voice_mode(&mut self, activation: Activation, cx: &mut Context) { + self.settings.voice.activation = activation; + self.commit_settings(cx); + } + + pub(super) fn capture_key(&mut self, window: &mut Window, cx: &mut Context) { + window.focus(&self.focus, cx); + self.voice.key = KeyCapture::Waiting; + cx.notify(); + } + + fn is_push_key(&self, key: &str) -> bool { + self.settings.voice.activation == Activation::PushToTalk + && !key.is_empty() + && self.settings.voice.push_to_talk_key == key + } + + pub(super) fn voice_key_down(&mut self, event: &KeyDownEvent, cx: &mut Context) { + let key = event.keystroke.key.clone(); + + match self.voice.key { + KeyCapture::Waiting => { + cx.stop_propagation(); + self.voice.key = KeyCapture::Idle; + if key != "escape" { + self.settings.voice.push_to_talk_key = key; + self.commit_settings(cx); + } + cx.notify(); + } + KeyCapture::Idle => { + if self.is_push_key(&key) { + self.network.set_talking(true); + } + } + } + } + + pub(super) fn voice_key_up(&mut self, event: &KeyUpEvent, _: &mut Context) { + if self.is_push_key(&event.keystroke.key) { + self.network.set_talking(false); + } + } + + pub(super) fn voice_modifiers( + &mut self, + event: &ModifiersChangedEvent, + cx: &mut Context, + ) { + let modifiers = event.modifiers; + let held = [ + ("ctrl", modifiers.control), + ("shift", modifiers.shift), + ("alt", modifiers.alt), + ("super", modifiers.platform), + ]; + + match self.voice.key { + KeyCapture::Waiting => { + let Some((key, _)) = held.iter().find(|(_, down)| *down) else { + return; + }; + self.voice.key = KeyCapture::Idle; + self.settings.voice.push_to_talk_key = key.to_string(); + self.commit_settings(cx); + cx.notify(); + } + KeyCapture::Idle => { + if let Some((_, down)) = held.iter().find(|(key, _)| self.is_push_key(key)) { + self.network.set_talking(*down); + } + } + } + } + + pub(super) fn toggle_mic_test(&mut self, cx: &mut Context) { + match self.voice.mic_test { + MicTest::On => self.stop_mic_test(), + MicTest::Off => { + self.network.start_mic_test(); + self.voice.mic_test = MicTest::On; + self.start_level_poll(cx); + } + } + cx.notify(); + } + + pub(super) fn stop_mic_test(&mut self) { + self.network.stop_mic_test(); + 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; + } + + pub(super) fn enter_settings(&mut self, window: &mut Window, cx: &mut Context) { + self.load_audio_devices(window, cx); + if self.network.voice_level_db().is_some() { + 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)) { + break; + } + } + })); + } + + fn load_audio_devices(&self, window: &mut Window, cx: &mut Context) { + cx.spawn_in(window, 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); + }); + }) + .detach(); + } + + fn apply_devices(&mut self, devices: Devices, window: &mut Window, cx: &mut Context) { + let choice = self.settings.voice.choice.clone(); + + self.voice.inputs.update(cx, |state, cx| { + state.set_items(device_list(devices.inputs), window, cx); + state.set_selected_value(&choice.input, window, cx); + }); + self.voice.outputs.update(cx, |state, cx| { + state.set_items(device_list(devices.outputs), window, cx); + state.set_selected_value(&choice.output, window, cx); + }); + } +} + +fn test_button( + id: &'static str, + palette: Palette, + active: bool, + on_click: impl Fn(&mut Window, &mut App) + 'static, +) -> Stateful
{ + clickable(id, palette, on_click) + .h(px(28.)) + .px(px(10.)) + .flex() + .items_center() + .gap(px(6.)) + .rounded(px(6.)) + .border_1() + .border_color(if active { + palette.accent + } else { + palette.border + }) + .text_color(if active { palette.text } else { palette.body }) +} diff --git a/crates/client/src/lib.rs b/crates/client/src/lib.rs index ac25474..9d43ef5 100644 --- a/crates/client/src/lib.rs +++ b/crates/client/src/lib.rs @@ -1,7 +1,13 @@ use common::config::Config; +pub mod accounts; +pub mod avatar; +pub mod embed; pub mod gui; +pub mod media; pub mod network; +pub mod settings; +pub mod voice; pub const NAME: &str = "Yumush"; diff --git a/crates/client/src/main.rs b/crates/client/src/main.rs index 7ee7424..52949e2 100644 --- a/crates/client/src/main.rs +++ b/crates/client/src/main.rs @@ -1,38 +1,58 @@ -use client::{ClientConfig, NAME, gui::Yumush, network}; +use client::{ + ClientConfig, NAME, + gui::{self, Yumush}, + network, settings, +}; use gpui_kit::{ App, AppContext, Bounds, TitlebarOptions, WindowBounds, WindowOptions, application, - component::Root, init, px, size, + assets::AllAssets, component::Root, init, px, size, }; +use tracing::Level; +use tracing_subscriber::{filter::Targets, layer::SubscriberExt, util::SubscriberInitExt}; + fn main() { - tracing_subscriber::fmt().with_max_level(tracing::Level::INFO).init(); + tracing_subscriber::registry() + .with(tracing_subscriber::fmt::layer()) + .with( + Targets::new() + .with_default(Level::INFO) + .with_target("zbus", Level::ERROR), + ) + .init(); + let settings = settings::load(); let (network_handle, network_event_receiver) = network::start(ClientConfig::default()); - application().run(|cx: &mut App| { - init(cx); + application() + .with_assets(AllAssets) + .run(move |cx: &mut App| { + init(cx); + settings::apply(settings.theme, cx); + gui::bind_keys(cx); - let window_bounds = Bounds::centered(None, size(px(800.0), px(600.0)), cx); + let window_bounds = Bounds::centered(None, size(px(1100.0), px(720.0)), cx); - let titlebar = TitlebarOptions { - title: Some(NAME.into()), - ..Default::default() - }; - - cx.open_window( - WindowOptions { - window_bounds: Some(WindowBounds::Windowed(window_bounds)), - titlebar: Some(titlebar), + let titlebar = TitlebarOptions { + title: Some(NAME.into()), ..Default::default() - }, - |window, cx| { - let view = - cx.new(|cx| Yumush::new(network_handle, network_event_receiver, window, cx)); - cx.new(|cx| Root::new(view, window, cx)) - }, - ) - .unwrap(); + }; + + cx.open_window( + WindowOptions { + window_bounds: Some(WindowBounds::Windowed(window_bounds)), + titlebar: Some(titlebar), + ..Default::default() + }, + |window, cx| { + let view = cx.new(|cx| { + Yumush::new(network_handle, network_event_receiver, settings, window, cx) + }); + cx.new(|cx| Root::new(view, window, cx)) + }, + ) + .unwrap(); - cx.activate(true); - }); + cx.activate(true); + }); } diff --git a/crates/client/src/media/convert.rs b/crates/client/src/media/convert.rs new file mode 100644 index 0000000..c7c0bae --- /dev/null +++ b/crates/client/src/media/convert.rs @@ -0,0 +1,59 @@ +const MAX_WIDTH: u32 = 1280; + +pub fn yuv_to_bgra( + y: &[u8], + y_stride: usize, + u: &[u8], + v: &[u8], + uv_stride: usize, + width: u32, + height: u32, +) -> Option<(u32, u32, Vec)> { + if width == 0 || height == 0 { + return None; + } + let step = width.div_ceil(MAX_WIDTH); + let out_width = width.div_ceil(step); + let out_height = height.div_ceil(step); + let mut out = Vec::with_capacity(out_width as usize * out_height as usize * 4); + for row in 0..out_height { + let py = (row * step).min(height - 1) as usize; + for column in 0..out_width { + let px = (column * step).min(width - 1) as usize; + let luma = sample(y, y_stride, px, py) - 16; + let cb = sample(u, uv_stride, px / 2, py / 2) - 128; + let cr = sample(v, uv_stride, px / 2, py / 2) - 128; + let scaled = 298 * luma; + let red = clamp((scaled + 459 * cr + 128) >> 8); + let green = clamp((scaled - 55 * cb - 136 * cr + 128) >> 8); + let blue = clamp((scaled + 541 * cb + 128) >> 8); + out.extend_from_slice(&[blue, green, red, 255]); + } + } + Some((out_width, out_height, out)) +} + +fn sample(plane: &[u8], stride: usize, x: usize, y: usize) -> i32 { + plane + .get(y * stride + x) + .map_or(0, |&value| i32::from(value)) +} + +fn clamp(value: i32) -> u8 { + value.clamp(0, 255) as u8 +} + +#[cfg(test)] +mod tests { + use super::*; + + fn bgra(luma: u8) -> Option<(u32, u32, Vec)> { + yuv_to_bgra(&[luma; 4], 2, &[128], &[128], 1, 2, 2) + } + + #[test] + fn i420_limits_map_to_black_and_white_bgra() { + assert_eq!(bgra(235), Some((2, 2, [255, 255, 255, 255].repeat(4)))); + assert_eq!(bgra(16), Some((2, 2, [0, 0, 0, 255].repeat(4)))); + } +} diff --git a/crates/client/src/media/decode.rs b/crates/client/src/media/decode.rs new file mode 100644 index 0000000..aaf3e96 --- /dev/null +++ b/crates/client/src/media/decode.rs @@ -0,0 +1,579 @@ +use std::{ + collections::VecDeque, + path::PathBuf, + sync::{ + Arc, Mutex, MutexGuard, PoisonError, + atomic::{AtomicBool, Ordering}, + }, + time::{Duration, Instant}, +}; + +use common::constant::VOICE_SAMPLE_RATE; +use ec_core::frame::{Frame as CodecFrame, PixelFormat, VideoFrame}; +use ec_core::packet::Packet; +use ec_core::registry::{CodecId, CodecParameters, Decoder as CodecDecoder, SeekMode}; +use ec_core::timebase::{TimeBase, Timestamp}; +use ec_h264::H264Decoder; +use ec_probe::{Reader, decoder::AudioDecoder}; +use rtrb::Producer; +use tracing::warn; + +use super::{ + Frame, Tracks, convert, + resample::{self, Resampler}, +}; +use crate::voice::Playback; + +pub const RING_SAMPLES: usize = VOICE_SAMPLE_RATE as usize / 4; +const QUEUE_LIMIT: usize = 8; +const BACKLOG_LIMIT: usize = 600; +const LATE: f64 = 0.1; +const TICK: Duration = Duration::from_millis(4); +const MAX_PAD: usize = VOICE_SAMPLE_RATE as usize * 5; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum State { + Playing, + Paused, + Finished, +} + +#[derive(Debug)] +pub struct Clock { + pub state: State, + pub base: f64, + pub written: u64, + pub started: Option, + pub audio: bool, +} + +impl Clock { + pub fn new(audio: bool) -> Clock { + Clock { + state: State::Paused, + base: 0.0, + written: 0, + started: None, + audio, + } + } + + pub fn position(&self, queued: usize) -> f64 { + let played = if self.audio { + self.written.saturating_sub(queued as u64) as f64 / f64::from(VOICE_SAMPLE_RATE) + } else { + self.started + .map_or(0.0, |started| started.elapsed().as_secs_f64()) + }; + self.base + played + } + + pub fn set(&mut self, state: State) { + if !self.audio { + self.base = self.position(0); + } + self.state = state; + self.started = self.wall_start(); + } + + pub fn rebase(&mut self, to: f64) { + self.base = to; + self.written = 0; + self.started = self.wall_start(); + } + + fn wall_start(&self) -> Option { + (self.state == State::Playing && !self.audio).then(Instant::now) + } +} + +#[derive(Debug, Default)] +pub struct Video { + pub queue: VecDeque<(f64, Frame)>, + pub current: Option, + pub generation: u64, +} + +#[derive(Debug)] +pub struct Shared { + pub stop: AtomicBool, + pub seek: Mutex>, + pub clock: Mutex, + pub video: Mutex