ArthurOutputDev.cc 31.5 KB
Newer Older
1 2 3 4 5
//========================================================================
//
// ArthurOutputDev.cc
//
// Copyright 2003 Glyph & Cog, LLC
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
// Copyright (C) 2005 Brad Hards <bradh@frogmouth.net>
17
// Copyright (C) 2005-2009, 2011, 2012, 2014, 2015 Albert Astals Cid <aacid@kde.org>
Pino Toscano's avatar
Pino Toscano committed
18
// Copyright (C) 2008, 2010 Pino Toscano <pino@kde.org>
Albert Astals Cid's avatar
Albert Astals Cid committed
19
// Copyright (C) 2009, 2011 Carlos Garcia Campos <carlosgc@gnome.org>
20
// Copyright (C) 2009 Petr Gajdos <pgajdos@novell.com>
21
// Copyright (C) 2010 Matthias Fauconneau <matthias.fauconneau@gmail.com>
22
// Copyright (C) 2011 Andreas Hartmetz <ahartmetz@gmail.com>
Thomas Freitag's avatar
Thomas Freitag committed
23
// Copyright (C) 2013 Thomas Freitag <Thomas.Freitag@alfa.de>
24
// Copyright (C) 2013 Dominik Haumann <dhaumann@kde.org>
25
// Copyright (C) 2013 Mihai Niculescu <q.quark@gmail.com>
26
// Copyright (C) 2017 Oliver Sander <oliver.sander@tu-dresden.de>
27
// Copyright (C) 2017 Adrian Johnson <ajohnson@redneon.com>
28 29 30
//
// 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
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
//
//========================================================================

#include <config.h>

#ifdef USE_GCC_PRAGMAS
#pragma implementation
#endif

#include <string.h>
#include <math.h>

#include "goo/gfile.h"
#include "GlobalParams.h"
#include "Error.h"
#include "Object.h"
#include "GfxState.h"
#include "GfxFont.h"
#include "Link.h"
#include "FontEncodingTables.h"
#include <fofi/FoFiTrueType.h>
#include "ArthurOutputDev.h"

#include <QtCore/QtDebug>
55 56
#include <QRawFont>
#include <QGlyphRun>
57
#include <QtGui/QPainterPath>
58 59
#include <QPicture>

60 61
//------------------------------------------------------------------------

62
#ifdef HAVE_SPLASH
63
#include "splash/SplashFontFileID.h"
64
#include "splash/SplashFTFontFile.h"
65 66 67 68 69 70 71 72 73 74 75 76
#include "splash/SplashFontEngine.h"
//------------------------------------------------------------------------
// SplashOutFontFileID
//------------------------------------------------------------------------

class SplashOutFontFileID: public SplashFontFileID {
public:

  SplashOutFontFileID(Ref *rA) { r = *rA; }

  ~SplashOutFontFileID() {}

Albert Astals Cid's avatar
Albert Astals Cid committed
77
  GBool matches(SplashFontFileID *id) override {
78 79 80 81 82 83 84 85 86
    return ((SplashOutFontFileID *)id)->r.num == r.num &&
           ((SplashOutFontFileID *)id)->r.gen == r.gen;
  }

private:

  Ref r;
};

87
#endif
88

89 90 91 92 93
//------------------------------------------------------------------------
// ArthurOutputDev
//------------------------------------------------------------------------

ArthurOutputDev::ArthurOutputDev(QPainter *painter):
94
  m_lastTransparencyGroupPicture(nullptr),
95
  m_fontHinting(NoHinting)
96
{
97
  m_painter.push(painter);
98
  m_currentBrush = QBrush(Qt::SolidPattern);
99
  m_fontEngine = nullptr;
100 101 102 103
}

ArthurOutputDev::~ArthurOutputDev()
{
104
#ifdef HAVE_SPLASH
105
  delete m_fontEngine;
106
#endif
107 108 109
}

void ArthurOutputDev::startDoc(XRef *xrefA) {
110
  xref = xrefA;
111
#ifdef HAVE_SPLASH
Krzysztof Kowalczyk's avatar
Krzysztof Kowalczyk committed
112
  delete m_fontEngine;
113 114 115 116

  const bool isHintingEnabled = m_fontHinting != NoHinting;
  const bool isSlightHinting = m_fontHinting == SlightHinting;

117
  m_fontEngine = new SplashFontEngine(
Krzysztof Kowalczyk's avatar
Krzysztof Kowalczyk committed
118
  globalParams->getEnableFreeType(),
119 120
  isHintingEnabled,
  isSlightHinting,
121
  m_painter.top()->testRenderHint(QPainter::TextAntialiasing));
122
#endif
123 124
}

Thomas Freitag's avatar
Thomas Freitag committed
125
void ArthurOutputDev::startPage(int pageNum, GfxState *state, XRef *xref)
126
{
127 128 129 130 131
  // fill page with white background.
  int w = static_cast<int>(state->getPageWidth());
  int h = static_cast<int>(state->getPageHeight());
  QColor fillColour(Qt::white);
  QBrush fill(fillColour);
132 133 134 135 136
  m_painter.top()->save();
  m_painter.top()->setPen(fillColour);
  m_painter.top()->setBrush(fill);
  m_painter.top()->drawRect(0, 0, w, h);
  m_painter.top()->restore();
137 138 139 140 141 142 143
}

