src/base.rs

1300 lines · 38529 bytes

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