PSOutputDev.cc 209 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>
Thomas Freitag's avatar
Thomas Freitag committed
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>
Kovid Goyal's avatar
Kovid Goyal committed
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 37 38 39 40 41
//
// 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
42 43 44 45 46 47 48 49 50 51 52
#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>
53
#include <limits.h>
54
#include <algorithm>
Kristian Høgsberg's avatar
Kristian Høgsberg committed
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
#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"
Adrian Johnson's avatar
Adrian Johnson committed
71
#ifdef ENABLE_ZLIB
72 73
#  include "FlateEncoder.h"
#endif
Adrian Johnson's avatar
Adrian Johnson committed
74
#ifdef ENABLE_ZLIB_UNCOMPRESS
75 76
#  include "FlateStream.h"
#endif
Kristian Høgsberg's avatar
Kristian Høgsberg committed
77
#include "Annot.h"
78 79
#include "XRef.h"
#include "PreScanOutputDev.h"
80
#include "FileSpec.h"
81
#include "CharCodeToUnicode.h"
Adrian Johnson's avatar
Adrian Johnson committed
82
#ifdef HAVE_SPLASH
83 84 85 86
#  include "splash/Splash.h"
#  include "splash/SplashBitmap.h"
#  include "SplashOutputDev.h"
#endif
Kristian Høgsberg's avatar
Kristian Høgsberg committed
87
#include "PSOutputDev.h"
Hib Eris's avatar
Hib Eris committed
88
#include "PDFDoc.h"
Kristian Høgsberg's avatar
Kristian Høgsberg committed
89 90 91 92 93 94

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

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

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

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

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

109 110 111 112 113 114 115
// 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*

