PSOutputDev.cc 210 KB
Newer Older
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1 2 3 4
//========================================================================
//
// PSOutputDev.cc
//
Albert Astals Cid's avatar
Albert Astals Cid committed
5
// Copyright 1996-2013 Glyph & Cog, LLC
Kristian Høgsberg's avatar
Kristian Høgsberg committed
6 7 8
//
//========================================================================

9 10 11 12
//========================================================================
//
// Modified under the Poppler project - http://poppler.freedesktop.org
//
13 14 15
// All changes made under the Poppler project to this file are licensed
// under GPL version 2 or later
//
16 17
// Copyright (C) 2005 Martin Kretzschmar <martink@gnome.org>
// Copyright (C) 2005, 2006 Kristian Høgsberg <krh@redhat.com>
18
// Copyright (C) 2006-2009, 2011-2013, 2015-2018 Albert Astals Cid <aacid@kde.org>
19 20
// Copyright (C) 2006 Jeff Muizelaar <jeff@infidigm.net>
// Copyright (C) 2007, 2008 Brad Hards <bradh@kde.org>
21
// Copyright (C) 2008, 2009 Koji Otani <sho@bbr.jp>
Hib Eris's avatar
Hib Eris committed
22
// Copyright (C) 2008, 2010 Hib Eris <hib@hiberis.nl>
23
// Copyright (C) 2009-2013 Thomas Freitag <Thomas.Freitag@alfa.de>
24
// Copyright (C) 2009 Till Kamppeter <till.kamppeter@gmail.com>
25
// Copyright (C) 2009 Carlos Garcia Campos <carlosgc@gnome.org>
Albert Astals Cid's avatar
Albert Astals Cid committed
26
// Copyright (C) 2009, 2011, 2012, 2014-2017 William Bader <williambader@hotmail.com>
27
// Copyright (C) 2009 Kovid Goyal <kovid@kovidgoyal.net>
28
// Copyright (C) 2009-2011, 2013-2015, 2017 Adrian Johnson <ajohnson@redneon.com>
Fabio D'Urso's avatar
Fabio D'Urso committed
29
// Copyright (C) 2012, 2014 Fabio D'Urso <fabiodurso@hotmail.it>
30
// Copyright (C) 2012 Lu Wang <coolwanglu@gmail.com>
Albert Astals Cid's avatar
Albert Astals Cid committed
31
// Copyright (C) 2014 Till Kamppeter <till.kamppeter@gmail.com>
Albert Astals Cid's avatar
Albert Astals Cid committed
32
// Copyright (C) 2015 Marek Kasik <mkasik@redhat.com>
Albert Astals Cid's avatar
Albert Astals Cid committed
33
// Copyright (C) 2016 Caolán McNamara <caolanm@redhat.com>
34
// Copyright (C) 2018 Klarälvdalens Datakonsult AB, a KDAB Group company, <info@kdab.com>. Work sponsored by the LiMux project of the city of Munich
35
// Copyright (C) 2018 Adam Reichold <adam.reichold@t-online.de>
36
// Copyright (C) 2018 Philipp Knechtges <philipp-dev@knechtges.com>
37 38 39 40 41 42
//
// To see a description of the changes please see the Changelog file that
// came with your tarball or type make ChangeLog if you are building from git
//
//========================================================================

Kristian Høgsberg's avatar
Kristian Høgsberg committed
43 44 45 46 47 48 49 50 51 52 53
#include <config.h>

#ifdef USE_GCC_PRAGMAS
#pragma implementation
#endif

#include <stdio.h>
#include <stddef.h>
#include <stdarg.h>
#include <signal.h>
#include <math.h>
54
#include <limits.h>
55
#include <algorithm>
56
#include <array>
Kristian Høgsberg's avatar
Kristian Høgsberg committed
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
#include "goo/GooString.h"
#include "goo/GooList.h"
#include "poppler-config.h"
#include "GlobalParams.h"
#include "Object.h"
#include "Error.h"
#include "Function.h"
#include "Gfx.h"
#include "GfxState.h"
#include "GfxFont.h"
#include "UnicodeMap.h"
#include <fofi/FoFiType1C.h>
#include <fofi/FoFiTrueType.h>
#include "Catalog.h"
#include "Page.h"
#include "Stream.h"
73
#ifdef ENABLE_ZLIB
74 75
#  include "FlateEncoder.h"
#endif
76
#ifdef ENABLE_ZLIB_UNCOMPRESS
77 78
#  include "FlateStream.h"
#endif
Kristian Høgsberg's avatar
Kristian Høgsberg committed
79
#include "Annot.h"
80 81
#include "XRef.h"
#include "PreScanOutputDev.h"
82
#include "FileSpec.h"
83
#include "CharCodeToUnicode.h"
84
#ifdef HAVE_SPLASH
85 86 87 88
#  include "splash/Splash.h"
#  include "splash/SplashBitmap.h"
#  include "SplashOutputDev.h"
#endif
Kristian Høgsberg's avatar
Kristian Høgsberg committed
89
#include "PSOutputDev.h"
Hib Eris's avatar
Hib Eris committed
90
#include "PDFDoc.h"
Kristian Høgsberg's avatar
Kristian Høgsberg committed
91 92 93 94 95 96

#ifdef MACOS
// needed for setting type/creator of MacOS files
#include "ICSupport.h"
#endif

97 98 99 100 101 102 103
// the MSVC math.h doesn't define this
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif

//------------------------------------------------------------------------

104 105
// Max size of a slice when rasterizing pages, in pixels.
#define rasterizationSliceSize 20000000
106

Kristian Høgsberg's avatar
Kristian Høgsberg committed
107 108 109 110
//------------------------------------------------------------------------
// PostScript prolog and setup
//------------------------------------------------------------------------

111 112 113 114 115 116 117
// The '~' escapes mark prolog code that is emitted only in certain
// levels:
//
//   ~[123][sn]
//      ^   ^----- s=psLevel*Sep, n=psLevel*
//      +----- 1=psLevel1*, 2=psLevel2*, 3=psLevel3*

