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