src/base.rs

1734 lines · 52764 bytes

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