src/windows/room/chat.rs

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