Replace 'i < len-1 && func(i+1)' by 'i+1 < len && func(i+1)'
[profile/ivi/qtbase.git] / src / gui / painting / qpaintengine_mac.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
6 **
7 ** This file is part of the QtGui module of the Qt Toolkit.
8 **
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.
17 **
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.
21 **
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.
29 **
30 ** Other Usage
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.
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include <qbitmap.h>
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>
49 #include <qprinter.h>
50 #include <qstack.h>
51 #include <qtextcodec.h>
52 #include <qwidget.h>
53 #include <qvarlengtharray.h>
54 #include <qdebug.h>
55 #include <qcoreapplication.h>
56 #include <qmath.h>
57
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>
70
71 #include <string.h>
72
73 QT_BEGIN_NAMESPACE
74
75 extern int qt_antialiasing_threshold; // QApplication.cpp
76
77 /*****************************************************************************
78   External functions
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
86
87 void qt_mac_clip_cg(CGContextRef hd, const QRegion &rgn, CGAffineTransform *orig_xform);
88
89
90 //Implemented for qt_mac_p.h
91 QMacCGContext::QMacCGContext(QPainter *p)
92 {
93     QPaintEngine *pe = p->paintEngine();
94     if (pe->type() == QPaintEngine::MacPrinter)
95         pe = static_cast<QMacPrintEngine*>(pe)->paintEngine();
96     pe->syncState();
97     context = 0;
98     if(pe->type() == QPaintEngine::CoreGraphics)
99         context = static_cast<QCoreGraphicsPaintEngine*>(pe)->handle();
100
101     int devType = p->device()->devType();
102     if (pe->type() == QPaintEngine::Raster
103             && (devType == QInternal::Widget ||
104                 devType == QInternal::Pixmap ||
105                 devType == QInternal::Image)) {
106
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;
112 #endif
113         const QImage *image = (const QImage *) pe->paintDevice();
114
115         context = CGBitmapContextCreate((void *) image->bits(), image->width(), image->height(),
116                                         8, image->bytesPerLine(), colorspace, flags);
117
118         CGContextTranslateCTM(context, 0, image->height());
119         CGContextScaleCTM(context, 1, -1);
120
121         if (devType == QInternal::Widget) {
122             QRegion clip = p->paintEngine()->systemClip();
123             QTransform native = p->deviceTransform();
124             QTransform logical = p->combinedTransform();
125
126             if (p->hasClipping()) {
127                 QRegion r = p->clipRegion();
128                 r.translate(native.dx(), native.dy());
129                 if (clip.isEmpty())
130                     clip = r;
131                 else
132                     clip &= r;
133             }
134             qt_mac_clip_cg(context, clip, 0);
135
136             CGContextTranslateCTM(context, native.dx(), native.dy());
137         }
138     } else {
139         CGContextRetain(context);
140     }
141 }
142
143
144 /*****************************************************************************
145   QCoreGraphicsPaintEngine utility functions
146  *****************************************************************************/
147
148 //conversion
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());
153 }
154
155 CGColorSpaceRef qt_mac_colorSpaceForDeviceType(const QPaintDevice *paintDevice)
156 {
157     bool isWidget = (paintDevice->devType() == QInternal::Widget);
158     return QCoreGraphicsPaintEngine::macDisplayColorSpace(isWidget ? static_cast<const QWidget *>(paintDevice)
159                                                                    : 0);
160 }
161
162 inline static QCFType<CGColorRef> cgColorForQColor(const QColor &col, QPaintDevice *pdev)
163 {
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())
169     };
170     return CGColorCreate(qt_mac_colorSpaceForDeviceType(pdev), components);
171 }
172
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
176
177 #ifdef QT_MAC_USE_NATIVE_GRADIENTS
178 static bool drawGradientNatively(const QGradient *gradient)
179 {
180     return gradient->spread() == QGradient::PadSpread;
181 }
182
183 // gradiant callback
184 static void qt_mac_color_gradient_function(void *info, const CGFloat *in, CGFloat *out)
185 {
186     QBrush *brush = static_cast<QBrush *>(info);
187     Q_ASSERT(brush && brush->gradient());
188
189     const QGradientStops stops = brush->gradient()->stops();
190     const int n = stops.count();
191     Q_ASSERT(n >= 1);
192     const QGradientStop *begin = stops.constBegin();
193     const QGradientStop *end = begin + n;
194
195     qreal p = in[0];
196     const QGradientStop *i = begin;
197     while (i != end && i->first < p)
198         ++i;
199
200     QRgb c;
201     if (i == begin) {
202         c = begin->second.rgba();
203     } else if (i == end) {
204         c = (end - 1)->second.rgba();
205     } else {
206         const QGradientStop &s1 = *(i - 1);
207         const QGradientStop &s2 = *i;
208         qreal p1 = s1.first;
209         qreal p2 = s2.first;
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));
218     }
219
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));
224 }
225 #endif
226
227 //clipping handling
228 void QCoreGraphicsPaintEnginePrivate::resetClip()
229 {
230     static bool inReset = false;
231     if (inReset)
232         return;
233     inReset = true;
234
235     CGAffineTransform old_xform = CGContextGetCTM(hd);
236
237     //setup xforms
238     CGContextConcatCTM(hd, CGAffineTransformInvert(old_xform));
239     while (stackCount > 0) {
240         restoreGraphicsState();
241     }
242     saveGraphicsState();
243     inReset = false;
244     //reset xforms
245     CGContextConcatCTM(hd, CGAffineTransformInvert(CGContextGetCTM(hd)));
246     CGContextConcatCTM(hd, old_xform);
247 }
248
249 static CGRect qt_mac_compose_rect(const QRectF &r, float off=0)
250 {
251     return CGRectMake(r.x()+off, r.y()+off, r.width(), r.height());
252 }
253
254 static CGMutablePathRef qt_mac_compose_path(const QPainterPath &p, float off=0)
255 {
256     CGMutablePathRef ret = CGPathCreateMutable();
257     QPointF startPt;
258     for (int i=0; i<p.elementCount(); ++i) {
259         const QPainterPath::Element &elm = p.elementAt(i);
260         switch (elm.type) {
261             case QPainterPath::MoveToElement:
262                 if(i > 0
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);
268                 break;
269             case QPainterPath::LineToElement:
270                 CGPathAddLineToPoint(ret, 0, elm.x+off, elm.y+off);
271                 break;
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);
279                 i+=2;
280                 break;
281             default:
282                 qFatal("QCoreGraphicsPaintEngine::drawPath(), unhandled type: %d", elm.type);
283                 break;
284         }
285     }
286     if(!p.isEmpty()
287             && p.elementAt(p.elementCount() - 1).x == startPt.x()
288             && p.elementAt(p.elementCount() - 1).y == startPt.y())
289         CGPathCloseSubpath(ret);
290     return ret;
291 }
292
293 CGColorSpaceRef QCoreGraphicsPaintEngine::m_genericColorSpace = 0;
294 QHash<CGDirectDisplayID, CGColorSpaceRef> QCoreGraphicsPaintEngine::m_displayColorSpaceHash;
295 bool QCoreGraphicsPaintEngine::m_postRoutineRegistered = false;
296
297 CGColorSpaceRef QCoreGraphicsPaintEngine::macGenericColorSpace()
298 {
299 #if 0
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);
304         } else
305 #endif
306         {
307             m_genericColorSpace = CGColorSpaceCreateDeviceRGB();
308         }
309         if (!m_postRoutineRegistered) {
310             m_postRoutineRegistered = true;
311             qAddPostRoutine(QCoreGraphicsPaintEngine::cleanUpMacColorSpaces);
312         }
313     }
314     return m_genericColorSpace;
315 #else
316     // Just return the main display colorspace for the moment.
317     return macDisplayColorSpace();
318 #endif
319 }
320
321 /*
322     Ideally, we should pass the widget in here, and use CGGetDisplaysWithRect() etc.
323     to support multiple displays correctly.
324 */
325 CGColorSpaceRef QCoreGraphicsPaintEngine::macDisplayColorSpace(const QWidget *widget)
326 {
327     CGColorSpaceRef colorSpace;
328
329     CGDirectDisplayID displayID;
330     CMProfileRef displayProfile = 0;
331     if (widget == 0) {
332         displayID = CGMainDisplayID();
333     } else {
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
340     }
341     if ((colorSpace = m_displayColorSpaceHash.value(displayID)))
342         return colorSpace;
343
344     CMError err = CMGetProfileByAVID((CMDisplayIDType)displayID, &displayProfile);
345     if (err == noErr) {
346         colorSpace = CGColorSpaceCreateWithPlatformColorSpace(displayProfile);
347     } else if (widget) {
348         return macDisplayColorSpace(0); // fall back on main display
349     }
350
351     if (colorSpace == 0)
352         colorSpace = CGColorSpaceCreateDeviceRGB();
353
354     m_displayColorSpaceHash.insert(displayID, colorSpace);
355     CMCloseProfile(displayProfile);
356     if (!m_postRoutineRegistered) {
357         m_postRoutineRegistered = true;
358         qAddPostRoutine(QCoreGraphicsPaintEngine::cleanUpMacColorSpaces);
359     }
360     return colorSpace;
361 }
362
363 void QCoreGraphicsPaintEngine::cleanUpMacColorSpaces()
364 {
365     if (m_genericColorSpace) {
366         CFRelease(m_genericColorSpace);
367         m_genericColorSpace = 0;
368     }
369     QHash<CGDirectDisplayID, CGColorSpaceRef>::const_iterator it = m_displayColorSpaceHash.constBegin();
370     while (it != m_displayColorSpaceHash.constEnd()) {
371         if (it.value())
372             CFRelease(it.value());
373         ++it;
374     }
375     m_displayColorSpaceHash.clear();
376 }
377
378 void qt_mac_clip_cg(CGContextRef hd, const QRegion &rgn, CGAffineTransform *orig_xform)
379 {
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);
385     }
386
387     //do the clipping
388     CGContextBeginPath(hd);
389     if(rgn.isEmpty()) {
390         CGContextAddRect(hd, CGRectMake(0, 0, 0, 0));
391     } else {
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);
397         } else
398 #endif
399         {
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);
406             }
407         }
408
409     }
410     CGContextClip(hd);
411
412     if(orig_xform) {//reset xforms
413         CGContextConcatCTM(hd, CGAffineTransformInvert(CGContextGetCTM(hd)));
414         CGContextConcatCTM(hd, old_xform);
415     }
416 }
417
418
419 //pattern handling (tiling)
420 #if 1
421 #  define QMACPATTERN_MASK_MULTIPLIER 32
422 #else
423 #  define QMACPATTERN_MASK_MULTIPLIER 1
424 #endif
425 class QMacPattern
426 {
427 public:
428     QMacPattern() : as_mask(false), pdev(0), image(0) { data.bytes = 0; }
429     ~QMacPattern() { CGImageRelease(image); }
430     int width() {
431         if(image)
432             return CGImageGetWidth(image);
433         if(data.bytes)
434             return 8*QMACPATTERN_MASK_MULTIPLIER;
435         return data.pixmap.width();
436     }
437     int height() {
438         if(image)
439             return CGImageGetHeight(image);
440         if(data.bytes)
441             return 8*QMACPATTERN_MASK_MULTIPLIER;
442         return data.pixmap.height();
443     }
444
445     //input
446     QColor foreground;
447     bool as_mask;
448     struct {
449         QPixmap pixmap;
450         const uchar *bytes;
451     } data;
452     QPaintDevice *pdev;
453     //output
454     CGImageRef image;
455 };
456 static void qt_mac_draw_pattern(void *info, CGContextRef c)
457 {
458     QMacPattern *pat = (QMacPattern*)info;
459     int w = 0, h = 0;
460     bool isBitmap = (pat->data.pixmap.depth() == 1);
461     if(!pat->image) { //lazy cache
462         if(pat->as_mask) {
463             Q_ASSERT(pat->data.bytes);
464             w = h = 8;
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);
469 #else
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);
477
478             const QColor c0(0, 0, 0, 0), c1(255, 255, 255, 255);
479             QPixmap pm(w*QMACPATTERN_MASK_MULTIPLIER, h*QMACPATTERN_MASK_MULTIPLIER);
480             pm.fill(c0);
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);
489                 }
490             }
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;
496 #endif
497         } else {
498             w = pat->data.pixmap.width();
499             h = pat->data.pixmap.height();
500             if (isBitmap)
501                 pat->image = qt_mac_create_imagemask(pat->data.pixmap, pat->data.pixmap.rect());
502             else
503                 pat->image = (CGImageRef)pat->data.pixmap.macCGHandle();
504         }
505     } else {
506         w = CGImageGetWidth(pat->image);
507         h = CGImageGetHeight(pat->image);
508     }
509
510     //draw
511     bool needRestore = false;
512     if (CGImageIsMask(pat->image)) {
513         CGContextSaveGState(c);
514         CGContextSetFillColorWithColor(c, cgColorForQColor(pat->foreground, pat->pdev));
515     }
516     CGRect rect = CGRectMake(0, 0, w, h);
517     qt_mac_drawCGImage(c, &rect, pat->image);
518     if(needRestore)
519         CGContextRestoreGState(c);
520 }
521 static void qt_mac_dispose_pattern(void *info)
522 {
523     QMacPattern *pat = (QMacPattern*)info;
524     delete pat;
525 }
526
527 /*****************************************************************************
528   QCoreGraphicsPaintEngine member functions
529  *****************************************************************************/
530
531 inline static QPaintEngine::PaintEngineFeatures qt_mac_cg_features()
532 {
533     return QPaintEngine::PaintEngineFeatures(QPaintEngine::AllFeatures & ~QPaintEngine::PaintOutsidePaintEvent
534                                               & ~QPaintEngine::PerspectiveTransform
535                                               & ~QPaintEngine::ConicalGradientFill
536                                               & ~QPaintEngine::LinearGradientFill
537                                               & ~QPaintEngine::RadialGradientFill
538                                               & ~QPaintEngine::BrushStroke);
539 }
540
541 QCoreGraphicsPaintEngine::QCoreGraphicsPaintEngine()
542 : QPaintEngine(*(new QCoreGraphicsPaintEnginePrivate), qt_mac_cg_features())
543 {
544 }
545
546 QCoreGraphicsPaintEngine::QCoreGraphicsPaintEngine(QPaintEnginePrivate &dptr)
547 : QPaintEngine(dptr, qt_mac_cg_features())
548 {
549 }
550
551 QCoreGraphicsPaintEngine::~QCoreGraphicsPaintEngine()
552 {
553 }
554
555 bool
556 QCoreGraphicsPaintEngine::begin(QPaintDevice *pdev)
557 {
558     Q_D(QCoreGraphicsPaintEngine);
559     if(isActive()) {                         // already active painting
560         qWarning("QCoreGraphicsPaintEngine::begin: Painter already active");
561         return false;
562     }
563
564     //initialization
565     d->pdev = pdev;
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);
572     if(d->hd) {
573         d->saveGraphicsState();
574         d->orig_xform = CGContextGetCTM(d->hd);
575         if (d->shading) {
576             CGShadingRelease(d->shading);
577             d->shading = 0;
578         }
579         d->setClip(0);  //clear the context's clipping
580     }
581
582     setActive(true);
583
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);
587
588         if((w->windowType() == Qt::Desktop)) {
589             if(!unclipped)
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");
594         }
595     } else if(d->pdev->devType() == QInternal::Pixmap) {             // device is a pixmap
596         QPixmap *pm = (QPixmap*)d->pdev;
597         if(pm->isNull()) {
598             qWarning("QCoreGraphicsPaintEngine::begin: Cannot paint null pixmap");
599             end();
600             return false;
601         }
602     }
603
604     setDirty(QPaintEngine::DirtyPen);
605     setDirty(QPaintEngine::DirtyBrush);
606     setDirty(QPaintEngine::DirtyBackground);
607     setDirty(QPaintEngine::DirtyHints);
608     return true;
609 }
610
611 bool
612 QCoreGraphicsPaintEngine::end()
613 {
614     Q_D(QCoreGraphicsPaintEngine);
615     setActive(false);
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)));
619 #else
620 //        // ### need to do [qt_mac_window_for(static_cast<QWidget *>(d->pdev)) orderOut]; (need to rename)
621 #endif
622
623         }
624     if(d->shading) {
625         CGShadingRelease(d->shading);
626         d->shading = 0;
627     }
628     d->pdev = 0;
629     if(d->hd) {
630         d->restoreGraphicsState();
631         CGContextSynchronize(d->hd);
632         CGContextRelease(d->hd);
633         d->hd = 0;
634     }
635     return true;
636 }
637
638 void
639 QCoreGraphicsPaintEngine::updateState(const QPaintEngineState &state)
640 {
641     Q_D(QCoreGraphicsPaintEngine);
642     QPaintEngine::DirtyFlags flags = state.state();
643
644     if (flags & DirtyTransform)
645         updateMatrix(state.transform());
646
647     if (flags & DirtyClipEnabled) {
648         if (state.isClipEnabled())
649             updateClipPath(painter()->clipPath(), Qt::ReplaceClip);
650         else
651             updateClipPath(QPainterPath(), Qt::NoClip);
652     }
653
654     if (flags & DirtyClipPath) {
655         updateClipPath(state.clipPath(), state.clipOperation());
656     } else if (flags & DirtyClipRegion) {
657         updateClipRegion(state.clipRegion(), state.clipOperation());
658     }
659
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))
664         flags |= AllDirty;
665
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());
678
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;
688         } else {
689             d->cosmeticPen = QCoreGraphicsPaintEnginePrivate::CosmeticSetPenWidth;
690             static const float sqrt2 = sqrt(2);
691             qreal width = d->current.pen.widthF();
692             if (!width)
693                 width = 1;
694             d->cosmeticPenSize = sqrt(pow(d->pixelSize.y(), 2) + pow(d->pixelSize.x(), 2)) / sqrt2 * width;
695         }
696     }
697 }
698
699 void
700 QCoreGraphicsPaintEngine::updatePen(const QPen &pen)
701 {
702     Q_D(QCoreGraphicsPaintEngine);
703     Q_ASSERT(isActive());
704     d->current.pen = pen;
705     d->setStrokePen(pen);
706 }
707
708 void
709 QCoreGraphicsPaintEngine::updateBrush(const QBrush &brush, const QPointF &brushOrigin)
710 {
711     Q_D(QCoreGraphicsPaintEngine);
712     Q_ASSERT(isActive());
713     d->current.brush = brush;
714
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;
720         } else {
721             gccaps &= ~(QPaintEngine::LinearGradientFill | QPaintEngine::RadialGradientFill);
722         }
723     }
724 #endif
725
726     if (d->shading) {
727         CGShadingRelease(d->shading);
728         d->shading = 0;
729     }
730     d->setFillBrush(brushOrigin);
731 }
732
733 void
734 QCoreGraphicsPaintEngine::updateOpacity(qreal opacity)
735 {
736     Q_D(QCoreGraphicsPaintEngine);
737     CGContextSetAlpha(d->hd, opacity);
738 }
739
740 void
741 QCoreGraphicsPaintEngine::updateFont(const QFont &)
742 {
743     Q_D(QCoreGraphicsPaintEngine);
744     Q_ASSERT(isActive());
745     updatePen(d->current.pen);
746 }
747
748 void
749 QCoreGraphicsPaintEngine::updateMatrix(const QTransform &transform)
750 {
751     Q_D(QCoreGraphicsPaintEngine);
752     Q_ASSERT(isActive());
753
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()))
757         return;
758
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);
764 }
765
766 void
767 QCoreGraphicsPaintEngine::updateClipPath(const QPainterPath &p, Qt::ClipOperation op)
768 {
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();
775             d->setClip(0);
776         }
777     } else {
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;
784             d->setClip(0);
785             if(p.isEmpty()) {
786                 CGRect rect = CGRectMake(0, 0, 0, 0);
787                 CGContextClipToRect(d->hd, rect);
788             } else {
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);
794                 else
795                     CGContextEOClip(d->hd);
796                 CGPathRelease(path);
797             }
798         } else if(op == Qt::IntersectClip) {
799             d->current.clip = d->current.clip.intersected(clipRegion);
800             d->setClip(&d->current.clip);
801         }
802     }
803 }
804
805 void
806 QCoreGraphicsPaintEngine::updateClipRegion(const QRegion &clipRegion, Qt::ClipOperation op)
807 {
808     Q_D(QCoreGraphicsPaintEngine);
809     Q_ASSERT(isActive());
810     if(op == Qt::NoClip) {
811         d->current.clipEnabled = false;
812         d->current.clip = QRegion();
813         d->setClip(0);
814     } else {
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);
823     }
824 }
825
826 void
827 QCoreGraphicsPaintEngine::drawPath(const QPainterPath &p)
828 {
829     Q_D(QCoreGraphicsPaintEngine);
830     Q_ASSERT(isActive());
831
832     if (state->compositionMode() == QPainter::CompositionMode_Destination)
833         return;
834
835     CGMutablePathRef path = qt_mac_compose_path(p);
836     uchar ops = QCoreGraphicsPaintEnginePrivate::CGStroke;
837     if(p.fillRule() == Qt::WindingFill)
838         ops |= QCoreGraphicsPaintEnginePrivate::CGFill;
839     else
840         ops |= QCoreGraphicsPaintEnginePrivate::CGEOFill;
841     CGContextBeginPath(d->hd);
842     d->drawPath(ops, path);
843     CGPathRelease(path);
844 }
845
846 void
847 QCoreGraphicsPaintEngine::drawRects(const QRectF *rects, int rectCount)
848 {
849     Q_D(QCoreGraphicsPaintEngine);
850     Q_ASSERT(isActive());
851
852     if (state->compositionMode() == QPainter::CompositionMode_Destination)
853         return;
854
855     for (int i=0; i<rectCount; ++i) {
856         QRectF r = rects[i];
857
858         CGMutablePathRef path = CGPathCreateMutable();
859         CGPathAddRect(path, 0, qt_mac_compose_rect(r));
860         d->drawPath(QCoreGraphicsPaintEnginePrivate::CGFill|QCoreGraphicsPaintEnginePrivate::CGStroke,
861                 path);
862         CGPathRelease(path);
863     }
864 }
865
866 void
867 QCoreGraphicsPaintEngine::drawPoints(const QPointF *points, int pointCount)
868 {
869     Q_D(QCoreGraphicsPaintEngine);
870     Q_ASSERT(isActive());
871
872     if (state->compositionMode() == QPainter::CompositionMode_Destination)
873         return;
874
875     if (d->current.pen.capStyle() == Qt::FlatCap)
876         CGContextSetLineCap(d->hd, kCGLineCapSquare);
877
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);
883     }
884
885     bool doRestore = false;
886     if(d->cosmeticPen == QCoreGraphicsPaintEnginePrivate::CosmeticNone && !(state->renderHints() & QPainter::Antialiasing)) {
887         //we don't want adjusted pens for point rendering
888         doRestore = true;
889         d->saveGraphicsState();
890         CGContextSetLineWidth(d->hd, d->current.pen.widthF());
891     }
892     d->drawPath(QCoreGraphicsPaintEnginePrivate::CGStroke, path);
893     if (doRestore)
894         d->restoreGraphicsState();
895     CGPathRelease(path);
896     if (d->current.pen.capStyle() == Qt::FlatCap)
897         CGContextSetLineCap(d->hd, kCGLineCapButt);
898 }
899
900 void
901 QCoreGraphicsPaintEngine::drawEllipse(const QRectF &r)
902 {
903     Q_D(QCoreGraphicsPaintEngine);
904     Q_ASSERT(isActive());
905
906     if (state->compositionMode() == QPainter::CompositionMode_Destination)
907         return;
908
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,
914             path);
915     CGPathRelease(path);
916 }
917
918 void
919 QCoreGraphicsPaintEngine::drawPolygon(const QPointF *points, int pointCount, PolygonDrawMode mode)
920 {
921     Q_D(QCoreGraphicsPaintEngine);
922     Q_ASSERT(isActive());
923
924     if (state->compositionMode() == QPainter::CompositionMode_Destination)
925         return;
926
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);
938     CGPathRelease(path);
939 }
940
941 void
942 QCoreGraphicsPaintEngine::drawLines(const QLineF *lines, int lineCount)
943 {
944     Q_D(QCoreGraphicsPaintEngine);
945     Q_ASSERT(isActive());
946
947     if (state->compositionMode() == QPainter::CompositionMode_Destination)
948         return;
949
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());
955     }
956     d->drawPath(QCoreGraphicsPaintEnginePrivate::CGStroke, path);
957     CGPathRelease(path);
958 }
959
960 void QCoreGraphicsPaintEngine::drawPixmap(const QRectF &r, const QPixmap &pm, const QRectF &sr)
961 {
962     Q_D(QCoreGraphicsPaintEngine);
963     Q_ASSERT(isActive());
964
965     if (state->compositionMode() == QPainter::CompositionMode_Destination)
966         return;
967
968     if(pm.isNull())
969         return;
970
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);
975     if (isBitmap) {
976         doRestore = true;
977         d->saveGraphicsState();
978
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())));
985     } else {
986         image = (CGImageRef)pm.macCGHandle();
987     }
988     qt_mac_drawCGImage(d->hd, &rect, image);
989     if (doRestore)
990         d->restoreGraphicsState();
991 }
992
993 static void drawImageReleaseData (void *info, const void *, size_t)
994 {
995     delete static_cast<QImage *>(info);
996 }
997
998 CGImageRef qt_mac_createCGImageFromQImage(const QImage &img, const QImage **imagePtr = 0)
999 {
1000     QImage *image;
1001     if (img.depth() != 32)
1002         image = new QImage(img.convertToFormat(QImage::Format_ARGB32_Premultiplied));
1003     else
1004         image = new QImage(img);
1005
1006     uint cgflags = kCGImageAlphaNone;
1007     switch (image->format()) {
1008     case QImage::Format_ARGB32_Premultiplied:
1009         cgflags = kCGImageAlphaPremultipliedFirst;
1010         break;
1011     case QImage::Format_ARGB32:
1012         cgflags = kCGImageAlphaFirst;
1013         break;
1014     case QImage::Format_RGB32:
1015         cgflags = kCGImageAlphaNoneSkipFirst;
1016     default:
1017         break;
1018     }
1019 #if defined(kCGBitmapByteOrder32Host) //only needed because CGImage.h added symbols in the minor version
1020     cgflags |= kCGBitmapByteOrder32Host;
1021 #endif
1022     QCFType<CGDataProviderRef> dataProvider = CGDataProviderCreateWithData(image,
1023                                                           static_cast<const QImage *>(image)->bits(),
1024                                                           image->byteCount(),
1025                                                           drawImageReleaseData);
1026     if (imagePtr)
1027         *imagePtr = image;
1028     return CGImageCreate(image->width(), image->height(), 8, 32,
1029                                         image->bytesPerLine(),
1030                                         QCoreGraphicsPaintEngine::macGenericColorSpace(),
1031                                         cgflags, dataProvider, 0, false, kCGRenderingIntentDefault);
1032
1033 }
1034
1035 void QCoreGraphicsPaintEngine::drawImage(const QRectF &r, const QImage &img, const QRectF &sr,
1036                                          Qt::ImageConversionFlags flags)
1037 {
1038     Q_D(QCoreGraphicsPaintEngine);
1039     Q_UNUSED(flags);
1040     Q_ASSERT(isActive());
1041
1042     if (img.isNull() || state->compositionMode() == QPainter::CompositionMode_Destination)
1043         return;
1044
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);
1052 }
1053
1054 void QCoreGraphicsPaintEngine::initialize()
1055 {
1056 }
1057
1058 void QCoreGraphicsPaintEngine::cleanup()
1059 {
1060 }
1061
1062 CGContextRef
1063 QCoreGraphicsPaintEngine::handle() const
1064 {
1065     return d_func()->hd;
1066 }
1067
1068 void
1069 QCoreGraphicsPaintEngine::drawTiledPixmap(const QRectF &r, const QPixmap &pixmap,
1070         const QPointF &p)
1071 {
1072     Q_D(QCoreGraphicsPaintEngine);
1073     Q_ASSERT(isActive());
1074
1075     if (state->compositionMode() == QPainter::CompositionMode_Destination)
1076         return;
1077
1078     //save the old state
1079     d->saveGraphicsState();
1080
1081     //setup the pattern
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);
1101
1102     //fill the rectangle
1103     CGRect mac_rect = CGRectMake(r.x(), r.y(), r.width(), r.height());
1104     CGContextFillRect(d->hd, mac_rect);
1105
1106     //restore the state
1107     d->restoreGraphicsState();
1108     //cleanup
1109     CGColorSpaceRelease(cs);
1110     CGPatternRelease(pat);
1111 }
1112
1113 void QCoreGraphicsPaintEngine::drawTextItem(const QPointF &pos, const QTextItem &item)
1114 {
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
1119 #endif
1120         ) {
1121         QPaintEngine::drawTextItem(pos, item);
1122         return;
1123     }
1124
1125     if (state->compositionMode() == QPainter::CompositionMode_Destination)
1126         return;
1127
1128     const QTextItemInt &ti = static_cast<const QTextItemInt &>(item);
1129
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));
1135
1136     Q_ASSERT(type() == QPaintEngine::CoreGraphics);
1137
1138     QFontEngine *fe = ti.fontEngine;
1139
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);
1144
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());
1150 #else
1151             static_cast<QFontEngineMac *>(fe)->draw(d->hd, pos.x(), pos.y(), ti, paintDevice()->height());
1152 #endif
1153             break;
1154         case QFontEngine::Box:
1155             d->drawBoxTextItem(pos, ti);
1156             break;
1157         default:
1158             break;
1159         }
1160     }
1161
1162     if(textAA != lineAA)
1163         CGContextSetShouldAntialias(d->hd, !textAA);
1164
1165     updatePen(oldPen);
1166     updateBrush(oldBrush, oldBrushOrigin);
1167 }
1168
1169 QPainter::RenderHints
1170 QCoreGraphicsPaintEngine::supportedRenderHints() const
1171 {
1172     return QPainter::RenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform);
1173 }
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))
1188     };
1189 extern "C" {
1190     extern void CGContextSetCompositeOperation(CGContextRef, int);
1191 } // private function, but is in all versions of OS X.
1192 void
1193 QCoreGraphicsPaintEngine::updateCompositionMode(QPainter::CompositionMode mode)
1194 {
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;
1198         switch(mode) {
1199         case QPainter::CompositionMode_Multiply:
1200             cg_mode = kCGBlendModeMultiply;
1201             break;
1202         case QPainter::CompositionMode_Screen:
1203             cg_mode = kCGBlendModeScreen;
1204             break;
1205         case QPainter::CompositionMode_Overlay:
1206             cg_mode = kCGBlendModeOverlay;
1207             break;
1208         case QPainter::CompositionMode_Darken:
1209             cg_mode = kCGBlendModeDarken;
1210             break;
1211         case QPainter::CompositionMode_Lighten:
1212             cg_mode = kCGBlendModeLighten;
1213             break;
1214         case QPainter::CompositionMode_ColorDodge:
1215             cg_mode = kCGBlendModeColorDodge;
1216             break;
1217         case QPainter::CompositionMode_ColorBurn:
1218             cg_mode = kCGBlendModeColorBurn;
1219             break;
1220         case QPainter::CompositionMode_HardLight:
1221             cg_mode = kCGBlendModeHardLight;
1222             break;
1223         case QPainter::CompositionMode_SoftLight:
1224             cg_mode = kCGBlendModeSoftLight;
1225             break;
1226         case QPainter::CompositionMode_Difference:
1227             cg_mode = kCGBlendModeDifference;
1228             break;
1229         case QPainter::CompositionMode_Exclusion:
1230             cg_mode = kCGBlendModeExclusion;
1231             break;
1232         case QPainter::CompositionMode_Plus:
1233             cg_mode = kCGBlendModePlusLighter;
1234             break;
1235         case QPainter::CompositionMode_SourceOver:
1236             cg_mode = kCGBlendModeNormal;
1237             break;
1238         case QPainter::CompositionMode_DestinationOver:
1239             cg_mode = kCGBlendModeDestinationOver;
1240             break;
1241         case QPainter::CompositionMode_Clear:
1242             cg_mode = kCGBlendModeClear;
1243             break;
1244         case QPainter::CompositionMode_Source:
1245             cg_mode = kCGBlendModeCopy;
1246             break;
1247         case QPainter::CompositionMode_Destination:
1248             cg_mode = -1;
1249             break;
1250         case QPainter::CompositionMode_SourceIn:
1251             cg_mode = kCGBlendModeSourceIn;
1252             break;
1253         case QPainter::CompositionMode_DestinationIn:
1254             cg_mode = kCGCompositeModeDestinationIn;
1255             break;
1256         case QPainter::CompositionMode_SourceOut:
1257             cg_mode = kCGBlendModeSourceOut;
1258             break;
1259         case QPainter::CompositionMode_DestinationOut:
1260             cg_mode = kCGBlendModeDestinationOver;
1261             break;
1262         case QPainter::CompositionMode_SourceAtop:
1263             cg_mode = kCGBlendModeSourceAtop;
1264             break;
1265         case QPainter::CompositionMode_DestinationAtop:
1266             cg_mode = kCGBlendModeDestinationAtop;
1267             break;
1268         case QPainter::CompositionMode_Xor:
1269             cg_mode = kCGBlendModeXOR;
1270             break;
1271         default:
1272             break;
1273         }
1274         if (cg_mode > -1) {
1275             CGContextSetBlendMode(d_func()->hd, CGBlendMode(cg_mode));
1276         }
1277     } else
1278 #endif
1279     // The standard porter duff ops.
1280     if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_3
1281             && mode <= QPainter::CompositionMode_Xor) {
1282         int cg_mode = kCGCompositeModeCopy;
1283         switch (mode) {
1284         case QPainter::CompositionMode_SourceOver:
1285             cg_mode = kCGCompositeModeSourceOver;
1286             break;
1287         case QPainter::CompositionMode_DestinationOver:
1288             cg_mode = kCGCompositeModeDestinationOver;
1289             break;
1290         case QPainter::CompositionMode_Clear:
1291             cg_mode = kCGCompositeModeClear;
1292             break;
1293         default:
1294             qWarning("QCoreGraphicsPaintEngine: Unhandled composition mode %d", (int)mode);
1295             break;
1296         case QPainter::CompositionMode_Source:
1297             cg_mode = kCGCompositeModeCopy;
1298             break;
1299         case QPainter::CompositionMode_Destination:
1300             cg_mode = CGCompositeMode(-1);
1301             break;
1302         case QPainter::CompositionMode_SourceIn:
1303             cg_mode = kCGCompositeModeSourceIn;
1304             break;
1305         case QPainter::CompositionMode_DestinationIn:
1306             cg_mode = kCGCompositeModeDestinationIn;
1307             break;
1308         case QPainter::CompositionMode_SourceOut:
1309             cg_mode = kCGCompositeModeSourceOut;
1310             break;
1311         case QPainter::CompositionMode_DestinationOut:
1312             cg_mode = kCGCompositeModeDestinationOut;
1313             break;
1314         case QPainter::CompositionMode_SourceAtop:
1315             cg_mode = kCGCompositeModeSourceAtop;
1316             break;
1317         case QPainter::CompositionMode_DestinationAtop:
1318             cg_mode = kCGCompositeModeDestinationAtop;
1319             break;
1320         case QPainter::CompositionMode_Xor:
1321             cg_mode = kCGCompositeModeXOR;
1322             break;
1323         }
1324         if (cg_mode > -1)
1325             CGContextSetCompositeOperation(d_func()->hd, CGCompositeMode(cg_mode));
1326     } else {
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;
1331             switch (mode) {
1332             case QPainter::CompositionMode_Multiply:
1333                 cg_mode = kCGBlendModeMultiply;
1334                 break;
1335             case QPainter::CompositionMode_Screen:
1336                 cg_mode = kCGBlendModeScreen;
1337                 break;
1338             case QPainter::CompositionMode_Overlay:
1339                 cg_mode = kCGBlendModeOverlay;
1340                 break;
1341             case QPainter::CompositionMode_Darken:
1342                 cg_mode = kCGBlendModeDarken;
1343                 break;
1344             case QPainter::CompositionMode_Lighten:
1345                 cg_mode = kCGBlendModeLighten;
1346                 break;
1347             case QPainter::CompositionMode_ColorDodge:
1348                 cg_mode = kCGBlendModeColorDodge;
1349                 break;
1350             case QPainter::CompositionMode_ColorBurn:
1351                 cg_mode = kCGBlendModeColorBurn;
1352                 break;
1353             case QPainter::CompositionMode_HardLight:
1354                 cg_mode = kCGBlendModeHardLight;
1355                 break;
1356             case QPainter::CompositionMode_SoftLight:
1357                 cg_mode = kCGBlendModeSoftLight;
1358                 break;
1359             case QPainter::CompositionMode_Difference:
1360                 cg_mode = kCGBlendModeDifference;
1361                 break;
1362             case QPainter::CompositionMode_Exclusion:
1363                 cg_mode = kCGBlendModeExclusion;
1364                 break;
1365             case QPainter::CompositionMode_Plus:
1366                 needPrivateAPI = true;
1367                 cg_mode = kCGCompositeModePlusLighter;
1368                 break;
1369             default:
1370                 break;
1371             }
1372             if (!needPrivateAPI)
1373                 CGContextSetBlendMode(d_func()->hd, CGBlendMode(cg_mode));
1374             else
1375                 CGContextSetCompositeOperation(d_func()->hd, CGCompositeMode(cg_mode));
1376         }
1377 #endif
1378     }
1379 }
1380
1381 void
1382 QCoreGraphicsPaintEngine::updateRenderHints(QPainter::RenderHints hints)
1383 {
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);
1389     } else {
1390         CGContextSetInterpolationQuality(d->hd, (hints & QPainter::SmoothPixmapTransform) ?
1391                                          kCGInterpolationHigh : kCGInterpolationNone);
1392     }
1393     bool textAntialiasing = (hints & QPainter::TextAntialiasing) == QPainter::TextAntialiasing;
1394     if (!textAntialiasing || d->disabledSmoothFonts) {
1395         d->disabledSmoothFonts = !textAntialiasing;
1396         CGContextSetShouldSmoothFonts(d->hd, textAntialiasing);
1397     }
1398 }
1399
1400 /*
1401     Returns the size of one device pixel in user-space coordinates.
1402 */
1403 QPointF QCoreGraphicsPaintEnginePrivate::devicePixelSize(CGContextRef)
1404 {
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()));
1408 }
1409
1410 /*
1411     Adjusts the pen width so we get correct line widths in the
1412     non-transformed, aliased case.
1413 */
1414 float QCoreGraphicsPaintEnginePrivate::adjustPenWidth(float penWidth)
1415 {
1416     Q_Q(QCoreGraphicsPaintEngine);
1417     float ret = penWidth;
1418     if (!complexXForm && !(q->state->renderHints() & QPainter::Antialiasing)) {
1419         if (penWidth < 2)
1420             ret = 1;
1421         else if (penWidth < 3)
1422             ret = 1.5;
1423         else
1424             ret = penWidth -1;
1425     }
1426     return ret;
1427 }
1428
1429 void
1430 QCoreGraphicsPaintEnginePrivate::setStrokePen(const QPen &pen)
1431 {
1432     //pencap
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()));
1440
1441     //join
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());
1449
1450     //pen style
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);
1474     }
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)) {
1479             if((i%2))
1480                 linedashes[i] += cglinewidth/2;
1481             else
1482                 linedashes[i] -= cglinewidth/2;
1483         }
1484     }
1485     CGContextSetLineDash(hd, pen.dashOffset() * cglinewidth, linedashes.data(), linedashes.size());
1486
1487     // color
1488     CGContextSetStrokeColorWithColor(hd, cgColorForQColor(pen.color(), pdev));
1489 }
1490
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)
1494 {
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];
1514 }
1515
1516 void QCoreGraphicsPaintEnginePrivate::setFillBrush(const QPointF &offset)
1517 {
1518     // pattern
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);
1525
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 *>(&current.brush),
1529                     1, domain, 4, 0, &callbacks);
1530
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);
1538             } else {
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);
1547             }
1548
1549             CGFunctionRelease(fill_func);
1550         }
1551     } else
1552 #endif
1553     if(bs != Qt::SolidPattern && bs != Qt::NoBrush
1554 #ifndef QT_MAC_USE_NATIVE_GRADIENTS
1555        && (bs < Qt::LinearGradientPattern || bs > Qt::ConicalGradientPattern)
1556 #endif
1557         )
1558     {
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();
1571             }
1572         } else {
1573             qpattern->as_mask = true;
1574
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();
1581         }
1582         int width = qpattern->width(), height = qpattern->height();
1583         qpattern->foreground = current.brush.color();
1584
1585         CGColorSpaceRef fill_colorspace = CGColorSpaceCreatePattern(base_colorspace);
1586         CGContextSetFillColorSpace(hd, fill_colorspace);
1587
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());
1591
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);
1600
1601         CGPatternRelease(fill_pattern);
1602         CGColorSpaceRelease(fill_colorspace);
1603     } else if(bs != Qt::NoBrush) {
1604         CGContextSetFillColorWithColor(hd, cgColorForQColor(current.brush.color(), pdev));
1605     }
1606 }
1607
1608 void
1609 QCoreGraphicsPaintEnginePrivate::setClip(const QRegion *rgn)
1610 {
1611     Q_Q(QCoreGraphicsPaintEngine);
1612     if(hd) {
1613         resetClip();
1614         QRegion sysClip = q->systemClip();
1615         if(!sysClip.isEmpty())
1616             qt_mac_clip_cg(hd, sysClip, &orig_xform);
1617         if(rgn)
1618             qt_mac_clip_cg(hd, *rgn, 0);
1619     }
1620 }
1621
1622 struct qt_mac_cg_transform_path {
1623     CGMutablePathRef path;
1624     CGAffineTransform transform;
1625 };
1626
1627 void qt_mac_cg_transform_path_apply(void *info, const CGPathElement *element)
1628 {
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);
1634         break;
1635     case kCGPathElementAddLineToPoint:
1636         CGPathAddLineToPoint(t->path, &t->transform, element->points[0].x, element->points[0].y);
1637         break;
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);
1641         break;
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);
1646         break;
1647     case kCGPathElementCloseSubpath:
1648         CGPathCloseSubpath(t->path);
1649         break;
1650     default:
1651         qDebug() << "Unhandled path transform type: " << element->type;
1652     }
1653 }
1654
1655 void QCoreGraphicsPaintEnginePrivate::drawPath(uchar ops, CGMutablePathRef path)
1656 {
1657     Q_Q(QCoreGraphicsPaintEngine);
1658     Q_ASSERT((ops & (CGFill | CGEOFill)) != (CGFill | CGEOFill)); //can't really happen
1659     if((ops & (CGFill | CGEOFill))) {
1660         if (shading) {
1661             Q_ASSERT(path);
1662             CGContextBeginPath(hd);
1663             CGContextAddPath(hd, path);
1664             saveGraphicsState();
1665             if (ops & CGFill)
1666                 CGContextClip(hd);
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));
1675             }
1676             CGContextDrawShading(hd, shading);
1677             restoreGraphicsState();
1678             ops &= ~CGFill;
1679             ops &= ~CGEOFill;
1680         } else if (current.brush.style() == Qt::NoBrush) {
1681             ops &= ~CGFill;
1682             ops &= ~CGEOFill;
1683         }
1684     }
1685     if((ops & CGStroke) && current.pen.style() == Qt::NoPen)
1686         ops &= ~CGStroke;
1687
1688     if(ops & (CGEOFill | CGFill)) {
1689         CGContextBeginPath(hd);
1690         CGContextAddPath(hd, path);
1691         if (ops & CGEOFill) {
1692             CGContextEOFillPath(hd);
1693         } else {
1694             CGContextFillPath(hd);
1695         }
1696     }
1697
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);
1705
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)
1714                 ; // Do nothing.
1715             else
1716                 CGContextTranslateCTM(hd, 0, double(pixelSize.y()) * 0.1);
1717         }
1718
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);
1725             else
1726                 CGContextSetLineWidth(hd, cosmeticPenSize);
1727         }
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);
1737         } else {
1738             CGContextAddPath(hd, path);
1739         }
1740
1741         CGContextStrokePath(hd);
1742         if (needContextSave)
1743             restoreGraphicsState();
1744     }
1745 }
1746
1747 QT_END_NAMESPACE