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

filter: Statementstmt 0.0% 0 / 313 Branchbran 0.0% 0 / 94 Conditioncond 0.0% 0 / 59 MC/DCmcdc 0.0% 0 / 34 Subroutinesub 0.0% 0 / 27 Podpod n/a totaltotal 0.0% 0 / 527 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::ColorPicker;
2  
3 use v5.32;
4 use warnings;
5 use feature 'signatures';
6 no warnings 'experimental::signatures';
7  
8 use Object::Pad 0.825;
9  
10 use Term::Fabulous::Widget::Box;
11  
12 our $VERSION = '0.02';
13  
14 # A color chooser built from other widgets: a field for the color as
15 # text, a sample of it, sliders for its channels (RGB or HSL, switched by
16 # a segmented control), an optional alpha slider and an optional list of
17 # named swatches. The parts' own events stop at them; the picker fires
18 # its own Change and Submit.
19 class Term::Fabulous::Widget::ColorPicker
20 :isa(Term::Fabulous::Widget::Box)
21 :strict(params)
22 {
23 use Clay::XS qw(sizing_fixed sizing_grow CLAY_TOP_TO_BOTTOM);
24 use Feature::Compat::Try;
25 use List::Util qw(first max min);
26 use Scalar::Util qw(weaken);
27 use Term::Fabulous::Check qw(boolean color describe one_of optional positive_integer string);
28 use Term::Fabulous::Color;
29 use Term::Fabulous::Event::Change;
30 use Term::Fabulous::Event::Submit;
31 use Term::Fabulous::Unicode qw(string_columns);
32 use Term::Fabulous::Widget::SegmentedControl;
33 use Term::Fabulous::Widget::Slider;
34 use Term::Fabulous::Widget::Table;
35 use Term::Fabulous::Widget::Table::Frame qw(framed);
36 use Term::Fabulous::Widget::Text;
37 use Term::Fabulous::Widget::TextField;
38  
39 use constant SAMPLE => "\x{2588}" x 3; # full blocks in the swatch's color
40 use constant FIELD_WIDTH => 22; # the field shrinks to FIELD_MINIMUM on a narrow screen
41 use constant FIELD_MINIMUM => 10;
42 use constant LABEL_MINIMUM => 20; # the swatch labels keep up to this many columns
43 use constant LIST_FURNITURE => 2 + 6 + 1 + 1; # the frame's borders, the sample column, the gap after it, the scrollbar
44 use constant SAMPLE_WIDTH => 6;
45  
46 # The three channel sliders of each mode: their labels and maximums.
47 my %CHANNELS_OF_MODE = (
48 rgb => [ [ R => 255 ], [ G => 255 ], [ B => 255 ] ],
49 hsl => [ [ H => 359 ], [ S => 100 ], [ L => 100 ] ],
50 );
51  
52 my $pickers_built = 0; # for the ids of pickers built without one
53  
54 field $alpha :param = 1;
55 field $sliders :param = 'rgb';
56 field $list_rows :param = 12;
57  
58 field $chosen; # the spec chosen now: a swatch's value or a color, or undef
59 field $_rgba; # the color of $chosen as [r, g, b, a], or undef
60 field @_swatches; # { value, label, rgba }, in order
61  
62 field $_field;
63 field $_sample;
64 field $_switch;
65 field @_channel_sliders;
66 field @_channel_labels;
67 field $_alpha_slider;
68 field $_alpha_row;
69 field $_column;
70 field $_list;
71 field $_frame;
72  
73 ADJUST :params ( :$value = undef, :$swatches = undef ) {
74 $alpha = boolean( $self, alpha => $alpha );
75 $sliders = one_of( $self, sliders => $sliders, keys %CHANNELS_OF_MODE );
76 $list_rows = positive_integer( $self, list_rows => $list_rows );
77 @_swatches = $self->_parsed_swatches($swatches);
78  
79 my $layout = $self->layout;
80 $self->layout( { child_gap => 2, %$layout, sizing => { width => sizing_grow(), %{ $layout->{sizing} // {} } } } );
81 $self->add_child( $self->_swatch_list ) if @_swatches;
82 $self->add_child( $self->_editor );
83 $self->_use_sliders;
84 $self->_show_value($value);
85 }
86  
87 # ---------------------------------------------------------------------
88 # Parameters
89 # ---------------------------------------------------------------------
90  
91 # Swatches as { value, label, rgba }: a value (a non-empty string,
92 # unique), a label (the value when left out) and a color (none when
93 # left out).
94 method _parsed_swatches ($swatches) {
95 return () unless defined $swatches;
96 die ref($self) . ": swatches must be an array reference, got " . describe($swatches) unless ref $swatches eq 'ARRAY';
97 my ( @parsed, %seen );
98 foreach my $swatch (@$swatches) {
99 die ref($self) . ": a swatch must be an array reference [ value, label, color ], got " . describe($swatch) unless ref $swatch eq 'ARRAY' && @$swatch >= 1 && @$swatch <= 3;
100 my ( $spec, $label, $rgba ) = @$swatch;
101 die ref($self) . ": the value of a swatch must be a non-empty string, got " . describe($spec) unless defined $spec && !ref $spec && length $spec;
102 die ref($self) . ": two swatches have the value '$spec'" if $seen{$spec}++;
103 push @parsed,
104 {
105 value => $spec,
106 label => optional( \&string, $self, "the label of the swatch '$spec'" => $label ) // $spec,
107 rgba => optional( \&color, $self, "the color of the swatch '$spec'" => $rgba ),
108 };
109 }
110 return @parsed;
111 }
112  
113 method _swatch_of ($spec) {
114 return undef unless defined $spec;
115 return first { $_->{value} eq $spec } @_swatches;
116 }
117  
118 # ---------------------------------------------------------------------
119 # The parts
120 # ---------------------------------------------------------------------
121  
122 method _swatch_list () {
123 my %rgba_of = map { $_->{value} => $_->{rgba} } @_swatches;
124 $_list = Term::Fabulous::Widget::Table->new(
125 id => ( $self->id // 'color-picker-' . ++$pickers_built ) . '/list',
126 row_id => 'value',
127 selection => 'single',
128 header => 0,
129 border => 'none',
130 column_lines => 'none',
131 columns => [
132 { key => 'sample', width => 'fixed(6)', cell_style => sub ($cell) { my $rgba = $rgba_of{ $cell->{row}{value} }; return defined $rgba ? { text_color => $rgba } : {} } },
133 { key => 'label', width => 'grow' },
134 ],
135 rows => [ map { { value => $_->{value}, label => $_->{label}, sample => defined $_->{rgba} ? SAMPLE : '' } } @_swatches ],
136 layout => { sizing => { width => sizing_grow(), height => sizing_grow() } },
137 );
138 weaken( my $weak_self = $self );
139 $_list->on( CursorMove => sub ($event) { $weak_self->_swatch_chosen( $event->row_id ) if $weak_self && defined $event->row_id; return } );
140 $_list->on( RowActivate => sub ($event) { $weak_self->_swatch_submitted( $event->row_id ) if $weak_self; return } );
141 $_frame = framed( $_list, $list_rows );
142 my $layout = $_frame->layout;
143 $_frame->layout( { %$layout, sizing => { %{ $layout->{sizing} }, width => sizing_grow( $self->_list_minimum_width ) } } );
144 return $_frame;
145 }
146  
147 # Wide enough for the swatch labels (up to LABEL_MINIMUM columns), so
148 # that a narrow screen shrinks the field and the sliders first.
149 method _list_minimum_width () {
150 my $longest = max map { string_columns( $_->{label} ) } @_swatches;
151 return LIST_FURNITURE + min( $longest, LABEL_MINIMUM );
152 }
153  
154 # The field and the sample, the RGB/HSL switch, the channel sliders and
155 # the alpha slider.
156 method _editor () {
157 weaken( my $weak_self = $self );
158 $_column = Term::Fabulous::Widget::Box->new( layout => { layout_direction => CLAY_TOP_TO_BOTTOM, sizing => { width => sizing_grow() } } );
159  
160 $_field = Term::Fabulous::Widget::TextField->new(
161 placeholder => $self->_placeholder,
162 max_length => 32,
163 validator => sub ($text) { $weak_self ? $weak_self->_color_problem($text) : undef },
164 layout => { sizing => { width => sizing_grow( FIELD_MINIMUM, FIELD_WIDTH ) } },
165 );
166 $_sample = Term::Fabulous::Widget::Box->new( layout => { sizing => { width => sizing_fixed(SAMPLE_WIDTH), height => sizing_fixed(1) } } );
167 my $top = Term::Fabulous::Widget::Box->new( layout => { sizing => { width => sizing_grow() }, child_gap => 1, padding => { bottom => 1 } } );
168 $top->add_child( $_field, $_sample );
169 $_field->on( Change => sub ($event) { $weak_self->_typed( $event->value ) if $weak_self; return } );
170 $_field->on( Submit => sub ($event) { $weak_self->_submit if $weak_self; return } );
171  
172 $_switch = Term::Fabulous::Widget::SegmentedControl->new( options => [ [ RGB => 'rgb' ], [ HSL => 'hsl' ] ], value => $sliders );
173 $_switch->on( Change => sub ($event) { $weak_self->sliders( $event->value ) if $weak_self; return } );
174 $_column->add_child( $top, $_switch );
175  
176 foreach ( 1 .. 3 ) {
177 my ( $row, $label, $slider ) = $self->_slider_row;
178 push @_channel_sliders, $slider;
179 push @_channel_labels, $label;
180 $_column->add_child($row);
181 }
182 ( $_alpha_row, my $alpha_label, $_alpha_slider ) = $self->_slider_row;
183 $alpha_label->text('A');
184 $_alpha_slider->set_range( min => 0, max => 255 );
185 $_column->add_child($_alpha_row) if $alpha;
186 return $_column;
187 }
188  
189 # A label and a slider in a row; moving the slider writes the value.
190 method _slider_row () {
191 weaken( my $weak_self = $self );
192 my $label = Term::Fabulous::Widget::Text->new( text => ' ' );
193 my $slider = Term::Fabulous::Widget::Slider->new( min => 0, max => 255, value_format => '%3d', layout => { sizing => { width => sizing_grow() } } );
194 my $row = Term::Fabulous::Widget::Box->new( layout => { sizing => { width => sizing_grow() }, child_gap => 1 } );
195 $row->add_child( $label, $slider );
196 $slider->on( Change => sub ($event) { $weak_self->_slid if $weak_self; return } );
197 return ( $row, $label, $slider );
198 }
199  
200 method _placeholder () {
201 return $alpha ? '#rrggbb or #rrggbbaa' : '#rrggbb';
202 }
203  
204 # What is wrong with a typed color, or undef: the field's validator.
205 method _color_problem ($text) {
206 my $rgba = _parsed_color($text);
207 return 'Please enter a color: #rrggbb, rgb(...), hsl(...) or a color name.' unless defined $rgba;
208 return 'Please enter a color without transparency.' if !$alpha && $rgba->[3] != 255;
209 return undef;
210 }
211  
212 # The color a text stands for as [r, g, b, a], or undef when it is none.
213 sub _parsed_color ($text) {
214 my $rgba;
215 try {
216 $rgba = color( __PACKAGE__, color => $text );
217 }
218 catch ($error) {
219 $rgba = undef;
220 }
221 return $rgba;
222 }
223  
224 sub _hex_of ( $red, $green, $blue, $opacity ) {
225 return sprintf( '#%02x%02x%02x', $red, $green, $blue ) if $opacity == 255;
226 return sprintf( '#%02x%02x%02x%02x', $red, $green, $blue, $opacity );
227 }
228  
229 # ---------------------------------------------------------------------
230 # Showing the value
231 # ---------------------------------------------------------------------
232  
233 # Sets the value from the program: the field, the sliders and the list
234 # follow. Dies on a value that is neither a swatch's nor a color.
235 method _show_value ($spec) {
236 my $swatch = $self->_swatch_of($spec);
237 my $rgba = defined $spec && !defined $swatch ? $self->_checked_color($spec) : undef;
238 ( $chosen, $_rgba ) = ( $spec, defined $swatch ? $swatch->{rgba} : $rgba );
239 $_field->value( defined $swatch ? ( $spec =~ /\A#/ ? $spec : '' ) : $spec // '' );
240 $_field->editor->select_all; # typing replaces the color
241 $self->_show_in_list($swatch);
242 $self->_show_on_sliders;
243 $self->_show_sample;
244 return;
245 }
246  
247 method _checked_color ($spec) {
248 my $rgba = color( $self, value => $spec );
249 die ref($self) . ": value must be opaque without alpha, got " . describe($spec) if !$alpha && $rgba->[3] != 255;
250 return $rgba;
251 }
252  
253 # Selects the swatch in the list, scrolled so that it is near the
254 # middle; without one, the list has no selection.
255 method _show_in_list ($swatch) {
256 return unless defined $_list;
257 return $_list->set_selection unless defined $swatch;
258 my ($index) = grep { $_swatches[$_] == $swatch } 0 .. $#_swatches;
259 my $below = min( $#_swatches, $index + int( $list_rows / 2 ) );
260 $_list->cursor( $_swatches[$below]{value} );
261 $_list->cursor( $swatch->{value} );
262 $_list->set_selection( $swatch->{value} );
263 return;
264 }
265  
266 # The sliders show the color in the current mode; without a color,
267 # black.
268 method _show_on_sliders () {
269 my ( $red, $green, $blue, $opacity ) = defined $_rgba ? @$_rgba : ( 0, 0, 0, 255 );
270 my @levels = $sliders eq 'hsl' ? Term::Fabulous::Color->rgb_to_hsl( $red, $green, $blue ) : ( $red, $green, $blue );
271 $_channel_sliders[$_]->value( $levels[$_] ) foreach 0 .. 2;
272 $_alpha_slider->value($opacity);
273 return;
274 }
275  
276 method _show_sample () {
277 return $_sample->background_color($_rgba) if defined $_rgba && $_rgba->[3] > 0;
278 $_sample->reset_look('background_color');
279 return;
280 }
281  
282 # The channel sliders take the ranges and labels of the mode, then
283 # read the color again; the value stays as it is.
284 method _use_sliders () {
285 my $channels = $CHANNELS_OF_MODE{$sliders};
286 foreach my $index ( 0 .. 2 ) {
287 my ( $label, $maximum ) = @{ $channels->[$index] };
288 $_channel_sliders[$index]->set_range( min => 0, max => $maximum );
289 $_channel_labels[$index]->text($label);
290 }
291 $self->_show_on_sliders;
292 return;
293 }
294  
295 # ---------------------------------------------------------------------
296 # What the user does
297 # ---------------------------------------------------------------------
298  
299 method _typed ($text) {
300 return unless length $text && $_field->is_valid;
301 ( $chosen, $_rgba ) = ( $text, _parsed_color($text) );
302 $_list->set_selection if defined $_list;
303 $self->_show_on_sliders;
304 $self->_show_sample;
305 $self->_fire_change;
306 return;
307 }
308  
309 # A slider moved: the value is written from the sliders, which stay
310 # as they are (HSL in whole numbers cannot reach every RGB color).
311 method _slid () {
312 my @levels = map { $_->value } @_channel_sliders;
313 my @rgb = $sliders eq 'hsl' ? Term::Fabulous::Color->hsl_to_rgb(@levels) : @levels;
314 my $opacity = $alpha ? $_alpha_slider->value : 255;
315 $chosen = _hex_of( @rgb, $opacity );
316 $_rgba = [ @rgb, $opacity ];
317 $_field->value($chosen);
318 $_list->set_selection if defined $_list;
319 $self->_show_sample;
320 $self->_fire_change;
321 return;
322 }
323  
324 method _swatch_chosen ($spec) {
325 my $swatch = $self->_swatch_of($spec);
326 ( $chosen, $_rgba ) = ( $spec, $swatch->{rgba} );
327 $_field->value( $spec =~ /\A#/ ? $spec : '' );
328 $_list->set_selection($spec);
329 $self->_show_on_sliders;
330 $self->_show_sample;
331 $self->_fire_change;
332 return;
333 }
334  
335 # Enter on a swatch row: a row under the cursor but not chosen (after
336 # typing or sliding) is chosen first.
337 method _swatch_submitted ($spec) {
338 $self->_swatch_chosen($spec) if defined $spec && ( $chosen // '' ) ne $spec;
339 $self->_submit;
340 return;
341 }
342  
343 method _fire_change () {
344 $self->fire_event( Term::Fabulous::Event::Change->new( value => $chosen ) );
345 return;
346 }
347  
348 method _submit () {
349 $self->fire_event( Term::Fabulous::Event::Submit->new( value => $chosen ) );
350 return;
351 }
352  
353 # ---------------------------------------------------------------------
354 # Accessors
355 # ---------------------------------------------------------------------
356  
357 method value (@new) {
358 return $chosen unless @new;
359 $self->_show_value( optional( \&string, $self, value => $new[0] ) );
360 return $chosen;
361 }
362  
363 method rgba () {
364 return defined $_rgba ? [@$_rgba] : undef;
365 }
366  
367 method sliders (@new) {
368 return $sliders unless @new;
369 $sliders = one_of( $self, sliders => $new[0], keys %CHANNELS_OF_MODE );
370 $_switch->value($sliders);
371 $self->_use_sliders;
372 return $sliders;
373 }
374  
375 method alpha (@new) {
376 return $alpha unless @new;
377 my $wanted = boolean( $self, alpha => $new[0] );
378 die ref($self) . ": cannot turn alpha off while the value " . describe($chosen) . " is translucent"
379 if !$wanted && defined $_rgba && $_rgba->[3] != 255 && !defined $self->_swatch_of($chosen);
380 $alpha = $wanted;
381 $_column->add_child($_alpha_row) if $alpha && !$_column->has_child($_alpha_row);
382 $_column->remove_child($_alpha_row) if !$alpha && $_column->has_child($_alpha_row);
383 $_field->placeholder( $self->_placeholder );
384 $_field->validate;
385 return $alpha;
386 }
387  
388 method list_rows (@new) {
389 return $list_rows unless @new;
390 $list_rows = positive_integer( $self, list_rows => $new[0] );
391 if ( defined $_frame ) {
392 my $layout = $_frame->layout;
393 $_frame->layout( { %$layout, sizing => { %{ $layout->{sizing} }, height => sizing_fixed( $list_rows + 2 ) } } );
394 }
395 return $list_rows;
396 }
397  
398 # The field's validation: what Prompt and forms read.
399 method validate () { return $_field->validate }
400 method error () { return $_field->error }
401 method is_valid () { return $_field->is_valid }
402  
403 method layout_properties :common () {
404 return ( $class->SUPER::layout_properties, ( map { $_ => 'scalar' } qw(value sliders list_rows) ), alpha => 'boolean' );
405 }
406 }
407  
408 1;
409  
410 __END__