~ubuntu-branches/ubuntu/saucy/luatex/saucy

« back to all changes in this revision

Viewing changes to source/texk/web2c/luatexdir/image/pdftoepdf.cc

  • Committer: Bazaar Package Importer
  • Author(s): Norbert Preining
  • Date: 2009-12-25 09:47:05 UTC
  • mfrom: (1.1.9 upstream) (4.2.3 squeeze)
  • Revision ID: james.westby@ubuntu.com-20091225094705-y33rpflo8t4u9nag
Tags: 0.50.0-1
* new upstream release
* disable fix-hurd-ftbfs patch, included upstream
* disable upstram-fixes, included upstream
* disable ubuntu_libpoppler-0.11, not needed anymore

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
/* pdftoepdf.cc
2
 
   
 
2
 
3
3
   Copyright 1996-2006 Han The Thanh <thanh@pdftex.org>
4
 
   Copyright 2006-2008 Taco Hoekwater <taco@luatex.org>
 
4
   Copyright 2006-2009 Taco Hoekwater <taco@luatex.org>
5
5
 
6
6
   This file is part of LuaTeX.
7
7
 
18
18
   You should have received a copy of the GNU General Public License along
19
19
   with LuaTeX; if not, see <http://www.gnu.org/licenses/>. */
20
20
 
 
21
static const char _svn_version[] =
 
22
    "$Id: pdftoepdf.cc 3294 2009-12-24 14:37:58Z hhenkel $ "
 
23
    "$URL: http://foundry.supelec.fr/svn/luatex/tags/beta-0.50.0/source/texk/web2c/luatexdir/image/pdftoepdf.cc $";
 
24
 
21
25
#include <stdlib.h>
22
26
#include <math.h>
23
27
#include <stddef.h>
24
28
#include <stdio.h>
25
29
#include <string.h>
26
30
#include <ctype.h>
 
31
#include <sys/stat.h>
27
32
#ifdef POPPLER_VERSION
28
33
#  define GString GooString
29
34
#  include <dirent.h>
53
58
 
54
59
#include "epdf.h"
55
60
 
56
 
static const char _svn_version[] =
57
 
    "$Id: pdftoepdf.cc 2448 2009-06-08 07:43:50Z taco $ "
58
 
    "$URL: http://foundry.supelec.fr/svn/luatex/tags/beta-0.40.6/source/texk/web2c/luatexdir/image/pdftoepdf.cc $";
59
 
 
60
 
#define one_hundred_bp  6578176 /* 7227 * 65536 / 72 */
 
61
#define one_hundred_bp  6578176 // one_hundred_bp = 7227 * 65536 / 72
61
62
 
62
63
// This file is mostly C and not very much C++; it's just used to interface
63
64
// the functions of xpdf, which happens to be written in C++.
95
96
};
96
97
/* *INDENT-ON* */
97
98
 
98
 
// When copying the Resources of the selected page, all objects are copied
99
 
// recusively top-down. Indirect objects however are not fetched during
100
 
// copying, but get a new object number from pdfTeX and then will be
101
 
// appended into a linked list. Duplicates are checked and removed from the
102
 
// list of indirect objects during appending.
103
 
 
104
 
enum InObjType { objFont, objFontDesc, objOther };
 
99
// When copying the Resources of the selected page, all objects are
 
100
// copied recursively top-down.  The findObjMap() function checks if an
 
101
// object has already been copied; if so, instead of copying just the
 
102
// new object number will be referenced.  The ObjMapTree guarantees,
 
103
// that during the entire LuaTeX run any object from any embedded PDF
 
104
// file will end up max. once in the output PDF file.  Indirect objects
 
105
// are not fetched during copying, but get a new object number from
 
106
// LuaTeX and then will be appended into a linked list.
105
107
 
106
108
struct InObj {
107
109
    Ref ref;                    // ref in original PDF
108
 
    InObjType type;             // object type
109
 
    integer num;                // new object number in output PDF
110
 
    fd_entry *fd;               // pointer to /FontDescriptor object structure
111
 
    integer enc_objnum;         // Encoding for objFont
112
 
    int written;                // has it been written to output PDF?
 
110
    int num;                    // new object number in output PDF
113
111
    InObj *next;                // next entry in list of indirect objects
114
112
};
115
113
 
116
 
struct UsedEncoding {
117
 
    integer enc_objnum;
118
 
    GfxFont *font;
119
 
    UsedEncoding *next;
120
 
};
121
 
 
122
 
static XRef *xref = NULL;
123
 
static InObj *inObjList = NULL;
124
 
static UsedEncoding *encodingList;
125
114
static GBool isInit = gFalse;
126
115
static bool groupIsIndirect;
127
116
static PdfObject lastGroup;
133
122
 
134
123
struct PdfDocument {
135
124
    char *file_path;            // full file name including path
 
125
    char *checksum;             // for reopening
136
126
    PDFDoc *doc;
137
127
    XRef *xref;
138
 
    InObj *inObjList;
 
128
    InObj *inObjList;           // temporary linked list
 
129
    avl_table *ObjMapTree;      // permanent over luatex run
139
130
    int occurences;             // number of references to the PdfDocument; it can be deleted when occurences == 0
140
131
};
141
132
 
142
 
/* AVL sort PdfDocument into PdfDocumentTree by file_path */
 
133
// AVL sort PdfDocument into PdfDocumentTree by file_path
143
134
 
144
 
static int CompPdfDocument(const void *pa, const void *pb, void *p)
 
