src/base.rs

2101 lines · 65412 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    /// Whether the application is currently focused
1324    pub focused: bool,
1325}
1326
1327impl ChatStore {
1328    /// Create a new [ChatStore].
1329    pub fn new(worker: Requester, settings: ApplicationSettings) -> Self {
1330        let picker = picker_from_settings(&settings);
1331
1332        ChatStore {
1333            worker,
1334            settings,
1335            picker,
1336            cmds: crate::commands::setup_commands(),
1337            emojis: emoji_map(),
1338
1339            names: Default::default(),
1340            rooms: Default::default(),
1341            presences: Default::default(),
1342            verifications: Default::default(),
1343            need_load: Default::default(),
1344            sync_info: Default::default(),
1345            draw_curr: None,
1346            ring_bell: false,
1347            focused: true,
1348        }
1349    }
1350
1351    /// Get a joined room.
1352    pub fn get_joined_room(&self, room_id: &RoomId) -> Option<MatrixRoom> {
1353        let room = self.worker.client.get_room(room_id)?;
1354
1355        if room.state() == MatrixRoomState::Joined {
1356            Some(room)
1357        } else {
1358            None
1359        }
1360    }
1361
1362    /// Get the title for a room.
1363    pub fn get_room_title(&self, room_id: &RoomId) -> String {
1364        self.rooms
1365            .get(room_id)
1366            .and_then(|i| i.name.as_ref())
1367            .map(String::from)
1368            .unwrap_or_else(|| "Untitled Matrix Room".to_string())
1369    }
1370
1371    /// Get the [RoomInfo] for a given room identifier.
1372    pub fn get_room_info(&mut self, room_id: OwnedRoomId) -> &mut RoomInfo {
1373        self.rooms.get_or_default(room_id)
1374    }
1375
1376    /// Set the name for a room.
1377    pub fn set_room_name(&mut self, room_id: &RoomId, name: &str) {
1378        self.rooms.get_or_default(room_id.to_owned()).name = name.to_string().into();
1379    }
1380
1381    /// Insert a new E2EE verification.
1382    pub fn insert_sas(&mut self, sas: SasVerification) {
1383        let key = format!("{}/{}", sas.other_user_id(), sas.other_device().device_id());
1384
1385        self.verifications.insert(key, sas);
1386    }
1387}
1388
1389impl ApplicationStore for ChatStore {}
1390
1391/// Identified used to track window content.
1392#[derive(Clone, Debug, Eq, Hash, PartialEq)]
1393pub enum IambId {
1394    /// A Matrix room, with an optional thread to show.
1395    Room(OwnedRoomId, Option<OwnedEventId>),
1396
1397    /// The `:dms` window.
1398    DirectList,
1399
1400    /// The `:members` window for a given Matrix room.
1401    MemberList(OwnedRoomId),
1402
1403    /// The `:rooms` window.
1404    RoomList,
1405
1406    /// The `:spaces` window.
1407    SpaceList,
1408
1409    /// The `:verify` window.
1410    VerifyList,
1411
1412    /// The `:welcome` window.
1413    Welcome,
1414
1415    /// The `:chats` window.
1416    ChatList,
1417}
1418
1419impl Display for IambId {
1420    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1421        match self {
1422            IambId::Room(room_id, None) => {
1423                write!(f, "iamb://room/{room_id}")
1424            },
1425            IambId::Room(room_id, Some(thread)) => {
1426                write!(f, "iamb://room/{room_id}/threads/{thread}")
1427            },
1428            IambId::MemberList(room_id) => {
1429                write!(f, "iamb://members/{room_id}")
1430            },
1431            IambId::DirectList => f.write_str("iamb://dms"),
1432            IambId::RoomList => f.write_str("iamb://rooms"),
1433            IambId::SpaceList => f.write_str("iamb://spaces"),
1434            IambId::VerifyList => f.write_str("iamb://verify"),
1435            IambId::Welcome => f.write_str("iamb://welcome"),
1436            IambId::ChatList => f.write_str("iamb://chats"),
1437        }
1438    }
1439}
1440
1441impl ApplicationWindowId for IambId {}
1442
1443impl Serialize for IambId {
1444    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1445    where
1446        S: Serializer,
1447    {
1448        serializer.serialize_str(&self.to_string())
1449    }
1450}
1451
1452impl<'de> Deserialize<'de> for IambId {
1453    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1454    where
1455        D: Deserializer<'de>,
1456    {
1457        deserializer.deserialize_str(IambIdVisitor)
1458    }
1459}
1460
1461/// [serde] visitor for deserializing [IambId].
1462struct IambIdVisitor;
1463
1464impl<'de> Visitor<'de> for IambIdVisitor {
1465    type Value = IambId;
1466
1467    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1468        formatter.write_str("a valid window URL")
1469    }
1470
1471    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1472    where
1473        E: SerdeError,
1474    {
1475        let Ok(url) = Url::parse(value) else {
1476            return Err(E::custom("Invalid iamb window URL"));
1477        };
1478
1479        if url.scheme() != "iamb" {
1480            return Err(E::custom("Invalid iamb window URL"));
1481        }
1482
1483        match url.domain() {
1484            Some("room") => {
1485                let Some(path) = url.path_segments() else {
1486                    return Err(E::custom("Invalid members window URL"));
1487                };
1488
1489                match *path.collect::<Vec<_>>().as_slice() {
1490                    [room_id] => {
1491                        let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
1492                            return Err(E::custom("Invalid room identifier"));
1493                        };
1494
1495                        Ok(IambId::Room(room_id, None))
1496                    },
1497                    [room_id, "threads", thread_root] => {
1498                        let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
1499                            return Err(E::custom("Invalid room identifier"));
1500                        };
1501
1502                        let Ok(thread_root) = OwnedEventId::try_from(thread_root) else {
1503                            return Err(E::custom("Invalid thread root identifier"));
1504                        };
1505
1506                        Ok(IambId::Room(room_id, Some(thread_root)))
1507                    },
1508                    _ => return Err(E::custom("Invalid members window URL")),
1509                }
1510            },
1511            Some("members") => {
1512                let Some(path) = url.path_segments() else {
1513                    return Err(E::custom("Invalid members window URL"));
1514                };
1515
1516                let &[room_id] = path.collect::<Vec<_>>().as_slice() else {
1517                    return Err(E::custom("Invalid members window URL"));
1518                };
1519
1520                let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
1521                    return Err(E::custom("Invalid room identifier"));
1522                };
1523
1524                Ok(IambId::MemberList(room_id))
1525            },
1526            Some("dms") => {
1527                if url.path() != "" {
1528                    return Err(E::custom("iamb://dms takes no path"));
1529                }
1530
1531                Ok(IambId::DirectList)
1532            },
1533            Some("rooms") => {
1534                if url.path() != "" {
1535                    return Err(E::custom("iamb://rooms takes no path"));
1536                }
1537
1538                Ok(IambId::RoomList)
1539            },
1540            Some("spaces") => {
1541                if url.path() != "" {
1542                    return Err(E::custom("iamb://spaces takes no path"));
1543                }
1544
1545                Ok(IambId::SpaceList)
1546            },
1547            Some("verify") => {
1548                if url.path() != "" {
1549                    return Err(E::custom("iamb://verify takes no path"));
1550                }
1551
1552                Ok(IambId::VerifyList)
1553            },
1554            Some("welcome") => {
1555                if url.path() != "" {
1556                    return Err(E::custom("iamb://welcome takes no path"));
1557                }
1558
1559                Ok(IambId::Welcome)
1560            },
1561            Some("chats") => {
1562                if url.path() != "" {
1563                    return Err(E::custom("iamb://chats takes no path"));
1564                }
1565
1566                Ok(IambId::ChatList)
1567            },
1568            Some(s) => Err(E::custom(format!("{s:?} is not a valid window"))),
1569            None => Err(E::custom("Invalid iamb window URL")),
1570        }
1571    }
1572}
1573
1574/// Which part of the room window's UI is focused.
1575#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1576pub enum RoomFocus {
1577    /// The scrollback for a room window is focused.
1578    Scrollback,
1579
1580    /// The message bar for a room window is focused.
1581    MessageBar,
1582}
1583
1584impl RoomFocus {
1585    /// Whether this is [RoomFocus::Scrollback].
1586    pub fn is_scrollback(&self) -> bool {
1587        matches!(self, RoomFocus::Scrollback)
1588    }
1589
1590    /// Whether this is [RoomFocus::MessageBar].
1591    pub fn is_msgbar(&self) -> bool {
1592        matches!(self, RoomFocus::MessageBar)
1593    }
1594}
1595
1596/// Identifiers used to track where a mark was placed.
1597///
1598/// While this is the "buffer identifier" for the mark,
1599/// not all of these are necessarily actual buffers.
1600#[derive(Clone, Debug, Eq, Hash, PartialEq)]
1601pub enum IambBufferId {
1602    /// The command bar buffer.
1603    Command(CommandType),
1604
1605    /// The message buffer or a specific message in a room.
1606    Room(OwnedRoomId, Option<OwnedEventId>, RoomFocus),
1607
1608    /// The `:dms` window.
1609    DirectList,
1610
1611    /// The `:members` window for a room.
1612    MemberList(OwnedRoomId),
1613
1614    /// The `:rooms` window.
1615    RoomList,
1616
1617    /// The `:spaces` window.
1618    SpaceList,
1619
1620    /// The `:verify` window.
1621    VerifyList,
1622
1623    /// The buffer for the `:rooms` window.
1624    Welcome,
1625
1626    /// The `:chats` window.
1627    ChatList,
1628}
1629
1630impl IambBufferId {
1631    /// Get the identifier for the window that contains this buffer.
1632    pub fn to_window(&self) -> Option<IambId> {
1633        let id = match self {
1634            IambBufferId::Command(_) => return None,
1635            IambBufferId::Room(room, thread, _) => IambId::Room(room.clone(), thread.clone()),
1636            IambBufferId::DirectList => IambId::DirectList,
1637            IambBufferId::MemberList(room) => IambId::MemberList(room.clone()),
1638            IambBufferId::RoomList => IambId::RoomList,
1639            IambBufferId::SpaceList => IambId::SpaceList,
1640            IambBufferId::VerifyList => IambId::VerifyList,
1641            IambBufferId::Welcome => IambId::Welcome,
1642            IambBufferId::ChatList => IambId::ChatList,
1643        };
1644
1645        Some(id)
1646    }
1647}
1648
1649impl ApplicationContentId for IambBufferId {}
1650
1651impl ApplicationInfo for IambInfo {
1652    type Error = IambError;
1653    type Store = ChatStore;
1654    type Action = IambAction;
1655    type WindowId = IambId;
1656    type ContentId = IambBufferId;
1657
1658    fn complete(
1659        text: &EditRope,
1660        cursor: &mut Cursor,
1661        content: &IambBufferId,
1662        store: &mut ProgramStore,
1663    ) -> Vec<String> {
1664        match content {
1665            IambBufferId::Command(CommandType::Command) => complete_cmdbar(text, cursor, store),
1666            IambBufferId::Command(CommandType::Search) => vec![],
1667            IambBufferId::Room(_, _, RoomFocus::MessageBar) => complete_msgbar(text, cursor, store),
1668            IambBufferId::Room(_, _, RoomFocus::Scrollback) => vec![],
1669
1670            IambBufferId::DirectList => vec![],
1671            IambBufferId::MemberList(_) => vec![],
1672            IambBufferId::RoomList => vec![],
1673            IambBufferId::SpaceList => vec![],
1674            IambBufferId::VerifyList => vec![],
1675            IambBufferId::Welcome => vec![],
1676            IambBufferId::ChatList => vec![],
1677        }
1678    }
1679
1680    fn content_of_command(ct: CommandType) -> IambBufferId {
1681        IambBufferId::Command(ct)
1682    }
1683}
1684
1685/// Tab completion for user IDs.
1686fn complete_users(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
1687    let id = text
1688        .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
1689        .unwrap_or_else(EditRope::empty);
1690    let id = Cow::from(&id);
1691
1692    store
1693        .application
1694        .presences
1695        .complete(id.as_ref())
1696        .into_iter()
1697        .map(|i| i.to_string())
1698        .collect()
1699}
1700
1701/// Tab completion within the message bar.
1702fn complete_msgbar(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
1703    let id = text
1704        .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
1705        .unwrap_or_else(EditRope::empty);
1706    let id = Cow::from(&id);
1707
1708    match id.chars().next() {
1709        // Complete room aliases.
1710        Some('#') => {
1711            return store.application.names.complete(id.as_ref());
1712        },
1713
1714        // Complete room identifiers.
1715        Some('!') => {
1716            return store
1717                .application
1718                .rooms
1719                .complete(id.as_ref())
1720                .into_iter()
1721                .map(|i| i.to_string())
1722                .collect();
1723        },
1724
1725        // Complete Emoji shortcodes.
1726        Some(':') => {
1727            let list = store.application.emojis.complete(&id[1..]);
1728            let iter = list.into_iter().take(200).map(|s| format!(":{}:", s));
1729
1730            return iter.collect();
1731        },
1732
1733        // Complete usernames for @ and empty strings.
1734        Some('@') | None => {
1735            return store
1736                .application
1737                .presences
1738                .complete(id.as_ref())
1739                .into_iter()
1740                .map(|i| i.to_string())
1741                .collect();
1742        },
1743
1744        // Unknown sigil.
1745        Some(_) => return vec![],
1746    }
1747}
1748
1749/// Tab completion for Matrix identifiers (usernames, room aliases, etc.)
1750fn complete_matrix_names(
1751    text: &EditRope,
1752    cursor: &mut Cursor,
1753    store: &ProgramStore,
1754) -> Vec<String> {
1755    let id = text
1756        .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
1757        .unwrap_or_else(EditRope::empty);
1758    let id = Cow::from(&id);
1759
1760    let list = store.application.names.complete(id.as_ref());
1761    if !list.is_empty() {
1762        return list;
1763    }
1764
1765    let list = store.application.presences.complete(id.as_ref());
1766    if !list.is_empty() {
1767        return list.into_iter().map(|i| i.to_string()).collect();
1768    }
1769
1770    store
1771        .application
1772        .rooms
1773        .complete(id.as_ref())
1774        .into_iter()
1775        .map(|i| i.to_string())
1776        .collect()
1777}
1778
1779/// Tab completion for Emoji shortcode names.
1780fn complete_emoji(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
1781    let sc = text.get_prefix_word_mut(cursor, &WordStyle::Little);
1782    let sc = sc.unwrap_or_else(EditRope::empty);
1783    let sc = Cow::from(&sc);
1784
1785    store.application.emojis.complete(sc.as_ref())
1786}
1787
1788/// Tab completion for command names.
1789fn complete_cmdname(
1790    desc: CommandDescription,
1791    text: &EditRope,
1792    cursor: &mut Cursor,
1793    store: &ProgramStore,
1794) -> Vec<String> {
1795    // Complete command name and set cursor position.
1796    let _ = text.get_prefix_word_mut(cursor, &WordStyle::Little);
1797    store.application.cmds.complete_name(desc.command.as_str())
1798}
1799
1800/// Tab completion for command arguments.
1801fn complete_cmdarg(
1802    desc: CommandDescription,
1803    text: &EditRope,
1804    cursor: &mut Cursor,
1805    store: &ProgramStore,
1806) -> Vec<String> {
1807    let cmd = match store.application.cmds.get(desc.command.as_str()) {
1808        Ok(cmd) => cmd,
1809        Err(_) => return vec![],
1810    };
1811
1812    match cmd.name.as_str() {
1813        "cancel" | "dms" | "edit" | "redact" | "reply" => vec![],
1814        "members" | "rooms" | "spaces" | "welcome" => vec![],
1815        "download" | "keys" | "open" | "upload" => complete_path(text, cursor),
1816        "react" | "unreact" => complete_emoji(text, cursor, store),
1817
1818        "invite" => complete_users(text, cursor, store),
1819        "join" | "split" | "vsplit" | "tabedit" => complete_matrix_names(text, cursor, store),
1820        "room" => vec![],
1821        "verify" => vec![],
1822        "vertical" | "horizontal" | "aboveleft" | "belowright" | "tab" => {
1823            complete_cmd(desc.arg.text.as_str(), text, cursor, store)
1824        },
1825        _ => vec![],
1826    }
1827}
1828
1829/// Tab completion for commands.
1830fn complete_cmd(
1831    cmd: &str,
1832    text: &EditRope,
1833    cursor: &mut Cursor,
1834    store: &ProgramStore,
1835) -> Vec<String> {
1836    match CommandDescription::from_str(cmd) {
1837        Ok(desc) => {
1838            if desc.arg.untrimmed.is_empty() {
1839                complete_cmdname(desc, text, cursor, store)
1840            } else {
1841                // Complete command argument.
1842                complete_cmdarg(desc, text, cursor, store)
1843            }
1844        },
1845
1846        // Can't parse command text, so return zero completions.
1847        Err(_) => vec![],
1848    }
1849}
1850
1851/// Tab completion for the command bar.
1852fn complete_cmdbar(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
1853    let eo = text.cursor_to_offset(cursor);
1854    let slice = text.slice(..eo);
1855    let cow = Cow::from(&slice);
1856
1857    complete_cmd(cow.as_ref(), text, cursor, store)
1858}
1859
1860#[cfg(test)]
1861pub mod tests {
1862    use super::*;
1863    use crate::config::user_style_from_color;
1864    use crate::tests::*;
1865    use matrix_sdk::ruma::{
1866        events::{reaction::ReactionEventContent, relation::Annotation, MessageLikeUnsigned},
1867        owned_event_id,
1868        owned_room_id,
1869        owned_user_id,
1870        MilliSecondsSinceUnixEpoch,
1871    };
1872    use pretty_assertions::assert_eq;
1873    use ratatui::style::Color;
1874
1875    #[test]
1876    fn multiple_identical_reactions() {
1877        let mut info = RoomInfo::default();
1878
1879        let content = ReactionEventContent::new(Annotation::new(
1880            owned_event_id!("$my_reaction"),
1881            "🏠".to_owned(),
1882        ));
1883
1884        for i in 0..3 {
1885            let event_id = format!("$house_{}", i);
1886            info.insert_reaction(MessageLikeEvent::Original(
1887                matrix_sdk::ruma::events::OriginalMessageLikeEvent {
1888                    content: content.clone(),
1889                    event_id: OwnedEventId::from_str(&event_id).unwrap(),
1890                    sender: owned_user_id!("@foo:example.org"),
1891                    origin_server_ts: MilliSecondsSinceUnixEpoch::now(),
1892                    room_id: owned_room_id!("!foo:example.org"),
1893                    unsigned: MessageLikeUnsigned::new(),
1894                },
1895            ));
1896        }
1897
1898        let content = ReactionEventContent::new(Annotation::new(
1899            owned_event_id!("$my_reaction"),
1900            "🙂".to_owned(),
1901        ));
1902
1903        for i in 0..2 {
1904            let event_id = format!("$smile_{}", i);
1905            info.insert_reaction(MessageLikeEvent::Original(
1906                matrix_sdk::ruma::events::OriginalMessageLikeEvent {
1907                    content: content.clone(),
1908                    event_id: OwnedEventId::from_str(&event_id).unwrap(),
1909                    sender: owned_user_id!("@foo:example.org"),
1910                    origin_server_ts: MilliSecondsSinceUnixEpoch::now(),
1911                    room_id: owned_room_id!("!foo:example.org"),
1912                    unsigned: MessageLikeUnsigned::new(),
1913                },
1914            ));
1915        }
1916
1917        for i in 2..4 {
1918            let event_id = format!("$smile_{}", i);
1919            info.insert_reaction(MessageLikeEvent::Original(
1920                matrix_sdk::ruma::events::OriginalMessageLikeEvent {
1921                    content: content.clone(),
1922                    event_id: OwnedEventId::from_str(&event_id).unwrap(),
1923                    sender: owned_user_id!("@bar:example.org"),
1924                    origin_server_ts: MilliSecondsSinceUnixEpoch::now(),
1925                    room_id: owned_room_id!("!foo:example.org"),
1926                    unsigned: MessageLikeUnsigned::new(),
1927                },
1928            ));
1929        }
1930
1931        assert_eq!(info.get_reactions(&owned_event_id!("$my_reaction")), vec![
1932            ("🏠", 1),
1933            ("🙂", 2)
1934        ]);
1935    }
1936
1937    #[test]
1938    fn test_typing_spans() {
1939        let mut info = RoomInfo::default();
1940        let settings = mock_settings();
1941
1942        let users0 = vec![];
1943        let users1 = vec![TEST_USER1.clone()];
1944        let users2 = vec![TEST_USER1.clone(), TEST_USER2.clone()];
1945        let users4 = vec![
1946            TEST_USER1.clone(),
1947            TEST_USER2.clone(),
1948            TEST_USER3.clone(),
1949            TEST_USER4.clone(),
1950        ];
1951        let users5 = vec![
1952            TEST_USER1.clone(),
1953            TEST_USER2.clone(),
1954            TEST_USER3.clone(),
1955            TEST_USER4.clone(),
1956            TEST_USER5.clone(),
1957        ];
1958
1959        // Nothing set.
1960        assert_eq!(info.users_typing, None);
1961        assert_eq!(info.get_typing_spans(&settings), Line::from(vec![]));
1962
1963        // Empty typing list.
1964        info.set_typing(users0);
1965        assert!(info.users_typing.is_some());
1966        assert_eq!(info.get_typing_spans(&settings), Line::from(vec![]));
1967
1968        // Single user typing.
1969        info.set_typing(users1);
1970        assert!(info.users_typing.is_some());
1971        assert_eq!(
1972            info.get_typing_spans(&settings),
1973            Line::from(vec![
1974                Span::styled("@user1:example.com", user_style("@user1:example.com")),
1975                Span::from(" is typing...")
1976            ])
1977        );
1978
1979        // Two users typing.
1980        info.set_typing(users2);
1981        assert!(info.users_typing.is_some());
1982        assert_eq!(
1983            info.get_typing_spans(&settings),
1984            Line::from(vec![
1985                Span::styled("@user1:example.com", user_style("@user1:example.com")),
1986                Span::raw(" and "),
1987                Span::styled("@user2:example.com", user_style("@user2:example.com")),
1988                Span::raw(" are typing...")
1989            ])
1990        );
1991
1992        // Four users typing.
1993        info.set_typing(users4);
1994        assert!(info.users_typing.is_some());
1995        assert_eq!(info.get_typing_spans(&settings), Line::from("Several people are typing..."));
1996
1997        // Five users typing.
1998        info.set_typing(users5);
1999        assert!(info.users_typing.is_some());
2000        assert_eq!(info.get_typing_spans(&settings), Line::from("Many people are typing..."));
2001
2002        // Test that USER5 gets rendered using the configured color and name.
2003        info.set_typing(vec![TEST_USER5.clone()]);
2004        assert!(info.users_typing.is_some());
2005        assert_eq!(
2006            info.get_typing_spans(&settings),
2007            Line::from(vec![
2008                Span::styled("USER 5", user_style_from_color(Color::Black)),
2009                Span::from(" is typing...")
2010            ])
2011        );
2012    }
2013
2014    #[test]
2015    fn test_need_load() {
2016        let room_id = TEST_ROOM1_ID.clone();
2017
2018        let mut need_load = RoomNeeds::default();
2019
2020        need_load.insert(room_id.clone(), Need::MESSAGES);
2021        need_load.insert(room_id.clone(), Need::MEMBERS);
2022
2023        assert_eq!(need_load.into_iter().collect::<Vec<(OwnedRoomId, Need)>>(), vec![(
2024            room_id,
2025            Need::MESSAGES | Need::MEMBERS,
2026        )],);
2027    }
2028
2029    #[tokio::test]
2030    async fn test_complete_msgbar() {
2031        let store = mock_store().await;
2032
2033        let text = EditRope::from("going for a walk :walk ");
2034        let mut cursor = Cursor::new(0, 22);
2035        let res = complete_msgbar(&text, &mut cursor, &store);
2036        assert_eq!(res, vec![":walking:", ":walking_man:", ":walking_woman:"]);
2037        assert_eq!(cursor, Cursor::new(0, 17));
2038
2039        let text = EditRope::from("hello @user1 ");
2040        let mut cursor = Cursor::new(0, 12);
2041        let res = complete_msgbar(&text, &mut cursor, &store);
2042        assert_eq!(res, vec!["@user1:example.com"]);
2043        assert_eq!(cursor, Cursor::new(0, 6));
2044
2045        let text = EditRope::from("see #room ");
2046        let mut cursor = Cursor::new(0, 9);
2047        let res = complete_msgbar(&text, &mut cursor, &store);
2048        assert_eq!(res, vec!["#room1:example.com"]);
2049        assert_eq!(cursor, Cursor::new(0, 4));
2050    }
2051
2052    #[tokio::test]
2053    async fn test_complete_cmdbar() {
2054        let store = mock_store().await;
2055        let users = vec![
2056            "@user1:example.com",
2057            "@user2:example.com",
2058            "@user3:example.com",
2059            "@user4:example.com",
2060            "@user5:example.com",
2061        ];
2062
2063        let text = EditRope::from("invite    ");
2064        let mut cursor = Cursor::new(0, 7);
2065        let id = text
2066            .get_prefix_word_mut(&mut cursor, &MATRIX_ID_WORD)
2067            .unwrap_or_else(EditRope::empty);
2068        assert_eq!(id.to_string(), "");
2069        assert_eq!(cursor, Cursor::new(0, 7));
2070
2071        let text = EditRope::from("invite    ");
2072        let mut cursor = Cursor::new(0, 7);
2073        let res = complete_cmdbar(&text, &mut cursor, &store);
2074        assert_eq!(res, users);
2075
2076        let text = EditRope::from("invite ignored");
2077        let mut cursor = Cursor::new(0, 7);
2078        let res = complete_cmdbar(&text, &mut cursor, &store);
2079        assert_eq!(res, users);
2080
2081        let text = EditRope::from("invite @user1ignored");
2082        let mut cursor = Cursor::new(0, 13);
2083        let res = complete_cmdbar(&text, &mut cursor, &store);
2084        assert_eq!(res, vec!["@user1:example.com"]);
2085
2086        let text = EditRope::from("abo hor");
2087        let mut cursor = Cursor::new(0, 7);
2088        let res = complete_cmdbar(&text, &mut cursor, &store);
2089        assert_eq!(res, vec!["horizontal"]);
2090
2091        let text = EditRope::from("abo hor inv");
2092        let mut cursor = Cursor::new(0, 11);
2093        let res = complete_cmdbar(&text, &mut cursor, &store);
2094        assert_eq!(res, vec!["invite"]);
2095
2096        let text = EditRope::from("abo hor invite \n");
2097        let mut cursor = Cursor::new(0, 15);
2098        let res = complete_cmdbar(&text, &mut cursor, &store);
2099        assert_eq!(res, users);
2100    }
2101}