src/base.rs

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