116
static const char *prolog[] = {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
117 118 119
  "/xpdf 75 dict def xpdf begin",
  "% PDF special state",
  "/pdfDictSize 15 def",
120
  "~1sn",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
121 122 123 124 125 126
  "/pdfStates 64 array def",
  "  0 1 63 {",
  "    pdfStates exch pdfDictSize dict",
  "    dup /pdfStateIdx 3 index put",
  "    put",
  "  } for",
127
  "~123sn",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
128 129
  "/pdfSetup {",
  "  /setpagedevice where {",
130 131 132 133 134 135 136 137 138
  "    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 {",
139 140 141
  "  % 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.",
142
  "  /setpagedevice where {",
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
  "    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
165
  "  } {",
166
  "    pop",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
167 168
  "  } ifelse",
  "} def",
169
  "~1sn",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
170 171
  "/pdfOpNames [",
  "  /pdfFill /pdfStroke /pdfLastFill /pdfLastStroke",
172
  "  /pdfTextMat /pdfFontSize /pdfCharSpacing /pdfTextRender /pdfPatternCS",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
173 174
  "  /pdfTextRise /pdfWordSpacing /pdfHorizScaling /pdfTextClipPath",
  "] def",
175
  "~123sn",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
176
  "/pdfStartPage {",
177
  "~1sn",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
178
  "  pdfStates 0 get begin",
179
  "~23sn",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
180
  "  pdfDictSize dict begin",
181 182 183 184 185 186 187 188 189 190 191 192
  "~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
193 194
  "  /pdfFill [0] def",
  "  /pdfStroke [0] def",
195 196
  "  /pdfFillOP false def",
  "  /pdfStrokeOP false def",
197 198
  "~3sn",
  "  /pdfOPM false def",
199
  "~123sn",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
200 201 202 203 204 205
  "  /pdfLastFill false def",
  "  /pdfLastStroke false def",
  "  /pdfTextMat [1 0 0 1 0 0] def",
  "  /pdfFontSize 0 def",
  "  /pdfCharSpacing 0 def",
  "  /pdfTextRender 0 def",
206
  "  /pdfPatternCS false def", 
Kristian Høgsberg's avatar
Kristian Høgsberg committed
207 208 209 210 211 212
  "  /pdfTextRise 0 def",
  "  /pdfWordSpacing 0 def",
  "  /pdfHorizScaling 1 def",
  "  /pdfTextClipPath [] def",
  "} def",
  "/pdfEndPage { end } def",
213
  "~23s",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
214 215 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
  "% 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",
255
  "~123sn",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
256
  "% PDF color state",
257 258 259 260 261 262 263 264 265 266 267
  "~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
268 269
  "/sCol {",
  "  pdfLastStroke not {",
270
  "    pdfStroke setgray",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
271 272 273
  "    /pdfLastStroke true def /pdfLastFill false def",
  "  } if",
  "} def",
274 275 276 277 278
  "~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
279 280
  "/fCol {",
  "  pdfLastFill not {",
281 282 283 284 285 286 287 288 289 290
  "    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",
291 292
  "~3n",
  "/opm { dup /pdfOPM exch def",
293
  "      /setoverprintmode where{pop setoverprintmode}{pop}ifelse  } def",
294 295 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
  "~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",
325 326
  "~3s",
  "/opm { dup /pdfOPM exch def",
327
  "      /setoverprintmode where{pop setoverprintmode}{pop}ifelse } def",
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
  "~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 {",
346 347 348 349
  "      setcmykcolor",
  "    }{",
  "      findcmykcustomcolor exch setcustomcolor",
  "    } ifelse",
350
  "    pdfFillOP setoverprint",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
351 352 353
  "    /pdfLastFill true def /pdfLastStroke false def",
  "  } if",
  "} def",
354 355 356 357 358 359 360 361 362 363 364 365
  "/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
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
  "% 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",
386
  "~3sn",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
387 388 389 390 391 392 393 394 395 396 397 398 399
  "/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",
400
  "~123sn",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
401
  "% graphics state operators",
402
  "~1sn",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
403 404 405 406 407 408 409
  "/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",
410 411 412 413 414 415 416 417 418 419 420 421
  "~23sn",
  "/q { gsave pdfDictSize dict begin } def",
  "/Q {",
  "  end grestore",
  "  /pdfLastFill where {",
  "    pop",
  "    pdfLastFill {",
  "      pdfFillOP setoverprint",
  "    } {",
  "      pdfStrokeOP setoverprint",
  "    } ifelse",
  "  } if",
422 423 424
  "~3sn",
  "  /pdfOPM where {",
  "    pop",
425
  "    pdfOPM /setoverprintmode where{pop setoverprintmode}{pop}ifelse ",
426 427
  "  } if",
  "~23sn",
428 429
  "} def",
  "~123sn",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
  "/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",
452
  "/Ws { strokepath clip newpath } def",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
453 454 455 456 457 458 459
  "% 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",
460
  "/Tp { /pdfPatternCS exch def } def", 
Kristian Høgsberg's avatar
Kristian Høgsberg committed
461 462 463 464 465 466 467
  "/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",
468 469 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
  "/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
498 499
  "/cshow where {",
  "  pop",
500 501 502 503 504 505 506 507
  "  /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
508 509 510 511
  "    } exch cshow",
  "    pop pop",
  "  } def",
  "}{",
512
  "  /xycp {", // xycharpath
Kristian Høgsberg's avatar
Kristian Høgsberg committed
513
  "    currentfont /FontType get 0 eq {",
514 515 516 517
  "      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
518 519
  "      } for",
  "    } {",
520 521 522 523 524
  "      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
525 526 527 528 529 530 531
  "    } ifelse",
  "    pop pop",
  "  } def",
  "} ifelse",
  "/Tj {",
  "  fCol",  // because stringwidth has to draw Type 3 chars
  "  0 pdfTextRise pdfTextMat dtransform rmoveto",
532 533 534
  "  currentpoint 4 2 roll",
  "  pdfTextRender 1 and 0 eq {",
  "    2 copy xyshow2",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
535 536
  "  } if",
  "  pdfTextRender 3 and dup 1 eq exch 2 eq or {",
537 538
  "    3 index 3 index moveto",
  "    2 copy",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
539
  "    currentfont /FontType get 3 eq { fCol } { sCol } ifelse",
540
  "    xycp currentpoint stroke moveto",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
541
  "  } if",
542 543
  "  pdfTextRender 4 and 0 ne {",
  "    4 2 roll moveto xycp",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
544 545 546 547 548 549 550 551
  "    /pdfTextClipPath [ pdfTextClipPath aload pop",
  "      {/moveto cvx}",
  "      {/lineto cvx}",
  "      {/curveto cvx}",
  "      {/closepath cvx}",
  "    pathforall ] def",
  "    currentpoint newpath moveto",
  "  } {",
552
  "    pop pop pop pop",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
553 554 555
  "  } ifelse",
  "  0 pdfTextRise neg pdfTextMat dtransform rmoveto",
  "} def",
556
  "/TJm { 0.001 mul pdfFontSize mul pdfHorizScaling mul neg 0",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
557
  "       pdfTextMat dtransform rmoveto } def",
558
  "/TJmV { 0.001 mul pdfFontSize mul neg 0 exch",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
559 560 561
  "        pdfTextMat dtransform rmoveto } def",
  "/Tclip { pdfTextClipPath cvx exec clip newpath",
  "         /pdfTextClipPath [] def } def",
562 563
  "/Tclip* { pdfTextClipPath cvx exec eoclip newpath",
  "         /pdfTextClipPath [] def } def",
564
  "~1ns",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
565 566 567 568 569
  "% Level 1 image operators",
  "/pdfIm1 {",
  "  /pdfImBuf1 4 index string def",
  "  { currentfile pdfImBuf1 readhexstring pop } image",
  "} def",
570 571 572 573
  "/pdfIm1Bin {",
  "  /pdfImBuf1 4 index string def",
  "  { currentfile pdfImBuf1 readstring pop } image",
  "} def",
574
  "~1s",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
575 576 577 578 579 580 581 582 583 584 585
  "/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",
586 587 588 589 590 591 592 593 594 595 596
  "/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",
597
  "~1ns",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
598
  "/pdfImM1 {",
599
  "  fCol /pdfImBuf1 4 index 7 add 8 idiv string def",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
600 601
  "  { currentfile pdfImBuf1 readhexstring pop } imagemask",
  "} def",
602 603 604 605
  "/pdfImM1Bin {",
  "  fCol /pdfImBuf1 4 index 7 add 8 idiv string def",
  "  { currentfile pdfImBuf1 readstring pop } imagemask",
  "} def",
606 607 608 609 610 611 612
  "/pdfImStr {",
  "  2 copy exch length lt {",
  "    2 copy get exch 1 add exch",
  "  } {",
  "    ()",
  "  } ifelse",
  "} def",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
613
  "/pdfImM1a {",
614
  "  { pdfImStr } imagemask",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
615 616
  "  pop pop",
  "} def",
617
  "~23sn",
618
  "% Level 2/3 image operators",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
619
  "/pdfImBuf 100 string def",
620 621 622 623 624 625 626 627
  "/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
628 629 630 631
  "  { currentfile pdfImBuf readline",
  "    not { pop exit } if",
  "    (%-EOD-) eq { exit } if } loop",
  "} def",
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
  "/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",
652
  "~23s",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
653 654 655 656 657 658 659 660 661 662 663 664 665 666
  "/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",
667
  "  skipEOD",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
668
  "} def",
669
  "~23sn",
670
  "/pdfImM { fCol imagemask skipEOD } def",
671
  "~123sn",
672
  "/pr { 2 index 2 index 3 2 roll putinterval 4 add } def",
673 674 675 676 677 678 679 680 681 682 683
  "/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",
684
  "~23sn",
685 686 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
  "% 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",
721
  "~23n",
722
  "    funcCol sc",
723 724 725
  "~23s",
  "    funcCol aload pop k",
  "~23sn",
726 727 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
  "    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",
  "  } {",
759 760 761 762 763 764
  "    pop 2 copy add 0.5 mul",
  "~23n",
  "    axialCol sc",
  "~23s",
  "    axialCol aload pop k",
  "~23sn",
765 766 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
  "    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",
  "  } {",
808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
  "    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",
830 831 832
  "  } ifelse",
  "} def",
  "~123sn",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
833
  "end",
834
  nullptr
Kristian Høgsberg's avatar
Kristian Høgsberg committed
835 836
};