118
static const char *prolog[] = {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
119 120 121
  "/xpdf 75 dict def xpdf begin",
  "% PDF special state",
  "/pdfDictSize 15 def",
122
  "~1sn",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
123 124 125 126 127 128
  "/pdfStates 64 array def",
  "  0 1 63 {",
  "    pdfStates exch pdfDictSize dict",
  "    dup /pdfStateIdx 3 index put",
  "    put",
  "  } for",
129
  "~123sn",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
130 131
  "/pdfSetup {",
  "  /setpagedevice where {",
132 133 134 135 136 137 138 139 140
  "    pop 2 dict begin",
  "      /Policies 1 dict dup begin /PageSize 6 def end def",
  "      { /Duplex true def } if",
  "    currentdict end setpagedevice",
  "  } {",
  "    pop",
  "  } ifelse",
  "} def",
  "/pdfSetupPaper {",
141 142 143
  "  % Change paper size, but only if different from previous paper size otherwise",
  "  % duplex fails. PLRM specifies a tolerance of 5 pts when matching paper size",
  "  % so we use the same when checking if the size changes.",
144
  "  /setpagedevice where {",
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
  "    pop currentpagedevice",
  "    /PageSize known {",
  "      2 copy",
  "      currentpagedevice /PageSize get aload pop",
  "      exch 4 1 roll",
  "      sub abs 5 gt",
  "      3 1 roll",
  "      sub abs 5 gt",
  "      or",
  "    } {",
  "      true",
  "    } ifelse",
  "    {",
  "      2 array astore",
  "      2 dict begin",
  "        /PageSize exch def",
  "        /ImagingBBox null def",
  "      currentdict end",
  "      setpagedevice",
  "    } {",
  "      pop pop",
  "    } ifelse",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
167
  "  } {",
168
  "    pop",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
169 170
  "  } ifelse",
  "} def",
171
  "~1sn",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
172 173
  "/pdfOpNames [",
  "  /pdfFill /pdfStroke /pdfLastFill /pdfLastStroke",
174
  "  /pdfTextMat /pdfFontSize /pdfCharSpacing /pdfTextRender /pdfPatternCS",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
175 176
  "  /pdfTextRise /pdfWordSpacing /pdfHorizScaling /pdfTextClipPath",
  "] def",
177
  "~123sn",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
178
  "/pdfStartPage {",
179
  "~1sn",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
180
  "  pdfStates 0 get begin",
181
  "~23sn",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
182
  "  pdfDictSize dict begin",
183 184 185 186 187 188 189 190 191 192 193 194
  "~23n",
  "  /pdfFillCS [] def",
  "  /pdfFillXform {} def",
  "  /pdfStrokeCS [] def",
  "  /pdfStrokeXform {} def",
  "~1n",
  "  /pdfFill 0 def",
  "  /pdfStroke 0 def",
  "~1s",
  "  /pdfFill [0 0 0 1] def",
  "  /pdfStroke [0 0 0 1] def",
  "~23sn",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
195 196
  "  /pdfFill [0] def",
  "  /pdfStroke [0] def",
197 198
  "  /pdfFillOP false def",
  "  /pdfStrokeOP false def",
199 200
  "~3sn",
  "  /pdfOPM false def",
201
  "~123sn",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
202 203 204 205 206 207
  "  /pdfLastFill false def",
  "  /pdfLastStroke false def",
  "  /pdfTextMat [1 0 0 1 0 0] def",
  "  /pdfFontSize 0 def",
  "  /pdfCharSpacing 0 def",
  "  /pdfTextRender 0 def",
208
  "  /pdfPatternCS false def", 
Kristian Høgsberg's avatar
Kristian Høgsberg committed
209 210 211 212 213 214
  "  /pdfTextRise 0 def",
  "  /pdfWordSpacing 0 def",
  "  /pdfHorizScaling 1 def",
  "  /pdfTextClipPath [] def",
  "} def",
  "/pdfEndPage { end } def",
215
  "~23s",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
  "% separation convention operators",
  "/findcmykcustomcolor where {",
  "  pop",
  "}{",
  "  /findcmykcustomcolor { 5 array astore } def",
  "} ifelse",
  "/setcustomcolor where {",
  "  pop",
  "}{",
  "  /setcustomcolor {",
  "    exch",
  "    [ exch /Separation exch dup 4 get exch /DeviceCMYK exch",
  "      0 4 getinterval cvx",
  "      [ exch /dup load exch { mul exch dup } /forall load",
  "        /pop load dup ] cvx",
  "    ] setcolorspace setcolor",
  "  } def",
  "} ifelse",
  "/customcolorimage where {",
  "  pop",
  "}{",
  "  /customcolorimage {",
  "    gsave",
  "    [ exch /Separation exch dup 4 get exch /DeviceCMYK exch",
  "      0 4 getinterval",
  "      [ exch /dup load exch { mul exch dup } /forall load",
  "        /pop load dup ] cvx",
  "    ] setcolorspace",
  "    10 dict begin",
  "      /ImageType 1 def",
  "      /DataSource exch def",
  "      /ImageMatrix exch def",
  "      /BitsPerComponent exch def",
  "      /Height exch def",
  "      /Width exch def",
  "      /Decode [1 0] def",
  "    currentdict end",
  "    image",
  "    grestore",
  "  } def",
  "} ifelse",
257
  "~123sn",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
258
  "% PDF color state",
259 260 261 262 263 264 265 266 267 268 269
  "~1n",
  "/g { dup /pdfFill exch def setgray",
  "     /pdfLastFill true def /pdfLastStroke false def } def",
  "/G { dup /pdfStroke exch def setgray",
  "     /pdfLastStroke true def /pdfLastFill false def } def",
  "/fCol {",
  "  pdfLastFill not {",
  "    pdfFill setgray",
  "    /pdfLastFill true def /pdfLastStroke false def",
  "  } if",
  "} def",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
270 271
  "/sCol {",
  "  pdfLastStroke not {",
272
  "    pdfStroke setgray",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
273 274 275
  "    /pdfLastStroke true def /pdfLastFill false def",
  "  } if",
  "} def",
276 277 278 279 280
  "~1s",
  "/k { 4 copy 4 array astore /pdfFill exch def setcmykcolor",
  "     /pdfLastFill true def /pdfLastStroke false def } def",
  "/K { 4 copy 4 array astore /pdfStroke exch def setcmykcolor",
  "     /pdfLastStroke true def /pdfLastFill false def } def",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
281 282
  "/fCol {",
  "  pdfLastFill not {",
283 284 285 286 287 288 289 290 291 292
  "    pdfFill aload pop setcmykcolor",
  "    /pdfLastFill true def /pdfLastStroke false def",
  "  } if",
  "} def",
  "/sCol {",
  "  pdfLastStroke not {",
  "    pdfStroke aload pop setcmykcolor",
  "    /pdfLastStroke true def /pdfLastFill false def",
  "  } if",
  "} def",
293 294
  "~3n",
  "/opm { dup /pdfOPM exch def",
295
  "      /setoverprintmode where{pop setoverprintmode}{pop}ifelse  } def",
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
  "~23n",
  "/cs { /pdfFillXform exch def dup /pdfFillCS exch def",
  "      setcolorspace } def",
  "/CS { /pdfStrokeXform exch def dup /pdfStrokeCS exch def",
  "      setcolorspace } def",
  "/sc { pdfLastFill not { pdfFillCS setcolorspace } if",
  "      dup /pdfFill exch def aload pop pdfFillXform setcolor",
  "     /pdfLastFill true def /pdfLastStroke false def } def",
  "/SC { pdfLastStroke not { pdfStrokeCS setcolorspace } if",
  "      dup /pdfStroke exch def aload pop pdfStrokeXform setcolor",
  "     /pdfLastStroke true def /pdfLastFill false def } def",
  "/op { /pdfFillOP exch def",
  "      pdfLastFill { pdfFillOP setoverprint } if } def",
  "/OP { /pdfStrokeOP exch def",
  "      pdfLastStroke { pdfStrokeOP setoverprint } if } def",
  "/fCol {",
  "  pdfLastFill not {",
  "    pdfFillCS setcolorspace",
  "    pdfFill aload pop pdfFillXform setcolor",
  "    pdfFillOP setoverprint",
  "    /pdfLastFill true def /pdfLastStroke false def",
  "  } if",
  "} def",
  "/sCol {",
  "  pdfLastStroke not {",
  "    pdfStrokeCS setcolorspace",
  "    pdfStroke aload pop pdfStrokeXform setcolor",
  "    pdfStrokeOP setoverprint",
  "    /pdfLastStroke true def /pdfLastFill false def",
  "  } if",
  "} def",
327 328
  "~3s",
  "/opm { dup /pdfOPM exch def",
329
  "      /setoverprintmode where{pop setoverprintmode}{pop}ifelse } def",
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
  "~23s",
  "/k { 4 copy 4 array astore /pdfFill exch def setcmykcolor",
  "     /pdfLastFill true def /pdfLastStroke false def } def",
  "/K { 4 copy 4 array astore /pdfStroke exch def setcmykcolor",
  "     /pdfLastStroke true def /pdfLastFill false def } def",
  "/ck { 6 copy 6 array astore /pdfFill exch def",
  "      findcmykcustomcolor exch setcustomcolor",
  "      /pdfLastFill true def /pdfLastStroke false def } def",
  "/CK { 6 copy 6 array astore /pdfStroke exch def",
  "      findcmykcustomcolor exch setcustomcolor",
  "      /pdfLastStroke true def /pdfLastFill false def } def",
  "/op { /pdfFillOP exch def",
  "      pdfLastFill { pdfFillOP setoverprint } if } def",
  "/OP { /pdfStrokeOP exch def",
  "      pdfLastStroke { pdfStrokeOP setoverprint } if } def",
  "/fCol {",
  "  pdfLastFill not {",
  "    pdfFill aload length 4 eq {",
348 349 350 351
  "      setcmykcolor",
  "    }{",
  "      findcmykcustomcolor exch setcustomcolor",
  "    } ifelse",
352
  "    pdfFillOP setoverprint",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
353 354 355
  "    /pdfLastFill true def /pdfLastStroke false def",
  "  } if",
  "} def",
356 357 358 359 360 361 362 363 364 365 366 367
  "/sCol {",
  "  pdfLastStroke not {",
  "    pdfStroke aload length 4 eq {",
  "      setcmykcolor",
  "    }{",
  "      findcmykcustomcolor exch setcustomcolor",
  "    } ifelse",
  "    pdfStrokeOP setoverprint",
  "    /pdfLastStroke true def /pdfLastFill false def",
  "  } if",
  "} def",
  "~123sn",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
  "% build a font",
  "/pdfMakeFont {",
  "  4 3 roll findfont",
  "  4 2 roll matrix scale makefont",
  "  dup length dict begin",
  "    { 1 index /FID ne { def } { pop pop } ifelse } forall",
  "    /Encoding exch def",
  "    currentdict",
  "  end",
  "  definefont pop",
  "} def",
  "/pdfMakeFont16 {",
  "  exch findfont",
  "  dup length dict begin",
  "    { 1 index /FID ne { def } { pop pop } ifelse } forall",
  "    /WMode exch def",
  "    currentdict",
  "  end",
  "  definefont pop",
  "} def",
388
  "~3sn",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
389 390 391 392 393 394 395 396 397 398 399 400 401
  "/pdfMakeFont16L3 {",
  "  1 index /CIDFont resourcestatus {",
  "    pop pop 1 index /CIDFont findresource /CIDFontType known",
  "  } {",
  "    false",
  "  } ifelse",
  "  {",
  "    0 eq { /Identity-H } { /Identity-V } ifelse",
  "    exch 1 array astore composefont pop",
  "  } {",
  "    pdfMakeFont16",
  "  } ifelse",
  "} def",
402
  "~123sn",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
403
  "% graphics state operators",
404
  "~1sn",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
405 406 407 408 409 410 411
  "/q {",
  "  gsave",
  "  pdfOpNames length 1 sub -1 0 { pdfOpNames exch get load } for",
  "  pdfStates pdfStateIdx 1 add get begin",
  "  pdfOpNames { exch def } forall",
  "} def",
  "/Q { end grestore } def",
412 413 414 415 416 417 418 419 420 421 422 423
  "~23sn",
  "/q { gsave pdfDictSize dict begin } def",
  "/Q {",
  "  end grestore",
  "  /pdfLastFill where {",
  "    pop",
  "    pdfLastFill {",
  "      pdfFillOP setoverprint",
  "    } {",
  "      pdfStrokeOP setoverprint",
  "    } ifelse",
  "  } if",
424 425 426
  "~3sn",
  "  /pdfOPM where {",
  "    pop",
427
  "    pdfOPM /setoverprintmode where{pop setoverprintmode}{pop}ifelse ",
428 429
  "  } if",
  "~23sn",
430 431
  "} def",
  "~123sn",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
  "/cm { concat } def",
  "/d { setdash } def",
  "/i { setflat } def",
  "/j { setlinejoin } def",
  "/J { setlinecap } def",
  "/M { setmiterlimit } def",
  "/w { setlinewidth } def",
  "% path segment operators",
  "/m { moveto } def",
  "/l { lineto } def",
  "/c { curveto } def",
  "/re { 4 2 roll moveto 1 index 0 rlineto 0 exch rlineto",
  "      neg 0 rlineto closepath } def",
  "/h { closepath } def",
  "% path painting operators",
  "/S { sCol stroke } def",
  "/Sf { fCol stroke } def",
  "/f { fCol fill } def",
  "/f* { fCol eofill } def",
  "% clipping operators",
  "/W { clip newpath } def",
  "/W* { eoclip newpath } def",
454
  "/Ws { strokepath clip newpath } def",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
455 456 457 458 459 460 461
  "% text state operators",
  "/Tc { /pdfCharSpacing exch def } def",
  "/Tf { dup /pdfFontSize exch def",
  "      dup pdfHorizScaling mul exch matrix scale",
  "      pdfTextMat matrix concatmatrix dup 4 0 put dup 5 0 put",
  "      exch findfont exch makefont setfont } def",
  "/Tr { /pdfTextRender exch def } def",
462
  "/Tp { /pdfPatternCS exch def } def", 
Kristian Høgsberg's avatar
Kristian Høgsberg committed
463 464 465 466 467 468 469
  "/Ts { /pdfTextRise exch def } def",
  "/Tw { /pdfWordSpacing exch def } def",
  "/Tz { /pdfHorizScaling exch def } def",
  "% text positioning operators",
  "/Td { pdfTextMat transform moveto } def",
  "/Tm { /pdfTextMat exch def } def",
  "% text string operators",
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
  "/xyshow where {",
  "  pop",
  "  /xyshow2 {",
  "    dup length array",
  "    0 2 2 index length 1 sub {",
  "      2 index 1 index 2 copy get 3 1 roll 1 add get",
  "      pdfTextMat dtransform",
  "      4 2 roll 2 copy 6 5 roll put 1 add 3 1 roll dup 4 2 roll put",
  "    } for",
  "    exch pop",
  "    xyshow",
  "  } def",
  "}{",
  "  /xyshow2 {",
  "    currentfont /FontType get 0 eq {",
  "      0 2 3 index length 1 sub {",
  "        currentpoint 4 index 3 index 2 getinterval show moveto",
  "        2 copy get 2 index 3 2 roll 1 add get",
  "        pdfTextMat dtransform rmoveto",
  "      } for",
  "    } {",
  "      0 1 3 index length 1 sub {",
  "        currentpoint 4 index 3 index 1 getinterval show moveto",
  "        2 copy 2 mul get 2 index 3 2 roll 2 mul 1 add get",
  "        pdfTextMat dtransform rmoveto",
  "      } for",
  "    } ifelse",
  "    pop pop",
  "  } def",
  "} ifelse",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
500 501
  "/cshow where {",
  "  pop",
502 503 504 505 506 507 508 509
  "  /xycp {", // xycharpath
  "    0 3 2 roll",
  "    {",
  "      pop pop currentpoint 3 2 roll",
  "      1 string dup 0 4 3 roll put false charpath moveto",
  "      2 copy get 2 index 2 index 1 add get",
  "      pdfTextMat dtransform rmoveto",
  "      2 add",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
510 511 512 513
  "    } exch cshow",
  "    pop pop",
  "  } def",
  "}{",
514
  "  /xycp {", // xycharpath
Kristian Høgsberg's avatar
Kristian Høgsberg committed
515
  "    currentfont /FontType get 0 eq {",
516 517 518 519
  "      0 2 3 index length 1 sub {",
  "        currentpoint 4 index 3 index 2 getinterval false charpath moveto",
  "        2 copy get 2 index 3 2 roll 1 add get",
  "        pdfTextMat dtransform rmoveto",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
520 521
  "      } for",
  "    } {",
522 523 524 525 526
  "      0 1 3 index length 1 sub {",
  "        currentpoint 4 index 3 index 1 getinterval false charpath moveto",
  "        2 copy 2 mul get 2 index 3 2 roll 2 mul 1 add get",
  "        pdfTextMat dtransform rmoveto",
  "      } for",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
527 528 529 530 531 532 533
  "    } ifelse",
  "    pop pop",
  "  } def",
  "} ifelse",
  "/Tj {",
  "  fCol",  // because stringwidth has to draw Type 3 chars
  "  0 pdfTextRise pdfTextMat dtransform rmoveto",
534 535 536
  "  currentpoint 4 2 roll",
  "  pdfTextRender 1 and 0 eq {",
  "    2 copy xyshow2",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
537 538
  "  } if",
  "  pdfTextRender 3 and dup 1 eq exch 2 eq or {",
539 540
  "    3 index 3 index moveto",
  "    2 copy",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
541
  "    currentfont /FontType get 3 eq { fCol } { sCol } ifelse",
542
  "    xycp currentpoint stroke moveto",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
543
  "  } if",
544 545
  "  pdfTextRender 4 and 0 ne {",
  "    4 2 roll moveto xycp",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
546 547 548 549 550 551 552 553
  "    /pdfTextClipPath [ pdfTextClipPath aload pop",
  "      {/moveto cvx}",
  "      {/lineto cvx}",
  "      {/curveto cvx}",
  "      {/closepath cvx}",
  "    pathforall ] def",
  "    currentpoint newpath moveto",
  "  } {",
554
  "    pop pop pop pop",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
555 556 557
  "  } ifelse",
  "  0 pdfTextRise neg pdfTextMat dtransform rmoveto",
  "} def",
558
  "/TJm { 0.001 mul pdfFontSize mul pdfHorizScaling mul neg 0",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
559
  "       pdfTextMat dtransform rmoveto } def",
560
  "/TJmV { 0.001 mul pdfFontSize mul neg 0 exch",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
561 562 563
  "        pdfTextMat dtransform rmoveto } def",
  "/Tclip { pdfTextClipPath cvx exec clip newpath",
  "         /pdfTextClipPath [] def } def",
564 565
  "/Tclip* { pdfTextClipPath cvx exec eoclip newpath",
  "         /pdfTextClipPath [] def } def",
566
  "~1ns",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
567 568 569 570 571
  "% Level 1 image operators",
  "/pdfIm1 {",
  "  /pdfImBuf1 4 index string def",
  "  { currentfile pdfImBuf1 readhexstring pop } image",
  "} def",
572 573 574 575
  "/pdfIm1Bin {",
  "  /pdfImBuf1 4 index string def",
  "  { currentfile pdfImBuf1 readstring pop } image",
  "} def",
576
  "~1s",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
577 578 579 580 581 582 583 584 585 586 587
  "/pdfIm1Sep {",
  "  /pdfImBuf1 4 index string def",
  "  /pdfImBuf2 4 index string def",
  "  /pdfImBuf3 4 index string def",
  "  /pdfImBuf4 4 index string def",
  "  { currentfile pdfImBuf1 readhexstring pop }",
  "  { currentfile pdfImBuf2 readhexstring pop }",
  "  { currentfile pdfImBuf3 readhexstring pop }",
  "  { currentfile pdfImBuf4 readhexstring pop }",
  "  true 4 colorimage",
  "} def",
588 589 590 591 592 593 594 595 596 597 598
  "/pdfIm1SepBin {",
  "  /pdfImBuf1 4 index string def",
  "  /pdfImBuf2 4 index string def",
  "  /pdfImBuf3 4 index string def",
  "  /pdfImBuf4 4 index string def",
  "  { currentfile pdfImBuf1 readstring pop }",
  "  { currentfile pdfImBuf2 readstring pop }",
  "  { currentfile pdfImBuf3 readstring pop }",
  "  { currentfile pdfImBuf4 readstring pop }",
  "  true 4 colorimage",
  "} def",
599
  "~1ns",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
600
  "/pdfImM1 {",
601
  "  fCol /pdfImBuf1 4 index 7 add 8 idiv string def",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
602 603
  "  { currentfile pdfImBuf1 readhexstring pop } imagemask",
  "} def",
604 605 606 607
  "/pdfImM1Bin {",
  "  fCol /pdfImBuf1 4 index 7 add 8 idiv string def",
  "  { currentfile pdfImBuf1 readstring pop } imagemask",
  "} def",
608 609 610 611 612 613 614
  "/pdfImStr {",
  "  2 copy exch length lt {",
  "    2 copy get exch 1 add exch",
  "  } {",
  "    ()",
  "  } ifelse",
  "} def",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
615
  "/pdfImM1a {",
616
  "  { pdfImStr } imagemask",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
617 618
  "  pop pop",
  "} def",
619
  "~23sn",
620
  "% Level 2/3 image operators",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
621
  "/pdfImBuf 100 string def",
622 623 624 625 626 627 628 629
  "/pdfImStr {",
  "  2 copy exch length lt {",
  "    2 copy get exch 1 add exch",
  "  } {",
  "    ()",
  "  } ifelse",
  "} def",
  "/skipEOD {",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
630 631 632 633
  "  { currentfile pdfImBuf readline",
  "    not { pop exit } if",
  "    (%-EOD-) eq { exit } if } loop",
  "} def",
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
  "/pdfIm { image skipEOD } def",
  "~3sn",
  "/pdfMask {",
  "  /ReusableStreamDecode filter",
  "  skipEOD",
  "  /maskStream exch def",
  "} def",
  "/pdfMaskEnd { maskStream closefile } def",
  "/pdfMaskInit {",
  "  /maskArray exch def",
  "  /maskIdx 0 def",
  "} def",
  "/pdfMaskSrc {",
  "  maskIdx maskArray length lt {",
  "    maskArray maskIdx get",
  "    /maskIdx maskIdx 1 add def",
  "  } {",
  "    ()",
  "  } ifelse",
  "} def",
654
  "~23s",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
655 656 657 658 659 660 661 662 663 664 665 666 667 668
  "/pdfImSep {",
  "  findcmykcustomcolor exch",
  "  dup /Width get /pdfImBuf1 exch string def",
  "  dup /Decode get aload pop 1 index sub /pdfImDecodeRange exch def",
  "  /pdfImDecodeLow exch def",
  "  begin Width Height BitsPerComponent ImageMatrix DataSource end",
  "  /pdfImData exch def",
  "  { pdfImData pdfImBuf1 readstring pop",
  "    0 1 2 index length 1 sub {",
  "      1 index exch 2 copy get",
  "      pdfImDecodeRange mul 255 div pdfImDecodeLow add round cvi",
  "      255 exch sub put",
  "    } for }",
  "  6 5 roll customcolorimage",
669
  "  skipEOD",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
670
  "} def",
671
  "~23sn",
672
  "/pdfImM { fCol imagemask skipEOD } def",
673
  "~123sn",
674
  "/pr { 2 index 2 index 3 2 roll putinterval 4 add } def",
675 676 677 678 679 680 681 682 683 684 685
  "/pdfImClip {",
  "  gsave",
  "  0 2 4 index length 1 sub {",
  "    dup 4 index exch 2 copy",
  "    get 5 index div put",
  "    1 add 3 index exch 2 copy",
  "    get 3 index div put",
  "  } for",
  "  pop pop rectclip",
  "} def",
  "/pdfImClipEnd { grestore } def",
686
  "~23sn",
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
  "% shading operators",
  "/colordelta {",
  "  false 0 1 3 index length 1 sub {",
  "    dup 4 index exch get 3 index 3 2 roll get sub abs 0.004 gt {",
  "      pop true",
  "    } if",
  "  } for",
  "  exch pop exch pop",
  "} def",
  "/funcCol { func n array astore } def",
  "/funcSH {",
  "  dup 0 eq {",
  "    true",
  "  } {",
  "    dup 6 eq {",
  "      false",
  "    } {",
  "      4 index 4 index funcCol dup",
  "      6 index 4 index funcCol dup",
  "      3 1 roll colordelta 3 1 roll",
  "      5 index 5 index funcCol dup",
  "      3 1 roll colordelta 3 1 roll",
  "      6 index 8 index funcCol dup",
  "      3 1 roll colordelta 3 1 roll",
  "      colordelta or or or",
  "    } ifelse",
  "  } ifelse",
  "  {",
  "    1 add",
  "    4 index 3 index add 0.5 mul exch 4 index 3 index add 0.5 mul exch",
  "    6 index 6 index 4 index 4 index 4 index funcSH",
  "    2 index 6 index 6 index 4 index 4 index funcSH",
  "    6 index 2 index 4 index 6 index 4 index funcSH",
  "    5 3 roll 3 2 roll funcSH pop pop",
  "  } {",
  "    pop 3 index 2 index add 0.5 mul 3 index  2 index add 0.5 mul",
723
  "~23n",
724
  "    funcCol sc",
725 726 727
  "~23s",
  "    funcCol aload pop k",
  "~23sn",
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
  "    dup 4 index exch mat transform m",
  "    3 index 3 index mat transform l",
  "    1 index 3 index mat transform l",
  "    mat transform l pop pop h f*",
  "  } ifelse",
  "} def",
  "/axialCol {",
  "  dup 0 lt {",
  "    pop t0",
  "  } {",
  "    dup 1 gt {",
  "      pop t1",
  "    } {",
  "      dt mul t0 add",
  "    } ifelse",
  "  } ifelse",
  "  func n array astore",
  "} def",
  "/axialSH {",
  "  dup 0 eq {",
  "    true",
  "  } {",
  "    dup 8 eq {",
  "      false",
  "    } {",
  "      2 index axialCol 2 index axialCol colordelta",
  "    } ifelse",
  "  } ifelse",
  "  {",
  "    1 add 3 1 roll 2 copy add 0.5 mul",
  "    dup 4 3 roll exch 4 index axialSH",
  "    exch 3 2 roll axialSH",
  "  } {",
761 762 763 764 765 766
  "    pop 2 copy add 0.5 mul",
  "~23n",
  "    axialCol sc",
  "~23s",
  "    axialCol aload pop k",
  "~23sn",
767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
  "    exch dup dx mul x0 add exch dy mul y0 add",
  "    3 2 roll dup dx mul x0 add exch dy mul y0 add",
  "    dx abs dy abs ge {",
  "      2 copy yMin sub dy mul dx div add yMin m",
  "      yMax sub dy mul dx div add yMax l",
  "      2 copy yMax sub dy mul dx div add yMax l",
  "      yMin sub dy mul dx div add yMin l",
  "      h f*",
  "    } {",
  "      exch 2 copy xMin sub dx mul dy div add xMin exch m",
  "      xMax sub dx mul dy div add xMax exch l",
  "      exch 2 copy xMax sub dx mul dy div add xMax exch l",
  "      xMin sub dx mul dy div add xMin exch l",
  "      h f*",
  "    } ifelse",
  "  } ifelse",
  "} def",
  "/radialCol {",
  "  dup t0 lt {",
  "    pop t0",
  "  } {",
  "    dup t1 gt {",
  "      pop t1",
  "    } if",
  "  } ifelse",
  "  func n array astore",
  "} def",
  "/radialSH {",
  "  dup 0 eq {",
  "    true",
  "  } {",
  "    dup 8 eq {",
  "      false",
  "    } {",
  "      2 index dt mul t0 add radialCol",
  "      2 index dt mul t0 add radialCol colordelta",
  "    } ifelse",
  "  } ifelse",
  "  {",
  "    1 add 3 1 roll 2 copy add 0.5 mul",
  "    dup 4 3 roll exch 4 index radialSH",
  "    exch 3 2 roll radialSH",
  "  } {",
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831
  "    pop 2 copy add 0.5 mul dt mul t0 add",
  "~23n",
  "    radialCol sc",
  "~23s",
  "    radialCol aload pop k",
  "~23sn",
  "    encl {",
  "      exch dup dx mul x0 add exch dup dy mul y0 add exch dr mul r0 add",
  "      0 360 arc h",
  "      dup dx mul x0 add exch dup dy mul y0 add exch dr mul r0 add",
  "      360 0 arcn h f",
  "    } {",
  "      2 copy",
  "      dup dx mul x0 add exch dup dy mul y0 add exch dr mul r0 add",
  "      a1 a2 arcn",
  "      dup dx mul x0 add exch dup dy mul y0 add exch dr mul r0 add",
  "      a2 a1 arcn h",
  "      dup dx mul x0 add exch dup dy mul y0 add exch dr mul r0 add",
  "      a1 a2 arc",
  "      dup dx mul x0 add exch dup dy mul y0 add exch dr mul r0 add",
  "      a2 a1 arc h f",
  "    } ifelse",
832 833 834
  "  } ifelse",
  "} def",
  "~123sn",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
835
  "end",
836
  nullptr
Kristian Høgsberg's avatar
Kristian Høgsberg committed
837 838
};

