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