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>
14#include <QtGui/private/qicon_p.h>
16#if defined(Q_OS_MACOS)
17# include <AppKit/AppKit.h>
18#elif defined(QT_PLATFORM_UIKIT)
19# include <UIKit/UIKit.h>
22#include <Accelerate/Accelerate.h>
30std::optional<vImage_CGImageFormat> qt_mac_cgImageFormatForImage(
const QImage &image)
32 const QPixelFormat format = image.pixelFormat();
36 if (format.colorModel() != QPixelFormat::RGB)
39 const int alphaBits = format.alphaSize();
41 CGBitmapInfo bitmapInfo = [&]{
43 return kCGImageAlphaNone;
45 if (format.channelCount() == 1)
46 return kCGImageAlphaOnly;
48 return CGImageAlphaInfo(
49 (format.alphaUsage() == QPixelFormat::IgnoresAlpha ?
50 kCGImageAlphaNoneSkipLast
51 : (format.premultiplied() == QPixelFormat::Premultiplied ?
52 kCGImageAlphaPremultipliedLast : kCGImageAlphaLast)
54 + (format.alphaPosition() == QPixelFormat::AtBeginning ? 1 : 0)
58 const std::tuple rgbBits{format.redSize(), format.greenSize(), format.blueSize() };
60 const CGImageByteOrderInfo byteOrder16Bit =
61 format.byteOrder() == QPixelFormat::LittleEndian ?
62 kCGImageByteOrder16Little : kCGImageByteOrder16Big;
64 const CGImageByteOrderInfo byteOrder32Bit =
65 format.byteOrder() == QPixelFormat::LittleEndian ?
66 kCGImageByteOrder32Little : kCGImageByteOrder32Big;
68 static const auto isPacked = [](
const QPixelFormat f) {
69 return f.redSize() == f.greenSize()
70 && f.greenSize() == f.blueSize()
71 && (!f.alphaSize() || f.alphaSize() == f.blueSize());
74 switch (format.typeInterpretation()) {
75 case QPixelFormat::UnsignedByte:
79 if (format.bitsPerPixel() == 32)
80 bitmapInfo |= kCGImageByteOrder32Big;
81 else if (format.bitsPerPixel() == 16)
82 bitmapInfo |= kCGImageByteOrder16Big;
84 bitmapInfo |= kCGImageByteOrderDefault;
86 case QPixelFormat::UnsignedShort:
87 bitmapInfo |= byteOrder16Bit;
89 bitmapInfo |= kCGImagePixelFormatPacked;
90 else if (rgbBits == std::tuple{5,5,5} && alphaBits == 1)
91 bitmapInfo |= kCGImagePixelFormatRGB555;
92 else if (rgbBits == std::tuple{5,6,5} && !alphaBits)
93 bitmapInfo |= kCGImagePixelFormatRGB565;
97 case QPixelFormat::UnsignedInteger:
98 bitmapInfo |= byteOrder32Bit;
100 bitmapInfo |= kCGImagePixelFormatPacked;
101 else if (rgbBits == std::tuple{10,10,10} && alphaBits == 2)
102 bitmapInfo |= kCGImagePixelFormatRGB101010;
106 case QPixelFormat::FloatingPoint:
107 bitmapInfo |= kCGBitmapFloatComponents;
108 if (!isPacked(format))
110 if (format.bitsPerPixel() == 128)
111 bitmapInfo |= byteOrder32Bit;
112 else if (format.bitsPerPixel() == 64)
113 bitmapInfo |= byteOrder16Bit;
121 const uint32_t bitsPerComponent = std::min({
122 format.redSize(), format.greenSize(), format.blueSize()
125 QCFType<CGColorSpaceRef> colorSpace = [&]{
126 if (
const auto colorSpace = image.colorSpace(); colorSpace.isValid()) {
127 QCFType<CFDataRef> iccData = colorSpace.iccProfile().toCFData();
128 return CGColorSpaceCreateWithICCData(iccData);
130 return CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
134 return vImage_CGImageFormat{
135 bitsPerComponent, format.bitsPerPixel(),
136 colorSpace, bitmapInfo, 0,
nullptr,
137 kCGRenderingIntentDefault
143 CGImageRef cgImage = inImage.toCGImage();
148 return inImage.convertToFormat(QImage::Format_ARGB32_Premultiplied).toCGImage();
153 CGContextSaveGState( inContext );
154 CGContextTranslateCTM (inContext, 0, inBounds->origin.y + CGRectGetMaxY(*inBounds));
155 CGContextScaleCTM(inContext, 1, -1);
157 CGContextDrawImage(inContext, *inBounds, inImage);
159 CGContextRestoreGState(inContext);
165 return QImage::Format_Invalid;
167 const CGColorSpaceRef colorSpace = CGImageGetColorSpace(image);
168 if (CGColorSpaceGetModel(colorSpace) != kCGColorSpaceModelRGB)
169 return QImage::Format_Invalid;
171 const CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(image);
172 const auto byteOrder = CGImageByteOrderInfo(bitmapInfo & kCGBitmapByteOrderMask);
174 auto qtByteOrder = [&]() -> std::optional<QPixelFormat::ByteOrder> {
176 case kCGImageByteOrder16Big:
177 case kCGImageByteOrder32Big:
178 case kCGImageByteOrderDefault:
179 return QPixelFormat::BigEndian;
180 case kCGImageByteOrder16Little:
181 case kCGImageByteOrder32Little:
182 return QPixelFormat::LittleEndian;
188 return QImage::Format_Invalid;
190 auto typeInterpretation = [&]() -> std::optional<QPixelFormat::TypeInterpretation> {
191 if (bitmapInfo & kCGBitmapFloatComponents)
192 return QPixelFormat::FloatingPoint;
193 else if (qtByteOrder == QPixelFormat::BigEndian)
196 return QPixelFormat::UnsignedByte;
197 else if (byteOrder == kCGImageByteOrder16Little)
198 return QPixelFormat::UnsignedShort;
199 else if (byteOrder == kCGImageByteOrder32Little)
200 return QPixelFormat::UnsignedInteger;
204 if (!typeInterpretation)
205 return QImage::Format_Invalid;
207 const auto alphaInfo = CGImageAlphaInfo(bitmapInfo & kCGBitmapAlphaInfoMask);
209 QPixelFormat::AlphaPosition alphaPosition = [&]{
211 case kCGImageAlphaNone:
212 case kCGImageAlphaFirst:
213 case kCGImageAlphaNoneSkipFirst:
214 case kCGImageAlphaPremultipliedFirst:
215 return QPixelFormat::AtBeginning;
217 return QPixelFormat::AtEnd;
221 QPixelFormat::AlphaUsage alphaUsage = [&]{
223 case kCGImageAlphaNone:
224 case kCGImageAlphaNoneSkipLast:
225 case kCGImageAlphaNoneSkipFirst:
226 return QPixelFormat::IgnoresAlpha;
228 return QPixelFormat::UsesAlpha;
232 QPixelFormat::AlphaPremultiplied alphaPremultiplied = [&]{
234 case kCGImageAlphaPremultipliedFirst:
235 case kCGImageAlphaPremultipliedLast:
236 return QPixelFormat::Premultiplied;
238 return QPixelFormat::NotPremultiplied;
242 auto [redSize, greenSize, blueSize, alphaSize] = [&]() -> std::tuple<uchar,uchar,uchar,uchar> {
243 const auto pixelFormat = CGImagePixelFormatInfo(bitmapInfo & kCGImagePixelFormatMask);
244 const size_t bpc = CGImageGetBitsPerComponent(image);
245 if (pixelFormat == kCGImagePixelFormatPacked)
246 return {bpc, bpc, bpc, alphaInfo != kCGImageAlphaNone ? bpc : 0};
247 else if (pixelFormat == kCGImagePixelFormatRGB555)
249 else if (pixelFormat == kCGImagePixelFormatRGB565)
251 else if (pixelFormat == kCGImagePixelFormatRGB101010)
252 return {10, 10, 10, 2};
257 QPixelFormat pixelFormat(QPixelFormat::RGB, redSize, greenSize, blueSize, 0, 0,
258 alphaSize, alphaUsage, alphaPosition, alphaPremultiplied,
259 *typeInterpretation, *qtByteOrder);
261 return QImage::toImageFormat(pixelFormat);
266 const size_t width = CGImageGetWidth(cgImage);
267 const size_t height = CGImageGetHeight(cgImage);
269 QImage image = [&]() -> QImage {
270 QImage::Format imageFormat = qt_mac_imageFormatForCGImage(cgImage);
271 if (imageFormat == QImage::Format_Invalid)
274 CGDataProviderRef dataProvider = CGImageGetDataProvider(cgImage);
279 CFDataRef data = CGDataProviderCopyData(dataProvider);
284 return QImage(CFDataGetBytePtr(data), width, height,
285 CGImageGetBytesPerRow(cgImage), imageFormat,
286 QImageCleanupFunction(CFRelease), (
void*)data);
289 if (image.isNull()) {
291 image = QImage(width, height, QImage::Format_ARGB32_Premultiplied);
292 image.fill(Qt::transparent);
294 CGRect rect = CGRectMake(0, 0, width, height);
295 qt_mac_drawCGImage(context, &rect, cgImage);
298 if (!image.isNull()) {
299 CGColorSpaceRef colorSpace = CGImageGetColorSpace(cgImage);
300 QCFType<CFDataRef> iccData = CGColorSpaceCopyICCData(colorSpace);
301 image.setColorSpace(QColorSpace::fromIccProfile(QByteArray::fromRawCFData(iccData)));
309 if (image.width() == image.height())
312 const int size = std::max(image.width(), image.height());
313 QImage squareImage(size, size, image.format());
314 squareImage.setDevicePixelRatio(image.devicePixelRatio());
315 squareImage.fill(Qt::transparent);
317 QPoint pos((size - image.width()) / (2.0 * image.devicePixelRatio()),
318 (size - image.height()) / (2.0 * image.devicePixelRatio()));
320 QPainter painter(&squareImage);
321 painter.drawImage(pos, image);
331@implementation NSImage (QtExtras)
332+ (instancetype)imageFromQImage:(
const QImage &)image
337 QCFType<CGImageRef> cgImage = image.toCGImage();
346 auto nsImage = [[NSImage alloc] initWithSize:NSZeroSize];
347 auto *imageRep = [[NSBitmapImageRep alloc] initWithCGImage:cgImage];
348 imageRep.size = image.deviceIndependentSize().toCGSize();
349 [nsImage addRepresentation:[imageRep autorelease]];
350 Q_ASSERT(CGSizeEqualToSize(nsImage.size, imageRep.size));
352 return [nsImage autorelease];
355+ (instancetype)imageFromQIcon:(
const QIcon &)icon
357 return [NSImage imageFromQIcon:icon withSize:QSize()];
360+ (instancetype)imageFromQIcon:(
const QIcon &)icon withSize:(
const QSize &)size
362 return [NSImage imageFromQIcon:icon withSize:size withMode:QIcon::Normal withState:QIcon::Off];
365+ (instancetype)imageFromQIcon:(
const QIcon &)icon withSize:(
const QSize &)size
366 withMode:(QIcon::Mode)mode withState:(QIcon::State)state
372 auto availableSizes = icon.availableSizes();
373 if (availableSizes.isEmpty() && !size.isNull())
374 availableSizes << size;
376 auto nsImage = [[[NSImage alloc] initWithSize:NSZeroSize] autorelease];
378 for (QSize size : std::as_const(availableSizes)) {
379 const QImage image = icon.pixmap(size, mode, state).toImage();
383 QCFType<CGImageRef> cgImage = image.toCGImage();
387 auto *imageRep = [[NSBitmapImageRep alloc] initWithCGImage:cgImage];
388 imageRep.size = image.deviceIndependentSize().toCGSize();
389 [nsImage addRepresentation:[imageRep autorelease]];
392 nsImage.size = imageRep.size;
395 if (!nsImage.representations.count)
398 [nsImage setTemplate:icon.isMask()];
400 if (!size.isNull()) {
401 auto imageSize = QSizeF::fromCGSize(nsImage.size);
402 nsImage.size = imageSize.scaled(size, Qt::KeepAspectRatio).toCGSize();
408+ (instancetype)internalImageFromQIcon:(
const QT_PREPEND_NAMESPACE(QIcon) &)icon
414 auto *iconPrivate = QIconPrivate::get(&icon);
415 NSImage *iconImage =
nullptr;
416 iconPrivate->engine->virtual_hook(QIconPrivate::PlatformIconHook, &iconImage);
424QPixmap qt_mac_toQPixmap(
const NSImage *image,
const QSizeF &size)
429 const NSSize pixmapSize = NSMakeSize(size.width(), size.height());
430 QPixmap pixmap(pixmapSize.width, pixmapSize.height);
431 pixmap.fill(Qt::transparent);
432 [image setSize:pixmapSize];
433 const NSRect iconRect = NSMakeRect(0, 0, pixmapSize.width, pixmapSize.height);
434 QMacCGContext ctx(&pixmap);
437 NSGraphicsContext *gc = [NSGraphicsContext graphicsContextWithCGContext:ctx flipped:YES];
440 [NSGraphicsContext saveGraphicsState];
441 [NSGraphicsContext setCurrentContext:gc];
442 [image drawInRect:iconRect fromRect:iconRect operation:NSCompositingOperationSourceOver fraction:1.0 respectFlipped:YES hints:nil];
443 [NSGraphicsContext restoreGraphicsState];
449#ifdef QT_PLATFORM_UIKIT
451QImage qt_mac_toQImage(
const UIImage *image, QSizeF size)
454 QImage ret(size.width(), size.height(), QImage::Format_ARGB32_Premultiplied);
455 ret.fill(Qt::transparent);
456 QMacCGContext ctx(&ret);
459 UIGraphicsPushContext(ctx);
460 const CGRect rect = CGRectMake(0, 0, size.width(), size.height());
461 [image drawInRect:rect];
462 UIGraphicsPopContext();
473 CGColorSpaceModel model = CGColorSpaceGetModel(CGColorGetColorSpace(color));
474 const CGFloat *components = CGColorGetComponents(color);
475 if (model == kCGColorSpaceModelRGB) {
476 qtColor.setRgbF(components[0], components[1], components[2], components[3]);
477 }
else if (model == kCGColorSpaceModelCMYK) {
478 qtColor.setCmykF(components[0], components[1], components[2], components[3]);
479 }
else if (model == kCGColorSpaceModelMonochrome) {
480 qtColor.setRgbF(components[0], components[0], components[0], components[1]);
483 qWarning(
"Qt: qt_mac_toQColor: cannot convert from colorspace model: %d", model);
490QColor qt_mac_toQColor(
const NSColor *color)
496 switch (color.type) {
497 case NSColorTypeComponentBased: {
498 const NSColorSpace *colorSpace = [color colorSpace];
499 if (colorSpace == NSColorSpace.genericRGBColorSpace
500 && color.numberOfComponents == 4) {
501 CGFloat components[4];
502 [color getComponents:components];
503 qtColor.setRgbF(components[0], components[1], components[2], components[3]);
505 }
else if (colorSpace == NSColorSpace.genericCMYKColorSpace
506 && color.numberOfComponents == 5) {
507 CGFloat components[5];
508 [color getComponents:components];
509 qtColor.setCmykF(components[0], components[1], components[2], components[3], components[4]);
515 const NSColor *tmpColor = [color colorUsingColorSpace:NSColorSpace.genericRGBColorSpace];
516 CGFloat red = 0, green = 0, blue = 0, alpha = 0;
517 [tmpColor getRed:&red green:&green blue:&blue alpha:&alpha];
518 qtColor.setRgbF(red, green, blue, alpha);
530 CGColorSpaceModel model = CGColorSpaceGetModel(CGColorGetColorSpace(color));
531 if (model == kCGColorSpaceModelPattern) {
533 qWarning(
"Qt: qt_mac_toQBrush: cannot convert from colorspace model: %d", model);
536 qtBrush.setStyle(Qt::SolidPattern);
537 qtBrush.setColor(qt_mac_toQColor(color));
543static bool qt_mac_isSystemColorOrInstance(
const NSColor *color, NSString *colorNameComponent, NSString *className)
546 if ([color.className isEqualToString:className])
548 if (color.type == NSColorTypeCatalog &&
549 [color.catalogNameComponent isEqualToString:@
"System"] &&
550 [color.colorNameComponent isEqualToString:colorNameComponent])
555QBrush qt_mac_toQBrush(
const NSColor *color, QPalette::ColorGroup colorGroup)
560 if ([color.className isEqualToString:@
"NSMenuItemHighlightColor"]) {
561 qWarning(
"Qt: qt_mac_toQBrush: cannot convert from NSMenuItemHighlightColor");
567 if ([color.className isEqualToString:@
"NSMetalPatternColor"]) {
573 qWarning(
"Qt: qt_mac_toQBrush: cannot convert from NSMetalPatternColor");
580 if (qt_mac_isSystemColorOrInstance(color, @
"_sourceListBackgroundColor", @
"NSSourceListBackgroundColor")) {
581 QLinearGradient gradient;
582 if (colorGroup == QPalette::Active) {
583 gradient.setColorAt(0, QColor(233, 237, 242));
584 gradient.setColorAt(0.5, QColor(225, 229, 235));
585 gradient.setColorAt(1, QColor(209, 216, 224));
587 gradient.setColorAt(0, QColor(248, 248, 248));
588 gradient.setColorAt(0.5, QColor(240, 240, 240));
589 gradient.setColorAt(1, QColor(235, 235, 235));
591 return QBrush(gradient);
599 if (qt_mac_isSystemColorOrInstance(color, @
"controlColor", @
"NSGradientPatternColor") ||
600 qt_mac_isSystemColorOrInstance(color, @
"windowBackgroundColor", @
"NSGradientPatternColor")) {
601 qtBrush.setStyle(Qt::SolidPattern);
602 qtBrush.setColor(qt_mac_toQColor(color.CGColor));
606 if (color.type == NSColorTypePattern) {
607 NSImage *patternImage = color.patternImage;
608 const QSizeF sz(patternImage.size.width, patternImage.size.height);
610 qtBrush.setTexture(qt_mac_toQPixmap(patternImage, sz));
612 qtBrush.setStyle(Qt::SolidPattern);
613 qtBrush.setColor(qt_mac_toQColor(color));
621void qt_mac_clip_cg(CGContextRef hd,
const QRegion &rgn, CGAffineTransform *orig_xform)
623 CGAffineTransform old_xform = CGAffineTransformIdentity;
625 old_xform = CGContextGetCTM(hd);
626 CGContextConcatCTM(hd, CGAffineTransformInvert(old_xform));
627 CGContextConcatCTM(hd, *orig_xform);
631 CGContextBeginPath(hd);
633 CGContextAddRect(hd, CGRectMake(0, 0, 0, 0));
635 for (
const QRect &r : rgn) {
636 CGRect mac_r = CGRectMake(r.x(), r.y(), r.width(), r.height());
637 CGContextAddRect(hd, mac_r);
643 CGContextConcatCTM(hd, CGAffineTransformInvert(CGContextGetCTM(hd)));
644 CGContextConcatCTM(hd, old_xform);
651 if (!region || !region->rectCount())
654 QVector<QRect> scaledRects;
655 scaledRects.reserve(region->rectCount());
657 for (
const QRect &rect : *region)
658 scaledRects.append(QRect(rect.topLeft() * scaleFactor, rect.size() * scaleFactor));
660 region->setRects(&scaledRects[0], scaledRects.count());
665QMacCGContext::QMacCGContext(QPaintDevice *paintDevice)
667 initialize(paintDevice);
670void QMacCGContext::initialize(QPaintDevice *paintDevice)
673 switch (
int deviceType = paintDevice->devType()) {
674 case QInternal::Pixmap: {
675 if (
auto *platformPixmap =
static_cast<QPixmap*>(paintDevice)->handle()) {
676 if (platformPixmap->classId() == QPlatformPixmap::RasterClass)
677 initialize(platformPixmap->buffer());
679 qWarning() <<
"QMacCGContext: Unsupported pixmap class" << platformPixmap->classId();
681 qWarning() <<
"QMacCGContext: Empty platformPixmap";
685 case QInternal::Image:
686 initialize(
static_cast<
const QImage *>(paintDevice));
688 case QInternal::Widget:
689 qWarning() <<
"QMacCGContext: not implemented: Widget class";
692 qWarning() <<
"QMacCGContext:: Unsupported paint device type" << deviceType;
696QMacCGContext::QMacCGContext(QPainter *painter)
698 QPaintEngine *paintEngine = painter->paintEngine();
701 while (QPaintEngine *aggregateEngine = QPaintEnginePrivate::get(paintEngine)->aggregateEngine())
702 paintEngine = aggregateEngine;
704 paintEngine->syncState();
706 if (Qt::HANDLE handle = QPaintEnginePrivate::get(paintEngine)->nativeHandle()) {
707 context =
static_cast<CGContextRef>(handle);
711 if (paintEngine->type() != QPaintEngine::Raster) {
712 qWarning() <<
"QMacCGContext:: Unsupported paint engine type" << paintEngine->type();
717 Q_ASSERT(paintEngine->paintDevice()->devType() == QInternal::Image);
720 switch (
int painterDeviceType = painter->device()->devType()) {
721 case QInternal::Pixmap:
722 case QInternal::Image:
723 case QInternal::Widget:
726 qWarning() <<
"QMacCGContext:: Unsupported paint device type" << painterDeviceType;
732 initialize(
static_cast<
const QImage *>(paintEngine->paintDevice()), painter);
735void QMacCGContext::initialize(
const QImage *image, QPainter *painter)
737 auto cgImageFormat = qt_mac_cgImageFormatForImage(*image);
738 if (!cgImageFormat) {
739 qWarning() <<
"QMacCGContext:: Could not get bitmap info for" << image;
743 context = CGBitmapContextCreate((
void *)image->bits(), image->width(), image->height(),
744 cgImageFormat->bitsPerComponent, image->bytesPerLine(), cgImageFormat->colorSpace,
745 cgImageFormat->bitmapInfo);
748 CGContextTranslateCTM(context, 0, image->height());
749 CGContextScaleCTM(context, 1, -1);
751 const qreal devicePixelRatio = image->devicePixelRatio();
753 if (painter && painter->device()->devType() == QInternal::Widget) {
755 QRegion clip = painter->paintEngine()->systemClip();
756 QTransform deviceTransform = painter->deviceTransform();
758 if (painter->hasClipping()) {
761 QRegion painterClip = painter->clipRegion();
762 qt_mac_scale_region(&painterClip, devicePixelRatio);
764 painterClip.translate(deviceTransform.dx(), deviceTransform.dy());
772 qt_mac_clip_cg(context, clip,
nullptr);
774 CGContextTranslateCTM(context, deviceTransform.dx(), deviceTransform.dy());
778 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)
QImage qt_mac_padToSquareImage(const QImage &image)