# PyFT -- Python's FreeType Wrapper

# Contents

- 1. Introduction
  - 1.1. Python Notes
  - 1.2. Extensions
  - 1.3. To Do
- 2. Structures
  - 2.1. class TT_UnitVector
  - 2.2. class TT_Vector
  - 2.3. class TT_Matrix
  - 2.4. class TT_Outline
  - 2.5. class TT_BBox
  - 2.6. class TT_Glyph_Metrics
  - 2.7. class TT_Big_Glyph_Metrics
  - 2.8. class TT_Instance_Metrics
  - 2.9. class TT_Raster_Map
  - 2.10. class TT_Header
  - 2.11. class TT_Horizontal_Header
  - 2.12. class TT_Vertical_Header
  - 2.13. class TT_OS2
  - 2.14. class TT_Postscript
  - 2.15. class TT_Hdmx_Record
  - 2.16. class TT_Hdmx
  - 2.17. class TT_Face_Properties
  - 2.18. class TT_Engine
  - 2.19. class TT_Instance
  - 2.20. class TT_Glyph
  - 2.21. Structure Helper Functions
    - 2.21.1. TT_Outline Helpers
    - 2.21.2. TT_Hdmx Helpers
  - 2.22. Raster Map Generation
  - 2.23. Flow Constants
- 3. Initialization
- 4. Face Management
- 5. Instance Management
- 6. Glyph Management
- 7. Outline Support
- 8. Character Mapping Support
- 9. Names Table Support
- 10. FreeType Extensions
  - 10.1. Kerning
    - 10.1.1. Structures
      - 10.1.1.1. class TT_Kern_0_Pair
      - 10.1.1.2. class TT_Kern_0
      - 10.1.1.3. class TT_Kern_2_Class
      - 10.1.1.4. class TT_Kern_2
      - 10.1.1.5. class TT_Kern_Subtable
      - 10.1.1.6. class TT_Kern_Subtable_t
      - 10.1.1.7. class TT_Kerning
    - 10.1.2. Functions
  - 10.2. cmap Iteration
  - 10.3. gasp Extension
  - 10.4. PostScript Glyph Names
    - 10.4.1. Structures
      - 10.4.1.1. class TT_Post_20
      - 10.4.1.2. class TT_Post_25
      - 10.4.1.3. class TT_Post
      - 10.4.1.4. class TT_Post_p
    - 10.4.2. Functions
  - 10.5. Glyph Widths
- 11. Memory Allocation Module
- 12. Memory Manipulation Module
- 13. Pointer Handling Library
- 14. Changes
- 15. Credits
- 16. Legal

## 1. Introduction

    Welcome to PyFT, a hopefully complete wrapping of the FreeType 1.3.1
    rendering engine for TrueType fonts.  Most of this is a direct and
    nearly exhaustive translation of the FreeType API.  A few of the
    functions have been given more "Pythonic" wrappings for convenience.
    There are also a couple of _de_novo_ convenience functions to access
    certain bits of data.

    Documenting FreeType itself is not my goal here.  The following
    documentation was gleaned almost entirely from the comments in the C
    headers.  To learn how to use the API, I refer you to the
    documentation distributed with the FreeType source code.
    Specifically, you will want to read the User Guide
    <URL: http://www.freetype.org/docs/user/user.txt>, skim the API Reference
    <URL: http://www.freetype.org/docs/api/freetype1.txt>, and read the
    Introduction to Glyphs <URL: http://www.freetype.org/glyphs/index.html>.  All
    of these documents are also included in the "docs" subdirectory of the
    binary PyFT distribution with some other useful documents.

### 1.1. Python Notes

    To make using FreeType from Python easier, I took some liberties with the API.

     * There is now an OO wrapper to the lower-level API.  It is contained in
       PyFT.py .  Please refer to its docstrings for documentation.  For simple
       uses, this will be the best API to use.

     * In C, most of the API functions return an error code; in Python,
       they either return None or the values that would be placed in their
       "output arguments" in C.  If an error occurs, the function will raise
       a "FreeTypeError" and display an appropriate error message.

     * Some of the API functions take a reference to an uninitialized
       structure and initialize that structure.  E.g.

         TT_Engine engine;
         TT_Face face;

         TT_Init_FreeType(&engine);
         TT_Open_Face(engine, "arial.ttf", &face);
         ...

       In Python, such functions do not take this argument and will return
       a suitably initialized structure.  The equivalent Python code is as follows:

         engine = TT_Init_FreeType()
         face = TT_Open_Face(engine, "arial.ttf")

       The exception to this exception is TT_Raster_Map, the structure
       that holds the bitmap and pixmap data.  Since they need extra
       parameters to specify them (say, height and width), they must be
       created by calling TT_Raster_Map(...) with the appropriate arguments.
       They are then passed to the rendering functions normally.

     * Similarly, for "output arguments" that are readily mapped to Python
       types (e.g. TT_Long becomes a PyInt), the function will return them
       in a tuple. E.g. the C code:

         ...
         TT_UShort platformID;
         TT_UShort encodingID;

         TT_Get_CharMap_ID(face, charmapIndex, &platformID, &encodingID);
         ...

       is replaced with

         platformID, encodingID = TT_Get_CharMap_ID(face, charmapIndex)

     * Due to the limitations of SWIG and/or my laziness to work around
       them, some members of structures can only be meaningfully accessed
       from helper functions. See the section "Structure Helper Functions".

     * Some of the structures have TT_Done_<Foo> functions that clean them
       up.  Getting the order of these right is somewhat tricky.  USE WITH
       EXTREME CAUTION.  Be sure not to access their pointers after using
       these functions.

     * The Python function 'toImage' will take a TT_Raster_Map and convert
       it to a PIL Image.

         Image = toImage(rasterMap, type='bit')

       The keyword argument can be either 'bit' for a bitmap or 'pix' for
       an antialiased pixmap.

       Similarly, the 'toMask' function will return a bit-/pixmap that can
       be used as an alpha mask; most useful for pasting text onto previous
       PIL images.

     * Convenience functions 'FLOOR' and 'CEIL' are for rounding integers
       to a multiple of 64.

     * Functions 'rotation' and 'skew' will return TT_Matrix's for
       rotating by an angle and skewing.

     * Memory and pointer manipulation functions from SWIG are also
       exposed.  They are documented in later sections.  You will probably
       never need to use them, but power users might enjoy their presence.

