Debian Codegraph @

texk/lcdf-typetools/lcdf-typetools-src/otftotfm/otftotfm.cc

raw
1 /* otftotfm.cc -- driver for translating OpenType fonts to TeX metrics
2 *
3 * Copyright (c) 2003-2019 Eddie Kohler
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the Free
7 * Software Foundation; either version 2 of the License, or (at your option)
8 * any later version. This program is distributed in the hope that it will be
9 * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
11 * Public License for more details.
12 */
13
14 #ifdef HAVE_CONFIG_H
15 # include <config.h>
16 #endif
17 #ifdef WIN32
18 # define _USE_MATH_DEFINES
19 # include <io.h>
20 #endif
21 #include <efont/psres.hh>
22 #include <efont/t1rw.hh>
23 #include <efont/t1font.hh>
24 #include <efont/t1item.hh>
25 #include <efont/t1bounds.hh>
26 #include <efont/otfcmap.hh>
27 #include <efont/otfname.hh>
28 #include <efont/otfgsub.hh>
29 #include <efont/ttfkern.hh>
30 #include "glyphfilter.hh"
31 #include "metrics.hh"
32 #include "dvipsencoding.hh"
33 #include "automatic.hh"
34 #include "secondary.hh"
35 #include "kpseinterface.h"
36 #include "util.hh"
37 #include "otftotfm.hh"
38 #include <lcdf/md5.h>
39 #include <lcdf/clp.h>
40 #include <lcdf/error.hh>
41 #include <lcdf/hashmap.hh>
42 #include <lcdf/straccum.hh>
43 #include <efont/cff.hh>
44 #include <efont/otf.hh>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <stdio.h>
48 #include <stdarg.h>
49 #include <ctype.h>
50 #include <errno.h>
51 #include <signal.h>
52 #include <algorithm>
53 #include <math.h>
54 /* M_PI isn't defined in C99 */
55 #ifndef M_PI
56 # define M_PI 3.14159265358979323846264338327
57 #endif
58 #ifdef HAVE_CTIME
59 # include <time.h>
60 #endif
61 #ifdef HAVE_UNISTD_H
62 # include <unistd.h>
63 #endif
64 #ifdef HAVE_FCNTL_H
65 # include <fcntl.h>
66 #endif
67
68 using namespace Efont;
69
70 #define VERSION_OPT 301
71 #define HELP_OPT 302
72 #define QUERY_SCRIPTS_OPT 303
73 #define QUERY_FEATURES_OPT 304
74 #define KPATHSEA_DEBUG_OPT 305
75
76 #define SCRIPT_OPT 311
77 #define FEATURE_OPT 312
78 #define ENCODING_OPT 313
79 #define LITERAL_ENCODING_OPT 314
80 #define EXTEND_OPT 315
81 #define SLANT_OPT 316
82 #define LETTERSPACE_OPT 317
83 #define LIGKERN_OPT 318
84 #define CODINGSCHEME_OPT 319
85 #define UNICODING_OPT 320
86 #define BOUNDARY_CHAR_OPT 321
87 #define DESIGN_SIZE_OPT 322
88 #define MINIMUM_KERN_OPT 323
89 #define ALTSELECTOR_CHAR_OPT 324
90 #define INCLUDE_ALTERNATES_OPT 325
91 #define EXCLUDE_ALTERNATES_OPT 326
92 #define CLEAR_ALTERNATES_OPT 327
93 #define ALTSELECTOR_FEATURE_OPT 328
94 #define DEFAULT_LIGKERN_OPT 329
95 #define NO_ECOMMAND_OPT 330
96 #define LETTER_FEATURE_OPT 331
97 #define INCLUDE_SUBS_OPT 332
98 #define EXCLUDE_SUBS_OPT 333
99 #define CLEAR_SUBS_OPT 334
100 #define SUBS_FILTER_OPT 335
101 #define ALTERNATES_FILTER_OPT 336
102 #define SPACE_FACTOR_OPT 337
103 #define MATH_SPACING_OPT 338
104 #define POSITION_OPT 339
105 #define WARN_MISSING_OPT 340
106 #define BASE_ENCODINGS_OPT 341
107 #define FIXED_PITCH_OPT 342
108 #define ITALIC_ANGLE_OPT 343
109 #define PROPORTIONAL_WIDTH_OPT 344
110 #define X_HEIGHT_OPT 345
111
112 #define AUTOMATIC_OPT 350
113 #define FONT_NAME_OPT 351
114 #define QUIET_OPT 352
115 #define GLYPHLIST_OPT 353
116 #define VENDOR_OPT 354
117 #define TYPEFACE_OPT 355
118 #define NOCREATE_OPT 356
119 #define VERBOSE_OPT 357
120 #define FORCE_OPT 358
121
122 #define VIRTUAL_OPT 360
123 #define PL_OPT 361
124 #define TFM_OPT 362
125 #define MAP_FILE_OPT 363
126 #define OUTPUT_ENCODING_OPT 364
127
128 #define DIR_OPTS 380
129 #define ENCODING_DIR_OPT (DIR_OPTS + O_ENCODING)
130 #define TFM_DIR_OPT (DIR_OPTS + O_TFM)
131 #define PL_DIR_OPT (DIR_OPTS + O_PL)
132 #define VF_DIR_OPT (DIR_OPTS + O_VF)
133 #define VPL_DIR_OPT (DIR_OPTS + O_VPL)
134 #define TYPE1_DIR_OPT (DIR_OPTS + O_TYPE1)
135 #define TYPE42_DIR_OPT (DIR_OPTS + O_TYPE42)
136 #define TRUETYPE_DIR_OPT (DIR_OPTS + O_TRUETYPE)
137 #define DIR_OPT (DIR_OPTS + NUMODIR)
138
139 #define NO_OUTPUT_OPTS 400
140 #define NO_ENCODING_OPT (NO_OUTPUT_OPTS + G_ENCODING)
141 #define NO_TYPE1_OPT (NO_OUTPUT_OPTS + G_TYPE1)
142 #define NO_DOTLESSJ_OPT (NO_OUTPUT_OPTS + G_DOTLESSJ)
143 #define NO_UPDMAP_OPT (NO_OUTPUT_OPTS + G_UPDMAP)
144 #define UPDMAP_SYS_OPT (NO_OUTPUT_OPTS + G_UPDMAP_USER)
145
146 #define YES_OUTPUT_OPTS 2000
147 #define TRUETYPE_OPT (YES_OUTPUT_OPTS + G_TRUETYPE)
148 #define TYPE42_OPT (YES_OUTPUT_OPTS + G_TYPE42)
149 #define UPDMAP_USER_OPT (YES_OUTPUT_OPTS + G_UPDMAP_USER)
150
151 #define CHAR_OPTTYPE (Clp_ValFirstUser)
152
153 static Clp_Option options[] = {
154
155 { "script", 's', SCRIPT_OPT, Clp_ValString, 0 },
156 { "feature", 'f', FEATURE_OPT, Clp_ValString, 0 },
157 { "letter-feature", 0, LETTER_FEATURE_OPT, Clp_ValString, 0 },
158 { "lf", 0, LETTER_FEATURE_OPT, Clp_ValString, 0 },
159 { "include-substitutions", 0, INCLUDE_SUBS_OPT, Clp_ValString, 0 },
160 { "exclude-substitutions", 0, EXCLUDE_SUBS_OPT, Clp_ValString, 0 },
161 { "clear-substitutions", 0, CLEAR_SUBS_OPT, 0, 0 },
162 { "substitution-filter", 0, SUBS_FILTER_OPT, Clp_ValString, 0 },
163 { "subs-filter", 0, SUBS_FILTER_OPT, Clp_ValString, 0 },
164 { "encoding", 'e', ENCODING_OPT, Clp_ValString, 0 },
165 { "literal-encoding", 0, LITERAL_ENCODING_OPT, Clp_ValString, 0 },
166 { "base-encodings", 0, BASE_ENCODINGS_OPT, Clp_ValString, 0 },
167 { "extend", 'E', EXTEND_OPT, Clp_ValDouble, 0 },
168 { "slant", 'S', SLANT_OPT, Clp_ValDouble, 0 },
169 { "letterspacing", 'L', LETTERSPACE_OPT, Clp_ValInt, 0 },
170 { "letterspace", 'L', LETTERSPACE_OPT, Clp_ValInt, 0 },
171 { "min-kern", 'k', MINIMUM_KERN_OPT, Clp_ValDouble, 0 },
172 { "minimum-kern", 'k', MINIMUM_KERN_OPT, Clp_ValDouble, 0 },
173 { "kern-precision", 'k', MINIMUM_KERN_OPT, Clp_ValDouble, 0 },
174 { "ligkern", 0, LIGKERN_OPT, Clp_ValString, 0 },
175 { "position", 0, POSITION_OPT, Clp_ValString, 0 },
176 { "warn-missing", 0, WARN_MISSING_OPT, 0, Clp_Negate },
177 { "no-encoding-commands", 0, NO_ECOMMAND_OPT, 0, 0 },
178 { "default-ligkern", 0, DEFAULT_LIGKERN_OPT, 0, Clp_Negate },
179 { "unicoding", 0, UNICODING_OPT, Clp_ValString, 0 },
180 { "coding-scheme", 0, CODINGSCHEME_OPT, Clp_ValString, 0 },
181 { "boundary-char", 0, BOUNDARY_CHAR_OPT, CHAR_OPTTYPE, 0 },
182 { "altselector", 0, ALTSELECTOR_CHAR_OPT, CHAR_OPTTYPE, Clp_PreferredMatch },
183 { "altselector-char", 0, ALTSELECTOR_CHAR_OPT, CHAR_OPTTYPE, 0 },
184 { "altselector-feature", 0, ALTSELECTOR_FEATURE_OPT, Clp_ValString, 0 },
185 { "design-size", 0, DESIGN_SIZE_OPT, Clp_ValDouble, 0 },
186 { "include-alternates", 0, INCLUDE_ALTERNATES_OPT, Clp_ValString, 0 },
187 { "exclude-alternates", 0, EXCLUDE_ALTERNATES_OPT, Clp_ValString, 0 },
188 { "clear-alternates", 0, CLEAR_ALTERNATES_OPT, 0, 0 },
189 { "alternates-filter", 0, ALTERNATES_FILTER_OPT, Clp_ValString, 0 },
190 { "space-factor", 0, SPACE_FACTOR_OPT, Clp_ValDouble, 0 },
191 { "math-spacing", 0, MATH_SPACING_OPT, CHAR_OPTTYPE, Clp_Negate | Clp_Optional },
192 { "fixed-pitch", 0, FIXED_PITCH_OPT, 0, Clp_Negate },
193 { "fixed-width", 0, FIXED_PITCH_OPT, 0, Clp_Negate },
194 { "proportional-width", 0, PROPORTIONAL_WIDTH_OPT, 0, Clp_Negate },
195 { "italic-angle", 0, ITALIC_ANGLE_OPT, Clp_ValDouble, 0 },
196 { "x-height", 0, X_HEIGHT_OPT, Clp_ValString, 0 },
197
198 { "pl", 'p', PL_OPT, 0, Clp_Negate },
199 { "tfm", 't', TFM_OPT, 0, Clp_Negate }, // not in documentation
200 { "virtual", 0, VIRTUAL_OPT, 0, Clp_Negate },
201 { "no-encoding", 0, NO_ENCODING_OPT, 0, 0 },
202 { "no-type1", 0, NO_TYPE1_OPT, 0, 0 },
203 { "no-dotlessj", 0, NO_DOTLESSJ_OPT, 0, 0 },
204 { "no-updmap", 0, NO_UPDMAP_OPT, 0, 0 },
205 { "updmap-sys", 0, UPDMAP_SYS_OPT, 0, 0 },
206 { "updmap-user", 0, UPDMAP_USER_OPT, 0, 0 },
207 { "truetype", 0, TRUETYPE_OPT, 0, Clp_Negate },
208 { "type42", 0, TYPE42_OPT, 0, Clp_Negate },
209 { "map-file", 0, MAP_FILE_OPT, Clp_ValString, Clp_Negate },
210 { "output-encoding", 0, OUTPUT_ENCODING_OPT, Clp_ValString, Clp_Optional },
211
212 { "automatic", 'a', AUTOMATIC_OPT, 0, Clp_Negate },
213 { "name", 'n', FONT_NAME_OPT, Clp_ValString, 0 },
214 { "vendor", 'v', VENDOR_OPT, Clp_ValString, 0 },
215 { "typeface", 0, TYPEFACE_OPT, Clp_ValString, 0 },
216
217 { "directory", 0, DIR_OPT, Clp_ValString, 0 },
218 { "encoding-directory", 0, ENCODING_DIR_OPT, Clp_ValString, 0 },
219 { "pl-directory", 0, PL_DIR_OPT, Clp_ValString, 0 },
220 { "tfm-directory", 0, TFM_DIR_OPT, Clp_ValString, 0 },
221 { "vpl-directory", 0, VPL_DIR_OPT, Clp_ValString, 0 },
222 { "vf-directory", 0, VF_DIR_OPT, Clp_ValString, 0 },
223 { "type1-directory", 0, TYPE1_DIR_OPT, Clp_ValString, 0 },
224 { "type42-directory", 0, TYPE42_DIR_OPT, Clp_ValString, 0 },
225 { "truetype-directory", 0, TRUETYPE_DIR_OPT, Clp_ValString, 0 },
226
227 { "quiet", 'q', QUIET_OPT, 0, Clp_Negate },
228 { "glyphlist", 0, GLYPHLIST_OPT, Clp_ValString, 0 },
229 { "no-create", 0, NOCREATE_OPT, 0, 0 },
230 { "force", 0, FORCE_OPT, 0, Clp_Negate },
231 { "verbose", 'V', VERBOSE_OPT, 0, Clp_Negate },
232 { "kpathsea-debug", 0, KPATHSEA_DEBUG_OPT, Clp_ValInt, 0 },
233
234 { "help", 'h', HELP_OPT, 0, 0 },
235 { "version", 0, VERSION_OPT, 0, 0 },
236
237 { "query-features", 0, QUERY_FEATURES_OPT, 0, 0 },
238 { "qf", 0, QUERY_FEATURES_OPT, 0, 0 },
239 { "query-scripts", 0, QUERY_SCRIPTS_OPT, 0, 0 },
240 { "qs", 0, QUERY_SCRIPTS_OPT, 0, 0 },
241
242 };
243
244 static const char * const default_ligkerns = "\
245 space l =: lslash ; space L =: Lslash ; \
246 question quoteleft =: questiondown ; \
247 exclam quoteleft =: exclamdown ; \
248 hyphen hyphen =: endash ; endash hyphen =: emdash ; \
249 quoteleft quoteleft =: quotedblleft ; \
250 quoteright quoteright =: quotedblright ;";
251
252 struct BaseEncoding {
253 String font_name;
254 String secondary;
255 DvipsEncoding encoding;
256 };
257
258 static const char *program_name;
259 static String current_time;
260 static StringAccum invocation;
261
262 static PermString::Initializer perm_initializer;
263 static PermString dot_notdef(".notdef");
264
265 static Vector<Efont::OpenType::Tag> interesting_scripts;
266 static Vector<Efont::OpenType::Tag> interesting_features;
267 static Vector<Efont::OpenType::Tag> altselector_features;
268 static GlyphFilter null_filter;
269 static HashMap<Efont::OpenType::Tag, GlyphFilter*> feature_filters(0);
270 static HashMap<Efont::OpenType::Tag, GlyphFilter*> altselector_feature_filters(0);
271
272 static String font_name;
273 static String encoding_file;
274 static Vector<BaseEncoding *> base_encodings;
275 static double extend;
276 static double slant;
277 int letterspace;
278 static double design_size;
279 static double minimum_kern = 2.0;
280 static double space_factor = 1.0;
281 static bool math_spacing = false;
282 static int skew_char = -1;
283 static bool override_is_fixed_pitch = false;
284 static bool is_fixed_pitch;
285 static bool override_italic_angle = false;
286 static double italic_angle;
287 static int override_x_height = FontInfo::x_height_auto;
288 static double x_height;
289
290 static String out_encoding_file;
291 static String out_encoding_name;
292
293 unsigned output_flags = G_ENCODING | G_METRICS | G_VMETRICS | G_PSFONTSMAP | G_TYPE1 | G_DOTLESSJ | G_UPDMAP | G_TRUETYPE;
294
295 bool automatic = false;
296 bool verbose = false;
297 bool no_create = false;
298 bool quiet = false;
299 bool force = false;
300
301 static String otf_data;
302
303
304 void
305 usage_error(ErrorHandler *errh, const char *error_message, ...)
306 {
307 va_list val;
308 va_start(val, error_message);
309 if (!error_message)
310 errh->message("Usage: %s [OPTION]... FONT", program_name);
311 else
312 errh->xmessage(ErrorHandler::e_error, error_message, val);
313 errh->message("Type %s --help for more information.", program_name);
314 exit(1);
315 va_end(val);
316 }
317
318 void
319 usage()
320 {
321 FileErrorHandler uerrh(stdout);
322 uerrh.message("\
323 %<Otftotfm%> generates TeX font metrics files from an OpenType font (PostScript\n\
324 flavor only), including ligatures, kerns, and some positionings. Supply\n\
325 %<-s SCRIPT[.LANG]%> options to specify a language system, %<-f FEAT%> options to\n\
326 turn on optional OpenType features, and a %<-e ENC%> option to specify a base\n\
327 encoding. Output files are written to the current directory (but see\n\
328 %<--automatic%> and the %<directory%> options).\n\
329 \n\
330 Usage: %s [-a] [OPTIONS] OTFFILE FONTNAME\n\n",
331 program_name);
332 uerrh.message("\
333 Font feature and transformation options:\n\
334 -s, --script=SCRIPT[.LANG] Use features for script SCRIPT[.LANG] [latn].\n\
335 -f, --feature=FEAT Activate feature FEAT.\n\
336 --lf, --letter-feature=FEAT Activate feature FEAT for letters.\n\
337 --subs-filter=PAT Substitute only characters matching PAT.\n\
338 --include-subs=PAT Same, but cumulative.\n\
339 --exclude-subs=PAT Don%,t substitute characters matching PAT.\n\
340 --clear-subs Clear included/excluded substitutions.\n\
341 -E, --extend=F Widen characters by a factor of F.\n\
342 -S, --slant=AMT Oblique characters by AMT, generally <<1.\n\
343 -L, --letterspacing=AMT Letterspace each character by AMT units.\n\
344 --math-spacing[=SKEWCH] Use letterspacing appropriate for math.\n\
345 -k, --min-kern=N Omit kerns with absolute value < N [2.0].\n\
346 --space-factor=F Scale wordspace by a factor of F.\n\
347 --design-size=SIZE Set font design size to SIZE.\n\
348 --fixed-width Set fixed width (no space stretch).\n\
349 --italic-angle=ANGLE Set font italic angle (for positioning accents).\n\
350 --x-height=AMT Set x-height to AMT units.\n\
351 \n");
352 uerrh.message("\
353 Encoding options:\n\
354 -e, --encoding=FILE Use DVIPS encoding FILE as a base encoding.\n\
355 --boundary-char=CHAR Set the boundary character to CHAR.\n\
356 --altselector-char=CHAR Set the alternate selector character to CHAR.\n\
357 --altselector-feature=F Activate feature F for --altselector-char.\n\
358 --alternates-filter=PAT Include only alternate characters matching PAT.\n\
359 --include-alternates=PAT Same as --alternates-filter, but cumulative.\n\
360 --exclude-alternates=PAT Ignore alternate characters matching PAT.\n\
361 --clear-alternates Clear included/excluded alternates.\n\
362 --ligkern=COMMAND Add a ligature or kern.\n\
363 --position=COMMAND Add a POSITION command.\n\
364 --unicoding=COMMAND Add a UNICODING command.\n\
365 --no-encoding-commands Ignore encoding file%,s LIGKERN/UNICODINGs.\n\
366 --no-default-ligkern Don%,t include default LIGKERNs.\n\
367 --coding-scheme=SCHEME Set the output coding scheme to SCHEME.\n\
368 --warn-missing Warn about characters not supported by font.\n\
369 --literal-encoding=FILE Use DVIPS encoding FILE verbatim.\n\
370 --base-encodings=FILE Output can refer to base fonts named in FILE.\n\
371 \n");
372 uerrh.message("\
373 Automatic mode options:\n\
374 -a, --automatic Install in a TeX Directory Structure.\n\
375 -v, --vendor=NAME Set font vendor for TDS [lcdftools].\n\
376 --typeface=NAME Set typeface name for TDS [<font family>].\n\
377 --no-type1 Do not generate Type 1 fonts.\n\
378 --no-dotlessj Do not generate dotless-j fonts.\n\
379 --no-truetype Do not install TrueType-flavored input fonts.\n\
380 --no-updmap Do not run updmap.\n\
381 --updmap-user Run `updmap-user` instead of `updmap-sys`.\n\
382 \n\
383 Output options:\n\
384 -n, --name=NAME Generated font name is NAME.\n\
385 -p, --pl Output human-readable PL/VPLs, not TFM/VFs.\n\
386 --no-virtual Do not generate VFs or VPLs.\n\
387 --no-encoding Do not generate an encoding file.\n\
388 --no-map Do not generate a psfonts.map line.\n\
389 --output-encoding[=FILE] Only generate an encoding file.\n\
390 \n");
391 uerrh.message("\
392 File location options:\n\
393 --tfm-directory=DIR Put TFM files in DIR [.|automatic].\n\
394 --pl-directory=DIR Put PL files in DIR [.|automatic].\n\
395 --vf-directory=DIR Put VF files in DIR [.|automatic].\n\
396 --vpl-directory=DIR Put VPL files in DIR [.|automatic].\n\
397 --encoding-directory=DIR Put encoding files in DIR [.|automatic].\n\
398 --type1-directory=DIR Put Type 1 fonts in DIR [automatic].\n\
399 --truetype-directory=DIR Put TrueType fonts in DIR [automatic].\n\
400 --directory=DIR Put output in DIR [.|automatic].\n\
401 --map-file=FILE Update FILE with psfonts.map information [-].\n\
402 \n\
403 Other options:\n\
404 --glyphlist=FILE Use FILE to map Adobe glyph names to Unicode.\n\
405 -V, --verbose Print progress information to standard error.\n\
406 --no-create Print messages, don't modify any files.\n\
407 --force Generate files even if versions already exist.\n"
408 #if HAVE_KPATHSEA
409 " --kpathsea-debug=MASK Set path searching debug flags to MASK.\n"
410 #endif
411 " -h, --help Print this message and exit.\n\
412 -q, --quiet Do not generate any error messages.\n\
413 --version Print version number and exit.\n\
414 \n\
415 Report bugs to <[email protected]>.\n");
416 }
417
418 #ifndef WIN32
419 extern "C" {
420 static void
421 sigchld_handler(int s)
422 {
423 #if !HAVE_SIGACTION
424 signal(s, sigchld_handler);
425 #else
426 (void) s;
427 #endif
428 }
429 }
430
431 static void
432 handle_sigchld()
433 {
434 #ifdef SIGCHLD
435 int sigchld = SIGCHLD;
436 #else
437 int sigchld = SIGCLD;
438 #endif
439 #if HAVE_SIGACTION
440 struct sigaction sa;
441 sigaction(sigchld, 0, &sa);
442 sa.sa_handler = sigchld_handler;
443 sa.sa_flags = 0;
444 sigaction(sigchld, &sa, 0);
445 #else
446 signal(sigchld, sigchld_handler);
447 #endif
448 }
449 #endif
450
451
452 // MAIN
453
454 String
455 suffix_font_name(const String &font_name, const String &suffix)
456 {
457 const char *begin = font_name.begin(), *end = font_name.end();
458 while (end > begin && isdigit((unsigned char) end[-1]))
459 --end;
460 if (end < font_name.end() && end > begin && end[-1] != '-' && end[-1] != '+')
461 end = font_name.end();
462 else
463 while (end > begin && (end[-1] == '-' || end[-1] == '+'))
464 --end;
465 if (end == begin)
466 end = font_name.end();
467 return font_name.substring(begin, end) + suffix + font_name.substring(end, font_name.end());
468 }
469
470 static inline String
471 make_base_font_name(const String &font_name)
472 {
473 return suffix_font_name(font_name, "--base");
474 }
475
476 static double
477 get_design_size(const FontInfo &finfo)
478 {
479 try {
480 String gpos_table = finfo.otf->table("GPOS");
481 if (!gpos_table)
482 throw OpenType::Error();
483
484 ErrorHandler *errh = ErrorHandler::silent_handler();
485 OpenType::Gpos gpos(gpos_table, errh);
486
487 // extract 'size' feature(s)
488 int required_fid;
489 Vector<int> fids;
490 for (const OpenType::Tag *t = interesting_scripts.begin(); t < interesting_scripts.end(); t += 2)
491 gpos.script_list().features(t[0], t[1], required_fid, fids, 0, false);
492
493 int size_fid = gpos.feature_list().find(OpenType::Tag("size"), fids);
494 if (size_fid < 0)
495 throw OpenType::Error();
496
497 // old Adobe fonts implement an old, incorrect idea
498 // of what the FeatureParams offset means.
499 OpenType::Name name(finfo.otf->table("name"), errh);
500 OpenType::Data size_data = gpos.feature_list().size_params(size_fid, name, errh);
501 if (!size_data.length())
502 throw OpenType::Error();
503
504 double result = size_data.u16(0) / 10.;
505 // check for insane design sizes
506 if (result < 1 || result > 1000)
507 throw OpenType::Error();
508
509 // return a number in 'pt', not 'bp'
510 return result * 72.27 / 72.;
511
512 } catch (OpenType::Error) {
513 return 10.0;
514 }
515 }
516
517 static const char * const digit_names[] = {
518 "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"
519 };
520
521 static inline const char *
522 lig_context_str(int ctx)
523 {
524 return (ctx == 0 ? "LIG" : (ctx < 0 ? "/LIG" : "LIG/"));
525 }
526
527 static double max_printed_real;
528
529 namespace {
530 struct Printer {
531 Printer(FILE* f, unsigned design_units, unsigned units_per_em)
532 : f_(f), du_((double) design_units / units_per_em),
533 round_(design_units == 1000) {
534 }
535 inline double transform(double value) const;
536 void print_transformed(const char* prefix, double value) const;
537 void print(const char* prefix, double value) const;
538 String render(double value) const;
539 FILE* f_;
540 double du_;
541 bool round_;
542 };
543
544 inline double Printer::transform(double value) const {
545 value *= du_;
546 if (round_)
547 value = ceil(value);
548 return value;
549 }
550
551 void Printer::print_transformed(const char* prefix, double value) const {
552 if (round_ || value == 0 || (value > 0.01 && value - floor(value) < 0.01))
553 fprintf(f_, "%s R %g)\n", prefix, value);
554 else
555 fprintf(f_, "%s R %.4f)\n", prefix, value);
556 max_printed_real = std::max(max_printed_real, fabs(value));
557 }
558
559 void Printer::print(const char* prefix, double value) const {
560 print_transformed(prefix, transform(value));
561 }
562
563 String Printer::render(double value) const {
564 value = transform(value);
565 if (round_ || value == 0 || (value > 0.01 && value - floor(value) < 0.01))
566 return String(value);
567 else {
568 char buf[128];
569 snprintf(buf, sizeof(buf), "%.4f", value);
570 return String(buf);
571 }
572 }
573 } // namespace
574
575 double
576 font_slant(const FontInfo &finfo)
577 {
578 double val = finfo.italic_angle();
579 return -tan(val * M_PI / 180.0) + slant;
580 }
581
582 static void
583 output_pl(Metrics &metrics, const String &ps_name, int boundary_char,
584 const FontInfo &finfo, bool vpl,
585 const String &filename, ErrorHandler *errh)
586 {
587 // create file
588 if (no_create) {
589 errh->message("would create %s", filename.c_str());
590 return;
591 }
592
593 if (verbose)
594 errh->message("creating %s", filename.c_str());
595 FILE *f = fopen(filename.c_str(), "wb");
596 if (!f) {
597 errh->error("%s: %s", filename.c_str(), strerror(errno));
598 return;
599 }
600
601 // XXX check DESIGNSIZE and DESIGNUNITS for correctness
602
603 fprintf(f, "(COMMENT Created by '%s'%s)\n", invocation.c_str(), current_time.c_str());
604
605 // calculate a TeX FAMILY name using afm2tfm's algorithm
606 String family_name = String("TeX-") + ps_name;
607 if (family_name.length() > 19)
608 family_name = family_name.substring(0, 9) + family_name.substring(-10);
609 fprintf(f, "(FAMILY %s)\n", family_name.c_str());
610
611 if (metrics.coding_scheme())
612 fprintf(f, "(CODINGSCHEME %.39s)\n", String(metrics.coding_scheme()).c_str());
613 int design_units = metrics.design_units();
614
615 if (design_size <= 0)
616 design_size = get_design_size(finfo);
617 max_printed_real = 0;
618
619 fprintf(f, "(DESIGNSIZE R %.1f)\n"
620 "(DESIGNUNITS R %d.0)\n"
621 "(COMMENT DESIGNSIZE (1 em) IS IN POINTS)\n"
622 "(COMMENT OTHER DIMENSIONS ARE MULTIPLES OF DESIGNSIZE/%d)\n"
623 "(FONTDIMEN\n", design_size, design_units, design_units);
624
625 // figure out font dimensions
626 Transform font_xform;
627 if (extend)
628 font_xform.scale(extend, 1);
629 if (slant)
630 font_xform.shear(slant);
631 double bounds[4], width;
632 Printer pr(f, design_units, metrics.units_per_em());
633
634 double actual_slant = font_slant(finfo);
635 if (actual_slant)
636 fprintf(f, " (SLANT R %g)\n", actual_slant);
637
638 if (char_bounds(bounds, width, finfo, font_xform, ' ')) {
639 // advance space width by letterspacing, scale by space_factor
640 double space_width = (width + (vpl ? letterspace : 0)) * space_factor;
641 pr.print(" (SPACE", space_width);
642 if (finfo.is_fixed_pitch()) {
643 // fixed-pitch: no space stretch or shrink
644 pr.print(" (STRETCH", 0);
645 pr.print(" (SHRINK", 0);
646 pr.print(" (EXTRASPACE", space_width);
647 } else {
648 pr.print(" (STRETCH", space_width / 2.);
649 pr.print(" (SHRINK", space_width / 3.);
650 pr.print(" (EXTRASPACE", space_width / 6.);
651 }
652 }
653
654 double x_height = finfo.x_height(font_xform);
655 if (x_height < finfo.units_per_em())
656 pr.print(" (XHEIGHT", x_height);
657
658 pr.print(" (QUAD", finfo.units_per_em());
659 fprintf(f, " )\n");
660
661 if (boundary_char >= 0)
662 fprintf(f, "(BOUNDARYCHAR D %d)\n", boundary_char);
663
664 // figure out font mapping
665 int mapped_font0 = 0;
666 Vector<int> font_mapping;
667 if (vpl) {
668 int vpl_first_font = (metrics.need_base() ? 0 : 1);
669 font_mapping.assign(metrics.n_mapped_fonts(), 0);
670 if (vpl_first_font == 1 && font_mapping.size() == 1)
671 font_mapping.push_back(0);
672 // how many times is each font used?
673 Vector<Setting> settings;
674 for (int i = 0; i < 256; i++)
675 if (metrics.setting(i, settings)) {
676 int font_number = 0;
677 for (const Setting *s = settings.begin(); s < settings.end(); s++)
678 if (s->op == Setting::SHOW)
679 font_mapping[font_number]++;
680 else if (s->op == Setting::FONT)
681 font_number = (int) s->x;
682 }
683 // make sure the most-used font is number 0
684 mapped_font0 = std::max_element(font_mapping.begin(), font_mapping.end()) - font_mapping.begin();
685 // prepare the mapping
686 for (int i = vpl_first_font; i < font_mapping.size(); i++)
687 font_mapping[i] = i - vpl_first_font;
688 font_mapping[mapped_font0] = 0;
689 font_mapping[vpl_first_font] = mapped_font0 - vpl_first_font;
690 if (vpl_first_font != 0)
691 font_mapping[0] = font_mapping.size() - 1;
692 // write MAPFONT
693 for (int i = 0; i < metrics.n_mapped_fonts() - vpl_first_font; i++) {
694 int j = std::find(font_mapping.begin(), font_mapping.end(), i) - font_mapping.begin();
695 String name = metrics.mapped_font_name(j);
696 if (!name)
697 name = make_base_font_name(font_name);
698 fprintf(f, "(MAPFONT D %d\n (FONTNAME %s)\n (FONTDSIZE R %.1f)\n )\n", i, name.c_str(), design_size);
699 }
700 } else
701 for (int i = 0; i < metrics.n_mapped_fonts(); i++)
702 font_mapping.push_back(i);
703
704 // figure out the proper names and numbers for glyphs
705 Vector<String> glyph_ids;
706 Vector<String> glyph_comments(257, String());
707 Vector<String> glyph_base_comments(257, String());
708 for (int i = 0; i < metrics.encoding_size(); i++) {
709 if (metrics.glyph(i)) {
710 PermString name = metrics.code_name(i), expected_name;
711 if (i >= '0' && i <= '9')
712 expected_name = digit_names[i - '0'];
713 else if ((i >= 'A' && i <= 'Z') || (i >= 'a' && i <= 'z'))
714 expected_name = PermString((char)i);
715 String glyph_comment;
716 if (name != expected_name)
717 glyph_comment = " (COMMENT " + String(name) + ")";
718
719 int base = metrics.base_code(i);
720 if (base >= 0 && base < 256)
721 glyph_base_comments[base] = glyph_comment;
722
723 if (i >= 256)
724 continue;
725
726 char* expected_name_end;
727 if (expected_name
728 && (name == expected_name
729 || (name.length() == 7
730 && memcmp(name.data(), "uni00", 5) == 0
731 && strtol(name.c_str() + 3, &expected_name_end, 16) == i
732 && *expected_name_end == 0)))
733 glyph_ids.push_back("C " + String((char)i));
734 else
735 glyph_ids.push_back("D " + String(i));
736
737 glyph_comments[i] = glyph_base_comments[i] = glyph_comment;
738
739 } else if (i < 256)
740 glyph_ids.push_back("D " + String(i));
741 }
742 // finally, BOUNDARYCHAR
743 glyph_ids.push_back("BOUNDARYCHAR");
744
745 // LIGTABLE
746 fprintf(f, "(LIGTABLE\n");
747 Vector<int> lig_code2, lig_outcode, lig_context, kern_code2, kern_amt;
748 // don't print KRN x after printing LIG x
749 uint32_t used[8];
750 bool any_ligs = false;
751 StringAccum omitted_clig_sa;
752 for (int i = 0; i <= 256; i++)
753 if (metrics.glyph(i) && minimum_kern < 10000) {
754 int any_lig = metrics.ligatures(i, lig_code2, lig_outcode, lig_context);
755 int any_kern = metrics.kerns(i, kern_code2, kern_amt);
756 if (any_lig || any_kern) {
757 StringAccum kern_sa;
758 memset(used, 0, sizeof(used));
759 for (int j = 0; j < lig_code2.size(); j++) {
760 if (lig_outcode[j] < 257) {
761 kern_sa << " (" << lig_context_str(lig_context[j])
762 << ' ' << glyph_ids[lig_code2[j]]
763 << ' ' << glyph_ids[lig_outcode[j]]
764 << ')' << glyph_comments[lig_code2[j]]
765 << glyph_comments[lig_outcode[j]] << '\n';
766 used[lig_code2[j] >> 5] |= (1 << (lig_code2[j] & 0x1F));
767 } else {
768 omitted_clig_sa << "(COMMENT omitted "
769 << lig_context_str(lig_context[j])
770 << ' ' << metrics.code_name(i)
771 << ' ' << metrics.code_name(lig_code2[j])
772 << ' ' << metrics.code_name(lig_outcode[j])
773 << ")\n";
774 }
775 }
776 for (Vector<int>::const_iterator k2 = kern_code2.begin(); k2 < kern_code2.end(); k2++)
777 if (!(used[*k2 >> 5] & (1 << (*k2 & 0x1F)))) {
778 double this_kern = kern_amt[k2 - kern_code2.begin()];
779 if (fabs(this_kern) >= minimum_kern)
780 kern_sa << " (KRN " << glyph_ids[*k2]
781 << " R " << pr.render(this_kern)
782 << ')' << glyph_comments[*k2] << '\n';
783 }
784 if (kern_sa) {
785 if (any_ligs)
786 fprintf(f, "\n");
787 fprintf(f, " (LABEL %s)%s\n%s (STOP)\n", glyph_ids[i].c_str(), glyph_comments[i].c_str(), kern_sa.c_str());
788 any_ligs = true;
789 }
790 }
791 }
792 fprintf(f, " )\n");
793 if (omitted_clig_sa)
794 fprintf(f, "%s\n", omitted_clig_sa.c_str());
795
796 // CHARACTERs
797 Vector<Setting> settings;
798 StringAccum sa;
799 Vector<Point> push_stack;
800
801 for (int i = 0; i < 256; i++)
802 if (metrics.setting(i, settings)) {
803 fprintf(f, "(CHARACTER %s%s\n", glyph_ids[i].c_str(), glyph_comments[i].c_str());
804
805 // unparse settings into DVI commands
806 sa.clear();
807 push_stack.clear();
808 CharstringBounds boundser(font_xform);
809 int program_number = mapped_font0;
810 const CharstringProgram *program = finfo.program();
811 for (const Setting *s = settings.begin(); s < settings.end(); s++)
812 switch (s->op) {
813
814 case Setting::SHOW:
815 if (vpl || program == finfo.program())
816 boundser.char_bounds(program->glyph_context(s->y));
817 // 3.Aug.2004 -- reported by Marco Kuhlmann: Don't use
818 // glyph_ids[] array when looking at a different font.
819 if (program_number == 0)
820 sa << " (SETCHAR " << glyph_ids[s->x] << ')' << glyph_base_comments[s->x] << "\n";
821 else
822 sa << " (SETCHAR D " << s->x << ")\n";
823 break;
824
825 case Setting::MOVE: {
826 int x = 0, y = 0;
827 while (s+1 < settings.end() && s[1].op == Setting::MOVE)
828 x += s->x, y += s->y, s++;
829 if (vpl)
830 boundser.translate(s->x + x, s->y + y);
831 if (s->x + x)
832 sa << " (MOVERIGHT R " << pr.render(s->x + x) << ")\n";
833 if (s->y + y)
834 sa << " (MOVEUP R " << pr.render(s->y + y) << ")\n";
835 break;
836 }
837
838 case Setting::RULE:
839 if (vpl) {
840 boundser.mark(Point(0, 0));
841 boundser.mark(Point(s->x, s->y));
842 boundser.translate(s->x, 0);
843 }
844 sa << " (SETRULE R " << pr.render(s->y) << " R " << pr.render(s->x) << ")\n";
845 break;
846
847 case Setting::FONT:
848 if ((int) s->x != program_number) {
849 program = metrics.mapped_font((int) s->x);
850 program_number = (int) s->x;
851 sa << " (SELECTFONT D " << font_mapping[program_number] << ")\n";
852 }
853 break;
854
855 case Setting::PUSH:
856 push_stack.push_back(boundser.transform(Point(0, 0)));
857 sa << " (PUSH)\n";
858 break;
859
860 case Setting::POP: {
861 assert(push_stack.size());
862 Point p = push_stack.back() - boundser.transform(Point(0, 0));
863 if (vpl)
864 boundser.translate(p.x, p.y);
865 push_stack.pop_back();
866 sa << " (POP)\n";
867 break;
868 }
869
870 case Setting::SPECIAL: {
871 bool needhex = false;
872 for (const char *str = s->s.begin(); str < s->s.end() && !needhex; str++)
873 if (*str < ' ' || *str > '~' || *str == '(' || *str == ')')
874 needhex = true;
875 if (needhex) {
876 sa << " (SPECIALHEX ";
877 for (const char *str = s->s.begin(); str < s->s.end(); str++) {
878 static const char hexdig[] = "0123456789ABCDEF";
879 int val = (unsigned char) *str;
880 sa << hexdig[val >> 4] << hexdig[val & 0xF];
881 }
882 sa << ")\n";
883 } else
884 sa << " (SPECIAL " << s->s << ")\n";
885 break;
886 }
887
888 }
889
890 assert(push_stack.size() == 0);
891
892 // output information
893 boundser.output(bounds, width);
894 pr.print(" (CHARWD", width);
895 if (bounds[3] > 0)
896 pr.print(" (CHARHT", bounds[3]);
897 if (bounds[1] < 0)
898 pr.print(" (CHARDP", -bounds[1]);
899 if (bounds[2] > width)
900 pr.print_transformed(" (CHARIC", pr.transform(bounds[2]) - pr.transform(width));
901 if (vpl && (settings.size() > 1 || settings[0].op != Setting::SHOW))
902 fprintf(f, " (MAP\n%s )\n", sa.c_str());
903 fprintf(f, " )\n");
904 }
905
906 // at last, close the file
907 fclose(f);
908
909 // Did we print a number too big for TeX to handle? If so, try again.
910 if (max_printed_real >= 2047) {
911 if (metrics.design_units() <= 1)
912 errh->fatal("This font appears to be broken. It has characters so big that the PL format\ncannot represent them.");
913 metrics.set_design_units(metrics.design_units() > 200 ? metrics.design_units() - 250 : 1);
914 if (verbose)
915 errh->message("the font%,s metrics overflow the limits of PL files\n(reducing DESIGNUNITS to %d and trying again)", metrics.design_units());
916 output_pl(metrics, ps_name, boundary_char, finfo, vpl, filename, errh);
917 }
918 }
919
920 struct Lookup {
921 bool used;
922 bool required;
923 Vector<OpenType::Tag> features;
924 GlyphFilter* filter;
925 Lookup() : used(false), required(false), filter(0) { }
926 };
927
928 static void
929 find_lookups(const OpenType::ScriptList& scripts, const OpenType::FeatureList& features, Vector<Lookup>& lookups, ErrorHandler* errh)
930 {
931 Vector<int> fids, lookupids;
932 int required;
933
934 // go over all scripts
935 for (int i = 0; i < interesting_scripts.size(); i += 2) {
936 OpenType::Tag script = interesting_scripts[i];
937 OpenType::Tag langsys = interesting_scripts[i+1];
938
939 // collect features applying to this script
940 scripts.features(script, langsys, required, fids, errh);
941
942 // only use the selected features
943 features.filter(fids, interesting_features);
944
945 // mark features as having been used
946 for (int j = (required < 0 ? 0 : -1); j < fids.size(); j++) {
947 int fid = (j < 0 ? required : fids[j]);
948 OpenType::Tag ftag = features.tag(fid);
949 if (features.lookups(fid, lookupids, errh) < 0)
950 lookupids.clear();
951 for (int k = 0; k < lookupids.size(); k++) {
952 int l = lookupids[k];
953 if (l < 0 || l >= lookups.size())
954 errh->error("lookup for %<%s%> feature out of range", OpenType::Tag::langsys_text(script, langsys).c_str());
955 else {
956 lookups[l].used = true;
957 lookups[l].features.push_back(ftag);
958 if (j < 0)
959 lookups[l].required = true;
960 }
961 }
962 }
963 }
964
965 // now check for compatible glyph filters
966 for (Lookup* l = lookups.begin(); l < lookups.end(); l++)
967 if (l->used && !l->required) {
968 l->filter = feature_filters[l->features[0]];
969 for (OpenType::Tag* ft = l->features.begin() + 1; ft < l->features.end(); ft++)
970 if (!l->filter->check_eq(*feature_filters[*ft])) {
971 errh->error("%<%s%> and %<%s%> features share a lookup, but have different filters", l->features[0].text().c_str(), ft->text().c_str());
972 break;
973 }
974 }
975 }
976
977 static int
978 write_encoding_file(String &filename, const String &encoding_name,
979 StringAccum &contents, ErrorHandler *errh)
980 {
981 FILE *f;
982 int ok_retval = (access(filename.c_str(), R_OK) >= 0 ? 0 : 1);
983
984 if (no_create) {
985 errh->message((ok_retval ? "would create encoding file %s" : "would update encoding file %s"), filename.c_str());
986 return ok_retval;
987 } else if (verbose)
988 errh->message((ok_retval ? "creating encoding file %s" : "updating encoding file %s"), filename.c_str());
989
990 int fd = open(filename.c_str(), O_RDWR | O_CREAT, 0666);
991 if (fd < 0)
992 return errh->error("%s: %s", filename.c_str(), strerror(errno));
993 f = fdopen(fd, "r+");
994 // NB: also change update_autofont_map if you change this code
995
996 #if defined(F_SETLKW) && defined(HAVE_FTRUNCATE)
997 {
998 struct flock lock;
999 lock.l_type = F_WRLCK;
1000 lock.l_whence = SEEK_SET;
1001 lock.l_start = 0;
1002 lock.l_len = 0;
1003 int result;
1004 while ((result = fcntl(fd, F_SETLKW, &lock)) < 0 && errno == EINTR)
1005 /* try again */;
1006 if (result < 0) {
1007 result = errno;
1008 fclose(f);
1009 return errh->error("locking %s: %s", filename.c_str(), strerror(result));
1010 }
1011 }
1012 #endif
1013
1014 // read old data from encoding file
1015 StringAccum sa;
1016 int amt;
1017 do {
1018 if (char *x = sa.reserve(8192)) {
1019 amt = fread(x, 1, 8192, f);
1020 sa.adjust_length(amt);
1021 } else
1022 amt = 0;
1023 } while (amt != 0);
1024 if (!feof(f) || ferror(f))
1025 return errh->error("%s: %s", filename.c_str(), strerror(errno));
1026 String old_encodings = sa.take_string();
1027 bool created = (!old_encodings);
1028
1029 // append old encodings
1030 int pos1 = old_encodings.find_left("\n%%");
1031 while (pos1 >= 0 && pos1 < old_encodings.length()) {
1032 int pos2 = old_encodings.find_left("\n%%", pos1 + 1);
1033 if (pos2 < 0)
1034 pos2 = old_encodings.length();
1035 if (old_encodings.substring(pos1 + 3, encoding_name.length()) == encoding_name) {
1036 // encoding already exists, don't change it
1037 fclose(f);
1038 if (verbose)
1039 errh->message("%s unchanged", filename.c_str());
1040 return 0;
1041 } else
1042 contents << old_encodings.substring(pos1, pos2 - pos1);
1043 pos1 = pos2;
1044 }
1045
1046 // rewind file
1047 #ifdef HAVE_FTRUNCATE
1048 rewind(f);
1049 if (ftruncate(fd, 0) < 0)
1050 #endif
1051 {
1052 fclose(f);
1053 f = fopen(filename.c_str(), "wb");
1054 fd = fileno(f);
1055 }
1056
1057 ignore_result(fwrite(contents.data(), 1, contents.length(), f));
1058
1059 fclose(f);
1060
1061 // inform about the new file if necessary
1062 if (created)
1063 update_odir(O_ENCODING, filename, errh);
1064 return 0;
1065 }
1066
1067 static bool
1068 output_encoding(const Metrics &metrics,
1069 const Vector<PermString> &glyph_names,
1070 ErrorHandler *errh)
1071 {
1072 static const char * const hex_digits = "0123456789ABCDEF";
1073
1074 // collect encoding data
1075 Vector<Metrics::Glyph> glyphs;
1076 if (!metrics.base_glyphs(glyphs, 256))
1077 return false;
1078
1079 StringAccum sa;
1080 for (int i = 0; i < 256; i++) {
1081 if ((i & 0xF) == 0)
1082 sa << (i ? "\n%" : "%") << hex_digits[(i >> 4) & 0xF] << '0' << '\n' << ' ';
1083 else if ((i & 0x7) == 0)
1084 sa << '\n' << ' ';
1085 int g = glyphs[i];
1086 if (g > 0 && g < glyph_names.size())
1087 sa << ' ' << '/' << glyph_names[g];
1088 else
1089 sa << " /.notdef";
1090 }
1091 sa << '\n';
1092
1093 // digest encoding data
1094 MD5_CONTEXT md5;
1095 md5_init(&md5);
1096 md5_update(&md5, (const unsigned char *)sa.data(), sa.length());
1097 char text_digest[MD5_TEXT_DIGEST_SIZE + 1];
1098 md5_final_text(text_digest, &md5);
1099
1100 // name encoding using digest
1101 out_encoding_name = "AutoEnc_" + String(text_digest);
1102
1103 // create encoding filename
1104 bool output_encoding_only = (bool) out_encoding_file;
1105 if (!out_encoding_file)
1106 out_encoding_file = getodir(O_ENCODING, errh) + String("/a_") + String(text_digest).substring(0, 6) + ".enc";
1107
1108 // exit if we're not responsible for generating an encoding
1109 if (!(output_flags & G_ENCODING))
1110 return true;
1111
1112 // put encoding block in a StringAccum
1113 // 3.Jun.2003: stick command line definition at the end of the encoding,
1114 // where it won't confuse idiotic ps2pk
1115 StringAccum contents;
1116 if (!output_encoding_only)
1117 contents << "% THIS FILE WAS AUTOMATICALLY GENERATED -- DO NOT EDIT\n\n\
1118 %%" << out_encoding_name << "\n";
1119 contents << "% Encoding created by otftotfm" << current_time << "\n\
1120 % Command line follows encoding\n";
1121
1122 // the encoding itself
1123 contents << '/' << out_encoding_name << " [\n" << sa << "] def\n";
1124
1125 // write banner -- unfortunately this takes some doing
1126 String banner = String("Command line: '") + String(invocation.data(), invocation.length()) + String("'");
1127 char *buf = banner.mutable_data();
1128 // get rid of crap characters
1129 for (int i = 0; i < banner.length(); i++)
1130 if (buf[i] < ' ' || buf[i] > 0176) {
1131 if (buf[i] == '\n' || buf[i] == '\r')
1132 buf[i] = ' ';
1133 else
1134 buf[i] = '.';
1135 }
1136 // break lines at 80 characters -- it would be nice if this were in a
1137 // library
1138 while (banner.length() > 0) {
1139 int pos = banner.find_left(' '), last_pos = pos;
1140 while (pos < 75 && pos >= 0) {
1141 last_pos = pos;
1142 pos = banner.find_left(' ', pos + 1);
1143 }
1144 if (last_pos < 0 || (pos < 0 && banner.length() < 75))
1145 last_pos = banner.length();
1146 contents << "% " << banner.substring(0, last_pos) << '\n';
1147 banner = banner.substring(last_pos + 1);
1148 }
1149
1150 // open encoding file
1151 if (out_encoding_file == "-")
1152 ignore_result(fwrite(contents.data(), 1, contents.length(), stdout));
1153 else if (write_encoding_file(out_encoding_file, out_encoding_name, contents, errh) == 1)
1154 update_odir(O_ENCODING, out_encoding_file, errh);
1155 return true;
1156 }
1157
1158 static void
1159 output_tfm(Metrics &metrics, const String &ps_name, int boundary_char,
1160 const FontInfo &finfo, String tfm_filename, String vf_filename,
1161 String pl_filename, ErrorHandler *errh)
1162 {
1163 bool had_pl_filename = !pl_filename.empty();
1164 bool vpl = vf_filename;
1165
1166 if (!pl_filename) {
1167 if (no_create) {
1168 errh->message("would write %s to temporary file", (vpl ? "VPL" : "PL"));
1169 pl_filename = "<temporary>";
1170 } else {
1171 int pl_fd = temporary_file(pl_filename, errh);
1172 if (pl_fd < 0)
1173 return;
1174 output_pl(metrics, ps_name, boundary_char, finfo, vpl, pl_filename, errh);
1175 close(pl_fd);
1176 }
1177 }
1178
1179 StringAccum command;
1180 if (vpl)
1181 command << "vptovf " << shell_quote(pl_filename) << ' ' << shell_quote(vf_filename) << ' ' << shell_quote(tfm_filename) << " 2>&1";
1182 else
1183 command << "pltotf " << shell_quote(pl_filename) << ' ' << shell_quote(tfm_filename) << " 2>&1";
1184
1185 FILE* cmdfile = mypopen(command.c_str(), "r", errh);
1186 int status;
1187 if (cmdfile) {
1188 StringAccum results;
1189 while (!feof(cmdfile)) {
1190 char* buf = results.reserve(BUFSIZ);
1191 results.adjust_length(fread(buf, 1, BUFSIZ, cmdfile));
1192 }
1193 // compensate for shitty vptovf/pltotf messages
1194 char* by_units, *last_line;
1195 while (!results.empty()
1196 && (by_units = strstr((char*) results.c_str(), " units"))
1197 && (last_line = strrchr((char*) results.c_str(), '\n'))
1198 && results.end() - last_line > 1
1199 && isdigit((unsigned char) last_line[1])) {
1200 char* start_number = last_line + 1;
1201 char* end_number = last_line + 2;
1202 while (end_number < results.end()
1203 && isdigit((unsigned char) *end_number))
1204 ++end_number;
1205 if (end_number < results.end() && *end_number == '.') {
1206 char* dot = end_number;
1207 ++end_number;
1208 while (end_number < results.end()
1209 && end_number < dot + 8
1210 && isdigit((unsigned char) *end_number))
1211 ++end_number;
1212 }
1213 String number(start_number, end_number);
1214 char* by_units_dest = by_units + 1 + (end_number - start_number);
1215 memmove(by_units_dest, by_units + 1, start_number - (by_units + 1));
1216 memmove(by_units + 1, number.begin(), number.length());
1217 }
1218 if (!results.empty())
1219 fwrite(results.begin(), 1, results.length(), stderr);
1220 status = pclose(cmdfile);
1221 } else
1222 status = -1;
1223
1224 if (!no_create && !had_pl_filename)
1225 unlink(pl_filename.c_str());
1226
1227 if (status != 0)
1228 errh->fatal("%s execution failed", (vpl ? "vptovf" : "pltotf"));
1229 else {
1230 update_odir(O_TFM, tfm_filename, errh);
1231 if (vpl)
1232 update_odir(O_VF, vf_filename, errh);
1233 }
1234 }
1235
1236 void
1237 output_metrics(Metrics &metrics, const String &ps_name, int boundary_char,
1238 const FontInfo &finfo,
1239 const String &encoding_name, const String &encoding_file,
1240 const String &font_name,
1241 String (*dvips_include)(const String &ps_name, const FontInfo &, ErrorHandler *),
1242 ErrorHandler *errh)
1243 {
1244 String base_font_name = font_name;
1245 bool need_virtual = metrics.need_virtual(257);
1246 if (need_virtual) {
1247 if (output_flags & G_VMETRICS)
1248 base_font_name = make_base_font_name(font_name);
1249 else if (output_flags & G_METRICS)
1250 errh->warning("features require virtual fonts");
1251 }
1252
1253 // output virtual metrics
1254 if (!(output_flags & G_VMETRICS))
1255 /* do nothing */;
1256 else if (!need_virtual) {
1257 if (automatic) {
1258 // erase old virtual font
1259 String vf = getodir(O_VF, errh) + "/" + font_name + ".vf";
1260 if (no_create)
1261 errh->message("would remove potential VF file %<%s%>", vf.c_str());
1262 else {
1263 if (verbose)
1264 errh->message("removing potential VF file %<%s%>", vf.c_str());
1265 if (unlink(vf.c_str()) < 0 && errno != ENOENT)
1266 errh->error("removing %s: %s", vf.c_str(), strerror(errno));
1267 }
1268 }
1269 } else {
1270 String vplfile;
1271 if (output_flags & G_ASCII) {
1272 vplfile = getodir(O_VPL, errh) + "/" + font_name + ".vpl";
1273 output_pl(metrics, ps_name, boundary_char, finfo, true, vplfile, errh);
1274 update_odir(O_VPL, vplfile, errh);
1275 }
1276 if (output_flags & G_BINARY) {
1277 String tfm = getodir(O_TFM, errh) + "/" + font_name + ".tfm";
1278 String vf = getodir(O_VF, errh) + "/" + font_name + ".vf";
1279 output_tfm(metrics, ps_name, boundary_char, finfo, tfm, vf, vplfile, errh);
1280 }
1281 }
1282
1283 // quit if no base needed
1284 metrics.make_base(257);
1285 if (!metrics.need_base())
1286 return;
1287
1288 // output metrics
1289 double save_minimum_kern = minimum_kern;
1290 if (need_virtual)
1291 minimum_kern = 100000;
1292 if (output_flags & G_METRICS) {
1293 String plfile;
1294 if (output_flags & G_ASCII) {
1295 plfile = getodir(O_PL, errh) + "/" + base_font_name + ".pl";
1296 output_pl(metrics, ps_name, boundary_char, finfo, false, plfile, errh);
1297 update_odir(O_PL, plfile, errh);
1298 }
1299 if (output_flags & G_BINARY) {
1300 String tfm = getodir(O_TFM, errh) + "/" + base_font_name + ".tfm";
1301 output_tfm(metrics, ps_name, boundary_char, finfo, tfm, String(), plfile, errh);
1302 }
1303 }
1304 minimum_kern = save_minimum_kern;
1305
1306 // print DVIPS map line
1307 if (errh->nerrors() == 0 && (output_flags & G_PSFONTSMAP)) {
1308 StringAccum sa;
1309 sa << base_font_name << ' ' << ps_name << " \"";
1310 if (extend)
1311 sa << extend << " ExtendFont ";
1312 if (slant)
1313 sa << slant << " SlantFont ";
1314 if (encoding_name)
1315 sa << encoding_name << " ReEncodeFont\" <[" << pathname_filename(encoding_file);
1316 else
1317 sa << "\"";
1318 sa << ' ' << dvips_include(ps_name, finfo, errh) << '\n';
1319 update_autofont_map(base_font_name, sa.take_string(), errh);
1320 // if virtual font, remove any map line for base font name
1321 if (base_font_name != font_name)
1322 update_autofont_map(font_name, "", errh);
1323 }
1324 }
1325
1326
1327 enum { F_GSUB_TRY = 1, F_GSUB_PART = 2, F_GSUB_ALL = 4,
1328 F_GPOS_TRY = 8, F_GPOS_PART = 16, F_GPOS_ALL = 32,
1329 X_UNUSED = 0, X_BOTH_NONE = 1, X_GSUB_NONE = 2,
1330 X_GSUB_PART = 3, X_GPOS_NONE = 4, X_GPOS_PART = 5, X_COUNT };
1331
1332 static const char * const x_messages[] = {
1333 "% ignored, not supported by font",
1334 "% ignored, too complex for me",
1335 "complex substitutions from % ignored",
1336 "some complex substitutions from % ignored",
1337 "complex positionings from % ignored",
1338 "some complex positionings from % ignored",
1339 };
1340
1341 static void
1342 report_underused_features(const HashMap<uint32_t, int> &feature_usage, ErrorHandler *errh)
1343 {
1344 Vector<String> x[X_COUNT];
1345 for (int i = 0; i < interesting_features.size(); i++) {
1346 OpenType::Tag f = interesting_features[i];
1347 int fu = feature_usage[f.value()];
1348 String ftext = errh->format("%<%s%>", f.text().c_str());
1349 if (fu == 0)
1350 x[X_UNUSED].push_back(ftext);
1351 else if ((fu & (F_GSUB_TRY | F_GPOS_TRY)) == fu)
1352 x[X_BOTH_NONE].push_back(ftext);
1353 else {
1354 if (fu & F_GSUB_TRY) {
1355 if ((fu & (F_GSUB_PART | F_GSUB_ALL)) == 0)
1356 x[X_GSUB_NONE].push_back(ftext);
1357 else if (fu & F_GSUB_PART)
1358 x[X_GSUB_PART].push_back(ftext);
1359 }
1360 if (fu & F_GPOS_TRY) {
1361 if ((fu & (F_GPOS_PART | F_GPOS_ALL)) == 0)
1362 x[X_GPOS_NONE].push_back(ftext);
1363 else if (fu & F_GPOS_PART)
1364 x[X_GPOS_PART].push_back(ftext);
1365 }
1366 }
1367 }
1368
1369 for (int i = 0; i < X_COUNT; i++)
1370 if (x[i].size())
1371 goto found;
1372 return;
1373
1374 found:
1375 for (int i = 0; i < X_COUNT; i++)
1376 if (x[i].size()) {
1377 StringAccum sa;
1378 const char* msg_pct = strchr(x_messages[i], '%');
1379 sa.append(x_messages[i], msg_pct - x_messages[i]);
1380 const char* sep = (x[i].size() > 2 ? ", " : " ");
1381 for (const String* a = x[i].begin(); a < x[i].end() - 1; a++)
1382 sa << *a << sep;
1383 sa << (x[i].size() > 1 ? "and " : "") << x[i].back()
1384 << (x[i].size() > 1 ? " features" : " feature") << (msg_pct+1);
1385 sa.append_break_lines(sa.take_string(), 58);
1386 errh->warning("%s", sa.c_str());
1387 }
1388 }
1389
1390 static String otf_filename;
1391
1392 static String
1393 main_dvips_map(const String &ps_name, const FontInfo &finfo, ErrorHandler *errh)
1394 {
1395 if (String fn = installed_type1(otf_filename, ps_name, (output_flags & G_TYPE1) != 0, errh))
1396 return "<" + pathname_filename(fn);
1397 if (!finfo.cff) {
1398 String ttf_fn, t42_fn;
1399 ttf_fn = installed_truetype(otf_filename, (output_flags & G_TRUETYPE) != 0, errh);
1400 t42_fn = installed_type42(otf_filename, ps_name, (output_flags & G_TYPE42) != 0, errh);
1401 if (t42_fn && (!ttf_fn || (output_flags & G_TYPE42) != 0))
1402 return "<" + pathname_filename(t42_fn);
1403 else if (ttf_fn)
1404 return "<" + pathname_filename(ttf_fn);
1405 }
1406 return "<" + pathname_filename(otf_filename);
1407 }
1408
1409 static void
1410 do_gsub(Metrics& metrics, const OpenType::Font& otf,
1411 DvipsEncoding& dvipsenc, bool dvipsenc_literal,
1412 HashMap<uint32_t, int>& feature_usage,
1413 const Vector<PermString>& glyph_names, ErrorHandler* errh)
1414 {
1415 // find activated GSUB features
1416 OpenType::Gsub gsub(otf.table("GSUB"), &otf, errh);
1417 Vector<Lookup> lookups(gsub.nlookups(), Lookup());
1418 find_lookups(gsub.script_list(), gsub.feature_list(), lookups, errh);
1419
1420 // find all characters that might result
1421 Vector<bool> used(glyph_names.size(), false);
1422 for (Metrics::Code c = 0; c < metrics.encoding_size(); ++c) {
1423 Metrics::Glyph g = metrics.glyph(c);
1424 if (g >= 0 && g < used.size())
1425 used[g] = true;
1426 }
1427 for (int i = 0; i < lookups.size(); ++i)
1428 if (lookups[i].used) {
1429 OpenType::GsubLookup l = gsub.lookup(i);
1430 l.mark_out_glyphs(gsub, used);
1431 }
1432 OpenType::Coverage used_coverage(used);
1433
1434 // apply activated GSUB features
1435 Vector<OpenType::Substitution> subs;
1436 for (int i = 0; i < lookups.size(); i++)
1437 if (lookups[i].used) {
1438 OpenType::GsubLookup l = gsub.lookup(i);
1439 subs.clear();
1440 bool understood = l.unparse_automatics(gsub, subs, used_coverage);
1441
1442 // check for -ffina, which should apply only at the ends of words,
1443 // and -finit, which should apply only at the beginnings.
1444 OpenType::Tag feature = (lookups[i].features.size() == 1 ? lookups[i].features[0] : OpenType::Tag());
1445 if (feature == OpenType::Tag("fina") || feature == OpenType::Tag("fin2") || feature == OpenType::Tag("fin3")) {
1446 if (dvipsenc.boundary_char() < 0)
1447 errh->warning("%<-ffina%> requires a boundary character\n(The input encoding didn%,t specify a boundary character, but\nI need one to implement %<-ffina%> features correctly. Try\nthe %<--boundary-char%> option.)");
1448 else {
1449 int bg = metrics.boundary_glyph();
1450 for (int j = 0; j < subs.size(); j++)
1451 subs[j].add_outer_right(bg);
1452 }
1453 } else if (feature == OpenType::Tag("init")) {
1454 int bg = metrics.boundary_glyph();
1455 for (int j = 0; j < subs.size(); j++)
1456 subs[j].add_outer_left(bg);
1457 }
1458
1459 //for (int subno = 0; subno < subs.size(); subno++) fprintf(stderr, "%5d\t%s\n", i, subs[subno].unparse().c_str());
1460
1461 // figure out which glyph filter to use
1462 int nunderstood = metrics.apply(subs, !dvipsenc_literal, i, *lookups[i].filter, glyph_names);
1463
1464 // mark as used
1465 int d = (understood && nunderstood == subs.size() ? F_GSUB_ALL : (nunderstood ? F_GSUB_PART : 0)) + F_GSUB_TRY;
1466 for (int j = 0; j < lookups[i].features.size(); j++)
1467 feature_usage.find_force(lookups[i].features[j].value()) |= d;
1468 }
1469
1470 // apply alternate selectors
1471 if (metrics.altselectors() && !dvipsenc_literal) {
1472 // do lookups
1473 altselector_features.swap(interesting_features);
1474 altselector_feature_filters.swap(feature_filters);
1475 Vector<Lookup> alt_lookups(gsub.nlookups(), Lookup());
1476 find_lookups(gsub.script_list(), gsub.feature_list(), alt_lookups, ErrorHandler::silent_handler());
1477 Vector<OpenType::Substitution> alt_subs;
1478 for (int i = 0; i < alt_lookups.size(); i++)
1479 if (alt_lookups[i].used) {
1480 OpenType::GsubLookup l = gsub.lookup(i);
1481 alt_subs.clear();
1482 (void) l.unparse_automatics(gsub, alt_subs, used_coverage);
1483 metrics.apply_alternates(alt_subs, i, *alt_lookups[i].filter, glyph_names);
1484 }
1485 altselector_features.swap(interesting_features);
1486 altselector_feature_filters.swap(feature_filters);
1487 }
1488 }
1489
1490 static bool
1491 kern_feature_requested()
1492 {
1493 return std::find(interesting_features.begin(), interesting_features.end(),
1494 OpenType::Tag("kern")) != interesting_features.end();
1495 }
1496
1497 static void
1498 do_try_ttf_kern(Metrics& metrics, const OpenType::Font& otf, HashMap<uint32_t, int>& feature_usage, ErrorHandler* errh)
1499 {
1500 // if no GPOS "kern" lookups and "kern" requested, try "kern" table
1501 if (!kern_feature_requested())
1502 return;
1503 try {
1504 OpenType::KernTable kern(otf.table("kern"), errh);
1505 Vector<OpenType::Positioning> poss;
1506 bool understood = kern.unparse_automatics(poss, errh);
1507 int nunderstood = metrics.apply(poss);
1508
1509 // mark as used
1510 int d = (understood && nunderstood == poss.size() ? F_GPOS_ALL : (nunderstood ? F_GPOS_PART : 0)) + F_GPOS_TRY;
1511 feature_usage.find_force(OpenType::Tag("kern").value()) |= d;
1512 } catch (OpenType::BlankTable) {
1513 // nada
1514 } catch (OpenType::Error e) {
1515 errh->warning("kern %<%s%> error, continuing", e.description.c_str());
1516 }
1517 }
1518
1519 static void
1520 do_gpos(Metrics& metrics, const OpenType::Font& otf, HashMap<uint32_t, int>& feature_usage, ErrorHandler* errh)
1521 {
1522 OpenType::Gpos gpos(otf.table("GPOS"), errh);
1523 Vector<Lookup> lookups(gpos.nlookups(), Lookup());
1524 find_lookups(gpos.script_list(), gpos.feature_list(), lookups, errh);
1525
1526 // OpenType recommends that if GPOS exists, but the "kern" feature loads
1527 // no lookups, we use the TrueType "kern" table, if any.
1528 if (kern_feature_requested()) {
1529 OpenType::Tag kern_tag("kern");
1530 for (Lookup *l = lookups.begin(); l != lookups.end(); ++l)
1531 if (std::find(l->features.begin(), l->features.end(), kern_tag) != l->features.end())
1532 goto skip_ttf_kern;
1533 do_try_ttf_kern(metrics, otf, feature_usage, errh);
1534 skip_ttf_kern: ;
1535 }
1536
1537 Vector<OpenType::Positioning> poss;
1538 for (int i = 0; i < lookups.size(); i++)
1539 if (lookups[i].used) {
1540 OpenType::GposLookup l = gpos.lookup(i);
1541 poss.clear();
1542 bool understood = l.unparse_automatics(poss, errh);
1543 int nunderstood = metrics.apply(poss);
1544
1545 // mark as used
1546 int d = (understood && nunderstood == poss.size() ? F_GPOS_ALL : (nunderstood ? F_GPOS_PART : 0)) + F_GPOS_TRY;
1547 for (int j = 0; j < lookups[i].features.size(); j++)
1548 feature_usage.find_force(lookups[i].features[j].value()) |= d;
1549 }
1550 }
1551
1552 static void
1553 do_math_spacing(Metrics &metrics, const FontInfo &finfo,
1554 const DvipsEncoding &dvipsenc)
1555 {
1556 Transform font_xform;
1557 if (extend)
1558 font_xform.scale(extend, 1);
1559 if (slant)
1560 font_xform.shear(slant);
1561 CharstringBounds boundser(font_xform);
1562
1563 double x_height = finfo.x_height(font_xform);
1564 double actual_slant = font_slant(finfo);
1565 int boundary_char = dvipsenc.boundary_char();
1566
1567 double bounds[4], width;
1568
1569 for (int code = 0; code < metrics.encoding_size(); code++)
1570 if (metrics.was_base_glyph(code)
1571 && code != boundary_char
1572 && char_bounds(bounds, width, finfo, font_xform, metrics.unicode(code))) {
1573 int left_sb = (bounds[0] < 0 ? (int) ceil(-bounds[0]) : 0);
1574 metrics.add_single_positioning(code, left_sb, 0, left_sb);
1575
1576 if (skew_char >= 0 && code < 256) {
1577 double sheight = std::max(bounds[3], x_height) - 0.5 * x_height;
1578 double right_sb = std::max(bounds[2] - width, 0.0);
1579 double desired = left_sb + 0.5 * width + actual_slant * sheight + 0.25 * right_sb;
1580 double computed = 0.5 * (left_sb + width + right_sb);
1581 int skew = (int) (desired - computed);
1582 metrics.add_kern(code, skew_char, skew);
1583 }
1584 }
1585 }
1586
1587 static void
1588 do_file(const String &otf_filename, const OpenType::Font &otf,
1589 const DvipsEncoding &dvipsenc_in, bool dvipsenc_literal,
1590 ErrorHandler *errh)
1591 {
1592 FontInfo finfo(&otf, errh);
1593 if (!finfo.ok())
1594 return;
1595 if (!finfo.cff)
1596 errh->warning("TrueType-flavored font support is experimental");
1597 if (override_is_fixed_pitch)
1598 finfo.set_is_fixed_pitch(is_fixed_pitch);
1599 if (override_italic_angle)
1600 finfo.set_italic_angle(italic_angle);
1601 if (override_x_height != FontInfo::x_height_auto)
1602 finfo.set_x_height(override_x_height, x_height);
1603
1604 // save glyph names
1605 Vector<PermString> glyph_names;
1606 finfo.glyph_names(glyph_names);
1607 OpenType::debug_glyph_names = glyph_names;
1608
1609 // set typeface name from font family name
1610 {
1611 String typeface = finfo.family_name();
1612
1613 // make it reasonable for the shell
1614 StringAccum sa;
1615 for (int i = 0; i < typeface.length(); i++)
1616 if (isalnum((unsigned char) typeface[i]) || typeface[i] == '_' || typeface[i] == '-' || typeface[i] == '.' || typeface[i] == ',' || typeface[i] == '+')
1617 sa << typeface[i];
1618
1619 set_typeface(sa.length() ? sa.take_string() : font_name, false);
1620 }
1621
1622 // initialize encoding
1623 DvipsEncoding dvipsenc(dvipsenc_in); // make copy
1624 Metrics metrics(finfo.program(), finfo.nglyphs());
1625 // encode boundary glyph at 256; pretend its Unicode value is '\n'
1626 metrics.encode(256, '\n', metrics.boundary_glyph());
1627 if (dvipsenc_literal)
1628 dvipsenc.make_metrics(metrics, finfo, 0, true, errh);
1629 else {
1630 T1Secondary secondary(finfo, font_name, otf_filename);
1631 dvipsenc.make_metrics(metrics, finfo, &secondary, false, errh);
1632 }
1633
1634 // maintain statistics about features
1635 HashMap<uint32_t, int> feature_usage(0);
1636
1637 // apply activated GSUB features
1638 try {
1639 do_gsub(metrics, otf, dvipsenc, dvipsenc_literal, feature_usage, glyph_names, errh);
1640 } catch (OpenType::BlankTable) {
1641 // nada
1642 } catch (OpenType::Error e) {
1643 errh->warning("GSUB %<%s%> error, continuing", e.description.c_str());
1644 }
1645
1646 // apply LIGKERN ligature commands to the result
1647 dvipsenc.apply_ligkern_lig(metrics, errh);
1648
1649 // test fake ligature mechanism
1650 //metrics.add_threeligature('T', 'h', 'e', '0');
1651
1652 // reencode characters to fit within 8 bytes (+ 1 for the boundary)
1653 if (!dvipsenc_literal)
1654 metrics.shrink_encoding(257, dvipsenc_in, errh);
1655
1656 // apply activated GPOS features
1657 try {
1658 do_gpos(metrics, otf, feature_usage, errh);
1659 } catch (OpenType::BlankTable) {
1660 do_try_ttf_kern(metrics, otf, feature_usage, errh);
1661 } catch (OpenType::Error e) {
1662 errh->warning("GPOS %<%s%> error, continuing", e.description.c_str());
1663 }
1664
1665 // apply LIGKERN kerning and POS positioning commands to the result
1666 dvipsenc.apply_ligkern_kern(metrics, errh);
1667 dvipsenc.apply_position(metrics, errh);
1668
1669 // use prespecified raw fonts
1670 for (BaseEncoding **be = base_encodings.begin(); be != base_encodings.end(); be++)
1671 if (!(*be)->secondary) {
1672 Vector<int> mapp;
1673 (*be)->encoding.make_base_mappings(mapp, finfo);
1674 metrics.apply_base_encoding((*be)->font_name, (*be)->encoding, mapp);
1675 }
1676
1677 // remove extra characters
1678 metrics.cut_encoding(257);
1679 //metrics.unparse();
1680 int boundary_char = dvipsenc.boundary_char();
1681
1682 // apply letterspacing, if any
1683 if (letterspace)
1684 for (int code = 0; code < metrics.encoding_size(); code++)
1685 if (metrics.was_base_glyph(code) && code != boundary_char) {
1686 metrics.add_single_positioning(code, letterspace / 2, 0, letterspace);
1687 if (code < 256) {
1688 metrics.add_kern(code, 256, -letterspace / 2);
1689 metrics.add_kern(256, code, -letterspace / 2);
1690 }
1691 }
1692
1693 // apply math letterspacing, if any
1694 if (math_spacing)
1695 do_math_spacing(metrics, finfo, dvipsenc);
1696
1697 // reencode right components of boundary_glyph as boundary_char
1698 if (metrics.reencode_right_ligkern(256, boundary_char) > 0
1699 && boundary_char < 0) {
1700 errh->warning("no boundary character, ignoring some ligatures and/or kerns\n");
1701 errh->message("(You may want to try the --boundary-char option.)");
1702 }
1703
1704 // report unused and underused features if any
1705 report_underused_features(feature_usage, errh);
1706
1707 // figure out our FONTNAME
1708 if (!font_name) {
1709 // derive font name from OpenType font name
1710 font_name = finfo.postscript_name();
1711 if (encoding_file) {
1712 int slash = encoding_file.find_right('/') + 1;
1713 int dot = encoding_file.find_right('.');
1714 if (dot < slash) // includes dot < 0 case
1715 dot = encoding_file.length();
1716 font_name += String("--") + encoding_file.substring(slash, dot - slash);
1717 }
1718 if (interesting_scripts.size() != 2 || interesting_scripts[0] != OpenType::Tag("latn") || interesting_scripts[1].valid())
1719 for (int i = 0; i < interesting_scripts.size(); i += 2) {
1720 font_name += String("--S") + interesting_scripts[i].text();
1721 if (interesting_scripts[i+1].valid())
1722 font_name += String(".") + interesting_scripts[i+1].text();
1723 }
1724 for (int i = 0; i < interesting_features.size(); i++)
1725 if (feature_usage[interesting_features[i].value()])
1726 font_name += String("--F") + interesting_features[i].text();
1727 }
1728
1729 // output encoding
1730 if (dvipsenc_literal) {
1731 out_encoding_name = dvipsenc_in.name();
1732 out_encoding_file = dvipsenc_in.filename();
1733 } else
1734 output_encoding(metrics, glyph_names, errh);
1735
1736 // set up coding scheme
1737 if (metrics.coding_scheme())
1738 metrics.set_design_units(1);
1739 else
1740 metrics.set_coding_scheme(out_encoding_name);
1741
1742 // force no type 1
1743 if (!finfo.cff && (output_flags & G_TYPE1)) {
1744 errh->warning("assuming --no-type1 since this font is TrueType-flavored");
1745 output_flags &= ~G_TYPE1;
1746 }
1747
1748 // output
1749 ::otf_filename = otf_filename;
1750 output_metrics(metrics, finfo.postscript_name(), dvipsenc.boundary_char(),
1751 finfo,
1752 out_encoding_name, out_encoding_file,
1753 font_name, main_dvips_map, errh);
1754 }
1755
1756
1757 String
1758 installed_metrics_font_name(const String &base_font_name, const String &secondary)
1759 {
1760 for (BaseEncoding **be = base_encodings.begin(); be != base_encodings.end(); be++)
1761 if ((*be)->secondary == secondary && ::font_name == base_font_name)
1762 return (*be)->font_name;
1763 return String();
1764 }
1765
1766
1767 extern "C" {
1768 static int
1769 clp_parse_char(Clp_Parser *clp, const char *arg, int complain, void *)
1770 {
1771 if (arg[0] && !arg[1] && !isdigit((unsigned char) arg[0])) {
1772 clp->val.i = (unsigned char)arg[0];
1773 return 1;
1774 } else if (arg[0] == '-' || isdigit((unsigned char) arg[0])) {
1775 char *end;
1776 clp->val.i = strtol(arg, &end, 10);
1777 if (clp->val.i <= 255 && !*end)
1778 return 1;
1779 }
1780 if (complain)
1781 Clp_OptionError(clp, "'%O' expects a character, not '%s'", arg);
1782 return 0;
1783 }
1784 }
1785
1786 static void
1787 parse_base_encodings(const String &filename, ErrorHandler *errh)
1788 {
1789 String str = read_file(filename, errh, true);
1790 String print_filename = (filename == "-" ? "<stdin>" : filename) + ":";
1791 int lineno = 1;
1792 str.c_str();
1793 const char *s_end = str.end();
1794 for (const char *s = str.begin(); s != s_end; ) {
1795 while (s != s_end && isspace((unsigned char) *s) && *s != '\n' && *s != '\r')
1796 s++;
1797 // skip comments and blank lines
1798 if (s != s_end && *s != '%' && *s != '#' && *s != '\n' && *s != '\r') {
1799 const char *w1 = s;
1800 while (s != s_end && !isspace((unsigned char) *s))
1801 s++;
1802 BaseEncoding *be = new BaseEncoding;
1803 be->font_name = str.substring(w1, s);
1804 while (s != s_end && isspace((unsigned char) *s) && *s != '\n' && *s != '\r')
1805 s++;
1806 const char *w2 = s;
1807 while (s != s_end && !isspace((unsigned char) *s))
1808 s++;
1809 String efile = str.substring(w2, s);
1810 while (s != s_end && isspace((unsigned char) *s) && *s != '\n' && *s != '\r')
1811 s++;
1812 if (s != s_end && !isspace((unsigned char) *s) && *s != '%' && *s != '#') {
1813 const char *w3 = s;
1814 while (s != s_end && !isspace((unsigned char) *s))
1815 s++;
1816 be->secondary = str.substring(w3, s);
1817 }
1818 LandmarkErrorHandler lerrh(errh, print_filename + String(lineno));
1819 int before = lerrh.nerrors();
1820 if (be->secondary)
1821 /* encoding ignored */;
1822 else if (!efile)
1823 lerrh.error("missing encoding name");
1824 else if (String path = locate_encoding(efile, errh))
1825 be->encoding.parse(path, true, true, &lerrh);
1826 else
1827 lerrh.error("encoding %<%s%> not found", efile.c_str());
1828 if (lerrh.nerrors() == before)
1829 base_encodings.push_back(be);
1830 else
1831 delete be;
1832 }
1833 while (s != s_end && *s != '\n' && *s != '\r')
1834 s++;
1835 if (s != s_end && *s == '\r')
1836 s++;
1837 if (s != s_end && *s == '\n')
1838 s++;
1839 lineno++;
1840 }
1841 }
1842
1843 int
1844 main(int argc, char *argv[])
1845 {
1846 #ifndef WIN32
1847 handle_sigchld();
1848 #endif
1849 Clp_Parser *clp =
1850 Clp_NewParser(argc, (const char * const *)argv, sizeof(options) / sizeof(options[0]), options);
1851 Clp_AddType(clp, CHAR_OPTTYPE, 0, clp_parse_char, 0);
1852 program_name = Clp_ProgramName(clp);
1853 #if HAVE_KPATHSEA
1854 kpsei_init(argv[0], "lcdftools");
1855 #endif
1856 #ifdef HAVE_CTIME
1857 {
1858 time_t t = time(0);
1859 char *c = ctime(&t);
1860 current_time = " on " + String(c).substring(0, -1); // get rid of \n
1861 }
1862 #endif
1863 for (int i = 0; i < argc; i++)
1864 invocation << (i ? " " : "") << argv[i];
1865
1866 ErrorHandler *errh = ErrorHandler::static_initialize(new FileErrorHandler(stderr, String(program_name) + ": "));
1867 const char *input_file = 0;
1868 Vector<String> glyphlist_files;
1869 bool literal_encoding = false;
1870 bool have_encoding_file = false;
1871 Vector<String> ligkern;
1872 Vector<String> pos;
1873 Vector<String> unicoding;
1874 Vector<String> base_encoding_files;
1875 bool no_ecommand = false, default_ligkern = true;
1876 int warn_missing = -1;
1877 unsigned specified_output_flags = 0;
1878 String codingscheme;
1879 const char* odirs[NUMODIR + 1];
1880 for (int i = 0; i <= NUMODIR; ++i) {
1881 odirs[i] = 0;
1882 }
1883
1884 GlyphFilter current_substitution_filter;
1885 GlyphFilter current_alternate_filter;
1886 GlyphFilter* current_filter_ptr = &null_filter;
1887 Vector<GlyphFilter*> allocated_filters;
1888
1889 while (1) {
1890 int opt = Clp_Next(clp);
1891 switch (opt) {
1892
1893 case SCRIPT_OPT: {
1894 String arg = clp->vstr;
1895 int period = arg.find_left('.');
1896 OpenType::Tag scr(period <= 0 ? arg : arg.substring(0, period));
1897 if (scr.valid() && period > 0) {
1898 OpenType::Tag lang(arg.substring(period + 1));
1899 if (lang.valid()) {
1900 interesting_scripts.push_back(scr);
1901 interesting_scripts.push_back(lang);
1902 } else
1903 usage_error(errh, "bad language tag");
1904 } else if (scr.valid()) {
1905 interesting_scripts.push_back(scr);
1906 interesting_scripts.push_back(OpenType::Tag());
1907 } else
1908 usage_error(errh, "bad script tag");
1909 break;
1910 }
1911
1912 case FEATURE_OPT: {
1913 OpenType::Tag t(clp->vstr);
1914 if (!t.valid())
1915 usage_error(errh, "bad feature tag");
1916 else if (feature_filters[t])
1917 usage_error(errh, "feature %<%s%> included twice", t.text().c_str());
1918 else {
1919 if (!current_filter_ptr) {
1920 current_filter_ptr = new GlyphFilter(current_substitution_filter + current_alternate_filter);
1921 allocated_filters.push_back(current_filter_ptr);
1922 }
1923 interesting_features.push_back(t);
1924 feature_filters.insert(t, current_filter_ptr);
1925 }
1926 break;
1927 }
1928
1929 case LETTER_FEATURE_OPT: {
1930 OpenType::Tag t(clp->vstr);
1931 if (!t.valid())
1932 usage_error(errh, "bad feature tag");
1933 else if (feature_filters[t])
1934 usage_error(errh, "feature %<%s%> included twice", t.text().c_str());
1935 else {
1936 interesting_features.push_back(t);
1937 GlyphFilter* gf = new GlyphFilter;
1938 gf->add_substitution_filter("<Letter>", false, errh);
1939 *gf += current_alternate_filter;
1940 feature_filters.insert(t, gf);
1941 }
1942 break;
1943 }
1944
1945 case SUBS_FILTER_OPT:
1946 current_substitution_filter = null_filter;
1947 /* fallthru */
1948 case EXCLUDE_SUBS_OPT:
1949 case INCLUDE_SUBS_OPT:
1950 current_substitution_filter.add_substitution_filter(clp->vstr, opt == EXCLUDE_SUBS_OPT, errh);
1951 current_filter_ptr = 0;
1952 break;
1953
1954 case CLEAR_SUBS_OPT:
1955 current_substitution_filter = null_filter;
1956 current_filter_ptr = 0;
1957 break;
1958
1959 case ENCODING_OPT:
1960 if (encoding_file)
1961 usage_error(errh, "encoding specified twice");
1962 encoding_file = clp->vstr;
1963 have_encoding_file = true;
1964 break;
1965
1966 case LITERAL_ENCODING_OPT:
1967 if (encoding_file)
1968 usage_error(errh, "encoding specified twice");
1969 encoding_file = clp->vstr;
1970 have_encoding_file = true;
1971 literal_encoding = true;
1972 break;
1973
1974 case BASE_ENCODINGS_OPT:
1975 base_encoding_files.push_back(clp->vstr);
1976 break;
1977
1978 case EXTEND_OPT:
1979 if (extend)
1980 usage_error(errh, "extend value specified twice");
1981 extend = clp->val.d;
1982 break;
1983
1984 case SLANT_OPT:
1985 if (slant)
1986 usage_error(errh, "slant value specified twice");
1987 slant = clp->val.d;
1988 break;
1989
1990 case LETTERSPACE_OPT:
1991 if (letterspace)
1992 usage_error(errh, "letterspacing value specified twice");
1993 letterspace = clp->val.i;
1994 break;
1995
1996 case SPACE_FACTOR_OPT:
1997 if (space_factor != 1)
1998 usage_error(errh, "space factor specified twice");
1999 space_factor = clp->val.d;
2000 break;
2001
2002 case MATH_SPACING_OPT:
2003 math_spacing = !clp->negated;
2004 if (math_spacing && clp->have_val) {
2005 if (clp->val.i < 0 || clp->val.i > 255)
2006 usage_error(errh, "--math-spacing skew character must be between 0 and 255");
2007 skew_char = clp->val.i;
2008 }
2009 break;
2010
2011 case DESIGN_SIZE_OPT:
2012 if (design_size > 0)
2013 usage_error(errh, "design size value specified twice");
2014 else if (clp->val.d <= 0)
2015 usage_error(errh, "design size must be > 0");
2016 design_size = clp->val.d;
2017 break;
2018
2019 case LIGKERN_OPT:
2020 ligkern.push_back(clp->vstr);
2021 break;
2022
2023 case POSITION_OPT:
2024 pos.push_back(clp->vstr);
2025 break;
2026
2027 case WARN_MISSING_OPT:
2028 warn_missing = !clp->negated;
2029 break;
2030
2031 case NO_ECOMMAND_OPT:
2032 no_ecommand = true;
2033 break;
2034
2035 case DEFAULT_LIGKERN_OPT:
2036 default_ligkern = !clp->negated;
2037 break;
2038
2039 case BOUNDARY_CHAR_OPT:
2040 ligkern.push_back(String("|| = ") + String(clp->val.i));
2041 break;
2042
2043 case ALTSELECTOR_CHAR_OPT:
2044 ligkern.push_back(String("^^ = ") + String(clp->val.i));
2045 break;
2046
2047 case ALTSELECTOR_FEATURE_OPT: {
2048 OpenType::Tag t(clp->vstr);
2049 if (!t.valid())
2050 usage_error(errh, "bad feature tag");
2051 else if (altselector_feature_filters[t])
2052 usage_error(errh, "altselector feature %<%s%> included twice", t.text().c_str());
2053 else {
2054 if (!current_filter_ptr) {
2055 current_filter_ptr = new GlyphFilter(current_substitution_filter + current_alternate_filter);
2056 allocated_filters.push_back(current_filter_ptr);
2057 }
2058 altselector_features.push_back(t);
2059 altselector_feature_filters.insert(t, current_filter_ptr);
2060 }
2061 break;
2062 }
2063
2064 case ALTERNATES_FILTER_OPT:
2065 current_alternate_filter = null_filter;
2066 /* fallthru */
2067 case EXCLUDE_ALTERNATES_OPT:
2068 case INCLUDE_ALTERNATES_OPT:
2069 current_alternate_filter.add_alternate_filter(clp->vstr, opt == EXCLUDE_ALTERNATES_OPT, errh);
2070 current_filter_ptr = 0;
2071 break;
2072
2073 case CLEAR_ALTERNATES_OPT:
2074 current_alternate_filter = null_filter;
2075 current_filter_ptr = 0;
2076 break;
2077
2078 case UNICODING_OPT:
2079 unicoding.push_back(clp->vstr);
2080 break;
2081
2082 case CODINGSCHEME_OPT:
2083 if (codingscheme)
2084 usage_error(errh, "coding scheme specified twice");
2085 codingscheme = clp->vstr;
2086 if (codingscheme.length() > 39)
2087 errh->warning("only first 39 characters of coding scheme are significant");
2088 if (codingscheme.find_left('(') >= 0 || codingscheme.find_left(')') >= 0)
2089 usage_error(errh, "coding scheme cannot contain parentheses");
2090 break;
2091
2092 case AUTOMATIC_OPT:
2093 automatic = !clp->negated;
2094 break;
2095
2096 case VENDOR_OPT:
2097 if (!set_vendor(clp->vstr))
2098 usage_error(errh, "vendor name specified twice");
2099 break;
2100
2101 case TYPEFACE_OPT:
2102 if (!set_typeface(clp->vstr, true))
2103 usage_error(errh, "typeface name specified twice");
2104 break;
2105
2106 case VIRTUAL_OPT:
2107 if (clp->negated)
2108 output_flags &= ~G_VMETRICS;
2109 else
2110 output_flags |= G_VMETRICS;
2111 specified_output_flags |= G_VMETRICS;
2112 break;
2113
2114 case NO_ENCODING_OPT:
2115 case NO_TYPE1_OPT:
2116 case NO_DOTLESSJ_OPT:
2117 case NO_UPDMAP_OPT:
2118 case UPDMAP_SYS_OPT:
2119 output_flags &= ~(opt - NO_OUTPUT_OPTS);
2120 specified_output_flags |= opt - NO_OUTPUT_OPTS;
2121 break;
2122
2123 case TRUETYPE_OPT:
2124 case TYPE42_OPT:
2125 case UPDMAP_USER_OPT:
2126 if (!clp->negated)
2127 output_flags |= (opt - YES_OUTPUT_OPTS);
2128 else
2129 output_flags &= ~(opt - YES_OUTPUT_OPTS);
2130 specified_output_flags |= opt - YES_OUTPUT_OPTS;
2131 break;
2132
2133 case OUTPUT_ENCODING_OPT:
2134 if (out_encoding_file)
2135 usage_error(errh, "encoding output file specified twice");
2136 out_encoding_file = (clp->have_val ? clp->vstr : "-");
2137 output_flags = G_ENCODING;
2138 specified_output_flags = -1;
2139 break;
2140
2141 case MINIMUM_KERN_OPT:
2142 minimum_kern = clp->val.d;
2143 break;
2144
2145 case MAP_FILE_OPT:
2146 if (clp->negated)
2147 output_flags &= ~G_PSFONTSMAP;
2148 else {
2149 output_flags |= G_PSFONTSMAP;
2150 if (!set_map_file(clp->vstr))
2151 usage_error(errh, "map file specified twice");
2152 }
2153 specified_output_flags |= G_PSFONTSMAP;
2154 break;
2155
2156 case PL_OPT:
2157 if (clp->negated)
2158 output_flags &= ~G_ASCII;
2159 else
2160 output_flags |= G_ASCII;
2161 specified_output_flags |= G_ASCII;
2162 break;
2163
2164 case TFM_OPT:
2165 if (clp->negated)
2166 output_flags &= ~G_BINARY;
2167 else
2168 output_flags |= G_BINARY;
2169 specified_output_flags |= G_BINARY;
2170 break;
2171
2172 case ENCODING_DIR_OPT:
2173 case TFM_DIR_OPT:
2174 case PL_DIR_OPT:
2175 case VF_DIR_OPT:
2176 case VPL_DIR_OPT:
2177 case TYPE1_DIR_OPT:
2178 case TRUETYPE_DIR_OPT:
2179 case TYPE42_DIR_OPT:
2180 case DIR_OPT:
2181 if (!odirs[opt - DIR_OPTS])
2182 odirs[opt - DIR_OPTS] = clp->vstr;
2183 else
2184 usage_error(errh, "%s directory specified twice", odirname(opt - DIR_OPTS));
2185 break;
2186
2187 case FONT_NAME_OPT:
2188 font_name:
2189 if (font_name)
2190 usage_error(errh, "font name specified twice");
2191 font_name = clp->vstr;
2192 break;
2193
2194 case FIXED_PITCH_OPT:
2195 override_is_fixed_pitch = true;
2196 is_fixed_pitch = !clp->negated;
2197 break;
2198
2199 case PROPORTIONAL_WIDTH_OPT:
2200 override_is_fixed_pitch = true;
2201 is_fixed_pitch = !!clp->negated;
2202 break;
2203
2204 case ITALIC_ANGLE_OPT:
2205 override_italic_angle = true;
2206 italic_angle = clp->val.d;
2207 break;
2208
2209 case GLYPHLIST_OPT:
2210 glyphlist_files.push_back(clp->vstr);
2211 break;
2212
2213 case QUERY_FEATURES_OPT:
2214 usage_error(errh, "run %<otfinfo --query-features%> instead");
2215 break;
2216
2217 case QUERY_SCRIPTS_OPT:
2218 usage_error(errh, "run %<otfinfo --query-scripts%> instead");
2219 break;
2220
2221 case QUIET_OPT:
2222 if (clp->negated)
2223 errh = ErrorHandler::default_handler();
2224 else
2225 // 9.Nov.05 -- need a new SilentErrorHandler, because we use
2226 // the base SilentErrorHandler elsewhere to ignore errors
2227 errh = new SilentErrorHandler;
2228 break;
2229
2230 case VERBOSE_OPT:
2231 verbose = !clp->negated;
2232 break;
2233
2234 case NOCREATE_OPT:
2235 no_create = clp->negated;
2236 break;
2237
2238 case FORCE_OPT:
2239 force = !clp->negated;
2240 break;
2241
2242 case KPATHSEA_DEBUG_OPT:
2243 #if HAVE_KPATHSEA
2244 kpsei_set_debug_flags(clp->val.u);
2245 #else
2246 errh->warning("Not compiled with kpathsea!");
2247 #endif
2248 break;
2249
2250 case X_HEIGHT_OPT: {
2251 char* ends;
2252 if (strcmp(clp->vstr, "auto") == 0)
2253 override_x_height = FontInfo::x_height_auto;
2254 else if (strcmp(clp->vstr, "x") == 0)
2255 override_x_height = FontInfo::x_height_x;
2256 else if (strcmp(clp->vstr, "font") == 0
2257 || strcmp(clp->vstr, "os/2") == 0)
2258 override_x_height = FontInfo::x_height_os2;
2259 else if ((x_height = strtod(clp->vstr, &ends)) >= 0
2260 && *ends == 0 && *clp->vstr != 0)
2261 override_x_height = FontInfo::x_height_explicit;
2262 else
2263 usage_error(errh, "bad --x-height option");
2264 break;
2265 }
2266
2267 case VERSION_OPT:
2268 printf("otftotfm (LCDF typetools) %s\n", VERSION);
2269 printf("Copyright (C) 2002-2023 Eddie Kohler\n\
2270 This is free software; see the source for copying conditions.\n\
2271 There is NO warranty, not even for merchantability or fitness for a\n\
2272 particular purpose.\n");
2273 exit(0);
2274 break;
2275
2276 case HELP_OPT:
2277 usage();
2278 exit(0);
2279 break;
2280
2281 case Clp_NotOption:
2282 if (input_file && font_name)
2283 usage_error(errh, "too many arguments");
2284 else if (input_file)
2285 goto font_name;
2286 else
2287 input_file = clp->vstr;
2288 break;
2289
2290 case Clp_Done:
2291 goto done;
2292
2293 case Clp_BadOption:
2294 usage_error(errh, 0);
2295 break;
2296
2297 default:
2298 break;
2299
2300 }
2301 }
2302
2303 done:
2304 // check for odd option combinations
2305 if (warn_missing > 0 && !(output_flags & G_VMETRICS))
2306 errh->warning("%<--warn-missing%> has no effect with %<--no-virtual%>");
2307 if (!(specified_output_flags & (G_BINARY | G_ASCII)))
2308 output_flags |= G_BINARY;
2309
2310 // set up file names
2311 if (!input_file)
2312 usage_error(errh, "no font filename provided");
2313 if (encoding_file == "-")
2314 encoding_file = "";
2315
2316 // set up output directories
2317 if (odirs[NUMODIR]) {
2318 for (int i = 0; i < NUMODIR; ++i)
2319 if (!odirs[i])
2320 odirs[i] = odirs[NUMODIR];
2321 }
2322 for (int i = 0; i < NUMODIR; ++i)
2323 if (odirs[i])
2324 setodir(i, odirs[i]);
2325
2326 // set up feature filters
2327 if (!altselector_features.size()) {
2328 if (!current_filter_ptr) {
2329 current_filter_ptr = new GlyphFilter(current_substitution_filter + current_alternate_filter);
2330 allocated_filters.push_back(current_filter_ptr);
2331 }
2332 altselector_features.push_back(OpenType::Tag("dlig"));
2333 altselector_feature_filters.insert(OpenType::Tag("dlig"), current_filter_ptr);
2334 altselector_features.push_back(OpenType::Tag("salt"));
2335 altselector_feature_filters.insert(OpenType::Tag("salt"), current_filter_ptr);
2336 } else if (!current_filter_ptr) {
2337 errh->warning("some filtering options ignored");
2338 errh->message("(--include-*, --exclude-*, and --*-filter options must occur\nbefore the feature options to which they should apply.)");
2339 }
2340
2341 try {
2342 // read font
2343 otf_data = read_file(input_file, errh);
2344 if (errh->nerrors())
2345 exit(1);
2346
2347 LandmarkErrorHandler cerrh(errh, printable_filename(input_file));
2348 BailErrorHandler bail_errh(&cerrh);
2349
2350 OpenType::Font otf(otf_data, &bail_errh);
2351 assert(otf.ok());
2352
2353 // figure out scripts we care about
2354 if (!interesting_scripts.size()) {
2355 interesting_scripts.push_back(Efont::OpenType::Tag("latn"));
2356 interesting_scripts.push_back(Efont::OpenType::Tag());
2357 }
2358 std::sort(interesting_features.begin(), interesting_features.end());
2359 std::sort(altselector_features.begin(), altselector_features.end());
2360
2361 // find glyphlist
2362 if (!glyphlist_files.size()) {
2363 #if HAVE_KPATHSEA
2364 if (String g = kpsei_find_file("glyphlist.txt", KPSEI_FMT_MAP)) {
2365 glyphlist_files.push_back(g);
2366 if (verbose)
2367 errh->message("glyphlist.txt found with kpathsea at %s", g.c_str());
2368 } else
2369 #endif
2370 glyphlist_files.push_back(GLYPHLISTDIR "/glyphlist.txt");
2371 #if HAVE_KPATHSEA
2372 if (String g = kpsei_find_file("texglyphlist.txt", KPSEI_FMT_MAP)) {
2373 glyphlist_files.push_back(g);
2374 if (verbose)
2375 errh->message("texglyphlist.txt found with kpathsea at %s", g.c_str());
2376 } else
2377 #endif
2378 glyphlist_files.push_back(GLYPHLISTDIR "/texglyphlist.txt");
2379 }
2380
2381 // read glyphlist
2382 for (String *g = glyphlist_files.begin(); g < glyphlist_files.end(); g++)
2383 if (String s = read_file(*g, errh, true))
2384 DvipsEncoding::add_glyphlist(s);
2385
2386 // read base encodings
2387 for (String *s = base_encoding_files.begin(); s < base_encoding_files.end(); s++)
2388 parse_base_encodings(*s, errh);
2389
2390 // read encoding
2391 DvipsEncoding dvipsenc;
2392 if (encoding_file) {
2393 if (String path = locate_encoding(encoding_file, errh))
2394 dvipsenc.parse(path, no_ecommand, no_ecommand, errh);
2395 else
2396 errh->fatal("encoding %<%s%> not found", encoding_file.c_str());
2397 } else {
2398 String cff_data(otf.table("CFF"));
2399 if (!cff_data) {
2400 errh->error("explicit encoding required for TrueType fonts");
2401 errh->message("(Use %<-e ENCODING%> to choose an encoding. %<-e texnansx%> often works.)");
2402 exit(1);
2403 } else if (!have_encoding_file) {
2404 errh->warning("no encoding provided");
2405 errh->message("(Use %<-e ENCODING%> to choose an encoding. %<-e texnansx%> often works,\nor say %<-e -%> to turn off this warning.)");
2406 }
2407
2408 // use encoding from font
2409 Cff cff(cff_data, otf.units_per_em(), &bail_errh);
2410 Cff::FontParent *font = cff.font(PermString(), &bail_errh);
2411 assert(cff.ok() && font->ok());
2412 if (Type1Encoding *t1e = font->type1_encoding()) {
2413 for (int i = 0; i < 256; i++)
2414 dvipsenc.encode(i, (*t1e)[i]);
2415 } else
2416 errh->fatal("font has no encoding, specify one explicitly");
2417 }
2418
2419 // apply default ligkern commands
2420 if (default_ligkern)
2421 dvipsenc.parse_ligkern(default_ligkerns, 0, ErrorHandler::silent_handler());
2422
2423 // apply command-line ligkern commands and coding scheme
2424 cerrh.set_landmark("--ligkern command");
2425 for (int i = 0; i < ligkern.size(); i++)
2426 dvipsenc.parse_ligkern(ligkern[i], 1, &cerrh);
2427 cerrh.set_landmark("--position command");
2428 for (int i = 0; i < pos.size(); i++)
2429 dvipsenc.parse_position(pos[i], 1, &cerrh);
2430 cerrh.set_landmark("--unicoding command");
2431 for (int i = 0; i < unicoding.size(); i++)
2432 dvipsenc.parse_unicoding(unicoding[i], 1, &cerrh);
2433 if (codingscheme)
2434 dvipsenc.set_coding_scheme(codingscheme);
2435 if (warn_missing >= 0)
2436 dvipsenc.set_warn_missing(warn_missing);
2437
2438 do_file(input_file, otf, dvipsenc, literal_encoding, errh);
2439
2440 } catch (OpenType::Error e) {
2441 errh->error("unhandled exception %<%s%>", e.description.c_str());
2442 }
2443
2444 for (int i = 0; i < allocated_filters.size(); ++i)
2445 delete allocated_filters[i];
2446 Clp_DeleteParser(clp);
2447 return (errh->nerrors() == 0 ? 0 : 1);
2448 }