1use crate::{settings_store::parse_json_with_comments, SettingsAssets};
2use anyhow::{anyhow, Context, Result};
3use collections::BTreeMap;
4use gpui::{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, ResultExt};
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
39impl KeymapFile {
40 pub fn load_asset(asset_path: &str, cx: &mut AppContext) -> Result<()> {
41 let content = asset_str::<SettingsAssets>(asset_path);
42
43 Self::parse(content.as_ref())?.add_to_cx(cx)
44 }
45
46 pub fn parse(content: &str) -> Result<Self> {
47 if content.is_empty() {
48 return Ok(Self::default());
49 }
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 cx.build_action(&name, Some(data))
77 }
78 Value::String(name) => cx.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 .log_err()
90 .map(|action| KeyBinding::load(&keystroke, action, context.as_deref()))
91 })
92 .collect::<Result<Vec<_>>>()?;
93
94 cx.bind_keys(bindings);
95 }
96 Ok(())
97 }
98
99 pub fn generate_json_schema(action_names: &[SharedString]) -> serde_json::Value {
100 let mut root_schema = SchemaSettings::draft07()
101 .with(|settings| settings.option_add_null_type = false)
102 .into_generator()
103 .into_root_schema_for::<KeymapFile>();
104
105 let action_schema = Schema::Object(SchemaObject {
106 subschemas: Some(Box::new(SubschemaValidation {
107 one_of: Some(vec![
108 Schema::Object(SchemaObject {
109 instance_type: Some(SingleOrVec::Single(Box::new(InstanceType::String))),
110 enum_values: Some(
111 action_names
112 .iter()
113 .map(|name| Value::String(name.to_string()))
114 .collect(),
115 ),
116 ..Default::default()
117 }),
118 Schema::Object(SchemaObject {
119 instance_type: Some(SingleOrVec::Single(Box::new(InstanceType::Array))),
120 ..Default::default()
121 }),
122 Schema::Object(SchemaObject {
123 instance_type: Some(SingleOrVec::Single(Box::new(InstanceType::Null))),
124 ..Default::default()
125 }),
126 ]),
127 ..Default::default()
128 })),
129 ..Default::default()
130 });
131
132 root_schema
133 .definitions
134 .insert("KeymapAction".to_owned(), action_schema);
135
136 serde_json::to_value(root_schema).unwrap()
137 }
138}
139
140fn no_action() -> Box<dyn gpui::Action> {
141 gpui::NoAction.boxed_clone()
142}
143
144#[cfg(test)]
145mod tests {
146 use crate::KeymapFile;
147
148 #[test]
149 fn can_deserialize_keymap_with_trailing_comma() {
150 let json = indoc::indoc! {"[
151 // Standard macOS bindings
152 {
153 \"bindings\": {
154 \"up\": \"menu::SelectPrev\",
155 },
156 },
157 ]
158 "
159
160 };
161 KeymapFile::parse(json).unwrap();
162 }
163}