src/base.rs

1792 lines · 54304 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 `:dms` 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    /// The `:chats` window.
1194    ChatList,
1195}
1196
1197impl Display for IambId {
1198    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1199        match self {
1200            IambId::Room(room_id) => {
1201                write!(f, "iamb://room/{room_id}")
1202            },
1203            IambId::MemberList(room_id) => {
1204                write!(f, "iamb://members/{room_id}")
1205            },
1206            IambId::DirectList => f.write_str("iamb://dms"),
1207            IambId::RoomList => f.write_str("iamb://rooms"),
1208            IambId::SpaceList => f.write_str("iamb://spaces"),
1209            IambId::VerifyList => f.write_str("iamb://verify"),
1210            IambId::Welcome => f.write_str("iamb://welcome"),
1211            IambId::ChatList => f.write_str("iamb://chats"),
1212        }
1213    }
1214}
1215
1216impl ApplicationWindowId for IambId {}
1217
1218impl Serialize for IambId {
1219    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1220    where
1221        S: Serializer,
1222    {
1223        serializer.serialize_str(&self.to_string())
1224    }
1225}
1226
1227impl<'de> Deserialize<'de> for IambId {
1228    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1229    where
1230        D: Deserializer<'de>,
1231    {
1232        deserializer.deserialize_str(IambIdVisitor)
1233    }
1234}
1235
1236/// [serde] visitor for deserializing [IambId].
1237struct IambIdVisitor;
1238
1239impl<'de> Visitor<'de> for IambIdVisitor {
1240    type Value = IambId;
1241
1242    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1243        formatter.write_str("a valid window URL")
1244    }
1245
1246    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1247    where
1248        E: SerdeError,
1249    {
1250        let Ok(url) = Url::parse(value) else {
1251            return Err(E::custom("Invalid iamb window URL"));
1252        };
1253
1254        if url.scheme() != "iamb" {
1255            return Err(E::custom("Invalid iamb window URL"));
1256        }
1257
1258        match url.domain() {
1259            Some("room") => {
1260                let Some(path) = url.path_segments() else {
1261                    return Err(E::custom("Invalid members window URL"));
1262                };
1263
1264                let &[room_id] = path.collect::<Vec<_>>().as_slice() else {
1265                    return Err(E::custom("Invalid members window URL"));
1266                };
1267
1268                let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
1269                    return Err(E::custom("Invalid room identifier"));
1270                };
1271
1272                Ok(IambId::Room(room_id))
1273            },
1274            Some("members") => {
1275                let Some(path) = url.path_segments() else {
1276                    return Err(E::custom("Invalid members window URL"));
1277                };
1278
1279                let &[room_id] = path.collect::<Vec<_>>().as_slice() else {
1280                    return Err(E::custom("Invalid members window URL"));
1281                };
1282
1283                let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
1284                    return Err(E::custom("Invalid room identifier"));
1285                };
1286
1287                Ok(IambId::MemberList(room_id))
1288            },
1289            Some("dms") => {
1290                if url.path() != "" {
1291                    return Err(E::custom("iamb://dms takes no path"));
1292                }
1293
1294                Ok(IambId::DirectList)
1295            },
1296            Some("rooms") => {
1297                if url.path() != "" {
1298                    return Err(E::custom("iamb://rooms takes no path"));
1299                }
1300
1301                Ok(IambId::RoomList)
1302            },
1303            Some("spaces") => {
1304                if url.path() != "" {
1305                    return Err(E::custom("iamb://spaces takes no path"));
1306                }
1307
1308                Ok(IambId::SpaceList)
1309            },
1310            Some("verify") => {
1311                if url.path() != "" {
1312                    return Err(E::custom("iamb://verify takes no path"));
1313                }
1314
1315                Ok(IambId::VerifyList)
1316            },
1317            Some("welcome") => {
1318                if url.path() != "" {
1319                    return Err(E::custom("iamb://welcome takes no path"));
1320                }
1321
1322                Ok(IambId::Welcome)
1323            },
1324            Some("chats") => {
1325                if url.path() != "" {
1326                    return Err(E::custom("iamb://chats takes no path"));
1327                }
1328
1329                Ok(IambId::ChatList)
1330            },
1331            Some(s) => Err(E::custom(format!("{s:?} is not a valid window"))),
1332            None => Err(E::custom("Invalid iamb window URL")),
1333        }
1334    }
1335}
1336
1337/// Which part of the room window's UI is focused.
1338#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1339pub enum RoomFocus {
1340    /// The scrollback for a room window is focused.
1341    Scrollback,
1342
1343    /// The message bar for a room window is focused.
1344    MessageBar,
1345}
1346
1347impl RoomFocus {
1348    /// Whether this is [RoomFocus::Scrollback].
1349    pub fn is_scrollback(&self) -> bool {
1350        matches!(self, RoomFocus::Scrollback)
1351    }
1352
1353    /// Whether this is [RoomFocus::MessageBar].
1354    pub fn is_msgbar(&self) -> bool {
1355        matches!(self, RoomFocus::MessageBar)
1356    }
1357}
1358
1359/// Identifiers used to track where a mark was placed.
1360///
1361/// While this is the "buffer identifier" for the mark,
1362/// not all of these are necessarily actual buffers.
1363#[derive(Clone, Debug, Eq, Hash, PartialEq)]
1364pub enum IambBufferId {
1365    /// The command bar buffer.
1366    Command(CommandType),
1367
1368    /// The message buffer or a specific message in a room.
1369    Room(OwnedRoomId, RoomFocus),
1370
1371    /// The `:dms` window.
1372    DirectList,
1373
1374    /// The `:members` window for a room.
1375    MemberList(OwnedRoomId),
1376
1377    /// The `:rooms` window.
1378    RoomList,
1379
1380    /// The `:spaces` window.
1381    SpaceList,
1382
1383    /// The `:verify` window.
1384    VerifyList,
1385
1386    /// The buffer for the `:rooms` window.
1387    Welcome,
1388
1389    /// The `:chats` window.
1390    ChatList,
1391}
1392
1393impl IambBufferId {
1394    /// Get the identifier for the window that contains this buffer.
1395    pub fn to_window(&self) -> Option<IambId> {
1396        match self {
1397            IambBufferId::Command(_) => None,
1398            IambBufferId::Room(room, _) => Some(IambId::Room(room.clone())),
1399            IambBufferId::DirectList => Some(IambId::DirectList),
1400            IambBufferId::MemberList(room) => Some(IambId::MemberList(room.clone())),
1401            IambBufferId::RoomList => Some(IambId::RoomList),
1402            IambBufferId::SpaceList => Some(IambId::SpaceList),
1403            IambBufferId::VerifyList => Some(IambId::VerifyList),
1404            IambBufferId::Welcome => Some(IambId::Welcome),
1405            IambBufferId::ChatList => Some(IambId::ChatList),
1406        }
1407    }
1408}
1409
1410impl ApplicationContentId for IambBufferId {}
1411
1412impl ApplicationInfo for IambInfo {
1413    type Error = IambError;
1414    type Store = ChatStore;
1415    type Action = IambAction;
1416    type WindowId = IambId;
1417    type ContentId = IambBufferId;
1418
1419    fn complete(
1420        text: &EditRope,
1421        cursor: &mut Cursor,
1422        content: &IambBufferId,
1423        store: &mut ProgramStore,
1424    ) -> Vec<String> {
1425        match content {
1426            IambBufferId::Command(CommandType::Command) => complete_cmdbar(text, cursor, store),
1427            IambBufferId::Command(CommandType::Search) => vec![],
1428            IambBufferId::Room(_, RoomFocus::MessageBar) => complete_msgbar(text, cursor, store),
1429            IambBufferId::Room(_, RoomFocus::Scrollback) => vec![],
1430
1431            IambBufferId::DirectList => vec![],
1432            IambBufferId::MemberList(_) => vec![],
1433            IambBufferId::RoomList => vec![],
1434            IambBufferId::SpaceList => vec![],
1435            IambBufferId::VerifyList => vec![],
1436            IambBufferId::Welcome => vec![],
1437            IambBufferId::ChatList => vec![],
1438        }
1439    }
1440
1441    fn content_of_command(ct: CommandType) -> IambBufferId {
1442        IambBufferId::Command(ct)
1443    }
1444}
1445
1446/// Tab completion for user IDs.
1447fn complete_users(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
1448    let id = text
1449        .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
1450        .unwrap_or_else(EditRope::empty);
1451    let id = Cow::from(&id);
1452
1453    store
1454        .application
1455        .presences
1456        .complete(id.as_ref())
1457        .into_iter()
1458        .map(|i| i.to_string())
1459        .collect()
1460}
1461
1462/// Tab completion within the message bar.
1463fn complete_msgbar(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
1464    let id = text
1465        .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
1466        .unwrap_or_else(EditRope::empty);
1467    let id = Cow::from(&id);
1468
1469    match id.chars().next() {
1470        // Complete room aliases.
1471        Some('#') => {
1472            return store.application.names.complete(id.as_ref());
1473        },
1474
1475        // Complete room identifiers.
1476        Some('!') => {
1477            return store
1478                .application
1479                .rooms
1480                .complete(id.as_ref())
1481                .into_iter()
1482                .map(|i| i.to_string())
1483                .collect();
1484        },
1485
1486        // Complete Emoji shortcodes.
1487        Some(':') => {
1488            let list = store.application.emojis.complete(&id[1..]);
1489            let iter = list.into_iter().take(200).map(|s| format!(":{}:", s));
1490
1491            return iter.collect();
1492        },
1493
1494        // Complete usernames for @ and empty strings.
1495        Some('@') | None => {
1496            return store
1497                .application
1498                .presences
1499                .complete(id.as_ref())
1500                .into_iter()
1501                .map(|i| i.to_string())
1502                .collect();
1503        },
1504
1505        // Unknown sigil.
1506        Some(_) => return vec![],
1507    }
1508}
1509
1510/// Tab completion for Matrix identifiers (usernames, room aliases, etc.)
1511fn complete_matrix_names(
1512    text: &EditRope,
1513    cursor: &mut Cursor,
1514    store: &ProgramStore,
1515) -> Vec<String> {
1516    let id = text
1517        .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
1518        .unwrap_or_else(EditRope::empty);
1519    let id = Cow::from(&id);
1520
1521    let list = store.application.names.complete(id.as_ref());
1522    if !list.is_empty() {
1523        return list;
1524    }
1525
1526    let list = store.application.presences.complete(id.as_ref());
1527    if !list.is_empty() {
1528        return list.into_iter().map(|i| i.to_string()).collect();
1529    }
1530
1531    store
1532        .application
1533        .rooms
1534        .complete(id.as_ref())
1535        .into_iter()
1536        .map(|i| i.to_string())
1537        .collect()
1538}
1539
1540/// Tab completion for Emoji shortcode names.
1541fn complete_emoji(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
1542    let sc = text.get_prefix_word_mut(cursor, &WordStyle::Little);
1543    let sc = sc.unwrap_or_else(EditRope::empty);
1544    let sc = Cow::from(&sc);
1545
1546    store.application.emojis.complete(sc.as_ref())
1547}
1548
1549/// Tab completion for command names.
1550fn complete_cmdname(
1551    desc: CommandDescription,
1552    text: &EditRope,
1553    cursor: &mut Cursor,
1554    store: &ProgramStore,
1555) -> Vec<String> {
1556    // Complete command name and set cursor position.
1557    let _ = text.get_prefix_word_mut(cursor, &WordStyle::Little);
1558    store.application.cmds.complete_name(desc.command.as_str())
1559}
1560
1561/// Tab completion for command arguments.
1562fn complete_cmdarg(
1563    desc: CommandDescription,
1564    text: &EditRope,
1565    cursor: &mut Cursor,
1566    store: &ProgramStore,
1567) -> Vec<String> {
1568    let cmd = match store.application.cmds.get(desc.command.as_str()) {
1569        Ok(cmd) => cmd,
1570        Err(_) => return vec![],
1571    };
1572
1573    match cmd.name.as_str() {
1574        "cancel" | "dms" | "edit" | "redact" | "reply" => vec![],
1575        "members" | "rooms" | "spaces" | "welcome" => vec![],
1576        "download" | "open" | "upload" => complete_path(text, cursor),
1577        "react" | "unreact" => complete_emoji(text, cursor, store),
1578
1579        "invite" => complete_users(text, cursor, store),
1580        "join" | "split" | "vsplit" | "tabedit" => complete_matrix_names(text, cursor, store),
1581        "room" => vec![],
1582        "verify" => vec![],
1583        "vertical" | "horizontal" | "aboveleft" | "belowright" | "tab" => {
1584            complete_cmd(desc.arg.text.as_str(), text, cursor, store)
1585        },
1586        _ => vec![],
1587    }
1588}
1589
1590/// Tab completion for commands.
1591fn complete_cmd(
1592    cmd: &str,
1593    text: &EditRope,
1594    cursor: &mut Cursor,
1595    store: &ProgramStore,
1596) -> Vec<String> {
1597    match CommandDescription::from_str(cmd) {
1598        Ok(desc) => {
1599            if desc.arg.untrimmed.is_empty() {
1600                complete_cmdname(desc, text, cursor, store)
1601            } else {
1602                // Complete command argument.
1603                complete_cmdarg(desc, text, cursor, store)
1604            }
1605        },
1606
1607        // Can't parse command text, so return zero completions.
1608        Err(_) => vec![],
1609    }
1610}
1611
1612/// Tab completion for the command bar.
1613fn complete_cmdbar(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
1614    let eo = text.cursor_to_offset(cursor);
1615    let slice = text.slice(0.into(), eo, false);
1616    let cow = Cow::from(&slice);
1617
1618    complete_cmd(cow.as_ref(), text, cursor, store)
1619}
1620
1621#[cfg(test)]
1622pub mod tests {
1623    use super::*;
1624    use crate::config::user_style_from_color;
1625    use crate::tests::*;
1626    use modalkit::tui::style::Color;
1627
1628    #[test]
1629    fn test_typing_spans() {
1630        let mut info = RoomInfo::default();
1631        let settings = mock_settings();
1632
1633        let users0 = vec![];
1634        let users1 = vec![TEST_USER1.clone()];
1635        let users2 = vec![TEST_USER1.clone(), TEST_USER2.clone()];
1636        let users4 = vec![
1637            TEST_USER1.clone(),
1638            TEST_USER2.clone(),
1639            TEST_USER3.clone(),
1640            TEST_USER4.clone(),
1641        ];
1642        let users5 = vec![
1643            TEST_USER1.clone(),
1644            TEST_USER2.clone(),
1645            TEST_USER3.clone(),
1646            TEST_USER4.clone(),
1647            TEST_USER5.clone(),
1648        ];
1649
1650        // Nothing set.
1651        assert_eq!(info.users_typing, None);
1652        assert_eq!(info.get_typing_spans(&settings), Line::from(vec![]));
1653
1654        // Empty typing list.
1655        info.set_typing(users0);
1656        assert!(info.users_typing.is_some());
1657        assert_eq!(info.get_typing_spans(&settings), Line::from(vec![]));
1658
1659        // Single user typing.
1660        info.set_typing(users1);
1661        assert!(info.users_typing.is_some());
1662        assert_eq!(
1663            info.get_typing_spans(&settings),
1664            Line::from(vec![
1665                Span::styled("@user1:example.com", user_style("@user1:example.com")),
1666                Span::from(" is typing...")
1667            ])
1668        );
1669
1670        // Two users typing.
1671        info.set_typing(users2);
1672        assert!(info.users_typing.is_some());
1673        assert_eq!(
1674            info.get_typing_spans(&settings),
1675            Line::from(vec![
1676                Span::styled("@user1:example.com", user_style("@user1:example.com")),
1677                Span::raw(" and "),
1678                Span::styled("@user2:example.com", user_style("@user2:example.com")),
1679                Span::raw(" are typing...")
1680            ])
1681        );
1682
1683        // Four users typing.
1684        info.set_typing(users4);
1685        assert!(info.users_typing.is_some());
1686        assert_eq!(info.get_typing_spans(&settings), Line::from("Several people are typing..."));
1687
1688        // Five users typing.
1689        info.set_typing(users5);
1690        assert!(info.users_typing.is_some());
1691        assert_eq!(info.get_typing_spans(&settings), Line::from("Many people are typing..."));
1692
1693        // Test that USER5 gets rendered using the configured color and name.
1694        info.set_typing(vec![TEST_USER5.clone()]);
1695        assert!(info.users_typing.is_some());
1696        assert_eq!(
1697            info.get_typing_spans(&settings),
1698            Line::from(vec![
1699                Span::styled("USER 5", user_style_from_color(Color::Black)),
1700                Span::from(" is typing...")
1701            ])
1702        );
1703    }
1704
1705    #[test]
1706    fn test_need_load() {
1707        let room_id = TEST_ROOM1_ID.clone();
1708
1709        let mut need_load = RoomNeeds::default();
1710
1711        need_load.insert(room_id.clone(), Need::MESSAGES);
1712        need_load.insert(room_id.clone(), Need::MEMBERS);
1713
1714        assert_eq!(need_load.into_iter().collect::<Vec<(OwnedRoomId, Need)>>(), vec![(
1715            room_id,
1716            Need::MESSAGES | Need::MEMBERS,
1717        )],);
1718    }
1719
1720    #[tokio::test]
1721    async fn test_complete_msgbar() {
1722        let store = mock_store().await;
1723
1724        let text = EditRope::from("going for a walk :walk ");
1725        let mut cursor = Cursor::new(0, 22);
1726        let res = complete_msgbar(&text, &mut cursor, &store);
1727        assert_eq!(res, vec![":walking:", ":walking_man:", ":walking_woman:"]);
1728        assert_eq!(cursor, Cursor::new(0, 17));
1729
1730        let text = EditRope::from("hello @user1 ");
1731        let mut cursor = Cursor::new(0, 12);
1732        let res = complete_msgbar(&text, &mut cursor, &store);
1733        assert_eq!(res, vec!["@user1:example.com"]);
1734        assert_eq!(cursor, Cursor::new(0, 6));
1735
1736        let text = EditRope::from("see #room ");
1737        let mut cursor = Cursor::new(0, 9);
1738        let res = complete_msgbar(&text, &mut cursor, &store);
1739        assert_eq!(res, vec!["#room1:example.com"]);
1740        assert_eq!(cursor, Cursor::new(0, 4));
1741    }
1742
1743    #[tokio::test]
1744    async fn test_complete_cmdbar() {
1745        let store = mock_store().await;
1746        let users = vec![
1747            "@user1:example.com",
1748            "@user2:example.com",
1749            "@user3:example.com",
1750            "@user4:example.com",
1751            "@user5:example.com",
1752        ];
1753
1754        let text = EditRope::from("invite    ");
1755        let mut cursor = Cursor::new(0, 7);
1756        let id = text
1757            .get_prefix_word_mut(&mut cursor, &MATRIX_ID_WORD)
1758            .unwrap_or_else(EditRope::empty);
1759        assert_eq!(id.to_string(), "");
1760        assert_eq!(cursor, Cursor::new(0, 7));
1761
1762        let text = EditRope::from("invite    ");
1763        let mut cursor = Cursor::new(0, 7);
1764        let res = complete_cmdbar(&text, &mut cursor, &store);
1765        assert_eq!(res, users);
1766
1767        let text = EditRope::from("invite ignored");
1768        let mut cursor = Cursor::new(0, 7);
1769        let res = complete_cmdbar(&text, &mut cursor, &store);
1770        assert_eq!(res, users);
1771
1772        let text = EditRope::from("invite @user1ignored");
1773        let mut cursor = Cursor::new(0, 13);
1774        let res = complete_cmdbar(&text, &mut cursor, &store);
1775        assert_eq!(res, vec!["@user1:example.com"]);
1776
1777        let text = EditRope::from("abo hor");
1778        let mut cursor = Cursor::new(0, 7);
1779        let res = complete_cmdbar(&text, &mut cursor, &store);
1780        assert_eq!(res, vec!["horizontal"]);
1781
1782        let text = EditRope::from("abo hor inv");
1783        let mut cursor = Cursor::new(0, 11);
1784        let res = complete_cmdbar(&text, &mut cursor, &store);
1785        assert_eq!(res, vec!["invite"]);
1786
1787        let text = EditRope::from("abo hor invite \n");
1788        let mut cursor = Cursor::new(0, 15);
1789        let res = complete_cmdbar(&text, &mut cursor, &store);
1790        assert_eq!(res, users);
1791    }
1792}