<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">package Font::TTF::Ttopen;

=head1 NAME

Font::TTF::Ttopen - Opentype superclass for standard Opentype lookup based tables
(GSUB and GPOS)

=head1 DESCRIPTION

Handles all the script, lang, feature, lookup stuff for a
L&lt;Font::TTF::Gsub&gt;/L&lt;Font::TTF::Gpos&gt; table leaving the class specifics to the
subclass

=head1 INSTANCE VARIABLES

The instance variables of an opentype table form a complex sub-module hierarchy.

=over 4

=item Version

This contains the version of the table as a floating point number

=item SCRIPTS

The scripts list is a hash of script tags. Each script tag (of the form
$t-&gt;{'SCRIPTS'}{$tag}) has information below it.

=over 8

=item OFFSET

This variable is preceeded by a space and gives the offset from the start of the
table (not the table section) to the script table for this script

=item REFTAG

This variable is preceded by a space and gives a corresponding script tag to this
one such that the offsets in the file are the same. When writing, it is up to the
caller to ensure that the REFTAGs are set correctly, since these will be used to
assume that the scripts are identical. Note that REFTAG must refer to a script which
has no REFTAG of its own.

=item DEFAULT

This corresponds to the default language for this script, if there is one, and
contains the same information as an itemised language

=item LANG_TAGS

This contains an array of language tag strings (each 4 bytes) corresponding to
the languages listed by this script

=item $lang

Each language is a hash containing its information:

=over 12

=item OFFSET

This variable is preceeded by a a space and gives the offset from the start of
the whole table to the language table for this language

=item REFTAG

This variable is preceded by a space and has the same function as for the script
REFTAG, only for the languages within a script.

=item RE-ORDER

This indicates re-ordering information, and has not been set. The value should
always be 0.

=item DEFAULT

This holds the index of the default feature, if there is one, or -1 otherwise.

=item FEATURES

This is an array of feature tags for all the features enabled for this language

=back

=back

=item FEATURES

The features section of instance variables corresponds to the feature table in
the opentype table.

=over 8

=item FEAT_TAGS

This array gives the ordered list of feature tags for this table. It is used during
reading and writing for converting between feature index and feature tag.

=back

The rest of the FEATURES variable is itself a hash based on the feature tag for
each feature. Each feature has the following structure:

=over 8

=item OFFSET

This attribute is preceeded by a space and gives the offset relative to the start of the whole
table of this particular feature.

=item PARMS

This is an unused offset to the parameters for each feature

=item LOOKUPS

This is an array containing indices to lookups in the LOOKUP instance variable of the table

=item INDEX

This gives the feature index for this feature and is used during reading and writing for
converting between feature tag and feature index.

=back

=item LOOKUP

This variable is an array of lookups in order and is indexed via the features of a language of a
script. Each lookup contains subtables and other information:

=over 8

=item OFFSET

This name is preceeded by a space and contains the offset from the start of the table to this
particular lookup

=item TYPE

This is a subclass specific type for a lookup. It stipulates the type of lookup and hence subtables
within the lookup

=item FLAG

Holds the lookup flag bits

=item SUB

This holds an array of subtables which are subclass specific. Each subtable must have
an OFFSET. The other variables described here are an abstraction used in both the
GSUB and GPOS tables which are the target subclasses of this class.

=over 12

=item OFFSET

This is preceeded by a space and gives the offset relative to the start of the table for this
subtable

=item FORMAT

Gives the sub-table sub format for this GSUB subtable. It is assumed that this
value is correct when it comes time to write the subtable.

=item COVERAGE

Most lookups consist of a coverage table corresponding to the first
glyph to match. The offset of this coverage table is stored here and the coverage
table looked up against the GSUB table proper. There are two lookups
without this initial coverage table which is used to index into the RULES array.
These lookups have one element in the RULES array which is used for the whole
match.

=item RULES

The rules are a complex array. Each element of the array corresponds to an
element in the coverage table (governed by the coverage index). If there is
no coverage table, then there is considered to be only one element in the rules
array. Each element of the array is itself an array corresponding to the
possibly multiple string matches which may follow the initial glyph. Each
element of this array is a hash with fixed keys corresponding to information
needed to match a glyph string or act upon it. Thus the RULES element is an
array of arrays of hashes which contain the following keys:

=over 16

=item MATCH

This contains a sequence of elements held as an array. The elements may be
glyph ids (gid), class ids (cids), or offsets to coverage tables. Each element
corresponds to one glyph in the glyph string. See MATCH_TYPE for details of
how the different element types are marked.

=item PRE

This array holds the sequence of elements preceeding the first match element
and has the same form as the MATCH array.

=item POST

This array holds the sequence of elements to be tested for following the match
string and is of the same form as the MATCH array.

=item ACTION

This array holds information regarding what should be done if a match is found.
The array may either hold glyph ids (which are used to replace or insert or
whatever glyphs in the glyph string) or 2 element arrays consisting of:

=over 20

=item OFFSET

Offset from the start of the matched string that the lookup should start at
when processing the substring.

=item LOOKUP_INDEX

The index to a lookup to be acted upon on the match string.

=back

=back

=back

=back

=item CLASS

For those lookups which use class categories rather than glyph ids for matching
this is the offset to the class definition used to categories glyphs in the
match string.

=item PRE_CLASS

This is the offset to the class definition for the before match glyphs

=item POST_CLASS

This is the offset to the class definition for the after match glyphs.

=item ACTION_TYPE

This string holds the type of information held in the ACTION variable of a RULE.
It is subclass specific.

=item MATCH_TYPE

This holds the type of information in the MATCH array of a RULE. This is subclass
specific.

=item ADJUST

This corresponds to a single action for all items in a coverage table. The meaning
is subclass specific.

=item CACHE

This key starts with a space

A hash of other tables (such as coverage tables, classes, anchors, device tables)
based on the offset given in the subtable to that other information.
Note that the documentation is particularly
unhelpful here in that such tables are given as offsets relative to the
beginning of the subtable not the whole GSUB table. This includes those items which
are stored relative to another base within the subtable.

=back


=head1 METHODS

=cut

use Font::TTF::Table;
use Font::TTF::Utils;
use Font::TTF::Coverage;
use strict;
use vars qw(@ISA);

@ISA = qw(Font::TTF::Table);

=head2 $t-&gt;read

