src/windows/room/chat.rs

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