1use std::collections::{BTreeMap, BTreeSet};
4use std::fs;
5use std::path::Path;
6
7use gpui_kit::component::{ThemeRegistry, ThemeSet};
8use gpui_kit::{App, Global};
9use serde_json::Value;
10use subspace_dashboard::CurrentProduct;
11use subspace_product::ValidatedProduct;
12
13use super::{GPUI_KIT_THEMES, SUBSPACE_THEMES, ThemeDocument};
14
15pub(super) struct ThemeChoices {
16 pub(super) documents: BTreeMap<String, ThemeDocument>,
17}
18
19impl Global for ThemeChoices {}
20
21pub type ProductThemes = &'static [(&'static str, &'static str)];
24
25const CUSTOM_THEME_ID: &str = "custom";
27
28const KIT_PRELOADED_THEMES: [&str; 2] = ["Default Dark", "Default Light"];
32
33struct ProductThemeDocuments(ProductThemes);
35
36impl Global for ProductThemeDocuments {}
37
38pub(crate) fn install_product_themes(themes: ProductThemes, cx: &mut App) {
41 cx.set_global(ProductThemeDocuments(themes));
42}
43
44pub(crate) fn product_themes(cx: &App) -> ProductThemes {
46 cx.try_global::<ProductThemeDocuments>()
47 .map_or(&[], |documents| documents.0)
48}
49
50fn catalogue(product: ProductThemes) -> impl Iterator<Item = (&'static str, &'static str)> {
52 product
53 .iter()
54 .chain(SUBSPACE_THEMES)
55 .chain(GPUI_KIT_THEMES)
56 .copied()
57}
58
59fn bundled_theme(id: &str, product: ProductThemes) -> Result<&'static str, String> {
60 catalogue(product)
61 .find(|(name, _)| *name == id)
62 .map(|(_, content)| content)
63 .ok_or_else(|| format!("product theme is not embedded: {id}"))
64}
65
66pub(crate) fn validate_product_theme_documents(product: ProductThemes) -> Result<(), String> {
73 let documents = product
74 .iter()
75 .map(|(id, content)| product_document(id, content))
76 .collect::<Result<Vec<_>, _>>()?;
77 require_unique_product_names(&documents, reserved_theme_names(&[])?)
78}
79
80fn product_document(
82 id: &'static str,
83 content: &str,
84) -> Result<(&'static str, Vec<String>), String> {
85 serde_json::from_str::<ThemeSet>(content)
86 .map_err(|error| error.to_string())
87 .and_then(|_| theme_documents(content))
88 .map(|variants| (id, variants.into_keys().collect()))
89 .map_err(|error| format!("product theme {id}: {error}"))
90}
91
92fn require_unique_product_names(
95 documents: &[(&str, Vec<String>)],
96 mut reserved: BTreeSet<String>,
97) -> Result<(), String> {
98 let mut ids = BTreeSet::new();
99 for (id, names) in documents {
100 if *id == CUSTOM_THEME_ID {
101 return Err(format!("product theme id is reserved: {id}"));
102 }
103 let reused = SUBSPACE_THEMES
104 .iter()
105 .chain(GPUI_KIT_THEMES)
106 .any(|(name, _)| name == id);
107 if reused || !ids.insert(*id) {
108 return Err(format!("product theme id is already in use: {id}"));
109 }
110 if let Some(name) = names
111 .iter()
112 .find(|name| !reserved.insert(name.to_lowercase()))
113 {
114 return Err(format!(
115 "product theme {id}: theme name is already in use: {name}"
116 ));
117 }
118 }
119 Ok(())
120}
121
122fn variant_names(id: &str, product: ProductThemes) -> Result<Vec<String>, String> {
123 let set: ThemeSet = serde_json::from_str(bundled_theme(id, product)?)
124 .map_err(|error| format!("product theme {id}: {error}"))?;
125 if set.themes.is_empty() {
126 return Err(format!("product theme has no variants: {id}"));
127 }
128 Ok(set
129 .themes
130 .into_iter()
131 .map(|theme| theme.name.to_string())
132 .collect())
133}
134
135pub(crate) fn bundled_theme_id(name: &str, product: ProductThemes) -> &'static str {
139 catalogue(product)
140 .find(|(_, content)| contains_theme(content, name))
141 .map_or(CUSTOM_THEME_ID, |(id, _)| id)
142}
143
144fn contains_theme(content: &str, name: &str) -> bool {
145 serde_json::from_str::<Value>(content)
146 .ok()
147 .and_then(|value| value.get("themes").and_then(Value::as_array).cloned())
148 .is_some_and(|themes| {
149 themes
150 .iter()
151 .any(|theme| theme.get("name").and_then(Value::as_str) == Some(name))
152 })
153}
154
155pub(crate) fn validate_product_themes(
158 product: &ValidatedProduct,
159 documents: ProductThemes,
160) -> Result<(), String> {
161 validate_product_theme_documents(documents)?;
162 require_catalogue_variant(product, "default theme", &product.default_theme, documents)
163}
164
165pub(crate) fn require_catalogue_variant(
168 product: &ValidatedProduct,
169 role: &str,
170 name: &str,
171 documents: ProductThemes,
172) -> Result<(), String> {
173 let names = product
174 .themes
175 .iter()
176 .map(|id| variant_names(id.as_str(), documents))
177 .collect::<Result<Vec<_>, _>>()?
178 .concat();
179 require_variant(&names, role, name)
180}
181
182fn require_variant(names: &[String], role: &str, name: &str) -> Result<(), String> {
183 if names.iter().any(|candidate| candidate == name) {
184 Ok(())
185 } else {
186 Err(format!(
187 "product {role} is not in its theme catalogue: {name}"
188 ))
189 }
190}
191
192pub(super) fn default_theme(cx: &App) -> String {
193 cx.global::<CurrentProduct>()
194 .0
195 .product
196 .default_theme
197 .clone()
198}
199
200pub(crate) fn validate_custom_theme(content: &str, product: ProductThemes) -> Result<(), String> {
201 let documents = theme_documents(content)?;
202 let reserved = reserved_theme_names(product)?;
203 for name in documents.keys() {
204 if reserved.contains(&name.to_lowercase()) {
205 return Err(format!("reserved theme name: {name}"));
206 }
207 }
208 Ok(())
209}
210
211fn reserved_theme_names(product: ProductThemes) -> Result<BTreeSet<String>, String> {
212 catalogue(product)
213 .map(|(_, content)| content)
214 .map(|content| serde_json::from_str::<ThemeSet>(content).map_err(|error| error.to_string()))
215 .collect::<Result<Vec<_>, _>>()
216 .map(|sets| {
217 sets.into_iter()
218 .flat_map(|set| {
219 set.themes
220 .into_iter()
221 .map(|theme| theme.name.to_lowercase())
222 })
223 .chain(KIT_PRELOADED_THEMES.map(str::to_lowercase))
224 .collect()
225 })
226}
227
228fn theme_documents(content: &str) -> Result<BTreeMap<String, ThemeDocument>, String> {
229 let document = ThemeDocument::parse(content)?;
230 let names = document.names();
231 validate_catalog_names(&names, &[])?;
232 names
233 .into_iter()
234 .map(|name| {
235 let variant = document.variant(&name)?;
236 variant.config()?;
237 variant.metadata()?;
238 Ok((name, variant))
239 })
240 .collect()
241}
242
243fn validate_catalog_names(names: &[String], existing: &[String]) -> Result<(), String> {
244 if names.is_empty() {
245 return Err("theme document has no variants".to_owned());
246 }
247 let mut occupied: BTreeSet<_> = existing.iter().map(|name| name.to_lowercase()).collect();
248 for name in names {
249 if name.trim().is_empty() {
250 return Err("theme name must not be blank".to_owned());
251 }
252 if !occupied.insert(name.to_lowercase()) {
253 return Err(format!("duplicate theme name: {name}"));
254 }
255 }
256 Ok(())
257}
258
259fn file_warning(path: &Path, error: &dyn std::fmt::Display) -> String {
260 format!("{}: {error}", path.display())
261}
262
263pub(super) fn load_registered_themes(cx: &mut App) -> Vec<String> {
264 let mut warnings = Vec::new();
265 let selected = cx.global::<CurrentProduct>().0.product.themes.clone();
266 cx.set_global(ThemeChoices {
267 documents: BTreeMap::new(),
268 });
269 for id in selected {
270 match bundled_theme(id.as_str(), product_themes(cx)) {
271 Ok(content) => load_theme(content, id.as_str(), &mut warnings, cx),
272 Err(error) => warnings.push(error),
273 }
274 }
275 if let Some(directory) = crate::product::gui_config_file(cx).parent() {
276 load_custom_themes(&directory.join("themes"), &mut warnings, cx);
277 }
278 warnings
279}
280
281fn custom_theme_files(directory: &Path) -> Result<Vec<std::path::PathBuf>, std::io::Error> {
282 let entries = match fs::read_dir(directory) {
283 Ok(entries) => entries,
284 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
285 Err(error) => return Err(error),
286 };
287 let mut files = Vec::new();
288 for entry in entries {
289 let path = entry?.path();
290 if path.extension().and_then(|extension| extension.to_str()) == Some("json") {
291 files.push(path);
292 }
293 }
294 files.sort();
295 Ok(files)
296}
297
298fn load_custom_themes(directory: &Path, warnings: &mut Vec<String>, cx: &mut App) {
299 let files = match custom_theme_files(directory) {
300 Ok(files) => files,
301 Err(error) => {
302 warnings.push(file_warning(directory, &error));
303 return;
304 }
305 };
306 let product = product_themes(cx);
307 for path in files {
308 match super::storage::read_theme(&path).and_then(|content| {
309 validate_custom_theme(&content, product)?;
310 Ok(content)
311 }) {
312 Ok(content) => load_theme(&content, &path.display().to_string(), warnings, cx),
313 Err(error) => warnings.push(file_warning(&path, &error)),
314 }
315 }
316}
317
318fn load_theme(content: &str, label: &str, warnings: &mut Vec<String>, cx: &mut App) {
319 let result = theme_documents(content).and_then(|documents| {
320 let existing = cx
321 .global::<ThemeChoices>()
322 .documents
323 .keys()
324 .cloned()
325 .collect::<Vec<_>>();
326 let names = documents.keys().cloned().collect::<Vec<_>>();
327 validate_catalog_names(&names, &existing)?;
328 ThemeRegistry::global_mut(cx)
329 .load_themes_from_str(content)
330 .map_err(|error| error.to_string())?;
331 Ok(documents)
332 });
333 match result {
334 Ok(documents) => cx.global_mut::<ThemeChoices>().documents.extend(documents),
335 Err(error) => warnings.push(format!("{label}: {error}")),
336 }
337}
338
339#[cfg(test)]
340mod tests {
341 use super::super::THEME_JSON;
342 use gpui_kit::TestAppContext;
343 use gpui_kit::component::ThemeRegistry;
344
345 use super::{
346 CUSTOM_THEME_ID, GPUI_KIT_THEMES, KIT_PRELOADED_THEMES, ProductThemes, bundled_theme,
347 custom_theme_files, file_warning, reserved_theme_names, theme_documents,
348 validate_catalog_names, validate_custom_theme, validate_product_theme_documents,
349 validate_product_themes, variant_names,
350 };
351 use crate::theme::THEME_NAME;
352
353 #[test]
354 fn known_products_default_to_cupertino_dark_from_their_embedded_documents() {
355 for product in subspace_product::fixture::products().unwrap() {
356 validate_product_themes(&product, &[]).unwrap();
357 assert_eq!(product.default_theme, "Cupertino Dark");
358 }
359 assert!(bundled_theme("unknown", &[]).is_err());
360 assert!(variant_names("unknown", &[]).is_err());
361 assert_eq!(
362 variant_names("cupertino", &[]).unwrap(),
363 ["Cupertino Light", "Cupertino Dark"]
364 );
365 assert!(bundled_theme("shell", &[]).is_err());
366 assert!(bundled_theme("subspace-shell-dark", &[]).is_err());
367 }
368
369 #[test]
370 fn a_default_variant_outside_the_declared_documents_fails_validation() {
371 let mut product = subspace_product::fixture::products().unwrap().remove(0);
372 product.themes.retain(|id| id.as_str() == "one-dark");
373 let error = validate_product_themes(&product, &[]).unwrap_err();
374 assert!(error.contains("Cupertino Dark"), "{error}");
375 product.default_theme = THEME_NAME.into();
376 assert!(validate_product_themes(&product, &[]).is_ok());
377 }
378
379 fn example_dark() -> String {
380 THEME_JSON.replace(THEME_NAME, "Example Dark")
381 }
382
383 #[test]
384 fn a_product_document_can_be_declared_and_be_the_default() {
385 let json: &'static str = Box::leak(example_dark().into_boxed_str());
386 let documents: ProductThemes = Box::leak(Box::new([("example-dark", json)]));
387 let mut product = subspace_product::fixture::products().unwrap().remove(0);
388 assert!(validate_product_themes(&product, documents).is_ok());
389 let id = subspace_product::parse_identity("example-dark").unwrap();
390 product.themes.push(id);
391 product.default_theme = "Example Dark".into();
392 assert!(validate_product_themes(&product, documents).is_ok());
393 assert_eq!(
394 variant_names("example-dark", documents).unwrap(),
395 ["Example Dark"]
396 );
397 assert_eq!(bundled_theme("example-dark", documents).unwrap(), json);
398 assert!(validate_product_themes(&product, &[]).is_err());
399 let reserved = reserved_theme_names(documents).unwrap();
400 assert!(reserved.contains("example dark"));
401 }
402
403 #[test]
404 fn a_product_document_with_invalid_json_or_a_reused_id_is_rejected() {
405 let broken: ProductThemes = &[("example-dark", "{malformed")];
406 let error = validate_product_theme_documents(broken).unwrap_err();
407 assert!(error.contains("example-dark"), "{error}");
408 let reused: ProductThemes = &[("one-dark", THEME_JSON)];
409 let error = validate_product_theme_documents(reused).unwrap_err();
410 assert!(error.contains("already in use"), "{error}");
411 let json: &'static str = Box::leak(example_dark().into_boxed_str());
412 let twice: ProductThemes = Box::leak(Box::new([("a", json), ("a", json)]));
413 assert!(validate_product_theme_documents(twice).is_err());
414 }
415
416 #[test]
417 fn a_product_variant_repeating_another_documents_variant_is_rejected() {
418 let framework = THEME_JSON.replace(THEME_NAME, "cupertino DARK");
419 let framework: &'static str = Box::leak(framework.into_boxed_str());
420 let documents: ProductThemes = Box::leak(Box::new([("example-dark", framework)]));
421 let error = validate_product_theme_documents(documents).unwrap_err();
422 assert!(error.contains("example-dark"), "{error}");
423 assert!(error.contains("cupertino DARK"), "{error}");
424 let json: &'static str = Box::leak(example_dark().into_boxed_str());
425 let again = THEME_JSON.replace(THEME_NAME, "EXAMPLE dark");
426 let again: &'static str = Box::leak(again.into_boxed_str());
427 let documents: ProductThemes =
428 Box::leak(Box::new([("example-dark", json), ("example-more", again)]));
429 let error = validate_product_theme_documents(documents).unwrap_err();
430 assert!(error.contains("example-more"), "{error}");
431 assert!(error.contains("EXAMPLE dark"), "{error}");
432 }
433
434 #[test]
435 fn an_unlisted_product_document_with_a_duplicate_field_is_rejected() {
436 let duplicate = example_dark().replace(
437 "\"name\": \"Example Dark\",",
438 "\"name\": \"Example Dark\", \"name\": \"Example Dark\",",
439 );
440 let duplicate: &'static str = Box::leak(duplicate.into_boxed_str());
441 let documents: ProductThemes = Box::leak(Box::new([("example-dark", duplicate)]));
442 let error = validate_product_theme_documents(documents).unwrap_err();
443 assert!(error.contains("example-dark"), "{error}");
444 assert!(error.contains("duplicate field"), "{error}");
445 assert!(reserved_theme_names(documents).is_err());
447 }
448
449 #[test]
450 fn a_product_variant_named_like_a_gpui_kit_default_is_rejected() {
451 for name in KIT_PRELOADED_THEMES {
452 let json = THEME_JSON.replace(THEME_NAME, &name.to_uppercase());
453 let json: &'static str = Box::leak(json.into_boxed_str());
454 let documents: ProductThemes = Box::leak(Box::new([("example-dark", json)]));
455 let error = validate_product_theme_documents(documents).unwrap_err();
456 assert!(error.contains("already in use"), "{name}: {error}");
457 let custom = THEME_JSON.replace(THEME_NAME, name);
458 let error = validate_custom_theme(&custom, &[]).unwrap_err();
459 assert!(error.contains("reserved theme name"), "{name}: {error}");
460 }
461 }
462
463 #[gpui_kit::test]
466 fn the_reserved_kit_defaults_are_the_themes_gpui_kit_preloads(cx: &mut TestAppContext) {
467 cx.update(|cx| {
468 gpui_kit::init(cx);
469 let mut preloaded = ThemeRegistry::global(cx)
470 .themes()
471 .keys()
472 .map(ToString::to_string)
473 .collect::<Vec<_>>();
474 preloaded.sort();
475 assert_eq!(preloaded, KIT_PRELOADED_THEMES);
476 });
477 }
478
479 #[test]
480 fn a_product_document_cannot_use_the_custom_theme_id() {
481 let json: &'static str = Box::leak(example_dark().into_boxed_str());
482 let documents: ProductThemes = Box::leak(Box::new([(CUSTOM_THEME_ID, json)]));
483 let error = validate_product_theme_documents(documents).unwrap_err();
484 assert!(error.contains("reserved"), "{error}");
485 assert!(error.contains(CUSTOM_THEME_ID), "{error}");
486 }
487
488 #[test]
489 fn all_bundled_variant_names_are_reserved_case_insensitively() {
490 for content in [THEME_JSON]
491 .into_iter()
492 .chain(GPUI_KIT_THEMES.iter().map(|(_, content)| *content))
493 {
494 let value: serde_json::Value = serde_json::from_str(content).unwrap();
495 for variant in value["themes"].as_array().unwrap() {
496 let name = variant["name"].as_str().unwrap().to_uppercase();
497 let custom = THEME_JSON.replace(THEME_NAME, &name);
498 let error = validate_custom_theme(&custom, &[]).unwrap_err();
499 assert!(error.contains("reserved theme name"), "{name}: {error}");
500 }
501 }
502 }
503
504 #[test]
505 fn catalog_rejects_entire_batch_when_any_name_collides() {
506 let existing = vec!["My Theme".to_owned()];
507 let names = vec!["New Theme".to_owned(), "my theme".to_owned()];
508 assert!(validate_catalog_names(&names, &existing).is_err());
509 assert_eq!(existing, ["My Theme"]);
510 assert!(validate_catalog_names(&["Unique".to_owned()], &existing).is_ok());
511 assert!(validate_catalog_names(&["Same".to_owned(), "same".to_owned()], &[]).is_err());
512 assert!(validate_catalog_names(&[" ".to_owned()], &[]).is_err());
513 assert!(validate_catalog_names(&[], &[]).is_err());
514 }
515
516 #[test]
517 fn catalog_keeps_each_original_variant_document() {
518 let documents = theme_documents(
519 GPUI_KIT_THEMES
520 .iter()
521 .find(|(name, _)| *name == "solarized")
522 .unwrap()
523 .1,
524 )
525 .unwrap();
526 assert_eq!(documents.len(), 2);
527 for (name, document) in documents {
528 assert_eq!(document.names(), vec![name]);
529 assert!(document.config().is_ok());
530 assert!(document.metadata().is_ok());
531 }
532 }
533
534 #[test]
535 fn custom_documents_reject_duplicate_and_blank_names() {
536 let mut value: serde_json::Value = serde_json::from_str(THEME_JSON).unwrap();
537 value["themes"][0]["name"] = "Custom".into();
538 assert!(validate_custom_theme(&value.to_string(), &[]).is_ok());
539 let duplicate = value["themes"][0].clone();
540 value["themes"].as_array_mut().unwrap().push(duplicate);
541 assert!(validate_custom_theme(&value.to_string(), &[]).is_err());
542 value["themes"].as_array_mut().unwrap().pop();
543 value["themes"][0]["name"] = " ".into();
544 assert!(validate_custom_theme(&value.to_string(), &[]).is_err());
545 assert!(validate_custom_theme("{malformed", &[]).is_err());
546 }
547
548 #[test]
549 fn custom_files_are_sorted_and_missing_directories_are_optional() {
550 let dir = tempfile::tempdir().unwrap();
551 assert!(
552 custom_theme_files(&dir.path().join("missing"))
553 .unwrap()
554 .is_empty()
555 );
556 for name in ["b.json", "a.json", "ignored.txt"] {
557 std::fs::write(dir.path().join(name), "{}").unwrap();
558 }
559 assert_eq!(
560 custom_theme_files(dir.path()).unwrap(),
561 [dir.path().join("a.json"), dir.path().join("b.json")]
562 );
563 assert!(custom_theme_files(&dir.path().join("a.json")).is_err());
564 assert_eq!(
565 file_warning(&dir.path().join("a.json"), &"invalid"),
566 format!("{}: invalid", dir.path().join("a.json").display())
567 );
568 }
569}