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