ArthurOutputDev.cc 37.8 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>
Albert Astals Cid's avatar
Albert Astals Cid committed
17
// Copyright (C) 2005-2009, 2011, 2012, 2014, 2015, 2018 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, 2018 Oliver Sander <oliver.sander@tu-dresden.de>
27
// Copyright (C) 2017 Adrian Johnson <ajohnson@redneon.com>
28
// 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
29
// Copyright (C) 2018 Adam Reichold <adam.reichold@t-online.de>
30 31 32
//
// 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
33 34 35 36 37 38 39 40
//
//========================================================================

#include <config.h>

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

41 42
#include <array>

43 44 45 46 47 48 49 50 51
#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>
52
#include <fofi/FoFiType1C.h>
53
#include "ArthurOutputDev.h"
54 55 56
#include "Page.h"
#include "Gfx.h"
#include "PDFDoc.h"
57 58

#include <QtCore/QtDebug>
59 60
#include <QRawFont>
#include <QGlyphRun>
61
#include <QtGui/QPainterPath>
62 63
#include <QPicture>

64

65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
class ArthurType3Font
{
public:

  ArthurType3Font(PDFDoc* doc, Gfx8BitFont* font);

  const QPicture& getGlyph(int gid) const;

private:
  PDFDoc* m_doc;
  Gfx8BitFont* m_font;

  mutable std::vector<std::unique_ptr<QPicture> > glyphs;

public:
  std::vector<int> codeToGID;
};

ArthurType3Font::ArthurType3Font(PDFDoc* doc, Gfx8BitFont* font)
: m_doc(doc), m_font(font)
{
  char *name;
  const Dict* charProcs = font->getCharProcs();

  // Storage for the rendered glyphs
  glyphs.resize(charProcs->getLength());

  // Compute the code-to-GID map
  char **enc = font->getEncoding();

  codeToGID.resize(256);

  for (int i = 0; i < 256; ++i) {
    codeToGID[i] = 0;
    if (charProcs && (name = enc[i])) {
      for (int j = 0; j < charProcs->getLength(); j++) {
        if (strcmp(name, charProcs->getKey(j)) == 0) {
          codeToGID[i] = j;
        }
      }
    }
  }
}

const QPicture& ArthurType3Font::getGlyph(int gid) const
{
  if (!glyphs[gid]) {

    // Glyph has not been rendered before: render it now

    // Smallest box that contains all the glyphs from this font
    const double* fontBBox = m_font->getFontBBox();
    PDFRectangle box(fontBBox[0], fontBBox[1], fontBBox[2], fontBBox[3]);

    Dict* resDict = m_font->getResources();

    QPainter glyphPainter;
122
    glyphs[gid] = std::make_unique<QPicture>();
123
    glyphPainter.begin(glyphs[gid].get());
124
    auto output_dev = std::make_unique<ArthurOutputDev>(&glyphPainter);
125

126 127 128 129 130
    auto gfx = std::make_unique<Gfx>(
	  m_doc, output_dev.get(), resDict,
	  &box,  // pagebox
	  nullptr  // cropBox
    );
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146

    output_dev->startDoc(m_doc);

    output_dev->startPage (1, gfx->getState(), gfx->getXRef());

    const Dict* charProcs = m_font->getCharProcs();
    Object charProc = charProcs->getVal(gid);
    gfx->display(&charProc);

    glyphPainter.end();
  }

  return *glyphs[gid];
}


147 148 149 150 151
//------------------------------------------------------------------------
// ArthurOutputDev
//------------------------------------------------------------------------

ArthurOutputDev::ArthurOutputDev(QPainter *painter):
152
  m_lastTransparencyGroupPicture(nullptr),
153
  m_fontHinting(NoHinting)
154
{
155
  m_painter.push(painter);
156
  m_currentBrush = QBrush(Qt::SolidPattern);
157 158 159 160 161 162 163 164 165 166 167 168

  auto error = FT_Init_FreeType(&m_ftLibrary);
  if (error)
  {
    qCritical() << "An error occurred will initializing the FreeType library";
  }

  // as of FT 2.1.8, CID fonts are indexed by CID instead of GID
  FT_Int major, minor, patch;
  FT_Library_Version(m_ftLibrary, &major, &minor, &patch);
  m_useCIDs = major > 2 ||
              (major == 2 && (minor > 1 || (minor == 1 && patch > 7)));
169 170 171 172
}

