Debian Codegraph @

qt6/src/QPainterOutputDev.cc

raw
1 //========================================================================
2 //
3 // QPainterOutputDev.cc
4 //
5 // Copyright 2003 Glyph & Cog, LLC
6 //
7 //========================================================================
8
9 //========================================================================
10 //
11 // Modified under the Poppler project - http://poppler.freedesktop.org
12 //
13 // All changes made under the Poppler project to this file are licensed
14 // under GPL version 2 or later
15 //
16 // Copyright (C) 2005 Brad Hards <[email protected]>
17 // // Copyright (C) 2005-2009, 2011, 2012, 2014, 2015, 2018, 2019, 2021, 2022, 2024, 2025 Albert Astals Cid <[email protected]>
18 // Copyright (C) 2008, 2010 Pino Toscano <[email protected]>
19 // Copyright (C) 2009, 2011 Carlos Garcia Campos <[email protected]>
20 // Copyright (C) 2009 Petr Gajdos <[email protected]>
21 // Copyright (C) 2010 Matthias Fauconneau <[email protected]>
22 // Copyright (C) 2011 Andreas Hartmetz <[email protected]>
23 // Copyright (C) 2013 Thomas Freitag <[email protected]>
24 // Copyright (C) 2013 Dominik Haumann <[email protected]>
25 // Copyright (C) 2013 Mihai Niculescu <[email protected]>
26 // Copyright (C) 2017, 2018, 2020-2022 Oliver Sander <[email protected]>
27 // Copyright (C) 2017, 2022 Adrian Johnson <[email protected]>
28 // Copyright (C) 2018 Klarälvdalens Datakonsult AB, a KDAB Group company, <[email protected]>. Work sponsored by the LiMux project of the city of Munich
29 // Copyright (C) 2018 Adam Reichold <[email protected]>
30 // Copyright (C) 2025 g10 Code GmbH, Author: Sune Stolborg Vuorela <[email protected]>
31 // Copyright (C) 2025 Arnav V <[email protected]>
32 //
33 // To see a description of the changes please see the Changelog file that
34 // came with your tarball or type make ChangeLog if you are building from git
35 //
36 //========================================================================
37
38 #include <config.h>
39
40 #include <cstring>
41 #include <cmath>
42
43 #include <array>
44
45 #include "goo/ft_utils.h"
46 #include "GlobalParams.h"
47 #include "Error.h"
48 #include "Object.h"
49 #include "GfxState.h"
50 #include "GfxFont.h"
51 #include "Link.h"
52 #include <fofi/FoFiTrueType.h>
53 #include <fofi/FoFiType1C.h>
54 #include "QPainterOutputDev.h"
55 #include "Page.h"
56 #include "Gfx.h"
57 #include "PDFDoc.h"
58
59 #include <QtCore/QtDebug>
60 #include <QRawFont>
61 #include <QGlyphRun>
62 #include <QtGui/QPainterPath>
63 #include <QPicture>
64
65 class QPainterOutputDevType3Font
66 {
67 public:
68 QPainterOutputDevType3Font(PDFDoc *doc, const std::shared_ptr<Gfx8BitFont> &font);
69
70 const QPicture &getGlyph(int gid) const;
71
72 private:
73 PDFDoc *m_doc;
74 std::shared_ptr<Gfx8BitFont> m_font;
75
76 mutable std::vector<std::unique_ptr<QPicture>> glyphs;
77
78 public:
79 std::vector<int> codeToGID;
80 };
81
82 QPainterOutputDevType3Font::QPainterOutputDevType3Font(PDFDoc *doc, const std::shared_ptr<Gfx8BitFont> &font) : m_doc(doc), m_font(font)
83 {
84 char *name;
85 const Dict *charProcs = font->getCharProcs();
86
87 // Storage for the rendered glyphs
88 glyphs.resize(charProcs->getLength());
89
90 // Compute the code-to-GID map
91 char **enc = font->getEncoding();
92
93 codeToGID.resize(256);
94
95 for (int i = 0; i < 256; ++i) {
96 codeToGID[i] = 0;
97 if (charProcs && (name = enc[i])) {
98 for (int j = 0; j < charProcs->getLength(); j++) {
99 if (strcmp(name, charProcs->getKey(j)) == 0) {
100 codeToGID[i] = j;
101 }
102 }
103 }
104 }
105 }
106
107 const QPicture &QPainterOutputDevType3Font::getGlyph(int gid) const
108 {
109 if (!glyphs[gid]) {
110
111 // Glyph has not been rendered before: render it now
112
113 // Smallest box that contains all the glyphs from this font
114 const std::array<double, 4> &fontBBox = m_font->getFontBBox();
115 PDFRectangle box(fontBBox[0], fontBBox[1], fontBBox[2], fontBBox[3]);
116
117 Dict *resDict = m_font->getResources();
118
119 QPainter glyphPainter;
120 glyphs[gid] = std::make_unique<QPicture>();
121 glyphPainter.begin(glyphs[gid].get());
122 auto output_dev = std::make_unique<QPainterOutputDev>(&glyphPainter);
123
124 auto gfx = std::make_unique<Gfx>(m_doc, output_dev.get(), resDict,
125 &box, // pagebox
126 nullptr // cropBox
127 );
128
129 output_dev->startDoc(m_doc);
130
131 output_dev->startPage(1, gfx->getState(), gfx->getXRef());
132
133 const Dict *charProcs = m_font->getCharProcs();
134 Object charProc = charProcs->getVal(gid);
135 gfx->display(&charProc);
136
137 glyphPainter.end();
138 }
139
140 return *glyphs[gid];
141 }
142
143 //------------------------------------------------------------------------
144 // QPainterOutputDev
145 //------------------------------------------------------------------------
146
147 QPainterOutputDev::QPainterOutputDev(QPainter *painter) : m_lastTransparencyGroupPicture(nullptr), m_hintingPreference(QFont::PreferDefaultHinting)
148 {
149 m_painter.push(painter);
150 m_currentBrush = QBrush(Qt::SolidPattern);
151
152 auto error = FT_Init_FreeType(&m_ftLibrary);
153 if (error) {
154 qCritical() << "An error occurred will initializing the FreeType library";
155 }
156
157 // as of FT 2.1.8, CID fonts are indexed by CID instead of GID
158 FT_Int major, minor, patch;
159 FT_Library_Version(m_ftLibrary, &major, &minor, &patch);
160 m_useCIDs = major > 2 || (major == 2 && (minor > 1 || (minor == 1 && patch > 7)));
161 }
162
163 QPainterOutputDev::~QPainterOutputDev()
164 {
165 FT_Done_FreeType(m_ftLibrary);
166 }
167
168 void QPainterOutputDev::startDoc(PDFDoc *doc)
169 {
170 xref = doc->getXRef();
171 m_doc = doc;
172
173 m_codeToGIDCache.clear();
174 m_codeToGIDStack = {};
175 m_codeToGID = nullptr;
176 }
177
178 void QPainterOutputDev::startPage(int /*pageNum*/, GfxState * /*state*/, XRef *) { }
179
180 void QPainterOutputDev::endPage() { }
181
182 void QPainterOutputDev::saveState(GfxState * /*state*/)
183 {
184 m_currentPenStack.push(m_currentPen);
185 m_currentBrushStack.push(m_currentBrush);
186 m_rawFontStack.push(m_rawFont);
187 m_type3FontStack.push(m_currentType3Font);
188 m_codeToGIDStack.push(m_codeToGID);
189
190 m_painter.top()->save();
191 }
192
193 void QPainterOutputDev::restoreState(GfxState * /*state*/)
194 {
195 m_painter.top()->restore();
196
197 m_codeToGID = m_codeToGIDStack.top();
198 m_codeToGIDStack.pop();
199 m_rawFont = m_rawFontStack.top();
200 m_rawFontStack.pop();
201 m_currentType3Font = m_type3FontStack.top();
202 m_type3FontStack.pop();
203 m_currentBrush = m_currentBrushStack.top();
204 m_currentBrushStack.pop();
205 m_currentPen = m_currentPenStack.top();
206 m_currentPenStack.pop();
207 }
208
209 void QPainterOutputDev::updateAll(GfxState *state)
210 {
211 OutputDev::updateAll(state);
212 m_needFontUpdate = true;
213 }
214
215 // Set CTM (Current Transformation Matrix) to a fixed matrix
216 void QPainterOutputDev::setDefaultCTM(const double *ctm)
217 {
218 m_painter.top()->setTransform(QTransform(ctm[0], ctm[1], ctm[2], ctm[3], ctm[4], ctm[5]));
219 }
220
221 // Update the CTM (Current Transformation Matrix), i.e., compose the old
222 // CTM with a new matrix.
223 void QPainterOutputDev::updateCTM(GfxState *state, double m11, double m12, double m21, double m22, double m31, double m32)
224 {
225 updateLineDash(state);
226 updateLineJoin(state);
227 updateLineCap(state);
228 updateLineWidth(state);
229
230 QTransform update(m11, m12, m21, m22, m31, m32);
231
232 // We could also set (rather than update) the painter transformation to state->getCMT();
233 m_painter.top()->setTransform(update, true);
234 }
235
236 void QPainterOutputDev::updateLineDash(GfxState *state)
237 {
238 double dashStart;
239 const std::vector<double> &dashPattern = state->getLineDash(&dashStart);
240
241 // Special handling for zero-length patterns, i.e., solid lines.
242 // Simply calling QPen::setDashPattern with an empty pattern does *not*
243 // result in a solid line. Rather, the current pattern is unchanged.
244 // See the implementation of the setDashPattern method in the file qpen.cpp.
245 if (dashPattern.empty()) {
246 m_currentPen.setStyle(Qt::SolidLine);
247 m_painter.top()->setPen(m_currentPen);
248 return;
249 }
250
251 QVector<qreal> pattern(dashPattern.size());
252 double scaling = state->getLineWidth();
253
254 // Negative line widths are not allowed, width 0 counts as 'one pixel width'.
255 if (scaling <= 0) {
256 scaling = 1.0;
257 }
258
259 for (std::vector<double>::size_type i = 0; i < dashPattern.size(); ++i) {
260 // pdf measures the dash pattern in dots, but Qt uses the
261 // line width as the unit.
262 pattern[i] = dashPattern[i] / scaling;
263 }
264 m_currentPen.setDashPattern(pattern);
265 m_currentPen.setDashOffset(dashStart);
266 m_painter.top()->setPen(m_currentPen);
267 }
268
269 void QPainterOutputDev::updateFlatness(GfxState * /*state*/)
270 {
271 // qDebug() << "updateFlatness";
272 }
273
274 void QPainterOutputDev::updateLineJoin(GfxState *state)
275 {
276 switch (state->getLineJoin()) {
277 case 0:
278 // The correct style here is Qt::SvgMiterJoin, *not* Qt::MiterJoin.
279 // The two differ in what to do if the miter limit is exceeded.
280 // See https://bugs.freedesktop.org/show_bug.cgi?id=102356
281 m_currentPen.setJoinStyle(Qt::SvgMiterJoin);
282 break;
283 case 1:
284 m_currentPen.setJoinStyle(Qt::RoundJoin);
285 break;
286 case 2:
287 m_currentPen.setJoinStyle(Qt::BevelJoin);
288 break;
289 }
290 m_painter.top()->setPen(m_currentPen);
291 }
292
293 void QPainterOutputDev::updateLineCap(GfxState *state)
294 {
295 switch (state->getLineCap()) {
296 case 0:
297 m_currentPen.setCapStyle(Qt::FlatCap);
298 break;
299 case 1:
300 m_currentPen.setCapStyle(Qt::RoundCap);
301 break;
302 case 2:
303 m_currentPen.setCapStyle(Qt::SquareCap);
304 break;
305 }
306 m_painter.top()->setPen(m_currentPen);
307 }
308
309 void QPainterOutputDev::updateMiterLimit(GfxState *state)
310 {
311 m_currentPen.setMiterLimit(state->getMiterLimit());
312 m_painter.top()->setPen(m_currentPen);
313 }
314
315 void QPainterOutputDev::updateLineWidth(GfxState *state)
316 {
317 m_currentPen.setWidthF(state->getLineWidth());
318 m_painter.top()->setPen(m_currentPen);
319 // The updateLineDash method needs to know the line width, but it is sometimes
320 // called before the updateLineWidth method. To make sure that the last call
321 // to updateLineDash before a drawing operation is always with the correct line
322 // width, we call it here, right after a change to the line width.
323 updateLineDash(state);
324 }
325
326 void QPainterOutputDev::updateFillColor(GfxState *state)
327 {
328 GfxRGB rgb;
329 QColor brushColour = m_currentBrush.color();
330 state->getFillRGB(&rgb);
331 brushColour.setRgbF(colToDbl(rgb.r), colToDbl(rgb.g), colToDbl(rgb.b), brushColour.alphaF());
332 m_currentBrush.setColor(brushColour);
333 }
334
335 void QPainterOutputDev::updateStrokeColor(GfxState *state)
336 {
337 GfxRGB rgb;
338 QColor penColour = m_currentPen.color();
339 state->getStrokeRGB(&rgb);
340 penColour.setRgbF(colToDbl(rgb.r), colToDbl(rgb.g), colToDbl(rgb.b), penColour.alphaF());
341 m_currentPen.setColor(penColour);
342 m_painter.top()->setPen(m_currentPen);
343 }
344
345 void QPainterOutputDev::updateBlendMode(GfxState *state)
346 {
347 GfxBlendMode blendMode = state->getBlendMode();
348
349 // missing composition modes in QPainter:
350 // - CompositionMode_Hue
351 // - CompositionMode_Color
352 // - CompositionMode_Luminosity
353 // - CompositionMode_Saturation
354
355 switch (blendMode) {
356 case gfxBlendMultiply:
357 m_painter.top()->setCompositionMode(QPainter::CompositionMode_Multiply);
358 break;
359 case gfxBlendScreen:
360 m_painter.top()->setCompositionMode(QPainter::CompositionMode_Screen);
361 break;
362 case gfxBlendDarken:
363 m_painter.top()->setCompositionMode(QPainter::CompositionMode_Darken);
364 break;
365 case gfxBlendLighten:
366 m_painter.top()->setCompositionMode(QPainter::CompositionMode_Lighten);
367 break;
368 case gfxBlendColorDodge:
369 m_painter.top()->setCompositionMode(QPainter::CompositionMode_ColorDodge);
370 break;
371 case gfxBlendColorBurn:
372 m_painter.top()->setCompositionMode(QPainter::CompositionMode_ColorBurn);
373 break;
374 case gfxBlendHardLight:
375 m_painter.top()->setCompositionMode(QPainter::CompositionMode_HardLight);
376 break;
377 case gfxBlendSoftLight:
378 m_painter.top()->setCompositionMode(QPainter::CompositionMode_SoftLight);
379 break;
380 case gfxBlendDifference:
381 m_painter.top()->setCompositionMode(QPainter::CompositionMode_Difference);
382 break;
383 case gfxBlendExclusion:
384 m_painter.top()->setCompositionMode(QPainter::CompositionMode_Exclusion);
385 break;
386 case gfxBlendColor:
387 m_painter.top()->setCompositionMode(QPainter::CompositionMode_Plus);
388 break;
389 default:
390 qDebug() << "Unsupported blend mode, falling back to CompositionMode_SourceOver";
391 [[fallthrough]];
392 case gfxBlendNormal:
393 m_painter.top()->setCompositionMode(QPainter::CompositionMode_SourceOver);
394 break;
395 }
396 }
397
398 void QPainterOutputDev::updateFillOpacity(GfxState *state)
399 {
400 QColor brushColour = m_currentBrush.color();
401 brushColour.setAlphaF(state->getFillOpacity());
402 m_currentBrush.setColor(brushColour);
403 }
404
405 void QPainterOutputDev::updateStrokeOpacity(GfxState *state)
406 {
407 QColor penColour = m_currentPen.color();
408 penColour.setAlphaF(state->getStrokeOpacity());
409 m_currentPen.setColor(penColour);
410 m_painter.top()->setPen(m_currentPen);
411 }
412
413 void QPainterOutputDev::updateFont(GfxState *state)
414 {
415 const std::shared_ptr<GfxFont> &gfxFont = state->getFont();
416 if (!gfxFont) {
417 return;
418 }
419
420 // The key to look in the font caches
421 QPainterFontID fontID = { *gfxFont->getID(), state->getFontSize() };
422
423 // Current font is a type3 font
424 if (gfxFont->getType() == fontType3) {
425 auto cacheEntry = m_type3FontCache.find(fontID);
426
427 if (cacheEntry != m_type3FontCache.end()) {
428
429 // Take the font from the cache
430 m_currentType3Font = cacheEntry->second.get();
431
432 } else {
433
434 m_currentType3Font = new QPainterOutputDevType3Font(m_doc, std::static_pointer_cast<Gfx8BitFont>(gfxFont));
435 m_type3FontCache.insert(std::make_pair(fontID, std::unique_ptr<QPainterOutputDevType3Font>(m_currentType3Font)));
436 }
437
438 return;
439 }
440
441 // Non-type3: is the font in the cache?
442 auto cacheEntry = m_rawFontCache.find(fontID);
443
444 if (cacheEntry != m_rawFontCache.end()) {
445
446 // Take the font from the cache
447 m_rawFont = cacheEntry->second.get();
448
449 } else {
450
451 // New font: load it into the cache
452 float fontSize = state->getFontSize();
453
454 std::optional<GfxFontLoc> fontLoc = gfxFont->locateFont(xref, nullptr);
455
456 if (fontLoc) {
457 // load the font from respective location
458 switch (fontLoc->locType) {
459 case gfxFontLocEmbedded: { // if there is an embedded font, read it to memory
460 const std::optional<std::vector<unsigned char>> fontData = gfxFont->readEmbFontFile(xref);
461
462 // fontData gets copied in the QByteArray constructor
463 m_rawFont = new QRawFont(QByteArray(fontData ? (const char *)fontData->data() : nullptr, fontData ? fontData->size() : 0), fontSize, m_hintingPreference);
464 m_rawFontCache.insert(std::make_pair(fontID, std::unique_ptr<QRawFont>(m_rawFont)));
465
466 break;
467 }
468 case gfxFontLocExternal: { // font is in an external font file
469 QString fontFile = QString::fromStdString(fontLoc->path);
470 m_rawFont = new QRawFont(fontFile, fontSize, m_hintingPreference);
471 m_rawFontCache.insert(std::make_pair(fontID, std::unique_ptr<QRawFont>(m_rawFont)));
472 break;
473 }
474 case gfxFontLocResident: { // font resides in a PS printer
475 qDebug() << "Resident Font Resident not implemented yet!";
476
477 break;
478 }
479 } // end switch
480
481 } else {
482 qDebug() << "Font location not found!";
483 return;
484 }
485 }
486
487 if (!m_rawFont->isValid()) {
488 qDebug() << "RawFont is not valid";
489 }
490
491 // *****************************************************************************
492 // We have now successfully loaded the font into a QRawFont object. This
493 // allows us to draw all the glyphs in the font. However, what is missing is
494 // the charcode-to-glyph-index mapping. Apparently, Qt does not provide this
495 // information at all. Therefore, we need to figure it ourselves, using
496 // FoFi and FreeType.
497 // *****************************************************************************
498
499 m_needFontUpdate = false;
500
501 GfxFontType fontType = gfxFont->getType();
502
503 // Default: no codeToGID table
504 m_codeToGID = nullptr;
505
506 // check the font file cache
507 Ref id = *gfxFont->getID();
508
509 auto codeToGIDIt = m_codeToGIDCache.find(id);
510
511 if (codeToGIDIt != m_codeToGIDCache.end()) {
512
513 m_codeToGID = &codeToGIDIt->second;
514
515 } else {
516
517 std::vector<unsigned char> fontBuffer;
518
519 std::optional<GfxFontLoc> fontLoc = gfxFont->locateFont(xref, nullptr);
520 if (!fontLoc) {
521 error(errSyntaxError, -1, "Couldn't find a font for '{0:s}'", gfxFont->getName() ? gfxFont->getName()->c_str() : "(unnamed)");
522 return;
523 }
524
525 // embedded font
526 if (fontLoc->locType == gfxFontLocEmbedded) {
527 // if there is an embedded font, read it to memory
528 std::optional<std::vector<unsigned char>> fontData = gfxFont->readEmbFontFile(xref);
529 if (!fontData) {
530 return;
531 }
532 fontBuffer = std::move(*fontData);
533
534 // external font
535 } else { // gfxFontLocExternal
536 // Hmm, fontType has already been set to gfxFont->getType() above.
537 // Can it really assume a different value here?
538 fontType = fontLoc->fontType;
539 }
540
541 switch (fontType) {
542 case fontType1:
543 case fontType1C:
544 case fontType1COT: {
545 // Load the font face using FreeType
546 FT_Face freeTypeFace;
547
548 if (fontLoc->locType != gfxFontLocEmbedded) {
549 if (ft_new_face_from_file(m_ftLibrary, fontLoc->path.c_str(), fontLoc->fontNum, &freeTypeFace)) {
550 error(errSyntaxError, -1, "Couldn't create a FreeType face for '{0:s}'", gfxFont->getName() ? gfxFont->getName()->c_str() : "(unnamed)");
551 return;
552 }
553 } else {
554 if (FT_New_Memory_Face(m_ftLibrary, (const FT_Byte *)fontBuffer.data(), fontBuffer.size(), fontLoc->fontNum, &freeTypeFace)) {
555 error(errSyntaxError, -1, "Couldn't create a FreeType face for '{0:s}'", gfxFont->getName() ? gfxFont->getName()->c_str() : "(unnamed)");
556 return;
557 }
558 }
559
560 const char *name;
561
562 std::vector<int> codeToGID;
563 codeToGID.resize(256, 0);
564 for (int i = 0; i < 256; ++i) {
565 if ((name = ((const char **)((Gfx8BitFont *)gfxFont.get())->getEncoding())[i])) {
566 codeToGID[i] = (int)FT_Get_Name_Index(freeTypeFace, (char *)name);
567 if (codeToGID[i] == 0) {
568 name = GfxFont::getAlternateName(name);
569 if (name) {
570 codeToGID[i] = FT_Get_Name_Index(freeTypeFace, (char *)name);
571 }
572 }
573 }
574 }
575
576 FT_Done_Face(freeTypeFace);
577
578 m_codeToGIDCache[id] = std::move(codeToGID);
579
580 break;
581 }
582 case fontTrueType:
583 case fontTrueTypeOT: {
584 auto ff = (fontLoc->locType != gfxFontLocEmbedded) ? FoFiTrueType::load(fontLoc->path.c_str(), fontLoc->fontNum) : FoFiTrueType::make(std::span(fontBuffer), fontLoc->fontNum);
585
586 m_codeToGIDCache[id] = (ff) ? ((Gfx8BitFont *)gfxFont.get())->getCodeToGIDMap(ff.get()) : std::vector<int> {};
587
588 break;
589 }
590 case fontCIDType0:
591 case fontCIDType0C: {
592 std::vector<int> cidToGIDMap;
593
594 // check for a CFF font
595 if (!m_useCIDs) {
596 auto ff = (fontLoc->locType != gfxFontLocEmbedded) ? std::unique_ptr<FoFiType1C>(FoFiType1C::load(fontLoc->path.c_str())) : std::unique_ptr<FoFiType1C>(FoFiType1C::make(std::span(fontBuffer)));
597
598 cidToGIDMap = (ff) ? ff->getCIDToGIDMap() : std::vector<int> {};
599 }
600
601 m_codeToGIDCache[id] = std::move(cidToGIDMap);
602
603 break;
604 }
605 case fontCIDType0COT: {
606 std::vector<int> codeToGID;
607 ;
608
609 if (((GfxCIDFont *)gfxFont.get())->getCIDToGIDLen() > 0) {
610 codeToGID = ((GfxCIDFont *)gfxFont.get())->getCIDToGID();
611 }
612
613 std::vector<int> cidToGIDMap;
614
615 if (codeToGID.empty() && !m_useCIDs) {
616 auto ff = (fontLoc->locType != gfxFontLocEmbedded) ? FoFiTrueType::load(fontLoc->path.c_str(), fontLoc->fontNum) : FoFiTrueType::make(std::span(fontBuffer), fontLoc->fontNum);
617
618 if (ff && ff->isOpenTypeCFF()) {
619 cidToGIDMap = ff->getCIDToGIDMap();
620 }
621 }
622
623 m_codeToGIDCache[id] = !codeToGID.empty() ? codeToGID : cidToGIDMap;
624
625 break;
626 }
627 case fontCIDType2:
628 case fontCIDType2OT: {
629 std::vector<int> codeToGID;
630 ;
631 if (((GfxCIDFont *)gfxFont.get())->getCIDToGIDLen() > 0) {
632 codeToGID = ((GfxCIDFont *)gfxFont.get())->getCIDToGID();
633 } else {
634 auto ff = (fontLoc->locType != gfxFontLocEmbedded) ? FoFiTrueType::load(fontLoc->path.c_str(), fontLoc->fontNum) : FoFiTrueType::make(std::span(fontBuffer), fontLoc->fontNum);
635 if (!ff) {
636 return;
637 }
638 codeToGID = ((GfxCIDFont *)gfxFont.get())->getCodeToGIDMap(ff.get());
639 }
640
641 m_codeToGIDCache[id] = codeToGID;
642
643 break;
644 }
645 default:
646 // this shouldn't happen
647 return;
648 }
649
650 m_codeToGID = &m_codeToGIDCache[id];
651 }
652 }
653
654 static QPainterPath convertPath(const GfxPath *path, Qt::FillRule fillRule)
655 {
656 int i, j;
657
658 QPainterPath qPath;
659 qPath.setFillRule(fillRule);
660 for (i = 0; i < path->getNumSubpaths(); ++i) {
661 const GfxSubpath *subpath = path->getSubpath(i);
662 if (subpath->getNumPoints() > 0) {
663 qPath.moveTo(subpath->getX(0), subpath->getY(0));
664 j = 1;
665 while (j < subpath->getNumPoints()) {
666 if (subpath->getCurve(j)) {
667 qPath.cubicTo(subpath->getX(j), subpath->getY(j), subpath->getX(j + 1), subpath->getY(j + 1), subpath->getX(j + 2), subpath->getY(j + 2));
668 j += 3;
669 } else {
670 qPath.lineTo(subpath->getX(j), subpath->getY(j));
671 ++j;
672 }
673 }
674 if (subpath->isClosed()) {
675 qPath.closeSubpath();
676 }
677 }
678 }
679 return qPath;
680 }
681
682 void QPainterOutputDev::stroke(GfxState *state)
683 {
684 m_painter.top()->strokePath(convertPath(state->getPath(), Qt::OddEvenFill), m_currentPen);
685 }
686
687 void QPainterOutputDev::fill(GfxState *state)
688 {
689 m_painter.top()->fillPath(convertPath(state->getPath(), Qt::WindingFill), m_currentBrush);
690 }
691
692 void QPainterOutputDev::eoFill(GfxState *state)
693 {
694 m_painter.top()->fillPath(convertPath(state->getPath(), Qt::OddEvenFill), m_currentBrush);
695 }
696
697 bool QPainterOutputDev::axialShadedFill(GfxState *state, GfxAxialShading *shading, double tMin, double tMax)
698 {
699 double x0, y0, x1, y1;
700 shading->getCoords(&x0, &y0, &x1, &y1);
701
702 // get the clip region bbox
703 double xMin, yMin, xMax, yMax;
704 state->getUserClipBBox(&xMin, &yMin, &xMax, &yMax);
705
706 // get the function domain
707 double t0 = shading->getDomain0();
708 double t1 = shading->getDomain1();
709
710 // Max number of splits along the t axis
711 constexpr int maxSplits = 256;
712
713 // Max delta allowed in any color component
714 const double colorDelta = (dblToCol(1 / 256.0));
715
716 // Number of color space components
717 auto nComps = shading->getColorSpace()->getNComps();
718 // If the clipping region is a stroke, then the current operation counts as a stroke
719 // rather than as a fill, and the opacity has to be set accordingly.
720 // See https://gitlab.freedesktop.org/poppler/poppler/-/issues/178
721 auto opacity = (state->getStrokePattern()) ? state->getStrokeOpacity() : state->getFillOpacity();
722
723 // Helper function to test two color objects for 'almost-equality'
724 auto isSameGfxColor = [&nComps, &colorDelta](const GfxColor &colorA, const GfxColor &colorB) {
725 for (int k = 0; k < nComps; ++k) {
726 if (abs(colorA.c[k] - colorB.c[k]) > colorDelta) {
727 return false;
728 }
729 }
730 return true;
731 };
732
733 // Helper function: project a number into an interval
734 // With C++17 this is part of the standard library
735 auto clamp = [](double v, double lo, double hi) { return std::min(std::max(v, lo), hi); };
736
737 // ta stores all parameter values where we evaluate the input shading function.
738 // In between, QLinearGradient will interpolate linearly.
739 // We set up the array with three values.
740 std::array<double, maxSplits + 1> ta;
741 ta[0] = tMin;
742 std::array<int, maxSplits + 1> next;
743 next[0] = maxSplits / 2;
744 ta[maxSplits / 2] = 0.5 * (tMin + tMax);
745 next[maxSplits / 2] = maxSplits;
746 ta[maxSplits] = tMax;
747
748 // compute the color at t = tMin
749 double tt = clamp(t0 + (t1 - t0) * tMin, t0, t1);
750
751 GfxColor color0, color1;
752 shading->getColor(tt, &color0);
753
754 // Construct a gradient object and set its color at one parameter end
755 QLinearGradient gradient(QPointF(x0 + tMin * (x1 - x0), y0 + tMin * (y1 - y0)), QPointF(x0 + tMax * (x1 - x0), y0 + tMax * (y1 - y0)));
756
757 GfxRGB rgb;
758 shading->getColorSpace()->getRGB(&color0, &rgb);
759 QColor qColor(colToByte(rgb.r), colToByte(rgb.g), colToByte(rgb.b), dblToByte(opacity));
760 gradient.setColorAt(0, qColor);
761
762 // Look for more relevant parameter values by bisection
763 int i = 0;
764 while (i < maxSplits) {
765
766 int j = next[i];
767 while (j > i + 1) {
768
769 // Next parameter value to try
770 tt = clamp(t0 + (t1 - t0) * ta[j], t0, t1);
771 shading->getColor(tt, &color1);
772
773 // j is a good next color stop if the input shading can be approximated well
774 // on the interval (ta[i], ta[j]) by a linear interpolation.
775 // We test this by comparing the real color in the middle between ta[i] and ta[j]
776 // with the linear interpolant there.
777 auto midPoint = 0.5 * (ta[i] + ta[j]);
778 GfxColor colorAtMidPoint;
779 shading->getColor(midPoint, &colorAtMidPoint);
780
781 GfxColor linearlyInterpolatedColor;
782 for (int ii = 0; ii < nComps; ii++) {
783 linearlyInterpolatedColor.c[ii] = 0.5 * (color0.c[ii] + color1.c[ii]);
784 }
785
786 // If the two colors are equal, ta[j] is a good place for the next color stop; take it!
787 if (isSameGfxColor(colorAtMidPoint, linearlyInterpolatedColor)) {
788 break;
789 }
790
791 // Otherwise: bisect further
792 int k = (i + j) / 2;
793 ta[k] = midPoint;
794 next[i] = k;
795 next[k] = j;
796 j = k;
797 }
798
799 // set the color
800 shading->getColorSpace()->getRGB(&color1, &rgb);
801 qColor.setRgb(colToByte(rgb.r), colToByte(rgb.g), colToByte(rgb.b), dblToByte(opacity));
802 gradient.setColorAt((ta[j] - tMin) / (tMax - tMin), qColor);
803
804 // Move to the next parameter region
805 color0 = color1;
806 i = next[i];
807 }
808
809 state->moveTo(xMin, yMin);
810 state->lineTo(xMin, yMax);
811 state->lineTo(xMax, yMax);
812 state->lineTo(xMax, yMin);
813 state->closePath();
814
815 // Actually paint the shaded region
816 QBrush newBrush(gradient);
817 m_painter.top()->fillPath(convertPath(state->getPath(), Qt::WindingFill), newBrush);
818
819 state->clearPath();
820
821 // True means: The shaded region has been painted
822 return true;
823 }
824
825 void QPainterOutputDev::clip(GfxState *state)
826 {
827 m_painter.top()->setClipPath(convertPath(state->getPath(), Qt::WindingFill), Qt::IntersectClip);
828 }
829
830 void QPainterOutputDev::eoClip(GfxState *state)
831 {
832 m_painter.top()->setClipPath(convertPath(state->getPath(), Qt::OddEvenFill), Qt::IntersectClip);
833 }
834
835 void QPainterOutputDev::clipToStrokePath(GfxState *state)
836 {
837 QPainterPath clipPath = convertPath(state->getPath(), Qt::WindingFill);
838
839 // Get the outline of 'clipPath' as a separate path
840 QPainterPathStroker stroker;
841 stroker.setWidth(state->getLineWidth());
842 stroker.setCapStyle(m_currentPen.capStyle());
843 stroker.setJoinStyle(m_currentPen.joinStyle());
844 stroker.setMiterLimit(state->getMiterLimit());
845 stroker.setDashPattern(m_currentPen.dashPattern());
846 stroker.setDashOffset(m_currentPen.dashOffset());
847 QPainterPath clipPathOutline = stroker.createStroke(clipPath);
848
849 // The interior of the outline is the desired clipping region
850 m_painter.top()->setClipPath(clipPathOutline, Qt::IntersectClip);
851 }
852
853 void QPainterOutputDev::drawChar(GfxState *state, double x, double y, double /*dx*/, double /*dy*/, double originX, double originY, CharCode code, int /*nBytes*/, const Unicode * /*u*/, int /*uLen*/)
854 {
855
856 // First handle type3 fonts
857 const std::shared_ptr<GfxFont> &gfxFont = state->getFont();
858
859 GfxFontType fontType = gfxFont->getType();
860 if (fontType == fontType3) {
861
862 /////////////////////////////////////////////////////////////////////
863 // Draw the QPicture that contains the glyph onto the page
864 /////////////////////////////////////////////////////////////////////
865
866 // Store the QPainter state; we need to modify it temporarily
867 m_painter.top()->save();
868
869 // Make the glyph position the coordinate origin -- that's our center of scaling
870 m_painter.top()->translate(QPointF(x - originX, y - originY));
871
872 const std::array<double, 6> &mat = gfxFont->getFontMatrix();
873 QTransform fontMatrix(mat[0], mat[1], mat[2], mat[3], mat[4], mat[5]);
874
875 // Scale with the font size
876 fontMatrix.scale(state->getFontSize(), state->getFontSize());
877 m_painter.top()->setTransform(fontMatrix, true);
878
879 // Apply the text matrix on top
880 const double *textMat = state->getTextMat();
881
882 QTransform textTransform(textMat[0] * state->getHorizScaling(), textMat[1] * state->getHorizScaling(), textMat[2], textMat[3], 0, 0);
883
884 m_painter.top()->setTransform(textTransform, true);
885
886 // Actually draw the glyph
887 int gid = m_currentType3Font->codeToGID[code];
888 m_painter.top()->drawPicture(QPointF(0, 0), m_currentType3Font->getGlyph(gid));
889
890 // Restore transformation
891 m_painter.top()->restore();
892
893 return;
894 }
895
896 // check for invisible text -- this is used by Acrobat Capture
897 int render = state->getRender();
898 if (render == 3 || !m_rawFont) {
899 qDebug() << "Invisible text found!";
900 return;
901 }
902
903 if (!(render & 1)) {
904 quint32 glyphIndex = (m_codeToGID && code < m_codeToGID->size()) ? m_codeToGID->at(code) : code;
905 QPointF glyphPosition = QPointF(x - originX, y - originY);
906
907 // QGlyphRun objects can hold an entire sequence of glyphs, and it would possibly
908 // be more efficient to simply note the glyph and glyph position here and then
909 // draw several glyphs at once in the endString method. What keeps us from doing
910 // that is the transformation below: each glyph needs to be drawn upside down,
911 // i.e., reflected at its own baseline. Since we have no guarantee that this
912 // baseline is the same for all glyphs in a string we have to do it one by one.
913 QGlyphRun glyphRun;
914 glyphRun.setRawData(&glyphIndex, &glyphPosition, 1);
915 glyphRun.setRawFont(*m_rawFont);
916
917 // Store the QPainter state; we need to modify it temporarily
918 m_painter.top()->save();
919
920 // Apply the text matrix to the glyph. The glyph is not scaled by the font size,
921 // because the font in m_rawFont already has the correct size.
922 // Additionally, the CTM is upside down, i.e., it contains a negative Y-scaling
923 // entry. Therefore, Qt will paint the glyphs upside down. We need to temporarily
924 // reflect the page at glyphPosition.y().
925
926 // Make the glyph position the coordinate origin -- that's our center of scaling
927 const double *textMat = state->getTextMat();
928
929 m_painter.top()->translate(QPointF(glyphPosition.x(), glyphPosition.y()));
930
931 QTransform textTransform(textMat[0] * state->getHorizScaling(), textMat[1] * state->getHorizScaling(),
932 -textMat[2], // reflect at the horizontal axis,
933 -textMat[3], // because CTM is upside-down.
934 0, 0);
935
936 m_painter.top()->setTransform(textTransform, true);
937
938 // We are painting a filled glyph here. But QPainter uses the pen to draw even filled text,
939 // not the brush. (see, e.g., http://doc.qt.io/qt-5/qpainter.html#setPen )
940 // Therefore we have to temporarily overwrite the pen color.
941
942 // Since we are drawing a filled glyph, one would really expect to have m_currentBrush
943 // have the correct color. However, somehow state->getFillRGB can change without
944 // updateFillColor getting called. Then m_currentBrush may not contain the correct color.
945 GfxRGB rgb;
946 state->getFillRGB(&rgb);
947 QColor fontColor;
948 fontColor.setRgbF(colToDbl(rgb.r), colToDbl(rgb.g), colToDbl(rgb.b), state->getFillOpacity());
949 m_painter.top()->setPen(fontColor);
950
951 // Actually draw the glyph
952 m_painter.top()->drawGlyphRun(QPointF(-glyphPosition.x(), -glyphPosition.y()), glyphRun);
953
954 // Restore transformation and pen color
955 m_painter.top()->restore();
956 }
957 }
958
959 void QPainterOutputDev::type3D0(GfxState * /*state*/, double /*wx*/, double /*wy*/) { }
960
961 void QPainterOutputDev::type3D1(GfxState * /*state*/, double /*wx*/, double /*wy*/, double /*llx*/, double /*lly*/, double /*urx*/, double /*ury*/) { }
962
963 void QPainterOutputDev::endTextObject(GfxState * /*state*/) { }
964
965 void QPainterOutputDev::drawImageMask(GfxState * /*state*/, Object * /*ref*/, Stream *str, int width, int height, bool invert, bool /*interpolate*/, bool /*inlineImg*/)
966 {
967 auto imgStr = std::make_unique<ImageStream>(str, width,
968 1, // numPixelComps
969 1 // getBits
970 );
971 if (!imgStr->rewind()) {
972 imgStr->close();
973 return;
974 }
975
976 // TODO: Would using QImage::Format_Mono be more efficient here?
977 QImage image(width, height, QImage::Format_ARGB32);
978 unsigned int *data = reinterpret_cast<unsigned int *>(image.bits());
979 int stride = image.bytesPerLine() / 4;
980
981 QRgb fillColor = m_currentBrush.color().rgb();
982
983 for (int y = 0; y < height; y++) {
984
985 unsigned char *pix = imgStr->getLine();
986
987 // Invert the vertical coordinate: y is increasing from top to bottom
988 // on the page, but y is increasing bottom to top in the picture.
989 unsigned int *dest = data + (height - 1 - y) * stride;
990
991 for (int x = 0; x < width; x++) {
992
993 bool opaque = ((bool)pix[x]) == invert;
994 dest[x] = (opaque) ? fillColor : 0;
995 }
996 }
997
998 // At this point, the QPainter coordinate transformation (CTM) is such
999 // that QRect(0,0,1,1) is exactly the area of the image.
1000 m_painter.top()->drawImage(QRect(0, 0, 1, 1), image);
1001 imgStr->close();
1002 }
1003
1004 // TODO: lots more work here.
1005 void QPainterOutputDev::drawImage(GfxState * /*state*/, Object * /*ref*/, Stream *str, int width, int height, GfxImageColorMap *colorMap, bool /*interpolate*/, const int *maskColors, bool /*inlineImg*/)
1006 {
1007 unsigned int *data;
1008 unsigned int *line;
1009 int x, y;
1010 unsigned char *pix;
1011 int i;
1012 QImage image;
1013 int stride;
1014
1015 /* TODO: Do we want to cache these? */
1016 auto imgStr = std::make_unique<ImageStream>(str, width, colorMap->getNumPixelComps(), colorMap->getBits());
1017 if (!imgStr->rewind()) {
1018 imgStr->close();
1019 return;
1020 }
1021
1022 image = QImage(width, height, QImage::Format_ARGB32);
1023 data = reinterpret_cast<unsigned int *>(image.bits());
1024 stride = image.bytesPerLine() / 4;
1025 for (y = 0; y < height; y++) {
1026 pix = imgStr->getLine();
1027 // Invert the vertical coordinate: y is increasing from top to bottom
1028 // on the page, but y is increasing bottom to top in the picture.
1029 line = data + (height - 1 - y) * stride;
1030 colorMap->getRGBLine(pix, line, width);
1031
1032 if (maskColors) {
1033 for (x = 0; x < width; x++) {
1034 for (i = 0; i < colorMap->getNumPixelComps(); ++i) {
1035 if (pix[i] < maskColors[2 * i] * 255 || pix[i] > maskColors[2 * i + 1] * 255) {
1036 *line = *line | 0xff000000;
1037 break;
1038 }
1039 }
1040 pix += colorMap->getNumPixelComps();
1041 line++;
1042 }
1043 } else {
1044 for (x = 0; x < width; x++) {
1045 *line = *line | 0xff000000;
1046 line++;
1047 }
1048 }
1049 }
1050
1051 // At this point, the QPainter coordinate transformation (CTM) is such
1052 // that QRect(0,0,1,1) is exactly the area of the image.
1053 m_painter.top()->drawImage(QRect(0, 0, 1, 1), image);
1054 }
1055
1056 void QPainterOutputDev::drawSoftMaskedImage(GfxState *state, Object *ref, Stream *str, int width, int height, GfxImageColorMap *colorMap, bool interpolate, Stream *maskStr, int maskWidth, int maskHeight, GfxImageColorMap *maskColorMap,
1057 bool /*maskInterpolate*/)
1058 {
1059 // Bail out if the image size doesn't match the mask size. I don't know
1060 // what to do in this case.
1061 if (width != maskWidth || height != maskHeight) {
1062 qDebug() << "Soft mask size does not match image size!";
1063 drawImage(state, ref, str, width, height, colorMap, interpolate, nullptr, false);
1064 return;
1065 }
1066
1067 // Bail out if the mask isn't a single channel. I don't know
1068 // what to do in this case.
1069 if (maskColorMap->getColorSpace()->getNComps() != 1) {
1070 qDebug() << "Soft mask is not a single 8-bit channel!";
1071 drawImage(state, ref, str, width, height, colorMap, interpolate, nullptr, false);
1072 return;
1073 }
1074
1075 /* TODO: Do we want to cache these? */
1076 auto imgStr = std::make_unique<ImageStream>(str, width, colorMap->getNumPixelComps(), colorMap->getBits());
1077 if (!imgStr->rewind()) {
1078 return;
1079 }
1080
1081 auto maskImageStr = std::make_unique<ImageStream>(maskStr, maskWidth, maskColorMap->getNumPixelComps(), maskColorMap->getBits());
1082 if (!maskImageStr->rewind()) {
1083 return;
1084 }
1085
1086 QImage image(width, height, QImage::Format_ARGB32);
1087 unsigned int *data = reinterpret_cast<unsigned int *>(image.bits());
1088 int stride = image.bytesPerLine() / 4;
1089
1090 std::vector<unsigned char> maskLine(maskWidth);
1091
1092 for (int y = 0; y < height; y++) {
1093
1094 unsigned char *pix = imgStr->getLine();
1095 unsigned char *maskPix = maskImageStr->getLine();
1096
1097 // Invert the vertical coordinate: y is increasing from top to bottom
1098 // on the page, but y is increasing bottom to top in the picture.
1099 unsigned int *line = data + (height - 1 - y) * stride;
1100 colorMap->getRGBLine(pix, line, width);
1101
1102 // Apply the mask values to the image alpha channel
1103 maskColorMap->getGrayLine(maskPix, maskLine.data(), width);
1104 for (int x = 0; x < width; x++) {
1105 *line = *line | (maskLine[x] << 24);
1106 line++;
1107 }
1108 }
1109
1110 // At this point, the QPainter coordinate transformation (CTM) is such
1111 // that QRect(0,0,1,1) is exactly the area of the image.
1112 m_painter.top()->drawImage(QRect(0, 0, 1, 1), image);
1113 }
1114
1115 void QPainterOutputDev::beginTransparencyGroup(GfxState * /*state*/, const std::array<double, 4> & /*bbox*/, GfxColorSpace * /*blendingColorSpace*/, bool /*isolated*/, bool /*knockout*/, bool /*forSoftMask*/)
1116 {
1117 // The entire transparency group will be painted into a
1118 // freshly created QPicture object. Since an existing painter
1119 // cannot change its paint device, we need to construct a
1120 // new QPainter object as well.
1121 m_qpictures.push(new QPicture);
1122 m_painter.push(new QPainter(m_qpictures.top()));
1123 }
1124
1125 void QPainterOutputDev::endTransparencyGroup(GfxState * /*state*/)
1126 {
1127 // Stop painting into the group
1128 m_painter.top()->end();
1129
1130 // Kill the painter that has been used for the transparency group
1131 delete (m_painter.top());
1132 m_painter.pop();
1133
1134 // Store the QPicture object that holds the result of the transparency group
1135 // painting. It will be painted and deleted in the method paintTransparencyGroup.
1136 if (m_lastTransparencyGroupPicture) {
1137 qDebug() << "Found a transparency group that has not been painted";
1138 delete (m_lastTransparencyGroupPicture);
1139 }
1140 m_lastTransparencyGroupPicture = m_qpictures.top();
1141 m_qpictures.pop();
1142 }
1143
1144 void QPainterOutputDev::paintTransparencyGroup(GfxState * /*state*/, const std::array<double, 4> & /*bbox*/)
1145 {
1146 // Actually draw the transparency group
1147 m_painter.top()->drawPicture(0, 0, *m_lastTransparencyGroupPicture);
1148
1149 // And delete it
1150 delete (m_lastTransparencyGroupPicture);
1151 m_lastTransparencyGroupPicture = nullptr;
1152 }