Debian Codegraph @

texk/gsftopk/gsftopk.c

raw
1 /*========================================================================*\
2
3 Copyright (c) 1993-2000 Paul Vojta
4
5 Permission is hereby granted, free of charge, to any person obtaining a copy
6 of this software and associated documentation files (the "Software"), to
7 deal in the Software without restriction, including without limitation the
8 rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
9 sell copies of the Software, and to permit persons to whom the Software is
10 furnished to do so, subject to the following conditions:
11
12 The above copyright notice and this permission notice shall be included in
13 all copies or substantial portions of the Software.
14
15 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 PAUL VOJTA BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19 IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22 \*========================================================================*/
23
24 #if !lint
25 static char copyright[] =
26 "@(#) Copyright (c) 1993-1998 Paul Vojta.\n";
27 #endif
28
29 /*
30 * Reference for PK file format:
31 *
32 * Tomas Rokicki, Packed (PK) font file format, TUGBoat 6 (1985) 115-120.
33 */
34
35 /*
36 * Kpathsea version by Thomas Esser, John Interrante, Yves Arrouye, Karl Berry.
37 */
38
39 #include "version.h"
40
41 #ifndef KPATHSEA
42
43 #include "config.h"
44
45 /* Some O/S dependent kludges. */
46 #if _AIX
47 #define _ALL_SOURCE 1
48 #endif
49
50 #if __hpux
51 #define _HPUX_SOURCE 1
52 #endif
53
54 #if STDC_HEADERS
55 # include <stdlib.h>
56 # include <string.h>
57 #else
58 # if !HAVE_STRCHR
59 # define strchr index
60 # define strrchr rindex
61 # endif
62 char *strchr(), *strrchr();
63 # if !HAVE_MEMCPY
64 # define memcpy(d, s, n) bcopy((s), (d), (n))
65 # define memmove(d, s, n) bcopy((s), (d), (n))
66 # define memcmp(s1, s2, n) bcmp((s1), (s2), (n))
67 # endif
68 #endif
69
70 #if HAVE_UNISTD_H
71 #include <unistd.h>
72 #endif
73
74 #include <stdio.h>
75 #include <ctype.h>
76 #include <memory.h>
77 #include <sys/types.h>
78 #include <sys/stat.h>
79 #include <setjmp.h>
80 #include <signal.h>
81 #include <fcntl.h>
82
83 #include <errno.h>
84 #ifndef errno
85 extern int errno;
86 #endif
87
88 #if HAVE_DIRENT_H
89 # include <dirent.h>
90 # define NAMLEN(dirent) strlen((dirent)->d_name)
91 #else
92 # define dirent direct
93 # define NAMLEN(dirent) (dirent)->d_namlen
94 # if HAVE_SYS_NDIR_H
95 # include <sys/ndir.h>
96 # endif
97 # if HAVE_SYS_DIR_H
98 # include <sys/dir.h>
99 # endif
100 # if HAVE_NDIR_H
101 # include <ndir.h>
102 # endif
103 #endif
104
105 #if TIME_WITH_SYS_TIME
106 # include <sys/time.h>
107 # include <time.h>
108 #else
109 # if HAVE_SYS_TIME_H
110 # include <sys/time.h>
111 # else
112 # include <time.h>
113 # endif
114 #endif
115
116 #ifndef atof
117 double atof();
118 #endif
119 char *getenv();
120
121 /* <sys/types.h> is already included. */
122 #if HAVE_SYS_WAIT_H
123 #include <sys/wait.h>
124 #endif
125
126 #ifndef WIFSTOPPED
127 #define WIFSTOPPED(stat_val) (((stat_val) & 0377) == 0177)
128 #endif
129
130 #ifndef WIFSIGNALED
131 #define WIFSIGNALED(stat_val) (((stat_val) & 0377) != 0)
132 #endif
133
134 #ifndef WTERMSIG
135 #define WTERMSIG(stat_val) ((stat_val) & 0177)
136 #endif
137
138 #ifndef WEXITSTATUS
139 #define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
140 #endif
141
142 #ifndef SIGCHLD
143 #define SIGCHLD SIGCLD
144 #endif
145
146 /* How to open a text file for reading: */
147 #ifndef FOPEN_R_MODE
148 #define FOPEN_R_MODE "r"
149 #endif
150
151 /* How to open a binary file for reading: */
152 #ifndef FOPEN_RBIN_MODE
153 #if DOS
154 #define FOPEN_RBIN_MODE "r+b"
155 #elif VMS || VMCMS || OS2 || WIN32
156 #define FOPEN_RBIN_MODE "rb"
157 #else
158 #define FOPEN_RBIN_MODE "r"
159 #endif
160 #endif /* undef FOPEN_RBIN_MODE */
161
162 /* How to open a binary file for writing: */
163 #ifndef FOPEN_WBIN_MODE
164 #if DOS
165 #define FOPEN_WBIN_MODE "w+b"
166 #elif OS2 || WIN32
167 #define FOPEN_WBIN_MODE "wb"
168 #elif VMCMS
169 #define FOPEN_WBIN_MODE "wb, lrecl=1024, recfm=f"
170 #else
171 #define FOPEN_WBIN_MODE "w"
172 #endif
173 #endif /* undef FOPEN_WBIN_MODE */
174
175 #else /* KPATHSEA */
176
177 #include <kpathsea/config.h>
178 #include <kpathsea/c-errno.h>
179 #include <kpathsea/c-ctype.h>
180 #include <kpathsea/c-fopen.h>
181 #include <kpathsea/c-pathmx.h>
182 #include <kpathsea/proginit.h>
183 #include <kpathsea/tex-file.h>
184 #include <kpathsea/tex-make.h>
185 #include <kpathsea/variable.h>
186 #include <kpathsea/version.h>
187 #include <c-auto.h>
188 #include <signal.h>
189 #include <fcntl.h>
190 #include <setjmp.h>
191
192 #if TIME_WITH_SYS_TIME
193 # include <sys/time.h>
194 # include <time.h>
195 #else
196 # if HAVE_SYS_TIME_H
197 # include <sys/time.h>
198 # else
199 # include <time.h>
200 # endif
201 #endif
202
203 #if !HAVE_STRCHR
204 #define strchr index
205 #endif
206
207 #if !HAVE_STRRCHR
208 #define strrchr rindex
209 #endif
210
211 #if HAVE_POLL && !HAVE_POLL_H
212 #undef HAVE_POLL
213 #endif
214
215 /* Add two new flags to kpathsea_debug for debugging gsftopk */
216 #define GSPK_DEBUG_BITMAP (KPSE_LAST_DEBUG + 1)
217 #define GSPK_DEBUG_PK (KPSE_LAST_DEBUG + 2)
218
219 /* <sys/types.h> is already included: <kpathsea/config.h>
220 --> <kpathsea/c-std.h> --> <kpathsea/c-unistd.h>
221 --> <kpathsea/systypes.h> --> <sys/types.h>. */
222 #if HAVE_SYS_WAIT_H
223 # include <sys/wait.h>
224 #endif
225
226 #if WIN32
227
228 /* code from Akira Kakuto */
229
230 /* message values for callback */
231 #define GSDLL_STDIN 1
232 #define GSDLL_STDOUT 2
233 #define GSDLL_DEVICE 3
234 #define GSDLL_SYNC 4
235 #define GSDLL_PAGE 5
236 #define GSDLL_SIZE 6
237 #define GSDLL_POLL 7
238 /* return values from gsdll_init() */
239 #define GSDLL_INIT_IN_USE 100
240 #define GSDLL_INIT_QUIT 101
241
242 #include <windows.h>
243
244 HINSTANCE hgsdll = NULL;
245 PROC pgsdll_init = NULL;
246 PROC pgsdll_exit = NULL;
247 PROC pgsdll_revision = NULL;
248
249 #if 0 /* unused */
250 static long revision_n = 0;
251 static char product_str[128];
252 static char copyright_str[128];
253 static long revdate_n;
254 #endif /* 0, unused */
255
256 static void Win32Error(const char *s)
257 {
258 fprintf(stderr, "%s\n", s);
259 exit(EXIT_FAILURE);
260 }
261
262 #ifdef _WIN64
263 #define GSDLLNAME "gsdll64.dll"
264 #else
265 #define GSDLLNAME "gsdll32.dll"
266 #endif
267
268 static HINSTANCE gs_locate(void)
269 {
270 hgsdll = GetModuleHandle(GSDLLNAME);
271 if(hgsdll == NULL) {
272 hgsdll = LoadLibrary(GSDLLNAME);
273 }
274 return hgsdll;
275 }
276
277 static void gs_dll_release(void)
278 {
279 FreeLibrary(hgsdll);
280 }
281
282 static void gs_dll_initialize(void)
283 {
284 pgsdll_init = GetProcAddress(hgsdll, "gsdll_init");
285 pgsdll_exit = GetProcAddress(hgsdll, "gsdll_exit");
286 pgsdll_revision = GetProcAddress(hgsdll, "gsdll_revision");
287 if(pgsdll_init == NULL || pgsdll_exit == NULL ||
288 pgsdll_revision == NULL) {
289 fprintf(stderr, "Failed to get proc addresses in GSDLL32.\n");
290 gs_dll_release();
291 exit(100);
292 }
293 }
294
295 /* end of code from Akira Kakuto */
296
297 HANDLE hGsThread = NULL;
298 HANDLE hGsDataIn = 0, hGsDataOut = 0; /* Events to synchronize threads */
299 /* Arguments to gs dll */
300 const
301 char *gs_argv[] = { "rungs.exe", /* 0, dummy */
302 "-dNODISPLAY", /* 1, */
303 "-dNOGC", /* 2, */
304 "-dNOSAFER", /* 3, */
305 NULL, /* 4, substarg */
306 "-q", /* 5, */
307 "--", /* 6, */
308 NULL, /* 7, searchpath */
309 NULL, /* 8, PSname */
310 NULL, /* 9, dlstring != NULL ? dlstring : "" */
311 NULL, /* 10, specinfo */
312 NULL, /* 11, dpistr */
313 NULL /* 12, NULL terminator */
314 };
315 int gs_argc = 12;
316
317 char *buffer_stdin; /* This is the buffer from where data are taken. */
318
319 #else /* not WIN32 */
320
321 #ifndef WEXITSTATUS
322 #define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
323 #endif
324
325 #ifndef WIFSTOPPED
326 #define WIFSTOPPED(stat_val) (((stat_val) & 0377) == 0177)
327 #endif
328
329 #ifndef WIFSIGNALED
330 #define WIFSIGNALED(stat_val) (((stat_val) & 0377) != 0)
331 #endif
332
333 #ifndef WTERMSIG
334 #define WTERMSIG(stat_val) ((stat_val) & 0177)
335 #endif
336
337 #endif /* not WIN32 */
338
339 #endif /* KPATHSEA */
340
341 #if HAVE_POLL
342 # include <poll.h>
343 #else
344 # if HAVE_SYS_SELECT_H
345 # include <sys/select.h>
346 # else
347 # if HAVE_SELECT_H
348 # include <select.h>
349 # endif
350 # endif
351 #endif
352
353 #if HAVE_VFORK_H
354 #include <vfork.h>
355 #endif
356
357 #if _AMIGA
358 #include <proto/dos.h>
359 #include <dos/dostags.h>
360 #endif
361
362 #define NUMBER(x) (sizeof (x) / sizeof *(x))
363
364 /* if POSIX O_NONBLOCK is not available, use O_NDELAY */
365 #if !defined(O_NONBLOCK) && defined(O_NDELAY)
366 #define O_NONBLOCK O_NDELAY
367 #endif
368
369 #ifndef S_ISDIR
370 #if defined(S_IFMT) && defined(S_IFDIR)
371 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
372 #endif
373 #endif
374
375 #ifndef GS_PATH
376 #define GS_PATH "gs"
377 #endif
378
379 #include <stdarg.h>
380
381 typedef char Boolean;
382 #define True 1
383 #define False 0
384
385 typedef int wide_bool;
386
387 #ifndef MAXPATHLEN
388 #define MAXPATHLEN 256
389 #endif
390
391 #define PK_PRE (char) 247
392 #define PK_ID (char) 89
393 #define PK_SPC (char) 240
394 #define PK_POST (char) 245
395 #define PK_NOP (char) 246
396
397 #ifndef KPATHSEA
398 char progname[] = "gsftopk ";
399 #else
400 char progname[] = "gsftopk(k) ";
401 #endif
402
403 char version[] = VERSION;
404
405 /*
406 * Command line arguments
407 */
408
409 #define OPT_DBG 0x101
410
411 Boolean test = False;
412 char *fontname;
413 int fontlen;
414 char *mapline = NULL;
415 char *mapfile = NULL;
416 char gspath[] = GS_PATH; /* gs interpreter path */
417 Boolean dosnames = False;
418 Boolean quiet = False;
419
420 struct option {
421 const char *longname;
422 short shortname;
423 Boolean has_arg;
424 void *addr;
425 int value;
426 };
427
428 static const struct option options[] = {
429 {"test", 't', False, &test, True},
430 {"mapline", 0, True, &mapline, 0},
431 {"mapfile", 0, True, &mapfile, 0},
432 {"interpreter", 'i', True, &gspath, 0},
433 {"dosnames", 0, False, &dosnames, True},
434 {"quiet", 'q', False, &quiet, True},
435 #if defined(KPATHSEA) && defined (KPSE_DEBUG)
436 {"debug", OPT_DBG,True, NULL, 0},
437 #endif
438 {"version", 'v', False, NULL, 0},
439 {"help", 'h', False, NULL, 0}};
440
441 FILE *pk_file = NULL;
442 char *xfilename;
443 int col = 0; /* current column number */
444 const char *specinfo = "";
445 pid_t gs_pid = 0;
446
447 /*
448 * Config file options
449 */
450
451 #ifndef KPATHSEA /* 'H' option */
452 const char *config_file_header_path = HEADERPATH;
453 #else
454 const char *config_file_header_path = NULL;
455 #endif
456
457 struct p_list { /* list of 'p' options */
458 struct p_list *next;
459 const char *value;
460 };
461
462 /* Initialize this list to "psfonts.map". */
463
464 struct p_list psfonts_map = {NULL, "psfonts.map"};
465
466 struct p_list *p_head = &psfonts_map;
467 struct p_list **p_tail = &psfonts_map.next;
468
469 /*
470 * Reading from the pipe from ghostscript
471 */
472
473 Boolean data_eof = False;
474
475 #if !_AMIGA
476
477 #define BUFSIZE 512
478
479 typedef unsigned char byte;
480
481 int data_fd;
482 byte buffer[BUFSIZE];
483 byte *data_out = buffer;
484 byte *data_end = buffer;
485
486 #else /* _AMIGA */
487
488 FILE *data_file;
489
490 /* This string will be used to open pipes in and out */
491 char tmpname[] = "gsftopkXXXXXX";
492
493 #endif /* _AMIGA */
494
495 /*
496 * Information from the .tfm file.
497 */
498
499 int tfm_lengths[12];
500 #define lh tfm_lengths[1]
501 #define bc tfm_lengths[2]
502 #define ec tfm_lengths[3]
503 #define nw tfm_lengths[4]
504
505 long checksum;
506 long design;
507 byte width_index[256];
508 long tfm_widths[256];
509
510 /*
511 * Information on the bitmap currently being worked on.
512 */
513
514 byte *bitmap;
515 int width;
516 int skip;
517 int height;
518 int hoff;
519 int voff;
520 int bytes_wide;
521 unsigned int bm_size;
522 byte *bitmap_end;
523 int pk_len;
524
525
526 #if !_AMIGA
527
528 /*
529 * Exit, and kill the child process, too.
530 */
531
532 static void
533 exit_toto_too(void)
534 {
535 #if !WIN32
536 if (gs_pid != 0)
537 kill(gs_pid, SIGKILL);
538 #else
539 if (hGsThread) {
540 switch (WaitForSingleObject(hGsThread, 2000)) {
541 case WAIT_OBJECT_0:
542 CloseHandle(hGsThread);
543 hGsThread = NULL;
544 break;
545 case WAIT_TIMEOUT:
546 fprintf(stderr, "Timeout waiting for Gs thread.\n");
547 break;
548 case WAIT_FAILED:
549 fprintf(stderr, "WaitForSingleObject failed on Gs thread (Error code %d).\n",
550 (int)GetLastError());
551 break;
552 default:
553 break;
554 }
555
556 if (hGsThread) {
557 if (TerminateThread(hGsThread, 1) == 0) {
558 fprintf(stderr, "... couldn't terminate gs thread\n");
559 }
560 CloseHandle(hGsThread);
561 /* FIXME : is it right to call this ? */
562 gs_dll_release();
563 }
564 }
565
566 if (hGsDataIn)
567 CloseHandle(hGsDataIn);
568 if (hGsDataOut)
569 CloseHandle(hGsDataOut);
570
571 #endif
572 if (pk_file != NULL) {
573 fclose(pk_file);
574 if (unlink(xfilename) != 0) perror("unlink");
575 }
576
577 _exit(1);
578 }
579
580 #else /* _AMIGA */
581
582 #define exit_toto_too() exit(1)
583
584 #endif /* _AMIGA */
585
586 /*
587 * Print error message and quit.
588 */
589
590 static void
591 oops(const char *message, ...)
592 {
593 va_list args;
594
595 va_start(args, message);
596 if (col != 0) putchar('\n');
597 vfprintf(stderr, message, args);
598 va_end(args);
599 putc('\n', stderr);
600 exit_toto_too();
601 }
602
603
604 /*
605 * Same as oops, but with arguments.
606 */
607 static void
608 opt_oops(const char *message, ...)
609 {
610 va_list args;
611
612 va_start(args, message);
613 fputs("gsftopk: ", stderr);
614 vfprintf(stderr, message, args);
615 va_end(args);
616 fputs("\nTry `gsftopk --help' for more information.\n", stderr);
617 exit(1);
618 }
619
620
621 #ifndef KPATHSEA
622
623 /*
624 * Either allocate storage or fail.
625 */
626
627 static void *
628 xmalloc(unsigned size)
629 {
630 void *mem = (void *) malloc(size);
631
632 if (mem == NULL)
633 oops("gsftopk: Cannot allocate %u bytes.\n", size);
634 return mem;
635 }
636
637
638 /*
639 * Either reallocate storage or fail.
640 */
641
642 static void *
643 xrealloc(char *oldp, unsigned size)
644 {
645 void *mem;
646
647 mem = oldp == NULL ? (void *) malloc(size)
648 : (void *) realloc(oldp, size);
649 if (mem == NULL)
650 oops("gsftopk: Cannot reallocate %u bytes.\n", size);
651 return mem;
652 }
653
654 #endif /* not KPATHSEA */
655
656
657 /*
658 * Get a single white-space-delimited argument (or fail).
659 */
660
661 static char *
662 get_one_arg(const char *src)
663 {
664 char *dest;
665 const char *p;
666 unsigned int len;
667
668 len = strlen(src);
669 p = memchr(src, ' ', len);
670 if (p != NULL) len = p - src;
671 p = memchr(src, '\t', len);
672 if (p != NULL) len = p - src;
673
674 dest = xmalloc(len + 1);
675 memcpy(dest, src, len);
676 dest[len] = '\0';
677
678 return dest;
679 }
680
681 #if !_AMIGA
682
683 /*
684 * Signal handlers.
685 */
686
687 #if WIN32
688
689 static BOOL WINAPI
690 handle_sigterm(DWORD dwCtrlType)
691 {
692
693 /*
694 * Fix me: There is a problem if a system() command is running.
695 * We should wait for the child process to be interrupted.
696 * Only way I can think of to do that : rewrite system() based on
697 * spawn() with parsing of the command line and set a global pid
698 * Next cwait(pid) in the HandlerRoutine.
699 */
700
701 switch (dwCtrlType) {
702 case CTRL_C_EVENT:
703 case CTRL_BREAK_EVENT:
704 fprintf(stderr, "...exiting\n");
705 if (hGsThread) {
706 if (TerminateThread(hGsThread, 1) == 0) {
707 fprintf(stderr, "... couldn't terminate gs thread\n");
708 }
709 }
710 exit_toto_too();
711 return FALSE;
712 default:
713 fprintf(stderr, "... not exiting\n");
714 return TRUE;
715 }
716 }
717
718 #else /* not WIN32 */
719
720 static Boolean got_sigchld = False;
721
722 /* ARGSUSED */
723 static RETSIGTYPE
724 handle_sigchild(int signo)
725 {
726 got_sigchld = True;
727 }
728
729 /* ARGSUSED */
730 static RETSIGTYPE
731 handle_sigterm(int signo)
732 {
733 exit_toto_too();
734 }
735
736 #endif /* WIN32 */
737
738 #define gs_is_done (gs_pid == 0)
739
740 typedef int gsf_wait_t;
741
742 #if WIN32
743
744 /* This is the callback function for gs. It is mainly used to read and
745 write data on gs stdin/stdout. Data exchanges happen through
746 buffers. */
747 static int __cdecl
748 gsdll_callback(int message, char *str, unsigned long count)
749 {
750 int n;
751 static char **pin = &buffer_stdin; /* not yet allocated, so used a pointer on it. */
752
753 switch (message) {
754
755 case GSDLL_STDIN:
756 /* Put count chars on gs stdin */
757 #if DEBUG
758 fprintf(stderr, "gs wants %d chars\n", count);
759 #endif
760 strncpy(str, *pin, count);
761 *pin += count;
762 return strlen(str);
763
764 case GSDLL_STDOUT:
765 /* Fill the buffer in, wait for gsftopk to ask for data. */
766 WaitForSingleObject(hGsDataOut, INFINITE);
767 #if DEBUG
768 fprintf(stderr, "gs gives %d chars\n", count);
769 #endif
770 data_out = buffer;
771
772 if (str == (char *)NULL || count == 0) {
773 data_eof = True;
774 data_end = data_out;
775 /* Tell data_fillbuf() */
776 SetEvent(hGsDataIn);
777 return 0;
778 }
779 n = (count >= BUFSIZE ? BUFSIZE : count);
780 memcpy(data_out, str, n);
781 data_end = data_out + n;
782 /* Tell data_fillbuf() that data are available */
783 if (SetEvent(hGsDataIn) == FALSE)
784 Win32Error("gsdll_callback/SetEvent");
785 /* return the number of chars read */
786 return n;
787
788 case GSDLL_DEVICE:
789 #if DEBUG
790 fprintf(stdout,"Callback: DEVICE %p %s\n", str,
791 count ? "open" : "close");
792 #endif
793 break;
794
795 case GSDLL_SYNC:
796 #if DEBUG
797 fprintf(stdout,"Callback: SYNC %p\n", str);
798 #endif
799 break;
800
801 case GSDLL_PAGE:
802 fprintf(stdout,"Callback: PAGE %p\n", str);
803 break;
804
805 case GSDLL_SIZE:
806 #if DEBUG
807 fprintf(stdout,"Callback: SIZE %p width=%d height=%d\n", str,
808 (int)(count & 0xffff), (int)((count>>16) & 0xffff) );
809 #endif
810 break;
811
812 case GSDLL_POLL:
813 return 0; /* no error ? */
814 default:
815 fprintf(stdout,"%s: gs callback: unknown message=%d\n",progname, message);
816 break;
817 }
818 return 0;
819 }
820
821 /*
822 This is the thread function that will load the gs dll and
823 send it the data.
824 */
825 static DWORD WINAPI Win32GsSendData(LPVOID lpParam)
826 {
827 int ret;
828
829 if (gs_locate() == NULL) {
830 fprintf(stderr, "Can't locate Ghostscript ! Exiting ...\n");
831 return EXIT_FAILURE;
832 }
833
834 gs_dll_initialize();
835
836 ret = (*pgsdll_init)(gsdll_callback,
837 NULL,
838 gs_argc,
839 gs_argv);
840
841 if (ret == 0) {
842 /* Should not happen : gs should quit
843 right after being initialized. */
844 (*pgsdll_exit)();
845 /* FIXME: this is working, but we could expect something cleaner ! */
846 /* GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, 0); */
847 return EXIT_FAILURE;
848 }
849
850 if (ret == GSDLL_INIT_QUIT) {
851 gs_dll_release();
852 return 0;
853 }
854
855 if (ret == GSDLL_INIT_IN_USE) {
856 fprintf(stderr, "gsdll_init returned %d\n", ret);
857 gs_dll_release();
858 return EXIT_FAILURE;
859 }
860
861 (*pgsdll_exit)();
862
863 #if DEBUG
864 fprintf(stderr, "%s: gsdll_init returned %d\n", progname, ret);
865 #endif
866
867 WaitForSingleObject(hGsDataOut, INFINITE);
868 data_eof = True;
869 data_end = data_out;
870 /* Tell data_fillbuf() */
871 SetEvent(hGsDataIn);
872
873 gs_dll_release();
874
875 return 0;
876 }
877
878 #else /* not WIN32 */
879
880 static void
881 wait_for_gs(void)
882 {
883 gsf_wait_t status;
884
885 #if _AMIGA
886
887 /* Do nothing */
888
889 #else /* not _AMIGA */
890
891 got_sigchld = False;
892
893 for (;;) {
894 if (wait(&status) != -1) break;
895 /* if (errno == EINTR) continue; */
896 if (errno != EINTR) {
897 perror("wait");
898 exit_toto_too();
899 }
900 }
901
902 if (WIFSTOPPED(status))
903 return;
904
905 gs_pid = 0;
906
907 if (WIFSIGNALED(status))
908 oops("gs died due to signal %d\n", WTERMSIG(status));
909
910 /* otherwise, it exited */
911 if (WEXITSTATUS(status) != 0)
912 oops("gs terminated abnormally with status %d\n",
913 WEXITSTATUS(status));
914
915 #endif /* not _AMIGA */
916
917 }
918
919 #endif /* not WIN32 */
920
921 #endif /* not _AMIGA */
922
923 /*
924 * Routines to read from the data file.
925 */
926
927 #if _AMIGA
928
929 #define data_getc() getc(data_file)
930 #define data_ungetc(c) ungetc(c, data_file)
931 #define data_read(p, l) fread(p, 1, l, data_file)
932
933 #else /* not _AMIGA */
934
935 #if WIN32
936
937 static void
938 data_fillbuf(void)
939 {
940 if (data_eof)
941 return;
942
943 /* wait until data are available. First tell gs it can fill the buffer in. */
944 SetEvent(hGsDataOut);
945 /* wait for the data. */
946 switch (WaitForSingleObject(hGsDataIn, INFINITE)) {
947 case WAIT_OBJECT_0:
948 /* normal case */
949 break;
950 case WAIT_TIMEOUT:
951 /* should not happen */
952 fprintf(stderr, "Gs did not return on time from callback.\n");
953 break;
954 case WAIT_FAILED:
955 break;
956 default:
957 fprintf(stderr, "WaitForSingleObject failed for unknown reason.\n");
958 }
959 }
960
961 #else /* not WIN32 */
962
963 #if HAVE_POLL
964 #define ISSET(a, b) ((poll_fd.revents & POLLIN) != 0)
965 #else
966 #define ISSET(a, b) FD_ISSET(a, b)
967 #endif
968
969 static void
970 data_fillbuf(void)
971 {
972 int n;
973
974 #if HAVE_POLL
975 static struct pollfd poll_fd = {0, POLLIN, 0};
976 #else
977 fd_set read_fds;
978 struct timeval timeout;
979 #endif
980
981 if (data_eof)
982 return;
983
984 /* wait for readable data */
985 if (!gs_is_done) {
986 for (;;) {
987 if (!got_sigchld) {
988 #if HAVE_POLL
989 poll_fd.fd = data_fd;
990 poll_fd.revents = 0;
991 if (poll(&poll_fd, 1, 5000) == -1) {
992 if (errno != EINTR) {
993 perror("poll");
994 sleep(4);
995 }
996 continue;
997 }
998 #else
999 FD_ZERO(&read_fds);
1000 FD_SET(data_fd, &read_fds);
1001 timeout.tv_sec = 5;
1002 timeout.tv_usec = 0;
1003 if (select(data_fd + 1, &read_fds, (fd_set *) NULL,
1004 (fd_set *) NULL, &timeout) == -1) {
1005 if (errno != EINTR) {
1006 perror("select");
1007 sleep(4);
1008 }
1009 continue;
1010 }
1011 #endif
1012 }
1013 if (got_sigchld) {
1014 wait_for_gs();
1015 break;
1016 }
1017 if (ISSET(data_fd, &read_fds))
1018 break;
1019 }
1020 }
1021
1022 /* read the data */
1023 for (;;) {
1024 n = read(data_fd, (void *) (data_out = buffer), BUFSIZE);
1025 if (n >= 0)
1026 break;
1027 if (errno == EINTR)
1028 continue;
1029 if (gs_is_done && errno == EAGAIN) {
1030 n = 0;
1031 break;
1032 }
1033 perror("read from gs");
1034 sleep(4);
1035 }
1036
1037 data_end = data_out + n;
1038 if (n == 0)
1039 data_eof = True;
1040 }
1041
1042 #endif /* not WIN32 */
1043
1044 static byte
1045 data_fgetc(void)
1046 {
1047 if (data_out >= data_end)
1048 data_fillbuf();
1049
1050 return data_eof ? EOF : *data_out++;
1051 }
1052
1053 #define data_getc() (data_out < data_end ? *data_out++ : data_fgetc())
1054
1055 static void
1056 data_ungetc(byte c)
1057 {
1058 if (data_out <= buffer)
1059 oops("Too many calls to data_ungetc()");
1060
1061 *--data_out = c;
1062 }
1063
1064 static int
1065 data_read(byte *buf, int n)
1066 {
1067 byte *buf1 = buf;
1068 byte *buf_end = buf + n;
1069 int n1;
1070
1071 if (buf1 >= buf_end)
1072 return 0;
1073
1074 while (!data_eof) {
1075 n1 = buf_end - buf1;
1076 if (n1 > data_end - data_out)
1077 n1 = data_end - data_out;
1078 memcpy(buf1, data_out, n1);
1079 buf1 += n1;
1080 data_out += n1;
1081 if (buf1 >= buf_end) break;
1082 data_fillbuf();
1083 }
1084
1085 return buf1 - buf;
1086 }
1087
1088 static void
1089 data_gets(byte *buf, int n)
1090 {
1091 byte *buf1 = buf;
1092 byte *buf_end = buf + n - 1;
1093 int n1;
1094 byte *p1;
1095
1096 if (n <= 0)
1097 return;
1098
1099 for (;;) {
1100 if (data_eof)
1101 oops("Premature end of file");
1102 n1 = buf_end - buf1;
1103 if (n1 > data_end - data_out)
1104 n1 = data_end - data_out;
1105 p1 = (byte *) memchr((char *) data_out, '\n', n1);
1106 if (p1 != NULL)
1107 n1 = p1 + 1 - data_out;
1108 memcpy((char *) buf1, (char *) data_out, n1);
1109 buf1 += n1;
1110 data_out += n1;
1111 if (p1 != NULL || buf1 >= buf_end) break;
1112 data_fillbuf();
1113 }
1114
1115 *buf1 = '\0';
1116
1117 return;
1118 }
1119
1120 #endif /* not _AMIGA */
1121
1122 /*
1123 * Here's the patch searching stuff. First the typedefs and variables.
1124 */
1125
1126 #ifndef KPATHSEA
1127 static char searchpath[MAXPATHLEN + 1];
1128 #else
1129 static char *searchpath;
1130 #endif
1131
1132 #define HUNKSIZE (MAXPATHLEN + 2)
1133
1134 struct spacenode { /* used for storage of directory names */
1135 struct spacenode *next;
1136 char *sp_end; /* end of data for this chunk */
1137 char sp[HUNKSIZE];
1138 }
1139 firstnode;
1140
1141 #ifndef KPATHSEA
1142
1143 static jmp_buf found_env;
1144 static FILE *searchfile;
1145 static const char *searchname;
1146 static int searchnamelen;
1147
1148 static const char *
1149 find_dbl_slash(const char *sp_bgn, const char *sp_end)
1150 {
1151 const char *p;
1152
1153 for (;;) {
1154 p = memchr(sp_bgn, '/', sp_end - sp_bgn);
1155 if (p == NULL) return sp_end;
1156 if (p[1] == '/') return p;
1157 sp_bgn = p + 1;
1158 }
1159 }
1160
1161 static void
1162 main_search_proc(char *matpos, const char *sp_pos,
1163 const char *sp_slash, const char *sp_end,
1164 wide_bool skip_subdirs, struct spacenode *space, char *spacenext)
1165 {
1166 char *mp;
1167 struct stat statbuf;
1168 DIR *dir;
1169 struct dirent *entry;
1170 int lenleft;
1171 int len;
1172 struct spacenode *space1;
1173 char *spacenext1;
1174
1175 mp = matpos + (sp_slash - sp_pos);
1176 /* check length */
1177 if (mp + searchnamelen >= searchpath + sizeof(searchpath) - 2) return;
1178 memcpy(matpos, sp_pos, sp_slash - sp_pos);
1179 if (sp_slash == sp_end) { /* try for a file */
1180 *mp = '/';
1181 strcpy(mp + (mp == searchpath || mp[-1] != '/'), searchname);
1182 searchfile = fopen(searchpath, "r");
1183 if (searchfile != NULL) longjmp(found_env, True);
1184 }
1185 else {/* try for a subdirectory */
1186 *mp = '\0';
1187 if (stat(searchpath, &statbuf) == 0 && S_ISDIR(statbuf.st_mode)) {
1188 *mp++ = '/';
1189 main_search_proc(mp, sp_slash + 2,
1190 find_dbl_slash(sp_slash + 2, sp_end), sp_end,
1191 statbuf.st_nlink <= 2, space, spacenext);
1192 }
1193 }
1194 if (skip_subdirs) return;
1195 *matpos = '\0';
1196 dir = opendir(searchpath);
1197 if (dir == NULL) return;
1198 lenleft = searchpath + sizeof(searchpath) - matpos;
1199 space1 = space;
1200 spacenext1 = spacenext;
1201 for (;;) {
1202 entry = readdir(dir);
1203 if (entry == NULL) break;
1204 len = NAMLEN(entry) + 1;
1205 if (len > lenleft) continue; /* too long */
1206 strcpy(matpos, entry->d_name);
1207 if (*matpos == '.' && (matpos[1] == '\0' || (matpos[1] == '.'
1208 && matpos[2] == '\0')))
1209 continue; /* ignore . and .. */
1210 if (stat(searchpath, &statbuf) != 0 || !S_ISDIR(statbuf.st_mode))
1211 continue; /* if not a directory */
1212 if (statbuf.st_nlink > 2) ++len;
1213 if (spacenext1 + len > space1->sp + HUNKSIZE) {
1214 space1->sp_end = spacenext1;
1215 if (space1->next == NULL) {
1216 space1->next = xmalloc(sizeof(struct spacenode));
1217 space1->next->next = NULL;
1218 }
1219 space1 = space1->next;
1220 spacenext1 = space1->sp;
1221 }
1222 if (statbuf.st_nlink > 2) {
1223 *spacenext1++ = '/';
1224 --len;
1225 }
1226 memcpy(spacenext1, entry->d_name, len - 1);
1227 spacenext1[len - 1] = '\0';
1228 spacenext1 += len;
1229 }
1230 closedir(dir);
1231 for (;;) {
1232 space1->sp_end = spacenext1;
1233 if (spacenext == space->sp_end) {
1234 if (space == space1) break;
1235 space = space->next;
1236 spacenext = space->sp;
1237 }
1238 skip_subdirs = True;
1239 if (*spacenext == '/') {
1240 ++spacenext;
1241 skip_subdirs = False;
1242 }
1243 len = strlen(spacenext);
1244 memcpy(matpos, spacenext, len);
1245 matpos[len] = '/';
1246 main_search_proc(matpos + len + 1, sp_pos, sp_slash, sp_end,
1247 skip_subdirs, space1, spacenext1);
1248 spacenext += len + 1;
1249 }
1250 }
1251
1252 static FILE *
1253 search(const char *path, const char *path_var, const char *name)
1254 {
1255 const char *env_path = NULL;
1256 FILE *f;
1257
1258 if (path_var != NULL) {
1259 if (*name == '/') {
1260 strcpy(searchpath, name);
1261 return fopen(searchpath, "r");
1262 }
1263 env_path = getenv(path_var);
1264 }
1265 if (env_path == NULL) {
1266 env_path = path;
1267 path = NULL;
1268 }
1269 searchname = name;
1270 searchnamelen = strlen(name);
1271 for (;;) {
1272 const char *p;
1273
1274 p = strchr(env_path, ':');
1275 if (p == NULL) p = env_path + strlen(env_path);
1276 if (p == env_path) {
1277 if (path != NULL) {
1278 f = search(path, (char *) NULL, name);
1279 if (f != NULL) return f;
1280 }
1281 }
1282 else {
1283 if (setjmp(found_env))
1284 return searchfile;
1285 main_search_proc(searchpath,
1286 env_path, find_dbl_slash(env_path, p), p,
1287 True, &firstnode, firstnode.sp);
1288 }
1289 if (*p == '\0') return NULL;
1290 env_path = p + 1;
1291 }
1292 }
1293
1294 #endif /* not KPATHSEA */
1295
1296 /*
1297 * Reading configuration and map files.
1298 */
1299
1300 char *long_line = NULL; /* for reading config and map files */
1301 int long_line_len = 82; /* allocated length of the above */
1302
1303 static Boolean
1304 fgets_long(FILE *f)
1305 {
1306 int len;
1307
1308 if (fgets(long_line, long_line_len, f) == NULL)
1309 return False;
1310
1311 len = 0;
1312 for (;;) {
1313 len += strlen(long_line + len);
1314 if (len > 0 && long_line[len - 1] == '\n') {
1315 long_line[--len] = '\0';
1316 break;
1317 }
1318 if (len < long_line_len - 1)
1319 break;
1320 long_line_len += 80;
1321 long_line = xrealloc(long_line, long_line_len);
1322 fgets(long_line + len, long_line_len - len, f);
1323 }
1324
1325 return True;
1326 }
1327
1328
1329 static void
1330 #ifndef KPATHSEA
1331 getdefaults(FILE *f)
1332 #else
1333 getdefaults(const char *name)
1334 #endif
1335 {
1336 #ifdef KPATHSEA
1337 FILE *f;
1338 #endif
1339 char *p;
1340 char c;
1341 struct p_list *p_node;
1342
1343 #ifdef KPATHSEA
1344 p = kpse_find_file(name, kpse_dvips_config_format, false);
1345 if (p == NULL)
1346 return;
1347
1348 f = fopen(p, FOPEN_R_MODE);
1349 if (f == NULL)
1350 return;
1351 #endif
1352
1353 while (fgets_long(f)) {
1354 p = long_line;
1355 while (*p == ' ' || *p == '\t') ++p;
1356 c = *p;
1357 if (c == '\0')
1358 continue;
1359 do ++p;
1360 while (*p == ' ' || *p == '\t');
1361 switch (c) {
1362 case 'H':
1363 config_file_header_path = get_one_arg(p);
1364 break;
1365
1366 case 'p':
1367 if (*p == '+')
1368 do ++p;
1369 while (*p == ' ' || *p == '\t');
1370 else
1371 p_tail = &p_head; /* discard old list */
1372
1373 p_node = xmalloc(sizeof *p_node);
1374 p_node->value = get_one_arg(p);
1375 *p_tail = p_node;
1376 p_tail = &p_node->next;
1377 break;
1378 }
1379 }
1380
1381 fclose(f);
1382 }
1383
1384
1385 static Boolean
1386 scan_map_file(FILE *f)
1387 {
1388 while (fgets_long(f))
1389 if (memcmp(long_line, fontname, fontlen) == 0
1390 && (long_line[fontlen] == '\0' || isspace((unsigned char)long_line[fontlen]))) {
1391 fclose(f);
1392 return True;
1393 }
1394
1395 fclose(f);
1396 return False;
1397 }
1398
1399
1400 /*
1401 * Add to dlstring
1402 */
1403
1404 char *dlstring = NULL;
1405 unsigned int dls_len = 0;
1406 unsigned int dls_max = 0;
1407
1408 static void
1409 addtodls(const char *s)
1410 {
1411 int len = strlen(s);
1412
1413 if (dls_len + len >= dls_max) {
1414 unsigned int newsize = dls_max + 80;
1415
1416 if (newsize <= dls_len + len) newsize = dls_len + len + 1;
1417 dlstring = xrealloc(dlstring, dls_max = newsize);
1418 }
1419 strcpy(dlstring + dls_len, s);
1420 dls_len += len;
1421 }
1422
1423
1424
1425 static long
1426 getlong(FILE *f)
1427 {
1428 int value;
1429
1430 value = (int) ((byte) getc(f)) << 24;
1431 value |= (int) ((byte) getc(f)) << 16;
1432 value |= (int) ((byte) getc(f)) << 8;
1433 value |= (int) ((byte) getc(f));
1434 return value;
1435 }
1436
1437
1438 char line[82];
1439
1440 static void
1441 expect(const char *waitingfor)
1442 {
1443 for (;;) {
1444 #if !_AMIGA
1445 data_gets((byte *) line, sizeof(line));
1446 #else
1447 if (fgets(line, sizeof(line), data_file) == NULL)
1448 oops("Premature end of file");
1449 #endif
1450 if (memcmp(line, waitingfor, strlen(waitingfor)) == 0) return;
1451 fputs("gs: ", stdout);
1452 for (;;) {
1453 fputs(line, stdout);
1454 if (*line == '\0' || line[strlen(line) - 1] == '\n') break;
1455 #if !_AMIGA
1456 data_gets((byte *) line, sizeof(line));
1457 #else
1458 if (fgets(line, sizeof(line), data_file) == NULL)
1459 oops("Premature end of file");
1460 #endif
1461 }
1462 }
1463 }
1464
1465 static void
1466 whitespace(void)
1467 {
1468 char c;
1469
1470 for (;;) {
1471 c = data_getc();
1472 if (c == '#')
1473 do c = data_getc(); while (!data_eof && c != '\n');
1474 else if (!isspace((unsigned char)c)) {
1475 data_ungetc(c);
1476 break;
1477 }
1478 }
1479 }
1480
1481 static int
1482 getint(void)
1483 {
1484 char c;
1485 int i = 0;
1486
1487 do c = data_getc(); while (isspace((unsigned char)c));
1488 if (c < '0' || c > '9') oops("digit expected");
1489 do {
1490 i = i * 10 + (c - '0');
1491 c = data_getc();
1492 } while (c >= '0' && c <= '9');
1493 if (!data_eof) data_ungetc(c);
1494 return i;
1495 }
1496
1497 static byte masks[] = {0, 1, 3, 7, 017, 037, 077, 0177, 0377};
1498
1499 byte flag;
1500 int pk_dyn_f;
1501 int pk_dyn_g;
1502 int base; /* cost of this character if pk_dyn_f = 0 */
1503 int deltas[13]; /* cost of increasing pk_dyn_f from i to i+1 */
1504
1505 /*
1506 * Add up statistics for putting out the given shift count
1507 */
1508
1509 static void
1510 tallyup(int n)
1511 {
1512 int m;
1513
1514 if (n > 208) {
1515 ++base;
1516 n -= 192;
1517 for (m = 0x100; m != 0 && m < n; m <<= 4) base += 2;
1518 if (m != 0 && (m = (m - n) / 15) < 13) deltas[m] += 2;
1519 }
1520 else if (n > 13) ++deltas[(208 - n) / 15];
1521 else --deltas[n - 1];
1522 }
1523
1524 /*
1525 * Routines for storing the shift counts
1526 */
1527
1528 static Boolean odd = False;
1529 static byte part;
1530
1531 static void
1532 pk_put_nyb(int n)
1533 {
1534 if (odd) {
1535 *bitmap_end++ = (part << 4) | n;
1536 odd = False;
1537 }
1538 else {
1539 part = n;
1540 odd = True;
1541 }
1542 }
1543
1544 static void
1545 pk_put_long(int n)
1546 {
1547 if (n >= 16) {
1548 pk_put_nyb(0);
1549 pk_put_long(n / 16);
1550 }
1551 pk_put_nyb(n % 16);
1552 }
1553
1554 static void
1555 pk_put_count(int n)
1556 {
1557 if (n > pk_dyn_f) {
1558 if (n > pk_dyn_g)
1559 pk_put_long(n - pk_dyn_g + 15);
1560 else {
1561 pk_put_nyb(pk_dyn_f + (n - pk_dyn_f + 15) / 16);
1562 pk_put_nyb((n - pk_dyn_f - 1) % 16);
1563 }
1564 }
1565 else pk_put_nyb(n);
1566 }
1567
1568 static void
1569 trim_bitmap(void)
1570 {
1571 byte *p;
1572 byte mask;
1573
1574 /* clear out garbage bits in bitmap */
1575 if (width % 8 != 0) {
1576 mask = ~masks[8 - width % 8];
1577 for (p = bitmap + bytes_wide - 1; p < bitmap_end; p += bytes_wide)
1578 *p &= mask;
1579 }
1580
1581 /*
1582 * Find the bounding box of the bitmap.
1583 */
1584
1585 /* trim top */
1586 skip = 0;
1587 mask = 0;
1588 for (;;) {
1589 if (bitmap >= bitmap_end) { /* if bitmap is empty */
1590 width = height = hoff = voff = 0;
1591 return;
1592 }
1593 p = bitmap + bytes_wide;
1594 while (p > bitmap) mask |= *--p;
1595 if (mask) break;
1596 ++skip;
1597 bitmap += bytes_wide;
1598 }
1599 height -= skip;
1600 voff -= skip;
1601 #if DEBUG
1602 #if defined(KPATHSEA) && defined (KPSE_DEBUG)
1603 if (KPSE_DEBUG_P (GSPK_DEBUG_PK))
1604 #endif
1605 if (skip < 2 || skip > 3)
1606 printf("Character has %d empty rows at top\n", skip);
1607 #endif /* DEBUG */
1608
1609 /* trim bottom */
1610 skip = 0;
1611 mask = 0;
1612 for (;;) {
1613 p = bitmap_end - bytes_wide;
1614 while (p < bitmap_end) mask |= *p++;
1615 if (mask) break;
1616 ++skip;
1617 bitmap_end -= bytes_wide;
1618 }
1619 height -= skip;
1620 #if DEBUG
1621 #if defined(KPATHSEA) && defined (KPSE_DEBUG)
1622 if (KPSE_DEBUG_P (GSPK_DEBUG_PK))
1623 #endif
1624 if (skip < 2 || skip > 3)
1625 printf("Character has %d empty rows at bottom\n", skip);
1626 #endif /* DEBUG */
1627
1628 /* trim right */
1629 skip = 0;
1630 --width;
1631 for (;;) {
1632 mask = 0;
1633 for (p = bitmap + width / 8; p < bitmap_end; p += bytes_wide)
1634 mask |= *p;
1635 if (mask & (0x80 >> (width % 8))) break;
1636 --width;
1637 ++skip;
1638 }
1639 ++width;
1640 #if DEBUG
1641 #if defined(KPATHSEA) && defined (KPSE_DEBUG)
1642 if (KPSE_DEBUG_P (GSPK_DEBUG_PK))
1643 #endif
1644 if (skip < 2 || skip > 3)
1645 printf("Character has %d empty columns at right\n", skip);
1646 #endif /* DEBUG */
1647
1648 /* trim left */
1649 skip = 0;
1650 for (;;) {
1651 mask = 0;
1652 for (p = bitmap + skip / 8; p < bitmap_end; p += bytes_wide)
1653 mask |= *p;
1654 if (mask & (0x80 >> (skip % 8))) break;
1655 ++skip;
1656 }
1657 width -= skip;
1658 hoff -= skip;
1659 #if DEBUG
1660 #if defined(KPATHSEA) && defined (KPSE_DEBUG)
1661 if (KPSE_DEBUG_P (GSPK_DEBUG_PK))
1662 #endif
1663 if (skip < 2 || skip > 3)
1664 printf("Character has %d empty columns at left\n", skip);
1665 #endif /* DEBUG */
1666 bitmap += skip / 8;
1667 skip = skip % 8;
1668 }
1669
1670 /*
1671 * Pack the bitmap using the rll method. (Return false if it's better
1672 * to just pack the bits.)
1673 */
1674
1675 static Boolean
1676 pk_rll_cvt(void)
1677 {
1678 static int *counts = NULL; /* area for saving bit counts */
1679 static int maxcounts = 0; /* size of this area */
1680 unsigned int ncounts; /* max to allow this time */
1681 int *nextcount; /* next count value */
1682 int *counts_end; /* pointer to end */
1683 byte *rowptr;
1684 byte *p;
1685 byte mask;
1686 byte *rowdup; /* last row checked for dup */
1687 byte paint_switch; /* 0 or 0xff */
1688 int bits_left; /* bits left in row */
1689 int cost;
1690 int i;
1691
1692 /*
1693 * Allocate space for bit counts.
1694 */
1695
1696 ncounts = (width * height + 3) / 4;
1697 if (ncounts > maxcounts) {
1698 if (counts != NULL) free(counts);
1699 counts = xmalloc((ncounts + 2) * sizeof(int));
1700 maxcounts = ncounts;
1701 }
1702 counts_end = counts + ncounts;
1703
1704 /*
1705 * Form bit counts and collect statistics
1706 */
1707 base = 0;
1708 memset(deltas, 0, sizeof(deltas));
1709 rowdup = NULL; /* last row checked for duplicates */
1710 p = rowptr = bitmap;
1711 mask = 0x80 >> skip;
1712 flag = 0;
1713 paint_switch = 0;
1714 if (*p & mask) {
1715 flag = 8;
1716 paint_switch = 0xff;
1717 }
1718 bits_left = width;
1719 nextcount = counts;
1720 while (rowptr < bitmap_end) { /* loop over shift counts */
1721 int shift_count = bits_left;
1722
1723 for (;;) {
1724 if (bits_left == 0) {
1725 if ((p = rowptr += bytes_wide) >= bitmap_end) break;
1726 mask = 0x80 >> skip;
1727 bits_left = width;
1728 shift_count += width;
1729 }
1730 if (((*p ^ paint_switch) & mask) != 0) break;
1731 --bits_left;
1732 mask >>= 1;
1733 if (mask == 0) {
1734 ++p;
1735 while (*p == paint_switch && bits_left >= 8) {
1736 ++p;
1737 bits_left -= 8;
1738 }
1739 mask = 0x80;
1740 }
1741 }
1742 if (nextcount >= counts_end) return False;
1743 shift_count -= bits_left;
1744 *nextcount++ = shift_count;
1745 tallyup(shift_count);
1746 /* check for duplicate rows */
1747 if (rowptr != rowdup && bits_left != width) {
1748 byte *p1 = rowptr;
1749 byte *q = rowptr + bytes_wide;
1750 int repeat_count;
1751
1752 while (q < bitmap_end && *p1 == *q) ++p1, ++q;
1753 repeat_count = (p1 - rowptr) / bytes_wide;
1754 if (repeat_count > 0) {
1755 *nextcount++ = -repeat_count;
1756 if (repeat_count == 1) --base;
1757 else {
1758 ++base;
1759 tallyup(repeat_count);
1760 }
1761 rowptr += repeat_count * bytes_wide;
1762 }
1763 rowdup = rowptr;
1764 }
1765 paint_switch = ~paint_switch;
1766 }
1767
1768 #if DEBUG
1769 #if defined(KPATHSEA) && defined (KPSE_DEBUG)
1770 if (KPSE_DEBUG_P (GSPK_DEBUG_BITMAP))
1771 #endif
1772 {
1773 /*
1774 * Dump the bitmap
1775 */
1776
1777 for (p = bitmap; p < bitmap_end; p += bytes_wide) {
1778 byte *p1 = p;
1779 int j;
1780
1781 mask = 0x80 >> skip;
1782 for (j = 0; j < width; ++j) {
1783 putchar(*p1 & mask ? '@' : '.');
1784 if ((mask >>= 1) == 0) mask = 0x80, ++p1;
1785 }
1786 putchar('\n');
1787 }
1788 putchar('\n');
1789 }
1790 #endif /* DEBUG */
1791
1792 /*
1793 * Determine the best pk_dyn_f
1794 */
1795
1796 pk_dyn_f = 0;
1797 cost = base += 2 * (nextcount - counts);
1798 for (i = 1; i < 14; ++i) {
1799 base += deltas[i - 1];
1800 if (base < cost) {
1801 pk_dyn_f = i;
1802 cost = base;
1803 }
1804 }
1805 /* last chance to bail out */
1806 if (cost * 4 > width * height) return False;
1807
1808 /*
1809 * Pack the bit counts
1810 */
1811
1812 pk_dyn_g = 208 - 15 * pk_dyn_f;
1813 flag |= pk_dyn_f << 4;
1814 bitmap_end = bitmap;
1815 *nextcount = 0;
1816 nextcount = counts;
1817 while (*nextcount != 0) {
1818 if (*nextcount > 0) pk_put_count(*nextcount);
1819 else
1820 if (*nextcount == -1) pk_put_nyb(15);
1821 else {
1822 pk_put_nyb(14);
1823 pk_put_count(-*nextcount);
1824 }
1825 ++nextcount;
1826 }
1827 if (odd) {
1828 pk_put_nyb(0);
1829 ++cost;
1830 }
1831 if (cost != 2 * (bitmap_end - bitmap))
1832 printf("Cost miscalculation: expected %d, got %ld\n", cost,
1833 2 * (long) (bitmap_end - bitmap));
1834 pk_len = bitmap_end - bitmap;
1835 return True;
1836 }
1837
1838 static void
1839 pk_bm_cvt(void)
1840 {
1841 byte *rowptr;
1842 byte *p;
1843 int blib1; /* bits left in byte */
1844 int bits_left; /* bits left in row */
1845 byte *q;
1846 int blib2;
1847 byte nextbyte;
1848
1849 flag = 14 << 4;
1850 q = bitmap;
1851 blib2 = 8;
1852 nextbyte = 0;
1853 for (rowptr = bitmap; rowptr < bitmap_end; rowptr += bytes_wide) {
1854 p = rowptr;
1855 blib1 = 8 - skip;
1856 bits_left = width;
1857 if (blib2 != 8) {
1858 int n;
1859
1860 if (blib1 < blib2) {
1861 nextbyte |= *p << (blib2 - blib1);
1862 n = blib1;
1863 }
1864 else {
1865 nextbyte |= *p >> (blib1 - blib2);
1866 n = blib2;
1867 }
1868 blib2 -= n;
1869 if ((bits_left -= n) < 0) {
1870 blib2 -= bits_left;
1871 continue;
1872 }
1873 if ((blib1 -= n) == 0) {
1874 blib1 = 8;
1875 ++p;
1876 if (blib2 > 0) {
1877 nextbyte |= *p >> (8 - blib2);
1878 blib1 -= blib2;
1879 bits_left -= blib2;
1880 if (bits_left < 0) {
1881 blib2 = -bits_left;
1882 continue;
1883 }
1884 }
1885 }
1886 *q++ = nextbyte;
1887 }
1888 /* fill up whole (destination) bytes */
1889 while (bits_left >= 8) {
1890 nextbyte = *p++ << (8 - blib1);
1891 *q++ = nextbyte | (*p >> blib1);
1892 bits_left -= 8;
1893 }
1894 /* now do the remainder */
1895 nextbyte = *p << (8 - blib1);
1896 if (bits_left > blib1) nextbyte |= p[1] >> blib1;
1897 blib2 = 8 - bits_left;
1898 }
1899 if (blib2 != 8) *q++ = nextbyte;
1900 pk_len = q - bitmap;
1901 }
1902
1903 static void
1904 putshort(int w)
1905 {
1906 putc(w >> 8, pk_file);
1907 putc(w, pk_file);
1908 }
1909
1910 static void
1911 putmed(long w)
1912 {
1913 putc(w >> 16, pk_file);
1914 putc(w >> 8, pk_file);
1915 putc(w, pk_file);
1916 }
1917
1918 static void
1919 putlong(long w)
1920 {
1921 putc(w >> 24, pk_file);
1922 putc(w >> 16, pk_file);
1923 putc(w >> 8, pk_file);
1924 putc(w, pk_file);
1925 }
1926
1927 static void
1928 putglyph(int cc)
1929 {
1930 static Boolean have_first_line = False;
1931 static int llx, lly, urx, ury;
1932 static float char_width;
1933 static byte *area1 = NULL;
1934 static unsigned int size1 = 0;
1935 static int i;
1936 long dm;
1937 long tfm_wid;
1938 byte *p;
1939
1940 if (!quiet) {
1941 int wid;
1942 static const char *s = "";
1943
1944 wid = (cc >= 100) + (cc >= 10) + 4;
1945 if (col + wid > 80) {
1946 s = "\n";
1947 col = 0;
1948 }
1949 printf("%s[%d", s, cc);
1950 fflush(stdout);
1951 col += wid;
1952 s = " ";
1953 }
1954 if (!have_first_line) {
1955 expect("#^");
1956 if (sscanf(line, "#^ %d %d %d %d %d %f\n", &i,
1957 &llx, &lly, &urx, &ury, &char_width) != 6)
1958 oops("Cannot scanf first line");
1959 }
1960 if (i < cc) oops("Character %d received, %d expected", i, cc);
1961 if (i > cc) {
1962 fprintf(stderr, "Character %d is missing.\n", cc);
1963 have_first_line = True;
1964 return;
1965 }
1966 have_first_line = False;
1967 hoff = -llx + 2;
1968 voff = ury + 2 - 1;
1969 expect("P4\n");
1970 whitespace();
1971 width = getint();
1972 whitespace();
1973 height = getint();
1974 (void) data_getc();
1975 if (width != urx - llx + 4 || height != ury - lly + 4)
1976 oops("Dimensions do not match: %d %d %d %d %d %d",
1977 llx, lly, urx, ury, width, height);
1978 bytes_wide = (width + 7) / 8;
1979 bm_size = bytes_wide * height;
1980 if (size1 < bm_size) {
1981 if (area1 != NULL) free(area1);
1982 area1 = xmalloc(bm_size);
1983 size1 = bm_size;
1984 }
1985 for (p = area1 + (height - 1) * bytes_wide; p >= area1; p -= bytes_wide)
1986 if (data_read(p, bytes_wide) != bytes_wide)
1987 oops("Cannot read bitmap of size %u", bm_size);
1988 bitmap = area1;
1989 bitmap_end = bitmap + bm_size;
1990 trim_bitmap();
1991 if (height == 0 || !pk_rll_cvt()) pk_bm_cvt();
1992 tfm_wid = tfm_widths[width_index[cc]];
1993 dm = (long) (char_width + 0.5) - (char_width < -0.5);
1994 if (pk_len + 8 < 4 * 256 && tfm_wid < (1<<24) &&
1995 dm >= 0 && dm < 256 && width < 256 && height < 256 &&
1996 hoff >= -128 && hoff < 128 && voff >= -128 && voff < 128) {
1997 putc(flag | ((pk_len + 8) >> 8), pk_file);
1998 putc(pk_len + 8, pk_file);
1999 putc(cc, pk_file);
2000 putmed(tfm_wid);
2001 putc(dm, pk_file);
2002 putc(width, pk_file);
2003 putc(height, pk_file);
2004 putc(hoff, pk_file);
2005 putc(voff, pk_file);
2006 } else
2007 if (pk_len + 13 < 3 * 65536L && tfm_wid < (1<<24) &&
2008 dm >= 0 && dm < 65536L && width < 65536L && height < 65536L &&
2009 hoff >= -65536L && hoff < 65536L &&
2010 voff >= -65536L && voff < 65536L) {
2011 putc(flag | 4 | ((pk_len + 13) >> 16), pk_file);
2012 putshort(pk_len + 13);
2013 putc(cc, pk_file);
2014 putmed(tfm_wid);
2015 putshort(dm);
2016 putshort(width);
2017 putshort(height);
2018 putshort(hoff);
2019 putshort(voff);
2020 }
2021 else {
2022 putc(flag | 7, pk_file);
2023 putlong(pk_len + 28);
2024 putlong(cc);
2025 putlong(tfm_wid);
2026 putlong((long) (char_width * 65536.0 + 0.5) - (char_width < -0.5));
2027 putlong(0);
2028 putlong(width);
2029 putlong(height);
2030 putlong(hoff);
2031 putlong(voff);
2032 }
2033 fwrite(bitmap, 1, pk_len, pk_file);
2034 if (!quiet) {
2035 putchar(']');
2036 fflush(stdout);
2037 }
2038 }
2039
2040 static void
2041 putspecl(const char *str1, const char *str2)
2042 {
2043 int len1 = strlen(str1);
2044 int len2 = 0;
2045
2046 if (str2 != NULL) len2 = strlen(str2);
2047 if (len1 + len2 > 255) return;
2048 putc(PK_SPC, pk_file);
2049 putc(len1 + len2, pk_file);
2050 fwrite(str1, 1, len1, pk_file);
2051 if (len2 != 0) fwrite(str2, 1, len2, pk_file);
2052 }
2053
2054 int
2055 main(int argc, char **argv)
2056 {
2057 FILE *config_file;
2058 FILE *render_ps;
2059 FILE *tfm_file;
2060 char **argp;
2061 float dpi;
2062 const char *dvipsrc;
2063 char *p;
2064 char *PSname = NULL;
2065 char *specinf = NULL;
2066 char *specp = NULL; /* NULL pacifies lint */
2067 char charlist[10*2 + 90*3 + 156*4 + 1];
2068 char designstr[20];
2069 char dpistr[20];
2070 #if HAVE_SIGACTION
2071 struct sigaction sigact;
2072 #endif
2073 #if _AMIGA
2074 char fngs[50];
2075 char fngsf[50];
2076 char tfm_path[256];
2077 BPTR in, out;
2078 #else
2079 char *substarg;
2080 #endif
2081 #if WIN32
2082 DWORD idGsThread;
2083 SECURITY_ATTRIBUTES sa = { sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
2084 #else /* not WIN32 */
2085 #if !_AMIGA
2086 int std_out[2];
2087 #endif
2088 int std_in[2];
2089 #endif /* not WIN32 */
2090 int cc;
2091 int ppp;
2092 int i;
2093
2094 argp = argv;
2095 while (++argp < argv + argc && (*argp)[0] == '-') {
2096 const struct option *opt_ptr;
2097 const struct option *opt;
2098 char *arg = *argp + 1;
2099
2100 if (*arg == '\0') --arg; /* this will flag an error later */
2101 if (*arg != '-') { /* if short argument */
2102 opt = options;
2103 for (;;) {
2104 if (*arg == opt->shortname)
2105 break;
2106 if (++opt >= options + NUMBER(options))
2107 opt_oops("invalid option -- %c", *arg);
2108 }
2109 if (opt->has_arg) {
2110 ++arg;
2111 if (*arg == '\0') {
2112 if (++argp >= argv + argc)
2113 opt_oops("option requires an argument -- %c",
2114 arg[-1]);
2115 arg = *argp;
2116 }
2117 }
2118 else {
2119 if (arg[1] != '\0')
2120 opt_oops("invalid number of bytes in option `%s'",
2121 arg - 1);
2122 }
2123 }
2124 else { /* long argument */
2125 int len;
2126 char *arg1;
2127
2128 ++arg;
2129 if (*arg == '\0') { /* if -- */
2130 ++argp;
2131 break;
2132 }
2133 len = strlen(arg);
2134 arg1 = memchr(arg, '=', len);
2135 if (arg1 != NULL) {
2136 len = arg1 - arg;
2137 ++arg1;
2138 }
2139 opt = NULL;
2140 for (opt_ptr = options; opt_ptr < options + NUMBER(options);
2141 ++opt_ptr)
2142 if (memcmp(arg, opt_ptr->longname, len) == 0) {
2143 if (opt != NULL)
2144 opt_oops("option `%s' is ambiguous.", arg - 2);
2145 opt = opt_ptr;
2146 }
2147 if (opt == NULL)
2148 opt_oops("unrecognized option `%s'", arg - 2);
2149 if (opt->has_arg) {
2150 if (arg1 == NULL) {
2151 if (++argp >= argv + argc)
2152 opt_oops("option `--%s' requires an argument.",
2153 opt->longname);
2154 arg1 = *argp;
2155 }
2156 }
2157 else {
2158 if (arg1 != NULL)
2159 opt_oops("option `--%s' doesn't allow an argument.",
2160 opt->longname);
2161 }
2162 arg = arg1;
2163 } /* end long argument */
2164
2165 if (opt->addr != NULL) {
2166 if (opt->has_arg)
2167 *((char **) opt->addr) = arg;
2168 else
2169 *((Boolean *) opt->addr) = opt->value;
2170 }
2171
2172 switch (opt->shortname) {
2173 #if defined(KPATHSEA) && defined (KPSE_DEBUG)
2174 case OPT_DBG:
2175 kpathsea_debug |= atoi(arg);
2176 break;
2177 #endif
2178 case 'h':
2179 #ifndef KPATHSEA
2180 puts("\
2181 Usage: gsftopk [OPTION] FONT DPI\n\
2182 Translate the PostScript Type 1 font FONT to PK bitmap format at DPI dpi.\n\
2183 \n\
2184 -t, --test check for presence of font in .map file.\n\
2185 --mapline=LINE use LINE as the line from the .map file.\n\
2186 --mapfile=FILE use FILE as a .map file; default psfonts.map.\n\
2187 -i GS, --interpreter=GS use GS as Ghostscript interpreter.\n\
2188 --dosnames short pk filename (cmr10.pk instead of cmr10.600pk).\n\
2189 -q, --quiet don't print progress information to standard output.\n\
2190 -h, --help print this message and exit.\n\
2191 -v, --version print version number and exit.\n");
2192 #else
2193 puts("\
2194 Usage: gsftopk [OPTION] FONT DPI\n\
2195 Translate the PostScript Type 1 font FONT to PK bitmap format at DPI dpi.\n\
2196 \n\
2197 -t, --test check for presence of font in .map file.\n\
2198 --mapline=LINE use LINE as the line from the .map file.\n\
2199 --mapfile=FILE use FILE as a .map file; default psfonts.map.\n\
2200 -i GS, --interpreter=GS use GS as Ghostscript interpreter.\n\
2201 --dosnames short pk filename (cmr10.pk instead of cmr10.600pk).\n\
2202 -q, --quiet don't print progress information to standard output.\n\
2203 --debug=NUM set debugging flags.\n\
2204 -h, --help print this message and exit.\n\
2205 -v, --version print version number and exit.\n");
2206 #endif
2207 return 0;
2208 case 'v':
2209 #ifndef KPATHSEA
2210 printf("gsftopk %s\n", version);
2211 #else
2212 {
2213 printf("gsftopk(k) %s\n", version);
2214 puts(kpathsea_version_string);
2215 puts("Copyright (C) 1993-1998 Paul Vojta.\n\
2216 There is NO warranty. You may redistribute this software\n\
2217 under the terms of the GNU General Public License\n\
2218 and the standard X consortium copyright notice.\n\
2219 For more information about these matters, see the files\n\
2220 named COPYING and gsftopk.c.\n\
2221 Author of gsftopk: Paul Vojta.");
2222 }
2223 #endif
2224 return 0;
2225 }
2226 }
2227
2228 if (mapfile != NULL && mapline != NULL)
2229 opt_oops("cannot specify both `--mapline' and `--mapfile'");
2230
2231 if (argp >= argv + argc)
2232 opt_oops(test ? "must provide a font name"
2233 : "must provide a font name and resolution");
2234
2235 fontname = *argp++;
2236 fontlen = strlen(fontname);
2237
2238 if (argp >= argv + argc) {
2239 if (!test)
2240 opt_oops("must provide rendering resolution");
2241 dpi = 0.0;
2242 }
2243 else {
2244 dpi = atof(*argp++);
2245 if (dpi <= 0.0)
2246 opt_oops("DPI argument `%s' must be a positive number", *argp);
2247 }
2248
2249 if (argp < argv + argc)
2250 opt_oops("no more than two arguments are allowed");
2251
2252 #ifdef KPATHSEA
2253 #ifdef WIN32
2254 setmode(fileno(stdout), _O_BINARY);
2255 #endif
2256 kpse_set_program_name(argv[0], "gsftopk");
2257 kpse_init_prog("GSFTOPK", (int) (dpi + 0.5), NULL, "cmr10");
2258 if (!test)
2259 xputenv_int("KPATHSEA_DPI", (int) (dpi + 0.5));
2260
2261 #if defined(WIN32)
2262 /* TeXLive uses its own Ghostscript */
2263 texlive_gs_init();
2264 #endif
2265
2266 #endif
2267
2268 #if _AMIGA
2269 /* [CL] 21-Jun-97
2270 This is quite silly but it really helps things when determining the
2271 font supplier and family.
2272 */
2273 putenv("GSFTOPKTFM=");
2274 #endif
2275
2276 /*
2277 * Read the dvips-style config file(s).
2278 */
2279
2280 long_line = xmalloc(long_line_len); /* initialize fgets_long */
2281
2282 #ifndef KPATHSEA
2283 config_file = search(CONFIGPATH, "TEXCONFIG", "config.ps");
2284 if (config_file != NULL)
2285 getdefaults(config_file);
2286
2287 dvipsrc = getenv("DVIPSRC");
2288 if (dvipsrc == NULL) {
2289 dvipsrc = getenv("HOME");
2290 if (dvipsrc != NULL) {
2291 i = strlen(dvipsrc);
2292 p = xmalloc(i + 10);
2293 memcpy(p, dvipsrc, i);
2294 memcpy(p + i, "/.dvipsrc", 10);
2295 }
2296 }
2297 if (dvipsrc != NULL) {
2298 config_file = fopen(dvipsrc, "r");
2299 if (config_file != NULL)
2300 getdefaults(config_file);
2301 }
2302
2303 config_file = search(CONFIGPATH, "TEXCONFIG", "config.gsftopk");
2304 if (config_file != NULL)
2305 getdefaults(config_file);
2306 #else
2307 getdefaults("config.ps");
2308
2309 dvipsrc = kpse_var_value("DVIPSRC");
2310 getdefaults(dvipsrc != NULL ? dvipsrc : "$HOME/.dvipsrc");
2311
2312 getdefaults("config.gsftopk");
2313
2314 /* Set HEADERPATH from config file. */
2315
2316 if (config_file_header_path != NULL)
2317 kpse_format_info[kpse_tex_ps_header_format].client_path
2318 = config_file_header_path;
2319 #endif
2320
2321 /*
2322 * Get the map line.
2323 */
2324
2325 if (mapline != NULL) {
2326 if (memcmp(mapline, fontname, fontlen) != 0
2327 || (mapline[fontlen] != '\0' && !isspace((unsigned char)mapline[fontlen])))
2328 oops("font name does not match --mapline argument");
2329 }
2330 else {
2331 Boolean font_found;
2332
2333 if (mapfile != NULL) {
2334 #ifndef KPATHSEA
2335 config_file = search(CONFIGPATH, "TEXCONFIG",
2336 mapfile);
2337 #else
2338 config_file = kpse_open_file(mapfile,
2339 kpse_fontmap_format);
2340 #endif
2341
2342 if (config_file == NULL) {
2343 perror(mapfile);
2344 exit(1);
2345 }
2346 font_found = scan_map_file(config_file);
2347 }
2348 else {
2349 struct p_list *p_node;
2350
2351 font_found = False;
2352 *p_tail = NULL;
2353 for (p_node = p_head; p_node != NULL; p_node = p_node->next) {
2354 #ifndef KPATHSEA
2355 config_file = search(CONFIGPATH, "TEXCONFIG",
2356 p_node->value);
2357 #else
2358 config_file = kpse_open_file(p_node->value,
2359 kpse_fontmap_format);
2360 #endif
2361 if (config_file != NULL)
2362 if (scan_map_file(config_file)) {
2363 font_found = True;
2364 break;
2365 }
2366 }
2367 }
2368
2369 if (!font_found) {
2370 if (test)
2371 exit(1);
2372 else
2373 oops("Cannot find font %s in map file(s).", fontname);
2374 }
2375
2376 mapline = long_line;
2377 }
2378
2379 if (test)
2380 exit(0);
2381
2382 if (!quiet) {
2383 printf("%sversion %s", progname, version);
2384 fflush(stdout);
2385 col = 1; /* any nonzero value will do */
2386 }
2387
2388 /*
2389 * Parse the line from the map file.
2390 */
2391 for (p = mapline + fontlen; *p != '\0'; ++p) {
2392 if (isspace((unsigned char)*p)) continue;
2393 if (*p == '<') {
2394 char *q;
2395 char endc;
2396 char c;
2397 FILE *f;
2398
2399 ++p;
2400 /* There may be two '<'s in front of the filename. */
2401 if (*p == '<') ++p;
2402 /* ... and maybe a '[' */
2403 if (*p == '[') ++p;
2404 q = p;
2405 while (*p != '\0' && !isspace((unsigned char)*p)) ++p;
2406 endc = *p;
2407 *p = '\0';
2408 #ifdef KPATHSEA
2409 searchpath = kpse_find_file(q, kpse_tex_ps_header_format,true);
2410 f = searchpath ? fopen(searchpath, FOPEN_R_MODE) : NULL;
2411 #else
2412 f = search(config_file_header_path, "DVIPSHEADERS", q);
2413 #endif
2414 if (f == NULL) oops("Cannot find font file %s", q);
2415 /* search() also sets searchpath */
2416 addtodls(" (");
2417 addtodls(searchpath);
2418 c = getc(f);
2419 addtodls(c == '\0' ? ") ttload"
2420 : c == '\200' ? ") brun"
2421 : ") run");
2422 fclose(f);
2423 if (endc == '\0') break;
2424 continue;
2425 }
2426 else if (*p == '"') {
2427 char *q;
2428
2429 if (specinf != NULL)
2430 *specp++ = ' ';
2431 else
2432 specinf = specp = xmalloc(strlen(p));
2433 ++p;
2434 q = strchr(p, '"');
2435 if (q == NULL) q = p + strlen(p);
2436 memcpy(specp, p, q - p);
2437 specp += q - p;
2438 p = q;
2439 if (*p == '\0') break;
2440 else continue;
2441 }
2442 else {
2443 PSname = p;
2444 while (*p != '\0' && !isspace((unsigned char)*p)) ++p;
2445 if (*p == '\0') break;
2446 }
2447 *p = '\0';
2448 }
2449
2450 #if OLD_DVIPS
2451 /* Parse lines like `Symbol-Slanted "/Symbol .167 SlantFont"'. */
2452 if (*(p = specinf) == '/') {
2453 PSname = ++p;
2454 while (*p && !isspace(*p)) ++p;
2455 if (*p) *p++ = '\0';
2456 specinf = p;
2457 }
2458 #endif /* OLD_DVIPS */
2459
2460 if (specinf != NULL) {
2461 *specp = '\0';
2462 specinfo = specinf;
2463 }
2464
2465 if (PSname == NULL)
2466 PSname = fontname;
2467
2468 /*
2469 * Start up Ghostscript.
2470 */
2471
2472 #ifdef KPATHSEA
2473 searchpath = kpse_find_file("render.ps", kpse_tex_ps_header_format,
2474 true);
2475 render_ps = searchpath ? fopen (searchpath, FOPEN_R_MODE) : NULL;
2476 #else
2477 render_ps = search(config_file_header_path, "DVIPSHEADERS",
2478 "render.ps");
2479 #endif
2480 if (render_ps == NULL)
2481 oops("Cannot find PS driver file \"render.ps\".");
2482 fclose(render_ps);
2483
2484 #if !_AMIGA
2485 substarg = xmalloc(strlen(PSname) + 13);
2486 sprintf(substarg, "-sSUBSTFONT=%s", PSname);
2487 #endif
2488
2489 sprintf(dpistr, "%f", dpi);
2490
2491 #if _AMIGA
2492
2493 mktemp(tmpname);
2494
2495 sprintf(fngs, "fifo:%s/rweK", tmpname);
2496 sprintf(fngsf, "fifo:%s/rweKm", tmpname);
2497
2498 std_in[1] = open(fngsf, O_WRONLY|O_TRUNC|O_CREAT, 511);
2499
2500 if (std_in[1] == -1) {
2501 perror("pipe");
2502 return 1;
2503 }
2504
2505 in = Open(fngs, MODE_OLDFILE);
2506 out = Open(fngs, MODE_NEWFILE);
2507
2508 if (in && out) {
2509 int error;
2510 char *cmd;
2511 char formatstr[] = "%s -dNODISPLAY -dNOGC -dNOSAFER -sSUBSTFONT=\"%s\" -q -- \"%s\" \"%s\" \"%s\" \"%s\" \"%s\"";
2512 unsigned int len;
2513
2514 len = sizeof formatstr + strlen(gspath) + strlen(searchpath)
2515 + 2 * strlen(PSname) + (dlstring != NULL ? strlen(dlstring) : 0)
2516 + strlen(specinfo) + strlen(dpistr);
2517
2518 cmd = xmalloc(len);
2519
2520 sprintf(cmd, formatstr, PSname, gspath, searchpath, PSname,
2521 dlstring != NULL ? dlstring : "", specinfo, dpistr);
2522
2523 error = SystemTags(cmd, SYS_Input, in,
2524 SYS_Output, out,
2525 SYS_Asynch, TRUE,
2526 /* NP_StackSize, 50000, */
2527 TAG_DONE, TAG_DONE);
2528 free(cmd);
2529
2530 if (error == -1) {
2531 Close(in);
2532 Close(out);
2533 PrintFault(error, "System(gs)");
2534 exit(1);
2535 }
2536 }
2537 else {
2538 perror("pipes");
2539 if (in) Close(in);
2540 if (out) Close(out);
2541 exit(1);
2542 }
2543
2544 #elif WIN32
2545
2546 /* (later) */
2547
2548 #else /* neither _AMIGA nor WIN32 */
2549
2550 if (pipe(std_in) != 0 || pipe(std_out) != 0) {
2551 perror("pipe");
2552 return 1;
2553 }
2554
2555 /* Catch the signal for death of the child process. */
2556
2557 #if HAVE_SIGACTION
2558 sigact.sa_handler = handle_sigchild;
2559 (void) sigemptyset(&sigact.sa_mask);
2560 sigact.sa_flags = SA_NOCLDSTOP;
2561 (void) sigaction(SIGCHLD, &sigact, (struct sigaction *) NULL);
2562 #else
2563 (void) signal(SIGCHLD, handle_sigchild);
2564 #endif
2565
2566 /*
2567 * Also catch various termination signals, so that we can kill the
2568 * gs process before terminating.
2569 */
2570
2571 (void) signal(SIGHUP, handle_sigterm);
2572 (void) signal(SIGINT, handle_sigterm);
2573 (void) signal(SIGQUIT, handle_sigterm);
2574 (void) signal(SIGTERM, handle_sigterm);
2575
2576 fflush(stderr); /* to avoid double flushing */
2577 gs_pid = vfork();
2578 if (gs_pid == 0) {
2579 close(std_in[1]);
2580 dup2(std_in[0], 0);
2581 close(std_in[0]);
2582 close(std_out[0]);
2583 dup2(std_out[1], 1);
2584 close(std_out[1]);
2585 execlp(gspath, "gs", "-dNODISPLAY", "-dNOGC", "-dNOSAFER", substarg, "-q", "--",
2586 /* render.ps */ searchpath,
2587 PSname,
2588 dlstring != NULL ? dlstring : "", specinfo, dpistr, NULL);
2589 if (col != 0) {
2590 putc('\n', stderr);
2591 col = 0;
2592 }
2593 perror(gspath);
2594 exit(1);
2595 }
2596 if (gs_pid == -1) {
2597 perror("fork");
2598 exit(1);
2599 }
2600
2601 #endif /* neither _AMIGA nor WIN32 */
2602
2603 /*
2604 * Open and read the tfm file. If this takes a while, at least
2605 * it can overlap with the startup of Ghostscript.
2606 */
2607
2608 xfilename = xmalloc(fontlen + 10);
2609 strcpy(xfilename, fontname);
2610 #ifdef KPATHSEA
2611 #if _AMIGA
2612 strcpy(tfm_path, kpse_find_file(xfilename, kpse_tfm_format, true));
2613 tfm_file = fopen(tfm_path, "r");
2614 #else
2615 tfm_file = kpse_open_file(xfilename, kpse_tfm_format);
2616 #endif /* _AMIGA */
2617 #else /* not KPATHSEA */
2618 strcpy(xfilename + fontlen, ".tfm");
2619 tfm_file = search(TFMPATH, "TEXFONTS", xfilename);
2620 #endif /* not KPATHSEA */
2621 if (tfm_file == NULL) oops("Cannot find tfm file.");
2622
2623 for (i = 0; i < 12; ++i) {
2624 int j;
2625
2626 j = (int) ((byte) getc(tfm_file)) << 8;
2627 tfm_lengths[i] = j | (int) ((byte) getc(tfm_file));
2628 }
2629 checksum = getlong(tfm_file);
2630 design = getlong(tfm_file);
2631 fseek(tfm_file, 4 * (lh + 6), 0);
2632 p = charlist;
2633 for (cc = bc; cc <= ec; ++cc) {
2634 width_index[cc] = (byte) getc(tfm_file);
2635 if (width_index[cc] != 0) {
2636 sprintf(p, "%d ", cc);
2637 p += strlen(p);
2638 }
2639 (void) getc(tfm_file);
2640 (void) getc(tfm_file);
2641 (void) getc(tfm_file);
2642 }
2643 for (i = 0; i < nw; ++i) tfm_widths[i] = getlong(tfm_file);
2644 fclose(tfm_file);
2645 p[-1] = '\n';
2646
2647 sprintf(designstr, "%f\n", (float) design / (1 << 20));
2648
2649 #if !WIN32
2650
2651 /* write the design size and character list to the file */
2652 write(std_in[1], designstr, strlen(designstr));
2653 write(std_in[1], charlist, p - charlist);
2654
2655 close(std_in[1]);
2656
2657 #else /* WIN32 */
2658 SetConsoleCtrlHandler(handle_sigterm, TRUE);
2659
2660 hGsDataIn = CreateEvent(&sa, FALSE, FALSE, "gsDataIn");
2661 hGsDataOut = CreateEvent(&sa, FALSE, FALSE, "gsDataOut");
2662
2663 gs_argv[4] = substarg;
2664 gs_argv[7] = searchpath;
2665 gs_argv[8] = PSname;
2666 gs_argv[9] = dlstring != NULL ? dlstring : "";
2667 gs_argv[10] = specinfo;
2668 gs_argv[11] = dpistr;
2669
2670 buffer_stdin = concat(designstr, charlist);
2671
2672 if ((hGsThread = CreateThread(&sa, /* security attributes */
2673 0, /* default stack size */
2674 Win32GsSendData, /* start address of thread */
2675 0, /* parameter */
2676 0, /* creation flags */
2677 &idGsThread /* thread id */
2678 )) == NULL)
2679 Win32Error("CreateThread");
2680
2681 #endif /* WIN32 */
2682
2683 /*
2684 * Read the output from Ghostscript.
2685 */
2686
2687 #if _AMIGA
2688
2689 if ((data_file = fopen(fngsf, "r")) == NULL) {
2690 perror("GS_out");
2691 exit(1);
2692 }
2693
2694 #elif WIN32
2695
2696 /* Nothing */
2697
2698 #else /* neither _AMIGA nor WIN32 */
2699
2700 data_fd = std_out[0];
2701
2702 /* Set data_fd for non-blocking I/O */
2703 if (fcntl(data_fd, F_SETFL, fcntl(data_fd, F_GETFL, 0) | O_NONBLOCK)
2704 == -1)
2705 perror("fcntl");
2706
2707 #endif /* neither _AMIGA nor WIN32 */
2708
2709 /*
2710 * Create pk file and write preamble.
2711 */
2712
2713 if (dosnames)
2714 strcpy(xfilename + fontlen, ".pk");
2715 else
2716 sprintf(xfilename + fontlen, ".%dpk", (int) (dpi + 0.5));
2717
2718 if ((pk_file = fopen(xfilename, FOPEN_WBIN_MODE)) == NULL) {
2719 perror(xfilename);
2720 exit_toto_too();
2721 }
2722 putc(PK_PRE, pk_file);
2723 putc(PK_ID, pk_file);
2724 expect("V"); /* get GS version */
2725 i = strlen(line) - 2;
2726 if (i < 0 || i > 10) i = 0;
2727 line[1] = '/';
2728 if (!quiet) {
2729 if (i > 0) fwrite(line + 1, 1, i, stdout);
2730 putchar('\n');
2731 col = 0;
2732 }
2733 putc(sizeof(progname) + sizeof(version) + i - 2, pk_file);
2734 fwrite(progname, 1, sizeof(progname) - 1, pk_file);
2735 fwrite(version, 1, sizeof(version) - 1, pk_file);
2736 if (i >= 0) {
2737 fwrite(line + 1, 1, i, pk_file);
2738 }
2739 putlong(design);
2740 putlong(checksum);
2741 ppp = dpi / 72.27 * 65536.0 + 0.5;
2742 putlong(ppp); /* hppp */
2743 putlong(ppp); /* vppp */
2744
2745 /*
2746 * Write the actual characters.
2747 */
2748
2749 for (cc = bc; cc <= ec; ++cc)
2750 if (width_index[cc] != 0)
2751 putglyph(cc);
2752
2753 #if _AMIGA
2754
2755 fclose(data_file);
2756
2757 #elif WIN32
2758
2759 /* Release data buffer, enable thread to terminate */
2760 SetEvent(hGsDataOut);
2761
2762 #ifdef DEBUG
2763 fprintf(stderr, "Waiting for thread ... \n");
2764 #endif
2765 if (hGsThread) {
2766 switch (WaitForSingleObject(hGsThread, 2000)) {
2767 case WAIT_OBJECT_0:
2768 CloseHandle(hGsThread);
2769 hGsThread = NULL;
2770 break;
2771 case WAIT_TIMEOUT:
2772 fprintf(stderr, "Timeout waiting for Gs thread.\n");
2773 break;
2774 case WAIT_FAILED:
2775 fprintf(stderr, "WaitForSingleObject failed on Gs thread (Error code %d).\n",
2776 (int)GetLastError());
2777 break;
2778 default:
2779 break;
2780 }
2781 }
2782
2783 if (hGsThread) {
2784 if (TerminateThread(hGsThread, 1) == 0) {
2785 fprintf(stderr, "... couldn't terminate gs thread\n");
2786 }
2787 CloseHandle(hGsThread);
2788 /* FIXME : is it right to call this ? */
2789 gs_dll_release();
2790 }
2791 if (hGsDataIn)
2792 CloseHandle(hGsDataIn);
2793 if (hGsDataOut)
2794 CloseHandle(hGsDataOut);
2795
2796 #else /* neither _AMIGA nor WIN32 */
2797
2798 close(data_fd);
2799 if (!gs_is_done)
2800 wait_for_gs();
2801
2802 #endif /* neither _AMIGA nor WIN32 */
2803
2804 /*
2805 * Write out identifying specials:
2806 * jobname=(font)
2807 * mag=1
2808 * mode=modeless
2809 * pixels_per_inch=(dpi)
2810 */
2811
2812 putspecl("jobname=", fontname);
2813 putspecl("mag=1", NULL);
2814 putspecl("mode=modeless", NULL);
2815 sprintf(dpistr, "%d", (int) dpi);
2816 putspecl("pixels_per_inch=", dpistr);
2817
2818 /*
2819 * Postamble
2820 */
2821
2822 putc(PK_POST, pk_file);
2823 while (ftell(pk_file) % 4 != 0) putc(PK_NOP, pk_file);
2824 fclose(pk_file);
2825 if (!quiet) putchar('\n');
2826 col = 0;
2827
2828 #if _AMIGA
2829 /* [CL] 21-Jun-97
2830 The same silly thing to indicate the path of the tfm file
2831 */
2832 {
2833 char tmpstr[80];
2834
2835 sprintf(tmpstr, "GSFTOPKTFM=%s", tfm_path);
2836 putenv(tmpstr);
2837 }
2838 #endif
2839
2840 return 0;
2841 }