837
static const char *cmapProlog[] = {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
838 839 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
  "/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",
879
  nullptr
Kristian Høgsberg's avatar
Kristian Høgsberg committed
880 881 882 883 884 885 886
};

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

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

891 892 893 894 895 896
// 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
897 898 899 900 901 902 903 904
  {"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},
905 906 907 908 909 910 911 912 913 914
  // 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
915 916
};

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

Kristian Høgsberg's avatar
Kristian Høgsberg committed
923 924 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
// 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();

950 951 952
  PSOutCustomColor(const PSOutCustomColor &) = delete;
  PSOutCustomColor& operator=(const PSOutCustomColor &) = delete;

Kristian Høgsberg's avatar
Kristian Høgsberg committed
953 954 955 956 957 958 959 960 961 962 963 964
  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;
965
  next = nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
966 967 968 969 970 971
}

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

972 973 974 975 976 977
//------------------------------------------------------------------------

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

978 979 980
//------------------------------------------------------------------------

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

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

class DeviceNRecoder: public FilterStream {
public:

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

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;
1029
  imgStr = nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
  pixelIdx = 0;
  bufIdx = gfxColorMaxComps;
  bufSize = ((GfxDeviceNColorSpace *)colorMap->getColorSpace())->
              getAlt()->getNComps();
  func = ((GfxDeviceNColorSpace *)colorMap->getColorSpace())->
           getTintTransformFunc();
}

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

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

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

  if (pixelIdx >= width * height) {
    return gFalse;
  }
  imgStr->getPixel(pixBuf);
  colorMap->getColor(pixBuf, &color);
