src/base.rs

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