839
static const char *cmapProlog[] = {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880
  "/CIDInit /ProcSet findresource begin",
  "10 dict begin",
  "  begincmap",
  "  /CMapType 1 def",
  "  /CMapName /Identity-H def",
  "  /CIDSystemInfo 3 dict dup begin",
  "    /Registry (Adobe) def",
  "    /Ordering (Identity) def",
  "    /Supplement 0 def",
  "  end def",
  "  1 begincodespacerange",
  "    <0000> <ffff>",
  "  endcodespacerange",
  "  0 usefont",
  "  1 begincidrange",
  "    <0000> <ffff> 0",
  "  endcidrange",
  "  endcmap",
  "  currentdict CMapName exch /CMap defineresource pop",
  "end",
  "10 dict begin",
  "  begincmap",
  "  /CMapType 1 def",
  "  /CMapName /Identity-V def",
  "  /CIDSystemInfo 3 dict dup begin",
  "    /Registry (Adobe) def",
  "    /Ordering (Identity) def",
  "    /Supplement 0 def",
  "  end def",
  "  /WMode 1 def",
  "  1 begincodespacerange",
  "    <0000> <ffff>",
  "  endcodespacerange",
  "  0 usefont",
  "  1 begincidrange",
  "    <0000> <ffff> 0",
  "  endcidrange",
  "  endcmap",
  "  currentdict CMapName exch /CMap defineresource pop",
  "end",
  "end",
881
  nullptr
Kristian Høgsberg's avatar
Kristian Høgsberg committed
882 883 884 885 886 887 888
};

