src/base.rs

2651 lines · 85030 bytes

   1//! # Common types and utilities
   2//!
   3//! The types defined here get used throughout iamb.
   4use std::borrow::Cow;
   5use std::collections::hash_map::{Entry, IntoIter};
   6use std::collections::{BTreeSet, HashMap, HashSet};
   7use std::convert::TryFrom;
   8use std::fmt::{self, Display};
   9use std::hash::Hash;
  10use std::str::FromStr;
  11use std::sync::Arc;
  12use std::time::{Duration, Instant};
  13
  14use emojis::Emoji;
  15
  16use matrix_sdk::ruma::events::receipt::ReceiptThread;
  17use matrix_sdk::ruma::events::room::MediaSource;
  18use matrix_sdk::ruma::events::sticker::StickerEvent;
  19use matrix_sdk::ruma::OwnedTransactionId;
  20use ratatui::{
  21    buffer::Buffer,
  22    layout::{Alignment, Rect},
  23    text::{Line, Span},
  24    widgets::{Paragraph, Widget},
  25};
  26use ratatui_image::picker::{Picker, ProtocolType};
  27use serde::{
  28    de::Error as SerdeError,
  29    de::Visitor,
  30    Deserialize,
  31    Deserializer,
  32    Serialize,
  33    Serializer,
  34};
  35use tokio::sync::Mutex as AsyncMutex;
  36use url::Url;
  37
  38use matrix_sdk::{
  39    encryption::verification::SasVerification,
  40    room::Room as MatrixRoom,
  41    ruma::{
  42        events::{
  43            reaction::ReactionEvent,
  44            relation::{Replacement, Thread},
  45            room::encrypted::RoomEncryptedEvent,
  46            room::message::{
  47                OriginalRoomMessageEvent,
  48                Relation,
  49                RoomMessageEvent,
  50                RoomMessageEventContent,
  51                RoomMessageEventContentWithoutRelation,
  52            },
  53            room::redaction::{OriginalSyncRoomRedactionEvent, SyncRoomRedactionEvent},
  54            tag::{TagName, Tags},
  55            AnySyncStateEvent,
  56            MessageLikeEvent,
  57        },
  58        presence::PresenceState,
  59        EventId,
  60        OwnedEventId,
  61        OwnedRoomId,
  62        OwnedUserId,
  63        RoomId,
  64        UserId,
  65    },
  66    RoomState as MatrixRoomState,
  67};
  68
  69use modalkit::{
  70    actions::Action,
  71    editing::{
  72        application::{
  73            ApplicationAction,
  74            ApplicationContentId,
  75            ApplicationError,
  76            ApplicationInfo,
  77            ApplicationStore,
  78            ApplicationWindowId,
  79        },
  80        completion::{complete_path, Completer, CompletionMap},
  81        context::EditContext,
  82        cursor::Cursor,
  83        rope::EditRope,
  84        store::Store,
  85    },
  86    env::vim::{
  87        command::{CommandContext, CommandDescription, VimCommand, VimCommandMachine},
  88        keybindings::VimMachine,
  89    },
  90    errors::{UIError, UIResult},
  91    key::TerminalKey,
  92    keybindings::SequenceStatus,
  93    prelude::{CommandType, WordStyle},
  94};
  95
  96use crate::config::ImagePreviewProtocolValues;
  97use crate::notifications::NotificationHandle;
  98use crate::preview::{source_from_event, PreviewManager};
  99use crate::{
 100    message::{Message, MessageEvent, MessageKey, MessageTimeStamp, Messages},
 101    worker::Requester,
 102    ApplicationSettings,
 103};
 104
 105/// The set of characters used in different Matrix IDs.
 106pub const MATRIX_ID_WORD: WordStyle = WordStyle::CharSet(is_mxid_char);
 107
 108/// Find the boundaries for a Matrix username, room alias, or room ID.
 109///
 110/// Technically "[" and "]" should be here since IPv6 addresses are allowed
 111/// in the server name, but in practice that should be uncommon, and people
 112/// can just use `gf` and friends in Visual mode instead.
 113fn is_mxid_char(c: char) -> bool {
 114    return c >= 'a' && c <= 'z' ||
 115        c >= 'A' && c <= 'Z' ||
 116        c >= '0' && c <= '9' ||
 117        ":-./@_#!".contains(c);
 118}
 119
 120const ROOM_FETCH_DEBOUNCE: Duration = Duration::from_secs(2);
 121
 122/// Empty type used solely to implement [ApplicationInfo].
 123#[derive(Clone, Debug, Eq, PartialEq)]
 124pub enum IambInfo {}
 125
 126/// An action taken against an ongoing verification request.
 127#[derive(Clone, Debug, Eq, PartialEq)]
 128pub enum VerifyAction {
 129    /// Accept a verification request.
 130    Accept,
 131
 132    /// Cancel an in-progress verification.
 133    Cancel,
 134
 135    /// Confirm an in-progress verification.
 136    Confirm,
 137
 138    /// Reject an in-progress verification due to mismatched Emoji.
 139    Mismatch,
 140}
 141
 142/// An action taken against the currently selected message.
 143#[derive(Clone, Debug, Eq, PartialEq)]
 144pub enum MessageAction {
 145    /// Cance the current reply or edit.
 146    ///
 147    /// The [bool] argument indicates whether to skip confirmation for clearing the message bar.
 148    Cancel(bool),
 149
 150    /// Download an attachment to the given path.
 151    ///
 152    /// The second argument controls whether to overwrite any already existing file at the
 153    /// destination path, or to open the attachment after downloading.
 154    Download(Option<String>, DownloadFlags),
 155
 156    /// Edit a sent message.
 157    Edit,
 158
 159    /// React to a message with an Emoji.
 160    ///
 161    /// `:react` will by default try to convert the [String] argument to an Emoji, and error when
 162    /// it doesn't recognize it. The second [bool] argument forces it to be interpreted literally
 163    /// when it is `true`.
 164    React(String, bool),
 165
 166    /// Redact a message, with an optional reason.
 167    ///
 168    /// The [bool] argument indicates whether to skip confirmation.
 169    Redact(Option<String>, bool),
 170
 171    /// Reply to a message.
 172    Reply,
 173
 174    /// Go to the message the hovered message replied to.
 175    Replied,
 176
 177    /// Unreact to a message.
 178    ///
 179    /// If no specific Emoji to remove to is specified, then all reactions from the user on the
 180    /// message are removed.
 181    ///
 182    /// Like `:react`, `:unreact` will by default try to convert the [String] argument to an Emoji,
 183    /// and error when it doesn't recognize it. The second [bool] argument forces it to be
 184    /// interpreted literally when it is `true`.
 185    Unreact(Option<String>, bool),
 186}
 187
 188/// An action taken in the currently selected space.
 189#[derive(Clone, Debug, Eq, PartialEq)]
 190pub enum SpaceAction {
 191    /// Add a room or update metadata.
 192    ///
 193    /// The [`Option<String>`] argument is the order parameter.
 194    /// The [`bool`] argument indicates whether the room is suggested.
 195    SetChild(OwnedRoomId, Option<String>, bool),
 196
 197    /// Remove the selected room.
 198    RemoveChild,
 199}
 200
 201/// The type of room being created.
 202#[derive(Clone, Debug, Eq, PartialEq)]
 203pub enum CreateRoomType {
 204    /// A standard chat room.
 205    Room,
 206
 207    /// A Matrix space.
 208    Space,
 209}
 210
 211bitflags::bitflags! {
 212    /// Available options for newly created rooms.
 213    #[derive(Clone, Debug, Eq, PartialEq)]
 214    pub struct CreateRoomFlags: u32 {
 215        /// No flags specified.
 216        const NONE = 0b00000000;
 217
 218        /// Make the room public.
 219        const PUBLIC = 0b00000001;
 220
 221        /// Encrypt this room.
 222        const ENCRYPTED = 0b00000010;
 223    }
 224}
 225
 226bitflags::bitflags! {
 227    /// Available options when downloading files.
 228    #[derive(Clone, Debug, Eq, PartialEq)]
 229    pub struct DownloadFlags: u32 {
 230        /// No flags specified.
 231        const NONE = 0b00000000;
 232
 233        /// Overwrite file if it already exists.
 234        const FORCE = 0b00000001;
 235
 236        /// Open file after downloading.
 237        const OPEN = 0b00000010;
 238    }
 239}
 240
 241/// Fields that rooms and spaces can be sorted by.
 242#[derive(Clone, Debug, Eq, PartialEq)]
 243pub enum SortFieldRoom {
 244    /// Sort rooms by whether they have the Favorite tag.
 245    Favorite,
 246
 247    /// Sort rooms by whether they have the Low Priority tag.
 248    LowPriority,
 249
 250    /// Sort rooms by their room name.
 251    Name,
 252
 253    /// Sort rooms by their canonical room alias.
 254    Alias,
 255
 256    /// Sort rooms by their Matrix room identifier.
 257    RoomId,
 258
 259    /// Sort rooms by the server portion of their canonical room alias.
 260    ///
 261    /// If the room has no canonical alias, and the room identifier uses the version 1 syntax
 262    /// for formatting the MXID, then this will fall back to using the server portion of the
 263    /// identifier (aka, the "namespace").
 264    Server,
 265
 266    /// Sort rooms by whether they have unread messages.
 267    Unread,
 268
 269    /// Sort rooms by the timestamps of their most recent messages.
 270    Recent,
 271
 272    /// Sort rooms by whether they are invites.
 273    Invite,
 274}
 275
 276/// Fields that users can be sorted by.
 277#[derive(Clone, Debug, Eq, PartialEq)]
 278pub enum SortFieldUser {
 279    PowerLevel,
 280    UserId,
 281    LocalPart,
 282    Server,
 283}
 284
 285/// Whether to use the default sort direction for a field, or to reverse it.
 286#[derive(Clone, Debug, Eq, PartialEq)]
 287pub enum SortOrder {
 288    Ascending,
 289    Descending,
 290}
 291
 292/// One of the columns to sort on.
 293#[derive(Clone, Debug, Eq, PartialEq)]
 294pub struct SortColumn<T>(pub T, pub SortOrder);
 295
 296impl<'de> Deserialize<'de> for SortColumn<SortFieldRoom> {
 297    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
 298    where
 299        D: Deserializer<'de>,
 300    {
 301        deserializer.deserialize_str(SortRoomVisitor)
 302    }
 303}
 304
 305/// [serde] visitor for deserializing [SortColumn] for rooms and spaces.
 306struct SortRoomVisitor;
 307
 308impl Visitor<'_> for SortRoomVisitor {
 309    type Value = SortColumn<SortFieldRoom>;
 310
 311    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
 312        formatter.write_str("a valid field for sorting rooms")
 313    }
 314
 315    fn visit_str<E>(self, mut value: &str) -> Result<Self::Value, E>
 316    where
 317        E: SerdeError,
 318    {
 319        if value.is_empty() {
 320            return Err(E::custom("Invalid sort field"));
 321        }
 322
 323        let order = if value.starts_with('~') {
 324            value = &value[1..];
 325            SortOrder::Descending
 326        } else {
 327            SortOrder::Ascending
 328        };
 329
 330        let field = match value {
 331            "favorite" => SortFieldRoom::Favorite,
 332            "lowpriority" => SortFieldRoom::LowPriority,
 333            "recent" => SortFieldRoom::Recent,
 334            "unread" => SortFieldRoom::Unread,
 335            "name" => SortFieldRoom::Name,
 336            "alias" => SortFieldRoom::Alias,
 337            "id" => SortFieldRoom::RoomId,
 338            "server" => SortFieldRoom::Server,
 339            "invite" => SortFieldRoom::Invite,
 340            _ => {
 341                let msg = format!("Unknown sort field: {value:?}");
 342                return Err(E::custom(msg));
 343            },
 344        };
 345
 346        Ok(SortColumn(field, order))
 347    }
 348}
 349
 350impl<'de> Deserialize<'de> for SortColumn<SortFieldUser> {
 351    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
 352    where
 353        D: Deserializer<'de>,
 354    {
 355        deserializer.deserialize_str(SortUserVisitor)
 356    }
 357}
 358
 359/// [serde] visitor for deserializing [SortColumn] for users.
 360struct SortUserVisitor;
 361
 362impl Visitor<'_> for SortUserVisitor {
 363    type Value = SortColumn<SortFieldUser>;
 364
 365    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
 366        formatter.write_str("a valid field for sorting rooms")
 367    }
 368
 369    fn visit_str<E>(self, mut value: &str) -> Result<Self::Value, E>
 370    where
 371        E: SerdeError,
 372    {
 373        if value.is_empty() {
 374            return Err(E::custom("Invalid field for sorting users"));
 375        }
 376
 377        let order = if value.starts_with('~') {
 378            value = &value[1..];
 379            SortOrder::Descending
 380        } else {
 381            SortOrder::Ascending
 382        };
 383
 384        let field = match value {
 385            "id" => SortFieldUser::UserId,
 386            "localpart" => SortFieldUser::LocalPart,
 387            "server" => SortFieldUser::Server,
 388            "power" => SortFieldUser::PowerLevel,
 389            _ => {
 390                let msg = format!("Unknown sort field: {value:?}");
 391                return Err(E::custom(msg));
 392            },
 393        };
 394
 395        Ok(SortColumn(field, order))
 396    }
 397}
 398
 399/// A room property.
 400#[derive(Clone, Debug, Eq, PartialEq)]
 401pub enum RoomField {
 402    /// The room's history visibility.
 403    History,
 404
 405    /// The room name.
 406    Name,
 407
 408    /// The room id.
 409    Id,
 410
 411    /// A room tag.
 412    Tag(TagName),
 413
 414    /// The room topic.
 415    Topic,
 416
 417    /// Notification level.
 418    NotificationMode,
 419
 420    /// The room's entire list of alternative aliases.
 421    Aliases,
 422
 423    /// A specific alternative alias to the room.
 424    Alias(String),
 425
 426    /// The room's canonical alias.
 427    CanonicalAlias,
 428}
 429
 430/// An action that operates on a room member.
 431#[derive(Clone, Debug, Eq, PartialEq)]
 432pub enum MemberUpdateAction {
 433    Ban,
 434    Kick,
 435    Unban,
 436}
 437
 438impl Display for MemberUpdateAction {
 439    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 440        match self {
 441            MemberUpdateAction::Ban => write!(f, "ban"),
 442            MemberUpdateAction::Kick => write!(f, "kick"),
 443            MemberUpdateAction::Unban => write!(f, "unban"),
 444        }
 445    }
 446}
 447
 448/// An action that operates on a focused room.
 449#[derive(Clone, Debug, Eq, PartialEq)]
 450pub enum RoomAction {
 451    /// Accept an invitation to join this room.
 452    InviteAccept,
 453
 454    /// Reject an invitation to join this room.
 455    InviteReject,
 456
 457    /// Invite a user to this room.
 458    InviteSend(OwnedUserId),
 459
 460    /// Leave this room.
 461    Leave(bool),
 462
 463    /// Update a user's membership in this room.
 464    MemberUpdate(MemberUpdateAction, String, Option<String>, bool),
 465
 466    /// Open the members window.
 467    Members(Box<CommandContext>),
 468
 469    /// Set whether a room is a direct message.
 470    SetDirect(bool),
 471
 472    /// Set a room property.
 473    Set(RoomField, String),
 474
 475    /// Unset a room property.
 476    Unset(RoomField),
 477
 478    /// List the values in a list room property.
 479    Show(RoomField),
 480
 481    /// Mark the room as read/unread.
 482    SetUnread(bool),
 483}
 484
 485/// An action that sends a message to a room.
 486#[derive(Clone, Debug, Eq, PartialEq)]
 487pub enum SendAction {
 488    /// Send the text in the message bar.
 489    Submit,
 490
 491    /// Send text provided from an external editor.
 492    SubmitFromEditor,
 493
 494    /// Upload a file.
 495    Upload(String),
 496
 497    /// Upload the image data.
 498    UploadImage(usize, usize, Cow<'static, [u8]>),
 499}
 500
 501/// An action performed against the user's homeserver.
 502#[derive(Clone, Debug, Eq, PartialEq)]
 503pub enum HomeserverAction {
 504    /// Create a new room with an optional localpart.
 505    CreateRoom(Option<String>, CreateRoomType, CreateRoomFlags),
 506    Logout(String, bool),
 507    /// Forget all left rooms
 508    Forget,
 509}
 510
 511/// An action performed against the user's room keys.
 512#[derive(Clone, Debug, Eq, PartialEq)]
 513pub enum KeysAction {
 514    /// Export room keys to a file, encrypted with a passphrase.
 515    Export(String, String),
 516    /// Import room keys from a file, encrypted with a passphrase.
 517    Import(String, String),
 518}
 519
 520/// An action that the main program loop should.
 521///
 522/// See [the commands module][super::commands] for where these are usually created.
 523#[derive(Clone, Debug, Eq, PartialEq)]
 524pub enum IambAction {
 525    /// Perform an action against the homeserver.
 526    Homeserver(HomeserverAction),
 527
 528    /// Perform an action over room keys.
 529    Keys(KeysAction),
 530
 531    /// Perform an action on the currently selected message.
 532    Message(MessageAction),
 533
 534    /// Perform an action on the current space.
 535    Space(SpaceAction),
 536
 537    /// Open a URL.
 538    OpenLink(String),
 539
 540    /// Perform an action on the currently focused room.
 541    Room(RoomAction),
 542
 543    /// Send a message to the currently focused room.
 544    Send(SendAction),
 545
 546    /// Perform an action for an in-progress verification.
 547    Verify(VerifyAction, String),
 548
 549    /// Request a new verification with the specified user.
 550    VerifyRequest(String),
 551
 552    /// Toggle the focus within the focused room.
 553    ToggleScrollbackFocus,
 554
 555    /// Clear all unread messages.
 556    ClearUnreads,
 557}
 558
 559impl IambAction {
 560    /// Indicates whether this action will draw over the screen.
 561    pub fn scribbles(&self) -> bool {
 562        matches!(self, IambAction::Send(SendAction::SubmitFromEditor))
 563    }
 564}
 565
 566impl From<HomeserverAction> for IambAction {
 567    fn from(act: HomeserverAction) -> Self {
 568        IambAction::Homeserver(act)
 569    }
 570}
 571
 572impl From<MessageAction> for IambAction {
 573    fn from(act: MessageAction) -> Self {
 574        IambAction::Message(act)
 575    }
 576}
 577
 578impl From<SpaceAction> for IambAction {
 579    fn from(act: SpaceAction) -> Self {
 580        IambAction::Space(act)
 581    }
 582}
 583
 584impl From<RoomAction> for IambAction {
 585    fn from(act: RoomAction) -> Self {
 586        IambAction::Room(act)
 587    }
 588}
 589
 590impl From<SendAction> for IambAction {
 591    fn from(act: SendAction) -> Self {
 592        IambAction::Send(act)
 593    }
 594}
 595
 596impl ApplicationAction for IambAction {
 597    fn is_edit_sequence(&self, _: &EditContext) -> SequenceStatus {
 598        match self {
 599            IambAction::ClearUnreads => SequenceStatus::Break,
 600            IambAction::Homeserver(..) => SequenceStatus::Break,
 601            IambAction::Keys(..) => SequenceStatus::Break,
 602            IambAction::Message(..) => SequenceStatus::Break,
 603            IambAction::Space(..) => SequenceStatus::Break,
 604            IambAction::Room(..) => SequenceStatus::Break,
 605            IambAction::OpenLink(..) => SequenceStatus::Break,
 606            IambAction::Send(..) => SequenceStatus::Break,
 607            IambAction::ToggleScrollbackFocus => SequenceStatus::Break,
 608            IambAction::Verify(..) => SequenceStatus::Break,
 609            IambAction::VerifyRequest(..) => SequenceStatus::Break,
 610        }
 611    }
 612
 613    fn is_last_action(&self, _: &EditContext) -> SequenceStatus {
 614        match self {
 615            IambAction::ClearUnreads => SequenceStatus::Atom,
 616            IambAction::Homeserver(..) => SequenceStatus::Atom,
 617            IambAction::Keys(..) => SequenceStatus::Atom,
 618            IambAction::Message(..) => SequenceStatus::Atom,
 619            IambAction::Space(..) => SequenceStatus::Atom,
 620            IambAction::OpenLink(..) => SequenceStatus::Atom,
 621            IambAction::Room(..) => SequenceStatus::Atom,
 622            IambAction::Send(..) => SequenceStatus::Atom,
 623            IambAction::ToggleScrollbackFocus => SequenceStatus::Atom,
 624            IambAction::Verify(..) => SequenceStatus::Atom,
 625            IambAction::VerifyRequest(..) => SequenceStatus::Atom,
 626        }
 627    }
 628
 629    fn is_last_selection(&self, _: &EditContext) -> SequenceStatus {
 630        match self {
 631            IambAction::ClearUnreads => SequenceStatus::Ignore,
 632            IambAction::Homeserver(..) => SequenceStatus::Ignore,
 633            IambAction::Keys(..) => SequenceStatus::Ignore,
 634            IambAction::Message(..) => SequenceStatus::Ignore,
 635            IambAction::Space(..) => SequenceStatus::Ignore,
 636            IambAction::Room(..) => SequenceStatus::Ignore,
 637            IambAction::OpenLink(..) => SequenceStatus::Ignore,
 638            IambAction::Send(..) => SequenceStatus::Ignore,
 639            IambAction::ToggleScrollbackFocus => SequenceStatus::Ignore,
 640            IambAction::Verify(..) => SequenceStatus::Ignore,
 641            IambAction::VerifyRequest(..) => SequenceStatus::Ignore,
 642        }
 643    }
 644
 645    fn is_switchable(&self, _: &EditContext) -> bool {
 646        match self {
 647            IambAction::ClearUnreads => false,
 648            IambAction::Homeserver(..) => false,
 649            IambAction::Message(..) => false,
 650            IambAction::Space(..) => false,
 651            IambAction::Room(..) => false,
 652            IambAction::Keys(..) => false,
 653            IambAction::Send(..) => false,
 654            IambAction::OpenLink(..) => false,
 655            IambAction::ToggleScrollbackFocus => false,
 656            IambAction::Verify(..) => false,
 657            IambAction::VerifyRequest(..) => false,
 658        }
 659    }
 660}
 661
 662impl From<RoomAction> for ProgramAction {
 663    fn from(act: RoomAction) -> Self {
 664        IambAction::from(act).into()
 665    }
 666}
 667
 668impl From<SpaceAction> for ProgramAction {
 669    fn from(act: SpaceAction) -> Self {
 670        IambAction::from(act).into()
 671    }
 672}
 673
 674impl From<IambAction> for ProgramAction {
 675    fn from(act: IambAction) -> Self {
 676        Action::Application(act)
 677    }
 678}
 679
 680/// Alias for program actions.
 681pub type ProgramAction = Action<IambInfo>;
 682/// Alias for program context.
 683pub type ProgramContext = EditContext;
 684/// Alias for program keybindings.
 685pub type Keybindings = VimMachine<TerminalKey, IambInfo>;
 686/// Alias for a program command.
 687pub type ProgramCommand = VimCommand<IambInfo>;
 688/// Alias for mapped program commands.
 689pub type ProgramCommands = VimCommandMachine<IambInfo>;
 690/// Alias for program store.
 691pub type ProgramStore = Store<IambInfo>;
 692/// Alias for shared program store.
 693pub type AsyncProgramStore = Arc<AsyncMutex<ProgramStore>>;
 694/// Alias for an action result.
 695pub type IambResult<T> = UIResult<T, IambInfo>;
 696
 697/// Reaction events for some message.
 698///
 699/// The event identifier used as a key here is the ID for the reaction, and not for the message
 700/// it's reacting to.
 701pub type MessageReactions = HashMap<OwnedEventId, (String, OwnedUserId)>;
 702
 703/// Errors encountered during application use.
 704#[derive(thiserror::Error, Debug)]
 705pub enum IambError {
 706    /// An invalid history visibility was specified.
 707    #[error("Invalid history visibility setting: {0}")]
 708    InvalidHistoryVisibility(String),
 709
 710    /// An invalid notification level was specified.
 711    #[error("Invalid notification level: {0}")]
 712    InvalidNotificationLevel(String),
 713
 714    /// An invalid user identifier was specified.
 715    #[error("Invalid user identifier: {0}")]
 716    InvalidUserId(String),
 717
 718    /// An invalid user identifier was specified.
 719    #[error("Invalid room alias: {0}")]
 720    InvalidRoomAlias(String),
 721
 722    /// An invalid verification identifier was specified.
 723    #[error("Invalid verification user/device pair: {0}")]
 724    InvalidVerificationId(String),
 725
 726    /// A failure related to the cryptographic store.
 727    #[error("Cryptographic storage error: {0}")]
 728    CryptoStore(#[from] matrix_sdk::encryption::CryptoStoreError),
 729
 730    #[error("Failed to import room keys: {0}")]
 731    FailedKeyImport(#[from] matrix_sdk::encryption::RoomKeyImportError),
 732
 733    /// A failure related to the cryptographic store.
 734    #[error("Cannot export keys from sled: {0}")]
 735    UpgradeSled(#[from] crate::sled_export::SledMigrationError),
 736
 737    /// An HTTP error.
 738    #[error("HTTP client error: {0}")]
 739    Http(#[from] matrix_sdk::HttpError),
 740
 741    /// A failure from the Matrix client.
 742    #[error("Matrix client error: {0}")]
 743    Matrix(#[from] matrix_sdk::Error),
 744
 745    /// A failure when sending a message.
 746    #[error("Send queue error: {0}")]
 747    SendQueue(#[from] matrix_sdk::send_queue::RoomSendQueueError),
 748
 749    /// A failure in the sled storage.
 750    #[error("Matrix client storage error: {0}")]
 751    Store(#[from] matrix_sdk::StoreError),
 752
 753    /// A failure during serialization or deserialization.
 754    #[error("Serialization/deserialization error: {0}")]
 755    Serde(#[from] serde_json::Error),
 756
 757    /// A failure due to not having a configured download directory.
 758    #[error("No download directory configured")]
 759    NoDownloadDir,
 760
 761    /// A failure due to not having a message with an attachment selected.
 762    #[error("Selected message does not have any attachments")]
 763    NoAttachment,
 764
 765    /// A failure due to not having a message selected.
 766    #[error("No message currently selected")]
 767    NoSelectedMessage,
 768
 769    /// A failure due to not having a room or space selected.
 770    #[error("Current window is not a room or space")]
 771    NoSelectedRoomOrSpace,
 772
 773    /// A failure due to not having a room or space item selected in a list.
 774    #[error("No room or space currently selected in list")]
 775    NoSelectedRoomOrSpaceItem,
 776
 777    /// A failure due to not having a room selected.
 778    #[error("Current window is not a room")]
 779    NoSelectedRoom,
 780
 781    /// A failure due to not having a space selected.
 782    #[error("Current window is not a space")]
 783    NoSelectedSpace,
 784
 785    /// A failure due to not having sufficient permission to perform an action in a room.
 786    #[error("You do not have the permission to do that")]
 787    InsufficientPermission,
 788
 789    /// A failure due to not having an outstanding room invitation.
 790    #[error("You do not have a current invitation to this room")]
 791    NotInvited,
 792
 793    /// A failure due to not being a joined room member.
 794    #[error("You need to join the room before you can do that")]
 795    NotJoined,
 796
 797    /// An unknown room was specified.
 798    #[error("Unknown room identifier: {0}")]
 799    UnknownRoom(OwnedRoomId),
 800
 801    /// An invalid room alias id was specified.
 802    #[error("Invalid room alias id: {0}")]
 803    InvalidRoomAliasId(#[from] matrix_sdk::ruma::IdParseError),
 804
 805    /// An invalid space child order was specified.
 806    #[error("Invalid space child order: {0}")]
 807    InvalidSpaceChildOrder(matrix_sdk::ruma::IdParseError),
 808
 809    /// A failure occurred during verification.
 810    #[error("Verification request error: {0}")]
 811    VerificationRequestError(#[from] matrix_sdk::encryption::identities::RequestVerificationError),
 812
 813    #[error("Notification setting error: {0}")]
 814    NotificationSettingError(#[from] matrix_sdk::NotificationSettingsError),
 815
 816    /// A failure related to images.
 817    #[error("Image error: {0}")]
 818    Image(#[from] image::ImageError),
 819
 820    /// A failure to access the system's clipboard.
 821    #[error("Could not use system clipboard data")]
 822    Clipboard,
 823
 824    /// An failure during disk/network/ipc/etc. I/O.
 825    #[error("Input/Output error: {0}")]
 826    IOError(#[from] std::io::Error),
 827
 828    /// A failure while trying to show an image preview.
 829    #[error("Preview error: {0}")]
 830    Preview(String),
 831}
 832
 833impl From<IambError> for UIError<IambInfo> {
 834    fn from(err: IambError) -> Self {
 835        UIError::Application(err)
 836    }
 837}
 838
 839impl ApplicationError for IambError {}
 840
 841/// Status for tracking how much room scrollback we've fetched.
 842#[derive(Default)]
 843pub enum RoomFetchStatus {
 844    /// Room history has been completely fetched.
 845    Done,
 846
 847    /// More room history can be fetched.
 848    HaveMore(String),
 849
 850    /// We have not yet started fetching history for this room.
 851    #[default]
 852    NotStarted,
 853}
 854
 855/// Indicates where an [EventId] lives in the [ChatStore].
 856pub enum EventLocation {
 857    /// The [EventId] belongs to a message.
 858    ///
 859    /// If the first argument is [None], then it's part of the main scrollback. When [Some],
 860    /// it specifies which thread it's in reply to.
 861    Message(Option<OwnedEventId>, MessageKey),
 862
 863    /// The [EventId] belongs to a reaction to the given event.
 864    Reaction(OwnedEventId),
 865
 866    /// The [EventId] belongs to a state event in the main timeline of the room.
 867    State(MessageKey),
 868
 869    /// The [EventId] belongs to a sticker event in the main scrollback
 870    Sticker(MessageKey),
 871}
 872
 873impl EventLocation {
 874    fn to_message_key(&self) -> Option<&MessageKey> {
 875        match self {
 876            EventLocation::Message(_, key) => Some(key),
 877            EventLocation::Sticker(key) => Some(key),
 878            _ => None,
 879        }
 880    }
 881}
 882
 883/// Indicates where a local echo lives in the [`ChatStore`].
 884#[derive(Debug, Clone)]
 885pub enum EchoLocation {
 886    /// The [`OwnedTransactionId`] belongs to a message.
 887    ///
 888    /// If the first argument is [`None`], then it's part of the main scrollback. When [`Some`], it
 889    /// specifies which thread it's in reply to.
 890    Message(Option<OwnedEventId>, MessageKey),
 891
 892    /// The local echo has been replaced by an event with this event id.
 893    Replaced(OwnedEventId),
 894}
 895
 896#[derive(Clone, Debug, Default, Eq, PartialEq)]
 897pub struct UnreadInfo {
 898    pub(crate) unread_mark: bool,
 899    pub(crate) unread_messages: u64,
 900    pub(crate) unread_notifications: u64,
 901    pub(crate) unread_mentions: u64,
 902    pub(crate) latest: Option<MessageTimeStamp>,
 903}
 904
 905impl UnreadInfo {
 906    pub fn is_unread(&self) -> bool {
 907        self.unread_mark || self.unread_notifications > 0 || self.unread_mentions > 0
 908    }
 909
 910    pub fn has_mention(&self) -> bool {
 911        self.unread_mentions > 0
 912    }
 913
 914    pub fn latest(&self) -> Option<&MessageTimeStamp> {
 915        self.latest.as_ref()
 916    }
 917}
 918
 919/// Track the display names for users and render any needed disambiguation for
 920/// those with overlapping names.
 921#[derive(Default)]
 922pub struct DisplayNameStore {
 923    by_ids: HashMap<OwnedUserId, String>,
 924    by_names: HashMap<String, HashSet<OwnedUserId>>,
 925}
 926
 927impl DisplayNameStore {
 928    /// Update the `HashSet` associated with a given displayname.
 929    ///
 930    /// Note that this *could* be done more elegantly using the Entry API, but
 931    /// is intentionally written in a way to avoid cloning conflicting display
 932    /// names.
 933    fn set_by_name(&mut self, user_id: OwnedUserId, name: &str) {
 934        if let Some(existing) = self.by_names.get_mut(name) {
 935            existing.insert(user_id);
 936        } else {
 937            self.by_names.insert(name.to_owned(), HashSet::from([user_id]));
 938        }
 939    }
 940
 941    /// Track a new user ID to displayname mapping, or unset any existing ones.
 942    pub fn set(&mut self, user_id: OwnedUserId, name: Option<String>) {
 943        if let Some(name) = name.as_deref() {
 944            self.set_by_name(user_id.clone(), name);
 945        }
 946
 947        let previous = match (self.by_ids.entry(user_id), name) {
 948            // Nothing to do!
 949            (Entry::Vacant(_), None) => None,
 950
 951            // Setting initial display name for user:
 952            (Entry::Vacant(v), Some(name)) => {
 953                v.insert(name);
 954                None
 955            },
 956
 957            // Unsetting display name:
 958            (Entry::Occupied(o), None) => Some(o.remove_entry()),
 959
 960            // Replacing existing name:
 961            (Entry::Occupied(mut o), Some(name)) => {
 962                if o.get() == &name {
 963                    None
 964                } else {
 965                    Some((o.key().clone(), o.insert(name)))
 966                }
 967            },
 968        };
 969
 970        let Some((user_id, previous)) = previous else {
 971            return;
 972        };
 973
 974        let Some(users) = self.by_names.get_mut(&previous) else {
 975            return;
 976        };
 977
 978        users.remove(&user_id);
 979
 980        if users.is_empty() {
 981            self.by_names.remove(&previous);
 982        }
 983    }
 984
 985    pub fn get<'a>(&'a self, user_id: &UserId) -> Option<Cow<'a, str>> {
 986        let displayname = self.by_ids.get(user_id)?;
 987        let users = self.by_names.get(displayname)?;
 988
 989        if !users.contains(user_id) {
 990            // Internal consistency error? Assume no display name:
 991            return None;
 992        }
 993
 994        if users.len() == 1 {
 995            // Unambiguous!
 996            return Some(Cow::Borrowed(displayname.as_str()));
 997        }
 998
 999        // Ambiguous username, so include unique user ID:
1000        Some(Cow::Owned(format!("{displayname} ({user_id})")))
1001    }
1002}
1003
1004/// Information about room's the user's joined.
1005pub struct RoomInfo {
1006    /// The display name for this room.
1007    pub name: Option<String>,
1008
1009    /// The tags placed on this room.
1010    pub tags: Option<Tags>,
1011
1012    /// A map of event IDs to where they are stored in this struct.
1013    pub keys: HashMap<OwnedEventId, EventLocation>,
1014    pub echo_keys: HashMap<OwnedTransactionId, EchoLocation>,
1015
1016    /// The messages loaded for this room.
1017    messages: Messages,
1018
1019    /// A map of read markers to display on different events.
1020    pub event_receipts: HashMap<ReceiptThread, HashMap<OwnedEventId, HashSet<OwnedUserId>>>,
1021    /// A map of the most recent read marker for each user.
1022    ///
1023    /// Every receipt in this map should also have an entry in [`event_receipts`](`Self::event_receipts`),
1024    /// however not every user has an entry. If a user's most recent receipt is
1025    /// older than the oldest loaded event, that user will not be included.
1026    pub user_receipts: HashMap<ReceiptThread, HashMap<OwnedUserId, OwnedEventId>>,
1027    /// A map of message identifiers to a map of reaction events.
1028    pub reactions: HashMap<OwnedEventId, MessageReactions>,
1029
1030    /// A map of message identifiers to thread replies.
1031    threads: HashMap<OwnedEventId, Messages>,
1032
1033    /// Whether the scrollback for this room is currently being fetched.
1034    pub fetching: bool,
1035
1036    /// Where to continue fetching from when we continue loading scrollback history.
1037    pub fetch_id: RoomFetchStatus,
1038
1039    /// The time that we last fetched scrollback for this room.
1040    pub fetch_last: Option<Instant>,
1041
1042    /// Users currently typing in this room, and when we received notification of them doing so.
1043    pub users_typing: Option<(Instant, Vec<OwnedUserId>)>,
1044
1045    /// The display names for users in this room.
1046    pub display_names: DisplayNameStore,
1047
1048    /// The last time the room was rendered, used to detect if it is currently open.
1049    pub draw_last: Option<Instant>,
1050}
1051
1052impl Default for RoomInfo {
1053    fn default() -> Self {
1054        Self {
1055            messages: Messages::new(ReceiptThread::Main),
1056
1057            name: Default::default(),
1058            tags: Default::default(),
1059            keys: Default::default(),
1060            echo_keys: Default::default(),
1061            event_receipts: Default::default(),
1062            user_receipts: Default::default(),
1063            reactions: Default::default(),
1064            threads: Default::default(),
1065            fetching: Default::default(),
1066            fetch_id: Default::default(),
1067            fetch_last: Default::default(),
1068            users_typing: Default::default(),
1069            display_names: Default::default(),
1070            draw_last: Default::default(),
1071        }
1072    }
1073}
1074
1075impl RoomInfo {
1076    pub fn get_thread(&self, root: Option<&EventId>) -> Option<&Messages> {
1077        if let Some(thread_root) = root {
1078            self.threads.get(thread_root)
1079        } else {
1080            Some(&self.messages)
1081        }
1082    }
1083
1084    pub fn get_thread_mut(&mut self, root: Option<OwnedEventId>) -> &mut Messages {
1085        if let Some(thread_root) = root {
1086            self.threads
1087                .entry(thread_root.clone())
1088                .or_insert_with(|| Messages::thread(thread_root))
1089        } else {
1090            &mut self.messages
1091        }
1092    }
1093
1094    /// Get the event for the last message in a thread (or the thread root if there are no
1095    /// in-thread replies yet).
1096    ///
1097    /// This returns `None` if the event identifier isn't in the room.
1098    pub fn get_thread_last<'a>(
1099        &'a self,
1100        thread_root: &OwnedEventId,
1101    ) -> Option<&'a OriginalRoomMessageEvent> {
1102        let last = self.threads.get(thread_root).and_then(|t| Some(t.last_key_value()?.1));
1103
1104        let msg = if let Some(last) = last {
1105            &last.event
1106        } else if let EventLocation::Message(_, key) = self.keys.get(thread_root)? {
1107            let msg = self.messages.get(key)?;
1108            &msg.event
1109        } else {
1110            return None;
1111        };
1112
1113        if let MessageEvent::Original(ev) = &msg {
1114            Some(ev)
1115        } else {
1116            None
1117        }
1118    }
1119
1120    /// Get the reactions and their counts for a message.
1121    pub fn get_reactions(&self, event_id: &EventId) -> Vec<(&str, usize)> {
1122        if let Some(reacts) = self.reactions.get(event_id) {
1123            let mut counts = HashMap::new();
1124
1125            let mut seen_user_reactions = BTreeSet::new();
1126
1127            for (key, user) in reacts.values() {
1128                if !seen_user_reactions.contains(&(key, user)) {
1129                    seen_user_reactions.insert((key, user));
1130                    let count = counts.entry(key.as_str()).or_default();
1131                    *count += 1;
1132                }
1133            }
1134
1135            let mut reactions = counts.into_iter().collect::<Vec<_>>();
1136            reactions.sort();
1137
1138            reactions
1139        } else {
1140            vec![]
1141        }
1142    }
1143
1144    /// Map an event identifier to its [MessageKey].
1145    pub fn get_message_key(&self, event_id: &EventId) -> Option<&MessageKey> {
1146        self.keys.get(event_id)?.to_message_key()
1147    }
1148
1149    /// Get an event for an identifier.
1150    pub fn get_event(&self, event_id: &EventId) -> Option<&Message> {
1151        self.messages.get(self.get_message_key(event_id)?)
1152    }
1153
1154    /// Get an event for an identifier as mutable.
1155    pub fn get_event_mut(&mut self, event_id: &EventId) -> Option<&mut Message> {
1156        self.messages.get_mut(self.keys.get(event_id)?.to_message_key()?)
1157    }
1158
1159    pub fn redact(&mut self, ev: OriginalSyncRoomRedactionEvent) {
1160        let Some(redacts) = &ev.redacts else {
1161            return;
1162        };
1163
1164        match self.keys.get(redacts) {
1165            None => return,
1166            Some(EventLocation::State(key)) => {
1167                if let Some(msg) = self.messages.get_mut(key) {
1168                    let ev = SyncRoomRedactionEvent::Original(ev);
1169                    msg.redact(ev);
1170                }
1171            },
1172            Some(EventLocation::Message(None, key)) => {
1173                if let Some(msg) = self.messages.get_mut(key) {
1174                    let ev = SyncRoomRedactionEvent::Original(ev);
1175                    msg.redact(ev);
1176                }
1177            },
1178            Some(EventLocation::Message(Some(root), key)) => {
1179                if let Some(thread) = self.threads.get_mut(root) {
1180                    if let Some(msg) = thread.get_mut(key) {
1181                        let ev = SyncRoomRedactionEvent::Original(ev);
1182                        msg.redact(ev);
1183                    }
1184                }
1185            },
1186            Some(EventLocation::Reaction(event_id)) => {
1187                if let Some(reactions) = self.reactions.get_mut(event_id) {
1188                    reactions.remove(redacts);
1189                }
1190
1191                self.keys.remove(redacts);
1192            },
1193            Some(EventLocation::Sticker(key)) => {
1194                if let Some(msg) = self.messages.get_mut(key) {
1195                    let ev = SyncRoomRedactionEvent::Original(ev);
1196                    msg.redact(ev);
1197                }
1198            },
1199        }
1200    }
1201
1202    /// Insert a reaction to a message.
1203    pub fn insert_reaction(&mut self, react: ReactionEvent) {
1204        match react {
1205            MessageLikeEvent::Original(react) => {
1206                let rel_id = react.content.relates_to.event_id;
1207                let key = react.content.relates_to.key;
1208
1209                let message = self.reactions.entry(rel_id.clone()).or_default();
1210                let event_id = react.event_id;
1211                let user_id = react.sender;
1212
1213                message.insert(event_id.clone(), (key, user_id));
1214
1215                let loc = EventLocation::Reaction(rel_id);
1216                self.keys.insert(event_id, loc);
1217            },
1218            MessageLikeEvent::Redacted(_) => {
1219                return;
1220            },
1221        }
1222    }
1223
1224    /// Insert a sticker
1225    pub fn insert_sticker(
1226        &mut self,
1227        sticker: StickerEvent,
1228        settings: &ApplicationSettings,
1229        previews: &mut PreviewManager,
1230        worker: &Requester,
1231    ) {
1232        match sticker {
1233            MessageLikeEvent::Original(ref sticker_content) => {
1234                let key = MessageKey {
1235                    ts: sticker_content.origin_server_ts.into(),
1236                    id: sticker_content.event_id.clone().into(),
1237                };
1238
1239                let loc = EventLocation::Sticker(key.clone());
1240
1241                self.keys.insert(sticker_content.event_id.clone(), loc);
1242                self.messages.insert_message(key.clone(), sticker.clone());
1243
1244                if let (Some(msg), Some(image_preview)) = (
1245                    self.get_event_mut(&sticker_content.event_id),
1246                    &settings.tunables.image_preview,
1247                ) {
1248                    let source: MediaSource = sticker_content.content.source.clone().into();
1249                    msg.image_preview = Some(source.clone());
1250                    previews.register_preview(settings, source, image_preview.size, worker);
1251                }
1252            },
1253            MessageLikeEvent::Redacted(ref redaction) => {
1254                let key = MessageKey {
1255                    ts: redaction.origin_server_ts.into(),
1256                    id: redaction.event_id.clone().into(),
1257                };
1258
1259                self.messages.insert_message(key.clone(), sticker.clone());
1260            },
1261        }
1262    }
1263
1264    /// Insert an edit.
1265    pub fn insert_edit(&mut self, msg: Replacement<RoomMessageEventContentWithoutRelation>) {
1266        let event_id = msg.event_id;
1267        let new_msgtype = msg.new_content;
1268
1269        let Some(EventLocation::Message(thread, key)) = self.keys.get(&event_id) else {
1270            return;
1271        };
1272
1273        let source = if let Some(thread) = thread {
1274            self.threads
1275                .entry(thread.clone())
1276                .or_insert_with(|| Messages::thread(thread.clone()))
1277        } else {
1278            &mut self.messages
1279        };
1280
1281        let Some(msg) = source.get_mut(key) else {
1282            return;
1283        };
1284
1285        match &mut msg.event {
1286            MessageEvent::Original(orig) => {
1287                orig.content.apply_replacement(new_msgtype);
1288            },
1289            MessageEvent::Local(_, _, content) => {
1290                content.apply_replacement(new_msgtype);
1291            },
1292            MessageEvent::Redacted(_, _) |
1293            MessageEvent::State(_) |
1294            MessageEvent::Sticker(_) |
1295            MessageEvent::EncryptedOriginal(_) |
1296            MessageEvent::EncryptedRedacted(_) => {
1297                return;
1298            },
1299        }
1300
1301        msg.html = msg.event.html();
1302        msg.event.strip_reply_fallback();
1303    }
1304
1305    pub fn insert_any_state(&mut self, msg: AnySyncStateEvent) {
1306        let event_id = msg.event_id().to_owned();
1307        let key = MessageKey {
1308            ts: msg.origin_server_ts().into(),
1309            id: event_id.clone().into(),
1310        };
1311
1312        let loc = EventLocation::State(key.clone());
1313        self.keys.insert(event_id, loc);
1314        self.messages.insert_message(key, msg);
1315    }
1316
1317    /// Indicates whether this room has unread messages.
1318    pub fn unreads(&self, room: &matrix_sdk::Room) -> UnreadInfo {
1319        let last_message = self
1320            .messages
1321            .iter()
1322            .rev()
1323            .find(|(_, msg)| !matches!(&msg.event, MessageEvent::State(..)));
1324
1325        UnreadInfo {
1326            unread_mark: room.is_marked_unread(),
1327            unread_messages: room.num_unread_messages(),
1328            unread_notifications: room.num_unread_notifications(),
1329            unread_mentions: room.num_unread_mentions(),
1330            latest: last_message.map(|(key, _)| key.ts.to_owned()),
1331        }
1332    }
1333
1334    /// Inserts events that couldn't be decrypted into the scrollback.
1335    pub fn insert_encrypted(&mut self, msg: RoomEncryptedEvent) {
1336        let event_id = msg.event_id().to_owned();
1337        let key = MessageKey {
1338            ts: msg.origin_server_ts().into(),
1339            id: event_id.clone().into(),
1340        };
1341
1342        self.keys.insert(event_id, EventLocation::Message(None, key.clone()));
1343        self.messages.insert(key, msg.into());
1344    }
1345
1346    /// Insert a new message.
1347    pub fn insert_message(&mut self, msg: RoomMessageEvent) {
1348        let event_id = msg.event_id().to_owned();
1349        let key = MessageKey {
1350            ts: msg.origin_server_ts().into(),
1351            id: event_id.clone().into(),
1352        };
1353
1354        let loc = EventLocation::Message(None, key.clone());
1355        self.keys.insert(event_id, loc);
1356        self.messages.insert_message(key, msg);
1357    }
1358
1359    fn insert_thread(&mut self, msg: RoomMessageEvent, thread_root: OwnedEventId) {
1360        let event_id = msg.event_id().to_owned();
1361        let key = MessageKey {
1362            ts: msg.origin_server_ts().into(),
1363            id: event_id.clone().into(),
1364        };
1365
1366        let replies = self
1367            .threads
1368            .entry(thread_root.clone())
1369            .or_insert_with(|| Messages::thread(thread_root.clone()));
1370        let loc = EventLocation::Message(Some(thread_root), key.clone());
1371        self.keys.insert(event_id, loc);
1372        replies.insert_message(key, msg);
1373    }
1374
1375    /// Insert a new message event.
1376    pub fn insert(&mut self, msg: RoomMessageEvent) {
1377        match msg {
1378            RoomMessageEvent::Original(OriginalRoomMessageEvent {
1379                content: RoomMessageEventContent { relates_to: Some(ref relates_to), .. },
1380                ..
1381            }) => {
1382                match relates_to {
1383                    Relation::Replacement(repl) => self.insert_edit(repl.clone()),
1384                    Relation::Thread(Thread { event_id, .. }) => {
1385                        let event_id = event_id.clone();
1386                        self.insert_thread(msg, event_id);
1387                    },
1388                    Relation::Reply { .. } => self.insert_message(msg),
1389                    _ => self.insert_message(msg),
1390                }
1391            },
1392            _ => self.insert_message(msg),
1393        }
1394    }
1395
1396    /// Insert a new message event, and prepare for image-preview if it has an image attachment.
1397    pub fn insert_with_preview(
1398        &mut self,
1399        ev: RoomMessageEvent,
1400        settings: &ApplicationSettings,
1401        previews: &mut PreviewManager,
1402        worker: &Requester,
1403    ) {
1404        let source = source_from_event(&ev);
1405        self.insert(ev);
1406
1407        if let Some((event_id, source)) = source {
1408            if let (Some(msg), Some(image_preview)) =
1409                (self.get_event_mut(&event_id), &settings.tunables.image_preview)
1410            {
1411                msg.image_preview = Some(source.clone());
1412                previews.register_preview(settings, source, image_preview.size, worker)
1413            }
1414        }
1415    }
1416
1417    /// Indicates whether we've recently fetched scrollback for this room.
1418    pub fn recently_fetched(&self) -> bool {
1419        self.fetch_last.is_some_and(|i| i.elapsed() < ROOM_FETCH_DEBOUNCE)
1420    }
1421
1422    fn clear_receipt(&mut self, thread: &ReceiptThread, user_id: &OwnedUserId) -> Option<()> {
1423        let old_event_id =
1424            self.user_receipts.get(thread).and_then(|receipts| receipts.get(user_id))?;
1425        let old_thread = self.event_receipts.get_mut(thread)?;
1426        let old_receipts = old_thread.get_mut(old_event_id)?;
1427        old_receipts.remove(user_id);
1428
1429        if old_receipts.is_empty() {
1430            old_thread.remove(old_event_id);
1431        }
1432        if old_thread.is_empty() {
1433            self.event_receipts.remove(thread);
1434        }
1435
1436        None
1437    }
1438
1439    pub fn set_receipt(
1440        &mut self,
1441        thread: ReceiptThread,
1442        user_id: OwnedUserId,
1443        event_id: OwnedEventId,
1444    ) {
1445        self.clear_receipt(&thread, &user_id);
1446        self.event_receipts
1447            .entry(thread.clone())
1448            .or_default()
1449            .entry(event_id.clone())
1450            .or_default()
1451            .insert(user_id.clone());
1452        self.user_receipts.entry(thread).or_default().insert(user_id, event_id);
1453    }
1454
1455    pub fn fully_read(&mut self, user_id: OwnedUserId, thread: ReceiptThread) {
1456        let messages = match &thread {
1457            ReceiptThread::Main => self.get_thread(None),
1458            ReceiptThread::Thread(root) => self.get_thread(Some(root)),
1459            _ => None,
1460        };
1461
1462        let Some(messages) = messages else {
1463            return;
1464        };
1465
1466        let event_id = messages
1467            .iter()
1468            .filter(|(_, msg)| msg.sender != user_id)
1469            .filter(|(_, msg)| {
1470                matches!(
1471                    msg.event,
1472                    MessageEvent::EncryptedOriginal(..) |
1473                        MessageEvent::EncryptedRedacted(..) |
1474                        MessageEvent::Original(..) |
1475                        MessageEvent::Redacted(..)
1476                )
1477            })
1478            .flat_map(|(_, msg)| msg.event.event_id())
1479            .next_back();
1480
1481        if let Some(event_id) = event_id {
1482            self.set_receipt(thread, user_id, event_id.to_owned());
1483        }
1484    }
1485
1486    pub fn fully_read_all(&mut self, user_id: &UserId) {
1487        self.fully_read(user_id.to_owned(), ReceiptThread::Main);
1488
1489        let threads: Vec<_> = self.threads.keys().map(|root| root.to_owned()).collect();
1490
1491        for thread in threads {
1492            self.fully_read(user_id.to_owned(), ReceiptThread::Thread(thread));
1493        }
1494    }
1495
1496    pub fn receipts<'a>(
1497        &'a self,
1498        user_id: &'a UserId,
1499    ) -> impl Iterator<Item = (&'a ReceiptThread, &'a OwnedEventId)> + 'a {
1500        self.user_receipts
1501            .iter()
1502            .filter_map(move |(t, rs)| rs.get(user_id).map(|r| (t, r)))
1503    }
1504
1505    fn get_typers(&self) -> &[OwnedUserId] {
1506        if let Some((t, users)) = &self.users_typing {
1507            if t.elapsed() < Duration::from_secs(4) {
1508                return users.as_ref();
1509            } else {
1510                return &[];
1511            }
1512        } else {
1513            return &[];
1514        }
1515    }
1516
1517    fn get_typing_spans<'a>(&'a self, settings: &'a ApplicationSettings) -> Line<'a> {
1518        let typers = self.get_typers();
1519        let n = typers.len();
1520
1521        match n {
1522            0 => Line::from(vec![]),
1523            1 => {
1524                let user = settings.get_user_span(typers[0].as_ref(), self);
1525
1526                Line::from(vec![user, Span::from(" is typing...")])
1527            },
1528            2 => {
1529                let user1 = settings.get_user_span(typers[0].as_ref(), self);
1530                let user2 = settings.get_user_span(typers[1].as_ref(), self);
1531
1532                Line::from(vec![
1533                    user1,
1534                    Span::raw(" and "),
1535                    user2,
1536                    Span::from(" are typing..."),
1537                ])
1538            },
1539            n if n < 5 => Line::from("Several people are typing..."),
1540            _ => Line::from("Many people are typing..."),
1541        }
1542    }
1543
1544    /// Update typing information for this room.
1545    pub fn set_typing(&mut self, user_ids: Vec<OwnedUserId>) {
1546        self.users_typing = (Instant::now(), user_ids).into();
1547    }
1548
1549    /// Create a [Rect] that displays what users are typing.
1550    pub fn render_typing(
1551        &mut self,
1552        area: Rect,
1553        buf: &mut Buffer,
1554        settings: &ApplicationSettings,
1555    ) -> Rect {
1556        if area.height <= 2 || area.width <= 20 {
1557            return area;
1558        }
1559
1560        if !settings.tunables.typing_notice_display {
1561            // still keep one line blank, so `render_jump_to_recent` doesn't immediately hide the
1562            // last line in scrollback
1563            return Rect::new(area.x, area.y, area.width, area.height - 1);
1564        }
1565
1566        let top = Rect::new(area.x, area.y, area.width, area.height - 1);
1567        let bar = Rect::new(area.x, area.y + top.height, area.width, 1);
1568
1569        Paragraph::new(self.get_typing_spans(settings))
1570            .alignment(Alignment::Center)
1571            .render(bar, buf);
1572
1573        return top;
1574    }
1575
1576    /// Checks if a given user has reacted with the given emoji on the given event
1577    pub fn user_reactions_contains(
1578        &mut self,
1579        user_id: &UserId,
1580        event_id: &EventId,
1581        emoji: &str,
1582    ) -> bool {
1583        if let Some(reactions) = self.reactions.get(event_id) {
1584            reactions
1585                .values()
1586                .any(|(annotation, user)| annotation == emoji && user == user_id)
1587        } else {
1588            false
1589        }
1590    }
1591}
1592
1593/// Generate a [CompletionMap] for Emoji shortcodes.
1594fn emoji_map() -> CompletionMap<String, &'static Emoji> {
1595    let mut emojis = CompletionMap::default();
1596
1597    for emoji in emojis::iter() {
1598        for shortcode in emoji.shortcodes() {
1599            emojis.insert(shortcode.to_string(), emoji);
1600        }
1601    }
1602
1603    return emojis;
1604}
1605
1606#[cfg(unix)]
1607fn picker_from_termios(protocol_type: Option<ProtocolType>) -> Option<Picker> {
1608    let mut picker = match Picker::from_query_stdio() {
1609        Ok(picker) => picker,
1610        Err(e) => {
1611            tracing::error!("Failed to setup image previews: {e}");
1612            return None;
1613        },
1614    };
1615
1616    if let Some(protocol_type) = protocol_type {
1617        picker.set_protocol_type(protocol_type);
1618    }
1619
1620    Some(picker)
1621}
1622
1623/// Windows cannot guess the right protocol, and always needs type and font_size.
1624#[cfg(windows)]
1625fn picker_from_termios(_: Option<ProtocolType>) -> Option<Picker> {
1626    tracing::error!("\"image_preview\" requires \"protocol\" with \"type\" and \"font_size\" options on Windows.");
1627    None
1628}
1629
1630fn picker_from_settings(settings: &ApplicationSettings) -> Option<Picker> {
1631    let image_preview = settings.tunables.image_preview.as_ref()?;
1632    let image_preview_protocol = image_preview.protocol.as_ref();
1633
1634    if let Some(&ImagePreviewProtocolValues {
1635        r#type: Some(protocol_type),
1636        font_size: Some(font_size),
1637    }) = image_preview_protocol
1638    {
1639        // User forced type and font_size: use that.
1640        let mut picker = Picker::from_fontsize(font_size);
1641        picker.set_protocol_type(protocol_type);
1642        Some(picker)
1643    } else {
1644        // Guess, but use type if forced.
1645        picker_from_termios(image_preview_protocol.and_then(|p| p.r#type))
1646    }
1647}
1648
1649/// Information gathered during server syncs about joined rooms.
1650#[derive(Default)]
1651pub struct SyncInfo {
1652    /// Spaces that the user is a member of.
1653    pub spaces: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
1654
1655    /// Rooms that the user is a member of.
1656    pub rooms: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
1657
1658    /// DMs that the user is a member of.
1659    pub dms: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
1660}
1661
1662impl SyncInfo {
1663    pub fn rooms(&self) -> impl Iterator<Item = &RoomId> {
1664        self.rooms.iter().map(|r| r.0.room_id())
1665    }
1666
1667    pub fn dms(&self) -> impl Iterator<Item = &RoomId> {
1668        self.dms.iter().map(|r| r.0.room_id())
1669    }
1670
1671    pub fn chats(&self) -> impl Iterator<Item = &RoomId> {
1672        self.rooms().chain(self.dms())
1673    }
1674}
1675
1676static MESSAGE_NEED_TTL: u8 = 30;
1677
1678#[derive(Debug, PartialEq)]
1679/// Load messages until the event is loaded or `ttl` loads are exceeded
1680pub struct MessageNeed {
1681    pub event_id: OwnedEventId,
1682    pub ttl: u8,
1683}
1684
1685#[derive(Default, Debug, PartialEq)]
1686pub struct Need {
1687    pub members: bool,
1688    pub messages: Option<Vec<MessageNeed>>,
1689}
1690
1691/// Things that need loading for different rooms.
1692#[derive(Default)]
1693pub struct RoomNeeds {
1694    needs: HashMap<OwnedRoomId, Need>,
1695}
1696
1697impl RoomNeeds {
1698    /// Mark a room for needing to load members.
1699    pub fn need_members(&mut self, room_id: OwnedRoomId) {
1700        self.needs.entry(room_id).or_default().members = true;
1701    }
1702
1703    /// Mark a room for needing to load messages.
1704    pub fn need_messages(&mut self, room_id: OwnedRoomId) {
1705        self.needs.entry(room_id).or_default().messages.get_or_insert_default();
1706    }
1707
1708    /// Mark a room for needing to load messages until the given message is loaded or a retry limit
1709    /// is exceeded.
1710    pub fn need_message(&mut self, room_id: OwnedRoomId, event_id: OwnedEventId) {
1711        let messages = &mut self.needs.entry(room_id).or_default().messages.get_or_insert_default();
1712
1713        messages.push(MessageNeed { event_id, ttl: MESSAGE_NEED_TTL });
1714    }
1715
1716    pub fn need_messages_all(&mut self, room_id: OwnedRoomId, message_needs: Vec<MessageNeed>) {
1717        self.needs
1718            .entry(room_id)
1719            .or_default()
1720            .messages
1721            .get_or_insert_default()
1722            .extend(message_needs);
1723    }
1724
1725    pub fn rooms(&self) -> usize {
1726        self.needs.len()
1727    }
1728}
1729
1730impl IntoIterator for RoomNeeds {
1731    type Item = (OwnedRoomId, Need);
1732    type IntoIter = IntoIter<OwnedRoomId, Need>;
1733
1734    fn into_iter(self) -> Self::IntoIter {
1735        self.needs.into_iter()
1736    }
1737}
1738
1739/// The main application state.
1740pub struct ChatStore {
1741    /// `:`-commands
1742    pub cmds: ProgramCommands,
1743
1744    /// Handle for communicating w/ the worker thread.
1745    pub worker: Requester,
1746
1747    /// Map of joined rooms.
1748    pub rooms: CompletionMap<OwnedRoomId, RoomInfo>,
1749
1750    /// Map of room names.
1751    pub names: CompletionMap<String, OwnedRoomId>,
1752
1753    /// Presence information for other users.
1754    pub presences: CompletionMap<OwnedUserId, PresenceState>,
1755
1756    /// In-progress and completed verifications.
1757    pub verifications: HashMap<String, SasVerification>,
1758
1759    /// Settings for the current profile loaded from config file.
1760    pub settings: ApplicationSettings,
1761
1762    /// Set of rooms that need more messages loaded in their scrollback.
1763    pub need_load: RoomNeeds,
1764
1765    /// [CompletionMap] of Emoji shortcodes.
1766    pub emojis: CompletionMap<String, &'static Emoji>,
1767
1768    /// Information gathered by the background thread.
1769    pub sync_info: SyncInfo,
1770
1771    /// Rendered image previews.
1772    pub previews: PreviewManager,
1773
1774    /// Last draw time, used to match with RoomInfo's draw_last.
1775    pub draw_curr: Option<Instant>,
1776
1777    /// Whether to ring the terminal bell on the next redraw.
1778    pub ring_bell: bool,
1779
1780    /// Whether the application is currently focused
1781    pub focused: bool,
1782
1783    /// Collator for locale-aware text sorting.
1784    pub collator: feruca::Collator,
1785
1786    /// Notifications that should be dismissed when the user opens the room.
1787    pub open_notifications: HashMap<OwnedRoomId, Vec<NotificationHandle>>,
1788}
1789
1790impl ChatStore {
1791    /// Create a new [ChatStore].
1792    pub fn new(worker: Requester, settings: ApplicationSettings) -> Self {
1793        let picker = picker_from_settings(&settings);
1794
1795        ChatStore {
1796            worker,
1797            settings,
1798            previews: PreviewManager::new(picker),
1799            cmds: crate::commands::setup_commands(),
1800            emojis: emoji_map(),
1801
1802            collator: Default::default(),
1803            names: Default::default(),
1804            rooms: Default::default(),
1805            presences: Default::default(),
1806            verifications: Default::default(),
1807            need_load: Default::default(),
1808            sync_info: Default::default(),
1809            draw_curr: None,
1810            ring_bell: false,
1811            focused: true,
1812            open_notifications: Default::default(),
1813        }
1814    }
1815
1816    /// Get a joined room.
1817    pub fn get_joined_room(&self, room_id: &RoomId) -> Option<MatrixRoom> {
1818        let room = self.worker.client.get_room(room_id)?;
1819
1820        if room.state() == MatrixRoomState::Joined {
1821            Some(room)
1822        } else {
1823            None
1824        }
1825    }
1826
1827    /// Get the title for a room.
1828    pub fn get_room_title(&self, room_id: &RoomId) -> String {
1829        self.rooms
1830            .get(room_id)
1831            .and_then(|i| i.name.as_ref())
1832            .map(String::from)
1833            .unwrap_or_else(|| "Untitled Matrix Room".to_string())
1834    }
1835
1836    /// Get the [RoomInfo] for a given room identifier.
1837    pub fn get_room_info(&mut self, room_id: OwnedRoomId) -> &mut RoomInfo {
1838        self.rooms.get_or_default(room_id)
1839    }
1840
1841    /// Set the name for a room.
1842    pub fn set_room_name(&mut self, room_id: &RoomId, name: &str) {
1843        self.rooms.get_or_default(room_id.to_owned()).name = name.to_string().into();
1844    }
1845
1846    /// Insert a new E2EE verification.
1847    pub fn insert_sas(&mut self, sas: SasVerification) {
1848        let key = format!("{}/{}", sas.other_user_id(), sas.other_device().device_id());
1849
1850        self.verifications.insert(key, sas);
1851    }
1852}
1853
1854impl ApplicationStore for ChatStore {}
1855
1856/// Identified used to track window content.
1857#[derive(Clone, Debug, Eq, Hash, PartialEq)]
1858pub enum IambId {
1859    /// A Matrix room, with an optional thread to show.
1860    Room(OwnedRoomId, Option<OwnedEventId>),
1861
1862    /// The `:dms` window.
1863    DirectList,
1864
1865    /// The `:members` window for a given Matrix room.
1866    MemberList(OwnedRoomId),
1867
1868    /// The `:rooms` window.
1869    RoomList,
1870
1871    /// The `:spaces` window.
1872    SpaceList,
1873
1874    /// The `:verify` window.
1875    VerifyList,
1876
1877    /// The `:welcome` window.
1878    Welcome,
1879
1880    /// The `:chats` window.
1881    ChatList,
1882
1883    /// The `:unreads` window.
1884    UnreadList,
1885
1886    /// The `:mentions` window.
1887    MentionsList,
1888}
1889
1890impl Display for IambId {
1891    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1892        match self {
1893            IambId::Room(room_id, None) => {
1894                write!(f, "iamb://room/{room_id}")
1895            },
1896            IambId::Room(room_id, Some(thread)) => {
1897                write!(f, "iamb://room/{room_id}/threads/{thread}")
1898            },
1899            IambId::MemberList(room_id) => {
1900                write!(f, "iamb://members/{room_id}")
1901            },
1902            IambId::DirectList => f.write_str("iamb://dms"),
1903            IambId::RoomList => f.write_str("iamb://rooms"),
1904            IambId::SpaceList => f.write_str("iamb://spaces"),
1905            IambId::VerifyList => f.write_str("iamb://verify"),
1906            IambId::Welcome => f.write_str("iamb://welcome"),
1907            IambId::ChatList => f.write_str("iamb://chats"),
1908            IambId::UnreadList => f.write_str("iamb://unreads"),
1909            IambId::MentionsList => f.write_str("iamb://mentions"),
1910        }
1911    }
1912}
1913
1914impl ApplicationWindowId for IambId {}
1915
1916impl Serialize for IambId {
1917    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1918    where
1919        S: Serializer,
1920    {
1921        serializer.serialize_str(&self.to_string())
1922    }
1923}
1924
1925impl<'de> Deserialize<'de> for IambId {
1926    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1927    where
1928        D: Deserializer<'de>,
1929    {
1930        deserializer.deserialize_str(IambIdVisitor)
1931    }
1932}
1933
1934/// [serde] visitor for deserializing [IambId].
1935struct IambIdVisitor;
1936
1937impl Visitor<'_> for IambIdVisitor {
1938    type Value = IambId;
1939
1940    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1941        formatter.write_str("a valid window URL")
1942    }
1943
1944    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1945    where
1946        E: SerdeError,
1947    {
1948        let Ok(url) = Url::parse(value) else {
1949            return Err(E::custom("Invalid iamb window URL"));
1950        };
1951
1952        if url.scheme() != "iamb" {
1953            return Err(E::custom("Invalid iamb window URL"));
1954        }
1955
1956        match url.domain() {
1957            Some("room") => {
1958                let Some(path) = url.path_segments() else {
1959                    return Err(E::custom("Invalid members window URL"));
1960                };
1961
1962                match *path.collect::<Vec<_>>().as_slice() {
1963                    [room_id] => {
1964                        let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
1965                            return Err(E::custom("Invalid room identifier"));
1966                        };
1967
1968                        Ok(IambId::Room(room_id, None))
1969                    },
1970                    [room_id, "threads", thread_root] => {
1971                        let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
1972                            return Err(E::custom("Invalid room identifier"));
1973                        };
1974
1975                        let Ok(thread_root) = OwnedEventId::try_from(thread_root) else {
1976                            return Err(E::custom("Invalid thread root identifier"));
1977                        };
1978
1979                        Ok(IambId::Room(room_id, Some(thread_root)))
1980                    },
1981                    _ => return Err(E::custom("Invalid members window URL")),
1982                }
1983            },
1984            Some("members") => {
1985                let Some(path) = url.path_segments() else {
1986                    return Err(E::custom("Invalid members window URL"));
1987                };
1988
1989                let &[room_id] = path.collect::<Vec<_>>().as_slice() else {
1990                    return Err(E::custom("Invalid members window URL"));
1991                };
1992
1993                let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
1994                    return Err(E::custom("Invalid room identifier"));
1995                };
1996
1997                Ok(IambId::MemberList(room_id))
1998            },
1999            Some("dms") => {
2000                if url.path() != "" {
2001                    return Err(E::custom("iamb://dms takes no path"));
2002                }
2003
2004                Ok(IambId::DirectList)
2005            },
2006            Some("rooms") => {
2007                if url.path() != "" {
2008                    return Err(E::custom("iamb://rooms takes no path"));
2009                }
2010
2011                Ok(IambId::RoomList)
2012            },
2013            Some("spaces") => {
2014                if url.path() != "" {
2015                    return Err(E::custom("iamb://spaces takes no path"));
2016                }
2017
2018                Ok(IambId::SpaceList)
2019            },
2020            Some("verify") => {
2021                if url.path() != "" {
2022                    return Err(E::custom("iamb://verify takes no path"));
2023                }
2024
2025                Ok(IambId::VerifyList)
2026            },
2027            Some("welcome") => {
2028                if url.path() != "" {
2029                    return Err(E::custom("iamb://welcome takes no path"));
2030                }
2031
2032                Ok(IambId::Welcome)
2033            },
2034            Some("chats") => {
2035                if url.path() != "" {
2036                    return Err(E::custom("iamb://chats takes no path"));
2037                }
2038
2039                Ok(IambId::ChatList)
2040            },
2041            Some("unreads") => {
2042                if url.path() != "" {
2043                    return Err(E::custom("iamb://unreads takes no path"));
2044                }
2045
2046                Ok(IambId::UnreadList)
2047            },
2048            Some("mentions") => {
2049                if url.path() != "" {
2050                    return Err(E::custom("iamb://mentions takes no path"));
2051                }
2052
2053                Ok(IambId::MentionsList)
2054            },
2055            Some(s) => Err(E::custom(format!("{s:?} is not a valid window"))),
2056            None => Err(E::custom("Invalid iamb window URL")),
2057        }
2058    }
2059}
2060
2061/// Which part of the room window's UI is focused.
2062#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
2063pub enum RoomFocus {
2064    /// The scrollback for a room window is focused.
2065    Scrollback,
2066
2067    /// The message bar for a room window is focused.
2068    MessageBar,
2069}
2070
2071impl RoomFocus {
2072    /// Whether this is [RoomFocus::Scrollback].
2073    pub fn is_scrollback(&self) -> bool {
2074        matches!(self, RoomFocus::Scrollback)
2075    }
2076
2077    /// Whether this is [RoomFocus::MessageBar].
2078    pub fn is_msgbar(&self) -> bool {
2079        matches!(self, RoomFocus::MessageBar)
2080    }
2081
2082    pub fn toggle(&mut self) {
2083        *self = match self {
2084            RoomFocus::MessageBar => RoomFocus::Scrollback,
2085            RoomFocus::Scrollback => RoomFocus::MessageBar,
2086        };
2087    }
2088}
2089
2090/// Identifiers used to track where a mark was placed.
2091///
2092/// While this is the "buffer identifier" for the mark,
2093/// not all of these are necessarily actual buffers.
2094#[derive(Clone, Debug, Eq, Hash, PartialEq)]
2095pub enum IambBufferId {
2096    /// The command bar buffer.
2097    Command(CommandType),
2098
2099    /// The message buffer or a specific message in a room.
2100    Room(OwnedRoomId, Option<OwnedEventId>, RoomFocus),
2101
2102    /// The `:dms` window.
2103    DirectList,
2104
2105    /// The `:members` window for a room.
2106    MemberList(OwnedRoomId),
2107
2108    /// The `:rooms` window.
2109    RoomList,
2110
2111    /// The `:spaces` window.
2112    SpaceList,
2113
2114    /// The `:verify` window.
2115    VerifyList,
2116
2117    /// The buffer for the `:rooms` window.
2118    Welcome,
2119
2120    /// The `:chats` window.
2121    ChatList,
2122
2123    /// The `:unreads` window.
2124    UnreadList,
2125
2126    /// The `:mentions` window.
2127    MentionsList,
2128}
2129
2130impl IambBufferId {
2131    /// Get the identifier for the window that contains this buffer.
2132    pub fn to_window(&self) -> Option<IambId> {
2133        let id = match self {
2134            IambBufferId::Command(_) => return None,
2135            IambBufferId::Room(room, thread, _) => IambId::Room(room.clone(), thread.clone()),
2136            IambBufferId::DirectList => IambId::DirectList,
2137            IambBufferId::MemberList(room) => IambId::MemberList(room.clone()),
2138            IambBufferId::RoomList => IambId::RoomList,
2139            IambBufferId::SpaceList => IambId::SpaceList,
2140            IambBufferId::VerifyList => IambId::VerifyList,
2141            IambBufferId::Welcome => IambId::Welcome,
2142            IambBufferId::ChatList => IambId::ChatList,
2143            IambBufferId::UnreadList => IambId::UnreadList,
2144            IambBufferId::MentionsList => IambId::MentionsList,
2145        };
2146
2147        Some(id)
2148    }
2149}
2150
2151impl ApplicationContentId for IambBufferId {}
2152
2153impl ApplicationInfo for IambInfo {
2154    type Error = IambError;
2155    type Store = ChatStore;
2156    type Action = IambAction;
2157    type WindowId = IambId;
2158    type ContentId = IambBufferId;
2159
2160    fn content_of_command(ct: CommandType) -> IambBufferId {
2161        IambBufferId::Command(ct)
2162    }
2163}
2164
2165pub struct IambCompleter;
2166
2167impl Completer<IambInfo> for IambCompleter {
2168    fn complete(
2169        &mut self,
2170        text: &EditRope,
2171        cursor: &mut Cursor,
2172        content: &IambBufferId,
2173        store: &mut ChatStore,
2174    ) -> Vec<String> {
2175        match content {
2176            IambBufferId::Command(CommandType::Command) => complete_cmdbar(text, cursor, store),
2177            IambBufferId::Command(CommandType::Search) => vec![],
2178            IambBufferId::Room(_, _, RoomFocus::MessageBar) => complete_msgbar(text, cursor, store),
2179            IambBufferId::Room(_, _, RoomFocus::Scrollback) => vec![],
2180
2181            IambBufferId::DirectList => vec![],
2182            IambBufferId::MemberList(_) => vec![],
2183            IambBufferId::RoomList => vec![],
2184            IambBufferId::SpaceList => vec![],
2185            IambBufferId::VerifyList => vec![],
2186            IambBufferId::Welcome => vec![],
2187            IambBufferId::ChatList => vec![],
2188            IambBufferId::UnreadList => vec![],
2189            IambBufferId::MentionsList => vec![],
2190        }
2191    }
2192}
2193
2194/// Tab completion for user IDs.
2195fn complete_users(text: &EditRope, cursor: &mut Cursor, store: &ChatStore) -> Vec<String> {
2196    let id = text
2197        .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
2198        .unwrap_or_else(EditRope::empty);
2199    let id = Cow::from(&id);
2200
2201    store
2202        .presences
2203        .complete(id.as_ref())
2204        .into_iter()
2205        .map(|i| i.to_string())
2206        .collect()
2207}
2208
2209/// Tab completion within the message bar.
2210fn complete_msgbar(text: &EditRope, cursor: &mut Cursor, store: &ChatStore) -> Vec<String> {
2211    let id = text
2212        .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
2213        .unwrap_or_else(EditRope::empty);
2214    let id = Cow::from(&id);
2215
2216    match id.chars().next() {
2217        // Complete room aliases.
2218        Some('#') => {
2219            return store.names.complete(id.as_ref());
2220        },
2221
2222        // Complete room identifiers.
2223        Some('!') => {
2224            return store
2225                .rooms
2226                .complete(id.as_ref())
2227                .into_iter()
2228                .map(|i| i.to_string())
2229                .collect();
2230        },
2231
2232        // Complete Emoji shortcodes.
2233        Some(':') => {
2234            let list = store.emojis.complete(&id[1..]);
2235            let iter = list.into_iter().take(200).map(|s| format!(":{s}:"));
2236
2237            return iter.collect();
2238        },
2239
2240        // Complete usernames for @ and empty strings.
2241        Some('@') | None => {
2242            return store
2243                .presences
2244                .complete(id.as_ref())
2245                .into_iter()
2246                .map(|i| i.to_string())
2247                .collect();
2248        },
2249
2250        // Unknown sigil.
2251        Some(_) => return vec![],
2252    }
2253}
2254
2255/// Tab completion for Matrix identifiers (usernames, room aliases, etc.)
2256fn complete_matrix_names(text: &EditRope, cursor: &mut Cursor, store: &ChatStore) -> Vec<String> {
2257    let id = text
2258        .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
2259        .unwrap_or_else(EditRope::empty);
2260    let id = Cow::from(&id);
2261
2262    let list = store.names.complete(id.as_ref());
2263    if !list.is_empty() {
2264        return list;
2265    }
2266
2267    let list = store.presences.complete(id.as_ref());
2268    if !list.is_empty() {
2269        return list.into_iter().map(|i| i.to_string()).collect();
2270    }
2271
2272    store
2273        .rooms
2274        .complete(id.as_ref())
2275        .into_iter()
2276        .map(|i| i.to_string())
2277        .collect()
2278}
2279
2280/// Tab completion for Emoji shortcode names.
2281fn complete_emoji(text: &EditRope, cursor: &mut Cursor, store: &ChatStore) -> Vec<String> {
2282    let sc = text.get_prefix_word_mut(cursor, &WordStyle::Little);
2283    let sc = sc.unwrap_or_else(EditRope::empty);
2284    let sc = Cow::from(&sc);
2285
2286    store.emojis.complete(sc.as_ref())
2287}
2288
2289/// Tab completion for command names.
2290fn complete_cmdname(
2291    desc: CommandDescription,
2292    text: &EditRope,
2293    cursor: &mut Cursor,
2294    store: &ChatStore,
2295) -> Vec<String> {
2296    // Complete command name and set cursor position.
2297    let _ = text.get_prefix_word_mut(cursor, &WordStyle::Little);
2298    store.cmds.complete_name(desc.command.as_str())
2299}
2300
2301/// Tab completion for command arguments.
2302fn complete_cmdarg(
2303    desc: CommandDescription,
2304    text: &EditRope,
2305    cursor: &mut Cursor,
2306    store: &ChatStore,
2307) -> Vec<String> {
2308    let cmd = match store.cmds.get(desc.command.as_str()) {
2309        Ok(cmd) => cmd,
2310        Err(_) => return vec![],
2311    };
2312
2313    match cmd.name.as_str() {
2314        "cancel" | "dms" | "edit" | "redact" | "reply" => vec![],
2315        "members" | "rooms" | "spaces" | "welcome" => vec![],
2316        "download" | "keys" | "open" | "upload" => complete_path(text, cursor),
2317        "react" | "unreact" => complete_emoji(text, cursor, store),
2318
2319        "invite" => complete_users(text, cursor, store),
2320        "join" | "split" | "vsplit" | "tabedit" => complete_matrix_names(text, cursor, store),
2321        "room" => vec![],
2322        "verify" => vec![],
2323        "vertical" | "horizontal" | "aboveleft" | "belowright" | "tab" => {
2324            complete_cmd(desc.arg.text.as_str(), text, cursor, store)
2325        },
2326        _ => vec![],
2327    }
2328}
2329
2330/// Tab completion for commands.
2331fn complete_cmd(cmd: &str, text: &EditRope, cursor: &mut Cursor, store: &ChatStore) -> Vec<String> {
2332    match CommandDescription::from_str(cmd) {
2333        Ok(desc) => {
2334            if desc.arg.untrimmed.is_empty() {
2335                complete_cmdname(desc, text, cursor, store)
2336            } else {
2337                // Complete command argument.
2338                complete_cmdarg(desc, text, cursor, store)
2339            }
2340        },
2341
2342        // Can't parse command text, so return zero completions.
2343        Err(_) => vec![],
2344    }
2345}
2346
2347/// Tab completion for the command bar.
2348fn complete_cmdbar(text: &EditRope, cursor: &mut Cursor, store: &ChatStore) -> Vec<String> {
2349    let eo = text.cursor_to_offset(cursor);
2350    let slice = text.slice(..eo);
2351    let cow = Cow::from(&slice);
2352
2353    complete_cmd(cow.as_ref(), text, cursor, store)
2354}
2355
2356#[cfg(test)]
2357pub mod tests {
2358    use std::iter::FromIterator as _;
2359
2360    use super::*;
2361    use crate::config::user_style_from_color;
2362    use crate::tests::*;
2363    use matrix_sdk::ruma::{
2364        events::{reaction::ReactionEventContent, relation::Annotation},
2365        owned_event_id,
2366        MilliSecondsSinceUnixEpoch,
2367    };
2368    use pretty_assertions::assert_eq;
2369    use ratatui::style::Color;
2370    use serde_json::{Map, Value};
2371
2372    fn create_reaction_event(
2373        content: &ReactionEventContent,
2374        event_id: &str,
2375        sender: &str,
2376    ) -> ReactionEvent {
2377        serde_json::from_value(Value::Object(Map::from_iter([
2378            ("type".to_owned(), Value::String("m.reaction".into())),
2379            ("content".to_owned(), serde_json::to_value(content).unwrap()),
2380            ("event_id".to_owned(), serde_json::to_value(event_id).unwrap()),
2381            ("sender".to_owned(), Value::String(sender.into())),
2382            (
2383                "origin_server_ts".to_owned(),
2384                serde_json::to_value(MilliSecondsSinceUnixEpoch::now()).unwrap(),
2385            ),
2386            ("room_id".to_owned(), Value::String("!foo:example.org".into())),
2387        ])))
2388        .unwrap()
2389    }
2390
2391    #[test]
2392    fn multiple_identical_reactions() {
2393        let mut info = RoomInfo::default();
2394
2395        let content = ReactionEventContent::new(Annotation::new(
2396            owned_event_id!("$my_reaction"),
2397            "🏠".to_owned(),
2398        ));
2399
2400        for i in 0..3 {
2401            let event_id = format!("$house_{i}");
2402            let react = create_reaction_event(&content, &event_id, "@foo:example.com");
2403            info.insert_reaction(react);
2404        }
2405
2406        let content = ReactionEventContent::new(Annotation::new(
2407            owned_event_id!("$my_reaction"),
2408            "🙂".to_owned(),
2409        ));
2410
2411        for i in 0..2 {
2412            let event_id = format!("$smile_{i}");
2413            let react = create_reaction_event(&content, &event_id, "@foo:example.com");
2414            info.insert_reaction(react);
2415        }
2416
2417        for i in 2..4 {
2418            let event_id = format!("$smile2_{i}");
2419            let react = create_reaction_event(&content, &event_id, "@bar:example.com");
2420            info.insert_reaction(react);
2421        }
2422
2423        assert_eq!(info.get_reactions(&owned_event_id!("$my_reaction")), vec![
2424            ("🏠", 1),
2425            ("🙂", 2)
2426        ]);
2427    }
2428
2429    #[test]
2430    fn test_typing_spans() {
2431        let mut info = RoomInfo::default();
2432        let settings = mock_settings();
2433
2434        let users0 = vec![];
2435        let users1 = vec![TEST_USER1.clone()];
2436        let users2 = vec![TEST_USER1.clone(), TEST_USER2.clone()];
2437        let users4 = vec![
2438            TEST_USER1.clone(),
2439            TEST_USER2.clone(),
2440            TEST_USER3.clone(),
2441            TEST_USER4.clone(),
2442        ];
2443        let users5 = vec![
2444            TEST_USER1.clone(),
2445            TEST_USER2.clone(),
2446            TEST_USER3.clone(),
2447            TEST_USER4.clone(),
2448            TEST_USER5.clone(),
2449        ];
2450
2451        // Nothing set.
2452        assert_eq!(info.users_typing, None);
2453        assert_eq!(info.get_typing_spans(&settings), Line::from(vec![]));
2454
2455        // Empty typing list.
2456        info.set_typing(users0);
2457        assert!(info.users_typing.is_some());
2458        assert_eq!(info.get_typing_spans(&settings), Line::from(vec![]));
2459
2460        // Single user typing.
2461        info.set_typing(users1);
2462        assert!(info.users_typing.is_some());
2463        assert_eq!(
2464            info.get_typing_spans(&settings),
2465            Line::from(vec![
2466                Span::styled("@user1:example.com", user_style("@user1:example.com")),
2467                Span::from(" is typing...")
2468            ])
2469        );
2470
2471        // Two users typing.
2472        info.set_typing(users2);
2473        assert!(info.users_typing.is_some());
2474        assert_eq!(
2475            info.get_typing_spans(&settings),
2476            Line::from(vec![
2477                Span::styled("@user1:example.com", user_style("@user1:example.com")),
2478                Span::raw(" and "),
2479                Span::styled("@user2:example.com", user_style("@user2:example.com")),
2480                Span::raw(" are typing...")
2481            ])
2482        );
2483
2484        // Four users typing.
2485        info.set_typing(users4);
2486        assert!(info.users_typing.is_some());
2487        assert_eq!(info.get_typing_spans(&settings), Line::from("Several people are typing..."));
2488
2489        // Five users typing.
2490        info.set_typing(users5);
2491        assert!(info.users_typing.is_some());
2492        assert_eq!(info.get_typing_spans(&settings), Line::from("Many people are typing..."));
2493
2494        // Test that USER5 gets rendered using the configured color and name.
2495        info.set_typing(vec![TEST_USER5.clone()]);
2496        assert!(info.users_typing.is_some());
2497        assert_eq!(
2498            info.get_typing_spans(&settings),
2499            Line::from(vec![
2500                Span::styled("USER 5", user_style_from_color(Color::Black)),
2501                Span::from(" is typing...")
2502            ])
2503        );
2504    }
2505
2506    #[test]
2507    fn test_need_load() {
2508        let room_id = TEST_ROOM1_ID.clone();
2509
2510        let mut need_load = RoomNeeds::default();
2511
2512        need_load.need_messages(room_id.clone());
2513        need_load.need_members(room_id.clone());
2514
2515        assert_eq!(need_load.into_iter().collect::<Vec<(OwnedRoomId, Need)>>(), vec![(
2516            room_id,
2517            Need { members: true, messages: Some(Vec::new()) }
2518        )],);
2519    }
2520
2521    #[tokio::test]
2522    async fn test_complete_msgbar() {
2523        let store = mock_store().await;
2524        let store = store.application;
2525
2526        let text = EditRope::from("going for a walk :walk ");
2527        let mut cursor = Cursor::new(0, 22);
2528        let res = complete_msgbar(&text, &mut cursor, &store);
2529        assert_eq!(res, vec![":walking:", ":walking_man:", ":walking_woman:"]);
2530        assert_eq!(cursor, Cursor::new(0, 17));
2531
2532        let text = EditRope::from("hello @user1 ");
2533        let mut cursor = Cursor::new(0, 12);
2534        let res = complete_msgbar(&text, &mut cursor, &store);
2535        assert_eq!(res, vec!["@user1:example.com"]);
2536        assert_eq!(cursor, Cursor::new(0, 6));
2537
2538        let text = EditRope::from("see #room ");
2539        let mut cursor = Cursor::new(0, 9);
2540        let res = complete_msgbar(&text, &mut cursor, &store);
2541        assert_eq!(res, vec!["#room1:example.com"]);
2542        assert_eq!(cursor, Cursor::new(0, 4));
2543    }
2544
2545    #[tokio::test]
2546    async fn test_complete_cmdbar() {
2547        let store = mock_store().await;
2548        let store = store.application;
2549        let users = vec![
2550            "@user1:example.com",
2551            "@user2:example.com",
2552            "@user3:example.com",
2553            "@user4:example.com",
2554            "@user5:example.com",
2555        ];
2556
2557        let text = EditRope::from("invite    ");
2558        let mut cursor = Cursor::new(0, 7);
2559        let id = text
2560            .get_prefix_word_mut(&mut cursor, &MATRIX_ID_WORD)
2561            .unwrap_or_else(EditRope::empty);
2562        assert_eq!(id.to_string(), "");
2563        assert_eq!(cursor, Cursor::new(0, 7));
2564
2565        let text = EditRope::from("invite    ");
2566        let mut cursor = Cursor::new(0, 7);
2567        let res = complete_cmdbar(&text, &mut cursor, &store);
2568        assert_eq!(res, users);
2569
2570        let text = EditRope::from("invite ignored");
2571        let mut cursor = Cursor::new(0, 7);
2572        let res = complete_cmdbar(&text, &mut cursor, &store);
2573        assert_eq!(res, users);
2574
2575        let text = EditRope::from("invite @user1ignored");
2576        let mut cursor = Cursor::new(0, 13);
2577        let res = complete_cmdbar(&text, &mut cursor, &store);
2578        assert_eq!(res, vec!["@user1:example.com"]);
2579
2580        let text = EditRope::from("abo hor");
2581        let mut cursor = Cursor::new(0, 7);
2582        let res = complete_cmdbar(&text, &mut cursor, &store);
2583        assert_eq!(res, vec!["horizontal"]);
2584
2585        let text = EditRope::from("abo hor inv");
2586        let mut cursor = Cursor::new(0, 11);
2587        let res = complete_cmdbar(&text, &mut cursor, &store);
2588        assert_eq!(res, vec!["invite"]);
2589
2590        let text = EditRope::from("abo hor invite \n");
2591        let mut cursor = Cursor::new(0, 15);
2592        let res = complete_cmdbar(&text, &mut cursor, &store);
2593        assert_eq!(res, users);
2594    }
2595
2596    #[test]
2597    fn test_ambiguous_displaynames() {
2598        let mut store = DisplayNameStore::default();
2599
2600        store.set(TEST_USER1.clone(), Some("John".into()));
2601        store.set(TEST_USER2.clone(), Some("John".into()));
2602        store.set(TEST_USER3.clone(), Some("Jane".into()));
2603        store.set(TEST_USER4.clone(), Some("Alice".into()));
2604        store.set(TEST_USER5.clone(), Some("Bob".into()));
2605
2606        // TEST_USER1 and TEST_USER2 are both ambiguous, while the other are unambiguous:
2607        assert_eq!(store.get(&TEST_USER1).unwrap().as_ref(), "John (@user1:example.com)");
2608        assert_eq!(store.get(&TEST_USER2).unwrap().as_ref(), "John (@user2:example.com)");
2609        assert_eq!(store.get(&TEST_USER3).unwrap().as_ref(), "Jane");
2610        assert_eq!(store.get(&TEST_USER4).unwrap().as_ref(), "Alice");
2611        assert_eq!(store.get(&TEST_USER5).unwrap().as_ref(), "Bob");
2612
2613        // TEST_USER1 becomes unambiguous when TEST_USER2 changes:
2614        store.set(TEST_USER2.clone(), Some("Eve".into()));
2615        assert_eq!(store.get(&TEST_USER1).unwrap().as_ref(), "John");
2616        assert_eq!(store.get(&TEST_USER2).unwrap().as_ref(), "Eve");
2617        assert_eq!(store.get(&TEST_USER3).unwrap().as_ref(), "Jane");
2618        assert_eq!(store.get(&TEST_USER4).unwrap().as_ref(), "Alice");
2619        assert_eq!(store.get(&TEST_USER5).unwrap().as_ref(), "Bob");
2620
2621        // TEST_USER5 becomes ambiguous when TEST_USER2 once again changes their name to match:
2622        store.set(TEST_USER2.clone(), Some("Bob".into()));
2623        assert_eq!(store.get(&TEST_USER1).unwrap().as_ref(), "John");
2624        assert_eq!(store.get(&TEST_USER2).unwrap().as_ref(), "Bob (@user2:example.com)");
2625        assert_eq!(store.get(&TEST_USER3).unwrap().as_ref(), "Jane");
2626        assert_eq!(store.get(&TEST_USER4).unwrap().as_ref(), "Alice");
2627        assert_eq!(store.get(&TEST_USER5).unwrap().as_ref(), "Bob (@user5:example.com)");
2628
2629        // Now "Everyone is John":
2630        store.set(TEST_USER2.clone(), Some("John".into()));
2631        store.set(TEST_USER3.clone(), Some("John".into()));
2632        store.set(TEST_USER4.clone(), Some("John".into()));
2633        store.set(TEST_USER5.clone(), Some("John".into()));
2634        assert_eq!(store.get(&TEST_USER1).unwrap().as_ref(), "John (@user1:example.com)");
2635        assert_eq!(store.get(&TEST_USER2).unwrap().as_ref(), "John (@user2:example.com)");
2636        assert_eq!(store.get(&TEST_USER3).unwrap().as_ref(), "John (@user3:example.com)");
2637        assert_eq!(store.get(&TEST_USER4).unwrap().as_ref(), "John (@user4:example.com)");
2638        assert_eq!(store.get(&TEST_USER5).unwrap().as_ref(), "John (@user5:example.com)");
2639
2640        // 2-5 unset their displayname:
2641        store.set(TEST_USER2.clone(), None);
2642        store.set(TEST_USER3.clone(), None);
2643        store.set(TEST_USER4.clone(), None);
2644        store.set(TEST_USER5.clone(), None);
2645        assert_eq!(store.get(&TEST_USER1).unwrap().as_ref(), "John");
2646        assert_eq!(store.get(&TEST_USER2), None);
2647        assert_eq!(store.get(&TEST_USER3), None);
2648        assert_eq!(store.get(&TEST_USER4), None);
2649        assert_eq!(store.get(&TEST_USER5), None);
2650    }
2651}