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