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