small fixes
[swftools.git] / lib / pdf / BitmapOutputDev.cc
1 /* InfoOutputDev.h
2
3    Output Device which creates a bitmap.
4
5    Swftools is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 2 of the License, or
8    (at your option) any later version.
9
10    Swftools is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with swftools; if not, write to the Free Software
17    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
18
19 #include <stdlib.h>
20 #include <stdio.h>
21 #include <memory.h>
22 #include <assert.h>
23 #include "config.h"
24 #include "BitmapOutputDev.h"
25 #include "GFXOutputDev.h"
26 #include "SplashBitmap.h"
27 #include "SplashPattern.h"
28 #include "Splash.h"
29 #include "../log.h"
30 #include "../png.h"
31 #include "../devices/record.h"
32 #include "../types.h"
33
34 #define UNKNOWN_BOUNDING_BOX 0,0,0,0
35
36 static SplashColor splash_white = {255,255,255};
37 static SplashColor splash_black = {0,0,0};
38     
39 ClipState::ClipState()
40 {
41     this->next = 0;
42     this->clipbitmap = 0;
43     this->written = 0;
44 }
45
46 BitmapOutputDev::BitmapOutputDev(InfoOutputDev*info, PDFDoc*doc)
47 {
48     this->info = info;
49     this->doc = doc;
50     this->xref = doc->getXRef();
51     
52     /* color graphic output device, for creating bitmaps */
53     this->rgbdev = new SplashOutputDev(splashModeRGB8, 1, gFalse, splash_white, gTrue, gTrue);
54   
55     /* color mode for binary bitmaps */
56     SplashColorMode colorMode = splashModeMono1;
57
58     /* two devices for testing things against clipping: one clips, the other doesn't */
59     this->clip0dev = new SplashOutputDev(colorMode, 1, gFalse, splash_black, gTrue, gFalse);
60     this->clip1dev = new SplashOutputDev(colorMode, 1, gFalse, splash_black, gTrue, gFalse);
61     
62     /* device indicating where polygonal pixels were drawn */
63     this->boolpolydev = new SplashOutputDev(colorMode, 1, gFalse, splash_black, gTrue, gFalse);
64     /* device indicating where text pixels were drawn */
65     this->booltextdev = new SplashOutputDev(colorMode, 1, gFalse, splash_black, gTrue, gFalse);
66
67     /* device for handling texts and links */
68     this->gfxdev = new GFXOutputDev(info, this->doc);
69
70     this->rgbdev->startDoc(this->xref);
71     this->boolpolydev->startDoc(this->xref);
72     this->booltextdev->startDoc(this->xref);
73     this->clip0dev->startDoc(this->xref);
74     this->clip1dev->startDoc(this->xref);
75
76     this->gfxoutput = (gfxdevice_t*)malloc(sizeof(gfxdevice_t));
77     gfxdevice_record_init(this->gfxoutput);
78
79     this->gfxdev->setDevice(this->gfxoutput);
80     
81     this->config_extrafontdata = 0;
82     this->bboxpath = 0;
83     //this->clipdev = 0;
84     //this->clipstates = 0;
85 }
86 BitmapOutputDev::~BitmapOutputDev()
87 {
88     if(this->gfxoutput) {
89         gfxresult_t*r = this->gfxoutput->finish(this->gfxoutput);
90         r->destroy(r);
91         free(this->gfxoutput);this->gfxoutput = 0;
92     }
93     if(this->bboxpath) {
94         delete this->bboxpath;this->bboxpath = 0;
95     }
96     if(this->rgbdev) {
97         delete this->rgbdev;this->rgbdev = 0;
98     }
99     if(this->gfxdev) {
100         delete this->gfxdev;this->gfxdev= 0;
101     }
102     if(this->boolpolydev) {
103         delete this->boolpolydev;this->boolpolydev = 0;
104     }
105     if(this->booltextdev) {
106         delete this->booltextdev;this->booltextdev = 0;
107     }
108     if(this->clip0dev) {
109         delete this->clip0dev;this->clip0dev = 0;
110     }
111     if(this->clip1dev) {
112         delete this->clip1dev;this->clip1dev = 0;
113     }
114     //if(this->clipbitmap) {
115     //    delete this->clipbitmap;this->clipbitmap = 0;
116     //}
117     //if(this->clipdev) {
118     //    delete this->clipdev;this->clipdev = 0;
119     //}
120
121 }
122
123 GBool BitmapOutputDev::getVectorAntialias()
124 {
125     return this->rgbdev->getVectorAntialias();
126 }
127 void BitmapOutputDev::setVectorAntialias(GBool vaa)
128 {
129     this->rgbdev->setVectorAntialias(vaa);
130 }
131 void BitmapOutputDev::setDevice(gfxdevice_t*dev)
132 {
133     this->dev = dev;
134 }
135 void BitmapOutputDev::setMove(int x,int y)
136 {
137     this->gfxdev->setMove(x,y);
138     this->user_movex = x;
139     this->user_movey = y;
140 }
141 void BitmapOutputDev::setClip(int x1,int y1,int x2,int y2)
142 {
143     this->gfxdev->setClip(x1,y1,x2,y2);
144     this->user_clipx1 = x1;
145     this->user_clipy1 = y1;
146     this->user_clipx2 = x2;
147     this->user_clipy2 = y2;
148 }
149 void BitmapOutputDev::setParameter(const char*key, const char*value)
150 {
151     if(!strcmp(key, "extrafontdata")) {
152         this->config_extrafontdata = atoi(value);
153     }
154     this->gfxdev->setParameter(key, value);
155 }
156 void BitmapOutputDev::setPageMap(int*page2page, int num_pages)
157 {
158     this->gfxdev->setPageMap(page2page, num_pages);
159 }
160
161 static void getBitmapBBox(Guchar*alpha, int width, int height, int*xmin, int*ymin, int*xmax, int*ymax)
162 {
163     *ymin = -1;
164     *xmin = width;
165     *xmax = 0;
166     int x,y;
167     for(y=0;y<height;y++) {
168         Guchar*a = &alpha[y*width];
169         for(x=0;x<width;x++) {
170             if(a[x]) break;
171         }
172         int left = x; //first occupied pixel from left
173         int right = x+1; //last non-occupied pixel from right
174         for(;x<width;x++) {
175             if(a[x]) right=x+1;
176         }
177
178         if(left!=width) {
179             if(*ymin<0) 
180                 *ymin=y;
181             *ymax=y+1;
182             if(left<*xmin) *xmin = left;
183             if(right>*xmax) *xmax = right;
184         }
185     }
186     if(*xmin>=*xmax || *ymin>=*ymax) {
187         *xmin = 0;
188         *ymin = 0;
189         *xmax = 0;
190         *ymax = 0;
191     }
192 }
193
194 void BitmapOutputDev::flushBitmap()
195 {
196     int width = rgbdev->getBitmapWidth();
197     int height = rgbdev->getBitmapHeight();
198     
199     SplashColorPtr rgb = rgbbitmap->getDataPtr();
200     Guchar*alpha = rgbbitmap->getAlphaPtr();
201     Guchar*alpha2 = boolpolybitmap->getAlphaPtr();
202
203     int xmin,ymin,xmax,ymax;
204     getBitmapBBox(alpha, width, height, &xmin,&ymin,&xmax,&ymax);
205
206     /* clip against (-movex, -movey, -movex+width, -movey+height) */
207     if(xmin < -this->movex) xmin = -this->movex;
208     if(ymin < -this->movey) ymin = -this->movey;
209     if(xmax > -this->movex + width) xmax = -this->movex+this->width;
210     if(ymax > -this->movey + height) ymax = -this->movey+this->height;
211
212     msg("<verbose> Flushing bitmap (bbox: %d,%d,%d,%d)", xmin,ymin,xmax,ymax);
213     
214     if((xmax-xmin)<=0 || (ymax-ymin)<=0) // no bitmap, nothing to do
215         return;
216
217     if(sizeof(SplashColor)!=3) {
218         msg("<error> sizeof(SplashColor)!=3");
219         return;
220     }
221     //xmin = ymin = 0;
222     //xmax = width;
223     //ymax = height;
224     
225     int rangex = xmax-xmin;
226     int rangey = ymax-ymin;
227     gfximage_t*img = (gfximage_t*)malloc(sizeof(gfximage_t)); 
228     img->data = (gfxcolor_t*)malloc(rangex * rangey * 4);
229     img->width = rangex;
230     img->height = rangey;
231     int x,y;
232     for(y=0;y<rangey;y++) {
233         SplashColorPtr in=&rgb[((y+ymin)*width+xmin)*sizeof(SplashColor)];
234         gfxcolor_t*out = &img->data[y*rangex];
235         Guchar*ain = &alpha[(y+ymin)*width+xmin];
236         Guchar*ain2 = &alpha2[(y+ymin)*width+xmin];
237         if(this->emptypage) {
238             for(x=0;x<rangex;x++) {
239                 /* the first bitmap on the page doesn't need to have an alpha channel-
240                    blend against a white background*/
241                 out[x].r = (in[x*3+0]*ain[x])/255 + 255-ain[x];
242                 out[x].g = (in[x*3+1]*ain[x])/255 + 255-ain[x];
243                 out[x].b = (in[x*3+2]*ain[x])/255 + 255-ain[x];
244                 out[x].a = 255;
245             }
246         } else {
247             for(x=0;x<rangex;x++) {
248                 /*
249                 if(!ain2[x]) {
250                     out[x].r = 0;out[x].g = 0;out[x].b = 0;out[x].a = 0;
251                 } else {*/
252
253                 /* according to endPage()/compositeBackground() in xpdf/SplashOutputDev.cc, we
254                    have to premultiply alpha (mix background and pixel according to the alpha channel).
255                 */
256                 out[x].r = (in[x*3+0]*ain[x])/255;
257                 out[x].g = (in[x*3+1]*ain[x])/255;
258                 out[x].b = (in[x*3+2]*ain[x])/255;
259                 out[x].a = ain[x];
260             }
261         }
262     }
263     /* transform bitmap rectangle to "device space" */
264     xmin += movex;
265     ymin += movey;
266     xmax += movex;
267     ymax += movey;
268
269     gfxmatrix_t m;
270     m.tx = xmin;
271     m.ty = ymin;
272     m.m00 = m.m11 = 1;
273     m.m10 = m.m01 = 0;
274     m.tx -= 0.5;
275     m.ty -= 0.5;
276
277     gfxline_t* line = gfxline_makerectangle(xmin, ymin, xmax, ymax);
278     dev->fillbitmap(dev, line, img, &m, 0);
279     gfxline_free(line);
280
281     memset(rgbbitmap->getAlphaPtr(), 0, rgbbitmap->getWidth()*rgbbitmap->getHeight());
282     memset(rgbbitmap->getDataPtr(), 0, rgbbitmap->getRowSize()*rgbbitmap->getHeight());
283
284     free(img->data);img->data=0;free(img);img=0;
285
286     this->emptypage = 0;
287 }
288
289 void BitmapOutputDev::flushText()
290 {
291     msg("<verbose> Flushing text/polygons");
292     gfxdevice_record_flush(this->gfxoutput, this->dev);
293     
294     this->emptypage = 0;
295 }
296
297 void writeMonoBitmap(SplashBitmap*btm, char*filename)
298 {
299     int width8 = (btm->getWidth()+7)/8;
300     int width = btm->getWidth();
301     int height = btm->getHeight();
302     gfxcolor_t*b = (gfxcolor_t*)malloc(sizeof(gfxcolor_t)*width*height);
303     unsigned char*data = btm->getDataPtr();
304     int x,y;
305     for(y=0;y<height;y++) {
306         unsigned char*l = &data[width8*y];
307         gfxcolor_t*d = &b[width*y];
308         for(x=0;x<width;x++) {
309             if(l[x>>3]&(128>>(x&7))) {
310                 d[x].r = d[x].g = d[x].b = 255;
311             } else {
312                 d[x].r = d[x].g = d[x].b = 0;
313             }
314             d[x].a = 255;
315         }
316     }
317     writePNG(filename, (unsigned char*)b, width, height);
318     free(b);
319 }
320
321 void writeBitmap(SplashBitmap*bitmap, char*filename)
322 {
323     int y,x;
324     
325     int width = bitmap->getWidth();
326     int height = bitmap->getHeight();
327
328     gfxcolor_t*data = (gfxcolor_t*)malloc(sizeof(gfxcolor_t)*width*height);
329
330     if(bitmap->getMode()==splashModeMono1) {
331         writeMonoBitmap(bitmap, filename);
332         return;
333     }
334
335     for(y=0;y<height;y++) {
336         gfxcolor_t*line = &data[y*width];
337         for(x=0;x<width;x++) {
338             Guchar c[4] = {0,0,0,0};
339             bitmap->getPixel(x,y,c);
340             line[x].r = c[0];
341             line[x].g = c[1];
342             line[x].b = c[2];
343             line[x].a =  bitmap->getAlpha(x,y);
344         }
345     }
346     writePNG(filename, (unsigned char*)data, width, height);
347     free(data);
348 }
349
350 void writeAlpha(SplashBitmap*bitmap, char*filename)
351 {
352     int y,x;
353     
354     int width = bitmap->getWidth();
355     int height = bitmap->getHeight();
356     
357     if(bitmap->getMode()==splashModeMono1) {
358         writeMonoBitmap(bitmap, filename);
359         return;
360     }
361
362     gfxcolor_t*data = (gfxcolor_t*)malloc(sizeof(gfxcolor_t)*width*height);
363
364     for(y=0;y<height;y++) {
365         gfxcolor_t*line = &data[y*width];
366         for(x=0;x<width;x++) {
367             int a = bitmap->getAlpha(x,y);
368             line[x].r = a;
369             line[x].g = a;
370             line[x].b = a;
371             line[x].a = 255;
372         }
373     }
374     writePNG(filename, (unsigned char*)data, width, height);
375     free(data);
376 }
377 static int dbg_btm_counter=1;
378
379 static const char*STATE_NAME[] = {"parallel", "textabovebitmap", "bitmapabovetext"};
380
381 int checkAlphaSanity(SplashBitmap*boolbtm, SplashBitmap*alphabtm)
382 {
383     assert(boolbtm->getWidth() == alphabtm->getWidth());
384     assert(boolbtm->getHeight() == alphabtm->getHeight());
385     if(boolbtm->getMode()==splashModeMono1) {
386         return 1;
387     }
388
389     int width = boolbtm->getWidth();
390     int height = boolbtm->getHeight();
391
392     int bad=0;
393     int x,y;
394     for(y=0;y<height;y++) {
395         for(x=0;x<width;x++) {
396             int a1 = alphabtm->getAlpha(x,y);
397             int a2 = boolbtm->getAlpha(x,y);
398             if(a1!=a2) {
399                 bad++;
400             }
401         }
402     }
403     double badness = bad/(double)(width*height);
404     if(badness>0.2) {
405         msg("<error> Bitmaps don't correspond: %d out of %d pixels wrong (%.2f%%)", bad, width*height, 
406                 badness*100.0);
407         return 0;
408     }
409     msg("<notice> %f", badness);
410     return 1;
411 }
412
413 GBool BitmapOutputDev::checkNewText(int x1, int y1, int x2, int y2)
414 {
415     /* called once some new text was drawn on booltextdev, and
416        before the same thing is drawn on gfxdev */
417    
418     msg("<trace> Testing new text data against current bitmap data, state=%s, counter=%d\n", STATE_NAME[layerstate], dbg_btm_counter);
419     
420     char filename1[80];
421     char filename2[80];
422     char filename3[80];
423     sprintf(filename1, "state%dboolbitmap_afternewtext.png", dbg_btm_counter);
424     sprintf(filename2, "state%dbooltext_afternewtext.png", dbg_btm_counter);
425     sprintf(filename3, "state%dbitmap_afternewtext.png", dbg_btm_counter);
426     if(0) {
427         msg("<verbose> %s %s %s", filename1, filename2, filename3);
428         writeAlpha(boolpolybitmap, filename1);
429         writeAlpha(booltextbitmap, filename2);
430         writeBitmap(rgbdev->getBitmap(), filename3);
431     }
432     dbg_btm_counter++;
433
434     GBool ret = false;
435     if(intersection(x1,y1,x2,y2)) {
436         if(layerstate==STATE_PARALLEL) {
437             /* the new text is above the bitmap. So record that fact,
438                and also clear the bitmap buffer, so we can check for
439                new intersections */
440             msg("<verbose> Text is above current bitmap/polygon data");
441             layerstate=STATE_TEXT_IS_ABOVE;
442             clearBoolPolyDev(x1,y1,x2,y2);
443         } else if(layerstate==STATE_BITMAP_IS_ABOVE) {
444             /* there's a bitmap above the (old) text. So we need
445                to flush out that text, and record that the *new*
446                text is now *above* the bitmap
447              */
448             msg("<verbose> Text is above current bitmap/polygon data (which is above some other text)");
449             flushText();
450             layerstate=STATE_TEXT_IS_ABOVE;
451             /* clear both bool devices- the text device because
452                we just dumped out all the (old) text, and the
453                poly dev so we can check for new intersections */
454             clearBoolPolyDev(x1,y1,x2,y2);
455             /* FIXME this destroys the text pixels we just
456                drew to test for the intersection- however we need
457                those to check for the *new* intersections */
458             clearBoolTextDev(x1,y1,x2,y2);
459             ret = true;
460         } else {
461             /* we already know that the current text section is
462                above the current bitmap section- now just new
463                bitmap data *and* new text data was drawn, and
464                *again* it's above the current bitmap- so clear
465                the polygon bitmap again, so we can check for
466                new intersections */
467             msg("<verbose> Text is still above current bitmap/polygon data");
468             clearBoolPolyDev(x1,y1,x2,y2);
469         }
470     } 
471     return ret;
472 }
473
474 GBool BitmapOutputDev::checkNewBitmap(int x1, int y1, int x2, int y2)
475 {
476     /* similar to checkNewText() above, only in reverse */
477     msg("<trace> Testing new graphics data against current text data, state=%s, counter=%d\n", STATE_NAME[layerstate], dbg_btm_counter);
478
479     char filename1[80];
480     char filename2[80];
481     char filename3[80];
482     sprintf(filename1, "state%dboolbitmap_afternewgfx.png", dbg_btm_counter);
483     sprintf(filename2, "state%dbooltext_afternewgfx.png", dbg_btm_counter);
484     sprintf(filename3, "state%dbitmap_afternewgfx.png", dbg_btm_counter);
485
486     if(0) {
487         msg("<verbose> %s %s %s", filename1, filename2, filename3);
488         writeAlpha(boolpolybitmap, filename1);
489         writeAlpha(booltextbitmap, filename2);
490         writeBitmap(rgbdev->getBitmap(), filename3);
491     }
492     dbg_btm_counter++;
493
494     GBool ret = false;
495     if(intersection(x1,y1,x2,y2)) {
496         if(layerstate==STATE_PARALLEL) {
497             msg("<verbose> Bitmap is above current text data");
498             layerstate=STATE_BITMAP_IS_ABOVE;
499             clearBoolTextDev(x1,y1,x2,y2);
500         } else if(layerstate==STATE_TEXT_IS_ABOVE) {
501             msg("<verbose> Bitmap is above current text data (which is above some bitmap)");
502             flushBitmap();
503             layerstate=STATE_BITMAP_IS_ABOVE;
504             clearBoolTextDev(x1,y1,x2,y2);
505             /* FIXME this destroys the polygon pixels we just
506                drew to test for the intersection- however we need
507                those to check for the *new* intersections */
508             clearBoolPolyDev(x1,y1,x2,y2);
509             ret = true;
510         } else {
511             msg("<verbose> Bitmap is still above current text data");
512             clearBoolTextDev(x1,y1,x2,y2);
513         }
514     } 
515     return ret;
516 }
517
518 //void checkNewText() {
519 //    Guchar*alpha = rgbbitmap->getAlphaPtr();
520 //    Guchar*charpixels = clip1bitmap->getDataPtr();
521 //    int xx,yy;
522 //    for(yy=0;yy<height;yy++) {
523 //        Guchar*aline = &alpha[yy*width];
524 //        Guchar*cline = &charpixels[yy*width8];
525 //        for(xx=0;xx<width;xx++) {
526 //            int bit = xx&7;
527 //            int bytepos = xx>>3;
528 //            /* TODO: is the bit order correct? */
529 //            if(aline[xx] && (cline[bytepos]&(1<<bit))) 
530 //              break;
531 //        }
532 //        if(xx!=width)
533 //            break;
534 //}
535
536 static inline GBool fixBBox(int*x1, int*y1, int*x2, int*y2, int width, int height)
537 {
538     if(!(*x1|*y1|*x2|*y2)) {
539         // undefined bbox
540         *x1 = *y1 = 0;
541         *x2 = width;
542         *y2 = height;
543         return gTrue;
544     }
545     if(*x2<=*x1) return gFalse;
546     if(*x2<0) return gFalse;
547     if(*x1<0) *x1 = 0;
548     if(*x1>=width) return gFalse;
549     if(*x2>width) *x2=width;
550
551     if(*y2<=*y1) return gFalse;
552     if(*y2<0) return gFalse;
553     if(*y1<0) *y1 = 0;
554     if(*y1>=height) return gFalse;
555     if(*y2>height) *y2=height;
556     return gTrue;
557 }
558
559 GBool BitmapOutputDev::clip0and1differ(int x1,int y1,int x2,int y2)
560 {
561     if(clip0bitmap->getMode()==splashModeMono1) {
562         int width = clip0bitmap->getWidth();
563         int width8 = (width+7)/8;
564         int height = clip0bitmap->getHeight();
565
566         if(fixBBox(&x1,&y1,&x2,&y2,width,height)) {
567             /* area is outside or null */
568             return gFalse;
569         }
570         
571         SplashBitmap*clip0 = clip0bitmap;
572         SplashBitmap*clip1 = clip1bitmap;
573         int x18 = x1/8;
574         int x28 = (x2+7)/8;
575         int y;
576
577         for(y=y1;y<y2;y++) {
578             unsigned char*row1 = &clip0bitmap->getDataPtr()[width8*y+x18];
579             unsigned char*row2 = &clip1bitmap->getDataPtr()[width8*y+x28];
580             if(memcmp(row1, row2, x28-x18))
581                 return gTrue;
582         }
583         return gFalse;
584     } else {
585         SplashBitmap*clip0 = clip0bitmap;
586         SplashBitmap*clip1 = clip1bitmap;
587         int width = clip0->getAlphaRowSize();
588         int height = clip0->getHeight();
589
590         if(!fixBBox(&x1, &y1, &x2, &y2, width, height)) {
591             x1=y1=0;x2=y2=1;
592         }
593
594         Guchar*a0 = clip0->getAlphaPtr();
595         Guchar*a1 = clip1->getAlphaPtr();
596         int x,y;
597         char differs=0;
598         for(y=y1;y<y2;y++) {
599             for(x=x1;x<x2;x++) {
600                 if(a0[y*width+x]!=a1[y*width+x]) {
601                     differs=1;
602                     break;
603                 }
604             }
605             if(differs)
606                 break;
607         }
608         char differs2 = memcmp(a0, a1, width*height);
609         if(differs && !differs2) 
610             msg("<warning> Strange internal error (2)");
611         else if(!differs && differs2) {
612             msg("<warning> Bad Bounding Box: Difference in clip0 and clip1 outside bbox");
613             msg("<warning> %d %d %d %d", x1, y1, x2, y2);
614         }
615         return differs2;
616     }
617 }
618
619 static void clearBooleanBitmap(SplashBitmap*btm, int x1, int y1, int x2, int y2)
620 {
621     if(!(x1|y1|x2|y2)) {
622         x1 = y1 = 0;
623         x2 = btm->getWidth();
624         y2 = btm->getHeight();
625     }
626     if(btm->getMode()==splashModeMono1) {
627         int width8 = (btm->getWidth()+7)/8;
628         int width = btm->getWidth();
629         int height = btm->getHeight();
630         memset(btm->getDataPtr(), 0, width8*height);
631     } else {
632         int width = btm->getAlphaRowSize();
633         int height = btm->getHeight();
634         memset(btm->getAlphaPtr(), 0, width*height);
635     }
636 }
637
638 GBool compare8(unsigned char*data1, unsigned char*data2, int len)
639 {
640     if(!len)
641         return 0;
642     if(((ptroff_t)data1&7)==((ptroff_t)data2&7)) {
643         // oh good, we can do aligning
644         while((ptroff_t)data1&7) {
645             if(*data1&*data2)
646                 return 1;
647             data1++;
648             data2++;
649             if(!--len)
650                 return 0;
651         }
652     }
653     /* use 64 bit for the (hopefully aligned) middle section */
654     int l8 = len/8;
655     long long unsigned int*d1 = (long long unsigned int*)data1;
656     long long unsigned int*d2 = (long long unsigned int*)data2;
657     long long unsigned int x = 0;
658     int t;
659     for(t=0;t<l8;t++) {
660         x |= d1[t]&d2[t];
661     }
662     if(x)
663         return 1;
664
665     data1+=l8*8;
666     data2+=l8*8;
667     len -= l8*8;
668     for(t=0;t<len;t++) {
669         if(data1[t]&data2[t]) {
670             return 1;
671         }
672     }
673     return 0;
674 }
675
676 GBool BitmapOutputDev::intersection(int x1, int y1, int x2, int y2)
677 {
678     SplashBitmap*boolpoly = boolpolybitmap;
679     SplashBitmap*booltext = booltextbitmap;
680             
681     if(boolpoly->getMode()==splashModeMono1) {
682         /* alternative implementation, using one bit per pixel-
683            needs the no-dither patch in xpdf */
684         
685         int width = boolpoly->getWidth();
686         int height = boolpoly->getHeight();
687
688         if(!fixBBox(&x1,&y1,&x2,&y2, width, height)) {
689             return gFalse;
690         }
691
692         Guchar*polypixels = boolpoly->getDataPtr();
693         Guchar*textpixels = booltext->getDataPtr();
694
695         int width8 = (width+7)/8;
696         int runx = width8;
697         int runy = height;
698         
699         if(x1|y1|x2|y2) {
700             polypixels+=y1*width8+x1/8;
701             textpixels+=y1*width8+x1/8;
702             runx=(x2+7)/8 - x1/8;
703             runy=y2-y1;
704         }
705         
706         int t;
707         unsigned char c=0;
708         
709         /*assert(sizeof(unsigned long long int)==8);
710         if(((ptroff_t)polypixels&7) || ((ptroff_t)textpixels&7)) {
711             //msg("<warning> Non-optimal alignment");
712         }*/
713
714         int x,y;
715         unsigned char*data1 = (unsigned char*)polypixels;
716         unsigned char*data2 = (unsigned char*)textpixels;
717         msg("<verbose> Testing area (%d,%d,%d,%d), runx=%d,runy=%d", x1,y1,x2,y2, runx, runy);
718         for(y=0;y<runy;y++) {
719             if(compare8(data1,data2,runx))
720                 return gTrue;
721             data1+=width8;
722             data2+=width8;
723         }
724         return gFalse;
725     } else {
726         int width = boolpoly->getAlphaRowSize();
727         int height = boolpoly->getHeight();
728
729         if(!fixBBox(&x1, &y1, &x2, &y2, width, height)) {
730             x1=y1=0;x2=y2=1;
731         }
732         Guchar*polypixels = boolpoly->getAlphaPtr();
733         Guchar*textpixels = booltext->getAlphaPtr();
734
735         int x,y;
736         char overlap1 = 0;
737         char overlap2 = 0;
738         for(x=x1;x<x2;x++) {
739             for(y=y1;y<y2;y++) {
740                 if(polypixels[width*y+x]&&textpixels[width*y+x])
741                     overlap1 = 1;
742             }
743         }
744         int ax1=0,ay1=0,ax2=0,ay2=0;
745         for(y=0;y<height;y++) {
746             for(x=0;x<width;x++) {
747                 if(polypixels[width*y+x]&&textpixels[width*y+x]) {
748                     overlap2 = 1;
749                     if(!(ax1|ay1|ax2|ay2)) {
750                         ax1 = ax2 = x;
751                         ay1 = ay2 = y;
752                     } else {
753                         ax1 = ax1<x?ax1:x;
754                         ay1 = ay1<y?ay1:y;
755                         ax2 = ax2>x?ax2:x;
756                         ay2 = ay2>y?ay2:y;
757                     }
758                 }
759             }
760         }
761         if(overlap1 && !overlap2)
762             msg("<warning> strange internal error");
763         if(!overlap1 && overlap2) {
764             msg("<warning> Bad bounding box: intersection outside bbox");
765             msg("<warning> given bbox: %d %d %d %d", x1, y1, x2, y2);
766             msg("<warning> changed area: %d %d %d %d", ax1, ay1, ax2, ay2);
767             //writeAlpha(booltextbitmap, "alpha.png");
768         }
769         return overlap2;
770     }
771 }
772
773
774 void BitmapOutputDev::startPage(int pageNum, GfxState *state, double crop_x1, double crop_y1, double crop_x2, double crop_y2)
775 {
776     double x1,y1,x2,y2;
777     state->transform(crop_x1,crop_y1,&x1,&y1);
778     state->transform(crop_x2,crop_y2,&x2,&y2);
779     if(x2<x1) {double x3=x1;x1=x2;x2=x3;}
780     if(y2<y1) {double y3=y1;y1=y2;y2=y3;}
781     
782     this->movex = -(int)x1 - user_movex;
783     this->movey = -(int)y1 - user_movey;
784     
785     if(user_clipx1|user_clipy1|user_clipx2|user_clipy2) {
786         x1 = user_clipx1;
787         x2 = user_clipx2;
788         y1 = user_clipy1;
789         y2 = user_clipy2;
790     }
791     this->width = (int)(x2-x1);
792     this->height = (int)(y2-y1);
793
794     msg("<debug> startPage");
795     rgbdev->startPage(pageNum, state, crop_x1, crop_y1, crop_x2, crop_y2);
796     boolpolydev->startPage(pageNum, state, crop_x1, crop_y1, crop_x2, crop_y2);
797     booltextdev->startPage(pageNum, state, crop_x1, crop_y1, crop_x2, crop_y2);
798     clip0dev->startPage(pageNum, state, crop_x1, crop_y1, crop_x2, crop_y2);
799     clip1dev->startPage(pageNum, state, crop_x1, crop_y1, crop_x2, crop_y2);
800     gfxdev->startPage(pageNum, state, crop_x1, crop_y1, crop_x2, crop_y2);
801
802     boolpolybitmap = boolpolydev->getBitmap();
803     booltextbitmap = booltextdev->getBitmap();
804     clip0bitmap = clip0dev->getBitmap();
805     clip1bitmap = clip1dev->getBitmap();
806     rgbbitmap = rgbdev->getBitmap();
807     
808     flushText(); // write out the initial clipping rectangle
809
810     /* just in case any device did draw a white background rectangle 
811        into the device */
812     clearBoolTextDev(UNKNOWN_BOUNDING_BOX);
813     clearBoolPolyDev(UNKNOWN_BOUNDING_BOX);
814
815     this->layerstate = STATE_PARALLEL;
816     this->emptypage = 1;
817     msg("<debug> startPage done");
818 }
819
820 void BitmapOutputDev::endPage()
821 {
822     msg("<verbose> endPage (BitmapOutputDev)");
823
824     /* notice: we're not fully done yet with this page- there might still be 
825        a few calls to drawLink() yet to come */
826 }
827 void BitmapOutputDev::finishPage()
828 {
829     msg("<verbose> finishPage (BitmapOutputDev)");
830     gfxdev->endPage();
831    
832     if(layerstate == STATE_BITMAP_IS_ABOVE) {
833         this->flushText();
834         this->flushBitmap();
835     } else {
836         this->flushBitmap();
837         this->flushText();
838     }
839
840     /* splash will now destroy alpha, and paint the 
841        background color into the "holes" in the bitmap */
842     boolpolydev->endPage();
843     booltextdev->endPage();
844     rgbdev->endPage();
845     clip0dev->endPage();
846     clip1dev->endPage();
847 }
848
849 GBool BitmapOutputDev::upsideDown()
850 {
851     boolpolydev->upsideDown();
852     booltextdev->upsideDown();
853     clip0dev->upsideDown();
854     clip1dev->upsideDown();
855     return rgbdev->upsideDown();
856 }
857
858 GBool BitmapOutputDev::useDrawChar()
859 {
860     boolpolydev->useDrawChar();
861     booltextdev->useDrawChar();
862     clip0dev->useDrawChar();
863     clip1dev->useDrawChar();
864     return rgbdev->useDrawChar();
865 }
866
867 GBool BitmapOutputDev::useTilingPatternFill()
868 {
869     boolpolydev->useTilingPatternFill();
870     booltextdev->useTilingPatternFill();
871     clip0dev->useTilingPatternFill();
872     clip1dev->useTilingPatternFill();
873     return rgbdev->useTilingPatternFill();
874 }
875
876 GBool BitmapOutputDev::useShadedFills()
877 {
878     boolpolydev->useShadedFills();
879     booltextdev->useShadedFills();
880     clip0dev->useShadedFills();
881     clip1dev->useShadedFills();
882     return rgbdev->useShadedFills();
883 }
884
885 GBool BitmapOutputDev::useDrawForm()
886 {
887     boolpolydev->useDrawForm();
888     booltextdev->useDrawForm();
889     clip0dev->useDrawForm();
890     clip1dev->useDrawForm();
891     return rgbdev->useDrawForm();
892 }
893
894 GBool BitmapOutputDev::interpretType3Chars()
895 {
896     boolpolydev->interpretType3Chars();
897     booltextdev->interpretType3Chars();
898     clip0dev->interpretType3Chars();
899     clip1dev->interpretType3Chars();
900     return rgbdev->interpretType3Chars();
901 }
902
903 GBool BitmapOutputDev::needNonText() 
904 {
905     boolpolydev->needNonText();
906     booltextdev->needNonText();
907     clip0dev->needNonText();
908     clip1dev->needNonText();
909     return rgbdev->needNonText();
910 }
911 /*GBool BitmapOutputDev::checkPageSlice(Page *page, double hDPI, double vDPI,
912                            int rotate, GBool useMediaBox, GBool crop,
913                            int sliceX, int sliceY, int sliceW, int sliceH,
914                            GBool printing, Catalog *catalog,
915                            GBool (*abortCheckCbk)(void *data),
916                            void *abortCheckCbkData)
917 {
918     return gTrue;
919 }*/
920 void BitmapOutputDev::setDefaultCTM(double *ctm) 
921 {
922     boolpolydev->setDefaultCTM(ctm);
923     booltextdev->setDefaultCTM(ctm);
924     rgbdev->setDefaultCTM(ctm);
925     clip0dev->setDefaultCTM(ctm);
926     clip1dev->setDefaultCTM(ctm);
927     gfxdev->setDefaultCTM(ctm);
928 }
929 void BitmapOutputDev::saveState(GfxState *state) 
930 {
931     boolpolydev->saveState(state);
932     booltextdev->saveState(state);
933     rgbdev->saveState(state);
934     clip0dev->saveState(state);
935     clip1dev->saveState(state);
936
937     /*ClipState*cstate = new ClipState();
938     cstate->next = this->clipstates;
939     this->clipstates = cstate;*/
940 }
941 void BitmapOutputDev::restoreState(GfxState *state) 
942 {
943     boolpolydev->restoreState(state);
944     booltextdev->restoreState(state);
945     rgbdev->restoreState(state);
946     clip0dev->restoreState(state);
947     clip1dev->restoreState(state);
948
949     /*if(this->clipstates) {
950         ClipState*old = this->clipstates;
951         if(old->written) {
952             gfxdev->restoreState(state);
953         }
954         this->clipstates = this->clipstates->next;
955         delete(old);
956     } else {
957         msg("<error> invalid restoreState()");
958     }*/
959 }
960 void BitmapOutputDev::updateAll(GfxState *state)
961 {
962     boolpolydev->updateAll(state);
963     booltextdev->updateAll(state);
964     rgbdev->updateAll(state);
965     clip0dev->updateAll(state);
966     clip1dev->updateAll(state);
967     gfxdev->updateAll(state);
968 }
969 void BitmapOutputDev::updateCTM(GfxState *state, double m11, double m12, double m21, double m22, double m31, double m32)
970 {
971     boolpolydev->updateCTM(state,m11,m12,m21,m22,m31,m32);
972     booltextdev->updateCTM(state,m11,m12,m21,m22,m31,m32);
973     rgbdev->updateCTM(state,m11,m12,m21,m22,m31,m32);
974     clip0dev->updateCTM(state,m11,m12,m21,m22,m31,m32);
975     clip1dev->updateCTM(state,m11,m12,m21,m22,m31,m32);
976     gfxdev->updateCTM(state,m11,m12,m21,m22,m31,m32);
977 }
978 void BitmapOutputDev::updateLineDash(GfxState *state)
979 {
980     boolpolydev->updateLineDash(state);
981     booltextdev->updateLineDash(state);
982     rgbdev->updateLineDash(state);
983     clip0dev->updateLineDash(state);
984     clip1dev->updateLineDash(state);
985     gfxdev->updateLineDash(state);
986 }
987 void BitmapOutputDev::updateFlatness(GfxState *state)
988 {
989     boolpolydev->updateFlatness(state);
990     booltextdev->updateFlatness(state);
991     rgbdev->updateFlatness(state);
992     clip0dev->updateFlatness(state);
993     clip1dev->updateFlatness(state);
994     gfxdev->updateFlatness(state);
995 }
996 void BitmapOutputDev::updateLineJoin(GfxState *state)
997 {
998     boolpolydev->updateLineJoin(state);
999     booltextdev->updateLineJoin(state);
1000     rgbdev->updateLineJoin(state);
1001     clip0dev->updateLineJoin(state);
1002     clip1dev->updateLineJoin(state);
1003     gfxdev->updateLineJoin(state);
1004 }
1005 void BitmapOutputDev::updateLineCap(GfxState *state)
1006 {
1007     boolpolydev->updateLineCap(state);
1008     booltextdev->updateLineCap(state);
1009     rgbdev->updateLineCap(state);
1010     clip0dev->updateLineCap(state);
1011     clip1dev->updateLineCap(state);
1012     gfxdev->updateLineCap(state);
1013 }
1014 void BitmapOutputDev::updateMiterLimit(GfxState *state)
1015 {
1016     boolpolydev->updateMiterLimit(state);
1017     booltextdev->updateMiterLimit(state);
1018     rgbdev->updateMiterLimit(state);
1019     clip0dev->updateMiterLimit(state);
1020     clip1dev->updateMiterLimit(state);
1021     gfxdev->updateMiterLimit(state);
1022 }
1023 void BitmapOutputDev::updateLineWidth(GfxState *state)
1024 {
1025     boolpolydev->updateLineWidth(state);
1026     booltextdev->updateLineWidth(state);
1027     rgbdev->updateLineWidth(state);
1028     clip0dev->updateLineWidth(state);
1029     clip1dev->updateLineWidth(state);
1030     gfxdev->updateLineWidth(state);
1031 }
1032 void BitmapOutputDev::updateStrokeAdjust(GfxState *state)
1033 {
1034     boolpolydev->updateStrokeAdjust(state);
1035     booltextdev->updateStrokeAdjust(state);
1036     rgbdev->updateStrokeAdjust(state);
1037     clip0dev->updateStrokeAdjust(state);
1038     clip1dev->updateStrokeAdjust(state);
1039     gfxdev->updateStrokeAdjust(state);
1040 }
1041 void BitmapOutputDev::updateFillColorSpace(GfxState *state)
1042 {
1043     boolpolydev->updateFillColorSpace(state);
1044     booltextdev->updateFillColorSpace(state);
1045     rgbdev->updateFillColorSpace(state);
1046     clip0dev->updateFillColorSpace(state);
1047     clip1dev->updateFillColorSpace(state);
1048     gfxdev->updateFillColorSpace(state);
1049 }
1050 void BitmapOutputDev::updateStrokeColorSpace(GfxState *state)
1051 {
1052     boolpolydev->updateStrokeColorSpace(state);
1053     booltextdev->updateStrokeColorSpace(state);
1054     rgbdev->updateStrokeColorSpace(state);
1055     clip0dev->updateStrokeColorSpace(state);
1056     clip1dev->updateStrokeColorSpace(state);
1057     gfxdev->updateStrokeColorSpace(state);
1058 }
1059 void BitmapOutputDev::updateFillColor(GfxState *state)
1060 {
1061     boolpolydev->updateFillColor(state);
1062     booltextdev->updateFillColor(state);
1063     rgbdev->updateFillColor(state);
1064     clip0dev->updateFillColor(state);
1065     clip1dev->updateFillColor(state);
1066     gfxdev->updateFillColor(state);
1067 }
1068 void BitmapOutputDev::updateStrokeColor(GfxState *state)
1069 {
1070     boolpolydev->updateStrokeColor(state);
1071     booltextdev->updateStrokeColor(state);
1072     rgbdev->updateStrokeColor(state);
1073     clip0dev->updateStrokeColor(state);
1074     clip1dev->updateStrokeColor(state);
1075     gfxdev->updateStrokeColor(state);
1076 }
1077 void BitmapOutputDev::updateBlendMode(GfxState *state)
1078 {
1079     boolpolydev->updateBlendMode(state);
1080     booltextdev->updateBlendMode(state);
1081     rgbdev->updateBlendMode(state);
1082     clip0dev->updateBlendMode(state);
1083     clip1dev->updateBlendMode(state);
1084     gfxdev->updateBlendMode(state);
1085 }
1086 void BitmapOutputDev::updateFillOpacity(GfxState *state)
1087 {
1088     boolpolydev->updateFillOpacity(state);
1089     booltextdev->updateFillOpacity(state);
1090     rgbdev->updateFillOpacity(state);
1091     clip0dev->updateFillOpacity(state);
1092     clip1dev->updateFillOpacity(state);
1093     gfxdev->updateFillOpacity(state);
1094 }
1095 void BitmapOutputDev::updateStrokeOpacity(GfxState *state)
1096 {
1097     boolpolydev->updateStrokeOpacity(state);
1098     booltextdev->updateStrokeOpacity(state);
1099     rgbdev->updateStrokeOpacity(state);
1100     clip0dev->updateStrokeOpacity(state);
1101     clip1dev->updateStrokeOpacity(state);
1102     gfxdev->updateStrokeOpacity(state);
1103 }
1104 void BitmapOutputDev::updateFillOverprint(GfxState *state)
1105 {
1106     boolpolydev->updateFillOverprint(state);
1107     booltextdev->updateFillOverprint(state);
1108     rgbdev->updateFillOverprint(state);
1109     clip0dev->updateFillOverprint(state);
1110     clip1dev->updateFillOverprint(state);
1111     gfxdev->updateFillOverprint(state);
1112 }
1113 void BitmapOutputDev::updateStrokeOverprint(GfxState *state)
1114 {
1115     boolpolydev->updateStrokeOverprint(state);
1116     booltextdev->updateStrokeOverprint(state);
1117     rgbdev->updateStrokeOverprint(state);
1118     clip0dev->updateStrokeOverprint(state);
1119     clip1dev->updateStrokeOverprint(state);
1120     gfxdev->updateStrokeOverprint(state);
1121 }
1122 void BitmapOutputDev::updateTransfer(GfxState *state)
1123 {
1124     boolpolydev->updateTransfer(state);
1125     booltextdev->updateTransfer(state);
1126     rgbdev->updateTransfer(state);
1127     clip0dev->updateTransfer(state);
1128     clip1dev->updateTransfer(state);
1129     gfxdev->updateTransfer(state);
1130 }
1131
1132 void BitmapOutputDev::updateFont(GfxState *state)
1133 {
1134     boolpolydev->updateFont(state);
1135     booltextdev->updateFont(state);
1136     rgbdev->updateFont(state);
1137     clip0dev->updateFont(state);
1138     clip1dev->updateFont(state);
1139     gfxdev->updateFont(state);
1140 }
1141 void BitmapOutputDev::updateTextMat(GfxState *state)
1142 {
1143     boolpolydev->updateTextMat(state);
1144     booltextdev->updateTextMat(state);
1145     rgbdev->updateTextMat(state);
1146     clip0dev->updateTextMat(state);
1147     clip1dev->updateTextMat(state);
1148     gfxdev->updateTextMat(state);
1149 }
1150 void BitmapOutputDev::updateCharSpace(GfxState *state)
1151 {
1152     boolpolydev->updateCharSpace(state);
1153     booltextdev->updateCharSpace(state);
1154     rgbdev->updateCharSpace(state);
1155     clip0dev->updateCharSpace(state);
1156     clip1dev->updateCharSpace(state);
1157     gfxdev->updateCharSpace(state);
1158 }
1159 void BitmapOutputDev::updateRender(GfxState *state)
1160 {
1161     boolpolydev->updateRender(state);
1162     booltextdev->updateRender(state);
1163     rgbdev->updateRender(state);
1164     clip0dev->updateRender(state);
1165     clip1dev->updateRender(state);
1166     gfxdev->updateRender(state);
1167 }
1168 void BitmapOutputDev::updateRise(GfxState *state)
1169 {
1170     boolpolydev->updateRise(state);
1171     booltextdev->updateRise(state);
1172     rgbdev->updateRise(state);
1173     clip0dev->updateRise(state);
1174     clip1dev->updateRise(state);
1175     gfxdev->updateRise(state);
1176 }
1177 void BitmapOutputDev::updateWordSpace(GfxState *state)
1178 {
1179     boolpolydev->updateWordSpace(state);
1180     booltextdev->updateWordSpace(state);
1181     rgbdev->updateWordSpace(state);
1182     clip0dev->updateWordSpace(state);
1183     clip1dev->updateWordSpace(state);
1184     gfxdev->updateWordSpace(state);
1185 }
1186 void BitmapOutputDev::updateHorizScaling(GfxState *state)
1187 {
1188     boolpolydev->updateHorizScaling(state);
1189     booltextdev->updateHorizScaling(state);
1190     rgbdev->updateHorizScaling(state);
1191     clip0dev->updateHorizScaling(state);
1192     clip1dev->updateHorizScaling(state);
1193     gfxdev->updateHorizScaling(state);
1194 }
1195 void BitmapOutputDev::updateTextPos(GfxState *state)
1196 {
1197     boolpolydev->updateTextPos(state);
1198     booltextdev->updateTextPos(state);
1199     rgbdev->updateTextPos(state);
1200     clip0dev->updateTextPos(state);
1201     clip1dev->updateTextPos(state);
1202     gfxdev->updateTextPos(state);
1203 }
1204 void BitmapOutputDev::updateTextShift(GfxState *state, double shift)
1205 {
1206     boolpolydev->updateTextShift(state, shift);
1207     booltextdev->updateTextShift(state, shift);
1208     rgbdev->updateTextShift(state, shift);
1209     clip0dev->updateTextShift(state, shift);
1210     clip1dev->updateTextShift(state, shift);
1211     gfxdev->updateTextShift(state, shift);
1212 }
1213
1214 double max(double x, double y) 
1215 {
1216     return x>y?x:y;
1217 }
1218 double min(double x, double y) 
1219 {
1220     return x<y?x:y;
1221 }
1222
1223 gfxbbox_t BitmapOutputDev::getBBox(GfxState*state)
1224 {
1225     GfxPath * path = state->getPath();
1226     int num = path->getNumSubpaths();
1227     gfxbbox_t bbox = {0,0,1,1};
1228     char valid=0;
1229     int t;
1230     for(t = 0; t < num; t++) {
1231         GfxSubpath *subpath = path->getSubpath(t);
1232         int subnum = subpath->getNumPoints();
1233         int s;
1234         for(s=0;s<subnum;s++) {
1235            double x,y;
1236            state->transform(subpath->getX(s),subpath->getY(s),&x,&y);
1237            if(!valid) {
1238                bbox.xmin = x; bbox.ymin = y;
1239                bbox.xmax = x; bbox.ymax = y;
1240                valid = 1;
1241            } else {
1242                bbox.xmin = min(bbox.xmin, x);
1243                bbox.ymin = min(bbox.ymin, y);
1244                bbox.xmax = max(bbox.xmax, x);
1245                bbox.ymax = max(bbox.ymax, y);
1246            }
1247         }
1248     }
1249     return bbox;
1250 }
1251
1252 void BitmapOutputDev::stroke(GfxState *state)
1253 {
1254     msg("<debug> stroke");
1255     boolpolydev->stroke(state);
1256     gfxbbox_t bbox = getBBox(state);
1257     double width = state->getTransformedLineWidth();
1258     bbox.xmin -= width; bbox.ymin -= width;
1259     bbox.xmax += width; bbox.ymax += width;
1260     checkNewBitmap(bbox.xmin, bbox.ymin, ceil(bbox.xmax), ceil(bbox.ymax));
1261     rgbdev->stroke(state);
1262 }
1263 void BitmapOutputDev::fill(GfxState *state)
1264 {
1265     msg("<debug> fill");
1266     boolpolydev->fill(state);
1267     gfxbbox_t bbox = getBBox(state);
1268     if(checkNewBitmap(bbox.xmin, bbox.ymin, ceil(bbox.xmax), ceil(bbox.ymax))) {
1269         boolpolydev->fill(state);
1270     }
1271     rgbdev->fill(state);
1272 }
1273 void BitmapOutputDev::eoFill(GfxState *state)
1274 {
1275     msg("<debug> eoFill");
1276     boolpolydev->eoFill(state);
1277     gfxbbox_t bbox = getBBox(state);
1278     if(checkNewBitmap(bbox.xmin, bbox.ymin, ceil(bbox.xmax), ceil(bbox.ymax))) {
1279         boolpolydev->eoFill(state);
1280     }
1281     rgbdev->eoFill(state);
1282 }
1283 #if (xpdfMajorVersion*10000 + xpdfMinorVersion*100 + xpdfUpdateVersion) < 30207
1284 void BitmapOutputDev::tilingPatternFill(GfxState *state, Object *str,
1285                                int paintType, Dict *resDict,
1286                                double *mat, double *bbox,
1287                                int x0, int y0, int x1, int y1,
1288                                double xStep, double yStep)
1289 {
1290     msg("<debug> tilingPatternFill");
1291     boolpolydev->tilingPatternFill(state, str, paintType, resDict, mat, bbox, x0, y0, x1, y1, xStep, yStep);
1292     checkNewBitmap(UNKNOWN_BOUNDING_BOX);
1293     rgbdev->tilingPatternFill(state, str, paintType, resDict, mat, bbox, x0, y0, x1, y1, xStep, yStep);
1294 }
1295 #else
1296 void BitmapOutputDev::tilingPatternFill(GfxState *state, Gfx *gfx, Object *str,
1297                                int paintType, Dict *resDict,
1298                                double *mat, double *bbox,
1299                                int x0, int y0, int x1, int y1,
1300                                double xStep, double yStep) 
1301 {
1302     msg("<debug> tilingPatternFill");
1303     boolpolydev->tilingPatternFill(state, gfx, str, paintType, resDict, mat, bbox, x0, y0, x1, y1, xStep, yStep);
1304     checkNewBitmap(UNKNOWN_BOUNDING_BOX);
1305     rgbdev->tilingPatternFill(state, gfx, str, paintType, resDict, mat, bbox, x0, y0, x1, y1, xStep, yStep);
1306 }
1307 #endif
1308
1309 GBool BitmapOutputDev::functionShadedFill(GfxState *state, GfxFunctionShading *shading) 
1310 {
1311     msg("<debug> functionShadedFill");
1312     boolpolydev->functionShadedFill(state, shading);
1313     checkNewBitmap(UNKNOWN_BOUNDING_BOX);
1314     return rgbdev->functionShadedFill(state, shading);
1315 }
1316 GBool BitmapOutputDev::axialShadedFill(GfxState *state, GfxAxialShading *shading)
1317 {
1318     msg("<debug> axialShadedFill");
1319     boolpolydev->axialShadedFill(state, shading);
1320     checkNewBitmap(UNKNOWN_BOUNDING_BOX);
1321     return rgbdev->axialShadedFill(state, shading);
1322 }
1323 GBool BitmapOutputDev::radialShadedFill(GfxState *state, GfxRadialShading *shading)
1324 {
1325     msg("<debug> radialShadedFill");
1326     boolpolydev->radialShadedFill(state, shading);
1327     checkNewBitmap(UNKNOWN_BOUNDING_BOX);
1328     return rgbdev->radialShadedFill(state, shading);
1329 }
1330
1331 SplashColor black = {0,0,0};
1332 SplashColor white = {255,255,255};
1333
1334 void BitmapOutputDev::clip(GfxState *state)
1335 {
1336     msg("<debug> clip");
1337     boolpolydev->clip(state);
1338     booltextdev->clip(state);
1339     rgbdev->clip(state);
1340     clip1dev->clip(state);
1341 }
1342 void BitmapOutputDev::eoClip(GfxState *state)
1343 {
1344     msg("<debug> eoClip");
1345     boolpolydev->eoClip(state);
1346     booltextdev->eoClip(state);
1347     rgbdev->eoClip(state);
1348     clip1dev->eoClip(state);
1349 }
1350 void BitmapOutputDev::clipToStrokePath(GfxState *state)
1351 {
1352     msg("<debug> clipToStrokePath");
1353     boolpolydev->clipToStrokePath(state);
1354     booltextdev->clipToStrokePath(state);
1355     rgbdev->clipToStrokePath(state);
1356     clip1dev->clipToStrokePath(state);
1357 }
1358
1359 void BitmapOutputDev::beginStringOp(GfxState *state)
1360 {
1361     msg("<debug> beginStringOp");
1362     clip0dev->beginStringOp(state);
1363     clip1dev->beginStringOp(state);
1364     booltextdev->beginStringOp(state);
1365     gfxdev->beginStringOp(state);
1366 }
1367 void BitmapOutputDev::beginString(GfxState *state, GString *s)
1368 {
1369     msg("<debug> beginString");
1370     clip0dev->beginString(state, s);
1371     clip1dev->beginString(state, s);
1372     booltextdev->beginString(state, s);
1373     gfxdev->beginString(state, s);
1374 }
1375
1376 void BitmapOutputDev::clearClips()
1377 {
1378     clearBooleanBitmap(clip0bitmap, 0, 0, 0, 0);
1379     clearBooleanBitmap(clip1bitmap, 0, 0, 0, 0);
1380 }
1381 void BitmapOutputDev::clearBoolPolyDev(int x1, int y1, int x2, int y2)
1382 {
1383     clearBooleanBitmap(boolpolybitmap, x1, y1, x2, y2);
1384 }
1385 void BitmapOutputDev::clearBoolTextDev(int x1, int y1, int x2, int y2)
1386 {
1387     clearBooleanBitmap(booltextbitmap, x1, y1, x2, y2);
1388 }
1389 void BitmapOutputDev::drawChar(GfxState *state, double x, double y,
1390                       double dx, double dy,
1391                       double originX, double originY,
1392                       CharCode code, int nBytes, Unicode *u, int uLen)
1393 {
1394     msg("<debug> drawChar render=%d", state->getRender());
1395
1396     if(state->getRender()&RENDER_CLIP) {
1397         //char is just a clipping boundary
1398         rgbdev->drawChar(state, x, y, dx, dy, originX, originY, code, nBytes, u, uLen);
1399         boolpolydev->drawChar(state, x, y, dx, dy, originX, originY, code, nBytes, u, uLen);
1400         booltextdev->drawChar(state, x, y, dx, dy, originX, originY, code, nBytes, u, uLen);
1401         clip1dev->drawChar(state, x, y, dx, dy, originX, originY, code, nBytes, u, uLen);
1402     } else if(rgbbitmap != rgbdev->getBitmap()) {
1403         // we're doing softmasking or transparency grouping
1404         boolpolydev->drawChar(state, x, y, dx, dy, originX, originY, code, nBytes, u, uLen);
1405         //checkNewBitmap(UNKNOWN_BOUNDING_BOX);
1406         rgbdev->drawChar(state, x, y, dx, dy, originX, originY, code, nBytes, u, uLen);
1407     } else {
1408         // we're drawing a regular char
1409         clearClips();
1410         clip0dev->drawChar(state, x, y, dx, dy, originX, originY, code, nBytes, u, uLen);
1411         clip1dev->drawChar(state, x, y, dx, dy, originX, originY, code, nBytes, u, uLen);
1412    
1413         /* calculate the bbox of this character */
1414         int x1 = (int)x, x2 = (int)x+1, y1 = (int)y, y2 = (int)y+1;
1415         SplashFont*font = clip0dev->getCurrentFont();
1416         SplashPath*path = font?font->getGlyphPath(code):NULL;
1417
1418         if(!path) {
1419             if(code)
1420                 msg("<error> couldn't create outline for char %d", code);
1421             return;
1422         }
1423         x-=originX;
1424         y-=originY;
1425         path->offset((SplashCoord)x, (SplashCoord)y);
1426         int t;
1427         for(t=0;t<path->getLength();t++) {
1428             double xx,yy;
1429             Guchar f;
1430             path->getPoint(t,&xx,&yy,&f);
1431             state->transform(xx,yy,&xx,&yy);
1432             if(xx<x1) x1=(int)xx;
1433             if(yy<y1) y1=(int)yy;
1434             if(xx>=x2) x2=(int)xx+1;
1435             if(yy>=y2) y2=(int)yy+1;
1436         }
1437
1438         /* if this character is affected somehow by the various clippings (i.e., it looks
1439            different on a device without clipping), then draw it on the bitmap, not as
1440            text */
1441         if(clip0and1differ(x1,y1,x2,y2)) {
1442             msg("<verbose> Char %d is affected by clipping", code);
1443             boolpolydev->drawChar(state, x, y, dx, dy, originX, originY, code, nBytes, u, uLen);
1444             checkNewBitmap(x1,y1,x2,y2);
1445             rgbdev->drawChar(state, x, y, dx, dy, originX, originY, code, nBytes, u, uLen);
1446             if(config_extrafontdata) {
1447                 int oldrender = state->getRender();
1448                 state->setRender(3); //invisible
1449                 gfxdev->drawChar(state, x, y, dx, dy, originX, originY, code, nBytes, u, uLen);
1450                 state->setRender(oldrender);
1451             }
1452         } else {
1453             /* this char is not at all affected by clipping. 
1454                Now just dump out the bitmap we're currently working on, if necessary. */
1455             booltextdev->drawChar(state, x, y, dx, dy, originX, originY, code, nBytes, u, uLen);
1456             checkNewText(x1,y1,x2,y2);
1457             /* use polygonal output device to do the actual text handling */
1458             gfxdev->drawChar(state, x, y, dx, dy, originX, originY, code, nBytes, u, uLen);
1459         }
1460     }
1461 }
1462 void BitmapOutputDev::drawString(GfxState *state, GString *s)
1463 {
1464     msg("<error> internal error: drawString not implemented");
1465     return;
1466     clip0dev->drawString(state, s);
1467     clip1dev->drawString(state, s);
1468     booltextdev->drawString(state, s);
1469     gfxdev->drawString(state, s);
1470 }
1471 void BitmapOutputDev::endTextObject(GfxState *state)
1472 {
1473     msg("<debug> endTextObject");
1474     rgbdev->endTextObject(state);
1475     clip0dev->endTextObject(state);
1476     clip1dev->endTextObject(state);
1477     booltextdev->endTextObject(state);
1478     /* the only thing "drawn" here is clipping */
1479     //checkNewText(UNKNOWN_BOUNDING_BOX);
1480     gfxdev->endTextObject(state);
1481 }
1482 void BitmapOutputDev::endString(GfxState *state)
1483 {
1484     msg("<debug> endString");
1485     clip0dev->endString(state);
1486     clip1dev->endString(state);
1487     booltextdev->endString(state);
1488     int render = state->getRender();
1489     if(render != RENDER_INVISIBLE && render != RENDER_FILL) {
1490         checkNewText(UNKNOWN_BOUNDING_BOX);
1491     }
1492     gfxdev->endString(state);
1493 }
1494 void BitmapOutputDev::endStringOp(GfxState *state)
1495 {
1496     msg("<debug> endStringOp");
1497     clip0dev->endStringOp(state);
1498     clip1dev->endStringOp(state);
1499     booltextdev->endStringOp(state);
1500     gfxdev->endStringOp(state);
1501 }
1502
1503 /* TODO: these four operations below *should* do nothing, as type3
1504          chars are drawn using operations like fill() */
1505 GBool BitmapOutputDev::beginType3Char(GfxState *state, double x, double y,
1506                              double dx, double dy,
1507                              CharCode code, Unicode *u, int uLen)
1508 {
1509     msg("<debug> beginType3Char");
1510     /* call gfxdev so that it can generate "invisible" characters
1511        on top of the actual graphic content, for text extraction */
1512     return gfxdev->beginType3Char(state, x, y, dx, dy, code, u, uLen);
1513 }
1514 void BitmapOutputDev::type3D0(GfxState *state, double wx, double wy)
1515 {
1516     msg("<debug> type3D0");
1517     return gfxdev->type3D0(state, wx, wy);
1518 }
1519 void BitmapOutputDev::type3D1(GfxState *state, double wx, double wy, double llx, double lly, double urx, double ury)
1520 {
1521     msg("<debug> type3D1");
1522     return gfxdev->type3D1(state, wx, wy, llx, lly, urx, ury);
1523 }
1524 void BitmapOutputDev::endType3Char(GfxState *state)
1525 {
1526     msg("<debug> endType3Char");
1527     gfxdev->endType3Char(state);
1528 }
1529
1530 class CopyStream: public Object
1531 {
1532     Dict*dict;
1533     char*buf;
1534     MemStream*memstream;
1535     public:
1536     CopyStream(Stream*str, int len)
1537     {
1538         buf = 0;
1539         str->reset();
1540         if(len) {
1541             buf = (char*)malloc(len);
1542             int t;
1543             for (t=0; t<len; t++)
1544               buf[t] = str->getChar();
1545         }
1546         str->close();
1547         this->dict = str->getDict();
1548         this->memstream = new MemStream(buf, 0, len, this);
1549     }
1550     ~CopyStream() 
1551     {
1552         ::free(this->buf);this->buf = 0;
1553         delete this->memstream;
1554     }
1555     Dict* getDict() {return dict;}
1556     Stream* getStream() {return this->memstream;};
1557 };
1558
1559 gfxbbox_t BitmapOutputDev::getImageBBox(GfxState*state)
1560 {
1561     gfxbbox_t bbox;
1562     double x,y;
1563     state->transform(0, 1, &x, &y);
1564     bbox.xmin=bbox.xmax = x;
1565     bbox.ymin=bbox.ymax = x;
1566     state->transform(0, 0, &x, &y);
1567     bbox.xmin=min(bbox.xmin,x);
1568     bbox.ymin=min(bbox.ymin,y);
1569     bbox.xmax=max(bbox.xmin,x);
1570     bbox.ymax=max(bbox.ymin,y);
1571     state->transform(1, 0, &x, &y);
1572     bbox.xmin=min(bbox.xmin,x);
1573     bbox.ymin=min(bbox.ymin,y);
1574     bbox.xmax=max(bbox.xmin,x);
1575     bbox.ymax=max(bbox.ymin,y);
1576     state->transform(1, 1, &x, &y);
1577     bbox.xmin=min(bbox.xmin,x);
1578     bbox.ymin=min(bbox.ymin,y);
1579     bbox.xmax=max(bbox.xmin,x);
1580     bbox.ymax=max(bbox.ymin,y);
1581     return bbox;
1582 }
1583 void BitmapOutputDev::drawImageMask(GfxState *state, Object *ref, Stream *str,
1584                            int width, int height, GBool invert,
1585                            GBool inlineImg)
1586 {
1587     msg("<debug> drawImageMask streamkind=%d", str->getKind());
1588     CopyStream*cpystr = 0;
1589     if(inlineImg) {
1590         cpystr = new CopyStream(str, height * ((width + 7) / 8));
1591         str = cpystr->getStream();
1592     }
1593     boolpolydev->drawImageMask(state, ref, str, width, height, invert, inlineImg);
1594     gfxbbox_t bbox = getImageBBox(state);
1595     checkNewBitmap(bbox.xmin, bbox.ymin, ceil(bbox.xmax), ceil(bbox.ymax));
1596     rgbdev->drawImageMask(state, ref, str, width, height, invert, inlineImg);
1597     if(cpystr)
1598         delete cpystr;
1599 }
1600 void BitmapOutputDev::drawImage(GfxState *state, Object *ref, Stream *str,
1601                        int width, int height, GfxImageColorMap *colorMap,
1602                        int *maskColors, GBool inlineImg)
1603 {
1604     msg("<debug> drawImage streamkind=%d", str->getKind());
1605     CopyStream*cpystr = 0;
1606     if(inlineImg) {
1607         cpystr = new CopyStream(str, height * ((width * colorMap->getNumPixelComps() * colorMap->getBits() + 7) / 8));
1608         str = cpystr->getStream();
1609     }
1610     boolpolydev->drawImage(state, ref, str, width, height, colorMap, maskColors, inlineImg);
1611     gfxbbox_t bbox=getImageBBox(state);
1612     checkNewBitmap(bbox.xmin, bbox.ymin, ceil(bbox.xmax), ceil(bbox.ymax));
1613     rgbdev->drawImage(state, ref, str, width, height, colorMap, maskColors, inlineImg);
1614     if(cpystr)
1615         delete cpystr;
1616 }
1617 void BitmapOutputDev::drawMaskedImage(GfxState *state, Object *ref, Stream *str,
1618                              int width, int height,
1619                              GfxImageColorMap *colorMap,
1620                              Stream *maskStr, int maskWidth, int maskHeight,
1621                              GBool maskInvert)
1622 {
1623     msg("<debug> drawMaskedImage streamkind=%d", str->getKind());
1624     boolpolydev->drawMaskedImage(state, ref, str, width, height, colorMap, maskStr, maskWidth, maskHeight, maskInvert);
1625     gfxbbox_t bbox=getImageBBox(state);
1626     checkNewBitmap(bbox.xmin, bbox.ymin, ceil(bbox.xmax), ceil(bbox.ymax));
1627     rgbdev->drawMaskedImage(state, ref, str, width, height, colorMap, maskStr, maskWidth, maskHeight, maskInvert);
1628 }
1629 void BitmapOutputDev::drawSoftMaskedImage(GfxState *state, Object *ref, Stream *str,
1630                                  int width, int height,
1631                                  GfxImageColorMap *colorMap,
1632                                  Stream *maskStr,
1633                                  int maskWidth, int maskHeight,
1634                                  GfxImageColorMap *maskColorMap)
1635 {
1636     msg("<debug> drawSoftMaskedImage %dx%d (%dx%d) streamkind=%d", width, height, maskWidth, maskHeight, str->getKind());
1637     boolpolydev->drawSoftMaskedImage(state, ref, str, width, height, colorMap, maskStr, maskWidth, maskHeight, maskColorMap);
1638     gfxbbox_t bbox=getImageBBox(state);
1639     checkNewBitmap(bbox.xmin, bbox.ymin, ceil(bbox.xmax), ceil(bbox.ymax));
1640     rgbdev->drawSoftMaskedImage(state, ref, str, width, height, colorMap, maskStr, maskWidth, maskHeight, maskColorMap);
1641 }
1642 void BitmapOutputDev::drawForm(Ref id)
1643 {
1644     msg("<debug> drawForm");
1645     boolpolydev->drawForm(id);
1646     checkNewBitmap(UNKNOWN_BOUNDING_BOX);
1647     rgbdev->drawForm(id);
1648 }
1649
1650 void BitmapOutputDev::processLink(Link *link, Catalog *catalog)
1651 {
1652     msg("<debug> processLink");
1653     gfxdev->processLink(link, catalog);
1654 }
1655
1656 void BitmapOutputDev::beginTransparencyGroup(GfxState *state, double *bbox,
1657                                     GfxColorSpace *blendingColorSpace,
1658                                     GBool isolated, GBool knockout,
1659                                     GBool forSoftMask)
1660 {
1661     msg("<debug> beginTransparencyGroup");
1662 #if (xpdfMajorVersion*10000 + xpdfMinorVersion*100 + xpdfUpdateVersion) < 30207
1663     GfxState*state1 = state->copy();
1664     GfxState*state2 = state->copy();
1665     state1->setPath(0);
1666     state1->setPath(state->getPath()->copy());
1667     state2->setPath(0);
1668     state2->setPath(state->getPath()->copy());
1669 #else
1670     GfxState*state1 = state->copy(gTrue);
1671     GfxState*state2 = state->copy(gTrue);
1672 #endif
1673     boolpolydev->beginTransparencyGroup(state1, bbox, blendingColorSpace, isolated, knockout, forSoftMask);
1674     rgbdev->beginTransparencyGroup(state2, bbox, blendingColorSpace, isolated, knockout, forSoftMask);
1675     clip1dev->beginTransparencyGroup(state, bbox, blendingColorSpace, isolated, knockout, forSoftMask);
1676     delete state1;
1677     delete state2;
1678 }
1679 void BitmapOutputDev::endTransparencyGroup(GfxState *state)
1680 {
1681     msg("<debug> endTransparencyGroup");
1682 #if (xpdfMajorVersion*10000 + xpdfMinorVersion*100 + xpdfUpdateVersion) < 30207
1683     GfxState*state1 = state->copy();
1684     GfxState*state2 = state->copy();
1685     state1->setPath(0);
1686     state1->setPath(state->getPath()->copy());
1687     state2->setPath(0);
1688     state2->setPath(state->getPath()->copy());
1689 #else
1690     GfxState*state1 = state->copy(gTrue);
1691     GfxState*state2 = state->copy(gTrue);
1692 #endif
1693     boolpolydev->endTransparencyGroup(state1);
1694     checkNewBitmap(UNKNOWN_BOUNDING_BOX);
1695     rgbdev->endTransparencyGroup(state2);
1696     delete state1;
1697     delete state2;
1698     clip1dev->endTransparencyGroup(state);
1699 }
1700 void BitmapOutputDev::paintTransparencyGroup(GfxState *state, double *bbox)
1701 {
1702     msg("<debug> paintTransparencyGroup");
1703     boolpolydev->paintTransparencyGroup(state,bbox);
1704     checkNewBitmap(UNKNOWN_BOUNDING_BOX);
1705     rgbdev->paintTransparencyGroup(state,bbox);
1706     clip1dev->paintTransparencyGroup(state,bbox);
1707 }
1708 void BitmapOutputDev::setSoftMask(GfxState *state, double *bbox, GBool alpha, Function *transferFunc, GfxColor *backdropColor)
1709 {
1710     msg("<debug> setSoftMask");
1711     boolpolydev->setSoftMask(state, bbox, alpha, transferFunc, backdropColor);
1712     checkNewBitmap(UNKNOWN_BOUNDING_BOX);
1713     rgbdev->setSoftMask(state, bbox, alpha, transferFunc, backdropColor);
1714     clip1dev->setSoftMask(state, bbox, alpha, transferFunc, backdropColor);
1715 }
1716 void BitmapOutputDev::clearSoftMask(GfxState *state)
1717 {
1718     msg("<debug> clearSoftMask");
1719     boolpolydev->clearSoftMask(state);
1720     checkNewBitmap(UNKNOWN_BOUNDING_BOX);
1721     rgbdev->clearSoftMask(state);
1722     clip1dev->clearSoftMask(state);
1723 }