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