src/base.rs

1308 lines · 38752 bytes

   1use std::borrow::Cow;
   2use std::collections::{HashMap, HashSet};
   3use std::convert::TryFrom;
   4use std::fmt::{self, Display};
   5use std::hash::Hash;
   6use std::str::FromStr;
   7use std::sync::Arc;
   8use std::time::{Duration, Instant};
   9
  10use emojis::Emoji;
  11use serde::{
  12    de::Error as SerdeError,
  13    de::Visitor,
  14    Deserialize,
  15    Deserializer,
  16    Serialize,
  17    Serializer,
  18};
  19use tokio::sync::Mutex as AsyncMutex;
  20use url::Url;
  21
  22use matrix_sdk::{
  23    encryption::verification::SasVerification,
  24    room::{Joined, Room as MatrixRoom},
  25    ruma::{
  26        events::{
  27            reaction::ReactionEvent,
  28            room::encrypted::RoomEncryptedEvent,
  29            room::message::{
  30                OriginalRoomMessageEvent,
  31                Relation,
  32                Replacement,
  33                RoomMessageEvent,
  34                RoomMessageEventContent,
  35            },
  36            tag::{TagName, Tags},
  37            MessageLikeEvent,
  38        },
  39        presence::PresenceState,
  40        EventId,
  41        OwnedEventId,
  42        OwnedRoomId,
  43        OwnedUserId,
  44        RoomId,
  45    },
  46};
  47
  48use modalkit::{
  49    editing::{
  50        action::{Action, UIError, UIResult},
  51        application::{
  52            ApplicationAction,
  53            ApplicationContentId,
  54            ApplicationError,
  55            ApplicationInfo,
  56            ApplicationStore,
  57            ApplicationWindowId,
  58        },
  59        base::{CommandType, WordStyle},
  60        completion::{complete_path, CompletionMap},
  61        context::EditContext,
  62        cursor::Cursor,
  63        rope::EditRope,
  64        store::Store,
  65    },
  66    env::vim::{
  67        command::{CommandContext, CommandDescription, VimCommand, VimCommandMachine},
  68        keybindings::VimMachine,
  69        VimContext,
  70    },
  71    input::bindings::SequenceStatus,
  72    input::key::TerminalKey,
  73    tui::{
  74        buffer::Buffer,
  75        layout::{Alignment, Rect},
  76        text::{Span, Spans},
  77        widgets::{Paragraph, Widget},
  78    },
  79};
  80
  81use crate::{
  82    message::{Message, MessageEvent, MessageKey, MessageTimeStamp, Messages},
  83    worker::Requester,
  84    ApplicationSettings,
  85};
  86
  87pub const MATRIX_ID_WORD: WordStyle = WordStyle::CharSet(is_mxid_char);
  88
  89/// Find the boundaries for a Matrix username, room alias, or room ID.
  90///
  91/// Technically "[" and "]" should be here since IPv6 addresses are allowed
  92/// in the server name, but in practice that should be uncommon, and people
  93/// can just use `gf` and friends in Visual mode instead.
  94fn is_mxid_char(c: char) -> bool {
  95    return c >= 'a' && c <= 'z' ||
  96        c >= 'A' && c <= 'Z' ||
  97        c >= '0' && c <= '9' ||
  98        ":-./@_#!".contains(c);
  99}
 100
 101const ROOM_FETCH_DEBOUNCE: Duration = Duration::from_secs(2);
 102
 103#[derive(Clone, Debug, Eq, PartialEq)]
 104pub enum IambInfo {}
 105
 106#[derive(Clone, Debug, Eq, PartialEq)]
 107pub enum VerifyAction {
 108    Accept,
 109    Cancel,
 110    Confirm,
 111    Mismatch,
 112}
 113
 114#[derive(Clone, Debug, Eq, PartialEq)]
 115pub enum MessageAction {
 116    /// Cance the current reply or edit.
 117    ///
 118    /// The [bool] argument indicates whether to skip confirmation for clearing the message bar.
 119    Cancel(bool),
 120
 121    /// Download an attachment to the given path.
 122    ///
 123    /// The second argument controls whether to overwrite any already existing file at the
 124    /// destination path, or to open the attachment after downloading.
 125    Download(Option<String>, DownloadFlags),
 126
 127    /// Edit a sent message.
 128    Edit,
 129
 130    /// React to a message with an Emoji.
 131    React(String),
 132
 133    /// Redact a message, with an optional reason.
 134    ///
 135    /// The [bool] argument indicates whether to skip confirmation.
 136    Redact(Option<String>, bool),
 137
 138    /// Reply to a message.
 139    Reply,
 140
 141    /// Unreact to a message.
 142    ///
 143    /// If no specific Emoji to remove to is specified, then all reactions from the user on the
 144    /// message are removed.
 145    Unreact(Option<String>),
 146}
 147
 148#[derive(Clone, Debug, Eq, PartialEq)]
 149pub enum CreateRoomType {
 150    /// A direct message room.
 151    Direct(OwnedUserId),
 152
 153    /// A standard chat room.
 154    Room,
 155
 156    /// A Matrix space.
 157    Space,
 158}
 159
 160bitflags::bitflags! {
 161    pub struct CreateRoomFlags: u32 {
 162        const NONE = 0b00000000;
 163
 164        /// Make the room public.
 165        const PUBLIC = 0b00000001;
 166
 167        /// Encrypt this room.
 168        const ENCRYPTED = 0b00000010;
 169    }
 170}
 171
 172bitflags::bitflags! {
 173    pub struct DownloadFlags: u32 {
 174        const NONE = 0b00000000;
 175
 176        /// Overwrite file if it already exists.
 177        const FORCE = 0b00000001;
 178
 179        /// Open file after downloading.
 180        const OPEN = 0b00000010;
 181    }
 182}
 183
 184#[derive(Clone, Debug, Eq, PartialEq)]
 185pub enum RoomField {
 186    Name,
 187    Tag(TagName),
 188    Topic,
 189}
 190
 191#[derive(Clone, Debug, Eq, PartialEq)]
 192pub enum RoomAction {
 193    InviteAccept,
 194    InviteReject,
 195    InviteSend(OwnedUserId),
 196    Leave(bool),
 197    Members(Box<CommandContext<ProgramContext>>),
 198    Set(RoomField, String),
 199    Unset(RoomField),
 200}
 201
 202#[derive(Clone, Debug, Eq, PartialEq)]
 203pub enum SendAction {
 204    Submit,
 205    SubmitFromEditor,
 206    Upload(String),
 207    UploadImage(usize, usize, Cow<'static, [u8]>),
 208}
 209
 210#[derive(Clone, Debug, Eq, PartialEq)]
 211pub enum HomeserverAction {
 212    CreateRoom(Option<String>, CreateRoomType, CreateRoomFlags),
 213}
 214
 215#[derive(Clone, Debug, Eq, PartialEq)]
 216pub enum IambAction {
 217    Homeserver(HomeserverAction),
 218    Message(MessageAction),
 219    Room(RoomAction),
 220    Send(SendAction),
 221    Verify(VerifyAction, String),
 222    VerifyRequest(String),
 223    ToggleScrollbackFocus,
 224}
 225
 226impl IambAction {
 227    /// Indicates whether this action will draw over the screen.
 228    pub fn scribbles(&self) -> bool {
 229        matches!(self, IambAction::Send(SendAction::SubmitFromEditor))
 230    }
 231}
 232
 233impl From<HomeserverAction> for IambAction {
 234    fn from(act: HomeserverAction) -> Self {
 235        IambAction::Homeserver(act)
 236    }
 237}
 238
 239impl From<MessageAction> for IambAction {
 240    fn from(act: MessageAction) -> Self {
 241        IambAction::Message(act)
 242    }
 243}
 244
 245impl From<RoomAction> for IambAction {
 246    fn from(act: RoomAction) -> Self {
 247        IambAction::Room(act)
 248    }
 249}
 250
 251impl From<SendAction> for IambAction {
 252    fn from(act: SendAction) -> Self {
 253        IambAction::Send(act)
 254    }
 255}
 256
 257impl ApplicationAction for IambAction {
 258    fn is_edit_sequence<C: EditContext>(&self, _: &C) -> SequenceStatus {
 259        match self {
 260            IambAction::Homeserver(..) => SequenceStatus::Break,
 261            IambAction::Message(..) => SequenceStatus::Break,
 262            IambAction::Room(..) => SequenceStatus::Break,
 263            IambAction::Send(..) => SequenceStatus::Break,
 264            IambAction::ToggleScrollbackFocus => SequenceStatus::Break,
 265            IambAction::Verify(..) => SequenceStatus::Break,
 266            IambAction::VerifyRequest(..) => SequenceStatus::Break,
 267        }
 268    }
 269
 270    fn is_last_action<C: EditContext>(&self, _: &C) -> SequenceStatus {
 271        match self {
 272            IambAction::Homeserver(..) => SequenceStatus::Atom,
 273            IambAction::Message(..) => SequenceStatus::Atom,
 274            IambAction::Room(..) => SequenceStatus::Atom,
 275            IambAction::Send(..) => SequenceStatus::Atom,
 276            IambAction::ToggleScrollbackFocus => SequenceStatus::Atom,
 277            IambAction::Verify(..) => SequenceStatus::Atom,
 278            IambAction::VerifyRequest(..) => SequenceStatus::Atom,
 279        }
 280    }
 281
 282    fn is_last_selection<C: EditContext>(&self, _: &C) -> SequenceStatus {
 283        match self {
 284            IambAction::Homeserver(..) => SequenceStatus::Ignore,
 285            IambAction::Message(..) => SequenceStatus::Ignore,
 286            IambAction::Room(..) => SequenceStatus::Ignore,
 287            IambAction::Send(..) => SequenceStatus::Ignore,
 288            IambAction::ToggleScrollbackFocus => SequenceStatus::Ignore,
 289            IambAction::Verify(..) => SequenceStatus::Ignore,
 290            IambAction::VerifyRequest(..) => SequenceStatus::Ignore,
 291        }
 292    }
 293
 294    fn is_switchable<C: EditContext>(&self, _: &C) -> bool {
 295        match self {
 296            IambAction::Homeserver(..) => false,
 297            IambAction::Message(..) => false,
 298            IambAction::Room(..) => false,
 299            IambAction::Send(..) => false,
 300            IambAction::ToggleScrollbackFocus => false,
 301            IambAction::Verify(..) => false,
 302            IambAction::VerifyRequest(..) => false,
 303        }
 304    }
 305}
 306
 307impl From<RoomAction> for ProgramAction {
 308    fn from(act: RoomAction) -> Self {
 309        IambAction::from(act).into()
 310    }
 311}
 312
 313impl From<IambAction> for ProgramAction {
 314    fn from(act: IambAction) -> Self {
 315        Action::Application(act)
 316    }
 317}
 318
 319pub type ProgramAction = Action<IambInfo>;
 320pub type ProgramContext = VimContext<IambInfo>;
 321pub type Keybindings = VimMachine<TerminalKey, IambInfo>;
 322pub type ProgramCommand = VimCommand<ProgramContext, IambInfo>;
 323pub type ProgramCommands = VimCommandMachine<ProgramContext, IambInfo>;
 324pub type ProgramStore = Store<IambInfo>;
 325pub type AsyncProgramStore = Arc<AsyncMutex<ProgramStore>>;
 326
 327pub type IambResult<T> = UIResult<T, IambInfo>;
 328
 329/// Reaction events for some message.
 330///
 331/// The event identifier used as a key here is the ID for the reaction, and not for the message
 332/// it's reacting to.
 333pub type MessageReactions = HashMap<OwnedEventId, (String, OwnedUserId)>;
 334
 335pub type Receipts = HashMap<OwnedEventId, Vec<OwnedUserId>>;
 336
 337#[derive(thiserror::Error, Debug)]
 338pub enum IambError {
 339    #[error("Invalid user identifier: {0}")]
 340    InvalidUserId(String),
 341
 342    #[error("Invalid verification user/device pair: {0}")]
 343    InvalidVerificationId(String),
 344
 345    #[error("Cryptographic storage error: {0}")]
 346    CryptoStore(#[from] matrix_sdk::encryption::CryptoStoreError),
 347
 348    #[error("HTTP client error: {0}")]
 349    Http(#[from] matrix_sdk::HttpError),
 350
 351    #[error("Matrix client error: {0}")]
 352    Matrix(#[from] matrix_sdk::Error),
 353
 354    #[error("Matrix client storage error: {0}")]
 355    Store(#[from] matrix_sdk::StoreError),
 356
 357    #[error("Serialization/deserialization error: {0}")]
 358    Serde(#[from] serde_json::Error),
 359
 360    #[error("No download directory configured")]
 361    NoDownloadDir,
 362
 363    #[error("Selected message does not have any attachments")]
 364    NoAttachment,
 365
 366    #[error("No message currently selected")]
 367    NoSelectedMessage,
 368
 369    #[error("Current window is not a room or space")]
 370    NoSelectedRoomOrSpace,
 371
 372    #[error("Current window is not a room")]
 373    NoSelectedRoom,
 374
 375    #[error("You do not have a current invitation to this room")]
 376    NotInvited,
 377
 378    #[error("You need to join the room before you can do that")]
 379    NotJoined,
 380
 381    #[error("Unknown room identifier: {0}")]
 382    UnknownRoom(OwnedRoomId),
 383
 384    #[error("Verification request error: {0}")]
 385    VerificationRequestError(#[from] matrix_sdk::encryption::identities::RequestVerificationError),
 386
 387    #[error("Image error: {0}")]
 388    Image(#[from] image::ImageError),
 389
 390    #[error("Could not use system clipboard data")]
 391    Clipboard,
 392}
 393
 394impl From<IambError> for UIError<IambInfo> {
 395    fn from(err: IambError) -> Self {
 396        UIError::Application(err)
 397    }
 398}
 399
 400impl ApplicationError for IambError {}
 401
 402#[derive(Default)]
 403pub enum RoomFetchStatus {
 404    Done,
 405    HaveMore(String),
 406    #[default]
 407    NotStarted,
 408}
 409
 410pub enum EventLocation {
 411    Message(MessageKey),
 412    Reaction(OwnedEventId),
 413}
 414
 415impl EventLocation {
 416    fn to_message_key(&self) -> Option<&MessageKey> {
 417        if let EventLocation::Message(key) = self {
 418            Some(key)
 419        } else {
 420            None
 421        }
 422    }
 423}
 424
 425#[derive(Default)]
 426pub struct RoomInfo {
 427    /// The display name for this room.
 428    pub name: Option<String>,
 429
 430    /// The tags placed on this room.
 431    pub tags: Option<Tags>,
 432
 433    /// A map of event IDs to where they are stored in this struct.
 434    pub keys: HashMap<OwnedEventId, EventLocation>,
 435
 436    /// The messages loaded for this room.
 437    pub messages: Messages,
 438
 439    /// A map of read markers to display on different events.
 440    pub receipts: HashMap<OwnedEventId, Vec<OwnedUserId>>,
 441
 442    /// An event ID for where we should indicate we've read up to.
 443    pub read_till: Option<OwnedEventId>,
 444
 445    /// A map of message identifiers to a map of reaction events.
 446    pub reactions: HashMap<OwnedEventId, MessageReactions>,
 447
 448    /// Whether the scrollback for this room is currently being fetched.
 449    pub fetching: bool,
 450
 451    /// Where to continue fetching from when we continue loading scrollback history.
 452    pub fetch_id: RoomFetchStatus,
 453
 454    /// The time that we last fetched scrollback for this room.
 455    pub fetch_last: Option<Instant>,
 456
 457    /// Users currently typing in this room, and when we received notification of them doing so.
 458    pub users_typing: Option<(Instant, Vec<OwnedUserId>)>,
 459
 460    /// The display names for users in this room.
 461    pub display_names: HashMap<OwnedUserId, String>,
 462}
 463
 464impl RoomInfo {
 465    pub fn get_reactions(&self, event_id: &EventId) -> Vec<(&str, usize)> {
 466        if let Some(reacts) = self.reactions.get(event_id) {
 467            let mut counts = HashMap::new();
 468
 469            for (key, _) in reacts.values() {
 470                let count = counts.entry(key.as_str()).or_default();
 471                *count += 1;
 472            }
 473
 474            let mut reactions = counts.into_iter().collect::<Vec<_>>();
 475            reactions.sort();
 476
 477            reactions
 478        } else {
 479            vec![]
 480        }
 481    }
 482
 483    pub fn get_message_key(&self, event_id: &EventId) -> Option<&MessageKey> {
 484        self.keys.get(event_id)?.to_message_key()
 485    }
 486
 487    pub fn get_event(&self, event_id: &EventId) -> Option<&Message> {
 488        self.messages.get(self.get_message_key(event_id)?)
 489    }
 490
 491    pub fn insert_reaction(&mut self, react: ReactionEvent) {
 492        match react {
 493            MessageLikeEvent::Original(react) => {
 494                let rel_id = react.content.relates_to.event_id;
 495                let key = react.content.relates_to.key;
 496
 497                let message = self.reactions.entry(rel_id.clone()).or_default();
 498                let event_id = react.event_id;
 499                let user_id = react.sender;
 500
 501                message.insert(event_id.clone(), (key, user_id));
 502
 503                let loc = EventLocation::Reaction(rel_id);
 504                self.keys.insert(event_id, loc);
 505            },
 506            MessageLikeEvent::Redacted(_) => {
 507                return;
 508            },
 509        }
 510    }
 511
 512    pub fn insert_edit(&mut self, msg: Replacement) {
 513        let event_id = msg.event_id;
 514        let new_content = msg.new_content;
 515
 516        let key = if let Some(EventLocation::Message(k)) = self.keys.get(&event_id) {
 517            k
 518        } else {
 519            return;
 520        };
 521
 522        let msg = if let Some(msg) = self.messages.get_mut(key) {
 523            msg
 524        } else {
 525            return;
 526        };
 527
 528        match &mut msg.event {
 529            MessageEvent::Original(orig) => {
 530                orig.content.msgtype = new_content.msgtype;
 531            },
 532            MessageEvent::Local(_, content) => {
 533                content.msgtype = new_content.msgtype;
 534            },
 535            MessageEvent::Redacted(_) |
 536            MessageEvent::EncryptedOriginal(_) |
 537            MessageEvent::EncryptedRedacted(_) => {
 538                return;
 539            },
 540        }
 541
 542        msg.html = msg.event.html();
 543    }
 544
 545    /// Inserts events that couldn't be decrypted into the scrollback.
 546    pub fn insert_encrypted(&mut self, msg: RoomEncryptedEvent) {
 547        let event_id = msg.event_id().to_owned();
 548        let key = (msg.origin_server_ts().into(), event_id.clone());
 549
 550        self.keys.insert(event_id, EventLocation::Message(key.clone()));
 551        self.messages.insert(key, msg.into());
 552    }
 553
 554    pub fn insert_message(&mut self, msg: RoomMessageEvent) {
 555        let event_id = msg.event_id().to_owned();
 556        let key = (msg.origin_server_ts().into(), event_id.clone());
 557
 558        self.keys.insert(event_id.clone(), EventLocation::Message(key.clone()));
 559        self.messages.insert(key, msg.into());
 560
 561        // Remove any echo.
 562        let key = (MessageTimeStamp::LocalEcho, event_id);
 563        let _ = self.messages.remove(&key);
 564    }
 565
 566    pub fn insert(&mut self, msg: RoomMessageEvent) {
 567        match msg {
 568            RoomMessageEvent::Original(OriginalRoomMessageEvent {
 569                content:
 570                    RoomMessageEventContent { relates_to: Some(Relation::Replacement(repl)), .. },
 571                ..
 572            }) => self.insert_edit(repl),
 573            _ => self.insert_message(msg),
 574        }
 575    }
 576
 577    pub fn recently_fetched(&self) -> bool {
 578        self.fetch_last.map_or(false, |i| i.elapsed() < ROOM_FETCH_DEBOUNCE)
 579    }
 580
 581    fn get_typers(&self) -> &[OwnedUserId] {
 582        if let Some((t, users)) = &self.users_typing {
 583            if t.elapsed() < Duration::from_secs(4) {
 584                return users.as_ref();
 585            } else {
 586                return &[];
 587            }
 588        } else {
 589            return &[];
 590        }
 591    }
 592
 593    fn get_typing_spans<'a>(&'a self, settings: &'a ApplicationSettings) -> Spans<'a> {
 594        let typers = self.get_typers();
 595        let n = typers.len();
 596
 597        match n {
 598            0 => Spans(vec![]),
 599            1 => {
 600                let user = settings.get_user_span(typers[0].as_ref(), self);
 601
 602                Spans(vec![user, Span::from(" is typing...")])
 603            },
 604            2 => {
 605                let user1 = settings.get_user_span(typers[0].as_ref(), self);
 606                let user2 = settings.get_user_span(typers[1].as_ref(), self);
 607
 608                Spans(vec![
 609                    user1,
 610                    Span::raw(" and "),
 611                    user2,
 612                    Span::from(" are typing..."),
 613                ])
 614            },
 615            n if n < 5 => Spans::from("Several people are typing..."),
 616            _ => Spans::from("Many people are typing..."),
 617        }
 618    }
 619
 620    pub fn set_typing(&mut self, user_ids: Vec<OwnedUserId>) {
 621        self.users_typing = (Instant::now(), user_ids).into();
 622    }
 623
 624    pub fn render_typing(
 625        &mut self,
 626        area: Rect,
 627        buf: &mut Buffer,
 628        settings: &ApplicationSettings,
 629    ) -> Rect {
 630        if area.height <= 2 || area.width <= 20 {
 631            return area;
 632        }
 633
 634        if !settings.tunables.typing_notice_display {
 635            return area;
 636        }
 637
 638        let top = Rect::new(area.x, area.y, area.width, area.height - 1);
 639        let bar = Rect::new(area.x, area.y + top.height, area.width, 1);
 640
 641        Paragraph::new(self.get_typing_spans(settings))
 642            .alignment(Alignment::Center)
 643            .render(bar, buf);
 644
 645        return top;
 646    }
 647}
 648
 649fn emoji_map() -> CompletionMap<String, &'static Emoji> {
 650    let mut emojis = CompletionMap::default();
 651
 652    for emoji in emojis::iter() {
 653        for shortcode in emoji.shortcodes() {
 654            emojis.insert(shortcode.to_string(), emoji);
 655        }
 656    }
 657
 658    return emojis;
 659}
 660
 661#[derive(Default)]
 662pub struct SyncInfo {
 663    pub spaces: Vec<MatrixRoom>,
 664    pub rooms: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
 665    pub dms: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
 666}
 667
 668pub struct ChatStore {
 669    pub cmds: ProgramCommands,
 670    pub worker: Requester,
 671    pub rooms: CompletionMap<OwnedRoomId, RoomInfo>,
 672    pub names: CompletionMap<String, OwnedRoomId>,
 673    pub presences: CompletionMap<OwnedUserId, PresenceState>,
 674    pub verifications: HashMap<String, SasVerification>,
 675    pub settings: ApplicationSettings,
 676    pub need_load: HashSet<OwnedRoomId>,
 677    pub emojis: CompletionMap<String, &'static Emoji>,
 678    pub sync_info: SyncInfo,
 679}
 680
 681impl ChatStore {
 682    pub fn new(worker: Requester, settings: ApplicationSettings) -> Self {
 683        ChatStore {
 684            worker,
 685            settings,
 686
 687            cmds: crate::commands::setup_commands(),
 688            emojis: emoji_map(),
 689
 690            names: Default::default(),
 691            rooms: Default::default(),
 692            presences: Default::default(),
 693            verifications: Default::default(),
 694            need_load: Default::default(),
 695            sync_info: Default::default(),
 696        }
 697    }
 698
 699    pub fn get_joined_room(&self, room_id: &RoomId) -> Option<Joined> {
 700        self.worker.client.get_joined_room(room_id)
 701    }
 702
 703    pub fn get_room_title(&self, room_id: &RoomId) -> String {
 704        self.rooms
 705            .get(room_id)
 706            .and_then(|i| i.name.as_ref())
 707            .map(String::from)
 708            .unwrap_or_else(|| "Untitled Matrix Room".to_string())
 709    }
 710
 711    pub async fn set_receipts(
 712        &mut self,
 713        receipts: Vec<(OwnedRoomId, Receipts)>,
 714    ) -> Vec<(OwnedRoomId, OwnedEventId)> {
 715        let mut updates = vec![];
 716
 717        for (room_id, receipts) in receipts.into_iter() {
 718            if let Some(info) = self.rooms.get_mut(&room_id) {
 719                info.receipts = receipts;
 720
 721                if let Some(read_till) = info.read_till.take() {
 722                    updates.push((room_id, read_till));
 723                }
 724            }
 725        }
 726
 727        return updates;
 728    }
 729
 730    pub fn mark_for_load(&mut self, room_id: OwnedRoomId) {
 731        self.need_load.insert(room_id);
 732    }
 733
 734    pub fn get_room_info(&mut self, room_id: OwnedRoomId) -> &mut RoomInfo {
 735        self.rooms.get_or_default(room_id)
 736    }
 737
 738    pub fn set_room_name(&mut self, room_id: &RoomId, name: &str) {
 739        self.rooms.get_or_default(room_id.to_owned()).name = name.to_string().into();
 740    }
 741
 742    pub fn insert_sas(&mut self, sas: SasVerification) {
 743        let key = format!("{}/{}", sas.other_user_id(), sas.other_device().device_id());
 744
 745        self.verifications.insert(key, sas);
 746    }
 747}
 748
 749impl ApplicationStore for ChatStore {}
 750
 751#[derive(Clone, Debug, Eq, Hash, PartialEq)]
 752pub enum IambId {
 753    /// A Matrix room.
 754    Room(OwnedRoomId),
 755
 756    /// The `:rooms` window.
 757    DirectList,
 758
 759    /// The `:members` window for a given Matrix room.
 760    MemberList(OwnedRoomId),
 761
 762    /// The `:rooms` window.
 763    RoomList,
 764
 765    /// The `:spaces` window.
 766    SpaceList,
 767
 768    /// The `:verify` window.
 769    VerifyList,
 770
 771    /// The `:welcome` window.
 772    Welcome,
 773}
 774
 775impl Display for IambId {
 776    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 777        match self {
 778            IambId::Room(room_id) => {
 779                write!(f, "iamb://room/{room_id}")
 780            },
 781            IambId::MemberList(room_id) => {
 782                write!(f, "iamb://members/{room_id}")
 783            },
 784            IambId::DirectList => f.write_str("iamb://dms"),
 785            IambId::RoomList => f.write_str("iamb://rooms"),
 786            IambId::SpaceList => f.write_str("iamb://spaces"),
 787            IambId::VerifyList => f.write_str("iamb://verify"),
 788            IambId::Welcome => f.write_str("iamb://welcome"),
 789        }
 790    }
 791}
 792
 793impl ApplicationWindowId for IambId {}
 794
 795impl Serialize for IambId {
 796    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
 797    where
 798        S: Serializer,
 799    {
 800        serializer.serialize_str(&self.to_string())
 801    }
 802}
 803
 804impl<'de> Deserialize<'de> for IambId {
 805    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
 806    where
 807        D: Deserializer<'de>,
 808    {
 809        deserializer.deserialize_str(IambIdVisitor)
 810    }
 811}
 812
 813struct IambIdVisitor;
 814
 815impl<'de> Visitor<'de> for IambIdVisitor {
 816    type Value = IambId;
 817
 818    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
 819        formatter.write_str("a valid window URL")
 820    }
 821
 822    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
 823    where
 824        E: SerdeError,
 825    {
 826        let Ok(url) = Url::parse(value) else {
 827            return Err(E::custom("Invalid iamb window URL"));
 828        };
 829
 830        if url.scheme() != "iamb" {
 831            return Err(E::custom("Invalid iamb window URL"));
 832        }
 833
 834        match url.domain() {
 835            Some("room") => {
 836                let Some(path) = url.path_segments() else {
 837                    return Err(E::custom("Invalid members window URL"));
 838                };
 839
 840                let &[room_id] = path.collect::<Vec<_>>().as_slice() else {
 841                    return Err(E::custom("Invalid members window URL"));
 842                };
 843
 844                let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
 845                    return Err(E::custom("Invalid room identifier"));
 846                };
 847
 848                Ok(IambId::Room(room_id))
 849            },
 850            Some("members") => {
 851                let Some(path) = url.path_segments() else {
 852                    return Err(E::custom("Invalid members window URL"));
 853                };
 854
 855                let &[room_id] = path.collect::<Vec<_>>().as_slice() else {
 856                    return Err(E::custom("Invalid members window URL"));
 857                };
 858
 859                let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
 860                    return Err(E::custom("Invalid room identifier"));
 861                };
 862
 863                Ok(IambId::MemberList(room_id))
 864            },
 865            Some("dms") => {
 866                if url.path() != "" {
 867                    return Err(E::custom("iamb://dms takes no path"));
 868                }
 869
 870                Ok(IambId::DirectList)
 871            },
 872            Some("rooms") => {
 873                if url.path() != "" {
 874                    return Err(E::custom("iamb://rooms takes no path"));
 875                }
 876
 877                Ok(IambId::RoomList)
 878            },
 879            Some("spaces") => {
 880                if url.path() != "" {
 881                    return Err(E::custom("iamb://spaces takes no path"));
 882                }
 883
 884                Ok(IambId::SpaceList)
 885            },
 886            Some("verify") => {
 887                if url.path() != "" {
 888                    return Err(E::custom("iamb://verify takes no path"));
 889                }
 890
 891                Ok(IambId::VerifyList)
 892            },
 893            Some("welcome") => {
 894                if url.path() != "" {
 895                    return Err(E::custom("iamb://welcome takes no path"));
 896                }
 897
 898                Ok(IambId::Welcome)
 899            },
 900            Some(s) => Err(E::custom(format!("{s:?} is not a valid window"))),
 901            None => Err(E::custom("Invalid iamb window URL")),
 902        }
 903    }
 904}
 905
 906#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
 907pub enum RoomFocus {
 908    Scrollback,
 909    MessageBar,
 910}
 911
 912impl RoomFocus {
 913    pub fn is_scrollback(&self) -> bool {
 914        matches!(self, RoomFocus::Scrollback)
 915    }
 916
 917    pub fn is_msgbar(&self) -> bool {
 918        matches!(self, RoomFocus::MessageBar)
 919    }
 920}
 921
 922#[derive(Clone, Debug, Eq, Hash, PartialEq)]
 923pub enum IambBufferId {
 924    Command(CommandType),
 925    Room(OwnedRoomId, RoomFocus),
 926    DirectList,
 927    MemberList(OwnedRoomId),
 928    RoomList,
 929    SpaceList,
 930    VerifyList,
 931    Welcome,
 932}
 933
 934impl IambBufferId {
 935    pub fn to_window(&self) -> Option<IambId> {
 936        match self {
 937            IambBufferId::Command(_) => None,
 938            IambBufferId::Room(room, _) => Some(IambId::Room(room.clone())),
 939            IambBufferId::DirectList => Some(IambId::DirectList),
 940            IambBufferId::MemberList(room) => Some(IambId::MemberList(room.clone())),
 941            IambBufferId::RoomList => Some(IambId::RoomList),
 942            IambBufferId::SpaceList => Some(IambId::SpaceList),
 943            IambBufferId::VerifyList => Some(IambId::VerifyList),
 944            IambBufferId::Welcome => Some(IambId::Welcome),
 945        }
 946    }
 947}
 948
 949impl ApplicationContentId for IambBufferId {}
 950
 951impl ApplicationInfo for IambInfo {
 952    type Error = IambError;
 953    type Store = ChatStore;
 954    type Action = IambAction;
 955    type WindowId = IambId;
 956    type ContentId = IambBufferId;
 957
 958    fn complete(
 959        text: &EditRope,
 960        cursor: &mut Cursor,
 961        content: &IambBufferId,
 962        store: &mut ProgramStore,
 963    ) -> Vec<String> {
 964        match content {
 965            IambBufferId::Command(CommandType::Command) => complete_cmdbar(text, cursor, store),
 966            IambBufferId::Command(CommandType::Search) => vec![],
 967
 968            IambBufferId::Room(_, RoomFocus::MessageBar) => complete_msgbar(text, cursor, store),
 969            IambBufferId::Room(_, RoomFocus::Scrollback) => vec![],
 970
 971            IambBufferId::DirectList => vec![],
 972            IambBufferId::MemberList(_) => vec![],
 973            IambBufferId::RoomList => vec![],
 974            IambBufferId::SpaceList => vec![],
 975            IambBufferId::VerifyList => vec![],
 976            IambBufferId::Welcome => vec![],
 977        }
 978    }
 979
 980    fn content_of_command(ct: CommandType) -> IambBufferId {
 981        IambBufferId::Command(ct)
 982    }
 983}
 984
 985fn complete_users(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
 986    let id = text
 987        .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
 988        .unwrap_or_else(EditRope::empty);
 989    let id = Cow::from(&id);
 990
 991    store
 992        .application
 993        .presences
 994        .complete(id.as_ref())
 995        .into_iter()
 996        .map(|i| i.to_string())
 997        .collect()
 998}
 999
1000fn complete_msgbar(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
1001    let id = text
1002        .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
1003        .unwrap_or_else(EditRope::empty);
1004    let id = Cow::from(&id);
1005
1006    match id.chars().next() {
1007        // Complete room aliases.
1008        Some('#') => {
1009            return store.application.names.complete(id.as_ref());
1010        },
1011
1012        // Complete room identifiers.
1013        Some('!') => {
1014            return store
1015                .application
1016                .rooms
1017                .complete(id.as_ref())
1018                .into_iter()
1019                .map(|i| i.to_string())
1020                .collect();
1021        },
1022
1023        // Complete Emoji shortcodes.
1024        Some(':') => {
1025            let list = store.application.emojis.complete(&id[1..]);
1026            let iter = list.into_iter().take(200).map(|s| format!(":{}:", s));
1027
1028            return iter.collect();
1029        },
1030
1031        // Complete usernames for @ and empty strings.
1032        Some('@') | None => {
1033            return store
1034                .application
1035                .presences
1036                .complete(id.as_ref())
1037                .into_iter()
1038                .map(|i| i.to_string())
1039                .collect();
1040        },
1041
1042        // Unknown sigil.
1043        Some(_) => return vec![],
1044    }
1045}
1046
1047fn complete_matrix_names(
1048    text: &EditRope,
1049    cursor: &mut Cursor,
1050    store: &ProgramStore,
1051) -> Vec<String> {
1052    let id = text
1053        .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
1054        .unwrap_or_else(EditRope::empty);
1055    let id = Cow::from(&id);
1056
1057    let list = store.application.names.complete(id.as_ref());
1058    if !list.is_empty() {
1059        return list;
1060    }
1061
1062    let list = store.application.presences.complete(id.as_ref());
1063    if !list.is_empty() {
1064        return list.into_iter().map(|i| i.to_string()).collect();
1065    }
1066
1067    store
1068        .application
1069        .rooms
1070        .complete(id.as_ref())
1071        .into_iter()
1072        .map(|i| i.to_string())
1073        .collect()
1074}
1075
1076fn complete_emoji(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
1077    let sc = text.get_prefix_word_mut(cursor, &WordStyle::Little);
1078    let sc = sc.unwrap_or_else(EditRope::empty);
1079    let sc = Cow::from(&sc);
1080
1081    store.application.emojis.complete(sc.as_ref())
1082}
1083
1084fn complete_cmdname(
1085    desc: CommandDescription,
1086    text: &EditRope,
1087    cursor: &mut Cursor,
1088    store: &ProgramStore,
1089) -> Vec<String> {
1090    // Complete command name and set cursor position.
1091    let _ = text.get_prefix_word_mut(cursor, &WordStyle::Little);
1092    store.application.cmds.complete_name(desc.command.as_str())
1093}
1094
1095fn complete_cmdarg(
1096    desc: CommandDescription,
1097    text: &EditRope,
1098    cursor: &mut Cursor,
1099    store: &ProgramStore,
1100) -> Vec<String> {
1101    let cmd = match store.application.cmds.get(desc.command.as_str()) {
1102        Ok(cmd) => cmd,
1103        Err(_) => return vec![],
1104    };
1105
1106    match cmd.name.as_str() {
1107        "cancel" | "dms" | "edit" | "redact" | "reply" => vec![],
1108        "members" | "rooms" | "spaces" | "welcome" => vec![],
1109        "download" | "open" | "upload" => complete_path(text, cursor),
1110        "react" | "unreact" => complete_emoji(text, cursor, store),
1111
1112        "invite" => complete_users(text, cursor, store),
1113        "join" | "split" | "vsplit" | "tabedit" => complete_matrix_names(text, cursor, store),
1114        "room" => vec![],
1115        "verify" => vec![],
1116        "vertical" | "horizontal" | "aboveleft" | "belowright" | "tab" => {
1117            complete_cmd(desc.arg.text.as_str(), text, cursor, store)
1118        },
1119        _ => vec![],
1120    }
1121}
1122
1123fn complete_cmd(
1124    cmd: &str,
1125    text: &EditRope,
1126    cursor: &mut Cursor,
1127    store: &ProgramStore,
1128) -> Vec<String> {
1129    match CommandDescription::from_str(cmd) {
1130        Ok(desc) => {
1131            if desc.arg.untrimmed.is_empty() {
1132                complete_cmdname(desc, text, cursor, store)
1133            } else {
1134                // Complete command argument.
1135                complete_cmdarg(desc, text, cursor, store)
1136            }
1137        },
1138
1139        // Can't parse command text, so return zero completions.
1140        Err(_) => vec![],
1141    }
1142}
1143
1144fn complete_cmdbar(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
1145    let eo = text.cursor_to_offset(cursor);
1146    let slice = text.slice(0.into(), eo, false);
1147    let cow = Cow::from(&slice);
1148
1149    complete_cmd(cow.as_ref(), text, cursor, store)
1150}
1151
1152#[cfg(test)]
1153pub mod tests {
1154    use super::*;
1155    use crate::config::user_style_from_color;
1156    use crate::tests::*;
1157    use modalkit::tui::style::Color;
1158
1159    #[test]
1160    fn test_typing_spans() {
1161        let mut info = RoomInfo::default();
1162        let settings = mock_settings();
1163
1164        let users0 = vec![];
1165        let users1 = vec![TEST_USER1.clone()];
1166        let users2 = vec![TEST_USER1.clone(), TEST_USER2.clone()];
1167        let users4 = vec![
1168            TEST_USER1.clone(),
1169            TEST_USER2.clone(),
1170            TEST_USER3.clone(),
1171            TEST_USER4.clone(),
1172        ];
1173        let users5 = vec![
1174            TEST_USER1.clone(),
1175            TEST_USER2.clone(),
1176            TEST_USER3.clone(),
1177            TEST_USER4.clone(),
1178            TEST_USER5.clone(),
1179        ];
1180
1181        // Nothing set.
1182        assert_eq!(info.users_typing, None);
1183        assert_eq!(info.get_typing_spans(&settings), Spans(vec![]));
1184
1185        // Empty typing list.
1186        info.set_typing(users0);
1187        assert!(info.users_typing.is_some());
1188        assert_eq!(info.get_typing_spans(&settings), Spans(vec![]));
1189
1190        // Single user typing.
1191        info.set_typing(users1);
1192        assert!(info.users_typing.is_some());
1193        assert_eq!(
1194            info.get_typing_spans(&settings),
1195            Spans(vec![
1196                Span::styled("@user1:example.com", user_style("@user1:example.com")),
1197                Span::from(" is typing...")
1198            ])
1199        );
1200
1201        // Two users typing.
1202        info.set_typing(users2);
1203        assert!(info.users_typing.is_some());
1204        assert_eq!(
1205            info.get_typing_spans(&settings),
1206            Spans(vec![
1207                Span::styled("@user1:example.com", user_style("@user1:example.com")),
1208                Span::raw(" and "),
1209                Span::styled("@user2:example.com", user_style("@user2:example.com")),
1210                Span::raw(" are typing...")
1211            ])
1212        );
1213
1214        // Four users typing.
1215        info.set_typing(users4);
1216        assert!(info.users_typing.is_some());
1217        assert_eq!(info.get_typing_spans(&settings), Spans::from("Several people are typing..."));
1218
1219        // Five users typing.
1220        info.set_typing(users5);
1221        assert!(info.users_typing.is_some());
1222        assert_eq!(info.get_typing_spans(&settings), Spans::from("Many people are typing..."));
1223
1224        // Test that USER5 gets rendered using the configured color and name.
1225        info.set_typing(vec![TEST_USER5.clone()]);
1226        assert!(info.users_typing.is_some());
1227        assert_eq!(
1228            info.get_typing_spans(&settings),
1229            Spans(vec![
1230                Span::styled("USER 5", user_style_from_color(Color::Black)),
1231                Span::from(" is typing...")
1232            ])
1233        );
1234    }
1235
1236    #[tokio::test]
1237    async fn test_complete_msgbar() {
1238        let store = mock_store().await;
1239
1240        let text = EditRope::from("going for a walk :walk ");
1241        let mut cursor = Cursor::new(0, 22);
1242        let res = complete_msgbar(&text, &mut cursor, &store);
1243        assert_eq!(res, vec![":walking:", ":walking_man:", ":walking_woman:"]);
1244        assert_eq!(cursor, Cursor::new(0, 17));
1245
1246        let text = EditRope::from("hello @user1 ");
1247        let mut cursor = Cursor::new(0, 12);
1248        let res = complete_msgbar(&text, &mut cursor, &store);
1249        assert_eq!(res, vec!["@user1:example.com"]);
1250        assert_eq!(cursor, Cursor::new(0, 6));
1251
1252        let text = EditRope::from("see #room ");
1253        let mut cursor = Cursor::new(0, 9);
1254        let res = complete_msgbar(&text, &mut cursor, &store);
1255        assert_eq!(res, vec!["#room1:example.com"]);
1256        assert_eq!(cursor, Cursor::new(0, 4));
1257    }
1258
1259    #[tokio::test]
1260    async fn test_complete_cmdbar() {
1261        let store = mock_store().await;
1262        let users = vec![
1263            "@user1:example.com",
1264            "@user2:example.com",
1265            "@user3:example.com",
1266            "@user4:example.com",
1267            "@user5:example.com",
1268        ];
1269
1270        let text = EditRope::from("invite    ");
1271        let mut cursor = Cursor::new(0, 7);
1272        let id = text
1273            .get_prefix_word_mut(&mut cursor, &MATRIX_ID_WORD)
1274            .unwrap_or_else(EditRope::empty);
1275        assert_eq!(id.to_string(), "");
1276        assert_eq!(cursor, Cursor::new(0, 7));
1277
1278        let text = EditRope::from("invite    ");
1279        let mut cursor = Cursor::new(0, 7);
1280        let res = complete_cmdbar(&text, &mut cursor, &store);
1281        assert_eq!(res, users);
1282
1283        let text = EditRope::from("invite ignored");
1284        let mut cursor = Cursor::new(0, 7);
1285        let res = complete_cmdbar(&text, &mut cursor, &store);
1286        assert_eq!(res, users);
1287
1288        let text = EditRope::from("invite @user1ignored");
1289        let mut cursor = Cursor::new(0, 13);
1290        let res = complete_cmdbar(&text, &mut cursor, &store);
1291        assert_eq!(res, vec!["@user1:example.com"]);
1292
1293        let text = EditRope::from("abo hor");
1294        let mut cursor = Cursor::new(0, 7);
1295        let res = complete_cmdbar(&text, &mut cursor, &store);
1296        assert_eq!(res, vec!["horizontal"]);
1297
1298        let text = EditRope::from("abo hor inv");
1299        let mut cursor = Cursor::new(0, 11);
1300        let res = complete_cmdbar(&text, &mut cursor, &store);
1301        assert_eq!(res, vec!["invite"]);
1302
1303        let text = EditRope::from("abo hor invite \n");
1304        let mut cursor = Cursor::new(0, 15);
1305        let res = complete_cmdbar(&text, &mut cursor, &store);
1306        assert_eq!(res, users);
1307    }
1308}