1use crate::{settings_store::parse_json_with_comments, SettingsAssets};
2use anyhow::{anyhow, Context, Result};
3use collections::BTreeMap;
4use gpui::{actions, Action, AppContext, KeyBinding, SharedString};
5use schemars::{
6 gen::{SchemaGenerator, SchemaSettings},
7 schema::{InstanceType, Schema, SchemaObject, SingleOrVec, SubschemaValidation},
8 JsonSchema,
9};
10use serde::Deserialize;
11use serde_json::Value;
12use util::asset_str;
13
14#[derive(Debug, Deserialize, Default, Clone, JsonSchema)]
15#[serde(transparent)]
16pub struct KeymapFile(Vec<KeymapBlock>);
17
18#[derive(Debug, Deserialize, Default, Clone, JsonSchema)]
19pub struct KeymapBlock {
20 #[serde(default)]
21 context: Option<String>,
22 bindings: BTreeMap<String, KeymapAction>,
23}
24
25#[derive(Debug, Deserialize, Default, Clone)]
26#[serde(transparent)]
27pub struct KeymapAction(Value);
28
29impl JsonSchema for KeymapAction {
30 fn schema_name() -> String {
31 "KeymapAction".into()
32 }
33
34 fn json_schema(_: &mut SchemaGenerator) -> Schema {
35 Schema::Bool(true)
36 }
37}
38
39#[derive(Deserialize)]
40struct ActionWithData(Box<str>, Value);
41
42impl KeymapFile {
43 pub fn load_asset(asset_path: &str, cx: &mut AppContext) -> Result<()> {
44 let content = asset_str::<SettingsAssets>(asset_path);
45
46 Self::parse(content.as_ref())?.add_to_cx(cx)
47 }
48
49 pub fn parse(content: &str) -> Result<Self> {
50 parse_json_with_comments::<Self>(content)
51 }
52
53 pub fn add_to_cx(self, cx: &mut AppContext) -> Result<()> {
54 for KeymapBlock { context, bindings } in self.0 {
55 let bindings = bindings
56 .into_iter()
57 .filter_map(|(keystroke, action)| {
58 let action = action.0;
59
60 // This is a workaround for a limitation in serde: serde-rs/json#497
61 // We want to deserialize the action data as a `RawValue` so that we can
62 // deserialize the action itself dynamically directly from the JSON
63 // string. But `RawValue` currently does not work inside of an untagged enum.
64 match action {
65 Value::Array(items) => {
66 let Ok([name, data]): Result<[serde_json::Value; 2], _> =
67 items.try_into()
68 else {
69 return Some(Err(anyhow!("Expected array of length 2")));
70 };
71 let serde_json::Value::String(name) = name else {
72 return Some(Err(anyhow!(
73 "Expected first item in array to be a string."
74 )));
75 };
76 gpui::build_action(&name, Some(data))
77 }
78 Value::String(name) => gpui::build_action(&name, None),
79 Value::Null => Ok(no_action()),
80 _ => {
81 return Some(Err(anyhow!("Expected two-element array, got {action:?}")))
82 }
83 }
84 .with_context(|| {
85 format!(
86 "invalid binding value for keystroke {keystroke}, context {context:?}"
87 )
88 })
89 // todo!()
90 .ok()
91 // .log_err()
92 .map(|action| KeyBinding::load(&keystroke, action, context.as_deref()))
93 })
94 .collect::<Result<Vec<_>>>()?;
95
96 cx.bind_keys(bindings);
97 }
98 Ok(())
99 }
100
101 pub fn generate_json_schema(action_names: &[SharedString]) -> serde_json::Value {
102 let mut root_schema = SchemaSettings::draft07()
103 .with(|settings| settings.option_add_null_type = false)
104 .into_generator()
105 .into_root_schema_for::<KeymapFile>();
106
107 let action_schema = Schema::Object(SchemaObject {
108 subschemas: Some(Box::new(SubschemaValidation {
109 one_of: Some(vec![
110 Schema::Object(SchemaObject {
111 instance_type: Some(SingleOrVec::Single(Box::new(InstanceType::String))),
112 enum_values: Some(
113 action_names
114 .iter()
115 .map(|name| Value::String(name.to_string()))
116 .collect(),
117 ),
118 ..Default::default()
119 }),
120 Schema::Object(SchemaObject {
121 instance_type: Some(SingleOrVec::Single(Box::new(InstanceType::Array))),
122 ..Default::default()
123 }),
124 Schema::Object(SchemaObject {
125 instance_type: Some(SingleOrVec::Single(Box::new(InstanceType::Null))),
126 ..Default::default()
127 }),
128 ]),
129 ..Default::default()
130 })),
131 ..Default::default()
132 });
133
134 root_schema
135 .definitions
136 .insert("KeymapAction".to_owned(), action_schema);
137
138 serde_json::to_value(root_schema).unwrap()
139 }
140}
141
142actions!(NoAction);
143
144fn no_action() -> Box<dyn gpui::Action> {
145 NoAction.boxed_clone()
146}
147
148#[cfg(test)]
149mod tests {
150 use crate::KeymapFile;
151
152 #[test]
153 fn can_deserialize_keymap_with_trailing_comma() {
154 let json = indoc::indoc! {"[
155 // Standard macOS bindings
156 {
157 \"bindings\": {
158 \"up\": \"menu::SelectPrev\",
159 },
160 },
161 ]
162 "
163
164 };
165 KeymapFile::parse(json).unwrap();
166 }
167}