src/windows/room/chat.rs

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