Debian Codegraph @

texk/ps2pk/psearch.c

raw
1 /* FILE: psearch.c
2 * PURPOSE: PATH search module
3 * VERSION: 1.7 (December 2014)
4 * AUTHOR: Piet Tutelaers
5 * (see README for license)
6 */
7
8 #define _POSIX_SOURCE 1
9 #ifdef ultrix
10 #define __POSIX /* otherwise MAXNAMLEN undefined */
11 #endif
12
13 #include <sys/types.h>
14 #include <sys/stat.h> /* struct stat */
15 #include <dirent.h> /* opendir(), readdir(), closedir() */
16 #include "ctype.h" /* isalpha() */
17 #include <stdio.h> /* sprintf(), fclose() */
18 #include "stdlib.h" /* getenv(), malloc() */
19 #include <stdarg.h> /* va_start(), va_arg(), va_end() */
20 #include "string.h" /* strcat(), strchr(), strcmp(), strcpy(), strlen(),
21 strncmp(), strncpy(), strstr() */
22 #include "basics.h" /* fatal() */
23 #include "strexpr.h" /* strexpr() */
24 #include "filenames.h" /* equal(), extension() */
25 #include "texfiles.h" /* four(), one(), two() */
26
27 #ifdef UNIX
28 #include <pwd.h> /* getpwnam() */
29
30 int tilde = 1; /* Substitute ~ and ~user */
31 static char *home = NULL;
32
33 /*
34 * During scanning of paths we often need to replace ~user with user's
35 * HOME directory and ~ with HOME directory. Subtilde() copies the actual
36 * value of `~' or `~user' from <path> into <fn>. The pointers <fn> and
37 * <path> are `updated'.
38 */
39 void subtilde(char **fn, char **path)
40 { char pattern[32], *p; int i;
41
42 i = 0; p = *path;
43 while (*p != '\0' && *p != DIRSEP && *p != PATHSEP)
44 pattern[i++] = *p++ ;
45 pattern[i] = '\0' ;
46 if (pattern[0] != '~') return;
47 if (pattern[1] == '\0') {
48 if (home == NULL)
49 home = getenv("HOME");
50 if (home == NULL) fatal("You don't have a HOME!\n");
51 sprintf(*fn, "%s\0", home);
52 *fn += strlen(*fn);
53 *path = p;
54 }
55 else {
56 struct passwd *pw;
57 if (pw = getpwnam(&pattern[1])) {
58 sprintf(*fn, "%s\0", pw->pw_dir);
59 *fn += strlen(*fn); *path = p;
60 }
61 else
62 fatal("%s: no such user\n", &pattern[1]) ;
63 }
64 }
65 #else
66 static int tilde = 0; /* Don't substitute ~ and ~user */
67 static void subtilde(char **fn, char **path) {}
68 #endif
69
70 /*
71 * Return a path constructed by <env> and <deFault>. If <env> is empty
72 * the returned path equals <deFault>, otherwise the returned path is
73 * <env> in which empty path elements are replaced by <deFault>. Double
74 * path elements are NOT removed.
75 */
76 char *path(char *deFault, char *env) {
77 char *e, *p, *q; int len, left = MAXPATHLEN;
78
79 if (env == NULL) return deFault;
80
81 p = (char *) malloc(MAXPATHLEN);
82 if (p == NULL) fatal("Out of memory\n");
83
84 q = p; e = env;
85 while (*e) {
86 if (*e == PATHSEP) {
87 if (left == MAXPATHLEN) {
88 len = strlen(deFault);
89 if (len > left-1) fatal("'%s' path too long!\n", env);
90 strcpy(q, deFault);
91 q += len; left -= len;
92 *q++ = *e++; left--;
93 }
94 else if (*(e+1) == PATHSEP || *(e+1) == '\0') {
95 *q++ = *e++; left--;
96 len = strlen(deFault);
97 if (len > left) fatal("'%s' path too long!\n", env);
98 strcpy(q, deFault);
99 q += len; left -= len;
100 }
101 else {
102 *q++ = *e++; left--;
103 }
104 }
105 else {
106 *q++ = *e++; left--;
107 }
108 if (left == 0) fatal("'%s' path too long!\n", env);
109 }
110 *q = '\0';
111 return p;
112 }
113
114 /*
115 * Rsearch() searches <file> through <path>. Recursion introduced by
116 * RECURSIVE string (system dependant) will be followed. Search stops
117 * after first match.
118 */
119 static char *rsearch(char *path, char *file)
120 {
121 struct stat status;
122 DIR *D;
123 struct dirent *de;
124 int i;
125 char *res = NULL, *ext, *file_ext,
126 head[MAXPATHLEN], target[MAXPATHLEN], *tail;
127 char fn[MAXPATHLEN];
128
129 /* determine head and tail of path */
130 i = 0;
131 while (*(path+i) != '\0' && strncmp(path+i, RECURSIVE, 2) != 0) {
132 head[i] = *(path+i); i++;
133 }
134 head[i] = '\0';
135 if (*(path+i) == '\0') tail = NULL;
136 else tail = path+i+2;
137
138 /* Check if we have found <file> */
139 if (tail == NULL || *tail == '\0') {
140 sprintf(fn, "%s%c%s", head, DIRSEP, file);
141 if (stat(fn, &status) == 0) {
142 res = malloc(strlen(fn)+1);
143 if (res == NULL) fatal("Out of memory\n");
144 strcpy(res, fn);
145 return res;
146 }
147 /* No recursion, so stop */
148 if (tail == NULL) return NULL;
149 }
150
151 if ((D = opendir(head)) == NULL) return NULL;
152 file_ext = extension(file);
153
154 /* now read directories and probe files */
155 while ((de = readdir(D)) != NULL) {
156 /* Ignore `.' and `..' directories */
157 if (strcmp(de->d_name, ".") == 0) continue;
158 if (strcmp(de->d_name, "..") == 0) continue;
159
160 /* Check if we have a directory */
161 sprintf(fn, "%s%c%s", head, DIRSEP, de->d_name);
162 (void) stat(fn, &status);
163 if (!S_ISDIR(status.st_mode)) {
164 /* if we are looking for a file with an extension and we find
165 * files with the same or a different extension we may consider
166 * this directory as a wrong place unless the user has defined
167 * funny directory search paths
168 */
169 if (file_ext && (ext = extension(de->d_name))) {
170 if (equal(ext, ".pk")) break;
171 if (equal(ext, ".vf")) break;
172 if (equal(ext, ".mf")) break;
173 if (equal(ext, ".tfm")) break;
174 if (equal(ext, ".afm")) break;
175 }
176 continue;
177 }
178
179 /* Directories with no real subdirectories can be skipped
180 * unless the file we are looking for is there. Unfortunately
181 * this shortcut only works for UNIX systems. On other systems
182 * the above check on extensions may help.
183 */
184 #if defined(UNIX)
185 if (status.st_nlink == 2) {
186 if (strchr(file, DIRSEP)) continue;
187 if ((*tail == '\0') && (res = rsearch(fn, file))) break;
188 continue;
189 }
190 #endif
191
192 /* path of the form "/aap/noot/mies//" */
193 if (*tail == '\0') {
194 sprintf(fn, "%s%c%s%s", head, DIRSEP, de->d_name, RECURSIVE);
195 if (res = rsearch(fn, file)) break;
196 continue;
197 }
198
199 /* path of the form "/aap/noot//mies" */
200
201 /* search /aap/noot/<d_name>// <tail>/<file> */
202 sprintf(fn, "%s%c%s%s", head, DIRSEP, de->d_name, RECURSIVE);
203 sprintf(target, "%s%c%s", tail, DIRSEP, file);
204 if (res = rsearch(fn, target)) break;
205 }
206 closedir(D);
207 return res;
208 }
209
210 /* Is <name> an absolute filename? */
211 int absname(char *name) {
212
213 if (*name == DIRSEP) return 1;
214 #ifdef MSDOS
215 if (*(name+1) == ':' && *(name+2) == DIRSEP && isalpha(*name)) return 1;
216 #endif
217 return 0;
218 }
219
220 /*
221 * Look for a <file> in <path>. Return absolute filename if found.
222 * If not found return NULL (if <terminate> is 0) or terminate program
223 * with appropriate message (if <terminate> is not equal to 0).
224 */
225 char *search_file(char *path, char *file, int terminate) {
226 char *fn, pe[MAXPATHLEN], *ppe, *ppath;
227 struct stat status;
228
229 if (path == NULL || *path == '\0' || absname(file)) {
230 if (stat(file, &status) == 0) return file;
231 if (terminate) fatal("File <%s> not found\n", file);
232 return NULL;
233 }
234 ppath = path;
235 while (*ppath) {
236 /* copy next pathelement into pe */
237 ppe = pe;
238 while (*ppath != PATHSEP && *ppath != '\0') {
239 if (tilde && *ppath == '~')
240 subtilde(&ppe, &ppath);
241 else
242 *ppe++ = *ppath++;
243 }
244 *ppe = '\0';
245 if (*ppath == PATHSEP) ppath++;
246 if (fn = rsearch(pe, file)) return fn;
247 }
248 if (terminate) fatal("File <%s> not found in path \"%s\"\n", file, path);
249 return NULL;
250 }
251
252 /*
253 * Now some functions for PK font search
254 */
255
256 /*
257 * replace <pattern> in <cs> by <value>. If the <pattern> is %b or %d
258 * the value will be converted to a decimal value.
259 */
260 static void replace(char *cs, char *pattern, void *value) {
261 char temp[MAXPATHLEN], *p, *q; int len;
262
263 while (q = strstr(cs, pattern)) {
264 strcpy(temp, q+strlen(pattern));
265 switch (*(pattern+1)) {
266 case 'b':
267 case 'd':
268 sprintf(q, "%d", *((int *)value));
269 len = strlen(q);
270 break;
271 case 'F':
272 sprintf(q, "%-8s", (char *) value);
273 len = strlen (q);
274 break;
275 case 'f':
276 sprintf(q, "%s", (char *) value);
277 len = strlen (q);
278 break;
279 default:
280 sprintf(q, "%s", (char *) value);
281 len = strlen (q);
282 break;
283 }
284 strcpy(q+len, temp);
285 }
286 }
287
288 /*
289 * This function substitutes the <patterns> encountered in <str>
290 * with their corresponding <value>. Recognized patterns are %b, %d,
291 * %f, %F and %m. They will be replaced with their corresponding integer
292 * (%b, %d) or string values (%f, %F and %m). These values can be used as
293 * placeholders for basic resolution (%b), resolution (%d), font name
294 * (%f or %F) or mode definition (%m). The %F is a special case for
295 * representing the fontname leftadjusted in a string of eight characters.
296 */
297
298 void substitute(char *str, char *patterns, ...) {
299 va_list ap;
300 char *p;
301 char *svalue; int ivalue;
302
303 /* get arguments ... */
304 va_start(ap, patterns);
305 for (p = patterns; *p; p++) {
306 if (*p != '%') {
307 fatal("%s: invalid format\n");
308 }
309 switch (*++p) {
310 case 'b':
311 ivalue = va_arg(ap, int);
312 replace(str, "%b", &ivalue);
313 break;
314 case 'd':
315 ivalue = va_arg(ap, int);
316 replace(str, "%d", &ivalue);
317 break;
318 case 'F':
319 svalue = va_arg(ap, char *);
320 replace(str, "%F", svalue);
321 break;
322 case 'f':
323 svalue = va_arg(ap, char *);
324 replace(str, "%f", svalue);
325 break;
326 case 'm':
327 svalue = va_arg(ap, char *);
328 replace(str, "%m", svalue);
329 break;
330 case 'p':
331 svalue = va_arg(ap, char *);
332 replace(str, "%p", svalue);
333 break;
334 default:
335 fatal("%s: invalid letter (%c) in format\n", patterns, *p);
336 }
337 }
338 va_end(ap);
339 }
340
341 /* global font searching parameters */
342 static char *_mode = NULL;
343 static int _margin = 0, _bdpi = -1;
344 static char *_tolerance = NULL;
345
346 void init_pksearch(int bdpi, char *mode, int margin, char *tolerance) {
347 _bdpi = bdpi;
348 _mode = mode;
349 _margin = margin;
350 _tolerance = tolerance;
351 }
352
353 /* evaluate <expr> after substituting %d with <dpi>. Return the
354 * integer result or abort with message when invalid expression.
355 */
356 int evaluate(char *expr, int dpi) {
357 char expression[128];
358 int result;
359
360 if (expr == NULL || *expr == '\0') return 0;
361 strcpy(expression, expr);
362 substitute(expression, "%d", dpi);
363 if (strexpr(&result, expression))
364 fatal("%s: expression error\n", expression);
365 return result;
366 }
367
368 #define INT(x) ((int)(x+0.5))
369
370 /*
371 * Round <dpi> to a whole or half magstep if the difference is within
372 * a certain _tolerance from it.
373 */
374 int nearesthalf(int dpi) {
375 double near = _bdpi, half = 1.095445115; int tolerance;
376
377 tolerance = evaluate(_tolerance, dpi);
378 if (tolerance == 0 || dpi == _bdpi) return dpi;
379 if (dpi > INT(near)+tolerance)
380 while (dpi > INT(near)+tolerance) near*=half;
381 else if (dpi < INT(near)-tolerance)
382 while (dpi < INT(near)-tolerance) near/=half;
383 if (dpi >= INT(near)-tolerance && dpi <= INT(near)+tolerance)
384 return INT(near);
385 return dpi;
386 }
387
388 /*
389 * Look for a PK <font> of resolution <dpi> in <path>. To avoid floating
390 * around lots of different font sizes TeX prefers to work with whole
391 * and half magsteps. So instead of using a 330 dpi font for a 11 point
392 * version of a 300 dpi font we would prefer the 329 dpi size because
393 * this size matches magstep 0.5 of 300 (329 = int(300 * 1.2 ** 0.5).
394 * The process of truncating real font sizes to magsteps can be
395 * controlled by the global parameter <tolerance> which may be an
396 * expression of the actual value of <dpi> itself. The value dvips(1)
397 * uses for <tolerance> is 1 + <dpi> / 500 allowing more tolerance in
398 * bigger sizes. Due to round-off different DVI drivers choose different
399 * <dpi> sizes. With <margin> we can define what font sizes are looked
400 * at whenever size <dpi> is wanted. With <margin> set to zero only the
401 * exact size is looked at, while a value of one would allow for a
402 * round-off of one. Both <margin> and <tolerance> can be set before a
403 * search starts otherwise they get their default values (zero) with
404 * init_pksearch().
405 *
406 * When <path> does contain placeholders like %b, %d, %f, %p and %m
407 * they will be substituted by their corresponding values _bdpi, <dpi>,
408 * <font>, "pk" and _mode respectivally. This allows to define paths
409 * for a whole range of printers. Occurrences off ~ or * ~user in <path>
410 * will be substituted by the corresponding HOME directories on UNIX.
411 *
412 * The result of search_pkfile() is a pointer to the name of <font> when
413 * one is found otherwise NULL.
414 */
415 char *search_pkfile(char *path, char *texfont, int dpi) {
416 char *ppe, *pkpath, pe[MAXPATHLEN];
417 int del;
418 char *pkname;
419 struct stat status;
420
421 for (del=0; del <= _margin ; del=del>0?-del:-del+1) {
422 pkpath = path;
423 while (*pkpath) {
424 /* copy next pathelement into pe */
425 ppe = pe;
426 while (*pkpath != PATHSEP && *pkpath != '\0') {
427 if (tilde && *pkpath == '~')
428 subtilde(&ppe, &pkpath);
429 else
430 *ppe++ = *pkpath++;
431 }
432 *ppe = '\0';
433 if (strchr(pe, '%')) {
434 if (strstr(pe, "%d") && strstr(pe, "%f")) {
435 /* try filename after replacing placeholders */
436 substitute(pe, "%b%m%f%d%p",
437 _bdpi, _mode, texfont, dpi+del, "pk");
438 if (stat(pe, &status) == 0) {
439 pkname = malloc(strlen(pe)+1);
440 if (pkname == NULL) fatal("Out of memory\n");
441 strcpy(pkname, pe);
442 return pkname;
443 }
444 }
445 else /* %f and %d are required! */
446 fatal("%s: incomplete path element!\n", pe);
447 }
448 else {
449 sprintf(ppe, "%c%s.%dpk", DIRSEP, texfont, dpi+del);
450 if (stat(pe, &status) == 0) {
451 pkname = malloc(strlen(pe)+1);
452 if (pkname == NULL) fatal("Out of memory\n");
453 strcpy(pkname, pe);
454 return pkname;
455 }
456 }
457 if (*pkpath == PATHSEP) pkpath++;
458 }
459 }
460 return NULL;
461 }
462
463 /*
464 * Functions for handling emTeX's FLI files.
465 */
466
467 /*
468 * Look at the fonts in the font library by calling the function <font>.
469 * This function can stop the search by returning a 1 or continue by
470 * returning a zero. In this way we can look for just one font or for
471 * a whole series of fonts. If the search is stopped the name of the
472 * current FLI file is returned otherwise a NULL pointer.
473 */
474 char *search_flifile(char *fliname, int (*font)(char *, int)) {
475 unsigned short len, numsizes, numfonts, version1, version2;
476 char fontname[50];
477 int i, size;
478
479 FILE *FLI;
480
481 FLI = fopen(fliname, RB);
482 if (FLI == NULL) return NULL;
483
484 for (i=0; i<4; i++) {
485 fontname[i] = one(FLI); /* read header */
486 }
487 version1 = one(FLI);
488 version2 = one(FLI);
489 if (strncmp(fontname,"FLIB",4)!=0 || version1 != 2 || version2 != 0)
490 fatal("incorrect font library format");
491
492 (void) two(FLI); /* ignore directory length */
493 numsizes = two(FLI); /* number of sizes */
494 numfonts = two(FLI); /* number of fonts */
495 len = two(FLI); /* length of comment */
496 for (i=0; i<len; i++)
497 (void)one(FLI); /* skip comment */
498
499 for ( ;numsizes>0; numsizes--) {
500 /* for each font size in this library */
501 (void)two(FLI); /* length of size entry - ignore */
502 numfonts = two(FLI); /* number of fonts */
503 /* DPI (fixed point 16.16) */
504 size = (int)(four(FLI)/65536.0+0.5);
505
506 for ( ;numfonts > 0; numfonts--) {
507 /* read each entry */
508 (void)four(FLI); /* ignore length of font */
509 (void)four(FLI); /* offset to font */
510 len = one(FLI); /* length of name */
511 for (i=0; i<len; i++)
512 fontname[i] = one(FLI);
513 fontname[len] = '\0';
514 if (font(fontname, size) == 1) {
515 fclose(FLI);
516 return fliname;
517 };
518 }
519 }
520 fclose(FLI);
521 return NULL;
522 }
523
524 /*
525 * Look for font libraries in <path> (ex.: c:\emtex\texfonts;fli_0;fli_1).
526 * Run <font()> function for each .fli file found in <path>. Continue
527 * if this function returns NULL, stop otherwise.
528 */
529 char *search_flipath(char *flipath, int (*font)(char *, int)) {
530 char fn[MAXPATHLEN], *pfn, *pfli, *fliname;
531 int len;
532
533 if (flipath == NULL) fatal("Invalid fli path\n");
534
535 /* treat first element of flipath as a directory */
536 pfn = fn;
537 while (*flipath != PATHSEP && *flipath != '\0') {
538 *pfn++ = *flipath++;
539 }
540 *pfn = '\0'; len = strlen(fn);
541 if (len >= 1 && fn[len-1] != DIRSEP) *pfn++ = DIRSEP;
542
543 /* and next elements as fli files */
544 while (*flipath != '\0') {
545 /* copy next pathelement into fn */
546 pfli = pfn; flipath++;
547 while (*flipath != PATHSEP && *flipath != '\0') {
548 *pfli++ = *flipath++;
549 }
550 *pfli = '\0'; len = strlen(pfn);
551 if (len > 4 && strcmp(pfli-4, ".fli") != 0)
552 strcat(pfli, ".fli");
553 if ((fliname = search_flifile(fn, font)) != NULL)
554 return fliname;
555 }
556 return NULL;
557 }