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