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>
28std::optional<QCGImageFormat> qt_mac_cgImageFormatForImage(
const QImage &image)
30 const QPixelFormat format = image.pixelFormat();
34 if (format.colorModel() != QPixelFormat::RGB)
37 const int alphaBits = format.alphaSize();
39 CGBitmapInfo bitmapInfo = [&]{
41 return kCGImageAlphaNone;
43 if (format.channelCount() == 1)
44 return kCGImageAlphaOnly;
46 return CGImageAlphaInfo(
47 (format.alphaUsage() == QPixelFormat::IgnoresAlpha ?
48 kCGImageAlphaNoneSkipLast
49 : (format.premultiplied() == QPixelFormat::Premultiplied ?
50 kCGImageAlphaPremultipliedLast : kCGImageAlphaLast)
52 + (format.alphaPosition() == QPixelFormat::AtBeginning ? 1 : 0)
56 const std::tuple rgbBits{format.redSize(), format.greenSize(), format.blueSize() };
58 const CGImageByteOrderInfo byteOrder16Bit =
59 format.byteOrder() == QPixelFormat::LittleEndian ?
60 kCGImageByteOrder16Little : kCGImageByteOrder16Big;
62 const CGImageByteOrderInfo byteOrder32Bit =
63 format.byteOrder() == QPixelFormat::LittleEndian ?
64 kCGImageByteOrder32Little : kCGImageByteOrder32Big;
66 static const auto isPacked = [](
const QPixelFormat f) {
67 return f.redSize() == f.greenSize()
68 && f.greenSize() == f.blueSize()
69 && (!f.alphaSize() || f.alphaSize() == f.blueSize());
72 switch (format.typeInterpretation()) {
73 case QPixelFormat::UnsignedByte:
77 if (format.bitsPerPixel() == 32)
78 bitmapInfo |= kCGImageByteOrder32Big;
79 else if (format.bitsPerPixel() == 16)
80 bitmapInfo |= kCGImageByteOrder16Big;
82 bitmapInfo |= kCGImageByteOrderDefault;
84 case QPixelFormat::UnsignedShort:
85 bitmapInfo |= byteOrder16Bit;
87 bitmapInfo |= kCGImagePixelFormatPacked;
88 else if (rgbBits == std::tuple{5,5,5} && alphaBits == 1)
89 bitmapInfo |= kCGImagePixelFormatRGB555;
90 else if (rgbBits == std::tuple{5,6,5} && !alphaBits)
91 bitmapInfo |= kCGImagePixelFormatRGB565;
95 case QPixelFormat::UnsignedInteger:
96 bitmapInfo |= byteOrder32Bit;
98 bitmapInfo |= kCGImagePixelFormatPacked;
99 else if (rgbBits == std::tuple{10,10,10} && alphaBits == 2)
100 bitmapInfo |= kCGImagePixelFormatRGB101010;
104 case QPixelFormat::FloatingPoint:
105 bitmapInfo |= kCGBitmapFloatComponents;
106 if (!isPacked(format))
108 if (format.bitsPerPixel() == 128)
109 bitmapInfo |= byteOrder32Bit;
110 else if (format.bitsPerPixel() == 64)
111 bitmapInfo |= byteOrder16Bit;
119 const uint32_t bitsPerComponent = std::min({
120 format.redSize(), format.greenSize(), format.blueSize()
123 QCFType<CGColorSpaceRef> colorSpace = [&]{
124 if (
const auto colorSpace = image.colorSpace(); colorSpace.isValid()) {
125 QCFType<CFDataRef> iccData = colorSpace.iccProfile().toCFData();
126 return CGColorSpaceCreateWithICCData(iccData);
128 return CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
132 return QCGImageFormat{
133 bitsPerComponent, format.bitsPerPixel(),
134 colorSpace, bitmapInfo
140 CGImageRef cgImage = inImage.toCGImage();
145 return inImage.convertToFormat(QImage::Format_ARGB32_Premultiplied).toCGImage();
150 CGContextSaveGState( inContext );
151 CGContextTranslateCTM (inContext, 0, inBounds->origin.y + CGRectGetMaxY(*inBounds));
152 CGContextScaleCTM(inContext, 1, -1);
154 CGContextDrawImage(inContext, *inBounds, inImage);
156 CGContextRestoreGState(inContext);
162 return QImage::Format_Invalid;
164 const CGColorSpaceRef colorSpace = CGImageGetColorSpace(image);
165 if (CGColorSpaceGetModel(colorSpace) != kCGColorSpaceModelRGB)
166 return QImage::Format_Invalid;
168 const CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(image);
169 const auto byteOrder = CGImageByteOrderInfo(bitmapInfo & kCGBitmapByteOrderMask);
171 auto qtByteOrder = [&]() -> std::optional<QPixelFormat::ByteOrder> {
173 case kCGImageByteOrder16Big:
174 case kCGImageByteOrder32Big:
175 case kCGImageByteOrderDefault:
176 return QPixelFormat::BigEndian;
177 case kCGImageByteOrder16Little:
178 case kCGImageByteOrder32Little:
179 return QPixelFormat::LittleEndian;
185 return QImage::Format_Invalid;
187 auto typeInterpretation = [&]() -> std::optional<QPixelFormat::TypeInterpretation> {
188 if (bitmapInfo & kCGBitmapFloatComponents)
189 return QPixelFormat::FloatingPoint;
190 else if (qtByteOrder == QPixelFormat::BigEndian)
193 return QPixelFormat::UnsignedByte;
194 else if (byteOrder == kCGImageByteOrder16Little)
195 return QPixelFormat::UnsignedShort;
196 else if (byteOrder == kCGImageByteOrder32Little)
197 return QPixelFormat::UnsignedInteger;
201 if (!typeInterpretation)
202 return QImage::Format_Invalid;
204 const auto alphaInfo = CGImageAlphaInfo(bitmapInfo & kCGBitmapAlphaInfoMask);
206 QPixelFormat::AlphaPosition alphaPosition = [&]{
208 case kCGImageAlphaNone:
209 case kCGImageAlphaFirst:
210 case kCGImageAlphaNoneSkipFirst:
211 case kCGImageAlphaPremultipliedFirst:
212 return QPixelFormat::AtBeginning;
214 return QPixelFormat::AtEnd;
218 QPixelFormat::AlphaUsage alphaUsage = [&]{
220 case kCGImageAlphaNone:
221 case kCGImageAlphaNoneSkipLast:
222 case kCGImageAlphaNoneSkipFirst:
223 return QPixelFormat::IgnoresAlpha;
225 return QPixelFormat::UsesAlpha;
229 QPixelFormat::AlphaPremultiplied alphaPremultiplied = [&]{
231 case kCGImageAlphaPremultipliedFirst:
232 case kCGImageAlphaPremultipliedLast:
233 return QPixelFormat::Premultiplied;
235 return QPixelFormat::NotPremultiplied;
239 auto [redSize, greenSize, blueSize, alphaSize] = [&]() -> std::tuple<uchar,uchar,uchar,uchar> {
240 const auto pixelFormat = CGImagePixelFormatInfo(bitmapInfo & kCGImagePixelFormatMask);
241 const size_t bpc = CGImageGetBitsPerComponent(image);
242 if (pixelFormat == kCGImagePixelFormatPacked)
243 return {bpc, bpc, bpc, alphaInfo != kCGImageAlphaNone ? bpc : 0};
244 else if (pixelFormat == kCGImagePixelFormatRGB555)
246 else if (pixelFormat == kCGImagePixelFormatRGB565)
248 else if (pixelFormat == kCGImagePixelFormatRGB101010)
249 return {10, 10, 10, 2};
254 QPixelFormat pixelFormat(QPixelFormat::RGB, redSize, greenSize, blueSize, 0, 0,
255 alphaSize, alphaUsage, alphaPosition, alphaPremultiplied,
256 *typeInterpretation, *qtByteOrder);
258 return QImage::toImageFormat(pixelFormat);
263 const size_t width = CGImageGetWidth(cgImage);
264 const size_t height = CGImageGetHeight(cgImage);
266 QImage image = [&]() -> QImage {
267 QImage::Format imageFormat = qt_mac_imageFormatForCGImage(cgImage);
268 if (imageFormat == QImage::Format_Invalid)
271 CGDataProviderRef dataProvider = CGImageGetDataProvider(cgImage);
276 CFDataRef data = CGDataProviderCopyData(dataProvider);
281 return QImage(CFDataGetBytePtr(data), width, height,
282 CGImageGetBytesPerRow(cgImage), imageFormat,
283 QImageCleanupFunction(CFRelease), (
void*)data);
286 if (image.isNull()) {
288 image = QImage(width, height, QImage::Format_ARGB32_Premultiplied);
289 image.fill(Qt::transparent);
291 CGRect rect = CGRectMake(0, 0, width, height);
292 qt_mac_drawCGImage(context, &rect, cgImage);
295 if (!image.isNull()) {
296 CGColorSpaceRef colorSpace = CGImageGetColorSpace(cgImage);
297 QCFType<CFDataRef> iccData = CGColorSpaceCopyICCData(colorSpace);
298 image.setColorSpace(QColorSpace::fromIccProfile(QByteArray::fromCFData(iccData)));
306 if (image.width() == image.height())
309 const int size = std::max(image.width(), image.height());
310 QImage squareImage(size, size, image.format());
311 squareImage.setDevicePixelRatio(image.devicePixelRatio());
312 squareImage.fill(Qt::transparent);
314 QPoint pos((size - image.width()) / (2.0 * image.devicePixelRatio()),
315 (size - image.height()) / (2.0 * image.devicePixelRatio()));
317 QPainter painter(&squareImage);
318 painter.drawImage(pos, image);
328@implementation NSImage (QtExtras)
329+ (instancetype)imageFromQImage:(
const QImage &)image
334 QCFType<CGImageRef> cgImage = image.toCGImage();
343 auto nsImage = [[NSImage alloc] initWithSize:NSZeroSize];
344 auto *imageRep = [[NSBitmapImageRep alloc] initWithCGImage:cgImage];
345 imageRep.size = image.deviceIndependentSize().toCGSize();
346 [nsImage addRepresentation:[imageRep autorelease]];
347 Q_ASSERT(CGSizeEqualToSize(nsImage.size, imageRep.size));
349 return [nsImage autorelease];
352+ (instancetype)imageFromQIcon:(
const QIcon &)icon
354 return [NSImage imageFromQIcon:icon withSize:QSize()];
357+ (instancetype)imageFromQIcon:(
const QIcon &)icon withSize:(
const QSize &)size
359 return [NSImage imageFromQIcon:icon withSize:size withMode:QIcon::Normal withState:QIcon::Off];
362+ (instancetype)imageFromQIcon:(
const QIcon &)icon withSize:(
const QSize &)size
363 withMode:(QIcon::Mode)mode withState:(QIcon::State)state
369 auto availableSizes = icon.availableSizes();
370 if (availableSizes.isEmpty() && !size.isNull())
371 availableSizes << size;
373 auto nsImage = [[[NSImage alloc] initWithSize:NSZeroSize] autorelease];
375 for (QSize size : std::as_const(availableSizes)) {
376 const QImage image = icon.pixmap(size, mode, state).toImage();
380 QCFType<CGImageRef> cgImage = image.toCGImage();
384 auto *imageRep = [[NSBitmapImageRep alloc] initWithCGImage:cgImage];
385 imageRep.size = image.deviceIndependentSize().toCGSize();
386 [nsImage addRepresentation:[imageRep autorelease]];
389 nsImage.size = imageRep.size;
392 if (!nsImage.representations.count)
395 [nsImage setTemplate:icon.isMask()];
397 if (!size.isNull()) {
398 auto imageSize = QSizeF::fromCGSize(nsImage.size);
399 nsImage.size = imageSize.scaled(size, Qt::KeepAspectRatio).toCGSize();
405+ (instancetype)internalImageFromQIcon:(
const QT_PREPEND_NAMESPACE(QIcon) &)icon
411 auto *iconPrivate = QIconPrivate::get(&icon);
412 NSImage *iconImage =
nullptr;
413 iconPrivate->engine->virtual_hook(QIconPrivate::PlatformIconHook, &iconImage);
421QPixmap qt_mac_toQPixmap(
const NSImage *image,
const QSizeF &size)
426 const NSSize pixmapSize = NSMakeSize(size.width(), size.height());
427 QPixmap pixmap(pixmapSize.width, pixmapSize.height);
428 pixmap.fill(Qt::transparent);
429 [image setSize:pixmapSize];
430 const NSRect iconRect = NSMakeRect(0, 0, pixmapSize.width, pixmapSize.height);
431 QMacCGContext ctx(&pixmap);
434 NSGraphicsContext *gc = [NSGraphicsContext graphicsContextWithCGContext:ctx flipped:YES];
437 [NSGraphicsContext saveGraphicsState];
438 [NSGraphicsContext setCurrentContext:gc];
439 [image drawInRect:iconRect fromRect:iconRect operation:NSCompositingOperationSourceOver fraction:1.0 respectFlipped:YES hints:nil];
440 [NSGraphicsContext restoreGraphicsState];
446#ifdef QT_PLATFORM_UIKIT
448QImage qt_mac_toQImage(
const UIImage *image, QSizeF size)
451 QImage ret(size.width(), size.height(), QImage::Format_ARGB32_Premultiplied);
452 ret.fill(Qt::transparent);
453 QMacCGContext ctx(&ret);
456 UIGraphicsPushContext(ctx);
457 const CGRect rect = CGRectMake(0, 0, size.width(), size.height());
458 [image drawInRect:rect];
459 UIGraphicsPopContext();
470 CGColorSpaceModel model = CGColorSpaceGetModel(CGColorGetColorSpace(color));
471 const CGFloat *components = CGColorGetComponents(color);
472 if (model == kCGColorSpaceModelRGB) {
473 qtColor.setRgbF(components[0], components[1], components[2], components[3]);
474 }
else if (model == kCGColorSpaceModelCMYK) {
475 qtColor.setCmykF(components[0], components[1], components[2], components[3]);
476 }
else if (model == kCGColorSpaceModelMonochrome) {
477 qtColor.setRgbF(components[0], components[0], components[0], components[1]);
480 qWarning(
"Qt: qt_mac_toQColor: cannot convert from colorspace model: %d", model);
487QColor qt_mac_toQColor(
const NSColor *color)
493 switch (color.type) {
494 case NSColorTypeComponentBased: {
495 const NSColorSpace *colorSpace = [color colorSpace];
496 if (colorSpace == NSColorSpace.genericRGBColorSpace
497 && color.numberOfComponents == 4) {
498 CGFloat components[4];
499 [color getComponents:components];
500 qtColor.setRgbF(components[0], components[1], components[2], components[3]);
502 }
else if (colorSpace == NSColorSpace.genericCMYKColorSpace
503 && color.numberOfComponents == 5) {
504 CGFloat components[5];
505 [color getComponents:components];
506 qtColor.setCmykF(components[0], components[1], components[2], components[3], components[4]);
512 const NSColor *tmpColor = [color colorUsingColorSpace:NSColorSpace.genericRGBColorSpace];
513 CGFloat red = 0, green = 0, blue = 0, alpha = 0;
514 [tmpColor getRed:&red green:&green blue:&blue alpha:&alpha];
515 qtColor.setRgbF(red, green, blue, alpha);
527 CGColorSpaceModel model = CGColorSpaceGetModel(CGColorGetColorSpace(color));
528 if (model == kCGColorSpaceModelPattern) {
530 qWarning(
"Qt: qt_mac_toQBrush: cannot convert from colorspace model: %d", model);
533 qtBrush.setStyle(Qt::SolidPattern);
534 qtBrush.setColor(qt_mac_toQColor(color));
540static bool qt_mac_isSystemColorOrInstance(
const NSColor *color, NSString *colorNameComponent, NSString *className)
543 if ([color.className isEqualToString:className])
545 if (color.type == NSColorTypeCatalog &&
546 [color.catalogNameComponent isEqualToString:@
"System"] &&
547 [color.colorNameComponent isEqualToString:colorNameComponent])
552QBrush qt_mac_toQBrush(
const NSColor *color, QPalette::ColorGroup colorGroup)
557 if ([color.className isEqualToString:@
"NSMenuItemHighlightColor"]) {
558 qWarning(
"Qt: qt_mac_toQBrush: cannot convert from NSMenuItemHighlightColor");
564 if ([color.className isEqualToString:@
"NSMetalPatternColor"]) {
570 qWarning(
"Qt: qt_mac_toQBrush: cannot convert from NSMetalPatternColor");
577 if (qt_mac_isSystemColorOrInstance(color, @
"_sourceListBackgroundColor", @
"NSSourceListBackgroundColor")) {
578 QLinearGradient gradient;
579 if (colorGroup == QPalette::Active) {
580 gradient.setColorAt(0, QColor(233, 237, 242));
581 gradient.setColorAt(0.5, QColor(225, 229, 235));
582 gradient.setColorAt(1, QColor(209, 216, 224));
584 gradient.setColorAt(0, QColor(248, 248, 248));
585 gradient.setColorAt(0.5, QColor(240, 240, 240));
586 gradient.setColorAt(1, QColor(235, 235, 235));
588 return QBrush(gradient);
596 if (qt_mac_isSystemColorOrInstance(color, @
"controlColor", @
"NSGradientPatternColor") ||
597 qt_mac_isSystemColorOrInstance(color, @
"windowBackgroundColor", @
"NSGradientPatternColor")) {
598 qtBrush.setStyle(Qt::SolidPattern);
599 qtBrush.setColor(qt_mac_toQColor(color.CGColor));
603 if (color.type == NSColorTypePattern) {
604 NSImage *patternImage = color.patternImage;
605 const QSizeF sz(patternImage.size.width, patternImage.size.height);
607 qtBrush.setTexture(qt_mac_toQPixmap(patternImage, sz));
609 qtBrush.setStyle(Qt::SolidPattern);
610 qtBrush.setColor(qt_mac_toQColor(color));
618void qt_mac_clip_cg(CGContextRef hd,
const QRegion &rgn, CGAffineTransform *orig_xform)
620 CGAffineTransform old_xform = CGAffineTransformIdentity;
622 old_xform = CGContextGetCTM(hd);
623 CGContextConcatCTM(hd, CGAffineTransformInvert(old_xform));
624 CGContextConcatCTM(hd, *orig_xform);
628 CGContextBeginPath(hd);
630 CGContextAddRect(hd, CGRectMake(0, 0, 0, 0));
632 for (
const QRect &r : rgn) {
633 CGRect mac_r = CGRectMake(r.x(), r.y(), r.width(), r.height());
634 CGContextAddRect(hd, mac_r);
640 CGContextConcatCTM(hd, CGAffineTransformInvert(CGContextGetCTM(hd)));
641 CGContextConcatCTM(hd, old_xform);
648 if (!region || !region->rectCount())
651 QVector<QRect> scaledRects;
652 scaledRects.reserve(region->rectCount());
654 for (
const QRect &rect : *region)
655 scaledRects.append(QRect(rect.topLeft() * scaleFactor, rect.size() * scaleFactor));
657 region->setRects(&scaledRects[0], scaledRects.count());
662QMacCGContext::QMacCGContext(QPaintDevice *paintDevice)
664 initialize(paintDevice);
667void QMacCGContext::initialize(QPaintDevice *paintDevice)
670 switch (
int deviceType = paintDevice->devType()) {
671 case QInternal::Pixmap: {
672 if (
auto *platformPixmap =
static_cast<QPixmap*>(paintDevice)->handle()) {
673 if (platformPixmap->classId() == QPlatformPixmap::RasterClass)
674 initialize(platformPixmap->buffer());
676 qWarning() <<
"QMacCGContext: Unsupported pixmap class" << platformPixmap->classId();
678 qWarning() <<
"QMacCGContext: Empty platformPixmap";
682 case QInternal::Image:
683 initialize(
static_cast<
const QImage *>(paintDevice));
685 case QInternal::Widget:
686 qWarning() <<
"QMacCGContext: not implemented: Widget class";
689 qWarning() <<
"QMacCGContext:: Unsupported paint device type" << deviceType;
693QMacCGContext::QMacCGContext(QPainter *painter)
695 QPaintEngine *paintEngine = painter->paintEngine();
698 while (QPaintEngine *aggregateEngine = QPaintEnginePrivate::get(paintEngine)->aggregateEngine())
699 paintEngine = aggregateEngine;
701 paintEngine->syncState();
703 if (Qt::HANDLE handle = QPaintEnginePrivate::get(paintEngine)->nativeHandle()) {
704 context =
static_cast<CGContextRef>(handle);
708 if (paintEngine->type() != QPaintEngine::Raster) {
709 qWarning() <<
"QMacCGContext:: Unsupported paint engine type" << paintEngine->type();
714 Q_ASSERT(paintEngine->paintDevice()->devType() == QInternal::Image);
717 switch (
int painterDeviceType = painter->device()->devType()) {
718 case QInternal::Pixmap:
719 case QInternal::Image:
720 case QInternal::Widget:
723 qWarning() <<
"QMacCGContext:: Unsupported paint device type" << painterDeviceType;
729 initialize(
static_cast<
const QImage *>(paintEngine->paintDevice()), painter);
732void QMacCGContext::initialize(
const QImage *image, QPainter *painter)
734 auto cgImageFormat = qt_mac_cgImageFormatForImage(*image);
735 if (!cgImageFormat) {
736 qWarning() <<
"QMacCGContext:: Could not get bitmap info for" << image;
740 context = CGBitmapContextCreate((
void *)image->bits(), image->width(), image->height(),
741 cgImageFormat->bitsPerComponent, image->bytesPerLine(), cgImageFormat->colorSpace,
742 cgImageFormat->bitmapInfo);
745 CGContextTranslateCTM(context, 0, image->height());
746 CGContextScaleCTM(context, 1, -1);
748 const qreal devicePixelRatio = image->devicePixelRatio();
750 if (painter && painter->device()->devType() == QInternal::Widget) {
752 QRegion clip = painter->paintEngine()->systemClip();
753 QTransform deviceTransform = painter->deviceTransform();
755 if (painter->hasClipping()) {
758 QRegion painterClip = painter->clipRegion();
759 qt_mac_scale_region(&painterClip, devicePixelRatio);
761 painterClip.translate(deviceTransform.dx(), deviceTransform.dy());
769 qt_mac_clip_cg(context, clip,
nullptr);
771 CGContextTranslateCTM(context, deviceTransform.dx(), deviceTransform.dy());
775 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)