src/windows/room/chat.rs

678 lines · 21004 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(event_id, _) => event_id.clone(),
279                    MessageEvent::Redacted(_) => {
280                        let msg = "";
281                        let err = UIError::Failure(msg.into());
282
283                        return Err(err);
284                    },
285                };
286
287                let event_id = event_id.as_ref();
288                let reason = reason.as_deref();
289                let _ = room.redact(event_id, reason, None).await.map_err(IambError::from)?;
290
291                Ok(None)
292            },
293            MessageAction::Reply => {
294                self.reply_to = self.scrollback.get_key(info);
295                self.focus = RoomFocus::MessageBar;
296
297                Ok(None)
298            },
299        }
300    }
301
302    pub async fn send_command(
303        &mut self,
304        act: SendAction,
305        _: ProgramContext,
306        store: &mut ProgramStore,
307    ) -> IambResult<EditInfo> {
308        let room = store
309            .application
310            .worker
311            .client
312            .get_joined_room(self.id())
313            .ok_or(IambError::NotJoined)?;
314        let info = store.application.rooms.entry(self.id().to_owned()).or_default();
315        let mut show_echo = true;
316
317        let (event_id, msg) = match act {
318            SendAction::Submit => {
319                let msg = self.tbox.get_text();
320
321                if msg.is_empty() {
322                    return Ok(None);
323                }
324
325                let msg = TextMessageEventContent::markdown(msg);
326                let msg = MessageType::Text(msg);
327
328                let mut msg = RoomMessageEventContent::new(msg);
329
330                if let Some((_, event_id)) = &self.editing {
331                    msg.relates_to = Some(Relation::Replacement(Replacement::new(
332                        event_id.clone(),
333                        Box::new(msg.clone()),
334                    )));
335
336                    show_echo = false;
337                } else if let Some(m) = self.get_reply_to(info) {
338                    // XXX: Switch to RoomMessageEventContent::reply() once it's stable?
339                    msg = msg.make_reply_to(m);
340                }
341
342                // XXX: second parameter can be a locally unique transaction id.
343                // Useful for doing retries.
344                let resp = room.send(msg.clone(), None).await.map_err(IambError::from)?;
345                let event_id = resp.event_id;
346
347                // Reset message bar state now that it's been sent.
348                self.reset();
349
350                (event_id, msg)
351            },
352            SendAction::Upload(file) => {
353                let path = Path::new(file.as_str());
354                let mime = mime_guess::from_path(path).first_or(mime::APPLICATION_OCTET_STREAM);
355
356                let bytes = fs::read(path)?;
357                let name = path
358                    .file_name()
359                    .map(OsStr::to_string_lossy)
360                    .unwrap_or_else(|| Cow::from("Attachment"));
361                let config = AttachmentConfig::new();
362
363                let resp = room
364                    .send_attachment(name.as_ref(), &mime, bytes.as_ref(), config)
365                    .await
366                    .map_err(IambError::from)?;
367
368                // Mock up the local echo message for the scrollback.
369                let msg = TextMessageEventContent::plain(format!("[Attached File: {}]", name));
370                let msg = MessageType::Text(msg);
371                let msg = RoomMessageEventContent::new(msg);
372
373                (resp.event_id, msg)
374            },
375        };
376
377        if show_echo {
378            let user = store.application.settings.profile.user_id.clone();
379            let key = (MessageTimeStamp::LocalEcho, event_id.clone());
380            let msg = MessageEvent::Local(event_id, msg.into());
381            let msg = Message::new(msg, user, MessageTimeStamp::LocalEcho);
382            info.messages.insert(key, msg);
383        }
384
385        // Jump to the end of the scrollback to show the message.
386        self.scrollback.goto_latest();
387
388        Ok(None)
389    }
390
391    pub fn focus_toggle(&mut self) {
392        self.focus = match self.focus {
393            RoomFocus::Scrollback => RoomFocus::MessageBar,
394            RoomFocus::MessageBar => RoomFocus::Scrollback,
395        };
396    }
397
398    pub fn room(&self) -> &MatrixRoom {
399        &self.room
400    }
401
402    pub fn id(&self) -> &RoomId {
403        &self.room_id
404    }
405
406    pub fn typing_notice(
407        &self,
408        act: &EditorAction,
409        ctx: &ProgramContext,
410        store: &mut ProgramStore,
411    ) {
412        if !self.focus.is_msgbar() || act.is_readonly(ctx) {
413            return;
414        }
415
416        if !store.application.settings.tunables.typing_notice_send {
417            return;
418        }
419
420        store.application.worker.typing_notice(self.room_id.clone());
421    }
422}
423
424macro_rules! delegate {
425    ($s: expr, $id: ident => $e: expr) => {
426        match $s.focus {
427            RoomFocus::Scrollback => {
428                match $s {
429                    ChatState { scrollback: $id, .. } => $e,
430                }
431            },
432            RoomFocus::MessageBar => {
433                match $s {
434                    ChatState { tbox: $id, .. } => $e,
435                }
436            },
437        }
438    };
439}
440
441impl WindowOps<IambInfo> for ChatState {
442    fn draw(&mut self, area: Rect, buf: &mut Buffer, focused: bool, store: &mut ProgramStore) {
443        Chat::new(store).focus(focused).render(area, buf, self)
444    }
445
446    fn dup(&self, store: &mut ProgramStore) -> Self {
447        // XXX: I want each WindowSlot to have its own shared buffer, instead of each Room; need to
448        // find a good way to pass that info here so that it can be part of the content id.
449        let id = IambBufferId::Room(self.room_id.clone(), RoomFocus::MessageBar);
450        let ebuf = store.load_buffer(id);
451        let tbox = TextBoxState::new(ebuf);
452
453        ChatState {
454            room_id: self.room_id.clone(),
455            room: self.room.clone(),
456
457            tbox,
458            sent: self.sent.clone(),
459            sent_scrollback: history::ScrollbackState::Pending,
460
461            scrollback: self.scrollback.dup(store),
462            focus: self.focus,
463
464            reply_to: None,
465            editing: None,
466        }
467    }
468
469    fn close(&mut self, _: CloseFlags, _: &mut ProgramStore) -> bool {
470        // XXX: what's the right closing behaviour for a room?
471        // Should write send a message?
472        true
473    }
474
475    fn get_cursor_word(&self, style: &WordStyle) -> Option<String> {
476        delegate!(self, w => w.get_cursor_word(style))
477    }
478
479    fn get_selected_word(&self) -> Option<String> {
480        delegate!(self, w => w.get_selected_word())
481    }
482}
483
484impl Editable<ProgramContext, ProgramStore, IambInfo> for ChatState {
485    fn editor_command(
486        &mut self,
487        act: &EditorAction,
488        ctx: &ProgramContext,
489        store: &mut ProgramStore,
490    ) -> EditResult<EditInfo, IambInfo> {
491        self.typing_notice(act, ctx, store);
492
493        match delegate!(self, w => w.editor_command(act, ctx, store)) {
494            res @ Ok(_) => res,
495            Err(EditError::WrongBuffer(IambBufferId::Room(room_id, focus)))
496                if room_id == self.room_id && act.is_switchable(ctx) =>
497            {
498                // Switch focus.
499                self.focus = focus;
500
501                // Run command again.
502                delegate!(self, w => w.editor_command(act, ctx, store))
503            },
504            res @ Err(_) => res,
505        }
506    }
507}
508
509impl TerminalCursor for ChatState {
510    fn get_term_cursor(&self) -> Option<(u16, u16)> {
511        delegate!(self, w => w.get_term_cursor())
512    }
513}
514
515impl Jumpable<ProgramContext, IambInfo> for ChatState {
516    fn jump(
517        &mut self,
518        list: PositionList,
519        dir: MoveDir1D,
520        count: usize,
521        ctx: &ProgramContext,
522    ) -> IambResult<usize> {
523        delegate!(self, w => w.jump(list, dir, count, ctx))
524    }
525}
526
527impl Scrollable<ProgramContext, ProgramStore, IambInfo> for ChatState {
528    fn scroll(
529        &mut self,
530        style: &ScrollStyle,
531        ctx: &ProgramContext,
532        store: &mut ProgramStore,
533    ) -> EditResult<EditInfo, IambInfo> {
534        // Send all scroll commands to the scrollback.
535        //
536        // If there's enough message text for scrolling to be necessary,
537        // navigating with movement keys should be enough to do the job.
538        self.scrollback.scroll(style, ctx, store)
539    }
540}
541
542impl PromptActions<ProgramContext, ProgramStore, IambInfo> for ChatState {
543    fn submit(
544        &mut self,
545        ctx: &ProgramContext,
546        _: &mut ProgramStore,
547    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
548        let act = SendAction::Submit;
549
550        Ok(vec![(IambAction::from(act).into(), ctx.clone())])
551    }
552
553    fn abort(
554        &mut self,
555        empty: bool,
556        _: &ProgramContext,
557        _: &mut ProgramStore,
558    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
559        let text = self.tbox.get();
560
561        if empty && text.is_blank() {
562            return Ok(vec![]);
563        }
564
565        let text = self.reset().trim();
566
567        if text.is_empty() {
568            let _ = self.sent.end();
569        } else {
570            self.sent.select(text);
571        }
572
573        return Ok(vec![]);
574    }
575
576    fn recall(
577        &mut self,
578        dir: &MoveDir1D,
579        count: &Count,
580        ctx: &ProgramContext,
581        _: &mut ProgramStore,
582    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
583        let count = ctx.resolve(count);
584        let rope = self.tbox.get();
585
586        let text = self.sent.recall(&rope, &mut self.sent_scrollback, *dir, count);
587
588        if let Some(text) = text {
589            self.tbox.set_text(text);
590        }
591
592        Ok(vec![])
593    }
594}
595
596impl Promptable<ProgramContext, ProgramStore, IambInfo> for ChatState {
597    fn prompt(
598        &mut self,
599        act: &PromptAction,
600        ctx: &ProgramContext,
601        store: &mut ProgramStore,
602    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
603        if let RoomFocus::Scrollback = self.focus {
604            return Ok(vec![]);
605        }
606
607        match act {
608            PromptAction::Submit => self.submit(ctx, store),
609            PromptAction::Abort(empty) => self.abort(*empty, ctx, store),
610            PromptAction::Recall(dir, count) => self.recall(dir, count, ctx, store),
611            _ => Err(EditError::Unimplemented("unknown prompt action".to_string())),
612        }
613    }
614}
615
616pub struct Chat<'a> {
617    store: &'a mut ProgramStore,
618    focused: bool,
619}
620
621impl<'a> Chat<'a> {
622    pub fn new(store: &'a mut ProgramStore) -> Chat<'a> {
623        Chat { store, focused: false }
624    }
625
626    pub fn focus(mut self, focused: bool) -> Self {
627        self.focused = focused;
628        self
629    }
630}
631
632impl<'a> StatefulWidget for Chat<'a> {
633    type State = ChatState;
634
635    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
636        let lines = state.tbox.has_lines(5).max(1) as u16;
637        let drawh = area.height;
638        let texth = lines.min(drawh).clamp(1, 5);
639        let desch = if state.reply_to.is_some() {
640            drawh.saturating_sub(texth).min(1)
641        } else {
642            0
643        };
644        let scrollh = drawh.saturating_sub(texth).saturating_sub(desch);
645
646        let scrollarea = Rect::new(area.x, area.y, area.width, scrollh);
647        let descarea = Rect::new(area.x, scrollarea.y + scrollh, area.width, desch);
648        let textarea = Rect::new(area.x, descarea.y + desch, area.width, texth);
649
650        let scrollback_focused = state.focus.is_scrollback() && self.focused;
651        let scrollback = Scrollback::new(self.store).focus(scrollback_focused);
652        scrollback.render(scrollarea, buf, &mut state.scrollback);
653
654        let desc_spans = match (&state.editing, &state.reply_to) {
655            (None, None) => None,
656            (Some(_), _) => Some(Spans::from("Editing message")),
657            (_, Some(_)) => {
658                state.reply_to.as_ref().and_then(|k| {
659                    let room = self.store.application.rooms.get(state.id())?;
660                    let msg = room.messages.get(k)?;
661                    let user = self.store.application.settings.get_user_span(msg.sender.as_ref());
662                    let spans = Spans(vec![Span::from("Replying to "), user]);
663
664                    spans.into()
665                })
666            },
667        };
668
669        if let Some(desc_spans) = desc_spans {
670            Paragraph::new(desc_spans).render(descarea, buf);
671        }
672
673        let prompt = if self.focused { "> " } else { "  " };
674
675        let tbox = TextBox::new().prompt(prompt);
676        tbox.render(textarea, buf, &mut state.tbox);
677    }
678}