1 /****************************************************************************
3 ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
7 ** This file is part of the QtGui module of the Qt Toolkit.
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** GNU Lesser General Public License Usage
11 ** This file may be used under the terms of the GNU Lesser General Public
12 ** License version 2.1 as published by the Free Software Foundation and
13 ** appearing in the file LICENSE.LGPL included in the packaging of this
14 ** file. Please review the following information to ensure the GNU Lesser
15 ** General Public License version 2.1 requirements will be met:
16 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
18 ** In addition, as a special exception, Nokia gives you certain additional
19 ** rights. These rights are described in the Nokia Qt LGPL Exception
20 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
22 ** GNU General Public License Usage
23 ** Alternatively, this file may be used under the terms of the GNU General
24 ** Public License version 3.0 as published by the Free Software Foundation
25 ** and appearing in the file LICENSE.GPL included in the packaging of this
26 ** file. Please review the following information to ensure the GNU General
27 ** Public License version 3.0 requirements will be met:
28 ** http://www.gnu.org/copyleft/gpl.html.
31 ** Alternatively, this file may be used in accordance with the terms and
32 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
43 #include <qpaintdevice.h>
44 #include <private/qpaintengine_mac_p.h>
45 #include <qpainterpath.h>
46 #include <qpixmapcache.h>
47 #include <private/qpaintengine_raster_p.h>
48 #include <private/qprintengine_mac_p.h>
51 #include <qtextcodec.h>
53 #include <qvarlengtharray.h>
55 #include <qcoreapplication.h>
58 #include <private/qfont_p.h>
59 #include <private/qfontengine_p.h>
60 #include <private/qfontengine_coretext_p.h>
61 #include <private/qfontengine_mac_p.h>
62 #include <private/qnumeric_p.h>
63 #include <private/qpainter_p.h>
64 #include <private/qpainterpath_p.h>
65 #include <private/qpixmap_mac_p.h>
66 #include <private/qt_mac_p.h>
67 #include <private/qtextengine_p.h>
68 #include <private/qwidget_p.h>
69 #include <private/qt_cocoa_helpers_mac_p.h>
75 extern int qt_antialiasing_threshold; // QApplication.cpp
77 /*****************************************************************************
79 *****************************************************************************/
80 extern CGImageRef qt_mac_create_imagemask(const QPixmap &px, const QRectF &sr); //qpixmap_mac.cpp
81 extern QPoint qt_mac_posInWindow(const QWidget *w); //qwidget_mac.cpp
82 extern OSWindowRef qt_mac_window_for(const QWidget *); //qwidget_mac.cpp
83 extern CGContextRef qt_mac_cg_context(const QPaintDevice *); //qpaintdevice_mac.cpp
84 extern void qt_mac_dispose_rgn(RgnHandle r); //qregion_mac.cpp
85 extern QPixmap qt_pixmapForBrush(int, bool); //qbrush.cpp
87 void qt_mac_clip_cg(CGContextRef hd, const QRegion &rgn, CGAffineTransform *orig_xform);
90 //Implemented for qt_mac_p.h
91 QMacCGContext::QMacCGContext(QPainter *p)
93 QPaintEngine *pe = p->paintEngine();
94 if (pe->type() == QPaintEngine::MacPrinter)
95 pe = static_cast<QMacPrintEngine*>(pe)->paintEngine();
98 if(pe->type() == QPaintEngine::CoreGraphics)
99 context = static_cast<QCoreGraphicsPaintEngine*>(pe)->handle();
101 int devType = p->device()->devType();
102 if (pe->type() == QPaintEngine::Raster
103 && (devType == QInternal::Widget ||
104 devType == QInternal::Pixmap ||
105 devType == QInternal::Image)) {
107 extern CGColorSpaceRef qt_mac_colorSpaceForDeviceType(const QPaintDevice *paintDevice);
108 CGColorSpaceRef colorspace = qt_mac_colorSpaceForDeviceType(pe->paintDevice());
109 uint flags = kCGImageAlphaPremultipliedFirst;
110 #ifdef kCGBitmapByteOrder32Host //only needed because CGImage.h added symbols in the minor version
111 flags |= kCGBitmapByteOrder32Host;
113 const QImage *image = (const QImage *) pe->paintDevice();
115 context = CGBitmapContextCreate((void *) image->bits(), image->width(), image->height(),
116 8, image->bytesPerLine(), colorspace, flags);
118 CGContextTranslateCTM(context, 0, image->height());
119 CGContextScaleCTM(context, 1, -1);
121 if (devType == QInternal::Widget) {
122 QRegion clip = p->paintEngine()->systemClip();
123 QTransform native = p->deviceTransform();
124 QTransform logical = p->combinedTransform();
126 if (p->hasClipping()) {
127 QRegion r = p->clipRegion();
128 r.translate(native.dx(), native.dy());
134 qt_mac_clip_cg(context, clip, 0);
136 CGContextTranslateCTM(context, native.dx(), native.dy());
139 CGContextRetain(context);
144 /*****************************************************************************
145 QCoreGraphicsPaintEngine utility functions
146 *****************************************************************************/
149 inline static float qt_mac_convert_color_to_cg(int c) { return ((float)c * 1000 / 255) / 1000; }
150 inline static int qt_mac_convert_color_from_cg(float c) { return qRound(c * 255); }
151 CGAffineTransform qt_mac_convert_transform_to_cg(const QTransform &t) {
152 return CGAffineTransformMake(t.m11(), t.m12(), t.m21(), t.m22(), t.dx(), t.dy());
155 CGColorSpaceRef qt_mac_colorSpaceForDeviceType(const QPaintDevice *paintDevice)
157 bool isWidget = (paintDevice->devType() == QInternal::Widget);
158 return QCoreGraphicsPaintEngine::macDisplayColorSpace(isWidget ? static_cast<const QWidget *>(paintDevice)
162 inline static QCFType<CGColorRef> cgColorForQColor(const QColor &col, QPaintDevice *pdev)
164 CGFloat components[] = {
165 qt_mac_convert_color_to_cg(col.red()),
166 qt_mac_convert_color_to_cg(col.green()),
167 qt_mac_convert_color_to_cg(col.blue()),
168 qt_mac_convert_color_to_cg(col.alpha())
170 return CGColorCreate(qt_mac_colorSpaceForDeviceType(pdev), components);
173 // There's architectural problems with using native gradients
174 // on the Mac at the moment, so disable them.
175 // #define QT_MAC_USE_NATIVE_GRADIENTS
177 #ifdef QT_MAC_USE_NATIVE_GRADIENTS
178 static bool drawGradientNatively(const QGradient *gradient)
180 return gradient->spread() == QGradient::PadSpread;
184 static void qt_mac_color_gradient_function(void *info, const CGFloat *in, CGFloat *out)
186 QBrush *brush = static_cast<QBrush *>(info);
187 Q_ASSERT(brush && brush->gradient());
189 const QGradientStops stops = brush->gradient()->stops();
190 const int n = stops.count();
192 const QGradientStop *begin = stops.constBegin();
193 const QGradientStop *end = begin + n;
196 const QGradientStop *i = begin;
197 while (i != end && i->first < p)
202 c = begin->second.rgba();
203 } else if (i == end) {
204 c = (end - 1)->second.rgba();
206 const QGradientStop &s1 = *(i - 1);
207 const QGradientStop &s2 = *i;
210 QRgb c1 = s1.second.rgba();
211 QRgb c2 = s2.second.rgba();
212 int idist = 256 * (p - p1) / (p2 - p1);
213 int dist = 256 - idist;
214 c = qRgba(INTERPOLATE_PIXEL_256(qRed(c1), dist, qRed(c2), idist),
215 INTERPOLATE_PIXEL_256(qGreen(c1), dist, qGreen(c2), idist),
216 INTERPOLATE_PIXEL_256(qBlue(c1), dist, qBlue(c2), idist),
217 INTERPOLATE_PIXEL_256(qAlpha(c1), dist, qAlpha(c2), idist));
220 out[0] = qt_mac_convert_color_to_cg(qRed(c));
221 out[1] = qt_mac_convert_color_to_cg(qGreen(c));
222 out[2] = qt_mac_convert_color_to_cg(qBlue(c));
223 out[3] = qt_mac_convert_color_to_cg(qAlpha(c));
228 void QCoreGraphicsPaintEnginePrivate::resetClip()
230 static bool inReset = false;
235 CGAffineTransform old_xform = CGContextGetCTM(hd);
238 CGContextConcatCTM(hd, CGAffineTransformInvert(old_xform));
239 while (stackCount > 0) {
240 restoreGraphicsState();
245 CGContextConcatCTM(hd, CGAffineTransformInvert(CGContextGetCTM(hd)));
246 CGContextConcatCTM(hd, old_xform);
249 static CGRect qt_mac_compose_rect(const QRectF &r, float off=0)
251 return CGRectMake(r.x()+off, r.y()+off, r.width(), r.height());
254 static CGMutablePathRef qt_mac_compose_path(const QPainterPath &p, float off=0)
256 CGMutablePathRef ret = CGPathCreateMutable();
258 for (int i=0; i<p.elementCount(); ++i) {
259 const QPainterPath::Element &elm = p.elementAt(i);
261 case QPainterPath::MoveToElement:
263 && p.elementAt(i - 1).x == startPt.x()
264 && p.elementAt(i - 1).y == startPt.y())
265 CGPathCloseSubpath(ret);
266 startPt = QPointF(elm.x, elm.y);
267 CGPathMoveToPoint(ret, 0, elm.x+off, elm.y+off);
269 case QPainterPath::LineToElement:
270 CGPathAddLineToPoint(ret, 0, elm.x+off, elm.y+off);
272 case QPainterPath::CurveToElement:
273 Q_ASSERT(p.elementAt(i+1).type == QPainterPath::CurveToDataElement);
274 Q_ASSERT(p.elementAt(i+2).type == QPainterPath::CurveToDataElement);
275 CGPathAddCurveToPoint(ret, 0,
276 elm.x+off, elm.y+off,
277 p.elementAt(i+1).x+off, p.elementAt(i+1).y+off,
278 p.elementAt(i+2).x+off, p.elementAt(i+2).y+off);
282 qFatal("QCoreGraphicsPaintEngine::drawPath(), unhandled type: %d", elm.type);
287 && p.elementAt(p.elementCount() - 1).x == startPt.x()
288 && p.elementAt(p.elementCount() - 1).y == startPt.y())
289 CGPathCloseSubpath(ret);
293 CGColorSpaceRef QCoreGraphicsPaintEngine::m_genericColorSpace = 0;
294 QHash<CGDirectDisplayID, CGColorSpaceRef> QCoreGraphicsPaintEngine::m_displayColorSpaceHash;
295 bool QCoreGraphicsPaintEngine::m_postRoutineRegistered = false;
297 CGColorSpaceRef QCoreGraphicsPaintEngine::macGenericColorSpace()
300 if (!m_genericColorSpace) {
301 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
302 if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_4) {
303 m_genericColorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
307 m_genericColorSpace = CGColorSpaceCreateDeviceRGB();
309 if (!m_postRoutineRegistered) {
310 m_postRoutineRegistered = true;
311 qAddPostRoutine(QCoreGraphicsPaintEngine::cleanUpMacColorSpaces);
314 return m_genericColorSpace;
316 // Just return the main display colorspace for the moment.
317 return macDisplayColorSpace();
322 Ideally, we should pass the widget in here, and use CGGetDisplaysWithRect() etc.
323 to support multiple displays correctly.
325 CGColorSpaceRef QCoreGraphicsPaintEngine::macDisplayColorSpace(const QWidget *widget)
327 CGColorSpaceRef colorSpace;
329 CGDirectDisplayID displayID;
330 CMProfileRef displayProfile = 0;
332 displayID = CGMainDisplayID();
334 const QRect &qrect = widget->window()->geometry();
335 CGRect rect = CGRectMake(qrect.x(), qrect.y(), qrect.width(), qrect.height());
336 CGDisplayCount throwAway;
337 CGDisplayErr dErr = CGGetDisplaysWithRect(rect, 1, &displayID, &throwAway);
338 if (dErr != kCGErrorSuccess)
339 return macDisplayColorSpace(0); // fall back on main display
341 if ((colorSpace = m_displayColorSpaceHash.value(displayID)))
344 CMError err = CMGetProfileByAVID((CMDisplayIDType)displayID, &displayProfile);
346 colorSpace = CGColorSpaceCreateWithPlatformColorSpace(displayProfile);
348 return macDisplayColorSpace(0); // fall back on main display
352 colorSpace = CGColorSpaceCreateDeviceRGB();
354 m_displayColorSpaceHash.insert(displayID, colorSpace);
355 CMCloseProfile(displayProfile);
356 if (!m_postRoutineRegistered) {
357 m_postRoutineRegistered = true;
358 qAddPostRoutine(QCoreGraphicsPaintEngine::cleanUpMacColorSpaces);
363 void QCoreGraphicsPaintEngine::cleanUpMacColorSpaces()
365 if (m_genericColorSpace) {
366 CFRelease(m_genericColorSpace);
367 m_genericColorSpace = 0;
369 QHash<CGDirectDisplayID, CGColorSpaceRef>::const_iterator it = m_displayColorSpaceHash.constBegin();
370 while (it != m_displayColorSpaceHash.constEnd()) {
372 CFRelease(it.value());
375 m_displayColorSpaceHash.clear();
378 void qt_mac_clip_cg(CGContextRef hd, const QRegion &rgn, CGAffineTransform *orig_xform)
380 CGAffineTransform old_xform = CGAffineTransformIdentity;
381 if(orig_xform) { //setup xforms
382 old_xform = CGContextGetCTM(hd);
383 CGContextConcatCTM(hd, CGAffineTransformInvert(old_xform));
384 CGContextConcatCTM(hd, *orig_xform);
388 CGContextBeginPath(hd);
390 CGContextAddRect(hd, CGRectMake(0, 0, 0, 0));
392 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
393 if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5) {
394 QCFType<HIMutableShapeRef> shape = rgn.toHIMutableShape();
395 Q_ASSERT(!HIShapeIsEmpty(shape));
396 HIShapeReplacePathInCGContext(shape, hd);
400 QVector<QRect> rects = rgn.rects();
401 const int count = rects.size();
402 for(int i = 0; i < count; i++) {
403 const QRect &r = rects[i];
404 CGRect mac_r = CGRectMake(r.x(), r.y(), r.width(), r.height());
405 CGContextAddRect(hd, mac_r);
412 if(orig_xform) {//reset xforms
413 CGContextConcatCTM(hd, CGAffineTransformInvert(CGContextGetCTM(hd)));
414 CGContextConcatCTM(hd, old_xform);
419 //pattern handling (tiling)
421 # define QMACPATTERN_MASK_MULTIPLIER 32
423 # define QMACPATTERN_MASK_MULTIPLIER 1
428 QMacPattern() : as_mask(false), pdev(0), image(0) { data.bytes = 0; }
429 ~QMacPattern() { CGImageRelease(image); }
432 return CGImageGetWidth(image);
434 return 8*QMACPATTERN_MASK_MULTIPLIER;
435 return data.pixmap.width();
439 return CGImageGetHeight(image);
441 return 8*QMACPATTERN_MASK_MULTIPLIER;
442 return data.pixmap.height();
456 static void qt_mac_draw_pattern(void *info, CGContextRef c)
458 QMacPattern *pat = (QMacPattern*)info;
460 bool isBitmap = (pat->data.pixmap.depth() == 1);
461 if(!pat->image) { //lazy cache
463 Q_ASSERT(pat->data.bytes);
465 #if (QMACPATTERN_MASK_MULTIPLIER == 1)
466 CGDataProviderRef provider = CGDataProviderCreateWithData(0, pat->data.bytes, w*h, 0);
467 pat->image = CGImageMaskCreate(w, h, 1, 1, 1, provider, 0, false);
468 CGDataProviderRelease(provider);
470 const int numBytes = (w*h)/sizeof(uchar);
471 uchar xor_bytes[numBytes];
472 for(int i = 0; i < numBytes; ++i)
473 xor_bytes[i] = pat->data.bytes[i] ^ 0xFF;
474 CGDataProviderRef provider = CGDataProviderCreateWithData(0, xor_bytes, w*h, 0);
475 CGImageRef swatch = CGImageMaskCreate(w, h, 1, 1, 1, provider, 0, false);
476 CGDataProviderRelease(provider);
478 const QColor c0(0, 0, 0, 0), c1(255, 255, 255, 255);
479 QPixmap pm(w*QMACPATTERN_MASK_MULTIPLIER, h*QMACPATTERN_MASK_MULTIPLIER);
481 CGContextRef pm_ctx = qt_mac_cg_context(&pm);
482 CGContextSetFillColorWithColor(c, cgColorForQColor(c1, pat->pdev));
483 CGRect rect = CGRectMake(0, 0, w, h);
484 for(int x = 0; x < QMACPATTERN_MASK_MULTIPLIER; ++x) {
485 rect.origin.x = x * w;
486 for(int y = 0; y < QMACPATTERN_MASK_MULTIPLIER; ++y) {
487 rect.origin.y = y * h;
488 qt_mac_drawCGImage(pm_ctx, &rect, swatch);
491 pat->image = qt_mac_create_imagemask(pm, pm.rect());
492 CGImageRelease(swatch);
493 CGContextRelease(pm_ctx);
494 w *= QMACPATTERN_MASK_MULTIPLIER;
495 h *= QMACPATTERN_MASK_MULTIPLIER;
498 w = pat->data.pixmap.width();
499 h = pat->data.pixmap.height();
501 pat->image = qt_mac_create_imagemask(pat->data.pixmap, pat->data.pixmap.rect());
503 pat->image = (CGImageRef)pat->data.pixmap.macCGHandle();
506 w = CGImageGetWidth(pat->image);
507 h = CGImageGetHeight(pat->image);
511 bool needRestore = false;
512 if (CGImageIsMask(pat->image)) {
513 CGContextSaveGState(c);
514 CGContextSetFillColorWithColor(c, cgColorForQColor(pat->foreground, pat->pdev));
516 CGRect rect = CGRectMake(0, 0, w, h);
517 qt_mac_drawCGImage(c, &rect, pat->image);
519 CGContextRestoreGState(c);
521 static void qt_mac_dispose_pattern(void *info)
523 QMacPattern *pat = (QMacPattern*)info;
527 /*****************************************************************************
528 QCoreGraphicsPaintEngine member functions
529 *****************************************************************************/
531 inline static QPaintEngine::PaintEngineFeatures qt_mac_cg_features()
533 return QPaintEngine::PaintEngineFeatures(QPaintEngine::AllFeatures & ~QPaintEngine::PaintOutsidePaintEvent
534 & ~QPaintEngine::PerspectiveTransform
535 & ~QPaintEngine::ConicalGradientFill
536 & ~QPaintEngine::LinearGradientFill
537 & ~QPaintEngine::RadialGradientFill
538 & ~QPaintEngine::BrushStroke);
541 QCoreGraphicsPaintEngine::QCoreGraphicsPaintEngine()
542 : QPaintEngine(*(new QCoreGraphicsPaintEnginePrivate), qt_mac_cg_features())
546 QCoreGraphicsPaintEngine::QCoreGraphicsPaintEngine(QPaintEnginePrivate &dptr)
547 : QPaintEngine(dptr, qt_mac_cg_features())
551 QCoreGraphicsPaintEngine::~QCoreGraphicsPaintEngine()
556 QCoreGraphicsPaintEngine::begin(QPaintDevice *pdev)
558 Q_D(QCoreGraphicsPaintEngine);
559 if(isActive()) { // already active painting
560 qWarning("QCoreGraphicsPaintEngine::begin: Painter already active");
566 d->complexXForm = false;
567 d->cosmeticPen = QCoreGraphicsPaintEnginePrivate::CosmeticSetPenWidth;
568 d->cosmeticPenSize = 1;
569 d->current.clipEnabled = false;
570 d->pixelSize = QPoint(1,1);
571 d->hd = qt_mac_cg_context(pdev);
573 d->saveGraphicsState();
574 d->orig_xform = CGContextGetCTM(d->hd);
576 CGShadingRelease(d->shading);
579 d->setClip(0); //clear the context's clipping
584 if(d->pdev->devType() == QInternal::Widget) { // device is a widget
585 QWidget *w = (QWidget*)d->pdev;
586 bool unclipped = w->testAttribute(Qt::WA_PaintUnclipped);
588 if((w->windowType() == Qt::Desktop)) {
590 qWarning("QCoreGraphicsPaintEngine::begin: Does not support clipped desktop on Mac OS X");
591 // ## need to do [qt_mac_window_for(w) makeKeyAndOrderFront]; (need to rename the file)
592 } else if(unclipped) {
593 qWarning("QCoreGraphicsPaintEngine::begin: Does not support unclipped painting");
595 } else if(d->pdev->devType() == QInternal::Pixmap) { // device is a pixmap
596 QPixmap *pm = (QPixmap*)d->pdev;
598 qWarning("QCoreGraphicsPaintEngine::begin: Cannot paint null pixmap");
604 setDirty(QPaintEngine::DirtyPen);
605 setDirty(QPaintEngine::DirtyBrush);
606 setDirty(QPaintEngine::DirtyBackground);
607 setDirty(QPaintEngine::DirtyHints);
612 QCoreGraphicsPaintEngine::end()
614 Q_D(QCoreGraphicsPaintEngine);
616 if(d->pdev->devType() == QInternal::Widget && static_cast<QWidget*>(d->pdev)->windowType() == Qt::Desktop) {
617 #ifndef QT_MAC_USE_COCOA
618 HideWindow(qt_mac_window_for(static_cast<QWidget*>(d->pdev)));
620 // // ### need to do [qt_mac_window_for(static_cast<QWidget *>(d->pdev)) orderOut]; (need to rename)
625 CGShadingRelease(d->shading);
630 d->restoreGraphicsState();
631 CGContextSynchronize(d->hd);
632 CGContextRelease(d->hd);
639 QCoreGraphicsPaintEngine::updateState(const QPaintEngineState &state)
641 Q_D(QCoreGraphicsPaintEngine);
642 QPaintEngine::DirtyFlags flags = state.state();
644 if (flags & DirtyTransform)
645 updateMatrix(state.transform());
647 if (flags & DirtyClipEnabled) {
648 if (state.isClipEnabled())
649 updateClipPath(painter()->clipPath(), Qt::ReplaceClip);
651 updateClipPath(QPainterPath(), Qt::NoClip);
654 if (flags & DirtyClipPath) {
655 updateClipPath(state.clipPath(), state.clipOperation());
656 } else if (flags & DirtyClipRegion) {
657 updateClipRegion(state.clipRegion(), state.clipOperation());
660 // If the clip has changed we need to update all other states
661 // too, since they are included in the system context on OSX,
662 // and changing the clip resets that context back to scratch.
663 if (flags & (DirtyClipPath | DirtyClipRegion | DirtyClipEnabled))
666 if (flags & DirtyPen)
667 updatePen(state.pen());
668 if (flags & (DirtyBrush|DirtyBrushOrigin))
669 updateBrush(state.brush(), state.brushOrigin());
670 if (flags & DirtyFont)
671 updateFont(state.font());
672 if (flags & DirtyOpacity)
673 updateOpacity(state.opacity());
674 if (flags & DirtyHints)
675 updateRenderHints(state.renderHints());
676 if (flags & DirtyCompositionMode)
677 updateCompositionMode(state.compositionMode());
679 if (flags & (DirtyPen | DirtyTransform)) {
680 if (!d->current.pen.isCosmetic()) {
681 d->cosmeticPen = QCoreGraphicsPaintEnginePrivate::CosmeticNone;
682 } else if (d->current.transform.m11() < d->current.transform.m22()-1.0 ||
683 d->current.transform.m11() > d->current.transform.m22()+1.0) {
684 d->cosmeticPen = QCoreGraphicsPaintEnginePrivate::CosmeticTransformPath;
685 d->cosmeticPenSize = d->adjustPenWidth(d->current.pen.widthF());
686 if (!d->cosmeticPenSize)
687 d->cosmeticPenSize = 1.0;
689 d->cosmeticPen = QCoreGraphicsPaintEnginePrivate::CosmeticSetPenWidth;
690 static const float sqrt2 = sqrt(2);
691 qreal width = d->current.pen.widthF();
694 d->cosmeticPenSize = sqrt(pow(d->pixelSize.y(), 2) + pow(d->pixelSize.x(), 2)) / sqrt2 * width;
700 QCoreGraphicsPaintEngine::updatePen(const QPen &pen)
702 Q_D(QCoreGraphicsPaintEngine);
703 Q_ASSERT(isActive());
704 d->current.pen = pen;
705 d->setStrokePen(pen);
709 QCoreGraphicsPaintEngine::updateBrush(const QBrush &brush, const QPointF &brushOrigin)
711 Q_D(QCoreGraphicsPaintEngine);
712 Q_ASSERT(isActive());
713 d->current.brush = brush;
715 #ifdef QT_MAC_USE_NATIVE_GRADIENTS
716 // Quartz supports only pad spread
717 if (const QGradient *gradient = brush.gradient()) {
718 if (drawGradientNatively(gradient)) {
719 gccaps |= QPaintEngine::LinearGradientFill | QPaintEngine::RadialGradientFill;
721 gccaps &= ~(QPaintEngine::LinearGradientFill | QPaintEngine::RadialGradientFill);
727 CGShadingRelease(d->shading);
730 d->setFillBrush(brushOrigin);
734 QCoreGraphicsPaintEngine::updateOpacity(qreal opacity)
736 Q_D(QCoreGraphicsPaintEngine);
737 CGContextSetAlpha(d->hd, opacity);
741 QCoreGraphicsPaintEngine::updateFont(const QFont &)
743 Q_D(QCoreGraphicsPaintEngine);
744 Q_ASSERT(isActive());
745 updatePen(d->current.pen);
749 QCoreGraphicsPaintEngine::updateMatrix(const QTransform &transform)
751 Q_D(QCoreGraphicsPaintEngine);
752 Q_ASSERT(isActive());
754 if (qt_is_nan(transform.m11()) || qt_is_nan(transform.m12()) || qt_is_nan(transform.m13())
755 || qt_is_nan(transform.m21()) || qt_is_nan(transform.m22()) || qt_is_nan(transform.m23())
756 || qt_is_nan(transform.m31()) || qt_is_nan(transform.m32()) || qt_is_nan(transform.m33()))
759 d->current.transform = transform;
760 d->setTransform(transform.isIdentity() ? 0 : &transform);
761 d->complexXForm = (transform.m11() != 1 || transform.m22() != 1
762 || transform.m12() != 0 || transform.m21() != 0);
763 d->pixelSize = d->devicePixelSize(d->hd);
767 QCoreGraphicsPaintEngine::updateClipPath(const QPainterPath &p, Qt::ClipOperation op)
769 Q_D(QCoreGraphicsPaintEngine);
770 Q_ASSERT(isActive());
771 if(op == Qt::NoClip) {
772 if(d->current.clipEnabled) {
773 d->current.clipEnabled = false;
774 d->current.clip = QRegion();
778 if(!d->current.clipEnabled)
779 op = Qt::ReplaceClip;
780 d->current.clipEnabled = true;
781 QRegion clipRegion(p.toFillPolygon().toPolygon(), p.fillRule());
782 if(op == Qt::ReplaceClip) {
783 d->current.clip = clipRegion;
786 CGRect rect = CGRectMake(0, 0, 0, 0);
787 CGContextClipToRect(d->hd, rect);
789 CGMutablePathRef path = qt_mac_compose_path(p);
790 CGContextBeginPath(d->hd);
791 CGContextAddPath(d->hd, path);
792 if(p.fillRule() == Qt::WindingFill)
793 CGContextClip(d->hd);
795 CGContextEOClip(d->hd);
798 } else if(op == Qt::IntersectClip) {
799 d->current.clip = d->current.clip.intersected(clipRegion);
800 d->setClip(&d->current.clip);
806 QCoreGraphicsPaintEngine::updateClipRegion(const QRegion &clipRegion, Qt::ClipOperation op)
808 Q_D(QCoreGraphicsPaintEngine);
809 Q_ASSERT(isActive());
810 if(op == Qt::NoClip) {
811 d->current.clipEnabled = false;
812 d->current.clip = QRegion();
815 if(!d->current.clipEnabled)
816 op = Qt::ReplaceClip;
817 d->current.clipEnabled = true;
818 if(op == Qt::IntersectClip)
819 d->current.clip = d->current.clip.intersected(clipRegion);
820 else if(op == Qt::ReplaceClip)
821 d->current.clip = clipRegion;
822 d->setClip(&d->current.clip);
827 QCoreGraphicsPaintEngine::drawPath(const QPainterPath &p)
829 Q_D(QCoreGraphicsPaintEngine);
830 Q_ASSERT(isActive());
832 if (state->compositionMode() == QPainter::CompositionMode_Destination)
835 CGMutablePathRef path = qt_mac_compose_path(p);
836 uchar ops = QCoreGraphicsPaintEnginePrivate::CGStroke;
837 if(p.fillRule() == Qt::WindingFill)
838 ops |= QCoreGraphicsPaintEnginePrivate::CGFill;
840 ops |= QCoreGraphicsPaintEnginePrivate::CGEOFill;
841 CGContextBeginPath(d->hd);
842 d->drawPath(ops, path);
847 QCoreGraphicsPaintEngine::drawRects(const QRectF *rects, int rectCount)
849 Q_D(QCoreGraphicsPaintEngine);
850 Q_ASSERT(isActive());
852 if (state->compositionMode() == QPainter::CompositionMode_Destination)
855 for (int i=0; i<rectCount; ++i) {
858 CGMutablePathRef path = CGPathCreateMutable();
859 CGPathAddRect(path, 0, qt_mac_compose_rect(r));
860 d->drawPath(QCoreGraphicsPaintEnginePrivate::CGFill|QCoreGraphicsPaintEnginePrivate::CGStroke,
867 QCoreGraphicsPaintEngine::drawPoints(const QPointF *points, int pointCount)
869 Q_D(QCoreGraphicsPaintEngine);
870 Q_ASSERT(isActive());
872 if (state->compositionMode() == QPainter::CompositionMode_Destination)
875 if (d->current.pen.capStyle() == Qt::FlatCap)
876 CGContextSetLineCap(d->hd, kCGLineCapSquare);
878 CGMutablePathRef path = CGPathCreateMutable();
879 for(int i=0; i < pointCount; i++) {
880 float x = points[i].x(), y = points[i].y();
881 CGPathMoveToPoint(path, 0, x, y);
882 CGPathAddLineToPoint(path, 0, x+0.001, y);
885 bool doRestore = false;
886 if(d->cosmeticPen == QCoreGraphicsPaintEnginePrivate::CosmeticNone && !(state->renderHints() & QPainter::Antialiasing)) {
887 //we don't want adjusted pens for point rendering
889 d->saveGraphicsState();
890 CGContextSetLineWidth(d->hd, d->current.pen.widthF());
892 d->drawPath(QCoreGraphicsPaintEnginePrivate::CGStroke, path);
894 d->restoreGraphicsState();
896 if (d->current.pen.capStyle() == Qt::FlatCap)
897 CGContextSetLineCap(d->hd, kCGLineCapButt);
901 QCoreGraphicsPaintEngine::drawEllipse(const QRectF &r)
903 Q_D(QCoreGraphicsPaintEngine);
904 Q_ASSERT(isActive());
906 if (state->compositionMode() == QPainter::CompositionMode_Destination)
909 CGMutablePathRef path = CGPathCreateMutable();
910 CGAffineTransform transform = CGAffineTransformMakeScale(r.width() / r.height(), 1);
911 CGPathAddArc(path, &transform,(r.x() + (r.width() / 2)) / (r.width() / r.height()),
912 r.y() + (r.height() / 2), r.height() / 2, 0, (2 * M_PI), false);
913 d->drawPath(QCoreGraphicsPaintEnginePrivate::CGFill | QCoreGraphicsPaintEnginePrivate::CGStroke,
919 QCoreGraphicsPaintEngine::drawPolygon(const QPointF *points, int pointCount, PolygonDrawMode mode)
921 Q_D(QCoreGraphicsPaintEngine);
922 Q_ASSERT(isActive());
924 if (state->compositionMode() == QPainter::CompositionMode_Destination)
927 CGMutablePathRef path = CGPathCreateMutable();
928 CGPathMoveToPoint(path, 0, points[0].x(), points[0].y());
929 for(int x = 1; x < pointCount; ++x)
930 CGPathAddLineToPoint(path, 0, points[x].x(), points[x].y());
931 if(mode != PolylineMode && points[0] != points[pointCount-1])
932 CGPathAddLineToPoint(path, 0, points[0].x(), points[0].y());
933 uint op = QCoreGraphicsPaintEnginePrivate::CGStroke;
934 if (mode != PolylineMode)
935 op |= mode == OddEvenMode ? QCoreGraphicsPaintEnginePrivate::CGEOFill
936 : QCoreGraphicsPaintEnginePrivate::CGFill;
937 d->drawPath(op, path);
942 QCoreGraphicsPaintEngine::drawLines(const QLineF *lines, int lineCount)
944 Q_D(QCoreGraphicsPaintEngine);
945 Q_ASSERT(isActive());
947 if (state->compositionMode() == QPainter::CompositionMode_Destination)
950 CGMutablePathRef path = CGPathCreateMutable();
951 for(int i = 0; i < lineCount; i++) {
952 const QPointF start = lines[i].p1(), end = lines[i].p2();
953 CGPathMoveToPoint(path, 0, start.x(), start.y());
954 CGPathAddLineToPoint(path, 0, end.x(), end.y());
956 d->drawPath(QCoreGraphicsPaintEnginePrivate::CGStroke, path);
960 void QCoreGraphicsPaintEngine::drawPixmap(const QRectF &r, const QPixmap &pm, const QRectF &sr)
962 Q_D(QCoreGraphicsPaintEngine);
963 Q_ASSERT(isActive());
965 if (state->compositionMode() == QPainter::CompositionMode_Destination)
971 bool differentSize = (QRectF(0, 0, pm.width(), pm.height()) != sr), doRestore = false;
972 CGRect rect = CGRectMake(r.x(), r.y(), r.width(), r.height());
973 QCFType<CGImageRef> image;
974 bool isBitmap = (pm.depth() == 1);
977 d->saveGraphicsState();
979 const QColor &col = d->current.pen.color();
980 CGContextSetFillColorWithColor(d->hd, cgColorForQColor(col, d->pdev));
981 image = qt_mac_create_imagemask(pm, sr);
982 } else if (differentSize) {
983 QCFType<CGImageRef> img = pm.toMacCGImageRef();
984 image = CGImageCreateWithImageInRect(img, CGRectMake(qRound(sr.x()), qRound(sr.y()), qRound(sr.width()), qRound(sr.height())));
986 image = (CGImageRef)pm.macCGHandle();
988 qt_mac_drawCGImage(d->hd, &rect, image);
990 d->restoreGraphicsState();
993 static void drawImageReleaseData (void *info, const void *, size_t)
995 delete static_cast<QImage *>(info);
998 CGImageRef qt_mac_createCGImageFromQImage(const QImage &img, const QImage **imagePtr = 0)
1001 if (img.depth() != 32)
1002 image = new QImage(img.convertToFormat(QImage::Format_ARGB32_Premultiplied));
1004 image = new QImage(img);
1006 uint cgflags = kCGImageAlphaNone;
1007 switch (image->format()) {
1008 case QImage::Format_ARGB32_Premultiplied:
1009 cgflags = kCGImageAlphaPremultipliedFirst;
1011 case QImage::Format_ARGB32:
1012 cgflags = kCGImageAlphaFirst;
1014 case QImage::Format_RGB32:
1015 cgflags = kCGImageAlphaNoneSkipFirst;
1019 #if defined(kCGBitmapByteOrder32Host) //only needed because CGImage.h added symbols in the minor version
1020 cgflags |= kCGBitmapByteOrder32Host;
1022 QCFType<CGDataProviderRef> dataProvider = CGDataProviderCreateWithData(image,
1023 static_cast<const QImage *>(image)->bits(),
1025 drawImageReleaseData);
1028 return CGImageCreate(image->width(), image->height(), 8, 32,
1029 image->bytesPerLine(),
1030 QCoreGraphicsPaintEngine::macGenericColorSpace(),
1031 cgflags, dataProvider, 0, false, kCGRenderingIntentDefault);
1035 void QCoreGraphicsPaintEngine::drawImage(const QRectF &r, const QImage &img, const QRectF &sr,
1036 Qt::ImageConversionFlags flags)
1038 Q_D(QCoreGraphicsPaintEngine);
1040 Q_ASSERT(isActive());
1042 if (img.isNull() || state->compositionMode() == QPainter::CompositionMode_Destination)
1045 const QImage *image;
1046 QCFType<CGImageRef> cgimage = qt_mac_createCGImageFromQImage(img, &image);
1047 CGRect rect = CGRectMake(r.x(), r.y(), r.width(), r.height());
1048 if (QRectF(0, 0, img.width(), img.height()) != sr)
1049 cgimage = CGImageCreateWithImageInRect(cgimage, CGRectMake(sr.x(), sr.y(),
1050 sr.width(), sr.height()));
1051 qt_mac_drawCGImage(d->hd, &rect, cgimage);
1054 void QCoreGraphicsPaintEngine::initialize()
1058 void QCoreGraphicsPaintEngine::cleanup()
1063 QCoreGraphicsPaintEngine::handle() const
1065 return d_func()->hd;
1069 QCoreGraphicsPaintEngine::drawTiledPixmap(const QRectF &r, const QPixmap &pixmap,
1072 Q_D(QCoreGraphicsPaintEngine);
1073 Q_ASSERT(isActive());
1075 if (state->compositionMode() == QPainter::CompositionMode_Destination)
1078 //save the old state
1079 d->saveGraphicsState();
1082 QMacPattern *qpattern = new QMacPattern;
1083 qpattern->data.pixmap = pixmap;
1084 qpattern->foreground = d->current.pen.color();
1085 qpattern->pdev = d->pdev;
1086 CGPatternCallbacks callbks;
1087 callbks.version = 0;
1088 callbks.drawPattern = qt_mac_draw_pattern;
1089 callbks.releaseInfo = qt_mac_dispose_pattern;
1090 const int width = qpattern->width(), height = qpattern->height();
1091 CGAffineTransform trans = CGContextGetCTM(d->hd);
1092 CGPatternRef pat = CGPatternCreate(qpattern, CGRectMake(0, 0, width, height),
1093 trans, width, height,
1094 kCGPatternTilingNoDistortion, true, &callbks);
1095 CGColorSpaceRef cs = CGColorSpaceCreatePattern(0);
1096 CGContextSetFillColorSpace(d->hd, cs);
1097 CGFloat component = 1.0; //just one
1098 CGContextSetFillPattern(d->hd, pat, &component);
1099 CGSize phase = CGSizeApplyAffineTransform(CGSizeMake(-(p.x()-r.x()), -(p.y()-r.y())), trans);
1100 CGContextSetPatternPhase(d->hd, phase);
1102 //fill the rectangle
1103 CGRect mac_rect = CGRectMake(r.x(), r.y(), r.width(), r.height());
1104 CGContextFillRect(d->hd, mac_rect);
1107 d->restoreGraphicsState();
1109 CGColorSpaceRelease(cs);
1110 CGPatternRelease(pat);
1113 void QCoreGraphicsPaintEngine::drawTextItem(const QPointF &pos, const QTextItem &item)
1115 Q_D(QCoreGraphicsPaintEngine);
1116 if (d->current.transform.type() == QTransform::TxProject
1117 #ifndef QMAC_NATIVE_GRADIENTS
1118 || painter()->pen().brush().gradient() //Just let the base engine "emulate" the gradient
1121 QPaintEngine::drawTextItem(pos, item);
1125 if (state->compositionMode() == QPainter::CompositionMode_Destination)
1128 const QTextItemInt &ti = static_cast<const QTextItemInt &>(item);
1130 QPen oldPen = painter()->pen();
1131 QBrush oldBrush = painter()->brush();
1132 QPointF oldBrushOrigin = painter()->brushOrigin();
1133 updatePen(Qt::NoPen);
1134 updateBrush(oldPen.brush(), QPointF(0, 0));
1136 Q_ASSERT(type() == QPaintEngine::CoreGraphics);
1138 QFontEngine *fe = ti.fontEngine;
1140 const bool textAA = state->renderHints() & QPainter::TextAntialiasing && fe->fontDef.pointSize > qt_antialiasing_threshold && !(fe->fontDef.styleStrategy & QFont::NoAntialias);
1141 const bool lineAA = state->renderHints() & QPainter::Antialiasing;
1142 if(textAA != lineAA)
1143 CGContextSetShouldAntialias(d->hd, textAA);
1145 if (ti.glyphs.numGlyphs) {
1146 switch (fe->type()) {
1147 case QFontEngine::Mac:
1148 #ifdef QT_MAC_USE_COCOA
1149 static_cast<QCoreTextFontEngine *>(fe)->draw(d->hd, pos.x(), pos.y(), ti, paintDevice()->height());
1151 static_cast<QFontEngineMac *>(fe)->draw(d->hd, pos.x(), pos.y(), ti, paintDevice()->height());
1154 case QFontEngine::Box:
1155 d->drawBoxTextItem(pos, ti);
1162 if(textAA != lineAA)
1163 CGContextSetShouldAntialias(d->hd, !textAA);
1166 updateBrush(oldBrush, oldBrushOrigin);
1169 QPainter::RenderHints
1170 QCoreGraphicsPaintEngine::supportedRenderHints() const
1172 return QPainter::RenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform);
1174 enum CGCompositeMode {
1175 kCGCompositeModeClear = 0,
1176 kCGCompositeModeCopy = 1,
1177 kCGCompositeModeSourceOver = 2,
1178 kCGCompositeModeSourceIn = 3,
1179 kCGCompositeModeSourceOut = 4,
1180 kCGCompositeModeSourceAtop = 5,
1181 kCGCompositeModeDestinationOver = 6,
1182 kCGCompositeModeDestinationIn = 7,
1183 kCGCompositeModeDestinationOut = 8,
1184 kCGCompositeModeDestinationAtop = 9,
1185 kCGCompositeModeXOR = 10,
1186 kCGCompositeModePlusDarker = 11, // (max (0, (1-d) + (1-s)))
1187 kCGCompositeModePlusLighter = 12, // (min (1, s + d))
1190 extern void CGContextSetCompositeOperation(CGContextRef, int);
1191 } // private function, but is in all versions of OS X.
1193 QCoreGraphicsPaintEngine::updateCompositionMode(QPainter::CompositionMode mode)
1195 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
1196 if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5) {
1197 int cg_mode = kCGBlendModeNormal;
1199 case QPainter::CompositionMode_Multiply:
1200 cg_mode = kCGBlendModeMultiply;
1202 case QPainter::CompositionMode_Screen:
1203 cg_mode = kCGBlendModeScreen;
1205 case QPainter::CompositionMode_Overlay:
1206 cg_mode = kCGBlendModeOverlay;
1208 case QPainter::CompositionMode_Darken:
1209 cg_mode = kCGBlendModeDarken;
1211 case QPainter::CompositionMode_Lighten:
1212 cg_mode = kCGBlendModeLighten;
1214 case QPainter::CompositionMode_ColorDodge:
1215 cg_mode = kCGBlendModeColorDodge;
1217 case QPainter::CompositionMode_ColorBurn:
1218 cg_mode = kCGBlendModeColorBurn;
1220 case QPainter::CompositionMode_HardLight:
1221 cg_mode = kCGBlendModeHardLight;
1223 case QPainter::CompositionMode_SoftLight:
1224 cg_mode = kCGBlendModeSoftLight;
1226 case QPainter::CompositionMode_Difference:
1227 cg_mode = kCGBlendModeDifference;
1229 case QPainter::CompositionMode_Exclusion:
1230 cg_mode = kCGBlendModeExclusion;
1232 case QPainter::CompositionMode_Plus:
1233 cg_mode = kCGBlendModePlusLighter;
1235 case QPainter::CompositionMode_SourceOver:
1236 cg_mode = kCGBlendModeNormal;
1238 case QPainter::CompositionMode_DestinationOver:
1239 cg_mode = kCGBlendModeDestinationOver;
1241 case QPainter::CompositionMode_Clear:
1242 cg_mode = kCGBlendModeClear;
1244 case QPainter::CompositionMode_Source:
1245 cg_mode = kCGBlendModeCopy;
1247 case QPainter::CompositionMode_Destination:
1250 case QPainter::CompositionMode_SourceIn:
1251 cg_mode = kCGBlendModeSourceIn;
1253 case QPainter::CompositionMode_DestinationIn:
1254 cg_mode = kCGCompositeModeDestinationIn;
1256 case QPainter::CompositionMode_SourceOut:
1257 cg_mode = kCGBlendModeSourceOut;
1259 case QPainter::CompositionMode_DestinationOut:
1260 cg_mode = kCGBlendModeDestinationOver;
1262 case QPainter::CompositionMode_SourceAtop:
1263 cg_mode = kCGBlendModeSourceAtop;
1265 case QPainter::CompositionMode_DestinationAtop:
1266 cg_mode = kCGBlendModeDestinationAtop;
1268 case QPainter::CompositionMode_Xor:
1269 cg_mode = kCGBlendModeXOR;
1275 CGContextSetBlendMode(d_func()->hd, CGBlendMode(cg_mode));
1279 // The standard porter duff ops.
1280 if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_3
1281 && mode <= QPainter::CompositionMode_Xor) {
1282 int cg_mode = kCGCompositeModeCopy;
1284 case QPainter::CompositionMode_SourceOver:
1285 cg_mode = kCGCompositeModeSourceOver;
1287 case QPainter::CompositionMode_DestinationOver:
1288 cg_mode = kCGCompositeModeDestinationOver;
1290 case QPainter::CompositionMode_Clear:
1291 cg_mode = kCGCompositeModeClear;
1294 qWarning("QCoreGraphicsPaintEngine: Unhandled composition mode %d", (int)mode);
1296 case QPainter::CompositionMode_Source:
1297 cg_mode = kCGCompositeModeCopy;
1299 case QPainter::CompositionMode_Destination:
1300 cg_mode = CGCompositeMode(-1);
1302 case QPainter::CompositionMode_SourceIn:
1303 cg_mode = kCGCompositeModeSourceIn;
1305 case QPainter::CompositionMode_DestinationIn:
1306 cg_mode = kCGCompositeModeDestinationIn;
1308 case QPainter::CompositionMode_SourceOut:
1309 cg_mode = kCGCompositeModeSourceOut;
1311 case QPainter::CompositionMode_DestinationOut:
1312 cg_mode = kCGCompositeModeDestinationOut;
1314 case QPainter::CompositionMode_SourceAtop:
1315 cg_mode = kCGCompositeModeSourceAtop;
1317 case QPainter::CompositionMode_DestinationAtop:
1318 cg_mode = kCGCompositeModeDestinationAtop;
1320 case QPainter::CompositionMode_Xor:
1321 cg_mode = kCGCompositeModeXOR;
1325 CGContextSetCompositeOperation(d_func()->hd, CGCompositeMode(cg_mode));
1327 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4)
1328 bool needPrivateAPI = false;
1329 if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_4) {
1330 int cg_mode = kCGBlendModeNormal;
1332 case QPainter::CompositionMode_Multiply:
1333 cg_mode = kCGBlendModeMultiply;
1335 case QPainter::CompositionMode_Screen:
1336 cg_mode = kCGBlendModeScreen;
1338 case QPainter::CompositionMode_Overlay:
1339 cg_mode = kCGBlendModeOverlay;
1341 case QPainter::CompositionMode_Darken:
1342 cg_mode = kCGBlendModeDarken;
1344 case QPainter::CompositionMode_Lighten:
1345 cg_mode = kCGBlendModeLighten;
1347 case QPainter::CompositionMode_ColorDodge:
1348 cg_mode = kCGBlendModeColorDodge;
1350 case QPainter::CompositionMode_ColorBurn:
1351 cg_mode = kCGBlendModeColorBurn;
1353 case QPainter::CompositionMode_HardLight:
1354 cg_mode = kCGBlendModeHardLight;
1356 case QPainter::CompositionMode_SoftLight:
1357 cg_mode = kCGBlendModeSoftLight;
1359 case QPainter::CompositionMode_Difference:
1360 cg_mode = kCGBlendModeDifference;
1362 case QPainter::CompositionMode_Exclusion:
1363 cg_mode = kCGBlendModeExclusion;
1365 case QPainter::CompositionMode_Plus:
1366 needPrivateAPI = true;
1367 cg_mode = kCGCompositeModePlusLighter;
1372 if (!needPrivateAPI)
1373 CGContextSetBlendMode(d_func()->hd, CGBlendMode(cg_mode));
1375 CGContextSetCompositeOperation(d_func()->hd, CGCompositeMode(cg_mode));
1382 QCoreGraphicsPaintEngine::updateRenderHints(QPainter::RenderHints hints)
1384 Q_D(QCoreGraphicsPaintEngine);
1385 CGContextSetShouldAntialias(d->hd, hints & QPainter::Antialiasing);
1386 static const CGFloat ScaleFactor = qt_mac_get_scalefactor();
1387 if (ScaleFactor > 1.) {
1388 CGContextSetInterpolationQuality(d->hd, kCGInterpolationHigh);
1390 CGContextSetInterpolationQuality(d->hd, (hints & QPainter::SmoothPixmapTransform) ?
1391 kCGInterpolationHigh : kCGInterpolationNone);
1393 bool textAntialiasing = (hints & QPainter::TextAntialiasing) == QPainter::TextAntialiasing;
1394 if (!textAntialiasing || d->disabledSmoothFonts) {
1395 d->disabledSmoothFonts = !textAntialiasing;
1396 CGContextSetShouldSmoothFonts(d->hd, textAntialiasing);
1401 Returns the size of one device pixel in user-space coordinates.
1403 QPointF QCoreGraphicsPaintEnginePrivate::devicePixelSize(CGContextRef)
1405 QPointF p1 = current.transform.inverted().map(QPointF(0, 0));
1406 QPointF p2 = current.transform.inverted().map(QPointF(1, 1));
1407 return QPointF(qAbs(p2.x() - p1.x()), qAbs(p2.y() - p1.y()));
1411 Adjusts the pen width so we get correct line widths in the
1412 non-transformed, aliased case.
1414 float QCoreGraphicsPaintEnginePrivate::adjustPenWidth(float penWidth)
1416 Q_Q(QCoreGraphicsPaintEngine);
1417 float ret = penWidth;
1418 if (!complexXForm && !(q->state->renderHints() & QPainter::Antialiasing)) {
1421 else if (penWidth < 3)
1430 QCoreGraphicsPaintEnginePrivate::setStrokePen(const QPen &pen)
1433 CGLineCap cglinecap = kCGLineCapButt;
1434 if(pen.capStyle() == Qt::SquareCap)
1435 cglinecap = kCGLineCapSquare;
1436 else if(pen.capStyle() == Qt::RoundCap)
1437 cglinecap = kCGLineCapRound;
1438 CGContextSetLineCap(hd, cglinecap);
1439 CGContextSetLineWidth(hd, adjustPenWidth(pen.widthF()));
1442 CGLineJoin cglinejoin = kCGLineJoinMiter;
1443 if(pen.joinStyle() == Qt::BevelJoin)
1444 cglinejoin = kCGLineJoinBevel;
1445 else if(pen.joinStyle() == Qt::RoundJoin)
1446 cglinejoin = kCGLineJoinRound;
1447 CGContextSetLineJoin(hd, cglinejoin);
1448 // CGContextSetMiterLimit(hd, pen.miterLimit());
1451 QVector<CGFloat> linedashes;
1452 if(pen.style() == Qt::CustomDashLine) {
1453 QVector<qreal> customs = pen.dashPattern();
1454 for(int i = 0; i < customs.size(); ++i)
1455 linedashes.append(customs.at(i));
1456 } else if(pen.style() == Qt::DashLine) {
1457 linedashes.append(4);
1458 linedashes.append(2);
1459 } else if(pen.style() == Qt::DotLine) {
1460 linedashes.append(1);
1461 linedashes.append(2);
1462 } else if(pen.style() == Qt::DashDotLine) {
1463 linedashes.append(4);
1464 linedashes.append(2);
1465 linedashes.append(1);
1466 linedashes.append(2);
1467 } else if(pen.style() == Qt::DashDotDotLine) {
1468 linedashes.append(4);
1469 linedashes.append(2);
1470 linedashes.append(1);
1471 linedashes.append(2);
1472 linedashes.append(1);
1473 linedashes.append(2);
1475 const CGFloat cglinewidth = pen.widthF() <= 0.0f ? 1.0f : float(pen.widthF());
1476 for(int i = 0; i < linedashes.size(); ++i) {
1477 linedashes[i] *= cglinewidth;
1478 if(cglinewidth < 3 && (cglinecap == kCGLineCapSquare || cglinecap == kCGLineCapRound)) {
1480 linedashes[i] += cglinewidth/2;
1482 linedashes[i] -= cglinewidth/2;
1485 CGContextSetLineDash(hd, pen.dashOffset() * cglinewidth, linedashes.data(), linedashes.size());
1488 CGContextSetStrokeColorWithColor(hd, cgColorForQColor(pen.color(), pdev));
1491 // Add our own patterns here to deal with the fact that the coordinate system
1492 // is flipped vertically with Quartz2D.
1493 static const uchar *qt_mac_patternForBrush(int brushStyle)
1495 Q_ASSERT(brushStyle > Qt::SolidPattern && brushStyle < Qt::LinearGradientPattern);
1496 static const uchar dense1_pat[] = { 0x00, 0x00, 0x44, 0x00, 0x00, 0x00, 0x44, 0x00 };
1497 static const uchar dense2_pat[] = { 0x00, 0x22, 0x00, 0x88, 0x00, 0x22, 0x00, 0x88 };
1498 static const uchar dense3_pat[] = { 0x11, 0xaa, 0x44, 0xaa, 0x11, 0xaa, 0x44, 0xaa };
1499 static const uchar dense4_pat[] = { 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55 };
1500 static const uchar dense5_pat[] = { 0xee, 0x55, 0xbb, 0x55, 0xee, 0x55, 0xbb, 0x55 };
1501 static const uchar dense6_pat[] = { 0xff, 0xdd, 0xff, 0x77, 0xff, 0xdd, 0xff, 0x77 };
1502 static const uchar dense7_pat[] = { 0xff, 0xff, 0xbb, 0xff, 0xff, 0xff, 0xbb, 0xff };
1503 static const uchar hor_pat[] = { 0xff, 0xff, 0xff, 0xff, 0x00, 0xff, 0xff, 0xff };
1504 static const uchar ver_pat[] = { 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef };
1505 static const uchar cross_pat[] = { 0xef, 0xef, 0xef, 0xef, 0x00, 0xef, 0xef, 0xef };
1506 static const uchar fdiag_pat[] = { 0x7f, 0xbf, 0xdf, 0xef, 0xf7, 0xfb, 0xfd, 0xfe };
1507 static const uchar bdiag_pat[] = { 0xfe, 0xfd, 0xfb, 0xf7, 0xef, 0xdf, 0xbf, 0x7f };
1508 static const uchar dcross_pat[] = { 0x7e, 0xbd, 0xdb, 0xe7, 0xe7, 0xdb, 0xbd, 0x7e };
1509 static const uchar *const pat_tbl[] = {
1510 dense1_pat, dense2_pat, dense3_pat, dense4_pat, dense5_pat,
1511 dense6_pat, dense7_pat,
1512 hor_pat, ver_pat, cross_pat, bdiag_pat, fdiag_pat, dcross_pat };
1513 return pat_tbl[brushStyle - Qt::Dense1Pattern];
1516 void QCoreGraphicsPaintEnginePrivate::setFillBrush(const QPointF &offset)
1519 Qt::BrushStyle bs = current.brush.style();
1520 #ifdef QT_MAC_USE_NATIVE_GRADIENTS
1521 if (bs == Qt::LinearGradientPattern || bs == Qt::RadialGradientPattern) {
1522 const QGradient *grad = static_cast<const QGradient*>(current.brush.gradient());
1523 if (drawGradientNatively(grad)) {
1524 Q_ASSERT(grad->spread() == QGradient::PadSpread);
1526 static const CGFloat domain[] = { 0.0f, +1.0f };
1527 static const CGFunctionCallbacks callbacks = { 0, qt_mac_color_gradient_function, 0 };
1528 CGFunctionRef fill_func = CGFunctionCreate(reinterpret_cast<void *>(¤t.brush),
1529 1, domain, 4, 0, &callbacks);
1531 CGColorSpaceRef colorspace = qt_mac_colorSpaceForDeviceType(pdev);
1532 if (bs == Qt::LinearGradientPattern) {
1533 const QLinearGradient *linearGrad = static_cast<const QLinearGradient *>(grad);
1534 const QPointF start(linearGrad->start());
1535 const QPointF stop(linearGrad->finalStop());
1536 shading = CGShadingCreateAxial(colorspace, CGPointMake(start.x(), start.y()),
1537 CGPointMake(stop.x(), stop.y()), fill_func, true, true);
1539 Q_ASSERT(bs == Qt::RadialGradientPattern);
1540 const QRadialGradient *radialGrad = static_cast<const QRadialGradient *>(grad);
1541 QPointF center(radialGrad->center());
1542 QPointF focal(radialGrad->focalPoint());
1543 qreal radius = radialGrad->radius();
1544 qreal focalRadius = radialGrad->focalRadius();
1545 shading = CGShadingCreateRadial(colorspace, CGPointMake(focal.x(), focal.y()),
1546 focalRadius, CGPointMake(center.x(), center.y()), radius, fill_func, false, true);
1549 CGFunctionRelease(fill_func);
1553 if(bs != Qt::SolidPattern && bs != Qt::NoBrush
1554 #ifndef QT_MAC_USE_NATIVE_GRADIENTS
1555 && (bs < Qt::LinearGradientPattern || bs > Qt::ConicalGradientPattern)
1559 QMacPattern *qpattern = new QMacPattern;
1560 qpattern->pdev = pdev;
1561 CGFloat components[4] = { 1.0, 1.0, 1.0, 1.0 };
1562 CGColorSpaceRef base_colorspace = 0;
1563 if(bs == Qt::TexturePattern) {
1564 qpattern->data.pixmap = current.brush.texture();
1565 if(qpattern->data.pixmap.isQBitmap()) {
1566 const QColor &col = current.brush.color();
1567 components[0] = qt_mac_convert_color_to_cg(col.red());
1568 components[1] = qt_mac_convert_color_to_cg(col.green());
1569 components[2] = qt_mac_convert_color_to_cg(col.blue());
1570 base_colorspace = QCoreGraphicsPaintEngine::macGenericColorSpace();
1573 qpattern->as_mask = true;
1575 qpattern->data.bytes = qt_mac_patternForBrush(bs);
1576 const QColor &col = current.brush.color();
1577 components[0] = qt_mac_convert_color_to_cg(col.red());
1578 components[1] = qt_mac_convert_color_to_cg(col.green());
1579 components[2] = qt_mac_convert_color_to_cg(col.blue());
1580 base_colorspace = QCoreGraphicsPaintEngine::macGenericColorSpace();
1582 int width = qpattern->width(), height = qpattern->height();
1583 qpattern->foreground = current.brush.color();
1585 CGColorSpaceRef fill_colorspace = CGColorSpaceCreatePattern(base_colorspace);
1586 CGContextSetFillColorSpace(hd, fill_colorspace);
1588 CGAffineTransform xform = CGContextGetCTM(hd);
1589 xform = CGAffineTransformConcat(qt_mac_convert_transform_to_cg(current.brush.transform()), xform);
1590 xform = CGAffineTransformTranslate(xform, offset.x(), offset.y());
1592 CGPatternCallbacks callbks;
1593 callbks.version = 0;
1594 callbks.drawPattern = qt_mac_draw_pattern;
1595 callbks.releaseInfo = qt_mac_dispose_pattern;
1596 CGPatternRef fill_pattern = CGPatternCreate(qpattern, CGRectMake(0, 0, width, height),
1597 xform, width, height, kCGPatternTilingNoDistortion,
1598 !base_colorspace, &callbks);
1599 CGContextSetFillPattern(hd, fill_pattern, components);
1601 CGPatternRelease(fill_pattern);
1602 CGColorSpaceRelease(fill_colorspace);
1603 } else if(bs != Qt::NoBrush) {
1604 CGContextSetFillColorWithColor(hd, cgColorForQColor(current.brush.color(), pdev));
1609 QCoreGraphicsPaintEnginePrivate::setClip(const QRegion *rgn)
1611 Q_Q(QCoreGraphicsPaintEngine);
1614 QRegion sysClip = q->systemClip();
1615 if(!sysClip.isEmpty())
1616 qt_mac_clip_cg(hd, sysClip, &orig_xform);
1618 qt_mac_clip_cg(hd, *rgn, 0);
1622 struct qt_mac_cg_transform_path {
1623 CGMutablePathRef path;
1624 CGAffineTransform transform;
1627 void qt_mac_cg_transform_path_apply(void *info, const CGPathElement *element)
1629 Q_ASSERT(info && element);
1630 qt_mac_cg_transform_path *t = (qt_mac_cg_transform_path*)info;
1631 switch(element->type) {
1632 case kCGPathElementMoveToPoint:
1633 CGPathMoveToPoint(t->path, &t->transform, element->points[0].x, element->points[0].y);
1635 case kCGPathElementAddLineToPoint:
1636 CGPathAddLineToPoint(t->path, &t->transform, element->points[0].x, element->points[0].y);
1638 case kCGPathElementAddQuadCurveToPoint:
1639 CGPathAddQuadCurveToPoint(t->path, &t->transform, element->points[0].x, element->points[0].y,
1640 element->points[1].x, element->points[1].y);
1642 case kCGPathElementAddCurveToPoint:
1643 CGPathAddCurveToPoint(t->path, &t->transform, element->points[0].x, element->points[0].y,
1644 element->points[1].x, element->points[1].y,
1645 element->points[2].x, element->points[2].y);
1647 case kCGPathElementCloseSubpath:
1648 CGPathCloseSubpath(t->path);
1651 qDebug() << "Unhandled path transform type: " << element->type;
1655 void QCoreGraphicsPaintEnginePrivate::drawPath(uchar ops, CGMutablePathRef path)
1657 Q_Q(QCoreGraphicsPaintEngine);
1658 Q_ASSERT((ops & (CGFill | CGEOFill)) != (CGFill | CGEOFill)); //can't really happen
1659 if((ops & (CGFill | CGEOFill))) {
1662 CGContextBeginPath(hd);
1663 CGContextAddPath(hd, path);
1664 saveGraphicsState();
1667 else if (ops & CGEOFill)
1668 CGContextEOClip(hd);
1669 if (current.brush.gradient()->coordinateMode() == QGradient::ObjectBoundingMode) {
1670 CGRect boundingBox = CGPathGetBoundingBox(path);
1671 CGContextConcatCTM(hd,
1672 CGAffineTransformMake(boundingBox.size.width, 0,
1673 0, boundingBox.size.height,
1674 boundingBox.origin.x, boundingBox.origin.y));
1676 CGContextDrawShading(hd, shading);
1677 restoreGraphicsState();
1680 } else if (current.brush.style() == Qt::NoBrush) {
1685 if((ops & CGStroke) && current.pen.style() == Qt::NoPen)
1688 if(ops & (CGEOFill | CGFill)) {
1689 CGContextBeginPath(hd);
1690 CGContextAddPath(hd, path);
1691 if (ops & CGEOFill) {
1692 CGContextEOFillPath(hd);
1694 CGContextFillPath(hd);
1698 // Avoid saving and restoring the context if we can.
1699 const bool needContextSave = (cosmeticPen != QCoreGraphicsPaintEnginePrivate::CosmeticNone ||
1700 !(q->state->renderHints() & QPainter::Antialiasing));
1701 if(ops & CGStroke) {
1702 if (needContextSave)
1703 saveGraphicsState();
1704 CGContextBeginPath(hd);
1706 // Translate a fraction of a pixel size in the y direction
1707 // to make sure that primitives painted at pixel borders
1708 // fills the right pixel. This is needed since the y xais
1709 // in the Quartz coordinate system is inverted compared to Qt.
1710 if (!(q->state->renderHints() & QPainter::Antialiasing)) {
1711 if (current.pen.style() == Qt::SolidLine || current.pen.width() >= 3)
1712 CGContextTranslateCTM(hd, double(pixelSize.x()) * 0.25, double(pixelSize.y()) * 0.25);
1713 else if (current.pen.style() == Qt::DotLine && QSysInfo::MacintoshVersion == QSysInfo::MV_10_3)
1716 CGContextTranslateCTM(hd, 0, double(pixelSize.y()) * 0.1);
1719 if (cosmeticPen != QCoreGraphicsPaintEnginePrivate::CosmeticNone) {
1720 // If antialiazing is enabled, use the cosmetic pen size directly.
1721 if (q->state->renderHints() & QPainter::Antialiasing)
1722 CGContextSetLineWidth(hd, cosmeticPenSize);
1723 else if (current.pen.widthF() <= 1)
1724 CGContextSetLineWidth(hd, cosmeticPenSize * 0.9f);
1726 CGContextSetLineWidth(hd, cosmeticPenSize);
1728 if(cosmeticPen == QCoreGraphicsPaintEnginePrivate::CosmeticTransformPath) {
1729 qt_mac_cg_transform_path t;
1730 t.transform = qt_mac_convert_transform_to_cg(current.transform);
1731 t.path = CGPathCreateMutable();
1732 CGPathApply(path, &t, qt_mac_cg_transform_path_apply); //transform the path
1733 setTransform(0); //unset the context transform
1734 CGContextSetLineWidth(hd, cosmeticPenSize);
1735 CGContextAddPath(hd, t.path);
1736 CGPathRelease(t.path);
1738 CGContextAddPath(hd, path);
1741 CGContextStrokePath(hd);
1742 if (needContextSave)
1743 restoreGraphicsState();