1use crate::{parse_json_with_comments, Settings};
2use anyhow::{Context, Result};
3use assets::Assets;
4use collections::BTreeMap;
5use gpui::{keymap::Binding, MutableAppContext};
6use schemars::{
7 gen::{SchemaGenerator, SchemaSettings},
8 schema::{InstanceType, Schema, SchemaObject, SingleOrVec, SubschemaValidation},
9 JsonSchema,
10};
11use serde::Deserialize;
12use serde_json::{value::RawValue, Value};
13use util::ResultExt;
14
15#[derive(Deserialize, Default, Clone, JsonSchema)]
16#[serde(transparent)]
17pub struct KeymapFileContent(Vec<KeymapBlock>);
18
19#[derive(Deserialize, Default, Clone, JsonSchema)]
20pub struct KeymapBlock {
21 #[serde(default)]
22 context: Option<String>,
23 bindings: BTreeMap<String, KeymapAction>,
24}
25
26#[derive(Deserialize, Default, Clone)]
27#[serde(transparent)]
28pub struct KeymapAction(Box<RawValue>);
29
30impl JsonSchema for KeymapAction {
31 fn schema_name() -> String {
32 "KeymapAction".into()
33 }
34
35 fn json_schema(_: &mut SchemaGenerator) -> Schema {
36 Schema::Bool(true)
37 }
38}
39
40#[derive(Deserialize)]
41struct ActionWithData(Box<str>, Box<RawValue>);
42
43impl KeymapFileContent {
44 pub fn load_defaults(cx: &mut MutableAppContext) {
45 let mut paths = vec!["keymaps/default.json", "keymaps/vim.json"];
46 paths.extend(cx.global::<Settings>().experiments.keymap_files());
47 for path in paths {
48 Self::load(path, cx).unwrap();
49 }
50 }
51
52 pub fn load(asset_path: &str, cx: &mut MutableAppContext) -> Result<()> {
53 let content = Assets::get(asset_path).unwrap().data;
54 let content_str = std::str::from_utf8(content.as_ref()).unwrap();
55 parse_json_with_comments::<Self>(content_str)?.add_to_cx(cx)
56 }
57
58 pub fn add_to_cx(self, cx: &mut MutableAppContext) -> Result<()> {
59 for KeymapBlock { context, bindings } in self.0 {
60 let bindings = bindings
61 .into_iter()
62 .filter_map(|(keystroke, action)| {
63 let action = action.0.get();
64
65 // This is a workaround for a limitation in serde: serde-rs/json#497
66 // We want to deserialize the action data as a `RawValue` so that we can
67 // deserialize the action itself dynamically directly from the JSON
68 // string. But `RawValue` currently does not work inside of an untagged enum.
69 if action.starts_with('[') {
70 let ActionWithData(name, data) = serde_json::from_str(action).log_err()?;
71 cx.deserialize_action(&name, Some(data.get()))
72 } else {
73 let name = serde_json::from_str(action).log_err()?;
74 cx.deserialize_action(name, None)
75 }
76 .with_context(|| {
77 format!(
78 "invalid binding value for keystroke {keystroke}, context {context:?}"
79 )
80 })
81 .log_err()
82 .map(|action| Binding::load(&keystroke, action, context.as_deref()))
83 })
84 .collect::<Result<Vec<_>>>()?;
85
86 cx.add_bindings(bindings);
87 }
88 Ok(())
89 }
90}
91
92pub fn keymap_file_json_schema(action_names: &[&'static str]) -> serde_json::Value {
93 let mut root_schema = SchemaSettings::draft07()
94 .with(|settings| settings.option_add_null_type = false)
95 .into_generator()
96 .into_root_schema_for::<KeymapFileContent>();
97
98 let action_schema = Schema::Object(SchemaObject {
99 subschemas: Some(Box::new(SubschemaValidation {
100 one_of: Some(vec![
101 Schema::Object(SchemaObject {
102 instance_type: Some(SingleOrVec::Single(Box::new(InstanceType::String))),
103 enum_values: Some(
104 action_names
105 .iter()
106 .map(|name| Value::String(name.to_string()))
107 .collect(),
108 ),
109 ..Default::default()
110 }),
111 Schema::Object(SchemaObject {
112 instance_type: Some(SingleOrVec::Single(Box::new(InstanceType::Array))),
113 ..Default::default()
114 }),
115 ]),
116 ..Default::default()
117 })),
118 ..Default::default()
119 });
120
121 root_schema
122 .definitions
123 .insert("KeymapAction".to_owned(), action_schema);
124
125 serde_json::to_value(root_schema).unwrap()
126}