head_music 23.0.0 → 24.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. checksums.yaml +4 -4
  2. data/.gitignore +1 -1
  3. data/.rspec_parallel +2 -0
  4. data/CHANGELOG.md +44 -0
  5. data/CLAUDE.md +5 -4
  6. data/Gemfile +1 -0
  7. data/Gemfile.lock +13 -10
  8. data/MUSIC_THEORY.md +1 -1
  9. data/Rakefile +55 -4
  10. data/bin/validate +1 -1
  11. data/lib/head_music/content/flow/staff_system_values.rb +2 -6
  12. data/lib/head_music/content/staff.rb +6 -2
  13. data/lib/head_music/instruments/alternate_tuning.rb +1 -1
  14. data/lib/head_music/instruments/alternate_tunings.yml +7 -4
  15. data/lib/head_music/instruments/instrument.rb +5 -2
  16. data/lib/head_music/instruments/instrument_family.rb +4 -0
  17. data/lib/head_music/instruments/instruments.yml +8 -0
  18. data/lib/head_music/instruments/stringings.yml +14 -0
  19. data/lib/head_music/locales/de.yml +8 -0
  20. data/lib/head_music/locales/en.yml +59 -0
  21. data/lib/head_music/locales/en_GB.yml +10 -0
  22. data/lib/head_music/locales/es.yml +8 -0
  23. data/lib/head_music/locales/fr.yml +8 -0
  24. data/lib/head_music/locales/it.yml +8 -0
  25. data/lib/head_music/locales/ru.yml +8 -0
  26. data/lib/head_music/midi/instrument_map.rb +2 -1
  27. data/lib/head_music/named.rb +11 -1
  28. data/lib/head_music/notation/concert_transposition.rb +8 -0
  29. data/lib/head_music/notation/instrument_names.rb +62 -0
  30. data/lib/head_music/notation/lily_pond/context_reader.rb +13 -3
  31. data/lib/head_music/notation/lily_pond/document.rb +25 -0
  32. data/lib/head_music/notation/lily_pond/flow_builder.rb +2 -0
  33. data/lib/head_music/notation/lily_pond/grace_reader.rb +38 -9
  34. data/lib/head_music/notation/lily_pond/part_layout.rb +26 -8
  35. data/lib/head_music/notation/lily_pond/render_plan.rb +21 -0
  36. data/lib/head_music/notation/lily_pond/setting_reader.rb +19 -2
  37. data/lib/head_music/notation/lily_pond/transposition_walk.rb +141 -0
  38. data/lib/head_music/notation/lily_pond/voice_context.rb +4 -2
  39. data/lib/head_music/notation/lily_pond/voice_item_reader.rb +2 -1
  40. data/lib/head_music/notation/lily_pond/voice_stream.rb +50 -14
  41. data/lib/head_music/notation/lily_pond/voice_writer.rb +18 -10
  42. data/lib/head_music/notation/lily_pond/writer.rb +3 -3
  43. data/lib/head_music/notation/music_xml/identity_reader.rb +54 -4
  44. data/lib/head_music/notation/music_xml/instrument_sounds.rb +15 -2
  45. data/lib/head_music/notation/music_xml/instrument_sounds.yml +3 -0
  46. data/lib/head_music/notation/music_xml/note_writer.rb +13 -3
  47. data/lib/head_music/notation/music_xml/part_reader.rb +36 -5
  48. data/lib/head_music/notation/music_xml/part_roster.rb +18 -1
  49. data/lib/head_music/notation/music_xml/part_writer.rb +20 -2
  50. data/lib/head_music/notation/music_xml/score_instruments.rb +20 -0
  51. data/lib/head_music/notation/music_xml/shared_instrument_sounds.yml +22 -0
  52. data/lib/head_music/notation/music_xml/writer.rb +10 -11
  53. data/lib/head_music/notation/notation_styles.yml +8 -0
  54. data/lib/head_music/notation.rb +1 -0
  55. data/lib/head_music/rudiment/clef.rb +8 -2
  56. data/lib/head_music/style/guide.rb +5 -2
  57. data/lib/head_music/style/guideline/bar_texture.rb +79 -0
  58. data/lib/head_music/style/guideline/dissonance_figures.rb +88 -0
  59. data/lib/head_music/style/guideline/harmonic_context.rb +1 -1
  60. data/lib/head_music/style/guideline/restruck_suspensions.rb +38 -0
  61. data/lib/head_music/style/guideline/voice_context.rb +34 -3
  62. data/lib/head_music/style/guidelines/allow_free_species_rhythmic_values.rb +80 -0
  63. data/lib/head_music/style/guidelines/always_move.rb +14 -3
  64. data/lib/head_music/style/guidelines/bar_count.rb +103 -0
  65. data/lib/head_music/style/guidelines/clausula_vera.rb +147 -0
  66. data/lib/head_music/style/guidelines/consonant_downbeats.rb +9 -6
  67. data/lib/head_music/style/guidelines/dissonance_figure_detection.rb +12 -70
  68. data/lib/head_music/style/guidelines/embellished_suspension_treatment.rb +2 -4
  69. data/lib/head_music/style/guidelines/free_dissonance_treatment.rb +157 -0
  70. data/lib/head_music/style/guidelines/independent_textures.rb +49 -0
  71. data/lib/head_music/style/guidelines/mix_species_textures.rb +4 -46
  72. data/lib/head_music/style/guidelines/no_parallel_perfect_across_barline.rb +2 -2
  73. data/lib/head_music/style/guides/composite_guide.rb +35 -4
  74. data/lib/head_music/style/guides/free_species_harmony.rb +29 -0
  75. data/lib/head_music/style/guides/free_species_melody.rb +27 -0
  76. data/lib/head_music/version.rb +1 -1
  77. data/lib/head_music.rb +10 -0
  78. data/user-stories/backlog/eighteenth-century-two-voice-counterpoint-guide.md +46 -0
  79. data/user-stories/backlog/fifth-species-published-examples.md +60 -0
  80. data/user-stories/backlog/free-species-translations.md +35 -0
  81. data/user-stories/backlog/free-species-with-imitation-guide.md +79 -0
  82. data/user-stories/backlog/free-species-with-sequence-guide.md +83 -0
  83. data/user-stories/done/banjo-notation-transpositions.md +369 -0
  84. data/user-stories/done/faster-test-suite.md +289 -0
  85. data/user-stories/done/free-species-guide.md +254 -0
  86. data/user-stories/done/lilypond-transposition-round-trip.md +330 -0
  87. data/user-stories/done/musicxml-instrument-fallback.md +468 -0
  88. data/user-stories/index.html +40 -0
  89. metadata +27 -2
