src/base.rs

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