src/base.rs

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