text:
/****************************************************************************
 *
 * winfnt.c
 *
 *   FreeType font driver for Windows FNT/FON files
 *
 * Copyright (C) 1996-2020 by
 * David Turner, Robert Wilhelm, and Werner Lemberg.
 * Copyright 2003 Huw D M Davies for Codeweavers
 * Copyright 2007 Dmitry Timoshkov for Codeweavers
 *
 * This file is part of the FreeType project, and may only be used,
 * modified, and distributed under the terms of the FreeType project
 * license, LICENSE.TXT.  By continuing to use, modify, or distribute
 * this file you indicate that you have read the license and
 * understand and accept it fully.
 *
 */

#include <ft2build.h>
#include FT_WINFONTS_H
#include FT_INTERNAL_DEBUG_H
#include FT_INTERNAL_STREAM_H
#include FT_INTERNAL_OBJECTS_H
#include FT_TRUETYPE_IDS_H

#include "winfnt.h"
#include "fnterrs.h"
#include FT_SERVICE_WINFNT_H
#include FT_SERVICE_FONT_FORMAT_H

  /**************************************************************************
   *
   * The macro FT_COMPONENT is used in trace mode.  It is an implicit
   * parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log
   * messages during execution.
   */
#undef  FT_COMPONENT
#define FT_COMPONENT  winfnt

  static const FT_Frame_Field  winmz_header_fields[] =
  {
#undef  FT_STRUCTURE
#define FT_STRUCTURE  WinMZ_HeaderRec

    FT_FRAME_START( 64 ),
      FT_FRAME_USHORT_LE ( magic ),
      FT_FRAME_SKIP_BYTES( 29 * 2 ),
      FT_FRAME_ULONG_LE  ( lfanew ),
    FT_FRAME_END
  };

  static const FT_Frame_Field  winne_header_fields[] =
  {
#undef  FT_STRUCTURE
#define FT_STRUCTURE  WinNE_HeaderRec

    FT_FRAME_START( 40 ),
      FT_FRAME_USHORT_LE ( magic ),
      FT_FRAME_SKIP_BYTES( 34 ),
      FT_FRAME_USHORT_LE ( resource_tab_offset ),
      FT_FRAME_USHORT_LE ( rname_tab_offset ),
    FT_FRAME_END
  };

  static const FT_Frame_Field  winpe32_header_fields[] =
  {
#undef  FT_STRUCTURE
#define FT_STRUCTURE  WinPE32_HeaderRec

    FT_FRAME_START( 248 ),
      FT_FRAME_ULONG_LE  ( magic ),   /* PE00 */
      FT_FRAME_USHORT_LE ( machine ), /* 0x014C - i386 */
      FT_FRAME_USHORT_LE ( number_of_sections ),
      FT_FRAME_SKIP_BYTES( 12 ),
      FT_FRAME_USHORT_LE ( size_of_optional_header ),
      FT_FRAME_SKIP_BYTES( 2 ),
      FT_FRAME_USHORT_LE ( magic32 ), /* 0x10B */
      FT_FRAME_SKIP_BYTES( 110 ),
      FT_FRAME_ULONG_LE  ( rsrc_virtual_address ),
      FT_FRAME_ULONG_LE  ( rsrc_size ),
      FT_FRAME_SKIP_BYTES( 104 ),
    FT_FRAME_END
  };

  static const FT_Frame_Field  winpe32_section_fields[] =
  {
#undef  FT_STRUCTURE
#define FT_STRUCTURE  WinPE32_SectionRec

    FT_FRAME_START( 40 ),
      FT_FRAME_BYTES     ( name, 8 ),
      FT_FRAME_SKIP_BYTES( 4 ),
      FT_FRAME_ULONG_LE  ( virtual_address ),
      FT_FRAME_ULONG_LE  ( size_of_raw_data ),
      FT_FRAME_ULONG_LE  ( pointer_to_raw_data ),
      FT_FRAME_SKIP_BYTES( 16 ),
    FT_FRAME_END
  };

  static const FT_Frame_Field  winpe_rsrc_dir_fields[] =
  {
#undef  FT_STRUCTURE
#define FT_STRUCTURE  WinPE_RsrcDirRec

    FT_FRAME_START( 16 ),
      FT_FRAME_ULONG_LE ( characteristics ),
      FT_FRAME_ULONG_LE ( time_date_stamp ),
      FT_FRAME_USHORT_LE( major_version ),
      FT_FRAME_USHORT_LE( minor_version ),
      FT_FRAME_USHORT_LE( number_of_named_entries ),
      FT_FRAME_USHORT_LE( number_of_id_entries ),
    FT_FRAME_END
  };

  static const FT_Frame_Field  winpe_rsrc_dir_entry_fields[] =
  {
#undef  FT_STRUCTURE
#define FT_STRUCTURE  WinPE_RsrcDirEntryRec

    FT_FRAME_START( 8 ),
      FT_FRAME_ULONG_LE( name ),
      FT_FRAME_ULONG_LE( offset ),
    FT_FRAME_END
  };

  static const FT_Frame_Field  winpe_rsrc_data_entry_fields[] =
  {
#undef  FT_STRUCTURE
#define FT_STRUCTURE  WinPE_RsrcDataEntryRec

    FT_FRAME_START( 16 ),
      FT_FRAME_ULONG_LE( offset_to_data ),
      FT_FRAME_ULONG_LE( size ),
      FT_FRAME_ULONG_LE( code_page ),
      FT_FRAME_ULONG_LE( reserved ),
    FT_FRAME_END
  };

  static const FT_Frame_Field  winfnt_header_fields[] =
  {
#undef  FT_STRUCTURE
#define FT_STRUCTURE  FT_WinFNT_HeaderRec

    FT_FRAME_START( 148 ),
      FT_FRAME_USHORT_LE( version ),
      FT_FRAME_ULONG_LE ( file_size ),
      FT_FRAME_BYTES    ( copyright, 60 ),
      FT_FRAME_USHORT_LE( file_type ),
      FT_FRAME_USHORT_LE( nominal_point_size ),
      FT_FRAME_USHORT_LE( vertical_resolution ),
      FT_FRAME_USHORT_LE( horizontal_resolution ),
      FT_FRAME_USHORT_LE( ascent ),
      FT_FRAME_USHORT_LE( internal_leading ),
      FT_FRAME_USHORT_LE( external_leading ),
      FT_FRAME_BYTE     ( italic ),
      FT_FRAME_BYTE     ( underline ),
      FT_FRAME_BYTE     ( strike_out ),
      FT_FRAME_USHORT_LE( weight ),
      FT_FRAME_BYTE     ( charset ),
      FT_FRAME_USHORT_LE( pixel_width ),
      FT_FRAME_USHORT_LE( pixel_height ),
      FT_FRAME_BYTE     ( pitch_and_family ),
      FT_FRAME_USHORT_LE( avg_width ),
      FT_FRAME_USHORT_LE( max_width ),
      FT_FRAME_BYTE     ( first_char ),
      FT_FRAME_BYTE     ( last_char ),
      FT_FRAME_BYTE     ( default_char ),
      FT_FRAME_BYTE     ( break_char ),
      FT_FRAME_USHORT_LE( bytes_per_row ),
      FT_FRAME_ULONG_LE ( device_offset ),
      FT_FRAME_ULONG_LE ( face_name_offset ),
      FT_FRAME_ULONG_LE ( bits_pointer ),
      FT_FRAME_ULONG_LE ( bits_offset ),
      FT_FRAME_BYTE     ( reserved ),
      FT_FRAME_ULONG_LE ( flags ),
      FT_FRAME_USHORT_LE( A_space ),
      FT_FRAME_USHORT_LE( B_space ),
      FT_FRAME_USHORT_LE( C_space ),
      FT_FRAME_ULONG_LE ( color_table_offset ),
      FT_FRAME_BYTES    ( reserved1, 16 ),
    FT_FRAME_END
  };

  static void
  fnt_font_done( FNT_Face face )
  {
    FT_Memory  memory = FT_FACE( face )->memory;
    FT_Stream  stream = FT_FACE( face )->stream;
    FNT_Font   font   = face->font;

    if ( !font )
      return;

    if ( font->fnt_frame )
      FT_FRAME_RELEASE( font->fnt_frame );
    FT_FREE( font->family_name );

    FT_FREE( font );
    face->font = NULL;
  }

  static FT_Error
  fnt_font_load( FNT_Font   font,
                 FT_Stream  stream )
  {
    FT_Error          error;
    FT_WinFNT_Header  header = &font->header;
    FT_Bool           new_format;
    FT_UInt           size;

    /* first of all, read the FNT header */
    if ( FT_STREAM_SEEK( font->offset )                        ||
         FT_STREAM_READ_FIELDS( winfnt_header_fields, header ) )
      goto Exit;

    /* check header */
    if ( header->version != 0x200 &&
         header->version != 0x300 )
    {
      FT_TRACE2(( "  not a Windows FNT file\n" ));
      error = FT_THROW( Unknown_File_Format );
      goto Exit;
    }

    new_format = FT_BOOL( font->header.version == 0x300 );
    size       = new_format ? 148 : 118;

    if ( header->file_size < size )
    {
      FT_TRACE2(( "  not a Windows FNT file\n" ));
      error = FT_THROW( Unknown_File_Format );
      goto Exit;
    }

    /* Version 2 doesn't have these fields */
    if ( header->version == 0x200 )
    {
      header->flags   = 0;
      header->A_space = 0;
      header->B_space = 0;
      header->C_space = 0;

      header->color_table_offset = 0;
    }

    if ( header->file_type & 1 )
    {
      FT_TRACE2(( "[can't handle vector FNT fonts]\n" ));
      error = FT_THROW( Unknown_File_Format );
      goto Exit;
    }

    /* this is a FNT file/table; extract its frame */
    if ( FT_STREAM_SEEK( font->offset )                         ||
         FT_FRAME_EXTRACT( header->file_size, font->fnt_frame ) )
      goto Exit;

  Exit:
    return error;
  }

  static FT_Error
  fnt_face_get_dll_font( FNT_Face  face,
                         FT_Int    face_instance_index )
  {
    FT_Error         error;
    FT_Stream        stream = FT_FACE( face )->stream;
    FT_Memory        memory = FT_FACE( face )->memory;
    WinMZ_HeaderRec  mz_header;
    FT_Long          face_index;

    face->font = NULL;

    face_index = FT_ABS( face_instance_index ) & 0xFFFF;

    /* does it begin with an MZ header? */
    if ( FT_STREAM_SEEK( 0 )                                      ||
         FT_STREAM_READ_FIELDS( winmz_header_fields, &mz_header ) )
      goto Exit;

    error = FT_ERR( Unknown_File_Format );
    if ( mz_header.magic == WINFNT_MZ_MAGIC )
    {
      /* yes, now look for an NE header in the file */
      WinNE_HeaderRec  ne_header;

      FT_TRACE2(( "MZ signature found\n" ));

      if ( FT_STREAM_SEEK( mz_header.lfanew )                       ||
           FT_STREAM_READ_FIELDS( winne_header_fields, &ne_header ) )
        goto Exit;

      error = FT_ERR( Unknown_File_Format );
      if ( ne_header.magic == WINFNT_NE_MAGIC )
      {
        /* good, now look into the resource table for each FNT resource */
        FT_ULong   res_offset  = mz_header.lfanew +
                                   ne_header.resource_tab_offset;
        FT_UShort  size_shift;
        FT_UShort  font_count  = 0;
        FT_ULong   font_offset = 0;

        FT_TRACE2(( "NE signature found\n" ));

        if ( FT_STREAM_SEEK( res_offset )                    ||
             FT_FRAME_ENTER( ne_header.rname_tab_offset -
                             ne_header.resource_tab_offset ) )
          goto Exit;

        size_shift = FT_GET_USHORT_LE();

        /* Microsoft's specification of the executable-file header format */
        /* for `New Executable' (NE) doesn't give a limit for the         */
        /* alignment shift count; however, in 1985, the year of the       */
        /* specification release, only 32bit values were supported, thus  */
        /* anything larger than 16 doesn't make sense in general, given   */
        /* that file offsets are 16bit values, shifted by the alignment   */
        /* shift count                                                    */
        if ( size_shift > 16 )
        {
          FT_TRACE2(( "invalid alignment shift count for resource data\n" ));
          error = FT_THROW( Invalid_File_Format );
          goto Exit1;
        }

        for (;;)
        {
          FT_UShort  type_id, count;

          type_id = FT_GET_USHORT_LE();
          if ( !type_id )
            break;

          count = FT_GET_USHORT_LE();

          if ( type_id == 0x8008U )
          {
            font_count  = count;
            font_offset = FT_STREAM_POS() + 4 +
                          (FT_ULong)( stream->cursor - stream->limit );
            break;
          }

          stream->cursor += 4 + count * 12;
        }

        FT_FRAME_EXIT();

        if ( !font_count || !font_offset )
        {
          FT_TRACE2(( "this file doesn't contain any FNT resources\n" ));
          error = FT_THROW( Invalid_File_Format );
          goto Exit;
        }

        /* loading `winfnt_header_fields' needs at least 118 bytes;    */
        /* use this as a rough measure to check the expected font size */
        if ( font_count * 118UL > stream->size )
        {
          FT_TRACE2(( "invalid number of faces\n" ));
          error = FT_THROW( Invalid_File_Format );
          goto Exit;
        }

        face->root.num_faces = font_count;

        if ( face_instance_index < 0 )
          goto Exit;

        if ( face_index >= font_count )
        {
          error = FT_THROW( Invalid_Argument );
          goto Exit;
        }

        if ( FT_NEW( face->font ) )
          goto Exit;

        if ( FT_STREAM_SEEK( font_offset + (FT_ULong)face_index * 12 ) ||
             FT_FRAME_ENTER( 12 )                                      )
          goto Fail;

        face->font->offset   = (FT_ULong)FT_GET_USHORT_LE() << size_shift;
        face->font->fnt_size = (FT_ULong)FT_GET_USHORT_LE() << size_shift;

        stream->cursor += 8;

        FT_FRAME_EXIT();

        error = fnt_font_load( face->font, stream );
      }
      else if ( ne_header.magic == WINFNT_PE_MAGIC )
      {
        WinPE32_HeaderRec       pe32_header;
        WinPE32_SectionRec      pe32_section;
        WinPE_RsrcDirRec        root_dir, name_dir, lang_dir;
        WinPE_RsrcDirEntryRec   dir_entry1, dir_entry2, dir_entry3;
        WinPE_RsrcDataEntryRec  data_entry;

        FT_ULong   root_dir_offset, name_dir_offset, lang_dir_offset;
        FT_UShort  i, j, k;

        FT_TRACE2(( "PE signature found\n" ));

        if ( FT_STREAM_SEEK( mz_header.lfanew )                           ||
             FT_STREAM_READ_FIELDS( winpe32_header_fields, &pe32_header ) )
          goto Exit;

        FT_TRACE2(( "magic %04lx, machine %02x, number_of_sections %u, "
                    "size_of_optional_header %02x\n"
                    "magic32 %02x, rsrc_virtual_address %04lx, "
                    "rsrc_size %04lx\n",
                    pe32_header.magic, pe32_header.machine,
                    pe32_header.number_of_sections,
                    pe32_header.size_of_optional_header,
                    pe32_header.magic32, pe32_header.rsrc_virtual_address,
                    pe32_header.rsrc_size ));

        if ( pe32_header.magic != WINFNT_PE_MAGIC /* check full signature */ ||
             pe32_header.machine != 0x014C /* i386 */                        ||
             pe32_header.size_of_optional_header != 0xE0 /* FIXME */         ||
             pe32_header.magic32 != 0x10B                                    )
        {
          FT_TRACE2(( "this file has an invalid PE header\n" ));
          error = FT_THROW( Invalid_File_Format );
          goto Exit;
        }

        face->root.num_faces = 0;

        for ( i = 0; i < pe32_header.number_of_sections; i++ )
        {
          if ( FT_STREAM_READ_FIELDS( winpe32_section_fields,
                                      &pe32_section ) )
            goto Exit;

          FT_TRACE2(( "name %.8s, va %04lx, size %04lx, offset %04lx\n",
                      pe32_section.name, pe32_section.virtual_address,
                      pe32_section.size_of_raw_data,
                      pe32_section.pointer_to_raw_data ));

          if ( pe32_header.rsrc_virtual_address ==
                 pe32_section.virtual_address )
            goto Found_rsrc_section;
        }

        FT_TRACE2(( "this file doesn't contain any resources\n" ));
        error = FT_THROW( Invalid_File_Format );
        goto Exit;

      Found_rsrc_section:
        FT_TRACE2(( "found resources section %.8s\n", pe32_section.name ));

        if ( FT_STREAM_SEEK( pe32_section.pointer_to_raw_data )        ||
             FT_STREAM_READ_FIELDS( winpe_rsrc_dir_fields, &root_dir ) )
          goto Exit;

        root_dir_offset = pe32_section.pointer_to_raw_data;

        for ( i = 0; i < root_dir.number_of_named_entries +
                           root_dir.number_of_id_entries; i++ )
        {
          if ( FT_STREAM_SEEK( root_dir_offset + 16 + i * 8 )      ||
               FT_STREAM_READ_FIELDS( winpe_rsrc_dir_entry_fields,
                                      &dir_entry1 )                )
            goto Exit;

          if ( !(dir_entry1.offset & 0x80000000UL ) /* DataIsDirectory */ )
          {
            error = FT_THROW( Invalid_File_Format );
            goto Exit;
          }

          dir_entry1.offset &= ~0x80000000UL;

          name_dir_offset = pe32_section.pointer_to_raw_data +
                            dir_entry1.offset;

          if ( FT_STREAM_SEEK( pe32_section.pointer_to_raw_data +
                               dir_entry1.offset )                       ||
               FT_STREAM_READ_FIELDS( winpe_rsrc_dir_fields, &name_dir ) )
            goto Exit;

          for ( j = 0; j < name_dir.number_of_named_entries +
                             name_dir.number_of_id_entries; j++ )
          {
            if ( FT_STREAM_SEEK( name_dir_offset + 16 + j * 8 )      ||
                 FT_STREAM_READ_FIELDS( winpe_rsrc_dir_entry_fields,
                                        &dir_entry2 )                )
              goto Exit;

            if ( !(dir_entry2.offset & 0x80000000UL ) /* DataIsDirectory */ )
            {
              error = FT_THROW( Invalid_File_Format );
              goto Exit;
            }

            dir_entry2.offset &= ~0x80000000UL;

            lang_dir_offset = pe32_section.pointer_to_raw_data +
                                dir_entry2.offset;

            if ( FT_STREAM_SEEK( pe32_section.pointer_to_raw_data +
                                   dir_entry2.offset )                     ||
                 FT_STREAM_READ_FIELDS( winpe_rsrc_dir_fields, &lang_dir ) )
              goto Exit;

            for ( k = 0; k < lang_dir.number_of_named_entries +
                               lang_dir.number_of_id_entries; k++ )
            {
              if ( FT_STREAM_SEEK( lang_dir_offset + 16 + k * 8 )      ||
                   FT_STREAM_READ_FIELDS( winpe_rsrc_dir_entry_fields,
                                          &dir_entry3 )                )
                goto Exit;

              if ( dir_entry2.offset & 0x80000000UL /* DataIsDirectory */ )
              {
                error = FT_THROW( Invalid_File_Format );
                goto Exit;
              }

              if ( dir_entry1.name == 8 /* RT_FONT */ )
              {
                if ( FT_STREAM_SEEK( root_dir_offset + dir_entry3.offset ) ||
                     FT_STREAM_READ_FIELDS( winpe_rsrc_data_entry_fields,
                                            &data_entry )                  )
                  goto Exit;

                FT_TRACE2(( "found font #%lu, offset %04lx, "
                            "size %04lx, cp %lu\n",
                            dir_entry2.name,
                            pe32_section.pointer_to_raw_data +
                              data_entry.offset_to_data -
                              pe32_section.virtual_address,
                            data_entry.size, data_entry.code_page ));

                if ( face_index == face->root.num_faces )
                {
                  if ( FT_NEW( face->font ) )
                    goto Exit;

                  face->font->offset   = pe32_section.pointer_to_raw_data +
                                           data_entry.offset_to_data -
                                           pe32_section.virtual_address;
                  face->font->fnt_size = data_entry.size;

                  error = fnt_font_load( face->font, stream );
                  if ( error )
                  {
                    FT_TRACE2(( "font #%lu load error 0x%x\n",
                                dir_entry2.name, error ));
                    goto Fail;
                  }
                  else
                    FT_TRACE2(( "font #%lu successfully loaded\n",
                                dir_entry2.name ));
                }

                face->root.num_faces++;
              }
            }
          }
        }
      }

      if ( !face->root.num_faces )
      {
        FT_TRACE2(( "this file doesn't contain any RT_FONT resources\n" ));
        error = FT_THROW( Invalid_File_Format );
        goto Exit;
      }

      if ( face_index >= face->root.num_faces )
      {
        error = FT_THROW( Invalid_Argument );
        goto Exit;
      }
    }

  Fail:
    if ( error )
      fnt_font_done( face );

  Exit:
    return error;

  Exit1:
    FT_FRAME_EXIT();
    goto Exit;
  }

  typedef struct  FNT_CMapRec_
  {
    FT_CMapRec  cmap;
    FT_UInt32   first;
    FT_UInt32   count;

  } FNT_CMapRec, *FNT_CMap;

  static FT_Error
  fnt_cmap_init( FNT_CMap    cmap,
                 FT_Pointer  pointer )
  {
    FNT_Face  face = (FNT_Face)FT_CMAP_FACE( cmap );
    FNT_Font  font = face->font;

    FT_UNUSED( pointer );

    cmap->first = (FT_UInt32)  font->header.first_char;
    cmap->count = (FT_UInt32)( font->header.last_char - cmap->first + 1 );

    return 0;
  }

  static FT_UInt
  fnt_cmap_char_index( FNT_CMap   cmap,
                       FT_UInt32  char_code )
  {
    FT_UInt  gindex = 0;

    char_code -= cmap->first;
    if ( char_code < cmap->count )
      /* we artificially increase the glyph index; */
      /* FNT_Load_Glyph reverts to the right one   */
      gindex = (FT_UInt)( char_code + 1 );
    return gindex;
  }

  static FT_UInt32
  fnt_cmap_char_next( FNT_CMap    cmap,
                      FT_UInt32  *pchar_code )
  {
    FT_UInt    gindex = 0;
    FT_UInt32  result = 0;
    FT_UInt32  char_code = *pchar_code + 1;

    if ( char_code <= cmap->first )
    {
      result = cmap->first;
      gindex = 1;
    }
    else
    {
      char_code -= cmap->first;
      if ( char_code < cmap->count )
      {
        result = cmap->first + char_code;
        gindex = (FT_UInt)( char_code + 1 );
      }
    }

    *pchar_code = result;
    return gindex;
  }

  static const FT_CMap_ClassRec  fnt_cmap_class_rec =
  {
    sizeof ( FNT_CMapRec ),

    (FT_CMap_InitFunc)     fnt_cmap_init,
    (FT_CMap_DoneFunc)     NULL,
    (FT_CMap_CharIndexFunc)fnt_cmap_char_index,
    (FT_CMap_CharNextFunc) fnt_cmap_char_next,

    NULL, NULL, NULL, NULL, NULL
  };

  static FT_CMap_Class const  fnt_cmap_class = &fnt_cmap_class_rec;

  static void
  FNT_Face_Done( FT_Face  fntface )       /* FNT_Face */
  {
    FNT_Face   face = (FNT_Face)fntface;
    FT_Memory  memory;

    if ( !face )
      return;

    memory = FT_FACE_MEMORY( face );

    fnt_font_done( face );

    FT_FREE( fntface->available_sizes );
    fntface->num_fixed_sizes = 0;
  }

  static FT_Error
  FNT_Face_Init( FT_Stream      stream,
                 FT_Face        fntface,        /* FNT_Face */
                 FT_Int         face_instance_index,
                 FT_Int         num_params,
                 FT_Parameter*  params )
  {
    FNT_Face   face   = (FNT_Face)fntface;
    FT_Error   error;
    FT_Memory  memory = FT_FACE_MEMORY( face );
    FT_Int     face_index;

    FT_UNUSED( num_params );
    FT_UNUSED( params );

    FT_TRACE2(( "Windows FNT driver\n" ));

    face_index = FT_ABS( face_instance_index ) & 0xFFFF;

    /* try to load font from a DLL */
    error = fnt_face_get_dll_font( face, face_instance_index );
    if ( !error && face_instance_index < 0 )
      goto Exit;

    if ( FT_ERR_EQ( error, Unknown_File_Format ) )
    {
      /* this didn't work; try to load a single FNT font */
      FNT_Font  font;

      if ( FT_NEW( face->font ) )
        goto Exit;

      fntface->num_faces = 1;

      font           = face->font;
      font->offset   = 0;
      font->fnt_size = stream->size;

      error = fnt_font_load( font, stream );

      if ( !error )
      {
        if ( face_instance_index < 0 )
          goto Exit;

        if ( face_index > 0 )
          error = FT_THROW( Invalid_Argument );
      }
    }

    if ( error )
      goto Fail;

    /* sanity check */
    if ( !face->font->header.pixel_height )
    {
      FT_TRACE2(( "invalid pixel height\n" ));
      error = FT_THROW( Invalid_File_Format );
      goto Fail;
    }

    /* we now need to fill the root FT_Face fields */
    /* with relevant information                   */
    {
      FT_Face   root = FT_FACE( face );
      FNT_Font  font = face->font;
      FT_ULong  family_size;

      root->face_index = face_index;

      root->face_flags |= FT_FACE_FLAG_FIXED_SIZES |
                          FT_FACE_FLAG_HORIZONTAL;

      if ( font->header.avg_width == font->header.max_width )
        root->face_flags |= FT_FACE_FLAG_FIXED_WIDTH;

      if ( font->header.italic )
        root->style_flags |= FT_STYLE_FLAG_ITALIC;

      if ( font->header.weight >= 800 )
        root->style_flags |= FT_STYLE_FLAG_BOLD;

      /* set up the `fixed_sizes' array */
      if ( FT_NEW_ARRAY( root->available_sizes, 1 ) )
        goto Fail;

      root->num_fixed_sizes = 1;

      {
        FT_Bitmap_Size*  bsize = root->available_sizes;
        FT_UShort        x_res, y_res;

        bsize->width  = (FT_Short)font->header.avg_width;
        bsize->height = (FT_Short)( font->header.pixel_height +
                                    font->header.external_leading );
        bsize->size   = font->header.nominal_point_size << 6;

        x_res = font->header.horizontal_resolution;
        if ( !x_res )
          x_res = 72;

        y_res = font->header.vertical_resolution;
        if ( !y_res )
          y_res = 72;

        bsize->y_ppem = FT_MulDiv( bsize->size, y_res, 72 );
        bsize->y_ppem = FT_PIX_ROUND( bsize->y_ppem );

        /*
         * this reads:
         *
         * the nominal height is larger than the bbox's height
         *
         * => nominal_point_size contains incorrect value;
         *    use pixel_height as the nominal height
         */
        if ( bsize->y_ppem > ( font->header.pixel_height << 6 ) )
        {
          FT_TRACE2(( "use pixel_height as the nominal height\n" ));

          bsize->y_ppem = font->header.pixel_height << 6;
          bsize->size   = FT_MulDiv( bsize->y_ppem, 72, y_res );
        }

        bsize->x_ppem = FT_MulDiv( bsize->size, x_res, 72 );
        bsize->x_ppem = FT_PIX_ROUND( bsize->x_ppem );
      }

      {
        FT_CharMapRec  charmap;

        charmap.encoding    = FT_ENCODING_NONE;
        /* initial platform/encoding should indicate unset status? */
        charmap.platform_id = TT_PLATFORM_APPLE_UNICODE;
        charmap.encoding_id = TT_APPLE_ID_DEFAULT;
        charmap.face        = root;

        if ( font->header.charset == FT_WinFNT_ID_MAC )
        {
          charmap.encoding    = FT_ENCODING_APPLE_ROMAN;
          charmap.platform_id = TT_PLATFORM_MACINTOSH;
/*        charmap.encoding_id = TT_MAC_ID_ROMAN; */
        }

        error = FT_CMap_New( fnt_cmap_class,
                             NULL,
                             &charmap,
                             NULL );
        if ( error )
          goto Fail;
      }

      /* set up remaining flags */

      if ( font->header.last_char < font->header.first_char )
      {
        FT_TRACE2(( "invalid number of glyphs\n" ));
        error = FT_THROW( Invalid_File_Format );
        goto Fail;
      }

      /* reserve one slot for the .notdef glyph at index 0 */
      root->num_glyphs = font->header.last_char -
                         font->header.first_char + 1 + 1;

      if ( font->header.face_name_offset >= font->header.file_size )
      {
        FT_TRACE2(( "invalid family name offset\n" ));
        error = FT_THROW( Invalid_File_Format );
        goto Fail;
      }
      family_size = font->header.file_size - font->header.face_name_offset;
      /* Some broken fonts don't delimit the face name with a final */
      /* NULL byte -- the frame is erroneously one byte too small.  */
      /* We thus allocate one more byte, setting it explicitly to   */
      /* zero.                                                      */
      if ( FT_ALLOC( font->family_name, family_size + 1 ) )
        goto Fail;

      FT_MEM_COPY( font->family_name,
                   font->fnt_frame + font->header.face_name_offset,
                   family_size );

      font->family_name[family_size] = '\0';

      if ( FT_REALLOC( font->family_name,
                       family_size,
                       ft_strlen( font->family_name ) + 1 ) )
        goto Fail;

      root->family_name = font->family_name;
      root->style_name  = (char *)"Regular";

      if ( root->style_flags & FT_STYLE_FLAG_BOLD )
      {
        if ( root->style_flags & FT_STYLE_FLAG_ITALIC )
          root->style_name = (char *)"Bold Italic";
        else
          root->style_name = (char *)"Bold";
      }
      else if ( root->style_flags & FT_STYLE_FLAG_ITALIC )
        root->style_name = (char *)"Italic";
    }
    goto Exit;

  Fail:
    FNT_Face_Done( fntface );

  Exit:
    return error;
  }

  static FT_Error
  FNT_Size_Select( FT_Size   size,
                   FT_ULong  strike_index )
  {
    FNT_Face          face   = (FNT_Face)size->face;
    FT_WinFNT_Header  header = &face->font->header;

    FT_UNUSED( strike_index );

    FT_Select_Metrics( size->face, 0 );

    size->metrics.ascender    = header->ascent * 64;
    size->metrics.descender   = -( header->pixel_height -
                                   header->ascent ) * 64;
    size->metrics.max_advance = header->max_width * 64;

    return FT_Err_Ok;
  }

  static FT_Error
  FNT_Size_Request( FT_Size          size,
                    FT_Size_Request  req )
  {
    FNT_Face          face    = (FNT_Face)size->face;
    FT_WinFNT_Header  header  = &face->font->header;
    FT_Bitmap_Size*   bsize   = size->face->available_sizes;
    FT_Error          error   = FT_ERR( Invalid_Pixel_Size );
    FT_Long           height;

    height = FT_REQUEST_HEIGHT( req );
    height = ( height + 32 ) >> 6;

    switch ( req->type )
    {
    case FT_SIZE_REQUEST_TYPE_NOMINAL:
      if ( height == ( ( bsize->y_ppem + 32 ) >> 6 ) )
        error = FT_Err_Ok;
      break;

    case FT_SIZE_REQUEST_TYPE_REAL_DIM:
      if ( height == header->pixel_height )
        error = FT_Err_Ok;
      break;

    default:
      error = FT_THROW( Unimplemented_Feature );
      break;
    }

    if ( error )
      return error;
    else
      return FNT_Size_Select( size, 0 );
  }

  static FT_Error
  FNT_Load_Glyph( FT_GlyphSlot  slot,
                  FT_Size       size,
                  FT_UInt       glyph_index,
                  FT_Int32      load_flags )
  {
    FNT_Face    face   = (FNT_Face)FT_SIZE_FACE( size );
    FNT_Font    font;
    FT_Error    error  = FT_Err_Ok;
    FT_Byte*    p;
    FT_UInt     len;
    FT_Bitmap*  bitmap = &slot->bitmap;
    FT_ULong    offset;
    FT_Bool     new_format;

    if ( !face )
    {
      error = FT_THROW( Invalid_Face_Handle );
      goto Exit;
    }

    font = face->font;

    if ( !font                                                   ||
         glyph_index >= (FT_UInt)( FT_FACE( face )->num_glyphs ) )
    {
      error = FT_THROW( Invalid_Argument );
      goto Exit;
    }

    FT_TRACE1(( "FNT_Load_Glyph: glyph index %d\n", glyph_index ));

    if ( glyph_index > 0 )
      glyph_index--;                           /* revert to real index */
    else
      glyph_index = font->header.default_char; /* the `.notdef' glyph  */

    new_format = FT_BOOL( font->header.version == 0x300 );
    len        = new_format ? 6 : 4;

    /* get glyph width and offset */
    offset = ( new_format ? 148 : 118 ) + len * glyph_index;

    if ( offset >= font->header.file_size - 2 - ( new_format ? 4 : 2 ) )
    {
      FT_TRACE2(( "invalid FNT offset\n" ));
      error = FT_THROW( Invalid_File_Format );
      goto Exit;
    }

    p = font->fnt_frame + offset;

    bitmap->width = FT_NEXT_USHORT_LE( p );

    /* jump to glyph entry */
    if ( new_format )
      offset = FT_NEXT_ULONG_LE( p );
    else
      offset = FT_NEXT_USHORT_LE( p );

    if ( offset >= font->header.file_size )
    {
      FT_TRACE2(( "invalid FNT offset\n" ));
      error = FT_THROW( Invalid_File_Format );
      goto Exit;
    }

    bitmap->rows       = font->header.pixel_height;
    bitmap->pixel_mode = FT_PIXEL_MODE_MONO;

    slot->bitmap_left     = 0;
    slot->bitmap_top      = font->header.ascent;
    slot->format          = FT_GLYPH_FORMAT_BITMAP;

    /* now set up metrics */
    slot->metrics.width        = (FT_Pos)( bitmap->width << 6 );
    slot->metrics.height       = (FT_Pos)( bitmap->rows << 6 );
    slot->metrics.horiAdvance  = (FT_Pos)( bitmap->width << 6 );
    slot->metrics.horiBearingX = 0;
    slot->metrics.horiBearingY = slot->bitmap_top << 6;

    ft_synthesize_vertical_metrics( &slot->metrics,
                                    (FT_Pos)( bitmap->rows << 6 ) );

    if ( load_flags & FT_LOAD_BITMAP_METRICS_ONLY )
      goto Exit;

    /* jump to glyph data */
    p = font->fnt_frame + /* font->header.bits_offset */ + offset;

    /* allocate and build bitmap */
    {
      FT_Memory  memory = FT_FACE_MEMORY( slot->face );
      FT_UInt    pitch  = ( bitmap->width + 7 ) >> 3;
      FT_Byte*   column;
      FT_Byte*   write;

      bitmap->pitch = (int)pitch;
      if ( !pitch                                                 ||
           offset + pitch * bitmap->rows > font->header.file_size )
      {
        FT_TRACE2(( "invalid bitmap width\n" ));
        error = FT_THROW( Invalid_File_Format );
        goto Exit;
      }

      /* note: since glyphs are stored in columns and not in rows we */
      /*       can't use ft_glyphslot_set_bitmap                     */
      if ( FT_ALLOC_MULT( bitmap->buffer, bitmap->rows, pitch ) )
        goto Exit;

      column = (FT_Byte*)bitmap->buffer;

      for ( ; pitch > 0; pitch--, column++ )
      {
        FT_Byte*  limit = p + bitmap->rows;

        for ( write = column; p < limit; p++, write += bitmap->pitch )
          *write = *p;
      }

      slot->internal->flags = FT_GLYPH_OWN_BITMAP;
    }

  Exit:
    return error;
  }

  static FT_Error
  winfnt_get_header( FT_Face               face,
                     FT_WinFNT_HeaderRec  *aheader )
  {
    FNT_Font  font = ((FNT_Face)face)->font;

    *aheader = font->header;

    return 0;
  }

  static const FT_Service_WinFntRec  winfnt_service_rec =
  {
    winfnt_get_header       /* get_header */
  };

  /*
   * SERVICE LIST
   *
   */

  static const FT_ServiceDescRec  winfnt_services[] =
  {
    { FT_SERVICE_ID_FONT_FORMAT, FT_FONT_FORMAT_WINFNT },
    { FT_SERVICE_ID_WINFNT,      &winfnt_service_rec },
    { NULL, NULL }
  };

  static FT_Module_Interface
  winfnt_get_service( FT_Module         module,
                      const FT_String*  service_id )
  {
    FT_UNUSED( module );

    return ft_service_list_lookup( winfnt_services, service_id );
  }

  FT_CALLBACK_TABLE_DEF
  const FT_Driver_ClassRec  winfnt_driver_class =
  {
    {
      FT_MODULE_FONT_DRIVER        |
      FT_MODULE_DRIVER_NO_OUTLINES,
      sizeof ( FT_DriverRec ),

      "winfonts",
      0x10000L,
      0x20000L,

      NULL, /* module-specific interface */

      NULL,                     /* FT_Module_Constructor  module_init   */
      NULL,                     /* FT_Module_Destructor   module_done   */
      winfnt_get_service        /* FT_Module_Requester    get_interface */
    },

    sizeof ( FNT_FaceRec ),
    sizeof ( FT_SizeRec ),
    sizeof ( FT_GlyphSlotRec ),

    FNT_Face_Init,              /* FT_Face_InitFunc  init_face */
    FNT_Face_Done,              /* FT_Face_DoneFunc  done_face */
    NULL,                       /* FT_Size_InitFunc  init_size */
    NULL,                       /* FT_Size_DoneFunc  done_size */
    NULL,                       /* FT_Slot_InitFunc  init_slot */
    NULL,                       /* FT_Slot_DoneFunc  done_slot */

    FNT_Load_Glyph,             /* FT_Slot_LoadFunc  load_glyph */

    NULL,                       /* FT_Face_GetKerningFunc   get_kerning  */
    NULL,                       /* FT_Face_AttachFunc       attach_file  */
    NULL,                       /* FT_Face_GetAdvancesFunc  get_advances */

    FNT_Size_Request,           /* FT_Size_RequestFunc  request_size */
    FNT_Size_Select             /* FT_Size_SelectFunc   select_size  */
  };

