src/base.rs

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