135
static int CompPdfDocument(const void *pa, const void *pb, void * /*p */ )
145
136
{
146
137
    return strcmp(((const PdfDocument *) pa)->file_path,
147
138
                  ((const PdfDocument *) pb)->file_path);
154
145
    PdfDocument *pdf_doc, tmp;
155
146
    assert(file_path != NULL);
156
147
    if (PdfDocumentTree == NULL)
157
 
        PdfDocumentTree = avl_create(CompPdfDocument, NULL, &avl_xallocator);
158
 
    assert(PdfDocumentTree != NULL);
 
148
        return NULL;
159
149
    tmp.file_path = file_path;
160
150
    pdf_doc = (PdfDocument *) avl_find(PdfDocumentTree, &tmp);
161
151
    return pdf_doc;
164
154
// Returns pointer to PdfDocument structure for PDF file.
165
155
// Creates a new structure if it doesn't exist yet.
166
156
 
 
157
char *get_file_checksum(char *a);
 
158
 
167
159
static PdfDocument *refPdfDocument(char *file_path)
168
160
{
169
161
    PdfDocument *pdf_doc = findPdfDocument(file_path);
170
162
    if (pdf_doc == NULL) {
 
163
        if (PdfDocumentTree == NULL)
 
164
            PdfDocumentTree =
 
165
                avl_create(CompPdfDocument, NULL, &avl_xallocator);
171
166
        pdf_doc = new PdfDocument;
172
167
        pdf_doc->file_path = xstrdup(file_path);
 
168
        pdf_doc->checksum = get_file_checksum(file_path);
173
169
        void **aa = avl_probe(PdfDocumentTree, pdf_doc);
174
170
        assert(aa != NULL);
 
171
        pdf_doc->ObjMapTree = NULL;
 
172
        pdf_doc->doc = NULL;
 
173
    }
 
174
    if (pdf_doc->doc == NULL) {
175
175
        GString *docName = new GString(pdf_doc->file_path);
176
176
        pdf_doc->doc = new PDFDoc(docName);     // takes ownership of docName
177
177
        if (!pdf_doc->doc->isOk() || !pdf_doc->doc->okToPrint())
179
179
        pdf_doc->xref = NULL;
180
180
        pdf_doc->inObjList = NULL;
181
181
        pdf_doc->occurences = 0;        // 0 = unreferenced
 
182
    }
182
183
#ifdef DEBUG
183
 
        fprintf(stderr, "\nluatex Debug: Creating %s (%d)\n",
184
 
                pdf_doc->file_path, pdf_doc->occurences);
 
184
    fprintf(stderr, "\nluatex Debug: Creating %s (%d)\n",
 
185
            pdf_doc->file_path, pdf_doc->occurences);
185
186
#endif
186
 
    }
187
187
    pdf_doc->occurences++;
188
188
#ifdef DEBUG
189
189
    fprintf(stderr, "\nluatex Debug: Incrementing %s (%d)\n",
192
192
    return pdf_doc;
193
193
}
194
194
 
195
 
static void deletePdfDocument(PdfDocument *);
196
 
 
197
 
// Called when an image has been written and its resources in image_tab are
198
 
// freed and it's not referenced anymore.
199
 
 
200
 
void unrefPdfDocument(char *file_path)
201
 
{
202
 
    PdfDocument *pdf_doc = findPdfDocument(file_path);
 
195
//**********************************************************************
 
196
// keep the ObjMap struct small, as these are accumulated until the end
 
197
 
 
198
struct ObjMap {
 
199
    Ref in;                     // object num/gen in orig. PDF file
 
200
    int out_num;                // object num after embedding (gen == 0)
 
201
};
 
202
 
 
203
// AVL sort ObjMap into ObjMapTree by object number and generation
 
204
 
 
205
static int CompObjMap(const void *pa, const void *pb, void * /*p */ )
 
206
{
 
207
    const Ref *a = &(((const ObjMap *) pa)->in);
 
208
    const Ref *b = &(((const ObjMap *) pb)->in);
 
209
    if (a->num > b->num)
 
210
        return 1;
 
211
    if (a->num < b->num)
 
212
        return -1;
 
213
    if (a->gen == b->gen)       // most likely gen == 0 anyway
 
214
        return 0;
 
215
    if (a->gen < b->gen)
 
216
        return -1;
 
217
    return 1;
 
218
}
 
219
 
 
220
static ObjMap *findObjMap(PdfDocument * pdf_doc, Ref in)
 
221
{
 
222
    ObjMap *obj_map, tmp;
203
223
    assert(pdf_doc != NULL);
204
 
    assert(pdf_doc->occurences > 0);    // aim for point landing
205
 
    pdf_doc->occurences--;
206
 
#ifdef DEBUG
207
 
    fprintf(stderr, "\nluatex Debug: Decrementing %s (%d)\n",
208
 
            pdf_doc->file_path, pdf_doc->occurences);
209
 
#endif
210
 
    if (pdf_doc->occurences == 0) {
211
 
#ifdef DEBUG
212
 
        fprintf(stderr, "\nluatex Debug: Deleting %s\n", pdf_doc->file_path);
213
 
#endif
214
 
        void *a = avl_delete(PdfDocumentTree, pdf_doc);
215
 
        assert((PdfDocument *) a == pdf_doc);
216
 
        deletePdfDocument(pdf_doc);
217
 
    }
 
224
    if (pdf_doc->ObjMapTree == NULL)
 
225
        return NULL;
 
226
    tmp.in = in;
 
227
    obj_map = (ObjMap *) avl_find(pdf_doc->ObjMapTree, &tmp);
 
228
    return obj_map;
 
229
}
 
230
 
 
231
static void addObjMap(PdfDocument * pdf_doc, Ref in, int out_num)
 
232
{
 
233
    ObjMap *obj_map = NULL;
 
234
    assert(findObjMap(pdf_doc, in) == NULL);
 
235
    if (pdf_doc->ObjMapTree == NULL)
 
236
        pdf_doc->ObjMapTree = avl_create(CompObjMap, NULL, &avl_xallocator);
 
237
    obj_map = new ObjMap;
 
238
    obj_map->in = in;
 
239
    obj_map->out_num = out_num;
 
240
    void **aa = avl_probe(pdf_doc->ObjMapTree, obj_map);
 
241
    assert(aa != NULL);
218
242
}
219
243
 
220
244
//**********************************************************************
222
246
// Replacement for
223
247
//      Object *initDict(Dict *dict1){ initObj(objDict); dict = dict1; return this; }
224
248
 
225
 
static void initDictFromDict(PdfObject & obj, Dict * dict)
 
249
static void initDictFromDict(PdfDocument * pdf_doc, PdfObject & obj,
 
250
                             Dict * dict)
226
251
{
227
 
    obj->initDict(xref);
 
252
    obj->initDict(pdf_doc->xref);
228
253
    for (int i = 0, l = dict->getLength(); i < l; i++) {
229
254
        Object obj1;
230
255
        obj->dictAdd(copyString(dict->getKey(i)), dict->getValNF(i, &obj1));
231
256
    }
232
257
}
233
258
 
234
 
static int addEncoding(GfxFont * gfont)
235
 
{
236
 
    UsedEncoding *n;
237
 
    n = new UsedEncoding;
238
 
    n->next = encodingList;
239
 
    encodingList = n;
240
 
    n->font = gfont;
241
 
    n->enc_objnum = pdf_new_objnum();
242
 
    return n->enc_objnum;
243
 
}
244
 
 
245
 
#define addFont(ref, fd, enc_objnum) \
246
 
        addInObj(objFont, ref, fd, enc_objnum)
247
 
 
248
 
// addFontDesc is only used to avoid writing the original FontDescriptor
249
 
// from the PDF file.
250
 
 
251
 
#define addFontDesc(ref, fd) \
252
 
        addInObj(objFontDesc, ref, fd, 0)
253
 
 
254
 
#define addOther(ref) \
255
 
        addInObj(objOther, ref, NULL, 0)
256
 
 
257
 
static int addInObj(InObjType type, Ref ref, fd_entry * fd, integer e)
258
 
{
259
 
    InObj *p, *q, *n = new InObj;
260
 
    if (ref.num == 0)
261
 
        pdftex_fail("PDF inclusion: invalid reference");
 
259
static int addInObj(PDF pdf, PdfDocument * pdf_doc, Ref ref)
 
260
{
 
261
    ObjMap *obj_map;
 
262
    InObj *p, *q, *n;
 
263
    if (ref.num == 0) {
 
264
        pdftex_fail("PDF inclusion: reference to invalid object"
 
265
                    " (is the included pdf broken?)");
 
266
    }
 
267
    if ((obj_map = findObjMap(pdf_doc, ref)) != NULL)
 
268
        return obj_map->out_num;
 
269
    n = new InObj;
262
270
    n->ref = ref;
263
 
    n->type = type;
264
271
    n->next = NULL;
265
 
    n->fd = fd;
266
 
    n->enc_objnum = e;
267
 
    n->written = 0;
268
 
    if (inObjList == NULL)
269
 
        inObjList = n;
 
272
    n->num = pdf_new_objnum(pdf);
 
273
    addObjMap(pdf_doc, ref, n->num);
 
274
    if (pdf_doc->inObjList == NULL)
 
275
        pdf_doc->inObjList = n;
270
276
    else {
271
 
        for (p = inObjList; p != NULL; p = p->next) {
272
 
            if (p->ref.num == ref.num && p->ref.gen == ref.gen) {
273
 
                delete n;
274
 
                return p->num;
275
 
            }
276
 
            q = p;
277
 
        }
278
277
        // it is important to add new objects at the end of the list,
279
278
        // because new objects are being added while the list is being
280
279
        // written out by writeRefs().
 
280
        for (p = pdf_doc->inObjList; p != NULL; p = p->next)
 
281
            q = p;
281
282
        q->next = n;
282
283
    }
283
 
    if (type == objFontDesc)
284
 
        n->num = get_fd_objnum(fd);
285
 
    else
286
 
        n->num = pdf_new_objnum();
287
284
    return n->num;
288
285
}
289
286
 
290
 
static void copyName(char *s)
 
287
static void copyName(PDF pdf, char *s)
291
288
{
292
 
    pdf_puts("/");
 
289
    pdf_puts(pdf, "/");
293
290
    for (; *s != 0; s++) {
294
291
        if (isdigit(*s) || isupper(*s) || islower(*s) || *s == '_' ||
295
292
            *s == '.' || *s == '-' || *s == '+')
296
 
            pdfout(*s);
 
293
            pdf_out(pdf, *s);
297
294
        else
298
 
            pdf_printf("#%.2X", *s & 0xFF);
 
295
            pdf_printf(pdf, "#%.2X", *s & 0xFF);
299
296
    }
300
297
}
301
298
 
302
 
static int getNewObjectNumber(Ref ref)
 
299
static int getNewObjectNumber(PdfDocument * pdf_doc, Ref ref)
303
300
{
304
 
    InObj *p;
305
 
    if (inObjList == 0) {
306
 
        pdftex_fail("No objects copied yet");
307
 
    } else {
308
 
        for (p = inObjList; p != 0; p = p->next) {
309
 
            if (p->ref.num == ref.num && p->ref.gen == ref.gen) {
310
 
                return p->num;
311
 
            }
312
 
        }
313
 
        pdftex_fail("Object not yet copied: %i %i", ref.num, ref.gen);
314
 
    }
 
301
    ObjMap *obj_map;
 
302
    if ((obj_map = findObjMap(pdf_doc, ref)) != NULL)
 
303
        return obj_map->out_num;
 
304
    pdftex_fail("Object not yet copied: %i %i", ref.num, ref.gen);
 
305
    return 0;
315
306
}
316
307
 
317
 
static void copyObject(Object *);
 
308
static void copyObject(PDF, PdfDocument *, Object *);
318
309
 
319
 
static void copyDictEntry(Object * obj, int i)
 
310
static void copyDictEntry(PDF pdf, PdfDocument * pdf_doc, Object * obj, int i)
320
311
{
321
312
    PdfObject obj1;
322
 
    copyName(obj->dictGetKey(i));
323
 
    pdf_puts(" ");
 
313
    copyName(pdf, obj->dictGetKey(i));
 
314
    pdf_puts(pdf, " ");
324
315
    obj->dictGetValNF(i, &obj1);
325
 
    copyObject(&obj1);
326
 
    pdf_puts("\n");
 
316
    copyObject(pdf, pdf_doc, &obj1);
 
317
    pdf_puts(pdf, "\n");
327
318
}
328
319
 
329
 
static void copyDict(Object * obj)
 
320
static void copyDict(PDF pdf, PdfDocument * pdf_doc, Object * obj)
330
321
{
331
322
    int i, l;
332
323
    if (!obj->isDict())
333
324
        pdftex_fail("PDF inclusion: invalid dict type <%s>",
334
325
                    obj->getTypeName());
335
326
    for (i = 0, l = obj->dictGetLength(); i < l; ++i)
336
 
        copyDictEntry(obj, i);
337
 
}
338
 
 
339
 
static void copyFontDict(Object * obj, InObj * r)
340
 
{
341
 
    int i, l;
342
 
    char *key;
343
 
    if (!obj->isDict())
344
 
        pdftex_fail("PDF inclusion: invalid dict type <%s>",
345
 
                    obj->getTypeName());
346
 
    pdf_puts("<<\n");
347
 
    assert(r->type == objFont); // FontDescriptor is in fd_tree
348
 
    for (i = 0, l = obj->dictGetLength(); i < l; ++i) {
349
 
        key = obj->dictGetKey(i);
350
 
        if (strncmp("FontDescriptor", key, strlen("FontDescriptor")) == 0
351
 
            || strncmp("BaseFont", key, strlen("BaseFont")) == 0
352
 
            || strncmp("Encoding", key, strlen("Encoding")) == 0)
353
 
            continue;           // skip original values
354
 
        copyDictEntry(obj, i);
355
 
    }
356
 
    // write new FontDescriptor, BaseFont, and Encoding
357
 
    pdf_printf("/FontDescriptor %d 0 R\n", (int) get_fd_objnum(r->fd));
358
 
    pdf_printf("/BaseFont %d 0 R\n", (int) get_fn_objnum(r->fd));
359
 
    pdf_printf("/Encoding %d 0 R\n", (int) r->enc_objnum);
360
 
    pdf_puts(">>");
361
 
}
362
 
 
363
 
static void copyStream(Stream * str)
 
327
        copyDictEntry(pdf, pdf_doc, obj, i);
 
328
}
 
329
 
 
330
static void copyStream(PDF pdf, Stream * str)
364
331
{
365
332
    int c;
366
333
    str->reset();
367
334
    while ((c = str->getChar()) != EOF) {
368
 
        pdfout(c);
369
 
        pdf_last_byte = c;
370
 
    }
371
 
}
372
 
 
373
 
static void copyProcSet(Object * obj)
374
 
{
375
 
    int i, l;
376
 
    PdfObject procset;
377
 
    if (!obj->isArray())
378
 
        pdftex_fail("PDF inclusion: invalid ProcSet array type <%s>",
379
 
                    obj->getTypeName());
380
 
    pdf_puts("/ProcSet [ ");
381
 
    for (i = 0, l = obj->arrayGetLength(); i < l; ++i) {
382
 
        obj->arrayGetNF(i, &procset);
383
 
        if (!procset->isName())
384
 
            pdftex_fail("PDF inclusion: invalid ProcSet entry type <%s>",
385
 
                        procset->getTypeName());
386
 
        copyName(procset->getName());
387
 
        pdf_puts(" ");
388
 
    }
389
 
    pdf_puts("]\n");
390
 
}
391
 
 
392
 
#define REPLACE_TYPE1C true
393
 
 
394
 
static void copyFont(char *tag, Object * fontRef)
395
 
{
396
 
    PdfObject fontdict, subtype, basefont, fontdescRef, fontdesc, charset,
397
 
        fontfile, ffsubtype, stemV;
398
 
    GfxFont *gfont;
399
 
    fd_entry *fd;
400
 
    fm_entry *fontmap;
401
 
    // Check whether the font has already been embedded before analysing it.
402
 
    InObj *p;
403
 
    Ref ref = fontRef->getRef();
404
 
    for (p = inObjList; p; p = p->next) {
405
 
        if (p->ref.num == ref.num && p->ref.gen == ref.gen) {
406
 
            copyName(tag);
407
 
            pdf_printf(" %d 0 R ", (int) p->num);
408
 
            return;
409
 
        }
410
 
    }
411
 
    // Only handle included Type1 (and Type1C) fonts; anything else will be copied.
412
 
    // Type1C fonts are replaced by Type1 fonts, if REPLACE_TYPE1C is true.
413
 
    if (!fixed_inclusion_copy_font && fontRef->fetch(xref, &fontdict)->isDict()
414
 
        && fontdict->dictLookup("Subtype", &subtype)->isName()
415
 
        && !strcmp(subtype->getName(), "Type1")
416
 
        && fontdict->dictLookup("BaseFont", &basefont)->isName()
417
 
        && fontdict->dictLookupNF("FontDescriptor", &fontdescRef)->isRef()
418
 
        && fontdescRef->fetch(xref, &fontdesc)->isDict()
419
 
        && (fontdesc->dictLookup("FontFile", &fontfile)->isStream()
420
 
            || (REPLACE_TYPE1C
421
 
                && fontdesc->dictLookup("FontFile3", &fontfile)->isStream()
422
 
                && fontfile->streamGetDict()->lookup("Subtype",
423
 
                                                     &ffsubtype)->isName()
424
 
                && !strcmp(ffsubtype->getName(), "Type1C")))
425
 
        && (fontmap = lookup_fontmap(basefont->getName())) != NULL) {
426
 
        // copy the value of /StemV
427
 
        fontdesc->dictLookup("StemV", &stemV);
428
 
        fd = epdf_create_fontdescriptor(fontmap, stemV->getInt());
429
 
        if (fontdesc->dictLookup("CharSet", &charset) &&
430
 
            charset->isString() && is_subsetable(fontmap))
431
 
            epdf_mark_glyphs(fd, charset->getString()->getCString());
432
 
        else
433
 
            embed_whole_font(fd);
434
 
        addFontDesc(fontdescRef->getRef(), fd);
435
 
        copyName(tag);
436
 
        gfont = GfxFont::makeFont(xref, tag, fontRef->getRef(),
437
 
                                  fontdict->getDict());
438
 
        pdf_printf(" %d 0 R ", addFont(fontRef->getRef(), fd,
439
 
                                       addEncoding(gfont)));
440
 
    } else {
441
 
        copyName(tag);
442
 
        pdf_puts(" ");
443
 
        copyObject(fontRef);
444
 
    }
445
 
}
446
 
 
447
 
static void copyFontResources(Object * obj)
448
 
{
449
 
    PdfObject fontRef;
450
 
    int i, l;
451
 
    if (!obj->isDict())
452
 
        pdftex_fail("PDF inclusion: invalid font resources dict type <%s>",
453
 
                    obj->getTypeName());
454
 
    pdf_puts("/Font << ");
455
 
    for (i = 0, l = obj->dictGetLength(); i < l; ++i) {
456
 
        obj->dictGetValNF(i, &fontRef);
457
 
        if (fontRef->isRef())
458
 
            copyFont(obj->dictGetKey(i), &fontRef);
459
 
        else
460
 
            pdftex_fail("PDF inclusion: invalid font in reference type <%s>",
461
 
                        fontRef->getTypeName());
462
 
    }
463
 
    pdf_puts(">>\n");
464
 
}
465
 
 
466
 
static void copyOtherResources(Object * obj, char *key)
467
 
{
468
 
    // copies all other resources (write_epdf handles Fonts and ProcSets),
469
 
    // but gives a warning if an object is not a dictionary.
470
 
 
471
 
    if (!obj->isDict())
472
 
        //FIXME: Write the message only to the log file
473
 
        pdftex_warn("PDF inclusion: invalid other resource which is no dict"
474
 
                    " (key '%s', type <%s>); copying it anyway.",
475
 
                    key, obj->getTypeName());
476
 
    copyName(key);
477
 
    pdf_puts(" ");
478
 
    copyObject(obj);
 
335
        pdf_out(pdf, c);
 
336
        pdf->last_byte = c;
 
337
    }
 
338
}
 
339
 
 
340
static void copyOtherResources(PDF pdf, PdfDocument * pdf_doc, Object * obj,
 
341
                               char *key)
 
342
{
 
343
    copyName(pdf, key);
 
344
    pdf_puts(pdf, " ");
 
345
    copyObject(pdf, pdf_doc, obj);
479
346
}
480
347
 
481
348
// Function onverts double to string; very small and very large numbers
536
403
    return (char *) buf;
537
404
}
538
405
 
