sfnt2fnt.c 24.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * sfnttofnt.  Bitmap only ttf to Window fnt file converter
 *
 * Copyright 2004 Huw Davies
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19 20 21
 */

#include "config.h"
22
#include "wine/port.h"
23 24 25

#include <assert.h>
#include <ctype.h>
26
#include <errno.h>
27
#include <signal.h>
28
#include <stdio.h>
29
#include <stdlib.h>
30 31 32
#ifdef HAVE_GETOPT_H
# include <getopt.h>
#endif
33 34 35 36 37 38 39 40 41

#ifdef HAVE_FREETYPE

#ifdef HAVE_FT2BUILD_H
#include <ft2build.h>
#endif
#include FT_FREETYPE_H
#include FT_SFNT_NAMES_H
#include FT_TRUETYPE_TABLES_H
42
#include FT_TRUETYPE_TAGS_H
43 44 45
#ifdef HAVE_FREETYPE_INTERNAL_SFNT_H
#include <freetype/internal/sfnt.h>
#endif
46 47

#include "wine/unicode.h"
48
#include "wine/wingdi16.h"
49 50
#include "wingdi.h"

51
#include "pshpack1.h"
52 53 54 55 56 57

typedef struct
{
    WORD dfVersion;
    DWORD dfSize;
    char dfCopyright[60];
58
    FONTINFO16 fi;
59 60 61 62 63 64 65
} FNT_HEADER;

typedef struct {
    WORD width;
    DWORD offset;
} CHAR_TABLE_ENTRY;

66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
typedef struct {
    DWORD version;
    ULONG numSizes;
} eblcHeader_t;

typedef struct {
    CHAR ascender;
    CHAR descender;
    BYTE widthMax;
    CHAR caretSlopeNumerator;
    CHAR caretSlopeDenominator;
    CHAR caretOffset;
    CHAR minOriginSB;
    CHAR minAdvanceSB;
    CHAR maxBeforeBL;
    CHAR maxAfterBL;
    CHAR pad1;
    CHAR pad2;
} sbitLineMetrics_t;

typedef struct {
    ULONG indexSubTableArrayOffset;
    ULONG indexTableSize;
    ULONG numberOfIndexSubTables;
    ULONG colorRef;
    sbitLineMetrics_t hori;
    sbitLineMetrics_t vert;
    USHORT startGlyphIndex;
    USHORT endGlyphIndex;
    BYTE ppemX;
    BYTE ppemY;
    BYTE bitDepth;
    CHAR flags;
} bitmapSizeTable_t;

101 102 103 104 105 106 107 108
typedef struct
{
    FT_Int major;
    FT_Int minor;
    FT_Int patch;
} FT_Version_t;
static FT_Version_t FT_Version;

109 110 111 112
#define GET_BE_WORD(ptr)  MAKEWORD( ((BYTE *)(ptr))[1], ((BYTE *)(ptr))[0] )
#define GET_BE_DWORD(ptr) ((DWORD)MAKELONG( GET_BE_WORD(&((WORD *)(ptr))[1]), \
                                            GET_BE_WORD(&((WORD *)(ptr))[0]) ))

113
#include "poppack.h"
114

115 116 117 118 119 120 121
struct fontinfo
{
    FNT_HEADER hdr;
    CHAR_TABLE_ENTRY dfCharTable[258];
    BYTE *data;
};

122 123 124 125 126 127 128 129 130 131 132 133
static const BYTE MZ_hdr[] =
{
    'M',  'Z',  0x0d, 0x01, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00,
    0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00,
    0x0e, 0x1f, 0xba, 0x0e, 0x00, 0xb4, 0x09, 0xcd, 0x21, 0xb8, 0x01, 0x4c, 0xcd, 0x21, 'T',  'h',
    'i',  's',  ' ',  'P',  'r',  'o',  'g',  'r',  'a',  'm',  ' ',  'c',  'a',  'n',  'n',  'o',
    't',  ' ',  'b',  'e',  ' ',  'r',  'u',  'n',  ' ',  'i',  'n',  ' ',  'D',  'O',  'S',  ' ',
    'm',  'o',  'd',  'e',  0x0d, 0x0a, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};