void ArthurOutputDev::endPage() {
}

void ArthurOutputDev::saveState(GfxState *state)
{
144 145 146 147 148
  m_currentPenStack.push(m_currentPen);
  m_currentBrushStack.push(m_currentBrush);
  m_rawFontStack.push(m_rawFont);
  m_codeToGIDStack.push(m_codeToGID);

149
  m_painter.top()->save();
150 151 152 153
}

void ArthurOutputDev::restoreState(GfxState *state)
{
154
  m_painter.top()->restore();
155 156 157 158 159 160 161 162 163

  m_codeToGID = m_codeToGIDStack.top();
  m_codeToGIDStack.pop();
  m_rawFont = m_rawFontStack.top();
  m_rawFontStack.pop();
  m_currentBrush = m_currentBrushStack.top();
  m_currentBrushStack.pop();
  m_currentPen = m_currentPenStack.top();
  m_currentPenStack.pop();
164 165 166 167
}

void ArthurOutputDev::updateAll(GfxState *state)
{
168
  OutputDev::updateAll(state);
169 170 171
  m_needFontUpdate = gTrue;
}

172 173 174
// Set CTM (Current Transformation Matrix) to a fixed matrix
void ArthurOutputDev::setDefaultCTM(double *ctm)
{
175
  m_painter.top()->setTransform(QTransform(ctm[0], ctm[1], ctm[2], ctm[3], ctm[4], ctm[5]));
176 177 178 179
}

// Update the CTM (Current Transformation Matrix), i.e., compose the old
// CTM with a new matrix.
180 181 182 183
void ArthurOutputDev::updateCTM(GfxState *state, double m11, double m12,
				double m21, double m22,
				double m31, double m32)
{
184 185 186 187
  updateLineDash(state);
  updateLineJoin(state);
  updateLineCap(state);
  updateLineWidth(state);
188 189 190 191

  QTransform update(m11, m12, m21, m22, m31, m32);

  // We could also set (rather than update) the painter transformation to state->getCMT();
192
  m_painter.top()->setTransform(update, true);
193 194 195 196
}

void ArthurOutputDev::updateLineDash(GfxState *state)
{
197 198 199 200
  double *dashPattern;
  int dashLength;
  double dashStart;
  state->getLineDash(&dashPattern, &dashLength, &dashStart);
201 202 203 204 205 206 207 208

  // Special handling for zero-length patterns, i.e., solid lines.
  // Simply calling QPen::setDashPattern with an empty pattern does *not*
  // result in a solid line.  Rather, the current pattern is unchanged.
  // See the implementation of the setDashPattern method in the file qpen.cpp.
  if (dashLength==0)
  {
    m_currentPen.setStyle(Qt::SolidLine);
209
    m_painter.top()->setPen(m_currentPen);
210 211 212
    return;
  }

213 214
  QVector<qreal> pattern(dashLength);
  for (int i = 0; i < dashLength; ++i) {
215 216 217
    // pdf measures the dash pattern in dots, but Qt uses the
    // line width as the unit.
    pattern[i] = dashPattern[i] / state->getLineWidth();
218 219 220
  }
  m_currentPen.setDashPattern(pattern);
  m_currentPen.setDashOffset(dashStart);
221
  m_painter.top()->setPen(m_currentPen);
222 223 224 225
}

void ArthurOutputDev::updateFlatness(GfxState *state)
{
226
  // qDebug() << "updateFlatness";
227 228 229 230 231 232
}

void ArthurOutputDev::updateLineJoin(GfxState *state)
{
  switch (state->getLineJoin()) {
  case 0:
233 234 235 236
    // The correct style here is Qt::SvgMiterJoin, *not* Qt::MiterJoin.
    // The two differ in what to do if the miter limit is exceeded.
    // See https://bugs.freedesktop.org/show_bug.cgi?id=102356
    m_currentPen.setJoinStyle(Qt::SvgMiterJoin);
237 238 239 240 241 242 243 244
    break;
  case 1:
    m_currentPen.setJoinStyle(Qt::RoundJoin);
    break;
  case 2:
    m_currentPen.setJoinStyle(Qt::BevelJoin);
    break;
  }
245
  m_painter.top()->setPen(m_currentPen);
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
}

void ArthurOutputDev::updateLineCap(GfxState *state)
{
  switch (state->getLineCap()) {
  case 0:
    m_currentPen.setCapStyle(Qt::FlatCap);
    break;
  case 1:
    m_currentPen.setCapStyle(Qt::RoundCap);
    break;
  case 2:
    m_currentPen.setCapStyle(Qt::SquareCap);
    break;
  }
261
  m_painter.top()->setPen(m_currentPen);
262 263 264 265
}

void ArthurOutputDev::updateMiterLimit(GfxState *state)
{
Pino Toscano's avatar
Pino Toscano committed
266
  m_currentPen.setMiterLimit(state->getMiterLimit());
267
  m_painter.top()->setPen(m_currentPen);
268 269 270 271
}

