summaryrefslogtreecommitdiff
path: root/Master/texmf-dist/scripts/fontools/afm2afm
blob: 87d6ef1bbb4991d4dab7f06331f010c30c9a4bc7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
#! /usr/bin/env perl

=begin COPYRIGHT

----------------------------------------------------------------------------

    Copyright (C) 2005-2012 Marc Penninga.

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    as published by the Free Software Foundation, either version 2
    of the License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to
        Free Software Foundation, Inc.,
        59 Temple Place,
        Suite 330,
        Boston, MA 02111-1307,
        USA

----------------------------------------------------------------------------

=end COPYRIGHT

=cut

use strict;
use warnings;

use File::Basename;
use Getopt::Long;
use Pod::Usage;

use v5.10;

parse_commandline();

my $afm = read_afm($ARGV[0]);

# If user specified encoding, use that; else, use encoding from .afm file
my $enc = $ARGV{encoding} ? read_enc($ARGV{encoding})
        :                   get_enc($afm)
        ;
# Make lookup table to quickly see if a character is present in the encoding
my %char_in_enc = map { ($_ => 1) } @{$enc->{vector}};

print_fontinfo($afm->{fontinfo}, $enc->{scheme});
print_charmetrics($afm->{metrics}, $enc->{vector});
print_kerndata($afm->{kernpairs}, $afm->{trackkerns}, \%char_in_enc);
print_composites($afm->{composites}, \%char_in_enc);
print "EndFontMetrics\n";

close select *STDOUT if $ARGV{output};

print_mapentry($afm->{fontinfo}, , $enc->{scheme})
    if $ARGV{encoding} && $ARGV{output};

#-----------------------------------------------------------------------
#
#-----------------------------------------------------------------------
sub parse_commandline {
    Getopt::Long::GetOptions(
        'help|?'     => sub { pod2usage(-verbose => 1) },
        'encoding=s' => \$ARGV{encoding},
        'output=s'   => \$ARGV{output},
    )
    or pod2usage(-verbose => 0);

    pod2usage(-verbose => 0) if @ARGV != 1;

    if ($ARGV{output}) {
        $ARGV{output} .= '.afm' unless $ARGV{output} =~ m/[.]afm\z/xms;
        open my $output, '>', $ARGV{output}
            or die "[ERROR] can't open '$ARGV{output}': $!";
        select $output;
    }

    return;
}

#-----------------------------------------------------------------------
#
#-----------------------------------------------------------------------
sub read_afm {
    my $filename = shift;
    open my $afmfile, '<', $filename
        or die "[ERROR] can't open '$filename': $!";

    my %afm = (
        fontinfo   => [],
        metrics    => [],
        kernpairs  => [],
        trackkerns => [],
        composites => [],
    );

    until ((my $line = <$afmfile>) =~ m/StartCharMetrics/xms) {
        push @{$afm{fontinfo}}, $line;
    }

    for (<$afmfile>) {
        when (m/\A\s* C         \s/xms) { push @{$afm{metrics}},    $_ }
        when (m/\A\s* KPX       \s/xms) { push @{$afm{kernpairs}},  $_ }
        when (m/\A\s* TrackKern \s/xms) { push @{$afm{trackkerns}}, $_ }
        when (m/\A\s* CC        \s/xms) { push @{$afm{composites}}, $_ }
    }

    close $afmfile;

    return \%afm;
}