539
 
static void copyObject(Object * obj)
 
406
static void copyObject(PDF pdf, PdfDocument * pdf_doc, Object * obj)
540
407
{
541
408
    PdfObject obj1;
542
409
    int i, l, c;
543
 
    Ref ref;
544
410
    char *p;
545
411
    GString *s;
546
412
    if (obj->isBool()) {
547
 
        pdf_printf("%s", obj->getBool()? "true" : "false");
 
413
        pdf_printf(pdf, "%s", obj->getBool()? "true" : "false");
548
414
    } else if (obj->isInt()) {
549
 
        pdf_printf("%i", obj->getInt());
 
415
        pdf_printf(pdf, "%i", obj->getInt());
550
416
    } else if (obj->isReal()) {
551
 
        pdf_printf("%s", convertNumToPDF(obj->getReal()));
 
417
        pdf_printf(pdf, "%s", convertNumToPDF(obj->getReal()));
552
418
    } else if (obj->isNum()) {
553
 
        pdf_printf("%s", convertNumToPDF(obj->getNum()));
 
419
        pdf_printf(pdf, "%s", convertNumToPDF(obj->getNum()));
554
420
    } else if (obj->isString()) {
555
421
        s = obj->getString();
556
422
        p = s->getCString();
557
423
        l = s->getLength();
558
424
        if (strlen(p) == (unsigned int) l) {
559
 
            pdf_puts("(");
 
425
            pdf_puts(pdf, "(");
560
426
            for (; *p != 0; p++) {
561
427
                c = (unsigned char) *p;
562
428
                if (c == '(' || c == ')' || c == '\\')
563
 
                    pdf_printf("\\%c", c);
 
429
                    pdf_printf(pdf, "\\%c", c);
564
430
                else if (c < 0x20 || c > 0x7F)
565
 
                    pdf_printf("\\%03o", c);
 
431
                    pdf_printf(pdf, "\\%03o", c);
566
432
                else
567
 
                    pdfout(c);
 
433
                    pdf_out(pdf, c);
568
434
            }
569
 
            pdf_puts(")");
 
435
            pdf_puts(pdf, ")");
570
436
        } else {
571
 
            pdf_puts("<");
 
437
            pdf_puts(pdf, "<");
572
438
            for (i = 0; i < l; i++) {
573
439
                c = s->getChar(i) & 0xFF;
574
 
                pdf_printf("%.2x", c);
 
440
                pdf_printf(pdf, "%.2x", c);
575
441
            }
576
 
            pdf_puts(">");
 
442
            pdf_puts(pdf, ">");
577
443
        }
578
444
    } else if (obj->isName()) {
579
 
        copyName(obj->getName());
 
445
        copyName(pdf, obj->getName());
580
446
    } else if (obj->isNull()) {
581
 
        pdf_puts("null");
 
447
        pdf_puts(pdf, "null");
582
448
    } else if (obj->isArray()) {
583
 
        pdf_puts("[");
 
449
        pdf_puts(pdf, "[");
584
450
        for (i = 0, l = obj->arrayGetLength(); i < l; ++i) {
585
451
            obj->arrayGetNF(i, &obj1);
586
452
            if (!obj1->isName())
587
 
                pdf_puts(" ");
588
 
            copyObject(&obj1);
 
453
                pdf_puts(pdf, " ");
 
454
            copyObject(pdf, pdf_doc, &obj1);
589
455
        }
590
 
        pdf_puts("]");
 
456
        pdf_puts(pdf, "]");
591
457
    } else if (obj->isDict()) {
592
 
        pdf_puts("<<\n");
593
 
        copyDict(obj);
594
 
        pdf_puts(">>");
 
458
        pdf_puts(pdf, "<<\n");
 
459
        copyDict(pdf, pdf_doc, obj);
 
460
        pdf_puts(pdf, ">>");
595
461
    } else if (obj->isStream()) {
596
 
        initDictFromDict(obj1, obj->streamGetDict());
 
462
        initDictFromDict(pdf_doc, obj1, obj->streamGetDict());
597
463
        obj->streamGetDict()->incRef();
598
 
        pdf_puts("<<\n");
599
 
        copyDict(&obj1);
600
 
        pdf_puts(">>\n");
601
 
        pdf_puts("stream\n");
602
 
        copyStream(obj->getStream()->getUndecodedStream());
603
 
        if (pdf_last_byte != '\n')
604
 
            pdf_puts("\n");
605
 
        pdf_puts("endstream");  // can't simply write pdf_end_stream()
 
464
        pdf_puts(pdf, "<<\n");
 
465
        copyDict(pdf, pdf_doc, &obj1);
 
466
        pdf_puts(pdf, ">>\n");
 
467
        pdf_puts(pdf, "stream\n");
 
468
        copyStream(pdf, obj->getStream()->getUndecodedStream());
 
469
        if (pdf->last_byte != '\n')
 
470
            pdf_puts(pdf, "\n");
 
471
        pdf_puts(pdf, "endstream");     // can't simply write pdf_end_stream()
606
472
    } else if (obj->isRef()) {
607
 
        ref = obj->getRef();
608
 
        if (ref.num == 0) {
609
 
            pdftex_fail
610
 
                ("PDF inclusion: reference to invalid object"
611
 
                 " (is the included pdf broken?)");
612
 
        } else
613
 
            pdf_printf("%d 0 R", addOther(ref));
 
473
        pdf_printf(pdf, "%d 0 R", addInObj(pdf, pdf_doc, obj->getRef()));
614
474
    } else {
615
475
        pdftex_fail("PDF inclusion: type <%s> cannot be copied",
616
476
                    obj->getTypeName());
617
477
    }
618
478
}
619
479
 
