chiark / gitweb /
01ae14584e645a15533bace6d52ce8c20024c8be
[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.  And we tolerate
245         # SIGPIPE in all the input filters.
246         flush $uswrite or die $!;
247
248         my $filterkind = 'input';
249         foreach my $ch (@children) {
250             if ($ch->{Stage} ne 'self') {
251                 kill 9, $ch->{Pid} or die "$ch->{Pid} $ch->{Exe} $!";
252                 $ch->{SigOK}{9} = 1;
253             } else {
254                 $filterkind = 'output';
255                 next;
256             }
257             if ($filterkind eq 'input') {
258                 $ch->{SigOK}{13} = 1;
259             }
260         }
261         # ... we might not have read all the output from pcf2bdf, which is OK
262     }
263
264     close $uswrite or die $!;
265     close $usread or die $!;
266
267     foreach my $ch (@children) {
268         $!=0; waitpid($ch->{Pid}, 0) == $ch->{Pid} or
269             die "$ch->{Pid} $ch->{Exe} $!";
270         $ch->{St} = $?;
271     }
272
273     $after_hook->();
274
275     foreach my $ch (@children) {
276         if (!filter_st_isok($ch)) {
277             die "update-xfonts-traditional:".
278                 " $ch->{Exe} [$ch->{Pid}] for $what".
279                 " failed $ch->{St}".
280                 " (".(join ' ', keys %{ $ch->{SigOK} })." ok)\n";
281         }
282     }
283 }
284
285 sub processpcfgz ($$$$) {
286     my ($inpcfgz,$outpcfgz,$logfh,$what) = @_;
287     print $reportfh "processing $inpcfgz to $outpcfgz\n" if $verbose>=2;
288     my $input = new IO::File $inpcfgz, '<' or die "$inpcfgz $!";
289     my $output = new IO::File $outpcfgz, '>' or die "$outpcfgz $!";
290
291     my $r;
292     process_filter(\$r, $input, $output, $inpcfgz, $logfh,
293         [
294             ['gunzip'], ['pcf2bdf'],
295             [],
296             ['bdftopcf'],['',qw(gzip -1 -n)]
297         ],
298         [qw(gunzip)],
299         # ... we never care if pcf2bdf didn't want all the data
300         sub {
301             if ($tolerate_bad_fonts &&
302                 $r eq 'no bdf data' &&
303                 filter_st_isok($ch{'gunzip'}) &&
304                 ($ch{'pcf2bdf'}{St} & ~128) == 6)
305             {
306                 $r = "pcf2bdf failed ($ch{'pcf2bdf'}{St})";
307                 print STDERR "warning: $r: skipping $inpcfgz\n";
308                 $ch{'pcf2bdf'}{SigOK}{6} = 1;
309             }
310     });
311     return $r;
312 }
313
314 sub processfontdir ($) {
315     my ($fontdir) = @_;
316     if (!opendir FD, $fontdir) {
317         die "$fontdir $!" unless $!==&ENOENT;
318         return;
319     }
320     my $changed = 0;
321     my $olddone;
322     if (!$always_reprocess) {
323         $olddone = do "$fontdir/$donefile";
324         if (!$olddone) {
325             die "$fontdir $! $@ " unless $!==&ENOENT;
326         } elsif ($olddone->{''} ne $foundryinfo) {
327             our $repro_reported;
328             print $reportfh "reprocessing fonts (rules updated)\n" or die $!
329                 unless $repro_reported++;
330             $olddone = undef;
331         }
332     }
333     if (!$olddone) {
334         $olddone = { };
335         $changed = 1;
336     }
337     my $newdone = { '' => $foundryinfo };
338     my %outfiles; # bitmask: 1 /*exists*/ | 2 /*wanted*/
339     my $updated=0;
340     my $reported=0;
341     my $anypcfs=0;
342
343     my $logpath = "$fontdir/$logfile";
344     unlink "$logpath" or $!==&ENOENT or die "$logpath $!";
345     my $logfh = new IO::File $logpath, ">>" or die "$logpath $!";
346
347     if (!$wanted_parallel) {
348         $wanted_parallel = Sys::CPU::cpu_count();
349         printf $reportfh "parallelism: %d\n", $wanted_parallel if $verbose>=2;
350     }
351     $wanted_parallel = 1 if $wanted_parallel < 1;
352
353     our %inprogress;
354
355     my $await = sub {
356         my $child = wait;
357         die $! unless defined $child;
358         my $job = $inprogress{$child};
359         die $child unless $job;
360
361         my $dent = $job->{Dent};
362         my $outdent = $job->{Outdent};
363         my $stats = $job->{Stats};
364         if ($?==0) {
365             $updated++;
366             $outfiles{$outdent} |= 3;
367         } elsif ($?==2*256) {
368         } else {
369             die "update-xfonts-traditional: processing of".
370                 " $fontdir/$dent [$child] failed ($?)\n";
371         }
372         $newdone->{$dent} = $stats;
373         $changed = 1;
374         delete $inprogress{$child};
375     };
376
377     flush $reportfh or die $!;
378     while (my $dent = scalar readdir FD) {
379         if ($dent =~ m/^\Q$fontprefix\E.*\.new$/) {
380             unlink "$fontdir/$dent" or $!==&ENOENT or die "$fontdir $dent $!";
381             next;
382         }
383         next unless $dent =~ m/^[^.\/].*\.pcf\.gz$/;
384         print $reportfh "processing $fontdir...\n" or die $!
385             unless $reported++;
386         if ($dent =~ m/^\Q$fontprefix/) {
387             $outfiles{$dent} |= 1;
388             next;
389         }
390         if (!stat "$fontdir/$dent") {
391             die "$fontdir $dent $!" unless $!==&ENOENT;
392             next;
393         }
394         die "$fontdir $dent" unless -f _;
395         $anypcfs++;
396
397         my $stats = statsummary();
398         my $tdone = $olddone->{$dent};
399         my $outdent = $fontprefix.$dent;
400         if (defined $tdone && $tdone eq $stats) {
401             $outfiles{$outdent} |= 2;
402             $newdone->{$dent} = $stats;
403             next;
404         }
405
406         $await->() while scalar keys %inprogress >= $wanted_parallel;
407
408         my $child = fork;  die unless defined $child;
409         if (!$child) {
410             my $r = processpcfgz("$fontdir/$dent",
411                                  "$fontdir/$outdent.new",
412                                  $logfh, $dent);
413             my $rc;
414             if ($r !~ m/^\d/) {
415                 printf $logfh "%s: unchanged - %s\n", $dent, $r;
416                 unlink "$fontdir/$outdent.new" or die "$fontdir $outdent $!";
417                 $rc = 2;
418             } else {
419                 rename "$fontdir/$outdent.new", "$fontdir/$outdent"
420                     or die "$fontdir $outdent $!";
421                 $rc = 0;
422             }
423             $logfh->flush or die "$logpath $!";
424             exit $rc;
425         }
426         $inprogress{$child} = {
427             Dent => $dent,
428             Outdent => $outdent,
429             Stats => $stats,
430         };
431     }
432     $await->() while scalar keys %inprogress;
433
434     my $affected=0;
435     foreach my $olddent (keys %outfiles) {
436         my $state = $outfiles{$olddent};
437         if ($state & 2) {
438             $affected++ if $state & 1;
439             next;
440         }
441         unlink "$fontdir/$olddent" or die "$fontdir $olddent $!";
442         $changed = 1;
443         $updated++;
444     }
445     if (!stat "$fontdir/fonts.dir") {
446         $!==&ENOENT or die "$fontdir $!";
447     } else {
448         $!=0; $?=0; system 'mkfontdir',$fontdir;
449         die "$fontdir $? $!" if $? or $!;
450     }
451     if (!$anypcfs) {
452         unlink "$logpath" or die "$fontdir $!";
453         unlink "$fontdir/$donefile" or $!==&ENOENT or die "$fontdir $!";
454     } elsif ($changed) {
455         my $newdoneh = new IO::File "$fontdir/$donefile.new", 'w' 
456             or die "$fontdir $!";
457         print $newdoneh Dumper($newdone) or die "$fontdir $!";
458         close $newdoneh or die "$fontdir $!";
459         rename "$fontdir/$donefile.new","$fontdir/$donefile"
460             or die "$fontdir $!";
461     }
462     if ($reported || %$newdone || $affected || $updated) {
463         printf " processed %s: %d pcfs, %d affected, %d updated.\n",
464             $fontdir, (scalar keys %$newdone), $affected, $updated;
465     }
466 }
467
468 sub processfonttree ($) {
469     my ($tree) = @_;
470     find({ follow => 1,
471            dangling_symlinks => 0,
472            no_chdir => 1,
473            wanted => sub {
474                return unless -d _;
475                processfontdir($File::Find::name);
476            }},
477          $tree);
478 }
479
480 our $stdin = new IO::File '<&STDIN' or die $!;
481 our $stdout = new IO::File '>&STDOUT' or die $!;
482 our $stderr = new IO::File '>&STDERR' or die $!;
483 $reportfh = $stdout;
484
485 our (@options)=(
486     'R|rules-include=s@' => \@rulespath,
487     'share-dir=s' => \$sharedir,
488     'verbose|v+' => \$verbose,
489     'j|parallel=i' => \$wanted_parallel,
490     'always-reprocess!' => \$always_reprocess,
491     'tolerate-bad-fonts!' => \$tolerate_bad_fonts,
492     );
493
494 sub define_mode ($$) {
495     my ($optname,$f) = @_;
496     push @options, $optname, sub {
497         die "only one mode may be specified\n" if defined $mode;
498         $mode=$f;
499     };
500 }
501
502 define_mode('bdf-filter', sub {
503     die "no arguments allowed with --bdf-filter\n" if @ARGV;
504     $reportfh = $stderr;
505     loadfoundries();
506     my $r = processbdf($stdin,$stdout,$reportfh,'stdin');
507     if ($r !~ m/^\d/) {
508         print STDERR "stdin not processed: $r\n";
509         exit 2;
510     }
511 });
512
513 define_mode('process-pcf', sub {
514     die "need source and destination pcf.gz\n" if @ARGV!=2;
515     loadfoundries();
516     my $r = processpcfgz($ARGV[0],$ARGV[1],$reportfh,"pcf");
517     if ($r !~ m/^\d/) {
518         print STDERR "pcf not processed: $r\n";
519         exit 2;
520     }
521 });
522
523 define_mode('process-fontdirs', sub {
524     die "need font dir(s)\n" unless @ARGV;
525     loadfoundries();
526     foreach my $d (@ARGV) {
527         processfontdir($d);
528     }
529 });
530
531 define_mode('process-fonttrees', sub {
532     die "need font tree(s)\n" unless @ARGV;
533     loadfoundries();
534     foreach my $d (@ARGV) {
535         processfonttree($d);
536     }
537 });
538
539 define_mode('update', sub {
540     die "no arguments allowed with --postinst\n" unless !@ARGV;
541     loadfoundries();
542     foreach my $d (@fonttrees) {
543         processfonttree($d);
544     }
545 });
546
547 Getopt::Long::Configure(qw(bundling));
548 GetOptions(@options) or exit 127;
549
550 push @rulespath, "$sharedir/rules";
551
552 die "need a mode\n" unless $mode;
553
554 $mode->();