src/base.rs
2292 lines · 71528 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 /// Collator for locale-aware text sorting.
1491 pub collator: feruca::Collator,
1492}
1493
1494impl ChatStore {
1495 /// Create a new [ChatStore].
1496 pub fn new(worker: Requester, settings: ApplicationSettings) -> Self {
1497 let picker = picker_from_settings(&settings);
1498
1499 ChatStore {
1500 worker,
1501 settings,
1502 picker,
1503 cmds: crate::commands::setup_commands(),
1504 emojis: emoji_map(),
1505
1506 collator: Default::default(),
1507 names: Default::default(),
1508 rooms: Default::default(),
1509 presences: Default::default(),
1510 verifications: Default::default(),
1511 need_load: Default::default(),
1512 sync_info: Default::default(),
1513 draw_curr: None,
1514 ring_bell: false,
1515 focused: true,
1516 }
1517 }
1518
1519 /// Get a joined room.
1520 pub fn get_joined_room(&self, room_id: &RoomId) -> Option<MatrixRoom> {
1521 let room = self.worker.client.get_room(room_id)?;
1522
1523 if room.state() == MatrixRoomState::Joined {
1524 Some(room)
1525 } else {
1526 None
1527 }
1528 }
1529
1530 /// Get the title for a room.
1531 pub fn get_room_title(&self, room_id: &RoomId) -> String {
1532 self.rooms
1533 .get(room_id)
1534 .and_then(|i| i.name.as_ref())
1535 .map(String::from)
1536 .unwrap_or_else(|| "Untitled Matrix Room".to_string())
1537 }
1538
1539 /// Get the [RoomInfo] for a given room identifier.
1540 pub fn get_room_info(&mut self, room_id: OwnedRoomId) -> &mut RoomInfo {
1541 self.rooms.get_or_default(room_id)
1542 }
1543
1544 /// Set the name for a room.
1545 pub fn set_room_name(&mut self, room_id: &RoomId, name: &str) {
1546 self.rooms.get_or_default(room_id.to_owned()).name = name.to_string().into();
1547 }
1548
1549 /// Insert a new E2EE verification.
1550 pub fn insert_sas(&mut self, sas: SasVerification) {
1551 let key = format!("{}/{}", sas.other_user_id(), sas.other_device().device_id());
1552
1553 self.verifications.insert(key, sas);
1554 }
1555}
1556
1557impl ApplicationStore for ChatStore {}
1558
1559/// Identified used to track window content.
1560#[derive(Clone, Debug, Eq, Hash, PartialEq)]
1561pub enum IambId {
1562 /// A Matrix room, with an optional thread to show.
1563 Room(OwnedRoomId, Option<OwnedEventId>),
1564
1565 /// The `:dms` window.
1566 DirectList,
1567
1568 /// The `:members` window for a given Matrix room.
1569 MemberList(OwnedRoomId),
1570
1571 /// The `:rooms` window.
1572 RoomList,
1573
1574 /// The `:spaces` window.
1575 SpaceList,
1576
1577 /// The `:verify` window.
1578 VerifyList,
1579
1580 /// The `:welcome` window.
1581 Welcome,
1582
1583 /// The `:chats` window.
1584 ChatList,
1585
1586 /// The `:unreads` window.
1587 UnreadList,
1588}
1589
1590impl Display for IambId {
1591 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1592 match self {
1593 IambId::Room(room_id, None) => {
1594 write!(f, "iamb://room/{room_id}")
1595 },
1596 IambId::Room(room_id, Some(thread)) => {
1597 write!(f, "iamb://room/{room_id}/threads/{thread}")
1598 },
1599 IambId::MemberList(room_id) => {
1600 write!(f, "iamb://members/{room_id}")
1601 },
1602 IambId::DirectList => f.write_str("iamb://dms"),
1603 IambId::RoomList => f.write_str("iamb://rooms"),
1604 IambId::SpaceList => f.write_str("iamb://spaces"),
1605 IambId::VerifyList => f.write_str("iamb://verify"),
1606 IambId::Welcome => f.write_str("iamb://welcome"),
1607 IambId::ChatList => f.write_str("iamb://chats"),
1608 IambId::UnreadList => f.write_str("iamb://unreads"),
1609 }
1610 }
1611}
1612
1613impl ApplicationWindowId for IambId {}
1614
1615impl Serialize for IambId {
1616 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1617 where
1618 S: Serializer,
1619 {
1620 serializer.serialize_str(&self.to_string())
1621 }
1622}
1623
1624impl<'de> Deserialize<'de> for IambId {
1625 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1626 where
1627 D: Deserializer<'de>,
1628 {
1629 deserializer.deserialize_str(IambIdVisitor)
1630 }
1631}
1632
1633/// [serde] visitor for deserializing [IambId].
1634struct IambIdVisitor;
1635
1636impl Visitor<'_> for IambIdVisitor {
1637 type Value = IambId;
1638
1639 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1640 formatter.write_str("a valid window URL")
1641 }
1642
1643 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1644 where
1645 E: SerdeError,
1646 {
1647 let Ok(url) = Url::parse(value) else {
1648 return Err(E::custom("Invalid iamb window URL"));
1649 };
1650
1651 if url.scheme() != "iamb" {
1652 return Err(E::custom("Invalid iamb window URL"));
1653 }
1654
1655 match url.domain() {
1656 Some("room") => {
1657 let Some(path) = url.path_segments() else {
1658 return Err(E::custom("Invalid members window URL"));
1659 };
1660
1661 match *path.collect::<Vec<_>>().as_slice() {
1662 [room_id] => {
1663 let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
1664 return Err(E::custom("Invalid room identifier"));
1665 };
1666
1667 Ok(IambId::Room(room_id, None))
1668 },
1669 [room_id, "threads", thread_root] => {
1670 let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
1671 return Err(E::custom("Invalid room identifier"));
1672 };
1673
1674 let Ok(thread_root) = OwnedEventId::try_from(thread_root) else {
1675 return Err(E::custom("Invalid thread root identifier"));
1676 };
1677
1678 Ok(IambId::Room(room_id, Some(thread_root)))
1679 },
1680 _ => return Err(E::custom("Invalid members window URL")),
1681 }
1682 },
1683 Some("members") => {
1684 let Some(path) = url.path_segments() else {
1685 return Err(E::custom("Invalid members window URL"));
1686 };
1687
1688 let &[room_id] = path.collect::<Vec<_>>().as_slice() else {
1689 return Err(E::custom("Invalid members window URL"));
1690 };
1691
1692 let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
1693 return Err(E::custom("Invalid room identifier"));
1694 };
1695
1696 Ok(IambId::MemberList(room_id))
1697 },
1698 Some("dms") => {
1699 if url.path() != "" {
1700 return Err(E::custom("iamb://dms takes no path"));
1701 }
1702
1703 Ok(IambId::DirectList)
1704 },
1705 Some("rooms") => {
1706 if url.path() != "" {
1707 return Err(E::custom("iamb://rooms takes no path"));
1708 }
1709
1710 Ok(IambId::RoomList)
1711 },
1712 Some("spaces") => {
1713 if url.path() != "" {
1714 return Err(E::custom("iamb://spaces takes no path"));
1715 }
1716
1717 Ok(IambId::SpaceList)
1718 },
1719 Some("verify") => {
1720 if url.path() != "" {
1721 return Err(E::custom("iamb://verify takes no path"));
1722 }
1723
1724 Ok(IambId::VerifyList)
1725 },
1726 Some("welcome") => {
1727 if url.path() != "" {
1728 return Err(E::custom("iamb://welcome takes no path"));
1729 }
1730
1731 Ok(IambId::Welcome)
1732 },
1733 Some("chats") => {
1734 if url.path() != "" {
1735 return Err(E::custom("iamb://chats takes no path"));
1736 }
1737
1738 Ok(IambId::ChatList)
1739 },
1740 Some("unreads") => {
1741 if url.path() != "" {
1742 return Err(E::custom("iamb://unreads takes no path"));
1743 }
1744
1745 Ok(IambId::UnreadList)
1746 },
1747 Some(s) => Err(E::custom(format!("{s:?} is not a valid window"))),
1748 None => Err(E::custom("Invalid iamb window URL")),
1749 }
1750 }
1751}
1752
1753/// Which part of the room window's UI is focused.
1754#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1755pub enum RoomFocus {
1756 /// The scrollback for a room window is focused.
1757 Scrollback,
1758
1759 /// The message bar for a room window is focused.
1760 MessageBar,
1761}
1762
1763impl RoomFocus {
1764 /// Whether this is [RoomFocus::Scrollback].
1765 pub fn is_scrollback(&self) -> bool {
1766 matches!(self, RoomFocus::Scrollback)
1767 }
1768
1769 /// Whether this is [RoomFocus::MessageBar].
1770 pub fn is_msgbar(&self) -> bool {
1771 matches!(self, RoomFocus::MessageBar)
1772 }
1773
1774 pub fn toggle(&mut self) {
1775 *self = match self {
1776 RoomFocus::MessageBar => RoomFocus::Scrollback,
1777 RoomFocus::Scrollback => RoomFocus::MessageBar,
1778 };
1779 }
1780}
1781
1782/// Identifiers used to track where a mark was placed.
1783///
1784/// While this is the "buffer identifier" for the mark,
1785/// not all of these are necessarily actual buffers.
1786#[derive(Clone, Debug, Eq, Hash, PartialEq)]
1787pub enum IambBufferId {
1788 /// The command bar buffer.
1789 Command(CommandType),
1790
1791 /// The message buffer or a specific message in a room.
1792 Room(OwnedRoomId, Option<OwnedEventId>, RoomFocus),
1793
1794 /// The `:dms` window.
1795 DirectList,
1796
1797 /// The `:members` window for a room.
1798 MemberList(OwnedRoomId),
1799
1800 /// The `:rooms` window.
1801 RoomList,
1802
1803 /// The `:spaces` window.
1804 SpaceList,
1805
1806 /// The `:verify` window.
1807 VerifyList,
1808
1809 /// The buffer for the `:rooms` window.
1810 Welcome,
1811
1812 /// The `:chats` window.
1813 ChatList,
1814
1815 /// The `:unreads` window.
1816 UnreadList,
1817}
1818
1819impl IambBufferId {
1820 /// Get the identifier for the window that contains this buffer.
1821 pub fn to_window(&self) -> Option<IambId> {
1822 let id = match self {
1823 IambBufferId::Command(_) => return None,
1824 IambBufferId::Room(room, thread, _) => IambId::Room(room.clone(), thread.clone()),
1825 IambBufferId::DirectList => IambId::DirectList,
1826 IambBufferId::MemberList(room) => IambId::MemberList(room.clone()),
1827 IambBufferId::RoomList => IambId::RoomList,
1828 IambBufferId::SpaceList => IambId::SpaceList,
1829 IambBufferId::VerifyList => IambId::VerifyList,
1830 IambBufferId::Welcome => IambId::Welcome,
1831 IambBufferId::ChatList => IambId::ChatList,
1832 IambBufferId::UnreadList => IambId::UnreadList,
1833 };
1834
1835 Some(id)
1836 }
1837}
1838
1839impl ApplicationContentId for IambBufferId {}
1840
1841impl ApplicationInfo for IambInfo {
1842 type Error = IambError;
1843 type Store = ChatStore;
1844 type Action = IambAction;
1845 type WindowId = IambId;
1846 type ContentId = IambBufferId;
1847
1848 fn complete(
1849 text: &EditRope,
1850 cursor: &mut Cursor,
1851 content: &IambBufferId,
1852 store: &mut ProgramStore,
1853 ) -> Vec<String> {
1854 match content {
1855 IambBufferId::Command(CommandType::Command) => complete_cmdbar(text, cursor, store),
1856 IambBufferId::Command(CommandType::Search) => vec![],
1857 IambBufferId::Room(_, _, RoomFocus::MessageBar) => complete_msgbar(text, cursor, store),
1858 IambBufferId::Room(_, _, RoomFocus::Scrollback) => vec![],
1859
1860 IambBufferId::DirectList => vec![],
1861 IambBufferId::MemberList(_) => vec![],
1862 IambBufferId::RoomList => vec![],
1863 IambBufferId::SpaceList => vec![],
1864 IambBufferId::VerifyList => vec![],
1865 IambBufferId::Welcome => vec![],
1866 IambBufferId::ChatList => vec![],
1867 IambBufferId::UnreadList => vec![],
1868 }
1869 }
1870
1871 fn content_of_command(ct: CommandType) -> IambBufferId {
1872 IambBufferId::Command(ct)
1873 }
1874}
1875
1876/// Tab completion for user IDs.
1877fn complete_users(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
1878 let id = text
1879 .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
1880 .unwrap_or_else(EditRope::empty);
1881 let id = Cow::from(&id);
1882
1883 store
1884 .application
1885 .presences
1886 .complete(id.as_ref())
1887 .into_iter()
1888 .map(|i| i.to_string())
1889 .collect()
1890}
1891
1892/// Tab completion within the message bar.
1893fn complete_msgbar(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
1894 let id = text
1895 .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
1896 .unwrap_or_else(EditRope::empty);
1897 let id = Cow::from(&id);
1898
1899 match id.chars().next() {
1900 // Complete room aliases.
1901 Some('#') => {
1902 return store.application.names.complete(id.as_ref());
1903 },
1904
1905 // Complete room identifiers.
1906 Some('!') => {
1907 return store
1908 .application
1909 .rooms
1910 .complete(id.as_ref())
1911 .into_iter()
1912 .map(|i| i.to_string())
1913 .collect();
1914 },
1915
1916 // Complete Emoji shortcodes.
1917 Some(':') => {
1918 let list = store.application.emojis.complete(&id[1..]);
1919 let iter = list.into_iter().take(200).map(|s| format!(":{}:", s));
1920
1921 return iter.collect();
1922 },
1923
1924 // Complete usernames for @ and empty strings.
1925 Some('@') | None => {
1926 return store
1927 .application
1928 .presences
1929 .complete(id.as_ref())
1930 .into_iter()
1931 .map(|i| i.to_string())
1932 .collect();
1933 },
1934
1935 // Unknown sigil.
1936 Some(_) => return vec![],
1937 }
1938}
1939
1940/// Tab completion for Matrix identifiers (usernames, room aliases, etc.)
1941fn complete_matrix_names(
1942 text: &EditRope,
1943 cursor: &mut Cursor,
1944 store: &ProgramStore,
1945) -> Vec<String> {
1946 let id = text
1947 .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
1948 .unwrap_or_else(EditRope::empty);
1949 let id = Cow::from(&id);
1950
1951 let list = store.application.names.complete(id.as_ref());
1952 if !list.is_empty() {
1953 return list;
1954 }
1955
1956 let list = store.application.presences.complete(id.as_ref());
1957 if !list.is_empty() {
1958 return list.into_iter().map(|i| i.to_string()).collect();
1959 }
1960
1961 store
1962 .application
1963 .rooms
1964 .complete(id.as_ref())
1965 .into_iter()
1966 .map(|i| i.to_string())
1967 .collect()
1968}
1969
1970/// Tab completion for Emoji shortcode names.
1971fn complete_emoji(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
1972 let sc = text.get_prefix_word_mut(cursor, &WordStyle::Little);
1973 let sc = sc.unwrap_or_else(EditRope::empty);
1974 let sc = Cow::from(&sc);
1975
1976 store.application.emojis.complete(sc.as_ref())
1977}
1978
1979/// Tab completion for command names.
1980fn complete_cmdname(
1981 desc: CommandDescription,
1982 text: &EditRope,
1983 cursor: &mut Cursor,
1984 store: &ProgramStore,
1985) -> Vec<String> {
1986 // Complete command name and set cursor position.
1987 let _ = text.get_prefix_word_mut(cursor, &WordStyle::Little);
1988 store.application.cmds.complete_name(desc.command.as_str())
1989}
1990
1991/// Tab completion for command arguments.
1992fn complete_cmdarg(
1993 desc: CommandDescription,
1994 text: &EditRope,
1995 cursor: &mut Cursor,
1996 store: &ProgramStore,
1997) -> Vec<String> {
1998 let cmd = match store.application.cmds.get(desc.command.as_str()) {
1999 Ok(cmd) => cmd,
2000 Err(_) => return vec![],
2001 };
2002
2003 match cmd.name.as_str() {
2004 "cancel" | "dms" | "edit" | "redact" | "reply" => vec![],
2005 "members" | "rooms" | "spaces" | "welcome" => vec![],
2006 "download" | "keys" | "open" | "upload" => complete_path(text, cursor),
2007 "react" | "unreact" => complete_emoji(text, cursor, store),
2008
2009 "invite" => complete_users(text, cursor, store),
2010 "join" | "split" | "vsplit" | "tabedit" => complete_matrix_names(text, cursor, store),
2011 "room" => vec![],
2012 "verify" => vec![],
2013 "vertical" | "horizontal" | "aboveleft" | "belowright" | "tab" => {
2014 complete_cmd(desc.arg.text.as_str(), text, cursor, store)
2015 },
2016 _ => vec![],
2017 }
2018}
2019
2020/// Tab completion for commands.
2021fn complete_cmd(
2022 cmd: &str,
2023 text: &EditRope,
2024 cursor: &mut Cursor,
2025 store: &ProgramStore,
2026) -> Vec<String> {
2027 match CommandDescription::from_str(cmd) {
2028 Ok(desc) => {
2029 if desc.arg.untrimmed.is_empty() {
2030 complete_cmdname(desc, text, cursor, store)
2031 } else {
2032 // Complete command argument.
2033 complete_cmdarg(desc, text, cursor, store)
2034 }
2035 },
2036
2037 // Can't parse command text, so return zero completions.
2038 Err(_) => vec![],
2039 }
2040}
2041
2042/// Tab completion for the command bar.
2043fn complete_cmdbar(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
2044 let eo = text.cursor_to_offset(cursor);
2045 let slice = text.slice(..eo);
2046 let cow = Cow::from(&slice);
2047
2048 complete_cmd(cow.as_ref(), text, cursor, store)
2049}
2050
2051#[cfg(test)]
2052pub mod tests {
2053 use super::*;
2054 use crate::config::user_style_from_color;
2055 use crate::tests::*;
2056 use matrix_sdk::ruma::{
2057 events::{reaction::ReactionEventContent, relation::Annotation, MessageLikeUnsigned},
2058 owned_event_id,
2059 owned_room_id,
2060 owned_user_id,
2061 MilliSecondsSinceUnixEpoch,
2062 };
2063 use pretty_assertions::assert_eq;
2064 use ratatui::style::Color;
2065
2066 #[test]
2067 fn multiple_identical_reactions() {
2068 let mut info = RoomInfo::default();
2069
2070 let content = ReactionEventContent::new(Annotation::new(
2071 owned_event_id!("$my_reaction"),
2072 "🏠".to_owned(),
2073 ));
2074
2075 for i in 0..3 {
2076 let event_id = format!("$house_{}", i);
2077 info.insert_reaction(MessageLikeEvent::Original(
2078 matrix_sdk::ruma::events::OriginalMessageLikeEvent {
2079 content: content.clone(),
2080 event_id: OwnedEventId::from_str(&event_id).unwrap(),
2081 sender: owned_user_id!("@foo:example.org"),
2082 origin_server_ts: MilliSecondsSinceUnixEpoch::now(),
2083 room_id: owned_room_id!("!foo:example.org"),
2084 unsigned: MessageLikeUnsigned::new(),
2085 },
2086 ));
2087 }
2088
2089 let content = ReactionEventContent::new(Annotation::new(
2090 owned_event_id!("$my_reaction"),
2091 "🙂".to_owned(),
2092 ));
2093
2094 for i in 0..2 {
2095 let event_id = format!("$smile_{}", i);
2096 info.insert_reaction(MessageLikeEvent::Original(
2097 matrix_sdk::ruma::events::OriginalMessageLikeEvent {
2098 content: content.clone(),
2099 event_id: OwnedEventId::from_str(&event_id).unwrap(),
2100 sender: owned_user_id!("@foo:example.org"),
2101 origin_server_ts: MilliSecondsSinceUnixEpoch::now(),
2102 room_id: owned_room_id!("!foo:example.org"),
2103 unsigned: MessageLikeUnsigned::new(),
2104 },
2105 ));
2106 }
2107
2108 for i in 2..4 {
2109 let event_id = format!("$smile_{}", i);
2110 info.insert_reaction(MessageLikeEvent::Original(
2111 matrix_sdk::ruma::events::OriginalMessageLikeEvent {
2112 content: content.clone(),
2113 event_id: OwnedEventId::from_str(&event_id).unwrap(),
2114 sender: owned_user_id!("@bar:example.org"),
2115 origin_server_ts: MilliSecondsSinceUnixEpoch::now(),
2116 room_id: owned_room_id!("!foo:example.org"),
2117 unsigned: MessageLikeUnsigned::new(),
2118 },
2119 ));
2120 }
2121
2122 assert_eq!(info.get_reactions(&owned_event_id!("$my_reaction")), vec![
2123 ("🏠", 1),
2124 ("🙂", 2)
2125 ]);
2126 }
2127
2128 #[test]
2129 fn test_typing_spans() {
2130 let mut info = RoomInfo::default();
2131 let settings = mock_settings();
2132
2133 let users0 = vec![];
2134 let users1 = vec![TEST_USER1.clone()];
2135 let users2 = vec![TEST_USER1.clone(), TEST_USER2.clone()];
2136 let users4 = vec![
2137 TEST_USER1.clone(),
2138 TEST_USER2.clone(),
2139 TEST_USER3.clone(),
2140 TEST_USER4.clone(),
2141 ];
2142 let users5 = vec![
2143 TEST_USER1.clone(),
2144 TEST_USER2.clone(),
2145 TEST_USER3.clone(),
2146 TEST_USER4.clone(),
2147 TEST_USER5.clone(),
2148 ];
2149
2150 // Nothing set.
2151 assert_eq!(info.users_typing, None);
2152 assert_eq!(info.get_typing_spans(&settings), Line::from(vec![]));
2153
2154 // Empty typing list.
2155 info.set_typing(users0);
2156 assert!(info.users_typing.is_some());
2157 assert_eq!(info.get_typing_spans(&settings), Line::from(vec![]));
2158
2159 // Single user typing.
2160 info.set_typing(users1);
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::from(" is typing...")
2167 ])
2168 );
2169
2170 // Two users typing.
2171 info.set_typing(users2);
2172 assert!(info.users_typing.is_some());
2173 assert_eq!(
2174 info.get_typing_spans(&settings),
2175 Line::from(vec![
2176 Span::styled("@user1:example.com", user_style("@user1:example.com")),
2177 Span::raw(" and "),
2178 Span::styled("@user2:example.com", user_style("@user2:example.com")),
2179 Span::raw(" are typing...")
2180 ])
2181 );
2182
2183 // Four users typing.
2184 info.set_typing(users4);
2185 assert!(info.users_typing.is_some());
2186 assert_eq!(info.get_typing_spans(&settings), Line::from("Several people are typing..."));
2187
2188 // Five users typing.
2189 info.set_typing(users5);
2190 assert!(info.users_typing.is_some());
2191 assert_eq!(info.get_typing_spans(&settings), Line::from("Many people are typing..."));
2192
2193 // Test that USER5 gets rendered using the configured color and name.
2194 info.set_typing(vec![TEST_USER5.clone()]);
2195 assert!(info.users_typing.is_some());
2196 assert_eq!(
2197 info.get_typing_spans(&settings),
2198 Line::from(vec![
2199 Span::styled("USER 5", user_style_from_color(Color::Black)),
2200 Span::from(" is typing...")
2201 ])
2202 );
2203 }
2204
2205 #[test]
2206 fn test_need_load() {
2207 let room_id = TEST_ROOM1_ID.clone();
2208
2209 let mut need_load = RoomNeeds::default();
2210
2211 need_load.insert(room_id.clone(), Need::MESSAGES);
2212 need_load.insert(room_id.clone(), Need::MEMBERS);
2213
2214 assert_eq!(need_load.into_iter().collect::<Vec<(OwnedRoomId, Need)>>(), vec![(
2215 room_id,
2216 Need::MESSAGES | Need::MEMBERS,
2217 )],);
2218 }
2219
2220 #[tokio::test]
2221 async fn test_complete_msgbar() {
2222 let store = mock_store().await;
2223
2224 let text = EditRope::from("going for a walk :walk ");
2225 let mut cursor = Cursor::new(0, 22);
2226 let res = complete_msgbar(&text, &mut cursor, &store);
2227 assert_eq!(res, vec![":walking:", ":walking_man:", ":walking_woman:"]);
2228 assert_eq!(cursor, Cursor::new(0, 17));
2229
2230 let text = EditRope::from("hello @user1 ");
2231 let mut cursor = Cursor::new(0, 12);
2232 let res = complete_msgbar(&text, &mut cursor, &store);
2233 assert_eq!(res, vec!["@user1:example.com"]);
2234 assert_eq!(cursor, Cursor::new(0, 6));
2235
2236 let text = EditRope::from("see #room ");
2237 let mut cursor = Cursor::new(0, 9);
2238 let res = complete_msgbar(&text, &mut cursor, &store);
2239 assert_eq!(res, vec!["#room1:example.com"]);
2240 assert_eq!(cursor, Cursor::new(0, 4));
2241 }
2242
2243 #[tokio::test]
2244 async fn test_complete_cmdbar() {
2245 let store = mock_store().await;
2246 let users = vec![
2247 "@user1:example.com",
2248 "@user2:example.com",
2249 "@user3:example.com",
2250 "@user4:example.com",
2251 "@user5:example.com",
2252 ];
2253
2254 let text = EditRope::from("invite ");
2255 let mut cursor = Cursor::new(0, 7);
2256 let id = text
2257 .get_prefix_word_mut(&mut cursor, &MATRIX_ID_WORD)
2258 .unwrap_or_else(EditRope::empty);
2259 assert_eq!(id.to_string(), "");
2260 assert_eq!(cursor, Cursor::new(0, 7));
2261
2262 let text = EditRope::from("invite ");
2263 let mut cursor = Cursor::new(0, 7);
2264 let res = complete_cmdbar(&text, &mut cursor, &store);
2265 assert_eq!(res, users);
2266
2267 let text = EditRope::from("invite ignored");
2268 let mut cursor = Cursor::new(0, 7);
2269 let res = complete_cmdbar(&text, &mut cursor, &store);
2270 assert_eq!(res, users);
2271
2272 let text = EditRope::from("invite @user1ignored");
2273 let mut cursor = Cursor::new(0, 13);
2274 let res = complete_cmdbar(&text, &mut cursor, &store);
2275 assert_eq!(res, vec!["@user1:example.com"]);
2276
2277 let text = EditRope::from("abo hor");
2278 let mut cursor = Cursor::new(0, 7);
2279 let res = complete_cmdbar(&text, &mut cursor, &store);
2280 assert_eq!(res, vec!["horizontal"]);
2281
2282 let text = EditRope::from("abo hor inv");
2283 let mut cursor = Cursor::new(0, 11);
2284 let res = complete_cmdbar(&text, &mut cursor, &store);
2285 assert_eq!(res, vec!["invite"]);
2286
2287 let text = EditRope::from("abo hor invite \n");
2288 let mut cursor = Cursor::new(0, 15);
2289 let res = complete_cmdbar(&text, &mut cursor, &store);
2290 assert_eq!(res, users);
2291 }
2292}