1use std::path::PathBuf;
4
5use gpui_kit::{App, Global};
6use serde_json::Value;
7use subspace_core::former_ids::Renames;
8use subspace_dashboard::CurrentProduct;
9use subspace_product::{
10 OsKind, PlatformEnv, ProductContext, ProductDescriptor, product_data_name, validate_product,
11};
12
13pub(crate) struct ProductFiles {
14 pub config: PathBuf,
15 pub state: PathBuf,
16}
17
18impl Global for ProductFiles {}
19
20pub(crate) struct DesktopName(String);
22
23impl Global for DesktopName {}
24
25impl DesktopName {
26 pub(crate) fn new(name: &str, prefix: Option<&str>) -> Self {
27 Self(
28 prefix
29 .filter(|prefix| !prefix.is_empty())
30 .map_or_else(|| name.to_owned(), |prefix| format!("{prefix} {name}")),
31 )
32 }
33
34 pub(crate) fn as_str(&self) -> &str {
35 &self.0
36 }
37}
38
39pub(crate) fn desktop_name(cx: &App) -> &str {
40 if let Some(name) = cx.try_global::<DesktopName>() {
41 return name.as_str();
42 }
43 cx.try_global::<CurrentProduct>()
44 .map_or("Subspace", |context| &context.0.product.display_name)
45}
46
47pub(crate) fn install_context(
49 context: std::sync::Arc<ProductContext>,
50 prefix: Option<&str>,
51 cx: &mut App,
52) {
53 let name = DesktopName::new(&context.product.display_name, prefix);
54 cx.set_app_identity(&context.product.bundle_id, name.as_str());
55 cx.set_global(name);
56 let diagnostics = crate::diagnostics::local_copy(&context);
57 cx.set_global(subspace_dashboard::copy_details::CopyDiagnostics::new(
58 diagnostics,
59 ));
60 cx.set_global(CurrentProduct(context));
61}
62
63impl ProductFiles {
64 pub(crate) fn for_context(context: &ProductContext) -> Self {
65 Self {
66 config: config_file(context),
67 state: preference_file(context),
68 }
69 }
70}
71
72pub fn config_file(context: &ProductContext) -> PathBuf {
75 let roots = context.product_roots();
76 roots
77 .product_roots()
78 .into_iter()
79 .map(|root| root.join("config.json"))
80 .find(|file| file.exists())
81 .unwrap_or_else(|| {
82 roots
83 .native
84 .unwrap_or(roots.cross_platform)
85 .join("config.json")
86 })
87}
88
89fn preference_file(context: &ProductContext) -> PathBuf {
90 state_directory(&context.env).join("state.json")
91}
92
93pub(crate) fn state_directory(env: &PlatformEnv) -> PathBuf {
96 let base = match env.os {
97 OsKind::Linux => env
98 .xdg_state_home
99 .clone()
100 .unwrap_or_else(|| env.home.join(".local/state")),
101 OsKind::Macos => env.home.join("Library/Application Support"),
102 OsKind::Windows => env
103 .local_app_data
104 .clone()
105 .unwrap_or_else(|| env.home.join("AppData/Local")),
106 };
107 base.join(product_data_name())
108}
109
110pub fn prepare_context(
116 mut descriptor: ProductDescriptor,
117 version: &str,
118) -> Result<ProductContext, String> {
119 let product = validate_product(&descriptor).map_err(|error| error.to_string())?;
120 crate::startup::name_data_directory(product.binary_name.as_str())?;
121 let env = PlatformEnv::from_process().map_err(|error| error.to_string())?;
122 let mut context = context_with_env(&mut descriptor, env)?;
123 context.version = version.to_owned();
124 Ok(context)
125}
126
127fn context_with_env(
128 descriptor: &mut ProductDescriptor,
129 env: PlatformEnv,
130) -> Result<ProductContext, String> {
131 let validated = validate_product(descriptor).map_err(|error| error.to_string())?;
132 let renames = subspace_core::former_ids::declared(&validated);
133 let context = ProductContext::new(validated, env);
134 let file = config_file(&context);
135 if let Some(value) = load_alias_file(&file, &renames)? {
136 apply_aliases(descriptor, &value)?;
137 }
138 let product = validate_product(descriptor).map_err(|error| error.to_string())?;
139 Ok(ProductContext::new(product, context.env))
140}
141
142fn load_alias_file(file: &std::path::Path, renames: &Renames) -> Result<Option<Value>, String> {
145 let text = match std::fs::read_to_string(file) {
146 Ok(text) => text,
147 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
148 Err(error) => {
149 return Err(format!(
150 "cannot read product configuration {}: {error}",
151 file.display()
152 ));
153 }
154 };
155 let mut value: Value = serde_json::from_str(&text)
156 .map_err(|_| format!("invalid product configuration JSON: {}", file.display()))?;
157 if let Some(root) = value.as_object_mut() {
158 subspace_core::former_ids::rename_config(root, renames);
159 }
160 Ok(Some(value))
161}
162
163fn apply_aliases(descriptor: &mut ProductDescriptor, value: &Value) -> Result<(), String> {
164 let Some(aliases) = value.pointer("/commands/aliases") else {
165 return Ok(());
166 };
167 let aliases = aliases
168 .as_object()
169 .ok_or("commands.aliases must be an object")?;
170 for (id, value) in aliases {
171 let board = descriptor
172 .boards
173 .iter_mut()
174 .find(|board| &board.id == id)
175 .ok_or_else(|| format!("commands.aliases names an excluded board: {id}"))?;
176 let values = value
177 .as_array()
178 .ok_or_else(|| format!("commands.aliases.{id} must be an array"))?;
179 for value in values {
180 let alias = value
181 .as_str()
182 .ok_or_else(|| format!("commands.aliases.{id} must contain strings"))?;
183 board.aliases.push(alias.to_owned());
184 }
185 }
186 Ok(())
187}
188
189pub(crate) fn gui_config_file(cx: &App) -> PathBuf {
190 cx.global::<ProductFiles>().config.clone()
191}
192
193#[cfg(test)]
194mod tests {
195 use super::{
196 DesktopName, ProductFiles, apply_aliases, config_file, context_with_env, load_alias_file,
197 preference_file,
198 };
199 use subspace_core::former_ids::Renames;
200 use subspace_product::{OsKind, PlatformEnv, ProductContext, fixture, validate_product};
201
202 #[test]
203 fn desktop_name_can_be_prefixed_without_changing_the_bundle_name() {
204 let name = "Subspace";
205 assert_eq!(
206 DesktopName::new(name, Some("Example")).as_str(),
207 "Example Subspace"
208 );
209 assert_eq!(DesktopName::new(name, Some("")).as_str(), name);
210 assert_eq!(DesktopName::new(name, None).as_str(), name);
211 }
212
213 #[test]
214 fn product_aliases_validate_collisions_and_excluded_boards() {
215 let mut descriptor = fixture::descriptor();
216 apply_aliases(
217 &mut descriptor,
218 &serde_json::json!({"commands":{"aliases":{"github":["gh"]}}}),
219 )
220 .unwrap();
221 assert!(
222 validate_product(&descriptor)
223 .unwrap()
224 .board_for_command("gh")
225 .is_some()
226 );
227 apply_aliases(
228 &mut descriptor,
229 &serde_json::json!({"commands":{"aliases":{"github":["github"]}}}),
230 )
231 .unwrap();
232 assert!(validate_product(&descriptor).is_err());
233 assert!(
234 apply_aliases(
235 &mut descriptor,
236 &serde_json::json!({"commands":{"aliases":{"missing":["m"]}}})
237 )
238 .unwrap_err()
239 .contains("excluded board")
240 );
241 }
242
243 fn context_with_config(config: &str) -> Result<ProductContext, String> {
246 let root = tempfile::tempdir().unwrap();
247 let env = PlatformEnv {
248 os: OsKind::Linux,
249 home: root.path().to_owned(),
250 xdg_config_home: Some(root.path().join("config")),
251 xdg_state_home: Some(root.path().join("state")),
252 app_data: None,
253 local_app_data: None,
254 };
255 let mut descriptor = fixture::descriptor();
256 descriptor.boards[0].former_ids = vec!["example-old".into()];
257 let product = validate_product(&descriptor).unwrap();
258 let file = config_file(&ProductContext::new(product, env.clone()));
259 std::fs::create_dir_all(file.parent().unwrap()).unwrap();
260 std::fs::write(&file, config).unwrap();
261 context_with_env(&mut descriptor, env)
262 }
263
264 #[test]
265 fn shortcuts_saved_under_a_former_space_id_reach_the_space() {
266 let context =
267 context_with_config(r#"{"commands":{"aliases":{"example-old":["example-short"]}}}"#)
268 .unwrap();
269 let board = context.product.board_for_command("example-short").unwrap();
270 assert_eq!(board.id.as_str(), "github");
271 }
272
273 #[test]
274 fn the_space_s_own_shortcuts_win_over_its_former_id_s() {
275 let context = context_with_config(
276 r#"{"commands":{"aliases":{"example-old":["example-short","example-gone"],
277 "github":["example-short"]}}}"#,
278 )
279 .unwrap();
280 let board = context.product.board_for_command("example-short").unwrap();
281 assert_eq!(board.id.as_str(), "github");
282 assert!(context.product.board_for_command("example-gone").is_none());
283 assert!(context.product.board_for_command("example-old").is_none());
284 }
285
286 #[test]
287 fn another_entry_s_shortcut_is_no_key_for_shortcuts() {
288 let error = context_with_config(
289 r#"{"commands":{"aliases":{"github":["zz-short"],"zz-short":["zz-other"]}}}"#,
290 )
291 .unwrap_err();
292 assert!(error.contains("excluded board: zz-short"), "{error}");
293 }
294
295 #[test]
296 fn gui_files_are_product_specific() {
297 let root = tempfile::tempdir().unwrap();
298 let known = fixture::products().unwrap();
299 let env = PlatformEnv {
300 os: OsKind::Macos,
301 home: root.path().to_owned(),
302 xdg_config_home: None,
303 xdg_state_home: None,
304 app_data: None,
305 local_app_data: None,
306 };
307 let context = ProductContext::new(known[0].clone(), env.clone());
308 let files = ProductFiles::for_context(&context);
309 assert_eq!(files.state, preference_file(&context));
310 assert_eq!(files.config, config_file(&context));
311 let name = subspace_product::product_data_name();
312 assert!(
313 preference_file(&context).ends_with(format!("Application Support/{name}/state.json"))
314 );
315 assert!(config_file(&context).ends_with(format!("Application Support/{name}/config.json")));
316 assert!(!root.path().join("Library").exists());
317 let mut descriptor = fixture::descriptor();
318 let reloaded = context_with_env(&mut descriptor, env).unwrap();
319 assert_eq!(reloaded.product.id.as_str(), "subspace");
320 assert!(!root.path().join("Library").exists());
321 }
322
323 #[test]
324 fn alias_loader_does_not_repeat_configuration_contents() {
325 let root = tempfile::tempdir().unwrap();
326 let file = root.path().join("config.json");
327 assert_eq!(load_alias_file(&file, &Renames::new()).unwrap(), None);
328 std::fs::write(&file, "a-secret-that-is-not-json").unwrap();
329 let error = load_alias_file(&file, &Renames::new()).unwrap_err();
330 assert!(error.contains("invalid product configuration JSON"));
331 assert!(!error.contains("a-secret"));
332 std::fs::write(&file, "{}").unwrap();
333 assert_eq!(
334 load_alias_file(&file, &Renames::new()).unwrap(),
335 Some(serde_json::json!({}))
336 );
337 }
338}