void ArthurOutputDev::updateLineWidth(GfxState *state)
{
272
  m_currentPen.setWidthF(state->getLineWidth());
273
  m_painter.top()->setPen(m_currentPen);
274 275 276 277 278
  // The updateLineDash method needs to know the line width, but it is sometimes
  // called before the updateLineWidth method.  To make sure that the last call
  // to updateLineDash before a drawing operation is always with the correct line
  // width, we call it here, right after a change to the line width.
  updateLineDash(state);
279 280 281 282 283 284 285
}

void ArthurOutputDev::updateFillColor(GfxState *state)
{
  GfxRGB rgb;
  QColor brushColour = m_currentBrush.color();
  state->getFillRGB(&rgb);
286
  brushColour.setRgbF(colToDbl(rgb.r), colToDbl(rgb.g), colToDbl(rgb.b), brushColour.alphaF());
287 288 289 290 291 292 293 294
  m_currentBrush.setColor(brushColour);
}

void ArthurOutputDev::updateStrokeColor(GfxState *state)
{
  GfxRGB rgb;
  QColor penColour = m_currentPen.color();
  state->getStrokeRGB(&rgb);
295
  penColour.setRgbF(colToDbl(rgb.r), colToDbl(rgb.g), colToDbl(rgb.b), penColour.alphaF());
296
  m_currentPen.setColor(penColour);
297
  m_painter.top()->setPen(m_currentPen);
298 299
}

300 301 302 303 304 305 306 307 308 309 310 311
void ArthurOutputDev::updateBlendMode(GfxState * state)
{
  GfxBlendMode blendMode = state->getBlendMode();

  // missing composition modes in QPainter:
  // - CompositionMode_Hue
  // - CompositionMode_Color
  // - CompositionMode_Luminosity
  // - CompositionMode_Saturation

  switch(blendMode){
  case gfxBlendMultiply:
312
    m_painter.top()->setCompositionMode(QPainter::CompositionMode_Multiply);
313 314
    break;
  case gfxBlendScreen:
315
    m_painter.top()->setCompositionMode(QPainter::CompositionMode_Screen);
316 317
    break;
  case gfxBlendDarken:
318
    m_painter.top()->setCompositionMode(QPainter::CompositionMode_Darken);
319 320
    break;
  case gfxBlendLighten:
321
    m_painter.top()->setCompositionMode(QPainter::CompositionMode_Lighten);
322 323
    break;
  case gfxBlendColorDodge:
324
    m_painter.top()->setCompositionMode(QPainter::CompositionMode_ColorDodge);
325 326
    break;
  case gfxBlendColorBurn:
327
    m_painter.top()->setCompositionMode(QPainter::CompositionMode_ColorBurn);
328 329
    break;
  case gfxBlendHardLight:
330
    m_painter.top()->setCompositionMode(QPainter::CompositionMode_HardLight);
331 332
    break;
  case gfxBlendSoftLight:
333
    m_painter.top()->setCompositionMode(QPainter::CompositionMode_SoftLight);
334 335
    break;
  case gfxBlendDifference:
336
    m_painter.top()->setCompositionMode(QPainter::CompositionMode_Difference);
337 338
    break;
  case gfxBlendExclusion:
339
    m_painter.top()->setCompositionMode(QPainter::CompositionMode_Exclusion);
340 341
    break;
  case gfxBlendColor:
342
    m_painter.top()->setCompositionMode(QPainter::CompositionMode_Plus);
343 344 345 346
    break;
  default:
    qDebug() << "Unsupported blend mode, falling back to CompositionMode_SourceOver";
  case gfxBlendNormal:
347
    m_painter.top()->setCompositionMode(QPainter::CompositionMode_SourceOver);
348 349 350 351
    break;
  }
}

352 353 354 355 356 357 358 359 360 361 362 363
void ArthurOutputDev::updateFillOpacity(GfxState *state)
{
  QColor brushColour= m_currentBrush.color();
  brushColour.setAlphaF(state->getFillOpacity());
  m_currentBrush.setColor(brushColour);
}

void ArthurOutputDev::updateStrokeOpacity(GfxState *state)
{
  QColor penColour= m_currentPen.color();
  penColour.setAlphaF(state->getStrokeOpacity());
  m_currentPen.setColor(penColour);
364
  m_painter.top()->setPen(m_currentPen);
365 366 367 368
}

