src/base.rs

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