src/base.rs

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