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