/* END */


text:
#
# FreeType 2 Windows FNT/FON driver configuration rules
#

# Copyright (C) 1996-2020 by
# David Turner, Robert Wilhelm, and Werner Lemberg.
#
# This file is part of the FreeType project, and may only be used, modified,
# and distributed under the terms of the FreeType project license,
# LICENSE.TXT.  By continuing to use, modify, or distribute this file you
# indicate that you have read the license and understand and accept it
# fully.

# Windows driver directory
#
FNT_DIR := $(SRC_DIR)/winfonts

FNT_COMPILE := $(CC) $(ANSIFLAGS)                            \
                     $I$(subst /,$(COMPILER_SEP),$(FNT_DIR)) \
                     $(INCLUDE_FLAGS)                        \
                     $(FT_CFLAGS)

# Windows driver sources (i.e., C files)
#
FNT_DRV_SRC := $(FNT_DIR)/winfnt.c

# Windows driver headers
#
FNT_DRV_H := $(FNT_DRV_SRC:%.c=%.h) \
             $(FNT_DIR)/fnterrs.h

# Windows driver object(s)
#
#   FNT_DRV_OBJ_M is used during `multi' builds
#   FNT_DRV_OBJ_S is used during `single' builds
#
FNT_DRV_OBJ_M := $(FNT_DRV_SRC:$(FNT_DIR)/%.c=$(OBJ_DIR)/%.$O)
FNT_DRV_OBJ_S := $(OBJ_DIR)/winfnt.$O

