src/base.rs

2024 lines · 62410 bytes

   1//! # Common types and utilities
   2//!
   3//! The types defined here get used throughout iamb.
   4use std::borrow::Cow;
   5use std::collections::hash_map::IntoIter;
   6use std::collections::{HashMap, HashSet};
   7use std::convert::TryFrom;
   8use std::fmt::{self, Display};
   9use std::hash::Hash;
  10use std::str::FromStr;
  11use std::sync::Arc;
  12use std::time::{Duration, Instant};
  13
  14use emojis::Emoji;
  15use ratatui::{
  16    buffer::Buffer,
  17    layout::{Alignment, Rect},
  18    text::{Line, Span},
  19    widgets::{Paragraph, Widget},
  20};
  21use ratatui_image::picker::{Picker, ProtocolType};
  22use serde::{
  23    de::Error as SerdeError,
  24    de::Visitor,
  25    Deserialize,
  26    Deserializer,
  27    Serialize,
  28    Serializer,
  29};
  30use tokio::sync::Mutex as AsyncMutex;
  31use url::Url;
  32
  33use matrix_sdk::{
  34    encryption::verification::SasVerification,
  35    room::Room as MatrixRoom,
  36    ruma::{
  37        events::{
  38            reaction::ReactionEvent,
  39            relation::{Replacement, Thread},
  40            room::encrypted::RoomEncryptedEvent,
  41            room::message::{
  42                OriginalRoomMessageEvent,
  43                Relation,
  44                RoomMessageEvent,
  45                RoomMessageEventContent,
  46                RoomMessageEventContentWithoutRelation,
  47            },
  48            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            for (key, _) in reacts.values() {
 842                let count = counts.entry(key.as_str()).or_default();
 843                *count += 1;
 844            }
 845
 846            let mut reactions = counts.into_iter().collect::<Vec<_>>();
 847            reactions.sort();
 848
 849            reactions
 850        } else {
 851            vec![]
 852        }
 853    }
 854
 855    /// Map an event identifier to its [MessageKey].
 856    pub fn get_message_key(&self, event_id: &EventId) -> Option<&MessageKey> {
 857        self.keys.get(event_id)?.to_message_key()
 858    }
 859
 860    /// Get an event for an identifier.
 861    pub fn get_event(&self, event_id: &EventId) -> Option<&Message> {
 862        self.messages.get(self.get_message_key(event_id)?)
 863    }
 864
 865    /// Get an event for an identifier as mutable.
 866    pub fn get_event_mut(&mut self, event_id: &EventId) -> Option<&mut Message> {
 867        self.messages.get_mut(self.keys.get(event_id)?.to_message_key()?)
 868    }
 869
 870    pub fn redact(&mut self, ev: OriginalSyncRoomRedactionEvent, room_version: &RoomVersionId) {
 871        let Some(redacts) = &ev.redacts else {
 872            return;
 873        };
 874
 875        match self.keys.get(redacts) {
 876            None => return,
 877            Some(EventLocation::Message(None, key)) => {
 878                if let Some(msg) = self.messages.get_mut(key) {
 879                    let ev = SyncRoomRedactionEvent::Original(ev);
 880                    msg.redact(ev, room_version);
 881                }
 882            },
 883            Some(EventLocation::Message(Some(root), key)) => {
 884                if let Some(thread) = self.threads.get_mut(root) {
 885                    if let Some(msg) = thread.get_mut(key) {
 886                        let ev = SyncRoomRedactionEvent::Original(ev);
 887                        msg.redact(ev, room_version);
 888                    }
 889                }
 890            },
 891            Some(EventLocation::Reaction(event_id)) => {
 892                if let Some(reactions) = self.reactions.get_mut(event_id) {
 893                    reactions.remove(redacts);
 894                }
 895
 896                self.keys.remove(redacts);
 897            },
 898        }
 899    }
 900
 901    /// Insert a reaction to a message.
 902    pub fn insert_reaction(&mut self, react: ReactionEvent) {
 903        match react {
 904            MessageLikeEvent::Original(react) => {
 905                let rel_id = react.content.relates_to.event_id;
 906                let key = react.content.relates_to.key;
 907
 908                let message = self.reactions.entry(rel_id.clone()).or_default();
 909                let event_id = react.event_id;
 910                let user_id = react.sender;
 911
 912                message.insert(event_id.clone(), (key, user_id));
 913
 914                let loc = EventLocation::Reaction(rel_id);
 915                self.keys.insert(event_id, loc);
 916            },
 917            MessageLikeEvent::Redacted(_) => {
 918                return;
 919            },
 920        }
 921    }
 922
 923    /// Insert an edit.
 924    pub fn insert_edit(&mut self, msg: Replacement<RoomMessageEventContentWithoutRelation>) {
 925        let event_id = msg.event_id;
 926        let new_msgtype = msg.new_content;
 927
 928        let Some(EventLocation::Message(thread, key)) = self.keys.get(&event_id) else {
 929            return;
 930        };
 931
 932        let source = if let Some(thread) = thread {
 933            self.threads.entry(thread.clone()).or_default()
 934        } else {
 935            &mut self.messages
 936        };
 937
 938        let Some(msg) = source.get_mut(key) else {
 939            return;
 940        };
 941
 942        match &mut msg.event {
 943            MessageEvent::Original(orig) => {
 944                orig.content.apply_replacement(new_msgtype);
 945            },
 946            MessageEvent::Local(_, content) => {
 947                content.apply_replacement(new_msgtype);
 948            },
 949            MessageEvent::Redacted(_) |
 950            MessageEvent::EncryptedOriginal(_) |
 951            MessageEvent::EncryptedRedacted(_) => {
 952                return;
 953            },
 954        }
 955
 956        msg.html = msg.event.html();
 957    }
 958
 959    /// Indicates whether this room has unread messages.
 960    pub fn unreads(&self, settings: &ApplicationSettings) -> UnreadInfo {
 961        let last_message = self.messages.last_key_value();
 962        let last_receipt = self.get_receipt(&settings.profile.user_id);
 963
 964        match (last_message, last_receipt) {
 965            (Some(((ts, recent), _)), Some(last_read)) => {
 966                UnreadInfo { unread: last_read != recent, latest: Some(*ts) }
 967            },
 968            (Some(((ts, _), _)), None) => UnreadInfo { unread: false, latest: Some(*ts) },
 969            (None, _) => UnreadInfo::default(),
 970        }
 971    }
 972
 973    /// Inserts events that couldn't be decrypted into the scrollback.
 974    pub fn insert_encrypted(&mut self, msg: RoomEncryptedEvent) {
 975        let event_id = msg.event_id().to_owned();
 976        let key = (msg.origin_server_ts().into(), event_id.clone());
 977
 978        self.keys.insert(event_id, EventLocation::Message(None, key.clone()));
 979        self.messages.insert(key, msg.into());
 980    }
 981
 982    /// Insert a new message.
 983    pub fn insert_message(&mut self, msg: RoomMessageEvent) {
 984        let event_id = msg.event_id().to_owned();
 985        let key = (msg.origin_server_ts().into(), event_id.clone());
 986
 987        let loc = EventLocation::Message(None, key.clone());
 988        self.keys.insert(event_id, loc);
 989        self.messages.insert_message(key, msg);
 990    }
 991
 992    fn insert_thread(&mut self, msg: RoomMessageEvent, thread_root: OwnedEventId) {
 993        let event_id = msg.event_id().to_owned();
 994        let key = (msg.origin_server_ts().into(), event_id.clone());
 995
 996        let replies = self.threads.entry(thread_root.clone()).or_default();
 997        let loc = EventLocation::Message(Some(thread_root), key.clone());
 998        self.keys.insert(event_id, loc);
 999        replies.insert_message(key, msg);
1000    }
1001
1002    /// Insert a new message event.
1003    pub fn insert(&mut self, msg: RoomMessageEvent) {
1004        match msg {
1005            RoomMessageEvent::Original(OriginalRoomMessageEvent {
1006                content: RoomMessageEventContent { relates_to: Some(ref relates_to), .. },
1007                ..
1008            }) => {
1009                match relates_to {
1010                    Relation::Replacement(repl) => self.insert_edit(repl.clone()),
1011                    Relation::Thread(Thread { event_id, .. }) => {
1012                        let event_id = event_id.clone();
1013                        self.insert_thread(msg, event_id);
1014                    },
1015                    Relation::Reply { .. } => self.insert_message(msg),
1016                    _ => self.insert_message(msg),
1017                }
1018            },
1019            _ => self.insert_message(msg),
1020        }
1021    }
1022
1023    /// Insert a new message event, and spawn a task for image-preview if it has an image
1024    /// attachment.
1025    pub fn insert_with_preview(
1026        &mut self,
1027        room_id: OwnedRoomId,
1028        store: AsyncProgramStore,
1029        picker: Option<Picker>,
1030        ev: RoomMessageEvent,
1031        settings: &mut ApplicationSettings,
1032        media: matrix_sdk::Media,
1033    ) {
1034        let source = picker.and_then(|_| source_from_event(&ev));
1035        self.insert(ev);
1036
1037        if let Some((event_id, source)) = source {
1038            if let (Some(msg), Some(image_preview)) =
1039                (self.get_event_mut(&event_id), &settings.tunables.image_preview)
1040            {
1041                msg.image_preview = ImageStatus::Downloading(image_preview.size.clone());
1042                spawn_insert_preview(
1043                    store,
1044                    room_id,
1045                    event_id,
1046                    source,
1047                    media,
1048                    settings.dirs.image_previews.clone(),
1049                )
1050            }
1051        }
1052    }
1053
1054    /// Indicates whether we've recently fetched scrollback for this room.
1055    pub fn recently_fetched(&self) -> bool {
1056        self.fetch_last.map_or(false, |i| i.elapsed() < ROOM_FETCH_DEBOUNCE)
1057    }
1058
1059    fn clear_receipt(&mut self, user_id: &OwnedUserId) -> Option<()> {
1060        let old_event_id = self.user_receipts.get(user_id)?;
1061        let old_receipts = self.event_receipts.get_mut(old_event_id)?;
1062        old_receipts.remove(user_id);
1063
1064        if old_receipts.is_empty() {
1065            self.event_receipts.remove(old_event_id);
1066        }
1067
1068        None
1069    }
1070
1071    pub fn set_receipt(&mut self, user_id: OwnedUserId, event_id: OwnedEventId) {
1072        self.clear_receipt(&user_id);
1073        self.event_receipts
1074            .entry(event_id.clone())
1075            .or_default()
1076            .insert(user_id.clone());
1077        self.user_receipts.insert(user_id, event_id);
1078    }
1079
1080    pub fn get_receipt(&self, user_id: &UserId) -> Option<&OwnedEventId> {
1081        self.user_receipts.get(user_id)
1082    }
1083
1084    fn get_typers(&self) -> &[OwnedUserId] {
1085        if let Some((t, users)) = &self.users_typing {
1086            if t.elapsed() < Duration::from_secs(4) {
1087                return users.as_ref();
1088            } else {
1089                return &[];
1090            }
1091        } else {
1092            return &[];
1093        }
1094    }
1095
1096    fn get_typing_spans<'a>(&'a self, settings: &'a ApplicationSettings) -> Line<'a> {
1097        let typers = self.get_typers();
1098        let n = typers.len();
1099
1100        match n {
1101            0 => Line::from(vec![]),
1102            1 => {
1103                let user = settings.get_user_span(typers[0].as_ref(), self);
1104
1105                Line::from(vec![user, Span::from(" is typing...")])
1106            },
1107            2 => {
1108                let user1 = settings.get_user_span(typers[0].as_ref(), self);
1109                let user2 = settings.get_user_span(typers[1].as_ref(), self);
1110
1111                Line::from(vec![
1112                    user1,
1113                    Span::raw(" and "),
1114                    user2,
1115                    Span::from(" are typing..."),
1116                ])
1117            },
1118            n if n < 5 => Line::from("Several people are typing..."),
1119            _ => Line::from("Many people are typing..."),
1120        }
1121    }
1122
1123    /// Update typing information for this room.
1124    pub fn set_typing(&mut self, user_ids: Vec<OwnedUserId>) {
1125        self.users_typing = (Instant::now(), user_ids).into();
1126    }
1127
1128    /// Create a [Rect] that displays what users are typing.
1129    pub fn render_typing(
1130        &mut self,
1131        area: Rect,
1132        buf: &mut Buffer,
1133        settings: &ApplicationSettings,
1134    ) -> Rect {
1135        if area.height <= 2 || area.width <= 20 {
1136            return area;
1137        }
1138
1139        if !settings.tunables.typing_notice_display {
1140            return area;
1141        }
1142
1143        let top = Rect::new(area.x, area.y, area.width, area.height - 1);
1144        let bar = Rect::new(area.x, area.y + top.height, area.width, 1);
1145
1146        Paragraph::new(self.get_typing_spans(settings))
1147            .alignment(Alignment::Center)
1148            .render(bar, buf);
1149
1150        return top;
1151    }
1152
1153    /// Checks if a given user has reacted with the given emoji on the given event
1154    pub fn user_reactions_contains(
1155        &mut self,
1156        user_id: &UserId,
1157        event_id: &EventId,
1158        emoji: &str,
1159    ) -> bool {
1160        if let Some(reactions) = self.reactions.get(event_id) {
1161            reactions
1162                .values()
1163                .any(|(annotation, user)| annotation == emoji && user == user_id)
1164        } else {
1165            false
1166        }
1167    }
1168}
1169
1170/// Generate a [CompletionMap] for Emoji shortcodes.
1171fn emoji_map() -> CompletionMap<String, &'static Emoji> {
1172    let mut emojis = CompletionMap::default();
1173
1174    for emoji in emojis::iter() {
1175        for shortcode in emoji.shortcodes() {
1176            emojis.insert(shortcode.to_string(), emoji);
1177        }
1178    }
1179
1180    return emojis;
1181}
1182
1183#[cfg(unix)]
1184fn picker_from_termios(protocol_type: Option<ProtocolType>) -> Option<Picker> {
1185    let mut picker = match Picker::from_termios() {
1186        Ok(picker) => picker,
1187        Err(e) => {
1188            tracing::error!("Failed to setup image previews: {e}");
1189            return None;
1190        },
1191    };
1192
1193    if let Some(protocol_type) = protocol_type {
1194        picker.protocol_type = protocol_type;
1195    } else {
1196        picker.guess_protocol();
1197    }
1198
1199    Some(picker)
1200}
1201
1202/// Windows cannot guess the right protocol, and always needs type and font_size.
1203#[cfg(windows)]
1204fn picker_from_termios(_: Option<ProtocolType>) -> Option<Picker> {
1205    tracing::error!("\"image_preview\" requires \"protocol\" with \"type\" and \"font_size\" options on Windows.");
1206    None
1207}
1208
1209fn picker_from_settings(settings: &ApplicationSettings) -> Option<Picker> {
1210    let image_preview = settings.tunables.image_preview.as_ref()?;
1211    let image_preview_protocol = image_preview.protocol.as_ref();
1212
1213    if let Some(&ImagePreviewProtocolValues {
1214        r#type: Some(protocol_type),
1215        font_size: Some(font_size),
1216    }) = image_preview_protocol
1217    {
1218        // User forced type and font_size: use that.
1219        let mut picker = Picker::new(font_size);
1220        picker.protocol_type = protocol_type;
1221        Some(picker)
1222    } else {
1223        // Guess, but use type if forced.
1224        picker_from_termios(image_preview_protocol.and_then(|p| p.r#type))
1225    }
1226}
1227
1228/// Information gathered during server syncs about joined rooms.
1229#[derive(Default)]
1230pub struct SyncInfo {
1231    /// Spaces that the user is a member of.
1232    pub spaces: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
1233
1234    /// Rooms that the user is a member of.
1235    pub rooms: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
1236
1237    /// DMs that the user is a member of.
1238    pub dms: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
1239}
1240
1241bitflags::bitflags! {
1242    /// Load-needs
1243    #[derive(Debug, Default, PartialEq)]
1244    pub struct Need: u32 {
1245        const EMPTY = 0b00000000;
1246        const MESSAGES = 0b00000001;
1247        const MEMBERS =  0b00000010;
1248    }
1249}
1250
1251/// Things that need loading for different rooms.
1252#[derive(Default)]
1253pub struct RoomNeeds {
1254    needs: HashMap<OwnedRoomId, Need>,
1255}
1256
1257impl RoomNeeds {
1258    /// Mark a room for needing something to be loaded.
1259    pub fn insert(&mut self, room_id: OwnedRoomId, need: Need) {
1260        self.needs.entry(room_id).or_default().insert(need);
1261    }
1262
1263    pub fn rooms(&self) -> usize {
1264        self.needs.len()
1265    }
1266}
1267
1268impl IntoIterator for RoomNeeds {
1269    type Item = (OwnedRoomId, Need);
1270    type IntoIter = IntoIter<OwnedRoomId, Need>;
1271
1272    fn into_iter(self) -> Self::IntoIter {
1273        self.needs.into_iter()
1274    }
1275}
1276
1277/// The main application state.
1278pub struct ChatStore {
1279    /// `:`-commands
1280    pub cmds: ProgramCommands,
1281
1282    /// Handle for communicating w/ the worker thread.
1283    pub worker: Requester,
1284
1285    /// Map of joined rooms.
1286    pub rooms: CompletionMap<OwnedRoomId, RoomInfo>,
1287
1288    /// Map of room names.
1289    pub names: CompletionMap<String, OwnedRoomId>,
1290
1291    /// Presence information for other users.
1292    pub presences: CompletionMap<OwnedUserId, PresenceState>,
1293
1294    /// In-progress and completed verifications.
1295    pub verifications: HashMap<String, SasVerification>,
1296
1297    /// Settings for the current profile loaded from config file.
1298    pub settings: ApplicationSettings,
1299
1300    /// Set of rooms that need more messages loaded in their scrollback.
1301    pub need_load: RoomNeeds,
1302
1303    /// [CompletionMap] of Emoji shortcodes.
1304    pub emojis: CompletionMap<String, &'static Emoji>,
1305
1306    /// Information gathered by the background thread.
1307    pub sync_info: SyncInfo,
1308
1309    /// Image preview "protocol" picker.
1310    pub picker: Option<Picker>,
1311
1312    /// Last draw time, used to match with RoomInfo's draw_last.
1313    pub draw_curr: Option<Instant>,
1314
1315    /// Whether to ring the terminal bell on the next redraw.
1316    pub ring_bell: bool,
1317}
1318
1319impl ChatStore {
1320    /// Create a new [ChatStore].
1321    pub fn new(worker: Requester, settings: ApplicationSettings) -> Self {
1322        let picker = picker_from_settings(&settings);
1323
1324        ChatStore {
1325            worker,
1326            settings,
1327            picker,
1328            cmds: crate::commands::setup_commands(),
1329            emojis: emoji_map(),
1330
1331            names: Default::default(),
1332            rooms: Default::default(),
1333            presences: Default::default(),
1334            verifications: Default::default(),
1335            need_load: Default::default(),
1336            sync_info: Default::default(),
1337            draw_curr: None,
1338            ring_bell: false,
1339        }
1340    }
1341
1342    /// Get a joined room.
1343    pub fn get_joined_room(&self, room_id: &RoomId) -> Option<MatrixRoom> {
1344        let Some(room) = self.worker.client.get_room(room_id) else {
1345            return None;
1346        };
1347
1348        if room.state() == MatrixRoomState::Joined {
1349            Some(room)
1350        } else {
1351            None
1352        }
1353    }
1354
1355    /// Get the title for a room.
1356    pub fn get_room_title(&self, room_id: &RoomId) -> String {
1357        self.rooms
1358            .get(room_id)
1359            .and_then(|i| i.name.as_ref())
1360            .map(String::from)
1361            .unwrap_or_else(|| "Untitled Matrix Room".to_string())
1362    }
1363
1364    /// Get the [RoomInfo] for a given room identifier.
1365    pub fn get_room_info(&mut self, room_id: OwnedRoomId) -> &mut RoomInfo {
1366        self.rooms.get_or_default(room_id)
1367    }
1368
1369    /// Set the name for a room.
1370    pub fn set_room_name(&mut self, room_id: &RoomId, name: &str) {
1371        self.rooms.get_or_default(room_id.to_owned()).name = name.to_string().into();
1372    }
1373
1374    /// Insert a new E2EE verification.
1375    pub fn insert_sas(&mut self, sas: SasVerification) {
1376        let key = format!("{}/{}", sas.other_user_id(), sas.other_device().device_id());
1377
1378        self.verifications.insert(key, sas);
1379    }
1380}
1381
1382impl ApplicationStore for ChatStore {}
1383
1384/// Identified used to track window content.
1385#[derive(Clone, Debug, Eq, Hash, PartialEq)]
1386pub enum IambId {
1387    /// A Matrix room, with an optional thread to show.
1388    Room(OwnedRoomId, Option<OwnedEventId>),
1389
1390    /// The `:dms` window.
1391    DirectList,
1392
1393    /// The `:members` window for a given Matrix room.
1394    MemberList(OwnedRoomId),
1395
1396    /// The `:rooms` window.
1397    RoomList,
1398
1399    /// The `:spaces` window.
1400    SpaceList,
1401
1402    /// The `:verify` window.
1403    VerifyList,
1404
1405    /// The `:welcome` window.
1406    Welcome,
1407
1408    /// The `:chats` window.
1409    ChatList,
1410}
1411
1412impl Display for IambId {
1413    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1414        match self {
1415            IambId::Room(room_id, None) => {
1416                write!(f, "iamb://room/{room_id}")
1417            },
1418            IambId::Room(room_id, Some(thread)) => {
1419                write!(f, "iamb://room/{room_id}/threads/{thread}")
1420            },
1421            IambId::MemberList(room_id) => {
1422                write!(f, "iamb://members/{room_id}")
1423            },
1424            IambId::DirectList => f.write_str("iamb://dms"),
1425            IambId::RoomList => f.write_str("iamb://rooms"),
1426            IambId::SpaceList => f.write_str("iamb://spaces"),
1427            IambId::VerifyList => f.write_str("iamb://verify"),
1428            IambId::Welcome => f.write_str("iamb://welcome"),
1429            IambId::ChatList => f.write_str("iamb://chats"),
1430        }
1431    }
1432}
1433
1434impl ApplicationWindowId for IambId {}
1435
1436impl Serialize for IambId {
1437    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1438    where
1439        S: Serializer,
1440    {
1441        serializer.serialize_str(&self.to_string())
1442    }
1443}
1444
1445impl<'de> Deserialize<'de> for IambId {
1446    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1447    where
1448        D: Deserializer<'de>,
1449    {
1450        deserializer.deserialize_str(IambIdVisitor)
1451    }
1452}
1453
1454/// [serde] visitor for deserializing [IambId].
1455struct IambIdVisitor;
1456
1457impl<'de> Visitor<'de> for IambIdVisitor {
1458    type Value = IambId;
1459
1460    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1461        formatter.write_str("a valid window URL")
1462    }
1463
1464    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1465    where
1466        E: SerdeError,
1467    {
1468        let Ok(url) = Url::parse(value) else {
1469            return Err(E::custom("Invalid iamb window URL"));
1470        };
1471
1472        if url.scheme() != "iamb" {
1473            return Err(E::custom("Invalid iamb window URL"));
1474        }
1475
1476        match url.domain() {
1477            Some("room") => {
1478                let Some(path) = url.path_segments() else {
1479                    return Err(E::custom("Invalid members window URL"));
1480                };
1481
1482                match *path.collect::<Vec<_>>().as_slice() {
1483                    [room_id] => {
1484                        let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
1485                            return Err(E::custom("Invalid room identifier"));
1486                        };
1487
1488                        Ok(IambId::Room(room_id, None))
1489                    },
1490                    [room_id, "threads", thread_root] => {
1491                        let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
1492                            return Err(E::custom("Invalid room identifier"));
1493                        };
1494
1495                        let Ok(thread_root) = OwnedEventId::try_from(thread_root) else {
1496                            return Err(E::custom("Invalid thread root identifier"));
1497                        };
1498
1499                        Ok(IambId::Room(room_id, Some(thread_root)))
1500                    },
1501                    _ => return Err(E::custom("Invalid members window URL")),
1502                }
1503            },
1504            Some("members") => {
1505                let Some(path) = url.path_segments() else {
1506                    return Err(E::custom("Invalid members window URL"));
1507                };
1508
1509                let &[room_id] = path.collect::<Vec<_>>().as_slice() else {
1510                    return Err(E::custom("Invalid members window URL"));
1511                };
1512
1513                let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
1514                    return Err(E::custom("Invalid room identifier"));
1515                };
1516
1517                Ok(IambId::MemberList(room_id))
1518            },
1519            Some("dms") => {
1520                if url.path() != "" {
1521                    return Err(E::custom("iamb://dms takes no path"));
1522                }
1523
1524                Ok(IambId::DirectList)
1525            },
1526            Some("rooms") => {
1527                if url.path() != "" {
1528                    return Err(E::custom("iamb://rooms takes no path"));
1529                }
1530
1531                Ok(IambId::RoomList)
1532            },
1533            Some("spaces") => {
1534                if url.path() != "" {
1535                    return Err(E::custom("iamb://spaces takes no path"));
1536                }
1537
1538                Ok(IambId::SpaceList)
1539            },
1540            Some("verify") => {
1541                if url.path() != "" {
1542                    return Err(E::custom("iamb://verify takes no path"));
1543                }
1544
1545                Ok(IambId::VerifyList)
1546            },
1547            Some("welcome") => {
1548                if url.path() != "" {
1549                    return Err(E::custom("iamb://welcome takes no path"));
1550                }
1551
1552                Ok(IambId::Welcome)
1553            },
1554            Some("chats") => {
1555                if url.path() != "" {
1556                    return Err(E::custom("iamb://chats takes no path"));
1557                }
1558
1559                Ok(IambId::ChatList)
1560            },
1561            Some(s) => Err(E::custom(format!("{s:?} is not a valid window"))),
1562            None => Err(E::custom("Invalid iamb window URL")),
1563        }
1564    }
1565}
1566
1567/// Which part of the room window's UI is focused.
1568#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1569pub enum RoomFocus {
1570    /// The scrollback for a room window is focused.
1571    Scrollback,
1572
1573    /// The message bar for a room window is focused.
1574    MessageBar,
1575}
1576
1577impl RoomFocus {
1578    /// Whether this is [RoomFocus::Scrollback].
1579    pub fn is_scrollback(&self) -> bool {
1580        matches!(self, RoomFocus::Scrollback)
1581    }
1582
1583    /// Whether this is [RoomFocus::MessageBar].
1584    pub fn is_msgbar(&self) -> bool {
1585        matches!(self, RoomFocus::MessageBar)
1586    }
1587}
1588
1589/// Identifiers used to track where a mark was placed.
1590///
1591/// While this is the "buffer identifier" for the mark,
1592/// not all of these are necessarily actual buffers.
1593#[derive(Clone, Debug, Eq, Hash, PartialEq)]
1594pub enum IambBufferId {
1595    /// The command bar buffer.
1596    Command(CommandType),
1597
1598    /// The message buffer or a specific message in a room.
1599    Room(OwnedRoomId, Option<OwnedEventId>, RoomFocus),
1600
1601    /// The `:dms` window.
1602    DirectList,
1603
1604    /// The `:members` window for a room.
1605    MemberList(OwnedRoomId),
1606
1607    /// The `:rooms` window.
1608    RoomList,
1609
1610    /// The `:spaces` window.
1611    SpaceList,
1612
1613    /// The `:verify` window.
1614    VerifyList,
1615
1616    /// The buffer for the `:rooms` window.
1617    Welcome,
1618
1619    /// The `:chats` window.
1620    ChatList,
1621}
1622
1623impl IambBufferId {
1624    /// Get the identifier for the window that contains this buffer.
1625    pub fn to_window(&self) -> Option<IambId> {
1626        let id = match self {
1627            IambBufferId::Command(_) => return None,
1628            IambBufferId::Room(room, thread, _) => IambId::Room(room.clone(), thread.clone()),
1629            IambBufferId::DirectList => IambId::DirectList,
1630            IambBufferId::MemberList(room) => IambId::MemberList(room.clone()),
1631            IambBufferId::RoomList => IambId::RoomList,
1632            IambBufferId::SpaceList => IambId::SpaceList,
1633            IambBufferId::VerifyList => IambId::VerifyList,
1634            IambBufferId::Welcome => IambId::Welcome,
1635            IambBufferId::ChatList => IambId::ChatList,
1636        };
1637
1638        Some(id)
1639    }
1640}
1641
1642impl ApplicationContentId for IambBufferId {}
1643
1644impl ApplicationInfo for IambInfo {
1645    type Error = IambError;
1646    type Store = ChatStore;
1647    type Action = IambAction;
1648    type WindowId = IambId;
1649    type ContentId = IambBufferId;
1650
1651    fn complete(
1652        text: &EditRope,
1653        cursor: &mut Cursor,
1654        content: &IambBufferId,
1655        store: &mut ProgramStore,
1656    ) -> Vec<String> {
1657        match content {
1658            IambBufferId::Command(CommandType::Command) => complete_cmdbar(text, cursor, store),
1659            IambBufferId::Command(CommandType::Search) => vec![],
1660            IambBufferId::Room(_, _, RoomFocus::MessageBar) => complete_msgbar(text, cursor, store),
1661            IambBufferId::Room(_, _, RoomFocus::Scrollback) => vec![],
1662
1663            IambBufferId::DirectList => vec![],
1664            IambBufferId::MemberList(_) => vec![],
1665            IambBufferId::RoomList => vec![],
1666            IambBufferId::SpaceList => vec![],
1667            IambBufferId::VerifyList => vec![],
1668            IambBufferId::Welcome => vec![],
1669            IambBufferId::ChatList => vec![],
1670        }
1671    }
1672
1673    fn content_of_command(ct: CommandType) -> IambBufferId {
1674        IambBufferId::Command(ct)
1675    }
1676}
1677
1678/// Tab completion for user IDs.
1679fn complete_users(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
1680    let id = text
1681        .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
1682        .unwrap_or_else(EditRope::empty);
1683    let id = Cow::from(&id);
1684
1685    store
1686        .application
1687        .presences
1688        .complete(id.as_ref())
1689        .into_iter()
1690        .map(|i| i.to_string())
1691        .collect()
1692}
1693
1694/// Tab completion within the message bar.
1695fn complete_msgbar(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
1696    let id = text
1697        .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
1698        .unwrap_or_else(EditRope::empty);
1699    let id = Cow::from(&id);
1700
1701    match id.chars().next() {
1702        // Complete room aliases.
1703        Some('#') => {
1704            return store.application.names.complete(id.as_ref());
1705        },
1706
1707        // Complete room identifiers.
1708        Some('!') => {
1709            return store
1710                .application
1711                .rooms
1712                .complete(id.as_ref())
1713                .into_iter()
1714                .map(|i| i.to_string())
1715                .collect();
1716        },
1717
1718        // Complete Emoji shortcodes.
1719        Some(':') => {
1720            let list = store.application.emojis.complete(&id[1..]);
1721            let iter = list.into_iter().take(200).map(|s| format!(":{}:", s));
1722
1723            return iter.collect();
1724        },
1725
1726        // Complete usernames for @ and empty strings.
1727        Some('@') | None => {
1728            return store
1729                .application
1730                .presences
1731                .complete(id.as_ref())
1732                .into_iter()
1733                .map(|i| i.to_string())
1734                .collect();
1735        },
1736
1737        // Unknown sigil.
1738        Some(_) => return vec![],
1739    }
1740}
1741
1742/// Tab completion for Matrix identifiers (usernames, room aliases, etc.)
1743fn complete_matrix_names(
1744    text: &EditRope,
1745    cursor: &mut Cursor,
1746    store: &ProgramStore,
1747) -> Vec<String> {
1748    let id = text
1749        .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
1750        .unwrap_or_else(EditRope::empty);
1751    let id = Cow::from(&id);
1752
1753    let list = store.application.names.complete(id.as_ref());
1754    if !list.is_empty() {
1755        return list;
1756    }
1757
1758    let list = store.application.presences.complete(id.as_ref());
1759    if !list.is_empty() {
1760        return list.into_iter().map(|i| i.to_string()).collect();
1761    }
1762
1763    store
1764        .application
1765        .rooms
1766        .complete(id.as_ref())
1767        .into_iter()
1768        .map(|i| i.to_string())
1769        .collect()
1770}
1771
1772/// Tab completion for Emoji shortcode names.
1773fn complete_emoji(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
1774    let sc = text.get_prefix_word_mut(cursor, &WordStyle::Little);
1775    let sc = sc.unwrap_or_else(EditRope::empty);
1776    let sc = Cow::from(&sc);
1777
1778    store.application.emojis.complete(sc.as_ref())
1779}
1780
1781/// Tab completion for command names.
1782fn complete_cmdname(
1783    desc: CommandDescription,
1784    text: &EditRope,
1785    cursor: &mut Cursor,
1786    store: &ProgramStore,
1787) -> Vec<String> {
1788    // Complete command name and set cursor position.
1789    let _ = text.get_prefix_word_mut(cursor, &WordStyle::Little);
1790    store.application.cmds.complete_name(desc.command.as_str())
1791}
1792
1793/// Tab completion for command arguments.
1794fn complete_cmdarg(
1795    desc: CommandDescription,
1796    text: &EditRope,
1797    cursor: &mut Cursor,
1798    store: &ProgramStore,
1799) -> Vec<String> {
1800    let cmd = match store.application.cmds.get(desc.command.as_str()) {
1801        Ok(cmd) => cmd,
1802        Err(_) => return vec![],
1803    };
1804
1805    match cmd.name.as_str() {
1806        "cancel" | "dms" | "edit" | "redact" | "reply" => vec![],
1807        "members" | "rooms" | "spaces" | "welcome" => vec![],
1808        "download" | "keys" | "open" | "upload" => complete_path(text, cursor),
1809        "react" | "unreact" => complete_emoji(text, cursor, store),
1810
1811        "invite" => complete_users(text, cursor, store),
1812        "join" | "split" | "vsplit" | "tabedit" => complete_matrix_names(text, cursor, store),
1813        "room" => vec![],
1814        "verify" => vec![],
1815        "vertical" | "horizontal" | "aboveleft" | "belowright" | "tab" => {
1816            complete_cmd(desc.arg.text.as_str(), text, cursor, store)
1817        },
1818        _ => vec![],
1819    }
1820}
1821
1822/// Tab completion for commands.
1823fn complete_cmd(
1824    cmd: &str,
1825    text: &EditRope,
1826    cursor: &mut Cursor,
1827    store: &ProgramStore,
1828) -> Vec<String> {
1829    match CommandDescription::from_str(cmd) {
1830        Ok(desc) => {
1831            if desc.arg.untrimmed.is_empty() {
1832                complete_cmdname(desc, text, cursor, store)
1833            } else {
1834                // Complete command argument.
1835                complete_cmdarg(desc, text, cursor, store)
1836            }
1837        },
1838
1839        // Can't parse command text, so return zero completions.
1840        Err(_) => vec![],
1841    }
1842}
1843
1844/// Tab completion for the command bar.
1845fn complete_cmdbar(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
1846    let eo = text.cursor_to_offset(cursor);
1847    let slice = text.slice(..eo);
1848    let cow = Cow::from(&slice);
1849
1850    complete_cmd(cow.as_ref(), text, cursor, store)
1851}
1852
1853#[cfg(test)]
1854pub mod tests {
1855    use super::*;
1856    use crate::config::user_style_from_color;
1857    use crate::tests::*;
1858    use ratatui::style::Color;
1859
1860    #[test]
1861    fn test_typing_spans() {
1862        let mut info = RoomInfo::default();
1863        let settings = mock_settings();
1864
1865        let users0 = vec![];
1866        let users1 = vec![TEST_USER1.clone()];
1867        let users2 = vec![TEST_USER1.clone(), TEST_USER2.clone()];
1868        let users4 = vec![
1869            TEST_USER1.clone(),
1870            TEST_USER2.clone(),
1871            TEST_USER3.clone(),
1872            TEST_USER4.clone(),
1873        ];
1874        let users5 = vec![
1875            TEST_USER1.clone(),
1876            TEST_USER2.clone(),
1877            TEST_USER3.clone(),
1878            TEST_USER4.clone(),
1879            TEST_USER5.clone(),
1880        ];
1881
1882        // Nothing set.
1883        assert_eq!(info.users_typing, None);
1884        assert_eq!(info.get_typing_spans(&settings), Line::from(vec![]));
1885
1886        // Empty typing list.
1887        info.set_typing(users0);
1888        assert!(info.users_typing.is_some());
1889        assert_eq!(info.get_typing_spans(&settings), Line::from(vec![]));
1890
1891        // Single user typing.
1892        info.set_typing(users1);
1893        assert!(info.users_typing.is_some());
1894        assert_eq!(
1895            info.get_typing_spans(&settings),
1896            Line::from(vec![
1897                Span::styled("@user1:example.com", user_style("@user1:example.com")),
1898                Span::from(" is typing...")
1899            ])
1900        );
1901
1902        // Two users typing.
1903        info.set_typing(users2);
1904        assert!(info.users_typing.is_some());
1905        assert_eq!(
1906            info.get_typing_spans(&settings),
1907            Line::from(vec![
1908                Span::styled("@user1:example.com", user_style("@user1:example.com")),
1909                Span::raw(" and "),
1910                Span::styled("@user2:example.com", user_style("@user2:example.com")),
1911                Span::raw(" are typing...")
1912            ])
1913        );
1914
1915        // Four users typing.
1916        info.set_typing(users4);
1917        assert!(info.users_typing.is_some());
1918        assert_eq!(info.get_typing_spans(&settings), Line::from("Several people are typing..."));
1919
1920        // Five users typing.
1921        info.set_typing(users5);
1922        assert!(info.users_typing.is_some());
1923        assert_eq!(info.get_typing_spans(&settings), Line::from("Many people are typing..."));
1924
1925        // Test that USER5 gets rendered using the configured color and name.
1926        info.set_typing(vec![TEST_USER5.clone()]);
1927        assert!(info.users_typing.is_some());
1928        assert_eq!(
1929            info.get_typing_spans(&settings),
1930            Line::from(vec![
1931                Span::styled("USER 5", user_style_from_color(Color::Black)),
1932                Span::from(" is typing...")
1933            ])
1934        );
1935    }
1936
1937    #[test]
1938    fn test_need_load() {
1939        let room_id = TEST_ROOM1_ID.clone();
1940
1941        let mut need_load = RoomNeeds::default();
1942
1943        need_load.insert(room_id.clone(), Need::MESSAGES);
1944        need_load.insert(room_id.clone(), Need::MEMBERS);
1945
1946        assert_eq!(need_load.into_iter().collect::<Vec<(OwnedRoomId, Need)>>(), vec![(
1947            room_id,
1948            Need::MESSAGES | Need::MEMBERS,
1949        )],);
1950    }
1951
1952    #[tokio::test]
1953    async fn test_complete_msgbar() {
1954        let store = mock_store().await;
1955
1956        let text = EditRope::from("going for a walk :walk ");
1957        let mut cursor = Cursor::new(0, 22);
1958        let res = complete_msgbar(&text, &mut cursor, &store);
1959        assert_eq!(res, vec![":walking:", ":walking_man:", ":walking_woman:"]);
1960        assert_eq!(cursor, Cursor::new(0, 17));
1961
1962        let text = EditRope::from("hello @user1 ");
1963        let mut cursor = Cursor::new(0, 12);
1964        let res = complete_msgbar(&text, &mut cursor, &store);
1965        assert_eq!(res, vec!["@user1:example.com"]);
1966        assert_eq!(cursor, Cursor::new(0, 6));
1967
1968        let text = EditRope::from("see #room ");
1969        let mut cursor = Cursor::new(0, 9);
1970        let res = complete_msgbar(&text, &mut cursor, &store);
1971        assert_eq!(res, vec!["#room1:example.com"]);
1972        assert_eq!(cursor, Cursor::new(0, 4));
1973    }
1974
1975    #[tokio::test]
1976    async fn test_complete_cmdbar() {
1977        let store = mock_store().await;
1978        let users = vec![
1979            "@user1:example.com",
1980            "@user2:example.com",
1981            "@user3:example.com",
1982            "@user4:example.com",
1983            "@user5:example.com",
1984        ];
1985
1986        let text = EditRope::from("invite    ");
1987        let mut cursor = Cursor::new(0, 7);
1988        let id = text
1989            .get_prefix_word_mut(&mut cursor, &MATRIX_ID_WORD)
1990            .unwrap_or_else(EditRope::empty);
1991        assert_eq!(id.to_string(), "");
1992        assert_eq!(cursor, Cursor::new(0, 7));
1993
1994        let text = EditRope::from("invite    ");
1995        let mut cursor = Cursor::new(0, 7);
1996        let res = complete_cmdbar(&text, &mut cursor, &store);
1997        assert_eq!(res, users);
1998
1999        let text = EditRope::from("invite ignored");
2000        let mut cursor = Cursor::new(0, 7);
2001        let res = complete_cmdbar(&text, &mut cursor, &store);
2002        assert_eq!(res, users);
2003
2004        let text = EditRope::from("invite @user1ignored");
2005        let mut cursor = Cursor::new(0, 13);
2006        let res = complete_cmdbar(&text, &mut cursor, &store);
2007        assert_eq!(res, vec!["@user1:example.com"]);
2008
2009        let text = EditRope::from("abo hor");
2010        let mut cursor = Cursor::new(0, 7);
2011        let res = complete_cmdbar(&text, &mut cursor, &store);
2012        assert_eq!(res, vec!["horizontal"]);
2013
2014        let text = EditRope::from("abo hor inv");
2015        let mut cursor = Cursor::new(0, 11);
2016        let res = complete_cmdbar(&text, &mut cursor, &store);
2017        assert_eq!(res, vec!["invite"]);
2018
2019        let text = EditRope::from("abo hor invite \n");
2020        let mut cursor = Cursor::new(0, 15);
2021        let res = complete_cmdbar(&text, &mut cursor, &store);
2022        assert_eq!(res, users);
2023    }
2024}