void ArthurOutputDev::updateFont(GfxState *state)
{
369 370
  GfxFont *gfxFont = state->getFont();
  if (!gfxFont)
371 372 373 374 375
  {
    return;
  }

  // is the font in the cache?
376
  ArthurFontID fontID = {*gfxFont->getID(), state->getFontSize()};
377 378 379 380 381 382 383 384 385 386 387 388
  auto cacheEntry = m_rawFontCache.find(fontID);

  if (cacheEntry!=m_rawFontCache.end()) {

    // Take the font from the cache
    m_rawFont = cacheEntry->second.get();

  } else {

    // New font: load it into the cache
    float fontSize = state->getFontSize();

389
    std::unique_ptr<GfxFontLoc> fontLoc(gfxFont->locateFont(xref, nullptr));
390 391 392 393 394 395

    if (fontLoc) {
      // load the font from respective location
      switch (fontLoc->locType) {
      case gfxFontLocEmbedded: {// if there is an embedded font, read it to memory
        int fontDataLen;
396
        const char* fontData = gfxFont->readEmbFontFile(xref, &fontDataLen);
397 398 399

        m_rawFont = new QRawFont(QByteArray(fontData, fontDataLen), fontSize);
        m_rawFontCache.insert(std::make_pair(fontID,std::unique_ptr<QRawFont>(m_rawFont)));
400 401 402

        // Free the font data, it was copied in the QByteArray constructor
        free((char*)fontData);
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
        break;
      }
      case gfxFontLocExternal:{ // font is in an external font file
        QString fontFile(fontLoc->path->getCString());
        m_rawFont = new QRawFont(fontFile, fontSize);
        m_rawFontCache.insert(std::make_pair(fontID,std::unique_ptr<QRawFont>(m_rawFont)));
        break;
      }
      case gfxFontLocResident:{ // font resides in a PS printer
        qDebug() << "Font Resident Encoding:" << fontLoc->encoding->getCString() << ", not implemented yet!";

      break;
      }
      }// end switch

    } else {
      qDebug() << "Font location not found!";
      return;
    }
  }

  if (!m_rawFont->isValid()) {
    qDebug() << "RawFont is not valid";
  }

  // *****************************************************************************
  //  We have now successfully loaded the font into a QRawFont object.  This
  //  allows us to draw all the glyphs in the font.  However, what is missing is
  //  the charcode-to-glyph-index mapping.  Apparently, Qt does not provide this
  //  information at all.  We therefore now load the font again, this time into
  //  a Splash font object.  This is wasteful, but I see no other way to access
  //  the important glyph-index mapping.
  // *****************************************************************************

437
#ifdef HAVE_SPLASH
438 439
  GfxFontType fontType;
  SplashFontFile *fontFile;
440
  SplashFontSrc *fontsrc = nullptr;
441
  FoFiTrueType *ff;
442
  GooString *fileName;
443
  char *tmpBuf;
Albert Astals Cid's avatar
Albert Astals Cid committed
444
  int tmpBufLen = 0;
Albert Astals Cid's avatar
Albert Astals Cid committed
445
  int *codeToGID;
446
  SplashCoord mat[4] = {0,0,0,0};
Albert Astals Cid's avatar
Albert Astals Cid committed
447
  int n;
448
  int faceIndex = 0;
449 450
  SplashCoord matrix[6] = {1,0,0,1,0,0};
  SplashFTFontFile* ftFontFile;
451 452

  m_needFontUpdate = false;
453 454
  fileName = nullptr;
  tmpBuf = nullptr;
455 456 457

  fontType = gfxFont->getType();
  if (fontType == fontType3) {
458
    return;
459 460
  }

461 462 463
  // Default: no codeToGID table
  m_codeToGID = nullptr;

464
  // check the font file cache
465
  SplashOutFontFileID *id = new SplashOutFontFileID(gfxFont->getID());
466 467 468 469 470
  if ((fontFile = m_fontEngine->getFontFile(id))) {
    delete id;

  } else {

471 472
    std::unique_ptr<GfxFontLoc> fontLoc(gfxFont->locateFont(xref, nullptr));
    if (!fontLoc) {
473 474 475 476 477 478 479 480 481
      error(errSyntaxError, -1, "Couldn't find a font for '{0:s}'",
	    gfxFont->getName() ? gfxFont->getName()->getCString()
	                       : "(unnamed)");
      goto err2;
    }

    // embedded font
    if (fontLoc->locType == gfxFontLocEmbedded) {
      // if there is an embedded font, read it to memory
482 483
      tmpBuf = gfxFont->readEmbFontFile(xref, &tmpBufLen);
      if (! tmpBuf)
484 485
	goto err2;

486 487 488 489
    // external font
    } else { // gfxFontLocExternal
      fileName = fontLoc->path;
      fontType = fontLoc->fontType;
490 491
    }

492 493 494 495
    fontsrc = new SplashFontSrc;
    if (fileName)
      fontsrc->setFile(fileName, gFalse);
    else
496
      fontsrc->setBuf(tmpBuf, tmpBufLen, gTrue);
497
    
498 499 500 501 502
    // load the font file
    switch (fontType) {
    case fontType1:
      if (!(fontFile = m_fontEngine->loadType1Font(
			   id,
503
			   fontsrc,
504
			   (const char **)((Gfx8BitFont *)gfxFont)->getEncoding()))) {
505
	error(errSyntaxError, -1, "Couldn't create a font for '{0:s}'",
506 507 508 509 510 511 512 513
	      gfxFont->getName() ? gfxFont->getName()->getCString()
	                         : "(unnamed)");
	goto err2;
      }
      break;
    case fontType1C:
      if (!(fontFile = m_fontEngine->loadType1CFont(
			   id,
514
			   fontsrc,
515
			   (const char **)((Gfx8BitFont *)gfxFont)->getEncoding()))) {
516
	error(errSyntaxError, -1, "Couldn't create a font for '{0:s}'",
517 518 519 520 521
	      gfxFont->getName() ? gfxFont->getName()->getCString()
	                         : "(unnamed)");
	goto err2;
      }
      break;
522 523 524 525
    case fontType1COT:
      if (!(fontFile = m_fontEngine->loadOpenTypeT1CFont(
			   id,
			   fontsrc,
526
			   (const char **)((Gfx8BitFont *)gfxFont)->getEncoding()))) {
527
	error(errSyntaxError, -1, "Couldn't create a font for '{0:s}'",
528 529
	      gfxFont->getName() ? gfxFont->getName()->getCString()
	                         : "(unnamed)");
530 531
	goto err2;
      }
532 533 534 535 536 537 538 539 540 541 542 543
      break;
    case fontTrueType:
    case fontTrueTypeOT:
	if (fileName)
	 ff = FoFiTrueType::load(fileName->getCString());
	else
	ff = FoFiTrueType::make(tmpBuf, tmpBufLen);
      if (ff) {
	codeToGID = ((Gfx8BitFont *)gfxFont)->getCodeToGIDMap(ff);
	n = 256;
	delete ff;
      } else {
544
	codeToGID = nullptr;
545 546
	n = 0;
      }
547 548
      if (!(fontFile = m_fontEngine->loadTrueTypeFont(
			   id,
549
			   fontsrc,
550
			   codeToGID, n))) {
551
	error(errSyntaxError, -1, "Couldn't create a font for '{0:s}'",
552 553 554 555 556 557 558 559 560
	      gfxFont->getName() ? gfxFont->getName()->getCString()
	                         : "(unnamed)");
	goto err2;
      }
      break;
    case fontCIDType0:
    case fontCIDType0C:
      if (!(fontFile = m_fontEngine->loadCIDFont(
			   id,
561
			   fontsrc))) {
562
	error(errSyntaxError, -1, "Couldn't create a font for '{0:s}'",
563 564 565 566 567
	      gfxFont->getName() ? gfxFont->getName()->getCString()
	                         : "(unnamed)");
	goto err2;
      }
      break;
568
    case fontCIDType0COT:
Albert Astals Cid's avatar
Albert Astals Cid committed
569 570 571 572 573 574
      if (((GfxCIDFont *)gfxFont)->getCIDToGID()) {
	n = ((GfxCIDFont *)gfxFont)->getCIDToGIDLen();
	codeToGID = (int *)gmallocn(n, sizeof(int));
	memcpy(codeToGID, ((GfxCIDFont *)gfxFont)->getCIDToGID(),
	       n * sizeof(int));
      } else {
575
	codeToGID = nullptr;
Albert Astals Cid's avatar
Albert Astals Cid committed
576 577
	n = 0;
      }      
578 579
      if (!(fontFile = m_fontEngine->loadOpenTypeCFFFont(
			   id,
Albert Astals Cid's avatar
Albert Astals Cid committed
580 581
			   fontsrc,
			   codeToGID, n))) {
582
	error(errSyntaxError, -1, "Couldn't create a font for '{0:s}'",
583 584 585 586 587
	      gfxFont->getName() ? gfxFont->getName()->getCString()
	                         : "(unnamed)");
	goto err2;
      }
      break;
588
    case fontCIDType2:
589
    case fontCIDType2OT:
590
      codeToGID = nullptr;
591 592 593 594
      n = 0;
      if (((GfxCIDFont *)gfxFont)->getCIDToGID()) {
	n = ((GfxCIDFont *)gfxFont)->getCIDToGIDLen();
	if (n) {
Albert Astals Cid's avatar
Albert Astals Cid committed
595
	  codeToGID = (int *)gmallocn(n, sizeof(int));
596 597 598 599 600 601 602 603 604 605 606 607 608
	  memcpy(codeToGID, ((GfxCIDFont *)gfxFont)->getCIDToGID(),
		  n * sizeof(Gushort));
	}
      } else {
	if (fileName)
	  ff = FoFiTrueType::load(fileName->getCString());
	else
	  ff = FoFiTrueType::make(tmpBuf, tmpBufLen);
	if (! ff)
	  goto err2;
	codeToGID = ((GfxCIDFont *)gfxFont)->getCodeToGIDMap(ff, &n);
	delete ff;
      }
609 610
      if (!(fontFile = m_fontEngine->loadTrueTypeFont(
			   id,
611
			   fontsrc,
612
			   codeToGID, n, faceIndex))) {
613
	error(errSyntaxError, -1, "Couldn't create a font for '{0:s}'",
614 615 616 617 618 619 620 621 622 623
	      gfxFont->getName() ? gfxFont->getName()->getCString()
	                         : "(unnamed)");
	goto err2;
      }
      break;
    default:
      // this shouldn't happen
      goto err2;
    }
  }
624

625 626 627
  ftFontFile = dynamic_cast<SplashFTFontFile*>(fontFile);
  if (ftFontFile)
    m_codeToGID = ftFontFile->getCodeToGID();
628

629 630 631 632 633
  // create dummy font
  // The font matrices are bogus, but we will never use the glyphs anyway.
  // However we need to call m_fontEngine->getFont, in order to have the
  // font in the Splash font cache.  Otherwise we'd load it again and again.
  m_fontEngine->getFont(fontFile, mat, matrix);
634

635 636
  if (fontsrc && !fontsrc->isFile)
      fontsrc->unref();
637 638 639 640
  return;

 err2:
  delete id;
641
#endif
642 643
}

