chiark / gitweb /
8dccad424924f88c36c012ceab5cc6a69a72cc14
[xfonts-traditional.git] / update-xfonts-traditional
1 #!/usr/bin/perl -w
2 use strict;
3 use POSIX;
4 use IO::File;
5 use Getopt::Long;
6 use File::Glob qw(:glob);
7 use Data::Dumper;
8 use IO::Pipe;
9 use File::Find;
10 use Sys::CPU;
11
12 our $prefix="/usr/local";
13 our $package='xfonts-traditional';
14 our $sharedir="$prefix/share/$package";
15 our @fonttrees=qw(/usr/share/fonts/X11 /usr/local/share/fonts/X11);
16 our $donefile="$package.done";
17 our $logfile="$package.log";
18 our $fontprefix="trad--";
19 our @rulespath;
20 our $mode;
21 our %foundrymap;
22 our $verbose=0;
23 our $reportfh;
24 our $foundryinfo;
25 our %props;
26 our $tolerate_bad_fonts=1;
27 our $always_reprocess;
28 our $wanted_parallel;
29
30 sub reportloaded {
31     return unless $verbose;
32     print $reportfh @_,"\n" or die $!;
33 }
34
35 sub statsummary () {
36     return join ' ', ((stat _)[1,7,9,10]);
37 }
38
39 sub loadrules ($) {
40     my ($key) = @_;
41     our %cache;
42     my $fc=$cache{$key};  
43     return $fc if $fc;
44     foreach my $path (@rulespath) {
45         my $script="$path/$key.rules";
46         $!=0; $@=''; my $f = do $script;
47         if (defined $f) {
48             reportloaded("rules: loaded ",$script);
49             $cache{$key}=$f;
50             return $f;
51         }
52         die "$! $? $script" unless $! == &ENOENT;
53     }
54     return $cache{$key}=undef;
55 }
56
57 sub processbdf ($$$$) {
58     my ($inbdf,$outbdf,$logfh,$what) = @_;
59     my $state='idle';
60     my ($foundry,$font);
61     my ($w,$h,$xo,$yo,$y,$bitmap,$glyph);
62     my $modified=0;
63     %props = ();
64     my $anyinput=0;
65     while (<$inbdf>) {
66         $anyinput=1;
67         if ($state eq 'bitmap' && $y==$h) {
68             $glyph = uc $glyph;
69             $glyph =~ s/\;$//;
70             local ($_) = $glyph;
71             my $key= sprintf "%s,%d,%d,%d,%d", $foundry,$w,$h,$xo,$yo;
72             my $rules= loadrules($key);
73             return 'no rules' if !$rules;
74             $rules->();
75             $modified += ($_ ne $glyph);
76             print $outbdf $_,"\n" or die $!
77                 foreach split /\;/, $_; # /;
78             $state='idle';
79         }
80         if ($state eq 'bitmap') {
81             m/^([0-9a-fA-F]+)\s+$/ or die $y;
82             length($1) == (($w+7 >> 3) << 1) or die "$1 $w";
83             $glyph .= "$1;";
84             $y++;
85             next;
86         }
87         if ($state eq 'idle' && m/^FOUNDRY\s+/) {
88             die if defined $foundry;
89             return 'foundry syntax' unless m/^FOUNDRY\s+\"(\w+)\"\s+/;
90             $foundry = $foundrymap{lc $1};
91             return 'no foundry' unless defined $foundry;
92             $_ = "FOUNDRY \"$foundry\"\n";
93         }
94         if ($state eq 'idle' && m/^FONT\s+/) {
95             die if defined $font;
96             return 'simple font name' unless m/^(FONT\s+)\-(\w+)\-/;
97             $font = $foundrymap{lc $2};
98             return 'no foundry' unless defined $font;
99             $_ = "FONT -$font-$'";
100         }
101         if ($state eq 'idle' && m/^STARTCHAR\s/) {
102             die unless defined $foundry;
103             die unless defined $font;
104             return 'foundry != font' unless $foundry eq $font;
105             $state='startchar';
106             $w=undef;
107         }
108         if (($state eq 'idle' || $state eq 'startchar') &&
109             m/^([A-Z_]+)\s+(.*\S)\s+$/) {
110             $props{$1}=$2;
111         }
112         if ($state eq 'startchar') {
113             if (m/^BBX\s+(\+?\d+)\s+(\+?\d+)\s+([-+]?\d+)\s+([-+]?\d+)\s+$/) {
114                 ($w,$h,$xo,$yo) = ($1,$2,$3,$4);
115             }
116             if (m/^BITMAP\s+$/) {
117                 die unless defined $w;
118                 $y=0;
119                 $glyph='';
120                 $state='bitmap';
121                 $props{' 7bit'}=
122                     ($props{'CHARSET_REGISTRY'} =~ m/iso8859|utf|iso10646/i &&
123                      $props{'ENCODING'} <= 127);
124             }
125         }
126         print $outbdf $_ or die $!;
127     }
128     die $! if $inbdf->error;
129     die $! if $outbdf->error or !$outbdf->flush;
130     die unless $state eq 'idle';
131     return 'no bdf data' # also special cased in processpcfgz
132         if !$anyinput;
133     if ($modified) {
134         printf $logfh "%s: %d glyphs changed\n", $what, $modified
135             or die $!;
136     } else {
137         printf $logfh "%s: unchanged - no rules matched\n", $what
138             or die $!;
139     }
140     return $modified;
141 }
142
143 sub loadfoundries () {
144     $foundryinfo = '';
145     foreach my $path (@rulespath) {
146         if (!stat $path) {
147             die "$path $!" unless $!==&ENOENT;
148             next;
149         }
150         $foundryinfo .= statsummary().' '.$path."\0\n";
151
152         my $p = "$path/foundries";
153         my $f = new IO::File $p;
154         if (!$f) {
155             die "$p $!" unless $!==&ENOENT;
156             print $reportfh "foundries: none in $p\n" or die $! if $verbose;
157             next;
158         }
159         stat $f or die $!;
160         while (<$f>) {
161             s/^\s*//; s/\s+$//;
162             next if m/^\#/;
163             m/^([.0-9A-Za-z]+)\s+([.0-9A-Za-z]+)$/ or die;
164             my $k = lc $1;
165             next if exists $foundrymap{$k};
166             $foundrymap{$k}=$2;
167         }
168         $f->error and die $!;
169         reportloaded('foundries: loaded ',$p);
170     }
171     die "no foundry maps\n" unless %foundrymap;
172 }
173
174 our %ch;
175
176 sub filter_st_isok ($) {
177     my ($ch) = @_;
178     my $st = $ch->{St};
179     return !$st || $ch->{SigOK}{($st & ~128)};
180 }
181
182 sub process_filter ($$$$$$$$) {
183     my ($rr, $input, $output,$what,$logfh,
184         $procs, $sigpipeok, $after_hook) = @_;
185     my ($reader,$writer);
186     my @children;
187     my ($usread,$uswrite);
188
189     my $current = $input;
190
191     foreach my $proc (@$procs) {
192         my $isfinal = (@$proc && $proc->[0] eq '');
193         if (!$isfinal) {
194             $reader = new IO::Handle or die $!;
195             $writer = new IO::Handle or die $!;
196             new IO::Pipe($reader,$writer) or die $!;
197         } else {
198             shift @$proc;
199             $reader = undef;
200             $writer = $output;
201         }
202         if (@$proc) {
203             my $exe = $proc->[0];
204             my $child = fork;  defined $child or die $!;
205             if (!$child) {
206                 open STDIN, '<&', $current or die $!;
207                 open STDOUT, '>&', $writer or die $!;
208                 if (!$isfinal) {
209                     close $reader or die $!;
210                 }
211                 close $usread or die $! if $usread;
212                 close $uswrite or die $! if $uswrite;
213                 exec $exe @$proc or die "$exe $!";
214             }
215             my $ch = {
216                 Pid => $child,
217                 Exe => $exe,
218                 Stage => (!$exe ? 'self' : defined $usread ? 'out' : 'in'),
219                 SigOK => { },
220             };
221             push @children, $ch;
222             $ch{$exe} = $ch;
223             close $current or die $!;
224             close $writer or die $!;
225             $current = $reader;
226         } else {
227             $usread = $current;
228             $uswrite = $writer;
229             $current = $reader;
230         }
231     }
232     $$rr = processbdf($usread,$uswrite,$logfh,$what);
233     my $none = $$rr !~ m/^\d/;
234
235     $ch{$_}{SigOK}{13} = 1 foreach @$sigpipeok;
236
237     if ($none || !$$rr) {
238         # We're not going to install or use this so we can kill our
239         # input and output filters.  We kill the input filters so that
240         # we don't risk waiting for them.  (If the input filter died
241         # for some other reason then sending it a KILL now won't
242         # affect its exit status.)  We kill the output filters (before
243         # we close the output pipe) so we don't produce messages from
244         # our output filters about corrupted data.
245         flush $uswrite or die $!;
246
247         foreach my $ch (@children) {
248             if ($ch->{Stage} ne 'self') {
249                 kill 9, $ch->{Pid} or die "$ch->{Pid} $ch->{Exe} $!";
250                 $ch->{SigOK}{9} = 1;
251             }
252         }
253         $ch{'pcf2bdf'}{SigOK}{13} = 1;
254         # ... we might not have read all the output from pcf2bdf, which is OK
255     }
256
257     close $uswrite or die $!;
258     close $usread or die $!;
259
260     foreach my $ch (@children) {
261         $!=0; waitpid($ch->{Pid}, 0) == $ch->{Pid} or
262             die "$ch->{Pid} $ch->{Exe} $!";
263         $ch->{St} = $?;
264     }
265
266     $after_hook->();
267
268     foreach my $ch (@children) {
269         if (!filter_st_isok($ch)) {
270             die "update-xfonts-traditional:".
271                 " $ch->{Exe} [$ch->{Pid}] for $what".
272                 " failed $ch->{St}".
273                 " (".(join ' ', keys %{ $ch->{SigOK} })." ok)\n";
274         }
275     }
276 }
277
278 sub processpcfgz ($$$$) {
279     my ($inpcfgz,$outpcfgz,$logfh,$what) = @_;
280     print $reportfh "processing $inpcfgz to $outpcfgz\n" if $verbose>=2;
281     my $input = new IO::File $inpcfgz, '<' or die "$inpcfgz $!";
282     my $output = new IO::File $outpcfgz, '>' or die "$outpcfgz $!";
283
284     my $r;
285     process_filter(\$r, $input, $output, $inpcfgz, $logfh,
286         [
287             ['gunzip'], ['pcf2bdf'],
288             [],
289             ['bdftopcf'],['',qw(gzip -1 -n)]
290         ],
291         [qw(gunzip)],
292         # ... we never care if pcf2bdf didn't want all the data
293         sub {
294             if ($tolerate_bad_fonts &&
295                 $r eq 'no bdf data' &&
296                 filter_st_isok($ch{'gunzip'}) &&
297                 ($ch{'pcf2bdf'}{St} & ~128) == 6)
298             {
299                 $r = "pcf2bdf failed ($ch{'pcf2bdf'}{St})";
300                 print STDERR "warning: $r: skipping $inpcfgz\n";
301                 $ch{'pcf2bdf'}{SigOK}{6} = 1;
302             }
303     });
304     return $r;
305 }
306
307 sub processfontdir ($) {
308     my ($fontdir) = @_;
309     if (!opendir FD, $fontdir) {
310         die "$fontdir $!" unless $!==&ENOENT;
311         return;
312     }
313     my $changed = 0;
314     my $olddone;
315     if (!$always_reprocess) {
316         $olddone = do "$fontdir/$donefile";
317         if (!$olddone) {
318             die "$fontdir $! $@ " unless $!==&ENOENT;
319         } elsif ($olddone->{''} ne $foundryinfo) {
320             our $repro_reported;
321             print $reportfh "reprocessing fonts (rules updated)\n" or die $!
322                 unless $repro_reported++;
323             $olddone = undef;
324         }
325     }
326     if (!$olddone) {
327         $olddone = { };
328         $changed = 1;
329     }
330     my $newdone = { '' => $foundryinfo };
331     my %outfiles; # bitmask: 1 /*exists*/ | 2 /*wanted*/
332     my $updated=0;
333     my $reported=0;
334     my $anypcfs=0;
335
336     my $logpath = "$fontdir/$logfile";
337     unlink "$logpath" or $!==&ENOENT or die "$logpath $!";
338     my $logfh = new IO::File $logpath, ">>" or die "$logpath $!";
339
340     if (!$wanted_parallel) {
341         $wanted_parallel = Sys::CPU::cpu_count();
342         printf $reportfh "parallelism: %d\n", $wanted_parallel if $verbose>=2;
343     }
344     $wanted_parallel = 1 if $wanted_parallel < 1;
345
346     our %inprogress;
347
348     my $await = sub {
349         my $child = wait;
350         die $! unless defined $child;
351         my $job = $inprogress{$child};
352         die $child unless $job;
353
354         my $dent = $job->{Dent};
355         my $outdent = $job->{Outdent};
356         my $stats = $job->{Stats};
357         if ($?==0) {
358             $updated++;
359             $outfiles{$outdent} |= 3;
360         } elsif ($?==2*256) {
361         } else {
362             die "update-xfonts-traditional: processing of".
363                 " $fontdir/$dent [$child] failed ($?)\n";
364         }
365         $newdone->{$dent} = $stats;
366         $changed = 1;
367         delete $inprogress{$child};
368     };
369
370     flush $reportfh or die $!;
371     while (my $dent = scalar readdir FD) {
372         if ($dent =~ m/^\Q$fontprefix\E.*\.new$/) {
373             unlink "$fontdir/$dent" or $!==&ENOENT or die "$fontdir $dent $!";
374             next;
375         }
376         next unless $dent =~ m/^[^.\/].*\.pcf\.gz$/;
377         print $reportfh "processing $fontdir...\n" or die $!
378             unless $reported++;
379         if ($dent =~ m/^\Q$fontprefix/) {
380             $outfiles{$dent} |= 1;
381             next;
382         }
383         if (!stat "$fontdir/$dent") {
384             die "$fontdir $dent $!" unless $!==&ENOENT;
385             next;
386         }
387         die "$fontdir $dent" unless -f _;
388         $anypcfs++;
389
390         my $stats = statsummary();
391         my $tdone = $olddone->{$dent};
392         my $outdent = $fontprefix.$dent;
393         if (defined $tdone && $tdone eq $stats) {
394             $outfiles{$outdent} |= 2;
395             $newdone->{$dent} = $stats;
396             next;
397         }
398
399         $await->() while scalar keys %inprogress >= $wanted_parallel;
400
401         my $child = fork;  die unless defined $child;
402         if (!$child) {
403             my $r = processpcfgz("$fontdir/$dent",
404                                  "$fontdir/$outdent.new",
405                                  $logfh, $dent);
406             my $rc;
407             if ($r !~ m/^\d/) {
408                 printf $logfh "%s: unchanged - %s\n", $dent, $r;
409                 unlink "$fontdir/$outdent.new" or die "$fontdir $outdent $!";
410                 $rc = 2;
411             } else {
412                 rename "$fontdir/$outdent.new", "$fontdir/$outdent"
413                     or die "$fontdir $outdent $!";
414                 $rc = 0;
415             }
416             $logfh->flush or die "$logpath $!";
417             exit $rc;
418         }
419         $inprogress{$child} = {
420             Dent => $dent,
421             Outdent => $outdent,
422             Stats => $stats,
423         };
424     }
425     $await->() while scalar keys %inprogress;
426
427     my $affected=0;
428     foreach my $olddent (keys %outfiles) {
429         my $state = $outfiles{$olddent};
430         if ($state & 2) {
431             $affected++ if $state & 1;
432             next;
433         }
434         unlink "$fontdir/$olddent" or die "$fontdir $olddent $!";
435         $changed = 1;
436         $updated++;
437     }
438     if (!stat "$fontdir/fonts.dir") {
439         $!==&ENOENT or die "$fontdir $!";
440     } else {
441         $!=0; $?=0; system 'mkfontdir',$fontdir;
442         die "$fontdir $? $!" if $? or $!;
443     }
444     if (!$anypcfs) {
445         unlink "$logpath" or die "$fontdir $!";
446         unlink "$fontdir/$donefile" or $!==&ENOENT or die "$fontdir $!";
447     } elsif ($changed) {
448         my $newdoneh = new IO::File "$fontdir/$donefile.new", 'w' 
449             or die "$fontdir $!";
450         print $newdoneh Dumper($newdone) or die "$fontdir $!";
451         close $newdoneh or die "$fontdir $!";
452         rename "$fontdir/$donefile.new","$fontdir/$donefile"
453             or die "$fontdir $!";
454     }
455     if ($reported || %$newdone || $affected || $updated) {
456         printf " processed %s: %d pcfs, %d affected, %d updated.\n",
457             $fontdir, (scalar keys %$newdone), $affected, $updated;
458     }
459 }
460
461 sub processfonttree ($) {
462     my ($tree) = @_;
463     find({ follow => 1,
464            dangling_symlinks => 0,
465            no_chdir => 1,
466            wanted => sub {
467                return unless -d _;
468                processfontdir($File::Find::name);
469            }},
470          $tree);
471 }
472
473 our $stdin = new IO::File '<&STDIN' or die $!;
474 our $stdout = new IO::File '>&STDOUT' or die $!;
475 our $stderr = new IO::File '>&STDERR' or die $!;
476 $reportfh = $stdout;
477
478 our (@options)=(
479     'R|rules-include=s@' => \@rulespath,
480     'share-dir=s' => \$sharedir,
481     'verbose|v+' => \$verbose,
482     'j|parallel=i' => \$wanted_parallel,
483     'always-reprocess!' => \$always_reprocess,
484     'tolerate-bad-fonts!' => \$tolerate_bad_fonts,
485     );
486
487 sub define_mode ($$) {
488     my ($optname,$f) = @_;
489     push @options, $optname, sub {
490         die "only one mode may be specified\n" if defined $mode;
491         $mode=$f;
492     };
493 }
494
495 define_mode('bdf-filter', sub {
496     die "no arguments allowed with --bdf-filter\n" if @ARGV;
497     $reportfh = $stderr;
498     loadfoundries();
499     my $r = processbdf($stdin,$stdout,$reportfh,'stdin');
500     if ($r !~ m/^\d/) {
501         print STDERR "stdin not processed: $r\n";
502         exit 2;
503     }
504 });
505
506 define_mode('process-pcf', sub {
507     die "need source and destination pcf.gz\n" if @ARGV!=2;
508     loadfoundries();
509     my $r = processpcfgz($ARGV[0],$ARGV[1],$reportfh,"pcf");
510     if ($r !~ m/^\d/) {
511         print STDERR "pcf not processed: $r\n";
512         exit 2;
513     }
514 });
515
516 define_mode('process-fontdirs', sub {
517     die "need font dir(s)\n" unless @ARGV;
518     loadfoundries();
519     foreach my $d (@ARGV) {
520         processfontdir($d);
521     }
522 });
523
524 define_mode('process-fonttrees', sub {
525     die "need font tree(s)\n" unless @ARGV;
526     loadfoundries();
527     foreach my $d (@ARGV) {
528         processfonttree($d);
529     }
530 });
531
532 define_mode('update', sub {
533     die "no arguments allowed with --postinst\n" unless !@ARGV;
534     loadfoundries();
535     foreach my $d (@fonttrees) {
536         processfonttree($d);
537     }
538 });
539
540 Getopt::Long::Configure(qw(bundling));
541 GetOptions(@options) or exit 127;
542
543 push @rulespath, "$sharedir/rules";
544
545 die "need a mode\n" unless $mode;
546
547 $mode->();