Debian Codegraph @

converter/other/pstopnm.c

raw
1 /*----------------------------------------------------------------------------
2 pstopnm
3 ------------------------------------------------------------------------------
4 Use Ghostscript to convert a Postscript file into a PBM, PGM, or PNM
5 file.
6
7 Implementation note: This program feeds the input file to Ghostcript
8 directly (with possible statements preceding it), and uses
9 Ghostscript's PNM output device drivers. As an alternative,
10 Ghostscript also comes with the Postscript program pstoppm.ps which
11 we could run and it would read the input file and produce PNM
12 output. It isn't clear to me what pstoppm.ps adds to what you get
13 from just feeding your input directly to Ghostscript as the main program.
14
15 -----------------------------------------------------------------------------*/
16
17 #define _DEFAULT_SOURCE 1 /* New name for SVID & BSD source defines */
18 #define _BSD_SOURCE 1 /* Make sure strdup() is in string.h */
19 #define _XOPEN_SOURCE 500
20 /* Make sure fdopen() is in stdio.h and strdup() is in string.h */
21
22 #include <assert.h>
23 #include <string.h>
24 #include <unistd.h>
25 #include <stdlib.h>
26 #include <stdio.h>
27 #include <signal.h>
28 #include <sys/wait.h>
29 #include <sys/stat.h>
30
31 #include "pm_c_util.h"
32 #include "mallocvar.h"
33 #include "pnm.h"
34 #include "shhopt.h"
35 #include "nstring.h"
36
37 static bool verbose;
38
39 enum Orientation {PORTRAIT, LANDSCAPE, UNSPECIFIED};
40 struct Box {
41 /* Description of a rectangle within an image; all coordinates
42 measured in points (1/72") with lower left corner of page being the
43 origin. Negative values are OK.
44 */
45 bool isDefined;
46
47 /* Nothing below is meaningful unless 'isDefined' is true */
48 int llx; /* lower left X coord */
49 int lly; /* lower left Y coord */
50 int urx; /* upper right X coord */
51 int ury; /* upper right Y coord */
52 };
53
54
55
56 static void
57 assertValidBox(struct Box const box) {
58
59 if (box.isDefined) {
60 assert(box.urx >= box.llx);
61 assert(box.ury >= box.lly);
62 }
63 }
64
65
66
67 struct Dimensions {
68 /*----------------------------------------------------------------------------
69 Horizontal and vertical dimensions of something, both in pixels and
70 spatial distance (points).
71
72 Sizes are in pixels. Resolutions are in dots per inch (pixels per inch);
73 -----------------------------------------------------------------------------*/
74 unsigned int xsize;
75 unsigned int ysize;
76 unsigned int xres;
77 unsigned int yres;
78 };
79
80 struct CmdlineInfo {
81 /* All the information the user supplied in the command line,
82 in a form easy for the program to use.
83 */
84 const char * inputFileName; /* Names of input files */
85 unsigned int forceplain;
86 struct Box extractBox;
87 unsigned int nocrop;
88 unsigned int formatType;
89 unsigned int verbose;
90 float xborder;
91 unsigned int xmax;
92 unsigned int xsize; /* zero means unspecified */
93 float yborder;
94 unsigned int ymax;
95 unsigned int ysize; /* zero means unspecified */
96 unsigned int dpi; /* zero means unspecified */
97 enum Orientation orientation;
98 unsigned int stdoutSpec;
99 unsigned int textalphabits;
100 };
101
102
103 static void
104 parseCommandLine(int argc, char ** argv,
105 struct CmdlineInfo * const cmdlineP) {
106 /*----------------------------------------------------------------------------
107 Note that the file spec array we return is stored in the storage that
108 was passed to us as the argv array.
109 -----------------------------------------------------------------------------*/
110 optEntry * option_def;
111 /* Instructions to pm_optParseOptions3 on how to parse our options.
112 */
113 optStruct3 opt;
114
115 unsigned int option_def_index;
116
117 unsigned int pbmOpt, pgmOpt, ppmOpt;
118 unsigned int portraitOpt, landscapeOpt;
119 float llx, lly, urx, ury;
120 unsigned int llxSpec, llySpec, urxSpec, urySpec;
121 unsigned int xmaxSpec, ymaxSpec, xsizeSpec, ysizeSpec, dpiSpec;
122 unsigned int textalphabitsSpec;
123
124 MALLOCARRAY_NOFAIL(option_def, 100);
125
126 option_def_index = 0; /* incremented by OPTENTRY */
127 OPTENT3(0, "forceplain", OPT_FLAG, NULL, &cmdlineP->forceplain, 0);
128 OPTENT3(0, "llx", OPT_FLOAT, &llx, &llxSpec, 0);
129 OPTENT3(0, "lly", OPT_FLOAT, &lly, &llySpec, 0);
130 OPTENT3(0, "urx", OPT_FLOAT, &urx, &urxSpec, 0);
131 OPTENT3(0, "ury", OPT_FLOAT, &ury, &urySpec, 0);
132 OPTENT3(0, "nocrop", OPT_FLAG, NULL, &cmdlineP->nocrop, 0);
133 OPTENT3(0, "pbm", OPT_FLAG, NULL, &pbmOpt , 0);
134 OPTENT3(0, "pgm", OPT_FLAG, NULL, &pgmOpt, 0);
135 OPTENT3(0, "ppm", OPT_FLAG, NULL, &ppmOpt, 0);
136 OPTENT3(0, "verbose", OPT_FLAG, NULL, &cmdlineP->verbose, 0);
137 OPTENT3(0, "xborder", OPT_FLOAT, &cmdlineP->xborder, NULL, 0);
138 OPTENT3(0, "xmax", OPT_UINT, &cmdlineP->xmax, &xmaxSpec, 0);
139 OPTENT3(0, "xsize", OPT_UINT, &cmdlineP->xsize, &xsizeSpec, 0);
140 OPTENT3(0, "yborder", OPT_FLOAT, &cmdlineP->yborder, NULL, 0);
141 OPTENT3(0, "ymax", OPT_UINT, &cmdlineP->ymax, &ymaxSpec, 0);
142 OPTENT3(0, "ysize", OPT_UINT, &cmdlineP->ysize, &ysizeSpec, 0);
143 OPTENT3(0, "dpi", OPT_UINT, &cmdlineP->dpi, &dpiSpec, 0);
144 OPTENT3(0, "portrait", OPT_FLAG, NULL, &portraitOpt, 0);
145 OPTENT3(0, "landscape", OPT_FLAG, NULL, &landscapeOpt, 0);
146 OPTENT3(0, "stdout", OPT_FLAG, NULL, &cmdlineP->stdoutSpec, 0);
147 OPTENT3(0, "textalphabits", OPT_UINT,
148 &cmdlineP->textalphabits, &textalphabitsSpec, 0);
149
150 /* Set the defaults */
151 cmdlineP->xborder = cmdlineP->yborder = 0.1;
152
153 opt.opt_table = option_def;
154 opt.short_allowed = FALSE; /* We have no short (old-fashioned) options */
155 opt.allowNegNum = FALSE; /* We have no parms that are negative numbers */
156
157 pm_optParseOptions3(&argc, argv, opt, sizeof(opt), 0);
158 /* Uses and sets argc, argv, and some of *cmdlineP and others. */
159
160 if (xmaxSpec) {
161 if (cmdlineP->xmax == 0)
162 pm_error("zero is not a valid value for -xmax");
163 } else
164 cmdlineP->xmax = 612;
165
166 if (ymaxSpec) {
167 if (cmdlineP->ymax == 0)
168 pm_error("zero is not a valid value for -ymax");
169 } else
170 cmdlineP->ymax = 792;
171
172 if (xsizeSpec) {
173 if (cmdlineP->xsize == 0)
174 pm_error("zero is not a valid value for -xsize");
175 } else
176 cmdlineP->xsize = 0;
177
178 if (ysizeSpec) {
179 if (cmdlineP->ysize == 0)
180 pm_error("zero is not a valid value for -ysize");
181 } else
182 cmdlineP->ysize = 0;
183
184 if (portraitOpt && !landscapeOpt)
185 cmdlineP->orientation = PORTRAIT;
186 else if (!portraitOpt && landscapeOpt)
187 cmdlineP->orientation = LANDSCAPE;
188 else if (!portraitOpt && !landscapeOpt)
189 cmdlineP->orientation = UNSPECIFIED;
190 else
191 pm_error("Cannot specify both -portrait and -landscape options");
192
193 if (pbmOpt)
194 cmdlineP->formatType = PBM_TYPE;
195 else if (pgmOpt)
196 cmdlineP->formatType = PGM_TYPE;
197 else if (ppmOpt)
198 cmdlineP->formatType = PPM_TYPE;
199 else
200 cmdlineP->formatType = PPM_TYPE;
201
202 /* If any one of the 4 bounding box coordinates is given on the
203 command line, we default any of the 4 that aren't.
204 */
205 if (llxSpec || llySpec || urxSpec || urySpec) {
206 cmdlineP->extractBox.isDefined = true;
207
208 if (!llxSpec) cmdlineP->extractBox.llx = 72;
209 else cmdlineP->extractBox.llx = llx * 72;
210 if (!llySpec) cmdlineP->extractBox.lly = 72;
211 else cmdlineP->extractBox.lly = lly * 72;
212 if (!urxSpec) cmdlineP->extractBox.urx = 540;
213 else cmdlineP->extractBox.urx = urx * 72;
214 if (!urySpec) cmdlineP->extractBox.ury = 720;
215 else cmdlineP->extractBox.ury = ury * 72;
216 } else {
217 cmdlineP->extractBox.isDefined = false;
218 }
219
220 if (dpiSpec) {
221 if (cmdlineP->dpi == 0)
222 pm_error("Zero is not a valid value for -dpi");
223 } else
224 cmdlineP->dpi = 0;
225
226 if (dpiSpec && xsizeSpec + ysizeSpec + xmaxSpec + ymaxSpec > 0)
227 pm_error("You may not specify both size options and -dpi");
228
229 if (textalphabitsSpec) {
230 if (cmdlineP->textalphabits != 1 && cmdlineP->textalphabits != 2
231 && cmdlineP->textalphabits != 4) {
232 /* Pstopnm won't take this value, and we don't want to inflict
233 a Pstopnm failure error message on the user.
234 */
235 pm_error("Valid values for -textalphabits are 1, 2, and 4. "
236 "You specified %u", cmdlineP->textalphabits );
237 }
238 } else
239 cmdlineP->textalphabits = 4;
240
241 if (argc-1 == 0)
242 cmdlineP->inputFileName = "-"; /* stdin */
243 else if (argc-1 == 1)
244 cmdlineP->inputFileName = argv[1];
245 else
246 pm_error("Too many arguments (%d). "
247 "Only need one: the Postscript file name", argc-1);
248
249 free(option_def);
250 }
251
252
253
254 static void
255 addPsToFileName(char const origFileName[],
256 const char ** const newFileNameP) {
257 /*----------------------------------------------------------------------------
258 If origFileName[] does not name an existing file, but the same
259 name with ".ps" added to the end does, return the name with the .ps
260 attached. Otherwise, just return origFileName[].
261
262 Return the name in newly malloc'ed storage, pointed to by
263 *newFileNameP.
264 -----------------------------------------------------------------------------*/
265 struct stat statbuf;
266 int statRc;
267
268 statRc = lstat(origFileName, &statbuf);
269
270 if (statRc == 0)
271 *newFileNameP = strdup(origFileName);
272 else {
273 const char * fileNamePlusPs;
274
275 pm_asprintf(&fileNamePlusPs, "%s.ps", origFileName);
276
277 statRc = lstat(fileNamePlusPs, &statbuf);
278 if (statRc == 0)
279 *newFileNameP = strdup(fileNamePlusPs);
280 else
281 *newFileNameP = strdup(origFileName);
282 pm_strfree(fileNamePlusPs);
283 }
284 if (verbose)
285 pm_message("Input file is %s", *newFileNameP);
286 }
287
288
289
290 static unsigned int
291 resolution(unsigned int const dotCt,
292 unsigned int const pointCt) {
293 /*----------------------------------------------------------------------------
294 The resolution in dots per inch when 'dotCt' dots print 'pointCt' points
295 long.
296
297 When this would round to zero, we return 1 dot per inch instead so it
298 doesn't play havoc with arithmetic - it's never going to happen unless
299 something is broken anyway.
300 -----------------------------------------------------------------------------*/
301 return MAX(1, (unsigned int)((float)dotCt * 72 / pointCt + 0.5));
302 }
303
304
305
306 static void
307 computeSizeResFromSizeSpec(unsigned int const requestedXsize,
308 unsigned int const requestedYsize,
309 unsigned int const imageWidth,
310 unsigned int const imageHeight,
311 struct Dimensions * const imageDimP) {
312 /*----------------------------------------------------------------------------
313 Compute output image size and assumed Postscript input resolution, assuming
314 user requested a specific size for at least one of the dimensions and the
315 input is 'imageWidth' x 'imageHeight' points.
316
317 'requestedXsize' is what the user requested for output image width in
318 pixels, or zero if he made no request. 'requestedYsize' is analogous
319 for the height.
320 -----------------------------------------------------------------------------*/
321 assert(requestedXsize || requestedYsize);
322
323 assert(imageWidth > 0);
324
325 if (requestedXsize) {
326 imageDimP->xsize = requestedXsize;
327 imageDimP->xres = resolution(requestedXsize, imageWidth);
328 if (!requestedYsize) {
329 imageDimP->yres = imageDimP->xres;
330 imageDimP->ysize = (unsigned int)
331 (imageHeight * (float)imageDimP->yres/72 + 0.5);
332 }
333 }
334
335 assert(imageHeight > 0);
336
337 if (requestedYsize) {
338 imageDimP->ysize = requestedYsize;
339 imageDimP->yres = resolution(requestedYsize, imageHeight);
340 if (!requestedXsize) {
341 imageDimP->xres = imageDimP->yres;
342 imageDimP->xsize = (unsigned int)
343 (imageWidth * (float)imageDimP->xres/72 + 0.5);
344 }
345 }
346 }
347
348
349
350 static void
351 computeSizeResBlind(unsigned int const xmax,
352 unsigned int const ymax,
353 unsigned int const imageWidth,
354 unsigned int const imageHeight,
355 bool const nocrop,
356 struct Dimensions * const imageDimP) {
357
358 if (imageWidth == 0 || imageHeight == 0) {
359 imageDimP->xres = imageDimP->yres = 72;
360 } else {
361 imageDimP->xres = imageDimP->yres =
362 MIN(resolution(xmax, imageWidth),
363 resolution(ymax, imageHeight));
364 }
365
366 if (nocrop) {
367 imageDimP->xsize = xmax;
368 imageDimP->ysize = ymax;
369 } else {
370 imageDimP->xsize = (unsigned int)
371 (imageWidth * (float)imageDimP->xres / 72 + 0.5);
372 imageDimP->ysize = (unsigned int)
373 (imageHeight * (float)imageDimP->yres / 72 + 0.5);
374 }
375 }
376
377
378
379 static void
380 computeSizeRes(struct CmdlineInfo const cmdline,
381 struct Box const borderedBox,
382 struct Dimensions * const imageDimP) {
383 /*----------------------------------------------------------------------------
384 Figure out how big the output image should be and what output device
385 resolution Ghostscript should assume (return as *imageDimP).
386
387 A resolution number is the number of pixels per inch that the
388 printer prints. Since we're emulating a printed page with a PNM
389 image, and a PNM image has no spatial dimension (you can't say how
390 many inches wide a PNM image is), it's kind of confusing.
391
392 If the user doesn't select a resolution, we choose the resolution
393 that causes the image to be a certain number of pixels, knowing how
394 big (in inches) Ghostscript wants the printed picture to be. For
395 example, the part of the Postscript image we are going to print is 2
396 inches wide. We want the PNM image to be 1000 pixels wide. So we
397 tell Ghostscript that our horizontal output device resolution is 500
398 pixels per inch.
399
400 X and Y in all returned values are with respect to the image, not the
401 page. Note that the image might be placed sideways on the page, so that
402 page X and Y would be reversed from image X and Y.
403 -----------------------------------------------------------------------------*/
404 /* The horizontal and vertical sizes of the input image, in points
405 (1/72 inch)
406 */
407 unsigned int const sx = borderedBox.urx - borderedBox.llx;
408 unsigned int const sy = borderedBox.ury - borderedBox.lly;
409
410 assertValidBox(borderedBox); assert(borderedBox.isDefined);
411
412 if (cmdline.dpi) {
413 /* User gave resolution; we figure out output image size */
414 imageDimP->xres = imageDimP->yres = cmdline.dpi;
415 imageDimP->xsize = ROUNDU(cmdline.dpi * sx / 72.0);
416 imageDimP->ysize = ROUNDU(cmdline.dpi * sy / 72.0);
417 } else if (cmdline.xsize || cmdline.ysize) {
418 if (sx == 0 || sy == 0)
419 pm_error("Input image is zero size; we cannot satisfy your "
420 "produce your requested output dimensions");
421
422 computeSizeResFromSizeSpec(cmdline.xsize, cmdline.ysize, sx, sy,
423 imageDimP);
424 } else
425 computeSizeResBlind(cmdline.xmax, cmdline.ymax, sx, sy, cmdline.nocrop,
426 imageDimP);
427
428 if (cmdline.verbose) {
429 pm_message("output is %u pixels wide X %u pixels high",
430 imageDimP->xsize, imageDimP->ysize);
431 pm_message("output device resolution is %u dpi horiz, %u dpi vert",
432 imageDimP->xres, imageDimP->yres);
433 }
434 }
435
436
437
438 enum PostscriptLanguage {COMMON_POSTSCRIPT, ENCAPSULATED_POSTSCRIPT};
439
440 static enum PostscriptLanguage
441 languageDeclaration(char const inputFileName[]) {
442 /*----------------------------------------------------------------------------
443 Return the Postscript language in which the file declares it is written.
444 (Except that if the file is on Standard Input or doesn't validly declare
445 a language, just say it is Common Postscript).
446 -----------------------------------------------------------------------------*/
447 enum PostscriptLanguage language;
448
449 if (streq(inputFileName, "-"))
450 /* Can't read stdin, because we need it to remain positioned for the
451 Ghostscript interpreter to read it.
452 */
453 language = COMMON_POSTSCRIPT;
454 else {
455 FILE *infile;
456 char line[80];
457
458 infile = pm_openr(inputFileName);
459
460 if (fgets(line, sizeof(line), infile) == NULL)
461 language = COMMON_POSTSCRIPT;
462 else {
463 const char epsHeader[] = " EPSF-";
464
465 if (strstr(line, epsHeader))
466 language = ENCAPSULATED_POSTSCRIPT;
467 else
468 language = COMMON_POSTSCRIPT;
469 }
470 fclose(infile);
471 }
472 if (verbose)
473 pm_message("language is %s",
474 language == ENCAPSULATED_POSTSCRIPT ?
475 "encapsulated postscript" :
476 "not encapsulated postscript");
477 return language;
478 }
479
480
481
482 static struct Box
483 boundingBoxFmPostscriptFile(FILE * const ifP) {
484
485 struct Box retval;
486 bool eof;
487
488 for (retval.isDefined = false, eof = false; !retval.isDefined && !eof; ) {
489 char line[200];
490 char * fgetsRc;
491
492 fgetsRc = fgets(line, sizeof(line), ifP);
493
494 if (fgetsRc == NULL)
495 eof = true;
496 else {
497 int rc;
498 int llx, lly, urx, ury;
499
500 rc = sscanf(line, "%%%%BoundingBox: %d %d %d %d",
501 &llx, &lly, &urx, &ury);
502 if (rc == 4) {
503 /* We found a BoundingBox statement */
504
505 if (llx > urx)
506 pm_error("%%%%BoundingBox statement in input file has "
507 "lower left corner to the right of the "
508 "upper right corner");
509 if (lly > ury)
510 pm_error("%%%%BoundingBox statement in input file has "
511 "lower left corner above the "
512 "upper right corner");
513
514 retval.llx = llx; retval.lly = lly;
515 retval.urx = urx; retval.ury = ury;
516 retval.isDefined = true;
517 }
518 }
519 }
520 fclose(ifP);
521
522 return retval;
523 }
524
525
526
527 static struct Box
528 computeBoxToExtract(struct Box const cmdlineExtractBox,
529 char const inputFileName[]) {
530
531 struct Box retval;
532
533 if (cmdlineExtractBox.isDefined)
534 /* User told us what box to extract, so that's what we'll do */
535 retval = cmdlineExtractBox;
536 else {
537 /* Try to get the bounding box from the DSC %%BoundingBox
538 statement (A Postscript comment) in the input.
539 */
540 struct Box psBb; /* Box described by %%BoundingBox stmt in input */
541
542 if (streq(inputFileName, "-"))
543 /* Can't read stdin, because we need it to remain
544 positioned for the Ghostscript interpreter to read it.
545 */
546 psBb.isDefined = false;
547 else {
548 FILE * ifP;
549
550 ifP = pm_openr(inputFileName);
551
552 psBb = boundingBoxFmPostscriptFile(ifP);
553
554 if (!psBb.isDefined)
555 pm_message("Warning: no %%%%BoundingBox statement "
556 "in the input or command line. "
557 "Will use defaults");
558 }
559 if (psBb.isDefined) {
560 if (verbose)
561 pm_message("Using %%%%BoundingBox statement from input.");
562 retval = psBb;
563 } else {
564 /* Use the center of an 8.5" x 11" page with 1" border all around*/
565 retval.isDefined = true;
566 retval.llx = 72;
567 retval.lly = 72;
568 retval.urx = 540;
569 retval.ury = 720;
570 }
571 }
572
573 assert(retval.isDefined);
574
575 if (verbose)
576 pm_message("Extracting the box ((%d,%d),(%d,%d))",
577 retval.llx, retval.lly, retval.urx, retval.ury);
578 return retval;
579 }
580
581
582
583 static enum Orientation
584 computeOrientation(struct CmdlineInfo const cmdline,
585 struct Box const extractBox) {
586 /*----------------------------------------------------------------------------
587 The proper orientation of the image on the page, given the user's
588 parameters 'cmdline' and the image dimensions 'extractBox'.
589 -----------------------------------------------------------------------------*/
590 /* We're putting an _image_ on a _page_. Either one can have portrait or
591 landscape aspect ratio. In our return value, orientation just means
592 whether the image is rotated on the page: Portrait means it isn't
593 Landscape means it is. The result can be confusing: Consider an image
594 which is a landscape, wider than it is tall, being printed on a page
595 which is also wider than it is tall. The orientation we would return
596 for that case is Portrait.
597
598 The decision is simple: if the user didn't request a particular
599 orientation, we return the value that makes the image orientation match
600 the page orientation. If both possibilities match equally (because the
601 image or the page is square), we return Portrait.
602 */
603
604 enum Orientation retval;
605
606 if (cmdline.orientation != UNSPECIFIED)
607 retval = cmdline.orientation;
608 else {
609 /* Dimensions of image to print, in points */
610 unsigned int const imageWidPt = extractBox.urx - extractBox.llx;
611 unsigned int const imageHgtPt = extractBox.ury - extractBox.lly;
612
613 /* Dimensions of image to print, in pixels (possibly of assumed
614 resolution)
615 */
616 unsigned int imageWidXel;
617 unsigned int imageHgtXel;
618
619 /* We have to deal with the awkward case that the printed pixels are
620 not square. We match up the aspect ratio of the image in _pixels_
621 and the aspect ratio of the page in _pixels_. But only the ratio
622 matters; we don't care what the absolute size of the pixels is.
623 And that's good, because if the user didn't specify xsize/ysize, we
624 don't know the absolute size in pixels. In that case, fortunately,
625 the pixels are guaranteed to be square so we can just pretend it is
626 one point per pixel and get the right result.
627 */
628
629 if (cmdline.xsize && cmdline.ysize) {
630 imageWidXel = cmdline.xsize;
631 imageHgtXel = cmdline.ysize;
632 } else {
633 /* Pixels are square, so it doesn't matter what the resolution
634 is; just call it one pixel per point.
635 */
636 imageWidXel = imageWidPt;
637 imageHgtXel = imageHgtPt;
638 }
639
640 if (imageHgtXel >= imageWidXel && cmdline.ymax >= cmdline.xmax) {
641 /* Both image and page are higher than wide, so no rotation */
642 retval = PORTRAIT;
643 } else if (imageHgtXel < imageWidXel &&
644 cmdline.ymax < cmdline.xmax) {
645 /* Both image and page are wider than high, so no rotation */
646 retval = PORTRAIT;
647 } else {
648 /* Image and pixel have opposite aspect ratios, so rotate
649 for best fit.
650 */
651 retval = LANDSCAPE;
652 }
653 }
654 return retval;
655 }
656
657
658
659 static struct Box
660 addBorders(struct Box const inputBox,
661 float const xborderScale,
662 float const yborderScale) {
663 /*----------------------------------------------------------------------------
664 Return a box which is 'inputBox' plus some borders.
665
666 Add left and right borders that are the fraction 'xborderScale' of the
667 width of the input box; likewise for top and bottom borders with
668 'yborderScale'.
669 -----------------------------------------------------------------------------*/
670 unsigned int const leftRightBorderSize =
671 ROUNDU((inputBox.urx - inputBox.llx) * xborderScale);
672 unsigned int const topBottomBorderSize =
673 ROUNDU((inputBox.ury - inputBox.lly) * yborderScale);
674
675 struct Box retval;
676
677 assertValidBox(inputBox); assert(inputBox.isDefined);
678
679 retval.llx = inputBox.llx - (int)leftRightBorderSize;
680 retval.lly = inputBox.lly - (int)topBottomBorderSize;
681 retval.urx = inputBox.urx + (int)leftRightBorderSize;
682 retval.ury = inputBox.ury + (int)topBottomBorderSize;
683 retval.isDefined = true;
684
685 if (verbose)
686 pm_message("With borders, extracted box is ((%d,%d),(%d,%d))",
687 retval.llx, retval.lly, retval.urx, retval.ury);
688
689 return retval;
690 }
691
692
693
694 static void
695 writePstrans(struct Box const box,
696 struct Dimensions const d,
697 enum Orientation const orientation,
698 FILE * const pipeToGsP) {
699
700 int const xsize = d.xsize;
701 int const ysize = d.ysize;
702 int const xres = d.xres;
703 int const yres = d.yres;
704
705 const char * pstrans;
706
707 assert(xres > 0); assert(yres > 0);
708
709 switch (orientation) {
710 case PORTRAIT: {
711 int llx, lly;
712 llx = box.llx - (xsize * 72 / xres - (box.urx - box.llx)) / 2;
713 lly = box.lly - (ysize * 72 / yres - (box.ury - box.lly)) / 2;
714 pm_asprintf(&pstrans, "%d neg %d neg translate", llx, lly);
715 } break;
716 case LANDSCAPE: {
717 int llx, ury;
718 llx = box.llx - (xsize * 72 / xres - (box.urx - box.llx)) / 2;
719 ury = box.ury + (ysize * 72 / yres - (box.ury - box.lly)) / 2;
720 pm_asprintf(&pstrans, "90 rotate %d neg %d neg translate", llx, ury);
721 } break;
722 case UNSPECIFIED:
723 assert(false);
724 }
725
726 if (pstrans == pm_strsol)
727 pm_error("Unable to allocate memory for pstrans");
728
729 if (verbose)
730 pm_message("Postscript prefix command: '%s'", pstrans);
731
732 fprintf(pipeToGsP, "%s\n", pstrans);
733
734 pm_strfree(pstrans);
735 }
736
737
738
739 static const char *
740 computeOutfileArg(struct CmdlineInfo const cmdline) {
741 /*----------------------------------------------------------------------------
742 Determine the value for the "OutputFile" variable to pass to Ghostscript,
743 which is what tells Ghostscript where to put its output. This is either
744 a pattern such as "foo%03d.ppm" or "-" to indicate Standard Output.
745
746 We go with "-" if, according to 'cmdline', the user asked for
747 Standard Output or is giving his input on Standard Input. Otherwise,
748 we go with the pattern, based on the name of the input file and output
749 format type the user requested.
750 -----------------------------------------------------------------------------*/
751 const char * retval; /* malloc'ed */
752
753 if (cmdline.stdoutSpec)
754 retval = strdup("-");
755 else if (streq(cmdline.inputFileName, "-"))
756 retval = strdup("-");
757 else {
758 char * basename;
759 const char * suffix;
760
761 basename = strdup(cmdline.inputFileName);
762 if (strlen(basename) > 3 &&
763 streq(basename+strlen(basename)-3, ".ps"))
764 /* The input file name ends in ".ps". Chop it off. */
765 basename[strlen(basename)-3] = '\0';
766
767 switch (cmdline.formatType) {
768 case PBM_TYPE: suffix = "pbm"; break;
769 case PGM_TYPE: suffix = "pgm"; break;
770 case PPM_TYPE: suffix = "ppm"; break;
771 default: pm_error("Internal error: invalid value for formatType: %d",
772 cmdline.formatType);
773 }
774 pm_asprintf(&retval, "%s%%03d.%s", basename, suffix);
775
776 pm_strfree(basename);
777 }
778 return(retval);
779 }
780
781
782
783 static const char *
784 computeGsDevice(int const formatType,
785 bool const forceplain) {
786
787 const char * basetype;
788 const char * retval;
789
790 switch (formatType) {
791 case PBM_TYPE: basetype = "pbm"; break;
792 case PGM_TYPE: basetype = "pgm"; break;
793 case PPM_TYPE: basetype = "ppm"; break;
794 default: pm_error("Internal error: invalid value formatType");
795 }
796 if (forceplain)
797 retval = strdup(basetype);
798 else
799 pm_asprintf(&retval, "%sraw", basetype);
800
801 if (retval == NULL)
802 pm_error("Unable to allocate memory for gs device");
803
804 return(retval);
805 }
806
807
808
809 static void
810 findGhostscriptProg(const char ** const retvalP) {
811
812 *retvalP = NULL; /* initial assumption */
813 if (getenv("GHOSTSCRIPT"))
814 *retvalP = strdup(getenv("GHOSTSCRIPT"));
815 if (*retvalP == NULL) {
816 if (getenv("PATH") != NULL) {
817 char * pathwork; /* malloc'ed */
818 const char * candidate;
819
820 pathwork = strdup(getenv("PATH"));
821
822 candidate = strtok(pathwork, ":");
823
824 *retvalP = NULL;
825 while (!*retvalP && candidate) {
826 struct stat statbuf;
827 const char * filename;
828 int rc;
829
830 pm_asprintf(&filename, "%s/gs", candidate);
831 rc = stat(filename, &statbuf);
832 if (rc == 0) {
833 if (S_ISREG(statbuf.st_mode))
834 *retvalP = strdup(filename);
835 } else if (errno != ENOENT)
836 pm_error("Error looking for Ghostscript program. "
837 "stat(\"%s\") returns errno %d (%s)",
838 filename, errno, strerror(errno));
839 pm_strfree(filename);
840
841 candidate = strtok(NULL, ":");
842 }
843 free(pathwork);
844 }
845 }
846 if (*retvalP == NULL)
847 *retvalP = strdup("/usr/bin/gs");
848 }
849
850
851
852 static void
853 execGhostscript(int const inputPipeFd,
854 char const ghostscriptDevice[],
855 char const outfileArg[],
856 struct Dimensions const pageDim,
857 unsigned int const textalphabits) {
858 /*----------------------------------------------------------------------------
859 Exec the Ghostscript program and have it execute the Postscript program
860 that it receives on 'inputPipeFd', then exit.
861
862 'pageDim' describes the print area. X and Y in 'pageDim' are with respect
863 to the page, independent of whether the program we receive on 'inputPipeFd'
864 puts an image in there sideways.
865 -----------------------------------------------------------------------------*/
866 const char * arg0;
867 const char * ghostscriptProg;
868 const char * deviceopt;
869 const char * outfileopt;
870 const char * gopt;
871 const char * ropt;
872 const char * textalphabitsopt;
873
874 findGhostscriptProg(&ghostscriptProg);
875
876 /* Put the input pipe on Standard Input */
877 dup2(inputPipeFd, STDIN_FILENO);
878 close(inputPipeFd);
879
880 pm_asprintf(&arg0, "gs");
881 pm_asprintf(&deviceopt, "-sDEVICE=%s", ghostscriptDevice);
882 pm_asprintf(&outfileopt, "-sOutputFile=%s", outfileArg);
883 pm_asprintf(&gopt, "-g%dx%d", pageDim.xsize, pageDim.ysize);
884 pm_asprintf(&ropt, "-r%dx%d", pageDim.xres, pageDim.yres);
885 pm_asprintf(&textalphabitsopt, "-dTextAlphaBits=%u", textalphabits);
886
887 /* -dSAFER causes Postscript to disable %pipe and file operations,
888 which are almost certainly not needed here. This prevents our
889 Postscript program from doing crazy unexpected things, possibly
890 as a result of a malicious booby trapping of our Postscript file.
891 */
892
893 if (verbose) {
894 pm_message("execing '%s' with args '%s' (arg 0), "
895 "'%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s'",
896 ghostscriptProg, arg0,
897 deviceopt, outfileopt, gopt, ropt, textalphabitsopt,
898 "-q", "-dNOPAUSE",
899 "-dSAFER", "-");
900 }
901
902 execl(ghostscriptProg, arg0, deviceopt, outfileopt, gopt, ropt,
903 textalphabitsopt, "-q", "-dNOPAUSE", "-dSAFER", "-", NULL);
904
905 pm_error("execl() of Ghostscript ('%s') failed, errno=%d (%s)",
906 ghostscriptProg, errno, strerror(errno));
907 }
908
909
910
911 static void
912 copyFileStream(FILE * const ifP,
913 FILE * const ofP) {
914
915 bool eof;
916
917 for (eof = false; !eof; ) {
918 char buffer[4096];
919 size_t readCt;
920
921 readCt = fread(buffer, 1, sizeof(buffer), ifP);
922
923 if (readCt == 0)
924 eof = true;
925 else
926 fwrite(buffer, 1, readCt, ofP);
927 }
928 }
929
930
931
932 static void
933 feedPsToGhostScript(const char * const inputFileName,
934 struct Box const borderedBox,
935 struct Dimensions const imageDim,
936 enum Orientation const orientation,
937 int const pipeToGhostscriptFd,
938 enum PostscriptLanguage const language) {
939 /*----------------------------------------------------------------------------
940 Send a Postscript program to the Ghostscript process running on the
941 other end of the pipe 'pipeToGhostscriptFd'. That program is mostly
942 the contents of file 'inputFileName' (special value "-" means Standard
943 Input), but we may add a little to it.
944
945 The image has dimensions 'imageDim' and is oriented on the page according
946 to 'orientation' ('imageDim' X and Y are with respect to the image itself,
947 without regard to how it is oriented on the page).
948 -----------------------------------------------------------------------------*/
949 FILE * pipeToGsP; /* Pipe to Ghostscript's standard input */
950 FILE * ifP;
951
952 pipeToGsP = fdopen(pipeToGhostscriptFd, "w");
953 if (pipeToGsP == NULL)
954 pm_error("Unable to open stream on pipe to Ghostscript process.");
955
956 ifP = pm_openr(inputFileName);
957 /*
958 In encapsulated Postscript, we the encapsulator are supposed to
959 handle showing the page (which we do by passing a showpage
960 statement to Ghostscript). Any showpage statement in the
961 input must be defined to have no effect.
962
963 See "Enscapsulated PostScript Format File Specification",
964 v. 3.0, 1 May 1992, in particular Example 2, p. 21. I found
965 it at
966 http://partners.adobe.com/asn/developer/pdfs/tn/5002.EPSF_Spec.pdf
967 The example given is a much fancier solution than we need
968 here, I think, so I boiled it down a bit. JM
969 */
970 if (language == ENCAPSULATED_POSTSCRIPT) {
971 const char * const defShowpageCmd =
972 "/b4_Inc_state save def /showpage { } def";
973 if (verbose)
974 pm_message("Defining showpage with '%s'", defShowpageCmd);
975
976 fprintf(pipeToGsP, "\n%s\n", defShowpageCmd);
977 }
978
979 writePstrans(borderedBox, imageDim, orientation, pipeToGsP);
980
981 /* If our child dies, it closes the pipe and when we next write to it,
982 we get a SIGPIPE. We must survive that signal in order to report
983 on the fate of the child. So we ignore SIGPIPE:
984 */
985 signal(SIGPIPE, SIG_IGN);
986
987 copyFileStream(ifP, pipeToGsP);
988
989 pm_close(ifP);
990
991 if (language == ENCAPSULATED_POSTSCRIPT) {
992 const char * const restoreShowpageCmd =
993 "b4_Inc_state restore showpage";
994
995 if (verbose)
996 pm_message("Restoring showpage with '%s'", restoreShowpageCmd);
997
998 fprintf(pipeToGsP, "\n%s\n", restoreShowpageCmd);
999 }
1000 fclose(pipeToGsP);
1001 }
1002
1003
1004
1005 static struct Dimensions
1006 pageDimFromImageDim(struct Dimensions const imageDim,
1007 enum Orientation const orientation) {
1008 /*----------------------------------------------------------------------------
1009 The dimensions of the page of an image whose dimensions are
1010 'imageDim', if we place it on the page with orientation 'orientation'.
1011
1012 (I.e. swap and X and Y if landscape orientation).
1013
1014 'orientation' must not be UNSPECIFIED.
1015 -----------------------------------------------------------------------------*/
1016 struct Dimensions retval;
1017
1018 switch (orientation) {
1019 case PORTRAIT:
1020 retval = imageDim;
1021 break;
1022 case LANDSCAPE:
1023 retval.xsize = imageDim.ysize;
1024 retval.ysize = imageDim.xsize;
1025 retval.xres = imageDim.yres;
1026 retval.yres = imageDim.xres;
1027 break;
1028 case UNSPECIFIED:
1029 assert(false);
1030 break;
1031 }
1032
1033 return retval;
1034 }
1035
1036
1037
1038 static void
1039 executeGhostscript(char const inputFileName[],
1040 struct Box const borderedBox,
1041 struct Dimensions const imageDim,
1042 enum Orientation const orientation,
1043 char const ghostscriptDevice[],
1044 char const outfileArg[],
1045 unsigned int const textalphabits,
1046 enum PostscriptLanguage const language) {
1047
1048 int rc;
1049 int pipefd[2];
1050
1051 if (strlen(outfileArg) > 80)
1052 pm_error("output file spec too long.");
1053
1054 rc = pm_pipe(pipefd);
1055 if (rc < 0)
1056 pm_error("Unable to create pipe to talk to Ghostscript process. "
1057 "errno = %d (%s)", errno, strerror(errno));
1058
1059 rc = fork();
1060 if (rc < 0)
1061 pm_error("Unable to fork a Ghostscript process. errno=%d (%s)",
1062 errno, strerror(errno));
1063 else if (rc == 0) {
1064 /* Child process */
1065 close(pipefd[1]);
1066 execGhostscript(pipefd[0], ghostscriptDevice, outfileArg,
1067 pageDimFromImageDim(imageDim, orientation),
1068 textalphabits);
1069 } else {
1070 /* parent process */
1071 pid_t const ghostscriptPid = rc;
1072 int const pipeToGhostscriptFd = pipefd[1];
1073
1074 int gsTermStatus; /* termination status of Ghostscript process */
1075 pid_t rc;
1076
1077 close(pipefd[0]);
1078
1079 feedPsToGhostScript(inputFileName, borderedBox,
1080 imageDim, orientation,
1081 pipeToGhostscriptFd, language);
1082
1083 rc = waitpid(ghostscriptPid, &gsTermStatus, 0);
1084 if (rc < 0)
1085 pm_error("Wait for Ghostscript process to terminated failed. "
1086 "errno = %d (%s)", errno, strerror(errno));
1087
1088 if (gsTermStatus != 0) {
1089 if (WIFEXITED(gsTermStatus))
1090 pm_error("Ghostscript failed. Exit code=%d\n",
1091 WEXITSTATUS(gsTermStatus));
1092 else if (WIFSIGNALED(gsTermStatus))
1093 pm_error("Ghostscript process died because of a signal %d.",
1094 WTERMSIG(gsTermStatus));
1095 else
1096 pm_error("Ghostscript process died with exit code %d",
1097 gsTermStatus);
1098 }
1099 }
1100 }
1101
1102
1103
1104 int
1105 main(int argc, char ** argv) {
1106
1107 struct CmdlineInfo cmdline;
1108 const char * inputFileName; /* malloc'ed */
1109 /* The file specification of our Postscript input file */
1110 struct Dimensions imageDim;
1111 /* Size and resolution of the input image */
1112 struct Box extractBox;
1113 /* coordinates of the box within the input we are to extract; i.e.
1114 that will become the output.
1115 */
1116 struct Box borderedBox;
1117 /* Same as above, but expanded to include borders */
1118
1119 enum PostscriptLanguage language;
1120 enum Orientation orientation;
1121 const char * ghostscriptDevice;
1122 const char * outfileArg;
1123
1124 pnm_init(&argc, argv);
1125
1126 parseCommandLine(argc, argv, &cmdline);
1127
1128 verbose = cmdline.verbose;
1129
1130 addPsToFileName(cmdline.inputFileName, &inputFileName);
1131
1132 extractBox = computeBoxToExtract(cmdline.extractBox, inputFileName);
1133
1134 language = languageDeclaration(inputFileName);
1135
1136 orientation = computeOrientation(cmdline, extractBox);
1137
1138 borderedBox = addBorders(extractBox, cmdline.xborder, cmdline.yborder);
1139
1140 assertValidBox(borderedBox); assert(borderedBox.isDefined);
1141
1142 computeSizeRes(cmdline, borderedBox, &imageDim);
1143
1144 assert(imageDim.xres > 0); assert(imageDim.yres > 0);
1145
1146 outfileArg = computeOutfileArg(cmdline);
1147
1148 ghostscriptDevice =
1149 computeGsDevice(cmdline.formatType, cmdline.forceplain);
1150
1151 pm_message("Writing %s format", ghostscriptDevice);
1152
1153 executeGhostscript(inputFileName, borderedBox, imageDim, orientation,
1154 ghostscriptDevice, outfileArg, cmdline.textalphabits,
1155 language);
1156
1157 pm_strfree(ghostscriptDevice);
1158 pm_strfree(outfileArg);
1159
1160 return 0;
1161 }
1162
1163
1164