1use std::sync::{Arc, LazyLock};
2
3use anyhow::{Context as _, Result};
4use collections::HashMap;
5use gpui::{App, AsyncApp, BorrowAppContext as _, Entity, Task, WeakEntity};
6use language::{
7 LanguageRegistry, LanguageServerName, LspAdapterDelegate,
8 language_settings::AllLanguageSettings,
9};
10use parking_lot::RwLock;
11use project::{LspStore, lsp_store::LocalLspAdapterDelegate};
12use settings::{LSP_SETTINGS_SCHEMA_URL_PREFIX, Settings as _, SettingsLocation};
13use util::schemars::{AllowTrailingCommas, DefaultDenyUnknownFields};
14
15const SCHEMA_URI_PREFIX: &str = "zed://schemas/";
16
17const TSCONFIG_SCHEMA: &str = include_str!("schemas/tsconfig.json");
18const PACKAGE_JSON_SCHEMA: &str = include_str!("schemas/package.json");
19
20static TASKS_SCHEMA: LazyLock<String> = LazyLock::new(|| {
21 serde_json::to_string(&task::TaskTemplates::generate_json_schema())
22 .expect("TaskTemplates schema should serialize")
23});
24
25static SNIPPETS_SCHEMA: LazyLock<String> = LazyLock::new(|| {
26 serde_json::to_string(&snippet_provider::format::VsSnippetsFile::generate_json_schema())
27 .expect("VsSnippetsFile schema should serialize")
28});
29
30static JSONC_SCHEMA: LazyLock<String> = LazyLock::new(|| {
31 serde_json::to_string(&generate_jsonc_schema()).expect("JSONC schema should serialize")
32});
33
34#[cfg(debug_assertions)]
35static INSPECTOR_STYLE_SCHEMA: LazyLock<String> = LazyLock::new(|| {
36 serde_json::to_string(&generate_inspector_style_schema())
37 .expect("Inspector style schema should serialize")
38});
39
40static KEYMAP_SCHEMA: LazyLock<String> = LazyLock::new(|| {
41 serde_json::to_string(&settings::KeymapFile::generate_json_schema_from_inventory())
42 .expect("Keymap schema should serialize")
43});
44
45static ACTION_SCHEMA_CACHE: LazyLock<RwLock<HashMap<String, String>>> =
46 LazyLock::new(|| RwLock::new(HashMap::default()));
47
48// Runtime cache for dynamic schemas that depend on runtime state:
49// - "settings": depends on installed fonts, themes, languages, LSP adapters (extensions can add these)
50// - "settings/lsp/*": depends on LSP adapter initialization options
51// - "debug_tasks": depends on DAP adapters (extensions can add these)
52// Cache is invalidated via notify_schema_changed() when extensions or DAP registry change.
53static DYNAMIC_SCHEMA_CACHE: LazyLock<RwLock<HashMap<String, String>>> =
54 LazyLock::new(|| RwLock::new(HashMap::default()));
55
56pub fn init(cx: &mut App) {
57 cx.set_global(SchemaStore::default());
58 project::lsp_store::json_language_server_ext::register_schema_handler(
59 handle_schema_request,
60 cx,
61 );
62
63 cx.observe_new(|_, _, cx| {
64 let lsp_store = cx.weak_entity();
65 cx.global_mut::<SchemaStore>().lsp_stores.push(lsp_store);
66 })
67 .detach();
68
69 if let Some(extension_events) = extension::ExtensionEvents::try_global(cx) {
70 cx.subscribe(&extension_events, move |_, evt, cx| match evt {
71 extension::Event::ExtensionsInstalledChanged => {
72 cx.update_global::<SchemaStore, _>(|schema_store, cx| {
73 schema_store.notify_schema_changed(ChangedSchemas::Settings, cx);
74 });
75 }
76 extension::Event::ExtensionUninstalled(_)
77 | extension::Event::ExtensionInstalled(_)
78 | extension::Event::ConfigureExtensionRequested(_) => {}
79 })
80 .detach();
81 }
82
83 cx.observe_global::<dap::DapRegistry>(move |cx| {
84 cx.update_global::<SchemaStore, _>(|schema_store, cx| {
85 schema_store.notify_schema_changed(ChangedSchemas::DebugTasks, cx);
86 });
87 })
88 .detach();
89}
90
91#[derive(Default)]
92pub struct SchemaStore {
93 lsp_stores: Vec<WeakEntity<LspStore>>,
94}
95
96impl gpui::Global for SchemaStore {}
97
98enum ChangedSchemas {
99 Settings,
100 DebugTasks,
101}
102
103impl SchemaStore {
104 fn notify_schema_changed(&mut self, changed_schemas: ChangedSchemas, cx: &mut App) {
105 let uris_to_invalidate = match changed_schemas {
106 ChangedSchemas::Settings => {
107 let settings_uri_prefix = &format!("{SCHEMA_URI_PREFIX}settings");
108 let project_settings_uri = &format!("{SCHEMA_URI_PREFIX}project_settings");
109 DYNAMIC_SCHEMA_CACHE
110 .write()
111 .extract_if(|uri, _| {
112 uri == project_settings_uri || uri.starts_with(settings_uri_prefix)
113 })
114 .map(|(url, _)| url)
115 .collect()
116 }
117 ChangedSchemas::DebugTasks => DYNAMIC_SCHEMA_CACHE
118 .write()
119 .remove_entry(&format!("{SCHEMA_URI_PREFIX}debug_tasks"))
120 .map_or_else(Vec::new, |(uri, _)| vec![uri]),
121 };
122
123 if uris_to_invalidate.is_empty() {
124 return;
125 }
126
127 self.lsp_stores.retain(|lsp_store| {
128 let Some(lsp_store) = lsp_store.upgrade() else {
129 return false;
130 };
131 project::lsp_store::json_language_server_ext::notify_schemas_changed(
132 lsp_store,
133 &uris_to_invalidate,
134 cx,
135 );
136 true
137 })
138 }
139}
140
141pub fn handle_schema_request(
142 lsp_store: Entity<LspStore>,
143 uri: String,
144 cx: &mut AsyncApp,
145) -> Task<Result<String>> {
146 let path = match uri.strip_prefix(SCHEMA_URI_PREFIX) {
147 Some(path) => path,
148 None => return Task::ready(Err(anyhow::anyhow!("Invalid schema URI: {}", uri))),
149 };
150
151 if let Some(json) = resolve_static_schema(path) {
152 return Task::ready(Ok(json));
153 }
154
155 if let Some(cached) = DYNAMIC_SCHEMA_CACHE.read().get(&uri).cloned() {
156 return Task::ready(Ok(cached));
157 }
158
159 let path = path.to_string();
160 let uri_clone = uri.clone();
161 cx.spawn(async move |cx| {
162 let schema = resolve_dynamic_schema(lsp_store, &path, cx).await?;
163 let json = serde_json::to_string(&schema).context("Failed to serialize schema")?;
164
165 DYNAMIC_SCHEMA_CACHE.write().insert(uri_clone, json.clone());
166
167 Ok(json)
168 })
169}
170
171fn resolve_static_schema(path: &str) -> Option<String> {
172 let (schema_name, rest) = path.split_once('/').unzip();
173 let schema_name = schema_name.unwrap_or(path);
174
175 match schema_name {
176 "tsconfig" => Some(TSCONFIG_SCHEMA.to_string()),
177 "package_json" => Some(PACKAGE_JSON_SCHEMA.to_string()),
178 "tasks" => Some(TASKS_SCHEMA.clone()),
179 "snippets" => Some(SNIPPETS_SCHEMA.clone()),
180 "jsonc" => Some(JSONC_SCHEMA.clone()),
181 "keymap" => Some(KEYMAP_SCHEMA.clone()),
182 "zed_inspector_style" => {
183 #[cfg(debug_assertions)]
184 {
185 Some(INSPECTOR_STYLE_SCHEMA.clone())
186 }
187 #[cfg(not(debug_assertions))]
188 {
189 Some(
190 serde_json::to_string(&schemars::json_schema!(true).to_value())
191 .expect("true schema should serialize"),
192 )
193 }
194 }
195
196 "action" => {
197 let normalized_action_name = match rest {
198 Some(name) => name,
199 None => return None,
200 };
201 let action_name = denormalize_action_name(normalized_action_name);
202
203 if let Some(cached) = ACTION_SCHEMA_CACHE.read().get(&action_name).cloned() {
204 return Some(cached);
205 }
206
207 let mut generator = settings::KeymapFile::action_schema_generator();
208 let schema =
209 settings::KeymapFile::get_action_schema_by_name(&action_name, &mut generator);
210 let json = serde_json::to_string(
211 &root_schema_from_action_schema(schema, &mut generator).to_value(),
212 )
213 .expect("Action schema should serialize");
214
215 ACTION_SCHEMA_CACHE
216 .write()
217 .insert(action_name, json.clone());
218 Some(json)
219 }
220
221 _ => None,
222 }
223}
224
225async fn resolve_dynamic_schema(
226 lsp_store: Entity<LspStore>,
227 path: &str,
228 cx: &mut AsyncApp,
229) -> Result<serde_json::Value> {
230 let languages = lsp_store.read_with(cx, |lsp_store, _| lsp_store.languages.clone());
231 let (schema_name, rest) = path.split_once('/').unzip();
232 let schema_name = schema_name.unwrap_or(path);
233
234 let schema = match schema_name {
235 "settings" if rest.is_some_and(|r| r.starts_with("lsp/")) => {
236 let lsp_path = rest
237 .and_then(|r| {
238 r.strip_prefix(
239 LSP_SETTINGS_SCHEMA_URL_PREFIX
240 .strip_prefix(SCHEMA_URI_PREFIX)
241 .and_then(|s| s.strip_prefix("settings/"))
242 .unwrap_or("lsp/"),
243 )
244 })
245 .context("Invalid LSP schema path")?;
246
247 // Parse the schema type from the path:
248 // - "rust-analyzer/initialization_options" → initialization_options_schema
249 // - "rust-analyzer/settings" → settings_schema
250 enum LspSchemaKind {
251 InitializationOptions,
252 Settings,
253 }
254 let (lsp_name, schema_kind) = if let Some(adapter_name) =
255 lsp_path.strip_suffix("/initialization_options")
256 {
257 (adapter_name, LspSchemaKind::InitializationOptions)
258 } else if let Some(adapter_name) = lsp_path.strip_suffix("/settings") {
259 (adapter_name, LspSchemaKind::Settings)
260 } else {
261 anyhow::bail!(
262 "Invalid LSP schema path: \
263 Expected '{{adapter}}/initialization_options' or '{{adapter}}/settings', got '{}'",
264 lsp_path
265 );
266 };
267
268 let adapter = languages
269 .all_lsp_adapters()
270 .into_iter()
271 .find(|adapter| adapter.name().as_ref() as &str == lsp_name)
272 .or_else(|| {
273 languages.load_available_lsp_adapter(&LanguageServerName::from(lsp_name))
274 })
275 .with_context(|| format!("LSP adapter not found: {}", lsp_name))?;
276
277 let delegate: Arc<dyn LspAdapterDelegate> = cx
278 .update(|inner_cx| {
279 lsp_store.update(inner_cx, |lsp_store, cx| {
280 let Some(local) = lsp_store.as_local() else {
281 return None;
282 };
283 let Some(worktree) = local.worktree_store.read(cx).worktrees().next()
284 else {
285 return None;
286 };
287 Some(LocalLspAdapterDelegate::from_local_lsp(
288 local, &worktree, cx,
289 ))
290 })
291 })
292 .context(concat!(
293 "Failed to create adapter delegate - ",
294 "either LSP store is not in local mode or no worktree is available"
295 ))?;
296
297 let schema = match schema_kind {
298 LspSchemaKind::InitializationOptions => {
299 adapter.initialization_options_schema(&delegate, cx).await
300 }
301 LspSchemaKind::Settings => adapter.settings_schema(&delegate, cx).await,
302 };
303
304 schema.unwrap_or_else(|| {
305 serde_json::json!({
306 "type": "object",
307 "additionalProperties": true
308 })
309 })
310 }
311 "settings" => {
312 let mut lsp_adapter_names: Vec<String> = languages
313 .all_lsp_adapters()
314 .into_iter()
315 .map(|adapter| adapter.name())
316 .chain(languages.available_lsp_adapter_names().into_iter())
317 .map(|name| name.to_string())
318 .collect();
319
320 let mut i = 0;
321 while i < lsp_adapter_names.len() {
322 let mut j = i + 1;
323 while j < lsp_adapter_names.len() {
324 if lsp_adapter_names[i] == lsp_adapter_names[j] {
325 lsp_adapter_names.swap_remove(j);
326 } else {
327 j += 1;
328 }
329 }
330 i += 1;
331 }
332
333 cx.update(|cx| {
334 let font_names = &cx.text_system().all_font_names();
335 let language_names = &languages
336 .language_names()
337 .into_iter()
338 .map(|name| name.to_string())
339 .collect::<Vec<_>>();
340
341 let mut icon_theme_names = vec![];
342 let mut theme_names = vec![];
343 if let Some(registry) = theme::ThemeRegistry::try_global(cx) {
344 icon_theme_names.extend(
345 registry
346 .list_icon_themes()
347 .into_iter()
348 .map(|icon_theme| icon_theme.name),
349 );
350 theme_names.extend(registry.list_names());
351 }
352 let icon_theme_names = icon_theme_names.as_slice();
353 let theme_names = theme_names.as_slice();
354
355 settings::SettingsStore::json_schema(&settings::SettingsJsonSchemaParams {
356 language_names,
357 font_names,
358 theme_names,
359 icon_theme_names,
360 lsp_adapter_names: &lsp_adapter_names,
361 })
362 })
363 }
364 "project_settings" => {
365 let lsp_adapter_names = languages
366 .all_lsp_adapters()
367 .into_iter()
368 .map(|adapter| adapter.name().to_string())
369 .collect::<Vec<_>>();
370
371 let language_names = &languages
372 .language_names()
373 .into_iter()
374 .map(|name| name.to_string())
375 .collect::<Vec<_>>();
376
377 settings::SettingsStore::project_json_schema(&settings::SettingsJsonSchemaParams {
378 language_names,
379 lsp_adapter_names: &lsp_adapter_names,
380 // These are not allowed in project-specific settings but
381 // they're still fields required by the
382 // `SettingsJsonSchemaParams` struct.
383 font_names: &[],
384 theme_names: &[],
385 icon_theme_names: &[],
386 })
387 }
388 "debug_tasks" => {
389 let adapter_schemas = cx.read_global::<dap::DapRegistry, _>(|dap_registry, _| {
390 dap_registry.adapters_schema()
391 });
392 task::DebugTaskFile::generate_json_schema(&adapter_schemas)
393 }
394 "keymap" => cx.update(settings::KeymapFile::generate_json_schema_for_registered_actions),
395 "action" => {
396 let normalized_action_name = rest.context("No Action name provided")?;
397 let action_name = denormalize_action_name(normalized_action_name);
398 let mut generator = settings::KeymapFile::action_schema_generator();
399 let schema = cx
400 .update(|cx| cx.action_schema_by_name(&action_name, &mut generator))
401 .flatten();
402 root_schema_from_action_schema(schema, &mut generator).to_value()
403 }
404 "tasks" => task::TaskTemplates::generate_json_schema(),
405 _ => {
406 anyhow::bail!("Unrecognized schema: {schema_name}");
407 }
408 };
409 Ok(schema)
410}
411
412const JSONC_LANGUAGE_NAME: &str = "JSONC";
413
414pub fn all_schema_file_associations(
415 languages: &Arc<LanguageRegistry>,
416 path: Option<SettingsLocation<'_>>,
417 cx: &mut App,
418) -> serde_json::Value {
419 let extension_globs = languages
420 .available_language_for_name(JSONC_LANGUAGE_NAME)
421 .map(|language| language.matcher().path_suffixes.clone())
422 .into_iter()
423 .flatten()
424 // Path suffixes can be entire file names or just their extensions.
425 .flat_map(|path_suffix| [format!("*.{path_suffix}"), path_suffix]);
426 let override_globs = AllLanguageSettings::get(path, cx)
427 .file_types
428 .get(JSONC_LANGUAGE_NAME)
429 .into_iter()
430 .flat_map(|(_, glob_strings)| glob_strings)
431 .cloned();
432 let jsonc_globs = extension_globs.chain(override_globs).collect::<Vec<_>>();
433
434 let mut file_associations = serde_json::json!([
435 {
436 "fileMatch": [
437 schema_file_match(paths::settings_file()),
438 ],
439 "url": format!("{SCHEMA_URI_PREFIX}settings"),
440 },
441 {
442 "fileMatch": [
443 paths::local_settings_file_relative_path()],
444 "url": format!("{SCHEMA_URI_PREFIX}project_settings"),
445 },
446 {
447 "fileMatch": [schema_file_match(paths::keymap_file())],
448 "url": format!("{SCHEMA_URI_PREFIX}keymap"),
449 },
450 {
451 "fileMatch": [
452 schema_file_match(paths::tasks_file()),
453 paths::local_tasks_file_relative_path()
454 ],
455 "url": format!("{SCHEMA_URI_PREFIX}tasks"),
456 },
457 {
458 "fileMatch": [
459 schema_file_match(paths::debug_scenarios_file()),
460 paths::local_debug_file_relative_path()
461 ],
462 "url": format!("{SCHEMA_URI_PREFIX}debug_tasks"),
463 },
464 {
465 "fileMatch": [
466 schema_file_match(
467 paths::snippets_dir()
468 .join("*.json")
469 .as_path()
470 )
471 ],
472 "url": format!("{SCHEMA_URI_PREFIX}snippets"),
473 },
474 {
475 "fileMatch": ["tsconfig.json"],
476 "url": format!("{SCHEMA_URI_PREFIX}tsconfig")
477 },
478 {
479 "fileMatch": ["package.json"],
480 "url": format!("{SCHEMA_URI_PREFIX}package_json")
481 },
482 {
483 "fileMatch": &jsonc_globs,
484 "url": format!("{SCHEMA_URI_PREFIX}jsonc")
485 },
486 ]);
487
488 #[cfg(debug_assertions)]
489 {
490 file_associations
491 .as_array_mut()
492 .unwrap()
493 .push(serde_json::json!({
494 "fileMatch": [
495 "zed-inspector-style.json"
496 ],
497 "url": format!("{SCHEMA_URI_PREFIX}zed_inspector_style")
498 }));
499 }
500
501 file_associations
502 .as_array_mut()
503 .unwrap()
504 .extend(cx.all_action_names().into_iter().map(|&name| {
505 let normalized_name = normalize_action_name(name);
506 let file_name = normalized_action_name_to_file_name(normalized_name.clone());
507 serde_json::json!({
508 "fileMatch": [file_name],
509 "url": format!("{SCHEMA_URI_PREFIX}action/{normalized_name}")
510 })
511 }));
512
513 file_associations
514}
515
516fn generate_jsonc_schema() -> serde_json::Value {
517 let generator = schemars::generate::SchemaSettings::draft2019_09()
518 .with_transform(DefaultDenyUnknownFields)
519 .with_transform(AllowTrailingCommas)
520 .into_generator();
521 let meta_schema = generator
522 .settings()
523 .meta_schema
524 .as_ref()
525 .expect("meta_schema should be present in schemars settings")
526 .to_string();
527 let defs = generator.definitions();
528 let schema = schemars::json_schema!({
529 "$schema": meta_schema,
530 "allowTrailingCommas": true,
531 "$defs": defs,
532 });
533 serde_json::to_value(schema).unwrap()
534}
535
536#[cfg(debug_assertions)]
537fn generate_inspector_style_schema() -> serde_json::Value {
538 let schema = schemars::generate::SchemaSettings::draft2019_09()
539 .with_transform(util::schemars::DefaultDenyUnknownFields)
540 .into_generator()
541 .root_schema_for::<gpui::StyleRefinement>();
542
543 serde_json::to_value(schema).unwrap()
544}
545
546pub fn normalize_action_name(action_name: &str) -> String {
547 action_name.replace("::", "__")
548}
549
550pub fn denormalize_action_name(action_name: &str) -> String {
551 action_name.replace("__", "::")
552}
553
554pub fn normalized_action_file_name(action_name: &str) -> String {
555 normalized_action_name_to_file_name(normalize_action_name(action_name))
556}
557
558pub fn normalized_action_name_to_file_name(mut normalized_action_name: String) -> String {
559 normalized_action_name.push_str(".json");
560 normalized_action_name
561}
562
563fn root_schema_from_action_schema(
564 action_schema: Option<schemars::Schema>,
565 generator: &mut schemars::SchemaGenerator,
566) -> schemars::Schema {
567 let Some(mut action_schema) = action_schema else {
568 return schemars::json_schema!(false);
569 };
570 let meta_schema = generator
571 .settings()
572 .meta_schema
573 .as_ref()
574 .expect("meta_schema should be present in schemars settings")
575 .to_string();
576 let defs = generator.definitions();
577 let mut schema = schemars::json_schema!({
578 "$schema": meta_schema,
579 "allowTrailingCommas": true,
580 "$defs": defs,
581 });
582 schema
583 .ensure_object()
584 .extend(std::mem::take(action_schema.ensure_object()));
585 schema
586}
587
588#[inline]
589fn schema_file_match(path: &std::path::Path) -> String {
590 path.strip_prefix(path.parent().unwrap().parent().unwrap())
591 .unwrap()
592 .display()
593 .to_string()
594 .replace('\\', "/")
595}