### 1.2. Extensions

    There are several extensions to the core FreeType renderer.  The
    following are exposed in PyFT:

      ftxkern:  Access to the kerning tables given by each font.
                The wrapping is somewhat non-functional at the moment. I
    	    need to figure out what one is supposed to do with the
    	    kerning structures before I can wrap the intelligently.  I
    	    have included them here mostly because I like seeing my
    	    name littered through the source code.  :-) Be sure to
    	    call TT_Init_Kerning_Extension(engine) first!

      ftxcmap:  Iteration over the 'cmap' table.
    	    You probably won't need this extension.  Python offers
                better ways to get the information you need from the
                standard character map functions.  Nonetheless, it's here
                for your enjoyment.

      ftxgasp:  Access to the 'gasp' table.
    	    If you know why you would need this information, this is
    	    where to get it from.

      ftxpost:  PostScript glyph names.
    	    You can obtain the PostScript names of each glyph from the
    	    functions from this extension.  Be sure to call
    	    TT_Init_Post_Extension(engine) first!

      ftxwidth: Glyph widths.
    	    Get the widths for a range of glyphs.

    The ftxerr18 extension converts error codes into error messages.  The
    error handler uses this extension internally, so that you will never
    see a bare error code.  Thus its API does not need to be exposed here.

    The other FreeType extensions are (as of version 1.3.1) still
    experimental (with the exception of ftxsbit, which I will get around
    to soon), so I won't bother wrapping them just yet.

    When compiling PyFT, your FreeType library must include the following
    extensions:

      ftxkern
      ftxcmap
      ftxgasp
      ftxpost
      ftxwidth
      ftxerr18

### 1.3. To Do

     * Write a converter from a TrueType font to a PIL font.

     * Extend piddlePIL to optionally use TTF fonts to draw text.

     * Clean up code.  The Python code is needlessly ugly and uncommented.

     * *** Fix Memory Leaks! *** They are probably rampant here.  There is
       a reason why I like Python; I do not have to think about such
       things.

## 2. Structures

### 2.1. class TT_UnitVector

`self.x`

`self.y`

`TT_UnitVector()`

`del this`

### 2.2. class TT_Vector

`self.x`

`self.y`

`TT_Vector()`

`del this`

### 2.3. class TT_Matrix

     A simple 2x2 matrix used for transformations.
     You should use 16.16 fixed floats.

       x' = xx*x + xy*y
       y' = yx*x + yy*y

`self.xx`

`self.xy`

`self.yx`

`self.yy`

`TT_Matrix()`

`del this`

### 2.4. class TT_Outline

    A structure used to describe the source glyph to the renderer.

`self.n_contours`

>     number of contours in glyph

`self.n_points`

>     number of points in the glyph

`self.points`

>     the outline's points

`self.flags`

>     the points flags

`self.contours`

>     the contour end points

`self.owner`

>     The owner flag indicates that the outline owns the arrays it
>     refers to.  Typically, this is true of outlines created from the
>     TT_New_Outline() API, while it isn't for those returned by
>     TT_Get_Glyph_Outline().

`self.high_precision`

>     When true, the scan-line converter will use
>     a higher precision to render bitmaps (i.e. a
>     1/1024 pixel precision).  This is important for
>     small ppem sizes.

`self.second_pass`

