src/base.rs

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