src/base.rs

3486 lines · 117794 bytes

   1//! # Common types and utilities
   2//!
   3//! The types defined here get used throughout iamb.
   4
   5use std::collections::hash_map::IntoIter;
   6use std::collections::{BTreeSet, HashSet};
   7
   8use emojis::Emoji;
   9use matrix_sdk::Client;
  10use matrix_sdk::ruma::events::poll::start::PollStartEvent;
  11use matrix_sdk::ruma::events::poll::unstable_start::{
  12    UnstablePollStartEvent,
  13    UnstablePollStartEventContent,
  14};
  15use matrix_sdk::ruma::events::reaction::ReactionEvent;
  16use matrix_sdk::ruma::events::relation::Replacement;
  17use matrix_sdk::ruma::events::room::encrypted::RoomEncryptedEvent;
  18use matrix_sdk::ruma::events::room::message::RelationWithoutReplacement;
  19use matrix_sdk::ruma::events::room::message::{
  20    RoomMessageEvent,
  21    RoomMessageEventContentWithoutRelation,
  22};
  23use matrix_sdk::ruma::events::room::redaction::{
  24    OriginalSyncRoomRedactionEvent,
  25    SyncRoomRedactionEvent,
  26};
  27use matrix_sdk::ruma::events::space::child::SpaceChildEventContent;
  28use matrix_sdk::ruma::events::sticker::{StickerEvent, StickerEventContent};
  29use matrix_sdk::ruma::events::{MessageLikeEvent, OriginalMessageLikeEvent};
  30use matrix_sdk::ruma::presence::PresenceState;
  31use matrix_sdk::ruma::room::{AllowRule, Restricted};
  32use matrix_sdk::ruma::{OwnedMxcUri, OwnedTransactionId, RoomVersionId};
  33use modalkit::editing::application::{
  34    ApplicationAction,
  35    ApplicationContentId,
  36    ApplicationError,
  37    ApplicationInfo,
  38    ApplicationStore,
  39    ApplicationWindowId,
  40};
  41use modalkit::editing::completion::CompletionMap;
  42use modalkit::editing::context::EditContext;
  43use modalkit::editing::store::Store;
  44use modalkit::env::vim::command::{CommandContext, VimCommand, VimCommandMachine};
  45use modalkit::env::vim::keybindings::VimMachine;
  46use modalkit::errors::UIResult;
  47use modalkit::keybindings::SequenceStatus;
  48use percent_encoding::{NON_ALPHANUMERIC, percent_decode, percent_encode};
  49use serde::de::Error as SerdeError;
  50use serde::de::Visitor;
  51use serde::{Deserialize, Deserializer, Serialize, Serializer};
  52use tokio::sync::Mutex as AsyncMutex;
  53
  54use crate::message::poll::{
  55    Poll,
  56    PollEventLocation,
  57    PollRelation,
  58    UnloadedPoll,
  59    UnloadedUnstablePoll,
  60    UnstablePoll,
  61    UnstablePollRelation,
  62};
  63use crate::notifications::NotificationHandle;
  64use crate::prelude::*;
  65
  66/// The set of characters used in different Matrix IDs.
  67pub const MATRIX_ID_WORD: WordStyle = WordStyle::CharSet(is_mxid_char);
  68
  69/// Find the boundaries for a Matrix username, room alias, or room ID.
  70///
  71/// Technically "[" and "]" should be here since IPv6 addresses are allowed
  72/// in the server name, but in practice that should be uncommon, and people
  73/// can just use `gf` and friends in Visual mode instead.
  74fn is_mxid_char(c: char) -> bool {
  75    return c >= 'a' && c <= 'z' ||
  76        c >= 'A' && c <= 'Z' ||
  77        c >= '0' && c <= '9' ||
  78        ":-./@_#!".contains(c);
  79}
  80
  81const ROOM_FETCH_DEBOUNCE: Duration = Duration::from_secs(2);
  82
  83/// Empty type used solely to implement [ApplicationInfo].
  84#[derive(Clone, Debug, Eq, PartialEq)]
  85pub enum IambInfo {}
  86
  87/// An action taken against an ongoing verification request.
  88#[derive(Clone, Debug, Eq, PartialEq)]
  89pub enum VerifyAction {
  90    /// Accept a verification request.
  91    Accept,
  92
  93    /// Cancel an in-progress verification.
  94    Cancel,
  95
  96    /// Confirm an in-progress verification.
  97    Confirm,
  98
  99    /// Reject an in-progress verification due to mismatched Emoji.
 100    Mismatch,
 101
 102    /// Start an interactive (SAS) emoji verification
 103    Emoji,
 104}
 105
 106/// An action taken against a room's timeline.
 107#[derive(Clone, Debug, Eq, PartialEq)]
 108pub enum TimelineAction {
 109    /// Jump to a loaded message in the scrollback.
 110    GotoEvent(OwnedEventId),
 111}
 112
 113/// An action taken against the currently selected message.
 114#[derive(Clone, Debug, Eq, PartialEq)]
 115pub enum MessageAction {
 116    /// Cance the current reply or edit.
 117    ///
 118    /// The [bool] argument indicates whether to skip confirmation for clearing the message bar.
 119    Cancel(bool),
 120
 121    /// Download an attachment to the given path.
 122    ///
 123    /// The second argument controls whether to overwrite any already existing file at the
 124    /// destination path, or to open the attachment after downloading.
 125    Download(Option<PathBuf>, DownloadFlags),
 126
 127    /// Edit a sent message.
 128    Edit,
 129
 130    /// React to a message with an Emoji.
 131    ///
 132    /// `:react` will by default try to convert the [String] argument to an Emoji, and error when
 133    /// it doesn't recognize it. The second [bool] argument forces it to be interpreted literally
 134    /// when it is `true`.
 135    React(String, bool),
 136
 137    /// Pin a message to the room.
 138    Pin,
 139
 140    /// Redact a message, with an optional reason.
 141    ///
 142    /// The [bool] argument indicates whether to skip confirmation.
 143    Redact(Option<String>, bool),
 144
 145    /// Reply to a message.
 146    Reply,
 147
 148    /// Go to the message the hovered message replied to.
 149    Replied,
 150
 151    /// Unreact to a message.
 152    ///
 153    /// If no specific Emoji to remove to is specified, then all reactions from the user on the
 154    /// message are removed.
 155    ///
 156    /// Like `:react`, `:unreact` will by default try to convert the [String] argument to an Emoji,
 157    /// and error when it doesn't recognize it. The second [bool] argument forces it to be
 158    /// interpreted literally when it is `true`.
 159    Unreact(Option<String>, bool),
 160
 161    /// Unpin a message from the room.
 162    Unpin,
 163}
 164
 165/// An action taken in the currently selected space.
 166#[derive(Clone, Debug, Eq, PartialEq)]
 167pub enum SpaceAction {
 168    /// Add a room or update metadata.
 169    SetChild {
 170        /// The room that should be added to the space.
 171        child: OwnedRoomOrAliasId,
 172        /// The order parameter to use when sorting children in the space.
 173        order: Option<String>,
 174        /// Whether the room is suggested.
 175        suggested: bool,
 176    },
 177
 178    /// Remove the selected room.
 179    RemoveChild,
 180}
 181
 182/// The type of room being created.
 183#[derive(Clone, Debug, Eq, PartialEq)]
 184pub enum CreateRoomType {
 185    /// A standard chat room.
 186    Room,
 187
 188    /// A Matrix space.
 189    Space,
 190}
 191
 192bitflags::bitflags! {
 193    /// Available options for newly created rooms.
 194    #[derive(Clone, Debug, Eq, PartialEq)]
 195    pub struct CreateRoomFlags: u32 {
 196        /// No flags specified.
 197        const NONE = 0b00000000;
 198
 199        /// Make the room public.
 200        const PUBLIC = 0b00000001;
 201
 202        /// Encrypt this room.
 203        const ENCRYPTED = 0b00000010;
 204    }
 205}
 206
 207bitflags::bitflags! {
 208    /// Available options when downloading files.
 209    #[derive(Clone, Debug, Eq, PartialEq)]
 210    pub struct DownloadFlags: u32 {
 211        /// No flags specified.
 212        const NONE = 0b00000000;
 213
 214        /// Overwrite file if it already exists.
 215        const FORCE = 0b00000001;
 216
 217        /// Open file after downloading.
 218        const OPEN = 0b00000010;
 219    }
 220}
 221
 222/// Fields that rooms and spaces can be sorted by.
 223#[derive(Clone, Debug, Eq, PartialEq)]
 224pub enum SortFieldRoom {
 225    /// Sort rooms by whether they have the Favorite tag.
 226    Favorite,
 227
 228    /// Sort rooms by whether they have the Low Priority tag.
 229    LowPriority,
 230
 231    /// Sort rooms by their room name.
 232    Name,
 233
 234    /// Sort rooms by their canonical room alias.
 235    Alias,
 236
 237    /// Sort rooms by their Matrix room identifier.
 238    RoomId,
 239
 240    /// Sort rooms by the server portion of their canonical room alias.
 241    ///
 242    /// If the room has no canonical alias, and the room identifier uses the version 1 syntax
 243    /// for formatting the MXID, then this will fall back to using the server portion of the
 244    /// identifier (aka, the "namespace").
 245    Server,
 246
 247    /// Sort rooms by whether they have unread messages.
 248    Unread,
 249
 250    /// Sort rooms by whether they have unread notifications.
 251    Notifications,
 252
 253    /// Sort rooms by whether they have unread mentions.
 254    Mentions,
 255
 256    /// Sort rooms by the timestamps of their most recent messages.
 257    Recent,
 258
 259    /// Sort rooms by whether they are direct messages.
 260    Direct,
 261
 262    /// Sort rooms by whether they are spaces.
 263    Space,
 264
 265    /// Sort rooms by whether they are invites.
 266    Invite,
 267
 268    /// Sort rooms by whether the user has joined them.
 269    Joined,
 270}
 271
 272/// Fields that space children can be sorted by.
 273#[derive(Clone, Debug, Eq, PartialEq)]
 274pub enum SortFieldSpace {
 275    Room(SortFieldRoom),
 276    SpaceOrder,
 277}
 278
 279/// Fields that users can be sorted by.
 280#[derive(Clone, Debug, Eq, PartialEq)]
 281pub enum SortFieldUser {
 282    PowerLevel,
 283    UserId,
 284    LocalPart,
 285    Server,
 286    Knock,
 287    Invite,
 288}
 289
 290/// Whether to use the default sort direction for a field, or to reverse it.
 291#[derive(Clone, Debug, Eq, PartialEq)]
 292pub enum SortOrder {
 293    Ascending,
 294    Descending,
 295}
 296
 297/// One of the columns to sort on.
 298#[derive(Clone, Debug, Eq, PartialEq)]
 299pub struct SortColumn<T>(pub T, pub SortOrder);
 300
 301impl<'de> Deserialize<'de> for SortColumn<SortFieldRoom> {
 302    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
 303    where
 304        D: Deserializer<'de>,
 305    {
 306        deserializer.deserialize_str(SortRoomVisitor)
 307    }
 308}
 309
 310/// [serde] visitor for deserializing [SortColumn] for rooms and spaces.
 311struct SortRoomVisitor;
 312
 313impl Visitor<'_> for SortRoomVisitor {
 314    type Value = SortColumn<SortFieldRoom>;
 315
 316    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
 317        formatter.write_str("a valid field for sorting rooms")
 318    }
 319
 320    fn visit_str<E>(self, mut value: &str) -> Result<Self::Value, E>
 321    where
 322        E: SerdeError,
 323    {
 324        if value.is_empty() {
 325            return Err(E::custom("Invalid sort field"));
 326        }
 327
 328        let order = if value.starts_with('~') {
 329            value = &value[1..];
 330            SortOrder::Descending
 331        } else {
 332            SortOrder::Ascending
 333        };
 334
 335        let field = match value {
 336            "favorite" => SortFieldRoom::Favorite,
 337            "lowpriority" => SortFieldRoom::LowPriority,
 338            "recent" => SortFieldRoom::Recent,
 339            "unread" => SortFieldRoom::Unread,
 340            "notifications" => SortFieldRoom::Notifications,
 341            "mentions" => SortFieldRoom::Mentions,
 342            "name" => SortFieldRoom::Name,
 343            "alias" => SortFieldRoom::Alias,
 344            "dm" => SortFieldRoom::Direct,
 345            "id" => SortFieldRoom::RoomId,
 346            "server" => SortFieldRoom::Server,
 347            "space" => SortFieldRoom::Space,
 348            "invite" => SortFieldRoom::Invite,
 349            "joined" => SortFieldRoom::Joined,
 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<SortFieldSpace> {
 361    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
 362    where
 363        D: Deserializer<'de>,
 364    {
 365        deserializer.deserialize_str(SortSpaceVisitor)
 366    }
 367}
 368
 369/// [serde] visitor for deserializing [SortColumn] for rooms and spaces.
 370struct SortSpaceVisitor;
 371
 372impl Visitor<'_> for SortSpaceVisitor {
 373    type Value = SortColumn<SortFieldSpace>;
 374
 375    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
 376        formatter.write_str("a valid field for sorting space children")
 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 sort field"));
 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            "spaceorder" => SortFieldSpace::SpaceOrder,
 396            _ => {
 397                let room_column = SortRoomVisitor.visit_str(value)?;
 398                SortFieldSpace::Room(room_column.0)
 399            },
 400        };
 401
 402        Ok(SortColumn(field, order))
 403    }
 404}
 405
 406impl<'de> Deserialize<'de> for SortColumn<SortFieldUser> {
 407    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
 408    where
 409        D: Deserializer<'de>,
 410    {
 411        deserializer.deserialize_str(SortUserVisitor)
 412    }
 413}
 414
 415/// [serde] visitor for deserializing [SortColumn] for users.
 416struct SortUserVisitor;
 417
 418impl Visitor<'_> for SortUserVisitor {
 419    type Value = SortColumn<SortFieldUser>;
 420
 421    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
 422        formatter.write_str("a valid field for sorting rooms")
 423    }
 424
 425    fn visit_str<E>(self, mut value: &str) -> Result<Self::Value, E>
 426    where
 427        E: SerdeError,
 428    {
 429        if value.is_empty() {
 430            return Err(E::custom("Invalid field for sorting users"));
 431        }
 432
 433        let order = if value.starts_with('~') {
 434            value = &value[1..];
 435            SortOrder::Descending
 436        } else {
 437            SortOrder::Ascending
 438        };
 439
 440        let field = match value {
 441            "id" => SortFieldUser::UserId,
 442            "localpart" => SortFieldUser::LocalPart,
 443            "server" => SortFieldUser::Server,
 444            "power" => SortFieldUser::PowerLevel,
 445            "knock" => SortFieldUser::Knock,
 446            "invite" => SortFieldUser::Invite,
 447            _ => {
 448                let msg = format!("Unknown sort field: {value:?}");
 449                return Err(E::custom(msg));
 450            },
 451        };
 452
 453        Ok(SortColumn(field, order))
 454    }
 455}
 456
 457/// An account property.
 458#[derive(Clone, Debug, Eq, PartialEq)]
 459pub enum AccountField {
 460    /// The account's ignore list.
 461    Ignore,
 462
 463    /// Set whether other user's are allowed to invite the user to rooms.
 464    Invites,
 465}
 466
 467/// A room property.
 468#[derive(Clone, Debug, Eq, PartialEq)]
 469pub enum RoomField {
 470    /// The room's join rules, aka who can access this room.
 471    Access,
 472
 473    /// The room's history visibility.
 474    History,
 475
 476    /// The room name.
 477    Name,
 478
 479    /// The room version.
 480    Version,
 481
 482    /// The room id.
 483    Id,
 484
 485    /// A room tag.
 486    Tag(TagName),
 487
 488    /// The room topic.
 489    Topic,
 490
 491    /// Notification level.
 492    NotificationMode,
 493
 494    /// The room's entire list of alternative aliases.
 495    Aliases,
 496
 497    /// A specific alternative alias to the room.
 498    Alias(String),
 499
 500    /// The room's canonical alias.
 501    CanonicalAlias,
 502
 503    /// The users own display name.
 504    UserName,
 505}
 506
 507/// An action that operates on a room member.
 508#[derive(Clone, Debug, Eq, PartialEq)]
 509pub enum MemberUpdateAction {
 510    Ban,
 511    Kick,
 512    Unban,
 513}
 514
 515impl Display for MemberUpdateAction {
 516    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 517        match self {
 518            MemberUpdateAction::Ban => write!(f, "ban"),
 519            MemberUpdateAction::Kick => write!(f, "kick"),
 520            MemberUpdateAction::Unban => write!(f, "unban"),
 521        }
 522    }
 523}
 524
 525/// An internal version of [`JoinRule`]
 526#[derive(Clone, Debug, Eq, PartialEq)]
 527pub enum IambJoinRule {
 528    Public,
 529    Restricted(Vec<OwnedRoomOrAliasId>),
 530    Knock,
 531    KnockRestricted(Vec<OwnedRoomOrAliasId>),
 532    Invite,
 533}
 534
 535impl IambJoinRule {
 536    pub async fn into_join_rule(self, client: &Client) -> Result<JoinRule, IambError> {
 537        async fn resolve_aliases(
 538            rooms: Vec<OwnedRoomOrAliasId>,
 539            client: &Client,
 540        ) -> Result<Restricted, IambError> {
 541            let mut allow = vec![];
 542            for room in rooms {
 543                let alias = match OwnedRoomId::try_from(room) {
 544                    Ok(room_id) => {
 545                        allow.push(AllowRule::room_membership(room_id));
 546                        continue;
 547                    },
 548                    Err(alias) => alias,
 549                };
 550
 551                let resp = client.resolve_room_alias(&alias).await?;
 552
 553                allow.push(AllowRule::room_membership(resp.room_id));
 554            }
 555
 556            Ok(Restricted::new(allow))
 557        }
 558
 559        Ok(match self {
 560            Self::Public => JoinRule::Public,
 561            Self::Invite => JoinRule::Invite,
 562            Self::Knock => JoinRule::Knock,
 563            Self::Restricted(rooms) => JoinRule::Restricted(resolve_aliases(rooms, client).await?),
 564            Self::KnockRestricted(rooms) => {
 565                JoinRule::KnockRestricted(resolve_aliases(rooms, client).await?)
 566            },
 567        })
 568    }
 569}
 570
 571/// An action that operates on a focused room.
 572#[derive(Clone, Debug, Eq, PartialEq)]
 573pub enum RoomAction {
 574    /// Follow the room upgrade information.
 575    Follow(Box<CommandContext>, MoveDir1D),
 576
 577    /// Accept an invitation to join this room.
 578    InviteAccept,
 579
 580    /// Reject an invitation to join this room.
 581    InviteReject,
 582
 583    /// Invite a user to this room.
 584    InviteSend(OwnedUserId),
 585
 586    /// Accept a knock from someone who wants to join this room.
 587    KnockAccept(OwnedUserId),
 588
 589    /// Reject a knock from someone who wants to join this room.
 590    KnockReject(OwnedUserId, Option<String>),
 591
 592    /// Reject a knock from someone who wants to join this room and ban them
 593    /// to prevent them from being able to try knocking again.
 594    KnockBan(OwnedUserId, Option<String>),
 595
 596    /// Leave this room.
 597    Leave(bool),
 598
 599    /// Update a user's membership in this room.
 600    MemberUpdate(MemberUpdateAction, String, Option<String>, bool),
 601
 602    /// Open the members window.
 603    Members(Box<CommandContext>),
 604
 605    /// Open the message info window.
 606    Message(Box<CommandContext>),
 607
 608    /// Open the pinned messages window.
 609    Pinned(Box<CommandContext>),
 610
 611    /// Set whether a room is a direct message.
 612    SetDirect(bool),
 613
 614    /// Set the join rules for a room to control who can access it and how.
 615    SetAccess(IambJoinRule),
 616
 617    /// Set a room property.
 618    Set(RoomField, String),
 619
 620    /// Unset a room property.
 621    Unset(RoomField),
 622
 623    /// Upgrade the version of a room.
 624    Upgrade(RoomVersionId, Vec<OwnedUserId>, bool),
 625
 626    /// List the values in a list room property.
 627    Show(RoomField),
 628
 629    /// Mark the room as read/unread.
 630    SetUnread(bool),
 631}
 632
 633/// An action that joins  a room.
 634#[derive(Clone, Debug, Eq, PartialEq)]
 635pub enum JoinAction {
 636    /// Join the focused room.
 637    Join,
 638
 639    /// Knock on the focused room.
 640    Knock,
 641}
 642
 643/// An action that sends a message to a room.
 644#[derive(Clone, Debug, Eq, PartialEq)]
 645pub enum SendAction {
 646    /// Send the text in the message bar.
 647    Submit,
 648
 649    /// Send text provided from an external editor.
 650    SubmitFromEditor,
 651
 652    /// Upload a file.
 653    ///
 654    /// The second argument indicates whether to use the messagebar as a caption, don't use it or
 655    /// ask the user.
 656    Upload(PathBuf, Option<bool>),
 657
 658    /// Upload the image data.
 659    ///
 660    /// The [`bool`] arguments indicates whether to use the messagebar as a caption.
 661    UploadImage(usize, usize, Cow<'static, [u8]>, bool),
 662}
 663
 664/// An action performed against the user's homeserver.
 665#[derive(Clone, Debug, Eq, PartialEq)]
 666pub enum HomeserverAction {
 667    /// Create a new room with an optional localpart.
 668    CreateRoom(Option<String>, CreateRoomType, CreateRoomFlags),
 669
 670    /// Update an account property.
 671    AccountSet(AccountField, String),
 672
 673    /// Show information about an account property.
 674    AccountShow(AccountField),
 675
 676    /// Remove a user from the account's ignore list.
 677    AccountUnset(AccountField, Option<String>),
 678
 679    /// "Knock" on a room, aka "request to join".
 680    KnockSend(OwnedRoomOrAliasId, Option<String>),
 681
 682    /// Logout the current iamb session on the homeserver.
 683    Logout(String, bool),
 684
 685    /// Forget all left rooms
 686    Forget,
 687
 688    /// Set a profile field.
 689    ProfileFieldSet(ProfileFieldValue),
 690
 691    /// Set a profile field.
 692    ProfileFieldUnset(ProfileFieldName),
 693
 694    /// Set a profile field.
 695    ProfileFieldShow(ProfileFieldName),
 696}
 697
 698/// An action performed against the user's room keys.
 699#[derive(Clone, Debug, Eq, PartialEq)]
 700pub enum KeysAction {
 701    /// Export room keys to a file, encrypted with a passphrase.
 702    Export(String, String),
 703    /// Import room keys from a file, encrypted with a passphrase.
 704    Import(String, String),
 705}
 706
 707/// An action that the main program loop should execute.
 708///
 709/// See [the commands module][super::commands] for where these are usually created.
 710#[derive(Clone, Debug, Eq, PartialEq)]
 711pub enum IambAction {
 712    /// Perform an action against the homeserver.
 713    Homeserver(HomeserverAction),
 714
 715    /// Perform an action against a room's timeline.
 716    Timeline(TimelineAction),
 717
 718    /// Perform an action over room keys.
 719    Keys(KeysAction),
 720
 721    /// Perform an action on the currently selected message.
 722    Message(MessageAction),
 723
 724    /// Perform an action on the current space.
 725    Space(SpaceAction),
 726
 727    /// Open a URL.
 728    OpenLink(String),
 729
 730    /// Perform an action on the currently focused room.
 731    Room(RoomAction),
 732
 733    /// Join the focused room preview.
 734    Join(JoinAction),
 735
 736    /// Send a message to the currently focused room.
 737    Send(SendAction),
 738
 739    /// Perform an action for an in-progress verification.
 740    Verify(VerifyAction, String),
 741
 742    /// Request a new verification with the specified user.
 743    VerifyRequest(String),
 744
 745    /// Recover the encryption secrets for this session with the given recovery key.
 746    Recover(String),
 747
 748    /// Toggle the focus within the focused room.
 749    ToggleScrollbackFocus,
 750
 751    /// Change the current theme.
 752    ChangeTheme(String),
 753
 754    /// Clear all unread messages.
 755    ClearUnreads,
 756}
 757
 758impl IambAction {
 759    /// Indicates whether this action will draw over the screen.
 760    pub fn scribbles(&self) -> bool {
 761        matches!(self, IambAction::Send(SendAction::SubmitFromEditor))
 762    }
 763}
 764
 765impl From<HomeserverAction> for IambAction {
 766    fn from(act: HomeserverAction) -> Self {
 767        IambAction::Homeserver(act)
 768    }
 769}
 770
 771impl From<MessageAction> for IambAction {
 772    fn from(act: MessageAction) -> Self {
 773        IambAction::Message(act)
 774    }
 775}
 776
 777impl From<SpaceAction> for IambAction {
 778    fn from(act: SpaceAction) -> Self {
 779        IambAction::Space(act)
 780    }
 781}
 782
 783impl From<RoomAction> for IambAction {
 784    fn from(act: RoomAction) -> Self {
 785        IambAction::Room(act)
 786    }
 787}
 788
 789impl From<JoinAction> for IambAction {
 790    fn from(act: JoinAction) -> Self {
 791        IambAction::Join(act)
 792    }
 793}
 794
 795impl From<SendAction> for IambAction {
 796    fn from(act: SendAction) -> Self {
 797        IambAction::Send(act)
 798    }
 799}
 800
 801impl From<TimelineAction> for IambAction {
 802    fn from(act: TimelineAction) -> Self {
 803        IambAction::Timeline(act)
 804    }
 805}
 806
 807impl ApplicationAction for IambAction {
 808    fn is_edit_sequence(&self, _: &EditContext) -> SequenceStatus {
 809        match self {
 810            IambAction::ChangeTheme(..) => SequenceStatus::Break,
 811            IambAction::ClearUnreads => SequenceStatus::Break,
 812            IambAction::Homeserver(..) => SequenceStatus::Break,
 813            IambAction::Keys(..) => SequenceStatus::Break,
 814            IambAction::Message(..) => SequenceStatus::Break,
 815            IambAction::Space(..) => SequenceStatus::Break,
 816            IambAction::Room(..) => SequenceStatus::Break,
 817            IambAction::OpenLink(..) => SequenceStatus::Break,
 818            IambAction::Send(..) => SequenceStatus::Break,
 819            IambAction::Timeline(..) => SequenceStatus::Break,
 820            IambAction::ToggleScrollbackFocus => SequenceStatus::Break,
 821            IambAction::Verify(..) => SequenceStatus::Break,
 822            IambAction::VerifyRequest(..) => SequenceStatus::Break,
 823            IambAction::Recover(..) => SequenceStatus::Break,
 824            IambAction::Join(..) => SequenceStatus::Break,
 825        }
 826    }
 827
 828    fn is_last_action(&self, _: &EditContext) -> SequenceStatus {
 829        match self {
 830            IambAction::ChangeTheme(..) => SequenceStatus::Atom,
 831            IambAction::ClearUnreads => SequenceStatus::Atom,
 832            IambAction::Homeserver(..) => SequenceStatus::Atom,
 833            IambAction::Keys(..) => SequenceStatus::Atom,
 834            IambAction::Message(..) => SequenceStatus::Atom,
 835            IambAction::Space(..) => SequenceStatus::Atom,
 836            IambAction::OpenLink(..) => SequenceStatus::Atom,
 837            IambAction::Room(..) => SequenceStatus::Atom,
 838            IambAction::Send(..) => SequenceStatus::Atom,
 839            IambAction::Timeline(..) => SequenceStatus::Atom,
 840            IambAction::ToggleScrollbackFocus => SequenceStatus::Atom,
 841            IambAction::Verify(..) => SequenceStatus::Atom,
 842            IambAction::VerifyRequest(..) => SequenceStatus::Atom,
 843            IambAction::Recover(..) => SequenceStatus::Atom,
 844            IambAction::Join(..) => SequenceStatus::Atom,
 845        }
 846    }
 847
 848    fn is_last_selection(&self, _: &EditContext) -> SequenceStatus {
 849        match self {
 850            IambAction::ChangeTheme(..) => SequenceStatus::Ignore,
 851            IambAction::ClearUnreads => SequenceStatus::Ignore,
 852            IambAction::Homeserver(..) => SequenceStatus::Ignore,
 853            IambAction::Keys(..) => SequenceStatus::Ignore,
 854            IambAction::Message(..) => SequenceStatus::Ignore,
 855            IambAction::Space(..) => SequenceStatus::Ignore,
 856            IambAction::Room(..) => SequenceStatus::Ignore,
 857            IambAction::OpenLink(..) => SequenceStatus::Ignore,
 858            IambAction::Send(..) => SequenceStatus::Ignore,
 859            IambAction::Timeline(..) => SequenceStatus::Ignore,
 860            IambAction::ToggleScrollbackFocus => SequenceStatus::Ignore,
 861            IambAction::Verify(..) => SequenceStatus::Ignore,
 862            IambAction::VerifyRequest(..) => SequenceStatus::Ignore,
 863            IambAction::Recover(..) => SequenceStatus::Ignore,
 864            IambAction::Join(..) => SequenceStatus::Ignore,
 865        }
 866    }
 867
 868    fn is_switchable(&self, _: &EditContext) -> bool {
 869        match self {
 870            IambAction::ChangeTheme(..) => false,
 871            IambAction::ClearUnreads => false,
 872            IambAction::Homeserver(..) => false,
 873            IambAction::Message(..) => false,
 874            IambAction::Space(..) => false,
 875            IambAction::Room(..) => false,
 876            IambAction::Keys(..) => false,
 877            IambAction::Send(..) => false,
 878            IambAction::OpenLink(..) => false,
 879            IambAction::Timeline(..) => false,
 880            IambAction::ToggleScrollbackFocus => false,
 881            IambAction::Verify(..) => false,
 882            IambAction::VerifyRequest(..) => false,
 883            IambAction::Recover(..) => false,
 884            IambAction::Join(..) => false,
 885        }
 886    }
 887}
 888
 889impl From<RoomAction> for ProgramAction {
 890    fn from(act: RoomAction) -> Self {
 891        IambAction::from(act).into()
 892    }
 893}
 894
 895impl From<SpaceAction> for ProgramAction {
 896    fn from(act: SpaceAction) -> Self {
 897        IambAction::from(act).into()
 898    }
 899}
 900
 901impl From<TimelineAction> for ProgramAction {
 902    fn from(act: TimelineAction) -> Self {
 903        IambAction::from(act).into()
 904    }
 905}
 906
 907impl From<IambAction> for ProgramAction {
 908    fn from(act: IambAction) -> Self {
 909        Action::Application(act)
 910    }
 911}
 912
 913/// Alias for program actions.
 914pub type ProgramAction = Action<IambInfo>;
 915/// Alias for program context.
 916pub type ProgramContext = EditContext;
 917/// Alias for program keybindings.
 918pub type Keybindings = VimMachine<TerminalKey, IambInfo>;
 919/// Alias for a program command.
 920pub type ProgramCommand = VimCommand<IambInfo>;
 921/// Alias for mapped program commands.
 922pub type ProgramCommands = VimCommandMachine<IambInfo>;
 923/// Alias for program store.
 924pub type ProgramStore = Store<IambInfo>;
 925/// Alias for shared program store.
 926pub type AsyncProgramStore = Arc<AsyncMutex<ProgramStore>>;
 927/// Alias for an action result.
 928pub type IambResult<T> = UIResult<T, IambInfo>;
 929
 930/// Reaction events for some message.
 931///
 932/// The event identifier used as a key here is the ID for the reaction, and not for the message
 933/// it's reacting to.
 934pub type MessageReactions = HashMap<OwnedEventId, (String, OwnedUserId, Option<MediaSource>)>;
 935
 936pub type MessageEdits = BTreeMap<MessageKey, RoomMessageEventContentWithoutRelation>;
 937
 938/// Errors encountered during application use.
 939#[derive(thiserror::Error, Debug)]
 940pub enum IambError {
 941    /// An invalid history visibility was specified.
 942    #[error("Invalid history visibility setting: {0}")]
 943    InvalidHistoryVisibility(String),
 944
 945    /// An invalid notification level was specified.
 946    #[error("Invalid notification level: {0}")]
 947    InvalidNotificationLevel(String),
 948
 949    /// An invalid user identifier was specified.
 950    #[error("Invalid user identifier: {0:?}")]
 951    InvalidUserId(String),
 952
 953    /// An invalid user identifier was specified.
 954    #[error("Invalid room alias: {0}")]
 955    InvalidRoomAlias(String),
 956
 957    /// An invalid verification identifier was specified.
 958    #[error("Invalid verification user/device pair: {0}")]
 959    InvalidVerificationId(String),
 960
 961    /// A failure related to the cryptographic store.
 962    #[error("Cryptographic storage error: {0}")]
 963    CryptoStore(#[from] matrix_sdk::encryption::CryptoStoreError),
 964
 965    #[error("Failed to import room keys: {0}")]
 966    FailedKeyImport(#[from] matrix_sdk::encryption::RoomKeyImportError),
 967
 968    /// An HTTP error.
 969    #[error("HTTP client error: {0}")]
 970    Http(#[from] matrix_sdk::HttpError),
 971
 972    /// A failure from the Matrix client.
 973    #[error("Matrix client error: {0}")]
 974    Matrix(#[from] matrix_sdk::Error),
 975
 976    /// A failure when sending a message.
 977    #[error("Send queue error: {0}")]
 978    SendQueue(#[from] matrix_sdk::send_queue::RoomSendQueueError),
 979
 980    /// A failure in the sled storage.
 981    #[error("Matrix client storage error: {0}")]
 982    Store(#[from] matrix_sdk::StoreError),
 983
 984    /// A failure during serialization or deserialization.
 985    #[error("Serialization/deserialization error: {0}")]
 986    Serde(#[from] serde_json::Error),
 987
 988    /// A failure due to not having a configured download directory.
 989    #[error("No download directory configured")]
 990    NoDownloadDir,
 991
 992    /// A failure due to not having a message with an attachment selected.
 993    #[error("Selected message does not have any attachments")]
 994    NoAttachment,
 995
 996    /// A failure due to not having a message selected.
 997    #[error("No message currently selected")]
 998    NoSelectedMessage,
 999
1000    /// A failure due to not having a room or space selected.
1001    #[error("Current window is not a room or space")]
1002    NoSelectedRoomOrSpace,
1003
1004    /// A failure due to not having a room or space item selected in a list.
1005    #[error("No room or space currently selected in list")]
1006    NoSelectedRoomOrSpaceItem,
1007
1008    /// A failure due to not having a room selected.
1009    #[error("Current window is not a room")]
1010    NoSelectedRoom,
1011
1012    /// A failure due to not having a space selected.
1013    #[error("Current window is not a space")]
1014    NoSelectedSpace,
1015
1016    /// A failure due to not having sufficient permission to perform an action in a room.
1017    #[error("You do not have the permission to do that")]
1018    InsufficientPermission,
1019
1020    /// A failure due to not having an outstanding room invitation.
1021    #[error("You do not have a current invitation to this room")]
1022    NotInvited,
1023
1024    /// A failure due to not being a joined room member.
1025    #[error("You need to join the room before you can do that")]
1026    NotJoined,
1027
1028    /// An unknown room was specified.
1029    #[error("Unknown room identifier: {0}")]
1030    UnknownRoom(OwnedRoomId),
1031
1032    /// An invalid room alias id was specified.
1033    #[error("Invalid room alias id: {0}")]
1034    InvalidRoomAliasId(#[from] matrix_sdk::ruma::IdParseError),
1035
1036    /// An invalid space child order was specified.
1037    #[error("Invalid space child order: {0}")]
1038    InvalidSpaceChildOrder(matrix_sdk::ruma::IdParseError),
1039
1040    /// A failure occurred during verification.
1041    #[error("Verification request error: {0}")]
1042    VerificationRequestError(#[from] matrix_sdk::encryption::identities::RequestVerificationError),
1043
1044    /// A failure occurred while recovering the encryption secrets.
1045    #[error("Recovery error: {0}")]
1046    RecoveryError(#[from] matrix_sdk::encryption::recovery::RecoveryError),
1047
1048    #[error("Notification setting error: {0}")]
1049    NotificationSettingError(#[from] matrix_sdk::NotificationSettingsError),
1050
1051    /// A failure related to images.
1052    #[error("Image error: {0}")]
1053    Image(#[from] image::ImageError),
1054
1055    /// A failure to access the system's clipboard.
1056    #[error("Could not use system clipboard data")]
1057    Clipboard,
1058
1059    /// An failure during disk/network/ipc/etc. I/O.
1060    #[error("Input/Output error: {0}")]
1061    IOError(#[from] std::io::Error),
1062
1063    /// A failure while trying to show an image preview.
1064    #[error("Preview error: {0}")]
1065    Preview(String),
1066
1067    /// A generic error that doesn't need a specific error type.
1068    #[error("{0}")]
1069    Custom(String),
1070}
1071
1072impl From<IambError> for UIError<IambInfo> {
1073    fn from(err: IambError) -> Self {
1074        UIError::Application(err)
1075    }
1076}
1077
1078impl From<matrix_sdk::event_cache::EventCacheError> for IambError {
1079    fn from(value: matrix_sdk::event_cache::EventCacheError) -> Self {
1080        Self::from(matrix_sdk::Error::from(value))
1081    }
1082}
1083
1084impl From<matrix_sdk::authentication::oauth::OAuthError> for IambError {
1085    fn from(value: matrix_sdk::authentication::oauth::OAuthError) -> Self {
1086        Self::from(matrix_sdk::Error::from(value))
1087    }
1088}
1089
1090impl ApplicationError for IambError {}
1091
1092/// Indicates where an [EventId] lives in the [ChatStore].
1093#[derive(Clone)]
1094pub enum EventLocation {
1095    /// The [EventId] belongs to a message like event.
1096    ///
1097    /// If the first argument is [None], then it's part of the main scrollback. When [Some],
1098    /// it specifies which thread it's in reply to.
1099    Message(Option<OwnedEventId>, MessageKey),
1100
1101    /// The [EventId] belongs to a reaction to the given event.
1102    Reaction(OwnedEventId),
1103
1104    /// The [EventId] belongs to an edit for the given event and has key [MessageKey].
1105    Edit(OwnedEventId, MessageKey),
1106
1107    /// The [EventId] belongs to an aggregation for the given poll.
1108    Poll(OwnedEventId, PollEventLocation),
1109}
1110
1111impl EventLocation {
1112    fn to_message_key(&self) -> Option<&MessageKey> {
1113        match self {
1114            EventLocation::Message(_, key) => Some(key),
1115            _ => None,
1116        }
1117    }
1118    fn to_thread_root(&self) -> Option<&EventId> {
1119        match self {
1120            EventLocation::Message(root, _) => root.as_deref(),
1121            _ => None,
1122        }
1123    }
1124}
1125
1126/// Indicates where a local echo lives in the [`ChatStore`].
1127#[derive(Debug, Clone)]
1128pub enum EchoLocation {
1129    /// The [`OwnedTransactionId`] belongs to a message.
1130    ///
1131    /// If the first argument is [`None`], then it's part of the main scrollback. When [`Some`], it
1132    /// specifies which thread it's in reply to.
1133    Message(Option<OwnedEventId>, MessageKey),
1134
1135    /// The local echo has been replaced by an event with this event id.
1136    Replaced(OwnedEventId),
1137}
1138
1139#[derive(Clone, Debug, Default, Eq, PartialEq)]
1140pub struct UnreadInfo {
1141    pub(crate) unread_mark: bool,
1142    pub(crate) unread_messages: u64,
1143    pub(crate) unread_notifications: u64,
1144    pub(crate) unread_mentions: u64,
1145    pub(crate) latest: Option<MessageTimeStamp>,
1146}
1147
1148impl UnreadInfo {
1149    pub fn is_unread(&self) -> bool {
1150        self.unread_mark || self.unread_notifications > 0 || self.unread_mentions > 0
1151    }
1152
1153    pub fn has_mention(&self) -> bool {
1154        self.unread_mentions > 0
1155    }
1156
1157    pub fn has_notification(&self) -> bool {
1158        self.unread_notifications > 0
1159    }
1160
1161    pub fn latest(&self) -> Option<&MessageTimeStamp> {
1162        self.latest.as_ref()
1163    }
1164}
1165
1166impl std::ops::AddAssign<Self> for UnreadInfo {
1167    fn add_assign(&mut self, rhs: Self) {
1168        self.unread_mark |= rhs.unread_mark;
1169        self.unread_messages += rhs.unread_messages;
1170        self.unread_notifications += rhs.unread_notifications;
1171        self.unread_mentions += rhs.unread_mentions;
1172        self.latest = self.latest.max(rhs.latest);
1173    }
1174}
1175
1176/// The [`OwnedUserId`]s for users with the given displayname in [`DisplayNameStore`].
1177#[derive(Default)]
1178struct DisplayNameUsers {
1179    /// Joined or invited users. Count towards username disambiguation.
1180    active: HashSet<OwnedUserId>,
1181
1182    /// Left and knocking users. Are always disambiguated.
1183    inactive: HashSet<OwnedUserId>,
1184}
1185
1186/// Track the display names for users and render any needed disambiguation for
1187/// those with overlapping names.
1188#[derive(Default)]
1189pub struct DisplayNameStore {
1190    /// The boolean is the same `is_active` field as the argument to [`Self::set`].
1191    by_ids: CompletionMap<OwnedUserId, (Option<String>, bool)>,
1192
1193    by_names: CompletionMap<String, DisplayNameUsers>,
1194}
1195
1196impl DisplayNameStore {
1197    /// Update the `HashSet` associated with a given displayname.
1198    ///
1199    /// Note that this *could* be done more elegantly using the Entry API, but
1200    /// is intentionally written in a way to avoid cloning conflicting display
1201    /// names.
1202    fn set_by_name(&mut self, user_id: OwnedUserId, name: &str, is_active: bool) {
1203        if let Some(existing) = self.by_names.get_mut(name) {
1204            if is_active {
1205                existing.active.insert(user_id);
1206            } else {
1207                existing.inactive.insert(user_id);
1208            }
1209        } else {
1210            let mut value = DisplayNameUsers::default();
1211            if is_active {
1212                value.active.insert(user_id);
1213            } else {
1214                value.inactive.insert(user_id);
1215            }
1216            self.by_names.insert(name.to_owned(), value);
1217        }
1218    }
1219
1220    /// Track a new user ID to displayname mapping, or unset any existing ones. `is_active` tracks,
1221    /// whether the user is an active member (invited or joined) or not.
1222    pub fn set(&mut self, user_id: OwnedUserId, name: Option<String>, is_active: bool) {
1223        if let Some(name) = name.as_deref() {
1224            self.set_by_name(user_id.clone(), name, is_active);
1225        }
1226
1227        if self
1228            .by_ids
1229            .get(&user_id)
1230            .is_some_and(|(n, a)| *n == name && *a == is_active)
1231        {
1232            // nothing to do
1233            return;
1234        }
1235
1236        let previous = self.by_ids.insert(user_id.to_owned(), (name, is_active));
1237
1238        let Some((Some(name), was_active)) = previous else {
1239            // no previous entry in `self.by_names` to remove
1240            return;
1241        };
1242
1243        let Some(users) = self.by_names.get_mut(&name) else {
1244            return;
1245        };
1246
1247        if was_active {
1248            users.active.remove(&user_id);
1249        } else {
1250            users.inactive.remove(&user_id);
1251        }
1252
1253        if users.active.is_empty() && users.inactive.is_empty() {
1254            self.by_names.remove(&name);
1255        }
1256    }
1257
1258    pub fn get<'a>(&'a self, user_id: &UserId) -> Option<Cow<'a, str>> {
1259        let (displayname, is_active) = self.by_ids.get(user_id)?;
1260        let displayname = displayname.as_ref()?;
1261        let users = self.by_names.get(displayname)?;
1262
1263        if !users.active.contains(user_id) && !users.inactive.contains(user_id) {
1264            // Internal consistency error? Assume no display name:
1265            return None;
1266        }
1267
1268        // Inactive members are always assumed to be ambiguous.
1269        if *is_active && users.active.len() == 1 {
1270            // Unambiguous!
1271            return Some(Cow::Borrowed(displayname.as_str()));
1272        }
1273
1274        // Ambiguous username, so include unique user ID:
1275        Some(Cow::Owned(format!("{displayname} ({user_id})")))
1276    }
1277
1278    pub fn complete_mention(&self, prefix: &str) -> Vec<String> {
1279        // spec says to mention with display name in anchor text
1280        let mut users: BTreeSet<_> = self
1281            .by_names
1282            .complete(prefix.strip_prefix('@').unwrap_or(prefix))
1283            .into_iter()
1284            .flat_map(|name| {
1285                let users = self.by_names.get(&name).unwrap();
1286                users.active.iter().map(move |id| format!("[{name}][{}]", id))
1287            })
1288            .collect();
1289
1290        users.extend(self.by_ids.complete(prefix).into_iter().map(|id| {
1291            let name = self
1292                .by_ids
1293                .get(&id)
1294                .and_then(|(name, _)| name.as_deref())
1295                .unwrap_or(id.as_str());
1296            format!("[{}][{}]", name, id)
1297        }));
1298
1299        users.into_iter().collect()
1300    }
1301}
1302
1303bitflags::bitflags! {
1304    /// Additional information about a room.
1305    #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
1306    pub struct RoomInfoFlags: u32 {
1307        /// No flags specified.
1308        const NONE = 0b00000000;
1309
1310        /// All notifications for this room have been muted.
1311        const MUTED = 0b00000001;
1312
1313        /// Non-mention/keyword notifications for this room have been muted.
1314        const CALMED = 0b00000010;
1315    }
1316}
1317
1318/// Information about room's the user's joined.
1319pub struct RoomInfo {
1320    /// The display name for this room.
1321    pub name: Option<String>,
1322
1323    /// The tags placed on this room.
1324    pub tags: Option<Tags>,
1325
1326    pub flags: RoomInfoFlags,
1327
1328    /// A map of event IDs to where they are stored in this struct.
1329    pub keys: HashMap<OwnedEventId, EventLocation>,
1330    pub echo_keys: HashMap<OwnedTransactionId, EchoLocation>,
1331
1332    /// The messages loaded for this room.
1333    messages: Messages,
1334
1335    /// A map of read markers to display on different events.
1336    pub event_receipts: HashMap<ReceiptThread, HashMap<OwnedEventId, HashSet<OwnedUserId>>>,
1337    /// A map of the most recent read marker for each user.
1338    ///
1339    /// Every receipt in this map should also have an entry in [`event_receipts`](`Self::event_receipts`),
1340    /// however not every user has an entry. If a user's most recent receipt is
1341    /// older than the oldest loaded event, that user will not be included.
1342    pub user_receipts: HashMap<ReceiptThread, HashMap<OwnedUserId, OwnedEventId>>,
1343    /// A map of message identifiers to a map of reaction events.
1344    pub reactions: HashMap<OwnedEventId, MessageReactions>,
1345    /// A map of message identifiers to a list of edit events for message that are not yet cached.
1346    pub unloaded_edits: HashMap<OwnedEventId, MessageEdits>,
1347    /// A map of message identifiers to the aggregated data for a poll that hasn't been loaded.
1348    pub unloaded_polls: HashMap<OwnedEventId, UnloadedPoll>,
1349    pub unloaded_unstable_polls: HashMap<OwnedEventId, UnloadedUnstablePoll>,
1350
1351    /// A map of message identifiers to thread replies.
1352    threads: HashMap<OwnedEventId, Messages>,
1353
1354    /// Whether the scrollback for this room is currently being fetched.
1355    pub fetching: bool,
1356
1357    /// Whether all messages are loaded.
1358    pub reached_timeline_start: bool,
1359
1360    /// The time that we last fetched scrollback for this room.
1361    pub fetch_last: Option<Instant>,
1362
1363    /// Users currently typing in this room, and when we received notification of them doing so.
1364    pub users_typing: Option<(Instant, Vec<OwnedUserId>)>,
1365
1366    /// The display names for users in this room.
1367    pub display_names: DisplayNameStore,
1368
1369    /// The last time the room was rendered, used to detect if it is currently open.
1370    pub draw_last: Option<Instant>,
1371
1372    /// The room's pinned events, mirrored from the SDK's room state for rendering.
1373    pub pinned_events: Vec<OwnedEventId>,
1374
1375    /// Pinned events fetched for the `:pinned` window that aren't in the loaded scrollback.
1376    pub pinned_previews: HashMap<OwnedEventId, Message>,
1377
1378    /// How many times fetching each pinned event for the `:pinned` window has failed.
1379    pub pinned_failures: HashMap<OwnedEventId, u8>,
1380}
1381
1382impl Default for RoomInfo {
1383    fn default() -> Self {
1384        Self {
1385            messages: Messages::new(ReceiptThread::Main),
1386
1387            name: Default::default(),
1388            tags: Default::default(),
1389            keys: Default::default(),
1390            flags: Default::default(),
1391            echo_keys: Default::default(),
1392            event_receipts: Default::default(),
1393            user_receipts: Default::default(),
1394            reactions: Default::default(),
1395            threads: Default::default(),
1396            fetching: Default::default(),
1397            reached_timeline_start: false,
1398            fetch_last: Default::default(),
1399            users_typing: Default::default(),
1400            display_names: Default::default(),
1401            draw_last: Default::default(),
1402            pinned_events: Default::default(),
1403            pinned_previews: Default::default(),
1404            pinned_failures: Default::default(),
1405            unloaded_edits: Default::default(),
1406            unloaded_polls: Default::default(),
1407            unloaded_unstable_polls: Default::default(),
1408        }
1409    }
1410}
1411
1412impl RoomInfo {
1413    pub fn get_thread(&self, root: Option<&EventId>) -> Option<&Messages> {
1414        if let Some(thread_root) = root {
1415            self.threads.get(thread_root)
1416        } else {
1417            Some(&self.messages)
1418        }
1419    }
1420
1421    pub fn get_thread_mut(&mut self, root: Option<OwnedEventId>) -> &mut Messages {
1422        if let Some(thread_root) = root {
1423            self.threads
1424                .entry(thread_root.clone())
1425                .or_insert_with(|| Messages::thread(thread_root))
1426        } else {
1427            &mut self.messages
1428        }
1429    }
1430
1431    /// Get the event for the last message in a thread (or the thread root if there are no
1432    /// in-thread replies yet).
1433    ///
1434    /// This does not apply edits to the returned event.
1435    ///
1436    /// This returns `None` if the event identifier isn't in the room.
1437    pub fn get_thread_last<'a>(
1438        &'a self,
1439        thread_root: &OwnedEventId,
1440    ) -> Option<&'a OriginalRoomMessageEvent> {
1441        let last = self.threads.get(thread_root).and_then(|t| Some(t.last_key_value()?.1));
1442
1443        let msg = if let Some(last) = last {
1444            &last.event
1445        } else if let EventLocation::Message(_, key) = self.keys.get(thread_root)? {
1446            let msg = self.messages.get(key)?;
1447            &msg.event
1448        } else {
1449            return None;
1450        };
1451
1452        if let MessageEvent::Original(ev, _) = &msg {
1453            Some(ev)
1454        } else {
1455            None
1456        }
1457    }
1458
1459    /// Whether a message is pinned to the room.
1460    pub fn is_pinned(&self, event_id: &EventId) -> bool {
1461        self.pinned_events.iter().any(|id| id == event_id)
1462    }
1463
1464    /// Get a pinned message, from the scrollback if it's loaded or else from the fetched previews.
1465    pub fn get_pinned(&self, event_id: &EventId) -> Option<&Message> {
1466        self.get_event(event_id).or_else(|| self.pinned_previews.get(event_id))
1467    }
1468
1469    /// Whether fetching a pinned event has failed too many times to keep retrying.
1470    pub fn pinned_unavailable(&self, event_id: &EventId) -> bool {
1471        self.pinned_failures
1472            .get(event_id)
1473            .is_some_and(|failures| *failures >= PINNED_FETCH_ATTEMPTS)
1474    }
1475
1476    /// Record the result of fetching a pinned event for the `:pinned` window.
1477    pub fn insert_pinned(&mut self, event_id: OwnedEventId, msg: Option<Message>) {
1478        match msg {
1479            Some(msg) => {
1480                self.pinned_failures.remove(&event_id);
1481                self.pinned_previews.insert(event_id, msg);
1482            },
1483            None => {
1484                let failures = self.pinned_failures.entry(event_id).or_default();
1485                *failures = failures.saturating_add(1);
1486            },
1487        }
1488    }
1489
1490    /// Pinned events that still need to be fetched for the `:pinned` window.
1491    pub fn missing_pinned(&self) -> Vec<OwnedEventId> {
1492        self.pinned_events
1493            .iter()
1494            .filter(|id| self.get_pinned(id).is_none() && !self.pinned_unavailable(id))
1495            .cloned()
1496            .collect()
1497    }
1498
1499    /// Get where a loaded message lives, as its thread root and key.
1500    pub fn get_message_location(
1501        &self,
1502        event_id: &EventId,
1503    ) -> Option<(Option<&EventId>, &MessageKey)> {
1504        let loc = self.keys.get(event_id)?;
1505
1506        Some((loc.to_thread_root(), loc.to_message_key()?))
1507    }
1508
1509    pub fn get_receipt_thread(&self, event_id: &EventId) -> Option<ReceiptThread> {
1510        match self.keys.get(event_id)? {
1511            EventLocation::Message(None, _) => Some(ReceiptThread::Main),
1512            EventLocation::Message(Some(root), _) => Some(ReceiptThread::Thread(root.clone())),
1513            _ => None,
1514        }
1515    }
1516
1517    /// Get the reactions and their counts for a message.
1518    pub fn get_reactions(
1519        &self,
1520        event_id: &EventId,
1521    ) -> Vec<(&str, Vec<&UserId>, &Option<MediaSource>)> {
1522        if let Some(reacts) = self.reactions.get(event_id) {
1523            let mut reactions = BTreeMap::new();
1524
1525            for (key, user, source) in reacts.values() {
1526                let react =
1527                    reactions.entry(key.as_str()).or_insert_with(|| (BTreeSet::new(), source));
1528                react.0.insert(user.deref());
1529            }
1530
1531            reactions
1532                .into_iter()
1533                .map(|(key, (users, source))| (key, users.into_iter().collect::<Vec<_>>(), source))
1534                .collect::<Vec<_>>()
1535        } else {
1536            vec![]
1537        }
1538    }
1539
1540    pub fn get_reaction_images(&self, event_id: &EventId) -> impl Iterator<Item = &MediaSource> {
1541        self.reactions
1542            .get(event_id)
1543            .map(HashMap::iter)
1544            .unwrap_or_default()
1545            .filter_map(|(_, (_, _, source))| source.as_ref())
1546    }
1547
1548    /// Map an event identifier to its [MessageKey].
1549    pub fn get_message_key(&self, event_id: &EventId) -> Option<&MessageKey> {
1550        self.keys.get(event_id)?.to_message_key()
1551    }
1552
1553    /// Get an event for an identifier.
1554    pub fn get_event(&self, event_id: &EventId) -> Option<&Message> {
1555        let loc = self.keys.get(event_id)?;
1556
1557        let key = loc.to_message_key()?;
1558        let root = loc.to_thread_root();
1559
1560        self.get_thread(root)?.get(key)
1561    }
1562
1563    /// Get an event for an identifier as mutable.
1564    pub fn get_event_mut(&mut self, event_id: &EventId) -> Option<&mut Message> {
1565        let loc = self.keys.get(event_id)?.clone();
1566
1567        let key = loc.to_message_key()?;
1568        let root = loc.to_thread_root();
1569
1570        self.get_thread_mut(root.map(ToOwned::to_owned)).get_mut(key)
1571    }
1572
1573    /// Map an event identifier to its [`MessageKey`] and thread root.
1574    fn get_message_thread_key(
1575        &self,
1576        message_id: &MessageId,
1577    ) -> Option<(Option<&EventId>, &MessageKey)> {
1578        let event_id = match message_id {
1579            MessageId::Local(id) => {
1580                let loc = self.echo_keys.get(id)?;
1581                match loc {
1582                    EchoLocation::Message(root, key) => return Some((root.as_deref(), key)),
1583                    EchoLocation::Replaced(event_id) => event_id,
1584                }
1585            },
1586            MessageId::Origin(event_id) => event_id,
1587        };
1588
1589        let loc = self.keys.get(event_id)?;
1590
1591        Some((loc.to_thread_root(), loc.to_message_key()?))
1592    }
1593
1594    /// Get an event for an identifier.
1595    pub fn get_message(&self, message_id: &MessageId) -> Option<&Message> {
1596        let (root, key) = self.get_message_thread_key(message_id)?;
1597
1598        self.get_thread(root)?.get(key)
1599    }
1600
1601    /// Get an event for an identifier as mutable.
1602    pub fn get_message_mut(&mut self, message_id: &MessageId) -> Option<&mut Message> {
1603        let (root, key) = self.get_message_thread_key(message_id)?;
1604
1605        let root = root.map(ToOwned::to_owned);
1606        let key = key.to_owned();
1607
1608        self.get_thread_mut(root).get_mut(&key)
1609    }
1610
1611    pub fn redact(&mut self, ev: OriginalSyncRoomRedactionEvent) {
1612        let Some(redacts) = &ev.redacts else {
1613            return;
1614        };
1615
1616        match self.keys.get(redacts) {
1617            None => return,
1618            Some(EventLocation::Edit(msg_event_id, edit_key)) => {
1619                let edit_key = edit_key.clone();
1620                let msg_loc = self.keys.get(msg_event_id).cloned();
1621                if let Some(EventLocation::Message(thread, msg_key)) = msg_loc {
1622                    if let Some(msg) = self.get_thread_mut(thread).get_mut(&msg_key) {
1623                        msg.remove_edit(&edit_key);
1624                    }
1625                } else {
1626                    self.unloaded_edits
1627                        .get_mut(msg_event_id)
1628                        .and_then(|edits| edits.remove(&edit_key));
1629                }
1630
1631                if let Some(msg) = self.messages.get_mut(&edit_key) {
1632                    let ev = SyncRoomRedactionEvent::Original(ev);
1633                    msg.redact(ev);
1634                }
1635            },
1636            Some(EventLocation::Poll(poll_event_id, loc)) => {
1637                let poll_event_id = poll_event_id.to_owned();
1638                let loc = loc.to_owned();
1639                if let Some(Message { event, .. }) = self.get_event_mut(&poll_event_id) {
1640                    match event {
1641                        MessageEvent::Poll(poll) => poll.redact(&loc),
1642                        MessageEvent::UnstablePoll(poll) => poll.redact(&loc),
1643                        _ => (),
1644                    }
1645                } else if let Some(poll) = self.unloaded_unstable_polls.get_mut(&poll_event_id) {
1646                    poll.redact(&loc);
1647                }
1648            },
1649            Some(EventLocation::Message(None, key)) => {
1650                if let Some(msg) = self.messages.get_mut(key) {
1651                    let ev = SyncRoomRedactionEvent::Original(ev);
1652                    msg.redact(ev);
1653                }
1654            },
1655            Some(EventLocation::Message(Some(root), key)) => {
1656                if let Some(thread) = self.threads.get_mut(root) &&
1657                    let Some(msg) = thread.get_mut(key)
1658                {
1659                    let ev = SyncRoomRedactionEvent::Original(ev);
1660                    msg.redact(ev);
1661                }
1662            },
1663            Some(EventLocation::Reaction(event_id)) => {
1664                if let Some(reactions) = self.reactions.get_mut(event_id) {
1665                    reactions.remove(redacts);
1666                }
1667
1668                self.keys.remove(redacts);
1669            },
1670        }
1671    }
1672
1673    /// Insert a message with a [`EventLocation::Message`].
1674    fn insert_msglike(
1675        &mut self,
1676        event_id: OwnedEventId,
1677        thread_root: Option<OwnedEventId>,
1678        message: Message,
1679    ) {
1680        let sender = message.sender.clone();
1681
1682        let key = MessageKey { ts: message.timestamp, id: event_id.clone().into() };
1683        let loc = EventLocation::Message(thread_root.clone(), key.clone());
1684        self.keys.insert(event_id.clone(), loc);
1685
1686        let thread = self.get_thread_mut(thread_root);
1687        thread.insert_message(key, message);
1688        self.set_implicit_receipt(sender, event_id);
1689    }
1690
1691    /// Insert a reaction to a message.
1692    fn insert_reaction(&mut self, react: ReactionEvent, source: Option<MediaSource>) {
1693        let MessageLikeEvent::Original(react) = react else {
1694            return;
1695        };
1696        let rel_id = react.content.relates_to.event_id;
1697        let key = react.content.relates_to.key;
1698
1699        let message = self.reactions.entry(rel_id.clone()).or_default();
1700        let event_id = react.event_id;
1701        let user_id = react.sender;
1702
1703        message.insert(event_id.clone(), (key, user_id, source));
1704
1705        let loc = EventLocation::Reaction(rel_id);
1706        self.keys.insert(event_id, loc);
1707    }
1708
1709    /// Insert a sticker
1710    pub fn insert_sticker_with_preview(
1711        &mut self,
1712        sticker: StickerEvent,
1713        settings: &ApplicationSettings,
1714        previews: &mut PreviewManager,
1715    ) {
1716        let event_id = sticker.event_id().to_owned();
1717        let thread_root = match &sticker {
1718            MessageLikeEvent::Original(OriginalMessageLikeEvent {
1719                content:
1720                    StickerEventContent {
1721                        relates_to: Some(Relation::Thread(Thread { event_id, .. })),
1722                        ..
1723                    },
1724                ..
1725            }) => Some(event_id.to_owned()),
1726            _ => None,
1727        };
1728
1729        if let MessageLikeEvent::Original(OriginalMessageLikeEvent {
1730            content: StickerEventContent { source, .. },
1731            ..
1732        }) = &sticker &&
1733            settings.tunables.image_preview.enabled
1734        {
1735            let source = source.clone().into();
1736            previews.register_preview(settings, &source, PreviewKind::Message);
1737        }
1738
1739        self.insert_msglike(event_id, thread_root, sticker.into());
1740    }
1741
1742    /// Insert a reaction to a message.
1743    pub fn insert_reaction_with_preview(
1744        &mut self,
1745        react: ReactionEvent,
1746        settings: &ApplicationSettings,
1747        previews: &mut PreviewManager,
1748    ) {
1749        let MessageLikeEvent::Original(ref orig_react) = react else {
1750            return;
1751        };
1752        let image_uri = OwnedMxcUri::from(orig_react.content.relates_to.key.as_str());
1753        let source = if image_uri.is_valid() && settings.tunables.image_preview.enabled {
1754            Some(MediaSource::Plain(image_uri))
1755        } else {
1756            None
1757        };
1758
1759        if settings.tunables.image_preview.enabled &&
1760            let Some(source) = source.as_ref()
1761        {
1762            previews.register_preview(settings, source, PreviewKind::Reaction);
1763        }
1764
1765        self.insert_reaction(react, source);
1766    }
1767
1768    /// Insert the start of a poll.
1769    pub fn insert_poll_start(&mut self, poll: PollStartEvent) {
1770        let event_id = poll.event_id().to_owned();
1771        let key = MessageKey {
1772            ts: poll.origin_server_ts().into(),
1773            id: event_id.clone().into(),
1774        };
1775
1776        match poll {
1777            MessageLikeEvent::Original(ev) => {
1778                if let Some(Relation::Replacement(Replacement {
1779                    event_id: poll_event_id,
1780                    new_content,
1781                    ..
1782                })) = ev.content.relates_to
1783                {
1784                    let loc = EventLocation::Poll(
1785                        poll_event_id.to_owned(),
1786                        PollEventLocation::Replacement(key.clone()),
1787                    );
1788                    self.keys.insert(event_id.clone(), loc);
1789
1790                    if let Some(msg) = self.get_event_mut(&poll_event_id) {
1791                        let MessageEvent::Poll(poll) = &mut msg.event else {
1792                            tracing::warn!("encountered poll replacement for non-poll message");
1793                            return;
1794                        };
1795
1796                        poll.replacements.insert(key, new_content);
1797                    } else {
1798                        self.unloaded_polls
1799                            .entry(poll_event_id)
1800                            .or_default()
1801                            .replacements
1802                            .insert(key, new_content);
1803                    }
1804                } else {
1805                    let thread_root = match &ev.content.relates_to {
1806                        Some(Relation::Thread(Thread { event_id, .. })) => {
1807                            Some(event_id.to_owned())
1808                        },
1809                        _ => None,
1810                    };
1811
1812                    let unloaded = self.unloaded_polls.remove(&ev.event_id).unwrap_or_default();
1813                    let msg = MessageEvent::Poll(
1814                        Poll::new(ev.event_id, ev.sender.to_owned(), ev.content, unloaded).into(),
1815                    );
1816                    let msg = Message::new(msg, ev.sender, ev.origin_server_ts.into());
1817
1818                    self.insert_msglike(event_id, thread_root, msg);
1819                }
1820            },
1821            MessageLikeEvent::Redacted(ev) => {
1822                let message: Message = ev.into();
1823
1824                self.insert_msglike(event_id, None, message);
1825            },
1826        }
1827    }
1828
1829    /// Insert the start of a poll.
1830    pub fn insert_unstable_poll_start(&mut self, poll: UnstablePollStartEvent) {
1831        let event_id = poll.event_id().to_owned();
1832        let key = MessageKey {
1833            ts: poll.origin_server_ts().into(),
1834            id: event_id.clone().into(),
1835        };
1836
1837        match poll {
1838            MessageLikeEvent::Original(ev) => {
1839                match ev.content {
1840                    UnstablePollStartEventContent::New(content) => {
1841                        let thread_root = match &content.relates_to {
1842                            Some(RelationWithoutReplacement::Thread(Thread {
1843                                event_id, ..
1844                            })) => Some(event_id.to_owned()),
1845                            _ => None,
1846                        };
1847
1848                        let unloaded =
1849                            self.unloaded_unstable_polls.remove(&ev.event_id).unwrap_or_default();
1850                        let msg = MessageEvent::UnstablePoll(
1851                            UnstablePoll::new(ev.event_id, ev.sender.to_owned(), content, unloaded)
1852                                .into(),
1853                        );
1854                        let msg = Message::new(msg, ev.sender, ev.origin_server_ts.into());
1855
1856                        self.insert_msglike(event_id, thread_root, msg);
1857                    },
1858                    UnstablePollStartEventContent::Replacement(content) => {
1859                        let loc = EventLocation::Poll(
1860                            content.relates_to.event_id.to_owned(),
1861                            PollEventLocation::Replacement(key.clone()),
1862                        );
1863                        self.keys.insert(event_id.clone(), loc);
1864
1865                        if let Some(msg) = self.get_event_mut(&content.relates_to.event_id) {
1866                            let MessageEvent::UnstablePoll(poll) = &mut msg.event else {
1867                                tracing::warn!("encountered poll replacement for non-poll message");
1868                                return;
1869                            };
1870
1871                            poll.replacements.insert(key, content);
1872                        } else {
1873                            self.unloaded_unstable_polls
1874                                .entry(content.relates_to.event_id.to_owned())
1875                                .or_default()
1876                                .replacements
1877                                .insert(key, content);
1878                        }
1879                    },
1880                    _ => {
1881                        tracing::warn!("ignoring unknown unstable poll variant");
1882                    },
1883                }
1884            },
1885            MessageLikeEvent::Redacted(ev) => {
1886                let message: Message = ev.into();
1887
1888                self.insert_msglike(event_id, None, message);
1889            },
1890        }
1891    }
1892
1893    /// Insert an event that relates to a poll
1894    pub fn insert_poll_relation(&mut self, relation: PollRelation) {
1895        let event_id = relation.event_id().to_owned();
1896        let poll_event_id = relation.poll_event_id().to_owned();
1897
1898        let loc = if let Some(msg) = self.get_event_mut(&poll_event_id) {
1899            let MessageEvent::Poll(poll) = &mut msg.event else {
1900                tracing::warn!("encountered poll replacement for non-poll message");
1901                return;
1902            };
1903
1904            poll.insert_relation(relation)
1905        } else {
1906            self.unloaded_polls
1907                .entry(poll_event_id.to_owned())
1908                .or_default()
1909                .insert_relation(relation)
1910        };
1911
1912        self.keys.insert(event_id, EventLocation::Poll(poll_event_id, loc));
1913    }
1914
1915    /// Insert an event that relates to a poll
1916    pub fn insert_unstable_poll_relation(&mut self, relation: UnstablePollRelation) {
1917        let event_id = relation.event_id().to_owned();
1918        let poll_event_id = relation.poll_event_id().to_owned();
1919
1920        let loc = if let Some(msg) = self.get_event_mut(&poll_event_id) {
1921            let MessageEvent::UnstablePoll(poll) = &mut msg.event else {
1922                tracing::warn!("encountered poll replacement for non-poll message");
1923                return;
1924            };
1925
1926            poll.insert_relation(relation)
1927        } else {
1928            self.unloaded_unstable_polls
1929                .entry(poll_event_id.to_owned())
1930                .or_default()
1931                .insert_relation(relation)
1932        };
1933
1934        self.keys.insert(event_id, EventLocation::Poll(poll_event_id, loc));
1935    }
1936
1937    /// Insert an edit.
1938    fn insert_edit(
1939        &mut self,
1940        edit_msg: RoomMessageEvent,
1941        replacement: Replacement<RoomMessageEventContentWithoutRelation>,
1942    ) {
1943        let RoomMessageEvent::Original(edit_msg) = edit_msg else {
1944            return;
1945        };
1946        let edit_key = MessageKey {
1947            ts: edit_msg.origin_server_ts.into(),
1948            id: edit_msg.event_id.clone().into(),
1949        };
1950        let msg_loc = self.keys.get(&replacement.event_id).cloned();
1951
1952        if let Some(EventLocation::Message(thread, key)) = msg_loc {
1953            // The edited message is already loaded in cache
1954            let Some(msg) = self.get_thread_mut(thread).get_mut(&key) else {
1955                return;
1956            };
1957            msg.insert_edit(edit_key.clone(), replacement.new_content);
1958        } else {
1959            // The edited message is not yet loaded
1960            let entry = self.unloaded_edits.entry(replacement.event_id.clone());
1961            entry.or_default().insert(edit_key.clone(), replacement.new_content);
1962        }
1963
1964        let loc = EventLocation::Edit(replacement.event_id.clone(), edit_key.clone());
1965        self.keys.insert(edit_msg.event_id.clone(), loc);
1966    }
1967
1968    pub fn insert_any_state(&mut self, msg: AnySyncStateEvent) {
1969        let event_id = msg.event_id().to_owned();
1970
1971        self.insert_msglike(event_id, None, msg.into());
1972    }
1973
1974    /// Inserts events that couldn't be decrypted into the scrollback.
1975    pub fn insert_encrypted(&mut self, msg: RoomEncryptedEvent) {
1976        let event_id = msg.event_id().to_owned();
1977
1978        let thread_root = if let Some(EncryptedRelation::Thread(Thread { event_id, .. })) =
1979            msg.as_original().and_then(|ev| ev.content.relates_to.as_ref())
1980        {
1981            Some(event_id.to_owned())
1982        } else {
1983            None
1984        };
1985
1986        self.insert_msglike(event_id, thread_root, msg.into());
1987    }
1988
1989    /// Insert a new message.
1990    fn insert_message(&mut self, msg: RoomMessageEvent) {
1991        let event_id = msg.event_id().to_owned();
1992        let thread_root = match msg.as_original().and_then(|ev| ev.content.relates_to.as_ref()) {
1993            Some(Relation::Replacement(repl)) => {
1994                let repl = repl.to_owned();
1995                self.insert_edit(msg, repl);
1996                return;
1997            },
1998            Some(Relation::Thread(Thread { event_id, .. })) => Some(event_id.to_owned()),
1999            _ => None,
2000        };
2001
2002        let mut message: Message = msg.into();
2003        if let Some(edits) = self.unloaded_edits.remove(&event_id) {
2004            message.set_edits(edits);
2005        }
2006
2007        self.insert_msglike(event_id, thread_root, message);
2008    }
2009
2010    /// Insert a new message event, and prepare for image-preview if it has an image attachment.
2011    pub fn insert_with_preview(
2012        &mut self,
2013        ev: RoomMessageEvent,
2014        settings: &ApplicationSettings,
2015        previews: &mut PreviewManager,
2016    ) {
2017        if let MessageLikeEvent::Original(OriginalMessageLikeEvent {
2018            content: RoomMessageEventContent { msgtype: MessageType::Image(c), .. },
2019            ..
2020        }) = &ev &&
2021            settings.tunables.image_preview.enabled
2022        {
2023            previews.register_preview(settings, &c.source, PreviewKind::Message)
2024        }
2025
2026        self.insert_message(ev);
2027    }
2028
2029    /// Indicates whether this room has unread messages.
2030    pub fn unreads(&self, room: &matrix_sdk::Room) -> UnreadInfo {
2031        let last_message = self
2032            .messages
2033            .iter()
2034            .rev()
2035            .find(|(_, msg)| !matches!(&msg.event, MessageEvent::State(..)));
2036
2037        UnreadInfo {
2038            unread_mark: room.is_marked_unread(),
2039            unread_messages: room.num_unread_messages(),
2040            unread_notifications: room.num_unread_notifications(),
2041            unread_mentions: room.num_unread_mentions(),
2042            latest: last_message.map(|(key, _)| key.ts.to_owned()),
2043        }
2044    }
2045
2046    /// Indicates whether we've recently fetched scrollback for this room.
2047    pub fn recently_fetched(&self) -> bool {
2048        self.fetch_last.is_some_and(|i| i.elapsed() < ROOM_FETCH_DEBOUNCE)
2049    }
2050
2051    fn clear_receipt(&mut self, thread: &ReceiptThread, user_id: &OwnedUserId) -> Option<()> {
2052        let old_user_receipts = self.user_receipts.get_mut(thread);
2053        let old_event_id = old_user_receipts.and_then(|rs| rs.remove(user_id))?;
2054        let old_thread = self.event_receipts.get_mut(thread)?;
2055        let old_receipts = old_thread.get_mut(&old_event_id)?;
2056        old_receipts.remove(user_id);
2057
2058        if old_receipts.is_empty() {
2059            old_thread.remove(&old_event_id);
2060        }
2061        if old_thread.is_empty() {
2062            self.event_receipts.remove(thread);
2063        }
2064
2065        None
2066    }
2067
2068    pub fn set_receipt(
2069        &mut self,
2070        thread: ReceiptThread,
2071        user_id: OwnedUserId,
2072        event_id: OwnedEventId,
2073    ) {
2074        if let Some(old_event_id) =
2075            self.user_receipts.get(&thread).and_then(|receipts| receipts.get(&user_id)) &&
2076            let (Some(old_key), Some(new_key)) =
2077                (self.receipt_key(old_event_id), self.receipt_key(&event_id)) &&
2078            new_key <= old_key
2079        {
2080            return;
2081        }
2082
2083        self.clear_receipt(&thread, &user_id);
2084        self.event_receipts(&thread, &event_id).insert(user_id.clone());
2085        self.user_receipts.entry(thread).or_default().insert(user_id, event_id);
2086    }
2087
2088    /// Get the users whose receipts currently point at the given event in the specified `thread`.
2089    fn event_receipts(
2090        &mut self,
2091        thread: &ReceiptThread,
2092        event_id: &EventId,
2093    ) -> &mut HashSet<OwnedUserId> {
2094        self.event_receipts
2095            .entry(thread.clone())
2096            .or_default()
2097            .entry(event_id.to_owned())
2098            .or_default()
2099    }
2100
2101    fn receipt_key(&self, event_id: &EventId) -> Option<&MessageKey> {
2102        match self.keys.get(event_id)? {
2103            EventLocation::Message(_, key) => Some(key),
2104            _ => None,
2105        }
2106    }
2107
2108    /// Whenever a user sends a message, we can consider that an effective update to their
2109    /// read receipt, even when their client isn't sending them to the room.
2110    ///
2111    /// While the Matrix specification doesn't explicitly mention "implicit receipts", this
2112    /// is effectively what is described by "Marking notifications as read",
2113    ///
2114    /// > When the user updates their read receipt (either by using the API or by sending an
2115    /// > event), notifications prior to and including that event MUST be marked as read.
2116    ///
2117    /// This method is called every time we insert a new message into the [RoomInfo], so that
2118    /// we show in the timeline that the user has now read up to the point where they sent
2119    /// a message.
2120    fn set_implicit_receipt(&mut self, user_id: OwnedUserId, event_id: OwnedEventId) {
2121        let Some(thread) = self.get_receipt_thread(&event_id) else {
2122            return;
2123        };
2124
2125        let current = self.user_receipts.get(&thread).and_then(|receipts| receipts.get(&user_id));
2126        let current_key = current.and_then(|event_id| self.receipt_key(event_id));
2127
2128        if current.is_some() && current_key.is_none() {
2129            // Do not set an implicit receipt if we have an explicit receipt that points
2130            // at an event whose information we don't have, since we need it to make sure
2131            // that we don't move the receipt backwards in the timeline.
2132            //
2133            // This event could technically be newer than the one the receipt currently
2134            // points at, but we can't be sure, so just trust what the user's receipt in
2135            // the room says to point at, and we'll update it once they send us a new one.
2136            //
2137            // This technically makes it possible for a user who previously sent room
2138            // receipts and then switched to just private receipts to not have their marker
2139            // moved with recent messages, but solving that would require us to force a
2140            // load of the event that every user's read marker points at.
2141            return;
2142        }
2143
2144        // If the user's client isn't thread-aware then make sure the implicit receipt
2145        // doesn't result in displaying a second read receipt after where their unthreaded
2146        // receipt is currently pointing at:
2147        self.clear_receipt(&ReceiptThread::Unthreaded, &user_id);
2148
2149        self.set_receipt(thread, user_id, event_id);
2150    }
2151
2152    /// This is called whenever the user has viewed the most recent message sent to a room or
2153    /// thread, so that we can update the read receipt on the homeserver.
2154    ///
2155    /// Note that the Matrix specification says:
2156    ///
2157    /// > Clients should send read receipts when there is some certainty that the event in
2158    /// > question has been displayed to the user. Simply receiving an event does not provide
2159    /// > enough certainty that the user has seen the event. The user SHOULD need to take some
2160    /// > action such as viewing the room that the event was sent to or dismissing a notification
2161    /// > in order for the event to count as “read”. Clients SHOULD NOT send read receipts for
2162    /// > events sent by their own user.
2163    pub fn fully_read(
2164        &mut self,
2165        room_id: OwnedRoomId,
2166        thread: ReceiptThread,
2167        worker: &Requester,
2168        settings: &ApplicationSettings,
2169        open_notifications: &mut HashMap<OwnedRoomId, Vec<NotificationHandle>>,
2170    ) {
2171        let user_id = &settings.profile.user_id;
2172
2173        let messages = match &thread {
2174            ReceiptThread::Main => self.get_thread(None),
2175            ReceiptThread::Thread(root) => self.get_thread(Some(root)),
2176            _ => None,
2177        };
2178
2179        let Some(messages) = messages else {
2180            return;
2181        };
2182
2183        let event_id = messages
2184            .iter()
2185            .filter(|(_, msg)| {
2186                // Handle the "do not send read receipts for our own events" part of the
2187                // specification quoted above.
2188                msg.sender != *user_id
2189            })
2190            .filter(|(_, msg)| {
2191                matches!(
2192                    msg.event,
2193                    MessageEvent::EncryptedOriginal(..) |
2194                        MessageEvent::EncryptedRedacted(..) |
2195                        MessageEvent::Original(..) |
2196                        MessageEvent::Redacted(..)
2197                )
2198            })
2199            .flat_map(|(_, msg)| msg.event.event_id())
2200            .next_back()
2201            .map(ToOwned::to_owned);
2202
2203        if let Some((_, msg)) = messages.last_key_value() &&
2204            let Some(event_id) = msg.event.event_id()
2205        {
2206            // Always update the local receipt info for this room so that we aren't reliant
2207            // on the homeserver echoing it back to us to update this and clear the trackbar:
2208            self.set_receipt(thread.clone(), user_id.clone(), event_id.to_owned());
2209        }
2210
2211        if let Some(event_id) = event_id {
2212            // Clear any desktop notifications for the room:
2213            open_notifications.remove(&room_id);
2214
2215            // Update the homeserver with the latest receipt:
2216            worker.send_receipt(room_id, thread, event_id, settings);
2217        }
2218    }
2219
2220    pub fn fully_read_all(
2221        &mut self,
2222        room_id: OwnedRoomId,
2223        worker: &Requester,
2224        settings: &ApplicationSettings,
2225        open_notifications: &mut HashMap<OwnedRoomId, Vec<NotificationHandle>>,
2226    ) {
2227        let threads: Vec<_> = self.threads.keys().map(|root| root.to_owned()).collect();
2228
2229        for thread in threads {
2230            self.fully_read(
2231                room_id.to_owned(),
2232                ReceiptThread::Thread(thread),
2233                worker,
2234                settings,
2235                open_notifications,
2236            );
2237        }
2238
2239        self.fully_read(room_id, ReceiptThread::Main, worker, settings, open_notifications);
2240    }
2241
2242    pub fn read_event_users<'a>(
2243        &'a self,
2244        thread: ReceiptThread,
2245        event_id: &'a EventId,
2246    ) -> impl Iterator<Item = &'a OwnedUserId> + 'a {
2247        self.event_receipts
2248            .get(&thread)
2249            .and_then(|rs| rs.get(event_id))
2250            .map(|read| read.iter())
2251            .unwrap_or_default()
2252    }
2253
2254    fn get_typers(&self) -> &[OwnedUserId] {
2255        if let Some((t, users)) = &self.users_typing {
2256            if t.elapsed() < Duration::from_secs(4) {
2257                return users.as_ref();
2258            } else {
2259                return &[];
2260            }
2261        } else {
2262            return &[];
2263        }
2264    }
2265
2266    fn get_typing_spans<'a>(&'a self, settings: &'a ApplicationSettings) -> Line<'a> {
2267        let typers = self.get_typers();
2268        let n = typers.len();
2269
2270        match n {
2271            0 => Line::from(vec![]),
2272            1 => {
2273                let user = settings.get_user_span(typers[0].as_ref(), self);
2274
2275                Line::from(vec![user, Span::from(" is typing...")])
2276            },
2277            2 => {
2278                let user1 = settings.get_user_span(typers[0].as_ref(), self);
2279                let user2 = settings.get_user_span(typers[1].as_ref(), self);
2280
2281                Line::from(vec![
2282                    user1,
2283                    Span::raw(" and "),
2284                    user2,
2285                    Span::from(" are typing..."),
2286                ])
2287            },
2288            n if n < 5 => Line::from("Several people are typing..."),
2289            _ => Line::from("Many people are typing..."),
2290        }
2291    }
2292
2293    /// Update typing information for this room.
2294    pub fn set_typing(&mut self, user_ids: Vec<OwnedUserId>) {
2295        self.users_typing = (Instant::now(), user_ids).into();
2296    }
2297
2298    /// Create a [Rect] that displays what users are typing.
2299    pub fn render_typing(
2300        &mut self,
2301        area: Rect,
2302        buf: &mut Buffer,
2303        settings: &ApplicationSettings,
2304    ) -> Rect {
2305        if area.height <= 2 || area.width <= 20 {
2306            return area;
2307        }
2308
2309        if !settings.tunables.typing_notice_display {
2310            // still keep one line blank, so `render_jump_to_recent` doesn't immediately hide the
2311            // last line in scrollback
2312            return Rect::new(area.x, area.y, area.width, area.height - 1);
2313        }
2314
2315        let top = Rect::new(area.x, area.y, area.width, area.height - 1);
2316        let bar = Rect::new(area.x, area.y + top.height, area.width, 1);
2317
2318        Paragraph::new(self.get_typing_spans(settings))
2319            .alignment(Alignment::Center)
2320            .render(bar, buf);
2321
2322        return top;
2323    }
2324
2325    /// Checks if a given user has reacted with the given emoji on the given event
2326    pub fn user_reactions_contains(
2327        &self,
2328        user_id: &UserId,
2329        event_id: &EventId,
2330        emoji: &str,
2331    ) -> bool {
2332        if let Some(reactions) = self.reactions.get(event_id) {
2333            reactions
2334                .values()
2335                .any(|(annotation, user, _)| annotation == emoji && user == user_id)
2336        } else {
2337            false
2338        }
2339    }
2340}
2341
2342/// Generate a [CompletionMap] for Emoji shortcodes.
2343fn emoji_map() -> CompletionMap<String, &'static Emoji> {
2344    let mut emojis = CompletionMap::default();
2345
2346    for emoji in emojis::iter() {
2347        for shortcode in emoji.shortcodes() {
2348            emojis.insert(shortcode.to_string(), emoji);
2349        }
2350    }
2351
2352    return emojis;
2353}
2354
2355/// Information about spaces the user's joined.
2356#[derive(Default)]
2357pub struct SpaceInfo {
2358    /// The space child events with content and `origin_server_ts`.
2359    pub children: HashMap<OwnedRoomId, (SpaceChildEventContent, MilliSecondsSinceUnixEpoch)>,
2360}
2361
2362/// Information gathered during server syncs about joined rooms.
2363#[derive(Default)]
2364pub struct SyncInfo {
2365    /// Spaces that the user is a member of.
2366    pub spaces: Vec<MatrixRoom>,
2367
2368    /// Rooms that the user is a member of.
2369    pub rooms: Vec<MatrixRoom>,
2370
2371    /// DMs that the user is a member of.
2372    pub dms: Vec<MatrixRoom>,
2373}
2374
2375impl SyncInfo {
2376    pub fn rooms(&self) -> impl Iterator<Item = &RoomId> {
2377        self.rooms.iter().map(|r| r.room_id())
2378    }
2379
2380    pub fn dms(&self) -> impl Iterator<Item = &RoomId> {
2381        self.dms.iter().map(|r| r.room_id())
2382    }
2383
2384    pub fn chats(&self) -> impl Iterator<Item = &RoomId> {
2385        self.rooms().chain(self.dms())
2386    }
2387}
2388
2389static MESSAGE_NEED_TTL: u8 = 30;
2390
2391/// How many failed fetches of a pinned event before the `:pinned` window stops retrying.
2392const PINNED_FETCH_ATTEMPTS: u8 = 10;
2393
2394#[derive(Debug, PartialEq)]
2395/// Load messages until the event is loaded or `ttl` loads are exceeded
2396pub struct MessageNeed {
2397    pub event_id: OwnedEventId,
2398    pub ttl: u8,
2399}
2400
2401#[derive(Default, Debug, PartialEq)]
2402pub struct Need {
2403    pub members: bool,
2404    pub pinned: bool,
2405    pub messages: Option<Vec<MessageNeed>>,
2406}
2407
2408/// Things that need loading for different rooms.
2409#[derive(Default, Debug)]
2410pub struct RoomNeeds {
2411    needs: HashMap<OwnedRoomId, Need>,
2412    previews: HashSet<OwnedRoomOrAliasId>,
2413}
2414
2415impl RoomNeeds {
2416    /// Mark a room for needing to load members.
2417    pub fn need_members(&mut self, room_id: OwnedRoomId) {
2418        self.needs.entry(room_id).or_default().members = true;
2419    }
2420
2421    /// Mark a room for needing to fetch its pinned events.
2422    pub fn need_pinned(&mut self, room_id: OwnedRoomId) {
2423        self.needs.entry(room_id).or_default().pinned = true;
2424    }
2425
2426    /// Mark a room for needing to load messages.
2427    pub fn need_messages(&mut self, room_id: OwnedRoomId) {
2428        self.needs.entry(room_id).or_default().messages.get_or_insert_default();
2429    }
2430
2431    /// Mark a room for needing to load messages until the given message is loaded or a retry limit
2432    /// is exceeded.
2433    pub fn need_message(&mut self, room_id: OwnedRoomId, event_id: OwnedEventId) {
2434        let messages = &mut self.needs.entry(room_id).or_default().messages.get_or_insert_default();
2435
2436        messages.push(MessageNeed { event_id, ttl: MESSAGE_NEED_TTL });
2437    }
2438
2439    pub fn need_messages_all(&mut self, room_id: OwnedRoomId, message_needs: Vec<MessageNeed>) {
2440        self.needs
2441            .entry(room_id)
2442            .or_default()
2443            .messages
2444            .get_or_insert_default()
2445            .extend(message_needs);
2446    }
2447
2448    /// Request the load of a room preview.
2449    pub fn need_preview(&mut self, room: OwnedRoomOrAliasId) {
2450        self.previews.insert(room);
2451    }
2452
2453    /// Return all requested room previews
2454    pub fn preview_needs(&mut self) -> impl Iterator<Item = OwnedRoomOrAliasId> {
2455        std::mem::take(&mut self.previews).into_iter()
2456    }
2457
2458    pub fn rooms(&self) -> usize {
2459        self.needs.len()
2460    }
2461}
2462
2463impl IntoIterator for RoomNeeds {
2464    type Item = (OwnedRoomId, Need);
2465    type IntoIter = IntoIter<OwnedRoomId, Need>;
2466
2467    fn into_iter(self) -> Self::IntoIter {
2468        self.needs.into_iter()
2469    }
2470}
2471
2472/// The main application state.
2473pub struct ChatStore {
2474    /// `:`-commands
2475    pub cmds: ProgramCommands,
2476
2477    /// Handle for communicating w/ the worker thread.
2478    pub worker: Requester,
2479
2480    /// Map of joined rooms.
2481    pub rooms: CompletionMap<OwnedRoomId, RoomInfo>,
2482
2483    /// Map of loaded room previews with their fetch time
2484    pub room_previews:
2485        HashMap<OwnedRoomOrAliasId, (Result<RoomPreview, matrix_sdk::Error>, Instant)>,
2486
2487    /// Cache of encountered `via` parameters in room links.
2488    ///
2489    /// This is stored here because this data is lost in the conversion to [IambId].
2490    pub room_via: HashMap<OwnedRoomOrAliasId, HashSet<OwnedServerName>>,
2491
2492    /// Map of joined spaces.
2493    pub spaces: HashMap<OwnedRoomId, SpaceInfo>,
2494
2495    /// Map of room aliases.
2496    pub aliases: CompletionMap<OwnedRoomAliasId, OwnedRoomId>,
2497
2498    /// Presence information for other users.
2499    pub presences: CompletionMap<OwnedUserId, PresenceState>,
2500
2501    /// In-progress and completed verifications.
2502    /// The map key is the `flow_id`.
2503    pub verifications: CompletionMap<String, VerificationRequest>,
2504
2505    /// Settings for the current profile loaded from config file.
2506    pub settings: ApplicationSettings,
2507
2508    /// Set of rooms that need more messages loaded in their scrollback.
2509    pub need_load: RoomNeeds,
2510
2511    /// [CompletionMap] of Emoji shortcodes.
2512    pub emojis: CompletionMap<String, &'static Emoji>,
2513
2514    /// Information gathered by the background thread.
2515    pub sync_info: SyncInfo,
2516
2517    /// Rendered image previews.
2518    pub previews: PreviewManager,
2519
2520    /// Last draw time, used to match with RoomInfo's draw_last.
2521    pub draw_curr: Option<Instant>,
2522
2523    /// Whether to ring the terminal bell on the next redraw.
2524    pub ring_bell: bool,
2525
2526    /// An error raised while drawing, shown in the message bar on the next redraw.
2527    pub draw_error: Option<String>,
2528
2529    /// Whether the application is currently focused
2530    pub focused: bool,
2531
2532    /// Collator for locale-aware text sorting.
2533    pub collator: feruca::Collator,
2534
2535    /// Notifications that should be dismissed when the user opens the room.
2536    pub open_notifications: HashMap<OwnedRoomId, Vec<NotificationHandle>>,
2537}
2538
2539impl ChatStore {
2540    /// Create a new [ChatStore].
2541    pub fn new(worker: Requester, settings: ApplicationSettings) -> IambResult<Self> {
2542        let previews = PreviewManager::new(&settings);
2543        let cmds = crate::commands::setup_commands(&settings.aliases)?;
2544
2545        let store = ChatStore {
2546            worker,
2547            settings,
2548            previews,
2549            cmds,
2550            emojis: emoji_map(),
2551
2552            collator: Default::default(),
2553            aliases: Default::default(),
2554            rooms: Default::default(),
2555            room_previews: Default::default(),
2556            room_via: Default::default(),
2557            spaces: Default::default(),
2558            presences: Default::default(),
2559            verifications: Default::default(),
2560            need_load: Default::default(),
2561            sync_info: Default::default(),
2562            draw_curr: None,
2563            ring_bell: false,
2564            draw_error: None,
2565            focused: true,
2566            open_notifications: Default::default(),
2567        };
2568
2569        Ok(store)
2570    }
2571
2572    /// Clear the `EventCache` for all rooms.
2573    ///
2574    /// This forces a re-fetch of the most recent messages in joined rooms afterwards,
2575    /// which makes sure that we re-fetch any missing events (such as those sent by
2576    /// recently unignored users that a re-fetch would make appear in the timeline).
2577    pub async fn clear_room_cache(&mut self, client: &Client) -> Result<(), IambError> {
2578        client.event_cache().clear_all_rooms().await?;
2579        for room in client.joined_rooms() {
2580            let room_id = room.room_id().to_owned();
2581            let room = self.rooms.get_or_default(room_id.clone());
2582            room.reached_timeline_start = false;
2583            self.need_load.need_messages(room_id.to_owned());
2584        }
2585        Ok(())
2586    }
2587
2588    /// Get a joined room.
2589    pub fn get_joined_room(&self, room_id: &RoomId) -> Option<MatrixRoom> {
2590        let room = self.worker.client.get_room(room_id)?;
2591
2592        if room.state() == MatrixRoomState::Joined {
2593            Some(room)
2594        } else {
2595            None
2596        }
2597    }
2598
2599    /// Get the alias for a room if it has one (and the client knows it).
2600    pub fn get_joined_room_alias(&self, room_id: &RoomId) -> Option<OwnedRoomAliasId> {
2601        self.worker.client.get_room(room_id).and_then(|r| r.canonical_alias())
2602    }
2603
2604    /// Get the title for a room.
2605    pub fn get_room_title(&self, room_id: &RoomId) -> String {
2606        self.rooms
2607            .get(room_id)
2608            .and_then(|i| i.name.as_ref())
2609            .map(String::from)
2610            .unwrap_or_else(|| "Untitled Matrix Room".to_string())
2611    }
2612
2613    /// Get the [RoomInfo] for a given room identifier.
2614    pub fn get_room_info(&mut self, room_id: OwnedRoomId) -> &mut RoomInfo {
2615        self.rooms.get_or_default(room_id)
2616    }
2617
2618    /// Set the name and tags for a room.
2619    pub fn set_room_info(
2620        &mut self,
2621        room_id: OwnedRoomId,
2622        name: String,
2623        tags: Option<Tags>,
2624        aliases: Vec<OwnedRoomAliasId>,
2625        flags: RoomInfoFlags,
2626    ) {
2627        for alias in aliases {
2628            self.aliases.insert(alias, room_id.clone());
2629        }
2630
2631        let info = self.rooms.get_or_default(room_id);
2632        info.name = name.into();
2633        info.flags = flags;
2634        info.tags = tags;
2635    }
2636}
2637
2638impl ApplicationStore for ChatStore {}
2639
2640#[derive(Clone, Debug, Eq, Hash, PartialEq)]
2641pub enum RoomView {
2642    /// The main timeline is shown.
2643    Main,
2644    /// A thread is shown.
2645    Thread(OwnedEventId),
2646    /// A single message is shown.
2647    Message(MessageId),
2648}
2649
2650impl From<Option<OwnedEventId>> for RoomView {
2651    fn from(thread: Option<OwnedEventId>) -> Self {
2652        match thread {
2653            Some(thread) => Self::Thread(thread),
2654            None => Self::Main,
2655        }
2656    }
2657}
2658
2659impl From<Option<&OwnedEventId>> for RoomView {
2660    fn from(thread: Option<&OwnedEventId>) -> Self {
2661        match thread {
2662            Some(thread) => Self::Thread(thread.to_owned()),
2663            None => Self::Main,
2664        }
2665    }
2666}
2667
2668/// Identified used to track window content.
2669#[derive(Clone, Debug, Eq, Hash, PartialEq)]
2670pub enum IambId {
2671    /// A Matrix room, with an item that is shown.
2672    Room(OwnedRoomOrAliasId, RoomView),
2673
2674    /// The `:dms` window.
2675    DirectList,
2676
2677    /// The `:members` window for a given Matrix room.
2678    MemberList(OwnedRoomId),
2679
2680    /// The `:pinned` window for a given Matrix room.
2681    PinnedList(OwnedRoomId),
2682
2683    /// The `:rooms` window.
2684    RoomList,
2685
2686    /// The `:spaces` window.
2687    SpaceList,
2688
2689    /// The `:spaces toplevel` window.
2690    ToplevelSpaceList,
2691
2692    /// The `:verify` window.
2693    VerifyList,
2694
2695    /// The `:welcome` window.
2696    Welcome,
2697
2698    /// The `:chats` window.
2699    ChatList,
2700
2701    /// The `:unreads` window.
2702    UnreadList,
2703
2704    /// The `:mentions` window.
2705    MentionsList,
2706
2707    /// The `:invites` window.
2708    InvitesList,
2709}
2710
2711impl Display for IambId {
2712    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2713        match self {
2714            IambId::Room(alias, RoomView::Main) => {
2715                let encoded = percent_encode(alias.as_bytes(), NON_ALPHANUMERIC);
2716                write!(f, "iamb://room/{encoded}")
2717            },
2718            IambId::Room(alias, RoomView::Thread(thread)) => {
2719                let encoded = percent_encode(alias.as_bytes(), NON_ALPHANUMERIC);
2720                write!(f, "iamb://room/{encoded}/threads/{thread}")
2721            },
2722            IambId::Room(alias, RoomView::Message(message)) => {
2723                let encoded = percent_encode(alias.as_bytes(), NON_ALPHANUMERIC);
2724                write!(f, "iamb://room/{encoded}/messages/{message}")
2725            },
2726            IambId::MemberList(room_id) => {
2727                write!(f, "iamb://members/{room_id}")
2728            },
2729            IambId::PinnedList(room_id) => {
2730                write!(f, "iamb://room/{room_id}/pinned")
2731            },
2732            IambId::DirectList => f.write_str("iamb://dms"),
2733            IambId::RoomList => f.write_str("iamb://rooms"),
2734            IambId::SpaceList => f.write_str("iamb://spaces"),
2735            IambId::ToplevelSpaceList => f.write_str("iamb://spaces/toplevel"),
2736            IambId::VerifyList => f.write_str("iamb://verify"),
2737            IambId::Welcome => f.write_str("iamb://welcome"),
2738            IambId::ChatList => f.write_str("iamb://chats"),
2739            IambId::UnreadList => f.write_str("iamb://unreads"),
2740            IambId::MentionsList => f.write_str("iamb://mentions"),
2741            IambId::InvitesList => f.write_str("iamb://invites"),
2742        }
2743    }
2744}
2745
2746impl ApplicationWindowId for IambId {}
2747
2748impl Serialize for IambId {
2749    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2750    where
2751        S: Serializer,
2752    {
2753        serializer.serialize_str(&self.to_string())
2754    }
2755}
2756
2757impl<'de> Deserialize<'de> for IambId {
2758    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2759    where
2760        D: Deserializer<'de>,
2761    {
2762        deserializer.deserialize_str(IambIdVisitor)
2763    }
2764}
2765
2766/// [serde] visitor for deserializing [IambId].
2767struct IambIdVisitor;
2768
2769impl Visitor<'_> for IambIdVisitor {
2770    type Value = IambId;
2771
2772    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2773        formatter.write_str("a valid window URL")
2774    }
2775
2776    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
2777    where
2778        E: SerdeError,
2779    {
2780        let Ok(url) = Url::parse(value) else {
2781            return Err(E::custom("Invalid iamb window URL"));
2782        };
2783
2784        if url.scheme() != "iamb" {
2785            return Err(E::custom("Invalid iamb window URL"));
2786        }
2787
2788        match url.domain() {
2789            Some("room") => {
2790                let Some(path) = url.path_segments() else {
2791                    return Err(E::custom("Invalid members window URL"));
2792                };
2793
2794                match *path.collect::<Vec<_>>().as_slice() {
2795                    [alias] => {
2796                        let decoded = percent_decode(alias.as_bytes()).decode_utf8_lossy();
2797                        let Ok(room_id) = OwnedRoomOrAliasId::try_from(decoded.as_ref()) else {
2798                            return Err(E::custom(format!("Invalid room identifier: {decoded:?}")));
2799                        };
2800
2801                        Ok(IambId::Room(room_id, RoomView::Main))
2802                    },
2803                    [alias, "threads", thread_root] => {
2804                        let decoded = percent_decode(alias.as_bytes()).decode_utf8_lossy();
2805                        let Ok(room_id) = OwnedRoomOrAliasId::try_from(decoded.as_ref()) else {
2806                            return Err(E::custom("Invalid room identifier: {decoded:?}"));
2807                        };
2808
2809                        let Ok(thread_root) = OwnedEventId::try_from(thread_root) else {
2810                            return Err(E::custom("Invalid thread root identifier"));
2811                        };
2812
2813                        Ok(IambId::Room(room_id, RoomView::Thread(thread_root)))
2814                    },
2815                    [alias, "messages", message] => {
2816                        let decoded = percent_decode(alias.as_bytes()).decode_utf8_lossy();
2817                        let Ok(room_id) = OwnedRoomOrAliasId::try_from(decoded.as_ref()) else {
2818                            return Err(E::custom("Invalid room identifier: {decoded:?}"));
2819                        };
2820
2821                        let message_id = OwnedEventId::try_from(message)
2822                            .map(Into::into)
2823                            .unwrap_or_else(|_| OwnedTransactionId::from(message).into());
2824
2825                        Ok(IambId::Room(room_id, RoomView::Message(message_id)))
2826                    },
2827                    [room_id, "pinned"] => {
2828                        let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
2829                            return Err(E::custom("Invalid room identifier"));
2830                        };
2831
2832                        Ok(IambId::PinnedList(room_id))
2833                    },
2834                    _ => return Err(E::custom("Invalid iamb window URL")),
2835                }
2836            },
2837            Some("members") => {
2838                let Some(path) = url.path_segments() else {
2839                    return Err(E::custom("Invalid members window URL"));
2840                };
2841
2842                let &[room_id] = path.collect::<Vec<_>>().as_slice() else {
2843                    return Err(E::custom("Invalid members window URL"));
2844                };
2845
2846                let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
2847                    return Err(E::custom("Invalid room identifier"));
2848                };
2849
2850                Ok(IambId::MemberList(room_id))
2851            },
2852            Some("dms") => {
2853                if url.path() != "" {
2854                    return Err(E::custom("iamb://dms takes no path"));
2855                }
2856
2857                Ok(IambId::DirectList)
2858            },
2859            Some("rooms") => {
2860                if url.path() != "" {
2861                    return Err(E::custom("iamb://rooms takes no path"));
2862                }
2863
2864                Ok(IambId::RoomList)
2865            },
2866            Some("spaces") => {
2867                if url.path() == "toplevel" {
2868                    return Ok(IambId::ToplevelSpaceList);
2869                }
2870
2871                if url.path() != "" {
2872                    return Err(E::custom("Invalid iamb window URL"));
2873                }
2874
2875                Ok(IambId::SpaceList)
2876            },
2877            Some("verify") => {
2878                if url.path() != "" {
2879                    return Err(E::custom("iamb://verify takes no path"));
2880                }
2881
2882                Ok(IambId::VerifyList)
2883            },
2884            Some("welcome") => {
2885                if url.path() != "" {
2886                    return Err(E::custom("iamb://welcome takes no path"));
2887                }
2888
2889                Ok(IambId::Welcome)
2890            },
2891            Some("chats") => {
2892                if url.path() != "" {
2893                    return Err(E::custom("iamb://chats takes no path"));
2894                }
2895
2896                Ok(IambId::ChatList)
2897            },
2898            Some("unreads") => {
2899                if url.path() != "" {
2900                    return Err(E::custom("iamb://unreads takes no path"));
2901                }
2902
2903                Ok(IambId::UnreadList)
2904            },
2905            Some("mentions") => {
2906                if url.path() != "" {
2907                    return Err(E::custom("iamb://mentions takes no path"));
2908                }
2909
2910                Ok(IambId::MentionsList)
2911            },
2912            Some("invites") => {
2913                if url.path() != "" {
2914                    return Err(E::custom("iamb://invites takes no path"));
2915                }
2916
2917                Ok(IambId::InvitesList)
2918            },
2919            Some(s) => Err(E::custom(format!("{s:?} is not a valid window"))),
2920            None => Err(E::custom("Invalid iamb window URL")),
2921        }
2922    }
2923}
2924
2925/// Which part of the room window's UI is focused.
2926#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
2927pub enum RoomFocus {
2928    /// The scrollback for a room window is focused.
2929    Scrollback,
2930
2931    /// The message bar for a room window is focused.
2932    MessageBar,
2933}
2934
2935impl RoomFocus {
2936    /// Whether this is [RoomFocus::Scrollback].
2937    pub fn is_scrollback(&self) -> bool {
2938        matches!(self, RoomFocus::Scrollback)
2939    }
2940
2941    /// Whether this is [RoomFocus::MessageBar].
2942    pub fn is_msgbar(&self) -> bool {
2943        matches!(self, RoomFocus::MessageBar)
2944    }
2945
2946    pub fn toggle(&mut self) {
2947        *self = match self {
2948            RoomFocus::MessageBar => RoomFocus::Scrollback,
2949            RoomFocus::Scrollback => RoomFocus::MessageBar,
2950        };
2951    }
2952}
2953
2954/// Identifiers used to track where a mark was placed.
2955///
2956/// While this is the "buffer identifier" for the mark,
2957/// not all of these are necessarily actual buffers.
2958#[derive(Clone, Debug, Eq, Hash, PartialEq)]
2959pub enum IambBufferId {
2960    /// The command bar buffer.
2961    Command(CommandType),
2962
2963    /// The message buffer or a specific message in a room.
2964    Room(OwnedRoomId, RoomView, RoomFocus),
2965
2966    /// The `:dms` window.
2967    DirectList,
2968
2969    /// The `:members` window for a room.
2970    MemberList(OwnedRoomId),
2971
2972    /// The `:pinned` window for a room.
2973    PinnedList(OwnedRoomId),
2974
2975    /// The `:rooms` window.
2976    RoomList,
2977
2978    /// The `:spaces` window.
2979    SpaceList,
2980
2981    /// The `:spaces toplevel` window.
2982    ToplevelSpaceList,
2983
2984    /// The `:verify` window.
2985    VerifyList,
2986
2987    /// The buffer for the `:rooms` window.
2988    Welcome,
2989
2990    /// The `:chats` window.
2991    ChatList,
2992
2993    /// The `:unreads` window.
2994    UnreadList,
2995
2996    /// The `:mentions` window.
2997    MentionsList,
2998
2999    /// The `:invites` window.
3000    InvitesList,
3001}
3002
3003impl IambBufferId {
3004    /// Get the identifier for the window that contains this buffer.
3005    pub fn to_window(&self) -> Option<IambId> {
3006        let id = match self {
3007            IambBufferId::Command(_) => return None,
3008            IambBufferId::Room(room, view, _) => IambId::Room(room.clone().into(), view.clone()),
3009            IambBufferId::DirectList => IambId::DirectList,
3010            IambBufferId::MemberList(room) => IambId::MemberList(room.clone()),
3011            IambBufferId::PinnedList(room) => IambId::PinnedList(room.clone()),
3012            IambBufferId::RoomList => IambId::RoomList,
3013            IambBufferId::SpaceList => IambId::SpaceList,
3014            IambBufferId::ToplevelSpaceList => IambId::ToplevelSpaceList,
3015            IambBufferId::VerifyList => IambId::VerifyList,
3016            IambBufferId::Welcome => IambId::Welcome,
3017            IambBufferId::ChatList => IambId::ChatList,
3018            IambBufferId::UnreadList => IambId::UnreadList,
3019            IambBufferId::MentionsList => IambId::MentionsList,
3020            IambBufferId::InvitesList => IambId::InvitesList,
3021        };
3022
3023        Some(id)
3024    }
3025}
3026
3027impl ApplicationContentId for IambBufferId {}
3028
3029impl ApplicationInfo for IambInfo {
3030    type Error = IambError;
3031    type Store = ChatStore;
3032    type Action = IambAction;
3033    type WindowId = IambId;
3034    type ContentId = IambBufferId;
3035
3036    fn content_of_command(ct: CommandType) -> IambBufferId {
3037        IambBufferId::Command(ct)
3038    }
3039}
3040
3041#[cfg(test)]
3042pub mod tests {
3043    use super::*;
3044
3045    use std::iter::FromIterator as _;
3046
3047    use matrix_sdk::ruma::events::reaction::ReactionEventContent;
3048    use matrix_sdk::ruma::events::relation::Annotation;
3049    use matrix_sdk::ruma::{MilliSecondsSinceUnixEpoch, owned_event_id, owned_user_id};
3050    use pretty_assertions::assert_eq;
3051    use ratatui::style::Color;
3052    use serde_json::{Map, Value};
3053
3054    use crate::tests::*;
3055
3056    fn mock_room_message_event(
3057        content: RoomMessageEventContent,
3058        sender: OwnedUserId,
3059        key: MessageKey,
3060    ) -> RoomMessageEvent {
3061        let message = mock_room1_message(content, sender, key);
3062        let MessageEvent::Original(event, _) = message.event else {
3063            unreachable!("mock_room1_message always returns an original room message")
3064        };
3065
3066        MessageLikeEvent::Original(*event)
3067    }
3068
3069    fn create_reaction_event(
3070        content: &ReactionEventContent,
3071        event_id: &str,
3072        sender: &str,
3073    ) -> ReactionEvent {
3074        serde_json::from_value(Value::Object(Map::from_iter([
3075            ("type".to_owned(), Value::String("m.reaction".into())),
3076            ("content".to_owned(), serde_json::to_value(content).unwrap()),
3077            ("event_id".to_owned(), serde_json::to_value(event_id).unwrap()),
3078            ("sender".to_owned(), Value::String(sender.into())),
3079            (
3080                "origin_server_ts".to_owned(),
3081                serde_json::to_value(MilliSecondsSinceUnixEpoch::now()).unwrap(),
3082            ),
3083            ("room_id".to_owned(), Value::String("!foo:example.org".into())),
3084        ])))
3085        .unwrap()
3086    }
3087
3088    #[test]
3089    fn test_multiple_identical_reactions() {
3090        let mut info = RoomInfo::default();
3091
3092        let content = ReactionEventContent::new(Annotation::new(
3093            owned_event_id!("$my_reaction"),
3094            "🏠".to_owned(),
3095        ));
3096
3097        for i in 0..3 {
3098            let event_id = format!("$house_{i}");
3099            let react = create_reaction_event(&content, &event_id, "@foo:example.com");
3100            info.insert_reaction(react, None);
3101        }
3102
3103        let content = ReactionEventContent::new(Annotation::new(
3104            owned_event_id!("$my_reaction"),
3105            "🙂".to_owned(),
3106        ));
3107
3108        for i in 0..2 {
3109            let event_id = format!("$smile_{i}");
3110            let react = create_reaction_event(&content, &event_id, "@foo:example.com");
3111            info.insert_reaction(react, None);
3112        }
3113
3114        for i in 2..4 {
3115            let event_id = format!("$smile2_{i}");
3116            let react = create_reaction_event(&content, &event_id, "@bar:example.com");
3117            info.insert_reaction(react, None);
3118        }
3119
3120        let reacts: Vec<_> = info
3121            .get_reactions(&owned_event_id!("$my_reaction"))
3122            .into_iter()
3123            .map(|(key, count, _)| (key, count))
3124            .collect();
3125        assert_eq!(reacts, vec![
3126            ("🏠", vec![owned_user_id!("@foo:example.com").deref()]),
3127            ("🙂", vec![
3128                owned_user_id!("@bar:example.com").deref(),
3129                owned_user_id!("@foo:example.com").deref(),
3130            ],)
3131        ]);
3132    }
3133
3134    #[test]
3135    fn test_implicit_receipt_tracks_message_sender_for_display() {
3136        let mut info = RoomInfo::default();
3137        let settings = mock_settings();
3138        let mut previews = PreviewManager::new(&settings);
3139        let event = mock_room_message_event(
3140            RoomMessageEventContent::text_plain("sent by another user"),
3141            TEST_USER2.clone(),
3142            MSG5_KEY.clone(),
3143        );
3144
3145        info.insert_with_preview(event, &settings, &mut previews);
3146
3147        assert_eq!(
3148            info.user_receipts
3149                .get(&ReceiptThread::Main)
3150                .and_then(|receipts| receipts.get(&*TEST_USER2)),
3151            Some(&*MSG5_EVID),
3152        );
3153        assert!(
3154            info.event_receipts
3155                .get(&ReceiptThread::Main)
3156                .and_then(|receipts| receipts.get(&*MSG5_EVID))
3157                .is_some_and(|users| users.contains(&*TEST_USER2))
3158        );
3159    }
3160
3161    #[test]
3162    fn test_implicit_receipts_do_not_move_backwards_during_backpagination() {
3163        let mut info = RoomInfo::default();
3164        let settings = mock_settings();
3165        let mut previews = PreviewManager::new(&settings);
3166        let newer = mock_room_message_event(
3167            RoomMessageEventContent::text_plain("newer"),
3168            TEST_USER2.clone(),
3169            MSG5_KEY.clone(),
3170        );
3171        let older = mock_room_message_event(
3172            RoomMessageEventContent::text_plain("older"),
3173            TEST_USER2.clone(),
3174            MSG2_KEY.clone(),
3175        );
3176
3177        info.insert_with_preview(newer, &settings, &mut previews);
3178        info.insert_with_preview(older, &settings, &mut previews);
3179
3180        assert_eq!(
3181            info.user_receipts
3182                .get(&ReceiptThread::Main)
3183                .and_then(|receipts| receipts.get(&*TEST_USER2)),
3184            Some(&*MSG5_EVID),
3185        );
3186    }
3187
3188    #[test]
3189    fn test_implicit_receipt_preserves_thread_context() {
3190        let mut info = RoomInfo::default();
3191        let root = owned_event_id!("$thread_root");
3192        let reply = owned_event_id!("$thread_reply");
3193        let thread = ReceiptThread::Thread(root.clone());
3194
3195        info.keys
3196            .insert(reply.clone(), EventLocation::Message(Some(root), MSG5_KEY.clone()));
3197        info.set_implicit_receipt(TEST_USER1.clone(), reply.clone());
3198
3199        assert_eq!(
3200            info.user_receipts
3201                .get(&thread)
3202                .and_then(|receipts| receipts.get(&*TEST_USER1)),
3203            Some(&reply),
3204        );
3205    }
3206
3207    #[test]
3208    fn test_implicit_receipt_supports_state_events() {
3209        let mut info = RoomInfo::default();
3210        info.keys
3211            .insert(MSG5_EVID.clone(), EventLocation::Message(None, MSG5_KEY.clone()));
3212
3213        info.set_implicit_receipt(TEST_USER2.clone(), MSG5_EVID.clone());
3214
3215        assert_eq!(
3216            info.user_receipts
3217                .get(&ReceiptThread::Main)
3218                .and_then(|receipts| receipts.get(&*TEST_USER2)),
3219            Some(&*MSG5_EVID),
3220        );
3221    }
3222
3223    #[test]
3224    fn test_explicit_receipt_does_not_move_implicit_receipt_backwards() {
3225        let mut info = RoomInfo::default();
3226        let older = mock_room_message_event(
3227            RoomMessageEventContent::text_plain("older"),
3228            TEST_USER2.clone(),
3229            MSG2_KEY.clone(),
3230        );
3231        let newer = mock_room_message_event(
3232            RoomMessageEventContent::text_plain("newer"),
3233            TEST_USER2.clone(),
3234            MSG5_KEY.clone(),
3235        );
3236
3237        info.insert_message(older);
3238        info.insert_message(newer);
3239        info.set_receipt(ReceiptThread::Main, TEST_USER2.clone(), MSG2_EVID.clone());
3240
3241        assert_eq!(
3242            info.user_receipts
3243                .get(&ReceiptThread::Main)
3244                .and_then(|receipts| receipts.get(&*TEST_USER2)),
3245            Some(&*MSG5_EVID),
3246        );
3247    }
3248
3249    #[test]
3250    fn test_implicit_receipt_waits_for_unloaded_explicit_receipt() {
3251        let mut info = RoomInfo::default();
3252        info.set_receipt(ReceiptThread::Main, TEST_USER2.clone(), MSG5_EVID.clone());
3253        let older = mock_room_message_event(
3254            RoomMessageEventContent::text_plain("older"),
3255            TEST_USER2.clone(),
3256            MSG2_KEY.clone(),
3257        );
3258
3259        info.insert_message(older);
3260
3261        assert_eq!(
3262            info.user_receipts
3263                .get(&ReceiptThread::Main)
3264                .and_then(|receipts| receipts.get(&*TEST_USER2)),
3265            Some(&*MSG5_EVID),
3266        );
3267    }
3268
3269    #[test]
3270    fn test_typing_spans() {
3271        let mut info = RoomInfo::default();
3272        let settings = mock_settings();
3273        let theme = &settings.theme;
3274
3275        let users0 = vec![];
3276        let users1 = vec![TEST_USER1.clone()];
3277        let users2 = vec![TEST_USER1.clone(), TEST_USER2.clone()];
3278        let users4 = vec![
3279            TEST_USER1.clone(),
3280            TEST_USER2.clone(),
3281            TEST_USER3.clone(),
3282            TEST_USER4.clone(),
3283        ];
3284        let users5 = vec![
3285            TEST_USER1.clone(),
3286            TEST_USER2.clone(),
3287            TEST_USER3.clone(),
3288            TEST_USER4.clone(),
3289            TEST_USER5.clone(),
3290        ];
3291
3292        // Nothing set.
3293        assert_eq!(info.users_typing, None);
3294        assert_eq!(info.get_typing_spans(&settings), Line::from(vec![]));
3295
3296        // Empty typing list.
3297        info.set_typing(users0);
3298        assert!(info.users_typing.is_some());
3299        assert_eq!(info.get_typing_spans(&settings), Line::from(vec![]));
3300
3301        // Single user typing.
3302        info.set_typing(users1);
3303        assert!(info.users_typing.is_some());
3304        assert_eq!(
3305            info.get_typing_spans(&settings),
3306            Line::from(vec![
3307                Span::styled("@user1:example.com", theme.users.style("@user1:example.com", None)),
3308                Span::from(" is typing...")
3309            ])
3310        );
3311
3312        // Two users typing.
3313        info.set_typing(users2);
3314        assert!(info.users_typing.is_some());
3315        assert_eq!(
3316            info.get_typing_spans(&settings),
3317            Line::from(vec![
3318                Span::styled("@user1:example.com", theme.users.style("@user1:example.com", None)),
3319                Span::raw(" and "),
3320                Span::styled("@user2:example.com", theme.users.style("@user2:example.com", None)),
3321                Span::raw(" are typing...")
3322            ])
3323        );
3324
3325        // Four users typing.
3326        info.set_typing(users4);
3327        assert!(info.users_typing.is_some());
3328        assert_eq!(info.get_typing_spans(&settings), Line::from("Several people are typing..."));
3329
3330        // Five users typing.
3331        info.set_typing(users5);
3332        assert!(info.users_typing.is_some());
3333        assert_eq!(info.get_typing_spans(&settings), Line::from("Many people are typing..."));
3334
3335        // Test that USER5 gets rendered using the configured color and name.
3336        info.set_typing(vec![TEST_USER5.clone()]);
3337        assert!(info.users_typing.is_some());
3338        assert_eq!(
3339            info.get_typing_spans(&settings),
3340            Line::from(vec![
3341                Span::styled("USER 5", Style::default().fg(Color::Black).bold()),
3342                Span::from(" is typing...")
3343            ])
3344        );
3345    }
3346
3347    #[test]
3348    fn test_need_load() {
3349        let room_id = TEST_ROOM1_ID.clone();
3350
3351        let mut need_load = RoomNeeds::default();
3352
3353        need_load.need_messages(room_id.clone());
3354        need_load.need_members(room_id.clone());
3355
3356        assert_eq!(need_load.into_iter().collect::<Vec<(OwnedRoomId, Need)>>(), vec![(
3357            room_id,
3358            Need {
3359                members: true,
3360                messages: Some(Vec::new()),
3361                pinned: false
3362            }
3363        )],);
3364    }
3365
3366    #[test]
3367    fn test_pinned_lookup() {
3368        let mut info = mock_room();
3369        let unloaded = owned_event_id!("$unloaded");
3370
3371        info.pinned_events = vec![MSG3_EVID.clone(), unloaded.clone()];
3372
3373        assert!(info.is_pinned(&MSG3_EVID));
3374        assert!(!info.is_pinned(&MSG4_EVID));
3375
3376        // Loaded messages come from the scrollback, so only the unloaded one needs fetching.
3377        assert!(info.get_pinned(&MSG3_EVID).is_some());
3378        assert_eq!(info.missing_pinned(), vec![unloaded.clone()]);
3379
3380        info.insert_pinned(unloaded.clone(), mock_message1().into());
3381        assert!(info.get_pinned(&unloaded).is_some());
3382        assert!(info.missing_pinned().is_empty());
3383
3384        // Failed fetches are retried until they hit the limit.
3385        let broken = owned_event_id!("$broken");
3386        info.pinned_events.push(broken.clone());
3387
3388        for _ in 1..PINNED_FETCH_ATTEMPTS {
3389            info.insert_pinned(broken.clone(), None);
3390        }
3391        assert!(!info.pinned_unavailable(&broken));
3392        assert_eq!(info.missing_pinned(), vec![broken.clone()]);
3393
3394        info.insert_pinned(broken.clone(), None);
3395        assert!(info.pinned_unavailable(&broken));
3396        assert!(info.missing_pinned().is_empty());
3397
3398        let (thread, key) = info.get_message_location(&MSG3_EVID).unwrap();
3399        assert_eq!(thread, None);
3400        assert_eq!(key, &*MSG3_KEY);
3401        assert!(info.get_message_location(&unloaded).is_none());
3402    }
3403
3404    #[test]
3405    fn test_alias_window_id() {
3406        let room_id = TEST_ROOM1_ALIAS.clone();
3407        let id = IambId::Room(room_id.into(), RoomView::Main);
3408
3409        // Hash gets replaced during encoding:
3410        let exp = "iamb://room/%23room1%3Aexample%2Ecom";
3411        assert_eq!(id.to_string(), exp);
3412
3413        // Percent encoding turns back into hash during decoding:
3414        let parsed: IambId = serde_json::from_str(&format!("{exp:?}")).unwrap();
3415        assert_eq!(parsed, id);
3416    }
3417
3418    #[test]
3419    fn test_pinned_window_id() {
3420        let room_id = TEST_ROOM1_ID.clone();
3421        let id = IambId::PinnedList(room_id.clone());
3422        let url = format!("iamb://room/{room_id}/pinned");
3423
3424        assert_eq!(id.to_string(), url);
3425
3426        let parsed: IambId = serde_json::from_str(&format!("{url:?}")).unwrap();
3427        assert_eq!(parsed, id);
3428    }
3429
3430    #[test]
3431    fn test_ambiguous_displaynames() {
3432        let mut store = DisplayNameStore::default();
3433
3434        store.set(TEST_USER1.clone(), Some("John".into()), true);
3435        store.set(TEST_USER2.clone(), Some("John".into()), true);
3436        store.set(TEST_USER3.clone(), Some("Jane".into()), true);
3437        store.set(TEST_USER4.clone(), Some("Alice".into()), true);
3438        store.set(TEST_USER5.clone(), Some("Bob".into()), true);
3439
3440        // TEST_USER1 and TEST_USER2 are both ambiguous, while the other are unambiguous:
3441        assert_eq!(store.get(&TEST_USER1).unwrap().as_ref(), "John (@user1:example.com)");
3442        assert_eq!(store.get(&TEST_USER2).unwrap().as_ref(), "John (@user2:example.com)");
3443        assert_eq!(store.get(&TEST_USER3).unwrap().as_ref(), "Jane");
3444        assert_eq!(store.get(&TEST_USER4).unwrap().as_ref(), "Alice");
3445        assert_eq!(store.get(&TEST_USER5).unwrap().as_ref(), "Bob");
3446
3447        // TEST_USER1 becomes unambiguous when TEST_USER2 changes:
3448        store.set(TEST_USER2.clone(), Some("Eve".into()), true);
3449        assert_eq!(store.get(&TEST_USER1).unwrap().as_ref(), "John");
3450        assert_eq!(store.get(&TEST_USER2).unwrap().as_ref(), "Eve");
3451        assert_eq!(store.get(&TEST_USER3).unwrap().as_ref(), "Jane");
3452        assert_eq!(store.get(&TEST_USER4).unwrap().as_ref(), "Alice");
3453        assert_eq!(store.get(&TEST_USER5).unwrap().as_ref(), "Bob");
3454
3455        // TEST_USER5 becomes ambiguous when TEST_USER2 once again changes their name to match:
3456        store.set(TEST_USER2.clone(), Some("Bob".into()), true);
3457        assert_eq!(store.get(&TEST_USER1).unwrap().as_ref(), "John");
3458        assert_eq!(store.get(&TEST_USER2).unwrap().as_ref(), "Bob (@user2:example.com)");
3459        assert_eq!(store.get(&TEST_USER3).unwrap().as_ref(), "Jane");
3460        assert_eq!(store.get(&TEST_USER4).unwrap().as_ref(), "Alice");
3461        assert_eq!(store.get(&TEST_USER5).unwrap().as_ref(), "Bob (@user5:example.com)");
3462
3463        // Now "Everyone is John":
3464        store.set(TEST_USER2.clone(), Some("John".into()), true);
3465        store.set(TEST_USER3.clone(), Some("John".into()), true);
3466        store.set(TEST_USER4.clone(), Some("John".into()), true);
3467        store.set(TEST_USER5.clone(), Some("John".into()), true);
3468        assert_eq!(store.get(&TEST_USER1).unwrap().as_ref(), "John (@user1:example.com)");
3469        assert_eq!(store.get(&TEST_USER2).unwrap().as_ref(), "John (@user2:example.com)");
3470        assert_eq!(store.get(&TEST_USER3).unwrap().as_ref(), "John (@user3:example.com)");
3471        assert_eq!(store.get(&TEST_USER4).unwrap().as_ref(), "John (@user4:example.com)");
3472        assert_eq!(store.get(&TEST_USER5).unwrap().as_ref(), "John (@user5:example.com)");
3473
3474        // 2-4 unset their displayname:
3475        store.set(TEST_USER2.clone(), None, true);
3476        store.set(TEST_USER3.clone(), None, true);
3477        store.set(TEST_USER4.clone(), None, true);
3478        // and 5 leaves
3479        store.set(TEST_USER5.clone(), Some("John".into()), false);
3480        assert_eq!(store.get(&TEST_USER1).unwrap().as_ref(), "John");
3481        assert_eq!(store.get(&TEST_USER2), None);
3482        assert_eq!(store.get(&TEST_USER3), None);
3483        assert_eq!(store.get(&TEST_USER4), None);
3484        assert_eq!(store.get(&TEST_USER5).unwrap().as_ref(), "John (@user5:example.com)");
3485    }
3486}