src/windows/room/chat.rs

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