Source

pygame / src / sdlttf / font.c

Full commit
  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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
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
566
567
568
569
/*
  pygame - Python Game Library
  Copyright (C) 2000-2001 Pete Shinners, 2008 Marcus von Appen

  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_SDLTTFFONT_INTERNAL

#include "ttfmod.h"
#include "pgsdl.h"
#include "pgttf.h"
#include "sdlttfbase_doc.h"

static PyObject *_font_new (PyTypeObject *type, PyObject *args, PyObject *kwds);
static int _font_init (PyObject *chunk, PyObject *args, PyObject *kwds);
static void _font_dealloc (PySDLFont_TTF *self);

static PyObject* _font_glyphmetrics (PyObject *self, PyObject* args);
static PyObject* _font_getsize (PyObject *self, PyObject* args);
static PyObject* _font_render (PyObject *self, PyObject* args, PyObject *kwds);

static PyObject* _font_getstyle (PyObject *self, void *closure);
static int _font_setstyle (PyObject *self, PyObject *value, void *closure);
static PyObject* _font_getheight (PyObject *self, void *closure);
static PyObject* _font_getascent (PyObject *self, void *closure);
static PyObject* _font_getdescent (PyObject *self, void *closure);
static PyObject* _font_getlineskip (PyObject *self, void *closure);
static PyObject* _font_getfaces (PyObject *self, void *closure);
static PyObject* _font_getisfixedwidth (PyObject *self, void *closure);
static PyObject* _font_getfamilyname (PyObject *self, void *closure);
static PyObject* _font_getstylename (PyObject *self, void *closure);

/**
 */
static PyMethodDef _font_methods[] = {
    { "get_glyph_metrics", _font_glyphmetrics, METH_VARARGS,
      DOC_BASE_FONT_GET_GLYPH_METRICS },
    { "get_size", _font_getsize, METH_VARARGS, DOC_BASE_FONT_GET_SIZE },
    { "render", (PyCFunction)_font_render, METH_VARARGS | METH_KEYWORDS,
      DOC_BASE_FONT_RENDER },
    { NULL, NULL, 0, NULL }
};

/**
 */
static PyGetSetDef _font_getsets[] = {
    { "style", _font_getstyle, _font_setstyle, DOC_BASE_FONT_STYLE, NULL },
    { "height", _font_getheight, NULL, DOC_BASE_FONT_HEIGHT, NULL },
    { "ascent", _font_getascent, NULL, DOC_BASE_FONT_ASCENT, NULL },
    { "descent", _font_getdescent, NULL, DOC_BASE_FONT_DESCENT, NULL },
    { "line_skip", _font_getlineskip, NULL, DOC_BASE_FONT_LINE_SKIP, NULL },
    { "faces", _font_getfaces, NULL, DOC_BASE_FONT_FACES, NULL },
    { "is_fixed_width", _font_getisfixedwidth, NULL,
      DOC_BASE_FONT_IS_FIXED_WIDTH, NULL },
    { "family_name", _font_getfamilyname, NULL, DOC_BASE_FONT_FAMILY_NAME,
      NULL },
    { "style_name", _font_getstylename, NULL, DOC_BASE_FONT_STYLE_NAME, NULL },
    { NULL, NULL, NULL, NULL, NULL }
};

/**
 */
PyTypeObject PySDLFont_TTF_Type =
{
    TYPE_HEAD(NULL,0)
    "sdlttf.Font",              /* tp_name */
    sizeof (PySDLFont_TTF),     /* tp_basicsize */
    0,                          /* tp_itemsize */
    (destructor) _font_dealloc, /* tp_dealloc */
    0,                          /* tp_print */
    0,                          /* tp_getattr */
    0,                          /* tp_setattr */
    0,                          /* tp_compare */
    0,                          /* tp_repr */
    0,                          /* tp_as_number */
    0,                          /* tp_as_sequence */
    0,                          /* tp_as_mapping */
    0,                          /* tp_hash */
    0,                          /* tp_call */
    0,                          /* tp_str */
    0,                          /* tp_getattro */
    0,                          /* tp_setattro */
    0,                          /* tp_as_buffer */
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
    DOC_BASE_FONT,
    0,                          /* tp_traverse */
    0,                          /* tp_clear */
    0,                          /* tp_richcompare */

    /* 
     * tp_weaklistoffset
     * FIXME: Weakrefs? Do we need those? 
     */
/*    offsetof(PySDLFont_TTF, weakrefs) */
    0, 

    0,                          /* tp_iter */
    0,                          /* tp_iternext */
    _font_methods,              /* tp_methods */
    0,                          /* tp_members */
    _font_getsets,              /* tp_getset */
    0,                          /* tp_base */
    0,                          /* tp_dict */
    0,                          /* tp_descr_get */
    0,                          /* tp_descr_set */

    /* 
     * tp_dictoffset
     * FIXME: What about the dictionary? Hueuh...
     */
/*    offsetof(PySDLFont_TTF, dict) */
    0, 

    (initproc) _font_init,      /* tp_init */
    0,                          /* tp_alloc */
    _font_new,                  /* tp_new */
    0,                          /* tp_free */
    0,                          /* tp_is_gc */
    0,                          /* tp_bases */
    0,                          /* tp_mro */
    0,                          /* tp_cache */
    0,                          /* tp_subclasses */
    0,                          /* tp_weaklist */
    0,                          /* tp_del */
#if PY_VERSION_HEX >= 0x02060000
    0                           /* tp_version_tag */
#endif
};

