src/windows/room/chat.rs

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