# Windows driver source file for single build
#
FNT_DRV_SRC_S := $(FNT_DIR)/winfnt.c

# Windows driver - single object
#
$(FNT_DRV_OBJ_S): $(FNT_DRV_SRC_S) $(FNT_DRV_SRC) $(FREETYPE_H) $(FNT_DRV_H)
	$(FNT_COMPILE) $T$(subst /,$(COMPILER_SEP),$@ $(FNT_DRV_SRC_S))

# Windows driver - multiple objects
#
$(OBJ_DIR)/%.$O: $(FNT_DIR)/%.c $(FREETYPE_H) $(FNT_DRV_H)
	$(FNT_COMPILE) $T$(subst /,$(COMPILER_SEP),$@ $<)

# update main driver object lists
#
DRV_OBJS_S += $(FNT_DRV_OBJ_S)
DRV_OBJS_M += $(FNT_DRV_OBJ_M)

# EOF

repo_language: C

mime_type: text/x-c


text:
/*  bdf.c

    FreeType font driver for bdf files

    Copyright (C) 2001, 2002 by
    Francesco Zappa Nardelli

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#define FT_MAKE_OPTION_SINGLE_OBJECT
#include <ft2build.h>

#include "bdflib.c"
#include "bdfdrivr.c"

/* END */


