src/base.rs

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