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