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