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