use crate::gui::glyph::Fill as _; use crate::lang::w; use common::model::{Hue, Id}; use std::{collections::HashMap, fmt::Display, rc::Rc, sync::Arc, time::Instant}; use common::{ call::{GetAvatar, GetSettings, MarkRead}, constant::{MAXIMUM_AVATAR_BYTES, MAXIMUM_MESSAGE_LENGTH}, error::{Error, ReleaseProblem}, event::Event, model::{ CallLog, Community, CommunityKind, Message, Presence, Rank, Sanction, ServerSettings, Staged, Unread, User, mentions, }, }; use gpui_kit::{ AnyElement, AnyWindowHandle, App, AppContext, AsyncWindowContext, Context, Div, ElementId, Entity, FontWeight, Hsla, Image, ImageFormat, InteractiveElement, IntoElement, KeyBinding, KeyDownEvent, KeyUpEvent, ModifiersChangedEvent, ParentElement, Pixels, Rems, Render, RenderOnce, Stateful, StatefulInteractiveElement, Styled, WeakEntity, Window, actions, base::Selectable, component::{ Sizable, Theme, ThemeRegistry, WindowExt, input::{Input, InputEvent, InputState}, notification::Notification, spinner::Spinner, }, div, img, prelude::FluentBuilder as _, px, rems, }; use jiff::{Timestamp, tz::TimeZone}; use tokio::sync::mpsc; use crate::{ accounts::{self, Accounts}, marks::{self, Mark}, net::{Fail, LinkError, NetworkEvent, NetworkHandle}, settings::Settings, voice::{self, Sound}, }; mod account_list; mod auth; mod builder; mod call_bar; mod camera_view; mod chat; mod community_card; mod community_settings; mod composer; mod dock; mod forward; pub mod gallery; pub mod glyph; mod jump; mod keys; mod media_view; mod message_actions; mod parts; mod poll; mod profile; mod settings_page; mod share_view; mod sidebar; mod snippet; mod social; mod stream_stats; pub mod style; mod surface; mod tow; mod update_view; mod voice_note; mod voice_settings; mod voice_stats; mod wave; mod widget; use auth::Auth; use chat::{Chat, View}; use style::{Tokens, radius, size, space}; use voice_settings::VoiceControls; actions!(yumush, [FocusFind, CloseSettings]); pub fn text(size: f32) -> Rems { rems(size / style::text::UI) } const FONT: &str = "Onest"; const MONO_FONT: &str = "Adwaita Mono"; pub fn init(cx: &mut App) { let fonts = [ include_bytes!("../assets/fonts/Onest-Regular.ttf").as_slice(), include_bytes!("../assets/fonts/Onest-Medium.ttf"), include_bytes!("../assets/fonts/Onest-SemiBold.ttf"), include_bytes!("../assets/fonts/Onest-Bold.ttf"), include_bytes!("../assets/fonts/AdwaitaMono-Regular.ttf"), include_bytes!("../assets/fonts/AdwaitaMono-Bold.ttf"), ]; let fonts = fonts.into_iter().map(std::borrow::Cow::Borrowed).collect(); if let Err(error) = cx.text_system().add_fonts(fonts) { tracing::warn!("fonts: {error}"); } let mut theme = Theme::default(); theme.font_family = FONT.into(); theme.mono_font_family = MONO_FONT.into(); cx.set_global(theme); gpui_kit::init(cx); let registry = ThemeRegistry::global(cx); let (light, dark) = ( registry.default_light_theme().clone(), registry.default_dark_theme().clone(), ); let theme = Theme::global_mut(cx); theme.light_theme = light; theme.dark_theme = dark; } pub fn sync_theme(cx: &mut App) { let t = Tokens::of(cx); let font_size = Tokens::of(cx).size.pixels(); let theme = Theme::global_mut(cx); theme.font_family = FONT.into(); theme.mono_font_family = MONO_FONT.into(); let colors = &mut theme.colors; colors.background = t.ground(); colors.foreground = t.paper(); colors.popover = t.ground(); colors.popover_foreground = t.paper(); colors.border = t.thread(); colors.input = t.thread(); colors.muted = t.raise(); colors.muted_foreground = t.dim(); colors.accent = t.hov(); colors.accent_foreground = t.paper(); colors.list_hover = t.hov(); colors.secondary = t.raise(); colors.secondary_foreground = t.paper(); colors.primary = t.paper(); colors.primary_hover = t.paper(); colors.primary_active = t.paper(); colors.primary_foreground = t.ground(); colors.ring = t.paper(); colors.caret = t.paper(); colors.danger = t.bad(); colors.slider_bar = t.paper(); colors.slider_thumb = t.paper(); theme.tokens = (&theme.colors).into(); theme.radius = px(radius::SM); theme.radius_lg = px(radius::LG); theme.font_size = font_size; theme.focus_ring = false; } pub fn badge(t: Tokens, id: Id, name: &str, size: Pixels, font: Rems) -> Div { let initial = name .chars() .next() .unwrap_or('?') .to_uppercase() .to_string(); div() .size(size) .flex_shrink_0() .flex() .items_center() .justify_center() .bg(t.person(id)) .text_color(t.ground()) .text_size(font) .font_weight(FontWeight::SEMIBOLD) .child(initial) } pub fn avatar( t: Tokens, user: &User, size: Pixels, font: Rems, avatars: &HashMap>, ) -> Div { let Some(image) = user.avatar_id.as_ref().and_then(|id| avatars.get(id)) else { return badge(t, 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 picture_of(community: &Community, avatars: &HashMap>) -> Option> { let avatar_id = match &community.kind { CommunityKind::Group => community.avatar_id, CommunityKind::Direct { peer } => peer.avatar_id, CommunityKind::Notes => None, }; avatar_id.and_then(|id| avatars.get(&id)).cloned() } pub struct Zoom { image: Arc, round: bool, name: String, } impl Zoom { pub fn new(image: Option>, round: bool, name: String) -> Option { image.map(|image| Self { image, round, name }) } } pub fn zoomable( entity: &Entity, id: impl Into, face: Div, zoom: Option, ) -> Stateful
{ let face = face.id(id); let Some(zoom) = zoom.map(Rc::new) else { return face; }; let entity = entity.clone(); face.cursor_pointer().on_click(move |_, _, cx| { let zoom = zoom.clone(); entity.update(cx, |yumush, cx| { yumush.zoom = Some(zoom); cx.notify(); }); }) } fn zoom_view(zoom: &Zoom, entity: &Entity, t: Tokens) -> Stateful
{ let entity = entity.clone(); let picture = img(zoom.image.clone()).size(px(size::MEDIA)); div() .id("zoom") .absolute() .inset_0() .occlude() .bg(t.scrim()) .flex() .flex_col() .items_center() .justify_center() .gap(px(space::LG)) .on_click(move |_, _, cx| { entity.update(cx, |yumush, cx| { yumush.zoom = None; cx.notify(); }) }) .child(if zoom.round { picture.rounded_full() } else { picture.rounded(px(radius::LG)) }) .child(parts::words( zoom.name.clone(), parts::Text::Title, parts::Ink::Paper, t, )) } pub fn community_name(community: &Community) -> &str { match &community.kind { CommunityKind::Group => &community.name, CommunityKind::Direct { peer } if community.name.is_empty() => &peer.username, CommunityKind::Direct { .. } => &community.name, CommunityKind::Notes => w().gui.notes, } } pub fn community_icon( t: Tokens, community: &Community, size: Pixels, font: Rems, 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(radius::SM)) .overflow_hidden() .child(img(image.clone()).size_full().rounded(px(radius::SM))), None => badge(t, community.id, &community.name, size, font).rounded(px(radius::SM)), }, CommunityKind::Direct { peer } => avatar(t, peer, size, font, avatars), CommunityKind::Notes => { badge(t, community.id, w().gui.notes, size, font).rounded(px(radius::SM)) } } } pub const KB: f64 = 1024.0; pub const MB: f64 = KB * 1024.0; pub const CLOCK: &str = "%H:%M"; pub const CLOCK_SECONDS: &str = "%H:%M:%S"; pub use common::error::size_text as storage; pub fn millis_time(millis: u64, format: &str) -> String { let Ok(timestamp) = Timestamp::from_millisecond(millis as i64) else { return String::new(); }; let zoned = timestamp.to_zoned_datetime(TimeZone::system()); zoned .strftime(&month_named(format, zoned.month())) .to_string() } pub fn month_named(format: &str, month: i8) -> String { let name = crate::lang::w() .common .months .split(' ') .nth(month as usize - 1) .unwrap_or_default(); format.replace("%b", name) } pub fn hoverable(id: impl Into, element: Div, t: Tokens) -> Stateful
{ let hover = t.hov(); element .id(id) .cursor_pointer() .hover(move |style| style.bg(hover)) } pub fn clickable( id: impl Into, t: Tokens, on_click: impl Fn(&mut Window, &mut App) + 'static, ) -> Stateful
{ hoverable(id, div(), t).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 t = Tokens::of(cx); div() .px(px(space::SM)) .py(px(space::XS)) .rounded(px(radius::SM)) .border_1() .border_color(t.thread()) .bg(t.raise()) .text_color(t.paper()) .font_family(FONT) .text_size(text(style::text::LABEL)) .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()) } } #[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 presence_color(presence: Presence, t: Tokens) -> Hsla { match presence { Presence::Online => t.hue(Hue::Mint), Presence::Busy => t.bad(), Presence::Offline => t.dim(), } } pub fn presence_avatar( avatar: impl IntoElement, presence: Presence, size: Pixels, t: Tokens, ) -> Div { let dot = if size > px(size::CHIP) { px(space::SM + space::XXS) } else { px(space::SM) }; div().relative().flex_shrink_0().child(avatar).child( div() .absolute() .right(px(-space::XXS)) .bottom(px(-space::XXS)) .size(dot) .rounded_full() .border_2() .border_color(t.ground()) .bg(presence_color(presence, t)), ) } pub fn bind_keys(cx: &mut App) { cx.bind_keys([ KeyBinding::new(keys::bind!("k"), FocusFind, None), KeyBinding::new("escape", CloseSettings, None), ]); composer::bind_keys(cx); } #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Route { Login, Register, Chat, } #[derive(Debug, Clone, PartialEq)] enum Connection { Connecting, Connected, Lost { error: String, attempts: u32 }, Failed(String), } impl Connection { fn is_connected(&self) -> bool { matches!(self, Self::Connected) } fn lost(&mut self, error: &LinkError) { if error.terminal() { *self = Self::Failed(error.to_string()); return; } let attempts = match self { Self::Lost { attempts, .. } => *attempts + 1, _ => 1, }; *self = Self::Lost { error: error.to_string(), attempts, }; } } fn connection_notice(connection: &Connection, t: Tokens) -> Option
{ let (label, color, busy) = match connection { Connection::Connecting => (w().gui.connecting.to_string(), t.dim(), true), Connection::Connected => return None, Connection::Lost { error, attempts } => { (w().gui.reconnecting(attempts, error), t.bad(), true) } Connection::Failed(error) => (error.clone(), t.bad(), false), }; Some( div() .h(px(size::CHIP)) .flex() .items_center() .justify_center() .gap(px(space::SM)) .text_size(text(style::text::CAPTION)) .text_color(color) .when(busy, |row| row.child(Spinner::new().xsmall().color(color))) .child(label), ) } #[derive(Default)] struct Missed { resume: bool, stale: bool, notices: Vec, imports: Vec<(String, Result, ReleaseProblem>)>, } pub struct Yumush { user: Option, current_route: Route, auth: Auth, chat: Chat, network: NetworkHandle, connection: Connection, server: Option, dismissed_announcement: Option, settings: Settings, accounts: Accounts, account_filter: Entity, voice: VoiceControls, focus: gpui_kit::FocusHandle, window: Option, missed: Missed, update: crate::update::Phase, desk: builder::releases::Desk, release_tag: Entity, log_search: Entity, log_scroll: gpui_kit::UniformListScrollHandle, share_apps: Vec, share_apps_seen: std::cell::Cell, share_apps_task: Option>, wordmark_flips: u32, wordmark_flipped: Option, zoom: Option>, emoji_group: usize, share_tab: common::share::Kind, camera_modes: Vec, camera_devices: Vec, share_more: bool, share_busy: bool, fullscreen: bool, pumping: bool, pumped: Instant, send_order: Arc>, } impl Yumush { pub fn new( network: NetworkHandle, mut network_event_receiver: mpsc::Receiver, settings: Settings, window: &mut Window, cx: &mut Context, ) -> Self { cx.spawn(async move |this, cx| { while let Some(event) = network_event_receiver.recv().await { let Ok(handle) = this.read_with(cx, |yumush, _| yumush.window) else { break; }; let mut event = Some(event); if let Some(handle) = handle { let _ = handle.update(cx, |_, window, cx| { if let Some(event) = event.take() { let _ = this.update(cx, |yumush, cx| { yumush.handle_network_event(event, Some(window), cx) }); } }); } if let Some(event) = event && this .update(cx, |yumush, cx| { yumush.handle_network_event(event, None, cx) }) .is_err() { break; } } }) .detach(); let mut phase = crate::update::subscribe(); cx.spawn(async move |this, cx| { loop { let now = *phase.borrow_and_update(); let alive = this .update(cx, |yumush, cx| { yumush.update = now; cx.notify(); }) .is_ok(); if !alive || phase.changed().await.is_err() { break; } } }) .detach(); sidebar::wander(cx); let voice = VoiceControls::new(&settings.voice, cx); let server = network.server(); let account_filter = new_input(w().auth.find_account, window, cx); let release_tag = new_input(w().builder_release.tag, window, cx); let log_search = new_input(w().chat.find, window, cx); cx.subscribe(&account_filter, |_, _, event: &InputEvent, cx| { if matches!(event, InputEvent::Change) { cx.notify(); } }) .detach(); let mut yumush = Self { user: None, focus: cx.focus_handle(), current_route: Route::Login, auth: Auth::new(&server, window, cx), chat: Chat::new(window, cx), network, connection: Connection::Connecting, server: None, dismissed_announcement: None, settings, accounts: accounts::load(&server.address), account_filter, voice, window: None, missed: Missed::default(), update: crate::update::Phase::Idle, desk: builder::releases::Desk::default(), release_tag, log_search, log_scroll: gpui_kit::UniformListScrollHandle::new(), share_apps: Vec::new(), share_apps_seen: std::cell::Cell::new(Instant::now()), share_apps_task: None, wordmark_flips: 0, wordmark_flipped: None, zoom: None, emoji_group: 0, share_tab: common::share::Kind::Screen, camera_modes: Vec::new(), camera_devices: Vec::new(), share_more: false, share_busy: false, fullscreen: false, pumping: false, pumped: Instant::now(), send_order: Default::default(), }; yumush.chat.session.camera_task = Some(camera_view::ticker(cx)); yumush } pub fn tray_state(&self) -> crate::tray::TrayState { let groups = self.chat.unread_groups(); let direct = self.chat.unread_direct(); crate::tray::TrayState { messages: groups.messages + direct.messages, mentions: groups.mentions + direct.mentions, } } pub fn attach_window(&mut self, window: &mut Window, cx: &mut Context) { self.window = Some(window.window_handle()); cx.observe_window_activation(window, |yumush, window, cx| { if window.is_window_active() { yumush.read_selected(cx); } else { yumush.network.set_talking(false); } }) .detach(); self.fullscreen = false; if let Some(viewer) = self.chat.session.viewer.as_mut() { viewer.fullscreen = false; } let missed = std::mem::take(&mut self.missed); if missed.resume { self.resume(window, cx); } for notice in missed.notices { window.push_notification(notice, cx); } for (tag, result) in missed.imports { self.release_imported(&tag, result, window, cx); } if missed.stale { self.releases_changed(window, cx); self.report_created(window, cx); self.voice_changed(window, cx); } self.focus_page(window, cx); } fn notify(&mut self, window: Option<&mut Window>, notice: Notification, cx: &mut App) { match window { Some(window) => window.push_notification(notice, cx), None => self.missed.notices.push(notice), } } fn resume(&mut self, window: &mut Window, cx: &mut Context) { if self.user.is_some() { self.reload(window, cx); } else if let Some(active) = self.accounts.active { self.switch_account(active, window, cx); } } pub fn window(&self) -> Option { self.window } pub fn detach_window(&mut self) -> bool { self.window = None; self.settings.close_to_tray } 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.chat.session.muted = marks::load(Mark::Mute, user.id); self.chat.session.pinned = marks::load(Mark::Pin, user.id); style::remember(&[&user]); style::remember_me(user.id); self.user = Some(user); self.change_page(Route::Chat, window, cx); self.load_communities(window, cx); self.load_social(window, cx); self.load_users(window, cx); self.watch_ci(window, cx); } pub(super) fn switch_account( &mut self, user_id: Id, window: &mut Window, cx: &mut Context, ) { let Some(account) = self.accounts.get(user_id).cloned() else { return; }; if !self.connection.is_connected() { window.push_notification(Notification::error(w().gui.not_connected), cx); return; } if self.user.is_some() { self.end_session(window, cx); } self.accounts.suspend(); 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 @ Fail::Server(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: Id, cx: &mut Context) { self.accounts.forget(user_id); cx.notify(); } pub(super) fn toggle_mark(&mut self, mark: Mark, community_id: Id, cx: &mut Context) { let Some(me) = self.user.as_ref().map(|me| me.id) else { return; }; let ids = match mark { Mark::Mute => &mut self.chat.session.muted, Mark::Pin => &mut self.chat.session.pinned, }; if !ids.remove(&community_id) { ids.insert(community_id); } marks::save(mark, me, ids); cx.notify(); } pub(super) fn armed(&self, armed: chat::Armed) -> bool { self.chat.session.armed.as_ref() == Some(&armed) } pub(super) fn armed_label(&self, armed: chat::Armed, label: &'static str) -> &'static str { if self.armed(armed) { w().common.confirm } else { label } } pub(super) fn arm(&mut self, armed: chat::Armed, cx: &mut Context) -> bool { if self.armed(armed.clone()) { self.chat.session.armed = None; return true; } self.chat.session.armed = Some(armed); cx.notify(); false } pub(super) fn disarm(&mut self, cx: &mut Context) { if self.chat.session.armed.take().is_some() { cx.notify(); } } fn logout(&mut self, window: &mut Window, cx: &mut Context) { let Some(user) = self.user.clone() else { return; }; self.accounts.forget(user.id); self.end_session(window, cx); let network = self.network.clone(); cx.spawn_in(window, async move |this, cx| { if let Err(error) = network.logout().await { notify_error(&this, cx, error); } }) .detach(); } fn change_page(&mut self, route: Route, window: &mut Window, cx: &mut Context) { self.current_route = route; cx.notify(); self.focus_page(window, cx); } fn focus_page(&self, window: &mut Window, cx: &mut Context) { match self.current_route { Route::Login | Route::Register => self.auth.focus(window, cx), Route::Chat => self.chat.focus(window, cx), } } fn show_view(&mut self, view: View, window: &mut Window, cx: &mut Context) { self.chat.session.section = None; if self.chat.session.view == View::Settings && view != View::Settings { self.leave_settings(); } if view == View::Settings { self.enter_settings(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.fill(status, window, cx)); } if view == View::Builder { self.load_builder(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.session.view = view; self.chat.session.armed = None; if view == View::Chat { self.chat.focus(window, cx); } cx.notify(); } pub fn actor_rank(&self) -> Option { self.user.as_ref().and_then(|me| self.chat.rank_of(me)) } pub fn community_badge( &self, community: &Community, size: Pixels, font: Rems, t: Tokens, ) -> Div { let icon = community_icon(t, community, size, font, &self.chat.session.avatars); match community.kind.peer() { Some(peer) => presence_avatar(icon, self.presence_of(peer.id), size, t), None => icon, } } pub fn presence_of(&self, user_id: Id) -> Presence { if self.is_me(user_id) && !self.connection.is_connected() { return Presence::Offline; } self.chat .session .presences .get(&user_id) .copied() .unwrap_or(Presence::Offline) } pub fn is_online(&self, user_id: Id) -> bool { self.presence_of(user_id) != Presence::Offline } pub fn request_avatar(&mut self, avatar_id: Id, cx: &mut Context) { if self.chat.session.avatars.contains_key(&avatar_id) || self.chat.session.avatar_requests.contains(&avatar_id) { return; } self.chat.session.avatar_requests.insert(avatar_id); let network = self.network.clone(); cx.spawn(async move |this, cx| { let result = network.call(GetAvatar { avatar_id }).await; let _ = this.update(cx, |yumush, cx| { yumush.chat.session.avatar_requests.remove(&avatar_id); if let Ok(bytes) = result { style::picture(avatar_id, &bytes); if let Some(me) = yumush .user .as_ref() .filter(|me| me.avatar_id == Some(avatar_id)) { yumush.accounts.set_picture(me.id, Some(bytes.clone())); } yumush.chat.session.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 user.avatar_id.is_none() && self .accounts .get(user.id) .is_some_and(|account| account.picture.is_some()) { self.accounts.set_picture(user.id, None); } 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); if !self.is_builder() && self.chat.session.view == View::Builder { self.chat.session.view = View::Chat; } } self.request_user_avatar(user, cx); } Event::VoiceLeft { community_id, user_id, } if self.is_me(*user_id) => self.leave_voice_in(*community_id, cx), Event::VoiceMuted { user_id, muted: true, .. } if self.is_me(*user_id) => self.set_muted(true, cx), Event::ShareStopped { user_id, kind, .. } if self.is_watching(*user_id, *kind) => { self.close_viewer(cx) } Event::StatsWanted(true) => self.start_stats_push(cx), Event::StatsWanted(false) => self.chat.session.stats_task = None, Event::Typing { .. } => { cx.spawn(async move |this, cx| { cx.background_executor().timer(chat::TYPING_TTL).await; let _ = this.update(cx, |_, cx| cx.notify()); }) .detach(); } _ => {} } let builder = self.is_builder(); self.chat .apply_event(event, self.user.as_ref().map(|user| user.id), builder); self.request_authors(cx); self.request_social_avatars(cx); self.request_media(cx); } fn mark_read(&mut self, community_id: Id, message_id: Id, cx: &mut Context) { self.chat.mark_read(community_id, message_id); let network = self.network.clone(); cx.spawn(async move |_, _| { let _ = network .call(MarkRead { community_id, message_id, }) .await; }) .detach(); } fn read_selected(&mut self, cx: &mut Context) { let Some(community_id) = self.chat.session.selected_community_id else { return; }; let Some(message_id) = self.chat.session.messages.last().map(|message| message.id) else { return; }; if self .chat .session .unread .get(&community_id) .is_some_and(|unread| unread.messages > 0) { self.mark_read(community_id, message_id, cx); } } fn count_message(&mut self, message: &Message, active: bool, cx: &mut Context) { let Some(me) = self.user.as_ref() else { return; }; if message.user_id == me.id { return; } if active && self.chat.is_selected(message.community_id) { self.mark_read(message.community_id, message.id, cx); return; } let unread = self .chat .session .unread .entry(message.community_id) .or_insert_with(|| Unread { community_id: message.community_id, ..Default::default() }); unread.messages += 1; if mentions(&message.body, &me.username) { unread.mentions += 1; } } fn should_notify(&self, message: &Message, active: bool) -> bool { let Some(me) = self.user.as_ref() else { return false; }; let viewing = active && self.chat.is_selected(message.community_id); message.user_id != me.id && message.call.is_none() && !self.chat.session.muted.contains(&message.community_id) && self.presence_of(me.id) == Presence::Online && !viewing } fn starts_call(&self, community_id: Id, user_id: Id) -> bool { !self.is_me(user_id) && self.chat.voice_ids(community_id).is_empty() && self.is_direct(community_id) } fn ends_call(&self, community_id: Id, user_id: Id) -> bool { !self.is_me(user_id) && self.chat.in_voice(community_id) && self.is_direct(community_id) && self .chat .voice_ids(community_id) .iter() .all(|id| *id == user_id || self.is_me(*id)) } pub(super) fn is_direct(&self, community_id: Id) -> bool { self.chat .community(community_id) .is_some_and(|community| community.kind.is_direct()) } pub(super) fn is_me(&self, user_id: Id) -> bool { self.user.as_ref().is_some_and(|me| me.id == user_id) } fn clear_session(&mut self, cx: &mut Context) { self.end_voice(cx); self.leave_settings(); self.stop_playing(cx); self.user = None; self.desk = builder::releases::Desk::default(); self.chat.reset(); } fn end_session(&mut self, window: &mut Window, cx: &mut Context) { self.clear_session(cx); self.change_page(Route::Login, window, cx); } pub(super) fn max_avatar_bytes(&self) -> u64 { self.server .as_ref() .map_or(MAXIMUM_AVATAR_BYTES as u64, |settings| { settings.max_avatar_bytes }) } pub(super) fn max_message_length(&self) -> usize { self.server .as_ref() .map_or(MAXIMUM_MESSAGE_LENGTH, |settings| { settings.max_message_length as usize }) } pub(super) fn announcement(&self) -> Option<&str> { let text = self.server.as_ref()?.announcement.as_str(); let dismissed = self.dismissed_announcement.as_deref() == Some(text); (!text.is_empty() && !dismissed).then_some(text) } pub(super) fn dismiss_announcement(&mut self, cx: &mut Context) { self.dismissed_announcement = self .server .as_ref() .map(|settings| settings.announcement.clone()); cx.notify(); } fn load_server_settings(&self, cx: &mut Context) { let network = self.network.clone(); cx.spawn(async move |this, cx| { let Ok(settings) = network.call(GetSettings).await else { return; }; let _ = this.update(cx, |yumush, cx| { yumush.server = Some(settings); cx.notify(); }); }) .detach(); } fn handle_network_event( &mut self, event: NetworkEvent, window: Option<&mut Window>, cx: &mut Context, ) { let active = window .as_ref() .is_some_and(|window| window.is_window_active()); if let NetworkEvent::Pushed(pushed) = &event { self.before_pushed(pushed, active, cx); } match event { NetworkEvent::Connected => { self.connection = Connection::Connected; self.desk.connected(); self.load_server_settings(cx); match window { Some(window) => self.resume(window, cx), None => self.missed.resume = true, } } NetworkEvent::Disconnected(error) => self.connection.lost(&error), NetworkEvent::VoiceRejoined => self.refresh_voice(cx), NetworkEvent::VoiceEnded => self.chat.set_voice_off(), NetworkEvent::SessionLost => { if let Some(user) = &self.user { self.accounts.forget(user.id); } self.clear_session(cx); match window { Some(window) => self.change_page(Route::Login, window, cx), None => self.current_route = Route::Login, } } NetworkEvent::Pushed(event) => match *event { Event::MemberLeft { 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, sanction, reason, } => { self.leave_voice_in(community_id, cx); self.chat.remove_community(community_id); let text = match (sanction, reason) { (Sanction::Ban, Some(reason)) => { w().gui.banned_reason(community_name, reason) } (Sanction::Ban, None) => w().gui.banned(community_name), (Sanction::Kick, Some(reason)) => { w().gui.kicked_reason(community_name, reason) } (Sanction::Kick, None) => w().gui.kicked(community_name), }; self.notify(window, Notification::warning(text), cx); } Event::CommunityDeleted { community_id } => { self.leave_voice_in(community_id, cx); self.apply_pushed(Event::CommunityDeleted { community_id }, cx); } Event::ReportCreated => match window { Some(window) => self.report_created(window, cx), None => self.missed.stale = true, }, Event::Release => match window { Some(window) => self.releases_changed(window, cx), None => self.missed.stale = true, }, Event::Imported { tag, result } => match window { Some(window) => self.release_imported(&tag, result, window, cx), None => self.missed.imports.push((tag, result)), }, Event::SettingsUpdated(settings) => self.server = Some(settings), event => { let voice = matches!( event, Event::VoiceJoined { .. } | Event::VoiceLeft { .. } | Event::VoiceMuted { .. } ); self.apply_pushed(event, cx); if voice { match window { Some(window) => self.voice_changed(window, cx), None => self.missed.stale = true, } } } }, } self.update_ringing(cx); cx.notify(); } fn before_pushed(&mut self, event: &Event, active: bool, cx: &mut Context) { match event { Event::MessageCreated(message) => { if self.should_notify(message, active) { voice::play_sound(Sound::Notification, &self.settings.voice); } self.count_message(message, active, cx); if !self .chat .session .communities .iter() .any(|community| community.id == message.community_id) { self.refresh_communities(cx); } if message.call == Some(CallLog::Declined) && self.chat.in_voice(message.community_id) { self.end_voice(cx); } } Event::VoiceJoined { community_id, user_id, } if self.starts_call(*community_id, *user_id) => { self.chat.session.ringing.insert(*community_id); } Event::VoiceLeft { community_id, user_id, } if self.ends_call(*community_id, *user_id) => { self.end_voice(cx); } _ => {} } } } 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 t = Tokens::of(cx); let entity = entity.clone(); let on_submit = on_submit.clone(); let button_input = dialog_input.clone(); dialog .title(title) .close_button(false) .w(px(size::POPOVER)) .child( div() .flex() .items_center() .gap(px(space::MD)) .child( widget::frame(t, Input::new(&dialog_input).token(glyph::token)) .flex_1() .min_w_0(), ) .child(parts::button( "input_dialog_submit", action, parts::Press::Primary, t, move |window, cx| { let text = button_input.read(cx).text().to_string(); entity.update(cx, |this, cx| on_submit(this, text, window, cx)); }, )), ) }); window.defer(cx, move |window, cx| { input.update(cx, |input, cx| input.focus(window, cx)); }); } pub fn notify_error( this: &WeakEntity, cx: &mut AsyncWindowContext, error: impl Display, ) { let _ = this.update_in(cx, |_, window, cx| { window.push_notification(Notification::error(error.to_string()), cx); }); } pub(super) fn new_input( placeholder: &'static str, window: &mut Window, cx: &mut Context, ) -> Entity { let input = cx.new(|cx| { let mut input_state = InputState::new(window, cx); input_state.set_placeholder(placeholder, window, cx); input_state }); cx.subscribe(&input, |_, input, event: &InputEvent, cx| { if matches!(event, InputEvent::Change) { input.update(cx, |state, cx| state.mark(cx)); } }) .detach(); input } impl Render for Yumush { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { crate::usage::tick(crate::usage::Group::Gui); let fullscreen = self .chat .session .viewer .as_ref() .is_some_and(|viewer| viewer.fullscreen); if fullscreen != self.fullscreen { self.fullscreen = fullscreen; window.toggle_fullscreen(); } if window.focused(cx).is_none() { window.focus(&self.focus, cx); } self.hide_idle_cursor(window, cx); self.schedule_pump(window, cx); let t = Tokens::of(cx); let route = self.current_route; let required = self.update.required(); let page = match route { _ if required => self.update_required(t).into_any_element(), Route::Login | Route::Register => self.auth_page(route, cx).into_any_element(), Route::Chat => self.chat_page(cx).into_any_element(), }; let banner = (route == Route::Chat && !required) .then(|| connection_notice(&self.connection, t)) .flatten(); div() .relative() .flex() .flex_col() .size_full() .bg(t.ground()) .text_color(t.paper()) .text_size(text(style::text::UI)) .track_focus(&self.focus) .on_action(cx.listener(|this, _: &FocusFind, window, cx| this.open_jump(window, cx))) .on_action(cx.listener(|this, _: &CloseSettings, window, cx| { if this.zoom.is_some() { this.zoom = None; cx.notify(); } else if this.chat.session.friends_open { this.close_friends(window, cx); } else if this.chat.goto.open { this.close_jump(window, cx); } else if this .chat .session .viewer .as_ref() .is_some_and(|v| v.fullscreen) { this.toggle_fullscreen(cx); } else if this.chat.session.view != View::Chat { this.show_view(View::Chat, window, cx); } else { this.cancel_composer(window, cx); } })) .on_key_down(cx.listener(|this, event: &KeyDownEvent, window, cx| { this.voice_key_down(event, window, cx); })) .on_key_up(cx.listener(|this, event: &KeyUpEvent, _, cx| { this.voice_key_up(event, cx); })) .on_modifiers_changed( cx.listener(|this, event: &ModifiersChangedEvent, window, cx| { this.voice_modifiers(event, window, cx); }), ) .children(banner) .child(div().flex_1().min_h_0().child(page)) .children( (route == Route::Chat && !required) .then(|| self.jump_box(t, cx)) .flatten(), ) .children( self.zoom .as_ref() .map(|zoom| zoom_view(zoom, &cx.entity(), t)), ) } }