blib/lib/Term/Fabulous/Widget/Chart.pm untested

filter: Statementstmt 0.0% 0 / 329 Branchbran 0.0% 0 / 168 Conditioncond 0.0% 0 / 95 MC/DCmcdc 0.0% 0 / 57 Subroutinesub 0.0% 0 / 18 Podpod n/a totaltotal 0.0% 0 / 667 CC 1 SCAR 6.9
CC
1
Cov
0%
BEGIN
2.0
BEGIN
2.0
BEGIN
2.0
CRAP 2.0
1 package Term::Fabulous::Widget::Chart;
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 use Clay::UI::Role::Interaction::Hoverable;
13 use Term::Fabulous::Widget::Display;
14  
15 class Term::Fabulous::Widget::Chart
16 :isa(Term::Fabulous::Widget::Display)
17 :does(Clay::UI::Role::Interaction::Hoverable)
18 :abstract
19 {
20 use Carp qw(croak);
21 use Clay::UI::Enum::Result;
22 use Clay::XS qw(sizing_grow);
23 use List::Util qw(max min sum0);
24 use Scalar::Util qw(refaddr);
25 use Term::Fabulous::Check qw(boolean describe one_of);
26 use Term::Fabulous::Chart::Palette qw(palette_colors is_palette_name palette_names chart_color mix_rgb is_light_rgb ink_colors);
27 use Term::Fabulous::Chart::Surface;
28 use Term::Fabulous::Event::SeriesHover;
29 use Term::Fabulous::Termbox qw(TB_BOLD);
30  
31 use constant {
32 DARK_SURFACE => 0x1A1A19, # the ink's base where the chart lies on nothing
33 LIGHT_SURFACE => 0xFCFCFB,
34 LEGEND_GAP => 3, # columns between legend entries in a row
35 };
36  
37 my @LEGEND = qw(auto top bottom left right none);
38 my @ALIGN = qw(left center right);
39 my @THEME = qw(auto dark light);
40 my @INK_COLORS = qw(title_color text_color label_color axis_color grid_color);
41 my %SYMBOL_COLUMNS = ( line => 2, fill => 1, point => 1 );
42  
43 field $title :param = undef;
44 field $title_align :param = 'left';
45 field $legend :param = 'auto';
46 field $palette :param = 'default';
47 field $theme :param = 'auto';
48 field $hover :param = 1;
49 field $hover_fade :param = 0.7;
50 field $highlight :param = undef;
51 field %_ink; # the colors given for title_color, ..., as 0xRRGGBB
52  
53 field $_surface; # the last frame's surface, for the mouse
54 field @_targets; # owner id => { key, series, index, label, value, x }
55 field $_hovered; # the target under the pointer, or undef
56  
57 # What the chart draws, from its own state; see SUBCLASS INTERFACE.
58 method legend_entries;
59 method draw_plot;
60 method default_legend_position;
61  
62 ADJUST :params ( :$title_color = undef, :$text_color = undef, :$label_color = undef, :$axis_color = undef, :$grid_color = undef ) {
63 my %given = ( title_color => $title_color, text_color => $text_color, label_color => $label_color, axis_color => $axis_color, grid_color => $grid_color );
64 $self->_check_title( title => $title );
65 one_of( $self, title_align => $title_align, @ALIGN );
66 one_of( $self, legend => $legend, @LEGEND );
67 one_of( $self, theme => $theme, @THEME );
68 $palette = $self->_checked_palette($palette);
69 $hover = boolean( $self, hover => $hover );
70 $hover_fade = $self->_checked_fraction( hover_fade => $hover_fade );
71 $self->_check_title( highlight => $highlight );
72  
73 foreach my $name (@INK_COLORS) {
74 ( $_ink{$name} ) = chart_color( $self, $name, $given{$name} ) if defined $given{$name};
75 }
76  
77 my $continue = Clay::UI::Enum::Result->CONTINUE;
78 $self->on( MouseMove => sub ( $self, $event ) { $self->_pointer_moved($event); return $continue }, owner => $self );
79 $self->on( Mouse => sub ( $self, $event ) { $self->_pointer_moved($event); return $continue }, owner => $self );
80 $self->on(
81 OnHoverStopped => sub ( $self, $event ) {
82 $self->_hover_target(undef) if refaddr( $event->target ) == refaddr($self);
83 return $continue;
84 },
85 owner => $self
86 );
87 }
88  
89 method _fail ( $name, $expected, $value ) {
90 croak ref($self) . ": $name must be $expected, got " . describe($value);
91 }
92  
93 method _check_title ( $name, $value ) {
94 $self->_fail( $name, 'a string or undef', $value ) if ref $value;
95 return $value;
96 }
97  
98 method _checked_fraction ( $name, $value ) {
99 $self->_fail( $name, 'a number from 0 to 1', $value ) unless defined $value && !ref $value && $value =~ /\A(?:0|1|0?\.[0-9]+|1\.0*)\z/;
100 return $value + 0;
101 }
102  
103 # A palette name, or an array of colors (as 0xRRGGBB).
104 method _checked_palette ($value) {
105 return $value if is_palette_name($value);
106 $self->_fail( 'palette', 'a palette name (' . join( ', ', palette_names() ) . ') or an array reference of colors', $value )
107 unless ref $value eq 'ARRAY' && @$value;
108 return [ map { ( chart_color( $self, 'palette color', $_ ) )[0] } @$value ];
109 }
110  
111 # ---------------------------------------------------------------------
112 # Changes and painting
113 # ---------------------------------------------------------------------
114  
115 # A chart without a size in the layout takes the room it gets
116 # (Term::Fabulous::Widget::Display).
117 method natural_size () {
118 return ( sizing_grow(), sizing_grow() );
119 }
120  
121 # The background the chart is drawn on (Term::Fabulous::Widget's
122 # background_below) as 0xRRGGBB; undef where there is none.
123 method effective_background () {
124 my $rgba = $self->background_below // return undef;
125 return ( $rgba->[0] << 16 ) | ( $rgba->[1] << 8 ) | $rgba->[2];
126 }
127  
128 # Besides its own state and the theme (Term::Fabulous::Widget::Display),
129 # a chart is drawn from what it lies on and what the pointer is on.
130 method paint_key :override () {
131 return ( $self->SUPER::paint_key, $self->effective_background, defined $_hovered ? $_hovered->{key} : undef );
132 }
133  
134 method paint () {
135 my $background = $self->effective_background;
136 my $look = $self->_look($background);
137 @_targets = ();
138 $_surface = Term::Fabulous::Chart::Surface->new( columns => $self->columns, rows => $self->rows, background => $background );
139 $self->_draw( $_surface, $look );
140 $_surface->paint($self);
141 return;
142 }
143  
144 # Everything a frame is drawn with: colors and the emphasized series.
145 method _look ($background) {
146 my $mode = $theme ne 'auto' ? $theme : defined $background && is_light_rgb($background) ? 'light' : 'dark';
147 my $base = $background // ( $mode eq 'light' ? LIGHT_SURFACE : DARK_SURFACE );
148 my $ink = ink_colors( $base, $mode );
149 my %color = map { my $short = s/_color\z//r; $short => $_ink{$_} // $ink->{$short} } @INK_COLORS;
150 my $emphasis = $hover && defined $_hovered ? $_hovered->{series} : $highlight;
151 return {
152 mode => $mode,
153 background => $background,
154 base => $base,
155 %color,
156 palette => ref $palette ? $palette : [ palette_colors( $palette, $mode ) ],
157 emphasis => $emphasis,
158 fade => $hover_fade,
159 };
160 }
161  
162 # The color of a palette slot.
163 method slot_color ( $look, $slot ) {
164 my $colors = $look->{palette};
165 return $colors->[ $slot % @$colors ];
166 }
167  
168 # A series' color as the frame shows it: faded while another series
169 # is emphasized.
170 method shown_color ( $look, $series, $color ) {
171 return $color if !defined $look->{emphasis} || !defined $series || $series eq $look->{emphasis};
172 return mix_rgb( $color, $look->{base}, $look->{fade} );
173 }
174  
175 method is_emphasized ( $look, $series ) {
176 return defined $look->{emphasis} && defined $series && $series eq $look->{emphasis} ? 1 : 0;
177 }
178  
179 # An owner id for what is drawn: what the pointer is on when it is
180 # over the cells drawn with it.
181 method register_target (%target) {
182 $target{key} = join "\0", map { $_ // '' } @target{qw(series index)};
183 push @_targets, \%target;
184 return $#_targets;
185 }
186  
187 method _draw ( $surface, $look ) {
188 my ( $columns, $rows ) = ( $surface->columns, $surface->rows );
189 my ( $left, $top, $right, $bottom ) = ( 0, 0, $columns, $rows );
190  
191 if ( defined $title && length $title && $rows >= 3 ) {
192 my $width = Term::Fabulous::Chart::Surface->text_columns($title);
193 my $x = $title_align eq 'center' ? max( 0, int( ( $columns - $width ) / 2 ) ) : $title_align eq 'right' ? max( 0, $columns - $width ) : 0;
194 $surface->text( $x, 0, $title, $look->{title}, flags => TB_BOLD, max => $columns );
195 $top = $rows >= 12 ? 2 : 1;
196 }
197  
198 my @entries = $self->legend_entries($look);
199 my $position = $legend eq 'auto' ? ( @entries >= 2 ? $self->default_legend_position : 'none' ) : $legend;
200 my $layout;
201 $layout = $self->_legend_layout( \@entries, $position, $left, $top, $right, $bottom ) if @entries && $position ne 'none';
202 if ($layout) {
203 ( $left, $top, $right, $bottom ) = $layout->{plot}->@*;
204 $self->_paint_legend( $surface, $look, $layout ) unless $position eq 'bottom';
205 }
206 my $at_bottom = $layout && $position eq 'bottom';
207 if ( $right - $left < 2 || $bottom - $top < 1 ) {
208 $self->_paint_legend( $surface, $look, $layout ) if $at_bottom;
209 return;
210 }
211 my $used = $self->draw_plot( $surface, $left, $top, $right - $left, $bottom - $top, $look );
212 return unless $at_bottom;
213  
214 # A legend at the bottom follows the rows the plot used, not the
215 # rows its ticks left free below the axis.
216 $layout->{y} = $top + min( $bottom - $top, $used // $bottom - $top ) + $layout->{gap};
217 $self->_paint_legend( $surface, $look, $layout );
218 return;
219 }
220  
221 # ---------------------------------------------------------------------
222 # Legend
223 # ---------------------------------------------------------------------
224  
225 # An entry's value may be several texts (an amount and a share); they
226 # are joined into one, in a column of their own each when the legend
227 # lists the entries one below the other.
228 sub _joined_values ( $entries, $in_columns ) {
229 my @widths;
230 foreach my $entry ( grep { ref $_->{value} } @$entries ) {
231 foreach my $index ( 0 .. $entry->{value}->$#* ) {
232 my $columns = Term::Fabulous::Chart::Surface->text_columns( $entry->{value}[$index] );
233 $widths[$index] = $columns if !defined $widths[$index] || $columns > $widths[$index];
234 }
235 }
236 return $entries unless @widths;
237 return [
238 map {
239 my $entry = $_;
240 !ref $entry->{value} ? $entry : {
241 %$entry,
242 value => join ' ',
243 map {
244 my $text = $entry->{value}[$_];
245 $in_columns ? ( ' ' x ( $widths[$_] - Term::Fabulous::Chart::Surface->text_columns($text) ) ) . $text : $text
246 } 0 .. $entry->{value}->$#*
247 }
248 } @$entries
249 ];
250 }
251  
252 sub _entry_columns ($entry) {
253 my $columns = $SYMBOL_COLUMNS{ $entry->{symbol} } + 1 + Term::Fabulous::Chart::Surface->text_columns( $entry->{label} );
254 $columns += 2 + Term::Fabulous::Chart::Surface->text_columns( $entry->{value} ) if defined $entry->{value};
255 return $columns;
256 }
257  
258 sub _more_text ($hidden) {
259 return "+$hidden more";
260 }
261  
262 # Lays the legend out at one side of the area: where its entries go
263 # and the area left for the plot. Entries that do not fit are left
264 # out, and the last row (or line) says how many. Nothing when a row
265 # could not show even one entry beside the count.
266 method _legend_layout ( $entries, $position, $left, $top, $right, $bottom ) {
267 my $width = $right - $left;
268 $entries = _joined_values( $entries, $position eq 'left' || $position eq 'right' );
269 if ( $position eq 'top' || $position eq 'bottom' ) {
270 my @rows = ( { items => [], used => 0 } );
271 foreach my $entry (@$entries) {
272 my $columns = min( _entry_columns($entry), $width );
273 push @rows, { items => [], used => 0 } if $rows[-1]{items}->@* && $rows[-1]{used} + LEGEND_GAP + $columns > $width;
274 $rows[-1]{used} += ( $rows[-1]{items}->@* ? LEGEND_GAP : 0 ) + $columns;
275 push $rows[-1]{items}->@*, [ $entry, $columns ];
276 }
277 my $room = $bottom - $top;
278 splice @rows, max( 1, int( $room / 3 ) ) if @rows > max( 1, int( $room / 3 ) );
279 my $hidden = @$entries - sum0( map { scalar $_->{items}->@* } @rows );
280 my $more;
281 if ($hidden) {
282 my $last = $rows[-1];
283 my $fits = sub { $last->{used} + LEGEND_GAP + length _more_text($hidden) <= $width };
284 while ( $last->{items}->@* > 1 && !$fits->() ) {
285 my $gone = pop $last->{items}->@*;
286 $last->{used} -= LEGEND_GAP + $gone->[1];
287 $hidden++;
288 }
289  
290 # The one entry left is cut short rather than the count; when
291 # that leaves it less than a letter of its label, the legend
292 # is left out.
293 if ( !$fits->() ) {
294 my $item = $last->{items}[0];
295 my $columns = $width - LEGEND_GAP - length _more_text($hidden);
296 return undef if $columns < $SYMBOL_COLUMNS{ $item->[0]{symbol} } + 3;
297 $item->[1] = $columns;
298 $last->{used} = $columns;
299 }
300 $more = { text => _more_text($hidden), x => $left + $last->{used} + LEGEND_GAP };
301 }
302 my $gap = $room - @rows >= 8 ? 1 : 0;
303 return {
304 kind => 'rows',
305 rows => \@rows,
306 more => $more,
307 x => $left,
308 y => $position eq 'top' ? $top : $bottom - @rows,
309 gap => $gap,
310 plot => $position eq 'top' ? [ $left, $top + @rows + $gap, $right, $bottom ] : [ $left, $top, $right, $bottom - @rows - $gap ],
311 };
312 }
313  
314 # A column beside the plot, its entries centered vertically; values
315 # line up at the right.
316 my $room = $bottom - $top;
317 my $hidden = max( 0, @$entries - $room );
318 my @shown = @$entries[ 0 .. $#$entries - $hidden - ( $hidden ? 1 : 0 ) ];
319 $hidden = @$entries - @shown;
320 my $lines = @shown + ( $hidden ? 1 : 0 );
321 my $label_columns = max( map { Term::Fabulous::Chart::Surface->text_columns( $_->{label} ) } @$entries );
322 my $value_columns = max( 0, map { Term::Fabulous::Chart::Surface->text_columns( $_->{value} // '' ) } @$entries );
323 my $wanted = max( map { $SYMBOL_COLUMNS{ $_->{symbol} } } @$entries ) + 1 + $label_columns + ( $value_columns ? 2 + $value_columns : 0 );
324 my $columns = min( max( $wanted, $hidden ? length _more_text($hidden) : 0 ), int( $width / 2 ) );
325 return {
326 kind => 'column',
327 entries => \@shown,
328 more => $hidden ? { text => _more_text($hidden) } : undef,
329 x => $position eq 'right' ? $right - $columns : $left,
330 y => $top + max( 0, int( ( $room - $lines ) / 2 ) ),
331 columns => $columns,
332 value_columns => $value_columns,
333 gap => 0,
334 plot => $position eq 'right' ? [ $left, $top, $right - $columns - 2, $bottom ] : [ $left + $columns + 2, $top, $right, $bottom ],
335 };
336 }
337  
338 method _paint_legend ( $surface, $look, $layout ) {
339 my ( $x, $y ) = @$layout{qw(x y)};
340 if ( $layout->{kind} eq 'column' ) {
341 $self->_draw_entry( $surface, $look, $_, $x, $y++, $layout->{columns}, $layout->{value_columns} ) foreach $layout->{entries}->@*;
342 $surface->text( $x, $y, $layout->{more}{text}, $look->{label}, max => $layout->{columns} ) if $layout->{more};
343 return;
344 }
345 foreach my $row ( $layout->{rows}->@* ) {
346 my $at = $x;
347 foreach my $item ( $row->{items}->@* ) {
348 $self->_draw_entry( $surface, $look, $item->[0], $at, $y, $item->[1], undef );
349 $at += $item->[1] + LEGEND_GAP;
350 }
351 $y++;
352 }
353 $surface->text( $layout->{more}{x}, $y - 1, $layout->{more}{text}, $look->{label} ) if $layout->{more};
354 return;
355 }
356  
357 # One entry: its symbol in the series color, its label, and its value
358 # (right-aligned in $value_columns, when given).
359 method _draw_entry ( $surface, $look, $entry, $x, $y, $columns, $value_columns ) {
360 my $emphasized = $self->is_emphasized( $look, $entry->{series} );
361 my $faded = defined $look->{emphasis} && !$emphasized;
362 my $color = $self->shown_color( $look, $entry->{series}, $entry->{color} );
363 my $text = $faded ? mix_rgb( $look->{text}, $look->{base}, $look->{fade} ) : $emphasized ? $look->{title} : $look->{text};
364 my $owner = $self->register_target( series => $entry->{series}, index => $entry->{index}, label => $entry->{label}, value => $entry->{raw_value} );
365  
366 my $symbol = $entry->{symbol} eq 'line' ? "\x{2501}\x{2501}" : $entry->{symbol} eq 'point' ? $entry->{glyph} // "\x{25CF}" : "\x{25A0}";
367 my $end = $x + $columns;
368 my $at = $x + $surface->text( $x, $y, $symbol, $color );
369 $at++;
370 my $value_room = defined $entry->{value} ? ( $value_columns // Term::Fabulous::Chart::Surface->text_columns( $entry->{value} ) ) + 2 : 0;
371 $at += $surface->text( $at, $y, $entry->{label}, $text, max => max( 0, $end - $at - $value_room ), flags => $emphasized ? TB_BOLD : 0 );
372 if ( defined $entry->{value} && $end - $at >= 2 ) {
373 my $value_width = Term::Fabulous::Chart::Surface->text_columns( $entry->{value} );
374 $surface->text( $end - $value_width, $y, $entry->{value}, $faded ? $text : $look->{label}, max => $end - $at - 1 );
375 }
376 $surface->set_owner( $_, $y, 'fill', $owner ) foreach $x .. $end - 1;
377 return;
378 }
379  
380 # ---------------------------------------------------------------------
381 # Hover
382 # ---------------------------------------------------------------------
383  
384 method _pointer_moved ($event) {
385 return unless $hover && defined $_surface;
386 my ( $x, $y ) = $self->cell_at($event);
387 my $owner = defined $x ? $_surface->owner_near( $x, $y ) : undef;
388 $self->_hover_target( defined $owner ? $_targets[$owner] : undef );
389 return;
390 }
391  
392 method _hover_target ($target) {
393 my $old = defined $_hovered ? $_hovered->{key} : '';
394 my $new = defined $target ? $target->{key} : '';
395 return if $old eq $new;
396 $_hovered = $target;
397 $self->mark_changed;
398 my %fields = defined $target ? map { $_ => $target->{$_} } grep { defined $target->{$_} } qw(series index label value x) : ();
399 $self->fire_event( Term::Fabulous::Event::SeriesHover->new(%fields) );
400 return;
401 }
402  
403 # Ends the hover when the program took away what the pointer is on:
404 # the hovered series or slice is none of the names still shown.
405 method end_hover_unless_shown (@shown_names) {
406 my $series = defined $_hovered ? $_hovered->{series} : undef;
407 return unless defined $series;
408 return if grep { $_ eq $series } @shown_names;
409 $self->_hover_target(undef);
410 return;
411 }
412  
413 method hovered () {
414 return undef unless defined $_hovered;
415 return { map { $_ => $_hovered->{$_} } grep { defined $_hovered->{$_} } qw(series index label value x) };
416 }
417  
418 # ---------------------------------------------------------------------
419 # Accessors
420 # ---------------------------------------------------------------------
421  
422 method _changed_to ( $field_ref, $value ) {
423 $$field_ref = $value;
424 $self->mark_changed;
425 return $value;
426 }
427  
428 method title (@new) {
429 return $title unless @new;
430 return $self->_changed_to( \$title, $self->_check_title( title => $new[0] ) );
431 }
432  
433 method title_align (@new) {
434 return $title_align unless @new;
435 return $self->_changed_to( \$title_align, one_of( $self, title_align => $new[0], @ALIGN ) );
436 }
437  
438 method legend (@new) {
439 return $legend unless @new;
440 return $self->_changed_to( \$legend, one_of( $self, legend => $new[0], @LEGEND ) );
441 }
442  
443 method theme (@new) {
444 return $theme unless @new;
445 return $self->_changed_to( \$theme, one_of( $self, theme => $new[0], @THEME ) );
446 }
447  
448 method palette (@new) {
449 return ref $palette ? [@$palette] : $palette unless @new;
450 $self->_changed_to( \$palette, $self->_checked_palette( $new[0] ) );
451 return $self->palette;
452 }
453  
454 method hover (@new) {
455 return $hover unless @new;
456 $self->_hover_target(undef) unless $new[0];
457 return $self->_changed_to( \$hover, boolean( $self, hover => $new[0] ) );
458 }
459  
460 method hover_fade (@new) {
461 return $hover_fade unless @new;
462 return $self->_changed_to( \$hover_fade, $self->_checked_fraction( hover_fade => $new[0] ) );
463 }
464  
465 method highlight (@new) {
466 return $highlight unless @new;
467 return $self->_changed_to( \$highlight, $self->_check_title( highlight => $new[0] ) );
468 }
469  
470 method _ink_color ( $name, @new ) {
471 return $_ink{$name} unless @new;
472 if ( defined $new[0] ) {
473 ( $_ink{$name} ) = chart_color( $self, $name, $new[0] );
474 }
475 else {
476 delete $_ink{$name};
477 }
478 $self->mark_changed;
479 return $_ink{$name};
480 }
481  
482 method title_color (@new) { return $self->_ink_color( title_color => @new ) }
483 method text_color (@new) { return $self->_ink_color( text_color => @new ) }
484 method label_color (@new) { return $self->_ink_color( label_color => @new ) }
485 method axis_color (@new) { return $self->_ink_color( axis_color => @new ) }
486 method grid_color (@new) { return $self->_ink_color( grid_color => @new ) }
487  
488 # ---------------------------------------------------------------------
489 # KDL
490 # ---------------------------------------------------------------------
491  
492 method layout_properties :common () {
493 return (
494 $class->SUPER::layout_properties,
495 title => 'scalar',
496 title_align => 'scalar',
497 legend => 'scalar',
498 theme => 'scalar',
499 hover => 'boolean',
500 hover_fade => 'scalar',
501 highlight => 'scalar',
502 palette => \&_parse_palette,
503 ( map { $_ => \&_parse_ink_color } @INK_COLORS ),
504 );
505 }
506  
507 # palette "vivid", or palette "#3987e5" "#d95926" ...
508 method _parse_palette ($kid) {
509 my @args = map { $_->as_perl } $kid->args->@*;
510 croak ref($self) . ": layout property 'palette' takes a palette name or one or more colors" unless @args && !$kid->props->@* && !$kid->children->@*;
511 $self->palette( @args == 1 && is_palette_name( $args[0] ) ? $args[0] : \@args );
512 return;
513 }
514  
515 method _parse_ink_color ($kid) {
516 my $name = $kid->name;
517 $self->_ink_color( $name => $self->kdl_value($kid) );
518 return;
519 }
520 }
521  
522 1;
523  
524 __END__