text:
/*  bdfdrivr.c

    FreeType font driver for bdf files

    Copyright (C) 2001-2008, 2011, 2013, 2014 by
    Francesco Zappa Nardelli

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include <ft2build.h>

#include FT_INTERNAL_DEBUG_H
#include FT_INTERNAL_STREAM_H
#include FT_INTERNAL_OBJECTS_H
#include FT_BDF_H
#include FT_TRUETYPE_IDS_H

#include FT_SERVICE_BDF_H
#include FT_SERVICE_FONT_FORMAT_H

#include "bdf.h"
#include "bdfdrivr.h"

#include "bdferror.h"

  /**************************************************************************
   *
   * The macro FT_COMPONENT is used in trace mode.  It is an implicit
   * parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log
   * messages during execution.
   */
#undef  FT_COMPONENT
#define FT_COMPONENT  bdfdriver

  typedef struct  BDF_CMapRec_
  {
    FT_CMapRec        cmap;
    FT_ULong          num_encodings; /* ftobjs.h: FT_CMap->clazz->size */
    BDF_encoding_el*  encodings;

  } BDF_CMapRec, *BDF_CMap;

  FT_CALLBACK_DEF( FT_Error )
  bdf_cmap_init( FT_CMap     bdfcmap,
                 FT_Pointer  init_data )
  {
    BDF_CMap  cmap = (BDF_CMap)bdfcmap;
    BDF_Face  face = (BDF_Face)FT_CMAP_FACE( cmap );
    FT_UNUSED( init_data );

    cmap->num_encodings = face->bdffont->glyphs_used;
    cmap->encodings     = face->en_table;

    return FT_Err_Ok;
  }

  FT_CALLBACK_DEF( void )
  bdf_cmap_done( FT_CMap  bdfcmap )
  {
    BDF_CMap  cmap = (BDF_CMap)bdfcmap;

    cmap->encodings     = NULL;
    cmap->num_encodings = 0;
  }

  FT_CALLBACK_DEF( FT_UInt )
  bdf_cmap_char_index( FT_CMap    bdfcmap,
                       FT_UInt32  charcode )
  {
    BDF_CMap          cmap      = (BDF_CMap)bdfcmap;
    BDF_encoding_el*  encodings = cmap->encodings;
    FT_ULong          min, max, mid; /* num_encodings */
    FT_UShort         result    = 0; /* encodings->glyph */

    min = 0;
    max = cmap->num_encodings;
    mid = ( min + max ) >> 1;

    while ( min < max )
    {
      FT_ULong  code;

      if ( mid >= max || mid < min )
        mid = ( min + max ) >> 1;

      code = encodings[mid].enc;

      if ( charcode == code )
      {
        /* increase glyph index by 1 --              */
        /* we reserve slot 0 for the undefined glyph */
        result = encodings[mid].glyph + 1;
        break;
      }

      if ( charcode < code )
        max = mid;
      else
        min = mid + 1;

      /* prediction in a continuous block */
      mid += charcode - code;
    }

    return result;
  }

  FT_CALLBACK_DEF( FT_UInt )
  bdf_cmap_char_next( FT_CMap     bdfcmap,
                      FT_UInt32  *acharcode )
  {
    BDF_CMap          cmap      = (BDF_CMap)bdfcmap;
    BDF_encoding_el*  encodings = cmap->encodings;
    FT_ULong          min, max, mid; /* num_encodings */
    FT_UShort         result   = 0;  /* encodings->glyph */
    FT_ULong          charcode = *acharcode + 1;

    min = 0;
    max = cmap->num_encodings;
    mid = ( min + max ) >> 1;

    while ( min < max )
    {
      FT_ULong  code; /* same as BDF_encoding_el.enc */

      if ( mid >= max || mid < min )
        mid = ( min + max ) >> 1;

      code = encodings[mid].enc;

      if ( charcode == code )
      {
        /* increase glyph index by 1 --              */
        /* we reserve slot 0 for the undefined glyph */
        result = encodings[mid].glyph + 1;
        goto Exit;
      }

      if ( charcode < code )
        max = mid;
      else
        min = mid + 1;

      /* prediction in a continuous block */
      mid += charcode - code;
    }

    charcode = 0;
    if ( min < cmap->num_encodings )
    {
      charcode = encodings[min].enc;
      result   = encodings[min].glyph + 1;
    }

  Exit:
    if ( charcode > 0xFFFFFFFFUL )
    {
      FT_TRACE1(( "bdf_cmap_char_next: charcode 0x%x > 32bit API" ));
      *acharcode = 0;
      /* XXX: result should be changed to indicate an overflow error */
    }
    else
      *acharcode = (FT_UInt32)charcode;
    return result;
  }

  static
  const FT_CMap_ClassRec  bdf_cmap_class =
  {
    sizeof ( BDF_CMapRec ),
    bdf_cmap_init,
    bdf_cmap_done,
    bdf_cmap_char_index,
    bdf_cmap_char_next,

    NULL, NULL, NULL, NULL, NULL
  };

  static FT_Error
  bdf_interpret_style( BDF_Face  bdf )
  {
    FT_Error         error  = FT_Err_Ok;
    FT_Face          face   = FT_FACE( bdf );
    FT_Memory        memory = face->memory;
    bdf_font_t*      font   = bdf->bdffont;
    bdf_property_t*  prop;

    const char*   strings[4] = { NULL, NULL, NULL, NULL };
    size_t        lengths[4], nn, len;

    face->style_flags = 0;

    prop = bdf_get_font_property( font, "SLANT" );
    if ( prop && prop->format == BDF_ATOM                             &&
         prop->value.atom                                             &&
         ( *(prop->value.atom) == 'O' || *(prop->value.atom) == 'o' ||
           *(prop->value.atom) == 'I' || *(prop->value.atom) == 'i' ) )
    {
      face->style_flags |= FT_STYLE_FLAG_ITALIC;
      strings[2] = ( *(prop->value.atom) == 'O' || *(prop->value.atom) == 'o' )
                   ? "Oblique"
                   : "Italic";
    }

    prop = bdf_get_font_property( font, "WEIGHT_NAME" );
    if ( prop && prop->format == BDF_ATOM                             &&
         prop->value.atom                                             &&
         ( *(prop->value.atom) == 'B' || *(prop->value.atom) == 'b' ) )
    {
      face->style_flags |= FT_STYLE_FLAG_BOLD;
      strings[1] = "Bold";
    }

    prop = bdf_get_font_property( font, "SETWIDTH_NAME" );
    if ( prop && prop->format == BDF_ATOM                              &&
         prop->value.atom && *(prop->value.atom)                       &&
         !( *(prop->value.atom) == 'N' || *(prop->value.atom) == 'n' ) )
      strings[3] = (const char *)(prop->value.atom);

    prop = bdf_get_font_property( font, "ADD_STYLE_NAME" );
    if ( prop && prop->format == BDF_ATOM                              &&
         prop->value.atom && *(prop->value.atom)                       &&
         !( *(prop->value.atom) == 'N' || *(prop->value.atom) == 'n' ) )
      strings[0] = (const char *)(prop->value.atom);

    for ( len = 0, nn = 0; nn < 4; nn++ )
    {
      lengths[nn] = 0;
      if ( strings[nn] )
      {
        lengths[nn] = ft_strlen( strings[nn] );
        len        += lengths[nn] + 1;
      }
    }

    if ( len == 0 )
    {
      strings[0] = "Regular";
      lengths[0] = ft_strlen( strings[0] );
      len        = lengths[0] + 1;
    }

    {
      char*  s;

      if ( FT_ALLOC( face->style_name, len ) )
        return error;

      s = face->style_name;

      for ( nn = 0; nn < 4; nn++ )
      {
        const char*  src = strings[nn];

        len = lengths[nn];

        if ( !src )
          continue;

        /* separate elements with a space */
        if ( s != face->style_name )
          *s++ = ' ';

        ft_memcpy( s, src, len );

        /* need to convert spaces to dashes for */
        /* add_style_name and setwidth_name     */
        if ( nn == 0 || nn == 3 )
        {
          size_t  mm;

          for ( mm = 0; mm < len; mm++ )
            if ( s[mm] == ' ' )
              s[mm] = '-';
        }

        s += len;
      }
      *s = 0;
    }

    return error;
  }

  FT_CALLBACK_DEF( void )
  BDF_Face_Done( FT_Face  bdfface )         /* BDF_Face */
  {
    BDF_Face   face = (BDF_Face)bdfface;
    FT_Memory  memory;

    if ( !face )
      return;

    memory = FT_FACE_MEMORY( face );

    bdf_free_font( face->bdffont );

    FT_FREE( face->en_table );

    FT_FREE( face->charset_encoding );
    FT_FREE( face->charset_registry );
    FT_FREE( bdfface->family_name );
    FT_FREE( bdfface->style_name );

    FT_FREE( bdfface->available_sizes );

    FT_FREE( face->bdffont );
  }

  FT_CALLBACK_DEF( FT_Error )
  BDF_Face_Init( FT_Stream      stream,
                 FT_Face        bdfface,        /* BDF_Face */
                 FT_Int         face_index,
                 FT_Int         num_params,
                 FT_Parameter*  params )
  {
    FT_Error       error  = FT_Err_Ok;
    BDF_Face       face   = (BDF_Face)bdfface;
    FT_Memory      memory = FT_FACE_MEMORY( face );

    bdf_font_t*    font = NULL;
    bdf_options_t  options;

    FT_UNUSED( num_params );
    FT_UNUSED( params );

    FT_TRACE2(( "BDF driver\n" ));

    if ( FT_STREAM_SEEK( 0 ) )
      goto Exit;

    options.correct_metrics = 1;   /* FZ XXX: options semantics */
    options.keep_unencoded  = 1;
    options.keep_comments   = 0;
    options.font_spacing    = BDF_PROPORTIONAL;

    error = bdf_load_font( stream, memory, &options, &font );
    if ( FT_ERR_EQ( error, Missing_Startfont_Field ) )
    {
      FT_TRACE2(( "  not a BDF file\n" ));
      goto Fail;
    }
    else if ( error )
      goto Exit;

    /* we have a bdf font: let's construct the face object */
    face->bdffont = font;

    /* BDF cannot have multiple faces in a single font file.
     * XXX: non-zero face_index is already invalid argument, but
     *      Type1, Type42 driver has a convention to return
     *      an invalid argument error when the font could be
     *      opened by the specified driver.
     */
    if ( face_index > 0 && ( face_index & 0xFFFF ) > 0 )
    {
      FT_ERROR(( "BDF_Face_Init: invalid face index\n" ));
      BDF_Face_Done( bdfface );
      return FT_THROW( Invalid_Argument );
    }

    {
      bdf_property_t*  prop = NULL;

      FT_TRACE4(( "  number of glyphs: allocated %d (used %d)\n",
                  font->glyphs_size,
                  font->glyphs_used ));
      FT_TRACE4(( "  number of unencoded glyphs: allocated %d (used %d)\n",
                  font->unencoded_size,
                  font->unencoded_used ));

      bdfface->num_faces  = 1;
      bdfface->face_index = 0;

      bdfface->face_flags |= FT_FACE_FLAG_FIXED_SIZES |
                             FT_FACE_FLAG_HORIZONTAL;

      prop = bdf_get_font_property( font, "SPACING" );
      if ( prop && prop->format == BDF_ATOM                             &&
           prop->value.atom                                             &&
           ( *(prop->value.atom) == 'M' || *(prop->value.atom) == 'm' ||
             *(prop->value.atom) == 'C' || *(prop->value.atom) == 'c' ) )
        bdfface->face_flags |= FT_FACE_FLAG_FIXED_WIDTH;

      /* FZ XXX: TO DO: FT_FACE_FLAGS_VERTICAL   */
      /* FZ XXX: I need a font to implement this */

      prop = bdf_get_font_property( font, "FAMILY_NAME" );
      if ( prop && prop->value.atom )
      {
        if ( FT_STRDUP( bdfface->family_name, prop->value.atom ) )
          goto Exit;
      }
      else
        bdfface->family_name = NULL;

      if ( FT_SET_ERROR( bdf_interpret_style( face ) ) )
        goto Exit;

      /* the number of glyphs (with one slot for the undefined glyph */
      /* at position 0 and all unencoded glyphs)                     */
      bdfface->num_glyphs = (FT_Long)( font->glyphs_size + 1 );

      bdfface->num_fixed_sizes = 1;
      if ( FT_NEW_ARRAY( bdfface->available_sizes, 1 ) )
        goto Exit;

      {
        FT_Bitmap_Size*  bsize = bdfface->available_sizes;
        FT_Short         resolution_x = 0, resolution_y = 0;
        long             value;

        FT_ZERO( bsize );

        /* sanity checks */
        if ( font->font_ascent > 0x7FFF || font->font_ascent < -0x7FFF )
        {
          font->font_ascent = font->font_ascent < 0 ? -0x7FFF : 0x7FFF;
          FT_TRACE0(( "BDF_Face_Init: clamping font ascent to value %d\n",
                      font->font_ascent ));
        }
        if ( font->font_descent > 0x7FFF || font->font_descent < -0x7FFF )
        {
          font->font_descent = font->font_descent < 0 ? -0x7FFF : 0x7FFF;
          FT_TRACE0(( "BDF_Face_Init: clamping font descent to value %d\n",
                      font->font_descent ));
        }

        bsize->height = (FT_Short)( font->font_ascent + font->font_descent );

        prop = bdf_get_font_property( font, "AVERAGE_WIDTH" );
        if ( prop )
        {
#ifdef FT_DEBUG_LEVEL_TRACE
          if ( prop->value.l < 0 )
            FT_TRACE0(( "BDF_Face_Init: negative average width\n" ));
#endif
          if ( prop->value.l >    0x7FFFL * 10 - 5   ||
               prop->value.l < -( 0x7FFFL * 10 - 5 ) )
          {
            bsize->width = 0x7FFF;
            FT_TRACE0(( "BDF_Face_Init: clamping average width to value %d\n",
                        bsize->width ));
          }
          else
            bsize->width = FT_ABS( (FT_Short)( ( prop->value.l + 5 ) / 10 ) );
        }
        else
        {
          /* this is a heuristical value */
          bsize->width = (FT_Short)FT_MulDiv( bsize->height, 2, 3 );
        }

        prop = bdf_get_font_property( font, "POINT_SIZE" );
        if ( prop )
        {
#ifdef FT_DEBUG_LEVEL_TRACE
          if ( prop->value.l < 0 )
            FT_TRACE0(( "BDF_Face_Init: negative point size\n" ));
#endif
          /* convert from 722.7 decipoints to 72 points per inch */
          if ( prop->value.l >  0x504C2L || /* 0x7FFF * 72270/7200 */
               prop->value.l < -0x504C2L )
          {
            bsize->size = 0x7FFF;
            FT_TRACE0(( "BDF_Face_Init: clamping point size to value %d\n",
                        bsize->size ));
          }
          else
            bsize->size = FT_MulDiv( FT_ABS( prop->value.l ),
                                     64 * 7200,
                                     72270L );
        }
        else if ( font->point_size )
        {
          if ( font->point_size > 0x7FFF )
          {
            bsize->size = 0x7FFF;
            FT_TRACE0(( "BDF_Face_Init: clamping point size to value %d\n",
                        bsize->size ));
          }
          else
            bsize->size = (FT_Pos)font->point_size << 6;
        }
        else
        {
          /* this is a heuristical value */
          bsize->size = bsize->width * 64;
        }

        prop = bdf_get_font_property( font, "PIXEL_SIZE" );
        if ( prop )
        {
#ifdef FT_DEBUG_LEVEL_TRACE
          if ( prop->value.l < 0 )
            FT_TRACE0(( "BDF_Face_Init: negative pixel size\n" ));
#endif
          if ( prop->value.l > 0x7FFF || prop->value.l < -0x7FFF )
          {
            bsize->y_ppem = 0x7FFF << 6;
            FT_TRACE0(( "BDF_Face_Init: clamping pixel size to value %d\n",
                        bsize->y_ppem ));
          }
          else
            bsize->y_ppem = FT_ABS( (FT_Short)prop->value.l ) << 6;
        }

        prop = bdf_get_font_property( font, "RESOLUTION_X" );
        if ( prop )
          value = prop->value.l;
        else
          value = (long)font->resolution_x;
        if ( value )
        {
#ifdef FT_DEBUG_LEVEL_TRACE
          if ( value < 0 )
            FT_TRACE0(( "BDF_Face_Init: negative X resolution\n" ));
#endif
          if ( value > 0x7FFF || value < -0x7FFF )
          {
            resolution_x = 0x7FFF;
            FT_TRACE0(( "BDF_Face_Init: clamping X resolution to value %d\n",
                        resolution_x ));
          }
          else
            resolution_x = FT_ABS( (FT_Short)value );
        }

        prop = bdf_get_font_property( font, "RESOLUTION_Y" );
        if ( prop )
          value = prop->value.l;
        else
          value = (long)font->resolution_y;
        if ( value )
        {
#ifdef FT_DEBUG_LEVEL_TRACE
          if ( value < 0 )
            FT_TRACE0(( "BDF_Face_Init: negative Y resolution\n" ));
#endif
          if ( value > 0x7FFF || value < -0x7FFF )
          {
            resolution_y = 0x7FFF;
            FT_TRACE0(( "BDF_Face_Init: clamping Y resolution to value %d\n",
                        resolution_y ));
          }
          else
            resolution_y = FT_ABS( (FT_Short)value );
        }

        if ( bsize->y_ppem == 0 )
        {
          bsize->y_ppem = bsize->size;
          if ( resolution_y )
            bsize->y_ppem = FT_MulDiv( bsize->y_ppem, resolution_y, 72 );
        }
        if ( resolution_x && resolution_y )
          bsize->x_ppem = FT_MulDiv( bsize->y_ppem,
                                     resolution_x,
                                     resolution_y );
        else
          bsize->x_ppem = bsize->y_ppem;
      }

      /* encoding table */
      {
        bdf_glyph_t*   cur = font->glyphs;
        unsigned long  n;

        if ( FT_NEW_ARRAY( face->en_table, font->glyphs_size ) )
          goto Exit;

        face->default_glyph = 0;
        for ( n = 0; n < font->glyphs_size; n++ )
        {
          (face->en_table[n]).enc = cur[n].encoding;
          FT_TRACE4(( "  idx %d, val 0x%lX\n", n, cur[n].encoding ));
          (face->en_table[n]).glyph = (FT_UShort)n;

          if ( cur[n].encoding == font->default_char )
          {
            if ( n < FT_UINT_MAX )
              face->default_glyph = (FT_UInt)n;
            else
              FT_TRACE1(( "BDF_Face_Init:"
                          " idx %d is too large for this system\n", n ));
          }
        }
      }

      /* charmaps */
      {
        bdf_property_t  *charset_registry, *charset_encoding;
        FT_Bool          unicode_charmap  = 0;

        charset_registry =
          bdf_get_font_property( font, "CHARSET_REGISTRY" );
        charset_encoding =
          bdf_get_font_property( font, "CHARSET_ENCODING" );
        if ( charset_registry && charset_encoding )
        {
          if ( charset_registry->format == BDF_ATOM &&
               charset_encoding->format == BDF_ATOM &&
               charset_registry->value.atom         &&
               charset_encoding->value.atom         )
          {
            const char*  s;

            if ( FT_STRDUP( face->charset_encoding,
                            charset_encoding->value.atom ) ||
                 FT_STRDUP( face->charset_registry,
                            charset_registry->value.atom ) )
              goto Exit;

            /* Uh, oh, compare first letters manually to avoid dependency */
            /* on locales.                                                */
            s = face->charset_registry;
            if ( ( s[0] == 'i' || s[0] == 'I' ) &&
                 ( s[1] == 's' || s[1] == 'S' ) &&
                 ( s[2] == 'o' || s[2] == 'O' ) )
            {
              s += 3;
              if ( !ft_strcmp( s, "10646" )                      ||
                   ( !ft_strcmp( s, "8859" ) &&
                     !ft_strcmp( face->charset_encoding, "1" ) ) )
                unicode_charmap = 1;
              /* another name for ASCII */
              else if ( !ft_strcmp( s, "646.1991" )                 &&
                        !ft_strcmp( face->charset_encoding, "IRV" ) )
                unicode_charmap = 1;
            }

            {
              FT_CharMapRec  charmap;

              charmap.face        = FT_FACE( face );
              charmap.encoding    = FT_ENCODING_NONE;
              /* initial platform/encoding should indicate unset status? */
              charmap.platform_id = TT_PLATFORM_APPLE_UNICODE;
              charmap.encoding_id = TT_APPLE_ID_DEFAULT;

              if ( unicode_charmap )
              {
                charmap.encoding    = FT_ENCODING_UNICODE;
                charmap.platform_id = TT_PLATFORM_MICROSOFT;
                charmap.encoding_id = TT_MS_ID_UNICODE_CS;
              }

              error = FT_CMap_New( &bdf_cmap_class, NULL, &charmap, NULL );
            }

            goto Exit;
          }
        }

        /* otherwise assume Adobe standard encoding */

        {
          FT_CharMapRec  charmap;

          charmap.face        = FT_FACE( face );
          charmap.encoding    = FT_ENCODING_ADOBE_STANDARD;
          charmap.platform_id = TT_PLATFORM_ADOBE;
          charmap.encoding_id = TT_ADOBE_ID_STANDARD;

          error = FT_CMap_New( &bdf_cmap_class, NULL, &charmap, NULL );

          /* Select default charmap */
          if ( bdfface->num_charmaps )
            bdfface->charmap = bdfface->charmaps[0];
        }
      }
    }

  Exit:
    return error;

  Fail:
    BDF_Face_Done( bdfface );
    return FT_THROW( Unknown_File_Format );
  }

  FT_CALLBACK_DEF( FT_Error )
  BDF_Size_Select( FT_Size   size,
                   FT_ULong  strike_index )
  {
    bdf_font_t*  bdffont = ( (BDF_Face)size->face )->bdffont;

    FT_Select_Metrics( size->face, strike_index );

    size->metrics.ascender    = bdffont->font_ascent * 64;
    size->metrics.descender   = -bdffont->font_descent * 64;
    size->metrics.max_advance = bdffont->bbx.width * 64;

    return FT_Err_Ok;
  }

  FT_CALLBACK_DEF( FT_Error )
  BDF_Size_Request( FT_Size          size,
                    FT_Size_Request  req )
  {
    FT_Face          face    = size->face;
    FT_Bitmap_Size*  bsize   = face->available_sizes;
    bdf_font_t*      bdffont = ( (BDF_Face)face )->bdffont;
    FT_Error         error   = FT_ERR( Invalid_Pixel_Size );
    FT_Long          height;

    height = FT_REQUEST_HEIGHT( req );
    height = ( height + 32 ) >> 6;

    switch ( req->type )
    {
    case FT_SIZE_REQUEST_TYPE_NOMINAL:
      if ( height == ( ( bsize->y_ppem + 32 ) >> 6 ) )
        error = FT_Err_Ok;
      break;

    case FT_SIZE_REQUEST_TYPE_REAL_DIM:
      if ( height == ( bdffont->font_ascent +
                       bdffont->font_descent ) )
        error = FT_Err_Ok;
      break;

    default:
      error = FT_THROW( Unimplemented_Feature );
      break;
    }

    if ( error )
      return error;
    else
      return BDF_Size_Select( size, 0 );
  }

  FT_CALLBACK_DEF( FT_Error )
  BDF_Glyph_Load( FT_GlyphSlot  slot,
                  FT_Size       size,
                  FT_UInt       glyph_index,
                  FT_Int32      load_flags )
  {
    BDF_Face     bdf    = (BDF_Face)FT_SIZE_FACE( size );
    FT_Face      face   = FT_FACE( bdf );
    FT_Error     error  = FT_Err_Ok;
    FT_Bitmap*   bitmap = &slot->bitmap;
    bdf_glyph_t  glyph;
    int          bpp    = bdf->bdffont->bpp;

    FT_UNUSED( load_flags );

    if ( !face )
    {
      error = FT_THROW( Invalid_Face_Handle );
      goto Exit;
    }

    if ( glyph_index >= (FT_UInt)face->num_glyphs )
    {
      error = FT_THROW( Invalid_Argument );
      goto Exit;
    }

    FT_TRACE1(( "BDF_Glyph_Load: glyph index %d\n", glyph_index ));

    /* index 0 is the undefined glyph */
    if ( glyph_index == 0 )
      glyph_index = bdf->default_glyph;
    else
      glyph_index--;

    /* slot, bitmap => freetype, glyph => bdflib */
    glyph = bdf->bdffont->glyphs[glyph_index];

    bitmap->rows  = glyph.bbx.height;
    bitmap->width = glyph.bbx.width;
    if ( glyph.bpr > FT_INT_MAX )
      FT_TRACE1(( "BDF_Glyph_Load: too large pitch %d is truncated\n",
                   glyph.bpr ));
    bitmap->pitch = (int)glyph.bpr; /* same as FT_Bitmap.pitch */

    /* note: we don't allocate a new array to hold the bitmap; */
    /*       we can simply point to it                         */
    ft_glyphslot_set_bitmap( slot, glyph.bitmap );

    switch ( bpp )
    {
    case 1:
      bitmap->pixel_mode = FT_PIXEL_MODE_MONO;
      break;
    case 2:
      bitmap->pixel_mode = FT_PIXEL_MODE_GRAY2;
      break;
    case 4:
      bitmap->pixel_mode = FT_PIXEL_MODE_GRAY4;
      break;
    case 8:
      bitmap->pixel_mode = FT_PIXEL_MODE_GRAY;
      bitmap->num_grays  = 256;
      break;
    }

    slot->format      = FT_GLYPH_FORMAT_BITMAP;
    slot->bitmap_left = glyph.bbx.x_offset;
    slot->bitmap_top  = glyph.bbx.ascent;

    slot->metrics.horiAdvance  = (FT_Pos)( glyph.dwidth * 64 );
    slot->metrics.horiBearingX = (FT_Pos)( glyph.bbx.x_offset * 64 );
    slot->metrics.horiBearingY = (FT_Pos)( glyph.bbx.ascent * 64 );
    slot->metrics.width        = (FT_Pos)( bitmap->width * 64 );
    slot->metrics.height       = (FT_Pos)( bitmap->rows * 64 );

    /*
     * XXX DWIDTH1 and VVECTOR should be parsed and
     * used here, provided such fonts do exist.
     */
    ft_synthesize_vertical_metrics( &slot->metrics,
                                    bdf->bdffont->bbx.height * 64 );

  Exit:
    return error;
  }

 /*
  *
  * BDF SERVICE
  *
  */

  static FT_Error
  bdf_get_bdf_property( BDF_Face          face,
                        const char*       prop_name,
                        BDF_PropertyRec  *aproperty )
  {
    bdf_property_t*  prop;

    FT_ASSERT( face && face->bdffont );

    prop = bdf_get_font_property( face->bdffont, prop_name );
    if ( prop )
    {
      switch ( prop->format )
      {
      case BDF_ATOM:
        aproperty->type   = BDF_PROPERTY_TYPE_ATOM;
        aproperty->u.atom = prop->value.atom;
        break;

      case BDF_INTEGER:
        if ( prop->value.l > 0x7FFFFFFFL || prop->value.l < ( -1 - 0x7FFFFFFFL ) )
        {
          FT_TRACE1(( "bdf_get_bdf_property:"
                      " too large integer 0x%x is truncated\n" ));
        }
        aproperty->type      = BDF_PROPERTY_TYPE_INTEGER;
        aproperty->u.integer = (FT_Int32)prop->value.l;
        break;

      case BDF_CARDINAL:
        if ( prop->value.ul > 0xFFFFFFFFUL )
        {
          FT_TRACE1(( "bdf_get_bdf_property:"
                      " too large cardinal 0x%x is truncated\n" ));
        }
        aproperty->type       = BDF_PROPERTY_TYPE_CARDINAL;
        aproperty->u.cardinal = (FT_UInt32)prop->value.ul;
        break;

      default:
        goto Fail;
      }
      return 0;
    }

  Fail:
    return FT_THROW( Invalid_Argument );
  }

  static FT_Error
  bdf_get_charset_id( BDF_Face      face,
                      const char*  *acharset_encoding,
                      const char*  *acharset_registry )
  {
    *acharset_encoding = face->charset_encoding;
    *acharset_registry = face->charset_registry;

    return 0;
  }

  static const FT_Service_BDFRec  bdf_service_bdf =
  {
    (FT_BDF_GetCharsetIdFunc)bdf_get_charset_id,       /* get_charset_id */
    (FT_BDF_GetPropertyFunc) bdf_get_bdf_property      /* get_property   */
  };

 /*
  *
  * SERVICES LIST
  *
  */

  static const FT_ServiceDescRec  bdf_services[] =
  {
    { FT_SERVICE_ID_BDF,         &bdf_service_bdf },
    { FT_SERVICE_ID_FONT_FORMAT, FT_FONT_FORMAT_BDF },
    { NULL, NULL }
  };

  FT_CALLBACK_DEF( FT_Module_Interface )
  bdf_driver_requester( FT_Module    module,
                        const char*  name )
  {
    FT_UNUSED( module );

    return ft_service_list_lookup( bdf_services, name );
  }

  FT_CALLBACK_TABLE_DEF
  const FT_Driver_ClassRec  bdf_driver_class =
  {
    {
      FT_MODULE_FONT_DRIVER         |
      FT_MODULE_DRIVER_NO_OUTLINES,
      sizeof ( FT_DriverRec ),

      "bdf",
      0x10000L,
      0x20000L,

      NULL,    /* module-specific interface */

      NULL,                     /* FT_Module_Constructor  module_init   */
      NULL,                     /* FT_Module_Destructor   module_done   */
      bdf_driver_requester      /* FT_Module_Requester    get_interface */
    },

    sizeof ( BDF_FaceRec ),
    sizeof ( FT_SizeRec ),
    sizeof ( FT_GlyphSlotRec ),

    BDF_Face_Init,              /* FT_Face_InitFunc  init_face */
    BDF_Face_Done,              /* FT_Face_DoneFunc  done_face */
    NULL,                       /* FT_Size_InitFunc  init_size */
    NULL,                       /* FT_Size_DoneFunc  done_size */
    NULL,                       /* FT_Slot_InitFunc  init_slot */
    NULL,                       /* FT_Slot_DoneFunc  done_slot */

    BDF_Glyph_Load,             /* FT_Slot_LoadFunc  load_glyph */

    NULL,                       /* FT_Face_GetKerningFunc   get_kerning  */
    NULL,                       /* FT_Face_AttachFunc       attach_file  */
    NULL,                       /* FT_Face_GetAdvancesFunc  get_advances */

    BDF_Size_Request,           /* FT_Size_RequestFunc  request_size */
    BDF_Size_Select             /* FT_Size_SelectFunc   select_size  */
  };

