src/base.rs

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