File: Style.pm

package info (click to toggle)
libtickit-widgets-perl 0.42-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 568 kB
  • sloc: perl: 5,636; makefile: 2
file content (570 lines) | stat: -rw-r--r-- 15,377 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
#  You may distribute under the terms of either the GNU General Public License
#  or the Artistic License (the same terms as Perl itself)
#
#  (C) Paul Evans, 2013-2024 -- leonerd@leonerd.org.uk

use v5.20;
use warnings;
use Object::Pad 0.805;

package Tickit::Style 0.60;

use warnings;
use experimental 'postderef';

use meta 0.008;
no warnings 'meta::experimental';

use Carp;

use Tickit::Pen;
use Tickit::Style::Parser;

our @EXPORTS = qw(
   style_definition
   style_reshape_keys
   style_reshape_textwidth_keys
   style_redraw_keys
);

# {$type}->{$class} = $tagset
my %TAGSETS_BY_TYPE_CLASS;

# {$type}->{$key} = 1
my %RESHAPE_KEYS;
my %RESHAPE_TEXTWIDTH_KEYS;
my %REDRAW_KEYS;

=head1 NAME

C<Tickit::Style> - declare customisable style information on widgets

=head1 SYNOPSIS

   package My::Widget::Class
   use base qw( Tickit::Widget );
   use Tickit::Style;

   style_definition base =>
      fg => "red";

   style_definition ':active' =>
      b => 1;

   ...

   sub render_to_rb
   {
      my $self = shift;
      my ( $rb, $rect ) = @_;

      $rb->text_at( 0, 0, "Here is my text", $self->get_style_pen );
   }

Z<>

   use My::Widget::Class;

   my $w = My::Widget::Class->new(
      class => "another-class",
   );

   ...

=head1 DESCRIPTION

This module adds the ability to a L<Tickit::Widget> class to declare a set of
named keys that take values, and provides convenient accessors for the widget
to determine what the values are at any given moment in time. The values
currently in effect are determined by the widget class code, and any
stylesheet files loaded by the application.

The widget itself can store a set of tags; named entities that may be present
or absent. The set of tags currently active on a widget helps to determine
which definitions style are to be used.

Finally, the widget itself stores a list of style class names. These classes
also help determine which style definitions from a loaded stylesheet file are
applied.

=head2 Stylesheet Files

