src/base.rs

2598 lines · 83526 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: bool,
 873    pub(crate) latest: Option<MessageTimeStamp>,
 874}
 875
 876impl UnreadInfo {
 877    pub fn is_unread(&self) -> bool {
 878        self.unread
 879    }
 880
 881    pub fn latest(&self) -> Option<&MessageTimeStamp> {
 882        self.latest.as_ref()
 883    }
 884}
 885
 886/// Track the display names for users and render any needed disambiguation for
 887/// those with overlapping names.
 888#[derive(Default)]
 889pub struct DisplayNameStore {
 890    by_ids: HashMap<OwnedUserId, String>,
 891    by_names: HashMap<String, HashSet<OwnedUserId>>,
 892}
 893
 894impl DisplayNameStore {
 895    /// Update the `HashSet` associated with a given displayname.
 896    ///
 897    /// Note that this *could* be done more elegantly using the Entry API, but
 898    /// is intentionally written in a way to avoid cloning conflicting display
 899    /// names.
 900    fn set_by_name(&mut self, user_id: OwnedUserId, name: &str) {
 901        if let Some(existing) = self.by_names.get_mut(name) {
 902            existing.insert(user_id);
 903        } else {
 904            self.by_names.insert(name.to_owned(), HashSet::from([user_id]));
 905        }
 906    }
 907
 908    /// Track a new user ID to displayname mapping, or unset any existing ones.
 909    pub fn set(&mut self, user_id: OwnedUserId, name: Option<String>) {
 910        if let Some(name) = name.as_deref() {
 911            self.set_by_name(user_id.clone(), name);
 912        }
 913
 914        let previous = match (self.by_ids.entry(user_id), name) {
 915            // Nothing to do!
 916            (Entry::Vacant(_), None) => None,
 917
 918            // Setting initial display name for user:
 919            (Entry::Vacant(v), Some(name)) => {
 920                v.insert(name);
 921                None
 922            },
 923
 924            // Unsetting display name:
 925            (Entry::Occupied(o), None) => Some(o.remove_entry()),
 926
 927            // Replacing existing name:
 928            (Entry::Occupied(mut o), Some(name)) => {
 929                if o.get() == &name {
 930                    None
 931                } else {
 932                    Some((o.key().clone(), o.insert(name)))
 933                }
 934            },
 935        };
 936
 937        let Some((user_id, previous)) = previous else {
 938            return;
 939        };
 940
 941        let Some(users) = self.by_names.get_mut(&previous) else {
 942            return;
 943        };
 944
 945        users.remove(&user_id);
 946
 947        if users.is_empty() {
 948            self.by_names.remove(&previous);
 949        }
 950    }
 951
 952    pub fn get<'a>(&'a self, user_id: &UserId) -> Option<Cow<'a, str>> {
 953        let displayname = self.by_ids.get(user_id)?;
 954        let users = self.by_names.get(displayname)?;
 955
 956        if !users.contains(user_id) {
 957            // Internal consistency error? Assume no display name:
 958            return None;
 959        }
 960
 961        if users.len() == 1 {
 962            // Unambiguous!
 963            return Some(Cow::Borrowed(displayname.as_str()));
 964        }
 965
 966        // Ambiguous username, so include unique user ID:
 967        Some(Cow::Owned(format!("{displayname} ({user_id})")))
 968    }
 969}
 970
 971/// Information about room's the user's joined.
 972pub struct RoomInfo {
 973    /// The display name for this room.
 974    pub name: Option<String>,
 975
 976    /// The tags placed on this room.
 977    pub tags: Option<Tags>,
 978
 979    /// A map of event IDs to where they are stored in this struct.
 980    pub keys: HashMap<OwnedEventId, EventLocation>,
 981
 982    /// The messages loaded for this room.
 983    messages: Messages,
 984
 985    /// A map of read markers to display on different events.
 986    pub event_receipts: HashMap<ReceiptThread, HashMap<OwnedEventId, HashSet<OwnedUserId>>>,
 987    /// A map of the most recent read marker for each user.
 988    ///
 989    /// Every receipt in this map should also have an entry in [`event_receipts`](`Self::event_receipts`),
 990    /// however not every user has an entry. If a user's most recent receipt is
 991    /// older than the oldest loaded event, that user will not be included.
 992    pub user_receipts: HashMap<ReceiptThread, HashMap<OwnedUserId, OwnedEventId>>,
 993    /// A map of message identifiers to a map of reaction events.
 994    pub reactions: HashMap<OwnedEventId, MessageReactions>,
 995
 996    /// A map of message identifiers to thread replies.
 997    threads: HashMap<OwnedEventId, Messages>,
 998
 999    /// Whether the scrollback for this room is currently being fetched.
1000    pub fetching: bool,
1001
1002    /// Where to continue fetching from when we continue loading scrollback history.
1003    pub fetch_id: RoomFetchStatus,
1004
1005    /// The time that we last fetched scrollback for this room.
1006    pub fetch_last: Option<Instant>,
1007
1008    /// Users currently typing in this room, and when we received notification of them doing so.
1009    pub users_typing: Option<(Instant, Vec<OwnedUserId>)>,
1010
1011    /// The display names for users in this room.
1012    pub display_names: DisplayNameStore,
1013
1014    /// The last time the room was rendered, used to detect if it is currently open.
1015    pub draw_last: Option<Instant>,
1016}
1017
1018impl Default for RoomInfo {
1019    fn default() -> Self {
1020        Self {
1021            messages: Messages::new(ReceiptThread::Main),
1022
1023            name: Default::default(),
1024            tags: Default::default(),
1025            keys: Default::default(),
1026            event_receipts: Default::default(),
1027            user_receipts: Default::default(),
1028            reactions: Default::default(),
1029            threads: Default::default(),
1030            fetching: Default::default(),
1031            fetch_id: Default::default(),
1032            fetch_last: Default::default(),
1033            users_typing: Default::default(),
1034            display_names: Default::default(),
1035            draw_last: Default::default(),
1036        }
1037    }
1038}
1039
1040impl RoomInfo {
1041    pub fn get_thread(&self, root: Option<&EventId>) -> Option<&Messages> {
1042        if let Some(thread_root) = root {
1043            self.threads.get(thread_root)
1044        } else {
1045            Some(&self.messages)
1046        }
1047    }
1048
1049    pub fn get_thread_mut(&mut self, root: Option<OwnedEventId>) -> &mut Messages {
1050        if let Some(thread_root) = root {
1051            self.threads
1052                .entry(thread_root.clone())
1053                .or_insert_with(|| Messages::thread(thread_root))
1054        } else {
1055            &mut self.messages
1056        }
1057    }
1058
1059    /// Get the event for the last message in a thread (or the thread root if there are no
1060    /// in-thread replies yet).
1061    ///
1062    /// This returns `None` if the event identifier isn't in the room.
1063    pub fn get_thread_last<'a>(
1064        &'a self,
1065        thread_root: &OwnedEventId,
1066    ) -> Option<&'a OriginalRoomMessageEvent> {
1067        let last = self.threads.get(thread_root).and_then(|t| Some(t.last_key_value()?.1));
1068
1069        let msg = if let Some(last) = last {
1070            &last.event
1071        } else if let EventLocation::Message(_, key) = self.keys.get(thread_root)? {
1072            let msg = self.messages.get(key)?;
1073            &msg.event
1074        } else {
1075            return None;
1076        };
1077
1078        if let MessageEvent::Original(ev) = &msg {
1079            Some(ev)
1080        } else {
1081            None
1082        }
1083    }
1084
1085    /// Get the reactions and their counts for a message.
1086    pub fn get_reactions(&self, event_id: &EventId) -> Vec<(&str, usize)> {
1087        if let Some(reacts) = self.reactions.get(event_id) {
1088            let mut counts = HashMap::new();
1089
1090            let mut seen_user_reactions = BTreeSet::new();
1091
1092            for (key, user) in reacts.values() {
1093                if !seen_user_reactions.contains(&(key, user)) {
1094                    seen_user_reactions.insert((key, user));
1095                    let count = counts.entry(key.as_str()).or_default();
1096                    *count += 1;
1097                }
1098            }
1099
1100            let mut reactions = counts.into_iter().collect::<Vec<_>>();
1101            reactions.sort();
1102
1103            reactions
1104        } else {
1105            vec![]
1106        }
1107    }
1108
1109    /// Map an event identifier to its [MessageKey].
1110    pub fn get_message_key(&self, event_id: &EventId) -> Option<&MessageKey> {
1111        self.keys.get(event_id)?.to_message_key()
1112    }
1113
1114    /// Get an event for an identifier.
1115    pub fn get_event(&self, event_id: &EventId) -> Option<&Message> {
1116        self.messages.get(self.get_message_key(event_id)?)
1117    }
1118
1119    /// Get an event for an identifier as mutable.
1120    pub fn get_event_mut(&mut self, event_id: &EventId) -> Option<&mut Message> {
1121        self.messages.get_mut(self.keys.get(event_id)?.to_message_key()?)
1122    }
1123
1124    pub fn redact(&mut self, ev: OriginalSyncRoomRedactionEvent) {
1125        let Some(redacts) = &ev.redacts else {
1126            return;
1127        };
1128
1129        match self.keys.get(redacts) {
1130            None => return,
1131            Some(EventLocation::State(key)) => {
1132                if let Some(msg) = self.messages.get_mut(key) {
1133                    let ev = SyncRoomRedactionEvent::Original(ev);
1134                    msg.redact(ev);
1135                }
1136            },
1137            Some(EventLocation::Message(None, 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(Some(root), key)) => {
1144                if let Some(thread) = self.threads.get_mut(root) {
1145                    if let Some(msg) = thread.get_mut(key) {
1146                        let ev = SyncRoomRedactionEvent::Original(ev);
1147                        msg.redact(ev);
1148                    }
1149                }
1150            },
1151            Some(EventLocation::Reaction(event_id)) => {
1152                if let Some(reactions) = self.reactions.get_mut(event_id) {
1153                    reactions.remove(redacts);
1154                }
1155
1156                self.keys.remove(redacts);
1157            },
1158            Some(EventLocation::Sticker(key)) => {
1159                if let Some(msg) = self.messages.get_mut(key) {
1160                    let ev = SyncRoomRedactionEvent::Original(ev);
1161                    msg.redact(ev);
1162                }
1163            },
1164        }
1165    }
1166
1167    /// Insert a reaction to a message.
1168    pub fn insert_reaction(&mut self, react: ReactionEvent) {
1169        match react {
1170            MessageLikeEvent::Original(react) => {
1171                let rel_id = react.content.relates_to.event_id;
1172                let key = react.content.relates_to.key;
1173
1174                let message = self.reactions.entry(rel_id.clone()).or_default();
1175                let event_id = react.event_id;
1176                let user_id = react.sender;
1177
1178                message.insert(event_id.clone(), (key, user_id));
1179
1180                let loc = EventLocation::Reaction(rel_id);
1181                self.keys.insert(event_id, loc);
1182            },
1183            MessageLikeEvent::Redacted(_) => {
1184                return;
1185            },
1186        }
1187    }
1188
1189    /// Insert a sticker
1190    pub fn insert_sticker(
1191        &mut self,
1192        sticker: StickerEvent,
1193        settings: &ApplicationSettings,
1194        previews: &mut PreviewManager,
1195        worker: &Requester,
1196    ) {
1197        match sticker {
1198            MessageLikeEvent::Original(ref sticker_content) => {
1199                let key =
1200                    (sticker_content.origin_server_ts.into(), sticker_content.event_id.clone());
1201
1202                let loc = EventLocation::Sticker(key.clone());
1203
1204                self.keys.insert(sticker_content.event_id.clone(), loc);
1205                self.messages.insert_message(key.clone(), sticker.clone());
1206
1207                if let (Some(msg), Some(image_preview)) = (
1208                    self.get_event_mut(&sticker_content.event_id),
1209                    &settings.tunables.image_preview,
1210                ) {
1211                    let source: MediaSource = sticker_content.content.source.clone().into();
1212                    msg.image_preview = Some(source.clone());
1213                    previews.register_preview(settings, source, image_preview.size, worker);
1214                }
1215            },
1216            MessageLikeEvent::Redacted(ref redaction) => {
1217                let key = (redaction.origin_server_ts.into(), redaction.event_id.clone());
1218                self.messages.insert_message(key.clone(), sticker.clone());
1219            },
1220        }
1221    }
1222
1223    /// Insert an edit.
1224    pub fn insert_edit(&mut self, msg: Replacement<RoomMessageEventContentWithoutRelation>) {
1225        let event_id = msg.event_id;
1226        let new_msgtype = msg.new_content;
1227
1228        let Some(EventLocation::Message(thread, key)) = self.keys.get(&event_id) else {
1229            return;
1230        };
1231
1232        let source = if let Some(thread) = thread {
1233            self.threads
1234                .entry(thread.clone())
1235                .or_insert_with(|| Messages::thread(thread.clone()))
1236        } else {
1237            &mut self.messages
1238        };
1239
1240        let Some(msg) = source.get_mut(key) else {
1241            return;
1242        };
1243
1244        match &mut msg.event {
1245            MessageEvent::Original(orig) => {
1246                orig.content.apply_replacement(new_msgtype);
1247            },
1248            MessageEvent::Local(_, content) => {
1249                content.apply_replacement(new_msgtype);
1250            },
1251            MessageEvent::Redacted(_, _) |
1252            MessageEvent::State(_) |
1253            MessageEvent::Sticker(_) |
1254            MessageEvent::EncryptedOriginal(_) |
1255            MessageEvent::EncryptedRedacted(_) => {
1256                return;
1257            },
1258        }
1259
1260        msg.html = msg.event.html();
1261        msg.event.strip_reply_fallback();
1262    }
1263
1264    pub fn insert_any_state(&mut self, msg: AnySyncStateEvent) {
1265        let event_id = msg.event_id().to_owned();
1266        let key = (msg.origin_server_ts().into(), event_id.clone());
1267
1268        let loc = EventLocation::State(key.clone());
1269        self.keys.insert(event_id, loc);
1270        self.messages.insert_message(key, msg);
1271    }
1272
1273    /// Indicates whether this room has unread messages.
1274    pub fn unreads(&self, room: &MatrixRoom, settings: &ApplicationSettings) -> UnreadInfo {
1275        let marked_unread = room.is_marked_unread();
1276
1277        let last_message = self.messages.last_key_value();
1278
1279        let last_receipt = self
1280            .user_receipts
1281            .get(&ReceiptThread::Main)
1282            .and_then(|receipts| receipts.get(&settings.profile.user_id));
1283        let last_receipt = last_receipt.as_ref().and_then(|event_id| {
1284            match &self.keys.get(*event_id)? {
1285                EventLocation::Message(_, key) |
1286                EventLocation::State(key) |
1287                EventLocation::Sticker(key) => Some(key),
1288                EventLocation::Reaction(_) => None,
1289            }
1290        });
1291
1292        let last_unthreaded = self
1293            .user_receipts
1294            .get(&ReceiptThread::Unthreaded)
1295            .and_then(|receipts| receipts.get(&settings.profile.user_id));
1296        let last_unthreaded = last_unthreaded.as_ref().and_then(|event_id| {
1297            match &self.keys.get(*event_id)? {
1298                EventLocation::Message(_, key) |
1299                EventLocation::State(key) |
1300                EventLocation::Sticker(key) => Some(key),
1301                EventLocation::Reaction(_) => None,
1302            }
1303        });
1304
1305        let last_receipt = std::cmp::max(last_receipt, last_unthreaded);
1306
1307        match (last_message, last_receipt) {
1308            (Some(((ts, _), _)), Some((read_ts, _))) => {
1309                UnreadInfo {
1310                    unread: marked_unread | (ts > read_ts),
1311                    latest: Some(*ts),
1312                }
1313            },
1314            (Some(((ts, _), _)), None) => {
1315                // If we've never loaded/generated a room's receipt (example,
1316                // a newly joined but never viewed room), show it as unread.
1317                UnreadInfo { unread: true, latest: Some(*ts) }
1318            },
1319            (None, _) => UnreadInfo { unread: marked_unread, latest: None },
1320        }
1321    }
1322
1323    /// Inserts events that couldn't be decrypted into the scrollback.
1324    pub fn insert_encrypted(&mut self, msg: RoomEncryptedEvent) {
1325        let event_id = msg.event_id().to_owned();
1326        let key = (msg.origin_server_ts().into(), event_id.clone());
1327
1328        self.keys.insert(event_id, EventLocation::Message(None, key.clone()));
1329        self.messages.insert(key, msg.into());
1330    }
1331
1332    /// Insert a new message.
1333    pub fn insert_message(&mut self, msg: RoomMessageEvent) {
1334        let event_id = msg.event_id().to_owned();
1335        let key = (msg.origin_server_ts().into(), event_id.clone());
1336
1337        let loc = EventLocation::Message(None, key.clone());
1338        self.keys.insert(event_id, loc);
1339        self.messages.insert_message(key, msg);
1340    }
1341
1342    fn insert_thread(&mut self, msg: RoomMessageEvent, thread_root: OwnedEventId) {
1343        let event_id = msg.event_id().to_owned();
1344        let key = (msg.origin_server_ts().into(), event_id.clone());
1345
1346        let replies = self
1347            .threads
1348            .entry(thread_root.clone())
1349            .or_insert_with(|| Messages::thread(thread_root.clone()));
1350        let loc = EventLocation::Message(Some(thread_root), key.clone());
1351        self.keys.insert(event_id, loc);
1352        replies.insert_message(key, msg);
1353    }
1354
1355    /// Insert a new message event.
1356    pub fn insert(&mut self, msg: RoomMessageEvent) {
1357        match msg {
1358            RoomMessageEvent::Original(OriginalRoomMessageEvent {
1359                content: RoomMessageEventContent { relates_to: Some(ref relates_to), .. },
1360                ..
1361            }) => {
1362                match relates_to {
1363                    Relation::Replacement(repl) => self.insert_edit(repl.clone()),
1364                    Relation::Thread(Thread { event_id, .. }) => {
1365                        let event_id = event_id.clone();
1366                        self.insert_thread(msg, event_id);
1367                    },
1368                    Relation::Reply { .. } => self.insert_message(msg),
1369                    _ => self.insert_message(msg),
1370                }
1371            },
1372            _ => self.insert_message(msg),
1373        }
1374    }
1375
1376    /// Insert a new message event, and prepare for image-preview if it has an image attachment.
1377    pub fn insert_with_preview(
1378        &mut self,
1379        ev: RoomMessageEvent,
1380        settings: &ApplicationSettings,
1381        previews: &mut PreviewManager,
1382        worker: &Requester,
1383    ) {
1384        let source = source_from_event(&ev);
1385        self.insert(ev);
1386
1387        if let Some((event_id, source)) = source {
1388            if let (Some(msg), Some(image_preview)) =
1389                (self.get_event_mut(&event_id), &settings.tunables.image_preview)
1390            {
1391                msg.image_preview = Some(source.clone());
1392                previews.register_preview(settings, source, image_preview.size, worker)
1393            }
1394        }
1395    }
1396
1397    /// Indicates whether we've recently fetched scrollback for this room.
1398    pub fn recently_fetched(&self) -> bool {
1399        self.fetch_last.is_some_and(|i| i.elapsed() < ROOM_FETCH_DEBOUNCE)
1400    }
1401
1402    fn clear_receipt(&mut self, thread: &ReceiptThread, user_id: &OwnedUserId) -> Option<()> {
1403        let old_event_id =
1404            self.user_receipts.get(thread).and_then(|receipts| receipts.get(user_id))?;
1405        let old_thread = self.event_receipts.get_mut(thread)?;
1406        let old_receipts = old_thread.get_mut(old_event_id)?;
1407        old_receipts.remove(user_id);
1408
1409        if old_receipts.is_empty() {
1410            old_thread.remove(old_event_id);
1411        }
1412        if old_thread.is_empty() {
1413            self.event_receipts.remove(thread);
1414        }
1415
1416        None
1417    }
1418
1419    pub fn set_receipt(
1420        &mut self,
1421        thread: ReceiptThread,
1422        user_id: OwnedUserId,
1423        event_id: OwnedEventId,
1424    ) {
1425        self.clear_receipt(&thread, &user_id);
1426        self.event_receipts
1427            .entry(thread.clone())
1428            .or_default()
1429            .entry(event_id.clone())
1430            .or_default()
1431            .insert(user_id.clone());
1432        self.user_receipts.entry(thread).or_default().insert(user_id, event_id);
1433    }
1434
1435    pub fn fully_read(&mut self, user_id: &UserId) {
1436        let Some(((_, event_id), _)) = self.messages.last_key_value() else {
1437            return;
1438        };
1439
1440        self.set_receipt(ReceiptThread::Main, user_id.to_owned(), event_id.clone());
1441
1442        let newest = self
1443            .threads
1444            .iter()
1445            .filter_map(|(thread_id, messages)| {
1446                let thread = ReceiptThread::Thread(thread_id.to_owned());
1447
1448                messages
1449                    .last_key_value()
1450                    .map(|((_, event_id), _)| (thread, event_id.to_owned()))
1451            })
1452            .collect::<Vec<_>>();
1453
1454        for (thread, event_id) in newest.into_iter() {
1455            self.set_receipt(thread, user_id.to_owned(), event_id.clone());
1456        }
1457    }
1458
1459    pub fn receipts<'a>(
1460        &'a self,
1461        user_id: &'a UserId,
1462    ) -> impl Iterator<Item = (&'a ReceiptThread, &'a OwnedEventId)> + 'a {
1463        self.user_receipts
1464            .iter()
1465            .filter_map(move |(t, rs)| rs.get(user_id).map(|r| (t, r)))
1466    }
1467
1468    fn get_typers(&self) -> &[OwnedUserId] {
1469        if let Some((t, users)) = &self.users_typing {
1470            if t.elapsed() < Duration::from_secs(4) {
1471                return users.as_ref();
1472            } else {
1473                return &[];
1474            }
1475        } else {
1476            return &[];
1477        }
1478    }
1479
1480    fn get_typing_spans<'a>(&'a self, settings: &'a ApplicationSettings) -> Line<'a> {
1481        let typers = self.get_typers();
1482        let n = typers.len();
1483
1484        match n {
1485            0 => Line::from(vec![]),
1486            1 => {
1487                let user = settings.get_user_span(typers[0].as_ref(), self);
1488
1489                Line::from(vec![user, Span::from(" is typing...")])
1490            },
1491            2 => {
1492                let user1 = settings.get_user_span(typers[0].as_ref(), self);
1493                let user2 = settings.get_user_span(typers[1].as_ref(), self);
1494
1495                Line::from(vec![
1496                    user1,
1497                    Span::raw(" and "),
1498                    user2,
1499                    Span::from(" are typing..."),
1500                ])
1501            },
1502            n if n < 5 => Line::from("Several people are typing..."),
1503            _ => Line::from("Many people are typing..."),
1504        }
1505    }
1506
1507    /// Update typing information for this room.
1508    pub fn set_typing(&mut self, user_ids: Vec<OwnedUserId>) {
1509        self.users_typing = (Instant::now(), user_ids).into();
1510    }
1511
1512    /// Create a [Rect] that displays what users are typing.
1513    pub fn render_typing(
1514        &mut self,
1515        area: Rect,
1516        buf: &mut Buffer,
1517        settings: &ApplicationSettings,
1518    ) -> Rect {
1519        if area.height <= 2 || area.width <= 20 {
1520            return area;
1521        }
1522
1523        if !settings.tunables.typing_notice_display {
1524            // still keep one line blank, so `render_jump_to_recent` doesn't immediately hide the
1525            // last line in scrollback
1526            return Rect::new(area.x, area.y, area.width, area.height - 1);
1527        }
1528
1529        let top = Rect::new(area.x, area.y, area.width, area.height - 1);
1530        let bar = Rect::new(area.x, area.y + top.height, area.width, 1);
1531
1532        Paragraph::new(self.get_typing_spans(settings))
1533            .alignment(Alignment::Center)
1534            .render(bar, buf);
1535
1536        return top;
1537    }
1538
1539    /// Checks if a given user has reacted with the given emoji on the given event
1540    pub fn user_reactions_contains(
1541        &mut self,
1542        user_id: &UserId,
1543        event_id: &EventId,
1544        emoji: &str,
1545    ) -> bool {
1546        if let Some(reactions) = self.reactions.get(event_id) {
1547            reactions
1548                .values()
1549                .any(|(annotation, user)| annotation == emoji && user == user_id)
1550        } else {
1551            false
1552        }
1553    }
1554}
1555
1556/// Generate a [CompletionMap] for Emoji shortcodes.
1557fn emoji_map() -> CompletionMap<String, &'static Emoji> {
1558    let mut emojis = CompletionMap::default();
1559
1560    for emoji in emojis::iter() {
1561        for shortcode in emoji.shortcodes() {
1562            emojis.insert(shortcode.to_string(), emoji);
1563        }
1564    }
1565
1566    return emojis;
1567}
1568
1569#[cfg(unix)]
1570fn picker_from_termios(protocol_type: Option<ProtocolType>) -> Option<Picker> {
1571    let mut picker = match Picker::from_query_stdio() {
1572        Ok(picker) => picker,
1573        Err(e) => {
1574            tracing::error!("Failed to setup image previews: {e}");
1575            return None;
1576        },
1577    };
1578
1579    if let Some(protocol_type) = protocol_type {
1580        picker.set_protocol_type(protocol_type);
1581    }
1582
1583    Some(picker)
1584}
1585
1586/// Windows cannot guess the right protocol, and always needs type and font_size.
1587#[cfg(windows)]
1588fn picker_from_termios(_: Option<ProtocolType>) -> Option<Picker> {
1589    tracing::error!("\"image_preview\" requires \"protocol\" with \"type\" and \"font_size\" options on Windows.");
1590    None
1591}
1592
1593fn picker_from_settings(settings: &ApplicationSettings) -> Option<Picker> {
1594    let image_preview = settings.tunables.image_preview.as_ref()?;
1595    let image_preview_protocol = image_preview.protocol.as_ref();
1596
1597    if let Some(&ImagePreviewProtocolValues {
1598        r#type: Some(protocol_type),
1599        font_size: Some(font_size),
1600    }) = image_preview_protocol
1601    {
1602        // User forced type and font_size: use that.
1603        let mut picker = Picker::from_fontsize(font_size);
1604        picker.set_protocol_type(protocol_type);
1605        Some(picker)
1606    } else {
1607        // Guess, but use type if forced.
1608        picker_from_termios(image_preview_protocol.and_then(|p| p.r#type))
1609    }
1610}
1611
1612/// Information gathered during server syncs about joined rooms.
1613#[derive(Default)]
1614pub struct SyncInfo {
1615    /// Spaces that the user is a member of.
1616    pub spaces: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
1617
1618    /// Rooms that the user is a member of.
1619    pub rooms: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
1620
1621    /// DMs that the user is a member of.
1622    pub dms: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
1623}
1624
1625impl SyncInfo {
1626    pub fn rooms(&self) -> impl Iterator<Item = &RoomId> {
1627        self.rooms.iter().map(|r| r.0.room_id())
1628    }
1629
1630    pub fn dms(&self) -> impl Iterator<Item = &RoomId> {
1631        self.dms.iter().map(|r| r.0.room_id())
1632    }
1633
1634    pub fn chats(&self) -> impl Iterator<Item = &RoomId> {
1635        self.rooms().chain(self.dms())
1636    }
1637}
1638
1639static MESSAGE_NEED_TTL: u8 = 30;
1640
1641#[derive(Debug, PartialEq)]
1642/// Load messages until the event is loaded or `ttl` loads are exceeded
1643pub struct MessageNeed {
1644    pub event_id: OwnedEventId,
1645    pub ttl: u8,
1646}
1647
1648#[derive(Default, Debug, PartialEq)]
1649pub struct Need {
1650    pub members: bool,
1651    pub messages: Option<Vec<MessageNeed>>,
1652}
1653
1654/// Things that need loading for different rooms.
1655#[derive(Default)]
1656pub struct RoomNeeds {
1657    needs: HashMap<OwnedRoomId, Need>,
1658}
1659
1660impl RoomNeeds {
1661    /// Mark a room for needing to load members.
1662    pub fn need_members(&mut self, room_id: OwnedRoomId) {
1663        self.needs.entry(room_id).or_default().members = true;
1664    }
1665
1666    /// Mark a room for needing to load messages.
1667    pub fn need_messages(&mut self, room_id: OwnedRoomId) {
1668        self.needs.entry(room_id).or_default().messages.get_or_insert_default();
1669    }
1670
1671    /// Mark a room for needing to load messages until the given message is loaded or a retry limit
1672    /// is exceeded.
1673    pub fn need_message(&mut self, room_id: OwnedRoomId, event_id: OwnedEventId) {
1674        let messages = &mut self.needs.entry(room_id).or_default().messages.get_or_insert_default();
1675
1676        messages.push(MessageNeed { event_id, ttl: MESSAGE_NEED_TTL });
1677    }
1678
1679    pub fn need_messages_all(&mut self, room_id: OwnedRoomId, message_needs: Vec<MessageNeed>) {
1680        self.needs
1681            .entry(room_id)
1682            .or_default()
1683            .messages
1684            .get_or_insert_default()
1685            .extend(message_needs);
1686    }
1687
1688    pub fn rooms(&self) -> usize {
1689        self.needs.len()
1690    }
1691}
1692
1693impl IntoIterator for RoomNeeds {
1694    type Item = (OwnedRoomId, Need);
1695    type IntoIter = IntoIter<OwnedRoomId, Need>;
1696
1697    fn into_iter(self) -> Self::IntoIter {
1698        self.needs.into_iter()
1699    }
1700}
1701
1702/// The main application state.
1703pub struct ChatStore {
1704    /// `:`-commands
1705    pub cmds: ProgramCommands,
1706
1707    /// Handle for communicating w/ the worker thread.
1708    pub worker: Requester,
1709
1710    /// Map of joined rooms.
1711    pub rooms: CompletionMap<OwnedRoomId, RoomInfo>,
1712
1713    /// Map of room names.
1714    pub names: CompletionMap<String, OwnedRoomId>,
1715
1716    /// Presence information for other users.
1717    pub presences: CompletionMap<OwnedUserId, PresenceState>,
1718
1719    /// In-progress and completed verifications.
1720    pub verifications: HashMap<String, SasVerification>,
1721
1722    /// Settings for the current profile loaded from config file.
1723    pub settings: ApplicationSettings,
1724
1725    /// Set of rooms that need more messages loaded in their scrollback.
1726    pub need_load: RoomNeeds,
1727
1728    /// [CompletionMap] of Emoji shortcodes.
1729    pub emojis: CompletionMap<String, &'static Emoji>,
1730
1731    /// Information gathered by the background thread.
1732    pub sync_info: SyncInfo,
1733
1734    /// Rendered image previews.
1735    pub previews: PreviewManager,
1736
1737    /// Last draw time, used to match with RoomInfo's draw_last.
1738    pub draw_curr: Option<Instant>,
1739
1740    /// Whether to ring the terminal bell on the next redraw.
1741    pub ring_bell: bool,
1742
1743    /// Whether the application is currently focused
1744    pub focused: bool,
1745
1746    /// Collator for locale-aware text sorting.
1747    pub collator: feruca::Collator,
1748
1749    /// Notifications that should be dismissed when the user opens the room.
1750    pub open_notifications: HashMap<OwnedRoomId, Vec<NotificationHandle>>,
1751}
1752
1753impl ChatStore {
1754    /// Create a new [ChatStore].
1755    pub fn new(worker: Requester, settings: ApplicationSettings) -> Self {
1756        let picker = picker_from_settings(&settings);
1757
1758        ChatStore {
1759            worker,
1760            settings,
1761            previews: PreviewManager::new(picker),
1762            cmds: crate::commands::setup_commands(),
1763            emojis: emoji_map(),
1764
1765            collator: Default::default(),
1766            names: Default::default(),
1767            rooms: Default::default(),
1768            presences: Default::default(),
1769            verifications: Default::default(),
1770            need_load: Default::default(),
1771            sync_info: Default::default(),
1772            draw_curr: None,
1773            ring_bell: false,
1774            focused: true,
1775            open_notifications: Default::default(),
1776        }
1777    }
1778
1779    /// Get a joined room.
1780    pub fn get_joined_room(&self, room_id: &RoomId) -> Option<MatrixRoom> {
1781        let room = self.worker.client.get_room(room_id)?;
1782
1783        if room.state() == MatrixRoomState::Joined {
1784            Some(room)
1785        } else {
1786            None
1787        }
1788    }
1789
1790    /// Get the title for a room.
1791    pub fn get_room_title(&self, room_id: &RoomId) -> String {
1792        self.rooms
1793            .get(room_id)
1794            .and_then(|i| i.name.as_ref())
1795            .map(String::from)
1796            .unwrap_or_else(|| "Untitled Matrix Room".to_string())
1797    }
1798
1799    /// Get the [RoomInfo] for a given room identifier.
1800    pub fn get_room_info(&mut self, room_id: OwnedRoomId) -> &mut RoomInfo {
1801        self.rooms.get_or_default(room_id)
1802    }
1803
1804    /// Set the name for a room.
1805    pub fn set_room_name(&mut self, room_id: &RoomId, name: &str) {
1806        self.rooms.get_or_default(room_id.to_owned()).name = name.to_string().into();
1807    }
1808
1809    /// Insert a new E2EE verification.
1810    pub fn insert_sas(&mut self, sas: SasVerification) {
1811        let key = format!("{}/{}", sas.other_user_id(), sas.other_device().device_id());
1812
1813        self.verifications.insert(key, sas);
1814    }
1815}
1816
1817impl ApplicationStore for ChatStore {}
1818
1819/// Identified used to track window content.
1820#[derive(Clone, Debug, Eq, Hash, PartialEq)]
1821pub enum IambId {
1822    /// A Matrix room, with an optional thread to show.
1823    Room(OwnedRoomId, Option<OwnedEventId>),
1824
1825    /// The `:dms` window.
1826    DirectList,
1827
1828    /// The `:members` window for a given Matrix room.
1829    MemberList(OwnedRoomId),
1830
1831    /// The `:rooms` window.
1832    RoomList,
1833
1834    /// The `:spaces` window.
1835    SpaceList,
1836
1837    /// The `:verify` window.
1838    VerifyList,
1839
1840    /// The `:welcome` window.
1841    Welcome,
1842
1843    /// The `:chats` window.
1844    ChatList,
1845
1846    /// The `:unreads` window.
1847    UnreadList,
1848}
1849
1850impl Display for IambId {
1851    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1852        match self {
1853            IambId::Room(room_id, None) => {
1854                write!(f, "iamb://room/{room_id}")
1855            },
1856            IambId::Room(room_id, Some(thread)) => {
1857                write!(f, "iamb://room/{room_id}/threads/{thread}")
1858            },
1859            IambId::MemberList(room_id) => {
1860                write!(f, "iamb://members/{room_id}")
1861            },
1862            IambId::DirectList => f.write_str("iamb://dms"),
1863            IambId::RoomList => f.write_str("iamb://rooms"),
1864            IambId::SpaceList => f.write_str("iamb://spaces"),
1865            IambId::VerifyList => f.write_str("iamb://verify"),
1866            IambId::Welcome => f.write_str("iamb://welcome"),
1867            IambId::ChatList => f.write_str("iamb://chats"),
1868            IambId::UnreadList => f.write_str("iamb://unreads"),
1869        }
1870    }
1871}
1872
1873impl ApplicationWindowId for IambId {}
1874
1875impl Serialize for IambId {
1876    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1877    where
1878        S: Serializer,
1879    {
1880        serializer.serialize_str(&self.to_string())
1881    }
1882}
1883
1884impl<'de> Deserialize<'de> for IambId {
1885    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1886    where
1887        D: Deserializer<'de>,
1888    {
1889        deserializer.deserialize_str(IambIdVisitor)
1890    }
1891}
1892
1893/// [serde] visitor for deserializing [IambId].
1894struct IambIdVisitor;
1895
1896impl Visitor<'_> for IambIdVisitor {
1897    type Value = IambId;
1898
1899    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1900        formatter.write_str("a valid window URL")
1901    }
1902
1903    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1904    where
1905        E: SerdeError,
1906    {
1907        let Ok(url) = Url::parse(value) else {
1908            return Err(E::custom("Invalid iamb window URL"));
1909        };
1910
1911        if url.scheme() != "iamb" {
1912            return Err(E::custom("Invalid iamb window URL"));
1913        }
1914
1915        match url.domain() {
1916            Some("room") => {
1917                let Some(path) = url.path_segments() else {
1918                    return Err(E::custom("Invalid members window URL"));
1919                };
1920
1921                match *path.collect::<Vec<_>>().as_slice() {
1922                    [room_id] => {
1923                        let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
1924                            return Err(E::custom("Invalid room identifier"));
1925                        };
1926
1927                        Ok(IambId::Room(room_id, None))
1928                    },
1929                    [room_id, "threads", thread_root] => {
1930                        let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
1931                            return Err(E::custom("Invalid room identifier"));
1932                        };
1933
1934                        let Ok(thread_root) = OwnedEventId::try_from(thread_root) else {
1935                            return Err(E::custom("Invalid thread root identifier"));
1936                        };
1937
1938                        Ok(IambId::Room(room_id, Some(thread_root)))
1939                    },
1940                    _ => return Err(E::custom("Invalid members window URL")),
1941                }
1942            },
1943            Some("members") => {
1944                let Some(path) = url.path_segments() else {
1945                    return Err(E::custom("Invalid members window URL"));
1946                };
1947
1948                let &[room_id] = path.collect::<Vec<_>>().as_slice() else {
1949                    return Err(E::custom("Invalid members window URL"));
1950                };
1951
1952                let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
1953                    return Err(E::custom("Invalid room identifier"));
1954                };
1955
1956                Ok(IambId::MemberList(room_id))
1957            },
1958            Some("dms") => {
1959                if url.path() != "" {
1960                    return Err(E::custom("iamb://dms takes no path"));
1961                }
1962
1963                Ok(IambId::DirectList)
1964            },
1965            Some("rooms") => {
1966                if url.path() != "" {
1967                    return Err(E::custom("iamb://rooms takes no path"));
1968                }
1969
1970                Ok(IambId::RoomList)
1971            },
1972            Some("spaces") => {
1973                if url.path() != "" {
1974                    return Err(E::custom("iamb://spaces takes no path"));
1975                }
1976
1977                Ok(IambId::SpaceList)
1978            },
1979            Some("verify") => {
1980                if url.path() != "" {
1981                    return Err(E::custom("iamb://verify takes no path"));
1982                }
1983
1984                Ok(IambId::VerifyList)
1985            },
1986            Some("welcome") => {
1987                if url.path() != "" {
1988                    return Err(E::custom("iamb://welcome takes no path"));
1989                }
1990
1991                Ok(IambId::Welcome)
1992            },
1993            Some("chats") => {
1994                if url.path() != "" {
1995                    return Err(E::custom("iamb://chats takes no path"));
1996                }
1997
1998                Ok(IambId::ChatList)
1999            },
2000            Some("unreads") => {
2001                if url.path() != "" {
2002                    return Err(E::custom("iamb://unreads takes no path"));
2003                }
2004
2005                Ok(IambId::UnreadList)
2006            },
2007            Some(s) => Err(E::custom(format!("{s:?} is not a valid window"))),
2008            None => Err(E::custom("Invalid iamb window URL")),
2009        }
2010    }
2011}
2012
2013/// Which part of the room window's UI is focused.
2014#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
2015pub enum RoomFocus {
2016    /// The scrollback for a room window is focused.
2017    Scrollback,
2018
2019    /// The message bar for a room window is focused.
2020    MessageBar,
2021}
2022
2023impl RoomFocus {
2024    /// Whether this is [RoomFocus::Scrollback].
2025    pub fn is_scrollback(&self) -> bool {
2026        matches!(self, RoomFocus::Scrollback)
2027    }
2028
2029    /// Whether this is [RoomFocus::MessageBar].
2030    pub fn is_msgbar(&self) -> bool {
2031        matches!(self, RoomFocus::MessageBar)
2032    }
2033
2034    pub fn toggle(&mut self) {
2035        *self = match self {
2036            RoomFocus::MessageBar => RoomFocus::Scrollback,
2037            RoomFocus::Scrollback => RoomFocus::MessageBar,
2038        };
2039    }
2040}
2041
2042/// Identifiers used to track where a mark was placed.
2043///
2044/// While this is the "buffer identifier" for the mark,
2045/// not all of these are necessarily actual buffers.
2046#[derive(Clone, Debug, Eq, Hash, PartialEq)]
2047pub enum IambBufferId {
2048    /// The command bar buffer.
2049    Command(CommandType),
2050
2051    /// The message buffer or a specific message in a room.
2052    Room(OwnedRoomId, Option<OwnedEventId>, RoomFocus),
2053
2054    /// The `:dms` window.
2055    DirectList,
2056
2057    /// The `:members` window for a room.
2058    MemberList(OwnedRoomId),
2059
2060    /// The `:rooms` window.
2061    RoomList,
2062
2063    /// The `:spaces` window.
2064    SpaceList,
2065
2066    /// The `:verify` window.
2067    VerifyList,
2068
2069    /// The buffer for the `:rooms` window.
2070    Welcome,
2071
2072    /// The `:chats` window.
2073    ChatList,
2074
2075    /// The `:unreads` window.
2076    UnreadList,
2077}
2078
2079impl IambBufferId {
2080    /// Get the identifier for the window that contains this buffer.
2081    pub fn to_window(&self) -> Option<IambId> {
2082        let id = match self {
2083            IambBufferId::Command(_) => return None,
2084            IambBufferId::Room(room, thread, _) => IambId::Room(room.clone(), thread.clone()),
2085            IambBufferId::DirectList => IambId::DirectList,
2086            IambBufferId::MemberList(room) => IambId::MemberList(room.clone()),
2087            IambBufferId::RoomList => IambId::RoomList,
2088            IambBufferId::SpaceList => IambId::SpaceList,
2089            IambBufferId::VerifyList => IambId::VerifyList,
2090            IambBufferId::Welcome => IambId::Welcome,
2091            IambBufferId::ChatList => IambId::ChatList,
2092            IambBufferId::UnreadList => IambId::UnreadList,
2093        };
2094
2095        Some(id)
2096    }
2097}
2098
2099impl ApplicationContentId for IambBufferId {}
2100
2101impl ApplicationInfo for IambInfo {
2102    type Error = IambError;
2103    type Store = ChatStore;
2104    type Action = IambAction;
2105    type WindowId = IambId;
2106    type ContentId = IambBufferId;
2107
2108    fn content_of_command(ct: CommandType) -> IambBufferId {
2109        IambBufferId::Command(ct)
2110    }
2111}
2112
2113pub struct IambCompleter;
2114
2115impl Completer<IambInfo> for IambCompleter {
2116    fn complete(
2117        &mut self,
2118        text: &EditRope,
2119        cursor: &mut Cursor,
2120        content: &IambBufferId,
2121        store: &mut ChatStore,
2122    ) -> Vec<String> {
2123        match content {
2124            IambBufferId::Command(CommandType::Command) => complete_cmdbar(text, cursor, store),
2125            IambBufferId::Command(CommandType::Search) => vec![],
2126            IambBufferId::Room(_, _, RoomFocus::MessageBar) => complete_msgbar(text, cursor, store),
2127            IambBufferId::Room(_, _, RoomFocus::Scrollback) => vec![],
2128
2129            IambBufferId::DirectList => vec![],
2130            IambBufferId::MemberList(_) => vec![],
2131            IambBufferId::RoomList => vec![],
2132            IambBufferId::SpaceList => vec![],
2133            IambBufferId::VerifyList => vec![],
2134            IambBufferId::Welcome => vec![],
2135            IambBufferId::ChatList => vec![],
2136            IambBufferId::UnreadList => vec![],
2137        }
2138    }
2139}
2140
2141/// Tab completion for user IDs.
2142fn complete_users(text: &EditRope, cursor: &mut Cursor, store: &ChatStore) -> Vec<String> {
2143    let id = text
2144        .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
2145        .unwrap_or_else(EditRope::empty);
2146    let id = Cow::from(&id);
2147
2148    store
2149        .presences
2150        .complete(id.as_ref())
2151        .into_iter()
2152        .map(|i| i.to_string())
2153        .collect()
2154}
2155
2156/// Tab completion within the message bar.
2157fn complete_msgbar(text: &EditRope, cursor: &mut Cursor, store: &ChatStore) -> Vec<String> {
2158    let id = text
2159        .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
2160        .unwrap_or_else(EditRope::empty);
2161    let id = Cow::from(&id);
2162
2163    match id.chars().next() {
2164        // Complete room aliases.
2165        Some('#') => {
2166            return store.names.complete(id.as_ref());
2167        },
2168
2169        // Complete room identifiers.
2170        Some('!') => {
2171            return store
2172                .rooms
2173                .complete(id.as_ref())
2174                .into_iter()
2175                .map(|i| i.to_string())
2176                .collect();
2177        },
2178
2179        // Complete Emoji shortcodes.
2180        Some(':') => {
2181            let list = store.emojis.complete(&id[1..]);
2182            let iter = list.into_iter().take(200).map(|s| format!(":{s}:"));
2183
2184            return iter.collect();
2185        },
2186
2187        // Complete usernames for @ and empty strings.
2188        Some('@') | None => {
2189            return store
2190                .presences
2191                .complete(id.as_ref())
2192                .into_iter()
2193                .map(|i| i.to_string())
2194                .collect();
2195        },
2196
2197        // Unknown sigil.
2198        Some(_) => return vec![],
2199    }
2200}
2201
2202/// Tab completion for Matrix identifiers (usernames, room aliases, etc.)
2203fn complete_matrix_names(text: &EditRope, cursor: &mut Cursor, store: &ChatStore) -> Vec<String> {
2204    let id = text
2205        .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
2206        .unwrap_or_else(EditRope::empty);
2207    let id = Cow::from(&id);
2208
2209    let list = store.names.complete(id.as_ref());
2210    if !list.is_empty() {
2211        return list;
2212    }
2213
2214    let list = store.presences.complete(id.as_ref());
2215    if !list.is_empty() {
2216        return list.into_iter().map(|i| i.to_string()).collect();
2217    }
2218
2219    store
2220        .rooms
2221        .complete(id.as_ref())
2222        .into_iter()
2223        .map(|i| i.to_string())
2224        .collect()
2225}
2226
2227/// Tab completion for Emoji shortcode names.
2228fn complete_emoji(text: &EditRope, cursor: &mut Cursor, store: &ChatStore) -> Vec<String> {
2229    let sc = text.get_prefix_word_mut(cursor, &WordStyle::Little);
2230    let sc = sc.unwrap_or_else(EditRope::empty);
2231    let sc = Cow::from(&sc);
2232
2233    store.emojis.complete(sc.as_ref())
2234}
2235
2236/// Tab completion for command names.
2237fn complete_cmdname(
2238    desc: CommandDescription,
2239    text: &EditRope,
2240    cursor: &mut Cursor,
2241    store: &ChatStore,
2242) -> Vec<String> {
2243    // Complete command name and set cursor position.
2244    let _ = text.get_prefix_word_mut(cursor, &WordStyle::Little);
2245    store.cmds.complete_name(desc.command.as_str())
2246}
2247
2248/// Tab completion for command arguments.
2249fn complete_cmdarg(
2250    desc: CommandDescription,
2251    text: &EditRope,
2252    cursor: &mut Cursor,
2253    store: &ChatStore,
2254) -> Vec<String> {
2255    let cmd = match store.cmds.get(desc.command.as_str()) {
2256        Ok(cmd) => cmd,
2257        Err(_) => return vec![],
2258    };
2259
2260    match cmd.name.as_str() {
2261        "cancel" | "dms" | "edit" | "redact" | "reply" => vec![],
2262        "members" | "rooms" | "spaces" | "welcome" => vec![],
2263        "download" | "keys" | "open" | "upload" => complete_path(text, cursor),
2264        "react" | "unreact" => complete_emoji(text, cursor, store),
2265
2266        "invite" => complete_users(text, cursor, store),
2267        "join" | "split" | "vsplit" | "tabedit" => complete_matrix_names(text, cursor, store),
2268        "room" => vec![],
2269        "verify" => vec![],
2270        "vertical" | "horizontal" | "aboveleft" | "belowright" | "tab" => {
2271            complete_cmd(desc.arg.text.as_str(), text, cursor, store)
2272        },
2273        _ => vec![],
2274    }
2275}
2276
2277/// Tab completion for commands.
2278fn complete_cmd(cmd: &str, text: &EditRope, cursor: &mut Cursor, store: &ChatStore) -> Vec<String> {
2279    match CommandDescription::from_str(cmd) {
2280        Ok(desc) => {
2281            if desc.arg.untrimmed.is_empty() {
2282                complete_cmdname(desc, text, cursor, store)
2283            } else {
2284                // Complete command argument.
2285                complete_cmdarg(desc, text, cursor, store)
2286            }
2287        },
2288
2289        // Can't parse command text, so return zero completions.
2290        Err(_) => vec![],
2291    }
2292}
2293
2294/// Tab completion for the command bar.
2295fn complete_cmdbar(text: &EditRope, cursor: &mut Cursor, store: &ChatStore) -> Vec<String> {
2296    let eo = text.cursor_to_offset(cursor);
2297    let slice = text.slice(..eo);
2298    let cow = Cow::from(&slice);
2299
2300    complete_cmd(cow.as_ref(), text, cursor, store)
2301}
2302
2303#[cfg(test)]
2304pub mod tests {
2305    use std::iter::FromIterator as _;
2306
2307    use super::*;
2308    use crate::config::user_style_from_color;
2309    use crate::tests::*;
2310    use matrix_sdk::ruma::{
2311        events::{reaction::ReactionEventContent, relation::Annotation},
2312        owned_event_id,
2313        MilliSecondsSinceUnixEpoch,
2314    };
2315    use pretty_assertions::assert_eq;
2316    use ratatui::style::Color;
2317    use serde_json::{Map, Value};
2318
2319    fn create_reaction_event(
2320        content: &ReactionEventContent,
2321        event_id: &str,
2322        sender: &str,
2323    ) -> ReactionEvent {
2324        serde_json::from_value(Value::Object(Map::from_iter([
2325            ("type".to_owned(), Value::String("m.reaction".into())),
2326            ("content".to_owned(), serde_json::to_value(content).unwrap()),
2327            ("event_id".to_owned(), serde_json::to_value(event_id).unwrap()),
2328            ("sender".to_owned(), Value::String(sender.into())),
2329            (
2330                "origin_server_ts".to_owned(),
2331                serde_json::to_value(MilliSecondsSinceUnixEpoch::now()).unwrap(),
2332            ),
2333            ("room_id".to_owned(), Value::String("!foo:example.org".into())),
2334        ])))
2335        .unwrap()
2336    }
2337
2338    #[test]
2339    fn multiple_identical_reactions() {
2340        let mut info = RoomInfo::default();
2341
2342        let content = ReactionEventContent::new(Annotation::new(
2343            owned_event_id!("$my_reaction"),
2344            "🏠".to_owned(),
2345        ));
2346
2347        for i in 0..3 {
2348            let event_id = format!("$house_{i}");
2349            let react = create_reaction_event(&content, &event_id, "@foo:example.com");
2350            info.insert_reaction(react);
2351        }
2352
2353        let content = ReactionEventContent::new(Annotation::new(
2354            owned_event_id!("$my_reaction"),
2355            "🙂".to_owned(),
2356        ));
2357
2358        for i in 0..2 {
2359            let event_id = format!("$smile_{i}");
2360            let react = create_reaction_event(&content, &event_id, "@foo:example.com");
2361            info.insert_reaction(react);
2362        }
2363
2364        for i in 2..4 {
2365            let event_id = format!("$smile2_{i}");
2366            let react = create_reaction_event(&content, &event_id, "@bar:example.com");
2367            info.insert_reaction(react);
2368        }
2369
2370        assert_eq!(info.get_reactions(&owned_event_id!("$my_reaction")), vec![
2371            ("🏠", 1),
2372            ("🙂", 2)
2373        ]);
2374    }
2375
2376    #[test]
2377    fn test_typing_spans() {
2378        let mut info = RoomInfo::default();
2379        let settings = mock_settings();
2380
2381        let users0 = vec![];
2382        let users1 = vec![TEST_USER1.clone()];
2383        let users2 = vec![TEST_USER1.clone(), TEST_USER2.clone()];
2384        let users4 = vec![
2385            TEST_USER1.clone(),
2386            TEST_USER2.clone(),
2387            TEST_USER3.clone(),
2388            TEST_USER4.clone(),
2389        ];
2390        let users5 = vec![
2391            TEST_USER1.clone(),
2392            TEST_USER2.clone(),
2393            TEST_USER3.clone(),
2394            TEST_USER4.clone(),
2395            TEST_USER5.clone(),
2396        ];
2397
2398        // Nothing set.
2399        assert_eq!(info.users_typing, None);
2400        assert_eq!(info.get_typing_spans(&settings), Line::from(vec![]));
2401
2402        // Empty typing list.
2403        info.set_typing(users0);
2404        assert!(info.users_typing.is_some());
2405        assert_eq!(info.get_typing_spans(&settings), Line::from(vec![]));
2406
2407        // Single user typing.
2408        info.set_typing(users1);
2409        assert!(info.users_typing.is_some());
2410        assert_eq!(
2411            info.get_typing_spans(&settings),
2412            Line::from(vec![
2413                Span::styled("@user1:example.com", user_style("@user1:example.com")),
2414                Span::from(" is typing...")
2415            ])
2416        );
2417
2418        // Two users typing.
2419        info.set_typing(users2);
2420        assert!(info.users_typing.is_some());
2421        assert_eq!(
2422            info.get_typing_spans(&settings),
2423            Line::from(vec![
2424                Span::styled("@user1:example.com", user_style("@user1:example.com")),
2425                Span::raw(" and "),
2426                Span::styled("@user2:example.com", user_style("@user2:example.com")),
2427                Span::raw(" are typing...")
2428            ])
2429        );
2430
2431        // Four users typing.
2432        info.set_typing(users4);
2433        assert!(info.users_typing.is_some());
2434        assert_eq!(info.get_typing_spans(&settings), Line::from("Several people are typing..."));
2435
2436        // Five users typing.
2437        info.set_typing(users5);
2438        assert!(info.users_typing.is_some());
2439        assert_eq!(info.get_typing_spans(&settings), Line::from("Many people are typing..."));
2440
2441        // Test that USER5 gets rendered using the configured color and name.
2442        info.set_typing(vec![TEST_USER5.clone()]);
2443        assert!(info.users_typing.is_some());
2444        assert_eq!(
2445            info.get_typing_spans(&settings),
2446            Line::from(vec![
2447                Span::styled("USER 5", user_style_from_color(Color::Black)),
2448                Span::from(" is typing...")
2449            ])
2450        );
2451    }
2452
2453    #[test]
2454    fn test_need_load() {
2455        let room_id = TEST_ROOM1_ID.clone();
2456
2457        let mut need_load = RoomNeeds::default();
2458
2459        need_load.need_messages(room_id.clone());
2460        need_load.need_members(room_id.clone());
2461
2462        assert_eq!(need_load.into_iter().collect::<Vec<(OwnedRoomId, Need)>>(), vec![(
2463            room_id,
2464            Need { members: true, messages: Some(Vec::new()) }
2465        )],);
2466    }
2467
2468    #[tokio::test]
2469    async fn test_complete_msgbar() {
2470        let store = mock_store().await;
2471        let store = store.application;
2472
2473        let text = EditRope::from("going for a walk :walk ");
2474        let mut cursor = Cursor::new(0, 22);
2475        let res = complete_msgbar(&text, &mut cursor, &store);
2476        assert_eq!(res, vec![":walking:", ":walking_man:", ":walking_woman:"]);
2477        assert_eq!(cursor, Cursor::new(0, 17));
2478
2479        let text = EditRope::from("hello @user1 ");
2480        let mut cursor = Cursor::new(0, 12);
2481        let res = complete_msgbar(&text, &mut cursor, &store);
2482        assert_eq!(res, vec!["@user1:example.com"]);
2483        assert_eq!(cursor, Cursor::new(0, 6));
2484
2485        let text = EditRope::from("see #room ");
2486        let mut cursor = Cursor::new(0, 9);
2487        let res = complete_msgbar(&text, &mut cursor, &store);
2488        assert_eq!(res, vec!["#room1:example.com"]);
2489        assert_eq!(cursor, Cursor::new(0, 4));
2490    }
2491
2492    #[tokio::test]
2493    async fn test_complete_cmdbar() {
2494        let store = mock_store().await;
2495        let store = store.application;
2496        let users = vec![
2497            "@user1:example.com",
2498            "@user2:example.com",
2499            "@user3:example.com",
2500            "@user4:example.com",
2501            "@user5:example.com",
2502        ];
2503
2504        let text = EditRope::from("invite    ");
2505        let mut cursor = Cursor::new(0, 7);
2506        let id = text
2507            .get_prefix_word_mut(&mut cursor, &MATRIX_ID_WORD)
2508            .unwrap_or_else(EditRope::empty);
2509        assert_eq!(id.to_string(), "");
2510        assert_eq!(cursor, Cursor::new(0, 7));
2511
2512        let text = EditRope::from("invite    ");
2513        let mut cursor = Cursor::new(0, 7);
2514        let res = complete_cmdbar(&text, &mut cursor, &store);
2515        assert_eq!(res, users);
2516
2517        let text = EditRope::from("invite ignored");
2518        let mut cursor = Cursor::new(0, 7);
2519        let res = complete_cmdbar(&text, &mut cursor, &store);
2520        assert_eq!(res, users);
2521
2522        let text = EditRope::from("invite @user1ignored");
2523        let mut cursor = Cursor::new(0, 13);
2524        let res = complete_cmdbar(&text, &mut cursor, &store);
2525        assert_eq!(res, vec!["@user1:example.com"]);
2526
2527        let text = EditRope::from("abo hor");
2528        let mut cursor = Cursor::new(0, 7);
2529        let res = complete_cmdbar(&text, &mut cursor, &store);
2530        assert_eq!(res, vec!["horizontal"]);
2531
2532        let text = EditRope::from("abo hor inv");
2533        let mut cursor = Cursor::new(0, 11);
2534        let res = complete_cmdbar(&text, &mut cursor, &store);
2535        assert_eq!(res, vec!["invite"]);
2536
2537        let text = EditRope::from("abo hor invite \n");
2538        let mut cursor = Cursor::new(0, 15);
2539        let res = complete_cmdbar(&text, &mut cursor, &store);
2540        assert_eq!(res, users);
2541    }
2542
2543    #[test]
2544    fn test_ambiguous_displaynames() {
2545        let mut store = DisplayNameStore::default();
2546
2547        store.set(TEST_USER1.clone(), Some("John".into()));
2548        store.set(TEST_USER2.clone(), Some("John".into()));
2549        store.set(TEST_USER3.clone(), Some("Jane".into()));
2550        store.set(TEST_USER4.clone(), Some("Alice".into()));
2551        store.set(TEST_USER5.clone(), Some("Bob".into()));
2552
2553        // TEST_USER1 and TEST_USER2 are both ambiguous, while the other are unambiguous:
2554        assert_eq!(store.get(&TEST_USER1).unwrap().as_ref(), "John (@user1:example.com)");
2555        assert_eq!(store.get(&TEST_USER2).unwrap().as_ref(), "John (@user2:example.com)");
2556        assert_eq!(store.get(&TEST_USER3).unwrap().as_ref(), "Jane");
2557        assert_eq!(store.get(&TEST_USER4).unwrap().as_ref(), "Alice");
2558        assert_eq!(store.get(&TEST_USER5).unwrap().as_ref(), "Bob");
2559
2560        // TEST_USER1 becomes unambiguous when TEST_USER2 changes:
2561        store.set(TEST_USER2.clone(), Some("Eve".into()));
2562        assert_eq!(store.get(&TEST_USER1).unwrap().as_ref(), "John");
2563        assert_eq!(store.get(&TEST_USER2).unwrap().as_ref(), "Eve");
2564        assert_eq!(store.get(&TEST_USER3).unwrap().as_ref(), "Jane");
2565        assert_eq!(store.get(&TEST_USER4).unwrap().as_ref(), "Alice");
2566        assert_eq!(store.get(&TEST_USER5).unwrap().as_ref(), "Bob");
2567
2568        // TEST_USER5 becomes ambiguous when TEST_USER2 once again changes their name to match:
2569        store.set(TEST_USER2.clone(), Some("Bob".into()));
2570        assert_eq!(store.get(&TEST_USER1).unwrap().as_ref(), "John");
2571        assert_eq!(store.get(&TEST_USER2).unwrap().as_ref(), "Bob (@user2:example.com)");
2572        assert_eq!(store.get(&TEST_USER3).unwrap().as_ref(), "Jane");
2573        assert_eq!(store.get(&TEST_USER4).unwrap().as_ref(), "Alice");
2574        assert_eq!(store.get(&TEST_USER5).unwrap().as_ref(), "Bob (@user5:example.com)");
2575
2576        // Now "Everyone is John":
2577        store.set(TEST_USER2.clone(), Some("John".into()));
2578        store.set(TEST_USER3.clone(), Some("John".into()));
2579        store.set(TEST_USER4.clone(), Some("John".into()));
2580        store.set(TEST_USER5.clone(), Some("John".into()));
2581        assert_eq!(store.get(&TEST_USER1).unwrap().as_ref(), "John (@user1:example.com)");
2582        assert_eq!(store.get(&TEST_USER2).unwrap().as_ref(), "John (@user2:example.com)");
2583        assert_eq!(store.get(&TEST_USER3).unwrap().as_ref(), "John (@user3:example.com)");
2584        assert_eq!(store.get(&TEST_USER4).unwrap().as_ref(), "John (@user4:example.com)");
2585        assert_eq!(store.get(&TEST_USER5).unwrap().as_ref(), "John (@user5:example.com)");
2586
2587        // 2-5 unset their displayname:
2588        store.set(TEST_USER2.clone(), None);
2589        store.set(TEST_USER3.clone(), None);
2590        store.set(TEST_USER4.clone(), None);
2591        store.set(TEST_USER5.clone(), None);
2592        assert_eq!(store.get(&TEST_USER1).unwrap().as_ref(), "John");
2593        assert_eq!(store.get(&TEST_USER2), None);
2594        assert_eq!(store.get(&TEST_USER3), None);
2595        assert_eq!(store.get(&TEST_USER4), None);
2596        assert_eq!(store.get(&TEST_USER5), None);
2597    }
2598}