Skip to main content

brep_app/
file_association.rs

1//! Register this executable as the system's opener for its three document
2//! classes: `.nbrep` parts, `.fbrep` family seeds and `.tbrep` templates —
3//! the DEFAULT opener for those — and as one AVAILABLE opener ("Open With")
4//! for the files it imports (STEP, IGES, STL, 3MF, OBJ), never their default.
5//! A file of an import type opened this way is imported into a new untitled
6//! tab (`BrepApp::open_path_from_command_line`).
7//!
8//! `brep-app --install-file-associations` writes the platform's own association
9//! records and points them at the RUNNING executable's path
10//! (`std::env::current_exe`), so a build the user moved or renamed associates
11//! itself rather than a path we guessed. `--uninstall-file-associations` removes
12//! what the install wrote.
13//!
14//! Why this is per-user and never system-wide: writing `/usr/share` or
15//! `HKEY_CLASSES_ROOT` needs privileges the app must not ask for, and a CAD
16//! viewer that silently wants root is worse than one that associates for the
17//! person who ran it. Everything below lands under `$XDG_DATA_HOME` (Linux) or
18//! `HKEY_CURRENT_USER` (Windows).
19//!
20//! Every step reports what it did or why it could not, and a failure in one step
21//! does not abandon the others: a desktop entry written but not indexed still
22//! works after the next login, so "wrote the entry, could not run
23//! update-desktop-database" is a useful outcome rather than an error to roll back.
24
25use std::path::{Path, PathBuf};
26
27/// The MIME type the association declares. `x-` because `.nbrep` is ours and
28/// unregistered with IANA; the glob is what actually routes a double click.
29pub const MIME_TYPE: &str = "application/x-nbrep";
30
31/// Every class the association declares, one MIME type each in the same
32/// family: `(extension without the dot, MIME type, what a file manager calls
33/// it, the Windows ProgID)`.
34pub 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
40/// The files the app imports that the OS may offer it for, never as their
41/// default opener: `(MIME type, its globs, what a file manager calls it)`.
42/// The standard `model/*` types (IANA registers `model/step`, `model/iges`,
43/// `model/vnd.parasolid.transmit.text`, `model/stl`, `model/3mf`,
44/// `model/obj`); the install declares them with
45/// their globs too, because an older shared-mime-info has no `model/step`
46/// and a desktop entry naming an unknown type routes nothing. Declaring a
47/// type the system already has merges the globs; it replaces nothing.
48/// KiCad files are imported too but have no registered type, and KiCad's own
49/// association owns them, so they are not offered here.
50pub 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/// The Windows ProgID the import types are offered under (`OpenWithProgids`).
60#[allow(dead_code)] // Windows only
61const IMPORT_PROG_ID: &str = "BREP.Import";
62
63/// The desktop entry's file name (Linux) — also the id `xdg-mime` takes.
64const DESKTOP_FILE: &str = "brep-app.desktop";
65
66/// What one step of the install did. Collected so the caller prints the whole
67/// story: a partial install is the common case (no `update-mime-database` on a
68/// minimal box) and the user needs to know which half took.
69pub struct Step {
70    pub what: String,
71    pub outcome: Result<String, String>,
72    /// A refresh the desktop would otherwise do at the next login
73    /// (`update-mime-database`, `update-desktop-database`, `xdg-mime`). Its
74    /// failure is a warning: the association's records were written and work
75    /// without it. Only a record that could not be written is a failure.
76    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)] // the refresh helpers exist on Linux only
87    fn optional(mut self) -> Self {
88        self.optional = true;
89        self
90    }
91}
92
93/// The steps that failed and are NOT optional: what the command's exit status
94/// counts. A missing refresh tool is a warning, not one of these.
95pub fn failures(steps: &[Step]) -> usize {
96    steps.iter().filter(|s| s.outcome.is_err() && !s.optional).count()
97}
98
99/// Render the steps for the terminal, and say plainly whether the association
100/// is expected to work now, later, or not at all.
101pub 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
136/// This executable's path, resolved through symlinks so the desktop entry names
137/// the real binary rather than a link that may be replaced by another build.
138fn 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
143/// Install the association. Returns the steps, in the order attempted.
144pub 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
151/// Remove what [`install`] wrote.
152pub fn uninstall() -> Vec<Step> {
153    platform::uninstall()
154}
155
156// --- Linux / BSD: XDG desktop entry + shared MIME info -------------------------
157#[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    /// Run a refresh helper that may not be installed. It is an OPTIONAL
182    /// step: a missing or failing tool is a WARN with the reason rather than a
183    /// silent skip, because the user needs to know their desktop will only
184    /// notice the new type after a re-login. It does not fail the command.
185    /// `path` overrides `PATH` for the tests.
186    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    // Desktop Entry Exec quoting, followed by the key-file string escaping.
207    // This is not shell quoting: the desktop launcher parses the argument itself.
208    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    /// [`install`] into `data` (an `XDG_DATA_HOME`), with the helpers found on
228    /// `path` when given.
229    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        // The types themselves, one per class. `*.nbrep` (and its two
239        // siblings) is the routing key; the comment is what a file manager
240        // shows in its "Type" column.
241        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        // The native classes first, then the import types: listing a type
266        // here makes the app an available opener for it; only the
267        // `xdg-mime default` calls below (native classes only) make it the
268        // default.
269        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        // The application. `%f` (a single local path) rather than `%F`: the
277        // window opens one document per launch, and `%U` would hand us URLs we
278        // cannot read.
279        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    /// [`uninstall`] from `data` (an `XDG_DATA_HOME`), with the helpers found
313    /// on `path` when given.
314    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// --- Windows: per-user file class under HKEY_CURRENT_USER ----------------------
340// Written with `reg.exe` rather than a registry crate: no new dependency, and the
341// same commands a user can read, check and undo by hand.
342#[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        // The import types: an "Open with" choice, never the default. Only
370        // the extension's OpenWithProgids list gains a value; its default
371        // ProgID (whatever owns .step today) is left alone.
372        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        // Only the values the install added: another program's association
390        // of the same extension stays.
391        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// --- macOS: the association lives in a bundle's Info.plist ---------------------
402// A bare binary cannot own a document type there, so this says so rather than
403// writing something that silently does nothing.
404#[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