src/base.rs

1507 lines · 46014 bytes

   1//! # Common types and utilities
   2//!
   3//! The types defined here get used throughout iamb.
   4use std::borrow::Cow;
   5use std::collections::{HashMap, HashSet};
   6use std::convert::TryFrom;
   7use std::fmt::{self, Display};
   8use std::hash::Hash;
   9use std::str::FromStr;
  10use std::sync::Arc;
  11use std::time::{Duration, Instant};
  12
  13use emojis::Emoji;
  14use serde::{
  15    de::Error as SerdeError,
  16    de::Visitor,
  17    Deserialize,
  18    Deserializer,
  19    Serialize,
  20    Serializer,
  21};
  22use tokio::sync::Mutex as AsyncMutex;
  23use url::Url;
  24
  25use matrix_sdk::{
  26    encryption::verification::SasVerification,
  27    room::{Joined, Room as MatrixRoom},
  28    ruma::{
  29        events::{
  30            reaction::ReactionEvent,
  31            room::encrypted::RoomEncryptedEvent,
  32            room::message::{
  33                OriginalRoomMessageEvent,
  34                Relation,
  35                Replacement,
  36                RoomMessageEvent,
  37                RoomMessageEventContent,
  38            },
  39            tag::{TagName, Tags},
  40            MessageLikeEvent,
  41        },
  42        presence::PresenceState,
  43        EventId,
  44        OwnedEventId,
  45        OwnedRoomId,
  46        OwnedUserId,
  47        RoomId,
  48    },
  49};
  50
  51use modalkit::{
  52    editing::{
  53        action::{Action, UIError, UIResult},
  54        application::{
  55            ApplicationAction,
  56            ApplicationContentId,
  57            ApplicationError,
  58            ApplicationInfo,
  59            ApplicationStore,
  60            ApplicationWindowId,
  61        },
  62        base::{CommandType, WordStyle},
  63        completion::{complete_path, CompletionMap},
  64        context::EditContext,
  65        cursor::Cursor,
  66        rope::EditRope,
  67        store::Store,
  68    },
  69    env::vim::{
  70        command::{CommandContext, CommandDescription, VimCommand, VimCommandMachine},
  71        keybindings::VimMachine,
  72        VimContext,
  73    },
  74    input::bindings::SequenceStatus,
  75    input::key::TerminalKey,
  76    tui::{
  77        buffer::Buffer,
  78        layout::{Alignment, Rect},
  79        text::{Line, Span},
  80        widgets::{Paragraph, Widget},
  81    },
  82};
  83
  84use crate::{
  85    message::{Message, MessageEvent, MessageKey, MessageTimeStamp, Messages},
  86    worker::Requester,
  87    ApplicationSettings,
  88};
  89
  90/// The set of characters used in different Matrix IDs.
  91pub const MATRIX_ID_WORD: WordStyle = WordStyle::CharSet(is_mxid_char);
  92
  93/// Find the boundaries for a Matrix username, room alias, or room ID.
  94///
  95/// Technically "[" and "]" should be here since IPv6 addresses are allowed
  96/// in the server name, but in practice that should be uncommon, and people
  97/// can just use `gf` and friends in Visual mode instead.
  98fn is_mxid_char(c: char) -> bool {
  99    return c >= 'a' && c <= 'z' ||
 100        c >= 'A' && c <= 'Z' ||
 101        c >= '0' && c <= '9' ||
 102        ":-./@_#!".contains(c);
 103}
 104
 105const ROOM_FETCH_DEBOUNCE: Duration = Duration::from_secs(2);
 106
 107/// Empty type used solely to implement [ApplicationInfo].
 108#[derive(Clone, Debug, Eq, PartialEq)]
 109pub enum IambInfo {}
 110
 111/// An action taken against an ongoing verification request.
 112#[derive(Clone, Debug, Eq, PartialEq)]
 113pub enum VerifyAction {
 114    /// Accept a verification request.
 115    Accept,
 116
 117    /// Cancel an in-progress verification.
 118    Cancel,
 119
 120    /// Confirm an in-progress verification.
 121    Confirm,
 122
 123    /// Reject an in-progress verification due to mismatched Emoji.
 124    Mismatch,
 125}
 126
 127/// An action taken against the currently selected message.
 128#[derive(Clone, Debug, Eq, PartialEq)]
 129pub enum MessageAction {
 130    /// Cance the current reply or edit.
 131    ///
 132    /// The [bool] argument indicates whether to skip confirmation for clearing the message bar.
 133    Cancel(bool),
 134
 135    /// Download an attachment to the given path.
 136    ///
 137    /// The second argument controls whether to overwrite any already existing file at the
 138    /// destination path, or to open the attachment after downloading.
 139    Download(Option<String>, DownloadFlags),
 140
 141    /// Edit a sent message.
 142    Edit,
 143
 144    /// React to a message with an Emoji.
 145    React(String),
 146
 147    /// Redact a message, with an optional reason.
 148    ///
 149    /// The [bool] argument indicates whether to skip confirmation.
 150    Redact(Option<String>, bool),
 151
 152    /// Reply to a message.
 153    Reply,
 154
 155    /// Unreact to a message.
 156    ///
 157    /// If no specific Emoji to remove to is specified, then all reactions from the user on the
 158    /// message are removed.
 159    Unreact(Option<String>),
 160}
 161
 162/// The type of room being created.
 163#[derive(Clone, Debug, Eq, PartialEq)]
 164pub enum CreateRoomType {
 165    /// A direct message room.
 166    Direct(OwnedUserId),
 167
 168    /// A standard chat room.
 169    Room,
 170
 171    /// A Matrix space.
 172    Space,
 173}
 174
 175bitflags::bitflags! {
 176    /// Available options for newly created rooms.
 177    #[derive(Clone, Debug, Eq, PartialEq)]
 178    pub struct CreateRoomFlags: u32 {
 179        /// No flags specified.
 180        const NONE = 0b00000000;
 181
 182        /// Make the room public.
 183        const PUBLIC = 0b00000001;
 184
 185        /// Encrypt this room.
 186        const ENCRYPTED = 0b00000010;
 187    }
 188}
 189
 190bitflags::bitflags! {
 191    /// Available options when downloading files.
 192    #[derive(Clone, Debug, Eq, PartialEq)]
 193    pub struct DownloadFlags: u32 {
 194        /// No flags specified.
 195        const NONE = 0b00000000;
 196
 197        /// Overwrite file if it already exists.
 198        const FORCE = 0b00000001;
 199
 200        /// Open file after downloading.
 201        const OPEN = 0b00000010;
 202    }
 203}
 204
 205/// A room property.
 206#[derive(Clone, Debug, Eq, PartialEq)]
 207pub enum RoomField {
 208    /// The room name.
 209    Name,
 210
 211    /// A room tag.
 212    Tag(TagName),
 213
 214    /// The room topic.
 215    Topic,
 216}
 217
 218/// An action that operates on a focused room.
 219#[derive(Clone, Debug, Eq, PartialEq)]
 220pub enum RoomAction {
 221    /// Accept an invitation to join this room.
 222    InviteAccept,
 223
 224    /// Reject an invitation to join this room.
 225    InviteReject,
 226
 227    /// Invite a user to this room.
 228    InviteSend(OwnedUserId),
 229
 230    /// Leave this room.
 231    Leave(bool),
 232
 233    /// Open the members window.
 234    Members(Box<CommandContext<ProgramContext>>),
 235
 236    /// Set a room property.
 237    Set(RoomField, String),
 238
 239    /// Unset a room property.
 240    Unset(RoomField),
 241}
 242
 243/// An action that sends a message to a room.
 244#[derive(Clone, Debug, Eq, PartialEq)]
 245pub enum SendAction {
 246    /// Send the text in the message bar.
 247    Submit,
 248
 249    /// Send text provided from an external editor.
 250    SubmitFromEditor,
 251
 252    /// Upload a file.
 253    Upload(String),
 254
 255    /// Upload the image data.
 256    UploadImage(usize, usize, Cow<'static, [u8]>),
 257}
 258
 259/// An action performed against the user's homeserver.
 260#[derive(Clone, Debug, Eq, PartialEq)]
 261pub enum HomeserverAction {
 262    /// Create a new room with an optional localpart.
 263    CreateRoom(Option<String>, CreateRoomType, CreateRoomFlags),
 264    Logout(String, bool),
 265}
 266
 267/// An action that the main program loop should.
 268///
 269/// See [the commands module][super::commands] for where these are usually created.
 270#[derive(Clone, Debug, Eq, PartialEq)]
 271pub enum IambAction {
 272    /// Perform an action against the homeserver.
 273    Homeserver(HomeserverAction),
 274
 275    /// Perform an action on the currently selected message.
 276    Message(MessageAction),
 277
 278    /// Open a URL.
 279    OpenLink(String),
 280
 281    /// Perform an action on the currently focused room.
 282    Room(RoomAction),
 283
 284    /// Send a message to the currently focused room.
 285    Send(SendAction),
 286
 287    /// Perform an action for an in-progress verification.
 288    Verify(VerifyAction, String),
 289
 290    /// Request a new verification with the specified user.
 291    VerifyRequest(String),
 292
 293    /// Toggle the focus within the focused room.
 294    ToggleScrollbackFocus,
 295}
 296
 297impl IambAction {
 298    /// Indicates whether this action will draw over the screen.
 299    pub fn scribbles(&self) -> bool {
 300        matches!(self, IambAction::Send(SendAction::SubmitFromEditor))
 301    }
 302}
 303
 304impl From<HomeserverAction> for IambAction {
 305    fn from(act: HomeserverAction) -> Self {
 306        IambAction::Homeserver(act)
 307    }
 308}
 309
 310impl From<MessageAction> for IambAction {
 311    fn from(act: MessageAction) -> Self {
 312        IambAction::Message(act)
 313    }
 314}
 315
 316impl From<RoomAction> for IambAction {
 317    fn from(act: RoomAction) -> Self {
 318        IambAction::Room(act)
 319    }
 320}
 321
 322impl From<SendAction> for IambAction {
 323    fn from(act: SendAction) -> Self {
 324        IambAction::Send(act)
 325    }
 326}
 327
 328impl ApplicationAction for IambAction {
 329    fn is_edit_sequence<C: EditContext>(&self, _: &C) -> SequenceStatus {
 330        match self {
 331            IambAction::Homeserver(..) => SequenceStatus::Break,
 332            IambAction::Message(..) => SequenceStatus::Break,
 333            IambAction::Room(..) => SequenceStatus::Break,
 334            IambAction::OpenLink(..) => SequenceStatus::Break,
 335            IambAction::Send(..) => SequenceStatus::Break,
 336            IambAction::ToggleScrollbackFocus => SequenceStatus::Break,
 337            IambAction::Verify(..) => SequenceStatus::Break,
 338            IambAction::VerifyRequest(..) => SequenceStatus::Break,
 339        }
 340    }
 341
 342    fn is_last_action<C: EditContext>(&self, _: &C) -> SequenceStatus {
 343        match self {
 344            IambAction::Homeserver(..) => SequenceStatus::Atom,
 345            IambAction::Message(..) => SequenceStatus::Atom,
 346            IambAction::OpenLink(..) => SequenceStatus::Atom,
 347            IambAction::Room(..) => SequenceStatus::Atom,
 348            IambAction::Send(..) => SequenceStatus::Atom,
 349            IambAction::ToggleScrollbackFocus => SequenceStatus::Atom,
 350            IambAction::Verify(..) => SequenceStatus::Atom,
 351            IambAction::VerifyRequest(..) => SequenceStatus::Atom,
 352        }
 353    }
 354
 355    fn is_last_selection<C: EditContext>(&self, _: &C) -> SequenceStatus {
 356        match self {
 357            IambAction::Homeserver(..) => SequenceStatus::Ignore,
 358            IambAction::Message(..) => SequenceStatus::Ignore,
 359            IambAction::Room(..) => SequenceStatus::Ignore,
 360            IambAction::OpenLink(..) => SequenceStatus::Ignore,
 361            IambAction::Send(..) => SequenceStatus::Ignore,
 362            IambAction::ToggleScrollbackFocus => SequenceStatus::Ignore,
 363            IambAction::Verify(..) => SequenceStatus::Ignore,
 364            IambAction::VerifyRequest(..) => SequenceStatus::Ignore,
 365        }
 366    }
 367
 368    fn is_switchable<C: EditContext>(&self, _: &C) -> bool {
 369        match self {
 370            IambAction::Homeserver(..) => false,
 371            IambAction::Message(..) => false,
 372            IambAction::Room(..) => false,
 373            IambAction::Send(..) => false,
 374            IambAction::OpenLink(..) => false,
 375            IambAction::ToggleScrollbackFocus => false,
 376            IambAction::Verify(..) => false,
 377            IambAction::VerifyRequest(..) => false,
 378        }
 379    }
 380}
 381
 382impl From<RoomAction> for ProgramAction {
 383    fn from(act: RoomAction) -> Self {
 384        IambAction::from(act).into()
 385    }
 386}
 387
 388impl From<IambAction> for ProgramAction {
 389    fn from(act: IambAction) -> Self {
 390        Action::Application(act)
 391    }
 392}
 393
 394/// Alias for program actions.
 395pub type ProgramAction = Action<IambInfo>;
 396/// Alias for program context.
 397pub type ProgramContext = VimContext<IambInfo>;
 398/// Alias for program keybindings.
 399pub type Keybindings = VimMachine<TerminalKey, IambInfo>;
 400/// Alias for a program command.
 401pub type ProgramCommand = VimCommand<ProgramContext, IambInfo>;
 402/// Alias for mapped program commands.
 403pub type ProgramCommands = VimCommandMachine<ProgramContext, IambInfo>;
 404/// Alias for program store.
 405pub type ProgramStore = Store<IambInfo>;
 406/// Alias for shared program store.
 407pub type AsyncProgramStore = Arc<AsyncMutex<ProgramStore>>;
 408/// Alias for an action result.
 409pub type IambResult<T> = UIResult<T, IambInfo>;
 410
 411/// Reaction events for some message.
 412///
 413/// The event identifier used as a key here is the ID for the reaction, and not for the message
 414/// it's reacting to.
 415pub type MessageReactions = HashMap<OwnedEventId, (String, OwnedUserId)>;
 416
 417/// Errors encountered during application use.
 418#[derive(thiserror::Error, Debug)]
 419pub enum IambError {
 420    /// An invalid user identifier was specified.
 421    #[error("Invalid user identifier: {0}")]
 422    InvalidUserId(String),
 423
 424    /// An invalid verification identifier was specified.
 425    #[error("Invalid verification user/device pair: {0}")]
 426    InvalidVerificationId(String),
 427
 428    /// A failure related to the cryptographic store.
 429    #[error("Cryptographic storage error: {0}")]
 430    CryptoStore(#[from] matrix_sdk::encryption::CryptoStoreError),
 431
 432    /// An HTTP error.
 433    #[error("HTTP client error: {0}")]
 434    Http(#[from] matrix_sdk::HttpError),
 435
 436    /// A failure from the Matrix client.
 437    #[error("Matrix client error: {0}")]
 438    Matrix(#[from] matrix_sdk::Error),
 439
 440    /// A failure in the sled storage.
 441    #[error("Matrix client storage error: {0}")]
 442    Store(#[from] matrix_sdk::StoreError),
 443
 444    /// A failure during serialization or deserialization.
 445    #[error("Serialization/deserialization error: {0}")]
 446    Serde(#[from] serde_json::Error),
 447
 448    /// A failure due to not having a configured download directory.
 449    #[error("No download directory configured")]
 450    NoDownloadDir,
 451
 452    /// A failure due to not having a message with an attachment selected.
 453    #[error("Selected message does not have any attachments")]
 454    NoAttachment,
 455
 456    /// A failure due to not having a message selected.
 457    #[error("No message currently selected")]
 458    NoSelectedMessage,
 459
 460    /// A failure due to not having a room or space selected.
 461    #[error("Current window is not a room or space")]
 462    NoSelectedRoomOrSpace,
 463
 464    /// A failure due to not having a room selected.
 465    #[error("Current window is not a room")]
 466    NoSelectedRoom,
 467
 468    /// A failure due to not having an outstanding room invitation.
 469    #[error("You do not have a current invitation to this room")]
 470    NotInvited,
 471
 472    /// A failure due to not being a joined room member.
 473    #[error("You need to join the room before you can do that")]
 474    NotJoined,
 475
 476    /// An unknown room was specified.
 477    #[error("Unknown room identifier: {0}")]
 478    UnknownRoom(OwnedRoomId),
 479
 480    /// A failure occurred during verification.
 481    #[error("Verification request error: {0}")]
 482    VerificationRequestError(#[from] matrix_sdk::encryption::identities::RequestVerificationError),
 483
 484    /// A failure related to images.
 485    #[error("Image error: {0}")]
 486    Image(#[from] image::ImageError),
 487
 488    /// A failure to access the system's clipboard.
 489    #[error("Could not use system clipboard data")]
 490    Clipboard,
 491}
 492
 493impl From<IambError> for UIError<IambInfo> {
 494    fn from(err: IambError) -> Self {
 495        UIError::Application(err)
 496    }
 497}
 498
 499impl ApplicationError for IambError {}
 500
 501/// Status for tracking how much room scrollback we've fetched.
 502#[derive(Default)]
 503pub enum RoomFetchStatus {
 504    /// Room history has been completely fetched.
 505    Done,
 506
 507    /// More room history can be fetched.
 508    HaveMore(String),
 509
 510    /// We have not yet started fetching history for this room.
 511    #[default]
 512    NotStarted,
 513}
 514
 515/// Indicates where an [EventId] lives in the [ChatStore].
 516pub enum EventLocation {
 517    /// The [EventId] belongs to a message.
 518    Message(MessageKey),
 519
 520    /// The [EventId] belongs to a reaction to the given event.
 521    Reaction(OwnedEventId),
 522}
 523
 524impl EventLocation {
 525    fn to_message_key(&self) -> Option<&MessageKey> {
 526        if let EventLocation::Message(key) = self {
 527            Some(key)
 528        } else {
 529            None
 530        }
 531    }
 532}
 533
 534/// Information about room's the user's joined.
 535#[derive(Default)]
 536pub struct RoomInfo {
 537    /// The display name for this room.
 538    pub name: Option<String>,
 539
 540    /// The tags placed on this room.
 541    pub tags: Option<Tags>,
 542
 543    /// A map of event IDs to where they are stored in this struct.
 544    pub keys: HashMap<OwnedEventId, EventLocation>,
 545
 546    /// The messages loaded for this room.
 547    pub messages: Messages,
 548
 549    /// A map of read markers to display on different events.
 550    pub event_receipts: HashMap<OwnedEventId, HashSet<OwnedUserId>>,
 551
 552    /// A map of the most recent read marker for each user.
 553    ///
 554    /// Every receipt in this map should also have an entry in [`event_receipts`],
 555    /// however not every user has an entry. If a user's most recent receipt is
 556    /// older than the oldest loaded event, that user will not be included.
 557    pub user_receipts: HashMap<OwnedUserId, OwnedEventId>,
 558
 559    /// An event ID for where we should indicate we've read up to.
 560    pub read_till: Option<OwnedEventId>,
 561
 562    /// A map of message identifiers to a map of reaction events.
 563    pub reactions: HashMap<OwnedEventId, MessageReactions>,
 564
 565    /// Whether the scrollback for this room is currently being fetched.
 566    pub fetching: bool,
 567
 568    /// Where to continue fetching from when we continue loading scrollback history.
 569    pub fetch_id: RoomFetchStatus,
 570
 571    /// The time that we last fetched scrollback for this room.
 572    pub fetch_last: Option<Instant>,
 573
 574    /// Users currently typing in this room, and when we received notification of them doing so.
 575    pub users_typing: Option<(Instant, Vec<OwnedUserId>)>,
 576
 577    /// The display names for users in this room.
 578    pub display_names: HashMap<OwnedUserId, String>,
 579}
 580
 581impl RoomInfo {
 582    /// Get the reactions and their counts for a message.
 583    pub fn get_reactions(&self, event_id: &EventId) -> Vec<(&str, usize)> {
 584        if let Some(reacts) = self.reactions.get(event_id) {
 585            let mut counts = HashMap::new();
 586
 587            for (key, _) in reacts.values() {
 588                let count = counts.entry(key.as_str()).or_default();
 589                *count += 1;
 590            }
 591
 592            let mut reactions = counts.into_iter().collect::<Vec<_>>();
 593            reactions.sort();
 594
 595            reactions
 596        } else {
 597            vec![]
 598        }
 599    }
 600
 601    /// Map an event identifier to its [MessageKey].
 602    pub fn get_message_key(&self, event_id: &EventId) -> Option<&MessageKey> {
 603        self.keys.get(event_id)?.to_message_key()
 604    }
 605
 606    /// Get an event for an identifier.
 607    pub fn get_event(&self, event_id: &EventId) -> Option<&Message> {
 608        self.messages.get(self.get_message_key(event_id)?)
 609    }
 610
 611    /// Insert a reaction to a message.
 612    pub fn insert_reaction(&mut self, react: ReactionEvent) {
 613        match react {
 614            MessageLikeEvent::Original(react) => {
 615                let rel_id = react.content.relates_to.event_id;
 616                let key = react.content.relates_to.key;
 617
 618                let message = self.reactions.entry(rel_id.clone()).or_default();
 619                let event_id = react.event_id;
 620                let user_id = react.sender;
 621
 622                message.insert(event_id.clone(), (key, user_id));
 623
 624                let loc = EventLocation::Reaction(rel_id);
 625                self.keys.insert(event_id, loc);
 626            },
 627            MessageLikeEvent::Redacted(_) => {
 628                return;
 629            },
 630        }
 631    }
 632
 633    /// Insert an edit.
 634    pub fn insert_edit(&mut self, msg: Replacement) {
 635        let event_id = msg.event_id;
 636        let new_content = msg.new_content;
 637
 638        let key = if let Some(EventLocation::Message(k)) = self.keys.get(&event_id) {
 639            k
 640        } else {
 641            return;
 642        };
 643
 644        let msg = if let Some(msg) = self.messages.get_mut(key) {
 645            msg
 646        } else {
 647            return;
 648        };
 649
 650        match &mut msg.event {
 651            MessageEvent::Original(orig) => {
 652                orig.content.msgtype = new_content.msgtype;
 653            },
 654            MessageEvent::Local(_, content) => {
 655                content.msgtype = new_content.msgtype;
 656            },
 657            MessageEvent::Redacted(_) |
 658            MessageEvent::EncryptedOriginal(_) |
 659            MessageEvent::EncryptedRedacted(_) => {
 660                return;
 661            },
 662        }
 663
 664        msg.html = msg.event.html();
 665    }
 666
 667    /// Inserts events that couldn't be decrypted into the scrollback.
 668    pub fn insert_encrypted(&mut self, msg: RoomEncryptedEvent) {
 669        let event_id = msg.event_id().to_owned();
 670        let key = (msg.origin_server_ts().into(), event_id.clone());
 671
 672        self.keys.insert(event_id, EventLocation::Message(key.clone()));
 673        self.messages.insert(key, msg.into());
 674    }
 675
 676    /// Insert a new message.
 677    pub fn insert_message(&mut self, msg: RoomMessageEvent) {
 678        let event_id = msg.event_id().to_owned();
 679        let key = (msg.origin_server_ts().into(), event_id.clone());
 680
 681        self.keys.insert(event_id.clone(), EventLocation::Message(key.clone()));
 682        self.messages.insert(key, msg.into());
 683
 684        // Remove any echo.
 685        let key = (MessageTimeStamp::LocalEcho, event_id);
 686        let _ = self.messages.remove(&key);
 687    }
 688
 689    /// Insert a new message event.
 690    pub fn insert(&mut self, msg: RoomMessageEvent) {
 691        match msg {
 692            RoomMessageEvent::Original(OriginalRoomMessageEvent {
 693                content:
 694                    RoomMessageEventContent { relates_to: Some(Relation::Replacement(repl)), .. },
 695                ..
 696            }) => self.insert_edit(repl),
 697            _ => self.insert_message(msg),
 698        }
 699    }
 700
 701    /// Indicates whether we've recently fetched scrollback for this room.
 702    pub fn recently_fetched(&self) -> bool {
 703        self.fetch_last.map_or(false, |i| i.elapsed() < ROOM_FETCH_DEBOUNCE)
 704    }
 705
 706    fn clear_receipt(&mut self, user_id: &OwnedUserId) -> Option<()> {
 707        let old_event_id = self.user_receipts.get(user_id)?;
 708        let old_receipts = self.event_receipts.get_mut(old_event_id)?;
 709        old_receipts.remove(user_id);
 710
 711        if old_receipts.is_empty() {
 712            self.event_receipts.remove(old_event_id);
 713        }
 714
 715        None
 716    }
 717
 718    pub fn set_receipt(&mut self, user_id: OwnedUserId, event_id: OwnedEventId) {
 719        self.clear_receipt(&user_id);
 720        self.event_receipts
 721            .entry(event_id.clone())
 722            .or_default()
 723            .insert(user_id.clone());
 724        self.user_receipts.insert(user_id, event_id);
 725    }
 726
 727    fn get_typers(&self) -> &[OwnedUserId] {
 728        if let Some((t, users)) = &self.users_typing {
 729            if t.elapsed() < Duration::from_secs(4) {
 730                return users.as_ref();
 731            } else {
 732                return &[];
 733            }
 734        } else {
 735            return &[];
 736        }
 737    }
 738
 739    fn get_typing_spans<'a>(&'a self, settings: &'a ApplicationSettings) -> Line<'a> {
 740        let typers = self.get_typers();
 741        let n = typers.len();
 742
 743        match n {
 744            0 => Line::from(vec![]),
 745            1 => {
 746                let user = settings.get_user_span(typers[0].as_ref(), self);
 747
 748                Line::from(vec![user, Span::from(" is typing...")])
 749            },
 750            2 => {
 751                let user1 = settings.get_user_span(typers[0].as_ref(), self);
 752                let user2 = settings.get_user_span(typers[1].as_ref(), self);
 753
 754                Line::from(vec![
 755                    user1,
 756                    Span::raw(" and "),
 757                    user2,
 758                    Span::from(" are typing..."),
 759                ])
 760            },
 761            n if n < 5 => Line::from("Several people are typing..."),
 762            _ => Line::from("Many people are typing..."),
 763        }
 764    }
 765
 766    /// Update typing information for this room.
 767    pub fn set_typing(&mut self, user_ids: Vec<OwnedUserId>) {
 768        self.users_typing = (Instant::now(), user_ids).into();
 769    }
 770
 771    /// Create a [Rect] that displays what users are typing.
 772    pub fn render_typing(
 773        &mut self,
 774        area: Rect,
 775        buf: &mut Buffer,
 776        settings: &ApplicationSettings,
 777    ) -> Rect {
 778        if area.height <= 2 || area.width <= 20 {
 779            return area;
 780        }
 781
 782        if !settings.tunables.typing_notice_display {
 783            return area;
 784        }
 785
 786        let top = Rect::new(area.x, area.y, area.width, area.height - 1);
 787        let bar = Rect::new(area.x, area.y + top.height, area.width, 1);
 788
 789        Paragraph::new(self.get_typing_spans(settings))
 790            .alignment(Alignment::Center)
 791            .render(bar, buf);
 792
 793        return top;
 794    }
 795}
 796
 797/// Generate a [CompletionMap] for Emoji shortcodes.
 798fn emoji_map() -> CompletionMap<String, &'static Emoji> {
 799    let mut emojis = CompletionMap::default();
 800
 801    for emoji in emojis::iter() {
 802        for shortcode in emoji.shortcodes() {
 803            emojis.insert(shortcode.to_string(), emoji);
 804        }
 805    }
 806
 807    return emojis;
 808}
 809
 810/// Information gathered during server syncs about joined rooms.
 811#[derive(Default)]
 812pub struct SyncInfo {
 813    /// Spaces that the user is a member of.
 814    pub spaces: Vec<MatrixRoom>,
 815
 816    /// Rooms that the user is a member of.
 817    pub rooms: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
 818
 819    /// DMs that the user is a member of.
 820    pub dms: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
 821}
 822
 823/// The main application state.
 824pub struct ChatStore {
 825    /// `:`-commands
 826    pub cmds: ProgramCommands,
 827
 828    /// Handle for communicating w/ the worker thread.
 829    pub worker: Requester,
 830
 831    /// Map of joined rooms.
 832    pub rooms: CompletionMap<OwnedRoomId, RoomInfo>,
 833
 834    /// Map of room names.
 835    pub names: CompletionMap<String, OwnedRoomId>,
 836
 837    /// Presence information for other users.
 838    pub presences: CompletionMap<OwnedUserId, PresenceState>,
 839
 840    /// In-progress and completed verifications.
 841    pub verifications: HashMap<String, SasVerification>,
 842
 843    /// Settings for the current profile loaded from config file.
 844    pub settings: ApplicationSettings,
 845
 846    /// Set of rooms that need more messages loaded in their scrollback.
 847    pub need_load: HashSet<OwnedRoomId>,
 848
 849    /// [CompletionMap] of Emoji shortcodes.
 850    pub emojis: CompletionMap<String, &'static Emoji>,
 851
 852    /// Information gathered by the background thread.
 853    pub sync_info: SyncInfo,
 854}
 855
 856impl ChatStore {
 857    /// Create a new [ChatStore].
 858    pub fn new(worker: Requester, settings: ApplicationSettings) -> Self {
 859        ChatStore {
 860            worker,
 861            settings,
 862
 863            cmds: crate::commands::setup_commands(),
 864            emojis: emoji_map(),
 865
 866            names: Default::default(),
 867            rooms: Default::default(),
 868            presences: Default::default(),
 869            verifications: Default::default(),
 870            need_load: Default::default(),
 871            sync_info: Default::default(),
 872        }
 873    }
 874
 875    /// Get a joined room.
 876    pub fn get_joined_room(&self, room_id: &RoomId) -> Option<Joined> {
 877        self.worker.client.get_joined_room(room_id)
 878    }
 879
 880    /// Get the title for a room.
 881    pub fn get_room_title(&self, room_id: &RoomId) -> String {
 882        self.rooms
 883            .get(room_id)
 884            .and_then(|i| i.name.as_ref())
 885            .map(String::from)
 886            .unwrap_or_else(|| "Untitled Matrix Room".to_string())
 887    }
 888
 889    /// Mark a room for loading more scrollback.
 890    pub fn mark_for_load(&mut self, room_id: OwnedRoomId) {
 891        self.need_load.insert(room_id);
 892    }
 893
 894    /// Get the [RoomInfo] for a given room identifier.
 895    pub fn get_room_info(&mut self, room_id: OwnedRoomId) -> &mut RoomInfo {
 896        self.rooms.get_or_default(room_id)
 897    }
 898
 899    /// Set the name for a room.
 900    pub fn set_room_name(&mut self, room_id: &RoomId, name: &str) {
 901        self.rooms.get_or_default(room_id.to_owned()).name = name.to_string().into();
 902    }
 903
 904    /// Insert a new E2EE verification.
 905    pub fn insert_sas(&mut self, sas: SasVerification) {
 906        let key = format!("{}/{}", sas.other_user_id(), sas.other_device().device_id());
 907
 908        self.verifications.insert(key, sas);
 909    }
 910}
 911
 912impl ApplicationStore for ChatStore {}
 913
 914/// Identified used to track window content.
 915#[derive(Clone, Debug, Eq, Hash, PartialEq)]
 916pub enum IambId {
 917    /// A Matrix room.
 918    Room(OwnedRoomId),
 919
 920    /// The `:rooms` window.
 921    DirectList,
 922
 923    /// The `:members` window for a given Matrix room.
 924    MemberList(OwnedRoomId),
 925
 926    /// The `:rooms` window.
 927    RoomList,
 928
 929    /// The `:spaces` window.
 930    SpaceList,
 931
 932    /// The `:verify` window.
 933    VerifyList,
 934
 935    /// The `:welcome` window.
 936    Welcome,
 937}
 938
 939impl Display for IambId {
 940    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 941        match self {
 942            IambId::Room(room_id) => {
 943                write!(f, "iamb://room/{room_id}")
 944            },
 945            IambId::MemberList(room_id) => {
 946                write!(f, "iamb://members/{room_id}")
 947            },
 948            IambId::DirectList => f.write_str("iamb://dms"),
 949            IambId::RoomList => f.write_str("iamb://rooms"),
 950            IambId::SpaceList => f.write_str("iamb://spaces"),
 951            IambId::VerifyList => f.write_str("iamb://verify"),
 952            IambId::Welcome => f.write_str("iamb://welcome"),
 953        }
 954    }
 955}
 956
 957impl ApplicationWindowId for IambId {}
 958
 959impl Serialize for IambId {
 960    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
 961    where
 962        S: Serializer,
 963    {
 964        serializer.serialize_str(&self.to_string())
 965    }
 966}
 967
 968impl<'de> Deserialize<'de> for IambId {
 969    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
 970    where
 971        D: Deserializer<'de>,
 972    {
 973        deserializer.deserialize_str(IambIdVisitor)
 974    }
 975}
 976
 977/// [serde] visitor for deserializing [IambId].
 978struct IambIdVisitor;
 979
 980impl<'de> Visitor<'de> for IambIdVisitor {
 981    type Value = IambId;
 982
 983    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
 984        formatter.write_str("a valid window URL")
 985    }
 986
 987    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
 988    where
 989        E: SerdeError,
 990    {
 991        let Ok(url) = Url::parse(value) else {
 992            return Err(E::custom("Invalid iamb window URL"));
 993        };
 994
 995        if url.scheme() != "iamb" {
 996            return Err(E::custom("Invalid iamb window URL"));
 997        }
 998
 999        match url.domain() {
1000            Some("room") => {
1001                let Some(path) = url.path_segments() else {
1002                    return Err(E::custom("Invalid members window URL"));
1003                };
1004
1005                let &[room_id] = path.collect::<Vec<_>>().as_slice() else {
1006                    return Err(E::custom("Invalid members window URL"));
1007                };
1008
1009                let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
1010                    return Err(E::custom("Invalid room identifier"));
1011                };
1012
1013                Ok(IambId::Room(room_id))
1014            },
1015            Some("members") => {
1016                let Some(path) = url.path_segments() else {
1017                    return Err(E::custom("Invalid members window URL"));
1018                };
1019
1020                let &[room_id] = path.collect::<Vec<_>>().as_slice() else {
1021                    return Err(E::custom("Invalid members window URL"));
1022                };
1023
1024                let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
1025                    return Err(E::custom("Invalid room identifier"));
1026                };
1027
1028                Ok(IambId::MemberList(room_id))
1029            },
1030            Some("dms") => {
1031                if url.path() != "" {
1032                    return Err(E::custom("iamb://dms takes no path"));
1033                }
1034
1035                Ok(IambId::DirectList)
1036            },
1037            Some("rooms") => {
1038                if url.path() != "" {
1039                    return Err(E::custom("iamb://rooms takes no path"));
1040                }
1041
1042                Ok(IambId::RoomList)
1043            },
1044            Some("spaces") => {
1045                if url.path() != "" {
1046                    return Err(E::custom("iamb://spaces takes no path"));
1047                }
1048
1049                Ok(IambId::SpaceList)
1050            },
1051            Some("verify") => {
1052                if url.path() != "" {
1053                    return Err(E::custom("iamb://verify takes no path"));
1054                }
1055
1056                Ok(IambId::VerifyList)
1057            },
1058            Some("welcome") => {
1059                if url.path() != "" {
1060                    return Err(E::custom("iamb://welcome takes no path"));
1061                }
1062
1063                Ok(IambId::Welcome)
1064            },
1065            Some(s) => Err(E::custom(format!("{s:?} is not a valid window"))),
1066            None => Err(E::custom("Invalid iamb window URL")),
1067        }
1068    }
1069}
1070
1071/// Which part of the room window's UI is focused.
1072#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1073pub enum RoomFocus {
1074    /// The scrollback for a room window is focused.
1075    Scrollback,
1076
1077    /// The message bar for a room window is focused.
1078    MessageBar,
1079}
1080
1081impl RoomFocus {
1082    /// Whether this is [RoomFocus::Scrollback].
1083    pub fn is_scrollback(&self) -> bool {
1084        matches!(self, RoomFocus::Scrollback)
1085    }
1086
1087    /// Whether this is [RoomFocus::MessageBar].
1088    pub fn is_msgbar(&self) -> bool {
1089        matches!(self, RoomFocus::MessageBar)
1090    }
1091}
1092
1093/// Identifiers used to track where a mark was placed.
1094///
1095/// While this is the "buffer identifier" for the mark,
1096/// not all of these are necessarily actual buffers.
1097#[derive(Clone, Debug, Eq, Hash, PartialEq)]
1098pub enum IambBufferId {
1099    /// The command bar buffer.
1100    Command(CommandType),
1101
1102    /// The message buffer or a specific message in a room.
1103    Room(OwnedRoomId, RoomFocus),
1104
1105    /// The `:dms` window.
1106    DirectList,
1107
1108    /// The `:members` window for a room.
1109    MemberList(OwnedRoomId),
1110
1111    /// The `:rooms` window.
1112    RoomList,
1113
1114    /// The `:spaces` window.
1115    SpaceList,
1116
1117    /// The `:verify` window.
1118    VerifyList,
1119
1120    /// The buffer for the `:rooms` window.
1121    Welcome,
1122}
1123
1124impl IambBufferId {
1125    /// Get the identifier for the window that contains this buffer.
1126    pub fn to_window(&self) -> Option<IambId> {
1127        match self {
1128            IambBufferId::Command(_) => None,
1129            IambBufferId::Room(room, _) => Some(IambId::Room(room.clone())),
1130            IambBufferId::DirectList => Some(IambId::DirectList),
1131            IambBufferId::MemberList(room) => Some(IambId::MemberList(room.clone())),
1132            IambBufferId::RoomList => Some(IambId::RoomList),
1133            IambBufferId::SpaceList => Some(IambId::SpaceList),
1134            IambBufferId::VerifyList => Some(IambId::VerifyList),
1135            IambBufferId::Welcome => Some(IambId::Welcome),
1136        }
1137    }
1138}
1139
1140impl ApplicationContentId for IambBufferId {}
1141
1142impl ApplicationInfo for IambInfo {
1143    type Error = IambError;
1144    type Store = ChatStore;
1145    type Action = IambAction;
1146    type WindowId = IambId;
1147    type ContentId = IambBufferId;
1148
1149    fn complete(
1150        text: &EditRope,
1151        cursor: &mut Cursor,
1152        content: &IambBufferId,
1153        store: &mut ProgramStore,
1154    ) -> Vec<String> {
1155        match content {
1156            IambBufferId::Command(CommandType::Command) => complete_cmdbar(text, cursor, store),
1157            IambBufferId::Command(CommandType::Search) => vec![],
1158
1159            IambBufferId::Room(_, RoomFocus::MessageBar) => complete_msgbar(text, cursor, store),
1160            IambBufferId::Room(_, RoomFocus::Scrollback) => vec![],
1161
1162            IambBufferId::DirectList => vec![],
1163            IambBufferId::MemberList(_) => vec![],
1164            IambBufferId::RoomList => vec![],
1165            IambBufferId::SpaceList => vec![],
1166            IambBufferId::VerifyList => vec![],
1167            IambBufferId::Welcome => vec![],
1168        }
1169    }
1170
1171    fn content_of_command(ct: CommandType) -> IambBufferId {
1172        IambBufferId::Command(ct)
1173    }
1174}
1175
1176/// Tab completion for user IDs.
1177fn complete_users(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
1178    let id = text
1179        .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
1180        .unwrap_or_else(EditRope::empty);
1181    let id = Cow::from(&id);
1182
1183    store
1184        .application
1185        .presences
1186        .complete(id.as_ref())
1187        .into_iter()
1188        .map(|i| i.to_string())
1189        .collect()
1190}
1191
1192/// Tab completion within the message bar.
1193fn complete_msgbar(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
1194    let id = text
1195        .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
1196        .unwrap_or_else(EditRope::empty);
1197    let id = Cow::from(&id);
1198
1199    match id.chars().next() {
1200        // Complete room aliases.
1201        Some('#') => {
1202            return store.application.names.complete(id.as_ref());
1203        },
1204
1205        // Complete room identifiers.
1206        Some('!') => {
1207            return store
1208                .application
1209                .rooms
1210                .complete(id.as_ref())
1211                .into_iter()
1212                .map(|i| i.to_string())
1213                .collect();
1214        },
1215
1216        // Complete Emoji shortcodes.
1217        Some(':') => {
1218            let list = store.application.emojis.complete(&id[1..]);
1219            let iter = list.into_iter().take(200).map(|s| format!(":{}:", s));
1220
1221            return iter.collect();
1222        },
1223
1224        // Complete usernames for @ and empty strings.
1225        Some('@') | None => {
1226            return store
1227                .application
1228                .presences
1229                .complete(id.as_ref())
1230                .into_iter()
1231                .map(|i| i.to_string())
1232                .collect();
1233        },
1234
1235        // Unknown sigil.
1236        Some(_) => return vec![],
1237    }
1238}
1239
1240/// Tab completion for Matrix identifiers (usernames, room aliases, etc.)
1241fn complete_matrix_names(
1242    text: &EditRope,
1243    cursor: &mut Cursor,
1244    store: &ProgramStore,
1245) -> Vec<String> {
1246    let id = text
1247        .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
1248        .unwrap_or_else(EditRope::empty);
1249    let id = Cow::from(&id);
1250
1251    let list = store.application.names.complete(id.as_ref());
1252    if !list.is_empty() {
1253        return list;
1254    }
1255
1256    let list = store.application.presences.complete(id.as_ref());
1257    if !list.is_empty() {
1258        return list.into_iter().map(|i| i.to_string()).collect();
1259    }
1260
1261    store
1262        .application
1263        .rooms
1264        .complete(id.as_ref())
1265        .into_iter()
1266        .map(|i| i.to_string())
1267        .collect()
1268}
1269
1270/// Tab completion for Emoji shortcode names.
1271fn complete_emoji(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
1272    let sc = text.get_prefix_word_mut(cursor, &WordStyle::Little);
1273    let sc = sc.unwrap_or_else(EditRope::empty);
1274    let sc = Cow::from(&sc);
1275
1276    store.application.emojis.complete(sc.as_ref())
1277}
1278
1279/// Tab completion for command names.
1280fn complete_cmdname(
1281    desc: CommandDescription,
1282    text: &EditRope,
1283    cursor: &mut Cursor,
1284    store: &ProgramStore,
1285) -> Vec<String> {
1286    // Complete command name and set cursor position.
1287    let _ = text.get_prefix_word_mut(cursor, &WordStyle::Little);
1288    store.application.cmds.complete_name(desc.command.as_str())
1289}
1290
1291/// Tab completion for command arguments.
1292fn complete_cmdarg(
1293    desc: CommandDescription,
1294    text: &EditRope,
1295    cursor: &mut Cursor,
1296    store: &ProgramStore,
1297) -> Vec<String> {
1298    let cmd = match store.application.cmds.get(desc.command.as_str()) {
1299        Ok(cmd) => cmd,
1300        Err(_) => return vec![],
1301    };
1302
1303    match cmd.name.as_str() {
1304        "cancel" | "dms" | "edit" | "redact" | "reply" => vec![],
1305        "members" | "rooms" | "spaces" | "welcome" => vec![],
1306        "download" | "open" | "upload" => complete_path(text, cursor),
1307        "react" | "unreact" => complete_emoji(text, cursor, store),
1308
1309        "invite" => complete_users(text, cursor, store),
1310        "join" | "split" | "vsplit" | "tabedit" => complete_matrix_names(text, cursor, store),
1311        "room" => vec![],
1312        "verify" => vec![],
1313        "vertical" | "horizontal" | "aboveleft" | "belowright" | "tab" => {
1314            complete_cmd(desc.arg.text.as_str(), text, cursor, store)
1315        },
1316        _ => vec![],
1317    }
1318}
1319
1320/// Tab completion for commands.
1321fn complete_cmd(
1322    cmd: &str,
1323    text: &EditRope,
1324    cursor: &mut Cursor,
1325    store: &ProgramStore,
1326) -> Vec<String> {
1327    match CommandDescription::from_str(cmd) {
1328        Ok(desc) => {
1329            if desc.arg.untrimmed.is_empty() {
1330                complete_cmdname(desc, text, cursor, store)
1331            } else {
1332                // Complete command argument.
1333                complete_cmdarg(desc, text, cursor, store)
1334            }
1335        },
1336
1337        // Can't parse command text, so return zero completions.
1338        Err(_) => vec![],
1339    }
1340}
1341
1342/// Tab completion for the command bar.
1343fn complete_cmdbar(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
1344    let eo = text.cursor_to_offset(cursor);
1345    let slice = text.slice(0.into(), eo, false);
1346    let cow = Cow::from(&slice);
1347
1348    complete_cmd(cow.as_ref(), text, cursor, store)
1349}
1350
1351#[cfg(test)]
1352pub mod tests {
1353    use super::*;
1354    use crate::config::user_style_from_color;
1355    use crate::tests::*;
1356    use modalkit::tui::style::Color;
1357
1358    #[test]
1359    fn test_typing_spans() {
1360        let mut info = RoomInfo::default();
1361        let settings = mock_settings();
1362
1363        let users0 = vec![];
1364        let users1 = vec![TEST_USER1.clone()];
1365        let users2 = vec![TEST_USER1.clone(), TEST_USER2.clone()];
1366        let users4 = vec![
1367            TEST_USER1.clone(),
1368            TEST_USER2.clone(),
1369            TEST_USER3.clone(),
1370            TEST_USER4.clone(),
1371        ];
1372        let users5 = vec![
1373            TEST_USER1.clone(),
1374            TEST_USER2.clone(),
1375            TEST_USER3.clone(),
1376            TEST_USER4.clone(),
1377            TEST_USER5.clone(),
1378        ];
1379
1380        // Nothing set.
1381        assert_eq!(info.users_typing, None);
1382        assert_eq!(info.get_typing_spans(&settings), Line::from(vec![]));
1383
1384        // Empty typing list.
1385        info.set_typing(users0);
1386        assert!(info.users_typing.is_some());
1387        assert_eq!(info.get_typing_spans(&settings), Line::from(vec![]));
1388
1389        // Single user typing.
1390        info.set_typing(users1);
1391        assert!(info.users_typing.is_some());
1392        assert_eq!(
1393            info.get_typing_spans(&settings),
1394            Line::from(vec![
1395                Span::styled("@user1:example.com", user_style("@user1:example.com")),
1396                Span::from(" is typing...")
1397            ])
1398        );
1399
1400        // Two users typing.
1401        info.set_typing(users2);
1402        assert!(info.users_typing.is_some());
1403        assert_eq!(
1404            info.get_typing_spans(&settings),
1405            Line::from(vec![
1406                Span::styled("@user1:example.com", user_style("@user1:example.com")),
1407                Span::raw(" and "),
1408                Span::styled("@user2:example.com", user_style("@user2:example.com")),
1409                Span::raw(" are typing...")
1410            ])
1411        );
1412
1413        // Four users typing.
1414        info.set_typing(users4);
1415        assert!(info.users_typing.is_some());
1416        assert_eq!(info.get_typing_spans(&settings), Line::from("Several people are typing..."));
1417
1418        // Five users typing.
1419        info.set_typing(users5);
1420        assert!(info.users_typing.is_some());
1421        assert_eq!(info.get_typing_spans(&settings), Line::from("Many people are typing..."));
1422
1423        // Test that USER5 gets rendered using the configured color and name.
1424        info.set_typing(vec![TEST_USER5.clone()]);
1425        assert!(info.users_typing.is_some());
1426        assert_eq!(
1427            info.get_typing_spans(&settings),
1428            Line::from(vec![
1429                Span::styled("USER 5", user_style_from_color(Color::Black)),
1430                Span::from(" is typing...")
1431            ])
1432        );
1433    }
1434
1435    #[tokio::test]
1436    async fn test_complete_msgbar() {
1437        let store = mock_store().await;
1438
1439        let text = EditRope::from("going for a walk :walk ");
1440        let mut cursor = Cursor::new(0, 22);
1441        let res = complete_msgbar(&text, &mut cursor, &store);
1442        assert_eq!(res, vec![":walking:", ":walking_man:", ":walking_woman:"]);
1443        assert_eq!(cursor, Cursor::new(0, 17));
1444
1445        let text = EditRope::from("hello @user1 ");
1446        let mut cursor = Cursor::new(0, 12);
1447        let res = complete_msgbar(&text, &mut cursor, &store);
1448        assert_eq!(res, vec!["@user1:example.com"]);
1449        assert_eq!(cursor, Cursor::new(0, 6));
1450
1451        let text = EditRope::from("see #room ");
1452        let mut cursor = Cursor::new(0, 9);
1453        let res = complete_msgbar(&text, &mut cursor, &store);
1454        assert_eq!(res, vec!["#room1:example.com"]);
1455        assert_eq!(cursor, Cursor::new(0, 4));
1456    }
1457
1458    #[tokio::test]
1459    async fn test_complete_cmdbar() {
1460        let store = mock_store().await;
1461        let users = vec![
1462            "@user1:example.com",
1463            "@user2:example.com",
1464            "@user3:example.com",
1465            "@user4:example.com",
1466            "@user5:example.com",
1467        ];
1468
1469        let text = EditRope::from("invite    ");
1470        let mut cursor = Cursor::new(0, 7);
1471        let id = text
1472            .get_prefix_word_mut(&mut cursor, &MATRIX_ID_WORD)
1473            .unwrap_or_else(EditRope::empty);
1474        assert_eq!(id.to_string(), "");
1475        assert_eq!(cursor, Cursor::new(0, 7));
1476
1477        let text = EditRope::from("invite    ");
1478        let mut cursor = Cursor::new(0, 7);
1479        let res = complete_cmdbar(&text, &mut cursor, &store);
1480        assert_eq!(res, users);
1481
1482        let text = EditRope::from("invite ignored");
1483        let mut cursor = Cursor::new(0, 7);
1484        let res = complete_cmdbar(&text, &mut cursor, &store);
1485        assert_eq!(res, users);
1486
1487        let text = EditRope::from("invite @user1ignored");
1488        let mut cursor = Cursor::new(0, 13);
1489        let res = complete_cmdbar(&text, &mut cursor, &store);
1490        assert_eq!(res, vec!["@user1:example.com"]);
1491
1492        let text = EditRope::from("abo hor");
1493        let mut cursor = Cursor::new(0, 7);
1494        let res = complete_cmdbar(&text, &mut cursor, &store);
1495        assert_eq!(res, vec!["horizontal"]);
1496
1497        let text = EditRope::from("abo hor inv");
1498        let mut cursor = Cursor::new(0, 11);
1499        let res = complete_cmdbar(&text, &mut cursor, &store);
1500        assert_eq!(res, vec!["invite"]);
1501
1502        let text = EditRope::from("abo hor invite \n");
1503        let mut cursor = Cursor::new(0, 15);
1504        let res = complete_cmdbar(&text, &mut cursor, &store);
1505        assert_eq!(res, users);
1506    }
1507}