src/windows/room/chat.rs

1162 lines · 41754 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_with_builder as external_edit;
   9use edit::Builder;
  10use modalkit::editing::store::RegisterError;
  11use std::process::Command;
  12use tokio;
  13use url::Url;
  14
  15use matrix_sdk::{
  16    attachment::AttachmentConfig,
  17    media::{MediaFormat, MediaRequestParameters},
  18    room::Room as MatrixRoom,
  19    ruma::{
  20        events::reaction::ReactionEventContent,
  21        events::relation::{Annotation, Replacement},
  22        events::room::message::{
  23            AddMentions,
  24            ForwardThread,
  25            MessageType,
  26            OriginalRoomMessageEvent,
  27            Relation,
  28            ReplyWithinThread,
  29            RoomMessageEventContent,
  30            TextMessageEventContent,
  31        },
  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    IambAction,
  76    IambBufferId,
  77    IambError,
  78    IambInfo,
  79    IambResult,
  80    MessageAction,
  81    ProgramAction,
  82    ProgramContext,
  83    ProgramStore,
  84    RoomFocus,
  85    RoomInfo,
  86    SendAction,
  87};
  88
  89use crate::message::{text_to_message, Message, MessageEvent, MessageKey, MessageTimeStamp};
  90use crate::worker::Requester;
  91
  92use super::scrollback::{Scrollback, ScrollbackState};
  93
  94/// State needed for rendering [Chat].
  95pub struct ChatState {
  96    room_id: OwnedRoomId,
  97    room: MatrixRoom,
  98
  99    tbox: TextBoxState<IambInfo>,
 100    sent: HistoryList<EditRope>,
 101    sent_scrollback: history::ScrollbackState,
 102
 103    scrollback: ScrollbackState,
 104    focus: RoomFocus,
 105
 106    reply_to: Option<MessageKey>,
 107    editing: Option<MessageKey>,
 108}
 109
 110impl ChatState {
 111    pub fn new(room: MatrixRoom, thread: Option<OwnedEventId>, store: &mut ProgramStore) -> Self {
 112        let room_id = room.room_id().to_owned();
 113        let scrollback = ScrollbackState::new(room_id.clone(), thread.clone());
 114        let id = IambBufferId::Room(room_id.clone(), thread, RoomFocus::MessageBar);
 115        let ebuf = store.load_buffer(id);
 116        let tbox = TextBoxState::new(ebuf);
 117
 118        ChatState {
 119            room_id,
 120            room,
 121
 122            tbox,
 123            sent: HistoryList::new(EditRope::from(""), 100),
 124            sent_scrollback: history::ScrollbackState::Pending,
 125
 126            scrollback,
 127            focus: RoomFocus::MessageBar,
 128
 129            reply_to: None,
 130            editing: None,
 131        }
 132    }
 133
 134    pub fn thread(&self) -> Option<&OwnedEventId> {
 135        self.scrollback.thread()
 136    }
 137
 138    fn get_joined(&self, worker: &Requester) -> Result<MatrixRoom, IambError> {
 139        let Some(room) = worker.client.get_room(self.id()) else {
 140            return Err(IambError::NotJoined);
 141        };
 142
 143        if room.state() == RoomState::Joined {
 144            Ok(room)
 145        } else {
 146            Err(IambError::NotJoined)
 147        }
 148    }
 149
 150    fn get_reply_to<'a>(&self, info: &'a RoomInfo) -> Option<&'a OriginalRoomMessageEvent> {
 151        let thread = self.scrollback.get_thread(info)?;
 152        let key = self.reply_to.as_ref()?;
 153        let msg = thread.get(key)?;
 154
 155        if let MessageEvent::Original(ev) = &msg.event {
 156            Some(ev)
 157        } else {
 158            None
 159        }
 160    }
 161
 162    fn reset(&mut self) -> EditRope {
 163        self.reply_to = None;
 164        self.editing = None;
 165        self.tbox.reset()
 166    }
 167
 168    pub fn refresh_room(&mut self, store: &mut ProgramStore) {
 169        if let Some(room) = store.application.worker.client.get_room(self.id()) {
 170            self.room = room;
 171        }
 172    }
 173
 174    pub async fn message_command(
 175        &mut self,
 176        act: MessageAction,
 177        _: ProgramContext,
 178        store: &mut ProgramStore,
 179    ) -> IambResult<EditInfo> {
 180        let client = &store.application.worker.client;
 181
 182        let settings = &store.application.settings;
 183        let info = store.application.rooms.get_or_default(self.room_id.clone());
 184
 185        let msg = self.scrollback.get_mut(info).ok_or(IambError::NoSelectedMessage)?;
 186
 187        match act {
 188            MessageAction::Cancel(skip_confirm) => {
 189                if skip_confirm {
 190                    self.reset();
 191
 192                    return Ok(None);
 193                }
 194
 195                self.reply_to = None;
 196                self.editing = None;
 197
 198                let msg = "Would you like to clear the message bar?";
 199                let act = PromptAction::Abort(false);
 200                let prompt = PromptYesNo::new(msg, vec![Action::from(act)]);
 201                let prompt = Box::new(prompt);
 202
 203                Err(UIError::NeedConfirm(prompt))
 204            },
 205            MessageAction::Download(filename, flags) => {
 206                if let MessageEvent::Original(ev) = &msg.event {
 207                    let media = client.media();
 208
 209                    let mut filename = match (filename, &settings.dirs.downloads) {
 210                        (Some(f), _) => PathBuf::from(f),
 211                        (None, Some(downloads)) => downloads.clone(),
 212                        (None, None) => return Err(IambError::NoDownloadDir.into()),
 213                    };
 214
 215                    let (source, msg_filename) = match &ev.content.msgtype {
 216                        MessageType::Audio(c) => (c.source.clone(), c.body.as_str()),
 217                        MessageType::File(c) => {
 218                            (c.source.clone(), c.filename.as_deref().unwrap_or(c.body.as_str()))
 219                        },
 220                        MessageType::Image(c) => (c.source.clone(), c.body.as_str()),
 221                        MessageType::Video(c) => (c.source.clone(), c.body.as_str()),
 222                        _ => {
 223                            if !flags.contains(DownloadFlags::OPEN) {
 224                                return Err(IambError::NoAttachment.into());
 225                            }
 226
 227                            let links = if let Some(html) = &msg.html {
 228                                html.get_links()
 229                            } else if let Ok(url) = Url::parse(&msg.event.body()) {
 230                                vec![('0', url)]
 231                            } else {
 232                                vec![]
 233                            };
 234
 235                            if links.is_empty() {
 236                                return Err(IambError::NoAttachment.into());
 237                            }
 238
 239                            let choices = links
 240                                .into_iter()
 241                                .map(|l| {
 242                                    let url = l.1.to_string();
 243                                    let act = IambAction::OpenLink(url.clone()).into();
 244                                    MultiChoiceItem::new(l.0, url, vec![act])
 245                                })
 246                                .collect();
 247                            let dialog = MultiChoice::new(choices);
 248                            let err = UIError::NeedConfirm(Box::new(dialog));
 249
 250                            return Err(err);
 251                        },
 252                    };
 253
 254                    if filename.is_dir() {
 255                        filename.push(msg_filename);
 256                    }
 257
 258                    if filename.exists() && !flags.contains(DownloadFlags::FORCE) {
 259                        // Find an incrementally suffixed filename, e.g. image-2.jpg -> image-3.jpg
 260                        if let Some(stem) = filename.file_stem().and_then(OsStr::to_str) {
 261                            let ext = filename.extension();
 262                            let mut filename_incr = filename.clone();
 263                            for n in 1..=1000 {
 264                                if let Some(ext) = ext.and_then(OsStr::to_str) {
 265                                    filename_incr.set_file_name(format!("{}-{}.{}", stem, n, ext));
 266                                } else {
 267                                    filename_incr.set_file_name(format!("{}-{}", stem, n));
 268                                }
 269
 270                                if !filename_incr.exists() {
 271                                    filename = filename_incr;
 272                                    break;
 273                                }
 274                            }
 275                        }
 276                    }
 277
 278                    if !filename.exists() || flags.contains(DownloadFlags::FORCE) {
 279                        let req = MediaRequestParameters { source, format: MediaFormat::File };
 280
 281                        let bytes =
 282                            media.get_media_content(&req, true).await.map_err(IambError::from)?;
 283
 284                        fs::write(filename.as_path(), bytes.as_slice())?;
 285
 286                        msg.downloaded = true;
 287                    } else if !flags.contains(DownloadFlags::OPEN) {
 288                        let msg = format!(
 289                            "The file {} already exists; add ! to end of command to overwrite it.",
 290                            filename.display()
 291                        );
 292                        let err = UIError::Failure(msg);
 293
 294                        return Err(err);
 295                    }
 296
 297                    let info = if flags.contains(DownloadFlags::OPEN) {
 298                        let target = filename.clone().into_os_string();
 299                        match open_command(
 300                            store.application.settings.tunables.open_command.as_ref(),
 301                            target,
 302                        ) {
 303                            Ok(_) => {
 304                                InfoMessage::from(format!(
 305                                    "Attachment downloaded to {} and opened",
 306                                    filename.display()
 307                                ))
 308                            },
 309                            Err(err) => {
 310                                return Err(err);
 311                            },
 312                        }
 313                    } else {
 314                        InfoMessage::from(format!(
 315                            "Attachment downloaded to {}",
 316                            filename.display()
 317                        ))
 318                    };
 319
 320                    return Ok(info.into());
 321                }
 322
 323                Err(IambError::NoAttachment.into())
 324            },
 325            MessageAction::Edit => {
 326                if msg.sender != settings.profile.user_id {
 327                    let msg = "Cannot edit messages sent by someone else";
 328                    let err = UIError::Failure(msg.into());
 329
 330                    return Err(err);
 331                }
 332
 333                let ev = match &msg.event {
 334                    MessageEvent::Original(ev) => &ev.content,
 335                    MessageEvent::Local(_, ev) => ev.deref(),
 336                    _ => {
 337                        let msg = "Cannot edit a redacted message";
 338                        let err = UIError::Failure(msg.into());
 339
 340                        return Err(err);
 341                    },
 342                };
 343
 344                let text = match &ev.msgtype {
 345                    MessageType::Text(msg) => msg.body.as_str(),
 346                    _ => {
 347                        let msg = "Cannot edit a non-text message";
 348                        let err = UIError::Failure(msg.into());
 349
 350                        return Err(err);
 351                    },
 352                };
 353
 354                self.tbox.set_text(text);
 355                self.reply_to = msg.reply_to().and_then(|id| info.get_message_key(&id)).cloned();
 356                self.editing = self.scrollback.get_key(info);
 357                self.focus = RoomFocus::MessageBar;
 358
 359                Ok(None)
 360            },
 361            MessageAction::React(reaction, literal) => {
 362                let emoji = if literal {
 363                    reaction
 364                } else if let Some(emoji) =
 365                    emojis::get(&reaction).or_else(|| emojis::get_by_shortcode(&reaction))
 366                {
 367                    emoji.to_string()
 368                } else {
 369                    let msg = format!("{reaction:?} is not a known Emoji shortcode; do you want to react with exactly {reaction:?}?");
 370                    let act = IambAction::Message(MessageAction::React(reaction, true));
 371                    let prompt = PromptYesNo::new(msg, vec![Action::from(act)]);
 372                    let prompt = Box::new(prompt);
 373
 374                    return Err(UIError::NeedConfirm(prompt));
 375                };
 376
 377                let room = self.get_joined(&store.application.worker)?;
 378                let event_id = match &msg.event {
 379                    MessageEvent::EncryptedOriginal(ev) => ev.event_id.clone(),
 380                    MessageEvent::EncryptedRedacted(ev) => ev.event_id.clone(),
 381                    MessageEvent::Original(ev) => ev.event_id.clone(),
 382                    MessageEvent::Local(event_id, _) => event_id.clone(),
 383                    MessageEvent::State(ev) => ev.event_id().to_owned(),
 384                    MessageEvent::Redacted(_) => {
 385                        let msg = "Cannot react to a redacted message";
 386                        let err = UIError::Failure(msg.into());
 387
 388                        return Err(err);
 389                    },
 390                };
 391
 392                if info.user_reactions_contains(&settings.profile.user_id, &event_id, &emoji) {
 393                    let msg = format!("You’ve already reacted to this message with {}", emoji);
 394                    let err = UIError::Failure(msg);
 395
 396                    return Err(err);
 397                }
 398
 399                let reaction = Annotation::new(event_id, emoji);
 400                let msg = ReactionEventContent::new(reaction);
 401                let _ = room.send(msg).await.map_err(IambError::from)?;
 402
 403                Ok(None)
 404            },
 405            MessageAction::Redact(reason, skip_confirm) => {
 406                if !skip_confirm {
 407                    let msg = "Are you sure you want to redact this message?";
 408                    let act = IambAction::Message(MessageAction::Redact(reason, true));
 409                    let prompt = PromptYesNo::new(msg, vec![Action::from(act)]);
 410                    let prompt = Box::new(prompt);
 411
 412                    return Err(UIError::NeedConfirm(prompt));
 413                }
 414
 415                let room = self.get_joined(&store.application.worker)?;
 416                let event_id = match &msg.event {
 417                    MessageEvent::EncryptedOriginal(ev) => ev.event_id.clone(),
 418                    MessageEvent::EncryptedRedacted(ev) => ev.event_id.clone(),
 419                    MessageEvent::Original(ev) => ev.event_id.clone(),
 420                    MessageEvent::Local(event_id, _) => event_id.clone(),
 421                    MessageEvent::State(ev) => ev.event_id().to_owned(),
 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(reaction, literal) => {
 443                let emoji = match reaction {
 444                    reaction if literal => reaction,
 445                    Some(reaction) => {
 446                        if let Some(emoji) =
 447                            emojis::get(&reaction).or_else(|| emojis::get_by_shortcode(&reaction))
 448                        {
 449                            Some(emoji.to_string())
 450                        } else {
 451                            let msg = format!("{reaction:?} is not a known Emoji shortcode; do you want to remove exactly {reaction:?}?");
 452                            let act =
 453                                IambAction::Message(MessageAction::Unreact(Some(reaction), true));
 454                            let prompt = PromptYesNo::new(msg, vec![Action::from(act)]);
 455                            let prompt = Box::new(prompt);
 456
 457                            return Err(UIError::NeedConfirm(prompt));
 458                        }
 459                    },
 460                    None => None,
 461                };
 462
 463                let room = self.get_joined(&store.application.worker)?;
 464                let event_id = match &msg.event {
 465                    MessageEvent::EncryptedOriginal(ev) => ev.event_id.clone(),
 466                    MessageEvent::EncryptedRedacted(ev) => ev.event_id.clone(),
 467                    MessageEvent::Original(ev) => ev.event_id.clone(),
 468                    MessageEvent::Local(event_id, _) => event_id.clone(),
 469                    MessageEvent::State(ev) => ev.event_id().to_owned(),
 470                    MessageEvent::Redacted(_) => {
 471                        let msg = "Cannot unreact to a redacted message";
 472                        let err = UIError::Failure(msg.into());
 473
 474                        return Err(err);
 475                    },
 476                };
 477
 478                let reactions = match info.reactions.get(&event_id) {
 479                    Some(r) => r,
 480                    None => return Ok(None),
 481                };
 482
 483                let reactions = reactions.iter().filter_map(|(event_id, (reaction, user_id))| {
 484                    if user_id != &settings.profile.user_id {
 485                        return None;
 486                    }
 487
 488                    if let Some(emoji) = &emoji {
 489                        if emoji == reaction {
 490                            return Some(event_id);
 491                        } else {
 492                            return None;
 493                        }
 494                    } else {
 495                        return Some(event_id);
 496                    }
 497                });
 498
 499                for reaction in reactions {
 500                    let _ = room.redact(reaction, None, None).await.map_err(IambError::from)?;
 501                }
 502
 503                Ok(None)
 504            },
 505        }
 506    }
 507
 508    pub async fn send_command(
 509        &mut self,
 510        act: SendAction,
 511        _: ProgramContext,
 512        store: &mut ProgramStore,
 513    ) -> IambResult<EditInfo> {
 514        let room = self.get_joined(&store.application.worker)?;
 515        let info = store.application.rooms.get_or_default(self.id().to_owned());
 516        let mut show_echo = true;
 517
 518        let (event_id, msg) = match act {
 519            SendAction::Submit | SendAction::SubmitFromEditor => {
 520                let msg = self.tbox.get();
 521
 522                let msg = if let SendAction::SubmitFromEditor = act {
 523                    let suffix =
 524                        store.application.settings.tunables.external_edit_file_suffix.as_str();
 525                    let edited_msg =
 526                        external_edit(msg.trim_end().to_string(), Builder::new().suffix(suffix))?
 527                            .trim_end()
 528                            .to_string();
 529                    if edited_msg.is_empty() {
 530                        return Ok(None);
 531                    }
 532                    edited_msg
 533                } else if msg.is_blank() {
 534                    return Ok(None);
 535                } else {
 536                    msg.trim_end().to_string()
 537                };
 538
 539                let mut msg = text_to_message(msg);
 540
 541                if let Some((_, event_id)) = &self.editing {
 542                    msg.relates_to = Some(Relation::Replacement(Replacement::new(
 543                        event_id.clone(),
 544                        msg.msgtype.clone().into(),
 545                    )));
 546
 547                    show_echo = false;
 548                } else if let Some(thread_root) = self.scrollback.thread() {
 549                    if let Some(m) = self.get_reply_to(info) {
 550                        msg = msg.make_for_thread(m, ReplyWithinThread::Yes, AddMentions::No);
 551                    } else if let Some(m) = info.get_thread_last(thread_root) {
 552                        msg = msg.make_for_thread(m, ReplyWithinThread::No, AddMentions::No);
 553                    } else {
 554                        // Internal state is wonky?
 555                    }
 556                } else if let Some(m) = self.get_reply_to(info) {
 557                    msg = msg.make_reply_to(m, ForwardThread::Yes, AddMentions::No);
 558                }
 559
 560                // XXX: second parameter can be a locally unique transaction id.
 561                // Useful for doing retries.
 562                let resp = room.send(msg.clone()).await.map_err(IambError::from)?;
 563                let event_id = resp.event_id;
 564
 565                // Reset message bar state now that it's been sent.
 566                self.reset();
 567
 568                (event_id, msg)
 569            },
 570            SendAction::Upload(file) => {
 571                let path = Path::new(file.as_str());
 572                let mime = mime_guess::from_path(path).first_or(mime::APPLICATION_OCTET_STREAM);
 573
 574                let bytes = fs::read(path)?;
 575                let name = path
 576                    .file_name()
 577                    .map(OsStr::to_string_lossy)
 578                    .unwrap_or_else(|| Cow::from("Attachment"));
 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            SendAction::UploadImage(width, height, bytes) => {
 594                // Convert to png because arboard does not give us the mime type.
 595                let bytes =
 596                    image::ImageBuffer::from_raw(width as _, height as _, bytes.into_owned())
 597                        .ok_or(IambError::Clipboard)
 598                        .and_then(|imagebuf| {
 599                            let dynimage = image::DynamicImage::ImageRgba8(imagebuf);
 600                            let bytes = Vec::<u8>::new();
 601                            let mut buff = std::io::Cursor::new(bytes);
 602                            dynimage.write_to(&mut buff, image::ImageFormat::Png)?;
 603                            Ok(buff.into_inner())
 604                        })
 605                        .map_err(IambError::from)?;
 606                let mime = mime::IMAGE_PNG;
 607
 608                let name = "Clipboard.png";
 609                let config = AttachmentConfig::new();
 610
 611                let resp = room
 612                    .send_attachment(name, &mime, bytes, config)
 613                    .await
 614                    .map_err(IambError::from)?;
 615
 616                // Mock up the local echo message for the scrollback.
 617                let msg = TextMessageEventContent::plain(format!("[Attached File: {name}]"));
 618                let msg = MessageType::Text(msg);
 619                let msg = RoomMessageEventContent::new(msg);
 620
 621                (resp.event_id, msg)
 622            },
 623        };
 624
 625        if show_echo {
 626            let user = store.application.settings.profile.user_id.clone();
 627            let key = (MessageTimeStamp::LocalEcho, event_id.clone());
 628            let msg = MessageEvent::Local(event_id, msg.into());
 629            let msg = Message::new(msg, user, MessageTimeStamp::LocalEcho);
 630            let thread = self.scrollback.get_thread_mut(info);
 631            thread.insert(key, msg);
 632        }
 633
 634        // Jump to the end of the scrollback to show the message.
 635        self.scrollback.goto_latest();
 636
 637        Ok(None)
 638    }
 639
 640    pub fn focus_toggle(&mut self) {
 641        self.focus.toggle();
 642    }
 643
 644    pub fn room(&self) -> &MatrixRoom {
 645        &self.room
 646    }
 647
 648    pub fn id(&self) -> &RoomId {
 649        &self.room_id
 650    }
 651
 652    pub fn auto_toggle_focus(
 653        &mut self,
 654        act: &EditorAction,
 655        ctx: &ProgramContext,
 656    ) -> Option<EditorAction> {
 657        auto_toggle_focus(&mut self.focus, act, ctx, &self.scrollback, &mut self.tbox)
 658    }
 659
 660    pub fn typing_notice(
 661        &self,
 662        act: &EditorAction,
 663        ctx: &ProgramContext,
 664        store: &mut ProgramStore,
 665    ) {
 666        if !self.focus.is_msgbar() || act.is_readonly(ctx) {
 667            return;
 668        }
 669
 670        if !store.application.settings.tunables.typing_notice_send {
 671            return;
 672        }
 673
 674        store.application.worker.typing_notice(self.room_id.clone());
 675    }
 676}
 677
 678macro_rules! delegate {
 679    ($s: expr, $id: ident => $e: expr) => {
 680        match $s.focus {
 681            RoomFocus::Scrollback => {
 682                match $s {
 683                    ChatState { scrollback: $id, .. } => $e,
 684                }
 685            },
 686            RoomFocus::MessageBar => {
 687                match $s {
 688                    ChatState { tbox: $id, .. } => $e,
 689                }
 690            },
 691        }
 692    };
 693}
 694
 695impl WindowOps<IambInfo> for ChatState {
 696    fn draw(&mut self, area: Rect, buf: &mut Buffer, focused: bool, store: &mut ProgramStore) {
 697        Chat::new(store).focus(focused).render(area, buf, self)
 698    }
 699
 700    fn dup(&self, store: &mut ProgramStore) -> Self {
 701        // XXX: I want each WindowSlot to have its own shared buffer, instead of each Room; need to
 702        // find a good way to pass that info here so that it can be part of the content id.
 703        let room_id = self.room_id.clone();
 704        let thread = self.thread().cloned();
 705        let id = IambBufferId::Room(room_id.clone(), thread, RoomFocus::MessageBar);
 706        let ebuf = store.load_buffer(id);
 707        let tbox = TextBoxState::new(ebuf);
 708
 709        ChatState {
 710            room_id,
 711            room: self.room.clone(),
 712
 713            tbox,
 714            sent: self.sent.clone(),
 715            sent_scrollback: history::ScrollbackState::Pending,
 716
 717            scrollback: self.scrollback.dup(store),
 718            focus: self.focus,
 719
 720            reply_to: None,
 721            editing: None,
 722        }
 723    }
 724
 725    fn close(&mut self, _: CloseFlags, _: &mut ProgramStore) -> bool {
 726        // XXX: what's the right closing behaviour for a room?
 727        // Should write send a message?
 728        true
 729    }
 730
 731    fn write(
 732        &mut self,
 733        _: Option<&str>,
 734        _: WriteFlags,
 735        _: &mut ProgramStore,
 736    ) -> IambResult<EditInfo> {
 737        // XXX: what's the right writing behaviour for a room?
 738        // Should write send a message?
 739        Ok(None)
 740    }
 741
 742    fn get_completions(&self) -> Option<CompletionList> {
 743        delegate!(self, w => w.get_completions())
 744    }
 745
 746    fn get_cursor_word(&self, style: &WordStyle) -> Option<String> {
 747        delegate!(self, w => w.get_cursor_word(style))
 748    }
 749
 750    fn get_selected_word(&self) -> Option<String> {
 751        delegate!(self, w => w.get_selected_word())
 752    }
 753}
 754
 755impl Editable<ProgramContext, ProgramStore, IambInfo> for ChatState {
 756    fn editor_command(
 757        &mut self,
 758        act: &EditorAction,
 759        ctx: &ProgramContext,
 760        store: &mut ProgramStore,
 761    ) -> EditResult<EditInfo, IambInfo> {
 762        // Check whether we should automatically switch between the message bar
 763        // or message scrollback, and use an adjusted action if we do so.
 764        let adjusted = self.auto_toggle_focus(act, ctx);
 765        let act = adjusted.as_ref().unwrap_or(act);
 766
 767        // Send typing notice if needed.
 768        self.typing_notice(act, ctx, store);
 769
 770        // And now we can finally run the editor command.
 771        match delegate!(self, w => w.editor_command(act, ctx, store)) {
 772            res @ Ok(_) => res,
 773            Err(EditError::WrongBuffer(IambBufferId::Room(room_id, thread, focus)))
 774                if room_id == self.room_id &&
 775                    thread.as_ref() == self.thread() &&
 776                    act.is_switchable(ctx) =>
 777            {
 778                // Switch focus.
 779                self.focus = focus;
 780
 781                // Run command again.
 782                delegate!(self, w => w.editor_command(act, ctx, store))
 783            },
 784            Err(EditError::Register(RegisterError::ClipboardImage(data))) => {
 785                let msg = "Do you really want to upload the image from your system clipboard?";
 786                let send =
 787                    IambAction::Send(SendAction::UploadImage(data.width, data.height, data.bytes));
 788                let prompt = PromptYesNo::new(msg, vec![Action::from(send)]);
 789                let prompt = Box::new(prompt);
 790
 791                Err(EditError::NeedConfirm(prompt))
 792            },
 793            res @ Err(_) => res,
 794        }
 795    }
 796}
 797
 798impl TerminalCursor for ChatState {
 799    fn get_term_cursor(&self) -> Option<(u16, u16)> {
 800        delegate!(self, w => w.get_term_cursor())
 801    }
 802}
 803
 804impl Jumpable<ProgramContext, IambInfo> for ChatState {
 805    fn jump(
 806        &mut self,
 807        list: PositionList,
 808        dir: MoveDir1D,
 809        count: usize,
 810        ctx: &ProgramContext,
 811    ) -> IambResult<usize> {
 812        delegate!(self, w => w.jump(list, dir, count, ctx))
 813    }
 814}
 815
 816impl Scrollable<ProgramContext, ProgramStore, IambInfo> for ChatState {
 817    fn scroll(
 818        &mut self,
 819        style: &ScrollStyle,
 820        ctx: &ProgramContext,
 821        store: &mut ProgramStore,
 822    ) -> EditResult<EditInfo, IambInfo> {
 823        // Send all scroll commands to the scrollback.
 824        //
 825        // If there's enough message text for scrolling to be necessary,
 826        // navigating with movement keys should be enough to do the job.
 827        self.scrollback.scroll(style, ctx, store)
 828    }
 829}
 830
 831impl PromptActions<ProgramContext, ProgramStore, IambInfo> for ChatState {
 832    fn submit(
 833        &mut self,
 834        ctx: &ProgramContext,
 835        _: &mut ProgramStore,
 836    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
 837        let act = SendAction::Submit;
 838
 839        Ok(vec![(IambAction::from(act).into(), ctx.clone())])
 840    }
 841
 842    fn abort(
 843        &mut self,
 844        empty: bool,
 845        _: &ProgramContext,
 846        _: &mut ProgramStore,
 847    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
 848        let text = self.tbox.get();
 849
 850        if empty && text.is_blank() {
 851            return Ok(vec![]);
 852        }
 853
 854        let text = self.reset().trim();
 855
 856        if text.is_empty() {
 857            let _ = self.sent.end();
 858        } else {
 859            self.sent.select(text);
 860        }
 861
 862        return Ok(vec![]);
 863    }
 864
 865    fn recall(
 866        &mut self,
 867        dir: &MoveDir1D,
 868        count: &Count,
 869        prefixed: bool,
 870        ctx: &ProgramContext,
 871        _: &mut ProgramStore,
 872    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
 873        let count = ctx.resolve(count);
 874        let rope = self.tbox.get();
 875
 876        let text = self.sent.recall(&rope, &mut self.sent_scrollback, *dir, prefixed, count);
 877
 878        if let Some(text) = text {
 879            self.tbox.set_text(text);
 880        }
 881
 882        Ok(vec![])
 883    }
 884}
 885
 886impl Promptable<ProgramContext, ProgramStore, IambInfo> for ChatState {
 887    fn prompt(
 888        &mut self,
 889        act: &PromptAction,
 890        ctx: &ProgramContext,
 891        store: &mut ProgramStore,
 892    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
 893        if let RoomFocus::Scrollback = self.focus {
 894            return self.scrollback.prompt(act, ctx, store);
 895        }
 896
 897        match act {
 898            PromptAction::Submit => self.submit(ctx, store),
 899            PromptAction::Abort(empty) => self.abort(*empty, ctx, store),
 900            PromptAction::Recall(dir, count, prefixed) => {
 901                self.recall(dir, count, *prefixed, ctx, store)
 902            },
 903        }
 904    }
 905}
 906
 907/// [StatefulWidget] for Matrix rooms.
 908pub struct Chat<'a> {
 909    store: &'a mut ProgramStore,
 910    focused: bool,
 911}
 912
 913impl<'a> Chat<'a> {
 914    pub fn new(store: &'a mut ProgramStore) -> Chat<'a> {
 915        Chat { store, focused: false }
 916    }
 917
 918    pub fn focus(mut self, focused: bool) -> Self {
 919        self.focused = focused;
 920        self
 921    }
 922}
 923
 924impl StatefulWidget for Chat<'_> {
 925    type State = ChatState;
 926
 927    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
 928        // Determine whether we have a description to show for the message bar.
 929        let desc_spans = match (&state.editing, &state.reply_to, state.thread()) {
 930            (None, None, None) => None,
 931            (None, None, Some(_)) => Some(Line::from("Replying in thread")),
 932            (Some(_), None, None) => Some(Line::from("Editing message")),
 933            (Some(_), None, Some(_)) => Some(Line::from("Editing message in thread")),
 934            (editing, Some(_), thread) => {
 935                self.store.application.rooms.get(state.id()).and_then(|room| {
 936                    let msg = state.get_reply_to(room)?;
 937                    let user =
 938                        self.store.application.settings.get_user_span(msg.sender.as_ref(), room);
 939                    let prefix = match (editing.is_some(), thread.is_some()) {
 940                        (true, false) => Span::from("Editing reply to "),
 941                        (true, true) => Span::from("Editing reply in thread to "),
 942                        (false, false) => Span::from("Replying to "),
 943                        (false, true) => Span::from("Replying in thread to "),
 944                    };
 945                    let spans = Line::from(vec![prefix, user]);
 946
 947                    spans.into()
 948                })
 949            },
 950        };
 951
 952        // Determine the region to show each UI element.
 953        let lines = state.tbox.has_lines(5).max(1) as u16;
 954        let drawh = area.height;
 955        let texth = lines.min(drawh).clamp(1, 5);
 956        let desch = if desc_spans.is_some() {
 957            drawh.saturating_sub(texth).min(1)
 958        } else {
 959            0
 960        };
 961        let scrollh = drawh.saturating_sub(texth).saturating_sub(desch);
 962
 963        let scrollarea = Rect::new(area.x, area.y, area.width, scrollh);
 964        let descarea = Rect::new(area.x, scrollarea.y + scrollh, area.width, desch);
 965        let textarea = Rect::new(area.x, descarea.y + desch, area.width, texth);
 966
 967        // Render the message bar and any description for it.
 968        if let Some(desc_spans) = desc_spans {
 969            Paragraph::new(desc_spans).render(descarea, buf);
 970        }
 971
 972        let prompt = if self.focused { "> " } else { "  " };
 973
 974        let tbox = TextBox::new().prompt(prompt);
 975        tbox.render(textarea, buf, &mut state.tbox);
 976
 977        // Render the message scrollback.
 978        let scrollback_focused = state.focus.is_scrollback() && self.focused;
 979        let scrollback = Scrollback::new(self.store)
 980            .focus(scrollback_focused)
 981            .room_focus(self.focused);
 982        scrollback.render(scrollarea, buf, &mut state.scrollback);
 983    }
 984}
 985
 986fn open_command(open_command: Option<&Vec<String>>, target: OsString) -> IambResult<()> {
 987    if let Some(mut cmd) = open_command.and_then(cmd) {
 988        cmd.arg(target);
 989        cmd.spawn()?;
 990        return Ok(());
 991    } else {
 992        // open::that may not return until the spawned program closes.
 993        tokio::task::spawn_blocking(move || {
 994            return open::that(target);
 995        });
 996        return Ok(());
 997    }
 998}
 999