static void
_font_dealloc (PySDLFont_TTF *self)
{
    TTF_CloseFont (self->font);
    ((PyObject*)self)->ob_type->tp_free ((PyObject *) self);
}

static PyObject*
_font_new (PyTypeObject *type, PyObject *args, PyObject *kwds)
{
    PySDLFont_TTF *font = (PySDLFont_TTF*) type->tp_alloc (type, 0);
    if (!font)
        return NULL;

    font->font = NULL;

    font->pyfont.get_height = _font_getheight;

    // TODO: Which get name? We've got family name and style name.
    font->pyfont.get_name = NULL;
    font->pyfont.get_style = _font_getstyle;
    font->pyfont.set_style = _font_setstyle;
    font->pyfont.get_size = _font_getsize;
    font->pyfont.render = _font_render;
    font->pyfont.copy = NULL; // TODO

    return (PyObject*) font;
}

static int
_font_init (PyObject *self, PyObject *args, PyObject *kwds)
{
    PyObject *file;
    int ptsize, _index = 0;
    TTF_Font *font;
    SDL_RWops *rw;
    int autoclose;

    ASSERT_TTF_INIT (-1);
    if (!PyArg_ParseTuple (args, "Oi|i", &file, &ptsize, &_index))
        return -1;

    if (_index < 0)
    {
        PyErr_SetString (PyExc_ValueError, "index must not be negative");
        return -1;
    }

    rw = PyRWops_NewRO_Threaded (file, &autoclose);
    if (!rw)
        return -1;

    Py_BEGIN_ALLOW_THREADS;
    if (_index == 0)
        font = TTF_OpenFontRW (rw, autoclose, ptsize);
    else
        font = TTF_OpenFontIndexRW (rw, autoclose, ptsize, _index);
    Py_END_ALLOW_THREADS;
    
    if (!autoclose)
        PyRWops_Close (rw, autoclose);
    
    if (!font)
    {
        PyErr_SetString (PyExc_PyGameError, TTF_GetError ());
        return -1;
    }
    ((PySDLFont_TTF*)self)->font = font;
    return 0;
}

/* Getters/Setters */
static PyObject*
_font_getstyle (PyObject *self, void *closure)
{
    ASSERT_TTF_INIT (NULL);
    return PyInt_FromLong (TTF_GetFontStyle (((PySDLFont_TTF*)self)->font));
}

static int
_font_setstyle (PyObject *self, PyObject *value, void *closure)
{
    int style;
    ASSERT_TTF_INIT (-1);

    if (!IntFromObj (value, &style))
        return -1;
    
    TTF_SetFontStyle (((PySDLFont_TTF*)self)->font, style);
    return 0;
}

static PyObject*
_font_getheight (PyObject *self, void *closure)
{
    ASSERT_TTF_INIT (NULL);
    return PyInt_FromLong (TTF_FontHeight (((PySDLFont_TTF*)self)->font));
}

static PyObject*
_font_getascent (PyObject *self, void *closure)
{
    ASSERT_TTF_INIT (NULL);
    return PyInt_FromLong (TTF_FontAscent (((PySDLFont_TTF*)self)->font));
}

static PyObject*
_font_getdescent (PyObject *self, void *closure)
{
    ASSERT_TTF_INIT (NULL);
    return PyInt_FromLong (TTF_FontDescent (((PySDLFont_TTF*)self)->font));
}

static PyObject*
_font_getlineskip (PyObject *self, void *closure)
{
    ASSERT_TTF_INIT (NULL);
    return PyInt_FromLong (TTF_FontLineSkip (((PySDLFont_TTF*)self)->font));
}

static PyObject*
_font_getfaces (PyObject *self, void *closure)
{
    ASSERT_TTF_INIT (NULL);
    return PyLong_FromLong (TTF_FontFaces (((PySDLFont_TTF*)self)->font));
}