/* END */


text:
/*
 * Copyright 2000 Computing Research Labs, New Mexico State University
 * Copyright 2001-2004, 2011 Francesco Zappa Nardelli
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COMPUTING RESEARCH LAB OR NEW MEXICO STATE UNIVERSITY BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
 * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
 * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#ifndef BDF_H_
#define BDF_H_

/*
 * Based on bdf.h,v 1.16 2000/03/16 20:08:51 mleisher
 */

#include <ft2build.h>
#include FT_INTERNAL_OBJECTS_H
#include FT_INTERNAL_STREAM_H
#include FT_INTERNAL_HASH_H

FT_BEGIN_HEADER

/* Imported from bdfP.h */

#define _bdf_glyph_modified( map, e )                     \
          ( (map)[(e) >> 5] & ( 1UL << ( (e) & 31 ) ) )
#define _bdf_set_glyph_modified( map, e )                 \
          ( (map)[(e) >> 5] |= ( 1UL << ( (e) & 31 ) ) )
#define _bdf_clear_glyph_modified( map, e )               \
          ( (map)[(e) >> 5] &= ~( 1UL << ( (e) & 31 ) ) )

/* end of bdfP.h */

  /**************************************************************************
   *
   * BDF font options macros and types.
   *
   */

#define BDF_CORRECT_METRICS  0x01 /* Correct invalid metrics when loading. */
#define BDF_KEEP_COMMENTS    0x02 /* Preserve the font comments.           */
#define BDF_KEEP_UNENCODED   0x04 /* Keep the unencoded glyphs.            */
#define BDF_PROPORTIONAL     0x08 /* Font has proportional spacing.        */
#define BDF_MONOWIDTH        0x10 /* Font has mono width.                  */
#define BDF_CHARCELL         0x20 /* Font has charcell spacing.            */