//------------------------------------------------------------------------
// Fonts
//------------------------------------------------------------------------

struct PSSubstFont {
889
  const char *psName;			// PostScript name
Kristian Høgsberg's avatar
Kristian Høgsberg committed
890 891 892
  double mWidth;		// width of 'm' character
};

893 894 895 896 897 898
// NB: must be in same order as base14SubstFonts in GfxFont.cc
static PSSubstFont psBase14SubstFonts[14] = {
  {"Courier",               0.600},
  {"Courier-Oblique",       0.600},
  {"Courier-Bold",          0.600},
  {"Courier-BoldOblique",   0.600},
Kristian Høgsberg's avatar
Kristian Høgsberg committed
899 900 901 902 903 904 905 906
  {"Helvetica",             0.833},
  {"Helvetica-Oblique",     0.833},
  {"Helvetica-Bold",        0.889},
  {"Helvetica-BoldOblique", 0.889},
  {"Times-Roman",           0.788},
  {"Times-Italic",          0.722},
  {"Times-Bold",            0.833},
  {"Times-BoldItalic",      0.778},
907 908 909 910 911 912 913 914 915 916
  // the last two are never used for substitution
  {"Symbol",                0},
  {"ZapfDingbats",          0}
};

// Mapping from Type 1/1C font file to PS font name.
struct PST1FontName {
  Ref fontFileID;
  GooString *psName;		// PostScript font name used for this
				//   embedded font file
Kristian Høgsberg's avatar
Kristian Høgsberg committed
917 918
};

