summaryrefslogtreecommitdiff
path: root/Master/texmf-dist/scripts/fontools/ot2kpx
blob: 2073d6b6d32b7bfdbb6139c37d15c1d8e6ebd2c9 (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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
#! /usr/bin/env perl

=begin COPYRIGHT

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

    Copyright (C) 2005-2019 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 integer;
use Getopt::Long ();
use List::Util @List::Util::EXPORT_OK;
use Pod::Usage;

my $VERSION = "20190712";

our ($NUM_GLYPHS, $UNITS_PER_EM, %kern);

sub main {
    %ARGV = (
        print_func  =>  \&print_kpx,
    );

    Getopt::Long::GetOptions(
        'help|?'    =>  sub { pod2usage(-verbose => 0) },
        'version'   =>  sub { print "$VERSION\n"; exit },
        'doc'       =>  sub { pod2usage(-verbose => 2) },
        'afm'       =>  sub { $ARGV{print_func} = \&print_kpx },
        'kpx'       =>  sub { $ARGV{print_func} = \&print_kpx },
        'lua'       =>  sub { $ARGV{print_func} = \&print_lua },
    ) or pod2usage(-verbose => 0);
    pod2usage(-verbose => 0) if @ARGV != 1;

    my %font = OTF::get_tables($ARGV[0]);

    $NUM_GLYPHS = unpack '@4n', $font{maxp};
    $UNITS_PER_EM = unpack '@18n', $font{head};

    my @glyph_name = map { sprintf "index%d", $_ } 0 .. $NUM_GLYPHS - 1;
    if (defined $font{CFF}) {
        OTF::CFF::get_glyph_names($font{CFF}, \@glyph_name);
    }

    if (defined $font{kern}) {
        OTF::Kern::parse_kerntable($font{kern});
    }

    if (defined $font{GPOS}) {
        my @lookup_list_indices
            = OTF::GPOS::get_lookup_list_indices($font{GPOS});
        my @all_lookups = OTF::GPOS::get_lookups($font{GPOS});
        my @lookups = @all_lookups[@lookup_list_indices];
        my @subtables = map { OTF::GPOS::get_subtables($_) } @lookups;

        for my $subtable (@subtables) {
            my $pos_format = unpack 'n', $subtable;
            if ($pos_format == 1) {
                OTF::GPOS::parse_pos_format_1($subtable);
            }
            elsif ($pos_format == 2) {
                OTF::GPOS::parse_pos_format_2($subtable);
            }
            else {
                warn "[ERROR] invalid PosFormat $pos_format ignored";
            }
        }
    }

    &{$ARGV{print_func}}( \%kern, \@glyph_name );
    return;
}

# ------------------------------------------------------------------------
# Print kerning data in Adobe's KPX format
# ------------------------------------------------------------------------
sub print_kpx {
    my %kern = %{ shift @_ };
    my @glyph = @{ shift @_ };

    my $num_kernpairs = sum map { scalar keys %{$kern{$_}} } keys %kern;
    print "StartKernData\nStartKernPairs $num_kernpairs\n";
    for my $l (sort { $glyph[$a] cmp $glyph[$b] } keys %kern) {
        my $l_glyph = $glyph[$l];
        for my $r (sort { $glyph[$a] cmp $glyph[$b] } keys %{$kern{$l}}) {
            print "KPX $l_glyph $glyph[$r] ",
                  "$kern{$l}{$r}\n";
        }
    }
    print "EndKernPairs\nEndKernData\n";
}

# ------------------------------------------------------------------------
# Print kerning data as a Luatex custom font feature
# ------------------------------------------------------------------------
sub print_lua {
    my %kern = %{ shift @_ };
    my @glyph = @{ shift @_ };

    print <<'END_FEATURE_PREFIX';
fonts.handlers.otf.addfeature {
    name = 'kern',
    type = 'kern',
    data = {
END_FEATURE_PREFIX

    for my $l ( sort { $glyph[$a] cmp $glyph[$b] } keys %kern ) {
        print ' ' x 8, "[ '$glyph[$l]' ] = {";
        for my $r ( sort { $glyph[$a] cmp $glyph[$b] } keys %{$kern{$l}} ) {
            print "\n", ' ' x 12, "[ '$glyph[$r]' ] = $kern{$l}{$r},";
        }
        print " },\n";
    }

    print <<'END_FEATURE_POSTFIX';
    }
}
END_FEATURE_POSTFIX
}

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


package OTF;

#-----------------------------------------------------------------------
# Return a hash with all tables (as strings) from the font
#-----------------------------------------------------------------------
sub get_tables {
    my $filename = shift;

    open my $fontfile, '<:raw', $filename
        or die "[ERROR] can't open $filename: $!";
    my $fontdata = do { local $/; <$fontfile> };
    close $fontfile;

    my ($sfnt_version, @tables) = unpack 'a4nx6/(a16)', $fontdata;

    die "[ERROR] $filename: unknown font type"
        unless $sfnt_version eq "\x00\x01\x00\x00"
            || $sfnt_version eq 'OTTO';

    my %table = map { my ($tag, $offset, $length) = unpack 'A4@8N@12N', $_;
                      ($tag => substr $fontdata, $offset, $length);
                    }
                    @tables;

    return %table;
}


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


package OTF::CFF;

my @STANDARD_STRINGS = qw(
    .notdef space exclam quotedbl
    numbersign dollar percent ampersand
    quoteright parenleft parenright asterisk
    plus comma hyphen period

    slash zero one two
    three four five six
    seven eight nine colon
    semicolon less equal greater

    question at A B
    C D E F
    G H I J
    K L M N

    O P Q R
    S T U V
    W X Y Z
    bracketleft backslash bracketright asciicircum

    underscore quoteleft a b
    c d e f
    g h i j
    k l m n

    o p q r
    s t u v
    w x y z
    braceleft bar braceright asciitilde

    exclamdown cent sterling fraction
    yen florin section currency
    quotesingle quotedblleft guillemotleft guilsinglleft
    guilsinglright fi fl endash

    dagger daggerdbl periodcentered paragraph
    bullet quotesinglbase quotedblbase quotedblright
    guillemotright ellipsis perthousand questiondown
    grave acute circumflex tilde

    macron breve dotaccent dieresis
    ring cedilla hungarumlaut ogonek
    caron emdash AE ordfeminine
    Lslash Oslash OE ordmasculine

    ae dotlessi lslash oslash
    oe germandbls onesuperior logicalnot
    mu trademark Eth onehalf
    plusminus Thorn onequarter divide

    brokenbar degree thorn threequarters
    twosuperior registered minus eth
    multiply threesuperior copyright Aacute
    Acircumflex Adieresis Agrave Aring

    Atilde Ccedilla Eacute Ecircumflex
    Edieresis Egrave Iacute Icircumflex
    Idieresis Igrave Ntilde Oacute
    Ocircumflex Odieresis Ograve Otilde

    Scaron Uacute Ucircumflex Udieresis
    Ugrave Yacute Ydieresis Zcaron
    aacute acircumflex adieresis agrave
    aring atilde ccedilla eacute

    ecircumflex edieresis egrave iacute
    icircumflex idieresis igrave ntilde
    oacute ocircumflex odieresis ograve
    otilde scaron uacute ucircumflex

    udieresis ugrave yacute ydieresis
    zcaron exclamsmall Hungarumlautsmall dollaroldstyle
    dollarsuperior ampersandsmall Acutesmall parenleftsuperior
    parenrightsuperior twodotenleader onedotenleader zerooldstyle

    oneoldstyle twooldstyle threeoldstyle fouroldstyle
    fiveoldstyle sixoldstyle sevenoldstyle eightoldstyle
    nineoldstyle commasuperior threequartersemdash periodsuperior
    questionsmall asuperior bsuperior centsuperior

    dsuperior esuperior isuperior lsuperior
    msuperior nsuperior osuperior rsuperior
    ssuperior tsuperior ff ffi
    ffl parenleftinferior parenrightinferior Circumflexsmall

    hyphensuperior Gravesmall Asmall Bsmall
    Csmall Dsmall Esmall Fsmall
    Gsmall Hsmall Ismall Jsmall
    Ksmall Lsmall Msmall Nsmall

    Osmall Psmall Qsmall Rsmall
    Ssmall Tsmall Usmall Vsmall
    Wsmall Xsmall Ysmall Zsmall
    colonmonetary onefitted rupiah Tildesmall

    exclamdownsmall centoldstyle Lslashsmall Scaronsmall
    Zcaronsmall Dieresissmall Brevesmall Caronsmall
    Dotaccentsmall Macronsmall figuredash hypheninferior
    Ogoneksmall Ringsmall Cedillasmall questiondownsmall

    oneeighth threeeighths fiveeighths seveneighths
    onethird twothirds zerosuperior foursuperior
    fivesuperior sixsuperior sevensuperior eightsuperior
    ninesuperior zeroinferior oneinferior twoinferior

    threeinferior fourinferior fiveinferior sixinferior
    seveninferior eightinferior nineinferior centinferior
    dollarinferior periodinferior commainferior Agravesmall
    Aacutesmall Acircumflexsmall Atildesmall Adieresissmall

    Aringsmall AEsmall Ccedillasmall Egravesmall
    Eacutesmall Ecircumflexsmall Edieresissmall Igravesmall
    Iacutesmall Icircumflexsmall Idieresissmall Ethsmall
    Ntildesmall Ogravesmall Oacutesmall Ocircumflexsmall

    Otildesmall Odieresissmall OEsmall Oslashsmall
    Ugravesmall Uacutesmall Ucircumflexsmall Udieresissmall
    Yacutesmall Thornsmall Ydieresissmall 001.000
    001.001 001.002 001.003 Black

    Bold Book Light Medium
    Regular Roman Semibold
);

#-----------------------------------------------------------------------
#
#-----------------------------------------------------------------------
sub get_glyph_names {
    my ($CFF, $glyph_name) = @_;

    # skip header; parse (and ignore) NAME index
    my ($rest) = _parse_index(substr $CFF, unpack '@2C', $CFF);

    # parse TopDict index
    ($rest, my @top_dict) = _parse_index($rest);
    if (@top_dict > 1) {
        warn "[WARNING] multiple fonts in single file not supported";
    }
    my %top_dict = _parse_dict($top_dict[0]);
    if ($NUM_GLYPHS != unpack 'n', substr($CFF, $top_dict{17}, 2)) {
        die "[ERROR] NumGlyphs different in 'maxp' and 'CFF' tables";
    }

    # parse String index
    ($rest, my @strings) = _parse_index($rest);
    @strings = (@STANDARD_STRINGS, @strings);

    my $charset = substr $CFF, $top_dict{15};
    my $format = unpack 'C', $charset;
    if ($format == 0) {
        my @codes = unpack "\@1n@{[ $NUM_GLYPHS - 1 ]}", $charset;
        @$glyph_name = @strings[0, @codes];
    }
    elsif ($format == 1) {
        my $i = 0;
        $glyph_name->[$i++] = $strings[0];
        for (my $j = 0; $i < $NUM_GLYPHS; $j++) {
            my ($first, $n_left)
                = unpack "\@@{[ 1 + 3*$j ]}nC", $charset;
            $glyph_name->[$i + $_] = $strings[$first + $_]
                for 0 .. $n_left;
            $i += 1 + $n_left;
        }
    }
    elsif ($format == 2) {
        my $i = 0;
        $glyph_name->[$i++] = $strings[0];
        for (my $j = 0; $i < $NUM_GLYPHS; $j++) {
            my ($first, $n_left)
                = unpack "\@@{[ 1 + 4*$j ]}nn", $charset;
            $glyph_name->[$i + $_] = $strings[$first + $_]
                for 0 .. $n_left;
            $i += 1 + $n_left;
        }
    }
    else {
        warn "[ERROR] invalid CharsetFormat '$format' ignored";
    }

    return;
}

#-----------------------------------------------------------------------
# Parse Adobe's INDEX format (see CFF spec); return "rest" plus data array
#-----------------------------------------------------------------------
sub _parse_index {
    my $index = shift;

    my ($count, $off_size) = unpack 'nC', $index;
    my @offsets = unpack "\@3(a$off_size)@{[ $count + 1 ]}", $index;
    if    ($off_size == 1) { $_ = unpack 'C', $_ for @offsets }
    elsif ($off_size == 2) { $_ = unpack 'n', $_ for @offsets }
    elsif ($off_size == 4) { $_ = unpack 'N', $_ for @offsets }
    elsif ($off_size == 3) {
        for my $offset (@offsets) {
            my @bytes = map 'C3', $offset;
            $offset = ($bytes[0] << 16) + ($bytes[1] << 8) + $bytes[2];
        }
    }
    else {
        warn "[ERROR] invalid OffSize $off_size ignored";
    }
    $_ += 2 + $off_size * ($count + 1) for @offsets;

    my @data;
    for my $i (0 .. $count - 1) {
        $data[$i]
            = substr $index, $offsets[$i], $offsets[$i + 1] - $offsets[$i];
    }

    return substr($index, $offsets[$count]), @data;
}

#-----------------------------------------------------------------------
# Parse Adobe's DICT format (see CFF spec); return data hash
#-----------------------------------------------------------------------
sub _parse_dict {
    my $dict = shift;

    my @bytes = unpack 'C*', $dict;
    my (@operands, %dict);
    while (@bytes) {
        if (( 0 <= $bytes[0] && $bytes[0] <= 11)
         || (13 <= $bytes[0] && $bytes[0] <= 22))
        {
            my $operator = shift @bytes;
            ($dict{$operator} = join q{ }, @operands) =~ s/^\s+//xms;
            @operands = ();
        }
        elsif ($bytes[0] == 12) {
            my $operator = join q{ }, splice @bytes, 0, 2;
            ($dict{$operator} = join q{ }, @operands) =~ s/^\s+//xms;
            @operands = ();
        }
        elsif ($bytes[0] == 28
           ||  $bytes[0] == 29
           ||  $bytes[0] == 30
           || (32 <= $bytes[0] && $bytes[0] <= 254))
        {
            push @operands, _get_number(\@bytes);
        }
        else {
            warn "[ERROR] invalid byte $bytes[0] in DICT ignored";
            shift @bytes;
        }
    }

    return %dict;
}

#-----------------------------------------------------------------------
# Parse Adobe's variable-length numbers (see CFF spec); shorten arg array
#-----------------------------------------------------------------------
sub _get_number {
    my $bytes = shift;

    my $b0 = shift @$bytes;
    if ($b0 == 28) {
        my ($b1, $b2) = splice @$bytes, 0, 2;
        return ($b1 << 8) | $b2;
    }
    elsif ($b0 == 29) {
        my ($b1, $b2, $b3, $b4) = splice @$bytes, 0, 4;
        return ((((($b1 << 8) + $b2) << 8) + $b3) << 8) + $b4;
    }
    elsif ($b0 == 30) {
        # Reals not implemented; just dump appropriate number of bytes
        until (($b0 & 0xf0) == 0xf0 || ($b0 & 0xf) == 0xf) {
            $b0 = shift @$bytes;
        }
    }
    elsif (32 <= $b0 && $b0 <= 246) {
        return $b0 - 139;
    }
    elsif (247 <= $b0 && $b0 <= 250) {
        my $b1 = shift @$bytes;
        return 256 * ($b0 - 247) + $b1 + 108;
    }
    elsif (251 <= $b0 && $b0 <= 254) {
        my $b1 = shift @$bytes;
        return -256 * ($b0 - 251) - $b1 - 108;
    }
}


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


package OTF::GPOS;

#-----------------------------------------------------------------------
# Return list of all Lookups from the GPOS table
#-----------------------------------------------------------------------
sub get_lookups {
    my $GPOS = shift;

    my $lookup_list = substr $GPOS, unpack '@8n', $GPOS;
    my @lookup_offsets = unpack 'n/n', $lookup_list;

    return map { substr $lookup_list, $_ } @lookup_offsets;
}

#-----------------------------------------------------------------------
# Return list of all LookupListIndices pointed to by 'kern' feature
#-----------------------------------------------------------------------
sub get_lookup_list_indices {
    my $GPOS = shift;

    my $feature_list = substr $GPOS, unpack '@6n', $GPOS;
    my %lookup_list_index;
    for my $feature_record (unpack 'n/(a6)', $feature_list) {
        my ($tag, $offset) = unpack 'a4n', $feature_record;
        next if $tag ne 'kern';

        my $feature = substr $feature_list, $offset;
        my @lookup_list_indices = unpack '@2n/n', $feature;
        $lookup_list_index{$_} = 1 for @lookup_list_indices;
    }

    return keys %lookup_list_index;
}

#-----------------------------------------------------------------------
# Return list of all subtables in Lookup table
#-----------------------------------------------------------------------
sub get_subtables {
    my $lookup = shift;

    my ($lookup_type, @subtable_offsets) = unpack 'n@4n/n', $lookup;
    if ($lookup_type != 2) {
        warn "[WARNING] LookupType $lookup_type not implemented";
        return;
    }

    return map { substr $lookup, $_ } @subtable_offsets;
}

#-----------------------------------------------------------------------
# Parse subtable in PairPosFormat 1, store kern pairs in global %kern
#-----------------------------------------------------------------------
sub parse_pos_format_1 {
    my $subtable = shift;

    my ($coverage_offset, $value_format_1, $value_format_2, @pair_set_offsets)
        = unpack '@2nnnn/n', $subtable;

    my @coverage = _get_coverage(substr $subtable, $coverage_offset);
    my @pair_sets = map { substr $subtable, $_ } @pair_set_offsets;
    if (@coverage != @pair_sets) {
        warn "[ERROR] Coverage table doesn't match PairSet table";
        return;
    }

    my ($record_size, $value_offset)
        = _parse_value_formats($value_format_1, $value_format_2, 2, 2);

    while (1) {
        my $pair_set = shift @pair_sets or last;
        my $first = shift @coverage;

        my @pair_value_records = unpack "n/(a$record_size)", $pair_set;

        for my $pair_value_record (@pair_value_records) {
            my ($second, $value)
                = unpack "n\@${value_offset}s>", $pair_value_record;
            next if $value == 0;
            $kern{$first}{$second} ||= 1000 * $value / $UNITS_PER_EM;
        }
    }

    return;
}

#-----------------------------------------------------------------------
# Parse subtable in PairPosFormat 2, store kern pairs in global %kern
#-----------------------------------------------------------------------
sub parse_pos_format_2 {
    my $subtable = shift;

    my ($coverage_offset, $value_format_1, $value_format_2,
        $class_def_1, $class_def_2, $class_1_count, $class_2_count)
        = unpack '@2nnnnnnn', $subtable;

    my @coverage = _get_coverage(substr $subtable, $coverage_offset);

    my ($class_2_record_size, $value_offset)
        = _parse_value_formats($value_format_1, $value_format_2, 0, 0);

    my @class_1 = _get_class(substr $subtable, $class_def_1);
    my @class_2 = _get_class(substr $subtable, $class_def_2);

    my $class_1_record_size = $class_2_count * $class_2_record_size;
    my @class_1_records
        = unpack "\@16(a$class_1_record_size)$class_1_count", $subtable;

    for my $class_1 (0 .. $class_1_count - 1) {
        my $class_1_record = $class_1_records[$class_1];
        my @class_2_records
            = unpack "(a$class_2_record_size)$class_2_count", $class_1_record;

        for my $class_2 (0 .. $class_2_count - 1) {
            my $class_2_record = $class_2_records[$class_2];
            my $value = unpack "\@${value_offset}s>", $class_2_record;
            next if $value == 0;
            $value = 1000 * $value / $UNITS_PER_EM;

            my @first  = grep { $class_1[$_] == $class_1 } @coverage;
            my @second = grep { $class_2[$_] == $class_2 } 0 .. $#class_2;

            for my $first (@first) {
                for my $second (@second) {
                    $kern{$first}{$second} ||= $value;
                }
            }
        }
    }

    return;
}

#-----------------------------------------------------------------------
# Get class number for all glyphs
#-----------------------------------------------------------------------
sub _get_class {
    my $class = shift;

    my @class = (0) x $NUM_GLYPHS;

    my $class_format = unpack 'n', $class;
    if ($class_format == 1) {
        my ($start_glyph, @class_value) = unpack '@2nn/n', $class;
        @class[$start_glyph .. $start_glyph + $#class_value]
            = @class_value;
    }
    elsif ($class_format == 2) {
        my @class_ranges = unpack '@2n/(a6)', $class;
        for my $class_range (@class_ranges) {
            my ($start, $end, $class) = unpack 'nnn', $class_range;
            @class[$start .. $end] = ($class) x ($end - $start + 1);
        }
    }
    else {
        warn "[ERROR] invalid ClassFormat '$class_format' ignored";
        return;
    }

    return @class;
}


#-----------------------------------------------------------------------
# Determine size of ValueRecord and offset of XAdvance value in it
#-----------------------------------------------------------------------
sub _parse_value_formats {
    my ($value_format_1, $value_format_2, $record_size, $value_offset) = @_;

    unless ($value_format_1 & 0x4 && $value_format_2 == 0) {
        warn "[WARNING] ValueFormat ($value_format_1, ",
             "$value_format_2) not implemented";
        return;
    }

    for my $bit ((0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80)) {
        $record_size += 2 if $value_format_1 & $bit;
    }
    for my $bit ((0x1, 0x2)) {
        $value_offset += 2 if $value_format_1 & $bit;
    }

    return ($record_size, $value_offset);
}

#-----------------------------------------------------------------------
# Return a list of GlyphIDs in a Coverage table
#-----------------------------------------------------------------------
sub _get_coverage {
    my $coverage = shift;

    my $coverage_format = unpack 'n', $coverage;
    if ($coverage_format == 1) {
        return unpack '@2n/n', $coverage;
    }
    elsif ($coverage_format == 2) {
        my @range_records = unpack '@2n/(a6)', $coverage;

        return map { my ($start, $end) = unpack 'nn', $_;
                     $start .. $end;
                   }
                   @range_records;
    }
    else {
        warn "[WARNING] unknown CoverageFormat $coverage_format ignored";
    }
}


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


package OTF::Kern;

#-----------------------------------------------------------------------
# Parse "kern"table, store kern pairs in global %kern
#-----------------------------------------------------------------------
sub parse_kerntable {
    my $kern = shift;

    my $num_tables = unpack '@2n', $kern;
    my $start_subtable = 4;
    for my $i (0 .. $num_tables - 1) {
        my $subtable = substr $kern, $start_subtable;
        my ($length, $coverage) = unpack '@2nn', $subtable;
        $start_subtable += $length;

        if ($coverage != 0x1) {
            warn "[WARNING] kern table format '$coverage' not implemented";
            next;
        }

        my @kern_pairs = unpack '@6nx6/(a6)', $subtable;
        for my $kern_pair (@kern_pairs) {
            my ($first, $second, $value) = unpack 'nns>', $kern_pair;
            next if $value == 0;

            $kern{$first}{$second} ||= 1000 * $value / $UNITS_PER_EM;
        }
    }

    return;
}


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


package main;

main();

__END__


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


    To create the documentation:

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

=pod

=head1 NAME

ot2kpx - extract kerning information from OpenType fonts


=head1 SYNOPSIS

B<ot2kpx> [ I<-afm> | I<-kpx> | I<-lua> ] B<< <fontfile> >>


=head1 DESCRIPTION

B<ot2kpx> extract the kerning data from OpenType fonts and prints it
to C<stdout>, either in Adobe's KPX format (for adding to an F<afm> file)
or as a Luatex custom feature, for use with the C<\directlua> command.


=head1 OPTIONS AND ARGUMENTS

=over 4

=item B<-help>

Print a short help text and exit.

=item B<-version>

Print B<ot2kpx>'s version and exit.

=item B<-afm>, B<-kpx>

Output the kerning data in Adobe's KPX format, as used in F<afm> files.
This is the default output format.

=item B<-lua>

Output the kerning data as a Luatex custom font feature,
to be included in a C<\directlua> command.

=item B<< <fontfile> >>

The OpenType font (both F<otf> and F<ttf> format are supported).

=back


=head1 RESTRICTIONS

=over 4

=item B<->

B<ot2kpx> doesn't implement all of the OpenType specification.
Things that are missing include: support for font files containing
multiple fonts, LookupTables with LookupTypes other than 2,
"kern" tables with format other than 0 and ValueRecords with
other types of data than just XAdvance data.

Most of these limitations won't matter, since the missing features
are rare (the only fonts I know of that use them are the non-western fonts
that come with Adobe Reader). Furthermore, many of these features define
(according to the OpenType specification) I<"subtle, device-dependent
adjustments at specific font sizes or device resolutions">;
since there's no way to express such adjustments in F<afm> format,
ignoring them seems to be the only option anyway.

=item B<->

B<ot2kpx> collects kerning data first from the "kern" table, then from
all LookupTables associated with the "kern" feature; if a kerning pair
occurs multiple times, the first value seen is chosen.
There are (or may be) several issues with this approach:

=over 4

=item -

The OpenType specification says that fonts in F<otf> format shouldn't
use the "kern" table at all, just the lookups from the "GPOS" table.
Many such fonts do, however, contain a "kern" table, but no "GPOS" table;
so we use the "kern" table anyway.

=item -

Instead of reading all LookupTables, it might be better to let the user
specify a script and language and process only the LookupTables for
those values.
However, at least in the fonts I checked, all script/language combinations
eventually point to the I<same> "kern" LookupTables, so this approach
wouldn't make any difference (apart from further complicating the code).

=back

=back


=head1 AUTHOR

Marc Penninga <marcpenninga@gmail.com>


=head1 COPYRIGHT

Copyright (C) 2005-2019 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<ot2kpx>;
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 VERSION

This document describes B<ot2kpx> version 20190712.


=head1 RECENT CHANGES

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

=over 12

=item I<2019-05-20>

Added the I<-version> option.

=item I<2019-04-15>

Added the I<-lua> command-line option to get output in Luatex's
custom feature format.

=back


=begin Really_old_history

=over 12

=item I<2013-08-07>

Replaced all C<given/when> constructions in the source code by C<if>'s,
to avoid warnings about experimental features in Perl 5.18 and later.

=item I<2012-02-01>

Refactored the code, and fixed a number of bugs in the process.
Updated the documentation.

=item I<2005-01-10>

First version

=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>

=item I<2005-03-21>

Test if GPOS table is present before trying to read it

=item I<2005-04-29>

Improved the documentation

=item I<2005-05-25>

Changed warning that's given when the font contains no GPOS table, to an
informational message.

=item I<2005-07-29>

A few updates to the documentation

=back

=cut