1 /****************************************************************************
2 **
3 ** Copyright (C) 2016 The Qt Company Ltd.
4 ** Contact: https://www.qt.io/licensing/
5 **
6 ** This file is part of the QtGui module of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and The Qt Company. For licensing terms
14 ** and conditions see https://www.qt.io/terms-conditions. For further
15 ** information use the contact form at https://www.qt.io/contact-us.
16 **
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 3 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL3 included in the
21 ** packaging of this file. Please review the following information to
22 ** ensure the GNU Lesser General Public License version 3 requirements
23 ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
24 **
25 ** GNU General Public License Usage
26 ** Alternatively, this file may be used under the terms of the GNU
27 ** General Public License version 2.0 or (at your option) the GNU General
28 ** Public license version 3 or any later version approved by the KDE Free
29 ** Qt Foundation. The licenses are as published by the Free Software
30 ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
31 ** included in the packaging of this file. Please review the following
32 ** information to ensure the GNU General Public License requirements will
33 ** be met: https://www.gnu.org/licenses/gpl-2.0.html and
34 ** https://www.gnu.org/licenses/gpl-3.0.html.
35 **
36 ** $QT_END_LICENSE$
37 **
38 ****************************************************************************/
39
40 #include <QtPrintSupport/qtprintsupportglobal.h>
41
42 #ifndef QT_NO_PRINTER
43
44 #include "qprintengine_win_p.h"
45
46 #include <limits.h>
47
48 #include <private/qprinter_p.h>
49 #include <private/qfont_p.h>
50 #include <private/qfontengine_p.h>
51 #include <private/qpainter_p.h>
52
53 #include <qpa/qplatformprintplugin.h>
54 #include <qpa/qplatformprintersupport.h>
55
56 #include <qbitmap.h>
57 #include <qdebug.h>
58 #include <qvector.h>
59 #include <qpicture.h>
60 #include <qpa/qplatformpixmap.h>
61 #include <private/qpicture_p.h>
62 #include <private/qpixmap_raster_p.h>
63 #include <QtCore/QMetaType>
64 #include <QtCore/qt_windows.h>
65 #include <QtGui/qpagelayout.h>
66
67 Q_DECLARE_METATYPE(HFONT)
68 Q_DECLARE_METATYPE(LOGFONT)
69
70 QT_BEGIN_NAMESPACE
71
72 Q_GUI_EXPORT HBITMAP qt_pixmapToWinHBITMAP(const QPixmap &p, int hbitmapFormat = 0);
73 extern QPainterPath qt_regionToPath(const QRegion ®ion);
74 extern QMarginsF qt_convertMargins(const QMarginsF &margins, QPageLayout::Unit fromUnits, QPageLayout::Unit toUnits);
75
76 // #define QT_DEBUG_DRAW
77 // #define QT_DEBUG_METRICS
78
79 static void draw_text_item_win(const QPointF &_pos, const QTextItemInt &ti, HDC hdc,
80 const QTransform &xform, const QPointF &topLeft);
81
QWin32PrintEngine(QPrinter::PrinterMode mode,const QString & deviceId)82 QWin32PrintEngine::QWin32PrintEngine(QPrinter::PrinterMode mode, const QString &deviceId)
83 : QAlphaPaintEngine(*(new QWin32PrintEnginePrivate),
84 PaintEngineFeatures(PrimitiveTransform
85 | PixmapTransform
86 | PerspectiveTransform
87 | PainterPaths
88 | Antialiasing
89 | PaintOutsidePaintEvent))
90 {
91 Q_D(QWin32PrintEngine);
92 d->mode = mode;
93 QPlatformPrinterSupport *ps = QPlatformPrinterSupportPlugin::get();
94 if (ps)
95 d->m_printDevice = ps->createPrintDevice(deviceId.isEmpty() ? ps->defaultPrintDeviceId() : deviceId);
96 d->m_pageLayout.setPageSize(d->m_printDevice.defaultPageSize());
97 d->initialize();
98 }
99
msgBeginFailed(const char * function,const DOCINFO & d)100 static QByteArray msgBeginFailed(const char *function, const DOCINFO &d)
101 {
102 QString result;
103 QTextStream str(&result);
104 str << "QWin32PrintEngine::begin: " << function << " failed";
105 if (d.lpszDocName && d.lpszDocName[0])
106 str << ", document \"" << QString::fromWCharArray(d.lpszDocName) << '"';
107 if (d.lpszOutput && d.lpszOutput[0])
108 str << ", file \"" << QString::fromWCharArray(d.lpszOutput) << '"';
109 return std::move(result).toLocal8Bit();
110 }
111
begin(QPaintDevice * pdev)112 bool QWin32PrintEngine::begin(QPaintDevice *pdev)
113 {
114 Q_D(QWin32PrintEngine);
115
116 QAlphaPaintEngine::begin(pdev);
117 if (!continueCall())
118 return true;
119
120 if (d->reinit) {
121 d->resetDC();
122 d->reinit = false;
123 }
124
125 // ### set default colors and stuff...
126
127 bool ok = d->state == QPrinter::Idle;
128
129 if (!d->hdc)
130 return false;
131
132 d->devMode->dmCopies = d->num_copies;
133
134 DOCINFO di;
135 memset(&di, 0, sizeof(DOCINFO));
136 di.cbSize = sizeof(DOCINFO);
137 if (d->docName.isEmpty())
138 di.lpszDocName = L"document1";
139 else
140 di.lpszDocName = reinterpret_cast<const wchar_t *>(d->docName.utf16());
141 if (d->printToFile && !d->fileName.isEmpty())
142 di.lpszOutput = reinterpret_cast<const wchar_t *>(d->fileName.utf16());
143 if (d->printToFile)
144 di.lpszOutput = d->fileName.isEmpty() ? L"FILE:" : reinterpret_cast<const wchar_t *>(d->fileName.utf16());
145 if (ok && StartDoc(d->hdc, &di) == SP_ERROR) {
146 qErrnoWarning(msgBeginFailed("StartDoc", di));
147 ok = false;
148 }
149
150 if (StartPage(d->hdc) <= 0) {
151 qErrnoWarning(msgBeginFailed("StartPage", di));
152 ok = false;
153 }
154
155 if (!ok) {
156 d->state = QPrinter::Idle;
157 } else {
158 d->state = QPrinter::Active;
159 }
160
161 d->matrix = QTransform();
162 d->has_pen = true;
163 d->pen = QColor(Qt::black);
164 d->has_brush = false;
165
166 d->complex_xform = false;
167
168 updateMatrix(d->matrix);
169
170 if (!ok)
171 cleanUp();
172
173 #ifdef QT_DEBUG_METRICS
174 qDebug("QWin32PrintEngine::begin()");
175 d->debugMetrics();
176 #endif // QT_DEBUG_METRICS
177
178 return ok;
179 }
180
end()181 bool QWin32PrintEngine::end()
182 {
183 Q_D(QWin32PrintEngine);
184
185 if (d->hdc) {
186 if (d->state == QPrinter::Aborted) {
187 cleanUp();
188 AbortDoc(d->hdc);
189 return true;
190 }
191 }
192
193 QAlphaPaintEngine::end();
194 if (!continueCall())
195 return true;
196
197 if (d->hdc) {
198 if (EndPage(d->hdc) <= 0) // end; printing done
199 qErrnoWarning("QWin32PrintEngine::end: EndPage failed (%p)", d->hdc);
200 if (EndDoc(d->hdc) <= 0)
201 qErrnoWarning("QWin32PrintEngine::end: EndDoc failed");
202 }
203
204 d->state = QPrinter::Idle;
205 d->reinit = true;
206 return true;
207 }
208
newPage()209 bool QWin32PrintEngine::newPage()
210 {
211 Q_D(QWin32PrintEngine);
212 Q_ASSERT(isActive());
213
214 Q_ASSERT(d->hdc);
215
216 flushAndInit();
217
218 bool transparent = GetBkMode(d->hdc) == TRANSPARENT;
219
220 if (EndPage(d->hdc) <= 0) {
221 qErrnoWarning("QWin32PrintEngine::newPage: EndPage failed");
222 return false;
223 }
224
225 if (d->reinit) {
226 if (!d->resetDC())
227 return false;
228 d->reinit = false;
229 }
230
231 if (StartPage(d->hdc) <= 0) {
232 qErrnoWarning("Win32PrintEngine::newPage: StartPage failed");
233 return false;
234 }
235
236 SetTextAlign(d->hdc, TA_BASELINE);
237 if (transparent)
238 SetBkMode(d->hdc, TRANSPARENT);
239
240 #ifdef QT_DEBUG_METRICS
241 qDebug("QWin32PrintEngine::newPage()");
242 d->debugMetrics();
243 #endif // QT_DEBUG_METRICS
244
245 // ###
246 return true;
247
248 bool success = false;
249 if (d->hdc && d->state == QPrinter::Active) {
250 if (EndPage(d->hdc) > 0) {
251 // reinitialize the DC before StartPage if needed,
252 // because resetdc is disabled between calls to the StartPage and EndPage functions
253 // (see StartPage documentation in the Platform SDK:Windows GDI)
254 // state = PST_ACTIVEDOC;
255 // reinit();
256 // state = PST_ACTIVE;
257 // start the new page now
258 if (d->reinit) {
259 if (!d->resetDC())
260 qErrnoWarning("QWin32PrintEngine::newPage(), ResetDC failed (2)");
261 d->reinit = false;
262 }
263 success = (StartPage(d->hdc) > 0);
264 if (!success)
265 qErrnoWarning("Win32PrintEngine::newPage: StartPage failed (2)");
266 }
267 if (!success) {
268 d->state = QPrinter::Aborted;
269 return false;
270 }
271 }
272 return true;
273 }
274
abort()275 bool QWin32PrintEngine::abort()
276 {
277 // do nothing loop.
278 return false;
279 }
280
drawTextItem(const QPointF & p,const QTextItem & textItem)281 void QWin32PrintEngine::drawTextItem(const QPointF &p, const QTextItem &textItem)
282 {
283 Q_D(const QWin32PrintEngine);
284
285 QAlphaPaintEngine::drawTextItem(p, textItem);
286 if (!continueCall())
287 return;
288
289 const QTextItemInt &ti = static_cast<const QTextItemInt &>(textItem);
290 QRgb brushColor = state->pen().brush().color().rgb();
291 bool fallBack = state->pen().brush().style() != Qt::SolidPattern
292 || qAlpha(brushColor) != 0xff
293 || d->txop >= QTransform::TxProject
294 || ti.fontEngine->type() != QFontEngine::Win
295 || !d->embed_fonts;
296
297 if (!fallBack) {
298 const QVariantMap userData = ti.fontEngine->userData().toMap();
299 const QVariant hFontV = userData.value(QStringLiteral("hFont"));
300 const QVariant logFontV = userData.value(QStringLiteral("logFont"));
301 if (hFontV.canConvert<HFONT>() && logFontV.canConvert<LOGFONT>()) {
302 const HFONT hfont = hFontV.value<HFONT>();
303 const LOGFONT logFont = logFontV.value<LOGFONT>();
304 // Try selecting the font to see if we get a substitution font
305 SelectObject(d->hdc, hfont);
306 if (GetDeviceCaps(d->hdc, TECHNOLOGY) != DT_CHARSTREAM) {
307 wchar_t n[64];
308 GetTextFace(d->hdc, 64, n);
309 fallBack = QString::fromWCharArray(n)
310 != QString::fromWCharArray(logFont.lfFaceName);
311 }
312 }
313 }
314
315
316 if (fallBack) {
317 QPaintEngine::drawTextItem(p, textItem);
318 return ;
319 }
320
321 COLORREF cf = RGB(qRed(brushColor), qGreen(brushColor), qBlue(brushColor));
322 SelectObject(d->hdc, CreateSolidBrush(cf));
323 SelectObject(d->hdc, CreatePen(PS_SOLID, 1, cf));
324 SetTextColor(d->hdc, cf);
325
326 draw_text_item_win(p, ti, d->hdc, d->matrix, QPointF(0.0, 0.0));
327 DeleteObject(SelectObject(d->hdc,GetStockObject(HOLLOW_BRUSH)));
328 DeleteObject(SelectObject(d->hdc,GetStockObject(BLACK_PEN)));
329 }
330
metric(QPaintDevice::PaintDeviceMetric m) const331 int QWin32PrintEngine::metric(QPaintDevice::PaintDeviceMetric m) const
332 {
333 Q_D(const QWin32PrintEngine);
334
335 if (!d->hdc)
336 return 0;
337
338 int val;
339 int res = d->resolution;
340
341 switch (m) {
342 case QPaintDevice::PdmWidth:
343 val = d->m_paintRectPixels.width();
344 #ifdef QT_DEBUG_METRICS
345 qDebug() << "QWin32PrintEngine::metric(PdmWidth) = " << val;
346 d->debugMetrics();
347 #endif // QT_DEBUG_METRICS
348 break;
349 case QPaintDevice::PdmHeight:
350 val = d->m_paintRectPixels.height();
351 #ifdef QT_DEBUG_METRICS
352 qDebug() << "QWin32PrintEngine::metric(PdmHeight) = " << val;
353 d->debugMetrics();
354 #endif // QT_DEBUG_METRICS
355 break;
356 case QPaintDevice::PdmDpiX:
357 val = res;
358 break;
359 case QPaintDevice::PdmDpiY:
360 val = res;
361 break;
362 case QPaintDevice::PdmPhysicalDpiX:
363 val = GetDeviceCaps(d->hdc, LOGPIXELSX);
364 break;
365 case QPaintDevice::PdmPhysicalDpiY:
366 val = GetDeviceCaps(d->hdc, LOGPIXELSY);
367 break;
368 case QPaintDevice::PdmWidthMM:
369 val = d->m_paintSizeMM.width();
370 #ifdef QT_DEBUG_METRICS
371 qDebug() << "QWin32PrintEngine::metric(PdmWidthMM) = " << val;
372 d->debugMetrics();
373 #endif // QT_DEBUG_METRICS
374 break;
375 case QPaintDevice::PdmHeightMM:
376 val = d->m_paintSizeMM.height();
377 #ifdef QT_DEBUG_METRICS
378 qDebug() << "QWin32PrintEngine::metric(PdmHeightMM) = " << val;
379 d->debugMetrics();
380 #endif // QT_DEBUG_METRICS
381 break;
382 case QPaintDevice::PdmNumColors:
383 {
384 int bpp = GetDeviceCaps(d->hdc, BITSPIXEL);
385 if(bpp==32)
386 val = INT_MAX;
387 else if(bpp<=8)
388 val = GetDeviceCaps(d->hdc, NUMCOLORS);
389 else
390 val = 1 << (bpp * GetDeviceCaps(d->hdc, PLANES));
391 }
392 break;
393 case QPaintDevice::PdmDepth:
394 val = GetDeviceCaps(d->hdc, PLANES);
395 break;
396 case QPaintDevice::PdmDevicePixelRatio:
397 val = 1;
398 break;
399 case QPaintDevice::PdmDevicePixelRatioScaled:
400 val = 1 * QPaintDevice::devicePixelRatioFScale();
401 break;
402 default:
403 qWarning("QPrinter::metric: Invalid metric command");
404 return 0;
405 }
406 return val;
407 }
408
updateState(const QPaintEngineState & state)409 void QWin32PrintEngine::updateState(const QPaintEngineState &state)
410 {
411 Q_D(QWin32PrintEngine);
412
413 QAlphaPaintEngine::updateState(state);
414 if (!continueCall())
415 return;
416
417 if (state.state() & DirtyTransform) {
418 updateMatrix(state.transform());
419 }
420
421 if (state.state() & DirtyPen) {
422 d->pen = state.pen();
423 d->has_pen = d->pen.style() != Qt::NoPen && d->pen.isSolid();
424 }
425
426 if (state.state() & DirtyBrush) {
427 QBrush brush = state.brush();
428 d->has_brush = brush.style() == Qt::SolidPattern;
429 d->brush_color = brush.color();
430 }
431
432 if (state.state() & DirtyClipEnabled) {
433 if (state.isClipEnabled())
434 updateClipPath(painter()->clipPath(), Qt::ReplaceClip);
435 else
436 updateClipPath(QPainterPath(), Qt::NoClip);
437 }
438
439 if (state.state() & DirtyClipPath) {
440 updateClipPath(state.clipPath(), state.clipOperation());
441 }
442
443 if (state.state() & DirtyClipRegion) {
444 QRegion clipRegion = state.clipRegion();
445 QPainterPath clipPath = qt_regionToPath(clipRegion);
446 updateClipPath(clipPath, state.clipOperation());
447 }
448 }
449
updateClipPath(const QPainterPath & clipPath,Qt::ClipOperation op)450 void QWin32PrintEngine::updateClipPath(const QPainterPath &clipPath, Qt::ClipOperation op)
451 {
452 Q_D(QWin32PrintEngine);
453
454 bool doclip = true;
455 if (op == Qt::NoClip) {
456 SelectClipRgn(d->hdc, 0);
457 doclip = false;
458 }
459
460 if (doclip) {
461 QPainterPath xformed = clipPath * d->matrix;
462
463 if (xformed.isEmpty()) {
464 // QRegion empty(-0x1000000, -0x1000000, 1, 1);
465 HRGN empty = CreateRectRgn(-0x1000000, -0x1000000, -0x0fffffff, -0x0ffffff);
466 SelectClipRgn(d->hdc, empty);
467 DeleteObject(empty);
468 } else {
469 d->composeGdiPath(xformed);
470 const int ops[] = {
471 -1, // Qt::NoClip, covered above
472 RGN_COPY, // Qt::ReplaceClip
473 RGN_AND, // Qt::IntersectClip
474 RGN_OR // Qt::UniteClip
475 };
476 Q_ASSERT(op > 0 && unsigned(op) <= sizeof(ops) / sizeof(int));
477 SelectClipPath(d->hdc, ops[op]);
478 }
479 }
480
481 QPainterPath aclip = qt_regionToPath(alphaClipping());
482 if (!aclip.isEmpty()) {
483 QTransform tx(d->stretch_x, 0, 0, d->stretch_y, d->origin_x, d->origin_y);
484 d->composeGdiPath(tx.map(aclip));
485 SelectClipPath(d->hdc, RGN_DIFF);
486 }
487 }
488
updateMatrix(const QTransform & m)489 void QWin32PrintEngine::updateMatrix(const QTransform &m)
490 {
491 Q_D(QWin32PrintEngine);
492
493 QTransform stretch(d->stretch_x, 0, 0, d->stretch_y, d->origin_x, d->origin_y);
494 d->painterMatrix = m;
495 d->matrix = d->painterMatrix * stretch;
496 d->txop = d->matrix.type();
497 d->complex_xform = (d->txop > QTransform::TxScale);
498 }
499
500 enum HBitmapFormat
501 {
502 HBitmapNoAlpha,
503 HBitmapPremultipliedAlpha,
504 HBitmapAlpha
505 };
506
drawPixmap(const QRectF & targetRect,const QPixmap & originalPixmap,const QRectF & sourceRect)507 void QWin32PrintEngine::drawPixmap(const QRectF &targetRect,
508 const QPixmap &originalPixmap,
509 const QRectF &sourceRect)
510 {
511 Q_D(QWin32PrintEngine);
512
513 QAlphaPaintEngine::drawPixmap(targetRect, originalPixmap, sourceRect);
514 if (!continueCall())
515 return;
516
517 const int tileSize = 2048;
518
519 QRectF r = targetRect;
520 QRectF sr = sourceRect;
521
522 QPixmap pixmap = originalPixmap;
523 if (sr.size() != pixmap.size()) {
524 pixmap = pixmap.copy(sr.toRect());
525 }
526
527 qreal scaleX = 1.0f;
528 qreal scaleY = 1.0f;
529
530 QTransform scaleMatrix = QTransform::fromScale(r.width() / pixmap.width(), r.height() / pixmap.height());
531 QTransform adapted = QPixmap::trueMatrix(d->painterMatrix * scaleMatrix,
532 pixmap.width(), pixmap.height());
533
534 qreal xform_offset_x = adapted.dx();
535 qreal xform_offset_y = adapted.dy();
536
537 if (d->complex_xform) {
538 pixmap = pixmap.transformed(adapted);
539 scaleX = d->stretch_x;
540 scaleY = d->stretch_y;
541 } else {
542 scaleX = d->stretch_x * (r.width() / pixmap.width()) * d->painterMatrix.m11();
543 scaleY = d->stretch_y * (r.height() / pixmap.height()) * d->painterMatrix.m22();
544 }
545
546 QPointF topLeft = r.topLeft() * d->painterMatrix;
547 int tx = int(topLeft.x() * d->stretch_x + d->origin_x);
548 int ty = int(topLeft.y() * d->stretch_y + d->origin_y);
549 int tw = qAbs(int(pixmap.width() * scaleX));
550 int th = qAbs(int(pixmap.height() * scaleY));
551
552 xform_offset_x *= d->stretch_x;
553 xform_offset_y *= d->stretch_y;
554
555 int dc_state = SaveDC(d->hdc);
556
557 int tilesw = pixmap.width() / tileSize;
558 int tilesh = pixmap.height() / tileSize;
559 ++tilesw;
560 ++tilesh;
561
562 int txinc = tileSize*scaleX;
563 int tyinc = tileSize*scaleY;
564
565 for (int y = 0; y < tilesh; ++y) {
566 int tposy = ty + (y * tyinc);
567 int imgh = tileSize;
568 int height = tyinc;
569 if (y == (tilesh - 1)) {
570 imgh = pixmap.height() - (y * tileSize);
571 height = (th - (y * tyinc));
572 }
573 for (int x = 0; x < tilesw; ++x) {
574 int tposx = tx + (x * txinc);
575 int imgw = tileSize;
576 int width = txinc;
577 if (x == (tilesw - 1)) {
578 imgw = pixmap.width() - (x * tileSize);
579 width = (tw - (x * txinc));
580 }
581
582
583 QImage img(QSize(imgw, imgh), QImage::Format_RGB32);
584 img.fill(Qt::white);
585 QPainter painter(&img);
586 painter.drawPixmap(0,0, pixmap, tileSize * x, tileSize * y, imgw, imgh);
587 QPixmap p = QPixmap::fromImage(img);
588
589 HBITMAP hbitmap = qt_pixmapToWinHBITMAP(p, HBitmapNoAlpha);
590 HDC hbitmap_hdc = CreateCompatibleDC(d->hdc);
591 HGDIOBJ null_bitmap = SelectObject(hbitmap_hdc, hbitmap);
592
593 if (!StretchBlt(d->hdc, qRound(tposx - xform_offset_x), qRound(tposy - xform_offset_y), width, height,
594 hbitmap_hdc, 0, 0, p.width(), p.height(), SRCCOPY))
595 qErrnoWarning("QWin32PrintEngine::drawPixmap, StretchBlt failed");
596
597 SelectObject(hbitmap_hdc, null_bitmap);
598 DeleteObject(hbitmap);
599 DeleteDC(hbitmap_hdc);
600 }
601 }
602
603 RestoreDC(d->hdc, dc_state);
604 }
605
606
drawTiledPixmap(const QRectF & r,const QPixmap & pm,const QPointF & pos)607 void QWin32PrintEngine::drawTiledPixmap(const QRectF &r, const QPixmap &pm, const QPointF &pos)
608 {
609 Q_D(QWin32PrintEngine);
610
611 QAlphaPaintEngine::drawTiledPixmap(r, pm, pos);
612 if (!continueCall())
613 return;
614
615 if (d->complex_xform || !pos.isNull()) {
616 QPaintEngine::drawTiledPixmap(r, pm, pos);
617 } else {
618 int dc_state = SaveDC(d->hdc);
619
620 HBITMAP hbitmap = qt_pixmapToWinHBITMAP(pm, HBitmapNoAlpha);
621 HDC hbitmap_hdc = CreateCompatibleDC(d->hdc);
622 HGDIOBJ null_bitmap = SelectObject(hbitmap_hdc, hbitmap);
623
624 QRectF trect = d->painterMatrix.mapRect(r);
625 int tx = int(trect.left() * d->stretch_x + d->origin_x);
626 int ty = int(trect.top() * d->stretch_y + d->origin_y);
627
628 int xtiles = int(trect.width() / pm.width()) + 1;
629 int ytiles = int(trect.height() / pm.height()) + 1;
630 int xinc = int(pm.width() * d->stretch_x);
631 int yinc = int(pm.height() * d->stretch_y);
632
633 for (int y = 0; y < ytiles; ++y) {
634 int ity = ty + (yinc * y);
635 int ith = pm.height();
636 if (y == (ytiles - 1)) {
637 ith = int(trect.height() - (pm.height() * y));
638 }
639
640 for (int x = 0; x < xtiles; ++x) {
641 int itx = tx + (xinc * x);
642 int itw = pm.width();
643 if (x == (xtiles - 1)) {
644 itw = int(trect.width() - (pm.width() * x));
645 }
646
647 if (!StretchBlt(d->hdc, itx, ity, int(itw * d->stretch_x), int(ith * d->stretch_y),
648 hbitmap_hdc, 0, 0, itw, ith, SRCCOPY))
649 qErrnoWarning("QWin32PrintEngine::drawPixmap, StretchBlt failed");
650
651 }
652 }
653
654 SelectObject(hbitmap_hdc, null_bitmap);
655 DeleteObject(hbitmap);
656 DeleteDC(hbitmap_hdc);
657
658 RestoreDC(d->hdc, dc_state);
659 }
660 }
661
662
composeGdiPath(const QPainterPath & path)663 void QWin32PrintEnginePrivate::composeGdiPath(const QPainterPath &path)
664 {
665 if (!BeginPath(hdc))
666 qErrnoWarning("QWin32PrintEnginePrivate::drawPath: BeginPath failed");
667
668 // Drawing the subpaths
669 int start = -1;
670 for (int i=0; i<path.elementCount(); ++i) {
671 const QPainterPath::Element &elm = path.elementAt(i);
672 switch (elm.type) {
673 case QPainterPath::MoveToElement:
674 if (start >= 0
675 && path.elementAt(start).x == path.elementAt(i-1).x
676 && path.elementAt(start).y == path.elementAt(i-1).y)
677 CloseFigure(hdc);
678 start = i;
679 MoveToEx(hdc, qRound(elm.x), qRound(elm.y), 0);
680 break;
681 case QPainterPath::LineToElement:
682 LineTo(hdc, qRound(elm.x), qRound(elm.y));
683 break;
684 case QPainterPath::CurveToElement: {
685 POINT pts[3] = {
686 { qRound(elm.x), qRound(elm.y) },
687 { qRound(path.elementAt(i+1).x), qRound(path.elementAt(i+1).y) },
688 { qRound(path.elementAt(i+2).x), qRound(path.elementAt(i+2).y) }
689 };
690 i+=2;
691 PolyBezierTo(hdc, pts, 3);
692 break;
693 }
694 default:
695 qFatal("QWin32PaintEngine::drawPath: Unhandled type: %d", elm.type);
696 }
697 }
698
699 if (start >= 0
700 && path.elementAt(start).x == path.elementAt(path.elementCount()-1).x
701 && path.elementAt(start).y == path.elementAt(path.elementCount()-1).y)
702 CloseFigure(hdc);
703
704 if (!EndPath(hdc))
705 qErrnoWarning("QWin32PaintEngine::drawPath: EndPath failed");
706
707 SetPolyFillMode(hdc, path.fillRule() == Qt::WindingFill ? WINDING : ALTERNATE);
708 }
709
710
fillPath_dev(const QPainterPath & path,const QColor & color)711 void QWin32PrintEnginePrivate::fillPath_dev(const QPainterPath &path, const QColor &color)
712 {
713 #ifdef QT_DEBUG_DRAW
714 qDebug() << " --- QWin32PrintEnginePrivate::fillPath() bound:" << path.boundingRect() << color;
715 #endif
716
717 composeGdiPath(path);
718
719 HBRUSH brush = CreateSolidBrush(RGB(color.red(), color.green(), color.blue()));
720 HGDIOBJ old_brush = SelectObject(hdc, brush);
721 FillPath(hdc);
722 DeleteObject(SelectObject(hdc, old_brush));
723 }
724
strokePath_dev(const QPainterPath & path,const QColor & color,qreal penWidth)725 void QWin32PrintEnginePrivate::strokePath_dev(const QPainterPath &path, const QColor &color, qreal penWidth)
726 {
727 composeGdiPath(path);
728 LOGBRUSH brush;
729 brush.lbStyle = BS_SOLID;
730 brush.lbColor = RGB(color.red(), color.green(), color.blue());
731 DWORD capStyle = PS_ENDCAP_SQUARE;
732 DWORD joinStyle = PS_JOIN_BEVEL;
733 if (pen.capStyle() == Qt::FlatCap)
734 capStyle = PS_ENDCAP_FLAT;
735 else if (pen.capStyle() == Qt::RoundCap)
736 capStyle = PS_ENDCAP_ROUND;
737
738 if (pen.joinStyle() == Qt::MiterJoin)
739 joinStyle = PS_JOIN_MITER;
740 else if (pen.joinStyle() == Qt::RoundJoin)
741 joinStyle = PS_JOIN_ROUND;
742
743 HPEN pen = ExtCreatePen(PS_GEOMETRIC | PS_SOLID | capStyle | joinStyle,
744 (penWidth == 0) ? 1 : penWidth, &brush, 0, 0);
745
746 HGDIOBJ old_pen = SelectObject(hdc, pen);
747 StrokePath(hdc);
748 DeleteObject(SelectObject(hdc, old_pen));
749 }
750
751
fillPath(const QPainterPath & path,const QColor & color)752 void QWin32PrintEnginePrivate::fillPath(const QPainterPath &path, const QColor &color)
753 {
754 fillPath_dev(path * matrix, color);
755 }
756
strokePath(const QPainterPath & path,const QColor & color)757 void QWin32PrintEnginePrivate::strokePath(const QPainterPath &path, const QColor &color)
758 {
759 Q_Q(QWin32PrintEngine);
760
761 QPainterPathStroker stroker;
762 if (pen.style() == Qt::CustomDashLine) {
763 stroker.setDashPattern(pen.dashPattern());
764 stroker.setDashOffset(pen.dashOffset());
765 } else {
766 stroker.setDashPattern(pen.style());
767 }
768 stroker.setCapStyle(pen.capStyle());
769 stroker.setJoinStyle(pen.joinStyle());
770 stroker.setMiterLimit(pen.miterLimit());
771
772 QPainterPath stroke;
773 qreal width = pen.widthF();
774 bool cosmetic = qt_pen_is_cosmetic(pen, q->state->renderHints());
775 if (pen.style() == Qt::SolidLine && (cosmetic || matrix.type() < QTransform::TxScale)) {
776 strokePath_dev(path * matrix, color, width);
777 } else {
778 stroker.setWidth(width);
779 if (cosmetic) {
780 stroke = stroker.createStroke(path * matrix);
781 } else {
782 stroke = stroker.createStroke(path) * painterMatrix;
783 QTransform stretch(stretch_x, 0, 0, stretch_y, origin_x, origin_y);
784 stroke = stroke * stretch;
785 }
786
787 if (stroke.isEmpty())
788 return;
789
790 fillPath_dev(stroke, color);
791 }
792 }
793
794
drawPath(const QPainterPath & path)795 void QWin32PrintEngine::drawPath(const QPainterPath &path)
796 {
797 #ifdef QT_DEBUG_DRAW
798 qDebug() << " - QWin32PrintEngine::drawPath(), bounds: " << path.boundingRect();
799 #endif
800
801 Q_D(QWin32PrintEngine);
802
803 QAlphaPaintEngine::drawPath(path);
804 if (!continueCall())
805 return;
806
807 if (d->has_brush)
808 d->fillPath(path, d->brush_color);
809
810 if (d->has_pen)
811 d->strokePath(path, d->pen.color());
812 }
813
814
drawPolygon(const QPointF * points,int pointCount,PolygonDrawMode mode)815 void QWin32PrintEngine::drawPolygon(const QPointF *points, int pointCount, PolygonDrawMode mode)
816 {
817 #ifdef QT_DEBUG_DRAW
818 qDebug() << " - QWin32PrintEngine::drawPolygon(), pointCount: " << pointCount;
819 #endif
820
821 QAlphaPaintEngine::drawPolygon(points, pointCount, mode);
822 if (!continueCall())
823 return;
824
825 Q_ASSERT(pointCount > 1);
826
827 QPainterPath path(points[0]);
828
829 for (int i=1; i<pointCount; ++i) {
830 path.lineTo(points[i]);
831 }
832
833 Q_D(QWin32PrintEngine);
834
835 bool has_brush = d->has_brush;
836
837 if (mode == PolylineMode)
838 d->has_brush = false; // No brush for polylines
839 else
840 path.closeSubpath(); // polygons are should always be closed.
841
842 drawPath(path);
843 d->has_brush = has_brush;
844 }
845
~QWin32PrintEnginePrivate()846 QWin32PrintEnginePrivate::~QWin32PrintEnginePrivate()
847 {
848 release();
849 }
850
initialize()851 void QWin32PrintEnginePrivate::initialize()
852 {
853 release();
854
855 Q_ASSERT(!hPrinter);
856 Q_ASSERT(!hdc);
857 Q_ASSERT(!devMode);
858 Q_ASSERT(!pInfo);
859
860 if (!m_printDevice.isValid())
861 return;
862
863 txop = QTransform::TxNone;
864
865 QString printerName = m_printDevice.id();
866 bool ok = OpenPrinter((LPWSTR)printerName.utf16(), (LPHANDLE)&hPrinter, 0);
867 if (!ok) {
868 qErrnoWarning("QWin32PrintEngine::initialize: OpenPrinter failed");
869 return;
870 }
871
872 // Fetch the PRINTER_INFO_2 with DEVMODE data containing the
873 // printer settings.
874 DWORD infoSize, numBytes;
875 GetPrinter(hPrinter, 2, NULL, 0, &infoSize);
876 hMem = GlobalAlloc(GHND, infoSize);
877 pInfo = (PRINTER_INFO_2*) GlobalLock(hMem);
878 ok = GetPrinter(hPrinter, 2, (LPBYTE)pInfo, infoSize, &numBytes);
879
880 if (!ok) {
881 qErrnoWarning("QWin32PrintEngine::initialize: GetPrinter failed");
882 release();
883 return;
884 }
885
886 devMode = pInfo->pDevMode;
887
888 if (!devMode) {
889 // pInfo->pDevMode == NULL for some printers and passing NULL
890 // into CreateDC leads to the printer doing nothing. In addition,
891 // the framework assumes that devMode isn't NULL, such as in
892 // QWin32PrintEngine::begin() and QPageSetupDialog::exec()
893 // Attempt to get the DEVMODE a different way.
894
895 // Allocate the required buffer
896 LONG result = DocumentProperties(NULL, hPrinter, (LPWSTR)printerName.utf16(),
897 NULL, NULL, 0);
898 devMode = (DEVMODE *) malloc(result);
899 ownsDevMode = true;
900
901 // Get the default DevMode
902 result = DocumentProperties(NULL, hPrinter, (LPWSTR)printerName.utf16(),
903 devMode, NULL, DM_OUT_BUFFER);
904 if (result != IDOK) {
905 qErrnoWarning("QWin32PrintEngine::initialize: Failed to obtain devMode");
906 free(devMode);
907 devMode = NULL;
908 ownsDevMode = false;
909 }
910 }
911
912 hdc = CreateDC(NULL, (LPCWSTR)printerName.utf16(), 0, devMode);
913
914 if (!hdc) {
915 qErrnoWarning("QWin32PrintEngine::initialize: CreateDC failed");
916 release();
917 return;
918 }
919
920 Q_ASSERT(hPrinter);
921 Q_ASSERT(pInfo);
922
923 initHDC();
924
925 if (devMode) {
926 num_copies = devMode->dmCopies;
927 devMode->dmCollate = DMCOLLATE_TRUE;
928 updatePageLayout();
929 }
930
931 #if defined QT_DEBUG_DRAW || defined QT_DEBUG_METRICS
932 qDebug("QWin32PrintEngine::initialize()");
933 debugMetrics();
934 #endif // QT_DEBUG_DRAW || QT_DEBUG_METRICS
935 }
936
initHDC()937 void QWin32PrintEnginePrivate::initHDC()
938 {
939 Q_ASSERT(hdc);
940
941 HDC display_dc = GetDC(0);
942 dpi_x = GetDeviceCaps(hdc, LOGPIXELSX);
943 dpi_y = GetDeviceCaps(hdc, LOGPIXELSY);
944 dpi_display = GetDeviceCaps(display_dc, LOGPIXELSY);
945 ReleaseDC(0, display_dc);
946 if (dpi_display == 0) {
947 qWarning("QWin32PrintEngine::metric: GetDeviceCaps() failed, "
948 "might be a driver problem");
949 dpi_display = 96; // Reasonable default
950 }
951
952 switch(mode) {
953 case QPrinter::ScreenResolution:
954 resolution = dpi_display;
955 stretch_x = dpi_x / double(dpi_display);
956 stretch_y = dpi_y / double(dpi_display);
957 break;
958 case QPrinter::PrinterResolution:
959 case QPrinter::HighResolution:
960 resolution = dpi_y;
961 stretch_x = 1;
962 stretch_y = 1;
963 break;
964 default:
965 break;
966 }
967
968 updateMetrics();
969 }
970
release()971 void QWin32PrintEnginePrivate::release()
972 {
973 if (globalDevMode) { // Devmode comes from print dialog
974 GlobalUnlock(globalDevMode);
975 } else if (hMem) {
976 GlobalUnlock(hMem);
977 GlobalFree(hMem);
978 }
979 if (hPrinter)
980 ClosePrinter(hPrinter);
981 if (hdc)
982 DeleteDC(hdc);
983
984 // Check if devMode was allocated separately from pInfo / hMem.
985 if (ownsDevMode)
986 free(devMode);
987
988 hdc = 0;
989 hPrinter = 0;
990 pInfo = 0;
991 hMem = 0;
992 devMode = 0;
993 ownsDevMode = false;
994 }
995
doReinit()996 void QWin32PrintEnginePrivate::doReinit()
997 {
998 if (state == QPrinter::Active) {
999 reinit = true;
1000 } else {
1001 resetDC();
1002 reinit = false;
1003 }
1004 }
1005
resetDC()1006 bool QWin32PrintEnginePrivate::resetDC()
1007 {
1008 if (!hdc) {
1009 qWarning("ResetDC() called with null hdc.");
1010 return false;
1011 }
1012 const HDC oldHdc = hdc;
1013 const HDC hdc = ResetDC(oldHdc, devMode);
1014 if (!hdc) {
1015 const int lastError = GetLastError();
1016 qErrnoWarning(lastError, "ResetDC() on %p failed (%d)", oldHdc, lastError);
1017 }
1018 return hdc != 0;
1019 }
1020
indexOfId(const QVector<QPrint::InputSlot> & inputSlots,QPrint::InputSlotId id)1021 static int indexOfId(const QVector<QPrint::InputSlot> &inputSlots, QPrint::InputSlotId id)
1022 {
1023 for (int i = 0; i < inputSlots.size(); ++i) {
1024 if (inputSlots.at(i).id == id)
1025 return i;
1026 }
1027 return -1;
1028 }
1029
indexOfWindowsId(const QVector<QPrint::InputSlot> & inputSlots,int windowsId)1030 static int indexOfWindowsId(const QVector<QPrint::InputSlot> &inputSlots, int windowsId)
1031 {
1032 for (int i = 0; i < inputSlots.size(); ++i) {
1033 if (inputSlots.at(i).windowsId == windowsId)
1034 return i;
1035 }
1036 return -1;
1037 }
1038
setProperty(PrintEnginePropertyKey key,const QVariant & value)1039 void QWin32PrintEngine::setProperty(PrintEnginePropertyKey key, const QVariant &value)
1040 {
1041 Q_D(QWin32PrintEngine);
1042 switch (key) {
1043
1044 // The following keys are properties or derived values and so cannot be set
1045 case PPK_PageRect:
1046 break;
1047 case PPK_PaperRect:
1048 break;
1049 case PPK_PaperSources:
1050 break;
1051 case PPK_SupportsMultipleCopies:
1052 break;
1053 case PPK_SupportedResolutions:
1054 break;
1055
1056 // The following keys are settings that are unsupported by the Windows PrintEngine
1057 case PPK_CustomBase:
1058 break;
1059 case PPK_PageOrder:
1060 break;
1061 case PPK_PrinterProgram:
1062 break;
1063 case PPK_SelectionOption:
1064 break;
1065
1066 // The following keys are properties and settings that are supported by the Windows PrintEngine
1067 case PPK_FontEmbedding:
1068 d->embed_fonts = value.toBool();
1069 break;
1070
1071 case PPK_CollateCopies:
1072 {
1073 if (!d->devMode)
1074 break;
1075 d->devMode->dmCollate = value.toBool() ? DMCOLLATE_TRUE : DMCOLLATE_FALSE;
1076 d->doReinit();
1077 }
1078 break;
1079
1080 case PPK_ColorMode:
1081 {
1082 if (!d->devMode)
1083 break;
1084 d->devMode->dmColor = (value.toInt() == QPrinter::Color) ? DMCOLOR_COLOR : DMCOLOR_MONOCHROME;
1085 d->doReinit();
1086 }
1087 break;
1088
1089 case PPK_Creator:
1090 d->m_creator = value.toString();
1091 break;
1092
1093 case PPK_DocumentName:
1094 if (isActive()) {
1095 qWarning("QWin32PrintEngine: Cannot change document name while printing is active");
1096 return;
1097 }
1098 d->docName = value.toString();
1099 break;
1100
1101 case PPK_Duplex: {
1102 if (!d->devMode)
1103 break;
1104 QPrint::DuplexMode mode = QPrint::DuplexMode(value.toInt());
1105 if (mode == property(PPK_Duplex).toInt() || !d->m_printDevice.supportedDuplexModes().contains(mode))
1106 break;
1107 switch (mode) {
1108 case QPrint::DuplexNone:
1109 d->devMode->dmDuplex = DMDUP_SIMPLEX;
1110 break;
1111 case QPrint::DuplexAuto:
1112 d->devMode->dmDuplex = d->m_pageLayout.orientation() == QPageLayout::Landscape ? DMDUP_HORIZONTAL : DMDUP_VERTICAL;
1113 break;
1114 case QPrint::DuplexLongSide:
1115 d->devMode->dmDuplex = DMDUP_VERTICAL;
1116 break;
1117 case QPrint::DuplexShortSide:
1118 d->devMode->dmDuplex = DMDUP_HORIZONTAL;
1119 break;
1120 default:
1121 // Don't change
1122 break;
1123 }
1124 d->doReinit();
1125 break;
1126 }
1127
1128 case PPK_FullPage:
1129 if (value.toBool())
1130 d->m_pageLayout.setMode(QPageLayout::FullPageMode);
1131 else
1132 d->m_pageLayout.setMode(QPageLayout::StandardMode);
1133 d->updateMetrics();
1134 #ifdef QT_DEBUG_METRICS
1135 qDebug() << "QWin32PrintEngine::setProperty(PPK_FullPage," << value.toBool() << + ")";
1136 d->debugMetrics();
1137 #endif // QT_DEBUG_METRICS
1138 break;
1139
1140 case PPK_CopyCount:
1141 case PPK_NumberOfCopies:
1142 if (!d->devMode)
1143 break;
1144 d->num_copies = value.toInt();
1145 d->devMode->dmCopies = d->num_copies;
1146 d->doReinit();
1147 break;
1148
1149 case PPK_Orientation: {
1150 if (!d->devMode)
1151 break;
1152 QPageLayout::Orientation orientation = QPageLayout::Orientation(value.toInt());
1153 d->devMode->dmOrientation = orientation == QPageLayout::Landscape ? DMORIENT_LANDSCAPE : DMORIENT_PORTRAIT;
1154 d->m_pageLayout.setOrientation(orientation);
1155 d->updateMetrics();
1156 d->doReinit();
1157 #ifdef QT_DEBUG_METRICS
1158 qDebug() << "QWin32PrintEngine::setProperty(PPK_Orientation," << orientation << ')';
1159 d->debugMetrics();
1160 #endif // QT_DEBUG_METRICS
1161 break;
1162 }
1163
1164 case PPK_OutputFileName:
1165 if (isActive()) {
1166 qWarning("QWin32PrintEngine: Cannot change filename while printing");
1167 } else {
1168 d->fileName = value.toString();
1169 d->printToFile = !value.toString().isEmpty();
1170 }
1171 break;
1172
1173 case PPK_PageSize: {
1174 if (!d->devMode)
1175 break;
1176 const QPageSize pageSize = QPageSize(QPageSize::PageSizeId(value.toInt()));
1177 if (pageSize.isValid()) {
1178 d->setPageSize(pageSize);
1179 d->doReinit();
1180 #ifdef QT_DEBUG_METRICS
1181 qDebug() << "QWin32PrintEngine::setProperty(PPK_PageSize," << value.toInt() << ')';
1182 d->debugMetrics();
1183 #endif // QT_DEBUG_METRICS
1184 }
1185 break;
1186 }
1187
1188 case PPK_PaperName: {
1189 if (!d->devMode)
1190 break;
1191 // Get the named page size from the printer if supported
1192 const QPageSize pageSize = d->m_printDevice.supportedPageSize(value.toString());
1193 if (pageSize.isValid()) {
1194 d->setPageSize(pageSize);
1195 d->doReinit();
1196 #ifdef QT_DEBUG_METRICS
1197 qDebug() << "QWin32PrintEngine::setProperty(PPK_PaperName," << value.toString() << ')';
1198 d->debugMetrics();
1199 #endif // QT_DEBUG_METRICS
1200 }
1201 break;
1202 }
1203
1204 case PPK_PaperSource: {
1205 if (!d->devMode)
1206 break;
1207 const auto inputSlots = d->m_printDevice.supportedInputSlots();
1208 const int paperSource = value.toInt();
1209 const int index = paperSource >= DMBIN_USER ?
1210 indexOfWindowsId(inputSlots, paperSource) : indexOfId(inputSlots, QPrint::InputSlotId(paperSource));
1211 d->devMode->dmDefaultSource = index >= 0 ? inputSlots.at(index).windowsId : DMBIN_AUTO;
1212 d->doReinit();
1213 break;
1214 }
1215
1216 case PPK_PrinterName: {
1217 QString id = value.toString();
1218 QPlatformPrinterSupport *ps = QPlatformPrinterSupportPlugin::get();
1219 if (!ps)
1220 return;
1221
1222 QVariant pageSize = QVariant::fromValue(d->m_pageLayout.pageSize());
1223 const bool isFullPage = (d->m_pageLayout.mode() == QPageLayout::FullPageMode);
1224 QVariant orientation = QVariant::fromValue(d->m_pageLayout.orientation());
1225 QVariant margins = QVariant::fromValue(
1226 QPair<QMarginsF, QPageLayout::Unit>(d->m_pageLayout.margins(), d->m_pageLayout.units()));
1227 QPrintDevice printDevice = ps->createPrintDevice(id.isEmpty() ? ps->defaultPrintDeviceId() : id);
1228 if (printDevice.isValid()) {
1229 d->m_printDevice = printDevice;
1230 d->initialize();
1231 if (d->m_printDevice.supportedPageSize(pageSize.value<QPageSize>()).isValid())
1232 setProperty(PPK_QPageSize, pageSize);
1233 else
1234 setProperty(PPK_CustomPaperSize, pageSize.value<QPageSize>().size(QPageSize::Point));
1235 setProperty(PPK_FullPage, QVariant(isFullPage));
1236 setProperty(PPK_Orientation, orientation);
1237 setProperty(PPK_QPageMargins, margins);
1238 }
1239 break;
1240 }
1241
1242 case PPK_Resolution: {
1243 d->resolution = value.toInt();
1244 d->stretch_x = d->dpi_x / double(d->resolution);
1245 d->stretch_y = d->dpi_y / double(d->resolution);
1246 d->updateMetrics();
1247 #ifdef QT_DEBUG_METRICS
1248 qDebug() << "QWin32PrintEngine::setProperty(PPK_Resolution," << value.toInt() << ')';
1249 d->debugMetrics();
1250 #endif // QT_DEBUG_METRICS
1251 break;
1252 }
1253
1254 case PPK_WindowsPageSize: {
1255 if (!d->devMode)
1256 break;
1257 const QPageSize pageSize = QPageSize(QPageSize::id(value.toInt()));
1258 if (pageSize.isValid()) {
1259 d->setPageSize(pageSize);
1260 d->doReinit();
1261 #ifdef QT_DEBUG_METRICS
1262 qDebug() << "QWin32PrintEngine::setProperty(PPK_WindowsPageSize," << value.toInt() << ')';
1263 d->debugMetrics();
1264 #endif // QT_DEBUG_METRICS
1265 break;
1266 }
1267 break;
1268 }
1269
1270 case PPK_CustomPaperSize: {
1271 if (!d->devMode)
1272 break;
1273 const QPageSize pageSize = QPageSize(value.toSizeF(), QPageSize::Point);
1274 if (pageSize.isValid()) {
1275 d->setPageSize(pageSize);
1276 d->doReinit();
1277 #ifdef QT_DEBUG_METRICS
1278 qDebug() << "QWin32PrintEngine::setProperty(PPK_CustomPaperSize," << value.toSizeF() << ')';
1279 d->debugMetrics();
1280 #endif // QT_DEBUG_METRICS
1281 }
1282 break;
1283 }
1284
1285 case PPK_PageMargins: {
1286 QList<QVariant> margins(value.toList());
1287 Q_ASSERT(margins.size() == 4);
1288 d->m_pageLayout.setUnits(QPageLayout::Point);
1289 d->m_pageLayout.setMargins(QMarginsF(margins.at(0).toReal(), margins.at(1).toReal(),
1290 margins.at(2).toReal(), margins.at(3).toReal()));
1291 d->updateMetrics();
1292 #ifdef QT_DEBUG_METRICS
1293 qDebug() << "QWin32PrintEngine::setProperty(PPK_PageMargins," << margins << ')';
1294 d->debugMetrics();
1295 #endif // QT_DEBUG_METRICS
1296 break;
1297 }
1298
1299 case PPK_QPageSize: {
1300 if (!d->devMode)
1301 break;
1302 // Get the page size from the printer if supported
1303 const QPageSize pageSize = value.value<QPageSize>();
1304 if (pageSize.isValid()) {
1305 d->setPageSize(pageSize);
1306 d->doReinit();
1307 #ifdef QT_DEBUG_METRICS
1308 qDebug() << "QWin32PrintEngine::setProperty(PPK_QPageSize," << pageSize << ')';
1309 d->debugMetrics();
1310 #endif // QT_DEBUG_METRICS
1311 }
1312 break;
1313 }
1314
1315 case PPK_QPageMargins: {
1316 QPair<QMarginsF, QPageLayout::Unit> pair = value.value<QPair<QMarginsF, QPageLayout::Unit> >();
1317 d->m_pageLayout.setUnits(pair.second);
1318 d->m_pageLayout.setMargins(pair.first);
1319 d->updateMetrics();
1320 #ifdef QT_DEBUG_METRICS
1321 qDebug() << "QWin32PrintEngine::setProperty(PPK_QPageMargins," << pair.first << pair.second << ')';
1322 d->debugMetrics();
1323 #endif // QT_DEBUG_METRICS
1324 break;
1325 }
1326
1327 case PPK_QPageLayout: {
1328 QPageLayout pageLayout = value.value<QPageLayout>();
1329 if (pageLayout.isValid() && d->m_printDevice.isValidPageLayout(pageLayout, d->resolution)) {
1330 setProperty(PPK_QPageSize, QVariant::fromValue(pageLayout.pageSize()));
1331 setProperty(PPK_FullPage, pageLayout.mode() == QPageLayout::FullPageMode);
1332 setProperty(PPK_Orientation, QVariant::fromValue(pageLayout.orientation()));
1333 d->m_pageLayout.setUnits(pageLayout.units());
1334 d->m_pageLayout.setMargins(pageLayout.margins());
1335 d->updateMetrics();
1336 #ifdef QT_DEBUG_METRICS
1337 qDebug() << "QWin32PrintEngine::setProperty(PPK_QPageLayout," << pageLayout << ')';
1338 d->debugMetrics();
1339 #endif // QT_DEBUG_METRICS
1340 }
1341 break;
1342 }
1343
1344 // No default so that compiler will complain if new keys added and not handled in this engine
1345 }
1346 }
1347
property(PrintEnginePropertyKey key) const1348 QVariant QWin32PrintEngine::property(PrintEnginePropertyKey key) const
1349 {
1350 Q_D(const QWin32PrintEngine);
1351 QVariant value;
1352 switch (key) {
1353
1354 // The following keys are settings that are unsupported by the Windows PrintEngine
1355 // Return sensible default values to ensure consistent behavior across platforms
1356 case PPK_PageOrder:
1357 value = QPrinter::FirstPageFirst;
1358 break;
1359 case PPK_PrinterProgram:
1360 value = QString();
1361 break;
1362 case PPK_SelectionOption:
1363 value = QString();
1364 break;
1365
1366 // The following keys are properties and settings that are supported by the Windows PrintEngine
1367 case PPK_FontEmbedding:
1368 value = d->embed_fonts;
1369 break;
1370
1371 case PPK_CollateCopies:
1372 if (!d->devMode)
1373 value = false;
1374 else
1375 value = d->devMode->dmCollate == DMCOLLATE_TRUE;
1376 break;
1377
1378 case PPK_ColorMode:
1379 {
1380 if (!d->devMode) {
1381 value = QPrinter::Color;
1382 } else {
1383 value = (d->devMode->dmColor == DMCOLOR_COLOR) ? QPrinter::Color : QPrinter::GrayScale;
1384 }
1385 }
1386 break;
1387
1388 case PPK_Creator:
1389 value = d->m_creator;
1390 break;
1391
1392 case PPK_DocumentName:
1393 value = d->docName;
1394 break;
1395
1396 case PPK_Duplex: {
1397 if (!d->devMode) {
1398 value = QPrinter::DuplexNone;
1399 } else {
1400 switch (d->devMode->dmDuplex) {
1401 case DMDUP_VERTICAL:
1402 value = QPrinter::DuplexLongSide;
1403 break;
1404 case DMDUP_HORIZONTAL:
1405 value = QPrinter::DuplexShortSide;
1406 break;
1407 case DMDUP_SIMPLEX:
1408 default:
1409 value = QPrinter::DuplexNone;
1410 break;
1411 }
1412 }
1413 break;
1414 }
1415
1416 case PPK_FullPage:
1417 value = d->m_pageLayout.mode() == QPageLayout::FullPageMode;
1418 break;
1419
1420 case PPK_CopyCount:
1421 value = d->num_copies;
1422 break;
1423
1424 case PPK_SupportsMultipleCopies:
1425 value = true;
1426 break;
1427
1428 case PPK_NumberOfCopies:
1429 value = 1;
1430 break;
1431
1432 case PPK_Orientation:
1433 value = d->m_pageLayout.orientation();
1434 break;
1435
1436 case PPK_OutputFileName:
1437 value = d->fileName;
1438 break;
1439
1440 case PPK_PageRect:
1441 // PageRect is returned in device pixels
1442 value = d->m_pageLayout.paintRectPixels(d->resolution);
1443 break;
1444
1445 case PPK_PageSize:
1446 value = d->m_pageLayout.pageSize().id();
1447 break;
1448
1449 case PPK_PaperRect:
1450 // PaperRect is returned in device pixels
1451 value = d->m_pageLayout.fullRectPixels(d->resolution);
1452 break;
1453
1454 case PPK_PaperName:
1455 value = d->m_pageLayout.pageSize().name();
1456 break;
1457
1458 case PPK_PaperSource:
1459 if (!d->devMode) {
1460 value = d->m_printDevice.defaultInputSlot().id;
1461 } else {
1462 if (d->devMode->dmDefaultSource >= DMBIN_USER) {
1463 value = int(d->devMode->dmDefaultSource);
1464 } else {
1465 const auto inputSlots = d->m_printDevice.supportedInputSlots();
1466 const int index = indexOfWindowsId(inputSlots, d->devMode->dmDefaultSource);
1467 value = index >= 0 ? inputSlots.at(index).id : QPrint::Auto;
1468 }
1469 }
1470 break;
1471
1472 case PPK_PrinterName:
1473 value = d->m_printDevice.id();
1474 break;
1475
1476 case PPK_Resolution:
1477 if (d->resolution || d->m_printDevice.isValid())
1478 value = d->resolution;
1479 break;
1480
1481 case PPK_SupportedResolutions: {
1482 QList<QVariant> list;
1483 const auto resolutions = d->m_printDevice.supportedResolutions();
1484 list.reserve(resolutions.size());
1485 for (int resolution : resolutions)
1486 list << resolution;
1487 value = list;
1488 break;
1489 }
1490
1491 case PPK_WindowsPageSize:
1492 value = d->m_pageLayout.pageSize().windowsId();
1493 break;
1494
1495 case PPK_PaperSources: {
1496 QList<QVariant> out;
1497 const auto inputSlots = d->m_printDevice.supportedInputSlots();
1498 out.reserve(inputSlots.size());
1499 for (const QPrint::InputSlot &inputSlot : inputSlots)
1500 out << QVariant(inputSlot.id == QPrint::CustomInputSlot ? inputSlot.windowsId : int(inputSlot.id));
1501 value = out;
1502 break;
1503 }
1504
1505 case PPK_CustomPaperSize:
1506 value = d->m_pageLayout.fullRectPoints().size();
1507 break;
1508
1509 case PPK_PageMargins: {
1510 QList<QVariant> list;
1511 QMarginsF margins = d->m_pageLayout.margins(QPageLayout::Point);
1512 list << margins.left() << margins.top() << margins.right() << margins.bottom();
1513 value = list;
1514 break;
1515 }
1516
1517 case PPK_QPageSize:
1518 value.setValue(d->m_pageLayout.pageSize());
1519 break;
1520
1521 case PPK_QPageMargins: {
1522 QPair<QMarginsF, QPageLayout::Unit> pair = qMakePair(d->m_pageLayout.margins(), d->m_pageLayout.units());
1523 value.setValue(pair);
1524 break;
1525 }
1526
1527 case PPK_QPageLayout:
1528 value.setValue(d->m_pageLayout);
1529 break;
1530
1531 case PPK_CustomBase:
1532 break;
1533
1534 // No default so that compiler will complain if new keys added and not handled in this engine
1535 }
1536 return value;
1537 }
1538
printerState() const1539 QPrinter::PrinterState QWin32PrintEngine::printerState() const
1540 {
1541 return d_func()->state;
1542 }
1543
getDC() const1544 HDC QWin32PrintEngine::getDC() const
1545 {
1546 return d_func()->hdc;
1547 }
1548
releaseDC(HDC) const1549 void QWin32PrintEngine::releaseDC(HDC) const
1550 {
1551
1552 }
1553
createGlobalDevNames()1554 HGLOBAL *QWin32PrintEngine::createGlobalDevNames()
1555 {
1556 Q_D(QWin32PrintEngine);
1557
1558 int size = sizeof(DEVNAMES) + d->m_printDevice.id().length() * 2 + 2;
1559 auto hGlobal = reinterpret_cast<HGLOBAL *>(GlobalAlloc(GMEM_MOVEABLE, size));
1560 auto dn = reinterpret_cast<DEVNAMES*>(GlobalLock(hGlobal));
1561
1562 dn->wDriverOffset = 0;
1563 dn->wDeviceOffset = sizeof(DEVNAMES) / sizeof(wchar_t);
1564 dn->wOutputOffset = 0;
1565
1566 memcpy(reinterpret_cast<ushort*>(dn) + dn->wDeviceOffset,
1567 d->m_printDevice.id().utf16(), d->m_printDevice.id().length() * 2 + 2);
1568 dn->wDefault = 0;
1569
1570 GlobalUnlock(hGlobal);
1571 return hGlobal;
1572 }
1573
setGlobalDevMode(HGLOBAL globalDevNames,HGLOBAL globalDevMode)1574 void QWin32PrintEngine::setGlobalDevMode(HGLOBAL globalDevNames, HGLOBAL globalDevMode)
1575 {
1576 Q_D(QWin32PrintEngine);
1577 if (globalDevNames) {
1578 auto dn = reinterpret_cast<DEVNAMES*>(GlobalLock(globalDevNames));
1579 const QString id =
1580 QString::fromWCharArray(reinterpret_cast<const wchar_t*>(dn) + dn->wDeviceOffset);
1581 QPlatformPrinterSupport *ps = QPlatformPrinterSupportPlugin::get();
1582 if (ps)
1583 d->m_printDevice = ps->createPrintDevice(id.isEmpty() ? ps->defaultPrintDeviceId() : id);
1584 GlobalUnlock(globalDevNames);
1585 }
1586
1587 if (globalDevMode) {
1588 auto dm = reinterpret_cast<DEVMODE*>(GlobalLock(globalDevMode));
1589 d->release();
1590 d->globalDevMode = globalDevMode;
1591 if (d->ownsDevMode) {
1592 free(d->devMode);
1593 d->ownsDevMode = false;
1594 }
1595 d->devMode = dm;
1596 d->hdc = CreateDC(NULL, reinterpret_cast<const wchar_t *>(d->m_printDevice.id().utf16()), 0, dm);
1597
1598 d->num_copies = d->devMode->dmCopies;
1599 d->updatePageLayout();
1600
1601 if (!OpenPrinter((wchar_t*)d->m_printDevice.id().utf16(), &d->hPrinter, 0))
1602 qWarning("QPrinter: OpenPrinter() failed after reading DEVMODE.");
1603 }
1604
1605 if (d->hdc)
1606 d->initHDC();
1607
1608 #if defined QT_DEBUG_DRAW || defined QT_DEBUG_METRICS
1609 qDebug("QWin32PrintEngine::setGlobalDevMode()");
1610 debugMetrics();
1611 #endif // QT_DEBUG_DRAW || QT_DEBUG_METRICS
1612 }
1613
globalDevMode()1614 HGLOBAL QWin32PrintEngine::globalDevMode()
1615 {
1616 Q_D(QWin32PrintEngine);
1617 return d->globalDevMode;
1618 }
1619
setPageSize(const QPageSize & pageSize)1620 void QWin32PrintEnginePrivate::setPageSize(const QPageSize &pageSize)
1621 {
1622 if (!pageSize.isValid())
1623 return;
1624
1625 Q_ASSERT(devMode);
1626
1627 // Use the printer page size if supported
1628 const QPageSize printerPageSize = m_printDevice.supportedPageSize(pageSize);
1629 const QPageSize usePageSize = printerPageSize.isValid() ? printerPageSize : pageSize;
1630
1631 const QMarginsF printable = m_printDevice.printableMargins(usePageSize, m_pageLayout.orientation(), resolution);
1632 m_pageLayout.setPageSize(usePageSize, qt_convertMargins(printable, QPageLayout::Point, m_pageLayout.units()));
1633
1634 // Setup if Windows custom size, i.e. not a known Windows ID
1635 if (printerPageSize.isValid()) {
1636 has_custom_paper_size = false;
1637 devMode->dmPaperSize = m_pageLayout.pageSize().windowsId();
1638 devMode->dmFields &= ~(DM_PAPERLENGTH | DM_PAPERWIDTH);
1639 devMode->dmPaperWidth = 0;
1640 devMode->dmPaperLength = 0;
1641 } else {
1642 devMode->dmPaperSize = DMPAPER_USER;
1643 devMode->dmFields |= DM_PAPERLENGTH | DM_PAPERWIDTH;
1644 // Size in tenths of a millimeter
1645 const QSizeF sizeMM = m_pageLayout.pageSize().size(QPageSize::Millimeter);
1646 devMode->dmPaperWidth = qRound(sizeMM.width() * 10.0);
1647 devMode->dmPaperLength = qRound(sizeMM.height() * 10.0);
1648 }
1649 updateMetrics();
1650 }
1651
1652 // Update the page layout after any changes made to devMode
updatePageLayout()1653 void QWin32PrintEnginePrivate::updatePageLayout()
1654 {
1655 Q_ASSERT(devMode);
1656
1657 // Update orientation first as is needed to obtain printable margins when changing page size
1658 m_pageLayout.setOrientation(devMode->dmOrientation == DMORIENT_LANDSCAPE ? QPageLayout::Landscape : QPageLayout::Portrait);
1659 if (devMode->dmPaperSize >= DMPAPER_LAST) {
1660 // Is a custom size
1661 // Check if it is using the Postscript Custom Size first
1662 bool hasCustom = false;
1663 int feature = PSIDENT_GDICENTRIC;
1664 if (ExtEscape(hdc, POSTSCRIPT_IDENTIFY,
1665 sizeof(DWORD), reinterpret_cast<LPCSTR>(&feature), 0, 0) >= 0) {
1666 PSFEATURE_CUSTPAPER custPaper;
1667 feature = FEATURESETTING_CUSTPAPER;
1668 if (ExtEscape(hdc, GET_PS_FEATURESETTING, sizeof(INT), reinterpret_cast<LPCSTR>(&feature),
1669 sizeof(custPaper), reinterpret_cast<LPSTR>(&custPaper)) > 0) {
1670 // If orientation is 1 and width/height is 0 then it's not really custom
1671 if (!(custPaper.lOrientation == 1 && custPaper.lWidth == 0 && custPaper.lHeight == 0)) {
1672 if (custPaper.lOrientation == 0 || custPaper.lOrientation == 2)
1673 m_pageLayout.setOrientation(QPageLayout::Portrait);
1674 else
1675 m_pageLayout.setOrientation(QPageLayout::Landscape);
1676 QPageSize pageSize = QPageSize(QSizeF(custPaper.lWidth, custPaper.lHeight),
1677 QPageSize::Point);
1678 setPageSize(pageSize);
1679 hasCustom = true;
1680 }
1681 }
1682 }
1683 if (!hasCustom) {
1684 QPageSize pageSize = QPageSize(QSizeF(devMode->dmPaperWidth / 10.0f, devMode->dmPaperLength / 10.0f),
1685 QPageSize::Millimeter);
1686 setPageSize(pageSize);
1687 }
1688 } else {
1689 // Is a supported size
1690 setPageSize(QPageSize(QPageSize::id(devMode->dmPaperSize)));
1691 }
1692 updateMetrics();
1693 }
1694
1695 // Update the cached page paint metrics whenever page layout is changed
updateMetrics()1696 void QWin32PrintEnginePrivate::updateMetrics()
1697 {
1698 m_paintRectPixels = m_pageLayout.paintRectPixels(resolution);
1699 QSizeF sizeMM = m_pageLayout.paintRect(QPageLayout::Millimeter).size();
1700 m_paintSizeMM = QSize(qRound(sizeMM.width()), qRound(sizeMM.height()));
1701 // Calculate the origin using the physical device pixels, not our paint pixels
1702 // Origin is defined as User Margins - Device Margins
1703 QMarginsF margins = m_pageLayout.margins(QPageLayout::Millimeter) / 25.4;
1704 origin_x = qRound(margins.left() * dpi_x) - GetDeviceCaps(hdc, PHYSICALOFFSETX);
1705 origin_y = qRound(margins.top() * dpi_y) - GetDeviceCaps(hdc, PHYSICALOFFSETY);
1706 }
1707
debugMetrics() const1708 void QWin32PrintEnginePrivate::debugMetrics() const
1709 {
1710 qDebug() << " " << "m_pageLayout = " << m_pageLayout;
1711 qDebug() << " " << "m_paintRectPixels = " << m_paintRectPixels;
1712 qDebug() << " " << "m_paintSizeMM = " << m_paintSizeMM;
1713 qDebug() << " " << "resolution = " << resolution;
1714 qDebug() << " " << "stretch = " << stretch_x << stretch_y;
1715 qDebug() << " " << "origin = " << origin_x << origin_y;
1716 qDebug() << " " << "dpi = " << dpi_x << dpi_y;
1717 qDebug() << "";
1718 }
1719
draw_text_item_win(const QPointF & pos,const QTextItemInt & ti,HDC hdc,const QTransform & xform,const QPointF & topLeft)1720 static void draw_text_item_win(const QPointF &pos, const QTextItemInt &ti, HDC hdc,
1721 const QTransform &xform, const QPointF &topLeft)
1722 {
1723 QPointF baseline_pos = xform.inverted().map(xform.map(pos) - topLeft);
1724
1725 SetTextAlign(hdc, TA_BASELINE);
1726 SetBkMode(hdc, TRANSPARENT);
1727
1728 const bool has_kerning = ti.f && ti.f->kerning();
1729
1730 HFONT hfont = 0;
1731
1732 if (ti.fontEngine->type() == QFontEngine::Win) {
1733 const QVariantMap userData = ti.fontEngine->userData().toMap();
1734 const QVariant hfontV = userData.value(QStringLiteral("hFont"));
1735 const QVariant ttfV = userData.value(QStringLiteral("trueType"));
1736 if (ttfV.toBool() && hfontV.canConvert<HFONT>())
1737 hfont = hfontV.value<HFONT>();
1738 }
1739
1740 if (!hfont)
1741 hfont = (HFONT)GetStockObject(ANSI_VAR_FONT);
1742
1743 HGDIOBJ old_font = SelectObject(hdc, hfont);
1744 unsigned int options = ETO_GLYPH_INDEX;
1745 QGlyphLayout glyphs = ti.glyphs;
1746
1747 bool fast = !has_kerning && !(ti.flags & QTextItem::RightToLeft);
1748 for (int i = 0; fast && i < glyphs.numGlyphs; i++) {
1749 if (glyphs.offsets[i].x != 0 || glyphs.offsets[i].y != 0 || glyphs.justifications[i].space_18d6 != 0
1750 || glyphs.attributes[i].dontPrint) {
1751 fast = false;
1752 break;
1753 }
1754 }
1755
1756 // Scale, rotate and translate here.
1757 XFORM win_xform;
1758 win_xform.eM11 = xform.m11();
1759 win_xform.eM12 = xform.m12();
1760 win_xform.eM21 = xform.m21();
1761 win_xform.eM22 = xform.m22();
1762 win_xform.eDx = xform.dx();
1763 win_xform.eDy = xform.dy();
1764
1765 SetGraphicsMode(hdc, GM_ADVANCED);
1766 SetWorldTransform(hdc, &win_xform);
1767
1768 if (fast) {
1769 // fast path
1770 QVarLengthArray<wchar_t> g(glyphs.numGlyphs);
1771 for (int i = 0; i < glyphs.numGlyphs; ++i)
1772 g[i] = glyphs.glyphs[i];
1773 ExtTextOut(hdc,
1774 qRound(baseline_pos.x() + glyphs.offsets[0].x.toReal()),
1775 qRound(baseline_pos.y() + glyphs.offsets[0].y.toReal()),
1776 options, 0, g.constData(), glyphs.numGlyphs, 0);
1777 } else {
1778 QVarLengthArray<QFixedPoint> positions;
1779 QVarLengthArray<glyph_t> _glyphs;
1780
1781 QTransform matrix = QTransform::fromTranslate(baseline_pos.x(), baseline_pos.y());
1782 ti.fontEngine->getGlyphPositions(ti.glyphs, matrix, ti.flags,
1783 _glyphs, positions);
1784 if (_glyphs.isEmpty()) {
1785 SelectObject(hdc, old_font);
1786 return;
1787 }
1788
1789 options |= ETO_PDY;
1790 QVarLengthArray<INT> glyphDistances(_glyphs.size() * 2);
1791 QVarLengthArray<wchar_t> g(_glyphs.size());
1792 const int lastGlyph = _glyphs.size() - 1;
1793 for (int i = 0; i < lastGlyph; ++i) {
1794 glyphDistances[i * 2] = qRound(positions[i + 1].x) - qRound(positions[i].x);
1795 glyphDistances[i * 2 + 1] = qRound(positions[i + 1].y) - qRound(positions[i].y);
1796 g[i] = _glyphs[i];
1797 }
1798 glyphDistances[lastGlyph * 2] = 0;
1799 glyphDistances[lastGlyph * 2 + 1] = 0;
1800 g[lastGlyph] = _glyphs[lastGlyph];
1801 ExtTextOut(hdc, qRound(positions[0].x), qRound(positions[0].y), options, nullptr,
1802 g.constData(), _glyphs.size(),
1803 glyphDistances.data());
1804 }
1805
1806 win_xform.eM11 = win_xform.eM22 = 1.0;
1807 win_xform.eM12 = win_xform.eM21 = win_xform.eDx = win_xform.eDy = 0.0;
1808 SetWorldTransform(hdc, &win_xform);
1809
1810 SelectObject(hdc, old_font);
1811 }
1812
1813 QT_END_NAMESPACE
1814
1815 #endif // QT_NO_PRINTER
1816