Commit 2ad2191d0b

2ad2191d0ba31659da4805b82899731918fb08e1

parent: 49d8542f31

Unregistered key

vaw <git@nlih.de> · 2026-07-24 21:29 UTC
committer: <noreply@github.com>

Handle ambiguous display names conforming to spec (#515)

Co-authored-by: Ulyssa <git@ulyssa.dev>

Layout: unified · split

src/base.rs +143 −2
@@ -2,7 +2,7 @@
22//!
33//! The types defined here get used throughout iamb.
44use std::borrow::Cow;
5use std::collections::hash_map::IntoIter;
5use std::collections::hash_map::{Entry, IntoIter};
66use std::collections::{BTreeSet, HashMap, HashSet};
77use std::convert::TryFrom;
88use std::fmt::{self, Display};
@@ -878,6 +878,91 @@ impl UnreadInfo {
878878 }
879879}
880880
881/// Track the display names for users and render any needed disambiguation for
882/// those with overlapping names.
883#[derive(Default)]
884pub struct DisplayNameStore {
885 by_ids: HashMap<OwnedUserId, String>,
886 by_names: HashMap<String, HashSet<OwnedUserId>>,
887}
888
889impl DisplayNameStore {
890 /// Update the `HashSet` associated with a given displayname.
891 ///
892 /// Note that this *could* be done more elegantly using the Entry API, but
893 /// is intentionally written in a way to avoid cloning conflicting display
894 /// names.
895 fn set_by_name(&mut self, user_id: OwnedUserId, name: &str) {
896 if let Some(existing) = self.by_names.get_mut(name) {
897 existing.insert(user_id);
898 } else {
899 self.by_names.insert(name.to_owned(), HashSet::from([user_id]));
900 }
901 }
902
903 /// Track a new user ID to displayname mapping, or unset any existing ones.
904 pub fn set(&mut self, user_id: OwnedUserId, name: Option<String>) {
905 if let Some(name) = name.as_deref() {
906 self.set_by_name(user_id.clone(), name);
907 }
908
909 let previous = match (self.by_ids.entry(user_id), name) {
910 // Nothing to do!
911 (Entry::Vacant(_), None) => None,
912
913 // Setting initial display name for user:
914 (Entry::Vacant(v), Some(name)) => {
915 v.insert(name);
916 None
917 },
918
919 // Unsetting display name:
920 (Entry::Occupied(o), None) => Some(o.remove_entry()),
921
922 // Replacing existing name:
923 (Entry::Occupied(mut o), Some(name)) => {
924 if o.get() == &name {
925 None
926 } else {
927 Some((o.key().clone(), o.insert(name)))
928 }
929 },
930 };
931
932 let Some((user_id, previous)) = previous else {
933 return;
934 };
935
936 let Some(users) = self.by_names.get_mut(&previous) else {
937 return;
938 };
939
940 users.remove(&user_id);
941
942 if users.is_empty() {
943 self.by_names.remove(&previous);
944 }
945 }
946
947 pub fn get<'a>(&'a self, user_id: &UserId) -> Option<Cow<'a, str>> {
948 let displayname = self.by_ids.get(user_id)?;
949 let users = self.by_names.get(displayname)?;
950
951 if !users.contains(user_id) {
952 // Internal consistency error? Assume no display name:
953 return None;
954 }
955
956 if users.len() == 1 {
957 // Unambiguous!
958 return Some(Cow::Borrowed(displayname.as_str()));
959 }
960
961 // Ambiguous username, so include unique user ID:
962 Some(Cow::Owned(format!("{displayname} ({user_id})")))
963 }
964}
965
881966/// Information about room's the user's joined.
882967pub struct RoomInfo {
883968 /// The display name for this room.
@@ -919,7 +1004,7 @@ pub struct RoomInfo {
9191004 pub users_typing: Option<(Instant, Vec<OwnedUserId>)>,
9201005
9211006 /// The display names for users in this room.
922 pub display_names: HashMap<OwnedUserId, String>,
1007 pub display_names: DisplayNameStore,
9231008
9241009 /// The last time the room was rendered, used to detect if it is currently open.
9251010 pub draw_last: Option<Instant>,
@@ -2409,4 +2494,60 @@ pub mod tests {
24092494 let res = complete_cmdbar(&text, &mut cursor, &store);
24102495 assert_eq!(res, users);
24112496 }
2497
2498 #[test]
2499 fn test_ambiguous_displaynames() {
2500 let mut store = DisplayNameStore::default();
2501
2502 store.set(TEST_USER1.clone(), Some("John".into()));
2503 store.set(TEST_USER2.clone(), Some("John".into()));
2504 store.set(TEST_USER3.clone(), Some("Jane".into()));
2505 store.set(TEST_USER4.clone(), Some("Alice".into()));
2506 store.set(TEST_USER5.clone(), Some("Bob".into()));
2507
2508 // TEST_USER1 and TEST_USER2 are both ambiguous, while the other are unambiguous:
2509 assert_eq!(store.get(&TEST_USER1).unwrap().as_ref(), "John (@user1:example.com)");
2510 assert_eq!(store.get(&TEST_USER2).unwrap().as_ref(), "John (@user2:example.com)");
2511 assert_eq!(store.get(&TEST_USER3).unwrap().as_ref(), "Jane");
2512 assert_eq!(store.get(&TEST_USER4).unwrap().as_ref(), "Alice");
2513 assert_eq!(store.get(&TEST_USER5).unwrap().as_ref(), "Bob");
2514
2515 // TEST_USER1 becomes unambiguous when TEST_USER2 changes:
2516 store.set(TEST_USER2.clone(), Some("Eve".into()));
2517 assert_eq!(store.get(&TEST_USER1).unwrap().as_ref(), "John");
2518 assert_eq!(store.get(&TEST_USER2).unwrap().as_ref(), "Eve");
2519 assert_eq!(store.get(&TEST_USER3).unwrap().as_ref(), "Jane");
2520 assert_eq!(store.get(&TEST_USER4).unwrap().as_ref(), "Alice");
2521 assert_eq!(store.get(&TEST_USER5).unwrap().as_ref(), "Bob");
2522
2523 // TEST_USER5 becomes ambiguous when TEST_USER2 once again changes their name to match:
2524 store.set(TEST_USER2.clone(), Some("Bob".into()));
2525 assert_eq!(store.get(&TEST_USER1).unwrap().as_ref(), "John");
2526 assert_eq!(store.get(&TEST_USER2).unwrap().as_ref(), "Bob (@user2:example.com)");
2527 assert_eq!(store.get(&TEST_USER3).unwrap().as_ref(), "Jane");
2528 assert_eq!(store.get(&TEST_USER4).unwrap().as_ref(), "Alice");
2529 assert_eq!(store.get(&TEST_USER5).unwrap().as_ref(), "Bob (@user5:example.com)");
2530
2531 // Now "Everyone is John":
2532 store.set(TEST_USER2.clone(), Some("John".into()));
2533 store.set(TEST_USER3.clone(), Some("John".into()));
2534 store.set(TEST_USER4.clone(), Some("John".into()));
2535 store.set(TEST_USER5.clone(), Some("John".into()));
2536 assert_eq!(store.get(&TEST_USER1).unwrap().as_ref(), "John (@user1:example.com)");
2537 assert_eq!(store.get(&TEST_USER2).unwrap().as_ref(), "John (@user2:example.com)");
2538 assert_eq!(store.get(&TEST_USER3).unwrap().as_ref(), "John (@user3:example.com)");
2539 assert_eq!(store.get(&TEST_USER4).unwrap().as_ref(), "John (@user4:example.com)");
2540 assert_eq!(store.get(&TEST_USER5).unwrap().as_ref(), "John (@user5:example.com)");
2541
2542 // 2-5 unset their displayname:
2543 store.set(TEST_USER2.clone(), None);
2544 store.set(TEST_USER3.clone(), None);
2545 store.set(TEST_USER4.clone(), None);
2546 store.set(TEST_USER5.clone(), None);
2547 assert_eq!(store.get(&TEST_USER1).unwrap().as_ref(), "John");
2548 assert_eq!(store.get(&TEST_USER2), None);
2549 assert_eq!(store.get(&TEST_USER3), None);
2550 assert_eq!(store.get(&TEST_USER4), None);
2551 assert_eq!(store.get(&TEST_USER5), None);
2552 }
24122553}
src/config.rs +2 −2
@@ -1055,8 +1055,8 @@ impl ApplicationSettings {
10551055 (None, UserDisplayStyle::Username) => Cow::Borrowed(user_id.as_str()),
10561056 (None, UserDisplayStyle::LocalPart) => Cow::Borrowed(user_id.localpart()),
10571057 (None, UserDisplayStyle::DisplayName) => {
1058 if let Some(display) = info.display_names.get(user_id) {
1059 Cow::Borrowed(display.as_str())
1058 if let Some(name) = info.display_names.get(user_id) {
1059 name
10601060 } else {
10611061 Cow::Borrowed(user_id.as_str())
10621062 }
src/windows/mod.rs +1 −1
@@ -1564,7 +1564,7 @@ impl ListItem<IambInfo> for MemberItem {
15641564 spans.push(Span::styled(name, style));
15651565 parens = true;
15661566 } else if let Some(display) = info.display_names.get(user_id) {
1567 spans.push(Span::styled(display.clone(), style));
1567 spans.push(Span::styled(display.into_owned(), style));
15681568 parens = true;
15691569 }
15701570
src/worker.rs +5 −27
@@ -22,7 +22,6 @@ use url::Url;
2222use matrix_sdk::{
2323 authentication::matrix::MatrixSession,
2424 config::{RequestConfig, SyncSettings},
25 deserialized_responses::DisplayName,
2625 encryption::{
2726 verification::{SasVerification, Verification},
2827 BackupDownloadStrategy,
@@ -430,10 +429,9 @@ fn members_insert(
430429 let info = rooms.get_or_default(room_id);
431430
432431 for member in members {
433 let user_id = member.user_id();
434 let display_name =
435 member.display_name().map_or(user_id.to_string(), |str| str.to_string());
436 info.display_names.insert(user_id.to_owned(), display_name);
432 let user_id = member.user_id().to_owned();
433 let name = member.display_name().map(|s| s.to_owned());
434 info.display_names.set(user_id, name);
437435 }
438436 }
439437 // else ???
@@ -1103,34 +1101,14 @@ impl ClientWorker {
11031101 );
11041102
11051103 let _ = self.client.add_event_handler(
1106 |ev: OriginalSyncRoomMemberEvent,
1107 room: MatrixRoom,
1108 client: Client,
1109 store: Ctx<AsyncProgramStore>| {
1104 |ev: OriginalSyncRoomMemberEvent, room: MatrixRoom, store: Ctx<AsyncProgramStore>| {
11101105 async move {
11111106 let room_id = room.room_id();
11121107 let user_id = ev.state_key;
11131108
1114 let ambiguous_name = DisplayName::new(
1115 ev.content.displayname.as_deref().unwrap_or_else(|| user_id.as_str()),
1116 );
1117 let ambiguous = client
1118 .state_store()
1119 .get_users_with_display_name(room_id, &ambiguous_name)
1120 .await
1121 .map(|users| users.len() > 1)
1122 .unwrap_or_default();
1123
11241109 let mut locked = store.lock().await;
11251110 let info = locked.application.get_room_info(room_id.to_owned());
1126
1127 if ambiguous {
1128 info.display_names.remove(&user_id);
1129 } else if let Some(display) = ev.content.displayname {
1130 info.display_names.insert(user_id, display);
1131 } else {
1132 info.display_names.remove(&user_id);
1133 }
1111 info.display_names.set(user_id, ev.content.displayname);
11341112 }
11351113 },
11361114 );