src/windows/room/mod.rs
679 lines · 24510 bytes
1//! # Windows for Matrix rooms and spaces
2use std::collections::HashSet;
3
4use matrix_sdk::{
5 room::Room as MatrixRoom,
6 ruma::{
7 api::client::{
8 alias::{
9 create_alias::v3::Request as CreateAliasRequest,
10 delete_alias::v3::Request as DeleteAliasRequest,
11 },
12 error::ErrorKind as ClientApiErrorKind,
13 },
14 events::{
15 room::{
16 canonical_alias::RoomCanonicalAliasEventContent,
17 name::RoomNameEventContent,
18 topic::RoomTopicEventContent,
19 },
20 tag::{TagInfo, Tags},
21 },
22 OwnedEventId,
23 OwnedRoomAliasId,
24 RoomId,
25 },
26 DisplayName,
27 RoomState as MatrixRoomState,
28};
29
30use ratatui::{
31 buffer::Buffer,
32 layout::{Alignment, Rect},
33 style::{Modifier as StyleModifier, Style},
34 text::{Line, Span, Text},
35 widgets::{Paragraph, StatefulWidget, Widget},
36};
37
38use modalkit::actions::{
39 Action,
40 Editable,
41 EditorAction,
42 Jumpable,
43 PromptAction,
44 Promptable,
45 Scrollable,
46};
47use modalkit::errors::{EditResult, UIError};
48use modalkit::prelude::*;
49use modalkit::{editing::completion::CompletionList, keybindings::dialog::PromptYesNo};
50use modalkit_ratatui::{TermOffset, TerminalCursor, WindowOps};
51
52use crate::base::{
53 IambAction,
54 IambError,
55 IambId,
56 IambInfo,
57 IambResult,
58 MessageAction,
59 ProgramAction,
60 ProgramContext,
61 ProgramStore,
62 RoomAction,
63 RoomField,
64 SendAction,
65};
66
67use self::chat::ChatState;
68use self::space::{Space, SpaceState};
69
70use std::convert::TryFrom;
71
72mod chat;
73mod scrollback;
74mod space;
75
76macro_rules! delegate {
77 ($s: expr, $id: ident => $e: expr) => {
78 match $s {
79 RoomState::Chat($id) => $e,
80 RoomState::Space($id) => $e,
81 }
82 };
83}
84
85/// State for a Matrix room or space.
86///
87/// Since spaces function as special rooms within Matrix, we wrap their window state together, so
88/// that operations like sending and accepting invites, opening the members window, etc., all work
89/// similarly.
90pub enum RoomState {
91 Chat(ChatState),
92 Space(SpaceState),
93}
94
95impl From<ChatState> for RoomState {
96 fn from(chat: ChatState) -> Self {
97 RoomState::Chat(chat)
98 }
99}
100
101impl From<SpaceState> for RoomState {
102 fn from(space: SpaceState) -> Self {
103 RoomState::Space(space)
104 }
105}
106
107impl RoomState {
108 pub fn new(
109 room: MatrixRoom,
110 thread: Option<OwnedEventId>,
111 name: DisplayName,
112 tags: Option<Tags>,
113 store: &mut ProgramStore,
114 ) -> Self {
115 let room_id = room.room_id().to_owned();
116 let info = store.application.get_room_info(room_id);
117 info.name = name.to_string().into();
118 info.tags = tags;
119
120 if room.is_space() {
121 SpaceState::new(room).into()
122 } else {
123 ChatState::new(room, thread, store).into()
124 }
125 }
126
127 pub fn thread(&self) -> Option<&OwnedEventId> {
128 match self {
129 RoomState::Chat(chat) => chat.thread(),
130 RoomState::Space(_) => None,
131 }
132 }
133
134 pub fn refresh_room(&mut self, store: &mut ProgramStore) {
135 match self {
136 RoomState::Chat(chat) => chat.refresh_room(store),
137 RoomState::Space(space) => space.refresh_room(store),
138 }
139 }
140
141 fn draw_invite(
142 &self,
143 invited: MatrixRoom,
144 area: Rect,
145 buf: &mut Buffer,
146 store: &mut ProgramStore,
147 ) {
148 let inviter = store.application.worker.get_inviter(invited.clone());
149
150 let name = match invited.canonical_alias() {
151 Some(alias) => alias.to_string(),
152 None => format!("{:?}", store.application.get_room_title(self.id())),
153 };
154
155 let mut invited = vec![Span::from(format!("You have been invited to join {name}"))];
156
157 if let Ok(Some(inviter)) = &inviter {
158 let info = store.application.rooms.get_or_default(self.id().to_owned());
159 invited.push(Span::from(" by "));
160 invited.push(store.application.settings.get_user_span(inviter.user_id(), info));
161 }
162
163 let l1 = Line::from(invited);
164 let l2 = Line::from(
165 "You can run `:invite accept` or `:invite reject` to accept or reject this invitation.",
166 );
167 let text = Text::from(vec![l1, l2]);
168
169 Paragraph::new(text).alignment(Alignment::Center).render(area, buf);
170
171 return;
172 }
173
174 pub async fn message_command(
175 &mut self,
176 act: MessageAction,
177 ctx: ProgramContext,
178 store: &mut ProgramStore,
179 ) -> IambResult<EditInfo> {
180 match self {
181 RoomState::Chat(chat) => chat.message_command(act, ctx, store).await,
182 RoomState::Space(_) => Err(IambError::NoSelectedMessage.into()),
183 }
184 }
185
186 pub async fn send_command(
187 &mut self,
188 act: SendAction,
189 ctx: ProgramContext,
190 store: &mut ProgramStore,
191 ) -> IambResult<EditInfo> {
192 match self {
193 RoomState::Chat(chat) => chat.send_command(act, ctx, store).await,
194 RoomState::Space(_) => Err(IambError::NoSelectedRoom.into()),
195 }
196 }
197
198 pub async fn room_command(
199 &mut self,
200 act: RoomAction,
201 ctx: ProgramContext,
202 store: &mut ProgramStore,
203 ) -> IambResult<Vec<(Action<IambInfo>, ProgramContext)>> {
204 match act {
205 RoomAction::InviteAccept => {
206 if let Some(room) = store.application.worker.client.get_room(self.id()) {
207 let details = room.invite_details().await.map_err(IambError::from)?;
208 let details = details.invitee.event().original_content();
209 let is_direct = details.and_then(|ev| ev.is_direct).unwrap_or_default();
210
211 room.join().await.map_err(IambError::from)?;
212
213 if is_direct {
214 room.set_is_direct(true).await.map_err(IambError::from)?;
215 }
216
217 Ok(vec![])
218 } else {
219 Err(IambError::NotInvited.into())
220 }
221 },
222 RoomAction::InviteReject => {
223 if let Some(room) = store.application.worker.client.get_room(self.id()) {
224 room.leave().await.map_err(IambError::from)?;
225
226 Ok(vec![])
227 } else {
228 Err(IambError::NotInvited.into())
229 }
230 },
231 RoomAction::InviteSend(user) => {
232 if let Some(room) = store.application.worker.client.get_room(self.id()) {
233 room.invite_user_by_id(user.as_ref()).await.map_err(IambError::from)?;
234
235 Ok(vec![])
236 } else {
237 Err(IambError::NotJoined.into())
238 }
239 },
240 RoomAction::Leave(skip_confirm) => {
241 if let Some(room) = store.application.worker.client.get_room(self.id()) {
242 if skip_confirm {
243 room.leave().await.map_err(IambError::from)?;
244
245 Ok(vec![])
246 } else {
247 let msg = "Do you really want to leave this room?";
248 let leave = IambAction::Room(RoomAction::Leave(true));
249 let prompt = PromptYesNo::new(msg, vec![Action::from(leave)]);
250 let prompt = Box::new(prompt);
251
252 Err(UIError::NeedConfirm(prompt))
253 }
254 } else {
255 Err(IambError::NotJoined.into())
256 }
257 },
258 RoomAction::Members(mut cmd) => {
259 let width = Count::Exact(30);
260 let act =
261 cmd.default_axis(Axis::Vertical).default_relation(MoveDir1D::Next).window(
262 OpenTarget::Application(IambId::MemberList(self.id().to_owned())),
263 width.into(),
264 );
265
266 Ok(vec![(act, cmd.context.clone())])
267 },
268 RoomAction::SetDirect(is_direct) => {
269 let room = store
270 .application
271 .get_joined_room(self.id())
272 .ok_or(UIError::Application(IambError::NotJoined))?;
273
274 room.set_is_direct(is_direct).await.map_err(IambError::from)?;
275
276 Ok(vec![])
277 },
278 RoomAction::Set(field, value) => {
279 let room = store
280 .application
281 .get_joined_room(self.id())
282 .ok_or(UIError::Application(IambError::NotJoined))?;
283
284 match field {
285 RoomField::Name => {
286 let ev = RoomNameEventContent::new(value);
287 let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
288 },
289 RoomField::Tag(tag) => {
290 let mut info = TagInfo::new();
291 info.order = Some(1.0);
292
293 let _ = room.set_tag(tag, info).await.map_err(IambError::from)?;
294 },
295 RoomField::Topic => {
296 let ev = RoomTopicEventContent::new(value);
297 let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
298 },
299 RoomField::CanonicalAlias => {
300 let client = &mut store.application.worker.client;
301
302 let Ok(orai) = OwnedRoomAliasId::try_from(value.as_str()) else {
303 let err = IambError::InvalidRoomAlias(value);
304
305 return Err(err.into());
306 };
307
308 let mut alt_aliases =
309 room.alt_aliases().into_iter().collect::<HashSet<_>>();
310 let canonical_old = room.canonical_alias();
311
312 // If the room's alias is already that, ignore it
313 if canonical_old.as_ref() == Some(&orai) {
314 let msg = format!("The canonical room alias is already {orai}");
315
316 return Ok(vec![(Action::ShowInfoMessage(msg.into()), ctx)]);
317 }
318
319 // Try creating the room alias on the server.
320 let alias_create_req =
321 CreateAliasRequest::new(orai.clone(), room.room_id().into());
322 if let Err(e) = client.send(alias_create_req, None).await {
323 if let Some(ClientApiErrorKind::Unknown) = e.client_api_error_kind() {
324 // Ignore when it already exists.
325 } else {
326 return Err(IambError::from(e).into());
327 }
328 }
329
330 // Demote the previous one to an alt alias.
331 alt_aliases.extend(canonical_old);
332
333 // At this point the room alias definitely exists, and we can update the
334 // state event.
335 let mut ev = RoomCanonicalAliasEventContent::new();
336 ev.alias = Some(orai);
337 ev.alt_aliases = alt_aliases.into_iter().collect();
338 let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
339 },
340 RoomField::Alias(alias) => {
341 let client = &mut store.application.worker.client;
342
343 let Ok(orai) = OwnedRoomAliasId::try_from(alias.as_str()) else {
344 let err = IambError::InvalidRoomAlias(alias);
345
346 return Err(err.into());
347 };
348
349 let mut alt_aliases =
350 room.alt_aliases().into_iter().collect::<HashSet<_>>();
351 let canonical = room.canonical_alias();
352
353 if alt_aliases.contains(&orai) || canonical.as_ref() == Some(&orai) {
354 let msg = format!("The alias {orai} already maps to this room");
355
356 return Ok(vec![(Action::ShowInfoMessage(msg.into()), ctx)]);
357 } else {
358 alt_aliases.insert(orai.clone());
359 }
360
361 // If the room alias does not exist on the server, create it
362 let alias_create_req = CreateAliasRequest::new(orai, room.room_id().into());
363 if let Err(e) = client.send(alias_create_req, None).await {
364 if let Some(ClientApiErrorKind::Unknown) = e.client_api_error_kind() {
365 // Ignore when it already exists.
366 } else {
367 return Err(IambError::from(e).into());
368 }
369 }
370
371 // And add it to the aliases in the state event.
372 let mut ev = RoomCanonicalAliasEventContent::new();
373 ev.alias = canonical;
374 ev.alt_aliases = alt_aliases.into_iter().collect();
375 let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
376 },
377 RoomField::Aliases => {
378 // This never happens, aliases is only used for showing
379 },
380 }
381
382 Ok(vec![])
383 },
384 RoomAction::Unset(field) => {
385 let room = store
386 .application
387 .get_joined_room(self.id())
388 .ok_or(UIError::Application(IambError::NotJoined))?;
389
390 match field {
391 RoomField::Name => {
392 let ev = RoomNameEventContent::new("".into());
393 let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
394 },
395 RoomField::Tag(tag) => {
396 let _ = room.remove_tag(tag).await.map_err(IambError::from)?;
397 },
398 RoomField::Topic => {
399 let ev = RoomTopicEventContent::new("".into());
400 let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
401 },
402 RoomField::CanonicalAlias => {
403 let Some(alias_to_destroy) = room.canonical_alias() else {
404 let msg = "This room has no canonical alias to unset";
405
406 return Ok(vec![(Action::ShowInfoMessage(msg.into()), ctx)]);
407 };
408
409 // Remove the canonical alias from the state event.
410 let mut ev = RoomCanonicalAliasEventContent::new();
411 ev.alias = None;
412 ev.alt_aliases = room.alt_aliases();
413 let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
414
415 // And then unmap it on the server.
416 let del_req = DeleteAliasRequest::new(alias_to_destroy);
417 let _ = store
418 .application
419 .worker
420 .client
421 .send(del_req, None)
422 .await
423 .map_err(IambError::from)?;
424 },
425 RoomField::Alias(alias) => {
426 let Ok(orai) = OwnedRoomAliasId::try_from(alias.as_str()) else {
427 let err = IambError::InvalidRoomAlias(alias);
428
429 return Err(err.into());
430 };
431
432 let alt_aliases = room.alt_aliases();
433 let canonical = room.canonical_alias();
434
435 if !alt_aliases.contains(&orai) && canonical.as_ref() != Some(&orai) {
436 let msg = format!("The alias {orai:?} isn't mapped to this room");
437
438 return Ok(vec![(Action::ShowInfoMessage(msg.into()), ctx)]);
439 }
440
441 // Remove the alias from the state event if it's in it.
442 let mut ev = RoomCanonicalAliasEventContent::new();
443 ev.alias = canonical.filter(|canon| canon != &orai);
444 ev.alt_aliases = alt_aliases;
445 ev.alt_aliases.retain(|in_orai| in_orai != &orai);
446 let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
447
448 // And then unmap it on the server.
449 let del_req = DeleteAliasRequest::new(orai);
450 let _ = store
451 .application
452 .worker
453 .client
454 .send(del_req, None)
455 .await
456 .map_err(IambError::from)?;
457 },
458 RoomField::Aliases => {
459 // This will not happen, you cannot unset all aliases
460 },
461 }
462
463 Ok(vec![])
464 },
465 RoomAction::Show(field) => {
466 let room = store
467 .application
468 .get_joined_room(self.id())
469 .ok_or(UIError::Application(IambError::NotJoined))?;
470
471 let msg = match field {
472 RoomField::Name => {
473 match room.name() {
474 None => "Room has no name".into(),
475 Some(name) => format!("Room name: {name:?}"),
476 }
477 },
478 RoomField::Topic => {
479 match room.topic() {
480 None => "Room has no topic".into(),
481 Some(topic) => format!("Room topic: {topic:?}"),
482 }
483 },
484 RoomField::Aliases => {
485 let aliases = room
486 .alt_aliases()
487 .iter()
488 .map(OwnedRoomAliasId::to_string)
489 .collect::<Vec<String>>();
490
491 if aliases.is_empty() {
492 "No alternative aliases in room".into()
493 } else {
494 format!("Alternative aliases: {}.", aliases.join(", "))
495 }
496 },
497 RoomField::CanonicalAlias => {
498 match room.canonical_alias() {
499 None => "No canonical alias for room".into(),
500 Some(can) => format!("Canonical alias: {can}"),
501 }
502 },
503 RoomField::Tag(_) => "Cannot currently show value for a tag".into(),
504 RoomField::Alias(_) => {
505 "Cannot show a single alias; use `:room aliases show` instead.".into()
506 },
507 };
508
509 let msg = InfoMessage::Pager(msg);
510 let act = Action::ShowInfoMessage(msg);
511
512 Ok(vec![(act, ctx)])
513 },
514 }
515 }
516
517 pub fn get_title(&self, store: &mut ProgramStore) -> Line {
518 let title = store.application.get_room_title(self.id());
519 let style = Style::default().add_modifier(StyleModifier::BOLD);
520 let mut spans = vec![];
521
522 if let RoomState::Chat(chat) = self {
523 if chat.thread().is_some() {
524 spans.push("Thread in ".into());
525 }
526 }
527
528 spans.push(Span::styled(title, style));
529
530 match self.room().topic() {
531 Some(desc) if !desc.is_empty() => {
532 spans.push(" (".into());
533 spans.push(desc.into());
534 spans.push(")".into());
535 },
536 _ => {},
537 }
538
539 Line::from(spans)
540 }
541
542 pub fn focus_toggle(&mut self) {
543 match self {
544 RoomState::Chat(chat) => chat.focus_toggle(),
545 RoomState::Space(_) => return,
546 }
547 }
548
549 pub fn room(&self) -> &MatrixRoom {
550 match self {
551 RoomState::Chat(chat) => chat.room(),
552 RoomState::Space(space) => space.room(),
553 }
554 }
555
556 pub fn id(&self) -> &RoomId {
557 match self {
558 RoomState::Chat(chat) => chat.id(),
559 RoomState::Space(space) => space.id(),
560 }
561 }
562}
563
564impl Editable<ProgramContext, ProgramStore, IambInfo> for RoomState {
565 fn editor_command(
566 &mut self,
567 act: &EditorAction,
568 ctx: &ProgramContext,
569 store: &mut ProgramStore,
570 ) -> EditResult<EditInfo, IambInfo> {
571 delegate!(self, w => w.editor_command(act, ctx, store))
572 }
573}
574
575impl Jumpable<ProgramContext, IambInfo> for RoomState {
576 fn jump(
577 &mut self,
578 list: PositionList,
579 dir: MoveDir1D,
580 count: usize,
581 ctx: &ProgramContext,
582 ) -> IambResult<usize> {
583 delegate!(self, w => w.jump(list, dir, count, ctx))
584 }
585}
586
587impl Scrollable<ProgramContext, ProgramStore, IambInfo> for RoomState {
588 fn scroll(
589 &mut self,
590 style: &ScrollStyle,
591 ctx: &ProgramContext,
592 store: &mut ProgramStore,
593 ) -> EditResult<EditInfo, IambInfo> {
594 delegate!(self, w => w.scroll(style, ctx, store))
595 }
596}
597
598impl Promptable<ProgramContext, ProgramStore, IambInfo> for RoomState {
599 fn prompt(
600 &mut self,
601 act: &PromptAction,
602 ctx: &ProgramContext,
603 store: &mut ProgramStore,
604 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
605 delegate!(self, w => w.prompt(act, ctx, store))
606 }
607}
608
609impl TerminalCursor for RoomState {
610 fn get_term_cursor(&self) -> Option<TermOffset> {
611 delegate!(self, w => w.get_term_cursor())
612 }
613}
614
615impl WindowOps<IambInfo> for RoomState {
616 fn draw(&mut self, area: Rect, buf: &mut Buffer, focused: bool, store: &mut ProgramStore) {
617 if self.room().state() == MatrixRoomState::Invited {
618 self.refresh_room(store);
619 }
620
621 if self.room().state() == MatrixRoomState::Invited {
622 self.draw_invite(self.room().clone(), area, buf, store);
623 }
624
625 match self {
626 RoomState::Chat(chat) => chat.draw(area, buf, focused, store),
627 RoomState::Space(space) => {
628 Space::new(store).focus(focused).render(area, buf, space);
629 },
630 }
631 }
632
633 fn dup(&self, store: &mut ProgramStore) -> Self {
634 match self {
635 RoomState::Chat(chat) => RoomState::Chat(chat.dup(store)),
636 RoomState::Space(space) => RoomState::Space(space.dup(store)),
637 }
638 }
639
640 fn close(&mut self, flags: CloseFlags, store: &mut ProgramStore) -> bool {
641 match self {
642 RoomState::Chat(chat) => chat.close(flags, store),
643 RoomState::Space(space) => space.close(flags, store),
644 }
645 }
646
647 fn write(
648 &mut self,
649 path: Option<&str>,
650 flags: WriteFlags,
651 store: &mut ProgramStore,
652 ) -> IambResult<EditInfo> {
653 match self {
654 RoomState::Chat(chat) => chat.write(path, flags, store),
655 RoomState::Space(space) => space.write(path, flags, store),
656 }
657 }
658
659 fn get_completions(&self) -> Option<CompletionList> {
660 match self {
661 RoomState::Chat(chat) => chat.get_completions(),
662 RoomState::Space(space) => space.get_completions(),
663 }
664 }
665
666 fn get_cursor_word(&self, style: &WordStyle) -> Option<String> {
667 match self {
668 RoomState::Chat(chat) => chat.get_cursor_word(style),
669 RoomState::Space(space) => space.get_cursor_word(style),
670 }
671 }
672
673 fn get_selected_word(&self) -> Option<String> {
674 match self {
675 RoomState::Chat(chat) => chat.get_selected_word(),
676 RoomState::Space(space) => space.get_selected_word(),
677 }
678 }
679}