src/base.rs

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