134 135 136 137 138 139
static char *option_output;
static int option_defchar = ' ';
static int option_dpi = 96;
static int option_fnt_mode = 0;
static int option_quiet = 0;

140 141
static const char *output_name;

142 143
static FT_Library ft_library;

144
static void usage(char **argv)
145
{
146 147 148 149 150 151 152 153
    fprintf(stderr, "%s [options] input.ttf ppem,enc,avg_width ...\n", argv[0]);
    fprintf(stderr, "Options:\n");
    fprintf(stderr, "  -h       Display help\n" );
    fprintf(stderr, "  -d char  Set the font default char\n" );
    fprintf(stderr, "  -o file  Set output file name\n" );
    fprintf(stderr, "  -q       Quiet mode\n" );
    fprintf(stderr, "  -r dpi   Set resolution in DPI (default: 96)\n" );
    fprintf(stderr, "  -s       Single .fnt file mode\n" );
154 155
}

156 157 158 159
#ifndef __GNUC__
#define __attribute__(X)
#endif

160 161 162 163 164 165
/* atexit handler to cleanup files */
static void cleanup(void)
{
    if (output_name) unlink( output_name );
}

166 167 168 169 170
static void exit_on_signal( int sig )
{
    exit(1);  /* this will call the atexit functions */
}

171 172 173 174 175 176 177 178 179 180 181 182
static void error(const char *s, ...) __attribute__((format (printf, 1, 2)));

static void error(const char *s, ...)
{
    va_list ap;
    va_start(ap, s);
    fprintf(stderr, "Error: ");
    vfprintf(stderr, s, ap);
    va_end(ap);
    exit(1);
}

183 184 185 186 187
static const char *get_face_name( const struct fontinfo *info )
{
    return (const char *)info->data + info->hdr.fi.dfFace - info->hdr.fi.dfBitsOffset;
}

188
static int lookup_charset(int enc)
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
{
    /* FIXME: make winelib app and use TranslateCharsetInfo */
    switch(enc) {
    case 1250:
        return EE_CHARSET;
    case 1251:
        return RUSSIAN_CHARSET;
    case 1252:
        return ANSI_CHARSET;
    case 1253:
        return GREEK_CHARSET;
    case 1254:
        return TURKISH_CHARSET;
    case 1255:
        return HEBREW_CHARSET;
    case 1256:
        return ARABIC_CHARSET;
    case 1257:
        return BALTIC_CHARSET;
    case 1258:
        return VIETNAMESE_CHARSET;
    case 437:
    case 737:
    case 775:
    case 850:
    case 852:
    case 855:
    case 857:
    case 860:
    case 861:
    case 862:
    case 863:
    case 864:
    case 865:
    case 866:
    case 869:
        return OEM_CHARSET;
    case 874:
        return THAI_CHARSET;
    case 932:
        return SHIFTJIS_CHARSET;
    case 936:
        return GB2312_CHARSET;
    case 949:
        return HANGUL_CHARSET;
    case 950:
        return CHINESEBIG5_CHARSET;
    }
    fprintf(stderr, "Unknown encoding %d - using OEM_CHARSET\n", enc);

    return OEM_CHARSET;
}

242 243 244 245 246 247 248 249 250
static int get_char(const union cptable *cptable, int enc, int index)
{
    /* Korean has the Won sign in place of '\\' */
    if(enc == 949 && index == '\\')
        return 0x20a9;

    return cptable->sbcs.cp2uni[index];
}

251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
/* from gdi32/freetype.c */
static FT_Error load_sfnt_table(FT_Face ft_face, FT_ULong table, FT_Long offset, FT_Byte *buf, FT_ULong *len)
{

    FT_Error err;

    /* If the FT_Load_Sfnt_Table function is there we'll use it */
#ifdef HAVE_FT_LOAD_SFNT_TABLE
    err = FT_Load_Sfnt_Table(ft_face, table, offset, buf, len);
#elif defined(HAVE_FREETYPE_INTERNAL_SFNT_H)
    TT_Face tt_face = (TT_Face) ft_face;
    SFNT_Interface *sfnt;
    if (FT_Version.major==2 && FT_Version.minor==0)
    {
        /* 2.0.x */
        sfnt = *(SFNT_Interface**)((char*)tt_face + 528);
    }
    else
    {
        /* A field was added in the middle of the structure in 2.1.x */
        sfnt = *(SFNT_Interface**)((char*)tt_face + 532);
    }
    err = sfnt->load_any(tt_face, table, offset, buf, len);
#else
    err = FT_Err_Unimplemented_Feature;
#endif
    return err;
}