620
 
static void writeRefs()
621
 
{
622
 
    InObj *r;
623
 
    for (r = inObjList; r != NULL; r = r->next) {
624
 
        if (!r->written) {
625
 
            Object obj1;
626
 
            r->written = 1;
627
 
            xref->fetch(r->ref.num, r->ref.gen, &obj1);
628
 
            if (r->type == objFont) {
629
 
                assert(!obj1.isStream());
630
 
                zpdf_begin_obj(r->num, 2);      // \pdfobjcompresslevel = 2 is for this
631
 
                copyFontDict(&obj1, r);
632
 
                pdf_puts("\n");
633
 
                pdf_end_obj();
634
 
            } else if (r->type != objFontDesc) {        // /FontDescriptor is written via write_fontdescriptor()
635
 
                if (obj1.isStream())
636
 
                    zpdf_begin_obj(r->num, 0);
637
 
                else
638
 
                    zpdf_begin_obj(r->num, 2);  // \pdfobjcompresslevel = 2 is for this
639
 
                copyObject(&obj1);
640
 
                pdf_puts("\n");
641
 
                pdf_end_obj();
642
 
            }
643
 
            obj1.free();
644
 
        }
645
 
    }
646
 
}
647
 
 
648
 
static void writeEncodings()
649
 
{
650
 
    UsedEncoding *r, *n;
651
 
    char *glyphNames[256], *s;
652
 
    int i;
653
 
    for (r = encodingList; r != NULL; r = r->next) {
654
 
        for (i = 0; i < 256; i++) {
655
 
            if (r->font->isCIDFont()) {
656
 
                pdftex_fail
657
 
                    ("PDF inclusion: CID fonts are not supported"
658
 
                     " (try to disable font replacement to fix this)");
659
 
            }
660
 
            if ((s = ((Gfx8BitFont *) r->font)->getCharName(i)) != NULL)
661
 
                glyphNames[i] = s;
662
 
            else
663
 
                glyphNames[i] = notdef;
664
 
        }
665
 
        epdf_write_enc(glyphNames, r->enc_objnum);
666
 
    }
667
 
    for (r = encodingList; r != NULL; r = n) {
 
480
static void writeRefs(PDF pdf, PdfDocument * pdf_doc)
 
481
{
 
482
    InObj *r, *n;
 
483
    for (r = pdf_doc->inObjList; r != NULL;) {
 
484
        Object obj1;
 
485
        pdf_doc->xref->fetch(r->ref.num, r->ref.gen, &obj1);
 
486
        if (obj1.isStream())
 
487
            pdf_begin_obj(pdf, r->num, 0);
 
488
        else
 
489
            pdf_begin_obj(pdf, r->num, 2);      // \pdfobjcompresslevel = 2 is for this
 
490
        copyObject(pdf, pdf_doc, &obj1);
 
491
        pdf_puts(pdf, "\n");
 
492
        pdf_end_obj(pdf);
 
493
        obj1.free();
668
494
        n = r->next;
669
 
        delete r->font;
670
495
        delete r;
 
496
        pdf_doc->inObjList = r = n;
671
497
    }
672
498
}
673
499
 
674
 
// get the pagebox according to the pagebox_spec
 
500
// get the pagebox coordinates according to the pagebox_spec
675
501
 
676
 
static PDFRectangle *get_pagebox(Page * page, integer pagebox_spec)
 
502
static PDFRectangle *get_pagebox(Page * page, int pagebox_spec)
677
503
{
678
 
    if (pagebox_spec == pdf_box_spec_media)
 
504
    switch (pagebox_spec) {
 
505
    case PDF_BOX_SPEC_MEDIA:
679
506
        return page->getMediaBox();
680
 
    else if (pagebox_spec == pdf_box_spec_crop)
 
507
        break;
 
508
    case PDF_BOX_SPEC_CROP:
681
509
        return page->getCropBox();
682
 
    else if (pagebox_spec == pdf_box_spec_bleed)
 
510
        break;
 
511
    case PDF_BOX_SPEC_BLEED:
683
512
        return page->getBleedBox();
684
 
    else if (pagebox_spec == pdf_box_spec_trim)
 
513
        break;
 
514
    case PDF_BOX_SPEC_TRIM:
685
515
        return page->getTrimBox();
686
 
    else if (pagebox_spec == pdf_box_spec_art)
 
516
        break;
 
517
    case PDF_BOX_SPEC_ART:
687
518
        return page->getArtBox();
688
 
    else
 
519
        break;
 
520
    default:
689
521
        pdftex_fail("PDF inclusion: unknown value of pagebox spec (%i)",
690
522
                    (int) pagebox_spec);
 
523
    }
691
524
    return page->getMediaBox(); // to make the compiler happy
692
525
}
693
526
 
 
527
#define PDF_CHECKSUM_SIZE 32
 
528
char *get_file_checksum(char *a)
 
529
{
 
530
    struct stat finfo;
 
531
    char *ck = NULL;
 
532
    if (stat(a, &finfo) == 0) {
 
533
        off_t size = finfo.st_size;
 
534
        time_t mtime = finfo.st_mtime;
 
535
        ck = (char *) malloc(PDF_CHECKSUM_SIZE);
 
536
        if (ck == NULL)
 
537
            pdftex_fail("PDF inclusion: out of memory while processing '%s'",
 
538
                        a);
 
539
        snprintf(ck, PDF_CHECKSUM_SIZE, "%llu_%llu", (unsigned long long) size,
 
540
                 (unsigned long long) mtime);
 
541
    } else {
 
542
        pdftex_fail("PDF inclusion: could not stat() file '%s'", a);
 
543
    }
 
544
    return ck;
 
545
}
 
546
 
694
547
// Reads various information about the PDF and sets it up for later inclusion.
695
548
// This will fail if the PDF version of the PDF is higher than
696
549
// minor_pdf_version_wanted or page_name is given and can not be found.
698
551
// Returns the page number.
699
552
 
700
553
void
701
 
read_pdf_info(image_dict * idict, integer minor_pdf_version_wanted,
702
 
              integer pdf_inclusion_errorlevel)
 
554
read_pdf_info(PDF pdf,
 
555
              image_dict * idict, int minor_pdf_version_wanted,
 
556
              int pdf_inclusion_errorlevel, img_readtype_e readtype)
703
557
{
704
558
    PdfDocument *pdf_doc;
705
559
    Page *page;
706
560
    int rotate;
 
561
    char *checksum;
707
562
    PDFRectangle *pagebox;
708
563
    float pdf_version_found, pdf_version_wanted, xsize, ysize, xorig, yorig;
709
564
    assert(idict != NULL);
710
565
    assert(img_type(idict) == IMG_TYPE_PDF);
 
566
    assert(readtype == IMG_CLOSEINBETWEEN);     // only this is implemented
711
567
    // initialize
712
568
    if (isInit == gFalse) {
713
569
        globalParams = new GlobalParams();
714
570
        globalParams->setErrQuiet(gFalse);
715
571
        isInit = gTrue;
716
572
    }
 
573
    // calculate a checksum string
 
574
    checksum = get_file_checksum(img_filepath(idict));
717
575
    // open PDF file
718
576
    pdf_doc = refPdfDocument(img_filepath(idict));
 
577
    if (strncmp(pdf_doc->checksum, checksum, PDF_CHECKSUM_SIZE) != 0) {
 
578
        pdftex_fail("PDF inclusion: file has changed '%s'",
 
579
                    img_filename(idict));
 
580
    }
 
581
    free(checksum);
719
582
    // check PDF version
720
583
    // this works only for PDF 1.x -- but since any versions of PDF newer
721
584
    // than 1.x will not be backwards compatible to PDF 1.x, pdfTeX will
757
620
    // get the required page
758
621
    page = pdf_doc->doc->getCatalog()->getPage(img_pagenum(idict));
759
622
 
760
 
    // get the pagebox (media, crop...) to use.
 
623
    // get the pagebox coordinates (media, crop,...) to use.
761
624
    pagebox = get_pagebox(page, img_pagebox(idict));
762
625
    if (pagebox->x2 > pagebox->x1) {
763
626
        xorig = pagebox->x1;
801
664
             "/Rotate parameter in PDF file not multiple of 90 degrees.");
802
665
    }
803
666
    if (page->getGroup() != NULL) {
804
 
        initDictFromDict(lastGroup, page->getGroup());
 
667
        initDictFromDict(pdf_doc, lastGroup, page->getGroup());
805
668
        if (lastGroup->dictGetLength() > 0) {
806
669
            groupIsIndirect = lastGroup->isRef();
807
670
            if (groupIsIndirect) {
808
671
                // FIXME: Here we already copy the object. It would be
809
672
                // better to do this only after write_epdf, otherwise we
810
 
                // may copy ununsed /Group objects
811
 
                copyObject(&lastGroup);
 
673
                // may copy unused /Group objects
 
674
                copyObject(pdf, pdf_doc, &lastGroup);
812
675
                epdf_lastGroupObjectNum =
813
 
                    getNewObjectNumber(lastGroup->getRef());
 
676
                    getNewObjectNumber(pdf_doc, lastGroup->getRef());
 
677
                pdf_puts(pdf, "\n");
814
678
            } else {
815
679
                // make the group an indirect object; copying is done later
816
680
                // by write_additional_epdf_objects after write_epdf
817
 
                epdf_lastGroupObjectNum = pdf_new_objnum();
 
681
                epdf_lastGroupObjectNum = pdf_new_objnum(pdf);
818
682
            }
819
 
            pdf_puts("\n");
820
683
        }
821
684
    } else {
822
685
        epdf_lastGroupObjectNum = 0;
823
686
    }
824
 
 
 
687
    if (readtype == IMG_CLOSEINBETWEEN)
 
688
        unrefPdfDocument(img_filepath(idict));
825
689
}
826
690
 
827
691
// Writes the current epf_doc.
828
692
// Here the included PDF is copied, so most errors that can happen during PDF
829
693
// inclusion will arise here.
830
694
 
831
 
static void write_epdf1(image_dict * idict)
 
695
static void write_epdf1(PDF pdf, image_dict * idict)
832
696
{
833
697
    Page *page;
834
698
    PdfObject contents, obj1, obj2;
835
699
    PdfObject metadata, pieceinfo, separationInfo;
836
700
    Object info;
837
 
    char *key;
 
701
    char *key, *checksum;
838
702
    char s[256];
839
703
    int i, l;
840
 
    PdfDocument *pdf_doc = (PdfDocument *) findPdfDocument(img_filepath(idict));
841
 
    assert(pdf_doc != NULL);
842
 
    xref = pdf_doc->xref;
843
 
    inObjList = pdf_doc->inObjList;
844
 
    encodingList = NULL;
 
704
    PdfDocument *pdf_doc;
 
705
    assert(idict != NULL);
 
706
    // calculate a checksum string
 
707
    checksum = get_file_checksum(img_filepath(idict));
 
708
    // open PDF file
 
709
    pdf_doc = refPdfDocument(img_filepath(idict));
 
710
    if (strncmp(pdf_doc->checksum, checksum, PDF_CHECKSUM_SIZE) != 0) {
 
711
        pdftex_fail("PDF inclusion: file has changed '%s'",
 
712
                    img_filename(idict));
 
713
    }
 
714
    free(checksum);
 
715
    pdf_doc->xref = pdf_doc->doc->getXRef();
 
716
    (void) pdf_doc->doc->getCatalog()->getPage(img_pagenum(idict));
845
717
    page = pdf_doc->doc->getCatalog()->getPage(img_pagenum(idict));
846
718
    PDFRectangle *pagebox;
847
719
    float bbox[4];
848
720
    // write the Page header
849
 
    pdf_puts("/Type /XObject\n/Subtype /Form\n");
 
721
    pdf_puts(pdf, "/Type /XObject\n/Subtype /Form\n");
850
722
    if (img_attr(idict) != NULL && strlen(img_attr(idict)) > 0)
851
 
        pdf_printf("%s\n", img_attr(idict));
852
 
    pdf_puts("/FormType 1\n");
 
723
        pdf_printf(pdf, "%s\n", img_attr(idict));
 
724
    pdf_puts(pdf, "/FormType 1\n");
853
725
 
854
726
    // write additional information
855
 
    pdf_printf("/%s.FileName (%s)\n", pdfkeyprefix,
 
727
    pdf_printf(pdf, "/%s.FileName (%s)\n", pdfkeyprefix,
856
728
               convertStringToPDFString(pdf_doc->file_path,
857
729
                                        strlen(pdf_doc->file_path)));
858
 
    pdf_printf("/%s.PageNumber %i\n", pdfkeyprefix, (int) img_pagenum(idict));
 
730
    pdf_printf(pdf, "/%s.PageNumber %i\n", pdfkeyprefix,
 
731
               (int) img_pagenum(idict));
859
732
    pdf_doc->doc->getDocInfoNF(&info);
860
733
    if (info.isRef()) {
861
734
        // the info dict must be indirect (PDF Ref p. 61)
862
 
        pdf_printf("/%s.InfoDict ", pdfkeyprefix);
863
 
        pdf_printf("%d 0 R\n", addOther(info.getRef()));
 
735
        pdf_printf(pdf, "/%s.InfoDict ", pdfkeyprefix);
 
736
        pdf_printf(pdf, "%d 0 R\n", addInObj(pdf, pdf_doc, info.getRef()));
864
737
    }
865
738
    if (img_is_bbox(idict)) {
866
739
        bbox[0] = int2bp(img_bbox(idict)[0]);
868
741
        bbox[2] = int2bp(img_bbox(idict)[2]);
869
742
        bbox[3] = int2bp(img_bbox(idict)[3]);
870
743
    } else {
871
 
        // get the pagebox (media, crop...) to use.
 
744
        // get the pagebox coordinates (media, crop,...) to use.
872
745
        pagebox = get_pagebox(page, img_pagebox(idict));
873
746
        bbox[0] = pagebox->x1;
874
747
        bbox[1] = pagebox->y1;
877
750
    }
878
751
    sprintf(s, "/BBox [%.8f %.8f %.8f %.8f]\n", bbox[0], bbox[1], bbox[2],
879
752
            bbox[3]);
880
 
    pdf_puts(stripzeros(s));
 
753
    pdf_puts(pdf, stripzeros(s));
881
754
    // The /Matrix calculation is replaced by transforms in out_img().
882
755
 
883
756
    // write the page Group if it's there
884
757
    if (epdf_lastGroupObjectNum > 0) {
885
758
        if (page->getGroup() != NULL) {
886
 
            initDictFromDict(lastGroup, page->getGroup());
 
759
            initDictFromDict(pdf_doc, lastGroup, page->getGroup());
887
760
            if (lastGroup->dictGetLength() > 0) {
888
 
                pdf_puts("/Group ");
 
761
                pdf_puts(pdf, "/Group ");
889
762
                groupIsIndirect = lastGroup->isRef();
890
 
                pdf_printf("%d 0 R", (int) epdf_lastGroupObjectNum);
891
 
                pdf_puts("\n");
 
763
                pdf_printf(pdf, "%d 0 R", (int) epdf_lastGroupObjectNum);
 
764
                pdf_puts(pdf, "\n");
892
765
            }
893
766
        }
894
767
    }
895
768
    // write the page Metadata if it's there
896
769
    if (page->getMetadata() != NULL) {
897
770
        metadata->initStream(page->getMetadata());
898
 
        pdf_puts("/Metadata ");
899
 
        copyObject(&metadata);
900
 
        pdf_puts("\n");
 
771
        pdf_puts(pdf, "/Metadata ");
 
772
        copyObject(pdf, pdf_doc, &metadata);
 
773
        pdf_puts(pdf, "\n");
901
774
    }
902
775
    // write the page PieceInfo if it's there
903
776
    if (page->getPieceInfo() != NULL) {
904
 
        initDictFromDict(pieceinfo, page->getPieceInfo());
 
777
        initDictFromDict(pdf_doc, pieceinfo, page->getPieceInfo());
905
778
        if (pieceinfo->dictGetLength() > 0) {
906
 
            pdf_puts("/PieceInfo ");
907
 
            copyObject(&pieceinfo);
908
 
            pdf_puts("\n");
 
779
            pdf_puts(pdf, "/PieceInfo ");
 
780
            copyObject(pdf, pdf_doc, &pieceinfo);
 
781
            pdf_puts(pdf, "\n");
909
782
        }
910
783
    }
911
784
    // copy LastModified (needed when PieceInfo is there)
912
785
    if (page->getLastModified() != NULL) {
913
 
        pdf_printf("/LastModified (%s)\n",
 
786
        pdf_printf(pdf, "/LastModified (%s)\n",
914
787
                   page->getLastModified()->getCString());
915
788
    }
916
789
    // write the page SeparationInfo if it's there
917
790
    if (page->getSeparationInfo() != NULL) {
918
 
        initDictFromDict(separationInfo, page->getSeparationInfo());
 
791
        initDictFromDict(pdf_doc, separationInfo, page->getSeparationInfo());
919
792
        if (separationInfo->dictGetLength() > 0) {
920
 
            pdf_puts("/SeparationInfo ");
921
 
            copyObject(&separationInfo);
922
 
            pdf_puts("\n");
 
793
            pdf_puts(pdf, "/SeparationInfo ");
 
794
            copyObject(pdf, pdf_doc, &separationInfo);
 
795
            pdf_puts(pdf, "\n");
923
796
        }
924
797
    }
925
798
    // write the Resources dictionary
930
803
        pdftex_warn
931
804
            ("PDF inclusion: /Resources missing. 'This practice is not recommended' (PDF Ref)");
932
805
    } else {
933
 
        initDictFromDict(obj1, page->getResourceDict());
 
806
        initDictFromDict(pdf_doc, obj1, page->getResourceDict());
934
807
        page->getResourceDict()->incRef();
935
808
        if (!obj1->isDict())
936
809
            pdftex_fail("PDF inclusion: invalid resources dict type <%s>",
937
810
                        obj1->getTypeName());
938
 
        pdf_puts("/Resources <<\n");
 
811
        pdf_puts(pdf, "/Resources <<\n");
939
812
        for (i = 0, l = obj1->dictGetLength(); i < l; ++i) {
940
813
            obj1->dictGetVal(i, &obj2);
941
814
            key = obj1->dictGetKey(i);
942
 
            if (strcmp("Font", key) == 0)
943
 
                copyFontResources(&obj2);
944
 
            else if (strcmp("ProcSet", key) == 0)
945
 
                copyProcSet(&obj2);
946
 
            else
947
 
                copyOtherResources(&obj2, key);
 
815
            copyOtherResources(pdf, pdf_doc, &obj2, key);
948
816
        }
949
 
        pdf_puts(">>\n");
 
817
        pdf_puts(pdf, ">>\n");
950
818
    }
951
819
    // write the page contents
952
820
    page->getContents(&contents);
960
828
 
961
829
        // Variant B: copy stream without recompressing
962
830
        //
963
 
        contents->streamGetDict()->lookup("F", &obj1);
 
831
        contents->streamGetDict()->lookup((char *) "F", &obj1);
964
832
        if (!obj1->isNull()) {
965
833
            pdftex_fail("PDF inclusion: Unsupported external stream");
966
834
        }
967
 
        contents->streamGetDict()->lookup("Length", &obj1);
 
835
        contents->streamGetDict()->lookup((char *) "Length", &obj1);
968
836
        assert(!obj1->isNull());
969
 
        pdf_puts("/Length ");
970
 
        copyObject(&obj1);
971
 
        pdf_puts("\n");
972
 
        contents->streamGetDict()->lookup("Filter", &obj1);
 
837
        pdf_puts(pdf, "/Length ");
 
838
        copyObject(pdf, pdf_doc, &obj1);
 
839
        pdf_puts(pdf, "\n");
 
840
        contents->streamGetDict()->lookup((char *) "Filter", &obj1);
973
841
        if (!obj1->isNull()) {
974
 
            pdf_puts("/Filter ");
975
 
            copyObject(&obj1);
976
 
            pdf_puts("\n");
977
 
            contents->streamGetDict()->lookup("DecodeParms", &obj1);
 
842
            pdf_puts(pdf, "/Filter ");
 
843
            copyObject(pdf, pdf_doc, &obj1);
 
844
            pdf_puts(pdf, "\n");
 
845
            contents->streamGetDict()->lookup((char *) "DecodeParms", &obj1);
978
846
            if (!obj1->isNull()) {
979
 
                pdf_puts("/DecodeParms ");
980
 
                copyObject(&obj1);
981
 
                pdf_puts("\n");
 
847
                pdf_puts(pdf, "/DecodeParms ");
 
848
                copyObject(pdf, pdf_doc, &obj1);
 
849
                pdf_puts(pdf, "\n");
982
850
            }
983
851
        }
984
 
        pdf_puts(">>\nstream\n");
985
 
        copyStream(contents->getStream()->getBaseStream());
986
 
        pdf_end_stream();
 
852
        pdf_puts(pdf, ">>\nstream\n");
 
853
        copyStream(pdf, contents->getStream()->getBaseStream());
 
854
        pdf_end_stream(pdf);
987
855
    } else if (contents->isArray()) {
988
 
        pdf_begin_stream();
 
856
        pdf_begin_stream(pdf);
989
857
        for (i = 0, l = contents->arrayGetLength(); i < l; ++i) {
990
858
            Object contentsobj;
991
 
            copyStream((contents->arrayGet(i, &contentsobj))->getStream());
 
859
            copyStream(pdf, (contents->arrayGet(i, &contentsobj))->getStream());
992
860
            contentsobj.free();
993
861
        }
994
 
        pdf_end_stream();
 
862
        pdf_end_stream(pdf);
995
863
    } else {                    // the contents are optional, but we need to include an empty stream
996
 
        pdf_begin_stream();
997
 
        pdf_end_stream();
 
864
        pdf_begin_stream(pdf);
 
865
        pdf_end_stream(pdf);
998
866
    }
999
867
    // write out all indirect objects
1000
 
    writeRefs();
1001
 
    // write out all used encodings (and delete list)
1002
 
    writeEncodings();
1003
 
    // save object list
1004
 
    pdf_doc->inObjList = inObjList;
1005
 
    assert(xref == pdf_doc->xref);      // xref should be unchanged
 
868
    writeRefs(pdf, pdf_doc);
1006
869
}
1007
870
 
1008
 
void write_epdf(image_dict * idict)
 
871
// this relay function is needed to keep some destructor quiet (???)
 
872
 
 
873
void write_epdf(PDF pdf, image_dict * idict)
1009
874
{
1010
 
    assert(idict != NULL);
1011
 
    write_epdf1(idict);
 
875
    write_epdf1(pdf, idict);
1012
876
    unrefPdfDocument(img_filepath(idict));
1013
877
}
1014
878
 
1015
879
//**********************************************************************
1016
880
// Deallocate a PdfDocument with all its resources
1017
881
 
1018
 
static void deletePdfDocument(PdfDocument * pdf_doc)
 
882
static void deletePdfDocumentPdfDoc(PdfDocument * pdf_doc)
1019
883
{
 
884
    InObj *r, *n;
1020
885
    assert(pdf_doc != NULL);
1021
 
    // free PdfDocument's resources
1022
 
    InObj *r, *n;
 
886
    // this may be probably needed for an emergency destroyPdfDocument()
1023
887
    for (r = pdf_doc->inObjList; r != NULL; r = n) {
1024
888
        n = r->next;
1025
889
        delete r;
1026
890
    }
1027
891
    delete pdf_doc->doc;
1028
 
    xfree(pdf_doc->file_path);
1029
 
    delete pdf_doc;
 
892
    pdf_doc->doc = NULL;
1030
893
}
1031
894
 
1032
 
static void destroyPdfDocument(void *pa, void *pb)
 
895
static void destroyPdfDocument(void *pa, void * /*pb */ )
1033
896
{
1034
897
    PdfDocument *pdf_doc = (PdfDocument *) pa;
1035
 
    deletePdfDocument(pdf_doc);
 
898
    deletePdfDocumentPdfDoc(pdf_doc);
 
899
    // TODO: delete rest of pdf_doc
 
900
}
 
901
 
 
902
// Called when an image has been written and its resources in image_tab are
 
903
// freed and it's not referenced anymore.
 
904
 
 
905
void unrefPdfDocument(char *file_path)
 
906
{
 
907
    PdfDocument *pdf_doc = findPdfDocument(file_path);
 
908
    assert(pdf_doc != NULL);
 
909
    assert(pdf_doc->occurences > 0);    // aim for point landing
 
910
    pdf_doc->occurences--;
 
911
#ifdef DEBUG
 
912
    fprintf(stderr, "\nluatex Debug: Decrementing %s (%d)\n",
 
913
            pdf_doc->file_path, pdf_doc->occurences);
 
914
#endif
 
915
    if (pdf_doc->occurences == 0) {
 
916
#ifdef DEBUG
 
917
        fprintf(stderr, "\nluatex Debug: Deleting %s\n", pdf_doc->file_path);
 
918
#endif
 
919
        assert(pdf_doc->inObjList == NULL);     // should be eaten up already
 
920
        deletePdfDocumentPdfDoc(pdf_doc);
 
921
    }
1036
922
}
1037
923
 
1038
924
// Called when PDF embedding system is finalized.
1050
936
 
1051
937
// Called after the xobject generated by write_epdf has been finished; used to
1052
938
// write out objects that have been made indirect
1053
 
void write_additional_epdf_objects(void)
 
939
 
 
940
void write_additional_epdf_objects(PDF pdf, char *file_path)
1054
941
{
 
942
    PdfDocument *pdf_doc = findPdfDocument(file_path);
1055
943
    if ((epdf_lastGroupObjectNum > 0) && !groupIsIndirect) {
1056
 
        zpdf_begin_obj(epdf_lastGroupObjectNum, 2);
1057
 
        copyObject(&lastGroup);
1058
 
        pdf_end_obj();
 
944
        pdf_begin_obj(pdf, epdf_lastGroupObjectNum, 2);
 
945
        copyObject(pdf, pdf_doc, &lastGroup);
 
946
        pdf_end_obj(pdf);
1059
947
    }
1060
948
}