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