280 281
static struct fontinfo *fill_fontinfo( const char *face_name, int ppem, int enc, int dpi,
                                       unsigned char def_char, int avg_width )
282
{
283 284
    FT_Face face;
    int ascent = 0, il, el, descent = 0, width_bytes = 0, space_size, max_width = 0;
285 286 287
    BYTE left_byte, right_byte, byte;
    DWORD start;
    int i, x, y, x_off, x_end, first_char;
288
    FT_UInt gi;
289 290 291 292
    int num_names;
    const union cptable *cptable;
    FT_SfntName sfntname;
    TT_OS2 *os2;
293 294 295 296
    FT_ULong needed;
    eblcHeader_t *eblc;
    bitmapSizeTable_t *size_table;
    int num_sizes;
297 298 299 300 301
    struct fontinfo *info;
    size_t data_pos;

    if (FT_New_Face(ft_library, face_name, 0, &face)) error( "Cannot open face %s\n", face_name );
    if (FT_Set_Pixel_Sizes(face, ppem, ppem)) error( "cannot set face size to %u\n", ppem );
302

303
    cptable = wine_cp_get_table(enc);
304 305
    if(!cptable)
        error("Can't find codepage %d\n", enc);
306

307
    if(cptable->info.char_size != 1) {
308 309
        /* for double byte charsets we actually want to use cp1252 */
        cptable = wine_cp_get_table(1252);
310 311
        if(!cptable)
            error("Can't find codepage 1252\n");
312 313
    }

314
    assert( face->size->metrics.y_ppem == ppem );
315 316

    needed = 0;
317 318 319 320 321 322
    if (load_sfnt_table(face, TTAG_EBLC, 0, NULL, &needed))
        fprintf(stderr,"Can't find EBLC table\n");
    else
    {
        eblc = malloc(needed);
        load_sfnt_table(face, TTAG_EBLC, 0, (FT_Byte *)eblc, &needed);
323

324
        num_sizes = GET_BE_DWORD(&eblc->numSizes);
325

326 327
        size_table = (bitmapSizeTable_t *)(eblc + 1);
        for(i = 0; i < num_sizes; i++)
328
        {
329 330 331 332 333 334 335
            if(size_table->hori.ascender - size_table->hori.descender == ppem)
            {
                ascent = size_table->hori.ascender;
                descent = -size_table->hori.descender;
                break;
            }
            size_table++;
336 337
        }

338 339
        free(eblc);
    }
340

341 342 343 344 345 346 347 348 349 350 351 352
    /* Versions of fontforge prior to early 2006 have incorrect
       ascender values in the eblc table, so we won't find the 
       correct bitmapSizeTable.  In this case use the height of
       the Aring glyph instead. */
    if(ascent == 0) 
    {
        if(FT_Load_Char(face, 0xc5, FT_LOAD_DEFAULT))
            error("Can't find Aring\n");
        ascent = face->glyph->metrics.horiBearingY >> 6;
        descent = ppem - ascent;
    }

353
    start = sizeof(FNT_HEADER);
354

355 356
    if(FT_Load_Char(face, 'M', FT_LOAD_DEFAULT))
        error("Can't find M\n");
357 358
    il = ascent - (face->glyph->metrics.height >> 6);

359 360
    /* Hack: Courier has no internal leading, nor do any Chinese or Japanese fonts */
    if(!strcmp(face->family_name, "Courier") || enc == 936 || enc == 950 || enc == 932)
361
        il = 0;
362 363
    /* Japanese system fonts have an external leading (not small font) */
    if (enc == 932 && ppem > 11)
364 365 366
        el = 2;
    else
        el = 0;
367 368 369

    first_char = FT_Get_First_Char(face, &gi);
    if(first_char == 0xd) /* fontforge's first glyph is 0xd, we'll catch this and skip it */
370 371
        first_char = 32; /* FT_Get_Next_Char for some reason returns too high
                            number in this case */
372

373
    info = calloc( 1, sizeof(*info) );
374

375 376 377
    info->hdr.fi.dfFirstChar = first_char;
    info->hdr.fi.dfLastChar = 0xff;
    start += ((unsigned char)info->hdr.fi.dfLastChar - (unsigned char)info->hdr.fi.dfFirstChar + 3 ) * sizeof(*info->dfCharTable);
378 379 380 381

    num_names = FT_Get_Sfnt_Name_Count(face);
    for(i = 0; i <num_names; i++) {
        FT_Get_Sfnt_Name(face, i, &sfntname);
382 383
        if(sfntname.platform_id == 1 && sfntname.encoding_id == 0 &&
           sfntname.language_id == 0 && sfntname.name_id == 0) {
384 385 386
            size_t len = min( sfntname.string_len, sizeof(info->hdr.dfCopyright)-1 );
            memcpy(info->hdr.dfCopyright, sfntname.string, len);
            info->hdr.dfCopyright[len] = 0;
387
        }
388 389 390 391
    }

    os2 = FT_Get_Sfnt_Table(face, ft_sfnt_os2);
    for(i = first_char; i < 0x100; i++) {
392 393
        int c = get_char(cptable, enc, i);
        gi = FT_Get_Char_Index(face, c);
394
        if(gi == 0 && !option_quiet)
395 396
            fprintf(stderr, "warning: %s %u: missing glyph for char %04x\n",
                    face->family_name, ppem, cptable->sbcs.cp2uni[i]);
397
        if(FT_Load_Char(face, c, FT_LOAD_DEFAULT)) {
398 399 400
            fprintf(stderr, "error loading char %d - bad news!\n", i);
            continue;
        }
401 402
        info->dfCharTable[i].width = face->glyph->metrics.horiAdvance >> 6;
        info->dfCharTable[i].offset = start + (width_bytes * ppem);
403 404 405 406 407 408
        width_bytes += ((face->glyph->metrics.horiAdvance >> 6) + 7) >> 3;
        if(max_width < (face->glyph->metrics.horiAdvance >> 6))
            max_width = face->glyph->metrics.horiAdvance >> 6;
    }
    /* space */
    space_size = (ppem + 3) / 4;
409 410
    info->dfCharTable[i].width = space_size;
    info->dfCharTable[i].offset = start + (width_bytes * ppem);
411 412
    width_bytes += (space_size + 7) >> 3;
    /* sentinel */
413 414 415 416
    info->dfCharTable[++i].width = 0;
    info->dfCharTable[i].offset = start + (width_bytes * ppem);

    info->hdr.fi.dfType = 0;
417
    info->hdr.fi.dfPoints = ((ppem - il - el) * 72 + dpi/2) / dpi;
418 419 420 421 422 423 424 425 426 427 428 429 430
    info->hdr.fi.dfVertRes = dpi;
    info->hdr.fi.dfHorizRes = dpi;
    info->hdr.fi.dfAscent = ascent;
    info->hdr.fi.dfInternalLeading = il;
    info->hdr.fi.dfExternalLeading = el;
    info->hdr.fi.dfItalic = (face->style_flags & FT_STYLE_FLAG_ITALIC) ? 1 : 0;
    info->hdr.fi.dfUnderline = 0;
    info->hdr.fi.dfStrikeOut = 0;
    info->hdr.fi.dfWeight = os2->usWeightClass;
    info->hdr.fi.dfCharSet = lookup_charset(enc);
    info->hdr.fi.dfPixWidth = (face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) ? avg_width : 0;
    info->hdr.fi.dfPixHeight = ppem;
    info->hdr.fi.dfPitchAndFamily = FT_IS_FIXED_WIDTH(face) ? 0 : TMPF_FIXED_PITCH;
431 432
    switch(os2->panose[PAN_FAMILYTYPE_INDEX]) {
    case PAN_FAMILY_SCRIPT:
433
        info->hdr.fi.dfPitchAndFamily |= FF_SCRIPT;
434 435 436
	break;
    case PAN_FAMILY_DECORATIVE:
    case PAN_FAMILY_PICTORIAL:
437
        info->hdr.fi.dfPitchAndFamily |= FF_DECORATIVE;
438 439
	break;
    case PAN_FAMILY_TEXT_DISPLAY:
440 441
        if(info->hdr.fi.dfPitchAndFamily == 0) /* fixed */
	    info->hdr.fi.dfPitchAndFamily = FF_MODERN;
442 443 444 445 446
	else {
	    switch(os2->panose[PAN_SERIFSTYLE_INDEX]) {
	    case PAN_SERIF_NORMAL_SANS:
	    case PAN_SERIF_OBTUSE_SANS:
	    case PAN_SERIF_PERP_SANS:
447
	        info->hdr.fi.dfPitchAndFamily |= FF_SWISS;
448 449
		break;
	    default:
450
	        info->hdr.fi.dfPitchAndFamily |= FF_ROMAN;
451 452 453 454
	    }
	}
	break;
    default:
455
        info->hdr.fi.dfPitchAndFamily |= FF_DONTCARE;
456 457
    }

458 459 460 461 462
    info->hdr.fi.dfAvgWidth = avg_width;
    info->hdr.fi.dfMaxWidth = max_width;
    info->hdr.fi.dfDefaultChar = def_char - info->hdr.fi.dfFirstChar;
    info->hdr.fi.dfBreakChar = ' ' - info->hdr.fi.dfFirstChar;
    info->hdr.fi.dfWidthBytes = (width_bytes + 1) & ~1;
463

464 465 466 467
    info->hdr.fi.dfFace = start + info->hdr.fi.dfWidthBytes * ppem;
    info->hdr.fi.dfBitsOffset = start;
    info->hdr.fi.dfFlags = 0x10; /* DFF_1COLOR */
    info->hdr.fi.dfFlags |= FT_IS_FIXED_WIDTH(face) ? 1 : 2; /* DFF_FIXED : DFF_PROPORTIONAL */
468

469 470 471 472 473
    info->hdr.dfVersion = 0x300;
    info->hdr.dfSize = start + info->hdr.fi.dfWidthBytes * ppem + strlen(face->family_name) + 1;

    info->data = calloc( info->hdr.dfSize - start, 1 );
    data_pos = 0;
474 475

    for(i = first_char; i < 0x100; i++) {
476 477
        int c = get_char(cptable, enc, i);
        if(FT_Load_Char(face, c, FT_LOAD_DEFAULT)) {
478 479
            continue;
        }
480
        assert(info->dfCharTable[i].width == face->glyph->metrics.horiAdvance >> 6);
481

482
        for(x = 0; x < ((info->dfCharTable[i].width + 7) / 8); x++) {
483 484 485
            for(y = 0; y < ppem; y++) {
                if(y < ascent - face->glyph->bitmap_top ||
                   y >=  face->glyph->bitmap.rows + ascent - face->glyph->bitmap_top) {
486
                    info->data[data_pos++] = 0;
487 488 489 490 491
                    continue;
                }
                x_off = face->glyph->bitmap_left / 8;
                x_end = (face->glyph->bitmap_left + face->glyph->bitmap.width - 1) / 8;
                if(x < x_off || x > x_end) {
492
                    info->data[data_pos++] = 0;
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
                    continue;
                }
                if(x == x_off)
                    left_byte = 0;
                else
                    left_byte = face->glyph->bitmap.buffer[(y - (ascent - face->glyph->bitmap_top)) * face->glyph->bitmap.pitch + x - x_off - 1];

                /* On the last non-trival output byte (x == x_end) have we got one or two input bytes */
                if(x == x_end && (face->glyph->bitmap_left % 8 != 0) && ((face->glyph->bitmap.width % 8 == 0) || (x != (((face->glyph->bitmap.width) & ~0x7) + face->glyph->bitmap_left) / 8)))
                    right_byte = 0;
                else
                    right_byte = face->glyph->bitmap.buffer[(y - (ascent - face->glyph->bitmap_top)) * face->glyph->bitmap.pitch + x - x_off];

                byte = (left_byte << (8 - (face->glyph->bitmap_left & 7))) & 0xff;
                byte |= ((right_byte >> (face->glyph->bitmap_left & 7)) & 0xff);
508
                info->data[data_pos++] = byte;
509 510 511
            }
        }
    }
512 513
    data_pos += ((space_size + 7) / 8) * ppem;
    if (width_bytes & 1) data_pos += ppem;
514

515 516 517
    memcpy( info->data + data_pos, face->family_name, strlen( face->family_name ));
    data_pos += strlen( face->family_name ) + 1;
    assert( start + data_pos == info->hdr.dfSize );
518

519 520
    FT_Done_Face( face );
    return info;
521 522
}

