forge
Explore
Log in

Don't you dare go Hollow

Add user admin, font size, music voice profile and adaptive jitter

Browse files at this commit

3950bc853afeffb8254d060622b8a3d49a5b5620Ahmet Kaan GümüşParent: 0df2293
  • feat
    • add user admin, font size, music voice profile and adaptive jitter
Show full message
✨ feat: add user admin, font size, music voice profile and adaptive jitter

Admin: staff get a users page with search and role changes through new Users and SetRole requests. The first account created becomes staff, and username lookup ignores case.

Settings: a font size choice (small, medium, large) next to the theme. A voice profile picks Voice (Opus VoIP, 48 kb/s) or Music (Opus Audio, 96 kb/s).

Voice: capture opens a mono stream instead of downmixing stereo. The jitter buffer sizes itself from measured arrival jitter, recovers lost packets with FEC or concealment, skips quiet frames to absorb drift and fades the gate in and out.

New request and response variants are appended to keep wire indices stable.
.gitignoremodified+2 -0
@@ -1,3 +1,5 @@
11 /target
22 Cargo.lock
33 configs/server_config.toml
4+*.pem
5+yumush.db*
crates/client/src/gui.rsmodified+25 -11
@@ -13,7 +13,7 @@ use common::{
1313 use gpui_kit::{
1414 AnyElement, App, AppContext, AsyncWindowContext, Context, Div, ElementId, Entity, FontWeight,
1515 Hsla, Image, ImageFormat, InteractiveElement, IntoElement, KeyBinding, KeyDownEvent,
16- KeyUpEvent, ModifiersChangedEvent, ParentElement, Pixels, Render, RenderOnce, Stateful,
16+ KeyUpEvent, ModifiersChangedEvent, ParentElement, Pixels, Rems, Render, RenderOnce, Stateful,
1717 StatefulInteractiveElement, Styled, WeakEntity, Window, actions,
1818 base::Selectable,
1919 component::{
@@ -21,7 +21,7 @@ use gpui_kit::{
2121 input::{Input, InputEvent, InputState},
2222 notification::Notification,
2323 },
24- div, hsla, img, px, rgb,
24+ div, hsla, img, px, rems, rgb,
2525 };
2626 use jiff::{Timestamp, tz::TimeZone};
2727 use tokio::sync::mpsc;
@@ -30,9 +30,10 @@ use uuid::Uuid;
3030 use crate::{
3131 accounts::{self, Accounts},
3232 network::{NetworkEvent, NetworkHandle},
33- settings::{Look, Settings, ThemeChoice},
33+ settings::{Look, Scale, Settings, ThemeChoice},
3434 };
3535
36+mod admin;
3637 mod auth;
3738 mod chat;
3839 mod community_settings;
@@ -53,6 +54,12 @@ use voice_settings::VoiceControls;
5354
5455 actions!(yumush, [FocusFind, CloseSettings]);
5556
57+pub const BASE_FONT: f32 = 14.;
58+
59+pub fn text(size: f32) -> Rems {
60+ rems(size / BASE_FONT)
61+}
62+
5663 const TINTS: [u32; 10] = [
5764 0x10b981, 0xa855f7, 0xf59e0b, 0xf97316, 0xec4899, 0x0ea5e9, 0x22c55e, 0xef4444, 0x06b6d4,
5865 0xd946ef,
@@ -159,6 +166,7 @@ pub fn sync_accent(accent: Hsla, cx: &mut App) {
159166
160167 pub fn sync_theme(cx: &mut App) {
161168 let palette = palette(cx);
169+ let font_size = cx.global::<Scale>().0.pixels();
162170 let theme = Theme::global_mut(cx);
163171 let colors = &mut theme.colors;
164172
@@ -185,7 +193,7 @@ pub fn sync_theme(cx: &mut App) {
185193 theme.tokens = (&theme.colors).into();
186194 theme.radius = px(6.);
187195 theme.radius_lg = px(10.);
188- theme.font_size = px(14.);
196+ theme.font_size = font_size;
189197 theme.focus_ring = false;
190198 }
191199
@@ -198,7 +206,7 @@ pub fn tint(id: &str) -> Hsla {
198206 rgb(TINTS[hasher.finish() as usize % TINTS.len()]).into()
199207 }
200208
201-pub fn badge(palette: Palette, id: &str, name: &str, size: Pixels, font: Pixels) -> Div {
209+pub fn badge(palette: Palette, id: &str, name: &str, size: Pixels, font: Rems) -> Div {
202210 let initial = name
203211 .chars()
204212 .next()
@@ -223,7 +231,7 @@ pub fn avatar(
223231 palette: Palette,
224232 user: &User,
225233 size: Pixels,
226- font: Pixels,
234+ font: Rems,
227235 avatars: &HashMap<String, Arc<Image>>,
228236 ) -> Div {
229237 let Some(image) = user.avatar_id.as_ref().and_then(|id| avatars.get(id)) else {
@@ -249,7 +257,7 @@ pub fn community_icon(
249257 palette: Palette,
250258 community: &Community,
251259 size: Pixels,
252- font: Pixels,
260+ font: Rems,
253261 avatars: &HashMap<String, Arc<Image>>,
254262 ) -> Div {
255263 match &community.kind {
@@ -325,7 +333,7 @@ impl Render for Tip {
325333 .border_color(palette.border)
326334 .bg(palette.panel)
327335 .text_color(palette.text)
328- .text_size(px(12.))
336+ .text_size(text(12.))
329337 .child(self.0)
330338 }
331339 }
@@ -394,7 +402,7 @@ pub fn rank_tag(rank: Option<Rank>, palette: Palette) -> Option<Div> {
394402 .py(px(1.))
395403 .rounded(px(4.))
396404 .bg(palette.hover)
397- .text_size(px(11.))
405+ .text_size(text(11.))
398406 .text_color(color)
399407 .child(label),
400408 )
@@ -598,6 +606,9 @@ impl Yumush {
598606 .status_input
599607 .update(cx, |input, cx| input.set_value(status, window, cx));
600608 }
609+ if view == View::Admin {
610+ self.load_users(window, cx);
611+ }
601612 if view == View::CommunitySettings {
602613 let name = self
603614 .chat
@@ -620,7 +631,7 @@ impl Yumush {
620631
621632 pub fn themed(&self, cx: &App) -> Palette {
622633 let community = match self.chat.view {
623- View::Settings => None,
634+ View::Settings | View::Admin => None,
624635 _ => self.chat.selected_community(),
625636 };
626637 palette(cx).for_community(community, &self.chat.hues)
@@ -673,6 +684,9 @@ impl Yumush {
673684 if self.is_me(&user.id) {
674685 self.user = Some(user.clone());
675686 self.accounts.rename(user);
687+ if !self.is_staff() && self.chat.view == View::Admin {
688+ self.chat.view = View::Chat;
689+ }
676690 }
677691 self.request_user_avatar(user, cx);
678692 }
@@ -848,7 +862,7 @@ impl Render for Yumush {
848862 .size_full()
849863 .bg(palette.window)
850864 .text_color(palette.text)
851- .text_size(px(13.))
865+ .text_size(text(13.))
852866 .track_focus(&self.focus)
853867 .on_action(
854868 cx.listener(|this, _: &FocusFind, window, cx| this.chat.focus_find(window, cx)),
crates/client/src/gui/admin.rsadded+217 -0
@@ -0,0 +1,217 @@
1+use super::text;
2+use common::{
3+ model::{Role, User},
4+ permission,
5+};
6+use gpui_kit::{
7+ App, Context, Div, Entity, IntoElement, ParentElement, Styled, Window, component::input::Input,
8+ div, prelude::FluentBuilder as _, px,
9+};
10+
11+use super::{
12+ Palette, Yumush, avatar, clickable,
13+ community_settings::search_text,
14+ entity_action, notify_error,
15+ settings_page::{page, section},
16+};
17+
18+impl Yumush {
19+ pub(super) fn is_staff(&self) -> bool {
20+ self.user.as_ref().is_some_and(|me| me.role == Role::Staff)
21+ }
22+
23+ pub(super) fn load_users(&self, window: &mut Window, cx: &mut Context<Self>) {
24+ if !self.is_staff() {
25+ return;
26+ }
27+ let network = self.network.clone();
28+
29+ cx.spawn_in(window, async move |this, cx| {
30+ let users = match network.users().await {
31+ Ok(users) => users,
32+ Err(error) => {
33+ notify_error(&this, cx, error);
34+ return;
35+ }
36+ };
37+
38+ let _ = this.update(cx, |yumush, cx| {
39+ for user in &users {
40+ yumush.request_user_avatar(user, cx);
41+ }
42+ yumush.chat.admin_users = users;
43+ cx.notify();
44+ });
45+ })
46+ .detach();
47+ }
48+
49+ fn set_admin_role(
50+ &mut self,
51+ user_id: &str,
52+ role: Role,
53+ window: &mut Window,
54+ cx: &mut Context<Self>,
55+ ) {
56+ let network = self.network.clone();
57+ let user_id = user_id.to_string();
58+
59+ cx.spawn_in(window, async move |this, cx| {
60+ match network.set_role(&user_id, role).await {
61+ Ok(user) => {
62+ let _ = this.update(cx, |yumush, cx| {
63+ let index = yumush
64+ .chat
65+ .admin_users
66+ .iter()
67+ .position(|existing| existing.id == user.id);
68+ if let Some(index) = index {
69+ yumush.chat.admin_users[index] = user;
70+ }
71+ cx.notify();
72+ });
73+ }
74+ Err(error) => notify_error(&this, cx, error),
75+ }
76+ })
77+ .detach();
78+ }
79+
80+ fn delete_admin_user(&mut self, user_id: &str, window: &mut Window, cx: &mut Context<Self>) {
81+ if self.chat.pending_admin_delete.as_deref() != Some(user_id) {
82+ self.chat.pending_admin_delete = Some(user_id.to_string());
83+ cx.notify();
84+ return;
85+ }
86+ self.chat.pending_admin_delete = None;
87+ let network = self.network.clone();
88+ let user_id = user_id.to_string();
89+
90+ cx.spawn_in(window, async move |this, cx| {
91+ match network.delete_user(&user_id).await {
92+ Ok(()) => {
93+ let _ = this.update(cx, |yumush, cx| {
94+ yumush.chat.admin_users.retain(|user| user.id != user_id);
95+ cx.notify();
96+ });
97+ }
98+ Err(error) => notify_error(&this, cx, error),
99+ }
100+ })
101+ .detach();
102+ }
103+
104+ pub(super) fn admin_page(
105+ &self,
106+ entity: &Entity<Self>,
107+ palette: Palette,
108+ cx: &App,
109+ ) -> impl IntoElement {
110+ let query = search_text(&self.chat.admin_search, cx);
111+ let rows: Vec<Div> = match self.user.as_ref() {
112+ Some(me) => self
113+ .chat
114+ .admin_users
115+ .iter()
116+ .filter(|user| user.username.to_lowercase().contains(query.as_str()))
117+ .map(|user| self.admin_row(user, me, entity, palette))
118+ .collect(),
119+ None => Vec::new(),
120+ };
121+
122+ page(
123+ "admin_scroll",
124+ entity,
125+ palette,
126+ "Admin",
127+ vec![
128+ div()
129+ .child(Input::new(&self.chat.admin_search))
130+ .into_any_element(),
131+ section("Users", palette, rows).into_any_element(),
132+ ],
133+ )
134+ }
135+
136+ fn admin_row(&self, user: &User, me: &User, entity: &Entity<Self>, palette: Palette) -> Div {
137+ let is_self = user.id == me.id;
138+ let staff = user.role == Role::Staff;
139+ let pending_delete = self.chat.pending_admin_delete.as_deref() == Some(user.id.as_str());
140+ let role_id = user.id.clone();
141+ let delete_id = user.id.clone();
142+ let next_role = if staff { Role::User } else { Role::Staff };
143+
144+ let role_button = clickable(
145+ format!("role_{}", user.id),
146+ palette,
147+ entity_action(entity, move |yumush, window, cx| {
148+ yumush.set_admin_role(&role_id, next_role, window, cx)
149+ }),
150+ )
151+ .h(px(28.))
152+ .px(px(8.))
153+ .flex()
154+ .items_center()
155+ .rounded(px(6.))
156+ .text_size(text(13.))
157+ .text_color(palette.muted)
158+ .child(if staff { "Remove staff" } else { "Make staff" });
159+
160+ let delete_button = clickable(
161+ format!("delete_user_{}", user.id),
162+ palette,
163+ entity_action(entity, move |yumush, window, cx| {
164+ yumush.delete_admin_user(&delete_id, window, cx)
165+ }),
166+ )
167+ .h(px(28.))
168+ .px(px(8.))
169+ .flex()
170+ .items_center()
171+ .rounded(px(6.))
172+ .text_size(text(13.))
173+ .border_1()
174+ .border_color(palette.danger.opacity(0.5))
175+ .text_color(palette.danger)
176+ .when(pending_delete, |this| {
177+ this.bg(palette.danger).text_color(palette.on_accent)
178+ })
179+ .child(if pending_delete { "Confirm" } else { "Delete" });
180+
181+ div()
182+ .h(px(48.))
183+ .px(px(12.))
184+ .flex()
185+ .items_center()
186+ .gap(px(8.))
187+ .child(avatar(
188+ palette,
189+ user,
190+ px(20.),
191+ text(10.),
192+ &self.chat.avatars,
193+ ))
194+ .child(
195+ div()
196+ .flex_1()
197+ .min_w_0()
198+ .flex()
199+ .items_center()
200+ .gap(px(6.))
201+ .child(div().truncate().child(user.username.clone()))
202+ .when(staff, |this| {
203+ this.child(
204+ div()
205+ .text_size(text(11.))
206+ .text_color(palette.accent)
207+ .child("Staff"),
208+ )
209+ }),
210+ )
211+ .children(permission::can_set_role(me.role, is_self).then_some(role_button))
212+ .children(
213+ (!is_self && permission::can_delete_user(me.role, is_self, user.role))
214+ .then_some(delete_button),
215+ )
216+ }
217+}
crates/client/src/gui/auth.rsmodified+26 -34
@@ -1,9 +1,11 @@
1+use super::{
2+ settings_page::{segment, segment_track},
3+ text,
4+};
15 use gpui_kit::{
26 Context, Div, Entity, FontWeight, IntoElement, ParentElement, Styled, Window,
37 component::input::{Input, InputEvent, InputState},
4- div,
5- prelude::FluentBuilder as _,
6- px,
8+ div, px,
79 };
810
911 use gpui_kit::{AnyElement, StatefulInteractiveElement, assets::IconName, component::Icon};
@@ -75,6 +77,14 @@ fn submit(this: &mut Yumush, window: &mut Window, cx: &mut Context<Yumush>) {
7577 }
7678
7779 pub(super) fn field(palette: Palette, input: &Entity<InputState>) -> Div {
80+ frame(palette, Input::new(input))
81+}
82+
83+fn password_field(palette: Palette, input: &Entity<InputState>) -> Div {
84+ frame(palette, Input::new(input).mask_toggle())
85+}
86+
87+fn frame(palette: Palette, input: Input) -> Div {
7888 div()
7989 .h(px(32.))
8090 .flex()
@@ -84,7 +94,7 @@ pub(super) fn field(palette: Palette, input: &Entity<InputState>) -> Div {
8494 .border_color(palette.border)
8595 .bg(palette.field)
8696 .child(
87- Input::new(input)
97+ input
8898 .appearance(false)
8999 .text_color(palette.text)
90100 .flex_1()
@@ -113,12 +123,7 @@ impl Yumush {
113123 .font_weight(FontWeight::MEDIUM)
114124 .child(action_label);
115125
116- let tabs = div()
117- .flex()
118- .p(px(3.))
119- .gap(px(3.))
120- .rounded(px(8.))
121- .bg(palette.window)
126+ let tabs = segment_track(palette)
122127 .child(tab(palette, &entity, Route::Login, "Log in", route))
123128 .child(tab(palette, &entity, Route::Register, "Register", route));
124129
@@ -141,14 +146,14 @@ impl Yumush {
141146 .bg(palette.panel)
142147 .child(
143148 div()
144- .text_size(px(18.))
149+ .text_size(text(18.))
145150 .font_weight(FontWeight::SEMIBOLD)
146151 .child("yumush"),
147152 )
148153 .children(self.saved_accounts(&entity, palette))
149154 .child(tabs)
150155 .child(field(palette, &self.auth.username_input))
151- .child(field(palette, &self.auth.password_input))
156+ .child(password_field(palette, &self.auth.password_input))
152157 .child(action_button),
153158 )
154159 }
@@ -184,7 +189,7 @@ impl Yumush {
184189 &account.user_id,
185190 &account.username,
186191 px(22.),
187- px(11.),
192+ text(11.),
188193 )
189194 .rounded_full(),
190195 )
@@ -231,27 +236,14 @@ fn tab(
231236 route: Route,
232237 ) -> impl IntoElement {
233238 let entity = entity.clone();
234- let active = route == target;
235- clickable(label, palette, move |window, cx| {
236- entity.update(cx, |this, cx| this.change_page(target, window, cx));
237- })
239+ segment(
240+ clickable(label, palette, move |window, cx| {
241+ entity.update(cx, |this, cx| this.change_page(target, window, cx));
242+ }),
243+ route == target,
244+ palette,
245+ )
238246 .flex_1()
239- .flex()
240- .justify_center()
241- .py(px(4.))
242- .rounded(px(6.))
243- .text_size(px(12.))
244- .when(active, |tab| {
245- tab.bg(palette.panel)
246- .border_1()
247- .border_color(palette.border)
248- .text_color(palette.text)
249- .font_weight(FontWeight::MEDIUM)
250- })
251- .when(!active, |tab| {
252- tab.border_1()
253- .border_color(palette.window)
254- .text_color(palette.muted)
255- })
247+ .text_size(text(12.))
256248 .child(label)
257249 }
crates/client/src/gui/chat.rsmodified+24 -12
@@ -1,3 +1,4 @@
1+use super::text;
12 use std::{
23 collections::{HashMap, HashSet},
34 sync::Arc,
@@ -46,6 +47,7 @@ pub enum View {
4647 Chat,
4748 Settings,
4849 CommunitySettings,
50+ Admin,
4951 }
5052
5153 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -113,6 +115,9 @@ pub struct Chat {
113115 pub(super) friends: Friends,
114116 pub(super) invitations: Vec<Invitation>,
115117 pub(super) pending_user_delete: Option<String>,
118+ pub(super) pending_admin_delete: Option<String>,
119+ pub(super) admin_users: Vec<User>,
120+ pub(super) admin_search: Entity<InputState>,
116121 pub(super) voice: HashMap<String, Vec<String>>,
117122 pub(super) voice_state: VoiceState,
118123 pub(super) speaking: HashSet<String>,
@@ -149,7 +154,8 @@ impl Chat {
149154
150155 let ban_search = new_input("Search...", window, cx);
151156 let log_search = new_input("Search...", window, cx);
152- for search in [&ban_search, &log_search] {
157+ let admin_search = new_input("Search...", window, cx);
158+ for search in [&ban_search, &log_search, &admin_search] {
153159 cx.subscribe_in(search, window, |_, _, event, window, cx| {
154160 if matches!(event, InputEvent::Change) {
155161 window.refresh();
@@ -191,6 +197,9 @@ impl Chat {
191197 user_requests: HashSet::new(),
192198 delete_step: DeleteStep::Idle,
193199 pending_user_delete: None,
200+ pending_admin_delete: None,
201+ admin_users: vec![],
202+ admin_search,
194203 voice: HashMap::new(),
195204 voice_state: VoiceState::Off,
196205 speaking: HashSet::new(),
@@ -531,6 +540,8 @@ impl Chat {
531540 self.found = None;
532541 self.select(None);
533542 self.unread.clear();
543+ self.admin_users.clear();
544+ self.pending_admin_delete = None;
534545 self.view = View::Chat;
535546 self.delete_step = DeleteStep::Idle;
536547 self.voice.clear();
@@ -591,7 +602,7 @@ fn empty_state(palette: Palette) -> impl IntoElement {
591602 .rounded(px(4.))
592603 .border_1()
593604 .border_color(palette.border)
594- .text_size(px(11.))
605+ .text_size(text(11.))
595606 .child(FIND_HINT),
596607 )
597608 .child("Find a user")
@@ -648,7 +659,7 @@ impl RenderOnce for MembersTrigger {
648659 .take(3)
649660 .enumerate()
650661 .map(|(index, user)| {
651- avatar(palette, user, px(18.), px(9.), &self.avatars)
662+ avatar(palette, user, px(18.), text(9.), &self.avatars)
652663 .border_2()
653664 .border_color(palette.panel)
654665 .when(index > 0, |this| this.ml(px(-6.)))
@@ -663,7 +674,7 @@ impl RenderOnce for MembersTrigger {
663674 .items_center()
664675 .gap(px(6.))
665676 .rounded(px(6.))
666- .text_size(px(12.))
677+ .text_size(text(12.))
667678 .text_color(palette.muted)
668679 .child(div().flex().children(avatars))
669680 .child(self.members.len().to_string()),
@@ -702,6 +713,7 @@ impl Yumush {
702713 .bg(palette.panel)
703714 .map(|panel| match self.chat.view {
704715 View::Settings => panel.child(self.settings_page(entity, palette, cx)),
716+ View::Admin => panel.child(self.admin_page(entity, palette, cx)),
705717 View::CommunitySettings => {
706718 panel.child(self.community_settings_page(entity, palette, cx))
707719 }
@@ -731,7 +743,7 @@ impl Yumush {
731743 .border_b_2()
732744 .border_color(palette.accent)
733745 .children(community.map(|community| {
734- community_icon(palette, community, px(20.), px(10.), &self.chat.avatars)
746+ community_icon(palette, community, px(20.), text(10.), &self.chat.avatars)
735747 }))
736748 .child(
737749 div()
@@ -1295,7 +1307,7 @@ impl Yumush {
12951307 Anchor::TopRight,
12961308 user,
12971309 entity,
1298- avatar(palette, user, px(20.), px(10.), &self.chat.avatars)
1310+ avatar(palette, user, px(20.), text(10.), &self.chat.avatars)
12991311 .border_2()
13001312 .border_color(ring)
13011313 .cursor_pointer()
@@ -1422,7 +1434,7 @@ fn members_popover(entity: &Entity<Yumush>, chat: &Chat, palette: Palette) -> im
14221434 .items_center()
14231435 .gap(px(8.))
14241436 .rounded(px(6.))
1425- .child(avatar(palette, user, px(18.), px(9.), &avatars))
1437+ .child(avatar(palette, user, px(18.), text(9.), &avatars))
14261438 .child(
14271439 div()
14281440 .flex_1()
@@ -1445,7 +1457,7 @@ fn members_popover(entity: &Entity<Yumush>, chat: &Chat, palette: Palette) -> im
14451457 )
14461458 .children((!user.status.is_empty()).then(|| {
14471459 div()
1448- .text_size(px(11.))
1460+ .text_size(text(11.))
14491461 .text_color(palette.muted)
14501462 .truncate()
14511463 .child(user.status.clone())
@@ -1492,8 +1504,8 @@ fn render_message(
14921504 .items_center()
14931505 .gap(px(8.))
14941506 .child(match author {
1495- Some(user) => avatar(palette, user, px(20.), px(10.), &chat.avatars),
1496- None => badge(palette, &message.user_id, username, px(20.), px(10.)).rounded_full(),
1507+ Some(user) => avatar(palette, user, px(20.), text(10.), &chat.avatars),
1508+ None => badge(palette, &message.user_id, username, px(20.), text(10.)).rounded_full(),
14971509 })
14981510 .child(
14991511 div()
@@ -1539,7 +1551,7 @@ fn render_message(
15391551 .child(author)
15401552 .child(
15411553 div()
1542- .text_size(px(12.))
1554+ .text_size(text(12.))
15431555 .text_color(palette.muted)
15441556 .child(id_time(&message.id, "%H:%M")),
15451557 ),
@@ -1571,7 +1583,7 @@ fn render_message(
15711583 .when(message.edited, |this| {
15721584 this.child(
15731585 div()
1574- .text_size(px(11.))
1586+ .text_size(text(11.))
15751587 .text_color(palette.muted)
15761588 .child("(edited)"),
15771589 )
crates/client/src/gui/community_settings.rsmodified+12 -11
@@ -1,3 +1,4 @@
1+use super::text;
12 use std::{collections::HashMap, sync::Arc};
23
34 use common::{
@@ -98,7 +99,7 @@ impl Yumush {
9899 palette,
99100 community,
100101 px(64.),
101- px(24.),
102+ text(24.),
102103 &self.chat.avatars,
103104 ),
104105 title: community.name.clone(),
@@ -144,7 +145,7 @@ impl Yumush {
144145 .gap(px(8.))
145146 .child(
146147 div()
147- .text_size(px(12.))
148+ .text_size(text(12.))
148149 .text_color(palette.muted)
149150 .child(bans_count.to_string()),
150151 )
@@ -435,7 +436,7 @@ fn view_control(
435436 .rounded(px(6.))
436437 .border_1()
437438 .border_color(palette.border)
438- .text_size(px(13.))
439+ .text_size(text(13.))
439440 .child("View")
440441 }
441442
@@ -469,7 +470,7 @@ fn sort_control<T: Copy + PartialEq + 'static, const N: usize>(
469470 .flex()
470471 .items_center()
471472 .rounded(px(4.))
472- .text_size(px(12.))
473+ .text_size(text(12.))
473474 .text_color(if active { palette.text } else { palette.muted })
474475 .when(active, |this| this.bg(palette.hover))
475476 .child(label)
@@ -486,7 +487,7 @@ fn moderation_body(
486487 ) -> impl IntoElement {
487488 let list = if rows.is_empty() {
488489 div()
489- .text_size(px(13.))
490+ .text_size(text(13.))
490491 .text_color(palette.muted)
491492 .child(empty)
492493 .into_any_element()
@@ -503,7 +504,7 @@ fn moderation_body(
503504 .child(div().id(id).max_h(px(360.)).overflow_y_scroll().child(list))
504505 }
505506
506-fn search_text(input: &Entity<InputState>, cx: &App) -> String {
507+pub(super) fn search_text(input: &Entity<InputState>, cx: &App) -> String {
507508 input.read(cx).text().to_string().trim().to_lowercase()
508509 }
509510
@@ -577,13 +578,13 @@ fn log_row(entry: &LogEntry, palette: Palette, avatars: &HashMap<String, Arc<Ima
577578 entry
578579 .actor
579580 .as_ref()
580- .map(|actor| avatar(palette, actor, px(20.), px(10.), avatars)),
581+ .map(|actor| avatar(palette, actor, px(20.), text(10.), avatars)),
581582 )
582583 .child(div().flex_1().min_w_0().truncate().child(log_text(entry)))
583584 .child(
584585 div()
585586 .flex_shrink_0()
586- .text_size(px(11.))
587+ .text_size(text(11.))
587588 .text_color(palette.muted)
588589 .child(id_time(&entry.id, "%b %-d, %H:%M")),
589590 )
@@ -608,7 +609,7 @@ fn leave_control(
608609 .rounded(px(6.))
609610 .border_1()
610611 .border_color(palette.danger.opacity(0.5))
611- .text_size(px(13.))
612+ .text_size(text(13.))
612613 .text_color(palette.danger)
613614 .child("Leave")
614615 }
@@ -629,7 +630,7 @@ fn ban_row(
629630 .flex()
630631 .items_center()
631632 .gap(px(8.))
632- .child(avatar(palette, user, px(20.), px(10.), avatars))
633+ .child(avatar(palette, user, px(20.), text(10.), avatars))
633634 .child(
634635 div()
635636 .flex_1()
@@ -639,7 +640,7 @@ fn ban_row(
639640 .child(user.username.clone())
640641 .children(ban.reason.clone().map(|reason| {
641642 div()
642- .text_size(px(11.))
643+ .text_size(text(11.))
643644 .text_color(palette.muted)
644645 .truncate()
645646 .child(reason)
crates/client/src/gui/composer.rsmodified+3 -2
@@ -1,3 +1,4 @@
1+use super::text;
12 use common::{
23 constant::MAXIMUM_FORWARD_MESSAGES,
34 validate::{validate_message_body, validate_new_message},
@@ -59,7 +60,7 @@ pub fn selection_bar(
5960 .flex()
6061 .items_center()
6162 .rounded(px(6.))
62- .text_size(px(12.))
63+ .text_size(text(12.))
6364 .child("Forward"),
6465 )
6566 .child(cancel_button(entity, palette))
@@ -75,7 +76,7 @@ fn bar(palette: Palette) -> Div {
7576 .gap(px(6.))
7677 .rounded(px(6.))
7778 .bg(palette.hover)
78- .text_size(px(12.))
79+ .text_size(text(12.))
7980 .text_color(palette.muted)
8081 }
8182
crates/client/src/gui/forward.rsmodified+2 -1
@@ -1,3 +1,4 @@
1+use super::text;
12 use gpui_kit::{
23 AppContext, Context, Entity, InteractiveElement, IntoElement, ParentElement, Render,
34 StatefulInteractiveElement, Styled, Window,
@@ -85,7 +86,7 @@ impl Render for Forward {
8586 palette,
8687 community,
8788 px(16.),
88- px(9.),
89+ text(9.),
8990 &yumush.chat.avatars,
9091 ))
9192 .child(
crates/client/src/gui/media_view.rsmodified+6 -5
@@ -1,3 +1,4 @@
1+use super::text;
12 use std::{
23 collections::{HashMap, HashSet},
34 path::PathBuf,
@@ -568,7 +569,7 @@ fn name_block(attachment: &Attachment, detail: String, palette: Palette) -> impl
568569 )
569570 .child(
570571 div()
571- .text_size(px(12.))
572+ .text_size(text(12.))
572573 .text_color(palette.muted)
573574 .child(detail),
574575 )
@@ -731,7 +732,7 @@ fn embed_view(loaded: &LoadedEmbed, palette: Palette) -> impl IntoElement {
731732 .bg(palette.panel)
732733 .children(embed.site.clone().map(|site| {
733734 div()
734- .text_size(px(12.))
735+ .text_size(text(12.))
735736 .text_color(palette.muted)
736737 .child(site)
737738 }))
@@ -747,7 +748,7 @@ fn embed_view(loaded: &LoadedEmbed, palette: Palette) -> impl IntoElement {
747748 }))
748749 .children(embed.description.clone().map(|description| {
749750 div()
750- .text_size(px(13.))
751+ .text_size(text(13.))
751752 .text_color(palette.body)
752753 .line_clamp(3)
753754 .child(description)
@@ -781,7 +782,7 @@ pub fn pending_row(
781782 .py(px(4.))
782783 .rounded(px(6.))
783784 .bg(palette.hover)
784- .text_size(px(12.))
785+ .text_size(text(12.))
785786 .child(
786787 div()
787788 .max_w(px(180.))
@@ -812,7 +813,7 @@ pub fn pending_row(
812813 div()
813814 .px(px(10.))
814815 .py(px(4.))
815- .text_size(px(12.))
816+ .text_size(text(12.))
816817 .text_color(palette.muted)
817818 .child("…"),
818819 )
crates/client/src/gui/message_actions.rsmodified+3 -2
@@ -1,3 +1,4 @@
1+use super::text;
12 use common::model::{Message, User};
23 use gpui_kit::{
34 Context, Entity, FontWeight, InteractiveElement, IntoElement, ParentElement, Styled, Window,
@@ -26,9 +27,9 @@ pub fn quote_line(message: &Message, chat: &Chat, palette: Palette) -> Option<im
2627 .pl(px(8.))
2728 .border_l_2()
2829 .border_color(palette.accent.opacity(0.6))
29- .text_size(px(12.))
30+ .text_size(text(12.))
3031 .text_color(palette.muted)
31- .children(author.map(|user| avatar(palette, user, px(14.), px(7.), &chat.avatars)))
32+ .children(author.map(|user| avatar(palette, user, px(14.), text(7.), &chat.avatars)))
3233 .children(author.map(|user| {
3334 div()
3435 .flex_shrink_0()
crates/client/src/gui/profile.rsmodified+5 -4
@@ -1,3 +1,4 @@
1+use super::text;
12 use std::{collections::HashMap, sync::Arc};
23
34 use common::{
@@ -155,7 +156,7 @@ impl Card {
155156 .border_1()
156157 .border_color(palette.border)
157158 .bg(palette.panel)
158- .child(avatar(palette, &self.user, px(48.), px(18.), avatars))
159+ .child(avatar(palette, &self.user, px(48.), text(18.), avatars))
159160 .child(
160161 div()
161162 .flex()
@@ -163,7 +164,7 @@ impl Card {
163164 .gap(px(6.))
164165 .child(
165166 div()
166- .text_size(px(15.))
167+ .text_size(text(15.))
167168 .font_weight(FontWeight::SEMIBOLD)
168169 .child(self.user.username.clone()),
169170 )
@@ -171,13 +172,13 @@ impl Card {
171172 )
172173 .children((!self.user.status.is_empty()).then(|| {
173174 div()
174- .text_size(px(12.))
175+ .text_size(text(12.))
175176 .text_color(palette.muted)
176177 .child(self.user.status.clone())
177178 }))
178179 .child(
179180 div()
180- .text_size(px(12.))
181+ .text_size(text(12.))
181182 .text_color(palette.muted)
182183 .child(format!("Joined {}", id_time(&self.user.id, "%b %-d, %Y"))),
183184 )
crates/client/src/gui/settings_page.rsmodified+82 -39
@@ -1,3 +1,4 @@
1+use super::text;
12 use std::path::Path;
23
34 use common::{error::Error, model::User};
@@ -8,14 +9,14 @@ use gpui_kit::{
89 component::{Icon, input::InputState},
910 div,
1011 prelude::FluentBuilder as _,
11- px,
12+ px, transparent_black,
1213 };
1314
1415 use super::{
1516 Palette, Tooltip as _, Yumush, auth::field, avatar, chat::DeleteStep, chat::View, clickable,
1617 notify_error, primary_button,
1718 };
18-use crate::settings::{self, ThemeChoice};
19+use crate::settings::{self, FontSize, ThemeChoice};
1920
2021 const THEMES: [(ThemeChoice, &str); 4] = [
2122 (ThemeChoice::System, "System"),
@@ -24,6 +25,12 @@ const THEMES: [(ThemeChoice, &str); 4] = [
2425 (ThemeChoice::Black, "Black"),
2526 ];
2627
28+const FONT_SIZES: [(FontSize, &str); 3] = [
29+ (FontSize::Small, "Small"),
30+ (FontSize::Medium, "Medium"),
31+ (FontSize::Large, "Large"),
32+];
33+
2734 impl Yumush {
2835 pub(super) fn settings_page(
2936 &self,
@@ -37,7 +44,7 @@ impl Yumush {
3744 picture_card(
3845 Picture {
3946 id: "avatar_picker",
40- image: avatar(palette, user, px(64.), px(24.), &self.chat.avatars),
47+ image: avatar(palette, user, px(64.), text(24.), &self.chat.avatars),
4148 title: user.username.clone(),
4249 subtitle: user.status.clone(),
4350 removable: user.avatar_id.is_some(),
@@ -90,16 +97,28 @@ impl Yumush {
9097 section(
9198 "Appearance",
9299 palette,
93- vec![row(
94- "Theme",
95- segmented(
96- THEMES,
97- self.settings.theme,
98- entity,
99- palette,
100- Yumush::set_theme,
100+ vec![
101+ row(
102+ "Theme",
103+ segmented(
104+ THEMES,
105+ self.settings.theme,
106+ entity,
107+ palette,
108+ Yumush::set_theme,
109+ ),
101110 ),
102- )],
111+ row(
112+ "Font size",
113+ segmented(
114+ FONT_SIZES,
115+ self.settings.font_size,
116+ entity,
117+ palette,
118+ Yumush::set_font_size,
119+ ),
120+ ),
121+ ],
103122 )
104123 .into_any_element(),
105124 );
@@ -241,7 +260,13 @@ impl Yumush {
241260
242261 pub(super) fn set_theme(&mut self, theme: ThemeChoice, cx: &mut Context<Self>) {
243262 self.settings.theme = theme;
244- settings::apply(theme, cx);
263+ settings::apply(theme, self.settings.font_size, cx);
264+ self.commit_settings(cx);
265+ }
266+
267+ pub(super) fn set_font_size(&mut self, font_size: FontSize, cx: &mut Context<Self>) {
268+ self.settings.font_size = font_size;
269+ settings::apply(self.settings.theme, font_size, cx);
245270 self.commit_settings(cx);
246271 }
247272
@@ -346,7 +371,7 @@ fn card(
346371 .child(
347372 div()
348373 .px(px(2.))
349- .text_size(px(12.))
374+ .text_size(text(12.))
350375 .font_weight(FontWeight::MEDIUM)
351376 .text_color(title_color)
352377 .child(title),
@@ -392,7 +417,7 @@ pub(super) fn text_row(
392417 .gap(px(6.))
393418 .child(
394419 div()
395- .text_size(px(12.))
420+ .text_size(text(12.))
396421 .text_color(palette.muted)
397422 .child(editable.label),
398423 )
@@ -471,7 +496,7 @@ pub(super) fn picture_card(picture: Picture, entity: &Entity<Yumush>, palette: P
471496 .gap(px(2.))
472497 .child(
473498 div()
474- .text_size(px(16.))
499+ .text_size(text(16.))
475500 .font_weight(FontWeight::SEMIBOLD)
476501 .truncate()
477502 .child(title),
@@ -479,7 +504,7 @@ pub(super) fn picture_card(picture: Picture, entity: &Entity<Yumush>, palette: P
479504 .when(!subtitle.is_empty(), |this| {
480505 this.child(
481506 div()
482- .text_size(px(12.))
507+ .text_size(text(12.))
483508 .text_color(palette.muted)
484509 .truncate()
485510 .child(subtitle),
@@ -511,7 +536,7 @@ fn small_button(
511536 .flex()
512537 .items_center()
513538 .rounded(px(6.))
514- .text_size(px(13.))
539+ .text_size(text(13.))
515540 .text_color(color)
516541 }
517542
@@ -554,6 +579,35 @@ pub(super) fn row(label: &'static str, control: impl IntoElement) -> Div {
554579 .child(control)
555580 }
556581
582+pub(super) fn segment_track(palette: Palette) -> Div {
583+ div()
584+ .h(px(30.))
585+ .p(px(3.))
586+ .flex()
587+ .gap(px(2.))
588+ .rounded(px(8.))
589+ .border_1()
590+ .border_color(palette.border)
591+ .bg(palette.window)
592+}
593+
594+pub(super) fn segment<E: Styled>(item: E, active: bool, palette: Palette) -> E {
595+ let (background, border, text) = if active {
596+ (palette.field, palette.border, palette.text)
597+ } else {
598+ (transparent_black(), transparent_black(), palette.muted)
599+ };
600+
601+ item.flex()
602+ .items_center()
603+ .justify_center()
604+ .rounded(px(5.))
605+ .border_1()
606+ .border_color(border)
607+ .bg(background)
608+ .text_color(text)
609+}
610+
557611 pub(super) fn segmented<T: Copy + PartialEq + 'static, const N: usize>(
558612 options: [(T, &'static str); N],
559613 selected: T,
@@ -561,28 +615,17 @@ pub(super) fn segmented<T: Copy + PartialEq + 'static, const N: usize>(
561615 palette: Palette,
562616 select: fn(&mut Yumush, T, &mut Context<Yumush>),
563617 ) -> impl IntoElement {
564- div()
565- .h(px(28.))
566- .p(px(2.))
567- .flex()
568- .gap(px(2.))
569- .rounded(px(6.))
570- .border_1()
571- .border_color(palette.border)
572- .bg(palette.field)
573- .children(options.map(|(choice, label)| {
574- let entity = entity.clone();
575- let active = choice == selected;
618+ segment_track(palette).children(options.map(|(choice, label)| {
619+ let entity = entity.clone();
576620
621+ segment(
577622 clickable(label, palette, move |_, cx| {
578623 entity.update(cx, |yumush, cx| select(yumush, choice, cx));
579- })
580- .px(px(10.))
581- .flex()
582- .items_center()
583- .rounded(px(4.))
584- .text_color(if active { palette.text } else { palette.muted })
585- .when(active, |this| this.bg(palette.hover))
586- .child(label)
587- }))
624+ }),
625+ choice == selected,
626+ palette,
627+ )
628+ .px(px(10.))
629+ .child(label)
630+ }))
588631 }
crates/client/src/gui/sidebar.rsmodified+61 -40
@@ -1,3 +1,4 @@
1+use super::text;
12 use common::{
23 model::{CommunityKind, Invitation, User},
34 permission,
@@ -23,6 +24,7 @@ use super::{
2324 clickable, community_icon, community_name, entity_action, hoverable, hoverable_with,
2425 input_dialog,
2526 profile::profile_popover,
27+ settings_page::{segment, segment_track},
2628 social::Relation,
2729 };
2830
@@ -93,35 +95,23 @@ impl Yumush {
9395 ),
9496 ];
9597
96- div()
98+ segment_track(palette)
9799 .flex_1()
98- .h(px(28.))
99- .p(px(2.))
100- .flex()
101- .gap(px(2.))
102- .rounded(px(6.))
103- .border_1()
104- .border_color(palette.border)
105- .bg(palette.field)
106100 .children(tabs.map(|(tab, label, alert)| {
107- let active = self.chat.tab == tab;
108-
109- let item = clickable(
110- label,
101+ let item = segment(
102+ clickable(
103+ label,
104+ palette,
105+ entity_action(entity, move |yumush, window, cx| {
106+ yumush.set_sidebar_tab(tab, window, cx)
107+ }),
108+ ),
109+ self.chat.tab == tab,
111110 palette,
112- entity_action(entity, move |yumush, window, cx| {
113- yumush.set_sidebar_tab(tab, window, cx)
114- }),
115111 )
116112 .flex_1()
117- .flex()
118- .items_center()
119- .justify_center()
120113 .gap(px(6.))
121- .rounded(px(4.))
122- .text_size(px(12.))
123- .text_color(if active { palette.text } else { palette.muted })
124- .when(active, |this| this.bg(palette.hover))
114+ .text_size(text(12.))
125115 .child(label)
126116 .children(alert.then(|| dot(palette)));
127117
@@ -204,7 +194,7 @@ impl Yumush {
204194 palette,
205195 community,
206196 px(16.),
207- px(10.),
197+ text(10.),
208198 &self.chat.avatars,
209199 ),
210200 community.name.clone(),
@@ -264,7 +254,7 @@ impl Yumush {
264254 entry(
265255 themed,
266256 active,
267- community_icon(palette, community, px(20.), px(10.), &self.chat.avatars),
257+ community_icon(palette, community, px(20.), text(10.), &self.chat.avatars),
268258 community_name(community).to_string(),
269259 alert.then(|| dot(palette).into_any_element()),
270260 ),
@@ -297,7 +287,7 @@ impl Yumush {
297287 entry(
298288 palette,
299289 false,
300- avatar(palette, user, px(20.), px(10.), &self.chat.avatars),
290+ avatar(palette, user, px(20.), text(10.), &self.chat.avatars),
301291 user.username.clone(),
302292 Vec::new(),
303293 ),
@@ -360,7 +350,7 @@ impl Yumush {
360350 entry(
361351 palette,
362352 false,
363- avatar(palette, user, px(20.), px(10.), &self.chat.avatars),
353+ avatar(palette, user, px(20.), text(10.), &self.chat.avatars),
364354 user.username.clone(),
365355 trailing,
366356 )
@@ -374,7 +364,7 @@ impl Yumush {
374364 entry(
375365 palette,
376366 false,
377- avatar(palette, user, px(20.), px(10.), &self.chat.avatars),
367+ avatar(palette, user, px(20.), text(10.), &self.chat.avatars),
378368 user.username.clone(),
379369 [
380370 icon_button(
@@ -406,7 +396,7 @@ impl Yumush {
406396 entry(
407397 palette,
408398 false,
409- avatar(palette, user, px(20.), px(10.), &self.chat.avatars),
399+ avatar(palette, user, px(20.), text(10.), &self.chat.avatars),
410400 user.username.clone(),
411401 [icon_button(
412402 format!("cancel_friend_{}", user.id),
@@ -432,7 +422,7 @@ impl Yumush {
432422 let decline_id = community.id.clone();
433423 let label = div().flex().flex_col().child(community.name.clone()).child(
434424 div()
435- .text_size(px(11.))
425+ .text_size(text(11.))
436426 .text_color(palette.muted)
437427 .child(format!("from {}", invitation.inviter.username)),
438428 );
@@ -440,7 +430,7 @@ impl Yumush {
440430 entry(
441431 palette,
442432 false,
443- community_icon(palette, community, px(16.), px(10.), &self.chat.avatars),
433+ community_icon(palette, community, px(16.), text(10.), &self.chat.avatars),
444434 label,
445435 [
446436 icon_button(
@@ -476,12 +466,10 @@ impl Yumush {
476466
477467 Some(
478468 div()
479- .h(px(32.))
480- .pl(px(8.))
481- .pr(px(4.))
469+ .h(px(36.))
482470 .flex()
483471 .items_center()
484- .gap(px(8.))
472+ .gap(px(4.))
485473 .child(
486474 profile_popover(
487475 "account_profile",
@@ -493,10 +481,32 @@ impl Yumush {
493481 div()
494482 .flex()
495483 .items_center()
484+ .h(px(36.))
496485 .gap(px(8.))
497- .px(px(4.))
486+ .px(px(6.))
498487 .rounded(px(6.))
499- .child(avatar(palette, user, px(20.), px(11.), &self.chat.avatars))
488+ .child(
489+ div()
490+ .relative()
491+ .child(avatar(
492+ palette,
493+ user,
494+ px(24.),
495+ text(12.),
496+ &self.chat.avatars,
497+ ))
498+ .child(
499+ div()
500+ .absolute()
501+ .right(px(-2.))
502+ .bottom(px(-2.))
503+ .size(px(10.))
504+ .rounded_full()
505+ .border_2()
506+ .border_color(palette.window)
507+ .bg(status),
508+ ),
509+ )
500510 .child(
501511 div()
502512 .flex_1()
@@ -510,7 +520,17 @@ impl Yumush {
510520 .flex_1()
511521 .min_w_0(),
512522 )
513- .child(div().size(px(6.)).rounded_full().bg(status))
523+ .children(self.is_staff().then(|| {
524+ icon_button(
525+ "admin_button".to_string(),
526+ palette,
527+ IconName::Shield,
528+ "Admin",
529+ entity_action(entity, |yumush, window, cx| {
530+ yumush.show_view(View::Admin, window, cx)
531+ }),
532+ )
533+ }))
514534 .children(self.voice_controls(entity, palette)),
515535 )
516536 }
@@ -641,7 +661,7 @@ fn group(title: &'static str, palette: Palette, rows: Vec<AnyElement>) -> Option
641661 .child(
642662 div()
643663 .px(px(8.))
644- .text_size(px(11.))
664+ .text_size(text(11.))
645665 .text_color(palette.muted)
646666 .child(title),
647667 )
@@ -683,7 +703,8 @@ fn icon_button(
683703 ) -> AnyElement {
684704 clickable(id, palette, on_click)
685705 .tip(tip)
686- .size(px(24.))
706+ .size(px(26.))
707+ .flex_shrink_0()
687708 .flex()
688709 .items_center()
689710 .justify_center()
crates/client/src/gui/snippet.rsmodified+4 -3
@@ -1,3 +1,4 @@
1+use super::text;
12 use common::model::{Message, Role, SnippetMessage, User};
23 use gpui_kit::{
34 Entity, FontWeight, IntoElement, ParentElement, Styled, div, prelude::FluentBuilder as _, px,
@@ -30,7 +31,7 @@ pub fn snippet_card(
3031 .bg(palette.panel)
3132 .child(
3233 div()
33- .text_size(px(12.))
34+ .text_size(text(12.))
3435 .text_color(palette.muted)
3536 .child(header),
3637 )
@@ -60,7 +61,7 @@ fn snippet_row(
6061 div()
6162 .flex()
6263 .gap(px(8.))
63- .child(avatar(palette, &user, px(20.), px(10.), &chat.avatars))
64+ .child(avatar(palette, &user, px(20.), text(10.), &chat.avatars))
6465 .child(
6566 div()
6667 .flex_1()
@@ -81,7 +82,7 @@ fn snippet_row(
8182 )
8283 .child(
8384 div()
84- .text_size(px(11.))
85+ .text_size(text(11.))
8586 .text_color(palette.muted)
8687 .child(id_time(&item.id, "%H:%M")),
8788 ),
crates/client/src/gui/social.rsmodified+4 -3
@@ -1,3 +1,4 @@
1+use super::text;
12 use std::{fmt::Display, future::Future};
23
34 use common::{
@@ -398,7 +399,7 @@ fn invite_result(
398399 InviteLookup::Idle => None,
399400 InviteLookup::Missing => Some(
400401 div()
401- .text_size(px(13.))
402+ .text_size(text(13.))
402403 .text_color(palette.muted)
403404 .child("No such user")
404405 .into_any_element(),
@@ -407,7 +408,7 @@ fn invite_result(
407408 user_row(user, yumush, palette)
408409 .child(
409410 div()
410- .text_size(px(13.))
411+ .text_size(text(13.))
411412 .text_color(palette.muted)
412413 .child("Member"),
413414 )
@@ -447,7 +448,7 @@ fn user_row(user: &common::model::User, yumush: &Yumush, palette: Palette) -> gp
447448 palette,
448449 user,
449450 px(32.),
450- px(14.),
451+ text(14.),
451452 &yumush.chat.avatars,
452453 ))
453454 .child(
crates/client/src/gui/voice_settings.rsmodified+17 -1
@@ -20,7 +20,7 @@ use super::{
2020 settings_page::{row, segmented},
2121 };
2222 use crate::{
23- settings::{Activation, SENSITIVITY_DB, VOLUME, VoiceSettings},
23+ settings::{Activation, Profile, SENSITIVITY_DB, VOLUME, VoiceSettings},
2424 voice::audio::{self, Device, Devices},
2525 };
2626
@@ -29,6 +29,7 @@ const MODES: [(Activation, &str); 2] = [
2929 (Activation::VoiceActivity, "Voice activity"),
3030 (Activation::PushToTalk, "Push to talk"),
3131 ];
32+const PROFILES: [(Profile, &str); 2] = [(Profile::Voice, "Voice"), (Profile::Music, "Music")];
3233
3334 #[derive(Clone, Copy, PartialEq, Eq)]
3435 pub(super) enum Side {
@@ -249,6 +250,16 @@ impl Yumush {
249250 Yumush::set_voice_mode,
250251 ),
251252 ),
253+ row(
254+ "Profile",
255+ segmented(
256+ PROFILES,
257+ voice.profile,
258+ entity,
259+ palette,
260+ Yumush::set_voice_profile,
261+ ),
262+ ),
252263 ];
253264
254265 if self.chat.voice_community().is_none() {
@@ -370,6 +381,11 @@ impl Yumush {
370381 self.commit_settings(cx);
371382 }
372383
384+ pub(super) fn set_voice_profile(&mut self, profile: Profile, cx: &mut Context<Self>) {
385+ self.settings.voice.profile = profile;
386+ self.commit_settings(cx);
387+ }
388+
373389 pub(super) fn capture_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
374390 window.focus(&self.focus, cx);
375391 self.voice.key = KeyCapture::Waiting;
crates/client/src/main.rsmodified+1 -1
@@ -28,7 +28,7 @@ fn main() {
2828 .with_assets(AllAssets)
2929 .run(move |cx: &mut App| {
3030 init(cx);
31- settings::apply(settings.theme, cx);
31+ settings::apply(settings.theme, settings.font_size, cx);
3232 gui::bind_keys(cx);
3333
3434 let window_bounds = Bounds::centered(None, size(px(1100.0), px(720.0)), cx);
crates/client/src/network.rsmodified+22 -1
@@ -9,7 +9,8 @@ use common::{
99 error::Error,
1010 event::Event,
1111 model::{
12- Attachment, Ban, Community, Friends, Invitation, LogEntry, Member, Message, Rank, User,
12+ Attachment, Ban, Community, Friends, Invitation, LogEntry, Member, Message, Rank, Role,
13+ User,
1314 },
1415 network::{
1516 DownloadStatus, RESPONSE_MAX_READ_LENGTH, StreamKind, receive_decoded,
@@ -177,6 +178,26 @@ impl NetworkHandle {
177178 }
178179 }
179180
181+ pub async fn users(&self) -> Result<Vec<User>, Error> {
182+ match self.request(Request::Users).await? {
183+ Response::Users(users) => Ok(users),
184+ _ => Err(Error::Server),
185+ }
186+ }
187+
188+ pub async fn set_role(&self, user_id: &str, role: Role) -> Result<User, Error> {
189+ match self
190+ .request(Request::SetRole {
191+ user_id: user_id.to_string(),
192+ role,
193+ })
194+ .await?
195+ {
196+ Response::User(user) => Ok(user),
197+ _ => Err(Error::Server),
198+ }
199+ }
200+
180201 pub async fn read_user(&self, user_id: &str) -> Result<User, Error> {
181202 match self
182203 .request(Request::ReadUser {
crates/client/src/settings.rsmodified+64 -2
@@ -2,8 +2,9 @@ use std::{fmt::Display, fs, ops::RangeInclusive, path::PathBuf};
22
33 use common::config::Config;
44 use gpui_kit::{
5- App, Global,
5+ App, Global, Pixels,
66 component::{Theme, ThemeMode},
7+ px,
78 };
89 use tracing::warn;
910
@@ -24,6 +25,44 @@ pub struct Look(pub ThemeChoice);
2425
2526 impl Global for Look {}
2627
28+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29+pub enum FontSize {
30+ Small,
31+ Medium,
32+ Large,
33+}
34+
35+pub struct Scale(pub FontSize);
36+
37+impl Global for Scale {}
38+
39+impl FontSize {
40+ fn name(self) -> &'static str {
41+ match self {
42+ FontSize::Small => "small",
43+ FontSize::Medium => "medium",
44+ FontSize::Large => "large",
45+ }
46+ }
47+
48+ fn parse(value: &str) -> Option<Self> {
49+ match value {
50+ "small" => Some(FontSize::Small),
51+ "medium" => Some(FontSize::Medium),
52+ "large" => Some(FontSize::Large),
53+ _ => None,
54+ }
55+ }
56+
57+ pub fn pixels(self) -> Pixels {
58+ match self {
59+ FontSize::Small => px(13.),
60+ FontSize::Medium => px(14.),
61+ FontSize::Large => px(16.),
62+ }
63+ }
64+}
65+
2766 impl ThemeChoice {
2867 fn name(self) -> &'static str {
2968 match self {
@@ -51,6 +90,12 @@ pub enum Activation {
5190 PushToTalk,
5291 }
5392
93+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94+pub enum Profile {
95+ Voice,
96+ Music,
97+}
98+
5499 #[derive(Debug, Clone, PartialEq)]
55100 pub struct VoiceSettings {
56101 pub sensitivity_db: f32,
@@ -58,6 +103,7 @@ pub struct VoiceSettings {
58103 pub output_volume: f32,
59104 pub choice: Choice,
60105 pub activation: Activation,
106+ pub profile: Profile,
61107 pub push_to_talk_key: String,
62108 }
63109
@@ -69,6 +115,7 @@ impl Default for VoiceSettings {
69115 output_volume: 100.0,
70116 choice: Choice::default(),
71117 activation: Activation::VoiceActivity,
118+ profile: Profile::Voice,
72119 push_to_talk_key: String::new(),
73120 }
74121 }
@@ -77,6 +124,7 @@ impl Default for VoiceSettings {
77124 #[derive(Debug, Clone, PartialEq)]
78125 pub struct Settings {
79126 pub theme: ThemeChoice,
127+ pub font_size: FontSize,
80128 pub voice: VoiceSettings,
81129 }
82130
@@ -118,6 +166,10 @@ pub fn load() -> Settings {
118166 Some("push_to_talk") => Activation::PushToTalk,
119167 _ => Activation::VoiceActivity,
120168 },
169+ profile: match text("voice.profile").as_deref() {
170+ Some("music") => Profile::Music,
171+ _ => Profile::Voice,
172+ },
121173 push_to_talk_key: text("voice.push_to_talk").unwrap_or_default(),
122174 };
123175
@@ -125,6 +177,9 @@ pub fn load() -> Settings {
125177 theme: text("theme")
126178 .and_then(|value| ThemeChoice::parse(&value))
127179 .unwrap_or(ThemeChoice::Dark),
180+ font_size: text("font_size")
181+ .and_then(|value| FontSize::parse(&value))
182+ .unwrap_or(FontSize::Medium),
128183 voice,
129184 }
130185 }
@@ -143,9 +198,14 @@ pub fn save(settings: &Settings) {
143198 Activation::VoiceActivity => "voice_activity",
144199 Activation::PushToTalk => "push_to_talk",
145200 };
201+ let profile = match voice.profile {
202+ Profile::Voice => "voice",
203+ Profile::Music => "music",
204+ };
146205 let key = voice.push_to_talk_key.as_str();
147206 let content = [
148207 line("theme", settings.theme.name()),
208+ line("font_size", settings.font_size.name()),
149209 line("voice.sensitivity", voice.sensitivity_db),
150210 line("voice.input_volume", voice.input_volume),
151211 line("voice.output_volume", voice.output_volume),
@@ -158,6 +218,7 @@ pub fn save(settings: &Settings) {
158218 voice.choice.output.as_deref().unwrap_or_default(),
159219 ),
160220 line("voice.activation", activation),
221+ line("voice.profile", profile),
161222 line("voice.push_to_talk", key),
162223 ]
163224 .concat();
@@ -172,8 +233,9 @@ pub fn save(settings: &Settings) {
172233 }
173234 }
174235
175-pub fn apply(choice: ThemeChoice, cx: &mut App) {
236+pub fn apply(choice: ThemeChoice, font_size: FontSize, cx: &mut App) {
176237 cx.set_global(Look(choice));
238+ cx.set_global(Scale(font_size));
177239 match choice {
178240 ThemeChoice::System => Theme::sync_system_appearance(None, cx),
179241 ThemeChoice::Light => Theme::change(ThemeMode::Light, None, cx),
crates/client/src/voice/audio/pipewire.rsmodified+18 -15
@@ -11,9 +11,7 @@ use pipewire as pw;
1111 use pw::{loop_::Timeout, properties::properties, spa, stream::StreamState, types::ObjectType};
1212 use spa::pod::Pod;
1313
14-use super::{
15- Choice, Device, Devices, Downmix, Worker, play, record, stereo_bytes, stereo_frame, supervise,
16-};
14+use super::{Choice, Device, Devices, Worker, play, record, stereo_bytes, supervise};
1715 use crate::voice::{Capture, Playback};
1816
1917 const STOP_CHECK: Duration = Duration::from_millis(100);
@@ -133,14 +131,18 @@ fn stream_properties(category: &str, target: Option<&str>) -> pw::properties::Pr
133131 props
134132 }
135133
136-fn format_values() -> Option<Vec<u8>> {
134+fn format_values(channels: u32) -> Option<Vec<u8>> {
137135 let mut info = spa::param::audio::AudioInfoRaw::new();
138136 info.set_format(spa::param::audio::AudioFormat::F32LE);
139137 info.set_rate(VOICE_SAMPLE_RATE);
140138 let mut position = [0; spa::sys::SPA_AUDIO_MAX_CHANNELS as usize];
141- position[0] = spa::sys::SPA_AUDIO_CHANNEL_FL;
142- position[1] = spa::sys::SPA_AUDIO_CHANNEL_FR;
143- info.set_channels(2);
139+ if channels == 1 {
140+ position[0] = spa::sys::SPA_AUDIO_CHANNEL_MONO;
141+ } else {
142+ position[0] = spa::sys::SPA_AUDIO_CHANNEL_FL;
143+ position[1] = spa::sys::SPA_AUDIO_CHANNEL_FR;
144+ }
145+ info.set_channels(channels);
144146 info.set_position(position);
145147
146148 let object = spa::pod::Object {
@@ -178,7 +180,8 @@ fn run(
178180 })
179181 .register();
180182
181- let values = format_values().ok_or("pipewire format")?;
183+ let capture_values = format_values(1).ok_or("pipewire format")?;
184+ let playback_values = format_values(2).ok_or("pipewire format")?;
182185 let flags = pw::stream::StreamFlags::AUTOCONNECT
183186 | pw::stream::StreamFlags::MAP_BUFFERS
184187 | pw::stream::StreamFlags::RT_PROCESS;
@@ -190,7 +193,6 @@ fn run(
190193 )?;
191194 let capture = capture.cloned();
192195 let connect_capture = capture.is_some();
193- let mut downmix = Downmix::default();
194196 let _capture_listener = capture_stream
195197 .add_local_listener_with_user_data(())
196198 .state_changed(state_watch(&failed))
@@ -209,16 +211,17 @@ fn run(
209211 let Some(capture) = &capture else {
210212 return;
211213 };
212- let frames = bytes
213- .as_chunks::<BYTES_PER_FRAME>()
214+ let samples = bytes
215+ .as_chunks::<4>()
214216 .0
215217 .iter()
216- .map(stereo_frame);
217- record(capture, downmix.mix(frames));
218+ .copied()
219+ .map(f32::from_le_bytes);
220+ record(capture, samples);
218221 })
219222 .register()?;
220223 if connect_capture {
221- let mut capture_params = [Pod::from_bytes(&values).ok_or("pipewire format")?];
224+ let mut capture_params = [Pod::from_bytes(&capture_values).ok_or("pipewire format")?];
222225 capture_stream.connect(
223226 spa::utils::Direction::Input,
224227 None,
@@ -262,7 +265,7 @@ fn run(
262265 *chunk.size_mut() = (frames * BYTES_PER_FRAME) as u32;
263266 })
264267 .register()?;
265- let mut playback_params = [Pod::from_bytes(&values).ok_or("pipewire format")?];
268+ let mut playback_params = [Pod::from_bytes(&playback_values).ok_or("pipewire format")?];
266269 playback_stream.connect(
267270 spa::utils::Direction::Output,
268271 None,
crates/client/src/voice/engine.rsmodified+117 -23
@@ -4,27 +4,61 @@ use std::{
44 };
55
66 use common::{
7- constant::{VOICE_BITRATE, VOICE_FRAME_SAMPLES, VOICE_MAX_PAYLOAD, VOICE_SAMPLE_RATE},
7+ constant::{
8+ MUSIC_BITRATE, VOICE_BITRATE, VOICE_FRAME_SAMPLES, VOICE_MAX_PAYLOAD, VOICE_SAMPLE_RATE,
9+ },
810 voice::{decode_relay, encode_packet},
911 };
10-use ec_opus::{Application, Decoder, Encoder};
12+use ec_opus::{Application, Bandwidth, Decoder, Encoder};
13+
14+use crate::settings::Profile;
1115
1216 pub const SILENT_DB: f32 = -100.0;
1317 const JITTER_CAPACITY: usize = 10;
14-const START_FRAMES: usize = 2;
18+const FRAME_MS: f32 = 20.0;
19+const MIN_FRAMES: usize = 1;
20+const MAX_FRAMES: usize = 6;
21+const DRIFT_MARGIN: usize = 2;
22+const QUIET: f32 = 0.01;
1523 const SPEAKING_WINDOW: Duration = Duration::from_millis(300);
1624 const RESTART_AFTER: Duration = Duration::from_secs(1);
1725 const MAX_DECODE_SAMPLES: usize = 5760;
1826 const HANGOVER_FRAMES: u32 = 15;
27+const FADE_SAMPLES: usize = 240;
28+const EXPECTED_LOSS_PERC: u8 = 10;
1929
2030 fn rms(samples: &[f32]) -> f32 {
2131 (samples.iter().map(|sample| sample * sample).sum::<f32>() / samples.len() as f32).sqrt()
2232 }
2333
34+fn soft_clip(sample: f32) -> f32 {
35+ const KNEE: f32 = 0.8;
36+ let magnitude = sample.abs();
37+ if magnitude <= KNEE {
38+ return sample;
39+ }
40+ let over = (magnitude - KNEE) / (1.0 - KNEE);
41+ sample.signum() * (KNEE + (1.0 - KNEE) * over.tanh())
42+}
43+
2444 fn db(amplitude: f32) -> f32 {
2545 (20.0 * amplitude.log10()).max(SILENT_DB)
2646 }
2747
48+fn encoder(profile: Profile) -> Encoder {
49+ let (application, bitrate) = match profile {
50+ Profile::Voice => (Application::Voip, VOICE_BITRATE),
51+ Profile::Music => (Application::Audio, MUSIC_BITRATE),
52+ };
53+ let mut encoder = Encoder::new(VOICE_SAMPLE_RATE, 1, application).expect("opus encoder");
54+ encoder.set_bitrate(bitrate as u32);
55+ encoder.set_bandwidth(Some(Bandwidth::Full));
56+ encoder.set_analysis(true);
57+ encoder.set_inband_fec(true);
58+ encoder.set_packet_loss_perc(EXPECTED_LOSS_PERC);
59+ encoder
60+}
61+
2862 struct Speaker {
2963 decoder: Decoder,
3064 scratch: Vec<f32>,
@@ -33,6 +67,10 @@ struct Speaker {
3367 pending: VecDeque<f32>,
3468 last_heard: Instant,
3569 started: bool,
70+ first_arrival: Instant,
71+ first_sequence: u32,
72+ previous_transit: Option<f32>,
73+ jitter_ms: f32,
3674 }
3775
3876 impl Speaker {
@@ -45,23 +83,51 @@ impl Speaker {
4583 pending: VecDeque::new(),
4684 last_heard: now,
4785 started: false,
86+ first_arrival: now,
87+ first_sequence: sequence,
88+ previous_transit: None,
89+ jitter_ms: 0.0,
4890 }
4991 }
5092
51- fn next_frame(&mut self) -> Option<Vec<f32>> {
52- if self.jitter.is_empty() {
53- return None;
54- }
55- let decoded = match self.jitter.remove(&self.next) {
56- Some(payload) => self.decoder.decode_float(&payload, &mut self.scratch),
57- None => self.decoder.conceal(VOICE_FRAME_SAMPLES, &mut self.scratch),
93+ fn target(&self) -> usize {
94+ ((self.jitter_ms * 2.0 / FRAME_MS).ceil() as usize + 1).clamp(MIN_FRAMES, MAX_FRAMES)
95+ }
96+
97+ fn decode_next(&mut self) -> (Vec<f32>, bool) {
98+ let (decoded, real) = match (
99+ self.jitter.remove(&self.next),
100+ self.jitter.get(&(self.next + 1)),
101+ ) {
102+ (Some(payload), _) => (self.decoder.decode_float(&payload, &mut self.scratch), true),
103+ (None, Some(following)) => (
104+ self.decoder
105+ .decode_fec(following, VOICE_FRAME_SAMPLES, &mut self.scratch),
106+ false,
107+ ),
108+ (None, None) => (
109+ self.decoder.conceal(VOICE_FRAME_SAMPLES, &mut self.scratch),
110+ false,
111+ ),
58112 };
59113 self.next += 1;
60114
61- Some(match decoded {
115+ let samples = match decoded {
62116 Ok(samples) => self.scratch[..samples].to_vec(),
63117 Err(_) => vec![0.0; VOICE_FRAME_SAMPLES],
64- })
118+ };
119+ (samples, real)
120+ }
121+
122+ fn next_frame(&mut self) -> Option<Vec<f32>> {
123+ if self.jitter.is_empty() {
124+ return None;
125+ }
126+ let (mut frame, real) = self.decode_next();
127+ if real && self.jitter.len() > self.target() + DRIFT_MARGIN && rms(&frame) < QUIET {
128+ (frame, _) = self.decode_next();
129+ }
130+ Some(frame)
65131 }
66132
67133 fn mix(&mut self, out: &mut [f32]) {
@@ -69,6 +135,7 @@ impl Speaker {
69135 if self.pending.is_empty() {
70136 let Some(frame) = self.next_frame() else {
71137 self.started = false;
138+ self.previous_transit = None;
72139 return;
73140 };
74141 self.pending.extend(frame);
@@ -80,6 +147,7 @@ impl Speaker {
80147
81148 pub struct Engine {
82149 encoder: Encoder,
150+ profile: Profile,
83151 capture_buffer: Vec<f32>,
84152 sequence: u32,
85153 muted: bool,
@@ -90,6 +158,7 @@ pub struct Engine {
90158 push_to_talk: bool,
91159 talking: bool,
92160 hangover: u32,
161+ sending: bool,
93162 level_db: f32,
94163 speakers: HashMap<String, Speaker>,
95164 }
@@ -102,12 +171,9 @@ impl Default for Engine {
102171
103172 impl Engine {
104173 pub fn new() -> Self {
105- let mut encoder =
106- Encoder::new(VOICE_SAMPLE_RATE, 1, Application::Voip).expect("opus encoder");
107- encoder.set_bitrate(VOICE_BITRATE as u32);
108-
109174 Self {
110- encoder,
175+ encoder: encoder(Profile::Voice),
176+ profile: Profile::Voice,
111177 capture_buffer: Vec::new(),
112178 sequence: 0,
113179 muted: false,
@@ -118,6 +184,7 @@ impl Engine {
118184 push_to_talk: false,
119185 talking: false,
120186 hangover: 0,
187+ sending: false,
121188 level_db: SILENT_DB,
122189 speakers: HashMap::new(),
123190 }
@@ -129,7 +196,7 @@ impl Engine {
129196 let full = self.capture_buffer.len() / VOICE_FRAME_SAMPLES * VOICE_FRAME_SAMPLES;
130197 let mut frames: Vec<f32> = self.capture_buffer.drain(..full).collect();
131198 for sample in &mut frames {
132- *sample *= self.input_gain;
199+ *sample = soft_clip(*sample * self.input_gain);
133200 }
134201
135202 let mut packets = Vec::new();
@@ -139,20 +206,35 @@ impl Engine {
139206 if loud >= self.gate {
140207 self.hangover = HANGOVER_FRAMES;
141208 }
142- let speaking = if self.push_to_talk {
209+ let talking = if self.push_to_talk {
143210 self.talking
144211 } else {
145212 self.hangover > 0
146213 };
147214 self.hangover = self.hangover.saturating_sub(1);
148- if self.muted || self.deafened || !speaking {
215+ let speaking = talking && !self.muted && !self.deafened;
216+ let was_sending = self.sending;
217+ self.sending = speaking;
218+ if !speaking && !was_sending {
149219 continue;
150220 }
151221
222+ let mut samples = *frame;
223+ if speaking && !was_sending {
224+ for (index, sample) in samples[..FADE_SAMPLES].iter_mut().enumerate() {
225+ *sample *= index as f32 / FADE_SAMPLES as f32;
226+ }
227+ }
228+ if !speaking {
229+ for (index, sample) in samples.iter_mut().enumerate() {
230+ *sample *= 1.0 - index as f32 / VOICE_FRAME_SAMPLES as f32;
231+ }
232+ }
233+
152234 let mut payload = [0u8; VOICE_MAX_PAYLOAD];
153235 let Ok(length) = self
154236 .encoder
155- .encode_float(frame, VOICE_FRAME_SAMPLES, &mut payload)
237+ .encode_float(&samples, VOICE_FRAME_SAMPLES, &mut payload)
156238 else {
157239 continue;
158240 };
@@ -187,11 +269,18 @@ impl Engine {
187269 return;
188270 }
189271
272+ let transit_ms = now.duration_since(speaker.first_arrival).as_secs_f32() * 1000.0
273+ - sequence.wrapping_sub(speaker.first_sequence) as f32 * FRAME_MS;
274+ if let Some(previous) = speaker.previous_transit {
275+ speaker.jitter_ms += ((transit_ms - previous).abs() - speaker.jitter_ms) / 16.0;
276+ }
277+ speaker.previous_transit = Some(transit_ms);
278+
190279 speaker.jitter.insert(sequence, payload.to_vec());
191280 while speaker.jitter.len() > JITTER_CAPACITY {
192281 speaker.jitter.pop_first();
193282 }
194- if speaker.jitter.len() >= START_FRAMES {
283+ if speaker.jitter.len() >= speaker.target() {
195284 speaker.started = true;
196285 }
197286 }
@@ -209,7 +298,7 @@ impl Engine {
209298 }
210299
211300 for sample in out.iter_mut() {
212- *sample = (*sample * self.output_gain).clamp(-1.0, 1.0);
301+ *sample = soft_clip(*sample * self.output_gain);
213302 }
214303 }
215304
@@ -241,11 +330,16 @@ impl Engine {
241330 input_volume: f32,
242331 output_volume: f32,
243332 push_to_talk: bool,
333+ profile: Profile,
244334 ) {
245335 self.gate = 10f32.powf(sensitivity_db / 20.0);
246336 self.input_gain = input_volume / 100.0;
247337 self.output_gain = output_volume / 100.0;
248338 self.push_to_talk = push_to_talk;
339+ if profile != self.profile {
340+ self.encoder = encoder(profile);
341+ self.profile = profile;
342+ }
249343 }
250344
251345 pub fn set_talking(&mut self, talking: bool) {
crates/client/src/voice/mod.rsmodified+1 -0
@@ -173,6 +173,7 @@ impl Voice {
173173 settings.input_volume,
174174 settings.output_volume,
175175 settings.activation == Activation::PushToTalk,
176+ settings.profile,
176177 );
177178 }
178179 }
crates/common/src/constant.rsmodified+2 -1
@@ -12,7 +12,8 @@ pub const MAXIMUM_AVATAR_BYTES: usize = 32 * 1024;
1212 pub const MAXIMUM_STATUS_LENGTH: usize = 64;
1313 pub const VOICE_SAMPLE_RATE: u32 = 48_000;
1414 pub const VOICE_FRAME_SAMPLES: usize = 960;
15-pub const VOICE_BITRATE: i32 = 32_000;
15+pub const VOICE_BITRATE: i32 = 48_000;
16+pub const MUSIC_BITRATE: i32 = 96_000;
1617 pub const VOICE_MAX_PAYLOAD: usize = 1000;
1718 pub const MAXIMUM_ATTACHMENT_BYTES: u64 = 25 * 1024 * 1024;
1819 pub const MAXIMUM_ATTACHMENTS_PER_MESSAGE: usize = 10;
crates/common/src/permission.rsmodified+4 -0
@@ -65,6 +65,10 @@ pub fn can_leave(actor: Option<Rank>) -> bool {
6565 actor.is_some() && actor != Some(Rank::Owner)
6666 }
6767
68+pub fn can_set_role(actor: Role, is_self: bool) -> bool {
69+ actor == Role::Staff && !is_self
70+}
71+
6872 pub fn can_delete_user(actor: Role, is_self: bool, target: Role) -> bool {
6973 is_self || (actor == Role::Staff && target != Role::Staff)
7074 }
crates/common/src/request.rsmodified+6 -1
@@ -1,6 +1,6 @@
11 use bitcode::{Decode, Encode};
22
3-use crate::model::Rank;
3+use crate::model::{Rank, Role};
44
55 #[derive(Debug, Clone, Encode, Decode)]
66 pub struct UploadHeader {
@@ -154,4 +154,9 @@ pub enum Request {
154154 Logs {
155155 community_id: String,
156156 },
157+ Users,
158+ SetRole {
159+ user_id: String,
160+ role: Role,
161+ },
157162 }
crates/common/src/response.rsmodified+1 -0
@@ -23,4 +23,5 @@ pub enum Response {
2323 Done,
2424 Error(Error),
2525 Logs(Vec<LogEntry>),
26+ Users(Vec<User>),
2627 }
crates/server/src/request.rsmodified+71 -48
@@ -3,7 +3,7 @@ use std::{collections::BTreeSet, path::Path, sync::Mutex};
33 use common::{
44 error::Error as CommonError,
55 event::Event,
6- model::{CommunityKind, LogAction, Member, Rank, User},
6+ model::{CommunityKind, LogAction, Member, Rank, Role, User},
77 permission,
88 request::Request,
99 response::Response,
@@ -70,27 +70,27 @@ async fn dispatch(
7070 sign_in(state, user, token, broadcasts)
7171 }
7272 Request::Detach => {
73- authenticated(state)?;
73+ authenticated(state, &conn).await?;
7474 let broadcasts = leave_connection_voice(voice, connection, &conn).await?;
7575 set_state(state, State::Anonymous);
7676 (Response::Done, broadcasts)
7777 }
7878 Request::Logout => {
79- let (_, token) = authenticated(state)?;
79+ let (_, token) = authenticated(state, &conn).await?;
8080 authentication::logout(&token, &conn).await?;
8181 let broadcasts = leave_connection_voice(voice, connection, &conn).await?;
8282 set_state(state, State::Anonymous);
8383 (Response::Done, broadcasts)
8484 }
8585 Request::ReadUser { user_id } => {
86- authenticated(state)?;
86+ authenticated(state, &conn).await?;
8787 (
8888 Response::User(user::read(&user_id, &conn).await?),
8989 Vec::new(),
9090 )
9191 }
9292 Request::UpdateUser { username } => {
93- let (me, token) = authenticated(state)?;
93+ let (me, token) = authenticated(state, &conn).await?;
9494 let user = user::update(&me.id, &username, &conn).await?;
9595 set_state(
9696 state,
@@ -102,8 +102,20 @@ async fn dispatch(
102102 let broadcasts = user_updated(&user, &conn).await?;
103103 (Response::User(user), broadcasts)
104104 }
105+ Request::Users => {
106+ let (me, _) = authenticated(state, &conn).await?;
107+ ensure(me.role == Role::Staff)?;
108+ (Response::Users(user::all(&conn).await?), Vec::new())
109+ }
110+ Request::SetRole { user_id, role } => {
111+ let (me, _) = authenticated(state, &conn).await?;
112+ ensure(permission::can_set_role(me.role, me.id == user_id))?;
113+ let user = user::set_role_by_id(&user_id, role, &conn).await?;
114+ let broadcasts = user_updated(&user, &conn).await?;
115+ (Response::User(user), broadcasts)
116+ }
105117 Request::UpdateStatus { status } => {
106- let (me, token) = authenticated(state)?;
118+ let (me, token) = authenticated(state, &conn).await?;
107119 let user = user::update_status(&me.id, &status, &conn).await?;
108120 set_state(
109121 state,
@@ -116,7 +128,7 @@ async fn dispatch(
116128 (Response::User(user), broadcasts)
117129 }
118130 Request::UpdateAvatar { image } => {
119- let (me, token) = authenticated(state)?;
131+ let (me, token) = authenticated(state, &conn).await?;
120132 let user = user::set_avatar(&me.id, &image, &mut conn).await?;
121133 set_state(
122134 state,
@@ -129,7 +141,7 @@ async fn dispatch(
129141 (Response::User(user), broadcasts)
130142 }
131143 Request::RemoveAvatar => {
132- let (me, token) = authenticated(state)?;
144+ let (me, token) = authenticated(state, &conn).await?;
133145 let user = user::remove_avatar(&me.id, &mut conn).await?;
134146 set_state(
135147 state,
@@ -142,14 +154,14 @@ async fn dispatch(
142154 (Response::User(user), broadcasts)
143155 }
144156 Request::ReadAvatar { avatar_id } => {
145- authenticated(state)?;
157+ authenticated(state, &conn).await?;
146158 (
147159 Response::Avatar(user::avatar(&avatar_id, &conn).await?),
148160 Vec::new(),
149161 )
150162 }
151163 Request::DeleteUser { user_id } => {
152- let (me, _) = authenticated(state)?;
164+ let (me, _) = authenticated(state, &conn).await?;
153165 let target = user::read(&user_id, &conn).await?;
154166 ensure(permission::can_delete_user(
155167 me.role,
@@ -184,7 +196,7 @@ async fn dispatch(
184196 (Response::User(deleted), broadcasts)
185197 }
186198 Request::CreateCommunity { name } => {
187- let (me, _) = authenticated(state)?;
199+ let (me, _) = authenticated(state, &conn).await?;
188200 let tx = conn.transaction().await?;
189201 let community = community::create(&name, &tx).await?;
190202 user_community::join(&me.id, &community.id, Rank::Owner, &tx).await?;
@@ -193,14 +205,14 @@ async fn dispatch(
193205 (Response::Community(community), Vec::new())
194206 }
195207 Request::ReadCommunity { community_id } => {
196- let (me, _) = authenticated(state)?;
208+ let (me, _) = authenticated(state, &conn).await?;
197209 (
198210 Response::Community(community::read(&community_id, &me.id, &conn).await?),
199211 Vec::new(),
200212 )
201213 }
202214 Request::UpdateCommunity { community_id, name } => {
203- let (me, _) = authenticated(state)?;
215+ let (me, _) = authenticated(state, &conn).await?;
204216 ensure(!community::is_direct(&community_id, &conn).await?)?;
205217 ensure(permission::can_rename_community(
206218 actor_rank(&me, &community_id, &conn).await?,
@@ -218,7 +230,7 @@ async fn dispatch(
218230 community_id,
219231 image,
220232 } => {
221- let (me, _) = authenticated(state)?;
233+ let (me, _) = authenticated(state, &conn).await?;
222234 ensure(!community::is_direct(&community_id, &conn).await?)?;
223235 ensure(permission::can_rename_community(
224236 actor_rank(&me, &community_id, &conn).await?,
@@ -236,7 +248,7 @@ async fn dispatch(
236248 (Response::Community(updated), broadcast(event, &members))
237249 }
238250 Request::DeleteCommunity { community_id } => {
239- let (me, _) = authenticated(state)?;
251+ let (me, _) = authenticated(state, &conn).await?;
240252 ensure(!community::is_direct(&community_id, &conn).await?)?;
241253 ensure(permission::can_delete_community(
242254 actor_rank(&me, &community_id, &conn).await?,
@@ -252,7 +264,7 @@ async fn dispatch(
252264 (Response::Community(deleted), broadcast(event, &members))
253265 }
254266 Request::LeaveCommunity { community_id } => {
255- let (me, _) = authenticated(state)?;
267+ let (me, _) = authenticated(state, &conn).await?;
256268 ensure(!community::is_direct(&community_id, &conn).await?)?;
257269 ensure(permission::can_leave(
258270 actor_rank(&me, &community_id, &conn).await?,
@@ -274,14 +286,14 @@ async fn dispatch(
274286 (Response::Done, broadcasts)
275287 }
276288 Request::Communities => {
277- let (me, _) = authenticated(state)?;
289+ let (me, _) = authenticated(state, &conn).await?;
278290 (
279291 Response::Communities(community::communities_of(&me.id, &conn).await?),
280292 Vec::new(),
281293 )
282294 }
283295 Request::Members { community_id } => {
284- let (me, _) = authenticated(state)?;
296+ let (me, _) = authenticated(state, &conn).await?;
285297 ensure(permission::can_read(
286298 actor_rank(&me, &community_id, &conn).await?,
287299 ))?;
@@ -295,7 +307,7 @@ async fn dispatch(
295307 user_id,
296308 reason,
297309 } => {
298- let (me, _) = authenticated(state)?;
310+ let (me, _) = authenticated(state, &conn).await?;
299311 remove_member(
300312 &me,
301313 Removal {
@@ -314,7 +326,7 @@ async fn dispatch(
314326 user_id,
315327 reason,
316328 } => {
317- let (me, _) = authenticated(state)?;
329+ let (me, _) = authenticated(state, &conn).await?;
318330 remove_member(
319331 &me,
320332 Removal {
@@ -332,7 +344,7 @@ async fn dispatch(
332344 community_id,
333345 user_id,
334346 } => {
335- let (me, _) = authenticated(state)?;
347+ let (me, _) = authenticated(state, &conn).await?;
336348 ensure(permission::can_unban(
337349 actor_rank(&me, &community_id, &conn).await?,
338350 ))?;
@@ -348,7 +360,7 @@ async fn dispatch(
348360 (Response::Done, Vec::new())
349361 }
350362 Request::Bans { community_id } => {
351- let (me, _) = authenticated(state)?;
363+ let (me, _) = authenticated(state, &conn).await?;
352364 ensure(permission::can_unban(
353365 actor_rank(&me, &community_id, &conn).await?,
354366 ))?;
@@ -362,7 +374,7 @@ async fn dispatch(
362374 user_id,
363375 rank,
364376 } => {
365- let (me, _) = authenticated(state)?;
377+ let (me, _) = authenticated(state, &conn).await?;
366378 ensure(!community::is_direct(&community_id, &conn).await?)?;
367379 let target = user::read(&user_id, &conn).await?;
368380 ensure(permission::can_set_rank(
@@ -393,7 +405,7 @@ async fn dispatch(
393405 attachments,
394406 reply_to,
395407 } => {
396- let (me, _) = authenticated(state)?;
408+ let (me, _) = authenticated(state, &conn).await?;
397409 ensure(permission::can_post(
398410 actor_rank(&me, &community_id, &conn).await?,
399411 ))?;
@@ -417,7 +429,7 @@ async fn dispatch(
417429 community_id,
418430 snippet,
419431 } => {
420- let (me, _) = authenticated(state)?;
432+ let (me, _) = authenticated(state, &conn).await?;
421433 validate_forward(message_ids.len())?;
422434 ensure(permission::can_post(
423435 actor_rank(&me, &community_id, &conn).await?,
@@ -443,7 +455,7 @@ async fn dispatch(
443455 (Response::Messages(created), broadcasts)
444456 }
445457 Request::UpdateMessage { message_id, body } => {
446- let (me, _) = authenticated(state)?;
458+ let (me, _) = authenticated(state, &conn).await?;
447459 let existing = message::read(&message_id, &conn).await?;
448460 ensure(permission::can_edit_message(existing.user_id == me.id))?;
449461 let updated = message::update(&message_id, &body, &conn).await?;
@@ -452,7 +464,7 @@ async fn dispatch(
452464 (Response::Message(updated), broadcast(event, &members))
453465 }
454466 Request::DeleteMessage { message_id } => {
455- let (me, _) = authenticated(state)?;
467+ let (me, _) = authenticated(state, &conn).await?;
456468 let existing = message::read(&message_id, &conn).await?;
457469 let author = user::read(&existing.user_id, &conn).await?;
458470 ensure(permission::can_delete_message(
@@ -479,7 +491,7 @@ async fn dispatch(
479491 community_id,
480492 before,
481493 } => {
482- let (me, _) = authenticated(state)?;
494+ let (me, _) = authenticated(state, &conn).await?;
483495 ensure(permission::can_read(
484496 actor_rank(&me, &community_id, &conn).await?,
485497 ))?;
@@ -487,7 +499,7 @@ async fn dispatch(
487499 (Response::Messages(messages), Vec::new())
488500 }
489501 Request::JoinVoice { community_id } => {
490- let (me, _) = authenticated(state)?;
502+ let (me, _) = authenticated(state, &conn).await?;
491503 ensure(permission::can_join_voice(
492504 actor_rank(&me, &community_id, &conn).await?,
493505 ))?;
@@ -516,14 +528,14 @@ async fn dispatch(
516528 )
517529 }
518530 Request::LeaveVoice => {
519- authenticated(state)?;
531+ authenticated(state, &conn).await?;
520532 (
521533 Response::Done,
522534 leave_connection_voice(voice, connection, &conn).await?,
523535 )
524536 }
525537 Request::VoiceParticipants { community_id } => {
526- let (me, _) = authenticated(state)?;
538+ let (me, _) = authenticated(state, &conn).await?;
527539 ensure(permission::can_read(
528540 actor_rank(&me, &community_id, &conn).await?,
529541 ))?;
@@ -533,14 +545,15 @@ async fn dispatch(
533545 )
534546 }
535547 Request::FindUser { username } => {
536- authenticated(state)?;
548+ let (me, _) = authenticated(state, &conn).await?;
537549 let found = user::by_username(&username, &conn)
538550 .await?
551+ .filter(|found| found.id != me.id)
539552 .ok_or(CommonError::NotFound)?;
540553 (Response::User(found), Vec::new())
541554 }
542555 Request::OpenDirect { user_id } => {
543- let (me, _) = authenticated(state)?;
556+ let (me, _) = authenticated(state, &conn).await?;
544557 let (community, created) = direct::open(&me.id, &user_id, &mut conn).await?;
545558 let broadcasts = if created {
546559 let peer_view = community::read(&community.id, &user_id, &conn).await?;
@@ -554,26 +567,26 @@ async fn dispatch(
554567 (Response::Community(community), broadcasts)
555568 }
556569 Request::Friends => {
557- let (me, _) = authenticated(state)?;
570+ let (me, _) = authenticated(state, &conn).await?;
558571 (
559572 Response::Friends(friend::state(&me.id, &conn).await?),
560573 Vec::new(),
561574 )
562575 }
563576 Request::AddFriend { user_id } => {
564- let (me, _) = authenticated(state)?;
577+ let (me, _) = authenticated(state, &conn).await?;
565578 friend::add(&me.id, &user_id, &mut conn).await?;
566579 let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?;
567580 (Response::Done, broadcasts)
568581 }
569582 Request::AcceptFriend { user_id } => {
570- let (me, _) = authenticated(state)?;
583+ let (me, _) = authenticated(state, &conn).await?;
571584 friend::accept(&me.id, &user_id, &mut conn).await?;
572585 let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?;
573586 (Response::Done, broadcasts)
574587 }
575588 Request::RemoveFriend { user_id } => {
576- let (me, _) = authenticated(state)?;
589+ let (me, _) = authenticated(state, &conn).await?;
577590 friend::remove(&me.id, &user_id, &mut conn).await?;
578591 let broadcasts = friends_updated(&[me.id.as_str(), user_id.as_str()], &conn).await?;
579592 (Response::Done, broadcasts)
@@ -582,7 +595,7 @@ async fn dispatch(
582595 community_id,
583596 user_id,
584597 } => {
585- let (me, _) = authenticated(state)?;
598+ let (me, _) = authenticated(state, &conn).await?;
586599 ensure(!community::is_direct(&community_id, &conn).await?)?;
587600 ensure(permission::can_read(
588601 actor_rank(&me, &community_id, &conn).await?,
@@ -612,14 +625,14 @@ async fn dispatch(
612625 (Response::Done, vec![broadcast])
613626 }
614627 Request::Invitations => {
615- let (me, _) = authenticated(state)?;
628+ let (me, _) = authenticated(state, &conn).await?;
616629 (
617630 Response::Invitations(invitation::of(&me.id, &conn).await?),
618631 Vec::new(),
619632 )
620633 }
621634 Request::AcceptInvitation { community_id } => {
622- let (me, _) = authenticated(state)?;
635+ let (me, _) = authenticated(state, &conn).await?;
623636 let tx = conn.transaction().await?;
624637 invitation::take(&community_id, &me.id, &tx).await?;
625638 let banned = user_community::is_banned(&me.id, &community_id, &tx).await?;
@@ -641,7 +654,7 @@ async fn dispatch(
641654 (Response::Community(community), broadcasts)
642655 }
643656 Request::DeclineInvitation { community_id } => {
644- let (me, _) = authenticated(state)?;
657+ let (me, _) = authenticated(state, &conn).await?;
645658 invitation::take(&community_id, &me.id, &conn).await?;
646659 (
647660 Response::Done,
@@ -649,7 +662,7 @@ async fn dispatch(
649662 )
650663 }
651664 Request::Logs { community_id } => {
652- let (me, _) = authenticated(state)?;
665+ let (me, _) = authenticated(state, &conn).await?;
653666 ensure(permission::can_read_logs(
654667 actor_rank(&me, &community_id, &conn).await?,
655668 ))?;
@@ -725,7 +738,7 @@ async fn remove_member(
725738 }
726739
727740 async fn user_updated(user: &User, conn: &Connection) -> Result<Vec<Broadcast>, Error> {
728- let mut user_ids = BTreeSet::new();
741+ let mut user_ids = BTreeSet::from([user.id.clone()]);
729742 for community in community::communities_of(&user.id, conn).await? {
730743 for member in user_community::members(&community.id, conn).await? {
731744 user_ids.insert(member.user.id);
@@ -831,11 +844,21 @@ fn set_state(state: &Mutex<State>, new_state: State) {
831844 *state.lock().unwrap() = new_state;
832845 }
833846
834-fn authenticated(state: &Mutex<State>) -> Result<(User, String), Error> {
835- match state.lock().unwrap().clone() {
836- State::Anonymous => Err(CommonError::Unauthenticated.into()),
837- State::Authenticated { user, token } => Ok((user, token)),
838- }
847+async fn authenticated(state: &Mutex<State>, conn: &Connection) -> Result<(User, String), Error> {
848+ let (cached, token) = match state.lock().unwrap().clone() {
849+ State::Anonymous => return Err(CommonError::Unauthenticated.into()),
850+ State::Authenticated { user, token } => (user, token),
851+ };
852+ let user = user::read(&cached.id, conn).await?;
853+ set_state(
854+ state,
855+ State::Authenticated {
856+ user: user.clone(),
857+ token: token.clone(),
858+ },
859+ );
860+
861+ Ok((user, token))
839862 }
840863
841864 pub async fn actor_rank(
crates/server/src/user.rsmodified+37 -4
@@ -28,8 +28,14 @@ fn role_of(row: &Row) -> Result<Role, Error> {
2828 pub async fn create(username: &str, password_hash: &str, conn: &Connection) -> Result<User, Error> {
2929 let mut rows = conn
3030 .query(
31- "INSERT INTO user (id, username, password_hash) VALUES (?1, ?2, ?3) RETURNING id, username, role, status, avatar_id",
32- (new_id(), username, password_hash),
31+ "INSERT INTO user (id, username, password_hash, role) VALUES (?1, ?2, ?3, CASE WHEN EXISTS (SELECT 1 FROM user) THEN ?4 ELSE ?5 END) RETURNING id, username, role, status, avatar_id",
32+ (
33+ new_id(),
34+ username,
35+ password_hash,
36+ Role::User.as_str(),
37+ Role::Staff.as_str(),
38+ ),
3339 )
3440 .await?;
3541 let row = rows.next().await?.ok_or(CommonError::NotFound)?;
@@ -52,7 +58,7 @@ pub async fn read(user_id: &str, conn: &Connection) -> Result<User, Error> {
5258 pub async fn by_username(username: &str, conn: &Connection) -> Result<Option<User>, Error> {
5359 let mut rows = conn
5460 .query(
55- "SELECT id, username, role, status, avatar_id FROM user WHERE username = ?1",
61+ "SELECT id, username, role, status, avatar_id FROM user WHERE username = ?1 COLLATE NOCASE",
5662 (username,),
5763 )
5864 .await?;
@@ -194,6 +200,33 @@ pub async fn set_role(username: &str, role: Role, conn: &Connection) -> Result<U
194200 from_row(&row)
195201 }
196202
203+pub async fn set_role_by_id(user_id: &str, role: Role, conn: &Connection) -> Result<User, Error> {
204+ let mut rows = conn
205+ .query(
206+ "UPDATE user SET role = ?2 WHERE id = ?1 RETURNING id, username, role, status, avatar_id",
207+ (user_id, role.as_str()),
208+ )
209+ .await?;
210+ let row = rows.next().await?.ok_or(CommonError::NotFound)?;
211+
212+ from_row(&row)
213+}
214+
215+pub async fn all(conn: &Connection) -> Result<Vec<User>, Error> {
216+ let mut rows = conn
217+ .query(
218+ "SELECT id, username, role, status, avatar_id FROM user ORDER BY username COLLATE NOCASE",
219+ (),
220+ )
221+ .await?;
222+ let mut users = Vec::new();
223+ while let Some(row) = rows.next().await? {
224+ users.push(from_row(&row)?);
225+ }
226+
227+ Ok(users)
228+}
229+
197230 pub async fn delete(user_id: &str, conn: &Connection) -> Result<User, Error> {
198231 let mut rows = conn
199232 .query(
@@ -274,7 +307,7 @@ mod tests {
274307 let created_user = user::create("Tahinli", "hash", &conn).await.unwrap();
275308 let _other_user = user::create("Not Tahinli", "hash", &conn).await.unwrap();
276309
277- let searched_user = user::by_username("Tahinli", &conn).await.unwrap();
310+ let searched_user = user::by_username("tahinli", &conn).await.unwrap();
278311
279312 assert_eq!(Some(created_user), searched_user);
280313 }