src/windows/room/chat.rs

595 lines · 17968 bytes

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