src/base.rs

2686 lines · 86923 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::{BTreeMap, 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
 707pub type MessageEdits = BTreeMap<MessageKey, RoomMessageEventContentWithoutRelation>;
 708
 709/// Errors encountered during application use.
 710#[derive(thiserror::Error, Debug)]
 711pub enum IambError {
 712    /// An invalid history visibility was specified.
 713    #[error("Invalid history visibility setting: {0}")]
 714    InvalidHistoryVisibility(String),
 715
 716    /// An invalid notification level was specified.
 717    #[error("Invalid notification level: {0}")]
 718    InvalidNotificationLevel(String),
 719
 720    /// An invalid user identifier was specified.
 721    #[error("Invalid user identifier: {0}")]
 722    InvalidUserId(String),
 723
 724    /// An invalid user identifier was specified.
 725    #[error("Invalid room alias: {0}")]
 726    InvalidRoomAlias(String),
 727
 728    /// An invalid verification identifier was specified.
 729    #[error("Invalid verification user/device pair: {0}")]
 730    InvalidVerificationId(String),
 731
 732    /// A failure related to the cryptographic store.
 733    #[error("Cryptographic storage error: {0}")]
 734    CryptoStore(#[from] matrix_sdk::encryption::CryptoStoreError),
 735
 736    #[error("Failed to import room keys: {0}")]
 737    FailedKeyImport(#[from] matrix_sdk::encryption::RoomKeyImportError),
 738
 739    /// A failure related to the cryptographic store.
 740    #[error("Cannot export keys from sled: {0}")]
 741    UpgradeSled(#[from] crate::sled_export::SledMigrationError),
 742
 743    /// An HTTP error.
 744    #[error("HTTP client error: {0}")]
 745    Http(#[from] matrix_sdk::HttpError),
 746
 747    /// A failure from the Matrix client.
 748    #[error("Matrix client error: {0}")]
 749    Matrix(#[from] matrix_sdk::Error),
 750
 751    /// A failure when sending a message.
 752    #[error("Send queue error: {0}")]
 753    SendQueue(#[from] matrix_sdk::send_queue::RoomSendQueueError),
 754
 755    /// A failure in the sled storage.
 756    #[error("Matrix client storage error: {0}")]
 757    Store(#[from] matrix_sdk::StoreError),
 758
 759    /// A failure during serialization or deserialization.
 760    #[error("Serialization/deserialization error: {0}")]
 761    Serde(#[from] serde_json::Error),
 762
 763    /// A failure due to not having a configured download directory.
 764    #[error("No download directory configured")]
 765    NoDownloadDir,
 766
 767    /// A failure due to not having a message with an attachment selected.
 768    #[error("Selected message does not have any attachments")]
 769    NoAttachment,
 770
 771    /// A failure due to not having a message selected.
 772    #[error("No message currently selected")]
 773    NoSelectedMessage,
 774
 775    /// A failure due to not having a room or space selected.
 776    #[error("Current window is not a room or space")]
 777    NoSelectedRoomOrSpace,
 778
 779    /// A failure due to not having a room or space item selected in a list.
 780    #[error("No room or space currently selected in list")]
 781    NoSelectedRoomOrSpaceItem,
 782
 783    /// A failure due to not having a room selected.
 784    #[error("Current window is not a room")]
 785    NoSelectedRoom,
 786
 787    /// A failure due to not having a space selected.
 788    #[error("Current window is not a space")]
 789    NoSelectedSpace,
 790
 791    /// A failure due to not having sufficient permission to perform an action in a room.
 792    #[error("You do not have the permission to do that")]
 793    InsufficientPermission,
 794
 795    /// A failure due to not having an outstanding room invitation.
 796    #[error("You do not have a current invitation to this room")]
 797    NotInvited,
 798
 799    /// A failure due to not being a joined room member.
 800    #[error("You need to join the room before you can do that")]
 801    NotJoined,
 802
 803    /// An unknown room was specified.
 804    #[error("Unknown room identifier: {0}")]
 805    UnknownRoom(OwnedRoomId),
 806
 807    /// An invalid room alias id was specified.
 808    #[error("Invalid room alias id: {0}")]
 809    InvalidRoomAliasId(#[from] matrix_sdk::ruma::IdParseError),
 810
 811    /// An invalid space child order was specified.
 812    #[error("Invalid space child order: {0}")]
 813    InvalidSpaceChildOrder(matrix_sdk::ruma::IdParseError),
 814
 815    /// A failure occurred during verification.
 816    #[error("Verification request error: {0}")]
 817    VerificationRequestError(#[from] matrix_sdk::encryption::identities::RequestVerificationError),
 818
 819    #[error("Notification setting error: {0}")]
 820    NotificationSettingError(#[from] matrix_sdk::NotificationSettingsError),
 821
 822    /// A failure related to images.
 823    #[error("Image error: {0}")]
 824    Image(#[from] image::ImageError),
 825
 826    /// A failure to access the system's clipboard.
 827    #[error("Could not use system clipboard data")]
 828    Clipboard,
 829
 830    /// An failure during disk/network/ipc/etc. I/O.
 831    #[error("Input/Output error: {0}")]
 832    IOError(#[from] std::io::Error),
 833
 834    /// A failure while trying to show an image preview.
 835    #[error("Preview error: {0}")]
 836    Preview(String),
 837}
 838
 839impl From<IambError> for UIError<IambInfo> {
 840    fn from(err: IambError) -> Self {
 841        UIError::Application(err)
 842    }
 843}
 844
 845impl ApplicationError for IambError {}
 846
 847/// Status for tracking how much room scrollback we've fetched.
 848#[derive(Default)]
 849pub enum RoomFetchStatus {
 850    /// Room history has been completely fetched.
 851    Done,
 852
 853    /// More room history can be fetched.
 854    HaveMore(String),
 855
 856    /// We have not yet started fetching history for this room.
 857    #[default]
 858    NotStarted,
 859}
 860
 861/// Indicates where an [EventId] lives in the [ChatStore].
 862#[derive(Clone)]
 863pub enum EventLocation {
 864    /// The [EventId] belongs to a message.
 865    ///
 866    /// If the first argument is [None], then it's part of the main scrollback. When [Some],
 867    /// it specifies which thread it's in reply to.
 868    Message(Option<OwnedEventId>, MessageKey),
 869
 870    /// The [EventId] belongs to a reaction to the given event.
 871    Reaction(OwnedEventId),
 872
 873    /// The [EventId] belongs to a state event in the main timeline of the room.
 874    State(MessageKey),
 875
 876    /// The [EventId] belongs to a sticker event in the main scrollback
 877    Sticker(MessageKey),
 878
 879    /// The [EventId] belongs to an edit for the given event and has key [MessageKey].
 880    Edit(OwnedEventId, MessageKey),
 881}
 882
 883impl EventLocation {
 884    fn to_message_key(&self) -> Option<&MessageKey> {
 885        match self {
 886            EventLocation::Message(_, key) => Some(key),
 887            EventLocation::Sticker(key) => Some(key),
 888            _ => None,
 889        }
 890    }
 891}
 892
 893/// Indicates where a local echo lives in the [`ChatStore`].
 894#[derive(Debug, Clone)]
 895pub enum EchoLocation {
 896    /// The [`OwnedTransactionId`] belongs to a message.
 897    ///
 898    /// If the first argument is [`None`], then it's part of the main scrollback. When [`Some`], it
 899    /// specifies which thread it's in reply to.
 900    Message(Option<OwnedEventId>, MessageKey),
 901
 902    /// The local echo has been replaced by an event with this event id.
 903    Replaced(OwnedEventId),
 904}
 905
 906#[derive(Clone, Debug, Default, Eq, PartialEq)]
 907pub struct UnreadInfo {
 908    pub(crate) unread_mark: bool,
 909    pub(crate) unread_messages: u64,
 910    pub(crate) unread_notifications: u64,
 911    pub(crate) unread_mentions: u64,
 912    pub(crate) latest: Option<MessageTimeStamp>,
 913}
 914
 915impl UnreadInfo {
 916    pub fn is_unread(&self) -> bool {
 917        self.unread_mark || self.unread_notifications > 0 || self.unread_mentions > 0
 918    }
 919
 920    pub fn has_mention(&self) -> bool {
 921        self.unread_mentions > 0
 922    }
 923
 924    pub fn latest(&self) -> Option<&MessageTimeStamp> {
 925        self.latest.as_ref()
 926    }
 927}
 928
 929/// Track the display names for users and render any needed disambiguation for
 930/// those with overlapping names.
 931#[derive(Default)]
 932pub struct DisplayNameStore {
 933    by_ids: HashMap<OwnedUserId, String>,
 934    by_names: HashMap<String, HashSet<OwnedUserId>>,
 935}
 936
 937impl DisplayNameStore {
 938    /// Update the `HashSet` associated with a given displayname.
 939    ///
 940    /// Note that this *could* be done more elegantly using the Entry API, but
 941    /// is intentionally written in a way to avoid cloning conflicting display
 942    /// names.
 943    fn set_by_name(&mut self, user_id: OwnedUserId, name: &str) {
 944        if let Some(existing) = self.by_names.get_mut(name) {
 945            existing.insert(user_id);
 946        } else {
 947            self.by_names.insert(name.to_owned(), HashSet::from([user_id]));
 948        }
 949    }
 950
 951    /// Track a new user ID to displayname mapping, or unset any existing ones.
 952    pub fn set(&mut self, user_id: OwnedUserId, name: Option<String>) {
 953        if let Some(name) = name.as_deref() {
 954            self.set_by_name(user_id.clone(), name);
 955        }
 956
 957        let previous = match (self.by_ids.entry(user_id), name) {
 958            // Nothing to do!
 959            (Entry::Vacant(_), None) => None,
 960
 961            // Setting initial display name for user:
 962            (Entry::Vacant(v), Some(name)) => {
 963                v.insert(name);
 964                None
 965            },
 966
 967            // Unsetting display name:
 968            (Entry::Occupied(o), None) => Some(o.remove_entry()),
 969
 970            // Replacing existing name:
 971            (Entry::Occupied(mut o), Some(name)) => {
 972                if o.get() == &name {
 973                    None
 974                } else {
 975                    Some((o.key().clone(), o.insert(name)))
 976                }
 977            },
 978        };
 979
 980        let Some((user_id, previous)) = previous else {
 981            return;
 982        };
 983
 984        let Some(users) = self.by_names.get_mut(&previous) else {
 985            return;
 986        };
 987
 988        users.remove(&user_id);
 989
 990        if users.is_empty() {
 991            self.by_names.remove(&previous);
 992        }
 993    }
 994
 995    pub fn get<'a>(&'a self, user_id: &UserId) -> Option<Cow<'a, str>> {
 996        let displayname = self.by_ids.get(user_id)?;
 997        let users = self.by_names.get(displayname)?;
 998
 999        if !users.contains(user_id) {
1000            // Internal consistency error? Assume no display name:
1001            return None;
1002        }
1003
1004        if users.len() == 1 {
1005            // Unambiguous!
1006            return Some(Cow::Borrowed(displayname.as_str()));
1007        }
1008
1009        // Ambiguous username, so include unique user ID:
1010        Some(Cow::Owned(format!("{displayname} ({user_id})")))
1011    }
1012}
1013
1014/// Information about room's the user's joined.
1015pub struct RoomInfo {
1016    /// The display name for this room.
1017    pub name: Option<String>,
1018
1019    /// The tags placed on this room.
1020    pub tags: Option<Tags>,
1021
1022    /// A map of event IDs to where they are stored in this struct.
1023    pub keys: HashMap<OwnedEventId, EventLocation>,
1024    pub echo_keys: HashMap<OwnedTransactionId, EchoLocation>,
1025
1026    /// The messages loaded for this room.
1027    messages: Messages,
1028
1029    /// A map of read markers to display on different events.
1030    pub event_receipts: HashMap<ReceiptThread, HashMap<OwnedEventId, HashSet<OwnedUserId>>>,
1031    /// A map of the most recent read marker for each user.
1032    ///
1033    /// Every receipt in this map should also have an entry in [`event_receipts`](`Self::event_receipts`),
1034    /// however not every user has an entry. If a user's most recent receipt is
1035    /// older than the oldest loaded event, that user will not be included.
1036    pub user_receipts: HashMap<ReceiptThread, HashMap<OwnedUserId, OwnedEventId>>,
1037    /// A map of message identifiers to a map of reaction events.
1038    pub reactions: HashMap<OwnedEventId, MessageReactions>,
1039    /// A map of message identifiers to a list of edit events for message that are not yet cached.
1040    pub unloaded_edits: HashMap<OwnedEventId, MessageEdits>,
1041
1042    /// A map of message identifiers to thread replies.
1043    threads: HashMap<OwnedEventId, Messages>,
1044
1045    /// Whether the scrollback for this room is currently being fetched.
1046    pub fetching: bool,
1047
1048    /// Where to continue fetching from when we continue loading scrollback history.
1049    pub fetch_id: RoomFetchStatus,
1050
1051    /// The time that we last fetched scrollback for this room.
1052    pub fetch_last: Option<Instant>,
1053
1054    /// Users currently typing in this room, and when we received notification of them doing so.
1055    pub users_typing: Option<(Instant, Vec<OwnedUserId>)>,
1056
1057    /// The display names for users in this room.
1058    pub display_names: DisplayNameStore,
1059
1060    /// The last time the room was rendered, used to detect if it is currently open.
1061    pub draw_last: Option<Instant>,
1062}
1063
1064impl Default for RoomInfo {
1065    fn default() -> Self {
1066        Self {
1067            messages: Messages::new(ReceiptThread::Main),
1068
1069            name: Default::default(),
1070            tags: Default::default(),
1071            keys: Default::default(),
1072            echo_keys: Default::default(),
1073            event_receipts: Default::default(),
1074            user_receipts: Default::default(),
1075            reactions: Default::default(),
1076            threads: Default::default(),
1077            fetching: Default::default(),
1078            fetch_id: Default::default(),
1079            fetch_last: Default::default(),
1080            users_typing: Default::default(),
1081            display_names: Default::default(),
1082            draw_last: Default::default(),
1083            unloaded_edits: Default::default(),
1084        }
1085    }
1086}
1087
1088impl RoomInfo {
1089    pub fn get_thread(&self, root: Option<&EventId>) -> Option<&Messages> {
1090        if let Some(thread_root) = root {
1091            self.threads.get(thread_root)
1092        } else {
1093            Some(&self.messages)
1094        }
1095    }
1096
1097    pub fn get_thread_mut(&mut self, root: Option<OwnedEventId>) -> &mut Messages {
1098        if let Some(thread_root) = root {
1099            self.threads
1100                .entry(thread_root.clone())
1101                .or_insert_with(|| Messages::thread(thread_root))
1102        } else {
1103            &mut self.messages
1104        }
1105    }
1106
1107    /// Get the event for the last message in a thread (or the thread root if there are no
1108    /// in-thread replies yet).
1109    ///
1110    /// This does not apply edits to the returned event.
1111    ///
1112    /// This returns `None` if the event identifier isn't in the room.
1113    pub fn get_thread_last<'a>(
1114        &'a self,
1115        thread_root: &OwnedEventId,
1116    ) -> Option<&'a OriginalRoomMessageEvent> {
1117        let last = self.threads.get(thread_root).and_then(|t| Some(t.last_key_value()?.1));
1118
1119        let msg = if let Some(last) = last {
1120            &last.event
1121        } else if let EventLocation::Message(_, key) = self.keys.get(thread_root)? {
1122            let msg = self.messages.get(key)?;
1123            &msg.event
1124        } else {
1125            return None;
1126        };
1127
1128        if let MessageEvent::Original(ev, _) = &msg {
1129            Some(ev)
1130        } else {
1131            None
1132        }
1133    }
1134
1135    /// Get the reactions and their counts for a message.
1136    pub fn get_reactions(&self, event_id: &EventId) -> Vec<(&str, usize)> {
1137        if let Some(reacts) = self.reactions.get(event_id) {
1138            let mut counts = HashMap::new();
1139
1140            let mut seen_user_reactions = BTreeSet::new();
1141
1142            for (key, user) in reacts.values() {
1143                if !seen_user_reactions.contains(&(key, user)) {
1144                    seen_user_reactions.insert((key, user));
1145                    let count = counts.entry(key.as_str()).or_default();
1146                    *count += 1;
1147                }
1148            }
1149
1150            let mut reactions = counts.into_iter().collect::<Vec<_>>();
1151            reactions.sort();
1152
1153            reactions
1154        } else {
1155            vec![]
1156        }
1157    }
1158
1159    /// Map an event identifier to its [MessageKey].
1160    pub fn get_message_key(&self, event_id: &EventId) -> Option<&MessageKey> {
1161        self.keys.get(event_id)?.to_message_key()
1162    }
1163
1164    /// Get an event for an identifier.
1165    pub fn get_event(&self, event_id: &EventId) -> Option<&Message> {
1166        self.messages.get(self.get_message_key(event_id)?)
1167    }
1168
1169    /// Get an event for an identifier as mutable.
1170    pub fn get_event_mut(&mut self, event_id: &EventId) -> Option<&mut Message> {
1171        self.messages.get_mut(self.keys.get(event_id)?.to_message_key()?)
1172    }
1173
1174    pub fn redact(&mut self, ev: OriginalSyncRoomRedactionEvent) {
1175        let Some(redacts) = &ev.redacts else {
1176            return;
1177        };
1178
1179        match self.keys.get(redacts) {
1180            None => return,
1181            Some(EventLocation::Edit(msg_event_id, edit_key)) => {
1182                let edit_key = edit_key.clone();
1183                let msg_loc = self.keys.get(msg_event_id).cloned();
1184                if let Some(EventLocation::Message(thread, msg_key)) = msg_loc {
1185                    if let Some(msg) = self.get_thread_mut(thread).get_mut(&msg_key) {
1186                        msg.remove_edit(&edit_key);
1187                    }
1188                } else {
1189                    self.unloaded_edits
1190                        .get_mut(msg_event_id)
1191                        .and_then(|edits| edits.remove(&edit_key));
1192                }
1193
1194                if let Some(msg) = self.messages.get_mut(&edit_key) {
1195                    let ev = SyncRoomRedactionEvent::Original(ev);
1196                    msg.redact(ev);
1197                }
1198            },
1199            Some(EventLocation::State(key)) => {
1200                if let Some(msg) = self.messages.get_mut(key) {
1201                    let ev = SyncRoomRedactionEvent::Original(ev);
1202                    msg.redact(ev);
1203                }
1204            },
1205            Some(EventLocation::Message(None, key)) => {
1206                if let Some(msg) = self.messages.get_mut(key) {
1207                    let ev = SyncRoomRedactionEvent::Original(ev);
1208                    msg.redact(ev);
1209                }
1210            },
1211            Some(EventLocation::Message(Some(root), key)) => {
1212                if let Some(thread) = self.threads.get_mut(root) &&
1213                    let Some(msg) = thread.get_mut(key)
1214                {
1215                    let ev = SyncRoomRedactionEvent::Original(ev);
1216                    msg.redact(ev);
1217                }
1218            },
1219            Some(EventLocation::Reaction(event_id)) => {
1220                if let Some(reactions) = self.reactions.get_mut(event_id) {
1221                    reactions.remove(redacts);
1222                }
1223
1224                self.keys.remove(redacts);
1225            },
1226            Some(EventLocation::Sticker(key)) => {
1227                if let Some(msg) = self.messages.get_mut(key) {
1228                    let ev = SyncRoomRedactionEvent::Original(ev);
1229                    msg.redact(ev);
1230                }
1231            },
1232        }
1233    }
1234
1235    /// Insert a reaction to a message.
1236    pub fn insert_reaction(&mut self, react: ReactionEvent) {
1237        match react {
1238            MessageLikeEvent::Original(react) => {
1239                let rel_id = react.content.relates_to.event_id;
1240                let key = react.content.relates_to.key;
1241
1242                let message = self.reactions.entry(rel_id.clone()).or_default();
1243                let event_id = react.event_id;
1244                let user_id = react.sender;
1245
1246                message.insert(event_id.clone(), (key, user_id));
1247
1248                let loc = EventLocation::Reaction(rel_id);
1249                self.keys.insert(event_id, loc);
1250            },
1251            MessageLikeEvent::Redacted(_) => {
1252                return;
1253            },
1254        }
1255    }
1256
1257    /// Insert a sticker
1258    pub fn insert_sticker(
1259        &mut self,
1260        sticker: StickerEvent,
1261        settings: &ApplicationSettings,
1262        previews: &mut PreviewManager,
1263        worker: &Requester,
1264    ) {
1265        match sticker {
1266            MessageLikeEvent::Original(ref sticker_content) => {
1267                let key = MessageKey {
1268                    ts: sticker_content.origin_server_ts.into(),
1269                    id: sticker_content.event_id.clone().into(),
1270                };
1271
1272                let loc = EventLocation::Sticker(key.clone());
1273
1274                self.keys.insert(sticker_content.event_id.clone(), loc);
1275                self.messages.insert_message(key.clone(), sticker.clone());
1276
1277                if let (Some(msg), Some(image_preview)) = (
1278                    self.get_event_mut(&sticker_content.event_id),
1279                    &settings.tunables.image_preview,
1280                ) {
1281                    let source: MediaSource = sticker_content.content.source.clone().into();
1282                    msg.image_preview = Some(source.clone());
1283                    previews.register_preview(settings, source, image_preview.size, worker);
1284                }
1285            },
1286            MessageLikeEvent::Redacted(ref redaction) => {
1287                let key = MessageKey {
1288                    ts: redaction.origin_server_ts.into(),
1289                    id: redaction.event_id.clone().into(),
1290                };
1291
1292                self.messages.insert_message(key.clone(), sticker.clone());
1293            },
1294        }
1295    }
1296
1297    /// Insert an edit.
1298    fn insert_edit(
1299        &mut self,
1300        edit_msg: RoomMessageEvent,
1301        replacement: Replacement<RoomMessageEventContentWithoutRelation>,
1302    ) {
1303        let RoomMessageEvent::Original(edit_msg) = edit_msg else {
1304            return;
1305        };
1306        let edit_key = MessageKey {
1307            ts: edit_msg.origin_server_ts.into(),
1308            id: edit_msg.event_id.clone().into(),
1309        };
1310        let msg_loc = self.keys.get(&replacement.event_id).cloned();
1311
1312        if let Some(EventLocation::Message(thread, key)) = msg_loc {
1313            // The edited message is already loaded in cache
1314            let Some(msg) = self.get_thread_mut(thread).get_mut(&key) else {
1315                return;
1316            };
1317            msg.insert_edit(edit_key.clone(), replacement.new_content);
1318        } else {
1319            // The edited message is not yet loaded
1320            let entry = self.unloaded_edits.entry(replacement.event_id.clone());
1321            entry.or_default().insert(edit_key.clone(), replacement.new_content);
1322        }
1323
1324        let loc = EventLocation::Edit(replacement.event_id.clone(), edit_key.clone());
1325        self.keys.insert(edit_msg.event_id.clone(), loc);
1326    }
1327
1328    pub fn insert_any_state(&mut self, msg: AnySyncStateEvent) {
1329        let event_id = msg.event_id().to_owned();
1330        let key = MessageKey {
1331            ts: msg.origin_server_ts().into(),
1332            id: event_id.clone().into(),
1333        };
1334
1335        let loc = EventLocation::State(key.clone());
1336        self.keys.insert(event_id, loc);
1337        self.messages.insert_message(key, msg);
1338    }
1339
1340    /// Indicates whether this room has unread messages.
1341    pub fn unreads(&self, room: &matrix_sdk::Room) -> UnreadInfo {
1342        let last_message = self
1343            .messages
1344            .iter()
1345            .rev()
1346            .find(|(_, msg)| !matches!(&msg.event, MessageEvent::State(..)));
1347
1348        UnreadInfo {
1349            unread_mark: room.is_marked_unread(),
1350            unread_messages: room.num_unread_messages(),
1351            unread_notifications: room.num_unread_notifications(),
1352            unread_mentions: room.num_unread_mentions(),
1353            latest: last_message.map(|(key, _)| key.ts.to_owned()),
1354        }
1355    }
1356
1357    /// Inserts events that couldn't be decrypted into the scrollback.
1358    pub fn insert_encrypted(&mut self, msg: RoomEncryptedEvent) {
1359        let event_id = msg.event_id().to_owned();
1360        let key = MessageKey {
1361            ts: msg.origin_server_ts().into(),
1362            id: event_id.clone().into(),
1363        };
1364
1365        self.keys.insert(event_id, EventLocation::Message(None, key.clone()));
1366        self.messages.insert(key, msg.into());
1367    }
1368
1369    /// Insert a new message.
1370    pub fn insert_message(&mut self, msg: RoomMessageEvent) {
1371        let event_id = msg.event_id().to_owned();
1372        let key = MessageKey {
1373            ts: msg.origin_server_ts().into(),
1374            id: event_id.clone().into(),
1375        };
1376
1377        let loc = EventLocation::Message(None, key.clone());
1378        let mut message: Message = msg.into();
1379        if let Some(edits) = self.unloaded_edits.remove(&event_id) {
1380            message.set_edits(edits);
1381        }
1382        self.keys.insert(event_id, loc);
1383        self.messages.insert_message(key, message);
1384    }
1385
1386    fn insert_thread(&mut self, msg: RoomMessageEvent, thread_root: OwnedEventId) {
1387        let event_id = msg.event_id().to_owned();
1388        let key = MessageKey {
1389            ts: msg.origin_server_ts().into(),
1390            id: event_id.clone().into(),
1391        };
1392
1393        let replies = self
1394            .threads
1395            .entry(thread_root.clone())
1396            .or_insert_with(|| Messages::thread(thread_root.clone()));
1397        let loc = EventLocation::Message(Some(thread_root), key.clone());
1398        let mut message: Message = msg.into();
1399        if let Some(edits) = self.unloaded_edits.remove(&event_id) {
1400            message.set_edits(edits);
1401        }
1402        self.keys.insert(event_id, loc);
1403        replies.insert_message(key, message);
1404    }
1405
1406    /// Insert a new message event.
1407    pub fn insert(&mut self, msg: RoomMessageEvent) {
1408        match msg {
1409            RoomMessageEvent::Original(OriginalRoomMessageEvent {
1410                content: RoomMessageEventContent { relates_to: Some(ref relates_to), .. },
1411                ..
1412            }) => {
1413                match relates_to {
1414                    Relation::Replacement(repl) => {
1415                        let repl = repl.clone();
1416                        self.insert_edit(msg, repl)
1417                    },
1418                    Relation::Thread(Thread { event_id, .. }) => {
1419                        let event_id = event_id.clone();
1420                        self.insert_thread(msg, event_id);
1421                    },
1422                    Relation::Reply { .. } => self.insert_message(msg),
1423                    _ => self.insert_message(msg),
1424                }
1425            },
1426            _ => self.insert_message(msg),
1427        }
1428    }
1429
1430    /// Insert a new message event, and prepare for image-preview if it has an image attachment.
1431    pub fn insert_with_preview(
1432        &mut self,
1433        ev: RoomMessageEvent,
1434        settings: &ApplicationSettings,
1435        previews: &mut PreviewManager,
1436        worker: &Requester,
1437    ) {
1438        let source = source_from_event(&ev);
1439        self.insert(ev);
1440
1441        if let Some((event_id, source)) = source &&
1442            let (Some(msg), Some(image_preview)) =
1443                (self.get_event_mut(&event_id), &settings.tunables.image_preview)
1444        {
1445            msg.image_preview = Some(source.clone());
1446            previews.register_preview(settings, source, image_preview.size, worker)
1447        }
1448    }
1449
1450    /// Indicates whether we've recently fetched scrollback for this room.
1451    pub fn recently_fetched(&self) -> bool {
1452        self.fetch_last.is_some_and(|i| i.elapsed() < ROOM_FETCH_DEBOUNCE)
1453    }
1454
1455    fn clear_receipt(&mut self, thread: &ReceiptThread, user_id: &OwnedUserId) -> Option<()> {
1456        let old_event_id =
1457            self.user_receipts.get(thread).and_then(|receipts| receipts.get(user_id))?;
1458        let old_thread = self.event_receipts.get_mut(thread)?;
1459        let old_receipts = old_thread.get_mut(old_event_id)?;
1460        old_receipts.remove(user_id);
1461
1462        if old_receipts.is_empty() {
1463            old_thread.remove(old_event_id);
1464        }
1465        if old_thread.is_empty() {
1466            self.event_receipts.remove(thread);
1467        }
1468
1469        None
1470    }
1471
1472    pub fn set_receipt(
1473        &mut self,
1474        thread: ReceiptThread,
1475        user_id: OwnedUserId,
1476        event_id: OwnedEventId,
1477    ) {
1478        self.clear_receipt(&thread, &user_id);
1479        self.event_receipts
1480            .entry(thread.clone())
1481            .or_default()
1482            .entry(event_id.clone())
1483            .or_default()
1484            .insert(user_id.clone());
1485        self.user_receipts.entry(thread).or_default().insert(user_id, event_id);
1486    }
1487
1488    pub fn fully_read(&mut self, user_id: OwnedUserId, thread: ReceiptThread) {
1489        let messages = match &thread {
1490            ReceiptThread::Main => self.get_thread(None),
1491            ReceiptThread::Thread(root) => self.get_thread(Some(root)),
1492            _ => None,
1493        };
1494
1495        let Some(messages) = messages else {
1496            return;
1497        };
1498
1499        let event_id = messages
1500            .iter()
1501            .filter(|(_, msg)| msg.sender != user_id)
1502            .filter(|(_, msg)| {
1503                matches!(
1504                    msg.event,
1505                    MessageEvent::EncryptedOriginal(..) |
1506                        MessageEvent::EncryptedRedacted(..) |
1507                        MessageEvent::Original(..) |
1508                        MessageEvent::Redacted(..)
1509                )
1510            })
1511            .flat_map(|(_, msg)| msg.event.event_id())
1512            .next_back();
1513
1514        if let Some(event_id) = event_id {
1515            self.set_receipt(thread, user_id, event_id.to_owned());
1516        }
1517    }
1518
1519    pub fn fully_read_all(&mut self, user_id: &UserId) {
1520        self.fully_read(user_id.to_owned(), ReceiptThread::Main);
1521
1522        let threads: Vec<_> = self.threads.keys().map(|root| root.to_owned()).collect();
1523
1524        for thread in threads {
1525            self.fully_read(user_id.to_owned(), ReceiptThread::Thread(thread));
1526        }
1527    }
1528
1529    pub fn receipts<'a>(
1530        &'a self,
1531        user_id: &'a UserId,
1532    ) -> impl Iterator<Item = (&'a ReceiptThread, &'a OwnedEventId)> + 'a {
1533        self.user_receipts
1534            .iter()
1535            .filter_map(move |(t, rs)| rs.get(user_id).map(|r| (t, r)))
1536    }
1537
1538    fn get_typers(&self) -> &[OwnedUserId] {
1539        if let Some((t, users)) = &self.users_typing {
1540            if t.elapsed() < Duration::from_secs(4) {
1541                return users.as_ref();
1542            } else {
1543                return &[];
1544            }
1545        } else {
1546            return &[];
1547        }
1548    }
1549
1550    fn get_typing_spans<'a>(&'a self, settings: &'a ApplicationSettings) -> Line<'a> {
1551        let typers = self.get_typers();
1552        let n = typers.len();
1553
1554        match n {
1555            0 => Line::from(vec![]),
1556            1 => {
1557                let user = settings.get_user_span(typers[0].as_ref(), self);
1558
1559                Line::from(vec![user, Span::from(" is typing...")])
1560            },
1561            2 => {
1562                let user1 = settings.get_user_span(typers[0].as_ref(), self);
1563                let user2 = settings.get_user_span(typers[1].as_ref(), self);
1564
1565                Line::from(vec![
1566                    user1,
1567                    Span::raw(" and "),
1568                    user2,
1569                    Span::from(" are typing..."),
1570                ])
1571            },
1572            n if n < 5 => Line::from("Several people are typing..."),
1573            _ => Line::from("Many people are typing..."),
1574        }
1575    }
1576
1577    /// Update typing information for this room.
1578    pub fn set_typing(&mut self, user_ids: Vec<OwnedUserId>) {
1579        self.users_typing = (Instant::now(), user_ids).into();
1580    }
1581
1582    /// Create a [Rect] that displays what users are typing.
1583    pub fn render_typing(
1584        &mut self,
1585        area: Rect,
1586        buf: &mut Buffer,
1587        settings: &ApplicationSettings,
1588    ) -> Rect {
1589        if area.height <= 2 || area.width <= 20 {
1590            return area;
1591        }
1592
1593        if !settings.tunables.typing_notice_display {
1594            // still keep one line blank, so `render_jump_to_recent` doesn't immediately hide the
1595            // last line in scrollback
1596            return Rect::new(area.x, area.y, area.width, area.height - 1);
1597        }
1598
1599        let top = Rect::new(area.x, area.y, area.width, area.height - 1);
1600        let bar = Rect::new(area.x, area.y + top.height, area.width, 1);
1601
1602        Paragraph::new(self.get_typing_spans(settings))
1603            .alignment(Alignment::Center)
1604            .render(bar, buf);
1605
1606        return top;
1607    }
1608
1609    /// Checks if a given user has reacted with the given emoji on the given event
1610    pub fn user_reactions_contains(
1611        &mut self,
1612        user_id: &UserId,
1613        event_id: &EventId,
1614        emoji: &str,
1615    ) -> bool {
1616        if let Some(reactions) = self.reactions.get(event_id) {
1617            reactions
1618                .values()
1619                .any(|(annotation, user)| annotation == emoji && user == user_id)
1620        } else {
1621            false
1622        }
1623    }
1624}
1625
1626/// Generate a [CompletionMap] for Emoji shortcodes.
1627fn emoji_map() -> CompletionMap<String, &'static Emoji> {
1628    let mut emojis = CompletionMap::default();
1629
1630    for emoji in emojis::iter() {
1631        for shortcode in emoji.shortcodes() {
1632            emojis.insert(shortcode.to_string(), emoji);
1633        }
1634    }
1635
1636    return emojis;
1637}
1638
1639#[cfg(unix)]
1640fn picker_from_termios(protocol_type: Option<ProtocolType>) -> Option<Picker> {
1641    let mut picker = match Picker::from_query_stdio() {
1642        Ok(picker) => picker,
1643        Err(e) => {
1644            tracing::error!("Failed to setup image previews: {e}");
1645            return None;
1646        },
1647    };
1648
1649    if let Some(protocol_type) = protocol_type {
1650        picker.set_protocol_type(protocol_type);
1651    }
1652
1653    Some(picker)
1654}
1655
1656/// Windows cannot guess the right protocol, and always needs type and font_size.
1657#[cfg(windows)]
1658fn picker_from_termios(_: Option<ProtocolType>) -> Option<Picker> {
1659    tracing::error!(
1660        "\"image_preview\" requires \"protocol\" with \"type\" and \"font_size\" options on Windows."
1661    );
1662    None
1663}
1664
1665fn picker_from_settings(settings: &ApplicationSettings) -> Option<Picker> {
1666    let image_preview = settings.tunables.image_preview.as_ref()?;
1667    let image_preview_protocol = image_preview.protocol.as_ref();
1668
1669    if let Some(&ImagePreviewProtocolValues {
1670        r#type: Some(protocol_type),
1671        font_size: Some(font_size),
1672    }) = image_preview_protocol
1673    {
1674        // User forced type and font_size: use that.
1675        let mut picker = Picker::from_fontsize(font_size);
1676        picker.set_protocol_type(protocol_type);
1677        Some(picker)
1678    } else {
1679        // Guess, but use type if forced.
1680        picker_from_termios(image_preview_protocol.and_then(|p| p.r#type))
1681    }
1682}
1683
1684/// Information gathered during server syncs about joined rooms.
1685#[derive(Default)]
1686pub struct SyncInfo {
1687    /// Spaces that the user is a member of.
1688    pub spaces: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
1689
1690    /// Rooms that the user is a member of.
1691    pub rooms: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
1692
1693    /// DMs that the user is a member of.
1694    pub dms: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
1695}
1696
1697impl SyncInfo {
1698    pub fn rooms(&self) -> impl Iterator<Item = &RoomId> {
1699        self.rooms.iter().map(|r| r.0.room_id())
1700    }
1701
1702    pub fn dms(&self) -> impl Iterator<Item = &RoomId> {
1703        self.dms.iter().map(|r| r.0.room_id())
1704    }
1705
1706    pub fn chats(&self) -> impl Iterator<Item = &RoomId> {
1707        self.rooms().chain(self.dms())
1708    }
1709}
1710
1711static MESSAGE_NEED_TTL: u8 = 30;
1712
1713#[derive(Debug, PartialEq)]
1714/// Load messages until the event is loaded or `ttl` loads are exceeded
1715pub struct MessageNeed {
1716    pub event_id: OwnedEventId,
1717    pub ttl: u8,
1718}
1719
1720#[derive(Default, Debug, PartialEq)]
1721pub struct Need {
1722    pub members: bool,
1723    pub messages: Option<Vec<MessageNeed>>,
1724}
1725
1726/// Things that need loading for different rooms.
1727#[derive(Default)]
1728pub struct RoomNeeds {
1729    needs: HashMap<OwnedRoomId, Need>,
1730}
1731
1732impl RoomNeeds {
1733    /// Mark a room for needing to load members.
1734    pub fn need_members(&mut self, room_id: OwnedRoomId) {
1735        self.needs.entry(room_id).or_default().members = true;
1736    }
1737
1738    /// Mark a room for needing to load messages.
1739    pub fn need_messages(&mut self, room_id: OwnedRoomId) {
1740        self.needs.entry(room_id).or_default().messages.get_or_insert_default();
1741    }
1742
1743    /// Mark a room for needing to load messages until the given message is loaded or a retry limit
1744    /// is exceeded.
1745    pub fn need_message(&mut self, room_id: OwnedRoomId, event_id: OwnedEventId) {
1746        let messages = &mut self.needs.entry(room_id).or_default().messages.get_or_insert_default();
1747
1748        messages.push(MessageNeed { event_id, ttl: MESSAGE_NEED_TTL });
1749    }
1750
1751    pub fn need_messages_all(&mut self, room_id: OwnedRoomId, message_needs: Vec<MessageNeed>) {
1752        self.needs
1753            .entry(room_id)
1754            .or_default()
1755            .messages
1756            .get_or_insert_default()
1757            .extend(message_needs);
1758    }
1759
1760    pub fn rooms(&self) -> usize {
1761        self.needs.len()
1762    }
1763}
1764
1765impl IntoIterator for RoomNeeds {
1766    type Item = (OwnedRoomId, Need);
1767    type IntoIter = IntoIter<OwnedRoomId, Need>;
1768
1769    fn into_iter(self) -> Self::IntoIter {
1770        self.needs.into_iter()
1771    }
1772}
1773
1774/// The main application state.
1775pub struct ChatStore {
1776    /// `:`-commands
1777    pub cmds: ProgramCommands,
1778
1779    /// Handle for communicating w/ the worker thread.
1780    pub worker: Requester,
1781
1782    /// Map of joined rooms.
1783    pub rooms: CompletionMap<OwnedRoomId, RoomInfo>,
1784
1785    /// Map of room names.
1786    pub names: CompletionMap<String, OwnedRoomId>,
1787
1788    /// Presence information for other users.
1789    pub presences: CompletionMap<OwnedUserId, PresenceState>,
1790
1791    /// In-progress and completed verifications.
1792    pub verifications: HashMap<String, SasVerification>,
1793
1794    /// Settings for the current profile loaded from config file.
1795    pub settings: ApplicationSettings,
1796
1797    /// Set of rooms that need more messages loaded in their scrollback.
1798    pub need_load: RoomNeeds,
1799
1800    /// [CompletionMap] of Emoji shortcodes.
1801    pub emojis: CompletionMap<String, &'static Emoji>,
1802
1803    /// Information gathered by the background thread.
1804    pub sync_info: SyncInfo,
1805
1806    /// Rendered image previews.
1807    pub previews: PreviewManager,
1808
1809    /// Last draw time, used to match with RoomInfo's draw_last.
1810    pub draw_curr: Option<Instant>,
1811
1812    /// Whether to ring the terminal bell on the next redraw.
1813    pub ring_bell: bool,
1814
1815    /// Whether the application is currently focused
1816    pub focused: bool,
1817
1818    /// Collator for locale-aware text sorting.
1819    pub collator: feruca::Collator,
1820
1821    /// Notifications that should be dismissed when the user opens the room.
1822    pub open_notifications: HashMap<OwnedRoomId, Vec<NotificationHandle>>,
1823}
1824
1825impl ChatStore {
1826    /// Create a new [ChatStore].
1827    pub fn new(worker: Requester, settings: ApplicationSettings) -> Self {
1828        let picker = picker_from_settings(&settings);
1829
1830        ChatStore {
1831            worker,
1832            settings,
1833            previews: PreviewManager::new(picker),
1834            cmds: crate::commands::setup_commands(),
1835            emojis: emoji_map(),
1836
1837            collator: Default::default(),
1838            names: Default::default(),
1839            rooms: Default::default(),
1840            presences: Default::default(),
1841            verifications: Default::default(),
1842            need_load: Default::default(),
1843            sync_info: Default::default(),
1844            draw_curr: None,
1845            ring_bell: false,
1846            focused: true,
1847            open_notifications: Default::default(),
1848        }
1849    }
1850
1851    /// Get a joined room.
1852    pub fn get_joined_room(&self, room_id: &RoomId) -> Option<MatrixRoom> {
1853        let room = self.worker.client.get_room(room_id)?;
1854
1855        if room.state() == MatrixRoomState::Joined {
1856            Some(room)
1857        } else {
1858            None
1859        }
1860    }
1861
1862    /// Get the title for a room.
1863    pub fn get_room_title(&self, room_id: &RoomId) -> String {
1864        self.rooms
1865            .get(room_id)
1866            .and_then(|i| i.name.as_ref())
1867            .map(String::from)
1868            .unwrap_or_else(|| "Untitled Matrix Room".to_string())
1869    }
1870
1871    /// Get the [RoomInfo] for a given room identifier.
1872    pub fn get_room_info(&mut self, room_id: OwnedRoomId) -> &mut RoomInfo {
1873        self.rooms.get_or_default(room_id)
1874    }
1875
1876    /// Set the name for a room.
1877    pub fn set_room_name(&mut self, room_id: &RoomId, name: &str) {
1878        self.rooms.get_or_default(room_id.to_owned()).name = name.to_string().into();
1879    }
1880
1881    /// Insert a new E2EE verification.
1882    pub fn insert_sas(&mut self, sas: SasVerification) {
1883        let key = format!("{}/{}", sas.other_user_id(), sas.other_device().device_id());
1884
1885        self.verifications.insert(key, sas);
1886    }
1887}
1888
1889impl ApplicationStore for ChatStore {}
1890
1891/// Identified used to track window content.
1892#[derive(Clone, Debug, Eq, Hash, PartialEq)]
1893pub enum IambId {
1894    /// A Matrix room, with an optional thread to show.
1895    Room(OwnedRoomId, Option<OwnedEventId>),
1896
1897    /// The `:dms` window.
1898    DirectList,
1899
1900    /// The `:members` window for a given Matrix room.
1901    MemberList(OwnedRoomId),
1902
1903    /// The `:rooms` window.
1904    RoomList,
1905
1906    /// The `:spaces` window.
1907    SpaceList,
1908
1909    /// The `:verify` window.
1910    VerifyList,
1911
1912    /// The `:welcome` window.
1913    Welcome,
1914
1915    /// The `:chats` window.
1916    ChatList,
1917
1918    /// The `:unreads` window.
1919    UnreadList,
1920
1921    /// The `:mentions` window.
1922    MentionsList,
1923}
1924
1925impl Display for IambId {
1926    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1927        match self {
1928            IambId::Room(room_id, None) => {
1929                write!(f, "iamb://room/{room_id}")
1930            },
1931            IambId::Room(room_id, Some(thread)) => {
1932                write!(f, "iamb://room/{room_id}/threads/{thread}")
1933            },
1934            IambId::MemberList(room_id) => {
1935                write!(f, "iamb://members/{room_id}")
1936            },
1937            IambId::DirectList => f.write_str("iamb://dms"),
1938            IambId::RoomList => f.write_str("iamb://rooms"),
1939            IambId::SpaceList => f.write_str("iamb://spaces"),
1940            IambId::VerifyList => f.write_str("iamb://verify"),
1941            IambId::Welcome => f.write_str("iamb://welcome"),
1942            IambId::ChatList => f.write_str("iamb://chats"),
1943            IambId::UnreadList => f.write_str("iamb://unreads"),
1944            IambId::MentionsList => f.write_str("iamb://mentions"),
1945        }
1946    }
1947}
1948
1949impl ApplicationWindowId for IambId {}
1950
1951impl Serialize for IambId {
1952    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1953    where
1954        S: Serializer,
1955    {
1956        serializer.serialize_str(&self.to_string())
1957    }
1958}
1959
1960impl<'de> Deserialize<'de> for IambId {
1961    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1962    where
1963        D: Deserializer<'de>,
1964    {
1965        deserializer.deserialize_str(IambIdVisitor)
1966    }
1967}
1968
1969/// [serde] visitor for deserializing [IambId].
1970struct IambIdVisitor;
1971
1972impl Visitor<'_> for IambIdVisitor {
1973    type Value = IambId;
1974
1975    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1976        formatter.write_str("a valid window URL")
1977    }
1978
1979    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1980    where
1981        E: SerdeError,
1982    {
1983        let Ok(url) = Url::parse(value) else {
1984            return Err(E::custom("Invalid iamb window URL"));
1985        };
1986
1987        if url.scheme() != "iamb" {
1988            return Err(E::custom("Invalid iamb window URL"));
1989        }
1990
1991        match url.domain() {
1992            Some("room") => {
1993                let Some(path) = url.path_segments() else {
1994                    return Err(E::custom("Invalid members window URL"));
1995                };
1996
1997                match *path.collect::<Vec<_>>().as_slice() {
1998                    [room_id] => {
1999                        let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
2000                            return Err(E::custom("Invalid room identifier"));
2001                        };
2002
2003                        Ok(IambId::Room(room_id, None))
2004                    },
2005                    [room_id, "threads", thread_root] => {
2006                        let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
2007                            return Err(E::custom("Invalid room identifier"));
2008                        };
2009
2010                        let Ok(thread_root) = OwnedEventId::try_from(thread_root) else {
2011                            return Err(E::custom("Invalid thread root identifier"));
2012                        };
2013
2014                        Ok(IambId::Room(room_id, Some(thread_root)))
2015                    },
2016                    _ => return Err(E::custom("Invalid members window URL")),
2017                }
2018            },
2019            Some("members") => {
2020                let Some(path) = url.path_segments() else {
2021                    return Err(E::custom("Invalid members window URL"));
2022                };
2023
2024                let &[room_id] = path.collect::<Vec<_>>().as_slice() else {
2025                    return Err(E::custom("Invalid members window URL"));
2026                };
2027
2028                let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
2029                    return Err(E::custom("Invalid room identifier"));
2030                };
2031
2032                Ok(IambId::MemberList(room_id))
2033            },
2034            Some("dms") => {
2035                if url.path() != "" {
2036                    return Err(E::custom("iamb://dms takes no path"));
2037                }
2038
2039                Ok(IambId::DirectList)
2040            },
2041            Some("rooms") => {
2042                if url.path() != "" {
2043                    return Err(E::custom("iamb://rooms takes no path"));
2044                }
2045
2046                Ok(IambId::RoomList)
2047            },
2048            Some("spaces") => {
2049                if url.path() != "" {
2050                    return Err(E::custom("iamb://spaces takes no path"));
2051                }
2052
2053                Ok(IambId::SpaceList)
2054            },
2055            Some("verify") => {
2056                if url.path() != "" {
2057                    return Err(E::custom("iamb://verify takes no path"));
2058                }
2059
2060                Ok(IambId::VerifyList)
2061            },
2062            Some("welcome") => {
2063                if url.path() != "" {
2064                    return Err(E::custom("iamb://welcome takes no path"));
2065                }
2066
2067                Ok(IambId::Welcome)
2068            },
2069            Some("chats") => {
2070                if url.path() != "" {
2071                    return Err(E::custom("iamb://chats takes no path"));
2072                }
2073
2074                Ok(IambId::ChatList)
2075            },
2076            Some("unreads") => {
2077                if url.path() != "" {
2078                    return Err(E::custom("iamb://unreads takes no path"));
2079                }
2080
2081                Ok(IambId::UnreadList)
2082            },
2083            Some("mentions") => {
2084                if url.path() != "" {
2085                    return Err(E::custom("iamb://mentions takes no path"));
2086                }
2087
2088                Ok(IambId::MentionsList)
2089            },
2090            Some(s) => Err(E::custom(format!("{s:?} is not a valid window"))),
2091            None => Err(E::custom("Invalid iamb window URL")),
2092        }
2093    }
2094}
2095
2096/// Which part of the room window's UI is focused.
2097#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
2098pub enum RoomFocus {
2099    /// The scrollback for a room window is focused.
2100    Scrollback,
2101
2102    /// The message bar for a room window is focused.
2103    MessageBar,
2104}
2105
2106impl RoomFocus {
2107    /// Whether this is [RoomFocus::Scrollback].
2108    pub fn is_scrollback(&self) -> bool {
2109        matches!(self, RoomFocus::Scrollback)
2110    }
2111
2112    /// Whether this is [RoomFocus::MessageBar].
2113    pub fn is_msgbar(&self) -> bool {
2114        matches!(self, RoomFocus::MessageBar)
2115    }
2116
2117    pub fn toggle(&mut self) {
2118        *self = match self {
2119            RoomFocus::MessageBar => RoomFocus::Scrollback,
2120            RoomFocus::Scrollback => RoomFocus::MessageBar,
2121        };
2122    }
2123}
2124
2125/// Identifiers used to track where a mark was placed.
2126///
2127/// While this is the "buffer identifier" for the mark,
2128/// not all of these are necessarily actual buffers.
2129#[derive(Clone, Debug, Eq, Hash, PartialEq)]
2130pub enum IambBufferId {
2131    /// The command bar buffer.
2132    Command(CommandType),
2133
2134    /// The message buffer or a specific message in a room.
2135    Room(OwnedRoomId, Option<OwnedEventId>, RoomFocus),
2136
2137    /// The `:dms` window.
2138    DirectList,
2139
2140    /// The `:members` window for a room.
2141    MemberList(OwnedRoomId),
2142
2143    /// The `:rooms` window.
2144    RoomList,
2145
2146    /// The `:spaces` window.
2147    SpaceList,
2148
2149    /// The `:verify` window.
2150    VerifyList,
2151
2152    /// The buffer for the `:rooms` window.
2153    Welcome,
2154
2155    /// The `:chats` window.
2156    ChatList,
2157
2158    /// The `:unreads` window.
2159    UnreadList,
2160
2161    /// The `:mentions` window.
2162    MentionsList,
2163}
2164
2165impl IambBufferId {
2166    /// Get the identifier for the window that contains this buffer.
2167    pub fn to_window(&self) -> Option<IambId> {
2168        let id = match self {
2169            IambBufferId::Command(_) => return None,
2170            IambBufferId::Room(room, thread, _) => IambId::Room(room.clone(), thread.clone()),
2171            IambBufferId::DirectList => IambId::DirectList,
2172            IambBufferId::MemberList(room) => IambId::MemberList(room.clone()),
2173            IambBufferId::RoomList => IambId::RoomList,
2174            IambBufferId::SpaceList => IambId::SpaceList,
2175            IambBufferId::VerifyList => IambId::VerifyList,
2176            IambBufferId::Welcome => IambId::Welcome,
2177            IambBufferId::ChatList => IambId::ChatList,
2178            IambBufferId::UnreadList => IambId::UnreadList,
2179            IambBufferId::MentionsList => IambId::MentionsList,
2180        };
2181
2182        Some(id)
2183    }
2184}
2185
2186impl ApplicationContentId for IambBufferId {}
2187
2188impl ApplicationInfo for IambInfo {
2189    type Error = IambError;
2190    type Store = ChatStore;
2191    type Action = IambAction;
2192    type WindowId = IambId;
2193    type ContentId = IambBufferId;
2194
2195    fn content_of_command(ct: CommandType) -> IambBufferId {
2196        IambBufferId::Command(ct)
2197    }
2198}
2199
2200pub struct IambCompleter;
2201
2202impl Completer<IambInfo> for IambCompleter {
2203    fn complete(
2204        &mut self,
2205        text: &EditRope,
2206        cursor: &mut Cursor,
2207        content: &IambBufferId,
2208        store: &mut ChatStore,
2209    ) -> Vec<String> {
2210        match content {
2211            IambBufferId::Command(CommandType::Command) => complete_cmdbar(text, cursor, store),
2212            IambBufferId::Command(CommandType::Search) => vec![],
2213            IambBufferId::Room(_, _, RoomFocus::MessageBar) => complete_msgbar(text, cursor, store),
2214            IambBufferId::Room(_, _, RoomFocus::Scrollback) => vec![],
2215
2216            IambBufferId::DirectList => vec![],
2217            IambBufferId::MemberList(_) => vec![],
2218            IambBufferId::RoomList => vec![],
2219            IambBufferId::SpaceList => vec![],
2220            IambBufferId::VerifyList => vec![],
2221            IambBufferId::Welcome => vec![],
2222            IambBufferId::ChatList => vec![],
2223            IambBufferId::UnreadList => vec![],
2224            IambBufferId::MentionsList => vec![],
2225        }
2226    }
2227}
2228
2229/// Tab completion for user IDs.
2230fn complete_users(text: &EditRope, cursor: &mut Cursor, store: &ChatStore) -> Vec<String> {
2231    let id = text
2232        .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
2233        .unwrap_or_else(EditRope::empty);
2234    let id = Cow::from(&id);
2235
2236    store
2237        .presences
2238        .complete(id.as_ref())
2239        .into_iter()
2240        .map(|i| i.to_string())
2241        .collect()
2242}
2243
2244/// Tab completion within the message bar.
2245fn complete_msgbar(text: &EditRope, cursor: &mut Cursor, store: &ChatStore) -> Vec<String> {
2246    let id = text
2247        .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
2248        .unwrap_or_else(EditRope::empty);
2249    let id = Cow::from(&id);
2250
2251    match id.chars().next() {
2252        // Complete room aliases.
2253        Some('#') => {
2254            return store.names.complete(id.as_ref());
2255        },
2256
2257        // Complete room identifiers.
2258        Some('!') => {
2259            return store
2260                .rooms
2261                .complete(id.as_ref())
2262                .into_iter()
2263                .map(|i| i.to_string())
2264                .collect();
2265        },
2266
2267        // Complete Emoji shortcodes.
2268        Some(':') => {
2269            let list = store.emojis.complete(&id[1..]);
2270            let iter = list.into_iter().take(200).map(|s| format!(":{s}:"));
2271
2272            return iter.collect();
2273        },
2274
2275        // Complete usernames for @ and empty strings.
2276        Some('@') | None => {
2277            return store
2278                .presences
2279                .complete(id.as_ref())
2280                .into_iter()
2281                .map(|i| i.to_string())
2282                .collect();
2283        },
2284
2285        // Unknown sigil.
2286        Some(_) => return vec![],
2287    }
2288}
2289
2290/// Tab completion for Matrix identifiers (usernames, room aliases, etc.)
2291fn complete_matrix_names(text: &EditRope, cursor: &mut Cursor, store: &ChatStore) -> Vec<String> {
2292    let id = text
2293        .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
2294        .unwrap_or_else(EditRope::empty);
2295    let id = Cow::from(&id);
2296
2297    let list = store.names.complete(id.as_ref());
2298    if !list.is_empty() {
2299        return list;
2300    }
2301
2302    let list = store.presences.complete(id.as_ref());
2303    if !list.is_empty() {
2304        return list.into_iter().map(|i| i.to_string()).collect();
2305    }
2306
2307    store
2308        .rooms
2309        .complete(id.as_ref())
2310        .into_iter()
2311        .map(|i| i.to_string())
2312        .collect()
2313}
2314
2315/// Tab completion for Emoji shortcode names.
2316fn complete_emoji(text: &EditRope, cursor: &mut Cursor, store: &ChatStore) -> Vec<String> {
2317    let sc = text.get_prefix_word_mut(cursor, &WordStyle::Little);
2318    let sc = sc.unwrap_or_else(EditRope::empty);
2319    let sc = Cow::from(&sc);
2320
2321    store.emojis.complete(sc.as_ref())
2322}
2323
2324/// Tab completion for command names.
2325fn complete_cmdname(
2326    desc: CommandDescription,
2327    text: &EditRope,
2328    cursor: &mut Cursor,
2329    store: &ChatStore,
2330) -> Vec<String> {
2331    // Complete command name and set cursor position.
2332    let _ = text.get_prefix_word_mut(cursor, &WordStyle::Little);
2333    store.cmds.complete_name(desc.command.as_str())
2334}
2335
2336/// Tab completion for command arguments.
2337fn complete_cmdarg(
2338    desc: CommandDescription,
2339    text: &EditRope,
2340    cursor: &mut Cursor,
2341    store: &ChatStore,
2342) -> Vec<String> {
2343    let cmd = match store.cmds.get(desc.command.as_str()) {
2344        Ok(cmd) => cmd,
2345        Err(_) => return vec![],
2346    };
2347
2348    match cmd.name.as_str() {
2349        "cancel" | "dms" | "edit" | "redact" | "reply" => vec![],
2350        "members" | "rooms" | "spaces" | "welcome" => vec![],
2351        "download" | "keys" | "open" | "upload" => complete_path(text, cursor),
2352        "react" | "unreact" => complete_emoji(text, cursor, store),
2353
2354        "invite" => complete_users(text, cursor, store),
2355        "join" | "split" | "vsplit" | "tabedit" => complete_matrix_names(text, cursor, store),
2356        "room" => vec![],
2357        "verify" => vec![],
2358        "vertical" | "horizontal" | "aboveleft" | "belowright" | "tab" => {
2359            complete_cmd(desc.arg.text.as_str(), text, cursor, store)
2360        },
2361        _ => vec![],
2362    }
2363}
2364
2365/// Tab completion for commands.
2366fn complete_cmd(cmd: &str, text: &EditRope, cursor: &mut Cursor, store: &ChatStore) -> Vec<String> {
2367    match CommandDescription::from_str(cmd) {
2368        Ok(desc) => {
2369            if desc.arg.untrimmed.is_empty() {
2370                complete_cmdname(desc, text, cursor, store)
2371            } else {
2372                // Complete command argument.
2373                complete_cmdarg(desc, text, cursor, store)
2374            }
2375        },
2376
2377        // Can't parse command text, so return zero completions.
2378        Err(_) => vec![],
2379    }
2380}
2381
2382/// Tab completion for the command bar.
2383fn complete_cmdbar(text: &EditRope, cursor: &mut Cursor, store: &ChatStore) -> Vec<String> {
2384    let eo = text.cursor_to_offset(cursor);
2385    let slice = text.slice(..eo);
2386    let cow = Cow::from(&slice);
2387
2388    complete_cmd(cow.as_ref(), text, cursor, store)
2389}
2390
2391#[cfg(test)]
2392pub mod tests {
2393    use std::iter::FromIterator as _;
2394
2395    use super::*;
2396    use crate::config::user_style_from_color;
2397    use crate::tests::*;
2398    use matrix_sdk::ruma::{
2399        MilliSecondsSinceUnixEpoch,
2400        events::{reaction::ReactionEventContent, relation::Annotation},
2401        owned_event_id,
2402    };
2403    use pretty_assertions::assert_eq;
2404    use ratatui::style::Color;
2405    use serde_json::{Map, Value};
2406
2407    fn create_reaction_event(
2408        content: &ReactionEventContent,
2409        event_id: &str,
2410        sender: &str,
2411    ) -> ReactionEvent {
2412        serde_json::from_value(Value::Object(Map::from_iter([
2413            ("type".to_owned(), Value::String("m.reaction".into())),
2414            ("content".to_owned(), serde_json::to_value(content).unwrap()),
2415            ("event_id".to_owned(), serde_json::to_value(event_id).unwrap()),
2416            ("sender".to_owned(), Value::String(sender.into())),
2417            (
2418                "origin_server_ts".to_owned(),
2419                serde_json::to_value(MilliSecondsSinceUnixEpoch::now()).unwrap(),
2420            ),
2421            ("room_id".to_owned(), Value::String("!foo:example.org".into())),
2422        ])))
2423        .unwrap()
2424    }
2425
2426    #[test]
2427    fn multiple_identical_reactions() {
2428        let mut info = RoomInfo::default();
2429
2430        let content = ReactionEventContent::new(Annotation::new(
2431            owned_event_id!("$my_reaction"),
2432            "🏠".to_owned(),
2433        ));
2434
2435        for i in 0..3 {
2436            let event_id = format!("$house_{i}");
2437            let react = create_reaction_event(&content, &event_id, "@foo:example.com");
2438            info.insert_reaction(react);
2439        }
2440
2441        let content = ReactionEventContent::new(Annotation::new(
2442            owned_event_id!("$my_reaction"),
2443            "🙂".to_owned(),
2444        ));
2445
2446        for i in 0..2 {
2447            let event_id = format!("$smile_{i}");
2448            let react = create_reaction_event(&content, &event_id, "@foo:example.com");
2449            info.insert_reaction(react);
2450        }
2451
2452        for i in 2..4 {
2453            let event_id = format!("$smile2_{i}");
2454            let react = create_reaction_event(&content, &event_id, "@bar:example.com");
2455            info.insert_reaction(react);
2456        }
2457
2458        assert_eq!(info.get_reactions(&owned_event_id!("$my_reaction")), vec![
2459            ("🏠", 1),
2460            ("🙂", 2)
2461        ]);
2462    }
2463
2464    #[test]
2465    fn test_typing_spans() {
2466        let mut info = RoomInfo::default();
2467        let settings = mock_settings();
2468
2469        let users0 = vec![];
2470        let users1 = vec![TEST_USER1.clone()];
2471        let users2 = vec![TEST_USER1.clone(), TEST_USER2.clone()];
2472        let users4 = vec![
2473            TEST_USER1.clone(),
2474            TEST_USER2.clone(),
2475            TEST_USER3.clone(),
2476            TEST_USER4.clone(),
2477        ];
2478        let users5 = vec![
2479            TEST_USER1.clone(),
2480            TEST_USER2.clone(),
2481            TEST_USER3.clone(),
2482            TEST_USER4.clone(),
2483            TEST_USER5.clone(),
2484        ];
2485
2486        // Nothing set.
2487        assert_eq!(info.users_typing, None);
2488        assert_eq!(info.get_typing_spans(&settings), Line::from(vec![]));
2489
2490        // Empty typing list.
2491        info.set_typing(users0);
2492        assert!(info.users_typing.is_some());
2493        assert_eq!(info.get_typing_spans(&settings), Line::from(vec![]));
2494
2495        // Single user typing.
2496        info.set_typing(users1);
2497        assert!(info.users_typing.is_some());
2498        assert_eq!(
2499            info.get_typing_spans(&settings),
2500            Line::from(vec![
2501                Span::styled("@user1:example.com", user_style("@user1:example.com")),
2502                Span::from(" is typing...")
2503            ])
2504        );
2505
2506        // Two users typing.
2507        info.set_typing(users2);
2508        assert!(info.users_typing.is_some());
2509        assert_eq!(
2510            info.get_typing_spans(&settings),
2511            Line::from(vec![
2512                Span::styled("@user1:example.com", user_style("@user1:example.com")),
2513                Span::raw(" and "),
2514                Span::styled("@user2:example.com", user_style("@user2:example.com")),
2515                Span::raw(" are typing...")
2516            ])
2517        );
2518
2519        // Four users typing.
2520        info.set_typing(users4);
2521        assert!(info.users_typing.is_some());
2522        assert_eq!(info.get_typing_spans(&settings), Line::from("Several people are typing..."));
2523
2524        // Five users typing.
2525        info.set_typing(users5);
2526        assert!(info.users_typing.is_some());
2527        assert_eq!(info.get_typing_spans(&settings), Line::from("Many people are typing..."));
2528
2529        // Test that USER5 gets rendered using the configured color and name.
2530        info.set_typing(vec![TEST_USER5.clone()]);
2531        assert!(info.users_typing.is_some());
2532        assert_eq!(
2533            info.get_typing_spans(&settings),
2534            Line::from(vec![
2535                Span::styled("USER 5", user_style_from_color(Color::Black)),
2536                Span::from(" is typing...")
2537            ])
2538        );
2539    }
2540
2541    #[test]
2542    fn test_need_load() {
2543        let room_id = TEST_ROOM1_ID.clone();
2544
2545        let mut need_load = RoomNeeds::default();
2546
2547        need_load.need_messages(room_id.clone());
2548        need_load.need_members(room_id.clone());
2549
2550        assert_eq!(need_load.into_iter().collect::<Vec<(OwnedRoomId, Need)>>(), vec![(
2551            room_id,
2552            Need { members: true, messages: Some(Vec::new()) }
2553        )],);
2554    }
2555
2556    #[tokio::test]
2557    async fn test_complete_msgbar() {
2558        let store = mock_store().await;
2559        let store = store.application;
2560
2561        let text = EditRope::from("going for a walk :walk ");
2562        let mut cursor = Cursor::new(0, 22);
2563        let res = complete_msgbar(&text, &mut cursor, &store);
2564        assert_eq!(res, vec![":walking:", ":walking_man:", ":walking_woman:"]);
2565        assert_eq!(cursor, Cursor::new(0, 17));
2566
2567        let text = EditRope::from("hello @user1 ");
2568        let mut cursor = Cursor::new(0, 12);
2569        let res = complete_msgbar(&text, &mut cursor, &store);
2570        assert_eq!(res, vec!["@user1:example.com"]);
2571        assert_eq!(cursor, Cursor::new(0, 6));
2572
2573        let text = EditRope::from("see #room ");
2574        let mut cursor = Cursor::new(0, 9);
2575        let res = complete_msgbar(&text, &mut cursor, &store);
2576        assert_eq!(res, vec!["#room1:example.com"]);
2577        assert_eq!(cursor, Cursor::new(0, 4));
2578    }
2579
2580    #[tokio::test]
2581    async fn test_complete_cmdbar() {
2582        let store = mock_store().await;
2583        let store = store.application;
2584        let users = vec![
2585            "@user1:example.com",
2586            "@user2:example.com",
2587            "@user3:example.com",
2588            "@user4:example.com",
2589            "@user5:example.com",
2590        ];
2591
2592        let text = EditRope::from("invite    ");
2593        let mut cursor = Cursor::new(0, 7);
2594        let id = text
2595            .get_prefix_word_mut(&mut cursor, &MATRIX_ID_WORD)
2596            .unwrap_or_else(EditRope::empty);
2597        assert_eq!(id.to_string(), "");
2598        assert_eq!(cursor, Cursor::new(0, 7));
2599
2600        let text = EditRope::from("invite    ");
2601        let mut cursor = Cursor::new(0, 7);
2602        let res = complete_cmdbar(&text, &mut cursor, &store);
2603        assert_eq!(res, users);
2604
2605        let text = EditRope::from("invite ignored");
2606        let mut cursor = Cursor::new(0, 7);
2607        let res = complete_cmdbar(&text, &mut cursor, &store);
2608        assert_eq!(res, users);
2609
2610        let text = EditRope::from("invite @user1ignored");
2611        let mut cursor = Cursor::new(0, 13);
2612        let res = complete_cmdbar(&text, &mut cursor, &store);
2613        assert_eq!(res, vec!["@user1:example.com"]);
2614
2615        let text = EditRope::from("abo hor");
2616        let mut cursor = Cursor::new(0, 7);
2617        let res = complete_cmdbar(&text, &mut cursor, &store);
2618        assert_eq!(res, vec!["horizontal"]);
2619
2620        let text = EditRope::from("abo hor inv");
2621        let mut cursor = Cursor::new(0, 11);
2622        let res = complete_cmdbar(&text, &mut cursor, &store);
2623        assert_eq!(res, vec!["invite"]);
2624
2625        let text = EditRope::from("abo hor invite \n");
2626        let mut cursor = Cursor::new(0, 15);
2627        let res = complete_cmdbar(&text, &mut cursor, &store);
2628        assert_eq!(res, users);
2629    }
2630
2631    #[test]
2632    fn test_ambiguous_displaynames() {
2633        let mut store = DisplayNameStore::default();
2634
2635        store.set(TEST_USER1.clone(), Some("John".into()));
2636        store.set(TEST_USER2.clone(), Some("John".into()));
2637        store.set(TEST_USER3.clone(), Some("Jane".into()));
2638        store.set(TEST_USER4.clone(), Some("Alice".into()));
2639        store.set(TEST_USER5.clone(), Some("Bob".into()));
2640
2641        // TEST_USER1 and TEST_USER2 are both ambiguous, while the other are unambiguous:
2642        assert_eq!(store.get(&TEST_USER1).unwrap().as_ref(), "John (@user1:example.com)");
2643        assert_eq!(store.get(&TEST_USER2).unwrap().as_ref(), "John (@user2:example.com)");
2644        assert_eq!(store.get(&TEST_USER3).unwrap().as_ref(), "Jane");
2645        assert_eq!(store.get(&TEST_USER4).unwrap().as_ref(), "Alice");
2646        assert_eq!(store.get(&TEST_USER5).unwrap().as_ref(), "Bob");
2647
2648        // TEST_USER1 becomes unambiguous when TEST_USER2 changes:
2649        store.set(TEST_USER2.clone(), Some("Eve".into()));
2650        assert_eq!(store.get(&TEST_USER1).unwrap().as_ref(), "John");
2651        assert_eq!(store.get(&TEST_USER2).unwrap().as_ref(), "Eve");
2652        assert_eq!(store.get(&TEST_USER3).unwrap().as_ref(), "Jane");
2653        assert_eq!(store.get(&TEST_USER4).unwrap().as_ref(), "Alice");
2654        assert_eq!(store.get(&TEST_USER5).unwrap().as_ref(), "Bob");
2655
2656        // TEST_USER5 becomes ambiguous when TEST_USER2 once again changes their name to match:
2657        store.set(TEST_USER2.clone(), Some("Bob".into()));
2658        assert_eq!(store.get(&TEST_USER1).unwrap().as_ref(), "John");
2659        assert_eq!(store.get(&TEST_USER2).unwrap().as_ref(), "Bob (@user2:example.com)");
2660        assert_eq!(store.get(&TEST_USER3).unwrap().as_ref(), "Jane");
2661        assert_eq!(store.get(&TEST_USER4).unwrap().as_ref(), "Alice");
2662        assert_eq!(store.get(&TEST_USER5).unwrap().as_ref(), "Bob (@user5:example.com)");
2663
2664        // Now "Everyone is John":
2665        store.set(TEST_USER2.clone(), Some("John".into()));
2666        store.set(TEST_USER3.clone(), Some("John".into()));
2667        store.set(TEST_USER4.clone(), Some("John".into()));
2668        store.set(TEST_USER5.clone(), Some("John".into()));
2669        assert_eq!(store.get(&TEST_USER1).unwrap().as_ref(), "John (@user1:example.com)");
2670        assert_eq!(store.get(&TEST_USER2).unwrap().as_ref(), "John (@user2:example.com)");
2671        assert_eq!(store.get(&TEST_USER3).unwrap().as_ref(), "John (@user3:example.com)");
2672        assert_eq!(store.get(&TEST_USER4).unwrap().as_ref(), "John (@user4:example.com)");
2673        assert_eq!(store.get(&TEST_USER5).unwrap().as_ref(), "John (@user5:example.com)");
2674
2675        // 2-5 unset their displayname:
2676        store.set(TEST_USER2.clone(), None);
2677        store.set(TEST_USER3.clone(), None);
2678        store.set(TEST_USER4.clone(), None);
2679        store.set(TEST_USER5.clone(), None);
2680        assert_eq!(store.get(&TEST_USER1).unwrap().as_ref(), "John");
2681        assert_eq!(store.get(&TEST_USER2), None);
2682        assert_eq!(store.get(&TEST_USER3), None);
2683        assert_eq!(store.get(&TEST_USER4), None);
2684        assert_eq!(store.get(&TEST_USER5), None);
2685    }
2686}