src/windows/room/chat.rs

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