static PyObject*
_font_getisfixedwidth (PyObject *self, void *closure)
{
    ASSERT_TTF_INIT (NULL);
    return PyBool_FromLong (TTF_FontFaceIsFixedWidth (((PySDLFont_TTF*)self)->font));
}

static PyObject*
_font_getfamilyname (PyObject *self, void *closure)
{
    ASSERT_TTF_INIT (NULL);
    return Text_FromUTF8 (TTF_FontFaceFamilyName (((PySDLFont_TTF*)self)->font));
}

static PyObject*
_font_getstylename (PyObject *self, void *closure)
{
    ASSERT_TTF_INIT (NULL);
    return Text_FromUTF8 (TTF_FontFaceStyleName (((PySDLFont_TTF*)self)->font));
}

/* Methods */
static PyObject*
_font_glyphmetrics (PyObject *self, PyObject* args)
{
    PySDLFont_TTF *font = (PySDLFont_TTF*) self;
    int minx, miny, maxx, maxy, advance, isunicode = 0, i;
    PyObject *textobj, *list;
    Py_ssize_t length;
    void *buf = NULL;

    ASSERT_TTF_INIT (NULL);
    
    if (!PyArg_ParseTuple (args, "O:glyph_metrics", &textobj))
        return NULL;

    if (PyUnicode_Check (textobj))
    {
        buf = PyUnicode_AsUnicode (textobj);
        isunicode = 1;
    }
    else if (Bytes_Check (textobj))
        buf = Bytes_AS_STRING (textobj);
    else
    {
        PyErr_SetString (PyExc_TypeError,
            "argument must be a string or unicode");
    }

    if (!buf)
        return NULL;

    if (isunicode)
        length = PyUnicode_GetSize (textobj);
    else
        length = Bytes_Size (textobj);
    if (length == 0)
        Py_RETURN_NONE;

    list = PyList_New (length);
    if (!list)
        return NULL;

    if (isunicode)
    {
        for (i = 0; i < length; i++)
        {
            /* 
             * TTF_GlyphMetrics() seems to return a value for any character,
             * using the default invalid character, if the char is not found.
             */
            if (TTF_GlyphMetrics (font->font, (Uint16) ((Py_UNICODE*) buf)[i],
                    &minx, &maxx, &miny, &maxy, &advance) == -1)
            {
                Py_INCREF (Py_None);
                PyList_SetItem (list, i, Py_None); /* No matching metrics. */
            }
            else
            {
                PyList_SetItem (list, i, Py_BuildValue
                    ("(iiiii)", minx, maxx, miny, maxy, advance));
            }
        }
    }
    else
    {
        for (i = 0; i < length; i++)
        {
            /* 
             * TTF_GlyphMetrics() seems to return a value for any character,
             * using the default invalid character, if the char is not found.
             */
            if (TTF_GlyphMetrics (font->font, (Uint16) ((char*) buf)[i], &minx,
                    &maxx, &miny, &maxy, &advance) == -1)
            {
                Py_INCREF (Py_None);
                PyList_SetItem (list, i, Py_None); /* No matching metrics. */
            }
            else
            {
                PyList_SetItem (list, i, Py_BuildValue
                    ("(iiiii)", minx, maxx, miny, maxy, advance));
            }
        }
    }
    return list;
}

static PyObject*
_font_getsize (PyObject *self, PyObject* args)
{
    PySDLFont_TTF *font = (PySDLFont_TTF*) self;
    PyObject *text;
    int w, h;
    
    ASSERT_TTF_INIT (NULL);

    if (!PyArg_ParseTuple (args, "O:size", &text))
        return NULL;

    if (PyUnicode_Check (text))
    {
        PyObject* strob = PyUnicode_AsEncodedString (text, "utf-8", "replace");
        char *string = Bytes_AS_STRING (strob);
        if (TTF_SizeUTF8 (font->font, string, &w, &h) == -1)
        {
            PyErr_SetString (PyExc_PyGameError, TTF_GetError ());
            Py_DECREF (strob);
            return NULL;
        }
        Py_DECREF (strob);
        return Py_BuildValue ("(ii)", w, h);
    }
    
    if (Bytes_Check (text))
    {
        char* string = Bytes_AS_STRING (text);
        if (TTF_SizeText (font->font, string, &w, &h) == -1)
        {
            PyErr_SetString (PyExc_PyGameError, TTF_GetError ());
            return NULL;
        }
        return Py_BuildValue ("(ii)", w, h);
    }

    PyErr_SetString (PyExc_TypeError, "text must be a string");
    return NULL;
}

