src/windows/room/chat.rs
963 lines · 33358 bytes
1//! Window for Matrix rooms
2use std::borrow::Cow;
3use std::ffi::{OsStr, OsString};
4use std::fs;
5use std::ops::Deref;
6use std::path::{Path, PathBuf};
7
8use edit::edit as external_edit;
9use modalkit::editing::store::RegisterError;
10use std::process::Command;
11use tokio;
12use url::Url;
13
14use matrix_sdk::{
15 attachment::AttachmentConfig,
16 media::{MediaFormat, MediaRequest},
17 room::Room as MatrixRoom,
18 ruma::{
19 events::reaction::ReactionEventContent,
20 events::relation::{Annotation, Replacement},
21 events::room::message::{
22 AddMentions,
23 ForwardThread,
24 MessageType,
25 OriginalRoomMessageEvent,
26 Relation,
27 ReplyWithinThread,
28 RoomMessageEventContent,
29 TextMessageEventContent,
30 },
31 EventId,
32 OwnedEventId,
33 OwnedRoomId,
34 RoomId,
35 },
36 RoomState,
37};
38
39use ratatui::{
40 buffer::Buffer,
41 layout::Rect,
42 text::{Line, Span},
43 widgets::{Paragraph, StatefulWidget, Widget},
44};
45
46use modalkit::keybindings::dialog::{MultiChoice, MultiChoiceItem, PromptYesNo};
47
48use modalkit_ratatui::{
49 textbox::{TextBox, TextBoxState},
50 PromptActions,
51 TerminalCursor,
52 WindowOps,
53};
54
55use modalkit::actions::{
56 Action,
57 Editable,
58 EditorAction,
59 Jumpable,
60 PromptAction,
61 Promptable,
62 Scrollable,
63};
64use modalkit::editing::{
65 completion::CompletionList,
66 context::Resolve,
67 history::{self, HistoryList},
68 rope::EditRope,
69};
70use modalkit::errors::{EditError, EditResult, UIError};
71use modalkit::prelude::*;
72
73use crate::base::{
74 DownloadFlags,
75 EventLocation,
76 IambAction,
77 IambBufferId,
78 IambError,
79 IambInfo,
80 IambResult,
81 MessageAction,
82 ProgramAction,
83 ProgramContext,
84 ProgramStore,
85 RoomFocus,
86 RoomInfo,
87 SendAction,
88};
89
90use crate::message::{text_to_message, Message, MessageEvent, MessageKey, MessageTimeStamp};
91use crate::worker::Requester;
92
93use super::scrollback::{Scrollback, ScrollbackState};
94
95/// State needed for rendering [Chat].
96pub struct ChatState {
97 room_id: OwnedRoomId,
98 room: MatrixRoom,
99
100 tbox: TextBoxState<IambInfo>,
101 sent: HistoryList<EditRope>,
102 sent_scrollback: history::ScrollbackState,
103
104 scrollback: ScrollbackState,
105 focus: RoomFocus,
106
107 reply_to: Option<MessageKey>,
108 editing: Option<MessageKey>,
109}
110
111impl ChatState {
112 pub fn new(room: MatrixRoom, thread: Option<OwnedEventId>, store: &mut ProgramStore) -> Self {
113 let room_id = room.room_id().to_owned();
114 let scrollback = ScrollbackState::new(room_id.clone(), thread.clone());
115 let id = IambBufferId::Room(room_id.clone(), thread, RoomFocus::MessageBar);
116 let ebuf = store.load_buffer(id);
117 let tbox = TextBoxState::new(ebuf);
118
119 ChatState {
120 room_id,
121 room,
122
123 tbox,
124 sent: HistoryList::new(EditRope::from(""), 100),
125 sent_scrollback: history::ScrollbackState::Pending,
126
127 scrollback,
128 focus: RoomFocus::MessageBar,
129
130 reply_to: None,
131 editing: None,
132 }
133 }
134
135 pub fn thread(&self) -> Option<&OwnedEventId> {
136 self.scrollback.thread()
137 }
138
139 fn get_joined(&self, worker: &Requester) -> Result<MatrixRoom, IambError> {
140 let Some(room) = worker.client.get_room(self.id()) else {
141 return Err(IambError::NotJoined);
142 };
143
144 if room.state() == RoomState::Joined {
145 Ok(room)
146 } else {
147 Err(IambError::NotJoined)
148 }
149 }
150
151 fn get_thread_last<'a>(
152 &self,
153 thread_root: &OwnedEventId,
154 info: &'a RoomInfo,
155 ) -> Option<&'a OriginalRoomMessageEvent> {
156 let last = info.threads.get(thread_root).and_then(|t| Some(t.last_key_value()?.1));
157
158 let msg = if let Some(last) = last {
159 &last.event
160 } else if let EventLocation::Message(_, key) = info.keys.get(thread_root)? {
161 let msg = info.messages.get(key)?;
162 &msg.event
163 } else {
164 return None;
165 };
166
167 if let MessageEvent::Original(ev) = &msg {
168 Some(ev)
169 } else {
170 None
171 }
172 }
173
174 fn get_reply_to<'a>(&self, info: &'a RoomInfo) -> Option<&'a OriginalRoomMessageEvent> {
175 let key = self.reply_to.as_ref()?;
176 let msg = info.messages.get(key)?;
177
178 if let MessageEvent::Original(ev) = &msg.event {
179 Some(ev)
180 } else {
181 None
182 }
183 }
184
185 fn reset(&mut self) -> EditRope {
186 self.reply_to = None;
187 self.editing = None;
188 self.tbox.reset()
189 }
190
191 pub fn refresh_room(&mut self, store: &mut ProgramStore) {
192 if let Some(room) = store.application.worker.client.get_room(self.id()) {
193 self.room = room;
194 }
195 }
196
197 pub async fn message_command(
198 &mut self,
199 act: MessageAction,
200 _: ProgramContext,
201 store: &mut ProgramStore,
202 ) -> IambResult<EditInfo> {
203 let client = &store.application.worker.client;
204
205 let settings = &store.application.settings;
206 let info = store.application.rooms.get_or_default(self.room_id.clone());
207
208 let msg = self
209 .scrollback
210 .get_mut(&mut info.messages)
211 .ok_or(IambError::NoSelectedMessage)?;
212
213 match act {
214 MessageAction::Cancel(skip_confirm) => {
215 self.reply_to = None;
216 self.editing = None;
217
218 if skip_confirm {
219 return Ok(None);
220 }
221
222 let msg = "Would you like to clear the message bar?";
223 let act = PromptAction::Abort(false);
224 let prompt = PromptYesNo::new(msg, vec![Action::from(act)]);
225 let prompt = Box::new(prompt);
226
227 Err(UIError::NeedConfirm(prompt))
228 },
229 MessageAction::Download(filename, flags) => {
230 if let MessageEvent::Original(ev) = &msg.event {
231 let media = client.media();
232
233 let mut filename = match (filename, &settings.dirs.downloads) {
234 (Some(f), _) => PathBuf::from(f),
235 (None, Some(downloads)) => downloads.clone(),
236 (None, None) => return Err(IambError::NoDownloadDir.into()),
237 };
238
239 let (source, msg_filename) = match &ev.content.msgtype {
240 MessageType::Audio(c) => (c.source.clone(), c.body.as_str()),
241 MessageType::File(c) => {
242 (c.source.clone(), c.filename.as_deref().unwrap_or(c.body.as_str()))
243 },
244 MessageType::Image(c) => (c.source.clone(), c.body.as_str()),
245 MessageType::Video(c) => (c.source.clone(), c.body.as_str()),
246 _ => {
247 if !flags.contains(DownloadFlags::OPEN) {
248 return Err(IambError::NoAttachment.into());
249 }
250
251 let links = if let Some(html) = &msg.html {
252 html.get_links()
253 } else if let Ok(url) = Url::parse(&msg.event.body()) {
254 vec![('0', url)]
255 } else {
256 vec![]
257 };
258
259 if links.is_empty() {
260 return Err(IambError::NoAttachment.into());
261 }
262
263 let choices = links
264 .into_iter()
265 .map(|l| {
266 let url = l.1.to_string();
267 let act = IambAction::OpenLink(url.clone()).into();
268 MultiChoiceItem::new(l.0, url, vec![act])
269 })
270 .collect();
271 let dialog = MultiChoice::new(choices);
272 let err = UIError::NeedConfirm(Box::new(dialog));
273
274 return Err(err);
275 },
276 };
277
278 if filename.is_dir() {
279 filename.push(msg_filename);
280 }
281
282 if filename.exists() && !flags.contains(DownloadFlags::FORCE) {
283 // Find an incrementally suffixed filename, e.g. image-2.jpg -> image-3.jpg
284 if let Some(stem) = filename.file_stem().and_then(OsStr::to_str) {
285 let ext = filename.extension();
286 let mut filename_incr = filename.clone();
287 for n in 1..=1000 {
288 if let Some(ext) = ext.and_then(OsStr::to_str) {
289 filename_incr.set_file_name(format!("{}-{}.{}", stem, n, ext));
290 } else {
291 filename_incr.set_file_name(format!("{}-{}", stem, n));
292 }
293
294 if !filename_incr.exists() {
295 filename = filename_incr;
296 break;
297 }
298 }
299 }
300 }
301
302 if !filename.exists() || flags.contains(DownloadFlags::FORCE) {
303 let req = MediaRequest { source, format: MediaFormat::File };
304
305 let bytes =
306 media.get_media_content(&req, true).await.map_err(IambError::from)?;
307
308 fs::write(filename.as_path(), bytes.as_slice())?;
309
310 msg.downloaded = true;
311 } else if !flags.contains(DownloadFlags::OPEN) {
312 let msg = format!(
313 "The file {} already exists; add ! to end of command to overwrite it.",
314 filename.display()
315 );
316 let err = UIError::Failure(msg);
317
318 return Err(err);
319 }
320
321 let info = if flags.contains(DownloadFlags::OPEN) {
322 let target = filename.clone().into_os_string();
323 match open_command(
324 store.application.settings.tunables.open_command.as_ref(),
325 target,
326 ) {
327 Ok(_) => {
328 InfoMessage::from(format!(
329 "Attachment downloaded to {} and opened",
330 filename.display()
331 ))
332 },
333 Err(err) => {
334 return Err(err);
335 },
336 }
337 } else {
338 InfoMessage::from(format!(
339 "Attachment downloaded to {}",
340 filename.display()
341 ))
342 };
343
344 return Ok(info.into());
345 }
346
347 Err(IambError::NoAttachment.into())
348 },
349 MessageAction::Edit => {
350 if msg.sender != settings.profile.user_id {
351 let msg = "Cannot edit messages sent by someone else";
352 let err = UIError::Failure(msg.into());
353
354 return Err(err);
355 }
356
357 let ev = match &msg.event {
358 MessageEvent::Original(ev) => &ev.content,
359 MessageEvent::Local(_, ev) => ev.deref(),
360 _ => {
361 let msg = "Cannot edit a redacted message";
362 let err = UIError::Failure(msg.into());
363
364 return Err(err);
365 },
366 };
367
368 let text = match &ev.msgtype {
369 MessageType::Text(msg) => msg.body.as_str(),
370 _ => {
371 let msg = "Cannot edit a non-text message";
372 let err = UIError::Failure(msg.into());
373
374 return Err(err);
375 },
376 };
377
378 self.tbox.set_text(text);
379 self.reply_to = msg.reply_to().and_then(|id| info.get_message_key(&id)).cloned();
380 self.editing = self.scrollback.get_key(info);
381 self.focus = RoomFocus::MessageBar;
382
383 Ok(None)
384 },
385 MessageAction::React(emoji) => {
386 let room = self.get_joined(&store.application.worker)?;
387 let event_id = match &msg.event {
388 MessageEvent::EncryptedOriginal(ev) => ev.event_id.clone(),
389 MessageEvent::EncryptedRedacted(ev) => ev.event_id.clone(),
390 MessageEvent::Original(ev) => ev.event_id.clone(),
391 MessageEvent::Local(event_id, _) => event_id.clone(),
392 MessageEvent::Redacted(_) => {
393 let msg = "Cannot react to a redacted message";
394 let err = UIError::Failure(msg.into());
395
396 return Err(err);
397 },
398 };
399
400 let reaction = Annotation::new(event_id, emoji);
401 let msg = ReactionEventContent::new(reaction);
402 let _ = room.send(msg).await.map_err(IambError::from)?;
403
404 Ok(None)
405 },
406 MessageAction::Redact(reason, skip_confirm) => {
407 if !skip_confirm {
408 let msg = "Are you sure you want to redact this message?";
409 let act = IambAction::Message(MessageAction::Redact(reason, true));
410 let prompt = PromptYesNo::new(msg, vec![Action::from(act)]);
411 let prompt = Box::new(prompt);
412
413 return Err(UIError::NeedConfirm(prompt));
414 }
415
416 let room = self.get_joined(&store.application.worker)?;
417 let event_id = match &msg.event {
418 MessageEvent::EncryptedOriginal(ev) => ev.event_id.clone(),
419 MessageEvent::EncryptedRedacted(ev) => ev.event_id.clone(),
420 MessageEvent::Original(ev) => ev.event_id.clone(),
421 MessageEvent::Local(event_id, _) => event_id.clone(),
422 MessageEvent::Redacted(_) => {
423 let msg = "Cannot redact already redacted message";
424 let err = UIError::Failure(msg.into());
425
426 return Err(err);
427 },
428 };
429
430 let event_id = event_id.as_ref();
431 let reason = reason.as_deref();
432 let _ = room.redact(event_id, reason, None).await.map_err(IambError::from)?;
433
434 Ok(None)
435 },
436 MessageAction::Reply => {
437 self.reply_to = self.scrollback.get_key(info);
438 self.focus = RoomFocus::MessageBar;
439
440 Ok(None)
441 },
442 MessageAction::Unreact(emoji) => {
443 let room = self.get_joined(&store.application.worker)?;
444 let event_id: &EventId = match &msg.event {
445 MessageEvent::EncryptedOriginal(ev) => ev.event_id.as_ref(),
446 MessageEvent::EncryptedRedacted(ev) => ev.event_id.as_ref(),
447 MessageEvent::Original(ev) => ev.event_id.as_ref(),
448 MessageEvent::Local(event_id, _) => event_id.as_ref(),
449 MessageEvent::Redacted(_) => {
450 let msg = "Cannot unreact to a redacted message";
451 let err = UIError::Failure(msg.into());
452
453 return Err(err);
454 },
455 };
456
457 let reactions = match info.reactions.get(event_id) {
458 Some(r) => r,
459 None => return Ok(None),
460 };
461
462 let reactions = reactions.iter().filter_map(|(event_id, (reaction, user_id))| {
463 if user_id != &settings.profile.user_id {
464 return None;
465 }
466
467 if let Some(emoji) = &emoji {
468 if emoji == reaction {
469 return Some(event_id);
470 } else {
471 return None;
472 }
473 } else {
474 return Some(event_id);
475 }
476 });
477
478 for reaction in reactions {
479 let _ = room.redact(reaction, None, None).await.map_err(IambError::from)?;
480 }
481
482 Ok(None)
483 },
484 }
485 }
486
487 pub async fn send_command(
488 &mut self,
489 act: SendAction,
490 _: ProgramContext,
491 store: &mut ProgramStore,
492 ) -> IambResult<EditInfo> {
493 let room = self.get_joined(&store.application.worker)?;
494 let info = store.application.rooms.get_or_default(self.id().to_owned());
495 let mut show_echo = true;
496
497 let (event_id, msg) = match act {
498 SendAction::Submit | SendAction::SubmitFromEditor => {
499 let msg = self.tbox.get();
500
501 let msg = if let SendAction::SubmitFromEditor = act {
502 external_edit(msg.trim_end().to_string())?
503 } else if msg.is_blank() {
504 return Ok(None);
505 } else {
506 msg.trim_end().to_string()
507 };
508
509 let mut msg = text_to_message(msg);
510
511 if let Some((_, event_id)) = &self.editing {
512 msg.relates_to = Some(Relation::Replacement(Replacement::new(
513 event_id.clone(),
514 msg.msgtype.clone().into(),
515 )));
516
517 show_echo = false;
518 } else if let Some(thread_root) = self.scrollback.thread() {
519 if let Some(m) = self.get_reply_to(info) {
520 msg = msg.make_for_thread(m, ReplyWithinThread::Yes, AddMentions::No);
521 } else if let Some(m) = self.get_thread_last(thread_root, info) {
522 msg = msg.make_for_thread(m, ReplyWithinThread::No, AddMentions::No);
523 } else {
524 // Internal state is wonky?
525 }
526 } else if let Some(m) = self.get_reply_to(info) {
527 msg = msg.make_reply_to(m, ForwardThread::Yes, AddMentions::No);
528 }
529
530 // XXX: second parameter can be a locally unique transaction id.
531 // Useful for doing retries.
532 let resp = room.send(msg.clone()).await.map_err(IambError::from)?;
533 let event_id = resp.event_id;
534
535 // Reset message bar state now that it's been sent.
536 self.reset();
537
538 (event_id, msg)
539 },
540 SendAction::Upload(file) => {
541 let path = Path::new(file.as_str());
542 let mime = mime_guess::from_path(path).first_or(mime::APPLICATION_OCTET_STREAM);
543
544 let bytes = fs::read(path)?;
545 let name = path
546 .file_name()
547 .map(OsStr::to_string_lossy)
548 .unwrap_or_else(|| Cow::from("Attachment"));
549 let config = AttachmentConfig::new();
550
551 let resp = room
552 .send_attachment(name.as_ref(), &mime, bytes, config)
553 .await
554 .map_err(IambError::from)?;
555
556 // Mock up the local echo message for the scrollback.
557 let msg = TextMessageEventContent::plain(format!("[Attached File: {name}]"));
558 let msg = MessageType::Text(msg);
559 let msg = RoomMessageEventContent::new(msg);
560
561 (resp.event_id, msg)
562 },
563 SendAction::UploadImage(width, height, bytes) => {
564 // Convert to png because arboard does not give us the mime type.
565 let bytes =
566 image::ImageBuffer::from_raw(width as _, height as _, bytes.into_owned())
567 .ok_or(IambError::Clipboard)
568 .and_then(|imagebuf| {
569 let dynimage = image::DynamicImage::ImageRgba8(imagebuf);
570 let bytes = Vec::<u8>::new();
571 let mut buff = std::io::Cursor::new(bytes);
572 dynimage.write_to(&mut buff, image::ImageOutputFormat::Png)?;
573 Ok(buff.into_inner())
574 })
575 .map_err(IambError::from)?;
576 let mime = mime::IMAGE_PNG;
577
578 let name = "Clipboard.png";
579 let config = AttachmentConfig::new();
580
581 let resp = room
582 .send_attachment(name.as_ref(), &mime, bytes, config)
583 .await
584 .map_err(IambError::from)?;
585
586 // Mock up the local echo message for the scrollback.
587 let msg = TextMessageEventContent::plain(format!("[Attached File: {name}]"));
588 let msg = MessageType::Text(msg);
589 let msg = RoomMessageEventContent::new(msg);
590
591 (resp.event_id, msg)
592 },
593 };
594
595 if show_echo {
596 let user = store.application.settings.profile.user_id.clone();
597 let key = (MessageTimeStamp::LocalEcho, event_id.clone());
598 let msg = MessageEvent::Local(event_id, msg.into());
599 let msg = Message::new(msg, user, MessageTimeStamp::LocalEcho);
600 let thread = self.scrollback.get_thread_mut(info);
601 thread.insert(key, msg);
602 }
603
604 // Jump to the end of the scrollback to show the message.
605 self.scrollback.goto_latest();
606
607 Ok(None)
608 }
609
610 pub fn focus_toggle(&mut self) {
611 self.focus = match self.focus {
612 RoomFocus::Scrollback => RoomFocus::MessageBar,
613 RoomFocus::MessageBar => RoomFocus::Scrollback,
614 };
615 }
616
617 pub fn room(&self) -> &MatrixRoom {
618 &self.room
619 }
620
621 pub fn id(&self) -> &RoomId {
622 &self.room_id
623 }
624
625 pub fn typing_notice(
626 &self,
627 act: &EditorAction,
628 ctx: &ProgramContext,
629 store: &mut ProgramStore,
630 ) {
631 if !self.focus.is_msgbar() || act.is_readonly(ctx) {
632 return;
633 }
634
635 if !store.application.settings.tunables.typing_notice_send {
636 return;
637 }
638
639 store.application.worker.typing_notice(self.room_id.clone());
640 }
641}
642
643macro_rules! delegate {
644 ($s: expr, $id: ident => $e: expr) => {
645 match $s.focus {
646 RoomFocus::Scrollback => {
647 match $s {
648 ChatState { scrollback: $id, .. } => $e,
649 }
650 },
651 RoomFocus::MessageBar => {
652 match $s {
653 ChatState { tbox: $id, .. } => $e,
654 }
655 },
656 }
657 };
658}
659
660impl WindowOps<IambInfo> for ChatState {
661 fn draw(&mut self, area: Rect, buf: &mut Buffer, focused: bool, store: &mut ProgramStore) {
662 Chat::new(store).focus(focused).render(area, buf, self)
663 }
664
665 fn dup(&self, store: &mut ProgramStore) -> Self {
666 // XXX: I want each WindowSlot to have its own shared buffer, instead of each Room; need to
667 // find a good way to pass that info here so that it can be part of the content id.
668 let room_id = self.room_id.clone();
669 let thread = self.thread().cloned();
670 let id = IambBufferId::Room(room_id.clone(), thread, RoomFocus::MessageBar);
671 let ebuf = store.load_buffer(id);
672 let tbox = TextBoxState::new(ebuf);
673
674 ChatState {
675 room_id,
676 room: self.room.clone(),
677
678 tbox,
679 sent: self.sent.clone(),
680 sent_scrollback: history::ScrollbackState::Pending,
681
682 scrollback: self.scrollback.dup(store),
683 focus: self.focus,
684
685 reply_to: None,
686 editing: None,
687 }
688 }
689
690 fn close(&mut self, _: CloseFlags, _: &mut ProgramStore) -> bool {
691 // XXX: what's the right closing behaviour for a room?
692 // Should write send a message?
693 true
694 }
695
696 fn write(
697 &mut self,
698 _: Option<&str>,
699 _: WriteFlags,
700 _: &mut ProgramStore,
701 ) -> IambResult<EditInfo> {
702 // XXX: what's the right writing behaviour for a room?
703 // Should write send a message?
704 Ok(None)
705 }
706
707 fn get_completions(&self) -> Option<CompletionList> {
708 delegate!(self, w => w.get_completions())
709 }
710
711 fn get_cursor_word(&self, style: &WordStyle) -> Option<String> {
712 delegate!(self, w => w.get_cursor_word(style))
713 }
714
715 fn get_selected_word(&self) -> Option<String> {
716 delegate!(self, w => w.get_selected_word())
717 }
718}
719
720impl Editable<ProgramContext, ProgramStore, IambInfo> for ChatState {
721 fn editor_command(
722 &mut self,
723 act: &EditorAction,
724 ctx: &ProgramContext,
725 store: &mut ProgramStore,
726 ) -> EditResult<EditInfo, IambInfo> {
727 self.typing_notice(act, ctx, store);
728
729 match delegate!(self, w => w.editor_command(act, ctx, store)) {
730 res @ Ok(_) => res,
731 Err(EditError::WrongBuffer(IambBufferId::Room(room_id, thread, focus)))
732 if room_id == self.room_id &&
733 thread.as_ref() == self.thread() &&
734 act.is_switchable(ctx) =>
735 {
736 // Switch focus.
737 self.focus = focus;
738
739 // Run command again.
740 delegate!(self, w => w.editor_command(act, ctx, store))
741 },
742 Err(EditError::Register(RegisterError::ClipboardImage(data))) => {
743 let msg = "Do you really want to upload the image from your system clipboard?";
744 let send =
745 IambAction::Send(SendAction::UploadImage(data.width, data.height, data.bytes));
746 let prompt = PromptYesNo::new(msg, vec![Action::from(send)]);
747 let prompt = Box::new(prompt);
748
749 Err(EditError::NeedConfirm(prompt))
750 },
751 res @ Err(_) => res,
752 }
753 }
754}
755
756impl TerminalCursor for ChatState {
757 fn get_term_cursor(&self) -> Option<(u16, u16)> {
758 delegate!(self, w => w.get_term_cursor())
759 }
760}
761
762impl Jumpable<ProgramContext, IambInfo> for ChatState {
763 fn jump(
764 &mut self,
765 list: PositionList,
766 dir: MoveDir1D,
767 count: usize,
768 ctx: &ProgramContext,
769 ) -> IambResult<usize> {
770 delegate!(self, w => w.jump(list, dir, count, ctx))
771 }
772}
773
774impl Scrollable<ProgramContext, ProgramStore, IambInfo> for ChatState {
775 fn scroll(
776 &mut self,
777 style: &ScrollStyle,
778 ctx: &ProgramContext,
779 store: &mut ProgramStore,
780 ) -> EditResult<EditInfo, IambInfo> {
781 // Send all scroll commands to the scrollback.
782 //
783 // If there's enough message text for scrolling to be necessary,
784 // navigating with movement keys should be enough to do the job.
785 self.scrollback.scroll(style, ctx, store)
786 }
787}
788
789impl PromptActions<ProgramContext, ProgramStore, IambInfo> for ChatState {
790 fn submit(
791 &mut self,
792 ctx: &ProgramContext,
793 _: &mut ProgramStore,
794 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
795 let act = SendAction::Submit;
796
797 Ok(vec![(IambAction::from(act).into(), ctx.clone())])
798 }
799
800 fn abort(
801 &mut self,
802 empty: bool,
803 _: &ProgramContext,
804 _: &mut ProgramStore,
805 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
806 let text = self.tbox.get();
807
808 if empty && text.is_blank() {
809 return Ok(vec![]);
810 }
811
812 let text = self.reset().trim();
813
814 if text.is_empty() {
815 let _ = self.sent.end();
816 } else {
817 self.sent.select(text);
818 }
819
820 return Ok(vec![]);
821 }
822
823 fn recall(
824 &mut self,
825 dir: &MoveDir1D,
826 count: &Count,
827 prefixed: bool,
828 ctx: &ProgramContext,
829 _: &mut ProgramStore,
830 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
831 let count = ctx.resolve(count);
832 let rope = self.tbox.get();
833
834 let text = self.sent.recall(&rope, &mut self.sent_scrollback, *dir, prefixed, count);
835
836 if let Some(text) = text {
837 self.tbox.set_text(text);
838 }
839
840 Ok(vec![])
841 }
842}
843
844impl Promptable<ProgramContext, ProgramStore, IambInfo> for ChatState {
845 fn prompt(
846 &mut self,
847 act: &PromptAction,
848 ctx: &ProgramContext,
849 store: &mut ProgramStore,
850 ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
851 if let RoomFocus::Scrollback = self.focus {
852 return self.scrollback.prompt(act, ctx, store);
853 }
854
855 match act {
856 PromptAction::Submit => self.submit(ctx, store),
857 PromptAction::Abort(empty) => self.abort(*empty, ctx, store),
858 PromptAction::Recall(dir, count, prefixed) => {
859 self.recall(dir, count, *prefixed, ctx, store)
860 },
861 }
862 }
863}
864
865/// [StatefulWidget] for Matrix rooms.
866pub struct Chat<'a> {
867 store: &'a mut ProgramStore,
868 focused: bool,
869}
870
871impl<'a> Chat<'a> {
872 pub fn new(store: &'a mut ProgramStore) -> Chat<'a> {
873 Chat { store, focused: false }
874 }
875
876 pub fn focus(mut self, focused: bool) -> Self {
877 self.focused = focused;
878 self
879 }
880}
881
882impl<'a> StatefulWidget for Chat<'a> {
883 type State = ChatState;
884
885 fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
886 // Determine whether we have a description to show for the message bar.
887 let desc_spans = match (&state.editing, &state.reply_to) {
888 (None, None) => None,
889 (Some(_), None) => Some(Line::from("Editing message")),
890 (editing, Some(_)) => {
891 state.reply_to.as_ref().and_then(|k| {
892 let room = self.store.application.rooms.get(state.id())?;
893 let msg = room.messages.get(k)?;
894 let user =
895 self.store.application.settings.get_user_span(msg.sender.as_ref(), room);
896 let prefix = if editing.is_some() {
897 Span::from("Editing reply to ")
898 } else {
899 Span::from("Replying to ")
900 };
901 let spans = Line::from(vec![prefix, user]);
902
903 spans.into()
904 })
905 },
906 };
907
908 // Determine the region to show each UI element.
909 let lines = state.tbox.has_lines(5).max(1) as u16;
910 let drawh = area.height;
911 let texth = lines.min(drawh).clamp(1, 5);
912 let desch = if desc_spans.is_some() {
913 drawh.saturating_sub(texth).min(1)
914 } else {
915 0
916 };
917 let scrollh = drawh.saturating_sub(texth).saturating_sub(desch);
918
919 let scrollarea = Rect::new(area.x, area.y, area.width, scrollh);
920 let descarea = Rect::new(area.x, scrollarea.y + scrollh, area.width, desch);
921 let textarea = Rect::new(area.x, descarea.y + desch, area.width, texth);
922
923 // Render the message bar and any description for it.
924 if let Some(desc_spans) = desc_spans {
925 Paragraph::new(desc_spans).render(descarea, buf);
926 }
927
928 let prompt = if self.focused { "> " } else { " " };
929
930 let tbox = TextBox::new().prompt(prompt);
931 tbox.render(textarea, buf, &mut state.tbox);
932
933 // Render the message scrollback.
934 let scrollback_focused = state.focus.is_scrollback() && self.focused;
935 let scrollback = Scrollback::new(self.store)
936 .focus(scrollback_focused)
937 .room_focus(self.focused);
938 scrollback.render(scrollarea, buf, &mut state.scrollback);
939 }
940}
941
942fn open_command(open_command: Option<&Vec<String>>, target: OsString) -> IambResult<()> {
943 if let Some(mut cmd) = open_command.and_then(cmd) {
944 cmd.arg(target);
945 cmd.spawn()?;
946 return Ok(());
947 } else {
948 // open::that may not return until the spawned program closes.
949 tokio::task::spawn_blocking(move || {
950 return open::that(target);
951 });
952 return Ok(());
953 }
954}
955
956fn cmd(open_command: &Vec<String>) -> Option<Command> {
957 if let [program, args @ ..] = open_command.as_slice() {
958 let mut cmd = Command::new(program);
959 cmd.args(args);
960 return Some(cmd);
961 }
962 None
963}