src/windows/room/mod.rs
861 lines · 30649 bytes
1//! # Windows for Matrix rooms and spaces
2use std::collections::HashSet;
3
4use matrix_sdk::ruma::api::error::ErrorKind as ClientApiErrorKind;
5use matrix_sdk::{
6 RoomDisplayName,
7 RoomState as MatrixRoomState,
8 notification_settings::RoomNotificationMode,
9 room::Room as MatrixRoom,
10 ruma::{
11 OwnedEventId,
12 OwnedRoomAliasId,
13 OwnedUserId,
14 RoomId,
15 events::{
16 room::{
17 canonical_alias::RoomCanonicalAliasEventContent,
18 history_visibility::{HistoryVisibility, RoomHistoryVisibilityEventContent},
19 name::RoomNameEventContent,
20 topic::RoomTopicEventContent,
21 },
22 tag::{TagInfo, Tags},
23 },
24 },
25};
26
27use ratatui::{
28 buffer::Buffer,
29 layout::{Alignment, Rect},
30 style::{Modifier as StyleModifier, Style},
31 text::{Line, Span, Text},
32 widgets::{Paragraph, StatefulWidget, Widget},
33};
34
35use modalkit::actions::{
36 Action,
37 Editable,
38 EditorAction,
39 Jumpable,
40 PromptAction,
41 Promptable,
42 Scrollable,
43};
44use modalkit::errors::{EditResult, UIError};
45use modalkit::prelude::*;
46use modalkit::{editing::completion::CompletionList, keybindings::dialog::PromptYesNo};
47use modalkit_ratatui::{TermOffset, TerminalCursor, WindowOps};
48
49use crate::base::{
50 IambAction,
51 IambError,
52 IambId,
53 IambInfo,
54 IambResult,
55 MemberUpdateAction,
56 MessageAction,
57 ProgramAction,
58 ProgramContext,
59 ProgramStore,
60 RoomAction,
61 RoomField,
62 SendAction,
63 SpaceAction,
64};
65
66use self::chat::ChatState;
67use self::space::{Space, SpaceState};
68use crate::config::EncryptionIndicatorLocation;
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
85fn notification_mode(name: impl Into<String>) -> IambResult<RoomNotificationMode> {
86 let name = name.into();
87
88 let mode = match name.to_lowercase().as_str() {
89 "mute" => RoomNotificationMode::Mute,
90 "mentions" | "keywords" => RoomNotificationMode::MentionsAndKeywordsOnly,
91 "all" => RoomNotificationMode::AllMessages,
92 _ => return Err(IambError::InvalidNotificationLevel(name).into()),
93 };
94
95 Ok(mode)
96}
97
98fn hist_visibility_mode(name: impl Into<String>) -> IambResult<HistoryVisibility> {
99 let name = name.into();
100
101 let mode = match name.to_lowercase().as_str() {
102 "invited" => HistoryVisibility::Invited,
103 "joined" => HistoryVisibility::Joined,
104 "shared" => HistoryVisibility::Shared,
105 "world" | "world_readable" => HistoryVisibility::WorldReadable,
106 _ => return Err(IambError::InvalidHistoryVisibility(name).into()),
107 };
108
109 Ok(mode)
110}
111
112pub async fn room_command(
113 id: &RoomId,
114 act: RoomAction,
115 ctx: ProgramContext,
116 store: &mut ProgramStore,
117) -> IambResult<Vec<(Action<IambInfo>, ProgramContext)>> {
118 match act {
119 RoomAction::InviteAccept => {
120 if let Some(room) = store.application.worker.client.get_room(id) {
121 room.join().await.map_err(IambError::from)?;
122 Ok(vec![])
123 } else {
124 Err(IambError::NotInvited.into())
125 }
126 },
127 RoomAction::InviteReject => {
128 if let Some(room) = store.application.worker.client.get_room(id) {
129 room.leave().await.map_err(IambError::from)?;
130
131 Ok(vec![])
132 } else {
133 Err(IambError::NotInvited.into())
134 }
135 },
136 RoomAction::InviteSend(user) => {
137 if let Some(room) = store.application.worker.client.get_room(id) {
138 room.invite_user_by_id(user.as_ref()).await.map_err(IambError::from)?;
139
140 Ok(vec![])
141 } else {
142 Err(IambError::NotJoined.into())
143 }
144 },
145 RoomAction::Leave(skip_confirm) => {
146 if let Some(room) = store.application.worker.client.get_room(id) {
147 if skip_confirm {
148 room.leave().await.map_err(IambError::from)?;
149
150 Ok(vec![])
151 } else {
152 let msg = "Do you really want to leave this room?";
153 let leave = IambAction::Room(RoomAction::Leave(true));
154 let prompt = PromptYesNo::new(msg, vec![Action::from(leave)]);
155 let prompt = Box::new(prompt);
156
157 Err(UIError::NeedConfirm(prompt))
158 }
159 } else {
160 Err(IambError::NotJoined.into())
161 }
162 },
163 RoomAction::MemberUpdate(mua, user, reason, skip_confirm) => {
164 let Some(room) = store.application.worker.client.get_room(id) else {
165 return Err(IambError::NotJoined.into());
166 };
167
168 let Ok(user_id) = OwnedUserId::try_from(user.as_str()) else {
169 let err = IambError::InvalidUserId(user);
170
171 return Err(err.into());
172 };
173
174 if !skip_confirm {
175 let msg = format!("Do you really want to {mua} {user} from this room?");
176 let act = RoomAction::MemberUpdate(mua, user, reason, true);
177 let act = IambAction::from(act);
178 let prompt = PromptYesNo::new(msg, vec![Action::from(act)]);
179 let prompt = Box::new(prompt);
180
181 return Err(UIError::NeedConfirm(prompt));
182 }
183
184 match mua {
185 MemberUpdateAction::Ban => {
186 room.ban_user(&user_id, reason.as_deref()).await.map_err(IambError::from)?;
187 },
188 MemberUpdateAction::Unban => {
189 room.unban_user(&user_id, reason.as_deref())
190 .await
191 .map_err(IambError::from)?;
192 },
193 MemberUpdateAction::Kick => {
194 room.kick_user(&user_id, reason.as_deref())
195 .await
196 .map_err(IambError::from)?;
197 },
198 }
199
200 Ok(vec![])
201 },
202 RoomAction::Members(mut cmd) => {
203 let id = IambId::MemberList(id.to_owned());
204 let target = OpenTarget::Application(id);
205 let cmd = cmd.default_relation(MoveDir1D::Next);
206
207 let act = match store.application.settings.tunables.members_split {
208 Some(dir) => cmd.default_axis(dir.to_axis()).window(target, None),
209 None => cmd.switch(target),
210 };
211
212 Ok(vec![(act, cmd.context.clone())])
213 },
214 RoomAction::SetDirect(is_direct) => {
215 let room = store
216 .application
217 .get_joined_room(id)
218 .ok_or(UIError::Application(IambError::NotJoined))?;
219
220 room.set_is_direct(is_direct).await.map_err(IambError::from)?;
221
222 Ok(vec![])
223 },
224 RoomAction::SetUnread(is_unread) => {
225 let room = store
226 .application
227 .get_joined_room(id)
228 .ok_or(UIError::Application(IambError::NotJoined))?;
229
230 room.set_unread_flag(is_unread).await.map_err(IambError::from)?;
231
232 if !is_unread {
233 let user_id = store.application.settings.profile.user_id.clone();
234 let info = store.application.get_room_info(id.to_owned());
235 let messages = info.get_thread(None).expect("room main timeline doesn't exist");
236 if let Some((key, _)) = messages.last_key_value() &&
237 let Some(event_id) = key.id.as_origin()
238 {
239 info.set_receipt(
240 matrix_sdk::ruma::events::receipt::ReceiptThread::Main,
241 user_id,
242 event_id.to_owned(),
243 );
244 }
245 }
246
247 Ok(vec![])
248 },
249 RoomAction::Set(field, value) => {
250 let room = store
251 .application
252 .get_joined_room(id)
253 .ok_or(UIError::Application(IambError::NotJoined))?;
254
255 match field {
256 RoomField::History => {
257 let visibility = hist_visibility_mode(value)?;
258 let ev = RoomHistoryVisibilityEventContent::new(visibility);
259 let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
260 },
261 RoomField::Name => {
262 let ev = RoomNameEventContent::new(value);
263 let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
264 },
265 RoomField::Tag(tag) => {
266 let mut info = TagInfo::new();
267 info.order = Some(1.0);
268
269 let _ = room.set_tag(tag, info).await.map_err(IambError::from)?;
270 },
271 RoomField::Topic => {
272 let ev = RoomTopicEventContent::new(value);
273 let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
274 },
275 RoomField::NotificationMode => {
276 let mode = notification_mode(value)?;
277 let client = &store.application.worker.client;
278 let notifications = client.notification_settings().await;
279
280 notifications
281 .set_room_notification_mode(id, mode)
282 .await
283 .map_err(IambError::from)?;
284 },
285 RoomField::CanonicalAlias => {
286 let client = &mut store.application.worker.client;
287
288 let Ok(orai) = OwnedRoomAliasId::try_from(value.as_str()) else {
289 let err = IambError::InvalidRoomAlias(value);
290
291 return Err(err.into());
292 };
293
294 let mut alt_aliases = room.alt_aliases().into_iter().collect::<HashSet<_>>();
295 let canonical_old = room.canonical_alias();
296
297 // If the room's alias is already that, ignore it
298 if canonical_old.as_ref() == Some(&orai) {
299 let msg = format!("The canonical room alias is already {orai}");
300
301 return Ok(vec![(Action::ShowInfoMessage(msg.into()), ctx)]);
302 }
303
304 // Try creating the room alias on the server.
305 if let Err(e) = client.create_room_alias(&orai, room.room_id()).await {
306 if let Some(ClientApiErrorKind::Unknown) = e.client_api_error_kind() {
307 // Ignore when it already exists.
308 } else {
309 return Err(IambError::from(e).into());
310 }
311 }
312
313 // Demote the previous one to an alt alias.
314 alt_aliases.extend(canonical_old);
315
316 // At this point the room alias definitely exists, and we can update the
317 // state event.
318 let mut ev = RoomCanonicalAliasEventContent::new();
319 ev.alias = Some(orai);
320 ev.alt_aliases = alt_aliases.into_iter().collect();
321 let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
322 },
323 RoomField::Alias(alias) => {
324 let client = &mut store.application.worker.client;
325
326 let Ok(orai) = OwnedRoomAliasId::try_from(alias.as_str()) else {
327 let err = IambError::InvalidRoomAlias(alias);
328
329 return Err(err.into());
330 };
331
332 let mut alt_aliases = room.alt_aliases().into_iter().collect::<HashSet<_>>();
333 let canonical = room.canonical_alias();
334
335 if alt_aliases.contains(&orai) || canonical.as_ref() == Some(&orai) {
336 let msg = format!("The alias {orai} already maps to this room");
337
338 return Ok(vec![(Action::ShowInfoMessage(msg.into()), ctx)]);
339 } else {
340 alt_aliases.insert(orai.clone());
341 }
342
343 // If the room alias does not exist on the server, create it
344 if let Err(e) = client.create_room_alias(&orai, room.room_id()).await {
345 if let Some(ClientApiErrorKind::Unknown) = e.client_api_error_kind() {
346 // Ignore when it already exists.
347 } else {
348 return Err(IambError::from(e).into());
349 }
350 }
351
352 // And add it to the aliases in the state event.
353 let mut ev = RoomCanonicalAliasEventContent::new();
354 ev.alias = canonical;
355 ev.alt_aliases = alt_aliases.into_iter().collect();
356 let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
357 },
358 RoomField::Aliases => {
359 // This never happens, aliases is only used for showing
360 },
361 RoomField::Id => {
362 // This never happens, id is only used for showing
363 },
364 }
365
366 Ok(vec![])
367 },
368 RoomAction::Unset(field) => {
369 let room = store
370 .application
371 .get_joined_room(id)
372 .ok_or(UIError::Application(IambError::NotJoined))?;
373
374 match field {
375 RoomField::History => {
376 let visibility = HistoryVisibility::Joined;
377 let ev = RoomHistoryVisibilityEventContent::new(visibility);
378 let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
379 },
380 RoomField::Name => {
381 let ev = RoomNameEventContent::new("".into());
382 let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
383 },
384 RoomField::Tag(tag) => {
385 let _ = room.remove_tag(tag).await.map_err(IambError::from)?;
386 },
387 RoomField::Topic => {
388 let ev = RoomTopicEventContent::new("".into());
389 let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
390 },
391 RoomField::NotificationMode => {
392 let client = &store.application.worker.client;
393 let notifications = client.notification_settings().await;
394
395 notifications
396 .delete_user_defined_room_rules(id)
397 .await
398 .map_err(IambError::from)?;
399 },
400 RoomField::CanonicalAlias => {
401 let Some(alias_to_destroy) = room.canonical_alias() else {
402 let msg = "This room has no canonical alias to unset";
403
404 return Ok(vec![(Action::ShowInfoMessage(msg.into()), ctx)]);
405 };
406
407 // Remove the canonical alias from the state event.
408 let mut ev = RoomCanonicalAliasEventContent::new();
409 ev.alias = None;
410 ev.alt_aliases = room.alt_aliases();
411 let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
412
413 // And then unmap it on the server.
414 store
415 .application
416 .worker
417 .client
418 .remove_room_alias(&alias_to_destroy)
419 .await
420 .map_err(IambError::from)?;
421 },
422 RoomField::Alias(alias) => {
423 let Ok(orai) = OwnedRoomAliasId::try_from(alias.as_str()) else {
424 let err = IambError::InvalidRoomAlias(alias);
425
426 return Err(err.into());
427 };
428
429 let alt_aliases = room.alt_aliases();
430 let canonical = room.canonical_alias();
431
432 if !alt_aliases.contains(&orai) && canonical.as_ref() != Some(&orai) {
433 let msg = format!("The alias {orai:?} isn't mapped to this room");
434
435 return Ok(vec![(Action::ShowInfoMessage(msg.into()), ctx)]);
436 }
437
438 // Remove the alias from the state event if it's in it.
439 let mut ev = RoomCanonicalAliasEventContent::new();
440 ev.alias = canonical.filter(|canon| canon != &orai);
441 ev.alt_aliases = alt_aliases;
442 ev.alt_aliases.retain(|in_orai| in_orai != &orai);
443 let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
444
445 // And then unmap it on the server.
446 store
447 .application
448 .worker
449 .client
450 .remove_room_alias(&orai)
451 .await
452 .map_err(IambError::from)?;
453 },
454 RoomField::Aliases => {
455 // This will not happen, you cannot unset all aliases
456 },
457 RoomField::Id => {
458 // This never happens, id is only used for showing
459 },
460 }
461
462 Ok(vec![])
463 },
464 RoomAction::Show(field) => {
465 let room = store
466 .application
467 .get_joined_room(id)
468 .ok_or(UIError::Application(IambError::NotJoined))?;
469
470 let msg = match field {
471 RoomField::History => {
472 let visibility = room.history_visibility();
473 let visibility = visibility.as_ref().map(|v| v.as_str());
474 format!("Room history visibility: {}", visibility.unwrap_or("<unknown>"))
475 },
476 RoomField::Id => {
477 let id = room.room_id();
478 format!("Room identifier: {id}")
479 },
480 RoomField::Name => {
481 match room.name() {
482 None => "Room has no name".into(),
483 Some(name) => format!("Room name: {name:?}"),
484 }
485 },
486 RoomField::Topic => {
487 match room.topic() {
488 None => "Room has no topic".into(),
489 Some(topic) => format!("Room topic: {topic:?}"),
490 }
491 },
492 RoomField::NotificationMode => {
493 let client = &store.application.worker.client;
494 let notifications = client.notification_settings().await;
495 let mode = notifications.get_user_defined_room_notification_mode(id).await;
496
497 let level = match mode {
498 Some(RoomNotificationMode::Mute) => "mute",
499 Some(RoomNotificationMode::MentionsAndKeywordsOnly) => "keywords",
500 Some(RoomNotificationMode::AllMessages) => "all",
501 None => "default",
502 };
503
504 format!("Room notification level: {level:?}")
505 },
506 RoomField::Aliases => {
507 let aliases = room
508 .alt_aliases()
509 .iter()
510 .map(OwnedRoomAliasId::to_string)
511 .collect::<Vec<String>>();
512
513 if aliases.is_empty() {
514 "No alternative aliases in room".into()
515 } else {
516 format!("Alternative aliases: {}.", aliases.join(", "))
517 }
518 },
519 RoomField::CanonicalAlias => {
520 match room.canonical_alias() {
521 None => "No canonical alias for room".into(),
522 Some(can) => format!("Canonical alias: {can}"),
523 }
524 },
525 RoomField::Tag(_) => "Cannot currently show value for a tag".into(),
526 RoomField::Alias(_) => {
527 "Cannot show a single alias; use `:room aliases show` instead.".into()
528 },
529 };
530
531 let msg = InfoMessage::Pager(msg);
532 let act = Action::ShowInfoMessage(msg);
533
534 Ok(vec![(act, ctx)])
535 },
536 }
537}
538
539/// State for a Matrix room or space.
540///
541/// Since spaces function as special rooms within Matrix, we wrap their window state together, so
542/// that operations like sending and accepting invites, opening the members window, etc., all work
543/// similarly.
544pub enum RoomState {
545 Chat(Box<ChatState>),
546 Space(Box<SpaceState>),
547}
548
549impl From<ChatState> for RoomState {
550 fn from(chat: ChatState) -> Self {
551 RoomState::Chat(Box::new(chat))
552 }
553}
554
555impl From<SpaceState> for RoomState {
556 fn from(space: SpaceState) -> Self {
557 RoomState::Space(Box::new(space))
558 }
559}
560
561impl RoomState {
562 pub fn new(
563 room: MatrixRoom,
564 thread: Option<OwnedEventId>,
565 name: RoomDisplayName,
566 tags: Option<Tags>,
567 store: &mut ProgramStore,
568 ) -> Self {
569 let room_id = room.room_id().to_owned();
570 let info = store.application.get_room_info(room_id);
571 info.name = name.to_string().into();
572 info.tags = tags;
573
574 if room.is_space() {
575 SpaceState::new(room).into()
576 } else {
577 ChatState::new(room, thread, store).into()
578 }
579 }
580
581 pub fn thread(&self) -> Option<&OwnedEventId> {
582 match self {
583 RoomState::Chat(chat) => chat.thread(),
584 RoomState::Space(_) => None,
585 }
586 }
587
588 pub fn refresh_room(&mut self, store: &mut ProgramStore) {
589 match self {
590 RoomState::Chat(chat) => chat.refresh_room(store),
591 RoomState::Space(space) => space.refresh_room(store),
592 }
593 }
594
595 fn draw_invite(
596 &self,
597 invited: MatrixRoom,
598 area: Rect,
599 buf: &mut Buffer,
600 store: &mut ProgramStore,
601 ) {
602 let inviter = store.application.worker.get_inviter(invited.clone());
603
604 let name = match invited.canonical_alias() {
605 Some(alias) => alias.to_string(),
606 None => format!("{:?}", store.application.get_room_title(self.id())),
607 };
608
609 let mut invited = vec![Span::from(format!("You have been invited to join {name}"))];
610
611 if let Ok(Some(inviter)) = &inviter {
612 let info = store.application.rooms.get_or_default(self.id().to_owned());
613 invited.push(Span::from(" by "));
614 invited.push(store.application.settings.get_user_span(inviter.user_id(), info));
615 }
616
617 let l1 = Line::from(invited);
618 let l2 = Line::from(
619 "You can run `:invite accept` or `:invite reject` to accept or reject this invitation.",
620 );
621 let text = Text::from(vec![l1, l2]);
622
623 Paragraph::new(text).alignment(Alignment::Center).render(area, buf);
624
625 return;
626 }
627
628 pub async fn message_command(
629 &mut self,
630 act: MessageAction,
631 ctx: ProgramContext,
632 store: &mut ProgramStore,
633 ) -> IambResult<EditInfo> {
634 match self {
635 RoomState::Chat(chat) => chat.message_command(act, ctx, store).await,
636 RoomState::Space(_) => Err(IambError::NoSelectedMessage.into()),
637 }
638 }
639
640 pub async fn space_command(
641 &mut self,
642 act: SpaceAction,
643 ctx: ProgramContext,
644 store: &mut ProgramStore,
645 ) -> IambResult<EditInfo> {
646 match self {
647 RoomState::Space(space) => space.space_command(act, ctx, store).await,
648 RoomState::Chat(_) => Err(IambError::NoSelectedSpace.into()),
649 }
650 }
651
652 pub async fn send_command(
653 &mut self,
654 act: SendAction,
655 ctx: ProgramContext,
656 store: &mut ProgramStore,
657 ) -> IambResult<EditInfo> {
658 match self {
659 RoomState::Chat(chat) => chat.send_command(act, ctx, store).await,
660 RoomState::Space(_) => Err(IambError::NoSelectedRoom.into()),
661 }
662 }
663
664 pub fn get_title(&self, store: &mut ProgramStore) -> Line<'_> {
665 let room = store.application.worker.client.get_room(self.id());
666
667 let title = store.application.get_room_title(self.id());
668 let style = Style::default().add_modifier(StyleModifier::BOLD);
669 let mut spans = vec![];
670
671 if let RoomState::Chat(chat) = self &&
672 chat.thread().is_some()
673 {
674 spans.push("Thread in ".into());
675 }
676
677 spans.push(Span::styled(title, style));
678
679 if let Some(room) = room {
680 let encryption_settings = &store.application.settings.tunables.encryption;
681 let encryption_indicator = encryption_settings
682 .get_indicator(EncryptionIndicatorLocation::TITLE, room.encryption_state());
683 spans.extend(encryption_indicator);
684 }
685
686 match self.room().topic() {
687 Some(desc) if !desc.is_empty() => {
688 spans.push(" (".into());
689 spans.push(desc.into());
690 spans.push(")".into());
691 },
692 _ => {
693 spans.push(" ".into());
694 },
695 }
696
697 Line::from(spans)
698 }
699
700 pub fn focus_toggle(&mut self) {
701 match self {
702 RoomState::Chat(chat) => chat.focus_toggle(),
703 RoomState::Space(_) => return,
704 }
705 }
706
707 pub fn room(&self) -> &MatrixRoom {
708 match self {
709 RoomState::Chat(chat) => chat.room(),
710 RoomState::Space(space) => space.room(),
711 }
712 }
713
714 pub fn id(&self) -> &RoomId {
715 match self {
716 RoomState::Chat(chat) => chat.id(),
717 RoomState::Space(space) => space.id(),
718 }
719 }
720}
721
722impl Editable<ProgramContext, ProgramStore, IambInfo> for RoomState {
723 fn editor_command(
724 &mut self,
725 act: &EditorAction,
726 ctx: &ProgramContext,
727 store: &mut ProgramStore,
728 ) -> EditResult<EditInfo, IambInfo> {
729 delegate!(self, w => w.editor_command(act, ctx, store))
730 }
731}
732
733impl Jumpable<ProgramContext, IambInfo> for RoomState {
734 fn jump(
735 &mut self,
736 list: PositionList,
737 dir: MoveDir1D,
738 count: usize,
739 ctx: &ProgramContext,
740 ) -> IambResult<usize> {
741 delegate!(self, w => w.jump(list, dir, count, ctx))
742 }
743}
744
745impl Scrollable<ProgramContext, ProgramStore, IambInfo> for RoomState {
746 fn scroll(
747 &mut self,
748 style: &ScrollStyle,
749 ctx: &ProgramContext,
750 store: &mut ProgramStore,
751 ) -> EditResult<EditInfo, IambInfo> {
752 delegate!(self, w => w.scroll(style, ctx, store))
753 }
754}
755
756impl Promptable<ProgramContext, ProgramStore, IambInfo> for RoomState {
757 fn prompt(
758 &mut self,
759 act: &PromptAction,
760 ctx: &ProgramContext,
761 store: &mut ProgramStore,
762 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
763 delegate!(self, w => w.prompt(act, ctx, store))
764 }
765}
766
767impl TerminalCursor for RoomState {
768 fn get_term_cursor(&self) -> Option<TermOffset> {
769 delegate!(self, w => w.get_term_cursor())
770 }
771}
772
773impl WindowOps<IambInfo> for RoomState {
774 fn draw(&mut self, area: Rect, buf: &mut Buffer, focused: bool, store: &mut ProgramStore) {
775 if self.room().state() == MatrixRoomState::Invited {
776 self.refresh_room(store);
777 }
778
779 if self.room().state() == MatrixRoomState::Invited {
780 self.draw_invite(self.room().clone(), area, buf, store);
781 }
782
783 match self {
784 RoomState::Chat(chat) => chat.draw(area, buf, focused, store),
785 RoomState::Space(space) => {
786 Space::new(store).focus(focused).render(area, buf, space);
787 },
788 }
789 }
790
791 fn dup(&self, store: &mut ProgramStore) -> Self {
792 match self {
793 RoomState::Chat(chat) => RoomState::Chat(Box::new(chat.dup(store))),
794 RoomState::Space(space) => RoomState::Space(Box::new(space.dup(store))),
795 }
796 }
797
798 fn close(&mut self, flags: CloseFlags, store: &mut ProgramStore) -> bool {
799 match self {
800 RoomState::Chat(chat) => chat.close(flags, store),
801 RoomState::Space(space) => space.close(flags, store),
802 }
803 }
804
805 fn write(
806 &mut self,
807 path: Option<&str>,
808 flags: WriteFlags,
809 store: &mut ProgramStore,
810 ) -> IambResult<EditInfo> {
811 match self {
812 RoomState::Chat(chat) => chat.write(path, flags, store),
813 RoomState::Space(space) => space.write(path, flags, store),
814 }
815 }
816
817 fn get_completions(&self) -> Option<CompletionList> {
818 match self {
819 RoomState::Chat(chat) => chat.get_completions(),
820 RoomState::Space(space) => space.get_completions(),
821 }
822 }
823
824 fn get_cursor_word(&self, style: &WordStyle) -> Option<String> {
825 match self {
826 RoomState::Chat(chat) => chat.get_cursor_word(style),
827 RoomState::Space(space) => space.get_cursor_word(style),
828 }
829 }
830
831 fn get_selected_word(&self) -> Option<String> {
832 match self {
833 RoomState::Chat(chat) => chat.get_selected_word(),
834 RoomState::Space(space) => space.get_selected_word(),
835 }
836 }
837}
838
839#[cfg(test)]
840mod tests {
841 use super::*;
842
843 #[test]
844 fn test_parse_room_notification_level() {
845 let tests = vec![
846 ("mute", RoomNotificationMode::Mute),
847 ("mentions", RoomNotificationMode::MentionsAndKeywordsOnly),
848 ("keywords", RoomNotificationMode::MentionsAndKeywordsOnly),
849 ("all", RoomNotificationMode::AllMessages),
850 ];
851
852 for (input, expect) in tests {
853 let res = notification_mode(input).unwrap();
854 assert_eq!(expect, res);
855 }
856
857 assert!(notification_mode("invalid").is_err());
858 assert!(notification_mode("not a level").is_err());
859 assert!(notification_mode("@user:example.com").is_err());
860 }
861}