src/windows/room/chat.rs

1757 lines · 63008 bytes

   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_messages(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    ) -> Option<EditorAction> {
 600        auto_toggle_focus(&mut self.focus, act, ctx, &self.scrollback, &mut self.tbox)
 601    }
 602
 603    pub fn typing_notice(
 604        &self,
 605        act: &EditorAction,
 606        ctx: &ProgramContext,
 607        store: &mut ProgramStore,
 608    ) {
 609        if !self.focus.is_msgbar() || act.is_readonly(ctx) {
 610            return;
 611        }
 612
 613        if !store.application.settings.tunables.typing_notice_send {
 614            return;
 615        }
 616
 617        store.application.worker.typing_notice(self.room_id.clone());
 618    }
 619}
 620
 621fn get_joined(id: &RoomId, worker: &Requester) -> Result<MatrixRoom, IambError> {
 622    let Some(room) = worker.client.get_room(id) else {
 623        return Err(IambError::NotJoined);
 624    };
 625
 626    if room.state() == MatrixRoomState::Joined {
 627        Ok(room)
 628    } else {
 629        Err(IambError::NotJoined)
 630    }
 631}
 632
 633fn open_links(msg: &Message) -> UIError<IambInfo> {
 634    let links = msg.find_links();
 635
 636    if links.is_empty() {
 637        return IambError::NoAttachment.into();
 638    }
 639
 640    let choices = links
 641        .into_iter()
 642        .map(|l| {
 643            let url = l.1.to_string();
 644            let act = IambAction::OpenLink(url.clone()).into();
 645            MultiChoiceItem::new(l.0, url, vec![act])
 646        })
 647        .collect();
 648    let dialog = MultiChoice::new(choices);
 649    UIError::NeedConfirm(Box::new(dialog))
 650}
 651
 652pub async fn msg_download(
 653    ctx: ProgramContext,
 654    client: &Client,
 655    msg: &Message,
 656    settings: &ApplicationSettings,
 657    filename: Option<PathBuf>,
 658    flags: DownloadFlags,
 659    tunables: &TunableValues,
 660) -> IambResult<Vec<(Action<IambInfo>, EditContext)>> {
 661    if let MessageEvent::State(_) = &msg.event {
 662        let err = open_links(msg);
 663        return Err(err);
 664    }
 665
 666    if let Some(msgtype) = msg.event.msgtype() {
 667        // A location message has no attachment to download, so `:open`
 668        // hands its `geo:` URI over to the system handler, which will
 669        // let the desktop open it with an application of its choosing.
 670        if let Some(geo_uri) = location_geo_uri(msgtype) {
 671            if !flags.contains(DownloadFlags::OPEN) {
 672                return Err(IambError::NoAttachment.into());
 673            }
 674
 675            let target = OsString::from(geo_uri.to_owned());
 676
 677            return match open_command(tunables.open_command.as_ref(), target) {
 678                Ok(_) => {
 679                    Ok(vec![(
 680                        Action::ShowInfoMessage(InfoMessage::from(format!("Opened {geo_uri}"))),
 681                        ctx,
 682                    )])
 683                },
 684                Err(err) => Err(err),
 685            };
 686        }
 687
 688        let media = client.media();
 689        let mut filename = match (filename, &settings.dirs.downloads) {
 690            (Some(f), _) => f,
 691            (None, Some(downloads)) => downloads.clone(),
 692            (None, None) => return Err(IambError::NoDownloadDir.into()),
 693        };
 694        let (source, msg_filename) = match msgtype {
 695            MessageType::Audio(c) => (c.source.clone(), c.filename()),
 696            MessageType::File(c) => (c.source.clone(), c.filename()),
 697            MessageType::Image(c) => (c.source.clone(), c.filename()),
 698            MessageType::Video(c) => (c.source.clone(), c.filename()),
 699            _ => {
 700                if !flags.contains(DownloadFlags::OPEN) {
 701                    return Err(IambError::NoAttachment.into());
 702                }
 703                let err = open_links(msg);
 704                return Err(err);
 705            },
 706        };
 707        if filename.is_dir() {
 708            filename.push(msg_filename.replace(std::path::MAIN_SEPARATOR_STR, "_"));
 709        }
 710        if filename.exists() && !flags.contains(DownloadFlags::FORCE) {
 711            // Find an incrementally suffixed filename, e.g. image-2.jpg -> image-3.jpg
 712            if let Some(stem) = filename.file_stem().and_then(OsStr::to_str) {
 713                let ext = filename.extension();
 714                let mut filename_incr = filename.clone();
 715                for n in 1..=1000 {
 716                    if let Some(ext) = ext.and_then(OsStr::to_str) {
 717                        filename_incr.set_file_name(format!("{stem}-{n}.{ext}"));
 718                    } else {
 719                        filename_incr.set_file_name(format!("{stem}-{n}"));
 720                    }
 721
 722                    if !filename_incr.exists() {
 723                        filename = filename_incr;
 724                        break;
 725                    }
 726                }
 727            }
 728        }
 729        if !filename.exists() || flags.contains(DownloadFlags::FORCE) {
 730            let req = MediaRequestParameters { source, format: MediaFormat::File };
 731
 732            let bytes = media.get_media_content(&req, true).await.map_err(IambError::from)?;
 733
 734            fs::write(filename.as_path(), bytes.as_slice())?;
 735        } else if !flags.contains(DownloadFlags::OPEN) {
 736            let msg = format!(
 737                "The file {} already exists; add ! to end of command to overwrite it.",
 738                filename.display()
 739            );
 740            let err = UIError::Failure(msg);
 741
 742            return Err(err);
 743        }
 744        let info = if flags.contains(DownloadFlags::OPEN) {
 745            let target = filename.clone().into_os_string();
 746            match open_command(settings.tunables.open_command.as_ref(), target) {
 747                Ok(_) => {
 748                    InfoMessage::from(format!(
 749                        "Attachment downloaded to {} and opened",
 750                        filename.display()
 751                    ))
 752                },
 753                Err(err) => {
 754                    return Err(err);
 755                },
 756            }
 757        } else {
 758            InfoMessage::from(format!("Attachment downloaded to {}", filename.display()))
 759        };
 760
 761        return Ok(vec![(Action::ShowInfoMessage(info), ctx)]);
 762    }
 763
 764    Err(IambError::NoAttachment.into())
 765}
 766
 767pub async fn msg_react(
 768    msg: &Message,
 769    settings: &ApplicationSettings,
 770    info: &RoomInfo,
 771    worker: &Requester,
 772    id: &RoomId,
 773    reaction: String,
 774    literal: bool,
 775) -> IambResult<Vec<(Action<IambInfo>, EditContext)>> {
 776    let emoji = if literal {
 777        reaction
 778    } else if let Some(emoji) =
 779        emojis::get(&reaction).or_else(|| emojis::get_by_shortcode(&reaction))
 780    {
 781        emoji.to_string()
 782    } else {
 783        let msg = format!(
 784            "{reaction:?} is not a known Emoji shortcode; do you want to react with exactly {reaction:?}?"
 785        );
 786        let act = IambAction::Message(MessageAction::React(reaction, true));
 787        let prompt = PromptYesNo::new(msg, vec![Action::from(act)]);
 788        let prompt = Box::new(prompt);
 789
 790        return Err(UIError::NeedConfirm(prompt));
 791    };
 792
 793    let room = get_joined(id, worker)?;
 794    let event_id = match &msg.event {
 795        MessageEvent::EncryptedOriginal(ev) => ev.event_id.clone(),
 796        MessageEvent::EncryptedRedacted(ev) => ev.event_id.clone(),
 797        MessageEvent::Original(ev, _) => ev.event_id.clone(),
 798        MessageEvent::Local(..) => {
 799            // XXX: Implement reactions for local echos
 800
 801            let msg = "Cannot react to a local echo";
 802            let err = UIError::Failure(msg.into());
 803
 804            return Err(err);
 805        },
 806        MessageEvent::State(ev) => ev.event_id().to_owned(),
 807        MessageEvent::Sticker(ev, ..) => ev.event_id.to_owned(),
 808        MessageEvent::Redacted(_, _) => {
 809            let msg = "Cannot react to a redacted message";
 810            let err = UIError::Failure(msg.into());
 811
 812            return Err(err);
 813        },
 814        MessageEvent::Poll(ev) => ev.event_id().to_owned(),
 815        MessageEvent::UnstablePoll(ev) => ev.event_id().to_owned(),
 816    };
 817
 818    if info.user_reactions_contains(&settings.user_id, &event_id, &emoji) {
 819        let msg = format!("You’ve already reacted to this message with {emoji}");
 820        let err = UIError::Failure(msg);
 821
 822        return Err(err);
 823    }
 824
 825    let reaction = Annotation::new(event_id, emoji);
 826    let msg = ReactionEventContent::new(reaction);
 827
 828    room.send_queue().send(msg.into()).await.map_err(IambError::from)?;
 829
 830    Ok(vec![])
 831}
 832
 833pub async fn msg_redact(
 834    msg: &Message,
 835    worker: &Requester,
 836    id: &RoomId,
 837    reason: Option<String>,
 838    skip_confirm: bool,
 839) -> IambResult<Vec<(Action<IambInfo>, EditContext)>> {
 840    if !skip_confirm {
 841        let msg = "Are you sure you want to redact this message?";
 842        let act = IambAction::Message(MessageAction::Redact(reason, true));
 843        let prompt = PromptYesNo::new(msg, vec![Action::from(act)]);
 844        let prompt = Box::new(prompt);
 845
 846        return Err(UIError::NeedConfirm(prompt));
 847    }
 848
 849    let room = get_joined(id, worker)?;
 850    let event_id = match &msg.event {
 851        MessageEvent::EncryptedOriginal(ev) => ev.event_id.clone(),
 852        MessageEvent::EncryptedRedacted(ev) => ev.event_id.clone(),
 853        MessageEvent::Original(ev, _) => ev.event_id.clone(),
 854        MessageEvent::Local(_, handle, _) => {
 855            let succeeded = handle
 856                .abort()
 857                .await
 858                .map_err(RoomSendQueueError::from)
 859                .map_err(IambError::from)?;
 860
 861            if !succeeded {
 862                let msg = "local echo was already sent; please retry";
 863                let err = UIError::Failure(msg.into());
 864
 865                return Err(err);
 866            }
 867
 868            return Ok(vec![]);
 869        },
 870        MessageEvent::State(ev) => ev.event_id().to_owned(),
 871        MessageEvent::Sticker(ev, ..) => ev.event_id.to_owned(),
 872        MessageEvent::Redacted(_, _) => {
 873            let msg = "Cannot redact already redacted message";
 874            let err = UIError::Failure(msg.into());
 875
 876            return Err(err);
 877        },
 878        MessageEvent::Poll(ev) => ev.event_id().to_owned(),
 879        MessageEvent::UnstablePoll(ev) => ev.event_id().to_owned(),
 880    };
 881
 882    let event_id = event_id.as_ref();
 883    let reason = reason.as_deref();
 884    let _ = room.redact(event_id, reason, None).await.map_err(IambError::from)?;
 885
 886    Ok(vec![])
 887}
 888
 889pub async fn msg_unreact(
 890    msg: &Message,
 891    settings: &ApplicationSettings,
 892    info: &RoomInfo,
 893    worker: &Requester,
 894    id: &RoomId,
 895    reaction: Option<String>,
 896    literal: bool,
 897) -> IambResult<Vec<(Action<IambInfo>, EditContext)>> {
 898    let emoji = match reaction {
 899        reaction if literal => reaction,
 900        Some(reaction) => {
 901            if let Some(emoji) =
 902                emojis::get(&reaction).or_else(|| emojis::get_by_shortcode(&reaction))
 903            {
 904                Some(emoji.to_string())
 905            } else {
 906                let msg = format!(
 907                    "{reaction:?} is not a known Emoji shortcode; do you want to remove exactly {reaction:?}?"
 908                );
 909                let act = IambAction::Message(MessageAction::Unreact(Some(reaction), true));
 910                let prompt = PromptYesNo::new(msg, vec![Action::from(act)]);
 911                let prompt = Box::new(prompt);
 912
 913                return Err(UIError::NeedConfirm(prompt));
 914            }
 915        },
 916        None => None,
 917    };
 918
 919    let room = get_joined(id, worker)?;
 920    let event_id = match &msg.event {
 921        MessageEvent::EncryptedOriginal(ev) => ev.event_id.clone(),
 922        MessageEvent::EncryptedRedacted(ev) => ev.event_id.clone(),
 923        MessageEvent::Original(ev, _) => ev.event_id.clone(),
 924        MessageEvent::Local(..) => {
 925            let msg = "Cannot unreact to a local echo";
 926            let err = UIError::Failure(msg.into());
 927
 928            return Err(err);
 929        },
 930        MessageEvent::State(ev) => ev.event_id().to_owned(),
 931        MessageEvent::Sticker(ev, ..) => ev.event_id.to_owned(),
 932        MessageEvent::Redacted(_, _) => {
 933            let msg = "Cannot unreact to a redacted message";
 934            let err = UIError::Failure(msg.into());
 935
 936            return Err(err);
 937        },
 938        MessageEvent::Poll(ev) => ev.event_id().to_owned(),
 939        MessageEvent::UnstablePoll(ev) => ev.event_id().to_owned(),
 940    };
 941
 942    let reactions = match info.reactions.get(&event_id) {
 943        Some(r) => r,
 944        None => return Ok(vec![]),
 945    };
 946
 947    let reactions = reactions.iter().filter_map(|(event_id, (reaction, user_id, _))| {
 948        if user_id != &settings.user_id {
 949            return None;
 950        }
 951
 952        if let Some(emoji) = &emoji {
 953            if emoji == reaction {
 954                return Some(event_id);
 955            } else {
 956                return None;
 957            }
 958        } else {
 959            return Some(event_id);
 960        }
 961    });
 962
 963    for reaction in reactions {
 964        let _ = room.redact(reaction, None, None).await.map_err(IambError::from)?;
 965    }
 966
 967    Ok(vec![])
 968}
 969
 970pub async fn msg_pin(
 971    pin: bool,
 972    msg: &Message,
 973    id: &RoomId,
 974    worker: &Requester,
 975    settings: &ApplicationSettings,
 976) -> IambResult<Vec<(Action<IambInfo>, EditContext)>> {
 977    let event_id = match &msg.event {
 978        MessageEvent::Local(..) => {
 979            let msg = "Cannot pin a message that hasn't been sent yet";
 980            return Err(UIError::Failure(msg.into()));
 981        },
 982        MessageEvent::Redacted(..) | MessageEvent::EncryptedRedacted(_) if pin => {
 983            let msg = "Cannot pin a redacted message";
 984            return Err(UIError::Failure(msg.into()));
 985        },
 986        event => {
 987            event
 988                .event_id()
 989                .map(ToOwned::to_owned)
 990                .ok_or(IambError::NoSelectedMessage)?
 991        },
 992    };
 993
 994    let room = get_joined(id, worker)?;
 995
 996    let can_pin = room
 997        .power_levels()
 998        .await
 999        .map_err(matrix_sdk::Error::from)
1000        .map_err(IambError::from)?
1001        .user_can_send_state(&settings.user_id, StateEventType::RoomPinnedEvents);
1002
1003    if !can_pin {
1004        return Err(IambError::InsufficientPermission.into());
1005    }
1006
1007    // The state event holds the whole list, so rebuild it from the SDK's latest copy.
1008    let mut pinned = room.pinned_event_ids().unwrap_or_default();
1009    let position = pinned.iter().position(|id| *id == event_id);
1010
1011    match (pin, position) {
1012        (true, Some(_)) => {
1013            let msg = "This message is already pinned";
1014            return Err(UIError::Failure(msg.into()));
1015        },
1016        (false, None) => {
1017            let msg = "This message is not pinned";
1018            return Err(UIError::Failure(msg.into()));
1019        },
1020        (true, None) => {
1021            pinned.push(event_id);
1022        },
1023        (false, Some(idx)) => {
1024            pinned.remove(idx);
1025        },
1026    }
1027
1028    room.send_state_event(RoomPinnedEventsEventContent::new(pinned))
1029        .await
1030        .map_err(IambError::from)?;
1031
1032    Ok(vec![])
1033}
1034
1035macro_rules! delegate {
1036    ($s: expr, $id: ident => $e: expr) => {
1037        match $s.focus {
1038            RoomFocus::Scrollback => {
1039                match $s {
1040                    ChatState { scrollback: $id, .. } => $e,
1041                }
1042            },
1043            RoomFocus::MessageBar => {
1044                match $s {
1045                    ChatState { tbox: $id, .. } => $e,
1046                }
1047            },
1048        }
1049    };
1050}
1051
1052impl WindowOps<IambInfo> for ChatState {
1053    fn draw(&mut self, area: Rect, buf: &mut Buffer, focused: bool, store: &mut ProgramStore) {
1054        Chat::new(store).focus(focused).render(area, buf, self)
1055    }
1056
1057    fn dup(&self, store: &mut ProgramStore) -> Self {
1058        // XXX: I want each WindowSlot to have its own shared buffer, instead of each Room; need to
1059        // find a good way to pass that info here so that it can be part of the content id.
1060        let room_id = self.room_id.clone();
1061        let view = self.thread().cloned().into();
1062        let id = IambBufferId::Room(room_id.clone(), view, RoomFocus::MessageBar);
1063        let ebuf = store.load_buffer(id);
1064        let tbox = TextBoxState::new(ebuf);
1065
1066        ChatState {
1067            room_id,
1068            room: self.room.clone(),
1069
1070            tbox,
1071            sent: self.sent.clone(),
1072            sent_scrollback: history::ScrollbackState::Pending,
1073
1074            scrollback: self.scrollback.dup(store),
1075            focus: self.focus,
1076
1077            reply_to: None,
1078            editing: None,
1079            pending_jump: None,
1080        }
1081    }
1082
1083    fn close(&mut self, _: CloseFlags, _: &mut ProgramStore) -> bool {
1084        // XXX: what's the right closing behaviour for a room?
1085        // Should write send a message?
1086        true
1087    }
1088
1089    fn write(
1090        &mut self,
1091        _: Option<&str>,
1092        _: WriteFlags,
1093        _: &mut ProgramStore,
1094    ) -> IambResult<EditInfo> {
1095        // XXX: what's the right writing behaviour for a room?
1096        // Should write send a message?
1097        Ok(None)
1098    }
1099
1100    fn get_completions(&self) -> Option<CompletionList> {
1101        delegate!(self, w => w.get_completions())
1102    }
1103
1104    fn get_cursor_word(&self, style: &WordStyle) -> Option<String> {
1105        delegate!(self, w => w.get_cursor_word(style))
1106    }
1107
1108    fn get_selected_word(&self) -> Option<String> {
1109        delegate!(self, w => w.get_selected_word())
1110    }
1111}
1112
1113impl Editable<ProgramContext, ProgramStore, IambInfo> for ChatState {
1114    fn editor_command(
1115        &mut self,
1116        act: &EditorAction,
1117        ctx: &ProgramContext,
1118        store: &mut ProgramStore,
1119    ) -> EditResult<EditInfo, IambInfo> {
1120        // Check whether we should automatically switch between the message bar
1121        // or message scrollback, and use an adjusted action if we do so.
1122        let adjusted = self.auto_toggle_focus(act, ctx);
1123        let act = adjusted.as_ref().unwrap_or(act);
1124
1125        // Send typing notice if needed.
1126        self.typing_notice(act, ctx, store);
1127
1128        // And now we can finally run the editor command.
1129        match delegate!(self, w => w.editor_command(act, ctx, store)) {
1130            res @ Ok(_) => res,
1131            Err(EditError::WrongBuffer(IambBufferId::Room(room_id, view, focus)))
1132                if room_id == self.room_id &&
1133                    view == self.thread().into() &&
1134                    act.is_switchable(ctx) =>
1135            {
1136                // Switch focus.
1137                self.focus = focus;
1138
1139                // Run command again.
1140                delegate!(self, w => w.editor_command(act, ctx, store))
1141            },
1142            #[cfg(feature = "desktop")]
1143            Err(EditError::Register(RegisterError::ClipboardImage(data))) => {
1144                let info = store.application.rooms.get_or_default(self.id().to_owned());
1145                let prompt = if self.tbox.get().is_blank() && self.get_reply_to(info).is_none() {
1146                    let msg = "Do you really want to upload the image from your system clipboard?";
1147                    let send = IambAction::Send(SendAction::UploadImage(
1148                        data.width,
1149                        data.height,
1150                        data.bytes,
1151                        false,
1152                    ));
1153                    let prompt = PromptYesNo::new(msg, vec![Action::from(send)]);
1154                    Box::new(prompt) as Box<dyn Dialog<_>>
1155                } else {
1156                    let msg_c = "Upload clipboard image with message bar as caption";
1157                    let act_c =
1158                        SendAction::UploadImage(data.width, data.height, data.bytes.clone(), true);
1159                    let choice_c =
1160                        MultiChoiceItem::new('c', msg_c, vec![IambAction::from(act_c).into()]);
1161
1162                    let msg_y = "Upload clipboard image without caption";
1163                    let act_y =
1164                        SendAction::UploadImage(data.width, data.height, data.bytes.clone(), false);
1165                    let choice_y =
1166                        MultiChoiceItem::new('y', msg_y, vec![IambAction::from(act_y).into()]);
1167
1168                    let msg_n = "Do not upload clipboard image";
1169                    let choice_n = MultiChoiceItem::new('n', msg_n, vec![Action::NoOp]);
1170
1171                    let prompt = MultiChoice::new(vec![choice_c, choice_y, choice_n]);
1172                    Box::new(prompt) as Box<dyn Dialog<_>>
1173                };
1174
1175                Err(EditError::NeedConfirm(prompt))
1176            },
1177            res @ Err(_) => res,
1178        }
1179    }
1180}
1181
1182impl TerminalCursor for ChatState {
1183    fn get_term_cursor(&self) -> Option<(u16, u16)> {
1184        delegate!(self, w => w.get_term_cursor())
1185    }
1186
1187    fn hide_term_cursor(&self) -> bool {
1188        delegate!(self, w => w.hide_term_cursor())
1189    }
1190}
1191
1192impl Jumpable<ProgramContext, IambInfo> for ChatState {
1193    fn jump(
1194        &mut self,
1195        list: PositionList,
1196        dir: MoveDir1D,
1197        count: usize,
1198        ctx: &ProgramContext,
1199    ) -> IambResult<usize> {
1200        delegate!(self, w => w.jump(list, dir, count, ctx))
1201    }
1202}
1203
1204impl Scrollable<ProgramContext, ProgramStore, IambInfo> for ChatState {
1205    fn scroll(
1206        &mut self,
1207        style: &ScrollStyle,
1208        ctx: &ProgramContext,
1209        store: &mut ProgramStore,
1210    ) -> EditResult<EditInfo, IambInfo> {
1211        // Send all scroll commands to the scrollback.
1212        //
1213        // If there's enough message text for scrolling to be necessary,
1214        // navigating with movement keys should be enough to do the job.
1215        self.scrollback.scroll(style, ctx, store)
1216    }
1217}
1218
1219impl PromptActions<ProgramContext, ProgramStore, IambInfo> for ChatState {
1220    fn submit(
1221        &mut self,
1222        ctx: &ProgramContext,
1223        _: &mut ProgramStore,
1224    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
1225        let act = SendAction::Submit;
1226
1227        Ok(vec![(IambAction::from(act).into(), ctx.clone())])
1228    }
1229
1230    fn abort(
1231        &mut self,
1232        empty: bool,
1233        _: &ProgramContext,
1234        _: &mut ProgramStore,
1235    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
1236        let text = self.tbox.get();
1237
1238        if empty && text.is_blank() {
1239            return Ok(vec![]);
1240        }
1241
1242        let text = self.reset().trim();
1243
1244        if text.is_empty() {
1245            let _ = self.sent.end();
1246        } else {
1247            self.sent.select(text);
1248        }
1249
1250        return Ok(vec![]);
1251    }
1252
1253    fn recall(
1254        &mut self,
1255        filter: &RecallFilter,
1256        dir: &MoveDir1D,
1257        count: &Count,
1258        ctx: &ProgramContext,
1259        _: &mut ProgramStore,
1260    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
1261        let count = ctx.resolve(count);
1262        let rope = self.tbox.get();
1263
1264        let text = self.sent.recall(&rope, &mut self.sent_scrollback, filter, *dir, count);
1265
1266        if let Some(text) = text {
1267            self.tbox.set_text(text);
1268        }
1269
1270        Ok(vec![])
1271    }
1272}
1273
1274impl Promptable<ProgramContext, ProgramStore, IambInfo> for ChatState {
1275    fn prompt(
1276        &mut self,
1277        act: &PromptAction,
1278        ctx: &ProgramContext,
1279        store: &mut ProgramStore,
1280    ) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
1281        if let RoomFocus::Scrollback = self.focus {
1282            return self.scrollback.prompt(act, ctx, store);
1283        }
1284
1285        match act {
1286            PromptAction::Submit => self.submit(ctx, store),
1287            PromptAction::Abort(empty) => self.abort(*empty, ctx, store),
1288            PromptAction::Recall(filter, dir, count) => self.recall(filter, dir, count, ctx, store),
1289        }
1290    }
1291}
1292
1293/// [StatefulWidget] for Matrix rooms.
1294pub struct Chat<'a> {
1295    store: &'a mut ProgramStore,
1296    focused: bool,
1297}
1298
1299impl<'a> Chat<'a> {
1300    pub fn new(store: &'a mut ProgramStore) -> Chat<'a> {
1301        Chat { store, focused: false }
1302    }
1303
1304    pub fn focus(mut self, focused: bool) -> Self {
1305        self.focused = focused;
1306        self
1307    }
1308}
1309
1310impl StatefulWidget for Chat<'_> {
1311    type State = ChatState;
1312
1313    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
1314        state.complete_pending_jump(self.store);
1315
1316        let info = self.store.application.rooms.get_or_default(state.id().to_owned());
1317        let settings = &self.store.application.settings;
1318        let theme = &settings.theme;
1319        let mut msgbar_style = theme.msgbar.default;
1320        let mut msgbar_readonly = false;
1321
1322        // Determine whether we have a description to show for the message bar.
1323        let mut desc_spans = match (&state.editing, &state.reply_to, state.thread()) {
1324            (None, None, None) => {
1325                if state.room.is_tombstoned() {
1326                    Some(
1327                        Line::from(vec![
1328                            Span::from("This room has been upgraded! ").bold(),
1329                            Span::from("Use "),
1330                            Span::from(":follow").bold(),
1331                            Span::from(" to join everyone in the new room."),
1332                        ])
1333                        .centered(),
1334                    )
1335                } else {
1336                    None
1337                }
1338            },
1339            (None, None, Some(_)) => Some(Line::from("Replying in thread")),
1340            (Some(_), None, None) => Some(Line::from("Editing message")),
1341            (Some(_), None, Some(_)) => Some(Line::from("Editing message in thread")),
1342            (editing, Some(_), thread) => {
1343                state.get_reply_to(info).map(|msg| {
1344                    let user = self
1345                        .store
1346                        .application
1347                        .settings
1348                        .get_user_span(msg.sender.as_ref(), info.display_names.get(&msg.sender));
1349                    let prefix = match (editing.is_some(), thread.is_some()) {
1350                        (true, false) => Span::from("Editing reply to "),
1351                        (true, true) => Span::from("Editing reply in thread to "),
1352                        (false, false) => Span::from("Replying to "),
1353                        (false, true) => Span::from("Replying in thread to "),
1354                    };
1355                    Line::from(vec![prefix, user])
1356                })
1357            },
1358        };
1359
1360        if desc_spans.is_none() &&
1361            let Some((user_id, _)) = info
1362                .identity_violations
1363                .iter()
1364                .find(|(_, state)| **state == IdentityState::PinViolation)
1365        {
1366            let text1 = Span::from("Cryptographic identity of ");
1367            let user = self
1368                .store
1369                .application
1370                .settings
1371                .get_user_span(user_id, info.display_names.get(user_id));
1372            let text2 =
1373                Span::from(format!(" has changed. Use `:verify pin {user_id}` to acknowledge."));
1374
1375            desc_spans = Some(Line::from(vec![text1, user, text2]));
1376        }
1377
1378        if let Some((user_id, _)) = info
1379            .identity_violations
1380            .iter()
1381            .find(|(_, state)| **state == IdentityState::VerificationViolation)
1382        {
1383            state.tbox.set_text(format!("Cryptographic identity of {user_id} was reset. Use `:verify withdraw {user_id}` to acknowledge"));
1384            msgbar_readonly = true;
1385            msgbar_style = theme.cmdbar.error;
1386        }
1387
1388        // Determine the region to show each UI element.
1389        let lines = state.tbox.has_lines(5).max(1) as u16;
1390        let drawh = area.height;
1391        let texth = lines.min(drawh).clamp(1, 5);
1392        let desch = if desc_spans.is_some() {
1393            drawh.saturating_sub(texth).min(1)
1394        } else {
1395            0
1396        };
1397        let scrollh = drawh.saturating_sub(texth).saturating_sub(desch);
1398
1399        let scrollarea = Rect::new(area.x, area.y, area.width, scrollh);
1400        let descarea = Rect::new(area.x, scrollarea.y + scrollh, area.width, desch);
1401        let textarea = Rect::new(area.x, descarea.y + desch, area.width, texth);
1402
1403        // Render the message bar and any description for it.
1404        if let Some(desc_spans) = desc_spans {
1405            Paragraph::new(desc_spans).render(descarea, buf);
1406        }
1407
1408        let encryption_settings = &settings.tunables.encryption;
1409        let encryption_indicator = encryption_settings.get_indicator(
1410            EncryptionIndicatorLocation::PROMPT,
1411            state.room().encryption_state(),
1412            theme,
1413        );
1414        let input_prompt = settings.tunables.input_prompt.as_deref();
1415        let prompt = match (self.focused, encryption_indicator, input_prompt) {
1416            // User has both encryption indicator and custom prompt, combine them:
1417            (false, Some(i), Some(p)) => Line::from(crate::util::space(i.width() + p.width())),
1418            (true, Some(i), Some(p)) => Line::from(vec![i, Span::from(p)]),
1419
1420            // User has custom prompt, use that:
1421            (false, None, Some(p)) => Line::from(crate::util::space(p.width())),
1422            (true, None, Some(p)) => Line::from(p),
1423
1424            // User has encryption indicator, use that as prompt:
1425            (false, Some(i), None) => Line::from(crate::util::space(i.width())),
1426            (true, Some(i), None) => Line::from(i),
1427
1428            // User has no encryption indicator, no custom prompt, so show "> ":
1429            (false, None, None) => Line::from(crate::util::space(2)),
1430            (true, None, None) => Line::from("> "),
1431        };
1432
1433        let tbox = TextBox::new().style(msgbar_style).prompt(prompt);
1434        state.tbox.set_readonly(msgbar_readonly);
1435        state
1436            .tbox
1437            .set_ignorecase(self.store.application.settings.tunables.ignorecase);
1438        tbox.render(textarea, buf, &mut state.tbox);
1439        if msgbar_readonly {
1440            // Clear the msgbar here. If it is still readonly on the next render, the content will
1441            // be overwritten anyway and if not the content would stay.
1442            state.tbox.reset();
1443        }
1444
1445        // Render the message scrollback.
1446        let scrollback_style = self.store.application.settings.theme.timeline.default;
1447        let scrollback_focused = state.focus.is_scrollback() && self.focused;
1448        let scrollback = Scrollback::new(self.store)
1449            .style(scrollback_style)
1450            .focus(scrollback_focused)
1451            .room_focus(self.focused);
1452        scrollback.render(scrollarea, buf, &mut state.scrollback);
1453    }
1454}
1455
1456/// Returns the `geo:` URI that a location message refers to.
1457fn location_geo_uri(msgtype: &MessageType) -> Option<&str> {
1458    match msgtype {
1459        MessageType::Location(content) => Some(content.geo_uri()),
1460        _ => None,
1461    }
1462}
1463
1464fn open_command(open_command: Option<&Vec<String>>, target: OsString) -> IambResult<()> {
1465    if let Some(mut cmd) = open_command.and_then(cmd) {
1466        cmd.arg(target);
1467        cmd.spawn()?;
1468        return Ok(());
1469    } else {
1470        // open::that may not return until the spawned program closes.
1471        tokio::task::spawn_blocking(move || {
1472            return open::that(target);
1473        });
1474        return Ok(());
1475    }
1476}
1477
1478/// Extract mentions from `https://matrix.to` html links
1479fn extract_mentions(content: &TextMessageEventContent) -> Mentions {
1480    let Some(formatted) = content.formatted.as_ref() else {
1481        return Mentions::new();
1482    };
1483    if !matches!(formatted.format, MessageFormat::Html) {
1484        return Mentions::new();
1485    }
1486    extract_mentions_str(formatted.body.as_str())
1487}
1488
1489fn extract_mentions_str(html: &str) -> Mentions {
1490    let re = Regex::new(r#"<a href="(https://matrix.to/#/@[^"]*:[^"]*)"[^>]*>"#).unwrap();
1491
1492    let user_ids = re.captures_iter(html).filter_map(|capture| {
1493        let link = capture.get(1)?.as_str();
1494        let uri = MatrixToUri::parse(link).ok()?;
1495
1496        if let MatrixId::User(user_id) = uri.id() {
1497            Some(user_id.to_owned())
1498        } else {
1499            None
1500        }
1501    });
1502
1503    Mentions::with_user_ids(user_ids)
1504}
1505
1506fn cmd(open_command: &Vec<String>) -> Option<Command> {
1507    if let [program, args @ ..] = open_command.as_slice() {
1508        let mut cmd = Command::new(program);
1509        cmd.args(args);
1510        return Some(cmd);
1511    }
1512    None
1513}
1514
1515pub fn auto_toggle_focus(
1516    focus: &mut RoomFocus,
1517    act: &EditorAction,
1518    ctx: &ProgramContext,
1519    scrollback: &ScrollbackState,
1520    tbox: &mut TextBoxState<IambInfo>,
1521) -> Option<EditorAction> {
1522    let is_insert = ctx.get_insert_style().is_some();
1523
1524    match (focus, act) {
1525        (f @ RoomFocus::Scrollback, _) if is_insert => {
1526            // Insert mode commands should switch focus.
1527            f.toggle();
1528            None
1529        },
1530        (f @ RoomFocus::Scrollback, EditorAction::InsertText(_)) => {
1531            // Pasting or otherwise inserting text should switch.
1532            f.toggle();
1533            None
1534        },
1535        (
1536            f @ RoomFocus::Scrollback,
1537            EditorAction::Edit(
1538                op,
1539                EditTarget::Motion(mov @ MoveType::Line(MoveDir1D::Next), count),
1540            ),
1541        ) if ctx.resolve(op).is_motion() => {
1542            let count = ctx.resolve(count);
1543
1544            if count > 0 && scrollback.is_latest() {
1545                // Trying to move down a line when already at the end of room history should
1546                // switch.
1547                f.toggle();
1548
1549                // And decrement the count for the action.
1550                let count = count.saturating_sub(1).into();
1551                let target = EditTarget::Motion(mov.clone(), count);
1552                let dec = EditorAction::Edit(op.clone(), target);
1553
1554                Some(dec)
1555            } else {
1556                None
1557            }
1558        },
1559        (
1560            f @ RoomFocus::MessageBar,
1561            EditorAction::Edit(
1562                op,
1563                EditTarget::Motion(mov @ MoveType::Line(MoveDir1D::Previous), count),
1564            ),
1565        ) if !is_insert && ctx.resolve(op).is_motion() => {
1566            let count = ctx.resolve(count);
1567
1568            if count > 0 && tbox.get_cursor().y == 0 {
1569                // Trying to move up a line when already at the top of the msgbar should
1570                // switch as long as we're not in Insert mode.
1571                f.toggle();
1572
1573                // And decrement the count for the action.
1574                let count = count.saturating_sub(1).into();
1575                let target = EditTarget::Motion(mov.clone(), count);
1576                let dec = EditorAction::Edit(op.clone(), target);
1577
1578                Some(dec)
1579            } else {
1580                None
1581            }
1582        },
1583        (RoomFocus::Scrollback, _) | (RoomFocus::MessageBar, _) => {
1584            // Do not switch.
1585            None
1586        },
1587    }
1588}
1589
1590#[cfg(test)]
1591mod tests {
1592    use super::*;
1593
1594    use modalkit::actions::{EditAction, InsertTextAction};
1595
1596    use crate::tests::{TEST_ROOM1_ID, mock_store};
1597
1598    fn mentions_in(html: &str) -> Vec<String> {
1599        extract_mentions_str(html).user_ids.iter().map(|u| u.to_string()).collect()
1600    }
1601
1602    #[test]
1603    fn test_location_geo_uri() {
1604        use matrix_sdk::ruma::events::room::message::{
1605            LocationMessageEventContent,
1606            TextMessageEventContent,
1607        };
1608
1609        let location = MessageType::Location(LocationMessageEventContent::new(
1610            "geo test".into(),
1611            "geo:51.5072,-0.1276".into(),
1612        ));
1613        assert_eq!(location_geo_uri(&location), Some("geo:51.5072,-0.1276"));
1614
1615        let text = MessageType::Text(TextMessageEventContent::plain("not a location"));
1616        assert_eq!(location_geo_uri(&text), None);
1617    }
1618
1619    #[test]
1620    fn test_extract_mentions_normal() {
1621        let res = mentions_in(r#"<a href="https://matrix.to/#/@user:example.com">user</a>"#);
1622        assert_eq!(res, vec!["@user:example.com"]);
1623    }
1624
1625    #[test]
1626    fn test_extract_mentions_ignore_parameters() {
1627        let res =
1628            mentions_in(r#"<a href="https://matrix.to/#/@user:example.com?via=example.com">u</a>"#);
1629        assert_eq!(res, vec!["@user:example.com"]);
1630    }
1631
1632    #[test]
1633    fn test_extract_mentions_title() {
1634        let twim = r#"<a href="https://matrix.to/#/@this-week-in:matrix.org" title="@this-week-in:matrix.org">TWIM</a>"#;
1635        let res = mentions_in(twim);
1636        assert_eq!(res, vec!["@this-week-in:matrix.org"]);
1637    }
1638
1639    #[test]
1640    fn test_extract_mentions_multiple_dedupe() {
1641        let res = mentions_in(
1642            r#"<a href="https://matrix.to/#/@a:example.com">a</a> and
1643                   <a href="https://matrix.to/#/@b:example.com">b</a> and
1644                   <a href="https://matrix.to/#/@a:example.com">a again</a>"#,
1645        );
1646        assert_eq!(res, vec!["@a:example.com", "@b:example.com"]);
1647    }
1648
1649    #[test]
1650    fn test_extract_mentions_skips_invalid_links() {
1651        let empty = vec![
1652            r#"<a href="https://matrix.to/#/@user:example.com/$eventid">e</a>"#,
1653            r#"<a href="https://matrix.to/#/@bob:">bob</a>"#,
1654            r#"<a href="https://matrix.to/#/@user:%E4%BE%8B.com">x</a>"#,
1655        ];
1656
1657        for html in empty {
1658            assert!(mentions_in(html).is_empty());
1659        }
1660
1661        // An invalid link is ignored, but a valid one is still extracted:
1662        assert_eq!(
1663            mentions_in(
1664                r#"<a href="https://matrix.to/#/@bob:">bob</a>
1665                   <a href="https://matrix.to/#/@user:example.com">user</a>"#
1666            ),
1667            vec!["@user:example.com"]
1668        );
1669    }
1670
1671    #[test]
1672    fn test_extract_mentions_ignores_unformatted() {
1673        // URIs in plain text messages don't count as mentions:
1674        let plain = TextMessageEventContent::plain(
1675            r#"<a href="https://matrix.to/#/@user:example.com">user</a>"#,
1676        );
1677        assert!(extract_mentions(&plain).user_ids.is_empty());
1678
1679        // Links to things other than users aren't mentions:
1680        let room = r#"<a href="https://matrix.to/#/#room:example.com">room</a>"#;
1681        assert!(mentions_in(room).is_empty());
1682
1683        let nonmx = r#"<a href="https://example.com/@user:example.com">nope</a>"#;
1684        assert!(mentions_in(nonmx).is_empty());
1685    }
1686
1687    macro_rules! move_line {
1688        ($dir: expr, $count: expr) => {
1689            EditorAction::Edit(
1690                EditAction::Motion.into(),
1691                EditTarget::Motion(MoveType::Line($dir), $count.into()),
1692            )
1693        };
1694    }
1695
1696    #[tokio::test]
1697    async fn test_auto_focus() {
1698        let mut store = mock_store().await;
1699        let ctx = ProgramContext::default();
1700
1701        let room_id = TEST_ROOM1_ID.clone();
1702        let scrollback = ScrollbackState::new(room_id.clone(), None);
1703
1704        let id = IambBufferId::Room(room_id, RoomView::Main, RoomFocus::MessageBar);
1705        let ebuf = store.load_buffer(id);
1706        let mut tbox = TextBoxState::new(ebuf);
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(&mut focused, &act, &ctx, &scrollback, &mut tbox);
1718        assert_eq!(focused, RoomFocus::MessageBar);
1719        assert!(res.is_none());
1720
1721        // Going down in message bar doesn't toggle:
1722        let act = move_line!(MoveDir1D::Next, 1);
1723        let res = auto_toggle_focus(&mut focused, &act, &ctx, &scrollback, &mut tbox);
1724        assert_eq!(focused, RoomFocus::MessageBar);
1725        assert!(res.is_none());
1726
1727        // But going up will:
1728        let act = move_line!(MoveDir1D::Previous, 1);
1729        let res = auto_toggle_focus(&mut focused, &act, &ctx, &scrollback, &mut tbox);
1730        assert_eq!(focused, RoomFocus::Scrollback);
1731        assert_eq!(res, Some(move_line!(MoveDir1D::Previous, 0)));
1732
1733        // Going up in scrollback doesn't toggle:
1734        let act = move_line!(MoveDir1D::Previous, 1);
1735        let res = auto_toggle_focus(&mut focused, &act, &ctx, &scrollback, &mut tbox);
1736        assert_eq!(focused, RoomFocus::Scrollback);
1737        assert_eq!(res, None);
1738
1739        // And then go back down:
1740        let act = move_line!(MoveDir1D::Next, 1);
1741        let res = auto_toggle_focus(&mut focused, &act, &ctx, &scrollback, &mut tbox);
1742        assert_eq!(focused, RoomFocus::MessageBar);
1743        assert_eq!(res, Some(move_line!(MoveDir1D::Next, 0)));
1744
1745        // Go up 2 will go up 1 in scrollback:
1746        let act = move_line!(MoveDir1D::Previous, 2);
1747        let res = auto_toggle_focus(&mut focused, &act, &ctx, &scrollback, &mut tbox);
1748        assert_eq!(focused, RoomFocus::Scrollback);
1749        assert_eq!(res, Some(move_line!(MoveDir1D::Previous, 1)));
1750
1751        // Go down 3 will go down 2 in messagebar:
1752        let act = move_line!(MoveDir1D::Next, 3);
1753        let res = auto_toggle_focus(&mut focused, &act, &ctx, &scrollback, &mut tbox);
1754        assert_eq!(focused, RoomFocus::MessageBar);
1755        assert_eq!(res, Some(move_line!(MoveDir1D::Next, 2)));
1756    }
1757}