Debian Codegraph @

FT2/freetyp2.c

raw
1 /*
2 =head1 NAME
3
4 freetyp2.c - font support via the FreeType library version 2.
5
6 =head1 SYNOPSIS
7
8 if (!i_ft2_init()) { error }
9 FT2_Fonthandle *font;
10 font = i_ft2_new(name, index);
11 if (!i_ft2_setdpi(font, xdpi, ydpi)) { error }
12 if (!i_ft2_getdpi(font, &xdpi, &ydpi)) { error }
13 double matrix[6];
14 if (!i_ft2_settransform(font, matrix)) { error }
15 i_img_dim bbox[BOUNDING_BOX_COUNT];
16 if (!i_ft2_bbox(font, cheight, cwidth, text, length, bbox, utf8)) { error }
17 i_img *im = ...;
18 i_color cl;
19 if (!i_ft2_text(font, im, tx, ty, cl, cheight, cwidth, text, length, align,
20 aa, vlayout, utf8)) { error }
21 if (!i_ft2_cp(font, im, tx, ty, channel, cheight, cwidth, text, length,
22 align, aa)) { error }
23 i_ft2_destroy(font);
24
25 =head1 DESCRIPTION
26
27 Implements Imager font support using the FreeType2 library.
28
29 The FreeType2 library understands several font file types, including
30 Truetype, Type1 and Windows FNT.
31
32 =over
33
34 =cut
35 */
36
37 #include "imext.h"
38 #include "imft2.h"
39 #include <stdio.h>
40 #include <math.h>
41 #include <string.h>
42 #include <ft2build.h>
43 #include FT_FREETYPE_H
44 #ifdef FT_MULTIPLE_MASTERS_H
45 #ifndef T1_CONFIG_OPTION_NO_MM_SUPPORT
46 #define IM_FT2_MM
47 #include FT_MULTIPLE_MASTERS_H
48 #endif
49 #endif
50 #ifdef FT_TYPE1_TABLES_H
51 #include FT_TYPE1_TABLES_H
52 #endif
53
54 static void ft2_push_message(int code);
55
56 static void ft2_final(void *);
57
58 static im_slot_t slot = -1;
59
60 typedef struct {
61 int initialized;
62 FT_Library library;
63 im_context_t ctx;
64 } ft2_state;
65
66 static ft2_state *
67 i_ft2_init(void);
68
69 static i_img_dim i_min(i_img_dim a, i_img_dim b);
70 static i_img_dim i_max(i_img_dim a, i_img_dim b);
71
72 int
73 i_ft2_version(int runtime, char *buf, size_t buf_size) {
74 char work[100];
75
76 i_clear_error();
77
78 if (buf_size == 0) {
79 i_push_error(0, "zero size buffer supplied");
80 return 0;
81 }
82 if (runtime) {
83 ft2_state *ft2;
84 /* initialized to work around a bug in FT2
85 http://lists.nongnu.org/archive/html/freetype-devel/2002-09/msg00058.html
86 Though I don't know why I still see this in 2.4.2
87 */
88 FT_Int major = 1, minor = 1, patch = 1;
89
90 if ((ft2 = i_ft2_init()) == NULL)
91 return 0;
92
93 FT_Library_Version(ft2->library, &major, &minor, &patch);
94 sprintf(work, "%d.%d.%d", (int)major, (int)minor, (int)patch);
95 }
96 else {
97 sprintf(work, "%d.%d.%d", FREETYPE_MAJOR, FREETYPE_MINOR, FREETYPE_PATCH);
98 }
99 strncpy(buf, work, buf_size);
100 buf[buf_size-1] = '\0';
101
102 return 1;
103 }
104
105 void
106 i_ft2_start(void) {
107 if (slot == -1)
108 slot = im_context_slot_new(ft2_final);
109 }
110
111 /*
112 =item i_ft2_init(void)
113
114 Initializes the Freetype 2 library.
115
116 Returns ft2_state * on success or NULL on failure.
117
118 =cut
119 */
120
121 static ft2_state *
122 i_ft2_init(void) {
123 FT_Error error;
124 im_context_t ctx = im_get_context();
125 ft2_state *ft2 = im_context_slot_get(ctx, slot);
126
127 if (ft2 == NULL) {
128 ft2 = mymalloc(sizeof(ft2_state));
129 ft2->initialized = 0;
130 ft2->library = NULL;
131 ft2->ctx = ctx;
132 im_context_slot_set(ctx, slot, ft2);
133 mm_log((1, "created FT2 state %p for context %p\n", ft2, ctx));
134 }
135
136 i_clear_error();
137 if (!ft2->initialized) {
138 error = FT_Init_FreeType(&ft2->library);
139 if (error) {
140 ft2_push_message(error);
141 i_push_error(0, "Initializing Freetype2");
142 return NULL;
143 }
144 mm_log((1, "initialized FT2 state %p\n", ft2));
145
146 ft2->initialized = 1;
147 }
148
149 return ft2;
150 }
151
152 static void
153 ft2_final(void *state) {
154 ft2_state *ft2 = state;
155
156 if (ft2->initialized) {
157 mm_log((1, "finalizing FT2 state %p\n", state));
158 FT_Done_FreeType(ft2->library);
159 ft2->library = NULL;
160 ft2->initialized = 0;
161 }
162
163 mm_log((1, "freeing FT2 state %p\n", state));
164 myfree(state);
165 }
166
167 struct FT2_Fonthandle {
168 FT_Face face;
169 ft2_state *state;
170 int xdpi, ydpi;
171 int hint;
172 FT_Encoding encoding;
173
174 /* used to adjust so we can align the draw point to the top-left */
175 double matrix[6];
176
177 #ifdef IM_FT2_MM
178 /* Multiple master data if any */
179 int has_mm;
180 FT_Multi_Master mm;
181 #endif
182 };
183
184 /* the following is used to select a "best" encoding */
185 static struct enc_score {
186 FT_Encoding encoding;
187 int score;
188 } enc_scores[] =
189 {
190 /* the selections here are fairly arbitrary
191 ideally we need to give the user a list of encodings available
192 and a mechanism to choose one */
193 { FT_ENCODING_UNICODE, 10 },
194 { FT_ENCODING_MS_SJIS, 8 },
195 { FT_ENCODING_MS_GB2312, 8 },
196 { FT_ENCODING_MS_BIG5, 8 },
197 { FT_ENCODING_MS_WANSUNG, 8 },
198 { FT_ENCODING_MS_JOHAB, 8 },
199 { FT_ENCODING_OLD_LATIN_2, 6 },
200 { FT_ENCODING_APPLE_ROMAN, 6 },
201 { FT_ENCODING_ADOBE_STANDARD, 6 },
202 { FT_ENCODING_ADOBE_EXPERT, 6 },
203 };
204
205 static const ssize_t
206 enc_score_count = sizeof(enc_scores) / sizeof(*enc_scores);
207
208 /*
209 =item i_ft2_new(char *name, int index)
210
211 Creates a new font object, from the file given by I<name>. I<index>
212 is the index of the font in a file with multiple fonts, where 0 is the
213 first font.
214
215 Return NULL on failure.
216
217 =cut
218 */
219
220 FT2_Fonthandle *
221 i_ft2_new(const char *name, int index) {
222 FT_Error error;
223 FT2_Fonthandle *result;
224 FT_Face face;
225 int i, j;
226 FT_Encoding encoding;
227 int score;
228 ft2_state *ft2;
229
230 mm_log((1, "i_ft2_new(name %p, index %d)\n", name, index));
231
232 if ((ft2 = i_ft2_init()) == NULL)
233 return NULL;
234
235 i_clear_error();
236 error = FT_New_Face(ft2->library, name, index, &face);
237 if (error) {
238 ft2_push_message(error);
239 i_push_error(error, "Opening face");
240 mm_log((2, "error opening face '%s': %d\n", name, error));
241 return NULL;
242 }
243
244 encoding = face->num_charmaps ? face->charmaps[0]->encoding : ft_encoding_unicode;
245 score = 0;
246 for (i = 0; i < face->num_charmaps; ++i) {
247 FT_Encoding enc_entry = face->charmaps[i]->encoding;
248 mm_log((2, "i_ft2_new, encoding %X platform %u encoding %u\n",
249 (unsigned)enc_entry, face->charmaps[i]->platform_id,
250 face->charmaps[i]->encoding_id));
251 for (j = 0; j < enc_score_count; ++j) {
252 if (enc_scores[j].encoding == enc_entry && enc_scores[j].score > score) {
253 encoding = enc_entry;
254 score = enc_scores[j].score;
255 break;
256 }
257 }
258 }
259 FT_Select_Charmap(face, encoding);
260 mm_log((2, "i_ft2_new, selected encoding %X\n", (unsigned)encoding));
261
262 result = mymalloc(sizeof(FT2_Fonthandle));
263 result->face = face;
264 result->state = ft2;
265 result->xdpi = result->ydpi = 72;
266 result->encoding = encoding;
267
268 /* by default we disable hinting on a call to i_ft2_settransform()
269 if we don't do this, then the hinting can the untransformed text
270 to be a different size to the transformed text.
271 Obviously we have it initially enabled.
272 */
273 result->hint = 1;
274
275 /* I originally forgot this: :/ */
276 /*i_ft2_settransform(result, matrix); */
277 result->matrix[0] = 1; result->matrix[1] = 0; result->matrix[2] = 0;
278 result->matrix[3] = 0; result->matrix[4] = 1; result->matrix[5] = 0;
279
280 #ifdef IM_FT2_MM
281 {
282 FT_Multi_Master *mm = &result->mm;
283 unsigned i;
284
285 if ((face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS) != 0
286 && (error = FT_Get_Multi_Master(face, mm)) == 0) {
287 mm_log((2, "MM Font, %d axes, %d designs\n", mm->num_axis, mm->num_designs));
288 for (i = 0; i < mm->num_axis; ++i) {
289 mm_log((2, " axis %u name %s range %ld - %ld\n", i, mm->axis[i].name,
290 (long)(mm->axis[i].minimum), (long)(mm->axis[i].maximum)));
291 }
292 result->has_mm = 1;
293 }
294 else {
295 mm_log((2, "No multiple masters\n"));
296 result->has_mm = 0;
297 }
298 }
299 #endif
300
301 return result;
302 }
303
304 /*
305 =item i_ft2_destroy(FT2_Fonthandle *handle)
306
307 Destroys a font object, which must have been the return value of
308 i_ft2_new().
309
310 =cut
311 */
312 void
313 i_ft2_destroy(FT2_Fonthandle *handle) {
314 FT_Done_Face(handle->face);
315 myfree(handle);
316 }
317
318 /*
319 =item i_ft2_setdpi(FT2_Fonthandle *handle, int xdpi, int ydpi)
320
321 Sets the resolution in dots per inch at which point sizes scaled, by
322 default xdpi and ydpi are 72, so that 1 point maps to 1 pixel.
323
324 Both xdpi and ydpi should be positive.
325
326 Return true on success.
327
328 =cut
329 */
330 int
331 i_ft2_setdpi(FT2_Fonthandle *handle, int xdpi, int ydpi) {
332 i_clear_error();
333 if (xdpi > 0 && ydpi > 0) {
334 handle->xdpi = xdpi;
335 handle->ydpi = ydpi;
336 return 1;
337 }
338 else {
339 i_push_error(0, "resolutions must be positive");
340 return 0;
341 }
342 }
343
344 /*
345 =item i_ft2_getdpi(FT2_Fonthandle *handle, int *xdpi, int *ydpi)
346
347 Retrieves the current horizontal and vertical resolutions at which
348 point sizes are scaled.
349
350 =cut
351 */
352 int
353 i_ft2_getdpi(FT2_Fonthandle *handle, int *xdpi, int *ydpi) {
354 *xdpi = handle->xdpi;
355 *ydpi = handle->ydpi;
356
357 return 1;
358 }
359
360 /*
361 =item i_ft2_settransform(FT2_FontHandle *handle, double *matrix)
362
363 Sets a transormation matrix for output.
364
365 This should be a 2 x 3 matrix like:
366
367 matrix[0] matrix[1] matrix[2]
368 matrix[3] matrix[4] matrix[5]
369
370 =cut
371 */
372 int
373 i_ft2_settransform(FT2_Fonthandle *handle, const double *matrix) {
374 FT_Matrix m;
375 FT_Vector v;
376 int i;
377
378 m.xx = matrix[0] * 65536;
379 m.xy = matrix[1] * 65536;
380 v.x = matrix[2]; /* this could be pels of 26.6 fixed - not sure */
381 m.yx = matrix[3] * 65536;
382 m.yy = matrix[4] * 65536;
383 v.y = matrix[5]; /* see just above */
384
385 FT_Set_Transform(handle->face, &m, &v);
386
387 for (i = 0; i < 6; ++i)
388 handle->matrix[i] = matrix[i];
389 handle->hint = 0;
390
391 return 1;
392 }
393
394 /*
395 =item i_ft2_sethinting(FT2_Fonthandle *handle, int hinting)
396
397 If hinting is non-zero then glyph hinting is enabled, otherwise disabled.
398
399 i_ft2_settransform() disables hinting to prevent distortions in
400 gradual text transformations.
401
402 =cut
403 */
404 int i_ft2_sethinting(FT2_Fonthandle *handle, int hinting) {
405 handle->hint = hinting;
406 return 1;
407 }
408
409 /*
410 =item i_ft2_bbox(FT2_Fonthandle *handle, double cheight, double cwidth, char *text, size_t len, i_img_dim *bbox)
411
412 Retrieves bounding box information for the font at the given
413 character width and height. This ignores the transformation matrix.
414
415 Returns non-zero on success.
416
417 =cut
418 */
419 int
420 i_ft2_bbox(FT2_Fonthandle *handle, double cheight, double cwidth,
421 char const *text, size_t len, i_img_dim *bbox, int utf8) {
422 FT_Error error;
423 i_img_dim width;
424 int index;
425 int first;
426 int ascent = 0, descent = 0;
427 int glyph_ascent, glyph_descent;
428 FT_Glyph_Metrics *gm;
429 int start = 0;
430 int loadFlags = FT_LOAD_DEFAULT;
431 int rightb = 0;
432
433 i_clear_error();
434
435 mm_log((1, "i_ft2_bbox(handle %p, cheight %f, cwidth %f, text %p, len %u, bbox %p)\n",
436 handle, cheight, cwidth, text, (unsigned)len, bbox));
437
438 error = FT_Set_Char_Size(handle->face, cwidth*64, cheight*64,
439 handle->xdpi, handle->ydpi);
440 if (error) {
441 ft2_push_message(error);
442 i_push_error(0, "setting size");
443 }
444
445 if (!handle->hint)
446 loadFlags |= FT_LOAD_NO_HINTING;
447
448 first = 1;
449 width = 0;
450 while (len) {
451 unsigned long c;
452 if (utf8) {
453 c = i_utf8_advance(&text, &len);
454 if (c == ~0UL) {
455 i_push_error(0, "invalid UTF8 character");
456 return 0;
457 }
458 }
459 else {
460 c = (unsigned char)*text++;
461 --len;
462 }
463
464 index = FT_Get_Char_Index(handle->face, c);
465 error = FT_Load_Glyph(handle->face, index, loadFlags);
466 if (error) {
467 ft2_push_message(error);
468 i_push_errorf(0, "loading glyph for character \\x%02lx (glyph 0x%04X)",
469 c, index);
470 return 0;
471 }
472 gm = &handle->face->glyph->metrics;
473 glyph_ascent = gm->horiBearingY / 64;
474 glyph_descent = glyph_ascent - gm->height/64;
475 if (first) {
476 start = gm->horiBearingX / 64;
477 /* handles -ve values properly */
478 ascent = glyph_ascent;
479 descent = glyph_descent;
480 first = 0;
481 }
482
483 if (glyph_ascent > ascent)
484 ascent = glyph_ascent;
485 if (glyph_descent < descent)
486 descent = glyph_descent;
487
488 width += gm->horiAdvance / 64;
489
490 if (len == 0) {
491 /* last character
492 handle the case where the right the of the character overlaps the
493 right*/
494 rightb = (gm->horiAdvance - gm->horiBearingX - gm->width)/64;
495 /*if (rightb > 0)
496 rightb = 0;*/
497 }
498 }
499
500 bbox[BBOX_NEG_WIDTH] = start;
501 bbox[BBOX_GLOBAL_DESCENT] = handle->face->size->metrics.descender / 64;
502 bbox[BBOX_POS_WIDTH] = width;
503 if (rightb < 0)
504 bbox[BBOX_POS_WIDTH] -= rightb;
505 bbox[BBOX_GLOBAL_ASCENT] = handle->face->size->metrics.ascender / 64;
506 bbox[BBOX_DESCENT] = descent;
507 bbox[BBOX_ASCENT] = ascent;
508 bbox[BBOX_ADVANCE_WIDTH] = width;
509 bbox[BBOX_RIGHT_BEARING] = rightb;
510 mm_log((1, " bbox=> negw=%" i_DF " glob_desc=%" i_DF " pos_wid=%" i_DF
511 " glob_asc=%" i_DF " desc=%" i_DF " asc=%" i_DF " adv_width=%" i_DF
512 " rightb=%" i_DF "\n",
513 i_DFc(bbox[0]), i_DFc(bbox[1]), i_DFc(bbox[2]), i_DFc(bbox[3]),
514 i_DFc(bbox[4]), i_DFc(bbox[5]), i_DFc(bbox[6]), i_DFc(bbox[7])));
515
516 return BBOX_RIGHT_BEARING + 1;
517 }
518
519 /*
520 =item transform_box(FT2_FontHandle *handle, int bbox[4])
521
522 bbox contains coorinates of a the top-left and bottom-right of a bounding
523 box relative to a point.
524
525 This is then transformed and the values in bbox[4] are the top-left
526 and bottom-right of the new bounding box.
527
528 This is meant to provide the bounding box of a transformed character
529 box. The problem is that if the character was round and is rotated,
530 the real bounding box isn't going to be much different from the
531 original, but this function will return a _bigger_ bounding box. I
532 suppose I could work my way through the glyph outline, but that's
533 too much hard work.
534
535 =cut
536 */
537 void ft2_transform_box(FT2_Fonthandle *handle, i_img_dim bbox[4]) {
538 double work[8];
539 double *matrix = handle->matrix;
540
541 work[0] = matrix[0] * bbox[0] + matrix[1] * bbox[1];
542 work[1] = matrix[3] * bbox[0] + matrix[4] * bbox[1];
543 work[2] = matrix[0] * bbox[2] + matrix[1] * bbox[1];
544 work[3] = matrix[3] * bbox[2] + matrix[4] * bbox[1];
545 work[4] = matrix[0] * bbox[0] + matrix[1] * bbox[3];
546 work[5] = matrix[3] * bbox[0] + matrix[4] * bbox[3];
547 work[6] = matrix[0] * bbox[2] + matrix[1] * bbox[3];
548 work[7] = matrix[3] * bbox[2] + matrix[4] * bbox[3];
549
550 bbox[0] = floor(i_min(i_min(work[0], work[2]),i_min(work[4], work[6])));
551 bbox[1] = floor(i_min(i_min(work[1], work[3]),i_min(work[5], work[7])));
552 bbox[2] = ceil(i_max(i_max(work[0], work[2]),i_max(work[4], work[6])));
553 bbox[3] = ceil(i_max(i_max(work[1], work[3]),i_max(work[5], work[7])));
554 }
555
556 /*
557 =item expand_bounds(int bbox[4], int bbox2[4])
558
559 Treating bbox[] and bbox2[] as 2 bounding boxes, produces a new
560 bounding box in bbox[] that encloses both.
561
562 =cut
563 */
564 static void expand_bounds(i_img_dim bbox[4], i_img_dim bbox2[4]) {
565 bbox[0] = i_min(bbox[0], bbox2[0]);
566 bbox[1] = i_min(bbox[1], bbox2[1]);
567 bbox[2] = i_max(bbox[2], bbox2[2]);
568 bbox[3] = i_max(bbox[3], bbox2[3]);
569 }
570
571 /*
572 =item i_ft2_bbox_r(FT2_Fonthandle *handle, double cheight, double cwidth, char *text, size_t len, int vlayout, int utf8, i_img_dim *bbox)
573
574 Retrieves bounding box information for the font at the given
575 character width and height.
576
577 This version finds the rectangular bounding box of the glyphs, with
578 the text as transformed by the transformation matrix. As with
579 i_ft2_bbox (bbox[0], bbox[1]) will the the offset from the start of
580 the topline to the top-left of the bounding box. Unlike i_ft2_bbox()
581 this could be near the bottom left corner of the box.
582
583 (bbox[4], bbox[5]) is the offset to the start of the baseline.
584 (bbox[6], bbox[7]) is the offset from the start of the baseline to the
585 end of the baseline.
586
587 Returns non-zero on success.
588
589 =cut
590 */
591 int
592 i_ft2_bbox_r(FT2_Fonthandle *handle, double cheight, double cwidth,
593 char const *text, size_t len, int vlayout, int utf8, i_img_dim *bbox) {
594 FT_Error error;
595 int index;
596 int first;
597 i_img_dim ascent = 0, descent = 0;
598 int glyph_ascent, glyph_descent;
599 FT_Glyph_Metrics *gm;
600 i_img_dim work[4];
601 i_img_dim bounds[4] = { 0 };
602 double x = 0, y = 0;
603 int i;
604 FT_GlyphSlot slot;
605 int loadFlags = FT_LOAD_DEFAULT;
606
607 if (vlayout)
608 loadFlags |= FT_LOAD_VERTICAL_LAYOUT;
609 if (!handle->hint)
610 loadFlags |= FT_LOAD_NO_HINTING;
611
612 error = FT_Set_Char_Size(handle->face, cwidth*64, cheight*64,
613 handle->xdpi, handle->ydpi);
614 if (error) {
615 ft2_push_message(error);
616 i_push_error(0, "setting size");
617 }
618
619 first = 1;
620 while (len) {
621 unsigned long c;
622 if (utf8) {
623 c = i_utf8_advance(&text, &len);
624 if (c == ~0UL) {
625 i_push_error(0, "invalid UTF8 character");
626 return 0;
627 }
628 }
629 else {
630 c = (unsigned char)*text++;
631 --len;
632 }
633
634 index = FT_Get_Char_Index(handle->face, c);
635 error = FT_Load_Glyph(handle->face, index, loadFlags);
636 if (error) {
637 ft2_push_message(error);
638 i_push_errorf(0, "loading glyph for character \\x%02lx (glyph 0x%04X)",
639 c, index);
640 return 0;
641 }
642 slot = handle->face->glyph;
643 gm = &slot->metrics;
644
645 /* these probably don't mean much for vertical layouts */
646 glyph_ascent = gm->horiBearingY / 64;
647 glyph_descent = glyph_ascent - gm->height/64;
648 if (vlayout) {
649 work[0] = gm->vertBearingX;
650 work[1] = gm->vertBearingY;
651 }
652 else {
653 work[0] = gm->horiBearingX;
654 work[1] = gm->horiBearingY;
655 }
656 work[2] = gm->width + work[0];
657 work[3] = work[1] - gm->height;
658 if (first) {
659 bbox[4] = work[0] * handle->matrix[0] + work[1] * handle->matrix[1] + handle->matrix[2];
660 bbox[5] = work[0] * handle->matrix[3] + work[1] * handle->matrix[4] + handle->matrix[5];
661 bbox[4] = bbox[4] < 0 ? -(-bbox[4] + 32)/64 : (bbox[4] + 32) / 64;
662 bbox[5] /= 64;
663 }
664 ft2_transform_box(handle, work);
665 for (i = 0; i < 4; ++i)
666 work[i] /= 64;
667 work[0] += x;
668 work[1] += y;
669 work[2] += x;
670 work[3] += y;
671 if (first) {
672 for (i = 0; i < 4; ++i)
673 bounds[i] = work[i];
674 ascent = glyph_ascent;
675 descent = glyph_descent;
676 first = 0;
677 }
678 else {
679 expand_bounds(bounds, work);
680 }
681 x += slot->advance.x / 64;
682 y += slot->advance.y / 64;
683
684 if (glyph_ascent > ascent)
685 ascent = glyph_ascent;
686 if (glyph_descent > descent)
687 descent = glyph_descent;
688
689 if (len == 0) {
690 /* last character
691 handle the case where the right the of the character overlaps the
692 right*/
693 /*int rightb = gm->horiAdvance - gm->horiBearingX - gm->width;
694 if (rightb < 0)
695 width -= rightb / 64;*/
696 }
697 }
698
699 /* at this point bounds contains the bounds relative to the CP,
700 and x, y hold the final position relative to the CP */
701 /*bounds[0] -= x;
702 bounds[1] -= y;
703 bounds[2] -= x;
704 bounds[3] -= y;*/
705
706 bbox[0] = bounds[0];
707 bbox[1] = -bounds[3];
708 bbox[2] = bounds[2];
709 bbox[3] = -bounds[1];
710 bbox[6] = x;
711 bbox[7] = -y;
712
713 return 1;
714 }
715
716 static int
717 make_bmp_map(FT_Bitmap *bitmap, unsigned char *map);
718
719 /*
720 =item i_ft2_text(FT2_Fonthandle *handle, i_img *im, int tx, int ty, i_color *cl, double cheight, double cwidth, char *text, size_t len, int align, int aa)
721
722 Renders I<text> to (I<tx>, I<ty>) in I<im> using color I<cl> at the given
723 I<cheight> and I<cwidth>.
724
725 If align is 0, then the text is rendered with the top-left of the
726 first character at (I<tx>, I<ty>). If align is non-zero then the text
727 is rendered with (I<tx>, I<ty>) aligned with the base-line of the
728 characters.
729
730 If aa is non-zero then the text is anti-aliased.
731
732 Returns non-zero on success.
733
734 =cut
735 */
736 int
737 i_ft2_text(FT2_Fonthandle *handle, i_img *im, i_img_dim tx, i_img_dim ty, const i_color *cl,
738 double cheight, double cwidth, char const *text, size_t len,
739 int align, int aa, int vlayout, int utf8) {
740 FT_Error error;
741 int index;
742 FT_Glyph_Metrics *gm;
743 i_img_dim bbox[BOUNDING_BOX_COUNT];
744 FT_GlyphSlot slot;
745 unsigned x, y;
746 unsigned char map[256];
747 char last_mode = ft_pixel_mode_none;
748 int last_grays = -1;
749 int loadFlags = FT_LOAD_DEFAULT;
750 i_render *render = NULL;
751 unsigned char *work_bmp = NULL;
752 size_t work_bmp_size = 0;
753
754 mm_log((1, "i_ft2_text(handle %p, im %p, (tx,ty) (" i_DFp "), cl %p (#%02x%02x%02x%02x), cheight %f, cwidth %f, text %p, len %u, align %d, aa %d, vlayout %d, utf8 %d)\n",
755 handle, im, i_DFcp(tx, ty), cl, cl->rgba.r, cl->rgba.g, cl->rgba.b,
756 cl->rgba.a, cheight, cwidth, text, (unsigned)len, align, aa,
757 vlayout, utf8));
758
759 i_clear_error();
760
761 if (vlayout) {
762 if (!FT_HAS_VERTICAL(handle->face)) {
763 i_push_error(0, "face has no vertical metrics");
764 return 0;
765 }
766 loadFlags |= FT_LOAD_VERTICAL_LAYOUT;
767 }
768 if (!handle->hint)
769 loadFlags |= FT_LOAD_NO_HINTING;
770
771 /* set the base-line based on the string ascent */
772 if (!i_ft2_bbox(handle, cheight, cwidth, text, len, bbox, utf8))
773 return 0;
774
775 render = i_render_new(im, bbox[BBOX_POS_WIDTH] - bbox[BBOX_NEG_WIDTH]);
776
777 work_bmp_size = bbox[BBOX_POS_WIDTH] - bbox[BBOX_NEG_WIDTH];
778 work_bmp = mymalloc(work_bmp_size);
779
780 if (!align) {
781 /* this may need adjustment */
782 tx -= bbox[0] * handle->matrix[0] + bbox[5] * handle->matrix[1] + handle->matrix[2];
783 ty += bbox[0] * handle->matrix[3] + bbox[5] * handle->matrix[4] + handle->matrix[5];
784 }
785 while (len) {
786 unsigned long c;
787 if (utf8) {
788 c = i_utf8_advance(&text, &len);
789 if (c == ~0UL) {
790 i_push_error(0, "invalid UTF8 character");
791 return 0;
792 }
793 }
794 else {
795 c = (unsigned char)*text++;
796 --len;
797 }
798
799 index = FT_Get_Char_Index(handle->face, c);
800 error = FT_Load_Glyph(handle->face, index, loadFlags);
801 if (error) {
802 ft2_push_message(error);
803 i_push_errorf(0, "loading glyph for character \\x%02lx (glyph 0x%04X)",
804 c, index);
805 if (render)
806 i_render_delete(render);
807 return 0;
808 }
809 slot = handle->face->glyph;
810 gm = &slot->metrics;
811
812 if (gm->width) {
813 error = FT_Render_Glyph(slot, aa ? ft_render_mode_normal : ft_render_mode_mono);
814 if (error) {
815 ft2_push_message(error);
816 i_push_errorf(0, "rendering glyph 0x%04lX (character \\x%02X)", c, index);
817 if (render)
818 i_render_delete(render);
819 return 0;
820 }
821 if (slot->bitmap.pixel_mode == ft_pixel_mode_mono) {
822 unsigned char *bmp = slot->bitmap.buffer;
823 if (work_bmp_size < slot->bitmap.width) {
824 work_bmp_size = slot->bitmap.width;
825 work_bmp = myrealloc(work_bmp, work_bmp_size);
826 }
827 for (y = 0; y < slot->bitmap.rows; ++y) {
828 int pos = 0;
829 int bit = 0x80;
830 unsigned char *p = work_bmp;
831 for (x = 0; x < slot->bitmap.width; ++x) {
832 *p++ = (bmp[pos] & bit) ? 0xff : 0;
833
834 bit >>= 1;
835 if (bit == 0) {
836 bit = 0x80;
837 ++pos;
838 }
839 }
840 i_render_color(render, tx + slot->bitmap_left, ty-slot->bitmap_top+y,
841 slot->bitmap.width, work_bmp, cl);
842
843 bmp += slot->bitmap.pitch;
844 }
845 }
846 else {
847 unsigned char *bmp = slot->bitmap.buffer;
848
849 /* grey scale or something we can treat as greyscale */
850 /* we create a map to convert from the bitmap values to 0-255 */
851 if (last_mode != slot->bitmap.pixel_mode
852 || last_grays != slot->bitmap.num_grays) {
853 if (!make_bmp_map(&slot->bitmap, map))
854 return 0;
855 last_mode = slot->bitmap.pixel_mode;
856 last_grays = slot->bitmap.num_grays;
857 }
858
859 for (y = 0; y < slot->bitmap.rows; ++y) {
860 if (last_mode == ft_pixel_mode_grays &&
861 last_grays != 255) {
862 for (x = 0; x < slot->bitmap.width; ++x)
863 bmp[x] = map[bmp[x]];
864 }
865 i_render_color(render, tx + slot->bitmap_left, ty-slot->bitmap_top+y,
866 slot->bitmap.width, bmp, cl);
867 bmp += slot->bitmap.pitch;
868 }
869 }
870 }
871
872 tx += slot->advance.x / 64;
873 ty -= slot->advance.y / 64;
874 }
875
876 if (render)
877 i_render_delete(render);
878
879 if (work_bmp)
880 myfree(work_bmp);
881
882 return 1;
883 }
884
885 /*
886 =item i_ft2_cp(FT2_Fonthandle *handle, i_img *im, int tx, int ty, int channel, double cheight, double cwidth, char *text, size_t len, int align, int aa, int vlayout, int utf8)
887
888 Renders I<text> to (I<tx>, I<ty>) in I<im> to I<channel> at the given
889 I<cheight> and I<cwidth>.
890
891 If align is 0, then the text is rendered with the top-left of the
892 first character at (I<tx>, I<ty>). If align is non-zero then the text
893 is rendered with (I<tx>, I<ty>) aligned with the base-line of the
894 characters.
895
896 If C<utf8> is non-zero the text is treated as UTF-8 encoded
897
898 If C<aa> is non-zero then the text is drawn anti-aliased.
899
900 Returns non-zero on success.
901
902 =cut
903 */
904
905 int
906 i_ft2_cp(FT2_Fonthandle *handle, i_img *im, i_img_dim tx, i_img_dim ty, int channel,
907 double cheight, double cwidth, char const *text, size_t len, int align,
908 int aa, int vlayout, int utf8) {
909 i_img_dim bbox[8];
910 i_img *work;
911 i_color cl;
912 int y;
913 unsigned char *bmp;
914
915 mm_log((1, "i_ft2_cp(handle %p, im %p, (tx, ty) (" i_DFp "), channel %d, cheight %f, cwidth %f, text %p, len %u, align %d, aa %d, vlayout %d, utf8 %d)\n",
916 handle, im, i_DFcp(tx, ty), channel, cheight, cwidth, text, (unsigned)len, align, aa, vlayout, utf8));
917
918 i_clear_error();
919
920 if (vlayout && !FT_HAS_VERTICAL(handle->face)) {
921 i_push_error(0, "face has no vertical metrics");
922 return 0;
923 }
924
925 if (!i_ft2_bbox_r(handle, cheight, cwidth, text, len, vlayout, utf8, bbox))
926 return 0;
927
928 work = i_img_8_new(bbox[2]-bbox[0]+1, bbox[3]-bbox[1]+1, 1);
929 cl.channel[0] = 255;
930 cl.channel[1] = 255;
931 cl.channel[2] = 255;
932 cl.channel[3] = 255;
933 if (!i_ft2_text(handle, work, -bbox[0], -bbox[1], &cl, cheight, cwidth,
934 text, len, 1, aa, vlayout, utf8))
935 return 0;
936
937 if (!align) {
938 tx -= bbox[4];
939 ty += bbox[5];
940 }
941
942 /* render to the specified channel */
943 /* this will be sped up ... */
944 bmp = mymalloc(work->xsize);
945 for (y = 0; y < work->ysize; ++y) {
946 i_gsamp(work, 0, work->xsize, y, bmp, NULL, 1);
947 i_psamp(im, tx + bbox[0], tx + bbox[0] + work->xsize,
948 ty + y + bbox[1], bmp, &channel, 1);
949 }
950 myfree(bmp);
951 i_img_destroy(work);
952 return 1;
953 }
954
955 /*
956 =item i_ft2_has_chars(handle, char *text, size_t len, int utf8, char *out)
957
958 Check if the given characters are defined by the font.
959
960 Returns the number of characters that were checked.
961
962 =cut
963 */
964 size_t
965 i_ft2_has_chars(FT2_Fonthandle *handle, char const *text, size_t len,
966 int utf8, char *out) {
967 int count = 0;
968 mm_log((1, "i_ft2_has_chars(handle %p, text %p, len %u, utf8 %d)\n",
969 handle, text, (unsigned)len, utf8));
970
971 i_clear_error();
972
973 while (len) {
974 unsigned long c;
975 int index;
976 if (utf8) {
977 c = i_utf8_advance(&text, &len);
978 if (c == ~0UL) {
979 i_push_error(0, "invalid UTF8 character");
980 return 0;
981 }
982 }
983 else {
984 c = (unsigned char)*text++;
985 --len;
986 }
987
988 index = FT_Get_Char_Index(handle->face, c);
989 *out++ = index != 0;
990 ++count;
991 }
992
993 return count;
994 }
995
996 /* uses a method described in fterrors.h to build an error translation
997 function
998 */
999 #undef __FTERRORS_H__
1000 #define FT_ERRORDEF(e, v, s) case v: i_push_error(code, s); return;
1001 #define FT_ERROR_START_LIST
1002 #define FT_ERROR_END_LIST
1003
1004 /*
1005 =back
1006
1007 =head2 Internal Functions
1008
1009 These functions are used in the implementation of freetyp2.c and should not
1010 (usually cannot) be called from outside it.
1011
1012 =over
1013
1014 =item ft2_push_message(int code)
1015
1016 Pushes an error message corresponding to code onto the error stack.
1017
1018 =cut
1019 */
1020
1021 #define UNKNOWN_ERROR_FORMAT "Unknown Freetype2 error code 0x%04X"
1022
1023 static void
1024 ft2_push_message(int code) {
1025 char unknown[40];
1026
1027 switch (code) {
1028 #include FT_ERRORS_H
1029 }
1030
1031 #ifdef IMAGER_SNPRINTF
1032 snprintf(unknown, sizeof(unknown), UNKNOWN_ERROR_FORMAT, code);
1033 #else
1034 sprintf(unknown, UNKNOWN_ERROR_FORMAT, code);
1035 #endif
1036 i_push_error(code, unknown);
1037 }
1038
1039 /*
1040 =item make_bmp_map(FT_Bitmap *bitmap, unsigned char *map)
1041
1042 Creates a map to convert grey levels from the glyphs bitmap into
1043 values scaled 0..255.
1044
1045 =cut
1046 */
1047 static int
1048 make_bmp_map(FT_Bitmap *bitmap, unsigned char *map) {
1049 int scale;
1050 int i;
1051
1052 switch (bitmap->pixel_mode) {
1053 case ft_pixel_mode_grays:
1054 scale = bitmap->num_grays;
1055 break;
1056
1057 default:
1058 i_push_errorf(0, "I can't handle pixel mode %d", bitmap->pixel_mode);
1059 return 0;
1060 }
1061
1062 /* build the table */
1063 for (i = 0; i < scale; ++i)
1064 map[i] = i * 255 / (bitmap->num_grays - 1);
1065
1066 return 1;
1067 }
1068
1069 /* FREETYPE_PATCH was introduced in 2.0.6, we don't want a false
1070 positive on 2.0.0 to 2.0.4, so we accept a false negative in 2.0.5 */
1071 #ifndef FREETYPE_PATCH
1072 #define FREETYPE_PATCH 4
1073 #endif
1074
1075 /* FT_Get_Postscript_Name() was introduced in FT2.0.5 */
1076 #define IM_HAS_FACE_NAME (FREETYPE_MINOR > 0 || FREETYPE_PATCH >= 5)
1077 /* #define IM_HAS_FACE_NAME 0 */
1078
1079 /*
1080 =item i_ft2_face_name(handle, name_buf, name_buf_size)
1081
1082 Fills the given buffer with the Postscript Face name of the font,
1083 if there is one.
1084
1085 Returns the number of bytes copied, including the terminating NUL.
1086
1087 =cut
1088 */
1089
1090 size_t
1091 i_ft2_face_name(FT2_Fonthandle *handle, char *name_buf, size_t name_buf_size) {
1092 #if IM_HAS_FACE_NAME
1093 char const *name = FT_Get_Postscript_Name(handle->face);
1094
1095 i_clear_error();
1096
1097 if (name) {
1098 strncpy(name_buf, name, name_buf_size);
1099 name_buf[name_buf_size-1] = '\0';
1100
1101 return strlen(name) + 1;
1102 }
1103 else {
1104 i_push_error(0, "no face name available");
1105 *name_buf = '\0';
1106
1107 return 0;
1108 }
1109 #else
1110 i_clear_error();
1111 i_push_error(0, "Freetype 2.0.6 or later required");
1112 *name_buf = '\0';
1113
1114 return 0;
1115 #endif
1116 }
1117
1118 int
1119 i_ft2_can_face_name(void) {
1120 return IM_HAS_FACE_NAME;
1121 }
1122
1123 /* FT_Has_PS_Glyph_Names() was introduced in FT2.1.1 */
1124 /* well, I assume FREETYPE_MAJOR is 2, since we're here */
1125 #if FREETYPE_MINOR < 1 || (FREETYPE_MINOR == 1 && FREETYPE_PATCH < 1)
1126 #define FT_Has_PS_Glyph_Names(face) (FT_HAS_GLYPH_NAMES(face))
1127 #endif
1128
1129 int
1130 i_ft2_glyph_name(FT2_Fonthandle *handle, unsigned long ch, char *name_buf,
1131 size_t name_buf_size, int reliable_only) {
1132 #ifdef FT_CONFIG_OPTION_NO_GLYPH_NAMES
1133 i_clear_error();
1134 *name_buf = '\0';
1135 i_push_error(0, "FT2 configured without glyph name support");
1136
1137 return 0;
1138 #else
1139 FT_UInt index;
1140
1141 i_clear_error();
1142
1143 if (!FT_HAS_GLYPH_NAMES(handle->face)) {
1144 i_push_error(0, "no glyph names in font");
1145 *name_buf = '\0';
1146 return 0;
1147 }
1148 if (reliable_only && !FT_Has_PS_Glyph_Names(handle->face)) {
1149 i_push_error(0, "no reliable glyph names in font - set reliable_only to 0 to try anyway");
1150 *name_buf = '\0';
1151 return 0;
1152 }
1153
1154 index = FT_Get_Char_Index(handle->face, ch);
1155
1156 if (index) {
1157 FT_Error error = FT_Get_Glyph_Name(handle->face, index, name_buf,
1158 name_buf_size);
1159 if (error) {
1160 ft2_push_message(error);
1161 *name_buf = '\0';
1162 return 0;
1163 }
1164 if (strcmp(name_buf, ".notdef") == 0) {
1165 *name_buf = 0;
1166 return 0;
1167 }
1168 if (*name_buf) {
1169 return strlen(name_buf) + 1;
1170 }
1171 else {
1172 return 0;
1173 }
1174 }
1175 else {
1176 *name_buf = 0;
1177 return 0;
1178 }
1179 #endif
1180 }
1181
1182 int
1183 i_ft2_can_do_glyph_names(void) {
1184 #ifdef FT_CONFIG_OPTION_NO_GLYPH_NAMES
1185 return 0;
1186 #else
1187 return 1;
1188 #endif
1189 }
1190
1191 int
1192 i_ft2_face_has_glyph_names(FT2_Fonthandle *handle) {
1193 #ifdef FT_CONFIG_OPTION_NO_GLYPH_NAMES
1194 return 0;
1195 #else
1196 return FT_HAS_GLYPH_NAMES(handle->face);
1197 /* return FT_Has_PS_Glyph_Names(handle->face);*/
1198 #endif
1199 }
1200
1201 int
1202 i_ft2_is_multiple_master(FT2_Fonthandle *handle) {
1203 i_clear_error();
1204 #ifdef IM_FT2_MM
1205 return handle->has_mm;
1206 #else
1207 return 0;
1208 #endif
1209 }
1210
1211 int
1212 i_ft2_get_multiple_masters(FT2_Fonthandle *handle, i_font_mm *mm) {
1213 #ifdef IM_FT2_MM
1214 unsigned i;
1215 FT_Multi_Master *mms = &handle->mm;
1216
1217 i_clear_error();
1218 if (!handle->has_mm) {
1219 i_push_error(0, "Font has no multiple masters");
1220 return 0;
1221 }
1222 mm->num_axis = mms->num_axis;
1223 mm->num_designs = mms->num_designs;
1224 for (i = 0; i < mms->num_axis; ++i) {
1225 mm->axis[i].name = mms->axis[i].name;
1226 mm->axis[i].minimum = mms->axis[i].minimum;
1227 mm->axis[i].maximum = mms->axis[i].maximum;
1228 }
1229
1230 return 1;
1231 #else
1232 i_clear_error();
1233 i_push_error(0, "Multiple master functions unavailable");
1234 return 0;
1235 #endif
1236 }
1237
1238 int
1239 i_ft2_set_mm_coords(FT2_Fonthandle *handle, int coord_count, const long *coords) {
1240 #ifdef IM_FT2_MM
1241 int i;
1242 FT_Long ftcoords[T1_MAX_MM_AXIS];
1243 FT_Error error;
1244
1245 i_clear_error();
1246 if (!handle->has_mm) {
1247 i_push_error(0, "Font has no multiple masters");
1248 return 0;
1249 }
1250 if ((unsigned)coord_count != handle->mm.num_axis) {
1251 i_push_error(0, "Number of MM coords doesn't match MM axis count");
1252 return 0;
1253 }
1254 for (i = 0; i < coord_count; ++i)
1255 ftcoords[i] = coords[i];
1256
1257 error = FT_Set_MM_Design_Coordinates(handle->face, coord_count, ftcoords);
1258 if (error) {
1259 ft2_push_message(error);
1260 return 0;
1261 }
1262
1263 return 1;
1264 #else
1265 i_clear_error();
1266 i_push_error(0, "Multiple master functions unavailable");
1267
1268 return 0;
1269 #endif
1270 }
1271
1272 static i_img_dim
1273 i_min(i_img_dim a, i_img_dim b) {
1274 return a < b ? a : b;
1275 }
1276
1277 static i_img_dim
1278 i_max(i_img_dim a, i_img_dim b) {
1279 return a > b ? a : b;
1280 }
1281
1282 /*
1283 =back
1284
1285 =head1 AUTHOR
1286
1287 Tony Cook <[email protected]>, with a fair amount of help from
1288 reading the code in font.c.
1289
1290 =head1 SEE ALSO
1291
1292 font.c, Imager::Font(3), Imager(3)
1293
1294 http://www.freetype.org/
1295
1296 =cut
1297 */
1298