pygame / src / freetype / ft_wrap.c

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
/*
  pygame - Python Game Library
  Copyright (C) 2009 Vicent Marti

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Library General Public
  License as published by the Free Software Foundation; either
  version 2 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
  Library General Public License for more details.

  You should have received a copy of the GNU Library General Public
  License along with this library; if not, write to the Free
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

*/

#define PYGAME_FREETYPE_INTERNAL

#include "ft_mod.h"
#include "ft_wrap.h"
#include "pgfreetype.h"
#include "pgtypes.h"
#include "freetypebase_doc.h"

#include FT_MODULE_H

void    _PGFT_SetError(FreeTypeInstance *, const char *, FT_Error);
FT_Face _PGFT_GetFace(FreeTypeInstance *, PyFreeTypeFont *);
FT_Face _PGFT_GetFaceSized(FreeTypeInstance *, PyFreeTypeFont *, int);
void    _PGFT_BuildScaler(PyFreeTypeFont *, FTC_Scaler, int);
int     _PGFT_LoadGlyph(FreeTypeInstance *, PyFreeTypeFont *, 
                        FTC_Scaler, int, FT_Glyph *, FT_UInt32 *);
void    _PGFT_GetMetrics_INTERNAL(FT_Glyph, int *, int *, int *, int *, int *);


static FT_Error
_PGFT_face_request(FTC_FaceID face_id, 
    FT_Library library, 
    FT_Pointer request_data, 
    FT_Face *aface)
{
    FontId *id = (FontId *)face_id; 
    FT_Error error;
    
    Py_BEGIN_ALLOW_THREADS;
        error = FT_Open_Face(library, &id->open_args, id->face_index, aface);
    Py_END_ALLOW_THREADS;

    return error;
}

void
_PGFT_SetError(FreeTypeInstance *ft, const char *error_msg, FT_Error error_id)
{
#undef __FTERRORS_H__
#define FT_ERRORDEF( e, v, s )  { e, s },
#define FT_ERROR_START_LIST     {
#define FT_ERROR_END_LIST       {0, 0}};
    static const struct
    {
        int          err_code;
        const char*  err_msg;
    } ft_errors[] = 
#include FT_ERRORS_H

          int i;
    const char *ft_msg;

    ft_msg = NULL;
    for (i = 0; ft_errors[i].err_msg != NULL; ++i)
    {
        if (error_id == ft_errors[i].err_code)
        {
            ft_msg = ft_errors[i].err_msg;
            break;
        }
    }

    if (ft_msg)
        sprintf(ft->_error_msg, "%s: %s", error_msg, ft_msg);
    else
        strcpy(ft->_error_msg, error_msg);
}


FT_UInt16 *
PGFT_BuildUnicodeString(PyObject *obj, int *must_free)
{
    FT_UInt16 *utf16_buffer = NULL;
    *must_free = 0;

#ifdef IS_PYTHON_3
    /* 
     * If this is Python 3 and we pass an unicode string,
     * we can access directly its internal contents, as
     * they are in UCS-2
     */
    if (PyUnicode_Check(obj))
    {
        utf16_buffer = (FT_UInt16 *)PyUnicode_AS_UNICODE(obj);
    } else
#endif

    /*
     * If we pass a Bytes array, we assume it's standard
     * text encoded in Latin1 (SDL_TTF does the same).
     * We need to expand each character into 2 bytes because
     * FreeType expects UTF16 encodings.
     *
     * TODO: What happens if the user passes a byte array
     * representing e.g. a UTF8 string? He would be mostly
     * stupid, yes, but we should probably handle it.
     */
    if (Bytes_Check(obj))
    {
        const char *latin1_buffer;
        size_t i, len;

        latin1_buffer = (const char *)Bytes_AsString(obj);
        len = strlen(latin1_buffer);

        utf16_buffer = malloc((len + 1) * sizeof(FT_UInt16));

        for (i = 0; i < len; ++i)
            utf16_buffer[i] = (FT_UInt16)latin1_buffer[i];

        utf16_buffer[i] = 0;
        *must_free = 1;
    }

    return utf16_buffer;
}

const char *
PGFT_GetError(FreeTypeInstance *ft)
{
    return ft->_error_msg;
}

int
PGFT_Face_IsFixedWidth(FreeTypeInstance *ft, PyFreeTypeFont *font)
{
    FT_Face face;
    face = _PGFT_GetFace(ft, font);

    return face ? FT_IS_FIXED_WIDTH(face) : 0;
}

const char *
PGFT_Face_GetName(FreeTypeInstance *ft, PyFreeTypeFont *font)
{
    FT_Face face;
    face = _PGFT_GetFace(ft, font);

    return face ? face->family_name : ""; 
}

