Commit 8846849cd8

8846849cd8e3bf9cbd4c0079c318dafc648b17ee

parent: 90eebc6218

Unregistered key

vaw <git@nlih.de> · 2026-09-14 00:57 UTC
committer: <noreply@github.com>

Open Matrix URIs on the command line and support user mentions (#508)

Layout: unified · split

docs/iamb.1 +5 −1
@@ -5,7 +5,7 @@
5.\" 5.\"
6.\" You can preview this file with: 6.\" You can preview this file with:
7.\" $ man ./docs/iamb.1 7.\" $ man ./docs/iamb.1
8.Dd Mar 24, 2024 8.Dd Sep 11, 2025
9.Dt IAMB 1 9.Dt IAMB 1
10.Os 10.Os
11.Sh NAME 11.Sh NAME
@@ -16,6 +16,7 @@
16.Op Fl hV 16.Op Fl hV
17.Op Fl P Ar profile 17.Op Fl P Ar profile
18.Op Fl C Ar dir 18.Op Fl C Ar dir
19.Op Ar URI
19.Sh DESCRIPTION 20.Sh DESCRIPTION
20.Nm 21.Nm
21is a client for the Matrix communication protocol. 22is a client for the Matrix communication protocol.
@@ -46,6 +47,9 @@ Show the help text and quit.
46Show the current 47Show the current
47.Nm 48.Nm
48version and quit. 49version and quit.
50.It Ar URI
51A matrix uri or matrix.to link to open on startup. Specified at
52.Lk https://spec.matrix.org/latest/appendices/#uris
49.El 53.El
50 54
51.Sh "GENERAL COMMANDS" 55.Sh "GENERAL COMMANDS"
iamb.desktop +2 −1
@@ -1,7 +1,8 @@
1[Desktop Entry] 1[Desktop Entry]
2Categories=Network;InstantMessaging;Chat; 2Categories=Network;InstantMessaging;Chat;
3Comment=A Matrix client for Vim addicts 3Comment=A Matrix client for Vim addicts
4Exec=iamb 4Exec=iamb %u
5MimeType=x-scheme-handler/matrix
5GenericName=Matrix Client 6GenericName=Matrix Client
6Keywords=Matrix;matrix.org;chat;communications;talk; 7Keywords=Matrix;matrix.org;chat;communications;talk;
7Name=iamb 8Name=iamb
src/base.rs +51 −33
@@ -2,7 +2,7 @@
2//! 2//!
3//! The types defined here get used throughout iamb. 3//! The types defined here get used throughout iamb.
4 4
5use std::collections::hash_map::{Entry, IntoIter}; 5use std::collections::hash_map::IntoIter;
6use std::collections::{BTreeSet, HashSet}; 6use std::collections::{BTreeSet, HashSet};
7 7
8use emojis::Emoji; 8use emojis::Emoji;
@@ -566,7 +566,7 @@ pub enum KeysAction {
566 Import(String, String), 566 Import(String, String),
567} 567}
568 568
569/// An action that the main program loop should. 569/// An action that the main program loop should execute.
570/// 570///
571/// See [the commands module][super::commands] for where these are usually created. 571/// See [the commands module][super::commands] for where these are usually created.
572#[derive(Clone, Debug, Eq, PartialEq)] 572#[derive(Clone, Debug, Eq, PartialEq)]
@@ -583,8 +583,8 @@ pub enum IambAction {
583 /// Perform an action on the current space. 583 /// Perform an action on the current space.
584 Space(SpaceAction), 584 Space(SpaceAction),
585 585
586 /// Open a URL. 586 /// Open a URL (and specify whether to join linked matrix rooms).
587 OpenLink(String), 587 OpenLink(String, bool),
588 588
589 /// Perform an action on the currently focused room. 589 /// Perform an action on the currently focused room.
590 Room(RoomAction), 590 Room(RoomAction),
@@ -992,9 +992,9 @@ struct DisplayNameUsers {
992#[derive(Default)] 992#[derive(Default)]
993pub struct DisplayNameStore { 993pub struct DisplayNameStore {
994 /// The boolean is the same `is_active` field as the argument to [`Self::set`]. 994 /// The boolean is the same `is_active` field as the argument to [`Self::set`].
995 by_ids: HashMap<OwnedUserId, (String, bool)>, 995 by_ids: CompletionMap<OwnedUserId, (Option<String>, bool)>,
996 996
997 by_names: HashMap<String, DisplayNameUsers>, 997 by_names: CompletionMap<String, DisplayNameUsers>,
998} 998}
999 999
1000impl DisplayNameStore { 1000impl DisplayNameStore {
@@ -1028,51 +1028,40 @@ impl DisplayNameStore {
1028 self.set_by_name(user_id.clone(), name, is_active); 1028 self.set_by_name(user_id.clone(), name, is_active);
1029 } 1029 }
1030 1030
1031 let previous = match (self.by_ids.entry(user_id), name) { 1031 if self
1032 // Nothing to do! 1032 .by_ids
1033 (Entry::Vacant(_), None) => None, 1033 .get(&user_id)
1034 1034 .is_some_and(|(n, a)| *n == name && *a == is_active)
1035 // Setting initial display name for user: 1035 {
1036 (Entry::Vacant(v), Some(name)) => { 1036 // nothing to do
1037 v.insert((name, is_active)); 1037 return;
1038 None 1038 }
1039 },
1040 1039
1041 // Unsetting display name: 1040 let previous = self.by_ids.insert(user_id.to_owned(), (name, is_active));
1042 (Entry::Occupied(o), None) => Some(o.remove_entry()),
1043 1041
1044 // Replacing existing name: 1042 let Some((Some(name), was_active)) = previous else {
1045 (Entry::Occupied(mut o), Some(name)) => { 1043 // no previous entry in `self.by_names` to remove
1046 let key = (name, is_active);
1047 if o.get() == &key {
1048 None
1049 } else {
1050 Some((o.key().clone(), o.insert(key)))
1051 }
1052 },
1053 };
1054
1055 let Some((user_id, previous)) = previous else {
1056 return; 1044 return;
1057 }; 1045 };
1058 1046
1059 let Some(users) = self.by_names.get_mut(&previous.0) else { 1047 let Some(users) = self.by_names.get_mut(&name) else {
1060 return; 1048 return;
1061 }; 1049 };
1062 1050
1063 if previous.1 { 1051 if was_active {
1064 users.active.remove(&user_id); 1052 users.active.remove(&user_id);
1065 } else { 1053 } else {
1066 users.inactive.remove(&user_id); 1054 users.inactive.remove(&user_id);
1067 } 1055 }
1068 1056
1069 if users.active.is_empty() && users.inactive.is_empty() { 1057 if users.active.is_empty() && users.inactive.is_empty() {
1070 self.by_names.remove(&previous.0); 1058 self.by_names.remove(&name);
1071 } 1059 }
1072 } 1060 }
1073 1061
1074 pub fn get<'a>(&'a self, user_id: &UserId) -> Option<Cow<'a, str>> { 1062 pub fn get<'a>(&'a self, user_id: &UserId) -> Option<Cow<'a, str>> {
1075 let (displayname, is_active) = self.by_ids.get(user_id)?; 1063 let (displayname, is_active) = self.by_ids.get(user_id)?;
1064 let displayname = displayname.as_ref()?;
1076 let users = self.by_names.get(displayname)?; 1065 let users = self.by_names.get(displayname)?;
1077 1066
1078 if !users.active.contains(user_id) && !users.inactive.contains(user_id) { 1067 if !users.active.contains(user_id) && !users.inactive.contains(user_id) {
@@ -1089,6 +1078,35 @@ impl DisplayNameStore {
1089 // Ambiguous username, so include unique user ID: 1078 // Ambiguous username, so include unique user ID:
1090 Some(Cow::Owned(format!("{displayname} ({user_id})"))) 1079 Some(Cow::Owned(format!("{displayname} ({user_id})")))
1091 } 1080 }
1081
1082 pub fn complete_mention(&self, prefix: &str) -> Vec<String> {
1083 // spec says to mention with display name in anchor text
1084 let mut users: BTreeSet<_> = self
1085 .by_names
1086 .complete(prefix.strip_prefix('@').unwrap_or(prefix))
1087 .into_iter()
1088 .flat_map(|name| {
1089 let users = self.by_names.get(&name).unwrap();
1090 users
1091 .active
1092 .iter()
1093 .map(move |id| format!("[{name}]({})", id.matrix_to_uri()))
1094 })
1095 .collect();
1096
1097 users.extend(self.by_ids.complete(prefix).into_iter().map(|id| {
1098 format!(
1099 "[{}]({})",
1100 self.by_ids
1101 .get(&id)
1102 .and_then(|(name, _)| name.as_deref())
1103 .unwrap_or(id.as_str()),
1104 id.matrix_to_uri()
1105 )
1106 }));
1107
1108 users.into_iter().collect()
1109 }
1092} 1110}
1093 1111
1094/// Information about room's the user's joined. 1112/// Information about room's the user's joined.
@@ -1856,7 +1874,7 @@ pub struct ChatStore {
1856 pub rooms: CompletionMap<OwnedRoomId, RoomInfo>, 1874 pub rooms: CompletionMap<OwnedRoomId, RoomInfo>,
1857 1875
1858 /// Map of room names. 1876 /// Map of room names.
1859 pub names: CompletionMap<String, OwnedRoomId>, 1877 pub names: CompletionMap<OwnedRoomAliasId, OwnedRoomId>,
1860 1878
1861 /// Presence information for other users. 1879 /// Presence information for other users.
1862 pub presences: CompletionMap<OwnedUserId, PresenceState>, 1880 pub presences: CompletionMap<OwnedUserId, PresenceState>,
src/completions.rs +32 −23
@@ -1,5 +1,6 @@
1//! Tab completions for iamb 1//! Tab completions for iamb
2 2
3use matrix_sdk::ruma::RoomId;
3use modalkit::editing::completion::{Completer, complete_path}; 4use modalkit::editing::completion::{Completer, complete_path};
4use modalkit::editing::cursor::Cursor; 5use modalkit::editing::cursor::Cursor;
5use modalkit::env::vim::command::CommandDescription; 6use modalkit::env::vim::command::CommandDescription;
@@ -264,7 +265,7 @@ fn complete_users(input: &str, store: &ChatStore) -> Vec<String> {
264fn complete_matrix_names(input: &str, store: &ChatStore) -> Vec<String> { 265fn complete_matrix_names(input: &str, store: &ChatStore) -> Vec<String> {
265 let list = store.names.complete(input); 266 let list = store.names.complete(input);
266 if !list.is_empty() { 267 if !list.is_empty() {
267 return list; 268 return list.into_iter().map(|i| i.to_string()).collect();
268 } 269 }
269 270
270 let list = store.presences.complete(input); 271 let list = store.presences.complete(input);
@@ -279,7 +280,7 @@ fn complete_matrix_names(input: &str, store: &ChatStore) -> Vec<String> {
279fn complete_room_alias_or_id(input: &str, store: &ChatStore) -> Vec<String> { 280fn complete_room_alias_or_id(input: &str, store: &ChatStore) -> Vec<String> {
280 let list = store.names.complete(input); 281 let list = store.names.complete(input);
281 if !list.is_empty() { 282 if !list.is_empty() {
282 return list; 283 return list.into_iter().map(|i| i.to_string()).collect();
283 } 284 }
284 285
285 store.rooms.complete(input).into_iter().map(|i| i.to_string()).collect() 286 store.rooms.complete(input).into_iter().map(|i| i.to_string()).collect()
@@ -685,26 +686,38 @@ fn complete_cmdbar(text: &EditRope, cursor: &mut Cursor, store: &ChatStore) -> V
685} 686}
686 687
687/// Tab completion within the message bar. 688/// Tab completion within the message bar.
688fn complete_msgbar(text: &EditRope, cursor: &mut Cursor, store: &ChatStore) -> Vec<String> { 689fn complete_msgbar(
690 text: &EditRope,
691 cursor: &mut Cursor,
692 store: &mut ChatStore,
693 room_id: &RoomId,
694) -> Vec<String> {
689 let id = text 695 let id = text
690 .get_prefix_word_mut(cursor, &MATRIX_ID_WORD) 696 .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
691 .unwrap_or_else(EditRope::empty); 697 .unwrap_or_else(EditRope::empty);
692 let id = Cow::from(&id); 698 let id = Cow::from(&id);
693 699
700 let info = store.rooms.get_or_default(room_id.to_owned());
701
694 match id.chars().next() { 702 match id.chars().next() {
695 // Complete room aliases. 703 // Complete room aliases.
696 Some('#') => { 704 Some('#') => {
697 return store.names.complete(id.as_ref()); 705 store
706 .names
707 .complete(id.as_ref())
708 .into_iter()
709 .map(|i| format!("[{}]({})", i, i.matrix_to_uri()))
710 .collect()
698 }, 711 },
699 712
700 // Complete room identifiers. 713 // Complete room identifiers.
701 Some('!') => { 714 Some('!') => {
702 return store 715 store
703 .rooms 716 .rooms
704 .complete(id.as_ref()) 717 .complete(id.as_ref())
705 .into_iter() 718 .into_iter()
706 .map(|i| i.to_string()) 719 .map(|i| format!("[{}]({})", i, i.matrix_to_uri()))
707 .collect(); 720 .collect()
708 }, 721 },
709 722
710 // Complete Emoji shortcodes. 723 // Complete Emoji shortcodes.
@@ -716,14 +729,7 @@ fn complete_msgbar(text: &EditRope, cursor: &mut Cursor, store: &ChatStore) -> V
716 }, 729 },
717 730
718 // Complete usernames for @ and empty strings. 731 // Complete usernames for @ and empty strings.
719 Some('@') | None => { 732 Some('@') | None => info.display_names.complete_mention(&id),
720 return store
721 .presences
722 .complete(id.as_ref())
723 .into_iter()
724 .map(|i| i.to_string())
725 .collect();
726 },
727 733
728 // Unknown sigil. 734 // Unknown sigil.
729 Some(_) => return vec![], 735 Some(_) => return vec![],
@@ -743,7 +749,9 @@ impl Completer<IambInfo> for IambCompleter {
743 match content { 749 match content {
744 IambBufferId::Command(CommandType::Command) => complete_cmdbar(text, cursor, store), 750 IambBufferId::Command(CommandType::Command) => complete_cmdbar(text, cursor, store),
745 IambBufferId::Command(CommandType::Search) => vec![], 751 IambBufferId::Command(CommandType::Search) => vec![],
746 IambBufferId::Room(_, _, RoomFocus::MessageBar) => complete_msgbar(text, cursor, store), 752 IambBufferId::Room(room_id, _, RoomFocus::MessageBar) => {
753 complete_msgbar(text, cursor, store, room_id)
754 },
747 IambBufferId::Room(_, _, RoomFocus::Scrollback) => vec![], 755 IambBufferId::Room(_, _, RoomFocus::Scrollback) => vec![],
748 756
749 IambBufferId::DirectList => vec![], 757 IambBufferId::DirectList => vec![],
@@ -774,24 +782,25 @@ pub mod tests {
774 #[tokio::test] 782 #[tokio::test]
775 async fn test_complete_msgbar() { 783 async fn test_complete_msgbar() {
776 let store = mock_store().await; 784 let store = mock_store().await;
777 let store = store.application; 785 let mut store = store.application;
786 let room_id = TEST_ROOM1_ID.clone();
778 787
779 let text = EditRope::from("going for a walk :walk "); 788 let text = EditRope::from("going for a walk :walk ");
780 let mut cursor = Cursor::new(0, 22); 789 let mut cursor = Cursor::new(0, 22);
781 let res = complete_msgbar(&text, &mut cursor, &store); 790 let res = complete_msgbar(&text, &mut cursor, &mut store, &room_id);
782 assert_eq!(res, vec![":walking:", ":walking_man:", ":walking_woman:"]); 791 assert_eq!(res, vec![":walking:", ":walking_man:", ":walking_woman:"]);
783 assert_eq!(cursor, Cursor::new(0, 17)); 792 assert_eq!(cursor, Cursor::new(0, 17));
784 793
785 let text = EditRope::from("hello @user1 "); 794 let text = EditRope::from("hello @user2 ");
786 let mut cursor = Cursor::new(0, 12); 795 let mut cursor = Cursor::new(0, 12);
787 let res = complete_msgbar(&text, &mut cursor, &store); 796 let res = complete_msgbar(&text, &mut cursor, &mut store, &room_id);
788 assert_eq!(res, vec!["@user1:example.com"]); 797 assert_eq!(res, vec!["[User 2](https://matrix.to/#/@user2:example.com)"]);
789 assert_eq!(cursor, Cursor::new(0, 6)); 798 assert_eq!(cursor, Cursor::new(0, 6));
790 799
791 let text = EditRope::from("see #room "); 800 let text = EditRope::from("see #room ");
792 let mut cursor = Cursor::new(0, 9); 801 let mut cursor = Cursor::new(0, 9);
793 let res = complete_msgbar(&text, &mut cursor, &store); 802 let res = complete_msgbar(&text, &mut cursor, &mut store, &room_id);
794 assert_eq!(res, vec!["#room1:example.com"]); 803 assert_eq!(res, vec!["[#room1:example.com](https://matrix.to/#/%23room1:example.com)"]);
795 assert_eq!(cursor, Cursor::new(0, 4)); 804 assert_eq!(cursor, Cursor::new(0, 4));
796 } 805 }
797 806
src/config.rs +15
@@ -188,6 +188,9 @@ pub struct Iamb {
188 188
189 #[clap(short = 'C', long, value_parser)] 189 #[clap(short = 'C', long, value_parser)]
190 pub config_directory: Option<PathBuf>, 190 pub config_directory: Option<PathBuf>,
191
192 /// `matrix:` uri or `https://matrix.to` link to open
193 pub uri: Option<String>,
191} 194}
192 195
193#[derive(thiserror::Error, Debug)] 196#[derive(thiserror::Error, Debug)]
@@ -1497,6 +1500,18 @@ mod tests {
1497 1500
1498 use matrix_sdk::ruma::user_id; 1501 use matrix_sdk::ruma::user_id;
1499 1502
1503 use crate::tests::{TEST_USER1, mock_room, mock_settings};
1504
1505 #[test]
1506 fn test_get_user_span_borrowed() {
1507 // fix `StyleTreeNode::print` for `StyleTreeNode::UserId` if this breaks
1508 let info = mock_room();
1509 let settings = mock_settings();
1510 let span = settings.get_user_span(&TEST_USER1, &info);
1511
1512 assert!(matches!(span.content, Cow::Borrowed(_)));
1513 }
1514
1500 #[test] 1515 #[test]
1501 fn test_profile_name_invalid() { 1516 fn test_profile_name_invalid() {
1502 assert_eq!(validate_profile_name(""), false); 1517 assert_eq!(validate_profile_name(""), false);
src/main.rs +144 −16
@@ -25,6 +25,7 @@ use std::sync::atomic::AtomicUsize;
25 25
26use clap::{CommandFactory, Parser}; 26use clap::{CommandFactory, Parser};
27use matrix_sdk::ruma::api::error::ErrorKind; 27use matrix_sdk::ruma::api::error::ErrorKind;
28use matrix_sdk::{OwnedServerName, RoomState};
28use matrix_sdk_crypto::encrypt_room_key_export; 29use matrix_sdk_crypto::encrypt_room_key_export;
29use modalkit::actions::{Commandable, TabAction, TabContainer, TabCount, WindowContainer}; 30use modalkit::actions::{Commandable, TabAction, TabContainer, TabCount, WindowContainer};
30use modalkit::crossterm; 31use modalkit::crossterm;
@@ -84,16 +85,13 @@ fn config_tab_to_desc(
84 85
85 let window = match window { 86 let window = match window {
86 config::WindowPath::UserId(user_id) => { 87 config::WindowPath::UserId(user_id) => {
87 let name = user_id.to_string(); 88 let room_id = worker.join_room(user_id.to_string(), vec![])?;
88 let room_id = worker.join_room(name.clone())?;
89 names.insert(name, room_id.clone());
90 IambId::Room(room_id, None) 89 IambId::Room(room_id, None)
91 }, 90 },
92 config::WindowPath::RoomId(room_id) => IambId::Room(room_id, None), 91 config::WindowPath::RoomId(room_id) => IambId::Room(room_id, None),
93 config::WindowPath::AliasId(alias) => { 92 config::WindowPath::AliasId(alias) => {
94 let name = alias.to_string(); 93 let room_id = worker.join_room(alias.to_string(), vec![])?;
95 let room_id = worker.join_room(name.clone())?; 94 names.insert(alias, room_id.clone());
96 names.insert(name, room_id.clone());
97 IambId::Room(room_id, None) 95 IambId::Room(room_id, None)
98 }, 96 },
99 config::WindowPath::Window(id) => id, 97 config::WindowPath::Window(id) => id,
@@ -125,14 +123,100 @@ fn restore_layout(
125 tabs.to_layout(area.into(), store) 123 tabs.to_layout(area.into(), store)
126} 124}
127 125
126/// Returns the `IambId` for the new window or a string to query the user. If they answer `y` this
127/// function should be rerun with `join_or_create` set to `true`.
128fn resolve_mxid(
129 store: &mut ProgramStore,
130 id: MatrixId,
131 via: &[OwnedServerName],
132 join_or_create: bool,
133) -> IambResult<Result<IambId, String>> {
134 let room_name;
135 let room_id = match id {
136 MatrixId::Room(id) => {
137 room_name = id.to_string();
138 id
139 },
140 MatrixId::RoomAlias(alias_id) => {
141 room_name = alias_id.to_string();
142 store.application.worker.resolve_alias(alias_id)?
143 },
144 MatrixId::User(user_id) => {
145 let id = match store.application.worker.client.get_dm_room(&user_id) {
146 Some(room) => room.room_id().to_owned(),
147 None if join_or_create => {
148 store.application.worker.join_room(user_id.to_string(), via.to_owned())?
149 },
150 None => return Ok(Err(format!("No dm with {user_id} found. Create new DM?"))),
151 };
152 room_name = id.to_string();
153 id
154 },
155 MatrixId::Event(owned_room_or_alias_id, _event_id) => {
156 // ignore event id for now
157 room_name = owned_room_or_alias_id.to_string();
158 let room_or_alias_id: &matrix_sdk::ruma::RoomOrAliasId = &owned_room_or_alias_id;
159 if let Ok(alias_id) = <&matrix_sdk::ruma::RoomAliasId>::try_from(room_or_alias_id) {
160 store.application.worker.resolve_alias(alias_id.to_owned())?
161 } else {
162 matrix_sdk::ruma::OwnedRoomId::try_from(owned_room_or_alias_id).unwrap()
163 }
164 },
165 _ => {
166 tracing::error!("encountered unrecoginsed matrix id: {id:?}");
167 return Ok(Err("Matrix link cannot be opened. Press 'n' to continue.".to_owned()));
168 },
169 };
170
171 if store
172 .application
173 .worker
174 .client
175 .get_room(&room_id)
176 .is_none_or(|room| room.state() != RoomState::Joined)
177 {
178 if join_or_create {
179 store.application.worker.join_room(room_name, via.to_owned())?;
180 } else {
181 return Ok(Err(format!("Join room {room_name:?}?")));
182 }
183 }
184
185 Ok(Ok(IambId::Room(room_id, None)))
186}
187
128fn setup_screen( 188fn setup_screen(
129 settings: ApplicationSettings, 189 settings: ApplicationSettings,
130 store: &mut ProgramStore, 190 store: &mut ProgramStore,
191 initial_room: Option<(MatrixId, Vec<OwnedServerName>)>,
131) -> IambResult<ScreenState<IambWindow, IambInfo>> { 192) -> IambResult<ScreenState<IambWindow, IambInfo>> {
132 let cmd = CommandBarState::new(store); 193 let cmd = CommandBarState::new(store);
133 let dims = crossterm::terminal::size()?; 194 let dims = crossterm::terminal::size()?;
134 let area = Rect::new(0, 0, dims.0, dims.1); 195 let area = Rect::new(0, 0, dims.0, dims.1);
135 196
197 if let Some((id, via)) = initial_room {
198 match resolve_mxid(store, id.clone(), &via, false)? {
199 Ok(id) => {
200 return Ok(ScreenState::new(IambWindow::open(id, store)?, cmd));
201 },
202 Err(question) => {
203 restore_tty(false, settings.tunables.mouse.enabled);
204 let join_or_create = loop {
205 match read_yesno(&format!("{question} [y]es/[n]o")) {
206 Some('y') => break true,
207 Some('n') => break false,
208 Some(_) | None => continue,
209 }
210 };
211 setup_tty(&settings)?;
212
213 if join_or_create && let Ok(id) = resolve_mxid(store, id, &via, true)? {
214 return Ok(ScreenState::new(IambWindow::open(id, store)?, cmd));
215 }
216 },
217 }
218 }
219
136 match settings.layout { 220 match settings.layout {
137 config::Layout::Restore => { 221 config::Layout::Restore => {
138 match restore_layout(area, &settings, store) { 222 match restore_layout(area, &settings, store) {
@@ -203,6 +287,7 @@ impl Application {
203 pub async fn new( 287 pub async fn new(
204 settings: ApplicationSettings, 288 settings: ApplicationSettings,
205 store: AsyncProgramStore, 289 store: AsyncProgramStore,
290 initial_room: Option<(MatrixId, Vec<OwnedServerName>)>,
206 ) -> IambResult<Application> { 291 ) -> IambResult<Application> {
207 let backend = CrosstermBackend::new(stdout()); 292 let backend = CrosstermBackend::new(stdout());
208 let terminal = Terminal::new(backend)?; 293 let terminal = Terminal::new(backend)?;
@@ -212,7 +297,7 @@ impl Application {
212 let bindings = KeyManager::new(bindings); 297 let bindings = KeyManager::new(bindings);
213 298
214 let mut locked = store.lock().await; 299 let mut locked = store.lock().await;
215 let screen = setup_screen(settings, locked.deref_mut())?; 300 let screen = setup_screen(settings, locked.deref_mut(), initial_room)?;
216 301
217 let worker = locked.application.worker.clone(); 302 let worker = locked.application.worker.clone();
218 303
@@ -551,12 +636,36 @@ impl Application {
551 self.screen.current_window_mut()?.send_command(act, ctx, store).await? 636 self.screen.current_window_mut()?.send_command(act, ctx, store).await?
552 }, 637 },
553 638
554 IambAction::OpenLink(url) => { 639 IambAction::OpenLink(url, join_or_create) => {
555 tokio::task::spawn_blocking(move || { 640 let matrix_uri = MatrixUri::parse(&url).ok();
556 return open::that(url); 641 let matrix_to_uri = MatrixToUri::parse(&url).ok();
557 });
558 642
559 None 643 let matrix_id = matrix_uri
644 .as_ref()
645 .map(|uri| (uri.id(), uri.via()))
646 .or(matrix_to_uri.as_ref().map(|uri| (uri.id(), uri.via())));
647
648 if let Some((id, via)) = matrix_id {
649 match resolve_mxid(store, id.clone(), via, join_or_create)? {
650 Ok(room) => {
651 let target = OpenTarget::Application(room);
652 let action = WindowAction::Switch(target);
653
654 self.action_prepend(vec![(action.into(), ctx)]);
655 None
656 },
657 Err(prompt) => {
658 let act = IambAction::OpenLink(url, true).into();
659 let dialog = PromptYesNo::new(prompt, vec![act]);
660 let err = UIError::NeedConfirm(Box::new(dialog));
661 return Err(err);
662 },
663 }
664 } else {
665 tokio::task::spawn_blocking(move || open::that(url));
666
667 None
668 }
560 }, 669 },
561 670
562 IambAction::Verify(act, flow_id) => { 671 IambAction::Verify(act, flow_id) => {
@@ -977,7 +1086,10 @@ async fn login_normal(
977 Ok(()) 1086 Ok(())
978} 1087}
979 1088
980async fn run(mut settings: ApplicationSettings) -> IambResult<()> { 1089async fn run(
1090 mut settings: ApplicationSettings,
1091 initial_room: Option<(MatrixId, Vec<OwnedServerName>)>,
1092) -> IambResult<()> {
981 // Work out whether to use the Kitty keyboard protocol before anything 1093 // Work out whether to use the Kitty keyboard protocol before anything
982 // clones the settings, so that every copy agrees with the flags we push in 1094 // clones the settings, so that every copy agrees with the flags we push in
983 // setup_tty() and pop in restore_tty(). 1095 // setup_tty() and pop in restore_tty().
@@ -1038,8 +1150,13 @@ async fn run(mut settings: ApplicationSettings) -> IambResult<()> {
1038 })); 1150 }));
1039 1151
1040 // And finally, start running the terminal UI. 1152 // And finally, start running the terminal UI.
1041 let mut application = Application::new(settings, store).await?; 1153 let mut application = Application::new(settings, store, initial_room)
1042 application.run().await?; 1154 .await
1155 .inspect_err(|_| restore_tty(enable_enhanced_keys, enable_mouse))?;
1156 application
1157 .run()
1158 .await
1159 .inspect_err(|_| restore_tty(enable_enhanced_keys, enable_mouse))?;
1043 1160
1044 // Clean up the terminal on exit. 1161 // Clean up the terminal on exit.
1045 restore_tty(enable_enhanced_keys, enable_mouse); 1162 restore_tty(enable_enhanced_keys, enable_mouse);
@@ -1094,6 +1211,17 @@ fn main() {
1094 return; 1211 return;
1095 } 1212 }
1096 1213
1214 let initial_room = if let Some(uri) = &iamb.uri {
1215 MatrixUri::parse(uri)
1216 .map(|uri| (uri.id().clone(), uri.via().to_owned()))
1217 .or_else(|_| {
1218 MatrixToUri::parse(uri).map(|uri| (uri.id().clone(), uri.via().to_owned()))
1219 })
1220 .ok()
1221 } else {
1222 None
1223 };
1224
1097 // Load configuration and set up the Matrix SDK. 1225 // Load configuration and set up the Matrix SDK.
1098 let settings = ApplicationSettings::load(iamb).unwrap_or_else(print_exit); 1226 let settings = ApplicationSettings::load(iamb).unwrap_or_else(print_exit);
1099 1227
@@ -1116,7 +1244,7 @@ fn main() {
1116 .build() 1244 .build()
1117 .unwrap(); 1245 .unwrap();
1118 1246
1119 if let Err(err) = rt.block_on(async move { run(settings).await }) { 1247 if let Err(err) = rt.block_on(async move { run(settings, initial_room).await }) {
1120 eprintln!("\n{err}\n"); 1248 eprintln!("\n{err}\n");
1121 process::exit(2); 1249 process::exit(2);
1122 } 1250 }
src/message/compose.rs +14 −16
@@ -67,7 +67,7 @@ impl SlashCommand {
67 MessageType::Text(msg) 67 MessageType::Text(msg)
68 }, 68 },
69 SlashCommand::Markdown => { 69 SlashCommand::Markdown => {
70 let msg = text_to_message_content(input.to_string()); 70 let msg = text_to_message_content(input.into());
71 MessageType::Text(msg) 71 MessageType::Text(msg)
72 }, 72 },
73 SlashCommand::Confetti => { 73 SlashCommand::Confetti => {
@@ -170,17 +170,21 @@ fn text_to_html(input: &str) -> Option<String> {
170 markdown_to_html(input, &options).into() 170 markdown_to_html(input, &options).into()
171} 171}
172 172
173fn text_to_message_content(input: String) -> TextMessageEventContent { 173fn text_to_message_content(input: Cow<'_, str>) -> TextMessageEventContent {
174 if let Some(html) = text_to_html(input.as_str()) { 174 if let Some(html) = text_to_html(&input) {
175 TextMessageEventContent::html(input, html) 175 TextMessageEventContent::html(input, html)
176 } else { 176 } else {
177 TextMessageEventContent::plain(input) 177 TextMessageEventContent::plain(input)
178 } 178 }
179} 179}
180 180
181pub fn text_to_message(input: String, default_markup: MarkupFormat) -> RoomMessageEventContent { 181pub fn text_to_message(
182 let (rest, slash) = parse_slash_command(input.as_str()) 182 input: Cow<'_, str>,
183 default_markup: MarkupFormat,
184) -> RoomMessageEventContent {
185 let (rest, slash) = parse_slash_command(&input)
183 .unwrap_or_else(|_| (&input, SlashCommand::from(default_markup))); 186 .unwrap_or_else(|_| (&input, SlashCommand::from(default_markup)));
187
184 let msg = slash 188 let msg = slash
185 .to_message(rest) 189 .to_message(rest)
186 .unwrap_or_else(|_| MessageType::Text(text_to_message_content(input))); 190 .unwrap_or_else(|_| MessageType::Text(text_to_message_content(input)));
@@ -193,19 +197,13 @@ pub fn text_to_text_message_event_content(
193 input: String, 197 input: String,
194 default_markup: MarkupFormat, 198 default_markup: MarkupFormat,
195) -> Option<TextMessageEventContent> { 199) -> Option<TextMessageEventContent> {
196 let (body, cmd) = parse_slash_command(&input) 200 let (rest, slash) = parse_slash_command(&input)
197 .unwrap_or_else(|_| (&input, SlashCommand::from(default_markup))); 201 .unwrap_or_else(|_| (&input, SlashCommand::from(default_markup)));
198 202
199 let content = match cmd { 203 let content = match slash {
200 SlashCommand::Html => TextMessageEventContent::html(body, body), 204 SlashCommand::Html => TextMessageEventContent::html(rest, rest),
201 SlashCommand::Plaintext => TextMessageEventContent::plain(body), 205 SlashCommand::Plaintext => TextMessageEventContent::plain(rest),
202 SlashCommand::Markdown => { 206 SlashCommand::Markdown => text_to_message_content(rest.into()),
203 if let Some(html) = text_to_html(body) {
204 TextMessageEventContent::html(body, html)
205 } else {
206 TextMessageEventContent::plain(body)
207 }
208 },
209 _ => return None, 207 _ => return None,
210 }; 208 };
211 209
src/message/html.rs +129 −50
@@ -17,6 +17,7 @@ use html5ever::interface::{Attribute, QualName};
17use html5ever::tendril::{StrTendril, TendrilSink}; 17use html5ever::tendril::{StrTendril, TendrilSink};
18use html5ever::{local_name, ns}; 18use html5ever::{local_name, ns};
19use markup5ever_rcdom::{Handle, NodeData, RcDom}; 19use markup5ever_rcdom::{Handle, NodeData, RcDom};
20use matrix_sdk::OwnedServerName;
20use ratatui::symbols::line; 21use ratatui::symbols::line;
21 22
22use crate::message::printer::TextPrinter; 23use crate::message::printer::TextPrinter;
@@ -79,12 +80,14 @@ impl ListStyle {
79pub type StyleTreeChildren = Vec<StyleTreeNode>; 80pub type StyleTreeChildren = Vec<StyleTreeNode>;
80 81
81/// Type of contents in a table cell. 82/// Type of contents in a table cell.
83#[derive(Debug, Clone, Copy)]
82pub enum CellType { 84pub enum CellType {
83 Data, 85 Data,
84 Header, 86 Header,
85} 87}
86 88
87/// A collection of cells for a single row in a table. 89/// A collection of cells for a single row in a table.
90#[derive(Debug, Clone)]
88pub struct TableRow { 91pub struct TableRow {
89 cells: Vec<(CellType, StyleTreeNode)>, 92 cells: Vec<(CellType, StyleTreeNode)>,
90} 93}
@@ -102,6 +105,7 @@ impl TableRow {
102} 105}
103 106
104/// A collection of rows in a table. 107/// A collection of rows in a table.
108#[derive(Debug, Clone)]
105pub struct TableSection { 109pub struct TableSection {
106 rows: Vec<TableRow>, 110 rows: Vec<TableRow>,
107} 111}
@@ -119,6 +123,7 @@ impl TableSection {
119} 123}
120 124
121/// A table. 125/// A table.
126#[derive(Debug, Clone)]
122pub struct Table { 127pub struct Table {
123 caption: Option<Box<StyleTreeNode>>, 128 caption: Option<Box<StyleTreeNode>>,
124 sections: Vec<TableSection>, 129 sections: Vec<TableSection>,
@@ -140,6 +145,7 @@ impl Table {
140 width: usize, 145 width: usize,
141 style: Style, 146 style: Style,
142 settings: &'a ApplicationSettings, 147 settings: &'a ApplicationSettings,
148 info: &'a RoomInfo,
143 ) -> Text<'a> { 149 ) -> Text<'a> {
144 let mut text = Text::default(); 150 let mut text = Text::default();
145 let columns = self.columns(); 151 let columns = self.columns();
@@ -158,7 +164,8 @@ impl Table {
158 164
159 if let Some(caption) = &self.caption { 165 if let Some(caption) = &self.caption {
160 let subw = width.saturating_sub(6); 166 let subw = width.saturating_sub(6);
161 let mut printer = TextPrinter::new(subw, style, settings).align(Alignment::Center); 167 let mut printer =
168 TextPrinter::new(subw, style, settings, info).align(Alignment::Center);
162 caption.print(&mut printer, style); 169 caption.print(&mut printer, style);
163 170
164 for mut line in printer.finish().lines { 171 for mut line in printer.finish().lines {
@@ -205,7 +212,7 @@ impl Table {
205 CellType::Data => style, 212 CellType::Data => style,
206 }; 213 };
207 214
208 cell.to_text(*w, style, settings) 215 cell.to_text(*w, style, settings, info)
209 } else { 216 } else {
210 space_text(*w, style) 217 space_text(*w, style)
211 }; 218 };
@@ -247,6 +254,7 @@ impl Table {
247} 254}
248 255
249/// A processed HTML element that we can render to the terminal. 256/// A processed HTML element that we can render to the terminal.
257#[derive(Debug, Clone)]
250pub enum StyleTreeNode { 258pub enum StyleTreeNode {
251 Anchor(Box<StyleTreeNode>, char, Url), 259 Anchor(Box<StyleTreeNode>, char, Url),
252 Blockquote(Box<StyleTreeNode>), 260 Blockquote(Box<StyleTreeNode>),
@@ -263,10 +271,10 @@ pub enum StyleTreeNode {
263 Table(Table), 271 Table(Table),
264 Text(Cow<'static, str>), 272 Text(Cow<'static, str>),
265 Sequence(StyleTreeChildren), 273 Sequence(StyleTreeChildren),
266 RoomAlias(OwnedRoomAliasId), 274 RoomAlias(OwnedRoomAliasId, Option<char>),
267 RoomId(OwnedRoomId), 275 RoomId(OwnedRoomId, Vec<OwnedServerName>, Option<char>),
268 UserId(OwnedUserId), 276 UserId(OwnedUserId, Option<char>),
269 DisplayName(String, OwnedUserId), 277 DisplayName(String, OwnedUserId, Option<char>),
270} 278}
271 279
272impl StyleTreeNode { 280impl StyleTreeNode {
@@ -275,8 +283,9 @@ impl StyleTreeNode {
275 width: usize, 283 width: usize,
276 style: Style, 284 style: Style,
277 settings: &'a ApplicationSettings, 285 settings: &'a ApplicationSettings,
286 info: &'a RoomInfo,
278 ) -> Text<'a> { 287 ) -> Text<'a> {
279 let mut printer = TextPrinter::new(width, style, settings); 288 let mut printer = TextPrinter::new(width, style, settings, info);
280 self.print(&mut printer, style); 289 self.print(&mut printer, style);
281 printer.finish() 290 printer.finish()
282 } 291 }
@@ -306,16 +315,31 @@ impl StyleTreeNode {
306 table.gather_links(urls); 315 table.gather_links(urls);
307 }, 316 },
308 317
318 StyleTreeNode::DisplayName(_, user_id, c) | StyleTreeNode::UserId(user_id, c) => {
319 if let Some(c) = c {
320 let to_url = Url::parse(&user_id.matrix_uri(false).to_string()).unwrap();
321 urls.push((*c, to_url));
322 }
323 },
324 StyleTreeNode::RoomId(room_id, via, c) => {
325 if let Some(c) = c {
326 let to_url =
327 Url::parse(&room_id.matrix_uri_via(via.iter().cloned(), false).to_string())
328 .unwrap();
329 urls.push((*c, to_url));
330 }
331 },
332 StyleTreeNode::RoomAlias(alias, c) => {
333 if let Some(c) = c {
334 let to_url = Url::parse(&alias.matrix_uri(false).to_string()).unwrap();
335 urls.push((*c, to_url));
336 }
337 },
338
309 StyleTreeNode::Image(_) => {}, 339 StyleTreeNode::Image(_) => {},
310 StyleTreeNode::Ruler => {}, 340 StyleTreeNode::Ruler => {},
311 StyleTreeNode::Text(_) => {}, 341 StyleTreeNode::Text(_) => {},
312 StyleTreeNode::Break => {}, 342 StyleTreeNode::Break => {},
313
314 // TODO: eventually these should turn into internal links:
315 StyleTreeNode::UserId(_) => {},
316 StyleTreeNode::RoomId(_) => {},
317 StyleTreeNode::RoomAlias(_) => {},
318 StyleTreeNode::DisplayName(_, _) => {},
319 } 343 }
320 } 344 }
321 345
@@ -428,7 +452,7 @@ impl StyleTreeNode {
428 } 452 }
429 }, 453 },
430 StyleTreeNode::Table(table) => { 454 StyleTreeNode::Table(table) => {
431 let text = table.to_text(width, style, printer.settings); 455 let text = table.to_text(width, style, printer.settings, printer.info);
432 printer.push_text(text); 456 printer.push_text(text);
433 }, 457 },
434 StyleTreeNode::Break => { 458 StyleTreeNode::Break => {
@@ -445,19 +469,25 @@ impl StyleTreeNode {
445 } 469 }
446 }, 470 },
447 471
448 StyleTreeNode::UserId(user_id) => { 472 StyleTreeNode::UserId(user_id, _) => {
449 let style = printer.settings().get_user_style(user_id); 473 let mut span: Span<'a> = printer.settings().get_user_span(user_id, printer.info);
450 printer.push_str(user_id.as_str(), style); 474 let style = style.patch(span.style);
475 span.style = style;
476
477 if !span.content.starts_with('@') {
478 printer.push_str("@", style);
479 }
480 printer.push_span_nobreak(span);
451 }, 481 },
452 StyleTreeNode::DisplayName(display_name, user_id) => { 482 StyleTreeNode::DisplayName(display_name, user_id, _) => {
453 let style = printer.settings().get_user_style(user_id); 483 let style = printer.settings().get_user_style(user_id);
454 printer.push_str(display_name.as_str(), style); 484 printer.push_str(display_name.as_str(), style);
455 }, 485 },
456 StyleTreeNode::RoomId(room_id) => { 486 StyleTreeNode::RoomId(room_id, _, _) => {
457 let bold = style.add_modifier(StyleModifier::BOLD); 487 let bold = style.add_modifier(StyleModifier::BOLD);
458 printer.push_str(room_id.as_str(), bold); 488 printer.push_str(room_id.as_str(), bold);
459 }, 489 },
460 StyleTreeNode::RoomAlias(alias) => { 490 StyleTreeNode::RoomAlias(alias, _) => {
461 let bold = style.add_modifier(StyleModifier::BOLD); 491 let bold = style.add_modifier(StyleModifier::BOLD);
462 printer.push_str(alias.as_str(), bold); 492 printer.push_str(alias.as_str(), bold);
463 }, 493 },
@@ -486,8 +516,9 @@ impl StyleTree {
486 width: usize, 516 width: usize,
487 style: Style, 517 style: Style,
488 settings: &'a ApplicationSettings, 518 settings: &'a ApplicationSettings,
519 info: &'a RoomInfo,
489 ) -> Text<'a> { 520 ) -> Text<'a> {
490 let mut printer = TextPrinter::new(width, style, settings); 521 let mut printer = TextPrinter::new(width, style, settings, info);
491 522
492 for child in self.children.iter() { 523 for child in self.children.iter() {
493 child.print(&mut printer, style); 524 child.print(&mut printer, style);
@@ -670,6 +701,37 @@ fn attrs_to_style(attrs: &[Attribute]) -> Style {
670 return style; 701 return style;
671} 702}
672 703
704fn mxid2t(
705 id: &MatrixId,
706 via: &[OwnedServerName],
707 n: Option<char>,
708 c: &StyleTreeNode,
709 h: &Url,
710) -> StyleTreeNode {
711 match id {
712 MatrixId::Room(room_id) => StyleTreeNode::RoomId(room_id.to_owned(), via.to_owned(), n),
713 MatrixId::RoomAlias(alias) => StyleTreeNode::RoomAlias(alias.to_owned(), n),
714 MatrixId::User(user_id) => StyleTreeNode::UserId(user_id.to_owned(), n),
715 MatrixId::Event(room_or_alias_id, _) => {
716 let room_or_alias_id: &matrix_sdk::ruma::RoomOrAliasId = room_or_alias_id;
717 // ignore event id for now
718 if let Ok(alias_id) = <&matrix_sdk::ruma::RoomAliasId>::try_from(room_or_alias_id) {
719 StyleTreeNode::RoomAlias(alias_id.to_owned(), n)
720 } else {
721 let room_id = <&matrix_sdk::ruma::RoomId>::try_from(room_or_alias_id).unwrap();
722 StyleTreeNode::RoomId(room_id.to_owned(), via.to_owned(), n)
723 }
724 },
725 _ => {
726 if let Some(n) = n {
727 StyleTreeNode::Anchor(Box::new(c.to_owned()), n, h.to_owned())
728 } else {
729 c.clone()
730 }
731 },
732 }
733}
734
673fn h2t(hdl: &Handle, state: &mut TreeGenState) -> StyleTreeChildren { 735fn h2t(hdl: &Handle, state: &mut TreeGenState) -> StyleTreeChildren {
674 let node = hdl.deref(); 736 let node = hdl.deref();
675 737
@@ -684,7 +746,13 @@ fn h2t(hdl: &Handle, state: &mut TreeGenState) -> StyleTreeChildren {
684 let h = attrs_to_href(&attrs.borrow()).and_then(|u| Url::parse(&u).ok()); 746 let h = attrs_to_href(&attrs.borrow()).and_then(|u| Url::parse(&u).ok());
685 747
686 if let Some(h) = h { 748 if let Some(h) = h {
687 if let Some(n) = state.next_link_char() { 749 let n = state.next_link_char();
750
751 if let Ok(uri) = MatrixToUri::parse(h.as_str()) {
752 mxid2t(uri.id(), uri.via(), n, &c, &h)
753 } else if let Ok(uri) = MatrixUri::parse(h.as_str()) {
754 mxid2t(uri.id(), uri.via(), n, &c, &h)
755 } else if let Some(n) = n {
688 StyleTreeNode::Anchor(c, n, h) 756 StyleTreeNode::Anchor(c, n, h)
689 } else { 757 } else {
690 *c 758 *c
@@ -827,21 +895,21 @@ pub fn parse_matrix_html(s: &str) -> StyleTree {
827#[cfg(test)] 895#[cfg(test)]
828pub mod tests { 896pub mod tests {
829 use super::*; 897 use super::*;
830
831 use pretty_assertions::assert_eq; 898 use pretty_assertions::assert_eq;
832 use unicode_width::UnicodeWidthStr; 899 use unicode_width::UnicodeWidthStr;
833 900
834 use crate::tests::mock_settings; 901 use crate::tests::{mock_room, mock_settings};
835 use crate::util::space_span; 902 use crate::util::space_span;
836 903
837 #[test] 904 #[test]
838 fn test_header() { 905 fn test_header() {
906 let info = mock_room();
839 let settings = mock_settings(); 907 let settings = mock_settings();
840 let bold = Style::default().add_modifier(StyleModifier::BOLD); 908 let bold = Style::default().add_modifier(StyleModifier::BOLD);
841 909
842 let s = "<h1>Header 1</h1>"; 910 let s = "<h1>Header 1</h1>";
843 let tree = parse_matrix_html(s); 911 let tree = parse_matrix_html(s);
844 let text = tree.to_text(20, Style::default(), &settings); 912 let text = tree.to_text(20, Style::default(), &settings, &info);
845 assert_eq!(text.lines, vec![Line::from(vec![ 913 assert_eq!(text.lines, vec![Line::from(vec![
846 Span::styled("#", bold), 914 Span::styled("#", bold),
847 Span::styled(" ", bold), 915 Span::styled(" ", bold),
@@ -853,7 +921,7 @@ pub mod tests {
853 921
854 let s = "<h2>Header 2</h2>"; 922 let s = "<h2>Header 2</h2>";
855 let tree = parse_matrix_html(s); 923 let tree = parse_matrix_html(s);
856 let text = tree.to_text(20, Style::default(), &settings); 924 let text = tree.to_text(20, Style::default(), &settings, &info);
857 assert_eq!(text.lines, vec![Line::from(vec![ 925 assert_eq!(text.lines, vec![Line::from(vec![
858 Span::styled("#", bold), 926 Span::styled("#", bold),
859 Span::styled("#", bold), 927 Span::styled("#", bold),
@@ -866,7 +934,7 @@ pub mod tests {
866 934
867 let s = "<h3>Header 3</h3>"; 935 let s = "<h3>Header 3</h3>";
868 let tree = parse_matrix_html(s); 936 let tree = parse_matrix_html(s);
869 let text = tree.to_text(20, Style::default(), &settings); 937 let text = tree.to_text(20, Style::default(), &settings, &info);
870 assert_eq!(text.lines, vec![Line::from(vec![ 938 assert_eq!(text.lines, vec![Line::from(vec![
871 Span::styled("#", bold), 939 Span::styled("#", bold),
872 Span::styled("#", bold), 940 Span::styled("#", bold),
@@ -880,7 +948,7 @@ pub mod tests {
880 948
881 let s = "<h4>Header 4</h4>"; 949 let s = "<h4>Header 4</h4>";
882 let tree = parse_matrix_html(s); 950 let tree = parse_matrix_html(s);
883 let text = tree.to_text(20, Style::default(), &settings); 951 let text = tree.to_text(20, Style::default(), &settings, &info);
884 assert_eq!(text.lines, vec![Line::from(vec![ 952 assert_eq!(text.lines, vec![Line::from(vec![
885 Span::styled("#", bold), 953 Span::styled("#", bold),
886 Span::styled("#", bold), 954 Span::styled("#", bold),
@@ -895,7 +963,7 @@ pub mod tests {
895 963
896 let s = "<h5>Header 5</h5>"; 964 let s = "<h5>Header 5</h5>";
897 let tree = parse_matrix_html(s); 965 let tree = parse_matrix_html(s);
898 let text = tree.to_text(20, Style::default(), &settings); 966 let text = tree.to_text(20, Style::default(), &settings, &info);
899 assert_eq!(text.lines, vec![Line::from(vec![ 967 assert_eq!(text.lines, vec![Line::from(vec![
900 Span::styled("#", bold), 968 Span::styled("#", bold),
901 Span::styled("#", bold), 969 Span::styled("#", bold),
@@ -911,7 +979,7 @@ pub mod tests {
911 979
912 let s = "<h6>Header 6</h6>"; 980 let s = "<h6>Header 6</h6>";
913 let tree = parse_matrix_html(s); 981 let tree = parse_matrix_html(s);
914 let text = tree.to_text(20, Style::default(), &settings); 982 let text = tree.to_text(20, Style::default(), &settings, &info);
915 assert_eq!(text.lines, vec![Line::from(vec![ 983 assert_eq!(text.lines, vec![Line::from(vec![
916 Span::styled("#", bold), 984 Span::styled("#", bold),
917 Span::styled("#", bold), 985 Span::styled("#", bold),
@@ -929,6 +997,7 @@ pub mod tests {
929 997
930 #[test] 998 #[test]
931 fn test_style() { 999 fn test_style() {
1000 let info = mock_room();
932 let settings = mock_settings(); 1001 let settings = mock_settings();
933 let def = Style::default(); 1002 let def = Style::default();
934 let bold = def.add_modifier(StyleModifier::BOLD); 1003 let bold = def.add_modifier(StyleModifier::BOLD);
@@ -939,7 +1008,7 @@ pub mod tests {
939 1008
940 let s = "<b>Bold!</b>"; 1009 let s = "<b>Bold!</b>";
941 let tree = parse_matrix_html(s); 1010 let tree = parse_matrix_html(s);
942 let text = tree.to_text(20, Style::default(), &settings); 1011 let text = tree.to_text(20, Style::default(), &settings, &info);
943 assert_eq!(text.lines, vec![Line::from(vec![ 1012 assert_eq!(text.lines, vec![Line::from(vec![
944 Span::styled("Bold", bold), 1013 Span::styled("Bold", bold),
945 Span::styled("!", bold), 1014 Span::styled("!", bold),
@@ -948,7 +1017,7 @@ pub mod tests {
948 1017
949 let s = "<strong>Bold!</strong>"; 1018 let s = "<strong>Bold!</strong>";
950 let tree = parse_matrix_html(s); 1019 let tree = parse_matrix_html(s);
951 let text = tree.to_text(20, Style::default(), &settings); 1020 let text = tree.to_text(20, Style::default(), &settings, &info);
952 assert_eq!(text.lines, vec![Line::from(vec![ 1021 assert_eq!(text.lines, vec![Line::from(vec![
953 Span::styled("Bold", bold), 1022 Span::styled("Bold", bold),
954 Span::styled("!", bold), 1023 Span::styled("!", bold),
@@ -957,7 +1026,7 @@ pub mod tests {
957 1026
958 let s = "<i>Italic!</i>"; 1027 let s = "<i>Italic!</i>";
959 let tree = parse_matrix_html(s); 1028 let tree = parse_matrix_html(s);
960 let text = tree.to_text(20, Style::default(), &settings); 1029 let text = tree.to_text(20, Style::default(), &settings, &info);
961 assert_eq!(text.lines, vec![Line::from(vec![ 1030 assert_eq!(text.lines, vec![Line::from(vec![
962 Span::styled("Italic", italic), 1031 Span::styled("Italic", italic),
963 Span::styled("!", italic), 1032 Span::styled("!", italic),
@@ -966,7 +1035,7 @@ pub mod tests {
966 1035
967 let s = "<em>Italic!</em>"; 1036 let s = "<em>Italic!</em>";
968 let tree = parse_matrix_html(s); 1037 let tree = parse_matrix_html(s);
969 let text = tree.to_text(20, Style::default(), &settings); 1038 let text = tree.to_text(20, Style::default(), &settings, &info);
970 assert_eq!(text.lines, vec![Line::from(vec![ 1039 assert_eq!(text.lines, vec![Line::from(vec![
971 Span::styled("Italic", italic), 1040 Span::styled("Italic", italic),
972 Span::styled("!", italic), 1041 Span::styled("!", italic),
@@ -975,7 +1044,7 @@ pub mod tests {
975 1044
976 let s = "<del>Strikethrough!</del>"; 1045 let s = "<del>Strikethrough!</del>";
977 let tree = parse_matrix_html(s); 1046 let tree = parse_matrix_html(s);
978 let text = tree.to_text(20, Style::default(), &settings); 1047 let text = tree.to_text(20, Style::default(), &settings, &info);
979 assert_eq!(text.lines, vec![Line::from(vec![ 1048 assert_eq!(text.lines, vec![Line::from(vec![
980 Span::styled("Strikethrough", strike), 1049 Span::styled("Strikethrough", strike),
981 Span::styled("!", strike), 1050 Span::styled("!", strike),
@@ -984,7 +1053,7 @@ pub mod tests {
984 1053
985 let s = "<strike>Strikethrough!</strike>"; 1054 let s = "<strike>Strikethrough!</strike>";
986 let tree = parse_matrix_html(s); 1055 let tree = parse_matrix_html(s);
987 let text = tree.to_text(20, Style::default(), &settings); 1056 let text = tree.to_text(20, Style::default(), &settings, &info);
988 assert_eq!(text.lines, vec![Line::from(vec![ 1057 assert_eq!(text.lines, vec![Line::from(vec![
989 Span::styled("Strikethrough", strike), 1058 Span::styled("Strikethrough", strike),
990 Span::styled("!", strike), 1059 Span::styled("!", strike),
@@ -993,7 +1062,7 @@ pub mod tests {
993 1062
994 let s = "<u>Underline!</u>"; 1063 let s = "<u>Underline!</u>";
995 let tree = parse_matrix_html(s); 1064 let tree = parse_matrix_html(s);
996 let text = tree.to_text(20, Style::default(), &settings); 1065 let text = tree.to_text(20, Style::default(), &settings, &info);
997 assert_eq!(text.lines, vec![Line::from(vec![ 1066 assert_eq!(text.lines, vec![Line::from(vec![
998 Span::styled("Underline", underl), 1067 Span::styled("Underline", underl),
999 Span::styled("!", underl), 1068 Span::styled("!", underl),
@@ -1002,7 +1071,7 @@ pub mod tests {
1002 1071
1003 let s = "<font color=\"#ff0000\">Red!</u>"; 1072 let s = "<font color=\"#ff0000\">Red!</u>";
1004 let tree = parse_matrix_html(s); 1073 let tree = parse_matrix_html(s);
1005 let text = tree.to_text(20, Style::default(), &settings); 1074 let text = tree.to_text(20, Style::default(), &settings, &info);
1006 assert_eq!(text.lines, vec![Line::from(vec![ 1075 assert_eq!(text.lines, vec![Line::from(vec![
1007 Span::styled("Red", red), 1076 Span::styled("Red", red),
1008 Span::styled("!", red), 1077 Span::styled("!", red),
@@ -1011,7 +1080,7 @@ pub mod tests {
1011 1080
1012 let s = "<font color=\"red\">Red!</u>"; 1081 let s = "<font color=\"red\">Red!</u>";
1013 let tree = parse_matrix_html(s); 1082 let tree = parse_matrix_html(s);
1014 let text = tree.to_text(20, Style::default(), &settings); 1083 let text = tree.to_text(20, Style::default(), &settings, &info);
1015 assert_eq!(text.lines, vec![Line::from(vec![ 1084 assert_eq!(text.lines, vec![Line::from(vec![
1016 Span::styled("Red", red), 1085 Span::styled("Red", red),
1017 Span::styled("!", red), 1086 Span::styled("!", red),
@@ -1021,10 +1090,11 @@ pub mod tests {
1021 1090
1022 #[test] 1091 #[test]
1023 fn test_paragraph() { 1092 fn test_paragraph() {
1093 let info = mock_room();
1024 let settings = mock_settings(); 1094 let settings = mock_settings();
1025 let s = "<p>Hello world!</p><p>Content</p><p>Goodbye world!</p>"; 1095 let s = "<p>Hello world!</p><p>Content</p><p>Goodbye world!</p>";
1026 let tree = parse_matrix_html(s); 1096 let tree = parse_matrix_html(s);
1027 let text = tree.to_text(10, Style::default(), &settings); 1097 let text = tree.to_text(10, Style::default(), &settings, &info);
1028 assert_eq!(text.lines.len(), 7); 1098 assert_eq!(text.lines.len(), 7);
1029 assert_eq!( 1099 assert_eq!(
1030 text.lines[0], 1100 text.lines[0],
@@ -1049,10 +1119,11 @@ pub mod tests {
1049 1119
1050 #[test] 1120 #[test]
1051 fn test_blockquote() { 1121 fn test_blockquote() {
1122 let info = mock_room();
1052 let settings = mock_settings(); 1123 let settings = mock_settings();
1053 let s = "<blockquote>Hello world!</blockquote>"; 1124 let s = "<blockquote>Hello world!</blockquote>";
1054 let tree = parse_matrix_html(s); 1125 let tree = parse_matrix_html(s);
1055 let text = tree.to_text(10, Style::default(), &settings); 1126 let text = tree.to_text(10, Style::default(), &settings, &info);
1056 let style = Style::new().fg(QUOTE_COLOR); 1127 let style = Style::new().fg(QUOTE_COLOR);
1057 assert_eq!(text.lines.len(), 2); 1128 assert_eq!(text.lines.len(), 2);
1058 assert_eq!( 1129 assert_eq!(
@@ -1081,10 +1152,11 @@ pub mod tests {
1081 1152
1082 #[test] 1153 #[test]
1083 fn test_list_unordered() { 1154 fn test_list_unordered() {
1155 let info = mock_room();
1084 let settings = mock_settings(); 1156 let settings = mock_settings();
1085 let s = "<ul><li>List Item 1</li><li>List Item 2</li><li>List Item 3</li></ul>"; 1157 let s = "<ul><li>List Item 1</li><li>List Item 2</li><li>List Item 3</li></ul>";
1086 let tree = parse_matrix_html(s); 1158 let tree = parse_matrix_html(s);
1087 let text = tree.to_text(8, Style::default(), &settings); 1159 let text = tree.to_text(8, Style::default(), &settings, &info);
1088 assert_eq!(text.lines.len(), 6); 1160 assert_eq!(text.lines.len(), 6);
1089 assert_eq!( 1161 assert_eq!(
1090 text.lines[0], 1162 text.lines[0],
@@ -1144,10 +1216,11 @@ pub mod tests {
1144 1216
1145 #[test] 1217 #[test]
1146 fn test_list_ordered() { 1218 fn test_list_ordered() {
1219 let info = mock_room();
1147 let settings = mock_settings(); 1220 let settings = mock_settings();
1148 let s = "<ol><li>List Item 1</li><li>List Item 2</li><li>List Item 3</li></ol>"; 1221 let s = "<ol><li>List Item 1</li><li>List Item 2</li><li>List Item 3</li></ol>";
1149 let tree = parse_matrix_html(s); 1222 let tree = parse_matrix_html(s);
1150 let text = tree.to_text(9, Style::default(), &settings); 1223 let text = tree.to_text(9, Style::default(), &settings, &info);
1151 assert_eq!(text.lines.len(), 6); 1224 assert_eq!(text.lines.len(), 6);
1152 assert_eq!( 1225 assert_eq!(
1153 text.lines[0], 1226 text.lines[0],
@@ -1207,6 +1280,7 @@ pub mod tests {
1207 1280
1208 #[test] 1281 #[test]
1209 fn test_table() { 1282 fn test_table() {
1283 let info = mock_room();
1210 let settings = mock_settings(); 1284 let settings = mock_settings();
1211 let s = "<table>\ 1285 let s = "<table>\
1212 <thead>\ 1286 <thead>\
@@ -1218,7 +1292,7 @@ pub mod tests {
1218 <tr><td>a</td><td>b</td><td>c</td></tr>\ 1292 <tr><td>a</td><td>b</td><td>c</td></tr>\
1219 </tbody></table>"; 1293 </tbody></table>";
1220 let tree = parse_matrix_html(s); 1294 let tree = parse_matrix_html(s);
1221 let text = tree.to_text(15, Style::default(), &settings); 1295 let text = tree.to_text(15, Style::default(), &settings, &info);
1222 let bold = Style::default().add_modifier(StyleModifier::BOLD); 1296 let bold = Style::default().add_modifier(StyleModifier::BOLD);
1223 assert_eq!(text.lines.len(), 11); 1297 assert_eq!(text.lines.len(), 11);
1224 1298
@@ -1308,11 +1382,12 @@ pub mod tests {
1308 1382
1309 #[test] 1383 #[test]
1310 fn test_matrix_reply_stripped() { 1384 fn test_matrix_reply_stripped() {
1385 let info = mock_room();
1311 let settings = mock_settings(); 1386 let settings = mock_settings();
1312 let s = "<mx-reply>This was replied to</mx-reply>This is the reply"; 1387 let s = "<mx-reply>This was replied to</mx-reply>This is the reply";
1313 1388
1314 let tree = parse_matrix_html(s); 1389 let tree = parse_matrix_html(s);
1315 let text = tree.to_text(10, Style::default(), &settings); 1390 let text = tree.to_text(10, Style::default(), &settings, &info);
1316 assert_eq!(text.lines.len(), 2); 1391 assert_eq!(text.lines.len(), 2);
1317 assert_eq!( 1392 assert_eq!(
1318 text.lines[0], 1393 text.lines[0],
@@ -1337,10 +1412,11 @@ pub mod tests {
1337 1412
1338 #[test] 1413 #[test]
1339 fn test_self_closing() { 1414 fn test_self_closing() {
1415 let info = mock_room();
1340 let settings = mock_settings(); 1416 let settings = mock_settings();
1341 let s = "Hello<br>World<br>Goodbye"; 1417 let s = "Hello<br>World<br>Goodbye";
1342 let tree = parse_matrix_html(s); 1418 let tree = parse_matrix_html(s);
1343 let text = tree.to_text(7, Style::default(), &settings); 1419 let text = tree.to_text(7, Style::default(), &settings, &info);
1344 assert_eq!(text.lines.len(), 3); 1420 assert_eq!(text.lines.len(), 3);
1345 assert_eq!(text.lines[0], Line::from(vec![Span::raw("Hello"), Span::raw(" "),])); 1421 assert_eq!(text.lines[0], Line::from(vec![Span::raw("Hello"), Span::raw(" "),]));
1346 assert_eq!(text.lines[1], Line::from(vec![Span::raw("World"), Span::raw(" "),])); 1422 assert_eq!(text.lines[1], Line::from(vec![Span::raw("World"), Span::raw(" "),]));
@@ -1349,10 +1425,11 @@ pub mod tests {
1349 1425
1350 #[test] 1426 #[test]
1351 fn test_embedded_newline() { 1427 fn test_embedded_newline() {
1428 let info = mock_room();
1352 let settings = mock_settings(); 1429 let settings = mock_settings();
1353 let s = "<p>Hello\nWorld</p>"; 1430 let s = "<p>Hello\nWorld</p>";
1354 let tree = parse_matrix_html(s); 1431 let tree = parse_matrix_html(s);
1355 let text = tree.to_text(15, Style::default(), &settings); 1432 let text = tree.to_text(15, Style::default(), &settings, &info);
1356 assert_eq!(text.lines.len(), 1); 1433 assert_eq!(text.lines.len(), 1);
1357 assert_eq!( 1434 assert_eq!(
1358 text.lines[0], 1435 text.lines[0],
@@ -1367,6 +1444,7 @@ pub mod tests {
1367 1444
1368 #[test] 1445 #[test]
1369 fn test_pre_tag() { 1446 fn test_pre_tag() {
1447 let info = mock_room();
1370 let settings = mock_settings(); 1448 let settings = mock_settings();
1371 let s = concat!( 1449 let s = concat!(
1372 "<pre><code class=\"language-rust\">", 1450 "<pre><code class=\"language-rust\">",
@@ -1377,7 +1455,7 @@ pub mod tests {
1377 "</code></pre>\n" 1455 "</code></pre>\n"
1378 ); 1456 );
1379 let tree = parse_matrix_html(s); 1457 let tree = parse_matrix_html(s);
1380 let text = tree.to_text(25, Style::default(), &settings); 1458 let text = tree.to_text(25, Style::default(), &settings, &info);
1381 assert_eq!(text.lines.len(), 6); 1459 assert_eq!(text.lines.len(), 6);
1382 assert_eq!( 1460 assert_eq!(
1383 text.lines[0], 1461 text.lines[0],
@@ -1455,6 +1533,7 @@ pub mod tests {
1455 1533
1456 #[test] 1534 #[test]
1457 fn test_emoji_shortcodes() { 1535 fn test_emoji_shortcodes() {
1536 let info = mock_room();
1458 let mut enabled = mock_settings(); 1537 let mut enabled = mock_settings();
1459 enabled.tunables.message_shortcode_display = true; 1538 enabled.tunables.message_shortcode_display = true;
1460 let mut disabled = mock_settings(); 1539 let mut disabled = mock_settings();
@@ -1468,13 +1547,13 @@ pub mod tests {
1468 let s = format!("<p>{emoji}</p>"); 1547 let s = format!("<p>{emoji}</p>");
1469 let tree = parse_matrix_html(s.as_str()); 1548 let tree = parse_matrix_html(s.as_str());
1470 // Test with emojis_shortcodes set to false 1549 // Test with emojis_shortcodes set to false
1471 let text = tree.to_text(20, Style::default(), &disabled); 1550 let text = tree.to_text(20, Style::default(), &disabled, &info);
1472 assert_eq!(text.lines, vec![Line::from(vec![ 1551 assert_eq!(text.lines, vec![Line::from(vec![
1473 Span::raw(emoji), 1552 Span::raw(emoji),
1474 space_span(20 - emoji_width, Style::default()), 1553 space_span(20 - emoji_width, Style::default()),
1475 ]),]); 1554 ]),]);
1476 // Test with emojis_shortcodes set to true 1555 // Test with emojis_shortcodes set to true
1477 let text = tree.to_text(20, Style::default(), &enabled); 1556 let text = tree.to_text(20, Style::default(), &enabled, &info);
1478 assert_eq!(text.lines, vec![Line::from(vec![ 1557 assert_eq!(text.lines, vec![Line::from(vec![
1479 Span::raw(replacement.as_str()), 1558 Span::raw(replacement.as_str()),
1480 space_span(20 - replacement_width, Style::default()), 1559 space_span(20 - replacement_width, Style::default()),
src/message/mod.rs +51 −9
@@ -644,6 +644,7 @@ enum SenderSpan<'a> {
644 644
645struct MessageFormatter<'a> { 645struct MessageFormatter<'a> {
646 settings: &'a ApplicationSettings, 646 settings: &'a ApplicationSettings,
647 info: &'a RoomInfo,
647 648
648 /// How many columns to print. 649 /// How many columns to print.
649 cols: MessageColumns, 650 cols: MessageColumns,
@@ -781,7 +782,7 @@ impl<'a> MessageFormatter<'a> {
781 782
782 let width = self.width(); 783 let width = self.width();
783 let w = width.saturating_sub(2); 784 let w = width.saturating_sub(2);
784 let (mut replied, proto) = msg.show_msg(w, reply_style, settings, previews); 785 let (mut replied, proto) = msg.show_msg(w, reply_style, settings, previews, info);
785 let mut sender = msg.sender_span(info, self.settings); 786 let mut sender = msg.sender_span(info, self.settings);
786 let sender_width = UnicodeWidthStr::width(sender.content.as_ref()); 787 let sender_width = UnicodeWidthStr::width(sender.content.as_ref());
787 let trailing = w.saturating_sub(sender_width + 1); 788 let trailing = w.saturating_sub(sender_width + 1);
@@ -826,7 +827,7 @@ impl<'a> MessageFormatter<'a> {
826 settings: &ApplicationSettings, 827 settings: &ApplicationSettings,
827 previews: &'a PreviewManager, 828 previews: &'a PreviewManager,
828 ) -> Vec<ProtocolPreview<'a>> { 829 ) -> Vec<ProtocolPreview<'a>> {
829 let mut emojis = printer::TextPrinter::new(self.width(), style, self.settings); 830 let mut emojis = printer::TextPrinter::new(self.width(), style, self.settings, self.info);
830 let mut reactions = 0; 831 let mut reactions = 0;
831 let mut protos = Vec::new(); 832 let mut protos = Vec::new();
832 833
@@ -898,7 +899,7 @@ impl<'a> MessageFormatter<'a> {
898 let plural = len != 1; 899 let plural = len != 1;
899 let style = Style::default(); 900 let style = Style::default();
900 let mut threaded = 901 let mut threaded =
901 printer::TextPrinter::new(self.width(), style, self.settings).literal(true); 902 printer::TextPrinter::new(self.width(), style, self.settings, self.info).literal(true);
902 let len = Span::styled(len.to_string(), style.add_modifier(StyleModifier::BOLD)); 903 let len = Span::styled(len.to_string(), style.add_modifier(StyleModifier::BOLD));
903 threaded.push_str(" \u{2937} ", style); 904 threaded.push_str(" \u{2937} ", style);
904 threaded.push_span_nobreak(len); 905 threaded.push_span_nobreak(len);
@@ -1064,7 +1065,17 @@ impl Message {
1064 .map(|user_id| user_id.to_owned()) 1065 .map(|user_id| user_id.to_owned())
1065 .collect(); 1066 .collect();
1066 1067
1067 MessageFormatter { settings, cols, orig, fill, user, date, time, read } 1068 MessageFormatter {
1069 settings,
1070 cols,
1071 orig,
1072 fill,
1073 user,
1074 date,
1075 time,
1076 read,
1077 info,
1078 }
1068 } else if user_gutter + TIME_GUTTER + MIN_MSG_LEN <= width { 1079 } else if user_gutter + TIME_GUTTER + MIN_MSG_LEN <= width {
1069 let cols = MessageColumns::Three; 1080 let cols = MessageColumns::Three;
1070 let fill = width - user_gutter - TIME_GUTTER; 1081 let fill = width - user_gutter - TIME_GUTTER;
@@ -1072,7 +1083,17 @@ impl Message {
1072 let time = Some(self.timestamp.show_time()); 1083 let time = Some(self.timestamp.show_time());
1073 let read = Vec::new(); 1084 let read = Vec::new();
1074 1085
1075 MessageFormatter { settings, cols, orig, fill, user, date, time, read } 1086 MessageFormatter {
1087 settings,
1088 cols,
1089 orig,
1090 fill,
1091 user,
1092 date,
1093 time,
1094 read,
1095 info,
1096 }
1076 } else if user_gutter + MIN_MSG_LEN <= width { 1097 } else if user_gutter + MIN_MSG_LEN <= width {
1077 let cols = MessageColumns::Two; 1098 let cols = MessageColumns::Two;
1078 let fill = width - user_gutter; 1099 let fill = width - user_gutter;
@@ -1080,7 +1101,17 @@ impl Message {
1080 let time = None; 1101 let time = None;
1081 let read = Vec::new(); 1102 let read = Vec::new();
1082 1103
1083 MessageFormatter { settings, cols, orig, fill, user, date, time, read } 1104 MessageFormatter {
1105 settings,
1106 cols,
1107 orig,
1108 fill,
1109 user,
1110 date,
1111 time,
1112 read,
1113 info,
1114 }
1084 } else { 1115 } else {
1085 let cols = MessageColumns::One; 1116 let cols = MessageColumns::One;
1086 let fill = width.saturating_sub(2); 1117 let fill = width.saturating_sub(2);
@@ -1088,7 +1119,17 @@ impl Message {
1088 let time = None; 1119 let time = None;
1089 let read = Vec::new(); 1120 let read = Vec::new();
1090 1121
1091 MessageFormatter { settings, cols, orig, fill, user, date, time, read } 1122 MessageFormatter {
1123 settings,
1124 cols,
1125 orig,
1126 fill,
1127 user,
1128 date,
1129 time,
1130 read,
1131 info,
1132 }
1092 } 1133 }
1093 } 1134 }
1094 1135
@@ -1137,7 +1178,7 @@ impl Message {
1137 } 1178 }
1138 1179
1139 // Now show the message contents, and the inlined reply if we couldn't find it above. 1180 // Now show the message contents, and the inlined reply if we couldn't find it above.
1140 let (msg, proto) = self.show_msg(width, style, settings, previews); 1181 let (msg, proto) = self.show_msg(width, style, settings, previews, info);
1141 1182
1142 // Given our text so far, determine the image offset. 1183 // Given our text so far, determine the image offset.
1143 if let Some(p) = proto { 1184 if let Some(p) = proto {
@@ -1199,6 +1240,7 @@ impl Message {
1199 style: Style, 1240 style: Style,
1200 settings: &'a ApplicationSettings, 1241 settings: &'a ApplicationSettings,
1201 previews: &'a PreviewManager, 1242 previews: &'a PreviewManager,
1243 info: &'a RoomInfo,
1202 ) -> (Text<'a>, Option<&'a SlicedProtocol>) { 1244 ) -> (Text<'a>, Option<&'a SlicedProtocol>) {
1203 let mut proto = None; 1245 let mut proto = None;
1204 let placeholder = match self 1246 let placeholder = match self
@@ -1234,7 +1276,7 @@ impl Message {
1234 } 1276 }
1235 1277
1236 if let Some(html) = &self.html { 1278 if let Some(html) = &self.html {
1237 text += html.to_text(width, style, settings); 1279 text += html.to_text(width, style, settings, info);
1238 } else { 1280 } else {
1239 let mut msg = self.event.body(); 1281 let mut msg = self.event.body();
1240 if settings.tunables.message_shortcode_display { 1282 if settings.tunables.message_shortcode_display {
src/message/printer.rs +13 −3
@@ -4,6 +4,7 @@
4//! lines to make concatenation work right (e.g., combining table cells after wrapping their 4//! lines to make concatenation work right (e.g., combining table cells after wrapping their
5//! contents). 5//! contents).
6 6
7use crate::base::RoomInfo;
7use crate::config::TunableValues; 8use crate::config::TunableValues;
8use crate::prelude::*; 9use crate::prelude::*;
9use crate::util::{ 10use crate::util::{
@@ -26,11 +27,17 @@ pub struct TextPrinter<'a> {
26 literal: bool, 27 literal: bool,
27 28
28 pub(super) settings: &'a ApplicationSettings, 29 pub(super) settings: &'a ApplicationSettings,
30 pub(super) info: &'a RoomInfo,
29} 31}
30 32
31impl<'a> TextPrinter<'a> { 33impl<'a> TextPrinter<'a> {
32 /// Create a new printer. 34 /// Create a new printer.
33 pub fn new(width: usize, base_style: Style, settings: &'a ApplicationSettings) -> Self { 35 pub fn new(
36 width: usize,
37 base_style: Style,
38 settings: &'a ApplicationSettings,
39 info: &'a RoomInfo,
40 ) -> Self {
34 TextPrinter { 41 TextPrinter {
35 text: Text::default(), 42 text: Text::default(),
36 width, 43 width,
@@ -41,6 +48,7 @@ impl<'a> TextPrinter<'a> {
41 curr_width: 0, 48 curr_width: 0,
42 literal: false, 49 literal: false,
43 settings, 50 settings,
51 info,
44 } 52 }
45 } 53 }
46 54
@@ -91,6 +99,7 @@ impl<'a> TextPrinter<'a> {
91 curr_width: 0, 99 curr_width: 0,
92 literal: self.literal, 100 literal: self.literal,
93 settings: self.settings, 101 settings: self.settings,
102 info: self.info,
94 } 103 }
95 } 104 }
96 105
@@ -290,12 +299,13 @@ impl<'a> TextPrinter<'a> {
290pub mod tests { 299pub mod tests {
291 use super::*; 300 use super::*;
292 301
293 use crate::tests::mock_settings; 302 use crate::tests::{mock_room, mock_settings};
294 303
295 #[test] 304 #[test]
296 fn test_push_nobreak() { 305 fn test_push_nobreak() {
297 let settings = mock_settings(); 306 let settings = mock_settings();
298 let mut printer = TextPrinter::new(5, Style::default(), &settings); 307 let info = mock_room();
308 let mut printer = TextPrinter::new(5, Style::default(), &settings, &info);
299 printer.push_span_nobreak("hello world".into()); 309 printer.push_span_nobreak("hello world".into());
300 let text = printer.finish(); 310 let text = printer.finish();
301 assert_eq!(text.lines.len(), 1); 311 assert_eq!(text.lines.len(), 1);
src/message/state.rs +22 −9
@@ -3,6 +3,7 @@
3use matrix_sdk::ruma::events::room::member::MembershipChange; 3use matrix_sdk::ruma::events::room::member::MembershipChange;
4use matrix_sdk::ruma::events::{AnyStateEventContentChange, StateEventContentChange}; 4use matrix_sdk::ruma::events::{AnyStateEventContentChange, StateEventContentChange};
5 5
6use crate::message::TreeGenState;
6use crate::message::html::{StyleTree, StyleTreeNode}; 7use crate::message::html::{StyleTree, StyleTreeNode};
7use crate::prelude::*; 8use crate::prelude::*;
8 9
@@ -510,7 +511,7 @@ pub fn html_state(ev: &AnySyncStateEvent) -> StyleTree {
510 .. 511 ..
511 }) => { 512 }) => {
512 if let Some(canon) = content.alias.as_ref() { 513 if let Some(canon) = content.alias.as_ref() {
513 let canon = StyleTreeNode::RoomAlias(canon.to_owned()); 514 let canon = StyleTreeNode::RoomAlias(canon.to_owned(), Some('0'));
514 let prefix = 515 let prefix =
515 StyleTreeNode::Text("* updated the canonical alias for the room to: ".into()); 516 StyleTreeNode::Text("* updated the canonical alias for the room to: ".into());
516 vec![prefix, canon] 517 vec![prefix, canon]
@@ -577,7 +578,7 @@ pub fn html_state(ev: &AnySyncStateEvent) -> StyleTree {
577 578
578 let prev_details = prev_content.as_ref().map(|p| p.details()); 579 let prev_details = prev_content.as_ref().map(|p| p.details());
579 let change = content.membership_change(prev_details, ev.sender(), &state_key); 580 let change = content.membership_change(prev_details, ev.sender(), &state_key);
580 let user_id = StyleTreeNode::UserId(state_key.clone()); 581 let user_id = StyleTreeNode::UserId(state_key.clone(), Some('0'));
581 582
582 match change { 583 match change {
583 MembershipChange::None => { 584 MembershipChange::None => {
@@ -656,7 +657,11 @@ pub fn html_state(ev: &AnySyncStateEvent) -> StyleTree {
656 (None, Some(new)) => { 657 (None, Some(new)) => {
657 vec![ 658 vec![
658 StyleTreeNode::Text("* set their display name to ".into()), 659 StyleTreeNode::Text("* set their display name to ".into()),
659 StyleTreeNode::DisplayName(new.into(), state_key), 660 StyleTreeNode::DisplayName(
661 new.into(),
662 state_key,
663 Some('0'),
664 ),
660 ] 665 ]
661 }, 666 },
662 (Some(old), Some(new)) => { 667 (Some(old), Some(new)) => {
@@ -664,9 +669,13 @@ pub fn html_state(ev: &AnySyncStateEvent) -> StyleTree {
664 StyleTreeNode::Text( 669 StyleTreeNode::Text(
665 "* changed their display name from ".into(), 670 "* changed their display name from ".into(),
666 ), 671 ),
667 StyleTreeNode::DisplayName(old.into(), state_key.clone()), 672 StyleTreeNode::DisplayName(
673 old.into(),
674 state_key.clone(),
675 Some('0'),
676 ),
668 StyleTreeNode::Text(" to ".into()), 677 StyleTreeNode::Text(" to ".into()),
669 StyleTreeNode::DisplayName(new.into(), state_key), 678 StyleTreeNode::DisplayName(new.into(), state_key, None),
670 ] 679 ]
671 }, 680 },
672 (Some(_), None) => { 681 (Some(_), None) => {
@@ -759,7 +768,7 @@ pub fn html_state(ev: &AnySyncStateEvent) -> StyleTree {
759 .. 768 ..
760 }) => { 769 }) => {
761 let prefix = StyleTreeNode::Text("* upgraded the room; replacement room is ".into()); 770 let prefix = StyleTreeNode::Text("* upgraded the room; replacement room is ".into());
762 let room = StyleTreeNode::RoomId(content.replacement_room.clone()); 771 let room = StyleTreeNode::RoomId(content.replacement_room.clone(), vec![], Some('0'));
763 vec![prefix, room] 772 vec![prefix, room]
764 }, 773 },
765 AnyStateEventContentChange::RoomTopic(StateEventContentChange::Original { 774 AnyStateEventContentChange::RoomTopic(StateEventContentChange::Original {
@@ -774,7 +783,7 @@ pub fn html_state(ev: &AnySyncStateEvent) -> StyleTree {
774 let prefix = StyleTreeNode::Text("* added a space child: ".into()); 783 let prefix = StyleTreeNode::Text("* added a space child: ".into());
775 784
776 let room_id = if let Ok(room_id) = OwnedRoomId::from_str(ev.state_key()) { 785 let room_id = if let Ok(room_id) = OwnedRoomId::from_str(ev.state_key()) {
777 StyleTreeNode::RoomId(room_id) 786 StyleTreeNode::RoomId(room_id, vec![], Some('0'))
778 } else { 787 } else {
779 bold(ev.state_key().to_string()) 788 bold(ev.state_key().to_string())
780 }; 789 };
@@ -792,7 +801,7 @@ pub fn html_state(ev: &AnySyncStateEvent) -> StyleTree {
792 }; 801 };
793 802
794 let room_id = if let Ok(room_id) = OwnedRoomId::from_str(ev.state_key()) { 803 let room_id = if let Ok(room_id) = OwnedRoomId::from_str(ev.state_key()) {
795 StyleTreeNode::RoomId(room_id) 804 StyleTreeNode::RoomId(room_id, vec![], Some('0'))
796 } else { 805 } else {
797 bold(ev.state_key().to_string()) 806 bold(ev.state_key().to_string())
798 }; 807 };
@@ -816,12 +825,16 @@ pub fn html_state(ev: &AnySyncStateEvent) -> StyleTree {
816 ); 825 );
817 let mut cs = vec![prefix]; 826 let mut cs = vec![prefix];
818 827
828 let mut state = TreeGenState { link_num: 0 };
829
819 for (i, member) in content.service_members.iter().enumerate() { 830 for (i, member) in content.service_members.iter().enumerate() {
820 if i != 0 { 831 if i != 0 {
821 cs.push(StyleTreeNode::Text(", ".into())); 832 cs.push(StyleTreeNode::Text(", ".into()));
822 } 833 }
823 834
824 cs.push(StyleTreeNode::UserId(member.clone())); 835 let c = state.next_link_char();
836
837 cs.push(StyleTreeNode::UserId(member.clone(), c));
825 } 838 }
826 839
827 cs 840 cs
src/prelude.rs +3
@@ -20,8 +20,11 @@ pub use matrix_sdk::ruma::events::room::message::{
20 RoomMessageEventContent, 20 RoomMessageEventContent,
21}; 21};
22pub use matrix_sdk::ruma::events::tag::{TagName, Tags}; 22pub use matrix_sdk::ruma::events::tag::{TagName, Tags};
23pub use matrix_sdk::ruma::matrix_uri::MatrixId;
23pub use matrix_sdk::ruma::{ 24pub use matrix_sdk::ruma::{
24 EventId, 25 EventId,
26 MatrixToUri,
27 MatrixUri,
25 MilliSecondsSinceUnixEpoch, 28 MilliSecondsSinceUnixEpoch,
26 OwnedEventId, 29 OwnedEventId,
27 OwnedRoomAliasId, 30 OwnedRoomAliasId,
src/tests.rs +9 −4
@@ -1,8 +1,9 @@
1use std::iter::FromIterator as _; 1use std::iter::FromIterator as _;
2 2
3use lazy_static::lazy_static; 3use lazy_static::lazy_static;
4use matrix_sdk::ruma::assign; 4use matrix_sdk::ruma::events::room::message::RoomMessageEventContent;
5use matrix_sdk::ruma::{UInt, event_id, server_name, user_id}; 5use matrix_sdk::ruma::{UInt, event_id, server_name, user_id};
6use matrix_sdk::ruma::{assign, owned_room_alias_id};
6use serde_json::{Map, Value}; 7use serde_json::{Map, Value};
7use tokio::sync::mpsc::unbounded_channel; 8use tokio::sync::mpsc::unbounded_channel;
8 9
@@ -10,9 +11,8 @@ use crate::base::EventLocation;
10use crate::config::*; 11use crate::config::*;
11use crate::prelude::*; 12use crate::prelude::*;
12 13
13const TEST_ROOM1_ALIAS: &str = "#room1:example.com";
14
15lazy_static! { 14lazy_static! {
15 pub static ref TEST_ROOM1_ALIAS: OwnedRoomAliasId = owned_room_alias_id!("#room1:example.com");
16 pub static ref TEST_ROOM1_ID: OwnedRoomId = 16 pub static ref TEST_ROOM1_ID: OwnedRoomId =
17 RoomId::new_v1(server_name!("example.com")).to_owned(); 17 RoomId::new_v1(server_name!("example.com")).to_owned();
18 pub static ref TEST_USER1: OwnedUserId = user_id!("@user1:example.com").to_owned(); 18 pub static ref TEST_USER1: OwnedUserId = user_id!("@user1:example.com").to_owned();
@@ -134,6 +134,11 @@ pub fn mock_room() -> RoomInfo {
134 room.name = Some("Watercooler Discussion".into()); 134 room.name = Some("Watercooler Discussion".into());
135 room.keys = mock_keys(); 135 room.keys = mock_keys();
136 *room.get_thread_mut(None) = mock_messages(); 136 *room.get_thread_mut(None) = mock_messages();
137
138 let user_id = TEST_USER2.clone();
139 let name = "User 2";
140 room.display_names.set(user_id.clone(), Some(name.to_string()), true);
141
137 room 142 room
138} 143}
139 144
@@ -248,7 +253,7 @@ pub async fn mock_store() -> ProgramStore {
248 let info = mock_room(); 253 let info = mock_room();
249 254
250 store.rooms.insert(room_id.clone(), info); 255 store.rooms.insert(room_id.clone(), info);
251 store.names.insert(TEST_ROOM1_ALIAS.to_string(), room_id); 256 store.names.insert(TEST_ROOM1_ALIAS.clone(), room_id);
252 257
253 ProgramStore::new(store) 258 ProgramStore::new(store)
254} 259}
src/windows/mod.rs +8 −5
@@ -912,8 +912,11 @@ impl Window<IambInfo> for IambWindow {
912 912
913 IambWindow::open(id, store) 913 IambWindow::open(id, store)
914 } else { 914 } else {
915 let room_id = worker.join_room(name.clone())?; 915 let room_id = worker.join_room(name.clone(), vec![])?;
916 names.insert(name, room_id.clone()); 916
917 if let Ok(alias) = OwnedRoomAliasId::from_str(&name) {
918 names.insert(alias, room_id.clone());
919 }
917 920
918 let (room, name, tags) = store.application.worker.get_room(room_id)?; 921 let (room, name, tags) = store.application.worker.get_room(room_id)?;
919 let room = RoomState::new(room, None, name, tags, store); 922 let room = RoomState::new(room, None, name, tags, store);
@@ -956,7 +959,7 @@ impl GenericChatItem {
956 info.tags.clone_from(&room_info.deref().1); 959 info.tags.clone_from(&room_info.deref().1);
957 960
958 if let Some(alias) = &alias { 961 if let Some(alias) = &alias {
959 store.application.names.insert(alias.to_string(), room_id.to_owned()); 962 store.application.names.insert(alias.to_owned(), room_id.to_owned());
960 } 963 }
961 964
962 GenericChatItem { room_info, name, alias, is_dm, unread } 965 GenericChatItem { room_info, name, alias, is_dm, unread }
@@ -1079,7 +1082,7 @@ impl RoomItem {
1079 info.tags.clone_from(&room_info.deref().1); 1082 info.tags.clone_from(&room_info.deref().1);
1080 1083
1081 if let Some(alias) = &alias { 1084 if let Some(alias) = &alias {
1082 store.application.names.insert(alias.to_string(), room_id.to_owned()); 1085 store.application.names.insert(alias.to_owned(), room_id.to_owned());
1083 } 1086 }
1084 1087
1085 RoomItem { room_info, name, alias, unread } 1088 RoomItem { room_info, name, alias, unread }
@@ -1300,7 +1303,7 @@ impl SpaceItem {
1300 let alias = room_info.0.canonical_alias(); 1303 let alias = room_info.0.canonical_alias();
1301 1304
1302 if let Some(alias) = &alias { 1305 if let Some(alias) = &alias {
1303 store.application.names.insert(alias.to_string(), room_id.to_owned()); 1306 store.application.names.insert(alias.to_owned(), room_id.to_owned());
1304 } 1307 }
1305 1308
1306 SpaceItem { room_info, name, alias } 1309 SpaceItem { room_info, name, alias }
src/windows/room/chat.rs +102 −49
@@ -11,9 +11,16 @@ use matrix_sdk::attachment::AttachmentConfig;
11use matrix_sdk::attachment::{AttachmentInfo, BaseImageInfo}; 11use matrix_sdk::attachment::{AttachmentInfo, BaseImageInfo};
12use matrix_sdk::media::{MediaFormat, MediaRequestParameters}; 12use matrix_sdk::media::{MediaFormat, MediaRequestParameters};
13use matrix_sdk::room::reply::{EnforceThread, Reply}; 13use matrix_sdk::room::reply::{EnforceThread, Reply};
14use matrix_sdk::ruma::events::Mentions;
14use matrix_sdk::ruma::events::reaction::ReactionEventContent; 15use matrix_sdk::ruma::events::reaction::ReactionEventContent;
15use matrix_sdk::ruma::events::relation::{Annotation, Replacement}; 16use matrix_sdk::ruma::events::relation::Annotation;
16use matrix_sdk::ruma::events::room::message::{AddMentions, ForwardThread, ReplyWithinThread}; 17use matrix_sdk::ruma::events::room::message::{
18 AddMentions,
19 ForwardThread,
20 MessageFormat,
21 ReplyWithinThread,
22 TextMessageEventContent,
23};
17use matrix_sdk::send_queue::RoomSendQueueError; 24use matrix_sdk::send_queue::RoomSendQueueError;
18use modalkit::editing::history::{self, HistoryList}; 25use modalkit::editing::history::{self, HistoryList};
19use modalkit::editing::store::RegisterError; 26use modalkit::editing::store::RegisterError;
@@ -21,6 +28,7 @@ use modalkit::keybindings::dialog::{Dialog, MultiChoice, MultiChoiceItem};
21use modalkit_ratatui::PromptActions; 28use modalkit_ratatui::PromptActions;
22use modalkit_ratatui::textbox::{TextBox, TextBoxState}; 29use modalkit_ratatui::textbox::{TextBox, TextBoxState};
23use ratatui::prelude::Stylize; 30use ratatui::prelude::Stylize;
31use regex::Regex;
24 32
25use crate::base::{DownloadFlags, EchoLocation}; 33use crate::base::{DownloadFlags, EchoLocation};
26use crate::config::EncryptionIndicatorLocation; 34use crate::config::EncryptionIndicatorLocation;
@@ -146,15 +154,18 @@ impl ChatState {
146 Err(UIError::NeedConfirm(prompt)) 154 Err(UIError::NeedConfirm(prompt))
147 }, 155 },
148 MessageAction::Download(filename, flags) => { 156 MessageAction::Download(filename, flags) => {
157 if let MessageEvent::State(_) = &msg.event {
158 let err = open_links(msg);
159 return Err(err);
160 }
161
149 if let Some(msgtype) = msg.event.msgtype() { 162 if let Some(msgtype) = msg.event.msgtype() {
150 let media = client.media(); 163 let media = client.media();
151
152 let mut filename = match (filename, &settings.dirs.downloads) { 164 let mut filename = match (filename, &settings.dirs.downloads) {
153 (Some(f), _) => PathBuf::from(f), 165 (Some(f), _) => PathBuf::from(f),
154 (None, Some(downloads)) => downloads.clone(), 166 (None, Some(downloads)) => downloads.clone(),
155 (None, None) => return Err(IambError::NoDownloadDir.into()), 167 (None, None) => return Err(IambError::NoDownloadDir.into()),
156 }; 168 };
157
158 let (source, msg_filename) = match msgtype { 169 let (source, msg_filename) = match msgtype {
159 MessageType::Audio(c) => (c.source.clone(), c.filename()), 170 MessageType::Audio(c) => (c.source.clone(), c.filename()),
160 MessageType::File(c) => (c.source.clone(), c.filename()), 171 MessageType::File(c) => (c.source.clone(), c.filename()),
@@ -164,46 +175,13 @@ impl ChatState {
164 if !flags.contains(DownloadFlags::OPEN) { 175 if !flags.contains(DownloadFlags::OPEN) {
165 return Err(IambError::NoAttachment.into()); 176 return Err(IambError::NoAttachment.into());
166 } 177 }
167 178 let err = open_links(msg);
168 let mut links = if let Some(html) = &msg.html {
169 html.get_links()
170 } else {
171 vec![]
172 };
173
174 if links.is_empty() {
175 links = linkify::LinkFinder::new()
176 .links(&msg.event.body())
177 .filter_map(|u| Url::parse(u.as_str()).ok())
178 .scan(TreeGenState { link_num: 0 }, |state, u| {
179 state.next_link_char().map(|c| (c, u))
180 })
181 .collect();
182 }
183
184 if links.is_empty() {
185 return Err(IambError::NoAttachment.into());
186 }
187
188 let choices = links
189 .into_iter()
190 .map(|l| {
191 let url = l.1.to_string();
192 let act = IambAction::OpenLink(url.clone()).into();
193 MultiChoiceItem::new(l.0, url, vec![act])
194 })
195 .collect();
196 let dialog = MultiChoice::new(choices);
197 let err = UIError::NeedConfirm(Box::new(dialog));
198
199 return Err(err); 179 return Err(err);
200 }, 180 },
201 }; 181 };
202
203 if filename.is_dir() { 182 if filename.is_dir() {
204 filename.push(msg_filename.replace(std::path::MAIN_SEPARATOR_STR, "_")); 183 filename.push(msg_filename.replace(std::path::MAIN_SEPARATOR_STR, "_"));
205 } 184 }
206
207 if filename.exists() && !flags.contains(DownloadFlags::FORCE) { 185 if filename.exists() && !flags.contains(DownloadFlags::FORCE) {
208 // Find an incrementally suffixed filename, e.g. image-2.jpg -> image-3.jpg 186 // Find an incrementally suffixed filename, e.g. image-2.jpg -> image-3.jpg
209 if let Some(stem) = filename.file_stem().and_then(OsStr::to_str) { 187 if let Some(stem) = filename.file_stem().and_then(OsStr::to_str) {
@@ -223,7 +201,6 @@ impl ChatState {
223 } 201 }
224 } 202 }
225 } 203 }
226
227 if !filename.exists() || flags.contains(DownloadFlags::FORCE) { 204 if !filename.exists() || flags.contains(DownloadFlags::FORCE) {
228 let req = MediaRequestParameters { source, format: MediaFormat::File }; 205 let req = MediaRequestParameters { source, format: MediaFormat::File };
229 206
@@ -242,7 +219,6 @@ impl ChatState {
242 219
243 return Err(err); 220 return Err(err);
244 } 221 }
245
246 let info = if flags.contains(DownloadFlags::OPEN) { 222 let info = if flags.contains(DownloadFlags::OPEN) {
247 let target = filename.clone().into_os_string(); 223 let target = filename.clone().into_os_string();
248 match open_command( 224 match open_command(
@@ -265,7 +241,6 @@ impl ChatState {
265 filename.display() 241 filename.display()
266 )) 242 ))
267 }; 243 };
268
269 return Ok(info.into()); 244 return Ok(info.into());
270 } 245 }
271 246
@@ -545,6 +520,14 @@ impl ChatState {
545 .filter(|c| !c.is_blank()) 520 .filter(|c| !c.is_blank())
546 .map(|c| c.trim_end().to_string()) 521 .map(|c| c.trim_end().to_string())
547 .and_then(|c| text_to_text_message_event_content(c, settings.tunables.default_markup)); 522 .and_then(|c| text_to_text_message_event_content(c, settings.tunables.default_markup));
523
524 let mentions = if let Some(content) = &config.caption {
525 extract_mentions(content)
526 } else {
527 Mentions::new()
528 };
529 config.mentions = Some(mentions);
530
548 config.reply = self.generate_reply_info(info, add_caption); 531 config.reply = self.generate_reply_info(info, add_caption);
549 config 532 config
550 } 533 }
@@ -585,7 +568,14 @@ impl ChatState {
585 msg.trim_end().to_string() 568 msg.trim_end().to_string()
586 }; 569 };
587 570
588 let mut msg = text_to_message(msg, tunables.default_markup); 571 let mut msg = text_to_message(msg.into(), tunables.default_markup);
572
573 let mentions = if let MessageType::Text(content) = &msg.msgtype {
574 extract_mentions(content)
575 } else {
576 Mentions::new()
577 };
578 msg = msg.add_mentions(mentions);
589 579
590 if let Some(key) = &self.editing { 580 if let Some(key) = &self.editing {
591 let id = match &key.id { 581 let id = match &key.id {
@@ -625,20 +615,27 @@ impl ChatState {
625 }, 615 },
626 }; 616 };
627 617
628 msg.relates_to = Some(Relation::Replacement(Replacement::new( 618 let Some(edited_msg) = info.get_event(id) else {
629 id.to_owned(), 619 let msg = "edited message not found in store";
630 msg.msgtype.clone().into(), 620 return Err(UIError::Failure(msg.into()));
631 ))); 621 };
622
623 let MessageEvent::Original(edited_msg, _) = &edited_msg.event else {
624 let msg = "you can only edit normal messages";
625 return Err(UIError::Failure(msg.into()));
626 };
627
628 msg = msg.make_replacement(edited_msg.as_ref());
632 } else if let Some(thread_root) = self.scrollback.thread() { 629 } else if let Some(thread_root) = self.scrollback.thread() {
633 if let Some(m) = self.get_reply_to(info) { 630 if let Some(m) = self.get_reply_to(info) {
634 msg = msg.make_for_thread(m, ReplyWithinThread::Yes, AddMentions::No); 631 msg = msg.make_for_thread(m, ReplyWithinThread::Yes, AddMentions::Yes);
635 } else if let Some(m) = info.get_thread_last(thread_root) { 632 } else if let Some(m) = info.get_thread_last(thread_root) {
636 msg = msg.make_for_thread(m, ReplyWithinThread::No, AddMentions::No); 633 msg = msg.make_for_thread(m, ReplyWithinThread::No, AddMentions::Yes);
637 } else { 634 } else {
638 // Internal state is wonky? 635 // Internal state is wonky?
639 } 636 }
640 } else if let Some(m) = self.get_reply_to(info) { 637 } else if let Some(m) = self.get_reply_to(info) {
641 msg = msg.make_reply_to(m, ForwardThread::Yes, AddMentions::No); 638 msg = msg.make_reply_to(m, ForwardThread::Yes, AddMentions::Yes);
642 } 639 }
643 640
644 room.send_queue().send(msg.into()).await.map_err(IambError::from)?; 641 room.send_queue().send(msg.into()).await.map_err(IambError::from)?;
@@ -772,6 +769,37 @@ impl ChatState {
772 } 769 }
773} 770}
774 771
772fn open_links(msg: &Message) -> UIError<IambInfo> {
773 let mut links = if let Some(html) = &msg.html {
774 html.get_links()
775 } else {
776 vec![]
777 };
778
779 if links.is_empty() {
780 links = linkify::LinkFinder::new()
781 .links(&msg.event.body())
782 .filter_map(|u| Url::parse(u.as_str()).ok())
783 .scan(TreeGenState { link_num: 0 }, |state, u| state.next_link_char().map(|c| (c, u)))
784 .collect();
785 }
786
787 if links.is_empty() {
788 return IambError::NoAttachment.into();
789 }
790
791 let choices = links
792 .into_iter()
793 .map(|l| {
794 let url = l.1.to_string();
795 let act = IambAction::OpenLink(url.clone(), false).into();
796 MultiChoiceItem::new(l.0, url, vec![act])
797 })
798 .collect();
799 let dialog = MultiChoice::new(choices);
800 UIError::NeedConfirm(Box::new(dialog))
801}
802
775macro_rules! delegate { 803macro_rules! delegate {
776 ($s: expr, $id: ident => $e: expr) => { 804 ($s: expr, $id: ident => $e: expr) => {
777 match $s.focus { 805 match $s.focus {
@@ -1161,6 +1189,31 @@ fn open_command(open_command: Option<&Vec<String>>, target: OsString) -> IambRes
1161 } 1189 }
1162} 1190}
1163 1191
1192/// Extract mentions from `https://matrix.to` html links
1193fn extract_mentions(content: &TextMessageEventContent) -> Mentions {
1194 let Some(formatted) = content.formatted.as_ref() else {
1195 return Mentions::new();
1196 };
1197 if !matches!(formatted.format, MessageFormat::Html) {
1198 return Mentions::new();
1199 }
1200 let html = formatted.body.as_str();
1201
1202 let re = Regex::new(r#"<a href="(https://matrix.to/#/@[^"]*:[^"]*)">"#).unwrap();
1203
1204 let user_ids = re.captures_iter(html).map(|capture| {
1205 let link = capture.get(1).unwrap().as_str();
1206 let uri = MatrixToUri::parse(link).unwrap();
1207 let MatrixId::User(user_id) = uri.id() else {
1208 // we only matched user links (starting with `@`)
1209 unreachable!()
1210 };
1211 user_id.to_owned()
1212 });
1213
1214 Mentions::with_user_ids(user_ids)
1215}
1216
1164fn cmd(open_command: &Vec<String>) -> Option<Command> { 1217fn cmd(open_command: &Vec<String>) -> Option<Command> {
1165 if let [program, args @ ..] = open_command.as_slice() { 1218 if let [program, args @ ..] = open_command.as_slice() {
1166 let mut cmd = Command::new(program); 1219 let mut cmd = Command::new(program);
src/worker.rs +51 −9
@@ -9,11 +9,13 @@ use std::sync::mpsc::{Receiver, SyncSender, sync_channel};
9use futures::StreamExt; 9use futures::StreamExt;
10use futures::stream::FuturesUnordered; 10use futures::stream::FuturesUnordered;
11use gethostname::gethostname; 11use gethostname::gethostname;
12use matrix_sdk::OwnedServerName;
12use matrix_sdk::authentication::matrix::MatrixSession; 13use matrix_sdk::authentication::matrix::MatrixSession;
13use matrix_sdk::config::{RequestConfig, SyncSettings}; 14use matrix_sdk::config::{RequestConfig, SyncSettings};
14use matrix_sdk::encryption::{BackupDownloadStrategy, EncryptionSettings}; 15use matrix_sdk::encryption::{BackupDownloadStrategy, EncryptionSettings};
15use matrix_sdk::event_handler::Ctx; 16use matrix_sdk::event_handler::Ctx;
16use matrix_sdk::room::{Messages as MatrixMessages, MessagesOptions, RoomMember}; 17use matrix_sdk::room::{Messages as MatrixMessages, MessagesOptions, RoomMember};
18use matrix_sdk::ruma::OwnedRoomAliasId;
17use matrix_sdk::ruma::api::client::filter::{ 19use matrix_sdk::ruma::api::client::filter::{
18 FilterDefinition, 20 FilterDefinition,
19 LazyLoadOptions, 21 LazyLoadOptions,
@@ -705,7 +707,8 @@ pub enum WorkerTask {
705 Logout(String, ClientReply<IambResult<EditInfo>>), 707 Logout(String, ClientReply<IambResult<EditInfo>>),
706 GetInviter(MatrixRoom, ClientReply<IambResult<Option<RoomMember>>>), 708 GetInviter(MatrixRoom, ClientReply<IambResult<Option<RoomMember>>>),
707 GetRoom(OwnedRoomId, ClientReply<IambResult<FetchedRoom>>), 709 GetRoom(OwnedRoomId, ClientReply<IambResult<FetchedRoom>>),
708 JoinRoom(String, ClientReply<IambResult<OwnedRoomId>>), 710 ResolveAlias(OwnedRoomAliasId, ClientReply<IambResult<OwnedRoomId>>),
711 JoinRoom(String, Vec<OwnedServerName>, ClientReply<IambResult<OwnedRoomId>>),
709 Members(OwnedRoomId, ClientReply<IambResult<Vec<RoomMember>>>), 712 Members(OwnedRoomId, ClientReply<IambResult<Vec<RoomMember>>>),
710 SpaceMembers(OwnedRoomId, ClientReply<IambResult<Vec<OwnedRoomId>>>), 713 SpaceMembers(OwnedRoomId, ClientReply<IambResult<Vec<OwnedRoomId>>>),
711 TypingNotice(OwnedRoomId), 714 TypingNotice(OwnedRoomId),
@@ -739,9 +742,16 @@ impl Debug for WorkerTask {
739 .field(&format_args!("_")) 742 .field(&format_args!("_"))
740 .finish() 743 .finish()
741 }, 744 },
742 WorkerTask::JoinRoom(s, _) => { 745 WorkerTask::ResolveAlias(s, _) => {
746 f.debug_tuple("WorkerTask::ResolveAlias")
747 .field(s)
748 .field(&format_args!("_"))
749 .finish()
750 },
751 WorkerTask::JoinRoom(s, via, _) => {
743 f.debug_tuple("WorkerTask::JoinRoom") 752 f.debug_tuple("WorkerTask::JoinRoom")
744 .field(s) 753 .field(s)
754 .field(via)
745 .field(&format_args!("_")) 755 .field(&format_args!("_"))
746 .finish() 756 .finish()
747 }, 757 },
@@ -915,10 +925,18 @@ impl Requester {
915 return response.recv(); 925 return response.recv();
916 } 926 }
917 927
918 pub fn join_room(&self, name: String) -> IambResult<OwnedRoomId> { 928 pub fn resolve_alias(&self, alias_id: OwnedRoomAliasId) -> IambResult<OwnedRoomId> {
929 let (reply, response) = oneshot();
930
931 self.tx.send(WorkerTask::ResolveAlias(alias_id, reply)).unwrap();
932
933 return response.recv();
934 }
935
936 pub fn join_room(&self, name: String, via: Vec<OwnedServerName>) -> IambResult<OwnedRoomId> {
919 let (reply, response) = oneshot(); 937 let (reply, response) = oneshot();
920 938
921 self.tx.send(WorkerTask::JoinRoom(name, reply)).unwrap(); 939 self.tx.send(WorkerTask::JoinRoom(name, via, reply)).unwrap();
922 940
923 return response.recv(); 941 return response.recv();
924 } 942 }
@@ -1012,9 +1030,13 @@ impl ClientWorker {
1012 self.init(store).await; 1030 self.init(store).await;
1013 reply.send(()); 1031 reply.send(());
1014 }, 1032 },
1015 WorkerTask::JoinRoom(room_id, reply) => { 1033 WorkerTask::ResolveAlias(alias_id, reply) => {
1034 assert!(self.initialized);
1035 reply.send(self.resolve_alias(alias_id).await);
1036 },
1037 WorkerTask::JoinRoom(name, via, reply) => {
1016 assert!(self.initialized); 1038 assert!(self.initialized);
1017 reply.send(self.join_room(room_id).await); 1039 reply.send(self.join_room(name, via).await);
1018 }, 1040 },
1019 WorkerTask::GetInviter(invited, reply) => { 1041 WorkerTask::GetInviter(invited, reply) => {
1020 assert!(self.initialized); 1042 assert!(self.initialized);
@@ -1483,7 +1505,11 @@ impl ClientWorker {
1483 1505
1484 async fn get_room(&mut self, room_id: OwnedRoomId) -> IambResult<FetchedRoom> { 1506 async fn get_room(&mut self, room_id: OwnedRoomId) -> IambResult<FetchedRoom> {
1485 if let Some(room) = self.client.get_room(&room_id) { 1507 if let Some(room) = self.client.get_room(&room_id) {
1486 let name = room.cached_display_name().ok_or_else(|| IambError::UnknownRoom(room_id))?; 1508 let name = if let Some(name) = room.cached_display_name() {
1509 name
1510 } else {
1511 room.display_name().await.map_err(IambError::from)?
1512 };
1487 let tags = room.tags().await.map_err(IambError::from)?; 1513 let tags = room.tags().await.map_err(IambError::from)?;
1488 1514
1489 Ok((room, name, tags)) 1515 Ok((room, name, tags))
@@ -1492,9 +1518,25 @@ impl ClientWorker {
1492 } 1518 }
1493 } 1519 }
1494 1520
1495 async fn join_room(&mut self, name: String) -> IambResult<OwnedRoomId> { 1521 async fn resolve_alias(&mut self, alias_id: OwnedRoomAliasId) -> IambResult<OwnedRoomId> {
1522 match self.client.resolve_room_alias(&alias_id).await {
1523 Ok(resp) => Ok(resp.room_id),
1524 Err(e) => {
1525 let msg = e.to_string();
1526 let err = UIError::Failure(msg);
1527
1528 return Err(err);
1529 },
1530 }
1531 }
1532
1533 async fn join_room(
1534 &mut self,
1535 name: String,
1536 via: Vec<OwnedServerName>,
1537 ) -> IambResult<OwnedRoomId> {
1496 if let Ok(alias_id) = OwnedRoomOrAliasId::from_str(name.as_str()) { 1538 if let Ok(alias_id) = OwnedRoomOrAliasId::from_str(name.as_str()) {
1497 match self.client.join_room_by_id_or_alias(&alias_id, &[]).await { 1539 match self.client.join_room_by_id_or_alias(&alias_id, &via).await {
1498 Ok(resp) => Ok(resp.room_id().to_owned()), 1540 Ok(resp) => Ok(resp.room_id().to_owned()),
1499 Err(e) => { 1541 Err(e) => {
1500 let msg = e.to_string(); 1542 let msg = e.to_string();