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/stl`, `model/3mf`, `model/obj`); the install declares them with
44/// their globs too, because an older shared-mime-info has no `model/step`
45/// and a desktop entry naming an unknown type routes nothing. Declaring a
46/// type the system already has merges the globs; it replaces nothing.
47/// KiCad files are imported too but have no registered type, and KiCad's own
48/// association owns them, so they are not offered here.
49pub 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/// The Windows ProgID the import types are offered under (`OpenWithProgids`).
58#[allow(dead_code)] // Windows only
59const IMPORT_PROG_ID: &str = "BREP.Import";
60
61/// The desktop entry's file name (Linux) — also the id `xdg-mime` takes.
62const DESKTOP_FILE: &str = "brep-app.desktop";
63
64/// What one step of the install did. Collected so the caller prints the whole
65/// story: a partial install is the common case (no `update-mime-database` on a
66/// minimal box) and the user needs to know which half took.
67pub struct Step {
68    pub what: String,
69    pub outcome: Result<String, String>,
70    /// A refresh the desktop would otherwise do at the next login
71    /// (`update-mime-database`, `update-desktop-database`, `xdg-mime`). Its
72    /// failure is a warning: the association's records were written and work
73    /// without it. Only a record that could not be written is a failure.
74    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)] // the refresh helpers exist on Linux only
85    fn optional(mut self) -> Self {
86        self.optional = true;
87        self
88    }
89}
90
91/// The steps that failed and are NOT optional: what the command's exit status
92/// counts. A missing refresh tool is a warning, not one of these.
93pub fn failures(steps: &[Step]) -> usize {
94    steps.iter().filter(|s| s.outcome.is_err() && !s.optional).count()
95}
96
97/// Render the steps for the terminal, and say plainly whether the association
98/// is expected to work now, later, or not at all.
99pub 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
134/// This executable's path, resolved through symlinks so the desktop entry names
135/// the real binary rather than a link that may be replaced by another build.
136fn 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
141/// Install the association. Returns the steps, in the order attempted.
142pub 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
149/// Remove what [`install`] wrote.
150pub fn uninstall() -> Vec<Step> {
151    platform::uninstall()
152}
153
154// --- Linux / BSD: XDG desktop entry + shared MIME info -------------------------
155#[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    /// Run a refresh helper that may not be installed. It is an OPTIONAL
180    /// step: a missing or failing tool is a WARN with the reason rather than a
181    /// silent skip, because the user needs to know their desktop will only
182    /// notice the new type after a re-login. It does not fail the command.
183    /// `path` overrides `PATH` for the tests.
184    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    // Desktop Entry Exec quoting, followed by the key-file string escaping.
205    // This is not shell quoting: the desktop launcher parses the argument itself.
206    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    /// [`install`] into `data` (an `XDG_DATA_HOME`), with the helpers found on
226    /// `path` when given.
227    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        // The types themselves, one per class. `*.nbrep` (and its two
237        // siblings) is the routing key; the comment is what a file manager
238        // shows in its "Type" column.
239        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        // The native classes first, then the import types: listing a type
264        // here makes the app an available opener for it; only the
265        // `xdg-mime default` calls below (native classes only) make it the
266        // default.
267        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        // The application. `%f` (a single local path) rather than `%F`: the
275        // window opens one document per launch, and `%U` would hand us URLs we
276        // cannot read.
277        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// --- Windows: per-user file class under HKEY_CURRENT_USER ----------------------
333// Written with `reg.exe` rather than a registry crate: no new dependency, and the
334// same commands a user can read, check and undo by hand.
335#[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        // The import types: an "Open with" choice, never the default. Only
363        // the extension's OpenWithProgids list gains a value; its default
364        // ProgID (whatever owns .step today) is left alone.
365        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        // Only the values the install added: another program's association
383        // of the same extension stays.
384        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// --- macOS: the association lives in a bundle's Info.plist ---------------------
395// A bare binary cannot own a document type there, so this says so rather than
396// writing something that silently does nothing.
397#[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