ArthurOutputDev::~ArthurOutputDev()
{
173 174 175 176 177
  for (auto& codeToGID : m_codeToGIDCache) {
    gfree(const_cast<int*>(codeToGID.second));
  }

  FT_Done_FreeType(m_ftLibrary);
178 179
}

180 181 182
void ArthurOutputDev::startDoc(PDFDoc* doc) {
  xref = doc->getXRef();
  m_doc = doc;
183 184 185 186 187 188 189 190 191

  if (!globalParams->getEnableFreeType()) {
    qCritical() << "Arthur backend will not render text without FreeType, but it is disabled!";
  }

  for (auto& codeToGID : m_codeToGIDCache) {
    gfree(const_cast<int*>(codeToGID.second));
  }
  m_codeToGIDCache.clear();
192 193
}

Albert Astals Cid's avatar
Albert Astals Cid committed
194
void ArthurOutputDev::startPage(int pageNum, GfxState *state, XRef *)
195
{}
196 197 198 199 200 201

void ArthurOutputDev::endPage() {
}

void ArthurOutputDev::saveState(GfxState *state)
{
202 203 204
  m_currentPenStack.push(m_currentPen);
  m_currentBrushStack.push(m_currentBrush);
  m_rawFontStack.push(m_rawFont);
205
  m_type3FontStack.push(m_currentType3Font);
206 207
  m_codeToGIDStack.push(m_codeToGID);

208
  m_painter.top()->save();
209 210 211 212
}

void ArthurOutputDev::restoreState(GfxState *state)
{
213
  m_painter.top()->restore();
214 215 216 217 218

  m_codeToGID = m_codeToGIDStack.top();
  m_codeToGIDStack.pop();
  m_rawFont = m_rawFontStack.top();
  m_rawFontStack.pop();
219 220
  m_currentType3Font = m_type3FontStack.top();
  m_type3FontStack.pop();
221 222 223 224
  m_currentBrush = m_currentBrushStack.top();
  m_currentBrushStack.pop();
  m_currentPen = m_currentPenStack.top();
  m_currentPenStack.pop();
225 226 227 228
}

void ArthurOutputDev::updateAll(GfxState *state)
{
229
  OutputDev::updateAll(state);
230
  m_needFontUpdate = true;
231 232
}

233
// Set CTM (Current Transformation Matrix) to a fixed matrix
Albert Astals Cid's avatar
Albert Astals Cid committed
234
void ArthurOutputDev::setDefaultCTM(const double *ctm)
235
{
236
  m_painter.top()->setTransform(QTransform(ctm[0], ctm[1], ctm[2], ctm[3], ctm[4], ctm[5]));
237 238 239 240
}

// Update the CTM (Current Transformation Matrix), i.e., compose the old
// CTM with a new matrix.
241 242 243 244
void ArthurOutputDev::updateCTM(GfxState *state, double m11, double m12,
				double m21, double m22,
				double m31, double m32)
{
245 246 247 248
  updateLineDash(state);
  updateLineJoin(state);
  updateLineCap(state);
  updateLineWidth(state);
249 250 251 252

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

  // We could also set (rather than update) the painter transformation to state->getCMT();
253
  m_painter.top()->setTransform(update, true);
254 255 256 257
}

void ArthurOutputDev::updateLineDash(GfxState *state)
{
258 259 260 261
  double *dashPattern;
  int dashLength;
  double dashStart;
  state->getLineDash(&dashPattern, &dashLength, &dashStart);
262 263 264 265 266 267 268 269

  // 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);
270
    m_painter.top()->setPen(m_currentPen);
271 272 273
    return;
  }

274 275
  QVector<qreal> pattern(dashLength);
  for (int i = 0; i < dashLength; ++i) {
276 277 278
    // pdf measures the dash pattern in dots, but Qt uses the
    // line width as the unit.
    pattern[i] = dashPattern[i] / state->getLineWidth();
279 280 281
  }
  m_currentPen.setDashPattern(pattern);
  m_currentPen.setDashOffset(dashStart);
282
  m_painter.top()->setPen(m_currentPen);
283 284 285 286
}

void ArthurOutputDev::updateFlatness(GfxState *state)
{
287
  // qDebug() << "updateFlatness";
288 289 290 291 292 293
}

