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