6#include <private/qcore_mac_p.h>
7#include <qpa/qplatformpixmap.h>
8#include <QtGui/qicon.h>
9#include <QtGui/private/qpaintengine_p.h>
10#include <QtCore/qdebug.h>
11#include <QtCore/qcoreapplication.h>
12#include <QtCore/qoperatingsystemversion.h>
13#include <QtGui/qcolorspace.h>
15#if defined(Q_OS_MACOS)
16# include <AppKit/AppKit.h>
17#elif defined(QT_PLATFORM_UIKIT)
18# include <UIKit/UIKit.h>
21#include <Accelerate/Accelerate.h>
29std::optional<vImage_CGImageFormat> qt_mac_cgImageFormatForImage(
const QImage &image)
31 const QPixelFormat format = image.pixelFormat();
35 if (format.colorModel() != QPixelFormat::RGB)
38 const int alphaBits = format.alphaSize();
40 CGBitmapInfo bitmapInfo = [&]{
42 return kCGImageAlphaNone;
44 if (format.channelCount() == 1)
45 return kCGImageAlphaOnly;
47 return CGImageAlphaInfo(
48 (format.alphaUsage() == QPixelFormat::IgnoresAlpha ?
49 kCGImageAlphaNoneSkipLast
50 : (format.premultiplied() == QPixelFormat::Premultiplied ?
51 kCGImageAlphaPremultipliedLast : kCGImageAlphaLast)
53 + (format.alphaPosition() == QPixelFormat::AtBeginning ? 1 : 0)
57 const std::tuple rgbBits{format.redSize(), format.greenSize(), format.blueSize() };
59 const CGImageByteOrderInfo byteOrder16Bit =
60 format.byteOrder() == QPixelFormat::LittleEndian ?
61 kCGImageByteOrder16Little : kCGImageByteOrder16Big;
63 const CGImageByteOrderInfo byteOrder32Bit =
64 format.byteOrder() == QPixelFormat::LittleEndian ?
65 kCGImageByteOrder32Little : kCGImageByteOrder32Big;
67 static const auto isPacked = [](
const QPixelFormat f) {
68 return f.redSize() == f.greenSize()
69 && f.greenSize() == f.blueSize()
70 && (!f.alphaSize() || f.alphaSize() == f.blueSize());
73 switch (format.typeInterpretation()) {
74 case QPixelFormat::UnsignedByte:
78 if (format.bitsPerPixel() == 32)
79 bitmapInfo |= kCGImageByteOrder32Big;
80 else if (format.bitsPerPixel() == 16)
81 bitmapInfo |= kCGImageByteOrder16Big;
83 bitmapInfo |= kCGImageByteOrderDefault;
85 case QPixelFormat::UnsignedShort:
86 bitmapInfo |= byteOrder16Bit;
88 bitmapInfo |= kCGImagePixelFormatPacked;
89 else if (rgbBits == std::tuple{5,5,5} && alphaBits == 1)
90 bitmapInfo |= kCGImagePixelFormatRGB555;
91 else if (rgbBits == std::tuple{5,6,5} && !alphaBits)
92 bitmapInfo |= kCGImagePixelFormatRGB565;
96 case QPixelFormat::UnsignedInteger:
97 bitmapInfo |= byteOrder32Bit;
99 bitmapInfo |= kCGImagePixelFormatPacked;
100 else if (rgbBits == std::tuple{10,10,10} && alphaBits == 2)
101 bitmapInfo |= kCGImagePixelFormatRGB101010;
105 case QPixelFormat::FloatingPoint:
106 bitmapInfo |= kCGBitmapFloatComponents;
107 if (!isPacked(format))
109 if (format.bitsPerPixel() == 128)
110 bitmapInfo |= byteOrder32Bit;
111 else if (format.bitsPerPixel() == 64)
112 bitmapInfo |= byteOrder16Bit;
120 const uint32_t bitsPerComponent = std::min({
121 format.redSize(), format.greenSize(), format.blueSize()
124 QCFType<CGColorSpaceRef> colorSpace = [&]{
125 if (
const auto colorSpace = image.colorSpace(); colorSpace.isValid()) {
126 QCFType<CFDataRef> iccData = colorSpace.iccProfile().toCFData();
127 return CGColorSpaceCreateWithICCData(iccData);
129 return CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
133 return vImage_CGImageFormat{
134 bitsPerComponent, format.bitsPerPixel(),
135 colorSpace, bitmapInfo, 0,
nullptr,
136 kCGRenderingIntentDefault
142 CGImageRef cgImage = inImage.toCGImage();
147 return inImage.convertToFormat(QImage::Format_ARGB32_Premultiplied).toCGImage();
152 CGContextSaveGState( inContext );
153 CGContextTranslateCTM (inContext, 0, inBounds->origin.y + CGRectGetMaxY(*inBounds));
154 CGContextScaleCTM(inContext, 1, -1);
156 CGContextDrawImage(inContext, *inBounds, inImage);
158 CGContextRestoreGState(inContext);
164 return QImage::Format_Invalid;
166 const CGColorSpaceRef colorSpace = CGImageGetColorSpace(image);
167 if (CGColorSpaceGetModel(colorSpace) != kCGColorSpaceModelRGB)
168 return QImage::Format_Invalid;
170 const CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(image);
171 const auto byteOrder = CGImageByteOrderInfo(bitmapInfo & kCGBitmapByteOrderMask);
173 auto qtByteOrder = [&]() -> std::optional<QPixelFormat::ByteOrder> {
175 case kCGImageByteOrder16Big:
176 case kCGImageByteOrder32Big:
177 case kCGImageByteOrderDefault:
178 return QPixelFormat::BigEndian;
179 case kCGImageByteOrder16Little:
180 case kCGImageByteOrder32Little:
181 return QPixelFormat::LittleEndian;
187 return QImage::Format_Invalid;
189 auto typeInterpretation = [&]() -> std::optional<QPixelFormat::TypeInterpretation> {
190 if (bitmapInfo & kCGBitmapFloatComponents)
191 return QPixelFormat::FloatingPoint;
192 else if (qtByteOrder == QPixelFormat::BigEndian)
195 return QPixelFormat::UnsignedByte;
196 else if (byteOrder == kCGImageByteOrder16Little)
197 return QPixelFormat::UnsignedShort;
198 else if (byteOrder == kCGImageByteOrder32Little)
199 return QPixelFormat::UnsignedInteger;
203 if (!typeInterpretation)
204 return QImage::Format_Invalid;
206 const auto alphaInfo = CGImageAlphaInfo(bitmapInfo & kCGBitmapAlphaInfoMask);
208 QPixelFormat::AlphaPosition alphaPosition = [&]{
210 case kCGImageAlphaNone:
211 case kCGImageAlphaFirst:
212 case kCGImageAlphaNoneSkipFirst:
213 case kCGImageAlphaPremultipliedFirst:
214 return QPixelFormat::AtBeginning;
216 return QPixelFormat::AtEnd;
220 QPixelFormat::AlphaUsage alphaUsage = [&]{
222 case kCGImageAlphaNone:
223 case kCGImageAlphaNoneSkipLast:
224 case kCGImageAlphaNoneSkipFirst:
225 return QPixelFormat::IgnoresAlpha;
227 return QPixelFormat::UsesAlpha;
231 QPixelFormat::AlphaPremultiplied alphaPremultiplied = [&]{
233 case kCGImageAlphaPremultipliedFirst:
234 case kCGImageAlphaPremultipliedLast:
235 return QPixelFormat::Premultiplied;
237 return QPixelFormat::NotPremultiplied;
241 auto [redSize, greenSize, blueSize, alphaSize] = [&]() -> std::tuple<uchar,uchar,uchar,uchar> {
242 const auto pixelFormat = CGImagePixelFormatInfo(bitmapInfo & kCGImagePixelFormatMask);
243 const size_t bpc = CGImageGetBitsPerComponent(image);
244 if (pixelFormat == kCGImagePixelFormatPacked)
245 return {bpc, bpc, bpc, alphaInfo != kCGImageAlphaNone ? bpc : 0};
246 else if (pixelFormat == kCGImagePixelFormatRGB555)
248 else if (pixelFormat == kCGImagePixelFormatRGB565)
250 else if (pixelFormat == kCGImagePixelFormatRGB101010)
251 return {10, 10, 10, 2};
256 QPixelFormat pixelFormat(QPixelFormat::RGB, redSize, greenSize, blueSize, 0, 0,
257 alphaSize, alphaUsage, alphaPosition, alphaPremultiplied,
258 *typeInterpretation, *qtByteOrder);
260 return QImage::toImageFormat(pixelFormat);
265 const size_t width = CGImageGetWidth(cgImage);
266 const size_t height = CGImageGetHeight(cgImage);
268 QImage image = [&]() -> QImage {
269 QImage::Format imageFormat = qt_mac_imageFormatForCGImage(cgImage);
270 if (imageFormat == QImage::Format_Invalid)
273 CGDataProviderRef dataProvider = CGImageGetDataProvider(cgImage);
278 CFDataRef data = CGDataProviderCopyData(dataProvider);
283 return QImage(CFDataGetBytePtr(data), width, height,
284 CGImageGetBytesPerRow(cgImage), imageFormat,
285 QImageCleanupFunction(CFRelease), (
void*)data);
288 if (image.isNull()) {
290 image = QImage(width, height, QImage::Format_ARGB32_Premultiplied);
291 image.fill(Qt::transparent);
293 CGRect rect = CGRectMake(0, 0, width, height);
294 qt_mac_drawCGImage(context, &rect, cgImage);
297 if (!image.isNull()) {
298 CGColorSpaceRef colorSpace = CGImageGetColorSpace(cgImage);
299 QCFType<CFDataRef> iccData = CGColorSpaceCopyICCData(colorSpace);
300 image.setColorSpace(QColorSpace::fromIccProfile(QByteArray::fromRawCFData(iccData)));
310@implementation NSImage (QtExtras)
311+ (instancetype)imageFromQImage:(
const QImage &)image
316 QCFType<CGImageRef> cgImage = image.toCGImage();
325 auto nsImage = [[NSImage alloc] initWithSize:NSZeroSize];
326 auto *imageRep = [[NSBitmapImageRep alloc] initWithCGImage:cgImage];
327 imageRep.size = image.deviceIndependentSize().toCGSize();
328 [nsImage addRepresentation:[imageRep autorelease]];
329 Q_ASSERT(CGSizeEqualToSize(nsImage.size, imageRep.size));
331 return [nsImage autorelease];
334+ (instancetype)imageFromQIcon:(
const QIcon &)icon
336 return [NSImage imageFromQIcon:icon withSize:QSize()];
339+ (instancetype)imageFromQIcon:(
const QIcon &)icon withSize:(
const QSize &)size
341 return [NSImage imageFromQIcon:icon withSize:size withMode:QIcon::Normal withState:QIcon::Off];
344+ (instancetype)imageFromQIcon:(
const QIcon &)icon withSize:(
const QSize &)size
345 withMode:(QIcon::Mode)mode withState:(QIcon::State)state
351 auto availableSizes = icon.availableSizes();
352 if (availableSizes.isEmpty() && !size.isNull())
353 availableSizes << size;
355 auto nsImage = [[[NSImage alloc] initWithSize:NSZeroSize] autorelease];
357 for (QSize size : std::as_const(availableSizes)) {
358 const QImage image = icon.pixmap(size, mode, state).toImage();
362 QCFType<CGImageRef> cgImage = image.toCGImage();
366 auto *imageRep = [[NSBitmapImageRep alloc] initWithCGImage:cgImage];
367 imageRep.size = image.deviceIndependentSize().toCGSize();
368 [nsImage addRepresentation:[imageRep autorelease]];
371 nsImage.size = imageRep.size;
374 if (!nsImage.representations.count)
377 [nsImage setTemplate:icon.isMask()];
379 if (!size.isNull()) {
380 auto imageSize = QSizeF::fromCGSize(nsImage.size);
381 nsImage.size = imageSize.scaled(size, Qt::KeepAspectRatio).toCGSize();
390QPixmap qt_mac_toQPixmap(
const NSImage *image,
const QSizeF &size)
395 const NSSize pixmapSize = NSMakeSize(size.width(), size.height());
396 QPixmap pixmap(pixmapSize.width, pixmapSize.height);
397 pixmap.fill(Qt::transparent);
398 [image setSize:pixmapSize];
399 const NSRect iconRect = NSMakeRect(0, 0, pixmapSize.width, pixmapSize.height);
400 QMacCGContext ctx(&pixmap);
403 NSGraphicsContext *gc = [NSGraphicsContext graphicsContextWithCGContext:ctx flipped:YES];
406 [NSGraphicsContext saveGraphicsState];
407 [NSGraphicsContext setCurrentContext:gc];
408 [image drawInRect:iconRect fromRect:iconRect operation:NSCompositingOperationSourceOver fraction:1.0 respectFlipped:YES hints:nil];
409 [NSGraphicsContext restoreGraphicsState];
415#ifdef QT_PLATFORM_UIKIT
417QImage qt_mac_toQImage(
const UIImage *image, QSizeF size)
420 QImage ret(size.width(), size.height(), QImage::Format_ARGB32_Premultiplied);
421 ret.fill(Qt::transparent);
422 QMacCGContext ctx(&ret);
425 UIGraphicsPushContext(ctx);
426 const CGRect rect = CGRectMake(0, 0, size.width(), size.height());
427 [image drawInRect:rect];
428 UIGraphicsPopContext();
439 CGColorSpaceModel model = CGColorSpaceGetModel(CGColorGetColorSpace(color));
440 const CGFloat *components = CGColorGetComponents(color);
441 if (model == kCGColorSpaceModelRGB) {
442 qtColor.setRgbF(components[0], components[1], components[2], components[3]);
443 }
else if (model == kCGColorSpaceModelCMYK) {
444 qtColor.setCmykF(components[0], components[1], components[2], components[3]);
445 }
else if (model == kCGColorSpaceModelMonochrome) {
446 qtColor.setRgbF(components[0], components[0], components[0], components[1]);
449 qWarning(
"Qt: qt_mac_toQColor: cannot convert from colorspace model: %d", model);
456QColor qt_mac_toQColor(
const NSColor *color)
462 switch (color.type) {
463 case NSColorTypeComponentBased: {
464 const NSColorSpace *colorSpace = [color colorSpace];
465 if (colorSpace == NSColorSpace.genericRGBColorSpace
466 && color.numberOfComponents == 4) {
467 CGFloat components[4];
468 [color getComponents:components];
469 qtColor.setRgbF(components[0], components[1], components[2], components[3]);
471 }
else if (colorSpace == NSColorSpace.genericCMYKColorSpace
472 && color.numberOfComponents == 5) {
473 CGFloat components[5];
474 [color getComponents:components];
475 qtColor.setCmykF(components[0], components[1], components[2], components[3], components[4]);
481 const NSColor *tmpColor = [color colorUsingColorSpace:NSColorSpace.genericRGBColorSpace];
482 CGFloat red = 0, green = 0, blue = 0, alpha = 0;
483 [tmpColor getRed:&red green:&green blue:&blue alpha:&alpha];
484 qtColor.setRgbF(red, green, blue, alpha);
496 CGColorSpaceModel model = CGColorSpaceGetModel(CGColorGetColorSpace(color));
497 if (model == kCGColorSpaceModelPattern) {
499 qWarning(
"Qt: qt_mac_toQBrush: cannot convert from colorspace model: %d", model);
502 qtBrush.setStyle(Qt::SolidPattern);
503 qtBrush.setColor(qt_mac_toQColor(color));
509static bool qt_mac_isSystemColorOrInstance(
const NSColor *color, NSString *colorNameComponent, NSString *className)
512 if ([color.className isEqualToString:className])
514 if (color.type == NSColorTypeCatalog &&
515 [color.catalogNameComponent isEqualToString:@
"System"] &&
516 [color.colorNameComponent isEqualToString:colorNameComponent])
521QBrush qt_mac_toQBrush(
const NSColor *color, QPalette::ColorGroup colorGroup)
526 if ([color.className isEqualToString:@
"NSMenuItemHighlightColor"]) {
527 qWarning(
"Qt: qt_mac_toQBrush: cannot convert from NSMenuItemHighlightColor");
533 if ([color.className isEqualToString:@
"NSMetalPatternColor"]) {
539 qWarning(
"Qt: qt_mac_toQBrush: cannot convert from NSMetalPatternColor");
546 if (qt_mac_isSystemColorOrInstance(color, @
"_sourceListBackgroundColor", @
"NSSourceListBackgroundColor")) {
547 QLinearGradient gradient;
548 if (colorGroup == QPalette::Active) {
549 gradient.setColorAt(0, QColor(233, 237, 242));
550 gradient.setColorAt(0.5, QColor(225, 229, 235));
551 gradient.setColorAt(1, QColor(209, 216, 224));
553 gradient.setColorAt(0, QColor(248, 248, 248));
554 gradient.setColorAt(0.5, QColor(240, 240, 240));
555 gradient.setColorAt(1, QColor(235, 235, 235));
557 return QBrush(gradient);
565 if (qt_mac_isSystemColorOrInstance(color, @
"controlColor", @
"NSGradientPatternColor") ||
566 qt_mac_isSystemColorOrInstance(color, @
"windowBackgroundColor", @
"NSGradientPatternColor")) {
567 qtBrush.setStyle(Qt::SolidPattern);
568 qtBrush.setColor(qt_mac_toQColor(color.CGColor));
572 if (color.type == NSColorTypePattern) {
573 NSImage *patternImage = color.patternImage;
574 const QSizeF sz(patternImage.size.width, patternImage.size.height);
576 qtBrush.setTexture(qt_mac_toQPixmap(patternImage, sz));
578 qtBrush.setStyle(Qt::SolidPattern);
579 qtBrush.setColor(qt_mac_toQColor(color));
587void qt_mac_clip_cg(CGContextRef hd,
const QRegion &rgn, CGAffineTransform *orig_xform)
589 CGAffineTransform old_xform = CGAffineTransformIdentity;
591 old_xform = CGContextGetCTM(hd);
592 CGContextConcatCTM(hd, CGAffineTransformInvert(old_xform));
593 CGContextConcatCTM(hd, *orig_xform);
597 CGContextBeginPath(hd);
599 CGContextAddRect(hd, CGRectMake(0, 0, 0, 0));
601 for (
const QRect &r : rgn) {
602 CGRect mac_r = CGRectMake(r.x(), r.y(), r.width(), r.height());
603 CGContextAddRect(hd, mac_r);
609 CGContextConcatCTM(hd, CGAffineTransformInvert(CGContextGetCTM(hd)));
610 CGContextConcatCTM(hd, old_xform);
617 if (!region || !region->rectCount())
620 QVector<QRect> scaledRects;
621 scaledRects.reserve(region->rectCount());
623 for (
const QRect &rect : *region)
624 scaledRects.append(QRect(rect.topLeft() * scaleFactor, rect.size() * scaleFactor));
626 region->setRects(&scaledRects[0], scaledRects.count());
631QMacCGContext::QMacCGContext(QPaintDevice *paintDevice)
633 initialize(paintDevice);
636void QMacCGContext::initialize(QPaintDevice *paintDevice)
639 switch (
int deviceType = paintDevice->devType()) {
640 case QInternal::Pixmap: {
641 if (
auto *platformPixmap =
static_cast<QPixmap*>(paintDevice)->handle()) {
642 if (platformPixmap->classId() == QPlatformPixmap::RasterClass)
643 initialize(platformPixmap->buffer());
645 qWarning() <<
"QMacCGContext: Unsupported pixmap class" << platformPixmap->classId();
647 qWarning() <<
"QMacCGContext: Empty platformPixmap";
651 case QInternal::Image:
652 initialize(
static_cast<
const QImage *>(paintDevice));
654 case QInternal::Widget:
655 qWarning() <<
"QMacCGContext: not implemented: Widget class";
658 qWarning() <<
"QMacCGContext:: Unsupported paint device type" << deviceType;
662QMacCGContext::QMacCGContext(QPainter *painter)
664 QPaintEngine *paintEngine = painter->paintEngine();
667 while (QPaintEngine *aggregateEngine = QPaintEnginePrivate::get(paintEngine)->aggregateEngine())
668 paintEngine = aggregateEngine;
670 paintEngine->syncState();
672 if (Qt::HANDLE handle = QPaintEnginePrivate::get(paintEngine)->nativeHandle()) {
673 context =
static_cast<CGContextRef>(handle);
677 if (paintEngine->type() != QPaintEngine::Raster) {
678 qWarning() <<
"QMacCGContext:: Unsupported paint engine type" << paintEngine->type();
683 Q_ASSERT(paintEngine->paintDevice()->devType() == QInternal::Image);
686 switch (
int painterDeviceType = painter->device()->devType()) {
687 case QInternal::Pixmap:
688 case QInternal::Image:
689 case QInternal::Widget:
692 qWarning() <<
"QMacCGContext:: Unsupported paint device type" << painterDeviceType;
698 initialize(
static_cast<
const QImage *>(paintEngine->paintDevice()), painter);
701void QMacCGContext::initialize(
const QImage *image, QPainter *painter)
703 auto cgImageFormat = qt_mac_cgImageFormatForImage(*image);
704 if (!cgImageFormat) {
705 qWarning() <<
"QMacCGContext:: Could not get bitmap info for" << image;
709 context = CGBitmapContextCreate((
void *)image->bits(), image->width(), image->height(),
710 cgImageFormat->bitsPerComponent, image->bytesPerLine(), cgImageFormat->colorSpace,
711 cgImageFormat->bitmapInfo);
714 CGContextTranslateCTM(context, 0, image->height());
715 CGContextScaleCTM(context, 1, -1);
717 const qreal devicePixelRatio = image->devicePixelRatio();
719 if (painter && painter->device()->devType() == QInternal::Widget) {
721 QRegion clip = painter->paintEngine()->systemClip();
722 QTransform deviceTransform = painter->deviceTransform();
724 if (painter->hasClipping()) {
727 QRegion painterClip = painter->clipRegion();
728 qt_mac_scale_region(&painterClip, devicePixelRatio);
730 painterClip.translate(deviceTransform.dx(), deviceTransform.dy());
738 qt_mac_clip_cg(context, clip,
nullptr);
740 CGContextTranslateCTM(context, deviceTransform.dx(), deviceTransform.dy());
744 CGContextScaleCTM(context, devicePixelRatio, devicePixelRatio);
The QColor class provides colors based on RGB, HSV or CMYK values.
void qt_mac_drawCGImage(CGContextRef inContext, const CGRect *inBounds, CGImageRef inImage)
QBrush qt_mac_toQBrush(CGColorRef color)
QImage::Format qt_mac_imageFormatForCGImage(CGImageRef image)
void qt_mac_clip_cg(CGContextRef hd, const QRegion &rgn, CGAffineTransform *orig_xform)
QColor qt_mac_toQColor(CGColorRef color)
void qt_mac_scale_region(QRegion *region, qreal scaleFactor)
QImage qt_mac_toQImage(CGImageRef cgImage)
CGImageRef qt_mac_toCGImage(const QImage &inImage)