int
PGFT_Face_GetHeight(FreeTypeInstance *ft, PyFreeTypeFont *font)
{
    FT_Face face;
    face = _PGFT_GetFace(ft, font);

    return face ? face->height : 0;
}

FT_Face
_PGFT_GetFace(FreeTypeInstance *ft,
        PyFreeTypeFont *font)
{
    FT_Error error;
    FT_Face face;

    error = FTC_Manager_LookupFace(ft->cache_manager,
            (FTC_FaceID)(&font->id),
            &face);

    if (error)
    {
        _PGFT_SetError(ft, "Failed to load face", error);
        return NULL;
    }

    return face;
}

void
_PGFT_BuildScaler(PyFreeTypeFont *font, FTC_Scaler scale, int size)
{
    scale->face_id = (FTC_FaceID)(&font->id);
    scale->width = scale->height = (pguint32)(size * 64);
    scale->pixel = 0;
    scale->x_res = scale->y_res = 0;
}

FT_Face
_PGFT_GetFaceSized(FreeTypeInstance *ft,
        PyFreeTypeFont *font,
        int face_size)
{
    FT_Error error;
    FTC_ScalerRec scale;
    FT_Size _fts;

    _PGFT_BuildScaler(font, &scale, face_size);

    /*
     * TODO: Check if face has already been sized?
     */

    error = FTC_Manager_LookupSize(ft->cache_manager, 
            &scale, &_fts);

    if (error)
    {
        _PGFT_SetError(ft, "Failed to resize face", error);
        return NULL;
    }

    return _fts->face;
}

int
_PGFT_LoadGlyph(FreeTypeInstance *ft, 
        PyFreeTypeFont *font,
        FTC_Scaler scale, 
        int character, 
        FT_Glyph *glyph, 
        FT_UInt32 *_index)
{
    FT_Error error = 0;
    FT_UInt32 char_index;

    char_index = FTC_CMapCache_Lookup(
            ft->cache_charmap, 
            (FTC_FaceID)(&font->id),
            -1, (FT_UInt32)character);

    if (_index)
        *_index = char_index;

    if (char_index == 0)
        return -1;

    if (glyph)
    {
        error = FTC_ImageCache_LookupScaler(
                ft->cache_img,
                scale,
                FT_LOAD_DEFAULT, /* TODO: proper load flags */
                char_index,
                glyph, NULL);
    }

    return error;
}

void _PGFT_GetMetrics_INTERNAL(FT_Glyph glyph, 
        int *minx, int *maxx, int *miny, int *maxy, int *advance)
{
    FT_BBox box;

    /*
     * FIXME: We need to return pixel-based coordinates...
     * It would make sense to use FT_GLYPH_BBOX_TRUNCATE
     * to get the fixed point coordinates truncated, but
     * the results are usually off by 1 pixel from what we
     * get from SDL_TTF.
     *
     * Using FT_GLYPH_BBOX_PIXELS (truncated + grid fitted
     * coordinates) we get exactly the same results as
     * SDL_TTF, but does SDL actually do this properly?
     * 
     * Which are the *right* results? 
     */
    FT_Glyph_Get_CBox(glyph, FT_GLYPH_BBOX_PIXELS, &box);

    *minx = box.xMin;
    *maxx = box.xMax;
    *miny = box.yMin;
    *maxy = box.yMax;
    *advance = (glyph->advance.x >> 16);
}


int PGFT_GetMetrics(FreeTypeInstance *ft, PyFreeTypeFont *font,
        int character, int font_size, 
        int *minx, int *maxx, int *miny, int *maxy, int *advance)
{
    FT_Error error;
    FTC_ScalerRec scale;
    FT_Glyph glyph;

    _PGFT_BuildScaler(font, &scale, font_size);

    error = _PGFT_LoadGlyph(ft, font, &scale, character, &glyph, NULL);

    if (error)
    {
        _PGFT_SetError(ft, "Failed to load glyph metrics", error);
        return error;
    }

    _PGFT_GetMetrics_INTERNAL(glyph, minx, maxx, miny, maxy, advance);
    return 0;
}

