src/windows/room/chat.rs

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