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