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