src/base.rs

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