1use std::path::{Path, PathBuf};
6
7use crate::environment::Platform;
8
9const PNG: &str = ".png";
11
12const FIRST_PAGES: [&str; 5] = ["1", "01", "001", "0001", "00001"];
15
16pub 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 Platform::Nix => &[
25 "mscore4portable",
26 "mscore3",
27 "musescore3",
28 "mscore",
29 "musescore",
30 ],
31 }
32}
33
34pub 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
56pub 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
78pub fn find(platform: Platform, directories: &[PathBuf]) -> Option<PathBuf> {
82 for pattern in patterns(platform) {
83 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
104fn 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
113fn 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
143fn 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
164fn shown(path: &Path) -> String {
166 path.to_string_lossy().into_owned()
167}
168
169pub 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#[derive(Clone, Debug, PartialEq, Eq)]
192pub enum PageError {
193 NotPng(String),
195 Unnumbered(String),
197 NoNumber(String),
199 Missing(String),
201}
202
203pub 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 Ok(pages.pop().unwrap_or_else(|| page.to_path_buf()))
234}
235
236pub 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
267pub struct PageRange {
268 pub last: u64,
270 pub digits: usize,
272}
273
274fn 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#[derive(Clone, Debug, PartialEq, Eq)]
283pub struct ImageRequest {
284 pub dpi: Option<u32>,
286 pub trim: Option<u32>,
289}
290
291pub 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}