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