NWC2MusicXML/Score.pm

filter: Statementstmt 97.5% 118 / 121 Branchbran 82.5% 33 / 40 Conditioncond 67.6% 23 / 34 MC/DCmcdc 38.8% 7 / 18 Subroutinesub 100% 26 / 26 Podpod 91.6% 11 / 12 totaltotal 86.8% 218 / 251 CC 39 SCAR 27.5
CC
39
Cov
89%
validate
32.2
_ts_to_rational
4.1
add_staff
4.0
CRAP 15.6
« NWC2MusicXML/MusicXML.pm ↑ Summary NWC2MusicXML/Parser.pm »
1 package Music::NWC2MusicXML::Score;
2  
3 15 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 15 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 15 our $VERSION = '0.003.0';
7  
8 15 ▶use Carp qw(croak carp);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 15 ▶use List::Util qw(any);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 15 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 15 ▶use Scalar::Util qw(blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
12 15 ▶use Params::Validate::Strict qw(validate_strict);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 15 ▶use Params::Get;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 15 ▶use Music::NWC2MusicXML::Staff;
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16 15 Readonly::Hash my %MESSAGES => (
17 error_bad_staff => 'add_staff: argument must be a Music::NWC2MusicXML::Staff, got: %s',
18 error_no_staves => 'Score contains no staves',
19 error_internal => 'Internal error: %s',
20 warn_empty_staff => "Staff '%s' has no events",
21 warn_bar_duration => "Staff '%s', measure %d: duration %s quarter-notes does not match time signature (%s expected)",
22 warn_unmatched_tie => "Staff '%s': unterminated tie from position '%s'",
23 warn_unclosed_slur => "Staff '%s': slur arc not closed at end of staff",
24 );
25  
26 # Recognised SongInfo keys that map to MusicXML metadata elements
27 15 Readonly::Array my @SONGINFO_KEYS => qw(
28 Title
29 Author
30 Lyricist
31 Copyright
32 Copyright1
33 Copyright2
34 Comments
35 );
36  
37 =head1 NAME
38  
39 Music::NWC2MusicXML::Score - Internal representation of a complete NWC score.
40  
41 =head1 VERSION
42  
43 0.003.0
44  
45 =head1 SYNOPSIS
46  
47 use Music::NWC2MusicXML::Score;
48  
49 my $score = Music::NWC2MusicXML::Score->new(
50 metadata => { Title => 'To a Pilgrim', Author => 'Trad, Arr Nigel Horne' },
51 page_setup => { StaffSize => 16, Zoom => 3 },
52 );
53  
54 $score->add_staff($staff_object);
55 my $staves = $score->staves;
56  
57 =head1 DESCRIPTION
58  
59 C<Music::NWC2MusicXML::Score> is the root of the internal representation tree.
60 It holds:
61  
62 =over 4
63  
64 =item * B<metadata> -- SongInfo fields (Title, Author, Lyricist, Copyright, Comments).
65  
66 =item * B<page_setup> -- PgSetup fields, retained but largely informational.
67  
68 =item * B<properties> -- additional score-level NWC properties.
69  
70 =item * B<staves> -- ordered list of C<Music::NWC2MusicXML::Staff> objects.
71  
72 =back
73  
74 This class is MusicXML-agnostic; it describes the musical content in NWC
75 terms. The C<Music::NWC2MusicXML::MusicXML> generator translates it to XML.
76  
77 =cut
78  
79 297 ▶sub new {
Subroutine new: called CC=2 SCAR=7.0
Pod undocumented
80 297 my ($class, %input) = @_;
81 297 my $args = validate_strict(
82 schema => {
83 metadata => { type => 'hashref', optional => 1, default => {} },
84 page_setup => { type => 'hashref', optional => 1, default => {} },
85 properties => { type => 'hashref', optional => 1, default => {} },
86 nwc_version => { type => 'scalar', optional => 1 },
87 },
88 input => \%input,
89 );
90 296 ▶ croak $@ unless defined $args;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args 0 296 296
91  
92 my $self = bless {
93 _metadata => $args->{metadata},
94 _page_setup => $args->{page_setup},
95 _properties => $args->{properties},
96 _nwc_version => $args->{nwc_version},
97 296 _staves => [],
98 _fonts => [],
99 }, $class;
100  
101 296 return $self;
102 }
103  
104 # ---------------------------------------------------------------------------
105 # Accessors
106 # ---------------------------------------------------------------------------
107  
108 =head2 metadata
109  
110 Return the metadata hashref.
111  
112 Keys correspond to NWC SongInfo field names: C<Title>, C<Author>,
113 C<Lyricist>, C<Copyright>, C<Comments>.
114  
115 =head3 Returns
116  
117 Hashref.
118  
119 =cut
120  
121 558 ▶sub metadata { return $_[0]->{_metadata} }
Subroutine metadata: called CC=1 SCAR=0.0
Pod documented
122  
123 =head2 page_setup
124  
125 Return the page-setup hashref (NWC PgSetup fields).
126  
127 =cut
128  
129 245 ▶sub page_setup { return $_[0]->{_page_setup} }
Subroutine page_setup: called CC=1 SCAR=0.0
Pod documented
130  
131 =head2 properties
132  
133 Return additional score-level properties hashref.
134  
135 =cut
136  
137 2 ▶sub properties { return $_[0]->{_properties} }
Subroutine properties: called CC=1 SCAR=0.0
Pod documented
138  
139 =head2 nwc_version
140  
141 Return the NWC version string extracted from the NWCTXT header
142 (e.g. C<2.751>), or undef if not available.
143  
144 =cut
145  
146 13 ▶sub nwc_version { return $_[0]->{_nwc_version} }
Subroutine nwc_version: called CC=1 SCAR=0.0
Pod documented
147  
148 =head2 fonts
149  
150 Return the arrayref of font descriptors parsed from NWC Font records.
151 Each entry is a hashref with keys: style, typeface, size, bold, italic.
152  
153 =cut
154  
155 172 ▶sub fonts { return $_[0]->{_fonts} }
Subroutine fonts: called CC=1 SCAR=0.0
Pod documented
156  
157 =head2 set_metadata_field
158  
159 Set a single metadata field.
160  
161 =head3 Arguments
162  
163 =over 4
164  
165 =item C<$key> -- field name (e.g. C<Title>).
166  
167 =item C<$value> -- string value.
168  
169 =back
170  
171 =head3 Returns
172  
173 C<$self>.
174  
175 =cut
176  
177 265 ▶sub set_metadata_field {
Subroutine set_metadata_field: called CC=1 SCAR=0.0
Pod documented
178 265 my ($self, $key, $value) = @_;
179 265 $self->{_metadata}{$key} = $value;
180 265 return $self;
181 }
182  
183 # ---------------------------------------------------------------------------
184 # Staff management
185 # ---------------------------------------------------------------------------
186  
187 =head2 add_staff
188  
189 Append a C<Music::NWC2MusicXML::Staff> to the score's staff list.
190  
191 =head3 Purpose
192  
193 Called by the parser each time it encounters an C<AddStaff> record; the staff
194 object is populated with subsequent per-staff records and then stays in the
195 list for MusicXML generation.
196  
197 =head3 Arguments
198  
199 =over 4
200  
201 =item C<$staff> -- a blessed C<Music::NWC2MusicXML::Staff> object (required).
202  
203 =back
204  
205 =head3 Returns
206  
207 C<$self> (for chaining).
208  
209 =head3 Side Effects
210  
211 Appends to C<_staves>.
212  
213 =head3 Usage Example
214  
215 $score->add_staff(
216 Music::NWC2MusicXML::Staff->new(name => 'Violin I')
217 );
218  
219 =head3 API SPECIFICATION
220  
221 =head4 Input
222  
223 $staff : Music::NWC2MusicXML::Staff (required)
224  
225 =head4 Output
226  
227 $self (Music::NWC2MusicXML::Score)
228  
229 =head3 MESSAGES
230  
231 | Code | Meaning | Resolution |
232 |----------------|----------------------------------|------------------------------|
233 | error_bad_staff| Argument is not a Staff object | Construct Staff before adding |
234  
235 =head3 FORMAL SPECIFICATION
236  
237 [AddStaff]
238 DeltaScore
239 staff? : Staff
240 ---------
241 staves' = staves ^ <staff?>
242  
243 (placeholder -- populate with Z calculus as implementation matures)
244  
245 =cut
246  
247 368 ▶sub add_staff {
Subroutine add_staff: called CC=4 SCAR=13.9
Pod documented
248 368 my ($self, $staff) = @_;
249 368 ▶ croak _fmt_msg('error_bad_staff', ref($staff) // 'SCALAR')
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($staff) and $staff->isa("Music::NWC2MusicXML::Staff") 10 358 368
Condition80%4/5
builtin::blessed($staff) and $staff->isa("Music::NWC2MusicXML::Staff")
!ll&&!rl&&r
82358
ref $staff // "SCALAR"
l!l
100
MC/DC100%2/2
builtin::blessed($staff) and $staff->isa("Music::NWC2MusicXML::Staff")
builtin::blessed($staff) $staff->isa("Music::NWC2MusicXML::Staff")
MC/DC0%0/1
ref $staff // "SCALAR"
ref $staff
Truth table100%3/3
A and B
A= builtin::blessed($staff)B= $staff->isa("Music::NWC2MusicXML::Staff")
ABresult
0X0
100
111
Truth table50%1/2
A
A= ref $staff
Aresult
11
00
250 unless blessed($staff) && $staff->isa('Music::NWC2MusicXML::Staff');
251 358 push @{ $self->{_staves} }, $staff;
252 358 return $self;
253 }
254  
255 =head2 staves
256  
257 Return an arrayref of all C<Music::NWC2MusicXML::Staff> objects in score order.
258  
259 =head3 Returns
260  
261 Arrayref of C<Music::NWC2MusicXML::Staff>.
262  
263 =head3 API SPECIFICATION
264  
265 =head4 Input
266  
267 (none)
268  
269 =head4 Output
270  
271 ARRAYREF of Music::NWC2MusicXML::Staff
272  
273 =cut
274  
275 573 ▶sub staves {
Subroutine staves: called CC=1 SCAR=0.0
Pod documented
276 573 my ($self) = @_;
277 573 return $self->{_staves};
278 }
279  
280 =head2 current_staff
281  
282 Return the last staff appended (the one currently being populated by the
283 parser), or undef if no staves have been added.
284  
285 =cut
286  
287 184544 ▶sub current_staff {
Subroutine current_staff: called CC=1 SCAR=0.0
Pod documented
288 184544 my ($self) = @_;
289 184544 return $self->{_staves}[-1];
290 }
291  
292 =head2 staff_count
293  
294 Return the number of staves.
295  
296 =cut
297  
298 224 ▶sub staff_count {
Subroutine staff_count: called CC=1 SCAR=0.0
Pod documented
299 224 my ($self) = @_;
300 224 return scalar @{ $self->{_staves} };
301 }
302  
303 =head2 validate
304  
305 Perform consistency checks on the score structure. Called when
306 C<--validate> is passed on the command line.
307  
308 =head3 Purpose
309  
310 Checks that every staff has at least one event, that tie/slur relationships
311 are consistent, and that measure durations match the current time signature.
312  
313 =head3 Returns
314  
315 Arrayref of diagnostic strings (empty on success).
316  
317 =head3 API SPECIFICATION
318  
319 =head4 Input
320  
321 (none)
322  
323 =head4 Output
324  
325 ARRAYREF of SCALAR (diagnostic messages)
326  
327 =head3 FORMAL SPECIFICATION
328  
329 [Validate]
330 score : Score
331 ---------
332 forall s : staves @ valid_staff(s)
333  
334 (placeholder)
335  
336 =cut
337  
338 9 ▶sub validate {
Subroutine validate: called CC=29 SCAR=34.7
Pod documented
339 9 my $self = $_[0];
340  
341 # Strategy: iterate staves; for each staff check that:
342 # - event list is non-empty
343 # - all Bar events divide time correctly per time signature
344 # - all Tie/Slur events have matching start/stop pairs
345 # Return all accumulated diagnostics rather than croaking on first failure.
346  
347 9 my @diagnostics;
348  
349 9 ▶ if ($self->staff_count == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->staff_count == 0) 4 5 9
350 4 push @diagnostics, _fmt_msg('error_no_staves');
351 4 return \@diagnostics;
352 }
353  
354 5 for my $staff (@{ $self->{_staves} }) {
355 10 ▶ my $sname = $staff->name // '(unnamed)';
Condition50%1/2
$staff->name // "(unnamed)"
l!l
100
MC/DC0%0/1
$staff->name // "(unnamed)"
$staff->name
Truth table50%1/2
A
A= $staff->name
Aresult
11
00
356  
357 10 ▶ if ($staff->event_count == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($staff->event_count == 0) 1 9 10
358 1 push @diagnostics, _fmt_msg('warn_empty_staff', $sname);
359 1 next;
360 }
361  
362 9 my %pending_tie; # pos_key => 1 for ties awaiting a stop
363 9 my $in_slur = 0; # 1 while inside an unclosed slur arc
364 9 my $bar_num = 1;
365 9 my ($acc_n, $acc_d) = (0, 1); # accumulated bar duration as a rational
366  
367 9 ▶ my $ts = $staff->initial_timesig // {};
Condition100%2/2
$staff->initial_timesig // {}
l!l
81
MC/DC100%1/1
$staff->initial_timesig // {}
$staff->initial_timesig
Truth table100%2/2
A
A= $staff->initial_timesig
Aresult
11
00
368 9 my ($exp_n, $exp_d) = _ts_to_rational($ts);
369  
370 9 for my $ev (@{ $staff->events }) {
371 6992 my $type = $ev->type;
372 6992 ▶ my $d = $ev->data // {};
Condition50%1/2
$ev->data // {}
l!l
69920
MC/DC0%0/1
$ev->data // {}
$ev->data
Truth table50%1/2
A
A= $ev->data
Aresult
11
00
373  
374 6992 ▶ if ($type eq 'TimeSig') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "TimeSig") 80 6912 6992
375 80 ($exp_n, $exp_d) = _ts_to_rational($d);
376 80 next;
377 }
378  
379 6912 ▶ if ($type eq 'Bar') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "Bar") 1556 5356 6912
380 1556 ▶ if ($acc_n > 0 && $exp_n > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($acc_n > 0 and $exp_n > 0) 0 1556 1556
Condition33%1/3
$acc_n > 0 and $exp_n > 0
!ll&&!rl&&r
155600
MC/DC0%0/2
$acc_n > 0 and $exp_n > 0
$acc_n > 0 $exp_n > 0
Truth table33%1/3
A and B
A= $acc_n > 0B= $exp_n > 0
ABresult
0X0
100
111
381 0 my ($cn, $cd) = _rat_reduce($acc_n, $acc_d);
382 0 my ($en, $ed) = _rat_reduce($exp_n, $exp_d);
383 0 ▶ push @diagnostics, _fmt_msg(
Branch: 1 branch
BranchTrueFalseTotal
unless $cn * $ed == $en * $cd 0 0 0
384 'warn_bar_duration', $sname, $bar_num,
385 "$cn/$cd", "$en/$ed",
386 ) unless $cn * $ed == $en * $cd;
387 }
388 1556 $bar_num++;
389 1556 ($acc_n, $acc_d) = (0, 1);
390 1556 next;
391 }
392  
393 5356 ▶ next unless $type eq 'Note' || $type eq 'Chord' || $type eq 'Rest';
Branch: 1 branch
BranchTrueFalseTotal
unless $type eq "Note" or $type eq "Chord" or $type eq "Rest" 138 5218 5356
Condition100%6/6
$type eq "Note" or $type eq "Chord" or $type eq "Rest"
l!l&&r!l&&!r
4409809138
$type eq "Note" or $type eq "Chord"
l!l&&r!l&&!r
3550859947
MC/DC100%3/3
$type eq "Note" or $type eq "Chord" or $type eq "Rest"
$type eq "Note" $type eq "Chord" $type eq "Rest"
Truth table100%4/4
A or B or C
A= $type eq "Note"B= $type eq "Chord"C= $type eq "Rest"
ABCresult
1XX1
01X1
0011
0000
394  
395 # Accumulate duration (grace notes contribute nothing)
396 5218 ▶ unless ($d->{is_grace}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($d->{"is_grace"}) 5218 0 5218
397 5218 ▶ my ($dn, $dd) = @{ $d->{duration} // [0, 1] };
Condition50%1/2
$d->{"duration"} // [0, 1]
l!l
05218
MC/DC0%0/1
$d->{"duration"} // [0, 1]
$d->{"duration"}
Truth table50%1/2
A
A= $d->{"duration"}
Aresult
11
00
398 5218 ($acc_n, $acc_d) = _rat_reduce(
399 $acc_n * $dd + $dn * $acc_d,
400 $acc_d * $dd,
401 );
402 }
403  
404 # Tie tracking (rests cannot be tied)
405 5218 ▶ unless ($type eq 'Rest') {
Branch: 1 branch
BranchTrueFalseTotal
unless ($type eq "Rest") 4409 809 5218
406 my @pos_strs = $type eq 'Chord'
407 859 ▶ ? @{ $d->{nwc_positions} // [] }
Condition50%2/4
$d->{"nwc_positions"} // []
l!l
8590
$d->{"nwc_pos"} // 0
l!l
35500
MC/DC0%0/1
$d->{"nwc_positions"} // []
$d->{"nwc_positions"}
MC/DC0%0/1
$d->{"nwc_pos"} // 0
$d->{"nwc_pos"}
Truth table50%1/2
A
A= $d->{"nwc_positions"}
Aresult
11
00
Truth table50%1/2
A
A= $d->{"nwc_pos"}
Aresult
11
00
408 4409 ▶ : ($d->{nwc_pos} // '0');
Branch: 1 branch
BranchTrueFalseTotal
$type eq 'Chord' ? : 859 3550 4409
409 4409 for my $ps (@pos_strs) {
410 5597 (my $pk = $ps) =~ s/\^\z//;
411 5597 delete $pending_tie{$pk}; # consume any pending stop
412 5597 ▶ $pending_tie{$pk} = 1 if $ps =~ /\^\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $ps =~ /\^\z/ 189 5408 5597
413 }
414 }
415  
416 # Slur tracking (rests are transparent to slur arcs)
417 5218 ▶ next if $type eq 'Rest';
Branch: 1 branch
BranchTrueFalseTotal
if $type eq "Rest" 809 4409 5218
418 4409 ▶ $in_slur = any { $_ eq 'Slur' } @{ $d->{articulations} // [] } ? 1 : 0;
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
@{$d->{'articulations'} // [];} ? : 1288 3121 4409
Condition50%1/2
$d->{"articulations"} // []
l!l
44090
MC/DC0%0/1
$d->{"articulations"} // []
$d->{"articulations"}
Truth table50%1/2
A
A= $d->{"articulations"}
Aresult
11
00
419 }
420  
421 9 for my $pk (sort keys %pending_tie) {
422 2 push @diagnostics, _fmt_msg('warn_unmatched_tie', $sname, $pk);
423 }
424 9 ▶ push @diagnostics, _fmt_msg('warn_unclosed_slur', $sname) if $in_slur;
Branch: 1 branch
BranchTrueFalseTotal
if $in_slur 0 9 9
425 }
426  
427 5 return \@diagnostics;
428 }
429  
430 # ---------------------------------------------------------------------------
431 # Private
432 # ---------------------------------------------------------------------------
433  
434 17 ▶sub _fmt_msg {
Subroutine _fmt_msg: called CC=2 SCAR=7.1
435 17 my ($key, @args) = @_;
436 17 ▶ croak "Unknown message key: $key" unless exists $MESSAGES{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $MESSAGES{$key} 0 17 17
437 17 return sprintf $MESSAGES{$key}, @args;
438 }
439  
440 # Convert a timesig hashref {beats, beat_type} to a rational [n, d] in quarter-note units.
441 # Returns (0, 1) when the timesig is absent or incomplete.
442 89 ▶sub _ts_to_rational {
Subroutine _ts_to_rational: called CC=4 SCAR=14.1
443 89 my ($ts) = @_;
444 89 ▶ return (0, 1) unless ref $ts eq 'HASH' && $ts->{beats} && $ts->{beat_type};
Branch: 1 branch
BranchTrueFalseTotal
unless ref $ts eq "HASH" and $ts->{"beats"} and $ts->{"beat_type"} 1 88 89
Condition66%4/6
ref $ts eq "HASH" and $ts->{"beats"} and $ts->{"beat_type"}
!ll&&!rl&&r
1088
ref $ts eq "HASH" and $ts->{"beats"}
!ll&&!rl&&r
0188
MC/DC33%1/3
ref $ts eq "HASH" and $ts->{"beats"} and $ts->{"beat_type"}
ref $ts eq "HASH" $ts->{"beats"} $ts->{"beat_type"}
Truth table50%2/4
A and B and C
A= ref $ts eq "HASH"B= $ts->{"beats"}C= $ts->{"beat_type"}
ABCresult
0XX0
10X0
1100
1111
445 88 return _rat_reduce($ts->{beats} * 4, $ts->{beat_type});
446 }
447  
448 # Reduce a fraction to lowest terms. Returns ($n, $d) with $d > 0.
449 5306 ▶sub _rat_reduce {
Subroutine _rat_reduce: called CC=2 SCAR=6.9
450 5306 my ($n, $d) = @_;
451 5306 ▶ return (0, 1) unless $n;
Branch: 1 branch
BranchTrueFalseTotal
unless $n 5218 88 5306
452 88 my $g = _gcd(abs($n), abs($d));
453 88 return ($n / $g, $d / $g);
454 }
455  
456 88 ▶sub _gcd {
Subroutine _gcd: called CC=2 SCAR=6.9
457 88 my ($a, $b) = @_;
458 88 ▶ ($a, $b) = ($b, $a % $b) while $b;
Branch: 1 branch
BranchTrueFalseTotal
$b and do { () = ($b, $a % $b) } 88 88 176
459 88 return $a;
460 }
461  
462 15 1;
463  
464 __END__
« NWC2MusicXML/MusicXML.pm ↑ Summary NWC2MusicXML/Parser.pm »