src/windows/room/mod.rs

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