1use std::{
5 collections::HashMap,
6 fs,
7 io::Read,
8 path::{Path, PathBuf},
9};
10use unicode_casefold::UnicodeCaseFold;
11
12#[derive(Clone, Debug)]
13pub struct KiCadModelSearchContext {
14 pub variables: HashMap<String, String>,
15 pub fallback_model_dir: Option<PathBuf>,
16 pub search_dirs: Vec<PathBuf>,
17 pub resolve_wrl_siblings: bool,
18 pub max_search_entries: usize,
19}
20
21impl Default for KiCadModelSearchContext {
22 fn default() -> Self {
23 Self {
24 variables: HashMap::new(),
25 fallback_model_dir: None,
26 search_dirs: vec![],
27 resolve_wrl_siblings: true,
28 max_search_entries: 20_000,
29 }
30 }
31}
32
33#[derive(Clone, Copy, Debug, Eq, PartialEq)]
34pub enum KiCadModelResolutionStatus {
35 Resolved,
36 Missing,
37 VariableUnresolved,
38}
39
40pub struct KiCadModelResolution {
41 pub authored_locator: String,
42 pub status: KiCadModelResolutionStatus,
43 pub resolved_name: Option<String>,
44 pub payload: Option<Vec<u8>>,
45 pub via_sibling: bool,
46 pub standard_library_reference: bool,
47}
48
49impl std::fmt::Debug for KiCadModelResolution {
50 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51 formatter
52 .debug_struct("KiCadModelResolution")
53 .field("authored_locator", &self.authored_locator)
54 .field("status", &self.status)
55 .field("resolved_name", &self.resolved_name)
56 .field("payload_bytes", &self.payload.as_ref().map(Vec::len))
57 .field("via_sibling", &self.via_sibling)
58 .field(
59 "standard_library_reference",
60 &self.standard_library_reference,
61 )
62 .finish()
63 }
64}
65
66#[derive(Clone, Debug)]
67pub struct KiCadModelResolver {
68 context: KiCadModelSearchContext,
69}
70
71impl KiCadModelResolver {
72 pub fn from_context(context: &KiCadModelSearchContext) -> Result<Self, String> {
73 if context.max_search_entries == 0 {
74 return Err("KiCad model search entry limit must be positive".into());
75 }
76 Ok(Self {
77 context: context.clone(),
78 })
79 }
80
81 pub fn context(&self) -> KiCadModelSearchContext {
82 self.context.clone()
83 }
84
85 #[allow(
86 clippy::cognitive_complexity,
87 reason = "3D model resolver evaluates KiCad env vars, project roots, and fallback search roots explicitly"
88 )]
89 pub fn resolve(
90 &self,
91 authored_locator: &str,
92 project_root: Option<&Path>,
93 max_bytes: usize,
94 ) -> Result<KiCadModelResolution, String> {
95 if max_bytes == 0 {
96 return Err("KiCad model byte limit must be positive".into());
97 }
98 let locator = authored_locator.trim();
99 let standard = standard_reference(locator);
100 let (primary, unresolved) =
101 expand_model_path(locator, project_root, &self.context.variables);
102 let mut candidates = Vec::new();
103 if let Some(primary) = primary {
104 candidates.push(primary);
105 }
106 if let Some(tail) = leading_variable_tail(locator) {
108 if standard && let Some(root) = &self.context.fallback_model_dir {
109 candidates.push(root.join(tail));
110 }
111 candidates.extend(self.context.search_dirs.iter().map(|root| root.join(tail)));
112 }
113 let mut non_step = None;
114 for candidate in &candidates {
115 if let Some(found) = existing_model_file(candidate, self.context.resolve_wrl_siblings) {
116 if is_step(&found.0) {
117 return self.read(locator, found, standard, max_bytes);
118 }
119 if non_step.is_none() {
120 non_step = Some(found);
121 }
122 }
123 }
124 if let Some(found) = non_step {
125 return self.read(locator, found, standard, max_bytes);
126 }
127 let normalized = locator.replace('\\', "/");
128 if !normalized.is_empty() && !normalized.contains('/') && !normalized.contains("${") {
129 let mut matches = HashMap::new();
130 let mut visited = 0;
131 let wanted: String = normalized.case_fold().collect();
132 for root in &self.context.search_dirs {
133 let mut single = root.is_file().then(|| root.clone());
134 let mut directories = if root.is_dir() {
135 vec![fs::read_dir(root).map_err(safe_io_error)?]
136 } else {
137 vec![]
138 };
139 loop {
140 let candidate = if let Some(single) = single.take() {
141 single
142 } else if let Some(entries) = directories.last_mut() {
143 match entries.next() {
144 Some(entry) => entry.map_err(safe_io_error)?.path(),
145 None => {
146 directories.pop();
147 continue;
148 }
149 }
150 } else {
151 break;
152 };
153 visited += 1;
154 if visited > self.context.max_search_entries {
155 return Err("KiCad model search exceeds entry limit".into());
156 }
157 if candidate.is_dir() && !candidate.is_symlink() {
159 directories.push(fs::read_dir(&candidate).map_err(safe_io_error)?);
160 }
161 if candidate.is_file()
162 && candidate.file_name().is_some_and(|name| {
163 name.to_string_lossy().case_fold().collect::<String>() == wanted
164 })
165 && let Some(found) =
166 existing_model_file(&candidate, self.context.resolve_wrl_siblings)
167 {
168 let identity = found.0.canonicalize().map_err(safe_io_error)?;
169 matches.insert(identity, found);
170 }
171 }
172 }
173 if matches.len() > 1 {
174 return Err(format!(
175 "Ambiguous KiCad external model: {} candidates",
176 matches.len()
177 ));
178 }
179 if let Some(found) = matches.into_values().next() {
180 return self.read(locator, found, standard, max_bytes);
181 }
182 }
183 Ok(KiCadModelResolution {
184 authored_locator: locator.into(),
185 status: if candidates.is_empty() && unresolved {
186 KiCadModelResolutionStatus::VariableUnresolved
187 } else {
188 KiCadModelResolutionStatus::Missing
189 },
190 resolved_name: None,
191 payload: None,
192 via_sibling: false,
193 standard_library_reference: standard,
194 })
195 }
196
197 fn read(
198 &self,
199 locator: &str,
200 (path, via_sibling): (PathBuf, bool),
201 standard: bool,
202 max_bytes: usize,
203 ) -> Result<KiCadModelResolution, String> {
204 let file = fs::File::open(&path).map_err(safe_io_error)?;
205 if file.metadata().map_err(safe_io_error)?.len() > max_bytes as u64 {
206 return Err("KiCad external model exceeds file limit".into());
207 }
208 let mut payload = Vec::new();
209 file.take((max_bytes as u64).saturating_add(1))
210 .read_to_end(&mut payload)
211 .map_err(safe_io_error)?;
212 if payload.is_empty() || payload.len() > max_bytes {
213 return Err("KiCad external model is empty or exceeds file limit".into());
214 }
215 Ok(KiCadModelResolution {
216 authored_locator: locator.into(),
217 status: KiCadModelResolutionStatus::Resolved,
218 resolved_name: path
219 .file_name()
220 .map(|value| value.to_string_lossy().into_owned()),
221 payload: Some(payload),
222 via_sibling,
223 standard_library_reference: standard,
224 })
225 }
226}
227
228fn safe_io_error(error: std::io::Error) -> String {
229 format!(
230 "Failed to read KiCad external model; operating-system error {}",
231 error
232 .raw_os_error()
233 .map(|value| value.to_string())
234 .unwrap_or_else(|| "unknown".into())
235 )
236}
237
238fn is_step(path: &Path) -> bool {
239 path.extension().is_some_and(|value| {
240 matches!(
241 value.to_string_lossy().to_ascii_lowercase().as_str(),
242 "step" | "stp"
243 )
244 })
245}
246
247fn existing_model_file(path: &Path, siblings: bool) -> Option<(PathBuf, bool)> {
248 if siblings
249 && path
250 .extension()
251 .is_some_and(|value| value.eq_ignore_ascii_case("wrl"))
252 {
253 for extension in ["step", "stp"] {
254 let candidate = path.with_extension(extension);
255 if candidate.is_file() {
256 return Some((candidate, true));
257 }
258 }
259 }
260 path.is_file().then(|| (path.to_owned(), false))
261}
262
263fn leading_variable_tail(locator: &str) -> Option<&str> {
264 let variable = locator.strip_prefix("${")?;
265 let (_, tail) = variable.split_once('}')?;
266 if variable.starts_with('}') {
267 return None;
268 }
269 Some(tail.strip_prefix(['/', '\\']).unwrap_or(tail))
270}
271
272fn standard_reference(locator: &str) -> bool {
273 let Some(variable) = locator
274 .strip_prefix("${")
275 .and_then(|value| value.split_once('}').map(|pair| pair.0))
276 else {
277 return false;
278 };
279 variable == "KISYS3DMOD"
280 || variable
281 .strip_prefix("KICAD")
282 .and_then(|value| value.strip_suffix("_3DMODEL_DIR"))
283 .is_some_and(|digits| {
284 !digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit())
285 })
286}
287
288fn expand_model_path(
289 locator: &str,
290 project_root: Option<&Path>,
291 variables: &HashMap<String, String>,
292) -> (Option<PathBuf>, bool) {
293 let mut expanded = String::new();
294 let mut unresolved = false;
295 let mut position = 0;
296 while position < locator.len() {
297 let remaining = &locator[position..];
298 let variable = if let Some(value) = remaining.strip_prefix("${") {
299 value
300 .find('}')
301 .filter(|end| *end > 0)
302 .map(|end| (&value[..end], end + 3))
303 } else if let Some(value) = remaining.strip_prefix('%') {
304 value
305 .find('%')
306 .filter(|end| *end > 0)
307 .map(|end| (&value[..end], end + 2))
308 } else if let Some(value) = remaining.strip_prefix('$') {
309 let length = value
310 .bytes()
311 .take_while(|byte| byte.is_ascii_alphanumeric() || *byte == b'_')
312 .count();
313 (length > 0
314 && (value.as_bytes()[0].is_ascii_alphabetic() || value.as_bytes()[0] == b'_'))
315 .then(|| (&value[..length], length + 1))
316 } else {
317 None
318 };
319 if let Some((name, length)) = variable {
320 let value = if name == "KIPRJMOD" {
321 project_root.map(|root| root.to_string_lossy().into_owned())
322 } else {
323 variables.get(name).cloned()
324 };
325 if let Some(value) = value {
326 expanded.push_str(&value);
327 } else {
328 unresolved = true;
329 expanded.push_str(&remaining[..length]);
330 }
331 position += length;
332 } else {
333 let character = remaining.chars().next().expect("nonempty remainder");
334 expanded.push(character);
335 position += character.len_utf8();
336 }
337 }
338 if unresolved {
339 return (None, true);
340 }
341 let path = PathBuf::from(&expanded);
342 if !path.is_absolute() && !expanded.is_empty() {
343 return (project_root.map(|root| root.join(path)), false);
344 }
345 (Some(path), false)
346}