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