charset: extend inheritance to generic metadata hashes
[sheet.git] / charset.plp
1 <(common.inc.plp)><:
2
3 Html({
4         title => 'charset cheat sheet',
5         version => '1.0',
6         description => [
7                 "Reference sheet with all glyphs in common character encoding tables,",
8                 "and an overview of Unicode ranges and UTF-8 bytes.",
9         ],
10         keywords => [qw'
11                 charset codepage unicode ascii utf8 latin glyph character encoding
12                 reference common overview table
13         '],
14         stylesheet => [qw'light'],
15         data => [qw(
16                 charset-encoding.inc.pl
17                 charset-unicode.inc.pl charset-ucplanes.inc.pl charset-utf8.inc.pl
18         )],
19 });
20
21 my @tablist = split m{/+}, $Request || 'default';
22
23 use List::Util qw( first pairmap pairfirst pairs );
24
25 :>
26 <h1>Character encodings</h1>
27
28 <p>
29 <:
30 if ($tablist[0] eq 'default') {
31         say "Overview of Unicode allocation and common latin code pages.";
32         say "Compare alternate charsets:";
33 }
34 else {
35         say "Charset comparison:";
36 }
37
38 sub optionlink {
39         my ($title, $href, $selected) = @_;
40         return sprintf(
41                 $selected ? '<strong>%s</strong>' : '<a href="%2$s">%s</a>',
42                 EscapeHTML($title), $href
43         );
44 }
45
46 print join " •\n", (
47         map {
48                 join " ·\n", pairmap {
49                         optionlink($b || ucfirst $a, '/charset'.($a && "/$a?compare"), $a eq $Request);
50                 } @{$_}
51         }
52         [
53                 iso      => 'ISO',
54                 win      => 'Windows',
55                 dos      => 'DOS',
56                 mac      => 'Apple',
57                 ebcdic   => 'EBCDIC',
58                 $tablist[0] eq 'default' ? () : ('' => 'common'),
59         ],
60         [
61                 westeur  => 'West',
62                 centeur  => 'Central',
63                 norteur  => 'North European',
64                 turkish  => 0,
65                 greek    => 0,
66                 cyrillic => 0,
67                 hebrew   => 0,
68         ],
69 );
70 :>.
71 </p>
72
73 <:
74 use POSIX qw( ceil );
75 use Shiar_Sheet::FormatChar;
76 my $glyphs = Shiar_Sheet::FormatChar->new;
77 my @request;
78
79 my $charsets = do 'charset-encoding.inc.pl'
80         or Alert('Encoding metadata could not be read', $@ || $!);
81
82 sub tabinput {
83         # generate character table(s)
84         my $input = shift or return;
85
86         state $ALIAS = {
87                 default    => [qw( u+0-27F utf-8+realsize iso-8859-1 iso-8859-15 cp1252 cp437 cp850 )],
88                 unicode    => [qw( uu+cols=32+realsize u+0-FFF u+1000-18AF u+18B0-1FFF )],
89                 us         => [qw( cp437 cp863 gsm0338 AdobeStandardEncoding )],
90                 ebcdic     => [qw( cp37 cp500 cp1047 posix-bc cp1026 cp875 )],
91                 iso        => [map {"iso-8859-$_"} 1 .. 11, 13 .. 16],
92                 dos        => [qw( cp437 cp865 cp861 cp860 cp863 cp850 cp857 cp852 cp775
93                                    cp737 cp869 cp866 cp855 cp862 cp864 )],
94                 aix        => [qw( cp1006 )],
95                 win        => [qw( cp1252 cp1250 cp1254 cp1257 cp1258 cp1253 cp1251 cp1255 cp1256 cp874 )],
96                 mac        => [qw( MacRoman MacRomanian MacRumanian MacCroatian MacCentralEurRoman MacTurkish MacIcelandic MacSami
97                                    MacGreek MacCyrillic MacHebrew MacArabic MacFarsi MacThai )],
98
99                 # languages
100                 westeur    => [qw( iso-8859-1 iso-8859-15 cp1252 iso-8859-14 cp850 hp-roman8 nextstep MacRoman )],
101                 centeur    => [qw( iso-8859-2 iso-8859-16 cp1250 cp852 MacRomanian MacCroatian MacCentralEurRoman )], # MacRumanian only for DB
102                 turkish    => [qw( iso-8859-9 iso-8859-3 cp1254 cp857 MacTurkish )],
103                 norteur    => [qw( baltic nordic )],
104                 baltic     => [qw( iso-8859-4 iso-8859-13 cp1257 cp775 )],
105                 nordic     => [qw( iso-8859-10 cp865 cp861 MacIcelandic MacSami )],
106                 cyrillic   => [qw( koi8-r koi8-u koi8-f iso-8859-5 cp1251 MacCyrillic cp866 cp855
107                                    +400 +2DE0 +A640-A69F +500-52F )], # MacUkrainian is broken
108                 arabic     => [qw( iso-8859-6 cp1256 MacArabic cp864 cp1006 MacFarsi
109                                    +600 +8A0-8BF+8E0 +750-77F )],
110                 greek      => [qw( iso-8859-7 cp1253 MacGreek cp737 cp869  +370 +1F00 )],
111                 hebrew     => [qw( iso-8859-8 cp1255 MacHebrew cp862  +590 )],
112                 thai       => [qw( iso-8859-11 cp874 MacThai )],
113                 vietnamese => [qw( viscii cp1258 MacVietnamese )],
114                 symbols    => [qw( symbol dingbats MacDingbats wingdings wingdings2 wingdings3 webdings )],
115
116                 # iso-code shorthand
117                 1 => 'westeur',
118                 2 => 'centeur',
119                 3 => 'turkish',
120                 4 => 'baltic',
121                 5 => 'cyrillic',
122                 6 => 'arabic',
123                 7 => 'greek',
124                 8 => 'hebrew',
125                 9 => 'turkish',
126                 10 => 'nordic',
127                 11 => 'thai',
128         };
129         if (my $follow = $ALIAS->{$input}) {
130                 tabinput($_) for ref $follow ? @{$follow} : $follow;
131                 return;
132         }
133
134         state $visible = {'' => 1};  # all present tables
135         my %row = (offset => 0, cols => 16);
136         my $params = $input =~ s/[+](.*)\z// ? $1 : undef;
137
138         if (not defined $params) {
139                 my $charset = $charsets->{$input} || {};
140                 my @parents = @{ $charset->{inherit} || [] };
141
142                 if (my ($parent, $part) = pairfirst { defined $visible->{$a} } @parents) {
143                         $row{parent} = $parent;
144                         $params = $part;
145                         $params = 80 unless $visible->{$parent}
146                                 or ($input eq 'MacCroatian' and defined $visible->{MacRomanian});
147                 }
148                 elsif (defined $visible->{ascii}) {
149                         $row{parent} = $parents[0];
150                         $params = $parents[1] // 80;
151                         $params = 80 if hex $params >= 0x80;  # ascii offset at most
152                 }
153                 elsif (@parents) {
154                         $row{parent} = $parents[0];
155                         $params = $parents[1] if hex $parents[1] == 0;  # apply ascii end
156                 }
157                 $visible->{$_} //= 0 for $row{parent} || ();
158         }
159
160         for my $param (split /[+]+/, $params // '') {
161                 if ($param eq 'realsize') {
162                         $row{realsize}++;
163                 }
164                 elsif ($param =~ m{ \A cols = (\d+) \z }x) {
165                         $row{cols} = $1;
166                 }
167                 elsif ($param =~ m{ \A (?<start> \p{AHex}+) (?: [-] (?<end> \p{AHex}+) )? \z }x) {
168                         if (defined $row{endpoint}) {
169                                 # extend earlier range
170                                 my $skip = int(($row{endpoint} || $row{startpoint}) / $row{cols});
171                                 for ($skip + 1 .. (hex($+{start}) / $row{cols}) - 1) {
172                                         $row{skip}->{ $_ * $row{cols} - $row{startpoint} }++;
173                                 }
174                         }
175                         else {
176                                 $row{startpoint} = hex $+{start};
177                         }
178                         $row{endpoint} = hex($+{end} || 0);
179                 }
180                 else {
181                         Alert("Unknown option <q>$param</q> for charset $input");
182                 }
183         }
184
185         if ($input =~ m{ \A (?:wing|web)dings \d* \z }ix) {
186                 eval "require Encode::\u$input";
187         }
188
189         if ($input eq '') {
190                 $row{offset} = delete $row{startpoint};
191                 $row{set} = 'Unicode characters';
192                 my $block = $row{offset} >> 8;
193                 $row{endpoint} ||= ($block + 1 << 8) - 1;
194                 $block == ($row{endpoint} >> 8) or undef $block;
195
196                 $row{table} = join '', map { chr } $row{offset} .. $row{endpoint};
197                 utf8::upgrade($row{table});  # prevent latin1 output
198
199                 $row{endpoint} -= $row{offset};
200
201                 if (defined $block) {
202                         $row{set} = sprintf 'Unicode block U+%02Xxx', $block;
203                         $row{offset} %= 0x100;
204                 }
205         }
206         elsif (lc $input eq 'uu') {
207                 $row{cell} = do 'charset-ucplanes.inc.pl'
208                         or Alert('Table data could not be read', $@ || $!);
209                 $row{endpoint} ||= 0x3FF;
210                 $row{set} = 'Unicode planes';
211         }
212         elsif (lc $input eq 'u') {
213                 $row{cell} = do 'charset-unicode.inc.pl'
214                         or Alert('Table data could not be read', $@ || $!);
215
216                 $row{endpoint} ||= 0x1FFF;
217                 $row{set} = 'Unicode ' . (
218                         $row{startpoint} <  0x1000 && $row{endpoint} < 0x1000 ? 'BMP' :
219                         $row{startpoint} >= 0x1000 && $row{endpoint} < 0x2000 ? 'SMP' :
220                         'allocations'
221                 );
222         }
223         elsif ($input =~ m/^utf-*8$/i) {
224                 $row{set} = 'UTF-8';
225                 $row{cell} = do 'charset-utf8.inc.pl'
226                         or Alert('Table data could not be read', $@ || $!);
227                 $row{endpoint} = 0xFF;
228         }
229         elsif ($row{set} = Encode::resolve_alias($input)) {
230                 $row{offset} = delete $row{startpoint};
231                 $row{endpoint} ||= 0xFF;
232                 if ($row{set} eq 'MacHebrew' or $row{set} eq 'MacThai') {
233                         # array of possibly multiple characters per code point
234                         $row{table} = [
235                                 map { Encode::decode($row{set}, pack 'C*', $_) } $row{offset} .. $row{endpoint}
236                         ];
237                 }
238                 else {
239                         # ~16x faster than decoding in loop;
240                         # substr strings is twice as fast as splitting to an array
241                         $row{table} = Encode::decode($row{set}, pack 'C*', $row{offset} .. $row{endpoint});
242                 }
243
244                 if ($row{set} eq 'cp437') {
245                         if ($row{offset} <= 0xED and $row{endpoint} >= 0xED) {
246                                 # replace phi glyph
247                                 substr($row{table}, 0xED - $row{offset}, 1) = 'ϕ';
248                         }
249                         if ($row{offset} < 0x20) {
250                                 # replace control characters by visible variants
251                                 my $sub = substr ' ☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼', $row{offset};
252                                 substr($row{table}, 0, length $sub) = $sub;
253                         }
254                 }
255                 elsif ($row{set} eq 'symbol') {
256                         if ($row{offset} <= 0x60 and $row{endpoint} >= 0x60) {
257                                 # replace radical extender by closest unicode equivalent
258                                 substr($row{table}, 0x60 - $row{offset},  1) = '│';
259                         }
260                         if ($row{offset} <= 0xBD and $row{endpoint} >= 0xFF) {
261                                 substr($row{table}, 0xBD - $row{offset},  2) = '⏐⎯'; # arrow extenders
262                                 substr($row{table}, 0xD2 - $row{offset},  3) = '®©™'; # serif variants
263                                 substr($row{table}, 0xE0 - $row{offset},  1) = '◊'; # replace lookalike, should match AdobeSymbol
264                                 substr($row{table}, 0xE2 - $row{offset},  3) = '®©™'; # sans-serif variants
265                                 substr($row{table}, 0xE6 - $row{offset}, 10) = '⎛⎜⎝⎡⎢⎣⎧⎨⎩⎪';
266                                 substr($row{table}, 0xF0 - $row{offset},  1) = '€';
267                                 substr($row{table}, 0xF4 - $row{offset}, 11) = '⎮⌡⎞⎟⎠⎤⎥⎦⎫⎬⎭';
268                         }
269                 }
270
271                 $row{endpoint} -= $row{offset};
272
273                 $visible->{ascii} =  # assume common base
274                 $visible->{ $row{set} } = 1;
275         }
276         else {
277                 Alert("Encoding <q>$input</q> unknown");
278                 return;
279         }
280         push @request, \%row;
281 }
282 tabinput($_) for @tablist;
283
284 my $NOCHAR = chr 0xFFFD;
285
286 sub range_cell {
287         my ($info, $offset) = @_;
288         my $table = $info->{cell} or return;
289         my $def = $table->{$offset} or return;
290         my ($len, $class, $name, $title) = @{$def};
291
292         my $cols = $info->{cols};
293         my $colsize = $table->{colsize} || 1;
294         my $attr = '';
295         $len /= $colsize;
296         $name //= $len <= 2 ? 'res' : 'reserved';
297
298         if (my $part = ($offset/$colsize - $info->{startpoint}) % $cols) {
299                 # continued row
300                 my $rest = $cols - $part;  # remaining
301                 $rest = $len if $len < $rest; #TODO: optimise
302                 if ($len -= $rest) {
303                         # continued on new row
304                         my @next = ($len * $colsize, "$class joinu");
305                         my $separate = $cols - $len > $rest;  # columns not on next row
306                         if ($len > $rest) {
307                                 # minority remains
308                                 push @next, $name, $title;
309                                 $title ||= $name;
310                                 $name = $separate && '…';
311                         }
312                         else {
313                                 # minority on next row
314                                 push @next, $separate && '"', $title || $name;
315                         }
316                         $table->{$offset + $colsize*$rest} //= \@next;
317                         $class .= ' joind';
318                 }
319                 $len = $rest;
320         }
321         elsif (my $rows = int($len / $cols)) {
322                 # multiple full rows
323                 my $rowsize = $colsize * $cols;
324                 if ($len -= $rows * $cols) {
325                         # partial row remains
326                         $table->{$offset + $rowsize * $rows} //= [$len*$colsize, "$class joinu", '', $title];
327                         $class .= ' joind';
328                 }
329
330                 unless ($info->{realsize}) {
331                         # coalesce multiple rows
332                         while ($rows > 3) {
333                                 $info->{skip}->{$offset += $rowsize}++;
334                                 $rows--;
335                         }
336                         if ($rows > 2) {
337                                 $info->{skip}->{$offset += $rowsize} = 0;
338                         }
339                 }
340
341                 $attr .= sprintf ' rowspan=%d', $rows;
342                 $len = $cols;
343         }
344
345         $attr .= sprintf ' colspan=%d', $len unless $len == 1;
346         $attr .= $1 if $class and $class =~ s/( \w+="[^"]*")//;
347         $attr .= sprintf ' class="%s"', $class if $class;
348         $attr .= sprintf ' title="%s"', EscapeHTML($title) if $title;
349         return "<td$attr>$name\n";
350 }
351
352 for my $row (@request) {
353         my $cols = $row->{cols};
354         my $colsize = $row->{cell} && $row->{cell}->{colsize} || 1;
355         my $coldigits = ceil(log($colsize * $cols) / log(16));  # uniform length of hexadecimal header
356         my $rowdiv = 16 ** $coldigits;  # row divide for column digits
357         $rowdiv = 1 if $rowdiv != $cols * $colsize;  # divide only if all columns are matched
358         my $offset = $row->{startpoint} * $colsize || 0;
359
360         printf '<div class="section"><table class="glyphs%s">', !$row->{cell} && ' charmap';
361         my $title = $row->{set};
362         $title .= " <aside>(over $_)</aside>"
363                 for $row->{parent} || ();
364         printf '<caption>%s</caption>', $title;
365         print '<col>' x ($cols + 1);
366         for my $section (qw{thead}) {
367                 print "<$section><tr><th>", $rowdiv == 1 ? '+' : '↱';
368                 printf '<th>%0*X', $coldigits, $_ * $colsize for 0 .. $cols - 1;
369                 print "\n";
370         }
371
372         print '<tbody>';
373         while ($offset <= $row->{endpoint} * $colsize) {
374                 if ($row->{skip}->{$offset}) {
375                         $offset += $cols * $colsize;
376                         next;
377                 }
378
379                 print '<tr><th>';
380                 if (defined $row->{skip}->{$offset}) {
381                         print '⋮';
382                 }
383                 else {
384                         if (my $rowmod = $offset % $rowdiv) {
385                                 # offset in column units
386                                 printf '<small>+%X</small>', $rowmod;
387                         }
388                         else {
389                                 # divided row offset
390                                 printf '%X', ($offset + $row->{offset}) / $rowdiv;
391                         }
392                 }
393                 say '';
394
395                 for (1 .. $cols) {
396                         if ($row->{cell}) {
397                                 print range_cell($row, $offset);
398                                 next;
399                         }
400
401                         my $cp = $offset + $row->{offset};
402                         my $glyph = ref $row->{table} eq 'ARRAY' ? $row->{table}->[$offset] :
403                                 substr $row->{table}, $offset, 1;
404                         my ($cell, $name, $class) = $glyph eq $NOCHAR ? () :
405                                 $glyphs->glyph_html($glyph);
406
407                         if (exists $get{compare}) {
408                                 state $visible = {};
409                                 $class = (
410                                         $cp == ord $glyph ? 'l4' :
411                                         $row->{parent} && $glyph eq
412                                                 Encode::decode($row->{parent}, pack 'C', $cp) ? 'l3' :
413                                         !$class ? undef :
414                                         $visible->{$glyph} ? 'l2' :
415                                         'l1'
416                                 );
417                                 $visible->{$glyph}++;
418                         }
419
420                         say sprintf $class ? '<td title="%s" class="X %s">%s' : '<td title="%s">',
421                                 $name, $class, $cell;
422                 }
423                 continue {
424                         $offset += $colsize;
425                 }
426         }
427         say '</table></div>';
428 }
429
430 :>
431 <hr>
432
433 <div class="legend">
434         <table class="glyphs"><tr><: if (exists $get{compare}) { :>
435         <td class="X l4">unicode
436         <td class="X l3">inherited
437         <td class="X l2">existing
438         <td class="X l1">original
439         <td class="">unassigned
440 <: } else { :>
441         <td class="X Cc">control
442         <td class="X Zs"><span>whitespace</span>
443         <td class="X Mn">diacritic<table class="glyphs"><tr>
444                 <td class="X Sk">letter
445                 </table>
446         <td class="X Po">punctuation<table class="glyphs"><tr>
447                 <td class="X Pf">quote
448                 </table>
449         <td class="X So">symbol<table class="glyphs"><tr>
450                 <td class="X Sm">math
451                 <td class="X Sc">currency
452                 </table>
453         <td class="X No">numeric
454         <td class="X Greek">greek<table class="glyphs"><tr>
455                 <td class="X Latin">latin
456                 <td class="X Cyrillic">cyrillic
457                 </table>
458         <td class="X Aramaic">aramaic<table class="glyphs"><tr>
459                 <td class="X Brahmic">brahmic
460                 <td class="X Arabic">arabic
461                 </table>
462         <td class="X Syllabic">syllabic<table class="glyphs"><tr>
463                 <td class="X African">african
464                 <td class="X Hiragana">japanese
465                 <td class="X Han">cjk
466                 <td class="X Bopomofo">chinese
467                 </table>
468         <td class="X Alpha">alphabetic
469         </table>
470
471         <table class="glyphs"><tr>
472         <td class="X">unicode 7.0
473         <td class="X Xr">proposed
474         <td class="X Xd">deprecated
475         <td class="">unassigned
476         <td class="X Xi">invalid
477 <: } :> </table>
478 </div>
479