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