src/windows/room/mod.rs

846 lines · 31455 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, None).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, None).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, None)
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, None)
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                        format!("Room history visibility: {visibility}")
595                    },
596                    RoomField::Id => {
597                        let id = room.room_id();
598                        format!("Room identifier: {id}")
599                    },
600                    RoomField::Name => {
601                        match room.name() {
602                            None => "Room has no name".into(),
603                            Some(name) => format!("Room name: {name:?}"),
604                        }
605                    },
606                    RoomField::Topic => {
607                        match room.topic() {
608                            None => "Room has no topic".into(),
609                            Some(topic) => format!("Room topic: {topic:?}"),
610                        }
611                    },
612                    RoomField::NotificationMode => {
613                        let client = &store.application.worker.client;
614                        let notifications = client.notification_settings().await;
615                        let mode =
616                            notifications.get_user_defined_room_notification_mode(self.id()).await;
617
618                        let level = match mode {
619                            Some(RoomNotificationMode::Mute) => "mute",
620                            Some(RoomNotificationMode::MentionsAndKeywordsOnly) => "keywords",
621                            Some(RoomNotificationMode::AllMessages) => "all",
622                            None => "default",
623                        };
624
625                        format!("Room notification level: {level:?}")
626                    },
627                    RoomField::Aliases => {
628                        let aliases = room
629                            .alt_aliases()
630                            .iter()
631                            .map(OwnedRoomAliasId::to_string)
632                            .collect::<Vec<String>>();
633
634                        if aliases.is_empty() {
635                            "No alternative aliases in room".into()
636                        } else {
637                            format!("Alternative aliases: {}.", aliases.join(", "))
638                        }
639                    },
640                    RoomField::CanonicalAlias => {
641                        match room.canonical_alias() {
642                            None => "No canonical alias for room".into(),
643                            Some(can) => format!("Canonical alias: {can}"),
644                        }
645                    },
646                    RoomField::Tag(_) => "Cannot currently show value for a tag".into(),
647                    RoomField::Alias(_) => {
648                        "Cannot show a single alias; use `:room aliases show` instead.".into()
649                    },
650                };
651
652                let msg = InfoMessage::Pager(msg);
653                let act = Action::ShowInfoMessage(msg);
654
655                Ok(vec![(act, ctx)])
656            },
657        }
658    }
659
660    pub fn get_title(&self, store: &mut ProgramStore) -> Line {
661        let title = store.application.get_room_title(self.id());
662        let style = Style::default().add_modifier(StyleModifier::BOLD);
663        let mut spans = vec![];
664
665        if let RoomState::Chat(chat) = self {
666            if chat.thread().is_some() {
667                spans.push("Thread in ".into());
668            }
669        }
670
671        spans.push(Span::styled(title, style));
672
673        match self.room().topic() {
674            Some(desc) if !desc.is_empty() => {
675                spans.push(" (".into());
676                spans.push(desc.into());
677                spans.push(")".into());
678            },
679            _ => {},
680        }
681
682        Line::from(spans)
683    }
684
685    pub fn focus_toggle(&mut self) {
686        match self {
687            RoomState::Chat(chat) => chat.focus_toggle(),
688            RoomState::Space(_) => return,
689        }
690    }
691
692    pub fn room(&self) -> &MatrixRoom {
693        match self {
694            RoomState::Chat(chat) => chat.room(),
695            RoomState::Space(space) => space.room(),
696        }
697    }
698
699    pub fn id(&self) -> &RoomId {
700        match self {
701            RoomState::Chat(chat) => chat.id(),
702            RoomState::Space(space) => space.id(),
703        }
704    }
705}
706
707impl Editable<ProgramContext, ProgramStore, IambInfo> for RoomState {
708    fn editor_command(
709        &mut self,
710        act: &EditorAction,
711        ctx: &ProgramContext,
712        store: &mut ProgramStore,
713    ) -> EditResult<EditInfo, IambInfo> {
714        delegate!(self, w => w.editor_command(act, ctx, store))
715    }
716}
717
718impl Jumpable<ProgramContext, IambInfo> for RoomState {
719    fn jump(
720        &mut self,
721        list: PositionList,
722        dir: MoveDir1D,
723        count: usize,
724        ctx: &ProgramContext,
725    ) -> IambResult<usize> {
726        delegate!(self, w => w.jump(list, dir, count, ctx))
727    }
728}
729
730impl Scrollable<ProgramContext, ProgramStore, IambInfo> for RoomState {
731    fn scroll(
732        &mut self,
733        style: &ScrollStyle,
734        ctx: &ProgramContext,
735        store: &mut ProgramStore,
736    ) -> EditResult<EditInfo, IambInfo> {
737        delegate!(self, w => w.scroll(style, ctx, store))
738    }
739}
740
741impl Promptable<ProgramContext, ProgramStore, IambInfo> for RoomState {
742    fn prompt(
743        &mut self,
744        act: &PromptAction,
745        ctx: &ProgramContext,
746        store: &mut ProgramStore,
747    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
748        delegate!(self, w => w.prompt(act, ctx, store))
749    }
750}
751
752impl TerminalCursor for RoomState {
753    fn get_term_cursor(&self) -> Option<TermOffset> {
754        delegate!(self, w => w.get_term_cursor())
755    }
756}
757
758impl WindowOps<IambInfo> for RoomState {
759    fn draw(&mut self, area: Rect, buf: &mut Buffer, focused: bool, store: &mut ProgramStore) {
760        if self.room().state() == MatrixRoomState::Invited {
761            self.refresh_room(store);
762        }
763
764        if self.room().state() == MatrixRoomState::Invited {
765            self.draw_invite(self.room().clone(), area, buf, store);
766        }
767
768        match self {
769            RoomState::Chat(chat) => chat.draw(area, buf, focused, store),
770            RoomState::Space(space) => {
771                Space::new(store).focus(focused).render(area, buf, space);
772            },
773        }
774    }
775
776    fn dup(&self, store: &mut ProgramStore) -> Self {
777        match self {
778            RoomState::Chat(chat) => RoomState::Chat(chat.dup(store)),
779            RoomState::Space(space) => RoomState::Space(space.dup(store)),
780        }
781    }
782
783    fn close(&mut self, flags: CloseFlags, store: &mut ProgramStore) -> bool {
784        match self {
785            RoomState::Chat(chat) => chat.close(flags, store),
786            RoomState::Space(space) => space.close(flags, store),
787        }
788    }
789
790    fn write(
791        &mut self,
792        path: Option<&str>,
793        flags: WriteFlags,
794        store: &mut ProgramStore,
795    ) -> IambResult<EditInfo> {
796        match self {
797            RoomState::Chat(chat) => chat.write(path, flags, store),
798            RoomState::Space(space) => space.write(path, flags, store),
799        }
800    }
801
802    fn get_completions(&self) -> Option<CompletionList> {
803        match self {
804            RoomState::Chat(chat) => chat.get_completions(),
805            RoomState::Space(space) => space.get_completions(),
806        }
807    }
808
809    fn get_cursor_word(&self, style: &WordStyle) -> Option<String> {
810        match self {
811            RoomState::Chat(chat) => chat.get_cursor_word(style),
812            RoomState::Space(space) => space.get_cursor_word(style),
813        }
814    }
815
816    fn get_selected_word(&self) -> Option<String> {
817        match self {
818            RoomState::Chat(chat) => chat.get_selected_word(),
819            RoomState::Space(space) => space.get_selected_word(),
820        }
821    }
822}
823
824#[cfg(test)]
825mod tests {
826    use super::*;
827
828    #[test]
829    fn test_parse_room_notification_level() {
830        let tests = vec![
831            ("mute", RoomNotificationMode::Mute),
832            ("mentions", RoomNotificationMode::MentionsAndKeywordsOnly),
833            ("keywords", RoomNotificationMode::MentionsAndKeywordsOnly),
834            ("all", RoomNotificationMode::AllMessages),
835        ];
836
837        for (input, expect) in tests {
838            let res = notification_mode(input).unwrap();
839            assert_eq!(expect, res);
840        }
841
842        assert!(notification_mode("invalid").is_err());
843        assert!(notification_mode("not a level").is_err());
844        assert!(notification_mode("@user:example.com").is_err());
845    }
846}