src/base.rs

2355 lines · 74038 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, Completer, 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            // still keep one line blank, so `render_jump_to_recent` doesn't immediately hide the
1365            // last line in scrollback
1366            return Rect::new(area.x, area.y, area.width, area.height - 1);
1367        }
1368
1369        let top = Rect::new(area.x, area.y, area.width, area.height - 1);
1370        let bar = Rect::new(area.x, area.y + top.height, area.width, 1);
1371
1372        Paragraph::new(self.get_typing_spans(settings))
1373            .alignment(Alignment::Center)
1374            .render(bar, buf);
1375
1376        return top;
1377    }
1378
1379    /// Checks if a given user has reacted with the given emoji on the given event
1380    pub fn user_reactions_contains(
1381        &mut self,
1382        user_id: &UserId,
1383        event_id: &EventId,
1384        emoji: &str,
1385    ) -> bool {
1386        if let Some(reactions) = self.reactions.get(event_id) {
1387            reactions
1388                .values()
1389                .any(|(annotation, user)| annotation == emoji && user == user_id)
1390        } else {
1391            false
1392        }
1393    }
1394}
1395
1396/// Generate a [CompletionMap] for Emoji shortcodes.
1397fn emoji_map() -> CompletionMap<String, &'static Emoji> {
1398    let mut emojis = CompletionMap::default();
1399
1400    for emoji in emojis::iter() {
1401        for shortcode in emoji.shortcodes() {
1402            emojis.insert(shortcode.to_string(), emoji);
1403        }
1404    }
1405
1406    return emojis;
1407}
1408
1409#[cfg(unix)]
1410fn picker_from_termios(protocol_type: Option<ProtocolType>) -> Option<Picker> {
1411    let mut picker = match Picker::from_query_stdio() {
1412        Ok(picker) => picker,
1413        Err(e) => {
1414            tracing::error!("Failed to setup image previews: {e}");
1415            return None;
1416        },
1417    };
1418
1419    if let Some(protocol_type) = protocol_type {
1420        picker.set_protocol_type(protocol_type);
1421    }
1422
1423    Some(picker)
1424}
1425
1426/// Windows cannot guess the right protocol, and always needs type and font_size.
1427#[cfg(windows)]
1428fn picker_from_termios(_: Option<ProtocolType>) -> Option<Picker> {
1429    tracing::error!("\"image_preview\" requires \"protocol\" with \"type\" and \"font_size\" options on Windows.");
1430    None
1431}
1432
1433fn picker_from_settings(settings: &ApplicationSettings) -> Option<Picker> {
1434    let image_preview = settings.tunables.image_preview.as_ref()?;
1435    let image_preview_protocol = image_preview.protocol.as_ref();
1436
1437    if let Some(&ImagePreviewProtocolValues {
1438        r#type: Some(protocol_type),
1439        font_size: Some(font_size),
1440    }) = image_preview_protocol
1441    {
1442        // User forced type and font_size: use that.
1443        let mut picker = Picker::from_fontsize(font_size);
1444        picker.set_protocol_type(protocol_type);
1445        Some(picker)
1446    } else {
1447        // Guess, but use type if forced.
1448        picker_from_termios(image_preview_protocol.and_then(|p| p.r#type))
1449    }
1450}
1451
1452/// Information gathered during server syncs about joined rooms.
1453#[derive(Default)]
1454pub struct SyncInfo {
1455    /// Spaces that the user is a member of.
1456    pub spaces: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
1457
1458    /// Rooms that the user is a member of.
1459    pub rooms: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
1460
1461    /// DMs that the user is a member of.
1462    pub dms: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
1463}
1464
1465impl SyncInfo {
1466    pub fn rooms(&self) -> impl Iterator<Item = &RoomId> {
1467        self.rooms.iter().map(|r| r.0.room_id())
1468    }
1469
1470    pub fn dms(&self) -> impl Iterator<Item = &RoomId> {
1471        self.dms.iter().map(|r| r.0.room_id())
1472    }
1473
1474    pub fn chats(&self) -> impl Iterator<Item = &RoomId> {
1475        self.rooms().chain(self.dms())
1476    }
1477}
1478
1479bitflags::bitflags! {
1480    /// Load-needs
1481    #[derive(Debug, Default, PartialEq)]
1482    pub struct Need: u32 {
1483        const EMPTY = 0b00000000;
1484        const MESSAGES = 0b00000001;
1485        const MEMBERS =  0b00000010;
1486    }
1487}
1488
1489/// Things that need loading for different rooms.
1490#[derive(Default)]
1491pub struct RoomNeeds {
1492    needs: HashMap<OwnedRoomId, Need>,
1493}
1494
1495impl RoomNeeds {
1496    /// Mark a room for needing something to be loaded.
1497    pub fn insert(&mut self, room_id: OwnedRoomId, need: Need) {
1498        self.needs.entry(room_id).or_default().insert(need);
1499    }
1500
1501    pub fn rooms(&self) -> usize {
1502        self.needs.len()
1503    }
1504}
1505
1506impl IntoIterator for RoomNeeds {
1507    type Item = (OwnedRoomId, Need);
1508    type IntoIter = IntoIter<OwnedRoomId, Need>;
1509
1510    fn into_iter(self) -> Self::IntoIter {
1511        self.needs.into_iter()
1512    }
1513}
1514
1515/// The main application state.
1516pub struct ChatStore {
1517    /// `:`-commands
1518    pub cmds: ProgramCommands,
1519
1520    /// Handle for communicating w/ the worker thread.
1521    pub worker: Requester,
1522
1523    /// Map of joined rooms.
1524    pub rooms: CompletionMap<OwnedRoomId, RoomInfo>,
1525
1526    /// Map of room names.
1527    pub names: CompletionMap<String, OwnedRoomId>,
1528
1529    /// Presence information for other users.
1530    pub presences: CompletionMap<OwnedUserId, PresenceState>,
1531
1532    /// In-progress and completed verifications.
1533    pub verifications: HashMap<String, SasVerification>,
1534
1535    /// Settings for the current profile loaded from config file.
1536    pub settings: ApplicationSettings,
1537
1538    /// Set of rooms that need more messages loaded in their scrollback.
1539    pub need_load: RoomNeeds,
1540
1541    /// [CompletionMap] of Emoji shortcodes.
1542    pub emojis: CompletionMap<String, &'static Emoji>,
1543
1544    /// Information gathered by the background thread.
1545    pub sync_info: SyncInfo,
1546
1547    /// Image preview "protocol" picker.
1548    pub picker: Option<Picker>,
1549
1550    /// Last draw time, used to match with RoomInfo's draw_last.
1551    pub draw_curr: Option<Instant>,
1552
1553    /// Whether to ring the terminal bell on the next redraw.
1554    pub ring_bell: bool,
1555
1556    /// Whether the application is currently focused
1557    pub focused: bool,
1558
1559    /// Collator for locale-aware text sorting.
1560    pub collator: feruca::Collator,
1561}
1562
1563impl ChatStore {
1564    /// Create a new [ChatStore].
1565    pub fn new(worker: Requester, settings: ApplicationSettings) -> Self {
1566        let picker = picker_from_settings(&settings);
1567
1568        ChatStore {
1569            worker,
1570            settings,
1571            picker,
1572            cmds: crate::commands::setup_commands(),
1573            emojis: emoji_map(),
1574
1575            collator: Default::default(),
1576            names: Default::default(),
1577            rooms: Default::default(),
1578            presences: Default::default(),
1579            verifications: Default::default(),
1580            need_load: Default::default(),
1581            sync_info: Default::default(),
1582            draw_curr: None,
1583            ring_bell: false,
1584            focused: true,
1585        }
1586    }
1587
1588    /// Get a joined room.
1589    pub fn get_joined_room(&self, room_id: &RoomId) -> Option<MatrixRoom> {
1590        let room = self.worker.client.get_room(room_id)?;
1591
1592        if room.state() == MatrixRoomState::Joined {
1593            Some(room)
1594        } else {
1595            None
1596        }
1597    }
1598
1599    /// Get the title for a room.
1600    pub fn get_room_title(&self, room_id: &RoomId) -> String {
1601        self.rooms
1602            .get(room_id)
1603            .and_then(|i| i.name.as_ref())
1604            .map(String::from)
1605            .unwrap_or_else(|| "Untitled Matrix Room".to_string())
1606    }
1607
1608    /// Get the [RoomInfo] for a given room identifier.
1609    pub fn get_room_info(&mut self, room_id: OwnedRoomId) -> &mut RoomInfo {
1610        self.rooms.get_or_default(room_id)
1611    }
1612
1613    /// Set the name for a room.
1614    pub fn set_room_name(&mut self, room_id: &RoomId, name: &str) {
1615        self.rooms.get_or_default(room_id.to_owned()).name = name.to_string().into();
1616    }
1617
1618    /// Insert a new E2EE verification.
1619    pub fn insert_sas(&mut self, sas: SasVerification) {
1620        let key = format!("{}/{}", sas.other_user_id(), sas.other_device().device_id());
1621
1622        self.verifications.insert(key, sas);
1623    }
1624}
1625
1626impl ApplicationStore for ChatStore {}
1627
1628/// Identified used to track window content.
1629#[derive(Clone, Debug, Eq, Hash, PartialEq)]
1630pub enum IambId {
1631    /// A Matrix room, with an optional thread to show.
1632    Room(OwnedRoomId, Option<OwnedEventId>),
1633
1634    /// The `:dms` window.
1635    DirectList,
1636
1637    /// The `:members` window for a given Matrix room.
1638    MemberList(OwnedRoomId),
1639
1640    /// The `:rooms` window.
1641    RoomList,
1642
1643    /// The `:spaces` window.
1644    SpaceList,
1645
1646    /// The `:verify` window.
1647    VerifyList,
1648
1649    /// The `:welcome` window.
1650    Welcome,
1651
1652    /// The `:chats` window.
1653    ChatList,
1654
1655    /// The `:unreads` window.
1656    UnreadList,
1657}
1658
1659impl Display for IambId {
1660    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1661        match self {
1662            IambId::Room(room_id, None) => {
1663                write!(f, "iamb://room/{room_id}")
1664            },
1665            IambId::Room(room_id, Some(thread)) => {
1666                write!(f, "iamb://room/{room_id}/threads/{thread}")
1667            },
1668            IambId::MemberList(room_id) => {
1669                write!(f, "iamb://members/{room_id}")
1670            },
1671            IambId::DirectList => f.write_str("iamb://dms"),
1672            IambId::RoomList => f.write_str("iamb://rooms"),
1673            IambId::SpaceList => f.write_str("iamb://spaces"),
1674            IambId::VerifyList => f.write_str("iamb://verify"),
1675            IambId::Welcome => f.write_str("iamb://welcome"),
1676            IambId::ChatList => f.write_str("iamb://chats"),
1677            IambId::UnreadList => f.write_str("iamb://unreads"),
1678        }
1679    }
1680}
1681
1682impl ApplicationWindowId for IambId {}
1683
1684impl Serialize for IambId {
1685    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1686    where
1687        S: Serializer,
1688    {
1689        serializer.serialize_str(&self.to_string())
1690    }
1691}
1692
1693impl<'de> Deserialize<'de> for IambId {
1694    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1695    where
1696        D: Deserializer<'de>,
1697    {
1698        deserializer.deserialize_str(IambIdVisitor)
1699    }
1700}
1701
1702/// [serde] visitor for deserializing [IambId].
1703struct IambIdVisitor;
1704
1705impl Visitor<'_> for IambIdVisitor {
1706    type Value = IambId;
1707
1708    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1709        formatter.write_str("a valid window URL")
1710    }
1711
1712    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1713    where
1714        E: SerdeError,
1715    {
1716        let Ok(url) = Url::parse(value) else {
1717            return Err(E::custom("Invalid iamb window URL"));
1718        };
1719
1720        if url.scheme() != "iamb" {
1721            return Err(E::custom("Invalid iamb window URL"));
1722        }
1723
1724        match url.domain() {
1725            Some("room") => {
1726                let Some(path) = url.path_segments() else {
1727                    return Err(E::custom("Invalid members window URL"));
1728                };
1729
1730                match *path.collect::<Vec<_>>().as_slice() {
1731                    [room_id] => {
1732                        let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
1733                            return Err(E::custom("Invalid room identifier"));
1734                        };
1735
1736                        Ok(IambId::Room(room_id, None))
1737                    },
1738                    [room_id, "threads", thread_root] => {
1739                        let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
1740                            return Err(E::custom("Invalid room identifier"));
1741                        };
1742
1743                        let Ok(thread_root) = OwnedEventId::try_from(thread_root) else {
1744                            return Err(E::custom("Invalid thread root identifier"));
1745                        };
1746
1747                        Ok(IambId::Room(room_id, Some(thread_root)))
1748                    },
1749                    _ => return Err(E::custom("Invalid members window URL")),
1750                }
1751            },
1752            Some("members") => {
1753                let Some(path) = url.path_segments() else {
1754                    return Err(E::custom("Invalid members window URL"));
1755                };
1756
1757                let &[room_id] = path.collect::<Vec<_>>().as_slice() else {
1758                    return Err(E::custom("Invalid members window URL"));
1759                };
1760
1761                let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
1762                    return Err(E::custom("Invalid room identifier"));
1763                };
1764
1765                Ok(IambId::MemberList(room_id))
1766            },
1767            Some("dms") => {
1768                if url.path() != "" {
1769                    return Err(E::custom("iamb://dms takes no path"));
1770                }
1771
1772                Ok(IambId::DirectList)
1773            },
1774            Some("rooms") => {
1775                if url.path() != "" {
1776                    return Err(E::custom("iamb://rooms takes no path"));
1777                }
1778
1779                Ok(IambId::RoomList)
1780            },
1781            Some("spaces") => {
1782                if url.path() != "" {
1783                    return Err(E::custom("iamb://spaces takes no path"));
1784                }
1785
1786                Ok(IambId::SpaceList)
1787            },
1788            Some("verify") => {
1789                if url.path() != "" {
1790                    return Err(E::custom("iamb://verify takes no path"));
1791                }
1792
1793                Ok(IambId::VerifyList)
1794            },
1795            Some("welcome") => {
1796                if url.path() != "" {
1797                    return Err(E::custom("iamb://welcome takes no path"));
1798                }
1799
1800                Ok(IambId::Welcome)
1801            },
1802            Some("chats") => {
1803                if url.path() != "" {
1804                    return Err(E::custom("iamb://chats takes no path"));
1805                }
1806
1807                Ok(IambId::ChatList)
1808            },
1809            Some("unreads") => {
1810                if url.path() != "" {
1811                    return Err(E::custom("iamb://unreads takes no path"));
1812                }
1813
1814                Ok(IambId::UnreadList)
1815            },
1816            Some(s) => Err(E::custom(format!("{s:?} is not a valid window"))),
1817            None => Err(E::custom("Invalid iamb window URL")),
1818        }
1819    }
1820}
1821
1822/// Which part of the room window's UI is focused.
1823#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1824pub enum RoomFocus {
1825    /// The scrollback for a room window is focused.
1826    Scrollback,
1827
1828    /// The message bar for a room window is focused.
1829    MessageBar,
1830}
1831
1832impl RoomFocus {
1833    /// Whether this is [RoomFocus::Scrollback].
1834    pub fn is_scrollback(&self) -> bool {
1835        matches!(self, RoomFocus::Scrollback)
1836    }
1837
1838    /// Whether this is [RoomFocus::MessageBar].
1839    pub fn is_msgbar(&self) -> bool {
1840        matches!(self, RoomFocus::MessageBar)
1841    }
1842
1843    pub fn toggle(&mut self) {
1844        *self = match self {
1845            RoomFocus::MessageBar => RoomFocus::Scrollback,
1846            RoomFocus::Scrollback => RoomFocus::MessageBar,
1847        };
1848    }
1849}
1850
1851/// Identifiers used to track where a mark was placed.
1852///
1853/// While this is the "buffer identifier" for the mark,
1854/// not all of these are necessarily actual buffers.
1855#[derive(Clone, Debug, Eq, Hash, PartialEq)]
1856pub enum IambBufferId {
1857    /// The command bar buffer.
1858    Command(CommandType),
1859
1860    /// The message buffer or a specific message in a room.
1861    Room(OwnedRoomId, Option<OwnedEventId>, RoomFocus),
1862
1863    /// The `:dms` window.
1864    DirectList,
1865
1866    /// The `:members` window for a room.
1867    MemberList(OwnedRoomId),
1868
1869    /// The `:rooms` window.
1870    RoomList,
1871
1872    /// The `:spaces` window.
1873    SpaceList,
1874
1875    /// The `:verify` window.
1876    VerifyList,
1877
1878    /// The buffer for the `:rooms` window.
1879    Welcome,
1880
1881    /// The `:chats` window.
1882    ChatList,
1883
1884    /// The `:unreads` window.
1885    UnreadList,
1886}
1887
1888impl IambBufferId {
1889    /// Get the identifier for the window that contains this buffer.
1890    pub fn to_window(&self) -> Option<IambId> {
1891        let id = match self {
1892            IambBufferId::Command(_) => return None,
1893            IambBufferId::Room(room, thread, _) => IambId::Room(room.clone(), thread.clone()),
1894            IambBufferId::DirectList => IambId::DirectList,
1895            IambBufferId::MemberList(room) => IambId::MemberList(room.clone()),
1896            IambBufferId::RoomList => IambId::RoomList,
1897            IambBufferId::SpaceList => IambId::SpaceList,
1898            IambBufferId::VerifyList => IambId::VerifyList,
1899            IambBufferId::Welcome => IambId::Welcome,
1900            IambBufferId::ChatList => IambId::ChatList,
1901            IambBufferId::UnreadList => IambId::UnreadList,
1902        };
1903
1904        Some(id)
1905    }
1906}
1907
1908impl ApplicationContentId for IambBufferId {}
1909
1910impl ApplicationInfo for IambInfo {
1911    type Error = IambError;
1912    type Store = ChatStore;
1913    type Action = IambAction;
1914    type WindowId = IambId;
1915    type ContentId = IambBufferId;
1916
1917    fn content_of_command(ct: CommandType) -> IambBufferId {
1918        IambBufferId::Command(ct)
1919    }
1920}
1921
1922pub struct IambCompleter;
1923
1924impl Completer<IambInfo> for IambCompleter {
1925    fn complete(
1926        &mut self,
1927        text: &EditRope,
1928        cursor: &mut Cursor,
1929        content: &IambBufferId,
1930        store: &mut ChatStore,
1931    ) -> Vec<String> {
1932        match content {
1933            IambBufferId::Command(CommandType::Command) => complete_cmdbar(text, cursor, store),
1934            IambBufferId::Command(CommandType::Search) => vec![],
1935            IambBufferId::Room(_, _, RoomFocus::MessageBar) => complete_msgbar(text, cursor, store),
1936            IambBufferId::Room(_, _, RoomFocus::Scrollback) => vec![],
1937
1938            IambBufferId::DirectList => vec![],
1939            IambBufferId::MemberList(_) => vec![],
1940            IambBufferId::RoomList => vec![],
1941            IambBufferId::SpaceList => vec![],
1942            IambBufferId::VerifyList => vec![],
1943            IambBufferId::Welcome => vec![],
1944            IambBufferId::ChatList => vec![],
1945            IambBufferId::UnreadList => vec![],
1946        }
1947    }
1948}
1949
1950/// Tab completion for user IDs.
1951fn complete_users(text: &EditRope, cursor: &mut Cursor, store: &ChatStore) -> Vec<String> {
1952    let id = text
1953        .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
1954        .unwrap_or_else(EditRope::empty);
1955    let id = Cow::from(&id);
1956
1957    store
1958        .presences
1959        .complete(id.as_ref())
1960        .into_iter()
1961        .map(|i| i.to_string())
1962        .collect()
1963}
1964
1965/// Tab completion within the message bar.
1966fn complete_msgbar(text: &EditRope, cursor: &mut Cursor, store: &ChatStore) -> Vec<String> {
1967    let id = text
1968        .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
1969        .unwrap_or_else(EditRope::empty);
1970    let id = Cow::from(&id);
1971
1972    match id.chars().next() {
1973        // Complete room aliases.
1974        Some('#') => {
1975            return store.names.complete(id.as_ref());
1976        },
1977
1978        // Complete room identifiers.
1979        Some('!') => {
1980            return store
1981                .rooms
1982                .complete(id.as_ref())
1983                .into_iter()
1984                .map(|i| i.to_string())
1985                .collect();
1986        },
1987
1988        // Complete Emoji shortcodes.
1989        Some(':') => {
1990            let list = store.emojis.complete(&id[1..]);
1991            let iter = list.into_iter().take(200).map(|s| format!(":{}:", s));
1992
1993            return iter.collect();
1994        },
1995
1996        // Complete usernames for @ and empty strings.
1997        Some('@') | None => {
1998            return store
1999                .presences
2000                .complete(id.as_ref())
2001                .into_iter()
2002                .map(|i| i.to_string())
2003                .collect();
2004        },
2005
2006        // Unknown sigil.
2007        Some(_) => return vec![],
2008    }
2009}
2010
2011/// Tab completion for Matrix identifiers (usernames, room aliases, etc.)
2012fn complete_matrix_names(text: &EditRope, cursor: &mut Cursor, store: &ChatStore) -> 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.names.complete(id.as_ref());
2019    if !list.is_empty() {
2020        return list;
2021    }
2022
2023    let list = store.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        .rooms
2030        .complete(id.as_ref())
2031        .into_iter()
2032        .map(|i| i.to_string())
2033        .collect()
2034}
2035
2036/// Tab completion for Emoji shortcode names.
2037fn complete_emoji(text: &EditRope, cursor: &mut Cursor, store: &ChatStore) -> Vec<String> {
2038    let sc = text.get_prefix_word_mut(cursor, &WordStyle::Little);
2039    let sc = sc.unwrap_or_else(EditRope::empty);
2040    let sc = Cow::from(&sc);
2041
2042    store.emojis.complete(sc.as_ref())
2043}
2044
2045/// Tab completion for command names.
2046fn complete_cmdname(
2047    desc: CommandDescription,
2048    text: &EditRope,
2049    cursor: &mut Cursor,
2050    store: &ChatStore,
2051) -> Vec<String> {
2052    // Complete command name and set cursor position.
2053    let _ = text.get_prefix_word_mut(cursor, &WordStyle::Little);
2054    store.cmds.complete_name(desc.command.as_str())
2055}
2056
2057/// Tab completion for command arguments.
2058fn complete_cmdarg(
2059    desc: CommandDescription,
2060    text: &EditRope,
2061    cursor: &mut Cursor,
2062    store: &ChatStore,
2063) -> Vec<String> {
2064    let cmd = match store.cmds.get(desc.command.as_str()) {
2065        Ok(cmd) => cmd,
2066        Err(_) => return vec![],
2067    };
2068
2069    match cmd.name.as_str() {
2070        "cancel" | "dms" | "edit" | "redact" | "reply" => vec![],
2071        "members" | "rooms" | "spaces" | "welcome" => vec![],
2072        "download" | "keys" | "open" | "upload" => complete_path(text, cursor),
2073        "react" | "unreact" => complete_emoji(text, cursor, store),
2074
2075        "invite" => complete_users(text, cursor, store),
2076        "join" | "split" | "vsplit" | "tabedit" => complete_matrix_names(text, cursor, store),
2077        "room" => vec![],
2078        "verify" => vec![],
2079        "vertical" | "horizontal" | "aboveleft" | "belowright" | "tab" => {
2080            complete_cmd(desc.arg.text.as_str(), text, cursor, store)
2081        },
2082        _ => vec![],
2083    }
2084}
2085
2086/// Tab completion for commands.
2087fn complete_cmd(cmd: &str, text: &EditRope, cursor: &mut Cursor, store: &ChatStore) -> Vec<String> {
2088    match CommandDescription::from_str(cmd) {
2089        Ok(desc) => {
2090            if desc.arg.untrimmed.is_empty() {
2091                complete_cmdname(desc, text, cursor, store)
2092            } else {
2093                // Complete command argument.
2094                complete_cmdarg(desc, text, cursor, store)
2095            }
2096        },
2097
2098        // Can't parse command text, so return zero completions.
2099        Err(_) => vec![],
2100    }
2101}
2102
2103/// Tab completion for the command bar.
2104fn complete_cmdbar(text: &EditRope, cursor: &mut Cursor, store: &ChatStore) -> Vec<String> {
2105    let eo = text.cursor_to_offset(cursor);
2106    let slice = text.slice(..eo);
2107    let cow = Cow::from(&slice);
2108
2109    complete_cmd(cow.as_ref(), text, cursor, store)
2110}
2111
2112#[cfg(test)]
2113pub mod tests {
2114    use super::*;
2115    use crate::config::user_style_from_color;
2116    use crate::tests::*;
2117    use matrix_sdk::ruma::{
2118        events::{reaction::ReactionEventContent, relation::Annotation, MessageLikeUnsigned},
2119        owned_event_id,
2120        owned_room_id,
2121        owned_user_id,
2122        MilliSecondsSinceUnixEpoch,
2123    };
2124    use pretty_assertions::assert_eq;
2125    use ratatui::style::Color;
2126
2127    #[test]
2128    fn multiple_identical_reactions() {
2129        let mut info = RoomInfo::default();
2130
2131        let content = ReactionEventContent::new(Annotation::new(
2132            owned_event_id!("$my_reaction"),
2133            "🏠".to_owned(),
2134        ));
2135
2136        for i in 0..3 {
2137            let event_id = format!("$house_{}", i);
2138            info.insert_reaction(MessageLikeEvent::Original(
2139                matrix_sdk::ruma::events::OriginalMessageLikeEvent {
2140                    content: content.clone(),
2141                    event_id: OwnedEventId::from_str(&event_id).unwrap(),
2142                    sender: owned_user_id!("@foo:example.org"),
2143                    origin_server_ts: MilliSecondsSinceUnixEpoch::now(),
2144                    room_id: owned_room_id!("!foo:example.org"),
2145                    unsigned: MessageLikeUnsigned::new(),
2146                },
2147            ));
2148        }
2149
2150        let content = ReactionEventContent::new(Annotation::new(
2151            owned_event_id!("$my_reaction"),
2152            "🙂".to_owned(),
2153        ));
2154
2155        for i in 0..2 {
2156            let event_id = format!("$smile_{}", i);
2157            info.insert_reaction(MessageLikeEvent::Original(
2158                matrix_sdk::ruma::events::OriginalMessageLikeEvent {
2159                    content: content.clone(),
2160                    event_id: OwnedEventId::from_str(&event_id).unwrap(),
2161                    sender: owned_user_id!("@foo:example.org"),
2162                    origin_server_ts: MilliSecondsSinceUnixEpoch::now(),
2163                    room_id: owned_room_id!("!foo:example.org"),
2164                    unsigned: MessageLikeUnsigned::new(),
2165                },
2166            ));
2167        }
2168
2169        for i in 2..4 {
2170            let event_id = format!("$smile_{}", i);
2171            info.insert_reaction(MessageLikeEvent::Original(
2172                matrix_sdk::ruma::events::OriginalMessageLikeEvent {
2173                    content: content.clone(),
2174                    event_id: OwnedEventId::from_str(&event_id).unwrap(),
2175                    sender: owned_user_id!("@bar:example.org"),
2176                    origin_server_ts: MilliSecondsSinceUnixEpoch::now(),
2177                    room_id: owned_room_id!("!foo:example.org"),
2178                    unsigned: MessageLikeUnsigned::new(),
2179                },
2180            ));
2181        }
2182
2183        assert_eq!(info.get_reactions(&owned_event_id!("$my_reaction")), vec![
2184            ("🏠", 1),
2185            ("🙂", 2)
2186        ]);
2187    }
2188
2189    #[test]
2190    fn test_typing_spans() {
2191        let mut info = RoomInfo::default();
2192        let settings = mock_settings();
2193
2194        let users0 = vec![];
2195        let users1 = vec![TEST_USER1.clone()];
2196        let users2 = vec![TEST_USER1.clone(), TEST_USER2.clone()];
2197        let users4 = vec![
2198            TEST_USER1.clone(),
2199            TEST_USER2.clone(),
2200            TEST_USER3.clone(),
2201            TEST_USER4.clone(),
2202        ];
2203        let users5 = vec![
2204            TEST_USER1.clone(),
2205            TEST_USER2.clone(),
2206            TEST_USER3.clone(),
2207            TEST_USER4.clone(),
2208            TEST_USER5.clone(),
2209        ];
2210
2211        // Nothing set.
2212        assert_eq!(info.users_typing, None);
2213        assert_eq!(info.get_typing_spans(&settings), Line::from(vec![]));
2214
2215        // Empty typing list.
2216        info.set_typing(users0);
2217        assert!(info.users_typing.is_some());
2218        assert_eq!(info.get_typing_spans(&settings), Line::from(vec![]));
2219
2220        // Single user typing.
2221        info.set_typing(users1);
2222        assert!(info.users_typing.is_some());
2223        assert_eq!(
2224            info.get_typing_spans(&settings),
2225            Line::from(vec![
2226                Span::styled("@user1:example.com", user_style("@user1:example.com")),
2227                Span::from(" is typing...")
2228            ])
2229        );
2230
2231        // Two users typing.
2232        info.set_typing(users2);
2233        assert!(info.users_typing.is_some());
2234        assert_eq!(
2235            info.get_typing_spans(&settings),
2236            Line::from(vec![
2237                Span::styled("@user1:example.com", user_style("@user1:example.com")),
2238                Span::raw(" and "),
2239                Span::styled("@user2:example.com", user_style("@user2:example.com")),
2240                Span::raw(" are typing...")
2241            ])
2242        );
2243
2244        // Four users typing.
2245        info.set_typing(users4);
2246        assert!(info.users_typing.is_some());
2247        assert_eq!(info.get_typing_spans(&settings), Line::from("Several people are typing..."));
2248
2249        // Five users typing.
2250        info.set_typing(users5);
2251        assert!(info.users_typing.is_some());
2252        assert_eq!(info.get_typing_spans(&settings), Line::from("Many people are typing..."));
2253
2254        // Test that USER5 gets rendered using the configured color and name.
2255        info.set_typing(vec![TEST_USER5.clone()]);
2256        assert!(info.users_typing.is_some());
2257        assert_eq!(
2258            info.get_typing_spans(&settings),
2259            Line::from(vec![
2260                Span::styled("USER 5", user_style_from_color(Color::Black)),
2261                Span::from(" is typing...")
2262            ])
2263        );
2264    }
2265
2266    #[test]
2267    fn test_need_load() {
2268        let room_id = TEST_ROOM1_ID.clone();
2269
2270        let mut need_load = RoomNeeds::default();
2271
2272        need_load.insert(room_id.clone(), Need::MESSAGES);
2273        need_load.insert(room_id.clone(), Need::MEMBERS);
2274
2275        assert_eq!(need_load.into_iter().collect::<Vec<(OwnedRoomId, Need)>>(), vec![(
2276            room_id,
2277            Need::MESSAGES | Need::MEMBERS,
2278        )],);
2279    }
2280
2281    #[tokio::test]
2282    async fn test_complete_msgbar() {
2283        let store = mock_store().await;
2284        let store = store.application;
2285
2286        let text = EditRope::from("going for a walk :walk ");
2287        let mut cursor = Cursor::new(0, 22);
2288        let res = complete_msgbar(&text, &mut cursor, &store);
2289        assert_eq!(res, vec![":walking:", ":walking_man:", ":walking_woman:"]);
2290        assert_eq!(cursor, Cursor::new(0, 17));
2291
2292        let text = EditRope::from("hello @user1 ");
2293        let mut cursor = Cursor::new(0, 12);
2294        let res = complete_msgbar(&text, &mut cursor, &store);
2295        assert_eq!(res, vec!["@user1:example.com"]);
2296        assert_eq!(cursor, Cursor::new(0, 6));
2297
2298        let text = EditRope::from("see #room ");
2299        let mut cursor = Cursor::new(0, 9);
2300        let res = complete_msgbar(&text, &mut cursor, &store);
2301        assert_eq!(res, vec!["#room1:example.com"]);
2302        assert_eq!(cursor, Cursor::new(0, 4));
2303    }
2304
2305    #[tokio::test]
2306    async fn test_complete_cmdbar() {
2307        let store = mock_store().await;
2308        let store = store.application;
2309        let users = vec![
2310            "@user1:example.com",
2311            "@user2:example.com",
2312            "@user3:example.com",
2313            "@user4:example.com",
2314            "@user5:example.com",
2315        ];
2316
2317        let text = EditRope::from("invite    ");
2318        let mut cursor = Cursor::new(0, 7);
2319        let id = text
2320            .get_prefix_word_mut(&mut cursor, &MATRIX_ID_WORD)
2321            .unwrap_or_else(EditRope::empty);
2322        assert_eq!(id.to_string(), "");
2323        assert_eq!(cursor, Cursor::new(0, 7));
2324
2325        let text = EditRope::from("invite    ");
2326        let mut cursor = Cursor::new(0, 7);
2327        let res = complete_cmdbar(&text, &mut cursor, &store);
2328        assert_eq!(res, users);
2329
2330        let text = EditRope::from("invite ignored");
2331        let mut cursor = Cursor::new(0, 7);
2332        let res = complete_cmdbar(&text, &mut cursor, &store);
2333        assert_eq!(res, users);
2334
2335        let text = EditRope::from("invite @user1ignored");
2336        let mut cursor = Cursor::new(0, 13);
2337        let res = complete_cmdbar(&text, &mut cursor, &store);
2338        assert_eq!(res, vec!["@user1:example.com"]);
2339
2340        let text = EditRope::from("abo hor");
2341        let mut cursor = Cursor::new(0, 7);
2342        let res = complete_cmdbar(&text, &mut cursor, &store);
2343        assert_eq!(res, vec!["horizontal"]);
2344
2345        let text = EditRope::from("abo hor inv");
2346        let mut cursor = Cursor::new(0, 11);
2347        let res = complete_cmdbar(&text, &mut cursor, &store);
2348        assert_eq!(res, vec!["invite"]);
2349
2350        let text = EditRope::from("abo hor invite \n");
2351        let mut cursor = Cursor::new(0, 15);
2352        let res = complete_cmdbar(&text, &mut cursor, &store);
2353        assert_eq!(res, users);
2354    }
2355}