void ArthurOutputDev::updateLineJoin(GfxState *state)
{
  switch (state->getLineJoin()) {
  case 0:
294 295 296 297
    // 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);
298 299 300 301 302 303 304 305
    break;
  case 1:
    m_currentPen.setJoinStyle(Qt::RoundJoin);
    break;
  case 2:
    m_currentPen.setJoinStyle(Qt::BevelJoin);
    break;
  }
306
  m_painter.top()->setPen(m_currentPen);
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
}

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;
  }
322
  m_painter.top()->setPen(m_currentPen);
323 324 325 326
}

void ArthurOutputDev::updateMiterLimit(GfxState *state)
{
Pino Toscano's avatar
Pino Toscano committed
327
  m_currentPen.setMiterLimit(state->getMiterLimit());
328
  m_painter.top()->setPen(m_currentPen);
329 330 331 332
}

void ArthurOutputDev::updateLineWidth(GfxState *state)
{
333
  m_currentPen.setWidthF(state->getLineWidth());
334
  m_painter.top()->setPen(m_currentPen);
335 336 337 338 339
  // 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);
340 341 342 343 344 345 346
}

void ArthurOutputDev::updateFillColor(GfxState *state)
{
  GfxRGB rgb;
  QColor brushColour = m_currentBrush.color();
  state->getFillRGB(&rgb);
347
  brushColour.setRgbF(colToDbl(rgb.r), colToDbl(rgb.g), colToDbl(rgb.b), brushColour.alphaF());
348 349 350 351 352 353 354 355
  m_currentBrush.setColor(brushColour);
}

void ArthurOutputDev::updateStrokeColor(GfxState *state)
{
  GfxRGB rgb;
  QColor penColour = m_currentPen.color();
  state->getStrokeRGB(&rgb);
356
  penColour.setRgbF(colToDbl(rgb.r), colToDbl(rgb.g), colToDbl(rgb.b), penColour.alphaF());
357
  m_currentPen.setColor(penColour);
358
  m_painter.top()->setPen(m_currentPen);
359 360
}

361 362 363 364 365 366 367 368 369 370 371 372
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:
373
    m_painter.top()->setCompositionMode(QPainter::CompositionMode_Multiply);
374 375
    break;
  case gfxBlendScreen:
376
    m_painter.top()->setCompositionMode(QPainter::CompositionMode_Screen);
377 378
    break;
  case gfxBlendDarken:
379
    m_painter.top()->setCompositionMode(QPainter::CompositionMode_Darken);
380 381
    break;
  case gfxBlendLighten:
382
    m_painter.top()->setCompositionMode(QPainter::CompositionMode_Lighten);
383 384
    break;
  case gfxBlendColorDodge:
385
    m_painter.top()->setCompositionMode(QPainter::CompositionMode_ColorDodge);
386 387
    break;
  case gfxBlendColorBurn:
388
    m_painter.top()->setCompositionMode(QPainter::CompositionMode_ColorBurn);
389 390
    break;
  case gfxBlendHardLight:
391
    m_painter.top()->setCompositionMode(QPainter::CompositionMode_HardLight);
392 393
    break;
  case gfxBlendSoftLight:
394
    m_painter.top()->setCompositionMode(QPainter::CompositionMode_SoftLight);
395 396
    break;
  case gfxBlendDifference:
397
    m_painter.top()->setCompositionMode(QPainter::CompositionMode_Difference);
398 399
    break;
  case gfxBlendExclusion:
400
    m_painter.top()->setCompositionMode(QPainter::CompositionMode_Exclusion);
401 402
    break;
  case gfxBlendColor:
403
    m_painter.top()->setCompositionMode(QPainter::CompositionMode_Plus);
404 405 406 407
    break;
  default:
    qDebug() << "Unsupported blend mode, falling back to CompositionMode_SourceOver";
  case gfxBlendNormal:
408
    m_painter.top()->setCompositionMode(QPainter::CompositionMode_SourceOver);
409 410 411 412
    break;
  }
}

413 414 415 416 417 418 419 420 421 422 423 424
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);
425
  m_painter.top()->setPen(m_currentPen);
426 427 428 429
}

void ArthurOutputDev::updateFont(GfxState *state)
{
430 431
  GfxFont *gfxFont = state->getFont();
  if (!gfxFont)
432 433 434 435
  {
    return;
  }

436
  // The key to look in the font caches
437
  ArthurFontID fontID = {*gfxFont->getID(), state->getFontSize()};
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459

  // Current font is a type3 font
  if (gfxFont->getType() == fontType3)
  {
    auto cacheEntry = m_type3FontCache.find(fontID);

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

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

    } else {

      m_currentType3Font = new ArthurType3Font(m_doc, (Gfx8BitFont*)gfxFont);
      m_type3FontCache.insert(std::make_pair(fontID,std::unique_ptr<ArthurType3Font>(m_currentType3Font)));

    }

    return;
  }

  // Non-type3: is the font in the cache?