919 920 921
// Info for 8-bit fonts
struct PSFont8Info {
  Ref fontID;
922
  int *codeToGID;		// code-to-GID mapping for TrueType fonts
923 924
};

Kristian Høgsberg's avatar
Kristian Høgsberg committed
925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
// Encoding info for substitute 16-bit font
struct PSFont16Enc {
  Ref fontID;
  GooString *enc;
};

//------------------------------------------------------------------------
// process colors
//------------------------------------------------------------------------

#define psProcessCyan     1
#define psProcessMagenta  2
#define psProcessYellow   4
#define psProcessBlack    8
#define psProcessCMYK    15

//------------------------------------------------------------------------
// PSOutCustomColor
//------------------------------------------------------------------------

class PSOutCustomColor {
public:

  PSOutCustomColor(double cA, double mA,
		   double yA, double kA, GooString *nameA);
  ~PSOutCustomColor();

952 953 954
  PSOutCustomColor(const PSOutCustomColor &) = delete;
  PSOutCustomColor& operator=(const PSOutCustomColor &) = delete;

Kristian Høgsberg's avatar
Kristian Høgsberg committed
955 956 957 958 959 960 961 962 963 964 965 966
  double c, m, y, k;
  GooString *name;
  PSOutCustomColor *next;
};

PSOutCustomColor::PSOutCustomColor(double cA, double mA,
				   double yA, double kA, GooString *nameA) {
  c = cA;
  m = mA;
  y = yA;
  k = kA;
  name = nameA;
967
  next = nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
968 969 970 971 972 973
}

PSOutCustomColor::~PSOutCustomColor() {
  delete name;
}

974 975 976 977 978 979
//------------------------------------------------------------------------

struct PSOutImgClipRect {
  int x0, x1, y0, y1;
};

980 981 982
//------------------------------------------------------------------------

struct PSOutPaperSize {
983 984
  PSOutPaperSize(GooString *nameA, int wA, int hA) { name = nameA; w = wA; h = hA; }
  ~PSOutPaperSize() { delete name; }
985 986
  PSOutPaperSize(const PSOutPaperSize &) = delete;
  PSOutPaperSize& operator=(const PSOutPaperSize &) = delete;
987
  GooString *name;
988 989 990
  int w, h;
};

Kristian Høgsberg's avatar
Kristian Høgsberg committed
991 992 993 994 995 996 997 998 999
//------------------------------------------------------------------------
// DeviceNRecoder
//------------------------------------------------------------------------

class DeviceNRecoder: public FilterStream {
public:

  DeviceNRecoder(Stream *strA, int widthA, int heightA,
		 GfxImageColorMap *colorMapA);
Albert Astals Cid's avatar
Albert Astals Cid committed
1000 1001 1002 1003
  ~DeviceNRecoder();
  StreamKind getKind() override { return strWeird; }
  void reset() override;
  int getChar() override
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1004
    { return (bufIdx >= bufSize && !fillBuf()) ? EOF : buf[bufIdx++]; }
Albert Astals Cid's avatar
Albert Astals Cid committed
1005
  int lookChar() override
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1006
    { return (bufIdx >= bufSize && !fillBuf()) ? EOF : buf[bufIdx]; }
1007
  GooString *getPSFilter(int psLevel, const char *indent) override { return nullptr; }
Albert Astals Cid's avatar
Albert Astals Cid committed
1008 1009
  GBool isBinary(GBool last = gTrue) override { return gTrue; }
  GBool isEncoder() override { return gTrue; }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030

private:

  GBool fillBuf();

  int width, height;
  GfxImageColorMap *colorMap;
  Function *func;
  ImageStream *imgStr;
  int buf[gfxColorMaxComps];
  int pixelIdx;
  int bufIdx;
  int bufSize;
};

DeviceNRecoder::DeviceNRecoder(Stream *strA, int widthA, int heightA,
			       GfxImageColorMap *colorMapA):
    FilterStream(strA) {
  width = widthA;
  height = heightA;
  colorMap = colorMapA;
1031
  imgStr = nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
  pixelIdx = 0;
  bufIdx = gfxColorMaxComps;
  bufSize = ((GfxDeviceNColorSpace *)colorMap->getColorSpace())->
              getAlt()->getNComps();
  func = ((GfxDeviceNColorSpace *)colorMap->getColorSpace())->
           getTintTransformFunc();
}

