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