Debian Codegraph @

texk/web2c/xetexdir/XeTeX_ext.c

raw
1 /****************************************************************************\
2 Part of the XeTeX typesetting system
3 Copyright (c) 1994-2008 by SIL International
4 Copyright (c) 2009, 2011 by Jonathan Kew
5 Copyright (c) 2012-2015 by Khaled Hosny
6 Copyright (c) 2012, 2013 by Jiang Jiang
7
8 SIL Author(s): Jonathan Kew
9
10 Permission is hereby granted, free of charge, to any person obtaining
11 a copy of this software and associated documentation files (the
12 "Software"), to deal in the Software without restriction, including
13 without limitation the rights to use, copy, modify, merge, publish,
14 distribute, sublicense, and/or sell copies of the Software, and to
15 permit persons to whom the Software is furnished to do so, subject to
16 the following conditions:
17
18 The above copyright notice and this permission notice shall be
19 included in all copies or substantial portions of the Software.
20
21 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 NONINFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE
25 FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
26 CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28
29 Except as contained in this notice, the name of the copyright holders
30 shall not be used in advertising or otherwise to promote the sale,
31 use or other dealings in this Software without prior written
32 authorization from the copyright holders.
33 \****************************************************************************/
34
35 /* XeTeX_ext.c
36 * additional plain C extensions for XeTeX - mostly platform-neutral
37 */
38
39 #include <w2c/config.h>
40
41 /*
42 * From TeX Live 2021, we use pplib by Pawe\l Jackowski instead of
43 * libpoppler
44 */
45 #include <ppapi.h>
46
47 #include <png.h>
48 #include <zlib.h>
49 #include <graphite2/Font.h>
50
51 #ifdef _MSC_VER
52 #undef timezone
53 #endif
54
55 #include <time.h> /* For `struct tm'. */
56 #if defined (HAVE_SYS_TIME_H)
57 #include <sys/time.h>
58 #elif defined (HAVE_SYS_TIMEB_H)
59 #include <sys/timeb.h>
60 #endif
61
62 #define EXTERN extern
63 #include "xetexd.h"
64
65 #include "XeTeX_ext.h"
66
67 #include <teckit/TECkit_Engine.h>
68
69 #include <kpathsea/c-ctype.h>
70 #include <kpathsea/line.h>
71 #include <kpathsea/readable.h>
72 #include <kpathsea/variable.h>
73 #include <kpathsea/absolute.h>
74 #if defined(WIN32)
75 #include <kpathsea/concatn.h>
76 #endif
77
78 #include <math.h> /* for fabs() */
79
80 #if defined(__STDC__)
81 #include <locale.h>
82 #endif
83
84 #include <signal.h> /* Catch interrupts. */
85
86 #include "XeTeXLayoutInterface.h"
87
88 #include "XeTeXswap.h"
89
90 #include <unicode/ubidi.h>
91 #include <unicode/ubrk.h>
92 #include <unicode/ucnv.h>
93
94 #include <assert.h>
95
96 /* for reading input files, we don't need the default locking routines
97 as xetex is a single-threaded program */
98 #ifdef WIN32
99 #ifdef __MINGW32__
100 /* MinGW (both 32- and 64-bit) has problems with _getc_nolock() and/or _ungetc_nolock() */
101 #define GETC(f) getc(f)
102 #define UNGETC(c,f) ungetc(c,f)
103 #else
104 #define GETC(f) _getc_nolock(f)
105 #define UNGETC(c,f) _ungetc_nolock(c,f)
106 #endif
107 #else
108 #define GETC(f) getc_unlocked(f)
109 #define UNGETC(c,f) ungetc(c,f)
110 #endif
111
112 /* tables/values used in UTF-8 interpretation -
113 code is based on ConvertUTF.[ch] sample code
114 published by the Unicode consortium */
115 const uint32_t
116 offsetsFromUTF8[6] = {
117 0x00000000UL,
118 0x00003080UL,
119 0x000E2080UL,
120 0x03C82080UL,
121 0xFA082080UL,
122 0x82082080UL
123 };
124
125 const uint8_t
126 bytesFromUTF8[256] = {
127 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
128 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
129 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
130 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
131 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
132 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
133 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
134 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5
135 };
136
137 const uint8_t
138 firstByteMark[7] = {
139 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC
140 };
141
142 const int halfShift = 10;
143 const uint32_t halfBase = 0x0010000UL;
144 const uint32_t halfMask = 0x3FFUL;
145 const uint32_t kSurrogateHighStart = 0xD800UL;
146 const uint32_t kSurrogateHighEnd = 0xDBFFUL;
147 const uint32_t kSurrogateLowStart = 0xDC00UL;
148 const uint32_t kSurrogateLowEnd = 0xDFFFUL;
149 const uint32_t byteMask = 0x000000BFUL;
150 const uint32_t byteMark = 0x00000080UL;
151
152
153 /* if the user specifies a paper size or output driver program */
154 const char *papersize;
155 const char *outputdriver = "xdvipdfmx -q -E"; /* default to portable xdvipdfmx driver */
156
157
158 void initversionstring(char **versions)
159 {
160 #ifndef XETEX_MAC
161 int fc_version = FcGetVersion();
162 #endif
163 FT_Int ftMajor, ftMinor, ftPatch;
164 int grMajor, grMinor, grBugfix;
165 UVersionInfo icuVersion;
166 char icu_version[U_MAX_VERSION_STRING_LENGTH] = "";
167
168 const_string fmt =
169 "Compiled with ICU version %s; using %s\n"
170 "Compiled with zlib version %s; using %s\n"
171 "Compiled with FreeType2 version %d.%d.%d; using %d.%d.%d\n"
172 "Compiled with Graphite2 version %d.%d.%d; using %d.%d.%d\n"
173 "Compiled with HarfBuzz version %s; using %s\n"
174 "Compiled with libpng version %s; using %s\n"
175 "Compiled with pplib version %s\n"
176 #ifdef XETEX_MAC
177 "Using Mac OS X Core Text and Cocoa frameworks\n"
178 #else
179 "Compiled with fontconfig version %d.%d.%d; using %d.%d.%d\n"
180 #endif
181 ;
182
183 int len = strlen(fmt)
184 + strlen(U_ICU_VERSION)
185 + strlen(icu_version)
186 + strlen(ZLIB_VERSION)
187 + strlen(zlib_version)
188 + strlen(HB_VERSION_STRING)
189 + strlen(hb_version_string())
190 + strlen(PNG_LIBPNG_VER_STRING)
191 + strlen(png_libpng_ver)
192 + strlen(pplib_version)
193 #ifndef XETEX_MAC
194 + 6 * 3 /* for fontconfig version #s (won't really need 3 digits per field!) */
195 #endif
196 + 6 * 3 /* for graphite2 version #s (ditto) */
197 + 6 * 3; /* for freetype version #s (ditto) */
198
199 *versions = (char *) xmalloc(len + 1);
200 /* len will be more than enough, because of the placeholder chars in fmt
201 that get replaced by the arguments */
202
203 u_getVersion(icuVersion);
204 u_versionToString(icuVersion, icu_version);
205
206 if (gFreeTypeLibrary == 0 && FT_Init_FreeType(&gFreeTypeLibrary) != 0) {
207 fprintf(stderr, "FreeType initialization failed!\n");
208 exit(9);
209 }
210 FT_Library_Version(gFreeTypeLibrary, &ftMajor, &ftMinor, &ftPatch);
211
212 gr_engine_version(&grMajor, &grMinor, &grBugfix);
213
214 (void)sprintf(*versions, fmt,
215 U_ICU_VERSION, icu_version,
216 ZLIB_VERSION, zlib_version,
217 FREETYPE_MAJOR, FREETYPE_MINOR, FREETYPE_PATCH,
218 ftMajor, ftMinor, ftPatch,
219 GR2_VERSION_MAJOR, GR2_VERSION_MINOR, GR2_VERSION_BUGFIX,
220 grMajor, grMinor, grBugfix,
221 HB_VERSION_STRING, hb_version_string(),
222 PNG_LIBPNG_VER_STRING, png_libpng_ver, pplib_version
223 #ifndef XETEX_MAC
224 ,
225 FC_VERSION / 10000, (FC_VERSION % 10000) / 100, FC_VERSION % 100,
226 fc_version / 10000, (fc_version % 10000) / 100, fc_version % 100
227 #endif
228 );
229 }
230
231
232 void
233 setinputfileencoding(UFILE* f, integer mode, integer encodingData)
234 {
235 if ((f->encodingMode == ICUMAPPING) && (f->conversionData != NULL))
236 ucnv_close((UConverter*)(f->conversionData));
237 f->conversionData = 0;
238
239 switch (mode) {
240 case UTF8:
241 case UTF16BE:
242 case UTF16LE:
243 case RAW:
244 f->encodingMode = mode;
245 break;
246
247 case ICUMAPPING:
248 {
249 char* name = gettexstring(encodingData);
250 UErrorCode err = U_ZERO_ERROR;
251 UConverter* cnv = ucnv_open(name, &err);
252 if (cnv == NULL) {
253 begindiagnostic();
254 printnl('E');
255 printcstring("rror ");
256 printint(err);
257 printcstring(" creating Unicode converter for `");
258 printcstring(name);
259 printcstring("'; reading as raw bytes");
260 enddiagnostic(1);
261 f->encodingMode = RAW;
262 } else {
263 f->encodingMode = ICUMAPPING;
264 f->conversionData = cnv;
265 }
266 free(name);
267 }
268 break;
269 }
270 }
271
272 static void
273 buffer_overflow(void)
274 {
275 fprintf (stderr, "! Unable to read an entire line---bufsize=%u.\n",
276 (unsigned) bufsize);
277 fputs ("Please increase buf_size in texmf.cnf.\n", stderr);
278 uexit (1);
279 }
280
281 static void
282 conversion_error(int errcode)
283 {
284 begindiagnostic();
285 printnl('U');
286 printcstring("nicode conversion failed (ICU error code = ");
287 printint(errcode);
288 printcstring(") discarding any remaining text");
289 enddiagnostic(1);
290 }
291
292 #ifdef WORDS_BIGENDIAN
293 #define NATIVE_UTF32 kForm_UTF32BE
294 #else
295 #define NATIVE_UTF32 kForm_UTF32LE
296 #endif
297
298 static void
299 apply_normalization(uint32_t* buf, int len, int norm)
300 {
301 static TECkit_Converter normalizers[2] = { NULL, NULL };
302
303 TECkit_Status status;
304 UInt32 inUsed, outUsed;
305 TECkit_Converter *normPtr = &normalizers[norm - 1];
306 if (*normPtr == NULL) {
307 status = TECkit_CreateConverter(NULL, 0, 1,
308 NATIVE_UTF32, NATIVE_UTF32 | (norm == 1 ? kForm_NFC : kForm_NFD),
309 &*normPtr);
310 if (status != kStatus_NoError) {
311 fprintf(stderr, "! Failed to create normalizer: error code = %d\n", (int)status);
312 uexit (1);
313 }
314 }
315
316 status = TECkit_ConvertBuffer(*normPtr, (Byte*)buf, len * sizeof(UInt32), &inUsed,
317 (Byte*)&buffer[first], sizeof(*buffer) * (bufsize - first), &outUsed, 1);
318 TECkit_ResetConverter(*normPtr);
319 if (status != kStatus_NoError)
320 buffer_overflow();
321 last = first + outUsed / sizeof(*buffer);
322 }
323
324 #ifdef WORDS_BIGENDIAN
325 #define UCNV_UTF32_NativeEndian UCNV_UTF32_BigEndian
326 #else
327 #define UCNV_UTF32_NativeEndian UCNV_UTF32_LittleEndian
328 #endif
329
330 int
331 input_line(UFILE* f)
332 {
333 static char* byteBuffer = NULL;
334 static uint32_t *utf32Buf = NULL;
335 int i, tmpLen;
336 int norm = getinputnormalizationstate();
337 #ifdef WIN32
338 const int fd = fileno(f->f);
339 if (fd == _fileno(stdin) && _isatty(fd)) {
340 f->encodingMode = WIN32CONSOLE;
341 }
342 #endif
343
344 last = first;
345
346 if (f->encodingMode == ICUMAPPING) {
347 uint32_t bytesRead = 0;
348 UConverter* cnv;
349 int outLen;
350 UErrorCode errorCode = U_ZERO_ERROR;
351
352 if (byteBuffer == NULL)
353 byteBuffer = (char*) xmalloc(bufsize + 1);
354
355 /* Recognize either LF or CR as a line terminator; skip initial LF if prev line ended with CR. */
356 i = GETC(f->f);
357 if (f->skipNextLF) {
358 f->skipNextLF = 0;
359 if (i == '\n')
360 i = GETC(f->f);
361 }
362
363 if (i != EOF && i != '\n' && i != '\r')
364 byteBuffer[bytesRead++] = i;
365 if (i != EOF && i != '\n' && i != '\r')
366 while (bytesRead < bufsize && (i = GETC(f->f)) != EOF && i != '\n' && i != '\r')
367 byteBuffer[bytesRead++] = i;
368
369 if (i == EOF && errno != EINTR && bytesRead == 0)
370 return false;
371
372 if (i != EOF && i != '\n' && i != '\r')
373 buffer_overflow();
374
375 /* now apply the mapping to turn external bytes into Unicode characters in buffer */
376 cnv = (UConverter*)(f->conversionData);
377 switch (norm) {
378 case 1: // NFC
379 case 2: // NFD
380 if (utf32Buf == NULL)
381 utf32Buf = (uint32_t*) xcalloc(bufsize, sizeof(uint32_t));
382 tmpLen = ucnv_toAlgorithmic(UCNV_UTF32_NativeEndian, cnv,
383 (char*)utf32Buf, bufsize * sizeof(*utf32Buf),
384 byteBuffer, bytesRead, &errorCode);
385 if (errorCode != 0) {
386 conversion_error((int)errorCode);
387 return false;
388 }
389 apply_normalization(utf32Buf, tmpLen / sizeof(*utf32Buf), norm); // sets 'last' correctly
390 break;
391
392 default: // none
393 outLen = ucnv_toAlgorithmic(UCNV_UTF32_NativeEndian, cnv,
394 (char*)&buffer[first], sizeof(*buffer) * (bufsize - first),
395 byteBuffer, bytesRead, &errorCode);
396 if (errorCode != 0) {
397 conversion_error((int)errorCode);
398 return false;
399 }
400 outLen /= sizeof(*buffer);
401 last = first + outLen;
402 break;
403 }
404 } else {
405 /* Recognize either LF or CR as a line terminator; skip initial LF if prev line ended with CR. */
406 i = get_uni_c(f);
407 if (f->skipNextLF) {
408 f->skipNextLF = 0;
409 if (i == '\n')
410 i = get_uni_c(f);
411 }
412
413 switch (norm) {
414 case 1: // NFC
415 case 2: // NFD
416 // read Unicode chars into utf32Buf as UTF32
417 if (utf32Buf == NULL)
418 utf32Buf = (uint32_t*) xcalloc(bufsize, sizeof(uint32_t));
419 tmpLen = 0;
420 if (i != EOF && i != '\n' && i != '\r')
421 utf32Buf[tmpLen++] = i;
422 if (i != EOF && i != '\n' && i != '\r')
423 while (tmpLen < bufsize && (i = get_uni_c(f)) != EOF && i != '\n' && i != '\r')
424 utf32Buf[tmpLen++] = i;
425
426 if (i == EOF && errno != EINTR && tmpLen == 0)
427 return false;
428
429 /* We didn't get the whole line because our buffer was too small. */
430 if (i != EOF && i != '\n' && i != '\r')
431 buffer_overflow();
432 apply_normalization(utf32Buf, tmpLen, norm);
433 break;
434
435 default: // none
436 #ifdef WIN32
437 if (f->encodingMode == WIN32CONSOLE && i == 0x1a) /* Ctrl+Z */
438 return false;
439 #endif
440 if (last < bufsize && i != EOF && i != '\n' && i != '\r')
441 buffer[last++] = i;
442 if (i != EOF && i != '\n' && i != '\r')
443 while (last < bufsize && (i = get_uni_c(f)) != EOF && i != '\n' && i != '\r')
444 buffer[last++] = i;
445
446 if (i == EOF && errno != EINTR && last == first)
447 return false;
448
449 /* We didn't get the whole line because our buffer was too small. */
450 if (i != EOF && i != '\n' && i != '\r')
451 buffer_overflow();
452 break;
453 }
454 }
455
456 /* If line ended with CR, remember to skip following LF. */
457 if (i == '\r')
458 f->skipNextLF = 1;
459
460 buffer[last] = ' ';
461 if (last >= maxbufstack)
462 maxbufstack = last;
463
464 /* Trim trailing space or EOL characters. */
465 #define IS_SPC_OR_EOL(c) ((c) == ' ' || (c) == '\r' || (c) == '\n')
466 while (last > first && IS_SPC_OR_EOL(buffer[last - 1]))
467 --last;
468
469 return true;
470 }
471
472 static void die(const_string s, int i)
473 {
474 fprintf(stderr, s, i);
475 fprintf(stderr, " - exiting\n");
476 exit(3);
477 }
478
479 static UBreakIterator* brkIter = NULL;
480 static int brkLocaleStrNum = 0;
481
482 void
483 linebreakstart(int f, integer localeStrNum, uint16_t* text, integer textLength)
484 {
485 UErrorCode status = U_ZERO_ERROR;
486 char* locale = (char*)gettexstring(localeStrNum);
487
488 if (fontarea[f] == OTGR_FONT_FLAG && strcmp(locale, "G") == 0) {
489 XeTeXLayoutEngine engine = (XeTeXLayoutEngine) fontlayoutengine[f];
490 if (initGraphiteBreaking(engine, text, textLength))
491 /* user asked for Graphite line breaking and the font supports it */
492 return;
493 }
494
495 if ((localeStrNum != brkLocaleStrNum) && (brkIter != NULL)) {
496 ubrk_close(brkIter);
497 brkIter = NULL;
498 }
499
500 if (brkIter == NULL) {
501 brkIter = ubrk_open(UBRK_LINE, locale, NULL, 0, &status);
502 if (U_FAILURE(status)) {
503 begindiagnostic();
504 printnl('E');
505 printcstring("rror ");
506 printint(status);
507 printcstring(" creating linebreak iterator for locale `");
508 printcstring(locale);
509 printcstring("'; trying default locale `en_us'.");
510 enddiagnostic(1);
511 if (brkIter != NULL)
512 ubrk_close(brkIter);
513 status = U_ZERO_ERROR;
514 brkIter = ubrk_open(UBRK_LINE, "en_us", NULL, 0, &status);
515 }
516 free(locale);
517 brkLocaleStrNum = localeStrNum;
518 }
519
520 if (brkIter == NULL) {
521 die("! failed to create linebreak iterator, status=%d", (int)status);
522 }
523
524 ubrk_setText(brkIter, (UChar*) text, textLength, &status);
525 }
526
527 int
528 linebreaknext(void)
529 {
530 if (brkIter != NULL)
531 return ubrk_next((UBreakIterator*)brkIter);
532 else
533 return findNextGraphiteBreak();
534 }
535
536 int
537 getencodingmodeandinfo(integer* info)
538 {
539 /* \XeTeXinputencoding "enc-name"
540 * -> name is packed in |nameoffile| as a C string, starting at [1]
541 * Check if it's a built-in name; if not, try to open an ICU converter by that name
542 */
543 UErrorCode err = U_ZERO_ERROR;
544 UConverter* cnv;
545 char* name = (char*)nameoffile + 1;
546 *info = 0;
547 if (strcasecmp(name, "auto") == 0) {
548 return AUTO;
549 }
550 if (strcasecmp(name, "utf8") == 0) {
551 return UTF8;
552 }
553 if (strcasecmp(name, "utf16") == 0) { /* depends on host platform */
554 #ifdef WORDS_BIGENDIAN
555 return UTF16BE;
556 #else
557 return UTF16LE;
558 #endif
559 }
560 if (strcasecmp(name, "utf16be") == 0) {
561 return UTF16BE;
562 }
563 if (strcasecmp(name, "utf16le") == 0) {
564 return UTF16LE;
565 }
566 if (strcasecmp(name, "bytes") == 0) {
567 return RAW;
568 }
569
570 /* try for an ICU converter */
571 cnv = ucnv_open(name, &err);
572 if (cnv == NULL) {
573 begindiagnostic();
574 printnl('U'); /* ensure message starts on a new line */
575 printcstring("nknown encoding `");
576 printcstring(name);
577 printcstring("'; reading as raw bytes");
578 enddiagnostic(1);
579 return RAW;
580 } else {
581 ucnv_close(cnv);
582 *info = maketexstring(name);
583 return ICUMAPPING;
584 }
585 }
586
587 void
588 printutf8str(const unsigned char* str, int len)
589 {
590 while (len-- > 0)
591 printrawchar(*(str++), true); /* bypass utf-8 encoding done in print_char() */
592 }
593
594 void
595 printchars(const unsigned short* str, int len)
596 {
597 while (len-- > 0)
598 printchar(*(str++));
599 }
600
601 #ifdef WORDS_BIGENDIAN
602 #define UTF16_NATIVE kForm_UTF16BE
603 #else
604 #define UTF16_NATIVE kForm_UTF16LE
605 #endif
606
607 static void*
608 load_mapping_file(const char* s, const char* e, char byteMapping)
609 {
610 char* mapPath;
611 TECkit_Converter cnv = 0;
612 char* buffer = (char*) xmalloc(e - s + 5);
613 strncpy(buffer, s, e - s);
614 buffer[e - s] = 0;
615 strcat(buffer, ".tec");
616 mapPath = kpse_find_file(buffer, kpse_miscfonts_format, 1);
617
618 if (mapPath) {
619 FILE* mapFile = fopen(mapPath, FOPEN_RBIN_MODE);
620 free(mapPath);
621 if (mapFile) {
622 uint32_t mappingSize;
623 Byte* mapping;
624 /* TECkit_Status status; */
625 fseek(mapFile, 0, SEEK_END);
626 mappingSize = ftell(mapFile);
627 fseek(mapFile, 0, SEEK_SET);
628 mapping = (Byte*) xmalloc(mappingSize);
629 fread(mapping, 1, mappingSize, mapFile);
630 fclose(mapFile);
631 if (byteMapping != 0)
632 /* status = */ TECkit_CreateConverter(mapping, mappingSize,
633 false,
634 UTF16_NATIVE, kForm_Bytes,
635 &cnv);
636 else
637 /* status = */ TECkit_CreateConverter(mapping, mappingSize,
638 true,
639 UTF16_NATIVE, UTF16_NATIVE,
640 &cnv);
641 free(mapping);
642 }
643 if (cnv == NULL)
644 fontmappingwarning(buffer, strlen(buffer), 2); /* not loadable */
645 else if (gettracingfontsstate() > 1)
646 fontmappingwarning(buffer, strlen(buffer), 0); /* tracing */
647 } else {
648 fontmappingwarning(buffer, strlen(buffer), 1); /* not found */
649 }
650
651 free(buffer);
652
653 return cnv;
654 }
655
656 char *saved_mapping_name = NULL;
657 void
658 checkfortfmfontmapping(void)
659 {
660 char* cp = strstr((char*)nameoffile + 1, ":mapping=");
661 if (saved_mapping_name != NULL) {
662 free(saved_mapping_name);
663 saved_mapping_name = NULL;
664 }
665 if (cp != NULL) {
666 *cp = 0;
667 cp += 9;
668 while (*cp && *cp <= ' ')
669 ++cp;
670 if (*cp)
671 saved_mapping_name = xstrdup(cp);
672 }
673 }
674
675 void*
676 loadtfmfontmapping(void)
677 {
678 void* rval = NULL;
679 if (saved_mapping_name != NULL) {
680 rval = load_mapping_file(saved_mapping_name,
681 saved_mapping_name + strlen(saved_mapping_name), 1);
682 free(saved_mapping_name);
683 saved_mapping_name = NULL;
684 }
685 return rval;
686 }
687
688 int
689 applytfmfontmapping(void* cnv, int c)
690 {
691 UniChar in = c;
692 Byte out[2];
693 UInt32 inUsed, outUsed;
694 /* TECkit_Status status; */
695 /* status = */ TECkit_ConvertBuffer((TECkit_Converter)cnv,
696 (const Byte*)&in, sizeof(in), &inUsed, out, sizeof(out), &outUsed, 1);
697 TECkit_ResetConverter((TECkit_Converter)cnv);
698 if (outUsed < 1)
699 return 0;
700 else
701 return out[0];
702 }
703
704 double
705 read_double(const char** s)
706 {
707 int neg = 0;
708 double val = 0.0;
709 const char* cp = *s;
710
711 while (*cp == ' '|| *cp == '\t')
712 ++cp;
713 if (*cp == '-') {
714 neg = 1;
715 ++cp;
716 } else if (*cp == '+') {
717 ++cp;
718 }
719
720 while (*cp >= '0' && *cp <= '9') {
721 val = val * 10.0 + *cp - '0';
722 ++cp;
723 }
724 if (*cp == '.') {
725 double dec = 10.0;
726 ++cp;
727 while (*cp >= '0' && *cp <= '9') {
728 val = val + (*cp - '0') / dec;
729 ++cp;
730 dec = dec * 10.0;
731 }
732 }
733 *s = cp;
734
735 return neg ? -val : val;
736 }
737
738 static hb_tag_t
739 read_tag_with_param(const char* cp, int* param)
740 {
741 const char* cp2;
742 hb_tag_t tag;
743
744 cp2 = cp;
745 while (*cp2 && (*cp2 != ':') && (*cp2 != ';') && (*cp2 != ',') && (*cp2 != '='))
746 ++cp2;
747
748 tag = hb_tag_from_string(cp, cp2 - cp);
749
750 cp = cp2;
751 if (*cp == '=') {
752 int neg = 0;
753 ++cp;
754 if (*cp == '-') {
755 ++neg;
756 ++cp;
757 }
758 while (*cp >= '0' && *cp <= '9') {
759 *param = *param * 10 + *cp - '0';
760 ++cp;
761 }
762 if (neg)
763 *param = -(*param);
764 }
765
766 return tag;
767 }
768
769 unsigned int
770 read_rgb_a(const char** cp)
771 {
772 uint32_t rgbValue = 0;
773 uint32_t alpha = 0;
774 int i;
775 for (i = 0; i < 6; ++i) {
776 if ((**cp >= '0') && (**cp <= '9'))
777 rgbValue = (rgbValue << 4) + **cp - '0';
778 else if ((**cp >= 'A') && (**cp <= 'F'))
779 rgbValue = (rgbValue << 4) + **cp - 'A' + 10;
780 else if ((**cp >= 'a') && (**cp <= 'f'))
781 rgbValue = (rgbValue << 4) + **cp - 'a' + 10;
782 else
783 return 0x000000FF;
784 (*cp)++;
785 }
786 rgbValue <<= 8;
787 for (i = 0; i < 2; ++i) {
788 if ((**cp >= '0') && (**cp <= '9'))
789 alpha = (alpha << 4) + **cp - '0';
790 else if ((**cp >= 'A') && (**cp <= 'F'))
791 alpha = (alpha << 4) + **cp - 'A' + 10;
792 else if ((**cp >= 'a') && (**cp <= 'f'))
793 alpha = (alpha << 4) + **cp - 'a' + 10;
794 else
795 break;
796 (*cp)++;
797 }
798 if (i == 2)
799 rgbValue += alpha;
800 else
801 rgbValue += 0xFF;
802 return rgbValue;
803 }
804
805 int
806 readCommonFeatures(const char* feat, const char* end, float* extend, float* slant, float* embolden, float* letterspace, uint32_t* rgbValue)
807 // returns 1 to go to next_option, -1 for bad_option, 0 to continue
808 {
809 const char* sep;
810 if (strncmp(feat, "mapping", 7) == 0) {
811 sep = feat + 7;
812 if (*sep != '=')
813 return -1;
814 loadedfontmapping = load_mapping_file(sep + 1, end, 0);
815 return 1;
816 }
817
818 if (strncmp(feat, "extend", 6) == 0) {
819 sep = feat + 6;
820 if (*sep != '=')
821 return -1;
822 ++sep;
823 *extend = read_double(&sep);
824 return 1;
825 }
826
827 if (strncmp(feat, "slant", 5) == 0) {
828 sep = feat + 5;
829 if (*sep != '=')
830 return -1;
831 ++sep;
832 *slant = read_double(&sep);
833 return 1;
834 }
835
836 if (strncmp(feat, "embolden", 8) == 0) {
837 sep = feat + 8;
838 if (*sep != '=')
839 return -1;
840 ++sep;
841 *embolden = read_double(&sep);
842 return 1;
843 }
844
845 if (strncmp(feat, "letterspace", 11) == 0) {
846 sep = feat + 11;
847 if (*sep != '=')
848 return -1;
849 ++sep;
850 *letterspace = read_double(&sep);
851 return 1;
852 }
853
854 if (strncmp(feat, "color", 5) == 0) {
855 const char* s;
856 sep = feat + 5;
857 if (*sep != '=')
858 return -1;
859 ++sep;
860 s = sep;
861 *rgbValue = read_rgb_a(&sep);
862 if ((sep == s+6) || (sep == s+8))
863 loadedfontflags |= FONT_FLAGS_COLORED;
864 else
865 return -1;
866 return 1;
867 }
868
869 return 0;
870 }
871
872 static bool
873 readFeatureNumber(const char* s, const char* e, hb_tag_t* f, int* v)
874 /* s...e is a "id=setting" string; */
875 {
876 *f = 0;
877 *v = 0;
878 if (*s < '0' || *s > '9')
879 return false;
880 while (*s >= '0' && *s <= '9')
881 *f = *f * 10 + *s++ - '0';
882 while ((*s == ' ') || (*s == '\t'))
883 ++s;
884 if (*s++ != '=')
885 /* no setting was specified */
886 return false;
887
888 if (*s < '0' || *s > '9')
889 return false;
890 while (*s >= '0' && *s <= '9')
891 *v = *v * 10 + *s++ - '0';
892 while ((*s == ' ') || (*s == '\t'))
893 ++s;
894 if (s != e)
895 return false;
896 return true;
897 }
898
899 static void*
900 loadOTfont(PlatformFontRef fontRef, XeTeXFont font, Fixed scaled_size, char* cp1)
901 {
902 XeTeXLayoutEngine engine = NULL;
903 hb_tag_t script = HB_TAG_NONE;
904 char * language = NULL;
905 hb_feature_t* features = NULL;
906 char** shapers = NULL; /* NULL-terminated array */
907 int nFeatures = 0;
908 int nShapers = 0;
909
910 char* cp2;
911 char* cp3;
912
913 hb_tag_t tag;
914
915 uint32_t rgbValue = 0x000000FF;
916
917 float extend = 1.0;
918 float slant = 0.0;
919 float embolden = 0.0;
920 float letterspace = 0.0;
921
922 int i;
923
924 char reqEngine = getReqEngine();
925
926 if (reqEngine == 'O' || reqEngine == 'G') {
927 shapers = (char**) xrealloc(shapers, (nShapers + 1) * sizeof(char *));
928 if (reqEngine == 'O') {
929 static char ot_const[] = "ot";
930 shapers[nShapers] = ot_const;
931 } else if (reqEngine == 'G') {
932 static char graphite2_const[] = "graphite2";
933 shapers[nShapers] = graphite2_const;
934 }
935 nShapers++;
936 }
937
938 if (reqEngine == 'G') {
939 char* tmpShapers[] = {shapers[0]};
940 /* create a default engine so we can query the font for Graphite features;
941 * because of font caching, it's cheap to discard this and create the real one later */
942 engine = createLayoutEngine(fontRef, font, script, language,
943 features, nFeatures, tmpShapers, rgbValue, extend, slant, embolden);
944
945 if (engine == NULL)
946 return NULL;
947 }
948
949 /* scan the feature string (if any) */
950 if (cp1 != NULL) {
951 while (*cp1) {
952 if ((*cp1 == ':') || (*cp1 == ';') || (*cp1 == ','))
953 ++cp1;
954 while ((*cp1 == ' ') || (*cp1 == '\t')) /* skip leading whitespace */
955 ++cp1;
956 if (*cp1 == 0) /* break if end of string */
957 break;
958
959 cp2 = cp1;
960 while (*cp2 && (*cp2 != ':') && (*cp2 != ';') && (*cp2 != ','))
961 ++cp2;
962
963 if (strncmp(cp1, "script", 6) == 0) {
964 cp3 = cp1 + 6;
965 if (*cp3 != '=')
966 goto bad_option;
967 ++cp3;
968 script = hb_tag_from_string(cp3, cp2 - cp3);
969 goto next_option;
970 }
971
972 if (strncmp(cp1, "language", 8) == 0) {
973 cp3 = cp1 + 8;
974 if (*cp3 != '=')
975 goto bad_option;
976 ++cp3;
977 language = (char*)xmalloc(cp2 - cp3 + 1);
978 language[cp2 - cp3] = '\0';
979 memcpy(language, cp3, cp2 - cp3);
980 goto next_option;
981 }
982
983 if (strncmp(cp1, "shaper", 6) == 0) {
984 cp3 = cp1 + 6;
985 if (*cp3 != '=')
986 goto bad_option;
987 ++cp3;
988 shapers = (char**) xrealloc(shapers, (nShapers + 1) * sizeof(char *));
989 /* some dumb systems have no strndup() */
990 shapers[nShapers] = strdup(cp3);
991 shapers[nShapers][cp2 - cp3] = '\0';
992 nShapers++;
993 goto next_option;
994 }
995
996 i = readCommonFeatures(cp1, cp2, &extend, &slant, &embolden, &letterspace, &rgbValue);
997 if (i == 1)
998 goto next_option;
999 else if (i == -1)
1000 goto bad_option;
1001
1002 if (reqEngine == 'G') {
1003 int value = 0;
1004 if (readFeatureNumber(cp1, cp2, &tag, &value)
1005 || findGraphiteFeature(engine, cp1, cp2, &tag, &value)) {
1006 features = (hb_feature_t*) xrealloc(features, (nFeatures + 1) * sizeof(hb_feature_t));
1007 features[nFeatures].tag = tag;
1008 features[nFeatures].value = value;
1009 features[nFeatures].start = 0;
1010 features[nFeatures].end = (unsigned int) -1;
1011 nFeatures++;
1012 goto next_option;
1013 }
1014 }
1015
1016 if (*cp1 == '+') {
1017 int param = 0;
1018 tag = read_tag_with_param(cp1 + 1, &param);
1019 features = (hb_feature_t*) xrealloc(features, (nFeatures + 1) * sizeof(hb_feature_t));
1020 features[nFeatures].tag = tag;
1021 features[nFeatures].start = 0;
1022 features[nFeatures].end = (unsigned int) -1;
1023 // for backward compatibility with pre-0.9999 where feature
1024 // indices started from 0
1025 if (param >= 0)
1026 param++;
1027 features[nFeatures].value = param;
1028 nFeatures++;
1029 goto next_option;
1030 }
1031
1032 if (*cp1 == '-') {
1033 ++cp1;
1034 tag = hb_tag_from_string(cp1, cp2 - cp1);
1035 features = (hb_feature_t*) xrealloc(features, (nFeatures + 1) * sizeof(hb_feature_t));
1036 features[nFeatures].tag = tag;
1037 features[nFeatures].start = 0;
1038 features[nFeatures].end = (unsigned int) -1;
1039 features[nFeatures].value = 0;
1040 nFeatures++;
1041 goto next_option;
1042 }
1043
1044 if (strncmp(cp1, "vertical", 8) == 0) {
1045 cp3 = cp2;
1046 if (*cp3 == ';' || *cp3 == ':' || *cp3 == ',')
1047 --cp3;
1048 while (*cp3 == '\0' || *cp3 == ' ' || *cp3 == '\t')
1049 --cp3;
1050 if (*cp3)
1051 ++cp3;
1052 if (cp3 == cp1 + 8) {
1053 loadedfontflags |= FONT_FLAGS_VERTICAL;
1054 goto next_option;
1055 }
1056 }
1057
1058 bad_option:
1059 fontfeaturewarning((void*) cp1, cp2 - cp1, 0, 0);
1060
1061 next_option:
1062 cp1 = cp2;
1063 }
1064 }
1065
1066 if (shapers != NULL) {
1067 shapers = (char**) xrealloc(shapers, (nShapers + 1) * sizeof(char *));
1068 shapers[nShapers] = NULL;
1069 }
1070
1071 if (embolden != 0.0)
1072 embolden = embolden * Fix2D(scaled_size) / 100.0;
1073
1074 if (letterspace != 0.0)
1075 loadedfontletterspace = (letterspace / 100.0) * scaled_size;
1076
1077 if ((loadedfontflags & FONT_FLAGS_COLORED) == 0)
1078 rgbValue = 0x000000FF;
1079
1080 if ((loadedfontflags & FONT_FLAGS_VERTICAL) != 0)
1081 setFontLayoutDir(font, 1);
1082
1083 engine = createLayoutEngine(fontRef, font, script, language,
1084 features, nFeatures, shapers, rgbValue, extend, slant, embolden);
1085
1086 if (engine == 0) {
1087 // only free these if creation failed, otherwise the engine now owns them
1088 free(features);
1089 free(shapers);
1090 } else {
1091 nativefonttypeflag = OTGR_FONT_FLAG;
1092 }
1093
1094 return engine;
1095 }
1096
1097 static void
1098 splitFontName(char* name, char** var, char** feat, char** end, int* index)
1099 {
1100 *var = NULL;
1101 *feat = NULL;
1102 *index = 0;
1103 if (*name == '[') {
1104 int withinFileName = 1;
1105 #ifdef WIN32
1106 char* start = name + 1;
1107 #endif
1108 ++name;
1109 while (*name) {
1110 if (withinFileName && *name == ']') {
1111 withinFileName = 0;
1112 if (*var == NULL)
1113 *var = name;
1114 } else if (*name == ':') {
1115 if (withinFileName && *var == NULL
1116 #ifdef WIN32
1117 && !((name - start == 1) && isalpha(*start))
1118 #endif
1119 ) {
1120 *var = name;
1121 ++name;
1122 while (*name >= '0' && *name <= '9')
1123 *index = *index * 10 + *name++ - '0';
1124 --name;
1125 } else if (!withinFileName && *feat == NULL)
1126 *feat = name;
1127 }
1128 ++name;
1129 }
1130 *end = name;
1131 } else {
1132 while (*name) {
1133 if (*name == '/' && *var == NULL && *feat == NULL)
1134 *var = name;
1135 else if (*name == ':' && *feat == NULL)
1136 *feat = name;
1137 ++name;
1138 }
1139 *end = name;
1140 }
1141 if (*feat == NULL)
1142 *feat = name;
1143 if (*var == NULL)
1144 *var = *feat;
1145 }
1146
1147 void*
1148 findnativefont(unsigned char* uname, integer scaled_size)
1149 /* scaled_size here is in TeX points, or is a negative integer for 'scaled' */
1150 {
1151 void* rval = NULL;
1152 char* nameString;
1153 char* var;
1154 char* feat;
1155 char* end;
1156 char* name = (char*)uname;
1157 char* varString = NULL;
1158 char* featString = NULL;
1159 PlatformFontRef fontRef;
1160 XeTeXFont font = NULL;
1161 int index = 0;
1162
1163 loadedfontmapping = NULL;
1164 loadedfontflags = 0;
1165 loadedfontletterspace = 0;
1166
1167 splitFontName(name, &var, &feat, &end, &index);
1168 nameString = (char*) xmalloc(var - name + 1);
1169 strncpy(nameString, name, var - name);
1170 nameString[var - name] = 0;
1171
1172 if (feat > var) {
1173 varString = (char*) xmalloc(feat - var);
1174 strncpy(varString, var + 1, feat - var - 1);
1175 varString[feat - var - 1] = 0;
1176 }
1177
1178 if (end > feat) {
1179 featString = (char*) xmalloc(end - feat);
1180 strncpy(featString, feat + 1, end - feat - 1);
1181 featString[end - feat - 1] = 0;
1182 }
1183
1184 // check for "[filename]" form, don't search maps in this case
1185 if (nameString[0] == '[') {
1186 char* path = kpse_find_file(nameString + 1, kpse_opentype_format, 0);
1187 if (path == NULL)
1188 path = kpse_find_file(nameString + 1, kpse_truetype_format, 0);
1189 if (path == NULL)
1190 path = kpse_find_file(nameString + 1, kpse_type1_format, 0);
1191 if (path != NULL) {
1192 if (scaled_size < 0) {
1193 font = createFontFromFile(path, index, 655360L);
1194 if (font != NULL) {
1195 Fixed dsize = D2Fix(getDesignSize(font));
1196 if (scaled_size == -1000)
1197 scaled_size = dsize;
1198 else
1199 scaled_size = zxnoverd(dsize, -scaled_size, 1000);
1200 deleteFont(font);
1201 }
1202 }
1203 font = createFontFromFile(path, index, scaled_size);
1204 if (font != NULL) {
1205 loadedfontdesignsize = D2Fix(getDesignSize(font));
1206
1207 /* This is duplicated in XeTeXFontMgr::findFont! */
1208 setReqEngine(0);
1209 if (varString) {
1210 if (strncmp(varString, "/AAT", 4) == 0)
1211 setReqEngine('A');
1212 else if ((strncmp(varString, "/OT", 3) == 0) || (strncmp(varString, "/ICU", 4) == 0))
1213 setReqEngine('O');
1214 else if (strncmp(varString, "/GR", 3) == 0)
1215 setReqEngine('G');
1216 }
1217
1218 rval = loadOTfont(0, font, scaled_size, featString);
1219 if (rval == NULL)
1220 deleteFont(font);
1221 if (rval != NULL && gettracingfontsstate() > 0) {
1222 begindiagnostic();
1223 zprintnl(' ');
1224 printcstring("-> ");
1225 printcstring(path);
1226 zenddiagnostic(0);
1227 }
1228 }
1229 }
1230 } else {
1231 fontRef = findFontByName(nameString, varString, Fix2D(scaled_size));
1232
1233 if (fontRef != 0) {
1234 /* update nameoffile to the full name of the font, for error messages during font loading */
1235 const char* fullName = getFullName(fontRef);
1236 namelength = strlen(fullName);
1237 if (featString != NULL)
1238 namelength += strlen(featString) + 1;
1239 if (varString != NULL)
1240 namelength += strlen(varString) + 1;
1241 free(nameoffile);
1242 nameoffile = xmalloc(namelength + 4); /* +2 would be correct: initial space, final NUL */
1243 nameoffile[0] = ' ';
1244 strcpy((char*)nameoffile + 1, fullName);
1245
1246 if (scaled_size < 0) {
1247 font = createFont(fontRef, scaled_size);
1248 if (font != NULL) {
1249 Fixed dsize = D2Fix(getDesignSize(font));
1250 if (scaled_size == -1000)
1251 scaled_size = dsize;
1252 else
1253 scaled_size = zxnoverd(dsize, -scaled_size, 1000);
1254 deleteFont(font);
1255 }
1256 }
1257
1258 font = createFont(fontRef, scaled_size);
1259 if (font != NULL) {
1260 #ifdef XETEX_MAC
1261 /* decide whether to use AAT or OpenType rendering with this font */
1262 if (getReqEngine() == 'A') {
1263 rval = loadAATfont(fontRef, scaled_size, featString);
1264 if (rval == NULL)
1265 deleteFont(font);
1266 } else {
1267 if (getReqEngine() == 'O' || getReqEngine() == 'G' ||
1268 getFontTablePtr(font, kGSUB) != NULL || getFontTablePtr(font, kGPOS) != NULL)
1269 rval = loadOTfont(fontRef, font, scaled_size, featString);
1270
1271 /* loadOTfont failed or the above check was false */
1272 if (rval == NULL)
1273 rval = loadAATfont(fontRef, scaled_size, featString);
1274
1275 if (rval == NULL)
1276 deleteFont(font);
1277 }
1278 #else
1279 rval = loadOTfont(fontRef, font, scaled_size, featString);
1280 if (rval == NULL)
1281 deleteFont(font);
1282 #endif
1283 }
1284
1285 /* append the style and feature strings, so that \show\fontID will give a full result */
1286 if (varString != NULL && *varString != 0) {
1287 strcat((char*)nameoffile + 1, "/");
1288 strcat((char*)nameoffile + 1, varString);
1289 }
1290 if (featString != NULL && *featString != 0) {
1291 strcat((char*)nameoffile + 1, ":");
1292 strcat((char*)nameoffile + 1, featString);
1293 }
1294 namelength = strlen((char*)nameoffile + 1);
1295 }
1296 }
1297
1298 if (varString != NULL)
1299 free(varString);
1300
1301 if (featString != NULL)
1302 free(featString);
1303
1304 free(nameString);
1305
1306 return rval;
1307 }
1308
1309 void
1310 releasefontengine(void* engine, int type_flag)
1311 {
1312 #ifdef XETEX_MAC
1313 if (type_flag == AAT_FONT_FLAG) {
1314 CFRelease((CFDictionaryRef)engine);
1315 } else
1316 #endif
1317 if (type_flag == OTGR_FONT_FLAG) {
1318 deleteLayoutEngine((XeTeXLayoutEngine)engine);
1319 }
1320 }
1321
1322 /* params are given as 'integer' in the header file, but are really TeX scaled integers */
1323 void
1324 otgetfontmetrics(void* pEngine, scaled* ascent, scaled* descent, scaled* xheight, scaled* capheight, scaled* slant)
1325 {
1326 XeTeXLayoutEngine engine = (XeTeXLayoutEngine)pEngine;
1327 float a, d;
1328
1329 getAscentAndDescent(engine, &a, &d);
1330 *ascent = D2Fix(a);
1331 *descent = D2Fix(d);
1332
1333 *slant = D2Fix(Fix2D(getSlant(getFont(engine))) * getExtendFactor(engine)
1334 + getSlantFactor(engine));
1335
1336 /* get cap and x height from OS/2 table */
1337 getCapAndXHeight(engine, &a, &d);
1338 *capheight = D2Fix(a);
1339 *xheight = D2Fix(d);
1340
1341 /* fallback in case the font does not have OS/2 table */
1342 if (*xheight == 0) {
1343 int glyphID = mapCharToGlyph(engine, 'x');
1344 if (glyphID != 0) {
1345 getGlyphHeightDepth(engine, glyphID, &a, &d);
1346 *xheight = D2Fix(a);
1347 } else {
1348 *xheight = *ascent / 2; /* arbitrary figure if there's no 'x' in the font */
1349 }
1350 }
1351
1352 if (*capheight == 0) {
1353 int glyphID = mapCharToGlyph(engine, 'X');
1354 if (glyphID != 0) {
1355 getGlyphHeightDepth(engine, glyphID, &a, &d);
1356 *capheight = D2Fix(a);
1357 } else {
1358 *capheight = *ascent; /* arbitrary figure if there's no 'X' in the font */
1359 }
1360 }
1361 }
1362
1363 integer
1364 otfontget(integer what, void* pEngine)
1365 {
1366 XeTeXLayoutEngine engine = (XeTeXLayoutEngine)pEngine;
1367 XeTeXFont fontInst = getFont(engine);
1368 switch (what) {
1369 case XeTeX_count_glyphs:
1370 return countGlyphs(fontInst);
1371 break;
1372
1373 case XeTeX_count_features: /* ie Graphite features */
1374 return countGraphiteFeatures(engine);
1375 break;
1376
1377 case XeTeX_OT_count_scripts:
1378 return countScripts(fontInst);
1379 break;
1380 }
1381 return 0;
1382 }
1383
1384
1385 integer
1386 otfontget1(integer what, void* pEngine, integer param)
1387 {
1388 XeTeXLayoutEngine engine = (XeTeXLayoutEngine)pEngine;
1389 XeTeXFont fontInst = getFont(engine);
1390 switch (what) {
1391 case XeTeX_OT_count_languages:
1392 return countLanguages(fontInst, param);
1393 break;
1394
1395 case XeTeX_OT_script_code:
1396 return getIndScript(fontInst, param);
1397 break;
1398
1399 /* for graphite fonts...*/
1400 case XeTeX_feature_code:
1401 return getGraphiteFeatureCode(engine, param);
1402 break;
1403 case XeTeX_is_exclusive_feature:
1404 return 1;
1405 break;
1406 case XeTeX_count_selectors:
1407 return countGraphiteFeatureSettings(engine, param);
1408 break;
1409 }
1410 return 0;
1411 }
1412
1413
1414 integer
1415 otfontget2(integer what, void* pEngine, integer param1, integer param2)
1416 {
1417 XeTeXLayoutEngine engine = (XeTeXLayoutEngine)pEngine;
1418 XeTeXFont fontInst = getFont(engine);
1419 switch (what) {
1420 case XeTeX_OT_language_code:
1421 return getIndLanguage(fontInst, param1, param2);
1422 break;
1423
1424 case XeTeX_OT_count_features:
1425 return countFeatures(fontInst, param1, param2);
1426 break;
1427
1428 /* for graphite fonts */
1429 case XeTeX_selector_code:
1430 return getGraphiteFeatureSettingCode(engine, param1, param2);
1431 break;
1432 case XeTeX_is_default_selector:
1433 return getGraphiteFeatureDefaultSetting(engine, param1) == param2;
1434 break;
1435 }
1436
1437 return 0;
1438 }
1439
1440
1441 integer
1442 otfontget3(integer what, void* pEngine, integer param1, integer param2, integer param3)
1443 {
1444 XeTeXLayoutEngine engine = (XeTeXLayoutEngine)pEngine;
1445 XeTeXFont fontInst = getFont(engine);
1446 switch (what) {
1447 case XeTeX_OT_feature_code:
1448 return getIndFeature(fontInst, param1, param2, param3);
1449 break;
1450 }
1451
1452 return 0;
1453 }
1454
1455 void
1456 grprintfontname(integer what, void* pEngine, integer param1, integer param2)
1457 {
1458 char* name = NULL;
1459 XeTeXLayoutEngine engine = (XeTeXLayoutEngine)pEngine;
1460 switch (what) {
1461 case XeTeX_feature_name:
1462 name = getGraphiteFeatureLabel(engine, param1);
1463 break;
1464 case XeTeX_selector_name:
1465 name = getGraphiteFeatureSettingLabel(engine, param1, param2);
1466 break;
1467 }
1468
1469 if (name != NULL) {
1470 printcstring(name);
1471 gr_label_destroy(name);
1472 }
1473 }
1474
1475 integer
1476 grfontgetnamed(integer what, void* pEngine)
1477 {
1478 long rval = -1;
1479 XeTeXLayoutEngine engine = (XeTeXLayoutEngine)pEngine;
1480 switch (what) {
1481 case XeTeX_find_feature_by_name:
1482 rval = findGraphiteFeatureNamed(engine, (const char*)nameoffile + 1, namelength);
1483 break;
1484 }
1485 return rval;
1486 }
1487
1488 integer
1489 grfontgetnamed1(integer what, void* pEngine, integer param)
1490 {
1491 long rval = -1;
1492 XeTeXLayoutEngine engine = (XeTeXLayoutEngine)pEngine;
1493 switch (what) {
1494 case XeTeX_find_selector_by_name:
1495 rval = findGraphiteFeatureSettingNamed(engine, param, (const char*)nameoffile + 1, namelength);
1496 break;
1497 }
1498 return rval;
1499 }
1500
1501 #define XDV_FLAG_VERTICAL 0x0100
1502 #define XDV_FLAG_COLORED 0x0200
1503 #define XDV_FLAG_EXTEND 0x1000
1504 #define XDV_FLAG_SLANT 0x2000
1505 #define XDV_FLAG_EMBOLDEN 0x4000
1506
1507 #ifdef XETEX_MAC
1508 static UInt32
1509 cgColorToRGBA32(CGColorRef color)
1510 {
1511 const CGFloat *components = CGColorGetComponents(color);
1512
1513 UInt32 rval = (UInt8)(components[0] * 255.0 + 0.5);
1514 rval <<= 8;
1515 rval += (UInt8)(components[1] * 255.0 + 0.5);
1516 rval <<= 8;
1517 rval += (UInt8)(components[2] * 255.0 + 0.5);
1518 rval <<= 8;
1519 rval += (UInt8)(components[3] * 255.0 + 0.5);
1520 return rval;
1521 }
1522 #endif
1523
1524 static int xdvBufSize = 0;
1525
1526 int
1527 makeXDVGlyphArrayData(void* pNode)
1528 {
1529 unsigned char* cp;
1530 uint16_t* glyphIDs;
1531 memoryword* p = (memoryword*) pNode;
1532 void* glyph_info;
1533 FixedPoint* locations;
1534 Fixed width;
1535 uint16_t glyphCount = native_glyph_count(p);
1536
1537 int i = glyphCount * native_glyph_info_size + 8; /* to guarantee enough space in the buffer */
1538 if (i > xdvBufSize) {
1539 if (xdvbuffer != NULL)
1540 free(xdvbuffer);
1541 xdvBufSize = ((i / 1024) + 1) * 1024;
1542 xdvbuffer = (char*) xmalloc(xdvBufSize);
1543 }
1544
1545 glyph_info = native_glyph_info_ptr(p);
1546 locations = (FixedPoint*)glyph_info;
1547 glyphIDs = (uint16_t*)(locations + glyphCount);
1548
1549 cp = (unsigned char*)xdvbuffer;
1550
1551 width = node_width(p);
1552 *cp++ = (width >> 24) & 0xff;
1553 *cp++ = (width >> 16) & 0xff;
1554 *cp++ = (width >> 8) & 0xff;
1555 *cp++ = width & 0xff;
1556
1557 *cp++ = (glyphCount >> 8) & 0xff;
1558 *cp++ = glyphCount & 0xff;
1559
1560 for (i = 0; i < glyphCount; ++i) {
1561 Fixed x = locations[i].x;
1562 Fixed y = locations[i].y;
1563 *cp++ = (x >> 24) & 0xff;
1564 *cp++ = (x >> 16) & 0xff;
1565 *cp++ = (x >> 8) & 0xff;
1566 *cp++ = x & 0xff;
1567 *cp++ = (y >> 24) & 0xff;
1568 *cp++ = (y >> 16) & 0xff;
1569 *cp++ = (y >> 8) & 0xff;
1570 *cp++ = y & 0xff;
1571 }
1572
1573 for (i = 0; i < glyphCount; ++i) {
1574 uint16_t g = glyphIDs[i];
1575 *cp++ = (g >> 8) & 0xff;
1576 *cp++ = g & 0xff;
1577 }
1578
1579 return ((char*)cp - xdvbuffer);
1580 }
1581
1582 int
1583 makefontdef(integer f)
1584 {
1585 uint16_t flags = 0;
1586 uint32_t rgba;
1587 Fixed size;
1588 char* filename;
1589 uint32_t index;
1590 uint8_t filenameLen;
1591 int fontDefLength;
1592 char* cp;
1593 /* PlatformFontRef fontRef = 0; */
1594 float extend = 1.0;
1595 float slant = 0.0;
1596 float embolden = 0.0;
1597
1598 #ifdef XETEX_MAC
1599 CFDictionaryRef attributes = NULL;
1600
1601 if (fontarea[f] == AAT_FONT_FLAG) {
1602 CTFontRef font;
1603 CGColorRef color;
1604 CGAffineTransform t;
1605 CFNumberRef emboldenNumber;
1606 CGFloat fSize;
1607
1608 attributes = (CFDictionaryRef) fontlayoutengine[f];
1609 font = CFDictionaryGetValue(attributes, kCTFontAttributeName);
1610
1611 filename = getFileNameFromCTFont(font, &index);
1612 assert(filename);
1613
1614 if (CFDictionaryGetValue(attributes, kCTVerticalFormsAttributeName))
1615 flags |= XDV_FLAG_VERTICAL;
1616
1617 color = (CGColorRef) CFDictionaryGetValue(attributes, kCTForegroundColorAttributeName);
1618 if (color)
1619 rgba = cgColorToRGBA32(color);
1620
1621 t = CTFontGetMatrix(font);
1622 extend = t.a;
1623 slant = t.c;
1624
1625 emboldenNumber = CFDictionaryGetValue(attributes, kXeTeXEmboldenAttributeName);
1626 if (emboldenNumber)
1627 CFNumberGetValue(emboldenNumber, kCFNumberFloatType, &embolden);
1628
1629 fSize = CTFontGetSize(font);
1630 size = D2Fix(fSize);
1631 } else
1632 #endif
1633 if (fontarea[f] == OTGR_FONT_FLAG) {
1634 XeTeXLayoutEngine engine;
1635
1636 engine = (XeTeXLayoutEngine)fontlayoutengine[f];
1637 /* fontRef = */ getFontRef(engine);
1638 filename = getFontFilename(engine, &index);
1639 assert(filename);
1640
1641 rgba = getRgbValue(engine);
1642 if ((fontflags[f] & FONT_FLAGS_VERTICAL) != 0)
1643 flags |= XDV_FLAG_VERTICAL;
1644
1645 extend = getExtendFactor(engine);
1646 slant = getSlantFactor(engine);
1647 embolden = getEmboldenFactor(engine);
1648
1649 size = D2Fix(getPointSize(engine));
1650 } else {
1651 fprintf(stderr, "\n! Internal error: bad native font flag in `make_font_def'\n");
1652 exit(3);
1653 }
1654
1655 filenameLen = strlen(filename);
1656
1657 /* parameters after internal font ID:
1658 // size[4]
1659 // flags[2]
1660 // l[1] n[l]
1661 // if flags & COLORED:
1662 // c[4]
1663 */
1664
1665 fontDefLength
1666 = 4 /* size */
1667 + 2 /* flags */
1668 + 1 /* name length */
1669 + filenameLen
1670 + 4 /* face index */;
1671
1672 if ((fontflags[f] & FONT_FLAGS_COLORED) != 0) {
1673 fontDefLength += 4; /* 32-bit RGBA value */
1674 flags |= XDV_FLAG_COLORED;
1675 }
1676
1677 if (extend != 1.0) {
1678 fontDefLength += 4;
1679 flags |= XDV_FLAG_EXTEND;
1680 }
1681 if (slant != 0.0) {
1682 fontDefLength += 4;
1683 flags |= XDV_FLAG_SLANT;
1684 }
1685 if (embolden != 0.0) {
1686 fontDefLength += 4;
1687 flags |= XDV_FLAG_EMBOLDEN;
1688 }
1689
1690 if (fontDefLength > xdvBufSize) {
1691 if (xdvbuffer != NULL)
1692 free(xdvbuffer);
1693 xdvBufSize = ((fontDefLength / 1024) + 1) * 1024;
1694 xdvbuffer = (char*) xmalloc(xdvBufSize);
1695 }
1696 cp = xdvbuffer;
1697
1698 *(Fixed*)cp = SWAP32(size);
1699 cp += 4;
1700
1701 *(uint16_t*)cp = SWAP16(flags);
1702 cp += 2;
1703
1704 *(uint8_t*)cp = filenameLen;
1705 cp += 1;
1706 memcpy(cp, filename, filenameLen);
1707 cp += filenameLen;
1708
1709 *(uint32_t*)cp = SWAP32(index);
1710 cp += 4;
1711
1712 if ((fontflags[f] & FONT_FLAGS_COLORED) != 0) {
1713 *(uint32_t*)cp = SWAP32(rgba);
1714 cp += 4;
1715 }
1716
1717 if (flags & XDV_FLAG_EXTEND) {
1718 Fixed f = D2Fix(extend);
1719 *(uint32_t*)(cp) = SWAP32(f);
1720 cp += 4;
1721 }
1722 if (flags & XDV_FLAG_SLANT) {
1723 Fixed f = D2Fix(slant);
1724 *(uint32_t*)(cp) = SWAP32(f);
1725 cp += 4;
1726 }
1727 if (flags & XDV_FLAG_EMBOLDEN) {
1728 Fixed f = D2Fix(embolden);
1729 *(uint32_t*)(cp) = SWAP32(f);
1730 cp += 4;
1731 }
1732
1733 free((char*) filename);
1734
1735 return fontDefLength;
1736 }
1737
1738 int
1739 applymapping(void* pCnv, uint16_t* txtPtr, int txtLen)
1740 {
1741 TECkit_Converter cnv = (TECkit_Converter)pCnv;
1742 UInt32 inUsed, outUsed;
1743 TECkit_Status status;
1744 static UInt32 outLength = 0;
1745
1746 /* allocate outBuffer if not big enough */
1747 if (outLength < txtLen * sizeof(UniChar) + 32) {
1748 if (mappedtext != 0)
1749 free(mappedtext);
1750 outLength = txtLen * sizeof(UniChar) + 32;
1751 mappedtext = xmalloc(outLength);
1752 }
1753
1754 /* try the mapping */
1755 retry:
1756 status = TECkit_ConvertBuffer(cnv,
1757 (Byte*)txtPtr, txtLen * sizeof(UniChar), &inUsed,
1758 (Byte*)mappedtext, outLength, &outUsed, true);
1759 TECkit_ResetConverter(cnv);
1760
1761 switch (status) {
1762 case kStatus_NoError:
1763 txtPtr = (UniChar*)mappedtext;
1764 return outUsed / sizeof(UniChar);
1765
1766 case kStatus_OutputBufferFull:
1767 outLength += (txtLen * sizeof(UniChar)) + 32;
1768 free(mappedtext);
1769 mappedtext = xmalloc(outLength);
1770 goto retry;
1771
1772 default:
1773 return 0;
1774 }
1775 }
1776
1777 static void
1778 snap_zone(scaled* value, scaled snap_value, scaled fuzz)
1779 {
1780 scaled difference = *value - snap_value;
1781 if (difference <= fuzz && difference >= -fuzz)
1782 *value = snap_value;
1783 }
1784
1785 void
1786 getnativecharheightdepth(integer font, integer ch, scaled* height, scaled* depth)
1787 {
1788 #define QUAD(f) fontinfo[6+parambase[f]].cint
1789 #define X_HEIGHT(f) fontinfo[5+parambase[f]].cint
1790 #define CAP_HEIGHT(f) fontinfo[8+parambase[f]].cint
1791
1792 float ht = 0.0;
1793 float dp = 0.0;
1794 Fixed fuzz;
1795
1796 #ifdef XETEX_MAC
1797 if (fontarea[font] == AAT_FONT_FLAG) {
1798 CFDictionaryRef attributes = (CFDictionaryRef)(fontlayoutengine[font]);
1799 int gid = MapCharToGlyph_AAT(attributes, ch);
1800 GetGlyphHeightDepth_AAT(attributes, gid, &ht, &dp);
1801 } else
1802 #endif
1803 if (fontarea[font] == OTGR_FONT_FLAG) {
1804 XeTeXLayoutEngine engine = (XeTeXLayoutEngine)fontlayoutengine[font];
1805 int gid = mapCharToGlyph(engine, ch);
1806 getGlyphHeightDepth(engine, gid, &ht, &dp);
1807 } else {
1808 fprintf(stderr, "\n! Internal error: bad native font flag in `get_native_char_height_depth`\n");
1809 exit(3);
1810 }
1811
1812 *height = D2Fix(ht);
1813 *depth = D2Fix(dp);
1814
1815 /* snap to "known" zones for baseline, x-height, cap-height if within 4% of em-size */
1816 fuzz = QUAD(font) / 25;
1817 snap_zone(depth, 0, fuzz);
1818 snap_zone(height, 0, fuzz);
1819 snap_zone(height, X_HEIGHT(font), fuzz);
1820 snap_zone(height, CAP_HEIGHT(font), fuzz);
1821 }
1822
1823 scaled
1824 getnativecharht(integer f, integer c)
1825 {
1826 scaled h, d;
1827 getnativecharheightdepth(f, c, &h, &d);
1828 return h;
1829 }
1830
1831 scaled
1832 getnativechardp(integer f, integer c)
1833 {
1834 scaled h, d;
1835 getnativecharheightdepth(f, c, &h, &d);
1836 return d;
1837 }
1838
1839 void
1840 getnativecharsidebearings(integer font, integer ch, scaled* lsb, scaled* rsb)
1841 {
1842 float l, r;
1843
1844 #ifdef XETEX_MAC
1845 if (fontarea[font] == AAT_FONT_FLAG) {
1846 CFDictionaryRef attributes = (CFDictionaryRef)(fontlayoutengine[font]);
1847 int gid = MapCharToGlyph_AAT(attributes, ch);
1848 GetGlyphSidebearings_AAT(attributes, gid, &l, &r);
1849 } else
1850 #endif
1851 if (fontarea[font] == OTGR_FONT_FLAG) {
1852 XeTeXLayoutEngine engine = (XeTeXLayoutEngine)fontlayoutengine[font];
1853 int gid = mapCharToGlyph(engine, ch);
1854 getGlyphSidebearings(engine, gid, &l, &r);
1855 } else {
1856 fprintf(stderr, "\n! Internal error: bad native font flag in `get_native_char_side_bearings'\n");
1857 exit(3);
1858 }
1859
1860 *lsb = D2Fix(l);
1861 *rsb = D2Fix(r);
1862 }
1863
1864 scaled
1865 getglyphbounds(integer font, integer edge, integer gid)
1866 {
1867 /* edge codes 1,2,3,4 => L T R B */
1868 float a, b;
1869
1870 #ifdef XETEX_MAC
1871 if (fontarea[font] == AAT_FONT_FLAG) {
1872 CFDictionaryRef attributes = (CFDictionaryRef)(fontlayoutengine[font]);
1873 if (edge & 1)
1874 GetGlyphSidebearings_AAT(attributes, gid, &a, &b);
1875 else
1876 GetGlyphHeightDepth_AAT(attributes, gid, &a, &b);
1877 } else
1878 #endif
1879 if (fontarea[font] == OTGR_FONT_FLAG) {
1880 XeTeXLayoutEngine engine = (XeTeXLayoutEngine)fontlayoutengine[font];
1881 if (edge & 1)
1882 getGlyphSidebearings(engine, gid, &a, &b);
1883 else
1884 getGlyphHeightDepth(engine, gid, &a, &b);
1885 } else {
1886 fprintf(stderr, "\n! Internal error: bad native font flag in `get_glyph_bounds'\n");
1887 exit(3);
1888 }
1889 return D2Fix((edge <= 2) ? a : b);
1890 }
1891
1892 scaled
1893 getnativecharic(integer f, integer c)
1894 {
1895 scaled lsb, rsb;
1896 getnativecharsidebearings(f, c, &lsb, &rsb);
1897 if (rsb < 0)
1898 return fontletterspace[f] - rsb;
1899 else
1900 return fontletterspace[f];
1901 }
1902
1903 scaled
1904 getnativecharwd(integer f, integer c)
1905 {
1906 scaled wd = 0;
1907 #ifdef XETEX_MAC
1908 if (fontarea[f] == AAT_FONT_FLAG) {
1909 CFDictionaryRef attributes = (CFDictionaryRef)(fontlayoutengine[f]);
1910 int gid = MapCharToGlyph_AAT(attributes, c);
1911 wd = D2Fix(GetGlyphWidth_AAT(attributes, gid));
1912 } else
1913 #endif
1914 if (fontarea[f] == OTGR_FONT_FLAG) {
1915 XeTeXLayoutEngine engine = (XeTeXLayoutEngine)fontlayoutengine[f];
1916 int gid = mapCharToGlyph(engine, c);
1917 wd = D2Fix(getGlyphWidthFromEngine(engine, gid));
1918 } else {
1919 fprintf(stderr, "\n! Internal error: bad native font flag in `get_native_char_wd'\n");
1920 exit(3);
1921 }
1922 return wd;
1923 }
1924
1925 uint16_t
1926 get_native_glyph(void* pNode, unsigned index)
1927 {
1928 memoryword* node = (memoryword*)pNode;
1929 FixedPoint* locations = (FixedPoint*)native_glyph_info_ptr(node);
1930 uint16_t* glyphIDs = (uint16_t*)(locations + native_glyph_count(node));
1931 if (index >= native_glyph_count(node))
1932 return 0;
1933 else
1934 return glyphIDs[index];
1935 }
1936
1937 void
1938 store_justified_native_glyphs(void* pNode)
1939 {
1940 memoryword* node = (memoryword*)pNode;
1941 unsigned f = native_font(node);
1942
1943 #ifdef XETEX_MAC /* separate Mac-only codepath for AAT fonts */
1944 if (fontarea[f] == AAT_FONT_FLAG) {
1945 (void)DoAATLayout(node, 1);
1946 return;
1947 }
1948 #endif
1949
1950 /* save desired width */
1951 int savedWidth = node_width(node);
1952
1953 measure_native_node(node, 0);
1954
1955 if (node_width(node) != savedWidth) {
1956 /* see how much adjustment is needed overall */
1957 double justAmount = Fix2D(savedWidth - node_width(node));
1958
1959 /* apply justification to spaces (or if there are none, distribute it to all glyphs as a last resort) */
1960 FixedPoint* locations = (FixedPoint*)native_glyph_info_ptr(node);
1961 uint16_t* glyphIDs = (uint16_t*)(locations + native_glyph_count(node));
1962 int glyphCount = native_glyph_count(node);
1963 int spaceCount = 0, i;
1964
1965 int spaceGlyph = mapchartoglyph(f, ' ');
1966 for (i = 0; i < glyphCount; ++i)
1967 if (glyphIDs[i] == spaceGlyph)
1968 spaceCount++;
1969
1970 if (spaceCount > 0) {
1971 double adjustment = 0;
1972 int spaceIndex = 0;
1973 for (i = 0; i < glyphCount; ++i) {
1974 locations[i].x = D2Fix(Fix2D(locations[i].x) + adjustment);
1975 if (glyphIDs[i] == spaceGlyph) {
1976 spaceIndex++;
1977 adjustment = justAmount * spaceIndex / spaceCount;
1978 }
1979 }
1980 } else {
1981 for (i = 1; i < glyphCount; ++i)
1982 locations[i].x = D2Fix(Fix2D(locations[i].x) + justAmount * i / (glyphCount - 1));
1983 }
1984
1985 node_width(node) = savedWidth;
1986 }
1987 }
1988
1989 void
1990 measure_native_node(void* pNode, int use_glyph_metrics)
1991 {
1992 memoryword* node = (memoryword*)pNode;
1993 int txtLen = native_length(node);
1994 uint16_t* txtPtr = (uint16_t*)(node + native_node_size);
1995
1996 unsigned f = native_font(node);
1997
1998 #ifdef XETEX_MAC
1999 if (fontarea[f] == AAT_FONT_FLAG) {
2000 /* we're using this font in AAT mode, so fontlayoutengine[f] is actually a CFDictionaryRef */
2001 DoAATLayout(node, 0);
2002 } else
2003 #endif
2004 if (fontarea[f] == OTGR_FONT_FLAG) {
2005 /* using this font in OT Layout mode, so fontlayoutengine[f] is actually a XeTeXLayoutEngine */
2006
2007 XeTeXLayoutEngine engine = (XeTeXLayoutEngine)(fontlayoutengine[f]);
2008
2009 FixedPoint* locations = NULL;
2010 uint16_t* glyphIDs;
2011 Fixed* glyphAdvances = NULL;
2012 int totalGlyphCount = 0;
2013
2014 /* need to find direction runs within the text, and call layoutChars separately for each */
2015
2016 UBiDiDirection dir;
2017 void* glyph_info = 0;
2018 static FloatPoint* positions = 0;
2019 static float* advances = 0;
2020 static uint32_t* glyphs = 0;
2021
2022 UBiDi* pBiDi = ubidi_open();
2023
2024 UErrorCode errorCode = U_ZERO_ERROR;
2025 ubidi_setPara(pBiDi, (const UChar*) txtPtr, txtLen, getDefaultDirection(engine), NULL, &errorCode);
2026
2027 dir = ubidi_getDirection(pBiDi);
2028 if (dir == UBIDI_MIXED) {
2029 /* we actually do the layout twice here, once to count glyphs and then again to get them;
2030 which is inefficient, but i figure that MIXED is a relatively rare occurrence, so i can't be
2031 bothered to deal with the memory reallocation headache of doing it differently
2032 */
2033 int nRuns = ubidi_countRuns(pBiDi, &errorCode);
2034 double width = 0;
2035 int i, runIndex;
2036 int32_t logicalStart, length;
2037 for (runIndex = 0; runIndex < nRuns; ++runIndex) {
2038 dir = ubidi_getVisualRun(pBiDi, runIndex, &logicalStart, &length);
2039 totalGlyphCount += layoutChars(engine, txtPtr, logicalStart, length, txtLen, (dir == UBIDI_RTL));
2040 }
2041
2042 if (totalGlyphCount > 0) {
2043 double x, y;
2044 glyph_info = xcalloc(totalGlyphCount, native_glyph_info_size);
2045 locations = (FixedPoint*)glyph_info;
2046 glyphIDs = (uint16_t*)(locations + totalGlyphCount);
2047 glyphAdvances = (Fixed*) xcalloc(totalGlyphCount, sizeof(Fixed));
2048 totalGlyphCount = 0;
2049
2050 x = y = 0.0;
2051 for (runIndex = 0; runIndex < nRuns; ++runIndex) {
2052 int nGlyphs;
2053 dir = ubidi_getVisualRun(pBiDi, runIndex, &logicalStart, &length);
2054 nGlyphs = layoutChars(engine, txtPtr, logicalStart, length, txtLen,
2055 (dir == UBIDI_RTL));
2056
2057 glyphs = (uint32_t*) xcalloc(nGlyphs, sizeof(uint32_t));
2058 positions = (FloatPoint*) xcalloc(nGlyphs + 1, sizeof(FloatPoint));
2059 advances = (float*) xcalloc(nGlyphs, sizeof(float));
2060
2061 getGlyphs(engine, glyphs);
2062 getGlyphAdvances(engine, advances);
2063 getGlyphPositions(engine, positions);
2064
2065 for (i = 0; i < nGlyphs; ++i) {
2066 glyphIDs[totalGlyphCount] = glyphs[i];
2067 locations[totalGlyphCount].x = D2Fix(positions[i].x + x);
2068 locations[totalGlyphCount].y = D2Fix(positions[i].y + y);
2069 glyphAdvances[totalGlyphCount] = D2Fix(advances[i]);
2070 ++totalGlyphCount;
2071 }
2072 x += positions[nGlyphs].x;
2073 y += positions[nGlyphs].y;
2074
2075 free(glyphs);
2076 free(positions);
2077 free(advances);
2078 }
2079 width = x;
2080 }
2081
2082 node_width(node) = D2Fix(width);
2083 native_glyph_count(node) = totalGlyphCount;
2084 native_glyph_info_ptr(node) = glyph_info;
2085 } else {
2086 double width = 0;
2087 totalGlyphCount = layoutChars(engine, txtPtr, 0, txtLen, txtLen, (dir == UBIDI_RTL));
2088
2089 glyphs = (uint32_t*) xcalloc(totalGlyphCount, sizeof(uint32_t));
2090 positions = (FloatPoint*) xcalloc(totalGlyphCount + 1, sizeof(FloatPoint));
2091 advances = (float*) xcalloc(totalGlyphCount, sizeof(float));
2092
2093 getGlyphs(engine, glyphs);
2094 getGlyphAdvances(engine, advances);
2095 getGlyphPositions(engine, positions);
2096
2097 if (totalGlyphCount > 0) {
2098 int i;
2099 glyph_info = xcalloc(totalGlyphCount, native_glyph_info_size);
2100 locations = (FixedPoint*)glyph_info;
2101 glyphIDs = (uint16_t*)(locations + totalGlyphCount);
2102 glyphAdvances = (Fixed*) xcalloc(totalGlyphCount, sizeof(Fixed));
2103 for (i = 0; i < totalGlyphCount; ++i) {
2104 glyphIDs[i] = glyphs[i];
2105 glyphAdvances[i] = D2Fix(advances[i]);
2106 locations[i].x = D2Fix(positions[i].x);
2107 locations[i].y = D2Fix(positions[i].y);
2108 }
2109 width = positions[totalGlyphCount].x;
2110 }
2111
2112 node_width(node) = D2Fix(width);
2113 native_glyph_count(node) = totalGlyphCount;
2114 native_glyph_info_ptr(node) = glyph_info;
2115
2116 free(glyphs);
2117 free(positions);
2118 free(advances);
2119 }
2120
2121 ubidi_close(pBiDi);
2122
2123
2124 if (fontletterspace[f] != 0) {
2125 Fixed lsDelta = 0;
2126 Fixed lsUnit = fontletterspace[f];
2127 int i;
2128 for (i = 0; i < totalGlyphCount; ++i) {
2129 if (glyphAdvances[i] == 0 && lsDelta != 0)
2130 lsDelta -= lsUnit;
2131 locations[i].x += lsDelta;
2132 lsDelta += lsUnit;
2133 }
2134 if (lsDelta != 0) {
2135 lsDelta -= lsUnit;
2136 node_width(node) += lsDelta;
2137 }
2138 }
2139 free(glyphAdvances);
2140 } else {
2141 fprintf(stderr, "\n! Internal error: bad native font flag in `measure_native_node'\n");
2142 exit(3);
2143 }
2144
2145 if (use_glyph_metrics == 0 || native_glyph_count(node) == 0) {
2146 /* for efficiency, height and depth are the font's ascent/descent,
2147 not true values based on the actual content of the word,
2148 unless use_glyph_metrics is non-zero */
2149 node_height(node) = heightbase[f];
2150 node_depth(node) = depthbase[f];
2151 } else {
2152 /* this iterates over the glyph data whether it comes from AAT or OT layout */
2153 FixedPoint* locations = (FixedPoint*)native_glyph_info_ptr(node);
2154 uint16_t* glyphIDs = (uint16_t*)(locations + native_glyph_count(node));
2155 float yMin = 65536.0;
2156 float yMax = -65536.0;
2157 int i;
2158 for (i = 0; i < native_glyph_count(node); ++i) {
2159 float ht, dp;
2160 float y = Fix2D(-locations[i].y); /* NB negative is upwards in locations[].y! */
2161
2162 GlyphBBox bbox;
2163 if (getCachedGlyphBBox(f, glyphIDs[i], &bbox) == 0) {
2164 #ifdef XETEX_MAC
2165 if (fontarea[f] == AAT_FONT_FLAG)
2166 GetGlyphBBox_AAT((CFDictionaryRef)(fontlayoutengine[f]), glyphIDs[i], &bbox);
2167 else
2168 #endif
2169 if (fontarea[f] == OTGR_FONT_FLAG)
2170 getGlyphBounds((XeTeXLayoutEngine)(fontlayoutengine[f]), glyphIDs[i], &bbox);
2171
2172 cacheGlyphBBox(f, glyphIDs[i], &bbox);
2173 }
2174
2175 ht = bbox.yMax;
2176 dp = -bbox.yMin;
2177
2178 if (y + ht > yMax)
2179 yMax = y + ht;
2180 if (y - dp < yMin)
2181 yMin = y - dp;
2182 }
2183 node_height(node) = D2Fix(yMax);
2184 node_depth(node) = -D2Fix(yMin);
2185 }
2186 }
2187
2188 Fixed
2189 get_native_italic_correction(void* pNode)
2190 {
2191 memoryword* node = (memoryword*) pNode;
2192 unsigned f = native_font(node);
2193 unsigned n = native_glyph_count(node);
2194 if (n > 0) {
2195 FixedPoint* locations = (FixedPoint*)native_glyph_info_ptr(node);
2196 uint16_t* glyphIDs = (uint16_t*)(locations + n);
2197
2198 #ifdef XETEX_MAC
2199 if (fontarea[f] == AAT_FONT_FLAG)
2200 return D2Fix(GetGlyphItalCorr_AAT((CFDictionaryRef)(fontlayoutengine[f]), glyphIDs[n-1]))
2201 + fontletterspace[f];
2202 #endif
2203 if (fontarea[f] == OTGR_FONT_FLAG)
2204 return D2Fix(getGlyphItalCorr((XeTeXLayoutEngine)(fontlayoutengine[f]), glyphIDs[n-1]))
2205 + fontletterspace[f];
2206 }
2207
2208 return 0;
2209 }
2210
2211
2212 Fixed
2213 get_native_glyph_italic_correction(void* pNode)
2214 {
2215 memoryword* node = (memoryword*) pNode;
2216 uint16_t gid = native_glyph(node);
2217 unsigned f = native_font(node);
2218
2219 #ifdef XETEX_MAC
2220 if (fontarea[f] == AAT_FONT_FLAG)
2221 return D2Fix(GetGlyphItalCorr_AAT((CFDictionaryRef)(fontlayoutengine[f]), gid));
2222 #endif
2223 if (fontarea[f] == OTGR_FONT_FLAG)
2224 return D2Fix(getGlyphItalCorr((XeTeXLayoutEngine)(fontlayoutengine[f]), gid));
2225
2226 return 0; /* can't actually happen */
2227 }
2228
2229 void
2230 measure_native_glyph(void* pNode, int use_glyph_metrics)
2231 {
2232 memoryword* node = (memoryword*) pNode;
2233 uint16_t gid = native_glyph(node);
2234 unsigned f = native_font(node);
2235
2236 float ht = 0.0;
2237 float dp = 0.0;
2238
2239 #ifdef XETEX_MAC
2240 if (fontarea[f] == AAT_FONT_FLAG) {
2241 CFDictionaryRef attributes = (CFDictionaryRef)(fontlayoutengine[f]);
2242 node_width(node) = D2Fix(GetGlyphWidth_AAT(attributes, gid));
2243 if (use_glyph_metrics)
2244 GetGlyphHeightDepth_AAT(attributes, gid, &ht, &dp);
2245 } else
2246 #endif
2247 if (fontarea[f] == OTGR_FONT_FLAG) {
2248 XeTeXLayoutEngine engine = (XeTeXLayoutEngine)fontlayoutengine[f];
2249 XeTeXFont fontInst = getFont(engine);
2250 node_width(node) = D2Fix(getGlyphWidth(fontInst, gid));
2251 if (use_glyph_metrics)
2252 getGlyphHeightDepth(engine, gid, &ht, &dp);
2253 } else {
2254 fprintf(stderr, "\n! Internal error: bad native font flag in `measure_native_glyph'\n");
2255 exit(3);
2256 }
2257
2258 if (use_glyph_metrics) {
2259 node_height(node) = D2Fix(ht);
2260 node_depth(node) = D2Fix(dp);
2261 } else {
2262 node_height(node) = heightbase[f];
2263 node_depth(node) = depthbase[f];
2264 }
2265 }
2266
2267 integer
2268 mapchartoglyph(integer font, integer ch)
2269 {
2270 if (ch > 0x10ffff || ((ch >= 0xd800) && (ch <= 0xdfff)))
2271 return 0;
2272 #ifdef XETEX_MAC
2273 if (fontarea[font] == AAT_FONT_FLAG)
2274 return MapCharToGlyph_AAT((CFDictionaryRef)(fontlayoutengine[font]), ch);
2275 else
2276 #endif
2277 if (fontarea[font] == OTGR_FONT_FLAG)
2278 return mapCharToGlyph((XeTeXLayoutEngine)(fontlayoutengine[font]), ch);
2279 else {
2280 fprintf(stderr, "\n! Internal error: bad native font flag in `map_char_to_glyph'\n");
2281 exit(3);
2282 }
2283 }
2284
2285 integer
2286 mapglyphtoindex(integer font)
2287 /* glyph name is at nameoffile+1 */
2288 {
2289 #ifdef XETEX_MAC
2290 if (fontarea[font] == AAT_FONT_FLAG)
2291 return MapGlyphToIndex_AAT((CFDictionaryRef)(fontlayoutengine[font]), (const char*)nameoffile + 1);
2292 else
2293 #endif
2294 if (fontarea[font] == OTGR_FONT_FLAG)
2295 return mapGlyphToIndex((XeTeXLayoutEngine)(fontlayoutengine[font]), (const char*)nameoffile + 1);
2296 else {
2297 fprintf(stderr, "\n! Internal error: bad native font flag in `map_glyph_to_index'\n");
2298 exit(3);
2299 }
2300 }
2301
2302 integer
2303 getfontcharrange(integer font, int first)
2304 {
2305 #ifdef XETEX_MAC
2306 if (fontarea[font] == AAT_FONT_FLAG)
2307 return GetFontCharRange_AAT((CFDictionaryRef)(fontlayoutengine[font]), first);
2308 else
2309 #endif
2310 if (fontarea[font] == OTGR_FONT_FLAG)
2311 return getFontCharRange((XeTeXLayoutEngine)(fontlayoutengine[font]), first);
2312 else {
2313 fprintf(stderr, "\n! Internal error: bad native font flag in `get_font_char_range'\n");
2314 exit(3);
2315 }
2316 }
2317
2318 Fixed D2Fix(double d)
2319 {
2320 Fixed rval = (int)(d * 65536.0 + 0.5);
2321 return rval;
2322 }
2323
2324 double Fix2D(Fixed f)
2325 {
2326 double rval = f / 65536.0;
2327 return rval;
2328 }
2329
2330 /* these are here, not XeTeX_mac.c, because we need stubs on other platforms */
2331 void
2332 aatgetfontmetrics(CFDictionaryRef attributes, integer* ascent, integer* descent, integer* xheight, integer* capheight, integer* slant)
2333 {
2334 #ifdef XETEX_MAC
2335 CTFontRef font = fontFromAttributes(attributes);
2336
2337 *ascent = D2Fix(CTFontGetAscent(font));
2338 *descent = D2Fix(CTFontGetDescent(font));
2339 *xheight = D2Fix(CTFontGetXHeight(font));
2340 *capheight = D2Fix(CTFontGetCapHeight(font));
2341 *slant = D2Fix(tan(-CTFontGetSlantAngle(font) * M_PI / 180.0));
2342 #endif
2343 }
2344
2345 int
2346 aatfontget(int what, CFDictionaryRef attributes)
2347 {
2348 int rval = -1;
2349
2350 #ifdef XETEX_MAC
2351 CTFontRef font = fontFromAttributes(attributes);
2352 CFArrayRef list;
2353
2354 switch (what) {
2355 case XeTeX_count_glyphs:
2356 rval = CTFontGetGlyphCount(font);
2357 break;
2358
2359 case XeTeX_count_features:
2360 list = CTFontCopyFeatures(font);
2361 if (list) {
2362 rval = CFArrayGetCount(list);
2363 CFRelease(list);
2364 }
2365 break;
2366 }
2367 #endif
2368 return rval;
2369 }
2370
2371 int
2372 aatfontget1(int what, CFDictionaryRef attributes, int param)
2373 {
2374 int rval = -1;
2375
2376 #ifdef XETEX_MAC
2377 CTFontRef font = fontFromAttributes(attributes);
2378
2379 switch (what) {
2380 case XeTeX_feature_code:
2381 {
2382 CFArrayRef features = CTFontCopyFeatures(font);
2383 if (features) {
2384 if (CFArrayGetCount(features) > param) {
2385 CFDictionaryRef feature = CFArrayGetValueAtIndex(features, param);
2386 CFNumberRef identifier = CFDictionaryGetValue(feature, kCTFontFeatureTypeIdentifierKey);
2387 if (identifier)
2388 CFNumberGetValue(identifier, kCFNumberIntType, &rval);
2389 }
2390 CFRelease(features);
2391 }
2392 break;
2393 }
2394
2395 case XeTeX_is_exclusive_feature:
2396 {
2397 CFArrayRef features = CTFontCopyFeatures(font);
2398 if (features) {
2399 CFBooleanRef value;
2400 CFDictionaryRef feature = findDictionaryInArrayWithIdentifier(features, kCTFontFeatureTypeIdentifierKey, param);
2401 Boolean found = CFDictionaryGetValueIfPresent(feature, kCTFontFeatureTypeExclusiveKey, (const void **)&value);
2402 if (found)
2403 rval = CFBooleanGetValue(value);
2404 CFRelease(features);
2405 }
2406 break;
2407 }
2408
2409 case XeTeX_count_selectors:
2410 {
2411 CFArrayRef features = CTFontCopyFeatures(font);
2412 if (features) {
2413 CFDictionaryRef feature = findDictionaryInArrayWithIdentifier(features, kCTFontFeatureTypeIdentifierKey, param);
2414 if (feature) {
2415 CFArrayRef selectors = CFDictionaryGetValue(feature, kCTFontFeatureTypeSelectorsKey);
2416 if (selectors)
2417 rval = CFArrayGetCount(selectors);
2418 }
2419 CFRelease(features);
2420 }
2421 break;
2422 }
2423 }
2424 #endif
2425
2426 return rval;
2427 }
2428
2429 int
2430 aatfontget2(int what, CFDictionaryRef attributes, int param1, int param2)
2431 {
2432 int rval = -1;
2433
2434 #ifdef XETEX_MAC
2435 CTFontRef font = fontFromAttributes(attributes);
2436 CFArrayRef features = CTFontCopyFeatures(font);
2437 if (features) {
2438 CFDictionaryRef feature = findDictionaryInArrayWithIdentifier(features, kCTFontFeatureTypeIdentifierKey, param1);
2439 if (feature) {
2440 CFArrayRef selectors = CFDictionaryGetValue(feature, kCTFontFeatureTypeSelectorsKey);
2441 if (selectors) {
2442 CFDictionaryRef selector;
2443 switch (what) {
2444 case XeTeX_selector_code:
2445 if (CFArrayGetCount(selectors) > param2) {
2446 CFNumberRef identifier;
2447 selector = CFArrayGetValueAtIndex(selectors, param2);
2448 identifier = CFDictionaryGetValue(selector, kCTFontFeatureSelectorIdentifierKey);
2449 if (identifier)
2450 CFNumberGetValue(identifier, kCFNumberIntType, &rval);
2451 }
2452 break;
2453 case XeTeX_is_default_selector:
2454 selector = findDictionaryInArrayWithIdentifier(selectors, kCTFontFeatureSelectorIdentifierKey, param2);
2455 if (selector) {
2456 CFBooleanRef isDefault;
2457 Boolean found = CFDictionaryGetValueIfPresent(selector, kCTFontFeatureSelectorDefaultKey, (const void **)&isDefault);
2458 if (found)
2459 rval = CFBooleanGetValue(isDefault);
2460 }
2461 break;
2462 }
2463 }
2464 }
2465 CFRelease(features);
2466 }
2467 #endif
2468
2469 return rval;
2470 }
2471
2472 int
2473 aatfontgetnamed(int what, CFDictionaryRef attributes)
2474 {
2475 int rval = -1;
2476
2477 #ifdef XETEX_MAC
2478 if (what == XeTeX_find_feature_by_name)
2479 {
2480 CTFontRef font = fontFromAttributes(attributes);
2481 CFArrayRef features = CTFontCopyFeatures(font);
2482 if (features) {
2483 CFDictionaryRef feature = findDictionaryInArray(features, kCTFontFeatureTypeNameKey,
2484 (const char*)nameoffile + 1, namelength);
2485 if (feature) {
2486 CFNumberRef identifier = CFDictionaryGetValue(feature, kCTFontFeatureTypeIdentifierKey);
2487 CFNumberGetValue(identifier, kCFNumberIntType, &rval);
2488 }
2489 CFRelease(features);
2490 }
2491 }
2492 #endif
2493
2494 return rval;
2495 }
2496
2497 int
2498 aatfontgetnamed1(int what, CFDictionaryRef attributes, int param)
2499 {
2500 int rval = -1;
2501
2502 #ifdef XETEX_MAC
2503 CTFontRef font = fontFromAttributes(attributes);
2504
2505 if (what == XeTeX_find_selector_by_name) {
2506 CFArrayRef features = CTFontCopyFeatures(font);
2507 if (features) {
2508 CFDictionaryRef feature = findDictionaryInArrayWithIdentifier(features, kCTFontFeatureTypeIdentifierKey, param);
2509 if (feature) {
2510 CFNumberRef selector = findSelectorByName(feature, (const char*)nameoffile + 1, namelength);
2511 if (selector)
2512 CFNumberGetValue(selector, kCFNumberIntType, &rval);
2513 }
2514 CFRelease(features);
2515 }
2516 }
2517 #endif
2518
2519 return rval;
2520 }
2521
2522 void
2523 aatprintfontname(int what, CFDictionaryRef attributes, int param1, int param2)
2524 {
2525 #ifdef XETEX_MAC
2526 CFStringRef name = NULL;
2527 if (what == XeTeX_feature_name || what == XeTeX_selector_name) {
2528 CTFontRef font = fontFromAttributes(attributes);
2529 CFArrayRef features = CTFontCopyFeatures(font);
2530 if (features) {
2531 CFDictionaryRef feature = findDictionaryInArrayWithIdentifier(features,
2532 kCTFontFeatureTypeIdentifierKey,
2533 param1);
2534 if (feature) {
2535 if (what == XeTeX_feature_name)
2536 name = CFDictionaryGetValue(feature, kCTFontFeatureTypeNameKey);
2537 else {
2538 CFArrayRef selectors = CFDictionaryGetValue(feature, kCTFontFeatureTypeSelectorsKey);
2539 CFDictionaryRef selector = findDictionaryInArrayWithIdentifier(selectors,
2540 kCTFontFeatureSelectorIdentifierKey,
2541 param2);
2542 if (selector)
2543 name = CFDictionaryGetValue(selector, kCTFontFeatureSelectorNameKey);
2544 }
2545 }
2546 CFRelease(features);
2547 }
2548 }
2549
2550 if (name) {
2551 CFIndex len = CFStringGetLength(name);
2552 UniChar* buf = xcalloc(len, sizeof(UniChar));
2553 CFStringGetCharacters(name, CFRangeMake(0, len), buf);
2554 printchars(buf, len);
2555 free(buf);
2556 }
2557 #endif
2558 }
2559
2560 void
2561 printglyphname(integer font, integer gid)
2562 {
2563 const char* s;
2564 int len = 0;
2565 #ifdef XETEX_MAC
2566 if (fontarea[font] == AAT_FONT_FLAG) {
2567 s = GetGlyphNameFromCTFont(fontFromInteger(font), gid, &len);
2568 } else
2569 #endif
2570 if (fontarea[font] == OTGR_FONT_FLAG) {
2571 XeTeXLayoutEngine engine = (XeTeXLayoutEngine)fontlayoutengine[font];
2572 s = getGlyphName(getFont(engine), gid, &len);
2573 } else {
2574 fprintf(stderr, "\n! Internal error: bad native font flag in `print_glyph_name'\n");
2575 exit(3);
2576 }
2577 while (len-- > 0)
2578 printchar(*s++);
2579 }
2580
2581 int
2582 u_open_in(unicodefile* f, integer filefmt, const_string fopen_mode, integer mode, integer encodingData)
2583 {
2584 boolean rval;
2585 *f = (unicodefile) xmalloc(sizeof(UFILE));
2586 (*f)->encodingMode = 0;
2587 (*f)->conversionData = 0;
2588 (*f)->savedChar = -1;
2589 (*f)->skipNextLF = 0;
2590 rval = open_input (&((*f)->f), filefmt, fopen_mode);
2591 if (rval) {
2592 int B1, B2;
2593 if (mode == AUTO) {
2594 /* sniff encoding form */
2595 B1 = GETC((*f)->f);
2596 B2 = GETC((*f)->f);
2597 if (B1 == 0xfe && B2 == 0xff)
2598 mode = UTF16BE;
2599 else if (B2 == 0xfe && B1 == 0xff)
2600 mode = UTF16LE;
2601 else if (B1 == 0 && B2 != 0) {
2602 mode = UTF16BE;
2603 rewind((*f)->f);
2604 } else if (B2 == 0 && B1 != 0) {
2605 mode = UTF16LE;
2606 rewind((*f)->f);
2607 } else if (B1 == 0xef && B2 == 0xbb) {
2608 int B3 = GETC((*f)->f);
2609 if (B3 == 0xbf)
2610 mode = UTF8;
2611 }
2612 if (mode == AUTO) {
2613 rewind((*f)->f);
2614 mode = UTF8;
2615 }
2616 }
2617
2618 setinputfileencoding(*f, mode, encodingData);
2619 }
2620 return rval;
2621 }
2622
2623 void
2624 u_close_inout(unicodefile* f)
2625 {
2626 if (f != 0) {
2627 fclose((*f)->f);
2628 if (((*f)->encodingMode == ICUMAPPING) && ((*f)->conversionData != NULL))
2629 ucnv_close((*f)->conversionData);
2630 free(*f);
2631 }
2632 }
2633
2634 #if defined(WIN32)
2635 static int
2636 Isspace(char c)
2637 {
2638 return (c == ' ' || c == '\t');
2639 }
2640 #endif
2641
2642 int
2643 open_dvi_output(FILE** fptr)
2644 {
2645 if (nopdfoutput) {
2646 return open_output(fptr, FOPEN_WBIN_MODE);
2647 } else {
2648 const char *p = (const char*)nameoffile+1;
2649 char *cmd, *q, *bindir = NULL;
2650 int len = strlen(p);
2651 while (*p)
2652 if (*p++ == '\"')
2653 ++len;
2654 len += strlen(outputdriver);
2655 #ifndef WIN32
2656 if (!kpse_absolute_p(outputdriver, true))
2657 bindir = kpse_var_value("SELFAUTOLOC");
2658 if (bindir)
2659 len += strlen(bindir) + 1;
2660 #endif
2661 if (output_directory)
2662 len += strlen(output_directory);
2663 len += 10; /* space for -o flag, quotes, NUL */
2664 for (p = (const char*)nameoffile+1; *p; p++)
2665 if (*p == '\"')
2666 ++len; /* allow extra space to escape quotes in filename */
2667 cmd = xmalloc(len);
2668 #ifdef WIN32
2669 strcpy(cmd, outputdriver);
2670 #else
2671 if (bindir) {
2672 strcpy(cmd, bindir);
2673 strcat(cmd, "/");
2674 strcat(cmd, outputdriver);
2675 } else {
2676 strcpy(cmd, outputdriver);
2677 }
2678 #endif
2679 strcat(cmd, " -o \"");
2680 if (output_directory) {
2681 len = strlen(output_directory);
2682 if (IS_DIR_SEP(output_directory[len-1]))
2683 output_directory[len-1] = '\0';
2684 strcat(cmd, output_directory);
2685 strcat(cmd, "/");
2686 }
2687 q = cmd + strlen(cmd);
2688 for (p = (const char*)nameoffile+1; *p; p++) {
2689 if (*p == '\"')
2690 *q++ = '\\';
2691 *q++ = *p;
2692 }
2693 *q++ = '\"';
2694 *q = '\0';
2695 if (papersize != 0) {
2696 char* cmd2 = concat3(cmd, " -p ", papersize);
2697 free(cmd);
2698 cmd = cmd2;
2699 }
2700 if (output_directory) {
2701 char *fullname = concat3(output_directory, "/", (const char*)nameoffile+1);
2702 free(nameoffile);
2703 namelength = strlen(fullname);
2704 nameoffile = (unsigned char*) xmalloc(namelength + 2);
2705 strcpy((char*)nameoffile+1, fullname);
2706 free(fullname);
2707 }
2708 #if defined(WIN32)
2709 {
2710 wchar_t *tmp1w;
2711 char *p, *pp, *fullcmd, *prgnam;
2712 bindir = kpse_var_value("SELFAUTOLOC");
2713 for(pp = bindir; *pp; pp++) {
2714 if(*pp == '/') *pp = '\\';
2715 }
2716 pp = cmd;
2717 while(Isspace(*pp))
2718 pp++;
2719 prgnam = xmalloc(strlen(cmd));
2720 p = prgnam;
2721 while(!Isspace(*pp)) {
2722 *p++ = *pp++;
2723 }
2724 *p = '\0';
2725 fullcmd = concatn("\"\"", bindir, "\\", prgnam, "\"", pp, "\"", NULL);
2726 tmp1w = get_wstring_from_mbstring(CP_UTF8, (const char *)fullcmd, tmp1w=NULL);
2727 *fptr = _wpopen(tmp1w, L"wb");
2728 free(bindir);
2729 free(prgnam);
2730 free(fullcmd);
2731 free(tmp1w);
2732 }
2733 #else
2734 *fptr = popen(cmd, "w");
2735 #endif
2736 free(cmd);
2737 return (*fptr != 0);
2738 }
2739 }
2740
2741 int
2742 dviclose(FILE* fptr)
2743 {
2744 if (nopdfoutput) {
2745 if (fclose(fptr) != 0)
2746 return errno;
2747 } else {
2748 return pclose(fptr);
2749 }
2750 return 0;
2751 }
2752
2753 int
2754 get_uni_c(UFILE* f)
2755 {
2756 int rval;
2757 int c;
2758 #ifdef WIN32
2759 HANDLE hStdin;
2760 DWORD ret;
2761 wint_t wc[1];
2762 #endif
2763
2764 if (f->savedChar != -1) {
2765 rval = f->savedChar;
2766 f->savedChar = -1;
2767 return rval;
2768 }
2769
2770 switch (f->encodingMode) {
2771 case UTF8:
2772 c = rval = GETC(f->f);
2773 if (rval != EOF) {
2774 uint16_t extraBytes = bytesFromUTF8[rval];
2775 switch (extraBytes) { /* note: code falls through cases! */
2776 case 3: c = GETC(f->f);
2777 if (c < 0x80 || c >= 0xc0) goto bad_utf8;
2778 rval <<= 6; rval += c;
2779 case 2: c = GETC(f->f);
2780 if (c < 0x80 || c >= 0xc0) goto bad_utf8;
2781 rval <<= 6; rval += c;
2782 case 1: c = GETC(f->f);
2783 if (c < 0x80 || c >= 0xc0) goto bad_utf8;
2784 rval <<= 6; rval += c;
2785 case 0:
2786 break;
2787
2788 bad_utf8:
2789 if (c != EOF)
2790 UNGETC(c, f->f);
2791 case 5:
2792 case 4:
2793 badutf8warning();
2794 return 0xfffd; /* return without adjusting by offsetsFromUTF8 */
2795 };
2796 rval -= offsetsFromUTF8[extraBytes];
2797 if (rval < 0 || rval > 0x10ffff) {
2798 badutf8warning();
2799 return 0xfffd;
2800 }
2801 }
2802 break;
2803
2804 case UTF16BE:
2805 rval = GETC(f->f);
2806 if (rval != EOF) {
2807 rval <<= 8;
2808 rval += GETC(f->f);
2809 if (rval >= 0xd800 && rval <= 0xdbff) {
2810 int lo = GETC(f->f);
2811 lo <<= 8;
2812 lo += GETC(f->f);
2813 if (lo >= 0xdc00 && lo <= 0xdfff)
2814 rval = 0x10000 + (rval - 0xd800) * 0x400 + (lo - 0xdc00);
2815 else {
2816 rval = 0xfffd;
2817 f->savedChar = lo;
2818 }
2819 } else if (rval >= 0xdc00 && rval <= 0xdfff)
2820 rval = 0xfffd;
2821 }
2822 break;
2823
2824 case UTF16LE:
2825 rval = GETC(f->f);
2826 if (rval != EOF) {
2827 rval += (GETC(f->f) << 8);
2828 if (rval >= 0xd800 && rval <= 0xdbff) {
2829 int lo = GETC(f->f);
2830 lo += (GETC(f->f) << 8);
2831 if (lo >= 0xdc00 && lo <= 0xdfff)
2832 rval = 0x10000 + (rval - 0xd800) * 0x400 + (lo - 0xdc00);
2833 else {
2834 rval = 0xfffd;
2835 f->savedChar = lo;
2836 }
2837 } else if (rval >= 0xdc00 && rval <= 0xdfff)
2838 rval = 0xfffd;
2839 }
2840 break;
2841
2842 #ifdef WIN32
2843 case WIN32CONSOLE:
2844 hStdin = GetStdHandle(STD_INPUT_HANDLE);
2845 if (ReadConsoleW(hStdin, wc, 1, &ret, NULL) == 0) {
2846 rval = EOF;
2847 break;
2848 }
2849 rval = wc[0];
2850 if (rval >= 0xd800 && rval <= 0xdbff) {
2851 int lo;
2852 if (ReadConsoleW(hStdin, wc, 1, &ret, NULL) == 0) {
2853 rval = EOF;
2854 break;
2855 }
2856 lo = wc[0];
2857 if (lo >= 0xdc00 && lo <= 0xdfff)
2858 rval = 0x10000 + (rval - 0xd800) * 0x400 + (lo - 0xdc00);
2859 else {
2860 rval = 0xfffd;
2861 f->savedChar = lo;
2862 }
2863 } else if (rval >= 0xdc00 && rval <= 0xdfff)
2864 rval = 0xfffd;
2865 break;
2866 #endif
2867
2868 case RAW:
2869 rval = GETC(f->f);
2870 break;
2871
2872 default:
2873 /* this can't happen */
2874 fprintf(stderr, "! Internal error---file input mode=%d.\n", f->encodingMode);
2875 uexit(3);
2876 }
2877
2878 return rval;
2879 }
2880
2881 void
2882 makeutf16name(void)
2883 {
2884 unsigned char* s = nameoffile + 1;
2885 uint32_t rval;
2886 uint16_t* t;
2887 static int name16len = 0;
2888 if (name16len <= namelength) {
2889 if (nameoffile16 != 0)
2890 free(nameoffile16);
2891 name16len = namelength + 10;
2892 nameoffile16 = (uint16_t*) xcalloc(name16len, sizeof(uint16_t));
2893 }
2894 t = nameoffile16;
2895 while (s <= nameoffile + namelength) {
2896 uint16_t extraBytes;
2897 rval = *(s++);
2898 extraBytes = bytesFromUTF8[rval];
2899 switch (extraBytes) { /* note: code falls through cases! */
2900 case 5: rval <<= 6; if (*s) rval += *(s++);
2901 case 4: rval <<= 6; if (*s) rval += *(s++);
2902 case 3: rval <<= 6; if (*s) rval += *(s++);
2903 case 2: rval <<= 6; if (*s) rval += *(s++);
2904 case 1: rval <<= 6; if (*s) rval += *(s++);
2905 case 0: ;
2906 };
2907 rval -= offsetsFromUTF8[extraBytes];
2908 if (rval > 0xffff) {
2909 rval -= 0x10000;
2910 *(t++) = 0xd800 + rval / 0x0400;
2911 *(t++) = 0xdc00 + rval % 0x0400;
2912 } else {
2913 *(t++) = rval;
2914 }
2915 }
2916 namelength16 = t - nameoffile16;
2917 }
2918
2919
2920 integer get_native_word_cp(void* pNode, int side)
2921 {
2922 memoryword* node = (memoryword*)pNode;
2923 FixedPoint* locations = (FixedPoint*)native_glyph_info_ptr(node);
2924 uint16_t* glyphIDs = (uint16_t*)(locations + native_glyph_count(node));
2925 uint16_t glyphCount = native_glyph_count(node);
2926 integer f = native_font(node);
2927 uint16_t actual_glyph;
2928
2929 if (glyphCount == 0)
2930 return 0;
2931
2932 switch (side) {
2933 case LEFT_SIDE:
2934 actual_glyph = *glyphIDs;
2935 break;
2936 case RIGHT_SIDE:
2937 actual_glyph = glyphIDs[glyphCount - 1];
2938 break;
2939 default:
2940 assert(0); // we should not reach this point
2941 }
2942 return get_cp_code(f, actual_glyph, side);
2943 }