src/base.rs

2530 lines · 81150 bytes

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