460 461 462 463 464 465 466 467 468 469 470 471
  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();

472
    std::unique_ptr<GfxFontLoc> fontLoc(gfxFont->locateFont(xref, nullptr));
473 474 475 476 477 478

    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;
479
        const char* fontData = gfxFont->readEmbFontFile(xref, &fontDataLen);
480 481 482

        m_rawFont = new QRawFont(QByteArray(fontData, fontDataLen), fontSize);
        m_rawFontCache.insert(std::make_pair(fontID,std::unique_ptr<QRawFont>(m_rawFont)));
483 484 485

        // Free the font data, it was copied in the QByteArray constructor
        free((char*)fontData);
486 487 488
        break;
      }
      case gfxFontLocExternal:{ // font is in an external font file
489
        QString fontFile(fontLoc->path->c_str());
490 491 492 493 494
        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
495
        qDebug() << "Font Resident Encoding:" << fontLoc->encoding->c_str() << ", not implemented yet!";
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514

      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
515 516
  //  information at all.  Therefore, we need to figure it ourselves, using
  //  FoFi and FreeType.
517 518
  // *****************************************************************************

519 520
  m_needFontUpdate = false;

521
  GfxFontType fontType = gfxFont->getType();
522

523 524 525
  // Default: no codeToGID table
  m_codeToGID = nullptr;

526
  // check the font file cache
527 528 529 530 531 532 533
  Ref id = *gfxFont->getID();

  auto codeToGIDIt = m_codeToGIDCache.find(id);

  if (codeToGIDIt != m_codeToGIDCache.end()) {

    m_codeToGID = codeToGIDIt->second;
534 535 536

  } else {

537 538 539
    std::unique_ptr<char[], void(*)(char*)> tmpBuf(nullptr, [](char* b){ free(b); });
    int tmpBufLen = 0;

540 541
    std::unique_ptr<GfxFontLoc> fontLoc(gfxFont->locateFont(xref, nullptr));
    if (!fontLoc) {
542
      error(errSyntaxError, -1, "Couldn't find a font for '{0:s}'",
543
	    gfxFont->getName() ? gfxFont->getName()->c_str()
544
	                       : "(unnamed)");
545
      return;
546 547 548 549 550
    }

    // embedded font
    if (fontLoc->locType == gfxFontLocEmbedded) {
      // if there is an embedded font, read it to memory
551 552 553 554
      tmpBuf.reset(gfxFont->readEmbFontFile(xref, &tmpBufLen));
      if (! tmpBuf) {
        return;
      }
555

556 557
    // external font
    } else { // gfxFontLocExternal
558 559
      // Hmm, fontType has already been set to gfxFont->getType() above.
      // Can it really assume a different value here?
560
      fontType = fontLoc->fontType;
561 562 563 564 565
    }

    switch (fontType) {
    case fontType1:
    case fontType1C:
566
    case fontType1COT:
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
    {
      // Load the font face using FreeType
      const int faceIndex = 0;  // We always load the zero-th face from a font
      FT_Face freeTypeFace;

      if (fontLoc->locType != gfxFontLocEmbedded) {
        if (FT_New_Face(m_ftLibrary, fontLoc->path->c_str(), faceIndex, &freeTypeFace)) {
          error(errSyntaxError, -1, "Couldn't create a FreeType face for '{0:s}'",
                gfxFont->getName() ? gfxFont->getName()->c_str() : "(unnamed)");
          return;
        }
      } else {
        if (FT_New_Memory_Face(m_ftLibrary, (const FT_Byte *)tmpBuf.get(), tmpBufLen, faceIndex, &freeTypeFace)) {
          error(errSyntaxError, -1, "Couldn't create a FreeType face for '{0:s}'",
                gfxFont->getName() ? gfxFont->getName()->c_str() : "(unnamed)");
          return;
        }
584
      }
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605

      const char *name;

      int *codeToGID = (int *)gmallocn(256, sizeof(int));
      for (int i = 0; i < 256; ++i) {
        codeToGID[i] = 0;
        if ((name = ((const char **)((Gfx8BitFont *)gfxFont)->getEncoding())[i])) {
          codeToGID[i] = (int)FT_Get_Name_Index(freeTypeFace, (char *)name);
          if (codeToGID[i] == 0) {
            name = GfxFont::getAlternateName(name);
            if (name) {
              codeToGID[i] = FT_Get_Name_Index(freeTypeFace, (char *)name);
	    }
          }
        }
      }

      FT_Done_Face(freeTypeFace);

      m_codeToGIDCache[id] = codeToGID;

606
      break;
607
    }
608 609
    case fontTrueType:
    case fontTrueTypeOT:
610 611 612 613 614 615 616
    {
      auto ff = (fontLoc->locType != gfxFontLocEmbedded)
                ? std::unique_ptr<FoFiTrueType>(FoFiTrueType::load(fontLoc->path->c_str()))
                : std::unique_ptr<FoFiTrueType>(FoFiTrueType::make(tmpBuf.get(), tmpBufLen));

      m_codeToGIDCache[id] = (ff) ? ((Gfx8BitFont *)gfxFont)->getCodeToGIDMap(ff.get()) : nullptr;

617
      break;
618
    }
619 620
    case fontCIDType0:
    case fontCIDType0C:
621 622 623 624 625 626 627 628 629 630 631
    {
      int *cidToGIDMap = nullptr;
      int nCIDs = 0;

      // check for a CFF font
      if (!m_useCIDs) {
        auto ff = (fontLoc->locType != gfxFontLocEmbedded)
                  ? std::unique_ptr<FoFiType1C>(FoFiType1C::load(fontLoc->path->c_str()))
                  : std::unique_ptr<FoFiType1C>(FoFiType1C::make(tmpBuf.get(), tmpBufLen));

        cidToGIDMap = (ff) ? ff->getCIDToGIDMap(&nCIDs) : nullptr;
632
      }
633 634 635

      m_codeToGIDCache[id] = cidToGIDMap;

636
      break;
637
    }
638
    case fontCIDType0COT:
639 640 641
    {
      int* codeToGID = nullptr;

Albert Astals Cid's avatar
Albert Astals Cid committed
642
      if (((GfxCIDFont *)gfxFont)->getCIDToGID()) {
643 644 645 646
        int codeToGIDLen = ((GfxCIDFont *)gfxFont)->getCIDToGIDLen();
        codeToGID = (int *)gmallocn(codeToGIDLen, sizeof(int));
        memcpy(codeToGID, ((GfxCIDFont *)gfxFont)->getCIDToGID(),
               codeToGIDLen * sizeof(int));
647
      }
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663

      int *cidToGIDMap = nullptr;
      int nCIDs = 0;

      if (!codeToGID && !m_useCIDs) {
        auto ff = (fontLoc->locType != gfxFontLocEmbedded)
                  ? std::unique_ptr<FoFiTrueType>(FoFiTrueType::load(fontLoc->path->c_str()))
                  : std::unique_ptr<FoFiTrueType>(FoFiTrueType::make(tmpBuf.get(), tmpBufLen));

        if (ff && ff->isOpenTypeCFF()) {
          cidToGIDMap = ff->getCIDToGIDMap(&nCIDs);
        }
      }

      m_codeToGIDCache[id] = codeToGID ? codeToGID : cidToGIDMap;

664
      break;
665
    }
666
    case fontCIDType2:
667
    case fontCIDType2OT:
668 669 670
    {
      int* codeToGID = nullptr;
      int codeToGIDLen = 0;
671
      if (((GfxCIDFont *)gfxFont)->getCIDToGID()) {
672 673 674 675 676 677
        codeToGIDLen = ((GfxCIDFont *)gfxFont)->getCIDToGIDLen();
        if (codeToGIDLen) {
          codeToGID = (int *)gmallocn(codeToGIDLen, sizeof(int));
          memcpy(codeToGID, ((GfxCIDFont *)gfxFont)->getCIDToGID(),
                 codeToGIDLen * sizeof(unsigned short));
        }
678
      } else {
679 680 681 682 683 684 685
        auto ff = (fontLoc->locType != gfxFontLocEmbedded)
                  ? std::unique_ptr<FoFiTrueType>(FoFiTrueType::load(fontLoc->path->c_str()))
                  : std::unique_ptr<FoFiTrueType>(FoFiTrueType::make(tmpBuf.get(), tmpBufLen));
        if (! ff) {
          return;
        }
	codeToGID = ((GfxCIDFont *)gfxFont)->getCodeToGIDMap(ff.get(), &codeToGIDLen);
686
      }
687 688 689

      m_codeToGIDCache[id] = codeToGID;

690
      break;
691
    }
692 693
    default:
      // this shouldn't happen
694
      return;
695 696
    }

697 698
    m_codeToGID = m_codeToGIDCache[id];
  }
699 700
}