644
static QPainterPath convertPath(GfxState *state, GfxPath *path, Qt::FillRule fillRule)
645 646 647 648 649
{
  GfxSubpath *subpath;
  int i, j;

  QPainterPath qPath;
650
  qPath.setFillRule(fillRule);
651 652 653
  for (i = 0; i < path->getNumSubpaths(); ++i) {
    subpath = path->getSubpath(i);
    if (subpath->getNumPoints() > 0) {
654
      qPath.moveTo(subpath->getX(0), subpath->getY(0));
655 656 657
      j = 1;
      while (j < subpath->getNumPoints()) {
	if (subpath->getCurve(j)) {
658 659 660
          qPath.cubicTo( subpath->getX(j),   subpath->getY(j),
                         subpath->getX(j+1), subpath->getY(j+1),
                         subpath->getX(j+2), subpath->getY(j+2));
661 662
	  j += 3;
	} else {
663
	  qPath.lineTo(subpath->getX(j), subpath->getY(j));
664 665 666 667 668 669 670 671 672 673 674 675 676
	  ++j;
	}
      }
      if (subpath->isClosed()) {
	qPath.closeSubpath();
      }
    }
  }
  return qPath;
}

void ArthurOutputDev::stroke(GfxState *state)
{
677
  m_painter.top()->strokePath( convertPath( state, state->getPath(), Qt::OddEvenFill ), m_currentPen );
678 679 680 681
}

