blib/lib/Term/Fabulous/Theme/Document.pm untested

filter: Statementstmt 0.0% 0 / 702 Branchbran 0.0% 0 / 370 Conditioncond 0.0% 0 / 338 MC/DCmcdc 0.0% 0 / 194 Subroutinesub 0.0% 0 / 15 Podpod 0.0% 0 / 1 totaltotal 0.0% 0 / 1620 CC 1 SCAR 6.9
CC
1
Cov
0%
_quoted
2.0
BEGIN
2.0
BEGIN
2.0
CRAP 2.0
1 package Term::Fabulous::Theme::Document;
2  
3 use v5.32;
4 use warnings;
5 use feature 'signatures';
6 no warnings 'experimental::signatures';
7  
8 our $VERSION = '0.05';
9  
10 use Object::Pad 0.825;
11  
12 class Term::Fabulous::Theme::Document :strict(params) {
13 use File::Basename ();
14 use File::Spec;
15 use Encode qw(decode encode FB_CROAK);
16 use Feature::Compat::Try;
17 use List::Util qw(any first max);
18 use Storable qw(dclone);
19 use Text::KDL::XS::Parser;
20 use Term::Fabulous::Check qw(color describe);
21 use Term::Fabulous::Theme;
22  
23 my %IS_STATE = map { $_ => 1 } grep { $_ ne 'normal' } Term::Fabulous::Theme::states();
24 my %IS_TOKEN = map { $_ => 1 } Term::Fabulous::Theme::tokens();
25 my %IS_BASE = map { $_ => 1 } Term::Fabulous::Theme::builtin_names();
26  
27 # Words KDL 2 does not take as bare strings.
28 my %KEYWORD = map { $_ => 1 } qw(true false null inf -inf nan);
29  
30 field $text :param :reader;
31  
32 # The source split into lines, each with its line end; line N of the
33 # messages is $lines[N - 1].
34 field @lines;
35  
36 # The tree of the document: containers ({ children, tail }) and items
37 # (nodes, comments, slashdashed nodes) with the lines they span. undef
38 # when the text is not valid KDL.
39 field $root;
40 field $kdl_version = 2;
41 field $indent_unit = "\t";
42 field $newline = "\n";
43  
44 # What the document sets: key => { spec, line, path, prop, family,
45 # variant, slot, state }, and the keys in document order.
46 field %setting;
47 field @setting_keys;
48 field @variant_names;
49 field %variant_line;
50  
51 field @errors;
52 field $theme;
53 field $theme_built = 0;
54  
55 ADJUST {
56 die "Term::Fabulous::Theme::Document: the text must be a character string, got " . describe($text) unless defined $text && !ref $text;
57 @lines = split /(?<=\n)/, $text;
58 $newline = "\r\n" if @lines && $lines[0] =~ /\r\n\z/;
59  
60 my $events = $self->_events;
61 if ( defined $events ) {
62 $root = _tree( $events, \@lines );
63 _measure( $root, \@lines, 0, scalar(@lines) + 1 );
64 $indent_unit = _indent_unit( $root, \@lines ) // "\t";
65 $self->_walk;
66 }
67 }
68  
69 # ---------------------------------------------------------------------
70 # Construction
71 # ---------------------------------------------------------------------
72  
73 method parse :common ($kdl) {
74 return $class->new( text => $kdl );
75 }
76  
77 method read_file :common ($path) {
78 die "Term::Fabulous::Theme::Document: read_file needs a file name, got " . describe($path) unless defined $path && !ref $path && length $path;
79 open my $handle, '<:raw', $path or die "Term::Fabulous::Theme::Document: cannot open '$path': $!\n";
80 my $bytes = do { local $/; <$handle> };
81 close $handle;
82 my $kdl;
83 try {
84 $kdl = decode( 'UTF-8', $bytes, FB_CROAK );
85 }
86 catch ($error) {
87 die "Term::Fabulous::Theme::Document: '$path' is not UTF-8 text\n";
88 }
89 $kdl =~ s/\A\x{FEFF}//;
90 return $class->new( text => $kdl );
91 }
92  
93 # Writes the text to a new file next to the target and renames it over
94 # the target, so the target is never half written; an existing file
95 # keeps its permissions, a symbolic link its target.
96 method write_file ($path) {
97 die "Term::Fabulous::Theme::Document: write_file needs a file name, got " . describe($path) unless defined $path && !ref $path && length $path;
98 $path = _link_target($path) if -l $path; # a link stays a link: its target is written
99 die "Term::Fabulous::Theme::Document: cannot write '$path': it is read-only\n" if -e $path && !-w $path;
100 my $mode = ( stat $path )[2];
101 my $temporary = "$path.tmp-$$";
102 open my $handle, '>:raw', $temporary or die "Term::Fabulous::Theme::Document: cannot write '$temporary': $!\n";
103 my $written = print {$handle} encode( 'UTF-8', $text );
104 my $closed = close $handle;
105  
106 unless ( $written && $closed ) {
107 my $reason = $!;
108 unlink $temporary;
109 die "Term::Fabulous::Theme::Document: cannot write '$temporary': $reason\n";
110 }
111 chmod $mode & oct(7777), $temporary if defined $mode;
112 unless ( rename $temporary, $path ) {
113 my $reason = $!;
114 unlink $temporary;
115 die "Term::Fabulous::Theme::Document: cannot replace '$path': $reason\n";
116 }
117 return $self;
118 }
119  
120 # Where a symbolic link points, also when that file does not exist yet.
121 sub _link_target ($link) {
122 my $target = readlink $link // die "Term::Fabulous::Theme::Document: cannot read the link '$link': $!\n";
123 $target = File::Spec->catfile( File::Basename::dirname($link), $target ) unless File::Spec->file_name_is_absolute($target);
124 return -l $target ? _link_target($target) : $target;
125 }
126  
127 # ---------------------------------------------------------------------
128 # Parsing: events with their lines
129 # ---------------------------------------------------------------------
130  
131 # The events of the text as KDL 2, or else as KDL 1; undef with the
132 # error of the KDL 2 attempt recorded when neither reads it.
133 method _events () {
134 my ( $events, $error ) = _events_as( \@lines, 2 );
135 return $events if defined $events;
136 my ($legacy) = _events_as( \@lines, 1 );
137 if ( defined $legacy ) {
138 $kdl_version = 1;
139 return $legacy;
140 }
141 push @errors, $error;
142 return undef;
143 }
144  
145 # The parser reads one line per call of its source, so an event comes
146 # while its own line is the last one read.
147 sub _events_as ( $lines, $version ) {
148 my $read = 0;
149 my $source = sub { return $read < @$lines ? $lines->[ $read++ ] : undef };
150 my @events;
151 try {
152 my $parser = Text::KDL::XS::Parser->new( $source, version => $version, emit_comments => 1 );
153 while ( my $event = $parser->next_event ) {
154 push @events, { %$event, line => $read };
155 }
156 }
157 catch ($error) {
158 $error =~ s/\AKDL parse error: //;
159 return ( undef, { line => max( 1, $read ), message => 'KDL syntax: ' . _without_location($error) } );
160 }
161 return ( \@events );
162 }
163  
164 sub _without_location ($message) {
165 $message =~ s/\s+at \S+ line \d+\.?\n?\z//;
166 $message =~ s/\n\z//;
167 return $message;
168 }
169  
170 # ---------------------------------------------------------------------
171 # The tree
172 # ---------------------------------------------------------------------
173  
174 sub _value_of ($value) {
175 return { type => $value->type, value => $value->is_string ? $value->value : $value->as_string };
176 }
177  
178 # The nodes and comments of the events. A slashdashed node (/-) is an
179 # item of its own, kept with its content; slashdashed arguments and
180 # properties of a node are kept on the node (slashed). A comment on a
181 # block's closing line, after its last node, belongs to the block.
182 sub _tree ( $events, $lines ) {
183 my $document = { children => [] };
184 my @open = ($document);
185 foreach my $event (@$events) {
186 my ( $kind, $line ) = @{$event}{qw(event line)};
187 my $inside = $open[-1]{commented_scope};
188 if ( $kind eq 'comment' ) {
189 _add_comment( $open[-1], $event->{text}, $line );
190 next;
191 }
192 if ( $kind eq 'start_node' ) {
193 my $slashed = $event->{commented} && !$inside;
194 my $node = {
195 type => $slashed ? 'slashdash' : 'node',
196 name => $event->{name},
197 args => [],
198 props => [],
199 children => [],
200 first => $line,
201 last => $line,
202 commented_scope => $inside || $slashed ? 1 : 0,
203 };
204 push @{ $open[-1]{children} }, $node;
205 push @open, $node;
206 next;
207 }
208 if ( $kind eq 'argument' || $kind eq 'property' ) {
209 my $value = _value_of( $event->{value} );
210 my $entry = $kind eq 'argument' ? $value : [ $event->{name}, $value ];
211 if ( $event->{commented} && !$inside ) {
212 $value->{bare} = 1 if $kind eq 'property' && $event->{name} =~ /style\z/; # written as it most likely was
213 push @{ $open[-1]{slashed} }, [ $kind, $entry ];
214 next;
215 }
216 push @{ $open[-1]{ $kind eq 'argument' ? 'args' : 'props' } }, $entry;
217 next;
218 }
219 my $node = pop @open;
220 $node->{last} = $line;
221 my $kids = $node->{children};
222 my @closing;
223 unshift @closing, pop @$kids while @$kids && $kids->[-1]{type} eq 'comment' && $kids->[-1]{last} == $line && grep { $_->{type} ne 'comment' } @$kids;
224 $node->{closing_comment} = join ' ', map { $_->{text} } @closing if @closing;
225 }
226 return $document;
227 }
228  
229 # A comment on the line a node starts, before its children, belongs to
230 # the node (it follows the head); any other is an item of its own.
231 sub _add_comment ( $container, $comment, $line ) {
232 my $first = $line - ( $comment =~ tr/\n// );
233 if ( ( $container->{type} // '' ) eq 'node' && !@{ $container->{children} } && $first == $container->{first} && !defined $container->{comment} ) {
234 $container->{comment} = $comment;
235 return;
236 }
237 push @{ $container->{children} }, { type => 'comment', text => $comment, first => $first, last => $line };
238 return;
239 }
240  
241 # Records, for every item, the blank lines before it (gap), whether it
242 # shares a line with what comes before it, and whether it shares one
243 # with the head or the end of its container; and for every container,
244 # the blank lines before its end (tail). Lines between items that are
245 # not blank (a head spread over several lines) make the item share.
246 sub _measure ( $container, $lines, $start, $end ) {
247 my $previous_last = $start;
248 foreach my $item ( @{ $container->{children} } ) {
249 $item->{gap} = _blank_lines( $lines, $previous_last + 1, $item->{first} - 1 );
250 $item->{shares_line} = ( $item->{first} <= $previous_last || !defined $item->{gap} ) ? 1 : 0;
251 $item->{gap} //= '';
252 $item->{shares_parent} = ( $item->{first} <= $start || $item->{last} >= $end ) ? 1 : 0;
253 $previous_last = max( $previous_last, $item->{last} );
254 _measure( $item, $lines, $item->{first}, $item->{last} ) if $item->{type} ne 'comment';
255 }
256 $container->{tail} = _blank_lines( $lines, $previous_last + 1, $end - 1 );
257 $container->{tail_shares} = ( $previous_last >= $end || !defined $container->{tail} ) ? 1 : 0;
258 $container->{tail} //= '';
259 return;
260 }
261  
262 sub _blank_lines ( $lines, $from, $to ) {
263 my $blank = '';
264 foreach my $number ( $from .. $to ) {
265 my $line = $lines->[ $number - 1 ] // return undef;
266 return undef if $line =~ /\S/;
267 $blank .= $line;
268 }
269 return $blank;
270 }
271  
272 # The indentation of the first indented child line, if any.
273 sub _indent_unit ( $document, $lines ) {
274 foreach my $node ( grep { $_->{type} eq 'node' } @{ $document->{children} } ) {
275 my $child = first { !$_->{shares_line} } @{ $node->{children} } or next;
276 my ($indent) = $lines->[ $child->{first} - 1 ] =~ /\A([ \t]+)/;
277 return $indent if defined $indent;
278 }
279 return undef;
280 }
281  
282 # ---------------------------------------------------------------------
283 # The theme the tree describes: settings, checked, with their lines
284 # ---------------------------------------------------------------------
285  
286 method _error ( $item, $message ) {
287 push @errors, { line => $item->{first}, message => $message };
288 return;
289 }
290  
291 method _walk () {
292 my ( $theme_node, $palette_node );
293 my $children = $root->{children};
294 foreach my $index ( 0 .. $#$children ) {
295 my $node = $children->[$index];
296 next unless $node->{type} eq 'node';
297 my $name = $node->{name};
298 if ( $name eq 'theme' ) {
299 $theme_node ? $self->_error( $node, "the 'theme' node may appear only once" ) : $self->_walk_theme( $node, [$index] );
300 $theme_node = $node;
301 }
302 elsif ( $name eq 'palette' ) {
303 $palette_node ? $self->_error( $node, "the 'palette' node may appear only once" ) : $self->_walk_palette( $node, [$index] );
304 $palette_node = $node;
305 }
306 elsif ( !Term::Fabulous::Theme::is_family($name) ) {
307 $self->_error( $node, "unknown top-level node '$name' (known: theme, palette and the families " . join( ', ', Term::Fabulous::Theme::families() ) . ")" );
308 }
309 elsif ( @{ $node->{args} } || @{ $node->{props} } ) {
310 $self->_error( $node, "$name: a family node takes no arguments or properties" );
311 }
312 else {
313 $self->_walk_block( $node, $name, 'normal', undef, [$index] );
314 }
315 }
316 @errors = sort { $a->{line} <=> $b->{line} } @errors;
317 return;
318 }
319  
320 method _record ( $key, $value, $item, $path, $prop, %parts ) {
321 $setting{$key} = { %parts, key => $key, spec => $value->{type} eq 'null' ? 'none' : $value->{value}, line => $item->{first}, path => $path, prop => $prop };
322 push @setting_keys, $key;
323 return;
324 }
325  
326 method _walk_theme ( $node, $path ) {
327 my @args = @{ $node->{args} };
328 return $self->_error( $node, "the 'theme' node takes at most one argument, the theme's name" ) if @args > 1;
329 return $self->_error( $node, "the theme's name must be a string" ) if @args && $args[0]{type} ne 'string';
330 return $self->_error( $node, "the 'theme' node has no children" ) if any { $_->{type} eq 'node' } @{ $node->{children} };
331 foreach my $prop ( @{ $node->{props} } ) {
332 my ( $key, $value ) = @$prop;
333 return $self->_error( $node, "the 'theme' node knows only the property 'extends', got '$key'" ) unless $key eq 'extends';
334 return $self->_error( $node, "extends must be the name of a built-in theme (" . join( ', ', Term::Fabulous::Theme::builtin_names() ) . "), got " . _shown($value) )
335 unless $value->{type} eq 'string' && $IS_BASE{ $value->{value} };
336 }
337 $self->_record( 'theme.name', $args[0], $node, $path, undef, section => 'theme', field => 'name' ) if @args;
338 $self->_record( 'theme.extends', $_->[1], $node, $path, 'extends', section => 'theme', field => 'extends' ) foreach @{ $node->{props} };
339 return;
340 }
341  
342 sub _shown ($value) {
343 return $value->{type} eq 'string' ? "'$value->{value}'" : $value->{type} eq 'null' ? '#null' : $value->{value};
344 }
345  
346 method _walk_palette ( $node, $path ) {
347 return $self->_error( $node, "the 'palette' node takes no arguments or properties" ) if @{ $node->{args} } || @{ $node->{props} };
348 my $children = $node->{children};
349 foreach my $index ( grep { $children->[$_]{type} eq 'node' } 0 .. $#$children ) {
350 my $kid = $children->[$index];
351 my $error = _palette_error($kid) // ( exists $setting{"palette.$kid->{name}"} ? "palette: the token '$kid->{name}' is set twice" : undef );
352 if ( defined $error ) {
353 $self->_error( $kid, $error );
354 next;
355 }
356 $self->_record( "palette.$kid->{name}", $kid->{args}[0], $kid, [ @$path, $index ], undef, section => 'palette', token => $kid->{name} );
357 }
358 return;
359 }
360  
361 # What is wrong with a token node of the palette, or undef.
362 sub _palette_error ($kid) {
363 my $token = $kid->{name};
364 return "palette: unknown token '$token' (known: " . join( ', ', Term::Fabulous::Theme::tokens() ) . ")" unless $IS_TOKEN{$token};
365 my @args = @{ $kid->{args} };
366 return "palette token '$token' needs exactly one string argument"
367 unless @args == 1 && $args[0]{type} eq 'string' && !@{ $kid->{props} } && !any { $_->{type} eq 'node' } @{ $kid->{children} };
368 return _failure( sub { color( 'Term::Fabulous::Theme', "palette token $token", $args[0]{value} ) } );
369 }
370  
371 # The message of a check that dies, or undef when it passes.
372 sub _failure ($check) {
373 try {
374 $check->();
375 }
376 catch ($error) {
377 return _theme_message($error);
378 }
379 return undef;
380 }
381  
382 sub _theme_message ($error) {
383 $error = _without_location($error);
384 $error =~ s/\ATerm::Fabulous::Theme: //;
385 return $error;
386 }
387  
388 # The nodes of a family block, or of a state or variant block in it.
389 method _walk_block ( $block, $family, $state, $variant, $path ) {
390 my $children = $block->{children};
391 foreach my $index ( grep { $children->[$_]{type} eq 'node' } 0 .. $#$children ) {
392 my $kid = $children->[$index];
393 my $name = $kid->{name};
394 if ( $name eq 'variant' ) {
395 $self->_walk_variant( $kid, $family, $state, $variant, [ @$path, $index ] );
396 }
397 elsif ( !$IS_STATE{$name} ) {
398 $self->_walk_slot_node( $kid, $family, $state, $variant, [ @$path, $index ] );
399 }
400 elsif ( $state ne 'normal' ) {
401 $self->_error( $kid, "$family: a state cannot be inside another state" );
402 }
403 elsif ( @{ $kid->{args} } || @{ $kid->{props} } ) {
404 $self->_error( $kid, "$family: a state node takes no arguments or properties" );
405 }
406 else {
407 $self->_walk_block( $kid, $family, $name, $variant, [ @$path, $index ] );
408 }
409 }
410 return;
411 }
412  
413 method _walk_variant ( $node, $family, $state, $variant, $path ) {
414 return $self->_error( $node, "$family: a variant cannot be inside a state or another variant" ) if $state ne 'normal' || defined $variant;
415 my @args = @{ $node->{args} };
416 return $self->_error( $node, "$family: a variant needs exactly one string argument" ) unless @args == 1 && $args[0]{type} eq 'string' && !@{ $node->{props} };
417 my $name = $args[0]{value};
418 return $self->_error( $node, "$family: a variant name must be a word" ) unless $name =~ /\A[A-Za-z0-9_-]+\z/;
419 $variant_line{"$family\[$name]"} //= $node->{first};
420 $self->_walk_block( $node, $family, 'normal', $name, $path );
421 return;
422 }
423  
424 method _walk_slot_node ( $node, $family, $state, $variant, $path ) {
425 my $name = $node->{name};
426 my @args = @{ $node->{args} };
427 my @props = @{ $node->{props} };
428 return $self->_error( $node, "$family: the node '$name' has no children" ) if any { $_->{type} eq 'node' } @{ $node->{children} };
429 return $self->_error( $node, "$family: the node '$name' needs either one value or key=value properties" ) if ( @args && @props ) || ( !@args && !@props ) || @args > 1;
430  
431 my $where = defined $variant ? "$family: variant '$variant': " : "$family: ";
432 my @pairs = @args ? ( [ $name, $args[0], undef ] ) : map { [ "$name.$_->[0]", $_->[1], $_->[0] ] } @props;
433 foreach my $pair (@pairs) {
434 my ( $slot_name, $value, $prop ) = @$pair;
435 my $full = $state eq 'normal' ? $slot_name : "$slot_name.$state";
436 my ( $slot, $slot_state );
437 my $error = _failure( sub { ( $slot, $slot_state ) = _slot_and_state( $family, $full ) } );
438 $error = defined $error ? ( defined $variant ? "variant '$variant': " : '' ) . $error : _value_error( $family, $slot, $slot_state, $slot_name, $value );
439 my $key = defined $error ? undef : key_for( family => $family, variant => $variant, slot => $slot, state => $slot_state );
440 $error //= "${where}the slot '$full' is set twice" if defined $key && exists $setting{$key};
441 if ( defined $error ) {
442 $self->_error( $node, $error );
443 next;
444 }
445  
446 $value->{bare} = 1 if Term::Fabulous::Theme::slot_info( $family, $slot )->{kind} eq 'style';
447 push @variant_names, "$family\[$variant]" if defined $variant && !grep { $_ eq "$family\[$variant]" } @variant_names;
448 $self->_record( $key, $value, $node, $path, $prop, section => 'slot', family => $family, variant => $variant, slot => $slot, state => $slot_state );
449 }
450 return;
451 }
452  
453 # What is wrong with the value of a slot, or undef: a boolean slot
454 # takes #true or #false, every other slot a string or #null.
455 sub _value_error ( $family, $slot, $state, $slot_name, $value ) {
456 my $wanted = Term::Fabulous::Theme::slot_info( $family, $slot )->{kind} eq 'boolean' ? 'bool' : 'string';
457 return "$family.$slot_name must be " . ( $wanted eq 'bool' ? '#true or #false' : 'a string or #null' ) unless $value->{type} eq $wanted || $value->{type} eq 'null';
458 return _failure( sub { Term::Fabulous::Theme::check_value( $family, $slot, $state, $value->{type} eq 'null' ? undef : $value->{value} ) } );
459 }
460  
461 # ( slot, state ) of "slot" or "slot.state" in a family.
462 sub _slot_and_state ( $family, $name ) {
463 return ( $name, 'normal' ) if Term::Fabulous::Theme::has_slot( $family, $name );
464 if ( my ( $slot, $state ) = $name =~ /\A(.+)\.([a-z]+)\z/ ) {
465 if ( Term::Fabulous::Theme::has_slot( $family, $slot ) ) {
466 my $states = Term::Fabulous::Theme::slot_info( $family, $slot )->{states};
467 die "the slot $family.$slot has no state '$state' (" . ( @$states ? 'its states: ' . join( ', ', @$states ) : 'it has the normal state only' ) . ")\n"
468 unless grep { $_ eq $state } 'normal', @$states;
469 return ( $slot, $state );
470 }
471 }
472 my %slots = Term::Fabulous::Theme::slots($family);
473 die "the family $family has no slot '$name' (known: " . join( ', ', sort keys %slots ) . ")\n";
474 }
475  
476 # ---------------------------------------------------------------------
477 # Keys
478 # ---------------------------------------------------------------------
479  
480 sub key_for (%parts) {
481 return "theme.$parts{field}" if defined $parts{field};
482 return "palette.$parts{token}" if defined $parts{token};
483 my $state = $parts{state} // 'normal';
484 return $parts{family} . ( defined $parts{variant} ? "[$parts{variant}]" : '' ) . ".$parts{slot}" . ( $state eq 'normal' ? '' : ".$state" );
485 }
486  
487 sub parse_key ($key) {
488 die "Term::Fabulous::Theme::Document: a setting key must be a string, got " . describe($key) unless defined $key && !ref $key;
489 return { section => 'theme', field => $1 } if $key =~ /\Atheme\.(name|extends)\z/;
490 if ( $key =~ /\Apalette\.(.+)\z/ ) {
491 die "Term::Fabulous::Theme::Document: '$key' names an unknown token (known: " . join( ', ', Term::Fabulous::Theme::tokens() ) . ")\n" unless $IS_TOKEN{$1};
492 return { section => 'palette', token => $1 };
493 }
494 my ( $family, $variant, $rest ) = $key =~ /\A([a-z_]+)(?:\[([A-Za-z0-9_-]+)\])?\.(.+)\z/
495 or die "Term::Fabulous::Theme::Document: '$key' is not a setting key (theme.name, theme.extends, palette.TOKEN, FAMILY.SLOT[.STATE] or FAMILY[VARIANT].SLOT[.STATE])\n";
496 die "Term::Fabulous::Theme::Document: '$key' names an unknown family '$family' (known: " . join( ', ', Term::Fabulous::Theme::families() ) . ")\n"
497 unless Term::Fabulous::Theme::is_family($family);
498 my ( $slot, $state );
499 try {
500 ( $slot, $state ) = _slot_and_state( $family, $rest );
501 }
502 catch ($error) {
503 die "Term::Fabulous::Theme::Document: '$key': $error";
504 }
505 return { section => 'slot', family => $family, variant => $variant, slot => $slot, state => $state };
506 }
507  
508 # ---------------------------------------------------------------------
509 # Reading
510 # ---------------------------------------------------------------------
511  
512 method errors () {
513 $self->theme; # a theme the walk let through but Term::Fabulous::Theme rejects adds its error
514 return map {
515 { %$_ }
516 } @errors;
517 }
518  
519 method is_valid () {
520 return @errors ? 0 : defined $self->theme ? 1 : 0;
521 }
522  
523 method has_syntax_error () {
524 return defined $root ? 0 : 1;
525 }
526  
527 # Built from the text by Term::Fabulous::Theme itself, once, when first
528 # asked for: what a program that loads the file gets.
529 method theme () {
530 return $theme if $theme_built;
531 $theme_built = 1;
532 return undef if @errors;
533 try {
534 $theme = Term::Fabulous::Theme->from_string($text);
535 }
536 catch ($error) {
537 $error = _without_location($error);
538 $error =~ s/\ATerm::Fabulous::Theme: theme: //;
539 push @errors, { line => 1, message => $error };
540 }
541 return $theme;
542 }
543  
544 method name () {
545 return $self->setting('theme.name');
546 }
547  
548 method extends () {
549 return $self->setting('theme.extends') // 'dark';
550 }
551  
552 method kdl_version () {
553 return $kdl_version;
554 }
555  
556 method setting ($key) {
557 my $info = $setting{ key_for( %{ parse_key($key) } ) } // return undef;
558 return $info->{spec};
559 }
560  
561 method setting_keys () {
562 return @setting_keys;
563 }
564  
565 method line_of ($key) {
566 return $variant_line{$key} if $key =~ /\A[a-z_]+\[[A-Za-z0-9_-]+\]\z/;
567 my $info = $setting{ key_for( %{ parse_key($key) } ) } // return undef;
568 return $info->{line};
569 }
570  
571 method variants () {
572 return map { [/\A([a-z_]+)\[(.+)\]\z/] } @variant_names;
573 }
574  
575 # What a setting is worth when the document does not set it, and where
576 # that comes from: the base theme (dark or light) for a palette token,
577 # the vocabulary's default for a slot, the normal state for a state
578 # that looks like it, the family for a variant.
579 method effective_setting ($key) {
580 my $parsed = parse_key($key);
581 $key = key_for(%$parsed);
582 return { spec => $setting{$key}{spec}, origin => 'set' } if exists $setting{$key};
583 my $section = $parsed->{section};
584 if ( $section eq 'theme' ) {
585 return { spec => undef, origin => 'default' } if $parsed->{field} eq 'name';
586 return { spec => 'dark', origin => 'default' };
587 }
588 if ( $section eq 'palette' ) {
589 my $base = $self->extends;
590 return { spec => _hex( Term::Fabulous::Theme->builtin($base)->token( $parsed->{token} ) ), origin => $base };
591 }
592 my ( $family, $variant, $slot, $state ) = @{$parsed}{qw(family variant slot state)};
593 if ( defined $variant ) {
594 my $of_family = $self->effective_setting( key_for( family => $family, slot => $slot, state => $state ) );
595 return { spec => $of_family->{spec}, origin => 'family' } if $state eq 'normal' || $of_family->{origin} ne 'normal';
596 return { spec => $self->effective_setting( key_for( family => $family, variant => $variant, slot => $slot ) )->{spec}, origin => 'normal' };
597 }
598 my $default = Term::Fabulous::Theme::slot_info( $family, $slot )->{default}{$state};
599 return { spec => $default, origin => 'default' } unless $default eq 'normal';
600 return { spec => $self->effective_setting( key_for( family => $family, slot => $slot ) )->{spec}, origin => 'normal' };
601 }
602  
603 sub _hex ($rgba) {
604 my ( $red, $green, $blue, $alpha ) = @$rgba;
605 return sprintf( '#%02x%02x%02x', $red, $green, $blue ) if $alpha == 255;
606 return sprintf( '#%02x%02x%02x%02x', $red, $green, $blue, $alpha );
607 }
608  
609 # ---------------------------------------------------------------------
610 # Changing: every change returns a new document
611 # ---------------------------------------------------------------------
612  
613 method _require_tree ($what) {
614 return if defined $root;
615 my $error = $errors[0];
616 die "Term::Fabulous::Theme::Document: $what needs a document that is valid KDL; line $error->{line}: $error->{message}\n";
617 }
618  
619 method with_setting ( $key, $value ) {
620 $self->_require_tree('with_setting');
621 my $parsed = parse_key($key);
622 my $spec = _checked_spec( $parsed, $value );
623 my $tree = dclone($root);
624 my $info = $setting{ key_for(%$parsed) };
625 defined $info ? _replace_value( $tree, $info, $spec ) : $self->_insert_setting( $tree, $parsed, $spec );
626 return $self->_changed_to($tree);
627 }
628  
629 method without_setting ($key) {
630 $self->_require_tree('without_setting');
631 my $info = $setting{ key_for( %{ parse_key($key) } ) } // return $self;
632 my $tree = dclone($root);
633 _remove_setting( $tree, $info );
634 return $self->_changed_to($tree);
635 }
636  
637 # Applies several changes in order; undef as a value removes the
638 # setting.
639 method with_settings ($changes) {
640 die "Term::Fabulous::Theme::Document: with_settings needs an array reference of [ key, value ] pairs, got " . describe($changes) unless ref $changes eq 'ARRAY';
641 my $document = $self;
642 foreach my $change (@$changes) {
643 die "Term::Fabulous::Theme::Document: with_settings: a change must be [ key, value ], got " . describe($change) unless ref $change eq 'ARRAY' && @$change == 2;
644 my ( $key, $value ) = @$change;
645 $document = defined $value ? $document->with_setting( $key, $value ) : $document->without_setting($key);
646 }
647 return $document;
648 }
649  
650 method without_variant ( $family, $variant ) {
651 $self->_require_tree('without_variant');
652 die "Term::Fabulous::Theme::Document: unknown family " . describe($family) unless Term::Fabulous::Theme::is_family($family);
653 my $tree = dclone($root);
654 my $removed = 0;
655 foreach my $block ( grep { $_->{type} eq 'node' && $_->{name} eq $family } @{ $tree->{children} } ) {
656 my @indexes = grep { _is_variant( $block->{children}[$_], $variant ) } 0 .. $#{ $block->{children} };
657 $removed += @indexes;
658 _remove_item( $block, $_ ) foreach reverse @indexes;
659 }
660 return $self unless $removed;
661 _prune_empty( $tree, [] );
662 return $self->_changed_to($tree);
663 }
664  
665 # The document of a changed tree. A change never makes a text worse: one
666 # that would leave a syntax error or more errors than the text had dies
667 # (a bug in the writer, reported before anything is written).
668 method _changed_to ($tree) {
669 my $changed = __CLASS__->new( text => $self->_render($tree) );
670 my @before = $self->errors;
671 my @after = $changed->errors;
672 return $changed unless $changed->has_syntax_error || @after > @before;
673 die "Term::Fabulous::Theme::Document: internal error: the change would break the text ("
674 . join( '; ', map { "line $_->{line}: $_->{message}" } @after[ 0 .. 0 ] )
675 . "); the document is left as it was\n";
676 }
677  
678 sub _is_variant ( $item, $variant ) {
679 return $item->{type} eq 'node' && $item->{name} eq 'variant' && @{ $item->{args} } && $item->{args}[0]{value} eq $variant;
680 }
681  
682 # The value as the file will hold it, checked as the theme checks it.
683 sub _checked_spec ( $parsed, $value ) {
684 die "Term::Fabulous::Theme::Document: a setting needs a string value (use without_setting to remove one), got " . describe($value) unless defined $value && !ref $value;
685 my $section = $parsed->{section};
686 if ( $section eq 'theme' ) {
687 die "Term::Fabulous::Theme::Document: theme.extends must be the name of a built-in theme (" . join( ', ', Term::Fabulous::Theme::builtin_names() ) . "), got '$value'\n"
688 if $parsed->{field} eq 'extends' && !$IS_BASE{$value};
689 return { type => 'string', value => $value };
690 }
691 my $checked;
692 try {
693 $checked
694 = $section eq 'palette'
695 ? color( 'Term::Fabulous::Theme', "palette token $parsed->{token}", $value )
696 : Term::Fabulous::Theme::check_value( @{$parsed}{qw(family slot state)}, $value );
697 }
698 catch ($error) {
699 die "Term::Fabulous::Theme::Document: " . _theme_message($error) . "\n";
700 }
701 my $kind = $section eq 'slot' ? Term::Fabulous::Theme::slot_info( @{$parsed}{qw(family slot)} )->{kind} : 'color';
702 return { type => 'bool', value => $checked } if $kind eq 'boolean'; # 'true' or 'false'
703 return { type => 'string', value => $value, ( $kind eq 'style' ? ( bare => 1 ) : () ) };
704 }
705  
706 sub _item_at ( $tree, $path ) {
707 my $item = $tree;
708 $item = $item->{children}[$_] foreach @$path;
709 return $item;
710 }
711  
712 sub _replace_value ( $tree, $info, $spec ) {
713 my $node = _item_at( $tree, $info->{path} );
714 if ( defined $info->{prop} ) {
715 $_->[1] = $spec foreach grep { $_->[0] eq $info->{prop} } @{ $node->{props} };
716 }
717 else {
718 $node->{args}[0] = $spec;
719 }
720 $node->{dirty} = 1;
721 return;
722 }
723  
724 sub _new_node ( $name, %parts ) {
725 return {
726 type => 'node', name => $name, args => $parts{args} // [], props => $parts{props} // [], children => [], gap => $parts{gap} // '', shares_line => 0, tail => '',
727 block => $parts{block} // 0
728 };
729 }
730  
731 sub _first_node_named ( $container, $name, $test = sub { 1 } ) {
732 return first { $_->{type} eq 'node' && $_->{name} eq $name && $test->($_) } @{ $container->{children} };
733 }
734  
735 # Puts an item into a container at an index; the container has changed.
736 sub _insert_item ( $container, $index, $item ) {
737 splice @{ $container->{children} }, $index, 0, $item;
738 $container->{changed} = 1;
739 return $item;
740 }
741  
742 # The index before the leading comments of the first node: where a
743 # theme or palette node goes at the top of a document.
744 sub _top_index ($tree) {
745 my $children = $tree->{children};
746 my $index = first { $children->[$_]{type} eq 'node' } 0 .. $#$children;
747 return scalar @$children unless defined $index;
748 $index-- while $index > 0 && _is_attached_comment( $children, $index - 1 );
749 return $index;
750 }
751  
752 # A comment on lines of its own right above the next item, with no
753 # blank line between: it belongs to that item.
754 sub _is_attached_comment ( $children, $index ) {
755 my ( $comment, $next ) = @{$children}[ $index, $index + 1 ];
756 return 0 unless defined $next && $comment->{type} eq 'comment';
757 return !$comment->{shares_line} && !$next->{shares_line} && $next->{gap} eq '' ? 1 : 0;
758 }
759  
760 # Inserts a top-level node, separated by a blank line from its
761 # neighbors.
762 sub _insert_top ( $tree, $index, $node ) {
763 my $children = $tree->{children};
764 $node->{gap} = $index > 0 ? "\n" : '';
765 my $next = $children->[$index];
766 $next->{gap} = "\n" if defined $next && $next->{gap} eq '' && !$next->{shares_line};
767 return _insert_item( $tree, $index, $node );
768 }
769  
770 method _insert_setting ( $tree, $parsed, $spec ) {
771 my $section = $parsed->{section};
772 if ( $section eq 'theme' ) {
773 my $node = _first_node_named( $tree, 'theme' );
774 if ( !defined $node ) {
775 $node = _insert_top( $tree, _top_index($tree), _new_node('theme') );
776 }
777 $parsed->{field} eq 'name' ? unshift( @{ $node->{args} }, $spec ) : push( @{ $node->{props} }, [ extends => $spec ] );
778 $node->{dirty} = 1;
779 return;
780 }
781 if ( $section eq 'palette' ) {
782 my $palette = _first_node_named( $tree, 'palette' );
783 if ( !defined $palette ) {
784 my $theme_node = first { $tree->{children}[$_]{type} eq 'node' && $tree->{children}[$_]{name} eq 'theme' } 0 .. $#{ $tree->{children} };
785 $palette = _insert_top( $tree, defined $theme_node ? $theme_node + 1 : _top_index($tree), _new_node( 'palette', block => 1 ) );
786 }
787 _insert_item( $palette, _end_index($palette), _new_node( $parsed->{token}, args => [$spec] ) );
788 return;
789 }
790  
791 my ( $family, $variant, $slot, $state ) = @{$parsed}{qw(family variant slot state)};
792 my $target = _first_node_named( $tree, $family ) // _insert_top( $tree, scalar @{ $tree->{children} }, _new_node( $family, block => 1 ) );
793 $target = _first_node_named( $target, 'variant', sub ($node) { _is_variant( $node, $variant ) } )
794 // _insert_item( $target, _end_index($target), _new_node( 'variant', args => [ { type => 'string', value => $variant } ], block => 1 ) )
795 if defined $variant;
796 $target = _first_node_named( $target, $state, sub ($node) { !@{ $node->{args} } && !@{ $node->{props} } } )
797 // _insert_item( $target, _index_before( $target, sub ($name) { $name eq 'variant' } ), _new_node( $state, block => 1 ) )
798 unless $state eq 'normal';
799  
800 if ( my ( $head, $key ) = $slot =~ /\A(.+)\.([^.]+)\z/ ) {
801 my $grouped = _first_node_named( $target, $head, sub ($node) { !@{ $node->{args} } && @{ $node->{props} } } );
802 if ( defined $grouped ) {
803 push @{ $grouped->{props} }, [ $key, $spec ];
804 $grouped->{dirty} = 1;
805 return;
806 }
807 _insert_item( $target, _index_before( $target, \&_is_block_name ), _new_node( $head, props => [ [ $key, $spec ] ] ) );
808 return;
809 }
810 _insert_item( $target, _index_before( $target, \&_is_block_name ), _new_node( $slot, args => [$spec] ) );
811 return;
812 }
813  
814 # After the last item of a container.
815 sub _end_index ($container) {
816 return scalar @{ $container->{children} };
817 }
818  
819 sub _is_block_name ($name) {
820 return $IS_STATE{$name} || $name eq 'variant' ? 1 : 0;
821 }
822  
823 # Where a new item goes in a block: before the first node whose name
824 # passes the test (and the comments attached to it), else at the end.
825 # Slots go before the state and variant blocks, states before the
826 # variants.
827 sub _index_before ( $container, $test ) {
828 my $children = $container->{children};
829 my $index = first { $children->[$_]{type} eq 'node' && $test->( $children->[$_]{name} ) } 0 .. $#$children;
830 return scalar @$children unless defined $index;
831 $index-- while $index > 0 && _is_attached_comment( $children, $index - 1 );
832 return $index;
833 }
834  
835 sub _remove_setting ( $tree, $info ) {
836 my @path = @{ $info->{path} };
837 my $node = _item_at( $tree, \@path );
838 my $parent = _item_at( $tree, [ @path[ 0 .. $#path - 1 ] ] );
839 if ( defined $info->{prop} ) {
840 $node->{props} = [ grep { $_->[0] ne $info->{prop} } @{ $node->{props} } ];
841 }
842 elsif ( ( $info->{section} // '' ) eq 'theme' ) {
843 shift @{ $node->{args} };
844 }
845 else {
846 $node->{args} = [];
847 }
848 $node->{dirty} = 1;
849 _remove_item( $parent, $path[-1] ) unless @{ $node->{args} } || @{ $node->{props} };
850 _prune_empty( $tree, [] );
851 return;
852 }
853  
854 # Removes an item with the comments attached to it.
855 sub _remove_item ( $container, $index ) {
856 my $children = $container->{children};
857 my $from = $index;
858 $from-- while $from > 0 && _is_attached_comment( $children, $from - 1 );
859 my $next = $children->[ $index + 1 ];
860 $next->{gap} = $children->[$from]{gap} if defined $next && $from == 0 && !$next->{shares_line};
861  
862 # Neighbors that shared a line with the removed items cannot copy
863 # that line any more.
864 $children->[ $from - 1 ]{dirty} = 1 if $from > 0 && $children->[$from]{shares_line};
865 $next->{dirty} = 1 if defined $next && $next->{shares_line};
866 splice @$children, $from, $index - $from + 1;
867 $container->{changed} = 1;
868 return $from;
869 }
870  
871 # Removes palette, family, state and variant blocks that hold nothing
872 # any more (a block with a comment or a slashdashed node stays).
873 sub _prune_empty ( $container, $path ) {
874 my $children = $container->{children};
875 my $index = $#$children;
876 while ( $index >= 0 ) {
877 my $item = $children->[$index];
878 if ( $item->{type} eq 'node' && _is_block( $item, $path ) ) {
879 _prune_empty( $item, [ @$path, $item->{name} ] );
880 $index = _remove_item( $container, $index ) unless @{ $item->{children} };
881 }
882 $index--;
883 }
884 return;
885 }
886  
887 # Palette and family nodes at the top, state and variant nodes inside
888 # them, are blocks; a theme node and slot nodes are not.
889 sub _is_block ( $node, $path ) {
890 my $name = $node->{name};
891 return $name eq 'palette' || Term::Fabulous::Theme::is_family($name) ? 1 : 0 unless @$path;
892 return 0 if $path->[0] eq 'palette';
893 return $IS_STATE{$name} || $name eq 'variant' ? 1 : 0;
894 }
895  
896 # ---------------------------------------------------------------------
897 # Writing: untouched lines are copied, changed nodes written anew
898 # ---------------------------------------------------------------------
899  
900 method _render ($tree) {
901 return $self->_render_items( $tree, 0 );
902 }
903  
904 sub _is_pristine ($item) {
905 return 0 unless defined $item->{first};
906 return 0 if $item->{dirty} || $item->{changed};
907 return 1 if $item->{type} eq 'comment';
908 return _all_pristine( $item->{children} );
909 }
910  
911 sub _all_pristine ($items) {
912 return ( any { !_is_pristine($_) } @$items ) ? 0 : 1;
913 }
914  
915 method _source ( $from, $to ) {
916 return join '', @lines[ $from - 1 .. $to - 1 ];
917 }
918  
919 # The children of a container: runs of items that share lines are
920 # copied as they were when nothing in them changed.
921 method _render_items ( $container, $depth ) {
922 my $children = $container->{children};
923 my $out = '';
924 my $index = 0;
925 while ( $index < @$children ) {
926 my $last = $index;
927 $last++ while $last + 1 < @$children && $children->[ $last + 1 ]{shares_line};
928 my @run = @{$children}[ $index .. $last ];
929 my $whole_lines = !$run[0]{shares_line} && !any { $_->{shares_parent} } @run;
930 if ( $whole_lines && _all_pristine( \@run ) ) {
931 $out .= $run[0]{gap} . $self->_source( $run[0]{first}, max map { $_->{last} } @run );
932 }
933 else {
934 # Items that share lines are written anew, each on its own;
935 # copying their lines would copy their neighbors too.
936 $out .= $run[0]{gap};
937 $out .= $self->_render_item( $_, $depth, $whole_lines && @run == 1 ) foreach @run;
938 }
939 $index = $last + 1;
940 }
941 $out .= $container->{tail} unless $container->{tail_shares};
942 return $out;
943 }
944  
945 # An item, from its source lines when it owns them and did not change,
946 # else written anew.
947 method _render_item ( $item, $depth, $owns_lines ) {
948 my $indent = $indent_unit x $depth;
949 return $self->_source( $item->{first}, $item->{last} ) if $owns_lines && _is_pristine($item);
950 return $indent . $item->{text} . $newline if $item->{type} eq 'comment';
951  
952 my $comment = defined $item->{comment} ? " $item->{comment}" : '';
953 my $closing = defined $item->{closing_comment} ? " $item->{closing_comment}" : '';
954 my $head = $indent . $self->_node_head($item);
955 my $has_kids = @{ $item->{children} } ? 1 : 0;
956 return $head . $comment . $newline unless $has_kids || $item->{block};
957 return $head . " {$comment$newline" . $indent . "}$closing$newline" unless $has_kids;
958 return $indent . $self->_one_line($item) . $newline if defined $item->{first} && $item->{first} == $item->{last}; # with its comments
959 return $self->_source( $item->{first}, $item->{first} ) . $self->_render_items( $item, $depth + 1 ) . $self->_source( $item->{last}, $item->{last} )
960 if $self->_keeps_frame($item);
961 return $head . " {$comment$newline" . $self->_render_items( $item, $depth + 1 ) . $indent . "}$closing$newline";
962 }
963  
964 # A node whose own head did not change keeps its head line and its
965 # closing line when they hold nothing else.
966 method _keeps_frame ($node) {
967 return 0 if $node->{dirty} || !defined $node->{first} || $node->{first} == $node->{last} || $node->{shares_line} || $node->{shares_parent};
968 my $children = $node->{children};
969 return 0 if @$children && ( $children->[0]{shares_line} || $node->{tail_shares} );
970 return 0 unless $lines[ $node->{first} - 1 ] =~ /\{\s*(?:\/\/.*)?\R?\z/;
971 return 0 unless $lines[ $node->{last} - 1 ] =~ /\A\s*\}\s*(?:\/\/.*|\/\*.*\*\/\s*)?\R?\z/;
972 return 1;
973 }
974  
975 # A block that was written on one line stays on one line, with its
976 # block comments and slashdashed nodes.
977 method _one_line ($node) {
978 my @kids = grep { $_->{type} ne 'comment' || $_->{text} =~ m{\A/\*} } @{ $node->{children} };
979 my $head = $self->_node_head($node) . ( defined $node->{comment} && $node->{comment} =~ m{\A/\*} ? " $node->{comment}" : '' );
980 my $end = defined $node->{closing_comment} ? " $node->{closing_comment}" : '';
981 return $head . $end unless @kids || $node->{block};
982  
983 # A node ends with ; before whatever follows it; a comment needs no ;.
984 my ( $inside, $after_node ) = ( '', 0 );
985 foreach my $kid (@kids) {
986 my $is_comment = $kid->{type} eq 'comment';
987 $inside .= ( $after_node ? '; ' : length $inside ? ' ' : '' ) . ( $is_comment ? $kid->{text} : $self->_one_line($kid) );
988 $after_node = !$is_comment;
989 }
990 return "$head { $inside }$end";
991 }
992  
993 method _node_head ($node) {
994 my @slashed = map { $_->[0] eq 'argument' ? '/-' . $self->_value( $_->[1] ) : '/-' . _name( $_->[1][0] ) . '=' . $self->_value( $_->[1][1] ) } @{ $node->{slashed} // [] };
995 return ( $node->{type} eq 'slashdash' ? '/-' : '' ) . join ' ', _name( $node->{name} ), ( map { $self->_value($_) } @{ $node->{args} } ),
996 ( map { _name( $_->[0] ) . '=' . $self->_value( $_->[1] ) } @{ $node->{props} } ), @slashed;
997 }
998  
999 sub _is_bare_word ($word) {
1000 return $word =~ /\A[A-Za-z_][A-Za-z0-9_.\-]*\z/ && !$KEYWORD{$word} ? 1 : 0;
1001 }
1002  
1003 sub _name ($word) {
1004 return _is_bare_word($word) ? $word : _quoted($word);
1005 }
1006  
1007 method _value ($value) {
1008 my $type = $value->{type};
1009 return $kdl_version == 1 ? 'null' : '#null' if $type eq 'null';
1010 return ( $kdl_version == 1 ? '' : '#' ) . $value->{value} if $type eq 'bool';
1011 return $value->{value} if $type eq 'number';
1012 return $value->{value} if $value->{bare} && $kdl_version == 2 && _is_bare_word( $value->{value} );
1013 return _quoted( $value->{value} );
1014 }
1015  
1016 my %ESCAPE = ( "\\" => "\\\\", '"' => '\\"', "\n" => '\\n', "\r" => '\\r', "\t" => '\\t', "\b" => '\\b', "\f" => '\\f' );
1017  
1018 sub _quoted ($string) {
1019 ( my $escaped = $string ) =~ s/(["\\\n\r\t\b\f])/$ESCAPE{$1}/g;
1020 $escaped =~ s/([\x00-\x1F\x7F])/sprintf('\\u{%x}', ord $1)/ge;
1021 return qq{"$escaped"};
1022 }
1023 }
1024  
1025 1;
1026  
1027 __END__