A stylesheet file contains a list of definitions of styles. Each definition
gives a C<Tickit::Widget> class name, optionally a style class name prefixed
by a period (C<.>), optionally a set of tags prefixed with colons (C<:>), and
a body definition in a brace-delimited (C<{}>) block. Comments can appear
anywhere that whitespace is allowed, starting with a hash symbol (C<#>) and
continuing to the end of the line.

   WidgetClass {
     # basic style goes here
   }

   WidgetClass.styleclass {
     # style to apply for this class goes here
   }

   WidgetClass:tag {
     # style to apply when this tag is active goes here
   }

Each style definition contains a set semicolon-delimited (C<;>) assignments of
values to keys. Each key is suffixed by a colon (C<:>), and the values may be
integers, quoted strings (C<"...">), or the special identifiers C<true> or
C<false>.

   WidgetClass.styleclass {
     key1: "value 1";
     key2: 123;
     key3: true;
   }

While it is more traditional for keys in stylesheet files to contain hyphens
(C<->), it is more convenient in Perl code to use underscores (C<_>) instead.
The parser will convert hyphens in key names into underscores.

As well as giving visual styling information, stylesheets can also associate
behavioural actions with keypresses. These are given by a keypress key name in
angle brackets (C<< <NAME> >>) and an action name, which is a bareword
identifier.

   WidgetClass {
     <Enter>: activate;
   }

A special widget type name of C<*> can also be used to provide style blocks
that will apply (at lower priority) to any type of widget. Typically these
would be used along with classes or tags, to set application-wide styles.

   *:error {
     bg: "red";
     fg: "hi-white";
   }

=head2 How Style is Determined

The full set of style definitions applied to one named class of one widget
type for all its style tags is called a "tagset". Each tagset consists of a
partially-ordered list of entities called "keysets", which give a mapping from
style keys to values for one particular set of active style tags. The widget
may also have a special tagset containing the "direct-applied" style
definition given to the constructor.

The style at any given moment is determined by taking into account the style
classes and tags that are in effect. The value of each key is determined by a
first-match-wins search along the "direct applied" tagset (if present), then
the tagset for each of the style classes, in order, followed finally by the
base tagset for the widget type without class.

Within each tagset, only the keysets that do not depend on a style tag that is
inactive are considered. That is, a keyset that depends on no tags will always
be considered, and any keyset that only depends on active keys will be
considered, even if there are other active tags that the keyset does not
consider. Tags are always additive, in this regard.

While the order of the tagsets is exactly defined by the order of the style
classes applied to the widget, the order of keysets within each tagset is not
fully specified. Tagsets are stored partially ordered, sorted by the number of
style tags that each keyset depends on. This ensures that more specific
keysets are found before, and therefore override, less specific ones. However,
it is not defined the ordering of keysets with equal numbers of (distinct)
tags.

For instance, if both C<tag1> and C<tag2> are active, the following
stylesheet does not precisely determine the foreground colour:

   WidgetClass      { fg: "red"; }
   WidgetClass:tag1 { fg: "blue"; }
   WidgetClass:tag2 { fg: "green"; }

While it is not specified which tagged definition takes precedence, and
therefore whether it shall be blue or green, it is specified that both of the
tagged definitions take precedence over the untagged definition, so the colour
will not be red.

=head1 SUBCLASSING

If a Widget class is subclassed and the subclass does not declare
C<use Tickit::Style> again, the subclass will be transparent from the point of
view of style. Any style applied to the base class will apply equally to the
subclass, and the name of the subclass does not take part in style decisions.

If the subclass does C<use Tickit::Style> again then the new subclass has a
distinct widget type for style purposes. It can optionally copy the style
information from its base class, but thereafter the stored information is
distinct, and changes in the base class (such as loading style files) will not
affect it.

To copy the style information from the base, apply the C<-copy> keyword:

   use Tickit::Style -copy;

Alternatively, to start with a new blank state, use the C<-blank> keyword:

   use Tickit::Style -blank;

Currently, C<-blank> is the default behaviour, but this may change in a future
version, with a deprecation warning if no keyword is specified.

=cut

# This class imports functions and sets up initial state
sub import
{
   my $class = shift;
   my $pkg = caller;
   my @symbols = @_;

   ( my $type = $pkg ) =~ s/^Tickit::Widget:://;

   my $mode = "blank";
   foreach ( @symbols ) {
      $mode = "blank", next if $_ eq "-blank";
      $mode = "copy",  next if $_ eq "-copy";

      croak "Unrecognised symbol $_ to Tickit::Style->import";
   }

   my $srctype = $pkg->can( "_widget_style_type" ) && $pkg->_widget_style_type;

   if( $mode eq "blank" ) {
      # OK
   }
   elsif( $mode eq "copy" ) {
      defined $srctype or croak "Cannot Tickit::Style -copy in $pkg as there is no source type";

      foreach my $c ( keys %{ $TAGSETS_BY_TYPE_CLASS{$srctype} || {} } ) {
         $TAGSETS_BY_TYPE_CLASS{$type}{$c} = $TAGSETS_BY_TYPE_CLASS{$srctype}{$c}->clone;
      }

      foreach my $hash ( \%RESHAPE_KEYS, \%RESHAPE_TEXTWIDTH_KEYS, \%REDRAW_KEYS ) {
         # shallow copy is sufficient
         $hash->{$type} = { $hash->{$srctype}->%* } if $hash->{$srctype};
      }
   }

   # Import the symbols
   use Object::Pad 0.808 ':experimental(mop)';
   if( my $meta = Object::Pad::MOP::Class->try_for_class( $pkg ) ) {
      $meta->add_method( $_ => \&{"Tickit::Style::$_"} ) for @EXPORTS;
      $meta->add_method( _widget_style_type => sub () { $type } );
   }
   else {
      carp "Using legacy Tickit::Style exporter for non-class";

      my $metapkg = meta::package->get( $pkg );
      $metapkg->add_named_sub( $_ => \&{"Tickit::Style::$_"} ) for @EXPORTS;
      $metapkg->add_named_sub( _widget_style_type => sub () { $type } );
   }

   $TAGSETS_BY_TYPE_CLASS{$type} ||= {};
}

sub _ref_tagset
{
   my ( $type, $class ) = @_;

   $type eq "*" or $TAGSETS_BY_TYPE_CLASS{$type} or
      croak "$type is not a styled Widget type";

   $class = "" if !defined $class;
   return $TAGSETS_BY_TYPE_CLASS{$type}{$class} ||= Tickit::Style::_Tagset->new;
}

=head1 FUNCTIONS

=cut

=head2 style_definition

   style_definition( $tags, %definition );

In addition to any loaded stylesheets, the widget class itself can provide
style information, via the C<style_definition> function. It provides a definition
equivalent to a stylesheet definition with no style class, optionally with a
single set of tags. To supply no tags, use the special string C<"base">.

   style_definition base =>
      key1 => "value",
      key2 => 123;

To provide definitions with tags, use the colon-prefixed notation.

   style_definition ':active' =>
      key3 => "value";

=cut

sub style_definition
{
   my $class = caller;
   my ( $tags, %definition ) = @_;

   my %tags;
   $tags{$1}++ while $tags =~ s/:([A-Z0-9_-]+)//i;

   die "Expected '\$tags' to be 'base' or a set of :tag names" unless $tags eq "base" or $tags eq "";

   my $type = $class->_widget_style_type;
   _ref_tagset( $type, undef )->merge_with_tags( \%tags, \%definition );
}

=head2 style_reshape_keys

   style_reshape_keys( @keys );

Declares that the given list of keys are somehow responsible for determining
the shape of the widget. If their values are changed, the C<reshape> method is
called.

=cut

sub style_reshape_keys
{
   my $class = caller;

   my $type = $class->_widget_style_type;
   $RESHAPE_KEYS{$type}{$_} = 1 for @_;
}

sub _reshape_keys
{
   my ( $type ) = @_;
   return keys $RESHAPE_KEYS{$type}->%*;
}

=head2 style_reshape_textwidth_keys

   style_reshape_textwidth_keys( @keys );

Declares that the given list of keys contain text, the C<textwidth()> of which
is used to determine the shape of the widget. If their values are changed such
that the C<textwidth()> differs, the C<reshape> method is called.

=cut

sub style_reshape_textwidth_keys
{
   my $class = caller;

   my $type = $class->_widget_style_type;
   $RESHAPE_TEXTWIDTH_KEYS{$type}{$_} = 1 for @_;
}

sub _reshape_textwidth_keys
{
   my ( $type ) = @_;
   return keys $RESHAPE_TEXTWIDTH_KEYS{$type}->%*;
}

=head2 style_redraw_keys

   style_redraw_keys( @keys );

Declares that the given list of keys are somehow responsible for determining
the look of the widget, but in a way that does not determine the size. If
their values are changed, the C<redraw> method is called.

Between them these three methods may help avoid C<Tickit::Widget> classes from
needing to override the C<on_style_changed_values> method.

=cut

sub style_redraw_keys
{
   my $class = caller;

   my $type = $class->_widget_style_type;
   $REDRAW_KEYS{$type}{$_} = 1 for @_;
}

sub _redraw_keys
{
   my ( $type ) = @_;
   return keys $REDRAW_KEYS{$type}->%*;
}

my @ON_STYLE_LOAD;

# Not exported
sub _load_style
{
   my ( $defs ) = @_;

   foreach my $def ( @$defs ) {
      my $type = $def->type;
      $TAGSETS_BY_TYPE_CLASS{$type} ||= {};
      my $tagset = _ref_tagset( $type, $def->class );
      $tagset->merge_with_tags( $def->tags, $def->style );
   }

   foreach my $code ( @ON_STYLE_LOAD ) {
      $code->();
   }
}

=head1 ADDITIONAL FUNCTIONS/METHODS

These functions are not exported, but may be called directly.

=cut

=head2 load_style

   Tickit::Style->load_style( $string );

Loads definitions from a stylesheet given in a string.

Definitions will be merged with existing definitions in memory, with new
values overwriting existing values.

=cut

sub load_style
{
   shift;
   my ( $str ) = @_;
   _load_style( Tickit::Style::Parser->new->from_string( $str ) );
}

=head2 load_style_file

   Tickit::Style->load_style_file( $path );

Loads definitions from a stylesheet file given by the path.

Definitions will be merged the same way as C<load_style>.

=cut

sub load_style_file
{
   shift;
   my ( $path ) = @_;
   # TODO: use ->from_file( $path, binmode => ":encoding(UTF-8)" ) when available
   my $str = do {
      open my $fh, "<:encoding(UTF-8)", $path or croak "Cannot read $path - $!";
      local $/;
      <$fh>;
   };
   _load_style( Tickit::Style::Parser->new->from_string( $str ) );
}

=head2 load_style_from_DATA

   Tickit::Style->load_style_from_DATA;

A convenient shortcut for loading style definitions from the caller's C<DATA>
filehandle.

=cut

sub load_style_from_DATA
{
   shift;
   my $pkg = caller;
   my $fh = meta::package->get( $pkg )->get_glob( "DATA" )->reference;
   my $str = do { local $/; <$fh> };
   _load_style( Tickit::Style::Parser->new->from_string( $str ) );
}

=head2 on_style_load

   Tickit::Style::on_style_load( \&code );

Adds a CODE reference to be invoked after either C<load_style> or
C<load_style_file> are called. This may be useful to flush any caches or
invalidate any state that depends on style information.

=cut

sub on_style_load
{
   my ( $code ) = @_;
   push @ON_STYLE_LOAD, $code;
}

class # hide from indexer
   Tickit::Style::_Keyset :strict(params) {

   # A "Keyset" is the set of style keys applied to one particular set of
   # style tags
   field $tags  :reader :param;
   field $style :reader :param;

   method clone
   {
      return __PACKAGE__->new( tags => $tags, style => { %$style } );
   }
}

class # hide from indexer
   Tickit::Style::_Tagset :strict(params);

use experimental 'postderef';

field @_keysets;

ADJUST :params ( :$keysets = undef ) { @_keysets = $keysets->@* if $keysets; }

method clone
{
   return __PACKAGE__->new( keysets => [ map { $_->clone } @_keysets ] );
}

method add
{
   my ( $key, $value ) = @_;

   my %tags;
   $tags{$1}++ while $key =~ s/:([A-Z0-9_-]+)//i;

   $self->merge_with_tags( \%tags, { $key => $value } );
}

method merge
{
   my ( $other ) = @_;

   foreach my $keyset ( $other->keysets ) {
      $self->merge_with_tags( $keyset->tags, $keyset->style );
   }
}

method merge_with_tags
{
   my ( $tags, $style ) = @_;

   my $keyset = Tickit::Style::_Keyset->new( tags => $tags, style => $style );
   @_keysets = ( $keyset ) and return if !@_keysets;

   # First see if we have to merge an existing one
   KEYSET: foreach my $keyset ( @_keysets ) {
      $keyset->tags->{$_} or next KEYSET for keys %$tags;
      $tags->{$_} or next KEYSET for keys $keyset->tags->%*;

      # Merge
      foreach my $key ( keys %$style ) {
         defined $style->{$key} ? $keyset->style->{$key} = $style->{$key}
                                : delete $keyset->style->{$key};
      }
      return;
   }

   # Keep sorted, most tags first
   # TODO: this might be doable more efficiently but we don't care for now
   @_keysets = sort { scalar keys $b->tags->%* <=> scalar keys $a->tags->%* } ( @_keysets, $keyset );
}

method keysets
{
   return @_keysets;
}

=head1 AUTHOR

Paul Evans <leonerd@leonerd.org.uk>

=cut

0x55AA;