701
static QPainterPath convertPath(GfxState *state, GfxPath *path, Qt::FillRule fillRule)
702 703 704 705 706
{
  GfxSubpath *subpath;
  int i, j;

  QPainterPath qPath;
707
  qPath.setFillRule(fillRule);
708 709 710
  for (i = 0; i < path->getNumSubpaths(); ++i) {
    subpath = path->getSubpath(i);
    if (subpath->getNumPoints() > 0) {
711
      qPath.moveTo(subpath->getX(0), subpath->getY(0));
712 713 714
      j = 1;
      while (j < subpath->getNumPoints()) {
	if (subpath->getCurve(j)) {
715 716 717
          qPath.cubicTo( subpath->getX(j),   subpath->getY(j),
                         subpath->getX(j+1), subpath->getY(j+1),
                         subpath->getX(j+2), subpath->getY(j+2));
718 719
	  j += 3;
	} else {
720
	  qPath.lineTo(subpath->getX(j), subpath->getY(j));
721 722 723 724 725 726 727 728 729 730 731 732 733
	  ++j;
	}
      }
      if (subpath->isClosed()) {
	qPath.closeSubpath();
      }
    }
  }
  return qPath;
}

void ArthurOutputDev::stroke(GfxState *state)
{
734
  m_painter.top()->strokePath( convertPath( state, state->getPath(), Qt::OddEvenFill ), m_currentPen );
735 736 737 738
}