DeviceNRecoder::~DeviceNRecoder() {
  if (imgStr) {
    delete imgStr;
  }
1044 1045 1046
  if (str->isEncoder()) {
    delete str;
  }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
}

void DeviceNRecoder::reset() {
  imgStr = new ImageStream(str, width, colorMap->getNumPixelComps(),
			   colorMap->getBits());
  imgStr->reset();
}

GBool DeviceNRecoder::fillBuf() {
  Guchar pixBuf[gfxColorMaxComps];
  GfxColor color;
1058
  double x[gfxColorMaxComps], y[gfxColorMaxComps];
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1059 1060 1061 1062 1063 1064 1065
  int i;

  if (pixelIdx >= width * height) {
    return gFalse;
  }
  imgStr->getPixel(pixBuf);
  colorMap->getColor(pixBuf, &color);
1066 1067 1068 1069 1070 1071
  for (i = 0;
       i < ((GfxDeviceNColorSpace *)colorMap->getColorSpace())->getNComps();
       ++i) {
    x[i] = colToDbl(color.c[i]);
  }
  func->transform(x, y);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
  for (i = 0; i < bufSize; ++i) {
    buf[i] = (int)(y[i] * 255 + 0.5);
  }
  bufIdx = 0;
  ++pixelIdx;
  return gTrue;
}

//------------------------------------------------------------------------
// PSOutputDev
//------------------------------------------------------------------------

extern "C" {
typedef void (*SignalFunc)(int);
}

1088
static void outputToFile(void *stream, const char *data, int len) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1089 1090 1091
  fwrite(data, 1, len, (FILE *)stream);
}

1092
PSOutputDev::PSOutputDev(const char *fileName, PDFDoc *doc,
1093
			 char *psTitleA,
1094
			 const std::vector<int> &pages, PSOutMode modeA,
1095 1096
			 int paperWidthA, int paperHeightA,
                         GBool noCropA, GBool duplexA,
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1097
			 int imgLLXA, int imgLLYA, int imgURXA, int imgURYA,
1098
			 GBool forceRasterizeA,
1099 1100 1101
			 GBool manualCtrlA,
			 PSOutCustomCodeCbk customCodeCbkA,
			 void *customCodeCbkDataA) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1102 1103 1104
  FILE *f;
  PSFileType fileTypeA;

1105 1106 1107 1108
  underlayCbk = nullptr;
  underlayCbkData = nullptr;
  overlayCbk = nullptr;
  overlayCbkData = nullptr;
1109 1110
  customCodeCbk = customCodeCbkA;
  customCodeCbkData = customCodeCbkDataA;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1111

1112 1113 1114 1115 1116 1117 1118 1119 1120
  fontIDs = nullptr;
  t1FontNames = nullptr;
  font8Info = nullptr;
  font16Enc = nullptr;
  imgIDs = nullptr;
  formIDs = nullptr;
  paperSizes = nullptr;
  embFontList = nullptr;
  customColors = nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1121
  haveTextClip = gFalse;
1122
  t3String = nullptr;
1123
  forceRasterize = forceRasterizeA;
1124
  psTitle = nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1125 1126 1127 1128 1129 1130 1131 1132

  // open file or pipe
  if (!strcmp(fileName, "-")) {
    fileTypeA = psStdout;
    f = stdout;
  } else if (fileName[0] == '|') {
    fileTypeA = psPipe;
#ifdef HAVE_POPEN
1133
#ifndef _WIN32
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1134 1135 1136
    signal(SIGPIPE, (SignalFunc)SIG_IGN);
#endif
    if (!(f = popen(fileName + 1, "w"))) {
1137
      error(errIO, -1, "Couldn't run print command '{0:s}'", fileName);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1138 1139 1140 1141
      ok = gFalse;
      return;
    }
#else
1142
    error(errIO, -1, "Print commands are not supported ('{0:s}')", fileName);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1143 1144 1145 1146 1147 1148
    ok = gFalse;
    return;
#endif
  } else {
    fileTypeA = psFile;
    if (!(f = fopen(fileName, "w"))) {
1149
      error(errIO, -1, "Couldn't open PostScript file '{0:s}'", fileName);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1150 1151 1152 1153 1154
      ok = gFalse;
      return;
    }
  }

1155
  init(outputToFile, f, fileTypeA, psTitleA,
1156
       doc, pages, modeA,
1157
       imgLLXA, imgLLYA, imgURXA, imgURYA, manualCtrlA,
1158
       paperWidthA, paperHeightA, noCropA, duplexA);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1159 1160 1161
}

PSOutputDev::PSOutputDev(PSOutputFunc outputFuncA, void *outputStreamA,
1162
			 char *psTitleA,
Hib Eris's avatar
Hib Eris committed
1163
			 PDFDoc *doc,
1164
			 const std::vector<int> &pages, PSOutMode modeA,
1165 1166
			 int paperWidthA, int paperHeightA,
                         GBool noCropA, GBool duplexA,
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1167
			 int imgLLXA, int imgLLYA, int imgURXA, int imgURYA,
1168
			 GBool forceRasterizeA,
1169 1170 1171
			 GBool manualCtrlA,
			 PSOutCustomCodeCbk customCodeCbkA,
			 void *customCodeCbkDataA) {
1172 1173 1174 1175
  underlayCbk = nullptr;
  underlayCbkData = nullptr;
  overlayCbk = nullptr;
  overlayCbkData = nullptr;
1176 1177
  customCodeCbk = customCodeCbkA;
  customCodeCbkData = customCodeCbkDataA;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1178

1179 1180 1181 1182 1183 1184 1185 1186 1187
  fontIDs = nullptr;
  t1FontNames = nullptr;
  font8Info = nullptr;
  font16Enc = nullptr;
  imgIDs = nullptr;
  formIDs = nullptr;
  paperSizes = nullptr;
  embFontList = nullptr;
  customColors = nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1188
  haveTextClip = gFalse;
1189
  t3String = nullptr;
1190
  forceRasterize = forceRasterizeA;
1191
  psTitle = nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1192

1193
  init(outputFuncA, outputStreamA, psGeneric, psTitleA,
1194
       doc, pages, modeA,
1195
       imgLLXA, imgLLYA, imgURXA, imgURYA, manualCtrlA,
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
       paperWidthA, paperHeightA, noCropA, duplexA);
}

struct StandardMedia {
    const char *name;
    int width;
    int height;
};

static const StandardMedia standardMedia[] =
{
    { "A0",       2384, 3371 },
    { "A1",       1685, 2384 },
    { "A2",       1190, 1684 },
    { "A3",        842, 1190 },
    { "A4",        595,  842 },
    { "A5",        420,  595 },
    { "B4",        729, 1032 },
    { "B5",        516,  729 },
    { "Letter",    612,  792 },
    { "Tabloid",   792, 1224 },
    { "Ledger",   1224,  792 },
    { "Legal",     612, 1008 },
    { "Statement", 396,  612 },
    { "Executive", 540,  720 },
    { "Folio",     612,  936 },
    { "Quarto",    610,  780 },
    { "10x14",     720, 1008 },
1224
    { nullptr,          0,    0 }
1225 1226 1227 1228 1229
};

/* PLRM specifies a tolerance of 5 points when matching page sizes */
static bool pageDimensionEqual(int a, int b) {
  return (abs (a - b) < 5);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1230 1231
}

1232 1233 1234 1235
// Shared initialization of PSOutputDev members.
//   Store the values but do not process them so the function that
//   created the PSOutputDev can use the various setters to change defaults.

