src/base.rs

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