>     When true, the scan-line converter performs
>     a second sweep phase dedicated to find
>     vertical drop-outs.  If false, only horizontal
>     drop-outs will be checked during the first
>     vertical sweep (yes, this is a bit confusing
>     but it's really the way it should work).
>     This is important for small ppems too.

`self.dropout_mode`

>     Specifies the TrueType drop-out mode to
>     use for continuity checking. valid values
>     are 0 (no check), 1, 2, 4, and 5.

### 2.5. class TT_BBox

    A structure used to describe a simple bounding box

`self.xMin`

`self.yMin`

`self.xMax`

`self.yMax`

### 2.6. class TT_Glyph_Metrics

    A structure used to return glyph metrics.

    The "bearingX" isn't called "left-side bearing" anymore because
    it has different meanings depending on the glyph's orientation.

    The same is true for "bearingY", which is the top-side bearing
    defined by the TT_Spec, i.e., the distance from the baseline to
    the top of the glyph's bbox.  According to our current convention,
    this is always the same as "bbox.yMax" but we make it appear for
    consistency in its proper field.

    The "advance" width is the advance width for horizontal layout,
    and advance height for vertical layouts.

    Finally, the library (ver. 1.1) doesn't support vertical text yet but
    these changes were introduced to accomodate it, as it will most
    certainly be introduced in later releases.

`self.bbox`

>     glyph bounding box

`self.bearingX`

>     left-side bearing

`self.bearingY`

>     top-side bearing, per se the TT spec

`self.advance`

>     advance width (or height)

### 2.7. class TT_Big_Glyph_Metrics

    A structure used to return horizontal _and_ vertical glyph
    metrics.

    A glyph can be used either in a horizontal or vertical layout.
    Its glyph metrics vary with orientation.  The Big_Glyph_Metrics
    structure is used to return _all_ metrics in one call.

    This structure is currently unused.

`self.bbox`

>     glyph bounding box

`self.horiBearingX`

>     left side bearing in horizontal layouts

`self.horiBearingY`

>     top side bearing in horizontal layouts

`self.vertBearingX`

>     left side bearing in vertical layouts

`self.vertBearingY`

>     top side bearing in vertical layouts

`self.horiAdvance`

>     advance width for horizontal layout

`self.vertAdvance`

>     advance height for vertical layout

`self.linearHoriBearingX`

>     linearly scaled horizontal lsb

`self.linearHoriAdvance`

>     linearly scaled horizontal advance

`self.linearVertBearingY`

>     linearly scaled vertical tsb

`self.linearVertAdvance`

>     linearly scaled vertical advance

### 2.8. class TT_Instance_Metrics

    A structure used to return instance metrics.

`self.pointSize`

>     char. size in points (1pt = 1/72 inch)

`self.x_ppem`

>     horizontal pixels per EM square

`self.y_ppem`

>     vertical pixels per EM square

`self.x_scale`

>     16.16 to convert from EM units to 26.6 pix

`self.y_scale`

>     16.16 to convert from EM units to 26.6 pix

`self.x_resolution`

>     device horizontal resolution in dpi

`self.y_resolution`

>     device vertical resolution in dpi

### 2.9. class TT_Raster_Map

    A structure used to describe the target bitmap or pixmap to the
    renderer.  Note that there is nothing in this structure that
    gives the nature of the buffer.

    IMPORTANT NOTE:

      In the case of a pixmap, the 'width' and 'cols' fields must
      have the _same_ values, and _must_ be padded to 32-bits, i.e.,
      be a multiple of 4.  Clipping problems will arise otherwise,
      if not even page faults!

      The typical settings are:

      - for an WxH bitmap:

          rows  = H
          cols  = (W+7)/8
          width = W
          flow  = your_choice

      - for an WxH pixmap:

          rows  = H
          cols  = (W+3) & ~3
          width = cols
          flow  = your_choice

`self.rows`

>     number of rows

`self.cols`

>     number of columns (bytes) per row

`self.width`

>     number of pixels per line

`self.flow`

>     bitmap orientation

`self.bitmap`

>     bit/pixmap buffer

`self.size`

>     bit/pixmap size in bytes

`tostring()`

`tobuffer()`

`TT_Raster_Map(width,height,type)`

>     Create a new TT_Raster_Map.  'width' and 'height' are in pixels.  'type'
>     is "bit" for a bitmap or "pix" for a pixmap.

### 2.10. class TT_Header

    The font header TrueType table structure

`self.Table_Version`

`self.Font_Revision`

`self.CheckSum_Adjust`

`self.Magic_Number`

`self.Flags`

`self.Units_Per_EM`

`self.Created`

`self.Modified`

`self.xMin`

`self.yMin`

`self.xMax`

`self.yMax`

`self.Mac_Style`

`self.Lowest_Rec_PPEM`

`self.Font_Direction`

`self.Index_To_Loc_Format`

`self.Glyph_Data_Format`

### 2.11. class TT_Horizontal_Header

    The horizontal header TrueType table structure

    This structure is the one defined by the TrueType
    specification, plus two fields used to link the
    font-units metrics to the header.

`self.Version`

`self.Ascender`

`self.Descender`

`self.Line_Gap`

`self.advance_Width_Max`

>     advance width maximum

`self.min_Left_Side_Bearing`

>     minimum left-sb

`self.min_Right_Side_Bearing`

>     minimum right-sb

`self.xMax_Extent`

>     xmax extents

`self.caret_Slope_Rise`

`self.caret_Slope_Run`

`self.Reserved0`

`self.Reserved1`

`self.Reserved2`

`self.Reserved3`

`self.Reserved4`

`self.metric_Data_Format`

`self.number_Of_HMetrics`

`self.long_metrics`

`self.short_metrics`

### 2.12. class TT_Vertical_Header

    The vertical header TrueType table structure

    This structure is the one defined by the TrueType
    specification.  Note that it has exactly the same
    layout as the horizontal header (both are loaded
    by the same function).

`self.Version`

`self.Ascender`

`self.Descender`

`self.Line_Gap`

`self.advance_Height_Max`

>     advance height maximum

`self.min_Top_Side_Bearing`

>     minimum left-sb or top-sb

`self.min_Bottom_Side_Bearing`

>     minimum right-sb or bottom-sb

`self.yMax_Extent`

>     xmax or ymax extents

`self.caret_Slope_Rise`

`self.caret_Slope_Run`

`self.caret_Offset`

`self.Reserved1`

`self.Reserved2`

`self.Reserved3`

`self.Reserved4`

`self.metric_Data_Format`

`self.number_Of_VMetrics`

`self.long_metrics`

`self.short_metrics`

### 2.13. class TT_OS2

    OS/2 Table

`self.version`

>     0x0001

`self.xAvgCharWidth`

`self.usWeightClass`

`self.usWidthClass`

`self.fsType`

`self.ySubscriptXSize`

`self.ySubscriptYSize`

`self.ySubscriptXOffset`

`self.ySubscriptYOffset`

`self.ySuperscriptXSize`

`self.ySuperscriptYSize`

`self.ySuperscriptXOffset`

`self.ySuperscriptYOffset`

`self.yStrikeoutSize`

`self.yStrikeoutPosition`

`self.sFamilyClass`

`self.panose`

`self.ulUnicodeRange1`

>     Bits 0-31

`self.ulUnicodeRange2`

>     Bits 32-63

`self.ulUnicodeRange3`

>     Bits 64-95

`self.ulUnicodeRange4`

>     Bits 96-127

`self.achVendID`

`self.fsSelection`

`self.usFirstCharIndex`

`self.usLastCharIndex`

`self.sTypoAscender`

`self.sTypoDescender`

`self.sTypoLineGap`

`self.usWinAscent`

`self.usWinDescent`

`self.ulCodePageRange1`

>     Bits 0-31

`self.ulCodePageRange2`

>     Bits 32-63

### 2.14. class TT_Postscript

    Postscript table

    Glyph names follow in the file, but we don't
    load them by default.  See the ftxpost.c extension.

`self.FormatType`

`self.italicAngle`

`self.underlinePosition`

`self.underlineThickness`

`self.isFixedPitch`

`self.minMemType42`

`self.maxMemType42`

`self.minMemType1`

`self.maxMemType1`

### 2.15. class TT_Hdmx_Record

    horizontal device metrics "hdmx"

`self.ppem`

`self.max_width`

`self.widths`

### 2.16. class TT_Hdmx

    horizontal device metrics "hdmx"

`self.version`

`self.num_records`

`self.records`

### 2.17. class TT_Face_Properties

    A structure used to describe face properties.

`self.num_Glyphs`

>     number of glyphs in face

`self.max_Points`

>     maximum number of points in a glyph

`self.max_Contours`

>     maximum number of contours in a glyph

`self.num_CharMaps`

>     number of charmaps in the face

`self.num_Names`

>     number of name records in the face

`self.num_Faces`

>     1 for normal TrueType files, and the number
>     of embedded faces for TrueType collections

`self.header`

>     TrueType header table

`self.horizontal`

>     TrueType horizontal header

`self.os2`

>     TrueType OS/2 table

`self.postscript`

>     TrueType Postscript table

`self.hdmx`

`self.vertical`

>     TT Vertical header, if present

### 2.18. class TT_Engine

    engine instance

`self.z`

### 2.19. class TT_Instance

    instance handle type

`self.z`

### 2.20. class TT_Glyph

    glyph handle type

`self.z`

### 2.21. Structure Helper Functions

     Since I cannot get SWIG to meaningfully handle some of the
    structure members, I have the following functions to return
    appropriate values for these members.  See the documentation under the
    various structures for the meanings of these members.

#### 2.21.1. TT_Outline Helpers

`getOutlinePoints(outline)`

>     Returns the 'points' member as a list of 2-tuples.  Note that this
>     is not a list of TT_Vector instances.

`getOutlineFlags(outline)`

>     Returns the 'flags' member as a tuple of length 'n_points'.  Rather
>     than representing the actual value that is stored, each element of
>     the tuple is either 0 or 1 depending on whether the corresponding
>     point is off or on the curve, respectively.

`getOutlineContours(outline)`

>     Returns the 'contours' member as a tuple of length 'n_contours'.
>     The returned tuple is a direct mapping from the internal C
>     representation to the Python representation.

#### 2.21.2. TT_Hdmx Helpers

`getHdmxRecords(hdmx)`

>     Returns the 'records' member as a list of TT_Hdmx_Record's.

### 2.22. Raster Map Generation

`newBitmap(width,height)`

>     Create a TT_Raster_Map bitmap structure from the width and height.

`newPixmap(width,height)`

>     Create a TT_Raster_Map pixmap structure from the width and height.

### 2.23. Flow Constants

    The flow of a bitmap refers to the way lines are oriented
    within the bitmap data, i.e., the orientation of the Y
    coordinate axis.

    For example, if the first bytes of the bitmap pertain to
    its top-most line, then the flow is 'down'.  If these bytes
    pertain to its lowest line, the the flow is 'up'.

`TT_Flow_Down = -1`

`TT_Flow_Up = 1`

`TT_Flow_Error = 0`

## 3. Initialization

`TT_Init_FreeType()`

>     Initialize the engine.

>       Python Note:
>         Returns a TT_Engine.  You do not need to pass this function
>         a pointer like you do in C.

`TT_Done_FreeType(engine)`

`TT_Set_Raster_Gray_Palette(engine,palette)`

>     Set the gray level palette.  This is an array of 5 bytes used
>     to produce the font smoothed pixmaps.  By convention:

>        palette[0] = background (white)
>        palette[1] = light
>        palette[2] = medium
>        palette[3] = dark
>        palette[4] = foreground (black)

>     Python Note:
>        Use a sequence of five integers like so:

>          TT_Set_Raster_Gray_Palette(engine, (0, 64, 128, 192, 255))

>        'newPixmap' automatically sets the pixmap to 0's.  The rendering
>        engine will sometimes leave a a group of pixels unaltered if they
>        all should be set to palette[0], so do not rely on palette[0]'s
>        being something other than 0 to paint that color in.

## 4. Face Management

`TT_Open_Face(engine,fontPathName)`

>     Open a new TrueType font file, and returns a handle for
>     it.

>     Note: The file can be either a TrueType file (*.ttf) or
>           a TrueType collection (*.ttc, in this case, only
>           the first face is opened).  The number of faces in
>           the same collection can be obtained in the face's
>           properties, using TT_Get_Face_Properties() and the
>           'max_Faces' field.

>     Python Note:
>       Returns a TT_Face.  You do not need to pass this function
>       a pointer like you do in C.

`TT_Open_Collection(engine,collectionPathName,fontIndex)`

>     Open a TrueType font file located inside a collection.
>     The font is assigned by its index in 'fontIndex'.

>     Python Note:
>       Returns a TT_Face.  You do not need to pass this function
>       a pointer like you do in C.

`TT_Get_Face_Properties(face)`

>     Return face properties.

>     Python Note:
>       Returns a TT_Face_Properties.  You do not need to pass this function
>       a pointer like you do in C.

`TT_Flush_Face(face)`

>     Close a face's file handle to save system resources.  The file
>     will be re-opened automatically on the next disk access.

`TT_Get_Face_Metrics(face,firstGlyph,lastGlyph)`

>     Get a face's glyph metrics expressed in font units.

>     Python Note:
>       Returns the arrays as a tuple:

>         leftBearings, widths, \
>           topBearings, heights = TT_Get_Face_Metrics(face,
>                                                      firstGlyph,
>                                                      lastGlyph)

>       Values of 'None' mean that there are no vertical metrics in the face.

`TT_Close_Face(face)`

>     Close a given font object, destroying all associated instances.

`TT_Get_Font_Data(face,table,offset)`

>     Get font or table data.

>     Python Note:
>       The Python function differs from the C function in the following ways:

>         1. Instead of a numerical 'tag', the Python function takes the
>            table name as a string.  I.e. to get the data from the
>            'eblc' table, you simply pass the string 'eblc' as the
>            second argument rather than MAKE_TT_TAG('e', 'b', 'l', 'c').

>         2. The buffer is returned to you as a string.  What you can do
>            with it, I have no idea, but I am sure that someone will
>            find a clever trick.

## 5. Instance Management

`TT_New_Instance(face)`

>     Open a new font instance and returns an instance handle
>     for it.

>     Python Note:
>       Returns a TT_Instance.  You do not need to pass this function
>       a pointer like you do in C.

`TT_Set_Instance_Resolutions(instance,xResolution,yResolution)`

>     Set device resolution for a given instance.  The values are
>     given in dpi (Dots Per Inch).  Default is 96 in both directions.

`TT_Set_Instance_CharSize(instance,charSize)`

>     Set the pointsize (in 1/64 points) for a given instance.  Default is 10pt.

>     charSize = pointSize * 64
>     e.g. for a 12pt fontsize, charSize = 12 * 64 = 768

`TT_Set_Instance_CharSizes(instance,charWidth,charHeight)`

`TT_Set_Instance_PointSize(instance,ptsize)`

>     Set the pointsize (in points) for a given instance.  Default is 10pt.

`TT_Set_Instance_PixelSizes(instance,pixelWidth,pixelHeight,pointSize)`

`TT_Get_Instance_Metrics(instance)`

>     Return instance metrics.

>     Python Note:
>       Returns a TT_Instance_Metrics.  You do not need to pass this function
>       a pointer like you do in C.

`TT_Done_Instance(instance)`

## 6. Glyph Management

`TT_New_Glyph(face)`

>     Create a new glyph object related to the given 'face'.

>     Python Note:
>       Returns a TT_Glyph.  You do not need to pass this function
>       a pointer like you do in C.

`TT_Done_Glyph(glyph)`

`TTLOAD_SCALE_GLYPH = 1`

`TTLOAD_HINT_GLYPH = 2`

`TTLOAD_DEFAULT = 3`

`TT_Load_Glyph(instance,glyph,glyphIndex,loadFlags)`

>     Load and process (scale/transform and hint) a glyph from the
>     given 'instance'.  The glyph and instance handles must be
>     related to the same face object.  The glyph index can be
>     computed with a call to TT_Char_Index().

>     The 'load_flags' argument is a combination of the macros
>     TTLOAD_SCALE_GLYPH and TTLOAD_HINT_GLYPH.  Hinting will be
>     applied only if the scaling is selected.

>     When scaling is off (i.e., load_flags = 0), the returned
>     outlines are in EM square coordinates (also called FUnits),
>     extracted directly from the font with no hinting.
>     Other glyph metrics are also in FUnits.

>     When scaling is on, the returned outlines are in fractional
>     pixel units (i.e. signed long = 26.6 fixed floats).

>     NOTE:  The glyph index must be in the range 0..num_glyphs-1
>            where 'num_glyphs' is the total number of glyphs in
>            the font file (given in the face properties).

`TT_Get_Glyph_Outline(glyph)`

>     Return glyph outline pointers in 'outline'.  Note that the returned
>     pointers are owned by the glyph object, and will be destroyed with
>     it.  The client application should _not_ change the pointers.

>     Python Note:
>       Returns a TT_Outline.  You do not need to pass this function
>       a pointer like you do in C.

`TT_Get_Glyph_Metrics(glyph)`

>     Copy the glyph metrics into 'metrics'.

>     Python Note:
>       Returns a TT_Glyph_Metrics.  You do not need to pass this function
>       a pointer like you do in C.

`TT_Get_Glyph_Big_Metrics(glyph)`

>     Copy the glyph's big metrics into 'metrics'.
>     Necessary to obtain vertical metrics.

>     Python Note:
>       Returns a TT_Big_Glyph_Metrics.  You do not need to pass this function
>       a pointer like you do in C.

`TT_Get_Glyph_Bitmap(glyph,map,xOffset,yOffset)`

>     Render the glyph into a bitmap, with given position offsets.

>     Note:  Only use integer pixel offsets to preserve the fine
>            hinting of the glyph and the 'correct' anti-aliasing
>            (where vertical and horizontal stems aren't grayed).
>            This means that xOffset and yOffset must be multiples
>            of 64!

`TT_Get_Glyph_Pixmap(glyph,map,xOffset,yOffset)`

>     Render the glyph into a pixmap, with given position offsets.

>     Note: Only use integer pixel offsets to preserve the fine
>           hinting of the glyph and the 'correct' anti-aliasing
>           (where vertical and horizontal stems aren't grayed).
>           This means that xOffset and yOffset must be multiples
>           of 64!

## 7. Outline Support

`TT_New_Outline(numPoints,numContours)`

>     Allocate a new outline.  Reserve space for 'numPoints' and 'numContours'.

>     Python Note:
>       Returns a TT_Outline.  You do not need to pass this function
>       a pointer like you do in C.

`TT_Done_Outline(outline)`

`TT_Copy_Outline(source)`

>     Copy an outline to another one.

>     Python Note:
>       Returns a TT_Outline.  You do not need to pass this function
>       a pointer like you do in C.

`TT_Get_Outline_Bitmap(engine,outline,map)`

>     Render an outline into a bitmap.

`TT_Get_Outline_Pixmap(engine,outline,map)`

>     Render an outline into a pixmap -- note that this function uses
>     a different pixel scale, where 1.0 pixels = 128

`TT_Get_Outline_BBox(outline)`

>     Return an outline's bounding box -- this function is slow as it
>     performs a complete scan-line process, without drawing, to get
>     the most accurate values.

>     Python Note:
>       Returns a TT_BBox.  You do not need to pass this function
>       a pointer like you do in C.

`TT_Transform_Outline(outline,matrix)`

>     Apply a transformation to a glyph outline.

`TT_Translate_Outline(outline,xOffset,yOffset)`

>     Apply a translation to a glyph outline.

`TT_Transform_Vector(x,y,matrix)`

>     Apply a transformation to a vector.

>     Python Note:

>       x, y = TT_Transform_Vector(x, y, matrix)

`TT_MulDiv(A,B,C)`

>     Compute A*B/C with 64 bits intermediate precision.

`TT_MulFix(A,B)`

>     Compute A*B/0x10000 with 64 bits intermediate precision.
>     Useful to multiply by a 16.16 fixed float value.

## 8. Character Mapping Support

`TT_Get_CharMap_ID(face,charmapIndex)`

>     Return the ID of charmap number 'charmapIndex' of a given face
>     used to enumerate the charmaps present in a TrueType file.

>     Common character mappings:
>       platformID encodingID : Mapping Name
>       0          0          : Apple Unicode
>       1          0          : Apple Roman
>       3          0          : Windows Symbol
>       3          1          : Windows Unicode

>     Python Note:

>       platformID, encodingID = TT_Get_CharMap_ID(face, charmapIndex)

`TT_Get_CharMap(face,charmapIndex)`

>     Look up the character maps found in 'face' and return a handle
>     for the one matching 'platformID' and 'platformEncodingID'
>     (see the TrueType specs relating to the 'cmap' table for
>     information on these ID numbers).

>     Python Note:
>       Returns a TT_CharMap.  You do not need to pass this function
>       a pointer like you do in C.

`pTT_Char_Index(charMap,inputChar)`

>     Return the index of the character inputChar in the character map.

`pTT_String_Indices(charMap,inputString)`

>     Return the indices of the characters in inputString as a tuple.

>     E.g.

>       a, b, c = pTT_String_Indices(charMap, 'abc')

`TT_Char_Index(charMap,charCode)`

>     Translate a character code through a given character map
>     and return the corresponding glyph index to be used in
>     a TT_Load_Glyph call.

>     Python Note:
>       For the Windows Unicode mapping (3,1),

>         charCode = ord(character)
>         (I think)

>       However, the use of this function is not recommended.

>       pTT_String_Indices(charMap, string) --> list of indices
>       and
>       pTT_Char_Index(charMap, character) --> index

>       are much more Pythonic.

## 9. Names Table Support

`TT_Get_Name_ID(face,nameIndex)`

>     Return the ID of the name number 'nameIndex' of a given face used
>     to enumerate the charmaps present in a TrueType file.

>     Python Note:

>       platformID, encodingID, languageID, nameID = TT_Get_Name_ID(face, nameIndex)

`TT_Get_Name_String(face,nameIndex)`

>     Return the address and length of the name number 'nameIndex' of a
>     given face.  The string is part of the face object and shouldn't be
>     written to or released.

>     Note that if for an invalid platformID a null pointer will be
>     returned.

## 10. FreeType Extensions

### 10.1. Kerning

#### 10.1.1. Structures

#### 10.1.1.1. class TT_Kern_0_Pair

    format 0 kerning pair

`self.left`

>     index of left  glyph in pair

`self.right`

>     index of right glyph in pair

`self.value`

>     kerning value

#### 10.1.1.2. class TT_Kern_0

    format 0 kerning subtable

`self.nPairs`

>     number of kerning pairs

`self.searchRange`

`self.entrySelector`

`self.rangeShift`

`self.pairs`

>     a table of nPairs `pairs'

#### 10.1.1.3. class TT_Kern_2_Class

    format 2 kerning glyph class

`self.firstGlyph`

>     first glyph in range

`self.nGlyphs`

>     number of glyphs in range

`self.classes`

>     a table giving for each ranged glyph its class offset in the
>     subtable pairs two-dimensional array

#### 10.1.1.4. class TT_Kern_2

    format 2 kerning subtable

`self.rowWidth`

>     length of one row in bytes

`self.leftClass`

>     left class table

`self.rightClass`

>     right class table

`self.array`

>     2-dimensional kerning values array

#### 10.1.1.5. class TT_Kern_Subtable

    kerning subtable

`self.loaded`

>     boolean; indicates whether the table is
>                              loaded

`self.version`

>     table version number

`self.offset`

>     file offset of table

`self.length`

>     length of table, _excluding_ header

`self.coverage`

>     lower 8 bit of the coverage table entry

`self.format`

>     the subtable format, as found in the higher 8 bits of the
>        coverage table entry

`self.t`

#### 10.1.1.6. class TT_Kern_Subtable_t

`self.kern0`

`self.kern2`

#### 10.1.1.7. class TT_Kerning

`self.version`

>     kern table version number. starts at 0

`self.nTables`

>     number of tables

`self.tables`

>     the kerning sub-tables

#### 10.1.2. Functions

`TT_Init_Kerning_Extension(engine)`

>     Initialize Kerning extension, must be called after
>     TT_Init_FreeType(). There is no need for a finalizer.

>     Note on the implemented mechanism:

>       The kerning table directory is loaded with the face through the
>       extension constructor.  However, the tables will only be loaded
>       on demand, as they may represent a lot of data, unnecessary to
>       most applications.

`TT_Get_Kerning_Directory(face)`

>     Queries a pointer to the kerning directory for the face object

>     Python Note:
>       Returns a TT_Kerning.  You do not need to pass this function
>       a pointer like you do in C.

`TT_Load_Kerning_Table(face,kern_index)`

>     Load the kerning table number `kern_index' in the kerning
>     directory.  The table will stay in memory until the `face'
>     face is destroyed.

### 10.2. cmap Iteration

`TT_CharMap_First(charMap)`

>     Find the first entry of a Cmap.

>     Python Note:
>       The return value is a 2-tuple of the first valid character
>       code in charMap and the first glyph index.

`TT_CharMap_Next(charMap,startId)`

>     Find the next entry of Cmap.  Same return conventions.

>     Python Note:
>       The return value is a 2-tuple of the next valid character
>       code in charMap and its corresponding glyph index.

`TT_CharMap_Last(charMap)`

>     Find the last entry of a Cmap.

>     Python Note:
>       The return value is a 2-tuple of the last valid character
>       code in charMap and the last glyph index.

### 10.3. gasp Extension

`TT_Get_Face_Gasp_Flags(face,point_size)`

### 10.4. PostScript Glyph Names

#### 10.4.1. Structures

#### 10.4.1.1. class TT_Post_20

    format 2.0 table

`self.numGlyphs`

`self.glyphNameIndex`

`self.glyphNames`

#### 10.4.1.2. class TT_Post_25

`self.numGlyphs`

`self.offset`

#### 10.4.1.3. class TT_Post

    This structure holds the information needed by TT_Get_PS_Name.
    Although, it is not passed as an argument in that function and one
    should access it's contents directly, I believe that it is
    necessary to have it available in memory when TT_Get_PS_Name is
    called.  Therefore, be sure to create one with TT_Load_PS_Names and
    don't let it be deleted until you are finished.

`self.offset`

`self.length`

`self.loaded`

`self.p`

#### 10.4.1.4. class TT_Post_p

`self.post20`

`self.post25`

#### 10.4.2. Functions

`TT_Init_Post_Extension(engine)`

`TT_Load_PS_Names(face)`

>     Python Note:
>       Returns a TT_Post.  You do not need to pass this function
>       a pointer like you do in C.

`TT_Get_PS_Name(face,index)`

### 10.5. Glyph Widths

`TT_Get_Face_Widths(face,first_glyph,last_glyph)`

>     Description: Returns the widths and/or heights of a given
>                  range of glyphs for a face.

>     Input:
>       face        ::  face handle

>       first_glyph ::  first glyph in range

>       last_glyph  ::  last glyph in range

>     Returns:
>       widths      ::  widths expressed in font units (ushorts).

>       heights     ::  heights expressed in font units (ushorts).

>     Python Note:
>       Returns the 2-tuple of tuples (widths, heights).

>       A value of 'None' in 'heights' means that there are no vertical
>       metrics in the font file.

## 11. Memory Allocation Module

    %include malloc.i

    This module provides access to a few basic C memory management functions.
    All functions return void pointers, but realloc() and free() will operate
    on any sort of pointer.   Sizes should be specified in bytes.

`calloc(nobj,size)`

>     [ returns void * ]
>     Returns a pointer to a space for an array of nobj objects, each with
>     size bytes.   Returns NULL if the request can't be satisfied.
>     Initializes the space to zero bytes.

`malloc(size)`

>     [ returns void * ]
>     Returns a pointer to space for an object of size bytes.  Returns NULL
>     upon failure.

`realloc(ptr,size)`

>     [ returns void * ]
>     Changes the size of the object pointed to by ptr to size bytes.
>     The contents will be unchanged up the minimum of the old and new
>     sizes.  Returns a pointer to the new space of NULL upon failure,
>     in which case *ptr is unchanged.

`free(ptr)`

>     [ returns void  ]
>     Deallocates the space pointed to by ptr.  Does nothing if ptr is NULL.
>     ptr must be a space previously allocated by calloc, malloc, or realloc.

## 12. Memory Manipulation Module

    %include memory.i

    This module provides support for a few memory operations from the C
    <string.h> library.  These functions can be used to manipulate binary
    data. s and t are of type void *, cs and ct are both of type const void *.

`memcpy(s,ct,n)`

>     [ returns void * ]
>     Copy n characters from ct to s, and return s

`memmove(s,ct,n)`

>     [ returns void * ]
>     Same as memcpy except that it works even if the objects overlap.

`memcmp(cs,ct,n)`

>     [ returns int  ]
>     Compare the first n characters of cs with ct.  Returns 0 if
>     they are equal, <0 if cs < ct, and >0 if cs > ct.

`memchr(cs,c,n)`

>     [ returns void * ]
>     Returns pointer to the first occurrence of character c in cs.

`memset(s,c,n)`

>     [ returns void * ]
>     Place character c into first n characters of s, return s

## 13. Pointer Handling Library

    %include pointer.i

    The pointer.i library provides run-time support for managing and
    manipulating a variety of C/C++ pointer values.  In particular,
    you can create various kinds of objects and dereference common
    pointer types.  This is done through a common set of functions:

        ptrcast      - Casts a pointer to a new type
        ptrvalue     - Dereferences a pointer
        ptrset       - Set the value of an object referenced by
                       a pointer.
        ptrcreate    - Create a new object and return a pointer.
        ptrfree      - Free the memory allocated by ptrcreate.
        ptradd       - Increment/decrement a pointer value.
        ptrmap       - Make two datatypes equivalent to each other.
                       (Is a runtime equivalent of typedef).

    When creating, dereferencing, or setting the value of pointer
    variable, only the common C datatypes of int, short, long, float,
    double, char, and char * are currently supported.   Other
    datatypes may generate an error.

    One of the more interesting aspects of this library is that
    it operates with a wide range of datatypes.  For example,
    the "ptrvalue" function can dereference "double *", "int *",
    "long *", "char *", and other datatypes. Since SWIG encodes
    pointers with type information, this can be done transparently
    and in most cases, you can dereference a pointer without
    ever knowing what type it actually is.

    This library is primarily designed for utility, not high
    performance (the dynamic determination of pointer types takes
    more work than most normal wrapper functions).  As a result,
    you may achieve better performance by writing customized
    "helper" functions if you're making lots of calls to these
    functions in inner loops or other intensive operations.

`ptrcast(ptr,type)`

>     Casts a pointer ptr to a new datatype given by the string type.
>     type may be either the SWIG generated representation of a datatype
>     or the C representation.  For example :

>        ptrcast(ptr,"double_p");   # Python representation
>        ptrcast(ptr,"double *");    # C representation

>     A new pointer value is returned.   ptr may also be an integer
>     value in which case the value will be used to set the pointer
>     value.  For example :

>        a = ptrcast(0,"Vector_p");

>     Will create a NULL pointer of type "Vector_p"

>     The casting operation is sensitive to formatting.  As a result,
>     "double *" is different than "double*".  As a result of thumb,
>     there should always be exactly one space between the C datatype
>     and any pointer specifiers (*).

`ptrvalue(ptr,index,type)`

>     Returns the value that a pointer is pointing to (ie. dereferencing).
>     The type is automatically inferred by the pointer type--thus, an
>     integer pointer will return an integer, a double will return a double,
>     and so on.   The index and type fields are optional parameters.  When
>     an index is specified, this function returns the value of ptr[index].
>     This allows array access.   When a type is specified, it overrides
>     the given pointer type.   Examples :

>        ptrvalue(a)             #  Returns the value *a
>        ptrvalue(a,10)          #  Returns the value a[10]
>        ptrvalue(a,10,"double") #  Returns a[10] assuming a is a double *

`ptrset(ptr,value,index,type)`

>     Sets the value pointed to by a pointer.  The type is automatically
>     inferred from the pointer type so this function will work for
>     integers, floats, doubles, etc...  The index and type fields are
>     optional.  When an index is given, it provides array access.  When
>     type is specified, it overrides the given pointer type.  Examples :

>       ptrset(a,3)            # Sets the value *a = 3
>       ptrset(a,3,10)         # Sets a[10] = 3
>       ptrset(a,3,10,"int")   # Sets a[10] = 3 assuming a is a int *

`ptrcreate(type,value,nitems)`

>     Creates a new object and returns a pointer to it.  This function
>     can be used to create various kinds of objects for use in C functions.
>     type specifies the basic C datatype to create and value is an
>     optional parameter that can be used to set the initial value of the
>     object.  nitems is an optional parameter that can be used to create
>     an array.  This function results in a memory allocation using
>     malloc().  Examples :

>       a = ptrcreate("double")     # Create a new double, return pointer
>       a = ptrcreate("int",7)      # Create an integer, set value to 7
>       a = ptrcreate("int",0,1000) # Create an integer array with initial
>                                   # values all set to zero

>     This function only recognizes a few common C datatypes as listed below :

>            int, short, long, float, double, char, char *, void

>     All other datatypes will result in an error.  However, other
>     datatypes can be created by using the ptrcast function.  For
>     example:

>      a = ptrcast(ptrcreate("int",0,100),"unsigned int *")

`ptrfree(ptr)`

>     Destroys the memory pointed to by ptr.  This function calls free()
>     and should only be used with objects created by ptrcreate().  Since
>     this function calls free, it may work with other objects, but this
>     is generally discouraged unless you absolutely know what you're
>     doing.

`ptradd(ptr,offset)`

>     Adds a value to the current pointer value.  For the C datatypes of
>     int, short, long, float, double, and char, the offset value is the
>     number of objects and works in exactly the same manner as in C.  For
>     example, the following code steps through the elements of an array

>      a = ptrcreate("double",0,100);    # Create an array double a[100]
>      b = a;
>      for i in range(0,100):
>          ptrset(b,0.0025*i);           # set *b = 0.0025*i
>          b = ptradd(b,1);              # b++ (go to next double)

>     In this case, adding one to b goes to the next double.

>     For all other datatypes (including all complex datatypes), the
>     offset corresponds to bytes.  This function does not perform any
>     bounds checking and negative offsets are perfectly legal.

`ptrmap(type1,type2)`

>     This is a rarely used function that performs essentially the same
>     operation as a C typedef.  To manage datatypes at run-time, SWIG
>     modules manage an internal symbol table of type mappings.  This
>     table keeps track of which types are equivalent to each other.  The
>     ptrmap() function provides a mechanism for scripts to add symbols
>     to this table.  For example :

>        ptrmap("double_p","Real_p");

>     would make the types "doublePtr" and "RealPtr" equivalent to each
>     other.  Pointers of either type could now be used interchangably.

>     Normally this function is not needed, but it can be used to
>     circumvent SWIG's normal type-checking behavior or to work around
>     weird type-handling problems.

## 14. Changes

    0.6 to 0.65
      * misc. bug fixes
      * PyFT.py OO wrapper

    0.5 to 0.6:

      * fixed up drawString
      * fixed the bug in TT_Char_Index
      * fixed toImage
      * added drawTransString
      * added toMask for drawing text onto a PIL image
      * added renderString, which actually draws the text onto a PIL image

## 15. Credits

    I would like to thank the FreeType project, especially its principal
    authors, David Turner, Robert Wilhelm, and Werner Lemberg, for writing
    such a wonderful library to wrap.

    Other notable persons/entities include

      * Robin Becker, Mathieu, and Mike Ivanov for bug reports.

      * Fred L. Drake, Jr. for letting me peek at (read: steal from) his
        t1python code for the bitmap-to-PIL conversion.

      * Dave Beazley for SWIG, without which I would never had had the
        activation energy to start this project.

      * Guido and the rest of the Python gang for making a damn fine
        programming language.

## 16. Legal

    Copyright 2000 by Robert Kern, Frederick MD, USA.

                            All Rights Reserved

    Permission to use, copy, modify, and distribute this software and its
    documentation for any purpose and without fee is hereby granted,
    provided that the above copyright notice appear in all copies and that
    both that copyright notice and this permission notice appear in
    supporting documentation, and that the name of Robert Kern not be used
    in advertising or publicity pertaining to distribution of the software
    without specific, written prior permission.

    ROBERT KERN DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
    INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
    EVENT SHALL ROBERT KERN BE LIABLE FOR ANY SPECIAL, INDIRECT OR
    CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
    USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
    OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
    PERFORMANCE OF THIS SOFTWARE.