]> www.fi.muni.cz Git - evince.git/blob - pdf/xpdf/Gfx.cc
Imported Xpdf 2.03 and fixed build.
[evince.git] / pdf / xpdf / Gfx.cc
1 //========================================================================
2 //
3 // Gfx.cc
4 //
5 // Copyright 1996-2003 Glyph & Cog, LLC
6 //
7 //========================================================================
8
9 #include <aconf.h>
10
11 #ifdef USE_GCC_PRAGMAS
12 #pragma implementation
13 #endif
14
15 #include <stdio.h>
16 #include <stddef.h>
17 #include <string.h>
18 #include <math.h>
19 #include "gmem.h"
20 #include "GlobalParams.h"
21 #include "CharTypes.h"
22 #include "Object.h"
23 #include "Array.h"
24 #include "Dict.h"
25 #include "Stream.h"
26 #include "Lexer.h"
27 #include "Parser.h"
28 #include "GfxFont.h"
29 #include "GfxState.h"
30 #include "OutputDev.h"
31 #include "Page.h"
32 #include "Error.h"
33 #include "Gfx.h"
34
35 // the MSVC math.h doesn't define this
36 #ifndef M_PI
37 #define M_PI 3.14159265358979323846
38 #endif
39
40 //------------------------------------------------------------------------
41 // constants
42 //------------------------------------------------------------------------
43
44 // Max recursive depth for a function shading fill.
45 #define functionMaxDepth 6
46
47 // Max delta allowed in any color component for a function shading fill.
48 #define functionColorDelta (1 / 256.0)
49
50 // Max number of splits along the t axis for an axial shading fill.
51 #define axialMaxSplits 256
52
53 // Max delta allowed in any color component for an axial shading fill.
54 #define axialColorDelta (1 / 256.0)
55
56 // Max number of splits along the t axis for a radial shading fill.
57 #define radialMaxSplits 256
58
59 // Max delta allowed in any color component for a radial shading fill.
60 #define radialColorDelta (1 / 256.0)
61
62 //------------------------------------------------------------------------
63 // Operator table
64 //------------------------------------------------------------------------
65
66 #ifdef WIN32 // this works around a bug in the VC7 compiler
67 #  pragma optimize("",off)
68 #endif
69
70 Operator Gfx::opTab[] = {
71   {"\"",  3, {tchkNum,    tchkNum,    tchkString},
72           &Gfx::opMoveSetShowText},
73   {"'",   1, {tchkString},
74           &Gfx::opMoveShowText},
75   {"B",   0, {tchkNone},
76           &Gfx::opFillStroke},
77   {"B*",  0, {tchkNone},
78           &Gfx::opEOFillStroke},
79   {"BDC", 2, {tchkName,   tchkProps},
80           &Gfx::opBeginMarkedContent},
81   {"BI",  0, {tchkNone},
82           &Gfx::opBeginImage},
83   {"BMC", 1, {tchkName},
84           &Gfx::opBeginMarkedContent},
85   {"BT",  0, {tchkNone},
86           &Gfx::opBeginText},
87   {"BX",  0, {tchkNone},
88           &Gfx::opBeginIgnoreUndef},
89   {"CS",  1, {tchkName},
90           &Gfx::opSetStrokeColorSpace},
91   {"DP",  2, {tchkName,   tchkProps},
92           &Gfx::opMarkPoint},
93   {"Do",  1, {tchkName},
94           &Gfx::opXObject},
95   {"EI",  0, {tchkNone},
96           &Gfx::opEndImage},
97   {"EMC", 0, {tchkNone},
98           &Gfx::opEndMarkedContent},
99   {"ET",  0, {tchkNone},
100           &Gfx::opEndText},
101   {"EX",  0, {tchkNone},
102           &Gfx::opEndIgnoreUndef},
103   {"F",   0, {tchkNone},
104           &Gfx::opFill},
105   {"G",   1, {tchkNum},
106           &Gfx::opSetStrokeGray},
107   {"ID",  0, {tchkNone},
108           &Gfx::opImageData},
109   {"J",   1, {tchkInt},
110           &Gfx::opSetLineCap},
111   {"K",   4, {tchkNum,    tchkNum,    tchkNum,    tchkNum},
112           &Gfx::opSetStrokeCMYKColor},
113   {"M",   1, {tchkNum},
114           &Gfx::opSetMiterLimit},
115   {"MP",  1, {tchkName},
116           &Gfx::opMarkPoint},
117   {"Q",   0, {tchkNone},
118           &Gfx::opRestore},
119   {"RG",  3, {tchkNum,    tchkNum,    tchkNum},
120           &Gfx::opSetStrokeRGBColor},
121   {"S",   0, {tchkNone},
122           &Gfx::opStroke},
123   {"SC",  -4, {tchkNum,   tchkNum,    tchkNum,    tchkNum},
124           &Gfx::opSetStrokeColor},
125   {"SCN", -5, {tchkSCN,   tchkSCN,    tchkSCN,    tchkSCN,
126                tchkSCN},
127           &Gfx::opSetStrokeColorN},
128   {"T*",  0, {tchkNone},
129           &Gfx::opTextNextLine},
130   {"TD",  2, {tchkNum,    tchkNum},
131           &Gfx::opTextMoveSet},
132   {"TJ",  1, {tchkArray},
133           &Gfx::opShowSpaceText},
134   {"TL",  1, {tchkNum},
135           &Gfx::opSetTextLeading},
136   {"Tc",  1, {tchkNum},
137           &Gfx::opSetCharSpacing},
138   {"Td",  2, {tchkNum,    tchkNum},
139           &Gfx::opTextMove},
140   {"Tf",  2, {tchkName,   tchkNum},
141           &Gfx::opSetFont},
142   {"Tj",  1, {tchkString},
143           &Gfx::opShowText},
144   {"Tm",  6, {tchkNum,    tchkNum,    tchkNum,    tchkNum,
145               tchkNum,    tchkNum},
146           &Gfx::opSetTextMatrix},
147   {"Tr",  1, {tchkInt},
148           &Gfx::opSetTextRender},
149   {"Ts",  1, {tchkNum},
150           &Gfx::opSetTextRise},
151   {"Tw",  1, {tchkNum},
152           &Gfx::opSetWordSpacing},
153   {"Tz",  1, {tchkNum},
154           &Gfx::opSetHorizScaling},
155   {"W",   0, {tchkNone},
156           &Gfx::opClip},
157   {"W*",  0, {tchkNone},
158           &Gfx::opEOClip},
159   {"b",   0, {tchkNone},
160           &Gfx::opCloseFillStroke},
161   {"b*",  0, {tchkNone},
162           &Gfx::opCloseEOFillStroke},
163   {"c",   6, {tchkNum,    tchkNum,    tchkNum,    tchkNum,
164               tchkNum,    tchkNum},
165           &Gfx::opCurveTo},
166   {"cm",  6, {tchkNum,    tchkNum,    tchkNum,    tchkNum,
167               tchkNum,    tchkNum},
168           &Gfx::opConcat},
169   {"cs",  1, {tchkName},
170           &Gfx::opSetFillColorSpace},
171   {"d",   2, {tchkArray,  tchkNum},
172           &Gfx::opSetDash},
173   {"d0",  2, {tchkNum,    tchkNum},
174           &Gfx::opSetCharWidth},
175   {"d1",  6, {tchkNum,    tchkNum,    tchkNum,    tchkNum,
176               tchkNum,    tchkNum},
177           &Gfx::opSetCacheDevice},
178   {"f",   0, {tchkNone},
179           &Gfx::opFill},
180   {"f*",  0, {tchkNone},
181           &Gfx::opEOFill},
182   {"g",   1, {tchkNum},
183           &Gfx::opSetFillGray},
184   {"gs",  1, {tchkName},
185           &Gfx::opSetExtGState},
186   {"h",   0, {tchkNone},
187           &Gfx::opClosePath},
188   {"i",   1, {tchkNum},
189           &Gfx::opSetFlat},
190   {"j",   1, {tchkInt},
191           &Gfx::opSetLineJoin},
192   {"k",   4, {tchkNum,    tchkNum,    tchkNum,    tchkNum},
193           &Gfx::opSetFillCMYKColor},
194   {"l",   2, {tchkNum,    tchkNum},
195           &Gfx::opLineTo},
196   {"m",   2, {tchkNum,    tchkNum},
197           &Gfx::opMoveTo},
198   {"n",   0, {tchkNone},
199           &Gfx::opEndPath},
200   {"q",   0, {tchkNone},
201           &Gfx::opSave},
202   {"re",  4, {tchkNum,    tchkNum,    tchkNum,    tchkNum},
203           &Gfx::opRectangle},
204   {"rg",  3, {tchkNum,    tchkNum,    tchkNum},
205           &Gfx::opSetFillRGBColor},
206   {"ri",  1, {tchkName},
207           &Gfx::opSetRenderingIntent},
208   {"s",   0, {tchkNone},
209           &Gfx::opCloseStroke},
210   {"sc",  -4, {tchkNum,   tchkNum,    tchkNum,    tchkNum},
211           &Gfx::opSetFillColor},
212   {"scn", -5, {tchkSCN,   tchkSCN,    tchkSCN,    tchkSCN,
213                tchkSCN},
214           &Gfx::opSetFillColorN},
215   {"sh",  1, {tchkName},
216           &Gfx::opShFill},
217   {"v",   4, {tchkNum,    tchkNum,    tchkNum,    tchkNum},
218           &Gfx::opCurveTo1},
219   {"w",   1, {tchkNum},
220           &Gfx::opSetLineWidth},
221   {"y",   4, {tchkNum,    tchkNum,    tchkNum,    tchkNum},
222           &Gfx::opCurveTo2},
223 };
224
225 #ifdef WIN32 // this works around a bug in the VC7 compiler
226 #  pragma optimize("",on)
227 #endif
228
229 #define numOps (sizeof(opTab) / sizeof(Operator))
230
231 //------------------------------------------------------------------------
232 // GfxResources
233 //------------------------------------------------------------------------
234
235 GfxResources::GfxResources(XRef *xref, Dict *resDict, GfxResources *nextA) {
236   Object obj1, obj2;
237   Ref r;
238
239   if (resDict) {
240
241     // build font dictionary
242     fonts = NULL;
243     resDict->lookupNF("Font", &obj1);
244     if (obj1.isRef()) {
245       obj1.fetch(xref, &obj2);
246       if (obj2.isDict()) {
247         r = obj1.getRef();
248         fonts = new GfxFontDict(xref, &r, obj2.getDict());
249       }
250       obj2.free();
251     } else if (obj1.isDict()) {
252       fonts = new GfxFontDict(xref, NULL, obj1.getDict());
253     }
254     obj1.free();
255
256     // get XObject dictionary
257     resDict->lookup("XObject", &xObjDict);
258
259     // get color space dictionary
260     resDict->lookup("ColorSpace", &colorSpaceDict);
261
262     // get pattern dictionary
263     resDict->lookup("Pattern", &patternDict);
264
265     // get shading dictionary
266     resDict->lookup("Shading", &shadingDict);
267
268     // get graphics state parameter dictionary
269     resDict->lookup("ExtGState", &gStateDict);
270
271   } else {
272     fonts = NULL;
273     xObjDict.initNull();
274     colorSpaceDict.initNull();
275     patternDict.initNull();
276     shadingDict.initNull();
277     gStateDict.initNull();
278   }
279
280   next = nextA;
281 }
282
283 GfxResources::~GfxResources() {
284   if (fonts) {
285     delete fonts;
286   }
287   xObjDict.free();
288   colorSpaceDict.free();
289   patternDict.free();
290   shadingDict.free();
291   gStateDict.free();
292 }
293
294 GfxFont *GfxResources::lookupFont(char *name) {
295   GfxFont *font;
296   GfxResources *resPtr;
297
298   for (resPtr = this; resPtr; resPtr = resPtr->next) {
299     if (resPtr->fonts) {
300       if ((font = resPtr->fonts->lookup(name)))
301         return font;
302     }
303   }
304   error(-1, "Unknown font tag '%s'", name);
305   return NULL;
306 }
307
308 GBool GfxResources::lookupXObject(char *name, Object *obj) {
309   GfxResources *resPtr;
310
311   for (resPtr = this; resPtr; resPtr = resPtr->next) {
312     if (resPtr->xObjDict.isDict()) {
313       if (!resPtr->xObjDict.dictLookup(name, obj)->isNull())
314         return gTrue;
315       obj->free();
316     }
317   }
318   error(-1, "XObject '%s' is unknown", name);
319   return gFalse;
320 }
321
322 GBool GfxResources::lookupXObjectNF(char *name, Object *obj) {
323   GfxResources *resPtr;
324
325   for (resPtr = this; resPtr; resPtr = resPtr->next) {
326     if (resPtr->xObjDict.isDict()) {
327       if (!resPtr->xObjDict.dictLookupNF(name, obj)->isNull())
328         return gTrue;
329       obj->free();
330     }
331   }
332   error(-1, "XObject '%s' is unknown", name);
333   return gFalse;
334 }
335
336 void GfxResources::lookupColorSpace(char *name, Object *obj) {
337   GfxResources *resPtr;
338
339   for (resPtr = this; resPtr; resPtr = resPtr->next) {
340     if (resPtr->colorSpaceDict.isDict()) {
341       if (!resPtr->colorSpaceDict.dictLookup(name, obj)->isNull()) {
342         return;
343       }
344       obj->free();
345     }
346   }
347   obj->initNull();
348 }
349
350 GfxPattern *GfxResources::lookupPattern(char *name) {
351   GfxResources *resPtr;
352   GfxPattern *pattern;
353   Object obj;
354
355   for (resPtr = this; resPtr; resPtr = resPtr->next) {
356     if (resPtr->patternDict.isDict()) {
357       if (!resPtr->patternDict.dictLookup(name, &obj)->isNull()) {
358         pattern = GfxPattern::parse(&obj);
359         obj.free();
360         return pattern;
361       }
362       obj.free();
363     }
364   }
365   error(-1, "Unknown pattern '%s'", name);
366   return NULL;
367 }
368
369 GfxShading *GfxResources::lookupShading(char *name) {
370   GfxResources *resPtr;
371   GfxShading *shading;
372   Object obj;
373
374   for (resPtr = this; resPtr; resPtr = resPtr->next) {
375     if (resPtr->shadingDict.isDict()) {
376       if (!resPtr->shadingDict.dictLookup(name, &obj)->isNull()) {
377         shading = GfxShading::parse(&obj);
378         obj.free();
379         return shading;
380       }
381       obj.free();
382     }
383   }
384   error(-1, "Unknown shading '%s'", name);
385   return NULL;
386 }
387
388 GBool GfxResources::lookupGState(char *name, Object *obj) {
389   GfxResources *resPtr;
390
391   for (resPtr = this; resPtr; resPtr = resPtr->next) {
392     if (resPtr->gStateDict.isDict()) {
393       if (!resPtr->gStateDict.dictLookup(name, obj)->isNull()) {
394         return gTrue;
395       }
396       obj->free();
397     }
398   }
399   error(-1, "ExtGState '%s' is unknown", name);
400   return gFalse;
401 }
402
403 //------------------------------------------------------------------------
404 // Gfx
405 //------------------------------------------------------------------------
406
407 Gfx::Gfx(XRef *xrefA, OutputDev *outA, int pageNum, Dict *resDict,
408          double hDPI, double vDPI, PDFRectangle *box, GBool crop,
409          PDFRectangle *cropBox, int rotate,
410          GBool (*abortCheckCbkA)(void *data),
411          void *abortCheckCbkDataA) {
412   int i;
413
414   xref = xrefA;
415   subPage = gFalse;
416   printCommands = globalParams->getPrintCommands();
417
418   // start the resource stack
419   res = new GfxResources(xref, resDict, NULL);
420
421   // initialize
422   out = outA;
423   state = new GfxState(hDPI, vDPI, box, rotate, out->upsideDown());
424   fontChanged = gFalse;
425   clip = clipNone;
426   ignoreUndef = 0;
427   out->startPage(pageNum, state);
428   out->setDefaultCTM(state->getCTM());
429   out->updateAll(state);
430   for (i = 0; i < 6; ++i) {
431     baseMatrix[i] = state->getCTM()[i];
432   }
433   formDepth = 0;
434   abortCheckCbk = abortCheckCbkA;
435   abortCheckCbkData = abortCheckCbkDataA;
436
437   // set crop box
438   if (crop) {
439     state->moveTo(cropBox->x1, cropBox->y1);
440     state->lineTo(cropBox->x2, cropBox->y1);
441     state->lineTo(cropBox->x2, cropBox->y2);
442     state->lineTo(cropBox->x1, cropBox->y2);
443     state->closePath();
444     state->clip();
445     out->clip(state);
446     state->clearPath();
447   }
448 }
449
450 Gfx::Gfx(XRef *xrefA, OutputDev *outA, Dict *resDict,
451          PDFRectangle *box, GBool crop, PDFRectangle *cropBox,
452          GBool (*abortCheckCbkA)(void *data),
453          void *abortCheckCbkDataA) {
454   int i;
455
456   xref = xrefA;
457   subPage = gTrue;
458   printCommands = globalParams->getPrintCommands();
459
460   // start the resource stack
461   res = new GfxResources(xref, resDict, NULL);
462
463   // initialize
464   out = outA;
465   state = new GfxState(72, 72, box, 0, gFalse);
466   fontChanged = gFalse;
467   clip = clipNone;
468   ignoreUndef = 0;
469   for (i = 0; i < 6; ++i) {
470     baseMatrix[i] = state->getCTM()[i];
471   }
472   formDepth = 0;
473   abortCheckCbk = abortCheckCbkA;
474   abortCheckCbkData = abortCheckCbkDataA;
475
476   // set crop box
477   if (crop) {
478     state->moveTo(cropBox->x1, cropBox->y1);
479     state->lineTo(cropBox->x2, cropBox->y1);
480     state->lineTo(cropBox->x2, cropBox->y2);
481     state->lineTo(cropBox->x1, cropBox->y2);
482     state->closePath();
483     state->clip();
484     out->clip(state);
485     state->clearPath();
486   }
487 }
488
489 Gfx::~Gfx() {
490   while (state->hasSaves()) {
491     restoreState();
492   }
493   if (!subPage) {
494     out->endPage();
495   }
496   while (res) {
497     popResources();
498   }
499   if (state) {
500     delete state;
501   }
502 }
503
504 void Gfx::display(Object *obj, GBool topLevel) {
505   Object obj2;
506   int i;
507
508   if (obj->isArray()) {
509     for (i = 0; i < obj->arrayGetLength(); ++i) {
510       obj->arrayGet(i, &obj2);
511       if (!obj2.isStream()) {
512         error(-1, "Weird page contents");
513         obj2.free();
514         return;
515       }
516       obj2.free();
517     }
518   } else if (!obj->isStream()) {
519     error(-1, "Weird page contents");
520     return;
521   }
522   parser = new Parser(xref, new Lexer(xref, obj));
523   go(topLevel);
524   delete parser;
525   parser = NULL;
526 }
527
528 void Gfx::go(GBool topLevel) {
529   Object obj;
530   Object args[maxArgs];
531   int numArgs, i;
532   int lastAbortCheck;
533
534   // scan a sequence of objects
535   updateLevel = lastAbortCheck = 0;
536   numArgs = 0;
537   parser->getObj(&obj);
538   while (!obj.isEOF()) {
539
540     // got a command - execute it
541     if (obj.isCmd()) {
542       if (printCommands) {
543         obj.print(stdout);
544         for (i = 0; i < numArgs; ++i) {
545           printf(" ");
546           args[i].print(stdout);
547         }
548         printf("\n");
549         fflush(stdout);
550       }
551       execOp(&obj, args, numArgs);
552       obj.free();
553       for (i = 0; i < numArgs; ++i)
554         args[i].free();
555       numArgs = 0;
556
557       // periodically update display
558       if (++updateLevel >= 20000) {
559         out->dump();
560         updateLevel = 0;
561       }
562
563       // check for an abort
564       if (abortCheckCbk) {
565         if (updateLevel - lastAbortCheck > 10) {
566           if ((*abortCheckCbk)(abortCheckCbkData)) {
567             break;
568           }
569           lastAbortCheck = updateLevel;
570         }
571       }
572
573     // got an argument - save it
574     } else if (numArgs < maxArgs) {
575       args[numArgs++] = obj;
576
577     // too many arguments - something is wrong
578     } else {
579       error(getPos(), "Too many args in content stream");
580       if (printCommands) {
581         printf("throwing away arg: ");
582         obj.print(stdout);
583         printf("\n");
584         fflush(stdout);
585       }
586       obj.free();
587     }
588
589     // grab the next object
590     parser->getObj(&obj);
591   }
592   obj.free();
593
594   // args at end with no command
595   if (numArgs > 0) {
596     error(getPos(), "Leftover args in content stream");
597     if (printCommands) {
598       printf("%d leftovers:", numArgs);
599       for (i = 0; i < numArgs; ++i) {
600         printf(" ");
601         args[i].print(stdout);
602       }
603       printf("\n");
604       fflush(stdout);
605     }
606     for (i = 0; i < numArgs; ++i)
607       args[i].free();
608   }
609
610   // update display
611   if (topLevel && updateLevel > 0) {
612     out->dump();
613   }
614 }
615
616 void Gfx::execOp(Object *cmd, Object args[], int numArgs) {
617   Operator *op;
618   char *name;
619   Object *argPtr;
620   int i;
621
622   // find operator
623   name = cmd->getCmd();
624   if (!(op = findOp(name))) {
625     if (ignoreUndef == 0)
626       error(getPos(), "Unknown operator '%s'", name);
627     return;
628   }
629
630   // type check args
631   argPtr = args;
632   if (op->numArgs >= 0) {
633     if (numArgs < op->numArgs) {
634       error(getPos(), "Too few (%d) args to '%s' operator", numArgs, name);
635       return;
636     }
637     if (numArgs > op->numArgs) {
638 #if 0
639       error(getPos(), "Too many (%d) args to '%s' operator", numArgs, name);
640 #endif
641       argPtr += numArgs - op->numArgs;
642       numArgs = op->numArgs;
643     }
644   } else {
645     if (numArgs > -op->numArgs) {
646       error(getPos(), "Too many (%d) args to '%s' operator",
647             numArgs, name);
648       return;
649     }
650   }
651   for (i = 0; i < numArgs; ++i) {
652     if (!checkArg(&argPtr[i], op->tchk[i])) {
653       error(getPos(), "Arg #%d to '%s' operator is wrong type (%s)",
654             i, name, argPtr[i].getTypeName());
655       return;
656     }
657   }
658
659   // do it
660   (this->*op->func)(argPtr, numArgs);
661 }
662
663 Operator *Gfx::findOp(char *name) {
664   int a, b, m, cmp;
665
666   a = -1;
667   b = numOps;
668   // invariant: opTab[a] < name < opTab[b]
669   while (b - a > 1) {
670     m = (a + b) / 2;
671     cmp = strcmp(opTab[m].name, name);
672     if (cmp < 0)
673       a = m;
674     else if (cmp > 0)
675       b = m;
676     else
677       a = b = m;
678   }
679   if (cmp != 0)
680     return NULL;
681   return &opTab[a];
682 }
683
684 GBool Gfx::checkArg(Object *arg, TchkType type) {
685   switch (type) {
686   case tchkBool:   return arg->isBool();
687   case tchkInt:    return arg->isInt();
688   case tchkNum:    return arg->isNum();
689   case tchkString: return arg->isString();
690   case tchkName:   return arg->isName();
691   case tchkArray:  return arg->isArray();
692   case tchkProps:  return arg->isDict() || arg->isName();
693   case tchkSCN:    return arg->isNum() || arg->isName();
694   case tchkNone:   return gFalse;
695   }
696   return gFalse;
697 }
698
699 int Gfx::getPos() {
700   return parser ? parser->getPos() : -1;
701 }
702
703 //------------------------------------------------------------------------
704 // graphics state operators
705 //------------------------------------------------------------------------
706
707 void Gfx::opSave(Object args[], int numArgs) {
708   saveState();
709 }
710
711 void Gfx::opRestore(Object args[], int numArgs) {
712   restoreState();
713 }
714
715 void Gfx::opConcat(Object args[], int numArgs) {
716   state->concatCTM(args[0].getNum(), args[1].getNum(),
717                    args[2].getNum(), args[3].getNum(),
718                    args[4].getNum(), args[5].getNum());
719   out->updateCTM(state, args[0].getNum(), args[1].getNum(),
720                  args[2].getNum(), args[3].getNum(),
721                  args[4].getNum(), args[5].getNum());
722   fontChanged = gTrue;
723 }
724
725 void Gfx::opSetDash(Object args[], int numArgs) {
726   Array *a;
727   int length;
728   Object obj;
729   double *dash;
730   int i;
731
732   a = args[0].getArray();
733   length = a->getLength();
734   if (length == 0) {
735     dash = NULL;
736   } else {
737     dash = (double *)gmalloc(length * sizeof(double));
738     for (i = 0; i < length; ++i) {
739       dash[i] = a->get(i, &obj)->getNum();
740       obj.free();
741     }
742   }
743   state->setLineDash(dash, length, args[1].getNum());
744   out->updateLineDash(state);
745 }
746
747 void Gfx::opSetFlat(Object args[], int numArgs) {
748   state->setFlatness((int)args[0].getNum());
749   out->updateFlatness(state);
750 }
751
752 void Gfx::opSetLineJoin(Object args[], int numArgs) {
753   state->setLineJoin(args[0].getInt());
754   out->updateLineJoin(state);
755 }
756
757 void Gfx::opSetLineCap(Object args[], int numArgs) {
758   state->setLineCap(args[0].getInt());
759   out->updateLineCap(state);
760 }
761
762 void Gfx::opSetMiterLimit(Object args[], int numArgs) {
763   state->setMiterLimit(args[0].getNum());
764   out->updateMiterLimit(state);
765 }
766
767 void Gfx::opSetLineWidth(Object args[], int numArgs) {
768   state->setLineWidth(args[0].getNum());
769   out->updateLineWidth(state);
770 }
771
772 void Gfx::opSetExtGState(Object args[], int numArgs) {
773   Object obj1, obj2;
774
775   if (!res->lookupGState(args[0].getName(), &obj1)) {
776     return;
777   }
778   if (!obj1.isDict()) {
779     error(getPos(), "ExtGState '%s' is wrong type", args[0].getName());
780     obj1.free();
781     return;
782   }
783   if (obj1.dictLookup("ca", &obj2)->isNum()) {
784     state->setFillOpacity(obj2.getNum());
785     out->updateFillOpacity(state);
786   }
787   obj2.free();
788   if (obj1.dictLookup("CA", &obj2)->isNum()) {
789     state->setStrokeOpacity(obj2.getNum());
790     out->updateStrokeOpacity(state);
791   }
792   obj2.free();
793   obj1.free();
794 }
795
796 void Gfx::opSetRenderingIntent(Object args[], int numArgs) {
797 }
798
799 //------------------------------------------------------------------------
800 // color operators
801 //------------------------------------------------------------------------
802
803 void Gfx::opSetFillGray(Object args[], int numArgs) {
804   GfxColor color;
805
806   state->setFillPattern(NULL);
807   state->setFillColorSpace(new GfxDeviceGrayColorSpace());
808   color.c[0] = args[0].getNum();
809   state->setFillColor(&color);
810   out->updateFillColor(state);
811 }
812
813 void Gfx::opSetStrokeGray(Object args[], int numArgs) {
814   GfxColor color;
815
816   state->setStrokePattern(NULL);
817   state->setStrokeColorSpace(new GfxDeviceGrayColorSpace());
818   color.c[0] = args[0].getNum();
819   state->setStrokeColor(&color);
820   out->updateStrokeColor(state);
821 }
822
823 void Gfx::opSetFillCMYKColor(Object args[], int numArgs) {
824   GfxColor color;
825   int i;
826
827   state->setFillPattern(NULL);
828   state->setFillColorSpace(new GfxDeviceCMYKColorSpace());
829   for (i = 0; i < 4; ++i) {
830     color.c[i] = args[i].getNum();
831   }
832   state->setFillColor(&color);
833   out->updateFillColor(state);
834 }
835
836 void Gfx::opSetStrokeCMYKColor(Object args[], int numArgs) {
837   GfxColor color;
838   int i;
839
840   state->setStrokePattern(NULL);
841   state->setStrokeColorSpace(new GfxDeviceCMYKColorSpace());
842   for (i = 0; i < 4; ++i) {
843     color.c[i] = args[i].getNum();
844   }
845   state->setStrokeColor(&color);
846   out->updateStrokeColor(state);
847 }
848
849 void Gfx::opSetFillRGBColor(Object args[], int numArgs) {
850   GfxColor color;
851   int i;
852
853   state->setFillPattern(NULL);
854   state->setFillColorSpace(new GfxDeviceRGBColorSpace());
855   for (i = 0; i < 3; ++i) {
856     color.c[i] = args[i].getNum();
857   }
858   state->setFillColor(&color);
859   out->updateFillColor(state);
860 }
861
862 void Gfx::opSetStrokeRGBColor(Object args[], int numArgs) {
863   GfxColor color;
864   int i;
865
866   state->setStrokePattern(NULL);
867   state->setStrokeColorSpace(new GfxDeviceRGBColorSpace());
868   for (i = 0; i < 3; ++i) {
869     color.c[i] = args[i].getNum();
870   }
871   state->setStrokeColor(&color);
872   out->updateStrokeColor(state);
873 }
874
875 void Gfx::opSetFillColorSpace(Object args[], int numArgs) {
876   Object obj;
877   GfxColorSpace *colorSpace;
878   GfxColor color;
879   int i;
880
881   state->setFillPattern(NULL);
882   res->lookupColorSpace(args[0].getName(), &obj);
883   if (obj.isNull()) {
884     colorSpace = GfxColorSpace::parse(&args[0]);
885   } else {
886     colorSpace = GfxColorSpace::parse(&obj);
887   }
888   obj.free();
889   if (colorSpace) {
890     state->setFillColorSpace(colorSpace);
891   } else {
892     error(getPos(), "Bad color space (fill)");
893   }
894   for (i = 0; i < gfxColorMaxComps; ++i) {
895     color.c[i] = 0;
896   }
897   state->setFillColor(&color);
898   out->updateFillColor(state);
899 }
900
901 void Gfx::opSetStrokeColorSpace(Object args[], int numArgs) {
902   Object obj;
903   GfxColorSpace *colorSpace;
904   GfxColor color;
905   int i;
906
907   state->setStrokePattern(NULL);
908   res->lookupColorSpace(args[0].getName(), &obj);
909   if (obj.isNull()) {
910     colorSpace = GfxColorSpace::parse(&args[0]);
911   } else {
912     colorSpace = GfxColorSpace::parse(&obj);
913   }
914   obj.free();
915   if (colorSpace) {
916     state->setStrokeColorSpace(colorSpace);
917   } else {
918     error(getPos(), "Bad color space (stroke)");
919   }
920   for (i = 0; i < gfxColorMaxComps; ++i) {
921     color.c[i] = 0;
922   }
923   state->setStrokeColor(&color);
924   out->updateStrokeColor(state);
925 }
926
927 void Gfx::opSetFillColor(Object args[], int numArgs) {
928   GfxColor color;
929   int i;
930
931   state->setFillPattern(NULL);
932   for (i = 0; i < numArgs; ++i) {
933     color.c[i] = args[i].getNum();
934   }
935   state->setFillColor(&color);
936   out->updateFillColor(state);
937 }
938
939 void Gfx::opSetStrokeColor(Object args[], int numArgs) {
940   GfxColor color;
941   int i;
942
943   state->setStrokePattern(NULL);
944   for (i = 0; i < numArgs; ++i) {
945     color.c[i] = args[i].getNum();
946   }
947   state->setStrokeColor(&color);
948   out->updateStrokeColor(state);
949 }
950
951 void Gfx::opSetFillColorN(Object args[], int numArgs) {
952   GfxColor color;
953   GfxPattern *pattern;
954   int i;
955
956   if (state->getFillColorSpace()->getMode() == csPattern) {
957     if (numArgs > 1) {
958       for (i = 0; i < numArgs && i < 4; ++i) {
959         if (args[i].isNum()) {
960           color.c[i] = args[i].getNum();
961         }
962       }
963       state->setFillColor(&color);
964       out->updateFillColor(state);
965     }
966     if (args[numArgs-1].isName() &&
967         (pattern = res->lookupPattern(args[numArgs-1].getName()))) {
968       state->setFillPattern(pattern);
969     }
970
971   } else {
972     state->setFillPattern(NULL);
973     for (i = 0; i < numArgs && i < 4; ++i) {
974       if (args[i].isNum()) {
975         color.c[i] = args[i].getNum();
976       }
977     }
978     state->setFillColor(&color);
979     out->updateFillColor(state);
980   }
981 }
982
983 void Gfx::opSetStrokeColorN(Object args[], int numArgs) {
984   GfxColor color;
985   GfxPattern *pattern;
986   int i;
987
988   if (state->getStrokeColorSpace()->getMode() == csPattern) {
989     if (numArgs > 1) {
990       for (i = 0; i < numArgs && i < 4; ++i) {
991         if (args[i].isNum()) {
992           color.c[i] = args[i].getNum();
993         }
994       }
995       state->setStrokeColor(&color);
996       out->updateStrokeColor(state);
997     }
998     if (args[numArgs-1].isName() &&
999         (pattern = res->lookupPattern(args[numArgs-1].getName()))) {
1000       state->setStrokePattern(pattern);
1001     }
1002
1003   } else {
1004     state->setStrokePattern(NULL);
1005     for (i = 0; i < numArgs && i < 4; ++i) {
1006       if (args[i].isNum()) {
1007         color.c[i] = args[i].getNum();
1008       }
1009     }
1010     state->setStrokeColor(&color);
1011     out->updateStrokeColor(state);
1012   }
1013 }
1014
1015 //------------------------------------------------------------------------
1016 // path segment operators
1017 //------------------------------------------------------------------------
1018
1019 void Gfx::opMoveTo(Object args[], int numArgs) {
1020   state->moveTo(args[0].getNum(), args[1].getNum());
1021 }
1022
1023 void Gfx::opLineTo(Object args[], int numArgs) {
1024   if (!state->isCurPt()) {
1025     error(getPos(), "No current point in lineto");
1026     return;
1027   }
1028   state->lineTo(args[0].getNum(), args[1].getNum());
1029 }
1030
1031 void Gfx::opCurveTo(Object args[], int numArgs) {
1032   double x1, y1, x2, y2, x3, y3;
1033
1034   if (!state->isCurPt()) {
1035     error(getPos(), "No current point in curveto");
1036     return;
1037   }
1038   x1 = args[0].getNum();
1039   y1 = args[1].getNum();
1040   x2 = args[2].getNum();
1041   y2 = args[3].getNum();
1042   x3 = args[4].getNum();
1043   y3 = args[5].getNum();
1044   state->curveTo(x1, y1, x2, y2, x3, y3);
1045 }
1046
1047 void Gfx::opCurveTo1(Object args[], int numArgs) {
1048   double x1, y1, x2, y2, x3, y3;
1049
1050   if (!state->isCurPt()) {
1051     error(getPos(), "No current point in curveto1");
1052     return;
1053   }
1054   x1 = state->getCurX();
1055   y1 = state->getCurY();
1056   x2 = args[0].getNum();
1057   y2 = args[1].getNum();
1058   x3 = args[2].getNum();
1059   y3 = args[3].getNum();
1060   state->curveTo(x1, y1, x2, y2, x3, y3);
1061 }
1062
1063 void Gfx::opCurveTo2(Object args[], int numArgs) {
1064   double x1, y1, x2, y2, x3, y3;
1065
1066   if (!state->isCurPt()) {
1067     error(getPos(), "No current point in curveto2");
1068     return;
1069   }
1070   x1 = args[0].getNum();
1071   y1 = args[1].getNum();
1072   x2 = args[2].getNum();
1073   y2 = args[3].getNum();
1074   x3 = x2;
1075   y3 = y2;
1076   state->curveTo(x1, y1, x2, y2, x3, y3);
1077 }
1078
1079 void Gfx::opRectangle(Object args[], int numArgs) {
1080   double x, y, w, h;
1081
1082   x = args[0].getNum();
1083   y = args[1].getNum();
1084   w = args[2].getNum();
1085   h = args[3].getNum();
1086   state->moveTo(x, y);
1087   state->lineTo(x + w, y);
1088   state->lineTo(x + w, y + h);
1089   state->lineTo(x, y + h);
1090   state->closePath();
1091 }
1092
1093 void Gfx::opClosePath(Object args[], int numArgs) {
1094   if (!state->isCurPt()) {
1095     error(getPos(), "No current point in closepath");
1096     return;
1097   }
1098   state->closePath();
1099 }
1100
1101 //------------------------------------------------------------------------
1102 // path painting operators
1103 //------------------------------------------------------------------------
1104
1105 void Gfx::opEndPath(Object args[], int numArgs) {
1106   doEndPath();
1107 }
1108
1109 void Gfx::opStroke(Object args[], int numArgs) {
1110   if (!state->isCurPt()) {
1111     //error(getPos(), "No path in stroke");
1112     return;
1113   }
1114   if (state->isPath())
1115     out->stroke(state);
1116   doEndPath();
1117 }
1118
1119 void Gfx::opCloseStroke(Object args[], int numArgs) {
1120   if (!state->isCurPt()) {
1121     //error(getPos(), "No path in closepath/stroke");
1122     return;
1123   }
1124   if (state->isPath()) {
1125     state->closePath();
1126     out->stroke(state);
1127   }
1128   doEndPath();
1129 }
1130
1131 void Gfx::opFill(Object args[], int numArgs) {
1132   if (!state->isCurPt()) {
1133     //error(getPos(), "No path in fill");
1134     return;
1135   }
1136   if (state->isPath()) {
1137     if (state->getFillColorSpace()->getMode() == csPattern) {
1138       doPatternFill(gFalse);
1139     } else {
1140       out->fill(state);
1141     }
1142   }
1143   doEndPath();
1144 }
1145
1146 void Gfx::opEOFill(Object args[], int numArgs) {
1147   if (!state->isCurPt()) {
1148     //error(getPos(), "No path in eofill");
1149     return;
1150   }
1151   if (state->isPath()) {
1152     if (state->getFillColorSpace()->getMode() == csPattern) {
1153       doPatternFill(gTrue);
1154     } else {
1155       out->eoFill(state);
1156     }
1157   }
1158   doEndPath();
1159 }
1160
1161 void Gfx::opFillStroke(Object args[], int numArgs) {
1162   if (!state->isCurPt()) {
1163     //error(getPos(), "No path in fill/stroke");
1164     return;
1165   }
1166   if (state->isPath()) {
1167     if (state->getFillColorSpace()->getMode() == csPattern) {
1168       doPatternFill(gFalse);
1169     } else {
1170       out->fill(state);
1171     }
1172     out->stroke(state);
1173   }
1174   doEndPath();
1175 }
1176
1177 void Gfx::opCloseFillStroke(Object args[], int numArgs) {
1178   if (!state->isCurPt()) {
1179     //error(getPos(), "No path in closepath/fill/stroke");
1180     return;
1181   }
1182   if (state->isPath()) {
1183     state->closePath();
1184     if (state->getFillColorSpace()->getMode() == csPattern) {
1185       doPatternFill(gFalse);
1186     } else {
1187       out->fill(state);
1188     }
1189     out->stroke(state);
1190   }
1191   doEndPath();
1192 }
1193
1194 void Gfx::opEOFillStroke(Object args[], int numArgs) {
1195   if (!state->isCurPt()) {
1196     //error(getPos(), "No path in eofill/stroke");
1197     return;
1198   }
1199   if (state->isPath()) {
1200     if (state->getFillColorSpace()->getMode() == csPattern) {
1201       doPatternFill(gTrue);
1202     } else {
1203       out->eoFill(state);
1204     }
1205     out->stroke(state);
1206   }
1207   doEndPath();
1208 }
1209
1210 void Gfx::opCloseEOFillStroke(Object args[], int numArgs) {
1211   if (!state->isCurPt()) {
1212     //error(getPos(), "No path in closepath/eofill/stroke");
1213     return;
1214   }
1215   if (state->isPath()) {
1216     state->closePath();
1217     if (state->getFillColorSpace()->getMode() == csPattern) {
1218       doPatternFill(gTrue);
1219     } else {
1220       out->eoFill(state);
1221     }
1222     out->stroke(state);
1223   }
1224   doEndPath();
1225 }
1226
1227 void Gfx::doPatternFill(GBool eoFill) {
1228   GfxPattern *pattern;
1229
1230   // this is a bit of a kludge -- patterns can be really slow, so we
1231   // skip them if we're only doing text extraction, since they almost
1232   // certainly don't contain any text
1233   if (!out->needNonText()) {
1234     return;
1235   }
1236
1237   if (!(pattern = state->getFillPattern())) {
1238     return;
1239   }
1240   switch (pattern->getType()) {
1241   case 1:
1242     doTilingPatternFill((GfxTilingPattern *)pattern, eoFill);
1243     break;
1244   case 2:
1245     doShadingPatternFill((GfxShadingPattern *)pattern, eoFill);
1246     break;
1247   default:
1248     error(getPos(), "Unimplemented pattern type (%d) in fill",
1249           pattern->getType());
1250     break;
1251   }
1252 }
1253
1254 void Gfx::doTilingPatternFill(GfxTilingPattern *tPat, GBool eoFill) {
1255   GfxPatternColorSpace *patCS;
1256   GfxColorSpace *cs;
1257   double xMin, yMin, xMax, yMax, x, y, x1, y1;
1258   double cxMin, cyMin, cxMax, cyMax;
1259   int xi0, yi0, xi1, yi1, xi, yi;
1260   double *ctm, *btm, *ptm;
1261   double m[6], ictm[6], m1[6], imb[6];
1262   double det;
1263   double xstep, ystep;
1264   int i;
1265
1266   // get color space
1267   patCS = (GfxPatternColorSpace *)state->getFillColorSpace();
1268
1269   // construct a (pattern space) -> (current space) transform matrix
1270   ctm = state->getCTM();
1271   btm = baseMatrix;
1272   ptm = tPat->getMatrix();
1273   // iCTM = invert CTM
1274   det = 1 / (ctm[0] * ctm[3] - ctm[1] * ctm[2]);
1275   ictm[0] = ctm[3] * det;
1276   ictm[1] = -ctm[1] * det;
1277   ictm[2] = -ctm[2] * det;
1278   ictm[3] = ctm[0] * det;
1279   ictm[4] = (ctm[2] * ctm[5] - ctm[3] * ctm[4]) * det;
1280   ictm[5] = (ctm[1] * ctm[4] - ctm[0] * ctm[5]) * det;
1281   // m1 = PTM * BTM = PTM * base transform matrix
1282   m1[0] = ptm[0] * btm[0] + ptm[1] * btm[2];
1283   m1[1] = ptm[0] * btm[1] + ptm[1] * btm[3];
1284   m1[2] = ptm[2] * btm[0] + ptm[3] * btm[2];
1285   m1[3] = ptm[2] * btm[1] + ptm[3] * btm[3];
1286   m1[4] = ptm[4] * btm[0] + ptm[5] * btm[2] + btm[4];
1287   m1[5] = ptm[4] * btm[1] + ptm[5] * btm[3] + btm[5];
1288   // m = m1 * iCTM = (PTM * BTM) * (iCTM)
1289   m[0] = m1[0] * ictm[0] + m1[1] * ictm[2];
1290   m[1] = m1[0] * ictm[1] + m1[1] * ictm[3];
1291   m[2] = m1[2] * ictm[0] + m1[3] * ictm[2];
1292   m[3] = m1[2] * ictm[1] + m1[3] * ictm[3];
1293   m[4] = m1[4] * ictm[0] + m1[5] * ictm[2] + ictm[4];
1294   m[5] = m1[4] * ictm[1] + m1[5] * ictm[3] + ictm[5];
1295
1296   // construct a (base space) -> (pattern space) transform matrix
1297   det = 1 / (m1[0] * m1[3] - m1[1] * m1[2]);
1298   imb[0] = m1[3] * det;
1299   imb[1] = -m1[1] * det;
1300   imb[2] = -m1[2] * det;
1301   imb[3] = m1[0] * det;
1302   imb[4] = (m1[2] * m1[5] - m1[3] * m1[4]) * det;
1303   imb[5] = (m1[1] * m1[4] - m1[0] * m1[5]) * det;
1304
1305   // save current graphics state
1306   saveState();
1307
1308   // set underlying color space (for uncolored tiling patterns); set
1309   // various other parameters (stroke color, line width) to match
1310   // Adobe's behavior
1311   if (tPat->getPaintType() == 2 && (cs = patCS->getUnder())) {
1312     state->setFillColorSpace(cs->copy());
1313     state->setStrokeColorSpace(cs->copy());
1314     state->setStrokeColor(state->getFillColor());
1315   } else {
1316     state->setFillColorSpace(new GfxDeviceGrayColorSpace());
1317     state->setStrokeColorSpace(new GfxDeviceGrayColorSpace());
1318   }
1319   state->setFillPattern(NULL);
1320   out->updateFillColor(state);
1321   state->setStrokePattern(NULL);
1322   out->updateStrokeColor(state);
1323   state->setLineWidth(0);
1324   out->updateLineWidth(state);
1325
1326   // clip to current path
1327   state->clip();
1328   if (eoFill) {
1329     out->eoClip(state);
1330   } else {
1331     out->clip(state);
1332   }
1333   state->clearPath();
1334
1335   // transform clip region bbox to pattern space
1336   state->getClipBBox(&cxMin, &cyMin, &cxMax, &cyMax);
1337   xMin = xMax = cxMin * imb[0] + cyMin * imb[2] + imb[4];
1338   yMin = yMax = cxMin * imb[1] + cyMin * imb[3] + imb[5];
1339   x1 = cxMin * imb[0] + cyMax * imb[2] + imb[4];
1340   y1 = cxMin * imb[1] + cyMax * imb[3] + imb[5];
1341   if (x1 < xMin) {
1342     xMin = x1;
1343   } else if (x1 > xMax) {
1344     xMax = x1;
1345   }
1346   if (y1 < yMin) {
1347     yMin = y1;
1348   } else if (y1 > yMax) {
1349     yMax = y1;
1350   }
1351   x1 = cxMax * imb[0] + cyMin * imb[2] + imb[4];
1352   y1 = cxMax * imb[1] + cyMin * imb[3] + imb[5];
1353   if (x1 < xMin) {
1354     xMin = x1;
1355   } else if (x1 > xMax) {
1356     xMax = x1;
1357   }
1358   if (y1 < yMin) {
1359     yMin = y1;
1360   } else if (y1 > yMax) {
1361     yMax = y1;
1362   }
1363   x1 = cxMax * imb[0] + cyMax * imb[2] + imb[4];
1364   y1 = cxMax * imb[1] + cyMax * imb[3] + imb[5];
1365   if (x1 < xMin) {
1366     xMin = x1;
1367   } else if (x1 > xMax) {
1368     xMax = x1;
1369   }
1370   if (y1 < yMin) {
1371     yMin = y1;
1372   } else if (y1 > yMax) {
1373     yMax = y1;
1374   }
1375
1376   // draw the pattern
1377   //~ this should treat negative steps differently -- start at right/top
1378   //~ edge instead of left/bottom (?)
1379   xstep = fabs(tPat->getXStep());
1380   ystep = fabs(tPat->getYStep());
1381   xi0 = (int)floor(xMin / xstep);
1382   xi1 = (int)ceil(xMax / xstep);
1383   yi0 = (int)floor(yMin / ystep);
1384   yi1 = (int)ceil(yMax / ystep);
1385   for (i = 0; i < 4; ++i) {
1386     m1[i] = m[i];
1387   }
1388   for (yi = yi0; yi < yi1; ++yi) {
1389     for (xi = xi0; xi < xi1; ++xi) {
1390       x = xi * xstep - tPat->getBBox()[0];
1391       y = yi * ystep - tPat->getBBox()[1];
1392       m1[4] = x * m[0] + y * m[2] + m[4];
1393       m1[5] = x * m[1] + y * m[3] + m[5];
1394       doForm1(tPat->getContentStream(), tPat->getResDict(),
1395               m1, tPat->getBBox());
1396     }
1397   }
1398
1399   // restore graphics state
1400   restoreState();
1401 }
1402
1403 void Gfx::doShadingPatternFill(GfxShadingPattern *sPat, GBool eoFill) {
1404   GfxShading *shading;
1405   double *ctm, *btm, *ptm;
1406   double m[6], ictm[6], m1[6];
1407   double xMin, yMin, xMax, yMax;
1408   double det;
1409
1410   shading = sPat->getShading();
1411
1412   // save current graphics state
1413   saveState();
1414
1415   // clip to bbox
1416   if (shading->getHasBBox()) {
1417     shading->getBBox(&xMin, &yMin, &xMax, &yMax);
1418     state->moveTo(xMin, yMin);
1419     state->lineTo(xMax, yMin);
1420     state->lineTo(xMax, yMax);
1421     state->lineTo(xMin, yMax);
1422     state->closePath();
1423     state->clip();
1424     out->clip(state);
1425     state->clearPath();
1426   }
1427
1428   // clip to current path
1429   state->clip();
1430   if (eoFill) {
1431     out->eoClip(state);
1432   } else {
1433     out->clip(state);
1434   }
1435   state->clearPath();
1436
1437   // construct a (pattern space) -> (current space) transform matrix
1438   ctm = state->getCTM();
1439   btm = baseMatrix;
1440   ptm = sPat->getMatrix();
1441   // iCTM = invert CTM
1442   det = 1 / (ctm[0] * ctm[3] - ctm[1] * ctm[2]);
1443   ictm[0] = ctm[3] * det;
1444   ictm[1] = -ctm[1] * det;
1445   ictm[2] = -ctm[2] * det;
1446   ictm[3] = ctm[0] * det;
1447   ictm[4] = (ctm[2] * ctm[5] - ctm[3] * ctm[4]) * det;
1448   ictm[5] = (ctm[1] * ctm[4] - ctm[0] * ctm[5]) * det;
1449   // m1 = PTM * BTM = PTM * base transform matrix
1450   m1[0] = ptm[0] * btm[0] + ptm[1] * btm[2];
1451   m1[1] = ptm[0] * btm[1] + ptm[1] * btm[3];
1452   m1[2] = ptm[2] * btm[0] + ptm[3] * btm[2];
1453   m1[3] = ptm[2] * btm[1] + ptm[3] * btm[3];
1454   m1[4] = ptm[4] * btm[0] + ptm[5] * btm[2] + btm[4];
1455   m1[5] = ptm[4] * btm[1] + ptm[5] * btm[3] + btm[5];
1456   // m = m1 * iCTM = (PTM * BTM) * (iCTM)
1457   m[0] = m1[0] * ictm[0] + m1[1] * ictm[2];
1458   m[1] = m1[0] * ictm[1] + m1[1] * ictm[3];
1459   m[2] = m1[2] * ictm[0] + m1[3] * ictm[2];
1460   m[3] = m1[2] * ictm[1] + m1[3] * ictm[3];
1461   m[4] = m1[4] * ictm[0] + m1[5] * ictm[2] + ictm[4];
1462   m[5] = m1[4] * ictm[1] + m1[5] * ictm[3] + ictm[5];
1463
1464   // set the new matrix
1465   state->concatCTM(m[0], m[1], m[2], m[3], m[4], m[5]);
1466   out->updateCTM(state, m[0], m[1], m[2], m[3], m[4], m[5]);
1467
1468   // set the color space
1469   state->setFillColorSpace(shading->getColorSpace()->copy());
1470
1471   // do shading type-specific operations
1472   switch (shading->getType()) {
1473   case 1:
1474     doFunctionShFill((GfxFunctionShading *)shading);
1475     break;
1476   case 2:
1477     doAxialShFill((GfxAxialShading *)shading);
1478     break;
1479   case 3:
1480     doRadialShFill((GfxRadialShading *)shading);
1481     break;
1482   }
1483
1484   // restore graphics state
1485   restoreState();
1486 }
1487
1488 void Gfx::opShFill(Object args[], int numArgs) {
1489   GfxShading *shading;
1490   double xMin, yMin, xMax, yMax;
1491
1492   if (!(shading = res->lookupShading(args[0].getName()))) {
1493     return;
1494   }
1495
1496   // save current graphics state
1497   saveState();
1498
1499   // clip to bbox
1500   if (shading->getHasBBox()) {
1501     shading->getBBox(&xMin, &yMin, &xMax, &yMax);
1502     state->moveTo(xMin, yMin);
1503     state->lineTo(xMax, yMin);
1504     state->lineTo(xMax, yMax);
1505     state->lineTo(xMin, yMax);
1506     state->closePath();
1507     state->clip();
1508     out->clip(state);
1509     state->clearPath();
1510   }
1511
1512   // set the color space
1513   state->setFillColorSpace(shading->getColorSpace()->copy());
1514
1515   // do shading type-specific operations
1516   switch (shading->getType()) {
1517   case 1:
1518     doFunctionShFill((GfxFunctionShading *)shading);
1519     break;
1520   case 2:
1521     doAxialShFill((GfxAxialShading *)shading);
1522     break;
1523   case 3:
1524     doRadialShFill((GfxRadialShading *)shading);
1525     break;
1526   }
1527
1528   // restore graphics state
1529   restoreState();
1530
1531   delete shading;
1532 }
1533
1534 void Gfx::doFunctionShFill(GfxFunctionShading *shading) {
1535   double x0, y0, x1, y1;
1536   GfxColor colors[4];
1537
1538   shading->getDomain(&x0, &y0, &x1, &y1);
1539   shading->getColor(x0, y0, &colors[0]);
1540   shading->getColor(x0, y1, &colors[1]);
1541   shading->getColor(x1, y0, &colors[2]);
1542   shading->getColor(x1, y1, &colors[3]);
1543   doFunctionShFill1(shading, x0, y0, x1, y1, colors, 0);
1544 }
1545
1546 void Gfx::doFunctionShFill1(GfxFunctionShading *shading,
1547                             double x0, double y0,
1548                             double x1, double y1,
1549                             GfxColor *colors, int depth) {
1550   GfxColor fillColor;
1551   GfxColor color0M, color1M, colorM0, colorM1, colorMM;
1552   GfxColor colors2[4];
1553   double *matrix;
1554   double xM, yM;
1555   int nComps, i, j;
1556
1557   nComps = shading->getColorSpace()->getNComps();
1558   matrix = shading->getMatrix();
1559
1560   // compare the four corner colors
1561   for (i = 0; i < 4; ++i) {
1562     for (j = 0; j < nComps; ++j) {
1563       if (fabs(colors[i].c[j] - colors[(i+1)&3].c[j]) > functionColorDelta) {
1564         break;
1565       }
1566     }
1567     if (j < nComps) {
1568       break;
1569     }
1570   }
1571
1572   // center of the rectangle
1573   xM = 0.5 * (x0 + x1);
1574   yM = 0.5 * (y0 + y1);
1575
1576   // the four corner colors are close (or we hit the recursive limit)
1577   // -- fill the rectangle; but require at least one subdivision
1578   // (depth==0) to avoid problems when the four outer corners of the
1579   // shaded region are the same color
1580   if ((i == 4 && depth > 0) || depth == functionMaxDepth) {
1581
1582     // use the center color
1583     shading->getColor(xM, yM, &fillColor);
1584     state->setFillColor(&fillColor);
1585     out->updateFillColor(state);
1586
1587     // fill the rectangle
1588     state->moveTo(x0 * matrix[0] + y0 * matrix[2] + matrix[4],
1589                   x0 * matrix[1] + y0 * matrix[3] + matrix[5]);
1590     state->lineTo(x1 * matrix[0] + y0 * matrix[2] + matrix[4],
1591                   x1 * matrix[1] + y0 * matrix[3] + matrix[5]);
1592     state->lineTo(x1 * matrix[0] + y1 * matrix[2] + matrix[4],
1593                   x1 * matrix[1] + y1 * matrix[3] + matrix[5]);
1594     state->lineTo(x0 * matrix[0] + y1 * matrix[2] + matrix[4],
1595                   x0 * matrix[1] + y1 * matrix[3] + matrix[5]);
1596     state->closePath();
1597     out->fill(state);
1598     state->clearPath();
1599
1600   // the four corner colors are not close enough -- subdivide the
1601   // rectangle
1602   } else {
1603
1604     // colors[0]       colorM0       colors[2]
1605     //   (x0,y0)       (xM,y0)       (x1,y0)
1606     //         +----------+----------+
1607     //         |          |          |
1608     //         |    UL    |    UR    |
1609     // color0M |       colorMM       | color1M
1610     // (x0,yM) +----------+----------+ (x1,yM)
1611     //         |       (xM,yM)       |
1612     //         |    LL    |    LR    |
1613     //         |          |          |
1614     //         +----------+----------+
1615     // colors[1]       colorM1       colors[3]
1616     //   (x0,y1)       (xM,y1)       (x1,y1)
1617
1618     shading->getColor(x0, yM, &color0M);
1619     shading->getColor(x1, yM, &color1M);
1620     shading->getColor(xM, y0, &colorM0);
1621     shading->getColor(xM, y1, &colorM1);
1622     shading->getColor(xM, yM, &colorMM);
1623
1624     // upper-left sub-rectangle
1625     colors2[0] = colors[0];
1626     colors2[1] = color0M;
1627     colors2[2] = colorM0;
1628     colors2[3] = colorMM;
1629     doFunctionShFill1(shading, x0, y0, xM, yM, colors2, depth + 1);
1630     
1631     // lower-left sub-rectangle
1632     colors2[0] = color0M;
1633     colors2[1] = colors[1];
1634     colors2[2] = colorMM;
1635     colors2[3] = colorM1;
1636     doFunctionShFill1(shading, x0, yM, xM, y1, colors2, depth + 1);
1637     
1638     // upper-right sub-rectangle
1639     colors2[0] = colorM0;
1640     colors2[1] = colorMM;
1641     colors2[2] = colors[2];
1642     colors2[3] = color1M;
1643     doFunctionShFill1(shading, xM, y0, x1, yM, colors2, depth + 1);
1644
1645     // lower-right sub-rectangle
1646     colors2[0] = colorMM;
1647     colors2[1] = colorM1;
1648     colors2[2] = color1M;
1649     colors2[3] = colors[3];
1650     doFunctionShFill1(shading, xM, yM, x1, y1, colors2, depth + 1);
1651   }
1652 }
1653
1654 void Gfx::doAxialShFill(GfxAxialShading *shading) {
1655   double xMin, yMin, xMax, yMax;
1656   double x0, y0, x1, y1;
1657   double dx, dy, mul;
1658   double tMin, tMax, t, tx, ty;
1659   double s[4], sMin, sMax, tmp;
1660   double ux0, uy0, ux1, uy1, vx0, vy0, vx1, vy1;
1661   double t0, t1, tt;
1662   double ta[axialMaxSplits + 1];
1663   int next[axialMaxSplits + 1];
1664   GfxColor color0, color1;
1665   int nComps;
1666   int i, j, k, kk;
1667
1668   // get the clip region bbox
1669   state->getUserClipBBox(&xMin, &yMin, &xMax, &yMax);
1670
1671   // compute min and max t values, based on the four corners of the
1672   // clip region bbox
1673   shading->getCoords(&x0, &y0, &x1, &y1);
1674   dx = x1 - x0;
1675   dy = y1 - y0;
1676   mul = 1 / (dx * dx + dy * dy);
1677   tMin = tMax = ((xMin - x0) * dx + (yMin - y0) * dy) * mul;
1678   t = ((xMin - x0) * dx + (yMax - y0) * dy) * mul;
1679   if (t < tMin) {
1680     tMin = t;
1681   } else if (t > tMax) {
1682     tMax = t;
1683   }
1684   t = ((xMax - x0) * dx + (yMin - y0) * dy) * mul;
1685   if (t < tMin) {
1686     tMin = t;
1687   } else if (t > tMax) {
1688     tMax = t;
1689   }
1690   t = ((xMax - x0) * dx + (yMax - y0) * dy) * mul;
1691   if (t < tMin) {
1692     tMin = t;
1693   } else if (t > tMax) {
1694     tMax = t;
1695   }
1696   if (tMin < 0 && !shading->getExtend0()) {
1697     tMin = 0;
1698   }
1699   if (tMax > 1 && !shading->getExtend1()) {
1700     tMax = 1;
1701   }
1702
1703   // get the function domain
1704   t0 = shading->getDomain0();
1705   t1 = shading->getDomain1();
1706
1707   // Traverse the t axis and do the shading.
1708   //
1709   // For each point (tx, ty) on the t axis, consider a line through
1710   // that point perpendicular to the t axis:
1711   //
1712   //     x(s) = tx + s * -dy   -->   s = (x - tx) / -dy
1713   //     y(s) = ty + s * dx    -->   s = (y - ty) / dx
1714   //
1715   // Then look at the intersection of this line with the bounding box
1716   // (xMin, yMin, xMax, yMax).  In the general case, there are four
1717   // intersection points:
1718   //
1719   //     s0 = (xMin - tx) / -dy
1720   //     s1 = (xMax - tx) / -dy
1721   //     s2 = (yMin - ty) / dx
1722   //     s3 = (yMax - ty) / dx
1723   //
1724   // and we want the middle two s values.
1725   //
1726   // In the case where dx = 0, take s0 and s1; in the case where dy =
1727   // 0, take s2 and s3.
1728   //
1729   // Each filled polygon is bounded by two of these line segments
1730   // perpdendicular to the t axis.
1731   //
1732   // The t axis is bisected into smaller regions until the color
1733   // difference across a region is small enough, and then the region
1734   // is painted with a single color.
1735
1736   // set up: require at least one split to avoid problems when the two
1737   // ends of the t axis have the same color
1738   nComps = shading->getColorSpace()->getNComps();
1739   ta[0] = tMin;
1740   next[0] = axialMaxSplits / 2;
1741   ta[axialMaxSplits / 2] = 0.5 * (tMin + tMax);
1742   next[axialMaxSplits / 2] = axialMaxSplits;
1743   ta[axialMaxSplits] = tMax;
1744
1745   // compute the color at t = tMin
1746   if (tMin < 0) {
1747     tt = t0;
1748   } else if (tMin > 1) {
1749     tt = t1;
1750   } else {
1751     tt = t0 + (t1 - t0) * tMin;
1752   }
1753   shading->getColor(tt, &color0);
1754
1755   // compute the coordinates of the point on the t axis at t = tMin;
1756   // then compute the intersection of the perpendicular line with the
1757   // bounding box
1758   tx = x0 + tMin * dx;
1759   ty = y0 + tMin * dy;
1760   if (dx == 0 && dy == 0) {
1761     sMin = sMax = 0;
1762   } if (dx == 0) {
1763     sMin = (xMin - tx) / -dy;
1764     sMax = (xMax - tx) / -dy;
1765     if (sMin > sMax) { tmp = sMin; sMin = sMax; sMax = tmp; }
1766   } else if (dy == 0) {
1767     sMin = (yMin - ty) / dx;
1768     sMax = (yMax - ty) / dx;
1769     if (sMin > sMax) { tmp = sMin; sMin = sMax; sMax = tmp; }
1770   } else {
1771     s[0] = (yMin - ty) / dx;
1772     s[1] = (yMax - ty) / dx;
1773     s[2] = (xMin - tx) / -dy;
1774     s[3] = (xMax - tx) / -dy;
1775     for (j = 0; j < 3; ++j) {
1776       kk = j;
1777       for (k = j + 1; k < 4; ++k) {
1778         if (s[k] < s[kk]) {
1779           kk = k;
1780         }
1781       }
1782       tmp = s[j]; s[j] = s[kk]; s[kk] = tmp;
1783     }
1784     sMin = s[1];
1785     sMax = s[2];
1786   }
1787   ux0 = tx - sMin * dy;
1788   uy0 = ty + sMin * dx;
1789   vx0 = tx - sMax * dy;
1790   vy0 = ty + sMax * dx;
1791
1792   i = 0;
1793   while (i < axialMaxSplits) {
1794
1795     // bisect until color difference is small enough or we hit the
1796     // bisection limit
1797     j = next[i];
1798     while (j > i + 1) {
1799       if (ta[j] < 0) {
1800         tt = t0;
1801       } else if (ta[j] > 1) {
1802         tt = t1;
1803       } else {
1804         tt = t0 + (t1 - t0) * ta[j];
1805       }
1806       shading->getColor(tt, &color1);
1807       for (k = 0; k < nComps; ++k) {
1808         if (fabs(color1.c[k] - color0.c[k]) > axialColorDelta) {
1809           break;
1810         }
1811       }
1812       if (k == nComps) {
1813         break;
1814       }
1815       k = (i + j) / 2;
1816       ta[k] = 0.5 * (ta[i] + ta[j]);
1817       next[i] = k;
1818       next[k] = j;
1819       j = k;
1820     }
1821
1822     // use the average of the colors of the two sides of the region
1823     for (k = 0; k < nComps; ++k) {
1824       color0.c[k] = 0.5 * (color0.c[k] + color1.c[k]);
1825     }
1826
1827     // compute the coordinates of the point on the t axis; then
1828     // compute the intersection of the perpendicular line with the
1829     // bounding box
1830     tx = x0 + ta[j] * dx;
1831     ty = y0 + ta[j] * dy;
1832     if (dx == 0 && dy == 0) {
1833       sMin = sMax = 0;
1834     } if (dx == 0) {
1835       sMin = (xMin - tx) / -dy;
1836       sMax = (xMax - tx) / -dy;
1837       if (sMin > sMax) { tmp = sMin; sMin = sMax; sMax = tmp; }
1838     } else if (dy == 0) {
1839       sMin = (yMin - ty) / dx;
1840       sMax = (yMax - ty) / dx;
1841       if (sMin > sMax) { tmp = sMin; sMin = sMax; sMax = tmp; }
1842     } else {
1843       s[0] = (yMin - ty) / dx;
1844       s[1] = (yMax - ty) / dx;
1845       s[2] = (xMin - tx) / -dy;
1846       s[3] = (xMax - tx) / -dy;
1847       for (j = 0; j < 3; ++j) {
1848         kk = j;
1849         for (k = j + 1; k < 4; ++k) {
1850           if (s[k] < s[kk]) {
1851             kk = k;
1852           }
1853         }
1854         tmp = s[j]; s[j] = s[kk]; s[kk] = tmp;
1855       }
1856       sMin = s[1];
1857       sMax = s[2];
1858     }
1859     ux1 = tx - sMin * dy;
1860     uy1 = ty + sMin * dx;
1861     vx1 = tx - sMax * dy;
1862     vy1 = ty + sMax * dx;
1863
1864     // set the color
1865     state->setFillColor(&color0);
1866     out->updateFillColor(state);
1867
1868     // fill the region
1869     state->moveTo(ux0, uy0);
1870     state->lineTo(vx0, vy0);
1871     state->lineTo(vx1, vy1);
1872     state->lineTo(ux1, uy1);
1873     state->closePath();
1874     out->fill(state);
1875     state->clearPath();
1876
1877     // set up for next region
1878     ux0 = ux1;
1879     uy0 = uy1;
1880     vx0 = vx1;
1881     vy0 = vy1;
1882     color0 = color1;
1883     i = next[i];
1884   }
1885 }
1886
1887 void Gfx::doRadialShFill(GfxRadialShading *shading) {
1888   double sMin, sMax, xMin, yMin, xMax, yMax;
1889   double x0, y0, r0, x1, y1, r1, t0, t1;
1890   int nComps;
1891   GfxColor colorA, colorB;
1892   double xa, ya, xb, yb, ra, rb;
1893   double ta, tb, sa, sb;
1894   int ia, ib, k, n;
1895   double *ctm;
1896   double angle, t;
1897
1898   // get the shading info
1899   shading->getCoords(&x0, &y0, &r0, &x1, &y1, &r1);
1900   t0 = shading->getDomain0();
1901   t1 = shading->getDomain1();
1902   nComps = shading->getColorSpace()->getNComps();
1903
1904   // compute the (possibly extended) s range
1905   sMin = 0;
1906   sMax = 1;
1907   if (shading->getExtend0()) {
1908     if (r0 < r1) {
1909       // extend the smaller end
1910       sMin = -r0 / (r1 - r0);
1911     } else {
1912       // extend the larger end
1913       //~ this computes the diagonal of the bounding box -- we should
1914       //~ really compute the intersection of the moving/expanding
1915       //~ circles with each of the four corners and look for the max
1916       //~ radius
1917       state->getUserClipBBox(&xMin, &yMin, &xMax, &yMax);
1918       sMin = (sqrt((xMax - xMin) * (xMax - xMin) +
1919                    (yMax - yMin) * (yMax - yMin)) - r0) / (r1 - r0);
1920       if (sMin > 0) {
1921         sMin = 0;
1922       } else if (sMin < -20) {
1923         // sanity check
1924         sMin = -20;
1925       }
1926     }
1927   }
1928   if (shading->getExtend1()) {
1929     if (r1 < r0) {
1930       // extend the smaller end
1931       sMax = -r0 / (r1 - r0);
1932     } else if (r1 > r0) {
1933       // extend the larger end
1934       state->getUserClipBBox(&xMin, &yMin, &xMax, &yMax);
1935       sMax = (sqrt((xMax - xMin) * (xMax - xMin) +
1936                    (yMax - yMin) * (yMax - yMin)) - r0) / (r1 - r0);
1937       if (sMax < 1) {
1938         sMin = 1;
1939       } else if (sMax > 20) {
1940         // sanity check
1941         sMax = 20;
1942       }
1943     }
1944   }
1945
1946   // compute the number of steps into which circles must be divided to
1947   // achieve a curve flatness of 0.1 pixel in device space for the
1948   // largest circle (note that "device space" is 72 dpi when generating
1949   // PostScript, hence the relatively small 0.1 pixel accuracy)
1950   ctm = state->getCTM();
1951   t = fabs(ctm[0]);
1952   if (fabs(ctm[1]) > t) {
1953     t = fabs(ctm[1]);
1954   }
1955   if (fabs(ctm[2]) > t) {
1956     t = fabs(ctm[2]);
1957   }
1958   if (fabs(ctm[3]) > t) {
1959     t = fabs(ctm[3]);
1960   }
1961   if (r0 > r1) {
1962     t *= r0;
1963   } else {
1964     t *= r1;
1965   }
1966   if (t < 1) {
1967     n = 3;
1968   } else {
1969     n = (int)(M_PI / acos(1 - 0.1 / t));
1970     if (n < 3) {
1971       n = 3;
1972     } else if (n > 200) {
1973       n = 200;
1974     }
1975   }
1976
1977   // Traverse the t axis and do the shading.
1978   //
1979   // This generates and fills a series of rings.  Each ring is defined
1980   // by two circles:
1981   //   sa, ta, xa, ya, ra, colorA
1982   //   sb, tb, xb, yb, rb, colorB
1983   //
1984   // The s/t axis is divided into radialMaxSplits parts; these parts
1985   // are combined as much as possible while respecting the
1986   // radialColorDelta parameter.
1987
1988   // setup for the start circle
1989   ia = 0;
1990   sa = sMin;
1991   ta = t0 + sa * (t1 - t0);
1992   xa = x0 + sa * (x1 - x0);
1993   ya = y0 + sa * (y1 - y0);
1994   ra = r0 + sa * (r1 - r0);
1995   if (ta < t0) {
1996     shading->getColor(t0, &colorA);
1997   } else if (ta > t1) {
1998     shading->getColor(t1, &colorA);
1999   } else {
2000     shading->getColor(ta, &colorA);
2001   }
2002
2003   while (ia < radialMaxSplits) {
2004
2005     // go as far along the t axis (toward t1) as we can, such that the
2006     // color difference is within the tolerance (radialColorDelta) --
2007     // this uses bisection (between the current value, t, and t1),
2008     // limited to radialMaxSplits points along the t axis; require at
2009     // least one split to avoid problems when the innermost and
2010     // outermost colors are the same
2011     ib = radialMaxSplits;
2012     sb = sMin + ((double)ib / (double)radialMaxSplits) * (sMax - sMin);
2013     tb = t0 + sb * (t1 - t0);
2014     if (tb < t0) {
2015       shading->getColor(t0, &colorB);
2016     } else if (tb > t1) {
2017       shading->getColor(t1, &colorB);
2018     } else {
2019       shading->getColor(tb, &colorB);
2020     }
2021     while (ib - ia > 1) {
2022       for (k = 0; k < nComps; ++k) {
2023         if (fabs(colorB.c[k] - colorA.c[k]) > radialColorDelta) {
2024           break;
2025         }
2026       }
2027       if (k == nComps && ib < radialMaxSplits) {
2028         break;
2029       }
2030       ib = (ia + ib) / 2;
2031       sb = sMin + ((double)ib / (double)radialMaxSplits) * (sMax - sMin);
2032       tb = t0 + sb * (t1 - t0);
2033       if (tb < t0) {
2034         shading->getColor(t0, &colorB);
2035       } else if (tb > t1) {
2036         shading->getColor(t1, &colorB);
2037       } else {
2038         shading->getColor(tb, &colorB);
2039       }
2040     }
2041
2042     // compute center and radius of the circle
2043     xb = x0 + sb * (x1 - x0);
2044     yb = y0 + sb * (y1 - y0);
2045     rb = r0 + sb * (r1 - r0);
2046
2047     // use the average of the colors at the two circles
2048     for (k = 0; k < nComps; ++k) {
2049       colorA.c[k] = 0.5 * (colorA.c[k] + colorB.c[k]);
2050     }
2051     state->setFillColor(&colorA);
2052     out->updateFillColor(state);
2053
2054     // construct path for first circle
2055     state->moveTo(xa + ra, ya);
2056     for (k = 1; k < n; ++k) {
2057       angle = ((double)k / (double)n) * 2 * M_PI;
2058       state->lineTo(xa + ra * cos(angle), ya + ra * sin(angle));
2059     }
2060     state->closePath();
2061
2062     // construct and append path for second circle
2063     state->moveTo(xb + rb, yb);
2064     for (k = 1; k < n; ++k) {
2065       angle = ((double)k / (double)n) * 2 * M_PI;
2066       state->lineTo(xb + rb * cos(angle), yb + rb * sin(angle));
2067     }
2068     state->closePath();
2069
2070     // fill the ring
2071     out->eoFill(state);
2072     state->clearPath();
2073
2074     // step to the next value of t
2075     ia = ib;
2076     sa = sb;
2077     ta = tb;
2078     xa = xb;
2079     ya = yb;
2080     ra = rb;
2081     colorA = colorB;
2082   }
2083 }
2084
2085 void Gfx::doEndPath() {
2086   if (state->isCurPt() && clip != clipNone) {
2087     state->clip();
2088     if (clip == clipNormal) {
2089       out->clip(state);
2090     } else {
2091       out->eoClip(state);
2092     }
2093   }
2094   clip = clipNone;
2095   state->clearPath();
2096 }
2097
2098 //------------------------------------------------------------------------
2099 // path clipping operators
2100 //------------------------------------------------------------------------
2101
2102 void Gfx::opClip(Object args[], int numArgs) {
2103   clip = clipNormal;
2104 }
2105
2106 void Gfx::opEOClip(Object args[], int numArgs) {
2107   clip = clipEO;
2108 }
2109
2110 //------------------------------------------------------------------------
2111 // text object operators
2112 //------------------------------------------------------------------------
2113
2114 void Gfx::opBeginText(Object args[], int numArgs) {
2115   state->setTextMat(1, 0, 0, 1, 0, 0);
2116   state->textMoveTo(0, 0);
2117   out->updateTextMat(state);
2118   out->updateTextPos(state);
2119   fontChanged = gTrue;
2120 }
2121
2122 void Gfx::opEndText(Object args[], int numArgs) {
2123   out->endTextObject(state);
2124 }
2125
2126 //------------------------------------------------------------------------
2127 // text state operators
2128 //------------------------------------------------------------------------
2129
2130 void Gfx::opSetCharSpacing(Object args[], int numArgs) {
2131   state->setCharSpace(args[0].getNum());
2132   out->updateCharSpace(state);
2133 }
2134
2135 void Gfx::opSetFont(Object args[], int numArgs) {
2136   GfxFont *font;
2137
2138   if (!(font = res->lookupFont(args[0].getName()))) {
2139     return;
2140   }
2141   if (printCommands) {
2142     printf("  font: tag=%s name='%s' %g\n",
2143            font->getTag()->getCString(),
2144            font->getName() ? font->getName()->getCString() : "???",
2145            args[1].getNum());
2146     fflush(stdout);
2147   }
2148   state->setFont(font, args[1].getNum());
2149   fontChanged = gTrue;
2150 }
2151
2152 void Gfx::opSetTextLeading(Object args[], int numArgs) {
2153   state->setLeading(args[0].getNum());
2154 }
2155
2156 void Gfx::opSetTextRender(Object args[], int numArgs) {
2157   state->setRender(args[0].getInt());
2158   out->updateRender(state);
2159 }
2160
2161 void Gfx::opSetTextRise(Object args[], int numArgs) {
2162   state->setRise(args[0].getNum());
2163   out->updateRise(state);
2164 }
2165
2166 void Gfx::opSetWordSpacing(Object args[], int numArgs) {
2167   state->setWordSpace(args[0].getNum());
2168   out->updateWordSpace(state);
2169 }
2170
2171 void Gfx::opSetHorizScaling(Object args[], int numArgs) {
2172   state->setHorizScaling(args[0].getNum());
2173   out->updateHorizScaling(state);
2174   fontChanged = gTrue;
2175 }
2176
2177 //------------------------------------------------------------------------
2178 // text positioning operators
2179 //------------------------------------------------------------------------
2180
2181 void Gfx::opTextMove(Object args[], int numArgs) {
2182   double tx, ty;
2183
2184   tx = state->getLineX() + args[0].getNum();
2185   ty = state->getLineY() + args[1].getNum();
2186   state->textMoveTo(tx, ty);
2187   out->updateTextPos(state);
2188 }
2189
2190 void Gfx::opTextMoveSet(Object args[], int numArgs) {
2191   double tx, ty;
2192
2193   tx = state->getLineX() + args[0].getNum();
2194   ty = args[1].getNum();
2195   state->setLeading(-ty);
2196   ty += state->getLineY();
2197   state->textMoveTo(tx, ty);
2198   out->updateTextPos(state);
2199 }
2200
2201 void Gfx::opSetTextMatrix(Object args[], int numArgs) {
2202   state->setTextMat(args[0].getNum(), args[1].getNum(),
2203                     args[2].getNum(), args[3].getNum(),
2204                     args[4].getNum(), args[5].getNum());
2205   state->textMoveTo(0, 0);
2206   out->updateTextMat(state);
2207   out->updateTextPos(state);
2208   fontChanged = gTrue;
2209 }
2210
2211 void Gfx::opTextNextLine(Object args[], int numArgs) {
2212   double tx, ty;
2213
2214   tx = state->getLineX();
2215   ty = state->getLineY() - state->getLeading();
2216   state->textMoveTo(tx, ty);
2217   out->updateTextPos(state);
2218 }
2219
2220 //------------------------------------------------------------------------
2221 // text string operators
2222 //------------------------------------------------------------------------
2223
2224 void Gfx::opShowText(Object args[], int numArgs) {
2225   if (!state->getFont()) {
2226     error(getPos(), "No font in show");
2227     return;
2228   }
2229   doShowText(args[0].getString());
2230 }
2231
2232 void Gfx::opMoveShowText(Object args[], int numArgs) {
2233   double tx, ty;
2234
2235   if (!state->getFont()) {
2236     error(getPos(), "No font in move/show");
2237     return;
2238   }
2239   tx = state->getLineX();
2240   ty = state->getLineY() - state->getLeading();
2241   state->textMoveTo(tx, ty);
2242   out->updateTextPos(state);
2243   doShowText(args[0].getString());
2244 }
2245
2246 void Gfx::opMoveSetShowText(Object args[], int numArgs) {
2247   double tx, ty;
2248
2249   if (!state->getFont()) {
2250     error(getPos(), "No font in move/set/show");
2251     return;
2252   }
2253   state->setWordSpace(args[0].getNum());
2254   state->setCharSpace(args[1].getNum());
2255   tx = state->getLineX();
2256   ty = state->getLineY() - state->getLeading();
2257   state->textMoveTo(tx, ty);
2258   out->updateWordSpace(state);
2259   out->updateCharSpace(state);
2260   out->updateTextPos(state);
2261   doShowText(args[2].getString());
2262 }
2263
2264 void Gfx::opShowSpaceText(Object args[], int numArgs) {
2265   Array *a;
2266   Object obj;
2267   int wMode;
2268   int i;
2269
2270   if (!state->getFont()) {
2271     error(getPos(), "No font in show/space");
2272     return;
2273   }
2274   wMode = state->getFont()->getWMode();
2275   a = args[0].getArray();
2276   for (i = 0; i < a->getLength(); ++i) {
2277     a->get(i, &obj);
2278     if (obj.isNum()) {
2279       if (wMode) {
2280         state->textShift(0, -obj.getNum() * 0.001 * state->getFontSize());
2281       } else {
2282         state->textShift(-obj.getNum() * 0.001 * state->getFontSize(), 0);
2283       }
2284       out->updateTextShift(state, obj.getNum());
2285     } else if (obj.isString()) {
2286       doShowText(obj.getString());
2287     } else {
2288       error(getPos(), "Element of show/space array must be number or string");
2289     }
2290     obj.free();
2291   }
2292 }
2293
2294 void Gfx::doShowText(GString *s) {
2295   GfxFont *font;
2296   int wMode;
2297   double riseX, riseY;
2298   CharCode code;
2299   Unicode u[8];
2300   double x, y, dx, dy, dx2, dy2, curX, curY, tdx, tdy, lineX, lineY;
2301   double originX, originY, tOriginX, tOriginY;
2302   double oldCTM[6], newCTM[6];
2303   double *mat;
2304   Object charProc;
2305   Dict *resDict;
2306   Parser *oldParser;
2307   char *p;
2308   int len, n, uLen, nChars, nSpaces, i;
2309
2310   if (fontChanged) {
2311     out->updateFont(state);
2312     fontChanged = gFalse;
2313   }
2314   font = state->getFont();
2315   wMode = font->getWMode();
2316
2317   if (out->useDrawChar()) {
2318     out->beginString(state, s);
2319   }
2320
2321   // handle a Type 3 char
2322   if (font->getType() == fontType3 && out->interpretType3Chars()) {
2323     mat = state->getCTM();
2324     for (i = 0; i < 6; ++i) {
2325       oldCTM[i] = mat[i];
2326     }
2327     mat = state->getTextMat();
2328     newCTM[0] = mat[0] * oldCTM[0] + mat[1] * oldCTM[2];
2329     newCTM[1] = mat[0] * oldCTM[1] + mat[1] * oldCTM[3];
2330     newCTM[2] = mat[2] * oldCTM[0] + mat[3] * oldCTM[2];
2331     newCTM[3] = mat[2] * oldCTM[1] + mat[3] * oldCTM[3];
2332     mat = font->getFontMatrix();
2333     newCTM[0] = mat[0] * newCTM[0] + mat[1] * newCTM[2];
2334     newCTM[1] = mat[0] * newCTM[1] + mat[1] * newCTM[3];
2335     newCTM[2] = mat[2] * newCTM[0] + mat[3] * newCTM[2];
2336     newCTM[3] = mat[2] * newCTM[1] + mat[3] * newCTM[3];
2337     newCTM[0] *= state->getFontSize();
2338     newCTM[3] *= state->getFontSize();
2339     newCTM[0] *= state->getHorizScaling();
2340     newCTM[2] *= state->getHorizScaling();
2341     state->textTransformDelta(0, state->getRise(), &riseX, &riseY);
2342     curX = state->getCurX();
2343     curY = state->getCurY();
2344     lineX = state->getLineX();
2345     lineY = state->getLineY();
2346     oldParser = parser;
2347     p = s->getCString();
2348     len = s->getLength();
2349     while (len > 0) {
2350       n = font->getNextChar(p, len, &code,
2351                             u, (int)(sizeof(u) / sizeof(Unicode)), &uLen,
2352                             &dx, &dy, &originX, &originY);
2353       dx = dx * state->getFontSize() + state->getCharSpace();
2354       if (n == 1 && *p == ' ') {
2355         dx += state->getWordSpace();
2356       }
2357       dx *= state->getHorizScaling();
2358       dy *= state->getFontSize();
2359       state->textTransformDelta(dx, dy, &tdx, &tdy);
2360       state->transform(curX + riseX, curY + riseY, &x, &y);
2361       saveState();
2362       state->setCTM(newCTM[0], newCTM[1], newCTM[2], newCTM[3], x, y);
2363       //~ out->updateCTM(???)
2364       if (!out->beginType3Char(state, code, u, uLen)) {
2365         ((Gfx8BitFont *)font)->getCharProc(code, &charProc);
2366         if ((resDict = ((Gfx8BitFont *)font)->getResources())) {
2367           pushResources(resDict);
2368         }
2369         if (charProc.isStream()) {
2370           display(&charProc, gFalse);
2371         } else {
2372           error(getPos(), "Missing or bad Type3 CharProc entry");
2373         }
2374         out->endType3Char(state);
2375         if (resDict) {
2376           popResources();
2377         }
2378         charProc.free();
2379       }
2380       restoreState();
2381       // GfxState::restore() does *not* restore the current position,
2382       // so we deal with it here using (curX, curY) and (lineX, lineY)
2383       curX += tdx;
2384       curY += tdy;
2385       state->moveTo(curX, curY);
2386       state->textSetPos(lineX, lineY);
2387       p += n;
2388       len -= n;
2389     }
2390     parser = oldParser;
2391
2392   } else if (out->useDrawChar()) {
2393     state->textTransformDelta(0, state->getRise(), &riseX, &riseY);
2394     p = s->getCString();
2395     len = s->getLength();
2396     while (len > 0) {
2397       n = font->getNextChar(p, len, &code,
2398                             u, (int)(sizeof(u) / sizeof(Unicode)), &uLen,
2399                             &dx, &dy, &originX, &originY);
2400       if (wMode) {
2401         dx *= state->getFontSize();
2402         dy = dy * state->getFontSize() + state->getCharSpace();
2403         if (n == 1 && *p == ' ') {
2404           dy += state->getWordSpace();
2405         }
2406       } else {
2407         dx = dx * state->getFontSize() + state->getCharSpace();
2408         if (n == 1 && *p == ' ') {
2409           dx += state->getWordSpace();
2410         }
2411         dx *= state->getHorizScaling();
2412         dy *= state->getFontSize();
2413       }
2414       state->textTransformDelta(dx, dy, &tdx, &tdy);
2415       originX *= state->getFontSize();
2416       originY *= state->getFontSize();
2417       state->textTransformDelta(originX, originY, &tOriginX, &tOriginY);
2418       out->drawChar(state, state->getCurX() + riseX, state->getCurY() + riseY,
2419                     tdx, tdy, tOriginX, tOriginY, code, u, uLen);
2420       state->shift(tdx, tdy);
2421       p += n;
2422       len -= n;
2423     }
2424
2425   } else {
2426     dx = dy = 0;
2427     p = s->getCString();
2428     len = s->getLength();
2429     nChars = nSpaces = 0;
2430     while (len > 0) {
2431       n = font->getNextChar(p, len, &code,
2432                             u, (int)(sizeof(u) / sizeof(Unicode)), &uLen,
2433                             &dx2, &dy2, &originX, &originY);
2434       dx += dx2;
2435       dy += dy2;
2436       if (n == 1 && *p == ' ') {
2437         ++nSpaces;
2438       }
2439       ++nChars;
2440       p += n;
2441       len -= n;
2442     }
2443     if (wMode) {
2444       dx *= state->getFontSize();
2445       dy = dy * state->getFontSize()
2446            + nChars * state->getCharSpace()
2447            + nSpaces * state->getWordSpace();
2448     } else {
2449       dx = dx * state->getFontSize()
2450            + nChars * state->getCharSpace()
2451            + nSpaces * state->getWordSpace();
2452       dx *= state->getHorizScaling();
2453       dy *= state->getFontSize();
2454     }
2455     state->textTransformDelta(dx, dy, &tdx, &tdy);
2456     out->drawString(state, s);
2457     state->shift(tdx, tdy);
2458   }
2459
2460   if (out->useDrawChar()) {
2461     out->endString(state);
2462   }
2463
2464   updateLevel += 10 * s->getLength();
2465 }
2466
2467 //------------------------------------------------------------------------
2468 // XObject operators
2469 //------------------------------------------------------------------------
2470
2471 void Gfx::opXObject(Object args[], int numArgs) {
2472   Object obj1, obj2, obj3, refObj;
2473 #if OPI_SUPPORT
2474   Object opiDict;
2475 #endif
2476
2477   if (!res->lookupXObject(args[0].getName(), &obj1)) {
2478     return;
2479   }
2480   if (!obj1.isStream()) {
2481     error(getPos(), "XObject '%s' is wrong type", args[0].getName());
2482     obj1.free();
2483     return;
2484   }
2485 #if OPI_SUPPORT
2486   obj1.streamGetDict()->lookup("OPI", &opiDict);
2487   if (opiDict.isDict()) {
2488     out->opiBegin(state, opiDict.getDict());
2489   }
2490 #endif
2491   obj1.streamGetDict()->lookup("Subtype", &obj2);
2492   if (obj2.isName("Image")) {
2493     res->lookupXObjectNF(args[0].getName(), &refObj);
2494     doImage(&refObj, obj1.getStream(), gFalse);
2495     refObj.free();
2496   } else if (obj2.isName("Form")) {
2497     doForm(&obj1);
2498   } else if (obj2.isName("PS")) {
2499     obj1.streamGetDict()->lookup("Level1", &obj3);
2500     out->psXObject(obj1.getStream(),
2501                    obj3.isStream() ? obj3.getStream() : (Stream *)NULL);
2502   } else if (obj2.isName()) {
2503     error(getPos(), "Unknown XObject subtype '%s'", obj2.getName());
2504   } else {
2505     error(getPos(), "XObject subtype is missing or wrong type");
2506   }
2507   obj2.free();
2508 #if OPI_SUPPORT
2509   if (opiDict.isDict()) {
2510     out->opiEnd(state, opiDict.getDict());
2511   }
2512   opiDict.free();
2513 #endif
2514   obj1.free();
2515 }
2516
2517 void Gfx::doImage(Object *ref, Stream *str, GBool inlineImg) {
2518   Dict *dict;
2519   int width, height;
2520   int bits;
2521   GBool mask;
2522   GBool invert;
2523   GfxColorSpace *colorSpace;
2524   GfxImageColorMap *colorMap;
2525   Object maskObj;
2526   GBool haveMask;
2527   int maskColors[2*gfxColorMaxComps];
2528   Object obj1, obj2;
2529   int i;
2530
2531   // get stream dict
2532   dict = str->getDict();
2533
2534   // get size
2535   dict->lookup("Width", &obj1);
2536   if (obj1.isNull()) {
2537     obj1.free();
2538     dict->lookup("W", &obj1);
2539   }
2540   if (!obj1.isInt())
2541     goto err2;
2542   width = obj1.getInt();
2543   obj1.free();
2544   dict->lookup("Height", &obj1);
2545   if (obj1.isNull()) {
2546     obj1.free();
2547     dict->lookup("H", &obj1);
2548   }
2549   if (!obj1.isInt())
2550     goto err2;
2551   height = obj1.getInt();
2552   obj1.free();
2553
2554   // image or mask?
2555   dict->lookup("ImageMask", &obj1);
2556   if (obj1.isNull()) {
2557     obj1.free();
2558     dict->lookup("IM", &obj1);
2559   }
2560   mask = gFalse;
2561   if (obj1.isBool())
2562     mask = obj1.getBool();
2563   else if (!obj1.isNull())
2564     goto err2;
2565   obj1.free();
2566
2567   // bit depth
2568   dict->lookup("BitsPerComponent", &obj1);
2569   if (obj1.isNull()) {
2570     obj1.free();
2571     dict->lookup("BPC", &obj1);
2572   }
2573   if (obj1.isInt()) {
2574     bits = obj1.getInt();
2575   } else if (mask) {
2576     bits = 1;
2577   } else {
2578     goto err2;
2579   }
2580   obj1.free();
2581
2582   // display a mask
2583   if (mask) {
2584
2585     // check for inverted mask
2586     if (bits != 1)
2587       goto err1;
2588     invert = gFalse;
2589     dict->lookup("Decode", &obj1);
2590     if (obj1.isNull()) {
2591       obj1.free();
2592       dict->lookup("D", &obj1);
2593     }
2594     if (obj1.isArray()) {
2595       obj1.arrayGet(0, &obj2);
2596       if (obj2.isInt() && obj2.getInt() == 1)
2597         invert = gTrue;
2598       obj2.free();
2599     } else if (!obj1.isNull()) {
2600       goto err2;
2601     }
2602     obj1.free();
2603
2604     // draw it
2605     out->drawImageMask(state, ref, str, width, height, invert, inlineImg);
2606
2607   } else {
2608
2609     // get color space and color map
2610     dict->lookup("ColorSpace", &obj1);
2611     if (obj1.isNull()) {
2612       obj1.free();
2613       dict->lookup("CS", &obj1);
2614     }
2615     if (obj1.isName()) {
2616       res->lookupColorSpace(obj1.getName(), &obj2);
2617       if (!obj2.isNull()) {
2618         obj1.free();
2619         obj1 = obj2;
2620       } else {
2621         obj2.free();
2622       }
2623     }
2624     colorSpace = GfxColorSpace::parse(&obj1);
2625     obj1.free();
2626     if (!colorSpace) {
2627       goto err1;
2628     }
2629     dict->lookup("Decode", &obj1);
2630     if (obj1.isNull()) {
2631       obj1.free();
2632       dict->lookup("D", &obj1);
2633     }
2634     colorMap = new GfxImageColorMap(bits, &obj1, colorSpace);
2635     obj1.free();
2636     if (!colorMap->isOk()) {
2637       delete colorMap;
2638       goto err1;
2639     }
2640
2641     // get the mask
2642     haveMask = gFalse;
2643     dict->lookup("Mask", &maskObj);
2644     if (maskObj.isArray()) {
2645       for (i = 0; i < maskObj.arrayGetLength(); ++i) {
2646         maskObj.arrayGet(i, &obj1);
2647         maskColors[i] = obj1.getInt();
2648         obj1.free();
2649       }
2650       haveMask = gTrue;
2651     }
2652
2653     // draw it
2654     out->drawImage(state, ref, str, width, height, colorMap,
2655                    haveMask ? maskColors : (int *)NULL,  inlineImg);
2656     delete colorMap;
2657
2658     maskObj.free();
2659   }
2660
2661   if ((i = width * height) > 1000) {
2662     i = 1000;
2663   }
2664   updateLevel += i;
2665
2666   return;
2667
2668  err2:
2669   obj1.free();
2670  err1:
2671   error(getPos(), "Bad image parameters");
2672 }
2673
2674 void Gfx::doForm(Object *str) {
2675   Dict *dict;
2676   Object matrixObj, bboxObj;
2677   double m[6], bbox[6];
2678   Object resObj;
2679   Dict *resDict;
2680   Object obj1;
2681   int i;
2682
2683   // check for excessive recursion
2684   if (formDepth > 20) {
2685     return;
2686   }
2687
2688   // get stream dict
2689   dict = str->streamGetDict();
2690
2691   // check form type
2692   dict->lookup("FormType", &obj1);
2693   if (!(obj1.isInt() && obj1.getInt() == 1)) {
2694     error(getPos(), "Unknown form type");
2695   }
2696   obj1.free();
2697
2698   // get bounding box
2699   dict->lookup("BBox", &bboxObj);
2700   if (!bboxObj.isArray()) {
2701     matrixObj.free();
2702     bboxObj.free();
2703     error(getPos(), "Bad form bounding box");
2704     return;
2705   }
2706   for (i = 0; i < 4; ++i) {
2707     bboxObj.arrayGet(i, &obj1);
2708     bbox[i] = obj1.getNum();
2709     obj1.free();
2710   }
2711   bboxObj.free();
2712
2713   // get matrix
2714   dict->lookup("Matrix", &matrixObj);
2715   if (matrixObj.isArray()) {
2716     for (i = 0; i < 6; ++i) {
2717       matrixObj.arrayGet(i, &obj1);
2718       m[i] = obj1.getNum();
2719       obj1.free();
2720     }
2721   } else {
2722     m[0] = 1; m[1] = 0;
2723     m[2] = 0; m[3] = 1;
2724     m[4] = 0; m[5] = 0;
2725   }
2726   matrixObj.free();
2727
2728   // get resources
2729   dict->lookup("Resources", &resObj);
2730   resDict = resObj.isDict() ? resObj.getDict() : (Dict *)NULL;
2731
2732   // draw it
2733   ++formDepth;
2734   doForm1(str, resDict, m, bbox);
2735   --formDepth;
2736
2737   resObj.free();
2738 }
2739
2740 void Gfx::doAnnot(Object *str, double xMin, double yMin,
2741                   double xMax, double yMax) {
2742   Dict *dict, *resDict;
2743   Object matrixObj, bboxObj, resObj;
2744   Object obj1;
2745   double m[6], bbox[6], ictm[6];
2746   double *ctm;
2747   double formX0, formY0, formX1, formY1;
2748   double annotX0, annotY0, annotX1, annotY1;
2749   double det, x, y, sx, sy;
2750   int i;
2751
2752   // get stream dict
2753   dict = str->streamGetDict();
2754
2755   // get the form bounding box
2756   dict->lookup("BBox", &bboxObj);
2757   if (!bboxObj.isArray()) {
2758     bboxObj.free();
2759     error(getPos(), "Bad form bounding box");
2760     return;
2761   }
2762   for (i = 0; i < 4; ++i) {
2763     bboxObj.arrayGet(i, &obj1);
2764     bbox[i] = obj1.getNum();
2765     obj1.free();
2766   }
2767   bboxObj.free();
2768
2769   // get the form matrix
2770   dict->lookup("Matrix", &matrixObj);
2771   if (matrixObj.isArray()) {
2772     for (i = 0; i < 6; ++i) {
2773       matrixObj.arrayGet(i, &obj1);
2774       m[i] = obj1.getNum();
2775       obj1.free();
2776     }
2777   } else {
2778     m[0] = 1; m[1] = 0;
2779     m[2] = 0; m[3] = 1;
2780     m[4] = 0; m[5] = 0;
2781   }
2782   matrixObj.free();
2783
2784   // transform the form bbox from form space to user space
2785   formX0 = bbox[0] * m[0] + bbox[1] * m[2] + m[4];
2786   formY0 = bbox[0] * m[1] + bbox[1] * m[3] + m[5];
2787   formX1 = bbox[2] * m[0] + bbox[3] * m[2] + m[4];
2788   formY1 = bbox[2] * m[1] + bbox[3] * m[3] + m[5];
2789
2790   // transform the annotation bbox from default user space to user
2791   // space: (bbox * baseMatrix) * iCTM
2792   ctm = state->getCTM();
2793   det = 1 / (ctm[0] * ctm[3] - ctm[1] * ctm[2]);
2794   ictm[0] = ctm[3] * det;
2795   ictm[1] = -ctm[1] * det;
2796   ictm[2] = -ctm[2] * det;
2797   ictm[3] = ctm[0] * det;
2798   ictm[4] = (ctm[2] * ctm[5] - ctm[3] * ctm[4]) * det;
2799   ictm[5] = (ctm[1] * ctm[4] - ctm[0] * ctm[5]) * det;
2800   x = baseMatrix[0] * xMin + baseMatrix[2] * yMin + baseMatrix[4];
2801   y = baseMatrix[1] * xMin + baseMatrix[3] * yMin + baseMatrix[5];
2802   annotX0 = ictm[0] * x + ictm[2] * y + ictm[4];
2803   annotY0 = ictm[1] * x + ictm[3] * y + ictm[5];
2804   x = baseMatrix[0] * xMax + baseMatrix[2] * yMax + baseMatrix[4];
2805   y = baseMatrix[1] * xMax + baseMatrix[3] * yMax + baseMatrix[5];
2806   annotX1 = ictm[0] * x + ictm[2] * y + ictm[4];
2807   annotY1 = ictm[1] * x + ictm[3] * y + ictm[5];
2808
2809   // swap min/max coords
2810   if (formX0 > formX1) {
2811     x = formX0; formX0 = formX1; formX1 = x;
2812   }
2813   if (formY0 > formY1) {
2814     y = formY0; formY0 = formY1; formY1 = y;
2815   }
2816   if (annotX0 > annotX1) {
2817     x = annotX0; annotX0 = annotX1; annotX1 = x;
2818   }
2819   if (annotY0 > annotY1) {
2820     y = annotY0; annotY0 = annotY1; annotY1 = y;
2821   }
2822
2823   // scale the form to fit the annotation bbox
2824   if (formX1 == formX0) {
2825     // this shouldn't happen
2826     sx = 1;
2827   } else {
2828     sx = (annotX1 - annotX0) / (formX1 - formX0);
2829   }
2830   if (formY1 == formY0) {
2831     // this shouldn't happen
2832     sy = 1;
2833   } else {
2834     sy = (annotY1 - annotY0) / (formY1 - formY0);
2835   }
2836   m[0] *= sx;
2837   m[2] *= sx;
2838   m[4] = (m[4] - formX0) * sx + annotX0;
2839   m[1] *= sy;
2840   m[3] *= sy;
2841   m[5] = (m[5] - formY0) * sy + annotY0;
2842
2843   // get resources
2844   dict->lookup("Resources", &resObj);
2845   resDict = resObj.isDict() ? resObj.getDict() : (Dict *)NULL;
2846
2847   // draw it
2848   doForm1(str, resDict, m, bbox);
2849
2850   resObj.free();
2851   bboxObj.free();
2852 }
2853
2854 void Gfx::doForm1(Object *str, Dict *resDict, double *matrix, double *bbox) {
2855   Parser *oldParser;
2856   double oldBaseMatrix[6];
2857   int i;
2858
2859   // push new resources on stack
2860   pushResources(resDict);
2861
2862   // save current graphics state
2863   saveState();
2864
2865   // kill any pre-existing path
2866   state->clearPath();
2867
2868   // save current parser
2869   oldParser = parser;
2870
2871   // set form transformation matrix
2872   state->concatCTM(matrix[0], matrix[1], matrix[2],
2873                    matrix[3], matrix[4], matrix[5]);
2874   out->updateCTM(state, matrix[0], matrix[1], matrix[2],
2875                  matrix[3], matrix[4], matrix[5]);
2876
2877   // set new base matrix
2878   for (i = 0; i < 6; ++i) {
2879     oldBaseMatrix[i] = baseMatrix[i];
2880     baseMatrix[i] = state->getCTM()[i];
2881   }
2882
2883   // set form bounding box
2884   state->moveTo(bbox[0], bbox[1]);
2885   state->lineTo(bbox[2], bbox[1]);
2886   state->lineTo(bbox[2], bbox[3]);
2887   state->lineTo(bbox[0], bbox[3]);
2888   state->closePath();
2889   state->clip();
2890   out->clip(state);
2891   state->clearPath();
2892
2893   // draw the form
2894   display(str, gFalse);
2895
2896   // restore base matrix
2897   for (i = 0; i < 6; ++i) {
2898     baseMatrix[i] = oldBaseMatrix[i];
2899   }
2900
2901   // restore parser
2902   parser = oldParser;
2903
2904   // restore graphics state
2905   restoreState();
2906
2907   // pop resource stack
2908   popResources();
2909
2910   return;
2911 }
2912
2913 //------------------------------------------------------------------------
2914 // in-line image operators
2915 //------------------------------------------------------------------------
2916
2917 void Gfx::opBeginImage(Object args[], int numArgs) {
2918   Stream *str;
2919   int c1, c2;
2920
2921   // build dict/stream
2922   str = buildImageStream();
2923
2924   // display the image
2925   if (str) {
2926     doImage(NULL, str, gTrue);
2927   
2928     // skip 'EI' tag
2929     c1 = str->getBaseStream()->getChar();
2930     c2 = str->getBaseStream()->getChar();
2931     while (!(c1 == 'E' && c2 == 'I') && c2 != EOF) {
2932       c1 = c2;
2933       c2 = str->getBaseStream()->getChar();
2934     }
2935     delete str;
2936   }
2937 }
2938
2939 Stream *Gfx::buildImageStream() {
2940   Object dict;
2941   Object obj;
2942   char *key;
2943   Stream *str;
2944
2945   // build dictionary
2946   dict.initDict(xref);
2947   parser->getObj(&obj);
2948   while (!obj.isCmd("ID") && !obj.isEOF()) {
2949     if (!obj.isName()) {
2950       error(getPos(), "Inline image dictionary key must be a name object");
2951       obj.free();
2952     } else {
2953       key = copyString(obj.getName());
2954       obj.free();
2955       parser->getObj(&obj);
2956       if (obj.isEOF() || obj.isError()) {
2957         gfree(key);
2958         break;
2959       }
2960       dict.dictAdd(key, &obj);
2961     }
2962     parser->getObj(&obj);
2963   }
2964   if (obj.isEOF()) {
2965     error(getPos(), "End of file in inline image");
2966     obj.free();
2967     dict.free();
2968     return NULL;
2969   }
2970   obj.free();
2971
2972   // make stream
2973   str = new EmbedStream(parser->getStream(), &dict);
2974   str = str->addFilters(&dict);
2975
2976   return str;
2977 }
2978
2979 void Gfx::opImageData(Object args[], int numArgs) {
2980   error(getPos(), "Internal: got 'ID' operator");
2981 }
2982
2983 void Gfx::opEndImage(Object args[], int numArgs) {
2984   error(getPos(), "Internal: got 'EI' operator");
2985 }
2986
2987 //------------------------------------------------------------------------
2988 // type 3 font operators
2989 //------------------------------------------------------------------------
2990
2991 void Gfx::opSetCharWidth(Object args[], int numArgs) {
2992   out->type3D0(state, args[0].getNum(), args[1].getNum());
2993 }
2994
2995 void Gfx::opSetCacheDevice(Object args[], int numArgs) {
2996   out->type3D1(state, args[0].getNum(), args[1].getNum(),
2997                args[2].getNum(), args[3].getNum(),
2998                args[4].getNum(), args[5].getNum());
2999 }
3000
3001 //------------------------------------------------------------------------
3002 // compatibility operators
3003 //------------------------------------------------------------------------
3004
3005 void Gfx::opBeginIgnoreUndef(Object args[], int numArgs) {
3006   ++ignoreUndef;
3007 }
3008
3009 void Gfx::opEndIgnoreUndef(Object args[], int numArgs) {
3010   if (ignoreUndef > 0)
3011     --ignoreUndef;
3012 }
3013
3014 //------------------------------------------------------------------------
3015 // marked content operators
3016 //------------------------------------------------------------------------
3017
3018 void Gfx::opBeginMarkedContent(Object args[], int numArgs) {
3019   if (printCommands) {
3020     printf("  marked content: %s ", args[0].getName());
3021     if (numArgs == 2)
3022       args[2].print(stdout);
3023     printf("\n");
3024     fflush(stdout);
3025   }
3026 }
3027
3028 void Gfx::opEndMarkedContent(Object args[], int numArgs) {
3029 }
3030
3031 void Gfx::opMarkPoint(Object args[], int numArgs) {
3032   if (printCommands) {
3033     printf("  mark point: %s ", args[0].getName());
3034     if (numArgs == 2)
3035       args[2].print(stdout);
3036     printf("\n");
3037     fflush(stdout);
3038   }
3039 }
3040
3041 //------------------------------------------------------------------------
3042 // misc
3043 //------------------------------------------------------------------------
3044
3045 void Gfx::saveState() {
3046   out->saveState(state);
3047   state = state->save();
3048 }
3049
3050 void Gfx::restoreState() {
3051   state = state->restore();
3052   out->restoreState(state);
3053 }
3054
3055 void Gfx::pushResources(Dict *resDict) {
3056   res = new GfxResources(xref, resDict, res);
3057 }
3058
3059 void Gfx::popResources() {
3060   GfxResources *resPtr;
3061
3062   resPtr = res->getNext();
3063   delete res;
3064   res = resPtr;
3065 }