digits: split up table method to display rows
[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'charset-unicode.inc.pl charset-utf8.inc.pl'],
16 });
17
18 my @tablist = split m{/+}, $Request || 'default';
19
20 use List::Util qw( first pairmap pairfirst pairs );
21
22 :>
23 <h1>Character encodings</h1>
24
25 <p>
26 <:
27 if ($tablist[0] eq 'default') {
28         say "Overview of Unicode allocation and common latin code pages.";
29         say "Compare alternate charsets:";
30 }
31 else {
32         say "Charset comparison:";
33 }
34
35 sub optionlink {
36         my ($title, $href, $selected) = @_;
37         return sprintf(
38                 $selected ? '<strong>%s</strong>' : '<a href="%2$s">%s</a>',
39                 EscapeHTML($title), $href
40         );
41 }
42
43 print join " •\n", (
44         map {
45                 join " ·\n", pairmap {
46                         optionlink($b || ucfirst $a, '/charset'.($a && "/$a?compare"), $a eq $Request);
47                 } @{$_}
48         }
49         [
50                 iso      => 'ISO',
51                 dos      => 'DOS',
52                 mac      => 'Apple',
53                 ebcdic   => 'EBCDIC',
54                 $tablist[0] eq 'default' ? () : ('' => 'common'),
55         ],
56         [
57                 westeur  => 'West',
58                 centeur  => 'Central',
59                 norteur  => 'North European',
60                 turkish  => 0,
61                 greek    => 0,
62                 cyrillic => 0,
63                 hebrew   => 0,
64         ],
65 );
66 :>.
67 </p>
68
69 <:
70 use POSIX qw( ceil );
71 use Shiar_Sheet::FormatChar;
72 my $glyphs = Shiar_Sheet::FormatChar->new;
73 my @request;
74
75 sub tabinput {
76         # generate character table(s)
77         my $input = shift or return;
78
79         state $ALIAS = {
80                 default    => [qw( u+0-639 utf-8+realsize iso-8859-1 iso-8859-15 cp1252 cp437 cp850 )],
81                 unicode    => [qw( uu+cols=32+realsize u+0-4095 u+4096-6319 u+6320-8191 )],
82                 us         => [qw( cp437 cp863 gsm0338 AdobeStandardEncoding )],
83                 ebcdic     => [qw( cp37 cp500 cp1047 posix-bc cp1026 cp875 )],
84                 iso        => [map {"iso-8859-$_"} 1 .. 11, 13 .. 16],
85                 dos        => [qw( cp437 cp865 cp861 cp860 cp863 cp850 cp857 cp852 cp775
86                                    cp737 cp869 cp866 cp855 cp862 cp864 )],
87                 aix        => [qw( cp1006 )],
88                 win        => [qw( cp1252 cp1250 cp1254 cp1257 cp1258 cp1253 cp1251 cp1255 cp1256 cp874 )],
89                 mac        => [qw( MacRoman MacRomanian MacRumanian MacCroatian MacCentralEurRoman MacTurkish MacIcelandic MacSami
90                                    MacGreek MacCyrillic MacHebrew MacArabic MacFarsi MacThai )],
91
92                 # languages
93                 westeur    => [qw( iso-8859-1 iso-8859-15 cp1252 iso-8859-14 cp850 hp-roman8 nextstep MacRoman )],
94                 centeur    => [qw( iso-8859-2 iso-8859-16 cp1250 cp852 MacRomanian MacCroatian MacCentralEurRoman )], # MacRumanian only for DB
95                 turkish    => [qw( iso-8859-9 iso-8859-3 cp1254 cp857 MacTurkish )],
96                 norteur    => [qw( baltic nordic )],
97                 baltic     => [qw( iso-8859-4 iso-8859-13 cp1257 cp775 )],
98                 nordic     => [qw( iso-8859-10 cp865 cp861 MacIcelandic MacSami )],
99                 cyrillic   => [qw( koi8-r koi8-u koi8-f iso-8859-5 cp1251 MacCyrillic cp866 cp855
100                                    U4 U2DE-2DF UA64-A69 U50-52 )], # MacUkrainian is broken
101                 arabic     => [qw( iso-8859-6 cp1256 MacArabic cp864 cp1006 MacFarsi
102                                    U6 U8A-8F+0-31+64 U75-77 )],
103                 greek      => [qw( iso-8859-7 cp1253 MacGreek cp737 cp869  U37-3F U1F )],
104                 hebrew     => [qw( iso-8859-8 cp1255 MacHebrew cp862  U59-5F )],
105                 thai       => [qw( iso-8859-11 cp874 MacThai )],
106                 vietnamese => [qw( viscii cp1258 MacVietnamese )],
107                 symbol     => [qw( symbol dingbats MacDingbats AdobeZdingbat AdobeSymbol )],
108
109                 # iso-code shorthand
110                 1 => 'westeur',
111                 2 => 'centeur',
112                 3 => 'turkish',
113                 4 => 'baltic',
114                 5 => 'cyrillic',
115                 6 => 'arabic',
116                 7 => 'greek',
117                 8 => 'hebrew',
118                 9 => 'turkish',
119                 10 => 'nordic',
120                 11 => 'thai',
121         };
122         if (my $follow = $ALIAS->{$input}) {
123                 tabinput($_) for ref $follow ? @{$follow} : $follow;
124                 return;
125         }
126
127         state $visible = {};  # all present tables
128         my %row = (offset => 0, cols => 16);
129         my $params = $input =~ s/[+](.*)\z// ? $1 : undef;
130
131         if (not defined $params) {
132                 state $INHERIT = {
133                         'cp437'       => ['cp850' => 0, 'ascii' => '0-31+128'], # ascii range overridden later
134                         'gsm0338'     => ['ascii' => '0-127'],
135
136                         'iso-8859-2'  => ['iso-8859-1' => '160'],
137                         'iso-8859-3'  => ['iso-8859-1' => '160'], #TODO: also apply to iso-8859-9
138                         'iso-8859-4'  => ['iso-8859-2' => '160'],
139                         'iso-8859-5'  => ['iso-8859-1' => '160'],
140                         'iso-8859-6'  => ['cp1256' => '128', 'iso-8859-1' => '160'],
141                         'iso-8859-7'  => ['iso-8859-1' => '160'],
142                         'iso-8859-8'  => ['iso-8859-1' => '160'],
143                         'iso-8859-9'  => ['iso-8859-1' => '208-223+240'],
144                         'iso-8859-10' => ['iso-8859-4' => '160'],
145                         'iso-8859-11' => ['iso-8859-1' => '160'],
146                         'iso-8859-13' => ['iso-8859-4' => '160'],
147                         'iso-8859-14' => ['iso-8859-1' => '160'],
148                         'iso-8859-15' => ['iso-8859-1' => '160-191'],
149                         'iso-8859-16' => ['iso-8859-2' => '160'],
150                         'hp-roman8'   => ['iso-8859-1' => '160'],
151
152                         'cp1252'      => ['iso-8859-1' => '128-159'],
153                         'cp1250'      => ['iso-8859-2' => '128-191', 'cp1252' => '128'],
154                         'cp1254'      => ['iso-8859-9' => '128-159', 'cp1252' => '128-159+208'],
155                         'cp874'       => ['iso-8859-11' => '128-159', 'cp1252' => '128'], # windows-874 actually cp1162
156                         'cp1257'      => ['iso-8859-13' => '128-159+255', 'cp1252' => '128'],
157                         'cp1251'      => ['cp1252' => '128'],
158                         'cp1253'      => ['cp1252' => '128'],
159                         'cp1255'      => ['iso-8859-8' => '128-223', 'cp1252' => '128'],
160                         'cp1256'      => ['cp1252' => '128'],
161                         'cp1258'      => ['cp1252' => '128-159+192'],
162
163                         'cp850'       => ['cp437' => '144'],
164                         'cp860'       => ['cp437' => '128-175'],
165                         'cp861'       => ['cp865' => '128-175'],
166                         'cp863'       => ['cp437' => '128-175'],
167                         'cp865'       => ['cp437' => '144-175'],
168                         'cp852'       => ['cp850' => '128', 'cp437' => '128'],
169                         'cp857'       => ['cp850' => '128-175+208-239', 'cp437' => '128'],
170                         'cp775'       => ['cp850' => '128'],  # partial cp437
171                         'cp866'       => ['cp437' => '128-175+224'],
172                         'cp855'       => ['cp437' => '128'],
173                         'cp1006'      => ['iso-8859-6' => '160', 'cp437' => '128'],
174                         'cp737'       => ['cp437' => '128-175+224'],
175                         'cp869'       => ['cp437' => '128'],
176                         'cp862'       => ['cp437' => '128-159'],
177                         'cp864'       => ['MacArabic' => '128', 'iso-8859-6' => '128', 'cp437' => '128'], #TODO: compare form variants
178
179                         'koi8-u'      => ['koi8-r' => '144-191'],
180                         'koi8-f'      => ['koi8-u' => '144-191'],
181
182                         'MacRomanian' => ['MacRoman' => '160-191+208-223'],
183                         'MacRumanian' => ['MacRomanian' => '160-191+208-223', 'MacRoman' => '160-191+208-223'],
184                         'MacCroatian' => ['MacRoman' => '160'],
185                         'MacCentralEurRoman' => ['MacRoman' => '128'],
186                         'MacIcelandic'=> ['MacRoman' => '160-175+208-239'],
187                         'MacTurkish'  => ['MacRoman' => '208-223'], # F5 is unassigned
188                         'MacSami'     => ['MacIcelandic' => '144-191+208-223+240', 'MacRoman' => '144'],
189                         'MacGreek'    => ['MacRoman' => '128'],
190                         'MacCyrillic' => ['MacRoman' => '128'],
191                         'MacHebrew'   => ['iso-8859-8' => '128', 'MacRoman' => '128-143+160'], # partial ascii
192                         'MacArabic'   => ['iso-8859-6' => '128', 'cp864' => '128', 'MacRoman' => '128'], #TODO: multiple parents
193                         'MacFarsi'    => ['MacArabic' => '176-191', 'MacRoman' => '128'],
194
195                         'cp37'        => ['posix-bc' => '0'],
196                         'posix-bc'    => ['cp1047' => '64'],
197                         'cp500'       => ['cp37' => '64-95+176-191'],
198                         'cp1047'      => ['cp37' => '16-47+80-95+160-191'],
199                         'cp1026'      => ['cp37' => '64'],
200                         'cp875'       => ['cp37' => '48'],
201
202                 };
203
204                 my @parents = @{ $INHERIT->{$input} || [] };
205
206                 if (my ($parent, $part) = pairfirst { defined $visible->{$a} } @parents) {
207                         $row{parent} = $parent;
208                         $params = $part;
209                         $params = 128 unless $visible->{$parent}
210                                 or ($input eq 'MacCroatian' and defined $visible->{MacRomanian});
211                 }
212                 elsif (defined $visible->{ascii}) {
213                         $row{parent} = $parents[0];
214                         $params = $parents[1] // 128;
215                         $params = 128 if $params >= 128;  # ascii offset at most
216                 }
217                 elsif (@parents) {
218                         $row{parent} = $parents[0];
219                         $params = $parents[1] if $parents[1] == 0;  # apply ascii end
220                 }
221                 $visible->{$_} //= 0 for $row{parent} || ();
222         }
223
224         for my $param (split /[+]+/, $params // '') {
225                 if ($param eq 'realsize') {
226                         $row{realsize}++;
227                 }
228                 elsif ($param =~ m{ \A cols = (\d+) \z }x) {
229                         $row{cols} = $1;
230                 }
231                 elsif ($param =~ m{ \A (?<offset> \d+) (?: [-] (?<endpoint> \d+) )? \z }x) {
232                         if (defined $row{endpoint}) {
233                                 # extend earlier range
234                                 my $skip = int(($row{endpoint} || $row{offset}) / $row{cols});
235                                 for ($skip + 1 .. ($+{offset} / $row{cols}) - 1) {
236                                         $row{skip}->{ $_ * $row{cols} - $row{offset} }++;
237                                 }
238                         }
239                         else {
240                                 $row{offset} = $+{offset};
241                         }
242                         $row{endpoint} = $+{endpoint} || 0;
243                 }
244                 else {
245                         Alert("Unknown option <q>$param</q> for charset $input");
246                 }
247         }
248
249         if ($input =~ m{ \A u ([0-9a-f]+) (?:-([0-9a-f]+))? \z }ix) {
250                 my $start = hex($1) << ($2 ? 4 : 8);
251                 my $end = $2 ? (hex($2) << 4) + $row{cols} - 1 : $start + 255;
252                 $row{table} = join '', map { chr } $start .. $end;
253                 utf8::upgrade($row{table});  # prevent latin1 output
254                 $row{endpoint} = $end - $start;
255                 $row{set} = sprintf 'Unicode block U+%02Xxx', $start >> 8;
256                 $row{offset} = $start % 256;
257         }
258         elsif (lc $input eq 'uu') {
259                 $row{set} = 'Unicode planes';
260                 $row{cell} = do 'charset-ucplanes.inc.pl'
261                         or Alert('Table data could not be read', $@ || $!);
262                 $row{endpoint} = 1023 * $row{cell}->{colsize};
263         }
264         elsif (lc $input eq 'u') {
265                 $row{cell} = do 'charset-unicode.inc.pl'
266                         or Alert('Table data could not be read', $@ || $!);
267
268                 $row{endpoint} ||= 8191;
269                 $row{endpoint}  *= $row{cell}->{colsize};
270                 $row{startpoint} = $row{cell}->{colsize} * $row{offset};
271                 $row{offset} = 0;
272                 $row{set} = 'Unicode ' . (
273                         $row{startpoint} <  0x10000 && $row{endpoint} < 0x10000 ? 'BMP' :
274                         $row{startpoint} >= 0x10000 && $row{endpoint} < 0x20000 ? 'SMP' :
275                         'allocations'
276                 );
277         }
278         elsif ($input =~ m/^utf-*8$/i) {
279                 $row{set} = 'UTF-8';
280                 $row{cell} = do 'charset-utf8.inc.pl'
281                         or Alert('Table data could not be read', $@ || $!);
282                 $row{endpoint} = 255;
283         }
284         elsif ($row{set} = Encode::resolve_alias($input)) {
285                 $row{endpoint} ||= 255;
286                 if ($row{set} eq 'MacHebrew' or $row{set} eq 'MacThai') {
287                         # array of possibly multiple characters per code point
288                         $row{table} = [
289                                 map { Encode::decode($row{set}, pack 'C*', $_) } $row{offset} .. $row{endpoint}
290                         ];
291                 }
292                 else {
293                         # ~16x faster than decoding in loop;
294                         # substr strings is twice as fast as splitting to an array
295                         $row{table} = Encode::decode($row{set}, pack 'C*', $row{offset} .. $row{endpoint});
296                 }
297                 $row{endpoint} -= $row{offset};
298
299                 if ($row{set} eq 'cp437') {
300                         for my $phipos (237 - $row{offset}) {
301                                 next if $phipos < 0 or $phipos > $row{endpoint};
302                                 # replace phi glyph
303                                 substr($row{table}, $phipos, 1) = pack 'U*', 0x3D5;
304                         }
305                         if ($row{offset} == 0) {
306                                 # replace control characters by visible variants
307                                 substr($row{table}, 0, 32) = pack 'U*', map {hex} qw(
308                                         2007 263A 263B 2665 2666 2663 2660 2022
309                                         25D8 25CB 25D9 2642 2640 266A 266B 263C
310                                         25BA 25C4 2195 203C 00B6 00A7 25AC 21A8
311                                         2191 2193 2192 2190 221F 2194 25B2 25BC
312                                 );
313                         }
314                 }
315
316                 $visible->{ascii} =  # assume common base
317                 $visible->{ $row{set} } = 1;
318         }
319         else {
320                 Alert("Encoding <q>$input</q> unknown");
321                 return;
322         }
323         push @request, \%row;
324 }
325 tabinput($_) for @tablist;
326
327 my $NOCHAR = chr 0xFFFD;
328
329 sub range_cell {
330         my ($info, $offset) = @_;
331         my $table = $info->{cell} or return;
332         my $def = $table->{$offset} or return;
333         my ($len, $class, $name, $title) = @{$def};
334
335         my $cols = $info->{cols};
336         my $colsize = $table->{colsize} || 1;
337         my $attr = '';
338         $len /= $colsize;
339         $name //= $len <= 2 ? 'res' : 'reserved';
340
341         if (my $part = $offset/$colsize % $cols) {
342                 # continued row
343                 my $rest = $cols - $part;  # remaining
344                 $rest = $len if $len < $rest; #TODO: optimise
345                 if ($len -= $rest) {
346                         # continued on new row
347                         my @next = ($len * $colsize, "$class joinu");
348                         if ($len > $rest) {
349                                 # minority remains
350                                 push @next, $name, $title;
351                                 $title ||= $name;
352                                 $name = '';
353                         }
354                         else {
355                                 # minority on next row
356                                 push @next, '"', $title || $name;
357                         }
358                         $table->{$offset + $colsize*$rest} //= \@next;
359                         $class .= ' joind';
360                 }
361                 $len = $rest;
362         }
363         elsif (my $rows = int($len / $cols)) {
364                 # multiple full rows
365                 my $rowsize = $colsize * $cols;
366                 if ($len -= $rows * $cols) {
367                         # partial row remains
368                         $table->{$offset + $rowsize * $rows} //= [$len*$colsize, "$class joinu", '', $title];
369                         $class .= ' joind';
370                 }
371
372                 unless ($info->{realsize}) {
373                         # coalesce multiple rows
374                         while ($rows > 3) {
375                                 $info->{skip}->{$offset += $rowsize}++;
376                                 $rows--;
377                         }
378                         if ($rows > 2) {
379                                 $info->{skip}->{$offset += $rowsize} = 0;
380                         }
381                 }
382
383                 $attr .= sprintf ' rowspan=%d', $rows;
384                 $len = $cols;
385         }
386
387         $attr .= sprintf ' colspan=%d', $len unless $len == 1;
388         $attr .= $1 if $class and $class =~ s/( \w+="[^"]*")//;
389         $attr .= sprintf ' class="%s"', $class if $class;
390         $attr .= sprintf ' title="%s"', EscapeHTML($title) if $title;
391         return "<td$attr>$name\n";
392 }
393
394 for my $row (@request) {
395         my $cols = $row->{cols};
396         my $colsize = $row->{cell} && $row->{cell}->{colsize} || 1;
397         my $coldigits = ceil(log($colsize * $cols) / log(16));  # uniform length of hexadecimal header
398         my $rowdiv = 16 ** $coldigits;  # row divide for column digits
399         $rowdiv = 1 if $rowdiv != $cols * $colsize;  # divide only if all columns are matched
400         my $offset = $row->{startpoint} || 0;
401
402         printf '<div class="section"><table class="glyphs%s">', !$row->{cell} && ' charmap';
403         my $title = $row->{set};
404         $title .= " <aside>(over $_)</aside>"
405                 for grep { $_ ne 'iso-8859-1' } $row->{parent} // ();
406         printf '<caption>%s</caption>', $title;
407         print '<col>' x ($cols + 1);
408         for my $section (qw{thead}) {
409                 print "<$section><tr><th>", $rowdiv == 1 ? '+' : '↱';
410                 printf '<th>%0*X', $coldigits, $_ * $colsize for 0 .. $cols - 1;
411                 print "\n";
412         }
413         print '<tbody>';
414         while ($offset < $row->{endpoint}) {
415                 if ($row->{skip}->{$offset}) {
416                         $offset += $cols * $colsize;
417                         next;
418                 }
419
420                 print '<tr><th>';
421                 if (defined $row->{skip}->{$offset}) {
422                         print '⋮';
423                 }
424                 else {
425                         if (my $rowmod = $offset % $rowdiv) {
426                                 # offset in column units
427                                 printf '<small>+%X</small>', $rowmod;
428                         }
429                         else {
430                                 # divided row offset
431                                 printf '%X', ($offset + $row->{offset}) / $rowdiv;
432                         }
433                 }
434                 say '';
435
436                 for (1 .. $cols) {
437                         if ($row->{cell}) {
438                                 print range_cell($row, $offset);
439                                 next;
440                         }
441
442                         my $cp = $offset + $row->{offset};
443                         my $glyph = ref $row->{table} eq 'ARRAY' ? $row->{table}->[$offset] :
444                                 substr $row->{table}, $offset, 1;
445                         my ($cell, $name, $class) = $glyph eq $NOCHAR ? () :
446                                 $glyphs->glyph_html($glyph);
447
448                         if (exists $get{compare}) {
449                                 state $visible = {};
450                                 $class = (
451                                         $cp == ord $glyph ? 'l4' :
452                                         $row->{parent} && $glyph eq
453                                                 Encode::decode($row->{parent}, pack 'C', $cp) ? 'l3' :
454                                         !$class ? undef :
455                                         $visible->{$glyph} ? 'l2' :
456                                         'l1'
457                                 );
458                                 $visible->{$glyph}++;
459                         }
460
461                         say sprintf $class ? '<td title="%s" class="X %s">%s' : '<td title="%s">',
462                                 $name, $class, $cell;
463                 }
464                 continue {
465                         $offset += $colsize;
466                 }
467         }
468         say '</table></div>';
469 }
470
471 :>
472 <hr>
473
474 <div class="legend">
475         <table class="glyphs"><tr><: if (exists $get{compare}) { :>
476         <td class="X l4">unicode
477         <td class="X l3">inherited
478         <td class="X l2">existing
479         <td class="X l1">original
480         <td class="">unassigned
481 <: } else { :>
482         <td class="X Cc">control
483         <td class="X Zs"><span>whitespace</span>
484         <td class="X Mn">diacritic<table class="glyphs"><tr>
485                 <td class="X Sk">letter
486                 </table>
487         <td class="X Po">punctuation<table class="glyphs"><tr>
488                 <td class="X Pf">quote
489                 </table>
490         <td class="X So">symbol<table class="glyphs"><tr>
491                 <td class="X Sm">math
492                 <td class="X Sc">currency
493                 </table>
494         <td class="X No">numeric
495         <td class="X Greek">greek<table class="glyphs"><tr>
496                 <td class="X Latin">latin
497                 <td class="X Cyrillic">cyrillic
498                 </table>
499         <td class="X Aramaic">aramaic<table class="glyphs"><tr>
500                 <td class="X Brahmic">brahmic
501                 <td class="X Arabic">arabic
502                 </table>
503         <td class="X Syllabic">syllabic<table class="glyphs"><tr>
504                 <td class="X African">african
505                 <td class="X Hiragana">japanese
506                 <td class="X Han">cjk
507                 <td class="X Bopomofo">chinese
508                 </table>
509         <td class="X Alpha">alphabetic
510         </table>
511
512         <table class="glyphs"><tr>
513         <td class="X">unicode 7.0
514         <td class="X Xr">proposed
515         <td class="X Xd">deprecated
516         <td class="">unassigned
517         <td class="X Xi">invalid
518 <: } :> </table>
519 </div>
520