6300622f3ea16088b40c6aee93c63a96f93ec1b2
[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 ($charset->{setup}) {
147                 eval { $charset->{setup}->(\%row) }
148                         or Alert("Incomplete setup of $input", $@);
149         }
150         $row{endpoint} ||= 0xFF;
151
152         if ($row{set}) {}
153         elsif ($row{set} = Encode::resolve_alias($input)) {
154                 $row{offset} = delete $row{startpoint};
155                 if ($row{set} eq 'MacHebrew' or $row{set} eq 'MacThai') {
156                         # array of possibly multiple characters per code point
157                         $row{table} = [
158                                 map { Encode::decode($row{set}, pack 'C*', $_) } $row{offset} .. $row{endpoint}
159                         ];
160                 }
161                 else {
162                         # ~16x faster than decoding in loop;
163                         # substr strings is twice as fast as splitting to an array
164                         $row{table} = Encode::decode($row{set}, pack 'C*', $row{offset} .. $row{endpoint});
165                 }
166
167                 $row{endpoint} -= $row{offset};
168
169                 $visible->{ascii} =  # assume common base
170                 $visible->{ $row{set} } = 1;
171         }
172         else {
173                 Alert("Encoding <q>$input</q> unknown");
174                 return;
175         }
176
177         if (my $replace = $charset->{replace}) {
178                 while (my ($offset, $sub) = each %{$replace}) {
179                         $offset -= $row{offset};
180
181                         if (ref $row{table} eq 'ARRAY') {
182                                 $row{table}->[$offset] = $sub
183                                         if $offset >= 0 and $offset <= $row{endpoint};
184                                 next;
185                         }
186
187                         my $length = length $sub;
188
189                         if ($offset < 0) {
190                                 $offset > -$length or next; # at least one character after start
191                                 # trim leftmost part to start at offset
192                                 substr($sub, 0, -$offset) = '';
193                                 $length += $offset;
194                                 $offset = 0;
195                         }
196
197                         if ((my $excess = $row{endpoint} - $offset - $length + 1) < 0) {
198                                 $excess > -$length or next;
199                                 # trim rightmost part to prevent overflow
200                                 substr($sub, $excess) = '';
201                                 $length += $excess;
202                         }
203
204                         substr($row{table}, $offset, $length) = $sub;
205                 }
206         }
207
208         push @request, \%row;
209 }
210 tabinput($_) for @tablist;
211
212 my $NOCHAR = chr 0xFFFD;
213
214 sub range_cell {
215         my ($info, $offset) = @_;
216         my $table = $info->{cell} or return;
217         my $def = $table->{$offset} or return;
218         my ($len, $class, $name, $title) = @{$def};
219
220         my $cols = $info->{cols};
221         my $colsize = $table->{colsize} || 1;
222         my $attr = '';
223         $len /= $colsize;
224         $name //= $len <= 2 ? 'res' : 'reserved';
225
226         if (my $part = ($offset/$colsize - $info->{startpoint}) % $cols) {
227                 # continued row
228                 my $rest = $cols - $part;  # remaining
229                 $rest = $len if $len < $rest; #TODO: optimise
230                 if ($len -= $rest) {
231                         # continued on new row
232                         my @next = ($len * $colsize, "$class joinu");
233                         my $separate = $cols - $len > $rest;  # columns not on next row
234                         if ($len > $rest) {
235                                 # minority remains
236                                 push @next, $name, $title;
237                                 $title ||= $name;
238                                 $name = $separate && '…';
239                         }
240                         else {
241                                 # minority on next row
242                                 push @next, $separate && '"', $title || $name;
243                         }
244                         $table->{$offset + $colsize*$rest} //= \@next;
245                         $class .= ' joind';
246                 }
247                 $len = $rest;
248         }
249         elsif (my $rows = int($len / $cols)) {
250                 # multiple full rows
251                 my $rowsize = $colsize * $cols;
252                 if ($len -= $rows * $cols) {
253                         # partial row remains
254                         $table->{$offset + $rowsize * $rows} //= [$len*$colsize, "$class joinu", '', $title];
255                         $class .= ' joind';
256                 }
257
258                 unless ($info->{realsize}) {
259                         # coalesce multiple rows
260                         while ($rows > 3) {
261                                 $info->{skip}->{$offset += $rowsize}++;
262                                 $rows--;
263                         }
264                         if ($rows > 2) {
265                                 $info->{skip}->{$offset += $rowsize} = 0;
266                         }
267                 }
268
269                 $attr .= sprintf ' rowspan=%d', $rows;
270                 $len = $cols;
271         }
272
273         $attr .= sprintf ' colspan=%d', $len unless $len == 1;
274         $attr .= $1 if $class and $class =~ s/( \w+="[^"]*")//;
275         $attr .= sprintf ' class="%s"', $class if $class;
276         $attr .= sprintf ' title="%s"', EscapeHTML($title) if $title;
277         return "<td$attr>$name\n";
278 }
279
280 for my $row (@request) {
281         my $cols = $row->{cols};
282         my $colsize = $row->{cell} && $row->{cell}->{colsize} || 1;
283         my $coldigits = ceil(log($colsize * $cols) / log(16));  # uniform length of hexadecimal header
284         my $rowdiv = 16 ** $coldigits;  # row divide for column digits
285         $rowdiv = 1 if $rowdiv != $cols * $colsize;  # divide only if all columns are matched
286         my $offset = $row->{startpoint} * $colsize || 0;
287
288         printf '<div class="section"><table class="glyphs%s">', !$row->{cell} && ' charmap';
289         my $title = $row->{set};
290         $title .= " <aside>(over $_)</aside>"
291                 for $row->{parent} || ();
292         printf '<caption>%s</caption>', $title;
293         print '<col>' x ($cols + 1);
294         for my $section (qw{thead}) {
295                 print "<$section><tr><th>", $rowdiv == 1 ? '+' : '↱';
296                 printf '<th>%0*X', $coldigits, $_ * $colsize for 0 .. $cols - 1;
297                 print "\n";
298         }
299
300         print '<tbody>';
301         while ($offset <= $row->{endpoint} * $colsize) {
302                 if ($row->{skip}->{$offset}) {
303                         $offset += $cols * $colsize;
304                         next;
305                 }
306
307                 print '<tr><th>';
308                 if (defined $row->{skip}->{$offset}) {
309                         print '⋮';
310                 }
311                 else {
312                         if (my $rowmod = $offset % $rowdiv) {
313                                 # offset in column units
314                                 printf '<small>+%X</small>', $rowmod;
315                         }
316                         else {
317                                 # divided row offset
318                                 printf '%X', ($offset + $row->{offset}) / $rowdiv;
319                         }
320                 }
321                 say '';
322
323                 for (1 .. $cols) {
324                         if ($row->{cell}) {
325                                 print range_cell($row, $offset);
326                                 next;
327                         }
328
329                         my $cp = $offset + $row->{offset};
330                         my $glyph = ref $row->{table} eq 'ARRAY' ? $row->{table}->[$offset] :
331                                 substr $row->{table}, $offset, 1;
332                         my ($cell, $name, $class) = $glyph eq $NOCHAR ? () :
333                                 $glyphs->glyph_html($glyph);
334
335                         if ($mode) {
336                                 state $visible = {};
337                                 $class = (
338                                         $cp == ord $glyph ? 'l4' :
339                                         $row->{parent} && $glyph eq
340                                                 Encode::decode($row->{parent}, pack 'C', $cp) ? 'l3' :
341                                         !$class ? undef :
342                                         $visible->{$glyph} ? 'l2' :
343                                         'l1'
344                                 );
345                                 $visible->{$glyph}++;
346                         }
347
348                         say sprintf $class ? '<td title="%s" class="X %s">%s' : '<td title="%s">',
349                                 $name, $class, $cell;
350                 }
351                 continue {
352                         $offset += $colsize;
353                 }
354         }
355         say '</table></div>';
356 }
357
358 :>
359 <hr>
360
361 <div class="legend">
362         <table class="glyphs"><tr><: if ($mode) { :>
363         <td class="X l4">unicode
364         <td class="X l3">inherited
365         <td class="X l2">existing
366         <td class="X l1">original
367         <td class="">unassigned
368 <: } else { :>
369         <td class="X Cc">control
370         <td class="X Zs"><span>whitespace</span>
371         <td class="X Mn">diacritic<table class="glyphs"><tr>
372                 <td class="X Sk">letter
373                 </table>
374         <td class="X Po">punctuation<table class="glyphs"><tr>
375                 <td class="X Pf">quote
376                 </table>
377         <td class="X So">symbol<table class="glyphs"><tr>
378                 <td class="X Sm">math
379                 <td class="X Sc">currency
380                 </table>
381         <td class="X No">numeric
382         <td class="X Greek">greek<table class="glyphs"><tr>
383                 <td class="X Latin">latin
384                 <td class="X Cyrillic">cyrillic
385                 </table>
386         <td class="X Aramaic">aramaic<table class="glyphs"><tr>
387                 <td class="X Brahmic">brahmic
388                 <td class="X Arabic">arabic
389                 </table>
390         <td class="X Syllabic">syllabic<table class="glyphs"><tr>
391                 <td class="X African">african
392                 <td class="X Hiragana">japanese
393                 <td class="X Han">cjk
394                 <td class="X Bopomofo">chinese
395                 </table>
396         <td class="X Alpha">alphabetic
397         </table>
398
399         <table class="glyphs"><tr>
400         <td class="X">unicode 7.0
401         <td class="X Xr">proposed
402         <td class="X Xd">deprecated
403         <td class="">unassigned
404         <td class="X Xi">invalid
405 <: } :> </table>
406 </div>
407