src/windows/room/mod.rs

455 lines · 13890 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            invited.push(Span::from(" by "));
143            invited.push(store.application.settings.get_user_span(inviter.user_id()));
144        }
145
146        let l1 = Spans(invited);
147        let l2 = Spans::from(
148            "You can run `:invite accept` or `:invite reject` to accept or reject this invitation.",
149        );
150        let text = Text { lines: vec![l1, l2] };
151
152        Paragraph::new(text).alignment(Alignment::Center).render(area, buf);
153
154        return;
155    }
156
157    pub async fn message_command(
158        &mut self,
159        act: MessageAction,
160        ctx: ProgramContext,
161        store: &mut ProgramStore,
162    ) -> IambResult<EditInfo> {
163        match self {
164            RoomState::Chat(chat) => chat.message_command(act, ctx, store).await,
165            RoomState::Space(_) => Err(IambError::NoSelectedMessage.into()),
166        }
167    }
168
169    pub async fn send_command(
170        &mut self,
171        act: SendAction,
172        ctx: ProgramContext,
173        store: &mut ProgramStore,
174    ) -> IambResult<EditInfo> {
175        match self {
176            RoomState::Chat(chat) => chat.send_command(act, ctx, store).await,
177            RoomState::Space(_) => Err(IambError::NoSelectedRoom.into()),
178        }
179    }
180
181    pub async fn room_command(
182        &mut self,
183        act: RoomAction,
184        _: ProgramContext,
185        store: &mut ProgramStore,
186    ) -> IambResult<Vec<(Action<IambInfo>, ProgramContext)>> {
187        match act {
188            RoomAction::InviteAccept => {
189                if let Some(room) = store.application.worker.client.get_invited_room(self.id()) {
190                    let details = room.invite_details().await.map_err(IambError::from)?;
191                    let details = details.invitee.event().original_content();
192                    let is_direct = details.and_then(|ev| ev.is_direct).unwrap_or_default();
193
194                    room.accept_invitation().await.map_err(IambError::from)?;
195
196                    if is_direct {
197                        room.set_is_direct(true).await.map_err(IambError::from)?;
198                    }
199
200                    Ok(vec![])
201                } else {
202                    Err(IambError::NotInvited.into())
203                }
204            },
205            RoomAction::InviteReject => {
206                if let Some(room) = store.application.worker.client.get_invited_room(self.id()) {
207                    room.reject_invitation().await.map_err(IambError::from)?;
208
209                    Ok(vec![])
210                } else {
211                    Err(IambError::NotInvited.into())
212                }
213            },
214            RoomAction::InviteSend(user) => {
215                if let Some(room) = store.application.worker.client.get_joined_room(self.id()) {
216                    room.invite_user_by_id(user.as_ref()).await.map_err(IambError::from)?;
217
218                    Ok(vec![])
219                } else {
220                    Err(IambError::NotJoined.into())
221                }
222            },
223            RoomAction::Leave(skip_confirm) => {
224                if let Some(room) = store.application.worker.client.get_joined_room(self.id()) {
225                    if skip_confirm {
226                        room.leave().await.map_err(IambError::from)?;
227
228                        Ok(vec![])
229                    } else {
230                        let msg = "Do you really want to leave this room?";
231                        let leave = IambAction::Room(RoomAction::Leave(true));
232                        let prompt = PromptYesNo::new(msg, vec![Action::from(leave)]);
233                        let prompt = Box::new(prompt);
234
235                        Err(UIError::NeedConfirm(prompt))
236                    }
237                } else {
238                    Err(IambError::NotJoined.into())
239                }
240            },
241            RoomAction::Members(mut cmd) => {
242                let width = Count::Exact(30);
243                let act =
244                    cmd.default_axis(Axis::Vertical).default_relation(MoveDir1D::Next).window(
245                        OpenTarget::Application(IambId::MemberList(self.id().to_owned())),
246                        width.into(),
247                    );
248
249                Ok(vec![(act, cmd.context.take())])
250            },
251            RoomAction::Set(field, value) => {
252                let room = store
253                    .application
254                    .get_joined_room(self.id())
255                    .ok_or(UIError::Application(IambError::NotJoined))?;
256
257                match field {
258                    RoomField::Name => {
259                        let ev = RoomNameEventContent::new(value.into());
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                }
273
274                Ok(vec![])
275            },
276            RoomAction::Unset(field) => {
277                let room = store
278                    .application
279                    .get_joined_room(self.id())
280                    .ok_or(UIError::Application(IambError::NotJoined))?;
281
282                match field {
283                    RoomField::Name => {
284                        let ev = RoomNameEventContent::new(None);
285                        let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
286                    },
287                    RoomField::Tag(tag) => {
288                        let _ = room.remove_tag(tag).await.map_err(IambError::from)?;
289                    },
290                    RoomField::Topic => {
291                        let ev = RoomTopicEventContent::new("".into());
292                        let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
293                    },
294                }
295
296                Ok(vec![])
297            },
298        }
299    }
300
301    pub fn get_title(&self, store: &mut ProgramStore) -> Spans {
302        let title = store.application.get_room_title(self.id());
303        let style = Style::default().add_modifier(StyleModifier::BOLD);
304        let mut spans = vec![Span::styled(title, style)];
305
306        match self.room().topic() {
307            Some(desc) if !desc.is_empty() => {
308                spans.push(" (".into());
309                spans.push(desc.into());
310                spans.push(")".into());
311            },
312            _ => {},
313        }
314
315        Spans(spans)
316    }
317
318    pub fn focus_toggle(&mut self) {
319        match self {
320            RoomState::Chat(chat) => chat.focus_toggle(),
321            RoomState::Space(_) => return,
322        }
323    }
324
325    pub fn room(&self) -> &MatrixRoom {
326        match self {
327            RoomState::Chat(chat) => chat.room(),
328            RoomState::Space(space) => space.room(),
329        }
330    }
331
332    pub fn id(&self) -> &RoomId {
333        match self {
334            RoomState::Chat(chat) => chat.id(),
335            RoomState::Space(space) => space.id(),
336        }
337    }
338}
339
340impl Editable<ProgramContext, ProgramStore, IambInfo> for RoomState {
341    fn editor_command(
342        &mut self,
343        act: &EditorAction,
344        ctx: &ProgramContext,
345        store: &mut ProgramStore,
346    ) -> EditResult<EditInfo, IambInfo> {
347        delegate!(self, w => w.editor_command(act, ctx, store))
348    }
349}
350
351impl Jumpable<ProgramContext, IambInfo> for RoomState {
352    fn jump(
353        &mut self,
354        list: PositionList,
355        dir: MoveDir1D,
356        count: usize,
357        ctx: &ProgramContext,
358    ) -> IambResult<usize> {
359        delegate!(self, w => w.jump(list, dir, count, ctx))
360    }
361}
362
363impl Scrollable<ProgramContext, ProgramStore, IambInfo> for RoomState {
364    fn scroll(
365        &mut self,
366        style: &ScrollStyle,
367        ctx: &ProgramContext,
368        store: &mut ProgramStore,
369    ) -> EditResult<EditInfo, IambInfo> {
370        delegate!(self, w => w.scroll(style, ctx, store))
371    }
372}
373
374impl Promptable<ProgramContext, ProgramStore, IambInfo> for RoomState {
375    fn prompt(
376        &mut self,
377        act: &PromptAction,
378        ctx: &ProgramContext,
379        store: &mut ProgramStore,
380    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
381        delegate!(self, w => w.prompt(act, ctx, store))
382    }
383}
384
385impl TerminalCursor for RoomState {
386    fn get_term_cursor(&self) -> Option<TermOffset> {
387        delegate!(self, w => w.get_term_cursor())
388    }
389}
390
391impl WindowOps<IambInfo> for RoomState {
392    fn draw(&mut self, area: Rect, buf: &mut Buffer, focused: bool, store: &mut ProgramStore) {
393        if let MatrixRoom::Invited(_) = self.room() {
394            self.refresh_room(store);
395        }
396
397        if let MatrixRoom::Invited(invited) = self.room() {
398            self.draw_invite(invited.clone(), area, buf, store);
399        }
400
401        match self {
402            RoomState::Chat(chat) => chat.draw(area, buf, focused, store),
403            RoomState::Space(space) => {
404                Space::new(store).focus(focused).render(area, buf, space);
405            },
406        }
407    }
408
409    fn dup(&self, store: &mut ProgramStore) -> Self {
410        match self {
411            RoomState::Chat(chat) => RoomState::Chat(chat.dup(store)),
412            RoomState::Space(space) => RoomState::Space(space.dup(store)),
413        }
414    }
415
416    fn close(&mut self, flags: CloseFlags, store: &mut ProgramStore) -> bool {
417        match self {
418            RoomState::Chat(chat) => chat.close(flags, store),
419            RoomState::Space(space) => space.close(flags, store),
420        }
421    }
422
423    fn write(
424        &mut self,
425        path: Option<&str>,
426        flags: WriteFlags,
427        store: &mut ProgramStore,
428    ) -> IambResult<EditInfo> {
429        match self {
430            RoomState::Chat(chat) => chat.write(path, flags, store),
431            RoomState::Space(space) => space.write(path, flags, store),
432        }
433    }
434
435    fn get_completions(&self) -> Option<CompletionList> {
436        match self {
437            RoomState::Chat(chat) => chat.get_completions(),
438            RoomState::Space(space) => space.get_completions(),
439        }
440    }
441
442    fn get_cursor_word(&self, style: &WordStyle) -> Option<String> {
443        match self {
444            RoomState::Chat(chat) => chat.get_cursor_word(style),
445            RoomState::Space(space) => space.get_cursor_word(style),
446        }
447    }
448
449    fn get_selected_word(&self) -> Option<String> {
450        match self {
451            RoomState::Chat(chat) => chat.get_selected_word(),
452            RoomState::Space(space) => space.get_selected_word(),
453        }
454    }
455}