src/base.rs
1063 lines · 31378 bytes
1use std::borrow::Cow;
2use std::collections::{HashMap, HashSet};
3use std::hash::Hash;
4use std::str::FromStr;
5use std::sync::Arc;
6use std::time::{Duration, Instant};
7
8use emojis::Emoji;
9use tokio::sync::Mutex as AsyncMutex;
10
11use matrix_sdk::{
12 encryption::verification::SasVerification,
13 room::Joined,
14 ruma::{
15 events::{
16 reaction::ReactionEvent,
17 room::encrypted::RoomEncryptedEvent,
18 room::message::{
19 OriginalRoomMessageEvent,
20 Relation,
21 Replacement,
22 RoomMessageEvent,
23 RoomMessageEventContent,
24 },
25 tag::{TagName, Tags},
26 MessageLikeEvent,
27 },
28 presence::PresenceState,
29 EventId,
30 OwnedEventId,
31 OwnedRoomId,
32 OwnedUserId,
33 RoomId,
34 },
35};
36
37use modalkit::{
38 editing::{
39 action::{Action, UIError, UIResult},
40 application::{
41 ApplicationAction,
42 ApplicationContentId,
43 ApplicationError,
44 ApplicationInfo,
45 ApplicationStore,
46 ApplicationWindowId,
47 },
48 base::{CommandType, WordStyle},
49 completion::{complete_path, CompletionMap},
50 context::EditContext,
51 cursor::Cursor,
52 rope::EditRope,
53 store::Store,
54 },
55 env::vim::{
56 command::{CommandContext, CommandDescription, VimCommand, VimCommandMachine},
57 keybindings::VimMachine,
58 VimContext,
59 },
60 input::bindings::SequenceStatus,
61 input::key::TerminalKey,
62 tui::{
63 buffer::Buffer,
64 layout::{Alignment, Rect},
65 text::{Span, Spans},
66 widgets::{Paragraph, Widget},
67 },
68};
69
70use crate::{
71 message::{Message, MessageEvent, MessageKey, MessageTimeStamp, Messages},
72 worker::Requester,
73 ApplicationSettings,
74};
75
76pub const MATRIX_ID_WORD: WordStyle = WordStyle::CharSet(is_mxid_char);
77
78/// Find the boundaries for a Matrix username, room alias, or room ID.
79///
80/// Technically "[" and "]" should be here since IPv6 addresses are allowed
81/// in the server name, but in practice that should be uncommon, and people
82/// can just use `gf` and friends in Visual mode instead.
83fn is_mxid_char(c: char) -> bool {
84 return c >= 'a' && c <= 'z' ||
85 c >= 'A' && c <= 'Z' ||
86 c >= '0' && c <= '9' ||
87 ":-./@_#!".contains(c);
88}
89
90const ROOM_FETCH_DEBOUNCE: Duration = Duration::from_secs(2);
91
92#[derive(Clone, Debug, Eq, PartialEq)]
93pub enum IambInfo {}
94
95#[derive(Clone, Debug, Eq, PartialEq)]
96pub enum VerifyAction {
97 Accept,
98 Cancel,
99 Confirm,
100 Mismatch,
101}
102
103#[derive(Clone, Debug, Eq, PartialEq)]
104pub enum MessageAction {
105 /// Cance the current reply or edit.
106 ///
107 /// The [bool] argument indicates whether to skip confirmation for clearing the message bar.
108 Cancel(bool),
109
110 /// Download an attachment to the given path.
111 ///
112 /// The second argument controls whether to overwrite any already existing file at the
113 /// destination path, or to open the attachment after downloading.
114 Download(Option<String>, DownloadFlags),
115
116 /// Edit a sent message.
117 Edit,
118
119 /// React to a message with an Emoji.
120 React(String),
121
122 /// Redact a message, with an optional reason.
123 ///
124 /// The [bool] argument indicates whether to skip confirmation.
125 Redact(Option<String>, bool),
126
127 /// Reply to a message.
128 Reply,
129
130 /// Unreact to a message.
131 ///
132 /// If no specific Emoji to remove to is specified, then all reactions from the user on the
133 /// message are removed.
134 Unreact(Option<String>),
135}
136
137#[derive(Clone, Debug, Eq, PartialEq)]
138pub enum CreateRoomType {
139 /// A direct message room.
140 Direct(OwnedUserId),
141
142 /// A standard chat room.
143 Room,
144
145 /// A Matrix space.
146 Space,
147}
148
149bitflags::bitflags! {
150 pub struct CreateRoomFlags: u32 {
151 const NONE = 0b00000000;
152
153 /// Make the room public.
154 const PUBLIC = 0b00000001;
155
156 /// Encrypt this room.
157 const ENCRYPTED = 0b00000010;
158 }
159}
160
161bitflags::bitflags! {
162 pub struct DownloadFlags: u32 {
163 const NONE = 0b00000000;
164
165 /// Overwrite file if it already exists.
166 const FORCE = 0b00000001;
167
168 /// Open file after downloading.
169 const OPEN = 0b00000010;
170 }
171}
172
173#[derive(Clone, Debug, Eq, PartialEq)]
174pub enum RoomField {
175 Name,
176 Tag(TagName),
177 Topic,
178}
179
180#[derive(Clone, Debug, Eq, PartialEq)]
181pub enum RoomAction {
182 InviteAccept,
183 InviteReject,
184 InviteSend(OwnedUserId),
185 Leave(bool),
186 Members(Box<CommandContext<ProgramContext>>),
187 Set(RoomField, String),
188 Unset(RoomField),
189}
190
191#[derive(Clone, Debug, Eq, PartialEq)]
192pub enum SendAction {
193 Submit,
194 Upload(String),
195 UploadImage(usize, usize, Cow<'static, [u8]>),
196}
197
198#[derive(Clone, Debug, Eq, PartialEq)]
199pub enum HomeserverAction {
200 CreateRoom(Option<String>, CreateRoomType, CreateRoomFlags),
201}
202
203#[derive(Clone, Debug, Eq, PartialEq)]
204pub enum IambAction {
205 Homeserver(HomeserverAction),
206 Message(MessageAction),
207 Room(RoomAction),
208 Send(SendAction),
209 Verify(VerifyAction, String),
210 VerifyRequest(String),
211 ToggleScrollbackFocus,
212}
213
214impl From<HomeserverAction> for IambAction {
215 fn from(act: HomeserverAction) -> Self {
216 IambAction::Homeserver(act)
217 }
218}
219
220impl From<MessageAction> for IambAction {
221 fn from(act: MessageAction) -> Self {
222 IambAction::Message(act)
223 }
224}
225
226impl From<RoomAction> for IambAction {
227 fn from(act: RoomAction) -> Self {
228 IambAction::Room(act)
229 }
230}
231
232impl From<SendAction> for IambAction {
233 fn from(act: SendAction) -> Self {
234 IambAction::Send(act)
235 }
236}
237
238impl ApplicationAction for IambAction {
239 fn is_edit_sequence<C: EditContext>(&self, _: &C) -> SequenceStatus {
240 match self {
241 IambAction::Homeserver(..) => SequenceStatus::Break,
242 IambAction::Message(..) => SequenceStatus::Break,
243 IambAction::Room(..) => SequenceStatus::Break,
244 IambAction::Send(..) => SequenceStatus::Break,
245 IambAction::ToggleScrollbackFocus => SequenceStatus::Break,
246 IambAction::Verify(..) => SequenceStatus::Break,
247 IambAction::VerifyRequest(..) => SequenceStatus::Break,
248 }
249 }
250
251 fn is_last_action<C: EditContext>(&self, _: &C) -> SequenceStatus {
252 match self {
253 IambAction::Homeserver(..) => SequenceStatus::Atom,
254 IambAction::Message(..) => SequenceStatus::Atom,
255 IambAction::Room(..) => SequenceStatus::Atom,
256 IambAction::Send(..) => SequenceStatus::Atom,
257 IambAction::ToggleScrollbackFocus => SequenceStatus::Atom,
258 IambAction::Verify(..) => SequenceStatus::Atom,
259 IambAction::VerifyRequest(..) => SequenceStatus::Atom,
260 }
261 }
262
263 fn is_last_selection<C: EditContext>(&self, _: &C) -> SequenceStatus {
264 match self {
265 IambAction::Homeserver(..) => SequenceStatus::Ignore,
266 IambAction::Message(..) => SequenceStatus::Ignore,
267 IambAction::Room(..) => SequenceStatus::Ignore,
268 IambAction::Send(..) => SequenceStatus::Ignore,
269 IambAction::ToggleScrollbackFocus => SequenceStatus::Ignore,
270 IambAction::Verify(..) => SequenceStatus::Ignore,
271 IambAction::VerifyRequest(..) => SequenceStatus::Ignore,
272 }
273 }
274
275 fn is_switchable<C: EditContext>(&self, _: &C) -> bool {
276 match self {
277 IambAction::Homeserver(..) => false,
278 IambAction::Message(..) => false,
279 IambAction::Room(..) => false,
280 IambAction::Send(..) => false,
281 IambAction::ToggleScrollbackFocus => false,
282 IambAction::Verify(..) => false,
283 IambAction::VerifyRequest(..) => false,
284 }
285 }
286}
287
288impl From<RoomAction> for ProgramAction {
289 fn from(act: RoomAction) -> Self {
290 IambAction::from(act).into()
291 }
292}
293
294impl From<IambAction> for ProgramAction {
295 fn from(act: IambAction) -> Self {
296 Action::Application(act)
297 }
298}
299
300pub type ProgramAction = Action<IambInfo>;
301pub type ProgramContext = VimContext<IambInfo>;
302pub type Keybindings = VimMachine<TerminalKey, IambInfo>;
303pub type ProgramCommand = VimCommand<ProgramContext, IambInfo>;
304pub type ProgramCommands = VimCommandMachine<ProgramContext, IambInfo>;
305pub type ProgramStore = Store<IambInfo>;
306pub type AsyncProgramStore = Arc<AsyncMutex<ProgramStore>>;
307
308pub type IambResult<T> = UIResult<T, IambInfo>;
309
310/// Reaction events for some message.
311///
312/// The event identifier used as a key here is the ID for the reaction, and not for the message
313/// it's reacting to.
314pub type MessageReactions = HashMap<OwnedEventId, (String, OwnedUserId)>;
315
316pub type Receipts = HashMap<OwnedEventId, Vec<OwnedUserId>>;
317
318#[derive(thiserror::Error, Debug)]
319pub enum IambError {
320 #[error("Invalid user identifier: {0}")]
321 InvalidUserId(String),
322
323 #[error("Invalid verification user/device pair: {0}")]
324 InvalidVerificationId(String),
325
326 #[error("Cryptographic storage error: {0}")]
327 CryptoStore(#[from] matrix_sdk::encryption::CryptoStoreError),
328
329 #[error("HTTP client error: {0}")]
330 Http(#[from] matrix_sdk::HttpError),
331
332 #[error("Matrix client error: {0}")]
333 Matrix(#[from] matrix_sdk::Error),
334
335 #[error("Matrix client storage error: {0}")]
336 Store(#[from] matrix_sdk::StoreError),
337
338 #[error("Serialization/deserialization error: {0}")]
339 Serde(#[from] serde_json::Error),
340
341 #[error("Selected message does not have any attachments")]
342 NoAttachment,
343
344 #[error("No message currently selected")]
345 NoSelectedMessage,
346
347 #[error("Current window is not a room or space")]
348 NoSelectedRoomOrSpace,
349
350 #[error("Current window is not a room")]
351 NoSelectedRoom,
352
353 #[error("You do not have a current invitation to this room")]
354 NotInvited,
355
356 #[error("You need to join the room before you can do that")]
357 NotJoined,
358
359 #[error("Unknown room identifier: {0}")]
360 UnknownRoom(OwnedRoomId),
361
362 #[error("Verification request error: {0}")]
363 VerificationRequestError(#[from] matrix_sdk::encryption::identities::RequestVerificationError),
364
365 #[error("Image error: {0}")]
366 Image(#[from] image::ImageError),
367
368 #[error("Could not use system clipboard data")]
369 Clipboard,
370}
371
372impl From<IambError> for UIError<IambInfo> {
373 fn from(err: IambError) -> Self {
374 UIError::Application(err)
375 }
376}
377
378impl ApplicationError for IambError {}
379
380#[derive(Default)]
381pub enum RoomFetchStatus {
382 Done,
383 HaveMore(String),
384 #[default]
385 NotStarted,
386}
387
388pub enum EventLocation {
389 Message(MessageKey),
390 Reaction(OwnedEventId),
391}
392
393impl EventLocation {
394 fn to_message_key(&self) -> Option<&MessageKey> {
395 if let EventLocation::Message(key) = self {
396 Some(key)
397 } else {
398 None
399 }
400 }
401}
402
403#[derive(Default)]
404pub struct RoomInfo {
405 /// The display name for this room.
406 pub name: Option<String>,
407
408 /// The tags placed on this room.
409 pub tags: Option<Tags>,
410
411 /// A map of event IDs to where they are stored in this struct.
412 pub keys: HashMap<OwnedEventId, EventLocation>,
413
414 /// The messages loaded for this room.
415 pub messages: Messages,
416
417 /// A map of read markers to display on different events.
418 pub receipts: HashMap<OwnedEventId, Vec<OwnedUserId>>,
419
420 /// An event ID for where we should indicate we've read up to.
421 pub read_till: Option<OwnedEventId>,
422
423 /// A map of message identifiers to a map of reaction events.
424 pub reactions: HashMap<OwnedEventId, MessageReactions>,
425
426 /// Whether the scrollback for this room is currently being fetched.
427 pub fetching: bool,
428
429 /// Where to continue fetching from when we continue loading scrollback history.
430 pub fetch_id: RoomFetchStatus,
431
432 /// The time that we last fetched scrollback for this room.
433 pub fetch_last: Option<Instant>,
434
435 /// Users currently typing in this room, and when we received notification of them doing so.
436 pub users_typing: Option<(Instant, Vec<OwnedUserId>)>,
437}
438
439impl RoomInfo {
440 pub fn get_reactions(&self, event_id: &EventId) -> Vec<(&str, usize)> {
441 if let Some(reacts) = self.reactions.get(event_id) {
442 let mut counts = HashMap::new();
443
444 for (key, _) in reacts.values() {
445 let count = counts.entry(key.as_str()).or_default();
446 *count += 1;
447 }
448
449 let mut reactions = counts.into_iter().collect::<Vec<_>>();
450 reactions.sort();
451
452 reactions
453 } else {
454 vec![]
455 }
456 }
457
458 pub fn get_message_key(&self, event_id: &EventId) -> Option<&MessageKey> {
459 self.keys.get(event_id)?.to_message_key()
460 }
461
462 pub fn get_event(&self, event_id: &EventId) -> Option<&Message> {
463 self.messages.get(self.get_message_key(event_id)?)
464 }
465
466 pub fn insert_reaction(&mut self, react: ReactionEvent) {
467 match react {
468 MessageLikeEvent::Original(react) => {
469 let rel_id = react.content.relates_to.event_id;
470 let key = react.content.relates_to.key;
471
472 let message = self.reactions.entry(rel_id.clone()).or_default();
473 let event_id = react.event_id;
474 let user_id = react.sender;
475
476 message.insert(event_id.clone(), (key, user_id));
477
478 let loc = EventLocation::Reaction(rel_id);
479 self.keys.insert(event_id, loc);
480 },
481 MessageLikeEvent::Redacted(_) => {
482 return;
483 },
484 }
485 }
486
487 pub fn insert_edit(&mut self, msg: Replacement) {
488 let event_id = msg.event_id;
489 let new_content = msg.new_content;
490
491 let key = if let Some(EventLocation::Message(k)) = self.keys.get(&event_id) {
492 k
493 } else {
494 return;
495 };
496
497 let msg = if let Some(msg) = self.messages.get_mut(key) {
498 msg
499 } else {
500 return;
501 };
502
503 match &mut msg.event {
504 MessageEvent::Original(orig) => {
505 orig.content.msgtype = new_content.msgtype;
506 },
507 MessageEvent::Local(_, content) => {
508 content.msgtype = new_content.msgtype;
509 },
510 MessageEvent::Redacted(_) |
511 MessageEvent::EncryptedOriginal(_) |
512 MessageEvent::EncryptedRedacted(_) => {
513 return;
514 },
515 }
516
517 msg.html = msg.event.html();
518 }
519
520 /// Inserts events that couldn't be decrypted into the scrollback.
521 pub fn insert_encrypted(&mut self, msg: RoomEncryptedEvent) {
522 let event_id = msg.event_id().to_owned();
523 let key = (msg.origin_server_ts().into(), event_id.clone());
524
525 self.keys.insert(event_id, EventLocation::Message(key.clone()));
526 self.messages.insert(key, msg.into());
527 }
528
529 pub fn insert_message(&mut self, msg: RoomMessageEvent) {
530 let event_id = msg.event_id().to_owned();
531 let key = (msg.origin_server_ts().into(), event_id.clone());
532
533 self.keys.insert(event_id.clone(), EventLocation::Message(key.clone()));
534 self.messages.insert(key, msg.into());
535
536 // Remove any echo.
537 let key = (MessageTimeStamp::LocalEcho, event_id);
538 let _ = self.messages.remove(&key);
539 }
540
541 pub fn insert(&mut self, msg: RoomMessageEvent) {
542 match msg {
543 RoomMessageEvent::Original(OriginalRoomMessageEvent {
544 content:
545 RoomMessageEventContent { relates_to: Some(Relation::Replacement(repl)), .. },
546 ..
547 }) => self.insert_edit(repl),
548 _ => self.insert_message(msg),
549 }
550 }
551
552 pub fn recently_fetched(&self) -> bool {
553 self.fetch_last.map_or(false, |i| i.elapsed() < ROOM_FETCH_DEBOUNCE)
554 }
555
556 fn get_typers(&self) -> &[OwnedUserId] {
557 if let Some((t, users)) = &self.users_typing {
558 if t.elapsed() < Duration::from_secs(4) {
559 return users.as_ref();
560 } else {
561 return &[];
562 }
563 } else {
564 return &[];
565 }
566 }
567
568 fn get_typing_spans<'a>(&'a self, settings: &'a ApplicationSettings) -> Spans<'a> {
569 let typers = self.get_typers();
570 let n = typers.len();
571
572 match n {
573 0 => Spans(vec![]),
574 1 => {
575 let user = settings.get_user_span(typers[0].as_ref());
576
577 Spans(vec![user, Span::from(" is typing...")])
578 },
579 2 => {
580 let user1 = settings.get_user_span(typers[0].as_ref());
581 let user2 = settings.get_user_span(typers[1].as_ref());
582
583 Spans(vec![
584 user1,
585 Span::raw(" and "),
586 user2,
587 Span::from(" are typing..."),
588 ])
589 },
590 n if n < 5 => Spans::from("Several people are typing..."),
591 _ => Spans::from("Many people are typing..."),
592 }
593 }
594
595 pub fn set_typing(&mut self, user_ids: Vec<OwnedUserId>) {
596 self.users_typing = (Instant::now(), user_ids).into();
597 }
598
599 pub fn render_typing(
600 &mut self,
601 area: Rect,
602 buf: &mut Buffer,
603 settings: &ApplicationSettings,
604 ) -> Rect {
605 if area.height <= 2 || area.width <= 20 {
606 return area;
607 }
608
609 if !settings.tunables.typing_notice_display {
610 return area;
611 }
612
613 let top = Rect::new(area.x, area.y, area.width, area.height - 1);
614 let bar = Rect::new(area.x, area.y + top.height, area.width, 1);
615
616 Paragraph::new(self.get_typing_spans(settings))
617 .alignment(Alignment::Center)
618 .render(bar, buf);
619
620 return top;
621 }
622}
623
624fn emoji_map() -> CompletionMap<String, &'static Emoji> {
625 let mut emojis = CompletionMap::default();
626
627 for emoji in emojis::iter() {
628 for shortcode in emoji.shortcodes() {
629 emojis.insert(shortcode.to_string(), emoji);
630 }
631 }
632
633 return emojis;
634}
635
636pub struct ChatStore {
637 pub cmds: ProgramCommands,
638 pub worker: Requester,
639 pub rooms: CompletionMap<OwnedRoomId, RoomInfo>,
640 pub names: CompletionMap<String, OwnedRoomId>,
641 pub presences: CompletionMap<OwnedUserId, PresenceState>,
642 pub verifications: HashMap<String, SasVerification>,
643 pub settings: ApplicationSettings,
644 pub need_load: HashSet<OwnedRoomId>,
645 pub emojis: CompletionMap<String, &'static Emoji>,
646}
647
648impl ChatStore {
649 pub fn new(worker: Requester, settings: ApplicationSettings) -> Self {
650 ChatStore {
651 worker,
652 settings,
653
654 cmds: crate::commands::setup_commands(),
655 names: Default::default(),
656 rooms: Default::default(),
657 presences: Default::default(),
658 verifications: Default::default(),
659 need_load: Default::default(),
660 emojis: emoji_map(),
661 }
662 }
663
664 pub fn get_joined_room(&self, room_id: &RoomId) -> Option<Joined> {
665 self.worker.client.get_joined_room(room_id)
666 }
667
668 pub fn get_room_title(&self, room_id: &RoomId) -> String {
669 self.rooms
670 .get(room_id)
671 .and_then(|i| i.name.as_ref())
672 .map(String::from)
673 .unwrap_or_else(|| "Untitled Matrix Room".to_string())
674 }
675
676 pub async fn set_receipts(
677 &mut self,
678 receipts: Vec<(OwnedRoomId, Receipts)>,
679 ) -> Vec<(OwnedRoomId, OwnedEventId)> {
680 let mut updates = vec![];
681
682 for (room_id, receipts) in receipts.into_iter() {
683 if let Some(info) = self.rooms.get_mut(&room_id) {
684 info.receipts = receipts;
685
686 if let Some(read_till) = info.read_till.take() {
687 updates.push((room_id, read_till));
688 }
689 }
690 }
691
692 return updates;
693 }
694
695 pub fn mark_for_load(&mut self, room_id: OwnedRoomId) {
696 self.need_load.insert(room_id);
697 }
698
699 pub fn get_room_info(&mut self, room_id: OwnedRoomId) -> &mut RoomInfo {
700 self.rooms.get_or_default(room_id)
701 }
702
703 pub fn set_room_name(&mut self, room_id: &RoomId, name: &str) {
704 self.rooms.get_or_default(room_id.to_owned()).name = name.to_string().into();
705 }
706
707 pub fn insert_sas(&mut self, sas: SasVerification) {
708 let key = format!("{}/{}", sas.other_user_id(), sas.other_device().device_id());
709
710 self.verifications.insert(key, sas);
711 }
712}
713
714impl ApplicationStore for ChatStore {}
715
716#[derive(Clone, Debug, Eq, Hash, PartialEq)]
717pub enum IambId {
718 Room(OwnedRoomId),
719 DirectList,
720 MemberList(OwnedRoomId),
721 RoomList,
722 SpaceList,
723 VerifyList,
724 Welcome,
725}
726
727impl ApplicationWindowId for IambId {}
728
729#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
730pub enum RoomFocus {
731 Scrollback,
732 MessageBar,
733}
734
735impl RoomFocus {
736 pub fn is_scrollback(&self) -> bool {
737 matches!(self, RoomFocus::Scrollback)
738 }
739
740 pub fn is_msgbar(&self) -> bool {
741 matches!(self, RoomFocus::MessageBar)
742 }
743}
744
745#[derive(Clone, Debug, Eq, Hash, PartialEq)]
746pub enum IambBufferId {
747 Command(CommandType),
748 Room(OwnedRoomId, RoomFocus),
749 DirectList,
750 MemberList(OwnedRoomId),
751 RoomList,
752 SpaceList,
753 VerifyList,
754 Welcome,
755}
756
757impl IambBufferId {
758 pub fn to_window(&self) -> Option<IambId> {
759 match self {
760 IambBufferId::Command(_) => None,
761 IambBufferId::Room(room, _) => Some(IambId::Room(room.clone())),
762 IambBufferId::DirectList => Some(IambId::DirectList),
763 IambBufferId::MemberList(room) => Some(IambId::MemberList(room.clone())),
764 IambBufferId::RoomList => Some(IambId::RoomList),
765 IambBufferId::SpaceList => Some(IambId::SpaceList),
766 IambBufferId::VerifyList => Some(IambId::VerifyList),
767 IambBufferId::Welcome => Some(IambId::Welcome),
768 }
769 }
770}
771
772impl ApplicationContentId for IambBufferId {}
773
774impl ApplicationInfo for IambInfo {
775 type Error = IambError;
776 type Store = ChatStore;
777 type Action = IambAction;
778 type WindowId = IambId;
779 type ContentId = IambBufferId;
780
781 fn complete(
782 text: &EditRope,
783 cursor: &mut Cursor,
784 content: &IambBufferId,
785 store: &mut ProgramStore,
786 ) -> Vec<String> {
787 match content {
788 IambBufferId::Command(CommandType::Command) => complete_cmdbar(text, cursor, store),
789 IambBufferId::Command(CommandType::Search) => vec![],
790
791 IambBufferId::Room(_, RoomFocus::MessageBar) => {
792 complete_matrix_names(text, cursor, store)
793 },
794 IambBufferId::Room(_, RoomFocus::Scrollback) => vec![],
795
796 IambBufferId::DirectList => vec![],
797 IambBufferId::MemberList(_) => vec![],
798 IambBufferId::RoomList => vec![],
799 IambBufferId::SpaceList => vec![],
800 IambBufferId::VerifyList => vec![],
801 IambBufferId::Welcome => vec![],
802 }
803 }
804
805 fn content_of_command(ct: CommandType) -> IambBufferId {
806 IambBufferId::Command(ct)
807 }
808}
809
810fn complete_users(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
811 let id = text
812 .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
813 .unwrap_or_else(EditRope::empty);
814 let id = Cow::from(&id);
815
816 store
817 .application
818 .presences
819 .complete(id.as_ref())
820 .into_iter()
821 .map(|i| i.to_string())
822 .collect()
823}
824
825fn complete_matrix_names(
826 text: &EditRope,
827 cursor: &mut Cursor,
828 store: &ProgramStore,
829) -> Vec<String> {
830 let id = text
831 .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
832 .unwrap_or_else(EditRope::empty);
833 let id = Cow::from(&id);
834
835 let list = store.application.names.complete(id.as_ref());
836 if !list.is_empty() {
837 return list;
838 }
839
840 let list = store.application.presences.complete(id.as_ref());
841 if !list.is_empty() {
842 return list.into_iter().map(|i| i.to_string()).collect();
843 }
844
845 store
846 .application
847 .rooms
848 .complete(id.as_ref())
849 .into_iter()
850 .map(|i| i.to_string())
851 .collect()
852}
853
854fn complete_emoji(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
855 let sc = text.get_prefix_word_mut(cursor, &WordStyle::Little);
856 let sc = sc.unwrap_or_else(EditRope::empty);
857 let sc = Cow::from(&sc);
858
859 store.application.emojis.complete(sc.as_ref())
860}
861
862fn complete_cmdname(
863 desc: CommandDescription,
864 text: &EditRope,
865 cursor: &mut Cursor,
866 store: &ProgramStore,
867) -> Vec<String> {
868 // Complete command name and set cursor position.
869 let _ = text.get_prefix_word_mut(cursor, &WordStyle::Little);
870 store.application.cmds.complete_name(desc.command.as_str())
871}
872
873fn complete_cmdarg(
874 desc: CommandDescription,
875 text: &EditRope,
876 cursor: &mut Cursor,
877 store: &ProgramStore,
878) -> Vec<String> {
879 let cmd = match store.application.cmds.get(desc.command.as_str()) {
880 Ok(cmd) => cmd,
881 Err(_) => return vec![],
882 };
883
884 match cmd.name.as_str() {
885 "cancel" | "dms" | "edit" | "redact" | "reply" => vec![],
886 "members" | "rooms" | "spaces" | "welcome" => vec![],
887 "download" | "open" | "upload" => complete_path(text, cursor),
888 "react" | "unreact" => complete_emoji(text, cursor, store),
889
890 "invite" => complete_users(text, cursor, store),
891 "join" | "split" | "vsplit" | "tabedit" => complete_matrix_names(text, cursor, store),
892 "room" => vec![],
893 "verify" => vec![],
894 "vertical" | "horizontal" | "aboveleft" | "belowright" | "tab" => {
895 complete_cmd(desc.arg.text.as_str(), text, cursor, store)
896 },
897 _ => vec![],
898 }
899}
900
901fn complete_cmd(
902 cmd: &str,
903 text: &EditRope,
904 cursor: &mut Cursor,
905 store: &ProgramStore,
906) -> Vec<String> {
907 match CommandDescription::from_str(cmd) {
908 Ok(desc) => {
909 if desc.arg.untrimmed.is_empty() {
910 complete_cmdname(desc, text, cursor, store)
911 } else {
912 // Complete command argument.
913 complete_cmdarg(desc, text, cursor, store)
914 }
915 },
916
917 // Can't parse command text, so return zero completions.
918 Err(_) => vec![],
919 }
920}
921
922fn complete_cmdbar(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
923 let eo = text.cursor_to_offset(cursor);
924 let slice = text.slice(0.into(), eo, false);
925 let cow = Cow::from(&slice);
926
927 complete_cmd(cow.as_ref(), text, cursor, store)
928}
929
930#[cfg(test)]
931pub mod tests {
932 use super::*;
933 use crate::config::user_style_from_color;
934 use crate::tests::*;
935 use modalkit::tui::style::Color;
936
937 #[test]
938 fn test_typing_spans() {
939 let mut info = RoomInfo::default();
940 let settings = mock_settings();
941
942 let users0 = vec![];
943 let users1 = vec![TEST_USER1.clone()];
944 let users2 = vec![TEST_USER1.clone(), TEST_USER2.clone()];
945 let users4 = vec![
946 TEST_USER1.clone(),
947 TEST_USER2.clone(),
948 TEST_USER3.clone(),
949 TEST_USER4.clone(),
950 ];
951 let users5 = vec![
952 TEST_USER1.clone(),
953 TEST_USER2.clone(),
954 TEST_USER3.clone(),
955 TEST_USER4.clone(),
956 TEST_USER5.clone(),
957 ];
958
959 // Nothing set.
960 assert_eq!(info.users_typing, None);
961 assert_eq!(info.get_typing_spans(&settings), Spans(vec![]));
962
963 // Empty typing list.
964 info.set_typing(users0);
965 assert!(info.users_typing.is_some());
966 assert_eq!(info.get_typing_spans(&settings), Spans(vec![]));
967
968 // Single user typing.
969 info.set_typing(users1);
970 assert!(info.users_typing.is_some());
971 assert_eq!(
972 info.get_typing_spans(&settings),
973 Spans(vec![
974 Span::styled("@user1:example.com", user_style("@user1:example.com")),
975 Span::from(" is typing...")
976 ])
977 );
978
979 // Two users typing.
980 info.set_typing(users2);
981 assert!(info.users_typing.is_some());
982 assert_eq!(
983 info.get_typing_spans(&settings),
984 Spans(vec![
985 Span::styled("@user1:example.com", user_style("@user1:example.com")),
986 Span::raw(" and "),
987 Span::styled("@user2:example.com", user_style("@user2:example.com")),
988 Span::raw(" are typing...")
989 ])
990 );
991
992 // Four users typing.
993 info.set_typing(users4);
994 assert!(info.users_typing.is_some());
995 assert_eq!(info.get_typing_spans(&settings), Spans::from("Several people are typing..."));
996
997 // Five users typing.
998 info.set_typing(users5);
999 assert!(info.users_typing.is_some());
1000 assert_eq!(info.get_typing_spans(&settings), Spans::from("Many people are typing..."));
1001
1002 // Test that USER5 gets rendered using the configured color and name.
1003 info.set_typing(vec![TEST_USER5.clone()]);
1004 assert!(info.users_typing.is_some());
1005 assert_eq!(
1006 info.get_typing_spans(&settings),
1007 Spans(vec![
1008 Span::styled("USER 5", user_style_from_color(Color::Black)),
1009 Span::from(" is typing...")
1010 ])
1011 );
1012 }
1013
1014 #[tokio::test]
1015 async fn test_complete_cmdbar() {
1016 let store = mock_store().await;
1017 let users = vec![
1018 "@user1:example.com",
1019 "@user2:example.com",
1020 "@user3:example.com",
1021 "@user4:example.com",
1022 "@user5:example.com",
1023 ];
1024
1025 let text = EditRope::from("invite ");
1026 let mut cursor = Cursor::new(0, 7);
1027 let id = text
1028 .get_prefix_word_mut(&mut cursor, &MATRIX_ID_WORD)
1029 .unwrap_or_else(EditRope::empty);
1030 assert_eq!(id.to_string(), "");
1031 assert_eq!(cursor, Cursor::new(0, 7));
1032
1033 let text = EditRope::from("invite ");
1034 let mut cursor = Cursor::new(0, 7);
1035 let res = complete_cmdbar(&text, &mut cursor, &store);
1036 assert_eq!(res, users);
1037
1038 let text = EditRope::from("invite ignored");
1039 let mut cursor = Cursor::new(0, 7);
1040 let res = complete_cmdbar(&text, &mut cursor, &store);
1041 assert_eq!(res, users);
1042
1043 let text = EditRope::from("invite @user1ignored");
1044 let mut cursor = Cursor::new(0, 13);
1045 let res = complete_cmdbar(&text, &mut cursor, &store);
1046 assert_eq!(res, vec!["@user1:example.com"]);
1047
1048 let text = EditRope::from("abo hor");
1049 let mut cursor = Cursor::new(0, 7);
1050 let res = complete_cmdbar(&text, &mut cursor, &store);
1051 assert_eq!(res, vec!["horizontal"]);
1052
1053 let text = EditRope::from("abo hor inv");
1054 let mut cursor = Cursor::new(0, 11);
1055 let res = complete_cmdbar(&text, &mut cursor, &store);
1056 assert_eq!(res, vec!["invite"]);
1057
1058 let text = EditRope::from("abo hor invite \n");
1059 let mut cursor = Cursor::new(0, 15);
1060 let res = complete_cmdbar(&text, &mut cursor, &store);
1061 assert_eq!(res, users);
1062 }
1063}