-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
_imagingft.c
1651 lines (1474 loc) · 48.8 KB
/
_imagingft.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
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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
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
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* PIL FreeType Driver
*
* a FreeType 2.X driver for PIL
*
* history:
* 2001-02-17 fl Created (based on old experimental freetype 1.0 code)
* 2001-04-18 fl Fixed some egcs compiler nits
* 2002-11-08 fl Added unicode support; more font metrics, etc
* 2003-05-20 fl Fixed compilation under 1.5.2 and newer non-unicode builds
* 2003-09-27 fl Added charmap encoding support
* 2004-05-15 fl Fixed compilation for FreeType 2.1.8
* 2004-09-10 fl Added support for monochrome bitmaps
* 2006-06-18 fl Fixed glyph bearing calculation
* 2007-12-23 fl Fixed crash in family/style attribute fetch
* 2008-01-02 fl Handle Unicode filenames properly
*
* Copyright (c) 1998-2007 by Secret Labs AB
*/
#define PY_SSIZE_T_CLEAN
#include "Python.h"
#include "thirdparty/pythoncapi_compat.h"
#include "libImaging/Imaging.h"
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_GLYPH_H
#include FT_BITMAP_H
#include FT_STROKER_H
#include FT_MULTIPLE_MASTERS_H
#include FT_SFNT_NAMES_H
#ifdef FT_COLOR_H
#include FT_COLOR_H
#endif
/* -------------------------------------------------------------------- */
/* error table */
#undef FTERRORS_H
#undef __FTERRORS_H__
#define FT_ERRORDEF(e, v, s) {e, s},
#define FT_ERROR_START_LIST {
#define FT_ERROR_END_LIST \
{ 0, 0 } \
} \
;
#ifdef HAVE_RAQM
#ifdef HAVE_RAQM_SYSTEM
#include <raqm.h>
#else
#include "thirdparty/raqm/raqm.h"
#ifdef HAVE_FRIBIDI_SYSTEM
#include <fribidi.h>
#else
#include "thirdparty/fribidi-shim/fribidi.h"
#include <hb.h>
#endif
#endif
#endif
static int have_raqm = 0;
#define LAYOUT_FALLBACK 0
#define LAYOUT_RAQM 1
typedef struct {
int index, x_offset, x_advance, y_offset, y_advance;
unsigned int cluster;
} GlyphInfo;
struct {
int code;
const char *message;
} ft_errors[] =
#include FT_ERRORS_H
/* -------------------------------------------------------------------- */
/* font objects */
static FT_Library library;
typedef struct {
PyObject_HEAD FT_Face face;
unsigned char *font_bytes;
int layout_engine;
} FontObject;
static PyTypeObject Font_Type;
/* round a 26.6 pixel coordinate to the nearest integer */
#define PIXEL(x) ((((x) + 32) & -64) >> 6)
static PyObject *
geterror(int code) {
int i;
for (i = 0; ft_errors[i].message; i++) {
if (ft_errors[i].code == code) {
PyErr_SetString(PyExc_OSError, ft_errors[i].message);
return NULL;
}
}
PyErr_SetString(PyExc_OSError, "unknown freetype error");
return NULL;
}
static PyObject *
getfont(PyObject *self_, PyObject *args, PyObject *kw) {
/* create a font object from a file name and a size (in pixels) */
FontObject *self;
int error = 0;
char *filename = NULL;
float size;
FT_Size_RequestRec req;
FT_Long width;
Py_ssize_t index = 0;
Py_ssize_t layout_engine = 0;
unsigned char *encoding;
unsigned char *font_bytes;
Py_ssize_t font_bytes_size = 0;
static char *kwlist[] = {
"filename", "size", "index", "encoding", "font_bytes", "layout_engine", NULL
};
if (!library) {
PyErr_SetString(PyExc_OSError, "failed to initialize FreeType library");
return NULL;
}
#if PY_MAJOR_VERSION > 3 || PY_MINOR_VERSION > 11
PyConfig config;
PyConfig_InitPythonConfig(&config);
if (!PyArg_ParseTupleAndKeywords(
args,
kw,
"etf|nsy#n",
kwlist,
config.filesystem_encoding,
&filename,
&size,
&index,
&encoding,
&font_bytes,
&font_bytes_size,
&layout_engine
)) {
PyConfig_Clear(&config);
return NULL;
}
PyConfig_Clear(&config);
#else
if (!PyArg_ParseTupleAndKeywords(
args,
kw,
"etf|nsy#n",
kwlist,
Py_FileSystemDefaultEncoding,
&filename,
&size,
&index,
&encoding,
&font_bytes,
&font_bytes_size,
&layout_engine
)) {
return NULL;
}
#endif
self = PyObject_New(FontObject, &Font_Type);
if (!self) {
if (filename) {
PyMem_Free(filename);
}
return NULL;
}
self->face = NULL;
self->layout_engine = layout_engine;
if (filename && font_bytes_size <= 0) {
self->font_bytes = NULL;
error = FT_New_Face(library, filename, index, &self->face);
} else {
/* need to have allocated storage for font_bytes for the life of the object.*/
/* Don't free this before FT_Done_Face */
self->font_bytes = PyMem_Malloc(font_bytes_size);
if (!self->font_bytes) {
error = FT_Err_Out_Of_Memory;
}
if (!error) {
memcpy(self->font_bytes, font_bytes, (size_t)font_bytes_size);
error = FT_New_Memory_Face(
library,
(FT_Byte *)self->font_bytes,
font_bytes_size,
index,
&self->face
);
}
}
if (!error) {
width = size * 64;
req.type = FT_SIZE_REQUEST_TYPE_NOMINAL;
req.width = width;
req.height = width;
req.horiResolution = 0;
req.vertResolution = 0;
error = FT_Request_Size(self->face, &req);
}
if (!error && encoding && strlen((char *)encoding) == 4) {
FT_Encoding encoding_tag =
FT_MAKE_TAG(encoding[0], encoding[1], encoding[2], encoding[3]);
error = FT_Select_Charmap(self->face, encoding_tag);
}
if (filename) {
PyMem_Free(filename);
}
if (error) {
if (self->font_bytes) {
PyMem_Free(self->font_bytes);
self->font_bytes = NULL;
}
Py_DECREF(self);
return geterror(error);
}
return (PyObject *)self;
}
#ifdef HAVE_RAQM
static size_t
text_layout_raqm(
PyObject *string,
FontObject *self,
const char *dir,
PyObject *features,
const char *lang,
GlyphInfo **glyph_info
) {
size_t i = 0, count = 0, start = 0;
raqm_t *rq;
raqm_glyph_t *glyphs = NULL;
raqm_direction_t direction;
rq = raqm_create();
if (rq == NULL) {
PyErr_SetString(PyExc_ValueError, "raqm_create() failed.");
goto failed;
}
Py_ssize_t size;
int set_text;
if (PyUnicode_Check(string)) {
Py_UCS4 *text = PyUnicode_AsUCS4Copy(string);
size = PyUnicode_GET_LENGTH(string);
if (!text || !size) {
/* return 0 and clean up, no glyphs==no size,
and raqm fails with empty strings */
goto failed;
}
set_text = raqm_set_text(rq, text, size);
PyMem_Free(text);
} else if (PyBytes_Check(string)) {
char *buffer;
PyBytes_AsStringAndSize(string, &buffer, &size);
if (!buffer || !size) {
/* return 0 and clean up, no glyphs==no size,
and raqm fails with empty strings */
goto failed;
}
set_text = raqm_set_text_utf8(rq, buffer, size);
} else {
PyErr_SetString(PyExc_TypeError, "expected string or bytes");
goto failed;
}
if (!set_text) {
PyErr_SetString(PyExc_ValueError, "raqm_set_text() failed");
goto failed;
}
if (lang && !raqm_set_language(rq, lang, start, size)) {
PyErr_SetString(PyExc_ValueError, "raqm_set_language() failed");
goto failed;
}
direction = RAQM_DIRECTION_DEFAULT;
if (dir) {
if (strcmp(dir, "rtl") == 0) {
direction = RAQM_DIRECTION_RTL;
} else if (strcmp(dir, "ltr") == 0) {
direction = RAQM_DIRECTION_LTR;
} else if (strcmp(dir, "ttb") == 0) {
direction = RAQM_DIRECTION_TTB;
#if !defined(RAQM_VERSION_ATLEAST)
/* RAQM_VERSION_ATLEAST was added in Raqm 0.7.0 */
PyErr_SetString(
PyExc_ValueError, "libraqm 0.7 or greater required for 'ttb' direction"
);
goto failed;
#endif
} else {
PyErr_SetString(
PyExc_ValueError, "direction must be either 'rtl', 'ltr' or 'ttb'"
);
goto failed;
}
}
if (!raqm_set_par_direction(rq, direction)) {
PyErr_SetString(PyExc_ValueError, "raqm_set_par_direction() failed");
goto failed;
}
if (features != Py_None) {
int j, len;
PyObject *seq = PySequence_Fast(features, "expected a sequence");
if (!seq) {
goto failed;
}
len = PySequence_Fast_GET_SIZE(seq);
for (j = 0; j < len; j++) {
PyObject *item = PySequence_Fast_GET_ITEM(seq, j);
char *feature = NULL;
Py_ssize_t size = 0;
PyObject *bytes;
if (!PyUnicode_Check(item)) {
Py_DECREF(seq);
PyErr_SetString(PyExc_TypeError, "expected a string");
goto failed;
}
bytes = PyUnicode_AsUTF8String(item);
if (bytes == NULL) {
Py_DECREF(seq);
goto failed;
}
feature = PyBytes_AS_STRING(bytes);
size = PyBytes_GET_SIZE(bytes);
if (!raqm_add_font_feature(rq, feature, size)) {
Py_DECREF(seq);
Py_DECREF(bytes);
PyErr_SetString(PyExc_ValueError, "raqm_add_font_feature() failed");
goto failed;
}
Py_DECREF(bytes);
}
Py_DECREF(seq);
}
if (!raqm_set_freetype_face(rq, self->face)) {
PyErr_SetString(PyExc_RuntimeError, "raqm_set_freetype_face() failed.");
goto failed;
}
if (!raqm_layout(rq)) {
PyErr_SetString(PyExc_RuntimeError, "raqm_layout() failed.");
goto failed;
}
glyphs = raqm_get_glyphs(rq, &count);
if (glyphs == NULL) {
PyErr_SetString(PyExc_ValueError, "raqm_get_glyphs() failed.");
count = 0;
goto failed;
}
(*glyph_info) = PyMem_New(GlyphInfo, count);
if ((*glyph_info) == NULL) {
PyErr_SetString(PyExc_MemoryError, "PyMem_New() failed");
count = 0;
goto failed;
}
for (i = 0; i < count; i++) {
(*glyph_info)[i].index = glyphs[i].index;
(*glyph_info)[i].x_offset = glyphs[i].x_offset;
(*glyph_info)[i].x_advance = glyphs[i].x_advance;
(*glyph_info)[i].y_offset = glyphs[i].y_offset;
(*glyph_info)[i].y_advance = glyphs[i].y_advance;
(*glyph_info)[i].cluster = glyphs[i].cluster;
}
failed:
raqm_destroy(rq);
return count;
}
#endif
static size_t
text_layout_fallback(
PyObject *string,
FontObject *self,
const char *dir,
PyObject *features,
const char *lang,
GlyphInfo **glyph_info,
int mask,
int color
) {
int error, load_flags, i;
char *buffer = NULL;
FT_ULong ch;
Py_ssize_t count;
FT_GlyphSlot glyph;
FT_Bool kerning = FT_HAS_KERNING(self->face);
FT_UInt last_index = 0;
if (features != Py_None || dir != NULL || lang != NULL) {
PyErr_SetString(
PyExc_KeyError,
"setting text direction, language or font features is not supported "
"without libraqm"
);
}
if (PyUnicode_Check(string)) {
count = PyUnicode_GET_LENGTH(string);
} else if (PyBytes_Check(string)) {
PyBytes_AsStringAndSize(string, &buffer, &count);
} else {
PyErr_SetString(PyExc_TypeError, "expected string or bytes");
return 0;
}
if (count == 0) {
return 0;
}
(*glyph_info) = PyMem_New(GlyphInfo, count);
if ((*glyph_info) == NULL) {
PyErr_SetString(PyExc_MemoryError, "PyMem_New() failed");
return 0;
}
load_flags = FT_LOAD_DEFAULT;
if (mask) {
load_flags |= FT_LOAD_TARGET_MONO;
}
if (color) {
load_flags |= FT_LOAD_COLOR;
}
for (i = 0; i < count; i++) {
if (buffer) {
ch = buffer[i];
} else {
ch = PyUnicode_READ_CHAR(string, i);
}
(*glyph_info)[i].index = FT_Get_Char_Index(self->face, ch);
error = FT_Load_Glyph(self->face, (*glyph_info)[i].index, load_flags);
if (error) {
geterror(error);
return 0;
}
glyph = self->face->glyph;
(*glyph_info)[i].x_offset = 0;
(*glyph_info)[i].y_offset = 0;
if (kerning && last_index && (*glyph_info)[i].index) {
FT_Vector delta;
if (FT_Get_Kerning(
self->face,
last_index,
(*glyph_info)[i].index,
ft_kerning_default,
&delta
) == 0) {
(*glyph_info)[i - 1].x_advance += PIXEL(delta.x);
(*glyph_info)[i - 1].y_advance += PIXEL(delta.y);
}
}
(*glyph_info)[i].x_advance = glyph->metrics.horiAdvance;
// y_advance is only used in ttb, which is not supported by basic layout
(*glyph_info)[i].y_advance = 0;
last_index = (*glyph_info)[i].index;
(*glyph_info)[i].cluster = ch;
}
return count;
}
static size_t
text_layout(
PyObject *string,
FontObject *self,
const char *dir,
PyObject *features,
const char *lang,
GlyphInfo **glyph_info,
int mask,
int color
) {
size_t count;
#ifdef HAVE_RAQM
if (have_raqm && self->layout_engine == LAYOUT_RAQM) {
count = text_layout_raqm(string, self, dir, features, lang, glyph_info);
} else
#endif
{
count = text_layout_fallback(
string, self, dir, features, lang, glyph_info, mask, color
);
}
return count;
}
static PyObject *
font_getlength(FontObject *self, PyObject *args) {
int length; /* length along primary axis, in 26.6 precision */
GlyphInfo *glyph_info = NULL; /* computed text layout */
size_t i, count; /* glyph_info index and length */
int horizontal_dir; /* is primary axis horizontal? */
int mask = 0; /* is FT_LOAD_TARGET_MONO enabled? */
int color = 0; /* is FT_LOAD_COLOR enabled? */
const char *mode = NULL;
const char *dir = NULL;
const char *lang = NULL;
PyObject *features = Py_None;
PyObject *string;
/* calculate size and bearing for a given string */
if (!PyArg_ParseTuple(
args, "O|zzOz:getlength", &string, &mode, &dir, &features, &lang
)) {
return NULL;
}
horizontal_dir = dir && strcmp(dir, "ttb") == 0 ? 0 : 1;
mask = mode && strcmp(mode, "1") == 0;
color = mode && strcmp(mode, "RGBA") == 0;
count = text_layout(string, self, dir, features, lang, &glyph_info, mask, color);
if (PyErr_Occurred()) {
return NULL;
}
length = 0;
for (i = 0; i < count; i++) {
if (horizontal_dir) {
length += glyph_info[i].x_advance;
} else {
length -= glyph_info[i].y_advance;
}
}
if (glyph_info) {
PyMem_Free(glyph_info);
glyph_info = NULL;
}
return PyLong_FromLong(length);
}
static int
bounding_box_and_anchors(
FT_Face face,
const char *anchor,
int horizontal_dir,
GlyphInfo *glyph_info,
size_t count,
int load_flags,
int *width,
int *height,
int *x_offset,
int *y_offset
) {
int position; /* pen position along primary axis, in 26.6 precision */
int advanced; /* pen position along primary axis, in pixels */
int px, py; /* position of current glyph, in pixels */
int x_min, x_max, y_min, y_max; /* text bounding box, in pixels */
int x_anchor, y_anchor; /* offset of point drawn at (0, 0), in pixels */
int error;
FT_Glyph glyph;
FT_BBox bbox; /* glyph bounding box */
size_t i; /* glyph_info index */
/*
* text bounds are given by:
* - bounding boxes of individual glyphs
* - pen line, i.e. 0 to `advanced` along primary axis
* this means point (0, 0) is part of the text bounding box
*/
position = x_min = x_max = y_min = y_max = 0;
for (i = 0; i < count; i++) {
if (horizontal_dir) {
px = PIXEL(position + glyph_info[i].x_offset);
py = PIXEL(glyph_info[i].y_offset);
position += glyph_info[i].x_advance;
advanced = PIXEL(position);
if (advanced > x_max) {
x_max = advanced;
}
} else {
px = PIXEL(glyph_info[i].x_offset);
py = PIXEL(position + glyph_info[i].y_offset);
position += glyph_info[i].y_advance;
advanced = PIXEL(position);
if (advanced < y_min) {
y_min = advanced;
}
}
error = FT_Load_Glyph(face, glyph_info[i].index, load_flags);
if (error) {
geterror(error);
return 1;
}
error = FT_Get_Glyph(face->glyph, &glyph);
if (error) {
geterror(error);
return 1;
}
FT_Glyph_Get_CBox(glyph, FT_GLYPH_BBOX_PIXELS, &bbox);
bbox.xMax += px;
if (bbox.xMax > x_max) {
x_max = bbox.xMax;
}
bbox.xMin += px;
if (bbox.xMin < x_min) {
x_min = bbox.xMin;
}
bbox.yMax += py;
if (bbox.yMax > y_max) {
y_max = bbox.yMax;
}
bbox.yMin += py;
if (bbox.yMin < y_min) {
y_min = bbox.yMin;
}
FT_Done_Glyph(glyph);
}
if (anchor == NULL) {
anchor = horizontal_dir ? "la" : "lt";
}
if (strlen(anchor) != 2) {
goto bad_anchor;
}
x_anchor = y_anchor = 0;
if (count) {
if (horizontal_dir) {
switch (anchor[0]) {
case 'l': // left
x_anchor = 0;
break;
case 'm': // middle (left + right) / 2
x_anchor = PIXEL(position / 2);
break;
case 'r': // right
x_anchor = PIXEL(position);
break;
case 's': // vertical baseline
default:
goto bad_anchor;
}
switch (anchor[1]) {
case 'a': // ascender
y_anchor = PIXEL(face->size->metrics.ascender);
break;
case 't': // top
y_anchor = y_max;
break;
case 'm': // middle (ascender + descender) / 2
y_anchor = PIXEL(
(face->size->metrics.ascender + face->size->metrics.descender) /
2
);
break;
case 's': // horizontal baseline
y_anchor = 0;
break;
case 'b': // bottom
y_anchor = y_min;
break;
case 'd': // descender
y_anchor = PIXEL(face->size->metrics.descender);
break;
default:
goto bad_anchor;
}
} else {
switch (anchor[0]) {
case 'l': // left
x_anchor = x_min;
break;
case 'm': // middle (left + right) / 2
x_anchor = (x_min + x_max) / 2;
break;
case 'r': // right
x_anchor = x_max;
break;
case 's': // vertical baseline
x_anchor = 0;
break;
default:
goto bad_anchor;
}
switch (anchor[1]) {
case 't': // top
y_anchor = 0;
break;
case 'm': // middle (top + bottom) / 2
y_anchor = PIXEL(position / 2);
break;
case 'b': // bottom
y_anchor = PIXEL(position);
break;
case 'a': // ascender
case 's': // horizontal baseline
case 'd': // descender
default:
goto bad_anchor;
}
}
}
*width = x_max - x_min;
*height = y_max - y_min;
*x_offset = -x_anchor + x_min;
*y_offset = -(-y_anchor + y_max);
return 0;
bad_anchor:
PyErr_Format(PyExc_ValueError, "bad anchor specified: %s", anchor);
return 1;
}
static PyObject *
font_getsize(FontObject *self, PyObject *args) {
int width, height, x_offset, y_offset;
int load_flags; /* FreeType load_flags parameter */
int error;
GlyphInfo *glyph_info = NULL; /* computed text layout */
size_t count; /* glyph_info length */
int horizontal_dir; /* is primary axis horizontal? */
int mask = 0; /* is FT_LOAD_TARGET_MONO enabled? */
int color = 0; /* is FT_LOAD_COLOR enabled? */
const char *mode = NULL;
const char *dir = NULL;
const char *lang = NULL;
const char *anchor = NULL;
PyObject *features = Py_None;
PyObject *string;
/* calculate size and bearing for a given string */
if (!PyArg_ParseTuple(
args, "O|zzOzz:getsize", &string, &mode, &dir, &features, &lang, &anchor
)) {
return NULL;
}
horizontal_dir = dir && strcmp(dir, "ttb") == 0 ? 0 : 1;
mask = mode && strcmp(mode, "1") == 0;
color = mode && strcmp(mode, "RGBA") == 0;
count = text_layout(string, self, dir, features, lang, &glyph_info, mask, color);
if (PyErr_Occurred()) {
return NULL;
}
load_flags = FT_LOAD_DEFAULT;
if (mask) {
load_flags |= FT_LOAD_TARGET_MONO;
}
if (color) {
load_flags |= FT_LOAD_COLOR;
}
error = bounding_box_and_anchors(
self->face,
anchor,
horizontal_dir,
glyph_info,
count,
load_flags,
&width,
&height,
&x_offset,
&y_offset
);
if (glyph_info) {
PyMem_Free(glyph_info);
glyph_info = NULL;
}
if (error) {
return NULL;
}
return Py_BuildValue("(ii)(ii)", width, height, x_offset, y_offset);
}
static PyObject *
font_render(FontObject *self, PyObject *args) {
int x, y; /* pen position, in 26.6 precision */
int px, py; /* position of current glyph, in pixels */
int x_min, y_max; /* text offset in 26.6 precision */
int load_flags; /* FreeType load_flags parameter */
int error;
FT_Glyph glyph;
FT_GlyphSlot glyph_slot;
FT_Bitmap bitmap;
FT_Bitmap bitmap_converted; /* initialized lazily, for non-8bpp fonts */
FT_BitmapGlyph bitmap_glyph;
FT_Stroker stroker = NULL;
int bitmap_converted_ready = 0; /* has bitmap_converted been initialized */
GlyphInfo *glyph_info = NULL; /* computed text layout */
size_t i, count; /* glyph_info index and length */
int xx, yy; /* pixel offset of current glyph bitmap */
int x0, x1; /* horizontal bounds of glyph bitmap to copy */
unsigned int bitmap_y; /* glyph bitmap y index */
unsigned char *source; /* glyph bitmap source buffer */
unsigned char convert_scale; /* scale factor for non-8bpp bitmaps */
PyObject *image;
Imaging im;
Py_ssize_t id;
int mask = 0; /* is FT_LOAD_TARGET_MONO enabled? */
int color = 0; /* is FT_LOAD_COLOR enabled? */
int stroke_width = 0;
PY_LONG_LONG foreground_ink_long = 0;
unsigned int foreground_ink;
const char *mode = NULL;
const char *dir = NULL;
const char *lang = NULL;
const char *anchor = NULL;
PyObject *features = Py_None;
PyObject *string;
PyObject *fill;
float x_start = 0;
float y_start = 0;
int width, height, x_offset, y_offset;
int horizontal_dir; /* is primary axis horizontal? */
/* render string into given buffer (the buffer *must* have
the right size, or this will crash) */
if (!PyArg_ParseTuple(
args,
"OO|zzOzizLffO:render",
&string,
&fill,
&mode,
&dir,
&features,
&lang,
&stroke_width,
&anchor,
&foreground_ink_long,
&x_start,
&y_start
)) {
return NULL;
}
mask = mode && strcmp(mode, "1") == 0;
color = mode && strcmp(mode, "RGBA") == 0;
foreground_ink = foreground_ink_long;
#ifdef FT_COLOR_H
if (color) {
FT_Color foreground_color;
FT_Byte *ink = (FT_Byte *)&foreground_ink;
foreground_color.red = ink[0];
foreground_color.green = ink[1];
foreground_color.blue = ink[2];
foreground_color.alpha =
(FT_Byte)255; /* ink alpha is handled in ImageDraw.text */
FT_Palette_Set_Foreground_Color(self->face, foreground_color);
}
#endif
count = text_layout(string, self, dir, features, lang, &glyph_info, mask, color);
if (PyErr_Occurred()) {
return NULL;
}
load_flags = stroke_width ? FT_LOAD_NO_BITMAP : FT_LOAD_DEFAULT;
if (mask) {
load_flags |= FT_LOAD_TARGET_MONO;
}
if (color) {
load_flags |= FT_LOAD_COLOR;
}
horizontal_dir = dir && strcmp(dir, "ttb") == 0 ? 0 : 1;
error = bounding_box_and_anchors(
self->face,
anchor,
horizontal_dir,
glyph_info,
count,
load_flags,
&width,
&height,
&x_offset,
&y_offset
);
if (error) {
PyMem_Del(glyph_info);
return NULL;
}
width += stroke_width * 2 + ceil(x_start);
height += stroke_width * 2 + ceil(y_start);
image = PyObject_CallFunction(fill, "ii", width, height);
if (image == Py_None) {
PyMem_Del(glyph_info);
return Py_BuildValue("N(ii)", image, 0, 0);
} else if (image == NULL) {
PyMem_Del(glyph_info);
return NULL;
}
PyObject *imageId = PyObject_GetAttrString(image, "id");
id = PyLong_AsSsize_t(imageId);
Py_XDECREF(imageId);
im = (Imaging)id;
x_offset -= stroke_width;
y_offset -= stroke_width;
if (count == 0 || width == 0 || height == 0) {
PyMem_Del(glyph_info);
return Py_BuildValue("N(ii)", image, x_offset, y_offset);
}
if (stroke_width) {
error = FT_Stroker_New(library, &stroker);
if (error) {
geterror(error);
goto glyph_error;
}
FT_Stroker_Set(
stroker,
(FT_Fixed)stroke_width * 64,
FT_STROKER_LINECAP_ROUND,
FT_STROKER_LINEJOIN_ROUND,
0
);
}
/*
* calculate x_min and y_max
* must match font_getsize or there may be clipping!
*/
x = y = x_min = y_max = 0;
for (i = 0; i < count; i++) {
px = PIXEL(x + glyph_info[i].x_offset);
py = PIXEL(y + glyph_info[i].y_offset);
error =
FT_Load_Glyph(self->face, glyph_info[i].index, load_flags | FT_LOAD_RENDER);
if (error) {
geterror(error);
goto glyph_error;
}
glyph_slot = self->face->glyph;
bitmap = glyph_slot->bitmap;
if (glyph_slot->bitmap_top + py > y_max) {
y_max = glyph_slot->bitmap_top + py;
}
if (glyph_slot->bitmap_left + px < x_min) {
x_min = glyph_slot->bitmap_left + px;
}
x += glyph_info[i].x_advance;
y += glyph_info[i].y_advance;
}
/* set pen position to text origin */
x = (-x_min + stroke_width + x_start) * 64;
y = (-y_max + (-stroke_width) - y_start) * 64;
if (stroker == NULL) {
load_flags |= FT_LOAD_RENDER;
}
for (i = 0; i < count; i++) {
px = PIXEL(x + glyph_info[i].x_offset);
py = PIXEL(y + glyph_info[i].y_offset);