Commit 0ed1d53946

0ed1d53946e421cd8037e0bda92606fa5ea00399

parent: e3be8c16cb

Unregistered key

Ulyssa <git@ulyssa.dev> · 2023-03-02 02:46 UTC

Support completing commands, usernames, and room names (#44)

Layout: unified · split

Cargo.lock +30 −3
@@ -860,6 +860,12 @@ dependencies = [
860860 "cfg-if",
861861]
862862
863[[package]]
864name = "endian-type"
865version = "0.1.2"
866source = "registry+https://github.com/rust-lang/crates.io-index"
867checksum = "c34f04666d835ff5d62e058c3995147c06f42fe86ff053337632bca83e42702d"
868
863869[[package]]
864870name = "errno"
865871version = "0.2.8"
@@ -1302,7 +1308,7 @@ dependencies = [
13021308
13031309[[package]]
13041310name = "iamb"
1305version = "0.0.4"
1311version = "0.0.5"
13061312dependencies = [
13071313 "bitflags",
13081314 "chrono",
@@ -1876,9 +1882,9 @@ dependencies = [
18761882
18771883[[package]]
18781884name = "modalkit"
1879version = "0.0.11"
1885version = "0.0.12"
18801886source = "registry+https://github.com/rust-lang/crates.io-index"
1881checksum = "bd7bd7d02d65842dab4cea53016cf29c16cde197131dd6d9eea95662deb77778"
1887checksum = "9a4e5226a5d33a7bdf5b4fc067baa211c94f21aa6667af5eec8b357a8af5e4ba"
18821888dependencies = [
18831889 "anymap2",
18841890 "arboard",
@@ -1888,10 +1894,12 @@ dependencies = [
18881894 "intervaltree",
18891895 "libc",
18901896 "nom",
1897 "radix_trie",
18911898 "regex",
18921899 "ropey",
18931900 "thiserror",
18941901 "tui",
1902 "unicode-segmentation",
18951903]
18961904
18971905[[package]]
@@ -1900,6 +1908,15 @@ version = "1.0.4"
19001908source = "registry+https://github.com/rust-lang/crates.io-index"
19011909checksum = "e4a24736216ec316047a1fc4252e27dabb04218aa4a3f37c6e7ddbf1f9782b54"
19021910
1911[[package]]
1912name = "nibble_vec"
1913version = "0.1.0"
1914source = "registry+https://github.com/rust-lang/crates.io-index"
1915checksum = "77a5d83df9f36fe23f0c3648c6bbb8b0298bb5f1939c8f2704431371f4b84d43"
1916dependencies = [
1917 "smallvec",
1918]
1919
19031920[[package]]
19041921name = "nix"
19051922version = "0.24.3"
@@ -2344,6 +2361,16 @@ dependencies = [
23442361 "proc-macro2",
23452362]
23462363
2364[[package]]
2365name = "radix_trie"
2366version = "0.2.1"
2367source = "registry+https://github.com/rust-lang/crates.io-index"
2368checksum = "c069c179fcdc6a2fe24d8d18305cf085fdbd4f922c041943e203685d6a1c58fd"
2369dependencies = [
2370 "endian-type",
2371 "nibble_vec",
2372]
2373
23472374[[package]]
23482375name = "rand"
23492376version = "0.7.3"
Cargo.toml +1 −1
@@ -39,7 +39,7 @@ unicode-width = "0.1.10"
3939url = {version = "^2.2.2", features = ["serde"]}
4040
4141[dependencies.modalkit]
42version = "0.0.11"
42version = "0.0.12"
4343
4444[dependencies.matrix-sdk]
4545version = "0.6"
src/base.rs +219 −9
@@ -1,8 +1,11 @@
1use std::borrow::Cow;
12use std::collections::{HashMap, HashSet};
23use std::hash::Hash;
4use std::str::FromStr;
35use std::sync::Arc;
46use std::time::{Duration, Instant};
57
8use emojis::Emoji;
69use tokio::sync::Mutex as AsyncMutex;
710use tracing::warn;
811
@@ -23,6 +26,7 @@ use matrix_sdk::{
2326 AnyMessageLikeEvent,
2427 MessageLikeEvent,
2528 },
29 presence::PresenceState,
2630 EventId,
2731 OwnedEventId,
2832 OwnedRoomId,
@@ -42,11 +46,15 @@ use modalkit::{
4246 ApplicationStore,
4347 ApplicationWindowId,
4448 },
49 base::{CommandType, WordStyle},
50 completion::{complete_path, CompletionMap},
4551 context::EditContext,
52 cursor::Cursor,
53 rope::EditRope,
4654 store::Store,
4755 },
4856 env::vim::{
49 command::{CommandContext, VimCommand, VimCommandMachine},
57 command::{CommandContext, CommandDescription, VimCommand, VimCommandMachine},
5058 keybindings::VimMachine,
5159 VimContext,
5260 },
@@ -66,6 +74,20 @@ use crate::{
6674 ApplicationSettings,
6775};
6876
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
6991const ROOM_FETCH_DEBOUNCE: Duration = Duration::from_secs(2);
7092
7193#[derive(Clone, Debug, Eq, PartialEq)]
@@ -528,13 +550,28 @@ impl RoomInfo {
528550 }
529551}
530552
553fn emoji_map() -> CompletionMap<String, &'static Emoji> {
554 let mut emojis = CompletionMap::default();
555
556 for emoji in emojis::iter() {
557 for shortcode in emoji.shortcodes() {
558 emojis.insert(shortcode.to_string(), emoji);
559 }
560 }
561
562 return emojis;
563}
564
531565pub struct ChatStore {
566 pub cmds: ProgramCommands,
532567 pub worker: Requester,
533 pub rooms: HashMap<OwnedRoomId, RoomInfo>,
534 pub names: HashMap<String, OwnedRoomId>,
568 pub rooms: CompletionMap<OwnedRoomId, RoomInfo>,
569 pub names: CompletionMap<String, OwnedRoomId>,
570 pub presences: CompletionMap<OwnedUserId, PresenceState>,
535571 pub verifications: HashMap<String, SasVerification>,
536572 pub settings: ApplicationSettings,
537573 pub need_load: HashSet<OwnedRoomId>,
574 pub emojis: CompletionMap<String, &'static Emoji>,
538575}
539576
540577impl ChatStore {
@@ -543,10 +580,13 @@ impl ChatStore {
543580 worker,
544581 settings,
545582
583 cmds: crate::commands::setup_commands(),
546584 names: Default::default(),
547585 rooms: Default::default(),
586 presences: Default::default(),
548587 verifications: Default::default(),
549588 need_load: Default::default(),
589 emojis: emoji_map(),
550590 }
551591 }
552592
@@ -587,10 +627,10 @@ impl ChatStore {
587627 }
588628
589629 pub fn load_older(&mut self, limit: u32) {
590 let ChatStore { need_load, rooms, worker, .. } = self;
630 let ChatStore { need_load, presences, rooms, worker, .. } = self;
591631
592632 for room_id in std::mem::take(need_load).into_iter() {
593 let info = rooms.entry(room_id.clone()).or_default();
633 let info = rooms.get_or_default(room_id.clone());
594634
595635 if info.recently_fetched() {
596636 need_load.insert(room_id);
@@ -610,6 +650,9 @@ impl ChatStore {
610650 match res {
611651 Ok((fetch_id, msgs)) => {
612652 for msg in msgs.into_iter() {
653 let sender = msg.sender().to_owned();
654 let _ = presences.get_or_default(sender);
655
613656 match msg {
614657 AnyMessageLikeEvent::RoomMessage(msg) => {
615658 info.insert(msg);
@@ -639,11 +682,11 @@ impl ChatStore {
639682 }
640683
641684 pub fn get_room_info(&mut self, room_id: OwnedRoomId) -> &mut RoomInfo {
642 self.rooms.entry(room_id).or_default()
685 self.rooms.get_or_default(room_id)
643686 }
644687
645688 pub fn set_room_name(&mut self, room_id: &RoomId, name: &str) {
646 self.rooms.entry(room_id.to_owned()).or_default().name = name.to_string().into();
689 self.rooms.get_or_default(room_id.to_owned()).name = name.to_string().into();
647690 }
648691
649692 pub fn insert_sas(&mut self, sas: SasVerification) {
@@ -686,7 +729,7 @@ impl RoomFocus {
686729
687730#[derive(Clone, Debug, Eq, Hash, PartialEq)]
688731pub enum IambBufferId {
689 Command,
732 Command(CommandType),
690733 Room(OwnedRoomId, RoomFocus),
691734 DirectList,
692735 MemberList(OwnedRoomId),
@@ -699,7 +742,7 @@ pub enum IambBufferId {
699742impl IambBufferId {
700743 pub fn to_window(&self) -> Option<IambId> {
701744 match self {
702 IambBufferId::Command => None,
745 IambBufferId::Command(_) => None,
703746 IambBufferId::Room(room, _) => Some(IambId::Room(room.clone())),
704747 IambBufferId::DirectList => Some(IambId::DirectList),
705748 IambBufferId::MemberList(room) => Some(IambId::MemberList(room.clone())),
@@ -719,6 +762,133 @@ impl ApplicationInfo for IambInfo {
719762 type Action = IambAction;
720763 type WindowId = IambId;
721764 type ContentId = IambBufferId;
765
766 fn complete(
767 text: &EditRope,
768 cursor: &mut Cursor,
769 content: &IambBufferId,
770 store: &mut ProgramStore,
771 ) -> Vec<String> {
772 match content {
773 IambBufferId::Command(CommandType::Command) => complete_cmdbar(text, cursor, store),
774 IambBufferId::Command(CommandType::Search) => vec![],
775
776 IambBufferId::Room(_, RoomFocus::MessageBar) => {
777 complete_matrix_names(text, cursor, store)
778 },
779 IambBufferId::Room(_, RoomFocus::Scrollback) => vec![],
780
781 IambBufferId::DirectList => vec![],
782 IambBufferId::MemberList(_) => vec![],
783 IambBufferId::RoomList => vec![],
784 IambBufferId::SpaceList => vec![],
785 IambBufferId::VerifyList => vec![],
786 IambBufferId::Welcome => vec![],
787 }
788 }
789
790 fn content_of_command(ct: CommandType) -> IambBufferId {
791 IambBufferId::Command(ct)
792 }
793}
794
795fn complete_users(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
796 let id = text
797 .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
798 .unwrap_or_else(EditRope::empty);
799 let id = Cow::from(&id);
800
801 store
802 .application
803 .presences
804 .complete(id.as_ref())
805 .into_iter()
806 .map(|i| i.to_string())
807 .collect()
808}
809
810fn complete_matrix_names(
811 text: &EditRope,
812 cursor: &mut Cursor,
813 store: &ProgramStore,
814) -> Vec<String> {
815 let id = text
816 .get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
817 .unwrap_or_else(EditRope::empty);
818 let id = Cow::from(&id);
819
820 let list = store.application.names.complete(id.as_ref());
821 if !list.is_empty() {
822 return list;
823 }
824
825 let list = store.application.presences.complete(id.as_ref());
826 if !list.is_empty() {
827 return list.into_iter().map(|i| i.to_string()).collect();
828 }
829
830 store
831 .application
832 .rooms
833 .complete(id.as_ref())
834 .into_iter()
835 .map(|i| i.to_string())
836 .collect()
837}
838
839fn complete_emoji(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
840 let sc = text.get_prefix_word_mut(cursor, &WordStyle::Little);
841 let sc = sc.unwrap_or_else(EditRope::empty);
842 let sc = Cow::from(&sc);
843
844 store.application.emojis.complete(sc.as_ref())
845}
846
847fn complete_cmdarg(
848 desc: CommandDescription,
849 text: &EditRope,
850 cursor: &mut Cursor,
851 store: &ProgramStore,
852) -> Vec<String> {
853 let cmd = match store.application.cmds.get(desc.command.as_str()) {
854 Ok(cmd) => cmd,
855 Err(_) => return vec![],
856 };
857
858 match cmd.name.as_str() {
859 "cancel" | "dms" | "edit" | "redact" | "reply" => vec![],
860 "members" | "rooms" | "spaces" | "welcome" => vec![],
861 "download" | "open" | "upload" => complete_path(text, cursor),
862 "react" | "unreact" => complete_emoji(text, cursor, store),
863
864 "invite" => complete_users(text, cursor, store),
865 "join" => complete_matrix_names(text, cursor, store),
866 "room" => vec![],
867 "verify" => vec![],
868 _ => panic!("unknown command {}", cmd.name.as_str()),
869 }
870}
871
872fn complete_cmdbar(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
873 let eo = text.cursor_to_offset(cursor);
874 let slice = text.slice(0.into(), eo, false);
875 let cow = Cow::from(&slice);
876
877 match CommandDescription::from_str(cow.as_ref()) {
878 Ok(desc) => {
879 if desc.arg.untrimmed.is_empty() {
880 // Complete command name and set cursor position.
881 let _ = text.get_prefix_word_mut(cursor, &WordStyle::Little);
882 store.application.cmds.complete_name(desc.command.as_str())
883 } else {
884 // Complete command argument.
885 complete_cmdarg(desc, text, cursor, store)
886 }
887 },
888
889 // Can't parse command text, so return zero completions.
890 Err(_) => vec![],
891 }
722892}
723893
724894#[cfg(test)]
@@ -804,4 +974,44 @@ pub mod tests {
804974 ])
805975 );
806976 }
977
978 #[tokio::test]
979 async fn test_complete_cmdbar() {
980 let store = mock_store().await;
981
982 let text = EditRope::from("invite ");
983 let mut cursor = Cursor::new(0, 7);
984 let id = text
985 .get_prefix_word_mut(&mut cursor, &MATRIX_ID_WORD)
986 .unwrap_or_else(EditRope::empty);
987 assert_eq!(id.to_string(), "");
988 assert_eq!(cursor, Cursor::new(0, 7));
989
990 let text = EditRope::from("invite ");
991 let mut cursor = Cursor::new(0, 7);
992 let res = complete_cmdbar(&text, &mut cursor, &store);
993 assert_eq!(res, vec![
994 "@user1:example.com",
995 "@user2:example.com",
996 "@user3:example.com",
997 "@user4:example.com",
998 "@user5:example.com"
999 ]);
1000
1001 let text = EditRope::from("invite ignored");
1002 let mut cursor = Cursor::new(0, 7);
1003 let res = complete_cmdbar(&text, &mut cursor, &store);
1004 assert_eq!(res, vec![
1005 "@user1:example.com",
1006 "@user2:example.com",
1007 "@user3:example.com",
1008 "@user4:example.com",
1009 "@user5:example.com"
1010 ]);
1011
1012 let text = EditRope::from("invite @user1ignored");
1013 let mut cursor = Cursor::new(0, 13);
1014 let res = complete_cmdbar(&text, &mut cursor, &store);
1015 assert_eq!(res, vec!["@user1:example.com"]);
1016 }
8071017}
src/commands.rs +70 −18
@@ -395,24 +395,76 @@ fn iamb_open(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
395395}
396396
397397fn add_iamb_commands(cmds: &mut ProgramCommands) {
398 cmds.add_command(ProgramCommand { names: vec!["cancel".into()], f: iamb_cancel });
399 cmds.add_command(ProgramCommand { names: vec!["dms".into()], f: iamb_dms });
400 cmds.add_command(ProgramCommand { names: vec!["download".into()], f: iamb_download });
401 cmds.add_command(ProgramCommand { names: vec!["open".into()], f: iamb_open });
402 cmds.add_command(ProgramCommand { names: vec!["edit".into()], f: iamb_edit });
403 cmds.add_command(ProgramCommand { names: vec!["invite".into()], f: iamb_invite });
404 cmds.add_command(ProgramCommand { names: vec!["join".into()], f: iamb_join });
405 cmds.add_command(ProgramCommand { names: vec!["members".into()], f: iamb_members });
406 cmds.add_command(ProgramCommand { names: vec!["react".into()], f: iamb_react });
407 cmds.add_command(ProgramCommand { names: vec!["redact".into()], f: iamb_redact });
408 cmds.add_command(ProgramCommand { names: vec!["reply".into()], f: iamb_reply });
409 cmds.add_command(ProgramCommand { names: vec!["rooms".into()], f: iamb_rooms });
410 cmds.add_command(ProgramCommand { names: vec!["room".into()], f: iamb_room });
411 cmds.add_command(ProgramCommand { names: vec!["spaces".into()], f: iamb_spaces });
412 cmds.add_command(ProgramCommand { names: vec!["unreact".into()], f: iamb_unreact });
413 cmds.add_command(ProgramCommand { names: vec!["upload".into()], f: iamb_upload });
414 cmds.add_command(ProgramCommand { names: vec!["verify".into()], f: iamb_verify });
415 cmds.add_command(ProgramCommand { names: vec!["welcome".into()], f: iamb_welcome });
398 cmds.add_command(ProgramCommand {
399 name: "cancel".into(),
400 aliases: vec![],
401 f: iamb_cancel,
402 });
403 cmds.add_command(ProgramCommand { name: "dms".into(), aliases: vec![], f: iamb_dms });
404 cmds.add_command(ProgramCommand {
405 name: "download".into(),
406 aliases: vec![],
407 f: iamb_download,
408 });
409 cmds.add_command(ProgramCommand { name: "open".into(), aliases: vec![], f: iamb_open });
410 cmds.add_command(ProgramCommand { name: "edit".into(), aliases: vec![], f: iamb_edit });
411 cmds.add_command(ProgramCommand {
412 name: "invite".into(),
413 aliases: vec![],
414 f: iamb_invite,
415 });
416 cmds.add_command(ProgramCommand { name: "join".into(), aliases: vec![], f: iamb_join });
417 cmds.add_command(ProgramCommand {
418 name: "members".into(),
419 aliases: vec![],
420 f: iamb_members,
421 });
422 cmds.add_command(ProgramCommand {
423 name: "react".into(),
424 aliases: vec![],
425 f: iamb_react,
426 });
427 cmds.add_command(ProgramCommand {
428 name: "redact".into(),
429 aliases: vec![],
430 f: iamb_redact,
431 });
432 cmds.add_command(ProgramCommand {
433 name: "reply".into(),
434 aliases: vec![],
435 f: iamb_reply,
436 });
437 cmds.add_command(ProgramCommand {
438 name: "rooms".into(),
439 aliases: vec![],
440 f: iamb_rooms,
441 });
442 cmds.add_command(ProgramCommand { name: "room".into(), aliases: vec![], f: iamb_room });
443 cmds.add_command(ProgramCommand {
444 name: "spaces".into(),
445 aliases: vec![],
446 f: iamb_spaces,
447 });
448 cmds.add_command(ProgramCommand {
449 name: "unreact".into(),
450 aliases: vec![],
451 f: iamb_unreact,
452 });
453 cmds.add_command(ProgramCommand {
454 name: "upload".into(),
455 aliases: vec![],
456 f: iamb_upload,
457 });
458 cmds.add_command(ProgramCommand {
459 name: "verify".into(),
460 aliases: vec![],
461 f: iamb_verify,
462 });
463 cmds.add_command(ProgramCommand {
464 name: "welcome".into(),
465 aliases: vec![],
466 f: iamb_welcome,
467 });
416468}
417469
418470pub fn setup_commands() -> ProgramCommands {
src/keybindings.rs +2 −15
@@ -1,34 +1,21 @@
11use modalkit::{
22 editing::action::WindowAction,
3 editing::base::WordStyle,
43 env::vim::keybindings::{InputStep, VimBindings},
54 env::vim::VimMode,
65 input::bindings::{EdgeEvent, EdgeRepeat, InputBindings},
76 input::key::TerminalKey,
87};
98
10use crate::base::{IambAction, IambInfo, Keybindings};
9use crate::base::{IambAction, IambInfo, Keybindings, MATRIX_ID_WORD};
1110
1211type IambStep = InputStep<IambInfo>;
1312
14/// Find the boundaries for a Matrix username, room alias, or room ID.
15///
16/// Technically "[" and "]" should be here since IPv6 addresses are allowed
17/// in the server name, but in practice that should be uncommon, and people
18/// can just use `gf` and friends in Visual mode instead.
19fn is_mxid_char(c: char) -> bool {
20 return c >= 'a' && c <= 'z' ||
21 c >= 'A' && c <= 'Z' ||
22 c >= '0' && c <= '9' ||
23 ":-./@_#!".contains(c);
24}
25
2613pub fn setup_keybindings() -> Keybindings {
2714 let mut ism = Keybindings::empty();
2815
2916 let vim = VimBindings::default()
3017 .submit_on_enter()
31 .cursor_open(WordStyle::CharSet(is_mxid_char));
18 .cursor_open(MATRIX_ID_WORD.clone());
3219
3320 vim.setup(&mut ism);
3421
src/main.rs +2 −7
@@ -54,13 +54,11 @@ use crate::{
5454 AsyncProgramStore,
5555 ChatStore,
5656 IambAction,
57 IambBufferId,
5857 IambError,
5958 IambId,
6059 IambInfo,
6160 IambResult,
6261 ProgramAction,
63 ProgramCommands,
6462 ProgramContext,
6563 ProgramStore,
6664 },
@@ -116,7 +114,6 @@ struct Application {
116114 terminal: Terminal<CrosstermBackend<Stdout>>,
117115 bindings: KeyManager<TerminalKey, ProgramAction, RepeatType, ProgramContext>,
118116 actstack: VecDeque<(ProgramAction, ProgramContext)>,
119 cmds: ProgramCommands,
120117 screen: ScreenState<IambWindow, IambInfo>,
121118}
122119
@@ -138,7 +135,6 @@ impl Application {
138135
139136 let bindings = crate::keybindings::setup_keybindings();
140137 let bindings = KeyManager::new(bindings);
141 let cmds = crate::commands::setup_commands();
142138
143139 let mut locked = store.lock().await;
144140
@@ -149,7 +145,7 @@ impl Application {
149145 .or_else(|| IambWindow::open(IambId::Welcome, locked.deref_mut()).ok())
150146 .unwrap();
151147
152 let cmd = CommandBarState::new(IambBufferId::Command, locked.deref_mut());
148 let cmd = CommandBarState::new(locked.deref_mut());
153149 let screen = ScreenState::new(win, cmd);
154150
155151 let worker = locked.application.worker.clone();
@@ -163,7 +159,6 @@ impl Application {
163159 terminal,
164160 bindings,
165161 actstack,
166 cmds,
167162 screen,
168163 })
169164 }
@@ -321,7 +316,7 @@ impl Application {
321316 None
322317 },
323318 Action::Command(act) => {
324 let acts = self.cmds.command(&act, &ctx)?;
319 let acts = store.application.cmds.command(&act, &ctx)?;
325320 self.action_prepend(acts);
326321
327322 None
src/tests.rs +8
@@ -208,6 +208,14 @@ pub async fn mock_store() -> ProgramStore {
208208 let worker = Requester { tx, client };
209209
210210 let mut store = ChatStore::new(worker, mock_settings());
211
212 // Add presence information.
213 store.presences.get_or_default(TEST_USER1.clone());
214 store.presences.get_or_default(TEST_USER2.clone());
215 store.presences.get_or_default(TEST_USER3.clone());
216 store.presences.get_or_default(TEST_USER4.clone());
217 store.presences.get_or_default(TEST_USER5.clone());
218
211219 let room_id = TEST_ROOM1_ID.clone();
212220 let info = mock_room();
213221
src/windows/mod.rs +36 −15
@@ -1,5 +1,4 @@
11use std::cmp::{Ord, Ordering, PartialOrd};
2use std::collections::hash_map::Entry;
32
43use matrix_sdk::{
54 encryption::verification::{format_emojis, SasVerification},
@@ -45,7 +44,9 @@ use modalkit::{
4544 ScrollStyle,
4645 ViewportContext,
4746 WordStyle,
47 WriteFlags,
4848 },
49 completion::CompletionList,
4950 },
5051 widgets::{
5152 list::{List, ListCursor, ListItem, ListState},
@@ -469,6 +470,19 @@ impl WindowOps<IambInfo> for IambWindow {
469470 delegate!(self, w => w.close(flags, store))
470471 }
471472
473 fn write(
474 &mut self,
475 path: Option<&str>,
476 flags: WriteFlags,
477 store: &mut ProgramStore,
478 ) -> IambResult<EditInfo> {
479 delegate!(self, w => w.write(path, flags, store))
480 }
481
482 fn get_completions(&self) -> Option<CompletionList> {
483 delegate!(self, w => w.get_completions())
484 }
485
472486 fn get_cursor_word(&self, style: &WordStyle) -> Option<String> {
473487 delegate!(self, w => w.get_cursor_word(style))
474488 }
@@ -575,21 +589,18 @@ impl Window<IambInfo> for IambWindow {
575589 fn find(name: String, store: &mut ProgramStore) -> IambResult<Self> {
576590 let ChatStore { names, worker, .. } = &mut store.application;
577591
578 match names.entry(name) {
579 Entry::Vacant(v) => {
580 let room_id = worker.join_room(v.key().to_string())?;
581 v.insert(room_id.clone());
592 if let Some(room) = names.get_mut(&name) {
593 let id = IambId::Room(room.clone());
582594
583 let (room, name, tags) = store.application.worker.get_room(room_id)?;
584 let room = RoomState::new(room, name, tags, store);
595 IambWindow::open(id, store)
596 } else {
597 let room_id = worker.join_room(name.clone())?;
598 names.insert(name, room_id.clone());
585599
586 Ok(room.into())
587 },
588 Entry::Occupied(o) => {
589 let id = IambId::Room(o.get().clone());
600 let (room, name, tags) = store.application.worker.get_room(room_id)?;
601 let room = RoomState::new(room, name, tags, store);
590602
591 IambWindow::open(id, store)
592 },
603 Ok(room.into())
593604 }
594605 }
595606
@@ -620,11 +631,16 @@ impl RoomItem {
620631 store: &mut ProgramStore,
621632 ) -> Self {
622633 let name = name.to_string();
634 let room_id = room.room_id();
623635
624 let info = store.application.get_room_info(room.room_id().to_owned());
636 let info = store.application.get_room_info(room_id.to_owned());
625637 info.name = name.clone().into();
626638 info.tags = tags.clone();
627639
640 if let Some(alias) = room.canonical_alias() {
641 store.application.names.insert(alias.to_string(), room_id.to_owned());
642 }
643
628644 RoomItem { room, tags, name }
629645 }
630646}
@@ -772,8 +788,13 @@ pub struct SpaceItem {
772788impl SpaceItem {
773789 fn new(room: MatrixRoom, name: DisplayName, store: &mut ProgramStore) -> Self {
774790 let name = name.to_string();
791 let room_id = room.room_id();
775792
776 store.application.set_room_name(room.room_id(), name.as_str());
793 store.application.set_room_name(room_id, name.as_str());
794
795 if let Some(alias) = room.canonical_alias() {
796 store.application.names.insert(alias.to_string(), room_id.to_owned());
797 }
777798
778799 SpaceItem { room, name }
779800 }
src/windows/room/chat.rs +19 −3
@@ -52,7 +52,8 @@ use modalkit::editing::{
5252 Scrollable,
5353 UIError,
5454 },
55 base::{CloseFlags, Count, MoveDir1D, PositionList, ScrollStyle, WordStyle},
55 base::{CloseFlags, Count, MoveDir1D, PositionList, ScrollStyle, WordStyle, WriteFlags},
56 completion::CompletionList,
5657 context::Resolve,
5758 history::{self, HistoryList},
5859 rope::EditRope,
@@ -154,7 +155,7 @@ impl ChatState {
154155 let client = &store.application.worker.client;
155156
156157 let settings = &store.application.settings;
157 let info = store.application.rooms.entry(self.room_id.clone()).or_default();
158 let info = store.application.rooms.get_or_default(self.room_id.clone());
158159
159160 let msg = self
160161 .scrollback
@@ -389,7 +390,7 @@ impl ChatState {
389390 .client
390391 .get_joined_room(self.id())
391392 .ok_or(IambError::NotJoined)?;
392 let info = store.application.rooms.entry(self.id().to_owned()).or_default();
393 let info = store.application.rooms.get_or_default(self.id().to_owned());
393394 let mut show_echo = true;
394395
395396 let (event_id, msg) = match act {
@@ -550,6 +551,21 @@ impl WindowOps<IambInfo> for ChatState {
550551 true
551552 }
552553
554 fn write(
555 &mut self,
556 _: Option<&str>,
557 _: WriteFlags,
558 _: &mut ProgramStore,
559 ) -> IambResult<EditInfo> {
560 // XXX: what's the right writing behaviour for a room?
561 // Should write send a message?
562 Ok(None)
563 }
564
565 fn get_completions(&self) -> Option<CompletionList> {
566 delegate!(self, w => w.get_completions())
567 }
568
553569 fn get_cursor_word(&self, style: &WordStyle) -> Option<String> {
554570 delegate!(self, w => w.get_cursor_word(style))
555571 }
src/windows/room/mod.rs +26 −4
@@ -40,7 +40,9 @@ use modalkit::{
4040 PositionList,
4141 ScrollStyle,
4242 WordStyle,
43 WriteFlags,
4344 },
45 editing::completion::CompletionList,
4446 input::InputContext,
4547 widgets::{TermOffset, TerminalCursor, WindowOps},
4648};
@@ -383,10 +385,30 @@ impl WindowOps<IambInfo> for RoomState {
383385 }
384386 }
385387
386 fn close(&mut self, _: CloseFlags, _: &mut ProgramStore) -> bool {
387 // XXX: what's the right closing behaviour for a room?
388 // Should write send a message?
389 true
388 fn close(&mut self, flags: CloseFlags, store: &mut ProgramStore) -> bool {
389 match self {
390 RoomState::Chat(chat) => chat.close(flags, store),
391 RoomState::Space(space) => space.close(flags, store),
392 }
393 }
394
395 fn write(
396 &mut self,
397 path: Option<&str>,
398 flags: WriteFlags,
399 store: &mut ProgramStore,
400 ) -> IambResult<EditInfo> {
401 match self {
402 RoomState::Chat(chat) => chat.write(path, flags, store),
403 RoomState::Space(space) => space.write(path, flags, store),
404 }
405 }
406
407 fn get_completions(&self) -> Option<CompletionList> {
408 match self {
409 RoomState::Chat(chat) => chat.get_completions(),
410 RoomState::Space(space) => space.get_completions(),
411 }
390412 }
391413
392414 fn get_cursor_word(&self, style: &WordStyle) -> Option<String> {
src/windows/room/scrollback.rs +41 −8
@@ -32,6 +32,9 @@ use modalkit::editing::{
3232 base::{
3333 Axis,
3434 CloseFlags,
35 CompletionDisplay,
36 CompletionSelection,
37 CompletionType,
3538 Count,
3639 EditRange,
3740 EditTarget,
@@ -51,7 +54,9 @@ use modalkit::editing::{
5154 TargetShape,
5255 ViewportContext,
5356 WordStyle,
57 WriteFlags,
5458 },
59 completion::CompletionList,
5560 context::{EditContext, Resolve},
5661 cursor::{CursorGroup, CursorState},
5762 history::HistoryList,
@@ -60,7 +65,7 @@ use modalkit::editing::{
6065};
6166
6267use crate::{
63 base::{IambBufferId, IambInfo, ProgramContext, ProgramStore, RoomFocus, RoomInfo},
68 base::{IambBufferId, IambInfo, IambResult, ProgramContext, ProgramStore, RoomFocus, RoomInfo},
6469 config::ApplicationSettings,
6570 message::{Message, MessageCursor, MessageKey, Messages},
6671};
@@ -515,6 +520,23 @@ impl WindowOps<IambInfo> for ScrollbackState {
515520 true
516521 }
517522
523 fn write(
524 &mut self,
525 _: Option<&str>,
526 flags: WriteFlags,
527 _: &mut ProgramStore,
528 ) -> IambResult<EditInfo> {
529 if flags.contains(WriteFlags::FORCE) {
530 Ok(None)
531 } else {
532 Err(EditError::ReadOnly.into())
533 }
534 }
535
536 fn get_completions(&self) -> Option<CompletionList> {
537 None
538 }
539
518540 fn get_cursor_word(&self, _: &WordStyle) -> Option<String> {
519541 None
520542 }
@@ -532,7 +554,7 @@ impl EditorActions<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
532554 ctx: &ProgramContext,
533555 store: &mut ProgramStore,
534556 ) -> EditResult<EditInfo, IambInfo> {
535 let info = store.application.rooms.entry(self.room_id.clone()).or_default();
557 let info = store.application.rooms.get_or_default(self.room_id.clone());
536558 let key = if let Some(k) = self.cursor.to_key(info) {
537559 k.clone()
538560 } else {
@@ -762,6 +784,17 @@ impl EditorActions<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
762784 }
763785 }
764786
787 fn complete(
788 &mut self,
789 _: &CompletionType,
790 _: &CompletionSelection,
791 _: &CompletionDisplay,
792 _: &ProgramContext,
793 _: &mut ProgramStore,
794 ) -> EditResult<EditInfo, IambInfo> {
795 Err(EditError::ReadOnly)
796 }
797
765798 fn insert_text(
766799 &mut self,
767800 _: &InsertTextAction,
@@ -867,9 +900,9 @@ impl Editable<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
867900 EditorAction::Mark(name) => self.mark(ctx.resolve(name), ctx, store),
868901 EditorAction::Selection(act) => self.selection_command(act, ctx, store),
869902
870 EditorAction::Complete(_, _) => {
871 let msg = "";
872 let err = EditError::Unimplemented(msg.into());
903 EditorAction::Complete(_, _, _) => {
904 let msg = "Nothing to complete in message scrollback";
905 let err = EditError::Failure(msg.into());
873906
874907 Err(err)
875908 },
@@ -991,7 +1024,7 @@ impl ScrollActions<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
9911024 ctx: &ProgramContext,
9921025 store: &mut ProgramStore,
9931026 ) -> EditResult<EditInfo, IambInfo> {
994 let info = store.application.rooms.entry(self.room_id.clone()).or_default();
1027 let info = store.application.rooms.get_or_default(self.room_id.clone());
9951028 let settings = &store.application.settings;
9961029 let mut corner = self.viewctx.corner.clone();
9971030
@@ -1105,7 +1138,7 @@ impl ScrollActions<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
11051138 Err(err)
11061139 },
11071140 Axis::Vertical => {
1108 let info = store.application.rooms.entry(self.room_id.clone()).or_default();
1141 let info = store.application.rooms.get_or_default(self.room_id.clone());
11091142 let settings = &store.application.settings;
11101143
11111144 if let Some(key) = self.cursor.to_key(info).cloned() {
@@ -1193,7 +1226,7 @@ impl<'a> StatefulWidget for Scrollback<'a> {
11931226 type State = ScrollbackState;
11941227
11951228 fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
1196 let info = self.store.application.rooms.entry(state.room_id.clone()).or_default();
1229 let info = self.store.application.rooms.get_or_default(state.room_id.clone());
11971230 let settings = &self.store.application.settings;
11981231 let area = info.render_typing(area, buf, &self.store.application.settings);
11991232
src/windows/welcome.rs +17 −2
@@ -8,9 +8,11 @@ use modalkit::{
88 widgets::{TermOffset, TerminalCursor},
99};
1010
11use modalkit::editing::base::{CloseFlags, WordStyle};
11use modalkit::editing::action::EditInfo;
12use modalkit::editing::base::{CloseFlags, WordStyle, WriteFlags};
13use modalkit::editing::completion::CompletionList;
1214
13use crate::base::{IambBufferId, IambInfo, ProgramStore};
15use crate::base::{IambBufferId, IambInfo, IambResult, ProgramStore};
1416
1517const WELCOME_TEXT: &str = include_str!("welcome.md");
1618
@@ -63,6 +65,19 @@ impl WindowOps<IambInfo> for WelcomeState {
6365 self.tbox.close(flags, store)
6466 }
6567
68 fn write(
69 &mut self,
70 path: Option<&str>,
71 flags: WriteFlags,
72 store: &mut ProgramStore,
73 ) -> IambResult<EditInfo> {
74 self.tbox.write(path, flags, store)
75 }
76
77 fn get_completions(&self) -> Option<CompletionList> {
78 self.tbox.get_completions()
79 }
80
6681 fn get_cursor_word(&self, style: &WordStyle) -> Option<String> {
6782 self.tbox.get_cursor_word(style)
6883 }
src/worker.rs +20 −6
@@ -32,6 +32,7 @@ use matrix_sdk::{
3232 start::{OriginalSyncKeyVerificationStartEvent, ToDeviceKeyVerificationStartEvent},
3333 VerificationMethod,
3434 },
35 presence::PresenceEvent,
3536 reaction::ReactionEventContent,
3637 room::{
3738 message::{MessageType, RoomMessageEventContent},
@@ -503,6 +504,15 @@ impl ClientWorker {
503504 },
504505 );
505506
507 let _ =
508 self.client
509 .add_event_handler(|ev: PresenceEvent, store: Ctx<AsyncProgramStore>| {
510 async move {
511 let mut locked = store.lock().await;
512 locked.application.presences.insert(ev.sender, ev.content.presence);
513 }
514 });
515
506516 let _ = self.client.add_event_handler(
507517 |ev: SyncStateEvent<RoomNameEventContent>,
508518 room: MatrixRoom,
@@ -513,8 +523,7 @@ impl ClientWorker {
513523 let room_id = room.room_id().to_owned();
514524 let room_name = Some(room_name.to_string());
515525 let mut locked = store.lock().await;
516 let mut info =
517 locked.application.rooms.entry(room_id.to_owned()).or_default();
526 let mut info = locked.application.rooms.get_or_default(room_id.clone());
518527 info.name = room_name;
519528 }
520529 }
@@ -529,8 +538,6 @@ impl ClientWorker {
529538 store: Ctx<AsyncProgramStore>| {
530539 async move {
531540 let room_id = room.room_id();
532 let room_name = room.display_name().await.ok();
533 let room_name = room_name.as_ref().map(ToString::to_string);
534541
535542 if let Some(msg) = ev.as_original() {
536543 if let MessageType::VerificationRequest(_) = msg.content.msgtype {
@@ -545,8 +552,11 @@ impl ClientWorker {
545552 }
546553
547554 let mut locked = store.lock().await;
548 let mut info = locked.application.get_room_info(room_id.to_owned());
549 info.name = room_name;
555
556 let sender = ev.sender().to_owned();
557 let _ = locked.application.presences.get_or_default(sender);
558
559 let info = locked.application.get_room_info(room_id.to_owned());
550560 info.insert(ev.into_full_event(room_id.to_owned()));
551561 }
552562 },
@@ -560,6 +570,10 @@ impl ClientWorker {
560570 let room_id = room.room_id();
561571
562572 let mut locked = store.lock().await;
573
574 let sender = ev.sender().to_owned();
575 let _ = locked.application.presences.get_or_default(sender);
576
563577 let info = locked.application.get_room_info(room_id.to_owned());
564578 info.insert_reaction(ev.into_full_event(room_id.to_owned()));
565579 }