@@ -193,6 +193,7 @@ es:
193
193
  hi-hat: charles
194
194
  high_tom: tom agudo
195
195
  horn: corno
196
+ irish_tenor_banjo: banjo tenor irlandés
196
197
  kettledrum: timbal
197
198
  kick_drum: bombo
198
199
  lute: laúd
@@ -255,6 +256,7 @@ es:
255
256
  tambourine: pandereta
256
257
  temple_blocks: bloques de templo
257
258
  tenor: tenor
259
+ tenor_banjo: banjo tenor
258
260
  tenor_drum: tambor tenor
259
261
  tenor_recorder: flauta dulce tenor
260
262
  tenor_saxophone: saxofón tenor
@@ -474,6 +476,12 @@ es:
474
476
  # por tanto en minuscula.
475
477
  style:
476
478
  guidelines:
479
+ allow_free_species_rhythmic_values:
480
+ instruction: "Escribir en redondas, blancas, negras y corcheas conjuntas apareadas en tiempos débiles."
481
+ instruction_with_dotted_rhythms: "Escribir en redondas, blancas, negras y corcheas conjuntas apareadas en tiempos débiles; una blanca o una redonda puede llevar puntillo, y una negra con puntillo puede ir seguida de una sola corchea que avance por grado conjunto."
482
+ violations:
483
+ default: "Emplear solo redondas, blancas, negras y corcheas conjuntas apareadas en tiempos débiles."
484
+ with_dotted_rhythms: "Emplear solo redondas, blancas, negras y corcheas conjuntas apareadas en tiempos débiles, blancas y redondas con puntillo, y una negra con puntillo seguida de una sola corchea que avance por grado conjunto."
477
485
  allow_fifth_species_rhythmic_values:
478
486
  instruction: "Escribir en blancas, negras y corcheas conjuntas apareadas en tiempos débiles, reservando la redonda para el compás final."
479
487
  violations:
@@ -200,6 +200,7 @@ fr:
200
200
  hi-hat: charleston
201
201
  high_tom: tom aigu
202
202
  horn: cor
203
+ irish_tenor_banjo: banjo ténor irlandais
203
204
  kettledrum: timbale
204
205
  kick_drum: grosse caisse
205
206
  lute: luth
@@ -261,6 +262,7 @@ fr:
261
262
  tambourine: tambourin
262
263
  temple_blocks: blocs de temple
263
264
  tenor: ténor
265
+ tenor_banjo: banjo ténor
264
266
  tenor_drum: tambour ténor
265
267
  tenor_recorder: flûte à bec ténor
