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