523 524 525 526 527 528 529
static void write_fontinfo( const struct fontinfo *info, FILE *fp )
{
    fwrite( &info->hdr, sizeof(info->hdr), 1, fp );
    fwrite( info->dfCharTable + info->hdr.fi.dfFirstChar, sizeof(*info->dfCharTable),
            ((unsigned char)info->hdr.fi.dfLastChar - (unsigned char)info->hdr.fi.dfFirstChar) + 3, fp );
    fwrite( info->data, info->hdr.dfSize - info->hdr.fi.dfBitsOffset, 1, fp );
}
530

531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
/* parse options from the argv array and remove all the recognized ones */
static char **parse_options( int argc, char **argv )
{
    int optc;

    while ((optc = getopt( argc, argv, "d:ho:qr:s" )) != -1)
    {
        switch(optc)
        {
        case 'd':
            option_defchar = atoi( optarg );
            break;
        case 'o':
            option_output = strdup( optarg );
            break;
        case 'q':
            option_quiet = 1;
            break;
        case 'r':
            option_dpi = atoi( optarg );
            break;
        case 's':
            option_fnt_mode = 1;
            break;
        case 'h':
            usage(argv);
            exit(0);
        case '?':
            usage(argv);
            exit(1);
        }
    }
    return &argv[optind];
}

