1 /****************************************************************************
2 **
3 ** Copyright (C) 2015 The Qt Company Ltd.
4 ** Contact: http://www.qt.io/licensing/
5 **
6 ** This file is part of the QtGui module of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and The Qt Company. For licensing terms
14 ** and conditions see http://www.qt.io/terms-conditions. For further
15 ** information use the contact form at http://www.qt.io/contact-us.
16 **
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 2.1 or version 3 as published by the Free
20 ** Software Foundation and appearing in the file LICENSE.LGPLv21 and
21 ** LICENSE.LGPLv3 included in the packaging of this file. Please review the
22 ** following information to ensure the GNU Lesser General Public License
23 ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
24 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
25 **
26 ** As a special exception, The Qt Company gives you certain additional
27 ** rights. These rights are described in The Qt Company LGPL Exception
28 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
29 **
30 ** GNU General Public License Usage
31 ** Alternatively, this file may be used under the terms of the GNU
32 ** General Public License version 3.0 as published by the Free Software
33 ** Foundation and appearing in the file LICENSE.GPL included in the
34 ** packaging of this file. Please review the following information to
35 ** ensure the GNU General Public License version 3.0 requirements will be
36 ** met: http://www.gnu.org/copyleft/gpl.html.
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
QMacCGContext(QPainter * p)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 || devType == QInternal::Pixmap || devType == QInternal::Image)) {
104
105 extern CGColorSpaceRef qt_mac_colorSpaceForDeviceType(const QPaintDevice *paintDevice);
106 CGColorSpaceRef colorspace = qt_mac_colorSpaceForDeviceType(pe->paintDevice());
107 uint flags = kCGImageAlphaPremultipliedFirst;
108 #ifdef kCGBitmapByteOrder32Host //only needed because CGImage.h added symbols in the minor version
109 flags |= kCGBitmapByteOrder32Host;
110 #endif
111 const QImage *image = (const QImage *) pe->paintDevice();
112
113 context = CGBitmapContextCreate((void *) image->bits(), image->width(), image->height(),
114 8, image->bytesPerLine(), colorspace, flags);
115
116 CGContextTranslateCTM(context, 0, image->height());
117 CGContextScaleCTM(context, 1, -1);
118
119 if (devType == QInternal::Widget) {
120 QRegion clip = p->paintEngine()->systemClip();
121 QTransform native = p->deviceTransform();
122 QTransform logical = p->combinedTransform();
123
124 if (p->hasClipping()) {
125 QRegion r = p->clipRegion();
126 r.translate(native.dx(), native.dy());
127 if (clip.isEmpty())
128 clip = r;
129 else
130 clip &= r;
131 }
132 qt_mac_clip_cg(context, clip, 0);
133
134 CGContextTranslateCTM(context, native.dx(), native.dy());
135 }
136 } else {
137 CGContextRetain(context);
138 }
139 }
140
141
142 /*****************************************************************************
143 QCoreGraphicsPaintEngine utility functions
144 *****************************************************************************/
145
146 //conversion
qt_mac_convert_color_to_cg(int c)147 inline static float qt_mac_convert_color_to_cg(int c) { return ((float)c * 1000 / 255) / 1000; }
qt_mac_convert_color_from_cg(float c)148 inline static int qt_mac_convert_color_from_cg(float c) { return qRound(c * 255); }
qt_mac_convert_transform_to_cg(const QTransform & t)149 CGAffineTransform qt_mac_convert_transform_to_cg(const QTransform &t) {
150 return CGAffineTransformMake(t.m11(), t.m12(), t.m21(), t.m22(), t.dx(), t.dy());
151 }
152
qt_mac_colorSpaceForDeviceType(const QPaintDevice * paintDevice)153 CGColorSpaceRef qt_mac_colorSpaceForDeviceType(const QPaintDevice *paintDevice)
154 {
155 bool isWidget = (paintDevice->devType() == QInternal::Widget);
156 return QCoreGraphicsPaintEngine::macDisplayColorSpace(isWidget ? static_cast<const QWidget *>(paintDevice)
157 : 0);
158 }
159
cgColorForQColor(const QColor & col,QPaintDevice * pdev)160 inline static QCFType<CGColorRef> cgColorForQColor(const QColor &col, QPaintDevice *pdev)
161 {
162 CGFloat components[] = {
163 qt_mac_convert_color_to_cg(col.red()),
164 qt_mac_convert_color_to_cg(col.green()),
165 qt_mac_convert_color_to_cg(col.blue()),
166 qt_mac_convert_color_to_cg(col.alpha())
167 };
168 return CGColorCreate(qt_mac_colorSpaceForDeviceType(pdev), components);
169 }
170
171 // There's architectural problems with using native gradients
172 // on the Mac at the moment, so disable them.
173 // #define QT_MAC_USE_NATIVE_GRADIENTS
174
175 #ifdef QT_MAC_USE_NATIVE_GRADIENTS
drawGradientNatively(const QGradient * gradient)176 static bool drawGradientNatively(const QGradient *gradient)
177 {
178 return gradient->spread() == QGradient::PadSpread;
179 }
180
181 // gradiant callback
qt_mac_color_gradient_function(void * info,const CGFloat * in,CGFloat * out)182 static void qt_mac_color_gradient_function(void *info, const CGFloat *in, CGFloat *out)
183 {
184 QBrush *brush = static_cast<QBrush *>(info);
185 Q_ASSERT(brush && brush->gradient());
186
187 const QGradientStops stops = brush->gradient()->stops();
188 const int n = stops.count();
189 Q_ASSERT(n >= 1);
190 const QGradientStop *begin = stops.constBegin();
191 const QGradientStop *end = begin + n;
192
193 qreal p = in[0];
194 const QGradientStop *i = begin;
195 while (i != end && i->first < p)
196 ++i;
197
198 QRgb c;
199 if (i == begin) {
200 c = begin->second.rgba();
201 } else if (i == end) {
202 c = (end - 1)->second.rgba();
203 } else {
204 const QGradientStop &s1 = *(i - 1);
205 const QGradientStop &s2 = *i;
206 qreal p1 = s1.first;
207 qreal p2 = s2.first;
208 QRgb c1 = s1.second.rgba();
209 QRgb c2 = s2.second.rgba();
210 int idist = 256 * (p - p1) / (p2 - p1);
211 int dist = 256 - idist;
212 c = qRgba(INTERPOLATE_PIXEL_256(qRed(c1), dist, qRed(c2), idist),
213 INTERPOLATE_PIXEL_256(qGreen(c1), dist, qGreen(c2), idist),
214 INTERPOLATE_PIXEL_256(qBlue(c1), dist, qBlue(c2), idist),
215 INTERPOLATE_PIXEL_256(qAlpha(c1), dist, qAlpha(c2), idist));
216 }
217
218 out[0] = qt_mac_convert_color_to_cg(qRed(c));
219 out[1] = qt_mac_convert_color_to_cg(qGreen(c));
220 out[2] = qt_mac_convert_color_to_cg(qBlue(c));
221 out[3] = qt_mac_convert_color_to_cg(qAlpha(c));
222 }
223 #endif
224
225 //clipping handling
resetClip()226 void QCoreGraphicsPaintEnginePrivate::resetClip()
227 {
228 static bool inReset = false;
229 if (inReset)
230 return;
231 inReset = true;
232
233 CGAffineTransform old_xform = CGContextGetCTM(hd);
234
235 //setup xforms
236 CGContextConcatCTM(hd, CGAffineTransformInvert(old_xform));
237 while (stackCount > 0) {
238 restoreGraphicsState();
239 }
240 saveGraphicsState();
241 inReset = false;
242 //reset xforms
243 CGContextConcatCTM(hd, CGAffineTransformInvert(CGContextGetCTM(hd)));
244 CGContextConcatCTM(hd, old_xform);
245 }
246
qt_mac_compose_rect(const QRectF & r,float off=0)247 static CGRect qt_mac_compose_rect(const QRectF &r, float off=0)
248 {
249 return CGRectMake(r.x()+off, r.y()+off, r.width(), r.height());
250 }
251
qt_mac_compose_path(const QPainterPath & p,float off=0)252 static CGMutablePathRef qt_mac_compose_path(const QPainterPath &p, float off=0)
253 {
254 CGMutablePathRef ret = CGPathCreateMutable();
255 QPointF startPt;
256 for (int i=0; i<p.elementCount(); ++i) {
257 const QPainterPath::Element &elm = p.elementAt(i);
258 switch (elm.type) {
259 case QPainterPath::MoveToElement:
260 if(i > 0
261 && p.elementAt(i - 1).x == startPt.x()
262 && p.elementAt(i - 1).y == startPt.y())
263 CGPathCloseSubpath(ret);
264 startPt = QPointF(elm.x, elm.y);
265 CGPathMoveToPoint(ret, 0, elm.x+off, elm.y+off);
266 break;
267 case QPainterPath::LineToElement:
268 CGPathAddLineToPoint(ret, 0, elm.x+off, elm.y+off);
269 break;
270 case QPainterPath::CurveToElement:
271 Q_ASSERT(p.elementAt(i+1).type == QPainterPath::CurveToDataElement);
272 Q_ASSERT(p.elementAt(i+2).type == QPainterPath::CurveToDataElement);
273 CGPathAddCurveToPoint(ret, 0,
274 elm.x+off, elm.y+off,
275 p.elementAt(i+1).x+off, p.elementAt(i+1).y+off,
276 p.elementAt(i+2).x+off, p.elementAt(i+2).y+off);
277 i+=2;
278 break;
279 default:
280 qFatal("QCoreGraphicsPaintEngine::drawPath(), unhandled type: %d", elm.type);
281 break;
282 }
283 }
284 if(!p.isEmpty()
285 && p.elementAt(p.elementCount() - 1).x == startPt.x()
286 && p.elementAt(p.elementCount() - 1).y == startPt.y())
287 CGPathCloseSubpath(ret);
288 return ret;
289 }
290
291 CGColorSpaceRef QCoreGraphicsPaintEngine::m_genericColorSpace = 0;
292 QHash<QWidget*, CGColorSpaceRef> QCoreGraphicsPaintEngine::m_displayColorSpaceHash; // window -> color space
293 bool QCoreGraphicsPaintEngine::m_postRoutineRegistered = false;
294
macGenericColorSpace()295 CGColorSpaceRef QCoreGraphicsPaintEngine::macGenericColorSpace()
296 {
297 #if 0
298 if (!m_genericColorSpace) {
299 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
300 if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_4) {
301 m_genericColorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
302 } else
303 #endif
304 {
305 m_genericColorSpace = CGColorSpaceCreateDeviceRGB();
306 }
307 if (!m_postRoutineRegistered) {
308 m_postRoutineRegistered = true;
309 qAddPostRoutine(QCoreGraphicsPaintEngine::cleanUpMacColorSpaces);
310 }
311 }
312 return m_genericColorSpace;
313 #else
314 // Just return the main display colorspace for the moment.
315 return macDisplayColorSpace();
316 #endif
317 }
318
macDisplayColorSpace(const QWidget * widget)319 CGColorSpaceRef QCoreGraphicsPaintEngine::macDisplayColorSpace(const QWidget *widget)
320 {
321 // The color space depends on which screen the widget's window is on.
322 // widget == 0 is a spacial case where we use the main display.
323 QWidget *window = widget ? widget->window() : 0;
324
325 // Check for cached color space and return if found.
326 if (m_displayColorSpaceHash.contains(window))
327 return m_displayColorSpaceHash.value(window);
328
329 // Find which display the window is on.
330 CGDirectDisplayID displayID;
331 if (window == 0) {
332 displayID = CGMainDisplayID();
333 } else {
334 const QRect &qrect = 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 displayID = CGMainDisplayID();
340 }
341
342 // Get the color space from the display profile.
343 CGColorSpaceRef colorSpace = 0;
344 colorSpace = CGDisplayCopyColorSpace(displayID);
345 // Fallback: use generic DeviceRGB
346 if (colorSpace == 0)
347 colorSpace = CGColorSpaceCreateDeviceRGB();
348
349 // Install cleanup routines
350 if (!m_postRoutineRegistered) {
351 m_postRoutineRegistered = true;
352 qAddPostRoutine(QCoreGraphicsPaintEngine::cleanUpMacColorSpaces);
353 }
354
355 // Cache and return.
356 m_displayColorSpaceHash.insert(window, colorSpace);
357 return colorSpace;
358 }
359
cleanUpMacColorSpaces()360 void QCoreGraphicsPaintEngine::cleanUpMacColorSpaces()
361 {
362 if (m_genericColorSpace) {
363 CFRelease(m_genericColorSpace);
364 m_genericColorSpace = 0;
365 }
366 QHash<QWidget*, CGColorSpaceRef>::const_iterator it = m_displayColorSpaceHash.constBegin();
367 while (it != m_displayColorSpaceHash.constEnd()) {
368 if (it.value())
369 CFRelease(it.value());
370 ++it;
371 }
372 m_displayColorSpaceHash.clear();
373 }
374
qt_mac_clip_cg(CGContextRef hd,const QRegion & rgn,CGAffineTransform * orig_xform)375 void qt_mac_clip_cg(CGContextRef hd, const QRegion &rgn, CGAffineTransform *orig_xform)
376 {
377 CGAffineTransform old_xform = CGAffineTransformIdentity;
378 if(orig_xform) { //setup xforms
379 old_xform = CGContextGetCTM(hd);
380 CGContextConcatCTM(hd, CGAffineTransformInvert(old_xform));
381 CGContextConcatCTM(hd, *orig_xform);
382 }
383
384 //do the clipping
385 CGContextBeginPath(hd);
386 if(rgn.isEmpty()) {
387 CGContextAddRect(hd, CGRectMake(0, 0, 0, 0));
388 } else {
389 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
390 if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5) {
391 QCFType<HIMutableShapeRef> shape = rgn.toHIMutableShape();
392 Q_ASSERT(!HIShapeIsEmpty(shape));
393 HIShapeReplacePathInCGContext(shape, hd);
394 } else
395 #endif
396 {
397 QVector<QRect> rects = rgn.rects();
398 const int count = rects.size();
399 for(int i = 0; i < count; i++) {
400 const QRect &r = rects[i];
401 CGRect mac_r = CGRectMake(r.x(), r.y(), r.width(), r.height());
402 CGContextAddRect(hd, mac_r);
403 }
404 }
405
406 }
407 CGContextClip(hd);
408
409 if(orig_xform) {//reset xforms
410 CGContextConcatCTM(hd, CGAffineTransformInvert(CGContextGetCTM(hd)));
411 CGContextConcatCTM(hd, old_xform);
412 }
413 }
414
415
416 //pattern handling (tiling)
417 #if 1
418 # define QMACPATTERN_MASK_MULTIPLIER 32
419 #else
420 # define QMACPATTERN_MASK_MULTIPLIER 1
421 #endif
422 class QMacPattern
423 {
424 public:
QMacPattern()425 QMacPattern() : as_mask(false), pdev(0), image(0) { data.bytes = 0; }
~QMacPattern()426 ~QMacPattern() { CGImageRelease(image); }
width()427 int width() {
428 if(image)
429 return CGImageGetWidth(image);
430 if(data.bytes)
431 return 8*QMACPATTERN_MASK_MULTIPLIER;
432 return data.pixmap.width();
433 }
height()434 int height() {
435 if(image)
436 return CGImageGetHeight(image);
437 if(data.bytes)
438 return 8*QMACPATTERN_MASK_MULTIPLIER;
439 return data.pixmap.height();
440 }
441
442 //input
443 QColor foreground;
444 bool as_mask;
445 struct {
446 QPixmap pixmap;
447 const uchar *bytes;
448 } data;
449 QPaintDevice *pdev;
450 //output
451 CGImageRef image;
452 };
qt_mac_draw_pattern(void * info,CGContextRef c)453 static void qt_mac_draw_pattern(void *info, CGContextRef c)
454 {
455 QMacPattern *pat = (QMacPattern*)info;
456 int w = 0, h = 0;
457 bool isBitmap = (pat->data.pixmap.depth() == 1);
458 if(!pat->image) { //lazy cache
459 if(pat->as_mask) {
460 Q_ASSERT(pat->data.bytes);
461 w = h = 8;
462 #if (QMACPATTERN_MASK_MULTIPLIER == 1)
463 CGDataProviderRef provider = CGDataProviderCreateWithData(0, pat->data.bytes, w*h, 0);
464 pat->image = CGImageMaskCreate(w, h, 1, 1, 1, provider, 0, false);
465 CGDataProviderRelease(provider);
466 #else
467 const int numBytes = (w*h)/sizeof(uchar);
468 uchar xor_bytes[numBytes];
469 for(int i = 0; i < numBytes; ++i)
470 xor_bytes[i] = pat->data.bytes[i] ^ 0xFF;
471 CGDataProviderRef provider = CGDataProviderCreateWithData(0, xor_bytes, w*h, 0);
472 CGImageRef swatch = CGImageMaskCreate(w, h, 1, 1, 1, provider, 0, false);
473 CGDataProviderRelease(provider);
474
475 const QColor c0(0, 0, 0, 0), c1(255, 255, 255, 255);
476 QPixmap pm(w*QMACPATTERN_MASK_MULTIPLIER, h*QMACPATTERN_MASK_MULTIPLIER);
477 pm.fill(c0);
478 CGContextRef pm_ctx = qt_mac_cg_context(&pm);
479 CGContextSetFillColorWithColor(c, cgColorForQColor(c1, pat->pdev));
480 CGRect rect = CGRectMake(0, 0, w, h);
481 for(int x = 0; x < QMACPATTERN_MASK_MULTIPLIER; ++x) {
482 rect.origin.x = x * w;
483 for(int y = 0; y < QMACPATTERN_MASK_MULTIPLIER; ++y) {
484 rect.origin.y = y * h;
485 qt_mac_drawCGImage(pm_ctx, &rect, swatch);
486 }
487 }
488 pat->image = qt_mac_create_imagemask(pm, pm.rect());
489 CGImageRelease(swatch);
490 CGContextRelease(pm_ctx);
491 w *= QMACPATTERN_MASK_MULTIPLIER;
492 h *= QMACPATTERN_MASK_MULTIPLIER;
493 #endif
494 } else {
495 w = pat->data.pixmap.width();
496 h = pat->data.pixmap.height();
497 if (isBitmap)
498 pat->image = qt_mac_create_imagemask(pat->data.pixmap, pat->data.pixmap.rect());
499 else
500 pat->image = (CGImageRef)pat->data.pixmap.macCGHandle();
501 }
502 } else {
503 w = CGImageGetWidth(pat->image);
504 h = CGImageGetHeight(pat->image);
505 }
506
507 //draw
508 bool needRestore = false;
509 if (CGImageIsMask(pat->image)) {
510 CGContextSaveGState(c);
511 CGContextSetFillColorWithColor(c, cgColorForQColor(pat->foreground, pat->pdev));
512 }
513 CGRect rect = CGRectMake(0, 0, w, h);
514 qt_mac_drawCGImage(c, &rect, pat->image);
515 if(needRestore)
516 CGContextRestoreGState(c);
517 }
qt_mac_dispose_pattern(void * info)518 static void qt_mac_dispose_pattern(void *info)
519 {
520 QMacPattern *pat = (QMacPattern*)info;
521 delete pat;
522 }
523
524 /*****************************************************************************
525 QCoreGraphicsPaintEngine member functions
526 *****************************************************************************/
527
qt_mac_cg_features()528 inline static QPaintEngine::PaintEngineFeatures qt_mac_cg_features()
529 {
530 return QPaintEngine::PaintEngineFeatures(QPaintEngine::AllFeatures & ~QPaintEngine::PaintOutsidePaintEvent
531 & ~QPaintEngine::PerspectiveTransform
532 & ~QPaintEngine::ConicalGradientFill
533 & ~QPaintEngine::LinearGradientFill
534 & ~QPaintEngine::RadialGradientFill
535 & ~QPaintEngine::BrushStroke);
536 }
537
QCoreGraphicsPaintEngine()538 QCoreGraphicsPaintEngine::QCoreGraphicsPaintEngine()
539 : QPaintEngine(*(new QCoreGraphicsPaintEnginePrivate), qt_mac_cg_features())
540 {
541 }
542
QCoreGraphicsPaintEngine(QPaintEnginePrivate & dptr)543 QCoreGraphicsPaintEngine::QCoreGraphicsPaintEngine(QPaintEnginePrivate &dptr)
544 : QPaintEngine(dptr, qt_mac_cg_features())
545 {
546 }
547
~QCoreGraphicsPaintEngine()548 QCoreGraphicsPaintEngine::~QCoreGraphicsPaintEngine()
549 {
550 }
551
552 bool
begin(QPaintDevice * pdev)553 QCoreGraphicsPaintEngine::begin(QPaintDevice *pdev)
554 {
555 Q_D(QCoreGraphicsPaintEngine);
556 if(isActive()) { // already active painting
557 qWarning("QCoreGraphicsPaintEngine::begin: Painter already active");
558 return false;
559 }
560
561 //initialization
562 d->pdev = pdev;
563 d->complexXForm = false;
564 d->cosmeticPen = QCoreGraphicsPaintEnginePrivate::CosmeticSetPenWidth;
565 d->cosmeticPenSize = 1;
566 d->current.clipEnabled = false;
567 d->pixelSize = QPoint(1,1);
568 d->hd = qt_mac_cg_context(pdev);
569 if(d->hd) {
570 d->saveGraphicsState();
571 d->orig_xform = CGContextGetCTM(d->hd);
572 if (d->shading) {
573 CGShadingRelease(d->shading);
574 d->shading = 0;
575 }
576 d->setClip(0); //clear the context's clipping
577 }
578
579 setActive(true);
580
581 if(d->pdev->devType() == QInternal::Widget) { // device is a widget
582 QWidget *w = (QWidget*)d->pdev;
583 bool unclipped = w->testAttribute(Qt::WA_PaintUnclipped);
584
585 if((w->windowType() == Qt::Desktop)) {
586 if(!unclipped)
587 qWarning("QCoreGraphicsPaintEngine::begin: Does not support clipped desktop on Mac OS X");
588 // ## need to do [qt_mac_window_for(w) makeKeyAndOrderFront]; (need to rename the file)
589 } else if(unclipped) {
590 qWarning("QCoreGraphicsPaintEngine::begin: Does not support unclipped painting");
591 }
592 } else if(d->pdev->devType() == QInternal::Pixmap) { // device is a pixmap
593 QPixmap *pm = (QPixmap*)d->pdev;
594 if(pm->isNull()) {
595 qWarning("QCoreGraphicsPaintEngine::begin: Cannot paint null pixmap");
596 end();
597 return false;
598 }
599 }
600
601 setDirty(QPaintEngine::DirtyPen);
602 setDirty(QPaintEngine::DirtyBrush);
603 setDirty(QPaintEngine::DirtyBackground);
604 setDirty(QPaintEngine::DirtyHints);
605 return true;
606 }
607
608 bool
end()609 QCoreGraphicsPaintEngine::end()
610 {
611 Q_D(QCoreGraphicsPaintEngine);
612 setActive(false);
613 if(d->pdev->devType() == QInternal::Widget && static_cast<QWidget*>(d->pdev)->windowType() == Qt::Desktop) {
614 #ifndef QT_MAC_USE_COCOA
615 HideWindow(qt_mac_window_for(static_cast<QWidget*>(d->pdev)));
616 #else
617 // // ### need to do [qt_mac_window_for(static_cast<QWidget *>(d->pdev)) orderOut]; (need to rename)
618 #endif
619
620 }
621 if(d->shading) {
622 CGShadingRelease(d->shading);
623 d->shading = 0;
624 }
625 d->pdev = 0;
626 if(d->hd) {
627 d->restoreGraphicsState();
628 CGContextSynchronize(d->hd);
629 CGContextRelease(d->hd);
630 d->hd = 0;
631 }
632 return true;
633 }
634
635 void
updateState(const QPaintEngineState & state)636 QCoreGraphicsPaintEngine::updateState(const QPaintEngineState &state)
637 {
638 Q_D(QCoreGraphicsPaintEngine);
639 QPaintEngine::DirtyFlags flags = state.state();
640
641 if (flags & DirtyTransform)
642 updateMatrix(state.transform());
643
644 if (flags & DirtyClipEnabled) {
645 if (state.isClipEnabled())
646 updateClipPath(painter()->clipPath(), Qt::ReplaceClip);
647 else
648 updateClipPath(QPainterPath(), Qt::NoClip);
649 }
650
651 if (flags & DirtyClipPath) {
652 updateClipPath(state.clipPath(), state.clipOperation());
653 } else if (flags & DirtyClipRegion) {
654 updateClipRegion(state.clipRegion(), state.clipOperation());
655 }
656
657 // If the clip has changed we need to update all other states
658 // too, since they are included in the system context on OSX,
659 // and changing the clip resets that context back to scratch.
660 if (flags & (DirtyClipPath | DirtyClipRegion | DirtyClipEnabled))
661 flags |= AllDirty;
662
663 if (flags & DirtyPen)
664 updatePen(state.pen());
665 if (flags & (DirtyBrush|DirtyBrushOrigin))
666 updateBrush(state.brush(), state.brushOrigin());
667 if (flags & DirtyFont)
668 updateFont(state.font());
669 if (flags & DirtyOpacity)
670 updateOpacity(state.opacity());
671 if (flags & DirtyHints)
672 updateRenderHints(state.renderHints());
673 if (flags & DirtyCompositionMode)
674 updateCompositionMode(state.compositionMode());
675
676 if (flags & (DirtyPen | DirtyTransform)) {
677 if (!d->current.pen.isCosmetic()) {
678 d->cosmeticPen = QCoreGraphicsPaintEnginePrivate::CosmeticNone;
679 } else if (d->current.transform.m11() < d->current.transform.m22()-1.0 ||
680 d->current.transform.m11() > d->current.transform.m22()+1.0) {
681 d->cosmeticPen = QCoreGraphicsPaintEnginePrivate::CosmeticTransformPath;
682 d->cosmeticPenSize = d->adjustPenWidth(d->current.pen.widthF());
683 if (!d->cosmeticPenSize)
684 d->cosmeticPenSize = 1.0;
685 } else {
686 d->cosmeticPen = QCoreGraphicsPaintEnginePrivate::CosmeticSetPenWidth;
687 static const float sqrt2 = sqrt(2);
688 qreal width = d->current.pen.widthF();
689 if (!width)
690 width = 1;
691 d->cosmeticPenSize = sqrt(pow(d->pixelSize.y(), 2) + pow(d->pixelSize.x(), 2)) / sqrt2 * width;
692 }
693 }
694 }
695
696 void
updatePen(const QPen & pen)697 QCoreGraphicsPaintEngine::updatePen(const QPen &pen)
698 {
699 Q_D(QCoreGraphicsPaintEngine);
700 Q_ASSERT(isActive());
701 d->current.pen = pen;
702 d->setStrokePen(pen);
703 }
704
705 void
updateBrush(const QBrush & brush,const QPointF & brushOrigin)706 QCoreGraphicsPaintEngine::updateBrush(const QBrush &brush, const QPointF &brushOrigin)
707 {
708 Q_D(QCoreGraphicsPaintEngine);
709 Q_ASSERT(isActive());
710 d->current.brush = brush;
711
712 #ifdef QT_MAC_USE_NATIVE_GRADIENTS
713 // Quartz supports only pad spread
714 if (const QGradient *gradient = brush.gradient()) {
715 if (drawGradientNatively(gradient)) {
716 gccaps |= QPaintEngine::LinearGradientFill | QPaintEngine::RadialGradientFill;
717 } else {
718 gccaps &= ~(QPaintEngine::LinearGradientFill | QPaintEngine::RadialGradientFill);
719 }
720 }
721 #endif
722
723 if (d->shading) {
724 CGShadingRelease(d->shading);
725 d->shading = 0;
726 }
727 d->setFillBrush(brushOrigin);
728 }
729
730 void
updateOpacity(qreal opacity)731 QCoreGraphicsPaintEngine::updateOpacity(qreal opacity)
732 {
733 Q_D(QCoreGraphicsPaintEngine);
734 CGContextSetAlpha(d->hd, opacity);
735 }
736
737 void
updateFont(const QFont &)738 QCoreGraphicsPaintEngine::updateFont(const QFont &)
739 {
740 Q_D(QCoreGraphicsPaintEngine);
741 Q_ASSERT(isActive());
742 updatePen(d->current.pen);
743 }
744
745 void
updateMatrix(const QTransform & transform)746 QCoreGraphicsPaintEngine::updateMatrix(const QTransform &transform)
747 {
748 Q_D(QCoreGraphicsPaintEngine);
749 Q_ASSERT(isActive());
750
751 if (qt_is_nan(transform.m11()) || qt_is_nan(transform.m12()) || qt_is_nan(transform.m13())
752 || qt_is_nan(transform.m21()) || qt_is_nan(transform.m22()) || qt_is_nan(transform.m23())
753 || qt_is_nan(transform.m31()) || qt_is_nan(transform.m32()) || qt_is_nan(transform.m33()))
754 return;
755
756 d->current.transform = transform;
757 d->setTransform(transform.isIdentity() ? 0 : &transform);
758 d->complexXForm = (transform.m11() != 1 || transform.m22() != 1
759 || transform.m12() != 0 || transform.m21() != 0);
760 d->pixelSize = d->devicePixelSize(d->hd);
761 }
762
763 void
updateClipPath(const QPainterPath & p,Qt::ClipOperation op)764 QCoreGraphicsPaintEngine::updateClipPath(const QPainterPath &p, Qt::ClipOperation op)
765 {
766 Q_D(QCoreGraphicsPaintEngine);
767 Q_ASSERT(isActive());
768 if(op == Qt::NoClip) {
769 if(d->current.clipEnabled) {
770 d->current.clipEnabled = false;
771 d->current.clip = QRegion();
772 d->setClip(0);
773 }
774 } else {
775 if(!d->current.clipEnabled)
776 op = Qt::ReplaceClip;
777 d->current.clipEnabled = true;
778 QRegion clipRegion(p.toFillPolygon().toPolygon(), p.fillRule());
779 if(op == Qt::ReplaceClip) {
780 d->current.clip = clipRegion;
781 d->setClip(0);
782 if(p.isEmpty()) {
783 CGRect rect = CGRectMake(0, 0, 0, 0);
784 CGContextClipToRect(d->hd, rect);
785 } else {
786 CGMutablePathRef path = qt_mac_compose_path(p);
787 CGContextBeginPath(d->hd);
788 CGContextAddPath(d->hd, path);
789 if(p.fillRule() == Qt::WindingFill)
790 CGContextClip(d->hd);
791 else
792 CGContextEOClip(d->hd);
793 CGPathRelease(path);
794 }
795 } else if(op == Qt::IntersectClip) {
796 d->current.clip = d->current.clip.intersected(clipRegion);
797 d->setClip(&d->current.clip);
798 } else if(op == Qt::UniteClip) {
799 d->current.clip = d->current.clip.united(clipRegion);
800 d->setClip(&d->current.clip);
801 }
802 }
803 }
804
805 void
updateClipRegion(const QRegion & clipRegion,Qt::ClipOperation op)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 else if(op == Qt::UniteClip)
823 d->current.clip = d->current.clip.united(clipRegion);
824 d->setClip(&d->current.clip);
825 }
826 }
827
828 void
drawPath(const QPainterPath & p)829 QCoreGraphicsPaintEngine::drawPath(const QPainterPath &p)
830 {
831 Q_D(QCoreGraphicsPaintEngine);
832 Q_ASSERT(isActive());
833
834 if (state->compositionMode() == QPainter::CompositionMode_Destination)
835 return;
836
837 CGMutablePathRef path = qt_mac_compose_path(p);
838 uchar ops = QCoreGraphicsPaintEnginePrivate::CGStroke;
839 if(p.fillRule() == Qt::WindingFill)
840 ops |= QCoreGraphicsPaintEnginePrivate::CGFill;
841 else
842 ops |= QCoreGraphicsPaintEnginePrivate::CGEOFill;
843 CGContextBeginPath(d->hd);
844 d->drawPath(ops, path);
845 CGPathRelease(path);
846 }
847
848 void
drawRects(const QRectF * rects,int rectCount)849 QCoreGraphicsPaintEngine::drawRects(const QRectF *rects, int rectCount)
850 {
851 Q_D(QCoreGraphicsPaintEngine);
852 Q_ASSERT(isActive());
853
854 if (state->compositionMode() == QPainter::CompositionMode_Destination)
855 return;
856
857 for (int i=0; i<rectCount; ++i) {
858 QRectF r = rects[i];
859
860 CGMutablePathRef path = CGPathCreateMutable();
861 CGPathAddRect(path, 0, qt_mac_compose_rect(r));
862 d->drawPath(QCoreGraphicsPaintEnginePrivate::CGFill|QCoreGraphicsPaintEnginePrivate::CGStroke,
863 path);
864 CGPathRelease(path);
865 }
866 }
867
868 void
drawPoints(const QPointF * points,int pointCount)869 QCoreGraphicsPaintEngine::drawPoints(const QPointF *points, int pointCount)
870 {
871 Q_D(QCoreGraphicsPaintEngine);
872 Q_ASSERT(isActive());
873
874 if (state->compositionMode() == QPainter::CompositionMode_Destination)
875 return;
876
877 if (d->current.pen.capStyle() == Qt::FlatCap)
878 CGContextSetLineCap(d->hd, kCGLineCapSquare);
879
880 CGMutablePathRef path = CGPathCreateMutable();
881 for(int i=0; i < pointCount; i++) {
882 float x = points[i].x(), y = points[i].y();
883 CGPathMoveToPoint(path, 0, x, y);
884 CGPathAddLineToPoint(path, 0, x+0.001, y);
885 }
886
887 bool doRestore = false;
888 if(d->cosmeticPen == QCoreGraphicsPaintEnginePrivate::CosmeticNone && !(state->renderHints() & QPainter::Antialiasing)) {
889 //we don't want adjusted pens for point rendering
890 doRestore = true;
891 d->saveGraphicsState();
892 CGContextSetLineWidth(d->hd, d->current.pen.widthF());
893 }
894 d->drawPath(QCoreGraphicsPaintEnginePrivate::CGStroke, path);
895 if (doRestore)
896 d->restoreGraphicsState();
897 CGPathRelease(path);
898 if (d->current.pen.capStyle() == Qt::FlatCap)
899 CGContextSetLineCap(d->hd, kCGLineCapButt);
900 }
901
902 void
drawEllipse(const QRectF & r)903 QCoreGraphicsPaintEngine::drawEllipse(const QRectF &r)
904 {
905 Q_D(QCoreGraphicsPaintEngine);
906 Q_ASSERT(isActive());
907
908 if (state->compositionMode() == QPainter::CompositionMode_Destination)
909 return;
910
911 CGMutablePathRef path = CGPathCreateMutable();
912 CGAffineTransform transform = CGAffineTransformMakeScale(r.width() / r.height(), 1);
913 CGPathAddArc(path, &transform,(r.x() + (r.width() / 2)) / (r.width() / r.height()),
914 r.y() + (r.height() / 2), r.height() / 2, 0, (2 * M_PI), false);
915 d->drawPath(QCoreGraphicsPaintEnginePrivate::CGFill | QCoreGraphicsPaintEnginePrivate::CGStroke,
916 path);
917 CGPathRelease(path);
918 }
919
920 void
drawPolygon(const QPointF * points,int pointCount,PolygonDrawMode mode)921 QCoreGraphicsPaintEngine::drawPolygon(const QPointF *points, int pointCount, PolygonDrawMode mode)
922 {
923 Q_D(QCoreGraphicsPaintEngine);
924 Q_ASSERT(isActive());
925
926 if (state->compositionMode() == QPainter::CompositionMode_Destination)
927 return;
928
929 CGMutablePathRef path = CGPathCreateMutable();
930 CGPathMoveToPoint(path, 0, points[0].x(), points[0].y());
931 for(int x = 1; x < pointCount; ++x)
932 CGPathAddLineToPoint(path, 0, points[x].x(), points[x].y());
933 if(mode != PolylineMode && points[0] != points[pointCount-1])
934 CGPathAddLineToPoint(path, 0, points[0].x(), points[0].y());
935 uint op = QCoreGraphicsPaintEnginePrivate::CGStroke;
936 if (mode != PolylineMode)
937 op |= mode == OddEvenMode ? QCoreGraphicsPaintEnginePrivate::CGEOFill
938 : QCoreGraphicsPaintEnginePrivate::CGFill;
939 d->drawPath(op, path);
940 CGPathRelease(path);
941 }
942
943 void
drawLines(const QLineF * lines,int lineCount)944 QCoreGraphicsPaintEngine::drawLines(const QLineF *lines, int lineCount)
945 {
946 Q_D(QCoreGraphicsPaintEngine);
947 Q_ASSERT(isActive());
948
949 if (state->compositionMode() == QPainter::CompositionMode_Destination)
950 return;
951
952 CGMutablePathRef path = CGPathCreateMutable();
953 for(int i = 0; i < lineCount; i++) {
954 const QPointF start = lines[i].p1(), end = lines[i].p2();
955 CGPathMoveToPoint(path, 0, start.x(), start.y());
956 CGPathAddLineToPoint(path, 0, end.x(), end.y());
957 }
958 d->drawPath(QCoreGraphicsPaintEnginePrivate::CGStroke, path);
959 CGPathRelease(path);
960 }
961
drawPixmap(const QRectF & r,const QPixmap & pm,const QRectF & sr)962 void QCoreGraphicsPaintEngine::drawPixmap(const QRectF &r, const QPixmap &pm, const QRectF &sr)
963 {
964 Q_D(QCoreGraphicsPaintEngine);
965 Q_ASSERT(isActive());
966
967 if (state->compositionMode() == QPainter::CompositionMode_Destination)
968 return;
969
970 if(pm.isNull())
971 return;
972
973 bool differentSize = (QRectF(0, 0, pm.width(), pm.height()) != sr), doRestore = false;
974 CGRect rect = CGRectMake(r.x(), r.y(), r.width(), r.height());
975 QCFType<CGImageRef> image;
976 bool isBitmap = (pm.depth() == 1);
977 if (isBitmap) {
978 doRestore = true;
979 d->saveGraphicsState();
980
981 const QColor &col = d->current.pen.color();
982 CGContextSetFillColorWithColor(d->hd, cgColorForQColor(col, d->pdev));
983 image = qt_mac_create_imagemask(pm, sr);
984 } else if (differentSize) {
985 QCFType<CGImageRef> img = pm.toMacCGImageRef();
986 image = CGImageCreateWithImageInRect(img, CGRectMake(qRound(sr.x()), qRound(sr.y()), qRound(sr.width()), qRound(sr.height())));
987 } else {
988 image = (CGImageRef)pm.macCGHandle();
989 }
990 qt_mac_drawCGImage(d->hd, &rect, image);
991 if (doRestore)
992 d->restoreGraphicsState();
993 }
994
drawImageReleaseData(void * info,const void *,size_t)995 static void drawImageReleaseData (void *info, const void *, size_t)
996 {
997 delete static_cast<QImage *>(info);
998 }
999
qt_mac_createCGImageFromQImage(const QImage & img,const QImage ** imagePtr=0)1000 CGImageRef qt_mac_createCGImageFromQImage(const QImage &img, const QImage **imagePtr = 0)
1001 {
1002 QImage *image;
1003 if (img.depth() != 32)
1004 image = new QImage(img.convertToFormat(QImage::Format_ARGB32_Premultiplied));
1005 else
1006 image = new QImage(img);
1007
1008 uint cgflags = kCGImageAlphaNone;
1009 switch (image->format()) {
1010 case QImage::Format_ARGB32_Premultiplied:
1011 cgflags = kCGImageAlphaPremultipliedFirst;
1012 break;
1013 case QImage::Format_ARGB32:
1014 cgflags = kCGImageAlphaFirst;
1015 break;
1016 case QImage::Format_RGB32:
1017 cgflags = kCGImageAlphaNoneSkipFirst;
1018 default:
1019 break;
1020 }
1021 #if defined(kCGBitmapByteOrder32Host) //only needed because CGImage.h added symbols in the minor version
1022 cgflags |= kCGBitmapByteOrder32Host;
1023 #endif
1024 QCFType<CGDataProviderRef> dataProvider = CGDataProviderCreateWithData(image,
1025 static_cast<const QImage *>(image)->bits(),
1026 image->byteCount(),
1027 drawImageReleaseData);
1028 if (imagePtr)
1029 *imagePtr = image;
1030 return CGImageCreate(image->width(), image->height(), 8, 32,
1031 image->bytesPerLine(),
1032 QCoreGraphicsPaintEngine::macGenericColorSpace(),
1033 cgflags, dataProvider, 0, false, kCGRenderingIntentDefault);
1034
1035 }
1036
drawImage(const QRectF & r,const QImage & img,const QRectF & sr,Qt::ImageConversionFlags flags)1037 void QCoreGraphicsPaintEngine::drawImage(const QRectF &r, const QImage &img, const QRectF &sr,
1038 Qt::ImageConversionFlags flags)
1039 {
1040 Q_D(QCoreGraphicsPaintEngine);
1041 Q_UNUSED(flags);
1042 Q_ASSERT(isActive());
1043
1044 if (img.isNull() || state->compositionMode() == QPainter::CompositionMode_Destination)
1045 return;
1046
1047 const QImage *image;
1048 QCFType<CGImageRef> cgimage = qt_mac_createCGImageFromQImage(img, &image);
1049 CGRect rect = CGRectMake(r.x(), r.y(), r.width(), r.height());
1050 if (QRectF(0, 0, img.width(), img.height()) != sr)
1051 cgimage = CGImageCreateWithImageInRect(cgimage, CGRectMake(sr.x(), sr.y(),
1052 sr.width(), sr.height()));
1053 qt_mac_drawCGImage(d->hd, &rect, cgimage);
1054 }
1055
initialize()1056 void QCoreGraphicsPaintEngine::initialize()
1057 {
1058 }
1059
cleanup()1060 void QCoreGraphicsPaintEngine::cleanup()
1061 {
1062 }
1063
clearColorSpace(QWidget * w)1064 void QCoreGraphicsPaintEngine::clearColorSpace(QWidget* w)
1065 {
1066 m_displayColorSpaceHash.remove(w);
1067 }
1068
1069 CGContextRef
handle() const1070 QCoreGraphicsPaintEngine::handle() const
1071 {
1072 return d_func()->hd;
1073 }
1074
1075 void
drawTiledPixmap(const QRectF & r,const QPixmap & pixmap,const QPointF & p)1076 QCoreGraphicsPaintEngine::drawTiledPixmap(const QRectF &r, const QPixmap &pixmap,
1077 const QPointF &p)
1078 {
1079 Q_D(QCoreGraphicsPaintEngine);
1080 Q_ASSERT(isActive());
1081
1082 if (state->compositionMode() == QPainter::CompositionMode_Destination)
1083 return;
1084
1085 //save the old state
1086 d->saveGraphicsState();
1087
1088 //setup the pattern
1089 QMacPattern *qpattern = new QMacPattern;
1090 qpattern->data.pixmap = pixmap;
1091 qpattern->foreground = d->current.pen.color();
1092 qpattern->pdev = d->pdev;
1093 CGPatternCallbacks callbks;
1094 callbks.version = 0;
1095 callbks.drawPattern = qt_mac_draw_pattern;
1096 callbks.releaseInfo = qt_mac_dispose_pattern;
1097 const int width = qpattern->width(), height = qpattern->height();
1098 CGAffineTransform trans = CGContextGetCTM(d->hd);
1099 CGPatternRef pat = CGPatternCreate(qpattern, CGRectMake(0, 0, width, height),
1100 trans, width, height,
1101 kCGPatternTilingNoDistortion, true, &callbks);
1102 CGColorSpaceRef cs = CGColorSpaceCreatePattern(0);
1103 CGContextSetFillColorSpace(d->hd, cs);
1104 CGFloat component = 1.0; //just one
1105 CGContextSetFillPattern(d->hd, pat, &component);
1106 CGSize phase = CGSizeApplyAffineTransform(CGSizeMake(-(p.x()-r.x()), -(p.y()-r.y())), trans);
1107 CGContextSetPatternPhase(d->hd, phase);
1108
1109 //fill the rectangle
1110 CGRect mac_rect = CGRectMake(r.x(), r.y(), r.width(), r.height());
1111 CGContextFillRect(d->hd, mac_rect);
1112
1113 //restore the state
1114 d->restoreGraphicsState();
1115 //cleanup
1116 CGColorSpaceRelease(cs);
1117 CGPatternRelease(pat);
1118 }
1119
drawTextItem(const QPointF & pos,const QTextItem & item)1120 void QCoreGraphicsPaintEngine::drawTextItem(const QPointF &pos, const QTextItem &item)
1121 {
1122 Q_D(QCoreGraphicsPaintEngine);
1123 if (d->current.transform.type() == QTransform::TxProject
1124 #ifndef QMAC_NATIVE_GRADIENTS
1125 || painter()->pen().brush().gradient() //Just let the base engine "emulate" the gradient
1126 #endif
1127 ) {
1128 QPaintEngine::drawTextItem(pos, item);
1129 return;
1130 }
1131
1132 if (state->compositionMode() == QPainter::CompositionMode_Destination)
1133 return;
1134
1135 const QTextItemInt &ti = static_cast<const QTextItemInt &>(item);
1136
1137 QPen oldPen = painter()->pen();
1138 QBrush oldBrush = painter()->brush();
1139 QPointF oldBrushOrigin = painter()->brushOrigin();
1140 updatePen(Qt::NoPen);
1141 updateBrush(oldPen.brush(), QPointF(0, 0));
1142
1143 Q_ASSERT(type() == QPaintEngine::CoreGraphics);
1144
1145 QFontEngine *fe = ti.fontEngine;
1146
1147 const bool textAA = state->renderHints() & QPainter::TextAntialiasing && fe->fontDef.pointSize > qt_antialiasing_threshold && !(fe->fontDef.styleStrategy & QFont::NoAntialias);
1148 const bool lineAA = state->renderHints() & QPainter::Antialiasing;
1149 if(textAA != lineAA)
1150 CGContextSetShouldAntialias(d->hd, textAA);
1151
1152 if (ti.glyphs.numGlyphs) {
1153 switch (fe->type()) {
1154 case QFontEngine::Mac:
1155 #ifdef QT_MAC_USE_COCOA
1156 static_cast<QCoreTextFontEngine *>(fe)->draw(d->hd, pos.x(), pos.y(), ti, paintDevice()->height());
1157 #else
1158 static_cast<QFontEngineMac *>(fe)->draw(d->hd, pos.x(), pos.y(), ti, paintDevice()->height());
1159 #endif
1160 break;
1161 case QFontEngine::Box:
1162 d->drawBoxTextItem(pos, ti);
1163 break;
1164 default:
1165 break;
1166 }
1167 }
1168
1169 if(textAA != lineAA)
1170 CGContextSetShouldAntialias(d->hd, !textAA);
1171
1172 updatePen(oldPen);
1173 updateBrush(oldBrush, oldBrushOrigin);
1174 }
1175
1176 QPainter::RenderHints
supportedRenderHints() const1177 QCoreGraphicsPaintEngine::supportedRenderHints() const
1178 {
1179 return QPainter::RenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform);
1180 }
1181 enum CGCompositeMode {
1182 kCGCompositeModeClear = 0,
1183 kCGCompositeModeCopy = 1,
1184 kCGCompositeModeSourceOver = 2,
1185 kCGCompositeModeSourceIn = 3,
1186 kCGCompositeModeSourceOut = 4,
1187 kCGCompositeModeSourceAtop = 5,
1188 kCGCompositeModeDestinationOver = 6,
1189 kCGCompositeModeDestinationIn = 7,
1190 kCGCompositeModeDestinationOut = 8,
1191 kCGCompositeModeDestinationAtop = 9,
1192 kCGCompositeModeXOR = 10,
1193 kCGCompositeModePlusDarker = 11, // (max (0, (1-d) + (1-s)))
1194 kCGCompositeModePlusLighter = 12, // (min (1, s + d))
1195 };
1196 extern "C" {
1197 extern void CGContextSetCompositeOperation(CGContextRef, int);
1198 } // private function, but is in all versions of OS X.
1199 void
updateCompositionMode(QPainter::CompositionMode mode)1200 QCoreGraphicsPaintEngine::updateCompositionMode(QPainter::CompositionMode mode)
1201 {
1202 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
1203 if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5) {
1204 int cg_mode = kCGBlendModeNormal;
1205 switch(mode) {
1206 case QPainter::CompositionMode_Multiply:
1207 cg_mode = kCGBlendModeMultiply;
1208 break;
1209 case QPainter::CompositionMode_Screen:
1210 cg_mode = kCGBlendModeScreen;
1211 break;
1212 case QPainter::CompositionMode_Overlay:
1213 cg_mode = kCGBlendModeOverlay;
1214 break;
1215 case QPainter::CompositionMode_Darken:
1216 cg_mode = kCGBlendModeDarken;
1217 break;
1218 case QPainter::CompositionMode_Lighten:
1219 cg_mode = kCGBlendModeLighten;
1220 break;
1221 case QPainter::CompositionMode_ColorDodge:
1222 cg_mode = kCGBlendModeColorDodge;
1223 break;
1224 case QPainter::CompositionMode_ColorBurn:
1225 cg_mode = kCGBlendModeColorBurn;
1226 break;
1227 case QPainter::CompositionMode_HardLight:
1228 cg_mode = kCGBlendModeHardLight;
1229 break;
1230 case QPainter::CompositionMode_SoftLight:
1231 cg_mode = kCGBlendModeSoftLight;
1232 break;
1233 case QPainter::CompositionMode_Difference:
1234 cg_mode = kCGBlendModeDifference;
1235 break;
1236 case QPainter::CompositionMode_Exclusion:
1237 cg_mode = kCGBlendModeExclusion;
1238 break;
1239 case QPainter::CompositionMode_Plus:
1240 cg_mode = kCGBlendModePlusLighter;
1241 break;
1242 case QPainter::CompositionMode_SourceOver:
1243 cg_mode = kCGBlendModeNormal;
1244 break;
1245 case QPainter::CompositionMode_DestinationOver:
1246 cg_mode = kCGBlendModeDestinationOver;
1247 break;
1248 case QPainter::CompositionMode_Clear:
1249 cg_mode = kCGBlendModeClear;
1250 break;
1251 case QPainter::CompositionMode_Source:
1252 cg_mode = kCGBlendModeCopy;
1253 break;
1254 case QPainter::CompositionMode_Destination:
1255 cg_mode = -1;
1256 break;
1257 case QPainter::CompositionMode_SourceIn:
1258 cg_mode = kCGBlendModeSourceIn;
1259 break;
1260 case QPainter::CompositionMode_DestinationIn:
1261 cg_mode = kCGCompositeModeDestinationIn;
1262 break;
1263 case QPainter::CompositionMode_SourceOut:
1264 cg_mode = kCGBlendModeSourceOut;
1265 break;
1266 case QPainter::CompositionMode_DestinationOut:
1267 cg_mode = kCGBlendModeDestinationOver;
1268 break;
1269 case QPainter::CompositionMode_SourceAtop:
1270 cg_mode = kCGBlendModeSourceAtop;
1271 break;
1272 case QPainter::CompositionMode_DestinationAtop:
1273 cg_mode = kCGBlendModeDestinationAtop;
1274 break;
1275 case QPainter::CompositionMode_Xor:
1276 cg_mode = kCGBlendModeXOR;
1277 break;
1278 default:
1279 break;
1280 }
1281 if (cg_mode > -1) {
1282 CGContextSetBlendMode(d_func()->hd, CGBlendMode(cg_mode));
1283 }
1284 } else
1285 #endif
1286 // The standard porter duff ops.
1287 if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_3
1288 && mode <= QPainter::CompositionMode_Xor) {
1289 int cg_mode = kCGCompositeModeCopy;
1290 switch (mode) {
1291 case QPainter::CompositionMode_SourceOver:
1292 cg_mode = kCGCompositeModeSourceOver;
1293 break;
1294 case QPainter::CompositionMode_DestinationOver:
1295 cg_mode = kCGCompositeModeDestinationOver;
1296 break;
1297 case QPainter::CompositionMode_Clear:
1298 cg_mode = kCGCompositeModeClear;
1299 break;
1300 default:
1301 qWarning("QCoreGraphicsPaintEngine: Unhandled composition mode %d", (int)mode);
1302 break;
1303 case QPainter::CompositionMode_Source:
1304 cg_mode = kCGCompositeModeCopy;
1305 break;
1306 case QPainter::CompositionMode_Destination:
1307 cg_mode = CGCompositeMode(-1);
1308 break;
1309 case QPainter::CompositionMode_SourceIn:
1310 cg_mode = kCGCompositeModeSourceIn;
1311 break;
1312 case QPainter::CompositionMode_DestinationIn:
1313 cg_mode = kCGCompositeModeDestinationIn;
1314 break;
1315 case QPainter::CompositionMode_SourceOut:
1316 cg_mode = kCGCompositeModeSourceOut;
1317 break;
1318 case QPainter::CompositionMode_DestinationOut:
1319 cg_mode = kCGCompositeModeDestinationOut;
1320 break;
1321 case QPainter::CompositionMode_SourceAtop:
1322 cg_mode = kCGCompositeModeSourceAtop;
1323 break;
1324 case QPainter::CompositionMode_DestinationAtop:
1325 cg_mode = kCGCompositeModeDestinationAtop;
1326 break;
1327 case QPainter::CompositionMode_Xor:
1328 cg_mode = kCGCompositeModeXOR;
1329 break;
1330 }
1331 if (cg_mode > -1)
1332 CGContextSetCompositeOperation(d_func()->hd, CGCompositeMode(cg_mode));
1333 } else {
1334 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4)
1335 bool needPrivateAPI = false;
1336 if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_4) {
1337 int cg_mode = kCGBlendModeNormal;
1338 switch (mode) {
1339 case QPainter::CompositionMode_Multiply:
1340 cg_mode = kCGBlendModeMultiply;
1341 break;
1342 case QPainter::CompositionMode_Screen:
1343 cg_mode = kCGBlendModeScreen;
1344 break;
1345 case QPainter::CompositionMode_Overlay:
1346 cg_mode = kCGBlendModeOverlay;
1347 break;
1348 case QPainter::CompositionMode_Darken:
1349 cg_mode = kCGBlendModeDarken;
1350 break;
1351 case QPainter::CompositionMode_Lighten:
1352 cg_mode = kCGBlendModeLighten;
1353 break;
1354 case QPainter::CompositionMode_ColorDodge:
1355 cg_mode = kCGBlendModeColorDodge;
1356 break;
1357 case QPainter::CompositionMode_ColorBurn:
1358 cg_mode = kCGBlendModeColorBurn;
1359 break;
1360 case QPainter::CompositionMode_HardLight:
1361 cg_mode = kCGBlendModeHardLight;
1362 break;
1363 case QPainter::CompositionMode_SoftLight:
1364 cg_mode = kCGBlendModeSoftLight;
1365 break;
1366 case QPainter::CompositionMode_Difference:
1367 cg_mode = kCGBlendModeDifference;
1368 break;
1369 case QPainter::CompositionMode_Exclusion:
1370 cg_mode = kCGBlendModeExclusion;
1371 break;
1372 case QPainter::CompositionMode_Plus:
1373 needPrivateAPI = true;
1374 cg_mode = kCGCompositeModePlusLighter;
1375 break;
1376 default:
1377 break;
1378 }
1379 if (!needPrivateAPI)
1380 CGContextSetBlendMode(d_func()->hd, CGBlendMode(cg_mode));
1381 else
1382 CGContextSetCompositeOperation(d_func()->hd, CGCompositeMode(cg_mode));
1383 }
1384 #endif
1385 }
1386 }
1387
1388 void
updateRenderHints(QPainter::RenderHints hints)1389 QCoreGraphicsPaintEngine::updateRenderHints(QPainter::RenderHints hints)
1390 {
1391 Q_D(QCoreGraphicsPaintEngine);
1392 CGContextSetShouldAntialias(d->hd, hints & QPainter::Antialiasing);
1393 static const CGFloat ScaleFactor = qt_mac_get_scalefactor();
1394 if (ScaleFactor > 1.) {
1395 CGContextSetInterpolationQuality(d->hd, kCGInterpolationHigh);
1396 } else {
1397 CGContextSetInterpolationQuality(d->hd, (hints & QPainter::SmoothPixmapTransform) ?
1398 kCGInterpolationHigh : kCGInterpolationNone);
1399 }
1400 bool textAntialiasing = (hints & QPainter::TextAntialiasing) == QPainter::TextAntialiasing;
1401 if (!textAntialiasing || d->disabledSmoothFonts) {
1402 d->disabledSmoothFonts = !textAntialiasing;
1403 CGContextSetShouldSmoothFonts(d->hd, textAntialiasing);
1404 }
1405 }
1406
1407 /*
1408 Returns the size of one device pixel in user-space coordinates.
1409 */
devicePixelSize(CGContextRef)1410 QPointF QCoreGraphicsPaintEnginePrivate::devicePixelSize(CGContextRef)
1411 {
1412 QPointF p1 = current.transform.inverted().map(QPointF(0, 0));
1413 QPointF p2 = current.transform.inverted().map(QPointF(1, 1));
1414 return QPointF(qAbs(p2.x() - p1.x()), qAbs(p2.y() - p1.y()));
1415 }
1416
1417 /*
1418 Adjusts the pen width so we get correct line widths in the
1419 non-transformed, aliased case.
1420 */
adjustPenWidth(float penWidth)1421 float QCoreGraphicsPaintEnginePrivate::adjustPenWidth(float penWidth)
1422 {
1423 Q_Q(QCoreGraphicsPaintEngine);
1424 float ret = penWidth;
1425 if (!complexXForm && !(q->state->renderHints() & QPainter::Antialiasing)) {
1426 if (penWidth < 2)
1427 ret = 1;
1428 else if (penWidth < 3)
1429 ret = 1.5;
1430 else
1431 ret = penWidth -1;
1432 }
1433 return ret;
1434 }
1435
1436 void
setStrokePen(const QPen & pen)1437 QCoreGraphicsPaintEnginePrivate::setStrokePen(const QPen &pen)
1438 {
1439 //pencap
1440 CGLineCap cglinecap = kCGLineCapButt;
1441 if(pen.capStyle() == Qt::SquareCap)
1442 cglinecap = kCGLineCapSquare;
1443 else if(pen.capStyle() == Qt::RoundCap)
1444 cglinecap = kCGLineCapRound;
1445 CGContextSetLineCap(hd, cglinecap);
1446 CGContextSetLineWidth(hd, adjustPenWidth(pen.widthF()));
1447
1448 //join
1449 CGLineJoin cglinejoin = kCGLineJoinMiter;
1450 if(pen.joinStyle() == Qt::BevelJoin)
1451 cglinejoin = kCGLineJoinBevel;
1452 else if(pen.joinStyle() == Qt::RoundJoin)
1453 cglinejoin = kCGLineJoinRound;
1454 CGContextSetLineJoin(hd, cglinejoin);
1455 // CGContextSetMiterLimit(hd, pen.miterLimit());
1456
1457 //pen style
1458 QVector<CGFloat> linedashes;
1459 if(pen.style() == Qt::CustomDashLine) {
1460 QVector<qreal> customs = pen.dashPattern();
1461 for(int i = 0; i < customs.size(); ++i)
1462 linedashes.append(customs.at(i));
1463 } else if(pen.style() == Qt::DashLine) {
1464 linedashes.append(4);
1465 linedashes.append(2);
1466 } else if(pen.style() == Qt::DotLine) {
1467 linedashes.append(1);
1468 linedashes.append(2);
1469 } else if(pen.style() == Qt::DashDotLine) {
1470 linedashes.append(4);
1471 linedashes.append(2);
1472 linedashes.append(1);
1473 linedashes.append(2);
1474 } else if(pen.style() == Qt::DashDotDotLine) {
1475 linedashes.append(4);
1476 linedashes.append(2);
1477 linedashes.append(1);
1478 linedashes.append(2);
1479 linedashes.append(1);
1480 linedashes.append(2);
1481 }
1482 const CGFloat cglinewidth = pen.widthF() <= 0.0f ? 1.0f : float(pen.widthF());
1483 for(int i = 0; i < linedashes.size(); ++i) {
1484 linedashes[i] *= cglinewidth;
1485 if(cglinewidth < 3 && (cglinecap == kCGLineCapSquare || cglinecap == kCGLineCapRound)) {
1486 if((i%2))
1487 linedashes[i] += cglinewidth/2;
1488 else
1489 linedashes[i] -= cglinewidth/2;
1490 }
1491 }
1492 CGContextSetLineDash(hd, pen.dashOffset() * cglinewidth, linedashes.data(), linedashes.size());
1493
1494 // color
1495 CGContextSetStrokeColorWithColor(hd, cgColorForQColor(pen.color(), pdev));
1496 }
1497
1498 // Add our own patterns here to deal with the fact that the coordinate system
1499 // is flipped vertically with Quartz2D.
qt_mac_patternForBrush(int brushStyle)1500 static const uchar *qt_mac_patternForBrush(int brushStyle)
1501 {
1502 Q_ASSERT(brushStyle > Qt::SolidPattern && brushStyle < Qt::LinearGradientPattern);
1503 static const uchar dense1_pat[] = { 0x00, 0x00, 0x44, 0x00, 0x00, 0x00, 0x44, 0x00 };
1504 static const uchar dense2_pat[] = { 0x00, 0x22, 0x00, 0x88, 0x00, 0x22, 0x00, 0x88 };
1505 static const uchar dense3_pat[] = { 0x11, 0xaa, 0x44, 0xaa, 0x11, 0xaa, 0x44, 0xaa };
1506 static const uchar dense4_pat[] = { 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55 };
1507 static const uchar dense5_pat[] = { 0xee, 0x55, 0xbb, 0x55, 0xee, 0x55, 0xbb, 0x55 };
1508 static const uchar dense6_pat[] = { 0xff, 0xdd, 0xff, 0x77, 0xff, 0xdd, 0xff, 0x77 };
1509 static const uchar dense7_pat[] = { 0xff, 0xff, 0xbb, 0xff, 0xff, 0xff, 0xbb, 0xff };
1510 static const uchar hor_pat[] = { 0xff, 0xff, 0xff, 0xff, 0x00, 0xff, 0xff, 0xff };
1511 static const uchar ver_pat[] = { 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef };
1512 static const uchar cross_pat[] = { 0xef, 0xef, 0xef, 0xef, 0x00, 0xef, 0xef, 0xef };
1513 static const uchar fdiag_pat[] = { 0x7f, 0xbf, 0xdf, 0xef, 0xf7, 0xfb, 0xfd, 0xfe };
1514 static const uchar bdiag_pat[] = { 0xfe, 0xfd, 0xfb, 0xf7, 0xef, 0xdf, 0xbf, 0x7f };
1515 static const uchar dcross_pat[] = { 0x7e, 0xbd, 0xdb, 0xe7, 0xe7, 0xdb, 0xbd, 0x7e };
1516 static const uchar *const pat_tbl[] = {
1517 dense1_pat, dense2_pat, dense3_pat, dense4_pat, dense5_pat,
1518 dense6_pat, dense7_pat,
1519 hor_pat, ver_pat, cross_pat, bdiag_pat, fdiag_pat, dcross_pat };
1520 return pat_tbl[brushStyle - Qt::Dense1Pattern];
1521 }
1522
setFillBrush(const QPointF & offset)1523 void QCoreGraphicsPaintEnginePrivate::setFillBrush(const QPointF &offset)
1524 {
1525 // pattern
1526 Qt::BrushStyle bs = current.brush.style();
1527 #ifdef QT_MAC_USE_NATIVE_GRADIENTS
1528 if (bs == Qt::LinearGradientPattern || bs == Qt::RadialGradientPattern) {
1529 const QGradient *grad = static_cast<const QGradient*>(current.brush.gradient());
1530 if (drawGradientNatively(grad)) {
1531 Q_ASSERT(grad->spread() == QGradient::PadSpread);
1532
1533 static const CGFloat domain[] = { 0.0f, +1.0f };
1534 static const CGFunctionCallbacks callbacks = { 0, qt_mac_color_gradient_function, 0 };
1535 CGFunctionRef fill_func = CGFunctionCreate(reinterpret_cast<void *>(¤t.brush),
1536 1, domain, 4, 0, &callbacks);
1537
1538 CGColorSpaceRef colorspace = qt_mac_colorSpaceForDeviceType(pdev);
1539 if (bs == Qt::LinearGradientPattern) {
1540 const QLinearGradient *linearGrad = static_cast<const QLinearGradient *>(grad);
1541 const QPointF start(linearGrad->start());
1542 const QPointF stop(linearGrad->finalStop());
1543 shading = CGShadingCreateAxial(colorspace, CGPointMake(start.x(), start.y()),
1544 CGPointMake(stop.x(), stop.y()), fill_func, true, true);
1545 } else {
1546 Q_ASSERT(bs == Qt::RadialGradientPattern);
1547 const QRadialGradient *radialGrad = static_cast<const QRadialGradient *>(grad);
1548 QPointF center(radialGrad->center());
1549 QPointF focal(radialGrad->focalPoint());
1550 qreal radius = radialGrad->radius();
1551 qreal focalRadius = radialGrad->focalRadius();
1552 shading = CGShadingCreateRadial(colorspace, CGPointMake(focal.x(), focal.y()),
1553 focalRadius, CGPointMake(center.x(), center.y()), radius, fill_func, false, true);
1554 }
1555
1556 CGFunctionRelease(fill_func);
1557 }
1558 } else
1559 #endif
1560 if(bs != Qt::SolidPattern && bs != Qt::NoBrush
1561 #ifndef QT_MAC_USE_NATIVE_GRADIENTS
1562 && (bs < Qt::LinearGradientPattern || bs > Qt::ConicalGradientPattern)
1563 #endif
1564 )
1565 {
1566 QMacPattern *qpattern = new QMacPattern;
1567 qpattern->pdev = pdev;
1568 CGFloat components[4] = { 1.0, 1.0, 1.0, 1.0 };
1569 CGColorSpaceRef base_colorspace = 0;
1570 if(bs == Qt::TexturePattern) {
1571 qpattern->data.pixmap = current.brush.texture();
1572 if(qpattern->data.pixmap.isQBitmap()) {
1573 const QColor &col = current.brush.color();
1574 components[0] = qt_mac_convert_color_to_cg(col.red());
1575 components[1] = qt_mac_convert_color_to_cg(col.green());
1576 components[2] = qt_mac_convert_color_to_cg(col.blue());
1577 base_colorspace = QCoreGraphicsPaintEngine::macGenericColorSpace();
1578 }
1579 } else {
1580 qpattern->as_mask = true;
1581
1582 qpattern->data.bytes = qt_mac_patternForBrush(bs);
1583 const QColor &col = current.brush.color();
1584 components[0] = qt_mac_convert_color_to_cg(col.red());
1585 components[1] = qt_mac_convert_color_to_cg(col.green());
1586 components[2] = qt_mac_convert_color_to_cg(col.blue());
1587 base_colorspace = QCoreGraphicsPaintEngine::macGenericColorSpace();
1588 }
1589 int width = qpattern->width(), height = qpattern->height();
1590 qpattern->foreground = current.brush.color();
1591
1592 CGColorSpaceRef fill_colorspace = CGColorSpaceCreatePattern(base_colorspace);
1593 CGContextSetFillColorSpace(hd, fill_colorspace);
1594
1595 CGAffineTransform xform = CGContextGetCTM(hd);
1596 xform = CGAffineTransformConcat(qt_mac_convert_transform_to_cg(current.brush.transform()), xform);
1597 xform = CGAffineTransformTranslate(xform, offset.x(), offset.y());
1598
1599 CGPatternCallbacks callbks;
1600 callbks.version = 0;
1601 callbks.drawPattern = qt_mac_draw_pattern;
1602 callbks.releaseInfo = qt_mac_dispose_pattern;
1603 CGPatternRef fill_pattern = CGPatternCreate(qpattern, CGRectMake(0, 0, width, height),
1604 xform, width, height, kCGPatternTilingNoDistortion,
1605 !base_colorspace, &callbks);
1606 CGContextSetFillPattern(hd, fill_pattern, components);
1607
1608 CGPatternRelease(fill_pattern);
1609 CGColorSpaceRelease(fill_colorspace);
1610 } else if(bs != Qt::NoBrush) {
1611 CGContextSetFillColorWithColor(hd, cgColorForQColor(current.brush.color(), pdev));
1612 }
1613 }
1614
1615 void
setClip(const QRegion * rgn)1616 QCoreGraphicsPaintEnginePrivate::setClip(const QRegion *rgn)
1617 {
1618 Q_Q(QCoreGraphicsPaintEngine);
1619 if(hd) {
1620 resetClip();
1621 QRegion sysClip = q->systemClip();
1622 if(!sysClip.isEmpty())
1623 qt_mac_clip_cg(hd, sysClip, &orig_xform);
1624 if(rgn)
1625 qt_mac_clip_cg(hd, *rgn, 0);
1626 }
1627 }
1628
1629 struct qt_mac_cg_transform_path {
1630 CGMutablePathRef path;
1631 CGAffineTransform transform;
1632 };
1633
qt_mac_cg_transform_path_apply(void * info,const CGPathElement * element)1634 void qt_mac_cg_transform_path_apply(void *info, const CGPathElement *element)
1635 {
1636 Q_ASSERT(info && element);
1637 qt_mac_cg_transform_path *t = (qt_mac_cg_transform_path*)info;
1638 switch(element->type) {
1639 case kCGPathElementMoveToPoint:
1640 CGPathMoveToPoint(t->path, &t->transform, element->points[0].x, element->points[0].y);
1641 break;
1642 case kCGPathElementAddLineToPoint:
1643 CGPathAddLineToPoint(t->path, &t->transform, element->points[0].x, element->points[0].y);
1644 break;
1645 case kCGPathElementAddQuadCurveToPoint:
1646 CGPathAddQuadCurveToPoint(t->path, &t->transform, element->points[0].x, element->points[0].y,
1647 element->points[1].x, element->points[1].y);
1648 break;
1649 case kCGPathElementAddCurveToPoint:
1650 CGPathAddCurveToPoint(t->path, &t->transform, element->points[0].x, element->points[0].y,
1651 element->points[1].x, element->points[1].y,
1652 element->points[2].x, element->points[2].y);
1653 break;
1654 case kCGPathElementCloseSubpath:
1655 CGPathCloseSubpath(t->path);
1656 break;
1657 default:
1658 qDebug() << "Unhandled path transform type: " << element->type;
1659 }
1660 }
1661
drawPath(uchar ops,CGMutablePathRef path)1662 void QCoreGraphicsPaintEnginePrivate::drawPath(uchar ops, CGMutablePathRef path)
1663 {
1664 Q_Q(QCoreGraphicsPaintEngine);
1665 Q_ASSERT((ops & (CGFill | CGEOFill)) != (CGFill | CGEOFill)); //can't really happen
1666 if((ops & (CGFill | CGEOFill))) {
1667 if (shading) {
1668 Q_ASSERT(path);
1669 CGContextBeginPath(hd);
1670 CGContextAddPath(hd, path);
1671 saveGraphicsState();
1672 if (ops & CGFill)
1673 CGContextClip(hd);
1674 else if (ops & CGEOFill)
1675 CGContextEOClip(hd);
1676 if (current.brush.gradient()->coordinateMode() == QGradient::ObjectBoundingMode) {
1677 CGRect boundingBox = CGPathGetBoundingBox(path);
1678 CGContextConcatCTM(hd,
1679 CGAffineTransformMake(boundingBox.size.width, 0,
1680 0, boundingBox.size.height,
1681 boundingBox.origin.x, boundingBox.origin.y));
1682 }
1683 CGContextDrawShading(hd, shading);
1684 restoreGraphicsState();
1685 ops &= ~CGFill;
1686 ops &= ~CGEOFill;
1687 } else if (current.brush.style() == Qt::NoBrush) {
1688 ops &= ~CGFill;
1689 ops &= ~CGEOFill;
1690 }
1691 }
1692 if((ops & CGStroke) && current.pen.style() == Qt::NoPen)
1693 ops &= ~CGStroke;
1694
1695 if(ops & (CGEOFill | CGFill)) {
1696 CGContextBeginPath(hd);
1697 CGContextAddPath(hd, path);
1698 if (ops & CGEOFill) {
1699 CGContextEOFillPath(hd);
1700 } else {
1701 CGContextFillPath(hd);
1702 }
1703 }
1704
1705 // Avoid saving and restoring the context if we can.
1706 const bool needContextSave = (cosmeticPen != QCoreGraphicsPaintEnginePrivate::CosmeticNone ||
1707 !(q->state->renderHints() & QPainter::Antialiasing));
1708 if(ops & CGStroke) {
1709 if (needContextSave)
1710 saveGraphicsState();
1711 CGContextBeginPath(hd);
1712
1713 // Translate a fraction of a pixel size in the y direction
1714 // to make sure that primitives painted at pixel borders
1715 // fills the right pixel. This is needed since the y xais
1716 // in the Quartz coordinate system is inverted compared to Qt.
1717 if (!(q->state->renderHints() & QPainter::Antialiasing)) {
1718 if (current.pen.style() == Qt::SolidLine || current.pen.width() >= 3)
1719 CGContextTranslateCTM(hd, double(pixelSize.x()) * 0.25, double(pixelSize.y()) * 0.25);
1720 else if (current.pen.style() == Qt::DotLine && QSysInfo::MacintoshVersion == QSysInfo::MV_10_3)
1721 ; // Do nothing.
1722 else
1723 CGContextTranslateCTM(hd, 0, double(pixelSize.y()) * 0.1);
1724 }
1725
1726 if (cosmeticPen != QCoreGraphicsPaintEnginePrivate::CosmeticNone) {
1727 // If antialiazing is enabled, use the cosmetic pen size directly.
1728 if (q->state->renderHints() & QPainter::Antialiasing)
1729 CGContextSetLineWidth(hd, cosmeticPenSize);
1730 else if (current.pen.widthF() <= 1)
1731 CGContextSetLineWidth(hd, cosmeticPenSize * 0.9f);
1732 else
1733 CGContextSetLineWidth(hd, cosmeticPenSize);
1734 }
1735 if(cosmeticPen == QCoreGraphicsPaintEnginePrivate::CosmeticTransformPath) {
1736 qt_mac_cg_transform_path t;
1737 t.transform = qt_mac_convert_transform_to_cg(current.transform);
1738 t.path = CGPathCreateMutable();
1739 CGPathApply(path, &t, qt_mac_cg_transform_path_apply); //transform the path
1740 setTransform(0); //unset the context transform
1741 CGContextSetLineWidth(hd, cosmeticPenSize);
1742 CGContextAddPath(hd, t.path);
1743 CGPathRelease(t.path);
1744 } else {
1745 CGContextAddPath(hd, path);
1746 }
1747
1748 CGContextStrokePath(hd);
1749 if (needContextSave)
1750 restoreGraphicsState();
1751 }
1752 }
1753
1754 QT_END_NAMESPACE
1755