charset: legacy map ansel (and extensions)
[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.2',
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']) x !$mode,
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 'unicode') {
32         say "Detailed allocation of Unicode blocks.";
33         print "See ", showlink("charsets", '/charset'), " to compare specific encodings";
34 }
35 else {
36
37 if ($tablist[0] eq 'default') {
38         say "Overview of Unicode ", showlink("allocation", '/charset/unicode');
39         say "and common latin code pages.";
40         say "Compare alternate charsets:";
41 }
42 else {
43         say "Charset comparison:";
44 }
45
46 print join " •\n", (
47         map {
48                 join " ·\n", pairmap {
49                         showlink($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                 legacy   => 'legacy',
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 }
73 :>.
74 </p>
75
76 <:
77 use POSIX qw( ceil );
78 use Shiar_Sheet::FormatChar;
79 my $glyphs = Shiar_Sheet::FormatChar->new;
80 my @request;
81
82 my $charsets = do 'charset-encoding.inc.pl'
83         or Alert('Encoding metadata could not be read', $@ || $!);
84
85 sub tabinput {
86         # generate character table(s)
87         my $input = shift or return;
88         my $params = $input =~ s/[+](.*)\z// ? $1 : undef;
89         my $charset = $charsets->{lc $input} || {};
90
91         if (ref $charset ne 'HASH') {
92                 $params and Alert("Parameters ignored for $input",
93                         "Cannot apply <q>$params</q> to multiple charsets.",
94                 );
95                 tabinput($_) for ref $charset ? @{$charset} : $charset;
96                 return;
97         }
98
99         state $visible = {'' => 1};  # all present tables
100         my %row = (offset => 0, cols => 16);
101         $row{$_} = $charset->{$_} for qw( note );  # copy metadata
102
103         if (not defined $params) {
104                 my @parents = @{ $charset->{inherit} || [] };
105
106                 if (my ($parent, $part) = pairfirst { defined $visible->{$a} } @parents) {
107                         $row{parent} = $parent;
108                         $params = $part;
109                         $params = 80 unless $visible->{$parent}
110                                 or ($input eq 'MacCroatian' and defined $visible->{MacRomanian});
111                 }
112                 elsif (defined $visible->{ascii}) {
113                         $row{parent} = $parents[0];
114                         $params = $parents[1] // 80;
115                         $params = 80 if hex $params >= 0x80;  # ascii offset at most
116                 }
117                 elsif (@parents) {
118                         $row{parent} = $parents[0];
119                         $params = $parents[1] if hex $parents[1] == 0;  # apply ascii end
120                 }
121                 $visible->{$_} //= 0 for $row{parent} || ();
122         }
123
124         for my $param (split /[+]+/, $params // '') {
125                 if ($param eq 'realsize') {
126                         $row{realsize}++;
127                 }
128                 elsif ($param =~ m{ \A cols = (\d+) \z }x) {
129                         $row{cols} = $1;
130                 }
131                 elsif ($param =~ m{ \A (?<start> \p{AHex}+) (?: [-] (?<end> \p{AHex}+) )? \z }x) {
132                         if (defined $row{endpoint}) {
133                                 # extend earlier range
134                                 my $skip = int(($row{endpoint} || $row{startpoint}) / $row{cols});
135                                 for ($skip + 1 .. (hex($+{start}) / $row{cols}) - 1) {
136                                         $row{skip}->{ $_ * $row{cols} }++;
137                                 }
138                         }
139                         else {
140                                 $row{startpoint} = hex $+{start};
141                         }
142                         $row{endpoint} = hex($+{end} || 0);
143                 }
144                 else {
145                         Alert("Unknown option <q>$param</q> for charset $input");
146                 }
147         }
148
149         if ($charset->{setup}) {
150                 eval { $charset->{setup}->(\%row) }
151                         or Alert("Incomplete setup of $input", $@);
152         }
153         $row{endpoint} ||= 0xFF;
154
155         if (defined $row{table} or defined $row{cell}) {
156                 $row{set} //= $input;
157         }
158         elsif ($row{set} = Encode::resolve_alias($charset->{set} // $input)) {
159                 $row{offset} = delete $row{startpoint};
160                 if ($charset->{varchar}) {
161                         # array of possibly multiple characters per code point
162                         $row{table} = [
163                                 map { Encode::decode($row{set}, pack 'C*', $_) } $row{offset} .. $row{endpoint}
164                         ];
165                 }
166                 else {
167                         # ~16x faster than decoding in loop;
168                         # substr strings is twice as fast as splitting to an array
169                         $row{table} = Encode::decode($row{set}, pack 'C*', $row{offset} .. $row{endpoint});
170                 }
171
172                 $row{endpoint} -= $row{offset};
173                 $visible->{ascii}++;  # assume common base
174                 $row{set} = $input if $charset->{set};  # base override
175         }
176         else {
177                 Alert("Encoding <q>$input</q> unknown");
178                 return;
179         }
180
181         if (my $replace = $charset->{replace}) {
182                 while (my ($offset, $sub) = each %{$replace}) {
183                         $offset -= $row{offset};
184
185                         if (ref $row{table} eq 'ARRAY') {
186                                 $row{table}->[$offset] = $sub
187                                         if $offset >= 0 and $offset <= $row{endpoint};
188                                 next;
189                         }
190
191                         my $length = length $sub;
192
193                         if ($offset < 0) {
194                                 $offset > -$length or next; # at least one character after start
195                                 # trim leftmost part to start at offset
196                                 substr($sub, 0, -$offset) = '';
197                                 $length += $offset;
198                                 $offset = 0;
199                         }
200
201                         if ((my $excess = $row{endpoint} - $offset - $length + 1) < 0) {
202                                 $excess > -$length or next;
203                                 # trim rightmost part to prevent overflow
204                                 substr($sub, $excess) = '';
205                                 $length += $excess;
206                         }
207
208                         substr($row{table}, $offset, $length) = $sub;
209                 }
210         }
211
212         push @request, \%row;
213         $visible->{ $row{set} } = 1 if $row{table};
214 }
215 tabinput($_) for @tablist;
216
217 my $NOCHAR = chr 0xFFFD;
218
219 sub range_cell {
220         my ($info, $offset) = @_;
221         my $table = $info->{cell} or return;
222         my $def = $table->{$offset} or return;
223         my ($len, $class, $name, $title) = @{$def};
224
225         my $cols = $info->{cols};
226         my $colsize = $table->{colsize} || 1;
227         my $attr = '';
228         $len /= $colsize;
229         $name //= $len <= 2 ? 'res' : 'reserved';
230
231         if (my $part = ($offset/$colsize - $info->{startpoint}) % $cols) {
232                 # continued row
233                 my $rest = $cols - $part;  # remaining
234                 $rest = $len if $len < $rest; #TODO: optimise
235                 if ($len -= $rest) {
236                         # continued on new row
237                         my @next = ($len * $colsize, "$class joinu");
238                         my $separate = $cols - $len > $rest;  # columns not on next row
239                         if ($len > $rest) {
240                                 # minority remains
241                                 push @next, $name, $title;
242                                 $title ||= $name;
243                                 $name = $separate && '…';
244                         }
245                         else {
246                                 # minority on next row
247                                 push @next, $separate && '"', $title || $name;
248                         }
249                         $table->{$offset + $colsize*$rest} //= \@next;
250                         $class .= ' joind';
251                 }
252                 $len = $rest;
253         }
254         elsif (my $rows = int($len / $cols)) {
255                 # multiple full rows
256                 my $rowsize = $colsize * $cols;
257                 if ($len -= $rows * $cols) {
258                         # partial row remains
259                         $table->{$offset + $rowsize * $rows} //= [$len*$colsize, "$class joinu", '', $title];
260                         $class .= ' joind';
261                 }
262
263                 unless ($info->{realsize}) {
264                         # coalesce multiple rows
265                         while ($rows > 3) {
266                                 $info->{skip}->{$offset += $rowsize}++;
267                                 $rows--;
268                         }
269                         if ($rows > 2) {
270                                 $info->{skip}->{$offset += $rowsize} = 0;
271                         }
272                 }
273
274                 $attr .= sprintf ' rowspan=%d', $rows;
275                 $len = $cols;
276         }
277
278         $attr .= sprintf ' colspan=%d', $len unless $len == 1;
279         $attr .= $1 if $class and $class =~ s/( \w+="[^"]*")//;
280         $attr .= sprintf ' class="%s"', $class if $class;
281         $attr .= sprintf ' title="%s"', EscapeHTML($title) if $title;
282         return "<td$attr>$name\n";
283 }
284
285 for my $row (@request) {
286         my $cols = $row->{cols};
287         my $colsize = $row->{cell} && $row->{cell}->{colsize} || 1;
288         my $coldigits = ceil(log($colsize * $cols) / log(16));  # uniform length of hexadecimal header
289         my $rowdiv = 16 ** $coldigits;  # row divide for column digits
290         $rowdiv = 1 if $rowdiv != $cols * $colsize;  # divide only if all columns are matched
291         my $offset = $row->{startpoint} * $colsize || 0;
292
293         printf '<div class="section"><table class="glyphs%s">', !$row->{cell} && ' charmap';
294         my $title = $row->{set};
295         $title .= " <aside>(over $_)</aside>" for $row->{parent} || ();
296         $title .= " <aside>($_)</aside>" for $row->{note} || ();
297         printf '<caption>%s</caption>', $title;
298         print '<col>' x ($cols + 1);
299         for my $section (qw{thead}) {
300                 print "<$section><tr><th>", $rowdiv == 1 ? '+' : '↱';
301                 printf '<th>%0*X', $coldigits, $_ * $colsize for 0 .. $cols - 1;
302                 print "\n";
303         }
304
305         print '<tbody>';
306         while ($offset <= $row->{endpoint} * $colsize) {
307                 if ($row->{skip}->{$offset + $row->{offset}}) {
308                         $offset += $cols * $colsize;
309                         next;
310                 }
311
312                 print '<tr><th>';
313                 if (defined $row->{skip}->{$offset + $row->{offset}}) {
314                         print '⋮';
315                 }
316                 else {
317                         if (my $rowmod = $offset % $rowdiv) {
318                                 # offset in column units
319                                 printf '<small>+%X</small>', $rowmod;
320                         }
321                         else {
322                                 # divided row offset
323                                 printf '%X', ($offset + $row->{offset}) / $rowdiv;
324                         }
325                 }
326                 say '';
327
328                 for (1 .. $cols) {
329                         if ($row->{cell}) {
330                                 print range_cell($row, $offset);
331                                 next;
332                         }
333
334                         my $cp = $offset + $row->{offset};
335                         my $glyph = ref $row->{table} eq 'ARRAY' ? $row->{table}->[$offset] :
336                                 substr $row->{table}, $offset, 1;
337                         my ($cell, $name, $class) = !defined $glyph || $glyph eq $NOCHAR ? () :
338                                 $glyphs->glyph_html($glyph);
339
340                         if ($mode) {
341                                 state $visible = {};
342                                 $class = (
343                                         $cp == ord $glyph ? 'l4' :
344                                         $row->{parent} && $glyph eq
345                                                 Encode::decode($row->{parent}, pack 'C', $cp) ? 'l3' :
346                                         !defined $cell ? undef :
347                                         $visible->{$glyph} ? 'l2' :
348                                         'l1'
349                                 );
350                                 $visible->{$glyph}++;
351                         }
352
353                         printf '<td title="%s"', $name;
354                         say $class ? sprintf(' class="X %s">%s', $class, $cell) : '>';
355                 }
356                 continue {
357                         $offset += $colsize;
358                 }
359         }
360         say '</table></div>';
361 }
362
363 :>
364 <hr>
365
366 <div class="legend">
367         <table class="glyphs"><tr><: if ($mode) { :>
368         <td class="X l4">unicode
369         <td class="X l3">inherited
370         <td class="X l2">existing
371         <td class="X l1">original
372         <td class="">unassigned
373 <: } else { :>
374         <td class="X Cc">control
375         <td class="X Zs"><span>whitespace</span>
376         <td class="X Mn">diacritic<table class="glyphs"><tr>
377                 <td class="X Sk">letter
378                 </table>
379         <td class="X Po">punctuation<table class="glyphs"><tr>
380                 <td class="X Pf">quote
381                 </table>
382         <td class="X So">symbol<table class="glyphs"><tr>
383                 <td class="X Sm">math
384                 <td class="X Sc">currency
385                 </table>
386         <td class="X No">numeric
387         <td class="X Greek">greek<table class="glyphs"><tr>
388                 <td class="X Latin">latin
389                 <td class="X Cyrillic">cyrillic
390                 </table>
391         <td class="X Aramaic">aramaic<table class="glyphs"><tr>
392                 <td class="X Brahmic">brahmic
393                 <td class="X Arabic">arabic
394                 </table>
395         <td class="X Syllabic">syllabic<table class="glyphs"><tr>
396                 <td class="X African">african
397                 <td class="X Hiragana">japanese
398                 <td class="X Han">cjk
399                 <td class="X Bopomofo">chinese
400                 </table>
401         <td class="X Alpha">alphabetic
402         </table>
403
404         <table class="glyphs"><tr>
405         <td class="X">unicode 10.0
406         <td class="X Xr">proposed
407         <td class="X Xd">deprecated
408         <td class="">unassigned
409         <td class="X Xi">invalid
410 <: } :> </table>
411 </div>
412