termcol: named function to parse table data
[sheet.git] / termcol.plp
1 <(common.inc.plp)><:
2
3 Html({
4         title => 'terminal colour cheat sheet',
5         version => '1.0',
6         description => [
7                 "Index of all terminal/console colour codes,",
8                 "with an example result of various environments.",
9         ],
10         keywords => [qw'
11                 color code terminal console escape table xterm rxvt
12         '],
13         data => ['termcol.inc.pl'],
14         stylesheet => [qw'light dark'],
15 });
16
17 my @draw = map { [$_, s/\W+\z//] } grep { $_ } split m(/),
18         $get{img} // exists $get{img} && 'indi.png';
19
20 my @termlist;
21 push @termlist, split /\W+/, $ENV{PATH_INFO} || 'default';
22
23 my %termgroup = (
24         default => [qw( ansi xkcd ansi88 )],
25         more    => [qw( ansi mirc legacy ansi256 )],
26         msx     => [qw( msx1 msx2 arnejmp )],
27         ansi    => [qw( cga xterm tango app html cgarne )],
28         legacy  => [qw( c64 msx2 mac2 risc arnegame cpc )],
29 );
30 @{$_} = map { $termgroup{$_} ? @{ $termgroup{$_} } : $_ } @{$_}
31         for values %termgroup, \@termlist;
32
33 :>
34 <h1>Terminal colours</h1>
35
36 <p>
37 <span title="ECMA-48">ANSI</span> (VT100, ISO-6429) 16-colour text palette
38 as implemented by various systems and programs.
39 <:
40 print
41         "@termlist" ne "@{ $termgroup{default} }" ? 'Additional palettes are included as specified.' :
42         'Also see <a href="/termcol/more">8-bit legacy hardware</a> palettes.';
43 :>
44 </p>
45
46 <div class="section">
47 <:
48 use 5.010;
49 use Shiar_Sheet::Colour '1.04';
50 use List::Util qw( min max );
51 use POSIX qw( ceil );
52
53 my $palettes = do 'termcol.inc.pl';
54 die "Cannot open palette data: $_\n" for $@ || $! || ();
55
56 sub colcell {
57         my $name = shift // return "<td>\n";
58         my $col = Shiar_Sheet::Colour->new(@_);
59         my $minhex = $col->rgb24;
60         my $css     = '#' . $col->rgb48;
61         my $inverse = '#' . sprintf('%X', $col->luminance/255 < .3 ? 12 : 0) x 3;
62
63         my $sample = [ qw(#000 #FFF) ];
64         ($name, $sample) = @$name if ref $name eq 'ARRAY';
65
66         my $out = sprintf('<td title="%s" style="%s">%s',
67                 join(',', map { int } @$col),
68                 "background:$css; color:$inverse",
69                 $name,
70         );
71         $out .= sprintf('<samp style="%s"><small>%s</small></samp>',
72                 "background:$_; color:$css", $minhex
73         ) for @$sample;
74         return "$out\n";
75 }
76
77 sub img_egapal {
78         my ($palette, $imgfile, $reindex) = @_;
79         return eval {
80                 require Imager;
81                 require MIME::Base64;
82
83                 my @imgpal = map { Imager::Color->new(ref $_ ? @$_ : $_) } @{$palette};
84                 state $imgcache = {};
85                 my $img = $imgcache->{$imgfile}
86                         //= Imager->new(file => "data/palimage/$imgfile")
87                         or die Imager->errstr.$/;
88
89                 do {
90                         if ($reindex) {
91                                 $img->to_paletted({
92                                         make_colors => 'none',
93                                         colors => \@imgpal,
94                                         translate => 'closest',
95                                 });
96                         }
97                         else {
98                                 @{[ $img->getcolors ]} == @imgpal
99                                         or die "incompatible palette size\n";
100                                 $img->setcolors(colors => \@imgpal);
101                                 $img;
102                         }
103                 }->write(data => \my $imgdata, type => 'png');
104                 return sprintf '<img src="data:image/png;base64,%s">',
105                         MIME::Base64::encode_base64($imgdata);
106         } || $@;
107 }
108
109 sub coltable {
110         my ($term) = @_;
111         my $info = $palettes->{$term};
112         ref $info eq 'HASH' or next;
113
114         my $caption = $info->{name} // $term;
115         $caption = sprintf('<%s %s>%s</%1$s>',
116                 $info->{href} ? 'a' : 'span',
117                 join(' ',
118                         map { sprintf '%s="%s"', $_, $info->{$_} }
119                         grep { defined $info->{$_} }
120                         qw( href title )
121                 ),
122                 $caption,
123         ) if $info->{href} or $info->{title};
124
125         if (my $mapinfo = $info->{rgbmap}) {
126                 print '<table class="color mapped">'."\n";
127                 printf "<caption>%s</caption>\n", $caption;
128                 print coltable_hsv(@{$mapinfo});
129                 print "</table>\n\n";
130         }
131
132         if (my $table = $info->{table}) {
133                 print '<table class="color mapped">'."\n";
134                 printf "<caption>%s</caption>\n", $caption;
135                 for my $row (@$table) {
136                         print '<tr>';
137                         print colcell(@$_) for @$row;
138                 }
139
140                 my $width = scalar @{ $table->[0] };
141                 my @imgpal = map { [ @{$_}[1 .. 3] ] } map { @{$_} } @{$table};
142                 for (@draw) {
143                         print "<tr><td colspan=$width>", img_egapal(\@imgpal, @{$_});
144                 }
145                 print "</table>\n\n";
146         }
147
148         if (my $palette = $info->{list}) {
149                 my $order = $get{order} && $get{order}.'order';
150                 my $colours = colorder($palette,
151                         $info->{$order} // $palettes->{ $info->{parent} }->{$order}
152                 );
153
154                 my $rows = 8;
155                 my $columns = ceil(@{$palette} / $rows);
156
157                 print '<table class=color>', "\n";
158                 printf "<caption>%s</caption>\n", $caption;
159                 for my $row (0 .. $rows - 1) {
160                         print '<tr>';
161                         for my $col (0 .. $columns - 1) {
162                                 my $num = $row + $col * $rows;
163                                 my ($rgb, $name) = split /:/, $colours->[$num], 3;
164                                 $name //= $rgb && $num;
165                                 $name = [ $name, [] ] if $term =~ /^msx/ and !$num;
166                                 $name = [ $name, ['#333'] ] if $term eq 'xkcd';
167                                 print colcell($name, $rgb);
168                         }
169                 }
170
171                 for (@draw) {
172                         my $imgpal = colorder($palette,
173                                 $info->{ansiorder} // $palettes->{ $info->{parent} }->{ansiorder}
174                         );
175                         print "<tr><td colspan=$columns>", img_egapal($imgpal, @{$_});
176                 }
177                 print "</table>\n\n";
178         }
179 }
180
181 sub colorder {
182         my ($palette, $reorder) = @_;
183         return [ map { $palette->[$_] =~ s/:(?![^:])|$/:$_/r } @{$reorder} ]
184                 if $reorder;
185         return $palette;
186 }
187
188 sub coltable_hsv {
189         my ($dim, $rgbval, $greyramp) = @_;
190
191         my $hmax = 2 * $dim * 3;  # each face of the rgb cube
192         my $vmax = $dim - 1;
193         my $smax = $dim - 1;
194         $rgbval ||= sub { join('', @_), map { int $_ * 255 / $vmax } @_ };
195
196         my @greymap = @{$greyramp || []};  # [name, r, g=l, b]
197         my @colmap;  # saturation => value => hue => [name, r,g,b]
198
199         for my $r (0 .. $dim - 1) {
200                 for my $g (0 .. $dim - 1) {
201                         for my $b (0 .. $dim - 1) {
202                                 my @rgb = ($r, $g, $b);
203
204                                 my ($h, $s, $v) = Shiar_Sheet::Colour->new(@rgb)->hsv;
205
206                                 if (!$s) {
207                                         if (@greymap) {
208                                                 push @greymap, [ $rgbval->(@rgb) ];
209                                                 next;
210                                         }
211
212                                         $h = 1;  # greyscale hue
213                                         $s = $smax - $v + 1;  # spread brightness over saturation groups
214                                         $v &&= $smax  # highest saturation
215                                                 or $v = $s = 1;  # black at initial column
216                                 }
217
218                                 $h *= $hmax;
219                                 $v = $vmax - $v;
220                                 $s = $smax - $s - $v;
221
222                                 $colmap[$s][$v][$h] = [ $rgbval->(@rgb) ];
223                         }
224                 }
225         }
226
227         my $out = '';
228         $out .= sprintf '<colgroup span=%d>', scalar @{$_} for @colmap;
229         my $huerow = $colmap[0][0]; # first {$_} map { @{$_} } @colmap;
230         for my $h (grep { $huerow->[$_] } 0 .. $#{$huerow}) {
231                 $out .= '<tr>';
232                 $out .= colcell(@$_) for map { $_->[$h] } map { reverse @{$_} } @colmap;
233         }
234
235         if (@greymap) {
236                 $out .= '<tbody>';
237                 my $col = 0;
238                 my $colbreak = scalar map { @$_ } @colmap;  # same width as hue rows
239                 for my $cell (sort { $a->[1] <=> $b->[1] || $a->[0] <=> $b->[0] } @greymap) {
240                         $out .= '<tr>' unless $col++ % $colbreak;
241                         $out .= colcell(@{$cell});
242                 }
243         }
244
245         if (@draw) {
246                 my @palette = map { [ @{$_}[1 .. 3] ] } @greymap, map {@$_} map {@$_} @colmap;
247                 my $tablespan = scalar map { @$_ } @colmap;
248                 my $imgdata = img_egapal(\@palette, @{ $draw[0] });
249                 $out .= "<tr><td colspan=$tablespan>$imgdata";
250         }
251
252         return $out;
253 }
254
255 coltable($_) for @termlist;
256 :></div>
257 <hr>
258