src/windows/room/chat.rs

680 lines · 21068 bytes

  1use std::borrow::Cow;
  2use std::ffi::OsStr;
  3use std::fs;
  4use std::ops::Deref;
  5use std::path::{Path, PathBuf};
  6
  7use matrix_sdk::{
  8    attachment::AttachmentConfig,
  9    media::{MediaFormat, MediaRequest},
 10    room::Room as MatrixRoom,
 11    ruma::{
 12        events::room::message::{
 13            MessageType,
 14            OriginalRoomMessageEvent,
 15            Relation,
 16            Replacement,
 17            RoomMessageEventContent,
 18            TextMessageEventContent,
 19        },
 20        OwnedRoomId,
 21        RoomId,
 22    },
 23};
 24
 25use modalkit::{
 26    tui::{
 27        buffer::Buffer,
 28        layout::Rect,
 29        text::{Span, Spans},
 30        widgets::{Paragraph, StatefulWidget, Widget},
 31    },
 32    widgets::textbox::{TextBox, TextBoxState},
 33    widgets::TerminalCursor,
 34    widgets::{PromptActions, WindowOps},
 35};
 36
 37use modalkit::editing::{
 38    action::{
 39        EditError,
 40        EditInfo,
 41        EditResult,
 42        Editable,
 43        EditorAction,
 44        InfoMessage,
 45        Jumpable,
 46        PromptAction,
 47        Promptable,
 48        Scrollable,
 49        UIError,
 50    },
 51    base::{CloseFlags, Count, MoveDir1D, PositionList, ScrollStyle, WordStyle},
 52    context::Resolve,
 53    history::{self, HistoryList},
 54    rope::EditRope,
 55};
 56
 57use crate::base::{
 58    IambAction,
 59    IambBufferId,
 60    IambError,
 61    IambInfo,
 62    IambResult,
 63    MessageAction,
 64    ProgramAction,
 65    ProgramContext,
 66    ProgramStore,
 67    RoomFocus,
 68    RoomInfo,
 69    SendAction,
 70};
 71
 72use crate::message::{Message, MessageEvent, MessageKey, MessageTimeStamp};
 73
 74use super::scrollback::{Scrollback, ScrollbackState};
 75
 76pub struct ChatState {
 77    room_id: OwnedRoomId,
 78    room: MatrixRoom,
 79
 80    tbox: TextBoxState<IambInfo>,
 81    sent: HistoryList<EditRope>,
 82    sent_scrollback: history::ScrollbackState,
 83
 84    scrollback: ScrollbackState,
 85    focus: RoomFocus,
 86
 87    reply_to: Option<MessageKey>,
 88    editing: Option<MessageKey>,
 89}
 90
 91impl ChatState {
 92    pub fn new(room: MatrixRoom, store: &mut ProgramStore) -> Self {
 93        let room_id = room.room_id().to_owned();
 94        let scrollback = ScrollbackState::new(room_id.clone());
 95        let id = IambBufferId::Room(room_id.clone(), RoomFocus::MessageBar);
 96        let ebuf = store.load_buffer(id);
 97        let tbox = TextBoxState::new(ebuf);
 98
 99        ChatState {
100            room_id,
101            room,
102
103            tbox,
104            sent: HistoryList::new(EditRope::from(""), 100),
105            sent_scrollback: history::ScrollbackState::Pending,
106
107            scrollback,
108            focus: RoomFocus::MessageBar,
109
110            reply_to: None,
111            editing: None,
112        }
113    }
114
115    fn get_reply_to<'a>(&self, info: &'a RoomInfo) -> Option<&'a OriginalRoomMessageEvent> {
116        let key = self.reply_to.as_ref()?;
117        let msg = info.messages.get(key)?;
118
119        if let MessageEvent::Original(ev) = &msg.event {
120            Some(ev)
121        } else {
122            None
123        }
124    }
125
126    fn reset(&mut self) -> EditRope {
127        self.reply_to = None;
128        self.editing = None;
129        self.tbox.reset()
130    }
131
132    pub fn refresh_room(&mut self, store: &mut ProgramStore) {
133        if let Some(room) = store.application.worker.client.get_room(self.id()) {
134            self.room = room;
135        }
136    }
137
138    pub async fn message_command(
139        &mut self,
140        act: MessageAction,
141        _: ProgramContext,
142        store: &mut ProgramStore,
143    ) -> IambResult<EditInfo> {
144        let client = &store.application.worker.client;
145
146        let settings = &store.application.settings;
147        let info = store.application.rooms.entry(self.room_id.clone()).or_default();
148
149        let msg = self.scrollback.get_mut(info).ok_or(IambError::NoSelectedMessage)?;
150
151        match act {
152            MessageAction::Cancel => {
153                self.reply_to = None;
154                self.editing = None;
155
156                Ok(None)
157            },
158            MessageAction::Download(filename, force) => {
159                if let MessageEvent::Original(ev) = &msg.event {
160                    let media = client.media();
161
162                    let mut filename = match filename {
163                        Some(f) => PathBuf::from(f),
164                        None => settings.dirs.downloads.clone(),
165                    };
166
167                    let source = match &ev.content.msgtype {
168                        MessageType::Audio(c) => {
169                            if filename.is_dir() {
170                                filename.push(c.body.as_str());
171                            }
172
173                            c.source.clone()
174                        },
175                        MessageType::File(c) => {
176                            if filename.is_dir() {
177                                if let Some(name) = &c.filename {
178                                    filename.push(name);
179                                } else {
180                                    filename.push(c.body.as_str());
181                                }
182                            }
183
184                            c.source.clone()
185                        },
186                        MessageType::Image(c) => {
187                            if filename.is_dir() {
188                                filename.push(c.body.as_str());
189                            }
190
191                            c.source.clone()
192                        },
193                        MessageType::Video(c) => {
194                            if filename.is_dir() {
195                                filename.push(c.body.as_str());
196                            }
197
198                            c.source.clone()
199                        },
200                        _ => {
201                            return Err(IambError::NoAttachment.into());
202                        },
203                    };
204
205                    if !force && filename.exists() {
206                        let msg = format!(
207                            "The file {} already exists; use :download! to overwrite it.",
208                            filename.display()
209                        );
210                        let err = UIError::Failure(msg);
211
212                        return Err(err);
213                    }
214
215                    let req = MediaRequest { source, format: MediaFormat::File };
216
217                    let bytes =
218                        media.get_media_content(&req, true).await.map_err(IambError::from)?;
219
220                    fs::write(filename.as_path(), bytes.as_slice())?;
221
222                    msg.downloaded = true;
223
224                    let info = InfoMessage::from(format!(
225                        "Attachment downloaded to {}",
226                        filename.display()
227                    ));
228
229                    return Ok(info.into());
230                }
231
232                Err(IambError::NoAttachment.into())
233            },
234            MessageAction::Edit => {
235                if msg.sender != settings.profile.user_id {
236                    let msg = "Cannot edit messages sent by someone else";
237                    let err = UIError::Failure(msg.into());
238
239                    return Err(err);
240                }
241
242                let ev = match &msg.event {
243                    MessageEvent::Original(ev) => &ev.content,
244                    MessageEvent::Local(ev) => ev.deref(),
245                    _ => {
246                        let msg = "Cannot edit a redacted message";
247                        let err = UIError::Failure(msg.into());
248
249                        return Err(err);
250                    },
251                };
252
253                let text = match &ev.msgtype {
254                    MessageType::Text(msg) => msg.body.as_str(),
255                    _ => {
256                        let msg = "Cannot edit a non-text message";
257                        let err = UIError::Failure(msg.into());
258
259                        return Err(err);
260                    },
261                };
262
263                self.tbox.set_text(text);
264                self.editing = self.scrollback.get_key(info);
265
266                Ok(None)
267            },
268            MessageAction::Redact(reason) => {
269                let room = store
270                    .application
271                    .worker
272                    .client
273                    .get_joined_room(self.id())
274                    .ok_or(IambError::NotJoined)?;
275
276                let event_id = match &msg.event {
277                    MessageEvent::Original(ev) => ev.event_id.clone(),
278                    MessageEvent::Local(_) => {
279                        self.scrollback.get_key(info).ok_or(IambError::NoSelectedMessage)?.1
280                    },
281                    MessageEvent::Redacted(_) => {
282                        let msg = "";
283                        let err = UIError::Failure(msg.into());
284
285                        return Err(err);
286                    },
287                };
288
289                let event_id = event_id.as_ref();
290                let reason = reason.as_deref();
291                let _ = room.redact(event_id, reason, None).await.map_err(IambError::from)?;
292
293                Ok(None)
294            },
295            MessageAction::Reply => {
296                self.reply_to = self.scrollback.get_key(info);
297                self.focus = RoomFocus::MessageBar;
298
299                Ok(None)
300            },
301        }
302    }
303
304    pub async fn send_command(
305        &mut self,
306        act: SendAction,
307        _: ProgramContext,
308        store: &mut ProgramStore,
309    ) -> IambResult<EditInfo> {
310        let room = store
311            .application
312            .worker
313            .client
314            .get_joined_room(self.id())
315            .ok_or(IambError::NotJoined)?;
316        let info = store.application.rooms.entry(self.id().to_owned()).or_default();
317        let mut show_echo = true;
318
319        let (event_id, msg) = match act {
320            SendAction::Submit => {
321                let msg = self.tbox.get_text();
322
323                if msg.is_empty() {
324                    return Ok(None);
325                }
326
327                let msg = TextMessageEventContent::markdown(msg);
328                let msg = MessageType::Text(msg);
329
330                let mut msg = RoomMessageEventContent::new(msg);
331
332                if let Some((_, event_id)) = &self.editing {
333                    msg.relates_to = Some(Relation::Replacement(Replacement::new(
334                        event_id.clone(),
335                        Box::new(msg.clone()),
336                    )));
337
338                    show_echo = false;
339                } else if let Some(m) = self.get_reply_to(info) {
340                    // XXX: Switch to RoomMessageEventContent::reply() once it's stable?
341                    msg = msg.make_reply_to(m);
342                }
343
344                // XXX: second parameter can be a locally unique transaction id.
345                // Useful for doing retries.
346                let resp = room.send(msg.clone(), None).await.map_err(IambError::from)?;
347                let event_id = resp.event_id;
348
349                // Reset message bar state now that it's been sent.
350                self.reset();
351
352                (event_id, msg)
353            },
354            SendAction::Upload(file) => {
355                let path = Path::new(file.as_str());
356                let mime = mime_guess::from_path(path).first_or(mime::APPLICATION_OCTET_STREAM);
357
358                let bytes = fs::read(path)?;
359                let name = path
360                    .file_name()
361                    .map(OsStr::to_string_lossy)
362                    .unwrap_or_else(|| Cow::from("Attachment"));
363                let config = AttachmentConfig::new();
364
365                let resp = room
366                    .send_attachment(name.as_ref(), &mime, bytes.as_ref(), config)
367                    .await
368                    .map_err(IambError::from)?;
369
370                // Mock up the local echo message for the scrollback.
371                let msg = TextMessageEventContent::plain(format!("[Attached File: {}]", name));
372                let msg = MessageType::Text(msg);
373                let msg = RoomMessageEventContent::new(msg);
374
375                (resp.event_id, msg)
376            },
377        };
378
379        if show_echo {
380            let user = store.application.settings.profile.user_id.clone();
381            let key = (MessageTimeStamp::LocalEcho, event_id);
382            let msg = MessageEvent::Local(msg.into());
383            let msg = Message::new(msg, user, MessageTimeStamp::LocalEcho);
384            info.messages.insert(key, msg);
385        }
386
387        // Jump to the end of the scrollback to show the message.
388        self.scrollback.goto_latest();
389
390        Ok(None)
391    }
392
393    pub fn focus_toggle(&mut self) {
394        self.focus = match self.focus {
395            RoomFocus::Scrollback => RoomFocus::MessageBar,
396            RoomFocus::MessageBar => RoomFocus::Scrollback,
397        };
398    }
399
400    pub fn room(&self) -> &MatrixRoom {
401        &self.room
402    }
403
404    pub fn id(&self) -> &RoomId {
405        &self.room_id
406    }
407
408    pub fn typing_notice(
409        &self,
410        act: &EditorAction,
411        ctx: &ProgramContext,
412        store: &mut ProgramStore,
413    ) {
414        if !self.focus.is_msgbar() || act.is_readonly(ctx) {
415            return;
416        }
417
418        if !store.application.settings.tunables.typing_notice {
419            return;
420        }
421
422        store.application.worker.typing_notice(self.room_id.clone());
423    }
424}
425
426macro_rules! delegate {
427    ($s: expr, $id: ident => $e: expr) => {
428        match $s.focus {
429            RoomFocus::Scrollback => {
430                match $s {
431                    ChatState { scrollback: $id, .. } => $e,
432                }
433            },
434            RoomFocus::MessageBar => {
435                match $s {
436                    ChatState { tbox: $id, .. } => $e,
437                }
438            },
439        }
440    };
441}
442
443impl WindowOps<IambInfo> for ChatState {
444    fn draw(&mut self, area: Rect, buf: &mut Buffer, focused: bool, store: &mut ProgramStore) {
445        Chat::new(store).focus(focused).render(area, buf, self)
446    }
447
448    fn dup(&self, store: &mut ProgramStore) -> Self {
449        // XXX: I want each WindowSlot to have its own shared buffer, instead of each Room; need to
450        // find a good way to pass that info here so that it can be part of the content id.
451        let id = IambBufferId::Room(self.room_id.clone(), RoomFocus::MessageBar);
452        let ebuf = store.load_buffer(id);
453        let tbox = TextBoxState::new(ebuf);
454
455        ChatState {
456            room_id: self.room_id.clone(),
457            room: self.room.clone(),
458
459            tbox,
460            sent: self.sent.clone(),
461            sent_scrollback: history::ScrollbackState::Pending,
462
463            scrollback: self.scrollback.dup(store),
464            focus: self.focus,
465
466            reply_to: None,
467            editing: None,
468        }
469    }
470
471    fn close(&mut self, _: CloseFlags, _: &mut ProgramStore) -> bool {
472        // XXX: what's the right closing behaviour for a room?
473        // Should write send a message?
474        true
475    }
476
477    fn get_cursor_word(&self, style: &WordStyle) -> Option<String> {
478        delegate!(self, w => w.get_cursor_word(style))
479    }
480
481    fn get_selected_word(&self) -> Option<String> {
482        delegate!(self, w => w.get_selected_word())
483    }
484}
485
486impl Editable<ProgramContext, ProgramStore, IambInfo> for ChatState {
487    fn editor_command(
488        &mut self,
489        act: &EditorAction,
490        ctx: &ProgramContext,
491        store: &mut ProgramStore,
492    ) -> EditResult<EditInfo, IambInfo> {
493        self.typing_notice(act, ctx, store);
494
495        match delegate!(self, w => w.editor_command(act, ctx, store)) {
496            res @ Ok(_) => res,
497            Err(EditError::WrongBuffer(IambBufferId::Room(room_id, focus)))
498                if room_id == self.room_id && act.is_switchable(ctx) =>
499            {
500                // Switch focus.
501                self.focus = focus;
502
503                // Run command again.
504                delegate!(self, w => w.editor_command(act, ctx, store))
505            },
506            res @ Err(_) => res,
507        }
508    }
509}
510
511impl TerminalCursor for ChatState {
512    fn get_term_cursor(&self) -> Option<(u16, u16)> {
513        delegate!(self, w => w.get_term_cursor())
514    }
515}
516
517impl Jumpable<ProgramContext, IambInfo> for ChatState {
518    fn jump(
519        &mut self,
520        list: PositionList,
521        dir: MoveDir1D,
522        count: usize,
523        ctx: &ProgramContext,
524    ) -> IambResult<usize> {
525        delegate!(self, w => w.jump(list, dir, count, ctx))
526    }
527}
528
529impl Scrollable<ProgramContext, ProgramStore, IambInfo> for ChatState {
530    fn scroll(
531        &mut self,
532        style: &ScrollStyle,
533        ctx: &ProgramContext,
534        store: &mut ProgramStore,
535    ) -> EditResult<EditInfo, IambInfo> {
536        // Send all scroll commands to the scrollback.
537        //
538        // If there's enough message text for scrolling to be necessary,
539        // navigating with movement keys should be enough to do the job.
540        self.scrollback.scroll(style, ctx, store)
541    }
542}
543
544impl PromptActions<ProgramContext, ProgramStore, IambInfo> for ChatState {
545    fn submit(
546        &mut self,
547        ctx: &ProgramContext,
548        _: &mut ProgramStore,
549    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
550        let act = SendAction::Submit;
551
552        Ok(vec![(IambAction::from(act).into(), ctx.clone())])
553    }
554
555    fn abort(
556        &mut self,
557        empty: bool,
558        _: &ProgramContext,
559        _: &mut ProgramStore,
560    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
561        let text = self.tbox.get();
562
563        if empty && text.is_blank() {
564            return Ok(vec![]);
565        }
566
567        let text = self.reset().trim();
568
569        if text.is_empty() {
570            let _ = self.sent.end();
571        } else {
572            self.sent.select(text);
573        }
574
575        return Ok(vec![]);
576    }
577
578    fn recall(
579        &mut self,
580        dir: &MoveDir1D,
581        count: &Count,
582        ctx: &ProgramContext,
583        _: &mut ProgramStore,
584    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
585        let count = ctx.resolve(count);
586        let rope = self.tbox.get();
587
588        let text = self.sent.recall(&rope, &mut self.sent_scrollback, *dir, count);
589
590        if let Some(text) = text {
591            self.tbox.set_text(text);
592        }
593
594        Ok(vec![])
595    }
596}
597
598impl Promptable<ProgramContext, ProgramStore, IambInfo> for ChatState {
599    fn prompt(
600        &mut self,
601        act: &PromptAction,
602        ctx: &ProgramContext,
603        store: &mut ProgramStore,
604    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
605        if let RoomFocus::Scrollback = self.focus {
606            return Ok(vec![]);
607        }
608
609        match act {
610            PromptAction::Submit => self.submit(ctx, store),
611            PromptAction::Abort(empty) => self.abort(*empty, ctx, store),
612            PromptAction::Recall(dir, count) => self.recall(dir, count, ctx, store),
613            _ => Err(EditError::Unimplemented("unknown prompt action".to_string())),
614        }
615    }
616}
617
618pub struct Chat<'a> {
619    store: &'a mut ProgramStore,
620    focused: bool,
621}
622
623impl<'a> Chat<'a> {
624    pub fn new(store: &'a mut ProgramStore) -> Chat<'a> {
625        Chat { store, focused: false }
626    }
627
628    pub fn focus(mut self, focused: bool) -> Self {
629        self.focused = focused;
630        self
631    }
632}
633
634impl<'a> StatefulWidget for Chat<'a> {
635    type State = ChatState;
636
637    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
638        let lines = state.tbox.has_lines(5).max(1) as u16;
639        let drawh = area.height;
640        let texth = lines.min(drawh).clamp(1, 5);
641        let desch = if state.reply_to.is_some() {
642            drawh.saturating_sub(texth).min(1)
643        } else {
644            0
645        };
646        let scrollh = drawh.saturating_sub(texth).saturating_sub(desch);
647
648        let scrollarea = Rect::new(area.x, area.y, area.width, scrollh);
649        let descarea = Rect::new(area.x, scrollarea.y + scrollh, area.width, desch);
650        let textarea = Rect::new(area.x, descarea.y + desch, area.width, texth);
651
652        let scrollback_focused = state.focus.is_scrollback() && self.focused;
653        let scrollback = Scrollback::new(self.store).focus(scrollback_focused);
654        scrollback.render(scrollarea, buf, &mut state.scrollback);
655
656        let desc_spans = match (&state.editing, &state.reply_to) {
657            (None, None) => None,
658            (Some(_), _) => Some(Spans::from("Editing message")),
659            (_, Some(_)) => {
660                state.reply_to.as_ref().and_then(|k| {
661                    let room = self.store.application.rooms.get(state.id())?;
662                    let msg = room.messages.get(k)?;
663                    let user = self.store.application.settings.get_user_span(msg.sender.as_ref());
664                    let spans = Spans(vec![Span::from("Replying to "), user]);
665
666                    spans.into()
667                })
668            },
669        };
670
671        if let Some(desc_spans) = desc_spans {
672            Paragraph::new(desc_spans).render(descarea, buf);
673        }
674
675        let prompt = if self.focused { "> " } else { "  " };
676
677        let tbox = TextBox::new().prompt(prompt);
678        tbox.render(textarea, buf, &mut state.tbox);
679    }
680}