Kristian Høgsberg's avatar
Kristian Høgsberg committed
1236
void PSOutputDev::init(PSOutputFunc outputFuncA, void *outputStreamA,
1237
		       PSFileType fileTypeA, char *psTitleA, PDFDoc *docA,
1238
		       const std::vector<int> &pagesA, PSOutMode modeA,
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1239
		       int imgLLXA, int imgLLYA, int imgURXA, int imgURYA,
1240
		       GBool manualCtrlA, int paperWidthA, int paperHeightA,
1241
		       GBool noCropA, GBool duplexA) {
1242 1243 1244 1245 1246

  if (pagesA.empty()) {
    ok = gFalse;
    return;
  }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1247 1248

  // initialize
1249
  postInitDone = gFalse;
1250 1251 1252 1253 1254
  embedType1 = gTrue;
  embedTrueType = gTrue;
  embedCIDPostScript = gTrue;
  embedCIDTrueType = gTrue;
  fontPassthrough = gFalse;
1255
  optimizeColorSpace = gFalse;
1256
  passLevel1CustomColor = gFalse;
1257 1258 1259 1260
  preloadImagesForms = gFalse;
  generateOPI = gFalse;
  useASCIIHex = gFalse;
  useBinary = gFalse;
1261
  enableLZW = gTrue;
1262
  enableFlate = gTrue;
1263 1264
  rasterMono = gFalse;
  rasterResolution = 300;
1265
  uncompressPreloadedImages = gFalse;
1266
  psCenter = gTrue;
1267
  rasterAntialias = gFalse;
1268
  displayText = gTrue;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1269 1270 1271 1272
  ok = gTrue;
  outputFunc = outputFuncA;
  outputStream = outputStreamA;
  fileType = fileTypeA;
1273
  psTitle = (psTitleA? strdup(psTitleA): nullptr);
1274
  doc = docA;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1275
  level = globalParams->getPSLevel();
1276
  pages = pagesA;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1277
  mode = modeA;
1278 1279
  paperWidth = paperWidthA;
  paperHeight = paperHeightA;
1280
  noCrop = noCropA;
1281
  duplex = duplexA;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1282 1283 1284 1285
  imgLLX = imgLLXA;
  imgLLY = imgLLYA;
  imgURX = imgURXA;
  imgURY = imgURYA;
1286 1287
  manualCtrl = manualCtrlA;

1288
  xref = nullptr;
1289 1290 1291 1292 1293 1294

  processColors = 0;
  inType3Char = gFalse;
  inUncoloredPattern = gFalse;
  t3FillColorOnly = gFalse;

1295
#ifdef OPI_SUPPORT
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
  // initialize OPI nesting levels
  opi13Nest = 0;
  opi20Nest = 0;
#endif

  tx0 = ty0 = -1;
  xScale0 = yScale0 = 0;
  rotate0 = -1;
  clipLLX0 = clipLLY0 = 0;
  clipURX0 = clipURY0 = -1;

  // initialize sequential page number
  seqPage = 1;
}

// Complete the initialization after the function that created the PSOutputDev
//   has had a chance to modify default values with the various setters.

void PSOutputDev::postInit()
{
  Catalog *catalog;
  PDFRectangle *box;
  PSOutPaperSize *size;
  int w, h, i;

  if (postInitDone || !ok) {
    return;
  }

  postInitDone = gTrue;

  xref = doc->getXRef();
  catalog = doc->getCatalog();

Kristian Høgsberg's avatar
Kristian Høgsberg committed
1330
  if (paperWidth < 0 || paperHeight < 0) {
1331
    paperMatch = gTrue;
1332 1333 1334 1335 1336
  } else {
    paperMatch = gFalse;
  }
  Page *page;
  paperSizes = new GooList();
1337 1338
  for (size_t pgi = 0; pgi < pages.size(); ++pgi) {
    const int pg = pages[pgi];
1339
    page = catalog->getPage(pg);
1340
    if (page == nullptr)
1341 1342 1343 1344
      paperMatch = gFalse;
    if (!paperMatch) {
      w = paperWidth;
      h = paperHeight;
1345 1346 1347 1348 1349 1350 1351
      if (w < 0 || h < 0) {
        // Unable to obtain a paper size from the document and no page size
        // specified. In this case use A4 as the page size to ensure the PS output is
        // valid. This will only occur if the PDF is very broken.
        w = 595;
        h = 842;
      }
1352
    } else if (noCrop) {
1353 1354
      w = (int)ceil(page->getMediaWidth());
      h = (int)ceil(page->getMediaHeight());
1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374
    } else {
      w = (int)ceil(page->getCropWidth());
      h = (int)ceil(page->getCropHeight());
    }
    if (paperMatch) {
      int rotate = page->getRotate();
      if (rotate == 90 || rotate == 270)
        std::swap(w, h);
    }
    if (w  > paperWidth)
      paperWidth = w;
    if (h  > paperHeight)
      paperHeight = h;
    for (i = 0; i < paperSizes->getLength(); ++i) {
      size = (PSOutPaperSize *)paperSizes->get(i);
      if (pageDimensionEqual(w, size->w) && pageDimensionEqual(h, size->h))
        break;
    }
    if (i == paperSizes->getLength()) {
      const StandardMedia *media = standardMedia;
1375
      GooString *name = nullptr;
1376 1377 1378 1379 1380 1381 1382 1383
      while (media->name) {
        if (pageDimensionEqual(w, media->width) && pageDimensionEqual(h, media->height)) {
          name = new GooString(media->name);
          w = media->width;
          h = media->height;
          break;
        }
        media++;
1384
      }
1385 1386 1387
      if (!name)
        name = GooString::format("{0:d}x{1:d}mm", int(w*25.4/72), int(h*25.4/72));
      paperSizes->append(new PSOutPaperSize(name, w, h));
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1388
    }
1389 1390 1391
    pagePaperSize.insert(std::pair<int,int>(pg, i));
    if (!paperMatch)
      break; // we only need one entry when all pages are the same size
1392
  }
1393 1394 1395 1396 1397
  if (imgLLX == 0 && imgURX == 0 && imgLLY == 0 && imgURY == 0) {
    imgLLX = imgLLY = 0;
    imgURX = paperWidth;
    imgURY = paperHeight;
  }
1398
  std::vector<int> pageList;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1399
  if (mode == psModeForm) {
1400
    pageList.push_back(pages[0]);
1401
  } else {
1402
    pageList = pages;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1403 1404 1405 1406 1407
  }

  // initialize fontIDs, fontFileIDs, and fontFileNames lists
  fontIDSize = 64;
  fontIDLen = 0;
1408
  fontIDs = (Ref *)gmallocn(fontIDSize, sizeof(Ref));
1409
  for (i = 0; i < 14; ++i) {
1410
    fontNames.emplace(psBase14SubstFonts[i].psName);
1411 1412 1413 1414
  }
  t1FontNameSize = 64;
  t1FontNameLen = 0;
  t1FontNames = (PST1FontName *)gmallocn(t1FontNameSize, sizeof(PST1FontName));
1415 1416
  font8InfoLen = 0;
  font8InfoSize = 0;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1417 1418
  font16EncLen = 0;
  font16EncSize = 0;
1419 1420 1421 1422
  imgIDLen = 0;
  imgIDSize = 0;
  formIDLen = 0;
  formIDSize = 0;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1423 1424

  numSaves = 0;
1425 1426
  numTilingPatterns = 0;
  nextFunc = 0;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1427 1428 1429 1430 1431

  // initialize embedded font resource comment list
  embFontList = new GooString();

  if (!manualCtrl) {
Hib Eris's avatar
Hib Eris committed
1432
    Page *page;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1433
    // this check is needed in case the document has zero pages
1434 1435
    if ((page = doc->getPage(pageList[0]))) {
      writeHeader(pageList,
Hib Eris's avatar
Hib Eris committed
1436 1437 1438
		  page->getMediaBox(),
		  page->getCropBox(),
		  page->getRotate(),
1439
		  psTitle);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1440
    } else {
1441
      error(errSyntaxError, -1, "Invalid page {0:d}", pageList[0]);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1442
      box = new PDFRectangle(0, 0, 1, 1);
1443
      writeHeader(pageList, box, box, 0, psTitle);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453
      delete box;
    }
    if (mode != psModeForm) {
      writePS("%%BeginProlog\n");
    }
    writeXpdfProcset();
    if (mode != psModeForm) {
      writePS("%%EndProlog\n");
      writePS("%%BeginSetup\n");
    }
1454
    writeDocSetup(doc, catalog, pageList, duplex);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465
    if (mode != psModeForm) {
      writePS("%%EndSetup\n");
    }
  }
}

PSOutputDev::~PSOutputDev() {
  PSOutCustomColor *cc;
  int i;

  if (ok) {
1466 1467 1468
    if (!postInitDone) {
      postInit();
    }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484
    if (!manualCtrl) {
      writePS("%%Trailer\n");
      writeTrailer();
      if (mode != psModeForm) {
	writePS("%%EOF\n");
      }
    }
    if (fileType == psFile) {
#ifdef MACOS
      ICS_MapRefNumAndAssign((short)((FILE *)outputStream)->handle);
#endif
      fclose((FILE *)outputStream);
    }
#ifdef HAVE_POPEN
    else if (fileType == psPipe) {
      pclose((FILE *)outputStream);
1485
#ifndef _WIN32
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1486 1487 1488 1489 1490
      signal(SIGPIPE, (SignalFunc)SIG_DFL);
#endif
    }
#endif
  }
1491 1492 1493
  if (paperSizes) {
    deleteGooList(paperSizes, PSOutPaperSize);
  }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1494 1495 1496 1497 1498 1499
  if (embFontList) {
    delete embFontList;
  }
  if (fontIDs) {
    gfree(fontIDs);
  }
1500 1501 1502
  if (t1FontNames) {
    for (i = 0; i < t1FontNameLen; ++i) {
      delete t1FontNames[i].psName;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1503
    }
1504
    gfree(t1FontNames);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1505
  }
1506 1507 1508 1509 1510 1511
  if (font8Info) {
    for (i = 0; i < font8InfoLen; ++i) {
      gfree(font8Info[i].codeToGID);
    }
    gfree(font8Info);
  }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1512 1513
  if (font16Enc) {
    for (i = 0; i < font16EncLen; ++i) {
1514 1515 1516
      if (font16Enc[i].enc) {
	delete font16Enc[i].enc;
      }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1517 1518 1519
    }
    gfree(font16Enc);
  }
1520 1521
  gfree(imgIDs);
  gfree(formIDs);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1522 1523 1524 1525 1526
  while (customColors) {
    cc = customColors;
    customColors = cc->next;
    delete cc;
  }
1527
  gfree(psTitle);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1528 1529
}

