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