#-----------------------------------------------------------------------
# Get encoding name and vector from the specified .enc file
#-----------------------------------------------------------------------
sub read_enc {
    my $filename = shift;

    open my $encfile, '<', $filename
        or die "[ERROR] can't open '$filename': $!";
    my $data = join ' ', map { s/%.+|\n//xmsg; $_ } <$encfile>;
    close $encfile;

    my ($scheme, $encoding)
        = $data =~ m{ /([-\w]+) \s* [[] (.+) []] \s* def }xms
        or die "[ERROR] parsing encoding file '$filename' failed";

    return { scheme => $scheme,
             vector => [ $encoding =~ m{ /([.\w]+) }xmsg ],
    };
}

#-----------------------------------------------------------------------
# Get encoding from the input .afm file
#-----------------------------------------------------------------------
sub get_enc {
    my $afm = shift;

    my %enc = ( scheme => 'FontSpecific', vector => [ ('/.undef') x 256 ] );

    for my $line (@{$afm->{fontinfo}}) {
        if ($line =~ m/EncodingScheme \s+ ([-\w]+)/xms) {
            $enc{scheme} = $1;
            last;
        }
    }
    for my $line (@{$afm->{metrics}}) {
        my ($pos, $name)
            = $line =~ m/C \s+ ([-]?\d+) .+? N \s+ ([.\w]+)/xms
            or die;
        $enc{vector}[$pos] = $name unless $pos == -1;
    }

    return \%enc;
}

#-----------------------------------------------------------------------
#
#-----------------------------------------------------------------------
sub print_fontinfo {
    my ($fontinfo, $scheme) = @_;

    for my $line (@$fontinfo) {
        $line = "EncodingScheme $scheme\n"
            if $line =~ m/EncodingScheme/xms;
        print $line;
    }

    return;
}

#-----------------------------------------------------------------------
# Print character metrics for characters in specified encoding
#-----------------------------------------------------------------------
sub print_charmetrics {
    my ($metrics, $vector) = @_;

    my %metrics = map { m/(WX .+? N \s+ ([.\w]+) .+)/xms; ($2 => $1) }
                      @$metrics;

    print "StartCharMetrics @{[ scalar grep { $metrics{$_} } @$vector ]}\n";
    for my $i (0 .. 255) {
        next unless $metrics{$vector->[$i]};
        print "C $i ; $metrics{$vector->[$i]}";
    }
    print "EndCharMetrics\n";

    return;
}

#-----------------------------------------------------------------------
# Print kerning data for characters in specified encoding
#-----------------------------------------------------------------------
sub print_kerndata {
    my ($kernpairs, $trackkerns, $char_in_enc) = @_;

    my @kernpairs = grep { m/\A\s* KPX \s+ ([.\w]+) \s+ ([.\w]+)/xms
                           and $char_in_enc->{$1}
                           and $char_in_enc->{$2}
                         }
                         @$kernpairs;

    if (@kernpairs || @$trackkerns) {
        print "StartKernData\n";
        if (@kernpairs) {
            print "StartKernPairs @{[ scalar @kernpairs ]}\n";
            print @kernpairs;
            print "EndKernPairs\n";
        }
        if (@$trackkerns) {
            print "StartTrackKern @{[ scalar @$trackkerns ]}\n";
            print @$trackkerns;
            print "EndTrackKern\n";
        }
        print "EndKernData\n";
    }

    return;
}

#-----------------------------------------------------------------------
# Print "composite" info for characters in specified encoding
#-----------------------------------------------------------------------
sub print_composites {
    my ($composites, $char_in_enc) = @_;

    # Each line mentions several characters: the composite and two or more
    # 'base' characters. We only print the line if all characters are
    # present in the specified encoding
    my @composites;
    COMPOSITE:
    for my $composite (@$composites) {
        my @chars = $composite =~ m/(?:CC \s+ ([.\w]+))/xmsg;
        for my $char (@chars) {
            next COMPOSITE unless $char_in_enc->{$char};
        }
        push @composites, $composite;
    }

    if (@composites) {
        print "StartComposites @{[ scalar @composites ]}\n";
        print @composites;
        print "EndComposites\n";
    }

    return;
}

#-----------------------------------------------------------------------
#
#-----------------------------------------------------------------------
sub print_mapentry {
    my ($fontinfo, $scheme) = @_;

    my $fontname = '';
    (my $fontfile = basename($ARGV[0]      // '')) =~ s/[.]afm\z//xms;
    (my $output   = basename($ARGV{output} // '')) =~ s/[.]afm\z//xms;

    for my $line (@$fontinfo) {
        if ($line =~ m/FontName \s+ ([-\w]+)/xms) {
            $fontname = $1;
            last;
        }
    }

    print {*STDOUT} qq(${output} ${fontname} <${fontfile}.pfb ),
                    qq(<[$ARGV{encoding} "${scheme} ReEncodeFont"\n);

    return;

}

__END__


############################################################################

    To create the documentation:

    pod2man --center="Marc Penninga" --release="fontools" --section=1 \
        afm2afm - | groff -Tps -man - | ps2pdf - afm2afm.pdf

=pod

=head1 NAME

afm2afm - reencode an F<afm> file

=head1 SYNOPSIS

=over 8

=item B<afm2afm>

[B<-help>]
[B<-encoding> I<encodingfile>]
[B<-output> I<outputfile>]
B<afmfile>

=back


=head1 DESCRIPTION

B<afm2afm> re-encodes an F<afm> file.

Metrics (including kerning data) for characters not present in the
chosen encoding are excluded from the output, which resuls in
much smaller files.

Note that if you don't specify an encoding file, the F<afm> file
isn't re-encoded, but the unused data is still pruned.

The program also generates an entry for a F<dvips>-style map file,
but only if the F<afm> file has been re-encoded and
the output was written to file
(i.e., if both the I<-encoding> and I<-output> options were specified).


=head1 OPTIONS AND ARGUMENTS

=over 4

=item B<-help>

Print a short description of the syntax

=item B<-encoding> I<encodingfile>

Re-encode to the enconding in I<encodingfile>

=item B<-output> I<outputfile>

Write the result to I<outputfile> instead of C<stdout>.

=item B<afmfile>

The F<afm> file to be re-encoded.

=back

Option names may be shortened to a unique prefix.


=head1 AUTHOR

Marc Penninga <marcpenninga@gmail.com>


=head1 COPYRIGHT

Copyright (C) 2005-2012 Marc Penninga.


=head1 LICENSE

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published
by the Free Software Foundation, either version 2 of the License,
or (at your option) any later version.
A copy of the GNU General Public License is included with B<autoinst>;
see the file F<GPLv2.txt>.


=head1 DISCLAIMER

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.


=head1 RECENT CHANGES

(See the source code for the rest of the story.)

=over 12

=item I<2012-02-01>

Refactored the code; added the "no re-encoding, only pruning"
functionality.

=back


=begin Really_old_history

=over 12

=item I<2005-01-10>

First version

=item I<2005-01-25>

Added printing of mapfile entry

=item I<2005-02-18>

Rewrote some of the code

=item I<2005-03-08>

Input files searched via B<kpsewhich> (where available)

=item I<2005-03-15>

Input files searched using B<kpsewhich> or B<findtexmf> (if available)

=item I<2005-04-15>

Updated creation of mapfile entry; look for font file to deduce the correct
font file format (pfb, pfa, ttf). If no font file is found,
pfb is assumed.

=item I<2005-04-20>

Program quits if the specified output file exists

=item I<2005-04-29>

Improved the documentation

=item I<2005-07-29>

Some updates to the documentation

=item I<2006-01-12>

A few minor changes to the code

=back

=cut