src/windows/room/mod.rs

451 lines · 14097 bytes

  1//! # Windows for Matrix rooms and spaces
  2use matrix_sdk::{
  3    room::{Invited, Room as MatrixRoom},
  4    ruma::{
  5        events::{
  6            room::{name::RoomNameEventContent, topic::RoomTopicEventContent},
  7            tag::{TagInfo, Tags},
  8        },
  9        RoomId,
 10    },
 11    DisplayName,
 12};
 13
 14use ratatui::{
 15    buffer::Buffer,
 16    layout::{Alignment, Rect},
 17    style::{Modifier as StyleModifier, Style},
 18    text::{Line, Span, Text},
 19    widgets::{Paragraph, StatefulWidget, Widget},
 20};
 21
 22use modalkit::prelude::*;
 23use modalkit::{
 24    editing::action::{
 25        Action,
 26        EditInfo,
 27        EditResult,
 28        Editable,
 29        EditorAction,
 30        Jumpable,
 31        PromptAction,
 32        Promptable,
 33        Scrollable,
 34        UIError,
 35    },
 36    editing::completion::CompletionList,
 37    keybindings::dialog::PromptYesNo,
 38};
 39use modalkit_ratatui::{TermOffset, TerminalCursor, WindowOps};
 40
 41use crate::base::{
 42    IambAction,
 43    IambError,
 44    IambId,
 45    IambInfo,
 46    IambResult,
 47    MessageAction,
 48    ProgramAction,
 49    ProgramContext,
 50    ProgramStore,
 51    RoomAction,
 52    RoomField,
 53    SendAction,
 54};
 55
 56use self::chat::ChatState;
 57use self::space::{Space, SpaceState};
 58
 59mod chat;
 60mod scrollback;
 61mod space;
 62
 63macro_rules! delegate {
 64    ($s: expr, $id: ident => $e: expr) => {
 65        match $s {
 66            RoomState::Chat($id) => $e,
 67            RoomState::Space($id) => $e,
 68        }
 69    };
 70}
 71
 72/// State for a Matrix room or space.
 73///
 74/// Since spaces function as special rooms within Matrix, we wrap their window state together, so
 75/// that operations like sending and accepting invites, opening the members window, etc., all work
 76/// similarly.
 77pub enum RoomState {
 78    Chat(ChatState),
 79    Space(SpaceState),
 80}
 81
 82impl From<ChatState> for RoomState {
 83    fn from(chat: ChatState) -> Self {
 84        RoomState::Chat(chat)
 85    }
 86}
 87
 88impl From<SpaceState> for RoomState {
 89    fn from(space: SpaceState) -> Self {
 90        RoomState::Space(space)
 91    }
 92}
 93
 94impl RoomState {
 95    pub fn new(
 96        room: MatrixRoom,
 97        name: DisplayName,
 98        tags: Option<Tags>,
 99        store: &mut ProgramStore,
100    ) -> Self {
101        let room_id = room.room_id().to_owned();
102        let info = store.application.get_room_info(room_id);
103        info.name = name.to_string().into();
104        info.tags = tags;
105
106        if room.is_space() {
107            SpaceState::new(room).into()
108        } else {
109            ChatState::new(room, store).into()
110        }
111    }
112
113    pub fn refresh_room(&mut self, store: &mut ProgramStore) {
114        match self {
115            RoomState::Chat(chat) => chat.refresh_room(store),
116            RoomState::Space(space) => space.refresh_room(store),
117        }
118    }
119
120    fn draw_invite(
121        &self,
122        invited: Invited,
123        area: Rect,
124        buf: &mut Buffer,
125        store: &mut ProgramStore,
126    ) {
127        let inviter = store.application.worker.get_inviter(invited.clone());
128
129        let name = match invited.canonical_alias() {
130            Some(alias) => alias.to_string(),
131            None => format!("{:?}", store.application.get_room_title(self.id())),
132        };
133
134        let mut invited = vec![Span::from(format!("You have been invited to join {name}"))];
135
136        if let Ok(Some(inviter)) = &inviter {
137            let info = store.application.rooms.get_or_default(self.id().to_owned());
138            invited.push(Span::from(" by "));
139            invited.push(store.application.settings.get_user_span(inviter.user_id(), info));
140        }
141
142        let l1 = Line::from(invited);
143        let l2 = Line::from(
144            "You can run `:invite accept` or `:invite reject` to accept or reject this invitation.",
145        );
146        let text = Text { lines: vec![l1, l2] };
147
148        Paragraph::new(text).alignment(Alignment::Center).render(area, buf);
149
150        return;
151    }
152
153    pub async fn message_command(
154        &mut self,
155        act: MessageAction,
156        ctx: ProgramContext,
157        store: &mut ProgramStore,
158    ) -> IambResult<EditInfo> {
159        match self {
160            RoomState::Chat(chat) => chat.message_command(act, ctx, store).await,
161            RoomState::Space(_) => Err(IambError::NoSelectedMessage.into()),
162        }
163    }
164
165    pub async fn send_command(
166        &mut self,
167        act: SendAction,
168        ctx: ProgramContext,
169        store: &mut ProgramStore,
170    ) -> IambResult<EditInfo> {
171        match self {
172            RoomState::Chat(chat) => chat.send_command(act, ctx, store).await,
173            RoomState::Space(_) => Err(IambError::NoSelectedRoom.into()),
174        }
175    }
176
177    pub async fn room_command(
178        &mut self,
179        act: RoomAction,
180        _: ProgramContext,
181        store: &mut ProgramStore,
182    ) -> IambResult<Vec<(Action<IambInfo>, ProgramContext)>> {
183        match act {
184            RoomAction::InviteAccept => {
185                if let Some(room) = store.application.worker.client.get_invited_room(self.id()) {
186                    let details = room.invite_details().await.map_err(IambError::from)?;
187                    let details = details.invitee.event().original_content();
188                    let is_direct = details.and_then(|ev| ev.is_direct).unwrap_or_default();
189
190                    room.accept_invitation().await.map_err(IambError::from)?;
191
192                    if is_direct {
193                        room.set_is_direct(true).await.map_err(IambError::from)?;
194                    }
195
196                    Ok(vec![])
197                } else {
198                    Err(IambError::NotInvited.into())
199                }
200            },
201            RoomAction::InviteReject => {
202                if let Some(room) = store.application.worker.client.get_invited_room(self.id()) {
203                    room.reject_invitation().await.map_err(IambError::from)?;
204
205                    Ok(vec![])
206                } else {
207                    Err(IambError::NotInvited.into())
208                }
209            },
210            RoomAction::InviteSend(user) => {
211                if let Some(room) = store.application.worker.client.get_joined_room(self.id()) {
212                    room.invite_user_by_id(user.as_ref()).await.map_err(IambError::from)?;
213
214                    Ok(vec![])
215                } else {
216                    Err(IambError::NotJoined.into())
217                }
218            },
219            RoomAction::Leave(skip_confirm) => {
220                if let Some(room) = store.application.worker.client.get_joined_room(self.id()) {
221                    if skip_confirm {
222                        room.leave().await.map_err(IambError::from)?;
223
224                        Ok(vec![])
225                    } else {
226                        let msg = "Do you really want to leave this room?";
227                        let leave = IambAction::Room(RoomAction::Leave(true));
228                        let prompt = PromptYesNo::new(msg, vec![Action::from(leave)]);
229                        let prompt = Box::new(prompt);
230
231                        Err(UIError::NeedConfirm(prompt))
232                    }
233                } else {
234                    Err(IambError::NotJoined.into())
235                }
236            },
237            RoomAction::Members(mut cmd) => {
238                let width = Count::Exact(30);
239                let act =
240                    cmd.default_axis(Axis::Vertical).default_relation(MoveDir1D::Next).window(
241                        OpenTarget::Application(IambId::MemberList(self.id().to_owned())),
242                        width.into(),
243                    );
244
245                Ok(vec![(act, cmd.context.clone())])
246            },
247            RoomAction::Set(field, value) => {
248                let room = store
249                    .application
250                    .get_joined_room(self.id())
251                    .ok_or(UIError::Application(IambError::NotJoined))?;
252
253                match field {
254                    RoomField::Name => {
255                        let ev = RoomNameEventContent::new(value.into());
256                        let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
257                    },
258                    RoomField::Tag(tag) => {
259                        let mut info = TagInfo::new();
260                        info.order = Some(1.0);
261
262                        let _ = room.set_tag(tag, info).await.map_err(IambError::from)?;
263                    },
264                    RoomField::Topic => {
265                        let ev = RoomTopicEventContent::new(value);
266                        let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
267                    },
268                }
269
270                Ok(vec![])
271            },
272            RoomAction::Unset(field) => {
273                let room = store
274                    .application
275                    .get_joined_room(self.id())
276                    .ok_or(UIError::Application(IambError::NotJoined))?;
277
278                match field {
279                    RoomField::Name => {
280                        let ev = RoomNameEventContent::new(None);
281                        let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
282                    },
283                    RoomField::Tag(tag) => {
284                        let _ = room.remove_tag(tag).await.map_err(IambError::from)?;
285                    },
286                    RoomField::Topic => {
287                        let ev = RoomTopicEventContent::new("".into());
288                        let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
289                    },
290                }
291
292                Ok(vec![])
293            },
294        }
295    }
296
297    pub fn get_title(&self, store: &mut ProgramStore) -> Line {
298        let title = store.application.get_room_title(self.id());
299        let style = Style::default().add_modifier(StyleModifier::BOLD);
300        let mut spans = vec![Span::styled(title, style)];
301
302        match self.room().topic() {
303            Some(desc) if !desc.is_empty() => {
304                spans.push(" (".into());
305                spans.push(desc.into());
306                spans.push(")".into());
307            },
308            _ => {},
309        }
310
311        Line::from(spans)
312    }
313
314    pub fn focus_toggle(&mut self) {
315        match self {
316            RoomState::Chat(chat) => chat.focus_toggle(),
317            RoomState::Space(_) => return,
318        }
319    }
320
321    pub fn room(&self) -> &MatrixRoom {
322        match self {
323            RoomState::Chat(chat) => chat.room(),
324            RoomState::Space(space) => space.room(),
325        }
326    }
327
328    pub fn id(&self) -> &RoomId {
329        match self {
330            RoomState::Chat(chat) => chat.id(),
331            RoomState::Space(space) => space.id(),
332        }
333    }
334}
335
336impl Editable<ProgramContext, ProgramStore, IambInfo> for RoomState {
337    fn editor_command(
338        &mut self,
339        act: &EditorAction,
340        ctx: &ProgramContext,
341        store: &mut ProgramStore,
342    ) -> EditResult<EditInfo, IambInfo> {
343        delegate!(self, w => w.editor_command(act, ctx, store))
344    }
345}
346
347impl Jumpable<ProgramContext, IambInfo> for RoomState {
348    fn jump(
349        &mut self,
350        list: PositionList,
351        dir: MoveDir1D,
352        count: usize,
353        ctx: &ProgramContext,
354    ) -> IambResult<usize> {
355        delegate!(self, w => w.jump(list, dir, count, ctx))
356    }
357}
358
359impl Scrollable<ProgramContext, ProgramStore, IambInfo> for RoomState {
360    fn scroll(
361        &mut self,
362        style: &ScrollStyle,
363        ctx: &ProgramContext,
364        store: &mut ProgramStore,
365    ) -> EditResult<EditInfo, IambInfo> {
366        delegate!(self, w => w.scroll(style, ctx, store))
367    }
368}
369
370impl Promptable<ProgramContext, ProgramStore, IambInfo> for RoomState {
371    fn prompt(
372        &mut self,
373        act: &PromptAction,
374        ctx: &ProgramContext,
375        store: &mut ProgramStore,
376    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
377        delegate!(self, w => w.prompt(act, ctx, store))
378    }
379}
380
381impl TerminalCursor for RoomState {
382    fn get_term_cursor(&self) -> Option<TermOffset> {
383        delegate!(self, w => w.get_term_cursor())
384    }
385}
386
387impl WindowOps<IambInfo> for RoomState {
388    fn draw(&mut self, area: Rect, buf: &mut Buffer, focused: bool, store: &mut ProgramStore) {
389        if let MatrixRoom::Invited(_) = self.room() {
390            self.refresh_room(store);
391        }
392
393        if let MatrixRoom::Invited(invited) = self.room() {
394            self.draw_invite(invited.clone(), area, buf, store);
395        }
396
397        match self {
398            RoomState::Chat(chat) => chat.draw(area, buf, focused, store),
399            RoomState::Space(space) => {
400                Space::new(store).focus(focused).render(area, buf, space);
401            },
402        }
403    }
404
405    fn dup(&self, store: &mut ProgramStore) -> Self {
406        match self {
407            RoomState::Chat(chat) => RoomState::Chat(chat.dup(store)),
408            RoomState::Space(space) => RoomState::Space(space.dup(store)),
409        }
410    }
411
412    fn close(&mut self, flags: CloseFlags, store: &mut ProgramStore) -> bool {
413        match self {
414            RoomState::Chat(chat) => chat.close(flags, store),
415            RoomState::Space(space) => space.close(flags, store),
416        }
417    }
418
419    fn write(
420        &mut self,
421        path: Option<&str>,
422        flags: WriteFlags,
423        store: &mut ProgramStore,
424    ) -> IambResult<EditInfo> {
425        match self {
426            RoomState::Chat(chat) => chat.write(path, flags, store),
427            RoomState::Space(space) => space.write(path, flags, store),
428        }
429    }
430
431    fn get_completions(&self) -> Option<CompletionList> {
432        match self {
433            RoomState::Chat(chat) => chat.get_completions(),
434            RoomState::Space(space) => space.get_completions(),
435        }
436    }
437
438    fn get_cursor_word(&self, style: &WordStyle) -> Option<String> {
439        match self {
440            RoomState::Chat(chat) => chat.get_cursor_word(style),
441            RoomState::Space(space) => space.get_cursor_word(style),
442        }
443    }
444
445    fn get_selected_word(&self) -> Option<String> {
446        match self {
447            RoomState::Chat(chat) => chat.get_selected_word(),
448            RoomState::Space(space) => space.get_selected_word(),
449        }
450    }
451}