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