1use std::borrow::Cow;
10use std::path::Path;
11
12use super::{
13 Metadata, contributor_answers_to, is_contributor_unique_name, namespace_name, old_work_id,
14 unique_name_of_field,
15};
16use crate::common::numbertools::{OffsetQL, op_frac};
17use crate::defaults::IntegerType;
18use crate::error::Result;
19use crate::interval::Interval;
20use crate::stream::{Stream, StreamElement};
21
22pub const RICH_ATTRIBUTES: [&str; 13] = [
25 "ambitus",
26 "keySignatureFirst",
27 "keySignatures",
28 "noteCount",
29 "numberOfParts",
30 "pitchHighest",
31 "pitchLowest",
32 "scoreQuarterLength",
33 "sourcePath",
34 "tempoFirst",
35 "tempos",
36 "timeSignatureFirst",
37 "timeSignatures",
38];
39
40#[derive(Clone, Debug, PartialEq, Eq)]
42#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
43pub struct AmbitusShort {
44 pub semitones: IntegerType,
46 pub diatonic: String,
48 pub pitch_lowest: Option<String>,
50 pub pitch_highest: Option<String>,
52}
53
54#[derive(Clone, Debug, PartialEq)]
56pub enum RichValue<'a> {
57 None,
59 Text(Cow<'a, str>),
61 Integer(IntegerType),
63 Length(OffsetQL),
65 Texts(&'a [String]),
67 Integers(&'a [IntegerType]),
69 Ambitus(&'a AmbitusShort),
71}
72
73pub enum RichQuery<'a> {
76 Text(&'a str),
78 Pattern(&'a dyn Fn(&str) -> bool),
81 Function(&'a dyn Fn(&RichValue<'_>) -> bool),
83 Integer(IntegerType),
85 Sharps(IntegerType),
87}
88
89impl std::fmt::Debug for RichQuery<'_> {
90 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91 match self {
92 Self::Text(query) => formatter.debug_tuple("Text").field(query).finish(),
93 Self::Pattern(_) => formatter.write_str("Pattern(..)"),
94 Self::Function(_) => formatter.write_str("Function(..)"),
95 Self::Integer(query) => formatter.debug_tuple("Integer").field(query).finish(),
96 Self::Sharps(query) => formatter.debug_tuple("Sharps").field(query).finish(),
97 }
98 }
99}
100
101impl RichQuery<'_> {
102 fn matches(&self, value: &RichValue<'_>) -> bool {
103 match (self, value) {
104 (Self::Function(function), value) => function(value),
105 (Self::Text(query), RichValue::Text(text)) => {
106 text.to_lowercase().contains(&query.to_lowercase())
107 }
108 (Self::Pattern(pattern), RichValue::Text(text)) => pattern(text),
109 (Self::Integer(query), RichValue::Text(text)) => text.contains(&query.to_string()),
110 (Self::Integer(query) | Self::Sharps(query), RichValue::Integer(value)) => {
111 query == value
112 }
113 _ => false,
114 }
115 }
116}
117
118#[derive(Clone, Debug, PartialEq)]
134#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
135pub struct RichMetadata {
136 pub metadata: Metadata,
138 pub ambitus: Option<AmbitusShort>,
140 pub key_signature_first: Option<IntegerType>,
142 pub key_signatures: Vec<IntegerType>,
144 pub note_count: Option<IntegerType>,
146 pub number_of_parts: Option<IntegerType>,
148 pub pitch_highest: Option<String>,
150 pub pitch_lowest: Option<String>,
152 pub score_quarter_length: OffsetQL,
154 pub source_path: String,
156 pub tempo_first: Option<String>,
158 pub tempos: Vec<String>,
160 pub time_signature_first: Option<String>,
162 pub time_signatures: Vec<String>,
164}
165
166impl Default for RichMetadata {
167 fn default() -> Self {
168 Self {
169 metadata: Metadata::new(),
170 ambitus: None,
171 key_signature_first: None,
172 key_signatures: Vec::new(),
173 note_count: None,
174 number_of_parts: None,
175 pitch_highest: None,
176 pitch_lowest: None,
177 score_quarter_length: OffsetQL::Float(0.0),
178 source_path: String::new(),
179 tempo_first: None,
180 tempos: Vec::new(),
181 time_signature_first: None,
182 time_signatures: Vec::new(),
183 }
184 }
185}
186
187impl RichMetadata {
188 pub fn of(metadata: Metadata) -> Self {
190 Self {
191 metadata,
192 ..Self::default()
193 }
194 }
195
196 pub fn value(&self, name: &str) -> Option<RichValue<'_>> {
199 fn text(found: &Option<String>) -> RichValue<'_> {
200 found
201 .as_deref()
202 .map_or(RichValue::None, |text| RichValue::Text(Cow::Borrowed(text)))
203 }
204 let integer =
205 |found: Option<IntegerType>| found.map_or(RichValue::None, RichValue::Integer);
206 let value = match name {
207 "ambitus" => self
208 .ambitus
209 .as_ref()
210 .map_or(RichValue::None, RichValue::Ambitus),
211 "keySignatureFirst" => integer(self.key_signature_first),
212 "keySignatures" => RichValue::Integers(&self.key_signatures),
213 "noteCount" => integer(self.note_count),
214 "numberOfParts" => integer(self.number_of_parts),
215 "pitchHighest" => text(&self.pitch_highest),
216 "pitchLowest" => text(&self.pitch_lowest),
217 "scoreQuarterLength" => RichValue::Length(self.score_quarter_length),
218 "sourcePath" => RichValue::Text(Cow::Borrowed(&self.source_path)),
219 "tempoFirst" => text(&self.tempo_first),
220 "tempos" => RichValue::Texts(&self.tempos),
221 "timeSignatureFirst" => text(&self.time_signature_first),
222 "timeSignatures" => RichValue::Texts(&self.time_signatures),
223 _ => return None,
224 };
225 Some(value)
226 }
227
228 pub fn update(&mut self, stream: &Stream, corpus: Option<&Path>) -> Result<()> {
236 self.number_of_parts = Some(stream.parts().len() as IntegerType);
237 self.source_path = source_path(stream, corpus);
238 self.key_signatures.clear();
239 self.tempos.clear();
240 self.time_signatures.clear();
241
242 let flat = stream.flatten();
244 for (_, element) in flat.leaves() {
245 match element {
246 StreamElement::TimeSignature(meter) => {
247 push_new(&mut self.time_signatures, meter.ratio_string());
248 }
249 StreamElement::KeySignature(signature) => {
250 push_new(&mut self.key_signatures, signature.sharps());
251 }
252 StreamElement::Key(key) => push_new(&mut self.key_signatures, key.sharps()),
253 StreamElement::MetronomeMark(mark) => {
254 push_new(&mut self.tempos, mark.music21_repr());
255 }
256 StreamElement::TempoText(text) => push_new(&mut self.tempos, text.music21_repr()),
257 _ => {}
258 }
259 }
260 self.time_signature_first = self.time_signatures.first().cloned();
261 self.key_signature_first = self.key_signatures.first().copied();
262 self.tempo_first = self.tempos.first().cloned();
263 self.note_count = Some(flat.notes_and_rests().len() as IntegerType);
264 self.score_quarter_length = op_frac(crate::variant::highest_time(&flat))?;
265
266 let span = crate::analysis::stream_pitch_span(stream);
268 self.pitch_lowest = span.as_ref().map(|(low, _)| low.name_with_octave());
269 self.pitch_highest = span.as_ref().map(|(_, high)| high.name_with_octave());
270 let interval = match &span {
271 Some((low, high)) => Interval::between_pitches(low, high)?,
272 None => Interval::from_name("P1")?,
273 };
274 self.ambitus = Some(AmbitusShort {
275 semitones: interval.semitones() as IntegerType,
276 diatonic: interval.diatonic().simple_name(),
277 pitch_lowest: self.pitch_lowest.clone(),
278 pitch_highest: self.pitch_highest.clone(),
279 });
280 Ok(())
281 }
282
283 pub fn search(&self, query: &RichQuery<'_>, field: Option<&str>) -> Option<Option<&str>> {
288 let field = field.map(str::to_lowercase);
289 self.search_pairs(field.as_deref())
290 .into_iter()
291 .find(|(value, _)| query.matches(value))
292 .map(|(_, field)| field)
293 }
294
295 fn search_pairs(&self, field: Option<&str>) -> Vec<(RichValue<'_>, Option<&str>)> {
298 let mut pairs = Vec::new();
299 match field {
300 Some(field) => pairs.extend(self.field_pairs(field)),
301 None => pairs.extend(
302 self.standard_values()
303 .into_iter()
304 .map(|(name, value)| (value, Some(name))),
305 ),
306 }
307
308 for (_, value) in self.metadata.contributors() {
310 if !contributor_answers_to(value.role(), field) {
311 continue;
312 }
313 let names: Vec<&str> = match value.as_contributor() {
314 Some(contributor) => contributor.names().iter().map(|name| name.data()).collect(),
315 None => vec![value.text()],
316 };
317 for name in names {
318 pairs.push((RichValue::Text(Cow::Borrowed(name)), value.role()));
319 }
320 }
321 pairs
322 }
323
324 fn field_pairs(&self, field: &str) -> Vec<(RichValue<'_>, Option<&str>)> {
327 if let Some(name) = RICH_ATTRIBUTES.iter().find(|name| **name == field) {
330 let value = self.value(name).unwrap_or(RichValue::None);
331 if value != RichValue::None {
332 return vec![(value, Some(*name))];
333 }
334 }
335 if let Some((unique_name, asked)) = unique_name_of_field(field) {
336 let texts = self.metadata.field_texts(unique_name);
337 if !texts.is_empty() {
338 return texts
339 .into_iter()
340 .map(|text| (RichValue::Text(text), Some(asked)))
341 .collect();
342 }
343 }
344
345 for (name, value) in self.standard_values() {
348 if name.to_lowercase().contains(field) {
349 return vec![(value, Some(name))];
350 }
351 let Some(work_id) = old_work_id(name) else {
352 continue;
353 };
354 if work_id.to_lowercase().contains(field) {
355 return vec![(value, Some(work_id))];
356 }
357 }
358 Vec::new()
359 }
360
361 fn standard_values(&self) -> Vec<(&str, RichValue<'_>)> {
365 let mut values: Vec<(&str, RichValue<'_>)> = self
366 .metadata
367 .all_sorted()
368 .into_iter()
369 .filter(|(name, _)| !is_contributor_unique_name(name) && namespace_name(name).is_some())
370 .map(|(name, value)| (name, RichValue::Text(Cow::Borrowed(value.text()))))
371 .collect();
372 for name in RICH_ATTRIBUTES {
373 values.push((name, self.value(name).unwrap_or(RichValue::None)));
374 }
375 values.sort_by(|left, right| left.0.cmp(right.0));
376 values
377 }
378}
379
380fn push_new<T: PartialEq>(values: &mut Vec<T>, value: T) {
382 if !values.contains(&value) {
383 values.push(value);
384 }
385}
386
387fn source_path(stream: &Stream, corpus: Option<&Path>) -> String {
390 let Some(metadata) = stream.metadata() else {
391 return String::new();
392 };
393 if let Some(found) = metadata
394 .first_text("corpusFilePath")
395 .filter(|found| !found.is_empty())
396 {
397 return found.to_string();
398 }
399 let Some(file) = metadata
400 .first_text("filePath")
401 .filter(|file| !file.is_empty())
402 else {
403 return String::new();
404 };
405 let file = Path::new(file);
406 let relative = corpus
407 .and_then(|corpus| file.strip_prefix(corpus).ok())
408 .unwrap_or(file);
409 relative
410 .components()
411 .map(|part| part.as_os_str().to_string_lossy())
412 .collect::<Vec<_>>()
413 .join("/")
414 .replacen("//", "/", 1)
415}
416
417#[cfg(test)]
418mod tests {
419 use super::*;
420
421 fn bach() -> RichMetadata {
422 let mut metadata = Metadata::new();
423 metadata.add_contributor("composer", "J.S. Bach");
424 metadata.add_text("title", "Aus meines Herzens Grunde");
425 let mut rich = RichMetadata::of(metadata);
426 rich.note_count = Some(12);
427 rich.time_signatures = vec!["3/4".to_string()];
428 rich.time_signature_first = Some("3/4".to_string());
429 rich.source_path = "bach/bwv1.6.mxl".to_string();
430 rich
431 }
432
433 #[test]
434 fn a_search_reads_the_score_s_values() {
435 let rich = bach();
436 assert_eq!(
437 rich.search(&RichQuery::Text("3/4"), None),
438 Some(Some("timeSignatureFirst"))
439 );
440 assert_eq!(
441 rich.search(&RichQuery::Text("bach"), Some("composer")),
442 Some(Some("composer"))
443 );
444 assert_eq!(
445 rich.search(&RichQuery::Text("bwv1.6"), None),
446 Some(Some("sourcePath"))
447 );
448 assert_eq!(rich.search(&RichQuery::Text("mozart"), None), None);
449 }
450
451 #[test]
452 fn a_camel_case_field_is_found_by_its_lowercase_spelling() {
453 let rich = bach();
454 let fewer =
455 |value: &RichValue<'_>| matches!(value, RichValue::Integer(count) if *count < 20);
456 let query = RichQuery::Function(&fewer);
457 assert_eq!(
458 rich.search(&query, Some("noteCount")),
459 Some(Some("noteCount"))
460 );
461 assert_eq!(
462 rich.search(&RichQuery::Integer(12), Some("notecount")),
463 Some(Some("noteCount"))
464 );
465 }
466
467 #[test]
468 fn a_list_is_not_text() {
469 let rich = bach();
470 assert_eq!(
471 rich.search(&RichQuery::Text("3/4"), Some("timeSignatures")),
472 None
473 );
474 }
475}