src/windows/room/mod.rs

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