void ArthurOutputDev::fill(GfxState *state)
{
682
  m_painter.top()->fillPath( convertPath( state, state->getPath(), Qt::WindingFill ), m_currentBrush );
683 684 685 686
}

void ArthurOutputDev::eoFill(GfxState *state)
{
687
  m_painter.top()->fillPath( convertPath( state, state->getPath(), Qt::OddEvenFill ), m_currentBrush );
688 689 690 691
}

void ArthurOutputDev::clip(GfxState *state)
{
692
  m_painter.top()->setClipPath(convertPath( state, state->getPath(), Qt::WindingFill ), Qt::IntersectClip );
693 694 695 696
}

void ArthurOutputDev::eoClip(GfxState *state)
{
697
  m_painter.top()->setClipPath(convertPath( state, state->getPath(), Qt::OddEvenFill ), Qt::IntersectClip );
698 699
}

700 701 702
void ArthurOutputDev::drawChar(GfxState *state, double x, double y,
			       double dx, double dy,
			       double originX, double originY,
703
			       CharCode code, int nBytes, Unicode *u, int uLen) {
704 705

  // check for invisible text -- this is used by Acrobat Capture
706 707 708
  int render = state->getRender();
  if (render == 3 || !m_rawFont) {
    qDebug() << "Invisible text found!";
709 710 711
    return;
  }

712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
  if (!(render & 1))
  {
    quint32 glyphIndex = (m_codeToGID) ? m_codeToGID[code] : code;
    QPointF glyphPosition = QPointF(x-originX, y-originY);

    // QGlyphRun objects can hold an entire sequence of glyphs, and it would possibly
    // be more efficient to simply note the glyph and glyph position here and then
    // draw several glyphs at once in the endString method.  What keeps us from doing
    // that is the transformation below: each glyph needs to be drawn upside down,
    // i.e., reflected at its own baseline.  Since we have no guarantee that this
    // baseline is the same for all glyphs in a string we have to do it one by one.
    QGlyphRun glyphRun;
    glyphRun.setRawData(&glyphIndex, &glyphPosition, 1);
    glyphRun.setRawFont(*m_rawFont);

    // Store the QPainter state; we need to modify it temporarily
728
    m_painter.top()->save();
729 730 731 732 733 734 735 736 737 738

    // Apply the text matrix to the glyph.  The glyph is not scaled by the font size,
    // because the font in m_rawFont already has the correct size.
    // Additionally, the CTM is upside down, i.e., it contains a negative Y-scaling
    // entry.  Therefore, Qt will paint the glyphs upside down.  We need to temporarily
    // reflect the page at glyphPosition.y().

    // Make the glyph position the coordinate origin -- that's our center of scaling
    const double *textMat = state->getTextMat();

739
    m_painter.top()->translate(QPointF(glyphPosition.x(),glyphPosition.y()));
740 741 742 743 744 745 746 747

    QTransform textTransform(textMat[0] * state->getHorizScaling(),
                             textMat[1] * state->getHorizScaling(),
                             -textMat[2], // reflect at the horizontal axis,
                             -textMat[3], // because CTM is upside-down.
                             0,
                             0);

748
    m_painter.top()->setTransform(textTransform,true);
749 750 751 752 753 754 755 756 757 758 759 760

    // We are painting a filled glyph here.  But QPainter uses the pen to draw even filled text,
    // not the brush.  (see, e.g.,  http://doc.qt.io/qt-5/qpainter.html#setPen )
    // Therefore we have to temporarily overwrite the pen color.

    // Since we are drawing a filled glyph, one would really expect to have m_currentBrush
    // have the correct color.  However, somehow state->getFillRGB can change without
    // updateFillColor getting called.  Then m_currentBrush may not contain the correct color.
    GfxRGB rgb;
    state->getFillRGB(&rgb);
    QColor fontColor;
    fontColor.setRgbF(colToDbl(rgb.r), colToDbl(rgb.g), colToDbl(rgb.b), state->getFillOpacity());
761
    m_painter.top()->setPen(fontColor);
762 763

    // Actually draw the glyph
764
    m_painter.top()->drawGlyphRun(QPointF(-glyphPosition.x(),-glyphPosition.y()), glyphRun);
765 766

    // Restore transformation and pen color
767
    m_painter.top()->restore();
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
  }
}

