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