Concise/Color.pm untested

filter: Statementstmt 0.0% 0 / 67 Branchbran 0.0% 0 / 20 Conditioncond 0.0% 0 / 16 MC/DCmcdc 0.0% 0 / 10 Subroutinesub 0.0% 0 / 12 Podpod 0.0% 0 / 7 totaltotal 0.0% 0 / 132 CC 11 SCAR 27.3
CC
11
Cov
0%
set_luminance
42.0
get_luminance
12.0
rgb
6.0
CRAP 15.4
1 # -*- indent-tabs-mode: nil -*-
2  
3 =head1 SEE ALSO
4  
5 L(<https://qiita.com/yoya/items/96c36b069e74398796f3>
6  
7 =cut
8  
9 package Term::ANSIColor::Concise::Color;
10  
11 our $VERSION = "3.06";
12  
13 use v5.14;
14 use warnings;
15 use utf8;
16  
17 use Data::Dumper;
18 use parent 'Colouring::In';
19  
20 sub rgb {
21 my $self = shift;
22 my $class = ref $self || $self;
23 if (@_) {
24 bless $self->SUPER::rgb(@_), $class;
25 } else {
26 map int, $self->colour;
27 }
28 }
29  
30 sub hsl {
31 my $self = shift;
32 my $class = ref $self || $self;
33 if (@_) {
34 bless $self->SUPER::hsl(@_), $class;
35 } else {
36 map int($_ + 0.5), $self->toHSL =~ /[\d.]+/g;
37 }
38 }
39  
40 sub new {
41 my $self = shift;
42 my $class = ref $self || $self;
43 bless $self->SUPER::new(@_), $class;
44 }
45  
46 sub greyscale {
47 my $self = shift;
48 my $class = ref $self || $self;
49 bless $self->SUPER::greyscale(@_), $class;
50 }
51  
52 sub luminance {
53 my $color = shift;
54 if (@_) {
55 $color->set_luminance(@_);
56 } else {
57 $color->get_luminance;
58 }
59 }
60  
61 our $LUMINANCE //= 'CIE';
62  
63 sub get_luminance {
64 my $color = shift;
65 my($r, $g, $b) = $color->rgb;
66 my $method = $LUMINANCE //= 'CIE';
67 my $y = do {
68 if ($LUMINANCE eq 'CIE') {
69 0.2126 * $r + 0.7152 * $g + 0.0722 * $b;
70 } elsif ($LUMINANCE eq 'ITU') {
71 0.299 * $r + 0.587 * $g + 0.114 * $b;
72 }
73 };
74 int($y / 255 * 100);
75 }
76  
77 sub set_luminance {
78 my $color = shift;
79 my $target = shift;
80 my($h, $s, $ol) = $color->hsl;
81 my $y = $color->luminance;
82 return $color if abs($y - $target) < 1;
83 my($low, $high) = $y < $target ? ($ol, 100) : (0, $ol);
84 my @y; @y[0, $ol, 100] = (0, $y, 100);
85 my $l = int(
86 $low + ($high-$low) * ($target-$y[$low])/($y[$high]-$y[$low]) + 0.5
87 );
88 my $count = 0;
89 my $dist = 2;
90 while (abs($y - $target) >= $dist) {
91 die "long loop ($count)\n" if ++$count >= 20;
92 my $new = __PACKAGE__->hsl($h, $s, $l);
93 $y[$l] = my $y = $new->luminance;
94 if (abs($y - $target) < $dist) {
95 last;
96 } elsif ($y < $target) {
97 $low = $l;
98 } else {
99 $high = $l;
100 }
101 $l = int(($low + $high) / 2 + 0.5);
102 }
103 __PACKAGE__->hsl($h, $s, $l);
104 }
105  
106 1;