src/windows/room/mod.rs
446 lines · 14046 bytes
1//! # Windows for Matrix rooms and spaces
2use matrix_sdk::{
3 room::{Invited, Room as MatrixRoom},
4 ruma::{
5 events::{
6 room::{name::RoomNameEventContent, topic::RoomTopicEventContent},
7 tag::{TagInfo, Tags},
8 },
9 RoomId,
10 },
11 DisplayName,
12};
13
14use ratatui::{
15 buffer::Buffer,
16 layout::{Alignment, Rect},
17 style::{Modifier as StyleModifier, Style},
18 text::{Line, Span, Text},
19 widgets::{Paragraph, StatefulWidget, Widget},
20};
21
22use modalkit::actions::{
23 Action,
24 Editable,
25 EditorAction,
26 Jumpable,
27 PromptAction,
28 Promptable,
29 Scrollable,
30};
31use modalkit::errors::{EditResult, UIError};
32use modalkit::prelude::*;
33use modalkit::{editing::completion::CompletionList, keybindings::dialog::PromptYesNo};
34use modalkit_ratatui::{TermOffset, TerminalCursor, WindowOps};
35
36use crate::base::{
37 IambAction,
38 IambError,
39 IambId,
40 IambInfo,
41 IambResult,
42 MessageAction,
43 ProgramAction,
44 ProgramContext,
45 ProgramStore,
46 RoomAction,
47 RoomField,
48 SendAction,
49};
50
51use self::chat::ChatState;
52use self::space::{Space, SpaceState};
53
54mod chat;
55mod scrollback;
56mod space;
57
58macro_rules! delegate {
59 ($s: expr, $id: ident => $e: expr) => {
60 match $s {
61 RoomState::Chat($id) => $e,
62 RoomState::Space($id) => $e,
63 }
64 };
65}
66
67/// State for a Matrix room or space.
68///
69/// Since spaces function as special rooms within Matrix, we wrap their window state together, so
70/// that operations like sending and accepting invites, opening the members window, etc., all work
71/// similarly.
72pub enum RoomState {
73 Chat(ChatState),
74 Space(SpaceState),
75}
76
77impl From<ChatState> for RoomState {
78 fn from(chat: ChatState) -> Self {
79 RoomState::Chat(chat)
80 }
81}
82
83impl From<SpaceState> for RoomState {
84 fn from(space: SpaceState) -> Self {
85 RoomState::Space(space)
86 }
87}
88
89impl RoomState {
90 pub fn new(
91 room: MatrixRoom,
92 name: DisplayName,
93 tags: Option<Tags>,
94 store: &mut ProgramStore,
95 ) -> Self {
96 let room_id = room.room_id().to_owned();
97 let info = store.application.get_room_info(room_id);
98 info.name = name.to_string().into();
99 info.tags = tags;
100
101 if room.is_space() {
102 SpaceState::new(room).into()
103 } else {
104 ChatState::new(room, store).into()
105 }
106 }
107
108 pub fn refresh_room(&mut self, store: &mut ProgramStore) {
109 match self {
110 RoomState::Chat(chat) => chat.refresh_room(store),
111 RoomState::Space(space) => space.refresh_room(store),
112 }
113 }
114
115 fn draw_invite(
116 &self,
117 invited: Invited,
118 area: Rect,
119 buf: &mut Buffer,
120 store: &mut ProgramStore,
121 ) {
122 let inviter = store.application.worker.get_inviter(invited.clone());
123
124 let name = match invited.canonical_alias() {
125 Some(alias) => alias.to_string(),
126 None => format!("{:?}", store.application.get_room_title(self.id())),
127 };
128
129 let mut invited = vec![Span::from(format!("You have been invited to join {name}"))];
130
131 if let Ok(Some(inviter)) = &inviter {
132 let info = store.application.rooms.get_or_default(self.id().to_owned());
133 invited.push(Span::from(" by "));
134 invited.push(store.application.settings.get_user_span(inviter.user_id(), info));
135 }
136
137 let l1 = Line::from(invited);
138 let l2 = Line::from(
139 "You can run `:invite accept` or `:invite reject` to accept or reject this invitation.",
140 );
141 let text = Text { lines: vec![l1, l2] };
142
143 Paragraph::new(text).alignment(Alignment::Center).render(area, buf);
144
145 return;
146 }
147
148 pub async fn message_command(
149 &mut self,
150 act: MessageAction,
151 ctx: ProgramContext,
152 store: &mut ProgramStore,
153 ) -> IambResult<EditInfo> {
154 match self {
155 RoomState::Chat(chat) => chat.message_command(act, ctx, store).await,
156 RoomState::Space(_) => Err(IambError::NoSelectedMessage.into()),
157 }
158 }
159
160 pub async fn send_command(
161 &mut self,
162 act: SendAction,
163 ctx: ProgramContext,
164 store: &mut ProgramStore,
165 ) -> IambResult<EditInfo> {
166 match self {
167 RoomState::Chat(chat) => chat.send_command(act, ctx, store).await,
168 RoomState::Space(_) => Err(IambError::NoSelectedRoom.into()),
169 }
170 }
171
172 pub async fn room_command(
173 &mut self,
174 act: RoomAction,
175 _: ProgramContext,
176 store: &mut ProgramStore,
177 ) -> IambResult<Vec<(Action<IambInfo>, ProgramContext)>> {
178 match act {
179 RoomAction::InviteAccept => {
180 if let Some(room) = store.application.worker.client.get_invited_room(self.id()) {
181 let details = room.invite_details().await.map_err(IambError::from)?;
182 let details = details.invitee.event().original_content();
183 let is_direct = details.and_then(|ev| ev.is_direct).unwrap_or_default();
184
185 room.accept_invitation().await.map_err(IambError::from)?;
186
187 if is_direct {
188 room.set_is_direct(true).await.map_err(IambError::from)?;
189 }
190
191 Ok(vec![])
192 } else {
193 Err(IambError::NotInvited.into())
194 }
195 },
196 RoomAction::InviteReject => {
197 if let Some(room) = store.application.worker.client.get_invited_room(self.id()) {
198 room.reject_invitation().await.map_err(IambError::from)?;
199
200 Ok(vec![])
201 } else {
202 Err(IambError::NotInvited.into())
203 }
204 },
205 RoomAction::InviteSend(user) => {
206 if let Some(room) = store.application.worker.client.get_joined_room(self.id()) {
207 room.invite_user_by_id(user.as_ref()).await.map_err(IambError::from)?;
208
209 Ok(vec![])
210 } else {
211 Err(IambError::NotJoined.into())
212 }
213 },
214 RoomAction::Leave(skip_confirm) => {
215 if let Some(room) = store.application.worker.client.get_joined_room(self.id()) {
216 if skip_confirm {
217 room.leave().await.map_err(IambError::from)?;
218
219 Ok(vec![])
220 } else {
221 let msg = "Do you really want to leave this room?";
222 let leave = IambAction::Room(RoomAction::Leave(true));
223 let prompt = PromptYesNo::new(msg, vec![Action::from(leave)]);
224 let prompt = Box::new(prompt);
225
226 Err(UIError::NeedConfirm(prompt))
227 }
228 } else {
229 Err(IambError::NotJoined.into())
230 }
231 },
232 RoomAction::Members(mut cmd) => {
233 let width = Count::Exact(30);
234 let act =
235 cmd.default_axis(Axis::Vertical).default_relation(MoveDir1D::Next).window(
236 OpenTarget::Application(IambId::MemberList(self.id().to_owned())),
237 width.into(),
238 );
239
240 Ok(vec![(act, cmd.context.clone())])
241 },
242 RoomAction::Set(field, value) => {
243 let room = store
244 .application
245 .get_joined_room(self.id())
246 .ok_or(UIError::Application(IambError::NotJoined))?;
247
248 match field {
249 RoomField::Name => {
250 let ev = RoomNameEventContent::new(value.into());
251 let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
252 },
253 RoomField::Tag(tag) => {
254 let mut info = TagInfo::new();
255 info.order = Some(1.0);
256
257 let _ = room.set_tag(tag, info).await.map_err(IambError::from)?;
258 },
259 RoomField::Topic => {
260 let ev = RoomTopicEventContent::new(value);
261 let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
262 },
263 }
264
265 Ok(vec![])
266 },
267 RoomAction::Unset(field) => {
268 let room = store
269 .application
270 .get_joined_room(self.id())
271 .ok_or(UIError::Application(IambError::NotJoined))?;
272
273 match field {
274 RoomField::Name => {
275 let ev = RoomNameEventContent::new(None);
276 let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
277 },
278 RoomField::Tag(tag) => {
279 let _ = room.remove_tag(tag).await.map_err(IambError::from)?;
280 },
281 RoomField::Topic => {
282 let ev = RoomTopicEventContent::new("".into());
283 let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
284 },
285 }
286
287 Ok(vec![])
288 },
289 }
290 }
291
292 pub fn get_title(&self, store: &mut ProgramStore) -> Line {
293 let title = store.application.get_room_title(self.id());
294 let style = Style::default().add_modifier(StyleModifier::BOLD);
295 let mut spans = vec![Span::styled(title, style)];
296
297 match self.room().topic() {
298 Some(desc) if !desc.is_empty() => {
299 spans.push(" (".into());
300 spans.push(desc.into());
301 spans.push(")".into());
302 },
303 _ => {},
304 }
305
306 Line::from(spans)
307 }
308
309 pub fn focus_toggle(&mut self) {
310 match self {
311 RoomState::Chat(chat) => chat.focus_toggle(),
312 RoomState::Space(_) => return,
313 }
314 }
315
316 pub fn room(&self) -> &MatrixRoom {
317 match self {
318 RoomState::Chat(chat) => chat.room(),
319 RoomState::Space(space) => space.room(),
320 }
321 }
322
323 pub fn id(&self) -> &RoomId {
324 match self {
325 RoomState::Chat(chat) => chat.id(),
326 RoomState::Space(space) => space.id(),
327 }
328 }
329}
330
331impl Editable<ProgramContext, ProgramStore, IambInfo> for RoomState {
332 fn editor_command(
333 &mut self,
334 act: &EditorAction,
335 ctx: &ProgramContext,
336 store: &mut ProgramStore,
337 ) -> EditResult<EditInfo, IambInfo> {
338 delegate!(self, w => w.editor_command(act, ctx, store))
339 }
340}
341
342impl Jumpable<ProgramContext, IambInfo> for RoomState {
343 fn jump(
344 &mut self,
345 list: PositionList,
346 dir: MoveDir1D,
347 count: usize,
348 ctx: &ProgramContext,
349 ) -> IambResult<usize> {
350 delegate!(self, w => w.jump(list, dir, count, ctx))
351 }
352}
353
354impl Scrollable<ProgramContext, ProgramStore, IambInfo> for RoomState {
355 fn scroll(
356 &mut self,
357 style: &ScrollStyle,
358 ctx: &ProgramContext,
359 store: &mut ProgramStore,
360 ) -> EditResult<EditInfo, IambInfo> {
361 delegate!(self, w => w.scroll(style, ctx, store))
362 }
363}
364
365impl Promptable<ProgramContext, ProgramStore, IambInfo> for RoomState {
366 fn prompt(
367 &mut self,
368 act: &PromptAction,
369 ctx: &ProgramContext,
370 store: &mut ProgramStore,
371 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
372 delegate!(self, w => w.prompt(act, ctx, store))
373 }
374}
375
376impl TerminalCursor for RoomState {
377 fn get_term_cursor(&self) -> Option<TermOffset> {
378 delegate!(self, w => w.get_term_cursor())
379 }
380}
381
382impl WindowOps<IambInfo> for RoomState {
383 fn draw(&mut self, area: Rect, buf: &mut Buffer, focused: bool, store: &mut ProgramStore) {
384 if let MatrixRoom::Invited(_) = self.room() {
385 self.refresh_room(store);
386 }
387
388 if let MatrixRoom::Invited(invited) = self.room() {
389 self.draw_invite(invited.clone(), area, buf, store);
390 }
391
392 match self {
393 RoomState::Chat(chat) => chat.draw(area, buf, focused, store),
394 RoomState::Space(space) => {
395 Space::new(store).focus(focused).render(area, buf, space);
396 },
397 }
398 }
399
400 fn dup(&self, store: &mut ProgramStore) -> Self {
401 match self {
402 RoomState::Chat(chat) => RoomState::Chat(chat.dup(store)),
403 RoomState::Space(space) => RoomState::Space(space.dup(store)),
404 }
405 }
406
407 fn close(&mut self, flags: CloseFlags, store: &mut ProgramStore) -> bool {
408 match self {
409 RoomState::Chat(chat) => chat.close(flags, store),
410 RoomState::Space(space) => space.close(flags, store),
411 }
412 }
413
414 fn write(
415 &mut self,
416 path: Option<&str>,
417 flags: WriteFlags,
418 store: &mut ProgramStore,
419 ) -> IambResult<EditInfo> {
420 match self {
421 RoomState::Chat(chat) => chat.write(path, flags, store),
422 RoomState::Space(space) => space.write(path, flags, store),
423 }
424 }
425
426 fn get_completions(&self) -> Option<CompletionList> {
427 match self {
428 RoomState::Chat(chat) => chat.get_completions(),
429 RoomState::Space(space) => space.get_completions(),
430 }
431 }
432
433 fn get_cursor_word(&self, style: &WordStyle) -> Option<String> {
434 match self {
435 RoomState::Chat(chat) => chat.get_cursor_word(style),
436 RoomState::Space(space) => space.get_cursor_word(style),
437 }
438 }
439
440 fn get_selected_word(&self) -> Option<String> {
441 match self {
442 RoomState::Chat(chat) => chat.get_selected_word(),
443 RoomState::Space(space) => space.get_selected_word(),
444 }
445 }
446}