src/base.rs
3702 lines · 124452 bytes
1//! # Common types and utilities
2//!
3//! The types defined here get used throughout iamb.
4
5use std::collections::{BTreeSet, HashSet};
6
7use emojis::Emoji;
8use matrix_sdk::Client;
9use matrix_sdk::deserialized_responses::{AmbiguityChange, ThreadSummary, ThreadSummaryStatus};
10use matrix_sdk::ruma::events::poll::start::PollStartEvent;
11use matrix_sdk::ruma::events::poll::unstable_start::{
12 UnstablePollStartEvent,
13 UnstablePollStartEventContent,
14};
15use matrix_sdk::ruma::events::reaction::ReactionEvent;
16use matrix_sdk::ruma::events::relation::Replacement;
17use matrix_sdk::ruma::events::room::encrypted::RoomEncryptedEvent;
18use matrix_sdk::ruma::events::room::member::MembershipState;
19use matrix_sdk::ruma::events::room::message::RelationWithoutReplacement;
20use matrix_sdk::ruma::events::room::message::{
21 RoomMessageEvent,
22 RoomMessageEventContentWithoutRelation,
23};
24use matrix_sdk::ruma::events::room::power_levels::UserPowerLevel;
25use matrix_sdk::ruma::events::room::redaction::{
26 OriginalSyncRoomRedactionEvent,
27 SyncRoomRedactionEvent,
28};
29use matrix_sdk::ruma::events::space::child::SpaceChildEventContent;
30use matrix_sdk::ruma::events::sticker::{StickerEvent, StickerEventContent};
31use matrix_sdk::ruma::events::{MessageLikeEvent, OriginalMessageLikeEvent};
32use matrix_sdk::ruma::presence::PresenceState;
33use matrix_sdk::ruma::room::{AllowRule, Restricted};
34use matrix_sdk::ruma::{OwnedMxcUri, OwnedTransactionId, RoomVersionId};
35use matrix_sdk_base::read_receipts::ReadReceipts;
36use modalkit::editing::application::{
37 ApplicationAction,
38 ApplicationContentId,
39 ApplicationError,
40 ApplicationInfo,
41 ApplicationStore,
42 ApplicationWindowId,
43};
44use modalkit::editing::completion::CompletionMap;
45use modalkit::editing::context::EditContext;
46use modalkit::editing::store::Store;
47use modalkit::env::vim::command::{CommandContext, VimCommand, VimCommandMachine};
48use modalkit::env::vim::keybindings::VimMachine;
49use modalkit::errors::UIResult;
50use modalkit::keybindings::SequenceStatus;
51use percent_encoding::{NON_ALPHANUMERIC, percent_decode, percent_encode};
52use serde::de::Error as SerdeError;
53use serde::de::Visitor;
54use serde::{Deserialize, Deserializer, Serialize, Serializer};
55use tokio::sync::{Mutex as AsyncMutex, Notify};
56use tokio::task::JoinHandle;
57
58use crate::message::poll::{
59 Poll,
60 PollEventLocation,
61 PollRelation,
62 UnloadedPoll,
63 UnloadedUnstablePoll,
64 UnstablePoll,
65 UnstablePollRelation,
66};
67use crate::notifications::NotificationHandle;
68use crate::prelude::*;
69use crate::worker::{subscribe_room_updates, subscribe_thread_updates};
70
71/// The set of characters used in different Matrix IDs.
72pub const MATRIX_ID_WORD: WordStyle = WordStyle::CharSet(is_mxid_char);
73
74/// Find the boundaries for a Matrix username, room alias, or room ID.
75///
76/// Technically "[" and "]" should be here since IPv6 addresses are allowed
77/// in the server name, but in practice that should be uncommon, and people
78/// can just use `gf` and friends in Visual mode instead.
79fn is_mxid_char(c: char) -> bool {
80 return c >= 'a' && c <= 'z' ||
81 c >= 'A' && c <= 'Z' ||
82 c >= '0' && c <= '9' ||
83 ":-./@_#!".contains(c);
84}
85
86const ROOM_FETCH_DEBOUNCE: Duration = Duration::from_secs(2);
87
88/// Empty type used solely to implement [ApplicationInfo].
89#[derive(Clone, Debug, Eq, PartialEq)]
90pub enum IambInfo {}
91
92/// An action taken against an ongoing verification request.
93#[derive(Clone, Debug, Eq, PartialEq)]
94pub enum VerifyAction {
95 /// Accept a verification request.
96 Accept,
97
98 /// Cancel an in-progress verification.
99 Cancel,
100
101 /// Confirm an in-progress verification.
102 Confirm,
103
104 /// Reject an in-progress verification due to mismatched Emoji.
105 Mismatch,
106
107 /// Start an interactive (SAS) emoji verification
108 Emoji,
109}
110
111/// An action taken against an ongoing verification request.
112#[derive(Clone, Debug, Eq, PartialEq)]
113pub enum VerifyUserAction {
114 /// Request a new verification with a user.
115 Request,
116
117 /// Withdraw the verification of a user.
118 Withdraw,
119
120 /// Pin the changed identity of a user.
121 Pin,
122}
123
124/// An action taken against a room's timeline.
125#[derive(Clone, Debug, Eq, PartialEq)]
126pub enum TimelineAction {
127 /// Jump to a loaded message in the scrollback.
128 GotoEvent(OwnedEventId),
129}
130
131/// An action taken against the currently selected message.
132#[derive(Clone, Debug, Eq, PartialEq)]
133pub enum MessageAction {
134 /// Cance the current reply or edit.
135 ///
136 /// The [bool] argument indicates whether to skip confirmation for clearing the message bar.
137 Cancel(bool),
138
139 /// Download an attachment to the given path.
140 ///
141 /// The second argument controls whether to overwrite any already existing file at the
142 /// destination path, or to open the attachment after downloading.
143 Download(Option<PathBuf>, DownloadFlags),
144
145 /// Edit a sent message.
146 Edit,
147
148 /// React to a message with an Emoji.
149 ///
150 /// `:react` will by default try to convert the [String] argument to an Emoji, and error when
151 /// it doesn't recognize it. The second [bool] argument forces it to be interpreted literally
152 /// when it is `true`.
153 React(String, bool),
154
155 /// Pin a message to the room.
156 Pin,
157
158 /// Redact a message, with an optional reason.
159 ///
160 /// The [bool] argument indicates whether to skip confirmation.
161 Redact(Option<String>, bool),
162
163 /// Reply to a message.
164 Reply,
165
166 /// Go to the message the hovered message replied to.
167 Replied,
168
169 /// Unreact to a message.
170 ///
171 /// If no specific Emoji to remove to is specified, then all reactions from the user on the
172 /// message are removed.
173 ///
174 /// Like `:react`, `:unreact` will by default try to convert the [String] argument to an Emoji,
175 /// and error when it doesn't recognize it. The second [bool] argument forces it to be
176 /// interpreted literally when it is `true`.
177 Unreact(Option<String>, bool),
178
179 /// Unpin a message from the room.
180 Unpin,
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 SetChild {
188 /// The room that should be added to the space.
189 child: OwnedRoomOrAliasId,
190 /// The order parameter to use when sorting children in the space.
191 order: Option<String>,
192 /// Whether the room is suggested.
193 suggested: bool,
194 },
195
196 /// Remove the selected room.
197 RemoveChild,
198}
199
200/// The type of room being created.
201#[derive(Clone, Debug, Eq, PartialEq)]
202pub enum CreateRoomType {
203 /// A standard chat room.
204 Room,
205
206 /// A Matrix space.
207 Space,
208}
209
210bitflags::bitflags! {
211 /// Available options for newly created rooms.
212 #[derive(Clone, Debug, Eq, PartialEq)]
213 pub struct CreateRoomFlags: u32 {
214 /// No flags specified.
215 const NONE = 0b00000000;
216
217 /// Make the room public.
218 const PUBLIC = 0b00000001;
219
220 /// Encrypt this room.
221 const ENCRYPTED = 0b00000010;
222 }
223}
224
225bitflags::bitflags! {
226 /// Available options when downloading files.
227 #[derive(Clone, Debug, Eq, PartialEq)]
228 pub struct DownloadFlags: u32 {
229 /// No flags specified.
230 const NONE = 0b00000000;
231
232 /// Overwrite file if it already exists.
233 const FORCE = 0b00000001;
234
235 /// Open file after downloading.
236 const OPEN = 0b00000010;
237 }
238}
239
240/// Fields that rooms and spaces can be sorted by.
241#[derive(Clone, Debug, Eq, PartialEq)]
242pub enum SortFieldRoom {
243 /// Sort rooms by whether they have the Favorite tag.
244 Favorite,
245
246 /// Sort rooms by whether they have the Low Priority tag.
247 LowPriority,
248
249 /// Sort rooms by their room name.
250 Name,
251
252 /// Sort rooms by their canonical room alias.
253 Alias,
254
255 /// Sort rooms by their Matrix room identifier.
256 RoomId,
257
258 /// Sort rooms by the server portion of their canonical room alias.
259 ///
260 /// If the room has no canonical alias, and the room identifier uses the version 1 syntax
261 /// for formatting the MXID, then this will fall back to using the server portion of the
262 /// identifier (aka, the "namespace").
263 Server,
264
265 /// Sort rooms by whether they have unread messages.
266 Unread,
267
268 /// Sort rooms by whether they have unread notifications.
269 Notifications,
270
271 /// Sort rooms by whether they have unread mentions.
272 Mentions,
273
274 /// Sort rooms by whether they were marked as unread.
275 MarkedUnread,
276
277 /// Sort rooms by the timestamps of their most recent messages.
278 Recent,
279
280 /// Sort rooms by whether they are direct messages.
281 Direct,
282
283 /// Sort rooms by whether they are spaces.
284 Space,
285
286 /// Sort rooms by whether they are invites.
287 Invite,
288
289 /// Sort rooms by whether the user has joined them.
290 Joined,
291}
292
293/// Fields that space children can be sorted by.
294#[derive(Clone, Debug, Eq, PartialEq)]
295pub enum SortFieldSpace {
296 Room(SortFieldRoom),
297 SpaceOrder,
298}
299
300/// Fields that users can be sorted by.
301#[derive(Clone, Debug, Eq, PartialEq)]
302pub enum SortFieldUser {
303 PowerLevel,
304 UserId,
305 LocalPart,
306 Server,
307 Knock,
308 Invite,
309}
310
311/// Whether to use the default sort direction for a field, or to reverse it.
312#[derive(Clone, Debug, Eq, PartialEq)]
313pub enum SortOrder {
314 Ascending,
315 Descending,
316}
317
318/// One of the columns to sort on.
319#[derive(Clone, Debug, Eq, PartialEq)]
320pub struct SortColumn<T>(pub T, pub SortOrder);
321
322impl<'de> Deserialize<'de> for SortColumn<SortFieldRoom> {
323 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
324 where
325 D: Deserializer<'de>,
326 {
327 deserializer.deserialize_str(SortRoomVisitor)
328 }
329}
330
331/// [serde] visitor for deserializing [SortColumn] for rooms and spaces.
332struct SortRoomVisitor;
333
334impl Visitor<'_> for SortRoomVisitor {
335 type Value = SortColumn<SortFieldRoom>;
336
337 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
338 formatter.write_str("a valid field for sorting rooms")
339 }
340
341 fn visit_str<E>(self, mut value: &str) -> Result<Self::Value, E>
342 where
343 E: SerdeError,
344 {
345 if value.is_empty() {
346 return Err(E::custom("Invalid sort field"));
347 }
348
349 let order = if value.starts_with('~') {
350 value = &value[1..];
351 SortOrder::Descending
352 } else {
353 SortOrder::Ascending
354 };
355
356 let field = match value {
357 "favorite" => SortFieldRoom::Favorite,
358 "lowpriority" => SortFieldRoom::LowPriority,
359 "recent" => SortFieldRoom::Recent,
360 "unread" => SortFieldRoom::Unread,
361 "notifications" => SortFieldRoom::Notifications,
362 "mentions" => SortFieldRoom::Mentions,
363 "marked_unread" => SortFieldRoom::MarkedUnread,
364 "name" => SortFieldRoom::Name,
365 "alias" => SortFieldRoom::Alias,
366 "dm" => SortFieldRoom::Direct,
367 "id" => SortFieldRoom::RoomId,
368 "server" => SortFieldRoom::Server,
369 "space" => SortFieldRoom::Space,
370 "invite" => SortFieldRoom::Invite,
371 "joined" => SortFieldRoom::Joined,
372 _ => {
373 let msg = format!("Unknown sort field: {value:?}");
374 return Err(E::custom(msg));
375 },
376 };
377
378 Ok(SortColumn(field, order))
379 }
380}
381
382impl<'de> Deserialize<'de> for SortColumn<SortFieldSpace> {
383 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
384 where
385 D: Deserializer<'de>,
386 {
387 deserializer.deserialize_str(SortSpaceVisitor)
388 }
389}
390
391/// [serde] visitor for deserializing [SortColumn] for rooms and spaces.
392struct SortSpaceVisitor;
393
394impl Visitor<'_> for SortSpaceVisitor {
395 type Value = SortColumn<SortFieldSpace>;
396
397 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
398 formatter.write_str("a valid field for sorting space children")
399 }
400
401 fn visit_str<E>(self, mut value: &str) -> Result<Self::Value, E>
402 where
403 E: SerdeError,
404 {
405 if value.is_empty() {
406 return Err(E::custom("Invalid sort field"));
407 }
408
409 let order = if value.starts_with('~') {
410 value = &value[1..];
411 SortOrder::Descending
412 } else {
413 SortOrder::Ascending
414 };
415
416 let field = match value {
417 "spaceorder" => SortFieldSpace::SpaceOrder,
418 _ => {
419 let room_column = SortRoomVisitor.visit_str(value)?;
420 SortFieldSpace::Room(room_column.0)
421 },
422 };
423
424 Ok(SortColumn(field, order))
425 }
426}
427
428impl<'de> Deserialize<'de> for SortColumn<SortFieldUser> {
429 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
430 where
431 D: Deserializer<'de>,
432 {
433 deserializer.deserialize_str(SortUserVisitor)
434 }
435}
436
437/// [serde] visitor for deserializing [SortColumn] for users.
438struct SortUserVisitor;
439
440impl Visitor<'_> for SortUserVisitor {
441 type Value = SortColumn<SortFieldUser>;
442
443 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
444 formatter.write_str("a valid field for sorting rooms")
445 }
446
447 fn visit_str<E>(self, mut value: &str) -> Result<Self::Value, E>
448 where
449 E: SerdeError,
450 {
451 if value.is_empty() {
452 return Err(E::custom("Invalid field for sorting users"));
453 }
454
455 let order = if value.starts_with('~') {
456 value = &value[1..];
457 SortOrder::Descending
458 } else {
459 SortOrder::Ascending
460 };
461
462 let field = match value {
463 "id" => SortFieldUser::UserId,
464 "localpart" => SortFieldUser::LocalPart,
465 "server" => SortFieldUser::Server,
466 "power" => SortFieldUser::PowerLevel,
467 "knock" => SortFieldUser::Knock,
468 "invite" => SortFieldUser::Invite,
469 _ => {
470 let msg = format!("Unknown sort field: {value:?}");
471 return Err(E::custom(msg));
472 },
473 };
474
475 Ok(SortColumn(field, order))
476 }
477}
478
479/// An account property.
480#[derive(Clone, Debug, Eq, PartialEq)]
481pub enum AccountField {
482 /// The account's ignore list.
483 Ignore,
484
485 /// Set whether other user's are allowed to invite the user to rooms.
486 Invites,
487}
488
489/// A room property.
490#[derive(Clone, Debug, Eq, PartialEq)]
491pub enum RoomField {
492 /// The room's join rules, aka who can access this room.
493 Access,
494
495 /// The room's history visibility.
496 History,
497
498 /// The room name.
499 Name,
500
501 /// The room version.
502 Version,
503
504 /// The room id.
505 Id,
506
507 /// A room tag.
508 Tag(TagName),
509
510 /// The room topic.
511 Topic,
512
513 /// Notification level.
514 NotificationMode,
515
516 /// The room's entire list of alternative aliases.
517 Aliases,
518
519 /// A specific alternative alias to the room.
520 Alias(String),
521
522 /// The room's canonical alias.
523 CanonicalAlias,
524
525 /// The users own display name.
526 UserName,
527}
528
529/// An action that operates on a room member.
530#[derive(Clone, Debug, Eq, PartialEq)]
531pub enum MemberUpdateAction {
532 Ban,
533 Kick,
534 Unban,
535}
536
537impl Display for MemberUpdateAction {
538 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
539 match self {
540 MemberUpdateAction::Ban => write!(f, "ban"),
541 MemberUpdateAction::Kick => write!(f, "kick"),
542 MemberUpdateAction::Unban => write!(f, "unban"),
543 }
544 }
545}
546
547/// An internal version of [`JoinRule`]
548#[derive(Clone, Debug, Eq, PartialEq)]
549pub enum IambJoinRule {
550 Public,
551 Restricted(Vec<OwnedRoomOrAliasId>),
552 Knock,
553 KnockRestricted(Vec<OwnedRoomOrAliasId>),
554 Invite,
555}
556
557impl IambJoinRule {
558 pub async fn into_join_rule(self, client: &Client) -> Result<JoinRule, IambError> {
559 async fn resolve_aliases(
560 rooms: Vec<OwnedRoomOrAliasId>,
561 client: &Client,
562 ) -> Result<Restricted, IambError> {
563 let mut allow = vec![];
564 for room in rooms {
565 let alias = match OwnedRoomId::try_from(room) {
566 Ok(room_id) => {
567 allow.push(AllowRule::room_membership(room_id));
568 continue;
569 },
570 Err(alias) => alias,
571 };
572
573 let resp = client.resolve_room_alias(&alias).await?;
574
575 allow.push(AllowRule::room_membership(resp.room_id));
576 }
577
578 Ok(Restricted::new(allow))
579 }
580
581 Ok(match self {
582 Self::Public => JoinRule::Public,
583 Self::Invite => JoinRule::Invite,
584 Self::Knock => JoinRule::Knock,
585 Self::Restricted(rooms) => JoinRule::Restricted(resolve_aliases(rooms, client).await?),
586 Self::KnockRestricted(rooms) => {
587 JoinRule::KnockRestricted(resolve_aliases(rooms, client).await?)
588 },
589 })
590 }
591}
592
593/// An action that operates on a focused room.
594#[derive(Clone, Debug, Eq, PartialEq)]
595pub enum RoomAction {
596 /// Follow the room upgrade information.
597 Follow(Box<CommandContext>, MoveDir1D),
598
599 /// Accept an invitation to join this room.
600 InviteAccept,
601
602 /// Reject an invitation to join this room.
603 InviteReject,
604
605 /// Invite a user to this room.
606 InviteSend(OwnedUserId),
607
608 /// Accept a knock from someone who wants to join this room.
609 KnockAccept(OwnedUserId),
610
611 /// Reject a knock from someone who wants to join this room.
612 KnockReject(OwnedUserId, Option<String>),
613
614 /// Reject a knock from someone who wants to join this room and ban them
615 /// to prevent them from being able to try knocking again.
616 KnockBan(OwnedUserId, Option<String>),
617
618 /// Leave this room.
619 Leave(bool),
620
621 /// Update a user's membership in this room.
622 MemberUpdate(MemberUpdateAction, String, Option<String>, bool),
623
624 /// Open the members window.
625 Members(Box<CommandContext>),
626
627 /// Open the message info window.
628 Message(Box<CommandContext>),
629
630 /// Open the pinned messages window.
631 Pinned(Box<CommandContext>),
632
633 /// Set whether a room is a direct message.
634 SetDirect(bool),
635
636 /// Set the join rules for a room to control who can access it and how.
637 SetAccess(IambJoinRule),
638
639 /// Set a room property.
640 Set(RoomField, String),
641
642 /// Unset a room property.
643 Unset(RoomField),
644
645 /// Upgrade the version of a room.
646 Upgrade(RoomVersionId, Vec<OwnedUserId>, bool),
647
648 /// List the values in a list room property.
649 Show(RoomField),
650
651 /// Mark the room as read/unread.
652 SetUnread(bool),
653}
654
655/// An action that joins a room.
656#[derive(Clone, Debug, Eq, PartialEq)]
657pub enum JoinAction {
658 /// Join the focused room.
659 Join,
660
661 /// Knock on the focused room.
662 Knock,
663}
664
665/// An action that sends a message to a room.
666#[derive(Clone, Debug, Eq, PartialEq)]
667pub enum SendAction {
668 /// Send the text in the message bar.
669 Submit,
670
671 /// Send text provided from an external editor.
672 SubmitFromEditor,
673
674 /// Upload a file.
675 ///
676 /// The second argument indicates whether to use the messagebar as a caption, don't use it or
677 /// ask the user.
678 Upload(PathBuf, Option<bool>),
679
680 /// Upload the image data.
681 ///
682 /// The [`bool`] arguments indicates whether to use the messagebar as a caption.
683 UploadImage(usize, usize, Cow<'static, [u8]>, bool),
684}
685
686/// An action performed against the user's homeserver.
687#[derive(Clone, Debug, Eq, PartialEq)]
688pub enum HomeserverAction {
689 /// Create a new room with an optional localpart.
690 CreateRoom(Option<String>, CreateRoomType, CreateRoomFlags),
691
692 /// Update an account property.
693 AccountSet(AccountField, String),
694
695 /// Show information about an account property.
696 AccountShow(AccountField),
697
698 /// Remove a user from the account's ignore list.
699 AccountUnset(AccountField, Option<String>),
700
701 /// "Knock" on a room, aka "request to join".
702 KnockSend(OwnedRoomOrAliasId, Option<String>),
703
704 /// Logout the current iamb session on the homeserver.
705 Logout(String, bool),
706
707 /// Forget all left rooms
708 Forget,
709
710 /// Set a profile field.
711 ProfileFieldSet(ProfileFieldValue),
712
713 /// Set a profile field.
714 ProfileFieldUnset(ProfileFieldName),
715
716 /// Set a profile field.
717 ProfileFieldShow(ProfileFieldName),
718}
719
720/// An action performed against the user's room keys.
721#[derive(Clone, Debug, Eq, PartialEq)]
722pub enum KeysAction {
723 /// Export room keys to a file, encrypted with a passphrase.
724 Export(String, String),
725 /// Import room keys from a file, encrypted with a passphrase.
726 Import(String, String),
727}
728
729/// An action that the main program loop should execute.
730///
731/// See [the commands module][super::commands] for where these are usually created.
732#[derive(Clone, Debug, Eq, PartialEq)]
733pub enum IambAction {
734 /// Perform an action against the homeserver.
735 Homeserver(HomeserverAction),
736
737 /// Perform an action against a room's timeline.
738 Timeline(TimelineAction),
739
740 /// Perform an action over room keys.
741 Keys(KeysAction),
742
743 /// Perform an action on the currently selected message.
744 Message(MessageAction),
745
746 /// Perform an action on the current space.
747 Space(SpaceAction),
748
749 /// Open a URL.
750 OpenLink(String),
751
752 /// Perform an action on the currently focused room.
753 Room(RoomAction),
754
755 /// Join the focused room preview.
756 Join(JoinAction),
757
758 /// Send a message to the currently focused room.
759 Send(SendAction),
760
761 /// Perform an action for an in-progress verification.
762 Verify(VerifyAction, String),
763
764 /// Perform a verification action against the specified user.
765 VerifyUser(VerifyUserAction, OwnedUserId),
766
767 /// Recover the encryption secrets for this session with the given recovery key.
768 Recover(String),
769
770 /// Toggle the focus within the focused room.
771 ToggleScrollbackFocus,
772
773 /// Change the current theme.
774 ChangeTheme(String),
775
776 /// Clear all unread messages.
777 ClearUnreads,
778}
779
780impl IambAction {
781 /// Indicates whether this action will draw over the screen.
782 pub fn scribbles(&self) -> bool {
783 matches!(self, IambAction::Send(SendAction::SubmitFromEditor))
784 }
785}
786
787impl From<HomeserverAction> for IambAction {
788 fn from(act: HomeserverAction) -> Self {
789 IambAction::Homeserver(act)
790 }
791}
792
793impl From<MessageAction> for IambAction {
794 fn from(act: MessageAction) -> Self {
795 IambAction::Message(act)
796 }
797}
798
799impl From<SpaceAction> for IambAction {
800 fn from(act: SpaceAction) -> Self {
801 IambAction::Space(act)
802 }
803}
804
805impl From<RoomAction> for IambAction {
806 fn from(act: RoomAction) -> Self {
807 IambAction::Room(act)
808 }
809}
810
811impl From<JoinAction> for IambAction {
812 fn from(act: JoinAction) -> Self {
813 IambAction::Join(act)
814 }
815}
816
817impl From<SendAction> for IambAction {
818 fn from(act: SendAction) -> Self {
819 IambAction::Send(act)
820 }
821}
822
823impl From<TimelineAction> for IambAction {
824 fn from(act: TimelineAction) -> Self {
825 IambAction::Timeline(act)
826 }
827}
828
829impl ApplicationAction for IambAction {
830 fn is_edit_sequence(&self, _: &EditContext) -> SequenceStatus {
831 match self {
832 IambAction::ChangeTheme(..) => SequenceStatus::Break,
833 IambAction::ClearUnreads => SequenceStatus::Break,
834 IambAction::Homeserver(..) => SequenceStatus::Break,
835 IambAction::Keys(..) => SequenceStatus::Break,
836 IambAction::Message(..) => SequenceStatus::Break,
837 IambAction::Space(..) => SequenceStatus::Break,
838 IambAction::Room(..) => SequenceStatus::Break,
839 IambAction::OpenLink(..) => SequenceStatus::Break,
840 IambAction::Send(..) => SequenceStatus::Break,
841 IambAction::Timeline(..) => SequenceStatus::Break,
842 IambAction::ToggleScrollbackFocus => SequenceStatus::Break,
843 IambAction::Verify(..) => SequenceStatus::Break,
844 IambAction::VerifyUser(..) => SequenceStatus::Break,
845 IambAction::Recover(..) => SequenceStatus::Break,
846 IambAction::Join(..) => SequenceStatus::Break,
847 }
848 }
849
850 fn is_last_action(&self, _: &EditContext) -> SequenceStatus {
851 match self {
852 IambAction::ChangeTheme(..) => SequenceStatus::Atom,
853 IambAction::ClearUnreads => SequenceStatus::Atom,
854 IambAction::Homeserver(..) => SequenceStatus::Atom,
855 IambAction::Keys(..) => SequenceStatus::Atom,
856 IambAction::Message(..) => SequenceStatus::Atom,
857 IambAction::Space(..) => SequenceStatus::Atom,
858 IambAction::OpenLink(..) => SequenceStatus::Atom,
859 IambAction::Room(..) => SequenceStatus::Atom,
860 IambAction::Send(..) => SequenceStatus::Atom,
861 IambAction::Timeline(..) => SequenceStatus::Atom,
862 IambAction::ToggleScrollbackFocus => SequenceStatus::Atom,
863 IambAction::Verify(..) => SequenceStatus::Atom,
864 IambAction::VerifyUser(..) => SequenceStatus::Atom,
865 IambAction::Recover(..) => SequenceStatus::Atom,
866 IambAction::Join(..) => SequenceStatus::Atom,
867 }
868 }
869
870 fn is_last_selection(&self, _: &EditContext) -> SequenceStatus {
871 match self {
872 IambAction::ChangeTheme(..) => SequenceStatus::Ignore,
873 IambAction::ClearUnreads => SequenceStatus::Ignore,
874 IambAction::Homeserver(..) => SequenceStatus::Ignore,
875 IambAction::Keys(..) => SequenceStatus::Ignore,
876 IambAction::Message(..) => SequenceStatus::Ignore,
877 IambAction::Space(..) => SequenceStatus::Ignore,
878 IambAction::Room(..) => SequenceStatus::Ignore,
879 IambAction::OpenLink(..) => SequenceStatus::Ignore,
880 IambAction::Send(..) => SequenceStatus::Ignore,
881 IambAction::Timeline(..) => SequenceStatus::Ignore,
882 IambAction::ToggleScrollbackFocus => SequenceStatus::Ignore,
883 IambAction::Verify(..) => SequenceStatus::Ignore,
884 IambAction::VerifyUser(..) => SequenceStatus::Ignore,
885 IambAction::Recover(..) => SequenceStatus::Ignore,
886 IambAction::Join(..) => SequenceStatus::Ignore,
887 }
888 }
889
890 fn is_switchable(&self, _: &EditContext) -> bool {
891 match self {
892 IambAction::ChangeTheme(..) => false,
893 IambAction::ClearUnreads => false,
894 IambAction::Homeserver(..) => false,
895 IambAction::Message(..) => false,
896 IambAction::Space(..) => false,
897 IambAction::Room(..) => false,
898 IambAction::Keys(..) => false,
899 IambAction::Send(..) => false,
900 IambAction::OpenLink(..) => false,
901 IambAction::Timeline(..) => false,
902 IambAction::ToggleScrollbackFocus => false,
903 IambAction::Verify(..) => false,
904 IambAction::VerifyUser(..) => false,
905 IambAction::Recover(..) => false,
906 IambAction::Join(..) => false,
907 }
908 }
909}
910
911impl From<RoomAction> for ProgramAction {
912 fn from(act: RoomAction) -> Self {
913 IambAction::from(act).into()
914 }
915}
916
917impl From<SpaceAction> for ProgramAction {
918 fn from(act: SpaceAction) -> Self {
919 IambAction::from(act).into()
920 }
921}
922
923impl From<TimelineAction> for ProgramAction {
924 fn from(act: TimelineAction) -> Self {
925 IambAction::from(act).into()
926 }
927}
928
929impl From<IambAction> for ProgramAction {
930 fn from(act: IambAction) -> Self {
931 Action::Application(act)
932 }
933}
934
935/// Alias for program actions.
936pub type ProgramAction = Action<IambInfo>;
937/// Alias for program context.
938pub type ProgramContext = EditContext;
939/// Alias for program keybindings.
940pub type Keybindings = VimMachine<TerminalKey, IambInfo>;
941/// Alias for a program command.
942pub type ProgramCommand = VimCommand<IambInfo>;
943/// Alias for mapped program commands.
944pub type ProgramCommands = VimCommandMachine<IambInfo>;
945/// Alias for program store.
946pub type ProgramStore = Store<IambInfo>;
947/// Alias for shared program store.
948pub type AsyncProgramStore = Arc<AsyncMutex<ProgramStore>>;
949/// Alias for an action result.
950pub type IambResult<T> = UIResult<T, IambInfo>;
951
952/// Reaction events for some message.
953///
954/// The event identifier used as a key here is the ID for the reaction, and not for the message
955/// it's reacting to.
956pub type MessageReactions = HashMap<OwnedEventId, (String, OwnedUserId, Option<MediaSource>)>;
957
958pub type MessageEdits = BTreeMap<MessageKey, RoomMessageEventContentWithoutRelation>;
959
960/// Errors encountered during application use.
961#[derive(thiserror::Error, Debug)]
962pub enum IambError {
963 /// An invalid history visibility was specified.
964 #[error("Invalid history visibility setting: {0}")]
965 InvalidHistoryVisibility(String),
966
967 /// An invalid notification level was specified.
968 #[error("Invalid notification level: {0}")]
969 InvalidNotificationLevel(String),
970
971 /// An invalid user identifier was specified.
972 #[error("Invalid user identifier: {0:?}")]
973 InvalidUserId(String),
974
975 /// An invalid user identifier was specified.
976 #[error("Invalid room alias: {0}")]
977 InvalidRoomAlias(String),
978
979 /// An invalid verification identifier was specified.
980 #[error("Invalid verification user/device pair: {0}")]
981 InvalidVerificationId(String),
982
983 /// A failure related to the cryptographic store.
984 #[error("Cryptographic storage error: {0}")]
985 CryptoStore(#[from] matrix_sdk::encryption::CryptoStoreError),
986
987 #[error("Failed to import room keys: {0}")]
988 FailedKeyImport(#[from] matrix_sdk::encryption::RoomKeyImportError),
989
990 /// An HTTP error.
991 #[error("HTTP client error: {0}")]
992 Http(#[from] matrix_sdk::HttpError),
993
994 /// A failure from the Matrix client.
995 #[error("Matrix client error: {0}")]
996 Matrix(#[from] matrix_sdk::Error),
997
998 /// A failure when sending a message.
999 #[error("Send queue error: {0}")]
1000 SendQueue(#[from] matrix_sdk::send_queue::RoomSendQueueError),
1001
1002 /// A failure in the sled storage.
1003 #[error("Matrix client storage error: {0}")]
1004 Store(#[from] matrix_sdk::StoreError),
1005
1006 /// A failure during serialization or deserialization.
1007 #[error("Serialization/deserialization error: {0}")]
1008 Serde(#[from] serde_json::Error),
1009
1010 /// A failure due to not having a configured download directory.
1011 #[error("No download directory configured")]
1012 NoDownloadDir,
1013
1014 /// A failure due to not having a message with an attachment selected.
1015 #[error("Selected message does not have any attachments")]
1016 NoAttachment,
1017
1018 /// A failure due to not having a message selected.
1019 #[error("No message currently selected")]
1020 NoSelectedMessage,
1021
1022 /// A failure due to not having a room or space selected.
1023 #[error("Current window is not a room or space")]
1024 NoSelectedRoomOrSpace,
1025
1026 /// A failure due to not having a room or space item selected in a list.
1027 #[error("No room or space currently selected in list")]
1028 NoSelectedRoomOrSpaceItem,
1029
1030 /// A failure due to not having a room selected.
1031 #[error("Current window is not a room")]
1032 NoSelectedRoom,
1033
1034 /// A failure due to not having a space selected.
1035 #[error("Current window is not a space")]
1036 NoSelectedSpace,
1037
1038 /// A failure due to not having sufficient permission to perform an action in a room.
1039 #[error("You do not have the permission to do that")]
1040 InsufficientPermission,
1041
1042 /// A failure due to not having an outstanding room invitation.
1043 #[error("You do not have a current invitation to this room")]
1044 NotInvited,
1045
1046 /// A failure due to not being a joined room member.
1047 #[error("You need to join the room before you can do that")]
1048 NotJoined,
1049
1050 /// An unknown room was specified.
1051 #[error("Unknown room identifier: {0}")]
1052 UnknownRoom(OwnedRoomId),
1053
1054 /// An invalid room alias id was specified.
1055 #[error("Invalid room alias id: {0}")]
1056 InvalidRoomAliasId(#[from] matrix_sdk::ruma::IdParseError),
1057
1058 /// An invalid space child order was specified.
1059 #[error("Invalid space child order: {0}")]
1060 InvalidSpaceChildOrder(matrix_sdk::ruma::IdParseError),
1061
1062 /// A failure occurred during verification.
1063 #[error("Verification request error: {0}")]
1064 VerificationRequestError(#[from] matrix_sdk::encryption::identities::RequestVerificationError),
1065
1066 /// A failure occurred while recovering the encryption secrets.
1067 #[error("Recovery error: {0}")]
1068 RecoveryError(#[from] matrix_sdk::encryption::recovery::RecoveryError),
1069
1070 #[error("Notification setting error: {0}")]
1071 NotificationSettingError(#[from] matrix_sdk::NotificationSettingsError),
1072
1073 /// A failure related to images.
1074 #[error("Image error: {0}")]
1075 Image(#[from] image::ImageError),
1076
1077 /// A failure to access the system's clipboard.
1078 #[error("Could not use system clipboard data")]
1079 Clipboard,
1080
1081 /// An failure during disk/network/ipc/etc. I/O.
1082 #[error("Input/Output error: {0}")]
1083 IOError(#[from] std::io::Error),
1084
1085 /// A failure while trying to show an image preview.
1086 #[error("Preview error: {0}")]
1087 Preview(String),
1088
1089 /// A generic error that doesn't need a specific error type.
1090 #[error("{0}")]
1091 Custom(String),
1092}
1093
1094impl From<IambError> for UIError<IambInfo> {
1095 fn from(err: IambError) -> Self {
1096 UIError::Application(err)
1097 }
1098}
1099
1100impl From<matrix_sdk::event_cache::EventCacheError> for IambError {
1101 fn from(value: matrix_sdk::event_cache::EventCacheError) -> Self {
1102 Self::from(matrix_sdk::Error::from(value))
1103 }
1104}
1105
1106impl From<matrix_sdk::authentication::oauth::OAuthError> for IambError {
1107 fn from(value: matrix_sdk::authentication::oauth::OAuthError) -> Self {
1108 Self::from(matrix_sdk::Error::from(value))
1109 }
1110}
1111
1112impl ApplicationError for IambError {}
1113
1114/// Indicates where an [EventId] lives in the [ChatStore].
1115#[derive(Clone)]
1116pub enum EventLocation {
1117 /// The [EventId] belongs to a message like event.
1118 ///
1119 /// If the first argument is [None], then it's part of the main scrollback. When [Some],
1120 /// it specifies which thread it's in reply to.
1121 Message(Option<OwnedEventId>, MessageKey),
1122
1123 /// The [EventId] belongs to a reaction to the given event.
1124 Reaction(OwnedEventId),
1125
1126 /// The [EventId] belongs to an edit for the given event and has key [MessageKey].
1127 Edit(OwnedEventId, MessageKey),
1128
1129 /// The [EventId] belongs to an aggregation for the given poll.
1130 Poll(OwnedEventId, PollEventLocation),
1131}
1132
1133impl EventLocation {
1134 fn to_message_key(&self) -> Option<&MessageKey> {
1135 match self {
1136 EventLocation::Message(_, key) => Some(key),
1137 _ => None,
1138 }
1139 }
1140 fn to_thread_root(&self) -> Option<&EventId> {
1141 match self {
1142 EventLocation::Message(root, _) => root.as_deref(),
1143 _ => None,
1144 }
1145 }
1146}
1147
1148/// Indicates where a local echo lives in the [`ChatStore`].
1149#[derive(Debug, Clone)]
1150pub enum EchoLocation {
1151 /// The [`OwnedTransactionId`] belongs to a message.
1152 ///
1153 /// If the first argument is [`None`], then it's part of the main scrollback. When [`Some`], it
1154 /// specifies which thread it's in reply to.
1155 Message(Option<OwnedEventId>, MessageKey),
1156
1157 /// The local echo has been replaced by an event with this event id.
1158 Replaced(OwnedEventId),
1159}
1160
1161#[derive(Clone, Debug, Default, Eq, PartialEq)]
1162pub struct UnreadInfo {
1163 pub(crate) unread_mark: bool,
1164 pub(crate) unread_messages: u64,
1165 pub(crate) unread_notifications: u64,
1166 pub(crate) unread_mentions: u64,
1167 pub(crate) latest: Option<MessageTimeStamp>,
1168}
1169
1170impl UnreadInfo {
1171 pub fn is_unread(&self) -> bool {
1172 self.unread_mark || self.unread_notifications > 0 || self.unread_mentions > 0
1173 }
1174
1175 pub fn has_mention(&self) -> bool {
1176 self.unread_mentions > 0
1177 }
1178
1179 pub fn has_notification(&self) -> bool {
1180 self.unread_notifications > 0
1181 }
1182
1183 pub fn latest(&self) -> Option<&MessageTimeStamp> {
1184 self.latest.as_ref()
1185 }
1186}
1187
1188impl std::ops::AddAssign<Self> for UnreadInfo {
1189 fn add_assign(&mut self, rhs: Self) {
1190 self.unread_mark |= rhs.unread_mark;
1191 self.unread_messages += rhs.unread_messages;
1192 self.unread_notifications += rhs.unread_notifications;
1193 self.unread_mentions += rhs.unread_mentions;
1194 self.latest = self.latest.max(rhs.latest);
1195 }
1196}
1197
1198/// Information about a user within a specific room.
1199#[derive(Clone, Debug)]
1200pub struct MemberSummary {
1201 /// The member's user identifier.
1202 pub user_id: OwnedUserId,
1203
1204 /// The member's display name in this room, if they have one.
1205 pub display_name: Option<String>,
1206
1207 /// The member's power level in the room.
1208 pub power_level: UserPowerLevel,
1209
1210 /// The member's current room membership (joined/invited/knocked/etc).
1211 pub membership: MembershipState,
1212
1213 /// Whether the name is ambiguous in the room.
1214 pub name_ambiguous: bool,
1215}
1216
1217impl MemberSummary {
1218 /// The display name to show for this member, falling back to their localpart.
1219 pub fn name(&self) -> &str {
1220 self.display_name.as_deref().unwrap_or_else(|| self.user_id.localpart())
1221 }
1222
1223 /// Get the member's current state.
1224 pub fn membership(&self) -> &MembershipState {
1225 &self.membership
1226 }
1227
1228 /// Get the member's power level in the room.
1229 pub fn power_level(&self) -> UserPowerLevel {
1230 self.power_level
1231 }
1232
1233 /// Get the user identifier.
1234 pub fn user_id(&self) -> &UserId {
1235 self.user_id.as_ref()
1236 }
1237
1238 /// Whether this member has joined the room.
1239 pub fn is_join(&self) -> bool {
1240 self.membership == MembershipState::Join
1241 }
1242
1243 /// Whether this member has been invited to the room.
1244 pub fn is_invite(&self) -> bool {
1245 self.membership == MembershipState::Invite
1246 }
1247
1248 /// Whether this member has knocked on the room.
1249 pub fn is_knock(&self) -> bool {
1250 self.membership == MembershipState::Knock
1251 }
1252
1253 /// Whether this member should be counted as active in the room.
1254 ///
1255 /// We show active room members in `:members`, use them for display name disambiguation,
1256 /// and so on.
1257 pub fn is_active(&self) -> bool {
1258 self.is_join() || self.is_invite() || self.is_knock()
1259 }
1260}
1261
1262#[derive(Default)]
1263struct UserDisplayName {
1264 name: Option<String>,
1265 is_ambiguous: bool,
1266}
1267
1268/// Track the display names for users and render any needed disambiguation for
1269/// those with overlapping names.
1270#[derive(Default)]
1271pub struct DisplayNameStore {
1272 by_ids: HashMap<OwnedUserId, UserDisplayName>,
1273}
1274
1275impl DisplayNameStore {
1276 pub(crate) fn apply_ambiguity_change(&mut self, change: AmbiguityChange) {
1277 self.by_ids.entry(change.member_id).or_default().is_ambiguous = change.member_ambiguous;
1278
1279 if let Some(user_id) = change.ambiguated_member {
1280 self.by_ids.entry(user_id).or_default().is_ambiguous = true;
1281 }
1282 if let Some(user_id) = change.disambiguated_member {
1283 self.by_ids.entry(user_id).or_default().is_ambiguous = false;
1284 }
1285 }
1286
1287 /// Track a new user ID to displayname mapping, or unset any existing ones.
1288 pub fn set(
1289 &mut self,
1290 user_id: OwnedUserId,
1291 name: Option<String>,
1292 name_ambiguous: Option<bool>,
1293 ) {
1294 let user = self.by_ids.entry(user_id).or_default();
1295 user.name = name;
1296
1297 if let Some(ambiguous) = name_ambiguous {
1298 user.is_ambiguous = ambiguous;
1299 }
1300 }
1301
1302 pub fn get<'a>(&'a self, user_id: &UserId) -> Option<Cow<'a, str>> {
1303 let user = self.by_ids.get(user_id)?;
1304 let displayname = user.name.as_ref()?;
1305
1306 if user.is_ambiguous {
1307 Some(Cow::Owned(format!("{displayname} ({user_id})")))
1308 } else {
1309 Some(Cow::Borrowed(displayname.as_str()))
1310 }
1311 }
1312
1313 pub fn complete_mention(&self, prefix: &str) -> Vec<String> {
1314 // spec says to mention with display name in anchor text
1315 let mut users = BTreeSet::new();
1316
1317 let name_prefix = prefix.strip_prefix('@').unwrap_or(prefix);
1318 for (user_id, user) in self.by_ids.iter() {
1319 if user_id.as_str().starts_with(prefix) {
1320 let name = user.name.as_deref().unwrap_or(user_id.as_str());
1321 users.insert(format!("[{}][{}]", name, user_id));
1322 }
1323
1324 if let Some(name) = &user.name &&
1325 name.starts_with(name_prefix)
1326 {
1327 users.insert(format!("[{}][{}]", name, user_id));
1328 }
1329 }
1330
1331 users.into_iter().collect()
1332 }
1333}
1334
1335bitflags::bitflags! {
1336 /// Additional information about a room.
1337 #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
1338 pub struct RoomInfoFlags: u32 {
1339 /// No flags specified.
1340 const NONE = 0b00000000;
1341
1342 /// All notifications for this room have been muted.
1343 const MUTED = 0b00000001;
1344
1345 /// Non-mention/keyword notifications for this room have been muted.
1346 const CALMED = 0b00000010;
1347 }
1348}
1349
1350pub struct Thread {
1351 messages: Messages,
1352
1353 root: Option<Message>,
1354 pub(crate) summary: Option<ThreadSummary>,
1355
1356 pub(crate) unreads: ReadReceipts,
1357 update_handle: Option<JoinHandle<()>>,
1358
1359 /// A map of read markers to display on different events.
1360 event_receipts: HashMap<OwnedEventId, HashSet<OwnedUserId>>,
1361 /// A map of the most recent read marker for each user.
1362 ///
1363 /// Every receipt in this map should also have an entry in [`event_receipts`](`Self::event_receipts`),
1364 /// however not every user has an entry. If a user's most recent receipt is
1365 /// older than the oldest loaded event, that user will not be included.
1366 user_receipts: HashMap<OwnedUserId, OwnedEventId>,
1367}
1368
1369impl Thread {
1370 fn new(root: OwnedEventId) -> Self {
1371 Self {
1372 messages: Messages::new(ReceiptThread::Thread(root)),
1373 root: Default::default(),
1374 summary: Default::default(),
1375 update_handle: Default::default(),
1376 unreads: Default::default(),
1377 event_receipts: Default::default(),
1378 user_receipts: Default::default(),
1379 }
1380 }
1381
1382 pub(crate) async fn subscribe_updates(
1383 &mut self,
1384 room: &MatrixRoom,
1385 root: &EventId,
1386 store: &AsyncProgramStore,
1387 ) {
1388 if self.update_handle.as_ref().is_some_and(|handle| !handle.is_finished()) {
1389 return;
1390 }
1391
1392 match subscribe_thread_updates(room.to_owned(), root.to_owned(), Arc::clone(store)).await {
1393 Ok(handle) => self.update_handle = Some(handle),
1394 Err(err) => {
1395 tracing::warn!(room_id = ?room.room_id(), ?root, "unable to subscribe to thread updates: {err}");
1396 },
1397 }
1398 }
1399}
1400
1401impl Deref for Thread {
1402 type Target = Messages;
1403
1404 fn deref(&self) -> &Self::Target {
1405 &self.messages
1406 }
1407}
1408
1409impl DerefMut for Thread {
1410 fn deref_mut(&mut self) -> &mut Self::Target {
1411 &mut self.messages
1412 }
1413}
1414
1415/// Information about room's the user's joined.
1416pub struct RoomInfo {
1417 /// The display name for this room.
1418 pub name: Option<String>,
1419
1420 /// The tags placed on this room.
1421 pub tags: Option<Tags>,
1422
1423 pub flags: RoomInfoFlags,
1424
1425 /// A map of event IDs to where they are stored in this struct.
1426 pub keys: HashMap<OwnedEventId, EventLocation>,
1427 pub echo_keys: HashMap<OwnedTransactionId, EchoLocation>,
1428
1429 /// The messages loaded for this room.
1430 messages: Messages,
1431
1432 /// A map of read markers to display on different events.
1433 pub event_receipts_main: HashMap<OwnedEventId, HashSet<OwnedUserId>>,
1434 /// A map of the most recent read marker for each user.
1435 ///
1436 /// Every receipt in this map should also have an entry in [`event_receipts`](`Self::event_receipts`),
1437 /// however not every user has an entry. If a user's most recent receipt is
1438 /// older than the oldest loaded event, that user will not be included.
1439 pub user_receipts_main: HashMap<OwnedUserId, OwnedEventId>,
1440 /// Untreaded mirror of [`event_receipts_main`](Self::event_receipts_main)
1441 pub event_receipts_unthreaded: HashMap<OwnedEventId, HashSet<OwnedUserId>>,
1442 /// Untreaded mirror of [`event_receipts_main`](Self::user_receipts_main)
1443 pub user_receipts_unthreaded: HashMap<OwnedUserId, OwnedEventId>,
1444
1445 /// A map of message identifiers to a map of reaction events.
1446 pub reactions: HashMap<OwnedEventId, MessageReactions>,
1447 /// A map of message identifiers to a list of edit events for message that are not yet cached.
1448 pub unloaded_edits: HashMap<OwnedEventId, MessageEdits>,
1449 /// A map of message identifiers to the aggregated data for a poll that hasn't been loaded.
1450 pub unloaded_polls: HashMap<OwnedEventId, UnloadedPoll>,
1451 pub unloaded_unstable_polls: HashMap<OwnedEventId, UnloadedUnstablePoll>,
1452
1453 /// A map of message identifiers to thread replies.
1454 threads: HashMap<OwnedEventId, Thread>,
1455
1456 /// Whether the scrollback for this room is currently being fetched.
1457 pub fetching: bool,
1458
1459 /// Whether all messages are loaded.
1460 pub reached_timeline_start: bool,
1461
1462 /// The time that we last fetched scrollback for this room.
1463 pub fetch_last: Option<Instant>,
1464
1465 /// Handle for the task receiving event cache updates.
1466 update_handle: Option<JoinHandle<()>>,
1467
1468 /// Users currently typing in this room, and when we received notification of them doing so.
1469 pub users_typing: Option<(Instant, Vec<OwnedUserId>)>,
1470
1471 /// The display names for users in this room.
1472 pub display_names: DisplayNameStore,
1473
1474 /// Cached information about the members in this room.
1475 ///
1476 /// Note that this includes members who have left or been banned, so you may need to
1477 /// filter out values when iterating over it, depending on the use case.
1478 pub memberships: HashMap<OwnedUserId, MemberSummary>,
1479
1480 /// List of all users with problematic identity state.
1481 ///
1482 /// This only tracks [`PinViolation`](`IdentityState::PinViolation`) and
1483 /// [`VerificationViolation`](`IdentityState::VerificationViolation`). The normal states don't
1484 /// need to be tracked.
1485 pub identity_violations: BTreeMap<OwnedUserId, IdentityState>,
1486
1487 /// The last time the room was rendered, used to detect if it is currently open.
1488 pub draw_last: Option<Instant>,
1489
1490 /// The room's pinned events, mirrored from the SDK's room state for rendering.
1491 pub pinned_events: Vec<OwnedEventId>,
1492
1493 /// Pinned events fetched for the `:pinned` window that aren't in the loaded scrollback.
1494 pub pinned_previews: HashMap<OwnedEventId, Message>,
1495
1496 /// How many times fetching each pinned event for the `:pinned` window has failed.
1497 pub pinned_failures: HashMap<OwnedEventId, u8>,
1498}
1499
1500impl Default for RoomInfo {
1501 fn default() -> Self {
1502 Self {
1503 messages: Messages::new(ReceiptThread::Main),
1504
1505 name: Default::default(),
1506 tags: Default::default(),
1507 keys: Default::default(),
1508 flags: Default::default(),
1509 echo_keys: Default::default(),
1510 event_receipts_main: Default::default(),
1511 user_receipts_main: Default::default(),
1512 event_receipts_unthreaded: Default::default(),
1513 user_receipts_unthreaded: Default::default(),
1514 reactions: Default::default(),
1515 threads: Default::default(),
1516 fetching: Default::default(),
1517 reached_timeline_start: false,
1518 fetch_last: Default::default(),
1519 update_handle: Default::default(),
1520 users_typing: Default::default(),
1521 display_names: Default::default(),
1522 memberships: Default::default(),
1523 identity_violations: Default::default(),
1524 draw_last: Default::default(),
1525 pinned_events: Default::default(),
1526 pinned_previews: Default::default(),
1527 pinned_failures: Default::default(),
1528 unloaded_edits: Default::default(),
1529 unloaded_polls: Default::default(),
1530 unloaded_unstable_polls: Default::default(),
1531 }
1532 }
1533}
1534
1535impl RoomInfo {
1536 pub fn get_messages(&self, thread_root: Option<&EventId>) -> Option<&Messages> {
1537 if let Some(thread_root) = thread_root {
1538 self.threads.get(thread_root).map(Deref::deref)
1539 } else {
1540 Some(&self.messages)
1541 }
1542 }
1543
1544 pub fn get_messages_mut(&mut self, thread_root: Option<OwnedEventId>) -> &mut Messages {
1545 if let Some(thread_root) = thread_root {
1546 self.threads
1547 .entry(thread_root.clone())
1548 .or_insert_with(|| Thread::new(thread_root))
1549 } else {
1550 &mut self.messages
1551 }
1552 }
1553
1554 pub(crate) fn get_thread(&self, root: &EventId) -> Option<&Thread> {
1555 self.threads.get(root)
1556 }
1557
1558 pub(crate) fn get_thread_mut(&mut self, root: OwnedEventId) -> &mut Thread {
1559 self.threads.entry(root.clone()).or_insert_with(|| Thread::new(root))
1560 }
1561
1562 pub(crate) fn event_receipts(
1563 &self,
1564 thread: &ReceiptThread,
1565 ) -> Option<&HashMap<OwnedEventId, HashSet<OwnedUserId>>> {
1566 match thread {
1567 ReceiptThread::Thread(root) => Some(&self.get_thread(root)?.event_receipts),
1568 ReceiptThread::Main => Some(&self.event_receipts_main),
1569 ReceiptThread::Unthreaded => Some(&self.event_receipts_unthreaded),
1570 _ => {
1571 tracing::debug!("encountered unknown receipt thread: {thread:?}");
1572 None
1573 },
1574 }
1575 }
1576
1577 pub(crate) fn event_receipts_mut(
1578 &mut self,
1579 thread: &ReceiptThread,
1580 ) -> Option<&mut HashMap<OwnedEventId, HashSet<OwnedUserId>>> {
1581 match thread {
1582 ReceiptThread::Thread(root) => Some(&mut self.threads.get_mut(root)?.event_receipts),
1583 ReceiptThread::Main => Some(&mut self.event_receipts_main),
1584 ReceiptThread::Unthreaded => Some(&mut self.event_receipts_unthreaded),
1585 _ => {
1586 tracing::debug!("encountered unknown receipt thread: {thread:?}");
1587 None
1588 },
1589 }
1590 }
1591
1592 /// # Panics
1593 ///
1594 /// Panics if called with [`ReceiptThread::_Custom`].
1595 pub(crate) fn event_receipts_or_default(
1596 &mut self,
1597 thread: ReceiptThread,
1598 ) -> &mut HashMap<OwnedEventId, HashSet<OwnedUserId>> {
1599 match thread {
1600 ReceiptThread::Thread(root) => &mut self.get_thread_mut(root).event_receipts,
1601 ReceiptThread::Main => &mut self.event_receipts_main,
1602 ReceiptThread::Unthreaded => &mut self.event_receipts_unthreaded,
1603 _ => {
1604 panic!("encountered unknown receipt thread: {thread:?}")
1605 },
1606 }
1607 }
1608
1609 pub(crate) fn user_receipts(
1610 &self,
1611 thread: &ReceiptThread,
1612 ) -> Option<&HashMap<OwnedUserId, OwnedEventId>> {
1613 match thread {
1614 ReceiptThread::Thread(root) => Some(&self.get_thread(root)?.user_receipts),
1615 ReceiptThread::Main => Some(&self.user_receipts_main),
1616 ReceiptThread::Unthreaded => Some(&self.user_receipts_unthreaded),
1617 _ => {
1618 tracing::debug!("encountered unknown receipt thread: {thread:?}");
1619 None
1620 },
1621 }
1622 }
1623
1624 pub(crate) fn user_receipts_mut(
1625 &mut self,
1626 thread: &ReceiptThread,
1627 ) -> Option<&mut HashMap<OwnedUserId, OwnedEventId>> {
1628 match thread {
1629 ReceiptThread::Thread(root) => Some(&mut self.threads.get_mut(root)?.user_receipts),
1630 ReceiptThread::Main => Some(&mut self.user_receipts_main),
1631 ReceiptThread::Unthreaded => Some(&mut self.user_receipts_unthreaded),
1632 _ => {
1633 tracing::debug!("encountered unknown receipt thread: {thread:?}");
1634 None
1635 },
1636 }
1637 }
1638
1639 /// Panics if called with [`ReceiptThread::_Custom`].
1640 pub(crate) fn user_receipts_or_default(
1641 &mut self,
1642 thread: ReceiptThread,
1643 ) -> &mut HashMap<OwnedUserId, OwnedEventId> {
1644 match thread {
1645 ReceiptThread::Thread(root) => &mut self.get_thread_mut(root).user_receipts,
1646 ReceiptThread::Main => &mut self.user_receipts_main,
1647 ReceiptThread::Unthreaded => &mut self.user_receipts_unthreaded,
1648 _ => {
1649 panic!("encountered unknown receipt thread: {thread:?}")
1650 },
1651 }
1652 }
1653
1654 /// Spawn subscriber tasks for all thread updates.
1655 pub(crate) async fn subscribe_updates(&mut self, room: &MatrixRoom, store: &AsyncProgramStore) {
1656 if self.update_handle.as_ref().is_none_or(|hanlde| hanlde.is_finished()) {
1657 match subscribe_room_updates(room.to_owned(), Arc::clone(store)).await {
1658 Ok(handle) => self.update_handle = Some(handle),
1659 Err(err) => {
1660 tracing::warn!(room_id = ?room.room_id(), "unable to subscribe to room updates: {err}");
1661 },
1662 }
1663 }
1664
1665 for (root, thread) in self.threads.iter_mut() {
1666 thread.subscribe_updates(room, root, store).await
1667 }
1668 }
1669
1670 /// Get the event for the last message in a thread (or the thread root if there are no
1671 /// in-thread replies yet).
1672 ///
1673 /// This does not apply edits to the returned event.
1674 ///
1675 /// This returns `None` if the event identifier isn't in the room.
1676 pub fn get_thread_last<'a>(
1677 &'a self,
1678 thread_root: &OwnedEventId,
1679 ) -> Option<&'a OriginalRoomMessageEvent> {
1680 let last = self.threads.get(thread_root).and_then(|t| Some(t.last_key_value()?.1));
1681
1682 let msg = if let Some(last) = last {
1683 &last.event
1684 } else if let EventLocation::Message(_, key) = self.keys.get(thread_root)? {
1685 let msg = self.messages.get(key)?;
1686 &msg.event
1687 } else {
1688 return None;
1689 };
1690
1691 if let MessageEvent::Original(ev, _) = &msg {
1692 Some(ev)
1693 } else {
1694 None
1695 }
1696 }
1697
1698 /// Whether a message is pinned to the room.
1699 pub fn is_pinned(&self, event_id: &EventId) -> bool {
1700 self.pinned_events.iter().any(|id| id == event_id)
1701 }
1702
1703 /// Get a pinned message, from the scrollback if it's loaded or else from the fetched previews.
1704 pub fn get_pinned(&self, event_id: &EventId) -> Option<&Message> {
1705 self.get_event(event_id).or_else(|| self.pinned_previews.get(event_id))
1706 }
1707
1708 /// Whether fetching a pinned event has failed too many times to keep retrying.
1709 pub fn pinned_unavailable(&self, event_id: &EventId) -> bool {
1710 self.pinned_failures
1711 .get(event_id)
1712 .is_some_and(|failures| *failures >= PINNED_FETCH_ATTEMPTS)
1713 }
1714
1715 /// Record the result of fetching a pinned event for the `:pinned` window.
1716 pub fn insert_pinned(&mut self, event_id: OwnedEventId, msg: Option<Message>) {
1717 match msg {
1718 Some(msg) => {
1719 self.pinned_failures.remove(&event_id);
1720 self.pinned_previews.insert(event_id, msg);
1721 },
1722 None => {
1723 let failures = self.pinned_failures.entry(event_id).or_default();
1724 *failures = failures.saturating_add(1);
1725 },
1726 }
1727 }
1728
1729 /// Pinned events that still need to be fetched for the `:pinned` window.
1730 pub fn missing_pinned(&self) -> Vec<OwnedEventId> {
1731 self.pinned_events
1732 .iter()
1733 .filter(|id| self.get_pinned(id).is_none() && !self.pinned_unavailable(id))
1734 .cloned()
1735 .collect()
1736 }
1737
1738 /// Get where a loaded message lives, as its thread root and key.
1739 pub fn get_message_location(
1740 &self,
1741 event_id: &EventId,
1742 ) -> Option<(Option<&EventId>, &MessageKey)> {
1743 let loc = self.keys.get(event_id)?;
1744
1745 Some((loc.to_thread_root(), loc.to_message_key()?))
1746 }
1747
1748 pub fn get_receipt_thread(&self, event_id: &EventId) -> Option<ReceiptThread> {
1749 match self.keys.get(event_id)? {
1750 EventLocation::Message(None, _) => Some(ReceiptThread::Main),
1751 EventLocation::Message(Some(root), _) => Some(ReceiptThread::Thread(root.clone())),
1752 _ => None,
1753 }
1754 }
1755
1756 /// Get the reactions and their counts for a message.
1757 pub fn get_reactions(
1758 &self,
1759 event_id: &EventId,
1760 ) -> Vec<(&str, Vec<&UserId>, &Option<MediaSource>)> {
1761 if let Some(reacts) = self.reactions.get(event_id) {
1762 let mut reactions = BTreeMap::new();
1763
1764 for (key, user, source) in reacts.values() {
1765 let react =
1766 reactions.entry(key.as_str()).or_insert_with(|| (BTreeSet::new(), source));
1767 react.0.insert(user.deref());
1768 }
1769
1770 reactions
1771 .into_iter()
1772 .map(|(key, (users, source))| (key, users.into_iter().collect::<Vec<_>>(), source))
1773 .collect::<Vec<_>>()
1774 } else {
1775 vec![]
1776 }
1777 }
1778
1779 pub fn get_reaction_images(&self, event_id: &EventId) -> impl Iterator<Item = &MediaSource> {
1780 self.reactions
1781 .get(event_id)
1782 .map(HashMap::iter)
1783 .unwrap_or_default()
1784 .filter_map(|(_, (_, _, source))| source.as_ref())
1785 }
1786
1787 /// Map an event identifier to its [MessageKey].
1788 pub fn get_message_key(&self, event_id: &EventId) -> Option<&MessageKey> {
1789 self.keys.get(event_id)?.to_message_key()
1790 }
1791
1792 /// Get an event for an identifier.
1793 pub fn get_event(&self, event_id: &EventId) -> Option<&Message> {
1794 let loc = self.keys.get(event_id)?;
1795
1796 let key = loc.to_message_key()?;
1797 let root = loc.to_thread_root();
1798
1799 self.get_messages(root)?.get(key)
1800 }
1801
1802 /// Get an event for an identifier as mutable.
1803 pub fn get_event_mut(&mut self, event_id: &EventId) -> Option<&mut Message> {
1804 let loc = self.keys.get(event_id)?.clone();
1805
1806 let key = loc.to_message_key()?;
1807 let root = loc.to_thread_root();
1808
1809 self.get_messages_mut(root.map(ToOwned::to_owned)).get_mut(key)
1810 }
1811
1812 /// Map an event identifier to its [`MessageKey`] and thread root.
1813 fn get_message_thread_key(
1814 &self,
1815 message_id: &MessageId,
1816 ) -> Option<(Option<&EventId>, &MessageKey)> {
1817 let event_id = match message_id {
1818 MessageId::Local(id) => {
1819 let loc = self.echo_keys.get(id)?;
1820 match loc {
1821 EchoLocation::Message(root, key) => return Some((root.as_deref(), key)),
1822 EchoLocation::Replaced(event_id) => event_id,
1823 }
1824 },
1825 MessageId::Origin(event_id) => event_id,
1826 };
1827
1828 let loc = self.keys.get(event_id)?;
1829
1830 Some((loc.to_thread_root(), loc.to_message_key()?))
1831 }
1832
1833 /// Get an event for an identifier.
1834 pub fn get_message(&self, message_id: &MessageId) -> Option<&Message> {
1835 let (root, key) = self.get_message_thread_key(message_id)?;
1836
1837 self.get_messages(root)?.get(key)
1838 }
1839
1840 /// Get an event for an identifier as mutable.
1841 pub fn get_message_mut(&mut self, message_id: &MessageId) -> Option<&mut Message> {
1842 let (root, key) = self.get_message_thread_key(message_id)?;
1843
1844 let root = root.map(ToOwned::to_owned);
1845 let key = key.to_owned();
1846
1847 self.get_messages_mut(root).get_mut(&key)
1848 }
1849
1850 pub fn redact(&mut self, ev: OriginalSyncRoomRedactionEvent) {
1851 let Some(redacts) = &ev.redacts else {
1852 return;
1853 };
1854
1855 match self.keys.get(redacts) {
1856 None => return,
1857 Some(EventLocation::Edit(msg_event_id, edit_key)) => {
1858 let edit_key = edit_key.clone();
1859 let msg_loc = self.keys.get(msg_event_id).cloned();
1860 if let Some(EventLocation::Message(thread, msg_key)) = msg_loc {
1861 if let Some(msg) = self.get_messages_mut(thread).get_mut(&msg_key) {
1862 msg.remove_edit(&edit_key);
1863 }
1864 } else {
1865 self.unloaded_edits
1866 .get_mut(msg_event_id)
1867 .and_then(|edits| edits.remove(&edit_key));
1868 }
1869
1870 if let Some(msg) = self.messages.get_mut(&edit_key) {
1871 let ev = SyncRoomRedactionEvent::Original(ev);
1872 msg.redact(ev);
1873 }
1874 },
1875 Some(EventLocation::Poll(poll_event_id, loc)) => {
1876 let poll_event_id = poll_event_id.to_owned();
1877 let loc = loc.to_owned();
1878 if let Some(Message { event, .. }) = self.get_event_mut(&poll_event_id) {
1879 match event {
1880 MessageEvent::Poll(poll) => poll.redact(&loc),
1881 MessageEvent::UnstablePoll(poll) => poll.redact(&loc),
1882 _ => (),
1883 }
1884 } else if let Some(poll) = self.unloaded_unstable_polls.get_mut(&poll_event_id) {
1885 poll.redact(&loc);
1886 }
1887 },
1888 Some(EventLocation::Message(None, key)) => {
1889 if let Some(msg) = self.messages.get_mut(key) {
1890 let ev = SyncRoomRedactionEvent::Original(ev);
1891 msg.redact(ev);
1892 }
1893 },
1894 Some(EventLocation::Message(Some(root), key)) => {
1895 if let Some(thread) = self.threads.get_mut(root) &&
1896 let Some(msg) = thread.get_mut(key)
1897 {
1898 let ev = SyncRoomRedactionEvent::Original(ev);
1899 msg.redact(ev);
1900 }
1901 },
1902 Some(EventLocation::Reaction(event_id)) => {
1903 if let Some(reactions) = self.reactions.get_mut(event_id) {
1904 reactions.remove(redacts);
1905 }
1906
1907 self.keys.remove(redacts);
1908 },
1909 }
1910 }
1911
1912 /// Insert a message with a [`EventLocation::Message`].
1913 fn insert_msglike(
1914 &mut self,
1915 event_id: OwnedEventId,
1916 thread_root: Option<OwnedEventId>,
1917 message: Message,
1918 thread_summary: ThreadSummaryStatus,
1919 ) {
1920 let sender = message.sender.clone();
1921
1922 if let ThreadSummaryStatus::Some(thread_summary) = thread_summary {
1923 let thread = self
1924 .threads
1925 .entry(event_id.clone())
1926 .or_insert_with(|| Thread::new(event_id.clone()));
1927
1928 thread.root = Some(message.clone());
1929 thread.summary = Some(thread_summary);
1930 }
1931
1932 let key = MessageKey { ts: message.timestamp, id: event_id.clone().into() };
1933 let loc = EventLocation::Message(thread_root.clone(), key.clone());
1934 self.keys.insert(event_id.clone(), loc);
1935
1936 let thread = self.get_messages_mut(thread_root);
1937 thread.insert_message(key, message);
1938 self.set_implicit_receipt(sender, event_id);
1939 }
1940
1941 /// Insert a message with a [`EventLocation::Message`] and previews.
1942 fn insert_msglike_with_preview(
1943 &mut self,
1944 event_id: OwnedEventId,
1945 thread_root: Option<OwnedEventId>,
1946 message: Message,
1947 thread_summary: ThreadSummaryStatus,
1948 settings: &ApplicationSettings,
1949 previews: &mut PreviewManager,
1950 ) {
1951 if settings.tunables.image_preview.enabled {
1952 for (source, kind) in message.image_previews() {
1953 previews.register_preview(settings, source, kind);
1954 }
1955 }
1956
1957 self.insert_msglike(event_id, thread_root, message, thread_summary);
1958 }
1959
1960 /// Insert a reaction to a message.
1961 fn insert_reaction(&mut self, react: ReactionEvent, source: Option<MediaSource>) {
1962 let MessageLikeEvent::Original(react) = react else {
1963 return;
1964 };
1965 let rel_id = react.content.relates_to.event_id;
1966 let key = react.content.relates_to.key;
1967
1968 let message = self.reactions.entry(rel_id.clone()).or_default();
1969 let event_id = react.event_id;
1970 let user_id = react.sender;
1971
1972 message.insert(event_id.clone(), (key, user_id, source));
1973
1974 let loc = EventLocation::Reaction(rel_id);
1975 self.keys.insert(event_id, loc);
1976 }
1977
1978 /// Insert a sticker
1979 pub fn insert_sticker(
1980 &mut self,
1981 sticker: StickerEvent,
1982 thread_summary: ThreadSummaryStatus,
1983 settings: &ApplicationSettings,
1984 previews: &mut PreviewManager,
1985 ) {
1986 let event_id = sticker.event_id().to_owned();
1987 let thread_root = match &sticker {
1988 MessageLikeEvent::Original(OriginalMessageLikeEvent {
1989 content:
1990 StickerEventContent {
1991 relates_to: Some(Relation::Thread(ThreadRelation { event_id, .. })),
1992 ..
1993 },
1994 ..
1995 }) => Some(event_id.to_owned()),
1996 _ => None,
1997 };
1998
1999 self.insert_msglike_with_preview(
2000 event_id,
2001 thread_root,
2002 sticker.into(),
2003 thread_summary,
2004 settings,
2005 previews,
2006 );
2007 }
2008
2009 /// Insert a reaction to a message.
2010 pub fn insert_reaction_with_preview(
2011 &mut self,
2012 react: ReactionEvent,
2013 settings: &ApplicationSettings,
2014 previews: &mut PreviewManager,
2015 ) {
2016 let MessageLikeEvent::Original(ref orig_react) = react else {
2017 return;
2018 };
2019 let image_uri = OwnedMxcUri::from(orig_react.content.relates_to.key.as_str());
2020 let source = if image_uri.is_valid() && settings.tunables.image_preview.enabled {
2021 Some(MediaSource::Plain(image_uri))
2022 } else {
2023 None
2024 };
2025
2026 if settings.tunables.image_preview.enabled &&
2027 let Some(source) = source.as_ref()
2028 {
2029 previews.register_preview(settings, source, PreviewKind::Emoji);
2030 }
2031
2032 self.insert_reaction(react, source);
2033 }
2034
2035 /// Insert the start of a poll.
2036 pub fn insert_poll_start(
2037 &mut self,
2038 poll: PollStartEvent,
2039 own_user_id: &UserId,
2040 thread_summary: ThreadSummaryStatus,
2041 ) {
2042 let event_id = poll.event_id().to_owned();
2043 let key = MessageKey {
2044 ts: poll.origin_server_ts().into(),
2045 id: event_id.clone().into(),
2046 };
2047
2048 match poll {
2049 MessageLikeEvent::Original(ev) => {
2050 if let Some(Relation::Replacement(Replacement {
2051 event_id: poll_event_id,
2052 new_content,
2053 ..
2054 })) = ev.content.relates_to
2055 {
2056 let loc = EventLocation::Poll(
2057 poll_event_id.to_owned(),
2058 PollEventLocation::Replacement(key.clone()),
2059 );
2060 self.keys.insert(event_id.clone(), loc);
2061
2062 if let Some(msg) = self.get_event_mut(&poll_event_id) {
2063 let MessageEvent::Poll(poll) = &mut msg.event else {
2064 tracing::warn!("encountered poll replacement for non-poll message");
2065 return;
2066 };
2067
2068 poll.replacements.insert(key, new_content);
2069 } else {
2070 self.unloaded_polls
2071 .entry(poll_event_id)
2072 .or_default()
2073 .replacements
2074 .insert(key, new_content);
2075 }
2076 } else {
2077 let thread_root = match &ev.content.relates_to {
2078 Some(Relation::Thread(ThreadRelation { event_id, .. })) => {
2079 Some(event_id.to_owned())
2080 },
2081 _ => None,
2082 };
2083
2084 let unloaded = self.unloaded_polls.remove(&ev.event_id).unwrap_or_default();
2085 let msg = MessageEvent::Poll(
2086 Poll::new(ev.event_id, own_user_id.to_owned(), ev.content, unloaded).into(),
2087 );
2088 let msg = Message::new(msg, ev.sender, ev.origin_server_ts.into());
2089
2090 self.insert_msglike(event_id, thread_root, msg, thread_summary);
2091 }
2092 },
2093 MessageLikeEvent::Redacted(ev) => {
2094 let message: Message = ev.into();
2095
2096 self.insert_msglike(event_id, None, message, thread_summary);
2097 },
2098 }
2099 }
2100
2101 /// Insert the start of a poll.
2102 pub fn insert_unstable_poll_start(
2103 &mut self,
2104 poll: UnstablePollStartEvent,
2105 own_user_id: &UserId,
2106 thread_summary: ThreadSummaryStatus,
2107 ) {
2108 let event_id = poll.event_id().to_owned();
2109 let key = MessageKey {
2110 ts: poll.origin_server_ts().into(),
2111 id: event_id.clone().into(),
2112 };
2113
2114 match poll {
2115 MessageLikeEvent::Original(ev) => {
2116 match ev.content {
2117 UnstablePollStartEventContent::New(content) => {
2118 let thread_root = match &content.relates_to {
2119 Some(RelationWithoutReplacement::Thread(ThreadRelation {
2120 event_id,
2121 ..
2122 })) => Some(event_id.to_owned()),
2123 _ => None,
2124 };
2125
2126 let unloaded =
2127 self.unloaded_unstable_polls.remove(&ev.event_id).unwrap_or_default();
2128 let msg = MessageEvent::UnstablePoll(
2129 UnstablePoll::new(
2130 ev.event_id,
2131 own_user_id.to_owned(),
2132 content,
2133 unloaded,
2134 )
2135 .into(),
2136 );
2137 let msg = Message::new(msg, ev.sender, ev.origin_server_ts.into());
2138
2139 self.insert_msglike(event_id, thread_root, msg, thread_summary);
2140 },
2141 UnstablePollStartEventContent::Replacement(content) => {
2142 let loc = EventLocation::Poll(
2143 content.relates_to.event_id.to_owned(),
2144 PollEventLocation::Replacement(key.clone()),
2145 );
2146 self.keys.insert(event_id.clone(), loc);
2147
2148 if let Some(msg) = self.get_event_mut(&content.relates_to.event_id) {
2149 let MessageEvent::UnstablePoll(poll) = &mut msg.event else {
2150 tracing::warn!("encountered poll replacement for non-poll message");
2151 return;
2152 };
2153
2154 poll.replacements.insert(key, content);
2155 } else {
2156 self.unloaded_unstable_polls
2157 .entry(content.relates_to.event_id.to_owned())
2158 .or_default()
2159 .replacements
2160 .insert(key, content);
2161 }
2162 },
2163 _ => {
2164 tracing::warn!("ignoring unknown unstable poll variant");
2165 },
2166 }
2167 },
2168 MessageLikeEvent::Redacted(ev) => {
2169 let message: Message = ev.into();
2170
2171 self.insert_msglike(event_id, None, message, thread_summary);
2172 },
2173 }
2174 }
2175
2176 /// Insert an event that relates to a poll
2177 pub fn insert_poll_relation(&mut self, relation: PollRelation) {
2178 let event_id = relation.event_id().to_owned();
2179 let poll_event_id = relation.poll_event_id().to_owned();
2180
2181 let loc = if let Some(msg) = self.get_event_mut(&poll_event_id) {
2182 let MessageEvent::Poll(poll) = &mut msg.event else {
2183 tracing::warn!("encountered poll replacement for non-poll message");
2184 return;
2185 };
2186
2187 poll.insert_relation(relation)
2188 } else {
2189 self.unloaded_polls
2190 .entry(poll_event_id.to_owned())
2191 .or_default()
2192 .insert_relation(relation)
2193 };
2194
2195 self.keys.insert(event_id, EventLocation::Poll(poll_event_id, loc));
2196 }
2197
2198 /// Insert an event that relates to a poll
2199 pub fn insert_unstable_poll_relation(&mut self, relation: UnstablePollRelation) {
2200 let event_id = relation.event_id().to_owned();
2201 let poll_event_id = relation.poll_event_id().to_owned();
2202
2203 let loc = if let Some(msg) = self.get_event_mut(&poll_event_id) {
2204 let MessageEvent::UnstablePoll(poll) = &mut msg.event else {
2205 tracing::warn!("encountered poll replacement for non-poll message");
2206 return;
2207 };
2208
2209 poll.insert_relation(relation)
2210 } else {
2211 self.unloaded_unstable_polls
2212 .entry(poll_event_id.to_owned())
2213 .or_default()
2214 .insert_relation(relation)
2215 };
2216
2217 self.keys.insert(event_id, EventLocation::Poll(poll_event_id, loc));
2218 }
2219
2220 /// Insert an edit.
2221 fn insert_edit(
2222 &mut self,
2223 edit_msg: RoomMessageEvent,
2224 replacement: Replacement<RoomMessageEventContentWithoutRelation>,
2225 settings: &ApplicationSettings,
2226 previews: &mut PreviewManager,
2227 ) {
2228 let RoomMessageEvent::Original(edit_msg) = edit_msg else {
2229 return;
2230 };
2231 let edit_key = MessageKey {
2232 ts: edit_msg.origin_server_ts.into(),
2233 id: edit_msg.event_id.clone().into(),
2234 };
2235 let msg_loc = self.keys.get(&replacement.event_id).cloned();
2236
2237 if let Some(EventLocation::Message(thread, key)) = msg_loc {
2238 // The edited message is already loaded in cache
2239 let Some(msg) = self.get_messages_mut(thread).get_mut(&key) else {
2240 return;
2241 };
2242 msg.insert_edit(edit_key.clone(), replacement.new_content);
2243
2244 if settings.tunables.image_preview.enabled {
2245 for (source, kind) in msg.image_previews() {
2246 previews.register_preview(settings, source, kind);
2247 }
2248 }
2249 } else {
2250 // The edited message is not yet loaded
2251 let entry = self.unloaded_edits.entry(replacement.event_id.clone());
2252 entry.or_default().insert(edit_key.clone(), replacement.new_content);
2253 }
2254
2255 let loc = EventLocation::Edit(replacement.event_id.clone(), edit_key.clone());
2256 self.keys.insert(edit_msg.event_id.clone(), loc);
2257 }
2258
2259 pub fn insert_any_state(&mut self, msg: AnySyncStateEvent) {
2260 let event_id = msg.event_id().to_owned();
2261
2262 self.insert_msglike(event_id, None, msg.into(), ThreadSummaryStatus::None);
2263 }
2264
2265 /// Inserts events that couldn't be decrypted into the scrollback.
2266 pub fn insert_encrypted(
2267 &mut self,
2268 msg: RoomEncryptedEvent,
2269 thread_summary: ThreadSummaryStatus,
2270 ) {
2271 let event_id = msg.event_id().to_owned();
2272
2273 let thread_root =
2274 if let Some(EncryptedRelation::Thread(ThreadRelation { event_id, .. })) =
2275 msg.as_original().and_then(|ev| ev.content.relates_to.as_ref())
2276 {
2277 Some(event_id.to_owned())
2278 } else {
2279 None
2280 };
2281
2282 self.insert_msglike(event_id, thread_root, msg.into(), thread_summary);
2283 }
2284
2285 /// Insert a new message event, and prepare for image-preview if it has an image attachment.
2286 pub fn insert_message(
2287 &mut self,
2288 ev: RoomMessageEvent,
2289 thread_summary: ThreadSummaryStatus,
2290 settings: &ApplicationSettings,
2291 previews: &mut PreviewManager,
2292 ) {
2293 let event_id = ev.event_id().to_owned();
2294 let thread_root = match ev.as_original().and_then(|ev| ev.content.relates_to.as_ref()) {
2295 Some(Relation::Replacement(repl)) => {
2296 let repl = repl.to_owned();
2297 self.insert_edit(ev, repl, settings, previews);
2298 return;
2299 },
2300 Some(Relation::Thread(ThreadRelation { event_id, .. })) => Some(event_id.to_owned()),
2301 _ => None,
2302 };
2303 let mut message: Message = ev.into();
2304 if let Some(edits) = self.unloaded_edits.remove(&event_id) {
2305 message.set_edits(edits);
2306 }
2307 self.insert_msglike_with_preview(
2308 event_id,
2309 thread_root,
2310 message,
2311 thread_summary,
2312 settings,
2313 previews,
2314 );
2315 }
2316
2317 /// Indicates whether this room has unread messages.
2318 pub fn unreads(&self, room: &matrix_sdk::Room) -> UnreadInfo {
2319 let last_message = self
2320 .messages
2321 .iter()
2322 .rev()
2323 .find(|(_, msg)| !matches!(&msg.event, MessageEvent::State(..)));
2324
2325 UnreadInfo {
2326 unread_mark: room.is_marked_unread(),
2327 unread_messages: room.num_unread_messages(),
2328 unread_notifications: room.num_unread_notifications(),
2329 unread_mentions: room.num_unread_mentions(),
2330 latest: last_message.map(|(key, _)| key.ts.to_owned()),
2331 }
2332 }
2333
2334 /// Indicates whether we've recently fetched scrollback for this room.
2335 pub fn recently_fetched(&self) -> bool {
2336 self.fetch_last.is_some_and(|i| i.elapsed() < ROOM_FETCH_DEBOUNCE)
2337 }
2338
2339 fn clear_receipt(&mut self, thread: &ReceiptThread, user_id: &OwnedUserId) -> Option<()> {
2340 let old_user_receipts = self.user_receipts_mut(thread);
2341 let old_event_id = old_user_receipts.and_then(|rs| rs.remove(user_id))?;
2342 let old_thread = self.event_receipts_mut(thread)?;
2343 let old_receipts = old_thread.get_mut(&old_event_id)?;
2344 old_receipts.remove(user_id);
2345
2346 if old_receipts.is_empty() {
2347 old_thread.remove(&old_event_id);
2348 }
2349
2350 None
2351 }
2352
2353 pub fn set_receipt(
2354 &mut self,
2355 thread: ReceiptThread,
2356 user_id: OwnedUserId,
2357 event_id: OwnedEventId,
2358 ) {
2359 if let Some(old_event_id) =
2360 self.user_receipts(&thread).and_then(|receipts| receipts.get(&user_id)) &&
2361 let (Some(old_key), Some(new_key)) =
2362 (self.receipt_key(old_event_id), self.receipt_key(&event_id)) &&
2363 new_key <= old_key
2364 {
2365 return;
2366 }
2367
2368 self.clear_receipt(&thread, &user_id);
2369 self.event_receipts_or_default(thread.clone())
2370 .entry(event_id.to_owned())
2371 .or_default()
2372 .insert(user_id.clone());
2373 self.user_receipts_or_default(thread).insert(user_id, event_id);
2374 }
2375
2376 fn receipt_key(&self, event_id: &EventId) -> Option<&MessageKey> {
2377 match self.keys.get(event_id)? {
2378 EventLocation::Message(_, key) => Some(key),
2379 _ => None,
2380 }
2381 }
2382
2383 /// Whenever a user sends a message, we can consider that an effective update to their
2384 /// read receipt, even when their client isn't sending them to the room.
2385 ///
2386 /// While the Matrix specification doesn't explicitly mention "implicit receipts", this
2387 /// is effectively what is described by "Marking notifications as read",
2388 ///
2389 /// > When the user updates their read receipt (either by using the API or by sending an
2390 /// > event), notifications prior to and including that event MUST be marked as read.
2391 ///
2392 /// This method is called every time we insert a new message into the [RoomInfo], so that
2393 /// we show in the timeline that the user has now read up to the point where they sent
2394 /// a message.
2395 fn set_implicit_receipt(&mut self, user_id: OwnedUserId, event_id: OwnedEventId) {
2396 let Some(thread) = self.get_receipt_thread(&event_id) else {
2397 return;
2398 };
2399
2400 let current = self.user_receipts(&thread).and_then(|receipts| receipts.get(&user_id));
2401 let current_key = current.and_then(|event_id| self.receipt_key(event_id));
2402
2403 if current.is_some() && current_key.is_none() {
2404 // Do not set an implicit receipt if we have an explicit receipt that points
2405 // at an event whose information we don't have, since we need it to make sure
2406 // that we don't move the receipt backwards in the timeline.
2407 //
2408 // This event could technically be newer than the one the receipt currently
2409 // points at, but we can't be sure, so just trust what the user's receipt in
2410 // the room says to point at, and we'll update it once they send us a new one.
2411 //
2412 // This technically makes it possible for a user who previously sent room
2413 // receipts and then switched to just private receipts to not have their marker
2414 // moved with recent messages, but solving that would require us to force a
2415 // load of the event that every user's read marker points at.
2416 return;
2417 }
2418
2419 // If the user's client isn't thread-aware then make sure the implicit receipt
2420 // doesn't result in displaying a second read receipt after where their unthreaded
2421 // receipt is currently pointing at:
2422 self.clear_receipt(&ReceiptThread::Unthreaded, &user_id);
2423
2424 self.set_receipt(thread, user_id, event_id);
2425 }
2426
2427 /// This is called whenever the user has viewed the most recent message sent to a room or
2428 /// thread, so that we can update the read receipt on the homeserver.
2429 ///
2430 /// Note that the Matrix specification says:
2431 ///
2432 /// > Clients should send read receipts when there is some certainty that the event in
2433 /// > question has been displayed to the user. Simply receiving an event does not provide
2434 /// > enough certainty that the user has seen the event. The user SHOULD need to take some
2435 /// > action such as viewing the room that the event was sent to or dismissing a notification
2436 /// > in order for the event to count as “read”. Clients SHOULD NOT send read receipts for
2437 /// > events sent by their own user.
2438 pub fn fully_read(
2439 &mut self,
2440 room_id: OwnedRoomId,
2441 thread: ReceiptThread,
2442 worker: &Requester,
2443 settings: &ApplicationSettings,
2444 open_notifications: &mut HashMap<OwnedRoomId, Vec<NotificationHandle>>,
2445 ) {
2446 let user_id = &settings.user_id;
2447
2448 let messages = match &thread {
2449 ReceiptThread::Main => self.get_messages(None),
2450 ReceiptThread::Thread(root) => self.get_messages(Some(root)),
2451 _ => None,
2452 };
2453
2454 let Some(messages) = messages else {
2455 return;
2456 };
2457
2458 let event_id = messages
2459 .iter()
2460 .filter(|(_, msg)| {
2461 // Handle the "do not send read receipts for our own events" part of the
2462 // specification quoted above.
2463 msg.sender != *user_id
2464 })
2465 .flat_map(|(_, msg)| msg.event.event_id())
2466 .next_back()
2467 .map(ToOwned::to_owned);
2468
2469 if let Some((_, msg)) = messages.last_key_value() &&
2470 let Some(event_id) = msg.event.event_id()
2471 {
2472 // Always update the local receipt info for this room so that we aren't reliant
2473 // on the homeserver echoing it back to us to update this and clear the trackbar:
2474 self.set_receipt(thread.clone(), user_id.clone(), event_id.to_owned());
2475 }
2476
2477 if let Some(event_id) = event_id {
2478 // Clear any desktop notifications for the room:
2479 open_notifications.remove(&room_id);
2480
2481 // Update the homeserver with the latest receipt:
2482 worker.send_receipt(room_id, thread, event_id, settings);
2483 }
2484 }
2485
2486 pub fn fully_read_all(
2487 &mut self,
2488 room_id: OwnedRoomId,
2489 worker: &Requester,
2490 settings: &ApplicationSettings,
2491 open_notifications: &mut HashMap<OwnedRoomId, Vec<NotificationHandle>>,
2492 ) {
2493 let threads: Vec<_> = self.threads.keys().map(|root| root.to_owned()).collect();
2494
2495 for thread in threads {
2496 self.fully_read(
2497 room_id.to_owned(),
2498 ReceiptThread::Thread(thread),
2499 worker,
2500 settings,
2501 open_notifications,
2502 );
2503 }
2504
2505 self.fully_read(room_id, ReceiptThread::Main, worker, settings, open_notifications);
2506 }
2507
2508 pub fn read_event_users<'a>(
2509 &'a self,
2510 thread: ReceiptThread,
2511 event_id: &'a EventId,
2512 ) -> impl Iterator<Item = &'a OwnedUserId> + 'a {
2513 self.event_receipts(&thread)
2514 .and_then(|rs| rs.get(event_id))
2515 .map(|read| read.iter())
2516 .unwrap_or_default()
2517 }
2518
2519 fn get_typers(&self) -> &[OwnedUserId] {
2520 if let Some((t, users)) = &self.users_typing {
2521 if t.elapsed() < Duration::from_secs(4) {
2522 return users.as_ref();
2523 } else {
2524 return &[];
2525 }
2526 } else {
2527 return &[];
2528 }
2529 }
2530
2531 fn get_typing_spans<'a>(&'a self, settings: &'a ApplicationSettings) -> Line<'a> {
2532 let typers = self.get_typers();
2533 let n = typers.len();
2534
2535 match n {
2536 0 => Line::from(vec![]),
2537 1 => {
2538 let user =
2539 settings.get_user_span(typers[0].as_ref(), self.display_names.get(&typers[0]));
2540
2541 Line::from(vec![user, Span::from(" is typing...")])
2542 },
2543 2 => {
2544 let user1 =
2545 settings.get_user_span(typers[0].as_ref(), self.display_names.get(&typers[0]));
2546 let user2 =
2547 settings.get_user_span(typers[1].as_ref(), self.display_names.get(&typers[1]));
2548
2549 Line::from(vec![
2550 user1,
2551 Span::raw(" and "),
2552 user2,
2553 Span::from(" are typing..."),
2554 ])
2555 },
2556 n if n < 5 => Line::from("Several people are typing..."),
2557 _ => Line::from("Many people are typing..."),
2558 }
2559 }
2560
2561 /// Update typing information for this room.
2562 pub fn set_typing(&mut self, user_ids: Vec<OwnedUserId>) {
2563 self.users_typing = (Instant::now(), user_ids).into();
2564 }
2565
2566 /// Create a [Rect] that displays what users are typing.
2567 pub fn render_typing(
2568 &mut self,
2569 area: Rect,
2570 buf: &mut Buffer,
2571 settings: &ApplicationSettings,
2572 ) -> Rect {
2573 if area.height <= 2 || area.width <= 20 {
2574 return area;
2575 }
2576
2577 if !settings.tunables.typing_notice_display {
2578 // still keep one line blank, so `render_jump_to_recent` doesn't immediately hide the
2579 // last line in scrollback
2580 return Rect::new(area.x, area.y, area.width, area.height - 1);
2581 }
2582
2583 let top = Rect::new(area.x, area.y, area.width, area.height - 1);
2584 let bar = Rect::new(area.x, area.y + top.height, area.width, 1);
2585
2586 Paragraph::new(self.get_typing_spans(settings))
2587 .alignment(Alignment::Center)
2588 .render(bar, buf);
2589
2590 return top;
2591 }
2592
2593 /// Checks if a given user has reacted with the given emoji on the given event
2594 pub fn user_reactions_contains(
2595 &self,
2596 user_id: &UserId,
2597 event_id: &EventId,
2598 emoji: &str,
2599 ) -> bool {
2600 if let Some(reactions) = self.reactions.get(event_id) {
2601 reactions
2602 .values()
2603 .any(|(annotation, user, _)| annotation == emoji && user == user_id)
2604 } else {
2605 false
2606 }
2607 }
2608}
2609
2610/// Generate a [CompletionMap] for Emoji shortcodes.
2611fn emoji_map() -> CompletionMap<String, &'static Emoji> {
2612 let mut emojis = CompletionMap::default();
2613
2614 for emoji in emojis::iter() {
2615 for shortcode in emoji.shortcodes() {
2616 emojis.insert(shortcode.to_string(), emoji);
2617 }
2618 }
2619
2620 return emojis;
2621}
2622
2623/// Information about spaces the user's joined.
2624#[derive(Default)]
2625pub struct SpaceInfo {
2626 /// The space child events with content and `origin_server_ts`.
2627 pub children: HashMap<OwnedRoomId, (SpaceChildEventContent, MilliSecondsSinceUnixEpoch)>,
2628}
2629
2630/// Information gathered during server syncs about joined rooms.
2631#[derive(Default)]
2632pub struct SyncInfo {
2633 /// Spaces that the user is a member of.
2634 pub spaces: Vec<MatrixRoom>,
2635
2636 /// Rooms that the user is a member of.
2637 pub rooms: Vec<MatrixRoom>,
2638
2639 /// DMs that the user is a member of.
2640 pub dms: Vec<MatrixRoom>,
2641}
2642
2643impl SyncInfo {
2644 pub fn rooms(&self) -> impl Iterator<Item = &RoomId> {
2645 self.rooms.iter().map(|r| r.room_id())
2646 }
2647
2648 pub fn dms(&self) -> impl Iterator<Item = &RoomId> {
2649 self.dms.iter().map(|r| r.room_id())
2650 }
2651
2652 pub fn chats(&self) -> impl Iterator<Item = &RoomId> {
2653 self.rooms().chain(self.dms())
2654 }
2655}
2656
2657static MESSAGE_NEED_TTL: u8 = 30;
2658
2659/// How many failed fetches of a pinned event before the `:pinned` window stops retrying.
2660const PINNED_FETCH_ATTEMPTS: u8 = 10;
2661
2662#[derive(Debug, PartialEq)]
2663/// Load messages until the event is loaded or `ttl` loads are exceeded
2664pub struct MessageNeed {
2665 pub event_id: OwnedEventId,
2666 pub ttl: u8,
2667}
2668
2669#[derive(Default, Debug, PartialEq)]
2670pub struct Need {
2671 pub members: bool,
2672 pub pinned: bool,
2673 pub messages: Option<Vec<MessageNeed>>,
2674}
2675
2676/// Things that need loading for different rooms.
2677#[derive(Default, Debug)]
2678pub struct RoomNeeds {
2679 needs: HashMap<OwnedRoomId, Need>,
2680 previews: HashSet<OwnedRoomOrAliasId>,
2681 notify: Arc<Notify>,
2682}
2683
2684impl RoomNeeds {
2685 /// Mark a room for needing to load members.
2686 pub fn need_members(&mut self, room_id: OwnedRoomId) {
2687 self.needs.entry(room_id).or_default().members = true;
2688 self.notify.notify_waiters();
2689 }
2690
2691 /// Mark a room for needing to fetch its pinned events.
2692 pub fn need_pinned(&mut self, room_id: OwnedRoomId) {
2693 self.needs.entry(room_id).or_default().pinned = true;
2694 self.notify.notify_waiters();
2695 }
2696
2697 /// Mark a room for needing to load messages.
2698 pub fn need_messages(&mut self, room_id: OwnedRoomId) {
2699 self.needs.entry(room_id).or_default().messages.get_or_insert_default();
2700 self.notify.notify_waiters();
2701 }
2702
2703 /// Mark a room for needing to load messages until the given message is loaded or a retry limit
2704 /// is exceeded.
2705 pub fn need_message(&mut self, room_id: OwnedRoomId, event_id: OwnedEventId) {
2706 let messages = &mut self.needs.entry(room_id).or_default().messages.get_or_insert_default();
2707
2708 messages.push(MessageNeed { event_id, ttl: MESSAGE_NEED_TTL });
2709 self.notify.notify_waiters();
2710 }
2711
2712 pub fn need_messages_all(&mut self, room_id: OwnedRoomId, message_needs: Vec<MessageNeed>) {
2713 self.needs
2714 .entry(room_id)
2715 .or_default()
2716 .messages
2717 .get_or_insert_default()
2718 .extend(message_needs);
2719 self.notify.notify_waiters();
2720 }
2721
2722 /// Request the load of a room preview.
2723 pub fn need_preview(&mut self, room: OwnedRoomOrAliasId) {
2724 self.previews.insert(room);
2725 self.notify.notify_waiters();
2726 }
2727
2728 /// Return all requested room previews
2729 pub fn preview_needs(&mut self) -> impl Iterator<Item = OwnedRoomOrAliasId> + use<> {
2730 std::mem::take(&mut self.previews).into_iter()
2731 }
2732
2733 /// Return all requested rooms
2734 pub fn room_needs(&mut self) -> impl Iterator<Item = (OwnedRoomId, Need)> + use<> {
2735 std::mem::take(&mut self.needs).into_iter()
2736 }
2737
2738 pub fn rooms(&self) -> usize {
2739 self.needs.len()
2740 }
2741
2742 /// The returned [`Notify`] instance will be notified with [`Notify::notify_waiters`] for every
2743 /// inserted [`Need`].
2744 pub fn notifier(&self) -> Arc<Notify> {
2745 Arc::clone(&self.notify)
2746 }
2747}
2748
2749/// The main application state.
2750pub struct ChatStore {
2751 /// `:`-commands
2752 pub cmds: ProgramCommands,
2753
2754 /// Handle for communicating w/ the worker thread.
2755 pub worker: Requester,
2756
2757 /// Map of joined rooms.
2758 pub rooms: CompletionMap<OwnedRoomId, RoomInfo>,
2759
2760 /// Map of loaded room previews with their fetch time
2761 pub room_previews:
2762 HashMap<OwnedRoomOrAliasId, (Result<RoomPreview, matrix_sdk::Error>, Instant)>,
2763
2764 /// Cache of encountered `via` parameters in room links.
2765 ///
2766 /// This is stored here because this data is lost in the conversion to [IambId].
2767 pub room_via: HashMap<OwnedRoomOrAliasId, HashSet<OwnedServerName>>,
2768
2769 /// Map of joined spaces.
2770 pub spaces: HashMap<OwnedRoomId, SpaceInfo>,
2771
2772 /// Map of room aliases.
2773 pub aliases: CompletionMap<OwnedRoomAliasId, OwnedRoomId>,
2774
2775 /// Presence information for other users.
2776 pub presences: CompletionMap<OwnedUserId, PresenceState>,
2777
2778 /// In-progress and completed verifications.
2779 /// The map key is the `flow_id`.
2780 pub verifications: CompletionMap<String, VerificationRequest>,
2781
2782 /// Settings for the current profile loaded from config file.
2783 pub settings: ApplicationSettings,
2784
2785 /// Set of rooms that need more messages loaded in their scrollback.
2786 pub need_load: RoomNeeds,
2787
2788 /// [CompletionMap] of Emoji shortcodes.
2789 pub emojis: CompletionMap<String, &'static Emoji>,
2790
2791 /// Information gathered by the background thread.
2792 pub sync_info: SyncInfo,
2793
2794 /// Rendered image previews.
2795 pub previews: PreviewManager,
2796
2797 /// Last draw time, used to match with RoomInfo's draw_last.
2798 pub draw_curr: Option<Instant>,
2799
2800 /// Whether to ring the terminal bell on the next redraw.
2801 pub ring_bell: bool,
2802
2803 /// An error raised while drawing, shown in the message bar on the next redraw.
2804 pub draw_error: Option<String>,
2805
2806 /// Whether the application is currently focused
2807 pub focused: bool,
2808
2809 /// Collator for locale-aware text sorting.
2810 pub collator: feruca::Collator,
2811
2812 /// Notifications that should be dismissed when the user opens the room.
2813 pub open_notifications: HashMap<OwnedRoomId, Vec<NotificationHandle>>,
2814}
2815
2816impl ChatStore {
2817 /// Create a new [ChatStore].
2818 pub fn new(worker: Requester, settings: ApplicationSettings) -> IambResult<Self> {
2819 let previews = PreviewManager::new(&settings);
2820 let cmds = crate::commands::setup_commands(&settings.aliases)?;
2821
2822 let store = ChatStore {
2823 worker,
2824 settings,
2825 previews,
2826 cmds,
2827 emojis: emoji_map(),
2828
2829 collator: Default::default(),
2830 aliases: Default::default(),
2831 rooms: Default::default(),
2832 room_previews: Default::default(),
2833 room_via: Default::default(),
2834 spaces: Default::default(),
2835 presences: Default::default(),
2836 verifications: Default::default(),
2837 need_load: Default::default(),
2838 sync_info: Default::default(),
2839 draw_curr: None,
2840 ring_bell: false,
2841 draw_error: None,
2842 focused: true,
2843 open_notifications: Default::default(),
2844 };
2845
2846 Ok(store)
2847 }
2848
2849 /// Clear the `EventCache` for all rooms.
2850 ///
2851 /// This forces a re-fetch of the most recent messages in joined rooms afterwards,
2852 /// which makes sure that we re-fetch any missing events (such as those sent by
2853 /// recently unignored users that a re-fetch would make appear in the timeline).
2854 pub async fn clear_room_cache(&mut self, client: &Client) -> Result<(), IambError> {
2855 client.event_cache().clear_all_rooms().await?;
2856 for room in client.joined_rooms() {
2857 let room_id = room.room_id().to_owned();
2858 let room = self.rooms.get_or_default(room_id.clone());
2859 room.reached_timeline_start = false;
2860 self.need_load.need_messages(room_id.to_owned());
2861 }
2862 Ok(())
2863 }
2864
2865 /// Get a joined room.
2866 pub fn get_joined_room(&self, room_id: &RoomId) -> Option<MatrixRoom> {
2867 let room = self.worker.client.get_room(room_id)?;
2868
2869 if room.state() == MatrixRoomState::Joined {
2870 Some(room)
2871 } else {
2872 None
2873 }
2874 }
2875
2876 /// Get the alias for a room if it has one (and the client knows it).
2877 pub fn get_joined_room_alias(&self, room_id: &RoomId) -> Option<OwnedRoomAliasId> {
2878 self.worker.client.get_room(room_id).and_then(|r| r.canonical_alias())
2879 }
2880
2881 /// Get the title for a room.
2882 pub fn get_room_title(&self, room_id: &RoomId) -> String {
2883 self.rooms
2884 .get(room_id)
2885 .and_then(|i| i.name.as_ref())
2886 .map(String::from)
2887 .unwrap_or_else(|| "Untitled Matrix Room".to_string())
2888 }
2889
2890 /// Get the [RoomInfo] for a given room identifier.
2891 pub fn get_room_info(&mut self, room_id: OwnedRoomId) -> &mut RoomInfo {
2892 self.rooms.get_or_default(room_id)
2893 }
2894
2895 /// Set the name and tags for a room.
2896 pub fn set_room_info(
2897 &mut self,
2898 room_id: OwnedRoomId,
2899 name: String,
2900 tags: Option<Tags>,
2901 aliases: Vec<OwnedRoomAliasId>,
2902 flags: RoomInfoFlags,
2903 ) {
2904 for alias in aliases {
2905 self.aliases.insert(alias, room_id.clone());
2906 }
2907
2908 let info = self.rooms.get_or_default(room_id);
2909 info.name = name.into();
2910 info.flags = flags;
2911 info.tags = tags;
2912 }
2913}
2914
2915impl ApplicationStore for ChatStore {}
2916
2917#[derive(Clone, Debug, Eq, Hash, PartialEq)]
2918pub enum RoomView {
2919 /// The main timeline is shown.
2920 Main,
2921 /// A thread is shown.
2922 Thread(OwnedEventId),
2923 /// A single message is shown.
2924 Message(MessageId),
2925}
2926
2927impl From<Option<OwnedEventId>> for RoomView {
2928 fn from(thread: Option<OwnedEventId>) -> Self {
2929 match thread {
2930 Some(thread) => Self::Thread(thread),
2931 None => Self::Main,
2932 }
2933 }
2934}
2935
2936impl From<Option<&OwnedEventId>> for RoomView {
2937 fn from(thread: Option<&OwnedEventId>) -> Self {
2938 match thread {
2939 Some(thread) => Self::Thread(thread.to_owned()),
2940 None => Self::Main,
2941 }
2942 }
2943}
2944
2945/// Identified used to track window content.
2946#[derive(Clone, Debug, Eq, Hash, PartialEq)]
2947pub enum IambId {
2948 /// A Matrix room, with an item that is shown.
2949 Room(OwnedRoomOrAliasId, RoomView),
2950
2951 /// The `:dms` window.
2952 DirectList,
2953
2954 /// The `:members` window for a given Matrix room.
2955 MemberList(OwnedRoomId),
2956
2957 /// The `:pinned` window for a given Matrix room.
2958 PinnedList(OwnedRoomId),
2959
2960 /// The `:rooms` window.
2961 RoomList,
2962
2963 /// The `:spaces` window.
2964 SpaceList,
2965
2966 /// The `:spaces toplevel` window.
2967 ToplevelSpaceList,
2968
2969 /// The `:verify` window.
2970 VerifyList,
2971
2972 /// The `:welcome` window.
2973 Welcome,
2974
2975 /// The `:chats` window.
2976 ChatList,
2977
2978 /// The `:unreads` window.
2979 UnreadList,
2980
2981 /// The `:mentions` window.
2982 MentionsList,
2983
2984 /// The `:invites` window.
2985 InvitesList,
2986}
2987
2988impl Display for IambId {
2989 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2990 match self {
2991 IambId::Room(alias, RoomView::Main) => {
2992 let encoded = percent_encode(alias.as_bytes(), NON_ALPHANUMERIC);
2993 write!(f, "iamb://room/{encoded}")
2994 },
2995 IambId::Room(alias, RoomView::Thread(thread)) => {
2996 let encoded = percent_encode(alias.as_bytes(), NON_ALPHANUMERIC);
2997 write!(f, "iamb://room/{encoded}/threads/{thread}")
2998 },
2999 IambId::Room(alias, RoomView::Message(message)) => {
3000 let encoded = percent_encode(alias.as_bytes(), NON_ALPHANUMERIC);
3001 write!(f, "iamb://room/{encoded}/messages/{message}")
3002 },
3003 IambId::MemberList(room_id) => {
3004 write!(f, "iamb://members/{room_id}")
3005 },
3006 IambId::PinnedList(room_id) => {
3007 write!(f, "iamb://room/{room_id}/pinned")
3008 },
3009 IambId::DirectList => f.write_str("iamb://dms"),
3010 IambId::RoomList => f.write_str("iamb://rooms"),
3011 IambId::SpaceList => f.write_str("iamb://spaces"),
3012 IambId::ToplevelSpaceList => f.write_str("iamb://spaces/toplevel"),
3013 IambId::VerifyList => f.write_str("iamb://verify"),
3014 IambId::Welcome => f.write_str("iamb://welcome"),
3015 IambId::ChatList => f.write_str("iamb://chats"),
3016 IambId::UnreadList => f.write_str("iamb://unreads"),
3017 IambId::MentionsList => f.write_str("iamb://mentions"),
3018 IambId::InvitesList => f.write_str("iamb://invites"),
3019 }
3020 }
3021}
3022
3023impl ApplicationWindowId for IambId {}
3024
3025impl Serialize for IambId {
3026 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
3027 where
3028 S: Serializer,
3029 {
3030 serializer.serialize_str(&self.to_string())
3031 }
3032}
3033
3034impl<'de> Deserialize<'de> for IambId {
3035 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3036 where
3037 D: Deserializer<'de>,
3038 {
3039 deserializer.deserialize_str(IambIdVisitor)
3040 }
3041}
3042
3043/// [serde] visitor for deserializing [IambId].
3044struct IambIdVisitor;
3045
3046impl Visitor<'_> for IambIdVisitor {
3047 type Value = IambId;
3048
3049 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
3050 formatter.write_str("a valid window URL")
3051 }
3052
3053 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
3054 where
3055 E: SerdeError,
3056 {
3057 let Ok(url) = Url::parse(value) else {
3058 return Err(E::custom("Invalid iamb window URL"));
3059 };
3060
3061 if url.scheme() != "iamb" {
3062 return Err(E::custom("Invalid iamb window URL"));
3063 }
3064
3065 match url.domain() {
3066 Some("room") => {
3067 let Some(path) = url.path_segments() else {
3068 return Err(E::custom("Invalid members window URL"));
3069 };
3070
3071 match *path.collect::<Vec<_>>().as_slice() {
3072 [alias] => {
3073 let decoded = percent_decode(alias.as_bytes()).decode_utf8_lossy();
3074 let Ok(room_id) = OwnedRoomOrAliasId::try_from(decoded.as_ref()) else {
3075 return Err(E::custom(format!("Invalid room identifier: {decoded:?}")));
3076 };
3077
3078 Ok(IambId::Room(room_id, RoomView::Main))
3079 },
3080 [alias, "threads", thread_root] => {
3081 let decoded = percent_decode(alias.as_bytes()).decode_utf8_lossy();
3082 let Ok(room_id) = OwnedRoomOrAliasId::try_from(decoded.as_ref()) else {
3083 return Err(E::custom("Invalid room identifier: {decoded:?}"));
3084 };
3085
3086 let Ok(thread_root) = OwnedEventId::try_from(thread_root) else {
3087 return Err(E::custom("Invalid thread root identifier"));
3088 };
3089
3090 Ok(IambId::Room(room_id, RoomView::Thread(thread_root)))
3091 },
3092 [alias, "messages", message] => {
3093 let decoded = percent_decode(alias.as_bytes()).decode_utf8_lossy();
3094 let Ok(room_id) = OwnedRoomOrAliasId::try_from(decoded.as_ref()) else {
3095 return Err(E::custom("Invalid room identifier: {decoded:?}"));
3096 };
3097
3098 let message_id = OwnedEventId::try_from(message)
3099 .map(Into::into)
3100 .unwrap_or_else(|_| OwnedTransactionId::from(message).into());
3101
3102 Ok(IambId::Room(room_id, RoomView::Message(message_id)))
3103 },
3104 [room_id, "pinned"] => {
3105 let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
3106 return Err(E::custom("Invalid room identifier"));
3107 };
3108
3109 Ok(IambId::PinnedList(room_id))
3110 },
3111 _ => return Err(E::custom("Invalid iamb window URL")),
3112 }
3113 },
3114 Some("members") => {
3115 let Some(path) = url.path_segments() else {
3116 return Err(E::custom("Invalid members window URL"));
3117 };
3118
3119 let &[room_id] = path.collect::<Vec<_>>().as_slice() else {
3120 return Err(E::custom("Invalid members window URL"));
3121 };
3122
3123 let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
3124 return Err(E::custom("Invalid room identifier"));
3125 };
3126
3127 Ok(IambId::MemberList(room_id))
3128 },
3129 Some("dms") => {
3130 if url.path() != "" {
3131 return Err(E::custom("iamb://dms takes no path"));
3132 }
3133
3134 Ok(IambId::DirectList)
3135 },
3136 Some("rooms") => {
3137 if url.path() != "" {
3138 return Err(E::custom("iamb://rooms takes no path"));
3139 }
3140
3141 Ok(IambId::RoomList)
3142 },
3143 Some("spaces") => {
3144 if url.path() == "toplevel" {
3145 return Ok(IambId::ToplevelSpaceList);
3146 }
3147
3148 if url.path() != "" {
3149 return Err(E::custom("Invalid iamb window URL"));
3150 }
3151
3152 Ok(IambId::SpaceList)
3153 },
3154 Some("verify") => {
3155 if url.path() != "" {
3156 return Err(E::custom("iamb://verify takes no path"));
3157 }
3158
3159 Ok(IambId::VerifyList)
3160 },
3161 Some("welcome") => {
3162 if url.path() != "" {
3163 return Err(E::custom("iamb://welcome takes no path"));
3164 }
3165
3166 Ok(IambId::Welcome)
3167 },
3168 Some("chats") => {
3169 if url.path() != "" {
3170 return Err(E::custom("iamb://chats takes no path"));
3171 }
3172
3173 Ok(IambId::ChatList)
3174 },
3175 Some("unreads") => {
3176 if url.path() != "" {
3177 return Err(E::custom("iamb://unreads takes no path"));
3178 }
3179
3180 Ok(IambId::UnreadList)
3181 },
3182 Some("mentions") => {
3183 if url.path() != "" {
3184 return Err(E::custom("iamb://mentions takes no path"));
3185 }
3186
3187 Ok(IambId::MentionsList)
3188 },
3189 Some("invites") => {
3190 if url.path() != "" {
3191 return Err(E::custom("iamb://invites takes no path"));
3192 }
3193
3194 Ok(IambId::InvitesList)
3195 },
3196 Some(s) => Err(E::custom(format!("{s:?} is not a valid window"))),
3197 None => Err(E::custom("Invalid iamb window URL")),
3198 }
3199 }
3200}
3201
3202/// Which part of the room window's UI is focused.
3203#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
3204pub enum RoomFocus {
3205 /// The scrollback for a room window is focused.
3206 Scrollback,
3207
3208 /// The message bar for a room window is focused.
3209 MessageBar,
3210}
3211
3212impl RoomFocus {
3213 /// Whether this is [RoomFocus::Scrollback].
3214 pub fn is_scrollback(&self) -> bool {
3215 matches!(self, RoomFocus::Scrollback)
3216 }
3217
3218 /// Whether this is [RoomFocus::MessageBar].
3219 pub fn is_msgbar(&self) -> bool {
3220 matches!(self, RoomFocus::MessageBar)
3221 }
3222
3223 pub fn toggle(&mut self) {
3224 *self = match self {
3225 RoomFocus::MessageBar => RoomFocus::Scrollback,
3226 RoomFocus::Scrollback => RoomFocus::MessageBar,
3227 };
3228 }
3229}
3230
3231/// Identifiers used to track where a mark was placed.
3232///
3233/// While this is the "buffer identifier" for the mark,
3234/// not all of these are necessarily actual buffers.
3235#[derive(Clone, Debug, Eq, Hash, PartialEq)]
3236pub enum IambBufferId {
3237 /// The command bar buffer.
3238 Command(CommandType),
3239
3240 /// The message buffer or a specific message in a room.
3241 Room(OwnedRoomId, RoomView, RoomFocus),
3242
3243 /// The `:dms` window.
3244 DirectList,
3245
3246 /// The `:members` window for a room.
3247 MemberList(OwnedRoomId),
3248
3249 /// The `:pinned` window for a room.
3250 PinnedList(OwnedRoomId),
3251
3252 /// The `:rooms` window.
3253 RoomList,
3254
3255 /// The `:spaces` window.
3256 SpaceList,
3257
3258 /// The `:spaces toplevel` window.
3259 ToplevelSpaceList,
3260
3261 /// The `:verify` window.
3262 VerifyList,
3263
3264 /// The buffer for the `:rooms` window.
3265 Welcome,
3266
3267 /// The `:chats` window.
3268 ChatList,
3269
3270 /// The `:unreads` window.
3271 UnreadList,
3272
3273 /// The `:mentions` window.
3274 MentionsList,
3275
3276 /// The `:invites` window.
3277 InvitesList,
3278}
3279
3280impl IambBufferId {
3281 /// Get the identifier for the window that contains this buffer.
3282 pub fn to_window(&self) -> Option<IambId> {
3283 let id = match self {
3284 IambBufferId::Command(_) => return None,
3285 IambBufferId::Room(room, view, _) => IambId::Room(room.clone().into(), view.clone()),
3286 IambBufferId::DirectList => IambId::DirectList,
3287 IambBufferId::MemberList(room) => IambId::MemberList(room.clone()),
3288 IambBufferId::PinnedList(room) => IambId::PinnedList(room.clone()),
3289 IambBufferId::RoomList => IambId::RoomList,
3290 IambBufferId::SpaceList => IambId::SpaceList,
3291 IambBufferId::ToplevelSpaceList => IambId::ToplevelSpaceList,
3292 IambBufferId::VerifyList => IambId::VerifyList,
3293 IambBufferId::Welcome => IambId::Welcome,
3294 IambBufferId::ChatList => IambId::ChatList,
3295 IambBufferId::UnreadList => IambId::UnreadList,
3296 IambBufferId::MentionsList => IambId::MentionsList,
3297 IambBufferId::InvitesList => IambId::InvitesList,
3298 };
3299
3300 Some(id)
3301 }
3302}
3303
3304impl ApplicationContentId for IambBufferId {}
3305
3306impl ApplicationInfo for IambInfo {
3307 type Error = IambError;
3308 type Store = ChatStore;
3309 type Action = IambAction;
3310 type WindowId = IambId;
3311 type ContentId = IambBufferId;
3312
3313 fn content_of_command(ct: CommandType) -> IambBufferId {
3314 IambBufferId::Command(ct)
3315 }
3316}
3317
3318#[cfg(test)]
3319pub mod tests {
3320 use super::*;
3321
3322 use std::iter::FromIterator as _;
3323
3324 use matrix_sdk::ruma::events::reaction::ReactionEventContent;
3325 use matrix_sdk::ruma::events::relation::Annotation;
3326 use matrix_sdk::ruma::{MilliSecondsSinceUnixEpoch, owned_event_id, owned_user_id};
3327 use pretty_assertions::assert_eq;
3328 use ratatui::style::Color;
3329 use serde_json::{Map, Value};
3330
3331 use crate::tests::*;
3332
3333 fn mock_room_message_event(
3334 content: RoomMessageEventContent,
3335 sender: OwnedUserId,
3336 key: MessageKey,
3337 ) -> RoomMessageEvent {
3338 let message = mock_room1_message(content, sender, key);
3339 let MessageEvent::Original(event, _) = message.event else {
3340 unreachable!("mock_room1_message always returns an original room message")
3341 };
3342
3343 MessageLikeEvent::Original(*event)
3344 }
3345
3346 fn create_reaction_event(
3347 content: &ReactionEventContent,
3348 event_id: &str,
3349 sender: &str,
3350 ) -> ReactionEvent {
3351 serde_json::from_value(Value::Object(Map::from_iter([
3352 ("type".to_owned(), Value::String("m.reaction".into())),
3353 ("content".to_owned(), serde_json::to_value(content).unwrap()),
3354 ("event_id".to_owned(), serde_json::to_value(event_id).unwrap()),
3355 ("sender".to_owned(), Value::String(sender.into())),
3356 (
3357 "origin_server_ts".to_owned(),
3358 serde_json::to_value(MilliSecondsSinceUnixEpoch::now()).unwrap(),
3359 ),
3360 ("room_id".to_owned(), Value::String("!foo:example.org".into())),
3361 ])))
3362 .unwrap()
3363 }
3364
3365 #[test]
3366 fn test_multiple_identical_reactions() {
3367 let mut info = RoomInfo::default();
3368
3369 let content = ReactionEventContent::new(Annotation::new(
3370 owned_event_id!("$my_reaction"),
3371 "🏠".to_owned(),
3372 ));
3373
3374 for i in 0..3 {
3375 let event_id = format!("$house_{i}");
3376 let react = create_reaction_event(&content, &event_id, "@foo:example.com");
3377 info.insert_reaction(react, None);
3378 }
3379
3380 let content = ReactionEventContent::new(Annotation::new(
3381 owned_event_id!("$my_reaction"),
3382 "🙂".to_owned(),
3383 ));
3384
3385 for i in 0..2 {
3386 let event_id = format!("$smile_{i}");
3387 let react = create_reaction_event(&content, &event_id, "@foo:example.com");
3388 info.insert_reaction(react, None);
3389 }
3390
3391 for i in 2..4 {
3392 let event_id = format!("$smile2_{i}");
3393 let react = create_reaction_event(&content, &event_id, "@bar:example.com");
3394 info.insert_reaction(react, None);
3395 }
3396
3397 let reacts: Vec<_> = info
3398 .get_reactions(&owned_event_id!("$my_reaction"))
3399 .into_iter()
3400 .map(|(key, count, _)| (key, count))
3401 .collect();
3402 assert_eq!(reacts, vec![
3403 ("🏠", vec![owned_user_id!("@foo:example.com").deref()]),
3404 ("🙂", vec![
3405 owned_user_id!("@bar:example.com").deref(),
3406 owned_user_id!("@foo:example.com").deref(),
3407 ],)
3408 ]);
3409 }
3410
3411 #[test]
3412 fn test_implicit_receipt_tracks_message_sender_for_display() {
3413 let mut info = RoomInfo::default();
3414 let settings = mock_settings();
3415 let mut previews = PreviewManager::new(&settings);
3416 let event = mock_room_message_event(
3417 RoomMessageEventContent::text_plain("sent by another user"),
3418 TEST_USER2.clone(),
3419 MSG5_KEY.clone(),
3420 );
3421
3422 info.insert_message(event, ThreadSummaryStatus::Unknown, &settings, &mut previews);
3423
3424 assert_eq!(
3425 info.user_receipts(&ReceiptThread::Main)
3426 .and_then(|receipts| receipts.get(&*TEST_USER2)),
3427 Some(&*MSG5_EVID),
3428 );
3429 assert!(
3430 info.event_receipts(&ReceiptThread::Main)
3431 .and_then(|receipts| receipts.get(&*MSG5_EVID))
3432 .is_some_and(|users| users.contains(&*TEST_USER2))
3433 );
3434 }
3435
3436 #[test]
3437 fn test_implicit_receipts_do_not_move_backwards_during_backpagination() {
3438 let mut info = RoomInfo::default();
3439 let settings = mock_settings();
3440 let mut previews = PreviewManager::new(&settings);
3441 let newer = mock_room_message_event(
3442 RoomMessageEventContent::text_plain("newer"),
3443 TEST_USER2.clone(),
3444 MSG5_KEY.clone(),
3445 );
3446 let older = mock_room_message_event(
3447 RoomMessageEventContent::text_plain("older"),
3448 TEST_USER2.clone(),
3449 MSG2_KEY.clone(),
3450 );
3451
3452 info.insert_message(newer, ThreadSummaryStatus::Unknown, &settings, &mut previews);
3453 info.insert_message(older, ThreadSummaryStatus::Unknown, &settings, &mut previews);
3454
3455 assert_eq!(
3456 info.user_receipts(&ReceiptThread::Main)
3457 .and_then(|receipts| receipts.get(&*TEST_USER2)),
3458 Some(&*MSG5_EVID),
3459 );
3460 }
3461
3462 #[test]
3463 fn test_implicit_receipt_preserves_thread_context() {
3464 let mut info = RoomInfo::default();
3465 let root = owned_event_id!("$thread_root");
3466 let reply = owned_event_id!("$thread_reply");
3467 let thread = ReceiptThread::Thread(root.clone());
3468
3469 info.keys
3470 .insert(reply.clone(), EventLocation::Message(Some(root), MSG5_KEY.clone()));
3471 info.set_implicit_receipt(TEST_USER1.clone(), reply.clone());
3472
3473 assert_eq!(
3474 info.user_receipts(&thread).and_then(|receipts| receipts.get(&*TEST_USER1)),
3475 Some(&reply),
3476 );
3477 }
3478
3479 #[test]
3480 fn test_implicit_receipt_supports_state_events() {
3481 let mut info = RoomInfo::default();
3482 info.keys
3483 .insert(MSG5_EVID.clone(), EventLocation::Message(None, MSG5_KEY.clone()));
3484
3485 info.set_implicit_receipt(TEST_USER2.clone(), MSG5_EVID.clone());
3486
3487 assert_eq!(
3488 info.user_receipts(&ReceiptThread::Main)
3489 .and_then(|receipts| receipts.get(&*TEST_USER2)),
3490 Some(&*MSG5_EVID),
3491 );
3492 }
3493
3494 #[test]
3495 fn test_explicit_receipt_does_not_move_implicit_receipt_backwards() {
3496 let settings = mock_settings();
3497 let mut previews = PreviewManager::new(&settings);
3498 let mut info = RoomInfo::default();
3499 let older = mock_room_message_event(
3500 RoomMessageEventContent::text_plain("older"),
3501 TEST_USER2.clone(),
3502 MSG2_KEY.clone(),
3503 );
3504 let newer = mock_room_message_event(
3505 RoomMessageEventContent::text_plain("newer"),
3506 TEST_USER2.clone(),
3507 MSG5_KEY.clone(),
3508 );
3509
3510 info.insert_message(older, ThreadSummaryStatus::Unknown, &settings, &mut previews);
3511 info.insert_message(newer, ThreadSummaryStatus::Unknown, &settings, &mut previews);
3512 info.set_receipt(ReceiptThread::Main, TEST_USER2.clone(), MSG2_EVID.clone());
3513
3514 assert_eq!(
3515 info.user_receipts(&ReceiptThread::Main)
3516 .and_then(|receipts| receipts.get(&*TEST_USER2)),
3517 Some(&*MSG5_EVID),
3518 );
3519 }
3520
3521 #[test]
3522 fn test_implicit_receipt_waits_for_unloaded_explicit_receipt() {
3523 let settings = mock_settings();
3524 let mut previews = PreviewManager::new(&settings);
3525 let mut info = RoomInfo::default();
3526 info.set_receipt(ReceiptThread::Main, TEST_USER2.clone(), MSG5_EVID.clone());
3527 let older = mock_room_message_event(
3528 RoomMessageEventContent::text_plain("older"),
3529 TEST_USER2.clone(),
3530 MSG2_KEY.clone(),
3531 );
3532
3533 info.insert_message(older, ThreadSummaryStatus::Unknown, &settings, &mut previews);
3534
3535 assert_eq!(
3536 info.user_receipts(&ReceiptThread::Main)
3537 .and_then(|receipts| receipts.get(&*TEST_USER2)),
3538 Some(&*MSG5_EVID),
3539 );
3540 }
3541
3542 #[test]
3543 fn test_typing_spans() {
3544 let mut info = RoomInfo::default();
3545 let settings = mock_settings();
3546 let theme = &settings.theme;
3547
3548 let users0 = vec![];
3549 let users1 = vec![TEST_USER1.clone()];
3550 let users2 = vec![TEST_USER1.clone(), TEST_USER2.clone()];
3551 let users4 = vec![
3552 TEST_USER1.clone(),
3553 TEST_USER2.clone(),
3554 TEST_USER3.clone(),
3555 TEST_USER4.clone(),
3556 ];
3557 let users5 = vec![
3558 TEST_USER1.clone(),
3559 TEST_USER2.clone(),
3560 TEST_USER3.clone(),
3561 TEST_USER4.clone(),
3562 TEST_USER5.clone(),
3563 ];
3564
3565 // Nothing set.
3566 assert_eq!(info.users_typing, None);
3567 assert_eq!(info.get_typing_spans(&settings), Line::from(vec![]));
3568
3569 // Empty typing list.
3570 info.set_typing(users0);
3571 assert!(info.users_typing.is_some());
3572 assert_eq!(info.get_typing_spans(&settings), Line::from(vec![]));
3573
3574 // Single user typing.
3575 info.set_typing(users1);
3576 assert!(info.users_typing.is_some());
3577 assert_eq!(
3578 info.get_typing_spans(&settings),
3579 Line::from(vec![
3580 Span::styled("@user1:example.com", theme.users.style("@user1:example.com", None)),
3581 Span::from(" is typing...")
3582 ])
3583 );
3584
3585 // Two users typing.
3586 info.set_typing(users2);
3587 assert!(info.users_typing.is_some());
3588 assert_eq!(
3589 info.get_typing_spans(&settings),
3590 Line::from(vec![
3591 Span::styled("@user1:example.com", theme.users.style("@user1:example.com", None)),
3592 Span::raw(" and "),
3593 Span::styled("@user2:example.com", theme.users.style("@user2:example.com", None)),
3594 Span::raw(" are typing...")
3595 ])
3596 );
3597
3598 // Four users typing.
3599 info.set_typing(users4);
3600 assert!(info.users_typing.is_some());
3601 assert_eq!(info.get_typing_spans(&settings), Line::from("Several people are typing..."));
3602
3603 // Five users typing.
3604 info.set_typing(users5);
3605 assert!(info.users_typing.is_some());
3606 assert_eq!(info.get_typing_spans(&settings), Line::from("Many people are typing..."));
3607
3608 // Test that USER5 gets rendered using the configured color and name.
3609 info.set_typing(vec![TEST_USER5.clone()]);
3610 assert!(info.users_typing.is_some());
3611 assert_eq!(
3612 info.get_typing_spans(&settings),
3613 Line::from(vec![
3614 Span::styled("USER 5", Style::default().fg(Color::Black).bold()),
3615 Span::from(" is typing...")
3616 ])
3617 );
3618 }
3619
3620 #[test]
3621 fn test_need_load() {
3622 let room_id = TEST_ROOM1_ID.clone();
3623
3624 let mut need_load = RoomNeeds::default();
3625
3626 need_load.need_messages(room_id.clone());
3627 need_load.need_members(room_id.clone());
3628
3629 assert_eq!(need_load.room_needs().collect::<Vec<(OwnedRoomId, Need)>>(), vec![(
3630 room_id,
3631 Need {
3632 members: true,
3633 messages: Some(Vec::new()),
3634 pinned: false
3635 }
3636 )],);
3637 }
3638
3639 #[test]
3640 fn test_pinned_lookup() {
3641 let mut info = mock_room();
3642 let unloaded = owned_event_id!("$unloaded");
3643
3644 info.pinned_events = vec![MSG3_EVID.clone(), unloaded.clone()];
3645
3646 assert!(info.is_pinned(&MSG3_EVID));
3647 assert!(!info.is_pinned(&MSG4_EVID));
3648
3649 // Loaded messages come from the scrollback, so only the unloaded one needs fetching.
3650 assert!(info.get_pinned(&MSG3_EVID).is_some());
3651 assert_eq!(info.missing_pinned(), vec![unloaded.clone()]);
3652
3653 info.insert_pinned(unloaded.clone(), mock_message1().into());
3654 assert!(info.get_pinned(&unloaded).is_some());
3655 assert!(info.missing_pinned().is_empty());
3656
3657 // Failed fetches are retried until they hit the limit.
3658 let broken = owned_event_id!("$broken");
3659 info.pinned_events.push(broken.clone());
3660
3661 for _ in 1..PINNED_FETCH_ATTEMPTS {
3662 info.insert_pinned(broken.clone(), None);
3663 }
3664 assert!(!info.pinned_unavailable(&broken));
3665 assert_eq!(info.missing_pinned(), vec![broken.clone()]);
3666
3667 info.insert_pinned(broken.clone(), None);
3668 assert!(info.pinned_unavailable(&broken));
3669 assert!(info.missing_pinned().is_empty());
3670
3671 let (thread, key) = info.get_message_location(&MSG3_EVID).unwrap();
3672 assert_eq!(thread, None);
3673 assert_eq!(key, &*MSG3_KEY);
3674 assert!(info.get_message_location(&unloaded).is_none());
3675 }
3676
3677 #[test]
3678 fn test_alias_window_id() {
3679 let room_id = TEST_ROOM1_ALIAS.clone();
3680 let id = IambId::Room(room_id.into(), RoomView::Main);
3681
3682 // Hash gets replaced during encoding:
3683 let exp = "iamb://room/%23room1%3Aexample%2Ecom";
3684 assert_eq!(id.to_string(), exp);
3685
3686 // Percent encoding turns back into hash during decoding:
3687 let parsed: IambId = serde_json::from_str(&format!("{exp:?}")).unwrap();
3688 assert_eq!(parsed, id);
3689 }
3690
3691 #[test]
3692 fn test_pinned_window_id() {
3693 let room_id = TEST_ROOM1_ID.clone();
3694 let id = IambId::PinnedList(room_id.clone());
3695 let url = format!("iamb://room/{room_id}/pinned");
3696
3697 assert_eq!(id.to_string(), url);
3698
3699 let parsed: IambId = serde_json::from_str(&format!("{url:?}")).unwrap();
3700 assert_eq!(parsed, id);
3701 }
3702}