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