Commit fa7e45088e

fa7e45088e8ff07def674bd4cf70716cef965c53

parent: d75abde232

Unregistered key

Ulyssa <git@ulyssa.dev> · 2026-09-18 01:09 UTC
committer: <noreply@github.com>

Show intermediate window instead of blocking on `:join` request (#711)

Layout: unified · split

src/base.rs +74
@@ -42,6 +42,7 @@ use serde::de::Error as SerdeError;
4242use serde::de::Visitor;
4343use serde::{Deserialize, Deserializer, Serialize, Serializer};
4444use tokio::sync::Mutex as AsyncMutex;
45use url::form_urlencoded;
4546
4647use crate::notifications::NotificationHandle;
4748use crate::prelude::*;
@@ -1990,6 +1991,12 @@ pub enum IambId {
19901991 /// A Matrix room, with an optional thread to show.
19911992 Room(OwnedRoomId, Option<OwnedEventId>),
19921993
1994 /// A Matrix room that we're currently in the middle of joining.
1995 Joining(String),
1996
1997 /// A Matrix room that we haven't joined, and aren't currently joining.
1998 NotJoined(String),
1999
19932000 /// The `:dms` window.
19942001 DirectList,
19952002
@@ -2021,6 +2028,24 @@ pub enum IambId {
20212028 InvitesList,
20222029}
20232030
2031/// Encode the room name for a [IambId::Joining] or [IambId::NotJoined] window URL.
2032///
2033/// Note that since these names come straight from the user's argument to `:join`,
2034/// they are likely room aliases containing characters like `#` that we should
2035/// escape before putting them into the URL, so we can later reparse it. They can
2036/// technically contain anything that the user tried to pass to `:join`.
2037fn room_query(room: &str) -> String {
2038 form_urlencoded::Serializer::new(String::new())
2039 .append_pair("room", room)
2040 .finish()
2041}
2042
2043/// Pull the room name back out of the query parameter for `iamb://joining` or
2044/// `iamb://not-joined`.
2045fn query_room(url: &Url) -> Option<String> {
2046 url.query_pairs().find_map(|(k, v)| (k == "room").then(|| v.into_owned()))
2047}
2048
20242049impl Display for IambId {
20252050 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
20262051 match self {
@@ -2030,6 +2055,12 @@ impl Display for IambId {
20302055 IambId::Room(room_id, Some(thread)) => {
20312056 write!(f, "iamb://room/{room_id}/threads/{thread}")
20322057 },
2058 IambId::Joining(room) => {
2059 write!(f, "iamb://joining?{}", room_query(room))
2060 },
2061 IambId::NotJoined(room) => {
2062 write!(f, "iamb://not-joined?{}", room_query(room))
2063 },
20332064 IambId::MemberList(room_id) => {
20342065 write!(f, "iamb://members/{room_id}")
20352066 },
@@ -2116,6 +2147,20 @@ impl Visitor<'_> for IambIdVisitor {
21162147 _ => return Err(E::custom("Invalid members window URL")),
21172148 }
21182149 },
2150 Some("joining") => {
2151 let Some(room) = query_room(&url) else {
2152 return Err(E::custom("iamb://joining requires a room parameter"));
2153 };
2154
2155 Ok(IambId::Joining(room))
2156 },
2157 Some("not-joined") => {
2158 let Some(room) = query_room(&url) else {
2159 return Err(E::custom("iamb://not-joined requires a room parameter"));
2160 };
2161
2162 Ok(IambId::NotJoined(room))
2163 },
21192164 Some("members") => {
21202165 let Some(path) = url.path_segments() else {
21212166 return Err(E::custom("Invalid members window URL"));
@@ -2460,6 +2505,35 @@ pub mod tests {
24602505 );
24612506 }
24622507
2508 #[test]
2509 fn test_unjoined_window_ids() {
2510 // Room names come from the user can contain characters that need escaping:
2511 for name in [
2512 "#foo:example.com",
2513 "!abc123:example.com",
2514 "@user:example.com",
2515 "a b&c=d?e#f",
2516 ] {
2517 for id in [IambId::Joining(name.into()), IambId::NotJoined(name.into())] {
2518 let json = serde_json::to_string(&id).unwrap();
2519 assert_eq!(serde_json::from_str::<IambId>(&json).unwrap(), id);
2520 }
2521 }
2522
2523 assert_eq!(
2524 IambId::Joining("#foo:example.com".into()).to_string(),
2525 "iamb://joining?room=%23foo%3Aexample.com"
2526 );
2527 assert_eq!(
2528 IambId::NotJoined("#foo:example.com".into()).to_string(),
2529 "iamb://not-joined?room=%23foo%3Aexample.com"
2530 );
2531
2532 // A window URL without a room name isn't valid and wasn't written by us:
2533 assert!(serde_json::from_str::<IambId>("\"iamb://joining\"").is_err());
2534 assert!(serde_json::from_str::<IambId>("\"iamb://not-joined\"").is_err());
2535 }
2536
24632537 #[test]
24642538 fn test_need_load() {
24652539 let room_id = TEST_ROOM1_ID.clone();
src/windows/mod.rs +15 −23
@@ -368,7 +368,7 @@ impl IambWindow {
368368 store: &mut ProgramStore,
369369 ) -> IambResult<Vec<(Action<IambInfo>, ProgramContext)>> {
370370 let id = match self {
371 IambWindow::Room(state) => Some(state.id()),
371 IambWindow::Room(state) => state.id(),
372372 IambWindow::MemberList(_, room_id, _) => Some(&**room_id),
373373
374374 IambWindow::DirectList(state) => state.get().map(|state| state.room_id()),
@@ -817,7 +817,7 @@ impl WindowOps<IambInfo> for IambWindow {
817817impl Window<IambInfo> for IambWindow {
818818 fn id(&self) -> IambId {
819819 match self {
820 IambWindow::Room(room) => IambId::Room(room.id().to_owned(), room.thread().cloned()),
820 IambWindow::Room(room) => room.window_id(),
821821 IambWindow::DirectList(_) => IambId::DirectList,
822822 IambWindow::MemberList(_, room_id, _) => IambId::MemberList(room_id.clone()),
823823 IambWindow::RoomList(_) => IambId::RoomList,
@@ -843,11 +843,7 @@ impl Window<IambInfo> for IambWindow {
843843 IambWindow::MentionsList(_) => bold_spans("Unread Mentions"),
844844 IambWindow::InvitesList(_) => bold_spans("Open Invites"),
845845
846 IambWindow::Room(w) => {
847 let title = store.application.get_room_title(w.id());
848
849 Line::from(title)
850 },
846 IambWindow::Room(w) => w.get_tab_title(store),
851847 IambWindow::MemberList(state, room_id, _) => {
852848 let title = store.application.get_room_title(room_id.as_ref());
853849 let n = state.len();
@@ -893,9 +889,18 @@ impl Window<IambInfo> for IambWindow {
893889 let (room, name, tags) = store.application.worker.get_room(room_id)?;
894890 let room = RoomState::new(room, thread, name, tags, store);
895891
896 store.application.need_load.need_members(room.id().to_owned());
892 if let Some(room_id) = room.id() {
893 store.application.need_load.need_members(room_id.to_owned());
894 }
895
897896 return Ok(room.into());
898897 },
898 IambId::Joining(name) => {
899 return Ok(RoomState::join(name, store).into());
900 },
901 IambId::NotJoined(name) => {
902 return Ok(RoomState::not_joined(name).into());
903 },
899904 IambId::DirectList => {
900905 let list = DirectListState::new(IambBufferId::DirectList, vec![]);
901906
@@ -952,24 +957,11 @@ impl Window<IambInfo> for IambWindow {
952957 }
953958
954959 fn find(name: String, store: &mut ProgramStore) -> IambResult<Self> {
955 let ChatStore { names, worker, settings, .. } = &mut store.application;
956
957 if let Some(room) = names.get_mut(&name) {
960 if let Some(room) = store.application.names.get(&name) {
958961 let id = IambId::Room(room.clone(), None);
959
960962 IambWindow::open(id, store)
961963 } else {
962 let via = settings.tunables.default_via.clone();
963 let room_id = worker.join_room(name.clone(), via)?;
964
965 if let Ok(alias) = OwnedRoomAliasId::from_str(&name) {
966 names.insert(alias, room_id.clone());
967 }
968
969 let (room, name, tags) = store.application.worker.get_room(room_id)?;
970 let room = RoomState::new(room, None, name, tags, store);
971
972 store.application.need_load.need_members(room.id().to_owned());
964 let room = RoomState::join(name, store);
973965 Ok(room.into())
974966 }
975967 }
src/windows/room/joining.rs added +98
@@ -0,0 +1,98 @@
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 +144 −40
@@ -19,15 +19,21 @@ use crate::base::{MemberUpdateAction, RoomField};
1919use crate::config::EncryptionIndicatorLocation;
2020use crate::prelude::*;
2121use crate::windows::room::chat::ChatState;
22use crate::windows::room::joining::{Joining, JoiningState};
23use crate::windows::room::not_joined::{NotJoined, NotJoinedState};
2224use crate::windows::room::space::{Space, SpaceState};
2325
2426mod chat;
27mod joining;
28mod not_joined;
2529mod scrollback;
2630mod space;
2731
2832macro_rules! delegate {
2933 ($s: expr, $id: ident => $e: expr) => {
3034 match $s {
35 RoomState::NotJoined($id) => $e,
36 RoomState::Joining($id) => $e,
3137 RoomState::Chat($id) => $e,
3238 RoomState::Space($id) => $e,
3339 }
@@ -640,10 +646,24 @@ pub async fn room_command(
640646/// that operations like sending and accepting invites, opening the members window, etc., all work
641647/// similarly.
642648pub enum RoomState {
649 NotJoined(Box<NotJoinedState>),
650 Joining(Box<JoiningState>),
643651 Chat(Box<ChatState>),
644652 Space(Box<SpaceState>),
645653}
646654
655impl From<NotJoinedState> for RoomState {
656 fn from(chat: NotJoinedState) -> Self {
657 RoomState::NotJoined(Box::new(chat))
658 }
659}
660
661impl From<JoiningState> for RoomState {
662 fn from(chat: JoiningState) -> Self {
663 RoomState::Joining(Box::new(chat))
664 }
665}
666
647667impl From<ChatState> for RoomState {
648668 fn from(chat: ChatState) -> Self {
649669 RoomState::Chat(Box::new(chat))
@@ -676,15 +696,64 @@ impl RoomState {
676696 }
677697 }
678698
679 pub fn thread(&self) -> Option<&OwnedEventId> {
699 pub fn join(name: String, store: &mut ProgramStore) -> Self {
700 let joining = JoiningState::new(name, store);
701 Self::from(joining)
702 }
703
704 pub fn not_joined(name: String) -> Self {
705 Self::from(NotJoinedState::new(name))
706 }
707
708 pub fn window_id(&self) -> IambId {
709 match self {
710 RoomState::NotJoined(nj) => IambId::NotJoined(nj.room.clone()),
711 RoomState::Joining(joining) => IambId::Joining(joining.room.clone()),
712 RoomState::Chat(chat) => IambId::Room(chat.id().to_owned(), chat.thread().cloned()),
713 RoomState::Space(space) => IambId::Room(space.id().to_owned(), None),
714 }
715 }
716
717 pub fn room_state(&self) -> Option<MatrixRoomState> {
680718 match self {
681 RoomState::Chat(chat) => chat.thread(),
682 RoomState::Space(_) => None,
719 RoomState::NotJoined(_) | RoomState::Joining(_) => None,
720 RoomState::Chat(chat) => Some(chat.room().state()),
721 RoomState::Space(space) => Some(space.room().state()),
683722 }
684723 }
685724
686725 pub fn refresh_room(&mut self, store: &mut ProgramStore) {
687726 match self {
727 RoomState::NotJoined(_) => {},
728 RoomState::Joining(joining) => {
729 let joined = joining.room.clone();
730
731 let room_id = match joining.try_recv() {
732 None => return,
733 Some(Ok(room_id)) => room_id.clone(),
734 Some(Err(e)) => {
735 // We failed to join the room, so show the NotJoined window,
736 // and let the user try again if the error was transient:
737 *self = NotJoinedState::failed(joined, e).into();
738 return;
739 },
740 };
741
742 let Ok((room, name, tags)) = store.application.worker.get_room(room_id.clone())
743 else {
744 return;
745 };
746
747 if let Ok(alias) = OwnedRoomAliasId::try_from(joined.as_str()) {
748 // If the `:join` was for a room alias, then track it so
749 // we can reuse it later for `:join`/`:sp`/etc:
750 store.application.names.insert(alias, room_id.clone());
751 }
752
753 store.application.need_load.need_members(room_id);
754
755 *self = RoomState::new(room, None, name, tags, store);
756 },
688757 RoomState::Chat(chat) => chat.refresh_room(store),
689758 RoomState::Space(space) => space.refresh_room(store),
690759 }
@@ -698,16 +767,17 @@ impl RoomState {
698767 store: &mut ProgramStore,
699768 ) {
700769 let inviter = store.application.worker.get_inviter(invited.clone());
770 let room_id = invited.room_id();
701771
702772 let name = match invited.canonical_alias() {
703773 Some(alias) => alias.to_string(),
704 None => format!("{:?}", store.application.get_room_title(self.id())),
774 None => format!("{:?}", store.application.get_room_title(room_id)),
705775 };
706776
707777 let mut invited = vec![Span::from(format!("You have been invited to join {name}"))];
708778
709779 if let Ok(Some(inviter)) = &inviter {
710 let info = store.application.rooms.get_or_default(self.id().to_owned());
780 let info = store.application.rooms.get_or_default(room_id.to_owned());
711781 invited.push(Span::from(" by "));
712782 invited.push(store.application.settings.get_user_span(inviter.user_id(), info));
713783 }
@@ -732,7 +802,7 @@ impl RoomState {
732802 ) {
733803 let name = match knocked.canonical_alias() {
734804 Some(alias) => alias.to_string(),
735 None => format!("{:?}", store.application.get_room_title(self.id())),
805 None => format!("{:?}", store.application.get_room_title(knocked.room_id())),
736806 };
737807
738808 let l1 = Line::from(format!(
@@ -749,7 +819,7 @@ impl RoomState {
749819 fn draw_left(&self, room: &MatrixRoom, area: Rect, buf: &mut Buffer, store: &mut ProgramStore) {
750820 let name = match room.canonical_alias() {
751821 Some(alias) => alias.to_string(),
752 None => format!("{:?}", store.application.get_room_title(self.id())),
822 None => format!("{:?}", store.application.get_room_title(room.room_id())),
753823 };
754824
755825 let mut lines = vec![Line::from(format!("You have left {name}!"))];
@@ -771,9 +841,10 @@ impl RoomState {
771841 ctx: ProgramContext,
772842 store: &mut ProgramStore,
773843 ) -> IambResult<EditInfo> {
774 match self {
775 RoomState::Chat(chat) => chat.message_command(act, ctx, store).await,
776 RoomState::Space(_) => Err(IambError::NoSelectedMessage.into()),
844 if let RoomState::Chat(chat) = self {
845 chat.message_command(act, ctx, store).await
846 } else {
847 Err(IambError::NoSelectedMessage.into())
777848 }
778849 }
779850
@@ -783,9 +854,10 @@ impl RoomState {
783854 ctx: ProgramContext,
784855 store: &mut ProgramStore,
785856 ) -> IambResult<EditInfo> {
786 match self {
787 RoomState::Space(space) => space.space_command(act, ctx, store).await,
788 RoomState::Chat(_) => Err(IambError::NoSelectedSpace.into()),
857 if let RoomState::Space(space) = self {
858 space.space_command(act, ctx, store).await
859 } else {
860 Err(IambError::NoSelectedSpace.into())
789861 }
790862 }
791863
@@ -795,26 +867,28 @@ impl RoomState {
795867 ctx: ProgramContext,
796868 store: &mut ProgramStore,
797869 ) -> IambResult<EditInfo> {
798 match self {
799 RoomState::Chat(chat) => chat.send_command(act, ctx, store).await,
800 RoomState::Space(_) => Err(IambError::NoSelectedRoom.into()),
870 if let RoomState::Chat(chat) = self {
871 chat.send_command(act, ctx, store).await
872 } else {
873 Err(IambError::NoSelectedRoom.into())
801874 }
802875 }
803876
804877 pub fn get_title(&self, store: &mut ProgramStore) -> Line<'_> {
805 let room = store.application.worker.client.get_room(self.id());
878 let Some(room) = self.room() else {
879 return Line::from("Unjoined Room");
880 };
806881
807 let title = store.application.get_room_title(self.id());
882 let room_id = room.room_id();
883 let title = store.application.get_room_title(room_id);
808884 let style = Style::default().add_modifier(StyleModifier::BOLD);
809885 let mut spans = vec![];
810886
811 if let Some(room) = room {
812 let encryption_settings = &store.application.settings.tunables.encryption;
813 let encryption_indicator = encryption_settings
814 .get_indicator(EncryptionIndicatorLocation::TITLE, room.encryption_state());
815 spans.extend(encryption_indicator);
816 spans.push(Span::raw(" "));
817 }
887 let encryption_settings = &store.application.settings.tunables.encryption;
888 let encryption_indicator = encryption_settings
889 .get_indicator(EncryptionIndicatorLocation::TITLE, room.encryption_state());
890 spans.extend(encryption_indicator);
891 spans.push(Span::raw(" "));
818892
819893 if let RoomState::Chat(chat) = self &&
820894 chat.thread().is_some()
@@ -824,7 +898,7 @@ impl RoomState {
824898
825899 spans.push(Span::styled(title, style));
826900
827 match self.room().topic() {
901 match room.topic() {
828902 Some(desc) if !desc.is_empty() => {
829903 spans.push(" (".into());
830904 spans.push(desc.into());
@@ -838,24 +912,37 @@ impl RoomState {
838912 Line::from(spans)
839913 }
840914
915 pub fn get_tab_title(&self, store: &mut ProgramStore) -> Line<'_> {
916 match self {
917 RoomState::Space(w) => store.application.get_room_title(w.id()).into(),
918 RoomState::Chat(w) => store.application.get_room_title(w.id()).into(),
919 RoomState::NotJoined(_) => Line::from("Unjoined Room"),
920 RoomState::Joining(w) => {
921 Line::from(vec![Span::raw("Joining "), Span::raw(w.room.as_str())])
922 },
923 }
924 }
925
841926 pub fn focus_toggle(&mut self) {
842927 match self {
843928 RoomState::Chat(chat) => chat.focus_toggle(),
844 RoomState::Space(_) => return,
929 RoomState::Joining(_) | RoomState::NotJoined(_) | RoomState::Space(_) => return,
845930 }
846931 }
847932
848 pub fn room(&self) -> &MatrixRoom {
933 pub fn room(&self) -> Option<&MatrixRoom> {
849934 match self {
850 RoomState::Chat(chat) => chat.room(),
851 RoomState::Space(space) => space.room(),
935 RoomState::Chat(chat) => Some(chat.room()),
936 RoomState::Space(space) => Some(space.room()),
937 RoomState::Joining(_) | RoomState::NotJoined(_) => None,
852938 }
853939 }
854940
855 pub fn id(&self) -> &RoomId {
941 pub fn id(&self) -> Option<&RoomId> {
856942 match self {
857 RoomState::Chat(chat) => chat.id(),
858 RoomState::Space(space) => space.id(),
943 RoomState::Chat(chat) => Some(chat.id()),
944 RoomState::Space(space) => Some(space.id()),
945 RoomState::Joining(_) | RoomState::NotJoined(_) => None,
859946 }
860947 }
861948}
@@ -917,19 +1004,29 @@ impl TerminalCursor for RoomState {
9171004
9181005impl WindowOps<IambInfo> for RoomState {
9191006 fn draw(&mut self, area: Rect, buf: &mut Buffer, focused: bool, store: &mut ProgramStore) {
920 if self.room().state() != MatrixRoomState::Joined {
1007 if self.room_state() != Some(MatrixRoomState::Joined) {
9211008 self.refresh_room(store);
9221009 }
9231010
924 match self.room().state() {
925 MatrixRoomState::Invited => return self.draw_invite(self.room(), area, buf, store),
926 MatrixRoomState::Knocked => return self.draw_knock(self.room(), area, buf, store),
927 MatrixRoomState::Left => return self.draw_left(self.room(), area, buf, store),
928 _ => (),
1011 if let Some(room) = self.room() {
1012 match room.state() {
1013 MatrixRoomState::Invited => return self.draw_invite(room, area, buf, store),
1014 MatrixRoomState::Knocked => return self.draw_knock(room, area, buf, store),
1015 MatrixRoomState::Left => return self.draw_left(room, area, buf, store),
1016 _ => (),
1017 }
9291018 }
9301019
9311020 match self {
932 RoomState::Chat(chat) => chat.draw(area, buf, focused, store),
1021 RoomState::Chat(chat) => {
1022 chat.draw(area, buf, focused, store);
1023 },
1024 RoomState::Joining(state) => {
1025 Joining.render(area, buf, state);
1026 },
1027 RoomState::NotJoined(state) => {
1028 NotJoined.render(area, buf, state);
1029 },
9331030 RoomState::Space(space) => {
9341031 Space::new(store).focus(focused).render(area, buf, space);
9351032 },
@@ -938,6 +1035,8 @@ impl WindowOps<IambInfo> for RoomState {
9381035
9391036 fn dup(&self, store: &mut ProgramStore) -> Self {
9401037 match self {
1038 RoomState::Joining(w) => RoomState::join(w.room.clone(), store),
1039 RoomState::NotJoined(w) => RoomState::NotJoined((*w).clone()),
9411040 RoomState::Chat(chat) => RoomState::Chat(Box::new(chat.dup(store))),
9421041 RoomState::Space(space) => RoomState::Space(Box::new(space.dup(store))),
9431042 }
@@ -945,6 +1044,7 @@ impl WindowOps<IambInfo> for RoomState {
9451044
9461045 fn close(&mut self, flags: CloseFlags, store: &mut ProgramStore) -> bool {
9471046 match self {
1047 RoomState::NotJoined(_) | RoomState::Joining(_) => true,
9481048 RoomState::Chat(chat) => chat.close(flags, store),
9491049 RoomState::Space(space) => space.close(flags, store),
9501050 }
@@ -957,6 +1057,7 @@ impl WindowOps<IambInfo> for RoomState {
9571057 store: &mut ProgramStore,
9581058 ) -> IambResult<EditInfo> {
9591059 match self {
1060 RoomState::NotJoined(_) | RoomState::Joining(_) => Err(EditError::ReadOnly.into()),
9601061 RoomState::Chat(chat) => chat.write(path, flags, store),
9611062 RoomState::Space(space) => space.write(path, flags, store),
9621063 }
@@ -964,6 +1065,7 @@ impl WindowOps<IambInfo> for RoomState {
9641065
9651066 fn get_completions(&self) -> Option<CompletionList> {
9661067 match self {
1068 RoomState::NotJoined(_) | RoomState::Joining(_) => None,
9671069 RoomState::Chat(chat) => chat.get_completions(),
9681070 RoomState::Space(space) => space.get_completions(),
9691071 }
@@ -971,6 +1073,7 @@ impl WindowOps<IambInfo> for RoomState {
9711073
9721074 fn get_cursor_word(&self, style: &WordStyle) -> Option<String> {
9731075 match self {
1076 RoomState::NotJoined(_) | RoomState::Joining(_) => None,
9741077 RoomState::Chat(chat) => chat.get_cursor_word(style),
9751078 RoomState::Space(space) => space.get_cursor_word(style),
9761079 }
@@ -978,6 +1081,7 @@ impl WindowOps<IambInfo> for RoomState {
9781081
9791082 fn get_selected_word(&self) -> Option<String> {
9801083 match self {
1084 RoomState::NotJoined(_) | RoomState::Joining(_) => None,
9811085 RoomState::Chat(chat) => chat.get_selected_word(),
9821086 RoomState::Space(space) => space.get_selected_word(),
9831087 }
src/windows/room/not_joined.rs added +100
@@ -0,0 +1,100 @@
1use crate::prelude::*;
2
3#[derive(Clone)]
4pub struct NotJoinedState {
5 pub(super) room: String,
6 err: Option<String>,
7}
8
9impl 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 }
13 }
14
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()) }
18 }
19}
20
21impl Editable<ProgramContext, ProgramStore, IambInfo> for NotJoinedState {
22 fn editor_command(
23 &mut self,
24 _: &EditorAction,
25 _: &ProgramContext,
26 _: &mut ProgramStore,
27 ) -> EditResult<EditInfo, IambInfo> {
28 Ok(None)
29 }
30}
31
32impl Jumpable<ProgramContext, IambInfo> for NotJoinedState {
33 fn jump(
34 &mut self,
35 _: PositionList,
36 _: MoveDir1D,
37 count: usize,
38 _: &ProgramContext,
39 ) -> IambResult<usize> {
40 Ok(count)
41 }
42}
43
44impl Scrollable<ProgramContext, ProgramStore, IambInfo> for NotJoinedState {
45 fn scroll(
46 &mut self,
47 _: &ScrollStyle,
48 _: &ProgramContext,
49 _: &mut ProgramStore,
50 ) -> EditResult<EditInfo, IambInfo> {
51 Ok(None)
52 }
53}
54
55impl Promptable<ProgramContext, ProgramStore, IambInfo> for NotJoinedState {
56 fn prompt(
57 &mut self,
58 _: &PromptAction,
59 _: &ProgramContext,
60 _: &mut ProgramStore,
61 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
62 Ok(vec![])
63 }
64}
65
66impl TerminalCursor for NotJoinedState {
67 fn get_term_cursor(&self) -> Option<TermOffset> {
68 None
69 }
70
71 fn hide_term_cursor(&self) -> bool {
72 true
73 }
74}
75
76/// [StatefulWidget] for Matrix rooms that haven't been joined.
77pub struct NotJoined;
78
79impl StatefulWidget for NotJoined {
80 type State = NotJoinedState;
81
82 fn render(self, area: Rect, buffer: &mut Buffer, state: &mut Self::State) {
83 let mut lines = vec![];
84
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 ]));
90
91 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)));
94 }
95
96 Paragraph::new(Text::from(lines))
97 .alignment(Alignment::Center)
98 .render(area, buffer);
99 }
100}
src/worker.rs +61 −52
@@ -683,11 +683,15 @@ impl<T> ClientResponse<T> {
683683 fn recv(self) -> T {
684684 self.0.recv().expect("failed to receive response from client thread")
685685 }
686
687 pub fn try_recv(&self) -> Option<T> {
688 self.0.try_recv().ok()
689 }
686690}
687691
688692impl<T> ClientReply<T> {
689693 fn send(self, t: T) {
690 self.0.send(t).unwrap();
694 let _ = self.0.send(t);
691695 }
692696}
693697
@@ -878,6 +882,50 @@ pub async fn create_client(settings: &ApplicationSettings) -> Client {
878882 client
879883}
880884
885async fn direct_message(user: OwnedUserId, client: Client) -> IambResult<OwnedRoomId> {
886 if let Some(room) = client.get_dm_room(&user) {
887 return Ok(room.room_id().to_owned());
888 }
889
890 client
891 .create_dm(&user)
892 .await
893 .map(|room| room.room_id().to_owned())
894 .map_err(|err| {
895 error!(
896 user_id = user.as_str(),
897 err = err.to_string(),
898 "Failed to create direct message room"
899 );
900
901 let msg = format!("Could not open a room with {user}");
902 UIError::Failure(msg)
903 })
904}
905
906async fn join_room(
907 name: String,
908 via: Vec<OwnedServerName>,
909 client: Client,
910) -> IambResult<OwnedRoomId> {
911 if let Ok(alias_id) = OwnedRoomOrAliasId::from_str(name.as_str()) {
912 match client.join_room_by_id_or_alias(&alias_id, &via).await {
913 Ok(resp) => Ok(resp.room_id().to_owned()),
914 Err(e) => {
915 let msg = e.to_string();
916 let err = UIError::Failure(msg);
917 return Err(err);
918 },
919 }
920 } else if let Ok(user) = OwnedUserId::try_from(name.as_str()) {
921 direct_message(user, client).await
922 } else {
923 let msg = format!("{:?} is not a valid room or user name", name.as_str());
924 let err = UIError::Failure(msg);
925 return Err(err);
926 }
927}
928
881929#[derive(Clone)]
882930pub struct Requester {
883931 pub client: Client,
@@ -933,12 +981,18 @@ impl Requester {
933981 return response.recv();
934982 }
935983
936 pub fn join_room(&self, name: String, via: Vec<OwnedServerName>) -> IambResult<OwnedRoomId> {
984 pub fn join_room_chan(
985 &self,
986 name: String,
987 via: Vec<OwnedServerName>,
988 ) -> ClientResponse<IambResult<OwnedRoomId>> {
937989 let (reply, response) = oneshot();
938
939990 self.tx.send(WorkerTask::JoinRoom(name, via, reply)).unwrap();
991 response
992 }
940993
941 return response.recv();
994 pub fn join_room(&self, name: String, via: Vec<OwnedServerName>) -> IambResult<OwnedRoomId> {
995 self.join_room_chan(name, via).recv()
942996 }
943997
944998 pub fn members(&self, room_id: OwnedRoomId) -> IambResult<Vec<RoomMember>> {
@@ -982,7 +1036,7 @@ pub struct ClientWorker {
9821036 load_handle: Option<JoinHandle<()>>,
9831037 sync_handle: Option<JoinHandle<()>>,
9841038
985 /// Take care when locking since worker commands are sent with the lock already hold
1039 /// Take care when locking since worker commands are sent with the lock already held
9861040 store: Option<AsyncProgramStore>,
9871041}
9881042
@@ -1036,7 +1090,8 @@ impl ClientWorker {
10361090 },
10371091 WorkerTask::JoinRoom(name, via, reply) => {
10381092 assert!(self.initialized);
1039 reply.send(self.join_room(name, via).await);
1093 let client = self.client.clone();
1094 tokio::spawn(async move { reply.send(join_room(name, via, client).await) });
10401095 },
10411096 WorkerTask::GetInviter(invited, reply) => {
10421097 assert!(self.initialized);
@@ -1476,27 +1531,6 @@ impl ClientWorker {
14761531 Ok(Some(InfoMessage::from("Successfully logged out")))
14771532 }
14781533
1479 async fn direct_message(&mut self, user: OwnedUserId) -> IambResult<OwnedRoomId> {
1480 if let Some(room) = self.client.get_dm_room(&user) {
1481 return Ok(room.room_id().to_owned());
1482 }
1483
1484 self.client
1485 .create_dm(&user)
1486 .await
1487 .map(|room| room.room_id().to_owned())
1488 .map_err(|err| {
1489 error!(
1490 user_id = user.as_str(),
1491 err = err.to_string(),
1492 "Failed to create direct message room"
1493 );
1494
1495 let msg = format!("Could not open a room with {user}");
1496 UIError::Failure(msg)
1497 })
1498 }
1499
15001534 async fn get_inviter(&mut self, invited: MatrixRoom) -> IambResult<Option<RoomMember>> {
15011535 let details = invited.invite_details().await.map_err(IambError::from)?;
15021536
@@ -1530,31 +1564,6 @@ impl ClientWorker {
15301564 }
15311565 }
15321566
1533 async fn join_room(
1534 &mut self,
1535 name: String,
1536 via: Vec<OwnedServerName>,
1537 ) -> IambResult<OwnedRoomId> {
1538 if let Ok(alias_id) = OwnedRoomOrAliasId::from_str(name.as_str()) {
1539 match self.client.join_room_by_id_or_alias(&alias_id, &via).await {
1540 Ok(resp) => Ok(resp.room_id().to_owned()),
1541 Err(e) => {
1542 let msg = e.to_string();
1543 let err = UIError::Failure(msg);
1544
1545 return Err(err);
1546 },
1547 }
1548 } else if let Ok(user) = OwnedUserId::try_from(name.as_str()) {
1549 self.direct_message(user).await
1550 } else {
1551 let msg = format!("{:?} is not a valid room or user name", name.as_str());
1552 let err = UIError::Failure(msg);
1553
1554 return Err(err);
1555 }
1556 }
1557
15581567 async fn members(&mut self, room_id: OwnedRoomId) -> IambResult<Vec<RoomMember>> {
15591568 if let Some(room) = self.client.get_room(room_id.as_ref()) {
15601569 Ok(room