int
PGFT_GetTextSize(FreeTypeInstance *ft, PyFreeTypeFont *font,
        const FT_UInt16 *text, int font_size, int *w, int *h)
{
#define UNICODE_BOM_NATIVE	0xFEFF
#define UNICODE_BOM_SWAPPED	0xFFFE

    const FT_UInt16 *ch;
    int swapped, use_kerning;
    FTC_ScalerRec scale;
    FT_Face face;
    FT_Glyph glyph;
    FT_UInt32 prev_index, cur_index;

    int minx, maxx, miny, maxy, x, z;
    int gl_maxx, gl_maxy, gl_minx, gl_miny, gl_advance;

    _PGFT_BuildScaler(font, &scale, font_size);

    /* FIXME: Some way to set the system's default ? */
    swapped = 0;
    x = 0;
    face = _PGFT_GetFace(ft, font);

    if (!face)
        return -1;

    minx = maxx = 0;
    miny = maxy = 0;
    prev_index = 0;

    use_kerning = FT_HAS_KERNING(face);

    for (ch = text; *ch; ++ch)
    {
        FT_UInt16 c = *ch;

        if (c == UNICODE_BOM_NATIVE || c == UNICODE_BOM_SWAPPED)
        {
            swapped = (c == UNICODE_BOM_SWAPPED);
            if (text == ch)
                ++text;

            continue;
        }

        if (swapped)
            c = (FT_UInt16)((c << 8) | (c >> 8));

        if (_PGFT_LoadGlyph(ft, font, &scale, c, &glyph, &cur_index) != 0)
            continue;

        _PGFT_GetMetrics_INTERNAL(glyph, 
                &gl_minx, &gl_maxx, &gl_miny, &gl_maxy, &gl_advance);

        if (use_kerning && prev_index)
        {
			FT_Vector delta;
			FT_Get_Kerning(face, prev_index, cur_index, ft_kerning_default, &delta); 
			x += delta.x >> 6;
		}

        z = x + gl_minx;
		if (minx > z)
			minx = z;
		
        /* TODO: Handle bold fonts */

        z = x + MAX(gl_maxx, gl_advance);
		if (maxx < z)
			maxx = z;

        miny = MIN(gl_miny, miny);
        maxy = MAX(gl_maxy, maxy);

		x += gl_advance;
        prev_index = cur_index;
    }

    *w = (maxx - minx);

    /* 
     * FIXME: According to SDL_TTF, the *real* height for the 
     * text seems to break some applications (?) but it seems
     * more sane to me having the real height than the max
     * height based on ascent/descent of all glyphs.
     */
    *h = (maxy - miny);
    return 0;
}


int
PGFT_TryLoadFont_Filename(FreeTypeInstance *ft, 
        PyFreeTypeFont *font, 
        const char *filename, 
        int face_index)
{
    char *filename_alloc;
    size_t file_len;

    file_len = strlen(filename);
    filename_alloc = malloc(file_len + 1);

    strcpy(filename_alloc, filename);
    filename_alloc[file_len] = 0;

    font->id.face_index = face_index;
    font->id.open_args.flags = FT_OPEN_PATHNAME;
    font->id.open_args.pathname = filename_alloc;

    return _PGFT_GetFace(ft, font) ? 0 : -1;
}

void
PGFT_UnloadFont(FreeTypeInstance *ft, PyFreeTypeFont *font)
{
    if (ft != NULL)
        FTC_Manager_RemoveFaceID(ft->cache_manager, (FTC_FaceID)(&font->id));

    free(font->id.open_args.pathname);
}

void
PGFT_Quit(FreeTypeInstance *ft)
{
    if (ft == NULL)
        return;

    /* TODO: Free caches */

    if (ft->cache_manager)
        FTC_Manager_Done(ft->cache_manager);

    if (ft->library)
        FT_Done_FreeType(ft->library);

    free(ft->_error_msg);
    free(ft);
}

int
PGFT_Init(FreeTypeInstance **_instance)
{
    FreeTypeInstance *inst = NULL;

    inst = malloc(sizeof(FreeTypeInstance));

    if (!inst)
        goto error_cleanup;

    memset(inst, 0, sizeof(FreeTypeInstance));
    inst->_error_msg = malloc(1024);
    
    if (FT_Init_FreeType(&inst->library) != 0)
        goto error_cleanup;

    if (FTC_Manager_New(inst->library, 0, 0, 0,
            &_PGFT_face_request, NULL,
            &inst->cache_manager) != 0)
        goto error_cleanup;

    if (FTC_CMapCache_New(inst->cache_manager, 
            &inst->cache_charmap) != 0)
        goto error_cleanup;

    if (FTC_SBitCache_New(inst->cache_manager,
            &inst->cache_sbit) != 0)
        goto error_cleanup;

    if (FTC_ImageCache_New(inst->cache_manager,
            &inst->cache_img) != 0)
        goto error_cleanup;

    *_instance = inst;
    return 0;

error_cleanup:
    PGFT_Quit(inst);
    *_instance = NULL;

    return -1;
}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.