566 567
int main(int argc, char **argv)
{
568 569 570 571 572 573 574 575 576 577 578 579 580
    int i, j;
    FILE *ofp;
    short align, num_files;
    int resource_table_len, non_resident_name_len, resident_name_len;
    unsigned short resource_table_off, resident_name_off, module_ref_off, non_resident_name_off, fontdir_off, font_off;
    char resident_name[200];
    int fontdir_len = 2;
    char non_resident_name[200];
    unsigned short first_res = 0x0050, pad, res;
    IMAGE_OS2_HEADER NE_hdr;
    NE_TYPEINFO rc_type;
    NE_NAMEINFO rc_name;
    struct fontinfo **info;
581 582
    char *input_file;
    char **args;
583

584 585 586 587 588
    args = parse_options( argc, argv );

    input_file = *args++;
    if (!input_file || !*args)
    {
589
        usage(argv);
590
        exit(1);
591 592
    }

593
    if(FT_Init_FreeType(&ft_library))
594
        error("ft init failure\n");
595

596
    FT_Version.major=FT_Version.minor=FT_Version.patch=-1;
597
    FT_Library_Version(ft_library,&FT_Version.major,&FT_Version.minor,&FT_Version.patch);
598

599 600 601 602 603 604
    num_files = 0;
    while (args[num_files]) num_files++;

    if (option_fnt_mode && num_files > 1)
        error( "can only specify one font in .fnt mode\n" );

605 606
    info = malloc( num_files * sizeof(*info) );
    for (i = 0; i < num_files; i++)
607
    {
608
        int ppem, enc, avg_width;
609 610
        const char *name;

611
        if (sscanf( args[i], "%d,%d,%d", &ppem, &enc, &avg_width ) != 3)
612 613 614 615
        {
            usage(argv);
            exit(1);
        }
616 617
        if (!(info[i] = fill_fontinfo( input_file, ppem, enc, option_dpi, option_defchar, avg_width )))
            exit(1);
618 619 620 621 622 623 624 625 626 627 628

        name = get_face_name( info[i] );
        fontdir_len += 0x74 + strlen(name) + 1;
        if(i == 0) {
            sprintf(non_resident_name, "FONTRES 100,%d,%d : %s %d",
                    info[i]->hdr.fi.dfVertRes, info[i]->hdr.fi.dfHorizRes,
                    name, info[i]->hdr.fi.dfPoints );
            strcpy(resident_name, name);
        } else {
            sprintf(non_resident_name + strlen(non_resident_name), ",%d", info[i]->hdr.fi.dfPoints );
        }
629 630
    }

631
    if (option_dpi <= 108)
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
        strcat(non_resident_name, " (VGA res)");
    else
        strcat(non_resident_name, " (8514 res)");
    non_resident_name_len = strlen(non_resident_name) + 4;

    /* shift count + fontdir entry + num_files of font + nul type + \007FONTDIR */
    resource_table_len = sizeof(align) + sizeof("FONTDIR") +
                         sizeof(NE_TYPEINFO) + sizeof(NE_NAMEINFO) +
                         sizeof(NE_TYPEINFO) + sizeof(NE_NAMEINFO) * num_files +
                         sizeof(NE_TYPEINFO);
    resource_table_off = sizeof(NE_hdr);
    resident_name_off = resource_table_off + resource_table_len;
    resident_name_len = strlen(resident_name) + 4;
    module_ref_off = resident_name_off + resident_name_len;
    non_resident_name_off = sizeof(MZ_hdr) + module_ref_off + sizeof(align);

    memset(&NE_hdr, 0, sizeof(NE_hdr));
    NE_hdr.ne_magic = 0x454e;
    NE_hdr.ne_ver = 5;
    NE_hdr.ne_rev = 1;
    NE_hdr.ne_flags = NE_FFLAGS_LIBMODULE | NE_FFLAGS_GUI;
    NE_hdr.ne_cbnrestab = non_resident_name_len;
    NE_hdr.ne_segtab = sizeof(NE_hdr);
    NE_hdr.ne_rsrctab = sizeof(NE_hdr);
    NE_hdr.ne_restab = resident_name_off;
    NE_hdr.ne_modtab = module_ref_off;
    NE_hdr.ne_imptab = module_ref_off;
    NE_hdr.ne_enttab = NE_hdr.ne_modtab;
    NE_hdr.ne_nrestab = non_resident_name_off;
    NE_hdr.ne_align = 4;
    NE_hdr.ne_exetyp = NE_OSFLAGS_WINDOWS;
    NE_hdr.ne_expver = 0x400;

    fontdir_off = (non_resident_name_off + non_resident_name_len + 15) & ~0xf;
    font_off = (fontdir_off + fontdir_len + 15) & ~0x0f;
667

668
    atexit( cleanup );
669 670 671 672 673 674
    signal( SIGTERM, exit_on_signal );
    signal( SIGINT, exit_on_signal );
#ifdef SIGHUP
    signal( SIGHUP, exit_on_signal );
#endif

675
    if (!option_output)  /* build a default output name */
676
    {
677 678 679 680 681 682 683 684
        char *p = strrchr( input_file, '/' );
        if (p) p++;
        else p = input_file;
        option_output = malloc( strlen(p) + sizeof(".fon") );
        strcpy( option_output, p );
        p = strrchr( option_output, '.' );
        if (!p) p = option_output + strlen(option_output);
        strcpy( p, option_fnt_mode ? ".fnt" : ".fon" );
685 686
    }

687
    if (!(ofp = fopen(option_output, "wb")))
688
    {
689
        perror( option_output );
690 691
        exit(1);
    }
692 693 694 695 696 697
    output_name = option_output;
    if (option_fnt_mode)
    {
        write_fontinfo( info[0], ofp );
        goto done;
    }
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788

    fwrite(MZ_hdr, sizeof(MZ_hdr), 1, ofp);
    fwrite(&NE_hdr, sizeof(NE_hdr), 1, ofp);

    align = 4;
    fwrite(&align, sizeof(align), 1, ofp);

    rc_type.type_id = NE_RSCTYPE_FONTDIR;
    rc_type.count = 1;
    rc_type.resloader = 0;
    fwrite(&rc_type, sizeof(rc_type), 1, ofp);

    rc_name.offset = fontdir_off >> 4;
    rc_name.length = (fontdir_len + 15) >> 4;
    rc_name.flags = NE_SEGFLAGS_MOVEABLE | NE_SEGFLAGS_PRELOAD;
    rc_name.id = resident_name_off - sizeof("FONTDIR") - NE_hdr.ne_rsrctab;
    rc_name.handle = 0;
    rc_name.usage = 0;
    fwrite(&rc_name, sizeof(rc_name), 1, ofp);

    rc_type.type_id = NE_RSCTYPE_FONT;
    rc_type.count = num_files;
    rc_type.resloader = 0;
    fwrite(&rc_type, sizeof(rc_type), 1, ofp);

    for(res = first_res | 0x8000, i = 0; i < num_files; i++, res++) {
        int len = (info[i]->hdr.dfSize + 15) & ~0xf;

        rc_name.offset = font_off >> 4;
        rc_name.length = len >> 4;
        rc_name.flags = NE_SEGFLAGS_MOVEABLE | NE_SEGFLAGS_SHAREABLE | NE_SEGFLAGS_DISCARDABLE;
        rc_name.id = res;
        rc_name.handle = 0;
        rc_name.usage = 0;
        fwrite(&rc_name, sizeof(rc_name), 1, ofp);

        font_off += len;
    }

    /* empty type info */
    memset(&rc_type, 0, sizeof(rc_type));
    fwrite(&rc_type, sizeof(rc_type), 1, ofp);

    fputc(strlen("FONTDIR"), ofp);
    fwrite("FONTDIR", strlen("FONTDIR"), 1, ofp);
    fputc(strlen(resident_name), ofp);
    fwrite(resident_name, strlen(resident_name), 1, ofp);

    fputc(0x00, ofp);    fputc(0x00, ofp);
    fputc(0x00, ofp);
    fputc(0x00, ofp);    fputc(0x00, ofp);

    fputc(strlen(non_resident_name), ofp);
    fwrite(non_resident_name, strlen(non_resident_name), 1, ofp);
    fputc(0x00, ofp); /* terminator */

    /* empty ne_modtab and ne_imptab */
    fputc(0x00, ofp);
    fputc(0x00, ofp);

    pad = ftell(ofp) & 0xf;
    if(pad != 0)
        pad = 0x10 - pad;
    for(i = 0; i < pad; i++)
        fputc(0x00, ofp);

    /* FONTDIR resource */
    fwrite(&num_files, sizeof(num_files), 1, ofp);

    for(res = first_res, i = 0; i < num_files; i++, res++) {
        const char *name = get_face_name( info[i] );
        fwrite(&res, sizeof(res), 1, ofp);
        fwrite(&info[i]->hdr, FIELD_OFFSET(FNT_HEADER,fi.dfBitsOffset), 1, ofp);
        fputc(0x00, ofp);
        fwrite(name, strlen(name) + 1, 1, ofp);
    }

    pad = ftell(ofp) & 0xf;
    if(pad != 0)
        pad = 0x10 - pad;
    for(i = 0; i < pad; i++)
        fputc(0x00, ofp);

    for(res = first_res, i = 0; i < num_files; i++, res++) {
        write_fontinfo( info[i], ofp );
        pad = info[i]->hdr.dfSize & 0xf;
        if(pad != 0)
            pad = 0x10 - pad;
        for(j = 0; j < pad; j++)
            fputc(0x00, ofp);
    }
789
done:
790
    fclose(ofp);
791
    output_name = NULL;
792 793 794 795 796 797 798
    exit(0);
}

#else /* HAVE_FREETYPE */

int main(int argc, char **argv)
{
799
    fprintf( stderr, "%s needs to be built with FreeType support\n", argv[0] );
800 801 802 803
    exit(1);
}

#endif /* HAVE_FREETYPE */