1000fn cmd(open_command: &Vec<String>) -> Option<Command> {
1001    if let [program, args @ ..] = open_command.as_slice() {
1002        let mut cmd = Command::new(program);
1003        cmd.args(args);
1004        return Some(cmd);
1005    }
1006    None
1007}
1008
1009pub fn auto_toggle_focus(
1010    focus: &mut RoomFocus,
1011    act: &EditorAction,
1012    ctx: &ProgramContext,
1013    scrollback: &ScrollbackState,
1014    tbox: &mut TextBoxState<IambInfo>,
1015) -> Option<EditorAction> {
1016    let is_insert = ctx.get_insert_style().is_some();
1017
1018    match (focus, act) {
1019        (f @ RoomFocus::Scrollback, _) if is_insert => {
1020            // Insert mode commands should switch focus.
1021            f.toggle();
1022            None
1023        },
1024        (f @ RoomFocus::Scrollback, EditorAction::InsertText(_)) => {
1025            // Pasting or otherwise inserting text should switch.
1026            f.toggle();
1027            None
1028        },
1029        (
1030            f @ RoomFocus::Scrollback,
1031            EditorAction::Edit(
1032                op,
1033                EditTarget::Motion(mov @ MoveType::Line(MoveDir1D::Next), count),
1034            ),
1035        ) if ctx.resolve(op).is_motion() => {
1036            let count = ctx.resolve(count);
1037
1038            if count > 0 && scrollback.is_latest() {
1039                // Trying to move down a line when already at the end of room history should
1040                // switch.
1041                f.toggle();
1042
1043                // And decrement the count for the action.
1044                let count = count.saturating_sub(1).into();
1045                let target = EditTarget::Motion(mov.clone(), count);
1046                let dec = EditorAction::Edit(op.clone(), target);
1047
1048                Some(dec)
1049            } else {
1050                None
1051            }
1052        },
1053        (
1054            f @ RoomFocus::MessageBar,
1055            EditorAction::Edit(
1056                op,
1057                EditTarget::Motion(mov @ MoveType::Line(MoveDir1D::Previous), count),
1058            ),
1059        ) if !is_insert && ctx.resolve(op).is_motion() => {
1060            let count = ctx.resolve(count);
1061
1062            if count > 0 && tbox.get_cursor().y == 0 {
1063                // Trying to move up a line when already at the top of the msgbar should
1064                // switch as long as we're not in Insert mode.
1065                f.toggle();
1066
1067                // And decrement the count for the action.
1068                let count = count.saturating_sub(1).into();
1069                let target = EditTarget::Motion(mov.clone(), count);
1070                let dec = EditorAction::Edit(op.clone(), target);
1071
1072                Some(dec)
1073            } else {
1074                None
1075            }
1076        },
1077        (RoomFocus::Scrollback, _) | (RoomFocus::MessageBar, _) => {
1078            // Do not switch.
1079            None
1080        },
1081    }
1082}
1083
1084#[cfg(test)]
1085mod tests {
1086    use super::*;
1087
1088    use modalkit::actions::{EditAction, InsertTextAction};
1089
1090    use crate::tests::{mock_store, TEST_ROOM1_ID};
1091
1092    macro_rules! move_line {
1093        ($dir: expr, $count: expr) => {
1094            EditorAction::Edit(
1095                EditAction::Motion.into(),
1096                EditTarget::Motion(MoveType::Line($dir), $count.into()),
1097            )
1098        };
1099    }
1100
1101    #[tokio::test]
1102    async fn test_auto_focus() {
1103        let mut store = mock_store().await;
1104        let ctx = ProgramContext::default();
1105
1106        let room_id = TEST_ROOM1_ID.clone();
1107        let scrollback = ScrollbackState::new(room_id.clone(), None);
1108
1109        let id = IambBufferId::Room(room_id, None, RoomFocus::MessageBar);
1110        let ebuf = store.load_buffer(id);
1111        let mut tbox = TextBoxState::new(ebuf);
1112
1113        // Start out focused on the scrollback.
1114        let mut focused = RoomFocus::Scrollback;
1115
1116        // Inserting text toggles:
1117        let act = EditorAction::InsertText(InsertTextAction::Type(
1118            Char::from('a').into(),
1119            MoveDir1D::Next,
1120            1.into(),
1121        ));
1122        let res = auto_toggle_focus(&mut focused, &act, &ctx, &scrollback, &mut tbox);
1123        assert_eq!(focused, RoomFocus::MessageBar);
1124        assert!(res.is_none());
1125
1126        // Going down in message bar doesn't toggle:
1127        let act = move_line!(MoveDir1D::Next, 1);
1128        let res = auto_toggle_focus(&mut focused, &act, &ctx, &scrollback, &mut tbox);
1129        assert_eq!(focused, RoomFocus::MessageBar);
1130        assert!(res.is_none());
1131
1132        // But going up will:
1133        let act = move_line!(MoveDir1D::Previous, 1);
1134        let res = auto_toggle_focus(&mut focused, &act, &ctx, &scrollback, &mut tbox);
1135        assert_eq!(focused, RoomFocus::Scrollback);
1136        assert_eq!(res, Some(move_line!(MoveDir1D::Previous, 0)));
1137
1138        // Going up in scrollback doesn't toggle:
1139        let act = move_line!(MoveDir1D::Previous, 1);
1140        let res = auto_toggle_focus(&mut focused, &act, &ctx, &scrollback, &mut tbox);
1141        assert_eq!(focused, RoomFocus::Scrollback);
1142        assert_eq!(res, None);
1143
1144        // And then go back down:
1145        let act = move_line!(MoveDir1D::Next, 1);
1146        let res = auto_toggle_focus(&mut focused, &act, &ctx, &scrollback, &mut tbox);
1147        assert_eq!(focused, RoomFocus::MessageBar);
1148        assert_eq!(res, Some(move_line!(MoveDir1D::Next, 0)));
1149
1150        // Go up 2 will go up 1 in scrollback:
1151        let act = move_line!(MoveDir1D::Previous, 2);
1152        let res = auto_toggle_focus(&mut focused, &act, &ctx, &scrollback, &mut tbox);
1153        assert_eq!(focused, RoomFocus::Scrollback);
1154        assert_eq!(res, Some(move_line!(MoveDir1D::Previous, 1)));
1155
1156        // Go down 3 will go down 2 in messagebar:
1157        let act = move_line!(MoveDir1D::Next, 3);
1158        let res = auto_toggle_focus(&mut focused, &act, &ctx, &scrollback, &mut tbox);
1159        assert_eq!(focused, RoomFocus::MessageBar);
1160        assert_eq!(res, Some(move_line!(MoveDir1D::Next, 2)));
1161    }
1162}