Commit 1de8891b62

1de8891b622d07d4ac4b53edddc2b503cf62123f

parent: f7ac4cc4d3

Unregistered key

vaw <git@nlih.de> · 2026-09-25 04:49 UTC
committer: <noreply@github.com>

Show preview information for unjoined rooms (#732)

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

Layout: unified · split

Cargo.lock +1
@@ -2545,6 +2545,7 @@ dependencies = [
25452545 "nom 8.0.0",
25462546 "notify-rust",
25472547 "open",
2548 "percent-encoding",
25482549 "pretty_assertions",
25492550 "ratatui",
25502551 "ratatui-image",
Cargo.toml +2 −1
@@ -69,7 +69,8 @@ tracing-appender = "0.2.2"
6969tracing-subscriber = { version = "0.3.16", features = ["env-filter"] }
7070unicode-segmentation = "1.7"
7171unicode-width = "0.2"
72url = {version = "2.2.2", features = ["serde"]}
72url = {version = "2.5.8", features = ["serde"]}
73percent-encoding = "2.3.2"
7374
7475[dependencies.comrak]
7576version = "0.55.0"
docs/iamb.1 +4
@@ -156,8 +156,12 @@ Accept an invitation to the currently focused room.
156156Reject an invitation to the currently focused room.
157157.It Sy ":invite send [user]"
158158Send an invitation to a user to join the currently focused room.
159.It Sy ":join"
160Join the focused preview room.
159161.It Sy ":join [room]"
160162Join a room or open it if you are already joined.
163.It Sy ":knock"
164Request to join the focused preview room.
161165.It Sy ":knock accept [user]"
162166Accept a knock from the specified user in the currently focused room.
163167.It Sy ":knock ban [user] [reason]"
src/base.rs +94 −92
@@ -44,11 +44,11 @@ use modalkit::env::vim::command::{CommandContext, VimCommand, VimCommandMachine}
4444use modalkit::env::vim::keybindings::VimMachine;
4545use modalkit::errors::UIResult;
4646use modalkit::keybindings::SequenceStatus;
47use percent_encoding::{NON_ALPHANUMERIC, percent_decode, percent_encode};
4748use serde::de::Error as SerdeError;
4849use serde::de::Visitor;
4950use serde::{Deserialize, Deserializer, Serialize, Serializer};
5051use tokio::sync::Mutex as AsyncMutex;
51use url::form_urlencoded;
5252
5353use crate::message::poll::{
5454 Poll,
@@ -543,6 +543,16 @@ pub enum RoomAction {
543543 SetUnread(bool),
544544}
545545
546/// An action that joins a room.
547#[derive(Clone, Debug, Eq, PartialEq)]
548pub enum JoinAction {
549 /// Join the focused room.
550 Join,
551
552 /// Knock on the focused room.
553 Knock,
554}
555
546556/// An action that sends a message to a room.
547557#[derive(Clone, Debug, Eq, PartialEq)]
548558pub enum SendAction {
@@ -618,12 +628,15 @@ pub enum IambAction {
618628 /// Perform an action on the current space.
619629 Space(SpaceAction),
620630
621 /// Open a URL (and specify whether to join linked matrix rooms).
622 OpenLink(String, bool),
631 /// Open a URL.
632 OpenLink(String),
623633
624634 /// Perform an action on the currently focused room.
625635 Room(RoomAction),
626636
637 /// Join the focused room preview.
638 Join(JoinAction),
639
627640 /// Send a message to the currently focused room.
628641 Send(SendAction),
629642
@@ -674,6 +687,12 @@ impl From<RoomAction> for IambAction {
674687 }
675688}
676689
690impl From<JoinAction> for IambAction {
691 fn from(act: JoinAction) -> Self {
692 IambAction::Join(act)
693 }
694}
695
677696impl From<SendAction> for IambAction {
678697 fn from(act: SendAction) -> Self {
679698 IambAction::Send(act)
@@ -702,6 +721,7 @@ impl ApplicationAction for IambAction {
702721 IambAction::Verify(..) => SequenceStatus::Break,
703722 IambAction::VerifyRequest(..) => SequenceStatus::Break,
704723 IambAction::Recover(..) => SequenceStatus::Break,
724 IambAction::Join(..) => SequenceStatus::Break,
705725 }
706726 }
707727
@@ -720,6 +740,7 @@ impl ApplicationAction for IambAction {
720740 IambAction::Verify(..) => SequenceStatus::Atom,
721741 IambAction::VerifyRequest(..) => SequenceStatus::Atom,
722742 IambAction::Recover(..) => SequenceStatus::Atom,
743 IambAction::Join(..) => SequenceStatus::Atom,
723744 }
724745 }
725746
@@ -738,6 +759,7 @@ impl ApplicationAction for IambAction {
738759 IambAction::Verify(..) => SequenceStatus::Ignore,
739760 IambAction::VerifyRequest(..) => SequenceStatus::Ignore,
740761 IambAction::Recover(..) => SequenceStatus::Ignore,
762 IambAction::Join(..) => SequenceStatus::Ignore,
741763 }
742764 }
743765
@@ -756,6 +778,7 @@ impl ApplicationAction for IambAction {
756778 IambAction::Verify(..) => false,
757779 IambAction::VerifyRequest(..) => false,
758780 IambAction::Recover(..) => false,
781 IambAction::Join(..) => false,
759782 }
760783 }
761784}
@@ -2273,6 +2296,7 @@ pub struct Need {
22732296#[derive(Default, Debug)]
22742297pub struct RoomNeeds {
22752298 needs: HashMap<OwnedRoomId, Need>,
2299 previews: HashSet<OwnedRoomOrAliasId>,
22762300}
22772301
22782302impl RoomNeeds {
@@ -2308,6 +2332,16 @@ impl RoomNeeds {
23082332 .extend(message_needs);
23092333 }
23102334
2335 /// Request the load of a room preview.
2336 pub fn need_preview(&mut self, room: OwnedRoomOrAliasId) {
2337 self.previews.insert(room);
2338 }
2339
2340 /// Return all requested room previews
2341 pub fn preview_needs(&mut self) -> impl Iterator<Item = OwnedRoomOrAliasId> {
2342 std::mem::take(&mut self.previews).into_iter()
2343 }
2344
23112345 pub fn rooms(&self) -> usize {
23122346 self.needs.len()
23132347 }
@@ -2333,8 +2367,17 @@ pub struct ChatStore {
23332367 /// Map of joined rooms.
23342368 pub rooms: CompletionMap<OwnedRoomId, RoomInfo>,
23352369
2336 /// Map of room names.
2337 pub names: CompletionMap<OwnedRoomAliasId, OwnedRoomId>,
2370 /// Map of loaded room previews with their fetch time
2371 pub room_previews:
2372 HashMap<OwnedRoomOrAliasId, (Result<RoomPreview, matrix_sdk::Error>, Instant)>,
2373
2374 /// Cache of encountered `via` parameters in room links.
2375 ///
2376 /// This is stored here because this data is lost in the conversion to [IambId].
2377 pub room_via: HashMap<OwnedRoomOrAliasId, Vec<OwnedServerName>>,
2378
2379 /// Map of room aliases.
2380 pub aliases: CompletionMap<OwnedRoomAliasId, OwnedRoomId>,
23382381
23392382 /// Presence information for other users.
23402383 pub presences: CompletionMap<OwnedUserId, PresenceState>,
@@ -2391,8 +2434,10 @@ impl ChatStore {
23912434 emojis: emoji_map(),
23922435
23932436 collator: Default::default(),
2394 names: Default::default(),
2437 aliases: Default::default(),
23952438 rooms: Default::default(),
2439 room_previews: Default::default(),
2440 room_via: Default::default(),
23962441 presences: Default::default(),
23972442 verifications: Default::default(),
23982443 need_load: Default::default(),
@@ -2438,7 +2483,17 @@ impl ChatStore {
24382483 }
24392484
24402485 /// Set the name and tags for a room.
2441 pub fn set_room_info(&mut self, room_id: OwnedRoomId, name: String, tags: Option<Tags>) {
2486 pub fn set_room_info(
2487 &mut self,
2488 room_id: OwnedRoomId,
2489 name: String,
2490 tags: Option<Tags>,
2491 aliases: Vec<OwnedRoomAliasId>,
2492 ) {
2493 for alias in aliases {
2494 self.aliases.insert(alias, room_id.clone());
2495 }
2496
24422497 let info = self.rooms.get_or_default(room_id);
24432498 info.name = name.into();
24442499 info.tags = tags;
@@ -2451,13 +2506,7 @@ impl ApplicationStore for ChatStore {}
24512506#[derive(Clone, Debug, Eq, Hash, PartialEq)]
24522507pub enum IambId {
24532508 /// A Matrix room, with an optional thread to show.
2454 Room(OwnedRoomId, Option<OwnedEventId>),
2455
2456 /// A Matrix room that we're currently in the middle of joining.
2457 Joining(String),
2458
2459 /// A Matrix room that we haven't joined, and aren't currently joining.
2460 NotJoined(String),
2509 Room(OwnedRoomOrAliasId, Option<OwnedEventId>),
24612510
24622511 /// The `:dms` window.
24632512 DirectList,
@@ -2493,38 +2542,16 @@ pub enum IambId {
24932542 InvitesList,
24942543}
24952544
2496/// Encode the room name for a [IambId::Joining] or [IambId::NotJoined] window URL.
2497///
2498/// Note that since these names come straight from the user's argument to `:join`,
2499/// they are likely room aliases containing characters like `#` that we should
2500/// escape before putting them into the URL, so we can later reparse it. They can
2501/// technically contain anything that the user tried to pass to `:join`.
2502fn room_query(room: &str) -> String {
2503 form_urlencoded::Serializer::new(String::new())
2504 .append_pair("room", room)
2505 .finish()
2506}
2507
2508/// Pull the room name back out of the query parameter for `iamb://joining` or
2509/// `iamb://not-joined`.
2510fn query_room(url: &Url) -> Option<String> {
2511 url.query_pairs().find_map(|(k, v)| (k == "room").then(|| v.into_owned()))
2512}
2513
25142545impl Display for IambId {
25152546 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25162547 match self {
2517 IambId::Room(room_id, None) => {
2518 write!(f, "iamb://room/{room_id}")
2519 },
2520 IambId::Room(room_id, Some(thread)) => {
2521 write!(f, "iamb://room/{room_id}/threads/{thread}")
2548 IambId::Room(alias, None) => {
2549 let encoded = percent_encode(alias.as_bytes(), NON_ALPHANUMERIC);
2550 write!(f, "iamb://room/{}", encoded)
25222551 },
2523 IambId::Joining(room) => {
2524 write!(f, "iamb://joining?{}", room_query(room))
2525 },
2526 IambId::NotJoined(room) => {
2527 write!(f, "iamb://not-joined?{}", room_query(room))
2552 IambId::Room(alias, Some(thread)) => {
2553 let encoded = percent_encode(alias.as_bytes(), NON_ALPHANUMERIC);
2554 write!(f, "iamb://room/{}/threads/{thread}", encoded)
25282555 },
25292556 IambId::MemberList(room_id) => {
25302557 write!(f, "iamb://members/{room_id}")
@@ -2594,16 +2621,18 @@ impl Visitor<'_> for IambIdVisitor {
25942621 };
25952622
25962623 match *path.collect::<Vec<_>>().as_slice() {
2597 [room_id] => {
2598 let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
2599 return Err(E::custom("Invalid room identifier"));
2624 [alias] => {
2625 let decoded = percent_decode(alias.as_bytes()).decode_utf8_lossy();
2626 let Ok(room_id) = OwnedRoomOrAliasId::try_from(decoded.as_ref()) else {
2627 return Err(E::custom(format!("Invalid room identifier: {decoded:?}")));
26002628 };
26012629
26022630 Ok(IambId::Room(room_id, None))
26032631 },
2604 [room_id, "threads", thread_root] => {
2605 let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
2606 return Err(E::custom("Invalid room identifier"));
2632 [alias, "threads", thread_root] => {
2633 let decoded = percent_decode(alias.as_bytes()).decode_utf8_lossy();
2634 let Ok(room_id) = OwnedRoomOrAliasId::try_from(decoded.as_ref()) else {
2635 return Err(E::custom("Invalid room identifier: {decoded:?}"));
26072636 };
26082637
26092638 let Ok(thread_root) = OwnedEventId::try_from(thread_root) else {
@@ -2622,20 +2651,6 @@ impl Visitor<'_> for IambIdVisitor {
26222651 _ => return Err(E::custom("Invalid iamb window URL")),
26232652 }
26242653 },
2625 Some("joining") => {
2626 let Some(room) = query_room(&url) else {
2627 return Err(E::custom("iamb://joining requires a room parameter"));
2628 };
2629
2630 Ok(IambId::Joining(room))
2631 },
2632 Some("not-joined") => {
2633 let Some(room) = query_room(&url) else {
2634 return Err(E::custom("iamb://not-joined requires a room parameter"));
2635 };
2636
2637 Ok(IambId::NotJoined(room))
2638 },
26392654 Some("members") => {
26402655 let Some(path) = url.path_segments() else {
26412656 return Err(E::custom("Invalid members window URL"));
@@ -2800,7 +2815,9 @@ impl IambBufferId {
28002815 pub fn to_window(&self) -> Option<IambId> {
28012816 let id = match self {
28022817 IambBufferId::Command(_) => return None,
2803 IambBufferId::Room(room, thread, _) => IambId::Room(room.clone(), thread.clone()),
2818 IambBufferId::Room(room, thread, _) => {
2819 IambId::Room(room.clone().into(), thread.clone())
2820 },
28042821 IambBufferId::DirectList => IambId::DirectList,
28052822 IambBufferId::MemberList(room) => IambId::MemberList(room.clone()),
28062823 IambBufferId::PinnedList(room) => IambId::PinnedList(room.clone()),
@@ -3131,35 +3148,6 @@ pub mod tests {
31313148 );
31323149 }
31333150
3134 #[test]
3135 fn test_unjoined_window_ids() {
3136 // Room names come from the user can contain characters that need escaping:
3137 for name in [
3138 "#foo:example.com",
3139 "!abc123:example.com",
3140 "@user:example.com",
3141 "a b&c=d?e#f",
3142 ] {
3143 for id in [IambId::Joining(name.into()), IambId::NotJoined(name.into())] {
3144 let json = serde_json::to_string(&id).unwrap();
3145 assert_eq!(serde_json::from_str::<IambId>(&json).unwrap(), id);
3146 }
3147 }
3148
3149 assert_eq!(
3150 IambId::Joining("#foo:example.com".into()).to_string(),
3151 "iamb://joining?room=%23foo%3Aexample.com"
3152 );
3153 assert_eq!(
3154 IambId::NotJoined("#foo:example.com".into()).to_string(),
3155 "iamb://not-joined?room=%23foo%3Aexample.com"
3156 );
3157
3158 // A window URL without a room name isn't valid and wasn't written by us:
3159 assert!(serde_json::from_str::<IambId>("\"iamb://joining\"").is_err());
3160 assert!(serde_json::from_str::<IambId>("\"iamb://not-joined\"").is_err());
3161 }
3162
31633151 #[test]
31643152 fn test_need_load() {
31653153 let room_id = TEST_ROOM1_ID.clone();
@@ -3217,6 +3205,20 @@ pub mod tests {
32173205 assert!(info.get_message_location(&unloaded).is_none());
32183206 }
32193207
3208 #[test]
3209 fn test_alias_window_id() {
3210 let room_id = TEST_ROOM1_ALIAS.clone();
3211 let id = IambId::Room(room_id.into(), None);
3212
3213 // Hash gets replaced during encoding:
3214 let exp = "iamb://room/%23room1%3Aexample%2Ecom";
3215 assert_eq!(id.to_string(), exp);
3216
3217 // Percent encoding turns back into hash during decoding:
3218 let parsed: IambId = serde_json::from_str(&format!("{exp:?}")).unwrap();
3219 assert_eq!(parsed, id);
3220 }
3221
32203222 #[test]
32213223 fn test_pinned_window_id() {
32223224 let room_id = TEST_ROOM1_ID.clone();
src/commands.rs +16 −3
@@ -122,6 +122,12 @@ fn iamb_keys(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
122122fn iamb_knock(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
123123 let mut args = desc.arg.strings()?;
124124
125 if args.is_empty() {
126 let act = IambAction::from(JoinAction::Knock);
127 let step = CommandStep::Continue(act.into(), ctx.context.clone());
128 return Ok(step);
129 }
130
125131 if args.len() < 2 || args.len() > 3 {
126132 return Err(CommandError::InvalidArgument);
127133 }
@@ -601,10 +607,16 @@ fn iamb_welcome(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
601607fn iamb_join(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
602608 let mut args = desc.arg.filenames()?;
603609
604 if args.len() != 1 {
610 if args.len() > 1 {
605611 return Result::Err(CommandError::InvalidArgument);
606612 }
607613
614 if args.is_empty() {
615 let act = IambAction::from(JoinAction::Join);
616 let step = CommandStep::Continue(act.into(), ctx.context.clone());
617 return Ok(step);
618 }
619
608620 let open = ctx.switch(args.remove(0));
609621 let step = CommandStep::Continue(open, ctx.context.clone());
610622
@@ -1331,8 +1343,9 @@ mod tests {
13311343 let act = WindowAction::Switch(OpenTarget::Alternate);
13321344 assert_eq!(res, vec![(act.into(), ctx.clone())]);
13331345
1334 let res = cmds.input_cmd("join", ctx.clone());
1335 assert_eq!(res, Err(CommandError::InvalidArgument));
1346 let res = cmds.input_cmd("join", ctx.clone()).unwrap();
1347 let act = IambAction::Join(JoinAction::Join);
1348 assert_eq!(res, vec![(act.into(), ctx.clone())]);
13361349
13371350 let res = cmds.input_cmd("join foo bar", ctx.clone());
13381351 assert_eq!(res, Err(CommandError::InvalidArgument));
src/completions.rs +3 −3
@@ -261,7 +261,7 @@ fn complete_users(input: &str, store: &ChatStore) -> Vec<String> {
261261
262262/// Tab completion for Matrix identifiers (usernames, room aliases, etc.)
263263fn complete_matrix_names(input: &str, store: &ChatStore) -> Vec<String> {
264 let list = store.names.complete(input);
264 let list = store.aliases.complete(input);
265265 if !list.is_empty() {
266266 return list.into_iter().map(|i| i.to_string()).collect();
267267 }
@@ -276,7 +276,7 @@ fn complete_matrix_names(input: &str, store: &ChatStore) -> Vec<String> {
276276
277277/// Tab completion for known room aliases and ids.
278278fn complete_room_alias_or_id(input: &str, store: &ChatStore) -> Vec<String> {
279 let list = store.names.complete(input);
279 let list = store.aliases.complete(input);
280280 if !list.is_empty() {
281281 return list.into_iter().map(|i| i.to_string()).collect();
282282 }
@@ -722,7 +722,7 @@ fn complete_msgbar(
722722 }
723723
724724 store
725 .names
725 .aliases
726726 .complete(id.as_ref())
727727 .into_iter()
728728 .map(|i| format!("[{}]", i))
src/main.rs +44 −88
@@ -24,8 +24,8 @@ use std::process;
2424use std::sync::atomic::AtomicUsize;
2525
2626use clap::{CommandFactory, Parser};
27use matrix_sdk::OwnedServerName;
2728use matrix_sdk::ruma::api::error::ErrorKind;
28use matrix_sdk::{OwnedServerName, RoomState};
2929use modalkit::actions::{Commandable, TabAction, TabContainer, TabCount, WindowContainer};
3030use modalkit::crossterm;
3131use modalkit::crossterm::cursor::SetCursorStyle;
@@ -76,20 +76,17 @@ fn config_tab_to_desc(
7676) -> IambResult<WindowLayoutDescription<IambInfo>> {
7777 let desc = match layout {
7878 config::WindowLayout::Window { window } => {
79 let ChatStore { names, worker, settings, .. } = &mut store.application;
80 let via = settings.tunables.default_via.clone();
81
8279 let window = match window {
8380 config::WindowPath::UserId(user_id) => {
84 let room_id = worker.join_room(user_id.to_string(), via)?;
85 IambId::Room(room_id, None)
86 },
87 config::WindowPath::RoomId(room_id) => IambId::Room(room_id, None),
88 config::WindowPath::AliasId(alias) => {
89 let room_id = worker.join_room(alias.to_string(), via)?;
90 names.insert(alias, room_id.clone());
91 IambId::Room(room_id, None)
81 if let Some(dm) = store.application.worker.client.get_dm_room(&user_id) {
82 IambId::Room(dm.room_id().to_owned().into(), None)
83 } else {
84 let room_id = store.application.worker.create_dm(user_id)?;
85 IambId::Room(room_id.into(), None)
86 }
9287 },
88 config::WindowPath::RoomId(room_id) => IambId::Room(room_id.into(), None),
89 config::WindowPath::AliasId(alias_id) => IambId::Room(alias_id.into(), None),
9390 config::WindowPath::Window(id) => id,
9491 };
9592
@@ -119,66 +116,40 @@ fn restore_layout(
119116 tabs.to_layout(area.into(), store)
120117}
121118
122/// Returns the `IambId` for the new window or a string to query the user. If they answer `y` this
123/// function should be rerun with `join_or_create` set to `true`.
124119fn resolve_mxid(
125120 store: &mut ProgramStore,
126121 id: MatrixId,
127 via: &[OwnedServerName],
128 join_or_create: bool,
129) -> IambResult<Result<IambId, String>> {
130 let room_name;
131 let room_id = match id {
132 MatrixId::Room(id) => {
133 room_name = id.to_string();
134 id
135 },
136 MatrixId::RoomAlias(alias_id) => {
137 room_name = alias_id.to_string();
138 store.application.worker.resolve_alias(alias_id)?
122 via: Vec<OwnedServerName>,
123) -> IambResult<IambId> {
124 let alias_id = match id {
125 MatrixId::Room(room_id) => room_id.into(),
126 MatrixId::RoomAlias(alias) => {
127 if let Some(room_id) = store.application.aliases.get(&alias) {
128 room_id.to_owned().into()
129 } else {
130 alias.into()
131 }
139132 },
140133 MatrixId::User(user_id) => {
141 let id = match store.application.worker.client.get_dm_room(&user_id) {
142 Some(room) => room.room_id().to_owned(),
143 None if join_or_create => {
144 store.application.worker.join_room(user_id.to_string(), via.to_owned())?
145 },
146 None => return Ok(Err(format!("No dm with {user_id} found. Create new DM?"))),
147 };
148 room_name = id.to_string();
149 id
150 },
151 MatrixId::Event(owned_room_or_alias_id, _event_id) => {
152 // ignore event id for now
153 room_name = owned_room_or_alias_id.to_string();
154 let room_or_alias_id: &matrix_sdk::ruma::RoomOrAliasId = &owned_room_or_alias_id;
155 if let Ok(alias_id) = <&matrix_sdk::ruma::RoomAliasId>::try_from(room_or_alias_id) {
156 store.application.worker.resolve_alias(alias_id.to_owned())?
134 if let Some(dm) = store.application.worker.client.get_dm_room(&user_id) {
135 dm.room_id().to_owned().into()
157136 } else {
158 matrix_sdk::ruma::OwnedRoomId::try_from(owned_room_or_alias_id).unwrap()
137 store.application.worker.create_dm(user_id.to_owned())?.into()
159138 }
160139 },
140 MatrixId::Event(alias_id, _) => {
141 // ignore event id for now
142 alias_id
143 },
161144 _ => {
162145 tracing::error!("encountered unrecoginsed matrix id: {id:?}");
163 return Ok(Err("Matrix link cannot be opened. Press 'n' to continue.".to_owned()));
146 return Err(UIError::Failure("Matrix link cannot be opened.".to_string()));
164147 },
165148 };
166149
167 if store
168 .application
169 .worker
170 .client
171 .get_room(&room_id)
172 .is_none_or(|room| room.state() != RoomState::Joined)
173 {
174 if join_or_create {
175 store.application.worker.join_room(room_name, via.to_owned())?;
176 } else {
177 return Ok(Err(format!("Join room {room_name:?}?")));
178 }
179 }
150 store.application.room_via.insert(alias_id.to_owned(), via);
180151
181 Ok(Ok(IambId::Room(room_id, None)))
152 Ok(IambId::Room(alias_id, None))
182153}
183154
184155fn setup_screen(
@@ -191,24 +162,12 @@ fn setup_screen(
191162 let area = Rect::new(0, 0, dims.0, dims.1);
192163
193164 if let Some((id, via)) = initial_room {
194 match resolve_mxid(store, id.clone(), &via, false)? {
165 match resolve_mxid(store, id, via) {
195166 Ok(id) => {
196167 return Ok(ScreenState::new(IambWindow::open(id, store)?, cmd));
197168 },
198 Err(question) => {
199 restore_tty(false, settings.tunables.mouse.enabled);
200 let join_or_create = loop {
201 match read_yesno(&format!("{question} [y]es/[n]o")) {
202 Some('y') => break true,
203 Some('n') => break false,
204 Some(_) | None => continue,
205 }
206 };
207 setup_tty(&settings)?;
208
209 if join_or_create && let Ok(id) = resolve_mxid(store, id, &via, true)? {
210 return Ok(ScreenState::new(IambWindow::open(id, store)?, cmd));
211 }
169 Err(err) => {
170 store.application.draw_error = Some(format!("layout restore: {err}"));
212171 },
213172 }
214173 }
@@ -646,6 +605,12 @@ impl Application {
646605
647606 None
648607 },
608 IambAction::Join(act) => {
609 let acts = self.screen.current_window_mut()?.join_command(act, ctx, store).await?;
610 self.action_prepend(acts);
611
612 None
613 },
649614 IambAction::Send(act) => {
650615 if store.application.settings.tunables.normal_after_send {
651616 self.bindings.reset_mode();
@@ -653,7 +618,7 @@ impl Application {
653618 self.screen.current_window_mut()?.send_command(act, ctx, store).await?
654619 },
655620
656 IambAction::OpenLink(url, join_or_create) => {
621 IambAction::OpenLink(url) => {
657622 let matrix_uri = MatrixUri::parse(&url).ok();
658623 let matrix_to_uri = MatrixToUri::parse(&url).ok();
659624
@@ -663,20 +628,15 @@ impl Application {
663628 .or(matrix_to_uri.as_ref().map(|uri| (uri.id(), uri.via())));
664629
665630 if let Some((id, via)) = matrix_id {
666 match resolve_mxid(store, id.clone(), via, join_or_create)? {
667 Ok(room) => {
668 let target = OpenTarget::Application(room);
631 match resolve_mxid(store, id.to_owned(), via.to_vec()) {
632 Ok(id) => {
633 let target = OpenTarget::Application(id);
669634 let action = WindowAction::Switch(target);
670635
671636 self.action_prepend(vec![(action.into(), ctx)]);
672637 None
673638 },
674 Err(prompt) => {
675 let act = IambAction::OpenLink(url, true).into();
676 let dialog = PromptYesNo::new(prompt, vec![act]);
677 let err = UIError::NeedConfirm(Box::new(dialog));
678 return Err(err);
679 },
639 Err(err) => return Err(UIError::Failure(err.to_string())),
680640 }
681641 } else {
682642 tokio::task::spawn_blocking(move || open::that(url));
@@ -713,7 +673,7 @@ impl Application {
713673 HomeserverAction::CreateRoom(alias, vis, flags) => {
714674 let client = &store.application.worker.client;
715675 let room_id = create_room(client, alias, vis, flags).await?;
716 let room = IambId::Room(room_id, None);
676 let room = IambId::Room(room_id.into(), None);
717677 let target = OpenTarget::Application(room);
718678 let action = WindowAction::Switch(target);
719679
@@ -916,10 +876,6 @@ fn read_response(question: &str) -> String {
916876 input
917877}
918878
919fn read_yesno(question: &str) -> Option<char> {
920 read_response(question).chars().next().map(|c| c.to_ascii_lowercase())
921}
922
923879async fn login(worker: &Requester, settings: &ApplicationSettings) -> IambResult<()> {
924880 if settings.session_json.is_file() {
925881 let session = settings.read_session(&settings.session_json)?;
src/prelude.rs +2
@@ -9,6 +9,7 @@ pub use std::str::FromStr;
99pub use std::sync::Arc;
1010pub use std::time::{Duration, Instant};
1111
12pub use matrix_sdk::room_preview::RoomPreview;
1213pub use matrix_sdk::ruma::events::AnySyncStateEvent;
1314pub use matrix_sdk::ruma::events::receipt::ReceiptThread;
1415pub use matrix_sdk::ruma::events::relation::Thread;
@@ -78,6 +79,7 @@ pub use crate::base::{
7879 IambId,
7980 IambInfo,
8081 IambResult,
82 JoinAction,
8183 MessageAction,
8284 ProgramAction,
8385 ProgramContext,
src/tests.rs +1 −1
@@ -257,7 +257,7 @@ pub async fn mock_store() -> ProgramStore {
257257 let info = mock_room();
258258
259259 store.rooms.insert(room_id.clone(), info);
260 store.names.insert(TEST_ROOM1_ALIAS.clone(), room_id);
260 store.aliases.insert(TEST_ROOM1_ALIAS.clone(), room_id);
261261
262262 ProgramStore::new(store)
263263}
src/windows/mod.rs +64 −29
@@ -13,7 +13,7 @@ use std::fmt::{self};
1313use feruca::Collator;
1414use matrix_sdk::room::RoomMember;
1515use matrix_sdk::ruma::events::room::member::MembershipState;
16use matrix_sdk::ruma::{RoomAliasId, assign};
16use matrix_sdk::ruma::{RoomAliasId, RoomOrAliasId, assign};
1717use modalkit::editing::completion::CompletionMap;
1818use modalkit_ratatui::Window;
1919use modalkit_ratatui::list::{List, ListCursor, ListItem, ListState};
@@ -242,7 +242,7 @@ fn room_prompt(
242242) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
243243 match act {
244244 PromptAction::Submit => {
245 let room = IambId::Room(room_id.to_owned(), None);
245 let room = IambId::Room(room_id.to_owned().into(), None);
246246 let open = WindowAction::Switch(OpenTarget::Application(room));
247247 let acts = vec![(open.into(), ctx.clone())];
248248
@@ -352,7 +352,7 @@ impl IambWindow {
352352 store: &mut ProgramStore,
353353 ) -> IambResult<Vec<(Action<IambInfo>, ProgramContext)>> {
354354 let id = match self {
355 IambWindow::Room(state) => state.id(),
355 IambWindow::Room(state) => state.id(store),
356356 IambWindow::MemberList(_, room_id, _) => Some(&**room_id),
357357 IambWindow::PinnedList(_, room_id, _) => Some(&**room_id),
358358
@@ -373,6 +373,19 @@ impl IambWindow {
373373 }
374374 }
375375
376 pub async fn join_command(
377 &mut self,
378 act: JoinAction,
379 ctx: ProgramContext,
380 store: &mut ProgramStore,
381 ) -> IambResult<Vec<(Action<IambInfo>, ProgramContext)>> {
382 if let IambWindow::Room(w) = self {
383 w.join_command(act, ctx, store).await
384 } else {
385 return Err(IambError::NoSelectedRoom.into());
386 }
387 }
388
376389 pub async fn send_command(
377390 &mut self,
378391 act: SendAction,
@@ -472,7 +485,7 @@ impl WindowOps<IambInfo> for IambWindow {
472485 fn draw(&mut self, area: Rect, buf: &mut Buffer, focused: bool, store: &mut ProgramStore) {
473486 let ChatStore {
474487 collator,
475 names,
488 aliases,
476489 rooms,
477490 settings,
478491 sync_info,
@@ -490,7 +503,7 @@ impl WindowOps<IambInfo> for IambWindow {
490503 let mut items = sync_info
491504 .dms
492505 .iter()
493 .map(|room| GenericRoomItem::new_unspecified(room, rooms, names))
506 .map(|room| GenericRoomItem::new_unspecified(room, rooms, aliases))
494507 .collect::<Vec<_>>();
495508 let fields = &settings.tunables.sort.dms;
496509 items.sort_by(|a, b| room_fields_cmp(a, b, fields, collator));
@@ -563,7 +576,7 @@ impl WindowOps<IambInfo> for IambWindow {
563576 let mut items = sync_info
564577 .rooms
565578 .iter()
566 .map(|room| GenericRoomItem::new_unspecified(room, rooms, names))
579 .map(|room| GenericRoomItem::new_unspecified(room, rooms, aliases))
567580 .collect::<Vec<_>>();
568581 let fields = &settings.tunables.sort.rooms;
569582 items.sort_by(|a, b| room_fields_cmp(a, b, fields, collator));
@@ -583,7 +596,7 @@ impl WindowOps<IambInfo> for IambWindow {
583596 .rooms
584597 .iter()
585598 .chain(sync_info.dms.iter())
586 .map(|room| GenericRoomItem::new(room, rooms, names))
599 .map(|room| GenericRoomItem::new(room, rooms, aliases))
587600 .collect::<Vec<_>>();
588601
589602 let fields = &settings.tunables.sort.chats;
@@ -604,7 +617,7 @@ impl WindowOps<IambInfo> for IambWindow {
604617 .rooms
605618 .iter()
606619 .chain(sync_info.dms.iter())
607 .map(|room| GenericRoomItem::new(room, rooms, names))
620 .map(|room| GenericRoomItem::new(room, rooms, aliases))
608621 .filter(RoomLikeItem::is_unread)
609622 .collect::<Vec<_>>();
610623
@@ -626,7 +639,7 @@ impl WindowOps<IambInfo> for IambWindow {
626639 .rooms
627640 .iter()
628641 .chain(sync_info.dms.iter())
629 .map(|room| GenericRoomItem::new(room, rooms, names))
642 .map(|room| GenericRoomItem::new(room, rooms, aliases))
630643 .filter(RoomLikeItem::has_mention)
631644 .collect::<Vec<_>>();
632645
@@ -648,7 +661,7 @@ impl WindowOps<IambInfo> for IambWindow {
648661 .rooms
649662 .iter()
650663 .chain(sync_info.dms.iter())
651 .map(|room| GenericRoomItem::new(room, rooms, names))
664 .map(|room| GenericRoomItem::new(room, rooms, aliases))
652665 .filter(RoomLikeItem::is_invite)
653666 .collect::<Vec<_>>();
654667
@@ -669,7 +682,7 @@ impl WindowOps<IambInfo> for IambWindow {
669682 let mut items = sync_info
670683 .spaces
671684 .iter()
672 .map(|room| GenericRoomItem::new_unspecified(room, rooms, names))
685 .map(|room| GenericRoomItem::new_unspecified(room, rooms, aliases))
673686 .collect::<Vec<_>>();
674687
675688 let fields = &settings.tunables.sort.spaces;
@@ -854,21 +867,28 @@ impl Window<IambInfo> for IambWindow {
854867
855868 fn open(id: IambId, store: &mut ProgramStore) -> IambResult<Self> {
856869 match id {
857 IambId::Room(room_id, thread) => {
858 let (room, name, tags) = store.application.worker.get_room(room_id)?;
859 let room = RoomState::new(room, thread, name, tags, store);
870 IambId::Room(alias_id, thread) => {
871 let alias: &RoomOrAliasId = &alias_id;
872 let room_id = match <&RoomId>::try_from(alias) {
873 Ok(room_id) => room_id,
874 Err(alias) => {
875 if let Some(room_id) = store.application.aliases.get(alias) {
876 room_id
877 } else {
878 return Ok(RoomState::not_joined(alias_id, store).into());
879 }
880 },
881 };
860882
861 if let Some(room_id) = room.id() {
883 if let Some(room) = store.application.worker.client.get_room(room_id) {
862884 store.application.need_load.need_members(room_id.to_owned());
885
886 let room = RoomState::new(room, thread, store);
887
888 return Ok(room.into());
863889 }
864890
865 return Ok(room.into());
866 },
867 IambId::Joining(name) => {
868 return Ok(RoomState::join(name, store).into());
869 },
870 IambId::NotJoined(name) => {
871 return Ok(RoomState::not_joined(name).into());
891 return Ok(RoomState::not_joined(alias_id, store).into());
872892 },
873893 IambId::DirectList => {
874894 let list = RoomListState::new(IambBufferId::DirectList, vec![]);
@@ -933,13 +953,28 @@ impl Window<IambInfo> for IambWindow {
933953 }
934954
935955 fn find(name: String, store: &mut ProgramStore) -> IambResult<Self> {
936 if let Some(room) = store.application.names.get(&name) {
937 let id = IambId::Room(room.clone(), None);
938 IambWindow::open(id, store)
956 let room_alias = if let Ok(alias) = <&RoomAliasId>::try_from(name.as_str()) {
957 if let Some(room_id) = store.application.aliases.get(alias) {
958 room_id.to_owned().into()
959 } else {
960 alias.to_owned().into()
961 }
962 } else if let Ok(room_id) = <&RoomId>::try_from(name.as_str()) {
963 room_id.to_owned().into()
964 } else if let Ok(user_id) = <&UserId>::try_from(name.as_str()) {
965 if let Some(dm) = store.application.worker.client.get_dm_room(user_id) {
966 dm.room_id().to_owned().into()
967 } else {
968 store.application.worker.create_dm(user_id.to_owned())?.into()
969 }
939970 } else {
940 let room = RoomState::join(name, store);
941 Ok(room.into())
942 }
971 // XXX: support passing matrix uris to `:join`
972
973 return Err(UIError::Failure("Could not parse room identifier".to_string()));
974 };
975
976 let id = IambId::Room(room_alias, None);
977 IambWindow::open(id, store)
943978 }
944979
945980 fn posn(index: usize, _: &mut ProgramStore) -> IambResult<Self> {
@@ -1348,7 +1383,7 @@ impl Promptable<ProgramContext, ProgramStore, IambInfo> for PinnedItem {
13481383 .and_then(|(thread, _)| thread)
13491384 .map(ToOwned::to_owned);
13501385
1351 let room = IambId::Room(self.room_id.clone(), thread);
1386 let room = IambId::Room(self.room_id.clone().into(), thread);
13521387 let open = WindowAction::Switch(OpenTarget::Application(room));
13531388 let jump = IambAction::from(TimelineAction::GotoEvent(self.event_id.clone()));
13541389
src/windows/room/chat.rs +1 −1
@@ -958,7 +958,7 @@ fn open_links(msg: &Message) -> UIError<IambInfo> {
958958 .into_iter()
959959 .map(|l| {
960960 let url = l.1.to_string();
961 let act = IambAction::OpenLink(url.clone(), false).into();
961 let act = IambAction::OpenLink(url.clone()).into();
962962 MultiChoiceItem::new(l.0, url, vec![act])
963963 })
964964 .collect();
src/windows/room/joining.rs deleted −98
@@ -1,98 +0,0 @@
1use crate::prelude::*;
2use crate::worker::ClientResponse;
3
4pub struct JoiningState {
5 pub(super) room: String,
6 room_id: Option<IambResult<OwnedRoomId>>,
7 chan: ClientResponse<IambResult<OwnedRoomId>>,
8}
9
10impl JoiningState {
11 pub fn new(room: String, store: &mut ProgramStore) -> Self {
12 let via = store.application.settings.tunables.default_via.clone();
13 let chan = store.application.worker.join_room_chan(room.clone(), via);
14 Self { room, room_id: None, chan }
15 }
16
17 pub fn try_recv(&mut self) -> Option<&IambResult<OwnedRoomId>> {
18 if self.room_id.is_none() &&
19 let Some(id) = self.chan.try_recv()
20 {
21 self.room_id = Some(id);
22 }
23
24 self.room_id.as_ref()
25 }
26}
27
28impl Editable<ProgramContext, ProgramStore, IambInfo> for JoiningState {
29 fn editor_command(
30 &mut self,
31 _: &EditorAction,
32 _: &ProgramContext,
33 _: &mut ProgramStore,
34 ) -> EditResult<EditInfo, IambInfo> {
35 Ok(None)
36 }
37}
38
39impl Jumpable<ProgramContext, IambInfo> for JoiningState {
40 fn jump(
41 &mut self,
42 _: PositionList,
43 _: MoveDir1D,
44 count: usize,
45 _: &ProgramContext,
46 ) -> IambResult<usize> {
47 Ok(count)
48 }
49}
50
51impl Scrollable<ProgramContext, ProgramStore, IambInfo> for JoiningState {
52 fn scroll(
53 &mut self,
54 _: &ScrollStyle,
55 _: &ProgramContext,
56 _: &mut ProgramStore,
57 ) -> EditResult<EditInfo, IambInfo> {
58 Ok(None)
59 }
60}
61
62impl Promptable<ProgramContext, ProgramStore, IambInfo> for JoiningState {
63 fn prompt(
64 &mut self,
65 _: &PromptAction,
66 _: &ProgramContext,
67 _: &mut ProgramStore,
68 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
69 Ok(vec![])
70 }
71}
72
73impl TerminalCursor for JoiningState {
74 fn get_term_cursor(&self) -> Option<TermOffset> {
75 None
76 }
77
78 fn hide_term_cursor(&self) -> bool {
79 true
80 }
81}
82
83/// [StatefulWidget] for Matrix rooms being joined.
84pub struct Joining;
85
86impl StatefulWidget for Joining {
87 type State = JoiningState;
88
89 fn render(self, area: Rect, buffer: &mut Buffer, state: &mut Self::State) {
90 let line = Line::from(vec![
91 Span::raw("Joining "),
92 Span::styled(state.room.as_str(), StyleModifier::BOLD),
93 Span::raw("..."),
94 ]);
95
96 Paragraph::new(line).alignment(Alignment::Center).render(area, buffer);
97 }
98}
src/windows/room/mod.rs +56 −105
@@ -1,7 +1,6 @@
11//! # Windows for Matrix rooms and spaces
22use std::collections::HashSet;
33
4use matrix_sdk::RoomDisplayName;
54use matrix_sdk::notification_settings::RoomNotificationMode;
65use matrix_sdk::ruma::api::client::room::upgrade_room::v3::Request as UpgradeRoomRequest;
76use matrix_sdk::ruma::api::error::ErrorKind as ClientApiErrorKind;
@@ -19,12 +18,10 @@ use crate::base::{MemberUpdateAction, RoomField};
1918use crate::config::EncryptionIndicatorLocation;
2019use crate::prelude::*;
2120use crate::windows::room::chat::ChatState;
22use crate::windows::room::joining::{Joining, JoiningState};
2321use crate::windows::room::not_joined::{NotJoined, NotJoinedState};
2422use crate::windows::room::space::{Space, SpaceState};
2523
2624mod chat;
27mod joining;
2825mod not_joined;
2926mod scrollback;
3027mod space;
@@ -33,7 +30,6 @@ macro_rules! delegate {
3330 ($s: expr, $id: ident => $e: expr) => {
3431 match $s {
3532 RoomState::NotJoined($id) => $e,
36 RoomState::Joining($id) => $e,
3733 RoomState::Chat($id) => $e,
3834 RoomState::Space($id) => $e,
3935 }
@@ -93,7 +89,7 @@ pub async fn room_command(
9389 },
9490 };
9591
96 let id = IambId::Room(room_id.to_owned(), None);
92 let id = IambId::Room(room_id.to_owned().into(), None);
9793 let target = OpenTarget::Application(id);
9894 let act = cmd.switch(target);
9995
@@ -635,7 +631,7 @@ pub async fn room_command(
635631 request.additional_creators = additional_creators;
636632
637633 let response = worker.client.send(request).await.map_err(IambError::from)?;
638 let id = IambId::Room(response.replacement_room, None);
634 let id = IambId::Room(response.replacement_room.into(), None);
639635 let target = OpenTarget::Application(id);
640636 let act = WindowAction::Switch(target);
641637
@@ -651,7 +647,6 @@ pub async fn room_command(
651647/// similarly.
652648pub enum RoomState {
653649 NotJoined(Box<NotJoinedState>),
654 Joining(Box<JoiningState>),
655650 Chat(Box<ChatState>),
656651 Space(Box<SpaceState>),
657652}
@@ -662,12 +657,6 @@ impl From<NotJoinedState> for RoomState {
662657 }
663658}
664659
665impl From<JoiningState> for RoomState {
666 fn from(chat: JoiningState) -> Self {
667 RoomState::Joining(Box::new(chat))
668 }
669}
670
671660impl From<ChatState> for RoomState {
672661 fn from(chat: ChatState) -> Self {
673662 RoomState::Chat(Box::new(chat))
@@ -681,18 +670,7 @@ impl From<SpaceState> for RoomState {
681670}
682671
683672impl RoomState {
684 pub fn new(
685 room: MatrixRoom,
686 thread: Option<OwnedEventId>,
687 name: RoomDisplayName,
688 tags: Option<Tags>,
689 store: &mut ProgramStore,
690 ) -> Self {
691 let room_id = room.room_id().to_owned();
692 let info = store.application.get_room_info(room_id);
693 info.name = name.to_string().into();
694 info.tags = tags;
695
673 pub fn new(room: MatrixRoom, thread: Option<OwnedEventId>, store: &mut ProgramStore) -> Self {
696674 if room.is_space() {
697675 SpaceState::new(room).into()
698676 } else {
@@ -700,63 +678,46 @@ impl RoomState {
700678 }
701679 }
702680
703 pub fn join(name: String, store: &mut ProgramStore) -> Self {
704 let joining = JoiningState::new(name, store);
705 Self::from(joining)
706 }
707
708 pub fn not_joined(name: String) -> Self {
709 Self::from(NotJoinedState::new(name))
681 pub fn not_joined(alias: OwnedRoomOrAliasId, store: &mut ProgramStore) -> Self {
682 Self::from(NotJoinedState::new(alias, store))
710683 }
711684
712685 pub fn window_id(&self) -> IambId {
713686 match self {
714 RoomState::NotJoined(nj) => IambId::NotJoined(nj.room.clone()),
715 RoomState::Joining(joining) => IambId::Joining(joining.room.clone()),
716 RoomState::Chat(chat) => IambId::Room(chat.id().to_owned(), chat.thread().cloned()),
717 RoomState::Space(space) => IambId::Room(space.id().to_owned(), None),
687 RoomState::NotJoined(nj) => IambId::Room(nj.alias().to_owned(), None),
688 RoomState::Chat(chat) => {
689 IambId::Room(chat.id().to_owned().into(), chat.thread().cloned())
690 },
691 RoomState::Space(space) => IambId::Room(space.id().to_owned().into(), None),
718692 }
719693 }
720694
721695 pub fn room_state(&self) -> Option<MatrixRoomState> {
722696 match self {
723 RoomState::NotJoined(_) | RoomState::Joining(_) => None,
697 RoomState::NotJoined(_) => None,
724698 RoomState::Chat(chat) => Some(chat.room().state()),
725699 RoomState::Space(space) => Some(space.room().state()),
726700 }
727701 }
728702
729703 pub fn refresh_room(&mut self, store: &mut ProgramStore) {
704 if let Some(room) = self.room() &&
705 room.state() == MatrixRoomState::Left
706 {
707 // room previews have more information than left rooms
708 let alias_id = if let Some(alias) = room.canonical_alias() {
709 alias.into()
710 } else {
711 room.room_id().to_owned().into()
712 };
713 *self = Self::not_joined(alias_id, store);
714 }
715
730716 match self {
731 RoomState::NotJoined(_) => {},
732 RoomState::Joining(joining) => {
733 let joined = joining.room.clone();
734
735 let room_id = match joining.try_recv() {
736 None => return,
737 Some(Ok(room_id)) => room_id.clone(),
738 Some(Err(e)) => {
739 // We failed to join the room, so show the NotJoined window,
740 // and let the user try again if the error was transient:
741 *self = NotJoinedState::failed(joined, e).into();
742 return;
743 },
744 };
745
746 let Ok((room, name, tags)) = store.application.worker.get_room(room_id.clone())
747 else {
748 return;
749 };
750
751 if let Ok(alias) = OwnedRoomAliasId::try_from(joined.as_str()) {
752 // If the `:join` was for a room alias, then track it so
753 // we can reuse it later for `:join`/`:sp`/etc:
754 store.application.names.insert(alias, room_id.clone());
717 RoomState::NotJoined(not_joined) => {
718 if let Some(state) = not_joined.refresh_room(store) {
719 *self = state;
755720 }
756
757 store.application.need_load.need_members(room_id);
758
759 *self = RoomState::new(room, None, name, tags, store);
760721 },
761722 RoomState::Chat(chat) => chat.refresh_room(store),
762723 RoomState::Space(space) => space.refresh_room(store),
@@ -820,25 +781,6 @@ impl RoomState {
820781 return;
821782 }
822783
823 fn draw_left(&self, room: &MatrixRoom, area: Rect, buf: &mut Buffer, store: &mut ProgramStore) {
824 let name = match room.canonical_alias() {
825 Some(alias) => alias.to_string(),
826 None => format!("{:?}", store.application.get_room_title(room.room_id())),
827 };
828
829 let mut lines = vec![Line::from(format!("You have left {name}!"))];
830
831 if room.is_public().is_some_and(|b| b) {
832 lines.push(Line::from(format!("You can run `:join {name}` to rejoin.")));
833 }
834
835 let text = Text::from(lines);
836
837 Paragraph::new(text).alignment(Alignment::Center).render(area, buf);
838
839 return;
840 }
841
842784 pub async fn timeline_command(
843785 &mut self,
844786 act: TimelineAction,
@@ -878,6 +820,19 @@ impl RoomState {
878820 }
879821 }
880822
823 pub async fn join_command(
824 &mut self,
825 act: JoinAction,
826 ctx: ProgramContext,
827 store: &mut ProgramStore,
828 ) -> IambResult<Vec<(Action<IambInfo>, ProgramContext)>> {
829 if let RoomState::NotJoined(nj) = self {
830 nj.join_command(act, ctx, store).await
831 } else {
832 Err(IambError::NoSelectedSpace.into())
833 }
834 }
835
881836 pub async fn send_command(
882837 &mut self,
883838 act: SendAction,
@@ -897,7 +852,11 @@ impl RoomState {
897852 let title_style = theme.windows.title;
898853
899854 let Some(room) = self.room() else {
900 return Line::styled("Unjoined Room", title_style);
855 if let RoomState::NotJoined(nj) = self {
856 return nj.get_title(store);
857 } else {
858 return Line::styled("Unknown Room", title_style);
859 }
901860 };
902861
903862 let room_id = room.room_id();
@@ -939,17 +898,14 @@ impl RoomState {
939898 match self {
940899 RoomState::Space(w) => store.application.get_room_title(w.id()).into(),
941900 RoomState::Chat(w) => store.application.get_room_title(w.id()).into(),
942 RoomState::NotJoined(_) => Line::from("Unjoined Room"),
943 RoomState::Joining(w) => {
944 Line::from(vec![Span::raw("Joining "), Span::raw(w.room.as_str())])
945 },
901 RoomState::NotJoined(w) => w.get_tab_title(store),
946902 }
947903 }
948904
949905 pub fn focus_toggle(&mut self) {
950906 match self {
951907 RoomState::Chat(chat) => chat.focus_toggle(),
952 RoomState::Joining(_) | RoomState::NotJoined(_) | RoomState::Space(_) => return,
908 RoomState::NotJoined(_) | RoomState::Space(_) => return,
953909 }
954910 }
955911
@@ -957,15 +913,15 @@ impl RoomState {
957913 match self {
958914 RoomState::Chat(chat) => Some(chat.room()),
959915 RoomState::Space(space) => Some(space.room()),
960 RoomState::Joining(_) | RoomState::NotJoined(_) => None,
916 RoomState::NotJoined(_) => None,
961917 }
962918 }
963919
964 pub fn id(&self) -> Option<&RoomId> {
920 pub fn id(&mut self, store: &ProgramStore) -> Option<&RoomId> {
965921 match self {
966922 RoomState::Chat(chat) => Some(chat.id()),
967923 RoomState::Space(space) => Some(space.id()),
968 RoomState::Joining(_) | RoomState::NotJoined(_) => None,
924 RoomState::NotJoined(nj) => nj.room_id(store),
969925 }
970926 }
971927}
@@ -1035,7 +991,6 @@ impl WindowOps<IambInfo> for RoomState {
1035991 match room.state() {
1036992 MatrixRoomState::Invited => return self.draw_invite(room, area, buf, store),
1037993 MatrixRoomState::Knocked => return self.draw_knock(room, area, buf, store),
1038 MatrixRoomState::Left => return self.draw_left(room, area, buf, store),
1039994 _ => (),
1040995 }
1041996 }
@@ -1044,11 +999,8 @@ impl WindowOps<IambInfo> for RoomState {
1044999 RoomState::Chat(chat) => {
10451000 chat.draw(area, buf, focused, store);
10461001 },
1047 RoomState::Joining(state) => {
1048 Joining.render(area, buf, state);
1049 },
10501002 RoomState::NotJoined(state) => {
1051 NotJoined.render(area, buf, state);
1003 NotJoined::new(store).render(area, buf, state);
10521004 },
10531005 RoomState::Space(space) => {
10541006 Space::new(store).focus(focused).render(area, buf, space);
@@ -1058,8 +1010,7 @@ impl WindowOps<IambInfo> for RoomState {
10581010
10591011 fn dup(&self, store: &mut ProgramStore) -> Self {
10601012 match self {
1061 RoomState::Joining(w) => RoomState::join(w.room.clone(), store),
1062 RoomState::NotJoined(w) => RoomState::NotJoined((*w).clone()),
1013 RoomState::NotJoined(w) => RoomState::NotJoined(Box::new(w.dup())),
10631014 RoomState::Chat(chat) => RoomState::Chat(Box::new(chat.dup(store))),
10641015 RoomState::Space(space) => RoomState::Space(Box::new(space.dup(store))),
10651016 }
@@ -1067,7 +1018,7 @@ impl WindowOps<IambInfo> for RoomState {
10671018
10681019 fn close(&mut self, flags: CloseFlags, store: &mut ProgramStore) -> bool {
10691020 match self {
1070 RoomState::NotJoined(_) | RoomState::Joining(_) => true,
1021 RoomState::NotJoined(_) => true,
10711022 RoomState::Chat(chat) => chat.close(flags, store),
10721023 RoomState::Space(space) => space.close(flags, store),
10731024 }
@@ -1080,7 +1031,7 @@ impl WindowOps<IambInfo> for RoomState {
10801031 store: &mut ProgramStore,
10811032 ) -> IambResult<EditInfo> {
10821033 match self {
1083 RoomState::NotJoined(_) | RoomState::Joining(_) => Err(EditError::ReadOnly.into()),
1034 RoomState::NotJoined(_) => Err(EditError::ReadOnly.into()),
10841035 RoomState::Chat(chat) => chat.write(path, flags, store),
10851036 RoomState::Space(space) => space.write(path, flags, store),
10861037 }
@@ -1088,7 +1039,7 @@ impl WindowOps<IambInfo> for RoomState {
10881039
10891040 fn get_completions(&self) -> Option<CompletionList> {
10901041 match self {
1091 RoomState::NotJoined(_) | RoomState::Joining(_) => None,
1042 RoomState::NotJoined(_) => None,
10921043 RoomState::Chat(chat) => chat.get_completions(),
10931044 RoomState::Space(space) => space.get_completions(),
10941045 }
@@ -1096,7 +1047,7 @@ impl WindowOps<IambInfo> for RoomState {
10961047
10971048 fn get_cursor_word(&self, style: &WordStyle) -> Option<String> {
10981049 match self {
1099 RoomState::NotJoined(_) | RoomState::Joining(_) => None,
1050 RoomState::NotJoined(_) => None,
11001051 RoomState::Chat(chat) => chat.get_cursor_word(style),
11011052 RoomState::Space(space) => space.get_cursor_word(style),
11021053 }
@@ -1104,7 +1055,7 @@ impl WindowOps<IambInfo> for RoomState {
11041055
11051056 fn get_selected_word(&self) -> Option<String> {
11061057 match self {
1107 RoomState::NotJoined(_) | RoomState::Joining(_) => None,
1058 RoomState::NotJoined(_) => None,
11081059 RoomState::Chat(chat) => chat.get_selected_word(),
11091060 RoomState::Space(space) => space.get_selected_word(),
11101061 }
src/windows/room/not_joined.rs +268 −18
@@ -1,20 +1,200 @@
1use matrix_sdk::ruma::RoomOrAliasId;
2use matrix_sdk::ruma::room::{JoinRuleSummary, RestrictedSummary};
3
4use crate::base::{HomeserverAction, SyncInfo};
15use crate::prelude::*;
6use crate::windows::room::RoomState;
7use crate::worker::ClientResponse;
8
9const ROOM_PREVIEW_DEBOUNCE: Duration = Duration::from_secs(15);
10
11fn can_join_restricted(summary: &RestrictedSummary, sync_info: &SyncInfo) -> bool {
12 sync_info
13 .spaces
14 .iter()
15 .map(|r| r.room_id())
16 .chain(sync_info.chats())
17 .any(|room_id| summary.allowed_room_ids.iter().any(|allowed| allowed == room_id))
18}
19
20fn preview_join_rule(
21 preview: &RoomPreview,
22 store: &ProgramStore,
23) -> (&'static str, Option<&'static str>) {
24 match &preview.join_rule {
25 Some(JoinRuleSummary::Public) => ("This room is public.", Some(":join")),
26 Some(JoinRuleSummary::Knock) => ("This room is knock-only.", Some(":knock")),
27 Some(JoinRuleSummary::Invite) => ("This room is invite-only.", None),
28 Some(JoinRuleSummary::Restricted(summary)) => {
29 if can_join_restricted(summary, &store.application.sync_info) {
30 ("This room is restricted to members of a room you are in.", Some(":join"))
31 } else {
32 ("This room is restricted to members of a room you are not in.", None)
33 }
34 },
35 Some(JoinRuleSummary::KnockRestricted(summary)) => {
36 if can_join_restricted(summary, &store.application.sync_info) {
37 ("This room is knock-restricted to members of a room you are in.", Some(":knock"))
38 } else {
39 ("This room is knock-restricted to members of a room you are not in.", None)
40 }
41 },
42 _ => ("Room join rules unknown. Try `:join` or `:knock` to join this room.", None),
43 }
44}
45
46fn preview_state(
47 preview: &RoomPreview,
48 store: &ProgramStore,
49) -> (&'static str, Option<&'static str>) {
50 match preview.state {
51 Some(MatrixRoomState::Invited) => {
52 ("You have been invited to join this room.", Some(":invite accept"))
53 },
54 Some(MatrixRoomState::Knocked) => ("You have knocked on this room.", None),
55 Some(MatrixRoomState::Banned) => ("You have been banned from this room.", None),
56 Some(MatrixRoomState::Joined) => ("You have already joined this room.", None),
57 Some(MatrixRoomState::Left) | None => preview_join_rule(preview, store),
58 }
59}
260
3#[derive(Clone)]
461pub struct NotJoinedState {
5 pub(super) room: String,
62 alias: OwnedRoomOrAliasId,
63 /// The resolved [`alias`](`Self::alias`).
64 room_id: Option<OwnedRoomId>,
665 err: Option<String>,
66 joining: Option<ClientResponse<IambResult<OwnedRoomId>>>,
67
68 term_cursor: (u16, u16),
769}
870
971impl NotJoinedState {
10 /// Create a window for a room the user hasn't yet joined.
11 pub fn new(room: String) -> Self {
12 Self { room, err: None }
72 /// Create a window for a room the user hasn't joined.
73 pub fn new(alias: OwnedRoomOrAliasId, store: &mut ProgramStore) -> Self {
74 store.application.need_load.need_preview(alias.clone());
75
76 Self {
77 alias,
78 room_id: None,
79 err: None,
80 joining: None,
81 term_cursor: (0, 0),
82 }
1383 }
1484
15 /// Create a window for a room whose `:join` command failed.
16 pub fn failed(room: String, err: &UIError<IambInfo>) -> Self {
17 Self { room, err: Some(err.to_string()) }
85 pub fn alias(&self) -> &RoomOrAliasId {
86 &self.alias
87 }
88
89 pub fn room_id(&mut self, store: &ProgramStore) -> Option<&RoomId> {
90 let alias_or_id: &RoomOrAliasId = &self.alias;
91 match <&RoomId>::try_from(alias_or_id) {
92 Ok(id) => Some(id),
93 Err(alias) => {
94 let room_id = store.application.aliases.get(alias);
95 self.room_id = room_id.cloned();
96 self.room_id.as_deref()
97 },
98 }
99 }
100
101 pub fn refresh_room(&mut self, store: &mut ProgramStore) -> Option<RoomState> {
102 let room = if let Some(room) = self
103 .room_id(store)
104 .and_then(|id| store.application.worker.client.get_room(id))
105 {
106 room
107 } else {
108 if let Some(Err(e)) = self.joining.as_ref().and_then(|chan| chan.try_recv()) {
109 self.err = Some(e.to_string());
110 self.joining = None;
111 }
112 return None;
113 };
114
115 if room.state() == MatrixRoomState::Left {
116 // room previews have more information than left rooms
117 return None;
118 }
119
120 store.application.need_load.need_members(room.room_id().to_owned());
121
122 Some(RoomState::new(room, None, store))
123 }
124
125 pub fn dup(&self) -> Self {
126 Self {
127 alias: self.alias.clone(),
128 room_id: self.room_id.clone(),
129 err: self.err.clone(),
130 joining: None,
131 term_cursor: (0, 0),
132 }
133 }
134
135 pub fn get_tab_title(&self, store: &ProgramStore) -> Line<'_> {
136 if let Some((Ok(preview), _)) = store.application.room_previews.get(self.alias()) {
137 if let Some(name) = &preview.name {
138 return Line::from(name.to_string());
139 }
140
141 if let Some(alias) = &preview.canonical_alias {
142 return Line::from(alias.to_string());
143 }
144 }
145
146 Line::from(self.alias.as_str())
147 }
148
149 pub fn get_title(&self, store: &ProgramStore) -> Line<'_> {
150 if let Some((Ok(preview), _)) = store.application.room_previews.get(self.alias()) {
151 if let Some(name) = &preview.name {
152 return Line::from(vec![
153 Span::styled(name.to_string(), StyleModifier::BOLD),
154 Span::raw(" (unjoined)"),
155 ]);
156 }
157
158 if let Some(alias) = &preview.canonical_alias {
159 return Line::from(vec![
160 Span::styled(alias.to_string(), StyleModifier::BOLD),
161 Span::raw(" (unjoined)"),
162 ]);
163 }
164 }
165
166 Line::from(vec![
167 Span::styled(self.alias.as_str(), StyleModifier::BOLD),
168 Span::raw(" (unjoined)"),
169 ])
170 }
171
172 pub async fn join_command(
173 &mut self,
174 act: JoinAction,
175 ctx: ProgramContext,
176 store: &mut ProgramStore,
177 ) -> IambResult<Vec<(Action<IambInfo>, ProgramContext)>> {
178 match act {
179 JoinAction::Join => {
180 let via = store
181 .application
182 .room_via
183 .get(self.alias())
184 .unwrap_or(&store.application.settings.tunables.default_via)
185 .to_vec();
186
187 let chan = store.application.worker.join_room_chan(self.alias().to_owned(), via);
188 self.joining = Some(chan);
189
190 Ok(vec![])
191 },
192 JoinAction::Knock => {
193 let act = HomeserverAction::KnockSend(self.alias().to_owned(), None);
194
195 Ok(vec![(IambAction::from(act).into(), ctx)])
196 },
197 }
18198 }
19199}
20200
@@ -65,7 +245,7 @@ impl Promptable<ProgramContext, ProgramStore, IambInfo> for NotJoinedState {
65245
66246impl TerminalCursor for NotJoinedState {
67247 fn get_term_cursor(&self) -> Option<TermOffset> {
68 None
248 self.term_cursor.into()
69249 }
70250
71251 fn hide_term_cursor(&self) -> bool {
@@ -74,23 +254,93 @@ impl TerminalCursor for NotJoinedState {
74254}
75255
76256/// [StatefulWidget] for Matrix rooms that haven't been joined.
77pub struct NotJoined;
257pub struct NotJoined<'a> {
258 store: &'a mut ProgramStore,
259}
78260
79impl StatefulWidget for NotJoined {
261impl<'a> NotJoined<'a> {
262 pub fn new(store: &'a mut ProgramStore) -> Self {
263 Self { store }
264 }
265}
266
267impl StatefulWidget for NotJoined<'_> {
80268 type State = NotJoinedState;
81269
82270 fn render(self, area: Rect, buffer: &mut Buffer, state: &mut Self::State) {
271 // Ensure the whole window receives the default timeline styling:
272 let theme = &self.store.application.settings.theme;
273 let default_style = theme.timeline.default;
274 let err_style = default_style.fg(Color::Red);
275 buffer.set_style(area, default_style);
276
277 // Save the top-left corner for indicating cursor placement:
278 state.term_cursor = (area.left(), area.top());
279
83280 let mut lines = vec![];
84281
85 lines.push(Line::from(vec![
86 Span::raw("Use "),
87 Span::styled(format!("`:join {}`", state.room), StyleModifier::BOLD),
88 Span::raw(" to join this room"),
89 ]));
282 let preview = self.store.application.room_previews.get(state.alias());
283 if let Some((_, fetched)) = &preview &&
284 fetched.elapsed() > ROOM_PREVIEW_DEBOUNCE
285 {
286 self.store.application.need_load.need_preview(state.alias().to_owned());
287 }
288
289 match preview {
290 Some((Ok(preview), _)) => {
291 let mut name_line = vec![];
292 if let Some(name) = &preview.name {
293 name_line.push(Span::styled(name, StyleModifier::BOLD));
294 name_line.push(Span::raw(" "));
295 }
296 if let Some(alias) = &preview.canonical_alias {
297 name_line.push(Span::raw(alias.as_str()));
298 name_line.push(Span::raw(" "));
299 }
300
301 name_line.push(Span::raw("("));
302 name_line.push(Span::raw(state.alias().as_str()));
303 name_line.push(Span::raw(")"));
304 lines.push(Line::from(name_line));
305 if let Some(topic) = &preview.topic {
306 lines.push(Line::raw(topic));
307 }
308
309 lines.push(Line::raw(""));
310
311 let (status, join_cmd) = preview_state(preview, self.store);
312
313 lines.push(Line::raw(status));
314 if let Some(join_cmd) = join_cmd {
315 lines.push(Line::from(vec![
316 Span::raw("Use `"),
317 Span::styled(join_cmd, StyleModifier::BOLD),
318 Span::raw("` to join this room"),
319 ]));
320 }
321 },
322 Some((Err(matrix_sdk::Error::InsufficientData), _)) => {
323 lines.push(Line::from(Span::styled(
324 "This room doesn't exist or room previews are disabled",
325 err_style,
326 )));
327 },
328 Some((Err(err), _)) => {
329 lines.push(Line::from(Span::styled(err.to_string(), err_style)));
330 },
331 None => {
332 self.store.application.need_load.need_preview(state.alias().to_owned());
333 lines.push(Line::raw("Loading room preview..."));
334 },
335 }
336
337 if state.joining.is_some() {
338 lines.push(Line::raw(""));
339 lines.push(Line::raw("Joining this room..."));
340 }
90341
91342 if let Some(err) = &state.err {
92 let style = Style::default().fg(Color::Red);
93 lines.push(Line::from(Span::styled(err.as_str(), style)));
343 lines.push(Line::from(Span::styled(err.as_str(), err_style)));
94344 }
95345
96346 Paragraph::new(Text::from(lines))
src/windows/room/scrollback.rs +1 −1
@@ -1021,7 +1021,7 @@ impl Promptable<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
10211021 return Err(err);
10221022 };
10231023 let room_id = self.room_id.clone();
1024 let id = IambId::Room(room_id, Some(root.to_owned()));
1024 let id = IambId::Room(room_id.into(), Some(root.to_owned()));
10251025 let open = WindowAction::Switch(OpenTarget::Application(id));
10261026 Ok(vec![(open.into(), ctx.clone())])
10271027 }
src/windows/room/space.rs +5 −5
@@ -189,8 +189,9 @@ impl StatefulWidget for Space<'_> {
189189 type State = SpaceState;
190190
191191 fn render(self, area: Rect, buffer: &mut Buffer, state: &mut Self::State) {
192 let ChatStore { rooms, names, worker, settings, collator, .. } =
193 &mut self.store.application;
192 let ChatStore {
193 rooms, aliases: names, worker, settings, collator, ..
194 } = &mut self.store.application;
194195 state.set_ignorecase(settings.tunables.ignorecase);
195196
196197 let mut empty_message = None;
@@ -207,11 +208,10 @@ impl StatefulWidget for Space<'_> {
207208 let mut items = members
208209 .into_iter()
209210 .filter_map(|id| {
210 let (room, _, tags) = worker.get_room(id.clone()).ok()?;
211 let room_info = std::sync::Arc::new((room, tags));
211 let (room, _) = worker.get_room(id.clone()).ok()?;
212212
213213 if id != state.room_id {
214 Some(GenericRoomItem::new(&room_info.0, rooms, names))
214 Some(GenericRoomItem::new(&room, rooms, names))
215215 } else {
216216 None
217217 }
src/worker.rs +76 −30
@@ -185,6 +185,7 @@ enum Plan {
185185 Messages(OwnedRoomId, Vec<MessageNeed>),
186186 Members(OwnedRoomId),
187187 Pinned(OwnedRoomId, Vec<OwnedEventId>),
188 RoomPreview(OwnedRoomOrAliasId),
188189}
189190
190191async fn load_plans(store: &AsyncProgramStore) -> Vec<Plan> {
@@ -192,6 +193,10 @@ async fn load_plans(store: &AsyncProgramStore) -> Vec<Plan> {
192193 let ChatStore { need_load, rooms, .. } = &mut locked.application;
193194 let mut plan = Vec::with_capacity(need_load.rooms() * 2);
194195
196 for room in need_load.preview_needs() {
197 plan.push(Plan::RoomPreview(room));
198 }
199
195200 for (room_id, need) in std::mem::take(need_load).into_iter() {
196201 if need.pinned {
197202 let missing = rooms.get_or_default(room_id.clone()).missing_pinned();
@@ -256,6 +261,31 @@ async fn run_plan(client: &Client, store: &AsyncProgramStore, plan: Plan) {
256261 info.insert_pinned(event_id, msg);
257262 }
258263 },
264 Plan::RoomPreview(alias_id) => {
265 let via = {
266 let locked = store.lock().await;
267 locked
268 .application
269 .room_via
270 .get(&alias_id)
271 .unwrap_or(&locked.application.settings.tunables.default_via)
272 .to_vec()
273 };
274
275 let res = client.get_room_preview(&alias_id, via).await;
276
277 let mut locked = store.lock().await;
278
279 if let Ok(preview) = &res &&
280 let Some(alias) = &preview.canonical_alias
281 {
282 locked
283 .application
284 .aliases
285 .insert(alias.to_owned(), preview.room_id.clone());
286 }
287 locked.application.room_previews.insert(alias_id, (res, Instant::now()));
288 },
259289 }
260290}
261291
@@ -667,9 +697,11 @@ async fn refresh_rooms(client: &Client, store: &AsyncProgramStore, first_sync: b
667697
668698 let name = display.to_string();
669699 let tags = room.tags().await.unwrap_or_default();
700 let mut aliases = room.alt_aliases();
701 aliases.extend(room.canonical_alias());
670702
671703 pinned.push((room.room_id().to_owned(), room.pinned_event_ids().unwrap_or_default()));
672 names_and_tags.push((room.room_id().to_owned(), name, tags));
704 names_and_tags.push((room.room_id().to_owned(), name, tags, aliases));
673705
674706 if room.is_direct().await.unwrap_or_default() {
675707 dms.push(room);
@@ -685,8 +717,8 @@ async fn refresh_rooms(client: &Client, store: &AsyncProgramStore, first_sync: b
685717 locked.application.sync_info.rooms = rooms;
686718 locked.application.sync_info.dms = dms;
687719
688 for (room_id, name, tags) in names_and_tags {
689 locked.application.set_room_info(room_id, name, tags);
720 for (room_id, name, tags, aliases) in names_and_tags {
721 locked.application.set_room_info(room_id, name, tags, aliases);
690722 }
691723
692724 for (room_id, pinned_events) in pinned {
@@ -977,7 +1009,7 @@ fn oneshot<T>() -> (ClientReply<T>, ClientResponse<T>) {
9771009 return (reply, response);
9781010}
9791011
980pub type FetchedRoom = (MatrixRoom, RoomDisplayName, Option<Tags>);
1012pub type FetchedRoom = (MatrixRoom, RoomDisplayName);
9811013
9821014pub enum WorkerTask {
9831015 Init(AsyncProgramStore, ClientReply<()>),
@@ -986,7 +1018,8 @@ pub enum WorkerTask {
9861018 GetInviter(MatrixRoom, ClientReply<IambResult<Option<RoomMember>>>),
9871019 GetRoom(OwnedRoomId, ClientReply<IambResult<FetchedRoom>>),
9881020 ResolveAlias(OwnedRoomAliasId, ClientReply<IambResult<OwnedRoomId>>),
989 JoinRoom(String, Vec<OwnedServerName>, ClientReply<IambResult<OwnedRoomId>>),
1021 JoinRoom(OwnedRoomOrAliasId, Vec<OwnedServerName>, ClientReply<IambResult<OwnedRoomId>>),
1022 CreateDM(OwnedUserId, ClientReply<IambResult<OwnedRoomId>>),
9901023 Members(OwnedRoomId, ClientReply<IambResult<Vec<RoomMember>>>),
9911024 SpaceMembers(OwnedRoomId, ClientReply<IambResult<Vec<OwnedRoomId>>>),
9921025 TypingNotice(OwnedRoomId),
@@ -1033,6 +1066,12 @@ impl Debug for WorkerTask {
10331066 .field(&format_args!("_"))
10341067 .finish()
10351068 },
1069 WorkerTask::CreateDM(user_id, _) => {
1070 f.debug_tuple("WorkerTask::CreateDM")
1071 .field(user_id)
1072 .field(&format_args!("_"))
1073 .finish()
1074 },
10361075 WorkerTask::Members(room_id, _) => {
10371076 f.debug_tuple("WorkerTask::Members")
10381077 .field(room_id)
@@ -1156,7 +1195,7 @@ pub async fn create_client(settings: &ApplicationSettings) -> Client {
11561195 client
11571196}
11581197
1159async fn direct_message(user: OwnedUserId, client: Client) -> IambResult<OwnedRoomId> {
1198async fn direct_message(user: OwnedUserId, client: &Client) -> IambResult<OwnedRoomId> {
11601199 if let Some(room) = client.get_dm_room(&user) {
11611200 return Ok(room.room_id().to_owned());
11621201 }
@@ -1178,25 +1217,17 @@ async fn direct_message(user: OwnedUserId, client: Client) -> IambResult<OwnedRo
11781217}
11791218
11801219async fn join_room(
1181 name: String,
1220 alias_id: OwnedRoomOrAliasId,
11821221 via: Vec<OwnedServerName>,
11831222 client: Client,
11841223) -> IambResult<OwnedRoomId> {
1185 if let Ok(alias_id) = OwnedRoomOrAliasId::from_str(name.as_str()) {
1186 match client.join_room_by_id_or_alias(&alias_id, &via).await {
1187 Ok(resp) => Ok(resp.room_id().to_owned()),
1188 Err(e) => {
1189 let msg = e.to_string();
1190 let err = UIError::Failure(msg);
1191 return Err(err);
1192 },
1193 }
1194 } else if let Ok(user) = OwnedUserId::try_from(name.as_str()) {
1195 direct_message(user, client).await
1196 } else {
1197 let msg = format!("{:?} is not a valid room or user name", name.as_str());
1198 let err = UIError::Failure(msg);
1199 return Err(err);
1224 match client.join_room_by_id_or_alias(&alias_id, &via).await {
1225 Ok(resp) => Ok(resp.room_id().to_owned()),
1226 Err(e) => {
1227 let msg = e.to_string();
1228 let err = UIError::Failure(msg);
1229 return Err(err);
1230 },
12001231 }
12011232}
12021233
@@ -1277,16 +1308,28 @@ impl Requester {
12771308
12781309 pub fn join_room_chan(
12791310 &self,
1280 name: String,
1311 alias_id: OwnedRoomOrAliasId,
12811312 via: Vec<OwnedServerName>,
12821313 ) -> ClientResponse<IambResult<OwnedRoomId>> {
12831314 let (reply, response) = oneshot();
1284 self.tx.send(WorkerTask::JoinRoom(name, via, reply)).unwrap();
1315 self.tx.send(WorkerTask::JoinRoom(alias_id, via, reply)).unwrap();
12851316 response
12861317 }
12871318
1288 pub fn join_room(&self, name: String, via: Vec<OwnedServerName>) -> IambResult<OwnedRoomId> {
1289 self.join_room_chan(name, via).recv()
1319 pub fn join_room(
1320 &self,
1321 alias_id: OwnedRoomOrAliasId,
1322 via: Vec<OwnedServerName>,
1323 ) -> IambResult<OwnedRoomId> {
1324 self.join_room_chan(alias_id, via).recv()
1325 }
1326
1327 pub fn create_dm(&self, user_id: OwnedUserId) -> IambResult<OwnedRoomId> {
1328 let (reply, response) = oneshot();
1329
1330 self.tx.send(WorkerTask::CreateDM(user_id, reply)).unwrap();
1331
1332 return response.recv();
12901333 }
12911334
12921335 pub fn members(&self, room_id: OwnedRoomId) -> IambResult<Vec<RoomMember>> {
@@ -1387,10 +1430,14 @@ impl ClientWorker {
13871430 assert!(self.initialized);
13881431 reply.send(self.resolve_alias(alias_id).await);
13891432 },
1390 WorkerTask::JoinRoom(name, via, reply) => {
1433 WorkerTask::JoinRoom(alias_id, via, reply) => {
13911434 assert!(self.initialized);
13921435 let client = self.client.clone();
1393 tokio::spawn(async move { reply.send(join_room(name, via, client).await) });
1436 tokio::spawn(async move { reply.send(join_room(alias_id, via, client).await) });
1437 },
1438 WorkerTask::CreateDM(user_id, reply) => {
1439 assert!(self.initialized);
1440 reply.send(direct_message(user_id, &self.client).await);
13941441 },
13951442 WorkerTask::GetInviter(invited, reply) => {
13961443 assert!(self.initialized);
@@ -2002,9 +2049,8 @@ impl ClientWorker {
20022049 } else {
20032050 room.display_name().await.map_err(IambError::from)?
20042051 };
2005 let tags = room.tags().await.map_err(IambError::from)?;
20062052
2007 Ok((room, name, tags))
2053 Ok((room, name))
20082054 } else {
20092055 Err(IambError::UnknownRoom(room_id).into())
20102056 }