static PyObject*
_font_render (PyObject *self, PyObject* args, PyObject *kwds)
{
    PySDLFont_TTF *font = (PySDLFont_TTF*) self;
    PyObject *text, *colorfg, *pysurf, *colorbg = NULL;
    SDL_Surface *surface = NULL;
    SDL_Color fgcolor, bgcolor;
    int render = -1;

    static char *kwlist[] = { "text", "fgcolor", "bgcolor", "blendargs", NULL };

    ASSERT_TTF_INIT (NULL);

    if (!PyArg_ParseTupleAndKeywords (args, kwds, "OO|Oi:render", kwlist,
            &text, &colorfg, &colorbg, &render))
        return NULL;

    if (!PyColor_Check (colorfg))
    {
        PyErr_SetString (PyExc_TypeError, "fgcolor must be a Color");
        return NULL;
    }
    if (colorbg && !PyColor_Check (colorbg))
    {
        PyErr_SetString (PyExc_TypeError, "bgcolor must be a Color");
        return NULL;
    }

    fgcolor.r = ((PyColor*)colorfg)->r;
    fgcolor.g = ((PyColor*)colorfg)->g;
    fgcolor.b = ((PyColor*)colorfg)->b;

    if (colorbg)
    {
        bgcolor.r = ((PyColor*)colorbg)->r;
        bgcolor.g = ((PyColor*)colorbg)->g;
        bgcolor.b = ((PyColor*)colorbg)->b;
        /* If the user set a bgcolor and left the render type aside, use
         * a shaded mode to activate the bgcolor. Otherwise ignore it.
         */
        if (render == -1)
            render = RENDER_SHADED;
    }

    if (render < RENDER_SOLID || render > RENDER_BLENDED)
        render = RENDER_SOLID;

    if (PyUnicode_Check (text))
    {
        PyObject* strob = PyUnicode_AsEncodedString (text, "utf-8", "replace");
        char *string = Bytes_AS_STRING (strob);

        switch (render)
        {
        case RENDER_SOLID:
            surface = TTF_RenderUTF8_Solid (font->font, string, fgcolor);
            break;
        case RENDER_SHADED:
            surface = TTF_RenderUTF8_Shaded (font->font, string, fgcolor,
                bgcolor);
            break;
        case RENDER_BLENDED:
            surface = TTF_RenderUTF8_Blended (font->font, string, fgcolor);
            break;
        }
        Py_DECREF (strob);
    }
    else if (Bytes_Check (text))
    {
        char* string = Bytes_AS_STRING (text);

        switch (render)
        {
        case RENDER_SOLID:
            surface = TTF_RenderText_Solid (font->font, string, fgcolor);
            break;
        case RENDER_SHADED:
            surface = TTF_RenderText_Shaded (font->font, string, fgcolor,
                bgcolor);
            break;
        case RENDER_BLENDED:
            surface = TTF_RenderText_Blended (font->font, string, fgcolor);
            break;
        }
        if (!surface)
        {
            PyErr_SetString (PyExc_PyGameError, TTF_GetError ());
            return NULL;
        }
        pysurf = PySDLSurface_NewFromSDLSurface (surface);
        if (!pysurf)
        {
            PyErr_SetString (PyExc_PyGameError, SDL_GetError ());
            return NULL;
        }
    }
    else
    {
        PyErr_SetString (PyExc_TypeError, "text must be a string");
        return NULL;
    }

    if (!surface)
    {
        PyErr_SetString (PyExc_PyGameError, TTF_GetError ());
        return NULL;
    }
    pysurf = PySDLSurface_NewFromSDLSurface (surface);
    if (!pysurf)
    {
        SDL_FreeSurface (surface);
        PyErr_SetString (PyExc_PyGameError, SDL_GetError ());
        return NULL;
    }
    return pysurf;
}

/* C API */
PyObject*
PySDLFont_TTF_New (char *file, int ptsize)
{
    PySDLFont_TTF *font;
    TTF_Font *ttf;

    ASSERT_TTF_INIT (NULL);

    if (!file)
        return NULL;

    font = (PySDLFont_TTF*) PySDLFont_TTF_Type.tp_new (&PySDLFont_TTF_Type, NULL, NULL);
    if (!font)
        return NULL;

    ttf = TTF_OpenFont (file, ptsize);
    if (!ttf)
    {
        PyErr_SetString (PyExc_PyGameError, TTF_GetError ());
        return NULL;
    }

    font->font = ttf;
    return (PyObject*) font;
}

void
font_export_capi (void **capi)
{
    capi[PYGAME_SDLTTFFONT_FIRSTSLOT] = &PySDLFont_TTF_Type;
    capi[PYGAME_SDLTTFFONT_FIRSTSLOT+1] = &PySDLFont_TTF_New;
}