#define BDF_ALL_SPACING  ( BDF_PROPORTIONAL | \
                           BDF_MONOWIDTH    | \
                           BDF_CHARCELL     )

#define BDF_DEFAULT_LOAD_OPTIONS  ( BDF_CORRECT_METRICS | \
                                    BDF_KEEP_COMMENTS   | \
                                    BDF_KEEP_UNENCODED  | \
                                    BDF_PROPORTIONAL    )

  typedef struct  bdf_options_t_
  {
    int            correct_metrics;
    int            keep_unencoded;
    int            keep_comments;
    int            font_spacing;

  } bdf_options_t;

  /* Callback function type for unknown configuration options. */
  typedef int
  (*bdf_options_callback_t)( bdf_options_t*  opts,
                             char**          params,
                             unsigned long   nparams,
                             void*           client_data );

  /**************************************************************************
   *
   * BDF font property macros and types.
   *
   */

#define BDF_ATOM      1
#define BDF_INTEGER   2
#define BDF_CARDINAL  3

  /* This structure represents a particular property of a font. */
  /* There are a set of defaults and each font has their own.   */
  typedef struct  bdf_property_t_
  {
    const char*  name;         /* Name of the property.   */
    int          format;       /* Format of the property. */
    int          builtin;      /* A builtin property.     */
    union
    {
      char*          atom;
      long           l;
      unsigned long  ul;

    } value;             /* Value of the property.  */

  } bdf_property_t;

  /**************************************************************************
   *
   * BDF font metric and glyph types.
   *
   */

  typedef struct  bdf_bbx_t_
  {
    unsigned short  width;
    unsigned short  height;

    short           x_offset;
    short           y_offset;

    short           ascent;
    short           descent;

  } bdf_bbx_t;

  typedef struct  bdf_glyph_t_
  {
    char*           name;        /* Glyph name.                          */
    unsigned long   encoding;    /* Glyph encoding.                      */
    unsigned short  swidth;      /* Scalable width.                      */
    unsigned short  dwidth;      /* Device width.                        */
    bdf_bbx_t       bbx;         /* Glyph bounding box.                  */
    unsigned char*  bitmap;      /* Glyph bitmap.                        */
    unsigned long   bpr;         /* Number of bytes used per row.        */
    unsigned short  bytes;       /* Number of bytes used for the bitmap. */

  } bdf_glyph_t;

  typedef struct  bdf_font_t_
  {
    char*            name;           /* Name of the font.                   */
    bdf_bbx_t        bbx;            /* Font bounding box.                  */

    unsigned long    point_size;     /* Point size of the font.             */
    unsigned long    resolution_x;   /* Font horizontal resolution.         */
    unsigned long    resolution_y;   /* Font vertical resolution.           */

    int              spacing;        /* Font spacing value.                 */

    unsigned short   monowidth;      /* Logical width for monowidth font.   */

    unsigned long    default_char;   /* Encoding of the default glyph.      */

    long             font_ascent;    /* Font ascent.                        */
    long             font_descent;   /* Font descent.                       */

    unsigned long    glyphs_size;    /* Glyph structures allocated.         */
    unsigned long    glyphs_used;    /* Glyph structures used.              */
    bdf_glyph_t*     glyphs;         /* Glyphs themselves.                  */

    unsigned long    unencoded_size; /* Unencoded glyph struct. allocated.  */
    unsigned long    unencoded_used; /* Unencoded glyph struct. used.       */
    bdf_glyph_t*     unencoded;      /* Unencoded glyphs themselves.        */

    unsigned long    props_size;     /* Font properties allocated.          */
    unsigned long    props_used;     /* Font properties used.               */
    bdf_property_t*  props;          /* Font properties themselves.         */

    char*            comments;       /* Font comments.                      */
    unsigned long    comments_len;   /* Length of comment string.           */

    void*            internal;       /* Internal data for the font.         */

    unsigned short   bpp;            /* Bits per pixel.                     */

    FT_Memory        memory;

    bdf_property_t*  user_props;
    unsigned long    nuser_props;
    FT_HashRec       proptbl;

  } bdf_font_t;

  /**************************************************************************
   *
   * Types for load/save callbacks.
   *
   */

  /* Error codes. */
