src/base.rs

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