Reads the table passing control to the subclass to handle the subtable specifics

=cut

sub read
{
    my ($self) = @_;
    my ($dat, $i, $l, $oScript, $oFeat, $oLook, $tag, $nScript, $off, $dLang, $nLang, $lTag);
    my ($nFeat, $nLook, $nSub, $j, $temp);
    my ($fh) = $self-&gt;{' INFILE'};
    my ($moff) = $self-&gt;{' OFFSET'};

    $self-&gt;SUPER::read or return $self;
    $fh-&gt;read($dat, 10);
    ($self-&gt;{'Version'}, $oScript, $oFeat, $oLook) = TTF_Unpack("vSSS", $dat);

# read features first so that in the script/lang hierarchy we can use feature tags

    $fh-&gt;seek($moff + $oFeat, 0);
    $fh-&gt;read($dat, 2);
    $nFeat = unpack("n", $dat);
    $self-&gt;{'FEATURES'} = {};
    $l = $self-&gt;{'FEATURES'};
    $fh-&gt;read($dat, 6 * $nFeat);
    for ($i = 0; $i &lt; $nFeat; $i++)
    {
    	($tag, $off) = unpack("a4n", substr($dat, $i * 6, 6));
    	while (defined $l-&gt;{$tag})
    	{
    	    if ($tag =~ m/(.*?)\s_(\d+)$/o)
    	    { $tag = $1 . " _" . ($2 + 1); }
    	    else
    	    { $tag .= " _0"; }
    	}
	    $l-&gt;{$tag}{' OFFSET'} = $off + $oFeat;
	    $l-&gt;{$tag}{'INDEX'} = $i;
	    push (@{$l-&gt;{'FEAT_TAGS'}}, $tag);
    }

    foreach $tag (grep {m/^.{4}(?:\s_\d+)?$/o} keys %$l)
    {
	    $fh-&gt;seek($moff + $l-&gt;{$tag}{' OFFSET'}, 0);
    	$fh-&gt;read($dat, 4);
	    ($l-&gt;{$tag}{'PARMS'}, $nLook) = unpack("n2", $dat);
    	$fh-&gt;read($dat, $nLook * 2);
	    $l-&gt;{$tag}{'LOOKUPS'} = [unpack("n*", $dat)];
    }

# Now the script/lang hierarchy

    $fh-&gt;seek($moff + $oScript, 0);
    $fh-&gt;read($dat, 2);
    $nScript = unpack("n", $dat);
    $self-&gt;{'SCRIPTS'} = {};
    $l = $self-&gt;{'SCRIPTS'};
    $fh-&gt;read($dat, 6 * $nScript);
    for ($i = 0; $i &lt; $nScript; $i++)
    {
    	($tag, $off) = unpack("a4n", substr($dat, $i * 6, 6));
    	$off += $oScript;
        foreach (keys %$l)
        { $l-&gt;{$tag}{' REFTAG'} = $_ if ($l-&gt;{$_}{' OFFSET'} == $off
                                        &amp;&amp; !defined $l-&gt;{$_}{' REFTAG'}); }
	    $l-&gt;{$tag}{' OFFSET'} = $off;
    }

    foreach $tag (keys %$l)
    {
        next if ($l-&gt;{$tag}{' REFTAG'});
    	$fh-&gt;seek($moff + $l-&gt;{$tag}{' OFFSET'}, 0);
    	$fh-&gt;read($dat, 4);
    	($dLang, $nLang) = unpack("n2", $dat);
    	$l-&gt;{$tag}{'DEFAULT'}{' OFFSET'} =
    	        $dLang + $l-&gt;{$tag}{' OFFSET'} if $dLang;
    	$fh-&gt;read($dat, 6 * $nLang);
    	for ($i = 0; $i &lt; $nLang; $i++)
    	{
    	    ($lTag, $off) = unpack("a4n", substr($dat, $i * 6, 6));
    	    $off += $l-&gt;{$tag}{' OFFSET'};
    	    $l-&gt;{$tag}{$lTag}{' OFFSET'} = $off;
            foreach (@{$l-&gt;{$tag}{'LANG_TAGS'}}, 'DEFAULT')
            { $l-&gt;{$tag}{$lTag}{' REFTAG'} = $_ if ($l-&gt;{$tag}{$_}{' OFFSET'} == $off
                                                   &amp;&amp; !$l-&gt;{$tag}{$_}{' REFTAG'}); }
    	    push (@{$l-&gt;{$tag}{'LANG_TAGS'}}, $lTag);
    	}
    	foreach $lTag (@{$l-&gt;{$tag}{'LANG_TAGS'}}, 'DEFAULT')
    	{
    	    next unless defined $l-&gt;{$tag}{$lTag};
            next if ($l-&gt;{$tag}{$lTag}{' REFTAG'});
    	    $fh-&gt;seek($moff + $l-&gt;{$tag}{$lTag}{' OFFSET'}, 0);
    	    $fh-&gt;read($dat, 6);
    	    ($l-&gt;{$tag}{$lTag}{'RE-ORDER'}, $l-&gt;{$tag}{$lTag}{'DEFAULT'}, $nFeat) 
    	      = unpack("n3", $dat);
    	    $fh-&gt;read($dat, $nFeat * 2);
    	    $l-&gt;{$tag}{$lTag}{'FEATURES'} = [map {$self-&gt;{'FEATURES'}{'FEAT_TAGS'}[$_]} unpack("n*", $dat)];
    	}
    	foreach $lTag (@{$l-&gt;{$tag}{'LANG_TAGS'}}, 'DEFAULT')
    	{
       	    next unless $l-&gt;{$tag}{$lTag}{' REFTAG'};
    	    $temp = $l-&gt;{$tag}{$lTag}{' REFTAG'};
    	    $l-&gt;{$tag}{$lTag} = &amp;copy($l-&gt;{$tag}{$temp});
    	    $l-&gt;{$tag}{$lTag}{' REFTAG'} = $temp;
    	}
    }
    foreach $tag (keys %$l)
    {
        next unless $l-&gt;{$tag}{' REFTAG'};
        $temp = $l-&gt;{$tag}{' REFTAG'};
        $l-&gt;{$tag} = &amp;copy($l-&gt;{$temp});
        $l-&gt;{$tag}{' REFTAG'} = $temp;
    }

# And finally the lookups

    $fh-&gt;seek($moff + $oLook, 0);
    $fh-&gt;read($dat, 2);
    $nLook = unpack("n", $dat);
    $fh-&gt;read($dat, $nLook * 2);
    $i = 0;
    map { $self-&gt;{'LOOKUP'}[$i++]{' OFFSET'} = $_; } unpack("n*", $dat);

    for ($i = 0; $i &lt; $nLook; $i++)
    {
    	$l = $self-&gt;{'LOOKUP'}[$i];
    	$fh-&gt;seek($l-&gt;{' OFFSET'} + $moff + $oLook, 0);
    	$fh-&gt;read($dat, 6);
    	($l-&gt;{'TYPE'}, $l-&gt;{'FLAG'}, $nSub) = unpack("n3", $dat);
    	$fh-&gt;read($dat, $nSub * 2);
    	$j = 0;
        my @offsets = unpack("n*", $dat);
        my $isExtension = ($l-&gt;{'TYPE'} == $self-&gt;extension());
    	for ($j = 0; $j &lt; $nSub; $j++)
    	{
    	    $l-&gt;{'SUB'}[$j]{' OFFSET'} = $offsets[$j];
       	    $fh-&gt;seek($moff + $oLook + $l-&gt;{' OFFSET'} + $l-&gt;{'SUB'}[$j]{' OFFSET'}, 0);
    	    if ($isExtension)
    	    {
    	        $fh-&gt;read($dat, 8);
    	        my $longOff;
    	        (undef, $l-&gt;{'TYPE'}, $longOff) = unpack("nnN", $dat);
    	        $l-&gt;{'SUB'}[$j]{' OFFSET'} += $longOff;
        	    $fh-&gt;seek($moff + $oLook + $l-&gt;{' OFFSET'} + $l-&gt;{'SUB'}[$j]{' OFFSET'}, 0);
            }
	        $self-&gt;read_sub($fh, $l, $j);
	    }
    }
    return $self;
}

