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