src/base.rs

1017 lines · 30037 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::Original(orig) => {
 489                orig.content = *new_content;
 490            },
 491            MessageEvent::Local(_, content) => {
 492                *content = new_content;
 493            },
 494            MessageEvent::Redacted(_) |
 495            MessageEvent::EncryptedOriginal(_) |
 496            MessageEvent::EncryptedRedacted(_) => {
 497                return;
 498            },
 499        }
 500
 501        msg.html = msg.event.html();
 502    }
 503
 504    /// Inserts events that couldn't be decrypted into the scrollback.
 505    pub fn insert_encrypted(&mut self, msg: RoomEncryptedEvent) {
 506        let event_id = msg.event_id().to_owned();
 507        let key = (msg.origin_server_ts().into(), event_id.clone());
 508
 509        self.keys.insert(event_id, EventLocation::Message(key.clone()));
 510        self.messages.insert(key, msg.into());
 511    }
 512
 513    pub fn insert_message(&mut self, msg: RoomMessageEvent) {
 514        let event_id = msg.event_id().to_owned();
 515        let key = (msg.origin_server_ts().into(), event_id.clone());
 516
 517        self.keys.insert(event_id.clone(), EventLocation::Message(key.clone()));
 518        self.messages.insert(key, msg.into());
 519
 520        // Remove any echo.
 521        let key = (MessageTimeStamp::LocalEcho, event_id);
 522        let _ = self.messages.remove(&key);
 523    }
 524
 525    pub fn insert(&mut self, msg: RoomMessageEvent) {
 526        match msg {
 527            RoomMessageEvent::Original(OriginalRoomMessageEvent {
 528                content:
 529                    RoomMessageEventContent { relates_to: Some(Relation::Replacement(repl)), .. },
 530                ..
 531            }) => self.insert_edit(repl),
 532            _ => self.insert_message(msg),
 533        }
 534    }
 535
 536    pub fn recently_fetched(&self) -> bool {
 537        self.fetch_last.map_or(false, |i| i.elapsed() < ROOM_FETCH_DEBOUNCE)
 538    }
 539
 540    fn get_typers(&self) -> &[OwnedUserId] {
 541        if let Some((t, users)) = &self.users_typing {
 542            if t.elapsed() < Duration::from_secs(4) {
 543                return users.as_ref();
 544            } else {
 545                return &[];
 546            }
 547        } else {
 548            return &[];
 549        }
 550    }
 551
 552    fn get_typing_spans<'a>(&'a self, settings: &'a ApplicationSettings) -> Spans<'a> {
 553        let typers = self.get_typers();
 554        let n = typers.len();
 555
 556        match n {
 557            0 => Spans(vec![]),
 558            1 => {
 559                let user = settings.get_user_span(typers[0].as_ref());
 560
 561                Spans(vec![user, Span::from(" is typing...")])
 562            },
 563            2 => {
 564                let user1 = settings.get_user_span(typers[0].as_ref());
 565                let user2 = settings.get_user_span(typers[1].as_ref());
 566
 567                Spans(vec![
 568                    user1,
 569                    Span::raw(" and "),
 570                    user2,
 571                    Span::from(" are typing..."),
 572                ])
 573            },
 574            n if n < 5 => Spans::from("Several people are typing..."),
 575            _ => Spans::from("Many people are typing..."),
 576        }
 577    }
 578
 579    pub fn set_typing(&mut self, user_ids: Vec<OwnedUserId>) {
 580        self.users_typing = (Instant::now(), user_ids).into();
 581    }
 582
 583    pub fn render_typing(
 584        &mut self,
 585        area: Rect,
 586        buf: &mut Buffer,
 587        settings: &ApplicationSettings,
 588    ) -> Rect {
 589        if area.height <= 2 || area.width <= 20 {
 590            return area;
 591        }
 592
 593        if !settings.tunables.typing_notice_display {
 594            return area;
 595        }
 596
 597        let top = Rect::new(area.x, area.y, area.width, area.height - 1);
 598        let bar = Rect::new(area.x, area.y + top.height, area.width, 1);
 599
 600        Paragraph::new(self.get_typing_spans(settings))
 601            .alignment(Alignment::Center)
 602            .render(bar, buf);
 603
 604        return top;
 605    }
 606}
 607
 608fn emoji_map() -> CompletionMap<String, &'static Emoji> {
 609    let mut emojis = CompletionMap::default();
 610
 611    for emoji in emojis::iter() {
 612        for shortcode in emoji.shortcodes() {
 613            emojis.insert(shortcode.to_string(), emoji);
 614        }
 615    }
 616
 617    return emojis;
 618}
 619
 620pub struct ChatStore {
 621    pub cmds: ProgramCommands,
 622    pub worker: Requester,
 623    pub rooms: CompletionMap<OwnedRoomId, RoomInfo>,
 624    pub names: CompletionMap<String, OwnedRoomId>,
 625    pub presences: CompletionMap<OwnedUserId, PresenceState>,
 626    pub verifications: HashMap<String, SasVerification>,
 627    pub settings: ApplicationSettings,
 628    pub need_load: HashSet<OwnedRoomId>,
 629    pub emojis: CompletionMap<String, &'static Emoji>,
 630}
 631
 632impl ChatStore {
 633    pub fn new(worker: Requester, settings: ApplicationSettings) -> Self {
 634        ChatStore {
 635            worker,
 636            settings,
 637
 638            cmds: crate::commands::setup_commands(),
 639            names: Default::default(),
 640            rooms: Default::default(),
 641            presences: Default::default(),
 642            verifications: Default::default(),
 643            need_load: Default::default(),
 644            emojis: emoji_map(),
 645        }
 646    }
 647
 648    pub fn get_joined_room(&self, room_id: &RoomId) -> Option<Joined> {
 649        self.worker.client.get_joined_room(room_id)
 650    }
 651
 652    pub fn get_room_title(&self, room_id: &RoomId) -> String {
 653        self.rooms
 654            .get(room_id)
 655            .and_then(|i| i.name.as_ref())
 656            .map(String::from)
 657            .unwrap_or_else(|| "Untitled Matrix Room".to_string())
 658    }
 659
 660    pub async fn set_receipts(&mut self, receipts: Vec<(OwnedRoomId, Receipts)>) {
 661        let mut updates = vec![];
 662
 663        for (room_id, receipts) in receipts.into_iter() {
 664            if let Some(info) = self.rooms.get_mut(&room_id) {
 665                info.receipts = receipts;
 666
 667                if let Some(read_till) = info.read_till.take() {
 668                    updates.push((room_id, read_till));
 669                }
 670            }
 671        }
 672
 673        for (room_id, read_till) in updates.into_iter() {
 674            if let Some(room) = self.worker.client.get_joined_room(&room_id) {
 675                let _ = room.read_receipt(read_till.as_ref()).await;
 676            }
 677        }
 678    }
 679
 680    pub fn mark_for_load(&mut self, room_id: OwnedRoomId) {
 681        self.need_load.insert(room_id);
 682    }
 683
 684    pub fn get_room_info(&mut self, room_id: OwnedRoomId) -> &mut RoomInfo {
 685        self.rooms.get_or_default(room_id)
 686    }
 687
 688    pub fn set_room_name(&mut self, room_id: &RoomId, name: &str) {
 689        self.rooms.get_or_default(room_id.to_owned()).name = name.to_string().into();
 690    }
 691
 692    pub fn insert_sas(&mut self, sas: SasVerification) {
 693        let key = format!("{}/{}", sas.other_user_id(), sas.other_device().device_id());
 694
 695        self.verifications.insert(key, sas);
 696    }
 697}
 698
 699impl ApplicationStore for ChatStore {}
 700
 701#[derive(Clone, Debug, Eq, Hash, PartialEq)]
 702pub enum IambId {
 703    Room(OwnedRoomId),
 704    DirectList,
 705    MemberList(OwnedRoomId),
 706    RoomList,
 707    SpaceList,
 708    VerifyList,
 709    Welcome,
 710}
 711
 712impl ApplicationWindowId for IambId {}
 713
 714#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
 715pub enum RoomFocus {
 716    Scrollback,
 717    MessageBar,
 718}
 719
 720impl RoomFocus {
 721    pub fn is_scrollback(&self) -> bool {
 722        matches!(self, RoomFocus::Scrollback)
 723    }
 724
 725    pub fn is_msgbar(&self) -> bool {
 726        matches!(self, RoomFocus::MessageBar)
 727    }
 728}
 729
 730#[derive(Clone, Debug, Eq, Hash, PartialEq)]
 731pub enum IambBufferId {
 732    Command(CommandType),
 733    Room(OwnedRoomId, RoomFocus),
 734    DirectList,
 735    MemberList(OwnedRoomId),
 736    RoomList,
 737    SpaceList,
 738    VerifyList,
 739    Welcome,
 740}
 741
 742impl IambBufferId {
 743    pub fn to_window(&self) -> Option<IambId> {
 744        match self {
 745            IambBufferId::Command(_) => None,
 746            IambBufferId::Room(room, _) => Some(IambId::Room(room.clone())),
 747            IambBufferId::DirectList => Some(IambId::DirectList),
 748            IambBufferId::MemberList(room) => Some(IambId::MemberList(room.clone())),
 749            IambBufferId::RoomList => Some(IambId::RoomList),
 750            IambBufferId::SpaceList => Some(IambId::SpaceList),
 751            IambBufferId::VerifyList => Some(IambId::VerifyList),
 752            IambBufferId::Welcome => Some(IambId::Welcome),
 753        }
 754    }
 755}
 756
 757impl ApplicationContentId for IambBufferId {}
 758
 759impl ApplicationInfo for IambInfo {
 760    type Error = IambError;
 761    type Store = ChatStore;
 762    type Action = IambAction;
 763    type WindowId = IambId;
 764    type ContentId = IambBufferId;
 765
 766    fn complete(
 767        text: &EditRope,
 768        cursor: &mut Cursor,
 769        content: &IambBufferId,
 770        store: &mut ProgramStore,
 771    ) -> Vec<String> {
 772        match content {
 773            IambBufferId::Command(CommandType::Command) => complete_cmdbar(text, cursor, store),
 774            IambBufferId::Command(CommandType::Search) => vec![],
 775
 776            IambBufferId::Room(_, RoomFocus::MessageBar) => {
 777                complete_matrix_names(text, cursor, store)
 778            },
 779            IambBufferId::Room(_, RoomFocus::Scrollback) => vec![],
 780
 781            IambBufferId::DirectList => vec![],
 782            IambBufferId::MemberList(_) => vec![],
 783            IambBufferId::RoomList => vec![],
 784            IambBufferId::SpaceList => vec![],
 785            IambBufferId::VerifyList => vec![],
 786            IambBufferId::Welcome => vec![],
 787        }
 788    }
 789
 790    fn content_of_command(ct: CommandType) -> IambBufferId {
 791        IambBufferId::Command(ct)
 792    }
 793}
 794
 795fn complete_users(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
 796    let id = text
 797        .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
 798        .unwrap_or_else(EditRope::empty);
 799    let id = Cow::from(&id);
 800
 801    store
 802        .application
 803        .presences
 804        .complete(id.as_ref())
 805        .into_iter()
 806        .map(|i| i.to_string())
 807        .collect()
 808}
 809
 810fn complete_matrix_names(
 811    text: &EditRope,
 812    cursor: &mut Cursor,
 813    store: &ProgramStore,
 814) -> Vec<String> {
 815    let id = text
 816        .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
 817        .unwrap_or_else(EditRope::empty);
 818    let id = Cow::from(&id);
 819
 820    let list = store.application.names.complete(id.as_ref());
 821    if !list.is_empty() {
 822        return list;
 823    }
 824
 825    let list = store.application.presences.complete(id.as_ref());
 826    if !list.is_empty() {
 827        return list.into_iter().map(|i| i.to_string()).collect();
 828    }
 829
 830    store
 831        .application
 832        .rooms
 833        .complete(id.as_ref())
 834        .into_iter()
 835        .map(|i| i.to_string())
 836        .collect()
 837}
 838
 839fn complete_emoji(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
 840    let sc = text.get_prefix_word_mut(cursor, &WordStyle::Little);
 841    let sc = sc.unwrap_or_else(EditRope::empty);
 842    let sc = Cow::from(&sc);
 843
 844    store.application.emojis.complete(sc.as_ref())
 845}
 846
 847fn complete_cmdarg(
 848    desc: CommandDescription,
 849    text: &EditRope,
 850    cursor: &mut Cursor,
 851    store: &ProgramStore,
 852) -> Vec<String> {
 853    let cmd = match store.application.cmds.get(desc.command.as_str()) {
 854        Ok(cmd) => cmd,
 855        Err(_) => return vec![],
 856    };
 857
 858    match cmd.name.as_str() {
 859        "cancel" | "dms" | "edit" | "redact" | "reply" => vec![],
 860        "members" | "rooms" | "spaces" | "welcome" => vec![],
 861        "download" | "open" | "upload" => complete_path(text, cursor),
 862        "react" | "unreact" => complete_emoji(text, cursor, store),
 863
 864        "invite" => complete_users(text, cursor, store),
 865        "join" => complete_matrix_names(text, cursor, store),
 866        "room" => vec![],
 867        "verify" => vec![],
 868        _ => panic!("unknown command {}", cmd.name.as_str()),
 869    }
 870}
 871
 872fn complete_cmdbar(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
 873    let eo = text.cursor_to_offset(cursor);
 874    let slice = text.slice(0.into(), eo, false);
 875    let cow = Cow::from(&slice);
 876
 877    match CommandDescription::from_str(cow.as_ref()) {
 878        Ok(desc) => {
 879            if desc.arg.untrimmed.is_empty() {
 880                // Complete command name and set cursor position.
 881                let _ = text.get_prefix_word_mut(cursor, &WordStyle::Little);
 882                store.application.cmds.complete_name(desc.command.as_str())
 883            } else {
 884                // Complete command argument.
 885                complete_cmdarg(desc, text, cursor, store)
 886            }
 887        },
 888
 889        // Can't parse command text, so return zero completions.
 890        Err(_) => vec![],
 891    }
 892}
 893
 894#[cfg(test)]
 895pub mod tests {
 896    use super::*;
 897    use crate::config::user_style_from_color;
 898    use crate::tests::*;
 899    use modalkit::tui::style::Color;
 900
 901    #[test]
 902    fn test_typing_spans() {
 903        let mut info = RoomInfo::default();
 904        let settings = mock_settings();
 905
 906        let users0 = vec![];
 907        let users1 = vec![TEST_USER1.clone()];
 908        let users2 = vec![TEST_USER1.clone(), TEST_USER2.clone()];
 909        let users4 = vec![
 910            TEST_USER1.clone(),
 911            TEST_USER2.clone(),
 912            TEST_USER3.clone(),
 913            TEST_USER4.clone(),
 914        ];
 915        let users5 = vec![
 916            TEST_USER1.clone(),
 917            TEST_USER2.clone(),
 918            TEST_USER3.clone(),
 919            TEST_USER4.clone(),
 920            TEST_USER5.clone(),
 921        ];
 922
 923        // Nothing set.
 924        assert_eq!(info.users_typing, None);
 925        assert_eq!(info.get_typing_spans(&settings), Spans(vec![]));
 926
 927        // Empty typing list.
 928        info.set_typing(users0);
 929        assert!(info.users_typing.is_some());
 930        assert_eq!(info.get_typing_spans(&settings), Spans(vec![]));
 931
 932        // Single user typing.
 933        info.set_typing(users1);
 934        assert!(info.users_typing.is_some());
 935        assert_eq!(
 936            info.get_typing_spans(&settings),
 937            Spans(vec![
 938                Span::styled("@user1:example.com", user_style("@user1:example.com")),
 939                Span::from(" is typing...")
 940            ])
 941        );
 942
 943        // Two users typing.
 944        info.set_typing(users2);
 945        assert!(info.users_typing.is_some());
 946        assert_eq!(
 947            info.get_typing_spans(&settings),
 948            Spans(vec![
 949                Span::styled("@user1:example.com", user_style("@user1:example.com")),
 950                Span::raw(" and "),
 951                Span::styled("@user2:example.com", user_style("@user2:example.com")),
 952                Span::raw(" are typing...")
 953            ])
 954        );
 955
 956        // Four users typing.
 957        info.set_typing(users4);
 958        assert!(info.users_typing.is_some());
 959        assert_eq!(info.get_typing_spans(&settings), Spans::from("Several people are typing..."));
 960
 961        // Five users typing.
 962        info.set_typing(users5);
 963        assert!(info.users_typing.is_some());
 964        assert_eq!(info.get_typing_spans(&settings), Spans::from("Many people are typing..."));
 965
 966        // Test that USER5 gets rendered using the configured color and name.
 967        info.set_typing(vec![TEST_USER5.clone()]);
 968        assert!(info.users_typing.is_some());
 969        assert_eq!(
 970            info.get_typing_spans(&settings),
 971            Spans(vec![
 972                Span::styled("USER 5", user_style_from_color(Color::Black)),
 973                Span::from(" is typing...")
 974            ])
 975        );
 976    }
 977
 978    #[tokio::test]
 979    async fn test_complete_cmdbar() {
 980        let store = mock_store().await;
 981
 982        let text = EditRope::from("invite    ");
 983        let mut cursor = Cursor::new(0, 7);
 984        let id = text
 985            .get_prefix_word_mut(&mut cursor, &MATRIX_ID_WORD)
 986            .unwrap_or_else(EditRope::empty);
 987        assert_eq!(id.to_string(), "");
 988        assert_eq!(cursor, Cursor::new(0, 7));
 989
 990        let text = EditRope::from("invite    ");
 991        let mut cursor = Cursor::new(0, 7);
 992        let res = complete_cmdbar(&text, &mut cursor, &store);
 993        assert_eq!(res, vec![
 994            "@user1:example.com",
 995            "@user2:example.com",
 996            "@user3:example.com",
 997            "@user4:example.com",
 998            "@user5:example.com"
 999        ]);
1000
1001        let text = EditRope::from("invite ignored");
1002        let mut cursor = Cursor::new(0, 7);
1003        let res = complete_cmdbar(&text, &mut cursor, &store);
1004        assert_eq!(res, vec![
1005            "@user1:example.com",
1006            "@user2:example.com",
1007            "@user3:example.com",
1008            "@user4:example.com",
1009            "@user5:example.com"
1010        ]);
1011
1012        let text = EditRope::from("invite @user1ignored");
1013        let mut cursor = Cursor::new(0, 13);
1014        let res = complete_cmdbar(&text, &mut cursor, &store);
1015        assert_eq!(res, vec!["@user1:example.com"]);
1016    }
1017}