=head2 $t-&gt;read_sub($fh, $lookup, $index)

This stub is to allow subclasses to read subtables of lookups in a table specific manner. A
reference to the lookup is passed in along with the subtable index. The file is located at the
start of the subtable to be read

=cut

sub read_sub
{ }


=head2 $t-&gt;extension()

Returns the lookup number for the extension table that allows access to 32-bit offsets.

=cut

sub extension
{ }


=head2 $t-&gt;out($fh)

Writes this Opentype table to the output calling $t-&gt;out_sub for each sub table
at the appropriate point in the output. The assumption is that on entry the
number of scripts, languages, features, lookups, etc. are all resolved and
the relationships fixed. This includes a script's LANG_TAGS list and that all
scripts and languages in their respective dictionaries either have a REFTAG or contain
real data.

=cut

sub out
{
    my ($self, $fh) = @_;
    my ($i, $j, $base, $off, $tag, $t, $l, $lTag, $oScript, @script, @tags);
    my ($end, $nTags, @offs, $oFeat, $oLook, $nSub, $nSubs, $big, $out);

    return $self-&gt;SUPER::out($fh) unless $self-&gt;{' read'};

# First sort the features
    $i = 0;
    $self-&gt;{'FEATURES'}{'FEAT_TAGS'} = [sort grep {m/^.{4}(?:\s_\d+)?$/o} %{$self-&gt;{'FEATURES'}}]
            if (!defined $self-&gt;{'FEATURES'}{'FEAT_TAGS'});
    foreach $t (@{$self-&gt;{'FEATURES'}{'FEAT_TAGS'}})
    { $self-&gt;{'FEATURES'}{$t}{'INDEX'} = $i++; }

    $base = $fh-&gt;tell();
    $fh-&gt;print(TTF_Pack("v", $self-&gt;{'Version'}));
    $fh-&gt;print(pack("n3", 10, 0, 0));
    $oScript = $fh-&gt;tell() - $base;
    @script = sort grep {length($_) == 4} keys %{$self-&gt;{'SCRIPTS'}};
    $fh-&gt;print(pack("n", $#script + 1));
    foreach $t (@script)
    { $fh-&gt;print(pack("a4n", $t, 0)); }

    $end = $fh-&gt;tell();
    foreach $t (@script)
    {
        $fh-&gt;seek($end, 0);
        $tag = $self-&gt;{'SCRIPTS'}{$t};
        next if ($tag-&gt;{' REFTAG'});
    	$tag-&gt;{' OFFSET'} = tell($fh) - $base - $oScript;
    	$fh-&gt;print(pack("n2", 0, $#{$tag-&gt;{'LANG_TAGS'}} + 1));
    	foreach $lTag (sort @{$tag-&gt;{'LANG_TAGS'}})
    	{ $fh-&gt;print(pack("a4n", $lTag, 0)); }
    	foreach $lTag (@{$tag-&gt;{'LANG_TAGS'}}, 'DEFAULT')
    	{
    	    my ($def);
    	    $l = $tag-&gt;{$lTag};
    	    next if (!defined $l || (defined $l-&gt;{' REFTAG'} &amp;&amp; $l-&gt;{' REFTAG'} ne ''));
    	    $l-&gt;{' OFFSET'} = $fh-&gt;tell() - $base - $oScript - $tag-&gt;{' OFFSET'};
    	    if (defined $l-&gt;{'DEFAULT'})
#    	    { $def = $self-&gt;{'FEATURES'}{$l-&gt;{'FEATURES'}[$l-&gt;{'DEFAULT'}]}{'INDEX'}; }
            { $def = $l-&gt;{'DEFAULT'}; }
    	    else
    	    { $def = -1; }
    	    $fh-&gt;print(pack("n*", $l-&gt;{'RE_ORDER'} || 0, $def, $#{$l-&gt;{'FEATURES'}} + 1,
    	            map {$self-&gt;{'FEATURES'}{$_}{'INDEX'} || 0} @{$l-&gt;{'FEATURES'}}));
    	}
    	$end = $fh-&gt;tell();
    	if ($tag-&gt;{'DEFAULT'}{' REFTAG'} || defined $tag-&gt;{'DEFAULT'}{'FEATURES'})
    	{
        	$fh-&gt;seek($base + $oScript + $tag-&gt;{' OFFSET'}, 0);
            if (defined $tag-&gt;{'DEFAULT'}{' REFTAG'})
            {
                my ($ttag);
                for ($ttag = $tag-&gt;{'DEFAULT'}{' REFTAG'}; defined $tag-&gt;{$ttag}{' REFTAG'}; $ttag = $tag-&gt;{$ttag}{' REFTAG'})
                { }
                $off = $tag-&gt;{$ttag}{' OFFSET'};
            }
            else
            { $off = $tag-&gt;{'DEFAULT'}{' OFFSET'}; }
        	$fh-&gt;print(pack("n", $off));
    	}
    	$fh-&gt;seek($base + $oScript + $tag-&gt;{' OFFSET'} + 4, 0);
    	foreach (sort @{$tag-&gt;{'LANG_TAGS'}})
    	{
            if (defined $tag-&gt;{$_}{' REFTAG'})
            {
                my ($ttag);
                for ($ttag = $tag-&gt;{$_}{' REFTAG'}; defined $tag-&gt;{$ttag}{' REFTAG'}; $ttag = $tag-&gt;{$ttag}{' REFTAG'})
                { }
                $off = $tag-&gt;{$ttag}{' OFFSET'};
            }
            else
            { $off = $tag-&gt;{$_}{' OFFSET'}; }
    	    $fh-&gt;print(pack("a4n", $_, $off));
    	}
    }
    $fh-&gt;seek($base + $oScript + 2, 0);
    foreach $t (@script)
    {
        $tag = $self-&gt;{'SCRIPTS'}{$t};
        $off = $tag-&gt;{' REFTAG'} ? $tag-&gt;{$tag-&gt;{' REFTAG'}}{' OFFSET'} : $tag-&gt;{' OFFSET'};
        $fh-&gt;print(pack("a4n", $t, $off));
    }

    $fh-&gt;seek($end, 0);
    $oFeat = $end - $base;
    $nTags = $#{$self-&gt;{'FEATURES'}{'FEAT_TAGS'}} + 1;
    $fh-&gt;print(pack("n", $nTags));
    $fh-&gt;print(pack("a4n", "    ", 0) x $nTags);
    
    foreach $t (@{$self-&gt;{'FEATURES'}{'FEAT_TAGS'}})
    {
        $tag = $self-&gt;{'FEATURES'}{$t};
        $tag-&gt;{' OFFSET'} = tell($fh) - $base - $oFeat;
        $fh-&gt;print(pack("n*", 0, $#{$tag-&gt;{'LOOKUPS'}} + 1, @{$tag-&gt;{'LOOKUPS'}}));
    }
    $end = $fh-&gt;tell();
    $fh-&gt;seek($oFeat + $base + 2, 0);
    foreach $t (@{$self-&gt;{'FEATURES'}{'FEAT_TAGS'}})
    { $fh-&gt;print(pack("a4n", $t, $self-&gt;{'FEATURES'}{$t}{' OFFSET'})); }

    undef $big;
    $fh-&gt;seek($end, 0);
    $oLook = $end - $base;
    
    # Start Lookup List Table
    $nTags = $#{$self-&gt;{'LOOKUP'}} + 1;
    $fh-&gt;print(pack("n", $nTags));
    $fh-&gt;print(pack("n", 0) x $nTags);
    $end = $fh-&gt;tell();		# end of LookupListTable = start of Lookups
    foreach $tag (@{$self-&gt;{'LOOKUP'}})
    { $nSubs += $self-&gt;num_sub($tag); }
    for ($i = 0; $i &lt; $nTags; $i++)
    {
        $fh-&gt;seek($end, 0);
        $tag = $self-&gt;{'LOOKUP'}[$i];
        $off = $end - $base - $oLook;	# BH 2004-03-04
        # Is there room, from the start of this i'th lookup, for this and the remaining
        # lookups to be wrapped in extension lookups?
        if (!defined $big &amp;&amp; $off + ($nTags - $i) * 6 + $nSubs * 10 &gt; 65535) # BH 2004-03-04
        {
			# Not enough room -- need to start an extension!            
            my ($k, $ext);
            $ext = $self-&gt;extension();
            # Must turn previous lookup into the first extension
            $i--;
            $tag = $self-&gt;{'LOOKUP'}[$i];
            $end = $tag-&gt;{' OFFSET'} + $base + $oLook;
            $fh-&gt;seek($end, 0);
            $big = $i;
            # For this and the remaining lookups, build extensions lookups
            for ($j = $i; $j &lt; $nTags; $j++)
            {
                $tag = $self-&gt;{'LOOKUP'}[$j];
                $nSub = $self-&gt;num_sub($tag);
                $fh-&gt;print(pack("nnn", $ext, $tag-&gt;{'FLAG'}, $nSub));
                $fh-&gt;print(pack("n*", map {$_ * 8 + 6 + $nSub * 2} (0 .. $nSub-1)));	# BH 2004-03-04
                $tag-&gt;{' EXT_OFFSET'} = $fh-&gt;tell();	# = first extension lookup subtable
                $tag-&gt;{' OFFSET'} = $tag-&gt;{' EXT_OFFSET'} - $nSub * 2 - 6 - $base - $oLook; # offset to this extension lookup
                for ($k = 0; $k &lt; $nSub; $k++)
                { $fh-&gt;print(pack('nnN', 1, $tag-&gt;{'TYPE'}, 0)); }
            }
            
            $tag = $self-&gt;{'LOOKUP'}[$i];
            # Leave file positioned after all the extension lookups -- where the referenced lookups will start.
        }
        $tag-&gt;{' OFFSET'} = $off unless defined $big;	# BH 2004-03-04
        $nSub = $self-&gt;num_sub($tag);
        if (!defined $big)
        {
            $fh-&gt;print(pack("nnn", $tag-&gt;{'TYPE'}, $tag-&gt;{'FLAG'}, $nSub));
            $fh-&gt;print(pack("n", 0) x $nSub);
        }
        else
        { $end = $tag-&gt;{' EXT_OFFSET'}; }
        my (@offs, $out, @refs);
        for ($j = 0; $j &lt; $nSub; $j++)
        {
            my ($ctables) = {};
            my ($base) = length($out);
            push(@offs, tell($fh) - $end + $base);
            $out .= $self-&gt;out_sub($fh, $tag, $j, $ctables, $base);
            push (@refs, [$ctables, $base]);
        }
        out_final($fh, $out, \@refs);
        $end = $fh-&gt;tell();
        if (!defined $big)
        {
            $fh-&gt;seek($tag-&gt;{' OFFSET'} + $base + $oLook + 6, 0);
            $fh-&gt;print(pack("n*", @offs));
        }
        else
        {
            $fh-&gt;seek($tag-&gt;{' EXT_OFFSET'}, 0);
            for ($j = 0; $j &lt; $nSub; $j++)
            { $fh-&gt;print(pack('nnN', 1, $tag-&gt;{'TYPE'}, $offs[$j] - $j * 8)); }
        }
    }
    $fh-&gt;seek($oLook + $base + 2, 0);
    $fh-&gt;print(pack("n*", map {$self-&gt;{'LOOKUP'}[$_]{' OFFSET'}} (0 .. $nTags - 1)));
    $fh-&gt;seek($base + 6, 0);
    $fh-&gt;print(pack('n2', $oFeat, $oLook));
    $fh-&gt;seek($end, 0);
    $self;
}


=head2 $t-&gt;num_sub($lookup)

Asks the subclass to count the number of subtables for a particular lookup and to
return that value. Used in out().

=cut

sub num_sub
{
    my ($self, $lookup) = @_;

    return $#{$lookup-&gt;{'SUB'}} + 1;
}


=head2 $t-&gt;out_sub($fh, $lookup, $index)

This stub is to allow subclasses to output subtables of lookups in a table specific manner. A
reference to the lookup is passed in along with the subtable index. The file is located at the
start of the subtable to be output

=cut

sub out_sub
{ }

=head2 $t-&gt;dirty

Setting GPOS or GSUB dirty means that OS/2 may need updating, so set it dirty.

=cut

sub dirty
{
    my ($self, $val) = @_;
    my $res = $self-&gt;SUPER::dirty ($val);
    $self-&gt;{' PARENT'}{'OS/2'}-&gt;read-&gt;dirty($val) if exists $self-&gt;{' PARENT'}{'OS/2'};
    $res;
}

=head2 $t-&gt;maxContext

Returns the length of the longest opentype rule in this table.

=cut

sub maxContext
{
    my ($self) = @_;
    
    # Make sure table is read
    $self-&gt;read;

    # Calculate my contribution to OS/2 usMaxContext
    
    my ($maxcontext, $l, $s, $r, $m);
   
    for $l (@{$self-&gt;{'LOOKUP'}})        # Examine each lookup
    {
        for $s (@{$l-&gt;{'SUB'}})         # Multiple possible subtables for this lookup
        {
            for $r (@{$s-&gt;{'RULES'}})   # One ruleset for each covered glyph
            {
                for $m (@{$r})          # Multiple possible matches for this covered glyph 
                {
                    my $lgt;
                    $lgt++ if exists $s-&gt;{'COVERAGE'};  # Count 1 for the coverage table if it exists
                    for (qw(MATCH PRE POST))
                    {
                        $lgt += @{$m-&gt;{$_}} if exists $m-&gt;{$_};
                    }
                    $maxcontext = $lgt if $lgt &gt; $maxcontext;
                }
            }
            
        }
    }
    
    $maxcontext;    
}    


=head2 $t-&gt;update

Unless $t-&gt;{' PARENT'}{' noharmony'} is true, update will make sure that GPOS and GSUB include 
the same scripts and languages. Any added scripts and languages will have empty feature sets.

=cut

# Assumes we are called on both GSUB and GPOS. So simply ADDS scripts and languages to $self that it finds
# in the other table.

sub update
{
    my ($self) = @_;
    
    return undef unless ($self-&gt;SUPER::update);

    # Enforce script/lang congruence unless asked not to:
    return $self if $self-&gt;{' PARENT'}{' noharmony'};

    # Find my sibling (GSUB or GPOS, depending on which I am)
    my $sibling = ref($self) eq 'Font::TTF::GSUB' ? 'GPOS' : ref($self) eq 'Font::TTF::GPOS' ? 'GSUB' : undef;
    return $self unless $sibling &amp;&amp; exists $self-&gt;{' PARENT'}{$sibling};
    $sibling = $self-&gt;{' PARENT'}{$sibling};
    next unless defined $sibling;
    
    # Look through scripts defined in sibling:
    for my $sTag (grep {length($_) == 4} keys %{$sibling-&gt;{'SCRIPTS'}})
    {
        my $sibScript = $sibling-&gt;{'SCRIPTS'}{$sTag};
        $sibScript = $sibling-&gt;{$sibScript-&gt;{' REFTAG'}} if exists $sibScript-&gt;{' REFTAG'} &amp;&amp; $sibScript-&gt;{' REFTAG'} ne '';
        
        $self-&gt;{'SCRIPTS'}{$sTag} = {} unless defined $self-&gt;{'SCRIPTS'}{$sTag}; # Create script if not present in $self
        
        my $myScript = $self-&gt;{'SCRIPTS'}{$sTag};
        $myScript = $self-&gt;{$myScript-&gt;{' REFTAG'}} if exists $myScript-&gt;{' REFTAG'} &amp;&amp; $myScript-&gt;{' REFTAG'} ne '';
                
        foreach my $lTag (@{$sibScript-&gt;{'LANG_TAGS'}})
        {
            # Ok, found a script/lang that is in our sibling.
            next if exists $myScript-&gt;{$lTag};  # Already in $self
            
            # Need to create this lang:
            push @{$myScript-&gt;{'LANG_TAGS'}}, $lTag;
            $myScript-&gt;{$lTag} = { 'FEATURES' =&gt; [] };
        }
        unless (defined $myScript-&gt;{'DEFAULT'})
        {
            # Create default lang for this script. Link to 'dflt' if it exists
            $myScript-&gt;{'DEFAULT'} = exists $myScript-&gt;{'dflt'} ? {' REFTAG' =&gt; 'dflt'} : { 'FEATURES' =&gt; [] };
        }
    }
    $self;
}

=head1 Internal Functions &amp; Methods

Most of these methods are used by subclasses for handling such things as coverage
tables.

=head2 copy($ref)

Internal function to copy the top level of a dictionary to create a new dictionary.
Only the top level is copied.

=cut

sub copy
{
    my ($ref) = @_;
    my ($res) = {};

    foreach (keys %$ref)
    { $res-&gt;{$_} = $ref-&gt;{$_}; }
    $res;
}


=head2 $t-&gt;read_cover($cover_offset, $lookup_loc, $lookup, $fh, $is_cover)

Reads a coverage table and stores the results in $lookup-&gt;{' CACHE'}, that is, if
it hasn't been read already.

=cut

sub read_cover
{
    my ($self, $offset, $base, $lookup, $fh, $is_cover) = @_;
    my ($loc) = $fh-&gt;tell();
    my ($cover, $str);

    return undef unless $offset;
    $str = sprintf("%X", $base + $offset);
    return $lookup-&gt;{' CACHE'}{$str} if defined $lookup-&gt;{' CACHE'}{$str};
    $fh-&gt;seek($base + $offset, 0);
    $cover = Font::TTF::Coverage-&gt;new($is_cover)-&gt;read($fh);
    $fh-&gt;seek($loc, 0);
    $lookup-&gt;{' CACHE'}{$str} = $cover;
    return $cover;
}


=head2 ref_cache($obj, $cache, $offset)

Internal function to keep track of the local positioning of subobjects such as
coverage and class definition tables, and their offsets.
What happens is that the cache is a hash of
sub objects indexed by the reference (using a string mashing of the
reference name which is valid for the duration of the reference) and holds a
list of locations in the output string which should be filled in with the
offset to the sub object when the final string is output in out_final.

Uses tricks for Tie::Refhash

=cut

sub ref_cache
{
    my ($obj, $cache, $offset) = @_;

    return 0 unless defined $obj;
    unless (defined $cache-&gt;{"$obj"})
    { push (@{$cache-&gt;{''}}, $obj); }
    push (@{$cache-&gt;{"$obj"}}, $offset);
    return 0;
}


=head2 out_final($fh, $out, $cache_list, $state)

Internal function to actually output everything to the file handle given that
now we know the offset to the first sub object to be output and which sub objects
are to be output and what locations need to be updated, we can now
generate everything. $cache_list is an array of two element arrays. The first element
is a cache object, the second is an offset to be subtracted from each reference
to that object made in the cache.

If $state is 1, then the output is not sent to the filehandle and the return value
is the string to be output. If $state is absent or 0 then output is not limited
by storing in a string first and the return value is "";

=cut

sub out_final
{
    my ($fh, $out, $cache_list, $state) = @_;
    my ($len) = length($out || '');
    my ($base_loc) = $state ? 0 : $fh-&gt;tell();
    my ($loc, $t, $r, $s, $master_cache, $offs, $str, %vecs);

    $fh-&gt;print($out || '') unless $state;       # first output the current attempt
    foreach $r (@$cache_list)
    {
        $offs = $r-&gt;[1];
        foreach $t (@{$r-&gt;[0]{''}})
        {
            $str = "$t";
            if (!defined $master_cache-&gt;{$str})
            {
                my ($vec) = $t-&gt;signature();
                if ($vecs{$vec})
                { $master_cache-&gt;{$str} = $master_cache-&gt;{$vecs{$vec}}; }
                else
                {
                    $vecs{$vec} = $str;
                    $master_cache-&gt;{$str} = ($state ? length($out) : $fh-&gt;tell())
                                                                       - $base_loc;
                    if ($state)
                    { $out .= $t-&gt;out($fh, 1); }
                    else
                    { $t-&gt;out($fh, 0); }
                }
            }
            foreach $s (@{$r-&gt;[0]{$str}})
            { substr($out, $s, 2) = pack('n', $master_cache-&gt;{$str} - $offs); }
        }
    }
    if ($state)
    { return $out; }
    else
    {
        $loc = $fh-&gt;tell();
        $fh-&gt;seek($base_loc, 0);
        $fh-&gt;print($out || '');       # the corrected version
        $fh-&gt;seek($loc, 0);
    }
}


=head2 $self-&gt;read_context($lookup, $fh, $type, $fmt, $cover, $count, $loc)

Internal method to read context (simple and chaining context) lookup subtables for
the GSUB and GPOS table types. The assumed values for $type correspond to those
for GSUB, so GPOS should adjust the values upon calling.

=cut

sub read_context
{
    my ($self, $lookup, $fh, $type, $fmt, $cover, $count, $loc) = @_;
    my ($dat, $i, $s, $t, @subst, @srec, $mcount, $scount);
    
    if ($type == 5 &amp;&amp; $fmt &lt; 3)
    {
        if ($fmt == 2)
        {
            $fh-&gt;read($dat, 2);
            $lookup-&gt;{'CLASS'} = $self-&gt;read_cover($count, $loc, $lookup, $fh, 0);
            $count = TTF_Unpack('S', $dat);
        }
        $fh-&gt;read($dat, $count &lt;&lt; 1);
        foreach $s (TTF_Unpack('S*', $dat))
        {
            if ($s == 0)
            {
                push (@{$lookup-&gt;{'RULES'}}, []);
                next;
            }
            @subst = ();
            $fh-&gt;seek($loc + $s, 0);
            $fh-&gt;read($dat, 2);
            $t = TTF_Unpack('S', $dat);
            $fh-&gt;read($dat, $t &lt;&lt; 1);
            foreach $t (TTF_Unpack('S*', $dat))
            {
                $fh-&gt;seek($loc + $s + $t, 0);
                @srec = ();
                $fh-&gt;read($dat, 4);
                ($mcount, $scount) = TTF_Unpack('S2', $dat);
                $mcount--;
                $fh-&gt;read($dat, ($mcount &lt;&lt; 1) + ($scount &lt;&lt; 2));
                for ($i = 0; $i &lt; $scount; $i++)
                { push (@srec, [TTF_Unpack('S2', substr($dat,
                    ($mcount &lt;&lt; 1) + ($i &lt;&lt; 2), 4))]); }
                push (@subst, {'ACTION' =&gt; [@srec],
                               'MATCH' =&gt; [TTF_Unpack('S*',
                                    substr($dat, 0, $mcount &lt;&lt; 1))]});
            }
            push (@{$lookup-&gt;{'RULES'}}, [@subst]);
        }
        $lookup-&gt;{'ACTION_TYPE'} = 'l';
        $lookup-&gt;{'MATCH_TYPE'} = ($fmt == 2 ? 'c' : 'g');
    } elsif ($type == 5 &amp;&amp; $fmt == 3)
    {
        $fh-&gt;read($dat, ($cover &lt;&lt; 1) + ($count &lt;&lt; 2));
        @subst = (); @srec = ();
        for ($i = 0; $i &lt; $cover; $i++)
        { push (@subst, $self-&gt;read_cover(TTF_Unpack('S', substr($dat, $i &lt;&lt; 1, 2)),
                                $loc, $lookup, $fh, 1)); }
        for ($i = 0; $i &lt; $count; $i++)
        { push (@srec, [TTF_Unpack('S2', substr($dat, ($count &lt;&lt; 1) + ($i &lt;&lt; 2), 4))]); }
        $lookup-&gt;{'RULES'} = [[{'ACTION' =&gt; [@srec], 'MATCH' =&gt; [@subst]}]];
        $lookup-&gt;{'ACTION_TYPE'} = 'l';
        $lookup-&gt;{'MATCH_TYPE'} = 'o';
    } elsif ($type == 6 &amp;&amp; $fmt &lt; 3)
    {
        if ($fmt == 2)
        {
            $fh-&gt;read($dat, 6);
            $lookup-&gt;{'PRE_CLASS'} = $self-&gt;read_cover($count, $loc, $lookup, $fh, 0) if $count;
            ($i, $mcount, $count) = TTF_Unpack('S3', $dat);     # messy: 2 classes &amp; count
            $lookup-&gt;{'CLASS'} = $self-&gt;read_cover($i, $loc, $lookup, $fh, 0) if $i;
            $lookup-&gt;{'POST_CLASS'} = $self-&gt;read_cover($mcount, $loc, $lookup, $fh, 0) if $mcount;
        }
        $fh-&gt;read($dat, $count &lt;&lt; 1);
        foreach $s (TTF_Unpack('S*', $dat))
        {
            if ($s == 0)
            {
                push (@{$lookup-&gt;{'RULES'}}, []);
                next;
            }
            @subst = ();
            $fh-&gt;seek($loc + $s, 0);
            $fh-&gt;read($dat, 2);
            $t = TTF_Unpack('S', $dat);
            $fh-&gt;read($dat, $t &lt;&lt; 1);
            foreach $i (TTF_Unpack('S*', $dat))
            {
                $fh-&gt;seek($loc + $s + $i, 0);
                @srec = ();
                $t = {};
                $fh-&gt;read($dat, 2);
                $mcount = TTF_Unpack('S', $dat);
                if ($mcount &gt; 0)
                {
                    $fh-&gt;read($dat, $mcount &lt;&lt; 1);
                    $t-&gt;{'PRE'} = [TTF_Unpack('S*', $dat)];
                }
                $fh-&gt;read($dat, 2);
                $mcount = TTF_Unpack('S', $dat);
                if ($mcount &gt; 1)
                {
                    $fh-&gt;read($dat, ($mcount - 1) &lt;&lt; 1);
                    $t-&gt;{'MATCH'} = [TTF_Unpack('S*', $dat)];
                }
                $fh-&gt;read($dat, 2);
                $mcount = TTF_Unpack('S', $dat);
                if ($mcount &gt; 0)
                {
                    $fh-&gt;read($dat, $mcount &lt;&lt; 1);
                    $t-&gt;{'POST'} = [TTF_Unpack('S*', $dat)];
                }
                $fh-&gt;read($dat, 2);
                $scount = TTF_Unpack('S', $dat);
                $fh-&gt;read($dat, $scount &lt;&lt; 2);
                for ($i = 0; $i &lt; $scount; $i++)
                { push (@srec, [TTF_Unpack('S2', substr($dat, $i &lt;&lt; 2))]); }
                $t-&gt;{'ACTION'} = [@srec];
                push (@subst, $t);
            }
            push (@{$lookup-&gt;{'RULES'}}, [@subst]);
        }
        $lookup-&gt;{'ACTION_TYPE'} = 'l';
        $lookup-&gt;{'MATCH_TYPE'} = ($fmt == 2 ? 'c' : 'g');
    } elsif ($type == 6 &amp;&amp; $fmt == 3)
    {
        $t = {};
        unless ($cover == 0)
        {
            @subst = ();
            $fh-&gt;read($dat, $cover &lt;&lt; 1);
            foreach $s (TTF_Unpack('S*', $dat))
            { push(@subst, $self-&gt;read_cover($s, $loc, $lookup, $fh, 1)); }
            $t-&gt;{'PRE'} = [@subst];
        }
        $fh-&gt;read($dat, 2);
        $count = TTF_Unpack('S', $dat);
        unless ($count == 0)
        {
            @subst = ();
            $fh-&gt;read($dat, $count &lt;&lt; 1);
            foreach $s (TTF_Unpack('S*', $dat))
            { push(@subst, $self-&gt;read_cover($s, $loc, $lookup, $fh, 1)); }
            $t-&gt;{'MATCH'} = [@subst];
        }
        $fh-&gt;read($dat, 2);
        $count = TTF_Unpack('S', $dat);
        unless ($count == 0)
        {
            @subst = ();
            $fh-&gt;read($dat, $count &lt;&lt; 1);
            foreach $s (TTF_Unpack('S*', $dat))
            { push(@subst, $self-&gt;read_cover($s, $loc, $lookup, $fh, 1)); }
            $t-&gt;{'POST'} = [@subst];
        }
        $fh-&gt;read($dat, 2);
        $count = TTF_Unpack('S', $dat);
        @subst = ();
        $fh-&gt;read($dat, $count &lt;&lt; 2);
        for ($i = 0; $i &lt; $count; $i++)
        { push (@subst, [TTF_Unpack('S2', substr($dat, $i &lt;&lt; 2, 4))]); }
        $t-&gt;{'ACTION'} = [@subst];
        $lookup-&gt;{'RULES'} = [[$t]];
        $lookup-&gt;{'ACTION_TYPE'} = 'l';
        $lookup-&gt;{'MATCH_TYPE'} = 'o';
    }
    $lookup;
}


=head2 $self-&gt;out_context($lookup, $fh, $type, $fmt, $ctables, $out, $num)

Provides shared behaviour between GSUB and GPOS tables during output for context
(chained and simple) rules. In addition, support is provided here for type 4 GSUB
tables, which are not used in GPOS. The value for $type corresponds to the type
in a GSUB table so calling from GPOS should adjust the value accordingly.

=cut

sub out_context
{
    my ($self, $lookup, $fh, $type, $fmt, $ctables, $out, $num, $base) = @_;
    my ($offc, $offd, $i, $j, $r, $t, $numd);

    $out ||= '';
    if (($type == 4 || $type == 5 || $type == 6) &amp;&amp; ($fmt == 1 || $fmt == 2))
    {
        my ($base_off);
        
        if ($fmt == 1)
        {
            $out = pack("nnn", $fmt, Font::TTF::Ttopen::ref_cache($lookup-&gt;{'COVERAGE'}, $ctables, 2 + $base),
                            $num);
            $base_off = 6;
        } elsif ($type == 5)
        {
            $out = pack("nnnn", $fmt, Font::TTF::Ttopen::ref_cache($lookup-&gt;{'COVERAGE'}, $ctables, 2 + $base),
                            Font::TTF::Ttopen::ref_cache($lookup-&gt;{'CLASS'}, $ctables, 4 + $base), $num);
            $base_off = 8;
        } elsif ($type == 6)
        {
            $out = pack("n6", $fmt, Font::TTF::Ttopen::ref_cache($lookup-&gt;{'COVERAGE'}, $ctables, 2 + $base),
                                Font::TTF::Ttopen::ref_cache($lookup-&gt;{'PRE_CLASS'}, $ctables, 4 + $base),
                                Font::TTF::Ttopen::ref_cache($lookup-&gt;{'CLASS'}, $ctables, 6 + $base),
                                Font::TTF::Ttopen::ref_cache($lookup-&gt;{'POST_CLASS'}, $ctables, 8 + $base),
                                $num);
            $base_off = 12;
        }

        $out .= pack('n*', (0) x $num);
        $offc = length($out);
        for ($i = 0; $i &lt; $num; $i++)
        {
            $r = $lookup-&gt;{'RULES'}[$i];
            next unless exists $r-&gt;[0]{'ACTION'};
            $numd = $#{$r} + 1;
            substr($out, ($i &lt;&lt; 1) + $base_off, 2) = pack('n', $offc);
            $out .= pack('n*', $numd, (0) x $numd);
            $offd = length($out) - $offc;
            for ($j = 0; $j &lt; $numd; $j++)
            {
                substr($out, $offc + 2 + ($j &lt;&lt; 1), 2) = pack('n', $offd);
                if ($type == 4)
                {
                    $out .= pack('n*', $r-&gt;[$j]{'ACTION'}[0], $#{$r-&gt;[$j]{'MATCH'}} + 2,
                                        @{$r-&gt;[$j]{'MATCH'}});
                } elsif ($type == 5)
                {
                    $out .= pack('n*', $#{$r-&gt;[$j]{'MATCH'}} + 2,
                                        $#{$r-&gt;[$j]{'ACTION'}} + 1,
                                        @{$r-&gt;[$j]{'MATCH'}});
                    foreach $t (@{$r-&gt;[$j]{'ACTION'}})
                    { $out .= pack('n2', @$t); }
                } elsif ($type == 6)
                {
                    $out .= pack('n*', $#{$r-&gt;[$j]{'PRE'}} + 1, @{$r-&gt;[$j]{'PRE'}},
                                    $#{$r-&gt;[$j]{'MATCH'}} + 2, @{$r-&gt;[$j]{'MATCH'}},
                                    $#{$r-&gt;[$j]{'POST'}} + 1, @{$r-&gt;[$j]{'POST'}},
                                    $#{$r-&gt;[$j]{'ACTION'}} + 1);
                    foreach $t (@{$r-&gt;[$j]{'ACTION'}})
                    { $out .= pack('n2', @$t); }
                }
                $offd = length($out) - $offc;
            }
            $offc = length($out);
        }
    } elsif ($type == 5 &amp;&amp; $fmt == 3)
    {
        $out .= pack('n3', $fmt, $#{$lookup-&gt;{'RULES'}[0][0]{'MATCH'}} + 1,
                                $#{$lookup-&gt;{'RULES'}[0][0]{'ACTION'}} + 1);
        foreach $t (@{$lookup-&gt;{'RULES'}[0][0]{'MATCH'}})
        { $out .= pack('n', Font::TTF::Ttopen::ref_cache($t, $ctables, length($out) + $base)); }
        foreach $t (@{$lookup-&gt;{'RULES'}[0][0]{'ACTION'}})
        { $out .= pack('n2', @$t); }
    } elsif ($type == 6 &amp;&amp; $fmt == 3)
    {
        $r = $lookup-&gt;{'RULES'}[0][0];
		no strict 'refs';	# temp fix - more code needed (probably "if" statements in the event 'PRE' or 'POST' are empty)
        $out .= pack('n2', $fmt, defined $r-&gt;{'PRE'} ? scalar @{$r-&gt;{'PRE'}} : 0);
        foreach $t (@{$r-&gt;{'PRE'}})
        { $out .= pack('n', Font::TTF::Ttopen::ref_cache($t, $ctables, length($out) + $base)); }
        $out .= pack('n', defined $r-&gt;{'MATCH'} ? scalar @{$r-&gt;{'MATCH'}} : 0);
        foreach $t (@{$r-&gt;{'MATCH'}})
        { $out .= pack('n', Font::TTF::Ttopen::ref_cache($t, $ctables, length($out) + $base)); }
        $out .= pack('n', defined $r-&gt;{'POST'} ? scalar @{$r-&gt;{'POST'}} : 0);
        foreach $t (@{$r-&gt;{'POST'}})
        { $out .= pack('n', Font::TTF::Ttopen::ref_cache($t, $ctables, length($out) + $base)); }
        $out .= pack('n', defined $r-&gt;{'ACTION'} ? scalar @{$r-&gt;{'ACTION'}} : 0);
        foreach $t (@{$r-&gt;{'ACTION'}})
        { $out .= pack('n2', @$t); }
    }
    $out;
}

=head1 BUGS

=over 4

=item *

No way to share cachable items (coverage tables, classes, anchors, device tables)
across different lookups. The items are always output after the lookup and
repeated if necessary. Within lookup sharing is possible.

=back

=head1 AUTHOR

Martin Hosken Martin_Hosken@sil.org. See L&lt;Font::TTF::Font&gt; for copyright and
licensing.

=cut

1;

</pre></body></html>