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