src/base.rs

1018 lines · 30022 bytes

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