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