forked from BoboTiG/python-mss
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdarwin.py
More file actions
246 lines (199 loc) · 7.62 KB
/
Copy pathdarwin.py
File metadata and controls
246 lines (199 loc) · 7.62 KB
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
"""
This is part of the MSS Python's module.
Source: https://github.com/BoboTiG/python-mss
"""
import ctypes
import ctypes.util
import sys
from ctypes import (
POINTER,
Structure,
c_double,
c_float,
c_int32,
c_uint64,
c_ubyte,
c_uint32,
c_void_p,
)
from platform import mac_ver
from typing import TYPE_CHECKING
from .base import MSSBase
from .exception import ScreenShotError
from .screenshot import Size
if TYPE_CHECKING:
from typing import Any, List, Type, Union # noqa
from .models import Monitor, Monitors # noqa
from .screenshot import ScreenShot # noqa
__all__ = ("MSS",)
def cgfloat():
# type: () -> Union[Type[c_double], Type[c_float]]
""" Get the appropriate value for a float. """
return c_double if sys.maxsize > 2 ** 32 else c_float
class CGPoint(Structure):
""" Structure that contains coordinates of a rectangle. """
_fields_ = [("x", cgfloat()), ("y", cgfloat())]
def __repr__(self):
return "{}(left={} top={})".format(type(self).__name__, self.x, self.y)
class CGSize(Structure):
""" Structure that contains dimensions of an rectangle. """
_fields_ = [("width", cgfloat()), ("height", cgfloat())]
def __repr__(self):
return "{}(width={} height={})".format(
type(self).__name__, self.width, self.height
)
class CGRect(Structure):
""" Structure that contains information about a rectangle. """
_fields_ = [("origin", CGPoint), ("size", CGSize)]
def __repr__(self):
return "{}<{} {}>".format(type(self).__name__, self.origin, self.size)
# C functions that will be initialised later.
#
# This is a dict:
# cfunction: (attr, argtypes, restype)
#
# Available attr: core.
#
# Note: keep it sorted by cfunction.
CFUNCTIONS = {
"CGDataProviderCopyData": ("core", [c_void_p], c_void_p),
"CGDisplayBounds": ("core", [c_uint32], CGRect),
"CGDisplayRotation": ("core", [c_uint32], c_float),
"CFDataGetBytePtr": ("core", [c_void_p], c_void_p),
"CFDataGetLength": ("core", [c_void_p], c_uint64),
"CFRelease": ("core", [c_void_p], c_void_p),
"CGDataProviderRelease": ("core", [c_void_p], c_void_p),
"CGGetActiveDisplayList": (
"core",
[c_uint32, POINTER(c_uint32), POINTER(c_uint32)],
c_int32,
),
"CGImageGetBitsPerPixel": ("core", [c_void_p], int),
"CGImageGetBytesPerRow": ("core", [c_void_p], int),
"CGImageGetDataProvider": ("core", [c_void_p], c_void_p),
"CGImageGetHeight": ("core", [c_void_p], int),
"CGImageGetWidth": ("core", [c_void_p], int),
"CGRectStandardize": ("core", [CGRect], CGRect),
"CGRectUnion": ("core", [CGRect, CGRect], CGRect),
"CGWindowListCreateImage": (
"core",
[CGRect, c_uint32, c_uint32, c_uint32],
c_void_p,
),
}
class MSS(MSSBase):
"""
Multiple ScreenShots implementation for macOS.
It uses intensively the CoreGraphics library.
"""
__slots__ = {"core", "max_displays"}
def __init__(self, **_):
""" macOS initialisations. """
super().__init__()
self.max_displays = 32
self._init_library()
self._set_cfunctions()
def _init_library(self):
""" Load the CoreGraphics library. """
version = float(".".join(mac_ver()[0].split(".")[:2]))
if version < 10.16:
coregraphics = ctypes.util.find_library("CoreGraphics")
else:
# macOS Big Sur and newer
# pylint: disable=line-too-long
coregraphics = "/System/Library/Frameworks/CoreGraphics.framework/Versions/Current/CoreGraphics"
if not coregraphics:
raise ScreenShotError("No CoreGraphics library found.")
self.core = ctypes.cdll.LoadLibrary(coregraphics)
def _set_cfunctions(self):
# type: () -> None
""" Set all ctypes functions and attach them to attributes. """
cfactory = self._cfactory
attrs = {"core": self.core}
for func, (attr, argtypes, restype) in CFUNCTIONS.items():
cfactory(
attr=attrs[attr],
func=func,
argtypes=argtypes, # type: ignore
restype=restype,
)
def _monitors_impl(self):
# type: () -> None
""" Get positions of monitors. It will populate self._monitors. """
int_ = int
core = self.core
# All monitors
# We need to update the value with every single monitor found
# using CGRectUnion. Else we will end with infinite values.
all_monitors = CGRect()
self._monitors.append({})
# Each monitors
display_count = c_uint32(0)
active_displays = (c_uint32 * self.max_displays)()
core.CGGetActiveDisplayList(
self.max_displays, active_displays, ctypes.byref(display_count)
)
rotations = {0.0: "normal", 90.0: "right", -90.0: "left"}
for idx in range(display_count.value):
display = active_displays[idx]
rect = core.CGDisplayBounds(display)
rect = core.CGRectStandardize(rect)
width, height = rect.size.width, rect.size.height
rot = core.CGDisplayRotation(display)
if rotations[rot] in ["left", "right"]:
width, height = height, width
self._monitors.append(
{
"left": int_(rect.origin.x),
"top": int_(rect.origin.y),
"width": int_(width),
"height": int_(height),
}
)
# Update AiO monitor's values
all_monitors = core.CGRectUnion(all_monitors, rect)
# Set the AiO monitor's values
self._monitors[0] = {
"left": int_(all_monitors.origin.x),
"top": int_(all_monitors.origin.y),
"width": int_(all_monitors.size.width),
"height": int_(all_monitors.size.height),
}
def _grab_impl(self, monitor):
# type: (Monitor) -> ScreenShot
""" Retrieve all pixels from a monitor. Pixels have to be RGB. """
# pylint: disable=too-many-locals
core = self.core
rect = CGRect(
(monitor["left"], monitor["top"]), (monitor["width"], monitor["height"])
)
image_ref = core.CGWindowListCreateImage(rect, 1, 0, 0)
if not image_ref:
raise ScreenShotError("CoreGraphics.CGWindowListCreateImage() failed.")
width = core.CGImageGetWidth(image_ref)
height = core.CGImageGetHeight(image_ref)
prov = copy_data = None
try:
prov = core.CGImageGetDataProvider(image_ref)
copy_data = core.CGDataProviderCopyData(prov)
data_ref = core.CFDataGetBytePtr(copy_data)
buf_len = core.CFDataGetLength(copy_data)
raw = ctypes.cast(data_ref, POINTER(c_ubyte * buf_len))
data = bytearray(raw.contents)
# Remove padding per row
bytes_per_row = core.CGImageGetBytesPerRow(image_ref)
bytes_per_pixel = core.CGImageGetBitsPerPixel(image_ref)
bytes_per_pixel = (bytes_per_pixel + 7) // 8
if bytes_per_pixel * width != bytes_per_row:
cropped = bytearray()
for row in range(height):
start = row * bytes_per_row
end = start + width * bytes_per_pixel
cropped.extend(data[start:end])
data = cropped
finally:
if prov:
core.CGDataProviderRelease(prov)
if copy_data:
core.CFRelease(copy_data)
return self.cls_image(data, monitor, size=Size(width, height))