src/base.rs
2261 lines · 70433 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 Visitor<'_> 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 Visitor<'_> 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.is_some_and(|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_query_stdio() {
1323 Ok(picker) => picker,
1324 Err(e) => {
1325 tracing::error!("Failed to setup image previews: {e}");
1326 return None;
1327 },
1328 };
1329
1330 if let Some(protocol_type) = protocol_type {
1331 picker.set_protocol_type(protocol_type);
1332 }
1333
1334 Some(picker)
1335}
1336
1337/// Windows cannot guess the right protocol, and always needs type and font_size.
1338#[cfg(windows)]
1339fn picker_from_termios(_: Option<ProtocolType>) -> Option<Picker> {
1340 tracing::error!("\"image_preview\" requires \"protocol\" with \"type\" and \"font_size\" options on Windows.");
1341 None
1342}
1343
1344fn picker_from_settings(settings: &ApplicationSettings) -> Option<Picker> {
1345 let image_preview = settings.tunables.image_preview.as_ref()?;
1346 let image_preview_protocol = image_preview.protocol.as_ref();
1347
1348 if let Some(&ImagePreviewProtocolValues {
1349 r#type: Some(protocol_type),
1350 font_size: Some(font_size),
1351 }) = image_preview_protocol
1352 {
1353 // User forced type and font_size: use that.
1354 let mut picker = Picker::from_fontsize(font_size);
1355 picker.set_protocol_type(protocol_type);
1356 Some(picker)
1357 } else {
1358 // Guess, but use type if forced.
1359 picker_from_termios(image_preview_protocol.and_then(|p| p.r#type))
1360 }
1361}
1362
1363/// Information gathered during server syncs about joined rooms.
1364#[derive(Default)]
1365pub struct SyncInfo {
1366 /// Spaces that the user is a member of.
1367 pub spaces: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
1368
1369 /// Rooms that the user is a member of.
1370 pub rooms: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
1371
1372 /// DMs that the user is a member of.
1373 pub dms: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
1374}
1375
1376impl SyncInfo {
1377 pub fn rooms(&self) -> impl Iterator<Item = &RoomId> {
1378 self.rooms.iter().map(|r| r.0.room_id())
1379 }
1380
1381 pub fn dms(&self) -> impl Iterator<Item = &RoomId> {
1382 self.dms.iter().map(|r| r.0.room_id())
1383 }
1384
1385 pub fn chats(&self) -> impl Iterator<Item = &RoomId> {
1386 self.rooms().chain(self.dms())
1387 }
1388}
1389
1390bitflags::bitflags! {
1391 /// Load-needs
1392 #[derive(Debug, Default, PartialEq)]
1393 pub struct Need: u32 {
1394 const EMPTY = 0b00000000;
1395 const MESSAGES = 0b00000001;
1396 const MEMBERS = 0b00000010;
1397 }
1398}
1399
1400/// Things that need loading for different rooms.
1401#[derive(Default)]
1402pub struct RoomNeeds {
1403 needs: HashMap<OwnedRoomId, Need>,
1404}
1405
1406impl RoomNeeds {
1407 /// Mark a room for needing something to be loaded.
1408 pub fn insert(&mut self, room_id: OwnedRoomId, need: Need) {
1409 self.needs.entry(room_id).or_default().insert(need);
1410 }
1411
1412 pub fn rooms(&self) -> usize {
1413 self.needs.len()
1414 }
1415}
1416
1417impl IntoIterator for RoomNeeds {
1418 type Item = (OwnedRoomId, Need);
1419 type IntoIter = IntoIter<OwnedRoomId, Need>;
1420
1421 fn into_iter(self) -> Self::IntoIter {
1422 self.needs.into_iter()
1423 }
1424}
1425
1426/// The main application state.
1427pub struct ChatStore {
1428 /// `:`-commands
1429 pub cmds: ProgramCommands,
1430
1431 /// Handle for communicating w/ the worker thread.
1432 pub worker: Requester,
1433
1434 /// Map of joined rooms.
1435 pub rooms: CompletionMap<OwnedRoomId, RoomInfo>,
1436
1437 /// Map of room names.
1438 pub names: CompletionMap<String, OwnedRoomId>,
1439
1440 /// Presence information for other users.
1441 pub presences: CompletionMap<OwnedUserId, PresenceState>,
1442
1443 /// In-progress and completed verifications.
1444 pub verifications: HashMap<String, SasVerification>,
1445
1446 /// Settings for the current profile loaded from config file.
1447 pub settings: ApplicationSettings,
1448
1449 /// Set of rooms that need more messages loaded in their scrollback.
1450 pub need_load: RoomNeeds,
1451
1452 /// [CompletionMap] of Emoji shortcodes.
1453 pub emojis: CompletionMap<String, &'static Emoji>,
1454
1455 /// Information gathered by the background thread.
1456 pub sync_info: SyncInfo,
1457
1458 /// Image preview "protocol" picker.
1459 pub picker: Option<Picker>,
1460
1461 /// Last draw time, used to match with RoomInfo's draw_last.
1462 pub draw_curr: Option<Instant>,
1463
1464 /// Whether to ring the terminal bell on the next redraw.
1465 pub ring_bell: bool,
1466
1467 /// Whether the application is currently focused
1468 pub focused: bool,
1469}
1470
1471impl ChatStore {
1472 /// Create a new [ChatStore].
1473 pub fn new(worker: Requester, settings: ApplicationSettings) -> Self {
1474 let picker = picker_from_settings(&settings);
1475
1476 ChatStore {
1477 worker,
1478 settings,
1479 picker,
1480 cmds: crate::commands::setup_commands(),
1481 emojis: emoji_map(),
1482
1483 names: Default::default(),
1484 rooms: Default::default(),
1485 presences: Default::default(),
1486 verifications: Default::default(),
1487 need_load: Default::default(),
1488 sync_info: Default::default(),
1489 draw_curr: None,
1490 ring_bell: false,
1491 focused: true,
1492 }
1493 }
1494
1495 /// Get a joined room.
1496 pub fn get_joined_room(&self, room_id: &RoomId) -> Option<MatrixRoom> {
1497 let room = self.worker.client.get_room(room_id)?;
1498
1499 if room.state() == MatrixRoomState::Joined {
1500 Some(room)
1501 } else {
1502 None
1503 }
1504 }
1505
1506 /// Get the title for a room.
1507 pub fn get_room_title(&self, room_id: &RoomId) -> String {
1508 self.rooms
1509 .get(room_id)
1510 .and_then(|i| i.name.as_ref())
1511 .map(String::from)
1512 .unwrap_or_else(|| "Untitled Matrix Room".to_string())
1513 }
1514
1515 /// Get the [RoomInfo] for a given room identifier.
1516 pub fn get_room_info(&mut self, room_id: OwnedRoomId) -> &mut RoomInfo {
1517 self.rooms.get_or_default(room_id)
1518 }
1519
1520 /// Set the name for a room.
1521 pub fn set_room_name(&mut self, room_id: &RoomId, name: &str) {
1522 self.rooms.get_or_default(room_id.to_owned()).name = name.to_string().into();
1523 }
1524
1525 /// Insert a new E2EE verification.
1526 pub fn insert_sas(&mut self, sas: SasVerification) {
1527 let key = format!("{}/{}", sas.other_user_id(), sas.other_device().device_id());
1528
1529 self.verifications.insert(key, sas);
1530 }
1531}
1532
1533impl ApplicationStore for ChatStore {}
1534
1535/// Identified used to track window content.
1536#[derive(Clone, Debug, Eq, Hash, PartialEq)]
1537pub enum IambId {
1538 /// A Matrix room, with an optional thread to show.
1539 Room(OwnedRoomId, Option<OwnedEventId>),
1540
1541 /// The `:dms` window.
1542 DirectList,
1543
1544 /// The `:members` window for a given Matrix room.
1545 MemberList(OwnedRoomId),
1546
1547 /// The `:rooms` window.
1548 RoomList,
1549
1550 /// The `:spaces` window.
1551 SpaceList,
1552
1553 /// The `:verify` window.
1554 VerifyList,
1555
1556 /// The `:welcome` window.
1557 Welcome,
1558
1559 /// The `:chats` window.
1560 ChatList,
1561
1562 /// The `:unreads` window.
1563 UnreadList,
1564}
1565
1566impl Display for IambId {
1567 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1568 match self {
1569 IambId::Room(room_id, None) => {
1570 write!(f, "iamb://room/{room_id}")
1571 },
1572 IambId::Room(room_id, Some(thread)) => {
1573 write!(f, "iamb://room/{room_id}/threads/{thread}")
1574 },
1575 IambId::MemberList(room_id) => {
1576 write!(f, "iamb://members/{room_id}")
1577 },
1578 IambId::DirectList => f.write_str("iamb://dms"),
1579 IambId::RoomList => f.write_str("iamb://rooms"),
1580 IambId::SpaceList => f.write_str("iamb://spaces"),
1581 IambId::VerifyList => f.write_str("iamb://verify"),
1582 IambId::Welcome => f.write_str("iamb://welcome"),
1583 IambId::ChatList => f.write_str("iamb://chats"),
1584 IambId::UnreadList => f.write_str("iamb://unreads"),
1585 }
1586 }
1587}
1588
1589impl ApplicationWindowId for IambId {}
1590
1591impl Serialize for IambId {
1592 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1593 where
1594 S: Serializer,
1595 {
1596 serializer.serialize_str(&self.to_string())
1597 }
1598}
1599
1600impl<'de> Deserialize<'de> for IambId {
1601 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1602 where
1603 D: Deserializer<'de>,
1604 {
1605 deserializer.deserialize_str(IambIdVisitor)
1606 }
1607}
1608
1609/// [serde] visitor for deserializing [IambId].
1610struct IambIdVisitor;
1611
1612impl Visitor<'_> for IambIdVisitor {
1613 type Value = IambId;
1614
1615 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1616 formatter.write_str("a valid window URL")
1617 }
1618
1619 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1620 where
1621 E: SerdeError,
1622 {
1623 let Ok(url) = Url::parse(value) else {
1624 return Err(E::custom("Invalid iamb window URL"));
1625 };
1626
1627 if url.scheme() != "iamb" {
1628 return Err(E::custom("Invalid iamb window URL"));
1629 }
1630
1631 match url.domain() {
1632 Some("room") => {
1633 let Some(path) = url.path_segments() else {
1634 return Err(E::custom("Invalid members window URL"));
1635 };
1636
1637 match *path.collect::<Vec<_>>().as_slice() {
1638 [room_id] => {
1639 let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
1640 return Err(E::custom("Invalid room identifier"));
1641 };
1642
1643 Ok(IambId::Room(room_id, None))
1644 },
1645 [room_id, "threads", thread_root] => {
1646 let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
1647 return Err(E::custom("Invalid room identifier"));
1648 };
1649
1650 let Ok(thread_root) = OwnedEventId::try_from(thread_root) else {
1651 return Err(E::custom("Invalid thread root identifier"));
1652 };
1653
1654 Ok(IambId::Room(room_id, Some(thread_root)))
1655 },
1656 _ => return Err(E::custom("Invalid members window URL")),
1657 }
1658 },
1659 Some("members") => {
1660 let Some(path) = url.path_segments() else {
1661 return Err(E::custom("Invalid members window URL"));
1662 };
1663
1664 let &[room_id] = path.collect::<Vec<_>>().as_slice() else {
1665 return Err(E::custom("Invalid members window URL"));
1666 };
1667
1668 let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
1669 return Err(E::custom("Invalid room identifier"));
1670 };
1671
1672 Ok(IambId::MemberList(room_id))
1673 },
1674 Some("dms") => {
1675 if url.path() != "" {
1676 return Err(E::custom("iamb://dms takes no path"));
1677 }
1678
1679 Ok(IambId::DirectList)
1680 },
1681 Some("rooms") => {
1682 if url.path() != "" {
1683 return Err(E::custom("iamb://rooms takes no path"));
1684 }
1685
1686 Ok(IambId::RoomList)
1687 },
1688 Some("spaces") => {
1689 if url.path() != "" {
1690 return Err(E::custom("iamb://spaces takes no path"));
1691 }
1692
1693 Ok(IambId::SpaceList)
1694 },
1695 Some("verify") => {
1696 if url.path() != "" {
1697 return Err(E::custom("iamb://verify takes no path"));
1698 }
1699
1700 Ok(IambId::VerifyList)
1701 },
1702 Some("welcome") => {
1703 if url.path() != "" {
1704 return Err(E::custom("iamb://welcome takes no path"));
1705 }
1706
1707 Ok(IambId::Welcome)
1708 },
1709 Some("chats") => {
1710 if url.path() != "" {
1711 return Err(E::custom("iamb://chats takes no path"));
1712 }
1713
1714 Ok(IambId::ChatList)
1715 },
1716 Some("unreads") => {
1717 if url.path() != "" {
1718 return Err(E::custom("iamb://unreads takes no path"));
1719 }
1720
1721 Ok(IambId::UnreadList)
1722 },
1723 Some(s) => Err(E::custom(format!("{s:?} is not a valid window"))),
1724 None => Err(E::custom("Invalid iamb window URL")),
1725 }
1726 }
1727}
1728
1729/// Which part of the room window's UI is focused.
1730#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1731pub enum RoomFocus {
1732 /// The scrollback for a room window is focused.
1733 Scrollback,
1734
1735 /// The message bar for a room window is focused.
1736 MessageBar,
1737}
1738
1739impl RoomFocus {
1740 /// Whether this is [RoomFocus::Scrollback].
1741 pub fn is_scrollback(&self) -> bool {
1742 matches!(self, RoomFocus::Scrollback)
1743 }
1744
1745 /// Whether this is [RoomFocus::MessageBar].
1746 pub fn is_msgbar(&self) -> bool {
1747 matches!(self, RoomFocus::MessageBar)
1748 }
1749}
1750
1751/// Identifiers used to track where a mark was placed.
1752///
1753/// While this is the "buffer identifier" for the mark,
1754/// not all of these are necessarily actual buffers.
1755#[derive(Clone, Debug, Eq, Hash, PartialEq)]
1756pub enum IambBufferId {
1757 /// The command bar buffer.
1758 Command(CommandType),
1759
1760 /// The message buffer or a specific message in a room.
1761 Room(OwnedRoomId, Option<OwnedEventId>, RoomFocus),
1762
1763 /// The `:dms` window.
1764 DirectList,
1765
1766 /// The `:members` window for a room.
1767 MemberList(OwnedRoomId),
1768
1769 /// The `:rooms` window.
1770 RoomList,
1771
1772 /// The `:spaces` window.
1773 SpaceList,
1774
1775 /// The `:verify` window.
1776 VerifyList,
1777
1778 /// The buffer for the `:rooms` window.
1779 Welcome,
1780
1781 /// The `:chats` window.
1782 ChatList,
1783
1784 /// The `:unreads` window.
1785 UnreadList,
1786}
1787
1788impl IambBufferId {
1789 /// Get the identifier for the window that contains this buffer.
1790 pub fn to_window(&self) -> Option<IambId> {
1791 let id = match self {
1792 IambBufferId::Command(_) => return None,
1793 IambBufferId::Room(room, thread, _) => IambId::Room(room.clone(), thread.clone()),
1794 IambBufferId::DirectList => IambId::DirectList,
1795 IambBufferId::MemberList(room) => IambId::MemberList(room.clone()),
1796 IambBufferId::RoomList => IambId::RoomList,
1797 IambBufferId::SpaceList => IambId::SpaceList,
1798 IambBufferId::VerifyList => IambId::VerifyList,
1799 IambBufferId::Welcome => IambId::Welcome,
1800 IambBufferId::ChatList => IambId::ChatList,
1801 IambBufferId::UnreadList => IambId::UnreadList,
1802 };
1803
1804 Some(id)
1805 }
1806}
1807
1808impl ApplicationContentId for IambBufferId {}
1809
1810impl ApplicationInfo for IambInfo {
1811 type Error = IambError;
1812 type Store = ChatStore;
1813 type Action = IambAction;
1814 type WindowId = IambId;
1815 type ContentId = IambBufferId;
1816
1817 fn complete(
1818 text: &EditRope,
1819 cursor: &mut Cursor,
1820 content: &IambBufferId,
1821 store: &mut ProgramStore,
1822 ) -> Vec<String> {
1823 match content {
1824 IambBufferId::Command(CommandType::Command) => complete_cmdbar(text, cursor, store),
1825 IambBufferId::Command(CommandType::Search) => vec![],
1826 IambBufferId::Room(_, _, RoomFocus::MessageBar) => complete_msgbar(text, cursor, store),
1827 IambBufferId::Room(_, _, RoomFocus::Scrollback) => vec![],
1828
1829 IambBufferId::DirectList => vec![],
1830 IambBufferId::MemberList(_) => vec![],
1831 IambBufferId::RoomList => vec![],
1832 IambBufferId::SpaceList => vec![],
1833 IambBufferId::VerifyList => vec![],
1834 IambBufferId::Welcome => vec![],
1835 IambBufferId::ChatList => vec![],
1836 IambBufferId::UnreadList => vec![],
1837 }
1838 }
1839
1840 fn content_of_command(ct: CommandType) -> IambBufferId {
1841 IambBufferId::Command(ct)
1842 }
1843}
1844
1845/// Tab completion for user IDs.
1846fn complete_users(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
1847 let id = text
1848 .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
1849 .unwrap_or_else(EditRope::empty);
1850 let id = Cow::from(&id);
1851
1852 store
1853 .application
1854 .presences
1855 .complete(id.as_ref())
1856 .into_iter()
1857 .map(|i| i.to_string())
1858 .collect()
1859}
1860
1861/// Tab completion within the message bar.
1862fn complete_msgbar(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
1863 let id = text
1864 .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
1865 .unwrap_or_else(EditRope::empty);
1866 let id = Cow::from(&id);
1867
1868 match id.chars().next() {
1869 // Complete room aliases.
1870 Some('#') => {
1871 return store.application.names.complete(id.as_ref());
1872 },
1873
1874 // Complete room identifiers.
1875 Some('!') => {
1876 return store
1877 .application
1878 .rooms
1879 .complete(id.as_ref())
1880 .into_iter()
1881 .map(|i| i.to_string())
1882 .collect();
1883 },
1884
1885 // Complete Emoji shortcodes.
1886 Some(':') => {
1887 let list = store.application.emojis.complete(&id[1..]);
1888 let iter = list.into_iter().take(200).map(|s| format!(":{}:", s));
1889
1890 return iter.collect();
1891 },
1892
1893 // Complete usernames for @ and empty strings.
1894 Some('@') | None => {
1895 return store
1896 .application
1897 .presences
1898 .complete(id.as_ref())
1899 .into_iter()
1900 .map(|i| i.to_string())
1901 .collect();
1902 },
1903
1904 // Unknown sigil.
1905 Some(_) => return vec![],
1906 }
1907}
1908
1909/// Tab completion for Matrix identifiers (usernames, room aliases, etc.)
1910fn complete_matrix_names(
1911 text: &EditRope,
1912 cursor: &mut Cursor,
1913 store: &ProgramStore,
1914) -> Vec<String> {
1915 let id = text
1916 .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
1917 .unwrap_or_else(EditRope::empty);
1918 let id = Cow::from(&id);
1919
1920 let list = store.application.names.complete(id.as_ref());
1921 if !list.is_empty() {
1922 return list;
1923 }
1924
1925 let list = store.application.presences.complete(id.as_ref());
1926 if !list.is_empty() {
1927 return list.into_iter().map(|i| i.to_string()).collect();
1928 }
1929
1930 store
1931 .application
1932 .rooms
1933 .complete(id.as_ref())
1934 .into_iter()
1935 .map(|i| i.to_string())
1936 .collect()
1937}
1938
1939/// Tab completion for Emoji shortcode names.
1940fn complete_emoji(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
1941 let sc = text.get_prefix_word_mut(cursor, &WordStyle::Little);
1942 let sc = sc.unwrap_or_else(EditRope::empty);
1943 let sc = Cow::from(&sc);
1944
1945 store.application.emojis.complete(sc.as_ref())
1946}
1947
1948/// Tab completion for command names.
1949fn complete_cmdname(
1950 desc: CommandDescription,
1951 text: &EditRope,
1952 cursor: &mut Cursor,
1953 store: &ProgramStore,
1954) -> Vec<String> {
1955 // Complete command name and set cursor position.
1956 let _ = text.get_prefix_word_mut(cursor, &WordStyle::Little);
1957 store.application.cmds.complete_name(desc.command.as_str())
1958}
1959
1960/// Tab completion for command arguments.
1961fn complete_cmdarg(
1962 desc: CommandDescription,
1963 text: &EditRope,
1964 cursor: &mut Cursor,
1965 store: &ProgramStore,
1966) -> Vec<String> {
1967 let cmd = match store.application.cmds.get(desc.command.as_str()) {
1968 Ok(cmd) => cmd,
1969 Err(_) => return vec![],
1970 };
1971
1972 match cmd.name.as_str() {
1973 "cancel" | "dms" | "edit" | "redact" | "reply" => vec![],
1974 "members" | "rooms" | "spaces" | "welcome" => vec![],
1975 "download" | "keys" | "open" | "upload" => complete_path(text, cursor),
1976 "react" | "unreact" => complete_emoji(text, cursor, store),
1977
1978 "invite" => complete_users(text, cursor, store),
1979 "join" | "split" | "vsplit" | "tabedit" => complete_matrix_names(text, cursor, store),
1980 "room" => vec![],
1981 "verify" => vec![],
1982 "vertical" | "horizontal" | "aboveleft" | "belowright" | "tab" => {
1983 complete_cmd(desc.arg.text.as_str(), text, cursor, store)
1984 },
1985 _ => vec![],
1986 }
1987}
1988
1989/// Tab completion for commands.
1990fn complete_cmd(
1991 cmd: &str,
1992 text: &EditRope,
1993 cursor: &mut Cursor,
1994 store: &ProgramStore,
1995) -> Vec<String> {
1996 match CommandDescription::from_str(cmd) {
1997 Ok(desc) => {
1998 if desc.arg.untrimmed.is_empty() {
1999 complete_cmdname(desc, text, cursor, store)
2000 } else {
2001 // Complete command argument.
2002 complete_cmdarg(desc, text, cursor, store)
2003 }
2004 },
2005
2006 // Can't parse command text, so return zero completions.
2007 Err(_) => vec![],
2008 }
2009}
2010
2011/// Tab completion for the command bar.
2012fn complete_cmdbar(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
2013 let eo = text.cursor_to_offset(cursor);
2014 let slice = text.slice(..eo);
2015 let cow = Cow::from(&slice);
2016
2017 complete_cmd(cow.as_ref(), text, cursor, store)
2018}
2019
2020#[cfg(test)]
2021pub mod tests {
2022 use super::*;
2023 use crate::config::user_style_from_color;
2024 use crate::tests::*;
2025 use matrix_sdk::ruma::{
2026 events::{reaction::ReactionEventContent, relation::Annotation, MessageLikeUnsigned},
2027 owned_event_id,
2028 owned_room_id,
2029 owned_user_id,
2030 MilliSecondsSinceUnixEpoch,
2031 };
2032 use pretty_assertions::assert_eq;
2033 use ratatui::style::Color;
2034
2035 #[test]
2036 fn multiple_identical_reactions() {
2037 let mut info = RoomInfo::default();
2038
2039 let content = ReactionEventContent::new(Annotation::new(
2040 owned_event_id!("$my_reaction"),
2041 "🏠".to_owned(),
2042 ));
2043
2044 for i in 0..3 {
2045 let event_id = format!("$house_{}", i);
2046 info.insert_reaction(MessageLikeEvent::Original(
2047 matrix_sdk::ruma::events::OriginalMessageLikeEvent {
2048 content: content.clone(),
2049 event_id: OwnedEventId::from_str(&event_id).unwrap(),
2050 sender: owned_user_id!("@foo:example.org"),
2051 origin_server_ts: MilliSecondsSinceUnixEpoch::now(),
2052 room_id: owned_room_id!("!foo:example.org"),
2053 unsigned: MessageLikeUnsigned::new(),
2054 },
2055 ));
2056 }
2057
2058 let content = ReactionEventContent::new(Annotation::new(
2059 owned_event_id!("$my_reaction"),
2060 "🙂".to_owned(),
2061 ));
2062
2063 for i in 0..2 {
2064 let event_id = format!("$smile_{}", i);
2065 info.insert_reaction(MessageLikeEvent::Original(
2066 matrix_sdk::ruma::events::OriginalMessageLikeEvent {
2067 content: content.clone(),
2068 event_id: OwnedEventId::from_str(&event_id).unwrap(),
2069 sender: owned_user_id!("@foo:example.org"),
2070 origin_server_ts: MilliSecondsSinceUnixEpoch::now(),
2071 room_id: owned_room_id!("!foo:example.org"),
2072 unsigned: MessageLikeUnsigned::new(),
2073 },
2074 ));
2075 }
2076
2077 for i in 2..4 {
2078 let event_id = format!("$smile_{}", i);
2079 info.insert_reaction(MessageLikeEvent::Original(
2080 matrix_sdk::ruma::events::OriginalMessageLikeEvent {
2081 content: content.clone(),
2082 event_id: OwnedEventId::from_str(&event_id).unwrap(),
2083 sender: owned_user_id!("@bar:example.org"),
2084 origin_server_ts: MilliSecondsSinceUnixEpoch::now(),
2085 room_id: owned_room_id!("!foo:example.org"),
2086 unsigned: MessageLikeUnsigned::new(),
2087 },
2088 ));
2089 }
2090
2091 assert_eq!(info.get_reactions(&owned_event_id!("$my_reaction")), vec![
2092 ("🏠", 1),
2093 ("🙂", 2)
2094 ]);
2095 }
2096
2097 #[test]
2098 fn test_typing_spans() {
2099 let mut info = RoomInfo::default();
2100 let settings = mock_settings();
2101
2102 let users0 = vec![];
2103 let users1 = vec![TEST_USER1.clone()];
2104 let users2 = vec![TEST_USER1.clone(), TEST_USER2.clone()];
2105 let users4 = vec![
2106 TEST_USER1.clone(),
2107 TEST_USER2.clone(),
2108 TEST_USER3.clone(),
2109 TEST_USER4.clone(),
2110 ];
2111 let users5 = vec![
2112 TEST_USER1.clone(),
2113 TEST_USER2.clone(),
2114 TEST_USER3.clone(),
2115 TEST_USER4.clone(),
2116 TEST_USER5.clone(),
2117 ];
2118
2119 // Nothing set.
2120 assert_eq!(info.users_typing, None);
2121 assert_eq!(info.get_typing_spans(&settings), Line::from(vec![]));
2122
2123 // Empty typing list.
2124 info.set_typing(users0);
2125 assert!(info.users_typing.is_some());
2126 assert_eq!(info.get_typing_spans(&settings), Line::from(vec![]));
2127
2128 // Single user typing.
2129 info.set_typing(users1);
2130 assert!(info.users_typing.is_some());
2131 assert_eq!(
2132 info.get_typing_spans(&settings),
2133 Line::from(vec![
2134 Span::styled("@user1:example.com", user_style("@user1:example.com")),
2135 Span::from(" is typing...")
2136 ])
2137 );
2138
2139 // Two users typing.
2140 info.set_typing(users2);
2141 assert!(info.users_typing.is_some());
2142 assert_eq!(
2143 info.get_typing_spans(&settings),
2144 Line::from(vec![
2145 Span::styled("@user1:example.com", user_style("@user1:example.com")),
2146 Span::raw(" and "),
2147 Span::styled("@user2:example.com", user_style("@user2:example.com")),
2148 Span::raw(" are typing...")
2149 ])
2150 );
2151
2152 // Four users typing.
2153 info.set_typing(users4);
2154 assert!(info.users_typing.is_some());
2155 assert_eq!(info.get_typing_spans(&settings), Line::from("Several people are typing..."));
2156
2157 // Five users typing.
2158 info.set_typing(users5);
2159 assert!(info.users_typing.is_some());
2160 assert_eq!(info.get_typing_spans(&settings), Line::from("Many people are typing..."));
2161
2162 // Test that USER5 gets rendered using the configured color and name.
2163 info.set_typing(vec![TEST_USER5.clone()]);
2164 assert!(info.users_typing.is_some());
2165 assert_eq!(
2166 info.get_typing_spans(&settings),
2167 Line::from(vec![
2168 Span::styled("USER 5", user_style_from_color(Color::Black)),
2169 Span::from(" is typing...")
2170 ])
2171 );
2172 }
2173
2174 #[test]
2175 fn test_need_load() {
2176 let room_id = TEST_ROOM1_ID.clone();
2177
2178 let mut need_load = RoomNeeds::default();
2179
2180 need_load.insert(room_id.clone(), Need::MESSAGES);
2181 need_load.insert(room_id.clone(), Need::MEMBERS);
2182
2183 assert_eq!(need_load.into_iter().collect::<Vec<(OwnedRoomId, Need)>>(), vec![(
2184 room_id,
2185 Need::MESSAGES | Need::MEMBERS,
2186 )],);
2187 }
2188
2189 #[tokio::test]
2190 async fn test_complete_msgbar() {
2191 let store = mock_store().await;
2192
2193 let text = EditRope::from("going for a walk :walk ");
2194 let mut cursor = Cursor::new(0, 22);
2195 let res = complete_msgbar(&text, &mut cursor, &store);
2196 assert_eq!(res, vec![":walking:", ":walking_man:", ":walking_woman:"]);
2197 assert_eq!(cursor, Cursor::new(0, 17));
2198
2199 let text = EditRope::from("hello @user1 ");
2200 let mut cursor = Cursor::new(0, 12);
2201 let res = complete_msgbar(&text, &mut cursor, &store);
2202 assert_eq!(res, vec!["@user1:example.com"]);
2203 assert_eq!(cursor, Cursor::new(0, 6));
2204
2205 let text = EditRope::from("see #room ");
2206 let mut cursor = Cursor::new(0, 9);
2207 let res = complete_msgbar(&text, &mut cursor, &store);
2208 assert_eq!(res, vec!["#room1:example.com"]);
2209 assert_eq!(cursor, Cursor::new(0, 4));
2210 }
2211
2212 #[tokio::test]
2213 async fn test_complete_cmdbar() {
2214 let store = mock_store().await;
2215 let users = vec![
2216 "@user1:example.com",
2217 "@user2:example.com",
2218 "@user3:example.com",
2219 "@user4:example.com",
2220 "@user5:example.com",
2221 ];
2222
2223 let text = EditRope::from("invite ");
2224 let mut cursor = Cursor::new(0, 7);
2225 let id = text
2226 .get_prefix_word_mut(&mut cursor, &MATRIX_ID_WORD)
2227 .unwrap_or_else(EditRope::empty);
2228 assert_eq!(id.to_string(), "");
2229 assert_eq!(cursor, Cursor::new(0, 7));
2230
2231 let text = EditRope::from("invite ");
2232 let mut cursor = Cursor::new(0, 7);
2233 let res = complete_cmdbar(&text, &mut cursor, &store);
2234 assert_eq!(res, users);
2235
2236 let text = EditRope::from("invite ignored");
2237 let mut cursor = Cursor::new(0, 7);
2238 let res = complete_cmdbar(&text, &mut cursor, &store);
2239 assert_eq!(res, users);
2240
2241 let text = EditRope::from("invite @user1ignored");
2242 let mut cursor = Cursor::new(0, 13);
2243 let res = complete_cmdbar(&text, &mut cursor, &store);
2244 assert_eq!(res, vec!["@user1:example.com"]);
2245
2246 let text = EditRope::from("abo hor");
2247 let mut cursor = Cursor::new(0, 7);
2248 let res = complete_cmdbar(&text, &mut cursor, &store);
2249 assert_eq!(res, vec!["horizontal"]);
2250
2251 let text = EditRope::from("abo hor inv");
2252 let mut cursor = Cursor::new(0, 11);
2253 let res = complete_cmdbar(&text, &mut cursor, &store);
2254 assert_eq!(res, vec!["invite"]);
2255
2256 let text = EditRope::from("abo hor invite \n");
2257 let mut cursor = Cursor::new(0, 15);
2258 let res = complete_cmdbar(&text, &mut cursor, &store);
2259 assert_eq!(res, users);
2260 }
2261}