src/base.rs

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