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