src/base.rs
3681 lines · 123740 bytes
1//! # Common types and utilities
2//!
3//! The types defined here get used throughout iamb.
4
5use std::collections::{BTreeSet, HashSet};
6
7use emojis::Emoji;
8use matrix_sdk::Client;
9use matrix_sdk::deserialized_responses::{AmbiguityChange, ThreadSummary, ThreadSummaryStatus};
10use matrix_sdk::ruma::events::poll::start::PollStartEvent;
11use matrix_sdk::ruma::events::poll::unstable_start::{
12 UnstablePollStartEvent,
13 UnstablePollStartEventContent,
14};
15use matrix_sdk::ruma::events::reaction::ReactionEvent;
16use matrix_sdk::ruma::events::relation::Replacement;
17use matrix_sdk::ruma::events::room::encrypted::RoomEncryptedEvent;
18use matrix_sdk::ruma::events::room::member::MembershipState;
19use matrix_sdk::ruma::events::room::message::RelationWithoutReplacement;
20use matrix_sdk::ruma::events::room::message::{
21 RoomMessageEvent,
22 RoomMessageEventContentWithoutRelation,
23};
24use matrix_sdk::ruma::events::room::power_levels::UserPowerLevel;
25use matrix_sdk::ruma::events::room::redaction::{
26 OriginalSyncRoomRedactionEvent,
27 SyncRoomRedactionEvent,
28};
29use matrix_sdk::ruma::events::space::child::SpaceChildEventContent;
30use matrix_sdk::ruma::events::sticker::{StickerEvent, StickerEventContent};
31use matrix_sdk::ruma::events::{MessageLikeEvent, OriginalMessageLikeEvent};
32use matrix_sdk::ruma::presence::PresenceState;
33use matrix_sdk::ruma::room::{AllowRule, Restricted};
34use matrix_sdk::ruma::{OwnedMxcUri, OwnedTransactionId, RoomVersionId};
35use matrix_sdk_base::read_receipts::ReadReceipts;
36use modalkit::editing::application::{
37 ApplicationAction,
38 ApplicationContentId,
39 ApplicationError,
40 ApplicationInfo,
41 ApplicationStore,
42 ApplicationWindowId,
43};
44use modalkit::editing::completion::CompletionMap;
45use modalkit::editing::context::EditContext;
46use modalkit::editing::store::Store;
47use modalkit::env::vim::command::{CommandContext, VimCommand, VimCommandMachine};
48use modalkit::env::vim::keybindings::VimMachine;
49use modalkit::errors::UIResult;
50use modalkit::keybindings::SequenceStatus;
51use percent_encoding::{NON_ALPHANUMERIC, percent_decode, percent_encode};
52use serde::de::Error as SerdeError;
53use serde::de::Visitor;
54use serde::{Deserialize, Deserializer, Serialize, Serializer};
55use tokio::sync::{Mutex as AsyncMutex, Notify};
56use tokio::task::JoinHandle;
57
58use crate::message::poll::{
59 Poll,
60 PollEventLocation,
61 PollRelation,
62 UnloadedPoll,
63 UnloadedUnstablePoll,
64 UnstablePoll,
65 UnstablePollRelation,
66};
67use crate::notifications::NotificationHandle;
68use crate::prelude::*;
69use crate::worker::{subscribe_room_updates, subscribe_thread_updates};
70
71/// The set of characters used in different Matrix IDs.
72pub const MATRIX_ID_WORD: WordStyle = WordStyle::CharSet(is_mxid_char);
73
74/// Find the boundaries for a Matrix username, room alias, or room ID.
75///
76/// Technically "[" and "]" should be here since IPv6 addresses are allowed
77/// in the server name, but in practice that should be uncommon, and people
78/// can just use `gf` and friends in Visual mode instead.
79fn is_mxid_char(c: char) -> bool {
80 return c >= 'a' && c <= 'z' ||
81 c >= 'A' && c <= 'Z' ||
82 c >= '0' && c <= '9' ||
83 ":-./@_#!".contains(c);
84}
85
86const ROOM_FETCH_DEBOUNCE: Duration = Duration::from_secs(2);
87
88/// Empty type used solely to implement [ApplicationInfo].
89#[derive(Clone, Debug, Eq, PartialEq)]
90pub enum IambInfo {}
91
92/// An action taken against an ongoing verification request.
93#[derive(Clone, Debug, Eq, PartialEq)]
94pub enum VerifyAction {
95 /// Accept a verification request.
96 Accept,
97
98 /// Cancel an in-progress verification.
99 Cancel,
100
101 /// Confirm an in-progress verification.
102 Confirm,
103
104 /// Reject an in-progress verification due to mismatched Emoji.
105 Mismatch,
106
107 /// Start an interactive (SAS) emoji verification
108 Emoji,
109}
110
111/// An action taken against 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/// Information about a user within a specific room.
1186#[derive(Clone, Debug)]
1187pub struct MemberSummary {
1188 /// The member's user identifier.
1189 pub user_id: OwnedUserId,
1190
1191 /// The member's display name in this room, if they have one.
1192 pub display_name: Option<String>,
1193
1194 /// The member's power level in the room.
1195 pub power_level: UserPowerLevel,
1196
1197 /// The member's current room membership (joined/invited/knocked/etc).
1198 pub membership: MembershipState,
1199
1200 /// Whether the name is ambiguous in the room.
1201 pub name_ambiguous: bool,
1202}
1203
1204impl MemberSummary {
1205 /// The display name to show for this member, falling back to their localpart.
1206 pub fn name(&self) -> &str {
1207 self.display_name.as_deref().unwrap_or_else(|| self.user_id.localpart())
1208 }
1209
1210 /// Get the member's current state.
1211 pub fn membership(&self) -> &MembershipState {
1212 &self.membership
1213 }
1214
1215 /// Get the member's power level in the room.
1216 pub fn power_level(&self) -> UserPowerLevel {
1217 self.power_level
1218 }
1219
1220 /// Get the user identifier.
1221 pub fn user_id(&self) -> &UserId {
1222 self.user_id.as_ref()
1223 }
1224
1225 /// Whether this member has joined the room.
1226 pub fn is_join(&self) -> bool {
1227 self.membership == MembershipState::Join
1228 }
1229
1230 /// Whether this member has been invited to the room.
1231 pub fn is_invite(&self) -> bool {
1232 self.membership == MembershipState::Invite
1233 }
1234
1235 /// Whether this member has knocked on the room.
1236 pub fn is_knock(&self) -> bool {
1237 self.membership == MembershipState::Knock
1238 }
1239
1240 /// Whether this member should be counted as active in the room.
1241 ///
1242 /// We show active room members in `:members`, use them for display name disambiguation,
1243 /// and so on.
1244 pub fn is_active(&self) -> bool {
1245 self.is_join() || self.is_invite() || self.is_knock()
1246 }
1247}
1248
1249#[derive(Default)]
1250struct UserDisplayName {
1251 name: Option<String>,
1252 is_ambiguous: bool,
1253}
1254
1255/// Track the display names for users and render any needed disambiguation for
1256/// those with overlapping names.
1257#[derive(Default)]
1258pub struct DisplayNameStore {
1259 by_ids: HashMap<OwnedUserId, UserDisplayName>,
1260}
1261
1262impl DisplayNameStore {
1263 pub(crate) fn apply_ambiguity_change(&mut self, change: AmbiguityChange) {
1264 self.by_ids.entry(change.member_id).or_default().is_ambiguous = change.member_ambiguous;
1265
1266 if let Some(user_id) = change.ambiguated_member {
1267 self.by_ids.entry(user_id).or_default().is_ambiguous = true;
1268 }
1269 if let Some(user_id) = change.disambiguated_member {
1270 self.by_ids.entry(user_id).or_default().is_ambiguous = false;
1271 }
1272 }
1273
1274 /// Track a new user ID to displayname mapping, or unset any existing ones.
1275 pub fn set(
1276 &mut self,
1277 user_id: OwnedUserId,
1278 name: Option<String>,
1279 name_ambiguous: Option<bool>,
1280 ) {
1281 let user = self.by_ids.entry(user_id).or_default();
1282 user.name = name;
1283
1284 if let Some(ambiguous) = name_ambiguous {
1285 user.is_ambiguous = ambiguous;
1286 }
1287 }
1288
1289 pub fn get<'a>(&'a self, user_id: &UserId) -> Option<Cow<'a, str>> {
1290 let user = self.by_ids.get(user_id)?;
1291 let displayname = user.name.as_ref()?;
1292
1293 if user.is_ambiguous {
1294 Some(Cow::Owned(format!("{displayname} ({user_id})")))
1295 } else {
1296 Some(Cow::Borrowed(displayname.as_str()))
1297 }
1298 }
1299
1300 pub fn complete_mention(&self, prefix: &str) -> Vec<String> {
1301 // spec says to mention with display name in anchor text
1302 let mut users = BTreeSet::new();
1303
1304 let name_prefix = prefix.strip_prefix('@').unwrap_or(prefix);
1305 for (user_id, user) in self.by_ids.iter() {
1306 if user_id.as_str().starts_with(prefix) {
1307 let name = user.name.as_deref().unwrap_or(user_id.as_str());
1308 users.insert(format!("[{}][{}]", name, user_id));
1309 }
1310
1311 if let Some(name) = &user.name &&
1312 name.starts_with(name_prefix)
1313 {
1314 users.insert(format!("[{}][{}]", name, user_id));
1315 }
1316 }
1317
1318 users.into_iter().collect()
1319 }
1320}
1321
1322bitflags::bitflags! {
1323 /// Additional information about a room.
1324 #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
1325 pub struct RoomInfoFlags: u32 {
1326 /// No flags specified.
1327 const NONE = 0b00000000;
1328
1329 /// All notifications for this room have been muted.
1330 const MUTED = 0b00000001;
1331
1332 /// Non-mention/keyword notifications for this room have been muted.
1333 const CALMED = 0b00000010;
1334 }
1335}
1336
1337pub struct Thread {
1338 messages: Messages,
1339
1340 root: Option<Message>,
1341 pub(crate) summary: Option<ThreadSummary>,
1342
1343 pub(crate) unreads: ReadReceipts,
1344 update_handle: Option<JoinHandle<()>>,
1345
1346 /// A map of read markers to display on different events.
1347 event_receipts: HashMap<OwnedEventId, HashSet<OwnedUserId>>,
1348 /// A map of the most recent read marker for each user.
1349 ///
1350 /// Every receipt in this map should also have an entry in [`event_receipts`](`Self::event_receipts`),
1351 /// however not every user has an entry. If a user's most recent receipt is
1352 /// older than the oldest loaded event, that user will not be included.
1353 user_receipts: HashMap<OwnedUserId, OwnedEventId>,
1354}
1355
1356impl Thread {
1357 fn new(root: OwnedEventId) -> Self {
1358 Self {
1359 messages: Messages::new(ReceiptThread::Thread(root)),
1360 root: Default::default(),
1361 summary: Default::default(),
1362 update_handle: Default::default(),
1363 unreads: Default::default(),
1364 event_receipts: Default::default(),
1365 user_receipts: Default::default(),
1366 }
1367 }
1368
1369 pub(crate) async fn subscribe_updates(
1370 &mut self,
1371 room: &MatrixRoom,
1372 root: &EventId,
1373 store: &AsyncProgramStore,
1374 ) {
1375 if self.update_handle.as_ref().is_some_and(|handle| !handle.is_finished()) {
1376 return;
1377 }
1378
1379 match subscribe_thread_updates(room.to_owned(), root.to_owned(), Arc::clone(store)).await {
1380 Ok(handle) => self.update_handle = Some(handle),
1381 Err(err) => {
1382 tracing::warn!(room_id = ?room.room_id(), ?root, "unable to subscribe to thread updates: {err}");
1383 },
1384 }
1385 }
1386}
1387
1388impl Deref for Thread {
1389 type Target = Messages;
1390
1391 fn deref(&self) -> &Self::Target {
1392 &self.messages
1393 }
1394}
1395
1396impl DerefMut for Thread {
1397 fn deref_mut(&mut self) -> &mut Self::Target {
1398 &mut self.messages
1399 }
1400}
1401
1402/// Information about room's the user's joined.
1403pub struct RoomInfo {
1404 /// The display name for this room.
1405 pub name: Option<String>,
1406
1407 /// The tags placed on this room.
1408 pub tags: Option<Tags>,
1409
1410 pub flags: RoomInfoFlags,
1411
1412 /// A map of event IDs to where they are stored in this struct.
1413 pub keys: HashMap<OwnedEventId, EventLocation>,
1414 pub echo_keys: HashMap<OwnedTransactionId, EchoLocation>,
1415
1416 /// The messages loaded for this room.
1417 messages: Messages,
1418
1419 /// A map of read markers to display on different events.
1420 pub event_receipts_main: HashMap<OwnedEventId, HashSet<OwnedUserId>>,
1421 /// A map of the most recent read marker for each user.
1422 ///
1423 /// Every receipt in this map should also have an entry in [`event_receipts`](`Self::event_receipts`),
1424 /// however not every user has an entry. If a user's most recent receipt is
1425 /// older than the oldest loaded event, that user will not be included.
1426 pub user_receipts_main: HashMap<OwnedUserId, OwnedEventId>,
1427 /// Untreaded mirror of [`event_receipts_main`](Self::event_receipts_main)
1428 pub event_receipts_unthreaded: HashMap<OwnedEventId, HashSet<OwnedUserId>>,
1429 /// Untreaded mirror of [`event_receipts_main`](Self::user_receipts_main)
1430 pub user_receipts_unthreaded: HashMap<OwnedUserId, OwnedEventId>,
1431
1432 /// A map of message identifiers to a map of reaction events.
1433 pub reactions: HashMap<OwnedEventId, MessageReactions>,
1434 /// A map of message identifiers to a list of edit events for message that are not yet cached.
1435 pub unloaded_edits: HashMap<OwnedEventId, MessageEdits>,
1436 /// A map of message identifiers to the aggregated data for a poll that hasn't been loaded.
1437 pub unloaded_polls: HashMap<OwnedEventId, UnloadedPoll>,
1438 pub unloaded_unstable_polls: HashMap<OwnedEventId, UnloadedUnstablePoll>,
1439
1440 /// A map of message identifiers to thread replies.
1441 threads: HashMap<OwnedEventId, Thread>,
1442
1443 /// Whether the scrollback for this room is currently being fetched.
1444 pub fetching: bool,
1445
1446 /// Whether all messages are loaded.
1447 pub reached_timeline_start: bool,
1448
1449 /// The time that we last fetched scrollback for this room.
1450 pub fetch_last: Option<Instant>,
1451
1452 /// Handle for the task receiving event cache updates.
1453 update_handle: Option<JoinHandle<()>>,
1454
1455 /// Users currently typing in this room, and when we received notification of them doing so.
1456 pub users_typing: Option<(Instant, Vec<OwnedUserId>)>,
1457
1458 /// The display names for users in this room.
1459 pub display_names: DisplayNameStore,
1460
1461 /// Cached information about the members in this room.
1462 ///
1463 /// Note that this includes members who have left or been banned, so you may need to
1464 /// filter out values when iterating over it, depending on the use case.
1465 pub memberships: HashMap<OwnedUserId, MemberSummary>,
1466
1467 /// The last time the room was rendered, used to detect if it is currently open.
1468 pub draw_last: Option<Instant>,
1469
1470 /// The room's pinned events, mirrored from the SDK's room state for rendering.
1471 pub pinned_events: Vec<OwnedEventId>,
1472
1473 /// Pinned events fetched for the `:pinned` window that aren't in the loaded scrollback.
1474 pub pinned_previews: HashMap<OwnedEventId, Message>,
1475
1476 /// How many times fetching each pinned event for the `:pinned` window has failed.
1477 pub pinned_failures: HashMap<OwnedEventId, u8>,
1478}
1479
1480impl Default for RoomInfo {
1481 fn default() -> Self {
1482 Self {
1483 messages: Messages::new(ReceiptThread::Main),
1484
1485 name: Default::default(),
1486 tags: Default::default(),
1487 keys: Default::default(),
1488 flags: Default::default(),
1489 echo_keys: Default::default(),
1490 event_receipts_main: Default::default(),
1491 user_receipts_main: Default::default(),
1492 event_receipts_unthreaded: Default::default(),
1493 user_receipts_unthreaded: Default::default(),
1494 reactions: Default::default(),
1495 threads: Default::default(),
1496 fetching: Default::default(),
1497 reached_timeline_start: false,
1498 fetch_last: Default::default(),
1499 update_handle: Default::default(),
1500 users_typing: Default::default(),
1501 display_names: Default::default(),
1502 memberships: Default::default(),
1503 draw_last: Default::default(),
1504 pinned_events: Default::default(),
1505 pinned_previews: Default::default(),
1506 pinned_failures: Default::default(),
1507 unloaded_edits: Default::default(),
1508 unloaded_polls: Default::default(),
1509 unloaded_unstable_polls: Default::default(),
1510 }
1511 }
1512}
1513
1514impl RoomInfo {
1515 pub fn get_messages(&self, thread_root: Option<&EventId>) -> Option<&Messages> {
1516 if let Some(thread_root) = thread_root {
1517 self.threads.get(thread_root).map(Deref::deref)
1518 } else {
1519 Some(&self.messages)
1520 }
1521 }
1522
1523 pub fn get_messages_mut(&mut self, thread_root: Option<OwnedEventId>) -> &mut Messages {
1524 if let Some(thread_root) = thread_root {
1525 self.threads
1526 .entry(thread_root.clone())
1527 .or_insert_with(|| Thread::new(thread_root))
1528 } else {
1529 &mut self.messages
1530 }
1531 }
1532
1533 pub(crate) fn get_thread(&self, root: &EventId) -> Option<&Thread> {
1534 self.threads.get(root)
1535 }
1536
1537 pub(crate) fn get_thread_mut(&mut self, root: OwnedEventId) -> &mut Thread {
1538 self.threads.entry(root.clone()).or_insert_with(|| Thread::new(root))
1539 }
1540
1541 pub(crate) fn event_receipts(
1542 &self,
1543 thread: &ReceiptThread,
1544 ) -> Option<&HashMap<OwnedEventId, HashSet<OwnedUserId>>> {
1545 match thread {
1546 ReceiptThread::Thread(root) => Some(&self.get_thread(root)?.event_receipts),
1547 ReceiptThread::Main => Some(&self.event_receipts_main),
1548 ReceiptThread::Unthreaded => Some(&self.event_receipts_unthreaded),
1549 _ => {
1550 tracing::debug!("encountered unknown receipt thread: {thread:?}");
1551 None
1552 },
1553 }
1554 }
1555
1556 pub(crate) fn event_receipts_mut(
1557 &mut self,
1558 thread: &ReceiptThread,
1559 ) -> Option<&mut HashMap<OwnedEventId, HashSet<OwnedUserId>>> {
1560 match thread {
1561 ReceiptThread::Thread(root) => Some(&mut self.threads.get_mut(root)?.event_receipts),
1562 ReceiptThread::Main => Some(&mut self.event_receipts_main),
1563 ReceiptThread::Unthreaded => Some(&mut self.event_receipts_unthreaded),
1564 _ => {
1565 tracing::debug!("encountered unknown receipt thread: {thread:?}");
1566 None
1567 },
1568 }
1569 }
1570
1571 /// # Panics
1572 ///
1573 /// Panics if called with [`ReceiptThread::_Custom`].
1574 pub(crate) fn event_receipts_or_default(
1575 &mut self,
1576 thread: ReceiptThread,
1577 ) -> &mut HashMap<OwnedEventId, HashSet<OwnedUserId>> {
1578 match thread {
1579 ReceiptThread::Thread(root) => &mut self.get_thread_mut(root).event_receipts,
1580 ReceiptThread::Main => &mut self.event_receipts_main,
1581 ReceiptThread::Unthreaded => &mut self.event_receipts_unthreaded,
1582 _ => {
1583 panic!("encountered unknown receipt thread: {thread:?}")
1584 },
1585 }
1586 }
1587
1588 pub(crate) fn user_receipts(
1589 &self,
1590 thread: &ReceiptThread,
1591 ) -> Option<&HashMap<OwnedUserId, OwnedEventId>> {
1592 match thread {
1593 ReceiptThread::Thread(root) => Some(&self.get_thread(root)?.user_receipts),
1594 ReceiptThread::Main => Some(&self.user_receipts_main),
1595 ReceiptThread::Unthreaded => Some(&self.user_receipts_unthreaded),
1596 _ => {
1597 tracing::debug!("encountered unknown receipt thread: {thread:?}");
1598 None
1599 },
1600 }
1601 }
1602
1603 pub(crate) fn user_receipts_mut(
1604 &mut self,
1605 thread: &ReceiptThread,
1606 ) -> Option<&mut HashMap<OwnedUserId, OwnedEventId>> {
1607 match thread {
1608 ReceiptThread::Thread(root) => Some(&mut self.threads.get_mut(root)?.user_receipts),
1609 ReceiptThread::Main => Some(&mut self.user_receipts_main),
1610 ReceiptThread::Unthreaded => Some(&mut self.user_receipts_unthreaded),
1611 _ => {
1612 tracing::debug!("encountered unknown receipt thread: {thread:?}");
1613 None
1614 },
1615 }
1616 }
1617
1618 /// Panics if called with [`ReceiptThread::_Custom`].
1619 pub(crate) fn user_receipts_or_default(
1620 &mut self,
1621 thread: ReceiptThread,
1622 ) -> &mut HashMap<OwnedUserId, OwnedEventId> {
1623 match thread {
1624 ReceiptThread::Thread(root) => &mut self.get_thread_mut(root).user_receipts,
1625 ReceiptThread::Main => &mut self.user_receipts_main,
1626 ReceiptThread::Unthreaded => &mut self.user_receipts_unthreaded,
1627 _ => {
1628 panic!("encountered unknown receipt thread: {thread:?}")
1629 },
1630 }
1631 }
1632
1633 /// Spawn subscriber tasks for all thread updates.
1634 pub(crate) async fn subscribe_updates(&mut self, room: &MatrixRoom, store: &AsyncProgramStore) {
1635 if self.update_handle.as_ref().is_none_or(|hanlde| hanlde.is_finished()) {
1636 match subscribe_room_updates(room.to_owned(), Arc::clone(store)).await {
1637 Ok(handle) => self.update_handle = Some(handle),
1638 Err(err) => {
1639 tracing::warn!(room_id = ?room.room_id(), "unable to subscribe to room updates: {err}");
1640 },
1641 }
1642 }
1643
1644 for (root, thread) in self.threads.iter_mut() {
1645 thread.subscribe_updates(room, root, store).await
1646 }
1647 }
1648
1649 /// Get the event for the last message in a thread (or the thread root if there are no
1650 /// in-thread replies yet).
1651 ///
1652 /// This does not apply edits to the returned event.
1653 ///
1654 /// This returns `None` if the event identifier isn't in the room.
1655 pub fn get_thread_last<'a>(
1656 &'a self,
1657 thread_root: &OwnedEventId,
1658 ) -> Option<&'a OriginalRoomMessageEvent> {
1659 let last = self.threads.get(thread_root).and_then(|t| Some(t.last_key_value()?.1));
1660
1661 let msg = if let Some(last) = last {
1662 &last.event
1663 } else if let EventLocation::Message(_, key) = self.keys.get(thread_root)? {
1664 let msg = self.messages.get(key)?;
1665 &msg.event
1666 } else {
1667 return None;
1668 };
1669
1670 if let MessageEvent::Original(ev, _) = &msg {
1671 Some(ev)
1672 } else {
1673 None
1674 }
1675 }
1676
1677 /// Whether a message is pinned to the room.
1678 pub fn is_pinned(&self, event_id: &EventId) -> bool {
1679 self.pinned_events.iter().any(|id| id == event_id)
1680 }
1681
1682 /// Get a pinned message, from the scrollback if it's loaded or else from the fetched previews.
1683 pub fn get_pinned(&self, event_id: &EventId) -> Option<&Message> {
1684 self.get_event(event_id).or_else(|| self.pinned_previews.get(event_id))
1685 }
1686
1687 /// Whether fetching a pinned event has failed too many times to keep retrying.
1688 pub fn pinned_unavailable(&self, event_id: &EventId) -> bool {
1689 self.pinned_failures
1690 .get(event_id)
1691 .is_some_and(|failures| *failures >= PINNED_FETCH_ATTEMPTS)
1692 }
1693
1694 /// Record the result of fetching a pinned event for the `:pinned` window.
1695 pub fn insert_pinned(&mut self, event_id: OwnedEventId, msg: Option<Message>) {
1696 match msg {
1697 Some(msg) => {
1698 self.pinned_failures.remove(&event_id);
1699 self.pinned_previews.insert(event_id, msg);
1700 },
1701 None => {
1702 let failures = self.pinned_failures.entry(event_id).or_default();
1703 *failures = failures.saturating_add(1);
1704 },
1705 }
1706 }
1707
1708 /// Pinned events that still need to be fetched for the `:pinned` window.
1709 pub fn missing_pinned(&self) -> Vec<OwnedEventId> {
1710 self.pinned_events
1711 .iter()
1712 .filter(|id| self.get_pinned(id).is_none() && !self.pinned_unavailable(id))
1713 .cloned()
1714 .collect()
1715 }
1716
1717 /// Get where a loaded message lives, as its thread root and key.
1718 pub fn get_message_location(
1719 &self,
1720 event_id: &EventId,
1721 ) -> Option<(Option<&EventId>, &MessageKey)> {
1722 let loc = self.keys.get(event_id)?;
1723
1724 Some((loc.to_thread_root(), loc.to_message_key()?))
1725 }
1726
1727 pub fn get_receipt_thread(&self, event_id: &EventId) -> Option<ReceiptThread> {
1728 match self.keys.get(event_id)? {
1729 EventLocation::Message(None, _) => Some(ReceiptThread::Main),
1730 EventLocation::Message(Some(root), _) => Some(ReceiptThread::Thread(root.clone())),
1731 _ => None,
1732 }
1733 }
1734
1735 /// Get the reactions and their counts for a message.
1736 pub fn get_reactions(
1737 &self,
1738 event_id: &EventId,
1739 ) -> Vec<(&str, Vec<&UserId>, &Option<MediaSource>)> {
1740 if let Some(reacts) = self.reactions.get(event_id) {
1741 let mut reactions = BTreeMap::new();
1742
1743 for (key, user, source) in reacts.values() {
1744 let react =
1745 reactions.entry(key.as_str()).or_insert_with(|| (BTreeSet::new(), source));
1746 react.0.insert(user.deref());
1747 }
1748
1749 reactions
1750 .into_iter()
1751 .map(|(key, (users, source))| (key, users.into_iter().collect::<Vec<_>>(), source))
1752 .collect::<Vec<_>>()
1753 } else {
1754 vec![]
1755 }
1756 }
1757
1758 pub fn get_reaction_images(&self, event_id: &EventId) -> impl Iterator<Item = &MediaSource> {
1759 self.reactions
1760 .get(event_id)
1761 .map(HashMap::iter)
1762 .unwrap_or_default()
1763 .filter_map(|(_, (_, _, source))| source.as_ref())
1764 }
1765
1766 /// Map an event identifier to its [MessageKey].
1767 pub fn get_message_key(&self, event_id: &EventId) -> Option<&MessageKey> {
1768 self.keys.get(event_id)?.to_message_key()
1769 }
1770
1771 /// Get an event for an identifier.
1772 pub fn get_event(&self, event_id: &EventId) -> Option<&Message> {
1773 let loc = self.keys.get(event_id)?;
1774
1775 let key = loc.to_message_key()?;
1776 let root = loc.to_thread_root();
1777
1778 self.get_messages(root)?.get(key)
1779 }
1780
1781 /// Get an event for an identifier as mutable.
1782 pub fn get_event_mut(&mut self, event_id: &EventId) -> Option<&mut Message> {
1783 let loc = self.keys.get(event_id)?.clone();
1784
1785 let key = loc.to_message_key()?;
1786 let root = loc.to_thread_root();
1787
1788 self.get_messages_mut(root.map(ToOwned::to_owned)).get_mut(key)
1789 }
1790
1791 /// Map an event identifier to its [`MessageKey`] and thread root.
1792 fn get_message_thread_key(
1793 &self,
1794 message_id: &MessageId,
1795 ) -> Option<(Option<&EventId>, &MessageKey)> {
1796 let event_id = match message_id {
1797 MessageId::Local(id) => {
1798 let loc = self.echo_keys.get(id)?;
1799 match loc {
1800 EchoLocation::Message(root, key) => return Some((root.as_deref(), key)),
1801 EchoLocation::Replaced(event_id) => event_id,
1802 }
1803 },
1804 MessageId::Origin(event_id) => event_id,
1805 };
1806
1807 let loc = self.keys.get(event_id)?;
1808
1809 Some((loc.to_thread_root(), loc.to_message_key()?))
1810 }
1811
1812 /// Get an event for an identifier.
1813 pub fn get_message(&self, message_id: &MessageId) -> Option<&Message> {
1814 let (root, key) = self.get_message_thread_key(message_id)?;
1815
1816 self.get_messages(root)?.get(key)
1817 }
1818
1819 /// Get an event for an identifier as mutable.
1820 pub fn get_message_mut(&mut self, message_id: &MessageId) -> Option<&mut Message> {
1821 let (root, key) = self.get_message_thread_key(message_id)?;
1822
1823 let root = root.map(ToOwned::to_owned);
1824 let key = key.to_owned();
1825
1826 self.get_messages_mut(root).get_mut(&key)
1827 }
1828
1829 pub fn redact(&mut self, ev: OriginalSyncRoomRedactionEvent) {
1830 let Some(redacts) = &ev.redacts else {
1831 return;
1832 };
1833
1834 match self.keys.get(redacts) {
1835 None => return,
1836 Some(EventLocation::Edit(msg_event_id, edit_key)) => {
1837 let edit_key = edit_key.clone();
1838 let msg_loc = self.keys.get(msg_event_id).cloned();
1839 if let Some(EventLocation::Message(thread, msg_key)) = msg_loc {
1840 if let Some(msg) = self.get_messages_mut(thread).get_mut(&msg_key) {
1841 msg.remove_edit(&edit_key);
1842 }
1843 } else {
1844 self.unloaded_edits
1845 .get_mut(msg_event_id)
1846 .and_then(|edits| edits.remove(&edit_key));
1847 }
1848
1849 if let Some(msg) = self.messages.get_mut(&edit_key) {
1850 let ev = SyncRoomRedactionEvent::Original(ev);
1851 msg.redact(ev);
1852 }
1853 },
1854 Some(EventLocation::Poll(poll_event_id, loc)) => {
1855 let poll_event_id = poll_event_id.to_owned();
1856 let loc = loc.to_owned();
1857 if let Some(Message { event, .. }) = self.get_event_mut(&poll_event_id) {
1858 match event {
1859 MessageEvent::Poll(poll) => poll.redact(&loc),
1860 MessageEvent::UnstablePoll(poll) => poll.redact(&loc),
1861 _ => (),
1862 }
1863 } else if let Some(poll) = self.unloaded_unstable_polls.get_mut(&poll_event_id) {
1864 poll.redact(&loc);
1865 }
1866 },
1867 Some(EventLocation::Message(None, key)) => {
1868 if let Some(msg) = self.messages.get_mut(key) {
1869 let ev = SyncRoomRedactionEvent::Original(ev);
1870 msg.redact(ev);
1871 }
1872 },
1873 Some(EventLocation::Message(Some(root), key)) => {
1874 if let Some(thread) = self.threads.get_mut(root) &&
1875 let Some(msg) = thread.get_mut(key)
1876 {
1877 let ev = SyncRoomRedactionEvent::Original(ev);
1878 msg.redact(ev);
1879 }
1880 },
1881 Some(EventLocation::Reaction(event_id)) => {
1882 if let Some(reactions) = self.reactions.get_mut(event_id) {
1883 reactions.remove(redacts);
1884 }
1885
1886 self.keys.remove(redacts);
1887 },
1888 }
1889 }
1890
1891 /// Insert a message with a [`EventLocation::Message`].
1892 fn insert_msglike(
1893 &mut self,
1894 event_id: OwnedEventId,
1895 thread_root: Option<OwnedEventId>,
1896 message: Message,
1897 thread_summary: ThreadSummaryStatus,
1898 ) {
1899 let sender = message.sender.clone();
1900
1901 if let ThreadSummaryStatus::Some(thread_summary) = thread_summary {
1902 let thread = self
1903 .threads
1904 .entry(event_id.clone())
1905 .or_insert_with(|| Thread::new(event_id.clone()));
1906
1907 thread.root = Some(message.clone());
1908 thread.summary = Some(thread_summary);
1909 }
1910
1911 let key = MessageKey { ts: message.timestamp, id: event_id.clone().into() };
1912 let loc = EventLocation::Message(thread_root.clone(), key.clone());
1913 self.keys.insert(event_id.clone(), loc);
1914
1915 let thread = self.get_messages_mut(thread_root);
1916 thread.insert_message(key, message);
1917 self.set_implicit_receipt(sender, event_id);
1918 }
1919
1920 /// Insert a message with a [`EventLocation::Message`] and previews.
1921 fn insert_msglike_with_preview(
1922 &mut self,
1923 event_id: OwnedEventId,
1924 thread_root: Option<OwnedEventId>,
1925 message: Message,
1926 thread_summary: ThreadSummaryStatus,
1927 settings: &ApplicationSettings,
1928 previews: &mut PreviewManager,
1929 ) {
1930 if settings.tunables.image_preview.enabled {
1931 for (source, kind) in message.image_previews() {
1932 previews.register_preview(settings, source, kind);
1933 }
1934 }
1935
1936 self.insert_msglike(event_id, thread_root, message, thread_summary);
1937 }
1938
1939 /// Insert a reaction to a message.
1940 fn insert_reaction(&mut self, react: ReactionEvent, source: Option<MediaSource>) {
1941 let MessageLikeEvent::Original(react) = react else {
1942 return;
1943 };
1944 let rel_id = react.content.relates_to.event_id;
1945 let key = react.content.relates_to.key;
1946
1947 let message = self.reactions.entry(rel_id.clone()).or_default();
1948 let event_id = react.event_id;
1949 let user_id = react.sender;
1950
1951 message.insert(event_id.clone(), (key, user_id, source));
1952
1953 let loc = EventLocation::Reaction(rel_id);
1954 self.keys.insert(event_id, loc);
1955 }
1956
1957 /// Insert a sticker
1958 pub fn insert_sticker(
1959 &mut self,
1960 sticker: StickerEvent,
1961 thread_summary: ThreadSummaryStatus,
1962 settings: &ApplicationSettings,
1963 previews: &mut PreviewManager,
1964 ) {
1965 let event_id = sticker.event_id().to_owned();
1966 let thread_root = match &sticker {
1967 MessageLikeEvent::Original(OriginalMessageLikeEvent {
1968 content:
1969 StickerEventContent {
1970 relates_to: Some(Relation::Thread(ThreadRelation { event_id, .. })),
1971 ..
1972 },
1973 ..
1974 }) => Some(event_id.to_owned()),
1975 _ => None,
1976 };
1977
1978 self.insert_msglike_with_preview(
1979 event_id,
1980 thread_root,
1981 sticker.into(),
1982 thread_summary,
1983 settings,
1984 previews,
1985 );
1986 }
1987
1988 /// Insert a reaction to a message.
1989 pub fn insert_reaction_with_preview(
1990 &mut self,
1991 react: ReactionEvent,
1992 settings: &ApplicationSettings,
1993 previews: &mut PreviewManager,
1994 ) {
1995 let MessageLikeEvent::Original(ref orig_react) = react else {
1996 return;
1997 };
1998 let image_uri = OwnedMxcUri::from(orig_react.content.relates_to.key.as_str());
1999 let source = if image_uri.is_valid() && settings.tunables.image_preview.enabled {
2000 Some(MediaSource::Plain(image_uri))
2001 } else {
2002 None
2003 };
2004
2005 if settings.tunables.image_preview.enabled &&
2006 let Some(source) = source.as_ref()
2007 {
2008 previews.register_preview(settings, source, PreviewKind::Emoji);
2009 }
2010
2011 self.insert_reaction(react, source);
2012 }
2013
2014 /// Insert the start of a poll.
2015 pub fn insert_poll_start(
2016 &mut self,
2017 poll: PollStartEvent,
2018 own_user_id: &UserId,
2019 thread_summary: ThreadSummaryStatus,
2020 ) {
2021 let event_id = poll.event_id().to_owned();
2022 let key = MessageKey {
2023 ts: poll.origin_server_ts().into(),
2024 id: event_id.clone().into(),
2025 };
2026
2027 match poll {
2028 MessageLikeEvent::Original(ev) => {
2029 if let Some(Relation::Replacement(Replacement {
2030 event_id: poll_event_id,
2031 new_content,
2032 ..
2033 })) = ev.content.relates_to
2034 {
2035 let loc = EventLocation::Poll(
2036 poll_event_id.to_owned(),
2037 PollEventLocation::Replacement(key.clone()),
2038 );
2039 self.keys.insert(event_id.clone(), loc);
2040
2041 if let Some(msg) = self.get_event_mut(&poll_event_id) {
2042 let MessageEvent::Poll(poll) = &mut msg.event else {
2043 tracing::warn!("encountered poll replacement for non-poll message");
2044 return;
2045 };
2046
2047 poll.replacements.insert(key, new_content);
2048 } else {
2049 self.unloaded_polls
2050 .entry(poll_event_id)
2051 .or_default()
2052 .replacements
2053 .insert(key, new_content);
2054 }
2055 } else {
2056 let thread_root = match &ev.content.relates_to {
2057 Some(Relation::Thread(ThreadRelation { event_id, .. })) => {
2058 Some(event_id.to_owned())
2059 },
2060 _ => None,
2061 };
2062
2063 let unloaded = self.unloaded_polls.remove(&ev.event_id).unwrap_or_default();
2064 let msg = MessageEvent::Poll(
2065 Poll::new(ev.event_id, own_user_id.to_owned(), ev.content, unloaded).into(),
2066 );
2067 let msg = Message::new(msg, ev.sender, ev.origin_server_ts.into());
2068
2069 self.insert_msglike(event_id, thread_root, msg, thread_summary);
2070 }
2071 },
2072 MessageLikeEvent::Redacted(ev) => {
2073 let message: Message = ev.into();
2074
2075 self.insert_msglike(event_id, None, message, thread_summary);
2076 },
2077 }
2078 }
2079
2080 /// Insert the start of a poll.
2081 pub fn insert_unstable_poll_start(
2082 &mut self,
2083 poll: UnstablePollStartEvent,
2084 own_user_id: &UserId,
2085 thread_summary: ThreadSummaryStatus,
2086 ) {
2087 let event_id = poll.event_id().to_owned();
2088 let key = MessageKey {
2089 ts: poll.origin_server_ts().into(),
2090 id: event_id.clone().into(),
2091 };
2092
2093 match poll {
2094 MessageLikeEvent::Original(ev) => {
2095 match ev.content {
2096 UnstablePollStartEventContent::New(content) => {
2097 let thread_root = match &content.relates_to {
2098 Some(RelationWithoutReplacement::Thread(ThreadRelation {
2099 event_id,
2100 ..
2101 })) => Some(event_id.to_owned()),
2102 _ => None,
2103 };
2104
2105 let unloaded =
2106 self.unloaded_unstable_polls.remove(&ev.event_id).unwrap_or_default();
2107 let msg = MessageEvent::UnstablePoll(
2108 UnstablePoll::new(
2109 ev.event_id,
2110 own_user_id.to_owned(),
2111 content,
2112 unloaded,
2113 )
2114 .into(),
2115 );
2116 let msg = Message::new(msg, ev.sender, ev.origin_server_ts.into());
2117
2118 self.insert_msglike(event_id, thread_root, msg, thread_summary);
2119 },
2120 UnstablePollStartEventContent::Replacement(content) => {
2121 let loc = EventLocation::Poll(
2122 content.relates_to.event_id.to_owned(),
2123 PollEventLocation::Replacement(key.clone()),
2124 );
2125 self.keys.insert(event_id.clone(), loc);
2126
2127 if let Some(msg) = self.get_event_mut(&content.relates_to.event_id) {
2128 let MessageEvent::UnstablePoll(poll) = &mut msg.event else {
2129 tracing::warn!("encountered poll replacement for non-poll message");
2130 return;
2131 };
2132
2133 poll.replacements.insert(key, content);
2134 } else {
2135 self.unloaded_unstable_polls
2136 .entry(content.relates_to.event_id.to_owned())
2137 .or_default()
2138 .replacements
2139 .insert(key, content);
2140 }
2141 },
2142 _ => {
2143 tracing::warn!("ignoring unknown unstable poll variant");
2144 },
2145 }
2146 },
2147 MessageLikeEvent::Redacted(ev) => {
2148 let message: Message = ev.into();
2149
2150 self.insert_msglike(event_id, None, message, thread_summary);
2151 },
2152 }
2153 }
2154
2155 /// Insert an event that relates to a poll
2156 pub fn insert_poll_relation(&mut self, relation: PollRelation) {
2157 let event_id = relation.event_id().to_owned();
2158 let poll_event_id = relation.poll_event_id().to_owned();
2159
2160 let loc = if let Some(msg) = self.get_event_mut(&poll_event_id) {
2161 let MessageEvent::Poll(poll) = &mut msg.event else {
2162 tracing::warn!("encountered poll replacement for non-poll message");
2163 return;
2164 };
2165
2166 poll.insert_relation(relation)
2167 } else {
2168 self.unloaded_polls
2169 .entry(poll_event_id.to_owned())
2170 .or_default()
2171 .insert_relation(relation)
2172 };
2173
2174 self.keys.insert(event_id, EventLocation::Poll(poll_event_id, loc));
2175 }
2176
2177 /// Insert an event that relates to a poll
2178 pub fn insert_unstable_poll_relation(&mut self, relation: UnstablePollRelation) {
2179 let event_id = relation.event_id().to_owned();
2180 let poll_event_id = relation.poll_event_id().to_owned();
2181
2182 let loc = if let Some(msg) = self.get_event_mut(&poll_event_id) {
2183 let MessageEvent::UnstablePoll(poll) = &mut msg.event else {
2184 tracing::warn!("encountered poll replacement for non-poll message");
2185 return;
2186 };
2187
2188 poll.insert_relation(relation)
2189 } else {
2190 self.unloaded_unstable_polls
2191 .entry(poll_event_id.to_owned())
2192 .or_default()
2193 .insert_relation(relation)
2194 };
2195
2196 self.keys.insert(event_id, EventLocation::Poll(poll_event_id, loc));
2197 }
2198
2199 /// Insert an edit.
2200 fn insert_edit(
2201 &mut self,
2202 edit_msg: RoomMessageEvent,
2203 replacement: Replacement<RoomMessageEventContentWithoutRelation>,
2204 settings: &ApplicationSettings,
2205 previews: &mut PreviewManager,
2206 ) {
2207 let RoomMessageEvent::Original(edit_msg) = edit_msg else {
2208 return;
2209 };
2210 let edit_key = MessageKey {
2211 ts: edit_msg.origin_server_ts.into(),
2212 id: edit_msg.event_id.clone().into(),
2213 };
2214 let msg_loc = self.keys.get(&replacement.event_id).cloned();
2215
2216 if let Some(EventLocation::Message(thread, key)) = msg_loc {
2217 // The edited message is already loaded in cache
2218 let Some(msg) = self.get_messages_mut(thread).get_mut(&key) else {
2219 return;
2220 };
2221 msg.insert_edit(edit_key.clone(), replacement.new_content);
2222
2223 if settings.tunables.image_preview.enabled {
2224 for (source, kind) in msg.image_previews() {
2225 previews.register_preview(settings, source, kind);
2226 }
2227 }
2228 } else {
2229 // The edited message is not yet loaded
2230 let entry = self.unloaded_edits.entry(replacement.event_id.clone());
2231 entry.or_default().insert(edit_key.clone(), replacement.new_content);
2232 }
2233
2234 let loc = EventLocation::Edit(replacement.event_id.clone(), edit_key.clone());
2235 self.keys.insert(edit_msg.event_id.clone(), loc);
2236 }
2237
2238 pub fn insert_any_state(&mut self, msg: AnySyncStateEvent) {
2239 let event_id = msg.event_id().to_owned();
2240
2241 self.insert_msglike(event_id, None, msg.into(), ThreadSummaryStatus::None);
2242 }
2243
2244 /// Inserts events that couldn't be decrypted into the scrollback.
2245 pub fn insert_encrypted(
2246 &mut self,
2247 msg: RoomEncryptedEvent,
2248 thread_summary: ThreadSummaryStatus,
2249 ) {
2250 let event_id = msg.event_id().to_owned();
2251
2252 let thread_root =
2253 if let Some(EncryptedRelation::Thread(ThreadRelation { event_id, .. })) =
2254 msg.as_original().and_then(|ev| ev.content.relates_to.as_ref())
2255 {
2256 Some(event_id.to_owned())
2257 } else {
2258 None
2259 };
2260
2261 self.insert_msglike(event_id, thread_root, msg.into(), thread_summary);
2262 }
2263
2264 /// Insert a new message event, and prepare for image-preview if it has an image attachment.
2265 pub fn insert_message(
2266 &mut self,
2267 ev: RoomMessageEvent,
2268 thread_summary: ThreadSummaryStatus,
2269 settings: &ApplicationSettings,
2270 previews: &mut PreviewManager,
2271 ) {
2272 let event_id = ev.event_id().to_owned();
2273 let thread_root = match ev.as_original().and_then(|ev| ev.content.relates_to.as_ref()) {
2274 Some(Relation::Replacement(repl)) => {
2275 let repl = repl.to_owned();
2276 self.insert_edit(ev, repl, settings, previews);
2277 return;
2278 },
2279 Some(Relation::Thread(ThreadRelation { event_id, .. })) => Some(event_id.to_owned()),
2280 _ => None,
2281 };
2282 let mut message: Message = ev.into();
2283 if let Some(edits) = self.unloaded_edits.remove(&event_id) {
2284 message.set_edits(edits);
2285 }
2286 self.insert_msglike_with_preview(
2287 event_id,
2288 thread_root,
2289 message,
2290 thread_summary,
2291 settings,
2292 previews,
2293 );
2294 }
2295
2296 /// Indicates whether this room has unread messages.
2297 pub fn unreads(&self, room: &matrix_sdk::Room) -> UnreadInfo {
2298 let last_message = self
2299 .messages
2300 .iter()
2301 .rev()
2302 .find(|(_, msg)| !matches!(&msg.event, MessageEvent::State(..)));
2303
2304 UnreadInfo {
2305 unread_mark: room.is_marked_unread(),
2306 unread_messages: room.num_unread_messages(),
2307 unread_notifications: room.num_unread_notifications(),
2308 unread_mentions: room.num_unread_mentions(),
2309 latest: last_message.map(|(key, _)| key.ts.to_owned()),
2310 }
2311 }
2312
2313 /// Indicates whether we've recently fetched scrollback for this room.
2314 pub fn recently_fetched(&self) -> bool {
2315 self.fetch_last.is_some_and(|i| i.elapsed() < ROOM_FETCH_DEBOUNCE)
2316 }
2317
2318 fn clear_receipt(&mut self, thread: &ReceiptThread, user_id: &OwnedUserId) -> Option<()> {
2319 let old_user_receipts = self.user_receipts_mut(thread);
2320 let old_event_id = old_user_receipts.and_then(|rs| rs.remove(user_id))?;
2321 let old_thread = self.event_receipts_mut(thread)?;
2322 let old_receipts = old_thread.get_mut(&old_event_id)?;
2323 old_receipts.remove(user_id);
2324
2325 if old_receipts.is_empty() {
2326 old_thread.remove(&old_event_id);
2327 }
2328
2329 None
2330 }
2331
2332 pub fn set_receipt(
2333 &mut self,
2334 thread: ReceiptThread,
2335 user_id: OwnedUserId,
2336 event_id: OwnedEventId,
2337 ) {
2338 if let Some(old_event_id) =
2339 self.user_receipts(&thread).and_then(|receipts| receipts.get(&user_id)) &&
2340 let (Some(old_key), Some(new_key)) =
2341 (self.receipt_key(old_event_id), self.receipt_key(&event_id)) &&
2342 new_key <= old_key
2343 {
2344 return;
2345 }
2346
2347 self.clear_receipt(&thread, &user_id);
2348 self.event_receipts_or_default(thread.clone())
2349 .entry(event_id.to_owned())
2350 .or_default()
2351 .insert(user_id.clone());
2352 self.user_receipts_or_default(thread).insert(user_id, event_id);
2353 }
2354
2355 fn receipt_key(&self, event_id: &EventId) -> Option<&MessageKey> {
2356 match self.keys.get(event_id)? {
2357 EventLocation::Message(_, key) => Some(key),
2358 _ => None,
2359 }
2360 }
2361
2362 /// Whenever a user sends a message, we can consider that an effective update to their
2363 /// read receipt, even when their client isn't sending them to the room.
2364 ///
2365 /// While the Matrix specification doesn't explicitly mention "implicit receipts", this
2366 /// is effectively what is described by "Marking notifications as read",
2367 ///
2368 /// > When the user updates their read receipt (either by using the API or by sending an
2369 /// > event), notifications prior to and including that event MUST be marked as read.
2370 ///
2371 /// This method is called every time we insert a new message into the [RoomInfo], so that
2372 /// we show in the timeline that the user has now read up to the point where they sent
2373 /// a message.
2374 fn set_implicit_receipt(&mut self, user_id: OwnedUserId, event_id: OwnedEventId) {
2375 let Some(thread) = self.get_receipt_thread(&event_id) else {
2376 return;
2377 };
2378
2379 let current = self.user_receipts(&thread).and_then(|receipts| receipts.get(&user_id));
2380 let current_key = current.and_then(|event_id| self.receipt_key(event_id));
2381
2382 if current.is_some() && current_key.is_none() {
2383 // Do not set an implicit receipt if we have an explicit receipt that points
2384 // at an event whose information we don't have, since we need it to make sure
2385 // that we don't move the receipt backwards in the timeline.
2386 //
2387 // This event could technically be newer than the one the receipt currently
2388 // points at, but we can't be sure, so just trust what the user's receipt in
2389 // the room says to point at, and we'll update it once they send us a new one.
2390 //
2391 // This technically makes it possible for a user who previously sent room
2392 // receipts and then switched to just private receipts to not have their marker
2393 // moved with recent messages, but solving that would require us to force a
2394 // load of the event that every user's read marker points at.
2395 return;
2396 }
2397
2398 // If the user's client isn't thread-aware then make sure the implicit receipt
2399 // doesn't result in displaying a second read receipt after where their unthreaded
2400 // receipt is currently pointing at:
2401 self.clear_receipt(&ReceiptThread::Unthreaded, &user_id);
2402
2403 self.set_receipt(thread, user_id, event_id);
2404 }
2405
2406 /// This is called whenever the user has viewed the most recent message sent to a room or
2407 /// thread, so that we can update the read receipt on the homeserver.
2408 ///
2409 /// Note that the Matrix specification says:
2410 ///
2411 /// > Clients should send read receipts when there is some certainty that the event in
2412 /// > question has been displayed to the user. Simply receiving an event does not provide
2413 /// > enough certainty that the user has seen the event. The user SHOULD need to take some
2414 /// > action such as viewing the room that the event was sent to or dismissing a notification
2415 /// > in order for the event to count as “read”. Clients SHOULD NOT send read receipts for
2416 /// > events sent by their own user.
2417 pub fn fully_read(
2418 &mut self,
2419 room_id: OwnedRoomId,
2420 thread: ReceiptThread,
2421 worker: &Requester,
2422 settings: &ApplicationSettings,
2423 open_notifications: &mut HashMap<OwnedRoomId, Vec<NotificationHandle>>,
2424 ) {
2425 let user_id = &settings.user_id;
2426
2427 let messages = match &thread {
2428 ReceiptThread::Main => self.get_messages(None),
2429 ReceiptThread::Thread(root) => self.get_messages(Some(root)),
2430 _ => None,
2431 };
2432
2433 let Some(messages) = messages else {
2434 return;
2435 };
2436
2437 let event_id = messages
2438 .iter()
2439 .filter(|(_, msg)| {
2440 // Handle the "do not send read receipts for our own events" part of the
2441 // specification quoted above.
2442 msg.sender != *user_id
2443 })
2444 .flat_map(|(_, msg)| msg.event.event_id())
2445 .next_back()
2446 .map(ToOwned::to_owned);
2447
2448 if let Some((_, msg)) = messages.last_key_value() &&
2449 let Some(event_id) = msg.event.event_id()
2450 {
2451 // Always update the local receipt info for this room so that we aren't reliant
2452 // on the homeserver echoing it back to us to update this and clear the trackbar:
2453 self.set_receipt(thread.clone(), user_id.clone(), event_id.to_owned());
2454 }
2455
2456 if let Some(event_id) = event_id {
2457 // Clear any desktop notifications for the room:
2458 open_notifications.remove(&room_id);
2459
2460 // Update the homeserver with the latest receipt:
2461 worker.send_receipt(room_id, thread, event_id, settings);
2462 }
2463 }
2464
2465 pub fn fully_read_all(
2466 &mut self,
2467 room_id: OwnedRoomId,
2468 worker: &Requester,
2469 settings: &ApplicationSettings,
2470 open_notifications: &mut HashMap<OwnedRoomId, Vec<NotificationHandle>>,
2471 ) {
2472 let threads: Vec<_> = self.threads.keys().map(|root| root.to_owned()).collect();
2473
2474 for thread in threads {
2475 self.fully_read(
2476 room_id.to_owned(),
2477 ReceiptThread::Thread(thread),
2478 worker,
2479 settings,
2480 open_notifications,
2481 );
2482 }
2483
2484 self.fully_read(room_id, ReceiptThread::Main, worker, settings, open_notifications);
2485 }
2486
2487 pub fn read_event_users<'a>(
2488 &'a self,
2489 thread: ReceiptThread,
2490 event_id: &'a EventId,
2491 ) -> impl Iterator<Item = &'a OwnedUserId> + 'a {
2492 self.event_receipts(&thread)
2493 .and_then(|rs| rs.get(event_id))
2494 .map(|read| read.iter())
2495 .unwrap_or_default()
2496 }
2497
2498 fn get_typers(&self) -> &[OwnedUserId] {
2499 if let Some((t, users)) = &self.users_typing {
2500 if t.elapsed() < Duration::from_secs(4) {
2501 return users.as_ref();
2502 } else {
2503 return &[];
2504 }
2505 } else {
2506 return &[];
2507 }
2508 }
2509
2510 fn get_typing_spans<'a>(&'a self, settings: &'a ApplicationSettings) -> Line<'a> {
2511 let typers = self.get_typers();
2512 let n = typers.len();
2513
2514 match n {
2515 0 => Line::from(vec![]),
2516 1 => {
2517 let user =
2518 settings.get_user_span(typers[0].as_ref(), self.display_names.get(&typers[0]));
2519
2520 Line::from(vec![user, Span::from(" is typing...")])
2521 },
2522 2 => {
2523 let user1 =
2524 settings.get_user_span(typers[0].as_ref(), self.display_names.get(&typers[0]));
2525 let user2 =
2526 settings.get_user_span(typers[1].as_ref(), self.display_names.get(&typers[1]));
2527
2528 Line::from(vec![
2529 user1,
2530 Span::raw(" and "),
2531 user2,
2532 Span::from(" are typing..."),
2533 ])
2534 },
2535 n if n < 5 => Line::from("Several people are typing..."),
2536 _ => Line::from("Many people are typing..."),
2537 }
2538 }
2539
2540 /// Update typing information for this room.
2541 pub fn set_typing(&mut self, user_ids: Vec<OwnedUserId>) {
2542 self.users_typing = (Instant::now(), user_ids).into();
2543 }
2544
2545 /// Create a [Rect] that displays what users are typing.
2546 pub fn render_typing(
2547 &mut self,
2548 area: Rect,
2549 buf: &mut Buffer,
2550 settings: &ApplicationSettings,
2551 ) -> Rect {
2552 if area.height <= 2 || area.width <= 20 {
2553 return area;
2554 }
2555
2556 if !settings.tunables.typing_notice_display {
2557 // still keep one line blank, so `render_jump_to_recent` doesn't immediately hide the
2558 // last line in scrollback
2559 return Rect::new(area.x, area.y, area.width, area.height - 1);
2560 }
2561
2562 let top = Rect::new(area.x, area.y, area.width, area.height - 1);
2563 let bar = Rect::new(area.x, area.y + top.height, area.width, 1);
2564
2565 Paragraph::new(self.get_typing_spans(settings))
2566 .alignment(Alignment::Center)
2567 .render(bar, buf);
2568
2569 return top;
2570 }
2571
2572 /// Checks if a given user has reacted with the given emoji on the given event
2573 pub fn user_reactions_contains(
2574 &self,
2575 user_id: &UserId,
2576 event_id: &EventId,
2577 emoji: &str,
2578 ) -> bool {
2579 if let Some(reactions) = self.reactions.get(event_id) {
2580 reactions
2581 .values()
2582 .any(|(annotation, user, _)| annotation == emoji && user == user_id)
2583 } else {
2584 false
2585 }
2586 }
2587}
2588
2589/// Generate a [CompletionMap] for Emoji shortcodes.
2590fn emoji_map() -> CompletionMap<String, &'static Emoji> {
2591 let mut emojis = CompletionMap::default();
2592
2593 for emoji in emojis::iter() {
2594 for shortcode in emoji.shortcodes() {
2595 emojis.insert(shortcode.to_string(), emoji);
2596 }
2597 }
2598
2599 return emojis;
2600}
2601
2602/// Information about spaces the user's joined.
2603#[derive(Default)]
2604pub struct SpaceInfo {
2605 /// The space child events with content and `origin_server_ts`.
2606 pub children: HashMap<OwnedRoomId, (SpaceChildEventContent, MilliSecondsSinceUnixEpoch)>,
2607}
2608
2609/// Information gathered during server syncs about joined rooms.
2610#[derive(Default)]
2611pub struct SyncInfo {
2612 /// Spaces that the user is a member of.
2613 pub spaces: Vec<MatrixRoom>,
2614
2615 /// Rooms that the user is a member of.
2616 pub rooms: Vec<MatrixRoom>,
2617
2618 /// DMs that the user is a member of.
2619 pub dms: Vec<MatrixRoom>,
2620}
2621
2622impl SyncInfo {
2623 pub fn rooms(&self) -> impl Iterator<Item = &RoomId> {
2624 self.rooms.iter().map(|r| r.room_id())
2625 }
2626
2627 pub fn dms(&self) -> impl Iterator<Item = &RoomId> {
2628 self.dms.iter().map(|r| r.room_id())
2629 }
2630
2631 pub fn chats(&self) -> impl Iterator<Item = &RoomId> {
2632 self.rooms().chain(self.dms())
2633 }
2634}
2635
2636static MESSAGE_NEED_TTL: u8 = 30;
2637
2638/// How many failed fetches of a pinned event before the `:pinned` window stops retrying.
2639const PINNED_FETCH_ATTEMPTS: u8 = 10;
2640
2641#[derive(Debug, PartialEq)]
2642/// Load messages until the event is loaded or `ttl` loads are exceeded
2643pub struct MessageNeed {
2644 pub event_id: OwnedEventId,
2645 pub ttl: u8,
2646}
2647
2648#[derive(Default, Debug, PartialEq)]
2649pub struct Need {
2650 pub members: bool,
2651 pub pinned: bool,
2652 pub messages: Option<Vec<MessageNeed>>,
2653}
2654
2655/// Things that need loading for different rooms.
2656#[derive(Default, Debug)]
2657pub struct RoomNeeds {
2658 needs: HashMap<OwnedRoomId, Need>,
2659 previews: HashSet<OwnedRoomOrAliasId>,
2660 notify: Arc<Notify>,
2661}
2662
2663impl RoomNeeds {
2664 /// Mark a room for needing to load members.
2665 pub fn need_members(&mut self, room_id: OwnedRoomId) {
2666 self.needs.entry(room_id).or_default().members = true;
2667 self.notify.notify_waiters();
2668 }
2669
2670 /// Mark a room for needing to fetch its pinned events.
2671 pub fn need_pinned(&mut self, room_id: OwnedRoomId) {
2672 self.needs.entry(room_id).or_default().pinned = true;
2673 self.notify.notify_waiters();
2674 }
2675
2676 /// Mark a room for needing to load messages.
2677 pub fn need_messages(&mut self, room_id: OwnedRoomId) {
2678 self.needs.entry(room_id).or_default().messages.get_or_insert_default();
2679 self.notify.notify_waiters();
2680 }
2681
2682 /// Mark a room for needing to load messages until the given message is loaded or a retry limit
2683 /// is exceeded.
2684 pub fn need_message(&mut self, room_id: OwnedRoomId, event_id: OwnedEventId) {
2685 let messages = &mut self.needs.entry(room_id).or_default().messages.get_or_insert_default();
2686
2687 messages.push(MessageNeed { event_id, ttl: MESSAGE_NEED_TTL });
2688 self.notify.notify_waiters();
2689 }
2690
2691 pub fn need_messages_all(&mut self, room_id: OwnedRoomId, message_needs: Vec<MessageNeed>) {
2692 self.needs
2693 .entry(room_id)
2694 .or_default()
2695 .messages
2696 .get_or_insert_default()
2697 .extend(message_needs);
2698 self.notify.notify_waiters();
2699 }
2700
2701 /// Request the load of a room preview.
2702 pub fn need_preview(&mut self, room: OwnedRoomOrAliasId) {
2703 self.previews.insert(room);
2704 self.notify.notify_waiters();
2705 }
2706
2707 /// Return all requested room previews
2708 pub fn preview_needs(&mut self) -> impl Iterator<Item = OwnedRoomOrAliasId> + use<> {
2709 std::mem::take(&mut self.previews).into_iter()
2710 }
2711
2712 /// Return all requested rooms
2713 pub fn room_needs(&mut self) -> impl Iterator<Item = (OwnedRoomId, Need)> + use<> {
2714 std::mem::take(&mut self.needs).into_iter()
2715 }
2716
2717 pub fn rooms(&self) -> usize {
2718 self.needs.len()
2719 }
2720
2721 /// The returned [`Notify`] instance will be notified with [`Notify::notify_waiters`] for every
2722 /// inserted [`Need`].
2723 pub fn notifier(&self) -> Arc<Notify> {
2724 Arc::clone(&self.notify)
2725 }
2726}
2727
2728/// The main application state.
2729pub struct ChatStore {
2730 /// `:`-commands
2731 pub cmds: ProgramCommands,
2732
2733 /// Handle for communicating w/ the worker thread.
2734 pub worker: Requester,
2735
2736 /// Map of joined rooms.
2737 pub rooms: CompletionMap<OwnedRoomId, RoomInfo>,
2738
2739 /// Map of loaded room previews with their fetch time
2740 pub room_previews:
2741 HashMap<OwnedRoomOrAliasId, (Result<RoomPreview, matrix_sdk::Error>, Instant)>,
2742
2743 /// Cache of encountered `via` parameters in room links.
2744 ///
2745 /// This is stored here because this data is lost in the conversion to [IambId].
2746 pub room_via: HashMap<OwnedRoomOrAliasId, HashSet<OwnedServerName>>,
2747
2748 /// Map of joined spaces.
2749 pub spaces: HashMap<OwnedRoomId, SpaceInfo>,
2750
2751 /// Map of room aliases.
2752 pub aliases: CompletionMap<OwnedRoomAliasId, OwnedRoomId>,
2753
2754 /// Presence information for other users.
2755 pub presences: CompletionMap<OwnedUserId, PresenceState>,
2756
2757 /// In-progress and completed verifications.
2758 /// The map key is the `flow_id`.
2759 pub verifications: CompletionMap<String, VerificationRequest>,
2760
2761 /// Settings for the current profile loaded from config file.
2762 pub settings: ApplicationSettings,
2763
2764 /// Set of rooms that need more messages loaded in their scrollback.
2765 pub need_load: RoomNeeds,
2766
2767 /// [CompletionMap] of Emoji shortcodes.
2768 pub emojis: CompletionMap<String, &'static Emoji>,
2769
2770 /// Information gathered by the background thread.
2771 pub sync_info: SyncInfo,
2772
2773 /// Rendered image previews.
2774 pub previews: PreviewManager,
2775
2776 /// Last draw time, used to match with RoomInfo's draw_last.
2777 pub draw_curr: Option<Instant>,
2778
2779 /// Whether to ring the terminal bell on the next redraw.
2780 pub ring_bell: bool,
2781
2782 /// An error raised while drawing, shown in the message bar on the next redraw.
2783 pub draw_error: Option<String>,
2784
2785 /// Whether the application is currently focused
2786 pub focused: bool,
2787
2788 /// Collator for locale-aware text sorting.
2789 pub collator: feruca::Collator,
2790
2791 /// Notifications that should be dismissed when the user opens the room.
2792 pub open_notifications: HashMap<OwnedRoomId, Vec<NotificationHandle>>,
2793}
2794
2795impl ChatStore {
2796 /// Create a new [ChatStore].
2797 pub fn new(worker: Requester, settings: ApplicationSettings) -> IambResult<Self> {
2798 let previews = PreviewManager::new(&settings);
2799 let cmds = crate::commands::setup_commands(&settings.aliases)?;
2800
2801 let store = ChatStore {
2802 worker,
2803 settings,
2804 previews,
2805 cmds,
2806 emojis: emoji_map(),
2807
2808 collator: Default::default(),
2809 aliases: Default::default(),
2810 rooms: Default::default(),
2811 room_previews: Default::default(),
2812 room_via: Default::default(),
2813 spaces: Default::default(),
2814 presences: Default::default(),
2815 verifications: Default::default(),
2816 need_load: Default::default(),
2817 sync_info: Default::default(),
2818 draw_curr: None,
2819 ring_bell: false,
2820 draw_error: None,
2821 focused: true,
2822 open_notifications: Default::default(),
2823 };
2824
2825 Ok(store)
2826 }
2827
2828 /// Clear the `EventCache` for all rooms.
2829 ///
2830 /// This forces a re-fetch of the most recent messages in joined rooms afterwards,
2831 /// which makes sure that we re-fetch any missing events (such as those sent by
2832 /// recently unignored users that a re-fetch would make appear in the timeline).
2833 pub async fn clear_room_cache(&mut self, client: &Client) -> Result<(), IambError> {
2834 client.event_cache().clear_all_rooms().await?;
2835 for room in client.joined_rooms() {
2836 let room_id = room.room_id().to_owned();
2837 let room = self.rooms.get_or_default(room_id.clone());
2838 room.reached_timeline_start = false;
2839 self.need_load.need_messages(room_id.to_owned());
2840 }
2841 Ok(())
2842 }
2843
2844 /// Get a joined room.
2845 pub fn get_joined_room(&self, room_id: &RoomId) -> Option<MatrixRoom> {
2846 let room = self.worker.client.get_room(room_id)?;
2847
2848 if room.state() == MatrixRoomState::Joined {
2849 Some(room)
2850 } else {
2851 None
2852 }
2853 }
2854
2855 /// Get the alias for a room if it has one (and the client knows it).
2856 pub fn get_joined_room_alias(&self, room_id: &RoomId) -> Option<OwnedRoomAliasId> {
2857 self.worker.client.get_room(room_id).and_then(|r| r.canonical_alias())
2858 }
2859
2860 /// Get the title for a room.
2861 pub fn get_room_title(&self, room_id: &RoomId) -> String {
2862 self.rooms
2863 .get(room_id)
2864 .and_then(|i| i.name.as_ref())
2865 .map(String::from)
2866 .unwrap_or_else(|| "Untitled Matrix Room".to_string())
2867 }
2868
2869 /// Get the [RoomInfo] for a given room identifier.
2870 pub fn get_room_info(&mut self, room_id: OwnedRoomId) -> &mut RoomInfo {
2871 self.rooms.get_or_default(room_id)
2872 }
2873
2874 /// Set the name and tags for a room.
2875 pub fn set_room_info(
2876 &mut self,
2877 room_id: OwnedRoomId,
2878 name: String,
2879 tags: Option<Tags>,
2880 aliases: Vec<OwnedRoomAliasId>,
2881 flags: RoomInfoFlags,
2882 ) {
2883 for alias in aliases {
2884 self.aliases.insert(alias, room_id.clone());
2885 }
2886
2887 let info = self.rooms.get_or_default(room_id);
2888 info.name = name.into();
2889 info.flags = flags;
2890 info.tags = tags;
2891 }
2892}
2893
2894impl ApplicationStore for ChatStore {}
2895
2896#[derive(Clone, Debug, Eq, Hash, PartialEq)]
2897pub enum RoomView {
2898 /// The main timeline is shown.
2899 Main,
2900 /// A thread is shown.
2901 Thread(OwnedEventId),
2902 /// A single message is shown.
2903 Message(MessageId),
2904}
2905
2906impl From<Option<OwnedEventId>> for RoomView {
2907 fn from(thread: Option<OwnedEventId>) -> Self {
2908 match thread {
2909 Some(thread) => Self::Thread(thread),
2910 None => Self::Main,
2911 }
2912 }
2913}
2914
2915impl From<Option<&OwnedEventId>> for RoomView {
2916 fn from(thread: Option<&OwnedEventId>) -> Self {
2917 match thread {
2918 Some(thread) => Self::Thread(thread.to_owned()),
2919 None => Self::Main,
2920 }
2921 }
2922}
2923
2924/// Identified used to track window content.
2925#[derive(Clone, Debug, Eq, Hash, PartialEq)]
2926pub enum IambId {
2927 /// A Matrix room, with an item that is shown.
2928 Room(OwnedRoomOrAliasId, RoomView),
2929
2930 /// The `:dms` window.
2931 DirectList,
2932
2933 /// The `:members` window for a given Matrix room.
2934 MemberList(OwnedRoomId),
2935
2936 /// The `:pinned` window for a given Matrix room.
2937 PinnedList(OwnedRoomId),
2938
2939 /// The `:rooms` window.
2940 RoomList,
2941
2942 /// The `:spaces` window.
2943 SpaceList,
2944
2945 /// The `:spaces toplevel` window.
2946 ToplevelSpaceList,
2947
2948 /// The `:verify` window.
2949 VerifyList,
2950
2951 /// The `:welcome` window.
2952 Welcome,
2953
2954 /// The `:chats` window.
2955 ChatList,
2956
2957 /// The `:unreads` window.
2958 UnreadList,
2959
2960 /// The `:mentions` window.
2961 MentionsList,
2962
2963 /// The `:invites` window.
2964 InvitesList,
2965}
2966
2967impl Display for IambId {
2968 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2969 match self {
2970 IambId::Room(alias, RoomView::Main) => {
2971 let encoded = percent_encode(alias.as_bytes(), NON_ALPHANUMERIC);
2972 write!(f, "iamb://room/{encoded}")
2973 },
2974 IambId::Room(alias, RoomView::Thread(thread)) => {
2975 let encoded = percent_encode(alias.as_bytes(), NON_ALPHANUMERIC);
2976 write!(f, "iamb://room/{encoded}/threads/{thread}")
2977 },
2978 IambId::Room(alias, RoomView::Message(message)) => {
2979 let encoded = percent_encode(alias.as_bytes(), NON_ALPHANUMERIC);
2980 write!(f, "iamb://room/{encoded}/messages/{message}")
2981 },
2982 IambId::MemberList(room_id) => {
2983 write!(f, "iamb://members/{room_id}")
2984 },
2985 IambId::PinnedList(room_id) => {
2986 write!(f, "iamb://room/{room_id}/pinned")
2987 },
2988 IambId::DirectList => f.write_str("iamb://dms"),
2989 IambId::RoomList => f.write_str("iamb://rooms"),
2990 IambId::SpaceList => f.write_str("iamb://spaces"),
2991 IambId::ToplevelSpaceList => f.write_str("iamb://spaces/toplevel"),
2992 IambId::VerifyList => f.write_str("iamb://verify"),
2993 IambId::Welcome => f.write_str("iamb://welcome"),
2994 IambId::ChatList => f.write_str("iamb://chats"),
2995 IambId::UnreadList => f.write_str("iamb://unreads"),
2996 IambId::MentionsList => f.write_str("iamb://mentions"),
2997 IambId::InvitesList => f.write_str("iamb://invites"),
2998 }
2999 }
3000}
3001
3002impl ApplicationWindowId for IambId {}
3003
3004impl Serialize for IambId {
3005 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
3006 where
3007 S: Serializer,
3008 {
3009 serializer.serialize_str(&self.to_string())
3010 }
3011}
3012
3013impl<'de> Deserialize<'de> for IambId {
3014 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3015 where
3016 D: Deserializer<'de>,
3017 {
3018 deserializer.deserialize_str(IambIdVisitor)
3019 }
3020}
3021
3022/// [serde] visitor for deserializing [IambId].
3023struct IambIdVisitor;
3024
3025impl Visitor<'_> for IambIdVisitor {
3026 type Value = IambId;
3027
3028 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
3029 formatter.write_str("a valid window URL")
3030 }
3031
3032 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
3033 where
3034 E: SerdeError,
3035 {
3036 let Ok(url) = Url::parse(value) else {
3037 return Err(E::custom("Invalid iamb window URL"));
3038 };
3039
3040 if url.scheme() != "iamb" {
3041 return Err(E::custom("Invalid iamb window URL"));
3042 }
3043
3044 match url.domain() {
3045 Some("room") => {
3046 let Some(path) = url.path_segments() else {
3047 return Err(E::custom("Invalid members window URL"));
3048 };
3049
3050 match *path.collect::<Vec<_>>().as_slice() {
3051 [alias] => {
3052 let decoded = percent_decode(alias.as_bytes()).decode_utf8_lossy();
3053 let Ok(room_id) = OwnedRoomOrAliasId::try_from(decoded.as_ref()) else {
3054 return Err(E::custom(format!("Invalid room identifier: {decoded:?}")));
3055 };
3056
3057 Ok(IambId::Room(room_id, RoomView::Main))
3058 },
3059 [alias, "threads", thread_root] => {
3060 let decoded = percent_decode(alias.as_bytes()).decode_utf8_lossy();
3061 let Ok(room_id) = OwnedRoomOrAliasId::try_from(decoded.as_ref()) else {
3062 return Err(E::custom("Invalid room identifier: {decoded:?}"));
3063 };
3064
3065 let Ok(thread_root) = OwnedEventId::try_from(thread_root) else {
3066 return Err(E::custom("Invalid thread root identifier"));
3067 };
3068
3069 Ok(IambId::Room(room_id, RoomView::Thread(thread_root)))
3070 },
3071 [alias, "messages", message] => {
3072 let decoded = percent_decode(alias.as_bytes()).decode_utf8_lossy();
3073 let Ok(room_id) = OwnedRoomOrAliasId::try_from(decoded.as_ref()) else {
3074 return Err(E::custom("Invalid room identifier: {decoded:?}"));
3075 };
3076
3077 let message_id = OwnedEventId::try_from(message)
3078 .map(Into::into)
3079 .unwrap_or_else(|_| OwnedTransactionId::from(message).into());
3080
3081 Ok(IambId::Room(room_id, RoomView::Message(message_id)))
3082 },
3083 [room_id, "pinned"] => {
3084 let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
3085 return Err(E::custom("Invalid room identifier"));
3086 };
3087
3088 Ok(IambId::PinnedList(room_id))
3089 },
3090 _ => return Err(E::custom("Invalid iamb window URL")),
3091 }
3092 },
3093 Some("members") => {
3094 let Some(path) = url.path_segments() else {
3095 return Err(E::custom("Invalid members window URL"));
3096 };
3097
3098 let &[room_id] = path.collect::<Vec<_>>().as_slice() else {
3099 return Err(E::custom("Invalid members window URL"));
3100 };
3101
3102 let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
3103 return Err(E::custom("Invalid room identifier"));
3104 };
3105
3106 Ok(IambId::MemberList(room_id))
3107 },
3108 Some("dms") => {
3109 if url.path() != "" {
3110 return Err(E::custom("iamb://dms takes no path"));
3111 }
3112
3113 Ok(IambId::DirectList)
3114 },
3115 Some("rooms") => {
3116 if url.path() != "" {
3117 return Err(E::custom("iamb://rooms takes no path"));
3118 }
3119
3120 Ok(IambId::RoomList)
3121 },
3122 Some("spaces") => {
3123 if url.path() == "toplevel" {
3124 return Ok(IambId::ToplevelSpaceList);
3125 }
3126
3127 if url.path() != "" {
3128 return Err(E::custom("Invalid iamb window URL"));
3129 }
3130
3131 Ok(IambId::SpaceList)
3132 },
3133 Some("verify") => {
3134 if url.path() != "" {
3135 return Err(E::custom("iamb://verify takes no path"));
3136 }
3137
3138 Ok(IambId::VerifyList)
3139 },
3140 Some("welcome") => {
3141 if url.path() != "" {
3142 return Err(E::custom("iamb://welcome takes no path"));
3143 }
3144
3145 Ok(IambId::Welcome)
3146 },
3147 Some("chats") => {
3148 if url.path() != "" {
3149 return Err(E::custom("iamb://chats takes no path"));
3150 }
3151
3152 Ok(IambId::ChatList)
3153 },
3154 Some("unreads") => {
3155 if url.path() != "" {
3156 return Err(E::custom("iamb://unreads takes no path"));
3157 }
3158
3159 Ok(IambId::UnreadList)
3160 },
3161 Some("mentions") => {
3162 if url.path() != "" {
3163 return Err(E::custom("iamb://mentions takes no path"));
3164 }
3165
3166 Ok(IambId::MentionsList)
3167 },
3168 Some("invites") => {
3169 if url.path() != "" {
3170 return Err(E::custom("iamb://invites takes no path"));
3171 }
3172
3173 Ok(IambId::InvitesList)
3174 },
3175 Some(s) => Err(E::custom(format!("{s:?} is not a valid window"))),
3176 None => Err(E::custom("Invalid iamb window URL")),
3177 }
3178 }
3179}
3180
3181/// Which part of the room window's UI is focused.
3182#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
3183pub enum RoomFocus {
3184 /// The scrollback for a room window is focused.
3185 Scrollback,
3186
3187 /// The message bar for a room window is focused.
3188 MessageBar,
3189}
3190
3191impl RoomFocus {
3192 /// Whether this is [RoomFocus::Scrollback].
3193 pub fn is_scrollback(&self) -> bool {
3194 matches!(self, RoomFocus::Scrollback)
3195 }
3196
3197 /// Whether this is [RoomFocus::MessageBar].
3198 pub fn is_msgbar(&self) -> bool {
3199 matches!(self, RoomFocus::MessageBar)
3200 }
3201
3202 pub fn toggle(&mut self) {
3203 *self = match self {
3204 RoomFocus::MessageBar => RoomFocus::Scrollback,
3205 RoomFocus::Scrollback => RoomFocus::MessageBar,
3206 };
3207 }
3208}
3209
3210/// Identifiers used to track where a mark was placed.
3211///
3212/// While this is the "buffer identifier" for the mark,
3213/// not all of these are necessarily actual buffers.
3214#[derive(Clone, Debug, Eq, Hash, PartialEq)]
3215pub enum IambBufferId {
3216 /// The command bar buffer.
3217 Command(CommandType),
3218
3219 /// The message buffer or a specific message in a room.
3220 Room(OwnedRoomId, RoomView, RoomFocus),
3221
3222 /// The `:dms` window.
3223 DirectList,
3224
3225 /// The `:members` window for a room.
3226 MemberList(OwnedRoomId),
3227
3228 /// The `:pinned` window for a room.
3229 PinnedList(OwnedRoomId),
3230
3231 /// The `:rooms` window.
3232 RoomList,
3233
3234 /// The `:spaces` window.
3235 SpaceList,
3236
3237 /// The `:spaces toplevel` window.
3238 ToplevelSpaceList,
3239
3240 /// The `:verify` window.
3241 VerifyList,
3242
3243 /// The buffer for the `:rooms` window.
3244 Welcome,
3245
3246 /// The `:chats` window.
3247 ChatList,
3248
3249 /// The `:unreads` window.
3250 UnreadList,
3251
3252 /// The `:mentions` window.
3253 MentionsList,
3254
3255 /// The `:invites` window.
3256 InvitesList,
3257}
3258
3259impl IambBufferId {
3260 /// Get the identifier for the window that contains this buffer.
3261 pub fn to_window(&self) -> Option<IambId> {
3262 let id = match self {
3263 IambBufferId::Command(_) => return None,
3264 IambBufferId::Room(room, view, _) => IambId::Room(room.clone().into(), view.clone()),
3265 IambBufferId::DirectList => IambId::DirectList,
3266 IambBufferId::MemberList(room) => IambId::MemberList(room.clone()),
3267 IambBufferId::PinnedList(room) => IambId::PinnedList(room.clone()),
3268 IambBufferId::RoomList => IambId::RoomList,
3269 IambBufferId::SpaceList => IambId::SpaceList,
3270 IambBufferId::ToplevelSpaceList => IambId::ToplevelSpaceList,
3271 IambBufferId::VerifyList => IambId::VerifyList,
3272 IambBufferId::Welcome => IambId::Welcome,
3273 IambBufferId::ChatList => IambId::ChatList,
3274 IambBufferId::UnreadList => IambId::UnreadList,
3275 IambBufferId::MentionsList => IambId::MentionsList,
3276 IambBufferId::InvitesList => IambId::InvitesList,
3277 };
3278
3279 Some(id)
3280 }
3281}
3282
3283impl ApplicationContentId for IambBufferId {}
3284
3285impl ApplicationInfo for IambInfo {
3286 type Error = IambError;
3287 type Store = ChatStore;
3288 type Action = IambAction;
3289 type WindowId = IambId;
3290 type ContentId = IambBufferId;
3291
3292 fn content_of_command(ct: CommandType) -> IambBufferId {
3293 IambBufferId::Command(ct)
3294 }
3295}
3296
3297#[cfg(test)]
3298pub mod tests {
3299 use super::*;
3300
3301 use std::iter::FromIterator as _;
3302
3303 use matrix_sdk::ruma::events::reaction::ReactionEventContent;
3304 use matrix_sdk::ruma::events::relation::Annotation;
3305 use matrix_sdk::ruma::{MilliSecondsSinceUnixEpoch, owned_event_id, owned_user_id};
3306 use pretty_assertions::assert_eq;
3307 use ratatui::style::Color;
3308 use serde_json::{Map, Value};
3309
3310 use crate::tests::*;
3311
3312 fn mock_room_message_event(
3313 content: RoomMessageEventContent,
3314 sender: OwnedUserId,
3315 key: MessageKey,
3316 ) -> RoomMessageEvent {
3317 let message = mock_room1_message(content, sender, key);
3318 let MessageEvent::Original(event, _) = message.event else {
3319 unreachable!("mock_room1_message always returns an original room message")
3320 };
3321
3322 MessageLikeEvent::Original(*event)
3323 }
3324
3325 fn create_reaction_event(
3326 content: &ReactionEventContent,
3327 event_id: &str,
3328 sender: &str,
3329 ) -> ReactionEvent {
3330 serde_json::from_value(Value::Object(Map::from_iter([
3331 ("type".to_owned(), Value::String("m.reaction".into())),
3332 ("content".to_owned(), serde_json::to_value(content).unwrap()),
3333 ("event_id".to_owned(), serde_json::to_value(event_id).unwrap()),
3334 ("sender".to_owned(), Value::String(sender.into())),
3335 (
3336 "origin_server_ts".to_owned(),
3337 serde_json::to_value(MilliSecondsSinceUnixEpoch::now()).unwrap(),
3338 ),
3339 ("room_id".to_owned(), Value::String("!foo:example.org".into())),
3340 ])))
3341 .unwrap()
3342 }
3343
3344 #[test]
3345 fn test_multiple_identical_reactions() {
3346 let mut info = RoomInfo::default();
3347
3348 let content = ReactionEventContent::new(Annotation::new(
3349 owned_event_id!("$my_reaction"),
3350 "🏠".to_owned(),
3351 ));
3352
3353 for i in 0..3 {
3354 let event_id = format!("$house_{i}");
3355 let react = create_reaction_event(&content, &event_id, "@foo:example.com");
3356 info.insert_reaction(react, None);
3357 }
3358
3359 let content = ReactionEventContent::new(Annotation::new(
3360 owned_event_id!("$my_reaction"),
3361 "🙂".to_owned(),
3362 ));
3363
3364 for i in 0..2 {
3365 let event_id = format!("$smile_{i}");
3366 let react = create_reaction_event(&content, &event_id, "@foo:example.com");
3367 info.insert_reaction(react, None);
3368 }
3369
3370 for i in 2..4 {
3371 let event_id = format!("$smile2_{i}");
3372 let react = create_reaction_event(&content, &event_id, "@bar:example.com");
3373 info.insert_reaction(react, None);
3374 }
3375
3376 let reacts: Vec<_> = info
3377 .get_reactions(&owned_event_id!("$my_reaction"))
3378 .into_iter()
3379 .map(|(key, count, _)| (key, count))
3380 .collect();
3381 assert_eq!(reacts, vec![
3382 ("🏠", vec![owned_user_id!("@foo:example.com").deref()]),
3383 ("🙂", vec![
3384 owned_user_id!("@bar:example.com").deref(),
3385 owned_user_id!("@foo:example.com").deref(),
3386 ],)
3387 ]);
3388 }
3389
3390 #[test]
3391 fn test_implicit_receipt_tracks_message_sender_for_display() {
3392 let mut info = RoomInfo::default();
3393 let settings = mock_settings();
3394 let mut previews = PreviewManager::new(&settings);
3395 let event = mock_room_message_event(
3396 RoomMessageEventContent::text_plain("sent by another user"),
3397 TEST_USER2.clone(),
3398 MSG5_KEY.clone(),
3399 );
3400
3401 info.insert_message(event, ThreadSummaryStatus::Unknown, &settings, &mut previews);
3402
3403 assert_eq!(
3404 info.user_receipts(&ReceiptThread::Main)
3405 .and_then(|receipts| receipts.get(&*TEST_USER2)),
3406 Some(&*MSG5_EVID),
3407 );
3408 assert!(
3409 info.event_receipts(&ReceiptThread::Main)
3410 .and_then(|receipts| receipts.get(&*MSG5_EVID))
3411 .is_some_and(|users| users.contains(&*TEST_USER2))
3412 );
3413 }
3414
3415 #[test]
3416 fn test_implicit_receipts_do_not_move_backwards_during_backpagination() {
3417 let mut info = RoomInfo::default();
3418 let settings = mock_settings();
3419 let mut previews = PreviewManager::new(&settings);
3420 let newer = mock_room_message_event(
3421 RoomMessageEventContent::text_plain("newer"),
3422 TEST_USER2.clone(),
3423 MSG5_KEY.clone(),
3424 );
3425 let older = mock_room_message_event(
3426 RoomMessageEventContent::text_plain("older"),
3427 TEST_USER2.clone(),
3428 MSG2_KEY.clone(),
3429 );
3430
3431 info.insert_message(newer, ThreadSummaryStatus::Unknown, &settings, &mut previews);
3432 info.insert_message(older, ThreadSummaryStatus::Unknown, &settings, &mut previews);
3433
3434 assert_eq!(
3435 info.user_receipts(&ReceiptThread::Main)
3436 .and_then(|receipts| receipts.get(&*TEST_USER2)),
3437 Some(&*MSG5_EVID),
3438 );
3439 }
3440
3441 #[test]
3442 fn test_implicit_receipt_preserves_thread_context() {
3443 let mut info = RoomInfo::default();
3444 let root = owned_event_id!("$thread_root");
3445 let reply = owned_event_id!("$thread_reply");
3446 let thread = ReceiptThread::Thread(root.clone());
3447
3448 info.keys
3449 .insert(reply.clone(), EventLocation::Message(Some(root), MSG5_KEY.clone()));
3450 info.set_implicit_receipt(TEST_USER1.clone(), reply.clone());
3451
3452 assert_eq!(
3453 info.user_receipts(&thread).and_then(|receipts| receipts.get(&*TEST_USER1)),
3454 Some(&reply),
3455 );
3456 }
3457
3458 #[test]
3459 fn test_implicit_receipt_supports_state_events() {
3460 let mut info = RoomInfo::default();
3461 info.keys
3462 .insert(MSG5_EVID.clone(), EventLocation::Message(None, MSG5_KEY.clone()));
3463
3464 info.set_implicit_receipt(TEST_USER2.clone(), MSG5_EVID.clone());
3465
3466 assert_eq!(
3467 info.user_receipts(&ReceiptThread::Main)
3468 .and_then(|receipts| receipts.get(&*TEST_USER2)),
3469 Some(&*MSG5_EVID),
3470 );
3471 }
3472
3473 #[test]
3474 fn test_explicit_receipt_does_not_move_implicit_receipt_backwards() {
3475 let settings = mock_settings();
3476 let mut previews = PreviewManager::new(&settings);
3477 let mut info = RoomInfo::default();
3478 let older = mock_room_message_event(
3479 RoomMessageEventContent::text_plain("older"),
3480 TEST_USER2.clone(),
3481 MSG2_KEY.clone(),
3482 );
3483 let newer = mock_room_message_event(
3484 RoomMessageEventContent::text_plain("newer"),
3485 TEST_USER2.clone(),
3486 MSG5_KEY.clone(),
3487 );
3488
3489 info.insert_message(older, ThreadSummaryStatus::Unknown, &settings, &mut previews);
3490 info.insert_message(newer, ThreadSummaryStatus::Unknown, &settings, &mut previews);
3491 info.set_receipt(ReceiptThread::Main, TEST_USER2.clone(), MSG2_EVID.clone());
3492
3493 assert_eq!(
3494 info.user_receipts(&ReceiptThread::Main)
3495 .and_then(|receipts| receipts.get(&*TEST_USER2)),
3496 Some(&*MSG5_EVID),
3497 );
3498 }
3499
3500 #[test]
3501 fn test_implicit_receipt_waits_for_unloaded_explicit_receipt() {
3502 let settings = mock_settings();
3503 let mut previews = PreviewManager::new(&settings);
3504 let mut info = RoomInfo::default();
3505 info.set_receipt(ReceiptThread::Main, TEST_USER2.clone(), MSG5_EVID.clone());
3506 let older = mock_room_message_event(
3507 RoomMessageEventContent::text_plain("older"),
3508 TEST_USER2.clone(),
3509 MSG2_KEY.clone(),
3510 );
3511
3512 info.insert_message(older, ThreadSummaryStatus::Unknown, &settings, &mut previews);
3513
3514 assert_eq!(
3515 info.user_receipts(&ReceiptThread::Main)
3516 .and_then(|receipts| receipts.get(&*TEST_USER2)),
3517 Some(&*MSG5_EVID),
3518 );
3519 }
3520
3521 #[test]
3522 fn test_typing_spans() {
3523 let mut info = RoomInfo::default();
3524 let settings = mock_settings();
3525 let theme = &settings.theme;
3526
3527 let users0 = vec![];
3528 let users1 = vec![TEST_USER1.clone()];
3529 let users2 = vec![TEST_USER1.clone(), TEST_USER2.clone()];
3530 let users4 = vec![
3531 TEST_USER1.clone(),
3532 TEST_USER2.clone(),
3533 TEST_USER3.clone(),
3534 TEST_USER4.clone(),
3535 ];
3536 let users5 = vec![
3537 TEST_USER1.clone(),
3538 TEST_USER2.clone(),
3539 TEST_USER3.clone(),
3540 TEST_USER4.clone(),
3541 TEST_USER5.clone(),
3542 ];
3543
3544 // Nothing set.
3545 assert_eq!(info.users_typing, None);
3546 assert_eq!(info.get_typing_spans(&settings), Line::from(vec![]));
3547
3548 // Empty typing list.
3549 info.set_typing(users0);
3550 assert!(info.users_typing.is_some());
3551 assert_eq!(info.get_typing_spans(&settings), Line::from(vec![]));
3552
3553 // Single user typing.
3554 info.set_typing(users1);
3555 assert!(info.users_typing.is_some());
3556 assert_eq!(
3557 info.get_typing_spans(&settings),
3558 Line::from(vec![
3559 Span::styled("@user1:example.com", theme.users.style("@user1:example.com", None)),
3560 Span::from(" is typing...")
3561 ])
3562 );
3563
3564 // Two users typing.
3565 info.set_typing(users2);
3566 assert!(info.users_typing.is_some());
3567 assert_eq!(
3568 info.get_typing_spans(&settings),
3569 Line::from(vec![
3570 Span::styled("@user1:example.com", theme.users.style("@user1:example.com", None)),
3571 Span::raw(" and "),
3572 Span::styled("@user2:example.com", theme.users.style("@user2:example.com", None)),
3573 Span::raw(" are typing...")
3574 ])
3575 );
3576
3577 // Four users typing.
3578 info.set_typing(users4);
3579 assert!(info.users_typing.is_some());
3580 assert_eq!(info.get_typing_spans(&settings), Line::from("Several people are typing..."));
3581
3582 // Five users typing.
3583 info.set_typing(users5);
3584 assert!(info.users_typing.is_some());
3585 assert_eq!(info.get_typing_spans(&settings), Line::from("Many people are typing..."));
3586
3587 // Test that USER5 gets rendered using the configured color and name.
3588 info.set_typing(vec![TEST_USER5.clone()]);
3589 assert!(info.users_typing.is_some());
3590 assert_eq!(
3591 info.get_typing_spans(&settings),
3592 Line::from(vec![
3593 Span::styled("USER 5", Style::default().fg(Color::Black).bold()),
3594 Span::from(" is typing...")
3595 ])
3596 );
3597 }
3598
3599 #[test]
3600 fn test_need_load() {
3601 let room_id = TEST_ROOM1_ID.clone();
3602
3603 let mut need_load = RoomNeeds::default();
3604
3605 need_load.need_messages(room_id.clone());
3606 need_load.need_members(room_id.clone());
3607
3608 assert_eq!(need_load.room_needs().collect::<Vec<(OwnedRoomId, Need)>>(), vec![(
3609 room_id,
3610 Need {
3611 members: true,
3612 messages: Some(Vec::new()),
3613 pinned: false
3614 }
3615 )],);
3616 }
3617
3618 #[test]
3619 fn test_pinned_lookup() {
3620 let mut info = mock_room();
3621 let unloaded = owned_event_id!("$unloaded");
3622
3623 info.pinned_events = vec![MSG3_EVID.clone(), unloaded.clone()];
3624
3625 assert!(info.is_pinned(&MSG3_EVID));
3626 assert!(!info.is_pinned(&MSG4_EVID));
3627
3628 // Loaded messages come from the scrollback, so only the unloaded one needs fetching.
3629 assert!(info.get_pinned(&MSG3_EVID).is_some());
3630 assert_eq!(info.missing_pinned(), vec![unloaded.clone()]);
3631
3632 info.insert_pinned(unloaded.clone(), mock_message1().into());
3633 assert!(info.get_pinned(&unloaded).is_some());
3634 assert!(info.missing_pinned().is_empty());
3635
3636 // Failed fetches are retried until they hit the limit.
3637 let broken = owned_event_id!("$broken");
3638 info.pinned_events.push(broken.clone());
3639
3640 for _ in 1..PINNED_FETCH_ATTEMPTS {
3641 info.insert_pinned(broken.clone(), None);
3642 }
3643 assert!(!info.pinned_unavailable(&broken));
3644 assert_eq!(info.missing_pinned(), vec![broken.clone()]);
3645
3646 info.insert_pinned(broken.clone(), None);
3647 assert!(info.pinned_unavailable(&broken));
3648 assert!(info.missing_pinned().is_empty());
3649
3650 let (thread, key) = info.get_message_location(&MSG3_EVID).unwrap();
3651 assert_eq!(thread, None);
3652 assert_eq!(key, &*MSG3_KEY);
3653 assert!(info.get_message_location(&unloaded).is_none());
3654 }
3655
3656 #[test]
3657 fn test_alias_window_id() {
3658 let room_id = TEST_ROOM1_ALIAS.clone();
3659 let id = IambId::Room(room_id.into(), RoomView::Main);
3660
3661 // Hash gets replaced during encoding:
3662 let exp = "iamb://room/%23room1%3Aexample%2Ecom";
3663 assert_eq!(id.to_string(), exp);
3664
3665 // Percent encoding turns back into hash during decoding:
3666 let parsed: IambId = serde_json::from_str(&format!("{exp:?}")).unwrap();
3667 assert_eq!(parsed, id);
3668 }
3669
3670 #[test]
3671 fn test_pinned_window_id() {
3672 let room_id = TEST_ROOM1_ID.clone();
3673 let id = IambId::PinnedList(room_id.clone());
3674 let url = format!("iamb://room/{room_id}/pinned");
3675
3676 assert_eq!(id.to_string(), url);
3677
3678 let parsed: IambId = serde_json::from_str(&format!("{url:?}")).unwrap();
3679 assert_eq!(parsed, id);
3680 }
3681}