void ArthurOutputDev::fill(GfxState *state)
{
739
  m_painter.top()->fillPath( convertPath( state, state->getPath(), Qt::WindingFill ), m_currentBrush );
740 741 742 743
}

void ArthurOutputDev::eoFill(GfxState *state)
{
744
  m_painter.top()->fillPath( convertPath( state, state->getPath(), Qt::OddEvenFill ), m_currentBrush );
745 746
}

747
bool ArthurOutputDev::axialShadedFill(GfxState *state, GfxAxialShading *shading, double tMin, double tMax)
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 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 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 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
{
  double x0, y0, x1, y1;
  shading->getCoords(&x0, &y0, &x1, &y1);

  // get the clip region bbox
  double xMin, yMin, xMax, yMax;
  state->getUserClipBBox(&xMin, &yMin, &xMax, &yMax);

  // get the function domain
  double t0 = shading->getDomain0();
  double t1 = shading->getDomain1();

  // Max number of splits along the t axis
  constexpr int maxSplits = 256;

  // Max delta allowed in any color component
  const double colorDelta = (dblToCol(1 / 256.0));

  // Number of color space components
  auto nComps = shading->getColorSpace()->getNComps();

  // Helper function to test two color objects for 'almost-equality'
  auto isSameGfxColor = [&nComps,&colorDelta](const GfxColor &colorA, const GfxColor &colorB)
                        {
                          for (int k = 0; k < nComps; ++k) {
                            if (abs(colorA.c[k] - colorB.c[k]) > colorDelta) {
                              return false;
                            }
                          }
                          return true;
                        };

  // Helper function: project a number into an interval
  // With C++17 this is part of the standard library
  auto clamp = [](double v, double lo, double hi)
                  { return std::min(std::max(v,lo), hi); };

  // ta stores all parameter values where we evaluate the input shading function.
  // In between, QLinearGradient will interpolate linearly.
  // We set up the array with three values.
  std::array<double, maxSplits+1> ta;
  ta[0] = tMin;
  std::array<int, maxSplits+1> next;
  next[0] = maxSplits / 2;
  ta[maxSplits / 2] = 0.5 * (tMin + tMax);
  next[maxSplits / 2] = maxSplits;
  ta[maxSplits] = tMax;

  // compute the color at t = tMin
  double tt = clamp(t0 + (t1 - t0) * tMin, t0, t1);

  GfxColor color0, color1;
  shading->getColor(tt, &color0);

  // Construct a gradient object and set its color at one parameter end
  QLinearGradient gradient(QPointF(x0 + tMin * (x1 - x0), y0 + tMin * (y1 - y0)),
                           QPointF(x0 + tMax * (x1 - x0), y0 + tMax * (y1 - y0)));

  GfxRGB rgb;
  shading->getColorSpace()->getRGB(&color0, &rgb);
  QColor qColor(colToByte(rgb.r), colToByte(rgb.g), colToByte(rgb.b));
  gradient.setColorAt(0,qColor);

  // Look for more relevant parameter values by bisection
  int i = 0;
  while (i < maxSplits) {

    int j = next[i];
    while (j > i + 1) {

      // Next parameter value to try
      tt = clamp(t0 + (t1 - t0) * ta[j], t0, t1);
      shading->getColor(tt, &color1);

      // j is a good next color stop if the input shading can be approximated well
      // on the interval (ta[i], ta[j]) by a linear interpolation.
      // We test this by comparing the real color in the middle between ta[i] and ta[j]
      // with the linear interpolant there.
      auto midPoint = 0.5 * (ta[i] + ta[j]);
      GfxColor colorAtMidPoint;
      shading->getColor(midPoint, &colorAtMidPoint);

      GfxColor linearlyInterpolatedColor;
      for (int ii=0; ii<nComps; ii++)
        linearlyInterpolatedColor.c[ii] = 0.5 * (color0.c[ii] + color1.c[ii]);

      // If the two colors are equal, ta[j] is a good place for the next color stop; take it!
      if (isSameGfxColor(colorAtMidPoint, linearlyInterpolatedColor))
        break;

      // Otherwise: bisect further
      int k = (i + j) / 2;
      ta[k] = midPoint;
      next[i] = k;
      next[k] = j;
      j = k;
    }

    // set the color
    GfxRGB rgb;
    shading->getColorSpace()->getRGB(&color1, &rgb);
    qColor.setRgb(colToByte(rgb.r), colToByte(rgb.g), colToByte(rgb.b));
    gradient.setColorAt((ta[j] - tMin)/(tMax - tMin), qColor);

    // Move to the next parameter region
    color0 = color1;
    i = next[i];
  }

  state->moveTo(xMin, yMin);
  state->lineTo(xMin, yMax);
  state->lineTo(xMax, yMax);
  state->lineTo(xMax, yMin);
  state->closePath();

  // Actually paint the shaded region
  QBrush newBrush(gradient);
  m_painter.top()->fillPath( convertPath( state, state->getPath(), Qt::WindingFill ), newBrush );

  state->clearPath();

  // True means: The shaded region has been painted
870
  return true;
871 872
}

