Debian Codegraph @

texk/dvipdfm-x/dvipdfmx.c

raw
1 /* This is (x)dvipdfmx, an extended version of...
2
3 DVIPDFMx, an eXtended version of DVIPDFM by Mark A. Wicks.
4
5 Copyright (C) 2002-2026 by Jin-Hwan Cho, Matthias Franz, and Shunsaku Hirata,
6 the DVIPDFMx project team.
7
8 Copyright (c) 2006 SIL. (xdvipdfmx extensions for XeTeX support)
9
10 Copyright (C) 1998, 1999 by Mark A. Wicks <[email protected]>
11
12 This program is free software; you can redistribute it and/or modify
13 it under the terms of the GNU General Public License as published by
14 the Free Software Foundation; either version 2 of the License, or
15 (at your option) any later version.
16
17 This program is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 GNU General Public License for more details.
21
22 You should have received a copy of the GNU General Public License
23 along with this program; if not, write to the Free Software
24 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
25 */
26
27 #ifdef HAVE_CONFIG_H
28 #include <config.h>
29 #endif
30
31 #include <stdio.h>
32 #include <string.h>
33 #include <limits.h>
34 #include <ctype.h>
35
36 #include "system.h"
37 #include "mem.h"
38
39 #include "dpxconf.h"
40 #include "dpxfile.h"
41 #include "dpxutil.h"
42 #include "dpxcrypt.h"
43
44 #include "dvi.h"
45
46 #include "pdflimits.h"
47 #include "pdfdoc.h"
48 #include "pdfdev.h"
49 #include "pdfparse.h"
50 #include "pdfencrypt.h"
51
52 #include "spc_tpic.h"
53 #include "specials.h"
54
55 #include "mpost.h"
56
57 #include "fontmap.h"
58 #include "pdffont.h"
59 #include "pdfximage.h"
60 #include "cid.h"
61
62 #include "dvipdfmx.h"
63 #include "tt_aux.h"
64
65 #include "error.h"
66
67 #if defined(LIBDPX)
68 const char *my_name = "ApTeX";
69 #else
70 const char *my_name;
71 #endif /* LIBDPX */
72
73 /* Verbosity level */
74 static int verbose = 0;
75 static int really_quiet = 0;
76
77 /* Compatibility option flags */
78 static int opt_flags = 0;
79 #define OPT_TPIC_TRANSPARENT_FILL (1 << 1)
80 #define OPT_CIDFONT_FIXEDPITCH (1 << 2)
81 #define OPT_FONTMAP_FIRST_MATCH (1 << 3)
82 #define OPT_PDFDOC_NO_DEST_REMOVE (1 << 4)
83 #define OPT_PDFOBJ_NO_PREDICTOR (1 << 5)
84 #define OPT_PDFOBJ_NO_OBJSTM (1 << 6)
85
86 /* Basic PDF output settings */
87 static int pdf_version_major = 1;
88 static int pdf_version_minor = 5;
89 static int compression_level = 9;
90
91 /* PDF document navigation feature settings */
92 static double annot_grow_x = 0.0;
93 static double annot_grow_y = 0.0;
94 static int bookmark_open = 0;
95 static double mag = 1.0;
96 static int enable_thumbnail = 0;
97
98 static int font_dpi = 600;
99
100 /* PDF output device settings */
101 static int pdfdecimaldigits = 3;
102 static char ignore_colors = 0;
103
104 /* Image cache life in hours
105 * 0 means erase all old images and leave new images
106 * -1 means erase all old images and also erase new images
107 * -2 means ignore image cache (default)
108 */
109 static int image_cache_life = -2;
110 /* Image format conversion filter template */
111 static char *filter_template = NULL;
112
113 /* Encryption */
114 static int do_encryption = 0;
115 static int key_bits = 40;
116 static int32_t permission = 0x003C;
117
118 /* Page device */
119 double paper_width = 595.0;
120 double paper_height = 842.0;
121 static double x_offset = 72.0;
122 static double y_offset = 72.0;
123 int landscape_mode = 0;
124 int dvi_ptex_with_vert = 0;
125 static int translate_origin = 0;
126
127 static int has_paper_option = 0;
128
129 /* Input and output filenames */
130 char *dvi_filename = NULL, *pdf_filename = NULL;
131
132 static void read_config_file (const char *config);
133
134 static void
135 set_default_pdf_filename (void)
136 {
137 const char *dvi_base;
138 const char *suffix;
139 size_t len = 0;
140
141 dvi_base = xbasename(dvi_filename);
142
143 suffix = strrchr(dvi_base, '.');
144 /* suffix can be dvi_base if dvi_base is like ".abcde" */
145
146 if (suffix == NULL || suffix == dvi_base) {
147 suffix = dvi_base + strlen(dvi_base);
148 }
149 len = strlen(dvi_base) - strlen(suffix);
150
151 if (dpx_conf.compat_mode == dpx_mode_mpost_mode &&
152 FILESTRCASEEQ(".mps", suffix)) {
153 pdf_filename = NEW(len+strlen(".pdf")+1, char);
154 strncpy(pdf_filename, dvi_base, len);
155 pdf_filename[len] = '\0';
156 } else if ((FILESTRCASEEQ(".dvi", suffix) ||
157 FILESTRCASEEQ(".xdv", suffix))) {
158 pdf_filename = NEW(len+strlen(".pdf")+1, char);
159 strncpy(pdf_filename, dvi_base, len);
160 pdf_filename[len] = '\0';
161 } else {
162 pdf_filename = NEW(strlen(dvi_base)+strlen(".pdf")+1, char);
163 strcpy(pdf_filename, dvi_base);
164 }
165
166 strcat (pdf_filename, ".pdf");
167 }
168
169 static void
170 show_version (void)
171 {
172 printf ("This is %s Version " VERSION " by the DVIPDFMx project team,\n",
173 my_name);
174 printf ("modified for TeX Live,\n");
175 if (*my_name == 'x')
176 printf ("an extended version of DVIPDFMx, which in turn was\n");
177 printf ("an extended version of dvipdfm-0.13.2c developed by Mark A. Wicks.\n");
178 printf ("\nCopyright (C) 2002-2026 the DVIPDFMx project team\n");
179 printf ("Copyright (C) 2006-2026 SIL International.\n");
180 printf ("\nThis is free software; you can redistribute it and/or modify\n");
181 printf ("it under the terms of the GNU General Public License as published by\n");
182 printf ("the Free Software Foundation; either version 2 of the License, or\n");
183 printf ("(at your option) any later version.\n");
184 }
185
186 static void
187 show_usage (void)
188 {
189 printf ("\nUsage: %s [OPTION]... [DVIFILE[.dvi|.xdv]]\n", my_name);
190 printf (" %s --extractbb|--xbb|--ebb [OPTION]...\tBe \"extractbb\"\n",
191 my_name);
192 printf (" %s --help|--showpaper|--version\n", my_name);
193 printf ("Convert DVI or XDV input to PDF; defaults given below.\n");
194 printf ("\nOptions:\n");
195 printf (" -c \t\tIgnore color specials (for B&W printing)\n");
196 printf (" --dvipdfm\tEnable DVIPDFM emulation mode\n");
197 printf (" -d number\tSet PDF decimal digits (0-5) [3]\n");
198 printf (" -f filename\tLoad additional font map filename[.map]\n");
199 printf (" -g dimension\tAnnotation \"grow\" amount [0.0in]\n");
200 printf (" -h | --help \tShow this help message and exit\n");
201 printf (" -i cfgfile\tRead additional configuration file\t\n");
202 printf (" --kpathsea-debug number\tSet kpathsea debugging flags [0]\n");
203 printf (" -l \t\tLandscape mode\n");
204 printf (" -m number\tSet additional magnification [1.0]\n");
205 printf (" --mvorigin\tTranslate the origin for MP inclusion\n");
206 printf (" -o filename\tSet output file name, \"-\" for stdout [DVIFILE.pdf]\n");
207 printf (" -p papersize\tSet papersize [a4]\n");
208 printf (" --pdfm-str-utf8\tAssume PDFMark strings are encoded in UTF-8\n");
209 printf (" -q \t\tBe quiet\n");
210 printf (" -r resolution\tSet resolution (in DPI) for raster fonts [600]\n");
211 printf (" -s pages\tSelect page ranges [all pages]\n");
212 printf (" --showpaper\tShow available paper formats and exit\n");
213 printf (" -t \t\tEmbed thumbnail images of PNG format (DVIFILE.pageno, pageno=int) \n");
214 printf (" --version\tOutput version information and exit\n");
215 printf (" -v \t\tBe verbose\n");
216 printf (" -vv\t\tBe more verbose\n");
217 printf (" -x dimension\tSet horizontal offset [1.0in]\n");
218 printf (" -y dimension\tSet vertical offset [1.0in]\n");
219 printf (" -z number \tSet zlib compression level (0-9) [9]\n");
220
221 printf (" -C number\tSpecify miscellaneous option flags [0]:\n");
222 printf ("\t\t 0x0001 reserved\n");
223 printf ("\t\t 0x0002 Use semi-transparent filling for tpic shading command,\n");
224 printf ("\t\t\t instead of opaque gray color; requires PDF 1.4.\n");
225 printf ("\t\t 0x0004 Treat all CIDFont as fixed-pitch font.\n");
226 printf ("\t\t 0x0008 Do not replace duplicate fontmap entries.\n");
227 printf ("\t\t 0x0010 Do not optimize PDF destinations.\n");
228 printf ("\t\t 0x0020 Do not use predictor filter for Flate compression.\n");
229 printf ("\t\t 0x0040 Do not use object stream.\n");
230 printf ("\t\tPositive values are always ORed with previously given flags.\n");
231 printf ("\t\tAnd negative values replace old values.\n");
232 printf (" -D template\tPS->PDF conversion command line template [none]\n");
233 printf (" -E \t\tAlways try to embed fonts, regardless of licensing flags.\n");
234 printf (" -I number\tImage cache life in hours [-2]\n");
235 printf (" \t 0: erase all old images and leave new images\n");
236 printf (" \t-1: erase all old images and also erase new images\n");
237 printf (" \t-2: ignore image cache\n");
238 printf (" -K number\tEncryption key length [40]\n");
239 printf (" -M \t\tProcess MetaPost PostScript output\n");
240 printf (" -O number\tSet maximum depth of open bookmark items [0]\n");
241 printf (" -P number\tSet permission flags for PDF encryption [0x003C]\n");
242 printf (" -S \t\tEnable PDF encryption\n");
243 printf (" -V number\tSet PDF version [%d.%d]\n",
244 PDF_VERSION_DEFAULT/10,PDF_VERSION_DEFAULT%10);
245 printf ("\nAll dimensions entered on the command line are \"true\" TeX dimensions.\n");
246 printf ("Argument of \"-s\" lists physical page ranges separated by commas,\n");
247 printf ("\te.g., \"-s 1-3,5-6\".\n");
248 printf ("Papersize is specified by paper format (e.g., \"a4\")\n");
249 printf ("\tor by w<unit>,h<unit> (e.g., \"20cm,30cm\").\n");
250 printf ("\n");
251 printf ("Package home page: https://ctan.org/pkg/dvipdfmx\n");
252 }
253
254 static void
255 usage (void)
256 {
257 fprintf (stderr, "\nTry \"%s --help\" for more information.\n", my_name);
258 exit(1);
259 }
260
261 static void
262 select_paper (const char *paperspec)
263 {
264 const struct paper *pi;
265 int error = 0;
266
267 pi = paperinfo(paperspec);
268 if (pi && papername(pi)) {
269 paper_width = paperpswidth (pi);
270 paper_height = paperpsheight(pi);
271 } else {
272 const char *p = paperspec, *endptr, *comma;
273 comma = strchr(p, ',');
274 endptr = p + strlen(p);
275 if (!comma)
276 ERROR("Unrecognized paper format: %s", paperspec);
277 error = dpx_util_read_length(&paper_width, 1.0, &p, comma);
278 p = comma + 1;
279 error = dpx_util_read_length(&paper_height, 1.0, &p, endptr);
280 }
281 if (error || paper_width <= 0.0 || paper_height <= 0.0)
282 ERROR("Invalid paper size: %s (%.2fx%.2f)", paperspec, paper_width, paper_height);
283 }
284
285 struct page_range
286 {
287 int first, last;
288 } *page_ranges = NULL;
289
290 int num_page_ranges = 0;
291 int max_page_ranges = 0;
292
293 static void
294 select_pages (const char *pagespec)
295 {
296 char *q;
297 const char *p = pagespec;
298
299 while (*p != '\0') {
300 /* Enlarge page range table if necessary */
301 if (num_page_ranges >= max_page_ranges) {
302 max_page_ranges += 4;
303 page_ranges = RENEW(page_ranges, max_page_ranges, struct page_range);
304 }
305
306 page_ranges[num_page_ranges].first = 0;
307 page_ranges[num_page_ranges].last = 0;
308
309 for ( ; *p && isspace((unsigned char)*p); p++);
310 q = parse_unsigned(&p, p + strlen(p)); /* Can't be signed. */
311 if (q) { /* '-' is allowed here */
312 page_ranges[num_page_ranges].first = atoi(q) - 1;
313 page_ranges[num_page_ranges].last = page_ranges[num_page_ranges].first;
314 RELEASE(q);
315 }
316 for ( ; *p && isspace((unsigned char)*p); p++);
317
318 if (*p == '-') {
319 for (++p; *p && isspace((unsigned char)*p); p++);
320 page_ranges[num_page_ranges].last = -1;
321 if (*p) {
322 q = parse_unsigned(&p, p + strlen(p));
323 if (q) {
324 page_ranges[num_page_ranges].last = atoi(q) - 1;
325 RELEASE(q);
326 }
327 for ( ; *p && isspace((unsigned char)*p); p++);
328 }
329 } else {
330 page_ranges[num_page_ranges].last = page_ranges[num_page_ranges].first;
331 }
332
333 num_page_ranges++;
334
335 if (*p == ',')
336 p++;
337 else {
338 for ( ; *p && isspace((unsigned char)*p); p++);
339 if (*p)
340 ERROR("Bad page range specification: %s", p);
341 }
342 }
343 return;
344 }
345
346 /* Ask passwords for encryption */
347 #ifdef WIN32
348 /* Broken on mintty? */
349 #include <conio.h>
350 #define getch _getch
351 static char *
352 getpass (const char *prompt)
353 {
354 static char pwd_buf[MAX_PWD_LEN];
355 size_t i;
356
357 fputs(prompt, stderr);
358 fflush(stderr);
359 for (i = 0; i < sizeof(pwd_buf)-1; i++) {
360 pwd_buf[i] = getch();
361 if (pwd_buf[i] == '\r' || pwd_buf[i] == '\n')
362 break;
363 fputs("*", stderr);
364 fflush(stderr);
365 }
366 pwd_buf[i] = '\0';
367 fputs("\n", stderr);
368 return pwd_buf;
369 }
370 #else /* !WIN32 */
371 #include <unistd.h>
372 #endif /* WIN32 */
373
374 static int
375 get_enc_password (char *oplain, char *uplain)
376 {
377 char *retry_passwd;
378
379 while (1) {
380 strncpy(oplain, getpass("Owner password: "), MAX_PWD_LEN);
381 retry_passwd = getpass("Re-enter owner password: ");
382 if (!strncmp(oplain, retry_passwd, MAX_PWD_LEN))
383 break;
384 fputs("Password is not identical.\nTry again.\n", stderr);
385 fflush(stderr);
386 }
387 while (1) {
388 strncpy(uplain, getpass("User password: "), MAX_PWD_LEN);
389 retry_passwd = getpass("Re-enter user password: ");
390 if (!strncmp(uplain, retry_passwd, MAX_PWD_LEN))
391 break;
392 fputs("Password is not identical.\nTry again.\n", stderr);
393 fflush(stderr);
394 }
395
396 return 0;
397 }
398
399 static void
400 compute_id_string (unsigned char *id, const char *producer,
401 const char *dviname, const char *pdfname)
402 {
403 char datestr[32];
404 MD5_CONTEXT md5;
405
406 MD5_init(&md5);
407 /* Don't use timezone for compatibility */
408 dpx_util_format_asn_date(datestr, 0);
409 MD5_write(&md5, (const unsigned char *)datestr, strlen(datestr));
410 if (producer)
411 MD5_write(&md5, (const unsigned char *)producer, strlen(producer));
412 if (dviname)
413 MD5_write(&md5, (const unsigned char *)dviname, strlen(dviname));
414 if (pdfname)
415 MD5_write(&md5, (const unsigned char *)pdfname, strlen(pdfname));
416 MD5_final(id, &md5);
417 }
418
419 static const char *optstrig = ":hD:r:m:g:x:y:o:s:p:clf:i:qtvV:z:d:I:K:P:O:MSC:Ee";
420
421 static struct option long_options[] = {
422 {"help", 0, 0, 'h'},
423 {"version", 0, 0, 130},
424 {"showpaper", 0, 0, 131},
425 {"dvipdfm", 0, 0, 132},
426 {"mvorigin", 0, 0, 1000},
427 {"kpathsea-debug", 1, 0, 133},
428 {"pdfm-str-utf8", 0, 0, 134},
429 {0, 0, 0, 0}
430 };
431
432 static void
433 do_args_first_pass (int argc, char *argv[], const char *source, int unsafe)
434 {
435 int c;
436
437 optind = 1;
438 while ((c = getopt_long(argc, argv, optstrig, long_options, NULL)) != -1) {
439 switch(c) {
440 case 'h':
441 show_usage();
442 exit(0);
443 break;
444
445 case 130: /* --version */
446 show_version();
447 exit(0);
448 break;
449
450 case 131: /* --showpaper */
451 dumppaperinfo();
452 exit(0);
453 break;
454
455 case 132: /* --dvipdfm */
456 dpx_conf.compat_mode = dpx_mode_compat_mode;
457 break;
458
459 case 133: /* --kpathsea-debug */
460 kpathsea_debug = atoi(optarg);
461 break;
462
463 case 134: /* --pdfm-str-utf8 */
464 dpx_conf.pdfm_str_utf8 = 1;
465 break;
466
467 case 1000: /* --mvorigin */
468 translate_origin = 1;
469 break;
470
471 case 'q':
472 really_quiet = 2;
473 break;
474
475 case 'v':
476 verbose++;
477 break;
478
479 case 'M':
480 dpx_conf.compat_mode = dpx_mode_mpost_mode;
481 break;
482
483 /* 'm' option placed here since other options set via special
484 * requires magnification already being determined for interpreting
485 * various length values.
486 */
487 case 'm':
488 {
489 char *nextptr;
490 if ((mag = strtod(optarg, &nextptr)) < 0.0 || nextptr == optarg)
491 ERROR("Invalid magnification specified: %s", optarg);
492 }
493 break;
494
495 default: /* ignore everything else */
496 break;
497 }
498 }
499
500 if (really_quiet)
501 shut_up(really_quiet);
502 else {
503 int i;
504
505 for (i = 0; i < verbose; i++) {
506 dpx_conf.verbose_level++;
507 }
508 }
509
510 if (argc > optind + 1) {
511 fprintf(stderr, "%s: Multiple dvi filenames?", my_name);
512 usage();
513 } else if (argc > optind) { /* last argument */
514 dvi_filename = NEW(strlen(argv[optind]) + 5, char); /* space to append ".dvi" */
515 strcpy(dvi_filename, argv[optind]);
516 }
517 }
518
519 /* Set "unsafe" to non-zero value when parsing config specials to
520 * disallow overriding "D" option value.
521 */
522 static void
523 do_args_second_pass (int argc, char *argv[], const char *source, int unsafe)
524 {
525 int c, error = 0;
526 char *nextptr;
527 const char *nnextptr;
528
529 optind = 1;
530 while ((c = getopt_long(argc, argv, optstrig, long_options, NULL)) != -1) {
531 switch(c) {
532 case 'h': case 130: case 131: case 132: case 133: case 134: case 1000: case 'q': case 'v': case 'M': /* already done */
533 break;
534
535 /* 'm' option handled in first_pass */
536 case 'm':
537 if (unsafe) { /* FIXME: it's not actually 'unsafe'... just to know it's called from special */
538 WARN("Ignoring \"m\" option for dvipdfmx:config special. (too late)");
539 }
540 break;
541
542 case 'D':
543 if (unsafe) {
544 WARN("Ignoring \"D\" option for dvipdfmx:config special. (unsafe)");
545 } else {
546 if (filter_template)
547 RELEASE(filter_template);
548 filter_template = NEW(strlen(optarg)+1, char);
549 strcpy(filter_template, optarg);
550 }
551 break;
552
553 case 'r':
554 if ((font_dpi = atoi(optarg)) <= 0)
555 ERROR("Invalid bitmap font dpi specified: %s", optarg);
556 break;
557
558 case 'g':
559 nnextptr = nextptr = optarg;
560 {
561 const char *comma;
562
563 comma = strchr(optarg, ',');
564 if (comma) {
565 error = dpx_util_read_length(&annot_grow_x, 1.0, &nnextptr, comma);
566 nnextptr = comma + 1;
567 if (!error)
568 error = dpx_util_read_length(&annot_grow_y, 1.0, &nnextptr, nextptr + strlen(nextptr));
569 } else {
570 error = dpx_util_read_length(&annot_grow_x, 1.0, &nnextptr, nextptr + strlen(nextptr));
571 if (!error)
572 annot_grow_y = annot_grow_x;
573 }
574 if (error) {
575 WARN("Error reading argument for \"-g\" option: %s", optarg);
576 }
577 }
578 break;
579
580 case 'x':
581 nnextptr = nextptr = optarg;
582 dpx_util_read_length(&x_offset, 1.0, &nnextptr, nextptr + strlen(nextptr));
583 break;
584
585 case 'y':
586 nnextptr = nextptr = optarg;
587 dpx_util_read_length(&y_offset, 1.0, &nnextptr, nextptr + strlen(nextptr));
588 break;
589
590 case 'o':
591 if (pdf_filename) {
592 RELEASE(pdf_filename);
593 }
594 pdf_filename = NEW (strlen(optarg)+1, char);
595 strcpy(pdf_filename, optarg);
596 break;
597
598 case 's':
599 select_pages(optarg);
600 break;
601
602 case 't':
603 enable_thumbnail = 1;
604 break;
605
606 case 'p':
607 select_paper(optarg);
608 has_paper_option = 1;
609 break;
610
611 case 'c':
612 ignore_colors = 1;
613 break;
614
615 case 'l':
616 landscape_mode = 1;
617 break;
618
619 case 'f':
620 if (opt_flags & OPT_FONTMAP_FIRST_MATCH)
621 pdf_load_fontmap_file(optarg, FONTMAP_RMODE_APPEND);
622 else
623 pdf_load_fontmap_file(optarg, FONTMAP_RMODE_REPLACE);
624 break;
625
626 case 'i':
627 {
628 /*
629 -i ./foo.cfg, -i /usr/abc/foo.cfg, etc. are not allowed for
630 security reason.
631 */
632 char *dir1, *dir2;
633 int optind_save= optind;
634 dir1 = strrchr(optarg, '/');
635 dir2 = strrchr(optarg, '\\');
636 if (dir1 || dir2) {
637 WARN("%s is not allowed. Default configuration file is used.", optarg);
638 } else {
639 read_config_file(optarg);
640 }
641 optind = optind_save;
642 break;
643 }
644
645 case 'V':
646 {
647 if (strchr(optarg, '.')) { /* new format X.X */
648 double tmp = atof(optarg);
649 pdf_version_major = (int) tmp;
650 pdf_version_minor = (int) (10 * (tmp - pdf_version_major) + 0.5);
651 } else {
652 pdf_version_major = 1;
653 pdf_version_minor = atoi(optarg);
654 }
655 break;
656 }
657
658 case 'z':
659 compression_level = atoi(optarg);
660 break;
661
662 case 'd':
663 pdfdecimaldigits = atoi(optarg);
664 break;
665
666 case 'I':
667 image_cache_life = atoi(optarg);
668 break;
669
670 case 'S':
671 do_encryption = 1;
672 break;
673
674 case 'K':
675 key_bits = (unsigned) atoi(optarg);
676 if (!(key_bits >= 40 && key_bits <= 128 && (key_bits % 8 == 0)) &&
677 key_bits != 256)
678 ERROR("Invalid encryption key length specified: %s", optarg);
679 break;
680
681 case 'P':
682 permission = (unsigned) strtoul(optarg, &nextptr, 0);
683 if (nextptr == optarg)
684 ERROR("Invalid encryption permission flag: %s", optarg);
685 break;
686
687 case 'O':
688 bookmark_open = atoi(optarg);
689 break;
690
691 case 'C':
692 {
693 int flags = (unsigned) strtol(optarg, &nextptr, 0);
694 if (nextptr == optarg)
695 ERROR("Invalid flag: %s", optarg);
696 if (flags < 0)
697 opt_flags = -flags;
698 else
699 opt_flags |= flags;
700 break;
701 }
702
703 case 'E':
704 dpx_conf.ignore_font_license = 1;
705 break;
706
707 case 'e':
708 if (dpx_conf.compat_mode == dpx_mode_compat_mode) {
709 WARN("dvipdfm \"-e\" option not supported.");
710 break;
711 } /* else fall through */
712
713 default:
714 fprintf(stderr, "%s: %s \"-%c\"\n", source ? source : my_name,
715 c == ':' ? "Missing argument for" : "Unknown option",
716 optopt);
717 usage();
718 }
719 }
720
721 if (source) {
722 if (argc > optind)
723 fprintf(stderr, "%s: Unexpected argument in \"%s %s\".\n", source, argv[1], argv[2]);
724 return;
725 }
726
727 return;
728 }
729
730 static void
731 cleanup (void)
732 {
733 if (dvi_filename)
734 RELEASE(dvi_filename);
735 if (pdf_filename)
736 RELEASE(pdf_filename);
737 if (page_ranges)
738 RELEASE(page_ranges);
739 if (filter_template)
740 RELEASE(filter_template);
741 }
742
743 static void
744 read_config_file (const char *config)
745 {
746 const char *start, *end;
747 char *option;
748 FILE *fp;
749 static char argv0[] = "config_file";
750 char *argv[3];
751
752 fp = DPXFOPEN(config, DPX_RES_TYPE_TEXT);
753 if (!fp) {
754 WARN("Could not open config file \"%s\".", config);
755 return;
756 }
757 argv[0] = argv0;
758 while ((start = mfgets (work_buffer, WORK_BUFFER_SIZE, fp)) != NULL) {
759 int argc = 1;
760
761 end = work_buffer + strlen(work_buffer);
762 skip_white (&start, end);
763 if (start >= end)
764 continue;
765 /* Build up an argument list as if it were passed on the command
766 line */
767 if ((option = parse_ident (&start, end))) {
768 argc = 2;
769 argv[1] = NEW (strlen(option)+2, char);
770 strcpy (argv[1]+1, option);
771 RELEASE (option);
772 *argv[1] = '-';
773 skip_white (&start, end);
774 if (start < end) {
775 argc += 1;
776 if (*start == '"') {
777 argv[2] = parse_c_string (&start, end);
778 }
779 else
780 argv[2] = parse_ident (&start, end);
781 }
782 }
783 do_args_second_pass (argc, argv, config, 0);
784 while (argc > 1) {
785 RELEASE (argv[--argc]);
786 }
787 }
788 if (fp)
789 MFCLOSE(fp);
790 }
791
792 void
793 read_config_special (const char **start, const char *end)
794 {
795 char *option;
796 static char argv0[] = "config_special";
797 char *argv[3];
798 int argc = 1;
799
800 argv[0] = argv0;
801
802 skip_white (start, end);
803 if (*start >= end)
804 return;
805 /* Build up an argument list as if it were passed on the command
806 line */
807 if ((option = parse_ident (start, end))) {
808 argc = 2;
809 argv[1] = NEW (strlen(option)+2, char);
810 strcpy (argv[1]+1, option);
811 RELEASE (option);
812 *argv[1] = '-';
813 skip_white (start, end);
814 if (*start < end) {
815 argc += 1;
816 if (**start == '"') {
817 argv[2] = parse_c_string (start, end);
818 }
819 else
820 argv[2] = parse_ident (start, end);
821 }
822 }
823 do_args_second_pass (argc, argv, argv0, 1); /* Set to unsafe */
824 while (argc > 1) {
825 RELEASE (argv[--argc]);
826 }
827 }
828
829 static void
830 system_default (void)
831 {
832 if (systempapername() != NULL) {
833 select_paper(systempapername());
834 } else if (defaultpapername() != NULL) {
835 select_paper(defaultpapername());
836 }
837 }
838
839 void
840 error_cleanup (void)
841 {
842 /* Fixed a stupid bug...
843 * Please don't put an ordinay function which may call ERROR() inside it.
844 * It may result in error cleanup routine being called recursively.
845 */
846 pdf_error_cleanup_cache(); /* delete temporary files */
847 pdf_error_cleanup();
848 if (pdf_filename) {
849 if (pdf_get_output_file()) {
850 remove(pdf_filename);
851 fprintf(stderr, "\nOutput file removed.\n");
852 } else {
853 fprintf(stderr, "\nNo output PDF file written.\n");
854 }
855 }
856 }
857
858 #define SWAP(v1,v2) do {\
859 double _tmp = (v1);\
860 (v1) = (v2);\
861 (v2) = _tmp;\
862 } while (0)
863
864 static void
865 do_dvi_pages (void)
866 {
867 int page_no, page_count, i, step;
868 double page_width, page_height;
869 double init_paper_width, init_paper_height;
870 pdf_rect mediabox;
871
872 spc_exec_at_begin_document();
873
874 if (num_page_ranges == 0) {
875 if (!page_ranges) {
876 page_ranges = NEW(1, struct page_range);
877 max_page_ranges = 1;
878 }
879 page_ranges[0].first = 0;
880 page_ranges[0].last = -1; /* last page */
881 num_page_ranges = 1;
882 }
883
884 init_paper_width = page_width = paper_width;
885 init_paper_height = page_height = paper_height;
886 page_count = 0;
887
888 mediabox.llx = 0.0;
889 mediabox.lly = 0.0;
890 mediabox.urx = paper_width;
891 mediabox.ury = paper_height;
892
893 pdf_doc_set_mediabox(0, &mediabox); /* Root node */
894
895 for (i = 0; i < num_page_ranges && dvi_npages(); i++) {
896 if (page_ranges[i].last < 0)
897 page_ranges[i].last += dvi_npages();
898
899 step = (page_ranges[i].first <= page_ranges[i].last) ? 1 : -1;
900 page_no = page_ranges[i].first;
901 while (dvi_npages()) {
902 if (page_no < dvi_npages()) {
903 double w, h, xo, yo;
904 int lm;
905
906 MESG("[%d", page_no+1);
907 /* FIXME: incompatibility here.... In older versions of dvipdfmx page sizes
908 * are inherited from the previous page but in the current implementation
909 * pagesize special only takes effect to the current page.
910 * The following line resets page sizes to the paper size...
911 */
912 page_width = paper_width; page_height = paper_height;
913 w = page_width; h = page_height; lm = landscape_mode;
914 xo = x_offset; yo = y_offset;
915 dvi_scan_specials(page_no,
916 &w, &h, &xo, &yo, &lm,
917 /* No need for encryption options */
918 NULL, NULL, NULL, NULL, NULL, NULL, NULL,
919 /* No trailer IDs */
920 NULL, NULL, NULL);
921 if (lm != landscape_mode) {
922 /* The first page was already scanned once and SWAP() was applied there.
923 * Do not apply SWAP() twice!
924 * FIXME: SWAP() not applied to paper_width and paper_height. Why?
925 */
926 SWAP(w, h);
927 landscape_mode = lm;
928 }
929 /* Specified as a command line option */
930 if (!has_paper_option) {
931 if (page_width != w || page_height != h) {
932 page_width = w;
933 page_height = h;
934 }
935 }
936 if (x_offset != xo || y_offset != yo) {
937 x_offset = xo;
938 y_offset = yo;
939 }
940 if (page_width != init_paper_width ||
941 page_height != init_paper_height) {
942 mediabox.llx = 0.0;
943 mediabox.lly = 0.0;
944 mediabox.urx = page_width;
945 mediabox.ury = page_height;
946 pdf_doc_set_mediabox(page_count+1, &mediabox);
947 }
948 dvi_do_page(page_height, x_offset, y_offset);
949 page_count++;
950 MESG("]");
951 }
952
953 if (step > 0 &&
954 page_no >= page_ranges[i].last)
955 break;
956 else if (step < 0 &&
957 page_no <= page_ranges[i].last)
958 break;
959 else {
960 page_no += step;
961 }
962 }
963 }
964
965 if (page_count < 1) {
966 ERROR("No pages fall in range!");
967 }
968
969 spc_exec_at_end_document();
970 }
971
972 static void
973 do_mps_pages (void)
974 {
975 FILE *fp;
976
977 /* _FIXME_ */
978 fp = MFOPEN(dvi_filename, FOPEN_RBIN_MODE);
979 if (fp) {
980 mps_do_page(fp);
981 MFCLOSE(fp);
982 } else {
983 int i, page_no, step, page_count = 0;
984 char *filename;
985 /* Process filename.1, filename.2,... */
986 filename = NEW(strlen(dvi_filename) + 16 + 1, char);
987 for (i = 0; i < num_page_ranges; i++) {
988 step = (page_ranges[i].first <= page_ranges[i].last) ? 1 : -1;
989 page_no = page_ranges[i].first;
990 for (;;) {
991 if (page_no < 0)
992 ERROR("Invalid page number for MPS input: %d", page_no);
993
994 sprintf(filename, "%s.%d", dvi_filename, page_no + 1);
995 fp = MFOPEN(filename, FOPEN_RBIN_MODE);
996 if (fp) {
997 MESG("[%ld<%s>", page_no + 1, filename);
998 mps_do_page(fp);
999 page_count++;
1000 MESG("]");
1001 MFCLOSE(fp);
1002 }
1003 if (step > 0 &&
1004 page_no >= page_ranges[i].last)
1005 break;
1006 else if (step < 0 &&
1007 page_no <= page_ranges[i].last)
1008 break;
1009 else {
1010 page_no += step;
1011 }
1012 }
1013 }
1014 RELEASE(filename);
1015 if (page_count == 0)
1016 ERROR("No page output for \"%s\".", dvi_filename);
1017 }
1018 }
1019
1020 #if !defined(LIBDPX)
1021 /* Support to make DLL in W32TeX */
1022 #define DLLPROC dlldvipdfmxmain
1023
1024 #if defined(WIN32) && !defined(__MINGW32__) && !defined(MIKTEX) && defined(DLLPROC)
1025 extern __declspec(dllexport) int DLLPROC (int argc, char *argv[]);
1026 #else
1027 #undef DLLPROC
1028 #endif
1029 #endif /* !LIBDPX */
1030
1031 #if defined(MIKTEX)
1032 # define main Main
1033 #endif
1034
1035 int
1036 #if defined(DLLPROC)
1037 DLLPROC (int argc, char *argv[])
1038 #else
1039 #if defined(LIBDPX)
1040 dvipdfmx_main (int argc, char *argv[])
1041 #else
1042 main (int argc, char *argv[])
1043 #endif /* LIBDPX */
1044 #endif
1045 {
1046 double dvi2pts;
1047 char *base;
1048 struct pdf_setting settings;
1049 char uplain[MAX_PWD_LEN+1], oplain[MAX_PWD_LEN+1]; /* encryption password */
1050 const char *creator = NULL;
1051 unsigned char id1[16], id2[16];
1052 int has_id = 0;
1053
1054 #ifdef WIN32
1055 int ac;
1056 char **av, *enc;
1057 #endif
1058
1059 #ifdef MIKTEX
1060 miktex_initialize();
1061 #else
1062 kpse_set_program_name(argv[0], "dvipdfmx"); /* we pretend to be dvipdfmx for kpse purposes */
1063 #ifdef WIN32
1064 texlive_gs_init ();
1065 enc = kpse_var_value("command_line_encoding");
1066 if (get_command_line_args_utf8(enc, &ac, &av)) {
1067 argc = ac;
1068 argv = av;
1069 }
1070 #endif
1071 #endif
1072
1073 if (argc > 1 &&
1074 (STREQ (argv[1], "--xbb") ||
1075 STREQ (argv[1], "--extractbb") ||
1076 STREQ (argv[1], "--dvipdfm") ||
1077 STREQ (argv[1], "--dvipdfmx") ||
1078 STREQ (argv[1], "--ebb"))) {
1079 argc--;
1080 base = argv++[1]+2;
1081 } else {
1082 base = kpse_program_basename (argv[0]);
1083 }
1084
1085 if (FILESTRCASEEQ (base, "extractbb") || FILESTRCASEEQ (base, "xbb")) {
1086 my_name = "extractbb";
1087 return extractbb (argc, argv);
1088 } else if (FILESTRCASEEQ (base, "ebb")) {
1089 my_name = "ebb";
1090 dpx_conf.compat_mode = dpx_mode_compat_mode;
1091 return extractbb (argc, argv);
1092 } else if (FILESTRCASEEQ (base, "dvipdfm")) {
1093 my_name = "dvipdfm";
1094 dpx_conf.compat_mode = dpx_mode_compat_mode;
1095 } else if (FILESTRCASEEQ (base, "dvipdfmx")) {
1096 my_name = "dvipdfmx";
1097 } else {
1098 my_name = "xdvipdfmx";
1099 }
1100
1101 opterr = 0;
1102 /* Special-case single option --mvorigin, --help, --showpaper, or --version,
1103 * to avoid possible diagnostics about config files, etc.
1104 * Also handle -q and -v that cannot be set in config file.
1105 * Get input DVI file name too.
1106 */
1107 do_args_first_pass(argc, argv, NULL, 0);
1108
1109 paperinit();
1110 system_default();
1111
1112 pdf_init_fontmaps(); /* This must come before parsing options... */
1113
1114 read_config_file(DPX_CONFIG_FILE);
1115
1116 /* Current implementation seems to be assuming that paper size read from config
1117 * is for "default" and explicitly specified one via command-line option must be
1118 * used for all pages regardless of papersize specials.
1119 */
1120 has_paper_option = 0;
1121
1122 if (!dvi_filename) {
1123 if (verbose)
1124 MESG("No dvi filename specified, reading standard input.\n");
1125 } else if (!pdf_filename)
1126 set_default_pdf_filename();
1127
1128 if (dpx_conf.compat_mode == dpx_mode_mpost_mode) {
1129 x_offset = 0.0;
1130 y_offset = 0.0;
1131 dvi2pts = 0.01; /* dvi2pts controls accuracy. */
1132 } else {
1133 dvi2pts = dvi_init(dvi_filename, mag);
1134 if (dvi2pts == 0.0)
1135 ERROR("dvi_init() failed!");
1136 creator = dvi_comment(); /* Set PDF Creator entry */
1137 dvi_scan_specials(0,
1138 &paper_width, &paper_height,
1139 &x_offset, &y_offset, &landscape_mode,
1140 &pdf_version_major, &pdf_version_minor,
1141 &do_encryption, &key_bits, &permission, oplain, uplain,
1142 &has_id, id1, id2);
1143 }
1144
1145 /* Command-line options take precedence */
1146 {
1147 int has_encrypt_special = do_encryption;
1148
1149 do_args_second_pass(argc, argv, NULL, 0);
1150 if (do_encryption && !has_encrypt_special) {
1151 get_enc_password(oplain, uplain);
1152 }
1153 }
1154
1155 /* moved to here because -o - was not effective */
1156 if (pdf_filename && !strcmp(pdf_filename, "-")) {
1157 RELEASE(pdf_filename);
1158 pdf_filename = NULL;
1159 }
1160
1161 /* moved to here because an incorrect message:
1162 "No pdf filename specified, writing to standard output."
1163 is printed for xdvipdfmx -v -o foo.pdf < foo.xdv */
1164 if (!pdf_filename)
1165 if (verbose)
1166 MESG("No pdf filename specified, writing to standard output.\n");
1167
1168 /* moved to here because -r option was not effective */
1169 #ifndef MIKTEX
1170 kpse_init_prog("", font_dpi, NULL, NULL);
1171 kpse_set_program_enabled(kpse_pk_format, true, kpse_src_texmf_cnf);
1172 #endif
1173 pdf_font_set_dpi(font_dpi);
1174
1175 /* moved to here because image caching was not effective */
1176 dpx_delete_old_cache(image_cache_life);
1177
1178 MESG("%s -> %s\n", dvi_filename ? dvi_filename : "stdin",
1179 pdf_filename ? pdf_filename : "stdout");
1180
1181 /* Kpathsea messages:
1182 * really_quiet > 1 is actually for suppressing error messages in dvipdfmx.
1183 */
1184 kpse_make_tex_discard_errors = really_quiet;
1185
1186 /* Setup Options */
1187 settings.ver_major = pdf_version_major;
1188 settings.ver_minor = pdf_version_minor;
1189
1190 /* PDF trailer ID. */
1191 if (!has_id) {
1192 #define PRODUCER \
1193 "%s-%s, Copyright 2002-2026 by Jin-Hwan Cho, Matthias Franz, and Shunsaku Hirata"
1194 char producer[256];
1195
1196 sprintf(producer, PRODUCER, my_name, VERSION);
1197 compute_id_string(id1, producer, dvi_filename, pdf_filename);
1198 memcpy(id2, id1, 16);
1199 }
1200
1201 /* Encryption and Other Settings */
1202 {
1203 memset(&settings.encrypt, 0, sizeof(struct pdf_enc_setting));
1204 settings.enable_encrypt = do_encryption;
1205 settings.encrypt.use_aes = 1;
1206 settings.encrypt.encrypt_metadata = 1;
1207 settings.encrypt.key_size = key_bits;
1208 settings.encrypt.permission = permission;
1209 settings.encrypt.uplain = uplain;
1210 settings.encrypt.oplain = oplain;
1211 }
1212
1213 /* PDF object settings */
1214 settings.object.compression_level = compression_level;
1215 if (opt_flags & OPT_PDFOBJ_NO_OBJSTM) {
1216 settings.object.enable_objstm = 0;
1217 } else {
1218 settings.object.enable_objstm = 1;
1219 }
1220 if (opt_flags & OPT_PDFOBJ_NO_PREDICTOR) {
1221 settings.object.enable_predictor = 0;
1222 } else {
1223 settings.object.enable_predictor = 1;
1224 }
1225
1226 /* PDF document settings
1227 * Set default paper size here so that all page's can inherite it.
1228 * annot_grow: Margin of annotation.
1229 * bookmark_open: Miximal depth of open bookmarks.
1230 */
1231 if (landscape_mode) {
1232 SWAP(paper_width, paper_height);
1233 }
1234 settings.media_width = paper_width;
1235 settings.media_height = paper_height;
1236 settings.annot_grow_amount.x = annot_grow_x;
1237 settings.annot_grow_amount.y = annot_grow_y;
1238 settings.outline_open_depth = bookmark_open;
1239 settings.check_gotos = !(opt_flags & OPT_PDFDOC_NO_DEST_REMOVE);
1240 settings.enable_manual_thumb = enable_thumbnail;
1241
1242 /* PDF page output settings */
1243 settings.device.dvi2pts = dvi2pts;
1244 settings.device.precision = pdfdecimaldigits;
1245 settings.device.ignore_colors = ignore_colors;
1246
1247 set_distiller_template(filter_template);
1248
1249 /* Initialize PDF document creation routine. */
1250 pdf_open_document(pdf_filename, creator, id1, id2, settings);
1251
1252 if (opt_flags & OPT_CIDFONT_FIXEDPITCH)
1253 CIDFont_set_flags(CIDFONT_FORCE_FIXEDPITCH);
1254 /* Please move this to spc_init_specials(). */
1255 if (opt_flags & OPT_TPIC_TRANSPARENT_FILL)
1256 tpic_set_fill_mode(1);
1257 if (translate_origin)
1258 mps_set_translate_origin(1);
1259
1260 if (dpx_conf.compat_mode == dpx_mode_mpost_mode) {
1261 do_mps_pages();
1262 } else {
1263 do_dvi_pages();
1264 }
1265
1266 pdf_close_document();
1267
1268 pdf_close_fontmaps(); /* pdf_font may depend on fontmap. */
1269
1270 if (dpx_conf.compat_mode != dpx_mode_mpost_mode)
1271 dvi_close();
1272
1273 MESG("\n");
1274 cleanup();
1275
1276 paperdone();
1277 #ifdef MIKTEX
1278 miktex_uninitialize ();
1279 #endif
1280
1281 return 0;
1282 }