1530
void PSOutputDev::writeHeader(const std::vector<int> &pages,
1531
			      PDFRectangle *mediaBox, PDFRectangle *cropBox,
1532
			      int pageRotate, char *psTitle) {
1533 1534
  PSOutPaperSize *size;
  double x1, y1, x2, y2;
1535

Kristian Høgsberg's avatar
Kristian Høgsberg committed
1536 1537 1538
  switch (mode) {
  case psModePS:
    writePS("%!PS-Adobe-3.0\n");
1539 1540 1541 1542 1543 1544 1545 1546
    break;
  case psModeEPS:
    writePS("%!PS-Adobe-3.0 EPSF-3.0\n");
    break;
  case psModeForm:
    writePS("%!PS-Adobe-3.0 Resource-Form\n");
    break;
  }
1547
  writePSFmt("%Produced by poppler pdftops version: {0:s} (http://poppler.freedesktop.org)\n", PACKAGE_VERSION);
Albert Astals Cid's avatar
Albert Astals Cid committed
1548 1549 1550 1551 1552 1553 1554
  Object info = xref->getDocInfo();
  if (info.isDict()) {
    Object obj1 = info.dictLookup("Creator");
    if (obj1.isString()) {
        writePS("%%Creator: ");
        writePSTextLine(obj1.getString());
    }
1555
  }
1556
  if(psTitle) {
1557 1558 1559 1560
    char *sanitizedTitle = strdup(psTitle);
    for (Guint i = 0; i < strlen(sanitizedTitle); ++i) {
      if (sanitizedTitle[i] == '\n' || sanitizedTitle[i] == '\r') {
        sanitizedTitle[i] = ' ';
1561 1562
      }
    }
1563 1564
    writePSFmt("%%Title: {0:s}\n", sanitizedTitle);
    free(sanitizedTitle);
1565
  }
1566 1567 1568 1569 1570 1571 1572 1573
  writePSFmt("%%LanguageLevel: {0:d}\n",
	     (level == psLevel1 || level == psLevel1Sep) ? 1 :
	     (level == psLevel2 || level == psLevel2Sep) ? 2 : 3);
  if (level == psLevel1Sep || level == psLevel2Sep || level == psLevel3Sep) {
    writePS("%%DocumentProcessColors: (atend)\n");
    writePS("%%DocumentCustomColors: (atend)\n");
  }
  writePS("%%DocumentSuppliedResources: (atend)\n");
1574
  if ((level == psLevel1 || level == psLevel1Sep) && useBinary) {
1575 1576
    writePS("%%DocumentData: Binary\n");
  }
1577 1578 1579

  switch (mode) {
  case psModePS:
1580
    for (int i = 0; i < paperSizes->getLength(); ++i) {
1581 1582 1583
      size = (PSOutPaperSize *)paperSizes->get(i);
      writePSFmt("%%{0:s} {1:t} {2:d} {3:d} 0 () ()\n",
                 i==0 ? "DocumentMedia:" : "+", size->name, size->w, size->h);
1584
    }
1585
    writePSFmt("%%BoundingBox: 0 0 {0:d} {1:d}\n", paperWidth, paperHeight);
1586
    writePSFmt("%%Pages: {0:d}\n", static_cast<int>(pages.size()));
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1587
    writePS("%%EndComments\n");
1588
    if (!paperMatch) {
1589
      size = (PSOutPaperSize *)paperSizes->get(0);
1590
      writePS("%%BeginDefaults\n");
1591
      writePSFmt("%%PageMedia: {0:t}\n", size->name);
1592 1593
      writePS("%%EndDefaults\n");
    }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1594 1595
    break;
  case psModeEPS:
1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610
    epsX1 = cropBox->x1;
    epsY1 = cropBox->y1;
    epsX2 = cropBox->x2;
    epsY2 = cropBox->y2;
    if (pageRotate == 0 || pageRotate == 180) {
      x1 = epsX1;
      y1 = epsY1;
      x2 = epsX2;
      y2 = epsY2;
    } else { // pageRotate == 90 || pageRotate == 270
      x1 = 0;
      y1 = 0;
      x2 = epsY2 - epsY1;
      y2 = epsX2 - epsX1;
    }
1611
    writePSFmt("%%BoundingBox: {0:d} {1:d} {2:d} {3:d}\n",
1612
	       (int)floor(x1), (int)floor(y1), (int)ceil(x2), (int)ceil(y2));
1613
    writePSFmt("%%HiResBoundingBox: {0:.6g} {1:.6g} {2:.6g} {3:.6g}\n",
1614
		 x1, y1, x2, y2);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1615 1616 1617 1618 1619 1620
    writePS("%%DocumentSuppliedResources: (atend)\n");
    writePS("%%EndComments\n");
    break;
  case psModeForm:
    writePS("%%EndComments\n");
    writePS("32 dict dup begin\n");
1621
    writePSFmt("/BBox [{0:d} {1:d} {2:d} {3:d}] def\n",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1622 1623 1624 1625 1626 1627 1628 1629 1630
	       (int)floor(mediaBox->x1), (int)floor(mediaBox->y1),
	       (int)ceil(mediaBox->x2), (int)ceil(mediaBox->y2));
    writePS("/FormType 1 def\n");
    writePS("/Matrix [1 0 0 1 0 0] def\n");
    break;
  }
}

void PSOutputDev::writeXpdfProcset() {
1631
  GBool lev1, lev2, lev3, sep, nonSep;
1632 1633
  const char **p;
  const char *q;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1634

1635
  writePSFmt("%%BeginResource: procset xpdf {0:s} 0\n", "3.00");
1636
  writePSFmt("%%Copyright: {0:s}\n", xpdfCopyright);
1637
  lev1 = lev2 = lev3 = sep = nonSep = gTrue;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1638
  for (p = prolog; *p; ++p) {
1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651
    if ((*p)[0] == '~') {
      lev1 = lev2 = lev3 = sep = nonSep = gFalse;
      for (q = *p + 1; *q; ++q) {
	switch (*q) {
	case '1': lev1 = gTrue; break;
	case '2': lev2 = gTrue; break;
	case '3': lev3 = gTrue; break;
	case 's': sep = gTrue; break;
	case 'n': nonSep = gTrue; break;
	}
      }
    } else if ((level == psLevel1 && lev1 && nonSep) ||
	       (level == psLevel1Sep && lev1 && sep) ||
1652
	       (level == psLevel1Sep && lev2 && sep && getPassLevel1CustomColor()) ||
1653 1654 1655 1656
	       (level == psLevel2 && lev2 && nonSep) ||
	       (level == psLevel2Sep && lev2 && sep) ||
	       (level == psLevel3 && lev3 && nonSep) ||
	       (level == psLevel3Sep && lev3 && sep)) {
1657
      writePSFmt("{0:s}\n", *p);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1658 1659 1660 1661 1662 1663
    }
  }
  writePS("%%EndResource\n");

  if (level >= psLevel3) {
    for (p = cmapProlog; *p; ++p) {
1664
      writePSFmt("{0:s}\n", *p);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1665 1666 1667 1668
    }
  }
}

Hib Eris's avatar
Hib Eris committed
1669
void PSOutputDev::writeDocSetup(PDFDoc *doc, Catalog *catalog,
1670
				const std::vector<int> &pages,
1671
                                GBool duplexA) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1672 1673 1674
  Page *page;
  Dict *resDict;
  Annots *annots;
1675 1676
  Object *acroForm;
  GooString *s;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1677 1678 1679 1680 1681 1682 1683

  if (mode == psModeForm) {
    // swap the form and xpdf dicts
    writePS("xpdf end begin dup begin\n");
  } else {
    writePS("xpdf begin\n");
  }