src/base.rs
2121 lines · 65956 bytes
1//! # Common types and utilities
2//!
3//! The types defined here get used throughout iamb.
4use std::borrow::Cow;
5use std::collections::hash_map::IntoIter;
6use std::collections::{BTreeSet, HashMap, HashSet};
7use std::convert::TryFrom;
8use std::fmt::{self, Display};
9use std::hash::Hash;
10use std::str::FromStr;
11use std::sync::Arc;
12use std::time::{Duration, Instant};
13
14use emojis::Emoji;
15use ratatui::{
16 buffer::Buffer,
17 layout::{Alignment, Rect},
18 text::{Line, Span},
19 widgets::{Paragraph, Widget},
20};
21use ratatui_image::picker::{Picker, ProtocolType};
22use serde::{
23 de::Error as SerdeError,
24 de::Visitor,
25 Deserialize,
26 Deserializer,
27 Serialize,
28 Serializer,
29};
30use tokio::sync::Mutex as AsyncMutex;
31use url::Url;
32
33use matrix_sdk::{
34 encryption::verification::SasVerification,
35 room::Room as MatrixRoom,
36 ruma::{
37 events::{
38 reaction::ReactionEvent,
39 relation::{Replacement, Thread},
40 room::encrypted::RoomEncryptedEvent,
41 room::message::{
42 OriginalRoomMessageEvent,
43 Relation,
44 RoomMessageEvent,
45 RoomMessageEventContent,
46 RoomMessageEventContentWithoutRelation,
47 },
48 room::redaction::{OriginalSyncRoomRedactionEvent, SyncRoomRedactionEvent},
49 tag::{TagName, Tags},
50 MessageLikeEvent,
51 },
52 presence::PresenceState,
53 EventId,
54 OwnedEventId,
55 OwnedRoomId,
56 OwnedUserId,
57 RoomId,
58 RoomVersionId,
59 UserId,
60 },
61 RoomState as MatrixRoomState,
62};
63
64use modalkit::{
65 actions::Action,
66 editing::{
67 application::{
68 ApplicationAction,
69 ApplicationContentId,
70 ApplicationError,
71 ApplicationInfo,
72 ApplicationStore,
73 ApplicationWindowId,
74 },
75 completion::{complete_path, CompletionMap},
76 context::EditContext,
77 cursor::Cursor,
78 rope::EditRope,
79 store::Store,
80 },
81 env::vim::{
82 command::{CommandContext, CommandDescription, VimCommand, VimCommandMachine},
83 keybindings::VimMachine,
84 },
85 errors::{UIError, UIResult},
86 key::TerminalKey,
87 keybindings::SequenceStatus,
88 prelude::{CommandType, WordStyle},
89};
90
91use crate::config::ImagePreviewProtocolValues;
92use crate::message::ImageStatus;
93use crate::preview::{source_from_event, spawn_insert_preview};
94use crate::{
95 message::{Message, MessageEvent, MessageKey, MessageTimeStamp, Messages},
96 worker::Requester,
97 ApplicationSettings,
98};
99
100/// The set of characters used in different Matrix IDs.
101pub const MATRIX_ID_WORD: WordStyle = WordStyle::CharSet(is_mxid_char);
102
103/// Find the boundaries for a Matrix username, room alias, or room ID.
104///
105/// Technically "[" and "]" should be here since IPv6 addresses are allowed
106/// in the server name, but in practice that should be uncommon, and people
107/// can just use `gf` and friends in Visual mode instead.
108fn is_mxid_char(c: char) -> bool {
109 return c >= 'a' && c <= 'z' ||
110 c >= 'A' && c <= 'Z' ||
111 c >= '0' && c <= '9' ||
112 ":-./@_#!".contains(c);
113}
114
115const ROOM_FETCH_DEBOUNCE: Duration = Duration::from_secs(2);
116
117/// Empty type used solely to implement [ApplicationInfo].
118#[derive(Clone, Debug, Eq, PartialEq)]
119pub enum IambInfo {}
120
121/// An action taken against an ongoing verification request.
122#[derive(Clone, Debug, Eq, PartialEq)]
123pub enum VerifyAction {
124 /// Accept a verification request.
125 Accept,
126
127 /// Cancel an in-progress verification.
128 Cancel,
129
130 /// Confirm an in-progress verification.
131 Confirm,
132
133 /// Reject an in-progress verification due to mismatched Emoji.
134 Mismatch,
135}
136
137/// An action taken against the currently selected message.
138#[derive(Clone, Debug, Eq, PartialEq)]
139pub enum MessageAction {
140 /// Cance the current reply or edit.
141 ///
142 /// The [bool] argument indicates whether to skip confirmation for clearing the message bar.
143 Cancel(bool),
144
145 /// Download an attachment to the given path.
146 ///
147 /// The second argument controls whether to overwrite any already existing file at the
148 /// destination path, or to open the attachment after downloading.
149 Download(Option<String>, DownloadFlags),
150
151 /// Edit a sent message.
152 Edit,
153
154 /// React to a message with an Emoji.
155 React(String),
156
157 /// Redact a message, with an optional reason.
158 ///
159 /// The [bool] argument indicates whether to skip confirmation.
160 Redact(Option<String>, bool),
161
162 /// Reply to a message.
163 Reply,
164
165 /// Unreact to a message.
166 ///
167 /// If no specific Emoji to remove to is specified, then all reactions from the user on the
168 /// message are removed.
169 Unreact(Option<String>),
170}
171
172/// The type of room being created.
173#[derive(Clone, Debug, Eq, PartialEq)]
174pub enum CreateRoomType {
175 /// A direct message room.
176 Direct(OwnedUserId),
177
178 /// A standard chat room.
179 Room,
180
181 /// A Matrix space.
182 Space,
183}
184
185bitflags::bitflags! {
186 /// Available options for newly created rooms.
187 #[derive(Clone, Debug, Eq, PartialEq)]
188 pub struct CreateRoomFlags: u32 {
189 /// No flags specified.
190 const NONE = 0b00000000;
191
192 /// Make the room public.
193 const PUBLIC = 0b00000001;
194
195 /// Encrypt this room.
196 const ENCRYPTED = 0b00000010;
197 }
198}
199
200bitflags::bitflags! {
201 /// Available options when downloading files.
202 #[derive(Clone, Debug, Eq, PartialEq)]
203 pub struct DownloadFlags: u32 {
204 /// No flags specified.
205 const NONE = 0b00000000;
206
207 /// Overwrite file if it already exists.
208 const FORCE = 0b00000001;
209
210 /// Open file after downloading.
211 const OPEN = 0b00000010;
212 }
213}
214
215/// Fields that rooms and spaces can be sorted by.
216#[derive(Clone, Debug, Eq, PartialEq)]
217pub enum SortFieldRoom {
218 /// Sort rooms by whether they have the Favorite tag.
219 Favorite,
220
221 /// Sort rooms by whether they have the Low Priority tag.
222 LowPriority,
223
224 /// Sort rooms by their room name.
225 Name,
226
227 /// Sort rooms by their canonical room alias.
228 Alias,
229
230 /// Sort rooms by their Matrix room identifier.
231 RoomId,
232
233 /// Sort rooms by whether they have unread messages.
234 Unread,
235
236 /// Sort rooms by the timestamps of their most recent messages.
237 Recent,
238}
239
240/// Fields that users can be sorted by.
241#[derive(Clone, Debug, Eq, PartialEq)]
242pub enum SortFieldUser {
243 PowerLevel,
244 UserId,
245 LocalPart,
246 Server,
247}
248
249/// Whether to use the default sort direction for a field, or to reverse it.
250#[derive(Clone, Debug, Eq, PartialEq)]
251pub enum SortOrder {
252 Ascending,
253 Descending,
254}
255
256/// One of the columns to sort on.
257#[derive(Clone, Debug, Eq, PartialEq)]
258pub struct SortColumn<T>(pub T, pub SortOrder);
259
260impl<'de> Deserialize<'de> for SortColumn<SortFieldRoom> {
261 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
262 where
263 D: Deserializer<'de>,
264 {
265 deserializer.deserialize_str(SortRoomVisitor)
266 }
267}
268
269/// [serde] visitor for deserializing [SortColumn] for rooms and spaces.
270struct SortRoomVisitor;
271
272impl<'de> Visitor<'de> for SortRoomVisitor {
273 type Value = SortColumn<SortFieldRoom>;
274
275 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
276 formatter.write_str("a valid field for sorting rooms")
277 }
278
279 fn visit_str<E>(self, mut value: &str) -> Result<Self::Value, E>
280 where
281 E: SerdeError,
282 {
283 if value.is_empty() {
284 return Err(E::custom("Invalid sort field"));
285 }
286
287 let order = if value.starts_with('~') {
288 value = &value[1..];
289 SortOrder::Descending
290 } else {
291 SortOrder::Ascending
292 };
293
294 let field = match value {
295 "favorite" => SortFieldRoom::Favorite,
296 "lowpriority" => SortFieldRoom::LowPriority,
297 "recent" => SortFieldRoom::Recent,
298 "unread" => SortFieldRoom::Unread,
299 "name" => SortFieldRoom::Name,
300 "alias" => SortFieldRoom::Alias,
301 "id" => SortFieldRoom::RoomId,
302 _ => {
303 let msg = format!("Unknown sort field: {value:?}");
304 return Err(E::custom(msg));
305 },
306 };
307
308 Ok(SortColumn(field, order))
309 }
310}
311
312impl<'de> Deserialize<'de> for SortColumn<SortFieldUser> {
313 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
314 where
315 D: Deserializer<'de>,
316 {
317 deserializer.deserialize_str(SortUserVisitor)
318 }
319}
320
321/// [serde] visitor for deserializing [SortColumn] for users.
322struct SortUserVisitor;
323
324impl<'de> Visitor<'de> for SortUserVisitor {
325 type Value = SortColumn<SortFieldUser>;
326
327 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
328 formatter.write_str("a valid field for sorting rooms")
329 }
330
331 fn visit_str<E>(self, mut value: &str) -> Result<Self::Value, E>
332 where
333 E: SerdeError,
334 {
335 if value.is_empty() {
336 return Err(E::custom("Invalid field for sorting users"));
337 }
338
339 let order = if value.starts_with('~') {
340 value = &value[1..];
341 SortOrder::Descending
342 } else {
343 SortOrder::Ascending
344 };
345
346 let field = match value {
347 "id" => SortFieldUser::UserId,
348 "localpart" => SortFieldUser::LocalPart,
349 "server" => SortFieldUser::Server,
350 "power" => SortFieldUser::PowerLevel,
351 _ => {
352 let msg = format!("Unknown sort field: {value:?}");
353 return Err(E::custom(msg));
354 },
355 };
356
357 Ok(SortColumn(field, order))
358 }
359}
360
361/// A room property.
362#[derive(Clone, Debug, Eq, PartialEq)]
363pub enum RoomField {
364 /// The room name.
365 Name,
366
367 /// A room tag.
368 Tag(TagName),
369
370 /// The room topic.
371 Topic,
372
373 /// The room's entire list of alternative aliases.
374 Aliases,
375
376 /// A specific alternative alias to the room.
377 Alias(String),
378
379 /// The room's canonical alias.
380 CanonicalAlias,
381}
382
383/// An action that operates on a focused room.
384#[derive(Clone, Debug, Eq, PartialEq)]
385pub enum RoomAction {
386 /// Accept an invitation to join this room.
387 InviteAccept,
388
389 /// Reject an invitation to join this room.
390 InviteReject,
391
392 /// Invite a user to this room.
393 InviteSend(OwnedUserId),
394
395 /// Leave this room.
396 Leave(bool),
397
398 /// Open the members window.
399 Members(Box<CommandContext>),
400
401 /// Set whether a room is a direct message.
402 SetDirect(bool),
403
404 /// Set a room property.
405 Set(RoomField, String),
406
407 /// Unset a room property.
408 Unset(RoomField),
409
410 /// List the values in a list room property.
411 Show(RoomField),
412}
413
414/// An action that sends a message to a room.
415#[derive(Clone, Debug, Eq, PartialEq)]
416pub enum SendAction {
417 /// Send the text in the message bar.
418 Submit,
419
420 /// Send text provided from an external editor.
421 SubmitFromEditor,
422
423 /// Upload a file.
424 Upload(String),
425
426 /// Upload the image data.
427 UploadImage(usize, usize, Cow<'static, [u8]>),
428}
429
430/// An action performed against the user's homeserver.
431#[derive(Clone, Debug, Eq, PartialEq)]
432pub enum HomeserverAction {
433 /// Create a new room with an optional localpart.
434 CreateRoom(Option<String>, CreateRoomType, CreateRoomFlags),
435 Logout(String, bool),
436}
437
438/// An action performed against the user's room keys.
439#[derive(Clone, Debug, Eq, PartialEq)]
440pub enum KeysAction {
441 /// Export room keys to a file, encrypted with a passphrase.
442 Export(String, String),
443 /// Import room keys from a file, encrypted with a passphrase.
444 Import(String, String),
445}
446
447/// An action that the main program loop should.
448///
449/// See [the commands module][super::commands] for where these are usually created.
450#[derive(Clone, Debug, Eq, PartialEq)]
451pub enum IambAction {
452 /// Perform an action against the homeserver.
453 Homeserver(HomeserverAction),
454
455 /// Perform an action over room keys.
456 Keys(KeysAction),
457
458 /// Perform an action on the currently selected message.
459 Message(MessageAction),
460
461 /// Open a URL.
462 OpenLink(String),
463
464 /// Perform an action on the currently focused room.
465 Room(RoomAction),
466
467 /// Send a message to the currently focused room.
468 Send(SendAction),
469
470 /// Perform an action for an in-progress verification.
471 Verify(VerifyAction, String),
472
473 /// Request a new verification with the specified user.
474 VerifyRequest(String),
475
476 /// Toggle the focus within the focused room.
477 ToggleScrollbackFocus,
478}
479
480impl IambAction {
481 /// Indicates whether this action will draw over the screen.
482 pub fn scribbles(&self) -> bool {
483 matches!(self, IambAction::Send(SendAction::SubmitFromEditor))
484 }
485}
486
487impl From<HomeserverAction> for IambAction {
488 fn from(act: HomeserverAction) -> Self {
489 IambAction::Homeserver(act)
490 }
491}
492
493impl From<MessageAction> for IambAction {
494 fn from(act: MessageAction) -> Self {
495 IambAction::Message(act)
496 }
497}
498
499impl From<RoomAction> for IambAction {
500 fn from(act: RoomAction) -> Self {
501 IambAction::Room(act)
502 }
503}
504
505impl From<SendAction> for IambAction {
506 fn from(act: SendAction) -> Self {
507 IambAction::Send(act)
508 }
509}
510
511impl ApplicationAction for IambAction {
512 fn is_edit_sequence(&self, _: &EditContext) -> SequenceStatus {
513 match self {
514 IambAction::Homeserver(..) => SequenceStatus::Break,
515 IambAction::Keys(..) => SequenceStatus::Break,
516 IambAction::Message(..) => SequenceStatus::Break,
517 IambAction::Room(..) => SequenceStatus::Break,
518 IambAction::OpenLink(..) => SequenceStatus::Break,
519 IambAction::Send(..) => SequenceStatus::Break,
520 IambAction::ToggleScrollbackFocus => SequenceStatus::Break,
521 IambAction::Verify(..) => SequenceStatus::Break,
522 IambAction::VerifyRequest(..) => SequenceStatus::Break,
523 }
524 }
525
526 fn is_last_action(&self, _: &EditContext) -> SequenceStatus {
527 match self {
528 IambAction::Homeserver(..) => SequenceStatus::Atom,
529 IambAction::Keys(..) => SequenceStatus::Atom,
530 IambAction::Message(..) => SequenceStatus::Atom,
531 IambAction::OpenLink(..) => SequenceStatus::Atom,
532 IambAction::Room(..) => SequenceStatus::Atom,
533 IambAction::Send(..) => SequenceStatus::Atom,
534 IambAction::ToggleScrollbackFocus => SequenceStatus::Atom,
535 IambAction::Verify(..) => SequenceStatus::Atom,
536 IambAction::VerifyRequest(..) => SequenceStatus::Atom,
537 }
538 }
539
540 fn is_last_selection(&self, _: &EditContext) -> SequenceStatus {
541 match self {
542 IambAction::Homeserver(..) => SequenceStatus::Ignore,
543 IambAction::Keys(..) => SequenceStatus::Ignore,
544 IambAction::Message(..) => SequenceStatus::Ignore,
545 IambAction::Room(..) => SequenceStatus::Ignore,
546 IambAction::OpenLink(..) => SequenceStatus::Ignore,
547 IambAction::Send(..) => SequenceStatus::Ignore,
548 IambAction::ToggleScrollbackFocus => SequenceStatus::Ignore,
549 IambAction::Verify(..) => SequenceStatus::Ignore,
550 IambAction::VerifyRequest(..) => SequenceStatus::Ignore,
551 }
552 }
553
554 fn is_switchable(&self, _: &EditContext) -> bool {
555 match self {
556 IambAction::Homeserver(..) => false,
557 IambAction::Message(..) => false,
558 IambAction::Room(..) => false,
559 IambAction::Keys(..) => false,
560 IambAction::Send(..) => false,
561 IambAction::OpenLink(..) => false,
562 IambAction::ToggleScrollbackFocus => false,
563 IambAction::Verify(..) => false,
564 IambAction::VerifyRequest(..) => false,
565 }
566 }
567}
568
569impl From<RoomAction> for ProgramAction {
570 fn from(act: RoomAction) -> Self {
571 IambAction::from(act).into()
572 }
573}
574
575impl From<IambAction> for ProgramAction {
576 fn from(act: IambAction) -> Self {
577 Action::Application(act)
578 }
579}
580
581/// Alias for program actions.
582pub type ProgramAction = Action<IambInfo>;
583/// Alias for program context.
584pub type ProgramContext = EditContext;
585/// Alias for program keybindings.
586pub type Keybindings = VimMachine<TerminalKey, IambInfo>;
587/// Alias for a program command.
588pub type ProgramCommand = VimCommand<IambInfo>;
589/// Alias for mapped program commands.
590pub type ProgramCommands = VimCommandMachine<IambInfo>;
591/// Alias for program store.
592pub type ProgramStore = Store<IambInfo>;
593/// Alias for shared program store.
594pub type AsyncProgramStore = Arc<AsyncMutex<ProgramStore>>;
595/// Alias for an action result.
596pub type IambResult<T> = UIResult<T, IambInfo>;
597
598/// Reaction events for some message.
599///
600/// The event identifier used as a key here is the ID for the reaction, and not for the message
601/// it's reacting to.
602pub type MessageReactions = HashMap<OwnedEventId, (String, OwnedUserId)>;
603
604/// Errors encountered during application use.
605#[derive(thiserror::Error, Debug)]
606pub enum IambError {
607 /// An invalid user identifier was specified.
608 #[error("Invalid user identifier: {0}")]
609 InvalidUserId(String),
610
611 /// An invalid user identifier was specified.
612 #[error("Invalid room alias: {0}")]
613 InvalidRoomAlias(String),
614
615 /// An invalid verification identifier was specified.
616 #[error("Invalid verification user/device pair: {0}")]
617 InvalidVerificationId(String),
618
619 /// A failure related to the cryptographic store.
620 #[error("Cryptographic storage error: {0}")]
621 CryptoStore(#[from] matrix_sdk::encryption::CryptoStoreError),
622
623 #[error("Failed to import room keys: {0}")]
624 FailedKeyImport(#[from] matrix_sdk::encryption::RoomKeyImportError),
625
626 /// A failure related to the cryptographic store.
627 #[error("Cannot export keys from sled: {0}")]
628 UpgradeSled(#[from] crate::sled_export::SledMigrationError),
629
630 /// An HTTP error.
631 #[error("HTTP client error: {0}")]
632 Http(#[from] matrix_sdk::HttpError),
633
634 /// A failure from the Matrix client.
635 #[error("Matrix client error: {0}")]
636 Matrix(#[from] matrix_sdk::Error),
637
638 /// A failure in the sled storage.
639 #[error("Matrix client storage error: {0}")]
640 Store(#[from] matrix_sdk::StoreError),
641
642 /// A failure during serialization or deserialization.
643 #[error("Serialization/deserialization error: {0}")]
644 Serde(#[from] serde_json::Error),
645
646 /// A failure due to not having a configured download directory.
647 #[error("No download directory configured")]
648 NoDownloadDir,
649
650 /// A failure due to not having a message with an attachment selected.
651 #[error("Selected message does not have any attachments")]
652 NoAttachment,
653
654 /// A failure due to not having a message selected.
655 #[error("No message currently selected")]
656 NoSelectedMessage,
657
658 /// A failure due to not having a room or space selected.
659 #[error("Current window is not a room or space")]
660 NoSelectedRoomOrSpace,
661
662 /// A failure due to not having a room selected.
663 #[error("Current window is not a room")]
664 NoSelectedRoom,
665
666 /// A failure due to not having an outstanding room invitation.
667 #[error("You do not have a current invitation to this room")]
668 NotInvited,
669
670 /// A failure due to not being a joined room member.
671 #[error("You need to join the room before you can do that")]
672 NotJoined,
673
674 /// An unknown room was specified.
675 #[error("Unknown room identifier: {0}")]
676 UnknownRoom(OwnedRoomId),
677
678 /// An invalid room alias id was specified.
679 #[error("Invalid room alias id: {0}")]
680 InvalidRoomAliasId(#[from] matrix_sdk::ruma::IdParseError),
681
682 /// A failure occurred during verification.
683 #[error("Verification request error: {0}")]
684 VerificationRequestError(#[from] matrix_sdk::encryption::identities::RequestVerificationError),
685
686 /// A failure related to images.
687 #[error("Image error: {0}")]
688 Image(#[from] image::ImageError),
689
690 /// A failure to access the system's clipboard.
691 #[error("Could not use system clipboard data")]
692 Clipboard,
693
694 /// An failure during disk/network/ipc/etc. I/O.
695 #[error("Input/Output error: {0}")]
696 IOError(#[from] std::io::Error),
697
698 /// A failure while trying to show an image preview.
699 #[error("Preview error: {0}")]
700 Preview(String),
701}
702
703impl From<IambError> for UIError<IambInfo> {
704 fn from(err: IambError) -> Self {
705 UIError::Application(err)
706 }
707}
708
709impl ApplicationError for IambError {}
710
711/// Status for tracking how much room scrollback we've fetched.
712#[derive(Default)]
713pub enum RoomFetchStatus {
714 /// Room history has been completely fetched.
715 Done,
716
717 /// More room history can be fetched.
718 HaveMore(String),
719
720 /// We have not yet started fetching history for this room.
721 #[default]
722 NotStarted,
723}
724
725/// Indicates where an [EventId] lives in the [ChatStore].
726pub enum EventLocation {
727 /// The [EventId] belongs to a message.
728 ///
729 /// If the first argument is [None], then it's part of the main scrollback. When [Some],
730 /// it specifies which thread it's in reply to.
731 Message(Option<OwnedEventId>, MessageKey),
732
733 /// The [EventId] belongs to a reaction to the given event.
734 Reaction(OwnedEventId),
735}
736
737impl EventLocation {
738 fn to_message_key(&self) -> Option<&MessageKey> {
739 if let EventLocation::Message(_, key) = self {
740 Some(key)
741 } else {
742 None
743 }
744 }
745}
746
747#[derive(Clone, Debug, Default, Eq, PartialEq)]
748pub struct UnreadInfo {
749 pub(crate) unread: bool,
750 pub(crate) latest: Option<MessageTimeStamp>,
751}
752
753impl UnreadInfo {
754 pub fn is_unread(&self) -> bool {
755 self.unread
756 }
757
758 pub fn latest(&self) -> Option<&MessageTimeStamp> {
759 self.latest.as_ref()
760 }
761}
762
763/// Information about room's the user's joined.
764#[derive(Default)]
765pub struct RoomInfo {
766 /// The display name for this room.
767 pub name: Option<String>,
768
769 /// The tags placed on this room.
770 pub tags: Option<Tags>,
771
772 /// A map of event IDs to where they are stored in this struct.
773 pub keys: HashMap<OwnedEventId, EventLocation>,
774
775 /// The messages loaded for this room.
776 messages: Messages,
777
778 /// A map of read markers to display on different events.
779 pub event_receipts: HashMap<OwnedEventId, HashSet<OwnedUserId>>,
780
781 /// A map of the most recent read marker for each user.
782 ///
783 /// Every receipt in this map should also have an entry in [`event_receipts`],
784 /// however not every user has an entry. If a user's most recent receipt is
785 /// older than the oldest loaded event, that user will not be included.
786 pub user_receipts: HashMap<OwnedUserId, OwnedEventId>,
787
788 /// A map of message identifiers to a map of reaction events.
789 pub reactions: HashMap<OwnedEventId, MessageReactions>,
790
791 /// A map of message identifiers to thread replies.
792 threads: HashMap<OwnedEventId, Messages>,
793
794 /// Whether the scrollback for this room is currently being fetched.
795 pub fetching: bool,
796
797 /// Where to continue fetching from when we continue loading scrollback history.
798 pub fetch_id: RoomFetchStatus,
799
800 /// The time that we last fetched scrollback for this room.
801 pub fetch_last: Option<Instant>,
802
803 /// Users currently typing in this room, and when we received notification of them doing so.
804 pub users_typing: Option<(Instant, Vec<OwnedUserId>)>,
805
806 /// The display names for users in this room.
807 pub display_names: HashMap<OwnedUserId, String>,
808
809 /// The last time the room was rendered, used to detect if it is currently open.
810 pub draw_last: Option<Instant>,
811}
812
813impl RoomInfo {
814 pub fn get_thread(&self, root: Option<&EventId>) -> Option<&Messages> {
815 if let Some(thread_root) = root {
816 self.threads.get(thread_root)
817 } else {
818 Some(&self.messages)
819 }
820 }
821
822 pub fn get_thread_mut(&mut self, root: Option<OwnedEventId>) -> &mut Messages {
823 if let Some(thread_root) = root {
824 self.threads.entry(thread_root).or_default()
825 } else {
826 &mut self.messages
827 }
828 }
829
830 /// Get the event for the last message in a thread (or the thread root if there are no
831 /// in-thread replies yet).
832 ///
833 /// This returns `None` if the event identifier isn't in the room.
834 pub fn get_thread_last<'a>(
835 &'a self,
836 thread_root: &OwnedEventId,
837 ) -> Option<&'a OriginalRoomMessageEvent> {
838 let last = self.threads.get(thread_root).and_then(|t| Some(t.last_key_value()?.1));
839
840 let msg = if let Some(last) = last {
841 &last.event
842 } else if let EventLocation::Message(_, key) = self.keys.get(thread_root)? {
843 let msg = self.messages.get(key)?;
844 &msg.event
845 } else {
846 return None;
847 };
848
849 if let MessageEvent::Original(ev) = &msg {
850 Some(ev)
851 } else {
852 None
853 }
854 }
855
856 /// Get the reactions and their counts for a message.
857 pub fn get_reactions(&self, event_id: &EventId) -> Vec<(&str, usize)> {
858 if let Some(reacts) = self.reactions.get(event_id) {
859 let mut counts = HashMap::new();
860
861 let mut seen_user_reactions = BTreeSet::new();
862
863 for (key, user) in reacts.values() {
864 if !seen_user_reactions.contains(&(key, user)) {
865 seen_user_reactions.insert((key, user));
866 let count = counts.entry(key.as_str()).or_default();
867 *count += 1;
868 }
869 }
870
871 let mut reactions = counts.into_iter().collect::<Vec<_>>();
872 reactions.sort();
873
874 reactions
875 } else {
876 vec![]
877 }
878 }
879
880 /// Map an event identifier to its [MessageKey].
881 pub fn get_message_key(&self, event_id: &EventId) -> Option<&MessageKey> {
882 self.keys.get(event_id)?.to_message_key()
883 }
884
885 /// Get an event for an identifier.
886 pub fn get_event(&self, event_id: &EventId) -> Option<&Message> {
887 self.messages.get(self.get_message_key(event_id)?)
888 }
889
890 /// Get an event for an identifier as mutable.
891 pub fn get_event_mut(&mut self, event_id: &EventId) -> Option<&mut Message> {
892 self.messages.get_mut(self.keys.get(event_id)?.to_message_key()?)
893 }
894
895 pub fn redact(&mut self, ev: OriginalSyncRoomRedactionEvent, room_version: &RoomVersionId) {
896 let Some(redacts) = &ev.redacts else {
897 return;
898 };
899
900 match self.keys.get(redacts) {
901 None => return,
902 Some(EventLocation::Message(None, key)) => {
903 if let Some(msg) = self.messages.get_mut(key) {
904 let ev = SyncRoomRedactionEvent::Original(ev);
905 msg.redact(ev, room_version);
906 }
907 },
908 Some(EventLocation::Message(Some(root), key)) => {
909 if let Some(thread) = self.threads.get_mut(root) {
910 if let Some(msg) = thread.get_mut(key) {
911 let ev = SyncRoomRedactionEvent::Original(ev);
912 msg.redact(ev, room_version);
913 }
914 }
915 },
916 Some(EventLocation::Reaction(event_id)) => {
917 if let Some(reactions) = self.reactions.get_mut(event_id) {
918 reactions.remove(redacts);
919 }
920
921 self.keys.remove(redacts);
922 },
923 }
924 }
925
926 /// Insert a reaction to a message.
927 pub fn insert_reaction(&mut self, react: ReactionEvent) {
928 match react {
929 MessageLikeEvent::Original(react) => {
930 let rel_id = react.content.relates_to.event_id;
931 let key = react.content.relates_to.key;
932
933 let message = self.reactions.entry(rel_id.clone()).or_default();
934 let event_id = react.event_id;
935 let user_id = react.sender;
936
937 message.insert(event_id.clone(), (key, user_id));
938
939 let loc = EventLocation::Reaction(rel_id);
940 self.keys.insert(event_id, loc);
941 },
942 MessageLikeEvent::Redacted(_) => {
943 return;
944 },
945 }
946 }
947
948 /// Insert an edit.
949 pub fn insert_edit(&mut self, msg: Replacement<RoomMessageEventContentWithoutRelation>) {
950 let event_id = msg.event_id;
951 let new_msgtype = msg.new_content;
952
953 let Some(EventLocation::Message(thread, key)) = self.keys.get(&event_id) else {
954 return;
955 };
956
957 let source = if let Some(thread) = thread {
958 self.threads.entry(thread.clone()).or_default()
959 } else {
960 &mut self.messages
961 };
962
963 let Some(msg) = source.get_mut(key) else {
964 return;
965 };
966
967 match &mut msg.event {
968 MessageEvent::Original(orig) => {
969 orig.content.apply_replacement(new_msgtype);
970 },
971 MessageEvent::Local(_, content) => {
972 content.apply_replacement(new_msgtype);
973 },
974 MessageEvent::Redacted(_) |
975 MessageEvent::EncryptedOriginal(_) |
976 MessageEvent::EncryptedRedacted(_) => {
977 return;
978 },
979 }
980
981 msg.html = msg.event.html();
982 }
983
984 /// Indicates whether this room has unread messages.
985 pub fn unreads(&self, settings: &ApplicationSettings) -> UnreadInfo {
986 let last_message = self.messages.last_key_value();
987 let last_receipt = self.get_receipt(&settings.profile.user_id);
988
989 match (last_message, last_receipt) {
990 (Some(((ts, recent), _)), Some(last_read)) => {
991 UnreadInfo { unread: last_read != recent, latest: Some(*ts) }
992 },
993 (Some(((ts, _), _)), None) => UnreadInfo { unread: false, latest: Some(*ts) },
994 (None, _) => UnreadInfo::default(),
995 }
996 }
997
998 /// Inserts events that couldn't be decrypted into the scrollback.
999 pub fn insert_encrypted(&mut self, msg: RoomEncryptedEvent) {
1000 let event_id = msg.event_id().to_owned();
1001 let key = (msg.origin_server_ts().into(), event_id.clone());
1002
1003 self.keys.insert(event_id, EventLocation::Message(None, key.clone()));
1004 self.messages.insert(key, msg.into());
1005 }
1006
1007 /// Insert a new message.
1008 pub fn insert_message(&mut self, msg: RoomMessageEvent) {
1009 let event_id = msg.event_id().to_owned();
1010 let key = (msg.origin_server_ts().into(), event_id.clone());
1011
1012 let loc = EventLocation::Message(None, key.clone());
1013 self.keys.insert(event_id, loc);
1014 self.messages.insert_message(key, msg);
1015 }
1016
1017 fn insert_thread(&mut self, msg: RoomMessageEvent, thread_root: OwnedEventId) {
1018 let event_id = msg.event_id().to_owned();
1019 let key = (msg.origin_server_ts().into(), event_id.clone());
1020
1021 let replies = self.threads.entry(thread_root.clone()).or_default();
1022 let loc = EventLocation::Message(Some(thread_root), key.clone());
1023 self.keys.insert(event_id, loc);
1024 replies.insert_message(key, msg);
1025 }
1026
1027 /// Insert a new message event.
1028 pub fn insert(&mut self, msg: RoomMessageEvent) {
1029 match msg {
1030 RoomMessageEvent::Original(OriginalRoomMessageEvent {
1031 content: RoomMessageEventContent { relates_to: Some(ref relates_to), .. },
1032 ..
1033 }) => {
1034 match relates_to {
1035 Relation::Replacement(repl) => self.insert_edit(repl.clone()),
1036 Relation::Thread(Thread { event_id, .. }) => {
1037 let event_id = event_id.clone();
1038 self.insert_thread(msg, event_id);
1039 },
1040 Relation::Reply { .. } => self.insert_message(msg),
1041 _ => self.insert_message(msg),
1042 }
1043 },
1044 _ => self.insert_message(msg),
1045 }
1046 }
1047
1048 /// Insert a new message event, and spawn a task for image-preview if it has an image
1049 /// attachment.
1050 pub fn insert_with_preview(
1051 &mut self,
1052 room_id: OwnedRoomId,
1053 store: AsyncProgramStore,
1054 picker: Option<Picker>,
1055 ev: RoomMessageEvent,
1056 settings: &mut ApplicationSettings,
1057 media: matrix_sdk::Media,
1058 ) {
1059 let source = picker.and_then(|_| source_from_event(&ev));
1060 self.insert(ev);
1061
1062 if let Some((event_id, source)) = source {
1063 if let (Some(msg), Some(image_preview)) =
1064 (self.get_event_mut(&event_id), &settings.tunables.image_preview)
1065 {
1066 msg.image_preview = ImageStatus::Downloading(image_preview.size.clone());
1067 spawn_insert_preview(
1068 store,
1069 room_id,
1070 event_id,
1071 source,
1072 media,
1073 settings.dirs.image_previews.clone(),
1074 )
1075 }
1076 }
1077 }
1078
1079 /// Indicates whether we've recently fetched scrollback for this room.
1080 pub fn recently_fetched(&self) -> bool {
1081 self.fetch_last.map_or(false, |i| i.elapsed() < ROOM_FETCH_DEBOUNCE)
1082 }
1083
1084 fn clear_receipt(&mut self, user_id: &OwnedUserId) -> Option<()> {
1085 let old_event_id = self.user_receipts.get(user_id)?;
1086 let old_receipts = self.event_receipts.get_mut(old_event_id)?;
1087 old_receipts.remove(user_id);
1088
1089 if old_receipts.is_empty() {
1090 self.event_receipts.remove(old_event_id);
1091 }
1092
1093 None
1094 }
1095
1096 pub fn set_receipt(&mut self, user_id: OwnedUserId, event_id: OwnedEventId) {
1097 self.clear_receipt(&user_id);
1098 self.event_receipts
1099 .entry(event_id.clone())
1100 .or_default()
1101 .insert(user_id.clone());
1102 self.user_receipts.insert(user_id, event_id);
1103 }
1104
1105 pub fn get_receipt(&self, user_id: &UserId) -> Option<&OwnedEventId> {
1106 self.user_receipts.get(user_id)
1107 }
1108
1109 fn get_typers(&self) -> &[OwnedUserId] {
1110 if let Some((t, users)) = &self.users_typing {
1111 if t.elapsed() < Duration::from_secs(4) {
1112 return users.as_ref();
1113 } else {
1114 return &[];
1115 }
1116 } else {
1117 return &[];
1118 }
1119 }
1120
1121 fn get_typing_spans<'a>(&'a self, settings: &'a ApplicationSettings) -> Line<'a> {
1122 let typers = self.get_typers();
1123 let n = typers.len();
1124
1125 match n {
1126 0 => Line::from(vec![]),
1127 1 => {
1128 let user = settings.get_user_span(typers[0].as_ref(), self);
1129
1130 Line::from(vec![user, Span::from(" is typing...")])
1131 },
1132 2 => {
1133 let user1 = settings.get_user_span(typers[0].as_ref(), self);
1134 let user2 = settings.get_user_span(typers[1].as_ref(), self);
1135
1136 Line::from(vec![
1137 user1,
1138 Span::raw(" and "),
1139 user2,
1140 Span::from(" are typing..."),
1141 ])
1142 },
1143 n if n < 5 => Line::from("Several people are typing..."),
1144 _ => Line::from("Many people are typing..."),
1145 }
1146 }
1147
1148 /// Update typing information for this room.
1149 pub fn set_typing(&mut self, user_ids: Vec<OwnedUserId>) {
1150 self.users_typing = (Instant::now(), user_ids).into();
1151 }
1152
1153 /// Create a [Rect] that displays what users are typing.
1154 pub fn render_typing(
1155 &mut self,
1156 area: Rect,
1157 buf: &mut Buffer,
1158 settings: &ApplicationSettings,
1159 ) -> Rect {
1160 if area.height <= 2 || area.width <= 20 {
1161 return area;
1162 }
1163
1164 if !settings.tunables.typing_notice_display {
1165 return area;
1166 }
1167
1168 let top = Rect::new(area.x, area.y, area.width, area.height - 1);
1169 let bar = Rect::new(area.x, area.y + top.height, area.width, 1);
1170
1171 Paragraph::new(self.get_typing_spans(settings))
1172 .alignment(Alignment::Center)
1173 .render(bar, buf);
1174
1175 return top;
1176 }
1177
1178 /// Checks if a given user has reacted with the given emoji on the given event
1179 pub fn user_reactions_contains(
1180 &mut self,
1181 user_id: &UserId,
1182 event_id: &EventId,
1183 emoji: &str,
1184 ) -> bool {
1185 if let Some(reactions) = self.reactions.get(event_id) {
1186 reactions
1187 .values()
1188 .any(|(annotation, user)| annotation == emoji && user == user_id)
1189 } else {
1190 false
1191 }
1192 }
1193}
1194
1195/// Generate a [CompletionMap] for Emoji shortcodes.
1196fn emoji_map() -> CompletionMap<String, &'static Emoji> {
1197 let mut emojis = CompletionMap::default();
1198
1199 for emoji in emojis::iter() {
1200 for shortcode in emoji.shortcodes() {
1201 emojis.insert(shortcode.to_string(), emoji);
1202 }
1203 }
1204
1205 return emojis;
1206}
1207
1208#[cfg(unix)]
1209fn picker_from_termios(protocol_type: Option<ProtocolType>) -> Option<Picker> {
1210 let mut picker = match Picker::from_termios() {
1211 Ok(picker) => picker,
1212 Err(e) => {
1213 tracing::error!("Failed to setup image previews: {e}");
1214 return None;
1215 },
1216 };
1217
1218 if let Some(protocol_type) = protocol_type {
1219 picker.protocol_type = protocol_type;
1220 } else {
1221 picker.guess_protocol();
1222 }
1223
1224 Some(picker)
1225}
1226
1227/// Windows cannot guess the right protocol, and always needs type and font_size.
1228#[cfg(windows)]
1229fn picker_from_termios(_: Option<ProtocolType>) -> Option<Picker> {
1230 tracing::error!("\"image_preview\" requires \"protocol\" with \"type\" and \"font_size\" options on Windows.");
1231 None
1232}
1233
1234fn picker_from_settings(settings: &ApplicationSettings) -> Option<Picker> {
1235 let image_preview = settings.tunables.image_preview.as_ref()?;
1236 let image_preview_protocol = image_preview.protocol.as_ref();
1237
1238 if let Some(&ImagePreviewProtocolValues {
1239 r#type: Some(protocol_type),
1240 font_size: Some(font_size),
1241 }) = image_preview_protocol
1242 {
1243 // User forced type and font_size: use that.
1244 let mut picker = Picker::new(font_size);
1245 picker.protocol_type = protocol_type;
1246 Some(picker)
1247 } else {
1248 // Guess, but use type if forced.
1249 picker_from_termios(image_preview_protocol.and_then(|p| p.r#type))
1250 }
1251}
1252
1253/// Information gathered during server syncs about joined rooms.
1254#[derive(Default)]
1255pub struct SyncInfo {
1256 /// Spaces that the user is a member of.
1257 pub spaces: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
1258
1259 /// Rooms that the user is a member of.
1260 pub rooms: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
1261
1262 /// DMs that the user is a member of.
1263 pub dms: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
1264}
1265
1266bitflags::bitflags! {
1267 /// Load-needs
1268 #[derive(Debug, Default, PartialEq)]
1269 pub struct Need: u32 {
1270 const EMPTY = 0b00000000;
1271 const MESSAGES = 0b00000001;
1272 const MEMBERS = 0b00000010;
1273 }
1274}
1275
1276/// Things that need loading for different rooms.
1277#[derive(Default)]
1278pub struct RoomNeeds {
1279 needs: HashMap<OwnedRoomId, Need>,
1280}
1281
1282impl RoomNeeds {
1283 /// Mark a room for needing something to be loaded.
1284 pub fn insert(&mut self, room_id: OwnedRoomId, need: Need) {
1285 self.needs.entry(room_id).or_default().insert(need);
1286 }
1287
1288 pub fn rooms(&self) -> usize {
1289 self.needs.len()
1290 }
1291}
1292
1293impl IntoIterator for RoomNeeds {
1294 type Item = (OwnedRoomId, Need);
1295 type IntoIter = IntoIter<OwnedRoomId, Need>;
1296
1297 fn into_iter(self) -> Self::IntoIter {
1298 self.needs.into_iter()
1299 }
1300}
1301
1302/// The main application state.
1303pub struct ChatStore {
1304 /// `:`-commands
1305 pub cmds: ProgramCommands,
1306
1307 /// Handle for communicating w/ the worker thread.
1308 pub worker: Requester,
1309
1310 /// Map of joined rooms.
1311 pub rooms: CompletionMap<OwnedRoomId, RoomInfo>,
1312
1313 /// Map of room names.
1314 pub names: CompletionMap<String, OwnedRoomId>,
1315
1316 /// Presence information for other users.
1317 pub presences: CompletionMap<OwnedUserId, PresenceState>,
1318
1319 /// In-progress and completed verifications.
1320 pub verifications: HashMap<String, SasVerification>,
1321
1322 /// Settings for the current profile loaded from config file.
1323 pub settings: ApplicationSettings,
1324
1325 /// Set of rooms that need more messages loaded in their scrollback.
1326 pub need_load: RoomNeeds,
1327
1328 /// [CompletionMap] of Emoji shortcodes.
1329 pub emojis: CompletionMap<String, &'static Emoji>,
1330
1331 /// Information gathered by the background thread.
1332 pub sync_info: SyncInfo,
1333
1334 /// Image preview "protocol" picker.
1335 pub picker: Option<Picker>,
1336
1337 /// Last draw time, used to match with RoomInfo's draw_last.
1338 pub draw_curr: Option<Instant>,
1339
1340 /// Whether to ring the terminal bell on the next redraw.
1341 pub ring_bell: bool,
1342
1343 /// Whether the application is currently focused
1344 pub focused: bool,
1345}
1346
1347impl ChatStore {
1348 /// Create a new [ChatStore].
1349 pub fn new(worker: Requester, settings: ApplicationSettings) -> Self {
1350 let picker = picker_from_settings(&settings);
1351
1352 ChatStore {
1353 worker,
1354 settings,
1355 picker,
1356 cmds: crate::commands::setup_commands(),
1357 emojis: emoji_map(),
1358
1359 names: Default::default(),
1360 rooms: Default::default(),
1361 presences: Default::default(),
1362 verifications: Default::default(),
1363 need_load: Default::default(),
1364 sync_info: Default::default(),
1365 draw_curr: None,
1366 ring_bell: false,
1367 focused: true,
1368 }
1369 }
1370
1371 /// Get a joined room.
1372 pub fn get_joined_room(&self, room_id: &RoomId) -> Option<MatrixRoom> {
1373 let room = self.worker.client.get_room(room_id)?;
1374
1375 if room.state() == MatrixRoomState::Joined {
1376 Some(room)
1377 } else {
1378 None
1379 }
1380 }
1381
1382 /// Get the title for a room.
1383 pub fn get_room_title(&self, room_id: &RoomId) -> String {
1384 self.rooms
1385 .get(room_id)
1386 .and_then(|i| i.name.as_ref())
1387 .map(String::from)
1388 .unwrap_or_else(|| "Untitled Matrix Room".to_string())
1389 }
1390
1391 /// Get the [RoomInfo] for a given room identifier.
1392 pub fn get_room_info(&mut self, room_id: OwnedRoomId) -> &mut RoomInfo {
1393 self.rooms.get_or_default(room_id)
1394 }
1395
1396 /// Set the name for a room.
1397 pub fn set_room_name(&mut self, room_id: &RoomId, name: &str) {
1398 self.rooms.get_or_default(room_id.to_owned()).name = name.to_string().into();
1399 }
1400
1401 /// Insert a new E2EE verification.
1402 pub fn insert_sas(&mut self, sas: SasVerification) {
1403 let key = format!("{}/{}", sas.other_user_id(), sas.other_device().device_id());
1404
1405 self.verifications.insert(key, sas);
1406 }
1407}
1408
1409impl ApplicationStore for ChatStore {}
1410
1411/// Identified used to track window content.
1412#[derive(Clone, Debug, Eq, Hash, PartialEq)]
1413pub enum IambId {
1414 /// A Matrix room, with an optional thread to show.
1415 Room(OwnedRoomId, Option<OwnedEventId>),
1416
1417 /// The `:dms` window.
1418 DirectList,
1419
1420 /// The `:members` window for a given Matrix room.
1421 MemberList(OwnedRoomId),
1422
1423 /// The `:rooms` window.
1424 RoomList,
1425
1426 /// The `:spaces` window.
1427 SpaceList,
1428
1429 /// The `:verify` window.
1430 VerifyList,
1431
1432 /// The `:welcome` window.
1433 Welcome,
1434
1435 /// The `:chats` window.
1436 ChatList,
1437}
1438
1439impl Display for IambId {
1440 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1441 match self {
1442 IambId::Room(room_id, None) => {
1443 write!(f, "iamb://room/{room_id}")
1444 },
1445 IambId::Room(room_id, Some(thread)) => {
1446 write!(f, "iamb://room/{room_id}/threads/{thread}")
1447 },
1448 IambId::MemberList(room_id) => {
1449 write!(f, "iamb://members/{room_id}")
1450 },
1451 IambId::DirectList => f.write_str("iamb://dms"),
1452 IambId::RoomList => f.write_str("iamb://rooms"),
1453 IambId::SpaceList => f.write_str("iamb://spaces"),
1454 IambId::VerifyList => f.write_str("iamb://verify"),
1455 IambId::Welcome => f.write_str("iamb://welcome"),
1456 IambId::ChatList => f.write_str("iamb://chats"),
1457 }
1458 }
1459}
1460
1461impl ApplicationWindowId for IambId {}
1462
1463impl Serialize for IambId {
1464 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1465 where
1466 S: Serializer,
1467 {
1468 serializer.serialize_str(&self.to_string())
1469 }
1470}
1471
1472impl<'de> Deserialize<'de> for IambId {
1473 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1474 where
1475 D: Deserializer<'de>,
1476 {
1477 deserializer.deserialize_str(IambIdVisitor)
1478 }
1479}
1480
1481/// [serde] visitor for deserializing [IambId].
1482struct IambIdVisitor;
1483
1484impl<'de> Visitor<'de> for IambIdVisitor {
1485 type Value = IambId;
1486
1487 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1488 formatter.write_str("a valid window URL")
1489 }
1490
1491 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1492 where
1493 E: SerdeError,
1494 {
1495 let Ok(url) = Url::parse(value) else {
1496 return Err(E::custom("Invalid iamb window URL"));
1497 };
1498
1499 if url.scheme() != "iamb" {
1500 return Err(E::custom("Invalid iamb window URL"));
1501 }
1502
1503 match url.domain() {
1504 Some("room") => {
1505 let Some(path) = url.path_segments() else {
1506 return Err(E::custom("Invalid members window URL"));
1507 };
1508
1509 match *path.collect::<Vec<_>>().as_slice() {
1510 [room_id] => {
1511 let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
1512 return Err(E::custom("Invalid room identifier"));
1513 };
1514
1515 Ok(IambId::Room(room_id, None))
1516 },
1517 [room_id, "threads", thread_root] => {
1518 let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
1519 return Err(E::custom("Invalid room identifier"));
1520 };
1521
1522 let Ok(thread_root) = OwnedEventId::try_from(thread_root) else {
1523 return Err(E::custom("Invalid thread root identifier"));
1524 };
1525
1526 Ok(IambId::Room(room_id, Some(thread_root)))
1527 },
1528 _ => return Err(E::custom("Invalid members window URL")),
1529 }
1530 },
1531 Some("members") => {
1532 let Some(path) = url.path_segments() else {
1533 return Err(E::custom("Invalid members window URL"));
1534 };
1535
1536 let &[room_id] = path.collect::<Vec<_>>().as_slice() else {
1537 return Err(E::custom("Invalid members window URL"));
1538 };
1539
1540 let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
1541 return Err(E::custom("Invalid room identifier"));
1542 };
1543
1544 Ok(IambId::MemberList(room_id))
1545 },
1546 Some("dms") => {
1547 if url.path() != "" {
1548 return Err(E::custom("iamb://dms takes no path"));
1549 }
1550
1551 Ok(IambId::DirectList)
1552 },
1553 Some("rooms") => {
1554 if url.path() != "" {
1555 return Err(E::custom("iamb://rooms takes no path"));
1556 }
1557
1558 Ok(IambId::RoomList)
1559 },
1560 Some("spaces") => {
1561 if url.path() != "" {
1562 return Err(E::custom("iamb://spaces takes no path"));
1563 }
1564
1565 Ok(IambId::SpaceList)
1566 },
1567 Some("verify") => {
1568 if url.path() != "" {
1569 return Err(E::custom("iamb://verify takes no path"));
1570 }
1571
1572 Ok(IambId::VerifyList)
1573 },
1574 Some("welcome") => {
1575 if url.path() != "" {
1576 return Err(E::custom("iamb://welcome takes no path"));
1577 }
1578
1579 Ok(IambId::Welcome)
1580 },
1581 Some("chats") => {
1582 if url.path() != "" {
1583 return Err(E::custom("iamb://chats takes no path"));
1584 }
1585
1586 Ok(IambId::ChatList)
1587 },
1588 Some(s) => Err(E::custom(format!("{s:?} is not a valid window"))),
1589 None => Err(E::custom("Invalid iamb window URL")),
1590 }
1591 }
1592}
1593
1594/// Which part of the room window's UI is focused.
1595#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1596pub enum RoomFocus {
1597 /// The scrollback for a room window is focused.
1598 Scrollback,
1599
1600 /// The message bar for a room window is focused.
1601 MessageBar,
1602}
1603
1604impl RoomFocus {
1605 /// Whether this is [RoomFocus::Scrollback].
1606 pub fn is_scrollback(&self) -> bool {
1607 matches!(self, RoomFocus::Scrollback)
1608 }
1609
1610 /// Whether this is [RoomFocus::MessageBar].
1611 pub fn is_msgbar(&self) -> bool {
1612 matches!(self, RoomFocus::MessageBar)
1613 }
1614}
1615
1616/// Identifiers used to track where a mark was placed.
1617///
1618/// While this is the "buffer identifier" for the mark,
1619/// not all of these are necessarily actual buffers.
1620#[derive(Clone, Debug, Eq, Hash, PartialEq)]
1621pub enum IambBufferId {
1622 /// The command bar buffer.
1623 Command(CommandType),
1624
1625 /// The message buffer or a specific message in a room.
1626 Room(OwnedRoomId, Option<OwnedEventId>, RoomFocus),
1627
1628 /// The `:dms` window.
1629 DirectList,
1630
1631 /// The `:members` window for a room.
1632 MemberList(OwnedRoomId),
1633
1634 /// The `:rooms` window.
1635 RoomList,
1636
1637 /// The `:spaces` window.
1638 SpaceList,
1639
1640 /// The `:verify` window.
1641 VerifyList,
1642
1643 /// The buffer for the `:rooms` window.
1644 Welcome,
1645
1646 /// The `:chats` window.
1647 ChatList,
1648}
1649
1650impl IambBufferId {
1651 /// Get the identifier for the window that contains this buffer.
1652 pub fn to_window(&self) -> Option<IambId> {
1653 let id = match self {
1654 IambBufferId::Command(_) => return None,
1655 IambBufferId::Room(room, thread, _) => IambId::Room(room.clone(), thread.clone()),
1656 IambBufferId::DirectList => IambId::DirectList,
1657 IambBufferId::MemberList(room) => IambId::MemberList(room.clone()),
1658 IambBufferId::RoomList => IambId::RoomList,
1659 IambBufferId::SpaceList => IambId::SpaceList,
1660 IambBufferId::VerifyList => IambId::VerifyList,
1661 IambBufferId::Welcome => IambId::Welcome,
1662 IambBufferId::ChatList => IambId::ChatList,
1663 };
1664
1665 Some(id)
1666 }
1667}
1668
1669impl ApplicationContentId for IambBufferId {}
1670
1671impl ApplicationInfo for IambInfo {
1672 type Error = IambError;
1673 type Store = ChatStore;
1674 type Action = IambAction;
1675 type WindowId = IambId;
1676 type ContentId = IambBufferId;
1677
1678 fn complete(
1679 text: &EditRope,
1680 cursor: &mut Cursor,
1681 content: &IambBufferId,
1682 store: &mut ProgramStore,
1683 ) -> Vec<String> {
1684 match content {
1685 IambBufferId::Command(CommandType::Command) => complete_cmdbar(text, cursor, store),
1686 IambBufferId::Command(CommandType::Search) => vec![],
1687 IambBufferId::Room(_, _, RoomFocus::MessageBar) => complete_msgbar(text, cursor, store),
1688 IambBufferId::Room(_, _, RoomFocus::Scrollback) => vec![],
1689
1690 IambBufferId::DirectList => vec![],
1691 IambBufferId::MemberList(_) => vec![],
1692 IambBufferId::RoomList => vec![],
1693 IambBufferId::SpaceList => vec![],
1694 IambBufferId::VerifyList => vec![],
1695 IambBufferId::Welcome => vec![],
1696 IambBufferId::ChatList => vec![],
1697 }
1698 }
1699
1700 fn content_of_command(ct: CommandType) -> IambBufferId {
1701 IambBufferId::Command(ct)
1702 }
1703}
1704
1705/// Tab completion for user IDs.
1706fn complete_users(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
1707 let id = text
1708 .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
1709 .unwrap_or_else(EditRope::empty);
1710 let id = Cow::from(&id);
1711
1712 store
1713 .application
1714 .presences
1715 .complete(id.as_ref())
1716 .into_iter()
1717 .map(|i| i.to_string())
1718 .collect()
1719}
1720
1721/// Tab completion within the message bar.
1722fn complete_msgbar(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
1723 let id = text
1724 .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
1725 .unwrap_or_else(EditRope::empty);
1726 let id = Cow::from(&id);
1727
1728 match id.chars().next() {
1729 // Complete room aliases.
1730 Some('#') => {
1731 return store.application.names.complete(id.as_ref());
1732 },
1733
1734 // Complete room identifiers.
1735 Some('!') => {
1736 return store
1737 .application
1738 .rooms
1739 .complete(id.as_ref())
1740 .into_iter()
1741 .map(|i| i.to_string())
1742 .collect();
1743 },
1744
1745 // Complete Emoji shortcodes.
1746 Some(':') => {
1747 let list = store.application.emojis.complete(&id[1..]);
1748 let iter = list.into_iter().take(200).map(|s| format!(":{}:", s));
1749
1750 return iter.collect();
1751 },
1752
1753 // Complete usernames for @ and empty strings.
1754 Some('@') | None => {
1755 return store
1756 .application
1757 .presences
1758 .complete(id.as_ref())
1759 .into_iter()
1760 .map(|i| i.to_string())
1761 .collect();
1762 },
1763
1764 // Unknown sigil.
1765 Some(_) => return vec![],
1766 }
1767}
1768
1769/// Tab completion for Matrix identifiers (usernames, room aliases, etc.)
1770fn complete_matrix_names(
1771 text: &EditRope,
1772 cursor: &mut Cursor,
1773 store: &ProgramStore,
1774) -> Vec<String> {
1775 let id = text
1776 .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
1777 .unwrap_or_else(EditRope::empty);
1778 let id = Cow::from(&id);
1779
1780 let list = store.application.names.complete(id.as_ref());
1781 if !list.is_empty() {
1782 return list;
1783 }
1784
1785 let list = store.application.presences.complete(id.as_ref());
1786 if !list.is_empty() {
1787 return list.into_iter().map(|i| i.to_string()).collect();
1788 }
1789
1790 store
1791 .application
1792 .rooms
1793 .complete(id.as_ref())
1794 .into_iter()
1795 .map(|i| i.to_string())
1796 .collect()
1797}
1798
1799/// Tab completion for Emoji shortcode names.
1800fn complete_emoji(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
1801 let sc = text.get_prefix_word_mut(cursor, &WordStyle::Little);
1802 let sc = sc.unwrap_or_else(EditRope::empty);
1803 let sc = Cow::from(&sc);
1804
1805 store.application.emojis.complete(sc.as_ref())
1806}
1807
1808/// Tab completion for command names.
1809fn complete_cmdname(
1810 desc: CommandDescription,
1811 text: &EditRope,
1812 cursor: &mut Cursor,
1813 store: &ProgramStore,
1814) -> Vec<String> {
1815 // Complete command name and set cursor position.
1816 let _ = text.get_prefix_word_mut(cursor, &WordStyle::Little);
1817 store.application.cmds.complete_name(desc.command.as_str())
1818}
1819
1820/// Tab completion for command arguments.
1821fn complete_cmdarg(
1822 desc: CommandDescription,
1823 text: &EditRope,
1824 cursor: &mut Cursor,
1825 store: &ProgramStore,
1826) -> Vec<String> {
1827 let cmd = match store.application.cmds.get(desc.command.as_str()) {
1828 Ok(cmd) => cmd,
1829 Err(_) => return vec![],
1830 };
1831
1832 match cmd.name.as_str() {
1833 "cancel" | "dms" | "edit" | "redact" | "reply" => vec![],
1834 "members" | "rooms" | "spaces" | "welcome" => vec![],
1835 "download" | "keys" | "open" | "upload" => complete_path(text, cursor),
1836 "react" | "unreact" => complete_emoji(text, cursor, store),
1837
1838 "invite" => complete_users(text, cursor, store),
1839 "join" | "split" | "vsplit" | "tabedit" => complete_matrix_names(text, cursor, store),
1840 "room" => vec![],
1841 "verify" => vec![],
1842 "vertical" | "horizontal" | "aboveleft" | "belowright" | "tab" => {
1843 complete_cmd(desc.arg.text.as_str(), text, cursor, store)
1844 },
1845 _ => vec![],
1846 }
1847}
1848
1849/// Tab completion for commands.
1850fn complete_cmd(
1851 cmd: &str,
1852 text: &EditRope,
1853 cursor: &mut Cursor,
1854 store: &ProgramStore,
1855) -> Vec<String> {
1856 match CommandDescription::from_str(cmd) {
1857 Ok(desc) => {
1858 if desc.arg.untrimmed.is_empty() {
1859 complete_cmdname(desc, text, cursor, store)
1860 } else {
1861 // Complete command argument.
1862 complete_cmdarg(desc, text, cursor, store)
1863 }
1864 },
1865
1866 // Can't parse command text, so return zero completions.
1867 Err(_) => vec![],
1868 }
1869}
1870
1871/// Tab completion for the command bar.
1872fn complete_cmdbar(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
1873 let eo = text.cursor_to_offset(cursor);
1874 let slice = text.slice(..eo);
1875 let cow = Cow::from(&slice);
1876
1877 complete_cmd(cow.as_ref(), text, cursor, store)
1878}
1879
1880#[cfg(test)]
1881pub mod tests {
1882 use super::*;
1883 use crate::config::user_style_from_color;
1884 use crate::tests::*;
1885 use matrix_sdk::ruma::{
1886 events::{reaction::ReactionEventContent, relation::Annotation, MessageLikeUnsigned},
1887 owned_event_id,
1888 owned_room_id,
1889 owned_user_id,
1890 MilliSecondsSinceUnixEpoch,
1891 };
1892 use pretty_assertions::assert_eq;
1893 use ratatui::style::Color;
1894
1895 #[test]
1896 fn multiple_identical_reactions() {
1897 let mut info = RoomInfo::default();
1898
1899 let content = ReactionEventContent::new(Annotation::new(
1900 owned_event_id!("$my_reaction"),
1901 "🏠".to_owned(),
1902 ));
1903
1904 for i in 0..3 {
1905 let event_id = format!("$house_{}", i);
1906 info.insert_reaction(MessageLikeEvent::Original(
1907 matrix_sdk::ruma::events::OriginalMessageLikeEvent {
1908 content: content.clone(),
1909 event_id: OwnedEventId::from_str(&event_id).unwrap(),
1910 sender: owned_user_id!("@foo:example.org"),
1911 origin_server_ts: MilliSecondsSinceUnixEpoch::now(),
1912 room_id: owned_room_id!("!foo:example.org"),
1913 unsigned: MessageLikeUnsigned::new(),
1914 },
1915 ));
1916 }
1917
1918 let content = ReactionEventContent::new(Annotation::new(
1919 owned_event_id!("$my_reaction"),
1920 "🙂".to_owned(),
1921 ));
1922
1923 for i in 0..2 {
1924 let event_id = format!("$smile_{}", i);
1925 info.insert_reaction(MessageLikeEvent::Original(
1926 matrix_sdk::ruma::events::OriginalMessageLikeEvent {
1927 content: content.clone(),
1928 event_id: OwnedEventId::from_str(&event_id).unwrap(),
1929 sender: owned_user_id!("@foo:example.org"),
1930 origin_server_ts: MilliSecondsSinceUnixEpoch::now(),
1931 room_id: owned_room_id!("!foo:example.org"),
1932 unsigned: MessageLikeUnsigned::new(),
1933 },
1934 ));
1935 }
1936
1937 for i in 2..4 {
1938 let event_id = format!("$smile_{}", i);
1939 info.insert_reaction(MessageLikeEvent::Original(
1940 matrix_sdk::ruma::events::OriginalMessageLikeEvent {
1941 content: content.clone(),
1942 event_id: OwnedEventId::from_str(&event_id).unwrap(),
1943 sender: owned_user_id!("@bar:example.org"),
1944 origin_server_ts: MilliSecondsSinceUnixEpoch::now(),
1945 room_id: owned_room_id!("!foo:example.org"),
1946 unsigned: MessageLikeUnsigned::new(),
1947 },
1948 ));
1949 }
1950
1951 assert_eq!(info.get_reactions(&owned_event_id!("$my_reaction")), vec![
1952 ("🏠", 1),
1953 ("🙂", 2)
1954 ]);
1955 }
1956
1957 #[test]
1958 fn test_typing_spans() {
1959 let mut info = RoomInfo::default();
1960 let settings = mock_settings();
1961
1962 let users0 = vec![];
1963 let users1 = vec![TEST_USER1.clone()];
1964 let users2 = vec![TEST_USER1.clone(), TEST_USER2.clone()];
1965 let users4 = vec![
1966 TEST_USER1.clone(),
1967 TEST_USER2.clone(),
1968 TEST_USER3.clone(),
1969 TEST_USER4.clone(),
1970 ];
1971 let users5 = vec![
1972 TEST_USER1.clone(),
1973 TEST_USER2.clone(),
1974 TEST_USER3.clone(),
1975 TEST_USER4.clone(),
1976 TEST_USER5.clone(),
1977 ];
1978
1979 // Nothing set.
1980 assert_eq!(info.users_typing, None);
1981 assert_eq!(info.get_typing_spans(&settings), Line::from(vec![]));
1982
1983 // Empty typing list.
1984 info.set_typing(users0);
1985 assert!(info.users_typing.is_some());
1986 assert_eq!(info.get_typing_spans(&settings), Line::from(vec![]));
1987
1988 // Single user typing.
1989 info.set_typing(users1);
1990 assert!(info.users_typing.is_some());
1991 assert_eq!(
1992 info.get_typing_spans(&settings),
1993 Line::from(vec![
1994 Span::styled("@user1:example.com", user_style("@user1:example.com")),
1995 Span::from(" is typing...")
1996 ])
1997 );
1998
1999 // Two users typing.
2000 info.set_typing(users2);
2001 assert!(info.users_typing.is_some());
2002 assert_eq!(
2003 info.get_typing_spans(&settings),
2004 Line::from(vec![
2005 Span::styled("@user1:example.com", user_style("@user1:example.com")),
2006 Span::raw(" and "),
2007 Span::styled("@user2:example.com", user_style("@user2:example.com")),
2008 Span::raw(" are typing...")
2009 ])
2010 );
2011
2012 // Four users typing.
2013 info.set_typing(users4);
2014 assert!(info.users_typing.is_some());
2015 assert_eq!(info.get_typing_spans(&settings), Line::from("Several people are typing..."));
2016
2017 // Five users typing.
2018 info.set_typing(users5);
2019 assert!(info.users_typing.is_some());
2020 assert_eq!(info.get_typing_spans(&settings), Line::from("Many people are typing..."));
2021
2022 // Test that USER5 gets rendered using the configured color and name.
2023 info.set_typing(vec![TEST_USER5.clone()]);
2024 assert!(info.users_typing.is_some());
2025 assert_eq!(
2026 info.get_typing_spans(&settings),
2027 Line::from(vec![
2028 Span::styled("USER 5", user_style_from_color(Color::Black)),
2029 Span::from(" is typing...")
2030 ])
2031 );
2032 }
2033
2034 #[test]
2035 fn test_need_load() {
2036 let room_id = TEST_ROOM1_ID.clone();
2037
2038 let mut need_load = RoomNeeds::default();
2039
2040 need_load.insert(room_id.clone(), Need::MESSAGES);
2041 need_load.insert(room_id.clone(), Need::MEMBERS);
2042
2043 assert_eq!(need_load.into_iter().collect::<Vec<(OwnedRoomId, Need)>>(), vec![(
2044 room_id,
2045 Need::MESSAGES | Need::MEMBERS,
2046 )],);
2047 }
2048
2049 #[tokio::test]
2050 async fn test_complete_msgbar() {
2051 let store = mock_store().await;
2052
2053 let text = EditRope::from("going for a walk :walk ");
2054 let mut cursor = Cursor::new(0, 22);
2055 let res = complete_msgbar(&text, &mut cursor, &store);
2056 assert_eq!(res, vec![":walking:", ":walking_man:", ":walking_woman:"]);
2057 assert_eq!(cursor, Cursor::new(0, 17));
2058
2059 let text = EditRope::from("hello @user1 ");
2060 let mut cursor = Cursor::new(0, 12);
2061 let res = complete_msgbar(&text, &mut cursor, &store);
2062 assert_eq!(res, vec!["@user1:example.com"]);
2063 assert_eq!(cursor, Cursor::new(0, 6));
2064
2065 let text = EditRope::from("see #room ");
2066 let mut cursor = Cursor::new(0, 9);
2067 let res = complete_msgbar(&text, &mut cursor, &store);
2068 assert_eq!(res, vec!["#room1:example.com"]);
2069 assert_eq!(cursor, Cursor::new(0, 4));
2070 }
2071
2072 #[tokio::test]
2073 async fn test_complete_cmdbar() {
2074 let store = mock_store().await;
2075 let users = vec![
2076 "@user1:example.com",
2077 "@user2:example.com",
2078 "@user3:example.com",
2079 "@user4:example.com",
2080 "@user5:example.com",
2081 ];
2082
2083 let text = EditRope::from("invite ");
2084 let mut cursor = Cursor::new(0, 7);
2085 let id = text
2086 .get_prefix_word_mut(&mut cursor, &MATRIX_ID_WORD)
2087 .unwrap_or_else(EditRope::empty);
2088 assert_eq!(id.to_string(), "");
2089 assert_eq!(cursor, Cursor::new(0, 7));
2090
2091 let text = EditRope::from("invite ");
2092 let mut cursor = Cursor::new(0, 7);
2093 let res = complete_cmdbar(&text, &mut cursor, &store);
2094 assert_eq!(res, users);
2095
2096 let text = EditRope::from("invite ignored");
2097 let mut cursor = Cursor::new(0, 7);
2098 let res = complete_cmdbar(&text, &mut cursor, &store);
2099 assert_eq!(res, users);
2100
2101 let text = EditRope::from("invite @user1ignored");
2102 let mut cursor = Cursor::new(0, 13);
2103 let res = complete_cmdbar(&text, &mut cursor, &store);
2104 assert_eq!(res, vec!["@user1:example.com"]);
2105
2106 let text = EditRope::from("abo hor");
2107 let mut cursor = Cursor::new(0, 7);
2108 let res = complete_cmdbar(&text, &mut cursor, &store);
2109 assert_eq!(res, vec!["horizontal"]);
2110
2111 let text = EditRope::from("abo hor inv");
2112 let mut cursor = Cursor::new(0, 11);
2113 let res = complete_cmdbar(&text, &mut cursor, &store);
2114 assert_eq!(res, vec!["invite"]);
2115
2116 let text = EditRope::from("abo hor invite \n");
2117 let mut cursor = Cursor::new(0, 15);
2118 let res = complete_cmdbar(&text, &mut cursor, &store);
2119 assert_eq!(res, users);
2120 }
2121}