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