src/windows/room/mod.rs

456 lines · 13981 bytes

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