src/base.rs
1855 lines · 56125 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,
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 Message(MessageKey),
685
686 /// The [EventId] belongs to a reaction to the given event.
687 Reaction(OwnedEventId),
688}
689
690impl EventLocation {
691 fn to_message_key(&self) -> Option<&MessageKey> {
692 if let EventLocation::Message(key) = self {
693 Some(key)
694 } else {
695 None
696 }
697 }
698}
699
700#[derive(Clone, Debug, Default, Eq, PartialEq)]
701pub struct UnreadInfo {
702 pub(crate) unread: bool,
703 pub(crate) latest: Option<MessageTimeStamp>,
704}
705
706impl UnreadInfo {
707 pub fn is_unread(&self) -> bool {
708 self.unread
709 }
710
711 pub fn latest(&self) -> Option<&MessageTimeStamp> {
712 self.latest.as_ref()
713 }
714}
715
716/// Information about room's the user's joined.
717#[derive(Default)]
718pub struct RoomInfo {
719 /// The display name for this room.
720 pub name: Option<String>,
721
722 /// The tags placed on this room.
723 pub tags: Option<Tags>,
724
725 /// A map of event IDs to where they are stored in this struct.
726 pub keys: HashMap<OwnedEventId, EventLocation>,
727
728 /// The messages loaded for this room.
729 pub messages: Messages,
730
731 /// A map of read markers to display on different events.
732 pub event_receipts: HashMap<OwnedEventId, HashSet<OwnedUserId>>,
733
734 /// A map of the most recent read marker for each user.
735 ///
736 /// Every receipt in this map should also have an entry in [`event_receipts`],
737 /// however not every user has an entry. If a user's most recent receipt is
738 /// older than the oldest loaded event, that user will not be included.
739 pub user_receipts: HashMap<OwnedUserId, OwnedEventId>,
740
741 /// A map of message identifiers to a map of reaction events.
742 pub reactions: HashMap<OwnedEventId, MessageReactions>,
743
744 /// Whether the scrollback for this room is currently being fetched.
745 pub fetching: bool,
746
747 /// Where to continue fetching from when we continue loading scrollback history.
748 pub fetch_id: RoomFetchStatus,
749
750 /// The time that we last fetched scrollback for this room.
751 pub fetch_last: Option<Instant>,
752
753 /// Users currently typing in this room, and when we received notification of them doing so.
754 pub users_typing: Option<(Instant, Vec<OwnedUserId>)>,
755
756 /// The display names for users in this room.
757 pub display_names: HashMap<OwnedUserId, String>,
758}
759
760impl RoomInfo {
761 /// Get the reactions and their counts for a message.
762 pub fn get_reactions(&self, event_id: &EventId) -> Vec<(&str, usize)> {
763 if let Some(reacts) = self.reactions.get(event_id) {
764 let mut counts = HashMap::new();
765
766 for (key, _) in reacts.values() {
767 let count = counts.entry(key.as_str()).or_default();
768 *count += 1;
769 }
770
771 let mut reactions = counts.into_iter().collect::<Vec<_>>();
772 reactions.sort();
773
774 reactions
775 } else {
776 vec![]
777 }
778 }
779
780 /// Map an event identifier to its [MessageKey].
781 pub fn get_message_key(&self, event_id: &EventId) -> Option<&MessageKey> {
782 self.keys.get(event_id)?.to_message_key()
783 }
784
785 /// Get an event for an identifier.
786 pub fn get_event(&self, event_id: &EventId) -> Option<&Message> {
787 self.messages.get(self.get_message_key(event_id)?)
788 }
789
790 /// Get an event for an identifier as mutable.
791 pub fn get_event_mut(&mut self, event_id: &EventId) -> Option<&mut Message> {
792 self.messages.get_mut(self.keys.get(event_id)?.to_message_key()?)
793 }
794
795 /// Insert a reaction to a message.
796 pub fn insert_reaction(&mut self, react: ReactionEvent) {
797 match react {
798 MessageLikeEvent::Original(react) => {
799 let rel_id = react.content.relates_to.event_id;
800 let key = react.content.relates_to.key;
801
802 let message = self.reactions.entry(rel_id.clone()).or_default();
803 let event_id = react.event_id;
804 let user_id = react.sender;
805
806 message.insert(event_id.clone(), (key, user_id));
807
808 let loc = EventLocation::Reaction(rel_id);
809 self.keys.insert(event_id, loc);
810 },
811 MessageLikeEvent::Redacted(_) => {
812 return;
813 },
814 }
815 }
816
817 /// Insert an edit.
818 pub fn insert_edit(&mut self, msg: Replacement<RoomMessageEventContentWithoutRelation>) {
819 let event_id = msg.event_id;
820 let new_msgtype = msg.new_content;
821
822 let key = if let Some(EventLocation::Message(k)) = self.keys.get(&event_id) {
823 k
824 } else {
825 return;
826 };
827
828 let msg = if let Some(msg) = self.messages.get_mut(key) {
829 msg
830 } else {
831 return;
832 };
833
834 match &mut msg.event {
835 MessageEvent::Original(orig) => {
836 orig.content.apply_replacement(new_msgtype);
837 },
838 MessageEvent::Local(_, content) => {
839 content.apply_replacement(new_msgtype);
840 },
841 MessageEvent::Redacted(_) |
842 MessageEvent::EncryptedOriginal(_) |
843 MessageEvent::EncryptedRedacted(_) => {
844 return;
845 },
846 }
847
848 msg.html = msg.event.html();
849 }
850
851 /// Indicates whether this room has unread messages.
852 pub fn unreads(&self, settings: &ApplicationSettings) -> UnreadInfo {
853 let last_message = self.messages.last_key_value();
854 let last_receipt = self.get_receipt(&settings.profile.user_id);
855
856 match (last_message, last_receipt) {
857 (Some(((ts, recent), _)), Some(last_read)) => {
858 UnreadInfo { unread: last_read != recent, latest: Some(*ts) }
859 },
860 (Some(((ts, _), _)), None) => UnreadInfo { unread: false, latest: Some(*ts) },
861 (None, _) => UnreadInfo::default(),
862 }
863 }
864
865 /// Inserts events that couldn't be decrypted into the scrollback.
866 pub fn insert_encrypted(&mut self, msg: RoomEncryptedEvent) {
867 let event_id = msg.event_id().to_owned();
868 let key = (msg.origin_server_ts().into(), event_id.clone());
869
870 self.keys.insert(event_id, EventLocation::Message(key.clone()));
871 self.messages.insert(key, msg.into());
872 }
873
874 /// Insert a new message.
875 pub fn insert_message(&mut self, msg: RoomMessageEvent) {
876 let event_id = msg.event_id().to_owned();
877 let key = (msg.origin_server_ts().into(), event_id.clone());
878
879 self.keys.insert(event_id.clone(), EventLocation::Message(key.clone()));
880 self.messages.insert(key, msg.into());
881
882 // Remove any echo.
883 let key = (MessageTimeStamp::LocalEcho, event_id);
884 let _ = self.messages.remove(&key);
885 }
886
887 /// Insert a new message event.
888 pub fn insert(&mut self, msg: RoomMessageEvent) {
889 match msg {
890 RoomMessageEvent::Original(OriginalRoomMessageEvent {
891 content:
892 RoomMessageEventContent { relates_to: Some(Relation::Replacement(repl)), .. },
893 ..
894 }) => self.insert_edit(repl),
895 _ => self.insert_message(msg),
896 }
897 }
898
899 /// Insert a new message event, and spawn a task for image-preview if it has an image
900 /// attachment.
901 pub fn insert_with_preview(
902 &mut self,
903 room_id: OwnedRoomId,
904 store: AsyncProgramStore,
905 picker: Option<Picker>,
906 ev: RoomMessageEvent,
907 settings: &mut ApplicationSettings,
908 media: matrix_sdk::Media,
909 ) {
910 let source = picker.and_then(|_| source_from_event(&ev));
911 self.insert(ev);
912
913 if let Some((event_id, source)) = source {
914 if let (Some(msg), Some(image_preview)) =
915 (self.get_event_mut(&event_id), &settings.tunables.image_preview)
916 {
917 msg.image_preview = ImageStatus::Downloading(image_preview.size.clone());
918 spawn_insert_preview(
919 store,
920 room_id,
921 event_id,
922 source,
923 media,
924 settings.dirs.image_previews.clone(),
925 )
926 }
927 }
928 }
929
930 /// Indicates whether we've recently fetched scrollback for this room.
931 pub fn recently_fetched(&self) -> bool {
932 self.fetch_last.map_or(false, |i| i.elapsed() < ROOM_FETCH_DEBOUNCE)
933 }
934
935 fn clear_receipt(&mut self, user_id: &OwnedUserId) -> Option<()> {
936 let old_event_id = self.user_receipts.get(user_id)?;
937 let old_receipts = self.event_receipts.get_mut(old_event_id)?;
938 old_receipts.remove(user_id);
939
940 if old_receipts.is_empty() {
941 self.event_receipts.remove(old_event_id);
942 }
943
944 None
945 }
946
947 pub fn set_receipt(&mut self, user_id: OwnedUserId, event_id: OwnedEventId) {
948 self.clear_receipt(&user_id);
949 self.event_receipts
950 .entry(event_id.clone())
951 .or_default()
952 .insert(user_id.clone());
953 self.user_receipts.insert(user_id, event_id);
954 }
955
956 pub fn get_receipt(&self, user_id: &UserId) -> Option<&OwnedEventId> {
957 self.user_receipts.get(user_id)
958 }
959
960 fn get_typers(&self) -> &[OwnedUserId] {
961 if let Some((t, users)) = &self.users_typing {
962 if t.elapsed() < Duration::from_secs(4) {
963 return users.as_ref();
964 } else {
965 return &[];
966 }
967 } else {
968 return &[];
969 }
970 }
971
972 fn get_typing_spans<'a>(&'a self, settings: &'a ApplicationSettings) -> Line<'a> {
973 let typers = self.get_typers();
974 let n = typers.len();
975
976 match n {
977 0 => Line::from(vec![]),
978 1 => {
979 let user = settings.get_user_span(typers[0].as_ref(), self);
980
981 Line::from(vec![user, Span::from(" is typing...")])
982 },
983 2 => {
984 let user1 = settings.get_user_span(typers[0].as_ref(), self);
985 let user2 = settings.get_user_span(typers[1].as_ref(), self);
986
987 Line::from(vec![
988 user1,
989 Span::raw(" and "),
990 user2,
991 Span::from(" are typing..."),
992 ])
993 },
994 n if n < 5 => Line::from("Several people are typing..."),
995 _ => Line::from("Many people are typing..."),
996 }
997 }
998
999 /// Update typing information for this room.
1000 pub fn set_typing(&mut self, user_ids: Vec<OwnedUserId>) {
1001 self.users_typing = (Instant::now(), user_ids).into();
1002 }
1003
1004 /// Create a [Rect] that displays what users are typing.
1005 pub fn render_typing(
1006 &mut self,
1007 area: Rect,
1008 buf: &mut Buffer,
1009 settings: &ApplicationSettings,
1010 ) -> Rect {
1011 if area.height <= 2 || area.width <= 20 {
1012 return area;
1013 }
1014
1015 if !settings.tunables.typing_notice_display {
1016 return area;
1017 }
1018
1019 let top = Rect::new(area.x, area.y, area.width, area.height - 1);
1020 let bar = Rect::new(area.x, area.y + top.height, area.width, 1);
1021
1022 Paragraph::new(self.get_typing_spans(settings))
1023 .alignment(Alignment::Center)
1024 .render(bar, buf);
1025
1026 return top;
1027 }
1028}
1029
1030/// Generate a [CompletionMap] for Emoji shortcodes.
1031fn emoji_map() -> CompletionMap<String, &'static Emoji> {
1032 let mut emojis = CompletionMap::default();
1033
1034 for emoji in emojis::iter() {
1035 for shortcode in emoji.shortcodes() {
1036 emojis.insert(shortcode.to_string(), emoji);
1037 }
1038 }
1039
1040 return emojis;
1041}
1042
1043#[cfg(unix)]
1044fn picker_from_termios(protocol_type: Option<ProtocolType>) -> Option<Picker> {
1045 let mut picker = match Picker::from_termios() {
1046 Ok(picker) => picker,
1047 Err(e) => {
1048 tracing::error!("Failed to setup image previews: {e}");
1049 return None;
1050 },
1051 };
1052
1053 if let Some(protocol_type) = protocol_type {
1054 picker.protocol_type = protocol_type;
1055 } else {
1056 picker.guess_protocol();
1057 }
1058
1059 Some(picker)
1060}
1061
1062/// Windows cannot guess the right protocol, and always needs type and font_size.
1063#[cfg(windows)]
1064fn picker_from_termios(_: Option<ProtocolType>) -> Option<Picker> {
1065 tracing::error!("\"image_preview\" requires \"protocol\" with \"type\" and \"font_size\" options on Windows.");
1066 None
1067}
1068
1069fn picker_from_settings(settings: &ApplicationSettings) -> Option<Picker> {
1070 let image_preview = settings.tunables.image_preview.as_ref()?;
1071 let image_preview_protocol = image_preview.protocol.as_ref();
1072
1073 if let Some(&ImagePreviewProtocolValues {
1074 r#type: Some(protocol_type),
1075 font_size: Some(font_size),
1076 }) = image_preview_protocol
1077 {
1078 // User forced type and font_size: use that.
1079 let mut picker = Picker::new(font_size);
1080 picker.protocol_type = protocol_type;
1081 Some(picker)
1082 } else {
1083 // Guess, but use type if forced.
1084 picker_from_termios(image_preview_protocol.and_then(|p| p.r#type))
1085 }
1086}
1087
1088/// Information gathered during server syncs about joined rooms.
1089#[derive(Default)]
1090pub struct SyncInfo {
1091 /// Spaces that the user is a member of.
1092 pub spaces: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
1093
1094 /// Rooms that the user is a member of.
1095 pub rooms: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
1096
1097 /// DMs that the user is a member of.
1098 pub dms: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
1099}
1100
1101bitflags::bitflags! {
1102 /// Load-needs
1103 #[derive(Debug, Default, PartialEq)]
1104 pub struct Need: u32 {
1105 const EMPTY = 0b00000000;
1106 const MESSAGES = 0b00000001;
1107 const MEMBERS = 0b00000010;
1108 }
1109}
1110
1111/// Things that need loading for different rooms.
1112#[derive(Default)]
1113pub struct RoomNeeds {
1114 needs: HashMap<OwnedRoomId, Need>,
1115}
1116
1117impl RoomNeeds {
1118 /// Mark a room for needing something to be loaded.
1119 pub fn insert(&mut self, room_id: OwnedRoomId, need: Need) {
1120 self.needs.entry(room_id).or_default().insert(need);
1121 }
1122}
1123
1124impl IntoIterator for RoomNeeds {
1125 type Item = (OwnedRoomId, Need);
1126 type IntoIter = IntoIter<OwnedRoomId, Need>;
1127
1128 fn into_iter(self) -> Self::IntoIter {
1129 self.needs.into_iter()
1130 }
1131}
1132
1133/// The main application state.
1134pub struct ChatStore {
1135 /// `:`-commands
1136 pub cmds: ProgramCommands,
1137
1138 /// Handle for communicating w/ the worker thread.
1139 pub worker: Requester,
1140
1141 /// Map of joined rooms.
1142 pub rooms: CompletionMap<OwnedRoomId, RoomInfo>,
1143
1144 /// Map of room names.
1145 pub names: CompletionMap<String, OwnedRoomId>,
1146
1147 /// Presence information for other users.
1148 pub presences: CompletionMap<OwnedUserId, PresenceState>,
1149
1150 /// In-progress and completed verifications.
1151 pub verifications: HashMap<String, SasVerification>,
1152
1153 /// Settings for the current profile loaded from config file.
1154 pub settings: ApplicationSettings,
1155
1156 /// Set of rooms that need more messages loaded in their scrollback.
1157 pub need_load: RoomNeeds,
1158
1159 /// [CompletionMap] of Emoji shortcodes.
1160 pub emojis: CompletionMap<String, &'static Emoji>,
1161
1162 /// Information gathered by the background thread.
1163 pub sync_info: SyncInfo,
1164
1165 /// Image preview "protocol" picker.
1166 pub picker: Option<Picker>,
1167}
1168
1169impl ChatStore {
1170 /// Create a new [ChatStore].
1171 pub fn new(worker: Requester, settings: ApplicationSettings) -> Self {
1172 let picker = picker_from_settings(&settings);
1173
1174 ChatStore {
1175 worker,
1176 settings,
1177 picker,
1178 cmds: crate::commands::setup_commands(),
1179 emojis: emoji_map(),
1180
1181 names: Default::default(),
1182 rooms: Default::default(),
1183 presences: Default::default(),
1184 verifications: Default::default(),
1185 need_load: Default::default(),
1186 sync_info: Default::default(),
1187 }
1188 }
1189
1190 /// Get a joined room.
1191 pub fn get_joined_room(&self, room_id: &RoomId) -> Option<MatrixRoom> {
1192 let Some(room) = self.worker.client.get_room(room_id) else {
1193 return None;
1194 };
1195
1196 if room.state() == MatrixRoomState::Joined {
1197 Some(room)
1198 } else {
1199 None
1200 }
1201 }
1202
1203 /// Get the title for a room.
1204 pub fn get_room_title(&self, room_id: &RoomId) -> String {
1205 self.rooms
1206 .get(room_id)
1207 .and_then(|i| i.name.as_ref())
1208 .map(String::from)
1209 .unwrap_or_else(|| "Untitled Matrix Room".to_string())
1210 }
1211
1212 /// Get the [RoomInfo] for a given room identifier.
1213 pub fn get_room_info(&mut self, room_id: OwnedRoomId) -> &mut RoomInfo {
1214 self.rooms.get_or_default(room_id)
1215 }
1216
1217 /// Set the name for a room.
1218 pub fn set_room_name(&mut self, room_id: &RoomId, name: &str) {
1219 self.rooms.get_or_default(room_id.to_owned()).name = name.to_string().into();
1220 }
1221
1222 /// Insert a new E2EE verification.
1223 pub fn insert_sas(&mut self, sas: SasVerification) {
1224 let key = format!("{}/{}", sas.other_user_id(), sas.other_device().device_id());
1225
1226 self.verifications.insert(key, sas);
1227 }
1228}
1229
1230impl ApplicationStore for ChatStore {}
1231
1232/// Identified used to track window content.
1233#[derive(Clone, Debug, Eq, Hash, PartialEq)]
1234pub enum IambId {
1235 /// A Matrix room.
1236 Room(OwnedRoomId),
1237
1238 /// The `:dms` window.
1239 DirectList,
1240
1241 /// The `:members` window for a given Matrix room.
1242 MemberList(OwnedRoomId),
1243
1244 /// The `:rooms` window.
1245 RoomList,
1246
1247 /// The `:spaces` window.
1248 SpaceList,
1249
1250 /// The `:verify` window.
1251 VerifyList,
1252
1253 /// The `:welcome` window.
1254 Welcome,
1255
1256 /// The `:chats` window.
1257 ChatList,
1258}
1259
1260impl Display for IambId {
1261 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1262 match self {
1263 IambId::Room(room_id) => {
1264 write!(f, "iamb://room/{room_id}")
1265 },
1266 IambId::MemberList(room_id) => {
1267 write!(f, "iamb://members/{room_id}")
1268 },
1269 IambId::DirectList => f.write_str("iamb://dms"),
1270 IambId::RoomList => f.write_str("iamb://rooms"),
1271 IambId::SpaceList => f.write_str("iamb://spaces"),
1272 IambId::VerifyList => f.write_str("iamb://verify"),
1273 IambId::Welcome => f.write_str("iamb://welcome"),
1274 IambId::ChatList => f.write_str("iamb://chats"),
1275 }
1276 }
1277}
1278
1279impl ApplicationWindowId for IambId {}
1280
1281impl Serialize for IambId {
1282 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1283 where
1284 S: Serializer,
1285 {
1286 serializer.serialize_str(&self.to_string())
1287 }
1288}
1289
1290impl<'de> Deserialize<'de> for IambId {
1291 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1292 where
1293 D: Deserializer<'de>,
1294 {
1295 deserializer.deserialize_str(IambIdVisitor)
1296 }
1297}
1298
1299/// [serde] visitor for deserializing [IambId].
1300struct IambIdVisitor;
1301
1302impl<'de> Visitor<'de> for IambIdVisitor {
1303 type Value = IambId;
1304
1305 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1306 formatter.write_str("a valid window URL")
1307 }
1308
1309 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1310 where
1311 E: SerdeError,
1312 {
1313 let Ok(url) = Url::parse(value) else {
1314 return Err(E::custom("Invalid iamb window URL"));
1315 };
1316
1317 if url.scheme() != "iamb" {
1318 return Err(E::custom("Invalid iamb window URL"));
1319 }
1320
1321 match url.domain() {
1322 Some("room") => {
1323 let Some(path) = url.path_segments() else {
1324 return Err(E::custom("Invalid members window URL"));
1325 };
1326
1327 let &[room_id] = path.collect::<Vec<_>>().as_slice() else {
1328 return Err(E::custom("Invalid members window URL"));
1329 };
1330
1331 let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
1332 return Err(E::custom("Invalid room identifier"));
1333 };
1334
1335 Ok(IambId::Room(room_id))
1336 },
1337 Some("members") => {
1338 let Some(path) = url.path_segments() else {
1339 return Err(E::custom("Invalid members window URL"));
1340 };
1341
1342 let &[room_id] = path.collect::<Vec<_>>().as_slice() else {
1343 return Err(E::custom("Invalid members window URL"));
1344 };
1345
1346 let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
1347 return Err(E::custom("Invalid room identifier"));
1348 };
1349
1350 Ok(IambId::MemberList(room_id))
1351 },
1352 Some("dms") => {
1353 if url.path() != "" {
1354 return Err(E::custom("iamb://dms takes no path"));
1355 }
1356
1357 Ok(IambId::DirectList)
1358 },
1359 Some("rooms") => {
1360 if url.path() != "" {
1361 return Err(E::custom("iamb://rooms takes no path"));
1362 }
1363
1364 Ok(IambId::RoomList)
1365 },
1366 Some("spaces") => {
1367 if url.path() != "" {
1368 return Err(E::custom("iamb://spaces takes no path"));
1369 }
1370
1371 Ok(IambId::SpaceList)
1372 },
1373 Some("verify") => {
1374 if url.path() != "" {
1375 return Err(E::custom("iamb://verify takes no path"));
1376 }
1377
1378 Ok(IambId::VerifyList)
1379 },
1380 Some("welcome") => {
1381 if url.path() != "" {
1382 return Err(E::custom("iamb://welcome takes no path"));
1383 }
1384
1385 Ok(IambId::Welcome)
1386 },
1387 Some("chats") => {
1388 if url.path() != "" {
1389 return Err(E::custom("iamb://chats takes no path"));
1390 }
1391
1392 Ok(IambId::ChatList)
1393 },
1394 Some(s) => Err(E::custom(format!("{s:?} is not a valid window"))),
1395 None => Err(E::custom("Invalid iamb window URL")),
1396 }
1397 }
1398}
1399
1400/// Which part of the room window's UI is focused.
1401#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1402pub enum RoomFocus {
1403 /// The scrollback for a room window is focused.
1404 Scrollback,
1405
1406 /// The message bar for a room window is focused.
1407 MessageBar,
1408}
1409
1410impl RoomFocus {
1411 /// Whether this is [RoomFocus::Scrollback].
1412 pub fn is_scrollback(&self) -> bool {
1413 matches!(self, RoomFocus::Scrollback)
1414 }
1415
1416 /// Whether this is [RoomFocus::MessageBar].
1417 pub fn is_msgbar(&self) -> bool {
1418 matches!(self, RoomFocus::MessageBar)
1419 }
1420}
1421
1422/// Identifiers used to track where a mark was placed.
1423///
1424/// While this is the "buffer identifier" for the mark,
1425/// not all of these are necessarily actual buffers.
1426#[derive(Clone, Debug, Eq, Hash, PartialEq)]
1427pub enum IambBufferId {
1428 /// The command bar buffer.
1429 Command(CommandType),
1430
1431 /// The message buffer or a specific message in a room.
1432 Room(OwnedRoomId, RoomFocus),
1433
1434 /// The `:dms` window.
1435 DirectList,
1436
1437 /// The `:members` window for a room.
1438 MemberList(OwnedRoomId),
1439
1440 /// The `:rooms` window.
1441 RoomList,
1442
1443 /// The `:spaces` window.
1444 SpaceList,
1445
1446 /// The `:verify` window.
1447 VerifyList,
1448
1449 /// The buffer for the `:rooms` window.
1450 Welcome,
1451
1452 /// The `:chats` window.
1453 ChatList,
1454}
1455
1456impl IambBufferId {
1457 /// Get the identifier for the window that contains this buffer.
1458 pub fn to_window(&self) -> Option<IambId> {
1459 match self {
1460 IambBufferId::Command(_) => None,
1461 IambBufferId::Room(room, _) => Some(IambId::Room(room.clone())),
1462 IambBufferId::DirectList => Some(IambId::DirectList),
1463 IambBufferId::MemberList(room) => Some(IambId::MemberList(room.clone())),
1464 IambBufferId::RoomList => Some(IambId::RoomList),
1465 IambBufferId::SpaceList => Some(IambId::SpaceList),
1466 IambBufferId::VerifyList => Some(IambId::VerifyList),
1467 IambBufferId::Welcome => Some(IambId::Welcome),
1468 IambBufferId::ChatList => Some(IambId::ChatList),
1469 }
1470 }
1471}
1472
1473impl ApplicationContentId for IambBufferId {}
1474
1475impl ApplicationInfo for IambInfo {
1476 type Error = IambError;
1477 type Store = ChatStore;
1478 type Action = IambAction;
1479 type WindowId = IambId;
1480 type ContentId = IambBufferId;
1481
1482 fn complete(
1483 text: &EditRope,
1484 cursor: &mut Cursor,
1485 content: &IambBufferId,
1486 store: &mut ProgramStore,
1487 ) -> Vec<String> {
1488 match content {
1489 IambBufferId::Command(CommandType::Command) => complete_cmdbar(text, cursor, store),
1490 IambBufferId::Command(CommandType::Search) => vec![],
1491 IambBufferId::Room(_, RoomFocus::MessageBar) => complete_msgbar(text, cursor, store),
1492 IambBufferId::Room(_, RoomFocus::Scrollback) => vec![],
1493
1494 IambBufferId::DirectList => vec![],
1495 IambBufferId::MemberList(_) => vec![],
1496 IambBufferId::RoomList => vec![],
1497 IambBufferId::SpaceList => vec![],
1498 IambBufferId::VerifyList => vec![],
1499 IambBufferId::Welcome => vec![],
1500 IambBufferId::ChatList => vec![],
1501 }
1502 }
1503
1504 fn content_of_command(ct: CommandType) -> IambBufferId {
1505 IambBufferId::Command(ct)
1506 }
1507}
1508
1509/// Tab completion for user IDs.
1510fn complete_users(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
1511 let id = text
1512 .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
1513 .unwrap_or_else(EditRope::empty);
1514 let id = Cow::from(&id);
1515
1516 store
1517 .application
1518 .presences
1519 .complete(id.as_ref())
1520 .into_iter()
1521 .map(|i| i.to_string())
1522 .collect()
1523}
1524
1525/// Tab completion within the message bar.
1526fn complete_msgbar(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
1527 let id = text
1528 .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
1529 .unwrap_or_else(EditRope::empty);
1530 let id = Cow::from(&id);
1531
1532 match id.chars().next() {
1533 // Complete room aliases.
1534 Some('#') => {
1535 return store.application.names.complete(id.as_ref());
1536 },
1537
1538 // Complete room identifiers.
1539 Some('!') => {
1540 return store
1541 .application
1542 .rooms
1543 .complete(id.as_ref())
1544 .into_iter()
1545 .map(|i| i.to_string())
1546 .collect();
1547 },
1548
1549 // Complete Emoji shortcodes.
1550 Some(':') => {
1551 let list = store.application.emojis.complete(&id[1..]);
1552 let iter = list.into_iter().take(200).map(|s| format!(":{}:", s));
1553
1554 return iter.collect();
1555 },
1556
1557 // Complete usernames for @ and empty strings.
1558 Some('@') | None => {
1559 return store
1560 .application
1561 .presences
1562 .complete(id.as_ref())
1563 .into_iter()
1564 .map(|i| i.to_string())
1565 .collect();
1566 },
1567
1568 // Unknown sigil.
1569 Some(_) => return vec![],
1570 }
1571}
1572
1573/// Tab completion for Matrix identifiers (usernames, room aliases, etc.)
1574fn complete_matrix_names(
1575 text: &EditRope,
1576 cursor: &mut Cursor,
1577 store: &ProgramStore,
1578) -> 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 let list = store.application.names.complete(id.as_ref());
1585 if !list.is_empty() {
1586 return list;
1587 }
1588
1589 let list = store.application.presences.complete(id.as_ref());
1590 if !list.is_empty() {
1591 return list.into_iter().map(|i| i.to_string()).collect();
1592 }
1593
1594 store
1595 .application
1596 .rooms
1597 .complete(id.as_ref())
1598 .into_iter()
1599 .map(|i| i.to_string())
1600 .collect()
1601}
1602
1603/// Tab completion for Emoji shortcode names.
1604fn complete_emoji(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
1605 let sc = text.get_prefix_word_mut(cursor, &WordStyle::Little);
1606 let sc = sc.unwrap_or_else(EditRope::empty);
1607 let sc = Cow::from(&sc);
1608
1609 store.application.emojis.complete(sc.as_ref())
1610}
1611
1612/// Tab completion for command names.
1613fn complete_cmdname(
1614 desc: CommandDescription,
1615 text: &EditRope,
1616 cursor: &mut Cursor,
1617 store: &ProgramStore,
1618) -> Vec<String> {
1619 // Complete command name and set cursor position.
1620 let _ = text.get_prefix_word_mut(cursor, &WordStyle::Little);
1621 store.application.cmds.complete_name(desc.command.as_str())
1622}
1623
1624/// Tab completion for command arguments.
1625fn complete_cmdarg(
1626 desc: CommandDescription,
1627 text: &EditRope,
1628 cursor: &mut Cursor,
1629 store: &ProgramStore,
1630) -> Vec<String> {
1631 let cmd = match store.application.cmds.get(desc.command.as_str()) {
1632 Ok(cmd) => cmd,
1633 Err(_) => return vec![],
1634 };
1635
1636 match cmd.name.as_str() {
1637 "cancel" | "dms" | "edit" | "redact" | "reply" => vec![],
1638 "members" | "rooms" | "spaces" | "welcome" => vec![],
1639 "download" | "open" | "upload" => complete_path(text, cursor),
1640 "react" | "unreact" => complete_emoji(text, cursor, store),
1641
1642 "invite" => complete_users(text, cursor, store),
1643 "join" | "split" | "vsplit" | "tabedit" => complete_matrix_names(text, cursor, store),
1644 "room" => vec![],
1645 "verify" => vec![],
1646 "vertical" | "horizontal" | "aboveleft" | "belowright" | "tab" => {
1647 complete_cmd(desc.arg.text.as_str(), text, cursor, store)
1648 },
1649 _ => vec![],
1650 }
1651}
1652
1653/// Tab completion for commands.
1654fn complete_cmd(
1655 cmd: &str,
1656 text: &EditRope,
1657 cursor: &mut Cursor,
1658 store: &ProgramStore,
1659) -> Vec<String> {
1660 match CommandDescription::from_str(cmd) {
1661 Ok(desc) => {
1662 if desc.arg.untrimmed.is_empty() {
1663 complete_cmdname(desc, text, cursor, store)
1664 } else {
1665 // Complete command argument.
1666 complete_cmdarg(desc, text, cursor, store)
1667 }
1668 },
1669
1670 // Can't parse command text, so return zero completions.
1671 Err(_) => vec![],
1672 }
1673}
1674
1675/// Tab completion for the command bar.
1676fn complete_cmdbar(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
1677 let eo = text.cursor_to_offset(cursor);
1678 let slice = text.slice(..eo);
1679 let cow = Cow::from(&slice);
1680
1681 complete_cmd(cow.as_ref(), text, cursor, store)
1682}
1683
1684#[cfg(test)]
1685pub mod tests {
1686 use super::*;
1687 use crate::config::user_style_from_color;
1688 use crate::tests::*;
1689 use ratatui::style::Color;
1690
1691 #[test]
1692 fn test_typing_spans() {
1693 let mut info = RoomInfo::default();
1694 let settings = mock_settings();
1695
1696 let users0 = vec![];
1697 let users1 = vec![TEST_USER1.clone()];
1698 let users2 = vec![TEST_USER1.clone(), TEST_USER2.clone()];
1699 let users4 = vec![
1700 TEST_USER1.clone(),
1701 TEST_USER2.clone(),
1702 TEST_USER3.clone(),
1703 TEST_USER4.clone(),
1704 ];
1705 let users5 = vec![
1706 TEST_USER1.clone(),
1707 TEST_USER2.clone(),
1708 TEST_USER3.clone(),
1709 TEST_USER4.clone(),
1710 TEST_USER5.clone(),
1711 ];
1712
1713 // Nothing set.
1714 assert_eq!(info.users_typing, None);
1715 assert_eq!(info.get_typing_spans(&settings), Line::from(vec![]));
1716
1717 // Empty typing list.
1718 info.set_typing(users0);
1719 assert!(info.users_typing.is_some());
1720 assert_eq!(info.get_typing_spans(&settings), Line::from(vec![]));
1721
1722 // Single user typing.
1723 info.set_typing(users1);
1724 assert!(info.users_typing.is_some());
1725 assert_eq!(
1726 info.get_typing_spans(&settings),
1727 Line::from(vec![
1728 Span::styled("@user1:example.com", user_style("@user1:example.com")),
1729 Span::from(" is typing...")
1730 ])
1731 );
1732
1733 // Two users typing.
1734 info.set_typing(users2);
1735 assert!(info.users_typing.is_some());
1736 assert_eq!(
1737 info.get_typing_spans(&settings),
1738 Line::from(vec![
1739 Span::styled("@user1:example.com", user_style("@user1:example.com")),
1740 Span::raw(" and "),
1741 Span::styled("@user2:example.com", user_style("@user2:example.com")),
1742 Span::raw(" are typing...")
1743 ])
1744 );
1745
1746 // Four users typing.
1747 info.set_typing(users4);
1748 assert!(info.users_typing.is_some());
1749 assert_eq!(info.get_typing_spans(&settings), Line::from("Several people are typing..."));
1750
1751 // Five users typing.
1752 info.set_typing(users5);
1753 assert!(info.users_typing.is_some());
1754 assert_eq!(info.get_typing_spans(&settings), Line::from("Many people are typing..."));
1755
1756 // Test that USER5 gets rendered using the configured color and name.
1757 info.set_typing(vec![TEST_USER5.clone()]);
1758 assert!(info.users_typing.is_some());
1759 assert_eq!(
1760 info.get_typing_spans(&settings),
1761 Line::from(vec![
1762 Span::styled("USER 5", user_style_from_color(Color::Black)),
1763 Span::from(" is typing...")
1764 ])
1765 );
1766 }
1767
1768 #[test]
1769 fn test_need_load() {
1770 let room_id = TEST_ROOM1_ID.clone();
1771
1772 let mut need_load = RoomNeeds::default();
1773
1774 need_load.insert(room_id.clone(), Need::MESSAGES);
1775 need_load.insert(room_id.clone(), Need::MEMBERS);
1776
1777 assert_eq!(need_load.into_iter().collect::<Vec<(OwnedRoomId, Need)>>(), vec![(
1778 room_id,
1779 Need::MESSAGES | Need::MEMBERS,
1780 )],);
1781 }
1782
1783 #[tokio::test]
1784 async fn test_complete_msgbar() {
1785 let store = mock_store().await;
1786
1787 let text = EditRope::from("going for a walk :walk ");
1788 let mut cursor = Cursor::new(0, 22);
1789 let res = complete_msgbar(&text, &mut cursor, &store);
1790 assert_eq!(res, vec![":walking:", ":walking_man:", ":walking_woman:"]);
1791 assert_eq!(cursor, Cursor::new(0, 17));
1792
1793 let text = EditRope::from("hello @user1 ");
1794 let mut cursor = Cursor::new(0, 12);
1795 let res = complete_msgbar(&text, &mut cursor, &store);
1796 assert_eq!(res, vec!["@user1:example.com"]);
1797 assert_eq!(cursor, Cursor::new(0, 6));
1798
1799 let text = EditRope::from("see #room ");
1800 let mut cursor = Cursor::new(0, 9);
1801 let res = complete_msgbar(&text, &mut cursor, &store);
1802 assert_eq!(res, vec!["#room1:example.com"]);
1803 assert_eq!(cursor, Cursor::new(0, 4));
1804 }
1805
1806 #[tokio::test]
1807 async fn test_complete_cmdbar() {
1808 let store = mock_store().await;
1809 let users = vec![
1810 "@user1:example.com",
1811 "@user2:example.com",
1812 "@user3:example.com",
1813 "@user4:example.com",
1814 "@user5:example.com",
1815 ];
1816
1817 let text = EditRope::from("invite ");
1818 let mut cursor = Cursor::new(0, 7);
1819 let id = text
1820 .get_prefix_word_mut(&mut cursor, &MATRIX_ID_WORD)
1821 .unwrap_or_else(EditRope::empty);
1822 assert_eq!(id.to_string(), "");
1823 assert_eq!(cursor, Cursor::new(0, 7));
1824
1825 let text = EditRope::from("invite ");
1826 let mut cursor = Cursor::new(0, 7);
1827 let res = complete_cmdbar(&text, &mut cursor, &store);
1828 assert_eq!(res, users);
1829
1830 let text = EditRope::from("invite ignored");
1831 let mut cursor = Cursor::new(0, 7);
1832 let res = complete_cmdbar(&text, &mut cursor, &store);
1833 assert_eq!(res, users);
1834
1835 let text = EditRope::from("invite @user1ignored");
1836 let mut cursor = Cursor::new(0, 13);
1837 let res = complete_cmdbar(&text, &mut cursor, &store);
1838 assert_eq!(res, vec!["@user1:example.com"]);
1839
1840 let text = EditRope::from("abo hor");
1841 let mut cursor = Cursor::new(0, 7);
1842 let res = complete_cmdbar(&text, &mut cursor, &store);
1843 assert_eq!(res, vec!["horizontal"]);
1844
1845 let text = EditRope::from("abo hor inv");
1846 let mut cursor = Cursor::new(0, 11);
1847 let res = complete_cmdbar(&text, &mut cursor, &store);
1848 assert_eq!(res, vec!["invite"]);
1849
1850 let text = EditRope::from("abo hor invite \n");
1851 let mut cursor = Cursor::new(0, 15);
1852 let res = complete_cmdbar(&text, &mut cursor, &store);
1853 assert_eq!(res, users);
1854 }
1855}