src/base.rs

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