Commit 64891ec68f

64891ec68f0c991d44201a9fa7de34fda61f9898

parent: 61aba80be1

Unregistered key

Ulyssa <git@ulyssa.dev> · 2023-07-07 06:15 UTC

Support hiding server part of username in message scrollback (#71)

Layout: unified · split

src/base.rs +8 −5
@@ -445,6 +445,9 @@ pub struct RoomInfo {
445 445
446 /// Users currently typing in this room, and when we received notification of them doing so. 446 /// Users currently typing in this room, and when we received notification of them doing so.
447 pub users_typing: Option<(Instant, Vec<OwnedUserId>)>, 447 pub users_typing: Option<(Instant, Vec<OwnedUserId>)>,
448
449 /// The display names for users in this room.
450 pub display_names: HashMap<OwnedUserId, String>,
448} 451}
449 452
450impl RoomInfo { 453impl RoomInfo {
@@ -583,13 +586,13 @@ impl RoomInfo {
583 match n { 586 match n {
584 0 => Spans(vec![]), 587 0 => Spans(vec![]),
585 1 => { 588 1 => {
586 let user = settings.get_user_span(typers[0].as_ref()); 589 let user = settings.get_user_span(typers[0].as_ref(), self);
587 590
588 Spans(vec![user, Span::from(" is typing...")]) 591 Spans(vec![user, Span::from(" is typing...")])
589 }, 592 },
590 2 => { 593 2 => {
591 let user1 = settings.get_user_span(typers[0].as_ref()); 594 let user1 = settings.get_user_span(typers[0].as_ref(), self);
592 let user2 = settings.get_user_span(typers[1].as_ref()); 595 let user2 = settings.get_user_span(typers[1].as_ref(), self);
593 596
594 Spans(vec![ 597 Spans(vec![
595 user1, 598 user1,
@@ -835,11 +838,11 @@ impl<'de> Visitor<'de> for IambIdVisitor {
835 }, 838 },
836 Some("members") => { 839 Some("members") => {
837 let Some(path) = url.path_segments() else { 840 let Some(path) = url.path_segments() else {
838 return Err(E::custom( "Invalid members window URL")); 841 return Err(E::custom("Invalid members window URL"));
839 }; 842 };
840 843
841 let &[room_id] = path.collect::<Vec<_>>().as_slice() else { 844 let &[room_id] = path.collect::<Vec<_>>().as_slice() else {
842 return Err(E::custom( "Invalid members window URL")); 845 return Err(E::custom("Invalid members window URL"));
843 }; 846 };
844 847
845 let Ok(room_id) = OwnedRoomId::try_from(room_id) else { 848 let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
src/config.rs +70 −8
@@ -19,7 +19,7 @@ use modalkit::tui::{
19 text::Span, 19 text::Span,
20}; 20};
21 21
22use super::base::IambId; 22use super::base::{IambId, RoomInfo};
23 23
24macro_rules! usage { 24macro_rules! usage {
25 ( $($args: tt)* ) => { 25 ( $($args: tt)* ) => {
@@ -227,6 +227,24 @@ fn merge_users(a: Option<UserOverrides>, b: Option<UserOverrides>) -> Option<Use
227 } 227 }
228} 228}
229 229
230#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
231#[serde(rename_all = "lowercase")]
232pub enum UserDisplayStyle {
233 // The Matrix username for the sender (e.g., "@user:example.com").
234 #[default]
235 Username,
236
237 // The localpart of the Matrix username (e.g., "@user").
238 LocalPart,
239
240 // The display name for the Matrix user, calculated according to the rules from the spec.
241 //
242 // This is usually something like "Ada Lovelace" if the user has configured a display name, but
243 // it can wind up being the Matrix username if there are display name collisions in the room,
244 // in order to avoid any confusion.
245 DisplayName,
246}
247
230#[derive(Clone)] 248#[derive(Clone)]
231pub struct TunableValues { 249pub struct TunableValues {
232 pub log_level: Level, 250 pub log_level: Level,
@@ -238,6 +256,7 @@ pub struct TunableValues {
238 pub typing_notice_send: bool, 256 pub typing_notice_send: bool,
239 pub typing_notice_display: bool, 257 pub typing_notice_display: bool,
240 pub users: UserOverrides, 258 pub users: UserOverrides,
259 pub username_display: UserDisplayStyle,
241 pub default_room: Option<String>, 260 pub default_room: Option<String>,
242 pub open_command: Option<Vec<String>>, 261 pub open_command: Option<Vec<String>>,
243} 262}
@@ -253,6 +272,7 @@ pub struct Tunables {
253 pub typing_notice_send: Option<bool>, 272 pub typing_notice_send: Option<bool>,
254 pub typing_notice_display: Option<bool>, 273 pub typing_notice_display: Option<bool>,
255 pub users: Option<UserOverrides>, 274 pub users: Option<UserOverrides>,
275 pub username_display: Option<UserDisplayStyle>,
256 pub default_room: Option<String>, 276 pub default_room: Option<String>,
257 pub open_command: Option<Vec<String>>, 277 pub open_command: Option<Vec<String>>,
258} 278}
@@ -271,6 +291,7 @@ impl Tunables {
271 typing_notice_send: self.typing_notice_send.or(other.typing_notice_send), 291 typing_notice_send: self.typing_notice_send.or(other.typing_notice_send),
272 typing_notice_display: self.typing_notice_display.or(other.typing_notice_display), 292 typing_notice_display: self.typing_notice_display.or(other.typing_notice_display),
273 users: merge_users(self.users, other.users), 293 users: merge_users(self.users, other.users),
294 username_display: self.username_display.or(other.username_display),
274 default_room: self.default_room.or(other.default_room), 295 default_room: self.default_room.or(other.default_room),
275 open_command: self.open_command.or(other.open_command), 296 open_command: self.open_command.or(other.open_command),
276 } 297 }
@@ -287,6 +308,7 @@ impl Tunables {
287 typing_notice_send: self.typing_notice_send.unwrap_or(true), 308 typing_notice_send: self.typing_notice_send.unwrap_or(true),
288 typing_notice_display: self.typing_notice_display.unwrap_or(true), 309 typing_notice_display: self.typing_notice_display.unwrap_or(true),
289 users: self.users.unwrap_or_default(), 310 users: self.users.unwrap_or_default(),
311 username_display: self.username_display.unwrap_or_default(),
290 default_room: self.default_room, 312 default_room: self.default_room,
291 open_command: self.open_command, 313 open_command: self.open_command,
292 } 314 }
@@ -525,18 +547,45 @@ impl ApplicationSettings {
525 Span::styled(String::from(c), style) 547 Span::styled(String::from(c), style)
526 } 548 }
527 549
528 pub fn get_user_span<'a>(&self, user_id: &'a UserId) -> Span<'a> { 550 pub fn get_user_overrides(
529 let (color, name) = self 551 &self,
530 .tunables 552 user_id: &UserId,
553 ) -> (Option<Color>, Option<Cow<'static, str>>) {
554 self.tunables
531 .users 555 .users
532 .get(user_id) 556 .get(user_id)
533 .map(|user| (user.color.as_ref().map(|c| c.0), user.name.clone().map(Cow::Owned))) 557 .map(|user| (user.color.as_ref().map(|c| c.0), user.name.clone().map(Cow::Owned)))
534 .unwrap_or_default(); 558 .unwrap_or_default()
559 }
535 560
536 let user_id = user_id.as_str(); 561 pub fn get_user_style(&self, user_id: &UserId) -> Style {
537 let color = color.unwrap_or_else(|| user_color(user_id)); 562 let color = self
563 .tunables
564 .users
565 .get(user_id)
566 .and_then(|user| user.color.as_ref().map(|c| c.0))
567 .unwrap_or_else(|| user_color(user_id.as_str()));
568
569 user_style_from_color(color)
570 }
571
572 pub fn get_user_span<'a>(&self, user_id: &'a UserId, info: &'a RoomInfo) -> Span<'a> {
573 let (color, name) = self.get_user_overrides(user_id);
574
575 let color = color.unwrap_or_else(|| user_color(user_id.as_str()));
538 let style = user_style_from_color(color); 576 let style = user_style_from_color(color);
539 let name = name.unwrap_or(Cow::Borrowed(user_id)); 577 let name = match (name, &self.tunables.username_display) {
578 (Some(name), _) => name,
579 (None, UserDisplayStyle::Username) => Cow::Borrowed(user_id.as_str()),
580 (None, UserDisplayStyle::LocalPart) => Cow::Borrowed(user_id.localpart()),
581 (None, UserDisplayStyle::DisplayName) => {
582 if let Some(display) = info.display_names.get(user_id) {
583 Cow::Borrowed(display.as_str())
584 } else {
585 Cow::Borrowed(user_id.as_str())
586 }
587 },
588 };
540 589
541 Span::styled(name, style) 590 Span::styled(name, style)
542 } 591 }
@@ -641,6 +690,19 @@ mod tests {
641 assert_eq!(res.users, Some(users.into_iter().collect())); 690 assert_eq!(res.users, Some(users.into_iter().collect()));
642 } 691 }
643 692
693 #[test]
694 fn test_parse_tunables_username_display() {
695 let res: Tunables = serde_json::from_str("{\"username_display\": \"username\"}").unwrap();
696 assert_eq!(res.username_display, Some(UserDisplayStyle::Username));
697
698 let res: Tunables = serde_json::from_str("{\"username_display\": \"localpart\"}").unwrap();
699 assert_eq!(res.username_display, Some(UserDisplayStyle::LocalPart));
700
701 let res: Tunables =
702 serde_json::from_str("{\"username_display\": \"displayname\"}").unwrap();
703 assert_eq!(res.username_display, Some(UserDisplayStyle::DisplayName));
704 }
705
644 #[test] 706 #[test]
645 fn test_parse_layout() { 707 fn test_parse_layout() {
646 let user = WindowPath::UserId(user_id!("@user:example.com").to_owned()); 708 let user = WindowPath::UserId(user_id!("@user:example.com").to_owned());
src/message/mod.rs +17 −12
@@ -644,7 +644,7 @@ impl Message {
644 { 644 {
645 let cols = MessageColumns::Four; 645 let cols = MessageColumns::Four;
646 let fill = width - USER_GUTTER - TIME_GUTTER - READ_GUTTER; 646 let fill = width - USER_GUTTER - TIME_GUTTER - READ_GUTTER;
647 let user = self.show_sender(prev, true, settings); 647 let user = self.show_sender(prev, true, info, settings);
648 let time = self.timestamp.show_time(); 648 let time = self.timestamp.show_time();
649 let read = match info.receipts.get(self.event.event_id()) { 649 let read = match info.receipts.get(self.event.event_id()) {
650 Some(read) => read.iter(), 650 Some(read) => read.iter(),
@@ -655,7 +655,7 @@ impl Message {
655 } else if USER_GUTTER + TIME_GUTTER + MIN_MSG_LEN <= width { 655 } else if USER_GUTTER + TIME_GUTTER + MIN_MSG_LEN <= width {
656 let cols = MessageColumns::Three; 656 let cols = MessageColumns::Three;
657 let fill = width - USER_GUTTER - TIME_GUTTER; 657 let fill = width - USER_GUTTER - TIME_GUTTER;
658 let user = self.show_sender(prev, true, settings); 658 let user = self.show_sender(prev, true, info, settings);
659 let time = self.timestamp.show_time(); 659 let time = self.timestamp.show_time();
660 let read = [].iter(); 660 let read = [].iter();
661 661
@@ -663,7 +663,7 @@ impl Message {
663 } else if USER_GUTTER + MIN_MSG_LEN <= width { 663 } else if USER_GUTTER + MIN_MSG_LEN <= width {
664 let cols = MessageColumns::Two; 664 let cols = MessageColumns::Two;
665 let fill = width - USER_GUTTER; 665 let fill = width - USER_GUTTER;
666 let user = self.show_sender(prev, true, settings); 666 let user = self.show_sender(prev, true, info, settings);
667 let time = None; 667 let time = None;
668 let read = [].iter(); 668 let read = [].iter();
669 669
@@ -671,7 +671,7 @@ impl Message {
671 } else { 671 } else {
672 let cols = MessageColumns::One; 672 let cols = MessageColumns::One;
673 let fill = width.saturating_sub(2); 673 let fill = width.saturating_sub(2);
674 let user = self.show_sender(prev, false, settings); 674 let user = self.show_sender(prev, false, info, settings);
675 let time = None; 675 let time = None;
676 let read = [].iter(); 676 let read = [].iter();
677 677
@@ -700,7 +700,7 @@ impl Message {
700 if let Some(r) = &reply { 700 if let Some(r) = &reply {
701 let w = width.saturating_sub(2); 701 let w = width.saturating_sub(2);
702 let mut replied = r.show_msg(w, style, true); 702 let mut replied = r.show_msg(w, style, true);
703 let mut sender = r.sender_span(settings); 703 let mut sender = r.sender_span(info, settings);
704 let sender_width = UnicodeWidthStr::width(sender.content.as_ref()); 704 let sender_width = UnicodeWidthStr::width(sender.content.as_ref());
705 let trailing = w.saturating_sub(sender_width + 1); 705 let trailing = w.saturating_sub(sender_width + 1);
706 706
@@ -793,16 +793,21 @@ impl Message {
793 } 793 }
794 } 794 }
795 795
796 fn sender_span(&self, settings: &ApplicationSettings) -> Span { 796 fn sender_span<'a>(
797 settings.get_user_span(self.sender.as_ref()) 797 &'a self,
798 info: &'a RoomInfo,
799 settings: &'a ApplicationSettings,
800 ) -> Span<'a> {
801 settings.get_user_span(self.sender.as_ref(), info)
798 } 802 }
799 803
800 fn show_sender( 804 fn show_sender<'a>(
801 &self, 805 &'a self,
802 prev: Option<&Message>, 806 prev: Option<&Message>,
803 align_right: bool, 807 align_right: bool,
804 settings: &ApplicationSettings, 808 info: &'a RoomInfo,
805 ) -> Option<Span> { 809 settings: &'a ApplicationSettings,
810 ) -> Option<Span<'a>> {
806 if let Some(prev) = prev { 811 if let Some(prev) = prev {
807 if self.sender == prev.sender && 812 if self.sender == prev.sender &&
808 self.timestamp.same_day(&prev.timestamp) && 813 self.timestamp.same_day(&prev.timestamp) &&
@@ -812,7 +817,7 @@ impl Message {
812 } 817 }
813 } 818 }
814 819
815 let Span { content, style } = self.sender_span(settings); 820 let Span { content, style } = self.sender_span(info, settings);
816 let stop = content.len().min(28); 821 let stop = content.len().min(28);
817 let s = &content[..stop]; 822 let s = &content[..stop];
818 823
src/tests.rs +3
@@ -30,6 +30,7 @@ use crate::{
30 ProfileConfig, 30 ProfileConfig,
31 TunableValues, 31 TunableValues,
32 UserColor, 32 UserColor,
33 UserDisplayStyle,
33 UserDisplayTunables, 34 UserDisplayTunables,
34 }, 35 },
35 message::{ 36 message::{
@@ -160,6 +161,7 @@ pub fn mock_room() -> RoomInfo {
160 fetch_id: RoomFetchStatus::NotStarted, 161 fetch_id: RoomFetchStatus::NotStarted,
161 fetch_last: None, 162 fetch_last: None,
162 users_typing: None, 163 users_typing: None,
164 display_names: HashMap::new(),
163 } 165 }
164} 166}
165 167
@@ -189,6 +191,7 @@ pub fn mock_tunables() -> TunableValues {
189 .into_iter() 191 .into_iter()
190 .collect::<HashMap<_, _>>(), 192 .collect::<HashMap<_, _>>(),
191 open_command: None, 193 open_command: None,
194 username_display: UserDisplayStyle::Username,
192 } 195 }
193} 196}
194 197
src/windows/mod.rs +29 −10
@@ -409,7 +409,7 @@ impl WindowOps<IambInfo> for IambWindow {
409 409
410 if need_fetch { 410 if need_fetch {
411 if let Ok(mems) = store.application.worker.members(room_id.clone()) { 411 if let Ok(mems) = store.application.worker.members(room_id.clone()) {
412 let items = mems.into_iter().map(MemberItem::new); 412 let items = mems.into_iter().map(|m| MemberItem::new(m, room_id.clone()));
413 state.set(items.collect()); 413 state.set(items.collect());
414 *last_fetch = Some(Instant::now()); 414 *last_fetch = Some(Instant::now());
415 } 415 }
@@ -1100,11 +1100,12 @@ impl Promptable<ProgramContext, ProgramStore, IambInfo> for VerifyItem {
1100#[derive(Clone)] 1100#[derive(Clone)]
1101pub struct MemberItem { 1101pub struct MemberItem {
1102 member: RoomMember, 1102 member: RoomMember,
1103 room_id: OwnedRoomId,
1103} 1104}
1104 1105
1105impl MemberItem { 1106impl MemberItem {
1106 fn new(member: RoomMember) -> Self { 1107 fn new(member: RoomMember, room_id: OwnedRoomId) -> Self {
1107 Self { member } 1108 Self { member, room_id }
1108 } 1109 }
1109} 1110}
1110 1111
@@ -1121,12 +1122,32 @@ impl ListItem<IambInfo> for MemberItem {
1121 _: &ViewportContext<ListCursor>, 1122 _: &ViewportContext<ListCursor>,
1122 store: &mut ProgramStore, 1123 store: &mut ProgramStore,
1123 ) -> Text { 1124 ) -> Text {
1124 let mut user = store.application.settings.get_user_span(self.member.user_id()); 1125 let info = store.application.rooms.get_or_default(self.room_id.clone());
1126 let user_id = self.member.user_id();
1127
1128 let (color, name) = store.application.settings.get_user_overrides(self.member.user_id());
1129 let color = color.unwrap_or_else(|| super::config::user_color(user_id.as_str()));
1130 let mut style = super::config::user_style_from_color(color);
1125 1131
1126 if selected { 1132 if selected {
1127 user.style = user.style.add_modifier(StyleModifier::REVERSED); 1133 style = style.add_modifier(StyleModifier::REVERSED);
1134 }
1135
1136 let mut spans = vec![];
1137 let mut parens = false;
1138
1139 if let Some(name) = name {
1140 spans.push(Span::styled(name, style));
1141 parens = true;
1142 } else if let Some(display) = info.display_names.get(user_id) {
1143 spans.push(Span::styled(display.clone(), style));
1144 parens = true;
1128 } 1145 }
1129 1146
1147 spans.extend(parens.then_some(Span::styled(" (", style)));
1148 spans.push(Span::styled(user_id.as_str(), style));
1149 spans.extend(parens.then_some(Span::styled(")", style)));
1150
1130 let state = match self.member.membership() { 1151 let state = match self.member.membership() {
1131 MembershipState::Ban => Span::raw(" (banned)").into(), 1152 MembershipState::Ban => Span::raw(" (banned)").into(),
1132 MembershipState::Invite => Span::raw(" (invited)").into(), 1153 MembershipState::Invite => Span::raw(" (invited)").into(),
@@ -1136,11 +1157,9 @@ impl ListItem<IambInfo> for MemberItem {
1136 _ => None, 1157 _ => None,
1137 }; 1158 };
1138 1159
1139 if let Some(state) = state { 1160 spans.extend(state);
1140 Spans(vec![user, state]).into() 1161
1141 } else { 1162 return Spans(spans).into();
1142 user.into()
1143 }
1144 } 1163 }
1145 1164
1146 fn get_word(&self) -> Option<String> { 1165 fn get_word(&self) -> Option<String> {
src/windows/room/chat.rs +2 −1
@@ -808,7 +808,8 @@ impl<'a> StatefulWidget for Chat<'a> {
808 state.reply_to.as_ref().and_then(|k| { 808 state.reply_to.as_ref().and_then(|k| {
809 let room = self.store.application.rooms.get(state.id())?; 809 let room = self.store.application.rooms.get(state.id())?;
810 let msg = room.messages.get(k)?; 810 let msg = room.messages.get(k)?;
811 let user = self.store.application.settings.get_user_span(msg.sender.as_ref()); 811 let user =
812 self.store.application.settings.get_user_span(msg.sender.as_ref(), room);
812 let prefix = if editing.is_some() { 813 let prefix = if editing.is_some() {
813 Span::from("Editing reply to ") 814 Span::from("Editing reply to ")
814 } else { 815 } else {
src/windows/room/mod.rs +2 −1
@@ -139,8 +139,9 @@ impl RoomState {
139 let mut invited = vec![Span::from(format!("You have been invited to join {name}"))]; 139 let mut invited = vec![Span::from(format!("You have been invited to join {name}"))];
140 140
141 if let Ok(Some(inviter)) = &inviter { 141 if let Ok(Some(inviter)) = &inviter {
142 let info = store.application.rooms.get_or_default(self.id().to_owned());
142 invited.push(Span::from(" by ")); 143 invited.push(Span::from(" by "));
143 invited.push(store.application.settings.get_user_span(inviter.user_id())); 144 invited.push(store.application.settings.get_user_span(inviter.user_id(), info));
144 } 145 }
145 146
146 let l1 = Spans(invited); 147 let l1 = Spans(invited);
src/worker.rs +33
@@ -40,6 +40,7 @@ use matrix_sdk::{
40 reaction::ReactionEventContent, 40 reaction::ReactionEventContent,
41 room::{ 41 room::{
42 encryption::RoomEncryptionEventContent, 42 encryption::RoomEncryptionEventContent,
43 member::OriginalSyncRoomMemberEvent,
43 message::{MessageType, RoomMessageEventContent}, 44 message::{MessageType, RoomMessageEventContent},
44 name::RoomNameEventContent, 45 name::RoomNameEventContent,
45 redaction::{OriginalSyncRoomRedactionEvent, SyncRoomRedactionEvent}, 46 redaction::{OriginalSyncRoomRedactionEvent, SyncRoomRedactionEvent},
@@ -838,6 +839,38 @@ impl ClientWorker {
838 }, 839 },
839 ); 840 );
840 841
842 let _ = self.client.add_event_handler(
843 |ev: OriginalSyncRoomMemberEvent,
844 room: MatrixRoom,
845 client: Client,
846 store: Ctx<AsyncProgramStore>| {
847 async move {
848 let room_id = room.room_id();
849 let user_id = ev.state_key;
850
851 let ambiguous_name =
852 ev.content.displayname.as_deref().unwrap_or_else(|| user_id.localpart());
853 let ambiguous = client
854 .store()
855 .get_users_with_display_name(room_id, ambiguous_name)
856 .await
857 .map(|users| users.len() > 1)
858 .unwrap_or_default();
859
860 let mut locked = store.lock().await;
861 let info = locked.application.get_room_info(room_id.to_owned());
862
863 if ambiguous {
864 info.display_names.remove(&user_id);
865 } else if let Some(display) = ev.content.displayname {
866 info.display_names.insert(user_id, display);
867 } else {
868 info.display_names.remove(&user_id);
869 }
870 }
871 },
872 );
873
841 let _ = self.client.add_event_handler( 874 let _ = self.client.add_event_handler(
842 |ev: OriginalSyncKeyVerificationStartEvent, 875 |ev: OriginalSyncKeyVerificationStartEvent,
843 client: Client, 876 client: Client,