Debian Codegraph @

src/FreeType/ftfuncs.c

raw
1 /*
2 Copyright (c) 1997 by Mark Leisher
3 Copyright (c) 1998-2003 by Juliusz Chroboczek
4 Copyright (c) 1998 Go Watanabe, All rights reserved.
5 Copyright (c) 1998 Kazushi (Jam) Marukawa, All rights reserved.
6 Copyright (c) 1998 Takuya SHIOZAKI, All rights reserved.
7 Copyright (c) 1998 X-TrueType Server Project, All rights reserved.
8 Copyright (c) 2003-2004 After X-TT Project, All rights reserved.
9
10 Permission is hereby granted, free of charge, to any person obtaining a copy
11 of this software and associated documentation files (the "Software"), to deal
12 in the Software without restriction, including without limitation the rights
13 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14 copies of the Software, and to permit persons to whom the Software is
15 furnished to do so, subject to the following conditions:
16
17 The above copyright notice and this permission notice shall be included in
18 all copies or substantial portions of the Software.
19
20 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26 THE SOFTWARE.
27 */
28
29 #ifdef HAVE_CONFIG_H
30 #include <config.h>
31 #endif
32 #include "libxfontint.h"
33 #include <X11/fonts/fontmisc.h>
34 #include "src/util/replace.h"
35
36 #include <string.h>
37 #include <math.h>
38 #include <ctype.h>
39
40 #include <X11/fonts/fntfilst.h>
41 #include <X11/fonts/fontutil.h>
42 #include <X11/fonts/FSproto.h>
43 #include <ft2build.h>
44 #include FT_FREETYPE_H
45 #include FT_SIZES_H
46 #include FT_TRUETYPE_IDS_H
47 #include FT_TRUETYPE_TABLES_H
48 #include FT_TYPE1_TABLES_H
49 #include FT_XFREE86_H
50 #include FT_BBOX_H
51 #include FT_TRUETYPE_TAGS_H
52 /*
53 * If you want to use FT_Outline_Get_CBox instead of
54 * FT_Outline_Get_BBox, define here.
55 */
56 /* #define USE_GET_CBOX */
57 #ifdef USE_GET_CBOX
58 #include FT_OUTLINE_H
59 #endif
60
61 #include <X11/fonts/fontenc.h>
62 #include "ft.h"
63 #include "ftfuncs.h"
64 #include "xttcap.h"
65
66 /* Work around FreeType bug */
67 #define WORK_AROUND_UPM 2048
68
69 #ifndef True
70 #define True (-1)
71 #endif /* True */
72 #ifndef False
73 #define False (0)
74 #endif /* False */
75
76 #define FLOOR64(x) ((x) & -64)
77 #define CEIL64(x) (((x) + 64 - 1) & -64)
78
79 /*
80 * If you want very lazy method(vl=y) AS DEFAULT when
81 * handling large charset, define here.
82 */
83 /* #define DEFAULT_VERY_LAZY 1 */ /* Always */
84 #define DEFAULT_VERY_LAZY 2 /* Multi-byte only */
85 /* #define DEFAULT_VERY_LAZY 256 */ /* Unicode only */
86
87 /* Does the X accept noSuchChar? */
88 #define X_ACCEPTS_NO_SUCH_CHAR
89 /* Does the XAA accept NULL noSuchChar.bits?(dangerous) */
90 /* #define XAA_ACCEPTS_NULL_BITS */
91
92 #ifdef X_ACCEPTS_NO_SUCH_CHAR
93 static CharInfoRec noSuchChar = { /* metrics */{0,0,0,0,0,0},
94 /* bits */ NULL };
95 #endif
96
97 /* The property names for all the XLFD properties. */
98
99 static const char *xlfd_props[] = {
100 "FOUNDRY",
101 "FAMILY_NAME",
102 "WEIGHT_NAME",
103 "SLANT",
104 "SETWIDTH_NAME",
105 "ADD_STYLE_NAME",
106 "PIXEL_SIZE",
107 "POINT_SIZE",
108 "RESOLUTION_X",
109 "RESOLUTION_Y",
110 "SPACING",
111 "AVERAGE_WIDTH",
112 "CHARSET_REGISTRY",
113 "CHARSET_ENCODING",
114 };
115
116
117 /* read 2-byte value from a SFNT table */
118 static FT_UShort
119 sfnt_get_ushort( FT_Face face,
120 FT_ULong table_tag,
121 FT_ULong table_offset )
122 {
123 FT_Byte buff[2];
124 FT_ULong len = sizeof(buff);
125 FT_UShort result = 0;
126
127 if ( !FT_Load_Sfnt_Table( face, table_tag, table_offset, buff, &len ) )
128 result = (FT_UShort)( (buff[0] << 8) | buff[1] );
129
130 return result;
131 }
132
133 #define sfnt_get_short(f,t,o) ((FT_Short)sfnt_get_ushort((f),(t),(o)))
134
135
136 static int ftypeInitP = 0; /* is the engine initialised? */
137 FT_Library ftypeLibrary;
138
139 static FTFacePtr faceTable[NUMFACEBUCKETS];
140
141 static unsigned
142 hash(char *string)
143 {
144 int i;
145 unsigned u = 0;
146 for(i = 0; string[i] != '\0'; i++)
147 u = (u<<5) + (u >> (NUMFACEBUCKETS - 5)) + (unsigned char)string[i];
148 return u;
149 }
150
151 static int
152 ifloor(int x, int y)
153 {
154 if(x >= 0)
155 return x/y;
156 else
157 return x/y - 1;
158 }
159
160 static int
161 iceil(int x, int y)
162 {
163 return ifloor(x + y - 1, y);
164 }
165
166 static int
167 FreeTypeOpenFace(FTFacePtr *facep, char *FTFileName, char *realFileName, int faceNumber)
168 {
169 FT_Error ftrc;
170 int bucket;
171 FTFacePtr face, otherFace;
172
173 if (!ftypeInitP) {
174 ftrc = FT_Init_FreeType(&ftypeLibrary);
175 if (ftrc != 0) {
176 ErrorF("FreeType: error initializing ftypeEngine: %d\n", ftrc);
177 return AllocError;
178 }
179 ftypeInitP = 1;
180 }
181
182 /* Try to find a matching face in the hashtable */
183 bucket = hash(FTFileName)%NUMFACEBUCKETS;
184 otherFace = faceTable[bucket];
185 while(otherFace) {
186 if( strcmp(otherFace->filename, FTFileName) == 0 ) break;
187 otherFace = otherFace->next;
188 }
189 if(otherFace) {
190 MUMBLE("Returning cached face: %s\n", otherFace->filename);
191 *facep = otherFace;
192 return Successful;
193 }
194
195 /* No cached match; need to make a new one */
196 face = calloc(1, sizeof(FTFaceRec));
197 if (face == NULL) {
198 return AllocError;
199 }
200
201 face->filename = strdup(FTFileName);
202 if (face->filename == NULL) {
203 free(face);
204 return AllocError;
205 }
206
207 ftrc = FT_New_Face(ftypeLibrary, realFileName, faceNumber, &face->face);
208 if(ftrc != 0) {
209 ErrorF("FreeType: couldn't open face %s: %d\n", FTFileName, ftrc);
210 free(face->filename);
211 free(face);
212 return BadFontName;
213 }
214
215 face->bitmap = ((face->face->face_flags & FT_FACE_FLAG_SCALABLE) == 0);
216 if(!face->bitmap) {
217 TT_MaxProfile *maxp;
218 maxp = FT_Get_Sfnt_Table(face->face, ft_sfnt_maxp);
219 if(maxp && maxp->maxContours == 0)
220 face->bitmap = 1;
221 }
222
223 face->num_hmetrics = (FT_UInt) sfnt_get_ushort( face->face,
224 TTAG_hhea, 34 );
225
226 /* Insert face in hashtable and return it */
227 face->next = faceTable[bucket];
228 faceTable[bucket] = face;
229 *facep = face;
230 return Successful;
231 }
232
233 static void
234 FreeTypeFreeFace(FTFacePtr face)
235 {
236 int bucket;
237 FTFacePtr otherFace;
238
239 if(!face->instances) {
240 bucket = hash(face->filename) % NUMFACEBUCKETS;
241 if(faceTable[bucket] == face)
242 faceTable[bucket] = face->next;
243 else {
244 otherFace = faceTable[bucket];
245 while(otherFace) {
246 if(otherFace->next == face)
247 break;
248 otherFace = otherFace->next;
249 }
250 if(otherFace && otherFace->next)
251 otherFace->next = otherFace->next->next;
252 else
253 ErrorF("FreeType: freeing unknown face\n");
254 }
255 MUMBLE("Closing face: %s\n", face->filename);
256 FT_Done_Face(face->face);
257 free(face->filename);
258 free(face);
259 }
260 }
261
262 static int
263 TransEqual(FTNormalisedTransformationPtr t1, FTNormalisedTransformationPtr t2)
264 {
265 if(t1->scale != t2->scale)
266 return 0;
267 else if(t1->xres != t2->xres || t1->yres != t2->yres)
268 return 0;
269 else if(t1->nonIdentity != t2->nonIdentity)
270 return 0;
271 else if(t1->nonIdentity && t2->nonIdentity) {
272 return
273 t1->matrix.xx == t2->matrix.xx &&
274 t1->matrix.yx == t2->matrix.yx &&
275 t1->matrix.yy == t2->matrix.yy &&
276 t1->matrix.xy == t2->matrix.xy;
277 } else
278 return 1;
279 }
280
281 static int
282 BitmapFormatEqual(FontBitmapFormatPtr f1, FontBitmapFormatPtr f2)
283 {
284 return
285 f1->bit == f2->bit &&
286 f1->byte == f2->byte &&
287 f1->glyph == f2->glyph;
288 }
289
290 static int
291 TTCapEqual(struct TTCapInfo *t1, struct TTCapInfo *t2)
292 {
293 return
294 t1->autoItalic == t2->autoItalic &&
295 t1->scaleWidth == t2->scaleWidth &&
296 t1->scaleBBoxWidth == t2->scaleBBoxWidth &&
297 t1->scaleBBoxHeight == t2->scaleBBoxHeight &&
298 t1->doubleStrikeShift == t2->doubleStrikeShift &&
299 t1->adjustBBoxWidthByPixel == t2->adjustBBoxWidthByPixel &&
300 t1->adjustLeftSideBearingByPixel == t2->adjustLeftSideBearingByPixel &&
301 t1->adjustRightSideBearingByPixel == t2->adjustRightSideBearingByPixel &&
302 t1->flags == t2->flags &&
303 t1->scaleBitmap == t2->scaleBitmap &&
304 /*
305 If we use forceConstantSpacing,
306 we *MUST* allocate new instance.
307 */
308 t1->forceConstantSpacingEnd < 0 &&
309 t2->forceConstantSpacingEnd < 0;
310 }
311
312 static int
313 FTInstanceMatch(FTInstancePtr instance,
314 char *FTFileName, FTNormalisedTransformationPtr trans,
315 int spacing, FontBitmapFormatPtr bmfmt,
316 struct TTCapInfo *tmp_ttcap, FT_Int32 load_flags)
317 {
318 if(strcmp(instance->face->filename, FTFileName) != 0) {
319 return 0;
320 } else if(!TransEqual(&instance->transformation, trans)) {
321 return 0;
322 } else if( spacing != instance->spacing ) {
323 return 0;
324 } else if( load_flags != instance->load_flags ) {
325 return 0;
326 } else if(!BitmapFormatEqual(&instance->bmfmt, bmfmt)) {
327 return 0;
328 } else if(!TTCapEqual(&instance->ttcap, tmp_ttcap)) {
329 return 0;
330 } else {
331 return 1;
332 }
333 }
334
335 static int
336 FreeTypeActivateInstance(FTInstancePtr instance)
337 {
338 FT_Error ftrc;
339 if(instance->face->active_instance == instance)
340 return Successful;
341
342 ftrc = FT_Activate_Size(instance->size);
343 if(ftrc != 0) {
344 instance->face->active_instance = NULL;
345 ErrorF("FreeType: couldn't activate instance: %d\n", ftrc);
346 return FTtoXReturnCode(ftrc);
347 }
348 FT_Set_Transform(instance->face->face,
349 instance->transformation.nonIdentity ?
350 &instance->transformation.matrix : 0,
351 0);
352
353 instance->face->active_instance = instance;
354 return Successful;
355 }
356
357 static int
358 FTFindSize(FT_Face face, FTNormalisedTransformationPtr trans,
359 int *x_return, int *y_return)
360 {
361 int tx, ty, x, y;
362 int i, j;
363 int d, dd;
364
365 if(trans->nonIdentity)
366 return BadFontName;
367
368 tx = (int)(trans->scale * trans->xres / 72.0 + 0.5);
369 ty = (int)(trans->scale * trans->yres / 72.0 + 0.5);
370
371 d = 100;
372 j = -1;
373 for(i = 0; i < face->num_fixed_sizes; i++) {
374 x = face->available_sizes[i].width;
375 y = face->available_sizes[i].height;
376 if(ABS(x - tx) <= 1 && ABS(y - ty) <= 1) {
377 dd = ABS(x - tx) * ABS(x - tx) + ABS(y - ty) * ABS(y - ty);
378 if(dd < d) {
379 j = i;
380 d = dd;
381 }
382 }
383 }
384 if(j < 0)
385 return BadFontName;
386
387 *x_return = face->available_sizes[j].width;
388 *y_return = face->available_sizes[j].height;
389 return Successful;
390 }
391
392 static int
393 FreeTypeOpenInstance(FTInstancePtr *instance_return, FTFacePtr face,
394 char *FTFileName, FTNormalisedTransformationPtr trans,
395 int spacing, FontBitmapFormatPtr bmfmt,
396 struct TTCapInfo *tmp_ttcap, FT_Int32 load_flags)
397 {
398 FT_Error ftrc;
399 int xrc;
400 FTInstancePtr instance, otherInstance;
401
402 /* Search for a matching instance */
403 for(otherInstance = face->instances;
404 otherInstance;
405 otherInstance = otherInstance->next) {
406 if(FTInstanceMatch(otherInstance, FTFileName, trans, spacing, bmfmt,
407 tmp_ttcap, load_flags)) break;
408 }
409 if(otherInstance) {
410 MUMBLE("Returning cached instance\n");
411 otherInstance->refcount++;
412 *instance_return = otherInstance;
413 return Successful;
414 }
415
416 /* None matching found */
417 instance = malloc(sizeof(FTInstanceRec));
418 if(instance == NULL) {
419 return AllocError;
420 }
421
422 instance->refcount = 1;
423 instance->face = face;
424
425 instance->load_flags = load_flags;
426 instance->spacing = spacing; /* Actual spacing */
427 instance->pixel_size =0;
428 instance->pixel_width_unit_x =0;
429 instance->pixel_width_unit_y =0;
430 instance->charcellMetrics = NULL;
431 instance->averageWidth = 0;
432 instance->rawAverageWidth = 0;
433 instance->forceConstantMetrics = NULL;
434
435 instance->transformation = *trans;
436 instance->bmfmt = *bmfmt;
437 instance->glyphs = NULL;
438 instance->available = NULL;
439
440 if( 0 <= tmp_ttcap->forceConstantSpacingEnd )
441 instance->nglyphs = 2 * instance->face->face->num_glyphs;
442 else
443 instance->nglyphs = instance->face->face->num_glyphs;
444
445 /* Store the TTCap info. */
446 memcpy((char*)&instance->ttcap, (char*)tmp_ttcap,
447 sizeof(struct TTCapInfo));
448
449 ftrc = FT_New_Size(instance->face->face, &instance->size);
450 if(ftrc != 0) {
451 ErrorF("FreeType: couldn't create size object: %d\n", ftrc);
452 free(instance);
453 return FTtoXReturnCode(ftrc);
454 }
455 FreeTypeActivateInstance(instance);
456 if(!face->bitmap) {
457 ftrc = FT_Set_Char_Size(instance->face->face,
458 (int)(trans->scale*(1<<6) + 0.5),
459 (int)(trans->scale*(1<<6) + 0.5),
460 trans->xres, trans->yres);
461 } else {
462 int xsize, ysize;
463 xrc = FTFindSize(face->face, trans, &xsize, &ysize);
464 if(xrc != Successful) {
465 free(instance);
466 return xrc;
467 }
468 ftrc = FT_Set_Pixel_Sizes(instance->face->face, xsize, ysize);
469 }
470 if(ftrc != 0) {
471 FT_Done_Size(instance->size);
472 free(instance);
473 return FTtoXReturnCode(ftrc);
474 }
475
476 if( FT_IS_SFNT( face->face ) ) {
477 #if 1
478 FT_F26Dot6 tt_char_width, tt_char_height, tt_dim_x, tt_dim_y;
479 FT_Int nn;
480
481 instance->strike_index=0xFFFFU;
482
483 tt_char_width = (FT_F26Dot6)(trans->scale*(1<<6) + 0.5);
484 tt_char_height = (FT_F26Dot6)(trans->scale*(1<<6) + 0.5);
485
486 tt_dim_x = FLOOR64( ( tt_char_width * trans->xres + 36 ) / 72 + 32 );
487 tt_dim_y = FLOOR64( ( tt_char_height * trans->yres + 36 ) / 72 + 32 );
488
489 if ( tt_dim_x && !tt_dim_y )
490 tt_dim_y = tt_dim_x;
491 else if ( !tt_dim_x && tt_dim_y )
492 tt_dim_x = tt_dim_y;
493
494 for ( nn = 0; nn < face->face->num_fixed_sizes; nn++ )
495 {
496 FT_Bitmap_Size* sz = &face->face->available_sizes[nn];
497
498 if ( tt_dim_x == FLOOR64(sz->x_ppem + 32) && tt_dim_y == FLOOR64(sz->y_ppem + 32) )
499 {
500 instance->strike_index = nn;
501 break;
502 }
503 }
504 #else
505 /* See Set_Char_Sizes() in ttdriver.c */
506 FT_Error err;
507 TT_Face tt_face;
508 FT_Long tt_dim_x, tt_dim_y;
509 FT_UShort tt_x_ppem, tt_y_ppem;
510 FT_F26Dot6 tt_char_width, tt_char_height;
511 SFNT_Service sfnt;
512 tt_face=(TT_Face)face->face;
513 tt_char_width = (int)(trans->scale*(1<<6) + 0.5);
514 tt_char_height = (int)(trans->scale*(1<<6) + 0.5);
515 if ( ( tt_face->header.Flags & 8 ) != 0 ) {
516 tt_dim_x = ( ( tt_char_width * trans->xres + (36+32*72) ) / 72 ) & -64;
517 tt_dim_y = ( ( tt_char_height * trans->yres + (36+32*72) ) / 72 ) & -64;
518 }
519 else{
520 tt_dim_x = ( ( tt_char_width * trans->xres + 36 ) / 72 );
521 tt_dim_y = ( ( tt_char_height * trans->yres + 36 ) / 72 );
522 }
523 tt_x_ppem = (FT_UShort)( tt_dim_x >> 6 );
524 tt_y_ppem = (FT_UShort)( tt_dim_y >> 6 );
525 /* See Reset_SBit_Size() in ttobjs.c */
526 sfnt = (SFNT_Service)tt_face->sfnt;
527 err = sfnt->set_sbit_strike(tt_face,tt_x_ppem,tt_y_ppem,&instance->strike_index);
528 if ( err ) instance->strike_index=0xFFFFU;
529 #endif
530 }
531
532 /* maintain a linked list of instances */
533 instance->next = instance->face->instances;
534 instance->face->instances = instance;
535
536 *instance_return = instance;
537 return Successful;
538 }
539
540 static void
541 FreeTypeFreeInstance(FTInstancePtr instance)
542 {
543 FTInstancePtr otherInstance;
544
545 if( instance == NULL ) return;
546
547 if(instance->face->active_instance == instance)
548 instance->face->active_instance = NULL;
549 instance->refcount--;
550 if(instance->refcount <= 0) {
551 int i,j;
552
553 if(instance->face->instances == instance)
554 instance->face->instances = instance->next;
555 else {
556 for(otherInstance = instance->face->instances;
557 otherInstance;
558 otherInstance = otherInstance->next)
559 if(otherInstance->next == instance) {
560 otherInstance->next = instance->next;
561 break;
562 }
563 }
564
565 FT_Done_Size(instance->size);
566 FreeTypeFreeFace(instance->face);
567
568 if(instance->charcellMetrics) {
569 free(instance->charcellMetrics);
570 }
571 if(instance->forceConstantMetrics) {
572 free(instance->forceConstantMetrics);
573 }
574 if(instance->glyphs) {
575 for(i = 0; i < iceil(instance->nglyphs, FONTSEGMENTSIZE); i++) {
576 if(instance->glyphs[i]) {
577 for(j = 0; j < FONTSEGMENTSIZE; j++) {
578 if(instance->available[i][j] ==
579 FT_AVAILABLE_RASTERISED)
580 free(instance->glyphs[i][j].bits);
581 }
582 free(instance->glyphs[i]);
583 }
584 }
585 free(instance->glyphs);
586 }
587 if(instance->available) {
588 for(i = 0; i < iceil(instance->nglyphs, FONTSEGMENTSIZE); i++) {
589 if(instance->available[i])
590 free(instance->available[i]);
591 }
592 free(instance->available);
593 }
594 free(instance);
595 }
596 }
597
598 static int
599 FreeTypeInstanceFindGlyph(unsigned idx_in, int flags, FTInstancePtr instance,
600 CharInfoPtr **glyphs, int ***available,
601 int *found, int *segmentP, int *offsetP)
602 {
603 int segment, offset;
604 unsigned idx = idx_in;
605
606 if( 0 <= instance->ttcap.forceConstantSpacingEnd ){
607 if( (flags & FT_FORCE_CONSTANT_SPACING) )
608 idx += instance->nglyphs / 2 ;
609 }
610
611 if(idx > instance->nglyphs) {
612 *found = 0;
613 return Successful;
614 }
615
616 if(*available == NULL) {
617 *available = calloc(iceil(instance->nglyphs, FONTSEGMENTSIZE),
618 sizeof(int *));
619 if(*available == NULL)
620 return AllocError;
621 }
622
623 segment = ifloor(idx, FONTSEGMENTSIZE);
624 offset = idx - segment * FONTSEGMENTSIZE;
625
626 if((*available)[segment] == NULL) {
627 (*available)[segment] = calloc(FONTSEGMENTSIZE, sizeof(int));
628 if((*available)[segment] == NULL)
629 return AllocError;
630 }
631
632 if(*glyphs == NULL) {
633 *glyphs = calloc(iceil(instance->nglyphs, FONTSEGMENTSIZE),
634 sizeof(CharInfoPtr));
635 if(*glyphs == NULL)
636 return AllocError;
637 }
638
639 if((*glyphs)[segment] == NULL) {
640 (*glyphs)[segment] = mallocarray(sizeof(CharInfoRec), FONTSEGMENTSIZE);
641 if((*glyphs)[segment] == NULL)
642 return AllocError;
643 }
644
645 *found = 1;
646 *segmentP = segment;
647 *offsetP = offset;
648 return Successful;
649 }
650
651 static int
652 FreeTypeInstanceGetGlyph(unsigned idx, int flags, CharInfoPtr *g, FTInstancePtr instance)
653 {
654 int found, segment, offset;
655 int xrc;
656 int ***available;
657 CharInfoPtr **glyphs;
658
659 available = &instance->available;
660 glyphs = &instance->glyphs;
661
662 xrc = FreeTypeInstanceFindGlyph(idx, flags, instance, glyphs, available,
663 &found, &segment, &offset);
664 if(xrc != Successful)
665 return xrc;
666
667 if(!found || (*available)[segment][offset] == FT_AVAILABLE_NO) {
668 *g = NULL;
669 return Successful;
670 }
671
672 if((*available)[segment][offset] == FT_AVAILABLE_RASTERISED) {
673 *g = &(*glyphs)[segment][offset];
674 return Successful;
675 }
676
677 flags |= FT_GET_GLYPH_BOTH;
678
679 xrc = FreeTypeRasteriseGlyph(idx, flags,
680 &(*glyphs)[segment][offset], instance,
681 (*available)[segment][offset] >= FT_AVAILABLE_METRICS);
682 if(xrc != Successful && (*available)[segment][offset] >= FT_AVAILABLE_METRICS) {
683 ErrorF("Warning: FreeTypeRasteriseGlyph() returns an error,\n");
684 ErrorF("\tso the backend tries to set a white space.\n");
685 xrc = FreeTypeRasteriseGlyph(idx, flags | FT_GET_DUMMY,
686 &(*glyphs)[segment][offset], instance,
687 (*available)[segment][offset] >= FT_AVAILABLE_METRICS);
688 }
689 if(xrc == Successful) {
690 (*available)[segment][offset] = FT_AVAILABLE_RASTERISED;
691 /* return the glyph */
692 *g = &(*glyphs)[segment][offset];
693 }
694 return xrc;
695 }
696
697 static int
698 FreeTypeInstanceGetGlyphMetrics(unsigned idx, int flags,
699 xCharInfo **metrics, FTInstancePtr instance )
700 {
701 int xrc;
702 int found, segment, offset;
703
704 /* Char cell */
705 if(instance->spacing == FT_CHARCELL) {
706 *metrics = instance->charcellMetrics;
707 return Successful;
708 }
709 /* Force constant metrics */
710 if( flags & FT_FORCE_CONSTANT_SPACING) {
711 *metrics = instance->forceConstantMetrics;
712 return Successful;
713 }
714
715 /* Not char cell */
716
717 xrc = FreeTypeInstanceFindGlyph(idx, flags, instance,
718 &instance->glyphs, &instance->available,
719 &found, &segment, &offset);
720 if(xrc != Successful)
721 return xrc;
722 if(!found) {
723 *metrics = NULL;
724 return Successful;
725 }
726 if( instance->available[segment][offset] == FT_AVAILABLE_NO ) {
727 *metrics = NULL;
728 return Successful;
729 }
730
731 if( instance->available[segment][offset] >= FT_AVAILABLE_METRICS ) {
732 *metrics = &instance->glyphs[segment][offset].metrics;
733 return Successful;
734 }
735
736 flags |= FT_GET_GLYPH_METRICS_ONLY;
737
738 xrc = FreeTypeRasteriseGlyph(idx, flags,
739 &instance->glyphs[segment][offset],
740 instance, 0);
741 if(xrc == Successful) {
742 instance->available[segment][offset] = FT_AVAILABLE_METRICS;
743 *metrics = &instance->glyphs[segment][offset].metrics;
744 }
745 return xrc;
746 }
747
748 /*
749 * Pseudo enbolding similar as Microsoft Windows.
750 * It is useful but poor.
751 */
752 static void
753 ft_make_up_bold_bitmap( char *raster, int bpr, int ht, int ds_mode)
754 {
755 int x, y;
756 unsigned char *p = (unsigned char *)raster;
757 if ( ds_mode & TTCAP_DOUBLE_STRIKE_MKBOLD_EDGE_LEFT ) {
758 for (y=0; y<ht; y++) {
759 unsigned char rev_pat=0;
760 unsigned char lsb = 0;
761 for (x=0; x<bpr; x++) {
762 unsigned char tmp = *p<<7;
763 if ( (rev_pat & 0x01) && (*p & 0x80) ) p[-1] &= 0xfe;
764 rev_pat = ~(*p);
765 *p |= (*p>>1) | lsb;
766 *p &= ~(rev_pat & (*p << 1));
767 lsb = tmp;
768 p++;
769 }
770 }
771 }
772 else {
773 for (y=0; y<ht; y++) {
774 unsigned char lsb = 0;
775 for (x=0; x<bpr; x++) {
776 unsigned char tmp = *p<<7;
777 *p |= (*p>>1) | lsb;
778 lsb = tmp;
779 p++;
780 }
781 }
782 }
783 }
784
785 static void
786 ft_make_up_italic_bitmap( char *raster, int bpr, int ht, int shift,
787 int h_total, int h_offset, double a_italic)
788 {
789 int x, y;
790 unsigned char *p = (unsigned char *)raster;
791 if ( a_italic < 0 ) shift = -shift;
792 for (y=0; y<ht; y++) {
793 unsigned char *tmp_p = p + y*bpr;
794 int tmp_shift = shift * (h_total -1 -(y+h_offset)) / h_total;
795 int tmp_byte_shift;
796 if ( 0 <= tmp_shift ) {
797 tmp_byte_shift = tmp_shift/8;
798 tmp_shift %= 8;
799 if ( tmp_shift ) {
800 for (x=bpr-1;0<=x;x--) {
801 if ( x != bpr-1 )
802 tmp_p[x+1] |= tmp_p[x]<<(8-tmp_shift);
803 tmp_p[x]>>=tmp_shift;
804 }
805 }
806 if ( tmp_byte_shift ) {
807 for (x=bpr-1;0<x;x--) {
808 tmp_p[x] = tmp_p[x-1];
809 }
810 tmp_p[x]=0;
811 }
812 }
813 else {
814 tmp_shift = -tmp_shift;
815 tmp_byte_shift = tmp_shift/8;
816 tmp_shift %= 8;
817 if ( tmp_shift ) {
818 for (x=0;x<bpr;x++) {
819 if ( x != 0 )
820 tmp_p[x-1] |= tmp_p[x]>>(8-tmp_shift);
821 tmp_p[x]<<=tmp_shift;
822 }
823 }
824 if ( tmp_byte_shift ) {
825 for (x=0;x<bpr-1;x++) {
826 tmp_p[x] = tmp_p[x+1];
827 }
828 tmp_p[x]=0;
829 }
830 }
831 }
832 }
833
834 /*
835 * The very lazy method,
836 * parse the htmx field in TrueType font.
837 */
838
839 static void
840 tt_get_metrics( FT_Face face,
841 FT_UInt idx,
842 FT_UInt num_hmetrics,
843 FT_Short* bearing,
844 FT_UShort* advance )
845 {
846 /* read the metrics directly from the horizontal header, we
847 * parse the SFNT table directly through the standard FreeType API.
848 * this works with any version of the library and doesn't need to
849 * peek at its internals. Maybe a bit less
850 */
851 FT_UInt count = num_hmetrics;
852 FT_ULong length = 0;
853 FT_ULong offset = 0;
854 FT_Error error;
855
856 error = FT_Load_Sfnt_Table( face, TTAG_hmtx, 0, NULL, &length );
857
858 if ( count == 0 || error )
859 {
860 *advance = 0;
861 *bearing = 0;
862 }
863 else if ( idx < count )
864 {
865 offset = idx * 4L;
866 if ( offset + 4 > length )
867 {
868 *advance = 0;
869 *bearing = 0;
870 }
871 else
872 {
873 *advance = sfnt_get_ushort( face, TTAG_hmtx, offset );
874 *bearing = sfnt_get_short ( face, TTAG_hmtx, offset+2 );
875 }
876 }
877 else
878 {
879 offset = 4L * (count - 1);
880 if ( offset + 4 > length )
881 {
882 *advance = 0;
883 *bearing = 0;
884 }
885 else
886 {
887 *advance = sfnt_get_ushort ( face, TTAG_hmtx, offset );
888 offset += 4 + 2 * ( idx - count );
889 if ( offset + 2 > length)
890 *bearing = 0;
891 else
892 *bearing = sfnt_get_short ( face, TTAG_hmtx, offset );
893 }
894 }
895 }
896
897 static int
898 ft_get_very_lazy_bbox( FT_UInt index,
899 FT_Face face,
900 FT_Size size,
901 FT_UInt num_hmetrics,
902 double slant,
903 FT_Matrix *matrix,
904 FT_BBox *bbox,
905 FT_Long *horiAdvance,
906 FT_Long *vertAdvance)
907 {
908 if ( FT_IS_SFNT( face ) ) {
909 FT_Size_Metrics *smetrics = &size->metrics;
910 FT_Short leftBearing = 0;
911 FT_UShort advance = 0;
912 FT_Vector p0, p1, p2, p3;
913
914 /* horizontal */
915 tt_get_metrics( face, index, num_hmetrics,
916 &leftBearing, &advance );
917
918 #if 0
919 fprintf(stderr,"x_scale=%f y_scale=%f\n",
920 (double)smetrics->x_scale,(double)smetrics->y_scale);
921 #endif
922 bbox->xMax = *horiAdvance =
923 FT_MulFix( advance, smetrics->x_scale );
924 bbox->xMin =
925 FT_MulFix( leftBearing, smetrics->x_scale );
926 /* vertical */
927 bbox->yMin = FT_MulFix( face->bbox.yMin,
928 smetrics->y_scale );
929 bbox->yMax = FT_MulFix( face->bbox.yMax,
930 smetrics->y_scale );
931 /* slant */
932 if( 0 < slant ) {
933 bbox->xMax += slant * bbox->yMax;
934 bbox->xMin += slant * bbox->yMin;
935 }
936 else if( slant < 0 ) {
937 bbox->xMax += slant * bbox->yMin;
938 bbox->xMin += slant * bbox->yMax;
939 }
940
941 *vertAdvance = -1; /* We don't support */
942
943 p0.x = p2.x = bbox->xMin;
944 p1.x = p3.x = bbox->xMax;
945 p0.y = p1.y = bbox->yMin;
946 p2.y = p3.y = bbox->yMax;
947
948 FT_Vector_Transform(&p0, matrix);
949 FT_Vector_Transform(&p1, matrix);
950 FT_Vector_Transform(&p2, matrix);
951 FT_Vector_Transform(&p3, matrix);
952
953 #if 0
954 fprintf(stderr,
955 "->(%.1f %.1f) (%.1f %.1f)"
956 " (%.1f %.1f) (%.1f %.1f)\n",
957 p0.x / 64.0, p0.y / 64.0,
958 p1.x / 64.0, p1.y / 64.0,
959 p2.x / 64.0, p2.y / 64.0,
960 p3.x / 64.0, p3.y / 64.0);
961 #endif
962 bbox->xMin = MIN(p0.x, MIN(p1.x, MIN(p2.x, p3.x)));
963 bbox->xMax = MAX(p0.x, MAX(p1.x, MAX(p2.x, p3.x)));
964 bbox->yMin = MIN(p0.y, MIN(p1.y, MIN(p2.y, p3.y)));
965 bbox->yMax = MAX(p0.y, MAX(p1.y, MAX(p2.y, p3.y)));
966 return 0; /* Successful */
967 }
968 return -1;
969 }
970
971 static FT_Error
972 FT_Do_SBit_Metrics( FT_Face ft_face, FT_Size ft_size, FT_ULong strike_index,
973 FT_UShort glyph_index, FT_Glyph_Metrics *metrics_return,
974 int *sbitchk_incomplete_but_exist )
975 {
976 #if 1
977 if ( strike_index != 0xFFFFU && ft_face->available_sizes != NULL )
978 {
979 FT_Error error;
980 FT_Bitmap_Size* sz = &ft_face->available_sizes[strike_index];
981
982 error = FT_Set_Pixel_Sizes( ft_face, sz->x_ppem/64, sz->y_ppem/64 );
983 if ( !error )
984 {
985 error = FT_Load_Glyph( ft_face, glyph_index, FT_LOAD_SBITS_ONLY );
986 if ( !error )
987 {
988 if ( metrics_return != NULL )
989 *metrics_return = ft_face->glyph->metrics;
990
991 return 0;
992 }
993 }
994 }
995 return -1;
996 #elif (FREETYPE_VERSION >= 2001008)
997 SFNT_Service sfnt;
998 TT_Face face;
999 FT_Error error;
1000 FT_Stream stream;
1001 TT_SBit_Strike strike;
1002 TT_SBit_Range range;
1003 TT_SBit_MetricsRec elem_metrics;
1004 FT_ULong ebdt_pos;
1005 FT_ULong glyph_offset;
1006 ;
1007
1008 if ( ! FT_IS_SFNT( ft_face ) )
1009 {
1010 error=-1;
1011 goto Exit;
1012 }
1013
1014 face = (TT_Face)ft_face;
1015 sfnt = (SFNT_Service)face->sfnt;
1016
1017 if (strike_index != 0xFFFFU && sfnt && sfnt->find_sbit_image &&
1018 sfnt->load_sbits) {
1019 /* Check whether there is a glyph sbit for the current index */
1020 error = sfnt->find_sbit_image( face, glyph_index, strike_index,
1021 &range, &strike, &glyph_offset );
1022 }
1023 else error=-1;
1024 if ( error ) goto Exit;
1025
1026 if ( metrics_return == NULL ) goto Exit;
1027
1028 stream = face->root.stream;
1029
1030 /* now, find the location of the `EBDT' table in */
1031 /* the font file */
1032 error = face->goto_table( face, TTAG_EBDT, stream, 0 );
1033 if ( error )
1034 error = face->goto_table( face, TTAG_bdat, stream, 0 );
1035 if (error)
1036 goto Exit;
1037
1038 ebdt_pos = FT_STREAM_POS();
1039
1040 /* place stream at beginning of glyph data and read metrics */
1041 if ( FT_STREAM_SEEK( ebdt_pos + glyph_offset ) )
1042 goto Exit;
1043
1044 error = sfnt->load_sbit_metrics( stream, range, &elem_metrics );
1045 if ( error )
1046 goto Exit;
1047
1048 metrics_return->width = (FT_Pos)elem_metrics.width << 6;
1049 metrics_return->height = (FT_Pos)elem_metrics.height << 6;
1050
1051 metrics_return->horiBearingX = (FT_Pos)elem_metrics.horiBearingX << 6;
1052 metrics_return->horiBearingY = (FT_Pos)elem_metrics.horiBearingY << 6;
1053 metrics_return->horiAdvance = (FT_Pos)elem_metrics.horiAdvance << 6;
1054
1055 metrics_return->vertBearingX = (FT_Pos)elem_metrics.vertBearingX << 6;
1056 metrics_return->vertBearingY = (FT_Pos)elem_metrics.vertBearingY << 6;
1057 metrics_return->vertAdvance = (FT_Pos)elem_metrics.vertAdvance << 6;
1058
1059 Exit:
1060 return error;
1061 #else /* if (FREETYPE_VERSION < 2001008) */
1062 TT_Face face;
1063 SFNT_Service sfnt;
1064 if ( ! FT_IS_SFNT( ft_face ) ) return -1;
1065 face = (TT_Face)ft_face;
1066 sfnt = (SFNT_Service)face->sfnt;
1067 if ( strike_index != 0xFFFFU && sfnt->load_sbits ) {
1068 if ( sbitchk_incomplete_but_exist ) *sbitchk_incomplete_but_exist=1;
1069 }
1070 return -1;
1071 #endif
1072 }
1073
1074 #pragma GCC diagnostic ignored "-Wbad-function-cast"
1075
1076 int
1077 FreeTypeRasteriseGlyph(unsigned idx, int flags, CharInfoPtr tgp,
1078 FTInstancePtr instance, int hasMetrics)
1079 {
1080 FTFacePtr face;
1081 FT_BBox bbox;
1082 FT_Long outline_hori_advance, outline_vert_advance;
1083 FT_Glyph_Metrics sbit_metrics;
1084 FT_Glyph_Metrics *bitmap_metrics=NULL, *metrics = NULL;
1085 char *raster;
1086 int wd, ht, bpr; /* width, height, bytes per row */
1087 int wd_actual, ht_actual;
1088 int ftrc, is_outline, correct, b_shift=0;
1089 int dx, dy;
1090 int leftSideBearing, rightSideBearing, characterWidth, rawCharacterWidth,
1091 ascent, descent;
1092 int sbitchk_incomplete_but_exist;
1093 double bbox_center_raw;
1094
1095 face = instance->face;
1096
1097 FreeTypeActivateInstance(instance);
1098
1099 if(!tgp) return AllocError;
1100
1101 /*
1102 * PREPARE METRICS
1103 */
1104
1105 if(!hasMetrics) {
1106 if( instance->spacing == FT_CHARCELL || flags & FT_GET_DUMMY ){
1107 memcpy((char*)&tgp->metrics,
1108 (char*)instance->charcellMetrics,
1109 sizeof(xCharInfo));
1110 }
1111 else if( flags & FT_FORCE_CONSTANT_SPACING ) {
1112 memcpy((char*)&tgp->metrics,
1113 (char*)instance->forceConstantMetrics,
1114 sizeof(xCharInfo));
1115 }
1116 /* mono or prop. */
1117 else{
1118 int new_width;
1119 double ratio;
1120
1121 sbitchk_incomplete_but_exist=0;
1122 if( ! (instance->load_flags & FT_LOAD_NO_BITMAP) ) {
1123 if( FT_Do_SBit_Metrics(face->face,instance->size,instance->strike_index,
1124 idx,&sbit_metrics,&sbitchk_incomplete_but_exist)==0 ) {
1125 bitmap_metrics = &sbit_metrics;
1126 }
1127 }
1128 if( bitmap_metrics == NULL ) {
1129 if ( sbitchk_incomplete_but_exist==0 && (instance->ttcap.flags & TTCAP_IS_VERY_LAZY) ) {
1130 if( ft_get_very_lazy_bbox( idx, face->face, instance->size,
1131 face->num_hmetrics,
1132 instance->ttcap.vl_slant,
1133 &instance->transformation.matrix,
1134 &bbox, &outline_hori_advance,
1135 &outline_vert_advance ) == 0 ) {
1136 goto bbox_ok; /* skip exact calculation */
1137 }
1138 }
1139 ftrc = FT_Load_Glyph(instance->face->face, idx,
1140 instance->load_flags);
1141 if(ftrc != 0) return FTtoXReturnCode(ftrc);
1142 metrics = &face->face->glyph->metrics;
1143 if( face->face->glyph->format == FT_GLYPH_FORMAT_BITMAP ) {
1144 bitmap_metrics = metrics;
1145 }
1146 }
1147
1148 if( bitmap_metrics ) {
1149 FT_Pos factor;
1150
1151 leftSideBearing = bitmap_metrics->horiBearingX / 64;
1152 rightSideBearing = (bitmap_metrics->width + bitmap_metrics->horiBearingX) / 64;
1153 bbox_center_raw = (2.0 * bitmap_metrics->horiBearingX + bitmap_metrics->width)/2.0/64.0;
1154 characterWidth = (int)floor(bitmap_metrics->horiAdvance
1155 * instance->ttcap.scaleBBoxWidth / 64.0 + .5);
1156 ascent = bitmap_metrics->horiBearingY / 64;
1157 descent = (bitmap_metrics->height - bitmap_metrics->horiBearingY) / 64 ;
1158 /* */
1159 new_width = characterWidth;
1160 if( instance->ttcap.flags & TTCAP_DOUBLE_STRIKE_CORRECT_B_BOX_WIDTH )
1161 new_width += instance->ttcap.doubleStrikeShift;
1162 new_width += instance->ttcap.adjustBBoxWidthByPixel;
1163 ratio = (double)new_width/characterWidth;
1164 characterWidth = new_width;
1165 /* adjustment by pixel unit */
1166 if( instance->ttcap.flags & TTCAP_DOUBLE_STRIKE )
1167 rightSideBearing += instance->ttcap.doubleStrikeShift;
1168 rightSideBearing += instance->ttcap.adjustRightSideBearingByPixel;
1169 leftSideBearing += instance->ttcap.adjustLeftSideBearingByPixel;
1170 rightSideBearing += instance->ttcap.rsbShiftOfBitmapAutoItalic;
1171 leftSideBearing += instance->ttcap.lsbShiftOfBitmapAutoItalic;
1172 /* */
1173 factor = bitmap_metrics->horiAdvance;
1174 rawCharacterWidth = (unsigned short)(short)(floor(1000 * factor
1175 * instance->ttcap.scaleBBoxWidth * ratio / 64.
1176 / instance->pixel_size));
1177 }
1178 else {
1179 /* Outline */
1180 #ifdef USE_GET_CBOX
1181 /* Very fast?? */
1182 FT_Outline_Get_CBox(&face->face->glyph->outline, &bbox);
1183 ftrc=0; /* FT_Outline_Get_CBox returns nothing. */
1184 #else
1185 /* Calculate exact metrics */
1186 ftrc=FT_Outline_Get_BBox(&face->face->glyph->outline, &bbox);
1187 #endif
1188 if( ftrc != 0 ) return FTtoXReturnCode(ftrc);
1189 outline_hori_advance = metrics->horiAdvance;
1190 outline_vert_advance = metrics->vertAdvance;
1191 bbox_ok:
1192 descent = CEIL64(-bbox.yMin - 32) / 64;
1193 leftSideBearing = FLOOR64(bbox.xMin + 32) / 64;
1194 ascent = FLOOR64(bbox.yMax + 32) / 64;
1195 rightSideBearing = FLOOR64(bbox.xMax + 32) / 64;
1196 bbox_center_raw = (double)(bbox.xMax + bbox.xMin)/2.0/64.;
1197 if ( instance->pixel_width_unit_x != 0 )
1198 characterWidth =
1199 (int)floor( outline_hori_advance
1200 * instance->ttcap.scaleBBoxWidth
1201 * instance->pixel_width_unit_x / 64. + .5);
1202 else {
1203 characterWidth =
1204 (int)floor( outline_vert_advance
1205 * instance->ttcap.scaleBBoxHeight
1206 * instance->pixel_width_unit_y / 64. + .5);
1207 if(characterWidth <= 0)
1208 characterWidth = instance->charcellMetrics->characterWidth;
1209 }
1210 /* */
1211 new_width = characterWidth;
1212 if( instance->ttcap.flags & TTCAP_DOUBLE_STRIKE_CORRECT_B_BOX_WIDTH )
1213 new_width += instance->ttcap.doubleStrikeShift;
1214 new_width += instance->ttcap.adjustBBoxWidthByPixel;
1215 ratio = (double)new_width/characterWidth;
1216 characterWidth = new_width;
1217 if ( instance->pixel_width_unit_x != 0 )
1218 rawCharacterWidth =
1219 (unsigned short)(short)(floor(1000 * outline_hori_advance
1220 * instance->ttcap.scaleBBoxWidth * ratio
1221 * instance->pixel_width_unit_x / 64.));
1222 else {
1223 rawCharacterWidth =
1224 (unsigned short)(short)(floor(1000 * outline_vert_advance
1225 * instance->ttcap.scaleBBoxHeight * ratio
1226 * instance->pixel_width_unit_y / 64.));
1227 if(rawCharacterWidth <= 0)
1228 rawCharacterWidth = instance->charcellMetrics->attributes;
1229 }
1230 /* adjustment by pixel unit */
1231 if( instance->ttcap.flags & TTCAP_DOUBLE_STRIKE )
1232 rightSideBearing += instance->ttcap.doubleStrikeShift;
1233 rightSideBearing += instance->ttcap.adjustRightSideBearingByPixel;
1234 leftSideBearing += instance->ttcap.adjustLeftSideBearingByPixel;
1235 }
1236
1237 /* Set the glyph metrics. */
1238 tgp->metrics.attributes = (unsigned short)((short)rawCharacterWidth);
1239 tgp->metrics.leftSideBearing = leftSideBearing;
1240 tgp->metrics.rightSideBearing = rightSideBearing;
1241 tgp->metrics.characterWidth = characterWidth;
1242 tgp->metrics.ascent = ascent;
1243 tgp->metrics.descent = descent;
1244 /* Update the width to match the width of the font */
1245 if( instance->spacing != FT_PROPORTIONAL )
1246 tgp->metrics.characterWidth = instance->charcellMetrics->characterWidth;
1247 if(instance->ttcap.flags & TTCAP_MONO_CENTER){
1248 b_shift = (int)floor((instance->advance/2.0-bbox_center_raw) + .5);
1249 tgp->metrics.leftSideBearing += b_shift;
1250 tgp->metrics.rightSideBearing += b_shift;
1251 }
1252 }
1253 }
1254
1255 if( flags & FT_GET_GLYPH_METRICS_ONLY ) return Successful;
1256
1257 /*
1258 * CHECK THE NECESSITY OF BITMAP POSITION'S CORRECTION
1259 */
1260
1261 correct=0;
1262 if( instance->spacing == FT_CHARCELL ) correct=1;
1263 else if( flags & FT_FORCE_CONSTANT_SPACING ) correct=1;
1264 else{
1265 int sbit_available=0;
1266 sbitchk_incomplete_but_exist=0;
1267 if( !(instance->load_flags & FT_LOAD_NO_BITMAP) ) {
1268 if( FT_Do_SBit_Metrics(face->face,instance->size,
1269 instance->strike_index,idx,NULL,
1270 &sbitchk_incomplete_but_exist)==0 ) {
1271 sbit_available=1;
1272 }
1273 }
1274 if( sbit_available == 0 ) {
1275 if ( sbitchk_incomplete_but_exist==0 && (instance->ttcap.flags & TTCAP_IS_VERY_LAZY) ) {
1276 if( FT_IS_SFNT(face->face) ) correct=1;
1277 }
1278 }
1279 }
1280
1281 /*
1282 * RENDER AND ALLOCATE BUFFER
1283 */
1284
1285 if( flags & FT_GET_DUMMY ) is_outline = -1;
1286 else {
1287 if( !metrics ) {
1288 ftrc = FT_Load_Glyph(instance->face->face, idx,
1289 instance->load_flags);
1290 metrics = &face->face->glyph->metrics;
1291
1292 if(ftrc != 0) return FTtoXReturnCode(ftrc);
1293 }
1294
1295 if( face->face->glyph->format != FT_GLYPH_FORMAT_BITMAP ) {
1296 #ifdef USE_GET_CBOX
1297 FT_Outline_Get_CBox(&face->face->glyph->outline, &bbox);
1298 ftrc = 0;
1299 #else
1300 ftrc = FT_Outline_Get_BBox(&face->face->glyph->outline, &bbox);
1301 #endif
1302 if( ftrc != 0 ) return FTtoXReturnCode(ftrc);
1303 bbox.yMin = FLOOR64( bbox.yMin );
1304 bbox.yMax = CEIL64 ( bbox.yMax );
1305 ht_actual = ( bbox.yMax - bbox.yMin ) >> 6;
1306 /* FreeType think a glyph with 0 height control box is invalid.
1307 * So just let X to create a empty bitmap instead. */
1308 if ( ht_actual == 0 )
1309 is_outline = -1;
1310 else
1311 {
1312 ftrc = FT_Render_Glyph(face->face->glyph,FT_RENDER_MODE_MONO);
1313 if( ftrc != 0 ) return FTtoXReturnCode(ftrc);
1314 is_outline = 1;
1315 }
1316 }
1317 else{
1318 is_outline=0;
1319 }
1320 }
1321
1322 /* Spacial case */
1323 if( (instance->ttcap.flags & TTCAP_MONO_CENTER) && hasMetrics ) {
1324 if( is_outline == 1 ){
1325 if( correct ){
1326 if( ft_get_very_lazy_bbox( idx, face->face, instance->size,
1327 face->num_hmetrics,
1328 instance->ttcap.vl_slant,
1329 &instance->transformation.matrix,
1330 &bbox, &outline_hori_advance,
1331 &outline_vert_advance ) != 0 ){
1332 is_outline = -1; /* <- error */
1333 }
1334 }
1335 else {
1336 #ifdef USE_GET_CBOX
1337 FT_Outline_Get_CBox(&face->face->glyph->outline, &bbox);
1338 ftrc=0;
1339 #else
1340 ftrc=FT_Outline_Get_BBox(&face->face->glyph->outline, &bbox);
1341 #endif
1342 if( ftrc != 0 ) return FTtoXReturnCode(ftrc);
1343 }
1344 bbox_center_raw = (double)(bbox.xMax + bbox.xMin)/2.0/64.;
1345 }
1346 else if( is_outline == 0 )
1347 bbox_center_raw = (2.0 * metrics->horiBearingX + metrics->width)/2.0/64.0;
1348 else
1349 bbox_center_raw = 0;
1350 b_shift = (int)floor((instance->advance/2.0-bbox_center_raw) + .5);
1351 }
1352
1353 wd_actual = tgp->metrics.rightSideBearing - tgp->metrics.leftSideBearing;
1354 ht_actual = tgp->metrics.ascent + tgp->metrics.descent;
1355
1356 /* The X convention is to consider a character with an empty
1357 * bounding box as undefined. This convention is broken. */
1358
1359 if(wd_actual <= 0) wd = 1;
1360 else wd=wd_actual;
1361 if(ht_actual <= 0) ht = 1;
1362 else ht=ht_actual;
1363
1364 bpr = (((wd + (instance->bmfmt.glyph<<3) - 1) >> 3) &
1365 -instance->bmfmt.glyph);
1366 raster = calloc(1, ht * bpr);
1367 if(raster == NULL)
1368 return AllocError;
1369
1370 tgp->bits = raster;
1371
1372 /* If FT_GET_DUMMY is set, we return white space. */
1373 if ( is_outline == -1 ) return Successful;
1374
1375 if ( wd_actual <= 0 || ht_actual <= 0 ) return Successful;
1376
1377 /*
1378 * CALCULATE OFFSET, dx AND dy.
1379 */
1380
1381 dx = face->face->glyph->bitmap_left - tgp->metrics.leftSideBearing;
1382 dy = tgp->metrics.ascent - face->face->glyph->bitmap_top;
1383
1384 if(instance->ttcap.flags & TTCAP_MONO_CENTER)
1385 dx += b_shift;
1386
1387 /* To prevent chipped bitmap, we correct dx and dy if needed. */
1388 if( correct && is_outline==1 ){
1389 int lsb, rsb, asc, des;
1390 int chip_left,chip_right,chip_top,chip_bot;
1391 #ifdef USE_GET_CBOX
1392 FT_Outline_Get_CBox(&face->face->glyph->outline, &bbox);
1393 ftrc=0;
1394 #else
1395 ftrc=FT_Outline_Get_BBox(&face->face->glyph->outline, &bbox);
1396 #endif
1397 if( ftrc != 0 ) return FTtoXReturnCode(ftrc);
1398 des = CEIL64(-bbox.yMin - 32) / 64;
1399 lsb = FLOOR64(bbox.xMin + 32) / 64;
1400 asc = FLOOR64(bbox.yMax + 32) / 64;
1401 rsb = FLOOR64(bbox.xMax + 32) / 64;
1402 rightSideBearing = tgp->metrics.rightSideBearing;
1403 leftSideBearing = tgp->metrics.leftSideBearing;
1404 if( instance->ttcap.flags & TTCAP_DOUBLE_STRIKE )
1405 rightSideBearing -= instance->ttcap.doubleStrikeShift;
1406 /* special case */
1407 if(instance->ttcap.flags & TTCAP_MONO_CENTER){
1408 leftSideBearing -= b_shift;
1409 rightSideBearing -= b_shift;
1410 }
1411 chip_left = lsb - leftSideBearing;
1412 chip_right = rightSideBearing - rsb;
1413 if( flags & FT_FORCE_CONSTANT_SPACING ){
1414 if( instance->ttcap.force_c_adjust_lsb_by_pixel != 0 ||
1415 instance->ttcap.force_c_adjust_rsb_by_pixel != 0 ){
1416 chip_left=0;
1417 chip_right=0;
1418 }
1419 }
1420 else{
1421 if( instance->ttcap.adjustRightSideBearingByPixel != 0 ||
1422 instance->ttcap.adjustLeftSideBearingByPixel != 0 ){
1423 chip_left=0;
1424 chip_right=0;
1425 }
1426 }
1427 chip_top = tgp->metrics.ascent - asc;
1428 chip_bot = tgp->metrics.descent - des;
1429 if( chip_left < 0 && 0 < chip_right ) dx++;
1430 else if( chip_right < 0 && 0 < chip_left ) dx--;
1431 if( chip_top < 0 && 0 < chip_bot ) dy++;
1432 else if( chip_bot < 0 && 0 < chip_top ) dy--;
1433 }
1434
1435 /*
1436 * COPY RASTER
1437 */
1438
1439 {
1440 FT_Bitmap *bitmap;
1441 int i, j;
1442 unsigned char *current_raster;
1443 unsigned char *current_buffer;
1444 int mod_dx0,mod_dx1;
1445 int div_dx;
1446 bitmap = &face->face->glyph->bitmap;
1447 if( 0 <= dx ){
1448 div_dx = dx / 8;
1449 mod_dx0 = dx % 8;
1450 mod_dx1 = 8-mod_dx0;
1451 }
1452 else{
1453 div_dx = dx / 8 -1;
1454 mod_dx1 = -dx % 8;
1455 mod_dx0 = 8-mod_dx1;
1456 }
1457 for( i = MAX(0, dy) ; i<ht ; i++ ){
1458 int prev_jj,jj;
1459 if( bitmap->rows <= (unsigned) (i-dy) ) break;
1460 current_buffer=(unsigned char *)(bitmap->buffer+bitmap->pitch*(i-dy));
1461 current_raster=(unsigned char *)(raster+i*bpr);
1462 j = MAX(0,div_dx);
1463 jj = j-div_dx;
1464 prev_jj = jj-1;
1465 if( j<bpr ){
1466 if( 0 <= prev_jj && prev_jj < bitmap->pitch )
1467 current_raster[j]|=current_buffer[prev_jj]<<mod_dx1;
1468 if( 0 <= jj && jj < bitmap->pitch ){
1469 current_raster[j]|=current_buffer[jj]>>mod_dx0;
1470 j++; prev_jj++; jj++;
1471 for( ; j<bpr ; j++,prev_jj++,jj++ ){
1472 current_raster[j]|=current_buffer[prev_jj]<<mod_dx1;
1473 if( bitmap->pitch <= jj ) break;
1474 current_raster[j]|=current_buffer[jj]>>mod_dx0;
1475 }
1476 }
1477 }
1478 }
1479 }
1480
1481 /* by TTCap */
1482 if ( instance->ttcap.flags & TTCAP_DOUBLE_STRIKE ) {
1483 int i;
1484 for( i=0 ; i < instance->ttcap.doubleStrikeShift ; i++ )
1485 ft_make_up_bold_bitmap( raster, bpr, ht, instance->ttcap.flags);
1486 }
1487 if ( is_outline == 0 &&
1488 ( instance->ttcap.lsbShiftOfBitmapAutoItalic != 0 ||
1489 instance->ttcap.rsbShiftOfBitmapAutoItalic != 0 ) ) {
1490 ft_make_up_italic_bitmap( raster, bpr, ht,
1491 - instance->ttcap.lsbShiftOfBitmapAutoItalic
1492 + instance->ttcap.rsbShiftOfBitmapAutoItalic,
1493 instance->charcellMetrics->ascent
1494 + instance->charcellMetrics->descent,
1495 instance->charcellMetrics->ascent
1496 - tgp->metrics.ascent,
1497 instance->ttcap.autoItalic);
1498 }
1499
1500 if(instance->bmfmt.bit == LSBFirst) {
1501 BitOrderInvert((unsigned char*)(tgp->bits), ht*bpr);
1502 }
1503
1504 if(instance->bmfmt.byte != instance->bmfmt.bit) {
1505 switch(instance->bmfmt.scan) {
1506 case 1:
1507 break;
1508 case 2:
1509 TwoByteSwap((unsigned char*)(tgp->bits), ht*bpr);
1510 break;
1511 case 4:
1512 FourByteSwap((unsigned char*)(tgp->bits), ht*bpr);
1513 break;
1514 default:
1515 ;
1516 }
1517 }
1518
1519 return Successful;
1520 }
1521
1522 static void
1523 FreeTypeFreeFont(FTFontPtr font)
1524 {
1525 FreeTypeFreeInstance(font->instance);
1526 if(font->ranges)
1527 free(font->ranges);
1528 if(font->dummy_char.bits)
1529 free(font->dummy_char.bits);
1530 free(font);
1531 }
1532
1533 /* Free a font. If freeProps is 0, don't free the properties. */
1534
1535 static void
1536 FreeTypeFreeXFont(FontPtr pFont, int freeProps)
1537 {
1538 FTFontPtr tf;
1539
1540 if(pFont) {
1541 if((tf = (FTFontPtr)pFont->fontPrivate)) {
1542 FreeTypeFreeFont(tf);
1543 }
1544 if(freeProps && pFont->info.nprops>0) {
1545 free(pFont->info.isStringProp);
1546 free(pFont->info.props);
1547 }
1548 DestroyFontRec(pFont);
1549 }
1550 }
1551
1552
1553 /* Unload a font */
1554
1555 static void
1556 FreeTypeUnloadXFont(FontPtr pFont)
1557 {
1558 MUMBLE("Unloading\n");
1559 FreeTypeFreeXFont(pFont, 1);
1560 }
1561
1562 /* Add the font properties, including the Font name, the XLFD
1563 properties, some strings from the font, and various typographical
1564 data. We only provide data readily available in the tables in the
1565 font for now, although FIGURE_WIDTH would be a good idea as it is
1566 used by Xaw. */
1567
1568 static int
1569 FreeTypeAddProperties(FTFontPtr font, FontScalablePtr vals, FontInfoPtr info,
1570 char *fontname, int rawAverageWidth, Bool font_properties)
1571 {
1572 int i, j, maxprops;
1573 char *sp, *ep, val[MAXFONTNAMELEN], *vp;
1574 FTFacePtr face;
1575 FTInstancePtr instance;
1576 FTNormalisedTransformationPtr trans;
1577 int upm;
1578 TT_OS2 *os2;
1579 TT_Postscript *post;
1580 PS_FontInfoRec t1info_rec, *t1info;
1581 int xlfdProps = 0;
1582 int ftrc;
1583
1584 instance = font->instance;
1585 face = instance->face;
1586 trans = &instance->transformation;
1587 upm = face->face->units_per_EM;
1588 if(upm == 0) {
1589 /* Work around FreeType bug */
1590 upm = WORK_AROUND_UPM;
1591 }
1592
1593 os2 = FT_Get_Sfnt_Table(face->face, ft_sfnt_os2);
1594 post = FT_Get_Sfnt_Table(face->face, ft_sfnt_post);
1595 ftrc = FT_Get_PS_Font_Info(face->face, &t1info_rec);
1596 if(ftrc == 0)
1597 t1info = &t1info_rec;
1598 else
1599 t1info = NULL;
1600
1601 if(t1info) {
1602 os2 = NULL;
1603 post = NULL;
1604 }
1605
1606 info->nprops = 0; /* in case we abort */
1607
1608 strlcpy(val, fontname, sizeof(val));
1609 if(FontParseXLFDName(val, vals, FONT_XLFD_REPLACE_VALUE)) {
1610 xlfdProps = 1;
1611 } else {
1612 MUMBLE("Couldn't parse XLFD\n");
1613 xlfdProps = 0;
1614 }
1615
1616 maxprops=
1617 1 + /* NAME */
1618 (xlfdProps ? 14 : 0) + /* from XLFD */
1619 5 +
1620 ( !face->bitmap ? 3 : 0 ) + /* raw_av,raw_asc,raw_dec */
1621 ( font_properties ? 2 : 0 ) + /* asc,dec */
1622 ( (font_properties && os2) ? 6 : 0 ) +
1623 ( (font_properties && (post || t1info)) ? 3 : 0 ) +
1624 2; /* type */
1625
1626 info->props = mallocarray(maxprops, sizeof(FontPropRec));
1627 if(info->props == NULL)
1628 return AllocError;
1629
1630 info->isStringProp = malloc(maxprops);
1631 if(info->isStringProp == NULL) {
1632 free(info->props);
1633 return AllocError;
1634 }
1635
1636 memset((char *)info->isStringProp, 0, maxprops);
1637
1638 i = 0;
1639
1640 info->props[i].name = MakeAtom("FONT", 4, TRUE);
1641 info->props[i].value = MakeAtom(val, strlen(val), TRUE);
1642 info->isStringProp[i] = 1;
1643 i++;
1644
1645 if(*val && *(sp = val + 1)) {
1646 for (j = 0, sp = val + 1; j < 14; j++) {
1647 if (j == 13)
1648 /* Handle the case of the final field containing a subset
1649 specification. */
1650 for (ep = sp; *ep && *ep != '['; ep++);
1651 else
1652 for (ep = sp; *ep && *ep != '-'; ep++);
1653
1654 info->props[i].name =
1655 MakeAtom(xlfd_props[j], strlen(xlfd_props[j]), TRUE);
1656
1657 switch(j) {
1658 case 6: /* pixel size */
1659 info->props[i].value =
1660 (int)(fabs(vals->pixel_matrix[3]) + 0.5);
1661 i++;
1662 break;
1663 case 7: /* point size */
1664 info->props[i].value =
1665 (int)(fabs(vals->point_matrix[3])*10.0 + 0.5);
1666 i++;
1667 break;
1668 case 8: /* resolution x */
1669 info->props[i].value = vals->x;
1670 i++;
1671 break;
1672 case 9: /* resolution y */
1673 info->props[i].value = vals->y;
1674 i++;
1675 break;
1676 case 11: /* average width */
1677 info->props[i].value = vals->width;
1678 i++;
1679 break;
1680 default: /* a string */
1681 info->props[i].value = MakeAtom(sp, ep - sp, TRUE);
1682 info->isStringProp[i] = 1;
1683 i++;
1684 }
1685 sp = ++ep;
1686 }
1687 }
1688
1689 info->props[i].name = MakeAtom("RAW_PIXEL_SIZE", 14, TRUE);
1690 info->props[i].value = 1000;
1691 i++;
1692
1693 info->props[i].name = MakeAtom("RAW_POINT_SIZE", 14, TRUE);
1694 info->props[i].value = (long)(72270.0 / (double)vals->y + .5);
1695 i++;
1696
1697 if(!face->bitmap) {
1698 info->props[i].name = MakeAtom("RAW_AVERAGE_WIDTH", 17, TRUE);
1699 info->props[i].value = rawAverageWidth;
1700 i++;
1701 }
1702
1703 if ( font_properties ) {
1704 info->props[i].name = MakeAtom("FONT_ASCENT", 11, TRUE);
1705 info->props[i].value = info->fontAscent;
1706 i++;
1707 }
1708
1709 if(!face->bitmap) {
1710 info->props[i].name = MakeAtom("RAW_ASCENT", 10, TRUE);
1711 info->props[i].value =
1712 ((double)face->face->ascender/(double)upm*1000.0);
1713 i++;
1714 }
1715
1716 if ( font_properties ) {
1717 info->props[i].name = MakeAtom("FONT_DESCENT", 12, TRUE);
1718 info->props[i].value = info->fontDescent;
1719 i++;
1720 }
1721
1722 if(!face->bitmap) {
1723 info->props[i].name = MakeAtom("RAW_DESCENT", 11, TRUE);
1724 info->props[i].value =
1725 -((double)face->face->descender/(double)upm*1000.0);
1726 i++;
1727 }
1728
1729 j = FTGetEnglishName(face->face, TT_NAME_ID_COPYRIGHT,
1730 val, MAXFONTNAMELEN);
1731 vp = val;
1732 if (j < 0) {
1733 if(t1info && t1info->notice) {
1734 vp = t1info->notice;
1735 j = strlen(vp);
1736 }
1737 }
1738 if(j > 0) {
1739 info->props[i].name = MakeAtom("COPYRIGHT", 9, TRUE);
1740 info->props[i].value = MakeAtom(vp, j, TRUE);
1741 info->isStringProp[i] = 1;
1742 i++;
1743 }
1744
1745 j = FTGetEnglishName(face->face, TT_NAME_ID_FULL_NAME,
1746 val, MAXFONTNAMELEN);
1747 vp = val;
1748 if (j < 0) {
1749 if(t1info && t1info->full_name) {
1750 vp = t1info->full_name;
1751 j = strlen(vp);
1752 }
1753 }
1754 if(j > 0) {
1755 info->props[i].name = MakeAtom("FACE_NAME", 9, TRUE);
1756 info->props[i].value = MakeAtom(vp, j, TRUE);
1757 info->isStringProp[i] = 1;
1758 i++;
1759 }
1760
1761 vp = (char *)FT_Get_Postscript_Name(face->face);
1762 if (vp) {
1763 j = strlen(vp);
1764 } else {
1765 j = -1;
1766 }
1767 if (j < 0) {
1768 j = FTGetEnglishName(face->face, TT_NAME_ID_PS_NAME,
1769 val, MAXFONTNAMELEN);
1770 vp = val;
1771 }
1772 if (j < 0) {
1773 if(t1info && t1info->full_name) {
1774 vp = t1info->full_name;
1775 j = strlen(vp);
1776 }
1777 }
1778 if(j > 0) {
1779 info->props[i].name = MakeAtom("_ADOBE_POSTSCRIPT_FONTNAME", 26, TRUE);
1780 info->props[i].value = MakeAtom(vp, j, TRUE);
1781 info->isStringProp[i] = 1;
1782 i++;
1783 }
1784
1785 /* These macros handle the case of a diagonal matrix. They convert
1786 FUnits into pixels. */
1787 #define TRANSFORM_FUNITS_X(xval) \
1788 ((int) \
1789 floor( ((double)(xval)/(double)upm) * (double)vals->pixel_matrix[0] + 0.5 ) )
1790
1791 #define TRANSFORM_FUNITS_Y(yval) \
1792 ((int) \
1793 floor( ((double)(yval)/(double)upm) * (double)vals->pixel_matrix[3] + 0.5 ) )
1794
1795 /* In what follows, we assume the matrix is diagonal. In the rare
1796 case when it is not, the values will be somewhat wrong. */
1797
1798 if( font_properties && os2 ) {
1799 info->props[i].name = MakeAtom("SUBSCRIPT_SIZE",14,TRUE);
1800 info->props[i].value =
1801 TRANSFORM_FUNITS_Y(os2->ySubscriptYSize);
1802 i++;
1803 info->props[i].name = MakeAtom("SUBSCRIPT_X",11,TRUE);
1804 info->props[i].value =
1805 TRANSFORM_FUNITS_X(os2->ySubscriptXOffset);
1806 i++;
1807 info->props[i].name = MakeAtom("SUBSCRIPT_Y",11,TRUE);
1808 info->props[i].value =
1809 TRANSFORM_FUNITS_Y(os2->ySubscriptYOffset);
1810 i++;
1811 info->props[i].name = MakeAtom("SUPERSCRIPT_SIZE",16,TRUE);
1812 info->props[i].value =
1813 TRANSFORM_FUNITS_Y(os2->ySuperscriptYSize);
1814 i++;
1815 info->props[i].name = MakeAtom("SUPERSCRIPT_X",13,TRUE);
1816 info->props[i].value =
1817 TRANSFORM_FUNITS_X(os2->ySuperscriptXOffset);
1818 i++;
1819 info->props[i].name = MakeAtom("SUPERSCRIPT_Y",13,TRUE);
1820 info->props[i].value =
1821 TRANSFORM_FUNITS_Y(os2->ySuperscriptYOffset);
1822 i++;
1823 }
1824
1825 if( font_properties && (post || t1info) ) {
1826 int underlinePosition, underlineThickness;
1827
1828 /* Raw underlineposition counts upwards,
1829 but UNDERLINE_POSITION counts downwards. */
1830 if(post) {
1831 underlinePosition = TRANSFORM_FUNITS_Y(-post->underlinePosition);
1832 underlineThickness = TRANSFORM_FUNITS_Y(post->underlineThickness);
1833 } else {
1834 underlinePosition =
1835 TRANSFORM_FUNITS_Y(-t1info->underline_position);
1836 underlineThickness =
1837 TRANSFORM_FUNITS_Y(t1info->underline_thickness);
1838 }
1839 if(underlineThickness <= 0)
1840 underlineThickness = 1;
1841
1842 info->props[i].name = MakeAtom("UNDERLINE_THICKNESS",19,TRUE);
1843 info->props[i].value = underlineThickness;
1844 i++;
1845
1846 info->props[i].name = MakeAtom("UNDERLINE_POSITION",18,TRUE);
1847
1848 info->props[i].value = underlinePosition;
1849
1850 i++;
1851
1852 /* The italic angle is often unreliable for Type 1 fonts */
1853 if(post && trans->matrix.xx == trans->matrix.yy) {
1854 info->props[i].name = MakeAtom("ITALIC_ANGLE",12,TRUE);
1855 info->props[i].value =
1856 /* Convert from TT_Fixed to
1857 64th of a degree counterclockwise from 3 o'clock */
1858 90*64+(post->italicAngle >> 10);
1859 i++;
1860 }
1861 #undef TRANSFORM_FUNITS_X
1862 #undef TRANSFORM_FUNITS_Y
1863 }
1864
1865 info->props[i].name = MakeAtom("FONT_TYPE", 9, TRUE);
1866 vp = (char *)FT_Get_X11_Font_Format(face->face);
1867 info->props[i].value = MakeAtom(vp, strlen(vp), TRUE);
1868 info->isStringProp[i] = 1;
1869 i++;
1870
1871 info->props[i].name = MakeAtom("RASTERIZER_NAME", 15, TRUE);
1872 info->props[i].value = MakeAtom("FreeType", 8, TRUE);
1873 info->isStringProp[i] = 1;
1874 i++;
1875
1876 info->nprops = i;
1877 return Successful;
1878 }
1879
1880 static int
1881 ft_get_index(unsigned code, FTFontPtr font, unsigned *idx)
1882 {
1883
1884 /* As a special case, we pass 0 even when it is not in the ranges;
1885 this will allow for the default glyph, which should exist in any
1886 TrueType font. */
1887
1888 /* This is not required...
1889 if(code > 0 && font->nranges) {
1890 int i;
1891 for(i = 0; i < font->nranges; i++)
1892 if((code >=
1893 font->ranges[i].min_char_low+
1894 (font->ranges[i].min_char_high<<8)) &&
1895 (code <=
1896 font->ranges[i].max_char_low +
1897 (font->ranges[i].max_char_high<<8)))
1898 break;
1899 if(i == font->nranges) {
1900 *idx = font->zero_idx;
1901 return -1;
1902 }
1903 }
1904 */
1905 if( font->info ) {
1906 if( !( font->info->firstCol <= (code & 0x000ff) &&
1907 (code & 0x000ff) <= font->info->lastCol &&
1908 font->info->firstRow <= (code >> 8) &&
1909 (code >> 8) <= font->info->lastRow ) ) {
1910 *idx = font->zero_idx;
1911 /* Error: The code has not been parsed in ft_compute_bounds()!
1912 We should not return any metrics. */
1913 return -1;
1914 }
1915 }
1916
1917 *idx = FTRemap(font->instance->face->face, &font->mapping, code);
1918
1919 return 0;
1920 }
1921
1922 static int
1923 FreeTypeFontGetGlyph(unsigned code, int flags, CharInfoPtr *g, FTFontPtr font)
1924 {
1925 unsigned idx = 0;
1926 int xrc;
1927
1928 #ifdef X_ACCEPTS_NO_SUCH_CHAR
1929 if( ft_get_index(code,font,&idx) || idx == 0 || idx == font->zero_idx ) {
1930 *g = NULL;
1931 flags &= ~FT_FORCE_CONSTANT_SPACING;
1932 /* if( font->instance->spacing != FT_CHARCELL ) */
1933 return Successful;
1934 }
1935 #else
1936 if( ft_get_index(code,font,&idx) ) {
1937 /* The code has not been parsed! */
1938 *g = NULL;
1939 flags &= ~FT_FORCE_CONSTANT_SPACING;
1940 }
1941 #endif
1942
1943 xrc = FreeTypeInstanceGetGlyph(idx, flags, g, font->instance);
1944 if( xrc == Successful && *g != NULL )
1945 return Successful;
1946 if( font->zero_idx != idx ) {
1947 xrc = FreeTypeInstanceGetGlyph(font->zero_idx, flags, g, font->instance);
1948 if( xrc == Successful && *g != NULL )
1949 return Successful;
1950 }
1951 return FreeTypeInstanceGetGlyph(font->zero_idx, flags|FT_GET_DUMMY, g, font->instance);
1952 }
1953
1954 static int
1955 FreeTypeFontGetGlyphMetrics(unsigned code, int flags, xCharInfo **metrics, FTFontPtr font)
1956 {
1957 unsigned idx = 0;
1958 int xrc;
1959
1960 #ifdef X_ACCEPTS_NO_SUCH_CHAR
1961 if ( ft_get_index(code,font,&idx) || idx == 0 || idx == font->zero_idx ) {
1962 *metrics = NULL;
1963 flags &= ~FT_FORCE_CONSTANT_SPACING;
1964 /* if( font->instance->spacing != FT_CHARCELL ) */
1965 return Successful;
1966 }
1967 #else
1968 if ( ft_get_index(code,font,&idx) || idx == 0 || idx == font->zero_idx ) {
1969 /* The code has not been parsed! */
1970 *metrics = NULL;
1971 flags &= ~FT_FORCE_CONSTANT_SPACING;
1972 }
1973 #endif
1974
1975 xrc = FreeTypeInstanceGetGlyphMetrics(idx, flags, metrics, font->instance);
1976 if( xrc == Successful && *metrics != NULL )
1977 return Successful;
1978 if( font->zero_idx != idx ) {
1979 xrc = FreeTypeInstanceGetGlyphMetrics(font->zero_idx, flags,
1980 metrics, font->instance);
1981 if( xrc == Successful && *metrics != NULL )
1982 return Successful;
1983 }
1984 return FreeTypeInstanceGetGlyphMetrics(font->zero_idx, flags|FT_GET_DUMMY, metrics, font->instance);
1985 }
1986
1987 /*
1988 * restrict code range
1989 *
1990 * boolean for the numeric zone:
1991 * results = results & (ranges[0] | ranges[1] | ... ranges[nranges-1])
1992 */
1993
1994 static void
1995 restrict_code_range(unsigned short *refFirstCol,
1996 unsigned short *refFirstRow,
1997 unsigned short *refLastCol,
1998 unsigned short *refLastRow,
1999 fsRange const *ranges, int nRanges)
2000 {
2001 if (nRanges) {
2002 int minCol = 256, minRow = 256, maxCol = -1, maxRow = -1;
2003 fsRange const *r = ranges;
2004 int i;
2005
2006 for (i=0; i<nRanges; i++) {
2007 if (r->min_char_high != r->max_char_high) {
2008 minCol = 0x00;
2009 maxCol = 0xff;
2010 } else {
2011 if (minCol > r->min_char_low)
2012 minCol = r->min_char_low;
2013 if (maxCol < r->max_char_low)
2014 maxCol = r->max_char_low;
2015 }
2016 if (minRow > r->min_char_high)
2017 minRow = r->min_char_high;
2018 if (maxRow < r->max_char_high)
2019 maxRow = r->max_char_high;
2020 r++;
2021 }
2022
2023 if (minCol > *refLastCol)
2024 *refFirstCol = *refLastCol;
2025 else if (minCol > *refFirstCol)
2026 *refFirstCol = minCol;
2027
2028 if (maxCol < *refFirstCol)
2029 *refLastCol = *refFirstCol;
2030 else if (maxCol < *refLastCol)
2031 *refLastCol = maxCol;
2032
2033 if (minRow > *refLastRow) {
2034 *refFirstRow = *refLastRow;
2035 *refFirstCol = *refLastCol;
2036 } else if (minRow > *refFirstRow)
2037 *refFirstRow = minRow;
2038
2039 if (maxRow < *refFirstRow) {
2040 *refLastRow = *refFirstRow;
2041 *refLastCol = *refFirstCol;
2042 } else if (maxRow < *refLastRow)
2043 *refLastRow = maxRow;
2044 }
2045 }
2046
2047
2048 static int
2049 restrict_code_range_by_str(int count,unsigned short *refFirstCol,
2050 unsigned short *refFirstRow,
2051 unsigned short *refLastCol,
2052 unsigned short *refLastRow,
2053 char const *str)
2054 {
2055 int nRanges = 0;
2056 int result = 0;
2057 fsRange *ranges = NULL, *oldRanges;
2058 char const *p, *q;
2059
2060 p = q = str;
2061 for (;;) {
2062 int minpoint=0, maxpoint=65535;
2063 long val;
2064
2065 /* skip comma and/or space */
2066 while (',' == *p || isspace((unsigned char)*p))
2067 p++;
2068
2069 /* begin point */
2070 if ('-' != *p) {
2071 val = strtol(p, (char **)&q, 0);
2072 if (p == q)
2073 /* end or illegal */
2074 break;
2075 if (val<0 || val>65535) {
2076 /* out of zone */
2077 break;
2078 }
2079 minpoint = val;
2080 p=q;
2081 }
2082
2083 /* skip space */
2084 while (isspace((unsigned char)*p))
2085 p++;
2086
2087 if (',' != *p && '\0' != *p) {
2088 /* contiune */
2089 if ('-' == *p)
2090 /* hyphon */
2091 p++;
2092 else
2093 /* end or illegal */
2094 break;
2095
2096 /* skip space */
2097 while (isspace((unsigned char)*p))
2098 p++;
2099
2100 val = strtol(p, (char **)&q, 0);
2101 if (p != q) {
2102 if (val<0 || val>65535)
2103 break;
2104 maxpoint = val;
2105 } else if (',' != *p && '\0' != *p)
2106 /* end or illegal */
2107 break;
2108 p=q;
2109 } else
2110 /* comma - single code */
2111 maxpoint = minpoint;
2112
2113 if ( count <= 0 && minpoint>maxpoint ) {
2114 int tmp;
2115 tmp = minpoint;
2116 minpoint = maxpoint;
2117 maxpoint = tmp;
2118 }
2119
2120 /* add range */
2121 #if 0
2122 fprintf(stderr, "zone: 0x%04X - 0x%04X\n", minpoint, maxpoint);
2123 fflush(stderr);
2124 #endif
2125 nRanges++;
2126 oldRanges = ranges;
2127 ranges = reallocarray(ranges, nRanges, sizeof(*ranges));
2128 if (NULL == ranges) {
2129 free(oldRanges);
2130 break;
2131 }
2132 else {
2133 fsRange *r = ranges+nRanges-1;
2134
2135 r->min_char_low = minpoint & 0xff;
2136 r->max_char_low = maxpoint & 0xff;
2137 r->min_char_high = (minpoint>>8) & 0xff;
2138 r->max_char_high = (maxpoint>>8) & 0xff;
2139 }
2140 }
2141
2142 if (ranges) {
2143 if ( count <= 0 ) {
2144 restrict_code_range(refFirstCol, refFirstRow, refLastCol, refLastRow,
2145 ranges, nRanges);
2146 }
2147 else {
2148 int i;
2149 fsRange *r;
2150 for ( i=0 ; i<nRanges ; i++ ) {
2151 if ( count <= i ) break;
2152 r = ranges+i;
2153 refFirstCol[i] = r->min_char_low;
2154 refLastCol[i] = r->max_char_low;
2155 refFirstRow[i] = r->min_char_high;
2156 refLastRow[i] = r->max_char_high;
2157 }
2158 result=i;
2159 }
2160 free(ranges);
2161 }
2162 return result;
2163 }
2164
2165 /* *face_number and *spacing are initialized but *load_flags is NOT. */
2166 static int
2167 FreeTypeSetUpTTCap( char *fileName, FontScalablePtr vals,
2168 char **dynStrRealFileName, char **dynStrFTFileName,
2169 struct TTCapInfo *ret, int *face_number, FT_Int32 *load_flags,
2170 int *spacing, Bool *font_properties, char **dynStrTTCapCodeRange )
2171 {
2172 int result = Successful;
2173 SDynPropRecValList listPropRecVal;
2174 SPropRecValContainer contRecValue;
2175 Bool hinting=True;
2176 Bool isEmbeddedBitmap = True;
2177 Bool alwaysEmbeddedBitmap = False;
2178 int pixel = vals->pixel;
2179
2180 *font_properties=True;
2181 *dynStrRealFileName=NULL;
2182 *dynStrFTFileName=NULL;
2183 *dynStrTTCapCodeRange=NULL;
2184
2185 if (SPropRecValList_new(&listPropRecVal)) {
2186 return AllocError;
2187 }
2188
2189 {
2190 int len = strlen(fileName);
2191 char *capHead = NULL;
2192 {
2193 /* font cap */
2194 char *p1=NULL, *p2=NULL;
2195
2196 p1=strrchr(fileName, '/');
2197 if ( p1 == NULL ) p1 = fileName;
2198 else p1++;
2199 if (NULL != (p2=strrchr(p1, ':'))) {
2200 /* colon exist in the right side of slash. */
2201 int dirLen = p1-fileName;
2202 int baseLen = fileName+len - p2 -1;
2203 int fullLen = dirLen+baseLen+1;
2204
2205 *dynStrRealFileName = malloc(fullLen);
2206 if( *dynStrRealFileName == NULL ) {
2207 result = AllocError;
2208 goto quit;
2209 }
2210 if ( 0 < dirLen )
2211 memcpy(*dynStrRealFileName, fileName, dirLen);
2212 strlcpy(*dynStrRealFileName+dirLen, p2+1, fullLen - dirLen);
2213 capHead = p1;
2214 } else {
2215 *dynStrRealFileName = strdup(fileName);
2216 if( *dynStrRealFileName == NULL ) {
2217 result = AllocError;
2218 goto quit;
2219 }
2220 }
2221 }
2222
2223 /* font cap */
2224 if (capHead) {
2225 if (SPropRecValList_add_by_font_cap(&listPropRecVal,
2226 capHead)) {
2227 result = BadFontPath;
2228 goto quit;
2229 }
2230 }
2231 }
2232
2233 *face_number=0;
2234 *spacing=0;
2235 ret->autoItalic=0.0;
2236 ret->scaleWidth=1.0;
2237 ret->scaleBBoxWidth = 1.0;
2238 ret->scaleBBoxHeight = 1.0;
2239 ret->doubleStrikeShift = 1;
2240 ret->adjustBBoxWidthByPixel = 0;
2241 ret->adjustLeftSideBearingByPixel = 0;
2242 ret->adjustRightSideBearingByPixel = 0;
2243 ret->flags = 0;
2244 ret->scaleBitmap = 0.0;
2245 ret->forceConstantSpacingBegin = -1;
2246 ret->forceConstantSpacingEnd = -1;
2247 ret->force_c_representative_metrics_char_code = -2;
2248 ret->force_c_scale_b_box_width = 1.0;
2249 ret->force_c_scale_b_box_height = 1.0;
2250 ret->force_c_adjust_width_by_pixel = 0;
2251 ret->force_c_adjust_lsb_by_pixel = 0;
2252 ret->force_c_adjust_rsb_by_pixel = 0;
2253 ret->force_c_scale_lsb = 0.0;
2254 ret->force_c_scale_rsb = 1.0;
2255 /* */
2256 ret->vl_slant=0;
2257 ret->lsbShiftOfBitmapAutoItalic=0;
2258 ret->rsbShiftOfBitmapAutoItalic=0;
2259 /* face number */
2260 {
2261 char *beginptr=NULL,*endptr;
2262 if ( SPropRecValList_search_record(&listPropRecVal,
2263 &contRecValue,
2264 "FaceNumber")) {
2265 int lv;
2266 beginptr = SPropContainer_value_str(contRecValue);
2267 lv=strtol(beginptr, &endptr, 10);
2268 if ( *beginptr != '\0' && *endptr == '\0' ) {
2269 if ( 0 < lv ) *face_number = lv;
2270 }
2271 }
2272 if( beginptr && 0 < *face_number ) {
2273 char *slash;
2274 size_t dsftlen = /* add -> ':'+strlen0+':'+strlen1+'\0' */
2275 1 + strlen(beginptr) + 1 + strlen(*dynStrRealFileName) + 1;
2276 *dynStrFTFileName = malloc(dsftlen);
2277 if( *dynStrFTFileName == NULL ){
2278 result = AllocError;
2279 goto quit;
2280 }
2281 **dynStrFTFileName = '\0';
2282 slash = strrchr(*dynStrRealFileName,'/');
2283 if( slash ) {
2284 char *p;
2285 strlcat(*dynStrFTFileName, *dynStrRealFileName, dsftlen);
2286 p = strrchr(*dynStrFTFileName,'/');
2287 p[1] = '\0';
2288 strlcat(*dynStrFTFileName, ":", dsftlen);
2289 strlcat(*dynStrFTFileName, beginptr, dsftlen);
2290 strlcat(*dynStrFTFileName, ":", dsftlen);
2291 strlcat(*dynStrFTFileName, slash+1, dsftlen);
2292 }
2293 else{
2294 strlcat(*dynStrFTFileName, ":", dsftlen);
2295 strlcat(*dynStrFTFileName, beginptr, dsftlen);
2296 strlcat(*dynStrFTFileName, ":", dsftlen);
2297 strlcat(*dynStrFTFileName, *dynStrRealFileName, dsftlen);
2298 }
2299 }
2300 else{
2301 *dynStrFTFileName = strdup(*dynStrRealFileName);
2302 if( *dynStrFTFileName == NULL ){
2303 result = AllocError;
2304 goto quit;
2305 }
2306 }
2307 }
2308 /*
2309 fprintf(stderr,"[Filename:%s]\n",fileName);
2310 fprintf(stderr,"[RealFilename:%s]\n",*dynStrRealFileName);
2311 fprintf(stderr,"[FTFilename:%s]\n",*dynStrFTFileName);
2312 */
2313 /* slant control */
2314 if (SPropRecValList_search_record(&listPropRecVal,
2315 &contRecValue,
2316 "AutoItalic"))
2317 ret->autoItalic = SPropContainer_value_dbl(contRecValue);
2318 /* hinting control */
2319 if (SPropRecValList_search_record(&listPropRecVal,
2320 &contRecValue,
2321 "Hinting"))
2322 hinting = SPropContainer_value_bool(contRecValue);
2323 /* scaling */
2324 if (SPropRecValList_search_record(&listPropRecVal,
2325 &contRecValue,
2326 "ScaleWidth")) {
2327 ret->scaleWidth = SPropContainer_value_dbl(contRecValue);
2328 if (ret->scaleWidth<=0.0) {
2329 fprintf(stderr, "ScaleWitdh needs plus.\n");
2330 result = BadFontName;
2331 goto quit;
2332 }
2333 }
2334 /* bbox adjustment */
2335 if (SPropRecValList_search_record(&listPropRecVal,
2336 &contRecValue,
2337 "ScaleBBoxWidth")) {
2338 /* Scaling to Bounding Box Width */
2339 int lv;
2340 char *endptr,*beginptr;
2341 double v,scaleBBoxWidth=1.0,scaleBBoxHeight=1.0;
2342 beginptr = SPropContainer_value_str(contRecValue);
2343 do {
2344 if ( strlen(beginptr) < 1 ) break;
2345 v=strtod(beginptr, &endptr);
2346 if ( endptr!=beginptr ) {
2347 scaleBBoxWidth = v;
2348 }
2349 if ( *endptr != ';' && *endptr != ',' ) break;
2350 if ( *endptr == ',' ) {
2351 beginptr=endptr+1;
2352 v=strtod(beginptr, &endptr);
2353 if ( endptr!=beginptr ) {
2354 scaleBBoxHeight = v;
2355 }
2356 }
2357 if ( *endptr != ';' && *endptr != ',' ) break;
2358 beginptr=endptr+1;
2359 lv=strtol(beginptr, &endptr, 10);
2360 if ( endptr!=beginptr ) {
2361 ret->adjustBBoxWidthByPixel = lv;
2362 }
2363 if ( *endptr != ',' ) break;
2364 beginptr=endptr+1;
2365 lv=strtol(beginptr, &endptr, 10);
2366 if ( endptr!=beginptr ) {
2367 ret->adjustLeftSideBearingByPixel = lv;
2368 }
2369 if ( *endptr != ',' ) break;
2370 beginptr=endptr+1;
2371 lv=strtol(beginptr, &endptr, 10);
2372 if ( endptr!=beginptr ) {
2373 ret->adjustRightSideBearingByPixel = lv;
2374 }
2375 } while ( 0 );
2376 if (scaleBBoxWidth<=0.0) {
2377 fprintf(stderr, "ScaleBBoxWitdh needs plus.\n");
2378 result = BadFontName;
2379 goto quit;
2380 }
2381 if (scaleBBoxHeight<=0.0) {
2382 fprintf(stderr, "ScaleBBoxHeight needs plus.\n");
2383 result = BadFontName;
2384 goto quit;
2385 }
2386 ret->scaleBBoxWidth = scaleBBoxWidth;
2387 ret->scaleBBoxHeight = scaleBBoxHeight;
2388 }
2389 /* spacing */
2390 if (SPropRecValList_search_record(&listPropRecVal,
2391 &contRecValue,
2392 "ForceSpacing")) {
2393 char *strSpace = SPropContainer_value_str(contRecValue);
2394 Bool err = False;
2395 if (1 != strlen(strSpace))
2396 err = True;
2397 else
2398 switch (strSpace[0]) {
2399 case 'M':
2400 ret->flags |= TTCAP_MONO_CENTER;
2401 *spacing = 'm';
2402 break;
2403 case 'm':
2404 case 'p':
2405 case 'c':
2406 *spacing = strSpace[0];
2407 break;
2408 default:
2409 err = True;
2410 }
2411 if (err) {
2412 result = BadFontName;
2413 goto quit;
2414 }
2415 }
2416 /* double striking */
2417 if (SPropRecValList_search_record(&listPropRecVal,
2418 &contRecValue,
2419 "DoubleStrike")) {
2420 /* Set or Reset Auto Bold Flag */
2421 char *strDoubleStrike = SPropContainer_value_str(contRecValue);
2422 Bool err = False;
2423 if ( 0 < strlen(strDoubleStrike) ) {
2424 switch (strDoubleStrike[0]) {
2425 case 'm':
2426 case 'M':
2427 case 'l':
2428 case 'L':
2429 ret->flags |= TTCAP_DOUBLE_STRIKE;
2430 ret->flags |= TTCAP_DOUBLE_STRIKE_MKBOLD_EDGE_LEFT;
2431 break;
2432 case 'y':
2433 case 'Y':
2434 ret->flags |= TTCAP_DOUBLE_STRIKE;
2435 break;
2436 case 'n':
2437 case 'N':
2438 ret->flags &= ~TTCAP_DOUBLE_STRIKE;
2439 ret->flags &= ~TTCAP_DOUBLE_STRIKE_MKBOLD_EDGE_LEFT;
2440 ret->flags &= ~TTCAP_DOUBLE_STRIKE_CORRECT_B_BOX_WIDTH;
2441 break;
2442 default:
2443 err = True;
2444 }
2445 if ( err != True ) {
2446 if ( strDoubleStrike[1] ) {
2447 switch (strDoubleStrike[1]) {
2448 case 'b':
2449 case 'B':
2450 case 'p':
2451 case 'P':
2452 case 'y':
2453 case 'Y':
2454 ret->flags |= TTCAP_DOUBLE_STRIKE_CORRECT_B_BOX_WIDTH;
2455 break;
2456 default:
2457 break;
2458 }
2459 }
2460 do {
2461 char *comma_ptr=strchr(strDoubleStrike,';');
2462 if ( !comma_ptr ) comma_ptr=strchr(strDoubleStrike,',');
2463 if ( !comma_ptr ) break;
2464 if ( comma_ptr[1] ) {
2465 char *endptr;
2466 int mkboldMaxPixel;
2467 mkboldMaxPixel=strtol(comma_ptr+1, &endptr, 10);
2468 if ( endptr != comma_ptr+1 && mkboldMaxPixel <= pixel ) {
2469 ret->flags &= ~TTCAP_DOUBLE_STRIKE_MKBOLD_EDGE_LEFT;
2470 }
2471 }
2472 comma_ptr=strchr(comma_ptr+1,',');
2473 if ( !comma_ptr ) break;
2474 if ( comma_ptr[1] ) {
2475 char *endptr;
2476 int max_pixel;
2477 max_pixel=strtol(comma_ptr+1, &endptr, 10);
2478 if ( endptr != comma_ptr+1 && max_pixel <= pixel ) {
2479 if( ret->flags & TTCAP_DOUBLE_STRIKE )
2480 ret->doubleStrikeShift += pixel / max_pixel;
2481 }
2482 }
2483 } while(0);
2484 }
2485 }
2486 else
2487 err = True;
2488 if (err) {
2489 result = BadFontName;
2490 goto quit;
2491 }
2492 }
2493 /* very lazy metrics */
2494 if (SPropRecValList_search_record(&listPropRecVal,
2495 &contRecValue,
2496 "VeryLazyMetrics")){
2497 Bool isVeryLazy = SPropContainer_value_bool(contRecValue);
2498 ret->flags |= TTCAP_DISABLE_DEFAULT_VERY_LAZY;
2499 if( isVeryLazy == True )
2500 ret->flags |= TTCAP_IS_VERY_LAZY;
2501 else
2502 ret->flags &= ~TTCAP_IS_VERY_LAZY;
2503 }
2504 /* embedded bitmap */
2505 if (SPropRecValList_search_record(&listPropRecVal,
2506 &contRecValue,
2507 "EmbeddedBitmap")) {
2508 char *strEmbeddedBitmap = SPropContainer_value_str(contRecValue);
2509 Bool err = False;
2510 if ( 1 == strlen(strEmbeddedBitmap) ) {
2511 switch (strEmbeddedBitmap[0]) {
2512 case 'y':
2513 case 'Y':
2514 isEmbeddedBitmap = True;
2515 alwaysEmbeddedBitmap = True;
2516 break;
2517 case 'u':
2518 case 'U':
2519 isEmbeddedBitmap = True;
2520 alwaysEmbeddedBitmap = False;
2521 break;
2522 case 'n':
2523 case 'N':
2524 isEmbeddedBitmap = False;
2525 break;
2526 default:
2527 err = True;
2528 }
2529 }
2530 else
2531 err = True;
2532 if (err) {
2533 result = BadFontName;
2534 goto quit;
2535 }
2536 }
2537 /* scale bitmap */
2538 if((ret->flags & TTCAP_IS_VERY_LAZY) &&
2539 SPropRecValList_search_record(&listPropRecVal,
2540 &contRecValue,
2541 "VeryLazyBitmapWidthScale")) {
2542 /* Scaling to Bitmap Bounding Box Width */
2543 double scaleBitmapWidth = SPropContainer_value_dbl(contRecValue);
2544
2545 fprintf(stderr, "Warning: `bs' option is not required in X-TT version 2.\n");
2546 #if 0
2547 if (scaleBitmapWidth<=0.0) {
2548 fprintf(stderr, "ScaleBitmapWitdh needs plus.\n");
2549 result = BadFontName;
2550 goto quit;
2551 }
2552 #endif
2553 ret->scaleBitmap = scaleBitmapWidth;
2554 }
2555 /* restriction of the code range */
2556 if (SPropRecValList_search_record(&listPropRecVal,
2557 &contRecValue,
2558 "CodeRange")) {
2559 *dynStrTTCapCodeRange = strdup(SPropContainer_value_str(contRecValue));
2560 if( *dynStrTTCapCodeRange == NULL ) {
2561 result = AllocError;
2562 goto quit;
2563 }
2564 }
2565 /* forceConstantSpacing{Begin,End} */
2566 if ( 1 /* ft->spacing == 'p' */ ){
2567 unsigned short first_col=0,last_col=0x00ff;
2568 unsigned short first_row=0,last_row=0x00ff;
2569 if (SPropRecValList_search_record(&listPropRecVal,
2570 &contRecValue,
2571 "ForceConstantSpacingCodeRange")) {
2572 if ( restrict_code_range_by_str(1,&first_col, &first_row,
2573 &last_col, &last_row,
2574 SPropContainer_value_str(contRecValue)) == 1 ) {
2575 ret->forceConstantSpacingBegin = (int)( first_row<<8 | first_col );
2576 ret->forceConstantSpacingEnd = (int)( last_row<<8 | last_col );
2577 if ( ret->forceConstantSpacingBegin <= ret->forceConstantSpacingEnd )
2578 ret->flags &= ~TTCAP_FORCE_C_OUTSIDE;
2579 else ret->flags |= TTCAP_FORCE_C_OUTSIDE;
2580 }
2581 }
2582 }
2583 /* */
2584 if ( 1 ){
2585 unsigned short first_col=0, last_col=0x0ff;
2586 unsigned short first_row=0, last_row=0x0ff;
2587 if ( SPropRecValList_search_record(&listPropRecVal,
2588 &contRecValue,
2589 "ForceConstantSpacingMetrics")) {
2590 char *strMetrics;
2591 strMetrics = SPropContainer_value_str(contRecValue);
2592 if ( strMetrics ) {
2593 char *comma_ptr,*period_ptr,*semic_ptr;
2594 semic_ptr=strchr(strMetrics,';');
2595 comma_ptr=strchr(strMetrics,',');
2596 period_ptr=strchr(strMetrics,'.');
2597 if ( semic_ptr && comma_ptr )
2598 if ( semic_ptr < comma_ptr ) comma_ptr=NULL;
2599 if ( semic_ptr && period_ptr )
2600 if ( semic_ptr < period_ptr ) period_ptr=NULL;
2601 if ( !comma_ptr && !period_ptr && strMetrics != semic_ptr ) {
2602 if ( restrict_code_range_by_str(1,&first_col, &first_row,
2603 &last_col, &last_row,
2604 SPropContainer_value_str(contRecValue)) == 1 ) {
2605 ret->force_c_representative_metrics_char_code =
2606 (int)( first_row<<8 | first_col );
2607 }
2608 }
2609 else {
2610 double v;
2611 char *endptr,*beginptr=strMetrics;
2612 do {
2613 v=strtod(beginptr, &endptr);
2614 if ( endptr!=beginptr ) {
2615 ret->force_c_scale_b_box_width = v;
2616 }
2617 if ( *endptr != ',' ) break;
2618 beginptr=endptr+1;
2619 v=strtod(beginptr, &endptr);
2620 if ( endptr!=beginptr ) {
2621 ret->force_c_scale_lsb = v;
2622 ret->flags |= TTCAP_FORCE_C_LSB_FLAG;
2623 }
2624 if ( *endptr != ',' ) break;
2625 beginptr=endptr+1;
2626 v=strtod(beginptr, &endptr);
2627 if ( endptr!=beginptr ) {
2628 ret->force_c_scale_rsb = v;
2629 ret->flags |= TTCAP_FORCE_C_RSB_FLAG;
2630 }
2631 if ( *endptr != ',' ) break;
2632 beginptr=endptr+1;
2633 v=strtod(beginptr, &endptr);
2634 if ( endptr!=beginptr ) {
2635 ret->force_c_scale_b_box_height = v;
2636 }
2637 } while (0);
2638 }
2639 if ( semic_ptr ) {
2640 int lv;
2641 char *endptr,*beginptr=semic_ptr+1;
2642 do {
2643 lv=strtol(beginptr, &endptr, 10);
2644 if ( endptr!=beginptr ) {
2645 ret->force_c_adjust_width_by_pixel=lv;
2646 }
2647 if ( *endptr != ',' ) break;
2648 beginptr=endptr+1;
2649 lv=strtol(beginptr, &endptr, 10);
2650 if ( endptr!=beginptr ) {
2651 ret->force_c_adjust_lsb_by_pixel=lv;
2652 }
2653 if ( *endptr != ',' ) break;
2654 beginptr=endptr+1;
2655 lv=strtol(beginptr, &endptr, 10);
2656 if ( endptr!=beginptr ) {
2657 ret->force_c_adjust_rsb_by_pixel=lv;
2658 }
2659 } while (0);
2660 }
2661 }
2662 }
2663 }
2664
2665 if (SPropRecValList_search_record(&listPropRecVal,
2666 &contRecValue,
2667 "FontProperties")) {
2668 /* Set or Reset the Flag of FontProperties */
2669 *font_properties=SPropContainer_value_bool(contRecValue);
2670 }
2671
2672 ret->force_c_scale_b_box_width *= ret->scaleBBoxWidth;
2673 ret->force_c_scale_b_box_height *= ret->scaleBBoxHeight;
2674
2675 ret->force_c_scale_b_box_width *= ret->scaleWidth;
2676 ret->scaleBBoxWidth *= ret->scaleWidth;
2677
2678 ret->force_c_adjust_rsb_by_pixel += ret->adjustRightSideBearingByPixel;
2679 ret->force_c_adjust_lsb_by_pixel += ret->adjustLeftSideBearingByPixel;
2680
2681 /* scaleWidth, scaleBBoxWidth, force_c_scale_b_box_width, force_c_scale_b_box_width */
2682
2683 /* by TTCap */
2684 if( hinting == False ) *load_flags |= FT_LOAD_NO_HINTING;
2685 if( isEmbeddedBitmap == False ) *load_flags |= FT_LOAD_NO_BITMAP;
2686 if( ret->autoItalic != 0 && alwaysEmbeddedBitmap == False )
2687 *load_flags |= FT_LOAD_NO_BITMAP;
2688
2689 quit:
2690 return result;
2691 }
2692
2693 static int
2694 ft_get_trans_from_vals( FontScalablePtr vals, FTNormalisedTransformationPtr trans )
2695 {
2696 /* Compute the transformation matrix. We use floating-point
2697 arithmetic for simplicity */
2698
2699 trans->xres = vals->x;
2700 trans->yres = vals->y;
2701
2702 /* This value cannot be 0. */
2703 trans->scale = hypot(vals->point_matrix[2], vals->point_matrix[3]);
2704 trans->nonIdentity = 0;
2705
2706 /* Try to round stuff. We want approximate zeros to be exact zeros,
2707 and if the elements on the diagonal are approximately equal, we
2708 want them equal. We do this to avoid breaking hinting. */
2709 if(DIFFER(vals->point_matrix[0], vals->point_matrix[3])) {
2710 trans->nonIdentity = 1;
2711 trans->matrix.xx =
2712 (int)((vals->point_matrix[0]*(double)TWO_SIXTEENTH)/trans->scale);
2713 trans->matrix.yy =
2714 (int)((vals->point_matrix[3]*(double)TWO_SIXTEENTH)/trans->scale);
2715 } else {
2716 trans->matrix.xx = trans->matrix.yy =
2717 ((vals->point_matrix[0] + vals->point_matrix[3])/2*
2718 (double)TWO_SIXTEENTH)/trans->scale;
2719 }
2720
2721 if(DIFFER0(vals->point_matrix[1], trans->scale)) {
2722 trans->matrix.yx =
2723 (int)((vals->point_matrix[1]*(double)TWO_SIXTEENTH)/trans->scale);
2724 trans->nonIdentity = 1;
2725 } else
2726 trans->matrix.yx = 0;
2727
2728 if(DIFFER0(vals->point_matrix[2], trans->scale)) {
2729 trans->matrix.xy =
2730 (int)((vals->point_matrix[2]*(double)TWO_SIXTEENTH)/trans->scale);
2731 trans->nonIdentity = 1;
2732 } else
2733 trans->matrix.xy=0;
2734 return 0;
2735 }
2736
2737
2738 static int
2739 is_fixed_width(FT_Face face)
2740 {
2741 PS_FontInfoRec t1info_rec;
2742 int ftrc;
2743
2744 if(FT_IS_FIXED_WIDTH(face)) {
2745 return 1;
2746 }
2747
2748 ftrc = FT_Get_PS_Font_Info(face, &t1info_rec);
2749 if(ftrc == 0 && t1info_rec.is_fixed_pitch) {
2750 return 1;
2751 }
2752
2753 return 0;
2754 }
2755
2756 static int
2757 FreeTypeLoadFont(FTFontPtr font, FontInfoPtr info, FTFacePtr face,
2758 char *FTFileName, FontScalablePtr vals, FontEntryPtr entry,
2759 FontBitmapFormatPtr bmfmt, FT_Int32 load_flags,
2760 struct TTCapInfo *tmp_ttcap, char *dynStrTTCapCodeRange,
2761 int ttcap_spacing )
2762 {
2763 int xrc;
2764 FTNormalisedTransformationRec trans;
2765 int spacing, actual_spacing, zero_code;
2766 long lastCode, firstCode;
2767 TT_Postscript *post;
2768
2769 ft_get_trans_from_vals(vals,&trans);
2770
2771 /* Check for charcell in XLFD */
2772 spacing = FT_PROPORTIONAL;
2773 if(entry->name.ndashes == 14) {
2774 char *p;
2775 int dashes = 0;
2776 for(p = entry->name.name;
2777 p <= entry->name.name + entry->name.length - 2;
2778 p++) {
2779 if(*p == '-') {
2780 dashes++;
2781 if(dashes == 11) {
2782 if(p[1]=='c' && p[2]=='-')
2783 spacing=FT_CHARCELL;
2784 else if(p[1]=='m' && p[2]=='-')
2785 spacing=FT_MONOSPACED;
2786 break;
2787 }
2788 }
2789 }
2790 }
2791 /* by TTCap */
2792 if( ttcap_spacing != 0 ) {
2793 if( ttcap_spacing == 'c' ) spacing=FT_CHARCELL;
2794 else if( ttcap_spacing == 'm' ) spacing=FT_MONOSPACED;
2795 else spacing=FT_PROPORTIONAL;
2796 }
2797
2798 actual_spacing = spacing;
2799 if( spacing == FT_PROPORTIONAL ) {
2800 if( is_fixed_width(face->face) )
2801 actual_spacing = FT_MONOSPACED;
2802 }
2803
2804 if(entry->name.ndashes == 14) {
2805 xrc = FTPickMapping(entry->name.name, entry->name.length, FTFileName,
2806 face->face, &font->mapping);
2807 if (xrc != Successful)
2808 return xrc;
2809 } else {
2810 xrc = FTPickMapping(0, 0, FTFileName,
2811 face->face, &font->mapping);
2812 if (xrc != Successful)
2813 return xrc;
2814 }
2815
2816 font->nranges = vals->nranges;
2817 font->ranges = 0;
2818 if(font->nranges) {
2819 font->ranges = mallocarray(vals->nranges, sizeof(fsRange));
2820 if(font->ranges == NULL)
2821 return AllocError;
2822 memcpy((char*)font->ranges, (char*)vals->ranges,
2823 vals->nranges*sizeof(fsRange));
2824 }
2825
2826 zero_code=-1;
2827 if(info) {
2828 firstCode = 0;
2829 lastCode = 0xFFFFL;
2830 if(!font->mapping.mapping ||
2831 font->mapping.mapping->encoding->row_size == 0) {
2832 /* linear indexing */
2833 lastCode=MIN(lastCode,
2834 font->mapping.mapping ?
2835 font->mapping.mapping->encoding->size-1 :
2836 0xFF);
2837 if(font->mapping.mapping && font->mapping.mapping->encoding->first)
2838 firstCode = font->mapping.mapping->encoding->first;
2839 info->firstRow = firstCode/0x100;
2840 info->lastRow = lastCode/0x100;
2841 info->firstCol =
2842 (info->firstRow || info->lastRow) ? 0 : (firstCode & 0xFF);
2843 info->lastCol = info->lastRow ? 0xFF : (lastCode & 0xFF);
2844 if ( firstCode == 0 ) zero_code=0;
2845 } else {
2846 /* matrix indexing */
2847 info->firstRow = font->mapping.mapping->encoding->first;
2848 info->lastRow = MIN(font->mapping.mapping->encoding->size-1,
2849 lastCode/0x100);
2850 info->firstCol = font->mapping.mapping->encoding->first_col;
2851 info->lastCol = MIN(font->mapping.mapping->encoding->row_size-1,
2852 lastCode<0x100?lastCode:0xFF);
2853 if( info->firstRow == 0 && info->firstCol == 0 ) zero_code=0;
2854 }
2855
2856 /* firstCode and lastCode are not valid in case of a matrix
2857 encoding */
2858
2859 if( dynStrTTCapCodeRange ) {
2860 restrict_code_range_by_str(0,&info->firstCol, &info->firstRow,
2861 &info->lastCol, &info->lastRow,
2862 dynStrTTCapCodeRange);
2863 }
2864 restrict_code_range(&info->firstCol, &info->firstRow,
2865 &info->lastCol, &info->lastRow,
2866 font->ranges, font->nranges);
2867 }
2868 font->info = info;
2869
2870 /* zero code is frequently used. */
2871 if ( zero_code < 0 ) {
2872 /* The fontenc should have the information of DefaultCh.
2873 But we do not have such a information.
2874 So we cannot but set 0. */
2875 font->zero_idx = 0;
2876 }
2877 else
2878 font->zero_idx = FTRemap(face->face,
2879 &font->mapping, zero_code);
2880
2881 post = FT_Get_Sfnt_Table(face->face, ft_sfnt_post);
2882
2883 #ifdef DEFAULT_VERY_LAZY
2884 if( !( tmp_ttcap->flags & TTCAP_DISABLE_DEFAULT_VERY_LAZY ) )
2885 if( DEFAULT_VERY_LAZY <= 1 + info->lastRow - info->firstRow ) {
2886 if( post ){
2887 tmp_ttcap->flags |= TTCAP_IS_VERY_LAZY;
2888 }
2889 }
2890 #endif
2891 /* We should always reset. */
2892 tmp_ttcap->flags &= ~TTCAP_DISABLE_DEFAULT_VERY_LAZY;
2893
2894 if ( face->bitmap || actual_spacing == FT_CHARCELL )
2895 tmp_ttcap->flags &= ~TTCAP_IS_VERY_LAZY;
2896 /* "vl=y" is available when TrueType or OpenType only */
2897 if ( !face->bitmap && !(FT_IS_SFNT( face->face )) )
2898 tmp_ttcap->flags &= ~TTCAP_IS_VERY_LAZY;
2899
2900 if( post ) {
2901 if( post->italicAngle != 0 )
2902 tmp_ttcap->vl_slant = -sin( (post->italicAngle/1024./5760.)*1.57079632679489661923 );
2903 /* fprintf(stderr,"angle=%g(%g)\n",tmp_ttcap->vl_slant,(post->italicAngle/1024./5760.)*90); */
2904 }
2905
2906 xrc = FreeTypeOpenInstance(&font->instance, face,
2907 FTFileName, &trans, actual_spacing, bmfmt,
2908 tmp_ttcap, load_flags );
2909 return xrc;
2910 }
2911
2912 static void
2913 adjust_min_max(xCharInfo *minc, xCharInfo *maxc, xCharInfo *tmp)
2914 {
2915 #define MINMAX(field,ci) \
2916 if (minc->field > (ci)->field) \
2917 minc->field = (ci)->field; \
2918 if (maxc->field < (ci)->field) \
2919 maxc->field = (ci)->field;
2920
2921 MINMAX(ascent, tmp);
2922 MINMAX(descent, tmp);
2923 MINMAX(leftSideBearing, tmp);
2924 MINMAX(rightSideBearing, tmp);
2925 MINMAX(characterWidth, tmp);
2926
2927 if ((INT16)minc->attributes > (INT16)tmp->attributes)
2928 minc->attributes = tmp->attributes;
2929 if ((INT16)maxc->attributes < (INT16)tmp->attributes)
2930 maxc->attributes = tmp->attributes;
2931 #undef MINMAX
2932 }
2933
2934 static void
2935 ft_compute_bounds(FTFontPtr font, FontInfoPtr pinfo, FontScalablePtr vals )
2936 {
2937 FTInstancePtr instance;
2938 int row, col;
2939 unsigned int c;
2940 xCharInfo minchar, maxchar, *tmpchar = NULL;
2941 int overlap, maxOverlap;
2942 long swidth = 0;
2943 long total_width = 0;
2944 int num_cols, num_chars = 0;
2945 int flags, skip_ok = 0;
2946 int force_c_outside ;
2947
2948 instance = font->instance;
2949 force_c_outside = instance->ttcap.flags & TTCAP_FORCE_C_OUTSIDE;
2950
2951 minchar.ascent = minchar.descent =
2952 minchar.leftSideBearing = minchar.rightSideBearing =
2953 minchar.characterWidth = minchar.attributes = 32767;
2954 maxchar.ascent = maxchar.descent =
2955 maxchar.leftSideBearing = maxchar.rightSideBearing =
2956 maxchar.characterWidth = maxchar.attributes = -32767;
2957 maxOverlap = -32767;
2958
2959 /* Parse all glyphs */
2960 num_cols = 1 + pinfo->lastCol - pinfo->firstCol;
2961 for (row = pinfo->firstRow; row <= pinfo->lastRow; row++) {
2962 if ( skip_ok && tmpchar ) {
2963 if ( !force_c_outside ) {
2964 if ( instance->ttcap.forceConstantSpacingBegin < row<<8
2965 && row<<8 < (instance->ttcap.forceConstantSpacingEnd & 0x0ff00) ) {
2966 if (tmpchar->characterWidth) {
2967 num_chars += num_cols;
2968 swidth += ABS(tmpchar->characterWidth)*num_cols;
2969 total_width += tmpchar->characterWidth*num_cols;
2970 continue;
2971 }
2972 }
2973 else skip_ok=0;
2974 }
2975 else { /* for GB18030 proportional */
2976 if ( instance->ttcap.forceConstantSpacingBegin < row<<8
2977 || row<<8 < (instance->ttcap.forceConstantSpacingEnd & 0x0ff00) ) {
2978 if (tmpchar->characterWidth) {
2979 num_chars += num_cols;
2980 swidth += ABS(tmpchar->characterWidth)*num_cols;
2981 total_width += tmpchar->characterWidth*num_cols;
2982 continue;
2983 }
2984 }
2985 else skip_ok=0;
2986 }
2987 }
2988 for (col = pinfo->firstCol; col <= pinfo->lastCol; col++) {
2989 c = row<<8|col;
2990 flags=0;
2991 if ( !force_c_outside ) {
2992 if ( (signed) c <= instance->ttcap.forceConstantSpacingEnd
2993 && instance->ttcap.forceConstantSpacingBegin <= (signed) c )
2994 flags|=FT_FORCE_CONSTANT_SPACING;
2995 }
2996 else { /* for GB18030 proportional */
2997 if ( (signed) c <= instance->ttcap.forceConstantSpacingEnd
2998 || instance->ttcap.forceConstantSpacingBegin <= (signed) c )
2999 flags|=FT_FORCE_CONSTANT_SPACING;
3000 }
3001 #if 0
3002 fprintf(stderr, "comp_bounds: %x ->", c);
3003 #endif
3004 if ( skip_ok == 0 || flags == 0 ){
3005 tmpchar=NULL;
3006 #if 0
3007 fprintf(stderr, "%x\n", c);
3008 #endif
3009 if( FreeTypeFontGetGlyphMetrics(c, flags, &tmpchar, font) != Successful )
3010 continue;
3011 }
3012 if ( !tmpchar ) continue;
3013 adjust_min_max(&minchar, &maxchar, tmpchar);
3014 overlap = tmpchar->rightSideBearing - tmpchar->characterWidth;
3015 if (maxOverlap < overlap)
3016 maxOverlap = overlap;
3017
3018 if (!tmpchar->characterWidth)
3019 continue;
3020 num_chars++;
3021 swidth += ABS(tmpchar->characterWidth);
3022 total_width += tmpchar->characterWidth;
3023
3024 if ( flags & FT_FORCE_CONSTANT_SPACING ) skip_ok=1;
3025 }
3026 }
3027
3028 #ifndef X_ACCEPTS_NO_SUCH_CHAR
3029 /* Check code 0 */
3030 if( FreeTypeInstanceGetGlyphMetrics(font->zero_idx, 0, &tmpchar, font->instance) != Successful || tmpchar == NULL)
3031 if( FreeTypeInstanceGetGlyphMetrics(font->zero_idx, FT_GET_DUMMY, &tmpchar, font->instance) != Successful )
3032 tmpchar = NULL;
3033 if ( tmpchar ) {
3034 adjust_min_max(&minchar, &maxchar, tmpchar);
3035 overlap = tmpchar->rightSideBearing - tmpchar->characterWidth;
3036 if (maxOverlap < overlap)
3037 maxOverlap = overlap;
3038 }
3039 #endif
3040
3041 /* AVERAGE_WIDTH ... 1/10 pixel unit */
3042 if (num_chars > 0) {
3043 swidth = (swidth * 10.0 + num_chars / 2.0) / num_chars;
3044 if (total_width < 0)
3045 swidth = -swidth;
3046 vals->width = swidth;
3047 } else
3048 vals->width = 0;
3049
3050 /*
3051 if (char_width.pixel) {
3052 maxchar.characterWidth = char_width.pixel;
3053 minchar.characterWidth = char_width.pixel;
3054 }
3055 */
3056
3057 pinfo->maxbounds = maxchar;
3058 pinfo->minbounds = minchar;
3059 pinfo->ink_maxbounds = maxchar;
3060 pinfo->ink_minbounds = minchar;
3061 pinfo->maxOverlap = maxOverlap;
3062 }
3063
3064 static int
3065 compute_new_extents( FontScalablePtr vals, double scale, double lsb, double rsb, double desc, double asc,
3066 int *lsb_result, int *rsb_result, int *desc_result, int *asc_result )
3067 {
3068 #define TRANSFORM_POINT(matrix, x, y, dest) \
3069 ((dest)[0] = (matrix)[0] * (x) + (matrix)[2] * (y), \
3070 (dest)[1] = (matrix)[1] * (x) + (matrix)[3] * (y))
3071
3072 #define CHECK_EXTENT(lsb, rsb, desc, asc, data) \
3073 ((lsb) > (data)[0] ? (lsb) = (data)[0] : 0 , \
3074 (rsb) < (data)[0] ? (rsb) = (data)[0] : 0, \
3075 (-desc) > (data)[1] ? (desc) = -(data)[1] : 0 , \
3076 (asc) < (data)[1] ? (asc) = (data)[1] : 0)
3077 double newlsb, newrsb, newdesc, newasc;
3078 double point[2];
3079
3080 /* Compute new extents for this glyph */
3081 TRANSFORM_POINT(vals->pixel_matrix, lsb, -desc, point);
3082 newlsb = point[0];
3083 newrsb = newlsb;
3084 newdesc = -point[1];
3085 newasc = -newdesc;
3086 TRANSFORM_POINT(vals->pixel_matrix, lsb, asc, point);
3087 CHECK_EXTENT(newlsb, newrsb, newdesc, newasc, point);
3088 TRANSFORM_POINT(vals->pixel_matrix, rsb, -desc, point);
3089 CHECK_EXTENT(newlsb, newrsb, newdesc, newasc, point);
3090 TRANSFORM_POINT(vals->pixel_matrix, rsb, asc, point);
3091 CHECK_EXTENT(newlsb, newrsb, newdesc, newasc, point);
3092
3093 /* ???: lsb = (int)floor(newlsb * scale); */
3094 *lsb_result = (int)floor(newlsb * scale + 0.5);
3095 *rsb_result = (int)floor(newrsb * scale + 0.5);
3096 *desc_result = (int)ceil(newdesc * scale - 0.5);
3097 *asc_result = (int)floor(newasc * scale + 0.5);
3098
3099 return 0;
3100 #undef CHECK_EXTENT
3101 #undef TRANSFORM_POINT
3102 }
3103
3104 static int
3105 is_matrix_unit(FontScalablePtr vals)
3106 {
3107 double base_size;
3108 FT_Matrix m;
3109
3110 base_size = hypot(vals->point_matrix[2], vals->point_matrix[3]);
3111
3112 m.xx = vals->point_matrix[0] / base_size * 65536;
3113 m.xy = vals->point_matrix[2] / base_size * 65536;
3114 m.yx = vals->point_matrix[1] / base_size * 65536;
3115 m.yy = vals->point_matrix[3] / base_size * 65536;
3116
3117 return (m.xx == 65536) && (m.yx == 0) &&
3118 (m.xy == 0) && (m.yy == 65536);
3119 }
3120
3121 /* Do all the real work for OpenFont or FontInfo */
3122 /* xf->info is only accessed through info, and xf might be null */
3123
3124 static int
3125 FreeTypeLoadXFont(char *fileName,
3126 FontScalablePtr vals, FontPtr xf, FontInfoPtr info,
3127 FontBitmapFormatPtr bmfmt, FontEntryPtr entry)
3128 {
3129 FTFontPtr font = NULL;
3130 FTFacePtr face = NULL;
3131 FTInstancePtr instance;
3132 FT_Size_Metrics *smetrics;
3133 int xrc=Successful;
3134 int charcell;
3135 long rawWidth = 0, rawAverageWidth = 0;
3136 int upm, minLsb, maxRsb, ascent, descent, width, averageWidth;
3137 double scale, base_width, base_height;
3138 Bool orig_is_matrix_unit, font_properties;
3139 int face_number, ttcap_spacing;
3140 struct TTCapInfo tmp_ttcap;
3141 struct TTCapInfo *ins_ttcap;
3142 FT_Int32 load_flags = FT_LOAD_DEFAULT; /* orig: FT_LOAD_RENDER | FT_LOAD_MONOCHROME */
3143 char *dynStrRealFileName = NULL; /* foo.ttc */
3144 char *dynStrFTFileName = NULL; /* :1:foo.ttc */
3145 char *dynStrTTCapCodeRange = NULL;
3146
3147 font = calloc(1, sizeof(FTFontRec));
3148 if(font == NULL) {
3149 xrc = AllocError;
3150 goto quit;
3151 }
3152
3153 xrc = FreeTypeSetUpTTCap(fileName, vals,
3154 &dynStrRealFileName, &dynStrFTFileName,
3155 &tmp_ttcap, &face_number,
3156 &load_flags, &ttcap_spacing,
3157 &font_properties, &dynStrTTCapCodeRange);
3158 if ( xrc != Successful ) {
3159 goto quit;
3160 }
3161
3162 xrc = FreeTypeOpenFace(&face, dynStrFTFileName, dynStrRealFileName, face_number);
3163 if(xrc != Successful) {
3164 goto quit;
3165 }
3166
3167 if( is_matrix_unit(vals) )
3168 orig_is_matrix_unit = True;
3169 else {
3170 orig_is_matrix_unit = False;
3171 /* Turn off EmbeddedBitmap when original matrix is not diagonal. */
3172 load_flags |= FT_LOAD_NO_BITMAP;
3173 }
3174
3175 if( face->bitmap ) load_flags &= ~FT_LOAD_NO_BITMAP;
3176
3177 /* Slant control by TTCap */
3178 if(!face->bitmap) {
3179 vals->pixel_matrix[2] +=
3180 vals->pixel_matrix[0] * tmp_ttcap.autoItalic;
3181 vals->point_matrix[2] +=
3182 vals->point_matrix[0] * tmp_ttcap.autoItalic;
3183 vals->pixel_matrix[3] +=
3184 vals->pixel_matrix[1] * tmp_ttcap.autoItalic;
3185 vals->point_matrix[3] +=
3186 vals->point_matrix[1] * tmp_ttcap.autoItalic;
3187 }
3188
3189 base_width=hypot(vals->pixel_matrix[0], vals->pixel_matrix[1]);
3190 base_height=hypot(vals->pixel_matrix[2], vals->pixel_matrix[3]);
3191 if(MAX(base_width, base_height) < 1.0 ) {
3192 xrc = BadFontName;
3193 goto quit;
3194 }
3195
3196 xrc = FreeTypeLoadFont(font, info, face, dynStrFTFileName, vals, entry, bmfmt,
3197 load_flags, &tmp_ttcap, dynStrTTCapCodeRange,
3198 ttcap_spacing );
3199 if(xrc != Successful) {
3200 goto quit;
3201 }
3202
3203 instance = font->instance;
3204 smetrics = &instance->size->metrics;
3205 ins_ttcap = &instance->ttcap;
3206
3207 upm = face->face->units_per_EM;
3208 if(upm == 0) {
3209 /* Work around FreeType bug */
3210 upm = WORK_AROUND_UPM;
3211 }
3212 scale = 1.0 / upm;
3213
3214 charcell = (instance->spacing == FT_CHARCELL);
3215
3216 if( instance->charcellMetrics == NULL ) {
3217
3218 /* New instance */
3219
3220 long force_c_rawWidth = 0;
3221 int force_c_lsb,force_c_rsb,force_c_width;
3222 double unit_x=0,unit_y=0,advance;
3223 CharInfoPtr tmpglyph;
3224
3225 /*
3226 * CALCULATE HEADER'S METRICS
3227 */
3228
3229 /* for OUTLINE fonts */
3230 if(!face->bitmap) {
3231 int new_width;
3232 double ratio,force_c_ratio;
3233 double width_x=0,width_y=0;
3234 double force_c_width_x, force_c_rsb_x, force_c_lsb_x;
3235 double tmp_rsb,tmp_lsb,tmp_asc,tmp_des;
3236 double max_advance_height;
3237 tmp_asc = face->face->bbox.yMax;
3238 tmp_des = -(face->face->bbox.yMin);
3239 if ( tmp_asc < face->face->ascender ) tmp_asc = face->face->ascender;
3240 if ( tmp_des < -(face->face->descender) ) tmp_des = -(face->face->descender);
3241 tmp_lsb = face->face->bbox.xMin;
3242 tmp_rsb = face->face->bbox.xMax;
3243 if ( tmp_rsb < face->face->max_advance_width ) tmp_rsb = face->face->max_advance_width;
3244 /* apply scaleBBoxWidth */
3245 /* we should not ...??? */
3246 tmp_lsb *= ins_ttcap->scaleBBoxWidth;
3247 tmp_rsb *= ins_ttcap->scaleBBoxWidth;
3248 /* transform and rescale */
3249 compute_new_extents( vals, scale, tmp_lsb, tmp_rsb, tmp_des, tmp_asc,
3250 &minLsb, &maxRsb, &descent, &ascent );
3251 /* */
3252 /* Consider vertical layouts */
3253 if( 0 < face->face->max_advance_height )
3254 max_advance_height = face->face->max_advance_height;
3255 else
3256 max_advance_height = tmp_asc + tmp_des;
3257 if( vals->pixel_matrix[1] == 0 ){
3258 unit_x = fabs(vals->pixel_matrix[0]);
3259 unit_y = 0;
3260 width_x = face->face->max_advance_width * ins_ttcap->scaleBBoxWidth * unit_x;
3261 }
3262 else if( vals->pixel_matrix[3] == 0 ){
3263 unit_y = fabs(vals->pixel_matrix[2]);
3264 unit_x = 0;
3265 width_x = max_advance_height * ins_ttcap->scaleBBoxHeight * unit_y;
3266 }
3267 else{
3268 unit_x = fabs(vals->pixel_matrix[0] -
3269 vals->pixel_matrix[1]*vals->pixel_matrix[2]/vals->pixel_matrix[3]);
3270 unit_y = fabs(vals->pixel_matrix[2] -
3271 vals->pixel_matrix[3]*vals->pixel_matrix[0]/vals->pixel_matrix[1]);
3272 width_x = face->face->max_advance_width * ins_ttcap->scaleBBoxWidth * unit_x;
3273 width_y = max_advance_height * ins_ttcap->scaleBBoxHeight * unit_y;
3274 if( width_y < width_x ){
3275 width_x = width_y;
3276 unit_x = 0;
3277 }
3278 else{
3279 unit_y = 0;
3280 }
3281 }
3282 /* calculate correction ratio */
3283 width = (int)floor( (advance = width_x * scale) + 0.5);
3284 new_width = width;
3285 if( ins_ttcap->flags & TTCAP_DOUBLE_STRIKE_CORRECT_B_BOX_WIDTH )
3286 new_width += ins_ttcap->doubleStrikeShift;
3287 new_width += ins_ttcap->adjustBBoxWidthByPixel;
3288 ratio = (double)new_width/width;
3289 width = new_width;
3290 /* force constant */
3291 if( unit_x != 0 ) {
3292 force_c_width_x = face->face->max_advance_width
3293 * ins_ttcap->force_c_scale_b_box_width * unit_x;
3294 force_c_lsb_x = face->face->max_advance_width
3295 * ins_ttcap->force_c_scale_lsb * unit_x;
3296 force_c_rsb_x = face->face->max_advance_width
3297 * ins_ttcap->force_c_scale_rsb * unit_x;
3298 }
3299 else {
3300 force_c_width_x = max_advance_height
3301 * ins_ttcap->force_c_scale_b_box_height * unit_y;
3302 force_c_lsb_x = max_advance_height
3303 * ins_ttcap->force_c_scale_lsb * unit_y;
3304 force_c_rsb_x = max_advance_height
3305 * ins_ttcap->force_c_scale_rsb * unit_y;
3306 }
3307 /* calculate correction ratio */
3308 force_c_width = (int)floor(force_c_width_x * scale + 0.5);
3309 new_width = force_c_width;
3310 if( ins_ttcap->flags & TTCAP_DOUBLE_STRIKE_CORRECT_B_BOX_WIDTH )
3311 force_c_width += ins_ttcap->doubleStrikeShift;
3312 new_width += ins_ttcap->force_c_adjust_width_by_pixel;
3313 force_c_ratio = (double)new_width/force_c_width;
3314 force_c_width = new_width;
3315 /* force_c_lsb, force_c_rsb */
3316 if( ins_ttcap->flags & TTCAP_FORCE_C_LSB_FLAG )
3317 force_c_lsb = (int)floor( force_c_lsb_x * scale + 0.5 );
3318 else
3319 force_c_lsb = minLsb;
3320 if( ins_ttcap->flags & TTCAP_FORCE_C_RSB_FLAG )
3321 force_c_rsb = (int)floor( force_c_rsb_x * scale + 0.5 );
3322 else
3323 force_c_rsb = maxRsb;
3324 /* calculate shift of BitmapAutoItalic
3325 (when diagonal matrix only) */
3326 if( orig_is_matrix_unit == True ) {
3327 if( ins_ttcap->autoItalic != 0 ) {
3328 double ai;
3329 int ai_lsb,ai_rsb,ai_total;
3330 if( 0 < ins_ttcap->autoItalic ) ai=ins_ttcap->autoItalic;
3331 else ai = -ins_ttcap->autoItalic;
3332 ai_total = (int)( (ascent+descent) * ai + 0.5);
3333 ai_rsb = (int)((double)ai_total * ascent / ( ascent + descent ) + 0.5 );
3334 ai_lsb = -(ai_total - ai_rsb);
3335 if( 0 < ins_ttcap->autoItalic ) {
3336 ins_ttcap->lsbShiftOfBitmapAutoItalic = ai_lsb;
3337 ins_ttcap->rsbShiftOfBitmapAutoItalic = ai_rsb;
3338 }
3339 else {
3340 ins_ttcap->lsbShiftOfBitmapAutoItalic = -ai_rsb;
3341 ins_ttcap->rsbShiftOfBitmapAutoItalic = -ai_lsb;
3342 }
3343 }
3344 }
3345 /* integer adjustment by TTCap */
3346 if( ins_ttcap->flags & TTCAP_DOUBLE_STRIKE )
3347 maxRsb += ins_ttcap->doubleStrikeShift;
3348 maxRsb += ins_ttcap->adjustRightSideBearingByPixel;
3349 minLsb += ins_ttcap->adjustLeftSideBearingByPixel;
3350 /* */
3351 if( ins_ttcap->flags & TTCAP_DOUBLE_STRIKE )
3352 force_c_rsb += ins_ttcap->doubleStrikeShift;
3353 force_c_rsb += ins_ttcap->force_c_adjust_rsb_by_pixel;
3354 force_c_lsb += ins_ttcap->force_c_adjust_lsb_by_pixel;
3355 /* apply to rawWidth */
3356 averageWidth = (int)floor(10 * width_x * scale
3357 * ratio + 0.5);
3358 rawWidth = floor(width_x * scale
3359 * ratio * 1000. / base_height + 0.5);
3360 rawAverageWidth = floor(width_x * scale * ratio * 10.
3361 * 1000. / base_height + 0.5);
3362 force_c_rawWidth = floor(force_c_width_x * scale
3363 * force_c_ratio * 1000. / base_height + 0.5);
3364 /* */
3365 }
3366 /* for BITMAP fonts [if(face->bitmap)] */
3367 else {
3368 /* These values differ from actual when outline,
3369 so we must use them ONLY FOR BITMAP. */
3370 width = (int)floor(smetrics->max_advance * ins_ttcap->scaleBBoxWidth / 64.0 + .5);
3371 descent = -smetrics->descender / 64;
3372 ascent = smetrics->ascender / 64;
3373 /* force constant */
3374 force_c_width = (int)floor(smetrics->max_advance
3375 * ins_ttcap->force_c_scale_b_box_width / 64.0 + .5);
3376 /* Preserve average width for bitmap fonts */
3377 if(vals->width != 0)
3378 averageWidth = (int)floor(vals->width * ins_ttcap->scaleBBoxWidth +.5);
3379 else
3380 averageWidth = (int)floor(10.0 * smetrics->max_advance
3381 * ins_ttcap->scaleBBoxWidth / 64.0 + .5);
3382 rawWidth = 0;
3383 rawAverageWidth = 0;
3384 force_c_rawWidth = 0;
3385 /* We don't consider vertical layouts */
3386 advance = (int)floor(smetrics->max_advance / 64.0 +.5);
3387 unit_x = vals->pixel_matrix[0];
3388 unit_y = 0;
3389 /* We can use 'width' only when bitmap.
3390 This should not be set when outline. */
3391 minLsb = 0;
3392 maxRsb = width;
3393 /* force constant */
3394 if( ins_ttcap->flags & TTCAP_FORCE_C_LSB_FLAG )
3395 force_c_lsb = (int)floor(smetrics->max_advance
3396 * ins_ttcap->force_c_scale_lsb / 64.0 + .5);
3397 else
3398 force_c_lsb = minLsb;
3399 if( ins_ttcap->flags & TTCAP_FORCE_C_RSB_FLAG )
3400 force_c_rsb = (int)floor(smetrics->max_advance
3401 * ins_ttcap->force_c_scale_rsb / 64.0 + .5);
3402 else
3403 force_c_rsb = maxRsb;
3404 /* calculate shift of BitmapAutoItalic */
3405 if( ins_ttcap->autoItalic != 0 ) {
3406 double ai;
3407 int ai_lsb,ai_rsb,ai_total;
3408 if( 0 < ins_ttcap->autoItalic ) ai=ins_ttcap->autoItalic;
3409 else ai = -ins_ttcap->autoItalic;
3410 ai_total = (int)( (ascent+descent) * ai + 0.5);
3411 ai_rsb = (int)((double)ai_total * ascent / ( ascent + descent ) + 0.5 );
3412 ai_lsb = -(ai_total - ai_rsb);
3413 if( 0 < ins_ttcap->autoItalic ) {
3414 ins_ttcap->lsbShiftOfBitmapAutoItalic = ai_lsb;
3415 ins_ttcap->rsbShiftOfBitmapAutoItalic = ai_rsb;
3416 }
3417 else {
3418 ins_ttcap->lsbShiftOfBitmapAutoItalic = -ai_rsb;
3419 ins_ttcap->rsbShiftOfBitmapAutoItalic = -ai_lsb;
3420 }
3421 }
3422 /* integer adjustment by TTCap */
3423 if( ins_ttcap->flags & TTCAP_DOUBLE_STRIKE_CORRECT_B_BOX_WIDTH )
3424 width += ins_ttcap->doubleStrikeShift;
3425 if( ins_ttcap->flags & TTCAP_DOUBLE_STRIKE )
3426 maxRsb += ins_ttcap->doubleStrikeShift;
3427 maxRsb += ins_ttcap->adjustRightSideBearingByPixel;
3428 minLsb += ins_ttcap->adjustLeftSideBearingByPixel;
3429 /* We have not carried out matrix calculation, so this is done. */
3430 maxRsb += ins_ttcap->rsbShiftOfBitmapAutoItalic;
3431 minLsb += ins_ttcap->lsbShiftOfBitmapAutoItalic;
3432 /* force constant */
3433 if( ins_ttcap->flags & TTCAP_DOUBLE_STRIKE )
3434 force_c_rsb += ins_ttcap->doubleStrikeShift;
3435 force_c_rsb += ins_ttcap->force_c_adjust_rsb_by_pixel;
3436 force_c_lsb += ins_ttcap->force_c_adjust_lsb_by_pixel;
3437 force_c_rsb += ins_ttcap->rsbShiftOfBitmapAutoItalic;
3438 force_c_lsb += ins_ttcap->lsbShiftOfBitmapAutoItalic;
3439 }
3440
3441 /* SET CALCULATED VALUES TO INSTANCE */
3442
3443 /* Set actual height and cosine */
3444 instance->pixel_size = base_height;
3445 instance->advance = advance;
3446 if ( unit_x != 0 ){
3447 instance->pixel_width_unit_x = unit_x/base_height;
3448 instance->pixel_width_unit_y = 0;
3449 }
3450 else{
3451 instance->pixel_width_unit_x = 0;
3452 instance->pixel_width_unit_y = unit_y/base_height;
3453 }
3454
3455 /* header's metrics */
3456 instance->charcellMetrics = malloc(sizeof(xCharInfo));
3457 if(instance->charcellMetrics == NULL) {
3458 xrc = AllocError;
3459 goto quit;
3460 }
3461 instance->charcellMetrics->ascent = ascent;
3462 instance->charcellMetrics->descent = descent;
3463 instance->charcellMetrics->attributes = rawWidth;
3464 instance->charcellMetrics->rightSideBearing = maxRsb;
3465 instance->charcellMetrics->leftSideBearing = minLsb;
3466 instance->charcellMetrics->characterWidth = width;
3467 instance->averageWidth = averageWidth;
3468 instance->rawAverageWidth = rawAverageWidth;
3469
3470 /* Check code 0 */
3471 if( FreeTypeInstanceGetGlyph(font->zero_idx, 0, &tmpglyph, font->instance) != Successful
3472 || tmpglyph == NULL)
3473 if( FreeTypeInstanceGetGlyph(font->zero_idx, FT_GET_DUMMY, &tmpglyph, font->instance)
3474 != Successful )
3475 tmpglyph = NULL;
3476 if ( !tmpglyph ) {
3477 xrc = AllocError;
3478 goto quit;
3479 }
3480
3481 /* FORCE CONSTANT METRICS */
3482 if( 0 <= ins_ttcap->forceConstantSpacingEnd ) {
3483 xCharInfo *tmpchar = NULL;
3484 int c = ins_ttcap->force_c_representative_metrics_char_code;
3485 /* header's metrics */
3486 if( instance->forceConstantMetrics == NULL ){
3487 instance->forceConstantMetrics = malloc(sizeof(xCharInfo));
3488 if(instance->forceConstantMetrics == NULL) {
3489 xrc = AllocError;
3490 goto quit;
3491 }
3492 }
3493 /* Get Representative Metrics */
3494 if ( 0 <= c ) {
3495 if( FreeTypeFontGetGlyphMetrics(c, 0, &tmpchar, font) != Successful )
3496 tmpchar = NULL;
3497 }
3498 if ( tmpchar && 0 < tmpchar->characterWidth ) {
3499 instance->forceConstantMetrics->leftSideBearing = tmpchar->leftSideBearing;
3500 instance->forceConstantMetrics->rightSideBearing = tmpchar->rightSideBearing;
3501 instance->forceConstantMetrics->characterWidth = tmpchar->characterWidth;
3502 instance->forceConstantMetrics->ascent = tmpchar->ascent;
3503 instance->forceConstantMetrics->descent = tmpchar->descent;
3504 instance->forceConstantMetrics->attributes = tmpchar->attributes;
3505 }
3506 else {
3507 instance->forceConstantMetrics->leftSideBearing = force_c_lsb;
3508 instance->forceConstantMetrics->rightSideBearing = force_c_rsb;
3509 instance->forceConstantMetrics->characterWidth = force_c_width;
3510 instance->forceConstantMetrics->ascent = ascent;
3511 instance->forceConstantMetrics->descent = descent;
3512 instance->forceConstantMetrics->attributes = force_c_rawWidth;
3513 }
3514 /* Check code 0 */
3515 if( FreeTypeInstanceGetGlyph(font->zero_idx, FT_FORCE_CONSTANT_SPACING,
3516 &tmpglyph, font->instance) != Successful
3517 || tmpglyph == NULL)
3518 if( FreeTypeInstanceGetGlyph(font->zero_idx, FT_FORCE_CONSTANT_SPACING | FT_GET_DUMMY,
3519 &tmpglyph, font->instance)
3520 != Successful )
3521 tmpglyph = NULL;
3522 if ( !tmpglyph ) {
3523 xrc = AllocError;
3524 goto quit;
3525 }
3526 }
3527 }
3528 else{
3529
3530 /*
3531 * CACHED VALUES
3532 */
3533
3534 width = instance->charcellMetrics->characterWidth;
3535 ascent = instance->charcellMetrics->ascent;
3536 descent = instance->charcellMetrics->descent;
3537 rawWidth = instance->charcellMetrics->attributes;
3538 maxRsb = instance->charcellMetrics->rightSideBearing;
3539 minLsb = instance->charcellMetrics->leftSideBearing;
3540 averageWidth = instance->averageWidth;
3541 rawAverageWidth = instance->rawAverageWidth;
3542
3543 }
3544
3545 /*
3546 * SET maxbounds, minbounds ...
3547 */
3548
3549 if( !charcell ) { /* NOT CHARCELL */
3550 if( info ){
3551 /*
3552 Calculate all glyphs' metrics.
3553 maxbounds.ascent and maxbounds.descent are quite important values
3554 for XAA. If ascent/descent of each glyph exceeds
3555 maxbounds.ascent/maxbounds.descent, XAA causes SERVER CRASH.
3556 Therefore, THIS MUST BE DONE.
3557 */
3558 ft_compute_bounds(font,info,vals);
3559 }
3560 }
3561 else{ /* CHARCELL */
3562
3563 /*
3564 * SET CALCULATED OR CACHED VARIABLES
3565 */
3566
3567 vals->width = averageWidth;
3568
3569 if( info ){
3570
3571 info->maxbounds.leftSideBearing = minLsb;
3572 info->maxbounds.rightSideBearing = maxRsb;
3573 info->maxbounds.characterWidth = width;
3574 info->maxbounds.ascent = ascent;
3575 info->maxbounds.descent = descent;
3576 info->maxbounds.attributes =
3577 (unsigned short)(short)rawWidth;
3578
3579 info->minbounds = info->maxbounds;
3580 }
3581 }
3582
3583 /* set info */
3584
3585 if( info ){
3586 /*
3587 info->fontAscent = ascent;
3588 info->fontDescent = descent;
3589 */
3590 info->fontAscent = info->maxbounds.ascent;
3591 info->fontDescent = info->maxbounds.descent;
3592 /* Glyph metrics are accurate */
3593 info->inkMetrics=1;
3594
3595 memcpy((char *)&info->ink_maxbounds,
3596 (char *)&info->maxbounds, sizeof(xCharInfo));
3597 memcpy((char *)&info->ink_minbounds,
3598 (char *)&info->minbounds, sizeof(xCharInfo));
3599
3600 /* XXX - hack */
3601 info->defaultCh=0;
3602
3603 /* Set the pInfo flags */
3604 /* Properties set by FontComputeInfoAccelerators:
3605 pInfo->noOverlap;
3606 pInfo->terminalFont;
3607 pInfo->constantMetrics;
3608 pInfo->constantWidth;
3609 pInfo->inkInside;
3610 */
3611 /* from lib/font/util/fontaccel.c */
3612 FontComputeInfoAccelerators(info);
3613 }
3614
3615 if(xf)
3616 xf->fontPrivate = (void*)font;
3617
3618 if(info) {
3619 xrc = FreeTypeAddProperties(font, vals, info, entry->name.name,
3620 rawAverageWidth, font_properties);
3621 if (xrc != Successful) {
3622 goto quit;
3623 }
3624 }
3625
3626 quit:
3627 if ( dynStrTTCapCodeRange ) free(dynStrTTCapCodeRange);
3628 if ( dynStrFTFileName ) free(dynStrFTFileName);
3629 if ( dynStrRealFileName ) free(dynStrRealFileName);
3630 if ( xrc != Successful ) {
3631 if( font ){
3632 if( face && font->instance == NULL ) FreeTypeFreeFace(face);
3633 FreeTypeFreeFont(font);
3634 }
3635 }
3636 return xrc;
3637 }
3638
3639 /* Routines used by X11 to get info and glyphs from the font. */
3640
3641 static int
3642 FreeTypeGetMetrics(FontPtr pFont, unsigned long count, unsigned char *chars,
3643 FontEncoding charEncoding, unsigned long *metricCount,
3644 xCharInfo **metrics)
3645 {
3646 unsigned int code = 0;
3647 int flags = 0;
3648 FTFontPtr tf;
3649 struct TTCapInfo *ttcap;
3650 xCharInfo **mp, *m;
3651
3652 /* MUMBLE("Get metrics for %ld characters\n", count);*/
3653
3654 tf = (FTFontPtr)pFont->fontPrivate;
3655 ttcap = &tf->instance->ttcap;
3656 mp = metrics;
3657
3658 while (count-- > 0) {
3659 switch (charEncoding) {
3660 case Linear8Bit:
3661 case TwoD8Bit:
3662 code = *chars++;
3663 break;
3664 case Linear16Bit:
3665 case TwoD16Bit:
3666 code = (*chars++ << 8);
3667 code |= *chars++;
3668 /* */
3669 if ( !(ttcap->flags & TTCAP_FORCE_C_OUTSIDE) ) {
3670 if ( (int)code <= ttcap->forceConstantSpacingEnd
3671 && ttcap->forceConstantSpacingBegin <= (int)code )
3672 flags|=FT_FORCE_CONSTANT_SPACING;
3673 else flags=0;
3674 }
3675 else { /* for GB18030 proportional */
3676 if ( (int)code <= ttcap->forceConstantSpacingEnd
3677 || ttcap->forceConstantSpacingBegin <= (int)code )
3678 flags|=FT_FORCE_CONSTANT_SPACING;
3679 else flags=0;
3680 }
3681 break;
3682 }
3683
3684 if(FreeTypeFontGetGlyphMetrics(code, flags, &m, tf) == Successful && m!=NULL) {
3685 *mp++ = m;
3686 }
3687 #ifdef X_ACCEPTS_NO_SUCH_CHAR
3688 else *mp++ = &noSuchChar.metrics;
3689 #endif
3690 }
3691
3692 *metricCount = mp - metrics;
3693 return Successful;
3694 }
3695
3696 static int
3697 FreeTypeGetGlyphs(FontPtr pFont, unsigned long count, unsigned char *chars,
3698 FontEncoding charEncoding, unsigned long *glyphCount,
3699 CharInfoPtr *glyphs)
3700 {
3701 unsigned int code = 0;
3702 int flags = 0;
3703 FTFontPtr tf;
3704 CharInfoPtr *gp;
3705 CharInfoPtr g;
3706 struct TTCapInfo *ttcap;
3707
3708 tf = (FTFontPtr)pFont->fontPrivate;
3709 ttcap = &tf->instance->ttcap;
3710 gp = glyphs;
3711
3712 while (count-- > 0) {
3713 switch (charEncoding) {
3714 case Linear8Bit: case TwoD8Bit:
3715 code = *chars++;
3716 break;
3717 case Linear16Bit: case TwoD16Bit:
3718 code = *chars++ << 8;
3719 code |= *chars++;
3720 /* */
3721 if ( !(ttcap->flags & TTCAP_FORCE_C_OUTSIDE) ) {
3722 if ( (int)code <= ttcap->forceConstantSpacingEnd
3723 && ttcap->forceConstantSpacingBegin <= (int)code )
3724 flags|=FT_FORCE_CONSTANT_SPACING;
3725 else flags=0;
3726 }
3727 else { /* for GB18030 proportional */
3728 if ( (int)code <= ttcap->forceConstantSpacingEnd
3729 || ttcap->forceConstantSpacingBegin <= (int)code )
3730 flags|=FT_FORCE_CONSTANT_SPACING;
3731 else flags=0;
3732 }
3733 break;
3734 }
3735
3736 if(FreeTypeFontGetGlyph(code, flags, &g, tf) == Successful && g!=NULL) {
3737 *gp++ = g;
3738 }
3739 #ifdef X_ACCEPTS_NO_SUCH_CHAR
3740 else {
3741 #ifdef XAA_ACCEPTS_NULL_BITS
3742 *gp++ = &noSuchChar;
3743 #else
3744 if ( tf->dummy_char.bits ) {
3745 *gp++ = &tf->dummy_char;
3746 }
3747 else {
3748 char *raster = NULL;
3749 int wd_actual, ht_actual, wd, ht, bpr;
3750 wd_actual = tf->info->maxbounds.rightSideBearing - tf->info->maxbounds.leftSideBearing;
3751 ht_actual = tf->info->maxbounds.ascent + tf->info->maxbounds.descent;
3752 if(wd_actual <= 0) wd = 1;
3753 else wd=wd_actual;
3754 if(ht_actual <= 0) ht = 1;
3755 else ht=ht_actual;
3756 bpr = (((wd + (tf->instance->bmfmt.glyph<<3) - 1) >> 3) &
3757 -tf->instance->bmfmt.glyph);
3758 raster = calloc(1, ht * bpr);
3759 if(raster) {
3760 tf->dummy_char.bits = raster;
3761 *gp++ = &tf->dummy_char;
3762 }
3763 }
3764 #endif
3765 }
3766 #endif
3767 }
3768
3769 *glyphCount = gp - glyphs;
3770 return Successful;
3771 }
3772
3773 static int
3774 FreeTypeSetUpFont(FontPathElementPtr fpe, FontPtr xf, FontInfoPtr info,
3775 fsBitmapFormat format, fsBitmapFormatMask fmask,
3776 FontBitmapFormatPtr bmfmt)
3777 {
3778 int xrc;
3779 int image;
3780
3781 /* Get the default bitmap format information for this X installation.
3782 Also update it for the client if running in the font server. */
3783 FontDefaultFormat(&bmfmt->bit, &bmfmt->byte, &bmfmt->glyph, &bmfmt->scan);
3784 if ((xrc = CheckFSFormat(format, fmask, &bmfmt->bit, &bmfmt->byte,
3785 &bmfmt->scan, &bmfmt->glyph,
3786 &image)) != Successful) {
3787 MUMBLE("Aborting after checking FS format: %d\n", xrc);
3788 return xrc;
3789 }
3790
3791 if(xf) {
3792 xf->refcnt = 0;
3793 xf->bit = bmfmt->bit;
3794 xf->byte = bmfmt->byte;
3795 xf->glyph = bmfmt->glyph;
3796 xf->scan = bmfmt->scan;
3797 xf->format = format;
3798 xf->get_glyphs = FreeTypeGetGlyphs;
3799 xf->get_metrics = FreeTypeGetMetrics;
3800 xf->unload_font = FreeTypeUnloadXFont;
3801 xf->unload_glyphs = 0;
3802 xf->fpe = fpe;
3803 xf->svrPrivate = 0;
3804 xf->fontPrivate = 0; /* we'll set it later */
3805 xf->fpePrivate = 0;
3806 }
3807
3808 info->defaultCh = 0;
3809 info->noOverlap = 0; /* not updated */
3810 info->terminalFont = 0; /* not updated */
3811 info->constantMetrics = 0; /* we'll set it later */
3812 info->constantWidth = 0; /* we'll set it later */
3813 info->inkInside = 1;
3814 info->inkMetrics = 1;
3815 info->allExist=0; /* not updated */
3816 info->drawDirection = LeftToRight; /* we'll set it later */
3817 info->cachable = 1; /* we don't do licensing */
3818 info->anamorphic = 0; /* can hinting lead to anamorphic scaling? */
3819 info->maxOverlap = 0; /* we'll set it later. */
3820 info->pad = 0; /* ??? */
3821 return Successful;
3822 }
3823
3824 /* Functions exported by the backend */
3825
3826 static int
3827 FreeTypeOpenScalable(FontPathElementPtr fpe, FontPtr *ppFont, int flags,
3828 FontEntryPtr entry, char *fileName, FontScalablePtr vals,
3829 fsBitmapFormat format, fsBitmapFormatMask fmask,
3830 FontPtr non_cachable_font)
3831 {
3832 int xrc;
3833 FontPtr xf;
3834 FontBitmapFormatRec bmfmt;
3835
3836 MUMBLE("Open Scalable %s, XLFD=%s\n",fileName, entry->name.length ? entry->name.name : "");
3837
3838 xf = CreateFontRec();
3839 if (xf == NULL)
3840 return AllocError;
3841
3842 xrc = FreeTypeSetUpFont(fpe, xf, &xf->info, format, fmask, &bmfmt);
3843 if(xrc != Successful) {
3844 DestroyFontRec(xf);
3845 return xrc;
3846 }
3847 xrc = FreeTypeLoadXFont(fileName, vals, xf, &xf->info, &bmfmt, entry);
3848 if(xrc != Successful) {
3849 MUMBLE("Error during load: %d\n",xrc);
3850 DestroyFontRec(xf);
3851 return xrc;
3852 }
3853
3854 *ppFont = xf;
3855
3856 return xrc;
3857 }
3858
3859 /* Routine to get requested font info. */
3860
3861 static int
3862 FreeTypeGetInfoScalable(FontPathElementPtr fpe, FontInfoPtr info,
3863 FontEntryPtr entry, FontNamePtr fontName,
3864 char *fileName, FontScalablePtr vals)
3865 {
3866 int xrc;
3867 FontBitmapFormatRec bmfmt;
3868
3869 MUMBLE("Get info, XLFD=%s\n", entry->name.length ? entry->name.name : "");
3870
3871 xrc = FreeTypeSetUpFont(fpe, 0, info, 0, 0, &bmfmt);
3872 if(xrc != Successful) {
3873 return xrc;
3874 }
3875
3876 bmfmt.glyph <<= 3;
3877
3878 xrc = FreeTypeLoadXFont(fileName, vals, 0, info, &bmfmt, entry);
3879 if(xrc != Successful) {
3880 MUMBLE("Error during load: %d\n", xrc);
3881 return xrc;
3882 }
3883
3884 return Successful;
3885 }
3886
3887 /* Renderer registration. */
3888
3889 /* Set the capabilities of this renderer. */
3890 #define CAPABILITIES (CAP_CHARSUBSETTING | CAP_MATRIX)
3891
3892 /* Set it up so file names with either upper or lower case can be
3893 loaded. We don't support compressed fonts. */
3894 static FontRendererRec renderers[] = {
3895 {".ttf", 4, 0, FreeTypeOpenScalable, 0,
3896 FreeTypeGetInfoScalable, 0, CAPABILITIES},
3897 {".ttc", 4, 0, FreeTypeOpenScalable, 0,
3898 FreeTypeGetInfoScalable, 0, CAPABILITIES},
3899 {".otf", 4, 0, FreeTypeOpenScalable, 0,
3900 FreeTypeGetInfoScalable, 0, CAPABILITIES},
3901 {".otc", 4, 0, FreeTypeOpenScalable, 0,
3902 FreeTypeGetInfoScalable, 0, CAPABILITIES},
3903 {".pfa", 4, 0, FreeTypeOpenScalable, 0,
3904 FreeTypeGetInfoScalable, 0, CAPABILITIES},
3905 {".pfb", 4, 0, FreeTypeOpenScalable, 0,
3906 FreeTypeGetInfoScalable, 0, CAPABILITIES},
3907 };
3908 static int num_renderers = sizeof(renderers) / sizeof(renderers[0]);
3909
3910 static FontRendererRec alt_renderers[] = {
3911 {".bdf", 4, 0, FreeTypeOpenScalable, 0,
3912 FreeTypeGetInfoScalable, 0, CAPABILITIES},
3913 {".pcf", 4, 0, FreeTypeOpenScalable, 0,
3914 FreeTypeGetInfoScalable, 0, CAPABILITIES},
3915 };
3916
3917 static int num_alt_renderers =
3918 sizeof(alt_renderers) / sizeof(alt_renderers[0]);
3919
3920
3921 void
3922 FreeTypeRegisterFontFileFunctions(void)
3923 {
3924 int i;
3925
3926 for (i = 0; i < num_renderers; i++)
3927 FontFileRegisterRenderer(&renderers[i]);
3928
3929 for (i = 0; i < num_alt_renderers; i++)
3930 FontFilePriorityRegisterRenderer(&alt_renderers[i], -10);
3931 }