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 {
445445
446446 /// Users currently typing in this room, and when we received notification of them doing so.
447447 pub users_typing: Option<(Instant, Vec<OwnedUserId>)>,
448
449 /// The display names for users in this room.
450 pub display_names: HashMap<OwnedUserId, String>,
448451}
449452
450453impl RoomInfo {
@@ -583,13 +586,13 @@ impl RoomInfo {
583586 match n {
584587 0 => Spans(vec![]),
585588 1 => {
586 let user = settings.get_user_span(typers[0].as_ref());
589 let user = settings.get_user_span(typers[0].as_ref(), self);
587590
588591 Spans(vec![user, Span::from(" is typing...")])
589592 },
590593 2 => {
591 let user1 = settings.get_user_span(typers[0].as_ref());
592 let user2 = settings.get_user_span(typers[1].as_ref());
594 let user1 = settings.get_user_span(typers[0].as_ref(), self);
595 let user2 = settings.get_user_span(typers[1].as_ref(), self);
593596
594597 Spans(vec![
595598 user1,
@@ -835,11 +838,11 @@ impl<'de> Visitor<'de> for IambIdVisitor {
835838 },
836839 Some("members") => {
837840 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"));
839842 };
840843
841844 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"));
843846 };
844847
845848 let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
src/config.rs +70 −8
@@ -19,7 +19,7 @@ use modalkit::tui::{
1919 text::Span,
2020};
2121
22use super::base::IambId;
22use super::base::{IambId, RoomInfo};
2323
2424macro_rules! usage {
2525 ( $($args: tt)* ) => {
@@ -227,6 +227,24 @@ fn merge_users(a: Option<UserOverrides>, b: Option<UserOverrides>) -> Option<Use
227227 }
228228}
229229
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
230248#[derive(Clone)]
231249pub struct TunableValues {
232250 pub log_level: Level,
@@ -238,6 +256,7 @@ pub struct TunableValues {
238256 pub typing_notice_send: bool,
239257 pub typing_notice_display: bool,
240258 pub users: UserOverrides,
259 pub username_display: UserDisplayStyle,
241260 pub default_room: Option<String>,
242261 pub open_command: Option<Vec<String>>,
243262}
@@ -253,6 +272,7 @@ pub struct Tunables {
253272 pub typing_notice_send: Option<bool>,
254273 pub typing_notice_display: Option<bool>,
255274 pub users: Option<UserOverrides>,
275 pub username_display: Option<UserDisplayStyle>,
256276 pub default_room: Option<String>,
257277 pub open_command: Option<Vec<String>>,
258278}
@@ -271,6 +291,7 @@ impl Tunables {
271291 typing_notice_send: self.typing_notice_send.or(other.typing_notice_send),
272292 typing_notice_display: self.typing_notice_display.or(other.typing_notice_display),
273293 users: merge_users(self.users, other.users),
294 username_display: self.username_display.or(other.username_display),
274295 default_room: self.default_room.or(other.default_room),
275296 open_command: self.open_command.or(other.open_command),
276297 }
@@ -287,6 +308,7 @@ impl Tunables {
287308 typing_notice_send: self.typing_notice_send.unwrap_or(true),
288309 typing_notice_display: self.typing_notice_display.unwrap_or(true),
289310 users: self.users.unwrap_or_default(),
311 username_display: self.username_display.unwrap_or_default(),
290312 default_room: self.default_room,
291313 open_command: self.open_command,
292314 }
@@ -525,18 +547,45 @@ impl ApplicationSettings {
525547 Span::styled(String::from(c), style)
526548 }
527549
528 pub fn get_user_span<'a>(&self, user_id: &'a UserId) -> Span<'a> {
529 let (color, name) = self
530 .tunables
550 pub fn get_user_overrides(
551 &self,
552 user_id: &UserId,
553 ) -> (Option<Color>, Option<Cow<'static, str>>) {
554 self.tunables
531555 .users
532556 .get(user_id)
533557 .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 }
535560
536 let user_id = user_id.as_str();
537 let color = color.unwrap_or_else(|| user_color(user_id));
561 pub fn get_user_style(&self, user_id: &UserId) -> Style {
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()));
538576 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 };
540589
541590 Span::styled(name, style)
542591 }
@@ -641,6 +690,19 @@ mod tests {
641690 assert_eq!(res.users, Some(users.into_iter().collect()));
642691 }
643692
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
644706 #[test]
645707 fn test_parse_layout() {
646708 let user = WindowPath::UserId(user_id!("@user:example.com").to_owned());
src/message/mod.rs +17 −12
@@ -644,7 +644,7 @@ impl Message {
644644 {
645645 let cols = MessageColumns::Four;
646646 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);
648648 let time = self.timestamp.show_time();
649649 let read = match info.receipts.get(self.event.event_id()) {
650650 Some(read) => read.iter(),
@@ -655,7 +655,7 @@ impl Message {
655655 } else if USER_GUTTER + TIME_GUTTER + MIN_MSG_LEN <= width {
656656 let cols = MessageColumns::Three;
657657 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);
659659 let time = self.timestamp.show_time();
660660 let read = [].iter();
661661
@@ -663,7 +663,7 @@ impl Message {
663663 } else if USER_GUTTER + MIN_MSG_LEN <= width {
664664 let cols = MessageColumns::Two;
665665 let fill = width - USER_GUTTER;
666 let user = self.show_sender(prev, true, settings);
666 let user = self.show_sender(prev, true, info, settings);
667667 let time = None;
668668 let read = [].iter();
669669
@@ -671,7 +671,7 @@ impl Message {
671671 } else {
672672 let cols = MessageColumns::One;
673673 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);
675675 let time = None;
676676 let read = [].iter();
677677
@@ -700,7 +700,7 @@ impl Message {
700700 if let Some(r) = &reply {
701701 let w = width.saturating_sub(2);
702702 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);
704704 let sender_width = UnicodeWidthStr::width(sender.content.as_ref());
705705 let trailing = w.saturating_sub(sender_width + 1);
706706
@@ -793,16 +793,21 @@ impl Message {
793793 }
794794 }
795795
796 fn sender_span(&self, settings: &ApplicationSettings) -> Span {
797 settings.get_user_span(self.sender.as_ref())
796 fn sender_span<'a>(
797 &'a self,
798 info: &'a RoomInfo,
799 settings: &'a ApplicationSettings,
800 ) -> Span<'a> {
801 settings.get_user_span(self.sender.as_ref(), info)
798802 }
799803
800 fn show_sender(
801 &self,
804 fn show_sender<'a>(
805 &'a self,
802806 prev: Option<&Message>,
803807 align_right: bool,
804 settings: &ApplicationSettings,
805 ) -> Option<Span> {
808 info: &'a RoomInfo,
809 settings: &'a ApplicationSettings,
810 ) -> Option<Span<'a>> {
806811 if let Some(prev) = prev {
807812 if self.sender == prev.sender &&
808813 self.timestamp.same_day(&prev.timestamp) &&
@@ -812,7 +817,7 @@ impl Message {
812817 }
813818 }
814819
815 let Span { content, style } = self.sender_span(settings);
820 let Span { content, style } = self.sender_span(info, settings);
816821 let stop = content.len().min(28);
817822 let s = &content[..stop];
818823
src/tests.rs +3
@@ -30,6 +30,7 @@ use crate::{
3030 ProfileConfig,
3131 TunableValues,
3232 UserColor,
33 UserDisplayStyle,
3334 UserDisplayTunables,
3435 },
3536 message::{
@@ -160,6 +161,7 @@ pub fn mock_room() -> RoomInfo {
160161 fetch_id: RoomFetchStatus::NotStarted,
161162 fetch_last: None,
162163 users_typing: None,
164 display_names: HashMap::new(),
163165 }
164166}
165167
@@ -189,6 +191,7 @@ pub fn mock_tunables() -> TunableValues {
189191 .into_iter()
190192 .collect::<HashMap<_, _>>(),
191193 open_command: None,
194 username_display: UserDisplayStyle::Username,
192195 }
193196}
194197
src/windows/mod.rs +29 −10
@@ -409,7 +409,7 @@ impl WindowOps<IambInfo> for IambWindow {
409409
410410 if need_fetch {
411411 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()));
413413 state.set(items.collect());
414414 *last_fetch = Some(Instant::now());
415415 }
@@ -1100,11 +1100,12 @@ impl Promptable<ProgramContext, ProgramStore, IambInfo> for VerifyItem {
11001100#[derive(Clone)]
11011101pub struct MemberItem {
11021102 member: RoomMember,
1103 room_id: OwnedRoomId,
11031104}
11041105
11051106impl MemberItem {
1106 fn new(member: RoomMember) -> Self {
1107 Self { member }
1107 fn new(member: RoomMember, room_id: OwnedRoomId) -> Self {
1108 Self { member, room_id }
11081109 }
11091110}
11101111
@@ -1121,12 +1122,32 @@ impl ListItem<IambInfo> for MemberItem {
11211122 _: &ViewportContext<ListCursor>,
11221123 store: &mut ProgramStore,
11231124 ) -> 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);
11251131
11261132 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;
11281145 }
11291146
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
11301151 let state = match self.member.membership() {
11311152 MembershipState::Ban => Span::raw(" (banned)").into(),
11321153 MembershipState::Invite => Span::raw(" (invited)").into(),
@@ -1136,11 +1157,9 @@ impl ListItem<IambInfo> for MemberItem {
11361157 _ => None,
11371158 };
11381159
1139 if let Some(state) = state {
1140 Spans(vec![user, state]).into()
1141 } else {
1142 user.into()
1143 }
1160 spans.extend(state);
1161
1162 return Spans(spans).into();
11441163 }
11451164
11461165 fn get_word(&self) -> Option<String> {
src/windows/room/chat.rs +2 −1
@@ -808,7 +808,8 @@ impl<'a> StatefulWidget for Chat<'a> {
808808 state.reply_to.as_ref().and_then(|k| {
809809 let room = self.store.application.rooms.get(state.id())?;
810810 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);
812813 let prefix = if editing.is_some() {
813814 Span::from("Editing reply to ")
814815 } else {
src/windows/room/mod.rs +2 −1
@@ -139,8 +139,9 @@ impl RoomState {
139139 let mut invited = vec![Span::from(format!("You have been invited to join {name}"))];
140140
141141 if let Ok(Some(inviter)) = &inviter {
142 let info = store.application.rooms.get_or_default(self.id().to_owned());
142143 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));
144145 }
145146
146147 let l1 = Spans(invited);
src/worker.rs +33
@@ -40,6 +40,7 @@ use matrix_sdk::{
4040 reaction::ReactionEventContent,
4141 room::{
4242 encryption::RoomEncryptionEventContent,
43 member::OriginalSyncRoomMemberEvent,
4344 message::{MessageType, RoomMessageEventContent},
4445 name::RoomNameEventContent,
4546 redaction::{OriginalSyncRoomRedactionEvent, SyncRoomRedactionEvent},
@@ -838,6 +839,38 @@ impl ClientWorker {
838839 },
839840 );
840841
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
841874 let _ = self.client.add_event_handler(
842875 |ev: OriginalSyncKeyVerificationStartEvent,
843876 client: Client,