src/base.rs

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