src/base.rs

1777 lines · 53837 bytes

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