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