266
268
  tenor_saxophone: saxophone ténor
@@ -484,6 +486,12 @@ fr:
484
486
  # commence donc en minuscule.
485
487
  style:
486
488
  guidelines:
489
+ allow_free_species_rhythmic_values:
490
+ instruction: "Écrire en rondes, blanches, noires et croches conjointes appariées sur les temps faibles."
491
+ instruction_with_dotted_rhythms: "Écrire en rondes, blanches, noires et croches conjointes appariées sur les temps faibles. Une blanche ou une ronde peut être pointée, et une noire pointée peut être suivie d'une seule croche qui avance par degré conjoint."
492
+ violations:
493
+ default: "N'employer que des rondes, des blanches, des noires et des croches conjointes appariées sur les temps faibles."
494
+ with_dotted_rhythms: "N'employer que des rondes, des blanches, des noires et des croches conjointes appariées sur les temps faibles, des blanches et des rondes pointées, et une noire pointée suivie d'une seule croche qui avance par degré conjoint."
487
495
  allow_fifth_species_rhythmic_values:
488
496
  instruction: "Écrire en blanches, noires et croches conjointes appariées sur les temps faibles, en réservant la ronde à la mesure finale."
489
497
  violations:
@@ -195,6 +195,7 @@ it:
195
195
  hi-hat: hi-hat
196
196
  high_tom: tom acuto
197
197
  horn: corno
198
+ irish_tenor_banjo: banjo tenore irlandese
198
199
  kettledrum: timpano
199
200
  kick_drum: grancassa
200
201
  lute: liuto
@@ -254,6 +255,7 @@ it:
254
255
  tambourine: tamburello
255
256
  temple_blocks: blocchi di legno
256
257
  tenor: tenore
258
+ tenor_banjo: banjo tenore
257
259
  tenor_drum: tamburo tenore
258
260
  tenor_recorder: flauto dolce tenore
259
261
  tenor_saxophone: sassofono tenore
@@ -472,6 +474,12 @@ it:
472
474
  # quindi in minuscolo.
473
475
  style:
474
476
  guidelines:
477
+ allow_free_species_rhythmic_values:
478
+ instruction: "Scrivere in semibrevi, minime, semiminime e crome congiunte appaiate sui tempi deboli."
479
+ instruction_with_dotted_rhythms: "Scrivere in semibrevi, minime, semiminime e crome congiunte appaiate sui tempi deboli; una minima o una semibreve può essere puntata, e una semiminima puntata può essere seguita da una sola croma che proceda per grado congiunto."
480
+ violations:
481
+ default: "Usare solo semibrevi, minime, semiminime e crome congiunte appaiate sui tempi deboli."
482
+ with_dotted_rhythms: "Usare solo semibrevi, minime, semiminime e crome congiunte appaiate sui tempi deboli, minime e semibrevi puntate, e una semiminima puntata seguita da una sola croma che proceda per grado congiunto."
475
483
  allow_fifth_species_rhythmic_values:
476
484
  instruction: "Scrivere in minime, semiminime e crome congiunte appaiate sui tempi deboli, riservando la semibreve alla battuta finale."
477
485
  violations:
@@ -141,6 +141,7 @@ ru:
141
141
  hi-hat: хай-хет
142
142
  high_tom: том высокий
143
143
  horn: валторна
144
+ irish_tenor_banjo: ирландское тенор-банджо
144
145
  kettledrum: тимпан
145
146
  kick_drum: бас-барабан
146
147
  lute: лютня
@@ -201,6 +202,7 @@ ru:
201
202
  tambourine: бубен
202
203
  temple_blocks: храмовые блоки
203
204
  tenor: тенор
205
+ tenor_banjo: тенор-банджо
204
206
  tenor_drum: теноровый барабан
205
207
  tenor_recorder: теноровая флейта
206
208
  tenor_saxophone: тенор-саксофон
@@ -448,6 +450,12 @@ ru:
448
450
  # со строчной.
449
451
  style:
450
452
  guidelines:
453
+ allow_free_species_rhythmic_values:
454
+ instruction: "Писать целыми, половинными, четвертными и парными плавными восьмыми на слабых долях."
455
+ instruction_with_dotted_rhythms: "Писать целыми, половинными, четвертными и парными плавными восьмыми на слабых долях; половинную или целую можно взять с точкой, а за четвертной с точкой может следовать одна восьмая, идущая дальше поступенно."
456
+ violations:
457
+ default: "Использовать только целые, половинные, четвертные и парные плавные восьмые на слабых долях."
458
+ with_dotted_rhythms: "Использовать только целые, половинные, четвертные и парные плавные восьмые на слабых долях, половинные и целые с точкой, а также четвертную с точкой, за которой следует одна восьмая, идущая дальше поступенно."
451
459
  allow_fifth_species_rhythmic_values:
