-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmac.mm
executable file
·338 lines (308 loc) · 13.9 KB
/
mac.mm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
// Copyright 2022-present Contributors to the colorpicker project.
// SPDX-License-Identifier: BSD-3-Clause
// https://github.com/mikaelsundell/colorpicker
#include "mac.h"
#import <Foundation/Foundation.h>
#import <Cocoa/Cocoa.h>
#include <QPainter>
#include <QPaintEngine>
#include <QScreen>
#include <QGuiApplication>
#include <QColorSpace>
#include <QDebug>
namespace mac
{
namespace utils
{
CGBitmapInfo toNativeFormat(const QImage &image)
{
CGBitmapInfo bitmapInfo = kCGImageAlphaNone;
switch (image.format())
{
case QImage::Format_ARGB32:
bitmapInfo = kCGImageAlphaFirst | kCGBitmapByteOrder32Host;
break;
case QImage::Format_RGB32:
bitmapInfo = kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Host;
break;
case QImage::Format_RGBA8888_Premultiplied:
bitmapInfo = kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big;
break;
case QImage::Format_RGBA8888:
bitmapInfo = kCGImageAlphaLast | kCGBitmapByteOrder32Big;
break;
case QImage::Format_RGBX8888:
bitmapInfo = kCGImageAlphaNoneSkipLast | kCGBitmapByteOrder32Big;
break;
case QImage::Format_ARGB32_Premultiplied:
bitmapInfo = kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host;
break;
default: break;
}
return bitmapInfo;
}
QImage fromNativeImage(CGImageRef cgImage)
{
QImage ig;
CGColorSpaceRef xcolorSpace = CGImageGetColorSpace(cgImage);
if (xcolorSpace) {
CFDataRef iccData = CGColorSpaceCopyICCData(xcolorSpace);
if (iccData) {
const UInt8 *bytePtr = CFDataGetBytePtr(iccData);
QByteArray iccProfile(reinterpret_cast<const char*>(bytePtr), CFDataGetLength(iccData));
CFRelease(iccData);
QColorSpace qtColorSpace = QColorSpace::fromIccProfile(iccProfile);
ig.setColorSpace(qtColorSpace);
}
}
const int width = (int)CGImageGetWidth(cgImage);
const int height = (int)CGImageGetHeight(cgImage);
QImage image(width, height, QImage::Format_ARGB32_Premultiplied);
image.fill(Qt::transparent);
// keep colorspace from incoming image ref as native values
CGColorSpaceRef colorSpace = CGImageGetColorSpace(cgImage);
CGContextRef context = CGBitmapContextCreate((void *)image.bits(), image.width(), image.height(), 8,
image.bytesPerLine(), colorSpace, toNativeFormat(image));
// scale the context so that painting happens in device-independent pixels
const qreal devicePixelRatio = image.devicePixelRatio();
CGContextScaleCTM(context, devicePixelRatio, devicePixelRatio);
CGRect rect = CGRectMake(0, 0, width, height);
CGContextDrawImage(context, rect, cgImage);
CGContextRelease(context);
return image;
}
NSWindow* toNativeWindow(WId winId)
{
NSView *view = (NSView*)winId;
return [view window];
}
NSScreen* toNativeScreen(WId winId)
{
NSWindow *window = toNativeWindow(winId);
return [window screen];
}
struct ColorSyncProfile {
uint32_t screenNumber;
CFStringRef displayProfileUrl;
ColorSyncProfile() : screenNumber(0), displayProfileUrl(nullptr) {}
ColorSyncProfile(const ColorSyncProfile& other)
: screenNumber(other.screenNumber) {
displayProfileUrl = other.displayProfileUrl ? static_cast<CFStringRef>(CFRetain(other.displayProfileUrl)) : nullptr;
}
ColorSyncProfile& operator=(const ColorSyncProfile& other) {
if (this != &other) {
screenNumber = other.screenNumber;
if (displayProfileUrl) CFRelease(displayProfileUrl);
displayProfileUrl = other.displayProfileUrl ? static_cast<CFStringRef>(CFRetain(other.displayProfileUrl)) : nullptr;
}
return *this;
}
~ColorSyncProfile() {
if (displayProfileUrl) CFRelease(displayProfileUrl);
}
};
QMap<uint32_t, ColorSyncProfile> colorsynccache;
ColorSyncProfile grabColorSyncProfile(NSScreen* screen)
{
ColorSyncProfile colorSyncProfile;
NSDictionary* screenDescription = [screen deviceDescription];
NSNumber* screenID = [screenDescription objectForKey:@"NSScreenNumber"];
colorSyncProfile.screenNumber = [screenID unsignedIntValue];
ColorSyncProfileRef csProfileRef = ColorSyncProfileCreateWithDisplayID((CGDirectDisplayID)colorSyncProfile.screenNumber);
if (csProfileRef) {
CFURLRef iccURLRef = ColorSyncProfileGetURL(csProfileRef, NULL);
if (iccURLRef) {
colorSyncProfile.displayProfileUrl = CFURLCopyFileSystemPath(iccURLRef, kCFURLPOSIXPathStyle);
}
CFRelease(csProfileRef);
}
return colorSyncProfile;
}
ColorSyncProfile grabDisplayProfile(NSScreen* screen) {
NSDictionary* screenDescription = [screen deviceDescription];
CGDirectDisplayID displayId = [[screenDescription objectForKey:@"NSScreenNumber"] unsignedIntValue];
if (colorsynccache.contains(displayId)) {
return colorsynccache.value(displayId);
}
ColorSyncProfile colorSyncProfile = grabColorSyncProfile(screen);
colorsynccache.insert(displayId, colorSyncProfile);
return colorSyncProfile;
}
}
void setDarkAppearance()
{
// we force dark aque no matter appearance set in system settings
[NSApp setAppearance:[NSAppearance appearanceNamed:NSAppearanceNameDarkAqua]];
}
void setTopLevel(WId wid)
{
NSView *view = reinterpret_cast<NSView *>(wid);
NSWindow *window = [view window];
// force window to be at status window level
[window setLevel:NSStatusWindowLevel];
}
static NSInteger cursorref = 0;
void hideCursor() {
static NSCursor* cursor = nil;
if (cursorref == 0) {
if (cursor == nil) {
NSImage *image = [[NSImage alloc] initWithSize:NSMakeSize(1, 1)];
[image lockFocus];
[[NSColor clearColor] set];
NSRectFill(NSMakeRect(0, 0, 1, 1));
[image unlockFocus];
cursor = [[NSCursor alloc] initWithImage:image hotSpot:NSMakePoint(0, 0)];
}
[cursor set];
[NSCursor hide];
}
cursorref++;
}
void showCursor() {
if (cursorref > 0) {
cursorref = 0;
[NSCursor unhide];
[[NSCursor arrowCursor] set];
}
}
QImage grabImage(int x, int y, int width, int height, WId windowId)
{
CGWindowID windowIdToExcude = 0;
if (windowId != 0) {
windowIdToExcude = (CGWindowID)[utils::toNativeWindow(windowId) windowNumber];
}
QRect grabRect = QRect(x, y, width, height);
CFArrayRef screenWindows = CGWindowListCreate(kCGWindowListOptionOnScreenOnly, kCGNullWindowID);
CFMutableArrayRef grabWindows = CFArrayCreateMutableCopy(NULL, 0, screenWindows);
if (windowIdToExcude != 0) {
for (long i = CFArrayGetCount(grabWindows) - 1; i >= 0; i--)
{
CGWindowID window = (CGWindowID)(uintptr_t)CFArrayGetValueAtIndex(grabWindows, i);
if (window == windowIdToExcude)
CFArrayRemoveValueAtIndex(grabWindows, i);
}
}
// find which displays to grab from, or all of them if the grab size is unspecified
const int maxDisplays = 128;
CGDirectDisplayID displays[maxDisplays];
CGDisplayCount displayCount;
CGRect cgRect = (width < 0 || height < 0) ? CGRectInfinite : grabRect.toCGRect();
const CGDisplayErr err = CGGetDisplaysWithRect(cgRect, maxDisplays, displays, &displayCount);
if (err || displayCount == 0)
{
CFRelease(screenWindows);
CFRelease(grabWindows);
return QImage();
}
// if the grab size is not specified, set it to be the bounding box of all screens,
if (width < 0 || height < 0) {
QRect windowRect;
for (uint i = 0; i < displayCount; ++i) {
QRect displayBounds = QRectF::fromCGRect(CGDisplayBounds(displays[i])).toRect();
// Only include the screen if it is positioned past the x/y position
if ((displayBounds.x() >= x || displayBounds.right() > x) &&
(displayBounds.y() >= y || displayBounds.bottom() > y)) {
windowRect = windowRect.united(displayBounds);
}
}
if (grabRect.width() < 0)
grabRect.setWidth(windowRect.width());
if (grabRect.height() < 0)
grabRect.setHeight(windowRect.height());
}
// grab images from each display
QVector<QImage> images;
QVector<QRect> destinations;
for (uint i = 0; i < displayCount; ++i)
{
auto display = displays[i];
QRect displayBounds = QRectF::fromCGRect(CGDisplayBounds(display)).toRect();
QRect grabBounds = displayBounds.intersected(grabRect);
if (grabBounds.isNull())
{
destinations.append(QRect());
images.append(QImage());
continue;
}
CGImageRef cgImage = CGWindowListCreateImageFromArray(grabBounds.toCGRect(), grabWindows, kCGWindowListOptionAll);
QImage displayImage = utils::fromNativeImage(cgImage);
CGImageRelease(cgImage); // Release the CGImageRef
displayImage.setDevicePixelRatio(displayImage.size().width() / grabBounds.size().width());
images.append(displayImage);
QRect destBounds = QRect(QPoint(grabBounds.topLeft() - grabRect.topLeft()), grabBounds.size());
destinations.append(destBounds);
}
// determine the highest dpr, which becomes the dpr for the returned pixmap.
qreal dpr = 1.0;
for (uint i = 0; i < displayCount; ++i)
dpr = qMax(dpr, images.at(i).devicePixelRatio());
// allocate target pixmap and draw each screen's content
QImage windowImage(grabRect.size() * dpr, QImage::Format_ARGB32_Premultiplied);
windowImage.setDevicePixelRatio(dpr);
windowImage.fill(Qt::transparent); // Ensure the image background is transparent
QPainter painter(&windowImage);
for (uint i = 0; i < displayCount; ++i) {
painter.drawImage(destinations.at(i), images.at(i));
}
painter.end(); // Ensure painting is finished properly
CFRelease(screenWindows);
CFRelease(grabWindows);
return windowImage;
}
IccProfile grabIccProfile(int x, int y)
{
QPointF cursor = toNativeCursor(x, y);
NSPoint point = NSMakePoint(cursor.x(), cursor.y());
for(NSScreen* screen in NSScreen.screens) {
if (NSMouseInRect(point, screen.frame, false)) {
utils::ColorSyncProfile colorsyncProfile = utils::grabDisplayProfile(screen);
return IccProfile {
int(colorsyncProfile.screenNumber),
QString::fromCFString(colorsyncProfile.displayProfileUrl)
};
}
}
return IccProfile();
}
IccProfile grabIccProfile(WId wid)
{
NSScreen* screen = utils::toNativeScreen(wid);
utils::ColorSyncProfile colorsyncProfile = utils::grabDisplayProfile(screen);
return IccProfile {
int(colorsyncProfile.screenNumber),
QString::fromCFString(colorsyncProfile.displayProfileUrl)
};
}
QString grabIccProfileUrl(WId wid)
{
return grabIccProfile(wid).displayProfileUrl;
}
QPoint fromNativeCursor(float x, float y) {
QPointF point(x, y);
QScreen* primaryScreen = QGuiApplication::primaryScreen();
QPointF cursor(point.x(), primaryScreen->geometry().height() - point.y());
QRect boundingRect;
for (QScreen* screen : QGuiApplication::screens()) {
boundingRect = boundingRect.united(screen->geometry());
}
// can happen over remote desktop, greater coordinates than physical dimensions
cursor.setX(qBound(static_cast<qreal>(boundingRect.left()), cursor.x(), static_cast<qreal>(boundingRect.right())));
cursor.setY(qBound(static_cast<qreal>(boundingRect.top()), cursor.y(), static_cast<qreal>(boundingRect.bottom())));
// this is worth to mention, mac uses float mouse location vs. integer in Qt,
// type conversion to closest integer will fail geometry contains() checks as
// mouse may be rounded up and fall on edge, hence treated as outside.
return QPoint(static_cast<int>(floor(cursor.x())), static_cast<int>(floor(cursor.y())));
}
QPointF toNativeCursor(int x, int y)
{
QScreen* screen = QGuiApplication::primaryScreen();
QPointF cursor = QPointF(x, y);
qreal reverse = screen->geometry().height() - cursor.y();
return QPointF(cursor.x(), reverse);
}
void console(QString message)
{
NSString *nsMessage = message.toNSString();
NSLog(@"%@", nsMessage);
}
}