src/base.rs
1056 lines · 31187 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(
670 &mut self,
671 receipts: Vec<(OwnedRoomId, Receipts)>,
672 ) -> Vec<(OwnedRoomId, OwnedEventId)> {
673 let mut updates = vec![];
674
675 for (room_id, receipts) in receipts.into_iter() {
676 if let Some(info) = self.rooms.get_mut(&room_id) {
677 info.receipts = receipts;
678
679 if let Some(read_till) = info.read_till.take() {
680 updates.push((room_id, read_till));
681 }
682 }
683 }
684
685 return updates;
686 }
687
688 pub fn mark_for_load(&mut self, room_id: OwnedRoomId) {
689 self.need_load.insert(room_id);
690 }
691
692 pub fn get_room_info(&mut self, room_id: OwnedRoomId) -> &mut RoomInfo {
693 self.rooms.get_or_default(room_id)
694 }
695
696 pub fn set_room_name(&mut self, room_id: &RoomId, name: &str) {
697 self.rooms.get_or_default(room_id.to_owned()).name = name.to_string().into();
698 }
699
700 pub fn insert_sas(&mut self, sas: SasVerification) {
701 let key = format!("{}/{}", sas.other_user_id(), sas.other_device().device_id());
702
703 self.verifications.insert(key, sas);
704 }
705}
706
707impl ApplicationStore for ChatStore {}
708
709#[derive(Clone, Debug, Eq, Hash, PartialEq)]
710pub enum IambId {
711 Room(OwnedRoomId),
712 DirectList,
713 MemberList(OwnedRoomId),
714 RoomList,
715 SpaceList,
716 VerifyList,
717 Welcome,
718}
719
720impl ApplicationWindowId for IambId {}
721
722#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
723pub enum RoomFocus {
724 Scrollback,
725 MessageBar,
726}
727
728impl RoomFocus {
729 pub fn is_scrollback(&self) -> bool {
730 matches!(self, RoomFocus::Scrollback)
731 }
732
733 pub fn is_msgbar(&self) -> bool {
734 matches!(self, RoomFocus::MessageBar)
735 }
736}
737
738#[derive(Clone, Debug, Eq, Hash, PartialEq)]
739pub enum IambBufferId {
740 Command(CommandType),
741 Room(OwnedRoomId, RoomFocus),
742 DirectList,
743 MemberList(OwnedRoomId),
744 RoomList,
745 SpaceList,
746 VerifyList,
747 Welcome,
748}
749
750impl IambBufferId {
751 pub fn to_window(&self) -> Option<IambId> {
752 match self {
753 IambBufferId::Command(_) => None,
754 IambBufferId::Room(room, _) => Some(IambId::Room(room.clone())),
755 IambBufferId::DirectList => Some(IambId::DirectList),
756 IambBufferId::MemberList(room) => Some(IambId::MemberList(room.clone())),
757 IambBufferId::RoomList => Some(IambId::RoomList),
758 IambBufferId::SpaceList => Some(IambId::SpaceList),
759 IambBufferId::VerifyList => Some(IambId::VerifyList),
760 IambBufferId::Welcome => Some(IambId::Welcome),
761 }
762 }
763}
764
765impl ApplicationContentId for IambBufferId {}
766
767impl ApplicationInfo for IambInfo {
768 type Error = IambError;
769 type Store = ChatStore;
770 type Action = IambAction;
771 type WindowId = IambId;
772 type ContentId = IambBufferId;
773
774 fn complete(
775 text: &EditRope,
776 cursor: &mut Cursor,
777 content: &IambBufferId,
778 store: &mut ProgramStore,
779 ) -> Vec<String> {
780 match content {
781 IambBufferId::Command(CommandType::Command) => complete_cmdbar(text, cursor, store),
782 IambBufferId::Command(CommandType::Search) => vec![],
783
784 IambBufferId::Room(_, RoomFocus::MessageBar) => {
785 complete_matrix_names(text, cursor, store)
786 },
787 IambBufferId::Room(_, RoomFocus::Scrollback) => vec![],
788
789 IambBufferId::DirectList => vec![],
790 IambBufferId::MemberList(_) => vec![],
791 IambBufferId::RoomList => vec![],
792 IambBufferId::SpaceList => vec![],
793 IambBufferId::VerifyList => vec![],
794 IambBufferId::Welcome => vec![],
795 }
796 }
797
798 fn content_of_command(ct: CommandType) -> IambBufferId {
799 IambBufferId::Command(ct)
800 }
801}
802
803fn complete_users(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
804 let id = text
805 .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
806 .unwrap_or_else(EditRope::empty);
807 let id = Cow::from(&id);
808
809 store
810 .application
811 .presences
812 .complete(id.as_ref())
813 .into_iter()
814 .map(|i| i.to_string())
815 .collect()
816}
817
818fn complete_matrix_names(
819 text: &EditRope,
820 cursor: &mut Cursor,
821 store: &ProgramStore,
822) -> Vec<String> {
823 let id = text
824 .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
825 .unwrap_or_else(EditRope::empty);
826 let id = Cow::from(&id);
827
828 let list = store.application.names.complete(id.as_ref());
829 if !list.is_empty() {
830 return list;
831 }
832
833 let list = store.application.presences.complete(id.as_ref());
834 if !list.is_empty() {
835 return list.into_iter().map(|i| i.to_string()).collect();
836 }
837
838 store
839 .application
840 .rooms
841 .complete(id.as_ref())
842 .into_iter()
843 .map(|i| i.to_string())
844 .collect()
845}
846
847fn complete_emoji(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
848 let sc = text.get_prefix_word_mut(cursor, &WordStyle::Little);
849 let sc = sc.unwrap_or_else(EditRope::empty);
850 let sc = Cow::from(&sc);
851
852 store.application.emojis.complete(sc.as_ref())
853}
854
855fn complete_cmdname(
856 desc: CommandDescription,
857 text: &EditRope,
858 cursor: &mut Cursor,
859 store: &ProgramStore,
860) -> Vec<String> {
861 // Complete command name and set cursor position.
862 let _ = text.get_prefix_word_mut(cursor, &WordStyle::Little);
863 store.application.cmds.complete_name(desc.command.as_str())
864}
865
866fn complete_cmdarg(
867 desc: CommandDescription,
868 text: &EditRope,
869 cursor: &mut Cursor,
870 store: &ProgramStore,
871) -> Vec<String> {
872 let cmd = match store.application.cmds.get(desc.command.as_str()) {
873 Ok(cmd) => cmd,
874 Err(_) => return vec![],
875 };
876
877 match cmd.name.as_str() {
878 "cancel" | "dms" | "edit" | "redact" | "reply" => vec![],
879 "members" | "rooms" | "spaces" | "welcome" => vec![],
880 "download" | "open" | "upload" => complete_path(text, cursor),
881 "react" | "unreact" => complete_emoji(text, cursor, store),
882
883 "invite" => complete_users(text, cursor, store),
884 "join" | "split" | "vsplit" | "tabedit" => complete_matrix_names(text, cursor, store),
885 "room" => vec![],
886 "verify" => vec![],
887 "vertical" | "horizontal" | "aboveleft" | "belowright" | "tab" => {
888 complete_cmd(desc.arg.text.as_str(), text, cursor, store)
889 },
890 _ => vec![],
891 }
892}
893
894fn complete_cmd(
895 cmd: &str,
896 text: &EditRope,
897 cursor: &mut Cursor,
898 store: &ProgramStore,
899) -> Vec<String> {
900 match CommandDescription::from_str(cmd) {
901 Ok(desc) => {
902 if desc.arg.untrimmed.is_empty() {
903 complete_cmdname(desc, text, cursor, store)
904 } else {
905 // Complete command argument.
906 complete_cmdarg(desc, text, cursor, store)
907 }
908 },
909
910 // Can't parse command text, so return zero completions.
911 Err(_) => vec![],
912 }
913}
914
915fn complete_cmdbar(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
916 let eo = text.cursor_to_offset(cursor);
917 let slice = text.slice(0.into(), eo, false);
918 let cow = Cow::from(&slice);
919
920 complete_cmd(cow.as_ref(), text, cursor, store)
921}
922
923#[cfg(test)]
924pub mod tests {
925 use super::*;
926 use crate::config::user_style_from_color;
927 use crate::tests::*;
928 use modalkit::tui::style::Color;
929
930 #[test]
931 fn test_typing_spans() {
932 let mut info = RoomInfo::default();
933 let settings = mock_settings();
934
935 let users0 = vec![];
936 let users1 = vec![TEST_USER1.clone()];
937 let users2 = vec![TEST_USER1.clone(), TEST_USER2.clone()];
938 let users4 = vec![
939 TEST_USER1.clone(),
940 TEST_USER2.clone(),
941 TEST_USER3.clone(),
942 TEST_USER4.clone(),
943 ];
944 let users5 = vec![
945 TEST_USER1.clone(),
946 TEST_USER2.clone(),
947 TEST_USER3.clone(),
948 TEST_USER4.clone(),
949 TEST_USER5.clone(),
950 ];
951
952 // Nothing set.
953 assert_eq!(info.users_typing, None);
954 assert_eq!(info.get_typing_spans(&settings), Spans(vec![]));
955
956 // Empty typing list.
957 info.set_typing(users0);
958 assert!(info.users_typing.is_some());
959 assert_eq!(info.get_typing_spans(&settings), Spans(vec![]));
960
961 // Single user typing.
962 info.set_typing(users1);
963 assert!(info.users_typing.is_some());
964 assert_eq!(
965 info.get_typing_spans(&settings),
966 Spans(vec![
967 Span::styled("@user1:example.com", user_style("@user1:example.com")),
968 Span::from(" is typing...")
969 ])
970 );
971
972 // Two users typing.
973 info.set_typing(users2);
974 assert!(info.users_typing.is_some());
975 assert_eq!(
976 info.get_typing_spans(&settings),
977 Spans(vec![
978 Span::styled("@user1:example.com", user_style("@user1:example.com")),
979 Span::raw(" and "),
980 Span::styled("@user2:example.com", user_style("@user2:example.com")),
981 Span::raw(" are typing...")
982 ])
983 );
984
985 // Four users typing.
986 info.set_typing(users4);
987 assert!(info.users_typing.is_some());
988 assert_eq!(info.get_typing_spans(&settings), Spans::from("Several people are typing..."));
989
990 // Five users typing.
991 info.set_typing(users5);
992 assert!(info.users_typing.is_some());
993 assert_eq!(info.get_typing_spans(&settings), Spans::from("Many people are typing..."));
994
995 // Test that USER5 gets rendered using the configured color and name.
996 info.set_typing(vec![TEST_USER5.clone()]);
997 assert!(info.users_typing.is_some());
998 assert_eq!(
999 info.get_typing_spans(&settings),
1000 Spans(vec![
1001 Span::styled("USER 5", user_style_from_color(Color::Black)),
1002 Span::from(" is typing...")
1003 ])
1004 );
1005 }
1006
1007 #[tokio::test]
1008 async fn test_complete_cmdbar() {
1009 let store = mock_store().await;
1010 let users = vec![
1011 "@user1:example.com",
1012 "@user2:example.com",
1013 "@user3:example.com",
1014 "@user4:example.com",
1015 "@user5:example.com",
1016 ];
1017
1018 let text = EditRope::from("invite ");
1019 let mut cursor = Cursor::new(0, 7);
1020 let id = text
1021 .get_prefix_word_mut(&mut cursor, &MATRIX_ID_WORD)
1022 .unwrap_or_else(EditRope::empty);
1023 assert_eq!(id.to_string(), "");
1024 assert_eq!(cursor, Cursor::new(0, 7));
1025
1026 let text = EditRope::from("invite ");
1027 let mut cursor = Cursor::new(0, 7);
1028 let res = complete_cmdbar(&text, &mut cursor, &store);
1029 assert_eq!(res, users);
1030
1031 let text = EditRope::from("invite ignored");
1032 let mut cursor = Cursor::new(0, 7);
1033 let res = complete_cmdbar(&text, &mut cursor, &store);
1034 assert_eq!(res, users);
1035
1036 let text = EditRope::from("invite @user1ignored");
1037 let mut cursor = Cursor::new(0, 13);
1038 let res = complete_cmdbar(&text, &mut cursor, &store);
1039 assert_eq!(res, vec!["@user1:example.com"]);
1040
1041 let text = EditRope::from("abo hor");
1042 let mut cursor = Cursor::new(0, 7);
1043 let res = complete_cmdbar(&text, &mut cursor, &store);
1044 assert_eq!(res, vec!["horizontal"]);
1045
1046 let text = EditRope::from("abo hor inv");
1047 let mut cursor = Cursor::new(0, 11);
1048 let res = complete_cmdbar(&text, &mut cursor, &store);
1049 assert_eq!(res, vec!["invite"]);
1050
1051 let text = EditRope::from("abo hor invite \n");
1052 let mut cursor = Cursor::new(0, 15);
1053 let res = complete_cmdbar(&text, &mut cursor, &store);
1054 assert_eq!(res, users);
1055 }
1056}