src/base.rs

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