termcol: trim 8-colour xcolors palettes
[sheet.git] / tools / mktermcol-xcolor
1 #!/usr/bin/env perl
2 use 5.014;
3
4 use Shiar_Sheet::Colour 1.05;
5
6 say 'use strict;';
7 say '+{';
8 my @names;
9 my %seen;
10
11 for my $path (@ARGV) {
12         open my $theme, '<', $path or do {
13                 warn "could not open $path: $!\n";
14                 next;
15         };
16         (my $name = $path) =~ s{.*/}{};  # basename
17
18         my (%pal, @pal);
19         while (readline $theme) {
20                 m{
21                         (?: (foreground | background) | color(\d+) ) \h* : \h*
22                         (?: \#(\S+) | rgb:(\S+) )
23                 }x or next;
24                 my ($name, $idx, $val) = ($1, $2, uc $+);
25                 $name or $idx < 16 or next;
26                 $val =~ s/[^0-9A-F]//g;
27                 ($name ? $pal{$name} : $pal[$idx]) = $val;
28         }
29
30         my $huesum = 0;
31         for my $hue (
32                 sort map { $_->hue }
33                 grep { ($_->hsv)[1] > 32 }  # ignore unsaturated
34                 map { Shiar_Sheet::Colour->new($_) }
35                 @pal
36         ) {
37                 state $lasthue;
38                 $huesum += abs($lasthue - $hue) > .02 if defined $lasthue;
39                 $lasthue = $hue;
40         }
41         $huesum > 3 or next;  # require number of significant hue changes
42         #TODO tweak to include good-pants, exclude cheesecake-*
43
44         if ($seen{"@pal"}++) {
45                 warn "ignore duplicate palette $name\n";
46                 next;
47         }
48
49         splice @pal, 8 if "@pal[0..7]" eq "@pal[8..15]";
50
51         say qq("$name" => {);
52         say qq(\ttitle => '$name',);
53         say qq(\tparent => 'cga',);
54         say qq(\tlist => [qw(@pal)],);
55         say qq(\t$_ => '$pal{$_}',) for keys %pal;
56         say qq(},);
57         push @names, $name;
58 }
59
60 say 'xcolor => [', join(', ', map {"'$_'"} @names), '],';
61 say '}';