src/windows/room/chat.rs

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