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

filter: Statementstmt 0.0% 0 / 916 Branchbran 0.0% 0 / 498 Conditioncond 0.0% 0 / 469 MC/DCmcdc 0.0% 0 / 278 Subroutinesub 0.0% 0 / 27 Podpod n/a totaltotal 0.0% 0 / 2188 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::XYChart;
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 Term::Fabulous::Role::HasSeries;
13 use Term::Fabulous::Widget::Chart;
14  
15 class Term::Fabulous::Widget::XYChart
16 :isa(Term::Fabulous::Widget::Chart)
17 :does(Term::Fabulous::Role::HasSeries)
18 :abstract
19 {
20 use Carp qw(croak);
21 use Feature::Compat::Try;
22 use List::Util qw(all any first max min sum0 uniq);
23 use POSIX qw(ceil floor strftime);
24 use Scalar::Util qw(blessed looks_like_number);
25 use Term::Fabulous::Check qw(boolean describe glyph one_of);
26 use Term::Fabulous::Chart::Curve qw(curve_points y_at check_curve);
27 use Term::Fabulous::Chart::Format qw(number_formatter format_value format_values check_number_format check_time_format time_formatter);
28 use Term::Fabulous::Chart::Marker;
29 use Term::Fabulous::Chart::Palette qw(mix_rgb);
30 use Term::Fabulous::Chart::Raster;
31 use Term::Fabulous::Chart::Scale::Category;
32 use Term::Fabulous::Chart::Scale::Linear;
33 use Term::Fabulous::Chart::Scale::Log;
34 use Term::Fabulous::Chart::Scale::Time;
35 use Term::Fabulous::Chart::Series;
36 use Term::Fabulous::Chart::Surface;
37 use Term::Fabulous::Chart::Transform qw(parse_transforms apply_transforms);
38 use Term::Fabulous::Widget::Table::Value qw(date_epoch number_of);
39  
40 use constant {
41 DOT_POINT => 'dot',
42 SQUARE_POINT => 'square',
43 LINE_POINT => "\x{2022}", # bullet
44 LEGEND_POINT => "\x{25CF}", # black circle
45 AREA_FILL_OPACITY => 0.6,
46 STACKED_FILL_OPACITY => 0.8,
47 TREND_PATTERN => [ 4, 2 ],
48 };
49  
50 my %GRID_GLYPHS = (
51 solid => [ "\x{2500}", "\x{2502}" ],
52 dashed => [ "\x{254C}", "\x{254E}" ],
53 dotted => [ "\x{2508}", "\x{250A}" ],
54 );
55 my @X_TYPES = qw(auto linear log time category);
56 my @Y_TYPES = qw(linear log);
57 my @AXIS_KEYS = qw(type min max title format ticks step grid visible zero utc span base nice);
58 my @SERIES_DEFAULTS = qw(marker curve tension line line_style points point fill_opacity transform max_points span_gaps value_labels);
59  
60 field $initial_series :param(series) = [];
61 field $labels :param = undef;
62 field $x_axis :param = {};
63 field $y_axis :param = {};
64 field $stacked :param = 0;
65 field $horizontal :param = 0;
66 field $bar_width :param = 0.7;
67  
68 field @_kdl_chart_steps; # the transform steps a layout gave so far
69 field %_ends; # x_axis and y_axis => { min, max } as the scales take them
70  
71 method series_types () { return qw(line area bar scatter) }
72 method series_default_names () { return @SERIES_DEFAULTS }
73  
74 ADJUST :params (
75 :$marker = undef, :$curve = undef, :$tension = undef, :$line = undef, :$line_style = undef, :$points = undef, :$point = undef,
76 :$fill_opacity = undef, :$transform = undef, :$max_points = undef, :$span_gaps = undef, :$value_labels = undef
77 )
78 {
79 my %given = (
80 marker => $marker, curve => $curve, tension => $tension, line => $line,
81 line_style => $line_style, points => $points, point => $point, fill_opacity => $fill_opacity,
82 transform => $transform, max_points => $max_points, span_gaps => $span_gaps, value_labels => $value_labels,
83 );
84 $self->_set_default( $_ => $given{$_} ) foreach grep { defined $given{$_} } @SERIES_DEFAULTS;
85 $labels = $self->_checked_labels($labels) if defined $labels;
86 ( $x_axis, $_ends{x_axis} ) = $self->_checked_axis( x_axis => $x_axis );
87 ( $y_axis, $_ends{y_axis} ) = $self->_checked_axis( y_axis => $y_axis );
88 $stacked = $self->_checked_stacked($stacked);
89 $horizontal = boolean( $self, horizontal => $horizontal );
90 $bar_width = $self->_checked_fraction( bar_width => $bar_width );
91 croak ref($self) . ": series must be an array reference of series hashes, got " . describe($initial_series) unless ref $initial_series eq 'ARRAY';
92 $self->add_series($_) foreach @$initial_series;
93 $initial_series = undef;
94 }
95  
96 # ---------------------------------------------------------------------
97 # Checks
98 # ---------------------------------------------------------------------
99  
100 method _checked_labels ($value) {
101 croak ref($self) . ": labels must be an array reference of strings, got " . describe($value) unless ref $value eq 'ARRAY';
102 foreach my $label (@$value) {
103 croak ref($self) . ": every label must be a string, got " . describe($label) unless defined $label && !ref $label;
104 }
105 return [@$value];
106 }
107  
108 method _checked_stacked ($value) {
109 return 0 unless defined $value;
110 croak ref($self) . ": stacked must be 0, 1 or 'percent', got " . describe($value) unless !ref $value && $value =~ /\A(?:0|1|percent|)\z/;
111 return $value eq 'percent' ? 'percent' : $value ? 1 : 0;
112 }
113  
114 method _checked_axis ( $which, $spec ) {
115 my $owner = ref $self;
116 croak "$owner: $which must be a hash reference, got " . describe($spec) unless ref $spec eq 'HASH';
117 my %axis = %$spec;
118 my %allowed = map { $_ => 1 } @AXIS_KEYS;
119 my @unknown = grep { !$allowed{$_} } sort keys %axis;
120 croak "$owner: $which does not take @unknown (known: @AXIS_KEYS)" if @unknown;
121 $axis{type} //= $which eq 'x_axis' ? 'auto' : 'linear';
122 one_of( $owner, "$which type", $axis{type}, $which eq 'x_axis' ? @X_TYPES : @Y_TYPES );
123  
124 foreach my $key (qw(visible utc nice)) {
125 $axis{$key} = boolean( $self, "$which $key", $axis{$key} ) if exists $axis{$key};
126 }
127 $axis{zero} = boolean( $self, "$which zero", $axis{zero} ) if defined $axis{zero};
128 if ( exists $axis{grid} ) {
129 my $grid = $axis{grid};
130 $axis{grid}
131 = !defined $grid || ( !ref $grid && $grid =~ /\A(?:0|)\z/ ) ? 0
132 : !ref $grid && $grid eq '1' ? 'solid'
133 : !ref $grid && $GRID_GLYPHS{$grid} ? $grid
134 : croak "$owner: the grid of $which must be 0, 1, solid, dashed or dotted, got " . describe($grid);
135 }
136 croak "$owner: the title of $which must be a string, got " . describe( $axis{title} ) if ref $axis{title};
137 foreach my $key (qw(ticks)) {
138 croak "$owner: the $key of $which must be a positive integer, got " . describe( $axis{$key} ) if defined $axis{$key} && ( ref $axis{$key} || $axis{$key} !~ /\A[1-9][0-9]*\z/ );
139 }
140 foreach my $key (qw(step span)) {
141 croak "$owner: the $key of $which must be a positive number, got " . describe( $axis{$key} ) if defined $axis{$key} && !( defined number_of( $axis{$key} ) && $axis{$key} > 0 );
142 }
143 croak "$owner: the base of $which must be a number greater than 1, got " . describe( $axis{base} ) if defined $axis{base} && !( defined number_of( $axis{base} ) && $axis{base} > 1 );
144 if ( $axis{type} eq 'time' ) {
145 check_time_format( $owner, "the format of $which", $axis{format} );
146 }
147 elsif ( $axis{type} ne 'auto' ) {
148 check_number_format( $owner, "the format of $which", $axis{format} );
149 }
150 elsif ( defined $axis{format} && !ref $axis{format} && $axis{format} !~ /%/ ) {
151 check_number_format( $owner, "the format of $which", $axis{format} );
152 }
153 return ( \%axis, $self->_parsed_ends( $which, \%axis ) );
154 }
155  
156 # The ends an axis is given, as the numbers its scale takes: numbers
157 # on y, linear and log axes, epoch seconds on time axes, either on an
158 # automatic x axis (whose kind the data decides later); a category
159 # axis has no ends. Dies for an end its axis cannot have.
160 method _parsed_ends ( $which, $axis ) {
161 my ( $owner, $type ) = ( ref $self, $axis->{type} );
162 my %given = map { defined $axis->{$_} ? ( $_ => $axis->{$_} ) : () } qw(min max);
163 if ( $type eq 'category' ) {
164 foreach my $end ( sort keys %given ) {
165 croak "$owner: the $end of $which must be a value, got " . describe( $given{$end} ) if ref $given{$end} && !( blessed $given{$end} && $given{$end}->can('epoch') );
166 }
167 return {};
168 }
169 my ( $parse, $expected )
170 = $type eq 'time' ? ( \&date_epoch, 'a date on a time axis' )
171 : $type eq 'auto' ? ( \&date_epoch, 'a number or a date' )
172 : ( \&number_of, 'a number' );
173 my %ends;
174 foreach my $end ( sort keys %given ) {
175 $ends{$end} = $parse->( $given{$end} ) // croak "$owner: the $end of $which must be $expected, got " . describe( $given{$end} );
176 croak "$owner: the $end of $which must be greater than 0 on a log axis, got " . describe( $given{$end} ) if $type eq 'log' && $ends{$end} <= 0;
177 }
178 croak "$owner: the min of $which (" . _end_text( $given{min} ) . ") must be less than its max (" . _end_text( $given{max} ) . ")"
179 if defined $ends{min} && defined $ends{max} && $ends{min} >= $ends{max};
180 return \%ends;
181 }
182  
183 # An axis end as messages show it: as it was given.
184 sub _end_text ($end) {
185 return ref $end ? describe($end) : $end;
186 }
187  
188 # ---------------------------------------------------------------------
189 # Accessors
190 # ---------------------------------------------------------------------
191  
192 method labels (@new) {
193 return defined $labels ? [@$labels] : undef unless @new;
194 $labels = defined $new[0] ? $self->_checked_labels( $new[0] ) : undef;
195 $self->mark_changed;
196 return $self->labels;
197 }
198  
199 method x_axis (@new) {
200 return {%$x_axis} unless @new;
201 ( $x_axis, $_ends{x_axis} ) = $self->_checked_axis( x_axis => $new[0] // {} );
202 $self->mark_changed;
203 return {%$x_axis};
204 }
205  
206 method y_axis (@new) {
207 return {%$y_axis} unless @new;
208 ( $y_axis, $_ends{y_axis} ) = $self->_checked_axis( y_axis => $new[0] // {} );
209 $self->mark_changed;
210 return {%$y_axis};
211 }
212  
213 method stacked (@new) {
214 return $stacked unless @new;
215 $stacked = $self->_checked_stacked( $new[0] );
216 $self->mark_changed;
217 return $stacked;
218 }
219  
220 method horizontal (@new) {
221 return $horizontal unless @new;
222 my $before = $horizontal;
223 $horizontal = boolean( $self, horizontal => $new[0] );
224 try {
225 $self->_check_horizontal;
226 }
227 catch ($error) {
228 $horizontal = $before;
229 die $error;
230 }
231 $self->mark_changed;
232 return $horizontal;
233 }
234  
235 method bar_width (@new) {
236 return $bar_width unless @new;
237 $bar_width = $self->_checked_fraction( bar_width => $new[0] );
238 $self->mark_changed;
239 return $bar_width;
240 }
241  
242 method marker (@new) { return $self->series_default( marker => @new ) }
243 method line (@new) { return $self->series_default( line => @new ) }
244 method curve (@new) { return $self->series_default( curve => @new ) }
245 method tension (@new) { return $self->series_default( tension => @new ) }
246 method line_style (@new) { return $self->series_default( line_style => @new ) }
247 method points (@new) { return $self->series_default( points => @new ) }
248 method point (@new) { return $self->series_default( point => @new ) }
249 method fill_opacity (@new) { return $self->series_default( fill_opacity => @new ) }
250 method max_points (@new) { return $self->series_default( max_points => @new ) }
251 method span_gaps (@new) { return $self->series_default( span_gaps => @new ) }
252 method value_labels (@new) { return $self->series_default( value_labels => @new ) }
253  
254 method transform (@new) {
255 $self->_set_default( transform => $new[0] ) if @new;
256 return;
257 }
258  
259 # ---------------------------------------------------------------------
260 # Preparing the data of a frame
261 # ---------------------------------------------------------------------
262  
263 # What the x values are: the axis type, or guessed from the data.
264 method _x_kind () {
265 my $type = $x_axis->{type};
266 return $type unless $type eq 'auto';
267 return 'category' if defined $labels;
268 my @xs = grep { defined } map {
269 map { $_->[0] }
270 $_->points->@*
271 } $self->all_series;
272 if ( !@xs ) {
273 return ( any { $_->type eq 'bar' } $self->all_series ) ? 'category' : 'linear';
274 }
275 return 'linear' if !grep { !defined number_of($_) } @xs;
276 return 'time' if !grep { !defined date_epoch($_) } @xs;
277 return 'category';
278 }
279  
280 # Turns an x value into a number for the axis kind; dies for values
281 # the axis cannot show.
282 method _x_number ( $kind, $x, $series_name, $categories ) {
283 if ( $kind eq 'category' ) {
284 my $label = blessed $x && $x->can('epoch') ? strftime( '%Y-%m-%d', localtime $x->epoch ) : "$x";
285 return $categories->{index}{$label} //= do { push $categories->{labels}->@*, $label; $categories->{labels}->$#* };
286 }
287 if ( $kind eq 'time' ) {
288 return date_epoch($x) // croak ref($self) . ": the x value " . describe($x) . " of series '$series_name' is not a date (the x axis is a time axis)";
289 }
290 return number_of($x) // croak ref($self) . ": the x value " . describe($x) . " of series '$series_name' is not a number (the x axis is $kind)";
291 }
292  
293 # The series as the frame draws them: x as numbers, prepared,
294 # stacked. See draw_plot.
295 method prepare_series () {
296 my $kind = $self->_x_kind;
297 my $categories = { labels => [ defined $labels ? @$labels : () ], index => {} };
298 $categories->{index}{ $categories->{labels}[$_] } //= $_ foreach 0 .. $categories->{labels}->$#*;
299  
300 my @prepared;
301 foreach my $series ( $self->visible_series ) {
302 my ( @xs, @ys );
303 my $index = 0;
304 foreach my $point ( $series->points->@* ) {
305 my ( $x, $y ) = @$point;
306 if ( !defined $x ) {
307 croak ref($self) . ": series '" . $series->name . "' needs x values for a time axis (give [ x, y ] points)" if $kind eq 'time';
308 if ( $kind eq 'category' ) {
309 push $categories->{labels}->@*, $index + 1 while $categories->{labels}->@* <= $index;
310 $x = $index;
311 }
312 else {
313 $x = $index;
314 }
315 }
316 else {
317 $x = $self->_x_number( $kind, $x, $series->name, $categories );
318 }
319 push @xs, $x;
320 push @ys, $y;
321 $index++;
322 }
323 my $type = $series->type;
324 if ( $kind ne 'category' && ( $type eq 'line' || $type eq 'area' ) ) {
325 my @order = sort { $xs[$a] <=> $xs[$b] } 0 .. $#xs;
326 @xs = @xs[@order];
327 @ys = @ys[@order];
328 }
329 my $steps = $self->series_option( $series, 'transform' );
330 ( my $xs, my $ys ) = $steps ? apply_transforms( $steps, \@xs, \@ys ) : ( \@xs, \@ys );
331 my ( $from, $to ) = map { my $raw = $series->option($_); defined $raw ? $self->_x_number( $kind, $raw, $series->name, $categories ) : undef } qw(from to);
332 push @prepared, { series => $series, name => $series->name, type => $type, xs => $xs, ys => $ys, from => $from, to => $to };
333 }
334 $self->stack_series( \@prepared );
335 return ( $kind, $categories->{labels}, \@prepared );
336 }
337  
338 # Gives every point of stacked series a base (y0) and a top (y1); the
339 # points of other series lie between the baseline and their value.
340 method stack_series ($prepared) {
341 my %totals;
342 my $group_of = sub ($entry) {
343 my $stack = $entry->{series}->option('stack') // ( $stacked && ( $entry->{type} eq 'bar' || $entry->{type} eq 'area' ) ? '' : undef );
344 return defined $stack ? $entry->{type} . "\0" . $stack : undef;
345 };
346 if ( $stacked eq 'percent' ) {
347 foreach my $entry (@$prepared) {
348 my $group = $group_of->($entry) // next;
349 $totals{$group}{ $entry->{xs}[$_] } += abs( $entry->{ys}[$_] // 0 ) foreach 0 .. $entry->{xs}->$#*;
350 }
351 }
352 my %running;
353 foreach my $entry (@$prepared) {
354 my $group = $group_of->($entry);
355 $entry->{group} = $group;
356 my ( @lows, @highs );
357 foreach my $index ( 0 .. $entry->{xs}->$#* ) {
358 my ( $x, $y ) = ( $entry->{xs}[$index], $entry->{ys}[$index] );
359 if ( !defined $group || !defined $y ) {
360 push @lows, undef;
361 push @highs, $y;
362 next;
363 }
364 $y = $totals{$group}{$x} ? $y / $totals{$group}{$x} : 0 if $stacked eq 'percent';
365 my $side = $y < 0 ? 'negative' : 'positive';
366 my $base = $running{$group}{$side}{$x} // 0;
367 push @lows, $base;
368 push @highs, $base + $y;
369 $running{$group}{$side}{$x} = $base + $y;
370 }
371 ( $entry->{lows}, $entry->{highs} ) = ( \@lows, \@highs );
372 }
373 return;
374 }
375  
376 # ---------------------------------------------------------------------
377 # Drawing
378 # ---------------------------------------------------------------------
379  
380 method default_legend_position () {
381 return 'top';
382 }
383  
384 # A hook for charts that show less than all of the data in narrow
385 # room: gets the room and what prepare_series returns, and returns it
386 # (changed).
387 method fit_prepared ( $width, $kind, $categories, $prepared ) {
388 return ( $kind, $categories, $prepared );
389 }
390  
391 # Horizontal charts show only bars.
392 method check_series_type ( $name, $type ) {
393 croak ref($self) . ": a horizontal chart shows only bar series, but '$name' is a $type series" if $horizontal && $type ne 'bar';
394 return;
395 }
396  
397 # Any point an axis can show later; what the axes cannot show is
398 # found when the frame is prepared.
399 method check_series_points ( $name, $points ) {
400 return;
401 }
402  
403 method _check_horizontal () {
404 $self->check_series_type( $_->name, $_->type ) foreach $self->all_series;
405 return;
406 }
407  
408 method legend_entries ($look) {
409 return map {
410 my $series = $_;
411 my $type = $series->type;
412 {
413 series => $series->name,
414 label => $series->name,
415 color => $self->_series_color( $look, $series ),
416 symbol => $type eq 'line' ? 'line' : $type eq 'scatter' ? 'point' : 'fill',
417 glyph => $type eq 'scatter' ? $self->_legend_point($series) : undef,
418 }
419 } $self->visible_series;
420 }
421  
422 method _series_color ( $look, $series ) {
423 return $series->color // $self->slot_color( $look, $series->slot );
424 }
425  
426 method _point_glyph ($series) {
427 my $glyph = $self->series_option( $series, 'point' );
428 return $glyph // ( $series->type eq 'scatter' ? SQUARE_POINT : LINE_POINT );
429 }
430  
431 # The point in the legend: the glyph, or a circle for dots.
432 method _legend_point ($series) {
433 my $glyph = $self->_point_glyph($series);
434 return $glyph eq DOT_POINT || $glyph eq SQUARE_POINT ? LEGEND_POINT : $glyph;
435 }
436  
437 method _marker_of ( $series, $orientation ) {
438 my $name = $self->series_option( $series, 'marker' ) // ( $series->type eq 'area' || $series->type eq 'bar' ? 'block' : 'braille' );
439 $name = 'block-horizontal' if $name eq 'block' && $orientation eq 'horizontal';
440 return $name;
441 }
442  
443 # Returns the number of rows used from the top of the area: the ticks
444 # may leave rows below the axis free. Nothing when no plot fits.
445 method draw_plot ( $surface, $x, $y, $width, $height, $look ) {
446 my ( $kind, $categories, $prepared ) = $self->fit_prepared( $width, $self->prepare_series );
447 my $frame = $self->_frame( $kind, $categories, $prepared, $x, $y, $width, $height ) // return;
448 $self->_draw_grid( $surface, $frame, $look );
449 $self->_draw_series( $surface, $frame, $prepared, $look );
450 $self->_draw_axes( $surface, $frame, $look );
451 my $bottom_shown = $frame->{orientation} eq 'vertical' ? $frame->{index_shown} : $frame->{value_shown};
452 return $frame->{top} - $y + $frame->{rows} + ( $bottom_shown ? 1 : 0 ) + $frame->{title_below};
453 }
454  
455 # Whether the chart reserves room for something: an axis that is
456 # visible (the default).
457 sub _shown ( $axis, $key ) {
458 return $axis->{$key} // 1;
459 }
460  
461 # The extent of x values (with the half slot bars need on numeric
462 # axes) and of y values (bases included) over the drawn series. With
463 # a span on the x axis, x runs over the last span up to the newest
464 # point, and only the points in it count for y. Values a logarithmic
465 # axis cannot show (0 and below) do not count.
466 method _extents ( $kind, $prepared ) {
467 my ( @xs, @samples ); # a sample: [ x, y, the y it rises from or undef ]
468 foreach my $entry (@$prepared) {
469 foreach my $index ( 0 .. $entry->{xs}->$#* ) {
470 my $y = $entry->{highs}[$index] // next;
471 my $x = $entry->{xs}[$index];
472 next if defined $entry->{from} && $x < $entry->{from};
473 next if defined $entry->{to} && $x > $entry->{to};
474 push @xs, $x, ( $entry->{edges} ? $entry->{edges}[$index]->@* : () );
475 push @samples, [ $x, $y, $entry->{lows}[$index] ];
476 }
477 }
478 @xs = grep { $_ > 0 } @xs if $kind eq 'log';
479 my $x_extent = @xs ? [ min(@xs), max(@xs) ] : undef;
480 if ( $kind ne 'category' && $x_extent && !grep { $_->{edges} } @$prepared ) {
481 my $spacing = $self->_bar_spacing($prepared);
482 $x_extent = [ $x_extent->[0] - $spacing / 2, $x_extent->[1] + $spacing / 2 ] if $spacing;
483 }
484 my $span = $x_axis->{span};
485 if ( defined $span && $x_extent && $kind ne 'category' ) {
486 $x_extent = [ $x_extent->[1] - $span, $x_extent->[1] ];
487 @samples = grep { $_->[0] >= $x_extent->[0] } @samples;
488 }
489 my @ys = map { ( $_->[1], $_->[2] // () ) } @samples;
490 @ys = grep { $_ > 0 } @ys if $y_axis->{type} eq 'log';
491 my $y_extent = @ys ? [ min(@ys), max(@ys) ] : undef;
492 return ( $x_extent, $y_extent );
493 }
494  
495 # The smallest distance between two x values of bars on a numeric
496 # axis: the width of one bar slot. 0 without bars.
497 method _bar_spacing ($prepared) {
498 my @xs = sort { $a <=> $b } uniq map { $_->{xs}->@* } grep { $_->{type} eq 'bar' && !$_->{edges} } @$prepared;
499 return 0 unless @xs;
500 return 1 if @xs == 1;
501 return min( map { $xs[$_] - $xs[ $_ - 1 ] } 1 .. $#xs );
502 }
503  
504 method value_format () {
505 return $stacked eq 'percent' && !defined $y_axis->{format} ? 'percent' : $y_axis->{format};
506 }
507  
508 # Lays out the axes and the plot in the chart's area and fits the
509 # scales: the frame every part is drawn in.
510 method _frame ( $kind, $categories, $prepared, $left, $top, $width, $height ) {
511 my ( $x_extent, $y_extent ) = $self->_extents( $kind, $prepared );
512 my $bar_like = any { $_->{type} eq 'bar' || $_->{type} eq 'area' || defined $_->{group} } @$prepared;
513 my $percent = $stacked eq 'percent';
514 my $measure = sub ($label) { Term::Fabulous::Chart::Surface->text_columns($label) };
515  
516 # The y axis holds the values and the x axis the x values
517 # (categories), also when horizontal bars turn them on their side.
518 my ( $value_axis, $index_axis ) = ( $y_axis, $x_axis );
519 my $value_shown = _shown( $value_axis, 'visible' );
520 my $index_shown = _shown( $index_axis, 'visible' );
521  
522 my $fit_value = sub ( $cells, $orientation ) {
523 my %common = ( cells => $cells, orientation => $orientation, measure => $measure, extent => $y_extent, format => $self->value_format );
524 return Term::Fabulous::Chart::Scale::Log->fit( %common, $_ends{y_axis}->%*, map { defined $value_axis->{$_} ? ( $_ => $value_axis->{$_} ) : () } qw(base) )
525 if $value_axis->{type} eq 'log';
526 my $integer = $y_extent && !grep { defined && $_ != int } map { $_->{ys}->@* } @$prepared;
527 return Term::Fabulous::Chart::Scale::Linear->fit(
528 %common,
529 align => $orientation eq 'vertical' || ( exists $value_axis->{grid} ? $value_axis->{grid} : 1 ) ? 1 : 0,
530 zero => $value_axis->{zero} // $bar_like,
531 integer => $integer && !$percent,
532 ( $percent ? ( min => 0, max => 1 ) : () ),
533 $_ends{y_axis}->%*,
534 map { defined $value_axis->{$_} ? ( $_ => $value_axis->{$_} ) : () } qw(ticks step nice),
535 );
536 };
537 my $band = $kind eq 'category' && ( any { $_->{type} eq 'bar' } @$prepared ) ? 1 : 0;
538 my $fit_index = sub ( $cells, $orientation ) {
539 my %common = ( cells => $cells, orientation => $orientation, measure => $measure, format => $index_axis->{format} );
540 return Term::Fabulous::Chart::Scale::Category->fit( %common, labels => $categories, band => $band ) if $kind eq 'category';
541 my %ends = $_ends{x_axis}->%*;
542 return Term::Fabulous::Chart::Scale::Time->fit( %common, extent => $x_extent, utc => $index_axis->{utc}, %ends ) if $kind eq 'time';
543 return Term::Fabulous::Chart::Scale::Log->fit( %common, extent => $x_extent, base => $index_axis->{base}, %ends ) if $kind eq 'log';
544 return Term::Fabulous::Chart::Scale::Linear->fit(
545 %common,
546 align => $index_axis->{grid} ? 1 : 0,
547 integer => (
548 !grep { $_ != int } map {
549 $_->{xs}->@*,
550 map { @$_ } ( $_->{edges} // [] )->@*
551 } @$prepared
552 ) ? 1 : 0,
553 extent => $x_extent,
554 nice => $index_axis->{nice} // ( ( grep { $_->{edges} } @$prepared ) ? 0 : 1 ),
555 %ends,
556 map { defined $index_axis->{$_} ? ( $_ => $index_axis->{$_} ) : () } qw(ticks step),
557 );
558 };
559  
560 my $frame = { kind => $kind, band => $band, edges => ( grep { $_->{edges} } @$prepared ) ? 1 : 0 };
561 my $title_rows_below = defined $x_axis->{title} && length $x_axis->{title} ? 1 : 0;
562 my $title_row_above = defined $y_axis->{title} && length $y_axis->{title} ? 1 : 0;
563  
564 if ( !$horizontal ) {
565 my $plot_rows = $height - ( $index_shown ? 1 : 0 ) - $title_rows_below - $title_row_above;
566 if ( $plot_rows < 2 ) {
567 ( $title_rows_below, $title_row_above ) = ( 0, 0 );
568 $plot_rows = $height - ( $index_shown && $height > 3 ? 1 : 0 );
569 $index_shown = 0 if $plot_rows == $height;
570 }
571 return undef if $plot_rows < 1;
572  
573 # Bars with value labels keep a row free above the highest one.
574 my $label_room = $plot_rows >= 6 && ( grep { $_->{type} eq 'bar' && $self->series_option( $_->{series}, 'value_labels' ) } @$prepared ) ? 1 : 0;
575 $plot_rows -= $label_room;
576 my $value_scale = $fit_value->( $plot_rows, 'vertical' );
577  
578 # Rows the ticks leave unused go below the axis, where they read
579 # as a margin.
580 $plot_rows = $value_scale->used;
581 my $gutter = $value_shown ? max( map { $measure->( $_->{label} ) } $value_scale->ticks ) + 1 : 0;
582 $gutter = 0 if $gutter > $width / 2;
583  
584 # The labels of the last x tick may stick out right of the plot.
585 my $margin = 0;
586 my $index_scale;
587 foreach my $attempt ( 1, 2 ) {
588 my $plot_columns = $width - $gutter - $margin;
589 return undef if $plot_columns < 2;
590 $index_scale = $fit_index->( $plot_columns, 'horizontal' );
591 last if $band || $frame->{edges} || !$index_shown;
592 my @ticks = $index_scale->ticks;
593 my $last = $ticks[-1] // last;
594 my $wanted = max( 0, ceil( $measure->( $last->{label} ) / 2 - ( 1 - $last->{position} ) * ( $index_scale->used - 1 ) - ( $plot_columns - $index_scale->used ) - 1e-9 ) );
595 last if $wanted <= $margin;
596 $margin = $wanted;
597 }
598 %$frame = (
599 %$frame,
600 orientation => 'vertical',
601 left => $left + $gutter,
602 top => $top + $title_row_above + $label_room,
603 label_room => $label_room,
604 columns => $width - $gutter - $margin,
605 rows => $plot_rows,
606 value_scale => $value_scale,
607 index_scale => $index_scale,
608 gutter => $gutter,
609 area_left => $left,
610 area_width => $width,
611 value_shown => $value_shown,
612 index_shown => $index_shown,
613 title_above => $title_row_above,
614 title_below => $title_rows_below,
615 );
616 return $frame;
617 }
618  
619 # Horizontal bars: categories down the left, values along the bottom.
620 my $plot_rows = $height - ( $value_shown ? 1 : 0 ) - $title_rows_below - $title_row_above;
621 if ( $plot_rows < 2 ) {
622 ( $title_rows_below, $title_row_above ) = ( 0, 0 );
623 $plot_rows = $height - ( $value_shown && $height > 3 ? 1 : 0 );
624 $value_shown = 0 if $plot_rows == $height;
625 }
626 return undef if $plot_rows < 1;
627 my $index_scale = $fit_index->( $plot_rows, 'vertical' );
628 my $gutter = $index_shown ? min( max( 0, map { $measure->( $_->{label} ) } $index_scale->ticks ) + 1, int( $width / 3 ) ) : 0;
629 my $plot_columns = $width - $gutter;
630 return undef if $plot_columns < 2;
631 my $value_scale = $fit_value->( $plot_columns, 'horizontal' );
632 my @ticks = $value_scale->ticks;
633 my $margin = @ticks ? max( 0, ceil( $measure->( $ticks[-1]{label} ) / 2 ) - ( $plot_columns - $value_scale->used ) ) : 0;
634  
635 if ( $margin && $plot_columns - $margin >= 2 ) {
636 $value_scale = $fit_value->( $plot_columns - $margin, 'horizontal' );
637 }
638 else {
639 $margin = 0;
640 }
641 %$frame = (
642 %$frame,
643 orientation => 'horizontal',
644 left => $left + $gutter,
645 top => $top + $title_row_above,
646 columns => $value_scale->used,
647 rows => $plot_rows,
648 value_scale => $value_scale,
649 index_scale => $index_scale,
650 gutter => $gutter,
651 area_left => $left,
652 area_width => $width,
653 value_shown => $value_shown,
654 index_shown => $index_shown,
655 title_above => $title_row_above,
656 title_below => $title_rows_below,
657 );
658 return $frame;
659 }
660  
661 # Positions in cells inside the plot, continuous: the value axis puts
662 # its ends on the centers of its first and last cell, so labels and
663 # grid lines meet; categories take slots; histograms fill edge to edge.
664 method _value_position ( $frame, $value ) {
665 my $scale = $frame->{value_scale};
666 my $t = $scale->position($value) // return undef;
667 if ( $self->value_axis_edges ) {
668 return $frame->{orientation} eq 'vertical' ? ( 1 - $t ) * $frame->{rows} : $t * $frame->{columns};
669 }
670 if ( $frame->{orientation} eq 'vertical' ) {
671 return ( $frame->{rows} - $scale->used ) + ( 1 - $t ) * ( $scale->used - 1 ) + 0.5;
672 }
673 return $t * ( $scale->used - 1 ) + 0.5;
674 }
675  
676 # Whether the value axis runs from edge to edge of the plot instead of
677 # from the center of its first cell to the center of its last, where
678 # grid lines and labels meet the ticks. Charts without an axis (a
679 # sparkline) use the whole height.
680 method value_axis_edges () {
681 return 0;
682 }
683  
684 # Whether the baseline is drawn in the axis color.
685 method draws_baseline () {
686 return 1;
687 }
688  
689 method _index_position ( $frame, $value ) {
690 my $scale = $frame->{index_scale};
691 my $t = $scale->position($value) // return undef;
692 my $cells = $frame->{orientation} eq 'vertical' ? $frame->{columns} : $frame->{rows};
693 return $t * $cells if $frame->{band} || $frame->{edges};
694 return $t * ( $scale->used - 1 ) + 0.5;
695 }
696  
697 # The baseline bars and areas grow from: 0, or the end of the value
698 # axis nearest to it.
699 method _baseline ($frame) {
700 my $scale = $frame->{value_scale};
701 return $scale->min if $scale->kind eq 'log';
702 return $scale->min > 0 ? $scale->min : $scale->max < 0 ? $scale->max : 0;
703 }
704  
705 method _draw_grid ( $surface, $frame, $look ) {
706 my ( $left, $top, $columns, $rows ) = @$frame{qw(left top columns rows)};
707 my $vertical = $frame->{orientation} eq 'vertical';
708 my $value_grid = exists $y_axis->{grid} ? $y_axis->{grid} : 'solid';
709 my $index_grid = exists $x_axis->{grid} ? $x_axis->{grid} : 0;
710  
711 # Value grid lines: rows in a vertical chart, columns in a horizontal one.
712 if ($value_grid) {
713 my $glyph = $GRID_GLYPHS{$value_grid}[ $vertical ? 0 : 1 ];
714 foreach my $tick ( $frame->{value_scale}->ticks ) {
715 my $at = floor( $self->_value_position( $frame, $tick->{value} ) // next );
716 if ($vertical) {
717 next if $at < 0 || $at >= $rows;
718 $surface->put( $left + $_, $top + $at, $glyph, $look->{grid} ) foreach 0 .. $columns - 1;
719 }
720 else {
721 next if $at < 0 || $at >= $columns;
722 $surface->put( $left + $at, $top + $_, $glyph, $look->{grid} ) foreach 0 .. $rows - 1;
723 }
724 }
725 }
726 if ( $index_grid && !$frame->{band} ) {
727 my $glyph = $GRID_GLYPHS{$index_grid}[ $vertical ? 1 : 0 ];
728 my $cross = $value_grid eq 'solid' && $index_grid eq 'solid' ? "\x{253C}" : undef;
729 foreach my $tick ( $frame->{index_scale}->ticks ) {
730 my $at = floor( $self->_index_position( $frame, $tick->{value} ) // next );
731 foreach my $along ( 0 .. ( $vertical ? $rows : $columns ) - 1 ) {
732 my ( $x, $y ) = $vertical ? ( $left + $at, $top + $along ) : ( $left + $along, $top + $at );
733 next unless $at >= 0 && $at < ( $vertical ? $columns : $rows );
734 my $crossing = defined $cross && defined $surface->glyph_at( $x, $y ) && $surface->glyph_at( $x, $y ) eq $GRID_GLYPHS{solid}[ $vertical ? 0 : 1 ];
735 $surface->put( $x, $y, $crossing ? $cross : $glyph, $look->{grid} );
736 }
737 }
738 }
739  
740 # The baseline, in the axis color: where bars and areas grow from.
741 return unless $self->draws_baseline;
742 my $base = floor( $self->_value_position( $frame, $self->_baseline($frame) ) // return );
743 $base = $vertical ? List::Util::min( $base, $rows - 1 ) : List::Util::min( $base, $columns - 1 );
744 if ($vertical) {
745 $surface->put( $left + $_, $top + $base, "\x{2500}", $look->{axis} ) foreach 0 .. $columns - 1;
746 }
747 else {
748 $surface->put( $left + $base, $top + $_, "\x{2502}", $look->{axis} ) foreach 0 .. $rows - 1;
749 }
750 return;
751 }
752  
753 # Every series, layer by layer: fills (areas, then bars) below lines,
754 # lines below points. The emphasized series is drawn last in its layer
755 # unless it is part of a stack.
756 method _draw_series ( $surface, $frame, $prepared, $look ) {
757 my @order = sort { $self->_draws_last( $look, $a ) <=> $self->_draws_last( $look, $b ) } @$prepared;
758 my %rasters; # marker name => raster, in order of first use
759 my @raster_order;
760 my $raster = sub ( $name, $layer ) {
761 my $key = "$layer\0$name";
762 return $rasters{$key} //= do {
763 push @raster_order, $key;
764 Term::Fabulous::Chart::Raster->new( marker => Term::Fabulous::Chart::Marker->named($name), columns => $frame->{columns}, rows => $frame->{rows} );
765 };
766 };
767 my @box_lines; # drawn in cells, over the rasters
768 my @glyph_points; # [ column, row, glyph, color, owner ], over everything
769  
770 # Each point is a target the pointer can find.
771 foreach my $entry (@order) {
772 $entry->{targets} = [ map { $self->_point_target( $frame, $entry, $_ ) } 0 .. $entry->{xs}->$#* ];
773 $entry->{color} = $self->shown_color( $look, $entry->{name}, $self->_series_color( $look, $entry->{series} ) );
774 }
775  
776 foreach my $entry ( grep { $_->{type} eq 'area' } @order ) {
777 $self->_draw_area_fill( $raster->( $self->_marker_of( $entry->{series}, 'vertical' ), 'fill' ), $frame, $entry, $look );
778 }
779 my @bars = grep { $_->{type} eq 'bar' } @order;
780 $self->_draw_bars( $raster, $frame, \@bars, $look ) if @bars;
781 foreach my $entry ( grep { $_->{type} eq 'line' || ( $_->{type} eq 'area' && $self->_has_line($_) ) } @order ) {
782 my $marker = $entry->{type} eq 'area' ? 'braille' : $self->_marker_of( $entry->{series}, 'vertical' );
783 if ( $marker eq 'box' ) {
784 push @box_lines, $entry;
785 }
786 else {
787 $self->_draw_line( $raster->( $marker, 'stroke' ), $frame, $entry );
788 }
789 push @glyph_points, $self->_draw_points( $raster->( 'braille', 'stroke' ), $frame, $entry ) if $self->series_option( $entry->{series}, 'points' );
790 }
791 foreach my $entry ( grep { $_->{type} eq 'scatter' } @order ) {
792 push @glyph_points, $self->_draw_points( $raster->( $self->_marker_of( $entry->{series}, 'vertical' ), 'stroke' ), $frame, $entry );
793 }
794 foreach my $entry ( grep { $self->series_option( $_->{series}, 'trend' ) } @order ) {
795 $self->_draw_trend( $raster->( 'braille', 'stroke' ), $frame, $entry );
796 }
797  
798 foreach my $key (@raster_order) {
799 my ( $layer, $name ) = split /\0/, $key;
800 $surface->composite( $rasters{$key}, $layer, $frame->{left}, $frame->{top} );
801 }
802 $self->_draw_box_line( $surface, $frame, $_ ) foreach @box_lines;
803 foreach my $point (@glyph_points) {
804 my ( $x, $y, $glyph, $color, $owner ) = @$point;
805 $surface->put( $frame->{left} + $x, $frame->{top} + $y, $glyph, $color );
806 $surface->set_owner( $frame->{left} + $x, $frame->{top} + $y, 'stroke', $owner );
807 }
808 $self->_draw_value_labels( $surface, $frame, \@bars, $look ) if grep { $self->series_option( $_->{series}, 'value_labels' ) } @bars;
809 return;
810 }
811  
812 # An area has no line along its top unless asked to: block fills show
813 # the edge to an eighth of a cell, while a Braille line on top takes
814 # over the cells it passes and so places the edge only to half a cell.
815 method _has_line ($entry) {
816 return $self->series_option( $entry->{series}, 'line' ) // 0;
817 }
818  
819 method _draws_last ( $look, $entry ) {
820 return $self->is_emphasized( $look, $entry->{name} ) && !defined $entry->{group} ? 1 : 0;
821 }
822  
823 method _point_target ( $frame, $entry, $index ) {
824 my $x = $entry->{xs}[$index];
825 my $scale = $frame->{index_scale};
826 my $label
827 = $entry->{labels} ? $entry->{labels}[$index]
828 : $scale->kind eq 'category' ? ( $scale->label_at($x) // $x )
829 : $scale->kind eq 'time' ? strftime( $x_axis->{format} && !ref $x_axis->{format} ? $x_axis->{format} : '%Y-%m-%d %H:%M', $x_axis->{utc} ? gmtime $x : localtime $x )
830 : format_value($x);
831 return $self->register_target( series => $entry->{name}, index => $index, label => $label, value => $entry->{ys}[$index], x => $x );
832 }
833  
834 # The runs of drawable points of a series, as [ x, y, target ] in plot
835 # cells: gaps (undef, or values a log axis cannot show) end a run
836 # unless the series spans them. A run is { points => [...], sorted =>
837 # whether x never falls }; the points of a sorted run are found by
838 # halving it (line and area series are sorted unless on a category
839 # axis).
840 method _runs ( $frame, $entry, $values ) {
841 my $span = $self->series_option( $entry->{series}, 'span_gaps' );
842 my ( @runs, @run );
843 foreach my $index ( 0 .. $entry->{xs}->$#* ) {
844 my $value = $values->[$index];
845 my $x = $self->_index_position( $frame, $entry->{xs}[$index] );
846 my $y = defined $value ? $self->_value_position( $frame, $value ) : undef;
847 if ( !defined $x || !defined $y ) {
848 next if $span;
849 push @runs, _run(@run) if @run;
850 @run = ();
851 next;
852 }
853 push @run, [ $x, $y, $entry->{targets}[$index] ];
854 }
855 push @runs, _run(@run) if @run;
856 return @runs;
857 }
858  
859 # A run of points, and whether it is sorted by x.
860 sub _run (@points) {
861 my $sorted = all { $points[ $_ - 1 ][0] <= $points[$_][0] } 1 .. $#points;
862 return { points => \@points, sorted => $sorted ? 1 : 0 };
863 }
864  
865 # How many of the first $count points pass $test, which a point passes
866 # only when every point before it does.
867 sub _leading ( $points, $count, $test ) {
868 my ( $low, $high ) = ( 0, $count );
869 while ( $low < $high ) {
870 my $middle = int( ( $low + $high ) / 2 );
871 $test->( $points->[$middle] ) ? ( $low = $middle + 1 ) : ( $high = $middle );
872 }
873 return $low;
874 }
875  
876 # The polyline of a run along the series' curve, cut to from .. to.
877 # Of a sorted run, only the segments that reach into the plot (or the
878 # cell around it) are made, so a long history beside the plot costs
879 # nothing; the shape there is the shape of the whole curve. With
880 # whole, every segment is made: a dashed line counts the steps before
881 # the plot for its dashes.
882 method _run_polyline ( $frame, $entry, $run, $step, %options ) {
883 my $points = $run->{points};
884 my $curve = $self->series_option( $entry->{series}, 'curve' ) // 'linear';
885 my @between = $run->{sorted} && !$options{whole} ? ( between => [ _points_around( $points, -1, $frame->{columns} + 1 ) ] ) : ();
886 my $polyline = curve_points( $points, $curve, step => $step, tension => $self->series_option( $entry->{series}, 'tension' ) // 0, @between );
887 my ( $from, $to ) = map { defined $entry->{$_} ? $self->_index_position( $frame, $entry->{$_} ) : undef } qw(from to);
888 return $polyline unless defined $from || defined $to;
889 return _clip_polyline( $polyline, $from, $to );
890 }
891  
892 # The first and last index of the points of a sorted run whose
893 # segments reach into $left .. $right: from the last point left of it
894 # to the first point right of it.
895 sub _points_around ( $points, $left, $right ) {
896 my $before_left = _leading( $points, scalar @$points, sub ($point) { $point->[0] < $left } );
897 my $up_to_right = _leading( $points, scalar @$points, sub ($point) { $point->[0] <= $right } );
898 return ( max( 0, $before_left - 1 ), min( $#$points, $up_to_right ) );
899 }
900  
901 # The part of a polyline between two x positions, with the ends
902 # interpolated, so a series starts and ends exactly there.
903 sub _clip_polyline ( $polyline, $from, $to ) {
904 my @kept;
905 $from //= $polyline->[0][0];
906 $to //= $polyline->[-1][0];
907 return [] if $to < $polyline->[0][0] || $from > $polyline->[-1][0];
908 push @kept, [ $from, y_at( $polyline, $from ) ] if $from > $polyline->[0][0];
909 push @kept, grep { $_->[0] >= $from && $_->[0] <= $to } @$polyline;
910 push @kept, [ $to, y_at( $polyline, $to ) ] if $to < $polyline->[-1][0];
911 return \@kept;
912 }
913  
914 # The target of the point of a run nearest to x; of points as near,
915 # the first. A sorted run is searched by halving it: the nearest point
916 # is the first one at or right of x, or among those just left of it.
917 sub _nearest_target ( $run, $x ) {
918 my $points = $run->{points};
919 return _nearest_target_by_scan( $points, $x ) unless $run->{sorted};
920 my $right = _leading( $points, scalar @$points, sub ($point) { $point->[0] < $x } );
921 return $points->[0][2] if $right == 0;
922 my $left_distance = abs( $points->[ $right - 1 ][0] - $x );
923 return $points->[$right][2] if $right < @$points && abs( $points->[$right][0] - $x ) < $left_distance;
924 my $first_as_near = _leading( $points, $right, sub ($point) { abs( $point->[0] - $x ) > $left_distance } );
925 return $points->[$first_as_near][2];
926 }
927  
928 sub _nearest_target_by_scan ( $points, $x ) {
929 my ( $best, $distance );
930 foreach my $point (@$points) {
931 my $away = abs( $point->[0] - $x );
932 ( $best, $distance ) = ( $point->[2], $away ) if !defined $distance || $away < $distance;
933 }
934 return $best;
935 }
936  
937 method _draw_line ( $raster, $frame, $entry ) {
938 my ( $sx, $sy ) = ( $raster->marker->columns, $raster->marker->rows );
939 my $series = $entry->{series};
940 my $pattern = $series->dash_pattern( $self->series_option( $series, 'line_style' ) // 'solid' );
941 $raster->start_pattern($pattern);
942 foreach my $run ( $self->_runs( $frame, $entry, $entry->{highs} ) ) {
943 my $polyline = $self->_run_polyline( $frame, $entry, $run, 1 / $sx, whole => defined $pattern );
944 next unless @$polyline;
945 if ( @$polyline == 1 ) {
946 $raster->set( floor( $polyline->[0][0] * $sx ), floor( $polyline->[0][1] * $sy ), $entry->{color}, $run->{points}[0][2] );
947 next;
948 }
949 foreach my $index ( 1 .. $#$polyline ) {
950 my ( $from, $to ) = @$polyline[ $index - 1, $index ];
951 my $owner = _nearest_target( $run, ( $from->[0] + $to->[0] ) / 2 );
952 $raster->line( $from->[0] * $sx, $from->[1] * $sy, $to->[0] * $sx, $to->[1] * $sy, $entry->{color}, $owner );
953 }
954 }
955 $raster->start_pattern(undef);
956 return;
957 }
958  
959 method _draw_area_fill ( $raster, $frame, $entry, $look ) {
960 my ( $sx, $sy ) = ( $raster->marker->columns, $raster->marker->rows );
961 my $opacity = ( $self->series_option( $entry->{series}, 'fill_opacity' ) // ( defined $entry->{group} ? STACKED_FILL_OPACITY : AREA_FILL_OPACITY ) ) * $entry->{series}->color_opacity;
962 my $base_y = $self->_value_position( $frame, $self->_baseline($frame) );
963 my @lows = $self->_runs( $frame, $entry, $entry->{lows} );
964 foreach my $run ( $self->_runs( $frame, $entry, $entry->{highs} ) ) {
965 my $top = $self->_run_polyline( $frame, $entry, $run, 1 / $sx );
966 next if @$top < 2;
967 my ( $run_start, $run_end ) = ( $run->{points}[0][0], $run->{points}[-1][0] );
968 my $low = first { $_->{points}[0][0] <= $run_start && $_->{points}[-1][0] >= $run_end } @lows;
969 my $bottom = defined $entry->{group} && $low ? $self->_run_polyline( $frame, $entry, $low, 1 / $sx ) : undef;
970 foreach my $column ( max( 0, floor( $top->[0][0] * $sx ) ) .. min( $raster->width - 1, ceil( $top->[-1][0] * $sx ) ) ) {
971 my $center = ( $column + 0.5 ) / $sx;
972 my $high_y = y_at( $top, $center ) // next;
973 my $low_y = $bottom ? y_at( $bottom, $center ) // $base_y : $base_y;
974 $raster->fill_column( $column, $high_y * $sy, $low_y * $sy, $entry->{color}, _nearest_target( $run, $center ), $opacity, $look->{base} );
975 }
976 }
977 return;
978 }
979  
980 # Bars: in slots of categories (side by side for several series,
981 # one on the other for a stack), around their x on a numeric axis,
982 # or from edge to edge (histograms).
983 method _draw_bars ( $raster_for, $frame, $bars, $look ) {
984 my $vertical = $frame->{orientation} eq 'vertical';
985  
986 # The slots in series order, whatever order the bars are drawn in.
987 my @columns = uniq map { $_->{group} // "\0" . $_->{name} } sort { $a->{series}->slot <=> $b->{series}->slot } @$bars;
988 my %column_of = map { $columns[$_] => $_ } 0 .. $#columns;
989 my $length = $vertical ? $frame->{columns} : $frame->{rows};
990 my $slot
991 = $frame->{band} ? $frame->{index_scale}->slot_cells
992 : $frame->{edges} ? undef
993 : do {
994 my $spacing = $self->_bar_spacing($bars);
995 my $first = $self->_index_position( $frame, 0 ) // 0;
996 abs( ( $self->_index_position( $frame, $spacing ) // $first ) - $first ) || 1;
997 };
998 my $base = $self->_baseline($frame);
999  
1000 $frame->{bar_columns} = scalar @columns;
1001 foreach my $entry (@$bars) {
1002 my $marker = $self->_marker_of( $entry->{series}, $vertical ? 'vertical' : 'horizontal' );
1003 my $raster = $raster_for->( $marker, 'fill' );
1004 my ( $along, $across ) = $vertical ? ( $raster->marker->columns, $raster->marker->rows ) : ( $raster->marker->rows, $raster->marker->columns );
1005 $frame->{bar_resolution} //= $along;
1006 my $opacity = ( $self->series_option( $entry->{series}, 'fill_opacity' ) // $self->default_bar_opacity($bars) ) * $entry->{series}->color_opacity;
1007 foreach my $index ( 0 .. $entry->{xs}->$#* ) {
1008 my $high = $entry->{highs}[$index] // next;
1009 my $low = $entry->{lows}[$index] // $base;
1010 my ( $start, $end );
1011 if ( $entry->{edges} ) {
1012 ( $start, $end ) = map { $self->_index_position( $frame, $_ ) } $entry->{edges}[$index]->@*;
1013 $end -= $self->_bin_gap( $end - $start );
1014 }
1015 else {
1016 my $center = $self->_index_position( $frame, $entry->{xs}[$index] ) // next;
1017 ( $start, $end ) = _bar_span( $center, $slot, $bar_width, scalar @columns, $column_of{ $entry->{group} // "\0" . $entry->{name} }, $along );
1018 }
1019 ( $start, $end ) = map { floor( $_ * $along + 0.5 ) / $along } $start, $end;
1020 $end = $start + 1 / $along if $end <= $start;
1021 my ( $from, $to ) = map { $self->_value_position( $frame, $_ ) } $low, $high;
1022 next unless defined $from && defined $to;
1023 my $owner = $entry->{targets}[$index];
1024 if ($vertical) {
1025 $raster->fill_rect( $start * $along, $from * $across, $end * $along, $to * $across, $entry->{color}, $owner, $opacity, $look->{base} );
1026 }
1027 else {
1028 $raster->fill_rect( $from * $across, $start * $along, $to * $across, $end * $along, $entry->{color}, $owner, $opacity, $look->{base} );
1029 }
1030 $entry->{bar_ends}[$index] = [ ( $start + $end ) / 2, $to ];
1031 }
1032 }
1033 return;
1034 }
1035  
1036 # Bars are opaque; a histogram overrides this for overlapping bins.
1037 method default_bar_opacity ($bars) {
1038 return 1;
1039 }
1040  
1041 # The gap at the right of a histogram bin: one cell between wide bins.
1042 method _bin_gap ($width) {
1043 return $width >= 4 ? 1 : 0;
1044 }
1045  
1046 # The [start, end) of bar $column of $columns in the slot around
1047 # $center; the bars of a slot take $width of it together. Every bar
1048 # is a whole number of subpixels ($resolution per cell) wide, and the
1049 # bars of a slot are equally wide.
1050 sub _bar_span ( $center, $slot, $width, $columns, $column, $resolution ) {
1051 my ( $first, $each ) = _bar_group( $center, $slot, $width, $columns, $resolution );
1052 my $start = $first + $column * $each;
1053 return ( $start, $start + $each );
1054 }
1055  
1056 # Where the bars of a slot start, and how wide each is.
1057 sub _bar_group ( $center, $slot, $width, $columns, $resolution ) {
1058 my $each = max( 1, floor( $slot * $width * $resolution / $columns ) ) / $resolution;
1059 my $first = floor( ( $center - $each * $columns / 2 ) * $resolution + 0.5 ) / $resolution;
1060 return ( $first, $each );
1061 }
1062  
1063 # The cell a label of the category at $center goes in, across the
1064 # bars: the middle of the bar group (its upper middle row, when the
1065 # group is an even number of cells high).
1066 method _category_cell ( $frame, $center ) {
1067 return floor($center) unless $frame->{band} && $frame->{bar_columns};
1068 my ( $first, $each ) = _bar_group( $center, $frame->{index_scale}->slot_cells, $bar_width, $frame->{bar_columns}, $frame->{bar_resolution} );
1069 return ceil( $first + $each * $frame->{bar_columns} / 2 ) - 1;
1070 }
1071  
1072 # Draws the points of a series: dots into the raster; returns the
1073 # glyph points, which are drawn over the cells later.
1074 method _draw_points ( $raster, $frame, $entry ) {
1075 my $glyph = $self->_point_glyph( $entry->{series} );
1076 my ( $sx, $sy ) = ( $raster->marker->columns, $raster->marker->rows );
1077 my @points;
1078 foreach my $run ( $self->_runs( $frame, $entry, $entry->{highs} ) ) {
1079 foreach my $point ( $run->{points}->@* ) {
1080 my ( $x, $y, $owner ) = @$point;
1081 next if defined $entry->{from} && $x < $self->_index_position( $frame, $entry->{from} );
1082 next if defined $entry->{to} && $x > $self->_index_position( $frame, $entry->{to} );
1083 if ( $glyph eq DOT_POINT ) {
1084 $raster->set( floor( $x * $sx ), floor( $y * $sy ), $entry->{color}, $owner );
1085 next;
1086 }
1087 if ( $glyph eq SQUARE_POINT ) {
1088 my ( $left, $top ) = ( floor( $x * $sx - 0.5 ), floor( $y * $sy - 0.5 ) );
1089 $raster->set( $left + $_ % 2, $top + int( $_ / 2 ), $entry->{color}, $owner ) foreach 0 .. 3;
1090 next;
1091 }
1092 my ( $column, $row ) = ( floor($x), floor($y) );
1093 next if $column < 0 || $row < 0 || $column >= $frame->{columns} || $row >= $frame->{rows};
1094 push @points, [ $column, $row, $glyph, $entry->{color}, $owner ];
1095 }
1096 }
1097 return @points;
1098 }
1099  
1100 # The least-squares line through the points, dashed, from the first
1101 # to the last x.
1102 method _draw_trend ( $raster, $frame, $entry ) {
1103 my @known = grep { defined $entry->{highs}[$_] } 0 .. $entry->{xs}->$#*;
1104 return if @known < 2;
1105 my ( $xs, $ys ) = apply_transforms( parse_transforms( ref $self, 'trend', 'regression' ), [ @{ $entry->{xs} }[@known] ], [ @{ $entry->{highs} }[@known] ] );
1106 my ( $first, $last ) = ( sort { $xs->[$a] <=> $xs->[$b] } 0 .. $#$xs )[ 0, -1 ];
1107 my @ends = map { [ $self->_index_position( $frame, $xs->[$_] ), $self->_value_position( $frame, $ys->[$_] ) ] } $first, $last;
1108 return if grep { !defined $_->[0] || !defined $_->[1] } @ends;
1109 my ( $sx, $sy ) = ( $raster->marker->columns, $raster->marker->rows );
1110 $raster->start_pattern(TREND_PATTERN);
1111 $raster->line( $ends[0][0] * $sx, $ends[0][1] * $sy, $ends[1][0] * $sx, $ends[1][1] * $sy, $entry->{color}, $entry->{targets}[ $known[0] ] );
1112 $raster->start_pattern(undef);
1113 return;
1114 }
1115  
1116 # A line of box drawing characters, one row per column (as the
1117 # asciichart program draws them), in the columns of the plot only: it
1118 # is drawn into the cells, where nothing clips it.
1119 method _draw_box_line ( $surface, $frame, $entry ) {
1120 my ( $left, $top ) = @$frame{qw(left top)};
1121 foreach my $run ( $self->_runs( $frame, $entry, $entry->{highs} ) ) {
1122 my $polyline = $self->_run_polyline( $frame, $entry, $run, 1 );
1123 next unless @$polyline;
1124 my $previous;
1125 foreach my $column ( max( 0, floor( $polyline->[0][0] ) ) .. min( $frame->{columns} - 1, floor( $polyline->[-1][0] ) ) ) {
1126 my $y = y_at( $polyline, $column + 0.5 ) // y_at( $polyline, $polyline->[0][0] ) // next;
1127 my $row = min( $frame->{rows} - 1, max( 0, floor($y) ) );
1128 my $owner = _nearest_target( $run, $column + 0.5 );
1129 my @cells;
1130 if ( !defined $previous || $previous == $row ) {
1131 @cells = ( [ $row, "\x{2500}" ] );
1132 }
1133 elsif ( $row < $previous ) {
1134 @cells = ( [ $previous, "\x{256F}" ], ( map { [ $_, "\x{2502}" ] } $row + 1 .. $previous - 1 ), [ $row, "\x{256D}" ] );
1135 }
1136 else {
1137 @cells = ( [ $previous, "\x{256E}" ], ( map { [ $_, "\x{2502}" ] } $previous + 1 .. $row - 1 ), [ $row, "\x{2570}" ] );
1138 }
1139 foreach my $cell (@cells) {
1140 $surface->put( $left + $column, $top + $cell->[0], $cell->[1], $entry->{color} );
1141 $surface->set_owner( $left + $column, $top + $cell->[0], 'stroke', $owner );
1142 }
1143 $previous = $row;
1144 }
1145 }
1146 return;
1147 }
1148  
1149 # The value of each bar (the total of a stack) beyond its end, where
1150 # there is room.
1151 method _draw_value_labels ( $surface, $frame, $bars, $look ) {
1152 my $vertical = $frame->{orientation} eq 'vertical';
1153 my %stack_end; # the outermost end of each stack, by category
1154 foreach my $entry ( grep { $self->series_option( $_->{series}, 'value_labels' ) } @$bars ) {
1155 foreach my $index ( 0 .. $entry->{xs}->$#* ) {
1156 my $end = $entry->{bar_ends}[$index] // next;
1157 my $key
1158 = defined $entry->{group}
1159 ? join( "\0", $entry->{group}, $entry->{xs}[$index], $entry->{highs}[$index] < ( $entry->{lows}[$index] // 0 ) ? '-' : '+' )
1160 : join( "\0", $entry->{name}, $index );
1161 my $value = defined $entry->{group} ? $entry->{highs}[$index] : $entry->{ys}[$index];
1162 my $known = $stack_end{$key};
1163 $stack_end{$key} = [ @$end, $value, $entry->{highs}[$index] >= ( $entry->{lows}[$index] // $self->_baseline($frame) ) ] if !$known || abs($value) >= abs( $known->[2] );
1164 }
1165 }
1166 my $format = $self->value_format;
1167 my @ends = sort { $a->[0] <=> $b->[0] } values %stack_end;
1168 my @texts = format_values( [ map { $_->[2] } @ends ], $format && $format ne 'auto' ? $format : undef );
1169  
1170 # A label that would touch one drawn before it in its row is left out.
1171 my %taken; # row => [ [ from, to ] ... ]
1172 my $place = sub ( $row, $column, $width ) {
1173 return 0 if grep { $column <= $_->[1] && $column + $width - 1 >= $_->[0] } @{ $taken{$row} // [] };
1174 push @{ $taken{$row} }, [ $column - 1, $column + $width ];
1175 return 1;
1176 };
1177 foreach my $end (@ends) {
1178 my ( $middle, $tip, $value, $positive ) = @$end;
1179 my $text = shift @texts;
1180 my $width = Term::Fabulous::Chart::Surface->text_columns($text);
1181 if ($vertical) {
1182  
1183 # Above the bar's top cell (below the end of a negative bar),
1184 # in the row the frame keeps free above the plot too.
1185 my $row = $positive ? floor($tip) - 1 : ceil($tip);
1186 next if $row < -( $frame->{label_room} // 0 ) || $row >= $frame->{rows};
1187 my $column = floor( $middle - $width / 2 + 0.5 );
1188 next if $column < 0 || $column + $width > $frame->{columns} || !$place->( $row, $column, $width );
1189 $surface->text( $frame->{left} + $column, $frame->{top} + $row, $text, $look->{text} );
1190 }
1191 else {
1192 my $row = ceil($middle) - 1;
1193 my $column = $positive ? ceil($tip) + 1 : floor($tip) - $width;
1194 next if $column < 0 || $column + $width > $frame->{columns} || !$place->( $row, $column, $width );
1195 $surface->text( $frame->{left} + $column, $frame->{top} + $row, $text, $look->{text} );
1196 }
1197 }
1198 return;
1199 }
1200  
1201 # Tick labels, tick marks and axis titles.
1202 method _draw_axes ( $surface, $frame, $look ) {
1203 my ( $left, $top, $columns, $rows ) = @$frame{qw(left top columns rows)};
1204 my $vertical = $frame->{orientation} eq 'vertical';
1205 my $measure = sub ($label) { Term::Fabulous::Chart::Surface->text_columns($label) };
1206  
1207 # The axis along the left: values (vertical) or categories (horizontal).
1208 my ( $left_scale, $bottom_scale ) = $vertical ? @$frame{qw(value_scale index_scale)} : @$frame{qw(index_scale value_scale)};
1209 my ( $left_shown, $bottom_shown ) = $vertical ? @$frame{qw(value_shown index_shown)} : @$frame{qw(index_shown value_shown)};
1210 if ( $left_shown && $frame->{gutter} ) {
1211 my $width = $frame->{gutter} - 1;
1212 my $last_row;
1213 foreach my $tick ( $left_scale->ticks ) {
1214 my $position = $vertical ? $self->_value_position( $frame, $tick->{value} ) : $self->_index_position( $frame, $tick->{value} );
1215 my $row = $vertical ? floor( $position // next ) : $self->_category_cell( $frame, $position // next );
1216 next if $row < 0 || $row >= $rows || ( defined $last_row && $row == $last_row );
1217 my $text_width = min( $measure->( $tick->{label} ), $width );
1218 $surface->text( $frame->{area_left} + $width - $text_width, $top + $row, $tick->{label}, $look->{label}, max => $width );
1219 $last_row = $row;
1220 }
1221 }
1222  
1223 # The axis along the bottom, below the plot.
1224 my $label_row = $top + $rows;
1225 if ($bottom_shown) {
1226 my $slot = $bottom_scale->can('slot_cells') && $frame->{band} ? $bottom_scale->slot_cells : undef;
1227 my $free_from = $frame->{area_left};
1228 foreach my $tick ( $bottom_scale->ticks ) {
1229 my $position = $vertical ? $self->_index_position( $frame, $tick->{value} ) : $self->_value_position( $frame, $tick->{value} );
1230 next unless defined $position;
1231 my $label = $tick->{label};
1232 my $room = defined $slot ? max( 1, floor($slot) - 1 ) : undef;
1233 my $width = min( $measure->($label), $room // $measure->($label) );
1234 my $start = $left + floor( $position - $width / 2 + ( defined $slot ? 0.5 : 0 ) );
1235 $start = max( $start, $frame->{area_left} );
1236 $start = min( $start, $frame->{area_left} + $frame->{area_width} - $width );
1237 next if $start < $free_from;
1238 $surface->text( $start, $label_row, $label, $look->{label}, max => $width );
1239 $free_from = $start + $width + 1;
1240  
1241 # A tick mark on the baseline below a point of a numeric axis.
1242 if ( $vertical && !$frame->{band} ) {
1243 my ( $mark_x, $mark_y ) = ( $left + floor($position), $top + $rows - 1 );
1244 my $glyph = $surface->glyph_at( $mark_x, $mark_y );
1245 $surface->put( $mark_x, $mark_y, "\x{252C}", $look->{axis} ) if defined $glyph && $glyph eq "\x{2500}" && $surface->fg_at( $mark_x, $mark_y ) == $look->{axis};
1246 }
1247 }
1248 $label_row++;
1249 }
1250  
1251 # Titles: the x axis title centered below, the y axis title above
1252 # the values.
1253 if ( $frame->{title_below} ) {
1254 my $title = $x_axis->{title};
1255 my $width = $measure->($title);
1256 $surface->text( $left + max( 0, int( ( $columns - $width ) / 2 ) ), $label_row, $title, $look->{label}, max => $frame->{area_width} );
1257 }
1258  
1259 # The y title sits right above the highest tick, also when the ticks
1260 # leave rows free at the top.
1261 if ( $frame->{title_above} ) {
1262 my $free = $vertical ? $rows - $frame->{value_scale}->used - ( $frame->{label_room} // 0 ) : 0;
1263 $surface->text( $frame->{area_left}, $top - 1 + $free, $y_axis->{title}, $look->{label}, max => $frame->{area_width} );
1264 }
1265 return;
1266 }
1267  
1268 # ---------------------------------------------------------------------
1269 # KDL
1270 # ---------------------------------------------------------------------
1271  
1272 method layout_properties :common () {
1273 return (
1274 $class->SUPER::layout_properties,
1275 stacked => 'scalar',
1276 horizontal => 'boolean',
1277 bar_width => 'scalar',
1278 marker => 'scalar',
1279 curve => 'scalar',
1280 tension => 'scalar',
1281 line_style => 'scalar',
1282 line => 'boolean',
1283 points => 'boolean',
1284 point => 'scalar',
1285 fill_opacity => 'scalar',
1286 max_points => 'scalar',
1287 span_gaps => 'boolean',
1288 value_labels => 'boolean',
1289 labels => \&_parse_labels,
1290 x_axis => \&_parse_axis,
1291 y_axis => \&_parse_axis,
1292 transform => \&_parse_chart_transform,
1293 series => \&_parse_series,
1294 );
1295 }
1296  
1297 # Axes and labels before the series, so the series' x values are read
1298 # the way the axis says.
1299 method apply_layout_settings :override (@settings) {
1300 my %rank = ( labels => 0, x_axis => 0, y_axis => 0, transform => 1, series => 2 );
1301 my @ordered = map { $_->[1] } sort { $a->[0] <=> $b->[0] } map { [ $rank{ $_->[0] } // 1, $_ ] } @settings;
1302 return $self->SUPER::apply_layout_settings(@ordered);
1303 }
1304  
1305 method _parse_labels ($kid) {
1306 my @labels = map { $_->as_perl } $kid->args->@*;
1307 croak ref($self) . ": layout property 'labels' takes one or more labels" unless @labels && !$kid->props->@* && !$kid->children->@*;
1308 $self->labels( [ map { "$_" } @labels ] );
1309 return;
1310 }
1311  
1312 method _parse_axis ($kid) {
1313 my $name = $kid->name;
1314 my $props = $self->kdl_properties( $kid, @AXIS_KEYS );
1315 $self->$name( { %{ $self->$name }, %$props } );
1316 return;
1317 }
1318  
1319 # transform "cumulative"; transform "moving_average" 5 "center"
1320 sub _kdl_transform_step ($kid) {
1321 my @args = map { $_->as_perl } $kid->args->@*;
1322 return @args > 1 ? [@args] : $args[0];
1323 }
1324  
1325 # Every transform node adds a step to the chart's transform.
1326 method _parse_chart_transform ($kid) {
1327 croak ref($self) . ": layout property 'transform' takes a step name and its arguments" unless $kid->args->@* && !$kid->props->@* && !$kid->children->@*;
1328 push @_kdl_chart_steps, _kdl_transform_step($kid);
1329 $self->_set_default( transform => [@_kdl_chart_steps] );
1330 return;
1331 }
1332  
1333 # series "name" type="area" color="#3987e5" curve="monotone" {
1334 # data 3 5 2 8
1335 # point "2026-06-01" 5
1336 # transform "moving_average" 3
1337 # }
1338 method _parse_series ($kid) {
1339 my @args = map { $_->as_perl } $kid->args->@*;
1340 croak ref($self) . ": layout property 'series' needs the series name as its one argument" unless @args == 1 && defined $args[0] && !ref $args[0];
1341 my %spec = ( name => "$args[0]", map { $_->[0] => $_->[1]->as_perl } $kid->props->@* );
1342 my ( @data, @steps );
1343 foreach my $child ( $kid->children->@* ) {
1344 my $name = $child->name;
1345 my @values = map { $_->as_perl } $child->args->@*;
1346 croak ref($self) . ": a series node holds 'data', 'point' and 'transform' nodes, got '$name'" unless $name eq 'data' || $name eq 'point' || $name eq 'transform';
1347 croak ref($self) . ": '$name' in series '$args[0]' takes no properties or children" if $child->props->@* || $child->children->@*;
1348 if ( $name eq 'data' ) {
1349 push @data, @values;
1350 }
1351 elsif ( $name eq 'point' ) {
1352 croak ref($self) . ": 'point' in series '$args[0]' takes an x and a y value" unless @values == 2;
1353 push @data, [@values];
1354 }
1355 else {
1356 croak ref($self) . ": 'transform' in series '$args[0]' takes a step name and its arguments" unless @values;
1357 push @steps, _kdl_transform_step($child);
1358 }
1359 }
1360 $self->add_series( %spec, data => \@data, ( @steps ? ( transform => \@steps ) : () ) );
1361 return;
1362 }
1363 }
1364  
1365 1;
1366  
1367 __END__