src/windows/room/chat.rs

1820 lines · 63639 bytes

67 symbols in this file
   1//! Window for Matrix rooms
   2use std::convert::TryInto;
   3use std::ffi::{OsStr, OsString};
   4use std::fs;
   5use std::process::Command;
   6
   7use edit::Builder;
   8use edit::edit_with_builder as external_edit;
   9use matrix_sdk::RoomState as MatrixRoomState;
  10use matrix_sdk::attachment::AttachmentConfig;
  11use matrix_sdk::attachment::{AttachmentInfo, BaseImageInfo};
  12use matrix_sdk::media::{MediaFormat, MediaRequestParameters};
  13use matrix_sdk::room::reply::{EnforceThread, Reply};
  14use matrix_sdk::ruma::events::Mentions;
  15use matrix_sdk::ruma::events::StateEventType;
  16use matrix_sdk::ruma::events::reaction::ReactionEventContent;
  17use matrix_sdk::ruma::events::relation::Annotation;
  18use matrix_sdk::ruma::events::room::message::{
  19    AddMentions,
  20    ForwardThread,
  21    MessageFormat,
  22    ReplyWithinThread,
  23    TextMessageEventContent,
  24};
  25use matrix_sdk::ruma::events::room::pinned_events::RoomPinnedEventsEventContent;
  26use matrix_sdk::send_queue::RoomSendQueueError;
  27use modalkit::editing::context::EditContext;
  28use modalkit::editing::history::{self, HistoryList};
  29use modalkit::editing::store::RegisterError;
  30use modalkit::keybindings::dialog::{Dialog, MultiChoice, MultiChoiceItem};
  31use modalkit_ratatui::PromptActions;
  32use modalkit_ratatui::textbox::{TextBox, TextBoxState};
  33use ratatui::prelude::Stylize;
  34use regex::Regex;
  35
  36use crate::base::{DownloadFlags, EchoLocation};
  37use crate::config::EncryptionIndicatorLocation;
  38use crate::message::{MessageId, text_to_message, text_to_text_message_event_content};
  39use crate::prelude::*;
  40use crate::util::SuspendedTty;
  41use crate::windows::room::scrollback::{Scrollback, ScrollbackState};
  42
  43/// How long to wait for a message to load before giving up on jumping to it.
  44///
  45/// History loads one page roughly every two seconds, for up to `MESSAGE_NEED_TTL` pages.
  46const PENDING_JUMP_TIMEOUT: Duration = Duration::from_secs(120);
  47
  48/// State needed for rendering [Chat].
  49pub struct ChatState {
  50    room_id: OwnedRoomId,
  51    room: MatrixRoom,
  52
  53    tbox: TextBoxState<IambInfo>,
  54    sent: HistoryList<EditRope>,
  55    sent_scrollback: history::ScrollbackState,
  56
  57    scrollback: ScrollbackState,
  58    focus: RoomFocus,
  59
  60    reply_to: Option<MessageKey>,
  61    editing: Option<MessageKey>,
  62
  63    /// A message to jump to once it has been loaded, and when the jump was requested.
  64    pending_jump: Option<(OwnedEventId, Instant)>,
  65}
  66
  67impl ChatState {
  68    pub fn new(room: MatrixRoom, thread: Option<OwnedEventId>, store: &mut ProgramStore) -> Self {
  69        let room_id = room.room_id().to_owned();
  70        let scrollback = ScrollbackState::new(room_id.clone(), thread.clone());
  71        let id = IambBufferId::Room(room_id.clone(), thread.into(), RoomFocus::MessageBar);
  72        let ebuf = store.load_buffer(id);
  73        let tbox = TextBoxState::new(ebuf);
  74
  75        ChatState {
  76            room_id,
  77            room,
  78
  79            tbox,
  80            sent: HistoryList::new(EditRope::from(""), 100),
  81            sent_scrollback: history::ScrollbackState::Pending,
  82
  83            scrollback,
  84            focus: RoomFocus::MessageBar,
  85
  86            reply_to: None,
  87            editing: None,
  88            pending_jump: None,
  89        }
  90    }
  91
  92    pub fn thread(&self) -> Option<&OwnedEventId> {
  93        self.scrollback.thread()
  94    }
  95
  96    fn get_reply_to<'a>(&self, info: &'a RoomInfo) -> Option<&'a OriginalRoomMessageEvent> {
  97        let thread = self.scrollback.get_thread(info)?;
  98        let key = self.reply_to.as_ref()?;
  99        let msg = thread.get(key)?;
 100
 101        if let MessageEvent::Original(ev, _) = &msg.event {
 102            Some(ev)
 103        } else {
 104            None
 105        }
 106    }
 107
 108    fn reset(&mut self) -> EditRope {
 109        self.reply_to = None;
 110        self.editing = None;
 111        self.tbox.reset()
 112    }
 113
 114    pub fn refresh_room(&mut self, store: &mut ProgramStore) {
 115        if let Some(room) = store.application.worker.client.get_room(self.id()) {
 116            self.room = room;
 117        }
 118    }
 119
 120    /// Where to put the cursor for a loaded message.
 121    ///
 122    /// A thread reply can't be shown in the main timeline, so that lands on its thread root.
 123    fn jump_target(&self, info: &RoomInfo, event_id: &EventId) -> Option<MessageKey> {
 124        let (thread, key) = info.get_message_location(event_id)?;
 125
 126        match thread {
 127            Some(root) if self.thread().is_none() => info.get_message_key(root).cloned(),
 128            _ => Some(key.clone()),
 129        }
 130    }
 131
 132    fn jump_to_message(
 133        &mut self,
 134        event_id: OwnedEventId,
 135        store: &mut ProgramStore,
 136    ) -> IambResult<EditInfo> {
 137        let info = store.application.rooms.get_or_default(self.room_id.clone());
 138
 139        if let Some(key) = self.jump_target(info, &event_id) {
 140            self.pending_jump = None;
 141            self.scrollback.goto_message(key);
 142            self.focus = RoomFocus::Scrollback;
 143
 144            return Ok(None);
 145        }
 146
 147        store
 148            .application
 149            .need_load
 150            .need_message(self.room_id.clone(), event_id.clone());
 151        self.pending_jump = Some((event_id, Instant::now()));
 152
 153        let msg = "Loading message; will jump to it once it arrives";
 154        Ok(Some(InfoMessage::from(msg)))
 155    }
 156
 157    /// Finish a jump that was waiting on its message to load.
 158    fn complete_pending_jump(&mut self, store: &mut ProgramStore) {
 159        let Some((event_id, requested)) = &self.pending_jump else {
 160            return;
 161        };
 162
 163        let info = store.application.rooms.get_or_default(self.room_id.clone());
 164
 165        if let Some(key) = self.jump_target(info, event_id) {
 166            self.pending_jump = None;
 167            self.scrollback.goto_message(key);
 168            self.focus = RoomFocus::Scrollback;
 169        } else if info.reached_timeline_start || requested.elapsed() >= PENDING_JUMP_TIMEOUT {
 170            // The whole history is loaded without it, or it's too far back to find.
 171            self.pending_jump = None;
 172
 173            let msg = "Unable to jump to message: it's too far back in the room's history";
 174            store.application.draw_error = Some(msg.into());
 175        }
 176    }
 177
 178    pub async fn timeline_command(
 179        &mut self,
 180        act: TimelineAction,
 181        _: ProgramContext,
 182        store: &mut ProgramStore,
 183    ) -> IambResult<EditInfo> {
 184        match act {
 185            TimelineAction::GotoEvent(event_id) => self.jump_to_message(event_id, store),
 186        }
 187    }
 188
 189    pub async fn message_command(
 190        &mut self,
 191        act: MessageAction,
 192        ctx: ProgramContext,
 193        store: &mut ProgramStore,
 194    ) -> IambResult<Vec<(Action<IambInfo>, EditContext)>> {
 195        let client = &store.application.worker.client;
 196
 197        let settings = &store.application.settings;
 198        let info = store.application.rooms.get_or_default(self.room_id.clone());
 199
 200        let msg = self.scrollback.get(info).ok_or(IambError::NoSelectedMessage)?;
 201
 202        match act {
 203            MessageAction::Cancel(skip_confirm) => {
 204                if skip_confirm {
 205                    self.reset();
 206
 207                    return Ok(vec![]);
 208                }
 209
 210                self.reply_to = None;
 211                self.editing = None;
 212
 213                let msg = "Would you like to clear the message bar?";
 214                let act = PromptAction::Abort(false);
 215                let prompt = PromptYesNo::new(msg, vec![Action::from(act)]);
 216                let prompt = Box::new(prompt);
 217
 218                Err(UIError::NeedConfirm(prompt))
 219            },
 220            MessageAction::Download(filename, flags) => {
 221                msg_download(
 222                    ctx,
 223                    client,
 224                    msg,
 225                    &store.application.settings,
 226                    filename,
 227                    flags,
 228                    &store.application.settings.tunables,
 229                )
 230                .await
 231            },
 232            MessageAction::Edit => {
 233                if msg.sender != settings.user_id {
 234                    let msg = "Cannot edit messages sent by someone else";
 235                    let err = UIError::Failure(msg.into());
 236
 237                    return Err(err);
 238                }
 239
 240                let Some(msgtype) = msg.event.msgtype() else {
 241                    let msg = "Cannot edit this type of message";
 242                    let err = UIError::Failure(msg.into());
 243
 244                    return Err(err);
 245                };
 246
 247                let text = match msgtype {
 248                    MessageType::Text(msg) => msg.body.as_str(),
 249                    _ => {
 250                        let msg = "Cannot edit a non-text message";
 251                        let err = UIError::Failure(msg.into());
 252
 253                        return Err(err);
 254                    },
 255                };
 256
 257                self.tbox.set_text(text);
 258                self.reply_to = msg.reply_to().and_then(|id| info.get_message_key(&id)).cloned();
 259                self.editing = self.scrollback.get_key(info);
 260                self.focus = RoomFocus::MessageBar;
 261
 262                Ok(vec![])
 263            },
 264            MessageAction::React(reaction, literal) => {
 265                let msg = self.scrollback.get(info).unwrap();
 266                msg_react(
 267                    msg,
 268                    settings,
 269                    info,
 270                    &store.application.worker,
 271                    self.id(),
 272                    reaction,
 273                    literal,
 274                )
 275                .await
 276            },
 277            MessageAction::Pin | MessageAction::Unpin => {
 278                let pin = act == MessageAction::Pin;
 279
 280                msg_pin(pin, msg, self.id(), &store.application.worker, settings).await
 281            },
 282            MessageAction::Redact(reason, skip_confirm) => {
 283                msg_redact(msg, &store.application.worker, self.id(), reason, skip_confirm).await
 284            },
 285            MessageAction::Reply => {
 286                self.reply_to = self.scrollback.get_key(info);
 287                self.focus = RoomFocus::MessageBar;
 288
 289                Ok(vec![])
 290            },
 291            MessageAction::Replied => {
 292                let Some(reply) = msg.reply_to() else {
 293                    let msg = "Selected message is not a reply";
 294                    return Err(UIError::Failure(msg.into()));
 295                };
 296
 297                let msg = self.jump_to_message(reply, store)?;
 298                let msg = msg.map(|msg| (Action::ShowInfoMessage(msg), ctx));
 299
 300                Ok(msg.into_iter().collect())
 301            },
 302            MessageAction::Unreact(reaction, literal) => {
 303                let msg = self.scrollback.get(info).unwrap();
 304                msg_unreact(
 305                    msg,
 306                    settings,
 307                    info,
 308                    &store.application.worker,
 309                    self.id(),
 310                    reaction,
 311                    literal,
 312                )
 313                .await
 314            },
 315        }
 316    }
 317
 318    /// Generate a [`Reply`] setting thread info and reply_to (if `set_reply` is true)
 319    fn generate_reply_info(&self, info: &RoomInfo, set_reply: bool) -> Option<Reply> {
 320        let thread_last = self.scrollback.thread().and_then(|id| info.get_thread_last(id));
 321
 322        let (event_id, enforce_thread) = if let Some(last) = thread_last {
 323            if let Some(m) = self.get_reply_to(info) &&
 324                set_reply
 325            {
 326                // thread reply
 327                (m.event_id.to_owned(), EnforceThread::Threaded(ReplyWithinThread::Yes))
 328            } else {
 329                // thread message
 330                (last.event_id.to_owned(), EnforceThread::Threaded(ReplyWithinThread::No))
 331            }
 332        } else if let Some(m) = self.get_reply_to(info) &&
 333            set_reply
 334        {
 335            // normal reply in main timeline:
 336            (m.event_id.to_owned(), EnforceThread::Unthreaded)
 337        } else {
 338            // not any kind of reply:
 339            return None;
 340        };
 341
 342        Some(Reply {
 343            add_mentions: AddMentions::No,
 344            event_id,
 345            enforce_thread,
 346        })
 347    }
 348
 349    /// Generate an attachment for this room based on the current message bar state.
 350    fn generate_attachment_config(
 351        &self,
 352        info: &RoomInfo,
 353        add_caption: bool,
 354        settings: &ApplicationSettings,
 355    ) -> AttachmentConfig {
 356        let mut config = AttachmentConfig::new();
 357        config.caption = add_caption
 358            .then(|| self.tbox.get())
 359            .filter(|c| !c.is_blank())
 360            .map(|c| c.trim_end().to_string())
 361            .and_then(|c| text_to_text_message_event_content(c, settings.tunables.default_markup));
 362
 363        let mentions = if let Some(content) = &config.caption {
 364            extract_mentions(content)
 365        } else {
 366            Mentions::new()
 367        };
 368        config.mentions = Some(mentions);
 369
 370        config.reply = self.generate_reply_info(info, add_caption);
 371        config
 372    }
 373
 374    pub async fn send_command(
 375        &mut self,
 376        act: SendAction,
 377        _: ProgramContext,
 378        store: &mut ProgramStore,
 379    ) -> IambResult<EditInfo> {
 380        let settings = &store.application.settings;
 381        let tunables = &settings.tunables;
 382        let room = get_joined(self.id(), &store.application.worker)?;
 383        let info = store.application.rooms.get_or_default(self.id().to_owned());
 384
 385        match act {
 386            SendAction::Submit | SendAction::SubmitFromEditor => {
 387                let msg = self.tbox.get();
 388
 389                let msg = if let SendAction::SubmitFromEditor = act {
 390                    let suffix =
 391                        store.application.settings.tunables.external_edit_file_suffix.as_str();
 392                    // Give the terminal back to the editor, and take it again
 393                    // however we leave this block.
 394                    let _tty = SuspendedTty::new(&store.application.settings);
 395                    let edited_msg =
 396                        external_edit(msg.trim_end().to_string(), Builder::new().suffix(suffix))?
 397                            .trim_end()
 398                            .to_string();
 399                    if edited_msg.is_empty() {
 400                        self.tbox.reset();
 401                        return Ok(None);
 402                    }
 403                    edited_msg
 404                } else if msg.is_blank() {
 405                    return Ok(None);
 406                } else {
 407                    msg.trim_end().to_string()
 408                };
 409
 410                let mut msg = text_to_message(msg.into(), tunables.default_markup);
 411
 412                let mentions = if let MessageType::Text(content) = &msg.msgtype {
 413                    extract_mentions(content)
 414                } else {
 415                    Mentions::new()
 416                };
 417                msg = msg.add_mentions(mentions);
 418
 419                if let Some(key) = &self.editing {
 420                    let id = match &key.id {
 421                        MessageId::Origin(id) => id,
 422                        MessageId::Local(transaction_id) => {
 423                            match info.echo_keys.get(transaction_id) {
 424                                Some(EchoLocation::Replaced(id)) => id,
 425                                Some(EchoLocation::Message(thread, orig_key)) => {
 426                                    let Some(MessageEvent::Local(_, handle, _)) = info
 427                                        .get_thread(thread.as_deref())
 428                                        .and_then(|thread| thread.get(orig_key))
 429                                        .map(|msg| &msg.event)
 430                                    else {
 431                                        let msg = "local echo not found in store";
 432                                        return Err(UIError::Failure(msg.into()));
 433                                    };
 434
 435                                    let succeeded = handle
 436                                        .edit(msg.into())
 437                                        .await
 438                                        .map_err(RoomSendQueueError::from)
 439                                        .map_err(IambError::from)?;
 440
 441                                    if !succeeded {
 442                                        let msg = "local echo was already sent; please retry";
 443                                        return Err(UIError::Failure(msg.into()));
 444                                    }
 445
 446                                    self.reset();
 447                                    return Ok(None);
 448                                },
 449                                None => {
 450                                    let msg = "local echo not found in store";
 451                                    return Err(UIError::Failure(msg.into()));
 452                                },
 453                            }
 454                        },
 455                    };
 456
 457                    let Some(edited_msg) = info.get_event(id) else {
 458                        let msg = "edited message not found in store";
 459                        return Err(UIError::Failure(msg.into()));
 460                    };
 461
 462                    let MessageEvent::Original(edited_msg, _) = &edited_msg.event else {
 463                        let msg = "you can only edit normal messages";
 464                        return Err(UIError::Failure(msg.into()));
 465                    };
 466
 467                    msg = msg.make_replacement(edited_msg.as_ref());
 468                } else if let Some(thread_root) = self.scrollback.thread() {
 469                    if let Some(m) = self.get_reply_to(info) {
 470                        msg = msg.make_for_thread(m, ReplyWithinThread::Yes, AddMentions::Yes);
 471                    } else if let Some(m) = info.get_thread_last(thread_root) {
 472                        msg = msg.make_for_thread(m, ReplyWithinThread::No, AddMentions::Yes);
 473                    } else {
 474                        // Internal state is wonky?
 475                    }
 476                } else if let Some(m) = self.get_reply_to(info) {
 477                    msg = msg.make_reply_to(m, ForwardThread::Yes, AddMentions::Yes);
 478                }
 479
 480                room.send_queue().send(msg.into()).await.map_err(IambError::from)?;
 481
 482                // Reset message bar state now that it's been sent.
 483                self.reset();
 484            },
 485            SendAction::Upload(file, add_caption) => {
 486                let caption = self.tbox.get();
 487
 488                if add_caption.is_none() &&
 489                    (!caption.is_blank() || self.get_reply_to(info).is_some())
 490                {
 491                    let msg = "Would you like to use the message bar as a caption?";
 492
 493                    let yes_act = SendAction::Upload(file.clone(), Some(true));
 494                    let no_act = SendAction::Upload(file, Some(false));
 495
 496                    let yes_choice =
 497                        MultiChoiceItem::new('y', msg, vec![IambAction::from(yes_act).into()]);
 498                    let no_choice =
 499                        MultiChoiceItem::new('n', "", vec![IambAction::from(no_act).into()]);
 500
 501                    let prompt = MultiChoice::new(vec![yes_choice, no_choice]);
 502                    let prompt = Box::new(prompt);
 503
 504                    return Err(UIError::NeedConfirm(prompt));
 505                }
 506
 507                let mime = mime_guess::from_path(&file).first_or(mime::APPLICATION_OCTET_STREAM);
 508
 509                let bytes = fs::read(&file)?;
 510                let name = file
 511                    .file_name()
 512                    .map(OsStr::to_string_lossy)
 513                    .unwrap_or_else(|| Cow::from("Attachment"));
 514
 515                let add_caption = add_caption.unwrap_or(false);
 516                let config = self.generate_attachment_config(info, add_caption, settings);
 517
 518                room.send_queue()
 519                    .send_attachment(name.as_ref(), mime, bytes, config)
 520                    .await
 521                    .map_err(IambError::from)?;
 522
 523                if add_caption {
 524                    self.reset();
 525                }
 526            },
 527            SendAction::UploadImage(width, height, bytes, add_caption) => {
 528                // Convert to png because arboard does not give us the mime type.
 529                let bytes =
 530                    image::ImageBuffer::from_raw(width as _, height as _, bytes.into_owned())
 531                        .ok_or(IambError::Clipboard)
 532                        .and_then(|imagebuf| {
 533                            let dynimage = image::DynamicImage::ImageRgba8(imagebuf);
 534                            let bytes = Vec::<u8>::new();
 535                            let mut buff = std::io::Cursor::new(bytes);
 536                            dynimage.write_to(&mut buff, image::ImageFormat::Png)?;
 537                            Ok(buff.into_inner())
 538                        })?;
 539                let mime = mime::IMAGE_PNG;
 540                let name = "Clipboard.png";
 541
 542                let mut config = self.generate_attachment_config(info, add_caption, settings);
 543                config.info = Some(AttachmentInfo::Image(BaseImageInfo {
 544                    height: height.try_into().ok(),
 545                    width: width.try_into().ok(),
 546                    ..Default::default()
 547                }));
 548
 549                room.send_queue()
 550                    .send_attachment(name, mime, bytes, config)
 551                    .await
 552                    .map_err(IambError::from)?;
 553
 554                if add_caption {
 555                    self.reset();
 556                }
 557            },
 558        }
 559
 560        // Jump to the end of the scrollback to show the message.
 561        self.scrollback.goto_latest();
 562
 563        if tunables.read_receipt_trigger.on_message() &&
 564            let Some(thread) = self.scrollback.get_thread(info)
 565        {
 566            info.fully_read(
 567                self.room_id.clone(),
 568                thread.1.clone(),
 569                &store.application.worker,
 570                settings,
 571                &mut store.application.open_notifications,
 572            );
 573        }
 574
 575        Ok(None)
 576    }
 577
 578    pub fn focus_toggle(&mut self) {
 579        self.focus.toggle();
 580    }
 581
 582    pub fn room(&self) -> &MatrixRoom {
 583        &self.room
 584    }
 585
 586    pub fn id(&self) -> &RoomId {
 587        &self.room_id
 588    }
 589
 590    pub fn current_message(&self, store: &mut ProgramStore) -> Option<MessageId> {
 591        let info = store.application.rooms.get_or_default(self.room_id.clone());
 592        self.scrollback.get_key(info).map(|key| key.id)
 593    }
 594
 595    pub fn auto_toggle_focus(
 596        &mut self,
 597        act: &EditorAction,
 598        ctx: &ProgramContext,
 599        info: &RoomInfo,
 600        settings: &ApplicationSettings,
 601    ) -> Option<EditorAction> {
 602        auto_toggle_focus(
 603            &mut self.focus,
 604            act,
 605            ctx,
 606            &self.scrollback,
 607            &mut self.tbox,
 608            &mut self.reply_to,
 609            info,
 610            settings,
 611        )
 612    }
 613
 614    pub fn typing_notice(
 615        &self,
 616        act: &EditorAction,
 617        ctx: &ProgramContext,
 618        store: &mut ProgramStore,
 619    ) {
 620        if !self.focus.is_msgbar() || act.is_readonly(ctx) {
 621            return;
 622        }
 623
 624        if !store.application.settings.tunables.typing_notice_send {
 625            return;
 626        }
 627
 628        store.application.worker.typing_notice(self.room_id.clone());
 629    }
 630}
 631
 632fn get_joined(id: &RoomId, worker: &Requester) -> Result<MatrixRoom, IambError> {
 633    let Some(room) = worker.client.get_room(id) else {
 634        return Err(IambError::NotJoined);
 635    };
 636
 637    if room.state() == MatrixRoomState::Joined {
 638        Ok(room)
 639    } else {
 640        Err(IambError::NotJoined)
 641    }
 642}
 643
 644fn open_links(msg: &Message) -> UIError<IambInfo> {
 645    let links = msg.find_links();
 646
 647    if links.is_empty() {
 648        return IambError::NoAttachment.into();
 649    }
 650
 651    let choices = links
 652        .into_iter()
 653        .map(|l| {
 654            let url = l.1.to_string();
 655            let act = IambAction::OpenLink(url.clone()).into();
 656            MultiChoiceItem::new(l.0, url, vec![act])
 657        })
 658        .collect();
 659    let dialog = MultiChoice::new(choices);
 660    UIError::NeedConfirm(Box::new(dialog))
 661}
 662
 663pub async fn msg_download(
 664    ctx: ProgramContext,
 665    client: &Client,
 666    msg: &Message,
 667    settings: &ApplicationSettings,
 668    filename: Option<PathBuf>,
 669    flags: DownloadFlags,
 670    tunables: &TunableValues,
 671) -> IambResult<Vec<(Action<IambInfo>, EditContext)>> {
 672    if let MessageEvent::State(_) = &msg.event {
 673        let err = open_links(msg);
 674        return Err(err);
 675    }
 676
 677    if let Some(msgtype) = msg.event.msgtype() {
 678        // A location message has no attachment to download, so `:open`
 679        // hands its `geo:` URI over to the system handler, which will
 680        // let the desktop open it with an application of its choosing.
 681        if let Some(geo_uri) = location_geo_uri(msgtype) {
 682            if !flags.contains(DownloadFlags::OPEN) {
 683                return Err(IambError::NoAttachment.into());
 684            }
 685
 686            let target = OsString::from(geo_uri.to_owned());
 687
 688            return match open_command(tunables.open_command.as_ref(), target) {
 689                Ok(_) => {
 690                    Ok(vec![(
 691                        Action::ShowInfoMessage(InfoMessage::from(format!("Opened {geo_uri}"))),
 692                        ctx,
 693                    )])
 694                },
 695                Err(err) => Err(err),
 696            };
 697        }
 698
 699        let media = client.media();
 700        let mut filename = match (filename, &settings.dirs.downloads) {
 701            (Some(f), _) => f,
 702            (None, Some(downloads)) => downloads.clone(),
 703            (None, None) => return Err(IambError::NoDownloadDir.into()),
 704        };
 705        let (source, msg_filename) = match msgtype {
 706            MessageType::Audio(c) => (c.source.clone(), c.filename()),
 707            MessageType::File(c) => (c.source.clone(), c.filename()),
 708            MessageType::Image(c) => (c.source.clone(), c.filename()),
 709            MessageType::Video(c) => (c.source.clone(), c.filename()),
 710            _ => {
 711                if !flags.contains(DownloadFlags::OPEN) {
 712                    return Err(IambError::NoAttachment.into());
 713                }
 714                let err = open_links(msg);
 715                return Err(err);
 716            },
 717        };
 718        if filename.is_dir() {
 719            filename.push(msg_filename.replace(std::path::MAIN_SEPARATOR_STR, "_"));
 720        }
 721        if filename.exists() && !flags.contains(DownloadFlags::FORCE) {
 722            // Find an incrementally suffixed filename, e.g. image-2.jpg -> image-3.jpg
 723            if let Some(stem) = filename.file_stem().and_then(OsStr::to_str) {
 724                let ext = filename.extension();
 725                let mut filename_incr = filename.clone();
 726                for n in 1..=1000 {
 727                    if let Some(ext) = ext.and_then(OsStr::to_str) {
 728                        filename_incr.set_file_name(format!("{stem}-{n}.{ext}"));
 729                    } else {
 730                        filename_incr.set_file_name(format!("{stem}-{n}"));
 731                    }
 732
 733                    if !filename_incr.exists() {
 734                        filename = filename_incr;
 735                        break;
 736                    }
 737                }
 738            }
 739        }
 740        if !filename.exists() || flags.contains(DownloadFlags::FORCE) {
 741            let req = MediaRequestParameters { source, format: MediaFormat::File };
 742
 743            let bytes = media.get_media_content(&req, true).await.map_err(IambError::from)?;
 744
 745            fs::write(filename.as_path(), bytes.as_slice())?;
 746        } else if !flags.contains(DownloadFlags::OPEN) {
 747            let msg = format!(
 748                "The file {} already exists; add ! to end of command to overwrite it.",
 749                filename.display()
 750            );
 751            let err = UIError::Failure(msg);
 752
 753            return Err(err);
 754        }
 755        let info = if flags.contains(DownloadFlags::OPEN) {
 756            let target = filename.clone().into_os_string();
 757            match open_command(settings.tunables.open_command.as_ref(), target) {
 758                Ok(_) => {
 759                    InfoMessage::from(format!(
 760                        "Attachment downloaded to {} and opened",
 761                        filename.display()
 762                    ))
 763                },
 764                Err(err) => {
 765                    return Err(err);
 766                },
 767            }
 768        } else {
 769            InfoMessage::from(format!("Attachment downloaded to {}", filename.display()))
 770        };
 771
 772        return Ok(vec![(Action::ShowInfoMessage(info), ctx)]);
 773    }
 774
 775    Err(IambError::NoAttachment.into())
 776}
 777
 778pub async fn msg_react(
 779    msg: &Message,
 780    settings: &ApplicationSettings,
 781    info: &RoomInfo,
 782    worker: &Requester,
 783    id: &RoomId,
 784    reaction: String,
 785    literal: bool,
 786) -> IambResult<Vec<(Action<IambInfo>, EditContext)>> {
 787    let emoji = if literal {
 788        reaction
 789    } else if let Some(emoji) =
 790        emojis::get(&reaction).or_else(|| emojis::get_by_shortcode(&reaction))
 791    {
 792        emoji.to_string()
 793    } else {
 794        let msg = format!(
 795            "{reaction:?} is not a known Emoji shortcode; do you want to react with exactly {reaction:?}?"
 796        );
 797        let act = IambAction::Message(MessageAction::React(reaction, true));
 798        let prompt = PromptYesNo::new(msg, vec![Action::from(act)]);
 799        let prompt = Box::new(prompt);
 800
 801        return Err(UIError::NeedConfirm(prompt));
 802    };
 803
 804    let room = get_joined(id, worker)?;
 805    let event_id = match &msg.event {
 806        MessageEvent::EncryptedOriginal(ev) => ev.event_id.clone(),
 807        MessageEvent::EncryptedRedacted(ev) => ev.event_id.clone(),
 808        MessageEvent::Original(ev, _) => ev.event_id.clone(),
 809        MessageEvent::Local(..) => {
 810            // XXX: Implement reactions for local echos
 811
 812            let msg = "Cannot react to a local echo";
 813            let err = UIError::Failure(msg.into());
 814
 815            return Err(err);
 816        },
 817        MessageEvent::State(ev) => ev.event_id().to_owned(),
 818        MessageEvent::Sticker(ev, ..) => ev.event_id.to_owned(),
 819        MessageEvent::Redacted(_, _) => {
 820            let msg = "Cannot react to a redacted message";
 821            let err = UIError::Failure(msg.into());
 822
 823            return Err(err);
 824        },
 825        MessageEvent::Poll(ev) => ev.event_id().to_owned(),
 826        MessageEvent::UnstablePoll(ev) => ev.event_id().to_owned(),
 827    };
 828
 829    if info.user_reactions_contains(&settings.user_id, &event_id, &emoji) {
 830        let msg = format!("You’ve already reacted to this message with {emoji}");
 831        let err = UIError::Failure(msg);
 832
 833        return Err(err);
 834    }
 835
 836    let reaction = Annotation::new(event_id, emoji);
 837    let msg = ReactionEventContent::new(reaction);
 838
 839    room.send_queue().send(msg.into()).await.map_err(IambError::from)?;
 840
 841    Ok(vec![])
 842}
 843
 844pub async fn msg_redact(
 845    msg: &Message,
 846    worker: &Requester,
 847    id: &RoomId,
 848    reason: Option<String>,
 849    skip_confirm: bool,
 850) -> IambResult<Vec<(Action<IambInfo>, EditContext)>> {
 851    if !skip_confirm {
 852        let msg = "Are you sure you want to redact this message?";
 853        let act = IambAction::Message(MessageAction::Redact(reason, true));
 854        let prompt = PromptYesNo::new(msg, vec![Action::from(act)]);
 855        let prompt = Box::new(prompt);
 856
 857        return Err(UIError::NeedConfirm(prompt));
 858    }
 859
 860    let room = get_joined(id, worker)?;
 861    let event_id = match &msg.event {
 862        MessageEvent::EncryptedOriginal(ev) => ev.event_id.clone(),
 863        MessageEvent::EncryptedRedacted(ev) => ev.event_id.clone(),
 864        MessageEvent::Original(ev, _) => ev.event_id.clone(),
 865        MessageEvent::Local(_, handle, _) => {
 866            let succeeded = handle
 867                .abort()
 868                .await
 869                .map_err(RoomSendQueueError::from)
 870                .map_err(IambError::from)?;
 871
 872            if !succeeded {
 873                let msg = "local echo was already sent; please retry";
 874                let err = UIError::Failure(msg.into());
 875
 876                return Err(err);
 877            }
 878
 879            return Ok(vec![]);
 880        },
 881        MessageEvent::State(ev) => ev.event_id().to_owned(),
 882        MessageEvent::Sticker(ev, ..) => ev.event_id.to_owned(),
 883        MessageEvent::Redacted(_, _) => {
 884            let msg = "Cannot redact already redacted message";
 885            let err = UIError::Failure(msg.into());
 886
 887            return Err(err);
 888        },
 889        MessageEvent::Poll(ev) => ev.event_id().to_owned(),
 890        MessageEvent::UnstablePoll(ev) => ev.event_id().to_owned(),
 891    };
 892
 893    let event_id = event_id.as_ref();
 894    let reason = reason.as_deref();
 895    let _ = room.redact(event_id, reason, None).await.map_err(IambError::from)?;
 896
 897    Ok(vec![])
 898}
 899
 900pub async fn msg_unreact(
 901    msg: &Message,
 902    settings: &ApplicationSettings,
 903    info: &RoomInfo,
 904    worker: &Requester,
 905    id: &RoomId,
 906    reaction: Option<String>,
 907    literal: bool,
 908) -> IambResult<Vec<(Action<IambInfo>, EditContext)>> {
 909    let emoji = match reaction {
 910        reaction if literal => reaction,
 911        Some(reaction) => {
 912            if let Some(emoji) =
 913                emojis::get(&reaction).or_else(|| emojis::get_by_shortcode(&reaction))
 914            {
 915                Some(emoji.to_string())
 916            } else {
 917                let msg = format!(
 918                    "{reaction:?} is not a known Emoji shortcode; do you want to remove exactly {reaction:?}?"
 919                );
 920                let act = IambAction::Message(MessageAction::Unreact(Some(reaction), true));
 921                let prompt = PromptYesNo::new(msg, vec![Action::from(act)]);
 922                let prompt = Box::new(prompt);
 923
 924                return Err(UIError::NeedConfirm(prompt));
 925            }
 926        },
 927        None => None,
 928    };
 929
 930    let room = get_joined(id, worker)?;
 931    let event_id = match &msg.event {
 932        MessageEvent::EncryptedOriginal(ev) => ev.event_id.clone(),
 933        MessageEvent::EncryptedRedacted(ev) => ev.event_id.clone(),
 934        MessageEvent::Original(ev, _) => ev.event_id.clone(),
 935        MessageEvent::Local(..) => {
 936            let msg = "Cannot unreact to a local echo";
 937            let err = UIError::Failure(msg.into());
 938
 939            return Err(err);
 940        },
 941        MessageEvent::State(ev) => ev.event_id().to_owned(),
 942        MessageEvent::Sticker(ev, ..) => ev.event_id.to_owned(),
 943        MessageEvent::Redacted(_, _) => {
 944            let msg = "Cannot unreact to a redacted message";
 945            let err = UIError::Failure(msg.into());
 946
 947            return Err(err);
 948        },
 949        MessageEvent::Poll(ev) => ev.event_id().to_owned(),
 950        MessageEvent::UnstablePoll(ev) => ev.event_id().to_owned(),
 951    };
 952
 953    let reactions = match info.reactions.get(&event_id) {
 954        Some(r) => r,
 955        None => return Ok(vec![]),
 956    };
 957
 958    let reactions = reactions.iter().filter_map(|(event_id, (reaction, user_id, _))| {
 959        if user_id != &settings.user_id {
 960            return None;
 961        }
 962
 963        if let Some(emoji) = &emoji {
 964            if emoji == reaction {
 965                return Some(event_id);
 966            } else {
 967                return None;
 968            }
 969        } else {
 970            return Some(event_id);
 971        }
 972    });
 973
 974    for reaction in reactions {
 975        let _ = room.redact(reaction, None, None).await.map_err(IambError::from)?;
 976    }
 977
 978    Ok(vec![])
 979}
 980
 981pub async fn msg_pin(
 982    pin: bool,
 983    msg: &Message,
 984    id: &RoomId,
 985    worker: &Requester,
 986    settings: &ApplicationSettings,
 987) -> IambResult<Vec<(Action<IambInfo>, EditContext)>> {
 988    let event_id = match &msg.event {
 989        MessageEvent::Local(..) => {
 990            let msg = "Cannot pin a message that hasn't been sent yet";
 991            return Err(UIError::Failure(msg.into()));
 992        },
 993        MessageEvent::Redacted(..) | MessageEvent::EncryptedRedacted(_) if pin => {
 994            let msg = "Cannot pin a redacted message";
 995            return Err(UIError::Failure(msg.into()));
 996        },
 997        event => {
 998            event
 999                .event_id()
1000                .map(ToOwned::to_owned)
1001                .ok_or(IambError::NoSelectedMessage)?
1002        },
1003    };
1004
1005    let room = get_joined(id, worker)?;
1006
1007    let can_pin = room
1008        .power_levels()
1009        .await
1010        .map_err(matrix_sdk::Error::from)
1011        .map_err(IambError::from)?
1012        .user_can_send_state(&settings.user_id, StateEventType::RoomPinnedEvents);
1013
1014    if !can_pin {
1015        return Err(IambError::InsufficientPermission.into());
1016    }
1017
1018    // The state event holds the whole list, so rebuild it from the SDK's latest copy.
1019    let mut pinned = room.pinned_event_ids().unwrap_or_default();
1020    let position = pinned.iter().position(|id| *id == event_id);
1021
1022    match (pin, position) {
1023        (true, Some(_)) => {
1024            let msg = "This message is already pinned";
1025            return Err(UIError::Failure(msg.into()));
1026        },
1027        (false, None) => {
1028            let msg = "This message is not pinned";
1029            return Err(UIError::Failure(msg.into()));
1030        },
1031        (true, None) => {
1032            pinned.push(event_id);
1033        },
1034        (false, Some(idx)) => {
1035            pinned.remove(idx);
1036        },
1037    }
1038
1039    room.send_state_event(RoomPinnedEventsEventContent::new(pinned))
1040        .await
1041        .map_err(IambError::from)?;
1042
1043    Ok(vec![])
1044}
1045
1046macro_rules! delegate {
1047    ($s: expr, $id: ident => $e: expr) => {
1048        match $s.focus {
1049            RoomFocus::Scrollback => {
1050                match $s {
1051                    ChatState { scrollback: $id, .. } => $e,
1052                }
1053            },
1054            RoomFocus::MessageBar => {
1055                match $s {
1056                    ChatState { tbox: $id, .. } => $e,
1057                }
1058            },
1059        }
1060    };
1061}
1062
1063impl WindowOps<IambInfo> for ChatState {
1064    fn draw(&mut self, area: Rect, buf: &mut Buffer, focused: bool, store: &mut ProgramStore) {
1065        Chat::new(store).focus(focused).render(area, buf, self)
1066    }
1067
1068    fn dup(&self, store: &mut ProgramStore) -> Self {
1069        // XXX: I want each WindowSlot to have its own shared buffer, instead of each Room; need to
1070        // find a good way to pass that info here so that it can be part of the content id.
1071        let room_id = self.room_id.clone();
1072        let view = self.thread().cloned().into();
1073        let id = IambBufferId::Room(room_id.clone(), view, RoomFocus::MessageBar);
1074        let ebuf = store.load_buffer(id);
1075        let tbox = TextBoxState::new(ebuf);
1076
1077        ChatState {
1078            room_id,
1079            room: self.room.clone(),
1080
1081            tbox,
1082            sent: self.sent.clone(),
1083            sent_scrollback: history::ScrollbackState::Pending,
1084
1085            scrollback: self.scrollback.dup(store),
1086            focus: self.focus,
1087
1088            reply_to: None,
1089            editing: None,
1090            pending_jump: None,
1091        }
1092    }
1093
1094    fn close(&mut self, _: CloseFlags, _: &mut ProgramStore) -> bool {
1095        // XXX: what's the right closing behaviour for a room?
1096        // Should write send a message?
1097        true
1098    }
1099
1100    fn write(
1101        &mut self,
1102        _: Option<&str>,
1103        _: WriteFlags,
1104        _: &mut ProgramStore,
1105    ) -> IambResult<EditInfo> {
1106        // XXX: what's the right writing behaviour for a room?
1107        // Should write send a message?
1108        Ok(None)
1109    }
1110
1111    fn get_completions(&self) -> Option<CompletionList> {
1112        delegate!(self, w => w.get_completions())
1113    }
1114
1115    fn get_cursor_word(&self, style: &WordStyle) -> Option<String> {
1116        delegate!(self, w => w.get_cursor_word(style))
1117    }
1118
1119    fn get_selected_word(&self) -> Option<String> {
1120        delegate!(self, w => w.get_selected_word())
1121    }
1122}
1123
1124impl Editable<ProgramContext, ProgramStore, IambInfo> for ChatState {
1125    fn editor_command(
1126        &mut self,
1127        act: &EditorAction,
1128        ctx: &ProgramContext,
1129        store: &mut ProgramStore,
1130    ) -> EditResult<EditInfo, IambInfo> {
1131        // Check whether we should automatically switch between the message bar
1132        // or message scrollback, and use an adjusted action if we do so.
1133        let info = store.application.rooms.get_or_default(self.room_id.clone());
1134        let adjusted = self.auto_toggle_focus(act, ctx, info, &store.application.settings);
1135        let act = adjusted.as_ref().unwrap_or(act);
1136
1137        // Send typing notice if needed.
1138        self.typing_notice(act, ctx, store);
1139
1140        // And now we can finally run the editor command.
1141        match delegate!(self, w => w.editor_command(act, ctx, store)) {
1142            res @ Ok(_) => res,
1143            Err(EditError::WrongBuffer(IambBufferId::Room(room_id, view, focus)))
1144                if room_id == self.room_id &&
1145                    view == self.thread().into() &&
1146                    act.is_switchable(ctx) =>
1147            {
1148                // Switch focus.
1149                self.focus = focus;
1150
1151                // Run command again.
1152                delegate!(self, w => w.editor_command(act, ctx, store))
1153            },
1154            #[cfg(feature = "desktop")]
1155            Err(EditError::Register(RegisterError::ClipboardImage(data))) => {
1156                let info = store.application.rooms.get_or_default(self.id().to_owned());
1157                let prompt = if self.tbox.get().is_blank() && self.get_reply_to(info).is_none() {
1158                    let msg = "Do you really want to upload the image from your system clipboard?";
1159                    let send = IambAction::Send(SendAction::UploadImage(
1160                        data.width,
1161                        data.height,
1162                        data.bytes,
1163                        false,
1164                    ));
1165                    let prompt = PromptYesNo::new(msg, vec![Action::from(send)]);
1166                    Box::new(prompt) as Box<dyn Dialog<_>>
1167                } else {
1168                    let msg_c = "Upload clipboard image with message bar as caption";
1169                    let act_c =
1170                        SendAction::UploadImage(data.width, data.height, data.bytes.clone(), true);
1171                    let choice_c =
1172                        MultiChoiceItem::new('c', msg_c, vec![IambAction::from(act_c).into()]);
1173
1174                    let msg_y = "Upload clipboard image without caption";
1175                    let act_y =
1176                        SendAction::UploadImage(data.width, data.height, data.bytes.clone(), false);
1177                    let choice_y =
1178                        MultiChoiceItem::new('y', msg_y, vec![IambAction::from(act_y).into()]);
1179
1180                    let msg_n = "Do not upload clipboard image";
1181                    let choice_n = MultiChoiceItem::new('n', msg_n, vec![Action::NoOp]);
1182
1183                    let prompt = MultiChoice::new(vec![choice_c, choice_y, choice_n]);
1184                    Box::new(prompt) as Box<dyn Dialog<_>>
1185                };
1186
1187                Err(EditError::NeedConfirm(prompt))
1188            },
1189            res @ Err(_) => res,
1190        }
1191    }
1192}
1193
1194impl TerminalCursor for ChatState {
1195    fn get_term_cursor(&self) -> Option<(u16, u16)> {
1196        delegate!(self, w => w.get_term_cursor())
1197    }
1198
1199    fn hide_term_cursor(&self) -> bool {
1200        delegate!(self, w => w.hide_term_cursor())
1201    }
1202}
1203
1204impl Jumpable<ProgramContext, IambInfo> for ChatState {
1205    fn jump(
1206        &mut self,
1207        list: PositionList,
1208        dir: MoveDir1D,
1209        count: usize,
1210        ctx: &ProgramContext,
1211    ) -> IambResult<usize> {
1212        delegate!(self, w => w.jump(list, dir, count, ctx))
1213    }
1214}
1215
1216impl Scrollable<ProgramContext, ProgramStore, IambInfo> for ChatState {
1217    fn scroll(
1218        &mut self,
1219        style: &ScrollStyle,
1220        ctx: &ProgramContext,
1221        store: &mut ProgramStore,
1222    ) -> EditResult<EditInfo, IambInfo> {
1223        // Send all scroll commands to the scrollback.
1224        //
1225        // If there's enough message text for scrolling to be necessary,
1226        // navigating with movement keys should be enough to do the job.
1227        self.scrollback.scroll(style, ctx, store)
1228    }
1229}
1230
1231impl PromptActions<ProgramContext, ProgramStore, IambInfo> for ChatState {
1232    fn submit(
1233        &mut self,
1234        ctx: &ProgramContext,
1235        _: &mut ProgramStore,
1236    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
1237        let act = SendAction::Submit;
1238
1239        Ok(vec![(IambAction::from(act).into(), ctx.clone())])
1240    }
1241
1242    fn abort(
1243        &mut self,
1244        empty: bool,
1245        _: &ProgramContext,
1246        _: &mut ProgramStore,
1247    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
1248        let text = self.tbox.get();
1249
1250        if empty && text.is_blank() {
1251            return Ok(vec![]);
1252        }
1253
1254        let text = self.reset().trim();
1255
1256        if text.is_empty() {
1257            let _ = self.sent.end();
1258        } else {
1259            self.sent.select(text);
1260        }
1261
1262        return Ok(vec![]);
1263    }
1264
1265    fn recall(
1266        &mut self,
1267        filter: &RecallFilter,
1268        dir: &MoveDir1D,
1269        count: &Count,
1270        ctx: &ProgramContext,
1271        _: &mut ProgramStore,
1272    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
1273        let count = ctx.resolve(count);
1274        let rope = self.tbox.get();
1275
1276        let text = self.sent.recall(&rope, &mut self.sent_scrollback, filter, *dir, count);
1277
1278        if let Some(text) = text {
1279            self.tbox.set_text(text);
1280        }
1281
1282        Ok(vec![])
1283    }
1284}
1285
1286impl Promptable<ProgramContext, ProgramStore, IambInfo> for ChatState {
1287    fn prompt(
1288        &mut self,
1289        act: &PromptAction,
1290        ctx: &ProgramContext,
1291        store: &mut ProgramStore,
1292    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
1293        if let RoomFocus::Scrollback = self.focus {
1294            return self.scrollback.prompt(act, ctx, store);
1295        }
1296
1297        match act {
1298            PromptAction::Submit => self.submit(ctx, store),
1299            PromptAction::Abort(empty) => self.abort(*empty, ctx, store),
1300            PromptAction::Recall(filter, dir, count) => self.recall(filter, dir, count, ctx, store),
1301        }
1302    }
1303}
1304
1305/// [StatefulWidget] for Matrix rooms.
1306pub struct Chat<'a> {
1307    store: &'a mut ProgramStore,
1308    focused: bool,
1309}
1310
1311impl<'a> Chat<'a> {
1312    pub fn new(store: &'a mut ProgramStore) -> Chat<'a> {
1313        Chat { store, focused: false }
1314    }
1315
1316    pub fn focus(mut self, focused: bool) -> Self {
1317        self.focused = focused;
1318        self
1319    }
1320}
1321
1322impl StatefulWidget for Chat<'_> {
1323    type State = ChatState;
1324
1325    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
1326        state.complete_pending_jump(self.store);
1327
1328        let settings = &self.store.application.settings;
1329        let theme = &settings.theme;
1330
1331        // Determine whether we have a description to show for the message bar.
1332        let desc_spans = match (&state.editing, &state.reply_to, state.thread()) {
1333            (None, None, None) => {
1334                if state.room.is_tombstoned() {
1335                    Some(
1336                        Line::from(vec![
1337                            Span::from("This room has been upgraded! ").bold(),
1338                            Span::from("Use "),
1339                            Span::from(":follow").bold(),
1340                            Span::from(" to join everyone in the new room."),
1341                        ])
1342                        .centered(),
1343                    )
1344                } else {
1345                    None
1346                }
1347            },
1348            (None, None, Some(_)) => Some(Line::from("Replying in thread")),
1349            (Some(_), None, None) => Some(Line::from("Editing message")),
1350            (Some(_), None, Some(_)) => Some(Line::from("Editing message in thread")),
1351            (editing, Some(_), thread) => {
1352                self.store.application.rooms.get(state.id()).and_then(|room| {
1353                    let msg = state.get_reply_to(room)?;
1354                    let user = self
1355                        .store
1356                        .application
1357                        .settings
1358                        .get_user_span(msg.sender.as_ref(), room.display_names.get(&msg.sender));
1359                    let prefix = match (editing.is_some(), thread.is_some()) {
1360                        (true, false) => Span::from("Editing reply to "),
1361                        (true, true) => Span::from("Editing reply in thread to "),
1362                        (false, false) => Span::from("Replying to "),
1363                        (false, true) => Span::from("Replying in thread to "),
1364                    };
1365                    let spans = Line::from(vec![prefix, user]);
1366
1367                    spans.into()
1368                })
1369            },
1370        };
1371
1372        // Determine the region to show each UI element.
1373        let lines = state.tbox.has_lines(5).max(1) as u16;
1374        let drawh = area.height;
1375        let texth = lines.min(drawh).clamp(1, 5);
1376        let desch = if desc_spans.is_some() {
1377            drawh.saturating_sub(texth).min(1)
1378        } else {
1379            0
1380        };
1381        let scrollh = drawh.saturating_sub(texth).saturating_sub(desch);
1382
1383        let scrollarea = Rect::new(area.x, area.y, area.width, scrollh);
1384        let descarea = Rect::new(area.x, scrollarea.y + scrollh, area.width, desch);
1385        let textarea = Rect::new(area.x, descarea.y + desch, area.width, texth);
1386
1387        // Render the message bar and any description for it.
1388        if let Some(desc_spans) = desc_spans {
1389            Paragraph::new(desc_spans).render(descarea, buf);
1390        }
1391
1392        let encryption_settings = &settings.tunables.encryption;
1393        let encryption_indicator = encryption_settings.get_indicator(
1394            EncryptionIndicatorLocation::PROMPT,
1395            state.room().encryption_state(),
1396            theme,
1397        );
1398        let input_prompt = settings.tunables.input_prompt.as_deref();
1399        let prompt = match (self.focused, encryption_indicator, input_prompt) {
1400            // User has both encryption indicator and custom prompt, combine them:
1401            (false, Some(i), Some(p)) => Line::from(crate::util::space(i.width() + p.width())),
1402            (true, Some(i), Some(p)) => Line::from(vec![i, Span::from(p)]),
1403
1404            // User has custom prompt, use that:
1405            (false, None, Some(p)) => Line::from(crate::util::space(p.width())),
1406            (true, None, Some(p)) => Line::from(p),
1407
1408            // User has encryption indicator, use that as prompt:
1409            (false, Some(i), None) => Line::from(crate::util::space(i.width())),
1410            (true, Some(i), None) => Line::from(i),
1411
1412            // User has no encryption indicator, no custom prompt, so show "> ":
1413            (false, None, None) => Line::from(crate::util::space(2)),
1414            (true, None, None) => Line::from("> "),
1415        };
1416
1417        let tbox = TextBox::new().style(theme.msgbar.default).prompt(prompt);
1418        state
1419            .tbox
1420            .set_ignorecase(self.store.application.settings.tunables.ignorecase);
1421        tbox.render(textarea, buf, &mut state.tbox);
1422
1423        // Render the message scrollback.
1424        let scrollback_style = self.store.application.settings.theme.timeline.default;
1425        let scrollback_focused = state.focus.is_scrollback() && self.focused;
1426        let scrollback = Scrollback::new(self.store)
1427            .style(scrollback_style)
1428            .focus(scrollback_focused)
1429            .room_focus(self.focused);
1430        scrollback.render(scrollarea, buf, &mut state.scrollback);
1431    }
1432}
1433
1434/// Returns the `geo:` URI that a location message refers to.
1435fn location_geo_uri(msgtype: &MessageType) -> Option<&str> {
1436    match msgtype {
1437        MessageType::Location(content) => Some(content.geo_uri()),
1438        _ => None,
1439    }
1440}
1441
1442fn open_command(open_command: Option<&Vec<String>>, target: OsString) -> IambResult<()> {
1443    if let Some(mut cmd) = open_command.and_then(cmd) {
1444        cmd.arg(target);
1445        cmd.spawn()?;
1446        return Ok(());
1447    } else {
1448        // open::that may not return until the spawned program closes.
1449        tokio::task::spawn_blocking(move || {
1450            return open::that(target);
1451        });
1452        return Ok(());
1453    }
1454}
1455
1456/// Extract mentions from `https://matrix.to` html links
1457fn extract_mentions(content: &TextMessageEventContent) -> Mentions {
1458    let Some(formatted) = content.formatted.as_ref() else {
1459        return Mentions::new();
1460    };
1461    if !matches!(formatted.format, MessageFormat::Html) {
1462        return Mentions::new();
1463    }
1464    extract_mentions_str(formatted.body.as_str())
1465}
1466
1467fn extract_mentions_str(html: &str) -> Mentions {
1468    let re = Regex::new(r#"<a href="(https://matrix.to/#/@[^"]*:[^"]*)"[^>]*>"#).unwrap();
1469
1470    let user_ids = re.captures_iter(html).filter_map(|capture| {
1471        let link = capture.get(1)?.as_str();
1472        let uri = MatrixToUri::parse(link).ok()?;
1473
1474        if let MatrixId::User(user_id) = uri.id() {
1475            Some(user_id.to_owned())
1476        } else {
1477            None
1478        }
1479    });
1480
1481    Mentions::with_user_ids(user_ids)
1482}
1483
1484fn cmd(open_command: &Vec<String>) -> Option<Command> {
1485    if let [program, args @ ..] = open_command.as_slice() {
1486        let mut cmd = Command::new(program);
1487        cmd.args(args);
1488        return Some(cmd);
1489    }
1490    None
1491}
1492
1493#[expect(
1494    clippy::too_many_arguments,
1495    reason = "this is only a seperate function to make testing easier"
1496)]
1497fn auto_toggle_focus(
1498    focus: &mut RoomFocus,
1499    act: &EditorAction,
1500    ctx: &ProgramContext,
1501    scrollback: &ScrollbackState,
1502    tbox: &mut TextBoxState<IambInfo>,
1503    reply_to: &mut Option<MessageKey>,
1504    info: &RoomInfo,
1505    settings: &ApplicationSettings,
1506) -> Option<EditorAction> {
1507    let is_insert = ctx.get_insert_style().is_some();
1508
1509    match (focus, act) {
1510        (f @ RoomFocus::Scrollback, _) if is_insert => {
1511            // Insert mode commands should switch focus.
1512            if settings.tunables.reply_on_insert &&
1513                reply_to.is_none() &&
1514                !tbox.get_text().is_empty()
1515            {
1516                *reply_to = scrollback.get_key(info);
1517            }
1518            f.toggle();
1519            None
1520        },
1521        (f @ RoomFocus::Scrollback, EditorAction::InsertText(_)) => {
1522            // Pasting or otherwise inserting text should switch.
1523            if settings.tunables.reply_on_insert &&
1524                reply_to.is_none() &&
1525                !tbox.get_text().is_empty()
1526            {
1527                *reply_to = scrollback.get_key(info);
1528            }
1529            f.toggle();
1530            None
1531        },
1532        (
1533            f @ RoomFocus::Scrollback,
1534            EditorAction::Edit(
1535                op,
1536                EditTarget::Motion(mov @ MoveType::Line(MoveDir1D::Next), count),
1537            ),
1538        ) if ctx.resolve(op).is_motion() => {
1539            let count = ctx.resolve(count);
1540
1541            if count > 0 && scrollback.is_latest() {
1542                // Trying to move down a line when already at the end of room history should
1543                // switch.
1544                f.toggle();
1545
1546                // And decrement the count for the action.
1547                let count = count.saturating_sub(1).into();
1548                let target = EditTarget::Motion(mov.clone(), count);
1549                let dec = EditorAction::Edit(op.clone(), target);
1550
1551                Some(dec)
1552            } else {
1553                None
1554            }
1555        },
1556        (
1557            f @ RoomFocus::MessageBar,
1558            EditorAction::Edit(
1559                op,
1560                EditTarget::Motion(mov @ MoveType::Line(MoveDir1D::Previous), count),
1561            ),
1562        ) if !is_insert && ctx.resolve(op).is_motion() => {
1563            let count = ctx.resolve(count);
1564
1565            if count > 0 && tbox.get_cursor().y == 0 {
1566                // Trying to move up a line when already at the top of the msgbar should
1567                // switch as long as we're not in Insert mode.
1568                f.toggle();
1569
1570                // And decrement the count for the action.
1571                let count = count.saturating_sub(1).into();
1572                let target = EditTarget::Motion(mov.clone(), count);
1573                let dec = EditorAction::Edit(op.clone(), target);
1574
1575                Some(dec)
1576            } else {
1577                None
1578            }
1579        },
1580        (RoomFocus::Scrollback, _) | (RoomFocus::MessageBar, _) => {
1581            // Do not switch.
1582            None
1583        },
1584    }
1585}
1586
1587#[cfg(test)]
1588mod tests {
1589    use super::*;
1590
1591    use modalkit::actions::{EditAction, InsertTextAction};
1592
1593    use crate::tests::{TEST_ROOM1_ID, mock_store};
1594
1595    fn mentions_in(html: &str) -> Vec<String> {
1596        extract_mentions_str(html).user_ids.iter().map(|u| u.to_string()).collect()
1597    }
1598
1599    #[test]
1600    fn test_location_geo_uri() {
1601        use matrix_sdk::ruma::events::room::message::{
1602            LocationMessageEventContent,
1603            TextMessageEventContent,
1604        };
1605
1606        let location = MessageType::Location(LocationMessageEventContent::new(
1607            "geo test".into(),
1608            "geo:51.5072,-0.1276".into(),
1609        ));
1610        assert_eq!(location_geo_uri(&location), Some("geo:51.5072,-0.1276"));
1611
1612        let text = MessageType::Text(TextMessageEventContent::plain("not a location"));
1613        assert_eq!(location_geo_uri(&text), None);
1614    }
1615
1616    #[test]
1617    fn test_extract_mentions_normal() {
1618        let res = mentions_in(r#"<a href="https://matrix.to/#/@user:example.com">user</a>"#);
1619        assert_eq!(res, vec!["@user:example.com"]);
1620    }
1621
1622    #[test]
1623    fn test_extract_mentions_ignore_parameters() {
1624        let res =
1625            mentions_in(r#"<a href="https://matrix.to/#/@user:example.com?via=example.com">u</a>"#);
1626        assert_eq!(res, vec!["@user:example.com"]);
1627    }
1628
1629    #[test]
1630    fn test_extract_mentions_title() {
1631        let twim = r#"<a href="https://matrix.to/#/@this-week-in:matrix.org" title="@this-week-in:matrix.org">TWIM</a>"#;
1632        let res = mentions_in(twim);
1633        assert_eq!(res, vec!["@this-week-in:matrix.org"]);
1634    }
1635
1636    #[test]
1637    fn test_extract_mentions_multiple_dedupe() {
1638        let res = mentions_in(
1639            r#"<a href="https://matrix.to/#/@a:example.com">a</a> and
1640                   <a href="https://matrix.to/#/@b:example.com">b</a> and
1641                   <a href="https://matrix.to/#/@a:example.com">a again</a>"#,
1642        );
1643        assert_eq!(res, vec!["@a:example.com", "@b:example.com"]);
1644    }
1645
1646    #[test]
1647    fn test_extract_mentions_skips_invalid_links() {
1648        let empty = vec![
1649            r#"<a href="https://matrix.to/#/@user:example.com/$eventid">e</a>"#,
1650            r#"<a href="https://matrix.to/#/@bob:">bob</a>"#,
1651            r#"<a href="https://matrix.to/#/@user:%E4%BE%8B.com">x</a>"#,
1652        ];
1653
1654        for html in empty {
1655            assert!(mentions_in(html).is_empty());
1656        }
1657
1658        // An invalid link is ignored, but a valid one is still extracted:
1659        assert_eq!(
1660            mentions_in(
1661                r#"<a href="https://matrix.to/#/@bob:">bob</a>
1662                   <a href="https://matrix.to/#/@user:example.com">user</a>"#
1663            ),
1664            vec!["@user:example.com"]
1665        );
1666    }
1667
1668    #[test]
1669    fn test_extract_mentions_ignores_unformatted() {
1670        // URIs in plain text messages don't count as mentions:
1671        let plain = TextMessageEventContent::plain(
1672            r#"<a href="https://matrix.to/#/@user:example.com">user</a>"#,
1673        );
1674        assert!(extract_mentions(&plain).user_ids.is_empty());
1675
1676        // Links to things other than users aren't mentions:
1677        let room = r#"<a href="https://matrix.to/#/#room:example.com">room</a>"#;
1678        assert!(mentions_in(room).is_empty());
1679
1680        let nonmx = r#"<a href="https://example.com/@user:example.com">nope</a>"#;
1681        assert!(mentions_in(nonmx).is_empty());
1682    }
1683
1684    macro_rules! move_line {
1685        ($dir: expr, $count: expr) => {
1686            EditorAction::Edit(
1687                EditAction::Motion.into(),
1688                EditTarget::Motion(MoveType::Line($dir), $count.into()),
1689            )
1690        };
1691    }
1692
1693    #[tokio::test]
1694    async fn test_auto_focus() {
1695        let mut store = mock_store().await;
1696        let ctx = ProgramContext::default();
1697
1698        let room_id = TEST_ROOM1_ID.clone();
1699        let scrollback = ScrollbackState::new(room_id.clone(), None);
1700
1701        let id = IambBufferId::Room(room_id, RoomView::Main, RoomFocus::MessageBar);
1702        let ebuf = store.load_buffer(id);
1703        let mut tbox = TextBoxState::new(ebuf);
1704        let mut reply_to = None;
1705        let info = RoomInfo::default();
1706        let settings = &store.application.settings;
1707
1708        // Start out focused on the scrollback.
1709        let mut focused = RoomFocus::Scrollback;
1710
1711        // Inserting text toggles:
1712        let act = EditorAction::InsertText(InsertTextAction::Type(
1713            Char::from('a').into(),
1714            MoveDir1D::Next,
1715            1.into(),
1716        ));
1717        let res = auto_toggle_focus(
1718            &mut focused,
1719            &act,
1720            &ctx,
1721            &scrollback,
1722            &mut tbox,
1723            &mut reply_to,
1724            &info,
1725            settings,
1726        );
1727        assert_eq!(focused, RoomFocus::MessageBar);
1728        assert!(res.is_none());
1729
1730        // Going down in message bar doesn't toggle:
1731        let act = move_line!(MoveDir1D::Next, 1);
1732        let res = auto_toggle_focus(
1733            &mut focused,
1734            &act,
1735            &ctx,
1736            &scrollback,
1737            &mut tbox,
1738            &mut reply_to,
1739            &info,
1740            settings,
1741        );
1742        assert_eq!(focused, RoomFocus::MessageBar);
1743        assert!(res.is_none());
1744
1745        // But going up will:
1746        let act = move_line!(MoveDir1D::Previous, 1);
1747        let res = auto_toggle_focus(
1748            &mut focused,
1749            &act,
1750            &ctx,
1751            &scrollback,
1752            &mut tbox,
1753            &mut reply_to,
1754            &info,
1755            settings,
1756        );
1757        assert_eq!(focused, RoomFocus::Scrollback);
1758        assert_eq!(res, Some(move_line!(MoveDir1D::Previous, 0)));
1759
1760        // Going up in scrollback doesn't toggle:
1761        let act = move_line!(MoveDir1D::Previous, 1);
1762        let res = auto_toggle_focus(
1763            &mut focused,
1764            &act,
1765            &ctx,
1766            &scrollback,
1767            &mut tbox,
1768            &mut reply_to,
1769            &info,
1770            settings,
1771        );
1772        assert_eq!(focused, RoomFocus::Scrollback);
1773        assert_eq!(res, None);
1774
1775        // And then go back down:
1776        let act = move_line!(MoveDir1D::Next, 1);
1777        let res = auto_toggle_focus(
1778            &mut focused,
1779            &act,
1780            &ctx,
1781            &scrollback,
1782            &mut tbox,
1783            &mut reply_to,
1784            &info,
1785            settings,
1786        );
1787        assert_eq!(focused, RoomFocus::MessageBar);
1788        assert_eq!(res, Some(move_line!(MoveDir1D::Next, 0)));
1789
1790        // Go up 2 will go up 1 in scrollback:
1791        let act = move_line!(MoveDir1D::Previous, 2);
1792        let res = auto_toggle_focus(
1793            &mut focused,
1794            &act,
1795            &ctx,
1796            &scrollback,
1797            &mut tbox,
1798            &mut reply_to,
1799            &info,
1800            settings,
1801        );
1802        assert_eq!(focused, RoomFocus::Scrollback);
1803        assert_eq!(res, Some(move_line!(MoveDir1D::Previous, 1)));
1804
1805        // Go down 3 will go down 2 in messagebar:
1806        let act = move_line!(MoveDir1D::Next, 3);
1807        let res = auto_toggle_focus(
1808            &mut focused,
1809            &act,
1810            &ctx,
1811            &scrollback,
1812            &mut tbox,
1813            &mut reply_to,
1814            &info,
1815            settings,
1816        );
1817        assert_eq!(focused, RoomFocus::MessageBar);
1818        assert_eq!(res, Some(move_line!(MoveDir1D::Next, 2)));
1819    }
1820}