#define BDF_MISSING_START       -1
#define BDF_MISSING_FONTNAME    -2
#define BDF_MISSING_SIZE        -3
#define BDF_MISSING_CHARS       -4
#define BDF_MISSING_STARTCHAR   -5
#define BDF_MISSING_ENCODING    -6
#define BDF_MISSING_BBX         -7

#define BDF_OUT_OF_MEMORY      -20

#define BDF_INVALID_LINE      -100

  /**************************************************************************
   *
   * BDF font API.
   *
   */

  FT_LOCAL( FT_Error )
  bdf_load_font( FT_Stream       stream,
                 FT_Memory       memory,
                 bdf_options_t*  opts,
                 bdf_font_t*    *font );

  FT_LOCAL( void )
  bdf_free_font( bdf_font_t*  font );

  FT_LOCAL( bdf_property_t * )
  bdf_get_property( char*        name,
                    bdf_font_t*  font );

  FT_LOCAL( bdf_property_t * )
  bdf_get_font_property( bdf_font_t*  font,
                         const char*  name );

FT_END_HEADER

#endif /* BDF_H_ */

/* END */


text:
/*
 * Copyright 2001, 2002, 2012 Francesco Zappa Nardelli
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COMPUTING RESEARCH LAB OR NEW MEXICO STATE UNIVERSITY BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
 * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
 * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

  /**************************************************************************
   *
   * This file is used to define the BDF error enumeration constants.
   *
   */

