Skip to main content

music21/musescore/
locate.rs

1//! Where MuseScore is installed, and the numbered pages it writes when it
2//! turns a score into PNG images: music21's `converter.museScore`, less the
3//! running of the program. It reads directories and nothing else.
4
5use std::path::{Path, PathBuf};
6
7use crate::environment::Platform;
8
9/// What a PNG file's name ends with.
10const PNG: &str = ".png";
11
12/// The page numbers MuseScore puts after a `-` on the first page, by how
13/// many pages it wrote: `-1`, `-01` and so on.
14const FIRST_PAGES: [&str; 5] = ["1", "01", "001", "0001", "00001"];
15
16/// The executable inside each MuseScore installation, as a pattern under
17/// a directory it is installed in, newest naming first where a name does
18/// not say which version it is.
19pub fn patterns(platform: Platform) -> &'static [&'static str] {
20    match platform {
21        Platform::Darwin => &["MuseScore*.app/Contents/MacOS/mscore"],
22        Platform::Windows => &["MuseScore*/bin/MuseScore*.exe"],
23        // A bare `mscore` is MuseScore 2 on Debian but MuseScore 4 on Arch.
24        Platform::Nix => &[
25            "mscore4portable",
26            "mscore3",
27            "musescore3",
28            "mscore",
29            "musescore",
30        ],
31    }
32}
33
34/// The directories MuseScore is looked for in when none are given: the
35/// applications folders on a Mac, the program folders on Windows and the
36/// search path elsewhere.
37pub fn default_directories(platform: Platform, home: &Path) -> Vec<PathBuf> {
38    match platform {
39        Platform::Darwin => vec![PathBuf::from("/Applications"), home.join("Applications")],
40        Platform::Windows => ["ProgramFiles", "ProgramFiles(x86)", "ProgramW6432"]
41            .iter()
42            .filter_map(std::env::var_os)
43            .filter(|value| !value.is_empty())
44            .map(PathBuf::from)
45            .collect(),
46        Platform::Nix => std::env::var_os("PATH")
47            .map(|paths| {
48                std::env::split_paths(&paths)
49                    .filter(|path| !path.as_os_str().is_empty())
50                    .collect()
51            })
52            .unwrap_or_default(),
53    }
54}
55
56/// Whether a name is of MuseScore 1 or 2, which cannot make the images:
57/// music21's `MuseScore ?[12]\b`, any case.
58pub fn is_before_three(name: &str) -> bool {
59    let lower = name.to_lowercase();
60    let mut rest = lower.as_str();
61    while let Some(at) = rest.find("musescore") {
62        let after = &rest[at + "musescore".len()..];
63        let digits = after.strip_prefix(' ').unwrap_or(after);
64        let mut chars = digits.chars();
65        if let Some('1' | '2') = chars.next() {
66            let bounded = chars
67                .next()
68                .is_none_or(|next| !(next.is_alphanumeric() || next == '_'));
69            if bounded {
70                return true;
71            }
72        }
73        rest = after;
74    }
75    false
76}
77
78/// MuseScore 3 or newer, found in the directories given, or nowhere: the
79/// newest where several are, by the name of the path under its directory.
80/// music21's `findMuseScore`.
81pub fn find(platform: Platform, directories: &[PathBuf]) -> Option<PathBuf> {
82    for pattern in patterns(platform) {
83        // Keyed by the path under its directory; a later directory's path
84        // of the same name takes its place, as music21's dictionary does.
85        let mut found: Vec<(String, PathBuf)> = Vec::new();
86        for directory in directories {
87            for path in glob(directory, pattern) {
88                let name = relative_name(directory, &path);
89                found.retain(|(held, _)| held != &name);
90                found.push((name, path));
91            }
92        }
93        let newest = found
94            .into_iter()
95            .filter(|(name, _)| !is_before_three(name))
96            .max_by(|left, right| left.0.cmp(&right.0));
97        if let Some((_, path)) = newest {
98            return Some(path);
99        }
100    }
101    None
102}
103
104/// A path's components under a directory, joined by the platform's
105/// separator, as `str(path.relative_to(directory))` writes them.
106fn relative_name(directory: &Path, path: &Path) -> String {
107    path.strip_prefix(directory)
108        .unwrap_or(path)
109        .to_string_lossy()
110        .into_owned()
111}
112
113/// Every path under a directory a pattern matches, a component at a time,
114/// where `*` in a component stands for any run of characters.
115fn glob(directory: &Path, pattern: &str) -> Vec<PathBuf> {
116    let mut reached = vec![directory.to_path_buf()];
117    for component in pattern.split('/') {
118        let mut next = Vec::new();
119        for path in &reached {
120            if !component.contains('*') {
121                let joined = path.join(component);
122                if joined.exists() {
123                    next.push(joined);
124                }
125                continue;
126            }
127            let Ok(entries) = std::fs::read_dir(path) else {
128                continue;
129            };
130            let mut matched: Vec<PathBuf> = entries
131                .flatten()
132                .filter(|entry| wildcard(component, &entry.file_name().to_string_lossy()))
133                .map(|entry| entry.path())
134                .collect();
135            matched.sort();
136            next.extend(matched);
137        }
138        reached = next;
139    }
140    reached
141}
142
143/// Whether a name matches a pattern whose `*`s stand for any run of
144/// characters.
145fn wildcard(pattern: &str, name: &str) -> bool {
146    let mut parts = pattern.split('*');
147    let first = parts.next().unwrap_or_default();
148    let Some(mut rest) = name.strip_prefix(first) else {
149        return false;
150    };
151    let parts: Vec<&str> = parts.collect();
152    let Some((last, middle)) = parts.split_last() else {
153        return rest.is_empty();
154    };
155    for part in middle {
156        let Some(at) = rest.find(part) else {
157            return false;
158        };
159        rest = &rest[at + part.len()..];
160    }
161    rest.len() >= last.len() && rest.ends_with(last)
162}
163
164/// A path named in a refusal as music21 names it.
165fn shown(path: &Path) -> String {
166    path.to_string_lossy().into_owned()
167}
168
169/// The first page MuseScore wrote for an image asked for at a path ending
170/// in `.png`: `score-1.png`, `score-01.png` and so on, whichever is there.
171/// music21's `findNumberedPNGPath`.
172pub fn first_page(path: &Path) -> Result<PathBuf, PageError> {
173    let written = shown(path);
174    let Some(stem) = written.strip_suffix(PNG) else {
175        return Err(PageError::NotPng(format!(
176            "inputFp must end with \".png\"; got {written}"
177        )));
178    };
179    for number in FIRST_PAGES {
180        let page = PathBuf::from(format!("{stem}-{number}{PNG}"));
181        if page.exists() {
182            return Ok(page);
183        }
184    }
185    Err(PageError::Missing(format!(
186        "No png file for {written} (such as {stem}-1.png) was found.  The conversion to png failed"
187    )))
188}
189
190/// Why a page could not be found or read, each with music21's message.
191#[derive(Clone, Debug, PartialEq, Eq)]
192pub enum PageError {
193    /// The name does not end in `.png`.
194    NotPng(String),
195    /// The name has no `-` before its number.
196    Unnumbered(String),
197    /// What stands where the last page's number should is no number.
198    NoNumber(String),
199    /// No page was written.
200    Missing(String),
201}
202
203/// The last page MuseScore wrote beside a numbered one: for `abc-01.png`,
204/// the last `abc-*.png` by name. music21's `findLastPNGPath`.
205pub fn last_page(page: &Path) -> Result<PathBuf, PageError> {
206    let name = file_name(page);
207    if !name.ends_with(PNG) {
208        return Err(PageError::NotPng(format!(
209            "inputFp must end with \".png\"; got {}",
210            shown(page)
211        )));
212    }
213    let Some(dash) = name.rfind('-') else {
214        return Err(PageError::Unnumbered(format!(
215            "inputFp must end with \"-0001.png\" or similar; got {}",
216            shown(page)
217        )));
218    };
219    let prefix = format!("{}-", &name[..dash]);
220    let directory = page.parent().unwrap_or(Path::new("."));
221    let mut pages: Vec<PathBuf> = std::fs::read_dir(directory)
222        .into_iter()
223        .flatten()
224        .flatten()
225        .filter(|entry| {
226            let name = entry.file_name().to_string_lossy().into_owned();
227            name.starts_with(&prefix) && name.ends_with(PNG) && name.len() >= prefix.len() + 4
228        })
229        .map(|entry| entry.path())
230        .collect();
231    pages.sort_by_key(|path| file_name(path));
232    // The page asked about is among them, so there is a last.
233    Ok(pages.pop().unwrap_or_else(|| page.to_path_buf()))
234}
235
236/// How many pages MuseScore wrote and how many digits number them, from
237/// the first page and the last: music21's `findPNGRange`.
238pub fn page_range(first: &Path, last: &Path) -> Result<PageRange, PageError> {
239    let name = file_name(first);
240    if !name.ends_with(PNG) {
241        return Err(PageError::NotPng(format!(
242            "firstFp must end with \".png\"; got {}",
243            shown(first)
244        )));
245    }
246    let Some(dash) = name.rfind('-') else {
247        return Err(PageError::Unnumbered(format!(
248            "firstFp must end with \"-0001.png\" or similar; got {}",
249            shown(first)
250        )));
251    };
252    let digits = name.len() - dash - PNG.len() - 1;
253    let last_name = file_name(last);
254    let number = last_name
255        .get(dash + 1..dash + 1 + digits)
256        .unwrap_or_default();
257    let last = number.parse().map_err(|_| {
258        PageError::NoNumber(format!(
259            "invalid literal for int() with base 10: '{number}'"
260        ))
261    })?;
262    Ok(PageRange { last, digits })
263}
264
265/// The number of the last page and how many digits each page's number has.
266#[derive(Clone, Copy, Debug, PartialEq, Eq)]
267pub struct PageRange {
268    /// The number of the last page.
269    pub last: u64,
270    /// How many digits each number is written with.
271    pub digits: usize,
272}
273
274/// A path's file name as text.
275fn file_name(path: &Path) -> String {
276    path.file_name()
277        .map(|name| name.to_string_lossy().into_owned())
278        .unwrap_or_default()
279}
280
281/// How MuseScore is asked to write a score as an image.
282#[derive(Clone, Debug, PartialEq, Eq)]
283pub struct ImageRequest {
284    /// The image's resolution, MuseScore's own where none.
285    pub dpi: Option<u32>,
286    /// The pixels left around the music where the image is cut to it, or
287    /// none to leave the page whole.
288    pub trim: Option<u32>,
289}
290
291/// The command line that has MuseScore write `input` as `output`: music21's
292/// `runThroughMuseScore`, `-T` for trimming and `-r` for resolution.
293pub fn image_command(
294    executable: &Path,
295    input: &Path,
296    output: &Path,
297    request: &ImageRequest,
298) -> Vec<String> {
299    let mut command = vec![shown(executable), shown(input), "-o".into(), shown(output)];
300    if let Some(margin) = request.trim {
301        command.extend(["-T".into(), margin.to_string()]);
302    }
303    if let Some(dpi) = request.dpi {
304        command.extend(["-r".into(), dpi.to_string()]);
305    }
306    command
307}
308
309#[cfg(test)]
310mod tests {
311    use super::*;
312
313    fn touch(root: &Path, relative: &str) {
314        let path = root.join(relative);
315        std::fs::create_dir_all(path.parent().expect("a parent")).expect("a directory");
316        std::fs::write(path, b"").expect("a file");
317    }
318
319    fn scratch(name: &str) -> PathBuf {
320        let directory =
321            std::env::temp_dir().join(format!("music21-rs-locate-{name}-{}", std::process::id()));
322        let _ = std::fs::remove_dir_all(&directory);
323        std::fs::create_dir_all(&directory).expect("a directory");
324        directory
325    }
326
327    #[test]
328    fn names_of_musescore_two_are_too_old() {
329        assert!(is_before_three("MuseScore 2.app/Contents/MacOS/mscore"));
330        assert!(is_before_three("musescore1"));
331        assert!(!is_before_three("MuseScore 4.app/Contents/MacOS/mscore"));
332        assert!(!is_before_three("MuseScore 20"));
333        assert!(!is_before_three("mscore3"));
334    }
335
336    #[test]
337    fn the_newest_mac_installation_is_found() {
338        let apps = scratch("mac");
339        touch(&apps, "MuseScore 3.app/Contents/MacOS/mscore");
340        touch(&apps, "MuseScore 4.app/Contents/MacOS/mscore");
341        touch(&apps, "old/MuseScore 2.app/Contents/MacOS/mscore");
342        assert_eq!(
343            find(Platform::Darwin, std::slice::from_ref(&apps)),
344            Some(apps.join("MuseScore 4.app/Contents/MacOS/mscore"))
345        );
346        assert_eq!(find(Platform::Darwin, &[apps.join("old")]), None);
347        let _ = std::fs::remove_dir_all(apps);
348    }
349
350    #[test]
351    fn a_name_saying_its_version_comes_before_a_bare_one() {
352        let bin = scratch("nix");
353        touch(&bin, "mscore");
354        touch(&bin, "mscore3");
355        assert_eq!(
356            find(Platform::Nix, std::slice::from_ref(&bin)),
357            Some(bin.join("mscore3"))
358        );
359        let _ = std::fs::remove_dir_all(bin);
360    }
361
362    #[test]
363    fn pages_are_found_by_their_numbers() {
364        let directory = scratch("pages");
365        touch(&directory, "score-01.png");
366        touch(&directory, "score-02.png");
367        touch(&directory, "score-12.png");
368        let first = first_page(&directory.join("score.png")).expect("a first page");
369        assert_eq!(first, directory.join("score-01.png"));
370        let last = last_page(&first).expect("a last page");
371        assert_eq!(last, directory.join("score-12.png"));
372        assert_eq!(
373            page_range(&first, &last),
374            Ok(PageRange {
375                last: 12,
376                digits: 2
377            })
378        );
379        assert!(first_page(&directory.join("other.png")).is_err());
380        assert!(first_page(&directory.join("score.pdf")).is_err());
381        let _ = std::fs::remove_dir_all(directory);
382    }
383
384    #[test]
385    fn an_image_command_trims_and_sets_a_resolution() {
386        let request = ImageRequest {
387            dpi: Some(72),
388            trim: Some(0),
389        };
390        let command = image_command(
391            Path::new("mscore"),
392            Path::new("a.xml"),
393            Path::new("a.png"),
394            &request,
395        );
396        assert_eq!(
397            command,
398            ["mscore", "a.xml", "-o", "a.png", "-T", "0", "-r", "72"]
399        );
400    }
401}