src/base.rs

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