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