lib/ChordPro/Utils.pm

filter: Statementstmt 61.3% 227 / 370 Branchbran 33.5% 69 / 206 Conditioncond 28.0% 14 / 50 MC/DCmcdc 19.3% 6 / 31 Subroutinesub 78.0% 39 / 50 Podpod 0.0% 0 / 33 totaltotal 47.9% 355 / 740 CC 136 SCAR 41.1
CC
136
Cov
50%
dimension
306.0
fontsize
110.0
_detect_image_format
110.0
CRAP 60.8
« lib/ChordPro/Output/Common.pm ↑ Summary lib/ChordPro/Chords.pm »
1 #! perl
2  
3 package ChordPro::Utils;
4  
5 92 ▶use v5.26;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 92 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 92 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 92 ▶use feature qw( signatures );
Subroutine BEGIN: called CC=1 SCAR=0.0
9 92 ▶no warnings "experimental::signatures";
Subroutine BEGIN: called CC=1 SCAR=0.0
10 92 ▶use Ref::Util qw( is_arrayref is_hashref );
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 92 ▶use Exporter 'import';
Subroutine BEGIN: called CC=1 SCAR=0.0
13 92 our @EXPORT;
14 92 our @EXPORT_OK;
15 92 our %EXPORT_TAGS;
16  
17 92 ▶use ChordPro::Files;
Subroutine BEGIN: called CC=1 SCAR=0.0
18  
19 ################ Filenames ################
20  
21 92 ▶use File::Glob ( ":bsd_glob" );
Subroutine BEGIN: called CC=1 SCAR=0.0
22  
23 # Derived from Path::ExpandTilde.
24  
25 92 ▶use constant BSD_GLOB_FLAGS => GLOB_NOCHECK | GLOB_QUOTE | GLOB_TILDE | GLOB_ERR
Subroutine BEGIN: called CC=2 SCAR=7.1
Branch: 1 branch
BranchTrueFalseTotal
$^O =~ /\A(?:MSWin32|VMS|os2|dos|riscos)\z/u ? : 0 92 92
26 # add GLOB_NOCASE as in File::Glob
27 92 | ($^O =~ m/\A(?:MSWin32|VMS|os2|dos|riscos)\z/ ? GLOB_NOCASE : 0);
28  
29 # File::Glob did not try %USERPROFILE% (set in Windows NT derivatives) for ~ before 5.16
30 92 ▶use constant WINDOWS_USERPROFILE => is_msw && $] < 5.016;
Subroutine BEGIN: called CC=2 SCAR=7.6
Condition33%1/3
is_msw() && $] < 5.016
!ll&&!rl&&r
9200
MC/DC0%0/2
is_msw() && $] < 5.016
is_msw() $] < 5.016
Truth table33%1/3
A && B
A= is_msw()B= $] < 5.016
ABresult
0X0
100
111
31  
32 306 ▶sub expand_tilde ( $dir ) {
Subroutine expand_tilde: called CC=7 SCAR=36.3
Pod undocumented
33  
34 306 ▶ return undef unless defined $dir;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $dir 0 306 306
35 306 ▶ return fn_canonpath($dir) unless $dir =~ m/^~/;
Branch: 1 branch
BranchTrueFalseTotal
unless $dir =~ /^~/u 306 0 306
36  
37 # Parse path into segments.
38 0 my ( $volume, $directories, $file ) = fn_splitpath( $dir, 1 );
39 0 my @parts = fn_splitdir($directories);
40 0 my $first = shift( @parts );
41 0 ▶ return fn_canonpath($dir) unless defined $first;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $first 0 0 0
42  
43 # Expand first segment.
44 0 my $expanded;
45 0 if ( WINDOWS_USERPROFILE and $first eq '~' ) {
46 $expanded = $ENV{HOME} || $ENV{USERPROFILE};
47 }
48 else {
49 0 ( my $pattern = $first ) =~ s/([\\*?{[])/\\$1/g;
50 0 ($expanded) = bsd_glob( $pattern, BSD_GLOB_FLAGS );
51 0 ▶ croak( "Failed to expand $first: $!") if GLOB_ERROR;
Branch: 1 branch
BranchTrueFalseTotal
if GLOB_ERROR() 0 0 0
52 }
53 0 ▶ return fn_canonpath($dir)
Branch: 1 branch
BranchTrueFalseTotal
if not defined $expanded or $expanded eq $first 0 0 0
Condition0%0/3
not defined $expanded or $expanded eq $first
l!l&&r!l&&!r
000
MC/DC0%0/2
not defined $expanded or $expanded eq $first
not defined $expanded $expanded eq $first
Truth table0%0/3
not(A) or B
A= not defined $expandedB= $expanded eq $first
ABresult
1X1
011
000
54 if !defined $expanded or $expanded eq $first;
55  
56 # Replace first segment with new path.
57 0 ( $volume, $directories ) = fn_splitpath( $expanded, 1 );
58 0 $directories = fn_catdir( $directories, @parts );
59 0 return fn_catpath($volume, $directories, $file);
60 }
61  
62 92 push( @EXPORT, 'expand_tilde' );
63  
64 0 ▶sub sys ( @cmd ) {
Subroutine sys: not called CC=3 SCAR=24.8
Pod undocumented
65 0 ▶ warn("+ @cmd\n") if $::options->{trace};
Branch: 1 branch
BranchTrueFalseTotal
if $main::options->{"trace"} 0 0 0
66 # Use outer defined subroutine, depends on Wx or not.
67 0 my $res = ::sys(@cmd);
68 0 ▶ warn( sprintf("=%02x=> @cmd", $res), "\n" ) if $res;
Branch: 1 branch
BranchTrueFalseTotal
if $res 0 0 0
69 0 return $res;
70 }
71  
72 92 push( @EXPORT, 'sys' );
73  
74 ################ (Pre)Processing ################
75  
76 247 ▶sub make_preprocessor ( $prp ) {
Subroutine make_preprocessor: called CC=9 SCAR=32.8
Pod undocumented
77 247 ▶ return unless $prp;
Branch: 1 branch
BranchTrueFalseTotal
unless $prp 0 247 247
78  
79 247 my $prep;
80 247 foreach my $linetype ( keys %{ $prp } ) {
81 741 my @targets;
82 741 my $code = "";
83 741 foreach ( @{ $prp->{$linetype} } ) {
84 0 ▶ my $flags = $_->{flags} // "g";
Condition0%0/2
$_->{"flags"} // "g"
l!l
00
MC/DC0%0/1
$_->{"flags"} // "g"
$_->{"flags"}
Truth table0%0/2
A
A= $_->{"flags"}
Aresult
11
00
85 $code .= "m\0" . $_->{select} . "\0 && "
86 0 ▶ if $_->{select};
Branch: 1 branch
BranchTrueFalseTotal
if $_->{"select"} 0 0 0
87 0 ▶ if ( $_->{pattern} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_->{'pattern'}) { } 0 0 0
88 $code .= "s\0" . $_->{pattern} . "\0"
89 0 . $_->{replace} . "\0$flags;\n";
90 }
91 else {
92 $code .= "s\0" . quotemeta($_->{target}) . "\0"
93 0 . quotemeta($_->{replace}) . "\0$flags;\n";
94 }
95 }
96 741 ▶ if ( $code ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($code) 0 741 741
97 0 my $t = "sub { for (\$_[0]) {\n" . $code . "}}";
98 0 $prep->{$linetype} = eval $t;
99 0 ▶ die( "CODE : $t\n$@" ) if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
100 }
101 }
102 247 $prep;
103 }
104  
105 92 push( @EXPORT, 'make_preprocessor' );
106  
107 ################ Utilities ################
108  
109 # Split (pseudo) command line into key/value pairs.
110  
111 # Similar to JavaScript, we do not distinguish single- and double
112 # quoted strings.
113 # \\ \' \" yield \ ' " (JS)
114 # \n yields a newline (convenience)
115 # Everything else yields the character following the backslash (JS)
116  
117 92 my %esc = ( n => "\n", '\\' => '\\', '"' => '"', "'" => "'" );
118  
119 103 ▶sub parse_kv ( $line, $kdef = undef ) {
Subroutine parse_kv: called CC=10 SCAR=23.3
Pod undocumented
120  
121 103 my @words;
122 103 ▶ if ( is_arrayref($line) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (is_arrayref($line)) { } 8 95 103
123 8 @words = @$line;
124 }
125 else {
126 # Strip.
127 95 $line =~ s/^\s+//;
128 95 $line =~ s/\s+$//;
129  
130 # If it doesn't look like key=value, use the default key (if any).
131 95 ▶ if ( $kdef && $line !~ /^\w+=(?:['"]|[-+]?\d|\w)/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($kdef and not $line =~ /^\w+=(?:['"]|[-+]?\d|\w)/u) 30 65 95
Condition66%2/3
$kdef and not $line =~ /^\w+=(?:['"]|[-+]?\d|\w)/u
!ll&&!rl&&r
65030
MC/DC50%1/2
$kdef and not $line =~ /^\w+=(?:['"]|[-+]?\d|\w)/u
$kdef not $line =~ /^\w+=(?:['"]|[-+]?\d|\w)/u
Truth table66%2/3
A and not(B)
A= $kdefB= not $line =~ /^\w+=(?:['"]|[-+]?\d|\w)/u
ABresult
0X0
100
111
132 30 return { $kdef => $line };
133 }
134  
135 92 ▶ use Text::ParseWords qw(quotewords);
Subroutine BEGIN: called CC=1 SCAR=0.0
136 65 @words = quotewords( '\s+', 1, $line );
137 }
138  
139 73 my $res = {};
140 73 foreach ( @words ) {
141  
142 # Quoted values.
143 41 ▶ if ( /^(.*?)=(["'])(.*)\2$/ ) {
Branch: 3 branches
BranchTrueFalseTotal
if (/^(.*?)=(["'])(.*)\2$/u) { } 10 31 41
elsif (/^(.*?)=(.+)$/u) { } 25 6 31
elsif (/^no[-_]?(.+)/u) { } 2 4 6
144 10 my ( $k, $v ) = ( $1, $3 );
145 0 ▶ $res->{$k} = $v =~ s;\\(.);$esc{$1}//$1;segr;
Condition0%0/3
$esc{$1} // $1
l!l&&r!l&&!r
000
MC/DC0%0/2
$esc{$1} // $1
$esc{$1} $1
Truth table0%0/3
A // B
A= $esc{$1}B= $1
ABresult
1X1
011
000
146 }
147  
148 # Unquoted values.
149 elsif ( /^(.*?)=(.+)$/ ) {
150 25 $res->{$1} = $2;
151 }
152  
153 # Negated keywords.
154 elsif ( /^no[-_]?(.+)/ ) {
155 2 $res->{$1} = 0;
156 }
157  
158 # Standalone keywords.
159 else {
160 4 $res->{$_}++;
161 }
162 }
163  
164 73 return $res;
165 }
166  
167 92 push( @EXPORT, 'parse_kv' );
168  
169 # Split (pseudo) command lines into key/value pairs.
170  
171 #### LEGACY -- WILL BE REMOVED ####
172  
173 2 ▶sub parse_kvm ( @lines ) {
Subroutine parse_kvm: called CC=2 SCAR=8.7
Pod undocumented
174  
175 2 ▶ if ( is_macos() ) {
Branch: 1 branch
BranchTrueFalseTotal
if (is_macos()) 0 2 2
176 # MacOS has the nasty habit to smartify quotes.
177 0 @lines = map { s/“/"/g; s/”/"/g; s/‘/'/g; s/’/'/gr;} @lines;
178 }
179  
180 92 ▶ use Text::ParseWords qw(quotewords);
Subroutine BEGIN: called CC=1 SCAR=0.0
181 2 my @words = quotewords( '\s+', 1, @lines );
182 2 parse_kv( \@words );
183 }
184  
185 92 push( @EXPORT, 'parse_kvm' );
186  
187 # Odd/even.
188  
189 359 ▶sub is_odd( $arg ) {
Subroutine is_odd: called CC=1 SCAR=0.0
Pod undocumented
190 359 ( $arg % 2 ) != 0;
191 }
192 8 ▶sub is_even( $arg ) {
Subroutine is_even: called CC=1 SCAR=0.0
Pod undocumented
193 8 ( $arg % 2 ) == 0;
194 }
195  
196 92 push( @EXPORT, qw( is_odd is_even ) );
197  
198 # Map true/false etc to true / false.
199  
200 685 ▶sub is_true ( $arg ) {
Subroutine is_true: called CC=4 SCAR=13.9
Pod undocumented
201 685 ▶ return 0 if !defined($arg) || $arg eq '';
Branch: 1 branch
BranchTrueFalseTotal
if not defined $arg or $arg eq "" 8 677 685
Condition66%2/3
not defined $arg or $arg eq ""
l!l&&r!l&&!r
80677
MC/DC50%1/2
not defined $arg or $arg eq ""
not defined $arg $arg eq ""
Truth table66%2/3
not(A) or B
A= not defined $argB= $arg eq ""
ABresult
1X1
011
000
202 677 ▶ return 0 if $arg =~ /^(false|null|no|none|off|\s+|0)$/i;
Branch: 1 branch
BranchTrueFalseTotal
if $arg =~ /^(false|null|no|none|off|\s+|0)$/iu 71 606 677
203 606 return !!$arg;
204 }
205  
206 92 push( @EXPORT, 'is_true' );
207  
208 # Stricter form of true.
209 9 ▶sub is_ttrue ( $arg ) {
Subroutine is_ttrue: called CC=2 SCAR=7.2
Pod undocumented
210 9 ▶ return 0 if !defined($arg);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $arg 0 9 9
211 9 $arg =~ /^(on|true|1)$/i;
212 }
213  
214 92 push( @EXPORT, 'is_ttrue' );
215  
216 # Fix apos -> quote.
217  
218 1129 ▶sub fq ( $arg ) {
Subroutine fq: called CC=1 SCAR=0.0
Pod undocumented
219 1129 $arg =~ s/'/\x{2019}/g;
220 1129 $arg;
221 }
222  
223 92 push( @EXPORT, 'fq' );
224  
225 # Quote a string if needed unless forced.
226  
227 11 ▶sub qquote ( $arg, $force = 0 ) {
Subroutine qquote: called CC=5 SCAR=16.1
Pod undocumented
228 11 for ( $arg ) {
229 11 s/([\\\"])/\\$1/g;
230 0 s/([[:^print:]])/sprintf("\\u%04x", ord($1))/ge;
231 11 ▶ return $_ unless /[\\\s]/ || $force;
Branch: 1 branch
BranchTrueFalseTotal
unless /[\\\s]/u or $force 2 9 11
Condition100%3/3
/[\\\s]/u or $force
l!l&&r!l&&!r
362
MC/DC100%2/2
/[\\\s]/u or $force
/[\\\s]/u $force
Truth table100%3/3
A or B
A= /[\\\s]/uB= $force
ABresult
1X1
011
000
232 9 return qq("$_");
233 }
234 }
235  
236 92 push( @EXPORT, 'qquote' );
237  
238 # Safely print values.
239  
240 92 ▶use Scalar::Util qw(looks_like_number);
Subroutine BEGIN: called CC=1 SCAR=0.0
241  
242 # We want overload:
243 # sub pv( $val )
244 # sub pv( $label, $val )
245  
246 0 ▶sub pv {
Subroutine pv: not called CC=7 SCAR=40.3
Pod undocumented
247 0 my $val = pop;
248 0 ▶ my $label = pop // "";
Condition0%0/2
pop() // ""
l!l
00
MC/DC0%0/1
pop() // ""
pop()
Truth table0%0/2
A
A= pop()
Aresult
11
00
249  
250 0 my $suppressundef;
251 0 ▶ if ( $label =~ /\?$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($label =~ /\?$/u) 0 0 0
252 0 $suppressundef++;
253 0 $label = $';
254 }
255 0 ▶ if ( defined $val ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $val) { } 0 0 0
256 0 ▶ if ( looks_like_number($val) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (&looks_like_number($val)) { } 0 0 0
257 0 $val = sprintf("%.3f", $val);
258 0 $val =~ s/0+$//;
259 0 $val =~ s/\.$//;
260 }
261 else {
262 0 $val = qquote( $val, 1 );
263 }
264 }
265 else {
266 0 ▶ return "" if $suppressundef;
Branch: 1 branch
BranchTrueFalseTotal
if $suppressundef 0 0 0
267 0 $val = "<undef>"
268 }
269 0 ▶ defined wantarray ? $label.$val : warn($label.$val."\n");
Branch: 1 branch
BranchTrueFalseTotal
defined wantarray ? : 0 0 0
270 }
271  
272 92 push( @EXPORT, 'pv' );
273  
274 # Processing JSON.
275  
276 92 my $_json_xs;
277 my $_json_rr;
278 92 our $json_last;
279  
280 138 ▶sub json_load( $json, $source = "<builtin>" ) {
Subroutine json_load: called CC=5 SCAR=16.5
Pod undocumented
281  
282 # We have two JSON parsers: Relaxed and XS.
283 # Relaxed accepts a lot of relaxing extensions, but XS is much
284 # much faster. So fast, in fact, that trying XS first will be a
285 # win in many cases, and a neglectable overhead in the other
286 # cases.
287  
288 138 state $jx = JSON::XS->new;
289 138 $jx->relaxed;
290  
291 # Glue lines, so we have at lease some relaxation.
292 138 $json =~ s/"\s*\\\r?\n\s*"//g;
293  
294 138 my $data;
295 138 $json_last = "xs";
296 138 eval { $data = $jx->decode($json."\n"); $_json_xs++ };
297 138 ▶ return $data if defined $data;
Branch: 1 branch
BranchTrueFalseTotal
if defined $data 124 14 138
298  
299 14 require JSON::Relaxed;
300 14 state $jr = JSON::Relaxed::Parser->new( croak_on_error => 0,
301 strict => 0,
302 prp => 1 );
303 14 $_json_rr++;
304 14 $json_last = "rr";
305 14 $data = $jr->decode($json."\n");
306 14 ▶ return $data unless $jr->is_error;
Branch: 1 branch
BranchTrueFalseTotal
unless $jr->is_error 14 0 14
307 0 ▶ $source .= ": " if $source;
Branch: 1 branch
BranchTrueFalseTotal
if $source 0 0 0
308 0 die("${source}JSON error: " . $jr->err_msg . "\n");
309 }
310  
311 0 ▶sub json_stats( $reset = 0 ) {
Subroutine json_stats: not called CC=5 SCAR=34.0
Pod undocumented
312 0 ▶ my $res = { xs => $_json_xs//0, rr => $_json_rr//0 };
Condition0%0/4
$_json_xs // 0
l!l
00
$_json_rr // 0
l!l
00
MC/DC0%0/1
$_json_xs // 0
$_json_xs
MC/DC0%0/1
$_json_rr // 0
$_json_rr
Truth table0%0/2
A
A= $_json_xs
Aresult
11
00
Truth table0%0/2
A
A= $_json_rr
Aresult
11
00
313 0 ▶ if ( $reset ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($reset) 0 0 0
314 0 $_json_xs = $_json_rr = 0;
315 }
316 0 return $res;
317 }
318  
319 92 push( @EXPORT, qw(json_load json_stats) );
320  
321 # Like prp2cfg, but updates.
322 # Also allows array pre/append and JSON data.
323 # Useful error messages are signalled with exceptions.
324  
325 92 push( @EXPORT, 'prpadd2cfg' );
326  
327 165 ▶sub prpadd2cfg ( $cfg, @defs ) {
Subroutine prpadd2cfg: called CC=28 SCAR=34.5
Pod undocumented
328 165 ▶ $cfg //= {};
Condition50%1/2
$cfg //= {}
l!l
1650
MC/DC0%0/1
$cfg //= {}
$cfg
Truth table50%1/2
A
A= $cfg
Aresult
11
00
329 165 state $specials = { false => 0, true => 1, null => undef };
330  
331 165 ▶ while ( @defs ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@defs) 77 163 240
332 77 my $key = shift(@defs);
333 77 my $value = shift(@defs);
334 # warn("K:$key V:$value\n");
335  
336 # Check and process the value, if needed.
337 77 ▶ if ( exists $specials->{$value} ) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $specials->{$value}) { } 6 71 77
elsif (not ref $value || !($value =~ /[\[\{\]\}]/u)) { } 1 70 71
338 6 $value = $specials->{$value};
339 # warn("Value => $value\n");
340 }
341 ▶ elsif ( !( ref($value)
Condition100%3/3
ref $value || !($value =~ /[\[\{\]\}]/u)
l!l&&r!l&&!r
2681
MC/DC100%2/2
ref $value || !($value =~ /[\[\{\]\}]/u)
ref $value !($value =~ /[\[\{\]\}]/u)
Truth table100%3/3
A || not(B)
A= ref $valueB= !($value =~ /[\[\{\]\}]/u)
ABresult
1X1
011
000
342 || $value !~ /[\[\{\]\}]/ ) ) {
343 # Not simple, assume JSON struct.
344 1 $value = json_load( $value, $value );
345 # use DDP; p($value, as => "Value ->");
346 }
347  
348 # Note that ':' is not oficially supported by RRJson.
349 77 my @keys = split( /[:.]/, $key );
350 77 my $lastkey = pop(@keys);
351  
352 # Handle pdf.fonts.xxx shortcuts.
353 77 ▶ if ( join( ".", @keys ) eq "pdf.fonts" ) {
Branch: 1 branch
BranchTrueFalseTotal
if (join(".", @keys) eq "pdf.fonts") 0 77 77
354 0 my $s = { pdf => { fonts => { $lastkey => $value } } };
355 0 ChordPro::Config::expand_font_shortcuts($s);
356 0 $value = $s->{pdf}{fonts}{$lastkey};
357 }
358  
359 77 my $cur = \$cfg; # current pointer in struct
360 77 my $errkey = ""; # error trail
361 77 ▶ if ( $keys[0] eq "chords" ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($keys[0] eq "chords") 0 77 77
362 # Chords are not in the config, but elsewhere.
363 0 $cur = \ChordPro::Chords::config_chords();
364 0 $errkey = "chords.";
365 0 shift(@keys);
366 }
367  
368 # Step through the keys.
369 77 foreach ( @keys ) {
370 102 ▶ if ( is_arrayref($$cur) ) {
Branch: 2 branches
BranchTrueFalseTotal
if (is_arrayref($$cur)) { } 19 83 102
elsif (is_hashref($$cur)) { } 83 0 83
371 19 my $ok;
372 19 ▶ if ( /^[<>]?[-+]?\d+$/ ) {
Branch: 2 branches
BranchTrueFalseTotal
if (/^[<>]?[-+]?\d+$/u) { } 18 1 19
elsif (not exists $$cur->[0]{'name'}) { } 0 1 1
373 18 $cur = \($$cur->[$_]);
374 18 $ok++;
375 }
376 elsif ( ! exists( $$cur->[0]->{name} ) ) {
377 0 die("Array ", substr($errkey,0,-1),
378 " requires integer index (got \"$_\")\n");
379 }
380 else {
381 1 for my $i ( 0..@{$$cur} ) {
382 1 ▶ if ( $$cur->[$i]->{name} eq $_ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$cur->[$i]{"name"} eq $_) 1 0 1
383 1 $cur = \($$cur->[$i]);
384 1 $ok++;
385 1 last;
386 }
387 }
388 }
389 19 ▶ unless ( $ok ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 0 19 19
390 0 die("Array ", substr($errkey,0,-1),
391 " has no matching element with name \"$_\"\n");
392 }
393 }
394 elsif ( is_hashref($$cur) ) {
395 83 $cur = \($$cur->{$_});
396 }
397 else {
398 0 die("Key ", substr($errkey,0,-1),
399 " ", ref($$cur),
400 " does not refer to an array or hash\n");
401 }
402 102 $errkey .= "$_."
403  
404 }
405  
406 # Final key.
407 77 ▶ if ( is_arrayref($$cur) ) {
Branch: 2 branches
BranchTrueFalseTotal
if (is_arrayref($$cur)) { } 24 53 77
elsif (is_hashref($$cur)) { } 51 2 53
408 24 ▶ if ( $lastkey =~ />([-+]?\d+)?$/ ) { # append
Branch: 3 branches
BranchTrueFalseTotal
if ($lastkey =~ />([-+]?\d+)?$/u) { } 9 15 24
elsif ($lastkey =~ /<([-+]?\d+)?$/u) { } 6 9 15
elsif ($lastkey =~ m[/([-+]?\d+)?$]u) { } 3 6 9
409 9 ▶ if ( defined $1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $1) { } 5 4 9
410 5 ▶ splice( @{$$cur},
Branch: 1 branch
BranchTrueFalseTotal
$1 >= 0 ? : 4 1 5
411 5 $1 >= 0 ? 1+$1 : 1+@{$$cur}+$1, 0, $value );
412 }
413 else {
414 4 push( @{$$cur}, $value );
415 }
416 }
417 elsif ( $lastkey =~ /<([-+]?\d+)?$/ ) { # prepend
418 6 ▶ if ( defined $1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $1) { } 4 2 6
419 4 splice( @{$$cur}, $1, 0, $value );
420 }
421 else {
422 2 unshift( @{$$cur}, $value );
423 }
424 }
425 elsif ( $lastkey =~ /\/([-+]?\d+)?$/ ) { # remove
426 3 ▶ if ( defined $1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $1) { } 2 1 3
427 2 splice( @{$$cur}, $1, 1 );
428 }
429 else {
430 1 pop( @{$$cur} );
431 }
432 }
433 else { # replace
434 6 ▶ die("Array $errkey requires integer index (got \"$lastkey\")\n")
Branch: 1 branch
BranchTrueFalseTotal
unless $lastkey =~ /^[-+]?\d+$/u 0 6 6
435 unless $lastkey =~ /^[-+]?\d+$/;
436 6 $$cur->[$lastkey] = $value;
437 }
438 }
439 elsif ( is_hashref($$cur) ) {
440 51 ▶ if ( $errkey =~ /^chords\./ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($errkey =~ /^chords\./u) { } 0 51 51
441 # Chords must be defined.
442 0 ChordPro::Chords::add_config_chord( { name => $lastkey,
443 %$value } );
444 }
445 else {
446 51 $$cur->{$lastkey} = $value;
447 }
448 }
449 else {
450 2 ▶ die("Key ", substr($errkey,0,-1),
Branch: 1 branch
BranchTrueFalseTotal
$lastkey =~ /^(?:[-+]?\d+|[<>])$/u ? : 1 1 2
451 " is scalar, not ",
452 $lastkey =~ /^(?:[-+]?\d+|[<>])$/ ? "array" : "hash",
453 "\n");
454 }
455 }
456  
457 # The structure has been modified, but also return for covenience.
458 163 return $cfg;
459 }
460  
461 92 push( @EXPORT, 'prpadd2cfg' );
462  
463 # Remove markup.
464 2633 ▶sub demarkup ( $t ) {
Subroutine demarkup: called CC=1 SCAR=0.0
Pod undocumented
465 2633 return join( '', grep { ! /^\</ } splitmarkup($t) );
466 }
467 92 push( @EXPORT, 'demarkup' );
468  
469 # Split into markup/nonmarkup segments.
470 2655 ▶sub splitmarkup ( $t ) {
Subroutine splitmarkup: called CC=1 SCAR=0.0
Pod undocumented
471 2655 my @t = split( qr;(</?(?:[-\w]+|span\s.*?)>);, $t );
472 2655 return @t;
473 }
474 92 push( @EXPORT, 'splitmarkup' );
475  
476 # For conditional filling of hashes.
477 46 ▶sub maybe ( $key, $value, @rest ) {
Subroutine maybe: called CC=5 SCAR=21.9
Pod undocumented
478 46 ▶ if (defined $key and defined $value) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $key and defined $value) { } 0 46 46
Condition33%1/3
defined $key and defined $value
!ll&&!rl&&r
0460
MC/DC0%0/2
defined $key and defined $value
defined $key defined $value
Truth table33%1/3
A and B
A= defined $keyB= defined $value
ABresult
0X0
100
111
479 0 return ( $key, $value, @rest );
480 }
481 else {
482 46 ▶ ( defined($key) || @rest ) ? @rest : ();
Branch: 1 branch
BranchTrueFalseTotal
defined $key || @rest ? : 46 0 46
Condition33%1/3
defined $key or @rest
l!l&&r!l&&!r
4600
MC/DC0%0/2
defined $key or @rest
defined $key @rest
Truth table33%1/3
A or B
A= defined $keyB= @rest
ABresult
1X1
011
000
483 }
484 }
485 92 push( @EXPORT, "maybe" );
486  
487 # Min/Max.
488 92 ▶use List::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
489 92 *min = \&List::Util::min;
490 92 *max = \&List::Util::max;
491  
492 92 push( @EXPORT, "min", "max" );
493  
494 # Plural
495 0 ▶sub plural( $n, $tag, $plural=undef ) {
Subroutine plural: not called CC=5 SCAR=34.0
Pod undocumented
496 0 ▶ $plural //= $tag . "s";
Condition0%0/2
$plural //= $tag . 's'
l!l
00
MC/DC0%0/1
$plural //= $tag . 's'
$plural
Truth table0%0/2
A
A= $plural
Aresult
11
00
497 0 ▶ ( $n || "no" ) . ( $n == 1 ? $tag : $plural );
Branch: 1 branch
BranchTrueFalseTotal
$n == 1 ? : 0 0 0
Condition0%0/2
$n || 'no'
l!l
00
MC/DC0%0/1
$n || 'no'
$n
Truth table0%0/2
A
A= $n
Aresult
11
00
498 }
499  
500 92 push( @EXPORT, "plural" );
501  
502 # Dimensions.
503 # Fontsize allows typical font units, and defaults to ref 12.
504 0 ▶sub fontsize( $size, $ref=12 ) {
Subroutine fontsize: not called CC=10 SCAR=47.0
Pod undocumented
505 0 ▶ if ( $size && $size =~ /^([.\d]+)(%|e[mx]|p[tx])$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($size and $size =~ /^([.\d]+)(%|e[mx]|p[tx])$/u) 0 0 0
Condition0%0/3
$size and $size =~ /^([.\d]+)(%|e[mx]|p[tx])$/u
!ll&&!rl&&r
000
MC/DC0%0/2
$size and $size =~ /^([.\d]+)(%|e[mx]|p[tx])$/u
$size $size =~ /^([.\d]+)(%|e[mx]|p[tx])$/u
Truth table0%0/3
A and B
A= $sizeB= $size =~ /^([.\d]+)(%|e[mx]|p[tx])$/u
ABresult
0X0
100
111
506 0 ▶ return $ref/100 * $1 if $2 eq '%';
Branch: 1 branch
BranchTrueFalseTotal
if $2 eq "%" 0 0 0
507 0 ▶ return $ref * $1 if $2 eq 'em';
Branch: 1 branch
BranchTrueFalseTotal
if $2 eq "em" 0 0 0
508 0 ▶ return $ref/2 * $1 if $2 eq 'ex';
Branch: 1 branch
BranchTrueFalseTotal
if $2 eq "ex" 0 0 0
509 0 ▶ return $1 if $2 eq 'pt';
Branch: 1 branch
BranchTrueFalseTotal
if $2 eq "pt" 0 0 0
510 0 ▶ return $1 * 0.75 if $2 eq 'px';
Branch: 1 branch
BranchTrueFalseTotal
if $2 eq "px" 0 0 0
511 }
512 0 ▶ $size || $ref;
Branch: 1 branch
BranchTrueFalseTotal
$size or $ref 0 0 0
513 }
514  
515 92 push( @EXPORT, "fontsize" );
516  
517 # Dimension allows arbitrary units, and defaults to ref 12.
518 0 ▶sub dimension( $size, %sz ) {
Subroutine dimension: not called CC=17 SCAR=57.2
Pod undocumented
519 0 ▶ return unless defined $size;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $size 0 0 0
520 0 my $ref;
521 0 ▶ if ( ( $ref = $sz{fsize} )
Branch: 1 branch
BranchTrueFalseTotal
if ($ref = $sz{"fsize"} and $size =~ /^([.\d]+)(%|e[mx])$/u) 0 0 0
Condition0%0/3
$ref = $sz{"fsize"} and $size =~ /^([.\d]+)(%|e[mx])$/u
!ll&&!rl&&r
000
MC/DC0%0/2
$ref = $sz{"fsize"} and $size =~ /^([.\d]+)(%|e[mx])$/u
$ref = $sz{"fsize"} $size =~ /^([.\d]+)(%|e[mx])$/u
Truth table0%0/3
A and B
A= $ref = $sz{"fsize"}B= $size =~ /^([.\d]+)(%|e[mx])$/u
ABresult
0X0
100
111
522 && $size =~ /^([.\d]+)(%|e[mx])$/ ) {
523 0 ▶ return $ref/100 * $1 if $2 eq '%';
Branch: 1 branch
BranchTrueFalseTotal
if $2 eq "%" 0 0 0
524 0 ▶ return $ref * $1 if $2 eq 'em';
Branch: 1 branch
BranchTrueFalseTotal
if $2 eq "em" 0 0 0
525 0 ▶ return $ref/2 * $1 if $2 eq 'ex';
Branch: 1 branch
BranchTrueFalseTotal
if $2 eq "ex" 0 0 0
526 }
527 0 ▶ if ( ( $ref = $sz{width} )
Branch: 1 branch
BranchTrueFalseTotal
if ($ref = $sz{"width"} and $size =~ /^([.\d]+)(%)$/u) 0 0 0
Condition0%0/3
$ref = $sz{"width"} and $size =~ /^([.\d]+)(%)$/u
!ll&&!rl&&r
000
MC/DC0%0/2
$ref = $sz{"width"} and $size =~ /^([.\d]+)(%)$/u
$ref = $sz{"width"} $size =~ /^([.\d]+)(%)$/u
Truth table0%0/3
A and B
A= $ref = $sz{"width"}B= $size =~ /^([.\d]+)(%)$/u
ABresult
0X0
100
111
528 && $size =~ /^([.\d]+)(%)$/ ) {
529 0 ▶ return $ref/100 * $1 if $2 eq '%';
Branch: 1 branch
BranchTrueFalseTotal
if $2 eq "%" 0 0 0
530 }
531 0 ▶ if ( $size =~ /^([.\d]+)(p[tx]|[cm]m|in|)$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($size =~ /^([.\d]+)(p[tx]|[cm]m|in|)$/u) 0 0 0
532 0 ▶ return $1 if $2 eq 'pt';
Branch: 1 branch
BranchTrueFalseTotal
if $2 eq "pt" 0 0 0
533 0 ▶ return $1 * 0.75 if $2 eq 'px';
Branch: 1 branch
BranchTrueFalseTotal
if $2 eq "px" 0 0 0
534 0 ▶ return $1 * 72 / 2.54 if $2 eq 'cm';
Branch: 1 branch
BranchTrueFalseTotal
if $2 eq "cm" 0 0 0
535 0 ▶ return $1 * 72 / 25.4 if $2 eq 'mm';
Branch: 1 branch
BranchTrueFalseTotal
if $2 eq "mm" 0 0 0
536 0 ▶ return $1 * 72 if $2 eq 'in';
Branch: 1 branch
BranchTrueFalseTotal
if $2 eq "in" 0 0 0
537 0 ▶ return $1 if $2 eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $2 eq "" 0 0 0
538 }
539 0 $size; # let someone else croak
540 }
541  
542 92 push( @EXPORT, "dimension" );
543  
544 # Checking font names against the PDF corefonts.
545  
546 my %corefonts =
547 (
548 92 ( map { lc($_) => $_ }
549 "Times-Roman",
550 "Times-Bold",
551 "Times-Italic",
552 "Times-BoldItalic",
553 "Helvetica",
554 "Helvetica-Bold",
555 "Helvetica-Oblique",
556 "Helvetica-BoldOblique",
557 "Courier",
558 "Courier-Bold",
559 "Courier-Oblique",
560 "Courier-BoldOblique",
561 "Symbol",
562 "ZapfDingbats" ),
563 );
564  
565 6255 ▶sub is_corefont {
Subroutine is_corefont: called CC=1 SCAR=0.0
Pod undocumented
566 6255 $corefonts{lc $_[0]};
567 }
568  
569 92 push( @EXPORT, "is_corefont" );
570  
571 # Progress reporting.
572  
573 92 ▶use Ref::Util qw(is_coderef);
Subroutine BEGIN: called CC=1 SCAR=0.0
574  
575 # Progress can return a false result to allow caller to stop.
576  
577 120 ▶sub progress(%args) {
Subroutine progress: called CC=13 SCAR=46.8
Pod undocumented
578 120 state $callback;
579 120 state $phase = "";
580 120 state $index = 0;
581 120 state $total = '';
582 120 ▶ unless ( %args ) { # reset
Branch: 1 branch
BranchTrueFalseTotal
unless (%args) 0 120 120
583 0 undef $callback;
584 0 $phase = "";
585 0 $index = 0;
586 0 return;
587 }
588  
589 120 ▶ $callback = $args{callback} if exists $args{callback};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"callback"} 0 120 120
590 120 ▶ return 1 unless $callback;
Branch: 1 branch
BranchTrueFalseTotal
unless $callback 120 0 120
591  
592 0 ▶ if ( exists $args{phase} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $args{"phase"}) 0 0 0
593 0 ▶ $index = 0 if $phase ne $args{phase};
Branch: 1 branch
BranchTrueFalseTotal
if $phase ne $args{"phase"} 0 0 0
594 0 $phase = $args{phase};
595 }
596 0 ▶ if ( exists $args{index} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $args{"index"}) 0 0 0
597 0 $index = $args{index};
598  
599 # Use index<0 to only set callback/phase.
600 0 ▶ $index = 0, $total = '', return if $index < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $index < 0 0 0 0
601 }
602 0 ▶ if ( exists $args{total} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $args{"total"}) 0 0 0
603 0 $total = $args{total};
604 }
605  
606 0 my $args = { phase => $phase, index => $index, total => $total, %args };
607  
608 0 my $ret = ++$index;
609 0 ▶ if ( is_coderef($callback) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (is_coderef($callback)) { } 0 0 0
610 0 $ret = eval { $callback->(%$args) };
611 0 ▶ if ( $@ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
612 0 warn($@);
613 0 undef $callback;
614 }
615 }
616 else {
617 0 ▶ if ( $callback eq "warn" ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($callback eq "warn") 0 0 0
618 # Simple progress message. Suppress if $index = 0 or total = 1.
619 0 $callback =
620 '%{index=0||' .
621 '%{total=1||Progress[%{phase}]: %{index}%{total|/%{}}%{msg| - %{}}}' .
622 '}';
623 }
624 0 my $msg = ChordPro::Output::Common::fmt_subst
625 ( { meta => $args }, $callback );
626 0 $msg =~ s/\n+$//;
627 0 ▶ warn( $msg, "\n" ) if $msg;
Branch: 1 branch
BranchTrueFalseTotal
if $msg 0 0 0
628 }
629  
630 0 return $ret;
631 }
632  
633 92 push( @EXPORT, "progress" );
634  
635 # Common items for property directives ({textsize} etc.).
636  
637 104 ▶sub propitems() {
Subroutine propitems: called CC=1 SCAR=0.0
Pod undocumented
638 104 qw( chord chorus diagrams footer grid label tab text title toc );
639 }
640  
641 104 ▶sub propitems_re() {
Subroutine propitems_re: called CC=1 SCAR=0.0
Pod undocumented
642 104 my $re = join( '|', propitems() );
643 104 qr/(?:$re)/;
644 }
645  
646 92 push( @EXPORT, "propitems_re" );
647 92 push( @EXPORT_OK, "propitems" );
648  
649 # For debugging encoding problems.
650  
651 0 ▶sub as( $s ) {
Subroutine as: not called CC=2 SCAR=17.9
Pod undocumented
652 0 ▶ return "<undef>" unless defined $s;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $s 0 0 0
653 0 $s =~ s{ ( [^\x{20}-\x{7f}] ) }
654 0 { join( '', map { sprintf '\x{%02x}', ord $_ } split //, $1) }gex;
655 0 return $s;
656 }
657  
658 92 push( @EXPORT_OK, "as" );
659  
660 0 ▶sub enumerated( @s ) {
Subroutine enumerated: not called CC=3 SCAR=24.8
Pod undocumented
661 0 ▶ return "" unless @s;
Branch: 1 branch
BranchTrueFalseTotal
unless @s 0 0 0
662 0 my $last = pop(@s);
663 0 my $ret = "";
664 0 ▶ $ret .= join(", ", @s) . " and " if @s;
Branch: 1 branch
BranchTrueFalseTotal
if @s 0 0 0
665 0 $ret .= $last;
666 0 return $ret;
667 }
668  
669 92 push( @EXPORT_OK, "enumerated" );
670  
671 # Determine image type.
672  
673 0 ▶sub _detect_image_format( $test ) {
Subroutine _detect_image_format: not called CC=10 SCAR=47.0
674  
675 0 ▶ for ( ref($test) ? $$test : $test ) {
Branch: 1 branch
BranchTrueFalseTotal
ref $test ? : 0 0 0
676 0 ▶ /^GIF\d\d[a-z]/ and return 'gif';
Branch: 1 branch
BranchTrueFalseTotal
/^GIF\d\d[a-z]/u and return "gif" 0 0 0
677 0 ▶ /^\xFF\xD8\xFF/ and return 'jpeg';
Branch: 1 branch
BranchTrueFalseTotal
/^\xFF\xD8\xFF/u and return "jpeg" 0 0 0
678 0 ▶ /^\x89PNG\x0D\x0A\x1A\x0A/ and return 'png';
Branch: 1 branch
BranchTrueFalseTotal
/^\x89PNG\x0D\x0A\x1A\x0A/u and return "png" 0 0 0
679 0 ▶ /^\s*P[1-6]/ and return 'pnm';
Branch: 1 branch
BranchTrueFalseTotal
/^\s*P[1-6]/u and return "pnm" 0 0 0
680 0 ▶ /^II\x2A\x00/ and return 'tiff';
Branch: 1 branch
BranchTrueFalseTotal
/^II\x2A\x00/u and return "tiff" 0 0 0
681 0 ▶ /^MM\x00\x2A/ and return 'tiff';
Branch: 1 branch
BranchTrueFalseTotal
/^MM\x00\x2A/u and return "tiff" 0 0 0
682 0 ▶ /^<svg\s/is and return 'svg';
Branch: 1 branch
BranchTrueFalseTotal
/^<svg\s/isu and return "svg" 0 0 0
683 }
684  
685 # Not recognized.
686 0 return;
687 }
688  
689 0 ▶sub detect_image_format( $test ) {
Subroutine detect_image_format: not called CC=2 SCAR=17.9
Pod undocumented
690 0 my $format = _detect_image_format($test);
691  
692 0 ▶ if ( $format ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($format) 0 0 0
693 0 return { file_ext => $format, error => "" };
694 }
695 0 return { file_ext => "", error => "Unrecognized image type." };
696 }
697  
698 92 push( @EXPORT_OK, "detect_image_format" );
699  
700 # Transpose types
701  
702 0 ▶sub XP_DEFAULT() { 0 }
Subroutine XP_DEFAULT: not called CC=1 SCAR=6.9
Pod undocumented
703 3784 ▶sub XP_FOLLOW() { 0 }
Subroutine XP_FOLLOW: called CC=1 SCAR=0.0
Pod undocumented
704 20 ▶sub XP_SHARP() { 1 }
Subroutine XP_SHARP: called CC=1 SCAR=0.0
Pod undocumented
705 22 ▶sub XP_FLAT() { 2 }
Subroutine XP_FLAT: called CC=1 SCAR=0.0
Pod undocumented
706 4473 ▶sub XP_KEY() { 3 }
Subroutine XP_KEY: called CC=1 SCAR=0.0
Pod undocumented
707  
708 92 $EXPORT_TAGS{"xp"} = [ qw( XP_DEFAULT XP_FOLLOW XP_SHARP XP_FLAT XP_KEY ) ];
709 92 push( @EXPORT_OK, @{ $EXPORT_TAGS{"xp"} } );
710  
711 92 1;
« lib/ChordPro/Output/Common.pm ↑ Summary lib/ChordPro/Chords.pm »