GBool ArthurOutputDev::beginType3Char(GfxState *state, double x, double y,
				      double dx, double dy,
				      CharCode code, Unicode *u, int uLen)
{
  return gFalse;
}

void ArthurOutputDev::endType3Char(GfxState *state)
{
}

void ArthurOutputDev::type3D0(GfxState *state, double wx, double wy)
{
}

void ArthurOutputDev::type3D1(GfxState *state, double wx, double wy,
			      double llx, double lly, double urx, double ury)
{
}

void ArthurOutputDev::endTextObject(GfxState *state)
{
}


void ArthurOutputDev::drawImageMask(GfxState *state, Object *ref, Stream *str,
				    int width, int height, GBool invert,
798
				    GBool interpolate, GBool inlineImg)
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815
{
  qDebug() << "drawImageMask";
#if 0
  unsigned char *buffer;
  unsigned char *dest;
  cairo_surface_t *image;
  cairo_pattern_t *pattern;
  int x, y;
  ImageStream *imgStr;
  Guchar *pix;
  double *ctm;
  cairo_matrix_t matrix;
  int invert_bit;
  int row_stride;

  row_stride = (width + 3) & ~3;
  buffer = (unsigned char *) malloc (height * row_stride);
816
  if (buffer == nullptr) {
817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
    error(-1, "Unable to allocate memory for image.");
    return;
  }

  /* TODO: Do we want to cache these? */
  imgStr = new ImageStream(str, width, 1, 1);
  imgStr->reset();

  invert_bit = invert ? 1 : 0;

  for (y = 0; y < height; y++) {
    pix = imgStr->getLine();
    dest = buffer + y * row_stride;
    for (x = 0; x < width; x++) {

      if (pix[x] ^ invert_bit)
	*dest++ = 0;
      else
	*dest++ = 255;
    }
  }

  image = cairo_image_surface_create_for_data (buffer, CAIRO_FORMAT_A8,
					  width, height, row_stride);
841
  if (image == nullptr)
842 843
    return;
  pattern = cairo_pattern_create_for_surface (image);
844
  if (pattern == nullptr)
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
    return;

  ctm = state->getCTM();
  LOG (printf ("drawImageMask %dx%d, matrix: %f, %f, %f, %f, %f, %f\n",
	       width, height, ctm[0], ctm[1], ctm[2], ctm[3], ctm[4], ctm[5]));
  matrix.xx = ctm[0] / width;
  matrix.xy = -ctm[2] / height;
  matrix.yx = ctm[1] / width;
  matrix.yy = -ctm[3] / height;
  matrix.x0 = ctm[2] + ctm[4];
  matrix.y0 = ctm[3] + ctm[5];
  cairo_matrix_invert (&matrix);
  cairo_pattern_set_matrix (pattern, &matrix);

  cairo_pattern_set_filter (pattern, CAIRO_FILTER_BEST);
  /* FIXME: Doesn't the image mask support any colorspace? */
  cairo_set_source_rgb (cairo, fill_color.r, fill_color.g, fill_color.b);
  cairo_mask (cairo, pattern);

  cairo_pattern_destroy (pattern);
  cairo_surface_destroy (image);
  free (buffer);
867
  imgStr->close ();
868 869 870 871 872 873 874 875
  delete imgStr;
#endif
}

//TODO: lots more work here.
void ArthurOutputDev::drawImage(GfxState *state, Object *ref, Stream *str,
				int width, int height,
				GfxImageColorMap *colorMap,
876
				GBool interpolate, int *maskColors, GBool inlineImg)
877
{
878 879
  unsigned int *data;
  unsigned int *line;
880 881 882
  int x, y;
  ImageStream *imgStr;
  Guchar *pix;
Krzysztof Kowalczyk's avatar
Krzysztof Kowalczyk committed
883
  int i;
884 885
  QImage image;
  int stride;
886 887 888 889 890 891 892
  
  /* TODO: Do we want to cache these? */
  imgStr = new ImageStream(str, width,
			   colorMap->getNumPixelComps(),
			   colorMap->getBits());
  imgStr->reset();
  
893 894 895 896 897
  image = QImage(width, height, QImage::Format_ARGB32);
  data = (unsigned int *)image.bits();
  stride = image.bytesPerLine()/4;
  for (y = 0; y < height; y++) {
    pix = imgStr->getLine();
898 899 900
    // Invert the vertical coordinate: y is increasing from top to bottom
    // on the page, but y is increasing bottom to top in the picture.
    line = data+(height-1-y)*stride;
901
    colorMap->getRGBLine(pix, line, width);
902

903
    if (maskColors) {
904
      for (x = 0; x < width; x++) {
905 906 907 908 909 910 911 912 913
        for (i = 0; i < colorMap->getNumPixelComps(); ++i) {
            if (pix[i] < maskColors[2*i] * 255||
                pix[i] > maskColors[2*i+1] * 255) {
                *line = *line | 0xff000000;
                break;
            }
        }
        pix += colorMap->getNumPixelComps();
        line++;
914
      }
915 916
    } else {
      for (x = 0; x < width; x++) { *line = *line | 0xff000000; line++; }
917 918 919
    }
  }

920 921
  // At this point, the QPainter coordinate transformation (CTM) is such
  // that QRect(0,0,1,1) is exactly the area of the image.
922
  m_painter.top()->drawImage( QRect(0,0,1,1), image );
923
  delete imgStr;
924 925

}
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941