873 874
void ArthurOutputDev::clip(GfxState *state)
{
875
  m_painter.top()->setClipPath(convertPath( state, state->getPath(), Qt::WindingFill ), Qt::IntersectClip );
876 877 878 879
}

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

883 884 885
void ArthurOutputDev::drawChar(GfxState *state, double x, double y,
			       double dx, double dy,
			       double originX, double originY,
886
			       CharCode code, int nBytes, Unicode *u, int uLen) {
887

888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933
  // First handle type3 fonts
  GfxFont *gfxFont = state->getFont();

  GfxFontType fontType = gfxFont->getType();
  if (fontType == fontType3) {

    /////////////////////////////////////////////////////////////////////
    //  Draw the QPicture that contains the glyph onto the page
    /////////////////////////////////////////////////////////////////////

    // Store the QPainter state; we need to modify it temporarily
    m_painter.top()->save();

    // Make the glyph position the coordinate origin -- that's our center of scaling
    m_painter.top()->translate(QPointF(x-originX, y-originY));

    const double* mat = gfxFont->getFontMatrix();
    QTransform fontMatrix(mat[0], mat[1], mat[2], mat[3], mat[4], mat[5]);

    // Scale with the font size
    fontMatrix.scale(state->getFontSize(), state->getFontSize());
    m_painter.top()->setTransform(fontMatrix,true);

    // Apply the text matrix on top
    const double *textMat = state->getTextMat();

    QTransform textTransform(textMat[0] * state->getHorizScaling(),
                             textMat[1] * state->getHorizScaling(),
                             textMat[2],
                             textMat[3],
                             0,
                             0);

    m_painter.top()->setTransform(textTransform,true);

    // Actually draw the glyph
    int gid = m_currentType3Font->codeToGID[code];
    m_painter.top()->drawPicture(QPointF(0,0), m_currentType3Font->getGlyph(gid));

    // Restore transformation
    m_painter.top()->restore();

    return;
  }


934
  // check for invisible text -- this is used by Acrobat Capture
935 936 937
  int render = state->getRender();
  if (render == 3 || !m_rawFont) {
    qDebug() << "Invisible text found!";
938 939 940
    return;
  }

941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
  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
957
    m_painter.top()->save();
958 959 960 961 962 963 964 965 966 967

    // 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();

968
    m_painter.top()->translate(QPointF(glyphPosition.x(),glyphPosition.y()));
969 970 971 972 973 974 975 976

    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);

