1use crate::{settings_store::parse_json_with_comments, SettingsAssets};
2use anyhow::{anyhow, Context, Result};
3use collections::BTreeMap;
4use gpui::{keymap_matcher::Binding, AppContext, NoAction};
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
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], _> = items.try_into() else {
67 return Some(Err(anyhow!("Expected array of length 2")));
68 };
69 let serde_json::Value::String(name) = name else {
70 return Some(Err(anyhow!("Expected first item in array to be a string.")))
71 };
72 cx.deserialize_action(
73 &name,
74 Some(data),
75 )
76 },
77 Value::String(name) => cx.deserialize_action(&name, None),
78 Value::Null => Ok(no_action()),
79 _ => return Some(Err(anyhow!("Expected two-element array, got {action:?}"))),
80 }
81 .with_context(|| {
82 format!(
83 "invalid binding value for keystroke {keystroke}, context {context:?}"
84 )
85 })
86 .log_err()
87 .map(|action| Binding::load(&keystroke, action, context.as_deref()))
88 })
89 .collect::<Result<Vec<_>>>()?;
90
91 cx.add_bindings(bindings);
92 }
93 Ok(())
94 }
95
96 pub fn generate_json_schema(action_names: &[&'static str]) -> serde_json::Value {
97 let mut root_schema = SchemaSettings::draft07()
98 .with(|settings| settings.option_add_null_type = false)
99 .into_generator()
100 .into_root_schema_for::<KeymapFile>();
101
102 let action_schema = Schema::Object(SchemaObject {
103 subschemas: Some(Box::new(SubschemaValidation {
104 one_of: Some(vec![
105 Schema::Object(SchemaObject {
106 instance_type: Some(SingleOrVec::Single(Box::new(InstanceType::String))),
107 enum_values: Some(
108 action_names
109 .iter()
110 .map(|name| Value::String(name.to_string()))
111 .collect(),
112 ),
113 ..Default::default()
114 }),
115 Schema::Object(SchemaObject {
116 instance_type: Some(SingleOrVec::Single(Box::new(InstanceType::Array))),
117 ..Default::default()
118 }),
119 Schema::Object(SchemaObject {
120 instance_type: Some(SingleOrVec::Single(Box::new(InstanceType::Null))),
121 ..Default::default()
122 }),
123 ]),
124 ..Default::default()
125 })),
126 ..Default::default()
127 });
128
129 root_schema
130 .definitions
131 .insert("KeymapAction".to_owned(), action_schema);
132
133 serde_json::to_value(root_schema).unwrap()
134 }
135}
136
137fn no_action() -> Box<dyn gpui::Action> {
138 Box::new(NoAction {})
139}
140
141#[cfg(test)]
142mod tests {
143 use crate::KeymapFile;
144
145 #[test]
146 fn can_deserialize_keymap_with_trailing_comma() {
147 let json = indoc::indoc! {"[
148 // Standard macOS bindings
149 {
150 \"bindings\": {
151 \"up\": \"menu::SelectPrev\",
152 },
153 },
154 ]
155 "
156
157 };
158 KeymapFile::parse(json).unwrap();
159 }
160}