void ArthurOutputDev::drawSoftMaskedImage(GfxState *state, Object *ref, Stream *str,
                                          int width, int height,
                                          GfxImageColorMap *colorMap,
                                          GBool interpolate,
                                          Stream *maskStr,
                                          int maskWidth, int maskHeight,
                                          GfxImageColorMap *maskColorMap,
                                          GBool maskInterpolate)
{
  // Bail out if the image size doesn't match the mask size.  I don't know
  // what to do in this case.
  if (width!=maskWidth || height!=maskHeight)
  {
    qDebug() << "Soft mask size does not match image size!";
    drawImage(state, ref, str, width, height, colorMap, interpolate, nullptr, gFalse);
942
    return;
943 944 945 946 947 948 949 950
  }

  // Bail out if the mask isn't a single channel.  I don't know
  // what to do in this case.
  if (maskColorMap->getColorSpace()->getNComps() != 1)
  {
    qDebug() << "Soft mask is not a single 8-bit channel!";
    drawImage(state, ref, str, width, height, colorMap, interpolate, nullptr, gFalse);
951
    return;
952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991
  }

  /* TODO: Do we want to cache these? */
  std::unique_ptr<ImageStream> imgStr(new ImageStream(str, width,
                                                      colorMap->getNumPixelComps(),
                                                      colorMap->getBits()));
  imgStr->reset();

  std::unique_ptr<ImageStream> maskImageStr(new ImageStream(maskStr, maskWidth,
                                                            maskColorMap->getNumPixelComps(),
                                                            maskColorMap->getBits()));
  maskImageStr->reset();

  QImage image(width, height, QImage::Format_ARGB32);
  unsigned int *data = (unsigned int *)image.bits();
  int stride = image.bytesPerLine()/4;

  std::vector<Guchar> maskLine(maskWidth);

  for (int y = 0; y < height; y++) {

    Guchar *pix = imgStr->getLine();
    Guchar *maskPix = maskImageStr->getLine();

    // Invert the vertical coordinate: y is increasing from top to bottom
    // on the page, but y is increasing bottom to top in the picture.
    unsigned int* line = data+(height-1-y)*stride;
    colorMap->getRGBLine(pix, line, width);

    // Apply the mask values to the image alpha channel
    maskColorMap->getGrayLine(maskPix, maskLine.data(), width);
    for (int x = 0; x < width; x++)
    {
      *line = *line | (maskLine[x]<<24);
      line++;
    }
  }

  // At this point, the QPainter coordinate transformation (CTM) is such
  // that QRect(0,0,1,1) is exactly the area of the image.
992
  m_painter.top()->drawImage( QRect(0,0,1,1), image );
993 994
}

995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
void ArthurOutputDev::beginTransparencyGroup(GfxState * /*state*/, double * /*bbox*/,
                                             GfxColorSpace * /*blendingColorSpace*/,
                                             GBool /*isolated*/, GBool /*knockout*/,
                                             GBool /*forSoftMask*/)
{
  // The entire transparency group will be painted into a
  // freshly created QPicture object.  Since an existing painter
  // cannot change its paint device, we need to construct a
  // new QPainter object as well.
  m_qpictures.push(new QPicture);
  m_painter.push(new QPainter(m_qpictures.top()));
}

void ArthurOutputDev::endTransparencyGroup(GfxState * /*state*/)
{
  // Stop painting into the group
  m_painter.top()->end();

  // Kill the painter that has been used for the transparency group
  delete(m_painter.top());
  m_painter.pop();

  // Store the QPicture object that holds the result of the transparency group
  // painting.  It will be painted and deleted in the method paintTransparencyGroup.
  if (m_lastTransparencyGroupPicture)
  {
    qDebug() << "Found a transparency group that has not been painted";
    delete(m_lastTransparencyGroupPicture);
  }
  m_lastTransparencyGroupPicture = m_qpictures.top();
  m_qpictures.pop();
}

void ArthurOutputDev::paintTransparencyGroup(GfxState * /*state*/, double * /*bbox*/)
{
  // Actually draw the transparency group
  m_painter.top()->drawPicture(0,0,*m_lastTransparencyGroupPicture);

  // And delete it
  delete(m_lastTransparencyGroupPicture);
  m_lastTransparencyGroupPicture = nullptr;
}