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