4f60765cd7c94d346dae6f013891ee39509cb95e
[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         my $params = $input =~ s/[+](.*)\z// ? $1 : undef;
87         my $charset = $charsets->{lc $input} || {};
88
89         if (ref $charset ne 'HASH') {
90                 $params and Alert("Parameters ignored for $input",
91                         "Cannot apply <q>$params</q> to multiple charsets.",
92                 );
93                 tabinput($_) for ref $charset ? @{$charset} : $charset;
94                 return;
95         }
96
97         state $visible = {'' => 1};  # all present tables
98         my %row = (offset => 0, cols => 16);
99
100         if (not defined $params) {
101                 my @parents = @{ $charset->{inherit} || [] };
102
103                 if (my ($parent, $part) = pairfirst { defined $visible->{$a} } @parents) {
104                         $row{parent} = $parent;
105                         $params = $part;
106                         $params = 80 unless $visible->{$parent}
107                                 or ($input eq 'MacCroatian' and defined $visible->{MacRomanian});
108                 }
109                 elsif (defined $visible->{ascii}) {
110                         $row{parent} = $parents[0];
111                         $params = $parents[1] // 80;
112                         $params = 80 if hex $params >= 0x80;  # ascii offset at most
113                 }
114                 elsif (@parents) {
115                         $row{parent} = $parents[0];
116                         $params = $parents[1] if hex $parents[1] == 0;  # apply ascii end
117                 }
118                 $visible->{$_} //= 0 for $row{parent} || ();
119         }
120
121         for my $param (split /[+]+/, $params // '') {
122                 if ($param eq 'realsize') {
123                         $row{realsize}++;
124                 }
125                 elsif ($param =~ m{ \A cols = (\d+) \z }x) {
126                         $row{cols} = $1;
127                 }
128                 elsif ($param =~ m{ \A (?<start> \p{AHex}+) (?: [-] (?<end> \p{AHex}+) )? \z }x) {
129                         if (defined $row{endpoint}) {
130                                 # extend earlier range
131                                 my $skip = int(($row{endpoint} || $row{startpoint}) / $row{cols});
132                                 for ($skip + 1 .. (hex($+{start}) / $row{cols}) - 1) {
133                                         $row{skip}->{ $_ * $row{cols} - $row{startpoint} }++;
134                                 }
135                         }
136                         else {
137                                 $row{startpoint} = hex $+{start};
138                         }
139                         $row{endpoint} = hex($+{end} || 0);
140                 }
141                 else {
142                         Alert("Unknown option <q>$param</q> for charset $input");
143                 }
144         }
145
146         if ($input =~ m{ \A (?:wing|web)dings \d* \z }ix) {
147                 eval "require Encode::\u$input";
148         }
149
150         if ($input eq '') {
151                 $row{offset} = delete $row{startpoint};
152                 $row{set} = 'Unicode characters';
153                 my $block = $row{offset} >> 8;
154                 $row{endpoint} ||= ($block + 1 << 8) - 1;
155                 $block == ($row{endpoint} >> 8) or undef $block;
156
157                 $row{table} = join '', map { chr } $row{offset} .. $row{endpoint};
158                 utf8::upgrade($row{table});  # prevent latin1 output
159
160                 $row{endpoint} -= $row{offset};
161
162                 if (defined $block) {
163                         $row{set} = sprintf 'Unicode block U+%02Xxx', $block;
164                         $row{offset} %= 0x100;
165                 }
166         }
167         elsif (lc $input eq 'uu') {
168                 $row{cell} = do 'charset-ucplanes.inc.pl'
169                         or Alert('Table data could not be read', $@ || $!);
170                 $row{endpoint} ||= 0x3FF;
171                 $row{set} = 'Unicode planes';
172         }
173         elsif (lc $input eq 'u') {
174                 $row{cell} = do 'charset-unicode.inc.pl'
175                         or Alert('Table data could not be read', $@ || $!);
176
177                 $row{endpoint} ||= 0x1FFF;
178                 $row{set} = 'Unicode ' . (
179                         $row{startpoint} <  0x1000 && $row{endpoint} < 0x1000 ? 'BMP' :
180                         $row{startpoint} >= 0x1000 && $row{endpoint} < 0x2000 ? 'SMP' :
181                         'allocations'
182                 );
183         }
184         elsif ($input =~ m/^utf-*8$/i) {
185                 $row{set} = 'UTF-8';
186                 $row{cell} = do 'charset-utf8.inc.pl'
187                         or Alert('Table data could not be read', $@ || $!);
188                 $row{endpoint} = 0xFF;
189         }
190         elsif ($row{set} = Encode::resolve_alias($input)) {
191                 $row{offset} = delete $row{startpoint};
192                 $row{endpoint} ||= 0xFF;
193                 if ($row{set} eq 'MacHebrew' or $row{set} eq 'MacThai') {
194                         # array of possibly multiple characters per code point
195                         $row{table} = [
196                                 map { Encode::decode($row{set}, pack 'C*', $_) } $row{offset} .. $row{endpoint}
197                         ];
198                 }
199                 else {
200                         # ~16x faster than decoding in loop;
201                         # substr strings is twice as fast as splitting to an array
202                         $row{table} = Encode::decode($row{set}, pack 'C*', $row{offset} .. $row{endpoint});
203                 }
204
205                 if ($row{set} eq 'cp437') {
206                         if ($row{offset} <= 0xED and $row{endpoint} >= 0xED) {
207                                 # replace phi glyph
208                                 substr($row{table}, 0xED - $row{offset}, 1) = 'ϕ';
209                         }
210                         if ($row{offset} < 0x20) {
211                                 # replace control characters by visible variants
212                                 my $sub = substr ' ☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼', $row{offset};
213                                 substr($row{table}, 0, length $sub) = $sub;
214                         }
215                 }
216                 elsif ($row{set} eq 'symbol') {
217                         if ($row{offset} <= 0x60 and $row{endpoint} >= 0x60) {
218                                 # replace radical extender by closest unicode equivalent
219                                 substr($row{table}, 0x60 - $row{offset},  1) = '│';
220                         }
221                         if ($row{offset} <= 0xBD and $row{endpoint} >= 0xFF) {
222                                 substr($row{table}, 0xBD - $row{offset},  2) = '⏐⎯'; # arrow extenders
223                                 substr($row{table}, 0xD2 - $row{offset},  3) = '®©™'; # serif variants
224                                 substr($row{table}, 0xE0 - $row{offset},  1) = '◊'; # replace lookalike, should match AdobeSymbol
225                                 substr($row{table}, 0xE2 - $row{offset},  3) = '®©™'; # sans-serif variants
226                                 substr($row{table}, 0xE6 - $row{offset}, 10) = '⎛⎜⎝⎡⎢⎣⎧⎨⎩⎪';
227                                 substr($row{table}, 0xF0 - $row{offset},  1) = '€';
228                                 substr($row{table}, 0xF4 - $row{offset}, 11) = '⎮⌡⎞⎟⎠⎤⎥⎦⎫⎬⎭';
229                         }
230                 }
231
232                 $row{endpoint} -= $row{offset};
233
234                 $visible->{ascii} =  # assume common base
235                 $visible->{ $row{set} } = 1;
236         }
237         else {
238                 Alert("Encoding <q>$input</q> unknown");
239                 return;
240         }
241         push @request, \%row;
242 }
243 tabinput($_) for @tablist;
244
245 my $NOCHAR = chr 0xFFFD;
246
247 sub range_cell {
248         my ($info, $offset) = @_;
249         my $table = $info->{cell} or return;
250         my $def = $table->{$offset} or return;
251         my ($len, $class, $name, $title) = @{$def};
252
253         my $cols = $info->{cols};
254         my $colsize = $table->{colsize} || 1;
255         my $attr = '';
256         $len /= $colsize;
257         $name //= $len <= 2 ? 'res' : 'reserved';
258
259         if (my $part = ($offset/$colsize - $info->{startpoint}) % $cols) {
260                 # continued row
261                 my $rest = $cols - $part;  # remaining
262                 $rest = $len if $len < $rest; #TODO: optimise
263                 if ($len -= $rest) {
264                         # continued on new row
265                         my @next = ($len * $colsize, "$class joinu");
266                         my $separate = $cols - $len > $rest;  # columns not on next row
267                         if ($len > $rest) {
268                                 # minority remains
269                                 push @next, $name, $title;
270                                 $title ||= $name;
271                                 $name = $separate && '…';
272                         }
273                         else {
274                                 # minority on next row
275                                 push @next, $separate && '"', $title || $name;
276                         }
277                         $table->{$offset + $colsize*$rest} //= \@next;
278                         $class .= ' joind';
279                 }
280                 $len = $rest;
281         }
282         elsif (my $rows = int($len / $cols)) {
283                 # multiple full rows
284                 my $rowsize = $colsize * $cols;
285                 if ($len -= $rows * $cols) {
286                         # partial row remains
287                         $table->{$offset + $rowsize * $rows} //= [$len*$colsize, "$class joinu", '', $title];
288                         $class .= ' joind';
289                 }
290
291                 unless ($info->{realsize}) {
292                         # coalesce multiple rows
293                         while ($rows > 3) {
294                                 $info->{skip}->{$offset += $rowsize}++;
295                                 $rows--;
296                         }
297                         if ($rows > 2) {
298                                 $info->{skip}->{$offset += $rowsize} = 0;
299                         }
300                 }
301
302                 $attr .= sprintf ' rowspan=%d', $rows;
303                 $len = $cols;
304         }
305
306         $attr .= sprintf ' colspan=%d', $len unless $len == 1;
307         $attr .= $1 if $class and $class =~ s/( \w+="[^"]*")//;
308         $attr .= sprintf ' class="%s"', $class if $class;
309         $attr .= sprintf ' title="%s"', EscapeHTML($title) if $title;
310         return "<td$attr>$name\n";
311 }
312
313 for my $row (@request) {
314         my $cols = $row->{cols};
315         my $colsize = $row->{cell} && $row->{cell}->{colsize} || 1;
316         my $coldigits = ceil(log($colsize * $cols) / log(16));  # uniform length of hexadecimal header
317         my $rowdiv = 16 ** $coldigits;  # row divide for column digits
318         $rowdiv = 1 if $rowdiv != $cols * $colsize;  # divide only if all columns are matched
319         my $offset = $row->{startpoint} * $colsize || 0;
320
321         printf '<div class="section"><table class="glyphs%s">', !$row->{cell} && ' charmap';
322         my $title = $row->{set};
323         $title .= " <aside>(over $_)</aside>"
324                 for $row->{parent} || ();
325         printf '<caption>%s</caption>', $title;
326         print '<col>' x ($cols + 1);
327         for my $section (qw{thead}) {
328                 print "<$section><tr><th>", $rowdiv == 1 ? '+' : '↱';
329                 printf '<th>%0*X', $coldigits, $_ * $colsize for 0 .. $cols - 1;
330                 print "\n";
331         }
332
333         print '<tbody>';
334         while ($offset <= $row->{endpoint} * $colsize) {
335                 if ($row->{skip}->{$offset}) {
336                         $offset += $cols * $colsize;
337                         next;
338                 }
339
340                 print '<tr><th>';
341                 if (defined $row->{skip}->{$offset}) {
342                         print '⋮';
343                 }
344                 else {
345                         if (my $rowmod = $offset % $rowdiv) {
346                                 # offset in column units
347                                 printf '<small>+%X</small>', $rowmod;
348                         }
349                         else {
350                                 # divided row offset
351                                 printf '%X', ($offset + $row->{offset}) / $rowdiv;
352                         }
353                 }
354                 say '';
355
356                 for (1 .. $cols) {
357                         if ($row->{cell}) {
358                                 print range_cell($row, $offset);
359                                 next;
360                         }
361
362                         my $cp = $offset + $row->{offset};
363                         my $glyph = ref $row->{table} eq 'ARRAY' ? $row->{table}->[$offset] :
364                                 substr $row->{table}, $offset, 1;
365                         my ($cell, $name, $class) = $glyph eq $NOCHAR ? () :
366                                 $glyphs->glyph_html($glyph);
367
368                         if ($mode) {
369                                 state $visible = {};
370                                 $class = (
371                                         $cp == ord $glyph ? 'l4' :
372                                         $row->{parent} && $glyph eq
373                                                 Encode::decode($row->{parent}, pack 'C', $cp) ? 'l3' :
374                                         !$class ? undef :
375                                         $visible->{$glyph} ? 'l2' :
376                                         'l1'
377                                 );
378                                 $visible->{$glyph}++;
379                         }
380
381                         say sprintf $class ? '<td title="%s" class="X %s">%s' : '<td title="%s">',
382                                 $name, $class, $cell;
383                 }
384                 continue {
385                         $offset += $colsize;
386                 }
387         }
388         say '</table></div>';
389 }
390
391 :>
392 <hr>
393
394 <div class="legend">
395         <table class="glyphs"><tr><: if ($mode) { :>
396         <td class="X l4">unicode
397         <td class="X l3">inherited
398         <td class="X l2">existing
399         <td class="X l1">original
400         <td class="">unassigned
401 <: } else { :>
402         <td class="X Cc">control
403         <td class="X Zs"><span>whitespace</span>
404         <td class="X Mn">diacritic<table class="glyphs"><tr>
405                 <td class="X Sk">letter
406                 </table>
407         <td class="X Po">punctuation<table class="glyphs"><tr>
408                 <td class="X Pf">quote
409                 </table>
410         <td class="X So">symbol<table class="glyphs"><tr>
411                 <td class="X Sm">math
412                 <td class="X Sc">currency
413                 </table>
414         <td class="X No">numeric
415         <td class="X Greek">greek<table class="glyphs"><tr>
416                 <td class="X Latin">latin
417                 <td class="X Cyrillic">cyrillic
418                 </table>
419         <td class="X Aramaic">aramaic<table class="glyphs"><tr>
420                 <td class="X Brahmic">brahmic
421                 <td class="X Arabic">arabic
422                 </table>
423         <td class="X Syllabic">syllabic<table class="glyphs"><tr>
424                 <td class="X African">african
425                 <td class="X Hiragana">japanese
426                 <td class="X Han">cjk
427                 <td class="X Bopomofo">chinese
428                 </table>
429         <td class="X Alpha">alphabetic
430         </table>
431
432         <table class="glyphs"><tr>
433         <td class="X">unicode 7.0
434         <td class="X Xr">proposed
435         <td class="X Xd">deprecated
436         <td class="">unassigned
437         <td class="X Xi">invalid
438 <: } :> </table>
439 </div>
440