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); 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/// The Windows ProgID the import types are offered under (`OpenWithProgids`).
61#[allow(dead_code)] // Windows only
62const IMPORT_PROG_ID: &str = "BREP.Import";
63
64/// The desktop entry's file name (Linux) — also the id `xdg-mime` takes.
65const DESKTOP_FILE: &str = "brep-app.desktop";
66
67/// What one step of the install did. Collected so the caller prints the whole
68/// story: a partial install is the common case (no `update-mime-database` on a
69/// minimal box) and the user needs to know which half took.
70pub struct Step {
71    pub what: String,
72    pub outcome: Result<String, String>,
73    /// A refresh the desktop would otherwise do at the next login
74    /// (`update-mime-database`, `update-desktop-database`, `xdg-mime`). Its
75    /// failure is a warning: the association's records were written and work
76    /// without it. Only a record that could not be written is a failure.
77    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)] // the refresh helpers exist on Linux only
88    fn optional(mut self) -> Self {
89        self.optional = true;
90        self
91    }
92}
93
94/// The steps that failed and are NOT optional: what the command's exit status
95/// counts. A missing refresh tool is a warning, not one of these.
96pub fn failures(steps: &[Step]) -> usize {
97    steps.iter().filter(|s| s.outcome.is_err() && !s.optional).count()
98}
99
100/// Render the steps for the terminal, and say plainly whether the association
101/// is expected to work now, later, or not at all.
102pub 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
137/// This executable's path, resolved through symlinks so the desktop entry names
138/// the real binary rather than a link that may be replaced by another build.
139fn 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
144/// Install the association. Returns the steps, in the order attempted.
145pub 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
152/// Remove what [`install`] wrote.
153pub fn uninstall() -> Vec<Step> {
154    platform::uninstall()
155}
156
157// --- Linux / BSD: XDG desktop entry + shared MIME info -------------------------
158#[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    /// Run a refresh helper that may not be installed. It is an OPTIONAL
183    /// step: a missing or failing tool is a WARN with the reason rather than a
184    /// silent skip, because the user needs to know their desktop will only
185    /// notice the new type after a re-login. It does not fail the command.
186    /// `path` overrides `PATH` for the tests.
187    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    // Desktop Entry Exec quoting, followed by the key-file string escaping.
208    // This is not shell quoting: the desktop launcher parses the argument itself.
209    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    /// [`install`] into `data` (an `XDG_DATA_HOME`), with the helpers found on
229    /// `path` when given.
230    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        // The types themselves, one per class. `*.nbrep` (and its two
240        // siblings) is the routing key; the comment is what a file manager
241        // shows in its "Type" column.
242        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        // The native classes first, then the import types: listing a type
267        // here makes the app an available opener for it; only the
268        // `xdg-mime default` calls below (native classes only) make it the
269        // default.
270        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        // The application. `%f` (a single local path) rather than `%F`: the
278        // window opens one document per launch, and `%U` would hand us URLs we
279        // cannot read.
280        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    /// [`uninstall`] from `data` (an `XDG_DATA_HOME`), with the helpers found
314    /// on `path` when given.
315    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// --- Windows: per-user file class under HKEY_CURRENT_USER ----------------------
341// Written with `reg.exe` rather than a registry crate: no new dependency, and the
342// same commands a user can read, check and undo by hand.
343#[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        // The import types: an "Open with" choice, never the default. Only
371        // the extension's OpenWithProgids list gains a value; its default
372        // ProgID (whatever owns .step today) is left alone.
373        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        // Only the values the install added: another program's association
391        // of the same extension stays.
392        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// --- macOS: the association lives in a bundle's Info.plist ---------------------
403// A bare binary cannot own a document type there, so this says so rather than
404// writing something that silently does nothing.
405#[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