2 /* Copyright (C) 2000, 2001, 2002, 2003, 2004 Free Software Foundation, Inc.
3 Written by Gaius Mulley (gaius@glam.ac.uk).
5 This file is part of groff.
7 groff is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2, or (at your option) any later
12 groff is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
17 You should have received a copy of the GNU General Public License along
18 with groff; see the file COPYING. If not, write to the Free Software
19 Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
32 #include "stringclass.h"
35 #include "searchpath.h"
40 #include <sys/types.h>
46 # include <sys/wait.h>
48 #else /* not _POSIX_VERSION */
50 #endif /* not _POSIX_VERSION */
56 /* Establish some definitions to facilitate discrimination between
57 differing runtime environments. */
59 #undef MAY_FORK_CHILD_PROCESS
60 #undef MAY_SPAWN_ASYNCHRONOUS_CHILD
62 #if defined(__MSDOS__) || defined(_WIN32)
64 // Most MS-DOS and Win32 environments will be missing the `fork' capability
65 // (some like Cygwin have it, but it is best avoided).
67 # define MAY_FORK_CHILD_PROCESS 0
69 // On these systems, we use `spawn...', instead of `fork' ... `exec...'.
70 # include <process.h> // for `spawn...'
71 # include <fcntl.h> // for attributes of pipes
73 # if defined(__CYGWIN__) || defined(_UWIN) || defined(_WIN32)
75 // These Win32 implementations allow parent and `spawn...'ed child to
76 // multitask asynchronously.
78 # define MAY_SPAWN_ASYNCHRONOUS_CHILD 1
82 // Others may adopt MS-DOS behaviour where parent must sleep,
83 // from `spawn...' until child terminates.
85 # define MAY_SPAWN_ASYNCHRONOUS_CHILD 0
87 # endif /* not defined __CYGWIN__, _UWIN, or _WIN32 */
89 # if defined(DEBUGGING) && !defined(DEBUG_FILE_DIR)
90 /* When we are building a DEBUGGING version we need to tell pre-grohtml
91 where to put intermediate files (the DEBUGGING version will preserve
94 On a UNIX host, we might simply use `/tmp', but MS-DOS and Win32 will
95 probably not have this on all disk drives, so default to using
96 `c:/temp' instead. (Note that user may choose to override this by
97 supplying a definition such as
99 -DDEBUG_FILE_DIR=d:/path/to/debug/files
101 in the CPPFLAGS to `make'.) */
103 # define DEBUG_FILE_DIR c:/temp
106 #else /* not __MSDOS__ or _WIN32 */
108 // For non-Microsoft environments assume UNIX conventions,
109 // so `fork' is required and child processes are asynchronous.
110 # define MAY_FORK_CHILD_PROCESS 1
111 # define MAY_SPAWN_ASYNCHRONOUS_CHILD 1
113 # if defined(DEBUGGING) && !defined(DEBUG_FILE_DIR)
114 /* For a DEBUGGING version, on the UNIX host, we can also usually rely
115 on being able to use `/tmp' for temporary file storage. (Note that,
116 as in the __MSDOS__ or _WIN32 case above, the user may override this
119 -DDEBUG_FILE_DIR=/path/to/debug/files
123 # define DEBUG_FILE_DIR /tmp
126 #endif /* not __MSDOS__ or _WIN32 */
129 // For a DEBUGGING version, we need some additional macros,
130 // to direct the captured debug mode output to appropriately named files
131 // in the specified DEBUG_FILE_DIR.
133 # define DEBUG_TEXT(text) #text
134 # define DEBUG_NAME(text) DEBUG_TEXT(text)
135 # define DEBUG_FILE(name) DEBUG_NAME(DEBUG_FILE_DIR) "/" name
138 extern "C" const char *Version_string;
140 #include "pre-html.h"
141 #include "pushback.h"
142 #include "html-strings.h"
144 #define DEFAULT_LINE_LENGTH 7 // inches wide
145 #define DEFAULT_IMAGE_RES 100 // number of pixels per inch resolution
146 #define IMAGE_BOARDER_PIXELS 0
147 #define INLINE_LEADER_CHAR '\\'
149 // Don't use colour names here! Otherwise there is a dependency on
150 // a file called `rgb.txt' which maps names to colours.
151 #define TRANSPARENT "-background rgb:f/f/f -transparent rgb:f/f/f"
152 #define MIN_ALPHA_BITS 0
153 #define MAX_ALPHA_BITS 4
155 #define PAGE_TEMPLATE_SHORT "pg"
156 #define PAGE_TEMPLATE_LONG "-page-"
157 #define PS_TEMPLATE_SHORT "ps"
158 #define PS_TEMPLATE_LONG "-ps-"
159 #define REGION_TEMPLATE_SHORT "rg"
160 #define REGION_TEMPLATE_LONG "-regions-"
170 # define FALSE (1==0)
174 CENTERED, LEFT, RIGHT, INLINE
177 static int postscriptRes = -1; // postscript resolution,
179 static int stdoutfd = 1; // output file descriptor -
180 // normally 1 but might move
182 static char *psFileName = NULL; // name of postscript file
183 static char *psPageName = NULL; // name of file containing
184 // postscript current page
185 static char *regionFileName = NULL; // name of file containing all
187 static char *imagePageName = NULL; // name of bitmap image containing
189 static const char *image_device = "pnmraw";
190 static int image_res = DEFAULT_IMAGE_RES;
191 static int vertical_offset = 0;
192 static char *image_template = NULL; // image template filename
193 static char *macroset_template= NULL; // image template passed to troff
195 static int troff_arg = 0; // troff arg index
196 static char *image_dir = NULL; // user specified image directory
197 static int textAlphaBits = MAX_ALPHA_BITS;
198 static int graphicAlphaBits = MAX_ALPHA_BITS;
199 static char *antiAlias = NULL; // antialias arguments we pass to gs
200 static int show_progress = FALSE; // should we display page numbers as
201 // they are processed?
202 static int currentPageNo = -1; // current image page number
203 #if defined(DEBUGGING)
204 static int debug = FALSE;
205 static char *troffFileName = NULL; // output of pre-html output which
206 // is sent to troff -Tps
207 static char *htmlFileName = NULL; // output of pre-html output which
208 // is sent to troff -Thtml
211 static char *linebuf = NULL; // for scanning devps/DESC
212 static int linebufsize = 0;
214 const char *const FONT_ENV_VAR = "GROFF_FONT_PATH";
215 static search_path font_path(FONT_ENV_VAR, FONTPATH, 0, 0);
219 * Images are generated via postscript, gs, and the pnm utilities.
221 #define IMAGE_DEVICE "-Tps"
224 static int do_file(const char *filename);
228 * sys_fatal - Write a fatal error message.
229 * Taken from src/roff/groff/pipeline.c.
232 void sys_fatal(const char *s)
234 fatal("%1: %2", s, strerror(errno));
238 * get_line - Copy a line (w/o newline) from a file to the
239 * global line buffer.
242 int get_line(FILE *f)
247 linebuf = new char[128];
251 // skip leading whitespace
256 if (c != ' ' && c != '\t') {
265 if (i + 1 >= linebufsize) {
266 char *old_linebuf = linebuf;
267 linebuf = new char[linebufsize * 2];
268 memcpy(linebuf, old_linebuf, linebufsize);
269 a_delete old_linebuf;
283 * get_resolution - Return the postscript resolution from devps/DESC.
286 static unsigned int get_resolution(void)
291 f = font_path.open_file("devps/DESC", &pathp);
294 fatal("can't open devps/DESC");
295 while (get_line(f)) {
296 int n = sscanf(linebuf, "res %u", &res);
302 fatal("can't find `res' keyword in devps/DESC");
307 * html_system - A wrapper for system().
310 void html_system(const char *s, int redirect_stdout)
312 // Redirect standard error to the null device. This is more
313 // portable than using "2> /dev/null", since it doesn't require a
315 int save_stderr = dup(2);
316 int save_stdout = dup(1);
317 int fdnull = open(NULL_DEV, O_WRONLY|O_BINARY, 0666);
318 if (save_stderr > 2 && fdnull > 2)
320 if (redirect_stdout && save_stdout > 1 && fdnull > 1)
324 int status = system(s);
325 dup2(save_stderr, 2);
327 dup2(save_stdout, 1);
329 fprintf(stderr, "Calling `%s' failed\n", s);
331 fprintf(stderr, "Calling `%s' returned status %d\n", s, status);
337 * make_message - Create a string via malloc and place the result of the
338 * va args into string. Finally the new string is returned.
339 * Taken from man page of printf(3).
342 char *make_message(const char *fmt, ...)
344 /* Guess we need no more than 100 bytes. */
349 if ((p = (char *)malloc(size)) == NULL)
352 /* Try to print in the allocated space. */
354 n = vsnprintf(p, size, fmt, ap);
356 /* If that worked, return the string. */
357 if (n > -1 && n < size - 1) { /* glibc 2.1 and pre-ANSI C 99 */
365 /* Else try again with more space. */
367 size *= 2; /* twice the old size */
368 if ((np = (char *)realloc(p, size)) == NULL) {
369 free(p); /* realloc failed, free old, p. */
372 p = np; /* use realloc'ed, p */
377 * the class and methods for retaining ascii text
390 * char_block - Constructor. Set the, used, and, next, fields to zero.
393 char_block::char_block()
396 for (int i = 0; i < SIZE; i++)
404 int read_file(FILE *fp);
405 int do_html(int argc, char *argv[]);
406 int do_image(int argc, char *argv[]);
407 void emit_troff_output(int device_format_selector);
408 void write_upto_newline(char_block **t, int *i, int is_html);
409 int can_see(char_block **t, int *i, const char *string);
410 int skip_spaces(char_block **t, int *i);
411 void skip_until_newline(char_block **t, int *i);
415 int run_output_filter(int device_format_selector, int argc, char *argv[]);
419 * char_buffer - Constructor.
422 char_buffer::char_buffer()
428 * char_buffer - Destructor. Throw away the whole buffer list.
431 char_buffer::~char_buffer()
433 while (head != NULL) {
434 char_block *temp = head;
441 * read_file - Read in a complete file, fp, placing the contents inside
445 int char_buffer::read_file(FILE *fp)
450 tail = new char_block;
454 if (tail->used == char_block::SIZE) {
455 tail->next = new char_block;
459 // at this point we have a tail which is ready for the next SIZE
461 n = fread(tail->buffer, sizeof(char), char_block::SIZE-tail->used, fp);
466 tail->used += n * sizeof(char);
472 * writeNbytes - Write n bytes to stdout.
475 static void writeNbytes(const char *s, int l)
481 r = write(stdoutfd, s, l - n);
490 * writeString - Write a string to stdout.
493 static void writeString(const char *s)
495 writeNbytes(s, strlen(s));
499 * makeFileName - Create the image filename template
500 * and the macroset image template.
503 static void makeFileName(void)
505 if ((image_dir != NULL) && (strchr(image_dir, '%') != NULL)) {
506 error("cannot use a `%%' within the image directory name");
510 if ((image_template != NULL) && (strchr(image_template, '%') != NULL)) {
511 error("cannot use a `%%' within the image template");
515 if (image_dir == NULL)
516 image_dir = (char *)"";
517 else if (strlen(image_dir) > 0
518 && image_dir[strlen(image_dir) - 1] != '/') {
519 image_dir = make_message("%s/", image_dir);
520 if (image_dir == NULL)
521 sys_fatal("make_message");
524 if (image_template == NULL)
525 macroset_template = make_message("%sgrohtml-%d", image_dir,
528 macroset_template = make_message("%s%s", image_dir, image_template);
530 if (macroset_template == NULL)
531 sys_fatal("make_message");
534 (char *)malloc(strlen("-%d") + strlen(macroset_template) + 1);
535 if (image_template == NULL)
537 strcpy(image_template, macroset_template);
538 strcat(image_template, "-%d");
542 * setupAntiAlias - Set up the antialias string, used when we call gs.
545 static void setupAntiAlias(void)
547 if (textAlphaBits == 0 && graphicAlphaBits == 0)
548 antiAlias = make_message(" ");
549 else if (textAlphaBits == 0)
550 antiAlias = make_message("-dGraphicsAlphaBits=%d ", graphicAlphaBits);
551 else if (graphicAlphaBits == 0)
552 antiAlias = make_message("-dTextAlphaBits=%d ", textAlphaBits);
554 antiAlias = make_message("-dTextAlphaBits=%d -dGraphicsAlphaBits=%d ",
555 textAlphaBits, graphicAlphaBits);
559 * checkImageDir - Check whether the image directory is available.
562 static void checkImageDir(void)
564 if (image_dir != NULL && strcmp(image_dir, "") != 0)
565 if (!(mkdir(image_dir, 0777) == 0 || errno == EEXIST)) {
566 error("cannot create directory `%1'", image_dir);
572 * write_end_image - End the image. Write out the image extents if we
576 static void write_end_image(int is_html)
579 * if we are producing html then these
580 * emit image name and enable output
582 * we are producing images
583 * in which case these generate image
586 writeString("\\O[4]\\O[2]");
588 writeString("\\O[1]");
590 writeString("\\O[0]");
594 * write_start_image - Write troff code which will:
596 * (i) disable html output for the following image
597 * (ii) reset the max/min x/y registers during postscript
601 static void write_start_image(IMAGE_ALIGNMENT pos, int is_html)
603 writeString("\\O[5");
619 writeString(image_template);
620 writeString(".png]");
622 writeString("\\O[0]\\O[3]");
624 // reset min/max registers
625 writeString("\\O[1]\\O[3]");
629 * write_upto_newline - Write the contents of the buffer until a newline
630 * is seen. Check for HTML_IMAGE_INLINE_BEGIN and
631 * HTML_IMAGE_INLINE_END; process them if they are
635 void char_buffer::write_upto_newline(char_block **t, int *i, int is_html)
640 while (j < (*t)->used
641 && (*t)->buffer[j] != '\n'
642 && (*t)->buffer[j] != INLINE_LEADER_CHAR)
645 && (*t)->buffer[j] == '\n')
647 writeNbytes((*t)->buffer + (*i), j - (*i));
648 if ((*t)->buffer[j] == INLINE_LEADER_CHAR) {
649 if (can_see(t, &j, HTML_IMAGE_INLINE_BEGIN))
650 write_start_image(INLINE, is_html);
651 else if (can_see(t, &j, HTML_IMAGE_INLINE_END))
652 write_end_image(is_html);
654 if (j < (*t)->used) {
657 writeNbytes((*t)->buffer + (*i), j - (*i));
661 if (j == (*t)->used) {
664 if (*t && (*t)->buffer[j - 1] != '\n')
665 write_upto_newline(t, i, is_html);
674 * can_see - Return TRUE if we can see string in t->buffer[i] onwards.
677 int char_buffer::can_see(char_block **t, int *i, const char *str)
685 while (k < s->used && j < l && s->buffer[k] == str[j]) {
694 else if (k < s->used && s->buffer[k] != str[j])
703 * skip_spaces - Return TRUE if we have not run out of data.
704 * Consume spaces also.
707 int char_buffer::skip_spaces(char_block **t, int *i)
713 while (k < s->used && isspace(s->buffer[k]))
728 * skip_until_newline - Skip all characters until a newline is seen.
729 * The newline is not consumed.
732 void char_buffer::skip_until_newline(char_block **t, int *i)
737 while (j < (*t)->used && (*t)->buffer[j] != '\n')
739 if (j == (*t)->used) {
742 skip_until_newline(t, i);
750 #define DEVICE_FORMAT(filter) (filter == HTML_OUTPUT_FILTER)
751 #define HTML_OUTPUT_FILTER 0
752 #define IMAGE_OUTPUT_FILTER 1
753 #define OUTPUT_STREAM(name) creat((name), S_IWUSR | S_IRUSR)
754 #define PS_OUTPUT_STREAM OUTPUT_STREAM(psFileName)
755 #define REGION_OUTPUT_STREAM OUTPUT_STREAM(regionFileName)
758 * emit_troff_output - Write formatted buffer content to the troff
759 * post-processor data pipeline.
762 void char_buffer::emit_troff_output(int device_format_selector)
764 // Handle output for BOTH html and image device formats
765 // if `device_format_selector' is passed as
767 // HTML_FORMAT(HTML_OUTPUT_FILTER)
768 // Buffer data is written to the output stream
769 // with template image names translated to actual image names.
771 // HTML_FORMAT(IMAGE_OUTPUT_FILTER)
772 // Buffer data is written to the output stream
773 // with no translation, for image file creation in the post-processor.
776 char_block *element = head;
778 while (element != NULL)
779 write_upto_newline(&element, &idx, device_format_selector);
782 if (close(stdoutfd) < 0)
785 // now we grab fd=1 so that the next pipe cannot use fd=1
787 if (dup(2) != stdoutfd)
788 sys_fatal ("dup failed to use fd=1");
794 * The image class remembers the position of all images in the
795 * postscript file and assigns names for each image.
809 imageItem(int x1, int y1, int x2, int y2,
810 int page, int res, int max_width, char *name);
815 * imageItem - Constructor.
818 imageItem::imageItem(int x1, int y1, int x2, int y2,
819 int page, int res, int max_width, char *name)
833 * imageItem - Destructor.
836 imageItem::~imageItem()
843 * imageList - A class containing a list of imageItems.
854 void add(int x1, int y1, int x2, int y2,
855 int page, int res, int maxx, char *name);
856 void createImages(void);
857 int createPage(int pageno);
858 void createImage(imageItem *i);
859 int getMaxX(int pageno);
863 * imageList - Constructor.
866 imageList::imageList()
867 : head(0), tail(0), count(0)
872 * imageList - Destructor.
875 imageList::~imageList()
877 while (head != NULL) {
885 * createPage - Create one image of, page pageno, from the postscript file.
888 int imageList::createPage(int pageno)
892 if (currentPageNo == pageno)
895 if (currentPageNo >= 1) {
897 * We need to unlink the files which change each time a new page is
898 * processed. The final unlink is done by xtmpfile when pre-grohtml
901 unlink(imagePageName);
906 fprintf(stderr, "[%d] ", pageno);
910 #if defined(DEBUGGING)
912 fprintf(stderr, "creating page %d\n", pageno);
915 s = make_message("psselect -q -p%d %s %s\n",
916 pageno, psFileName, psPageName);
919 sys_fatal("make_message");
920 #if defined(DEBUGGING)
922 fwrite(s, sizeof(char), strlen(s), stderr);
928 s = make_message("echo showpage | "
929 "gs%s -q -dBATCH -dSAFER "
930 "-dDEVICEHEIGHTPOINTS=792 "
931 "-dDEVICEWIDTHPOINTS=%d -dFIXEDMEDIA=true "
932 "-sDEVICE=%s -r%d %s "
933 "-sOutputFile=%s %s -\n",
935 (getMaxX(pageno) * image_res) / postscriptRes,
942 sys_fatal("make_message");
943 #if defined(DEBUGGING)
945 fwrite(s, sizeof(char), strlen(s), stderr);
951 currentPageNo = pageno;
956 * min - Return the minimum of two numbers.
959 int min(int x, int y)
968 * max - Return the maximum of two numbers.
971 int max(int x, int y)
980 * getMaxX - Return the largest right-hand position for any image
984 int imageList::getMaxX(int pageno)
987 int x = postscriptRes * DEFAULT_LINE_LENGTH;
990 if (h->pageNo == pageno)
998 * createImage - Generate a minimal png file from the set of page images.
1001 void imageList::createImage(imageItem *i)
1005 int x1 = max(min(i->X1, i->X2) * image_res / postscriptRes
1006 - IMAGE_BOARDER_PIXELS,
1008 int y1 = max(image_res * vertical_offset / 72
1009 + min(i->Y1, i->Y2) * image_res / postscriptRes
1010 - IMAGE_BOARDER_PIXELS,
1012 int x2 = max(i->X1, i->X2) * image_res / postscriptRes
1013 + IMAGE_BOARDER_PIXELS;
1014 int y2 = image_res * vertical_offset / 72
1015 + max(i->Y1, i->Y2) * image_res / postscriptRes
1016 + 1 + IMAGE_BOARDER_PIXELS;
1017 if (createPage(i->pageNo) == 0) {
1018 s = make_message("pnmcut%s %d %d %d %d < %s "
1019 "| pnmcrop -quiet | pnmtopng%s %s > %s\n",
1021 x1, y1, x2 - x1 + 1, y2 - y1 + 1,
1027 sys_fatal("make_message");
1029 #if defined(DEBUGGING)
1039 fprintf(stderr, "failed to generate image of page %d\n", i->pageNo);
1042 #if defined(DEBUGGING)
1046 fprintf(stderr, "ignoring image as x1 coord is -1\n");
1054 * add - Add an image description to the imageList.
1057 void imageList::add(int x1, int y1, int x2, int y2,
1058 int page, int res, int maxx, char *name)
1060 imageItem *i = new imageItem(x1, y1, x2, y2, page, res, maxx, name);
1073 * createImages - For each image descriptor on the imageList,
1074 * create the actual image.
1077 void imageList::createImages(void)
1079 imageItem *h = head;
1087 static imageList listOfImages; // List of images defined by the region file.
1090 * generateImages - Parse the region file and generate images
1091 * from the postscript file. The region file
1092 * contains the x1,y1--x2,y2 extents of each
1096 static void generateImages(char *region_file_name)
1098 pushBackBuffer *f=new pushBackBuffer(region_file_name);
1100 while (f->putPB(f->getPB()) != eof) {
1101 if (f->isString("grohtml-info:page")) {
1102 int page = f->readInt();
1103 int x1 = f->readInt();
1104 int y1 = f->readInt();
1105 int x2 = f->readInt();
1106 int y2 = f->readInt();
1107 int maxx = f->readInt();
1108 char *name = f->readString();
1109 int res = postscriptRes;
1110 listOfImages.add(x1, y1, x2, y2, page, res, maxx, name);
1111 while (f->putPB(f->getPB()) != '\n'
1112 && f->putPB(f->getPB()) != eof)
1114 if (f->putPB(f->getPB()) == '\n')
1118 /* Write any error messages out to the user. */
1119 fputc(f->getPB(), stderr);
1123 listOfImages.createImages();
1124 if (show_progress) {
1125 fprintf(stderr, "done\n");
1132 * set_redirection - Set up I/O Redirection for handle, was, to refer to
1133 * stream on handle, willbe.
1136 static void set_redirection(int was, int willbe)
1138 // Nothing to do if `was' and `willbe' already have same handle.
1139 if (was != willbe) {
1140 // Otherwise attempt the specified redirection.
1141 if (dup2 (willbe, was) < 0) {
1142 // Redirection failed, so issue diagnostic and bail out.
1143 fprintf(stderr, "failed to replace fd=%d with %d\n", was, willbe);
1144 if (willbe == STDOUT_FILENO)
1146 "likely that stdout should be opened before %d\n", was);
1150 // When redirection has been successfully completed assume redundant
1151 // handle `willbe' is no longer required, so close it.
1152 if (close(willbe) < 0)
1153 // Issue diagnostic if `close' fails.
1159 * save_and_redirect - Get duplicate handle for stream, was, then
1160 * redirect, was, to refer to, willbe.
1163 static int save_and_redirect(int was, int willbe)
1166 // No redirection specified so don't do anything but silently bailing out.
1169 // Proceeding with redirection so first save and verify our duplicate
1170 // handle for `was'.
1171 int saved = dup(was);
1173 fprintf(stderr, "unable to get duplicate handle for %d\n", was);
1177 // Duplicate handle safely established so complete redirection.
1178 set_redirection(was, willbe);
1180 // Finally return the saved duplicate descriptor for the
1181 // original `was' stream.
1186 * alterDeviceTo - If, toImage, is set
1187 * the argument list is altered to include
1188 * IMAGE_DEVICE and we invoke groff rather than troff.
1190 * set -Thtml and groff.
1193 static void alterDeviceTo(int argc, char *argv[], int toImage)
1199 if (strcmp(argv[i], "-Thtml") == 0)
1200 argv[i] = (char *)IMAGE_DEVICE;
1203 argv[troff_arg] = (char *)"groff"; /* rather than troff */
1207 if (strcmp(argv[i], IMAGE_DEVICE) == 0)
1208 argv[i] = (char *)"-Thtml";
1211 argv[troff_arg] = (char *)"groff"; /* use groff -Z */
1216 * addZ - Append -Z onto the command list for groff.
1219 char **addZ(int argc, char *argv[])
1221 char **new_argv = (char **)malloc((argc + 2) * sizeof(char *));
1224 if (new_argv == NULL)
1225 sys_fatal("malloc");
1228 new_argv[i] = argv[i];
1231 new_argv[i] = (char *)"-Z";
1233 new_argv[i + 1] = argv[i];
1237 new_argv[argc] = NULL;
1242 * addRegDef - Append a defined register or string onto the command
1246 char **addRegDef(int argc, char *argv[], const char *numReg)
1248 char **new_argv = (char **)malloc((argc + 2) * sizeof(char *));
1251 if (new_argv == NULL)
1252 sys_fatal("malloc");
1255 new_argv[i] = argv[i];
1258 new_argv[argc] = strsave(numReg);
1260 new_argv[argc] = NULL;
1265 * dump_args - Display the argument list.
1268 void dump_args(int argc, char *argv[])
1270 fprintf(stderr, " %d arguments:", argc);
1271 for (int i = 0; i < argc; i++)
1272 fprintf(stderr, " %s", argv[i]);
1273 fprintf(stderr, "\n");
1276 int char_buffer::run_output_filter(int filter, int /* argc */, char **argv)
1282 if (pipe(pipedes) < 0)
1285 #if MAY_FORK_CHILD_PROCESS
1286 // This is the UNIX process model. To invoke our post-processor,
1287 // we must `fork' the current process.
1289 if ((child_pid = fork()) < 0)
1292 else if (child_pid == 0) {
1293 // This is the child process fork. We redirect its `stdin' stream
1294 // to read data emerging from our pipe. There is no point in saving,
1295 // since we won't be able to restore later!
1297 set_redirection(STDIN_FILENO, pipedes[0]);
1299 // The parent process will be writing this data, so we should release
1300 // the child's writeable handle on the pipe, since we have no use for it.
1302 if (close(pipedes[1]) < 0)
1305 // The IMAGE_OUTPUT_FILTER needs special output redirection...
1307 if (filter == IMAGE_OUTPUT_FILTER) {
1308 // with BOTH `stdout' AND `stderr' diverted to files.
1310 set_redirection(STDOUT_FILENO, PS_OUTPUT_STREAM);
1311 set_redirection(STDERR_FILENO, REGION_OUTPUT_STREAM);
1314 // Now we are ready to launch the output filter.
1316 execvp(argv[0], argv);
1318 // If we get to here then the `exec...' request for the output filter
1319 // failed. Diagnose it and bail out.
1321 error("couldn't exec %1: %2", argv[0], strerror(errno), ((char *)0));
1322 fflush(stderr); // just in case error() didn't
1327 // This is the parent process fork. We will be writing data to the
1328 // filter pipeline, and the child will be reading it. We have no further
1329 // use for our read handle on the pipe, and should close it.
1331 if (close(pipedes[0]) < 0)
1334 // Now we redirect the `stdout' stream to the inlet end of the pipe,
1335 // and push out the appropiately formatted data to the filter.
1337 pipedes[1] = save_and_redirect(STDOUT_FILENO, pipedes[1]);
1338 emit_troff_output(DEVICE_FORMAT(filter));
1340 // After emitting all the data we close our connection to the inlet
1341 // end of the pipe so the child process will detect end of data.
1343 set_redirection(STDOUT_FILENO, pipedes[1]);
1345 // Finally, we must wait for the child process to complete.
1347 if (WAIT(&status, child_pid, _WAIT_CHILD) != child_pid)
1351 #elif MAY_SPAWN_ASYNCHRONOUS_CHILD
1353 // We do not have `fork', (or we prefer not to use it),
1354 // but asynchronous processes are allowed, passing data through pipes.
1355 // This should be ok for most Win32 systems and is preferred to `fork'
1356 // for starting child processes under Cygwin.
1358 // Before we start the post-processor we bind its inherited `stdin'
1359 // stream to the readable end of our pipe, saving our own `stdin' stream
1362 pipedes[0] = save_and_redirect(STDIN_FILENO, pipedes[0]);
1364 // for the Win32 model,
1365 // we need special provision for saving BOTH `stdout' and `stderr'.
1367 int saved_stdout = dup(STDOUT_FILENO);
1368 int saved_stderr = STDERR_FILENO;
1370 // The IMAGE_OUTPUT_FILTER needs special output redirection...
1372 if (filter == IMAGE_OUTPUT_FILTER) {
1373 // with BOTH `stdout' AND `stderr' diverted to files while saving a
1374 // duplicate handle for `stderr'.
1376 set_redirection(STDOUT_FILENO, PS_OUTPUT_STREAM);
1377 saved_stderr = save_and_redirect(STDERR_FILENO, REGION_OUTPUT_STREAM);
1380 // We then use an asynchronous spawn request to start the post-processor.
1382 if ((child_pid = spawnvp(_P_NOWAIT, argv[0], argv)) < 0) {
1383 // Should the spawn request fail we issue a diagnostic and bail out.
1385 error("cannot spawn %1: %2", argv[0], strerror(errno), ((char *)0));
1389 // Once the post-processor has been started we revert our `stdin'
1390 // to its original saved source, which also closes the readable handle
1393 set_redirection(STDIN_FILENO, pipedes[0]);
1395 // if we redirected `stderr', for use by the image post-processor,
1396 // then we also need to reinstate its original assignment.
1398 if (filter == IMAGE_OUTPUT_FILTER)
1399 set_redirection(STDERR_FILENO, saved_stderr);
1401 // Now we redirect the `stdout' stream to the inlet end of the pipe,
1402 // and push out the appropiately formatted data to the filter.
1404 set_redirection(STDOUT_FILENO, pipedes[1]);
1405 emit_troff_output(DEVICE_FORMAT(filter));
1407 // After emitting all the data we close our connection to the inlet
1408 // end of the pipe so the child process will detect end of data.
1410 set_redirection(STDOUT_FILENO, saved_stdout);
1412 // And finally, we must wait for the child process to complete.
1414 if (WAIT(&status, child_pid, _WAIT_CHILD) != child_pid)
1417 #else /* can't do asynchronous pipes! */
1419 // TODO: code to support an MS-DOS style process model
1422 #endif /* MAY_FORK_CHILD_PROCESS or MAY_SPAWN_ASYNCHRONOUS_CHILD */
1428 * do_html - Set the troff number htmlflip and
1429 * write out the buffer to troff -Thtml.
1432 int char_buffer::do_html(int argc, char *argv[])
1436 alterDeviceTo(argc, argv, 0);
1437 argv += troff_arg; // skip all arguments up to groff
1439 argv = addZ(argc, argv);
1442 s = "-dwww-image-template=";
1443 s += macroset_template; // do not combine these statements,
1444 // otherwise they will not work
1445 s += '\0'; // the trailing `\0' is ignored
1446 argv = addRegDef(argc, argv, s.contents());
1449 #if defined(DEBUGGING)
1450 # define HTML_DEBUG_STREAM OUTPUT_STREAM(htmlFileName)
1451 // slight security risk so only enabled if compiled with defined(DEBUGGING)
1453 int saved_stdout = save_and_redirect(STDOUT_FILENO, HTML_DEBUG_STREAM);
1454 emit_troff_output(DEVICE_FORMAT(HTML_OUTPUT_FILTER));
1455 set_redirection(STDOUT_FILENO, saved_stdout);
1459 return run_output_filter(HTML_OUTPUT_FILTER, argc, argv);
1463 * do_image - Write out the buffer to troff -Tps.
1466 int char_buffer::do_image(int argc, char *argv[])
1470 alterDeviceTo(argc, argv, 1);
1471 argv += troff_arg; // skip all arguments up to troff/groff
1473 argv = addRegDef(argc, argv, "-rps4html=1");
1476 s = "-dwww-image-template=";
1477 s += macroset_template;
1479 argv = addRegDef(argc, argv, s.contents());
1482 // override local settings and produce a page size letter postscript file
1483 argv = addRegDef(argc, argv, "-P-pletter");
1486 #if defined(DEBUGGING)
1487 # define IMAGE_DEBUG_STREAM OUTPUT_STREAM(troffFileName)
1488 // slight security risk so only enabled if compiled with defined(DEBUGGING)
1490 int saved_stdout = save_and_redirect(STDOUT_FILENO, IMAGE_DEBUG_STREAM);
1491 emit_troff_output(DEVICE_FORMAT(IMAGE_OUTPUT_FILTER));
1492 set_redirection(STDOUT_FILENO, saved_stdout);
1496 return run_output_filter(IMAGE_OUTPUT_FILTER, argc, argv);
1499 static char_buffer inputFile;
1502 * usage - Emit usage arguments.
1505 static void usage(FILE *stream)
1508 "usage: %s troffname [-Iimage_name] [-Dimage_directory]\n"
1509 " [-P-o vertical_image_offset] [-P-i image_resolution]\n"
1513 " vertical_image_offset (default %d/72 of an inch)\n",
1516 " image_resolution (default %d) pixels per inch\n",
1519 " image_name is the name of the stem for all images\n"
1520 " (default is grohtml-<pid>)\n");
1522 " place all png files into image_directory\n");
1526 * scanArguments - Scan for all arguments including -P-i, -P-o, -P-D,
1527 * and -P-I. Return the argument index of the first
1531 static int scanArguments(int argc, char **argv)
1533 const char *command_prefix = getenv("GROFF_COMMAND_PREFIX");
1534 if (!command_prefix)
1535 command_prefix = PROG_PREFIX;
1536 char *troff_name = new char[strlen(command_prefix) + strlen("troff") + 1];
1537 strcpy(troff_name, command_prefix);
1538 strcat(troff_name, "troff");
1540 static const struct option long_options[] = {
1541 { "help", no_argument, 0, CHAR_MAX + 1 },
1542 { "version", no_argument, 0, 'v' },
1545 while ((c = getopt_long(argc, argv,
1546 "+a:g:o:i:I:j:D:F:vbdhlrnp", long_options, NULL))
1550 printf("GNU pre-grohtml (groff) version %s\n", Version_string);
1553 textAlphaBits = min(max(MIN_ALPHA_BITS, atoi(optarg)),
1555 if (textAlphaBits == 3) {
1556 error("cannot use 3 bits of antialiasing information");
1561 graphicAlphaBits = min(max(MIN_ALPHA_BITS, atoi(optarg)),
1563 if (graphicAlphaBits == 3) {
1564 error("cannot use 3 bits of antialiasing information");
1569 // handled by post-grohtml (set background color to white)
1575 image_template = optarg;
1578 image_res = atoi(optarg);
1581 font_path.command_line_dir(optarg);
1584 // handled by post-grohtml (set job name for multiple file output)
1587 vertical_offset = atoi(optarg);
1590 show_progress = TRUE;
1593 #if defined(DEBUGGING)
1598 // handled by post-grohtml
1600 case CHAR_MAX + 1: // --help
1614 if (strcmp(argv[i], troff_name) == 0)
1616 else if (argv[i][0] != '-')
1620 a_delete troff_name;
1626 * makeTempFiles - Name the temporary files.
1629 static int makeTempFiles(void)
1631 #if defined(DEBUGGING)
1632 psFileName = DEBUG_FILE("prehtml-ps");
1633 regionFileName = DEBUG_FILE("prehtml-region");
1634 imagePageName = DEBUG_FILE("prehtml-page");
1635 psPageName = DEBUG_FILE("prehtml-psn");
1636 troffFileName = DEBUG_FILE("prehtml-troff");
1637 htmlFileName = DEBUG_FILE("prehtml-html");
1638 #else /* not DEBUGGING */
1641 /* psPageName contains a single page of postscript */
1642 f = xtmpfile(&psPageName,
1643 PS_TEMPLATE_LONG, PS_TEMPLATE_SHORT,
1646 sys_fatal("xtmpfile");
1651 /* imagePageName contains a bitmap image of the single postscript page */
1652 f = xtmpfile(&imagePageName,
1653 PAGE_TEMPLATE_LONG, PAGE_TEMPLATE_SHORT,
1656 sys_fatal("xtmpfile");
1661 /* psFileName contains a postscript file of the complete document */
1662 f = xtmpfile(&psFileName,
1663 PS_TEMPLATE_LONG, PS_TEMPLATE_SHORT,
1666 sys_fatal("xtmpfile");
1671 /* regionFileName contains a list of the images and their boxed coordinates */
1672 f = xtmpfile(®ionFileName,
1673 REGION_TEMPLATE_LONG, REGION_TEMPLATE_SHORT,
1676 sys_fatal("xtmpfile");
1681 #endif /* not DEBUGGING */
1685 int main(int argc, char **argv)
1687 program_name = argv[0];
1694 fprintf(stderr, "%s: invoked with %d arguments ...\n", argv[0], argc);
1695 for (i = 0; i < argc; i++)
1696 fprintf(stderr, "%2d: %s\n", i, argv[i]);
1697 if ((dump = fopen(DEBUG_FILE("pre-html-data"), "wb")) != NULL) {
1698 while((i = fgetc(stdin)) >= 0)
1703 #endif /* CAPTURE_MODE */
1704 postscriptRes = get_resolution();
1705 i = scanArguments(argc, argv);
1710 if (argv[i][0] != '-') {
1711 /* found source file */
1712 ok = do_file(argv[i]);
1722 if (makeTempFiles())
1724 ok = inputFile.do_image(argc, argv);
1726 generateImages(regionFileName);
1727 ok = inputFile.do_html(argc, argv);
1732 static int do_file(const char *filename)
1736 current_filename = filename;
1737 if (strcmp(filename, "-") == 0)
1740 fp = fopen(filename, "r");
1742 error("can't open `%1': %2", filename, strerror(errno));
1747 if (inputFile.read_file(fp)) {
1753 current_filename = NULL;