452
460
  instruction: "Писать половинными, четвертными и парными плавными восьмыми на слабых долях, оставляя целую для последнего такта."
453
461
  violations:
@@ -20,7 +20,8 @@ module HeadMusic::MIDI
20
20
  71 => :bassoon,
21
21
  72 => :clarinet,
22
22
  74 => :flute,
23
- 75 => :recorder
23
+ 75 => :recorder,
24
+ 106 => :banjo
24
25
  }.freeze
25
26
 
26
27
  PINNED_PERCUSSION_KEYS = {
@@ -9,7 +9,17 @@ module HeadMusic::Named
9
9
  name = name.to_s
10
10
  @instances ||= {}
11
11
  key = HeadMusic::Utilities::HashKey.for(name)
12
- @instances[key] ||= new(name)
12
+ @instances.fetch(key) do
13
+ instance = new(name)
14
+ @instances[key] = instance if recognized?(instance)
15
+ instance
16
+ end
17
+ end
18
+
19
+ # A class whose lookups can fail says so here, so that a name matching
20
+ # nothing is not kept.
21
+ def recognized?(_instance)
22
+ true
13
23
  end
14
24
  end
15
25
 
@@ -11,6 +11,14 @@ module HeadMusic::Notation
11
11
  # +errors+ UnsupportedFeatureError.
12
12
  class ConcertTransposition
13
13
  Step = Data.define(:diatonic, :chromatic, :octaves) do
14
+ # The step that makes a written middle C sound the pitch given.
15
+ def self.sounding(pitch)
16
+ semitones = pitch.midi_note_number - 60
17
+ steps = PitchSpelling::STEPS.index(pitch.letter_name.to_s) + 7 * (pitch.register - 4)
18
+ octaves = semitones.abs.div(12) * (semitones <=> 0)
19
+ new(diatonic: steps - 7 * octaves, chromatic: semitones - 12 * octaves, octaves: octaves)
20
+ end
21
+
14
22
  def identity?
15
23
  diatonic.zero? && chromatic.zero? && octaves.zero?
16
24
  end
@@ -0,0 +1,62 @@
1
+ # A module for visual music notation
2
+ module HeadMusic::Notation
3
+ # Finds the catalog instrument an instrument, part, or staff name names, in
4
+ # the forms other programs write: "C Clarinet" for the catalog's "clarinet
5
+ # in C", "Trumpet in Bb" for "trumpet", and "Violin 1" for "violin".
6
+ module InstrumentNames
7
+ KEY = "[A-G](?:b|#|♭|♯|[- ]?flat|[- ]?sharp)?"
8
+ PLAYER_NUMBER = /\s+(?:\d+|[IVX]+)\.?\z/
9
+ LEADING_KEY = /\A(#{KEY})\s+(.+)\z/
10
+ IN_KEY = /\A(.+?)\s+in\s+(#{KEY})\z/i
11
+ ACCIDENTALS = {"b" => "♭", "#" => "♯", "♭" => "♭", "♯" => "♯", "flat" => "♭", "sharp" => "♯"}.freeze
12
+ SEMITONES = {"C" => 0, "D" => 2, "E" => 4, "F" => 5, "G" => 7, "A" => 9, "B" => 11}.freeze
13
+
14
+ module_function
15
+
16
+ def instrument(name)
17
+ name = name.to_s.strip
18
+ return if name.empty?
19
+
20
+ get(name) || normalized(name.sub(PLAYER_NUMBER, ""))
21
+ end
22
+
23
+ def normalized(name)
24
+ base, key = split(name)
25
+ return get(base) unless key
26
+
27
+ get("#{base} in #{key}") || in_own_key(get(base), key)
28
+ end
29
+
30
+ def split(name)
31
+ in_key = IN_KEY.match(name)
32
+ return [in_key[1], spelled(in_key[2])] if in_key
33
+
34
+ leading_key = LEADING_KEY.match(name)
35
+ leading_key ? [leading_key[2], spelled(leading_key[1])] : [name, nil]
36
+ end
37
+
38
+ def spelled(key)
39
+ key[0].upcase + ACCIDENTALS.fetch(key[1..].downcase.delete("- "), "")
40
+ end
41
+
42
+ # The catalog names an instrument in its usual key without the key, as
43
+ # "trumpet" for the trumpet in B♭. An instrument's key is where its
44
+ # written C sounds.
45
+ def in_own_key(instrument, key)
46
+ sounding = SEMITONES.fetch(key[0]) + {"♭" => -1, "♯" => 1}.fetch(key[1], 0)
47
+ instrument if instrument && (instrument.sounding_transposition - sounding) % 12 == 0
48
+ end
49
+
50
+ # "Clarinet" written to sound a minor third low is the clarinet in A.
51
+ def variant(instrument, semitones)
52
+ return instrument if semitones.nil? || instrument.sounding_transposition == semitones
53
+
54
+ variants = HeadMusic::Instruments::Instrument.all.select { |variant| variant.parent_key.to_s == instrument.name_key.to_s }
55
+ variants.find { |variant| variant.sounding_transposition == semitones } || instrument
56
+ end
57
+
58
+ def get(name)
59
+ HeadMusic::Instruments::Instrument.get(name)
60
+ end
61
+ end
62
+ end
@@ -70,10 +70,14 @@ module HeadMusic::Notation::LilyPond
70
70
  # \new Dynamics after it governs.
71
71
  def read_staff_or_voice(opener, type, name, context)
72
72
  streams_before = document.streams.dup
73
+ instrument_name = with_role
73
74
  child = VoiceContext.new(
74
- document, role(context, type, name), explicit: true, group_staff: group_staff(context, type, name)
75
+ document, role(context, type, name, instrument_name), explicit: true,
76
+ group_staff: group_staff(context, type, name), staff: ungrouped_staff(context, type, instrument_name)
75
77
  )
78
+ child.stream.voice_name = instrument_name || name if type.lexeme == "Voice"
76
79
  child.stream.numeric_time_signature = context.stream.numeric_time_signature
80
+ child.stream.change_transposition(context.stream.transposition, nil) if context.stream.transposition
77
81
  music.nested(opener) { music.read_expression(child) }
78
82
  child.close
79
83
  context.preceding_staff = document.streams - streams_before if type.lexeme == "Staff"
@@ -101,8 +105,14 @@ module HeadMusic::Notation::LilyPond
101
105
  # A Voice with no name of its own belongs to the staff that holds it. In
102
106
  # a staff group, where staves carry no instrument name, a Voice's context
103
107
  # name is its role.
104
- def role(context, type, name)
105
- with_role || (voice_role(context, name) if type.lexeme == "Voice")
108
+ def role(context, type, name, instrument_name)
109
+ instrument_name || (voice_role(context, name) if type.lexeme == "Voice")
110
+ end
111
+
112
+ def ungrouped_staff(context, type, instrument_name)
113
+ return context.staff if type.lexeme == "Voice"
114
+
115
+ document.add_staff(instrument_name) unless context.group
106
116
  end
107
117
 
108
118
  def voice_role(context, name)
@@ -10,6 +10,9 @@ module HeadMusic::Notation::LilyPond
10
10
  # order. A staff's name is what a \change Staff command refers to.
11
11
  Group = Struct.new(:bracket, :staves)
12
12
  GroupStaff = Struct.new(:group, :name)
13
+ # A \new Staff outside a group, which is one part however many voices
14
+ # it holds. Its name is its instrumentName.
15
+ Staff = Struct.new(:name)
13
16
 
14
17
  attr_accessor :title, :composer
15
18
  attr_reader :streams, :groups, :dynamics_streams
@@ -28,6 +31,15 @@ module HeadMusic::Notation::LilyPond
28
31
  GroupStaff.new(group, name).tap { |staff| group.staves << staff }
29
32
  end
30
33
 
34
+ def add_staff(name)
35
+ Staff.new(name)
36
+ end
37
+
38
+ # The voice streams read inside an ungrouped staff.
39
+ def staff_streams(staff)
40
+ streams.select { |stream| stream.staff.equal?(staff) }
41
+ end
42
+
31
43
  def add_stream(role = nil)
32
44
  stream = VoiceStream.new(role)
33
45
  @streams << stream
@@ -48,6 +60,12 @@ module HeadMusic::Notation::LilyPond
48
60
  stream
49
61
  end
50
62
 
63
+ # \transposition is a Staff property, so each voice of a staff takes the
64
+ # changes the others make.
65
+ def resolve_transpositions
66
+ streams.each { |stream| stream.resolve_transpositions(foreign_changes(stream)) }
67
+ end
68
+
51
69
  def first_key_signature
52
70
  leading_event(:key)&.key_signature
53
71
  end
@@ -64,6 +82,13 @@ module HeadMusic::Notation::LilyPond
64
82
 
65
83
  private
66
84
 
85
+ def foreign_changes(stream)
86
+ return [] unless stream.staff
87
+
88
+ changes = staff_streams(stream.staff).reject { |other| other.equal?(stream) }.flat_map(&:transposition_changes)
89
+ changes.each_with_index.sort_by { |(elapsed, _step), index| [elapsed, index] }.map(&:first)
90
+ end
91
+
67
92
  # The first command of a kind that precedes any music in its stream,
68
93
  # taken from the first stream that has one.
69
94
  def leading_event(kind)
@@ -48,6 +48,8 @@ module HeadMusic::Notation::LilyPond
48
48
  streams = document.streams
49
49
  raise ParseError, "LilyPond input contains no music" if streams.empty?
50
50
 
51
+ document.resolve_transpositions
52
+
51
53
  flow = HeadMusic::Content::Flow.new(
52
54
  name: document.title, composer: document.composer,
53
55
  key_signature: document.first_key_signature, meter: document.first_meter, tempo: document.first_tempo
@@ -7,6 +7,9 @@ module HeadMusic::Notation::LilyPond
7
7
  #
8
8
  # \appoggiatura and \acciaccatura imply a slur from the first grace note to
9
9
  # the main note, unless the first grace note opens one of its own.
10
+ #
11
+ # A \transposition among them holds from the grace note after it, or from
12
+ # the main note when none follows.
10
13
  class GraceReader
11
14
  # Each command's [slashed, implied slur].
12
15
  COMMANDS_BY_NAME = {
@@ -17,7 +20,11 @@ module HeadMusic::Notation::LilyPond
17
20
  IMPLIED_SLUR_ID = :grace
18
21
  MUSIC_TYPES = %i[open_brace note open_chord].freeze
19
22
 
20
- Grace = Data.define(:pitches, :rhythmic_value, :slashed, :tied, :marks) do
23
+ Grace = Data.define(:pitches, :rhythmic_value, :slashed, :tied, :marks, :transposition) do
24
+ def initialize(transposition: nil, **)
25
+ super
26
+ end
27
+
21
28
  # A tie holds only into a note of the same pitches.
22
29
  def before(follower)
23
30
  with(tied: tied && pitches.sort == follower.sort)
@@ -30,10 +37,24 @@ module HeadMusic::Notation::LilyPond
30
37
  end
31
38
  end
32
39
 
33
- # The grace notes waiting for their main note.
34
- Graces = Data.define(:graces, :implied_slur) do
40
+ # The grace notes waiting for their main note, and the transposition
41
+ # that follows the last of them.
42
+ Graces = Data.define(:graces, :implied_slur, :transposition) do
43
+ def initialize(transposition: nil, **)
44
+ super
45
+ end
46
+
35
47
  def +(other)
36
- with(graces: graces + other.graces, implied_slur: implied_slur || other.implied_slur)
48
+ following = other.graces
49
+ following = [following.first.with(transposition: following.first.transposition || transposition), *following.drop(1)] if following.any?
50
+ with(
51
+ graces: graces + following, implied_slur: implied_slur || other.implied_slur,
52
+ transposition: other.transposition || (transposition if following.empty?)
53
+ )
54
+ end
55
+
56
+ def last_transposition
57
+ transposition || graces.filter_map(&:transposition).last
37
58
  end
38
59
 
39
60
  def before(pitches)
@@ -72,12 +93,13 @@ module HeadMusic::Notation::LilyPond
72
93
  end
73
94
  end
74
95
 
75
- NONE = Graces.new(graces: [], implied_slur: false)
96
+ NONE = Graces.new(graces: [], implied_slur: false, transposition: nil)
76
97
 
77
98
  def initialize(cursor, items)
78
99
  @cursor = cursor
79
100
  @items = items
80
101
  @mark_reader = MarkReader.new(cursor)
102
+ @setting_reader = SettingReader.new(cursor)
81
103
  end
82
104
 
83
105
  # The grace notes the command at the cursor writes, or the music after a
@@ -85,13 +107,14 @@ module HeadMusic::Notation::LilyPond
85
107
  def read(command = cursor.advance)
86
108
  @slashed, implied_slur = COMMANDS_BY_NAME.fetch(command.lexeme, [false, false])
87
109
  @graces = []
110
+ @transposition = nil
88
111
  read_music(command)
89
- Graces.new(graces: @graces, implied_slur: implied_slur)
112
+ Graces.new(graces: @graces, implied_slur: implied_slur, transposition: @transposition)
90
113
  end
91
114
 
92
115
  private
93
116
 
94
- attr_reader :cursor, :items, :mark_reader
117
+ attr_reader :cursor, :items, :mark_reader, :setting_reader
95
118
 
96
119
  def read_music(command)
97
120
  token = cursor.peek
@@ -115,13 +138,19 @@ module HeadMusic::Notation::LilyPond
115
138
  when :open_brace then read_braces
116
139
  when :bar_check then cursor.advance
117
140
  when :tuplet then raise cursor.unsupported("Tuplets inside grace music are not supported", token)
118
- else raise cursor.unexpected(token, %(Unexpected token "#{token.lexeme}" inside grace music))
141
+ else
142
+ return @transposition = setting_reader.read_transposition_step if token.type == :command && token.lexeme == "transposition"
143
+
144
+ raise cursor.unexpected(token, %(Unexpected token "#{token.lexeme}" inside grace music))
119
145
  end
120
146
  end
121
147
 
122
148
  def read_grace
123
149
  pitches, rhythmic_value, _line, marks, tie = items.read_marked_sounds
124
- @graces << Grace.new(pitches: pitches, rhythmic_value: rhythmic_value, slashed: @slashed, tied: !tie.nil?, marks: marks)
150
+ @graces << Grace.new(
151
+ pitches: pitches, rhythmic_value: rhythmic_value, slashed: @slashed, tied: !tie.nil?, marks: marks, transposition: @transposition
152
+ )
153
+ @transposition = nil
125
154
  end
126
155
 
127
156
  def skip_silence
@@ -1,9 +1,11 @@
1
1
  # A namespace for LilyPond-notation parsing helpers
2
2
  module HeadMusic::Notation::LilyPond
3
3
  # The parts, staves, and voices of a flow that a document's streams go to.
4
- # A stream outside a staff group is a voice, and a part, of its own. A
5
- # staff group is one part, whose staff system holds the group's staves in
6
- # order.
4
+ # A staff of several voices is one part, whose player its name names, and
5
+ # whose instrument too where the catalog knows it, and whose voices' names
6
+ # are their roles; a lone voice outside a staff
7
+ # group is a part of its own. A staff group is one part, whose staff system
8
+ # holds the group's staves in order.
7
9
  class PartLayout
8
10
  def initialize(flow, document)
9
11
  @flow = flow
@@ -12,6 +14,7 @@ module HeadMusic::Notation::LilyPond
12
14
  @parts_by_group = {}.compare_by_identity
13
15
  @staves_by_group_staff = {}.compare_by_identity
14
16
  @staves_by_name = {}.compare_by_identity
17
+ @parts_by_staff = {}.compare_by_identity
15
18
  end
16
19
 
17
20
  # A silent staff keeps its place in the system without a voice, since
@@ -33,20 +36,35 @@ module HeadMusic::Notation::LilyPond
33
36
  staves_by_name.fetch(part, {})[name]
34
37
  end
35
38
 
36
- # A staff outside a group may hold several voices, each read as a part of
37
- # its own, so its dynamics go to each of them.
38
39
  def dynamics_parts(target)
39
40
  return [parts_by_group[target]].compact if target.is_a?(Document::Group)
40
41
 
41
- target.filter_map { |stream| voices_by_stream[stream]&.part }
42
+ target.filter_map { |stream| voices_by_stream[stream]&.part }.uniq
42
43
  end
43
44
 
44
45
  private
45
46
 
46
- attr_reader :flow, :document, :voices_by_stream, :parts_by_group, :staves_by_group_staff, :staves_by_name
47
+ attr_reader :flow, :document, :voices_by_stream, :parts_by_group, :staves_by_group_staff, :staves_by_name, :parts_by_staff
47
48
 
48
49
  def ungrouped_voice(stream)
49
- voices_by_stream[stream] = flow.add_voice(role: stream.role)
50
+ streams = stream.staff ? document.staff_streams(stream.staff) : [stream]
51
+ return voices_by_stream[stream] = flow.add_voice(role: stream.role) if streams.one?
52
+
53
+ part = parts_by_staff[stream.staff] ||= flow.add_part(player: staff_player(stream.staff), instrument: staff_instrument(stream.staff, streams.first))
54
+ voices_by_stream[stream] = part.add_voice(role: stream.voice_name)
55
+ end
56
+
57
+ # A staff's name is its player's, as a MusicXML part name is, whether or
58
+ # not it also names an instrument.
59
+ def staff_player(staff)
60
+ staff.name && HeadMusic::Content::Player.new(name: staff.name)
61
+ end
62
+
63
+ # The name may say only "Clarinet", leaving the opening \transposition to
64
+ # say which one.
65
+ def staff_instrument(staff, first_stream)
66
+ instrument = HeadMusic::Notation::InstrumentNames.instrument(staff.name)
67
+ instrument && HeadMusic::Notation::InstrumentNames.variant(instrument, first_stream.opening_transposition&.semitones)
50
68
  end
51
69
 
52
70
  def part_for(group)
@@ -6,6 +6,8 @@ module HeadMusic::Notation::LilyPond
6
6
  # on unmappable keys, durations, or alterations, so a RenderPlan that builds successfully
7
7
  # cannot fail assembly on those grounds.
8
8
  class RenderPlan < HeadMusic::Notation::RenderPlan
9
+ MIDDLE_C = "C4"
10
+
9
11
  def tokens_by_segment
10
12
  @tokens_by_segment ||= flow.voices.each_with_object({}) { |voice, tokens| tokens.merge!(segment_tokens(voice).to_h) }
11
13
  end
@@ -47,6 +49,25 @@ module HeadMusic::Notation::LilyPond
47
49
  end
48
50
  end
49
51
 
52
+ # Where a written c' sounds, restated wherever the part's instrument
53
+ # changes it, back to c' for an instrument in C.
54
+ def transposition_changes(part)
55
+ return {} unless transposed? && part
56
+
57
+ @transposition_changes ||= {}.compare_by_identity
58
+ @transposition_changes[part] ||= part.instrument_changes.keys
59
+ .select { |bar_number| bar_numbers.cover?(bar_number) && bar_number > bar_numbers.first }
60
+ .filter_map { |bar_number|
61
+ command = transposition_command(part.instrument_at(bar_number))
62
+ [bar_number, command] unless command == transposition_command(part.instrument_at(bar_number - 1))
63
+ }.to_h
64
+ end
65
+
66
+ def transposition_command(instrument)
67
+ sounding = HeadMusic::Content::Layout::Transposition.for(instrument).sounding(MIDDLE_C)
68
+ "\\transposition #{PitchWriter.token(sounding)}"
69
+ end
70
+
50
71
  # Whether a part has a \new Dynamics to write.
51
72
  def dynamics?(part)
52
73
  !part.dynamic_events.empty? || part.spans.any?(&:hairpin?)
@@ -1,6 +1,6 @@
1
1
  # A namespace for LilyPond-notation parsing helpers
2
2
  module HeadMusic::Notation::LilyPond
3
- # Reads the \key, \time, \clef, and \tempo commands among a context's
3
+ # Reads the \key, \time, \clef, \tempo, and \transposition commands among a context's
4
4
  # music. With no stream to change, as in a \new Dynamics, which only
5
5
  # repeats the staves' settings, a setting is read for its syntax alone.
6
6
  #
@@ -9,7 +9,7 @@ module HeadMusic::Notation::LilyPond
9
9
  # again after \defaultTimeSignature.
10
10
  class SettingReader
11
11
  TIME_SIGNATURE_STYLES = {"numericTimeSignature" => true, "defaultTimeSignature" => false}.freeze
12
- COMMANDS = (%w[key time clef tempo] + TIME_SIGNATURE_STYLES.keys).freeze
12
+ COMMANDS = (%w[key time clef tempo transposition] + TIME_SIGNATURE_STYLES.keys).freeze
13
13
  SYMBOLS_BY_METER = {"4/4" => :common, "2/2" => :cut}.freeze
14
14
 
15
15
  def initialize(cursor)
@@ -24,14 +24,31 @@ module HeadMusic::Notation::LilyPond
24
24
  when "time" then read_time(command, stream)
25
25
  when "clef" then read_clef(command, stream)
26
26
  when "tempo" then read_tempo(command, stream)
27
+ when "transposition" then read_transposition(command, stream)
27
28
  else stream&.numeric_time_signature = TIME_SIGNATURE_STYLES.fetch(command.lexeme)
28
29
  end
29
30
  end
30
31
 
32
+ # Its pitch is absolute even inside \relative, and leaves the relative
33
+ # reference alone.
34
+ def read_transposition_step(command = cursor.advance)
35
+ token = cursor.advance
36
+ unless token&.type == :note && token.duration.nil? && token.multiplier.nil?
37
+ raise cursor.error("\\transposition expects a pitch", token || command)
38
+ end
39
+
40
+ HeadMusic::Notation::ConcertTransposition::Step.sounding(PitchReader.absolute.pitch(token))
41
+ end
42
+
31
43
  private
32
44
 
33
45
  attr_reader :cursor, :tempo_reader
34
46
 
47
+ def read_transposition(command, stream)
48
+ step = read_transposition_step(command)
49
+ stream&.change_transposition(step, command.line)
50
+ end
51
+
35
52
  def read_key(command, stream)
36
53
  pitch_token = cursor.advance
37
54
  mode_token = cursor.advance