src/base.rs

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