1use crate::settings_store::parse_json_with_comments;
2use anyhow::{Context, Result};
3use assets::Assets;
4use collections::BTreeMap;
5use gpui::{keymap_matcher::Binding, AppContext};
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_asset(asset_path: &str, cx: &mut AppContext) -> Result<()> {
45 let content = Assets::get(asset_path).unwrap().data;
46 let content_str = std::str::from_utf8(content.as_ref()).unwrap();
47 Self::parse(content_str)?.add_to_cx(cx)
48 }
49
50 pub fn parse(content: &str) -> Result<Self> {
51 parse_json_with_comments::<Self>(content)
52 }
53
54 pub fn add_to_cx(self, cx: &mut AppContext) -> Result<()> {
55 for KeymapBlock { context, bindings } in self.0 {
56 let bindings = bindings
57 .into_iter()
58 .filter_map(|(keystroke, action)| {
59 let action = action.0.get();
60
61 // This is a workaround for a limitation in serde: serde-rs/json#497
62 // We want to deserialize the action data as a `RawValue` so that we can
63 // deserialize the action itself dynamically directly from the JSON
64 // string. But `RawValue` currently does not work inside of an untagged enum.
65 if action.starts_with('[') {
66 let ActionWithData(name, data) = serde_json::from_str(action).log_err()?;
67 cx.deserialize_action(&name, Some(data.get()))
68 } else {
69 let name = serde_json::from_str(action).log_err()?;
70 cx.deserialize_action(name, None)
71 }
72 .with_context(|| {
73 format!(
74 "invalid binding value for keystroke {keystroke}, context {context:?}"
75 )
76 })
77 .log_err()
78 .map(|action| Binding::load(&keystroke, action, context.as_deref()))
79 })
80 .collect::<Result<Vec<_>>>()?;
81
82 cx.add_bindings(bindings);
83 }
84 Ok(())
85 }
86}
87
88pub fn keymap_file_json_schema(action_names: &[&'static str]) -> serde_json::Value {
89 let mut root_schema = SchemaSettings::draft07()
90 .with(|settings| settings.option_add_null_type = false)
91 .into_generator()
92 .into_root_schema_for::<KeymapFileContent>();
93
94 let action_schema = Schema::Object(SchemaObject {
95 subschemas: Some(Box::new(SubschemaValidation {
96 one_of: Some(vec![
97 Schema::Object(SchemaObject {
98 instance_type: Some(SingleOrVec::Single(Box::new(InstanceType::String))),
99 enum_values: Some(
100 action_names
101 .iter()
102 .map(|name| Value::String(name.to_string()))
103 .collect(),
104 ),
105 ..Default::default()
106 }),
107 Schema::Object(SchemaObject {
108 instance_type: Some(SingleOrVec::Single(Box::new(InstanceType::Array))),
109 ..Default::default()
110 }),
111 ]),
112 ..Default::default()
113 })),
114 ..Default::default()
115 });
116
117 root_schema
118 .definitions
119 .insert("KeymapAction".to_owned(), action_schema);
120
121 serde_json::to_value(root_schema).unwrap()
122}