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