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