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