Debian Codegraph @

darwin.go

raw
1 //go:build cgo && darwin
2
3 package screenshot
4
5 /*
6 #if __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ > MAC_OS_VERSION_14_4
7 #cgo CFLAGS: -x objective-c
8 #cgo LDFLAGS: -framework CoreGraphics -framework CoreFoundation -framework ScreenCaptureKit
9 #include <ScreenCaptureKit/ScreenCaptureKit.h>
10 #else
11 #cgo LDFLAGS: -framework CoreGraphics -framework CoreFoundation
12 #endif
13 #include <CoreGraphics/CoreGraphics.h>
14
15 static CGImageRef capture(CGDirectDisplayID id, CGRect diIntersectDisplayLocal, CGColorSpaceRef colorSpace) {
16 #if __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ > MAC_OS_VERSION_14_4
17 dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
18 __block CGImageRef result = nil;
19 [SCShareableContent getShareableContentWithCompletionHandler:^(SCShareableContent* content, NSError* error) {
20 @autoreleasepool {
21 if (error) {
22 dispatch_semaphore_signal(semaphore);
23 return;
24 }
25 SCDisplay* target = nil;
26 for (SCDisplay *display in content.displays) {
27 if (display.displayID == id) {
28 target = display;
29 break;
30 }
31 }
32 if (!target) {
33 dispatch_semaphore_signal(semaphore);
34 return;
35 }
36 SCContentFilter* filter = [[SCContentFilter alloc] initWithDisplay:target excludingWindows:@[]];
37 SCStreamConfiguration* config = [[SCStreamConfiguration alloc] init];
38 config.sourceRect = diIntersectDisplayLocal;
39 config.width = diIntersectDisplayLocal.size.width;
40 config.height = diIntersectDisplayLocal.size.height;
41 config.showsCursor = NO;
42 [SCScreenshotManager captureImageWithFilter:filter
43 configuration:config
44 completionHandler:^(CGImageRef img, NSError* error) {
45 if (!error) {
46 result = CGImageCreateCopyWithColorSpace(img, colorSpace);
47 }
48 dispatch_semaphore_signal(semaphore);
49 }];
50 }
51 }];
52 dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
53 dispatch_release(semaphore);
54 return result;
55 #else
56 CGImageRef img = CGDisplayCreateImageForRect(id, diIntersectDisplayLocal);
57 if (!img) {
58 return nil;
59 }
60 CGImageRef copy = CGImageCreateCopyWithColorSpace(img, colorSpace);
61 CGImageRelease(img);
62 if (!copy) {
63 return nil;
64 }
65 return copy;
66 #endif
67 }
68 */
69 import "C"
70
71 import (
72 "errors"
73 "image"
74 "unsafe"
75 )
76
77 func Capture(x, y, width, height int) (*image.RGBA, error) {
78 if width <= 0 || height <= 0 {
79 return nil, errors.New("width or height should be > 0")
80 }
81
82 rect := image.Rect(0, 0, width, height)
83 img, err := createImage(rect)
84 if err != nil {
85 return nil, err
86 }
87
88 // cg: CoreGraphics coordinate (origin: lower-left corner of primary display, x-axis: rightward, y-axis: upward)
89 // win: Windows coordinate (origin: upper-left corner of primary display, x-axis: rightward, y-axis: downward)
90 // di: Display local coordinate (origin: upper-left corner of the display, x-axis: rightward, y-axis: downward)
91
92 cgMainDisplayBounds := getCoreGraphicsCoordinateOfDisplay(C.CGMainDisplayID())
93
94 winBottomLeft := C.CGPointMake(C.CGFloat(x), C.CGFloat(y+height))
95 cgBottomLeft := getCoreGraphicsCoordinateFromWindowsCoordinate(winBottomLeft, cgMainDisplayBounds)
96 cgCaptureBounds := C.CGRectMake(cgBottomLeft.x, cgBottomLeft.y, C.CGFloat(width), C.CGFloat(height))
97
98 ids := activeDisplayList()
99
100 ctx := createBitmapContext(width, height, (*C.uint32_t)(unsafe.Pointer(&img.Pix[0])), img.Stride)
101 if ctx == 0 {
102 return nil, errors.New("cannot create bitmap context")
103 }
104
105 colorSpace := createColorspace()
106 if colorSpace == 0 {
107 return nil, errors.New("cannot create colorspace")
108 }
109 defer C.CGColorSpaceRelease(colorSpace)
110
111 for _, id := range ids {
112 cgBounds := getCoreGraphicsCoordinateOfDisplay(id)
113 cgIntersect := C.CGRectIntersection(cgBounds, cgCaptureBounds)
114 if C.CGRectIsNull(cgIntersect) {
115 continue
116 }
117 if cgIntersect.size.width <= 0 || cgIntersect.size.height <= 0 {
118 continue
119 }
120
121 // CGDisplayCreateImageForRect potentially fail in case width/height is odd number.
122 if int(cgIntersect.size.width)%2 != 0 {
123 cgIntersect.size.width = C.CGFloat(int(cgIntersect.size.width) + 1)
124 }
125 if int(cgIntersect.size.height)%2 != 0 {
126 cgIntersect.size.height = C.CGFloat(int(cgIntersect.size.height) + 1)
127 }
128
129 diIntersectDisplayLocal := C.CGRectMake(cgIntersect.origin.x-cgBounds.origin.x,
130 cgBounds.origin.y+cgBounds.size.height-(cgIntersect.origin.y+cgIntersect.size.height),
131 cgIntersect.size.width, cgIntersect.size.height)
132
133 image := C.capture(id, diIntersectDisplayLocal, colorSpace)
134 if unsafe.Pointer(image) == nil {
135 return nil, errors.New("cannot capture display")
136 }
137 defer C.CGImageRelease(image)
138
139 cgDrawRect := C.CGRectMake(cgIntersect.origin.x-cgCaptureBounds.origin.x, cgIntersect.origin.y-cgCaptureBounds.origin.y,
140 cgIntersect.size.width, cgIntersect.size.height)
141 C.CGContextDrawImage(ctx, cgDrawRect, image)
142 }
143
144 i := 0
145 for iy := 0; iy < height; iy++ {
146 j := i
147 for ix := 0; ix < width; ix++ {
148 // ARGB => RGBA, and set A to 255
149 img.Pix[j], img.Pix[j+1], img.Pix[j+2], img.Pix[j+3] = img.Pix[j+1], img.Pix[j+2], img.Pix[j+3], 255
150 j += 4
151 }
152 i += img.Stride
153 }
154
155 return img, nil
156 }
157
158 func NumActiveDisplays() int {
159 var count C.uint32_t = 0
160 if C.CGGetActiveDisplayList(0, nil, &count) == C.kCGErrorSuccess {
161 return int(count)
162 } else {
163 return 0
164 }
165 }
166
167 func GetDisplayBounds(displayIndex int) image.Rectangle {
168 id := getDisplayId(displayIndex)
169 main := C.CGMainDisplayID()
170
171 var rect image.Rectangle
172
173 bounds := getCoreGraphicsCoordinateOfDisplay(id)
174 rect.Min.X = int(bounds.origin.x)
175 if main == id {
176 rect.Min.Y = 0
177 } else {
178 mainBounds := getCoreGraphicsCoordinateOfDisplay(main)
179 mainHeight := mainBounds.size.height
180 rect.Min.Y = int(mainHeight - (bounds.origin.y + bounds.size.height))
181 }
182 rect.Max.X = rect.Min.X + int(bounds.size.width)
183 rect.Max.Y = rect.Min.Y + int(bounds.size.height)
184
185 return rect
186 }
187
188 func getDisplayId(displayIndex int) C.CGDirectDisplayID {
189 main := C.CGMainDisplayID()
190 if displayIndex == 0 {
191 return main
192 } else {
193 n := NumActiveDisplays()
194 ids := make([]C.CGDirectDisplayID, n)
195 if C.CGGetActiveDisplayList(C.uint32_t(n), (*C.CGDirectDisplayID)(unsafe.Pointer(&ids[0])), nil) != C.kCGErrorSuccess {
196 return 0
197 }
198 index := 0
199 for i := 0; i < n; i++ {
200 if ids[i] == main {
201 continue
202 }
203 index++
204 if index == displayIndex {
205 return ids[i]
206 }
207 }
208 }
209
210 return 0
211 }
212
213 func getCoreGraphicsCoordinateOfDisplay(id C.CGDirectDisplayID) C.CGRect {
214 main := C.CGDisplayBounds(C.CGMainDisplayID())
215 r := C.CGDisplayBounds(id)
216 return C.CGRectMake(r.origin.x, -r.origin.y-r.size.height+main.size.height,
217 r.size.width, r.size.height)
218 }
219
220 func getCoreGraphicsCoordinateFromWindowsCoordinate(p C.CGPoint, mainDisplayBounds C.CGRect) C.CGPoint {
221 return C.CGPointMake(p.x, mainDisplayBounds.size.height-p.y)
222 }
223
224 func createBitmapContext(width int, height int, data *C.uint32_t, bytesPerRow int) C.CGContextRef {
225 colorSpace := createColorspace()
226 if colorSpace == 0 {
227 return 0
228 }
229 defer C.CGColorSpaceRelease(colorSpace)
230
231 return C.CGBitmapContextCreate(unsafe.Pointer(data),
232 C.size_t(width),
233 C.size_t(height),
234 8, // bits per component
235 C.size_t(bytesPerRow),
236 colorSpace,
237 C.kCGImageAlphaNoneSkipFirst)
238 }
239
240 func createColorspace() C.CGColorSpaceRef {
241 return C.CGColorSpaceCreateWithName(C.kCGColorSpaceSRGB)
242 }
243
244 func activeDisplayList() []C.CGDirectDisplayID {
245 count := C.uint32_t(NumActiveDisplays())
246 ret := make([]C.CGDirectDisplayID, count)
247 if count > 0 && C.CGGetActiveDisplayList(count, (*C.CGDirectDisplayID)(unsafe.Pointer(&ret[0])), nil) == C.kCGErrorSuccess {
248 return ret
249 } else {
250 return make([]C.CGDirectDisplayID, 0)
251 }
252 }