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 @@
55.\"
66.\" You can preview this file with:
77.\" $ man ./docs/iamb.1
8.Dd Mar 24, 2024
8.Dd Sep 11, 2025
99.Dt IAMB 1
1010.Os
1111.Sh NAME
@@ -16,6 +16,7 @@
1616.Op Fl hV
1717.Op Fl P Ar profile
1818.Op Fl C Ar dir
19.Op Ar URI
1920.Sh DESCRIPTION
2021.Nm
2122is a client for the Matrix communication protocol.
@@ -46,6 +47,9 @@ Show the help text and quit.
4647Show the current
4748.Nm
4849version 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
4953.El
5054
5155.Sh "GENERAL COMMANDS"
iamb.desktop +2 −1
@@ -1,7 +1,8 @@
11[Desktop Entry]
22Categories=Network;InstantMessaging;Chat;
33Comment=A Matrix client for Vim addicts
4Exec=iamb
4Exec=iamb %u
5MimeType=x-scheme-handler/matrix
56GenericName=Matrix Client
67Keywords=Matrix;matrix.org;chat;communications;talk;
78Name=iamb
src/base.rs +51 −33
@@ -2,7 +2,7 @@
22//!
33//! The types defined here get used throughout iamb.
44
5use std::collections::hash_map::{Entry, IntoIter};
5use std::collections::hash_map::IntoIter;
66use std::collections::{BTreeSet, HashSet};
77
88use emojis::Emoji;
@@ -566,7 +566,7 @@ pub enum KeysAction {
566566 Import(String, String),
567567}
568568
569/// An action that the main program loop should.
569/// An action that the main program loop should execute.
570570///
571571/// See [the commands module][super::commands] for where these are usually created.
572572#[derive(Clone, Debug, Eq, PartialEq)]
@@ -583,8 +583,8 @@ pub enum IambAction {
583583 /// Perform an action on the current space.
584584 Space(SpaceAction),
585585
586 /// Open a URL.
587 OpenLink(String),
586 /// Open a URL (and specify whether to join linked matrix rooms).
587 OpenLink(String, bool),
588588
589589 /// Perform an action on the currently focused room.
590590 Room(RoomAction),
@@ -992,9 +992,9 @@ struct DisplayNameUsers {
992992#[derive(Default)]
993993pub struct DisplayNameStore {
994994 /// 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)>,
996996
997 by_names: HashMap<String, DisplayNameUsers>,
997 by_names: CompletionMap<String, DisplayNameUsers>,
998998}
999999
10001000impl DisplayNameStore {
@@ -1028,51 +1028,40 @@ impl DisplayNameStore {
10281028 self.set_by_name(user_id.clone(), name, is_active);
10291029 }
10301030
1031 let previous = match (self.by_ids.entry(user_id), name) {
1032 // Nothing to do!
1033 (Entry::Vacant(_), None) => None,
1034
1035 // Setting initial display name for user:
1036 (Entry::Vacant(v), Some(name)) => {
1037 v.insert((name, is_active));
1038 None
1039 },
1031 if self
1032 .by_ids
1033 .get(&user_id)
1034 .is_some_and(|(n, a)| *n == name && *a == is_active)
1035 {
1036 // nothing to do
1037 return;
1038 }
10401039
1041 // Unsetting display name:
1042 (Entry::Occupied(o), None) => Some(o.remove_entry()),
1040 let previous = self.by_ids.insert(user_id.to_owned(), (name, is_active));
10431041
1044 // Replacing existing name:
1045 (Entry::Occupied(mut o), Some(name)) => {
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 {
1042 let Some((Some(name), was_active)) = previous else {
1043 // no previous entry in `self.by_names` to remove
10561044 return;
10571045 };
10581046
1059 let Some(users) = self.by_names.get_mut(&previous.0) else {
1047 let Some(users) = self.by_names.get_mut(&name) else {
10601048 return;
10611049 };
10621050
1063 if previous.1 {
1051 if was_active {
10641052 users.active.remove(&user_id);
10651053 } else {
10661054 users.inactive.remove(&user_id);
10671055 }
10681056
10691057 if users.active.is_empty() && users.inactive.is_empty() {
1070 self.by_names.remove(&previous.0);
1058 self.by_names.remove(&name);
10711059 }
10721060 }
10731061
10741062 pub fn get<'a>(&'a self, user_id: &UserId) -> Option<Cow<'a, str>> {
10751063 let (displayname, is_active) = self.by_ids.get(user_id)?;
1064 let displayname = displayname.as_ref()?;
10761065 let users = self.by_names.get(displayname)?;
10771066
10781067 if !users.active.contains(user_id) && !users.inactive.contains(user_id) {
@@ -1089,6 +1078,35 @@ impl DisplayNameStore {
10891078 // Ambiguous username, so include unique user ID:
10901079 Some(Cow::Owned(format!("{displayname} ({user_id})")))
10911080 }
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 }
10921110}
10931111
10941112/// Information about room's the user's joined.
@@ -1856,7 +1874,7 @@ pub struct ChatStore {
18561874 pub rooms: CompletionMap<OwnedRoomId, RoomInfo>,
18571875
18581876 /// Map of room names.
1859 pub names: CompletionMap<String, OwnedRoomId>,
1877 pub names: CompletionMap<OwnedRoomAliasId, OwnedRoomId>,
18601878
18611879 /// Presence information for other users.
18621880 pub presences: CompletionMap<OwnedUserId, PresenceState>,
src/completions.rs +32 −23
@@ -1,5 +1,6 @@
11//! Tab completions for iamb
22
3use matrix_sdk::ruma::RoomId;
34use modalkit::editing::completion::{Completer, complete_path};
45use modalkit::editing::cursor::Cursor;
56use modalkit::env::vim::command::CommandDescription;
@@ -264,7 +265,7 @@ fn complete_users(input: &str, store: &ChatStore) -> Vec<String> {
264265fn complete_matrix_names(input: &str, store: &ChatStore) -> Vec<String> {
265266 let list = store.names.complete(input);
266267 if !list.is_empty() {
267 return list;
268 return list.into_iter().map(|i| i.to_string()).collect();
268269 }
269270
270271 let list = store.presences.complete(input);
@@ -279,7 +280,7 @@ fn complete_matrix_names(input: &str, store: &ChatStore) -> Vec<String> {
279280fn complete_room_alias_or_id(input: &str, store: &ChatStore) -> Vec<String> {
280281 let list = store.names.complete(input);
281282 if !list.is_empty() {
282 return list;
283 return list.into_iter().map(|i| i.to_string()).collect();
283284 }
284285
285286 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
685686}
686687
687688/// 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> {
689695 let id = text
690696 .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
691697 .unwrap_or_else(EditRope::empty);
692698 let id = Cow::from(&id);
693699
700 let info = store.rooms.get_or_default(room_id.to_owned());
701
694702 match id.chars().next() {
695703 // Complete room aliases.
696704 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()
698711 },
699712
700713 // Complete room identifiers.
701714 Some('!') => {
702 return store
715 store
703716 .rooms
704717 .complete(id.as_ref())
705718 .into_iter()
706 .map(|i| i.to_string())
707 .collect();
719 .map(|i| format!("[{}]({})", i, i.matrix_to_uri()))
720 .collect()
708721 },
709722
710723 // Complete Emoji shortcodes.
@@ -716,14 +729,7 @@ fn complete_msgbar(text: &EditRope, cursor: &mut Cursor, store: &ChatStore) -> V
716729 },
717730
718731 // Complete usernames for @ and empty strings.
719 Some('@') | None => {
720 return store
721 .presences
722 .complete(id.as_ref())
723 .into_iter()
724 .map(|i| i.to_string())
725 .collect();
726 },
732 Some('@') | None => info.display_names.complete_mention(&id),
727733
728734 // Unknown sigil.
729735 Some(_) => return vec![],
@@ -743,7 +749,9 @@ impl Completer<IambInfo> for IambCompleter {
743749 match content {
744750 IambBufferId::Command(CommandType::Command) => complete_cmdbar(text, cursor, store),
745751 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 },
747755 IambBufferId::Room(_, _, RoomFocus::Scrollback) => vec![],
748756
749757 IambBufferId::DirectList => vec![],
@@ -774,24 +782,25 @@ pub mod tests {
774782 #[tokio::test]
775783 async fn test_complete_msgbar() {
776784 let store = mock_store().await;
777 let store = store.application;
785 let mut store = store.application;
786 let room_id = TEST_ROOM1_ID.clone();
778787
779788 let text = EditRope::from("going for a walk :walk ");
780789 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);
782791 assert_eq!(res, vec![":walking:", ":walking_man:", ":walking_woman:"]);
783792 assert_eq!(cursor, Cursor::new(0, 17));
784793
785 let text = EditRope::from("hello @user1 ");
794 let text = EditRope::from("hello @user2 ");
786795 let mut cursor = Cursor::new(0, 12);
787 let res = complete_msgbar(&text, &mut cursor, &store);
788 assert_eq!(res, vec!["@user1:example.com"]);
796 let res = complete_msgbar(&text, &mut cursor, &mut store, &room_id);
797 assert_eq!(res, vec!["[User 2](https://matrix.to/#/@user2:example.com)"]);
789798 assert_eq!(cursor, Cursor::new(0, 6));
790799
791800 let text = EditRope::from("see #room ");
792801 let mut cursor = Cursor::new(0, 9);
793 let res = complete_msgbar(&text, &mut cursor, &store);
794 assert_eq!(res, vec!["#room1:example.com"]);
802 let res = complete_msgbar(&text, &mut cursor, &mut store, &room_id);
803 assert_eq!(res, vec!["[#room1:example.com](https://matrix.to/#/%23room1:example.com)"]);
795804 assert_eq!(cursor, Cursor::new(0, 4));
796805 }
797806
src/config.rs +15
@@ -188,6 +188,9 @@ pub struct Iamb {
188188
189189 #[clap(short = 'C', long, value_parser)]
190190 pub config_directory: Option<PathBuf>,
191
192 /// `matrix:` uri or `https://matrix.to` link to open
193 pub uri: Option<String>,
191194}
192195
193196#[derive(thiserror::Error, Debug)]
@@ -1497,6 +1500,18 @@ mod tests {
14971500
14981501 use matrix_sdk::ruma::user_id;
14991502
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
15001515 #[test]
15011516 fn test_profile_name_invalid() {
15021517 assert_eq!(validate_profile_name(""), false);
src/main.rs +144 −16
@@ -25,6 +25,7 @@ use std::sync::atomic::AtomicUsize;
2525
2626use clap::{CommandFactory, Parser};
2727use matrix_sdk::ruma::api::error::ErrorKind;
28use matrix_sdk::{OwnedServerName, RoomState};
2829use matrix_sdk_crypto::encrypt_room_key_export;
2930use modalkit::actions::{Commandable, TabAction, TabContainer, TabCount, WindowContainer};
3031use modalkit::crossterm;
@@ -84,16 +85,13 @@ fn config_tab_to_desc(
8485
8586 let window = match window {
8687 config::WindowPath::UserId(user_id) => {
87 let name = user_id.to_string();
88 let room_id = worker.join_room(name.clone())?;
89 names.insert(name, room_id.clone());
88 let room_id = worker.join_room(user_id.to_string(), vec![])?;
9089 IambId::Room(room_id, None)
9190 },
9291 config::WindowPath::RoomId(room_id) => IambId::Room(room_id, None),
9392 config::WindowPath::AliasId(alias) => {
94 let name = alias.to_string();
95 let room_id = worker.join_room(name.clone())?;
96 names.insert(name, room_id.clone());
93 let room_id = worker.join_room(alias.to_string(), vec![])?;
94 names.insert(alias, room_id.clone());
9795 IambId::Room(room_id, None)
9896 },
9997 config::WindowPath::Window(id) => id,
@@ -125,14 +123,100 @@ fn restore_layout(
125123 tabs.to_layout(area.into(), store)
126124}
127125
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
128188fn setup_screen(
129189 settings: ApplicationSettings,
130190 store: &mut ProgramStore,
191 initial_room: Option<(MatrixId, Vec<OwnedServerName>)>,
131192) -> IambResult<ScreenState<IambWindow, IambInfo>> {
132193 let cmd = CommandBarState::new(store);
133194 let dims = crossterm::terminal::size()?;
134195 let area = Rect::new(0, 0, dims.0, dims.1);
135196
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
136220 match settings.layout {
137221 config::Layout::Restore => {
138222 match restore_layout(area, &settings, store) {
@@ -203,6 +287,7 @@ impl Application {
203287 pub async fn new(
204288 settings: ApplicationSettings,
205289 store: AsyncProgramStore,
290 initial_room: Option<(MatrixId, Vec<OwnedServerName>)>,
206291 ) -> IambResult<Application> {
207292 let backend = CrosstermBackend::new(stdout());
208293 let terminal = Terminal::new(backend)?;
@@ -212,7 +297,7 @@ impl Application {
212297 let bindings = KeyManager::new(bindings);
213298
214299 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)?;
216301
217302 let worker = locked.application.worker.clone();
218303
@@ -551,12 +636,36 @@ impl Application {
551636 self.screen.current_window_mut()?.send_command(act, ctx, store).await?
552637 },
553638
554 IambAction::OpenLink(url) => {
555 tokio::task::spawn_blocking(move || {
556 return open::that(url);
557 });
639 IambAction::OpenLink(url, join_or_create) => {
640 let matrix_uri = MatrixUri::parse(&url).ok();
641 let matrix_to_uri = MatrixToUri::parse(&url).ok();
558642
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 }
560669 },
561670
562671 IambAction::Verify(act, flow_id) => {
@@ -977,7 +1086,10 @@ async fn login_normal(
9771086 Ok(())
9781087}
9791088
980async fn run(mut settings: ApplicationSettings) -> IambResult<()> {
1089async fn run(
1090 mut settings: ApplicationSettings,
1091 initial_room: Option<(MatrixId, Vec<OwnedServerName>)>,
1092) -> IambResult<()> {
9811093 // Work out whether to use the Kitty keyboard protocol before anything
9821094 // clones the settings, so that every copy agrees with the flags we push in
9831095 // setup_tty() and pop in restore_tty().
@@ -1038,8 +1150,13 @@ async fn run(mut settings: ApplicationSettings) -> IambResult<()> {
10381150 }));
10391151
10401152 // And finally, start running the terminal UI.
1041 let mut application = Application::new(settings, store).await?;
1042 application.run().await?;
1153 let mut application = Application::new(settings, store, initial_room)
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))?;
10431160
10441161 // Clean up the terminal on exit.
10451162 restore_tty(enable_enhanced_keys, enable_mouse);
@@ -1094,6 +1211,17 @@ fn main() {
10941211 return;
10951212 }
10961213
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
10971225 // Load configuration and set up the Matrix SDK.
10981226 let settings = ApplicationSettings::load(iamb).unwrap_or_else(print_exit);
10991227
@@ -1116,7 +1244,7 @@ fn main() {
11161244 .build()
11171245 .unwrap();
11181246
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 }) {
11201248 eprintln!("\n{err}\n");
11211249 process::exit(2);
11221250 }
src/message/compose.rs +14 −16
@@ -67,7 +67,7 @@ impl SlashCommand {
6767 MessageType::Text(msg)
6868 },
6969 SlashCommand::Markdown => {
70 let msg = text_to_message_content(input.to_string());
70 let msg = text_to_message_content(input.into());
7171 MessageType::Text(msg)
7272 },
7373 SlashCommand::Confetti => {
@@ -170,17 +170,21 @@ fn text_to_html(input: &str) -> Option<String> {
170170 markdown_to_html(input, &options).into()
171171}
172172
173fn text_to_message_content(input: String) -> TextMessageEventContent {
174 if let Some(html) = text_to_html(input.as_str()) {
173fn text_to_message_content(input: Cow<'_, str>) -> TextMessageEventContent {
174 if let Some(html) = text_to_html(&input) {
175175 TextMessageEventContent::html(input, html)
176176 } else {
177177 TextMessageEventContent::plain(input)
178178 }
179179}
180180
181pub fn text_to_message(input: String, default_markup: MarkupFormat) -> RoomMessageEventContent {
182 let (rest, slash) = parse_slash_command(input.as_str())
181pub fn text_to_message(
182 input: Cow<'_, str>,
183 default_markup: MarkupFormat,
184) -> RoomMessageEventContent {
185 let (rest, slash) = parse_slash_command(&input)
183186 .unwrap_or_else(|_| (&input, SlashCommand::from(default_markup)));
187
184188 let msg = slash
185189 .to_message(rest)
186190 .unwrap_or_else(|_| MessageType::Text(text_to_message_content(input)));
@@ -193,19 +197,13 @@ pub fn text_to_text_message_event_content(
193197 input: String,
194198 default_markup: MarkupFormat,
195199) -> Option<TextMessageEventContent> {
196 let (body, cmd) = parse_slash_command(&input)
200 let (rest, slash) = parse_slash_command(&input)
197201 .unwrap_or_else(|_| (&input, SlashCommand::from(default_markup)));
198202
199 let content = match cmd {
200 SlashCommand::Html => TextMessageEventContent::html(body, body),
201 SlashCommand::Plaintext => TextMessageEventContent::plain(body),
202 SlashCommand::Markdown => {
203 if let Some(html) = text_to_html(body) {
204 TextMessageEventContent::html(body, html)
205 } else {
206 TextMessageEventContent::plain(body)
207 }
208 },
203 let content = match slash {
204 SlashCommand::Html => TextMessageEventContent::html(rest, rest),
205 SlashCommand::Plaintext => TextMessageEventContent::plain(rest),
206 SlashCommand::Markdown => text_to_message_content(rest.into()),
209207 _ => return None,
210208 };
211209
src/message/html.rs +129 −50
@@ -17,6 +17,7 @@ use html5ever::interface::{Attribute, QualName};
1717use html5ever::tendril::{StrTendril, TendrilSink};
1818use html5ever::{local_name, ns};
1919use markup5ever_rcdom::{Handle, NodeData, RcDom};
20use matrix_sdk::OwnedServerName;
2021use ratatui::symbols::line;
2122
2223use crate::message::printer::TextPrinter;
@@ -79,12 +80,14 @@ impl ListStyle {
7980pub type StyleTreeChildren = Vec<StyleTreeNode>;
8081
8182/// Type of contents in a table cell.
83#[derive(Debug, Clone, Copy)]
8284pub enum CellType {
8385 Data,
8486 Header,
8587}
8688
8789/// A collection of cells for a single row in a table.
90#[derive(Debug, Clone)]
8891pub struct TableRow {
8992 cells: Vec<(CellType, StyleTreeNode)>,
9093}
@@ -102,6 +105,7 @@ impl TableRow {
102105}
103106
104107/// A collection of rows in a table.
108#[derive(Debug, Clone)]
105109pub struct TableSection {
106110 rows: Vec<TableRow>,
107111}
@@ -119,6 +123,7 @@ impl TableSection {
119123}
120124
121125/// A table.
126#[derive(Debug, Clone)]
122127pub struct Table {
123128 caption: Option<Box<StyleTreeNode>>,
124129 sections: Vec<TableSection>,
@@ -140,6 +145,7 @@ impl Table {
140145 width: usize,
141146 style: Style,
142147 settings: &'a ApplicationSettings,
148 info: &'a RoomInfo,
143149 ) -> Text<'a> {
144150 let mut text = Text::default();
145151 let columns = self.columns();
@@ -158,7 +164,8 @@ impl Table {
158164
159165 if let Some(caption) = &self.caption {
160166 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);
162169 caption.print(&mut printer, style);
163170
164171 for mut line in printer.finish().lines {
@@ -205,7 +212,7 @@ impl Table {
205212 CellType::Data => style,
206213 };
207214
208 cell.to_text(*w, style, settings)
215 cell.to_text(*w, style, settings, info)
209216 } else {
210217 space_text(*w, style)
211218 };
@@ -247,6 +254,7 @@ impl Table {
247254}
248255
249256/// A processed HTML element that we can render to the terminal.
257#[derive(Debug, Clone)]
250258pub enum StyleTreeNode {
251259 Anchor(Box<StyleTreeNode>, char, Url),
252260 Blockquote(Box<StyleTreeNode>),
@@ -263,10 +271,10 @@ pub enum StyleTreeNode {
263271 Table(Table),
264272 Text(Cow<'static, str>),
265273 Sequence(StyleTreeChildren),
266 RoomAlias(OwnedRoomAliasId),
267 RoomId(OwnedRoomId),
268 UserId(OwnedUserId),
269 DisplayName(String, OwnedUserId),
274 RoomAlias(OwnedRoomAliasId, Option<char>),
275 RoomId(OwnedRoomId, Vec<OwnedServerName>, Option<char>),
276 UserId(OwnedUserId, Option<char>),
277 DisplayName(String, OwnedUserId, Option<char>),
270278}
271279
272280impl StyleTreeNode {
@@ -275,8 +283,9 @@ impl StyleTreeNode {
275283 width: usize,
276284 style: Style,
277285 settings: &'a ApplicationSettings,
286 info: &'a RoomInfo,
278287 ) -> Text<'a> {
279 let mut printer = TextPrinter::new(width, style, settings);
288 let mut printer = TextPrinter::new(width, style, settings, info);
280289 self.print(&mut printer, style);
281290 printer.finish()
282291 }
@@ -306,16 +315,31 @@ impl StyleTreeNode {
306315 table.gather_links(urls);
307316 },
308317
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
309339 StyleTreeNode::Image(_) => {},
310340 StyleTreeNode::Ruler => {},
311341 StyleTreeNode::Text(_) => {},
312342 StyleTreeNode::Break => {},
313
314 // TODO: eventually these should turn into internal links:
315 StyleTreeNode::UserId(_) => {},
316 StyleTreeNode::RoomId(_) => {},
317 StyleTreeNode::RoomAlias(_) => {},
318 StyleTreeNode::DisplayName(_, _) => {},
319343 }
320344 }
321345
@@ -428,7 +452,7 @@ impl StyleTreeNode {
428452 }
429453 },
430454 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);
432456 printer.push_text(text);
433457 },
434458 StyleTreeNode::Break => {
@@ -445,19 +469,25 @@ impl StyleTreeNode {
445469 }
446470 },
447471
448 StyleTreeNode::UserId(user_id) => {
449 let style = printer.settings().get_user_style(user_id);
450 printer.push_str(user_id.as_str(), style);
472 StyleTreeNode::UserId(user_id, _) => {
473 let mut span: Span<'a> = printer.settings().get_user_span(user_id, printer.info);
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);
451481 },
452 StyleTreeNode::DisplayName(display_name, user_id) => {
482 StyleTreeNode::DisplayName(display_name, user_id, _) => {
453483 let style = printer.settings().get_user_style(user_id);
454484 printer.push_str(display_name.as_str(), style);
455485 },
456 StyleTreeNode::RoomId(room_id) => {
486 StyleTreeNode::RoomId(room_id, _, _) => {
457487 let bold = style.add_modifier(StyleModifier::BOLD);
458488 printer.push_str(room_id.as_str(), bold);
459489 },
460 StyleTreeNode::RoomAlias(alias) => {
490 StyleTreeNode::RoomAlias(alias, _) => {
461491 let bold = style.add_modifier(StyleModifier::BOLD);
462492 printer.push_str(alias.as_str(), bold);
463493 },
@@ -486,8 +516,9 @@ impl StyleTree {
486516 width: usize,
487517 style: Style,
488518 settings: &'a ApplicationSettings,
519 info: &'a RoomInfo,
489520 ) -> Text<'a> {
490 let mut printer = TextPrinter::new(width, style, settings);
521 let mut printer = TextPrinter::new(width, style, settings, info);
491522
492523 for child in self.children.iter() {
493524 child.print(&mut printer, style);
@@ -670,6 +701,37 @@ fn attrs_to_style(attrs: &[Attribute]) -> Style {
670701 return style;
671702}
672703
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
673735fn h2t(hdl: &Handle, state: &mut TreeGenState) -> StyleTreeChildren {
674736 let node = hdl.deref();
675737
@@ -684,7 +746,13 @@ fn h2t(hdl: &Handle, state: &mut TreeGenState) -> StyleTreeChildren {
684746 let h = attrs_to_href(&attrs.borrow()).and_then(|u| Url::parse(&u).ok());
685747
686748 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 {
688756 StyleTreeNode::Anchor(c, n, h)
689757 } else {
690758 *c
@@ -827,21 +895,21 @@ pub fn parse_matrix_html(s: &str) -> StyleTree {
827895#[cfg(test)]
828896pub mod tests {
829897 use super::*;
830
831898 use pretty_assertions::assert_eq;
832899 use unicode_width::UnicodeWidthStr;
833900
834 use crate::tests::mock_settings;
901 use crate::tests::{mock_room, mock_settings};
835902 use crate::util::space_span;
836903
837904 #[test]
838905 fn test_header() {
906 let info = mock_room();
839907 let settings = mock_settings();
840908 let bold = Style::default().add_modifier(StyleModifier::BOLD);
841909
842910 let s = "<h1>Header 1</h1>";
843911 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);
845913 assert_eq!(text.lines, vec![Line::from(vec![
846914 Span::styled("#", bold),
847915 Span::styled(" ", bold),
@@ -853,7 +921,7 @@ pub mod tests {
853921
854922 let s = "<h2>Header 2</h2>";
855923 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);
857925 assert_eq!(text.lines, vec![Line::from(vec![
858926 Span::styled("#", bold),
859927 Span::styled("#", bold),
@@ -866,7 +934,7 @@ pub mod tests {
866934
867935 let s = "<h3>Header 3</h3>";
868936 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);
870938 assert_eq!(text.lines, vec![Line::from(vec![
871939 Span::styled("#", bold),
872940 Span::styled("#", bold),
@@ -880,7 +948,7 @@ pub mod tests {
880948
881949 let s = "<h4>Header 4</h4>";
882950 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);
884952 assert_eq!(text.lines, vec![Line::from(vec![
885953 Span::styled("#", bold),
886954 Span::styled("#", bold),
@@ -895,7 +963,7 @@ pub mod tests {
895963
896964 let s = "<h5>Header 5</h5>";
897965 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);
899967 assert_eq!(text.lines, vec![Line::from(vec![
900968 Span::styled("#", bold),
901969 Span::styled("#", bold),
@@ -911,7 +979,7 @@ pub mod tests {
911979
912980 let s = "<h6>Header 6</h6>";
913981 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);
915983 assert_eq!(text.lines, vec![Line::from(vec![
916984 Span::styled("#", bold),
917985 Span::styled("#", bold),
@@ -929,6 +997,7 @@ pub mod tests {
929997
930998 #[test]
931999 fn test_style() {
1000 let info = mock_room();
9321001 let settings = mock_settings();
9331002 let def = Style::default();
9341003 let bold = def.add_modifier(StyleModifier::BOLD);
@@ -939,7 +1008,7 @@ pub mod tests {
9391008
9401009 let s = "<b>Bold!</b>";
9411010 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);
9431012 assert_eq!(text.lines, vec![Line::from(vec![
9441013 Span::styled("Bold", bold),
9451014 Span::styled("!", bold),
@@ -948,7 +1017,7 @@ pub mod tests {
9481017
9491018 let s = "<strong>Bold!</strong>";
9501019 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);
9521021 assert_eq!(text.lines, vec![Line::from(vec![
9531022 Span::styled("Bold", bold),
9541023 Span::styled("!", bold),
@@ -957,7 +1026,7 @@ pub mod tests {
9571026
9581027 let s = "<i>Italic!</i>";
9591028 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);
9611030 assert_eq!(text.lines, vec![Line::from(vec![
9621031 Span::styled("Italic", italic),
9631032 Span::styled("!", italic),
@@ -966,7 +1035,7 @@ pub mod tests {
9661035
9671036 let s = "<em>Italic!</em>";
9681037 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);
9701039 assert_eq!(text.lines, vec![Line::from(vec![
9711040 Span::styled("Italic", italic),
9721041 Span::styled("!", italic),
@@ -975,7 +1044,7 @@ pub mod tests {
9751044
9761045 let s = "<del>Strikethrough!</del>";
9771046 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);
9791048 assert_eq!(text.lines, vec![Line::from(vec![
9801049 Span::styled("Strikethrough", strike),
9811050 Span::styled("!", strike),
@@ -984,7 +1053,7 @@ pub mod tests {
9841053
9851054 let s = "<strike>Strikethrough!</strike>";
9861055 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);
9881057 assert_eq!(text.lines, vec![Line::from(vec![
9891058 Span::styled("Strikethrough", strike),
9901059 Span::styled("!", strike),
@@ -993,7 +1062,7 @@ pub mod tests {
9931062
9941063 let s = "<u>Underline!</u>";
9951064 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);
9971066 assert_eq!(text.lines, vec![Line::from(vec![
9981067 Span::styled("Underline", underl),
9991068 Span::styled("!", underl),
@@ -1002,7 +1071,7 @@ pub mod tests {
10021071
10031072 let s = "<font color=\"#ff0000\">Red!</u>";
10041073 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);
10061075 assert_eq!(text.lines, vec![Line::from(vec![
10071076 Span::styled("Red", red),
10081077 Span::styled("!", red),
@@ -1011,7 +1080,7 @@ pub mod tests {
10111080
10121081 let s = "<font color=\"red\">Red!</u>";
10131082 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);
10151084 assert_eq!(text.lines, vec![Line::from(vec![
10161085 Span::styled("Red", red),
10171086 Span::styled("!", red),
@@ -1021,10 +1090,11 @@ pub mod tests {
10211090
10221091 #[test]
10231092 fn test_paragraph() {
1093 let info = mock_room();
10241094 let settings = mock_settings();
10251095 let s = "<p>Hello world!</p><p>Content</p><p>Goodbye world!</p>";
10261096 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);
10281098 assert_eq!(text.lines.len(), 7);
10291099 assert_eq!(
10301100 text.lines[0],
@@ -1049,10 +1119,11 @@ pub mod tests {
10491119
10501120 #[test]
10511121 fn test_blockquote() {
1122 let info = mock_room();
10521123 let settings = mock_settings();
10531124 let s = "<blockquote>Hello world!</blockquote>";
10541125 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);
10561127 let style = Style::new().fg(QUOTE_COLOR);
10571128 assert_eq!(text.lines.len(), 2);
10581129 assert_eq!(
@@ -1081,10 +1152,11 @@ pub mod tests {
10811152
10821153 #[test]
10831154 fn test_list_unordered() {
1155 let info = mock_room();
10841156 let settings = mock_settings();
10851157 let s = "<ul><li>List Item 1</li><li>List Item 2</li><li>List Item 3</li></ul>";
10861158 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);
10881160 assert_eq!(text.lines.len(), 6);
10891161 assert_eq!(
10901162 text.lines[0],
@@ -1144,10 +1216,11 @@ pub mod tests {
11441216
11451217 #[test]
11461218 fn test_list_ordered() {
1219 let info = mock_room();
11471220 let settings = mock_settings();
11481221 let s = "<ol><li>List Item 1</li><li>List Item 2</li><li>List Item 3</li></ol>";
11491222 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);
11511224 assert_eq!(text.lines.len(), 6);
11521225 assert_eq!(
11531226 text.lines[0],
@@ -1207,6 +1280,7 @@ pub mod tests {
12071280
12081281 #[test]
12091282 fn test_table() {
1283 let info = mock_room();
12101284 let settings = mock_settings();
12111285 let s = "<table>\
12121286 <thead>\
@@ -1218,7 +1292,7 @@ pub mod tests {
12181292 <tr><td>a</td><td>b</td><td>c</td></tr>\
12191293 </tbody></table>";
12201294 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);
12221296 let bold = Style::default().add_modifier(StyleModifier::BOLD);
12231297 assert_eq!(text.lines.len(), 11);
12241298
@@ -1308,11 +1382,12 @@ pub mod tests {
13081382
13091383 #[test]
13101384 fn test_matrix_reply_stripped() {
1385 let info = mock_room();
13111386 let settings = mock_settings();
13121387 let s = "<mx-reply>This was replied to</mx-reply>This is the reply";
13131388
13141389 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);
13161391 assert_eq!(text.lines.len(), 2);
13171392 assert_eq!(
13181393 text.lines[0],
@@ -1337,10 +1412,11 @@ pub mod tests {
13371412
13381413 #[test]
13391414 fn test_self_closing() {
1415 let info = mock_room();
13401416 let settings = mock_settings();
13411417 let s = "Hello<br>World<br>Goodbye";
13421418 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);
13441420 assert_eq!(text.lines.len(), 3);
13451421 assert_eq!(text.lines[0], Line::from(vec![Span::raw("Hello"), Span::raw(" "),]));
13461422 assert_eq!(text.lines[1], Line::from(vec![Span::raw("World"), Span::raw(" "),]));
@@ -1349,10 +1425,11 @@ pub mod tests {
13491425
13501426 #[test]
13511427 fn test_embedded_newline() {
1428 let info = mock_room();
13521429 let settings = mock_settings();
13531430 let s = "<p>Hello\nWorld</p>";
13541431 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);
13561433 assert_eq!(text.lines.len(), 1);
13571434 assert_eq!(
13581435 text.lines[0],
@@ -1367,6 +1444,7 @@ pub mod tests {
13671444
13681445 #[test]
13691446 fn test_pre_tag() {
1447 let info = mock_room();
13701448 let settings = mock_settings();
13711449 let s = concat!(
13721450 "<pre><code class=\"language-rust\">",
@@ -1377,7 +1455,7 @@ pub mod tests {
13771455 "</code></pre>\n"
13781456 );
13791457 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);
13811459 assert_eq!(text.lines.len(), 6);
13821460 assert_eq!(
13831461 text.lines[0],
@@ -1455,6 +1533,7 @@ pub mod tests {
14551533
14561534 #[test]
14571535 fn test_emoji_shortcodes() {
1536 let info = mock_room();
14581537 let mut enabled = mock_settings();
14591538 enabled.tunables.message_shortcode_display = true;
14601539 let mut disabled = mock_settings();
@@ -1468,13 +1547,13 @@ pub mod tests {
14681547 let s = format!("<p>{emoji}</p>");
14691548 let tree = parse_matrix_html(s.as_str());
14701549 // 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);
14721551 assert_eq!(text.lines, vec![Line::from(vec![
14731552 Span::raw(emoji),
14741553 space_span(20 - emoji_width, Style::default()),
14751554 ]),]);
14761555 // 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);
14781557 assert_eq!(text.lines, vec![Line::from(vec![
14791558 Span::raw(replacement.as_str()),
14801559 space_span(20 - replacement_width, Style::default()),
src/message/mod.rs +51 −9
@@ -644,6 +644,7 @@ enum SenderSpan<'a> {
644644
645645struct MessageFormatter<'a> {
646646 settings: &'a ApplicationSettings,
647 info: &'a RoomInfo,
647648
648649 /// How many columns to print.
649650 cols: MessageColumns,
@@ -781,7 +782,7 @@ impl<'a> MessageFormatter<'a> {
781782
782783 let width = self.width();
783784 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);
785786 let mut sender = msg.sender_span(info, self.settings);
786787 let sender_width = UnicodeWidthStr::width(sender.content.as_ref());
787788 let trailing = w.saturating_sub(sender_width + 1);
@@ -826,7 +827,7 @@ impl<'a> MessageFormatter<'a> {
826827 settings: &ApplicationSettings,
827828 previews: &'a PreviewManager,
828829 ) -> 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);
830831 let mut reactions = 0;
831832 let mut protos = Vec::new();
832833
@@ -898,7 +899,7 @@ impl<'a> MessageFormatter<'a> {
898899 let plural = len != 1;
899900 let style = Style::default();
900901 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);
902903 let len = Span::styled(len.to_string(), style.add_modifier(StyleModifier::BOLD));
903904 threaded.push_str(" \u{2937} ", style);
904905 threaded.push_span_nobreak(len);
@@ -1064,7 +1065,17 @@ impl Message {
10641065 .map(|user_id| user_id.to_owned())
10651066 .collect();
10661067
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 }
10681079 } else if user_gutter + TIME_GUTTER + MIN_MSG_LEN <= width {
10691080 let cols = MessageColumns::Three;
10701081 let fill = width - user_gutter - TIME_GUTTER;
@@ -1072,7 +1083,17 @@ impl Message {
10721083 let time = Some(self.timestamp.show_time());
10731084 let read = Vec::new();
10741085
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 }
10761097 } else if user_gutter + MIN_MSG_LEN <= width {
10771098 let cols = MessageColumns::Two;
10781099 let fill = width - user_gutter;
@@ -1080,7 +1101,17 @@ impl Message {
10801101 let time = None;
10811102 let read = Vec::new();
10821103
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 }
10841115 } else {
10851116 let cols = MessageColumns::One;
10861117 let fill = width.saturating_sub(2);
@@ -1088,7 +1119,17 @@ impl Message {
10881119 let time = None;
10891120 let read = Vec::new();
10901121
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 }
10921133 }
10931134 }
10941135
@@ -1137,7 +1178,7 @@ impl Message {
11371178 }
11381179
11391180 // 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);
11411182
11421183 // Given our text so far, determine the image offset.
11431184 if let Some(p) = proto {
@@ -1199,6 +1240,7 @@ impl Message {
11991240 style: Style,
12001241 settings: &'a ApplicationSettings,
12011242 previews: &'a PreviewManager,
1243 info: &'a RoomInfo,
12021244 ) -> (Text<'a>, Option<&'a SlicedProtocol>) {
12031245 let mut proto = None;
12041246 let placeholder = match self
@@ -1234,7 +1276,7 @@ impl Message {
12341276 }
12351277
12361278 if let Some(html) = &self.html {
1237 text += html.to_text(width, style, settings);
1279 text += html.to_text(width, style, settings, info);
12381280 } else {
12391281 let mut msg = self.event.body();
12401282 if settings.tunables.message_shortcode_display {
src/message/printer.rs +13 −3
@@ -4,6 +4,7 @@
44//! lines to make concatenation work right (e.g., combining table cells after wrapping their
55//! contents).
66
7use crate::base::RoomInfo;
78use crate::config::TunableValues;
89use crate::prelude::*;
910use crate::util::{
@@ -26,11 +27,17 @@ pub struct TextPrinter<'a> {
2627 literal: bool,
2728
2829 pub(super) settings: &'a ApplicationSettings,
30 pub(super) info: &'a RoomInfo,
2931}
3032
3133impl<'a> TextPrinter<'a> {
3234 /// 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 {
3441 TextPrinter {
3542 text: Text::default(),
3643 width,
@@ -41,6 +48,7 @@ impl<'a> TextPrinter<'a> {
4148 curr_width: 0,
4249 literal: false,
4350 settings,
51 info,
4452 }
4553 }
4654
@@ -91,6 +99,7 @@ impl<'a> TextPrinter<'a> {
9199 curr_width: 0,
92100 literal: self.literal,
93101 settings: self.settings,
102 info: self.info,
94103 }
95104 }
96105
@@ -290,12 +299,13 @@ impl<'a> TextPrinter<'a> {
290299pub mod tests {
291300 use super::*;
292301
293 use crate::tests::mock_settings;
302 use crate::tests::{mock_room, mock_settings};
294303
295304 #[test]
296305 fn test_push_nobreak() {
297306 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);
299309 printer.push_span_nobreak("hello world".into());
300310 let text = printer.finish();
301311 assert_eq!(text.lines.len(), 1);
src/message/state.rs +22 −9
@@ -3,6 +3,7 @@
33use matrix_sdk::ruma::events::room::member::MembershipChange;
44use matrix_sdk::ruma::events::{AnyStateEventContentChange, StateEventContentChange};
55
6use crate::message::TreeGenState;
67use crate::message::html::{StyleTree, StyleTreeNode};
78use crate::prelude::*;
89
@@ -510,7 +511,7 @@ pub fn html_state(ev: &AnySyncStateEvent) -> StyleTree {
510511 ..
511512 }) => {
512513 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'));
514515 let prefix =
515516 StyleTreeNode::Text("* updated the canonical alias for the room to: ".into());
516517 vec![prefix, canon]
@@ -577,7 +578,7 @@ pub fn html_state(ev: &AnySyncStateEvent) -> StyleTree {
577578
578579 let prev_details = prev_content.as_ref().map(|p| p.details());
579580 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'));
581582
582583 match change {
583584 MembershipChange::None => {
@@ -656,7 +657,11 @@ pub fn html_state(ev: &AnySyncStateEvent) -> StyleTree {
656657 (None, Some(new)) => {
657658 vec![
658659 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 ),
660665 ]
661666 },
662667 (Some(old), Some(new)) => {
@@ -664,9 +669,13 @@ pub fn html_state(ev: &AnySyncStateEvent) -> StyleTree {
664669 StyleTreeNode::Text(
665670 "* changed their display name from ".into(),
666671 ),
667 StyleTreeNode::DisplayName(old.into(), state_key.clone()),
672 StyleTreeNode::DisplayName(
673 old.into(),
674 state_key.clone(),
675 Some('0'),
676 ),
668677 StyleTreeNode::Text(" to ".into()),
669 StyleTreeNode::DisplayName(new.into(), state_key),
678 StyleTreeNode::DisplayName(new.into(), state_key, None),
670679 ]
671680 },
672681 (Some(_), None) => {
@@ -759,7 +768,7 @@ pub fn html_state(ev: &AnySyncStateEvent) -> StyleTree {
759768 ..
760769 }) => {
761770 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'));
763772 vec![prefix, room]
764773 },
765774 AnyStateEventContentChange::RoomTopic(StateEventContentChange::Original {
@@ -774,7 +783,7 @@ pub fn html_state(ev: &AnySyncStateEvent) -> StyleTree {
774783 let prefix = StyleTreeNode::Text("* added a space child: ".into());
775784
776785 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'))
778787 } else {
779788 bold(ev.state_key().to_string())
780789 };
@@ -792,7 +801,7 @@ pub fn html_state(ev: &AnySyncStateEvent) -> StyleTree {
792801 };
793802
794803 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'))
796805 } else {
797806 bold(ev.state_key().to_string())
798807 };
@@ -816,12 +825,16 @@ pub fn html_state(ev: &AnySyncStateEvent) -> StyleTree {
816825 );
817826 let mut cs = vec![prefix];
818827
828 let mut state = TreeGenState { link_num: 0 };
829
819830 for (i, member) in content.service_members.iter().enumerate() {
820831 if i != 0 {
821832 cs.push(StyleTreeNode::Text(", ".into()));
822833 }
823834
824 cs.push(StyleTreeNode::UserId(member.clone()));
835 let c = state.next_link_char();
836
837 cs.push(StyleTreeNode::UserId(member.clone(), c));
825838 }
826839
827840 cs
src/prelude.rs +3
@@ -20,8 +20,11 @@ pub use matrix_sdk::ruma::events::room::message::{
2020 RoomMessageEventContent,
2121};
2222pub use matrix_sdk::ruma::events::tag::{TagName, Tags};
23pub use matrix_sdk::ruma::matrix_uri::MatrixId;
2324pub use matrix_sdk::ruma::{
2425 EventId,
26 MatrixToUri,
27 MatrixUri,
2528 MilliSecondsSinceUnixEpoch,
2629 OwnedEventId,
2730 OwnedRoomAliasId,
src/tests.rs +9 −4
@@ -1,8 +1,9 @@
11use std::iter::FromIterator as _;
22
33use lazy_static::lazy_static;
4use matrix_sdk::ruma::assign;
4use matrix_sdk::ruma::events::room::message::RoomMessageEventContent;
55use matrix_sdk::ruma::{UInt, event_id, server_name, user_id};
6use matrix_sdk::ruma::{assign, owned_room_alias_id};
67use serde_json::{Map, Value};
78use tokio::sync::mpsc::unbounded_channel;
89
@@ -10,9 +11,8 @@ use crate::base::EventLocation;
1011use crate::config::*;
1112use crate::prelude::*;
1213
13const TEST_ROOM1_ALIAS: &str = "#room1:example.com";
14
1514lazy_static! {
15 pub static ref TEST_ROOM1_ALIAS: OwnedRoomAliasId = owned_room_alias_id!("#room1:example.com");
1616 pub static ref TEST_ROOM1_ID: OwnedRoomId =
1717 RoomId::new_v1(server_name!("example.com")).to_owned();
1818 pub static ref TEST_USER1: OwnedUserId = user_id!("@user1:example.com").to_owned();
@@ -134,6 +134,11 @@ pub fn mock_room() -> RoomInfo {
134134 room.name = Some("Watercooler Discussion".into());
135135 room.keys = mock_keys();
136136 *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
137142 room
138143}
139144
@@ -248,7 +253,7 @@ pub async fn mock_store() -> ProgramStore {
248253 let info = mock_room();
249254
250255 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);
252257
253258 ProgramStore::new(store)
254259}
src/windows/mod.rs +8 −5
@@ -912,8 +912,11 @@ impl Window<IambInfo> for IambWindow {
912912
913913 IambWindow::open(id, store)
914914 } else {
915 let room_id = worker.join_room(name.clone())?;
916 names.insert(name, room_id.clone());
915 let room_id = worker.join_room(name.clone(), vec![])?;
916
917 if let Ok(alias) = OwnedRoomAliasId::from_str(&name) {
918 names.insert(alias, room_id.clone());
919 }
917920
918921 let (room, name, tags) = store.application.worker.get_room(room_id)?;
919922 let room = RoomState::new(room, None, name, tags, store);
@@ -956,7 +959,7 @@ impl GenericChatItem {
956959 info.tags.clone_from(&room_info.deref().1);
957960
958961 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());
960963 }
961964
962965 GenericChatItem { room_info, name, alias, is_dm, unread }
@@ -1079,7 +1082,7 @@ impl RoomItem {
10791082 info.tags.clone_from(&room_info.deref().1);
10801083
10811084 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());
10831086 }
10841087
10851088 RoomItem { room_info, name, alias, unread }
@@ -1300,7 +1303,7 @@ impl SpaceItem {
13001303 let alias = room_info.0.canonical_alias();
13011304
13021305 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());
13041307 }
13051308
13061309 SpaceItem { room_info, name, alias }
src/windows/room/chat.rs +102 −49
@@ -11,9 +11,16 @@ use matrix_sdk::attachment::AttachmentConfig;
1111use matrix_sdk::attachment::{AttachmentInfo, BaseImageInfo};
1212use matrix_sdk::media::{MediaFormat, MediaRequestParameters};
1313use matrix_sdk::room::reply::{EnforceThread, Reply};
14use matrix_sdk::ruma::events::Mentions;
1415use matrix_sdk::ruma::events::reaction::ReactionEventContent;
15use matrix_sdk::ruma::events::relation::{Annotation, Replacement};
16use matrix_sdk::ruma::events::room::message::{AddMentions, ForwardThread, ReplyWithinThread};
16use matrix_sdk::ruma::events::relation::Annotation;
17use matrix_sdk::ruma::events::room::message::{
18 AddMentions,
19 ForwardThread,
20 MessageFormat,
21 ReplyWithinThread,
22 TextMessageEventContent,
23};
1724use matrix_sdk::send_queue::RoomSendQueueError;
1825use modalkit::editing::history::{self, HistoryList};
1926use modalkit::editing::store::RegisterError;
@@ -21,6 +28,7 @@ use modalkit::keybindings::dialog::{Dialog, MultiChoice, MultiChoiceItem};
2128use modalkit_ratatui::PromptActions;
2229use modalkit_ratatui::textbox::{TextBox, TextBoxState};
2330use ratatui::prelude::Stylize;
31use regex::Regex;
2432
2533use crate::base::{DownloadFlags, EchoLocation};
2634use crate::config::EncryptionIndicatorLocation;
@@ -146,15 +154,18 @@ impl ChatState {
146154 Err(UIError::NeedConfirm(prompt))
147155 },
148156 MessageAction::Download(filename, flags) => {
157 if let MessageEvent::State(_) = &msg.event {
158 let err = open_links(msg);
159 return Err(err);
160 }
161
149162 if let Some(msgtype) = msg.event.msgtype() {
150163 let media = client.media();
151
152164 let mut filename = match (filename, &settings.dirs.downloads) {
153165 (Some(f), _) => PathBuf::from(f),
154166 (None, Some(downloads)) => downloads.clone(),
155167 (None, None) => return Err(IambError::NoDownloadDir.into()),
156168 };
157
158169 let (source, msg_filename) = match msgtype {
159170 MessageType::Audio(c) => (c.source.clone(), c.filename()),
160171 MessageType::File(c) => (c.source.clone(), c.filename()),
@@ -164,46 +175,13 @@ impl ChatState {
164175 if !flags.contains(DownloadFlags::OPEN) {
165176 return Err(IambError::NoAttachment.into());
166177 }
167
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
178 let err = open_links(msg);
199179 return Err(err);
200180 },
201181 };
202
203182 if filename.is_dir() {
204183 filename.push(msg_filename.replace(std::path::MAIN_SEPARATOR_STR, "_"));
205184 }
206
207185 if filename.exists() && !flags.contains(DownloadFlags::FORCE) {
208186 // Find an incrementally suffixed filename, e.g. image-2.jpg -> image-3.jpg
209187 if let Some(stem) = filename.file_stem().and_then(OsStr::to_str) {
@@ -223,7 +201,6 @@ impl ChatState {
223201 }
224202 }
225203 }
226
227204 if !filename.exists() || flags.contains(DownloadFlags::FORCE) {
228205 let req = MediaRequestParameters { source, format: MediaFormat::File };
229206
@@ -242,7 +219,6 @@ impl ChatState {
242219
243220 return Err(err);
244221 }
245
246222 let info = if flags.contains(DownloadFlags::OPEN) {
247223 let target = filename.clone().into_os_string();
248224 match open_command(
@@ -265,7 +241,6 @@ impl ChatState {
265241 filename.display()
266242 ))
267243 };
268
269244 return Ok(info.into());
270245 }
271246
@@ -545,6 +520,14 @@ impl ChatState {
545520 .filter(|c| !c.is_blank())
546521 .map(|c| c.trim_end().to_string())
547522 .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
548531 config.reply = self.generate_reply_info(info, add_caption);
549532 config
550533 }
@@ -585,7 +568,14 @@ impl ChatState {
585568 msg.trim_end().to_string()
586569 };
587570
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);
589579
590580 if let Some(key) = &self.editing {
591581 let id = match &key.id {
@@ -625,20 +615,27 @@ impl ChatState {
625615 },
626616 };
627617
628 msg.relates_to = Some(Relation::Replacement(Replacement::new(
629 id.to_owned(),
630 msg.msgtype.clone().into(),
631 )));
618 let Some(edited_msg) = info.get_event(id) else {
619 let msg = "edited message not found in store";
620 return Err(UIError::Failure(msg.into()));
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());
632629 } else if let Some(thread_root) = self.scrollback.thread() {
633630 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);
635632 } 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);
637634 } else {
638635 // Internal state is wonky?
639636 }
640637 } 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);
642639 }
643640
644641 room.send_queue().send(msg.into()).await.map_err(IambError::from)?;
@@ -772,6 +769,37 @@ impl ChatState {
772769 }
773770}
774771
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
775803macro_rules! delegate {
776804 ($s: expr, $id: ident => $e: expr) => {
777805 match $s.focus {
@@ -1161,6 +1189,31 @@ fn open_command(open_command: Option<&Vec<String>>, target: OsString) -> IambRes
11611189 }
11621190}
11631191
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
11641217fn cmd(open_command: &Vec<String>) -> Option<Command> {
11651218 if let [program, args @ ..] = open_command.as_slice() {
11661219 let mut cmd = Command::new(program);
src/worker.rs +51 −9
@@ -9,11 +9,13 @@ use std::sync::mpsc::{Receiver, SyncSender, sync_channel};
99use futures::StreamExt;
1010use futures::stream::FuturesUnordered;
1111use gethostname::gethostname;
12use matrix_sdk::OwnedServerName;
1213use matrix_sdk::authentication::matrix::MatrixSession;
1314use matrix_sdk::config::{RequestConfig, SyncSettings};
1415use matrix_sdk::encryption::{BackupDownloadStrategy, EncryptionSettings};
1516use matrix_sdk::event_handler::Ctx;
1617use matrix_sdk::room::{Messages as MatrixMessages, MessagesOptions, RoomMember};
18use matrix_sdk::ruma::OwnedRoomAliasId;
1719use matrix_sdk::ruma::api::client::filter::{
1820 FilterDefinition,
1921 LazyLoadOptions,
@@ -705,7 +707,8 @@ pub enum WorkerTask {
705707 Logout(String, ClientReply<IambResult<EditInfo>>),
706708 GetInviter(MatrixRoom, ClientReply<IambResult<Option<RoomMember>>>),
707709 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>>),
709712 Members(OwnedRoomId, ClientReply<IambResult<Vec<RoomMember>>>),
710713 SpaceMembers(OwnedRoomId, ClientReply<IambResult<Vec<OwnedRoomId>>>),
711714 TypingNotice(OwnedRoomId),
@@ -739,9 +742,16 @@ impl Debug for WorkerTask {
739742 .field(&format_args!("_"))
740743 .finish()
741744 },
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, _) => {
743752 f.debug_tuple("WorkerTask::JoinRoom")
744753 .field(s)
754 .field(via)
745755 .field(&format_args!("_"))
746756 .finish()
747757 },
@@ -915,10 +925,18 @@ impl Requester {
915925 return response.recv();
916926 }
917927
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> {
919937 let (reply, response) = oneshot();
920938
921 self.tx.send(WorkerTask::JoinRoom(name, reply)).unwrap();
939 self.tx.send(WorkerTask::JoinRoom(name, via, reply)).unwrap();
922940
923941 return response.recv();
924942 }
@@ -1012,9 +1030,13 @@ impl ClientWorker {
10121030 self.init(store).await;
10131031 reply.send(());
10141032 },
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) => {
10161038 assert!(self.initialized);
1017 reply.send(self.join_room(room_id).await);
1039 reply.send(self.join_room(name, via).await);
10181040 },
10191041 WorkerTask::GetInviter(invited, reply) => {
10201042 assert!(self.initialized);
@@ -1483,7 +1505,11 @@ impl ClientWorker {
14831505
14841506 async fn get_room(&mut self, room_id: OwnedRoomId) -> IambResult<FetchedRoom> {
14851507 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 };
14871513 let tags = room.tags().await.map_err(IambError::from)?;
14881514
14891515 Ok((room, name, tags))
@@ -1492,9 +1518,25 @@ impl ClientWorker {
14921518 }
14931519 }
14941520
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> {
14961538 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 {
14981540 Ok(resp) => Ok(resp.room_id().to_owned()),
14991541 Err(e) => {
15001542 let msg = e.to_string();