src/base.rs

1017 lines · 30402 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;
  10use tracing::warn;
  11
  12use matrix_sdk::{
  13    encryption::verification::SasVerification,
  14    room::Joined,
  15    ruma::{
  16        events::{
  17            reaction::ReactionEvent,
  18            room::message::{
  19                OriginalRoomMessageEvent,
  20                Relation,
  21                Replacement,
  22                RoomMessageEvent,
  23                RoomMessageEventContent,
  24            },
  25            tag::{TagName, Tags},
  26            AnyMessageLikeEvent,
  27            MessageLikeEvent,
  28        },
  29        presence::PresenceState,
  30        EventId,
  31        OwnedEventId,
  32        OwnedRoomId,
  33        OwnedUserId,
  34        RoomId,
  35    },
  36};
  37
  38use modalkit::{
  39    editing::{
  40        action::{Action, UIError, UIResult},
  41        application::{
  42            ApplicationAction,
  43            ApplicationContentId,
  44            ApplicationError,
  45            ApplicationInfo,
  46            ApplicationStore,
  47            ApplicationWindowId,
  48        },
  49        base::{CommandType, WordStyle},
  50        completion::{complete_path, CompletionMap},
  51        context::EditContext,
  52        cursor::Cursor,
  53        rope::EditRope,
  54        store::Store,
  55    },
  56    env::vim::{
  57        command::{CommandContext, CommandDescription, VimCommand, VimCommandMachine},
  58        keybindings::VimMachine,
  59        VimContext,
  60    },
  61    input::bindings::SequenceStatus,
  62    input::key::TerminalKey,
  63    tui::{
  64        buffer::Buffer,
  65        layout::{Alignment, Rect},
  66        text::{Span, Spans},
  67        widgets::{Paragraph, Widget},
  68    },
  69};
  70
  71use crate::{
  72    message::{Message, MessageEvent, MessageKey, MessageTimeStamp, Messages},
  73    worker::Requester,
  74    ApplicationSettings,
  75};
  76
  77pub const MATRIX_ID_WORD: WordStyle = WordStyle::CharSet(is_mxid_char);
  78
  79/// Find the boundaries for a Matrix username, room alias, or room ID.
  80///
  81/// Technically "[" and "]" should be here since IPv6 addresses are allowed
  82/// in the server name, but in practice that should be uncommon, and people
  83/// can just use `gf` and friends in Visual mode instead.
  84fn is_mxid_char(c: char) -> bool {
  85    return c >= 'a' && c <= 'z' ||
  86        c >= 'A' && c <= 'Z' ||
  87        c >= '0' && c <= '9' ||
  88        ":-./@_#!".contains(c);
  89}
  90
  91const ROOM_FETCH_DEBOUNCE: Duration = Duration::from_secs(2);
  92
  93#[derive(Clone, Debug, Eq, PartialEq)]
  94pub enum IambInfo {}
  95
  96#[derive(Clone, Debug, Eq, PartialEq)]
  97pub enum VerifyAction {
  98    Accept,
  99    Cancel,
 100    Confirm,
 101    Mismatch,
 102}
 103
 104#[derive(Clone, Debug, Eq, PartialEq)]
 105pub enum MessageAction {
 106    /// Cance the current reply or edit.
 107    Cancel,
 108
 109    /// Download an attachment to the given path.
 110    ///
 111    /// The second argument controls whether to overwrite any already existing file at the
 112    /// destination path, or to open the attachment after downloading.
 113    Download(Option<String>, DownloadFlags),
 114
 115    /// Edit a sent message.
 116    Edit,
 117
 118    /// React to a message with an Emoji.
 119    React(String),
 120
 121    /// Redact a message, with an optional reason.
 122    Redact(Option<String>),
 123
 124    /// Reply to a message.
 125    Reply,
 126
 127    /// Unreact to a message.
 128    ///
 129    /// If no specific Emoji to remove to is specified, then all reactions from the user on the
 130    /// message are removed.
 131    Unreact(Option<String>),
 132}
 133
 134bitflags::bitflags! {
 135    pub struct DownloadFlags: u32 {
 136        const NONE = 0b00000000;
 137
 138        /// Overwrite file if it already exists.
 139        const FORCE = 0b00000001;
 140
 141        /// Open file after downloading.
 142        const OPEN = 0b00000010;
 143    }
 144}
 145
 146#[derive(Clone, Debug, Eq, PartialEq)]
 147pub enum RoomField {
 148    Name,
 149    Tag(TagName),
 150    Topic,
 151}
 152
 153#[derive(Clone, Debug, Eq, PartialEq)]
 154pub enum RoomAction {
 155    InviteAccept,
 156    InviteReject,
 157    InviteSend(OwnedUserId),
 158    Members(Box<CommandContext<ProgramContext>>),
 159    Set(RoomField, String),
 160    Unset(RoomField),
 161}
 162
 163#[derive(Clone, Debug, Eq, PartialEq)]
 164pub enum SendAction {
 165    Submit,
 166    Upload(String),
 167}
 168
 169#[derive(Clone, Debug, Eq, PartialEq)]
 170pub enum IambAction {
 171    Message(MessageAction),
 172    Room(RoomAction),
 173    Send(SendAction),
 174    Verify(VerifyAction, String),
 175    VerifyRequest(String),
 176    ToggleScrollbackFocus,
 177}
 178
 179impl From<MessageAction> for IambAction {
 180    fn from(act: MessageAction) -> Self {
 181        IambAction::Message(act)
 182    }
 183}
 184
 185impl From<RoomAction> for IambAction {
 186    fn from(act: RoomAction) -> Self {
 187        IambAction::Room(act)
 188    }
 189}
 190
 191impl From<SendAction> for IambAction {
 192    fn from(act: SendAction) -> Self {
 193        IambAction::Send(act)
 194    }
 195}
 196
 197impl ApplicationAction for IambAction {
 198    fn is_edit_sequence<C: EditContext>(&self, _: &C) -> SequenceStatus {
 199        match self {
 200            IambAction::Message(..) => SequenceStatus::Break,
 201            IambAction::Room(..) => SequenceStatus::Break,
 202            IambAction::Send(..) => SequenceStatus::Break,
 203            IambAction::ToggleScrollbackFocus => SequenceStatus::Break,
 204            IambAction::Verify(..) => SequenceStatus::Break,
 205            IambAction::VerifyRequest(..) => SequenceStatus::Break,
 206        }
 207    }
 208
 209    fn is_last_action<C: EditContext>(&self, _: &C) -> SequenceStatus {
 210        match self {
 211            IambAction::Message(..) => SequenceStatus::Atom,
 212            IambAction::Room(..) => SequenceStatus::Atom,
 213            IambAction::Send(..) => SequenceStatus::Atom,
 214            IambAction::ToggleScrollbackFocus => SequenceStatus::Atom,
 215            IambAction::Verify(..) => SequenceStatus::Atom,
 216            IambAction::VerifyRequest(..) => SequenceStatus::Atom,
 217        }
 218    }
 219
 220    fn is_last_selection<C: EditContext>(&self, _: &C) -> SequenceStatus {
 221        match self {
 222            IambAction::Message(..) => SequenceStatus::Ignore,
 223            IambAction::Room(..) => SequenceStatus::Ignore,
 224            IambAction::Send(..) => SequenceStatus::Ignore,
 225            IambAction::ToggleScrollbackFocus => SequenceStatus::Ignore,
 226            IambAction::Verify(..) => SequenceStatus::Ignore,
 227            IambAction::VerifyRequest(..) => SequenceStatus::Ignore,
 228        }
 229    }
 230
 231    fn is_switchable<C: EditContext>(&self, _: &C) -> bool {
 232        match self {
 233            IambAction::Message(..) => false,
 234            IambAction::Room(..) => false,
 235            IambAction::Send(..) => false,
 236            IambAction::ToggleScrollbackFocus => false,
 237            IambAction::Verify(..) => false,
 238            IambAction::VerifyRequest(..) => false,
 239        }
 240    }
 241}
 242
 243impl From<RoomAction> for ProgramAction {
 244    fn from(act: RoomAction) -> Self {
 245        IambAction::from(act).into()
 246    }
 247}
 248
 249impl From<IambAction> for ProgramAction {
 250    fn from(act: IambAction) -> Self {
 251        Action::Application(act)
 252    }
 253}
 254
 255pub type ProgramAction = Action<IambInfo>;
 256pub type ProgramContext = VimContext<IambInfo>;
 257pub type Keybindings = VimMachine<TerminalKey, IambInfo>;
 258pub type ProgramCommand = VimCommand<ProgramContext, IambInfo>;
 259pub type ProgramCommands = VimCommandMachine<ProgramContext, IambInfo>;
 260pub type ProgramStore = Store<IambInfo>;
 261pub type AsyncProgramStore = Arc<AsyncMutex<ProgramStore>>;
 262
 263pub type IambResult<T> = UIResult<T, IambInfo>;
 264
 265/// Reaction events for some message.
 266///
 267/// The event identifier used as a key here is the ID for the reaction, and not for the message
 268/// it's reacting to.
 269pub type MessageReactions = HashMap<OwnedEventId, (String, OwnedUserId)>;
 270
 271pub type Receipts = HashMap<OwnedEventId, Vec<OwnedUserId>>;
 272
 273#[derive(thiserror::Error, Debug)]
 274pub enum IambError {
 275    #[error("Invalid user identifier: {0}")]
 276    InvalidUserId(String),
 277
 278    #[error("Invalid verification user/device pair: {0}")]
 279    InvalidVerificationId(String),
 280
 281    #[error("Cryptographic storage error: {0}")]
 282    CryptoStore(#[from] matrix_sdk::encryption::CryptoStoreError),
 283
 284    #[error("HTTP client error: {0}")]
 285    Http(#[from] matrix_sdk::HttpError),
 286
 287    #[error("Matrix client error: {0}")]
 288    Matrix(#[from] matrix_sdk::Error),
 289
 290    #[error("Matrix client storage error: {0}")]
 291    Store(#[from] matrix_sdk::StoreError),
 292
 293    #[error("Serialization/deserialization error: {0}")]
 294    Serde(#[from] serde_json::Error),
 295
 296    #[error("Selected message does not have any attachments")]
 297    NoAttachment,
 298
 299    #[error("No message currently selected")]
 300    NoSelectedMessage,
 301
 302    #[error("Current window is not a room or space")]
 303    NoSelectedRoomOrSpace,
 304
 305    #[error("Current window is not a room")]
 306    NoSelectedRoom,
 307
 308    #[error("You do not have a current invitation to this room")]
 309    NotInvited,
 310
 311    #[error("You need to join the room before you can do that")]
 312    NotJoined,
 313
 314    #[error("Unknown room identifier: {0}")]
 315    UnknownRoom(OwnedRoomId),
 316
 317    #[error("Verification request error: {0}")]
 318    VerificationRequestError(#[from] matrix_sdk::encryption::identities::RequestVerificationError),
 319}
 320
 321impl From<IambError> for UIError<IambInfo> {
 322    fn from(err: IambError) -> Self {
 323        UIError::Application(err)
 324    }
 325}
 326
 327impl ApplicationError for IambError {}
 328
 329#[derive(Default)]
 330pub enum RoomFetchStatus {
 331    Done,
 332    HaveMore(String),
 333    #[default]
 334    NotStarted,
 335}
 336
 337pub enum EventLocation {
 338    Message(MessageKey),
 339    Reaction(OwnedEventId),
 340}
 341
 342impl EventLocation {
 343    fn to_message_key(&self) -> Option<&MessageKey> {
 344        if let EventLocation::Message(key) = self {
 345            Some(key)
 346        } else {
 347            None
 348        }
 349    }
 350}
 351
 352#[derive(Default)]
 353pub struct RoomInfo {
 354    /// The display name for this room.
 355    pub name: Option<String>,
 356
 357    /// The tags placed on this room.
 358    pub tags: Option<Tags>,
 359
 360    /// A map of event IDs to where they are stored in this struct.
 361    pub keys: HashMap<OwnedEventId, EventLocation>,
 362
 363    /// The messages loaded for this room.
 364    pub messages: Messages,
 365
 366    /// A map of read markers to display on different events.
 367    pub receipts: HashMap<OwnedEventId, Vec<OwnedUserId>>,
 368
 369    /// An event ID for where we should indicate we've read up to.
 370    pub read_till: Option<OwnedEventId>,
 371
 372    /// A map of message identifiers to a map of reaction events.
 373    pub reactions: HashMap<OwnedEventId, MessageReactions>,
 374
 375    /// Where to continue fetching from when we continue loading scrollback history.
 376    pub fetch_id: RoomFetchStatus,
 377
 378    /// The time that we last fetched scrollback for this room.
 379    pub fetch_last: Option<Instant>,
 380
 381    /// Users currently typing in this room, and when we received notification of them doing so.
 382    pub users_typing: Option<(Instant, Vec<OwnedUserId>)>,
 383}
 384
 385impl RoomInfo {
 386    pub fn get_reactions(&self, event_id: &EventId) -> Vec<(&str, usize)> {
 387        if let Some(reacts) = self.reactions.get(event_id) {
 388            let mut counts = HashMap::new();
 389
 390            for (key, _) in reacts.values() {
 391                let count = counts.entry(key.as_str()).or_default();
 392                *count += 1;
 393            }
 394
 395            let mut reactions = counts.into_iter().collect::<Vec<_>>();
 396            reactions.sort();
 397
 398            reactions
 399        } else {
 400            vec![]
 401        }
 402    }
 403
 404    pub fn get_event(&self, event_id: &EventId) -> Option<&Message> {
 405        self.messages.get(self.keys.get(event_id)?.to_message_key()?)
 406    }
 407
 408    pub fn insert_reaction(&mut self, react: ReactionEvent) {
 409        match react {
 410            MessageLikeEvent::Original(react) => {
 411                let rel_id = react.content.relates_to.event_id;
 412                let key = react.content.relates_to.key;
 413
 414                let message = self.reactions.entry(rel_id.clone()).or_default();
 415                let event_id = react.event_id;
 416                let user_id = react.sender;
 417
 418                message.insert(event_id.clone(), (key, user_id));
 419
 420                let loc = EventLocation::Reaction(rel_id);
 421                self.keys.insert(event_id, loc);
 422            },
 423            MessageLikeEvent::Redacted(_) => {
 424                return;
 425            },
 426        }
 427    }
 428
 429    pub fn insert_edit(&mut self, msg: Replacement) {
 430        let event_id = msg.event_id;
 431        let new_content = msg.new_content;
 432
 433        let key = if let Some(EventLocation::Message(k)) = self.keys.get(&event_id) {
 434            k
 435        } else {
 436            return;
 437        };
 438
 439        let msg = if let Some(msg) = self.messages.get_mut(key) {
 440            msg
 441        } else {
 442            return;
 443        };
 444
 445        match &mut msg.event {
 446            MessageEvent::Original(orig) => {
 447                orig.content = *new_content;
 448            },
 449            MessageEvent::Local(_, content) => {
 450                *content = new_content;
 451            },
 452            MessageEvent::Redacted(_) => {
 453                return;
 454            },
 455        }
 456    }
 457
 458    pub fn insert_message(&mut self, msg: RoomMessageEvent) {
 459        let event_id = msg.event_id().to_owned();
 460        let key = (msg.origin_server_ts().into(), event_id.clone());
 461
 462        self.keys.insert(event_id.clone(), EventLocation::Message(key.clone()));
 463        self.messages.insert(key, msg.into());
 464
 465        // Remove any echo.
 466        let key = (MessageTimeStamp::LocalEcho, event_id);
 467        let _ = self.messages.remove(&key);
 468    }
 469
 470    pub fn insert(&mut self, msg: RoomMessageEvent) {
 471        match msg {
 472            RoomMessageEvent::Original(OriginalRoomMessageEvent {
 473                content:
 474                    RoomMessageEventContent { relates_to: Some(Relation::Replacement(repl)), .. },
 475                ..
 476            }) => self.insert_edit(repl),
 477            _ => self.insert_message(msg),
 478        }
 479    }
 480
 481    fn recently_fetched(&self) -> bool {
 482        self.fetch_last.map_or(false, |i| i.elapsed() < ROOM_FETCH_DEBOUNCE)
 483    }
 484
 485    fn get_typers(&self) -> &[OwnedUserId] {
 486        if let Some((t, users)) = &self.users_typing {
 487            if t.elapsed() < Duration::from_secs(4) {
 488                return users.as_ref();
 489            } else {
 490                return &[];
 491            }
 492        } else {
 493            return &[];
 494        }
 495    }
 496
 497    fn get_typing_spans<'a>(&'a self, settings: &'a ApplicationSettings) -> Spans<'a> {
 498        let typers = self.get_typers();
 499        let n = typers.len();
 500
 501        match n {
 502            0 => Spans(vec![]),
 503            1 => {
 504                let user = settings.get_user_span(typers[0].as_ref());
 505
 506                Spans(vec![user, Span::from(" is typing...")])
 507            },
 508            2 => {
 509                let user1 = settings.get_user_span(typers[0].as_ref());
 510                let user2 = settings.get_user_span(typers[1].as_ref());
 511
 512                Spans(vec![
 513                    user1,
 514                    Span::raw(" and "),
 515                    user2,
 516                    Span::from(" are typing..."),
 517                ])
 518            },
 519            n if n < 5 => Spans::from("Several people are typing..."),
 520            _ => Spans::from("Many people are typing..."),
 521        }
 522    }
 523
 524    pub fn set_typing(&mut self, user_ids: Vec<OwnedUserId>) {
 525        self.users_typing = (Instant::now(), user_ids).into();
 526    }
 527
 528    pub fn render_typing(
 529        &mut self,
 530        area: Rect,
 531        buf: &mut Buffer,
 532        settings: &ApplicationSettings,
 533    ) -> Rect {
 534        if area.height <= 2 || area.width <= 20 {
 535            return area;
 536        }
 537
 538        if !settings.tunables.typing_notice_display {
 539            return area;
 540        }
 541
 542        let top = Rect::new(area.x, area.y, area.width, area.height - 1);
 543        let bar = Rect::new(area.x, area.y + top.height, area.width, 1);
 544
 545        Paragraph::new(self.get_typing_spans(settings))
 546            .alignment(Alignment::Center)
 547            .render(bar, buf);
 548
 549        return top;
 550    }
 551}
 552
 553fn emoji_map() -> CompletionMap<String, &'static Emoji> {
 554    let mut emojis = CompletionMap::default();
 555
 556    for emoji in emojis::iter() {
 557        for shortcode in emoji.shortcodes() {
 558            emojis.insert(shortcode.to_string(), emoji);
 559        }
 560    }
 561
 562    return emojis;
 563}
 564
 565pub struct ChatStore {
 566    pub cmds: ProgramCommands,
 567    pub worker: Requester,
 568    pub rooms: CompletionMap<OwnedRoomId, RoomInfo>,
 569    pub names: CompletionMap<String, OwnedRoomId>,
 570    pub presences: CompletionMap<OwnedUserId, PresenceState>,
 571    pub verifications: HashMap<String, SasVerification>,
 572    pub settings: ApplicationSettings,
 573    pub need_load: HashSet<OwnedRoomId>,
 574    pub emojis: CompletionMap<String, &'static Emoji>,
 575}
 576
 577impl ChatStore {
 578    pub fn new(worker: Requester, settings: ApplicationSettings) -> Self {
 579        ChatStore {
 580            worker,
 581            settings,
 582
 583            cmds: crate::commands::setup_commands(),
 584            names: Default::default(),
 585            rooms: Default::default(),
 586            presences: Default::default(),
 587            verifications: Default::default(),
 588            need_load: Default::default(),
 589            emojis: emoji_map(),
 590        }
 591    }
 592
 593    pub fn get_joined_room(&self, room_id: &RoomId) -> Option<Joined> {
 594        self.worker.client.get_joined_room(room_id)
 595    }
 596
 597    pub fn get_room_title(&self, room_id: &RoomId) -> String {
 598        self.rooms
 599            .get(room_id)
 600            .and_then(|i| i.name.as_ref())
 601            .map(String::from)
 602            .unwrap_or_else(|| "Untitled Matrix Room".to_string())
 603    }
 604
 605    pub async fn set_receipts(&mut self, receipts: Vec<(OwnedRoomId, Receipts)>) {
 606        let mut updates = vec![];
 607
 608        for (room_id, receipts) in receipts.into_iter() {
 609            if let Some(info) = self.rooms.get_mut(&room_id) {
 610                info.receipts = receipts;
 611
 612                if let Some(read_till) = info.read_till.take() {
 613                    updates.push((room_id, read_till));
 614                }
 615            }
 616        }
 617
 618        for (room_id, read_till) in updates.into_iter() {
 619            if let Some(room) = self.worker.client.get_joined_room(&room_id) {
 620                let _ = room.read_receipt(read_till.as_ref()).await;
 621            }
 622        }
 623    }
 624
 625    pub fn mark_for_load(&mut self, room_id: OwnedRoomId) {
 626        self.need_load.insert(room_id);
 627    }
 628
 629    pub fn load_older(&mut self, limit: u32) {
 630        let ChatStore { need_load, presences, rooms, worker, .. } = self;
 631
 632        for room_id in std::mem::take(need_load).into_iter() {
 633            let info = rooms.get_or_default(room_id.clone());
 634
 635            if info.recently_fetched() {
 636                need_load.insert(room_id);
 637                continue;
 638            } else {
 639                info.fetch_last = Instant::now().into();
 640            }
 641
 642            let fetch_id = match &info.fetch_id {
 643                RoomFetchStatus::Done => continue,
 644                RoomFetchStatus::HaveMore(fetch_id) => Some(fetch_id.clone()),
 645                RoomFetchStatus::NotStarted => None,
 646            };
 647
 648            let res = worker.load_older(room_id.clone(), fetch_id, limit);
 649
 650            match res {
 651                Ok((fetch_id, msgs)) => {
 652                    for msg in msgs.into_iter() {
 653                        let sender = msg.sender().to_owned();
 654                        let _ = presences.get_or_default(sender);
 655
 656                        match msg {
 657                            AnyMessageLikeEvent::RoomMessage(msg) => {
 658                                info.insert(msg);
 659                            },
 660                            AnyMessageLikeEvent::Reaction(ev) => {
 661                                info.insert_reaction(ev);
 662                            },
 663                            _ => continue,
 664                        }
 665                    }
 666
 667                    info.fetch_id =
 668                        fetch_id.map_or(RoomFetchStatus::Done, RoomFetchStatus::HaveMore);
 669                },
 670                Err(e) => {
 671                    warn!(
 672                        room_id = room_id.as_str(),
 673                        err = e.to_string(),
 674                        "Failed to load older messages"
 675                    );
 676
 677                    // Wait and try again.
 678                    need_load.insert(room_id);
 679                },
 680            }
 681        }
 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}