Style.pm untested

filter: Statementstmt 0.0% 0 / 160 Branchbran 0.0% 0 / 22 Conditioncond 0.0% 0 / 30 MC/DCmcdc 0.0% 0 / 16 Subroutinesub 0.0% 0 / 26 Podpod 0.0% 0 / 14 totaltotal 0.0% 0 / 268 CC 9 SCAR 26.1
CC
9
Cov
0%
import
56.0
_ref_tagset
6.0
style_definition
6.0
CRAP 13.6
1 # You may distribute under the terms of either the GNU General Public License
2 # or the Artistic License (the same terms as Perl itself)
3 #
4 # (C) Paul Evans, 2013-2024 -- leonerd@leonerd.org.uk
5  
6 use v5.20;
7 use warnings;
8 use Object::Pad 0.805;
9  
10 package Tickit::Style 0.60;
11  
12 use warnings;
13 use experimental 'postderef';
14  
15 use meta 0.008;
16 no warnings 'meta::experimental';
17  
18 use Carp;
19  
20 use Tickit::Pen;
21 use Tickit::Style::Parser;
22  
23 our @EXPORTS = qw(
24 style_definition
25 style_reshape_keys
26 style_reshape_textwidth_keys
27 style_redraw_keys
28 );
29  
30 # {$type}->{$class} = $tagset
31 my %TAGSETS_BY_TYPE_CLASS;
32  
33 # {$type}->{$key} = 1
34 my %RESHAPE_KEYS;
35 my %RESHAPE_TEXTWIDTH_KEYS;
36 my %REDRAW_KEYS;
37  
38 =head1 NAME
39  
40 C<Tickit::Style> - declare customisable style information on widgets
41  
42 =head1 SYNOPSIS
43  
44 package My::Widget::Class
45 use base qw( Tickit::Widget );
46 use Tickit::Style;
47  
48 style_definition base =>
49 fg => "red";
50  
51 style_definition ':active' =>
52 b => 1;
53  
54 ...
55  
56 sub render_to_rb
57 {
58 my $self = shift;
59 my ( $rb, $rect ) = @_;
60  
61 $rb->text_at( 0, 0, "Here is my text", $self->get_style_pen );
62 }
63  
64 Z<>
65  
66 use My::Widget::Class;
67  
68 my $w = My::Widget::Class->new(
69 class => "another-class",
70 );
71  
72 ...
73  
74 =head1 DESCRIPTION
75  
76 This module adds the ability to a L<Tickit::Widget> class to declare a set of
77 named keys that take values, and provides convenient accessors for the widget
78 to determine what the values are at any given moment in time. The values
79 currently in effect are determined by the widget class code, and any
80 stylesheet files loaded by the application.
81  
82 The widget itself can store a set of tags; named entities that may be present
83 or absent. The set of tags currently active on a widget helps to determine
84 which definitions style are to be used.
85  
86 Finally, the widget itself stores a list of style class names. These classes
87 also help determine which style definitions from a loaded stylesheet file are
88 applied.
89  
90 =head2 Stylesheet Files
91  
92 A stylesheet file contains a list of definitions of styles. Each definition
93 gives a C<Tickit::Widget> class name, optionally a style class name prefixed
94 by a period (C<.>), optionally a set of tags prefixed with colons (C<:>), and
95 a body definition in a brace-delimited (C<{}>) block. Comments can appear
96 anywhere that whitespace is allowed, starting with a hash symbol (C<#>) and
97 continuing to the end of the line.
98  
99 WidgetClass {
100 # basic style goes here
101 }
102  
103 WidgetClass.styleclass {
104 # style to apply for this class goes here
105 }
106  
107 WidgetClass:tag {
108 # style to apply when this tag is active goes here
109 }
110  
111 Each style definition contains a set semicolon-delimited (C<;>) assignments of
112 values to keys. Each key is suffixed by a colon (C<:>), and the values may be
113 integers, quoted strings (C<"...">), or the special identifiers C<true> or
114 C<false>.
115  
116 WidgetClass.styleclass {
117 key1: "value 1";
118 key2: 123;
119 key3: true;
120 }
121  
122 While it is more traditional for keys in stylesheet files to contain hyphens
123 (C<->), it is more convenient in Perl code to use underscores (C<_>) instead.
124 The parser will convert hyphens in key names into underscores.
125  
126 As well as giving visual styling information, stylesheets can also associate
127 behavioural actions with keypresses. These are given by a keypress key name in
128 angle brackets (C<< <NAME> >>) and an action name, which is a bareword
129 identifier.
130  
131 WidgetClass {
132 <Enter>: activate;
133 }
134  
135 A special widget type name of C<*> can also be used to provide style blocks
136 that will apply (at lower priority) to any type of widget. Typically these
137 would be used along with classes or tags, to set application-wide styles.
138  
139 *:error {
140 bg: "red";
141 fg: "hi-white";
142 }
143  
144 =head2 How Style is Determined
145  
146 The full set of style definitions applied to one named class of one widget
147 type for all its style tags is called a "tagset". Each tagset consists of a
148 partially-ordered list of entities called "keysets", which give a mapping from
149 style keys to values for one particular set of active style tags. The widget
150 may also have a special tagset containing the "direct-applied" style
151 definition given to the constructor.
152  
153 The style at any given moment is determined by taking into account the style
154 classes and tags that are in effect. The value of each key is determined by a
155 first-match-wins search along the "direct applied" tagset (if present), then
156 the tagset for each of the style classes, in order, followed finally by the
157 base tagset for the widget type without class.
158  
159 Within each tagset, only the keysets that do not depend on a style tag that is
160 inactive are considered. That is, a keyset that depends on no tags will always
161 be considered, and any keyset that only depends on active keys will be
162 considered, even if there are other active tags that the keyset does not
163 consider. Tags are always additive, in this regard.
164  
165 While the order of the tagsets is exactly defined by the order of the style
166 classes applied to the widget, the order of keysets within each tagset is not
167 fully specified. Tagsets are stored partially ordered, sorted by the number of
168 style tags that each keyset depends on. This ensures that more specific
169 keysets are found before, and therefore override, less specific ones. However,
170 it is not defined the ordering of keysets with equal numbers of (distinct)
171 tags.
172  
173 For instance, if both C<tag1> and C<tag2> are active, the following
174 stylesheet does not precisely determine the foreground colour:
175  
176 WidgetClass { fg: "red"; }
177 WidgetClass:tag1 { fg: "blue"; }
178 WidgetClass:tag2 { fg: "green"; }
179  
180 While it is not specified which tagged definition takes precedence, and
181 therefore whether it shall be blue or green, it is specified that both of the
182 tagged definitions take precedence over the untagged definition, so the colour
183 will not be red.
184  
185 =head1 SUBCLASSING
186  
187 If a Widget class is subclassed and the subclass does not declare
188 C<use Tickit::Style> again, the subclass will be transparent from the point of
189 view of style. Any style applied to the base class will apply equally to the
190 subclass, and the name of the subclass does not take part in style decisions.
191  
192 If the subclass does C<use Tickit::Style> again then the new subclass has a
193 distinct widget type for style purposes. It can optionally copy the style
194 information from its base class, but thereafter the stored information is
195 distinct, and changes in the base class (such as loading style files) will not
196 affect it.
197  
198 To copy the style information from the base, apply the C<-copy> keyword:
199  
200 use Tickit::Style -copy;
201  
202 Alternatively, to start with a new blank state, use the C<-blank> keyword:
203  
204 use Tickit::Style -blank;
205  
206 Currently, C<-blank> is the default behaviour, but this may change in a future
207 version, with a deprecation warning if no keyword is specified.
208  
209 =cut
210  
211 # This class imports functions and sets up initial state
212 sub import
213 {
214 my $class = shift;
215 my $pkg = caller;
216 my @symbols = @_;
217  
218 ( my $type = $pkg ) =~ s/^Tickit::Widget:://;
219  
220 my $mode = "blank";
221 foreach ( @symbols ) {
222 $mode = "blank", next if $_ eq "-blank";
223 $mode = "copy", next if $_ eq "-copy";
224  
225 croak "Unrecognised symbol $_ to Tickit::Style->import";
226 }
227  
228 my $srctype = $pkg->can( "_widget_style_type" ) && $pkg->_widget_style_type;
229  
230 if( $mode eq "blank" ) {
231 # OK
232 }
233 elsif( $mode eq "copy" ) {
234 defined $srctype or croak "Cannot Tickit::Style -copy in $pkg as there is no source type";
235  
236 foreach my $c ( keys %{ $TAGSETS_BY_TYPE_CLASS{$srctype} || {} } ) {
237 $TAGSETS_BY_TYPE_CLASS{$type}{$c} = $TAGSETS_BY_TYPE_CLASS{$srctype}{$c}->clone;
238 }
239  
240 foreach my $hash ( \%RESHAPE_KEYS, \%RESHAPE_TEXTWIDTH_KEYS, \%REDRAW_KEYS ) {
241 # shallow copy is sufficient
242 $hash->{$type} = { $hash->{$srctype}->%* } if $hash->{$srctype};
243 }
244 }
245  
246 # Import the symbols
247 use Object::Pad 0.808 ':experimental(mop)';
248 if( my $meta = Object::Pad::MOP::Class->try_for_class( $pkg ) ) {
249 $meta->add_method( $_ => \&{"Tickit::Style::$_"} ) for @EXPORTS;
250 $meta->add_method( _widget_style_type => sub () { $type } );
251 }
252 else {
253 carp "Using legacy Tickit::Style exporter for non-class";
254  
255 my $metapkg = meta::package->get( $pkg );
256 $metapkg->add_named_sub( $_ => \&{"Tickit::Style::$_"} ) for @EXPORTS;
257 $metapkg->add_named_sub( _widget_style_type => sub () { $type } );
258 }
259  
260 $TAGSETS_BY_TYPE_CLASS{$type} ||= {};
261 }
262  
263 sub _ref_tagset
264 {
265 my ( $type, $class ) = @_;
266  
267 $type eq "*" or $TAGSETS_BY_TYPE_CLASS{$type} or
268 croak "$type is not a styled Widget type";
269  
270 $class = "" if !defined $class;
271 return $TAGSETS_BY_TYPE_CLASS{$type}{$class} ||= Tickit::Style::_Tagset->new;
272 }
273  
274 =head1 FUNCTIONS
275  
276 =cut
277  
278 =head2 style_definition
279  
280 style_definition( $tags, %definition );
281  
282 In addition to any loaded stylesheets, the widget class itself can provide
283 style information, via the C<style_definition> function. It provides a definition
284 equivalent to a stylesheet definition with no style class, optionally with a
285 single set of tags. To supply no tags, use the special string C<"base">.
286  
287 style_definition base =>
288 key1 => "value",
289 key2 => 123;
290  
291 To provide definitions with tags, use the colon-prefixed notation.
292  
293 style_definition ':active' =>
294 key3 => "value";
295  
296 =cut
297  
298 sub style_definition
299 {
300 my $class = caller;
301 my ( $tags, %definition ) = @_;
302  
303 my %tags;
304 $tags{$1}++ while $tags =~ s/:([A-Z0-9_-]+)//i;
305  
306 die "Expected '\$tags' to be 'base' or a set of :tag names" unless $tags eq "base" or $tags eq "";
307  
308 my $type = $class->_widget_style_type;
309 _ref_tagset( $type, undef )->merge_with_tags( \%tags, \%definition );
310 }
311  
312 =head2 style_reshape_keys
313  
314 style_reshape_keys( @keys );
315  
316 Declares that the given list of keys are somehow responsible for determining
317 the shape of the widget. If their values are changed, the C<reshape> method is
318 called.
319  
320 =cut
321  
322 sub style_reshape_keys
323 {
324 my $class = caller;
325  
326 my $type = $class->_widget_style_type;
327 $RESHAPE_KEYS{$type}{$_} = 1 for @_;
328 }
329  
330 sub _reshape_keys
331 {
332 my ( $type ) = @_;
333 return keys $RESHAPE_KEYS{$type}->%*;
334 }
335  
336 =head2 style_reshape_textwidth_keys
337  
338 style_reshape_textwidth_keys( @keys );
339  
340 Declares that the given list of keys contain text, the C<textwidth()> of which
341 is used to determine the shape of the widget. If their values are changed such
342 that the C<textwidth()> differs, the C<reshape> method is called.
343  
344 =cut
345  
346 sub style_reshape_textwidth_keys
347 {
348 my $class = caller;
349  
350 my $type = $class->_widget_style_type;
351 $RESHAPE_TEXTWIDTH_KEYS{$type}{$_} = 1 for @_;
352 }
353  
354 sub _reshape_textwidth_keys
355 {
356 my ( $type ) = @_;
357 return keys $RESHAPE_TEXTWIDTH_KEYS{$type}->%*;
358 }
359  
360 =head2 style_redraw_keys
361  
362 style_redraw_keys( @keys );
363  
364 Declares that the given list of keys are somehow responsible for determining
365 the look of the widget, but in a way that does not determine the size. If
366 their values are changed, the C<redraw> method is called.
367  
368 Between them these three methods may help avoid C<Tickit::Widget> classes from
369 needing to override the C<on_style_changed_values> method.
370  
371 =cut
372  
373 sub style_redraw_keys
374 {
375 my $class = caller;
376  
377 my $type = $class->_widget_style_type;
378 $REDRAW_KEYS{$type}{$_} = 1 for @_;
379 }
380  
381 sub _redraw_keys
382 {
383 my ( $type ) = @_;
384 return keys $REDRAW_KEYS{$type}->%*;
385 }
386  
387 my @ON_STYLE_LOAD;
388  
389 # Not exported
390 sub _load_style
391 {
392 my ( $defs ) = @_;
393  
394 foreach my $def ( @$defs ) {
395 my $type = $def->type;
396 $TAGSETS_BY_TYPE_CLASS{$type} ||= {};
397 my $tagset = _ref_tagset( $type, $def->class );
398 $tagset->merge_with_tags( $def->tags, $def->style );
399 }
400  
401 foreach my $code ( @ON_STYLE_LOAD ) {
402 $code->();
403 }
404 }
405  
406 =head1 ADDITIONAL FUNCTIONS/METHODS
407  
408 These functions are not exported, but may be called directly.
409  
410 =cut
411  
412 =head2 load_style
413  
414 Tickit::Style->load_style( $string );
415  
416 Loads definitions from a stylesheet given in a string.
417  
418 Definitions will be merged with existing definitions in memory, with new
419 values overwriting existing values.
420  
421 =cut
422  
423 sub load_style
424 {
425 shift;
426 my ( $str ) = @_;
427 _load_style( Tickit::Style::Parser->new->from_string( $str ) );
428 }
429  
430 =head2 load_style_file
431  
432 Tickit::Style->load_style_file( $path );
433  
434 Loads definitions from a stylesheet file given by the path.
435  
436 Definitions will be merged the same way as C<load_style>.
437  
438 =cut
439  
440 sub load_style_file
441 {
442 shift;
443 my ( $path ) = @_;
444 # TODO: use ->from_file( $path, binmode => ":encoding(UTF-8)" ) when available
445 my $str = do {
446 open my $fh, "<:encoding(UTF-8)", $path or croak "Cannot read $path - $!";
447 local $/;
448 <$fh>;
449 };
450 _load_style( Tickit::Style::Parser->new->from_string( $str ) );
451 }
452  
453 =head2 load_style_from_DATA
454  
455 Tickit::Style->load_style_from_DATA;
456  
457 A convenient shortcut for loading style definitions from the caller's C<DATA>
458 filehandle.
459  
460 =cut
461  
462 sub load_style_from_DATA
463 {
464 shift;
465 my $pkg = caller;
466 my $fh = meta::package->get( $pkg )->get_glob( "DATA" )->reference;
467 my $str = do { local $/; <$fh> };
468 _load_style( Tickit::Style::Parser->new->from_string( $str ) );
469 }
470  
471 =head2 on_style_load
472  
473 Tickit::Style::on_style_load( \&code );
474  
475 Adds a CODE reference to be invoked after either C<load_style> or
476 C<load_style_file> are called. This may be useful to flush any caches or
477 invalidate any state that depends on style information.
478  
479 =cut
480  
481 sub on_style_load
482 {
483 my ( $code ) = @_;
484 push @ON_STYLE_LOAD, $code;
485 }
486  
487 class # hide from indexer
488 Tickit::Style::_Keyset :strict(params) {
489  
490 # A "Keyset" is the set of style keys applied to one particular set of
491 # style tags
492 field $tags :reader :param;
493 field $style :reader :param;
494  
495 method clone
496 {
497 return __PACKAGE__->new( tags => $tags, style => { %$style } );
498 }
499 }
500  
501 class # hide from indexer
502 Tickit::Style::_Tagset :strict(params);
503  
504 use experimental 'postderef';
505  
506 field @_keysets;
507  
508 ADJUST :params ( :$keysets = undef ) { @_keysets = $keysets->@* if $keysets; }
509  
510 method clone
511 {
512 return __PACKAGE__->new( keysets => [ map { $_->clone } @_keysets ] );
513 }
514  
515 method add
516 {
517 my ( $key, $value ) = @_;
518  
519 my %tags;
520 $tags{$1}++ while $key =~ s/:([A-Z0-9_-]+)//i;
521  
522 $self->merge_with_tags( \%tags, { $key => $value } );
523 }
524  
525 method merge
526 {
527 my ( $other ) = @_;
528  
529 foreach my $keyset ( $other->keysets ) {
530 $self->merge_with_tags( $keyset->tags, $keyset->style );
531 }
532 }
533  
534 method merge_with_tags
535 {
536 my ( $tags, $style ) = @_;
537  
538 my $keyset = Tickit::Style::_Keyset->new( tags => $tags, style => $style );
539 @_keysets = ( $keyset ) and return if !@_keysets;
540  
541 # First see if we have to merge an existing one
542 KEYSET: foreach my $keyset ( @_keysets ) {
543 $keyset->tags->{$_} or next KEYSET for keys %$tags;
544 $tags->{$_} or next KEYSET for keys $keyset->tags->%*;
545  
546 # Merge
547 foreach my $key ( keys %$style ) {
548 defined $style->{$key} ? $keyset->style->{$key} = $style->{$key}
549 : delete $keyset->style->{$key};
550 }
551 return;
552 }
553  
554 # Keep sorted, most tags first
555 # TODO: this might be doable more efficiently but we don't care for now
556 @_keysets = sort { scalar keys $b->tags->%* <=> scalar keys $a->tags->%* } ( @_keysets, $keyset );
557 }
558  
559 method keysets
560 {
561 return @_keysets;
562 }
563  
564 =head1 AUTHOR
565  
566 Paul Evans <leonerd@leonerd.org.uk>
567  
568 =cut
569  
570 0x55AA;