]> git.donarmstrong.com Git - xournal.git/blob - src/xo-print.c
2cfc18ecd46dac68ac5b1581e504732e82a6d16c
[xournal.git] / src / xo-print.c
1 /*
2  *  This program is free software; you can redistribute it and/or
3  *  modify it under the terms of the GNU General Public
4  *  License as published by the Free Software Foundation; either
5  *  version 2 of the License, or (at your option) any later version.
6  *
7  *  This software is distributed in the hope that it will be useful,
8  *  but WITHOUT ANY WARRANTY; without even the implied warranty of  
9  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
10  *  General Public License for more details.
11  *
12  *  You should have received a copy of the GNU General Public License
13  *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
14  */
15
16 #ifdef HAVE_CONFIG_H
17 #  include <config.h>
18 #endif
19
20 #define PANGO_ENABLE_BACKEND /* to access PangoFcFont.font_pattern */
21
22 #include <gtk/gtk.h>
23 #include <libgnomecanvas/libgnomecanvas.h>
24 #include <zlib.h>
25 #include <string.h>
26 #include <locale.h>
27 #include <pango/pango.h>
28 #include <pango/pangofc-font.h>
29 #include <pango/pangoft2.h>
30 #include <fontconfig/fontconfig.h>
31 #include <ft2build.h>
32 #include FT_FREETYPE_H
33
34 #define NO_MAPPERS
35 #define NO_TYPE3
36 #define NO_TYPE42
37 #include "ttsubset/sft.h"
38
39 #include "xournal.h"
40 #include "xo-support.h"
41 #include "xo-misc.h"
42 #include "xo-paint.h"
43 #include "xo-print.h"
44 #include "xo-file.h"
45
46 #define RGBA_RED(rgba) (((rgba>>24)&0xff)/255.0)
47 #define RGBA_GREEN(rgba) (((rgba>>16)&0xff)/255.0)
48 #define RGBA_BLUE(rgba) (((rgba>>8)&0xff)/255.0)
49 #define RGBA_ALPHA(rgba) (((rgba>>0)&0xff)/255.0)
50 #define RGBA_RGB(rgba) RGBA_RED(rgba), RGBA_GREEN(rgba), RGBA_BLUE(rgba)
51
52 /*********** Printing to PDF ************/
53
54 gboolean ispdfspace(char c)
55 {
56   return (c==0 || c==9 || c==10 || c==12 || c==13 || c==' ');
57 }
58
59 gboolean ispdfdelim(char c)
60 {
61   return (c=='(' || c==')' || c=='<' || c=='>' || c=='[' || c==']' ||
62           c=='{' || c=='}' || c=='/' || c=='%');
63 }
64
65 void skipspace(char **p, char *eof)
66 {
67   while (ispdfspace(**p) || **p=='%') {
68     if (**p=='%') while (*p!=eof && **p!=10 && **p!=13) (*p)++;
69     if (*p==eof) return;
70     (*p)++;
71   }
72 }
73
74 void free_pdfobj(struct PdfObj *obj)
75 {
76   int i;
77   
78   if (obj==NULL) return;
79   if ((obj->type == PDFTYPE_STRING || obj->type == PDFTYPE_NAME ||
80       obj->type == PDFTYPE_STREAM) && obj->str!=NULL)
81     g_free(obj->str);
82   if ((obj->type == PDFTYPE_ARRAY || obj->type == PDFTYPE_DICT ||
83       obj->type == PDFTYPE_STREAM) && obj->num>0) {
84     for (i=0; i<obj->num; i++)
85       free_pdfobj(obj->elts[i]);
86     g_free(obj->elts);
87   }
88   if ((obj->type == PDFTYPE_DICT || obj->type == PDFTYPE_STREAM) && obj->num>0) {
89     for (i=0; i<obj->num; i++)
90       g_free(obj->names[i]);
91     g_free(obj->names);
92   }
93   g_free(obj);
94 }
95
96 struct PdfObj *dup_pdfobj(struct PdfObj *obj)
97 {
98   struct PdfObj *dup;
99   int i;
100   
101   if (obj==NULL) return NULL;
102   dup = g_memdup(obj, sizeof(struct PdfObj));
103   if ((obj->type == PDFTYPE_STRING || obj->type == PDFTYPE_NAME ||
104       obj->type == PDFTYPE_STREAM) && obj->str!=NULL) {
105     if (obj->type == PDFTYPE_NAME) obj->len = strlen(obj->str);
106     dup->str = g_memdup(obj->str, obj->len+1);
107   }
108   if ((obj->type == PDFTYPE_ARRAY || obj->type == PDFTYPE_DICT ||
109       obj->type == PDFTYPE_STREAM) && obj->num>0) {
110     dup->elts = g_malloc(obj->num*sizeof(struct PdfObj *));
111     for (i=0; i<obj->num; i++)
112       dup->elts[i] = dup_pdfobj(obj->elts[i]);
113   }
114   if ((obj->type == PDFTYPE_DICT || obj->type == PDFTYPE_STREAM) && obj->num>0) {
115     dup->names = g_malloc(obj->num*sizeof(char *));
116     for (i=0; i<obj->num; i++)
117       dup->names[i] = g_strdup(obj->names[i]);
118   }
119   return dup;
120 }
121
122 void show_pdfobj(struct PdfObj *obj, GString *str)
123 {
124   int i;
125   if (obj==NULL) return;
126   switch(obj->type) {
127     case PDFTYPE_CST:
128       if (obj->intval==1) g_string_append(str, "true");
129       if (obj->intval==0) g_string_append(str, "false");
130       if (obj->intval==-1) g_string_append(str, "null");
131       break;
132     case PDFTYPE_INT:
133       g_string_append_printf(str, "%d", obj->intval);
134       break;
135     case PDFTYPE_REAL:
136       g_string_append_printf(str, "%f", obj->realval);
137       break;
138     case PDFTYPE_STRING:
139       g_string_append_len(str, obj->str, obj->len);
140       break;
141     case PDFTYPE_NAME:
142       g_string_append(str, obj->str);
143       break;
144     case PDFTYPE_ARRAY:
145       g_string_append_c(str, '[');
146       for (i=0;i<obj->num;i++) {
147         if (i) g_string_append_c(str, ' ');
148         show_pdfobj(obj->elts[i], str);
149       }
150       g_string_append_c(str, ']');
151       break;
152     case PDFTYPE_DICT:
153       g_string_append(str, "<<");
154       for (i=0;i<obj->num;i++) {
155         g_string_append_printf(str, " %s ", obj->names[i]); 
156         show_pdfobj(obj->elts[i], str);
157       }
158       g_string_append(str, " >>");
159       break;
160     case PDFTYPE_REF:
161       g_string_append_printf(str, "%d %d R", obj->intval, obj->num);
162       break;
163   }
164 }
165
166 void DEBUG_PRINTOBJ(struct PdfObj *obj)
167 {
168   GString *s = g_string_new("");
169   show_pdfobj(obj, s);
170   puts(s->str);
171   g_string_free(s, TRUE);
172 }
173
174 // parse a PDF object; returns NULL if fails
175 // THIS PARSER DOES NOT RECOGNIZE STREAMS YET
176
177 struct PdfObj *parse_pdf_object(char **ptr, char *eof)
178 {
179   struct PdfObj *obj, *elt;
180   char *p, *q, *r, *eltname;
181   int stack;
182
183   obj = g_malloc(sizeof(struct PdfObj));
184   p = *ptr;
185   skipspace(&p, eof);
186   if (p==eof) { g_free(obj); return NULL; }
187   
188   // maybe a constant
189   if (!strncmp(p, "true", 4)) {
190     obj->type = PDFTYPE_CST;
191     obj->intval = 1;
192     *ptr = p+4;
193     return obj;
194   }
195   if (!strncmp(p, "false", 5)) {
196     obj->type = PDFTYPE_CST;
197     obj->intval = 0;
198     *ptr = p+5;
199     return obj;
200   }
201   if (!strncmp(p, "null", 4)) {
202     obj->type = PDFTYPE_CST;
203     obj->intval = -1;
204     *ptr = p+4;
205     return obj;
206   }
207
208   // or a number ?
209   obj->intval = strtol(p, &q, 10);
210   *ptr = q;
211   if (q!=p) {
212     if (*q == '.') {
213       obj->type = PDFTYPE_REAL;
214       obj->realval = g_ascii_strtod(p, ptr);
215       return obj;
216     }
217     if (ispdfspace(*q)) {
218       // check for indirect reference
219       skipspace(&q, eof);
220       obj->num = strtol(q, &r, 10);
221       if (r!=q) {
222         skipspace(&r, eof);
223         if (*r=='R') {
224           *ptr = r+1;
225           obj->type = PDFTYPE_REF;
226           return obj;
227         }
228       }
229     }
230     obj->type = PDFTYPE_INT;
231     return obj;
232   }
233
234   // a string ?
235   if (*p=='(') {
236     q=p+1; stack=1;
237     while (stack>0 && q!=eof) {
238       if (*q=='(') stack++;
239       if (*q==')') stack--;
240       if (*q=='\\') q++;
241       if (q!=eof) q++;
242     }
243     if (q==eof) { g_free(obj); return NULL; }
244     obj->type = PDFTYPE_STRING;
245     obj->len = q-p;
246     obj->str = g_malloc(obj->len+1);
247     obj->str[obj->len] = 0;
248     g_memmove(obj->str, p, obj->len);
249     *ptr = q;
250     return obj;
251   }  
252   if (*p=='<' && p[1]!='<') {
253     q=p+1;
254     while (*q!='>' && q!=eof) q++;
255     if (q==eof) { g_free(obj); return NULL; }
256     q++;
257     obj->type = PDFTYPE_STRING;
258     obj->len = q-p;
259     obj->str = g_malloc(obj->len+1);
260     obj->str[obj->len] = 0;
261     g_memmove(obj->str, p, obj->len);
262     *ptr = q;
263     return obj;
264   }
265   
266   // a name ?
267   if (*p=='/') {
268     q=p+1;
269     while (!ispdfspace(*q) && !ispdfdelim(*q)) q++;
270     obj->type = PDFTYPE_NAME;
271     obj->str = g_strndup(p, q-p);
272     *ptr = q;
273     return obj;
274   }
275
276   // an array ?
277   if (*p=='[') {
278     obj->type = PDFTYPE_ARRAY;
279     obj->num = 0;
280     obj->elts = NULL;
281     q=p+1; skipspace(&q, eof);
282     while (*q!=']') {
283       elt = parse_pdf_object(&q, eof);
284       if (elt==NULL) { free_pdfobj(obj); return NULL; }
285       obj->num++;
286       obj->elts = g_realloc(obj->elts, obj->num*sizeof(struct PdfObj *));
287       obj->elts[obj->num-1] = elt;
288       skipspace(&q, eof);
289     }
290     *ptr = q+1;
291     return obj;
292   }
293
294   // a dictionary ?
295   if (*p=='<' && p[1]=='<') {
296     obj->type = PDFTYPE_DICT;
297     obj->num = 0;
298     obj->elts = NULL;
299     obj->names = NULL;
300     q=p+2; skipspace(&q, eof);
301     while (*q!='>' || q[1]!='>') {
302       if (*q!='/') { free_pdfobj(obj); return NULL; }
303       r=q+1;
304       while (!ispdfspace(*r) && !ispdfdelim(*r)) r++;
305       eltname = g_strndup(q, r-q);
306       q=r; skipspace(&q, eof);
307       elt = parse_pdf_object(&q, eof);
308       if (elt==NULL) { g_free(eltname); free_pdfobj(obj); return NULL; }
309       obj->num++;
310       obj->elts = g_realloc(obj->elts, obj->num*sizeof(struct PdfObj *));
311       obj->names = g_realloc(obj->names, obj->num*sizeof(char *));
312       obj->elts[obj->num-1] = elt;
313       obj->names[obj->num-1] = eltname;
314       skipspace(&q, eof);
315     }
316     *ptr = q+2;
317     return obj;
318   }
319
320   // DOES NOT RECOGNIZE STREAMS YET (handle as subcase of dictionary)
321   
322   g_free(obj);
323   return NULL;
324 }
325
326 struct PdfObj *get_dict_entry(struct PdfObj *dict, char *name)
327 {
328   int i;
329   
330   if (dict==NULL) return NULL;
331   if (dict->type != PDFTYPE_DICT) return NULL;
332   for (i=0; i<dict->num; i++) 
333     if (!strcmp(dict->names[i], name)) return dict->elts[i];
334   return NULL;
335 }
336
337 struct PdfObj *get_pdfobj(GString *pdfbuf, struct XrefTable *xref, struct PdfObj *obj)
338 {
339   char *p, *eof;
340   int offs, n;
341
342   if (obj==NULL) return NULL;
343   if (obj->type!=PDFTYPE_REF) return dup_pdfobj(obj);
344   if (obj->intval>xref->last) return NULL;
345   offs = xref->data[obj->intval];
346   if (offs<=0 || offs >= pdfbuf->len) return NULL;
347
348   p = pdfbuf->str + offs;
349   eof = pdfbuf->str + pdfbuf->len;
350   n = strtol(p, &p, 10);
351   if (n!=obj->intval) return NULL;
352   skipspace(&p, eof);
353   n = strtol(p, &p, 10);
354   skipspace(&p, eof);
355   if (strncmp(p, "obj", 3)) return NULL;
356   p+=3;
357   return parse_pdf_object(&p, eof);
358 }
359
360 // read the xref table of a PDF file in memory, and return the trailerdict
361
362 struct PdfObj *parse_xref_table(GString *pdfbuf, struct XrefTable *xref, int offs)
363 {
364   char *p, *eof;
365   struct PdfObj *trailerdict, *obj;
366   int start, len, i;
367   
368   if (strncmp(pdfbuf->str+offs, "xref", 4)) return NULL;
369   p = strstr(pdfbuf->str+offs, "trailer");
370   eof = pdfbuf->str + pdfbuf->len;
371   if (p==NULL) return NULL;
372   p+=8;
373   trailerdict = parse_pdf_object(&p, eof);
374   obj = get_dict_entry(trailerdict, "/Size");
375   if (obj!=NULL && obj->type == PDFTYPE_INT && obj->intval-1>xref->last)
376     make_xref(xref, obj->intval-1, 0);
377   obj = get_dict_entry(trailerdict, "/Prev");
378   if (obj!=NULL && obj->type == PDFTYPE_INT && obj->intval>0 && obj->intval!=offs) {
379     // recurse into older xref table
380     obj = parse_xref_table(pdfbuf, xref, obj->intval);
381     free_pdfobj(obj);
382   }
383   p = pdfbuf->str+offs+4;
384   skipspace(&p, eof);
385   if (*p<'0' || *p>'9') { free_pdfobj(trailerdict); return NULL; }
386   while (*p>='0' && *p<='9') {
387     start = strtol(p, &p, 10);
388     skipspace(&p, eof);
389     len = strtol(p, &p, 10);
390     skipspace(&p, eof);
391     if (len <= 0 || 20*len > eof-p) break;
392     if (start+len-1 > xref->last) make_xref(xref, start+len-1, 0);
393     for (i=start; i<start+len; i++) {
394       xref->data[i] = strtol(p, NULL, 10);
395       p+=20;
396     }
397     skipspace(&p, eof);
398   }
399   if (*p!='t') { free_pdfobj(trailerdict); return NULL; }
400   return trailerdict;
401 }
402
403 // parse the page tree
404
405 int pdf_getpageinfo(GString *pdfbuf, struct XrefTable *xref, 
406                 struct PdfObj *pgtree, int nmax, struct PdfPageDesc *pages)
407 {
408   struct PdfObj *obj, *kid;
409   int i, count, j;
410   
411   obj = get_pdfobj(pdfbuf, xref, get_dict_entry(pgtree, "/Type"));
412   if (obj == NULL || obj->type != PDFTYPE_NAME)
413     return 0;
414   if (!strcmp(obj->str, "/Page")) {
415     free_pdfobj(obj);
416     pages->contents = dup_pdfobj(get_dict_entry(pgtree, "/Contents"));
417     obj = get_pdfobj(pdfbuf, xref, get_dict_entry(pgtree, "/Resources"));
418     if (obj!=NULL) {
419       free_pdfobj(pages->resources);
420       pages->resources = obj;
421     }
422     obj = get_pdfobj(pdfbuf, xref, get_dict_entry(pgtree, "/MediaBox"));
423     if (obj!=NULL) {
424       free_pdfobj(pages->mediabox);
425       pages->mediabox = obj;
426     }
427     obj = get_pdfobj(pdfbuf, xref, get_dict_entry(pgtree, "/Rotate"));
428     if (obj!=NULL && obj->type == PDFTYPE_INT)
429       pages->rotate = obj->intval;
430     free_pdfobj(obj);
431     return 1;
432   }
433   else if (!strcmp(obj->str, "/Pages")) {
434     free_pdfobj(obj);
435     obj = get_pdfobj(pdfbuf, xref, get_dict_entry(pgtree, "/Count"));
436     if (obj!=NULL && obj->type == PDFTYPE_INT && 
437         obj->intval>0 && obj->intval<=nmax) count = obj->intval;
438     else count = 0;
439     free_pdfobj(obj);
440     obj = get_pdfobj(pdfbuf, xref, get_dict_entry(pgtree, "/Resources"));
441     if (obj!=NULL)
442       for (i=0; i<count; i++) {
443         free_pdfobj(pages[i].resources);
444         pages[i].resources = dup_pdfobj(obj);
445       }
446     free_pdfobj(obj);
447     obj = get_pdfobj(pdfbuf, xref, get_dict_entry(pgtree, "/MediaBox"));
448     if (obj!=NULL)
449       for (i=0; i<count; i++) {
450         free_pdfobj(pages[i].mediabox);
451         pages[i].mediabox = dup_pdfobj(obj);
452       }
453     free_pdfobj(obj);
454     obj = get_pdfobj(pdfbuf, xref, get_dict_entry(pgtree, "/Rotate"));
455     if (obj!=NULL && obj->type == PDFTYPE_INT)
456       for (i=0; i<count; i++)
457         pages[i].rotate = obj->intval;
458     free_pdfobj(obj);
459     obj = get_pdfobj(pdfbuf, xref, get_dict_entry(pgtree, "/Kids"));
460     if (obj!=NULL && obj->type == PDFTYPE_ARRAY) {
461       for (i=0; i<obj->num; i++) {
462         kid = get_pdfobj(pdfbuf, xref, obj->elts[i]);
463         if (kid!=NULL) {
464           j = pdf_getpageinfo(pdfbuf, xref, kid, nmax, pages);
465           nmax -= j;
466           pages += j;
467           free_pdfobj(kid);
468         }
469       }
470     }
471     free_pdfobj(obj);
472     return count;
473   }
474   return 0;
475 }
476
477 // parse a PDF file in memory
478
479 gboolean pdf_parse_info(GString *pdfbuf, struct PdfInfo *pdfinfo, struct XrefTable *xref)
480 {
481   char *p;
482   int offs;
483   struct PdfObj *obj, *pages;
484
485   xref->n_alloc = xref->last = 0;
486   xref->data = NULL;
487   p = pdfbuf->str + pdfbuf->len-1;
488   
489   while (*p!='s' && p!=pdfbuf->str) p--;
490   if (strncmp(p, "startxref", 9)) return FALSE; // fail
491   p+=9;
492   while (ispdfspace(*p) && p!=pdfbuf->str+pdfbuf->len) p++;
493   offs = strtol(p, NULL, 10);
494   if (offs <= 0 || offs > pdfbuf->len) return FALSE; // fail
495   pdfinfo->startxref = offs;
496   
497   pdfinfo->trailerdict = parse_xref_table(pdfbuf, xref, offs);
498   if (pdfinfo->trailerdict == NULL) return FALSE; // fail
499   
500   obj = get_pdfobj(pdfbuf, xref,
501      get_dict_entry(pdfinfo->trailerdict, "/Root"));
502   if (obj == NULL)
503     { free_pdfobj(pdfinfo->trailerdict); return FALSE; }
504   pages = get_pdfobj(pdfbuf, xref, get_dict_entry(obj, "/Pages"));
505   free_pdfobj(obj);
506   if (pages == NULL)
507     { free_pdfobj(pdfinfo->trailerdict); return FALSE; }
508   obj = get_pdfobj(pdfbuf, xref, get_dict_entry(pages, "/Count"));
509   if (obj == NULL || obj->type != PDFTYPE_INT || obj->intval<=0) 
510     { free_pdfobj(pdfinfo->trailerdict); free_pdfobj(pages); 
511       free_pdfobj(obj); return FALSE; }
512   pdfinfo->npages = obj->intval;
513   free_pdfobj(obj);
514   
515   pdfinfo->pages = g_malloc0(pdfinfo->npages*sizeof(struct PdfPageDesc));
516   pdf_getpageinfo(pdfbuf, xref, pages, pdfinfo->npages, pdfinfo->pages);
517   free_pdfobj(pages);
518   
519   return TRUE;
520 }
521
522 // add an entry to the xref table
523
524 void make_xref(struct XrefTable *xref, int nobj, int offset)
525 {
526   if (xref->n_alloc <= nobj) {
527     xref->n_alloc = nobj + 10;
528     xref->data = g_realloc(xref->data, xref->n_alloc*sizeof(int));
529   }
530   if (xref->last < nobj) xref->last = nobj;
531   xref->data[nobj] = offset;
532 }
533
534 // a wrapper for deflate
535
536 GString *do_deflate(char *in, int len)
537 {
538   GString *out;
539   z_stream zs;
540   
541   zs.zalloc = Z_NULL;
542   zs.zfree = Z_NULL;
543   deflateInit(&zs, Z_DEFAULT_COMPRESSION);
544   zs.next_in = (Bytef *)in;
545   zs.avail_in = len;
546   zs.avail_out = deflateBound(&zs, len);
547   out = g_string_sized_new(zs.avail_out);
548   zs.next_out = (Bytef *)out->str;
549   deflate(&zs, Z_FINISH);
550   out->len = zs.total_out;
551   deflateEnd(&zs);
552   return out;
553 }
554
555 // prefix to scale the original page
556
557 GString *make_pdfprefix(struct PdfPageDesc *pgdesc, double width, double height)
558 {
559   GString *str;
560   double v[4], t, xscl, yscl;
561   int i;
562
563   // push 3 times in case code to be annotated has unbalanced q/Q (B of A., ...)
564   str = g_string_new("q q q "); 
565   if (pgdesc->rotate == 90) {
566     g_string_append_printf(str, "0 -1 1 0 0 %.2f cm ", height);
567     t = height; height = width; width = t;
568   }
569   if (pgdesc->rotate == 270) {
570     g_string_append_printf(str, "0 1 -1 0 %.2f 0 cm ", width);
571     t = height; height = width; width = t;
572   }
573   if (pgdesc->rotate == 180) {
574     g_string_append_printf(str, "-1 0 0 -1 %.2f %.2f cm ", width, height);
575   }
576   if (pgdesc->mediabox==NULL || pgdesc->mediabox->type != PDFTYPE_ARRAY ||
577       pgdesc->mediabox->num != 4) return str;
578   for (i=0; i<4; i++) {
579     if (pgdesc->mediabox->elts[i]->type == PDFTYPE_INT)
580       v[i] = pgdesc->mediabox->elts[i]->intval;
581     else if (pgdesc->mediabox->elts[i]->type == PDFTYPE_REAL)
582       v[i] = pgdesc->mediabox->elts[i]->realval;
583     else return str;
584   }
585   if (v[0]>v[2]) { t = v[0]; v[0] = v[2]; v[2] = t; }
586   if (v[1]>v[3]) { t = v[1]; v[1] = v[3]; v[3] = t; }
587   if (v[2]-v[0] < 1. || v[3]-v[1] < 1.) return str;
588   xscl = width/(v[2]-v[0]);
589   yscl = height/(v[3]-v[1]);
590   g_string_append_printf(str, "%.4f 0 0 %.4f %.2f %.2f cm ",
591     xscl, yscl, -v[0]*xscl, -v[1]*yscl);
592   return str;
593 }
594
595 // add an entry to a subentry of a directory
596
597 struct PdfObj *mk_pdfname(char *name)
598 {
599   struct PdfObj *obj;
600   
601   obj = g_malloc(sizeof(struct PdfObj));
602   obj->type = PDFTYPE_NAME;
603   obj->str = g_strdup(name);
604   return obj;
605 }
606
607 struct PdfObj *mk_pdfref(int num)
608 {
609   struct PdfObj *obj;
610   
611   obj = g_malloc(sizeof(struct PdfObj));
612   obj->type = PDFTYPE_REF;
613   obj->intval = num;
614   obj->num = 0;
615   return obj;
616 }
617
618 gboolean iseq_obj(struct PdfObj *a, struct PdfObj *b)
619 {
620   if (a==NULL || b==NULL) return (a==b);
621   if (a->type!=b->type) return FALSE;
622   if (a->type == PDFTYPE_CST || a->type == PDFTYPE_INT)
623     return (a->intval == b->intval);
624   if (a->type == PDFTYPE_REAL)
625     return (a->realval == b->realval);
626   if (a->type == PDFTYPE_NAME)
627     return !strcmp(a->str, b->str);
628   if (a->type == PDFTYPE_REF)
629     return (a->intval == b->intval && a->num == b->num);
630   return FALSE;
631 }
632
633 void add_dict_subentry(GString *pdfbuf, struct XrefTable *xref,
634    struct PdfObj *obj, char *section, int type, char *name, struct PdfObj *entry)
635 {
636   struct PdfObj *sec;
637   int i, subpos;
638   
639   subpos = -1;
640   for (i=0; i<obj->num; i++) 
641     if (!strcmp(obj->names[i], section)) subpos = i;
642   if (subpos == -1) {
643     subpos = obj->num;
644     obj->num++;
645     obj->elts = g_realloc(obj->elts, obj->num*sizeof(struct PdfObj*));
646     obj->names = g_realloc(obj->names, obj->num*sizeof(char *));
647     obj->names[subpos] = g_strdup(section);
648     obj->elts[subpos] = NULL;
649   }
650   if (obj->elts[subpos]!=NULL && obj->elts[subpos]->type==PDFTYPE_REF) {
651     sec = get_pdfobj(pdfbuf, xref, obj->elts[subpos]);
652     free_pdfobj(obj->elts[subpos]);
653     obj->elts[subpos] = sec;
654   }
655   if (obj->elts[subpos]!=NULL && obj->elts[subpos]->type!=type)
656     { free_pdfobj(obj->elts[subpos]); obj->elts[subpos] = NULL; }
657   if (obj->elts[subpos] == NULL) {
658     obj->elts[subpos] = sec = g_malloc(sizeof(struct PdfObj));
659     sec->type = type;
660     sec->num = 0;
661     sec->elts = NULL;
662     sec->names = NULL;
663   }
664   sec = obj->elts[subpos];
665
666   subpos = -1;
667   if (type==PDFTYPE_DICT) {
668     for (i=0; i<sec->num; i++) 
669       if (!strcmp(sec->names[i], name)) subpos = i;
670     if (subpos == -1) {
671       subpos = sec->num;
672       sec->num++;
673       sec->elts = g_realloc(sec->elts, sec->num*sizeof(struct PdfObj*));
674       sec->names = g_realloc(sec->names, sec->num*sizeof(char *));
675       sec->names[subpos] = g_strdup(name);
676       sec->elts[subpos] = NULL;
677     }
678     free_pdfobj(sec->elts[subpos]);
679     sec->elts[subpos] = entry;
680   } 
681   if (type==PDFTYPE_ARRAY) {
682     for (i=0; i<sec->num; i++)
683       if (iseq_obj(sec->elts[i], entry)) subpos = i;
684     if (subpos == -1) {
685       subpos = sec->num;
686       sec->num++;
687       sec->elts = g_realloc(sec->elts, sec->num*sizeof(struct PdfObj*));
688       sec->elts[subpos] = entry;
689     }
690     else free_pdfobj(entry);
691   }
692 }
693
694 // draw a page's background
695
696 void pdf_draw_solid_background(struct Page *pg, GString *str)
697 {
698   double x, y;
699
700   g_string_append_printf(str, 
701     "%.2f %.2f %.2f rg 0 0 %.2f %.2f re f ",
702     RGBA_RGB(pg->bg->color_rgba), pg->width, pg->height);
703   if (!ui.print_ruling) return;
704   if (pg->bg->ruling == RULING_NONE) return;
705   g_string_append_printf(str,
706     "%.2f %.2f %.2f RG %.2f w ",
707     RGBA_RGB(RULING_COLOR), RULING_THICKNESS);
708   if (pg->bg->ruling == RULING_GRAPH) {
709     for (x=RULING_GRAPHSPACING; x<pg->width-1; x+=RULING_GRAPHSPACING)
710       g_string_append_printf(str, "%.2f 0 m %.2f %.2f l S ",
711         x, x, pg->height);
712     for (y=RULING_GRAPHSPACING; y<pg->height-1; y+=RULING_GRAPHSPACING)
713       g_string_append_printf(str, "0 %.2f m %.2f %.2f l S ",
714         y, pg->width, y);
715     return;
716   }
717   for (y=RULING_TOPMARGIN; y<pg->height-1; y+=RULING_SPACING)
718     g_string_append_printf(str, "0 %.2f m %.2f %.2f l S ",
719       y, pg->width, y);
720   if (pg->bg->ruling == RULING_LINED)
721     g_string_append_printf(str, 
722       "%.2f %.2f %.2f RG %.2f 0 m %.2f %.2f l S ",
723       RGBA_RGB(RULING_MARGIN_COLOR), 
724       RULING_LEFTMARGIN, RULING_LEFTMARGIN, pg->height);
725 }
726
727 int pdf_draw_bitmap_background(struct Page *pg, GString *str, 
728                                 struct XrefTable *xref, GString *pdfbuf)
729 {
730   BgPdfPage *pgpdf;
731   GdkPixbuf *pix;
732   GString *zpix;
733   PopplerPage *pdfpage;
734   char *buf, *p1, *p2;
735   int height, width, stride, x, y, chan;
736   double pgheight, pgwidth;
737   
738   if (pg->bg->type == BG_PDF) {
739     if (!bgpdf.document) return -1;
740     pdfpage = poppler_document_get_page(bgpdf.document, pg->bg->file_page_seq-1);
741     if (!pdfpage) return -1;
742     poppler_page_get_size(pdfpage, &pgwidth, &pgheight);
743     width = (int) (PDFTOPPM_PRINTING_DPI * pgwidth/72.0);
744     height = (int) (PDFTOPPM_PRINTING_DPI * pgheight/72.0);
745     pix = gdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE, 8, width, height);
746     wrapper_poppler_page_render_to_pixbuf(
747        pdfpage, 0, 0, width, height, PDFTOPPM_PRINTING_DPI/72.0, 0, pix);
748     g_object_unref(pdfpage);
749   }
750   else pix = g_object_ref(pg->bg->pixbuf);
751   
752   if (gdk_pixbuf_get_bits_per_sample(pix) != 8 ||
753       gdk_pixbuf_get_colorspace(pix) != GDK_COLORSPACE_RGB)
754     { g_object_unref(pix); return -1; }
755                     
756   width = gdk_pixbuf_get_width(pix);
757   height = gdk_pixbuf_get_height(pix);
758   stride = gdk_pixbuf_get_rowstride(pix);
759   chan = gdk_pixbuf_get_n_channels(pix);
760   if (chan!=3 && chan!=4) { g_object_unref(pix); return -1; }
761
762   g_string_append_printf(str, "q %.2f 0 0 %.2f 0 %.2f cm /ImBg Do Q ",
763     pg->width, -pg->height, pg->height);
764   
765   p2 = buf = (char *)g_malloc(3*width*height);
766   for (y=0; y<height; y++) {
767     p1 = (char *)gdk_pixbuf_get_pixels(pix)+stride*y;
768     for (x=0; x<width; x++) {
769       *(p2++)=*(p1++); *(p2++)=*(p1++); *(p2++)=*(p1++);
770       if (chan==4) p1++;
771     }
772   }
773   zpix = do_deflate(buf, 3*width*height);
774   g_free(buf);
775   g_object_unref(pix);
776
777   make_xref(xref, xref->last+1, pdfbuf->len);
778   g_string_append_printf(pdfbuf, 
779     "%d 0 obj\n<< /Length %zu /Filter /FlateDecode /Type /Xobject "
780     "/Subtype /Image /Width %d /Height %d /ColorSpace /DeviceRGB "
781     "/BitsPerComponent 8 >> stream\n",
782     xref->last, zpix->len, width, height);
783   g_string_append_len(pdfbuf, zpix->str, zpix->len);
784   g_string_free(zpix, TRUE);
785   g_string_append(pdfbuf, "endstream\nendobj\n");
786  
787   return xref->last;
788 }
789
790 // manipulate Pdf fonts
791
792 struct PdfFont *new_pdffont(struct XrefTable *xref, GList **fonts,
793    char *filename, int font_id, FT_Face face, int glyph_page)
794 {
795   GList *list;
796   struct PdfFont *font;
797   int i;
798   const char *s;
799   
800   for (list = *fonts; list!=NULL; list = list->next) {
801     font = (struct PdfFont *)list->data;
802     if (!strcmp(font->filename, filename) && font->font_id == font_id 
803         && font->glyph_page == glyph_page)
804           { font->used_in_this_page = TRUE; return font; }
805   }
806   font = g_malloc(sizeof(struct PdfFont));
807   *fonts = g_list_append(*fonts, font);
808   font->n_obj = xref->last+1;
809   make_xref(xref, xref->last+1, 0); // will give it a value later
810   font->filename = g_strdup(filename);
811   font->font_id = font_id;
812   font->glyph_page = glyph_page;
813   font->used_in_this_page = TRUE;
814   font->num_glyphs_used = 0;
815   for (i=0; i<256; i++) {
816     font->glyphmap[i] = -1;
817     font->advance[i] = 0;
818     font->glyphpsnames[i] = NULL;
819   }
820   font->glyphmap[0] = 0;
821   // fill in info from the FT_Face
822   font->is_truetype = FT_IS_SFNT(face);
823   font->nglyphs = face->num_glyphs;
824   font->ft2ps = 1000.0 / face->units_per_EM;
825   font->ascender = (int)(font->ft2ps*face->ascender);
826   font->descender = (int)(font->ft2ps*face->descender);
827   if (face->bbox.xMin < -100000 || face->bbox.xMin > 100000) font->xmin = 0;
828   else font->xmin = (int)(font->ft2ps*face->bbox.xMin);
829   if (face->bbox.xMax < -100000 || face->bbox.xMax > 100000) font->xmax = 0;
830   else font->xmax = (int)(font->ft2ps*face->bbox.xMax);
831   if (face->bbox.yMin < -100000 || face->bbox.yMin > 100000) font->ymin = 0;
832   else font->ymin = (int)(font->ft2ps*face->bbox.yMin);
833   if (face->bbox.yMax < -100000 || face->bbox.yMax > 100000) font->ymax = 0;
834   else font->ymax = (int)(font->ft2ps*face->bbox.yMax);
835   if (font->is_truetype) font->flags = 4; // symbolic
836   else {
837     font->flags = 4; // symbolic
838     if (FT_IS_FIXED_WIDTH(face)) font->flags |= 1;
839     if (face->style_flags & FT_STYLE_FLAG_ITALIC) font->flags |= 64;
840   }
841   s = FT_Get_Postscript_Name(face);
842   if (s==NULL) s = "Noname";
843   if (glyph_page) font->fontname = g_strdup_printf("%s_%03d", s, glyph_page);
844   else font->fontname = g_strdup(s);
845   return font;
846 }
847
848 #define pfb_get_length(x) (((x)[3]<<24) + ((x)[2]<<16) + ((x)[1]<<8) + (x)[0])
849 #define T1_SEGMENT_1_END "currentfile eexec"
850 #define T1_SEGMENT_3_END "cleartomark"
851
852 void embed_pdffont(GString *pdfbuf, struct XrefTable *xref, struct PdfFont *font)
853 {
854   // this code inspired by libgnomeprint
855   gboolean fallback, is_binary;
856   guchar encoding[256];
857   gushort glyphs[256];
858   int i, j, num;
859   guint32 len1, len2;
860   guint32 tt_len;
861   gsize t1_len;
862   TrueTypeFont *ttfnt;
863   char *seg1, *seg2;
864   char *fontdata, *p;
865   char prefix[8];
866   int nobj_fontprog, nobj_descr, lastchar;
867   
868   fallback = FALSE;
869   // embed the font file: TrueType case
870   if (font->is_truetype) {
871     glyphs[0] = encoding[0] = 0;
872     num = 1;
873     for (i=1; i<=255; i++) 
874       if (font->glyphmap[i]>=0) {
875         font->glyphmap[i] = num;
876         glyphs[num] = 255*font->glyph_page+i-1;
877         encoding[num] = i;
878         num++;
879       }
880     font->num_glyphs_used = num-1;
881     if (OpenTTFont(font->filename, 0, &ttfnt) == SF_OK) {
882       if (CreateTTFromTTGlyphs_tomemory(ttfnt, (guint8**)&fontdata, &tt_len, glyphs, encoding, num, 
883                    0, NULL, TTCF_AutoName | TTCF_IncludeOS2) == SF_OK) {
884         make_xref(xref, xref->last+1, pdfbuf->len);
885         nobj_fontprog = xref->last;
886         g_string_append_printf(pdfbuf, 
887           "%d 0 obj\n<< /Length %u /Length1 %u >> stream\n",
888           nobj_fontprog, tt_len, tt_len);
889         g_string_append_len(pdfbuf, fontdata, tt_len);
890         g_string_append(pdfbuf, "endstream\nendobj\n");
891         g_free(fontdata);
892       }
893       else fallback = TRUE;
894       CloseTTFont(ttfnt);
895     } 
896     else fallback = TRUE;
897   } else {
898   // embed the font file: Type1 case
899     if (g_file_get_contents(font->filename, &fontdata, &t1_len, NULL) && t1_len>=8) {
900       if (fontdata[0]==(char)0x80 && fontdata[1]==(char)0x01) {
901         is_binary = TRUE;
902         len1 = pfb_get_length((unsigned char *)fontdata+2);
903         if (fontdata[len1+6]!=(char)0x80 || fontdata[len1+7]!=(char)0x02) fallback = TRUE;
904         else {
905           len2 = pfb_get_length((unsigned char *)fontdata+len1+8);
906           if (fontdata[len1+len2+12]!=(char)0x80 || fontdata[len1+len2+13]!=(char)0x01)
907             fallback = TRUE;
908         }
909       }
910       else if (!strncmp(fontdata, "%!PS", 4)) {
911         is_binary = FALSE;
912         p = strstr(fontdata, T1_SEGMENT_1_END) + strlen(T1_SEGMENT_1_END);
913         if (p==NULL) fallback = TRUE;
914         else {
915           if (*p=='\n' || *p=='\r') p++;
916           if (*p=='\n' || *p=='\r') p++;
917           len1 = p-fontdata;
918           p = g_strrstr_len(fontdata, t1_len, T1_SEGMENT_3_END);
919           if (p==NULL) fallback = TRUE;
920           else {
921             // rewind 512 zeros
922             i = 512; p--;
923             while (i>0 && p!=fontdata && (*p=='0' || *p=='\r' || *p=='\n')) {
924               if (*p=='0') i--;
925               p--;
926             }
927             while (p!=fontdata && (*p=='\r' || *p=='\n')) p--;
928             p++;
929             if (i>0) fallback = TRUE;
930             else len2 = p-fontdata-len1;
931           }
932         }
933       }
934       else fallback = TRUE;
935       if (!fallback) {
936         if (is_binary) {
937           seg1 = fontdata+6;
938           seg2 = fontdata + len1 + 12;
939         } else {
940           seg1 = fontdata;
941           seg2 = g_malloc(len2/2);
942           j=0;
943           p = fontdata+len1;
944           while (p+1 < fontdata+len1+len2) {
945             if (*p==' '||*p=='\t'||*p=='\n'||*p=='\r') { p++; continue; }
946             if (p[0]>'9') { p[0]|=0x20; p[0]-=39; }
947             if (p[1]>'9') { p[1]|=0x20; p[1]-=39; }
948             seg2[j++] = ((p[0]-'0')<<4) + (p[1]-'0');
949             p+=2;
950           }
951           len2 = j;
952         }
953         make_xref(xref, xref->last+1, pdfbuf->len);
954         nobj_fontprog = xref->last;
955         g_string_append_printf(pdfbuf, 
956           "%d 0 obj\n<< /Length %u /Length1 %u /Length2 %u /Length3 0 >> stream\n",
957           nobj_fontprog, len1+len2, len1, len2);
958         g_string_append_len(pdfbuf, seg1, len1);
959         g_string_append_len(pdfbuf, seg2, len2);
960         g_string_append(pdfbuf, "endstream\nendobj\n");
961         if (!is_binary) g_free(seg2);
962       }
963       g_free(fontdata);
964     }
965     else fallback = TRUE;
966   }
967   
968   // next, the font descriptor
969   if (!fallback) {
970     make_xref(xref, xref->last+1, pdfbuf->len);
971     nobj_descr = xref->last;
972     g_string_append_printf(pdfbuf,
973       "%d 0 obj\n<< /Type /FontDescriptor /FontName /%s /Flags %d "
974       "/FontBBox [%d %d %d %d] /ItalicAngle 0 /Ascent %d "
975       "/Descent %d /CapHeight %d /StemV 100 /%s %d 0 R >> endobj\n",
976       nobj_descr, font->fontname, font->flags, 
977       font->xmin, font->ymin, font->xmax, font->ymax, 
978       font->ascender, -font->descender, font->ascender, 
979       font->is_truetype ? "FontFile2":"FontFile",
980       nobj_fontprog);
981   }
982   
983   // finally, the font itself
984   /* Note: in Type1 case, font->glyphmap maps charcodes to glyph no's
985      in TrueType case, encoding lists the used charcodes by index,
986                        glyphs   list the used glyph no's by index
987                        font->glyphmap maps charcodes to indices        */
988   xref->data[font->n_obj] = pdfbuf->len;
989   if (font->is_truetype) lastchar = encoding[font->num_glyphs_used];
990   else lastchar = font->num_glyphs_used;
991   if (fallback) {
992     font->is_truetype = FALSE;
993     g_free(font->fontname);
994     font->fontname = g_strdup("Helvetica");
995   }
996   prefix[0]=0;
997   if (font->is_truetype) {
998     num = font->glyph_page;
999     for (i=0; i<6; i++) { prefix[i] = 'A'+(num%26); num/=26; }
1000     prefix[6]='+'; prefix[7]=0;
1001   }
1002   g_string_append_printf(pdfbuf,
1003     "%d 0 obj\n<< /Type /Font /Subtype /%s /BaseFont /%s%s /Name /F%d ",
1004     font->n_obj, font->is_truetype?"TrueType":"Type1",
1005     prefix, font->fontname, font->n_obj);
1006   if (!fallback) {
1007     g_string_append_printf(pdfbuf,
1008       "/FontDescriptor %d 0 R /FirstChar 0 /LastChar %d /Widths [",
1009       nobj_descr, lastchar);
1010     for (i=0; i<=lastchar; i++)
1011       g_string_append_printf(pdfbuf, "%d ", font->advance[i]);
1012     g_string_append(pdfbuf, "] ");
1013   }
1014   if (!font->is_truetype) { /* encoding */
1015     g_string_append(pdfbuf, "/Encoding << /Type /Encoding "
1016       "/BaseEncoding /MacRomanEncoding /Differences [1 ");
1017     for (i=1; i<=lastchar; i++) {
1018       g_string_append_printf(pdfbuf, "/%s ", font->glyphpsnames[i]);
1019       g_free(font->glyphpsnames[i]);
1020     }
1021     g_string_append(pdfbuf, "] >> ");
1022   }
1023   g_string_append(pdfbuf, ">> endobj\n");
1024 }
1025
1026 // draw a page's graphics
1027
1028 void pdf_draw_page(struct Page *pg, GString *str, gboolean *use_hiliter, 
1029                   struct XrefTable *xref, GList **pdffonts)
1030 {
1031   GList *layerlist, *itemlist, *tmplist;
1032   struct Layer *l;
1033   struct Item *item;
1034   guint old_rgba, old_text_rgba;
1035   double old_thickness;
1036   double *pt;
1037   int i, j;
1038   PangoFontDescription *font_desc;
1039   PangoContext *context;
1040   PangoLayout *layout;
1041   PangoLayoutIter *iter;
1042   PangoRectangle logical_rect;
1043   PangoLayoutRun *run;
1044   PangoFcFont *fcfont;
1045   PangoFontMap *fontmap;
1046   FcPattern *pattern;
1047   int baseline, advance;
1048   int glyph_no, glyph_page, current_page;
1049   char *filename;
1050   char tmpstr[200];
1051   int font_id;
1052   FT_Face ftface;
1053   struct PdfFont *cur_font;
1054   gboolean in_string;
1055   
1056   old_rgba = old_text_rgba = 0x12345678;    // not any values we use, so we'll reset them
1057   old_thickness = 0.0;
1058   for (tmplist = *pdffonts; tmplist!=NULL; tmplist = tmplist->next) {
1059     cur_font = (struct PdfFont *)tmplist->data;
1060     cur_font->used_in_this_page = FALSE;
1061   }
1062
1063   for (layerlist = pg->layers; layerlist!=NULL; layerlist = layerlist->next) {
1064     l = (struct Layer *)layerlist->data;
1065     for (itemlist = l->items; itemlist!=NULL; itemlist = itemlist->next) {
1066       item = (struct Item *)itemlist->data;
1067       if (item->type == ITEM_STROKE) {
1068         if ((item->brush.color_rgba & ~0xff) != old_rgba)
1069           g_string_append_printf(str, "%.2f %.2f %.2f RG ",
1070             RGBA_RGB(item->brush.color_rgba));
1071         if (item->brush.thickness != old_thickness)
1072           g_string_append_printf(str, "%.2f w ", item->brush.thickness);
1073         if ((item->brush.color_rgba & 0xf0) != 0xf0) { // transparent
1074           g_string_append(str, "q /XoHi gs ");
1075           *use_hiliter = TRUE;
1076         }
1077         old_rgba = item->brush.color_rgba & ~0xff;
1078         old_thickness = item->brush.thickness;
1079         pt = item->path->coords;
1080         if (!item->brush.variable_width) {
1081           g_string_append_printf(str, "%.2f %.2f m ", pt[0], pt[1]);
1082           for (i=1, pt+=2; i<item->path->num_points; i++, pt+=2)
1083             g_string_append_printf(str, "%.2f %.2f l ", pt[0], pt[1]);
1084           g_string_append_printf(str,"S\n");
1085           old_thickness = item->brush.thickness;
1086         } else {
1087           for (i=0; i<item->path->num_points-1; i++, pt+=2)
1088             g_string_append_printf(str, "%.2f w %.2f %.2f m %.2f %.2f l S\n", 
1089                item->widths[i], pt[0], pt[1], pt[2], pt[3]);
1090           old_thickness = 0.0;
1091         }
1092         if ((item->brush.color_rgba & 0xf0) != 0xf0) // undo transparent
1093           g_string_append(str, "Q ");
1094       }
1095       else if (item->type == ITEM_TEXT) {
1096         if ((item->brush.color_rgba & ~0xff) != old_text_rgba)
1097           g_string_append_printf(str, "%.2f %.2f %.2f rg ",
1098             RGBA_RGB(item->brush.color_rgba));
1099         old_text_rgba = item->brush.color_rgba & ~0xff;
1100         fontmap = pango_ft2_font_map_new();
1101         pango_ft2_font_map_set_resolution(PANGO_FT2_FONT_MAP (fontmap), 72, 72);
1102         context = pango_context_new();
1103         pango_context_set_font_map(context, fontmap);
1104         layout = pango_layout_new(context);
1105         g_object_unref(fontmap);
1106         g_object_unref(context);
1107         font_desc = pango_font_description_from_string(item->font_name);
1108         pango_font_description_set_absolute_size(font_desc,
1109           item->font_size*PANGO_SCALE);
1110         pango_layout_set_font_description(layout, font_desc);
1111         pango_font_description_free(font_desc);
1112         pango_layout_set_text(layout, item->text, -1);
1113         // this code inspired by the code in libgnomeprint
1114         iter = pango_layout_get_iter(layout);
1115         do {
1116           run = pango_layout_iter_get_run(iter);
1117           if (run==NULL) continue;
1118           pango_layout_iter_get_run_extents (iter, NULL, &logical_rect);
1119           baseline = pango_layout_iter_get_baseline (iter);
1120           if (!PANGO_IS_FC_FONT(run->item->analysis.font)) continue;
1121           fcfont = PANGO_FC_FONT(run->item->analysis.font);
1122           pattern = fcfont->font_pattern;
1123           if (FcPatternGetString(pattern, FC_FILE, 0, (unsigned char **)&filename) != FcResultMatch ||
1124               FcPatternGetInteger(pattern, FC_INDEX, 0, &font_id) != FcResultMatch)
1125                 continue;
1126           ftface = pango_fc_font_lock_face(fcfont);
1127           current_page = -1;
1128           cur_font = NULL;
1129           g_string_append_printf(str, "BT %.2f 0 0 %.2f %.2f %.2f Tm ",
1130             item->font_size, -item->font_size,
1131             item->bbox.left + (gdouble) logical_rect.x/PANGO_SCALE,
1132             item->bbox.top + (gdouble) baseline/PANGO_SCALE);
1133           in_string = FALSE;
1134           for (i=0; i<run->glyphs->num_glyphs; i++) {
1135             glyph_no = run->glyphs->glyphs[i].glyph;
1136             if (FT_IS_SFNT(ftface)) glyph_page = glyph_no/255;
1137             else glyph_page = 0;
1138             if (glyph_page != current_page) {
1139               cur_font = new_pdffont(xref, pdffonts, filename, font_id,
1140                  ftface, glyph_page);
1141               if (in_string) g_string_append(str, ") Tj ");
1142               in_string = FALSE;
1143               g_string_append_printf(str, "/F%d 1 Tf ", cur_font->n_obj);
1144             }
1145             current_page = glyph_page;
1146             FT_Load_Glyph(ftface, glyph_no, FT_LOAD_NO_SCALE | FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM);
1147             advance = (int)(ftface->glyph->metrics.horiAdvance * cur_font->ft2ps + 0.5);
1148             if (!in_string) g_string_append_c(str, '(');
1149             in_string = TRUE;
1150             if (cur_font->is_truetype) {
1151               if (glyph_no) glyph_no = (glyph_no%255)+1;
1152               cur_font->glyphmap[glyph_no] = glyph_no;
1153             }
1154             else {
1155               for (j=1; j<=cur_font->num_glyphs_used; j++)
1156                 if (cur_font->glyphmap[j] == glyph_no) break;
1157               if (j==256) j=0; // font is full, what do we do?
1158               if (j>cur_font->num_glyphs_used) {
1159                 cur_font->glyphmap[j] = glyph_no; 
1160                 cur_font->num_glyphs_used++;
1161                 if (FT_Get_Glyph_Name(ftface, glyph_no, tmpstr, 200) == FT_Err_Ok)
1162                   cur_font->glyphpsnames[j] = g_strdup(tmpstr);
1163                 else cur_font->glyphpsnames[j] = g_strdup(".notdef");
1164               }
1165               glyph_no = j;
1166             }
1167             cur_font->advance[glyph_no] = advance;
1168             if (glyph_no=='\\' || glyph_no == '(' || glyph_no == ')' || glyph_no == 10 || glyph_no == 13) 
1169               g_string_append_c(str, '\\');
1170             if (glyph_no==10) g_string_append_c(str,'n');
1171             else if (glyph_no==13) g_string_append_c(str,'r');
1172             else g_string_append_c(str, glyph_no);
1173           }
1174           if (in_string) g_string_append(str, ") Tj ");
1175           g_string_append(str, "ET ");
1176           pango_fc_font_unlock_face(fcfont);
1177         } while (pango_layout_iter_next_run(iter));
1178         pango_layout_iter_free(iter);
1179         g_object_unref(layout);
1180       }
1181     }
1182   }
1183 }
1184
1185 // main printing function
1186
1187 /* we use the following object numbers, starting with n_obj_catalog:
1188     0 the document catalog
1189     1 the page tree
1190     2 the GS for the hiliters
1191     3 ... the page objects
1192 */
1193
1194 gboolean print_to_pdf(char *filename)
1195 {
1196   FILE *f;
1197   GString *pdfbuf, *pgstrm, *zpgstrm, *tmpstr;
1198   int n_obj_catalog, n_obj_pages_offs, n_page, n_obj_bgpix, n_obj_prefix;
1199   int i, startxref;
1200   struct XrefTable xref;
1201   GList *pglist;
1202   struct Page *pg;
1203   gboolean annot, uses_pdf;
1204   gboolean use_hiliter;
1205   struct PdfInfo pdfinfo;
1206   struct PdfObj *obj;
1207   GList *pdffonts, *list;
1208   struct PdfFont *font;
1209   char *tmpbuf;
1210   
1211   f = fopen(filename, "wb");
1212   if (f == NULL) return FALSE;
1213   setlocale(LC_NUMERIC, "C");
1214   annot = FALSE;
1215   xref.data = NULL;
1216   uses_pdf = FALSE;
1217   pdffonts = NULL;
1218   for (pglist = journal.pages; pglist!=NULL; pglist = pglist->next) {
1219     pg = (struct Page *)pglist->data;
1220     if (pg->bg->type == BG_PDF) uses_pdf = TRUE;
1221   }
1222   
1223   if (uses_pdf && bgpdf.status != STATUS_NOT_INIT && 
1224       bgpdf.file_contents!=NULL && !strncmp(bgpdf.file_contents, "%PDF-1.", 7)) {
1225     // parse the existing PDF file
1226     pdfbuf = g_string_new_len(bgpdf.file_contents, bgpdf.file_length);
1227     if (pdfbuf->str[7]<'4') pdfbuf->str[7] = '4'; // upgrade to 1.4
1228     annot = pdf_parse_info(pdfbuf, &pdfinfo, &xref);
1229     if (!annot) {
1230       g_string_free(pdfbuf, TRUE);
1231       if (xref.data != NULL) g_free(xref.data);
1232     }
1233   }
1234
1235   if (!annot) {
1236     pdfbuf = g_string_new("%PDF-1.4\n%\370\357\365\362\n");
1237     xref.n_alloc = xref.last = 0;
1238     xref.data = NULL;
1239   }
1240     
1241   // catalog and page tree
1242   n_obj_catalog = xref.last+1;
1243   n_obj_pages_offs = xref.last+4;
1244   make_xref(&xref, n_obj_catalog, pdfbuf->len);
1245   g_string_append_printf(pdfbuf, 
1246     "%d 0 obj\n<< /Type /Catalog /Pages %d 0 R >> endobj\n",
1247      n_obj_catalog, n_obj_catalog+1);
1248   make_xref(&xref, n_obj_catalog+1, pdfbuf->len);
1249   g_string_append_printf(pdfbuf,
1250     "%d 0 obj\n<< /Type /Pages /Kids [", n_obj_catalog+1);
1251   for (i=0;i<journal.npages;i++)
1252     g_string_append_printf(pdfbuf, "%d 0 R ", n_obj_pages_offs+i);
1253   g_string_append_printf(pdfbuf, "] /Count %d >> endobj\n", journal.npages);
1254   make_xref(&xref, n_obj_catalog+2, pdfbuf->len);
1255   g_string_append_printf(pdfbuf, 
1256     "%d 0 obj\n<< /Type /ExtGState /CA %.2f >> endobj\n",
1257      n_obj_catalog+2, ui.hiliter_opacity);
1258   xref.last = n_obj_pages_offs + journal.npages-1;
1259   
1260   for (pglist = journal.pages, n_page = 0; pglist!=NULL;
1261        pglist = pglist->next, n_page++) {
1262     pg = (struct Page *)pglist->data;
1263     
1264     // draw the background and page into pgstrm
1265     pgstrm = g_string_new("");
1266     g_string_printf(pgstrm, "q 1 0 0 -1 0 %.2f cm 1 J 1 j ", pg->height);
1267     n_obj_bgpix = -1;
1268     n_obj_prefix = -1;
1269     if (pg->bg->type == BG_SOLID)
1270       pdf_draw_solid_background(pg, pgstrm);
1271     else if (pg->bg->type == BG_PDF && annot && 
1272              pdfinfo.pages[pg->bg->file_page_seq-1].contents!=NULL) {
1273       make_xref(&xref, xref.last+1, pdfbuf->len);
1274       n_obj_prefix = xref.last;
1275       tmpstr = make_pdfprefix(pdfinfo.pages+(pg->bg->file_page_seq-1),
1276                               pg->width, pg->height);
1277       g_string_append_printf(pdfbuf,
1278         "%d 0 obj\n<< /Length %zu >> stream\n%s\nendstream\nendobj\n",
1279         n_obj_prefix, tmpstr->len, tmpstr->str);
1280       g_string_free(tmpstr, TRUE);
1281       g_string_prepend(pgstrm, "Q Q Q ");
1282     }
1283     else if (pg->bg->type == BG_PIXMAP || pg->bg->type == BG_PDF)
1284       n_obj_bgpix = pdf_draw_bitmap_background(pg, pgstrm, &xref, pdfbuf);
1285     // draw the page contents
1286     use_hiliter = FALSE;
1287     pdf_draw_page(pg, pgstrm, &use_hiliter, &xref, &pdffonts);
1288     g_string_append_printf(pgstrm, "Q\n");
1289     
1290     // deflate pgstrm and write it
1291     zpgstrm = do_deflate(pgstrm->str, pgstrm->len);
1292     g_string_free(pgstrm, TRUE);
1293     
1294     make_xref(&xref, xref.last+1, pdfbuf->len);
1295     g_string_append_printf(pdfbuf, 
1296       "%d 0 obj\n<< /Length %zu /Filter /FlateDecode>> stream\n",
1297       xref.last, zpgstrm->len);
1298     g_string_append_len(pdfbuf, zpgstrm->str, zpgstrm->len);
1299     g_string_free(zpgstrm, TRUE);
1300     g_string_append(pdfbuf, "endstream\nendobj\n");
1301     
1302     // write the page object
1303     
1304     make_xref(&xref, n_obj_pages_offs+n_page, pdfbuf->len);
1305     g_string_append_printf(pdfbuf, 
1306       "%d 0 obj\n<< /Type /Page /Parent %d 0 R /MediaBox [0 0 %.2f %.2f] ",
1307       n_obj_pages_offs+n_page, n_obj_catalog+1, pg->width, pg->height);
1308     if (n_obj_prefix>0) {
1309       obj = get_pdfobj(pdfbuf, &xref, pdfinfo.pages[pg->bg->file_page_seq-1].contents);
1310       if (obj->type != PDFTYPE_ARRAY) {
1311         free_pdfobj(obj);
1312         obj = dup_pdfobj(pdfinfo.pages[pg->bg->file_page_seq-1].contents);
1313       }
1314       g_string_append_printf(pdfbuf, "/Contents [%d 0 R ", n_obj_prefix);
1315       if (obj->type == PDFTYPE_REF) 
1316         g_string_append_printf(pdfbuf, "%d %d R ", obj->intval, obj->num);
1317       if (obj->type == PDFTYPE_ARRAY) {
1318         for (i=0; i<obj->num; i++) {
1319           show_pdfobj(obj->elts[i], pdfbuf);
1320           g_string_append_c(pdfbuf, ' ');
1321         }
1322       }
1323       free_pdfobj(obj);
1324       g_string_append_printf(pdfbuf, "%d 0 R] ", xref.last);
1325     }
1326     else g_string_append_printf(pdfbuf, "/Contents %d 0 R ", xref.last);
1327     g_string_append(pdfbuf, "/Resources ");
1328
1329     if (n_obj_prefix>0)
1330       obj = dup_pdfobj(pdfinfo.pages[pg->bg->file_page_seq-1].resources);
1331     else obj = NULL;
1332     if (obj!=NULL && obj->type!=PDFTYPE_DICT)
1333       { free_pdfobj(obj); obj=NULL; }
1334     if (obj==NULL) {
1335       obj = g_malloc(sizeof(struct PdfObj));
1336       obj->type = PDFTYPE_DICT;
1337       obj->num = 0;
1338       obj->elts = NULL;
1339       obj->names = NULL;
1340     }
1341     add_dict_subentry(pdfbuf, &xref,
1342         obj, "/ProcSet", PDFTYPE_ARRAY, NULL, mk_pdfname("/PDF"));
1343     if (n_obj_bgpix>0)
1344       add_dict_subentry(pdfbuf, &xref,
1345         obj, "/ProcSet", PDFTYPE_ARRAY, NULL, mk_pdfname("/ImageC"));
1346     if (use_hiliter)
1347       add_dict_subentry(pdfbuf, &xref,
1348         obj, "/ExtGState", PDFTYPE_DICT, "/XoHi", mk_pdfref(n_obj_catalog+2));
1349     if (n_obj_bgpix>0)
1350       add_dict_subentry(pdfbuf, &xref,
1351         obj, "/XObject", PDFTYPE_DICT, "/ImBg", mk_pdfref(n_obj_bgpix));
1352     for (list=pdffonts; list!=NULL; list = list->next) {
1353       font = (struct PdfFont *)list->data;
1354       if (font->used_in_this_page) {
1355         add_dict_subentry(pdfbuf, &xref,
1356           obj, "/ProcSet", PDFTYPE_ARRAY, NULL, mk_pdfname("/Text"));
1357         tmpbuf = g_strdup_printf("/F%d", font->n_obj);
1358         add_dict_subentry(pdfbuf, &xref,
1359           obj, "/Font", PDFTYPE_DICT, tmpbuf, mk_pdfref(font->n_obj));
1360         g_free(tmpbuf);
1361       }
1362     }
1363     show_pdfobj(obj, pdfbuf);
1364     free_pdfobj(obj);
1365     g_string_append(pdfbuf, " >> endobj\n");
1366   }
1367   
1368   // after the pages, we insert fonts
1369   for (list = pdffonts; list!=NULL; list = list->next) {
1370     font = (struct PdfFont *)list->data;
1371     embed_pdffont(pdfbuf, &xref, font);
1372     g_free(font->filename);
1373     g_free(font->fontname);
1374     g_free(font);
1375   }
1376   g_list_free(pdffonts);
1377   
1378   // PDF trailer
1379   startxref = pdfbuf->len;
1380   if (annot) g_string_append_printf(pdfbuf,
1381         "xref\n%d %d\n", n_obj_catalog, xref.last-n_obj_catalog+1);
1382   else g_string_append_printf(pdfbuf, 
1383         "xref\n0 %d\n0000000000 65535 f \n", xref.last+1);
1384   for (i=n_obj_catalog; i<=xref.last; i++)
1385     g_string_append_printf(pdfbuf, "%010d 00000 n \n", xref.data[i]);
1386   g_string_append_printf(pdfbuf, 
1387     "trailer\n<< /Size %d /Root %d 0 R ", xref.last+1, n_obj_catalog);
1388   if (annot) {
1389     g_string_append_printf(pdfbuf, "/Prev %d ", pdfinfo.startxref);
1390     // keeping encryption info somehow doesn't work.
1391     // xournal can't annotate encrypted PDFs anyway...
1392 /*    
1393     obj = get_dict_entry(pdfinfo.trailerdict, "/Encrypt");
1394     if (obj!=NULL) {
1395       g_string_append_printf(pdfbuf, "/Encrypt ");
1396       show_pdfobj(obj, pdfbuf);
1397     } 
1398 */
1399   }
1400   g_string_append_printf(pdfbuf, 
1401     ">>\nstartxref\n%d\n%%%%EOF\n", startxref);
1402   
1403   g_free(xref.data);
1404   if (annot) {
1405     free_pdfobj(pdfinfo.trailerdict);
1406     if (pdfinfo.pages!=NULL)
1407       for (i=0; i<pdfinfo.npages; i++) {
1408         free_pdfobj(pdfinfo.pages[i].resources);
1409         free_pdfobj(pdfinfo.pages[i].mediabox);
1410         free_pdfobj(pdfinfo.pages[i].contents);
1411       }
1412   }
1413   
1414   setlocale(LC_NUMERIC, "");
1415   if (fwrite(pdfbuf->str, 1, pdfbuf->len, f) < pdfbuf->len) {
1416     fclose(f);
1417     g_string_free(pdfbuf, TRUE);
1418     return FALSE;
1419   }
1420   fclose(f);
1421   g_string_free(pdfbuf, TRUE);
1422   return TRUE;
1423 }
1424
1425 /*********** Printing via gtk-print **********/
1426
1427 #if GTK_CHECK_VERSION(2, 10, 0)
1428
1429 // does the same job as update_canvas_bg(), but to a print context
1430
1431 void print_background(cairo_t *cr, struct Page *pg)
1432 {
1433   double x, y;
1434   GdkPixbuf *pix;
1435   BgPdfPage *pgpdf;
1436   PopplerPage *pdfpage;
1437   cairo_surface_t *cr_pixbuf;
1438   double pgwidth, pgheight;
1439
1440   if (pg->bg->type == BG_SOLID) {
1441     cairo_set_source_rgb(cr, RGBA_RGB(pg->bg->color_rgba));
1442     cairo_rectangle(cr, 0, 0, pg->width, pg->height);
1443     cairo_fill(cr);
1444     if (!ui.print_ruling) return;
1445     if (pg->bg->ruling == RULING_NONE) return;
1446     cairo_set_source_rgb(cr, RGBA_RGB(RULING_COLOR));
1447     cairo_set_line_width(cr, RULING_THICKNESS);
1448
1449     if (pg->bg->ruling == RULING_GRAPH) {
1450       for (x=RULING_GRAPHSPACING; x<pg->width-1; x+=RULING_GRAPHSPACING)
1451         { cairo_move_to(cr, x, 0); cairo_line_to(cr, x, pg->height); }
1452       for (y=RULING_GRAPHSPACING; y<pg->height-1; y+=RULING_GRAPHSPACING)
1453         { cairo_move_to(cr, 0, y); cairo_line_to(cr, pg->width, y); }
1454       cairo_stroke(cr);
1455       return;
1456     }
1457     
1458     for (y=RULING_TOPMARGIN; y<pg->height-1; y+=RULING_SPACING)
1459       { cairo_move_to(cr, 0, y); cairo_line_to(cr, pg->width, y); }
1460     cairo_stroke(cr);
1461     if (pg->bg->ruling == RULING_LINED) {
1462       cairo_set_source_rgb(cr, RGBA_RGB(RULING_MARGIN_COLOR));
1463       cairo_move_to(cr, RULING_LEFTMARGIN, 0);
1464       cairo_line_to(cr, RULING_LEFTMARGIN, pg->height);
1465       cairo_stroke(cr);
1466     }
1467     return;
1468   }
1469   else
1470   if (pg->bg->type == BG_PDF) {
1471     if (!bgpdf.document) return;
1472     pdfpage = poppler_document_get_page(bgpdf.document, pg->bg->file_page_seq-1);
1473     if (!pdfpage) return;
1474     poppler_page_get_size(pdfpage, &pgwidth, &pgheight);
1475     cairo_save(cr);
1476     cairo_scale(cr, pg->width/pgwidth, pg->height/pgheight);
1477     poppler_page_render(pdfpage, cr);
1478     cairo_restore(cr);
1479     g_object_unref(pdfpage);
1480   }
1481   else 
1482   if (pg->bg->type == BG_PIXMAP) {
1483     cairo_save(cr);
1484     cairo_scale(cr, pg->width/gdk_pixbuf_get_width(pg->bg->pixbuf),
1485                     pg->height/gdk_pixbuf_get_height(pg->bg->pixbuf));
1486     gdk_cairo_set_source_pixbuf(cr, pg->bg->pixbuf, 0, 0);
1487     cairo_rectangle(cr, 0, 0, gdk_pixbuf_get_width(pg->bg->pixbuf), gdk_pixbuf_get_height(pg->bg->pixbuf));
1488     cairo_fill(cr);
1489     cairo_restore(cr);
1490   }
1491 }
1492
1493 void print_job_render_page(GtkPrintOperation *print, GtkPrintContext *context, gint pageno, gpointer user_data)
1494 {
1495   cairo_t *cr;
1496   gdouble width, height, scale;
1497   struct Page *pg;
1498   guint old_rgba;
1499   double old_thickness;
1500   GList *layerlist, *itemlist;
1501   struct Layer *l;
1502   struct Item *item;
1503   int i;
1504   double *pt;
1505   PangoFontDescription *font_desc;
1506   PangoLayout *layout;
1507         
1508   pg = (struct Page *)g_list_nth_data(journal.pages, pageno);
1509   cr = gtk_print_context_get_cairo_context(context);
1510   width = gtk_print_context_get_width(context);
1511   height = gtk_print_context_get_height(context);
1512   scale = MIN(width/pg->width, height/pg->height);
1513   
1514   cairo_translate(cr, (width-scale*pg->width)/2, (height-scale*pg->height)/2);
1515   cairo_scale(cr, scale, scale);
1516   cairo_set_line_join(cr, CAIRO_LINE_JOIN_ROUND);
1517   cairo_set_line_cap(cr, CAIRO_LINE_CAP_ROUND);
1518   
1519   print_background(cr, pg);
1520
1521   old_rgba = predef_colors_rgba[COLOR_BLACK];
1522   cairo_set_source_rgb(cr, 0, 0, 0);
1523   old_thickness = 0.0;
1524
1525   for (layerlist = pg->layers; layerlist!=NULL; layerlist = layerlist->next) {
1526     l = (struct Layer *)layerlist->data;
1527     for (itemlist = l->items; itemlist!=NULL; itemlist = itemlist->next) {
1528       item = (struct Item *)itemlist->data;
1529       if (item->type == ITEM_STROKE || item->type == ITEM_TEXT) {
1530         if (item->brush.color_rgba != old_rgba)
1531           cairo_set_source_rgba(cr, RGBA_RGB(item->brush.color_rgba),
1532                                     RGBA_ALPHA(item->brush.color_rgba));
1533         old_rgba = item->brush.color_rgba;
1534       }
1535       if (item->type == ITEM_STROKE) {    
1536         if (item->brush.thickness != old_thickness)
1537           cairo_set_line_width(cr, item->brush.thickness);
1538         pt = item->path->coords;
1539         if (!item->brush.variable_width) {
1540           cairo_move_to(cr, pt[0], pt[1]);
1541           for (i=1, pt+=2; i<item->path->num_points; i++, pt+=2)
1542             cairo_line_to(cr, pt[0], pt[1]);
1543           cairo_stroke(cr);
1544           old_thickness = item->brush.thickness;
1545         } else {
1546           for (i=0; i<item->path->num_points-1; i++, pt+=2) {
1547             cairo_move_to(cr, pt[0], pt[1]);
1548             cairo_set_line_width(cr, item->widths[i]);
1549             cairo_line_to(cr, pt[2], pt[3]);
1550             cairo_stroke(cr);
1551           }
1552           old_thickness = 0.0;
1553         }
1554       }
1555       if (item->type == ITEM_TEXT) {
1556         layout = gtk_print_context_create_pango_layout(context);
1557         font_desc = pango_font_description_from_string(item->font_name);
1558         if (item->font_size)
1559           pango_font_description_set_absolute_size(font_desc,
1560             item->font_size*PANGO_SCALE);
1561         pango_layout_set_font_description(layout, font_desc);
1562         pango_font_description_free(font_desc);
1563         pango_layout_set_text(layout, item->text, -1);
1564         cairo_move_to(cr, item->bbox.left, item->bbox.top);
1565         pango_cairo_show_layout(cr, layout);
1566         g_object_unref(layout);
1567       }
1568     }
1569   }
1570 }
1571
1572 #endif