src/base.rs

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