1use std::path::{Path, PathBuf};
26
27pub const MIME_TYPE: &str = "application/x-nbrep";
30
31pub const CLASSES: [(&str, &str, &str, &str); 3] = [
35 ("nbrep", MIME_TYPE, "BREP model document", "BREP.Model"),
36 ("fbrep", "application/x-fbrep", "BREP part family", "BREP.Family"),
37 ("tbrep", "application/x-tbrep", "BREP part template", "BREP.Template"),
38];
39
40pub const IMPORT_TYPES: [(&str, &[&str], &str); 7] = [
51 ("model/step", &["step", "stp", "p21"], "STEP 3D model"),
52 ("model/iges", &["iges", "igs"], "IGES 3D model"),
53 ("model/vnd.parasolid.transmit.text", &["x_t", "xmt_txt", "p_t"], "Parasolid part"),
54 ("model/vnd.parasolid.transmit.binary", &["x_b", "xmt_bin", "p_b"], "Parasolid binary part"),
55 ("model/stl", &["stl"], "STL mesh"),
56 ("model/3mf", &["3mf"], "3MF mesh package"),
57 ("model/obj", &["obj"], "OBJ mesh"),
58];
59
60#[allow(dead_code)] const IMPORT_PROG_ID: &str = "BREP.Import";
63
64const DESKTOP_FILE: &str = "brep-app.desktop";
66
67pub struct Step {
71 pub what: String,
72 pub outcome: Result<String, String>,
73 pub optional: bool,
78}
79
80impl Step {
81 fn done(what: impl Into<String>, detail: impl Into<String>) -> Self {
82 Step { what: what.into(), outcome: Ok(detail.into()), optional: false }
83 }
84 fn failed(what: impl Into<String>, why: impl Into<String>) -> Self {
85 Step { what: what.into(), outcome: Err(why.into()), optional: false }
86 }
87 #[allow(dead_code)] fn optional(mut self) -> Self {
89 self.optional = true;
90 self
91 }
92}
93
94pub fn failures(steps: &[Step]) -> usize {
97 steps.iter().filter(|s| s.outcome.is_err() && !s.optional).count()
98}
99
100pub fn report(action: &str, steps: &[Step]) -> String {
103 let mut out = String::new();
104 for step in steps {
105 match &step.outcome {
106 Ok(detail) if detail.is_empty() => out.push_str(&format!(" ok {}\n", step.what)),
107 Ok(detail) => out.push_str(&format!(" ok {} — {}\n", step.what, detail)),
108 Err(why) if step.optional => out.push_str(&format!(" WARN {} — {}\n", step.what, why)),
109 Err(why) => out.push_str(&format!(" FAIL {} — {}\n", step.what, why)),
110 }
111 }
112 let failed = failures(steps);
113 let warned = steps.iter().filter(|s| s.outcome.is_err() && s.optional).count();
114 out.push_str(&match (action, failed) {
115 ("install", 0) if warned > 0 => format!(
116 "\nThe association is written. {warned} refresh step(s) did not run, so the desktop may \
117 notice .nbrep, .fbrep and .tbrep only at the next login; to finish now, run\n \
118 xdg-mime default {DESKTOP_FILE} {MIME_TYPE}\n"
119 ),
120 ("install", 0) => format!(
121 "\n.nbrep, .fbrep and .tbrep documents now open in this build. MIME types {}.\n\
122 It is also offered (Open With, not the default) for {}: they are imported into a new tab.\n",
123 CLASSES.map(|(_, mime, _, _)| mime).join(", "),
124 IMPORT_TYPES.map(|(mime, _, _)| mime).join(", ")
125 ),
126 ("install", _) => format!(
127 "\n{failed} step(s) failed. What was written still counts: a desktop entry that could not be \
128 indexed usually takes effect at the next login, and you can finish by hand with\n \
129 xdg-mime default {DESKTOP_FILE} {MIME_TYPE}\n"
130 ),
131 ("uninstall", 0) => "\nthe .nbrep / .fbrep / .tbrep association written by this build is gone.\n".to_string(),
132 (_, _) => format!("\n{failed} step(s) failed; anything listed ok above was removed.\n"),
133 });
134 out
135}
136
137fn exe_path() -> Result<PathBuf, String> {
140 let exe = std::env::current_exe().map_err(|e| format!("cannot read my own path: {e}"))?;
141 Ok(std::fs::canonicalize(&exe).unwrap_or(exe))
142}
143
144pub fn install() -> Vec<Step> {
146 match exe_path() {
147 Ok(exe) => platform::install(&exe),
148 Err(e) => vec![Step::failed("locate this executable", e)],
149 }
150}
151
152pub fn uninstall() -> Vec<Step> {
154 platform::uninstall()
155}
156
157#[cfg(all(unix, not(target_os = "macos")))]
159mod platform {
160 use super::*;
161
162 fn data_home() -> PathBuf {
163 std::env::var_os("XDG_DATA_HOME")
164 .map(PathBuf::from)
165 .filter(|p| p.is_absolute())
166 .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".local/share")))
167 .unwrap_or_else(|| PathBuf::from(".local/share"))
168 }
169
170 fn write(path: &Path, contents: &str, what: &str) -> Step {
171 if let Some(parent) = path.parent() {
172 if let Err(e) = std::fs::create_dir_all(parent) {
173 return Step::failed(what, format!("create {}: {e}", parent.display()));
174 }
175 }
176 match std::fs::write(path, contents) {
177 Ok(()) => Step::done(what, path.display().to_string()),
178 Err(e) => Step::failed(what, format!("write {}: {e}", path.display())),
179 }
180 }
181
182 fn run(program: &str, args: &[&str], path: Option<&std::ffi::OsStr>) -> Step {
188 run_required(program, args, path).optional()
189 }
190
191 fn run_required(program: &str, args: &[&str], path: Option<&std::ffi::OsStr>) -> Step {
192 let what = format!("{program} {}", args.join(" "));
193 let mut command = std::process::Command::new(program);
194 if let Some(path) = path {
195 command.env("PATH", path);
196 }
197 match command.args(args).output() {
198 Ok(out) if out.status.success() => Step::done(what, String::new()),
199 Ok(out) => {
200 let err = String::from_utf8_lossy(&out.stderr).trim().to_string();
201 Step::failed(what, if err.is_empty() { format!("exit {}", out.status) } else { err })
202 }
203 Err(e) => Step::failed(what, format!("{e} (not installed?)")),
204 }
205 }
206
207 pub(super) fn exec_argument(exe: &Path) -> Result<String, String> {
210 let text = exe.to_str().ok_or("desktop executable path must be UTF-8")?;
211 if text.contains(['=', '\n', '\r', '\0']) {
212 return Err("desktop executable path cannot contain '=', a newline or NUL".into());
213 }
214 let mut quoted = String::from("\"");
215 for c in text.chars() {
216 if c == '%' { quoted.push_str("%%"); continue; }
217 if matches!(c, '\\' | '"' | '$' | '`') { quoted.push('\\'); }
218 quoted.push(c);
219 }
220 quoted.push('"');
221 Ok(quoted.replace('\\', "\\\\").replace('\t', "\\t"))
222 }
223
224 pub fn install(exe: &Path) -> Vec<Step> {
225 install_at(exe, &data_home(), None)
226 }
227
228 pub(super) fn install_at(exe: &Path, data: &Path, path: Option<&std::ffi::OsStr>) -> Vec<Step> {
231 let executable = match exec_argument(exe) {
232 Ok(value) => value,
233 Err(error) => return vec![Step::failed("desktop executable path", error)],
234 };
235 let data = data.to_path_buf();
236 let mime_dir = data.join("mime");
237 let mut steps = Vec::new();
238
239 let types: String = CLASSES
243 .iter()
244 .map(|(ext, mime, comment, _)| {
245 format!(
246 " <mime-type type=\"{mime}\">\n <comment>{comment}</comment>\n <glob pattern=\"*.{ext}\"/>\n </mime-type>\n"
247 )
248 })
249 .collect();
250 let import_types: String = IMPORT_TYPES
251 .iter()
252 .map(|(mime, globs, comment)| {
253 let globs: String = globs.iter().map(|ext| format!(" <glob pattern=\"*.{ext}\"/>\n")).collect();
254 format!(" <mime-type type=\"{mime}\">\n <comment>{comment}</comment>\n{globs} </mime-type>\n")
255 })
256 .collect();
257 steps.push(write(
258 &mime_dir.join("packages/brep-app.xml"),
259 &format!(
260 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
261 <mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n\
262 {types}{import_types}</mime-info>\n"
263 ),
264 "declare the .nbrep / .fbrep / .tbrep MIME types",
265 ));
266 let mime_types: String = CLASSES
271 .iter()
272 .map(|(_, mime, _, _)| mime)
273 .chain(IMPORT_TYPES.iter().map(|(mime, _, _)| mime))
274 .map(|mime| format!("{mime};"))
275 .collect();
276
277 steps.push(write(
281 &data.join("applications").join(DESKTOP_FILE),
282 &format!(
283 "[Desktop Entry]\n\
284 Type=Application\n\
285 Name=BREP\n\
286 Comment=Parametric B-rep CAD\n\
287 Exec={} %f\n\
288 Terminal=false\n\
289 Categories=Graphics;Engineering;3DGraphics;\n\
290 MimeType={mime_types}\n\
291 StartupNotify=true\n",
292 executable
293 ),
294 "write the desktop entry",
295 ));
296
297 steps.push(run("update-mime-database", &[&mime_dir.to_string_lossy()], path));
298 steps.push(run(
299 "update-desktop-database",
300 &[&data.join("applications").to_string_lossy()],
301 path,
302 ));
303 for (_, mime, _, _) in CLASSES {
304 steps.push(run("xdg-mime", &["default", DESKTOP_FILE, mime], path));
305 }
306 steps
307 }
308
309 pub fn uninstall() -> Vec<Step> {
310 uninstall_at(&data_home(), None)
311 }
312
313 pub(super) fn uninstall_at(data: &Path, path: Option<&std::ffi::OsStr>) -> Vec<Step> {
316 let mime_dir = data.join("mime");
317 let mut steps = Vec::new();
318 for (path, what) in [
319 (mime_dir.join("packages/brep-app.xml"), "remove the MIME type"),
320 (data.join("applications").join(DESKTOP_FILE), "remove the desktop entry"),
321 ] {
322 steps.push(match std::fs::remove_file(&path) {
323 Ok(()) => Step::done(what, path.display().to_string()),
324 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
325 Step::done(what, format!("{} was already gone", path.display()))
326 }
327 Err(e) => Step::failed(what, format!("remove {}: {e}", path.display())),
328 });
329 }
330 steps.push(run("update-mime-database", &[&mime_dir.to_string_lossy()], path));
331 steps.push(run(
332 "update-desktop-database",
333 &[&data.join("applications").to_string_lossy()],
334 path,
335 ));
336 steps
337 }
338}
339
340#[cfg(windows)]
344mod platform {
345 use super::*;
346
347 fn reg(args: &[&str]) -> Step {
348 let what = format!("reg {}", args.join(" "));
349 match std::process::Command::new("reg").args(args).output() {
350 Ok(out) if out.status.success() => Step::done(what, String::new()),
351 Ok(out) => {
352 let err = String::from_utf8_lossy(&out.stderr).trim().to_string();
353 Step::failed(what, if err.is_empty() { format!("exit {}", out.status) } else { err })
354 }
355 Err(e) => Step::failed(what, e.to_string()),
356 }
357 }
358
359 pub fn install(exe: &Path) -> Vec<Step> {
360 let open = format!("\"{}\" \"%1\"", exe.display());
361 let icon = format!("\"{}\",0", exe.display());
362 let mut steps = Vec::new();
363 for (ext, mime, comment, prog_id) in CLASSES {
364 steps.push(reg(&["add", &format!(r"HKCU\Software\Classes\{prog_id}"), "/ve", "/d", comment, "/f"]));
365 steps.push(reg(&["add", &format!(r"HKCU\Software\Classes\{prog_id}\DefaultIcon"), "/ve", "/d", &icon, "/f"]));
366 steps.push(reg(&["add", &format!(r"HKCU\Software\Classes\{prog_id}\shell\open\command"), "/ve", "/d", &open, "/f"]));
367 steps.push(reg(&["add", &format!(r"HKCU\Software\Classes\.{ext}"), "/ve", "/d", prog_id, "/f"]));
368 steps.push(reg(&["add", &format!(r"HKCU\Software\Classes\.{ext}"), "/v", "Content Type", "/d", mime, "/f"]));
369 }
370 steps.push(reg(&["add", &format!(r"HKCU\Software\Classes\{IMPORT_PROG_ID}"), "/ve", "/d", "BREP import", "/f"]));
374 steps.push(reg(&["add", &format!(r"HKCU\Software\Classes\{IMPORT_PROG_ID}\DefaultIcon"), "/ve", "/d", &icon, "/f"]));
375 steps.push(reg(&["add", &format!(r"HKCU\Software\Classes\{IMPORT_PROG_ID}\shell\open\command"), "/ve", "/d", &open, "/f"]));
376 for (_, globs, _) in IMPORT_TYPES {
377 for ext in globs {
378 steps.push(reg(&["add", &format!(r"HKCU\Software\Classes\.{ext}\OpenWithProgids"), "/v", IMPORT_PROG_ID, "/t", "REG_NONE", "/f"]));
379 }
380 }
381 steps
382 }
383
384 pub fn uninstall() -> Vec<Step> {
385 let mut steps = Vec::new();
386 for (ext, _, _, prog_id) in CLASSES {
387 steps.push(reg(&["delete", &format!(r"HKCU\Software\Classes\.{ext}"), "/f"]));
388 steps.push(reg(&["delete", &format!(r"HKCU\Software\Classes\{prog_id}"), "/f"]));
389 }
390 for (_, globs, _) in IMPORT_TYPES {
393 for ext in globs {
394 steps.push(reg(&["delete", &format!(r"HKCU\Software\Classes\.{ext}\OpenWithProgids"), "/v", IMPORT_PROG_ID, "/f"]));
395 }
396 }
397 steps.push(reg(&["delete", &format!(r"HKCU\Software\Classes\{IMPORT_PROG_ID}"), "/f"]));
398 steps
399 }
400}
401
402#[cfg(target_os = "macos")]
406mod platform {
407 use super::*;
408
409 pub fn install(_exe: &Path) -> Vec<Step> {
410 vec![Step::failed(
411 "register .nbrep / .fbrep / .tbrep",
412 "macOS routes documents by a .app bundle's CFBundleDocumentTypes, which a bare binary has none of; \
413 ship brep-app inside a bundle and declare the type there",
414 )]
415 }
416
417 pub fn uninstall() -> Vec<Step> {
418 vec![Step::done("register .nbrep / .fbrep / .tbrep", "nothing was ever written on macOS")]
419 }
420}
421