src/base.rs

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