pub(super) mod admin; pub(super) mod poll_draft; pub(super) mod session; use self::admin::Admin; use self::poll_draft::PollDraft; use self::session::Session; use super::style::{self, Tokens, radius, size, space, stroke, text}; use super::text; use crate::gui::glyph::Fill as _; use crate::lang::w; use std::{ collections::{HashSet, VecDeque}, time::{Duration, Instant}, }; use crate::gui::camera_view::Stage; use crate::gui::voice_stats::{self, SAMPLE_HISTORY}; use crate::gui::{ Tooltip as _, Yumush, avatar, clickable, community_name, community_settings::{BanSort, LogSort}, composer::{self, Composer}, entity_action, hoverable, media_view, message_actions, millis_time, new_input, notify_error, parts, poll, presence_avatar, profile::profile_popover, sidebar::unread_badge, snippet, voice_note::{self, VoiceNote}, widget::{ok_or_notify, search_text, spawn_done}, }; use crate::net::{Fail, Levels}; use crate::settings::VOLUME; use common::{ call::{ CreateCommunity, DeclineCall, DeleteMessage, GetUser, LeaveCommunity, ListBans, ListCommunities, ListEdits, ListMembers, ListMessages, ListPins, ListUnreads, ListVoiceParticipants, PushStats, SearchCommunity, WatchCommunity, }, constant::MESSAGE_PAGE_LIMIT, event::Event, model::{ CallLog, Community, CommunityKind, Hue, Id, Member, Message, Presence, Rank, Reply, Unread, User, mentions, }, permission, share::{Kind, Share}, stats::ShareSample, }; use gpui_kit::{ Anchor, AnimationExt, AnyElement, App, AppContext, Context, Div, Entity, FontWeight, InteractiveElement, IntoElement, ParentElement, ScrollHandle, StatefulInteractiveElement, Styled, Subscription, Window, assets::IconName, component::{ Icon, WindowExt, input::{InputEvent, InputState, Textarea, TextareaState}, resizable::{h_resizable, resizable_panel, v_resizable}, slider::{SliderEvent, SliderState}, text::TextView, }, div, prelude::FluentBuilder as _, px, relative, }; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum StatsAt { Header, Dock, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum View { #[default] Chat, Settings, CommunitySettings, Builder, } #[derive(Debug, Clone, PartialEq, Eq)] pub enum Armed { LogOut, Leave(Id), RemoveFriend(Id), DeleteUser(Id), DeleteAccount, DeleteCommunity, RestartServer, DeleteMessage(Id), DeleteAttachment(Id), BuilderDeleteUser(Id), PurgeUser(Id), BuilderDeleteCommunity(Id), DeleteInvite(String), } #[derive(Debug, Clone, PartialEq, Eq, Default)] pub enum VoiceState { #[default] Off, In { community_id: Id, muted: bool, deafened: bool, since: Instant, }, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub(super) enum History { #[default] End, More, } impl History { fn of_page(length: usize) -> Self { if length < MESSAGE_PAGE_LIMIT { History::End } else { History::More } } } #[derive(Debug, Clone, PartialEq, Eq)] pub enum ReportTarget { Message(Id), User(Id), } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum CardMenu { #[default] Main, More, Status, } pub struct Chat { pub(super) session: Session, pub(super) admin: Admin, pub(super) poll: PollDraft, pub(super) composer: Composer, pub(super) message_input: Entity, pub(super) search_input: Entity, pub(super) community_search: Entity, pub(super) username_input: Entity, pub(super) community_name_input: Entity, pub(super) status_input: Entity, pub(super) ban_search: Entity, pub(super) ban_sort: BanSort, pub(super) log_search: Entity, pub(super) log_sort: LogSort, pub(super) report_reason: Entity, pub(super) sidebar_collapsed: bool, pub(super) sidebar_toggled: Option, pub(super) stats_at: Option, pub(super) stage: Stage, pub(super) grid_size: (f32, f32), pub(super) strip_size: (f32, f32), pub(super) goto: super::jump::Jump, pub(super) usage_monitor: crate::usage::Monitor, scroll: ScrollHandle, } const RING_LIMIT: usize = 15; const RING_INTERVAL: Duration = Duration::from_secs(2); const VOICE_SAMPLE_INTERVAL: Duration = Duration::from_secs(1); const WAVE_INTERVAL: Duration = Duration::from_millis(33); const DEFAULT_USER_VOLUME: f32 = 100.0; pub struct UserVolume { pub user_id: Id, pub slider: Entity, _subscription: Subscription, } const DELETE_CONFIRM: Duration = Duration::from_secs(3); pub const TYPING_SEND_INTERVAL: Duration = Duration::from_secs(3); pub const TYPING_TTL: Duration = Duration::from_secs(5); const HIGHLIGHT_TTL: Duration = Duration::from_secs(2); impl Chat { pub fn new(window: &mut Window, cx: &mut Context) -> Self { let message_input = cx.new(|cx| { let mut state = TextareaState::new(window, cx) .auto_grow(1, 10) .submit_on_enter(true); state.set_placeholder(w().chat.message, window, cx); state }); cx.subscribe_in( &message_input, window, |this, input, event, window, cx| match event { InputEvent::PressEnter { shift: false, .. } => { this.submit_composer(input, window, cx) } InputEvent::Change => { input.update(cx, |state, cx| state.mark(cx)); this.send_typing(cx) } _ => {} }, ) .detach(); let jump_input = new_input(w().jump.placeholder, window, cx); cx.subscribe_in( &jump_input, window, |this, _, event, window, cx| match event { InputEvent::Change => { this.chat.goto.cursor = 0; this.chat.goto.scroll.scroll_to_item(0); cx.notify(); } InputEvent::PressEnter { .. } => this.jump_enter(window, cx), _ => {} }, ) .detach(); let search_input = new_input(w().chat.find_user, window, cx); cx.subscribe_in( &search_input, window, |this, _, event, window, cx| match event { InputEvent::Change => this.search_user(window, cx), InputEvent::PressEnter { .. } => this.open_found(window, cx), _ => {} }, ) .detach(); let community_search = new_input(w().chat.find, window, cx); cx.subscribe_in( &community_search, window, |this, _, event, window, cx| match event { InputEvent::PressEnter { .. } => this.search_community(window, cx), InputEvent::Change => cx.notify(), _ => {} }, ) .detach(); let ban_search = new_input(w().chat.search, window, cx); let log_search = new_input(w().chat.search, window, cx); let admin = Admin::new(window, cx); for search in [ &ban_search, &log_search, &admin.builder_search, &admin.builder_friend_search, ] { cx.subscribe_in(search, window, |_, _, event, window, cx| { if matches!(event, InputEvent::Change) { window.refresh(); cx.notify(); } }) .detach(); } Self { session: Session::default(), admin, poll: PollDraft::new(window, cx), composer: Composer::Compose { reply: None }, message_input, search_input, community_search, username_input: editable_input(w().chat.username, Yumush::save_username, window, cx), community_name_input: editable_input( w().chat.community_name, Yumush::save_community_name, window, cx, ), status_input: editable_input(w().chat.status, Yumush::save_status, window, cx), ban_search, ban_sort: BanSort::Newest, log_search, log_sort: LogSort::Newest, report_reason: new_input(w().chat.reason, window, cx), sidebar_collapsed: false, sidebar_toggled: None, stats_at: None, stage: Stage::Strip, grid_size: (1280., 720.), strip_size: (1280., 0.), goto: super::jump::Jump { open: false, cursor: 0, input: jump_input, scroll: ScrollHandle::new(), }, usage_monitor: { crate::usage::Monitor::new(crate::usage::Wake::OnDemand, crate::config_dir()) }, scroll: ScrollHandle::new(), } } fn unread_where(&self, keep: impl Fn(&CommunityKind) -> bool) -> Unread { self.session .communities .iter() .filter(|community| { !self.session.muted.contains(&community.id) && keep(&community.kind) }) .filter_map(|community| self.session.unread.get(&community.id)) .fold(Unread::default(), |total, unread| Unread { messages: total.messages + unread.messages, mentions: total.mentions + unread.mentions, ..total }) } pub(super) fn unread_groups(&self) -> Unread { self.unread_where(|kind| kind.is_group()) } pub(super) fn unread_direct(&self) -> Unread { self.unread_where(|kind| !kind.is_group()) } pub fn focus(&self, window: &mut Window, cx: &mut Context) { match self.session.selected_community_id { Some(_) => self .message_input .update(cx, |input, cx| input.focus(window, cx)), None => self .search_input .update(cx, |input, cx| input.focus(window, cx)), } } pub fn name_of(&self, user_id: Id) -> String { self.author(user_id) .map_or_else(|| user_id.to_string(), |user| user.username.clone()) } pub fn slow_seconds(&self) -> Option { let remaining = self .session .slowed_until? .saturating_sub(common::time::now_ms()); (remaining > 0).then(|| remaining.div_ceil(1000)) } pub fn apply_event(&mut self, event: Event, me: Option, builder: bool) { match event { Event::MessageCreated(message) => { if let Some(users) = self.session.typing.get_mut(&message.community_id) { users.remove(&message.user_id); } if self.is_selected(message.community_id) { self.insert_messages([message], me); } } Event::MessageUpdated(message) => { if self.is_selected(message.community_id) { self.update_pin(&message); if let Some(existing) = self .session .messages .iter_mut() .find(|existing| existing.id == message.id) { *existing = message.clone(); } let body = match &message.poll { Some(poll) if message.body.is_empty() => poll.question.clone(), _ => message.body.clone(), }; for quote in self.quotes_of(message.id) { quote.body = body.clone(); } } } Event::MyVotes { message_id, positions, } => { self.session.my_votes.insert(message_id, positions); } Event::MessagesDeleted { community_id, ids } => { if self.is_selected(community_id) { for id in ids { self.remove_message(id, builder); } } } Event::MemberJoined { community_id, member, } => { if self.is_selected(community_id) { self.insert_member(member); } } Event::MemberLeft { community_id, user_id, } => { if self.is_selected(community_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) => { style::remember( &friends .friends .iter() .chain(&friends.incoming) .chain(&friends.outgoing) .collect::>(), ); self.session.friends = friends; } Event::InvitationsUpdated(invitations) => self.session.invitations = invitations, Event::CommunityDeleted { community_id } => self.remove_community(community_id), Event::UserDeleted { user_id } => { self.remove_member(user_id); self.session .messages .retain(|message| message.user_id != user_id); } Event::UserUpdated(user) => self.update_member(&user), Event::PresenceChanged { user_id, presence } => { self.session.presences.insert(user_id, presence); } Event::VoiceJoined { community_id, user_id, } => { let ids = self.session.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.session.voice.get_mut(&community_id) { ids.retain(|id| *id != user_id); if ids.is_empty() { self.session.ringing.remove(&community_id); } } } Event::VoiceMuted { user_id, muted, .. } => { if muted { self.session.server_muted.insert(user_id); } else { self.session.server_muted.remove(&user_id); } } Event::Typing { community_id, user_id, } => { self.session .typing .entry(community_id) .or_default() .insert(user_id, Instant::now()); } Event::ShareStarted { community_id, share, } => { let shares = self.session.shares.entry(community_id).or_default(); shares.retain(|existing| { existing.user_id != share.user_id || existing.kind != share.kind }); shares.push(share); } Event::ShareStopped { community_id, user_id, kind, } => { if let Some(shares) = self.session.shares.get_mut(&community_id) { shares.retain(|share| share.user_id != user_id || share.kind != kind); } } Event::StatsWanted(_) => {} Event::StatsOf { user_id, stats } => { if let Some(followed) = self .session .followed .as_mut() .filter(|(id, _)| *id == user_id) { followed.1 = stats; } } Event::ReportCreated | Event::Removed { .. } | Event::SettingsUpdated(_) | Event::Release | Event::Imported { .. } => {} } } pub(super) fn is_selected(&self, community_id: Id) -> bool { self.session.selected_community_id == Some(community_id) } pub fn typing_label(&self) -> Option { let community_id = self.session.selected_community_id.as_ref()?; let names: Vec<&str> = self .session .typing .get(community_id)? .iter() .filter(|(_, at)| at.elapsed() < TYPING_TTL) .map(|(user_id, _)| { self.author(*user_id) .map_or(w().chat.someone, |user| user.username.as_str()) }) .collect(); match names.as_slice() { [] => None, [name] => Some(w().chat.typing_one(name)), names => Some(w().chat.typing_many(names.len())), } } fn select(&mut self, community_id: Option) { if community_id != self.session.selected_community_id { self.session.unread_anchor = community_id .as_ref() .and_then(|community_id| self.session.unread.get(community_id)) .filter(|unread| unread.messages > 0) .and_then(|unread| { unread .last_read .map(|last_read| (last_read, unread.messages)) }); self.session.unseen = 0; } if self.session.opened.as_ref().map(|opened| &opened.id) != community_id.as_ref() { self.session.opened = None; } if self.session.view == View::CommunitySettings { self.session.view = View::Chat; } self.session.selected_community_id = community_id; self.session.users.extend( self.session .members .drain(..) .map(|member| (member.user.id, member.user)), ); self.session.bans.clear(); self.session.logs.clear(); self.session.armed = None; self.session.messages.clear(); self.session.jump = None; self.session.pins.clear(); self.poll.expanded = false; self.poll.page = 0; self.session.my_votes.clear(); self.session.community_hits.clear(); self.session.history = History::End; self.session.media.leave(); self.composer = Composer::Compose { reply: None }; } pub fn joined(&self, community_id: Id) -> bool { self.session .communities .iter() .chain( self.session .opened .as_ref() .filter(|opened| opened.kind.is_direct()), ) .any(|community| community.id == community_id) } fn quotes_of(&mut self, message_id: Id) -> impl Iterator { self.session .messages .iter_mut() .filter_map(move |message| match &mut message.reply { Some(Reply::Quote(quote)) if quote.message_id == message_id => Some(quote), _ => None, }) } fn remove_message(&mut self, message_id: Id, builder: bool) { if builder { if let Some(message) = self .session .messages .iter_mut() .find(|existing| existing.id == message_id) { message.deleted = true; message.pinned = false; } } else { self.session .messages .retain(|existing| existing.id != message_id); } for message in &mut self.session.messages { message.reply = match message.reply.take() { Some(Reply::Quote(quote)) if quote.message_id == message_id => { Some(Reply::Deleted(builder.then_some(quote))) } other => other, }; } match &mut self.composer { Composer::Select { ids } => ids.retain(|id| *id != message_id), Composer::Compose { reply } if *reply == Some(message_id) => { self.composer = Composer::Compose { reply: None }; } Composer::Edit { message_id: edited, .. } if *edited == message_id => { self.composer = Composer::Compose { reply: None }; } _ => {} } } pub fn communities(&self) -> &[Community] { &self.session.communities } pub fn notes(&self) -> Option<&Community> { self.session .communities .iter() .find(|community| matches!(community.kind, CommunityKind::Notes)) } fn insert_messages(&mut self, messages: impl IntoIterator, me: Option) { let newest = self.session.messages.last().map(|message| message.id); for message in messages { self.session .messages .retain(|existing| existing.id != message.id); self.session.messages.push(message); } self.session.messages.sort_by_key(|message| message.id); if self.session.messages.last().map(|message| message.id) != newest { let mine = self .session .messages .last() .is_some_and(|message| Some(message.user_id) == me); if newest.is_none() { match self.unread_divider(me) { Some(index) => self.scroll_to_index(index), None => self.scroll.scroll_to_bottom(), } } else if !self.away() { let newest = self.session.messages.last().map_or(0, |message| message.id); self.session.glide = Some((newest, self.scroll.offset().y, Instant::now())); self.session.unseen = 0; } else if mine { self.jump_to_bottom(); } else { self.session.unseen += 1; } } self.reveal_jump(); } fn reveal_jump(&mut self) { let Some(message_id) = self.session.jump.as_ref() else { return; }; let Some(position) = self .session .messages .iter() .position(|message| &message.id == message_id) else { return; }; self.scroll_to_index(position); self.session.highlight = self .session .jump .take() .map(|message_id| (message_id, Instant::now())); } fn scroll_to_index(&self, position: usize) { let spacer = 1; let older = usize::from(self.session.history == History::More); self.scroll.scroll_to_item(spacer + older + position); } fn away(&self) -> bool { self.scroll.max_offset().y + self.scroll.offset().y > self.scroll.bounds().size.height } pub(super) fn engaged(&self, message_id: Id) -> bool { self.session.hover_bar == Some(message_id) || self.session.reacting == Some(message_id) } pub(super) fn jump_to_bottom(&mut self) { self.scroll.scroll_to_bottom(); self.session.unseen = 0; } pub(super) fn settle_scroll(&mut self) { if !self.away() { self.session.unseen = 0; } } fn unread_covered(&self) -> bool { match (&self.session.unread_anchor, self.session.messages.first()) { (Some((anchor, _)), Some(first)) => { self.session.history == History::End || first.id <= *anchor } _ => true, } } fn unread_divider(&self, me: Option) -> Option { let (anchor, _) = self.session.unread_anchor?; if !self.unread_covered() { return None; } self.session .messages .iter() .position(|message| message.id > anchor && Some(message.user_id) != me) } pub(super) fn mark_read(&mut self, community_id: Id, message_id: Id) { let unread = self .session .unread .entry(community_id) .or_insert_with(|| Unread { community_id, ..Default::default() }); unread.messages = 0; unread.mentions = 0; unread.last_read = Some(message_id); } fn add_page(&mut self, page: Vec, me: Option) { self.session.history = History::of_page(page.len()); self.insert_messages(page, me); } fn insert_member(&mut self, member: Member) { style::remember(&[&member.user]); self.remove_member(member.user.id); self.session.members.push(member); self.session.members.sort_by_key(|member| member.user.id); } pub(super) fn remove_member(&mut self, user_id: Id) { if let Some(index) = self .session .members .iter() .position(|member| member.user.id == user_id) { let member = self.session.members.remove(index); self.session.users.insert(member.user.id, member.user); } } fn set_rank(&mut self, user_id: Id, rank: Rank) { if let Some(member) = self .session .members .iter_mut() .find(|member| member.user.id == user_id) { member.rank = rank; } } pub fn community(&self, community_id: Id) -> Option<&Community> { self.session .communities .iter() .chain(self.session.opened.as_ref()) .find(|community| community.id == community_id) } pub fn selected_community(&self) -> Option<&Community> { self.community(self.session.selected_community_id?) } fn member_entry(&self, user_id: Id) -> Option<&Member> { self.session .members .iter() .find(|member| member.user.id == user_id) } pub fn member(&self, user_id: Id) -> Option<&User> { self.member_entry(user_id).map(|member| &member.user) } pub fn author(&self, user_id: Id) -> Option<&User> { self.member(user_id) .or_else(|| self.session.users.get(&user_id)) } fn missing_authors(&self) -> Vec { let mut ids: Vec = if self.session.members.is_empty() { vec![] } else { self.session .messages .iter() .chain(&self.session.pins) .flat_map(|message| { std::iter::once(message.user_id) .chain( message .reply .as_ref() .and_then(Reply::quote) .map(|quote| quote.user_id), ) .chain(message.poll.iter().flat_map(|poll| { poll.options .iter() .flat_map(|option| option.voter_ids.iter().copied()) })) }) .collect() }; if let Some(community_id) = self.voice_community() { ids.extend_from_slice(self.voice_ids(community_id)); } let mut missing: Vec = ids .into_iter() .filter(|id| self.author(*id).is_none() && !self.session.user_requests.contains(id)) .collect(); missing.sort(); missing.dedup(); missing } pub fn rank_of(&self, user: &User) -> Option { let rank = self.member_entry(user.id).map(|member| member.rank); permission::effective_rank(user.role, rank) } pub fn rank_of_id(&self, user_id: Id) -> Option { self.member(user_id).and_then(|user| self.rank_of(user)) } pub fn can_pin(&self, me: &User) -> bool { let direct = self .selected_community() .is_some_and(|community| community.kind.is_direct()); permission::can_pin(self.rank_of(me), direct) } fn update_pin(&mut self, message: &Message) { self.session.pins.retain(|pin| pin.id != message.id); if message.pinned { self.session.pins.push(message.clone()); self.session .pins .sort_by_key(|pin| std::cmp::Reverse(pin.id)); } } pub fn can_delete(&self, message: &Message, me: &User) -> bool { permission::can_delete_message( self.rank_of(me), self.rank_of_id(message.user_id), message.user_id == me.id, ) } pub fn update_member(&mut self, user: &User) { style::remember(&[user]); let peers = self.session .communities .iter_mut() .filter_map(|community| match &mut community.kind { CommunityKind::Direct { peer } => Some(peer), CommunityKind::Group | CommunityKind::Notes => None, }); let known = self .session .friends .friends .iter_mut() .chain(self.session.friends.incoming.iter_mut()) .chain(self.session.friends.outgoing.iter_mut()) .chain( self.session .invitations .iter_mut() .map(|invitation| &mut invitation.inviter), ) .chain( self.session .members .iter_mut() .map(|member| &mut member.user), ) .chain(self.session.users.values_mut()) .chain(peers); for existing in known.filter(|existing| existing.id == user.id) { *existing = user.clone(); } } pub(super) fn insert_community(&mut self, community: Community) { self.session .communities .retain(|existing| existing.id != community.id); self.session.communities.push(community); self.session .communities .sort_by_key(|community| community.id); } pub(super) fn remove_community(&mut self, community_id: Id) { self.session .communities .retain(|community| community.id != community_id); self.session.unread.remove(&community_id); self.session.voice.remove(&community_id); if self.is_selected(community_id) { self.select(None); } } fn replace_communities(&mut self, communities: Vec) { self.session.communities = communities; if self.selected_community().is_none() { self.select(None); } } pub fn reset(&mut self) { self.select(None); let camera_task = self.session.camera_task.take(); self.session = Session::default(); self.session.camera_task = camera_task; self.admin.clear(); } pub fn voice_community(&self) -> Option { match &self.session.voice_state { VoiceState::Off => None, VoiceState::In { community_id, .. } => Some(*community_id), } } pub fn voice_room(&self) -> Option<&Community> { self.community(self.voice_community()?) } pub fn in_voice(&self, community_id: Id) -> bool { self.voice_community() == Some(community_id) } pub fn voice_flags(&self) -> Option<(bool, bool)> { match &self.session.voice_state { VoiceState::Off => None, VoiceState::In { muted, deafened, .. } => Some((*muted, *deafened)), } } pub fn voice_enabled(&self, community_id: Id) -> bool { self.community(community_id) .is_some_and(|community| community.voice_enabled) } pub fn share_of(&self, community_id: Id, user_id: Id, kind: Kind) -> Option<&Share> { self.session .shares .get(&community_id)? .iter() .find(|share| share.user_id == user_id && share.kind == kind) } pub fn voice_ids(&self, community_id: Id) -> &[Id] { self.session .voice .get(&community_id) .map(Vec::as_slice) .unwrap_or_default() } pub fn set_voice_off(&mut self) { self.session.voice_state = VoiceState::Off; self.session.waves.clear(); self.session.voice_task = None; self.session.stats.voice.clear(); self.session.stats.traffic.clear(); self.session.stats.share = ShareSample::default(); self.session.share_loss.clear(); } pub fn record_share(&mut self, sample: ShareSample) { for (kind, stat) in &sample.sending { tracing::debug!( target: "metrics", ?kind, kbps = stat.kbps, fps = stat.fps, gap50 = stat.gap_ms.0, gap95 = stat.gap_ms.1, "send" ); } for (_, kind, stat) in &sample.watching { tracing::debug!( target: "metrics", ?kind, kbps = stat.kbps, fps = stat.fps, loss = stat.loss, keyframes = stat.keyframes, latency = stat.latency_ms, buffer = stat.buffer_ms, nacks = stat.nacks, shown = stat.shown_fps, dropped = stat.dropped, interval50 = stat.interval_ms.0, interval95 = stat.interval_ms.1, swing = stat.swing_ms, "watch" ); } self.session.share_loss.retain(|key, _| { sample .watching .iter() .any(|(user_id, kind, _)| (*user_id, *kind) == *key) }); for (user_id, kind, stats) in &sample.watching { let history = self .session .share_loss .entry((*user_id, *kind)) .or_default(); history.push_back((common::time::now_ms(), stats.loss)); while history.len() > SAMPLE_HISTORY { history.pop_front(); } } self.session.stats.share = sample; } } fn empty_state(t: Tokens) -> impl IntoElement { div() .flex_1() .flex() .items_center() .justify_center() .gap(px(space::SM)) .text_color(t.dim()) .child( div() .px(px(space::XS)) .rounded(px(radius::SM)) .border_1() .border_color(t.thread()) .text_size(text(text::CAPTION)) .child(super::keys::label("K")), ) .child(w().jump.placeholder) } pub(super) fn create_community( this: &mut Yumush, name: String, window: &mut Window, cx: &mut Context, ) { let network = this.network.clone(); cx.spawn_in(window, async move |this, cx| { let Some(community) = ok_or_notify(network.call(CreateCommunity { name }).await, &this, cx) else { return; }; let _ = this.update_in(cx, |yumush, window, cx| { window.close_dialog(cx); yumush.enter_community(community, window, cx); }); }) .detach(); } impl Yumush { pub(super) fn toggle_stats(&mut self, at: StatsAt) { self.chat.stats_at = (self.chat.stats_at != Some(at)).then_some(at); self.refresh_usage(); } pub(super) fn refresh_usage(&mut self) { if let Some(usage) = self.chat.usage_monitor.latest() { self.chat.session.stats.usage = Some(usage); } } pub(super) fn chat_page(&self, cx: &mut Context) -> impl IntoElement { let t = Tokens::of(cx); let entity = cx.entity(); div() .flex() .flex_row() .size_full() .when(self.chat.session.view == View::Chat, |page| { page.child(self.sidebar(&entity, t)) }) .relative() .on_mouse_move({ let entity = entity.clone(); move |event, window, cx| { entity.update(cx, |yumush, cx| yumush.float_moved(event, window, cx)) } }) .child(self.main_panel(&entity, t, cx)) .children(self.floating_viewer(&entity, t)) .children(self.fullscreen_viewer(&entity, t)) } fn main_panel(&self, entity: &Entity, t: Tokens, cx: &App) -> impl IntoElement { div() .flex_1() .min_w_0() .flex() .flex_col() .relative() .bg(t.ground()) .overflow_hidden() .children(self.announcement_banner(entity, t)) .children(self.call_banner(entity, t)) .map(|panel| match self.chat.session.view { View::Settings => panel.child(self.settings_page(entity, t, cx)), View::Builder => panel.child(self.builder_page(entity, t, cx)), View::CommunitySettings => panel.child(self.community_settings_page(entity, t, cx)), View::Chat => match self.chat.session.selected_community_id { Some(_) => { let viewer = self.inline_viewer(entity, t); let grid = viewer .is_none() .then(|| { self.stage_grid(entity, t, cx) .map(IntoElement::into_any_element) }) .flatten(); panel .child(self.header(entity, t)) .children(self.stage_strip(entity, t)) .children(self.unread_bar(entity, t)) .children(self.poll_banner(entity, t)) .child(self.chat_body(entity, t, viewer, grid, cx)) } None => panel.child(empty_state(t)), }, }) .children(self.stats_sheet(t)) .children(self.dock(entity, t, cx)) } fn chat_body( &self, entity: &Entity, t: Tokens, viewer: Option
, grid: Option, cx: &App, ) -> AnyElement { let chat = || { div() .size_full() .flex() .flex_col() .child(self.message_area(entity, t)) .child(self.composer(entity, t, cx)) }; let members = members_column(entity, self, t); match (viewer, grid, members) { (None, Some(grid), Some(members)) => div() .flex_1() .min_h_0() .child( h_resizable("stage_split") .child( resizable_panel() .size_range(px(size::PAGE)..gpui_kit::Pixels::MAX) .child(div().size_full().flex().flex_col().child(grid)), ) .child( resizable_panel() .size(px(size::MARGIN_CHAT)) .size_range(px(size::MARGIN)..px(size::MARGIN * 2.)) .fixed() .child( v_resizable("side_split") .child( resizable_panel() .size_range( px(size::ROW * 2.)..gpui_kit::Pixels::MAX, ) .child(members.size_full()), ) .child( resizable_panel() .size_range( px(size::THUMB * 2.)..gpui_kit::Pixels::MAX, ) .child(chat()), ), ), ), ) .into_any_element(), (viewer, grid, members) => div() .flex_1() .min_h_0() .flex() .child(div().flex_1().min_w_0().flex().flex_col().map(|panel| { match (viewer, grid) { (Some(viewer), _) => panel.child(viewer), (None, Some(grid)) => panel.child(grid), (None, None) => panel.child(chat()), } })) .children(members.map(|members| { div() .w(px(size::MARGIN)) .flex_none() .h_full() .flex() .flex_col() .border_l_1() .border_color(t.thread()) .child(members.flex_1().min_h_0()) })) .into_any_element(), } } fn stats_sheet(&self, t: Tokens) -> Option { let at = self .chat .stats_at .filter(|_| self.chat.voice_community().is_some())?; Some( super::parts::surface(t) .id("stats_sheet") .absolute() .right(px(space::LG)) .map(|sheet| match at { StatsAt::Header => sheet.top(px(size::ROW)), StatsAt::Dock => sheet.bottom(px(size::ROW + space::MD + space::SM)), }) .max_w(relative(0.95)) .max_h(relative(0.8)) .overflow_y_scroll() .p(px(match at { StatsAt::Header => space::XL, StatsAt::Dock => space::LG, })) .child(voice_stats::stats_panel( &self.chat.session.stats, &|id| self.chat.name_of(id), match at { StatsAt::Header => voice_stats::Detail::Full, StatsAt::Dock => voice_stats::Detail::Connection, }, t, )), ) } fn announcement_banner(&self, entity: &Entity, t: Tokens) -> Option
{ let text = self.announcement()?; Some( accent_bar(t) .child(super::glyph::line( text.to_string().into(), super::text(super::style::text::UI), )) .child( clickable( "dismiss_announcement", t, entity_action(entity, |yumush, _, cx| yumush.dismiss_announcement(cx)), ) .child("×"), ), ) } fn header(&self, entity: &Entity, t: Tokens) -> impl IntoElement { let community = self.chat.selected_community(); let name = community.map(community_name).unwrap_or_default(); let group = community.is_some_and(|community| community.kind.is_group()); let voice = self.voice_toggle(entity, t); let peer = community.and_then(|community| match &community.kind { CommunityKind::Direct { peer } => Some(self.chat.author(peer.id).unwrap_or(peer)), _ => None, }); let room = community.filter(|_| group); let title = super::parts::words( name.to_string(), super::parts::Text::Title, super::parts::Ink::Paper, t, ); div() .h(px(size::ROW + space::MD)) .px(px(space::XL)) .flex() .items_center() .gap(px(space::SM)) .child(match (peer, room) { (Some(peer), _) => super::profile::profile_popover( "header_peer", Anchor::TopLeft, peer, entity, div() .cursor_pointer() .flex() .items_center() .gap(px(space::SM)) .child(super::avatar( t, peer, px(size::AVATAR), super::text(super::style::text::CAPTION), &self.chat.session.avatars, )) .child(title), ) .into_any_element(), (None, Some(room)) => super::community_card::community_popover( room, entity, div() .cursor_pointer() .flex() .items_center() .gap(px(space::SM)) .child(super::community_icon( t, room, px(size::AVATAR), super::text(super::style::text::CAPTION), &self.chat.session.avatars, )) .child(title), ) .into_any_element(), _ => div() .flex() .items_center() .gap(px(space::SM)) .children(community.map(|community| { super::zoomable( entity, "header_picture", super::community_icon( t, community, px(size::AVATAR), super::text(super::style::text::CAPTION), &self.chat.session.avatars, ), super::Zoom::new( super::picture_of(community, &self.chat.session.avatars), !community.kind.is_group(), name.to_string(), ), ) })) .child(title) .into_any_element(), }) .child(div().flex_1()) .children( community .is_some() .then(|| self.stage_controls(entity, t)) .flatten(), ) .children( community .is_some_and(|community| self.chat.joined(community.id)) .then(|| { message_actions::search_popover( &self.chat, self.settings.clock(), entity, t, ) }), ) .children( (community.is_some() && !self.chat.session.pins.is_empty()) .then(|| message_actions::pins_popover(&self.chat, entity, t)), ) .children(self.calling_hint(t)) .children(voice.is_some().then(|| { div() .w(px(stroke::LINE)) .h(px(size::CHIP)) .flex_none() .bg(t.thread()) })) .children(voice) } fn message_area(&self, entity: &Entity, t: Tokens) -> impl IntoElement { div() .flex() .flex_col() .flex_1() .min_h_0() .relative() .child( div() .absolute() .left(px(space::XL)) .top_0() .bottom_0() .w(px(stroke::LINE)) .bg(t.thread()), ) .child(self.message_list(entity, t)) .children(self.jump_bottom(entity, t)) } fn unread_bar(&self, entity: &Entity, t: Tokens) -> Option { let (anchor, count) = self.chat.session.unread_anchor?; if self.chat.unread_covered() { return None; } Some( accent_bar(t).child(w().chat.new_messages(count)).child( div() .flex() .gap(px(space::SM)) .child( clickable( "jump_unread", t, entity_action(entity, move |yumush, window, cx| { yumush.go_to_message(anchor, window, cx) }), ) .child("↑"), ) .child( clickable( "dismiss_unread", t, entity_action(entity, |yumush, _, cx| { yumush.chat.session.unread_anchor = None; cx.notify(); }), ) .child("×"), ), ), ) } fn jump_bottom(&self, entity: &Entity, t: Tokens) -> Option { if !self.chat.away() { return None; } let unseen = self.chat.session.unseen; Some( clickable( "jump_bottom", t, entity_action(entity, |yumush, _, cx| { yumush.chat.jump_to_bottom(); cx.notify(); }), ) .absolute() .right(px(space::LG)) .bottom(px(space::MD)) .size(px(size::CONTROL)) .flex() .items_center() .justify_center() .rounded_full() .border_1() .border_color(t.thread()) .bg(t.ground()) .child(Icon::new(IconName::ArrowDown).size(px(size::ICON))) .children((unseen > 0).then(|| { div() .absolute() .top(px(-space::SM)) .right(px(-space::SM)) .children(unread_badge( t, false, Some(&Unread { messages: unseen, ..Default::default() }), )) })), ) } fn message_list(&self, entity: &Entity, t: Tokens) -> AnyElement { let divider = self .chat .unread_divider(self.user.as_ref().map(|user| user.id)); let entity_scroll = entity.clone(); let glide = self .chat .session .glide .filter(|(_, _, at)| at.elapsed() < GLIDE + GLIDE_SLACK); let list = div() .id("chat_messages") .track_scroll(&self.chat.scroll) .flex() .flex_col() .flex_1() .min_w_0() .overflow_y_scroll() .pl(px(space::XL + space::LG)) .pr(px(space::XL)) .py(px(space::LG)) .gap(px(space::XXS)) .on_scroll(move |_, window, _| { let entity = entity_scroll.clone(); window.on_next_frame(move |_, cx| { entity.update(cx, |yumush, cx| { yumush.chat.settle_scroll(); cx.notify(); }) }); }) .child(div().flex_1()) .children((self.chat.session.history == History::More).then(|| older_button(entity, t))) .children( message_rows( &self.chat.session.messages, &self.chat.session.open_calls, divider, ) .into_iter() .map(|(index, message, first, run)| { let row = render_message( message, first, index > 0, run, &self.chat, self.user.as_ref(), self.settings.clock(), entity, t, ); let row = match glide { Some((id, _, _)) if id == message.id => div() .child(row) .with_animation( format!("chat_arrive_{id}"), gpui_kit::Animation::new(GLIDE), |row, delta| row.opacity(delta), ) .into_any_element(), _ => row, }; if divider == Some(index) { div() .flex() .flex_col() .child(new_divider(t)) .child(row) .into_any_element() } else { row } }), ); let Some((id, from, _)) = glide else { return list.into_any_element(); }; let scroll = self.chat.scroll.clone(); list.with_animation( format!("chat_glide_{id}"), gpui_kit::Animation::new(GLIDE).with_easing(gpui_kit::ease_out_quint()), move |list, delta| { let to = -scroll.max_offset().y; let x = scroll.offset().x; scroll.set_offset(gpui_kit::point(x, from + (to - from) * delta)); list }, ) .into_any_element() } fn composer(&self, entity: &Entity, t: Tokens, cx: &App) -> AnyElement { if let Composer::Select { ids } = &self.chat.composer { return div() .p(px(space::LG)) .child(composer::selection_bar(ids, entity, t)) .into_any_element(); } let input = self.chat.message_input.clone(); let pending = media_view::pending_row(&self.chat.session.media, entity, t); let bar = composer::mode_bar(&self.chat, entity, t); let entity = entity.clone(); if let VoiceNote::Recording { started, levels, .. } = &self.chat.session.media.voice_note { return div() .p(px(space::LG)) .children(pending) .child(voice_note::recording_row(*started, levels, &entity, t)) .into_any_element(); } let ready = self.chat.message_input.read(cx).text().len() > 0 || !self.chat.session.media.pending.is_empty(); composer::format_actions( &self.chat.message_input, div().p(px(space::LG)).border_t_1().border_color(t.thread()), ) .children(pending) .children(bar) .children(self.chat.typing_label().map(|label| { div() .pl(px(space::XS)) .pb(px(space::XS)) .text_size(text(text::CAPTION)) .text_color(t.dim()) .child(label) })) .child( div() .min_h(px(size::ROW)) .pl(px(space::XS)) .pr(px(space::XS)) .py(px(space::XS)) .flex() .items_center() .gap(px(space::SM)) .child(composer::plus_popover(&entity, t)) .child( Textarea::new(&self.chat.message_input) .token(super::glyph::token) .on_paste({ let entity = entity.clone(); move |item, window, cx| { entity.update(cx, |yumush, cx| yumush.paste_files(item, window, cx)) } }) .appearance(false) .text_size(text(text::BODY)) .text_color(t.paper()) .flex_1() .min_w_0(), ) .child(super::glyph::picker_button( "composer_emoji", &entity, t, super::glyph::insert_into(self.chat.message_input.clone()), )) .when(!ready, |this| { this.child(voice_note::mic_button(&entity, t)) }) .when(ready, |this| { this.child( clickable("send_button", t, move |window, cx| { entity .update(cx, |yumush, cx| yumush.submit_composer(&input, window, cx)) }) .tip(w().chat.send) .size(px(size::CONTROL_SM)) .flex() .items_center() .justify_center() .text_color(t.paper()) .child(super::parts::small_icon(IconName::ArrowUp)), ) }), ) .into_any_element() } pub(super) fn select_community( &mut self, community_id: Id, window: &mut Window, cx: &mut Context, ) { if self.chat.session.view == View::Chat && self.chat.is_selected(community_id) { return; } self.show_view(View::Chat, window, cx); self.stop_playing(cx); self.save_draft(cx); self.chat.select(Some(community_id)); if let Some(me) = &self.user && self.settings.last_chats.get(&me.id) != Some(&community_id) { self.settings.last_chats.insert(me.id, community_id); crate::settings::save(&self.settings); } self.restore_draft(community_id, window, cx); self.chat.focus(window, cx); self.load_members(window, cx); self.load_pins(window, cx); self.load_voice(community_id, cx); self.load_shares(community_id, cx); self.load_messages(None, window, cx); cx.notify(); } pub(super) fn enter_community( &mut self, community: Community, window: &mut Window, cx: &mut Context, ) { self.chat.session.friends_open = false; let community_id = community.id; let listed = self .chat .session .communities .iter() .any(|known| known.id == community_id); if community.kind.is_direct() && !listed { self.chat.session.opened = Some(community); } else { self.chat.insert_community(community); } self.request_social_avatars(cx); self.select_community(community_id, window, cx); } pub(super) fn reload(&mut self, window: &mut Window, cx: &mut Context) { self.chat.session.voice.clear(); self.chat.session.shares.clear(); self.load_communities(window, cx); self.load_social(window, cx); if let Some(community_id) = self.chat.session.selected_community_id { self.load_members(window, cx); self.load_pins(window, cx); self.chat.session.messages.clear(); self.load_messages(None, window, cx); self.load_voice(community_id, cx); self.load_shares(community_id, cx); } } pub(super) fn refresh_communities(&self, cx: &mut Context) { let network = self.network.clone(); cx.spawn(async move |this, cx| { let Ok(communities) = network.call(ListCommunities).await else { return; }; let _ = this.update(cx, |yumush, cx| { let known: HashSet = yumush .chat .session .communities .iter() .map(|c| c.id) .collect(); yumush.chat.replace_communities(communities); yumush.end_voice_if_unjoined(cx); let calls: Vec = yumush .chat .session .communities .iter() .filter(|community| !known.contains(&community.id)) .filter(|community| { community.kind.is_direct() && !yumush.chat.in_voice(community.id) && yumush .chat .voice_ids(community.id) .iter() .any(|id| !yumush.is_me(*id)) }) .map(|community| community.id) .collect(); yumush.chat.session.ringing.extend(calls); yumush.update_ringing(cx); yumush.request_social_avatars(cx); cx.notify(); }); }) .detach(); } pub(super) fn load_communities(&self, window: &mut Window, cx: &mut Context) { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { let Some(communities) = ok_or_notify(network.call(ListCommunities).await, &this, cx) else { return; }; let unreads = network.call(ListUnreads).await.unwrap_or_default(); let _ = this.update_in(cx, |yumush, window, cx| { yumush.chat.session.unread = unreads .into_iter() .map(|unread| (unread.community_id, unread)) .collect(); yumush.chat.replace_communities(communities); yumush.end_voice_if_unjoined(cx); yumush.request_social_avatars(cx); if yumush.chat.session.selected_community_id.is_none() { let last = yumush .user .as_ref() .and_then(|me| yumush.settings.last_chats.get(&me.id)) .copied(); let communities = &yumush.chat.session.communities; let start = last .filter(|last| communities.iter().any(|community| community.id == *last)) .or_else(|| communities.first().map(|community| community.id)); if let Some(community_id) = start { yumush.select_community(community_id, window, cx); } } cx.notify(); }); }) .detach(); } fn search_community(&self, window: &mut Window, cx: &mut Context) { let Some(community_id) = self.chat.session.selected_community_id else { return; }; let text = search_text(&self.chat.community_search, cx); if text.is_empty() { return; } let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { let Some(hits) = ok_or_notify( network.call(SearchCommunity { community_id, text }).await, &this, cx, ) else { return; }; let _ = this.update(cx, |yumush, cx| { if yumush.chat.is_selected(community_id) { yumush.chat.session.community_hits = hits; cx.notify(); } }); }) .detach(); } fn load_pins(&self, window: &mut Window, cx: &mut Context) { let Some(community_id) = self.chat.session.selected_community_id else { return; }; let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { let Some(pins) = ok_or_notify(network.call(ListPins { community_id }).await, &this, cx) else { return; }; let _ = this.update(cx, |yumush, cx| { if yumush.chat.is_selected(community_id) { yumush.chat.session.pins = pins; yumush.request_poll_votes(cx); cx.notify(); } }); }) .detach(); } fn load_members(&self, window: &mut Window, cx: &mut Context) { let Some(community_id) = self.chat.session.selected_community_id else { return; }; let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { let Some(members) = ok_or_notify(network.call(ListMembers { community_id }).await, &this, cx) else { return; }; 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 .session .users .insert(member.user.id, member.user.clone()); } style::remember( &members .iter() .map(|member| &member.user) .collect::>(), ); let old = std::mem::replace(&mut yumush.chat.session.members, members); yumush .chat .session .users .extend(old.into_iter().map(|member| (member.user.id, member.user))); yumush.load_bans(window, cx); yumush.request_authors(cx); cx.notify(); } }); }) .detach(); } pub(super) fn request_authors(&mut self, cx: &mut Context) { let missing = self.chat.missing_authors(); if missing.is_empty() { return; } self.chat .session .user_requests .extend(missing.iter().copied()); let network = self.network.clone(); cx.spawn(async move |this, cx| { for user_id in missing { let user = match network.call(GetUser { user_id }).await { Ok(user) => user, Err(error) => { if !matches!(error, Fail::Server(_)) { let _ = this.update(cx, |yumush, _| { yumush.chat.session.user_requests.remove(&user_id); }); } continue; } }; let _ = this.update(cx, |yumush, cx| { yumush.request_user_avatar(&user, cx); style::remember(&[&user]); yumush.chat.session.users.insert(user.id, user); cx.notify(); }); } }) .detach(); } pub(super) fn load_bans(&self, window: &mut Window, cx: &mut Context) { if !permission::is_moderator(self.actor_rank()) { return; } let Some(community_id) = self.chat.session.selected_community_id else { return; }; let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { let Some(bans) = ok_or_notify(network.call(ListBans { community_id }).await, &this, cx) else { 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.session.bans = bans; cx.notify(); } }); }) .detach(); } pub(super) fn go_to_message( &mut self, message_id: Id, window: &mut Window, cx: &mut Context, ) { self.chat.session.jump = Some(message_id); self.chat.reveal_jump(); self.continue_jump(window, cx); cx.notify(); } fn continue_jump(&mut self, window: &mut Window, cx: &mut Context) { if self.chat.session.jump.is_none() { Self::fade_highlight(cx); } else if self.chat.session.history == History::More { self.load_older_messages(window, cx); } else { self.chat.session.jump = None; } } fn fade_highlight(cx: &mut Context) { cx.spawn(async move |this, cx| { cx.background_executor().timer(HIGHLIGHT_TTL).await; let _ = this.update(cx, |_, cx| cx.notify()); }) .detach(); } fn load_older_messages(&self, window: &mut Window, cx: &mut Context) { let Some(oldest_id) = self.chat.session.messages.first().map(|message| message.id) else { return; }; self.load_messages(Some(oldest_id), window, cx); } fn load_messages(&self, before: Option, window: &mut Window, cx: &mut Context) { let Some(community_id) = self.chat.session.selected_community_id else { return; }; let network = self.network.clone(); let latest = before.is_none() && window.is_window_active(); cx.spawn_in(window, async move |this, cx| { if before.is_none() { let _ = network .call(WatchCommunity { community_id: Some(community_id), }) .await; } let Some(page) = ok_or_notify( network .call(ListMessages { community_id, before, }) .await, &this, cx, ) else { return; }; let _ = this.update_in(cx, |yumush, window, cx| { if yumush.chat.is_selected(community_id) { let newest = page.last().map(|message| message.id); let seeking = yumush.chat.session.jump.is_some(); yumush .chat .add_page(page, yumush.user.as_ref().map(|user| user.id)); if seeking { yumush.continue_jump(window, cx); } if let Some(message_id) = newest.filter(|_| latest) { yumush.mark_read(community_id, message_id, cx); } yumush.request_media(cx); yumush.request_poll_votes(cx); yumush.request_authors(cx); cx.notify(); } }); }) .detach(); } pub(super) fn request_message_delete( &mut self, message_id: Id, window: &mut Window, cx: &mut Context, ) { let armed = Armed::DeleteMessage(message_id); if self.chat.session.armed.as_ref() == Some(&armed) { self.chat.session.armed = None; self.delete_message(message_id, window, cx); } else { self.chat.session.armed = Some(armed.clone()); cx.spawn(async move |this, cx| { cx.background_executor().timer(DELETE_CONFIRM).await; let _ = this.update(cx, |yumush, cx| { if yumush.chat.session.armed.as_ref() == Some(&armed) { yumush.chat.session.armed = None; cx.notify(); } }); }) .detach(); } cx.notify(); } pub(super) fn delete_message( &self, message_id: Id, window: &mut Window, cx: &mut Context, ) { let network = self.network.clone(); spawn_done(window, cx, async move { network.call(DeleteMessage { message_id }).await }); } pub(super) fn load_edits(&self, message_id: Id, cx: &mut Context) { let network = self.network.clone(); cx.spawn(async move |this, cx| { let edits = match network.call(ListEdits { message_id }).await { Ok(edits) => edits, Err(error) => { tracing::warn!("list edits failed: {error}"); return; } }; let _ = this.update(cx, |yumush, cx| { yumush.chat.session.edits.insert(message_id, edits); cx.notify(); }); }) .detach(); } pub(super) fn leave_community( &self, community_id: Id, window: &mut Window, cx: &mut Context, ) { let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { if let Err(error) = network.call(LeaveCommunity { community_id }).await { notify_error(&this, cx, error); return; } let _ = this.update(cx, |yumush, cx| { yumush.forget_community(community_id, cx); cx.notify(); }); }) .detach(); } fn load_voice(&self, community_id: Id, cx: &mut Context) { let network = self.network.clone(); cx.spawn(async move |this, cx| { let Ok(participants) = network.call(ListVoiceParticipants { community_id }).await else { return; }; let _ = this.update(cx, |yumush, cx| { yumush.chat.session.voice.insert(community_id, participants); yumush.request_authors(cx); cx.notify(); }); }) .detach(); } pub(super) fn toggle_voice( &mut self, community_id: Id, 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(); } self.join_voice(community_id, (muted, deafened), was_in, window, cx); } fn join_voice( &mut self, community_id: Id, (muted, deafened): (bool, bool), was_in: bool, window: &mut Window, cx: &mut Context, ) { let network = self.network.clone(); let voice_settings = self.settings.voice.clone(); cx.spawn_in(window, async move |this, cx| { if was_in { let _ = network.leave_voice().await; } match network.join_voice(community_id, &voice_settings).await { Ok(participants) => { network.set_deafened(deafened); let _ = this.update_in(cx, |yumush, _, cx| { let muted = muted || yumush.is_server_muted() || yumush.hidden_in(community_id); yumush.network.set_muted(muted); yumush.chat.session.voice.insert(community_id, participants); yumush.request_authors(cx); yumush.load_shares(community_id, cx); yumush.chat.session.voice_state = VoiceState::In { community_id, muted, deafened, since: Instant::now(), }; 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) { let Some(community_id) = self.chat.voice_community() else { return; }; self.chat.set_voice_off(); let network = self.network.clone(); cx.spawn(async move |this, cx| { let _ = network.leave_voice().await; let _ = this.update(cx, |yumush, cx| { yumush.load_voice(community_id, cx); yumush.load_shares(community_id, cx); }); }) .detach(); } pub(super) fn refresh_voice(&mut self, cx: &mut Context) { let Some(community_id) = self.chat.voice_community() else { return; }; self.load_voice(community_id, cx); self.load_shares(community_id, cx); } pub(super) fn leave_voice_in(&mut self, community_id: Id, cx: &mut Context) { if self.chat.in_voice(community_id) { self.end_voice(cx); } } pub(super) fn forget_community(&mut self, community_id: Id, cx: &mut Context) { self.leave_voice_in(community_id, cx); self.chat.remove_community(community_id); } pub(super) fn end_voice_if_unjoined(&mut self, cx: &mut Context) { if let Some(community_id) = self.chat.voice_community() && !self.chat.joined(community_id) { self.end_voice(cx); } } pub(super) fn is_server_muted(&self) -> bool { self.user .as_ref() .is_some_and(|me| self.chat.session.server_muted.contains(&me.id)) } fn hidden_in(&self, community_id: Id) -> bool { self.chat.session.ghost || !self.chat.joined(community_id) } pub(super) fn hidden_in_voice(&self) -> bool { self.chat .voice_community() .is_some_and(|community_id| self.hidden_in(community_id)) } pub(super) fn toggle_mute(&mut self, window: &mut Window, cx: &mut Context) { if self.is_server_muted() { return; } let Some((muted, _)) = self.chat.voice_flags() else { return; }; if muted && self.hidden_in_voice() { self.confirm_ghost_speak(window, cx); return; } self.set_muted(!muted, cx); } pub(super) fn set_muted(&mut self, value: bool, cx: &mut Context) { self.set_call_muted(value); cx.notify(); } pub(super) fn set_call_muted(&mut self, value: bool) { if let VoiceState::In { muted, .. } = &mut self.chat.session.voice_state { *muted = value; self.network.set_muted(value); } } fn confirm_ghost_speak(&mut self, window: &mut Window, cx: &mut Context) { let entity = cx.entity(); window.open_dialog(cx, move |dialog, _, cx| { let t = Tokens::of(cx); let speak = entity.clone(); dialog.title(w().chat.ghost_title).child( div() .flex() .flex_col() .gap(px(space::LG)) .child( div() .text_size(text(text::LABEL)) .text_color(t.dim()) .child(w().chat.ghost_hint), ) .child( div() .flex() .justify_end() .gap(px(space::SM)) .child(parts::button( "ghost_speak_cancel", w().chat.cancel, parts::Press::Plain, t, |window, cx| window.close_dialog(cx), )) .child(parts::button( "ghost_speak_confirm", w().chat.speak, parts::Press::Primary, t, move |window, cx| { window.close_dialog(cx); speak.update(cx, |yumush, cx| yumush.set_muted(false, cx)); }, )), ), ) }); } pub(super) fn toggle_deafen(&mut self, cx: &mut Context) { if let VoiceState::In { deafened, .. } = &mut self.chat.session.voice_state { *deafened = !*deafened; self.network.set_deafened(*deafened); } cx.notify(); } pub(super) fn start_stats_push(&mut self, cx: &mut Context) { let network = self.network.clone(); self.chat.session.stats_task = Some(cx.spawn(async move |this, cx| { loop { let Ok(stats) = this.update(cx, |yumush, _| { yumush.refresh_usage(); yumush.chat.session.stats.clone() }) else { break; }; let _ = network.call(PushStats { stats }).await; cx.background_executor().timer(VOICE_SAMPLE_INTERVAL).await; } })); } fn start_voice_poll(&mut self, cx: &mut Context) { let network = self.network.clone(); self.chat.session.voice_task = Some(cx.spawn(async move |this, cx| { let mut sampled = Instant::now(); loop { cx.background_executor().timer(WAVE_INTERVAL).await; let levels = network.levels(); let due = sampled.elapsed() >= VOICE_SAMPLE_INTERVAL; if due { sampled = Instant::now(); } let sample = due.then(|| network.voice_sample()).flatten(); let share = due.then(|| network.share_sample()); let polling = this.update(cx, |yumush, cx| { if yumush.chat.voice_community().is_none() { return false; } if due { yumush.refresh_usage(); } if let Some(share) = share { if let Some(sample) = &sample { let up = sample.traffic.up_kbps + share .sending .iter() .map(|(_, layer)| layer.kbps as f32) .sum::(); let down = sample.traffic.down_kbps + share .watching .iter() .map(|(_, _, stats)| stats.kbps as f32) .sum::(); let traffic = &mut yumush.chat.session.stats.traffic; traffic.push_back((sample.at_ms, up, down)); while traffic.len() > SAMPLE_HISTORY { traffic.pop_front(); } } yumush.chat.record_share(share); } if let Some(sample) = sample { let samples = &mut yumush.chat.session.stats.voice; tracing::debug!( target: "metrics", up = sample.traffic.up_kbps, down = sample.traffic.down_kbps, loss = sample.traffic.loss, buffer = sample.traffic.buffer_ms, "voice" ); samples.push_back(sample); while samples.len() > SAMPLE_HISTORY { samples.pop_front(); } } if due { cx.notify(); } yumush.update_waves(levels, cx); true }); if !matches!(polling, Ok(true)) { break; } } })); } pub(super) fn open_user_volume(&mut self, user_id: Id, cx: &mut Context) { let in_call = self .chat .voice_community() .is_some_and(|community_id| self.chat.voice_ids(community_id).contains(&user_id)); if !in_call || self.is_me(user_id) { self.chat.session.volume_popover = None; return; } let volume = self.user_volume(user_id); let slider = cx.new(|_| { SliderState::new() .min(*VOLUME.start()) .max(*VOLUME.end()) .default_value(volume) }); let subscription = cx.subscribe(&slider, move |this, _, event: &SliderEvent, cx| { let SliderEvent::Change(value) = event else { return; }; this.set_user_volume(user_id, value.start()); this.commit_settings(cx); }); self.chat.session.volume_popover = Some(UserVolume { user_id, slider, _subscription: subscription, }); } pub(super) fn toggle_user_mute( &mut self, user_id: Id, window: &mut Window, cx: &mut Context, ) { let volume = if self.user_volume(user_id) == 0. { DEFAULT_USER_VOLUME } else { 0. }; self.set_user_volume(user_id, volume); if let Some(user_volume) = self.chat.session.volume_popover.as_ref() { user_volume .slider .update(cx, |slider, cx| slider.set_value(volume, window, cx)); } self.commit_settings(cx); } fn set_user_volume(&mut self, user_id: Id, volume: f32) { let volumes = &mut self.settings.voice.user_volumes; if volume == DEFAULT_USER_VOLUME { volumes.remove(&user_id); } else { volumes.insert(user_id, volume); } } pub(super) fn user_volume(&self, user_id: Id) -> f32 { self.settings .voice .user_volumes .get(&user_id) .copied() .unwrap_or(DEFAULT_USER_VOLUME) } fn update_waves(&mut self, levels: Levels, cx: &mut Context) { let deafened = self .chat .voice_flags() .is_some_and(|(_, deafened)| deafened); let me = self.user.as_ref().map(|user| user.id); if self.chat.session.waves.update(levels, me, deafened) { cx.notify(); } } fn voice_toggle(&self, entity: &Entity, t: Tokens) -> Option { let community_id = self.chat.session.selected_community_id?; let direct = self.is_direct(community_id); let in_voice = self.chat.in_voice(community_id); if !direct || !(in_voice || self.can_join_voice(community_id)) { return None; } let users = self.voice_users(community_id); let (icon, label) = if in_voice { (IconName::PhoneOff, w().chat.hang_up) } else { (IconName::Phone, w().chat.call) }; let ink = if in_voice { super::parts::Ink::Bad } else if users.is_empty() { super::parts::Ink::Dim } else { super::parts::Ink::Paper }; let entity = entity.clone(); let on_click = move |window: &mut Window, cx: &mut App| { entity.update(cx, |yumush, cx| { yumush.toggle_voice(community_id, window, cx) }) }; let hov = t.hov(); Some( div() .id(format!("voice_toggle_{in_voice}")) .h(px(size::CONTROL_SM)) .px(px(space::MD)) .flex() .items_center() .gap(px(space::SM)) .rounded(px(radius::MD)) .cursor_pointer() .hover(move |style| style.bg(hov)) .text_color(ink.color(t)) .on_click(move |_, window, cx| on_click(window, cx)) .child(super::parts::small_icon(icon)) .child(super::parts::words(label, super::parts::Text::Ui, ink, t)), ) } fn can_join_voice(&self, community_id: Id) -> bool { permission::is_member(self.actor_rank()) && (self.is_builder() || self.chat.voice_enabled(community_id)) && self .chat .notes() .is_none_or(|notes| notes.id != community_id) } fn voice_users(&self, community_id: Id) -> Vec<&User> { self.chat .voice_ids(community_id) .iter() .filter(|id| !(self.chat.session.ghost && self.is_me(**id))) .filter_map(|id| self.chat.member(*id)) .collect() } fn calling_hint(&self, t: Tokens) -> Option
{ let community = self.chat.selected_community()?; let direct = self.is_direct(community.id); let alone = self.chat.in_voice(community.id) && self .chat .voice_ids(community.id) .iter() .all(|id| self.is_me(*id)); (direct && alone).then(|| { div() .text_color(t.dim()) .text_size(text(text::CAPTION)) .child(w().chat.calling) }) } fn call_banner(&self, entity: &Entity, t: Tokens) -> Option
{ let (community_id, caller) = self.incoming_call()?; Some( accent_bar(t) .child( div() .flex() .items_center() .gap(px(space::SM)) .child(super::parts::small_icon(IconName::PhoneIncoming)) .child(w().chat.is_calling(&caller.username)), ) .child( div() .flex() .gap(px(space::SM)) .child( clickable( "accept_call", t, entity_action(entity, move |yumush, window, cx| { yumush.accept_call(community_id, window, cx) }), ) .text_color(t.hue(Hue::Mint)) .font_weight(FontWeight::MEDIUM) .px(px(space::SM)) .rounded(px(radius::SM)) .child(w().chat.accept), ) .child( clickable( "decline_call", t, entity_action(entity, move |yumush, window, cx| { yumush.decline_call(community_id, window, cx) }), ) .text_color(t.bad()) .font_weight(FontWeight::MEDIUM) .px(px(space::SM)) .rounded(px(radius::SM)) .child(w().chat.decline), ), ), ) } fn incoming_call(&self) -> Option<(Id, User)> { self.chat.communities().iter().find_map(|community| { let CommunityKind::Direct { peer } = &community.kind else { return None; }; let calling = self.user.is_some() && self .chat .voice_ids(community.id) .iter() .any(|id| !self.is_me(*id)); let ringing = calling && !self.chat.in_voice(community.id) && self.chat.session.ringing.contains(&community.id); ringing.then(|| (community.id, peer.clone())) }) } fn ring_allowed(&self, community_id: Id) -> bool { self.user .as_ref() .is_some_and(|me| self.presence_of(me.id) == Presence::Online) && !self.chat.session.muted.contains(&community_id) } pub(super) fn update_ringing(&mut self, cx: &mut Context) { if self.incoming_call().is_none() { self.chat.session.ring_task = None; return; } if self.chat.session.ring_task.is_some() { return; } self.chat.session.ring_task = Some(cx.spawn(async move |this, cx| { for _ in 0..RING_LIMIT { let ringing = this.update(cx, |yumush, _| match yumush.incoming_call() { Some((community_id, _)) => { if yumush.ring_allowed(community_id) { crate::voice::play_sound( crate::voice::Sound::Ring, &yumush.settings.voice, ); } true } None => false, }); if !matches!(ringing, Ok(true)) { break; } cx.background_executor().timer(RING_INTERVAL).await; } })); } fn accept_call(&mut self, community_id: Id, window: &mut Window, cx: &mut Context) { self.chat.session.ringing.remove(&community_id); self.select_community(community_id, window, cx); self.toggle_voice(community_id, window, cx); self.update_ringing(cx); } fn decline_call(&mut self, community_id: Id, window: &mut Window, cx: &mut Context) { self.chat.session.ringing.remove(&community_id); self.update_ringing(cx); cx.notify(); let network = self.network.clone(); spawn_done(window, cx, async move { network.call(DeclineCall { community_id }).await }); } fn stage_controls(&self, entity: &Entity, t: Tokens) -> Option { let community_id = self.chat.session.selected_community_id?; if self.voice_users(community_id).is_empty() || !self.in_stage_chat() { return None; } let current = self.chat.stage; Some( div() .ml(px(space::SM)) .flex() .items_center() .gap(px(space::XXS)) .child(stage_button( entity, t, Stage::Strip, current == Stage::Strip, IconName::GalleryHorizontal, "Strip", w().chat.strip, )) .child(stage_button( entity, t, Stage::Grid, current == Stage::Grid, IconName::LayoutGrid, "Grid", w().chat.grid, )) .child(stats_button( entity, t, self.chat.stats_at == Some(StatsAt::Header), )), ) } } struct MemberRow { user: User, in_voice: bool, muted: bool, presence: Presence, } fn members_column( entity: &Entity, yumush: &Yumush, t: Tokens, ) -> Option> { let chat = &yumush.chat; let community_id = chat.session.selected_community_id?; let group = chat .selected_community() .is_some_and(|community| community.kind.is_group()); if !group { return None; } let voice = chat.voice_ids(community_id); let members: Vec = chat .session .members .iter() .map(|member| MemberRow { user: member.user.clone(), in_voice: voice.contains(&member.user.id), muted: chat.session.server_muted.contains(&member.user.id), presence: yumush.presence_of(member.user.id), }) .collect(); let avatars = &chat.session.avatars; let entity = entity.clone(); let row = |MemberRow { user, in_voice, muted, presence, }: &MemberRow| { let watch = |kind: Kind| { (*in_voice && chat.share_of(community_id, user.id, kind).is_some()).then(|| { super::sidebar::watch_pill( &entity, user.id, kind, yumush.is_watching(user.id, kind), (kind == Kind::Screen && chat.session.waves.share_audible(user.id)) .then(|| chat.session.waves.share(user.id).map(to_bands)) .flatten(), t, ) }) }; let line = in_voice.then(|| { let speaking = chat.session.waves.speaking.contains(&user.id); div() .flex_1() .min_w(px(size::CONTROL)) .h(px(space::LG)) .child(super::parts::voice_line( chat.session.waves.voice(user.id).map(to_bands).as_ref(), if speaking { super::parts::Voice::Live(t.person(user.id)) } else { super::parts::Voice::Quiet }, t, )) }); div() .flex() .items_center() .gap(px(space::XS)) .child( div() .min_w_0() .when(!in_voice, |this| this.flex_1()) .child(profile_popover( format!("member_{}", user.id), Anchor::RightCenter, user, &entity, hoverable( format!("member_trigger_{}", user.id), div() .h(px(size::CONTROL)) .px(px(space::SM)) .flex() .items_center() .gap(px(space::SM)) .rounded(px(radius::MD)) .child(presence_avatar( avatar(t, user, px(size::ICON), text(text::CAPTION), avatars), *presence, px(size::ICON), t, )) .child( div() .flex_1() .min_w_0() .flex() .flex_col() .child( div() .flex() .items_center() .gap(px(space::SM)) .child(user.username.clone()) .children(muted.then(|| { super::parts::small_icon(IconName::MicOff) .text_color(t.bad()) })), ) .children((!user.status.is_empty() && !in_voice).then( || { div() .text_size(text(text::CAPTION)) .text_color(t.dim()) .min_w_0() .child(super::glyph::line( user.status.clone().into(), super::text(super::style::text::CAPTION), )) }, )), ), t, ), )), ) .children(line) .children(watch(Kind::Camera)) .children(watch(Kind::Screen)) }; let section = |title: &'static str, rows: Vec<&MemberRow>| { (!rows.is_empty()).then(|| { div() .flex() .flex_col() .child( super::parts::caption_head(format!("{title} · {}", rows.len()), t) .pb(px(space::XS)), ) .children(rows.into_iter().map(row)) }) }; let in_call: Vec<&MemberRow> = members.iter().filter(|row| row.in_voice).collect(); let join = (!chat.in_voice(community_id) && yumush.can_join_voice(community_id)).then(|| { let action = entity_action(&entity, move |yumush, window, cx| { yumush.toggle_voice(community_id, window, cx) }); super::parts::pill("margin_join", t, action) .self_start() .gap(px(space::SM)) .text_color(t.ground()) .font_weight(FontWeight::SEMIBOLD) .child(super::parts::small_icon(IconName::Headphones)) .child(w().chat.join_voice) }); let call = (!in_call.is_empty() || join.is_some()).then(|| { div() .flex() .flex_col() .gap(px(space::SM)) .children(join) .children(section(w().chat.in_voice, in_call)) }); let online = members .iter() .filter(|row| !row.in_voice && row.presence != Presence::Offline) .collect(); let offline = members .iter() .filter(|row| !row.in_voice && row.presence == Presence::Offline) .collect(); Some( div() .id("members_column") .overflow_y_scroll() .px(px(space::SM)) .py(px(space::MD)) .flex() .flex_col() .gap(px(space::LG)) .child(room_head(yumush, t)) .children(call) .children(section(w().common.presence_online, online)) .children(section(w().common.presence_offline, offline)), ) } const GLIDE: Duration = Duration::from_millis(240); const GLIDE_SLACK: Duration = Duration::from_millis(100); fn room_head(yumush: &Yumush, t: Tokens) -> Div { let chat = &yumush.chat; let online = chat .session .members .iter() .filter(|member| yumush.is_online(member.user.id)) .count(); div().px(px(space::SM)).child(super::parts::words( w().community_card .people(chat.session.members.len(), online), super::parts::Text::Caption, super::parts::Ink::Dim, t, )) } fn accent_bar(t: Tokens) -> Div { div() .flex() .items_center() .justify_between() .gap(px(space::SM)) .px(px(space::MD)) .py(px(space::XS)) .text_size(text(text::LABEL)) .text_color(t.paper()) .border_b_1() .border_color(t.thread()) } fn thread_dot(mine: bool, t: Tokens) -> Div { let dot = div() .absolute() .left(px(-(space::LG + space::XS))) .top(px(space::SM)) .size(px(space::SM)) .rounded_full(); if mine { dot.bg(t.paper()) } else { dot.border_1().border_color(t.faint()).bg(t.ground()) } } fn new_divider(t: Tokens) -> impl IntoElement { div() .flex() .items_center() .gap(px(space::SM)) .my(px(space::SM)) .child(div().flex_1().h(px(stroke::LINE)).bg(t.paper())) .child( div() .text_size(text(text::CAPTION)) .text_color(t.paper()) .child(w().chat.new), ) } fn older_button(entity: &Entity, t: Tokens) -> impl IntoElement { let entity = entity.clone(); clickable("load_older_button", t, move |window, cx| { entity.update(cx, |yumush, cx| yumush.load_older_messages(window, cx)); }) .self_center() .h(px(size::CONTROL_SM)) .px(px(space::SM)) .flex() .items_center() .rounded(px(radius::MD)) .text_color(t.dim()) .child("↑") } fn call_duration(seconds: u64) -> String { let (hours, minutes, seconds) = (seconds / 3600, seconds % 3600 / 60, seconds % 60); if hours > 0 { format!("{hours}h {minutes}m") } else if minutes > 0 { format!("{minutes}m {seconds}s") } else { format!("{seconds}s") } } #[derive(Clone, Copy)] enum CallRun { Single, Folded(usize), Open, } pub(super) fn to_bands(bars: &[f32]) -> VecDeque { bars.iter().copied().collect() } fn message_rows<'a>( messages: &'a [Message], open_calls: &HashSet, divider: Option, ) -> Vec<(usize, &'a Message, bool, CallRun)> { let mut rows = Vec::new(); let mut start = 0; for run in messages.chunk_by(|a, b| a.call.is_some() == b.call.is_some()) { let is_call = run[0].call.is_some(); let open = is_call && open_calls.contains(&run[run.len() - 1].id); let started = run .iter() .filter(|message| message.call == Some(CallLog::Started)) .count(); for (offset, message) in run.iter().enumerate() { let index = start + offset; let last = offset + 1 == run.len(); if is_call && !open && !last && divider != Some(index) { continue; } let first = match message.call { Some(_) => { (index == start || !open) && start .checked_sub(1) .is_some_and(|previous| messages[previous].call.is_none()) } None => match index.checked_sub(1).map(|previous| &messages[previous]) { None => true, Some(previous) => { previous.user_id != message.user_id || previous.call.is_some() } }, }; let kind = match (is_call, last, open, started) { (true, true, true, _) => CallRun::Open, (true, true, false, 2..) => CallRun::Folded(started), _ => CallRun::Single, }; rows.push((index, message, first, kind)); } start += run.len(); } rows } fn render_call( message: &Message, call: CallLog, run: CallRun, spaced: bool, chat: &Chat, me: Option<&User>, entity: &Entity, t: Tokens, ) -> AnyElement { let mine = me.is_some_and(|me| me.id == message.user_id); let author = chat .author(message.user_id) .map_or(w().chat.unknown, |user| user.username.as_str()); let message_id = message.id; let entity = entity.clone(); let toggle = match run { CallRun::Single => None, CallRun::Folded(calls) => Some( div() .hover(|style| style.underline()) .child(format!("\u{a0}· {}", w().chat.calls(calls))), ), CallRun::Open => Some( div() .pl(px(space::XS)) .child(super::parts::small_icon(IconName::ChevronUp)), ), }; call_line(call, author, mine, t) .children(toggle.map(|toggle| { toggle .id(format!("calls_{message_id}")) .cursor_pointer() .text_color(t.faint()) .on_click(move |_, _, cx| { entity.update(cx, |yumush, cx| { if !yumush.chat.session.open_calls.remove(&message_id) { yumush.chat.session.open_calls.insert(message_id); } if !yumush.chat.away() { yumush.chat.jump_to_bottom(); } cx.notify(); }) }) })) .id(format!("message_row_{}", message.id)) .relative() .when(spaced, |this| this.mt(px(space::LG))) .into_any_element() } pub(super) fn call_line(call: CallLog, author: &str, mine: bool, t: Tokens) -> Div { let w = &w().chat; let (icon, color) = match call { CallLog::Started | CallLog::Ended { .. } => (IconName::Phone, t.dim()), CallLog::Declined => (IconName::PhoneOff, t.bad()), CallLog::Missed => (IconName::PhoneMissed, t.bad()), }; let label = match call { CallLog::Started if mine => w.call_started_mine.to_string(), CallLog::Started => w.call_started(author), CallLog::Declined if mine => w.call_declined_mine.to_string(), CallLog::Declined => w.call_declined(author), CallLog::Missed if mine => w.call_missed_mine.to_string(), CallLog::Missed => w.call_missed(author), CallLog::Ended { seconds } => w.call_ended(call_duration(seconds)), }; div() .relative() .flex() .items_center() .text_size(text(text::CAPTION)) .text_color(t.dim()) .child( div() .absolute() .left(px( -(space::LG + space::XS) - (size::ICON_SM - space::SM) / 2. )) .bg(t.ground()) .child(super::parts::small_icon(icon).text_color(color)), ) .child(label) } fn render_message( message: &Message, first: bool, spaced: bool, run: CallRun, chat: &Chat, me: Option<&User>, clock: &'static str, entity: &Entity, t: Tokens, ) -> AnyElement { if let Some(call) = message.call { return render_call(message, call, run, first && spaced, chat, me, entity, t); } let builder = me.is_some_and(|me| permission::is_builder(me.role)); let code = message.body.contains("```"); let collapsed = message.deleted && !chat.session.revealed.contains(&message.id); let author = chat.author(message.user_id); let username = author.map_or(w().chat.unknown, |user| user.username.as_str()); let name = div().flex().items_center().gap(px(space::SM)).child( div() .id(format!("author_name_{}", message.id)) .font_weight(FontWeight::SEMIBOLD) .text_color(t.paper()) .when(author.is_some(), |this| { this.hover(|style| style.underline()) }) .child(username.to_string()), ); let mentioned = me.is_some_and(|me| mentions(&message.body, &me.username)); let mine = me.is_some_and(|me| me.id == message.user_id); 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 highlighted = chat .session .highlight .as_ref() .is_some_and(|(id, at)| id == &message.id && at.elapsed() < HIGHLIGHT_TTL); let row = div() .id(format!("message_row_{}", message.id)) .group(group.clone()) .on_hover({ let entity = entity.clone(); let id = message.id; move |hovered, _, cx| { entity.update(cx, |yumush, cx| { if message_actions::track(&mut yumush.chat.session.hover_row, id, *hovered) { cx.notify(); } }); } }) .relative() .flex() .flex_col() .min_w_0() .hover(|style| style.bg(t.hov())) .when(chat.engaged(message.id), |this| this.bg(t.hov())) .when(message.deleted, |this| this.text_color(t.faint())) .when(first && spaced && !selecting, |this| this.mt(px(space::LG))) .when(highlighted, |this| this.bg(t.press())) .when(mentioned, |this| this.border_l_2().border_color(t.paper())) .when(first, |this| { let author = match author { Some(user) => profile_popover( format!("author_{}", message.id), Anchor::LeftCenter, user, entity, name.cursor_pointer(), ) .into_any_element(), None => name.into_any_element(), }; this.child( div() .relative() .flex() .items_center() .gap(px(space::SM)) .mb(px(space::XXS)) .child(thread_dot(if selecting { selected } else { mine }, t)) .child(author) .child( div() .text_size(text(text::CAPTION)) .text_color(t.dim()) .child(millis_time(message.created_at, clock)), ), ) }) .child( div() .relative() .min_w_0() .flex() .items_center() .gap(px(space::SM)) .when(selecting && !first, |this| { this.child(thread_dot(selected, t)) }) .child( div() .min_w_0() .max_w(px(size::PAGE)) .when(code, |this| this.w_full()) .flex() .flex_col() .gap(px(space::SM)) .when(collapsed, |this| { this.child(message_actions::reveal_deleted(message.id, entity, t)) }) .when(!collapsed, |this| { this.children(message_actions::quote_line(message, chat, entity, t)) .when(!message.body.is_empty(), |this| { this.child( div() .min_w_0() .when(code, |this| this.w_full()) .flex() .flex_wrap() .items_baseline() .gap(px(space::XS)) .text_size(text(text::BODY)) .line_height(relative(1.55)) .text_color(t.paper()) .child( div() .min_w_0() .when(code, |this| this.w_full()) .child( TextView::markdown( format!("message-body-{}", message.id), crate::emoji::markdown(&hard_breaks( &message.body, )), ) .markdown_extensions( super::glyph::extensions(), ) .selectable(true), ), ) .when(message.edited || message.deleted, |this| { this.child( div() .flex() .gap(px(space::SM)) .text_size(text(text::CAPTION)) .text_color(t.dim()) .children(message.edited.then(|| { message_actions::edited_mark( message, builder, entity, t, ) })) .children(message.deleted.then(|| { message_actions::collapse_deleted( message.id, entity, ) })), ) }), ) }) .children(media_view::attachments( &message.attachments, &chat.session.media, entity, t, )) .children(snippet::snippet_card(message, clock, chat, entity, t)) .children(message.poll.as_ref().map(|poll| { poll::poll_card( poll, poll::PollMode::Live(message), me, chat, entity, t, ) })) .children(media_view::embeds(message, &chat.session.media, t)) .children( (!message.reactions.is_empty()).then(|| { message_actions::reactions(message, me, entity, t) }), ) }), ) .children(message.pinned.then(|| message_actions::pin_mark(t))) .children((!selecting && !message.deleted).then(|| { div() .absolute() .right_0() .bottom(gpui_kit::relative(1.)) .child(message_actions::actions(message, chat, me, entity, t)) })), ) .children( (chat.session.report == Some(ReportTarget::Message(message.id))) .then(|| message_actions::report_bar(&chat.report_reason, entity, t)), ); if !selecting { return row.into_any_element(); } let message_id = message.id; let select_entity = entity.clone(); div() .id(format!("select_row_{}", message.id)) .when(first && spaced, |this| this.mt(px(space::LG))) .cursor_pointer() .on_click(move |_, _, cx| { select_entity.update(cx, |yumush, cx| yumush.toggle_select(message_id, cx)); }) .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 } fn hard_breaks(body: &str) -> String { let mut fenced = false; let lines: Vec = body .lines() .map(|line| { if line.trim_start().starts_with("```") { fenced = !fenced; return line.to_string(); } match (fenced, line.trim().is_empty()) { (true, _) => line.to_string(), (false, true) => "\u{a0} ".to_string(), (false, false) => format!("{line} "), } }) .collect(); lines.join("\n") } fn stats_button(entity: &Entity, t: Tokens, open: bool) -> impl IntoElement { clickable( format!("stats_toggle_{open}"), t, entity_action(entity, |yumush: &mut Yumush, _, cx| { yumush.toggle_stats(StatsAt::Header); cx.notify(); }), ) .tip(if open { w().chat.stats_hide } else { w().chat.stats }) .size(px(size::CONTROL_SM)) .flex() .items_center() .justify_center() .rounded(px(radius::MD)) .when(open, |this| this.bg(t.press())) .text_color(if open { t.paper() } else { t.dim() }) .child(super::parts::small_icon(IconName::Activity)) } fn stage_button( entity: &Entity, t: Tokens, layout: Stage, active: bool, icon: IconName, name: &'static str, label: &'static str, ) -> impl IntoElement { clickable( format!("stage_{name}_{active}"), t, entity_action(entity, move |yumush: &mut Yumush, _, cx| { let next = if active { Stage::Hidden } else { layout }; yumush.set_stage(next, cx) }), ) .tip(if active { w().chat.hide } else { label }) .size(px(size::CONTROL_SM)) .flex() .items_center() .justify_center() .rounded(px(radius::MD)) .when(active, |this| this.bg(t.press())) .text_color(if active { t.paper() } else { t.dim() }) .child(super::parts::small_icon(icon)) }