src/base.rs
1294 lines · 38340 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, Room as MatrixRoom},
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
647#[derive(Default)]
648pub struct SyncInfo {
649 pub spaces: Vec<MatrixRoom>,
650 pub rooms: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
651 pub dms: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
652}
653
654pub struct ChatStore {
655 pub cmds: ProgramCommands,
656 pub worker: Requester,
657 pub rooms: CompletionMap<OwnedRoomId, RoomInfo>,
658 pub names: CompletionMap<String, OwnedRoomId>,
659 pub presences: CompletionMap<OwnedUserId, PresenceState>,
660 pub verifications: HashMap<String, SasVerification>,
661 pub settings: ApplicationSettings,
662 pub need_load: HashSet<OwnedRoomId>,
663 pub emojis: CompletionMap<String, &'static Emoji>,
664 pub sync_info: SyncInfo,
665}
666
667impl ChatStore {
668 pub fn new(worker: Requester, settings: ApplicationSettings) -> Self {
669 ChatStore {
670 worker,
671 settings,
672
673 cmds: crate::commands::setup_commands(),
674 emojis: emoji_map(),
675
676 names: Default::default(),
677 rooms: Default::default(),
678 presences: Default::default(),
679 verifications: Default::default(),
680 need_load: Default::default(),
681 sync_info: Default::default(),
682 }
683 }
684
685 pub fn get_joined_room(&self, room_id: &RoomId) -> Option<Joined> {
686 self.worker.client.get_joined_room(room_id)
687 }
688
689 pub fn get_room_title(&self, room_id: &RoomId) -> String {
690 self.rooms
691 .get(room_id)
692 .and_then(|i| i.name.as_ref())
693 .map(String::from)
694 .unwrap_or_else(|| "Untitled Matrix Room".to_string())
695 }
696
697 pub async fn set_receipts(
698 &mut self,
699 receipts: Vec<(OwnedRoomId, Receipts)>,
700 ) -> Vec<(OwnedRoomId, OwnedEventId)> {
701 let mut updates = vec![];
702
703 for (room_id, receipts) in receipts.into_iter() {
704 if let Some(info) = self.rooms.get_mut(&room_id) {
705 info.receipts = receipts;
706
707 if let Some(read_till) = info.read_till.take() {
708 updates.push((room_id, read_till));
709 }
710 }
711 }
712
713 return updates;
714 }
715
716 pub fn mark_for_load(&mut self, room_id: OwnedRoomId) {
717 self.need_load.insert(room_id);
718 }
719
720 pub fn get_room_info(&mut self, room_id: OwnedRoomId) -> &mut RoomInfo {
721 self.rooms.get_or_default(room_id)
722 }
723
724 pub fn set_room_name(&mut self, room_id: &RoomId, name: &str) {
725 self.rooms.get_or_default(room_id.to_owned()).name = name.to_string().into();
726 }
727
728 pub fn insert_sas(&mut self, sas: SasVerification) {
729 let key = format!("{}/{}", sas.other_user_id(), sas.other_device().device_id());
730
731 self.verifications.insert(key, sas);
732 }
733}
734
735impl ApplicationStore for ChatStore {}
736
737#[derive(Clone, Debug, Eq, Hash, PartialEq)]
738pub enum IambId {
739 /// A Matrix room.
740 Room(OwnedRoomId),
741
742 /// The `:rooms` window.
743 DirectList,
744
745 /// The `:members` window for a given Matrix room.
746 MemberList(OwnedRoomId),
747
748 /// The `:rooms` window.
749 RoomList,
750
751 /// The `:spaces` window.
752 SpaceList,
753
754 /// The `:verify` window.
755 VerifyList,
756
757 /// The `:welcome` window.
758 Welcome,
759}
760
761impl Display for IambId {
762 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
763 match self {
764 IambId::Room(room_id) => {
765 write!(f, "iamb://room/{room_id}")
766 },
767 IambId::MemberList(room_id) => {
768 write!(f, "iamb://members/{room_id}")
769 },
770 IambId::DirectList => f.write_str("iamb://dms"),
771 IambId::RoomList => f.write_str("iamb://rooms"),
772 IambId::SpaceList => f.write_str("iamb://spaces"),
773 IambId::VerifyList => f.write_str("iamb://verify"),
774 IambId::Welcome => f.write_str("iamb://welcome"),
775 }
776 }
777}
778
779impl ApplicationWindowId for IambId {}
780
781impl Serialize for IambId {
782 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
783 where
784 S: Serializer,
785 {
786 serializer.serialize_str(&self.to_string())
787 }
788}
789
790impl<'de> Deserialize<'de> for IambId {
791 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
792 where
793 D: Deserializer<'de>,
794 {
795 deserializer.deserialize_str(IambIdVisitor)
796 }
797}
798
799struct IambIdVisitor;
800
801impl<'de> Visitor<'de> for IambIdVisitor {
802 type Value = IambId;
803
804 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
805 formatter.write_str("a valid window URL")
806 }
807
808 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
809 where
810 E: SerdeError,
811 {
812 let Ok(url) = Url::parse(value) else {
813 return Err(E::custom("Invalid iamb window URL"));
814 };
815
816 if url.scheme() != "iamb" {
817 return Err(E::custom("Invalid iamb window URL"));
818 }
819
820 match url.domain() {
821 Some("room") => {
822 let Some(path) = url.path_segments() else {
823 return Err(E::custom("Invalid members window URL"));
824 };
825
826 let &[room_id] = path.collect::<Vec<_>>().as_slice() else {
827 return Err(E::custom("Invalid members window URL"));
828 };
829
830 let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
831 return Err(E::custom("Invalid room identifier"));
832 };
833
834 Ok(IambId::Room(room_id))
835 },
836 Some("members") => {
837 let Some(path) = url.path_segments() else {
838 return Err(E::custom( "Invalid members window URL"));
839 };
840
841 let &[room_id] = path.collect::<Vec<_>>().as_slice() else {
842 return Err(E::custom( "Invalid members window URL"));
843 };
844
845 let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
846 return Err(E::custom("Invalid room identifier"));
847 };
848
849 Ok(IambId::MemberList(room_id))
850 },
851 Some("dms") => {
852 if url.path() != "" {
853 return Err(E::custom("iamb://dms takes no path"));
854 }
855
856 Ok(IambId::DirectList)
857 },
858 Some("rooms") => {
859 if url.path() != "" {
860 return Err(E::custom("iamb://rooms takes no path"));
861 }
862
863 Ok(IambId::RoomList)
864 },
865 Some("spaces") => {
866 if url.path() != "" {
867 return Err(E::custom("iamb://spaces takes no path"));
868 }
869
870 Ok(IambId::SpaceList)
871 },
872 Some("verify") => {
873 if url.path() != "" {
874 return Err(E::custom("iamb://verify takes no path"));
875 }
876
877 Ok(IambId::VerifyList)
878 },
879 Some("welcome") => {
880 if url.path() != "" {
881 return Err(E::custom("iamb://welcome takes no path"));
882 }
883
884 Ok(IambId::Welcome)
885 },
886 Some(s) => Err(E::custom(format!("{s:?} is not a valid window"))),
887 None => Err(E::custom("Invalid iamb window URL")),
888 }
889 }
890}
891
892#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
893pub enum RoomFocus {
894 Scrollback,
895 MessageBar,
896}
897
898impl RoomFocus {
899 pub fn is_scrollback(&self) -> bool {
900 matches!(self, RoomFocus::Scrollback)
901 }
902
903 pub fn is_msgbar(&self) -> bool {
904 matches!(self, RoomFocus::MessageBar)
905 }
906}
907
908#[derive(Clone, Debug, Eq, Hash, PartialEq)]
909pub enum IambBufferId {
910 Command(CommandType),
911 Room(OwnedRoomId, RoomFocus),
912 DirectList,
913 MemberList(OwnedRoomId),
914 RoomList,
915 SpaceList,
916 VerifyList,
917 Welcome,
918}
919
920impl IambBufferId {
921 pub fn to_window(&self) -> Option<IambId> {
922 match self {
923 IambBufferId::Command(_) => None,
924 IambBufferId::Room(room, _) => Some(IambId::Room(room.clone())),
925 IambBufferId::DirectList => Some(IambId::DirectList),
926 IambBufferId::MemberList(room) => Some(IambId::MemberList(room.clone())),
927 IambBufferId::RoomList => Some(IambId::RoomList),
928 IambBufferId::SpaceList => Some(IambId::SpaceList),
929 IambBufferId::VerifyList => Some(IambId::VerifyList),
930 IambBufferId::Welcome => Some(IambId::Welcome),
931 }
932 }
933}
934
935impl ApplicationContentId for IambBufferId {}
936
937impl ApplicationInfo for IambInfo {
938 type Error = IambError;
939 type Store = ChatStore;
940 type Action = IambAction;
941 type WindowId = IambId;
942 type ContentId = IambBufferId;
943
944 fn complete(
945 text: &EditRope,
946 cursor: &mut Cursor,
947 content: &IambBufferId,
948 store: &mut ProgramStore,
949 ) -> Vec<String> {
950 match content {
951 IambBufferId::Command(CommandType::Command) => complete_cmdbar(text, cursor, store),
952 IambBufferId::Command(CommandType::Search) => vec![],
953
954 IambBufferId::Room(_, RoomFocus::MessageBar) => complete_msgbar(text, cursor, store),
955 IambBufferId::Room(_, RoomFocus::Scrollback) => vec![],
956
957 IambBufferId::DirectList => vec![],
958 IambBufferId::MemberList(_) => vec![],
959 IambBufferId::RoomList => vec![],
960 IambBufferId::SpaceList => vec![],
961 IambBufferId::VerifyList => vec![],
962 IambBufferId::Welcome => vec![],
963 }
964 }
965
966 fn content_of_command(ct: CommandType) -> IambBufferId {
967 IambBufferId::Command(ct)
968 }
969}
970
971fn complete_users(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
972 let id = text
973 .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
974 .unwrap_or_else(EditRope::empty);
975 let id = Cow::from(&id);
976
977 store
978 .application
979 .presences
980 .complete(id.as_ref())
981 .into_iter()
982 .map(|i| i.to_string())
983 .collect()
984}
985
986fn complete_msgbar(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
987 let id = text
988 .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
989 .unwrap_or_else(EditRope::empty);
990 let id = Cow::from(&id);
991
992 match id.chars().next() {
993 // Complete room aliases.
994 Some('#') => {
995 return store.application.names.complete(id.as_ref());
996 },
997
998 // Complete room identifiers.
999 Some('!') => {
1000 return store
1001 .application
1002 .rooms
1003 .complete(id.as_ref())
1004 .into_iter()
1005 .map(|i| i.to_string())
1006 .collect();
1007 },
1008
1009 // Complete Emoji shortcodes.
1010 Some(':') => {
1011 let list = store.application.emojis.complete(&id[1..]);
1012 let iter = list.into_iter().take(200).map(|s| format!(":{}:", s));
1013
1014 return iter.collect();
1015 },
1016
1017 // Complete usernames for @ and empty strings.
1018 Some('@') | None => {
1019 return store
1020 .application
1021 .presences
1022 .complete(id.as_ref())
1023 .into_iter()
1024 .map(|i| i.to_string())
1025 .collect();
1026 },
1027
1028 // Unknown sigil.
1029 Some(_) => return vec![],
1030 }
1031}
1032
1033fn complete_matrix_names(
1034 text: &EditRope,
1035 cursor: &mut Cursor,
1036 store: &ProgramStore,
1037) -> Vec<String> {
1038 let id = text
1039 .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
1040 .unwrap_or_else(EditRope::empty);
1041 let id = Cow::from(&id);
1042
1043 let list = store.application.names.complete(id.as_ref());
1044 if !list.is_empty() {
1045 return list;
1046 }
1047
1048 let list = store.application.presences.complete(id.as_ref());
1049 if !list.is_empty() {
1050 return list.into_iter().map(|i| i.to_string()).collect();
1051 }
1052
1053 store
1054 .application
1055 .rooms
1056 .complete(id.as_ref())
1057 .into_iter()
1058 .map(|i| i.to_string())
1059 .collect()
1060}
1061
1062fn complete_emoji(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
1063 let sc = text.get_prefix_word_mut(cursor, &WordStyle::Little);
1064 let sc = sc.unwrap_or_else(EditRope::empty);
1065 let sc = Cow::from(&sc);
1066
1067 store.application.emojis.complete(sc.as_ref())
1068}
1069
1070fn complete_cmdname(
1071 desc: CommandDescription,
1072 text: &EditRope,
1073 cursor: &mut Cursor,
1074 store: &ProgramStore,
1075) -> Vec<String> {
1076 // Complete command name and set cursor position.
1077 let _ = text.get_prefix_word_mut(cursor, &WordStyle::Little);
1078 store.application.cmds.complete_name(desc.command.as_str())
1079}
1080
1081fn complete_cmdarg(
1082 desc: CommandDescription,
1083 text: &EditRope,
1084 cursor: &mut Cursor,
1085 store: &ProgramStore,
1086) -> Vec<String> {
1087 let cmd = match store.application.cmds.get(desc.command.as_str()) {
1088 Ok(cmd) => cmd,
1089 Err(_) => return vec![],
1090 };
1091
1092 match cmd.name.as_str() {
1093 "cancel" | "dms" | "edit" | "redact" | "reply" => vec![],
1094 "members" | "rooms" | "spaces" | "welcome" => vec![],
1095 "download" | "open" | "upload" => complete_path(text, cursor),
1096 "react" | "unreact" => complete_emoji(text, cursor, store),
1097
1098 "invite" => complete_users(text, cursor, store),
1099 "join" | "split" | "vsplit" | "tabedit" => complete_matrix_names(text, cursor, store),
1100 "room" => vec![],
1101 "verify" => vec![],
1102 "vertical" | "horizontal" | "aboveleft" | "belowright" | "tab" => {
1103 complete_cmd(desc.arg.text.as_str(), text, cursor, store)
1104 },
1105 _ => vec![],
1106 }
1107}
1108
1109fn complete_cmd(
1110 cmd: &str,
1111 text: &EditRope,
1112 cursor: &mut Cursor,
1113 store: &ProgramStore,
1114) -> Vec<String> {
1115 match CommandDescription::from_str(cmd) {
1116 Ok(desc) => {
1117 if desc.arg.untrimmed.is_empty() {
1118 complete_cmdname(desc, text, cursor, store)
1119 } else {
1120 // Complete command argument.
1121 complete_cmdarg(desc, text, cursor, store)
1122 }
1123 },
1124
1125 // Can't parse command text, so return zero completions.
1126 Err(_) => vec![],
1127 }
1128}
1129
1130fn complete_cmdbar(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
1131 let eo = text.cursor_to_offset(cursor);
1132 let slice = text.slice(0.into(), eo, false);
1133 let cow = Cow::from(&slice);
1134
1135 complete_cmd(cow.as_ref(), text, cursor, store)
1136}
1137
1138#[cfg(test)]
1139pub mod tests {
1140 use super::*;
1141 use crate::config::user_style_from_color;
1142 use crate::tests::*;
1143 use modalkit::tui::style::Color;
1144
1145 #[test]
1146 fn test_typing_spans() {
1147 let mut info = RoomInfo::default();
1148 let settings = mock_settings();
1149
1150 let users0 = vec![];
1151 let users1 = vec![TEST_USER1.clone()];
1152 let users2 = vec![TEST_USER1.clone(), TEST_USER2.clone()];
1153 let users4 = vec![
1154 TEST_USER1.clone(),
1155 TEST_USER2.clone(),
1156 TEST_USER3.clone(),
1157 TEST_USER4.clone(),
1158 ];
1159 let users5 = vec![
1160 TEST_USER1.clone(),
1161 TEST_USER2.clone(),
1162 TEST_USER3.clone(),
1163 TEST_USER4.clone(),
1164 TEST_USER5.clone(),
1165 ];
1166
1167 // Nothing set.
1168 assert_eq!(info.users_typing, None);
1169 assert_eq!(info.get_typing_spans(&settings), Spans(vec![]));
1170
1171 // Empty typing list.
1172 info.set_typing(users0);
1173 assert!(info.users_typing.is_some());
1174 assert_eq!(info.get_typing_spans(&settings), Spans(vec![]));
1175
1176 // Single user typing.
1177 info.set_typing(users1);
1178 assert!(info.users_typing.is_some());
1179 assert_eq!(
1180 info.get_typing_spans(&settings),
1181 Spans(vec![
1182 Span::styled("@user1:example.com", user_style("@user1:example.com")),
1183 Span::from(" is typing...")
1184 ])
1185 );
1186
1187 // Two users typing.
1188 info.set_typing(users2);
1189 assert!(info.users_typing.is_some());
1190 assert_eq!(
1191 info.get_typing_spans(&settings),
1192 Spans(vec![
1193 Span::styled("@user1:example.com", user_style("@user1:example.com")),
1194 Span::raw(" and "),
1195 Span::styled("@user2:example.com", user_style("@user2:example.com")),
1196 Span::raw(" are typing...")
1197 ])
1198 );
1199
1200 // Four users typing.
1201 info.set_typing(users4);
1202 assert!(info.users_typing.is_some());
1203 assert_eq!(info.get_typing_spans(&settings), Spans::from("Several people are typing..."));
1204
1205 // Five users typing.
1206 info.set_typing(users5);
1207 assert!(info.users_typing.is_some());
1208 assert_eq!(info.get_typing_spans(&settings), Spans::from("Many people are typing..."));
1209
1210 // Test that USER5 gets rendered using the configured color and name.
1211 info.set_typing(vec![TEST_USER5.clone()]);
1212 assert!(info.users_typing.is_some());
1213 assert_eq!(
1214 info.get_typing_spans(&settings),
1215 Spans(vec![
1216 Span::styled("USER 5", user_style_from_color(Color::Black)),
1217 Span::from(" is typing...")
1218 ])
1219 );
1220 }
1221
1222 #[tokio::test]
1223 async fn test_complete_msgbar() {
1224 let store = mock_store().await;
1225
1226 let text = EditRope::from("going for a walk :walk ");
1227 let mut cursor = Cursor::new(0, 22);
1228 let res = complete_msgbar(&text, &mut cursor, &store);
1229 assert_eq!(res, vec![":walking:", ":walking_man:", ":walking_woman:"]);
1230 assert_eq!(cursor, Cursor::new(0, 17));
1231
1232 let text = EditRope::from("hello @user1 ");
1233 let mut cursor = Cursor::new(0, 12);
1234 let res = complete_msgbar(&text, &mut cursor, &store);
1235 assert_eq!(res, vec!["@user1:example.com"]);
1236 assert_eq!(cursor, Cursor::new(0, 6));
1237
1238 let text = EditRope::from("see #room ");
1239 let mut cursor = Cursor::new(0, 9);
1240 let res = complete_msgbar(&text, &mut cursor, &store);
1241 assert_eq!(res, vec!["#room1:example.com"]);
1242 assert_eq!(cursor, Cursor::new(0, 4));
1243 }
1244
1245 #[tokio::test]
1246 async fn test_complete_cmdbar() {
1247 let store = mock_store().await;
1248 let users = vec![
1249 "@user1:example.com",
1250 "@user2:example.com",
1251 "@user3:example.com",
1252 "@user4:example.com",
1253 "@user5:example.com",
1254 ];
1255
1256 let text = EditRope::from("invite ");
1257 let mut cursor = Cursor::new(0, 7);
1258 let id = text
1259 .get_prefix_word_mut(&mut cursor, &MATRIX_ID_WORD)
1260 .unwrap_or_else(EditRope::empty);
1261 assert_eq!(id.to_string(), "");
1262 assert_eq!(cursor, Cursor::new(0, 7));
1263
1264 let text = EditRope::from("invite ");
1265 let mut cursor = Cursor::new(0, 7);
1266 let res = complete_cmdbar(&text, &mut cursor, &store);
1267 assert_eq!(res, users);
1268
1269 let text = EditRope::from("invite ignored");
1270 let mut cursor = Cursor::new(0, 7);
1271 let res = complete_cmdbar(&text, &mut cursor, &store);
1272 assert_eq!(res, users);
1273
1274 let text = EditRope::from("invite @user1ignored");
1275 let mut cursor = Cursor::new(0, 13);
1276 let res = complete_cmdbar(&text, &mut cursor, &store);
1277 assert_eq!(res, vec!["@user1:example.com"]);
1278
1279 let text = EditRope::from("abo hor");
1280 let mut cursor = Cursor::new(0, 7);
1281 let res = complete_cmdbar(&text, &mut cursor, &store);
1282 assert_eq!(res, vec!["horizontal"]);
1283
1284 let text = EditRope::from("abo hor inv");
1285 let mut cursor = Cursor::new(0, 11);
1286 let res = complete_cmdbar(&text, &mut cursor, &store);
1287 assert_eq!(res, vec!["invite"]);
1288
1289 let text = EditRope::from("abo hor invite \n");
1290 let mut cursor = Cursor::new(0, 15);
1291 let res = complete_cmdbar(&text, &mut cursor, &store);
1292 assert_eq!(res, users);
1293 }
1294}