1use std::collections::{BTreeMap, HashMap};
12use std::fs;
13use std::io::Read;
14use std::path::{Path, PathBuf};
15
16use crate::model_resolution::KiCadModelSearchContext;
17
18const MAX_CONFIG_BYTES: usize = 4 * 1024 * 1024;
19const MAX_DISCOVERY_ENTRIES: usize = 20_000;
20
21#[must_use]
26pub fn discover_model_search_context(
27 project_root: Option<&Path>,
28) -> (KiCadModelSearchContext, Vec<String>) {
29 let environment: HashMap<String, String> = std::env::vars_os()
30 .filter_map(|(key, value)| Some((key.into_string().ok()?, value.into_string().ok()?)))
31 .collect();
32 let platform_roots = default_platform_install_roots();
33 discover_model_search_context_from_env(project_root, &environment, &platform_roots)
34}
35
36#[must_use]
38pub fn discover_model_search_context_from_env(
39 _project_root: Option<&Path>,
40 environment: &HashMap<String, String>,
41 platform_install_roots: &[PathBuf],
42) -> (KiCadModelSearchContext, Vec<String>) {
43 let mut context = KiCadModelSearchContext {
44 resolve_wrl_siblings: true,
45 ..KiCadModelSearchContext::default()
46 };
47 let mut notes = Vec::new();
48 let installations = discover_installations(environment, platform_install_roots, &mut notes);
49 append_installation_defaults(&installations, platform_install_roots, &mut context);
50 read_latest_config(environment, &mut context, &mut notes);
51 for (key, value) in environment {
53 #[cfg(windows)]
54 {
55 let upper = key.to_ascii_uppercase();
56 if upper != *key {
57 context.variables.insert(upper, value.clone());
58 }
59 }
60 context.variables.insert(key.clone(), value.clone());
61 }
62 (context, notes)
63}
64
65fn default_platform_install_roots() -> Vec<PathBuf> {
66 if cfg!(windows) {
67 vec![
68 PathBuf::from(r"C:\Program Files\KiCad"),
69 PathBuf::from(r"C:\Program Files (x86)\KiCad"),
70 ]
71 } else if cfg!(target_os = "macos") {
72 vec![
73 PathBuf::from("/Applications/KiCad"),
74 PathBuf::from("/Applications/KiCad/KiCad.app/Contents/SharedSupport"),
75 ]
76 } else {
77 vec![
78 PathBuf::from("/usr"),
79 PathBuf::from("/usr/local"),
80 PathBuf::from("/app"),
81 ]
82 }
83}
84
85fn discover_installations(
86 environment: &HashMap<String, String>,
87 platform_install_roots: &[PathBuf],
88 notes: &mut Vec<String>,
89) -> BTreeMap<(u32, u32), PathBuf> {
90 let mut installations = BTreeMap::new();
91 for key in [
92 "KICAD_EXE",
93 "KICAD_CLI",
94 "KICAD_INSTALL_ROOT",
95 "KICAD_HOME",
96 "KICAD_PATH",
97 ] {
98 if let Some(value) = env_value(environment, key) {
99 add_installation(Path::new(value), &mut installations);
100 }
101 }
102 let mut bases = Vec::new();
103 if let Some(value) = env_value(environment, "LOCALAPPDATA") {
104 bases.push(Path::new(value).join("Programs/KiCad"));
105 }
106 for key in ["PROGRAMFILES", "PROGRAMFILES(X86)"] {
107 if let Some(value) = env_value(environment, key) {
108 bases.push(Path::new(value).join("KiCad"));
109 }
110 }
111 bases.extend_from_slice(platform_install_roots);
112 for base in bases {
113 add_installation(&base, &mut installations);
114 for child in child_directories(&base, notes) {
115 add_installation(&child, &mut installations);
116 }
117 }
118 installations
119}
120
121fn model_dir_for_install(installation: &Path) -> Option<PathBuf> {
122 let standard = installation.join("share/kicad/3dmodels");
123 if standard.is_dir() {
124 return Some(standard);
125 }
126 let flat = installation.join("3dmodels");
127 if flat.is_dir() {
128 return Some(flat);
129 }
130 None
131}
132
133fn append_installation_defaults(
134 installations: &BTreeMap<(u32, u32), PathBuf>,
135 platform_install_roots: &[PathBuf],
136 context: &mut KiCadModelSearchContext,
137) {
138 for ((major, _minor), installation) in installations {
139 if let Some(model_directory) = model_dir_for_install(installation) {
140 context.variables.insert(
141 format!("KICAD{major}_3DMODEL_DIR"),
142 model_directory.to_string_lossy().into_owned(),
143 );
144 }
145 }
146 let fallback = installations
147 .iter()
148 .rev()
149 .filter(|((_, minor), _)| *minor != 99)
150 .find_map(|(_, installation)| model_dir_for_install(installation))
151 .or_else(|| {
152 installations
153 .iter()
154 .rev()
155 .filter(|((_, minor), _)| *minor == 99)
156 .find_map(|(_, installation)| model_dir_for_install(installation))
157 });
158 if let Some(dir) = fallback {
159 context.fallback_model_dir = Some(dir);
160 } else if !cfg!(windows) && !platform_install_roots.is_empty() {
161 for base in platform_install_roots {
162 if let Some(dir) = model_dir_for_install(base) {
163 context.fallback_model_dir = Some(dir);
164 break;
165 }
166 }
167 }
168}
169
170fn config_base_from_env(environment: &HashMap<String, String>) -> Option<PathBuf> {
171 if let Some(explicit) = env_value(environment, "KICAD_CONFIG_HOME") {
172 return Some(PathBuf::from(explicit));
173 }
174 if cfg!(windows) {
175 env_value(environment, "APPDATA").map(|value| Path::new(value).join("kicad"))
176 } else if cfg!(target_os = "macos") {
177 env_value(environment, "HOME")
178 .map(|value| Path::new(value).join("Library/Preferences/kicad"))
179 } else if let Some(xdg) = env_value(environment, "XDG_CONFIG_HOME") {
180 Some(Path::new(xdg).join("kicad"))
181 } else {
182 env_value(environment, "HOME").map(|value| Path::new(value).join(".config/kicad"))
183 }
184}
185
186fn read_latest_config(
187 environment: &HashMap<String, String>,
188 context: &mut KiCadModelSearchContext,
189 notes: &mut Vec<String>,
190) {
191 let Some(base) = config_base_from_env(environment) else {
192 return;
193 };
194 let mut versions = child_directories(&base, notes)
195 .into_iter()
196 .filter_map(|path| Some((version(&path)?, path)))
197 .collect::<Vec<_>>();
198 versions.sort_by_key(|(ver, _)| *ver);
199 let selected = versions
200 .iter()
201 .rev()
202 .find(|((_, minor), _)| *minor != 99)
203 .or_else(|| versions.last());
204 if let Some((_, directory)) = selected {
205 read_config(&directory.join("kicad_common.json"), context, notes);
206 }
207}
208
209fn env_value<'a>(environment: &'a HashMap<String, String>, key: &str) -> Option<&'a str> {
210 environment
211 .get(key)
212 .or_else(|| {
213 environment
214 .iter()
215 .find(|(name, _)| name.eq_ignore_ascii_case(key))
216 .map(|(_, value)| value)
217 })
218 .map(String::as_str)
219 .filter(|value| !value.is_empty())
220}
221
222fn version(path: &Path) -> Option<(u32, u32)> {
223 let (major, minor) = path.file_name()?.to_str()?.split_once('.')?;
224 if !major.bytes().all(|value| value.is_ascii_digit())
225 || !minor.bytes().all(|value| value.is_ascii_digit())
226 {
227 return None;
228 }
229 Some((major.parse().ok()?, minor.parse().ok()?))
230}
231
232fn add_installation(candidate: &Path, installations: &mut BTreeMap<(u32, u32), PathBuf>) {
233 let root = if candidate.is_file() {
234 let Some(name) = candidate.file_name().and_then(|value| value.to_str()) else {
235 return;
236 };
237 if !["kicad", "kicad.exe", "kicad-cli", "kicad-cli.exe"]
238 .iter()
239 .any(|value| name.eq_ignore_ascii_case(value))
240 {
241 return;
242 }
243 let Some(root) = candidate.parent().and_then(Path::parent) else {
244 return;
245 };
246 root.to_owned()
247 } else if candidate
248 .file_name()
249 .and_then(|name| name.to_str())
250 .is_some_and(|name| name.eq_ignore_ascii_case("bin"))
251 {
252 let Some(root) = candidate.parent() else {
253 return;
254 };
255 root.to_owned()
256 } else {
257 candidate.to_owned()
258 };
259 if !["kicad", "kicad.exe", "kicad-cli", "kicad-cli.exe"]
260 .iter()
261 .any(|name| root.join("bin").join(name).is_file())
262 {
263 return;
264 }
265 if let Some(ver) = version(&root) {
266 installations.entry(ver).or_insert(root);
267 }
268}
269
270fn child_directories(root: &Path, notes: &mut Vec<String>) -> Vec<PathBuf> {
271 if !root.is_dir() {
272 return Vec::new();
273 }
274 let Ok(entries) = fs::read_dir(root) else {
275 note(
276 notes,
277 "Optional KiCad installation/configuration directory could not be inspected.",
278 );
279 return Vec::new();
280 };
281 let mut result = Vec::new();
282 for (index, entry) in entries.enumerate() {
283 if index >= MAX_DISCOVERY_ENTRIES {
284 note(
285 notes,
286 "Optional KiCad installation/configuration discovery reached its entry limit.",
287 );
288 break;
289 }
290 match entry {
291 Ok(entry) if entry.path().is_dir() => result.push(entry.path()),
292 Ok(_) => {}
293 Err(_) => note(
294 notes,
295 "An optional KiCad installation/configuration entry could not be inspected.",
296 ),
297 }
298 }
299 result.sort();
300 result
301}
302
303fn read_bounded_utf8(path: &Path, limit: usize) -> Result<String, String> {
304 let file = fs::File::open(path).map_err(|e| e.to_string())?;
305 let mut buf = Vec::new();
306 file.take((limit + 1) as u64)
307 .read_to_end(&mut buf)
308 .map_err(|e| e.to_string())?;
309 if buf.len() > limit {
310 return Err("exceeded size limit".to_owned());
311 }
312 String::from_utf8(buf).map_err(|e| e.to_string())
313}
314
315fn read_config(path: &Path, context: &mut KiCadModelSearchContext, notes: &mut Vec<String>) {
316 if !path.is_file() {
317 return;
318 }
319 let Ok(source) = read_bounded_utf8(path, MAX_CONFIG_BYTES) else {
320 note(
321 notes,
322 "Optional KiCad model configuration could not be read within its input limit.",
323 );
324 return;
325 };
326 let Ok(value) = serde_json::from_str::<serde_json::Value>(&source) else {
327 note(
328 notes,
329 "Malformed optional KiCad model configuration was ignored.",
330 );
331 return;
332 };
333 if !value.is_object() {
334 return;
335 }
336 if let Some(rows) = value
337 .pointer("/environment/vars")
338 .and_then(serde_json::Value::as_object)
339 {
340 for (name, val) in rows {
341 if let Some(text) = val.as_str() {
342 context.variables.insert(name.clone(), text.to_owned());
343 }
344 }
345 }
346 if let Some(rows) = value
347 .pointer("/system/extra_3d_search_dirs")
348 .and_then(serde_json::Value::as_array)
349 {
350 for dir in rows {
351 if let Some(text) = dir.as_str().filter(|s| !s.is_empty()) {
352 let path = PathBuf::from(text);
353 if !context.search_dirs.contains(&path) {
354 context.search_dirs.push(path);
355 }
356 }
357 }
358 }
359}
360
361fn note(notes: &mut Vec<String>, value: &str) {
362 if !notes.iter().any(|existing| existing == value) {
363 notes.push(value.to_owned());
364 }
365}
366
367#[cfg(test)]
368mod tests {
369 use super::*;
370 use crate::model_resolution::KiCadModelResolver;
371
372 #[test]
373 fn host_discovery_reads_install_kicad_common_and_resolves_wrl_sibling() {
374 let root = std::env::temp_dir().join(format!("km-model-host-test-{}", std::process::id()));
375 let _ = fs::remove_dir_all(&root);
376 let install = root.join("KiCad/10.0");
377 fs::create_dir_all(install.join("bin")).unwrap();
378 fs::write(install.join("bin/kicad-cli.exe"), b"").unwrap();
379 let model_dir = install.join("share/kicad/3dmodels/Resistor_SMD.3dshapes");
380 fs::create_dir_all(&model_dir).unwrap();
381 let step_file = model_dir.join("R_0603.step");
382 fs::write(&step_file, b"ISO-10303-21;\nEND-ISO-10303-21;\n").unwrap();
383
384 let custom_dir = root.join("custom_3d");
385 fs::create_dir_all(&custom_dir).unwrap();
386 let custom_step = custom_dir.join("CustomIC.step");
387 fs::write(&custom_step, b"ISO-10303-21;\nEND-ISO-10303-21;\n").unwrap();
388
389 let cfg_dir = root.join("cfg/10.0");
390 fs::create_dir_all(&cfg_dir).unwrap();
391 let kicad_common = serde_json::json!({
392 "environment": { "vars": { "MY_3D_LIB": custom_dir.to_string_lossy() } },
393 "system": { "extra_3d_search_dirs": [custom_dir.to_string_lossy()] }
394 });
395 fs::write(
396 cfg_dir.join("kicad_common.json"),
397 serde_json::to_vec_pretty(&kicad_common).unwrap(),
398 )
399 .unwrap();
400
401 let mut env = HashMap::new();
402 env.insert(
403 "KICAD_CONFIG_HOME".to_owned(),
404 root.join("cfg").to_string_lossy().into_owned(),
405 );
406 env.insert(
407 "KICAD_INSTALL_ROOT".to_owned(),
408 install.to_string_lossy().into_owned(),
409 );
410
411 let (ctx, notes) = discover_model_search_context_from_env(Some(&root), &env, &[]);
412 assert!(notes.is_empty(), "{notes:?}");
413 assert!(ctx.resolve_wrl_siblings);
414 assert_eq!(
415 ctx.fallback_model_dir.as_deref(),
416 Some(install.join("share/kicad/3dmodels").as_path())
417 );
418
419 let resolver = KiCadModelResolver::from_context(&ctx).unwrap();
420 let r_hit = resolver
422 .resolve(
423 "${KICAD6_3DMODEL_DIR}/Resistor_SMD.3dshapes/R_0603.wrl",
424 Some(&root),
425 1024,
426 )
427 .unwrap();
428 assert_eq!(
429 r_hit.status,
430 crate::model_resolution::KiCadModelResolutionStatus::Resolved
431 );
432 assert_eq!(r_hit.resolved_name.as_deref(), Some("R_0603.step"));
433 assert!(r_hit.via_sibling);
434 assert!(r_hit.payload.is_some());
435
436 let c_hit = resolver
438 .resolve("${MY_3D_LIB}/CustomIC.step", Some(&root), 1024)
439 .unwrap();
440 assert_eq!(
441 c_hit.status,
442 crate::model_resolution::KiCadModelResolutionStatus::Resolved
443 );
444 assert_eq!(c_hit.resolved_name.as_deref(), Some("CustomIC.step"));
445 assert!(c_hit.payload.is_some());
446
447 let _ = fs::remove_dir_all(&root);
448 }
449}