#ifndef BDFERROR_H_
#define BDFERROR_H_

#include FT_MODULE_ERRORS_H

#undef FTERRORS_H_

#undef  FT_ERR_PREFIX
#define FT_ERR_PREFIX  BDF_Err_
#define FT_ERR_BASE    FT_Mod_Err_BDF

#include FT_ERRORS_H

#endif /* BDFERROR_H_ */

/* END */


text:
# FreeType 2 src/bdf Jamfile
#
# Copyright (C) 2002-2020 by
# David Turner, Robert Wilhelm, and Werner Lemberg.
#
# This file is part of the FreeType project, and may only be used, modified,
# and distributed under the terms of the FreeType project license,
# LICENSE.TXT.  By continuing to use, modify, or distribute this file you
# indicate that you have read the license and understand and accept it
# fully.

SubDir  FT2_TOP $(FT2_SRC_DIR) bdf ;

{
  local  _sources ;

  if $(FT2_MULTI)
  {
    _sources = bdfdrivr
               bdflib
               ;
  }
  else
  {
    _sources = bdf ;
  }

  Library  $(FT2_LIB) : $(_sources).c ;
}

# end of src/bdf Jamfile


text:
#
# FreeType 2 BDF module definition
#

# Copyright 2001, 2002, 2006 by
# Francesco Zappa Nardelli
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

FTMODULE_H_COMMANDS += BDF_DRIVER

define BDF_DRIVER
$(OPEN_DRIVER) FT_Driver_ClassRec, bdf_driver_class $(CLOSE_DRIVER)
$(ECHO_DRIVER)bdf       $(ECHO_DRIVER_DESC)bdf bitmap fonts$(ECHO_DRIVER_DONE)
endef

# EOF


text:
                  FreeType font driver for BDF fonts

                       Francesco Zappa Nardelli
                  <francesco.zappa.nardelli@ens.fr>

Introduction
************

BDF (Bitmap Distribution Format) is a bitmap font format defined by Adobe,
which is intended to be easily understood by both humans and computers.
This code implements a BDF driver for the FreeType library, following the
Adobe Specification V 2.2.  The specification of the BDF font format is
available from Adobe's web site:

  https://www.adobe.com/content/dam/acom/en/devnet/font/pdfs/5005.BDF_Spec.pdf

Many good bitmap fonts in bdf format come with XFree86 (www.XFree86.org).
They do not define vertical metrics, because the X Consortium BDF
specification has removed them.

Encodings
*********

The variety of encodings that accompanies bdf fonts appears to encompass the
small set defined in freetype.h.  On the other hand, two properties that
specify encoding and registry are usually defined in bdf fonts.

I decided to make these two properties directly accessible, leaving to the
client application the work of interpreting them.  For instance:

  #include FT_INTERNAL_BDF_TYPES_H

  FT_Face          face;
  BDF_Public_Face  bdfface;

  FT_New_Face( library, ..., &face );

  bdfface = (BDF_Public_Face)face;

  if ( ( bdfface->charset_registry == "ISO10646" ) &&
       ( bdfface->charset_encoding == "1" )        )
    [..]

Thus the driver always exports `ft_encoding_none' as face->charmap.encoding.
FT_Get_Char_Index's behavior is unmodified, that is, it converts the ULong
value given as argument into the corresponding glyph number.

If the two properties are not available, Adobe Standard Encoding should be
assumed.

Anti-Aliased Bitmaps
********************

The driver supports an extension to the BDF format as used in Mark Leisher's
xmbdfed bitmap font editor.  Microsoft's SBIT tool expects bitmap fonts in
that format for adding anti-aliased them to TrueType fonts.  It introduces a
fourth field to the `SIZE' keyword which gives the bpp value (bits per
pixel) of the glyph data in the font.  Possible values are 1 (the default),
2 (four gray levels), 4 (16 gray levels), and 8 (256 gray levels).  The
driver returns either a bitmap with 1 bit per pixel or a pixmap with 8bits
per pixel (using 4, 16, and 256 gray levels, respectively).

Known problems
**************

- A font is entirely loaded into memory.  Obviously, this is not the Right
  Thing(TM).  If you have big fonts I suggest you convert them into PCF
  format (using the bdftopcf utility): the PCF font drive of FreeType can
  perform incremental glyph loading.

When I have some time, I will implement on-demand glyph parsing.

- Except for encodings properties, client applications have no visibility of
  the PCF_Face object.  This means that applications cannot directly access
  font tables and must trust FreeType.

- Currently, glyph names are ignored.

  I plan to give full visibility of the BDF_Face object in an upcoming
  revision of the driver, thus implementing also glyph names.

- As I have never seen a BDF font that defines vertical metrics, vertical
  metrics are (parsed and) discarded.  If you own a BDF font that defines
  vertical metrics, please let me know (I will implement them in 5-10
  minutes).

License
*******

Copyright (C) 2001-2002 by Francesco Zappa Nardelli

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*** Portions of the driver (that is, bdflib.c and bdf.h):

Copyright 2000 Computing Research Labs, New Mexico State University
Copyright 2001-2002, 2011 Francesco Zappa Nardelli

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
THE COMPUTING RESEARCH LAB OR NEW MEXICO STATE UNIVERSITY BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Credits
*******

This driver is based on excellent Mark Leisher's bdf library.  If you
find something good in this driver you should probably thank him, not
me.