Debian Codegraph @

texk/web2c/luatexdir/pdf/pdfgen.c

raw
1 /*
2
3 Copyright 2009-2013 Taco Hoekwater <[email protected]>
4
5 This file is part of LuaTeX.
6
7 LuaTeX 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 of the License, or (at your
10 option) any later version.
11
12 LuaTeX is distributed in the hope that it will be useful, but WITHOUT
13 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
15 License for more details.
16
17 You should have received a copy of the GNU General Public License along
18 with LuaTeX; if not, see <http://www.gnu.org/licenses/>.
19
20 */
21
22 #include "ptexlib.h"
23
24 #include <kpathsea/c-dir.h>
25 #include <kpathsea/c-ctype.h>
26 #include "lua/luatex-api.h"
27 #include "md5.h"
28
29 #define check_nprintf(size_get, size_want) \
30 if ((unsigned)(size_get) >= (unsigned)(size_want)) \
31 formatted_error("pdf backend","snprintf() failed in file %s at line %d", __FILE__, __LINE__);
32
33 PDF static_pdf = NULL;
34
35 /*tex The commandline interface: */
36
37 int output_mode_used;
38 int output_mode_option;
39 int output_mode_value;
40 int draft_mode_option;
41 int draft_mode_value;
42
43 /*tex Additional keys of the |/Info| dictionary: */
44
45 halfword pdf_info_toks;
46
47 /*tex Additional keys of the |/Catalog| and its |/OpenAction| dictionary: */
48
49 halfword pdf_catalog_toks;
50
51 halfword pdf_catalog_openaction;
52
53 /*tex Additional keys of the |/Names| dictionary: */
54
55 halfword pdf_names_toks;
56
57 /*tex Additional keys of the |/Trailer| dictionary" */
58
59 halfword pdf_trailer_toks;
60
61 /*tex Set to |shipping_mode| when |ship_out| starts */
62
63 shipping_mode_e global_shipping_mode = NOT_SHIPPING;
64
65 /*tex
66
67 Create a new buffer |strbuf_s| of size |size| and maximum allowed size
68 |limit|. Initialize it and set |p| to begin of data.
69
70 */
71
72 strbuf_s *new_strbuf(size_t size, size_t limit)
73 {
74 strbuf_s *b;
75 b = xtalloc(1, strbuf_s);
76 b->size = size;
77 b->limit = limit;
78 if (size > 0) {
79 b->p = b->data = xtalloc(b->size, unsigned char);
80 } else {
81 /*tex For other alloc: */
82 b->p = b->data = NULL;
83 }
84 return b;
85 }
86
87 /*tex Check that |n| bytes more fit into buffer; increase it if required. */
88
89 static void strbuf_room(strbuf_s * b, size_t n)
90 {
91 unsigned int a;
92 size_t l = (size_t) (b->p - b->data);
93 if (n > b->limit - l)
94 overflow("PDF buffer", (unsigned) b->size);
95 if (n + l > b->size) {
96 a = (unsigned int) (b->size >> 2);
97 if (n + l > b->size + a)
98 b->size = n + l;
99 else if (b->size < b->limit - a)
100 b->size = b->size + a;
101 else
102 b->size = b->limit;
103 b->data = xreallocarray(b->data, unsigned char, (unsigned) b->size);
104 b->p = b->data + l;
105 }
106 }
107
108 /*tex Seek to position |offset| within buffer. Position must be valid. */
109
110 void strbuf_seek(strbuf_s * b, off_t offset)
111 {
112 b->p = b->data + offset;
113 }
114
115 /*tex Get the current buffer fill level, the number of characters.*/
116
117 size_t strbuf_offset(strbuf_s * b)
118 {
119 return (size_t) (b->p - b->data);
120 }
121
122 /*tex Put one character into buffer. Make room before if needed. */
123
124 void strbuf_putchar(strbuf_s * b, unsigned char c)
125 {
126 if ((size_t) (b->p - b->data + 1) > b->size)
127 strbuf_room(b, 1);
128 *b->p++ = c;
129 }
130
131 /*tex Dump filled buffer part to the \PDF\ file. */
132
133 void strbuf_flush(PDF pdf, strbuf_s * b)
134 {
135 pdf_out_block(pdf, (const char *) b->data, strbuf_offset(b));
136 strbuf_seek(b, 0);
137 }
138
139 /*tex We free all dynamically allocated buffer structures. */
140
141 void strbuf_free(strbuf_s * b)
142 {
143 xfree(b->data);
144 xfree(b);
145 }
146
147 /*tex This |init_pdf_struct| is called early and only once. */
148
149 PDF init_pdf_struct(PDF pdf)
150 {
151 os_struct *os;
152 pdf = xtalloc(1, pdf_output_file);
153 memset(pdf, 0, sizeof(pdf_output_file));
154 pdf->job_name = makecstring(job_name);
155 /*tex This will be set by |fix_o_mode|: */
156 output_mode_used = OMODE_NONE;
157 /*tex Used by synctex, we need to use output_mode_used there. */
158 pdf->o_mode = output_mode_used;
159 pdf->o_state = ST_INITIAL;
160 /*tex Initialize \PDF\ and object stream writing */
161 pdf->os = os = xtalloc(1, os_struct);
162 memset(pdf->os, 0, sizeof(os_struct));
163 os->buf[PDFOUT_BUF] = new_strbuf(inf_pdfout_buf_size, sup_pdfout_buf_size);
164 os->buf[OBJSTM_BUF] = new_strbuf(inf_objstm_buf_size, sup_objstm_buf_size);
165 os->obj = xtalloc(PDF_OS_MAX_OBJS, os_obj_data);
166 os->cur_objstm = 0;
167 os->curbuf = PDFOUT_BUF;
168 pdf->buf = os->buf[os->curbuf];
169 /*tex
170 Later ttf_seek_outbuf(TABDIR_OFF + n * 4 * TTF_ULONG_SIZE); in
171 ttf_init_font we need 236 bytes, so we start with 256 bytes as in \PDFTEX.
172 */
173 pdf->fb = new_strbuf(256, 100000000);
174 pdf->stream_deflate = false;
175 pdf->stream_writing = false;
176 /*tex
177 Sometimes it is neccesary to allocate memory for PDF output that cannot be
178 deallocated then, so we use |mem| for this purpose.
179 */
180 pdf->mem_size = inf_pdf_mem_size;
181 pdf->mem = xtalloc(pdf->mem_size, int);
182 /*tex
183 The first word is not used so we can use zero as a value for testing
184 whether a pointer to |mem| is valid.
185 */
186 pdf->mem_ptr = 1;
187 pdf->pstruct = NULL;
188 pdf->posstruct = xtalloc(1, posstructure);
189 pdf->posstruct->pos.h = 0;
190 pdf->posstruct->pos.v = 0;
191 pdf->posstruct->dir = dir_TLT;
192 /*tex Allocated size of |obj_tab| array> */
193 pdf->obj_tab_size = (unsigned) inf_obj_tab_size;
194 pdf->obj_tab = xtalloc(pdf->obj_tab_size + 1, obj_entry);
195 memset(pdf->obj_tab, 0, sizeof(obj_entry));
196 pdf->minor_version = -1;
197 pdf->major_version = -1;
198 pdf->decimal_digits = 4;
199 pdf->gamma = 65536;
200 pdf->image_gamma = 65536;
201 pdf->image_hicolor = 1;
202 pdf->image_apply_gamma = 0;
203 pdf->objcompresslevel = 0;
204 pdf->compress_level = 0;
205 pdf->force_file = 0;
206 pdf->recompress = 0;
207 pdf->draftmode = 0;
208 pdf->inclusion_copy_font = 1;
209 pdf->pk_resolution = 0;
210 pdf->pk_fixed_dpi = 0;
211 pdf->pk_scale_factor = 0;
212 init_dest_names(pdf);
213 pdf->page_resources = NULL;
214 init_pdf_pagecalculations(pdf);
215 pdf->vfstruct = new_vfstruct();
216 return pdf;
217 }
218
219 /*tex We use |pdf_get_mem| to allocate memory in |mem|. */
220
221 int pdf_get_mem(PDF pdf, int s)
222 {
223 int a;
224 int ret;
225 if (s > sup_pdf_mem_size - pdf->mem_ptr)
226 overflow("pdf memory size (pdf_mem_size)", (unsigned) pdf->mem_size);
227 if (pdf->mem_ptr + s > pdf->mem_size) {
228 a = pdf->mem_size >> 2;
229 if (pdf->mem_ptr + s > pdf->mem_size + a) {
230 pdf->mem_size = pdf->mem_ptr + s;
231 } else if (pdf->mem_size < sup_pdf_mem_size - a) {
232 pdf->mem_size = pdf->mem_size + a;
233 } else {
234 pdf->mem_size = sup_pdf_mem_size;
235 }
236 pdf->mem = xreallocarray(pdf->mem, int, (unsigned) pdf->mem_size);
237 }
238 ret = pdf->mem_ptr;
239 pdf->mem_ptr = pdf->mem_ptr + s;
240 return ret;
241 }
242
243 /*tex
244
245 This ensures that |pdfmajorversion| and |pdfminorversion| are set only before
246 any bytes have been written to the generated \PDF\ file. Here also all
247 variables for \PDF\ output are initialized, the \PDF\ file is opened by
248 |ensure_pdf_open|, and the \PDF\ header is written.
249
250 */
251
252 void fix_pdf_version(PDF pdf)
253 {
254 if (pdf->major_version < 0) {
255 /*tex It is unset. */
256 if (pdf_major_version == 0) {
257 normal_warning("pdf backend","unset major version, using 1 instead");
258 pdf->major_version = 1;
259 } else if ((pdf_major_version < 0) || (pdf_major_version > 2)) {
260 formatted_warning("pdf backend","illegal major version %d, using 1 instead",pdf_major_version);
261 pdf->major_version = 1;
262 } else {
263 pdf->major_version = pdf_major_version;
264 }
265 } else if (pdf->major_version != pdf_major_version) {
266 normal_warning("pdf backend", "the major version cannot be changed after data is written to the PDF file");
267 }
268 if (pdf->minor_version < 0) {
269 /*tex It is unset. */
270 if ((pdf_minor_version < 0) || (pdf_minor_version > 9)) {
271 formatted_warning("pdf backend","illegal minor version %d, using 4 instead",pdf_minor_version);
272 pdf->minor_version = 4;
273 } else {
274 pdf->minor_version = pdf_minor_version;
275 }
276 } else if (pdf->minor_version != pdf_minor_version) {
277 normal_warning("pdf backend", "minorversion cannot be changed after data is written to the PDF file");
278 }
279 }
280
281 static void fix_pdf_draftmode(PDF pdf)
282 {
283 if (pdf->draftmode != draft_mode_par)
284 normal_warning("pdf backend", "draftmode cannot be changed after data is written to the PDF file");
285 if (pdf->draftmode != 0) {
286 /*tex Fix these as they might have been changed in between. */
287 pdf->compress_level = 0;
288 pdf->objcompresslevel = 0;
289 }
290 }
291
292 #define ZIP_BUF_SIZE 32768
293
294 #define check_err(f, fn) \
295 if (f != Z_OK) \
296 formatted_error("pdf backend","zlib %s() failed (error code %d)", fn, f)
297
298 static void write_zip(PDF pdf)
299 {
300 int flush, err = Z_OK;
301 uInt zip_len;
302 strbuf_s *buf = pdf->buf;
303 z_stream *s = pdf->c_stream;
304 boolean finish = pdf->zip_write_state == ZIP_FINISH;
305 if (pdf->stream_length == 0) {
306 if (s == NULL) {
307 s = pdf->c_stream = xtalloc(1, z_stream);
308 s->zalloc = (alloc_func) 0;
309 s->zfree = (free_func) 0;
310 s->opaque = (voidpf) 0;
311 check_err(deflateInit(s, pdf->compress_level), "deflateInit");
312 pdf->zipbuf = xtalloc(ZIP_BUF_SIZE, char);
313 } else
314 check_err(deflateReset(s), "deflateReset");
315 s->next_out = (Bytef *) pdf->zipbuf;
316 s->avail_out = ZIP_BUF_SIZE;
317 }
318 s->next_in = buf->data;
319 s->avail_in = (uInt) (buf->p - buf->data);
320 while (true) {
321 if (s->avail_out == 0 || (finish && s->avail_out < ZIP_BUF_SIZE)) {
322 zip_len = ZIP_BUF_SIZE - s->avail_out;
323 pdf->gone += (off_t) xfwrite(pdf->zipbuf, 1, zip_len, pdf->file);
324 pdf->last_byte = pdf->zipbuf[zip_len - 1];
325 s->next_out = (Bytef *) pdf->zipbuf;
326 s->avail_out = ZIP_BUF_SIZE;
327 }
328 if (finish) {
329 if (err == Z_STREAM_END) {
330 xfflush(pdf->file);
331 pdf->zip_write_state = NO_ZIP;
332 break;
333 }
334 flush = Z_FINISH;
335 } else {
336 if (s->avail_in == 0)
337 break;
338 flush = Z_NO_FLUSH;
339 }
340 err = deflate(s, flush);
341 if (err != Z_OK && err != Z_STREAM_END)
342 formatted_error("pdf backend","zlib deflate() failed (error code %d)", err);
343 }
344 pdf->stream_length = (off_t) s->total_out;
345 }
346
347 void zip_free(PDF pdf)
348 {
349 if (pdf->zipbuf != NULL) {
350 check_err(deflateEnd(pdf->c_stream), "deflateEnd");
351 xfree(pdf->zipbuf);
352 }
353 xfree(pdf->c_stream);
354 }
355
356 static void write_nozip(PDF pdf)
357 {
358 strbuf_s *buf = pdf->buf;
359 size_t l = strbuf_offset(buf);
360 if (l == 0)
361 return;
362 pdf->stream_length = pdf_offset(pdf) - pdf->save_offset;
363 pdf->gone += (off_t) xfwrite((char *) buf->data, sizeof(char), l, pdf->file);
364 pdf->last_byte = *(buf->p - 1);
365 }
366
367 /*tex
368
369 The PDF buffer is flushed by calling |pdf_flush|, which checks the variable
370 |zip_write_state| and will compress the buffer before flushing if neccesary.
371 We call |pdf_begin_stream| to begin a stream and |pdf_end_stream| to finish
372 it. The stream contents will be compressed if compression is turn on.
373
374 */
375
376 void pdf_flush(PDF pdf)
377 {
378 os_struct *os = pdf->os;
379 off_t saved_pdf_gone = pdf->gone;
380 switch (os->curbuf) {
381 case PDFOUT_BUF:
382 if (pdf->draftmode == 0) {
383 switch (pdf->zip_write_state) {
384 case NO_ZIP:
385 write_nozip(pdf);
386 break;
387 case ZIP_WRITING:
388 case ZIP_FINISH:
389 write_zip(pdf);
390 break;
391 default:
392 normal_error("pdf backend", "bad zip state");
393 }
394 } else
395 pdf->zip_write_state = NO_ZIP;
396 strbuf_seek(pdf->buf, 0);
397 if (saved_pdf_gone > pdf->gone)
398 normal_error("pdf backend", "file size exceeds architectural limits (pdf_gone wraps around)");
399 break;
400 case OBJSTM_BUF:
401 break;
402 default:
403 normal_error("pdf backend", "bad buffer state");
404 }
405 }
406
407 static void pdf_buffer_select(PDF pdf, buffer_e buf)
408 {
409 os_struct *os = pdf->os;
410 if (pdf->os_enable && buf == OBJSTM_BUF) {
411 /*tex Switch to object stream: */
412 os->curbuf = OBJSTM_BUF;
413 } else {
414 /*tex Switch to \PDF\ stream: */
415 os->curbuf = PDFOUT_BUF;
416 }
417 pdf->buf = os->buf[pdf->os->curbuf];
418 }
419
420 /*tex
421
422 We create new |/ObjStm| object if required, and set up cross reference info.
423
424 */
425
426 static void pdf_prepare_obj(PDF pdf, int k, int pdf_os_threshold)
427 {
428 os_struct *os = pdf->os;
429 strbuf_s *obuf = os->buf[OBJSTM_BUF];
430 if (pdf->objcompresslevel >= pdf_os_threshold)
431 pdf_buffer_select(pdf, OBJSTM_BUF);
432 else
433 pdf_buffer_select(pdf, PDFOUT_BUF);
434 switch (os->curbuf) {
435 case PDFOUT_BUF:
436 obj_offset(pdf, k) = pdf_offset(pdf);
437 /*tex Mark it as not included in any |ObjStm|. */
438 obj_os_idx(pdf, k) = PDF_OS_MAX_OBJS;
439 break;
440 case OBJSTM_BUF:
441 if (os->cur_objstm == 0) {
442 os->cur_objstm =
443 (unsigned int) pdf_create_obj(pdf, obj_type_objstm, 0);
444 os->idx = 0;
445 /*tex Start a fresh object stream. */
446 obuf->p = obuf->data;
447 /*tex Keep some statistics. */
448 os->ostm_ctr++;
449 }
450 obj_os_idx(pdf, k) = (int) os->idx;
451 obj_os_objnum(pdf, k) = (int) os->cur_objstm;
452 os->obj[os->idx].num = k;
453 os->obj[os->idx].off = obuf->p - obuf->data;
454 break;
455 default:
456 normal_error("pdf backend", "bad object state");
457 }
458 }
459
460 /*tex
461
462 We set the active buffer pointer and make sure that there are at least |n|
463 bytes free in that buffer, flushing happens if needed.
464
465 */
466
467 inline void pdf_room(PDF pdf, int n)
468 {
469 strbuf_s *buf = pdf->buf;
470 if ((size_t) (n + buf->p - buf->data) <= buf->size)
471 return;
472 if (pdf->os->curbuf == PDFOUT_BUF) {
473 if ((size_t) n > buf->size)
474 overflow("PDF output buffer", (unsigned) buf->size);
475 if ((size_t) (n + buf->p - buf->data) < buf->limit)
476 strbuf_room(buf, (size_t) n);
477 else
478 pdf_flush(pdf);
479 } else {
480 strbuf_room(buf, (size_t) n);
481 }
482 }
483
484 void pdf_out_block(PDF pdf, const char *s, size_t n)
485 {
486 size_t l;
487 strbuf_s *buf = pdf->buf;
488 do {
489 l = n;
490 if (l > buf->size)
491 l = buf->size;
492 pdf_room(pdf, (int) l);
493 (void) memcpy(buf->p, s, l);
494 buf->p += l;
495 s += l;
496 n -= l;
497 } while (n > 0);
498 }
499
500 __attribute__ ((format(printf, 2, 3)))
501 void pdf_printf(PDF pdf, const char *fmt, ...)
502 {
503 va_list args;
504 va_start(args, fmt);
505 if (pdf->printf_buf == NULL) {
506 pdf->printf_buf = xtalloc(PRINTF_BUF_SIZE, char);
507 }
508 (void) vsnprintf(pdf->printf_buf, PRINTF_BUF_SIZE, fmt, args);
509 pdf_puts(pdf, pdf->printf_buf);
510 va_end(args);
511 }
512
513 void pdf_print(PDF pdf, str_number s)
514 {
515 const char *ss;
516 size_t l;
517 if (s >= STRING_OFFSET) {
518 ss = (const char *) str_string(s);
519 l = str_length(s);
520 pdf_out_block(pdf, ss, l);
521 } else {
522 pdf_out(pdf, s);
523 }
524 }
525
526 void pdf_print_int(PDF pdf, longinteger n)
527 {
528 char s[24];
529 int w;
530 w = snprintf(s, 23, "%" LONGINTEGER_PRI "d", (LONGINTEGER_TYPE) n);
531 check_nprintf(w, 23);
532 pdf_out_block(pdf, (const char *) s, (size_t) w);
533 }
534
535 void print_pdffloat(PDF pdf, pdffloat f)
536 {
537 int64_t m = f.m;
538 if (m == 0) {
539 pdf_out(pdf, '0');
540 } else {
541 int e = f.e;
542 if (e == 0) {
543 /*tex division by |ten_pow[0] == 1| */
544 if (m == 1) {
545 pdf_out(pdf, '1');
546 } else {
547 char a[24];
548 snprintf(a, 23, "%" LONGINTEGER_PRI "i", (LONGINTEGER_TYPE) m);
549 pdf_puts(pdf, a);
550 }
551 } else {
552 int t = ten_pow[e] ;
553 if (t == m) {
554 pdf_out(pdf, '1');
555 } else {
556 int i, l, w;
557 char a[24];
558 if (m < 0) {
559 pdf_out(pdf, '-');
560 m *= -1;
561 }
562 l = m / t;
563 w = snprintf(a, 23, "%i", l);
564 pdf_out_block(pdf, (const char *) a, (size_t) w);
565 l = m % t;
566 if (l != 0) {
567 pdf_out(pdf, '.');
568 snprintf(a, 23, "%d", l + t);
569 for (i = e; i > 0; i--) {
570 if (a[i] != '0')
571 break;
572 a[i] = '\0';
573 }
574 pdf_puts(pdf, (a + 1));
575 }
576 }
577 }
578 }
579 }
580
581 void pdf_print_str(PDF pdf, const char *s)
582 {
583 const char *orig = s;
584 /*tex This initializes at the last string index. */
585 int l = (int) strlen(s) - 1;
586 if (l < 0) {
587 pdf_puts(pdf, "()");
588 return;
589 }
590 /*tex
591 The next might not really be safe as the string could be ``(a)xx(b)'' but
592 so far we never had an issue.
593 */
594 if ((s[0] == '(') && (s[l] == ')')) {
595 pdf_puts(pdf, s);
596 return;
597 }
598 if ((s[0] != '<') || (s[l] != '>') || odd((l + 1))) {
599 pdf_out(pdf, '(');
600 pdf_puts(pdf, s);
601 pdf_out(pdf, ')');
602 return;
603 }
604 s++;
605 while (isxdigit((unsigned char)*s))
606 s++;
607 if (s != orig + l) {
608 pdf_out(pdf, '(');
609 pdf_puts(pdf, orig);
610 pdf_out(pdf, ')');
611 return;
612 }
613 pdf_puts(pdf, orig);
614 }
615
616 /*tex A stream needs to have a stream dictionary also. */
617
618 void pdf_begin_stream(PDF pdf)
619 {
620 pdf_puts(pdf, "\nstream\n");
621 pdf_save_offset(pdf);
622 pdf_flush(pdf);
623 if (pdf->stream_deflate) {
624 pdf->zip_write_state = ZIP_WRITING;
625 }
626 pdf->stream_writing = true;
627 pdf->stream_length = 0;
628 pdf->last_byte = 0;
629 }
630
631 void pdf_end_stream(PDF pdf)
632 {
633 os_struct *os = pdf->os;
634 switch (os->curbuf) {
635 case PDFOUT_BUF:
636 if (pdf->zip_write_state == ZIP_WRITING)
637 pdf->zip_write_state = ZIP_FINISH;
638 /*tex This sets| pdf->last_byte|. */
639 pdf_flush(pdf);
640 break;
641 case OBJSTM_BUF:
642 normal_error("pdf backend", "bad buffer in end stream, case 1");
643 break;
644 default:
645 normal_error("pdf backend", "bad buffer in end stream, case 2");
646 }
647 pdf->stream_deflate = false;
648 pdf->stream_writing = false;
649 /*tex This doesn't really belong to the stream: */
650 pdf_out(pdf, '\n');
651 pdf_puts(pdf, "endstream");
652 /*tex Write the stream |/Length|. */
653
654 if (pdf->seek_write_length && pdf->draftmode == 0) {
655 xfseeko(pdf->file, (off_t)pdf->stream_length_offset+12, SEEK_SET, pdf->job_name);
656 fprintf(pdf->file, " ");
657 xfseeko(pdf->file, (off_t)pdf->stream_length_offset, SEEK_SET, pdf->job_name);
658 fprintf(pdf->file, "%" LONGINTEGER_PRI "i >>", (LONGINTEGER_TYPE) pdf->stream_length);
659 xfseeko(pdf->file, 0, SEEK_END, pdf->job_name);
660 }
661 pdf->seek_write_length = false;
662 }
663
664 /*tex
665
666 To print |scaled| value to \PDF\ output we need some subroutines to ensure
667 accurary.
668
669 */
670
671
672 /*tex We max out at $2^{31}-1$. */
673
674 #define max_integer 0x7FFFFFFF
675
676 /*tex scaled value corresponds to 100in, exact, 473628672 */
677
678 scaled one_hundred_inch = 7227 * 65536;
679
680 /*tex scaled value corresponds to 1in (rounded to 4736287) */
681
682 scaled one_inch = (7227 * 65536 + 50) / 100;
683
684 /*tex scaled value corresponds to 1truein (rounded!) */
685
686 scaled one_true_inch = (7227 * 65536 + 50) / 100;
687
688 /*tex scaled value corresponds to 100bp */
689
690 scaled one_hundred_bp = (7227 * 65536) / 72;
691
692 /*tex scaled value corresponds to 1bp (rounded to 65782) */
693
694 scaled one_bp = 65781;
695
696 /*tex
697
698 One basepoint is set to exactly 65781, as in \TEX\ itself, because this value
699 is also used for |\pdfpxdimen|.
700
701 */
702
703 int ten_pow[10] = {
704 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 /* $10^0..10^9$ */
705 };
706
707 /*tex
708
709 The function |divide_scaled| divides |s| by |m| using |dd| decimal digits of
710 precision.
711
712 */
713
714 scaled round_xn_over_d(scaled x, int n, unsigned int d)
715 {
716 boolean positive = true;
717 unsigned t, u, v;
718 if (x < 0) {
719 positive = !positive;
720 x = -(x);
721 }
722 if (n < 0) {
723 positive = !positive;
724 n = -(n);
725 }
726 t = (unsigned) ((x % 0100000) * n);
727 u = (unsigned) (((unsigned) (x) / 0100000) * (unsigned) n + (t / 0100000));
728 v = (u % d) * 0100000 + (t % 0100000);
729 if (u / d >= 0100000)
730 arith_error = true;
731 else
732 u = 0100000 * (u / d) + (v / d);
733 v = v % d;
734 if (2 * v >= d)
735 u++;
736 if (positive)
737 return (scaled) u;
738 else
739 return (-(scaled) u);
740 }
741
742 void pdf_add_bp(PDF pdf, scaled s)
743 {
744 pdffloat a;
745 pdfstructure *p = pdf->pstruct;
746 a.m = i64round(s * p->k1);
747 a.e = pdf->decimal_digits;
748 pdf_check_space(pdf);
749 print_pdffloat(pdf, a);
750 pdf_set_space(pdf);
751 }
752
753 typedef struct {
754 int obj_type;
755 pdf_object_list *list;
756 } pr_entry;
757
758 static int comp_page_resources(const void *pa, const void *pb, void *p)
759 {
760 int a = ((const pr_entry *) pa)->obj_type;
761 int b = ((const pr_entry *) pb)->obj_type;
762 (void) p;
763 if (a > b)
764 return 1;
765 if (a < b)
766 return -1;
767 return 0;
768 }
769
770 void addto_page_resources(PDF pdf, pdf_obj_type t, int k)
771 {
772 pdf_resource_struct *re;
773 pr_entry *pr, tmp;
774 void **pp;
775 pdf_object_list *p, *item = NULL;
776 re = pdf->page_resources;
777 if (re->resources_tree == NULL) {
778 re->resources_tree = avl_create(comp_page_resources, NULL, &avl_xallocator);
779 if (re->resources_tree == NULL)
780 formatted_error("pdf backend","addto_page_resources(): avl_create() page_resource_tree failed");
781 }
782 tmp.obj_type = t;
783 pr = (pr_entry *) avl_find(re->resources_tree, &tmp);
784 if (pr == NULL) {
785 pr = xtalloc(1, pr_entry);
786 pr->obj_type = t;
787 pr->list = NULL;
788 pp = avl_probe(re->resources_tree, pr);
789 if (pp == NULL)
790 formatted_error("pdf backend","addto_page_resources(): avl_probe() out of memory in insertion");
791 }
792 if (pr->list == NULL) {
793 item = xtalloc(1, pdf_object_list);
794 item->link = NULL;
795 item->info = k;
796 pr->list = item;
797 if (obj_type(pdf, k) == (int)t) {
798 /*tex |k| is an object number. */
799 set_obj_scheduled(pdf, k);
800 }
801 } else {
802 for (p = pr->list; p->info != k && p->link != NULL; p = p->link);
803 if (p->info != k) {
804 item = xtalloc(1, pdf_object_list);
805 item->link = NULL;
806 item->info = k;
807 p->link = item;
808 if (obj_type(pdf, k) == (int)t)
809 set_obj_scheduled(pdf, k);
810 }
811 }
812 }
813
814 pdf_object_list *get_page_resources_list(PDF pdf, pdf_obj_type t)
815 {
816 pdf_resource_struct *re = pdf->page_resources;
817 pr_entry *pr, tmp;
818 if (re == NULL || re->resources_tree == NULL)
819 return NULL;
820 tmp.obj_type = t;
821 pr = (pr_entry *) avl_find(re->resources_tree, &tmp);
822 if (pr == NULL)
823 return NULL;
824 return pr->list;
825 }
826
827 static void reset_page_resources(PDF pdf)
828 {
829 pdf_resource_struct *re = pdf->page_resources;
830 pr_entry *p;
831 struct avl_traverser t;
832 pdf_object_list *l1, *l2;
833 if (re == NULL || re->resources_tree == NULL)
834 return;
835 avl_t_init(&t, re->resources_tree);
836 for (p = avl_t_first(&t, re->resources_tree); p != NULL; p = avl_t_next(&t)) {
837 if (p->list != NULL) {
838 for (l1 = p->list; l1 != NULL; l1 = l2) {
839 l2 = l1->link;
840 free(l1);
841 }
842 /*tex We reset but the AVL tree remains! */
843 p->list = NULL;
844 }
845 }
846 }
847
848 static void destroy_pg_res_tree(void *pa, void *param)
849 {
850 (void) param;
851 xfree(pa);
852 }
853
854 static void destroy_page_resources_tree(PDF pdf)
855 {
856 pdf_resource_struct *re = pdf->page_resources;
857 reset_page_resources(pdf);
858 if (re->resources_tree != NULL)
859 avl_destroy(re->resources_tree, destroy_pg_res_tree);
860 re->resources_tree = NULL;
861 }
862
863 static void pdf_print_fw_int(PDF pdf, longinteger n)
864 {
865 unsigned char digits[11];
866
867 int k = 10;
868 do {
869 k--;
870 digits[k] = (unsigned char) ('0' + (n % 10));
871 n /= 10;
872 } while (k != 0);
873 if (n!=0) {
874 /*tex The absolute value of $n$ is greater than 9999999999. */
875 normal_error("pdf backend", "offset exceeds 10 bytes, try enabling object compression.");
876 }
877 digits[10]='\0';
878 pdf_puts(pdf, (const char *) digits);
879 }
880
881 /*tex
882
883 We print out an integer |n| as a fixed number |w| of bytes,. This is used in
884 the |XRef| cross-reference stream creator.
885
886 */
887
888 static void pdf_out_bytes(PDF pdf, longinteger n, size_t w)
889 {
890 /*tex The number of digits in a number being output. */
891 unsigned char bytes[8];
892 int k = (int) w;
893 do {
894 k--;
895 bytes[k] = (unsigned char) (n % 256);
896 n /= 256;
897 } while (k != 0);
898 pdf_out_block(pdf, (const char *) bytes, w);
899 }
900
901 void pdf_print_str_ln(PDF pdf, const char *s)
902 {
903 pdf_print_str(pdf, s);
904 pdf_out(pdf, '\n');
905 }
906
907 void pdf_print_toks(PDF pdf, halfword p)
908 {
909 int len = 0;
910 char *s = tokenlist_to_cstring(p, true, &len);
911 if (len > 0) {
912 pdf_check_space(pdf);
913 pdf_puts(pdf, s);
914 pdf_set_space(pdf);
915 }
916 xfree(s);
917 }
918
919 /*
920 void pdf_add_rect_spec(PDF pdf, halfword r)
921 {
922 pdf_add_bp(pdf, pdf_ann_left(r));
923 pdf_add_bp(pdf, pdf_ann_bottom(r));
924 pdf_add_bp(pdf, pdf_ann_right(r));
925 pdf_add_bp(pdf, pdf_ann_top(r));
926 }
927 */
928
929 void pdf_add_rect_spec(PDF pdf, halfword r)
930 {
931 /* the check is now here */
932 pdf_add_bp(pdf, (pdf_ann_left(r) < pdf_ann_right(r) ? pdf_ann_left(r) : pdf_ann_right(r) ) - pdf_ann_margin(r));
933 pdf_add_bp(pdf, (pdf_ann_bottom(r) < pdf_ann_top(r) ? pdf_ann_bottom(r) : pdf_ann_top(r) ) - pdf_ann_margin(r));
934 pdf_add_bp(pdf, (pdf_ann_left(r) < pdf_ann_right(r) ? pdf_ann_right(r) : pdf_ann_left(r) ) + pdf_ann_margin(r));
935 pdf_add_bp(pdf, (pdf_ann_bottom(r) < pdf_ann_top(r) ? pdf_ann_top(r) : pdf_ann_bottom(r)) + pdf_ann_margin(r));
936 }
937
938 void pdf_rectangle(PDF pdf, halfword r)
939 {
940 pdf_add_name(pdf, "Rect");
941 pdf_begin_array(pdf);
942 pdf_add_rect_spec(pdf, r);
943 pdf_end_array(pdf);
944 }
945
946 static void init_pdf_outputparameters(PDF pdf)
947 {
948 int pk_mode;
949 pdf->draftmode = fix_int(draft_mode_par, 0, 1);
950 pdf->compress_level = fix_int(pdf_compress_level, 0, 9);
951 pdf->decimal_digits = fix_int(pdf_decimal_digits, 3, 5);
952 pdf->gamma = fix_int(pdf_gamma, 0, 1000000);
953 pdf->image_gamma = fix_int(pdf_image_gamma, 0, 1000000);
954 pdf->image_hicolor = fix_int(pdf_image_hicolor, 0, 1);
955 pdf->image_apply_gamma = fix_int(pdf_image_apply_gamma, 0, 1);
956 pdf->objcompresslevel = fix_int(pdf_obj_compress_level, 0, MAX_OBJ_COMPRESS_LEVEL);
957 pdf->recompress = fix_int(pdf_recompress, 0, 1);
958 pdf->inclusion_copy_font = fix_int(pdf_inclusion_copy_font, 0, 1);
959 pdf->pk_resolution = fix_int(pdf_pk_resolution, 72, 8000);
960 pdf->pk_fixed_dpi = fix_int(pdf_pk_fixed_dpi, 0, 1);
961 if (((pdf->major_version > 1) || (pdf->minor_version >= 5)) && (pdf->objcompresslevel > 0)) {
962 pdf->os_enable = true;
963 } else {
964 if (pdf->objcompresslevel > 0) {
965 normal_warning("pdf backend","objcompresslevel > 0 requires minorversion > 4");
966 pdf->objcompresslevel = 0;
967 }
968 pdf->os_enable = false;
969 }
970 if (pdf->pk_resolution == 0) {
971 /*tex If not set from format file or by user take it from \.{texmf.cnf}. */
972 pdf->pk_resolution = pk_dpi;
973 }
974 pdf->pk_scale_factor = divide_scaled(72, pdf->pk_resolution, pk_decimal_digits(pdf,5));
975 if (!callback_defined(read_pk_file_callback)) {
976 pk_mode = pdf_pk_mode;
977 if (pk_mode != null) {
978 char *s = tokenlist_to_cstring(pk_mode, true, NULL);
979 kpse_init_prog("LUATEX", (unsigned) pdf->pk_resolution, s, nil);
980 xfree(s);
981 } else {
982 kpse_init_prog("LUATEX", (unsigned) pdf->pk_resolution, nil, nil);
983 }
984 if (!kpse_var_value("MKTEXPK"))
985 kpse_set_program_enabled(kpse_pk_format, 1, kpse_src_cmdline);
986 }
987 set_job_id(pdf, year_par, month_par, day_par, time_par);
988 if ((pdf_unique_resname > 0) && (pdf->resname_prefix == NULL))
989 pdf->resname_prefix = get_resname_prefix(pdf);
990 }
991
992 /*tex
993
994 This checks that we have a name for the generated PDF file and that it's
995 open.
996
997 */
998
999 void pdf_write_header(PDF pdf)
1000 {
1001 /*tex Initialize variables for \PDF\ output. */
1002 fix_pdf_version(pdf);
1003 init_pdf_outputparameters(pdf);
1004 fix_pdf_draftmode(pdf);
1005 /*tex Write \PDF\ header */
1006 pdf_printf(pdf, "%%PDF-%d.%d\n", pdf->major_version, pdf->minor_version);
1007 /* Some binary crap. */
1008 pdf_out(pdf, '%');
1009 pdf_out(pdf, 'L' + 128);
1010 pdf_out(pdf, 'U' + 128);
1011 pdf_out(pdf, 'A' + 128);
1012 pdf_out(pdf, 'T' + 128);
1013 pdf_out(pdf, 'E' + 128);
1014 pdf_out(pdf, 'X' + 128);
1015 pdf_out(pdf, 'P' + 128);
1016 pdf_out(pdf, 'D' + 128);
1017 pdf_out(pdf, 'F' + 128);
1018 pdf_out(pdf, '\n');
1019 }
1020
1021 void pdf_open_file(PDF pdf) {
1022 ensure_output_file_open(pdf, ".pdf");
1023 }
1024
1025 void ensure_output_state(PDF pdf, output_state s)
1026 {
1027 if (pdf->o_state < s) {
1028 if (s > ST_INITIAL) {
1029 ensure_output_state(pdf, s - 1);
1030 }
1031 switch (s - 1) {
1032 case ST_INITIAL:
1033 fix_o_mode();
1034 break;
1035 case ST_OMODE_FIX:
1036 backend_out_control[BACKEND_INDEX(backend_control_open_file)](pdf);
1037 break;
1038 case ST_FILE_OPEN:
1039 backend_out_control[BACKEND_INDEX(backend_control_write_header)](pdf);
1040 break;
1041 case ST_HEADER_WRITTEN:
1042 break;
1043 case ST_FILE_CLOSED:
1044 break;
1045 default:
1046 normal_error("pdf backend","weird output state");
1047 }
1048 pdf->o_state++;
1049 }
1050 }
1051
1052 /*tex
1053
1054 Write out an accumulated object stream. The object number and byte offset
1055 pairs are generated and appended to the ready buffered object stream. By this
1056 the value of \.{/First} can be calculated. Then a new \.{/ObjStm} object is
1057 generated, and everything is copied to the PDF output buffer, where also
1058 compression is done. When calling this procedure, |pdf_os_mode| must be
1059 |true|.
1060
1061 */
1062
1063 static void pdf_os_write_objstream(PDF pdf)
1064 {
1065 os_struct *os = pdf->os;
1066 /*tex |n1|, |n2|: |ObjStm| buffer may be reallocated! */
1067 unsigned int i, j, n1, n2;
1068 strbuf_s *obuf = os->buf[OBJSTM_BUF];
1069 if (os->cur_objstm == 0) {
1070 /*tex No object stream started. */
1071 return;
1072 }
1073 /*tex Remember end of collected object stream contents. */
1074 n1 = (unsigned int) strbuf_offset(obuf);
1075 /*tex This is needed here to calculate |/First| for the |ObjStm| dict */
1076 for (i = 0, j = 0; i < os->idx; i++) {
1077 /*tex Add object-number/byte-offset list to buffer. */
1078 pdf_print_int(pdf, (int) os->obj[i].num);
1079 pdf_out(pdf, ' ');
1080 pdf_print_int(pdf, (int) os->obj[i].off);
1081 if (j == 9 || i == os->idx - 1) {
1082 /*tex Print out in groups of ten for better readability. */
1083 pdf_out(pdf, '\n');
1084 j = 0;
1085 } else {
1086 pdf_out(pdf, ' ');
1087 j++;
1088 }
1089 }
1090 /*tex Remember current buffer end. */
1091 n2 = (unsigned int) strbuf_offset(obuf);
1092 /*tex Switch to \PDF\ stream writing. */
1093 pdf_begin_obj(pdf, (int) os->cur_objstm, OBJSTM_NEVER);
1094 pdf_begin_dict(pdf);
1095 pdf_dict_add_name(pdf, "Type", "ObjStm");
1096 /*tex The number of objects in |ObjStm|. */
1097 pdf_dict_add_int(pdf, "N", (int) os->idx);
1098 pdf_dict_add_int(pdf, "First", (int) (n2 - n1));
1099 pdf_dict_add_streaminfo(pdf);
1100 pdf_end_dict(pdf);
1101 pdf_begin_stream(pdf);
1102 /*tex Write object-number/byte-offset list. */
1103 pdf_out_block(pdf, (const char *) (obuf->data + n1), (size_t) (n2 - n1));
1104 /*tex Write collected object stream contents. */
1105 pdf_out_block(pdf, (const char *) obuf->data, (size_t) n1);
1106 pdf_end_stream(pdf);
1107 pdf_end_obj(pdf);
1108 /*tex We force object stream generation next time. */
1109 os->cur_objstm = 0;
1110 }
1111
1112 /*tex Here comes a bunch of flushers: */
1113
1114 void pdf_begin_dict(PDF pdf)
1115 {
1116 pdf_check_space(pdf);
1117 pdf_puts(pdf, "<<");
1118 pdf_set_space(pdf);
1119 }
1120
1121 void pdf_end_dict(PDF pdf)
1122 {
1123 pdf_check_space(pdf);
1124 pdf_puts(pdf, ">>");
1125 pdf_set_space(pdf);
1126 }
1127
1128 void pdf_dict_add_bool(PDF pdf, const char *key, int i)
1129 {
1130 pdf_add_name(pdf, key);
1131 pdf_add_bool(pdf, i);
1132 }
1133
1134 void pdf_dict_add_int(PDF pdf, const char *key, int i)
1135 {
1136 pdf_add_name(pdf, key);
1137 pdf_add_int(pdf, i);
1138 }
1139
1140 void pdf_dict_add_name(PDF pdf, const char *key, const char *val)
1141 {
1142 pdf_add_name(pdf, key);
1143 pdf_add_name(pdf, val);
1144 }
1145
1146 void pdf_dict_add_string(PDF pdf, const char *key, const char *val)
1147 {
1148 if (val == NULL)
1149 return;
1150 pdf_add_name(pdf, key);
1151 pdf_check_space(pdf);
1152 pdf_print_str(pdf, val);
1153 pdf_set_space(pdf);
1154 }
1155
1156 void pdf_dict_add_ref(PDF pdf, const char *key, int num)
1157 {
1158 pdf_add_name(pdf, key);
1159 pdf_add_ref(pdf, num);
1160 }
1161
1162 void pdf_add_null(PDF pdf)
1163 {
1164 pdf_check_space(pdf);
1165 pdf_puts(pdf, "null");
1166 pdf_set_space(pdf);
1167 }
1168
1169 void pdf_add_bool(PDF pdf, int i)
1170 {
1171 pdf_check_space(pdf);
1172 if (i == 0)
1173 pdf_puts(pdf, "false");
1174 else
1175 pdf_puts(pdf, "true");
1176 pdf_set_space(pdf);
1177 }
1178
1179 void pdf_add_int(PDF pdf, int i)
1180 {
1181 pdf_check_space(pdf);
1182 pdf_print_int(pdf, i);
1183 pdf_set_space(pdf);
1184 }
1185
1186 void pdf_add_longint(PDF pdf, longinteger n)
1187 {
1188 pdf_check_space(pdf);
1189 pdf_print_int(pdf, n);
1190 pdf_set_space(pdf);
1191 }
1192
1193 void pdf_add_string(PDF pdf, const char *s)
1194 {
1195 pdf_check_space(pdf);
1196 pdf_print_str(pdf, s);
1197 pdf_set_space(pdf);
1198 }
1199
1200 void pdf_add_name(PDF pdf, const char *name)
1201 {
1202 pdf_check_space(pdf);
1203 pdf_out(pdf, '/');
1204 pdf_puts(pdf, name);
1205 pdf_set_space(pdf);
1206 }
1207
1208 void pdf_add_ref(PDF pdf, int num)
1209 {
1210 pdf_check_space(pdf);
1211 pdf_print_int(pdf, num);
1212 pdf_puts(pdf, " 0 R");
1213 pdf_set_space(pdf);
1214 }
1215
1216 /*tex
1217
1218 When we add the stream length and filter entries to a stream dictionary,
1219 remember file position for seek.
1220
1221 */
1222
1223 void pdf_dict_add_streaminfo(PDF pdf)
1224 {
1225 if (pdf->compress_level > 0) {
1226 pdf_dict_add_name(pdf, "Filter", "FlateDecode");
1227 pdf->stream_deflate = true;
1228 }
1229 pdf_add_name(pdf, "Length");
1230 pdf->stream_length_offset = pdf_offset(pdf) + 1;
1231 /*tex Fill in length at |pdf_end_stream| call. */
1232 pdf->seek_write_length = true;
1233 /*tex We reserve space for 10 decimal digits plus space. */
1234 pdf_puts(pdf, " x ");
1235 pdf_set_space(pdf);
1236 }
1237
1238 void pdf_begin_array(PDF pdf)
1239 {
1240 pdf_check_space(pdf);
1241 pdf_out(pdf, '[');
1242 pdf_set_space(pdf);
1243 }
1244
1245 void pdf_end_array(PDF pdf)
1246 {
1247 pdf_check_space(pdf);
1248 pdf_out(pdf, ']');
1249 pdf_set_space(pdf);
1250 }
1251
1252 void pdf_begin_obj(PDF pdf, int i, int pdf_os_threshold)
1253 {
1254 os_struct *os = pdf->os;
1255 ensure_output_state(pdf, ST_HEADER_WRITTEN);
1256 pdf_prepare_obj(pdf, i, pdf_os_threshold);
1257 switch (os->curbuf) {
1258 case PDFOUT_BUF:
1259 pdf_printf(pdf, "%d 0 obj\n", (int) i);
1260 break;
1261 case OBJSTM_BUF:
1262 if (pdf->compress_level == 0) {
1263 /*tex Some debugging help. */
1264 pdf_printf(pdf, "%% %d 0 obj\n", (int) i);
1265 }
1266 break;
1267 default:
1268 normal_error("pdf backend","weird begin object");
1269 }
1270 pdf_reset_space(pdf);
1271 }
1272
1273 void pdf_end_obj(PDF pdf)
1274 {
1275 os_struct *os = pdf->os;
1276 switch (os->curbuf) {
1277 case PDFOUT_BUF:
1278 /*tex End a \PDF\ object. */
1279 pdf_puts(pdf, "\nendobj\n");
1280 break;
1281 case OBJSTM_BUF:
1282 /*tex Tthe number of objects collected so far in ObjStm: */
1283 os->idx++;
1284 /*tex Only for statistics: */
1285 os->o_ctr++;
1286 if (os->idx == PDF_OS_MAX_OBJS) {
1287 pdf_os_write_objstream(pdf);
1288 } else {
1289 /*tex Adobe Reader seems to need this. */
1290 pdf_out(pdf, '\n');
1291 }
1292 break;
1293 default:
1294 normal_error("pdf backend","weird end object");
1295 }
1296 }
1297
1298 /*
1299 Needed for embedding fonts.
1300
1301 */
1302
1303 pdf_obj *pdf_new_stream(void)
1304 {
1305 pdf_obj *stream = xmalloc(sizeof(pdf_obj));
1306 stream->length = 0;
1307 stream->data = NULL;
1308 return stream;
1309 }
1310
1311 void pdf_add_stream(pdf_obj * stream, unsigned char *buf, long len)
1312 {
1313 int i;
1314 assert(stream != NULL);
1315 if (stream->data == NULL) {
1316 stream->data = xmalloc((unsigned) len);
1317 } else {
1318 stream->data =
1319 xrealloc(stream->data, (unsigned) len + (unsigned) stream->length);
1320 }
1321 for (i = 0; i < len; i++) {
1322 *(stream->data + stream->length + i) = *(buf + i);
1323 }
1324 stream->length += (unsigned) len;
1325 }
1326
1327 void pdf_release_obj(pdf_obj * stream)
1328 {
1329 if (stream != NULL) {
1330 if (stream->data != NULL) {
1331 xfree(stream->data);
1332 }
1333 xfree(stream);
1334 }
1335 }
1336
1337 /*
1338
1339 This one converts any string given in in in an allowed PDF string which can
1340 be handled by printf et.al.: \.{\\} is escaped to \.{\\\\}, parenthesis are
1341 escaped and control characters are octal encoded. This assumes that the
1342 string does not contain any already escaped characters!
1343
1344 */
1345
1346 char *convertStringToPDFString(const char *in, int len)
1347 {
1348 static char pstrbuf[MAX_PSTRING_LEN];
1349 char *out = pstrbuf;
1350 int i, j, k;
1351 char buf[5];
1352 j = 0;
1353 for (i = 0; i < len; i++) {
1354 check_buf((unsigned) j + sizeof(buf), MAX_PSTRING_LEN);
1355 if (((unsigned char) in[i] < '!') || ((unsigned char) in[i] > '~')) {
1356 /*tex Convert control characters into octal. */
1357 k = snprintf(buf, sizeof(buf), "\\%03o", (unsigned int) (unsigned char) in[i]);
1358 check_nprintf(k, sizeof(buf));
1359 out[j++] = buf[0];
1360 out[j++] = buf[1];
1361 out[j++] = buf[2];
1362 out[j++] = buf[3];
1363 } else if ((in[i] == '(') || (in[i] == ')')) {
1364 /*tex Escape parenthesis: */
1365 out[j++] = '\\';
1366 out[j++] = in[i];
1367 } else if (in[i] == '\\') {
1368 /*tex Escape backslash: */
1369 out[j++] = '\\';
1370 out[j++] = '\\';
1371 } else {
1372 /* Copy char : */
1373 out[j++] = in[i];
1374 }
1375 }
1376 out[j] = '\0';
1377 return pstrbuf;
1378 }
1379
1380 /*tex
1381
1382 This one converts any string given in in in an allowed PDF string which is
1383 hexadecimal encoded; |sizeof(out)| should be at least $|lin|*2+1$.
1384
1385 */
1386
1387 static void convertStringToHexString(const char *in, char *out, int lin)
1388 {
1389 int i, k;
1390 char buf[3];
1391 int j = 0;
1392 for (i = 0; i < lin; i++) {
1393 k = snprintf(buf, sizeof(buf), "%02X", (unsigned int) (unsigned char) in[i]);
1394 check_nprintf(k, sizeof(buf));
1395 out[j++] = buf[0];
1396 out[j++] = buf[1];
1397 }
1398 out[j] = '\0';
1399 }
1400
1401 /*tex
1402
1403 We compute the ID string as per PDF specification 1.4 9.3 that stipulates
1404 only that the two IDs must be identical when the file is created and that
1405 they should be reasonably unique. Since it's difficult to get the file size
1406 at this point in the execution of pdfTeX and scanning the info dict is also
1407 difficult, we start with a simpler implementation using just the first two
1408 items.
1409
1410 A user supplied trailerid had better be an array! So maybe we need to check
1411 for |[]| and error otherwise.
1412
1413 */
1414
1415 static void print_ID(PDF pdf)
1416 {
1417 if ((pdf_suppress_optional_info & 512) == 0) {
1418 const char *p = NULL;
1419 pdf_add_name(pdf, "ID");
1420 p = get_pdf_table_string("trailerid");
1421 if (p && strlen(p) > 0) {
1422 pdf_puts(pdf,p);
1423 } else if (pdf_trailer_id != 0) {
1424 /*tex The user provided one: */
1425 pdf_print_toks(pdf, pdf_trailer_id);
1426 } else {
1427 /*tex The system provided one: */
1428 time_t t;
1429 size_t size;
1430 char time_str[32];
1431 md5_state_t state;
1432 md5_byte_t digest[16];
1433 char id[64];
1434 char pwd[4096];
1435 md5_init(&state);
1436 t = pdf->start_time;
1437 size = strftime(time_str, sizeof(time_str), "%Y%m%dT%H%M%SZ", gmtime(&t));
1438 md5_append(&state, (const md5_byte_t *) time_str, (int) size);
1439 if (getcwd(pwd, sizeof(pwd)) == NULL) {
1440 formatted_error("pdf backend","getcwd() failed (%s), (path too long?)", strerror(errno));
1441 }
1442 #ifdef WIN32
1443 {
1444 char *p;
1445 for (p = pwd; *p; p++) {
1446 if (*p == '\\')
1447 *p = '/';
1448 else if (IS_KANJI(p))
1449 p++;
1450 }
1451 }
1452 #endif
1453 md5_append(&state, (const md5_byte_t *) pwd, (int) strlen(pwd));
1454 md5_append(&state, (const md5_byte_t *) "/", 1);
1455 md5_append(&state, (const md5_byte_t *) pdf->file_name, (int) strlen(pdf->file_name));
1456 md5_finish(&state, digest);
1457 convertStringToHexString((char *) digest, id, 16);
1458 pdf_begin_array(pdf);
1459 pdf_check_space(pdf);
1460 pdf_printf(pdf, "<%s> <%s>", id, id);
1461 pdf_set_space(pdf);
1462 pdf_end_array(pdf);
1463 }
1464 }
1465 }
1466
1467 /*tex
1468
1469 Here we print the |/CreationDate| entry in the form
1470 |(D:YYYYMMDDHHmmSSOHH'mm')|. The main difficulty is get the time zone offset.
1471 |strftime()| does this in ISO C99 (e.g. newer glibc) with \%z, but we have to
1472 work with other systems (e.g. Solaris 2.5).
1473
1474 */
1475
1476 #define TIME_STR_SIZE 30
1477
1478 static void makepdftime(PDF pdf)
1479 {
1480 struct tm lt, gmt;
1481 size_t size;
1482 int i, off, off_hours, off_mins;
1483 time_t t = pdf->start_time;
1484 char *time_str = pdf->start_time_str;
1485 /*tex Get the time. */
1486 if (utc_option) {
1487 lt = *gmtime(&t);
1488 } else {
1489 lt = *localtime(&t);
1490 }
1491 size = strftime(time_str, TIME_STR_SIZE, "D:%Y%m%d%H%M%S", &lt);
1492 /*tex Expected format: |YYYYmmddHHMMSS|. */
1493 if (size == 0) {
1494 /*tex Unexpected, contents of |time_str| is undefined .*/
1495 time_str[0] = '\0';
1496 return;
1497 }
1498 /*tex
1499 A correction for seconds. the PDF reference expects 00..59, therefore we
1500 map 60 and 61 to 59.
1501 */
1502 if (time_str[14] == '6') {
1503 time_str[14] = '5';
1504 time_str[15] = '9';
1505 /*tex For safety: */
1506 time_str[16] = '\0';
1507 }
1508 /*tex Get the time zone offset. */
1509 gmt = *gmtime(&t);
1510 off = 60 * (lt.tm_hour - gmt.tm_hour) + lt.tm_min - gmt.tm_min;
1511 if (lt.tm_year != gmt.tm_year) {
1512 off += (lt.tm_year > gmt.tm_year) ? 1440 : -1440;
1513 } else if (lt.tm_yday != gmt.tm_yday) {
1514 off += (lt.tm_yday > gmt.tm_yday) ? 1440 : -1440;
1515 }
1516 if (off == 0) {
1517 time_str[size++] = 'Z';
1518 time_str[size] = 0;
1519 } else {
1520 off_hours = off / 60;
1521 off_mins = abs(off - off_hours * 60);
1522 i = snprintf(&time_str[size], 9, "%+03d'%02d'", off_hours, off_mins);
1523 check_nprintf(i, 9);
1524 }
1525 pdf->start_time = t;
1526 }
1527
1528 void initialize_start_time(PDF pdf)
1529 {
1530 if (pdf->start_time == 0) {
1531 pdf->start_time = get_start_time();
1532 pdf->start_time_str = xtalloc(TIME_STR_SIZE, char);
1533 makepdftime(pdf);
1534 }
1535 }
1536
1537 char *getcreationdate(PDF pdf)
1538 {
1539 initialize_start_time(pdf);
1540 return pdf->start_time_str;
1541 }
1542
1543 void remove_pdffile(PDF pdf)
1544 {
1545 if (pdf != NULL) {
1546 if (!kpathsea_debug && pdf->file_name && (pdf->draftmode == 0)) {
1547 xfclose(pdf->file, pdf->file_name);
1548 remove(pdf->file_name);
1549 }
1550 }
1551 }
1552
1553 /*tex We use this checker in other modules. It is not pdf specific. */
1554
1555 void check_o_mode(PDF pdf, const char *s, int o_mode_bitpattern, boolean strict)
1556 {
1557
1558 output_mode o_mode;
1559 const char *m = NULL;
1560 if (lua_only) {
1561 boolean texlua_img = false;
1562 get_lua_boolean("texconfig", "texlua_img", &texlua_img);
1563 if (texlua_img) {
1564 /* Ok, lets hope that you know what you are doing! */
1565 } else {
1566 normal_error("lua only","no backend present, needed for what you asked for");
1567 return ;
1568 }
1569 }
1570 if (output_mode_used == OMODE_NONE)
1571 o_mode = get_o_mode();
1572 else
1573 o_mode = output_mode_used;
1574 /*tex This is used by synctex, we need to use output_mode_used there. */
1575 pdf->o_mode = output_mode_used;
1576 if (!((1 << o_mode) & o_mode_bitpattern)) {
1577 switch (o_mode) {
1578 case OMODE_DVI:
1579 m = "DVI";
1580 break;
1581 case OMODE_PDF:
1582 m = "PDF";
1583 break;
1584 default:
1585 normal_error("pdf backend","weird output state");
1586 }
1587 if (strict)
1588 formatted_error("pdf backend", "%s not allowed in %s mode (outputmode = %d)",s, m, (int) output_mode_par);
1589 else
1590 formatted_warning("pdf backend", "%s not allowed in %s mode (outputmode = %d)",s, m, (int) output_mode_par);
1591 } else if (strict)
1592 ensure_output_state(pdf, ST_HEADER_WRITTEN);
1593 }
1594
1595 void ensure_output_file_open(PDF pdf, const char *ext)
1596 {
1597 char *fn;
1598 if (pdf->file_name != NULL)
1599 return;
1600 if (job_name == 0)
1601 open_log_file();
1602 fn = pack_job_name(ext);
1603 if (pdf->draftmode == 0 || output_mode_used == OMODE_DVI) {
1604 while (!lua_b_open_out(&pdf->file, fn))
1605 fn = prompt_file_name("file name for output", ext);
1606 }
1607 pdf->file_name = fn;
1608 }
1609
1610 /*tex till here */
1611
1612 void set_job_id(PDF pdf, int year, int month, int day, int time)
1613 {
1614 char *name_string, *format_string, *s;
1615 size_t slen;
1616 int i;
1617 if (pdf->job_id_string != NULL)
1618 return;
1619 name_string = makecstring(job_name);
1620 format_string = makecstring(format_ident);
1621 slen = SMALL_BUF_SIZE + strlen(name_string) + strlen(format_string) + strlen(luatex_banner);
1622 s = xtalloc(slen, char);
1623 /*tex The \WEBC\ version string starts with a space. (Really?) */
1624 i = snprintf(s, slen, "%.4d/%.2d/%.2d %.2d:%.2d %s %s %s", year, month, day, time / 60, time % 60, name_string, format_string, luatex_banner);
1625 check_nprintf(i, slen);
1626 pdf->job_id_string = xstrdup(s);
1627 xfree(s);
1628 xfree(name_string);
1629 xfree(format_string);
1630 }
1631
1632 char *get_resname_prefix(PDF pdf)
1633 {
1634 static char name_str[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1635 /*tex We make a tag of 6 characters long. */
1636 static char prefix[7];
1637 short i;
1638 size_t base = strlen(name_str);
1639 unsigned long crc = crc32(0L, Z_NULL, 0);
1640 crc = crc32(crc, (Bytef *) pdf->job_id_string, (uInt) strlen(pdf->job_id_string));
1641 for (i = 0; i < 6; i++) {
1642 prefix[i] = name_str[crc % base];
1643 crc /= base;
1644 }
1645 prefix[6] = '\0';
1646 return prefix;
1647 }
1648
1649 void pdf_begin_page(PDF pdf)
1650 {
1651 int xform_attributes;
1652 int xform_type = 0;
1653 scaled form_margin = pdf_xform_margin;
1654 ensure_output_state(pdf, ST_HEADER_WRITTEN);
1655 init_pdf_pagecalculations(pdf);
1656 if (pdf->page_resources == NULL) {
1657 pdf->page_resources = xtalloc(1, pdf_resource_struct);
1658 pdf->page_resources->resources_tree = NULL;
1659 }
1660 pdf->page_resources->last_resources = pdf_create_obj(pdf, obj_type_others, 0);
1661 reset_page_resources(pdf);
1662
1663 if (global_shipping_mode == SHIPPING_PAGE) {
1664 pdf->last_page = pdf_get_obj(pdf, obj_type_page, total_pages + 1, 0);
1665 /*tex Mark that this page has been created. */
1666 set_obj_aux(pdf, pdf->last_page, 1);
1667 pdf->last_stream = pdf_create_obj(pdf, obj_type_pagestream, 0);
1668 pdf_begin_obj(pdf, pdf->last_stream, OBJSTM_NEVER);
1669 pdf->last_thread = null;
1670 pdf_begin_dict(pdf);
1671 } else {
1672 xform_type = obj_xform_type(pdf, pdf_cur_form) ;
1673 pdf_begin_obj(pdf, pdf_cur_form, OBJSTM_NEVER);
1674 pdf->last_stream = pdf_cur_form;
1675 /*tex Write out the |Form| stream header */
1676 pdf_begin_dict(pdf);
1677 if (xform_type == 0) {
1678 pdf_dict_add_name(pdf, "Type", "XObject");
1679 pdf_dict_add_name(pdf, "Subtype", "Form");
1680 pdf_dict_add_int(pdf, "FormType", 1);
1681 }
1682 xform_attributes = pdf_xform_attr;
1683 /*tex Now stored in the object: */
1684 form_margin = obj_xform_margin(pdf, pdf_cur_form);
1685 if (xform_attributes != null)
1686 pdf_print_toks(pdf, xform_attributes);
1687 print_pdf_table_string(pdf, "xformattributes");
1688 if (obj_xform_attr(pdf, pdf_cur_form) != null) {
1689 pdf_print_toks(pdf, obj_xform_attr(pdf, pdf_cur_form));
1690 delete_token_ref(obj_xform_attr(pdf, pdf_cur_form));
1691 set_obj_xform_attr(pdf, pdf_cur_form, null);
1692 }
1693 if (obj_xform_attr_str(pdf, pdf_cur_form) != null) {
1694 lua_pdf_literal(pdf, obj_xform_attr_str(pdf, pdf_cur_form),1);
1695 luaL_unref(Luas, LUA_REGISTRYINDEX, obj_xform_attr_str(pdf, pdf_cur_form));
1696 set_obj_xform_attr_str(pdf, pdf_cur_form, null);
1697 }
1698 if (xform_type == 0 || xform_type == 1 || xform_type == 3) {
1699 pdf_add_name(pdf, "BBox");
1700 pdf_begin_array(pdf);
1701 pdf_add_bp(pdf, -form_margin);
1702 pdf_add_bp(pdf, -form_margin);
1703 pdf_add_bp(pdf, pdf->page_size.h + form_margin);
1704 pdf_add_bp(pdf, pdf->page_size.v + form_margin);
1705 pdf_end_array(pdf);
1706 }
1707 if (xform_type == 0 || xform_type == 2 || xform_type == 3) {
1708 pdf_add_name(pdf, "Matrix");
1709 pdf_begin_array(pdf);
1710 pdf_add_int(pdf, 1);
1711 pdf_add_int(pdf, 0);
1712 pdf_add_int(pdf, 0);
1713 pdf_add_int(pdf, 1);
1714 pdf_add_int(pdf, 0);
1715 pdf_add_int(pdf, 0);
1716 pdf_end_array(pdf);
1717 }
1718 pdf_dict_add_ref(pdf, "Resources", pdf->page_resources->last_resources);
1719 }
1720 /*tex Start a stream of page or form contents: */
1721 pdf_dict_add_streaminfo(pdf);
1722 pdf_end_dict(pdf);
1723 pdf_begin_stream(pdf);
1724 /*tex Start with an empty stack: */
1725 pos_stack_used = 0;
1726 if (global_shipping_mode == SHIPPING_PAGE) {
1727 colorstackpagestart();
1728 }
1729 if (global_shipping_mode == SHIPPING_PAGE)
1730 pdf_out_colorstack_startpage(pdf);
1731 }
1732
1733 void print_pdf_table_string(PDF pdf, const char *s)
1734 {
1735 size_t len;
1736 const char *ls;
1737 lua_rawgeti(Luas, LUA_REGISTRYINDEX, lua_key_index(pdf_data));
1738 lua_rawget(Luas, LUA_REGISTRYINDEX);
1739 lua_pushstring(Luas, s);
1740 lua_rawget(Luas, -2);
1741 if (lua_type(Luas, -1) == LUA_TSTRING) {
1742 ls = lua_tolstring(Luas, -1, &len);
1743 if (len > 0) {
1744 pdf_check_space(pdf);
1745 pdf_out_block(pdf, ls, len);
1746 pdf_set_space(pdf);
1747 }
1748 }
1749 lua_pop(Luas, 2);
1750 }
1751
1752 const char *get_pdf_table_string(const char *s)
1753 {
1754 const_lstring ls;
1755 lua_rawgeti(Luas, LUA_REGISTRYINDEX, lua_key_index(pdf_data));
1756 lua_rawget(Luas, LUA_REGISTRYINDEX);
1757 lua_pushstring(Luas, s);
1758 lua_rawget(Luas, -2);
1759 if (lua_type(Luas, -1) == LUA_TSTRING) {
1760 ls.s = lua_tolstring(Luas, -1, &ls.l);
1761 /*tex
1762 Here |s| is supposed to be anchored (e.g.\ in the registry) so it's
1763 not garbage collected.
1764 */
1765 lua_pop(Luas, 2);
1766 return ls.s;
1767 }
1768 lua_pop(Luas, 2);
1769 return NULL ;
1770 }
1771
1772 void pdf_end_page(PDF pdf)
1773 {
1774 char s[64], *p;
1775 int j, annots = 0, beads = 0, callback_id;
1776 pdf_resource_struct *res_p = pdf->page_resources;
1777 pdf_resource_struct local_page_resources;
1778 pdf_object_list *annot_list, *bead_list, *link_list, *ol, *ol1;
1779 /*tex We save |pdf->page_size| during flushing pending forms: */
1780 scaledpos save_cur_page_size;
1781 shipping_mode_e save_shipping_mode;
1782 int save_pdf_cur_form;
1783 int xform_resources;
1784 int page_resources, page_attributes;
1785 int procset = PROCSET_PDF;
1786 /*tex Finish the stream of page or form contents: */
1787 pdf_goto_pagemode(pdf);
1788 if (pos_stack_used > 0) {
1789 formatted_error("pdf backend","%u unmatched 'save' after %s shipout", (unsigned int) pos_stack_used,
1790 ((global_shipping_mode == SHIPPING_PAGE) ? "page" : "form"));
1791 }
1792 pdf_end_stream(pdf);
1793 pdf_end_obj(pdf);
1794 callback_id = callback_defined(finish_pdfpage_callback);
1795 if (callback_id > 0)
1796 run_callback(callback_id, "b->",(global_shipping_mode == SHIPPING_PAGE));
1797 if (global_shipping_mode == SHIPPING_PAGE) {
1798 int location = 0;
1799 int callback_id = callback_defined(page_order_index_callback);
1800 if (callback_id) {
1801 run_callback(callback_id, "d->d", total_pages, &location);
1802 }
1803 pdf->last_pages = pdf_do_page_divert(pdf, pdf->last_page, location);
1804 /*tex Write out the |/Page| object. */
1805 pdf_begin_obj(pdf, pdf->last_page, OBJSTM_ALWAYS);
1806 pdf_begin_dict(pdf);
1807 pdf_dict_add_name(pdf, "Type", "Page");
1808 pdf_dict_add_ref(pdf, "Contents", pdf->last_stream);
1809 pdf_dict_add_ref(pdf, "Resources", res_p->last_resources);
1810 pdf->omit_mediabox = pdf_omit_mediabox;
1811 if (! pdf->omit_mediabox) {
1812 pdf_add_name(pdf, "MediaBox");
1813 pdf_begin_array(pdf);
1814 pdf_add_int(pdf, 0);
1815 pdf_add_int(pdf, 0);
1816 pdf_add_bp(pdf, pdf->page_size.h);
1817 pdf_add_bp(pdf, pdf->page_size.v);
1818 pdf_end_array(pdf);
1819 }
1820 page_attributes = pdf_page_attr ;
1821 if (page_attributes != null)
1822 pdf_print_toks(pdf, page_attributes);
1823 print_pdf_table_string(pdf, "pageattributes");
1824 pdf_dict_add_ref(pdf, "Parent", pdf->last_pages);
1825 if (pdf->img_page_group_val != 0) {
1826 pdf_dict_add_ref(pdf, "Group", pdf->img_page_group_val);
1827 }
1828 annot_list = get_page_resources_list(pdf, obj_type_annot);
1829 link_list = get_page_resources_list(pdf, obj_type_link);
1830 if (annot_list != NULL || link_list != NULL) {
1831 annots = pdf_create_obj(pdf, obj_type_annots, 0);
1832 pdf_dict_add_ref(pdf, "Annots", annots);
1833 }
1834 bead_list = get_page_resources_list(pdf, obj_type_bead);
1835 if (bead_list != NULL) {
1836 beads = pdf_create_obj(pdf, obj_type_beads, 0);
1837 pdf_dict_add_ref(pdf, "B", beads);
1838 }
1839 pdf_end_dict(pdf);
1840 pdf_end_obj(pdf);
1841 pdf->img_page_group_val = 0;
1842 /*tex Generate an array of annotations or beads in page. */
1843 if (annot_list != NULL || link_list != NULL) {
1844 pdf_begin_obj(pdf, annots, OBJSTM_ALWAYS);
1845 pdf_begin_array(pdf);
1846 while (annot_list != NULL) {
1847 pdf_add_ref(pdf, annot_list->info);
1848 annot_list = annot_list->link;
1849 }
1850 while (link_list != NULL) {
1851 pdf_add_ref(pdf, link_list->info);
1852 link_list = link_list->link;
1853 }
1854 pdf_end_array(pdf);
1855 pdf_end_obj(pdf);
1856 }
1857 if (bead_list != NULL) {
1858 pdf_begin_obj(pdf, beads, OBJSTM_ALWAYS);
1859 pdf_begin_array(pdf);
1860 while (bead_list != NULL) {
1861 pdf_add_ref(pdf, bead_list->info);
1862 bead_list = bead_list->link;
1863 }
1864 pdf_end_array(pdf);
1865 pdf_end_obj(pdf);
1866 }
1867 }
1868 /*tex Write out the resource lists and pending raw objects. */
1869 ol = get_page_resources_list(pdf, obj_type_obj);
1870 while (ol != NULL) {
1871 if (!is_obj_written(pdf, ol->info))
1872 pdf_write_obj(pdf, ol->info);
1873 ol = ol->link;
1874 }
1875 /*tex
1876 When flushing pending forms we need to save and restore resource lists
1877 which are also used by page shipping. Saving and restoring
1878 |pdf->page_size| is needed for proper writing out pending \PDF\ marks.
1879 */
1880 ol = get_page_resources_list(pdf, obj_type_xform);
1881 while (ol != NULL) {
1882 if (!is_obj_written(pdf, ol->info)) {
1883 save_pdf_cur_form = pdf_cur_form;
1884 pdf_cur_form = ol->info;
1885 save_cur_page_size = pdf->page_size;
1886 save_shipping_mode = global_shipping_mode;
1887 pdf->page_resources = &local_page_resources;
1888 local_page_resources.resources_tree = NULL;
1889 ship_out(pdf, obj_xform_box(pdf, pdf_cur_form), SHIPPING_FORM);
1890 /*tex Restore the page size and page resources. */
1891 pdf->page_size = save_cur_page_size;
1892 global_shipping_mode = save_shipping_mode;
1893 destroy_page_resources_tree(pdf);
1894 pdf->page_resources = res_p;
1895 pdf_cur_form = save_pdf_cur_form;
1896 }
1897 ol = ol->link;
1898 }
1899 /*tex Write out pending images. */
1900 ol = get_page_resources_list(pdf, obj_type_ximage);
1901 while (ol != NULL) {
1902 if (!is_obj_written(pdf, ol->info))
1903 pdf_write_image(pdf, ol->info);
1904 ol = ol->link;
1905 }
1906 if (global_shipping_mode == SHIPPING_PAGE) {
1907 /*tex Write out pending \PDF\ marks and annotations. */
1908 ol = get_page_resources_list(pdf, obj_type_annot);
1909 while (ol != NULL) {
1910 if (ol->info > 0 && obj_type(pdf, ol->info) == obj_type_annot) {
1911 /*tex Here |j| points to |pdf_annot_node|: */
1912 j = obj_annot_ptr(pdf, ol->info);
1913 pdf_begin_obj(pdf, ol->info, OBJSTM_ALWAYS);
1914 pdf_begin_dict(pdf);
1915 pdf_dict_add_name(pdf, "Type", "Annot");
1916 pdf_print_toks(pdf, pdf_annot_data(j));
1917 pdf_rectangle(pdf, j);
1918 pdf_end_dict(pdf);
1919 pdf_end_obj(pdf);
1920 }
1921 ol = ol->link;
1922 }
1923 /*tex Write out PDF link annotations. */
1924 if ((ol = get_page_resources_list(pdf, obj_type_link)) != NULL) {
1925 while (ol != NULL) {
1926 j = obj_annot_ptr(pdf, ol->info);
1927 pdf_begin_obj(pdf, ol->info, OBJSTM_ALWAYS);
1928 pdf_begin_dict(pdf);
1929 pdf_dict_add_name(pdf, "Type", "Annot");
1930 if (pdf_action_type(pdf_link_action(j)) != pdf_action_user)
1931 pdf_dict_add_name(pdf, "Subtype", "Link");
1932 if (pdf_link_attr(j) != null)
1933 pdf_print_toks(pdf, pdf_link_attr(j));
1934 pdf_rectangle(pdf, j);
1935 if (pdf_action_type(pdf_link_action(j)) != pdf_action_user)
1936 pdf_puts(pdf, "/A ");
1937 write_action(pdf, pdf_link_action(j));
1938 pdf_end_dict(pdf);
1939 pdf_end_obj(pdf);
1940 ol = ol->link;
1941 }
1942 /*tex Flush |pdf_start_link_node|'s created by |append_link|. */
1943 ol = get_page_resources_list(pdf, obj_type_link);
1944 while (ol != NULL) {
1945 j = obj_annot_ptr(pdf, ol->info);
1946 /*tex
1947 Nodes with |subtype = pdf_link_data_node| were created by
1948 |append_link| and must be flushed here, as they are not
1949 linked in any list.
1950 */
1951 if (subtype(j) == pdf_link_data_node)
1952 flush_node(j);
1953 ol = ol->link;
1954 }
1955 }
1956 /*tex Write out \PDF\ mark destinations. */
1957 write_out_pdf_mark_destinations(pdf);
1958 /*tex Write out \PDF\ bead rectangle specifications. */
1959 print_bead_rectangles(pdf);
1960 }
1961 /*tex Write out resources dictionary. */
1962 pdf_begin_obj(pdf, res_p->last_resources, OBJSTM_ALWAYS);
1963 pdf_begin_dict(pdf);
1964 /*tex Print additional resources. */
1965 if (global_shipping_mode == SHIPPING_PAGE) {
1966 page_resources = pdf_page_resources;
1967 if (page_resources != null) {
1968 pdf_print_toks(pdf, page_resources);
1969 }
1970 print_pdf_table_string(pdf, "pageresources");
1971 } else {
1972 xform_resources = pdf_xform_resources;
1973 if (xform_resources != null) {
1974 pdf_print_toks(pdf, xform_resources);
1975 }
1976 print_pdf_table_string(pdf, "xformresources");
1977 if (obj_xform_resources(pdf, pdf_cur_form) != null) {
1978 pdf_print_toks(pdf, obj_xform_resources(pdf, pdf_cur_form));
1979 delete_token_ref(obj_xform_resources(pdf, pdf_cur_form));
1980 set_obj_xform_resources(pdf, pdf_cur_form, null);
1981 }
1982 if (obj_xform_resources_str(pdf, pdf_cur_form) != null) {
1983 lua_pdf_literal(pdf, obj_xform_resources_str(pdf, pdf_cur_form),1);
1984 luaL_unref(Luas, LUA_REGISTRYINDEX, obj_xform_resources_str(pdf, pdf_cur_form));
1985 set_obj_xform_resources_str(pdf, pdf_cur_form, null);
1986 }
1987 }
1988 /*tex Generate font resources. */
1989 if ((ol = get_page_resources_list(pdf, obj_type_font)) != NULL) {
1990 pdf_add_name(pdf, "Font");
1991 pdf_begin_dict(pdf);
1992 while (ol != NULL) {
1993 p = s;
1994 p += snprintf(p, 20, "F%i", obj_info(pdf, ol->info));
1995 if (pdf->resname_prefix != NULL)
1996 p += snprintf(p, 20, "%s", pdf->resname_prefix);
1997 pdf_dict_add_ref(pdf, s, ol->info);
1998 ol = ol->link;
1999 }
2000 pdf_end_dict(pdf);
2001 procset |= PROCSET_TEXT;
2002 }
2003 /*tex Generate |XObject| resources. */
2004 ol = get_page_resources_list(pdf, obj_type_xform);
2005 ol1 = get_page_resources_list(pdf, obj_type_ximage);
2006 if (ol != NULL || ol1 != NULL) {
2007 pdf_add_name(pdf, "XObject");
2008 pdf_begin_dict(pdf);
2009 while (ol != NULL) {
2010 p = s;
2011 p += snprintf(p, 20, "Fm%i", obj_info(pdf, ol->info));
2012 if (pdf->resname_prefix != NULL)
2013 p += snprintf(p, 20, "%s", pdf->resname_prefix);
2014 pdf_dict_add_ref(pdf, s, ol->info);
2015 ol = ol->link;
2016 }
2017 while (ol1 != null) {
2018 p = s;
2019 p += snprintf(p, 20, "Im%i", obj_info(pdf, ol1->info));
2020 if (pdf->resname_prefix != NULL)
2021 p += snprintf(p, 20, "%s", pdf->resname_prefix);
2022 pdf_dict_add_ref(pdf, s, ol1->info);
2023 procset |= img_procset(idict_array[obj_data_ptr(pdf, ol1->info)]);
2024 ol1 = ol1->link;
2025 }
2026 pdf_end_dict(pdf);
2027 }
2028 /*tex Generate |ProcSet| in version 1.*/
2029 if (pdf->major_version == 1 && ! pdf_omit_procset) {
2030 pdf_add_name(pdf, "ProcSet");
2031 pdf_begin_array(pdf);
2032 if ((procset & PROCSET_PDF) != 0)
2033 pdf_add_name(pdf, "PDF");
2034 if ((procset & PROCSET_TEXT) != 0)
2035 pdf_add_name(pdf, "Text");
2036 if ((procset & PROCSET_IMAGE_B) != 0)
2037 pdf_add_name(pdf, "ImageB");
2038 if ((procset & PROCSET_IMAGE_C) != 0)
2039 pdf_add_name(pdf, "ImageC");
2040 if ((procset & PROCSET_IMAGE_I) != 0)
2041 pdf_add_name(pdf, "ImageI");
2042 pdf_end_array(pdf);
2043 }
2044 pdf_end_dict(pdf);
2045 pdf_end_obj(pdf);
2046 }
2047
2048 /*tex
2049
2050 We're now ready to wrap up the output file. Destinations that have been
2051 referenced but don't exists have |obj_dest_ptr=null|. Leaving them undefined
2052 might cause troubles for PDF browsers, so we need to fix them; they point to
2053 the last page.
2054
2055 */
2056
2057 static void check_nonexisting_destinations(PDF pdf)
2058 {
2059 int k;
2060 for (k = pdf->head_tab[obj_type_dest]; k != 0; k = obj_link(pdf, k)) {
2061 if (obj_dest_ptr(pdf, k) == null) {
2062 if (obj_info(pdf, k) < 0) {
2063 char *ss = makecstring(-obj_info(pdf, k));
2064 formatted_warning("pdf backend", "unreferenced destination with name '%s'",ss);
2065 } else {
2066 formatted_warning("pdf backend", "unreferenced destination with num '%d'",obj_info(pdf,k));
2067 }
2068
2069 pdf_begin_obj(pdf, k, OBJSTM_ALWAYS);
2070 pdf_begin_array(pdf);
2071 pdf_add_ref(pdf, pdf->last_page);
2072 pdf_add_name(pdf, "Fit");
2073 pdf_end_array(pdf);
2074 pdf_end_obj(pdf);
2075 }
2076 }
2077 }
2078
2079 /*tex
2080
2081 For structure destinations we don't have a fallback structure element to use when
2082 they are not defined, so we insert "null" instead
2083 referenced but don't exists have |obj_dest_ptr=null|. Leaving them undefined
2084 might cause troubles for PDF browsers, so we need to fix them; they point to
2085 the last page.
2086
2087 */
2088
2089 static void check_nonexisting_structure_destinations(PDF pdf)
2090 {
2091 int k;
2092 for (k = pdf->head_tab[obj_type_struct_dest]; k != 0; k = obj_link(pdf, k)) {
2093 if (obj_dest_ptr(pdf, k) == null) {
2094 if (obj_info(pdf, k) < 0) {
2095 char *ss = makecstring(-obj_info(pdf, k));
2096 formatted_warning("pdf backend", "unreferenced structure destination with name '%s'",ss);
2097 } else {
2098 formatted_warning("pdf backend", "unreferenced structure destination with num '%d'",obj_info(pdf,k));
2099 }
2100
2101 pdf_begin_obj(pdf, k, OBJSTM_ALWAYS);
2102 pdf_begin_array(pdf);
2103 pdf_add_null(pdf);
2104 pdf_add_name(pdf, "Fit");
2105 pdf_end_array(pdf);
2106 pdf_end_obj(pdf);
2107 }
2108 }
2109 }
2110
2111 static void check_nonexisting_pages(PDF pdf)
2112 {
2113 struct avl_traverser t;
2114 oentry *p;
2115 struct avl_table *page_tree = pdf->obj_tree[obj_type_page];
2116 avl_t_init(&t, page_tree);
2117 /*tex Search from the end backward until the last real page is found. */
2118 for (p = avl_t_last(&t, page_tree); p != NULL && obj_aux(pdf, p->objptr) == 0; p = avl_t_prev(&t)) {
2119 formatted_warning("pdf backend", "page %d has been referenced but does not exist",obj_info(pdf, p->objptr));
2120 }
2121 }
2122
2123 /*tex
2124
2125 If the same keys in a dictionary are given several times, then it is not
2126 defined which value is choosen by an application. Therefore the keys
2127 |/Producer| and |/Creator| are only set if the token list |pdf_info_toks|
2128 converted to a string does not contain these key strings.
2129
2130 */
2131
2132 static boolean substr_of_str(const char *s, const char *t)
2133 {
2134 if (strstr(t, s) == NULL)
2135 return false;
2136 return true;
2137 }
2138
2139 const char* pdf_pdf_prefix_str(const char *a, const char *b)
2140 {
2141 return (pdf_ptex_prefix ? a : b);
2142 }
2143
2144 static int pdf_print_info(PDF pdf, int luatexversion, str_number luatexrevision)
2145 {
2146 boolean creator_given = false;
2147 boolean producer_given = false;
2148 boolean creationdate_given = false;
2149 boolean moddate_given = false;
2150 boolean trapped_given = false;
2151 char *s = NULL;
2152 const char *p = NULL;
2153 int k, len = 0;
2154 k = pdf_create_obj(pdf, obj_type_info, 0);
2155 pdf_begin_obj(pdf, k, 3);
2156 pdf_begin_dict(pdf);
2157 if (pdf_info_toks != 0) {
2158 s = tokenlist_to_cstring(pdf_info_toks, true, &len);
2159 creator_given = substr_of_str("/Creator", s);
2160 producer_given = substr_of_str("/Producer", s);
2161 creationdate_given = substr_of_str("/CreationDate", s);
2162 moddate_given = substr_of_str("/ModDate", s);
2163 trapped_given = substr_of_str("/Trapped", s);
2164 }
2165 p = get_pdf_table_string("info");
2166 if (p && strlen(p) > 0) {
2167 creator_given = creator_given || substr_of_str("/Creator", p);
2168 producer_given = producer_given || substr_of_str("/Producer", p);
2169 creationdate_given = creationdate_given || substr_of_str("/CreationDate", p);
2170 moddate_given = moddate_given || substr_of_str("/ModDate", p);
2171 trapped_given = trapped_given || substr_of_str("/Trapped", p);
2172 }
2173 if (pdf_info_toks != null) {
2174 if (len > 0) {
2175 pdf_check_space(pdf);
2176 pdf_puts(pdf, s);
2177 pdf_set_space(pdf);
2178 xfree(s);
2179 }
2180 delete_token_ref(pdf_info_toks);
2181 pdf_info_toks = null;
2182 }
2183 if (p && strlen(p) > 0) {
2184 pdf_check_space(pdf);
2185 pdf_puts(pdf, p);
2186 pdf_set_space(pdf);
2187 }
2188 if ((pdf_suppress_optional_info & 128) == 0 && !producer_given) {
2189 pdf_add_name(pdf, "Producer");
2190 pdf_puts(pdf, " (LuaTeX-");
2191 pdf_puts(pdf, luatex_version_string);
2192 pdf_out(pdf, ')');
2193 }
2194 if ((pdf_suppress_optional_info & 16) == 0 && !creator_given) {
2195 pdf_dict_add_string(pdf, "Creator", "TeX");
2196 }
2197 if ((pdf_suppress_optional_info & 32) == 0 && !creationdate_given) {
2198 initialize_start_time(pdf);
2199 pdf_dict_add_string(pdf, "CreationDate", pdf->start_time_str);
2200 }
2201 if ((pdf_suppress_optional_info & 64) == 0 && !moddate_given) {
2202 initialize_start_time(pdf);
2203 pdf_dict_add_string(pdf, "ModDate", pdf->start_time_str);
2204 }
2205 if ((pdf_suppress_optional_info & 256) == 0 && !trapped_given) {
2206 pdf_dict_add_name(pdf, "Trapped", "False");
2207 }
2208 if ((pdf_suppress_optional_info & 1) == 0) {
2209 pdf_dict_add_string(pdf, pdf_pdf_prefix_str("PTEX_FullBanner", "PTEX.FullBanner"), luatex_banner);
2210 }
2211 pdf_end_dict(pdf);
2212 pdf_end_obj(pdf);
2213 return k;
2214 }
2215
2216 static void build_free_object_list(PDF pdf)
2217 {
2218 int k;
2219 int l = 0;
2220 /*tex A |null| object at the begin of a list of free objects. */
2221 set_obj_fresh(pdf, l);
2222 for (k = 1; k <= pdf->obj_ptr; k++) {
2223 if (!is_obj_written(pdf, k)) {
2224 set_obj_link(pdf, l, k);
2225 l = k;
2226 }
2227 }
2228 set_obj_link(pdf, l, 0);
2229 }
2230
2231 /*tex
2232
2233 Now we can the finish of \PDF\ output file. At this moment all |/Page|
2234 objects are already written completely to \PDF\ output file.
2235
2236 */
2237
2238 void pdf_finish_file(PDF pdf, int fatal_error) {
2239 if (fatal_error) {
2240 remove_pdffile(static_pdf); /* will become remove_output_file */
2241 print_err(" ==> Fatal error occurred, no output PDF file produced!");
2242 } else {
2243 int i, j, k;
2244 int root = 0;
2245 int info = 0;
2246 int xref_stm = 0;
2247 int outlines = 0;
2248 int threads = 0;
2249 int names_tree = 0;
2250 int prerolled = 0;
2251 size_t xref_offset_width;
2252 int luatexversion = luatex_version;
2253 str_number luatexrevision = get_luatexrevision();
2254 int callback_id = callback_defined(stop_run_callback);
2255 int callback_id1 = callback_defined(finish_pdffile_callback);
2256 if (total_pages == 0 && !pdf->force_file) {
2257 if (callback_id == 0) {
2258 normal_warning("pdf backend","no pages of output.");
2259 } else if (callback_id > 0) {
2260 run_callback(callback_id, "->");
2261 }
2262 if (pdf->gone > 0) {
2263 /* number of bytes gone */
2264 normal_error("pdf backend","already written content discarded, no output file produced.");
2265 }
2266 } else {
2267 if (pdf->draftmode == 0) {
2268 pdf->gen_tounicode = pdf_gen_tounicode;
2269 pdf->omit_cidset = pdf_omit_cidset;
2270 pdf->omit_charset = pdf_omit_charset;
2271 pdf->omit_infodict = pdf_omit_infodict;
2272 /*tex We make sure that the output file name has been already created. */
2273 pdf_flush(pdf);
2274 /*tex Flush page 0 objects from JBIG2 images, if any. */
2275 flush_jbig2_page0_objects(pdf);
2276 if (callback_id1 > 0) {
2277 run_callback(callback_id1, "->");
2278 }
2279 if (total_pages > 0) {
2280 check_nonexisting_pages(pdf);
2281 check_nonexisting_destinations(pdf);
2282 check_nonexisting_structure_destinations(pdf);
2283 }
2284 /*tex
2285 The first pass over the list will flag the slots that are
2286 used so that we can do a preroll for type 3 fonts.
2287 */
2288 for (k = 1; k <= max_font_id(); k++) {
2289 if (font_used(k) && (pdf_font_num(k) < 0)) {
2290 i = -pdf_font_num(k);
2291 for (j = font_bc(k); j <= font_ec(k); j++)
2292 if (quick_char_exists(k, j) && pdf_char_marked(k, j))
2293 pdf_mark_char(i, j);
2294 }
2295 }
2296 k = pdf->head_tab[obj_type_font];
2297 while (k != 0) {
2298 int f = obj_info(pdf, k);
2299 if (do_pdf_preroll_font(pdf, f)) {
2300 prerolled = 1;
2301 }
2302 k = obj_link(pdf, k);
2303 }
2304 /*tex
2305 Just in case the user type 3 font has used fonts, we need to
2306 do a second pass. We also collect some additional data here.
2307 */
2308 for (k = 1; k <= max_font_id(); k++) {
2309 if (font_used(k) && (pdf_font_num(k) < 0)) {
2310 i = -pdf_font_num(k);
2311 if (prerolled) {
2312 for (j = font_bc(k); j <= font_ec(k); j++)
2313 if (quick_char_exists(k, j) && pdf_char_marked(k, j))
2314 pdf_mark_char(i, j);
2315 } else {
2316 /*tex No need to waste time on checking again. */
2317 }
2318 if ((pdf_font_attr(i) == 0) && (pdf_font_attr(k) != 0)) {
2319 set_pdf_font_attr(i, pdf_font_attr(k));
2320 } else if ((pdf_font_attr(k) == 0) && (pdf_font_attr(i) != 0)) {
2321 set_pdf_font_attr(k, pdf_font_attr(i));
2322 } else if ((pdf_font_attr(i) != 0) && (pdf_font_attr(k) != 0) && (!str_eq_str(pdf_font_attr(i), pdf_font_attr(k)))) {
2323 formatted_warning("pdf backend","fontattr of font %d and %d are conflicting, %k is used",i,k,i);
2324 }
2325 }
2326 }
2327 k = pdf->head_tab[obj_type_font];
2328 while (k != 0) {
2329 int f = obj_info(pdf, k);
2330 do_pdf_font(pdf, f);
2331 k = obj_link(pdf, k);
2332 }
2333 write_fontstuff(pdf);
2334 /*tex
2335 We're done with the fonts.
2336 */
2337 if (total_pages > 0) {
2338 pdf->last_pages = output_pages_tree(pdf);
2339 /*tex Output outlines. */
2340 outlines = print_outlines(pdf);
2341 /*tex
2342 The name tree is very similiar to Pages tree so its construction
2343 should be certain from Pages tree construction. For intermediate
2344 node |obj_info| will be the first name and |obj_link| will be the
2345 last name in \.{\\Limits} array. Note that |pdf_dest_names_ptr|
2346 will be less than |obj_ptr|, so we test if |k <
2347 pdf_dest_names_ptr| then |k| is index of leaf in |dest_names|;
2348 else |k| will be index in |obj_tab| of some intermediate node.
2349 */
2350 names_tree = output_name_tree(pdf);
2351 /*tex Output article threads. */
2352 if (pdf->head_tab[obj_type_thread] != 0) {
2353 threads = pdf_create_obj(pdf, obj_type_others, 0);
2354 pdf_begin_obj(pdf, threads, OBJSTM_ALWAYS);
2355 pdf_begin_array(pdf);
2356 k = pdf->head_tab[obj_type_thread];
2357 while (k != 0) {
2358 pdf_add_ref(pdf, k);
2359 k = obj_link(pdf, k);
2360 }
2361 pdf_end_array(pdf);
2362 pdf_end_obj(pdf);
2363 k = pdf->head_tab[obj_type_thread];
2364 while (k != 0) {
2365 out_thread(pdf, k);
2366 k = obj_link(pdf, k);
2367 }
2368 } else {
2369 threads = 0;
2370 }
2371 }
2372 /*tex Output the |/Catalog| object. */
2373 root = pdf_create_obj(pdf, obj_type_catalog, 0);
2374 pdf_begin_obj(pdf, root, OBJSTM_ALWAYS);
2375 pdf_begin_dict(pdf);
2376 pdf_dict_add_name(pdf, "Type", "Catalog");
2377 if (total_pages > 0) {
2378 pdf_dict_add_ref(pdf, "Pages", pdf->last_pages);
2379 if (threads != 0) {
2380 pdf_dict_add_ref(pdf, "Threads", threads);
2381 }
2382 if (outlines != 0) {
2383 pdf_dict_add_ref(pdf, "Outlines", outlines);
2384 }
2385 if (names_tree != 0) {
2386 pdf_dict_add_ref(pdf, "Names", names_tree);
2387 }
2388 if (pdf_catalog_toks != null) {
2389 pdf_print_toks(pdf, pdf_catalog_toks);
2390 delete_token_ref(pdf_catalog_toks);
2391 pdf_catalog_toks = null;
2392 }
2393 }
2394 if (pdf_catalog_openaction != 0) {
2395 pdf_dict_add_ref(pdf, "OpenAction", pdf_catalog_openaction);
2396 }
2397 print_pdf_table_string(pdf, "catalog");
2398 pdf_end_dict(pdf);
2399 pdf_end_obj(pdf);
2400 if (! pdf->omit_infodict)
2401 info = pdf_print_info(pdf, luatexversion, luatexrevision);
2402 if (pdf->os_enable) {
2403 pdf_buffer_select(pdf, OBJSTM_BUF);
2404 pdf_os_write_objstream(pdf);
2405 pdf_flush(pdf);
2406 pdf_buffer_select(pdf, PDFOUT_BUF);
2407 /*tex Output the cross-reference stream dictionary. */
2408 xref_stm = pdf_create_obj(pdf, obj_type_others, 0);
2409 pdf_begin_obj(pdf, xref_stm, OBJSTM_NEVER);
2410 if ((obj_offset(pdf, pdf->obj_ptr) / 256) > 16777215)
2411 xref_offset_width = 5;
2412 else if (obj_offset(pdf, pdf->obj_ptr) > 16777215)
2413 xref_offset_width = 4;
2414 else if (obj_offset(pdf, pdf->obj_ptr) > 65535)
2415 xref_offset_width = 3;
2416 else
2417 xref_offset_width = 2;
2418 /*tex Build a linked list of free objects. */
2419 build_free_object_list(pdf);
2420 pdf_begin_dict(pdf);
2421 pdf_dict_add_name(pdf, "Type", "XRef");
2422 pdf_add_name(pdf, "Index");
2423 pdf_begin_array(pdf);
2424 pdf_add_int(pdf, 0);
2425 pdf_add_int(pdf, pdf->obj_ptr + 1);
2426 pdf_end_array(pdf);
2427 pdf_dict_add_int(pdf, "Size", pdf->obj_ptr + 1);
2428 pdf_add_name(pdf, "W");
2429 pdf_begin_array(pdf);
2430 pdf_add_int(pdf, 1);
2431 pdf_add_int(pdf, (int) xref_offset_width);
2432 pdf_add_int(pdf, 1);
2433 pdf_end_array(pdf);
2434 pdf_dict_add_ref(pdf, "Root", root);
2435 if (! pdf->omit_infodict)
2436 pdf_dict_add_ref(pdf, "Info", info);
2437 if (pdf_trailer_toks != null) {
2438 pdf_print_toks(pdf, pdf_trailer_toks);
2439 delete_token_ref(pdf_trailer_toks);
2440 pdf_trailer_toks = null;
2441 }
2442 print_pdf_table_string(pdf, "trailer");
2443 print_ID(pdf);
2444 pdf_dict_add_streaminfo(pdf);
2445 pdf_end_dict(pdf);
2446 pdf_begin_stream(pdf);
2447 for (k = 0; k <= pdf->obj_ptr; k++) {
2448 if (!is_obj_written(pdf, k)) {
2449 /*tex A free object: */
2450 pdf_out(pdf, 0);
2451 pdf_out_bytes(pdf, obj_link(pdf, k), xref_offset_width);
2452 pdf_out(pdf, 255);
2453 } else if (obj_os_idx(pdf, k) == PDF_OS_MAX_OBJS) {
2454 /*tex An object not in object stream: */
2455 pdf_out(pdf, 1);
2456 pdf_out_bytes(pdf, obj_offset(pdf, k), xref_offset_width);
2457 pdf_out(pdf, 0);
2458 } else {
2459 /*tex An object in object stream: */
2460 pdf_out(pdf, 2);
2461 pdf_out_bytes(pdf, obj_offset(pdf, k), xref_offset_width);
2462 pdf_out(pdf, obj_os_idx(pdf, k));
2463 }
2464 }
2465 pdf_end_stream(pdf);
2466 pdf_end_obj(pdf);
2467 pdf_flush(pdf);
2468 } else {
2469 /*tex Output the |obj_tab| and build a linked list of free objects. */
2470 build_free_object_list(pdf);
2471 pdf_save_offset(pdf);
2472 pdf_puts(pdf, "xref\n");
2473 pdf_puts(pdf, "0 ");
2474 pdf_print_int_ln(pdf, pdf->obj_ptr + 1);
2475 pdf_print_fw_int(pdf, obj_link(pdf, 0));
2476 pdf_puts(pdf, " 65535 f \n");
2477 for (k = 1; k <= pdf->obj_ptr; k++) {
2478 if (!is_obj_written(pdf, k)) {
2479 pdf_print_fw_int(pdf, obj_link(pdf, k));
2480 pdf_puts(pdf, " 00000 f \n");
2481 } else {
2482 pdf_print_fw_int(pdf, obj_offset(pdf, k));
2483 pdf_puts(pdf, " 00000 n \n");
2484 }
2485 }
2486 }
2487 /*tex Output the trailer. */
2488 if (!pdf->os_enable) {
2489 pdf_puts(pdf, "trailer\n");
2490 pdf_reset_space(pdf);
2491 pdf_begin_dict(pdf);
2492 pdf_dict_add_int(pdf, "Size", pdf->obj_ptr + 1);
2493 pdf_dict_add_ref(pdf, "Root", root);
2494 if (! pdf->omit_infodict)
2495 pdf_dict_add_ref(pdf, "Info", info);
2496 if (pdf_trailer_toks != null) {
2497 pdf_print_toks(pdf, pdf_trailer_toks);
2498 delete_token_ref(pdf_trailer_toks);
2499 pdf_trailer_toks = null;
2500 }
2501 print_ID(pdf);
2502 pdf_end_dict(pdf);
2503 pdf_out(pdf, '\n');
2504 }
2505 pdf_puts(pdf, "startxref\n");
2506 pdf_reset_space(pdf);
2507 if (pdf->os_enable)
2508 pdf_add_longint(pdf, (longinteger) obj_offset(pdf, xref_stm));
2509 else
2510 pdf_add_longint(pdf, (longinteger) pdf->save_offset);
2511 pdf_puts(pdf, "\n%%EOF\n");
2512 pdf_flush(pdf);
2513 if (callback_id == 0) {
2514 tprint_nl("Output written on ");
2515 tprint(pdf->file_name);
2516 tprint(" (");
2517 print_int(total_pages);
2518 tprint(" page");
2519 if (total_pages != 1)
2520 print_char('s');
2521 tprint(", ");
2522 print_int(pdf_offset(pdf));
2523 tprint(" bytes).");
2524 print_ln();
2525 } else if (callback_id > 0) {
2526 run_callback(callback_id, "->");
2527 }
2528 libpdffinish(pdf);
2529 close_file(pdf->file);
2530 } else {
2531 if (callback_id > 0) {
2532 run_callback(callback_id, "->");
2533 }
2534 libpdffinish(pdf);
2535 normal_warning("pdf backend","draftmode enabled, not changing output pdf");
2536 }
2537 }
2538 if (callback_id == 0) {
2539 if (log_opened_global) {
2540 fprintf(log_file, "\nPDF statistics: %d PDF objects out of %d (max. %d)\n",
2541 (int) pdf->obj_ptr, (int) pdf->obj_tab_size,
2542 (int) sup_obj_tab_size);
2543 if (pdf->os->ostm_ctr > 0) {
2544 fprintf(log_file, " %d compressed objects within %d object stream%s\n",
2545 (int) pdf->os->o_ctr, (int) pdf->os->ostm_ctr,
2546 (pdf->os->ostm_ctr > 1 ? "s" : ""));
2547 }
2548 fprintf(log_file, " %d named destinations out of %d (max. %d)\n",
2549 (int) pdf->dest_names_ptr, (int) pdf->dest_names_size,
2550 (int) sup_dest_names_size);
2551 fprintf(log_file, " %d words of extra memory for PDF output out of %d (max. %d)\n",
2552 (int) pdf->mem_ptr, (int) pdf->mem_size,
2553 (int) sup_pdf_mem_size);
2554 }
2555 }
2556 }
2557 }
2558
2559 void scan_pdfcatalog(PDF pdf)
2560 {
2561 halfword p;
2562 scan_toks(false, true);
2563 pdf_catalog_toks = concat_tokens(pdf_catalog_toks, def_ref);
2564 if (scan_keyword("openaction")) {
2565 if (pdf_catalog_openaction != 0) {
2566 normal_error("pdf backend", "duplicate of openaction");
2567 } else {
2568 check_o_mode(pdf, "catalog", 1 << OMODE_PDF, true);
2569 p = scan_action(pdf);
2570 pdf_catalog_openaction = pdf_create_obj(pdf, obj_type_others, 0);
2571 pdf_begin_obj(pdf, pdf_catalog_openaction, OBJSTM_ALWAYS);
2572 write_action(pdf, p);
2573 pdf_end_obj(pdf);
2574 delete_action_ref(p);
2575 }
2576 }
2577 }
2578
2579 /*tex
2580
2581 This function converts double to pdffloat; very small and very large numbers
2582 are {\em not} converted to scientific notation. Here n must be a number or
2583 real conforming to the implementation limits of \PDF\ as specified in
2584 appendix C.1 of the \PDF\ standard. The maximum value of ints is |+2^32|, the
2585 maximum value of reals is |+2^15| and the smallest values of reals is
2586 |1/(2^16)|. We are quite large on precision, because it could happen that a
2587 pdf file imported as figure has real numbers with an unusual (and possibly useless)
2588 high precision. Later the formatter will write the numbers in the correct format.
2589
2590 */
2591
2592 static pdffloat conv_double_to_pdffloat(double n)
2593 {
2594 pdffloat a;
2595 /* was a.e = 6; */
2596 a.e = 9 ;
2597 a.m = i64round(n * ten_pow[a.e]);
2598 return a;
2599 }
2600
2601 void pdf_add_real(PDF pdf, double d)
2602 {
2603 pdf_check_space(pdf);
2604 print_pdffloat(pdf, conv_double_to_pdffloat(d));
2605 pdf_set_space(pdf);
2606 }
2607
2608 void pdf_push_list(PDF pdf, scaledpos *saved_pos, int *saved_loc) {
2609 /* nothing */
2610 }
2611
2612 void pdf_pop_list(PDF pdf, scaledpos *saved_pos, int *saved_loc) {
2613 /* nothing */
2614 }
2615
2616 extern void pdf_set_reference_point(PDF pdf, posstructure *refpoint)
2617 {
2618 refpoint->pos.h = pdf_h_origin;
2619 refpoint->pos.v = pdf->page_size.v - pdf_v_origin;
2620 }