1064 1065 1066 1067 1068 1069
  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
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
  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);
}

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

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

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

1110 1111 1112 1113 1114 1115 1116 1117 1118
  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
1119
  haveTextClip = gFalse;
1120
  t3String = nullptr;
1121
  forceRasterize = forceRasterizeA;
1122
  psTitle = nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1123 1124 1125 1126 1127 1128 1129 1130

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

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

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

1177 1178 1179 1180 1181 1182 1183 1184 1185
  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
1186
  haveTextClip = gFalse;
1187
  t3String = nullptr;
1188
  forceRasterize = forceRasterizeA;
1189
  psTitle = nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1190

1191
  init(outputFuncA, outputStreamA, psGeneric, psTitleA,
1192
       doc, pages, modeA,
1193
       imgLLXA, imgLLYA, imgURXA, imgURYA, manualCtrlA,
1194 1195 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
       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 },
1222
    { nullptr,          0,    0 }
1223 1224 1225 1226 1227
};

/* 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
1228 1229
}

1230 1231 1232 1233
// 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
1234
void PSOutputDev::init(PSOutputFunc outputFuncA, void *outputStreamA,
1235
		       PSFileType fileTypeA, char *psTitleA, PDFDoc *docA,
1236
		       const std::vector<int> &pagesA, PSOutMode modeA,
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1237
		       int imgLLXA, int imgLLYA, int imgURXA, int imgURYA,
1238
		       GBool manualCtrlA, int paperWidthA, int paperHeightA,
1239
		       GBool noCropA, GBool duplexA) {
1240 1241 1242 1243 1244

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

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

1286
  xref = nullptr;
1287 1288 1289 1290 1291 1292

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

1293
#ifdef OPI_SUPPORT
1294 1295 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
  // 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
1328
  if (paperWidth < 0 || paperHeight < 0) {
1329
    paperMatch = gTrue;
1330 1331 1332 1333 1334
  } else {
    paperMatch = gFalse;
  }
  Page *page;
  paperSizes = new GooList();
1335 1336
  for (size_t pgi = 0; pgi < pages.size(); ++pgi) {
    const int pg = pages[pgi];
1337
    page = catalog->getPage(pg);
1338
    if (page == nullptr)
1339 1340 1341 1342
      paperMatch = gFalse;
    if (!paperMatch) {
      w = paperWidth;
      h = paperHeight;
1343 1344 1345 1346 1347 1348 1349
      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;
      }
1350
    } else if (noCrop) {
1351 1352
      w = (int)ceil(page->getMediaWidth());
      h = (int)ceil(page->getMediaHeight());
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
    } 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;
1373
      GooString *name = nullptr;
1374 1375 1376 1377 1378 1379 1380 1381
      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++;
1382
      }
1383 1384 1385
      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
1386
    }
1387 1388 1389
    pagePaperSize.insert(std::pair<int,int>(pg, i));
    if (!paperMatch)
      break; // we only need one entry when all pages are the same size
1390
  }
1391 1392 1393 1394 1395
  if (imgLLX == 0 && imgURX == 0 && imgLLY == 0 && imgURY == 0) {
    imgLLX = imgLLY = 0;
    imgURX = paperWidth;
    imgURY = paperHeight;
  }
1396
  std::vector<int> pageList;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1397
  if (mode == psModeForm) {
1398
    pageList.push_back(pages[0]);
1399
  } else {
1400
    pageList = pages;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1401 1402 1403 1404 1405
  }

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

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

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

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

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

  if (ok) {
1464 1465 1466
    if (!postInitDone) {
      postInit();
    }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482
    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);
Kovid Goyal's avatar
Kovid Goyal committed
1483
#ifndef _WIN32
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1484 1485 1486 1487 1488
      signal(SIGPIPE, (SignalFunc)SIG_DFL);
#endif
    }
#endif
  }
1489 1490 1491
  if (paperSizes) {
    deleteGooList(paperSizes, PSOutPaperSize);
  }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1492 1493 1494 1495 1496 1497
  if (embFontList) {
    delete embFontList;
  }
  if (fontIDs) {
    gfree(fontIDs);
  }
1498 1499 1500
  if (t1FontNames) {
    for (i = 0; i < t1FontNameLen; ++i) {
      delete t1FontNames[i].psName;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1501
    }
1502
    gfree(t1FontNames);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1503
  }
1504 1505 1506 1507 1508 1509
  if (font8Info) {
    for (i = 0; i < font8InfoLen; ++i) {
      gfree(font8Info[i].codeToGID);
    }
    gfree(font8Info);
  }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1510 1511
  if (font16Enc) {
    for (i = 0; i < font16EncLen; ++i) {
1512 1513 1514
      if (font16Enc[i].enc) {
	delete font16Enc[i].enc;
      }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1515 1516 1517
    }
    gfree(font16Enc);
  }
1518 1519
  gfree(imgIDs);
  gfree(formIDs);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1520 1521 1522 1523 1524
  while (customColors) {
    cc = customColors;
    customColors = cc->next;
    delete cc;
  }
1525
  gfree(psTitle);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1526 1527
}

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

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

  switch (mode) {
  case psModePS:
1578
    for (int i = 0; i < paperSizes->getLength(); ++i) {
1579 1580 1581
      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);
1582
    }
1583
    writePSFmt("%%BoundingBox: 0 0 {0:d} {1:d}\n", paperWidth, paperHeight);
1584
    writePSFmt("%%Pages: {0:d}\n", static_cast<int>(pages.size()));
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1585
    writePS("%%EndComments\n");
1586
    if (!paperMatch) {
1587
      size = (PSOutPaperSize *)paperSizes->get(0);
1588
      writePS("%%BeginDefaults\n");