977
    m_painter.top()->setTransform(textTransform,true);
978 979 980 981 982 983 984 985 986 987 988 989

    // 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());
990
    m_painter.top()->setPen(fontColor);
991 992

    // Actually draw the glyph
993
    m_painter.top()->drawGlyphRun(QPointF(-glyphPosition.x(),-glyphPosition.y()), glyphRun);
994 995

    // Restore transformation and pen color
996
    m_painter.top()->restore();
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
  }
}

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,
1015 1016
				    int width, int height, bool invert,
				    bool interpolate, bool inlineImg)
1017
{
1018 1019 1020 1021 1022
  auto imgStr = std::make_unique<ImageStream>(
	str, width,
	1,  // numPixelComps
	1  // getBits
  );
1023 1024
  imgStr->reset();

1025 1026 1027 1028
  // TODO: Would using QImage::Format_Mono be more efficient here?
  QImage image(width, height, QImage::Format_ARGB32);
  unsigned int *data = (unsigned int *)image.bits();
  int stride = image.bytesPerLine()/4;
1029

1030 1031 1032 1033
  QRgb fillColor = m_currentBrush.color().rgb();

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

1034
    unsigned char *pix = imgStr->getLine();
1035 1036 1037 1038 1039 1040 1041 1042 1043

    // 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* dest = data + (height-1-y) * stride;

    for (int x = 0; x < width; x++) {

      bool opaque = ((bool)pix[x]) == invert;
      dest[x] = (opaque) ? fillColor : 0;
1044 1045 1046 1047

    }
  }

1048 1049 1050
  // At this point, the QPainter coordinate transformation (CTM) is such
  // that QRect(0,0,1,1) is exactly the area of the image.
  m_painter.top()->drawImage( QRect(0,0,1,1), image );
1051
  imgStr->close ();
1052 1053 1054 1055 1056 1057
}

//TODO: lots more work here.
void ArthurOutputDev::drawImage(GfxState *state, Object *ref, Stream *str,
				int width, int height,
				GfxImageColorMap *colorMap,
1058
				bool interpolate, int *maskColors, bool inlineImg)
1059
{
1060 1061
  unsigned int *data;
  unsigned int *line;
1062
  int x, y;
1063
  unsigned char *pix;
Krzysztof Kowalczyk's avatar
Krzysztof Kowalczyk committed
1064
  int i;
1065 1066
  QImage image;
  int stride;
1067 1068
  
  /* TODO: Do we want to cache these? */
1069 1070 1071 1072 1073
  auto imgStr = std::make_unique<ImageStream>(
	str, width,
	colorMap->getNumPixelComps(),
	colorMap->getBits()
  );
1074 1075
  imgStr->reset();
  
1076 1077 1078 1079 1080
  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();
1081 1082 1083
    // 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;
1084
    colorMap->getRGBLine(pix, line, width);
1085

1086
    if (maskColors) {
1087
      for (x = 0; x < width; x++) {
1088 1089 1090 1091 1092 1093 1094 1095 1096
        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++;
1097
      }
1098 1099
    } else {
      for (x = 0; x < width; x++) { *line = *line | 0xff000000; line++; }
1100 1101 1102
    }
  }

1103 1104
  // At this point, the QPainter coordinate transformation (CTM) is such
  // that QRect(0,0,1,1) is exactly the area of the image.
1105
  m_painter.top()->drawImage( QRect(0,0,1,1), image );
1106 1107

}
1108 1109 1110 1111

void ArthurOutputDev::drawSoftMaskedImage(GfxState *state, Object *ref, Stream *str,
                                          int width, int height,
                                          GfxImageColorMap *colorMap,
1112
                                          bool interpolate,
1113 1114 1115
                                          Stream *maskStr,
                                          int maskWidth, int maskHeight,
                                          GfxImageColorMap *maskColorMap,
1116
                                          bool maskInterpolate)