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"
41 #include <sys/types.h>
47 # include <sys/wait.h>
49 #else /* not _POSIX_VERSION */
51 #endif /* not _POSIX_VERSION */
57 /* Establish some definitions to facilitate discrimination between
58 differing runtime environments. */
60 #undef MAY_FORK_CHILD_PROCESS
61 #undef MAY_SPAWN_ASYNCHRONOUS_CHILD
63 #if defined(__MSDOS__) || defined(_WIN32)
65 // Most MS-DOS and Win32 environments will be missing the `fork' capability
66 // (some like Cygwin have it, but it is best avoided).
68 # define MAY_FORK_CHILD_PROCESS 0
70 // On these systems, we use `spawn...', instead of `fork' ... `exec...'.
71 # include <process.h> // for `spawn...'
72 # include <fcntl.h> // for attributes of pipes
74 # if defined(__CYGWIN__) || defined(_UWIN) || defined(_WIN32)
76 // These Win32 implementations allow parent and `spawn...'ed child to
77 // multitask asynchronously.
79 # define MAY_SPAWN_ASYNCHRONOUS_CHILD 1
83 // Others may adopt MS-DOS behaviour where parent must sleep,
84 // from `spawn...' until child terminates.
86 # define MAY_SPAWN_ASYNCHRONOUS_CHILD 0
88 # endif /* not defined __CYGWIN__, _UWIN, or _WIN32 */
90 # if defined(DEBUGGING) && !defined(DEBUG_FILE_DIR)
91 /* When we are building a DEBUGGING version we need to tell pre-grohtml
92 where to put intermediate files (the DEBUGGING version will preserve
95 On a UNIX host, we might simply use `/tmp', but MS-DOS and Win32 will
96 probably not have this on all disk drives, so default to using
97 `c:/temp' instead. (Note that user may choose to override this by
98 supplying a definition such as
100 -DDEBUG_FILE_DIR=d:/path/to/debug/files
102 in the CPPFLAGS to `make'.) */
104 # define DEBUG_FILE_DIR c:/temp
107 #else /* not __MSDOS__ or _WIN32 */
109 // For non-Microsoft environments assume UNIX conventions,
110 // so `fork' is required and child processes are asynchronous.
111 # define MAY_FORK_CHILD_PROCESS 1
112 # define MAY_SPAWN_ASYNCHRONOUS_CHILD 1
114 # if defined(DEBUGGING) && !defined(DEBUG_FILE_DIR)
115 /* For a DEBUGGING version, on the UNIX host, we can also usually rely
116 on being able to use `/tmp' for temporary file storage. (Note that,
117 as in the __MSDOS__ or _WIN32 case above, the user may override this
120 -DDEBUG_FILE_DIR=/path/to/debug/files
124 # define DEBUG_FILE_DIR /tmp
127 #endif /* not __MSDOS__ or _WIN32 */
130 // For a DEBUGGING version, we need some additional macros,
131 // to direct the captured debug mode output to appropriately named files
132 // in the specified DEBUG_FILE_DIR.
134 # define DEBUG_TEXT(text) #text
135 # define DEBUG_NAME(text) DEBUG_TEXT(text)
136 # define DEBUG_FILE(name) DEBUG_NAME(DEBUG_FILE_DIR) "/" name
139 extern "C" const char *Version_string
;
141 #include "pre-html.h"
142 #include "pushback.h"
143 #include "html-strings.h"
145 #define DEFAULT_LINE_LENGTH 7 // inches wide
146 #define DEFAULT_IMAGE_RES 100 // number of pixels per inch resolution
147 #define IMAGE_BOARDER_PIXELS 0
148 #define INLINE_LEADER_CHAR '\\'
150 // Don't use colour names here! Otherwise there is a dependency on
151 // a file called `rgb.txt' which maps names to colours.
152 #define TRANSPARENT "-background rgb:f/f/f -transparent rgb:f/f/f"
153 #define MIN_ALPHA_BITS 0
154 #define MAX_ALPHA_BITS 4
156 #define PAGE_TEMPLATE_SHORT "pg"
157 #define PAGE_TEMPLATE_LONG "-page-"
158 #define PS_TEMPLATE_SHORT "ps"
159 #define PS_TEMPLATE_LONG "-ps-"
160 #define REGION_TEMPLATE_SHORT "rg"
161 #define REGION_TEMPLATE_LONG "-regions-"
171 # define FALSE (1==0)
175 CENTERED
, LEFT
, RIGHT
, INLINE
178 static int postscriptRes
= -1; // postscript resolution,
180 static int stdoutfd
= 1; // output file descriptor -
181 // normally 1 but might move
183 static char *psFileName
= NULL
; // name of postscript file
184 static char *psPageName
= NULL
; // name of file containing
185 // postscript current page
186 static char *regionFileName
= NULL
; // name of file containing all
188 static char *imagePageName
= NULL
; // name of bitmap image containing
190 static const char *image_device
= "pnmraw";
191 static int image_res
= DEFAULT_IMAGE_RES
;
192 static int vertical_offset
= 0;
193 static char *image_template
= NULL
; // image template filename
194 static char *macroset_template
= NULL
; // image template passed to troff
196 static int troff_arg
= 0; // troff arg index
197 static char *image_dir
= NULL
; // user specified image directory
198 static int textAlphaBits
= MAX_ALPHA_BITS
;
199 static int graphicAlphaBits
= MAX_ALPHA_BITS
;
200 static char *antiAlias
= NULL
; // antialias arguments we pass to gs
201 static int show_progress
= FALSE
; // should we display page numbers as
202 // they are processed?
203 static int currentPageNo
= -1; // current image page number
204 #if defined(DEBUGGING)
205 static int debug
= FALSE
;
206 static char *troffFileName
= NULL
; // output of pre-html output which
207 // is sent to troff -Tps
208 static char *htmlFileName
= NULL
; // output of pre-html output which
209 // is sent to troff -Thtml
212 static char *linebuf
= NULL
; // for scanning devps/DESC
213 static int linebufsize
= 0;
214 static const char *image_gen
= NULL
; // the `gs' program
216 const char *const FONT_ENV_VAR
= "GROFF_FONT_PATH";
217 static search_path
font_path(FONT_ENV_VAR
, FONTPATH
, 0, 0);
221 * Images are generated via postscript, gs, and the pnm utilities.
223 #define IMAGE_DEVICE "-Tps"
226 static int do_file(const char *filename
);
230 * sys_fatal - Write a fatal error message.
231 * Taken from src/roff/groff/pipeline.c.
234 void sys_fatal(const char *s
)
236 fatal("%1: %2", s
, strerror(errno
));
240 * get_line - Copy a line (w/o newline) from a file to the
241 * global line buffer.
244 int get_line(FILE *f
)
249 linebuf
= new char[128];
253 // skip leading whitespace
258 if (c
!= ' ' && c
!= '\t') {
267 if (i
+ 1 >= linebufsize
) {
268 char *old_linebuf
= linebuf
;
269 linebuf
= new char[linebufsize
* 2];
270 memcpy(linebuf
, old_linebuf
, linebufsize
);
271 a_delete old_linebuf
;
285 * get_resolution - Return the postscript resolution from devps/DESC.
288 static unsigned int get_resolution(void)
293 f
= font_path
.open_file("devps/DESC", &pathp
);
296 fatal("can't open devps/DESC");
297 while (get_line(f
)) {
298 int n
= sscanf(linebuf
, "res %u", &res
);
304 fatal("can't find `res' keyword in devps/DESC");
309 * html_system - A wrapper for system().
312 void html_system(const char *s
, int redirect_stdout
)
314 // Redirect standard error to the null device. This is more
315 // portable than using "2> /dev/null", since it doesn't require a
317 int save_stderr
= dup(2);
318 int save_stdout
= dup(1);
319 int fdnull
= open(NULL_DEV
, O_WRONLY
|O_BINARY
, 0666);
320 if (save_stderr
> 2 && fdnull
> 2)
322 if (redirect_stdout
&& save_stdout
> 1 && fdnull
> 1)
326 int status
= system(s
);
327 dup2(save_stderr
, 2);
329 dup2(save_stdout
, 1);
331 fprintf(stderr
, "Calling `%s' failed\n", s
);
333 fprintf(stderr
, "Calling `%s' returned status %d\n", s
, status
);
339 * make_message - Create a string via malloc and place the result of the
340 * va args into string. Finally the new string is returned.
341 * Taken from man page of printf(3).
344 char *make_message(const char *fmt
, ...)
346 /* Guess we need no more than 100 bytes. */
351 if ((p
= (char *)malloc(size
)) == NULL
)
354 /* Try to print in the allocated space. */
356 n
= vsnprintf(p
, size
, fmt
, ap
);
358 /* If that worked, return the string. */
359 if (n
> -1 && n
< size
- 1) { /* glibc 2.1 and pre-ANSI C 99 */
367 /* Else try again with more space. */
369 size
*= 2; /* twice the old size */
370 if ((np
= (char *)realloc(p
, size
)) == NULL
) {
371 free(p
); /* realloc failed, free old, p. */
374 p
= np
; /* use realloc'ed, p */
379 * the class and methods for retaining ascii text
392 * char_block - Constructor. Set the, used, and, next, fields to zero.
395 char_block::char_block()
398 for (int i
= 0; i
< SIZE
; i
++)
406 int read_file(FILE *fp
);
407 int do_html(int argc
, char *argv
[]);
408 int do_image(int argc
, char *argv
[]);
409 void emit_troff_output(int device_format_selector
);
410 void write_upto_newline(char_block
**t
, int *i
, int is_html
);
411 int can_see(char_block
**t
, int *i
, const char *string
);
412 int skip_spaces(char_block
**t
, int *i
);
413 void skip_until_newline(char_block
**t
, int *i
);
417 int run_output_filter(int device_format_selector
, int argc
, char *argv
[]);
421 * char_buffer - Constructor.
424 char_buffer::char_buffer()
430 * char_buffer - Destructor. Throw away the whole buffer list.
433 char_buffer::~char_buffer()
435 while (head
!= NULL
) {
436 char_block
*temp
= head
;
443 * read_file - Read in a complete file, fp, placing the contents inside
447 int char_buffer::read_file(FILE *fp
)
452 tail
= new char_block
;
456 if (tail
->used
== char_block::SIZE
) {
457 tail
->next
= new char_block
;
461 // at this point we have a tail which is ready for the next SIZE
463 n
= fread(tail
->buffer
, sizeof(char), char_block::SIZE
-tail
->used
, fp
);
468 tail
->used
+= n
* sizeof(char);
474 * writeNbytes - Write n bytes to stdout.
477 static void writeNbytes(const char *s
, int l
)
483 r
= write(stdoutfd
, s
, l
- n
);
492 * writeString - Write a string to stdout.
495 static void writeString(const char *s
)
497 writeNbytes(s
, strlen(s
));
501 * makeFileName - Create the image filename template
502 * and the macroset image template.
505 static void makeFileName(void)
507 if ((image_dir
!= NULL
) && (strchr(image_dir
, '%') != NULL
)) {
508 error("cannot use a `%%' within the image directory name");
512 if ((image_template
!= NULL
) && (strchr(image_template
, '%') != NULL
)) {
513 error("cannot use a `%%' within the image template");
517 if (image_dir
== NULL
)
518 image_dir
= (char *)"";
519 else if (strlen(image_dir
) > 0
520 && image_dir
[strlen(image_dir
) - 1] != '/') {
521 image_dir
= make_message("%s/", image_dir
);
522 if (image_dir
== NULL
)
523 sys_fatal("make_message");
526 if (image_template
== NULL
)
527 macroset_template
= make_message("%sgrohtml-%d", image_dir
,
530 macroset_template
= make_message("%s%s", image_dir
, image_template
);
532 if (macroset_template
== NULL
)
533 sys_fatal("make_message");
536 (char *)malloc(strlen("-%d") + strlen(macroset_template
) + 1);
537 if (image_template
== NULL
)
539 strcpy(image_template
, macroset_template
);
540 strcat(image_template
, "-%d");
544 * setupAntiAlias - Set up the antialias string, used when we call gs.
547 static void setupAntiAlias(void)
549 if (textAlphaBits
== 0 && graphicAlphaBits
== 0)
550 antiAlias
= make_message(" ");
551 else if (textAlphaBits
== 0)
552 antiAlias
= make_message("-dGraphicsAlphaBits=%d ", graphicAlphaBits
);
553 else if (graphicAlphaBits
== 0)
554 antiAlias
= make_message("-dTextAlphaBits=%d ", textAlphaBits
);
556 antiAlias
= make_message("-dTextAlphaBits=%d -dGraphicsAlphaBits=%d ",
557 textAlphaBits
, graphicAlphaBits
);
561 * checkImageDir - Check whether the image directory is available.
564 static void checkImageDir(void)
566 if (image_dir
!= NULL
&& strcmp(image_dir
, "") != 0)
567 if (!(mkdir(image_dir
, 0777) == 0 || errno
== EEXIST
)) {
568 error("cannot create directory `%1'", image_dir
);
574 * write_end_image - End the image. Write out the image extents if we
578 static void write_end_image(int is_html
)
581 * if we are producing html then these
582 * emit image name and enable output
584 * we are producing images
585 * in which case these generate image
588 writeString("\\O[4]\\O[2]");
590 writeString("\\O[1]");
592 writeString("\\O[0]");
596 * write_start_image - Write troff code which will:
598 * (i) disable html output for the following image
599 * (ii) reset the max/min x/y registers during postscript
603 static void write_start_image(IMAGE_ALIGNMENT pos
, int is_html
)
605 writeString("\\O[5");
621 writeString(image_template
);
622 writeString(".png]");
624 writeString("\\O[0]\\O[3]");
626 // reset min/max registers
627 writeString("\\O[1]\\O[3]");
631 * write_upto_newline - Write the contents of the buffer until a newline
632 * is seen. Check for HTML_IMAGE_INLINE_BEGIN and
633 * HTML_IMAGE_INLINE_END; process them if they are
637 void char_buffer::write_upto_newline(char_block
**t
, int *i
, int is_html
)
642 while (j
< (*t
)->used
643 && (*t
)->buffer
[j
] != '\n'
644 && (*t
)->buffer
[j
] != INLINE_LEADER_CHAR
)
647 && (*t
)->buffer
[j
] == '\n')
649 writeNbytes((*t
)->buffer
+ (*i
), j
- (*i
));
650 if ((*t
)->buffer
[j
] == INLINE_LEADER_CHAR
) {
651 if (can_see(t
, &j
, HTML_IMAGE_INLINE_BEGIN
))
652 write_start_image(INLINE
, is_html
);
653 else if (can_see(t
, &j
, HTML_IMAGE_INLINE_END
))
654 write_end_image(is_html
);
656 if (j
< (*t
)->used
) {
659 writeNbytes((*t
)->buffer
+ (*i
), j
- (*i
));
663 if (j
== (*t
)->used
) {
666 if (*t
&& (*t
)->buffer
[j
- 1] != '\n')
667 write_upto_newline(t
, i
, is_html
);
676 * can_see - Return TRUE if we can see string in t->buffer[i] onwards.
679 int char_buffer::can_see(char_block
**t
, int *i
, const char *str
)
687 while (k
< s
->used
&& j
< l
&& s
->buffer
[k
] == str
[j
]) {
696 else if (k
< s
->used
&& s
->buffer
[k
] != str
[j
])
705 * skip_spaces - Return TRUE if we have not run out of data.
706 * Consume spaces also.
709 int char_buffer::skip_spaces(char_block
**t
, int *i
)
715 while (k
< s
->used
&& isspace(s
->buffer
[k
]))
730 * skip_until_newline - Skip all characters until a newline is seen.
731 * The newline is not consumed.
734 void char_buffer::skip_until_newline(char_block
**t
, int *i
)
739 while (j
< (*t
)->used
&& (*t
)->buffer
[j
] != '\n')
741 if (j
== (*t
)->used
) {
744 skip_until_newline(t
, i
);
752 #define DEVICE_FORMAT(filter) (filter == HTML_OUTPUT_FILTER)
753 #define HTML_OUTPUT_FILTER 0
754 #define IMAGE_OUTPUT_FILTER 1
755 #define OUTPUT_STREAM(name) creat((name), S_IWUSR | S_IRUSR)
756 #define PS_OUTPUT_STREAM OUTPUT_STREAM(psFileName)
757 #define REGION_OUTPUT_STREAM OUTPUT_STREAM(regionFileName)
760 * emit_troff_output - Write formatted buffer content to the troff
761 * post-processor data pipeline.
764 void char_buffer::emit_troff_output(int device_format_selector
)
766 // Handle output for BOTH html and image device formats
767 // if `device_format_selector' is passed as
769 // HTML_FORMAT(HTML_OUTPUT_FILTER)
770 // Buffer data is written to the output stream
771 // with template image names translated to actual image names.
773 // HTML_FORMAT(IMAGE_OUTPUT_FILTER)
774 // Buffer data is written to the output stream
775 // with no translation, for image file creation in the post-processor.
778 char_block
*element
= head
;
780 while (element
!= NULL
)
781 write_upto_newline(&element
, &idx
, device_format_selector
);
784 if (close(stdoutfd
) < 0)
787 // now we grab fd=1 so that the next pipe cannot use fd=1
789 if (dup(2) != stdoutfd
)
790 sys_fatal ("dup failed to use fd=1");
796 * The image class remembers the position of all images in the
797 * postscript file and assigns names for each image.
811 imageItem(int x1
, int y1
, int x2
, int y2
,
812 int page
, int res
, int max_width
, char *name
);
817 * imageItem - Constructor.
820 imageItem::imageItem(int x1
, int y1
, int x2
, int y2
,
821 int page
, int res
, int max_width
, char *name
)
835 * imageItem - Destructor.
838 imageItem::~imageItem()
845 * imageList - A class containing a list of imageItems.
856 void add(int x1
, int y1
, int x2
, int y2
,
857 int page
, int res
, int maxx
, char *name
);
858 void createImages(void);
859 int createPage(int pageno
);
860 void createImage(imageItem
*i
);
861 int getMaxX(int pageno
);
865 * imageList - Constructor.
868 imageList::imageList()
869 : head(0), tail(0), count(0)
874 * imageList - Destructor.
877 imageList::~imageList()
879 while (head
!= NULL
) {
887 * createPage - Create one image of, page pageno, from the postscript file.
890 int imageList::createPage(int pageno
)
894 if (currentPageNo
== pageno
)
897 if (currentPageNo
>= 1) {
899 * We need to unlink the files which change each time a new page is
900 * processed. The final unlink is done by xtmpfile when pre-grohtml
903 unlink(imagePageName
);
908 fprintf(stderr
, "[%d] ", pageno
);
912 #if defined(DEBUGGING)
914 fprintf(stderr
, "creating page %d\n", pageno
);
917 s
= make_message("psselect -q -p%d %s %s\n",
918 pageno
, psFileName
, psPageName
);
921 sys_fatal("make_message");
922 #if defined(DEBUGGING)
924 fwrite(s
, sizeof(char), strlen(s
), stderr
);
930 s
= make_message("echo showpage | "
931 "%s%s -q -dBATCH -dSAFER "
932 "-dDEVICEHEIGHTPOINTS=792 "
933 "-dDEVICEWIDTHPOINTS=%d -dFIXEDMEDIA=true "
934 "-sDEVICE=%s -r%d %s "
935 "-sOutputFile=%s %s -\n",
938 (getMaxX(pageno
) * image_res
) / postscriptRes
,
945 sys_fatal("make_message");
946 #if defined(DEBUGGING)
948 fwrite(s
, sizeof(char), strlen(s
), stderr
);
954 currentPageNo
= pageno
;
959 * min - Return the minimum of two numbers.
962 int min(int x
, int y
)
971 * max - Return the maximum of two numbers.
974 int max(int x
, int y
)
983 * getMaxX - Return the largest right-hand position for any image
987 int imageList::getMaxX(int pageno
)
990 int x
= postscriptRes
* DEFAULT_LINE_LENGTH
;
993 if (h
->pageNo
== pageno
)
1001 * createImage - Generate a minimal png file from the set of page images.
1004 void imageList::createImage(imageItem
*i
)
1008 int x1
= max(min(i
->X1
, i
->X2
) * image_res
/ postscriptRes
1009 - IMAGE_BOARDER_PIXELS
,
1011 int y1
= max(image_res
* vertical_offset
/ 72
1012 + min(i
->Y1
, i
->Y2
) * image_res
/ postscriptRes
1013 - IMAGE_BOARDER_PIXELS
,
1015 int x2
= max(i
->X1
, i
->X2
) * image_res
/ postscriptRes
1016 + IMAGE_BOARDER_PIXELS
;
1017 int y2
= image_res
* vertical_offset
/ 72
1018 + max(i
->Y1
, i
->Y2
) * image_res
/ postscriptRes
1019 + 1 + IMAGE_BOARDER_PIXELS
;
1020 if (createPage(i
->pageNo
) == 0) {
1021 s
= make_message("pnmcut%s %d %d %d %d < %s "
1022 "| pnmcrop -quiet | pnmtopng%s %s > %s\n",
1024 x1
, y1
, x2
- x1
+ 1, y2
- y1
+ 1,
1030 sys_fatal("make_message");
1032 #if defined(DEBUGGING)
1042 fprintf(stderr
, "failed to generate image of page %d\n", i
->pageNo
);
1045 #if defined(DEBUGGING)
1049 fprintf(stderr
, "ignoring image as x1 coord is -1\n");
1057 * add - Add an image description to the imageList.
1060 void imageList::add(int x1
, int y1
, int x2
, int y2
,
1061 int page
, int res
, int maxx
, char *name
)
1063 imageItem
*i
= new imageItem(x1
, y1
, x2
, y2
, page
, res
, maxx
, name
);
1076 * createImages - For each image descriptor on the imageList,
1077 * create the actual image.
1080 void imageList::createImages(void)
1082 imageItem
*h
= head
;
1090 static imageList listOfImages
; // List of images defined by the region file.
1093 * generateImages - Parse the region file and generate images
1094 * from the postscript file. The region file
1095 * contains the x1,y1--x2,y2 extents of each
1099 static void generateImages(char *region_file_name
)
1101 pushBackBuffer
*f
=new pushBackBuffer(region_file_name
);
1103 while (f
->putPB(f
->getPB()) != eof
) {
1104 if (f
->isString("grohtml-info:page")) {
1105 int page
= f
->readInt();
1106 int x1
= f
->readInt();
1107 int y1
= f
->readInt();
1108 int x2
= f
->readInt();
1109 int y2
= f
->readInt();
1110 int maxx
= f
->readInt();
1111 char *name
= f
->readString();
1112 int res
= postscriptRes
;
1113 listOfImages
.add(x1
, y1
, x2
, y2
, page
, res
, maxx
, name
);
1114 while (f
->putPB(f
->getPB()) != '\n'
1115 && f
->putPB(f
->getPB()) != eof
)
1117 if (f
->putPB(f
->getPB()) == '\n')
1121 /* Write any error messages out to the user. */
1122 fputc(f
->getPB(), stderr
);
1126 listOfImages
.createImages();
1127 if (show_progress
) {
1128 fprintf(stderr
, "done\n");
1135 * set_redirection - Set up I/O Redirection for handle, was, to refer to
1136 * stream on handle, willbe.
1139 static void set_redirection(int was
, int willbe
)
1141 // Nothing to do if `was' and `willbe' already have same handle.
1142 if (was
!= willbe
) {
1143 // Otherwise attempt the specified redirection.
1144 if (dup2 (willbe
, was
) < 0) {
1145 // Redirection failed, so issue diagnostic and bail out.
1146 fprintf(stderr
, "failed to replace fd=%d with %d\n", was
, willbe
);
1147 if (willbe
== STDOUT_FILENO
)
1149 "likely that stdout should be opened before %d\n", was
);
1153 // When redirection has been successfully completed assume redundant
1154 // handle `willbe' is no longer required, so close it.
1155 if (close(willbe
) < 0)
1156 // Issue diagnostic if `close' fails.
1162 * save_and_redirect - Get duplicate handle for stream, was, then
1163 * redirect, was, to refer to, willbe.
1166 static int save_and_redirect(int was
, int willbe
)
1169 // No redirection specified so don't do anything but silently bailing out.
1172 // Proceeding with redirection so first save and verify our duplicate
1173 // handle for `was'.
1174 int saved
= dup(was
);
1176 fprintf(stderr
, "unable to get duplicate handle for %d\n", was
);
1180 // Duplicate handle safely established so complete redirection.
1181 set_redirection(was
, willbe
);
1183 // Finally return the saved duplicate descriptor for the
1184 // original `was' stream.
1189 * alterDeviceTo - If, toImage, is set
1190 * the argument list is altered to include
1191 * IMAGE_DEVICE and we invoke groff rather than troff.
1193 * set -Thtml and groff.
1196 static void alterDeviceTo(int argc
, char *argv
[], int toImage
)
1202 if (strcmp(argv
[i
], "-Thtml") == 0)
1203 argv
[i
] = (char *)IMAGE_DEVICE
;
1206 argv
[troff_arg
] = (char *)"groff"; /* rather than troff */
1210 if (strcmp(argv
[i
], IMAGE_DEVICE
) == 0)
1211 argv
[i
] = (char *)"-Thtml";
1214 argv
[troff_arg
] = (char *)"groff"; /* use groff -Z */
1219 * addZ - Append -Z onto the command list for groff.
1222 char **addZ(int argc
, char *argv
[])
1224 char **new_argv
= (char **)malloc((argc
+ 2) * sizeof(char *));
1227 if (new_argv
== NULL
)
1228 sys_fatal("malloc");
1231 new_argv
[i
] = argv
[i
];
1234 new_argv
[i
] = (char *)"-Z";
1236 new_argv
[i
+ 1] = argv
[i
];
1240 new_argv
[argc
] = NULL
;
1245 * addRegDef - Append a defined register or string onto the command
1249 char **addRegDef(int argc
, char *argv
[], const char *numReg
)
1251 char **new_argv
= (char **)malloc((argc
+ 2) * sizeof(char *));
1254 if (new_argv
== NULL
)
1255 sys_fatal("malloc");
1258 new_argv
[i
] = argv
[i
];
1261 new_argv
[argc
] = strsave(numReg
);
1263 new_argv
[argc
] = NULL
;
1268 * dump_args - Display the argument list.
1271 void dump_args(int argc
, char *argv
[])
1273 fprintf(stderr
, " %d arguments:", argc
);
1274 for (int i
= 0; i
< argc
; i
++)
1275 fprintf(stderr
, " %s", argv
[i
]);
1276 fprintf(stderr
, "\n");
1279 int char_buffer::run_output_filter(int filter
, int /* argc */, char **argv
)
1285 if (pipe(pipedes
) < 0)
1288 #if MAY_FORK_CHILD_PROCESS
1289 // This is the UNIX process model. To invoke our post-processor,
1290 // we must `fork' the current process.
1292 if ((child_pid
= fork()) < 0)
1295 else if (child_pid
== 0) {
1296 // This is the child process fork. We redirect its `stdin' stream
1297 // to read data emerging from our pipe. There is no point in saving,
1298 // since we won't be able to restore later!
1300 set_redirection(STDIN_FILENO
, pipedes
[0]);
1302 // The parent process will be writing this data, so we should release
1303 // the child's writeable handle on the pipe, since we have no use for it.
1305 if (close(pipedes
[1]) < 0)
1308 // The IMAGE_OUTPUT_FILTER needs special output redirection...
1310 if (filter
== IMAGE_OUTPUT_FILTER
) {
1311 // with BOTH `stdout' AND `stderr' diverted to files.
1313 set_redirection(STDOUT_FILENO
, PS_OUTPUT_STREAM
);
1314 set_redirection(STDERR_FILENO
, REGION_OUTPUT_STREAM
);
1317 // Now we are ready to launch the output filter.
1319 execvp(argv
[0], argv
);
1321 // If we get to here then the `exec...' request for the output filter
1322 // failed. Diagnose it and bail out.
1324 error("couldn't exec %1: %2", argv
[0], strerror(errno
), ((char *)0));
1325 fflush(stderr
); // just in case error() didn't
1330 // This is the parent process fork. We will be writing data to the
1331 // filter pipeline, and the child will be reading it. We have no further
1332 // use for our read handle on the pipe, and should close it.
1334 if (close(pipedes
[0]) < 0)
1337 // Now we redirect the `stdout' stream to the inlet end of the pipe,
1338 // and push out the appropiately formatted data to the filter.
1340 pipedes
[1] = save_and_redirect(STDOUT_FILENO
, pipedes
[1]);
1341 emit_troff_output(DEVICE_FORMAT(filter
));
1343 // After emitting all the data we close our connection to the inlet
1344 // end of the pipe so the child process will detect end of data.
1346 set_redirection(STDOUT_FILENO
, pipedes
[1]);
1348 // Finally, we must wait for the child process to complete.
1350 if (WAIT(&status
, child_pid
, _WAIT_CHILD
) != child_pid
)
1354 #elif MAY_SPAWN_ASYNCHRONOUS_CHILD
1356 // We do not have `fork', (or we prefer not to use it),
1357 // but asynchronous processes are allowed, passing data through pipes.
1358 // This should be ok for most Win32 systems and is preferred to `fork'
1359 // for starting child processes under Cygwin.
1361 // Before we start the post-processor we bind its inherited `stdin'
1362 // stream to the readable end of our pipe, saving our own `stdin' stream
1365 pipedes
[0] = save_and_redirect(STDIN_FILENO
, pipedes
[0]);
1367 // for the Win32 model,
1368 // we need special provision for saving BOTH `stdout' and `stderr'.
1370 int saved_stdout
= dup(STDOUT_FILENO
);
1371 int saved_stderr
= STDERR_FILENO
;
1373 // The IMAGE_OUTPUT_FILTER needs special output redirection...
1375 if (filter
== IMAGE_OUTPUT_FILTER
) {
1376 // with BOTH `stdout' AND `stderr' diverted to files while saving a
1377 // duplicate handle for `stderr'.
1379 set_redirection(STDOUT_FILENO
, PS_OUTPUT_STREAM
);
1380 saved_stderr
= save_and_redirect(STDERR_FILENO
, REGION_OUTPUT_STREAM
);
1383 // We then use an asynchronous spawn request to start the post-processor.
1385 if ((child_pid
= spawnvp(_P_NOWAIT
, argv
[0], argv
)) < 0) {
1386 // Should the spawn request fail we issue a diagnostic and bail out.
1388 error("cannot spawn %1: %2", argv
[0], strerror(errno
), ((char *)0));
1392 // Once the post-processor has been started we revert our `stdin'
1393 // to its original saved source, which also closes the readable handle
1396 set_redirection(STDIN_FILENO
, pipedes
[0]);
1398 // if we redirected `stderr', for use by the image post-processor,
1399 // then we also need to reinstate its original assignment.
1401 if (filter
== IMAGE_OUTPUT_FILTER
)
1402 set_redirection(STDERR_FILENO
, saved_stderr
);
1404 // Now we redirect the `stdout' stream to the inlet end of the pipe,
1405 // and push out the appropiately formatted data to the filter.
1407 set_redirection(STDOUT_FILENO
, pipedes
[1]);
1408 emit_troff_output(DEVICE_FORMAT(filter
));
1410 // After emitting all the data we close our connection to the inlet
1411 // end of the pipe so the child process will detect end of data.
1413 set_redirection(STDOUT_FILENO
, saved_stdout
);
1415 // And finally, we must wait for the child process to complete.
1417 if (WAIT(&status
, child_pid
, _WAIT_CHILD
) != child_pid
)
1420 #else /* can't do asynchronous pipes! */
1422 // TODO: code to support an MS-DOS style process model
1425 #endif /* MAY_FORK_CHILD_PROCESS or MAY_SPAWN_ASYNCHRONOUS_CHILD */
1431 * do_html - Set the troff number htmlflip and
1432 * write out the buffer to troff -Thtml.
1435 int char_buffer::do_html(int argc
, char *argv
[])
1439 alterDeviceTo(argc
, argv
, 0);
1440 argv
+= troff_arg
; // skip all arguments up to groff
1442 argv
= addZ(argc
, argv
);
1445 s
= "-dwww-image-template=";
1446 s
+= macroset_template
; // do not combine these statements,
1447 // otherwise they will not work
1448 s
+= '\0'; // the trailing `\0' is ignored
1449 argv
= addRegDef(argc
, argv
, s
.contents());
1452 #if defined(DEBUGGING)
1453 # define HTML_DEBUG_STREAM OUTPUT_STREAM(htmlFileName)
1454 // slight security risk so only enabled if compiled with defined(DEBUGGING)
1456 int saved_stdout
= save_and_redirect(STDOUT_FILENO
, HTML_DEBUG_STREAM
);
1457 emit_troff_output(DEVICE_FORMAT(HTML_OUTPUT_FILTER
));
1458 set_redirection(STDOUT_FILENO
, saved_stdout
);
1462 return run_output_filter(HTML_OUTPUT_FILTER
, argc
, argv
);
1466 * do_image - Write out the buffer to troff -Tps.
1469 int char_buffer::do_image(int argc
, char *argv
[])
1473 alterDeviceTo(argc
, argv
, 1);
1474 argv
+= troff_arg
; // skip all arguments up to troff/groff
1476 argv
= addRegDef(argc
, argv
, "-rps4html=1");
1479 s
= "-dwww-image-template=";
1480 s
+= macroset_template
;
1482 argv
= addRegDef(argc
, argv
, s
.contents());
1485 // override local settings and produce a page size letter postscript file
1486 argv
= addRegDef(argc
, argv
, "-P-pletter");
1489 #if defined(DEBUGGING)
1490 # define IMAGE_DEBUG_STREAM OUTPUT_STREAM(troffFileName)
1491 // slight security risk so only enabled if compiled with defined(DEBUGGING)
1493 int saved_stdout
= save_and_redirect(STDOUT_FILENO
, IMAGE_DEBUG_STREAM
);
1494 emit_troff_output(DEVICE_FORMAT(IMAGE_OUTPUT_FILTER
));
1495 set_redirection(STDOUT_FILENO
, saved_stdout
);
1499 return run_output_filter(IMAGE_OUTPUT_FILTER
, argc
, argv
);
1502 static char_buffer inputFile
;
1505 * usage - Emit usage arguments.
1508 static void usage(FILE *stream
)
1511 "usage: %s troffname [-Iimage_name] [-Dimage_directory]\n"
1512 " [-P-o vertical_image_offset] [-P-i image_resolution]\n"
1516 " vertical_image_offset (default %d/72 of an inch)\n",
1519 " image_resolution (default %d) pixels per inch\n",
1522 " image_name is the name of the stem for all images\n"
1523 " (default is grohtml-<pid>)\n");
1525 " place all png files into image_directory\n");
1529 * scanArguments - Scan for all arguments including -P-i, -P-o, -P-D,
1530 * and -P-I. Return the argument index of the first
1534 static int scanArguments(int argc
, char **argv
)
1536 const char *command_prefix
= getenv("GROFF_COMMAND_PREFIX");
1537 if (!command_prefix
)
1538 command_prefix
= PROG_PREFIX
;
1539 char *troff_name
= new char[strlen(command_prefix
) + strlen("troff") + 1];
1540 strcpy(troff_name
, command_prefix
);
1541 strcat(troff_name
, "troff");
1543 static const struct option long_options
[] = {
1544 { "help", no_argument
, 0, CHAR_MAX
+ 1 },
1545 { "version", no_argument
, 0, 'v' },
1548 while ((c
= getopt_long(argc
, argv
, "+a:bdD:F:g:hi:I:j:lno:prs:S:v",
1549 long_options
, NULL
))
1553 textAlphaBits
= min(max(MIN_ALPHA_BITS
, atoi(optarg
)),
1555 if (textAlphaBits
== 3) {
1556 error("cannot use 3 bits of antialiasing information");
1561 // handled by post-grohtml (set background color to white)
1564 #if defined(DEBUGGING)
1572 font_path
.command_line_dir(optarg
);
1575 graphicAlphaBits
= min(max(MIN_ALPHA_BITS
, atoi(optarg
)),
1577 if (graphicAlphaBits
== 3) {
1578 error("cannot use 3 bits of antialiasing information");
1583 // handled by post-grohtml
1586 image_res
= atoi(optarg
);
1589 image_template
= optarg
;
1592 // handled by post-grohtml (set job name for multiple file output)
1595 // handled by post-grohtml (no automatic section links)
1598 // handled by post-grohtml (generate simple heading anchors)
1601 vertical_offset
= atoi(optarg
);
1604 show_progress
= TRUE
;
1607 // handled by post-grohtml (no header and footer lines)
1610 // handled by post-grohtml (use font size n as the html base font size)
1613 // handled by post-grohtml (set file split level)
1616 printf("GNU pre-grohtml (groff) version %s\n", Version_string
);
1618 case CHAR_MAX
+ 1: // --help
1632 if (strcmp(argv
[i
], troff_name
) == 0)
1634 else if (argv
[i
][0] != '-')
1638 a_delete troff_name
;
1644 * makeTempFiles - Name the temporary files.
1647 static int makeTempFiles(void)
1649 #if defined(DEBUGGING)
1650 psFileName
= DEBUG_FILE("prehtml-ps");
1651 regionFileName
= DEBUG_FILE("prehtml-region");
1652 imagePageName
= DEBUG_FILE("prehtml-page");
1653 psPageName
= DEBUG_FILE("prehtml-psn");
1654 troffFileName
= DEBUG_FILE("prehtml-troff");
1655 htmlFileName
= DEBUG_FILE("prehtml-html");
1656 #else /* not DEBUGGING */
1659 /* psPageName contains a single page of postscript */
1660 f
= xtmpfile(&psPageName
,
1661 PS_TEMPLATE_LONG
, PS_TEMPLATE_SHORT
,
1664 sys_fatal("xtmpfile");
1669 /* imagePageName contains a bitmap image of the single postscript page */
1670 f
= xtmpfile(&imagePageName
,
1671 PAGE_TEMPLATE_LONG
, PAGE_TEMPLATE_SHORT
,
1674 sys_fatal("xtmpfile");
1679 /* psFileName contains a postscript file of the complete document */
1680 f
= xtmpfile(&psFileName
,
1681 PS_TEMPLATE_LONG
, PS_TEMPLATE_SHORT
,
1684 sys_fatal("xtmpfile");
1689 /* regionFileName contains a list of the images and their boxed coordinates */
1690 f
= xtmpfile(®ionFileName
,
1691 REGION_TEMPLATE_LONG
, REGION_TEMPLATE_SHORT
,
1694 sys_fatal("xtmpfile");
1699 #endif /* not DEBUGGING */
1703 int main(int argc
, char **argv
)
1705 program_name
= argv
[0];
1712 fprintf(stderr
, "%s: invoked with %d arguments ...\n", argv
[0], argc
);
1713 for (i
= 0; i
< argc
; i
++)
1714 fprintf(stderr
, "%2d: %s\n", i
, argv
[i
]);
1715 if ((dump
= fopen(DEBUG_FILE("pre-html-data"), "wb")) != NULL
) {
1716 while((i
= fgetc(stdin
)) >= 0)
1721 #endif /* CAPTURE_MODE */
1723 if (!font::load_desc())
1724 fatal("cannot find devhtml/DESC exiting");
1725 image_gen
= font::image_generator
;
1726 if (image_gen
== NULL
|| (strcmp(image_gen
, "") == 0))
1727 fatal("devhtml/DESC must set the image_generator field, exiting");
1728 postscriptRes
= get_resolution();
1729 i
= scanArguments(argc
, argv
);
1734 if (argv
[i
][0] != '-') {
1735 /* found source file */
1736 ok
= do_file(argv
[i
]);
1746 if (makeTempFiles())
1748 ok
= inputFile
.do_image(argc
, argv
);
1750 generateImages(regionFileName
);
1751 ok
= inputFile
.do_html(argc
, argv
);
1756 static int do_file(const char *filename
)
1760 current_filename
= filename
;
1761 if (strcmp(filename
, "-") == 0)
1764 fp
= fopen(filename
, "r");
1766 error("can't open `%1': %2", filename
, strerror(errno
));
1771 if (inputFile
.read_file(fp
)) {
1777 current_filename
= NULL
;