ScreenMagnifier 1.11.0.post8__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of ScreenMagnifier might be problematic. Click here for more details.

Files changed (117) hide show
  1. ScreenMagnifier/__init__.py +68 -0
  2. ScreenMagnifier/__main__.py +17 -0
  3. ScreenMagnifier/advancedoverlay.py +593 -0
  4. ScreenMagnifier/advancedpanel.py +521 -0
  5. ScreenMagnifier/analysiscontroller.py +533 -0
  6. ScreenMagnifier/analysisserver.py +404 -0
  7. ScreenMagnifier/colordetector/__init__.py +28 -0
  8. ScreenMagnifier/colordetector/colordetector.py +570 -0
  9. ScreenMagnifier/colordetector/core.py +434 -0
  10. ScreenMagnifier/colordetector/main.py +23 -0
  11. ScreenMagnifier/colordetector/mainwindow.py +182 -0
  12. ScreenMagnifier/colorpanel.py +424 -0
  13. ScreenMagnifier/colorswatches/__init__.py +16 -0
  14. ScreenMagnifier/colorswatches/colorswatches.py +316 -0
  15. ScreenMagnifier/colorswatches/main.py +23 -0
  16. ScreenMagnifier/colorswatches/mainwindow.py +60 -0
  17. ScreenMagnifier/controlpanel.py +234 -0
  18. ScreenMagnifier/detectionpanel.py +790 -0
  19. ScreenMagnifier/facedetector/__init__.py +24 -0
  20. ScreenMagnifier/facedetector/core.py +314 -0
  21. ScreenMagnifier/facedetector/facedetector.py +288 -0
  22. ScreenMagnifier/facedetector/main.py +23 -0
  23. ScreenMagnifier/facedetector/mainwindow.py +122 -0
  24. ScreenMagnifier/facedetector/models/__init__.py +4 -0
  25. ScreenMagnifier/facepointer.py +1121 -0
  26. ScreenMagnifier/features.py +50 -0
  27. ScreenMagnifier/hotkeys/__init__.py +16 -0
  28. ScreenMagnifier/hotkeys/hotkeys.py +379 -0
  29. ScreenMagnifier/hotkeys/main.py +23 -0
  30. ScreenMagnifier/hotkeys/mainwindow.py +56 -0
  31. ScreenMagnifier/imagefilters/__init__.py +24 -0
  32. ScreenMagnifier/imagefilters/core.py +172 -0
  33. ScreenMagnifier/imagefilters/imagefilters.py +220 -0
  34. ScreenMagnifier/imagefilters/main.py +23 -0
  35. ScreenMagnifier/imagefilters/mainwindow.py +120 -0
  36. ScreenMagnifier/magnifierview/__init__.py +16 -0
  37. ScreenMagnifier/magnifierview/magnifierview.py +1249 -0
  38. ScreenMagnifier/magnifierview/main.py +23 -0
  39. ScreenMagnifier/magnifierview/mainwindow.py +91 -0
  40. ScreenMagnifier/main.py +157 -0
  41. ScreenMagnifier/mainwindow.py +1368 -0
  42. ScreenMagnifier/mousecatcher/__init__.py +16 -0
  43. ScreenMagnifier/mousecatcher/main.py +23 -0
  44. ScreenMagnifier/mousecatcher/mainwindow.py +78 -0
  45. ScreenMagnifier/mousecatcher/mousecatcher.py +251 -0
  46. ScreenMagnifier/mousemove.py +259 -0
  47. ScreenMagnifier/netprotocol/__init__.py +25 -0
  48. ScreenMagnifier/netprotocol/main.py +23 -0
  49. ScreenMagnifier/netprotocol/mainwindow.py +91 -0
  50. ScreenMagnifier/netprotocol/netprotocol.py +372 -0
  51. ScreenMagnifier/netprotocol/wire.py +189 -0
  52. ScreenMagnifier/regionselector/__init__.py +16 -0
  53. ScreenMagnifier/regionselector/main.py +23 -0
  54. ScreenMagnifier/regionselector/mainwindow.py +70 -0
  55. ScreenMagnifier/regionselector/regionselector.py +549 -0
  56. ScreenMagnifier/remoteclient.py +636 -0
  57. ScreenMagnifier/resources/icon-128.png +0 -0
  58. ScreenMagnifier/resources/icon-16.png +0 -0
  59. ScreenMagnifier/resources/icon-24.png +0 -0
  60. ScreenMagnifier/resources/icon-256.png +0 -0
  61. ScreenMagnifier/resources/icon-32.png +0 -0
  62. ScreenMagnifier/resources/icon-48.png +0 -0
  63. ScreenMagnifier/resources/icon-512.png +0 -0
  64. ScreenMagnifier/resources/icon-64.png +0 -0
  65. ScreenMagnifier/resources/icon.icns +0 -0
  66. ScreenMagnifier/resources/icon.ico +0 -0
  67. ScreenMagnifier/screengrabber/__init__.py +16 -0
  68. ScreenMagnifier/screengrabber/main.py +23 -0
  69. ScreenMagnifier/screengrabber/mainwindow.py +79 -0
  70. ScreenMagnifier/screengrabber/screengrabber.py +558 -0
  71. ScreenMagnifier/server.py +150 -0
  72. ScreenMagnifier/serverpanel.py +379 -0
  73. ScreenMagnifier/shortcuteditor/__init__.py +16 -0
  74. ScreenMagnifier/shortcuteditor/main.py +23 -0
  75. ScreenMagnifier/shortcuteditor/mainwindow.py +54 -0
  76. ScreenMagnifier/shortcuteditor/shortcuteditor.py +411 -0
  77. ScreenMagnifier/shortcuts.py +118 -0
  78. ScreenMagnifier/shortcutspanel.py +140 -0
  79. ScreenMagnifier/support.py +127 -0
  80. ScreenMagnifier/translations/ar.json +387 -0
  81. ScreenMagnifier/translations/de.json +387 -0
  82. ScreenMagnifier/translations/es.json +387 -0
  83. ScreenMagnifier/translations/fr.json +387 -0
  84. ScreenMagnifier/translations/it.json +387 -0
  85. ScreenMagnifier/translations/ja.json +387 -0
  86. ScreenMagnifier/translations/ko.json +387 -0
  87. ScreenMagnifier/translations/pt_BR.json +387 -0
  88. ScreenMagnifier/translations/ru.json +387 -0
  89. ScreenMagnifier/translations/tr.json +387 -0
  90. ScreenMagnifier/translations/zh_CN.json +387 -0
  91. ScreenMagnifier/translator/__init__.py +16 -0
  92. ScreenMagnifier/translator/main.py +23 -0
  93. ScreenMagnifier/translator/mainwindow.py +62 -0
  94. ScreenMagnifier/translator/translator.py +284 -0
  95. ScreenMagnifier/upscaler/__init__.py +24 -0
  96. ScreenMagnifier/upscaler/core.py +315 -0
  97. ScreenMagnifier/upscaler/main.py +23 -0
  98. ScreenMagnifier/upscaler/mainwindow.py +128 -0
  99. ScreenMagnifier/upscaler/models/FSRCNN-small_x2.pb +0 -0
  100. ScreenMagnifier/upscaler/models/FSRCNN-small_x3.pb +0 -0
  101. ScreenMagnifier/upscaler/models/FSRCNN-small_x4.pb +0 -0
  102. ScreenMagnifier/upscaler/models/FSRCNN_x2.pb +0 -0
  103. ScreenMagnifier/upscaler/models/FSRCNN_x3.pb +0 -0
  104. ScreenMagnifier/upscaler/models/FSRCNN_x4.pb +0 -0
  105. ScreenMagnifier/upscaler/models/LICENSE-FSRCNN +201 -0
  106. ScreenMagnifier/upscaler/models/__init__.py +4 -0
  107. ScreenMagnifier/upscaler/upscaler.py +285 -0
  108. ScreenMagnifier/wincheck.py +65 -0
  109. ScreenMagnifier/zoomoverlay/__init__.py +16 -0
  110. ScreenMagnifier/zoomoverlay/main.py +23 -0
  111. ScreenMagnifier/zoomoverlay/mainwindow.py +99 -0
  112. ScreenMagnifier/zoomoverlay/zoomoverlay.py +1779 -0
  113. screenmagnifier-1.11.0.post8.dist-info/METADATA +591 -0
  114. screenmagnifier-1.11.0.post8.dist-info/RECORD +117 -0
  115. screenmagnifier-1.11.0.post8.dist-info/WHEEL +5 -0
  116. screenmagnifier-1.11.0.post8.dist-info/entry_points.txt +5 -0
  117. screenmagnifier-1.11.0.post8.dist-info/top_level.txt +1 -0
@@ -0,0 +1,23 @@
1
+ # coding=utf-8
2
+ """
3
+ Entry point for the ScreenGrabber demo.
4
+ """
5
+ from os.path import dirname
6
+ from sys import path
7
+
8
+ if not __package__ and dirname(__file__) not in path:
9
+ path.append(dirname(__file__))
10
+
11
+ try:
12
+ from .mainwindow import MainWindow
13
+ except:
14
+ from mainwindow import MainWindow
15
+
16
+ if __name__ == '__main__':
17
+ from ManyQt.QtWidgets import QApplication
18
+ from sys import argv, exit
19
+
20
+ a = QApplication(argv) # type: QApplication
21
+ w = MainWindow() # type: MainWindow
22
+ w.show()
23
+ exit(a.exec_())
@@ -0,0 +1,79 @@
1
+ # coding=utf-8
2
+ """
3
+ Demo window for ScreenGrabber: live capture around the mouse cursor (or a fixed region).
4
+ """
5
+ from ManyQt.QtWidgets import QMainWindow, QVBoxLayout, QHBoxLayout, QWidget, QLabel, QCheckBox, QSpinBox
6
+ from ManyQt.QtCore import Qt, QRect, QSize, pyqtSlot
7
+ from ManyQt.QtGui import QImage, QPixmap
8
+ from os.path import dirname
9
+ from sys import path
10
+
11
+ if not __package__ and dirname(__file__) not in path:
12
+ path.append(dirname(__file__))
13
+
14
+ try:
15
+ from .screengrabber import ScreenGrabber
16
+ except:
17
+ from screengrabber import ScreenGrabber
18
+
19
+
20
+ class MainWindow(QMainWindow):
21
+ """
22
+ MainWindow class.
23
+ """
24
+
25
+ def __init__(self, *args, **kwargs):
26
+ """
27
+ :param args: any
28
+ :param kwargs: any
29
+ """
30
+ super(MainWindow, self).__init__(*args, **kwargs)
31
+ self.setWindowTitle(self.tr(u'ScreenGrabber demo'))
32
+ self.resize(760, 520)
33
+ self.__m_image = QLabel(self.tr(u'Waiting for frames...')) # type: QLabel
34
+ self.__m_image.setAlignment(Qt.AlignCenter)
35
+ self.__m_image.setMinimumSize(320, 240)
36
+ self.__m_info = QLabel() # type: QLabel
37
+ follow = QCheckBox(self.tr(u'Follow cursor')) # type: QCheckBox
38
+ follow.setChecked(True)
39
+ fps = QSpinBox() # type: QSpinBox
40
+ fps.setRange(1, 120)
41
+ fps.setValue(30)
42
+ fps.setSuffix(' fps')
43
+ self.__m_grabber = ScreenGrabber(fps=30, followCursor=True, followSize=QSize(360, 240),
44
+ region=QRect(0, 0, 360, 240), ignoreWidgets=[self],
45
+ frameReady=self.onFrame, captureFailed=self.onFailed,
46
+ autoStart=True) # type: ScreenGrabber
47
+ follow.toggled.connect(self.__m_grabber.setFollowCursor)
48
+ fps.valueChanged.connect(self.__m_grabber.setFps)
49
+ bar = QHBoxLayout() # type: QHBoxLayout
50
+ bar.addWidget(follow)
51
+ bar.addWidget(fps)
52
+ bar.addStretch(1)
53
+ bar.addWidget(self.__m_info)
54
+ wdg = QWidget() # type: QWidget
55
+ layout = QVBoxLayout(wdg) # type: QVBoxLayout
56
+ layout.addLayout(bar)
57
+ layout.addWidget(self.__m_image, 1)
58
+ self.setCentralWidget(wdg)
59
+
60
+ @pyqtSlot(QImage)
61
+ def onFrame(self, image):
62
+ """
63
+ :param image: QImage
64
+ :return:
65
+ """
66
+ self.__m_image.setPixmap(QPixmap.fromImage(image).scaled(
67
+ self.__m_image.size(), Qt.KeepAspectRatio, Qt.FastTransformation))
68
+ r = self.__m_grabber.getCaptureRect() # type: QRect
69
+ self.__m_info.setText(u'{}x{} @ ({}, {}) grab {:.1f} ms'.format(
70
+ image.width(), image.height(), r.x(), r.y(), self.__m_grabber.getLastGrabTime()))
71
+
72
+ @pyqtSlot('QString')
73
+ @pyqtSlot(str)
74
+ def onFailed(self, message):
75
+ """
76
+ :param message: str | unicode | QString
77
+ :return:
78
+ """
79
+ self.__m_image.setText(message)
@@ -0,0 +1,558 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ ScreenGrabber: live capture of a screen region at a fixed frame rate.
4
+ - Fixed-region mode: captures region (global, device-independent coordinates).
5
+ - Follow-cursor mode: captures a followSize area (in output image pixels) centred on the mouse cursor.
6
+ - Multi-monitor: regions spanning several screens are composed of each screen's grab.
7
+ - HiDPI: frames are delivered in physical pixels of the screen under the region center.
8
+ - Windows/macOS/X11 supported by Qt's QScreen.grabWindow; Wayland compositors usually refuse
9
+ screen grabs, in which case captureFailed is emitted once.
10
+ - captureFunction: plug in another capture method, e.g. winGrabWindowRect() which captures one application
11
+ window directly with PrintWindow, so overlays drawn above it (a magnifier lens) are never captured.
12
+ """
13
+ from ManyQt.QtCore import Qt, QTimer, QElapsedTimer, QRect, QRectF, QSize, QPoint, QObject, pyqtSignal, pyqtSlot, \
14
+ pyqtProperty
15
+ from ManyQt.QtGui import QImage, QPainter, QColor, QCursor, QGuiApplication
16
+ from sys import platform
17
+ from os import getpid
18
+
19
+
20
+ def screenAtPoint(point):
21
+ """
22
+ :param point: QPoint
23
+ :return: QScreen
24
+ """
25
+ screen = QGuiApplication.screenAt(point) if hasattr(QGuiApplication, 'screenAt') else None
26
+ return screen if screen is not None else QGuiApplication.primaryScreen()
27
+
28
+
29
+ _WIN = {} # type: dict # Lazily created ctypes handles for the Windows window-capture helpers.
30
+
31
+
32
+ def _winApi():
33
+ """
34
+ Private user32 / gdi32 / dwmapi handles with 64-bit safe prototypes.
35
+ :return: dict
36
+ """
37
+ if _WIN:
38
+ return _WIN
39
+ from ctypes import WinDLL, POINTER, c_long, c_void_p, c_int
40
+ from ctypes.wintypes import BOOL, UINT, DWORD, RECT
41
+ u = WinDLL('user32', use_last_error=True)
42
+ g = WinDLL('gdi32', use_last_error=True)
43
+ H = c_void_p
44
+ for name, args, res in (('GetTopWindow', [H], H), ('GetWindow', [H, UINT], H),
45
+ ('IsWindowVisible', [H], BOOL), ('IsIconic', [H], BOOL),
46
+ ('GetWindowThreadProcessId', [H, POINTER(DWORD)], DWORD),
47
+ ('GetWindowLongW', [H, c_int], c_long),
48
+ ('GetWindowRect', [H, POINTER(RECT)], BOOL),
49
+ ('GetDC', [H], H), ('ReleaseDC', [H, H], c_int),
50
+ ('PrintWindow', [H, H, UINT], BOOL)):
51
+ f = getattr(u, name)
52
+ f.argtypes, f.restype = args, res
53
+ for name, args, res in (('CreateCompatibleDC', [H], H), ('CreateCompatibleBitmap', [H, c_int, c_int], H),
54
+ ('SelectObject', [H, H], H), ('DeleteObject', [H], BOOL),
55
+ ('DeleteDC', [H], BOOL), ('GdiFlush', [], BOOL),
56
+ ('BitBlt', [H, c_int, c_int, c_int, c_int, H, c_int,
57
+ c_int, DWORD], BOOL),
58
+ ('PatBlt', [H, c_int, c_int, c_int, c_int, DWORD],
59
+ BOOL),
60
+ ('CreateDIBSection', [H, c_void_p, UINT, POINTER(c_void_p), H, DWORD], H)):
61
+ f = getattr(g, name)
62
+ f.argtypes, f.restype = args, res
63
+ try:
64
+ d = WinDLL('dwmapi')
65
+ d.DwmGetWindowAttribute.argtypes = [H, DWORD, c_void_p, DWORD]
66
+ d.DwmGetWindowAttribute.restype = c_long
67
+ except Exception:
68
+ d = None
69
+ _WIN.update(user32=u, gdi32=g, dwmapi=d)
70
+ return _WIN
71
+
72
+
73
+ def toPhysical(point):
74
+ """
75
+ Qt (device-independent) global point -> Windows physical pixels (Qt keeps each screen's origin unscaled).
76
+ :param point: QPoint
77
+ :return: (tuple[int, int, float]) x, y and the device pixel ratio of that screen.
78
+ """
79
+ screen = screenAtPoint(point)
80
+ sg = screen.geometry() # type: QRect
81
+ dpr = float(screen.devicePixelRatio()) # type: float
82
+ return int(round(sg.x() + (point.x() - sg.x()) * dpr)), int(round(sg.y() + (point.y() - sg.y()) * dpr)), dpr
83
+
84
+
85
+ def winWindowAt(point):
86
+ """
87
+ Topmost real application window under a global point, ignoring this process' windows, click-through
88
+ overlays (WS_EX_TRANSPARENT), tool windows and cloaked windows. Windows only.
89
+ :param point: QPoint
90
+ :return: (int | None) HWND
91
+ """
92
+ if platform != 'win32':
93
+ return None
94
+ try:
95
+ from ctypes.wintypes import DWORD, RECT
96
+ from ctypes import byref
97
+ api = _winApi()
98
+ u, d = api['user32'], api['dwmapi']
99
+ px, py, dpr = toPhysical(point)
100
+ pid = getpid() # type: int
101
+ GW_HWNDNEXT, GWL_EXSTYLE, WS_EX_TRANSPARENT, WS_EX_TOOLWINDOW, DWMWA_CLOAKED = 2, -20, 0x20, 0x80, 14
102
+ hwnd = u.GetTopWindow(None)
103
+ for _ in range(10000):
104
+ if not hwnd:
105
+ break
106
+ if u.IsWindowVisible(hwnd) and not u.IsIconic(hwnd):
107
+ owner = DWORD(0)
108
+ u.GetWindowThreadProcessId(hwnd, byref(owner))
109
+ ex = u.GetWindowLongW(hwnd, GWL_EXSTYLE) # type: int
110
+ if owner.value != pid and not ex & (WS_EX_TRANSPARENT | WS_EX_TOOLWINDOW):
111
+ cloaked = DWORD(0)
112
+ if d is not None:
113
+ d.DwmGetWindowAttribute(hwnd, DWMWA_CLOAKED, byref(cloaked), 4)
114
+ r = RECT()
115
+ if not cloaked.value and u.GetWindowRect(
116
+ hwnd, byref(r)) and r.left <= px < r.right and r.top <= py < r.bottom:
117
+ return hwnd
118
+ hwnd = u.GetWindow(hwnd, GW_HWNDNEXT)
119
+ except Exception:
120
+ pass
121
+ return None
122
+
123
+
124
+ def winGrabWindowRect(hwnd, rect, background=QColor(16, 16, 20)):
125
+ """
126
+ Capture the part of one window that lies under a global rect with PrintWindow(PW_RENDERFULLCONTENT).
127
+ Windows drawn ON TOP of that window (such as a magnifier lens) are never part of the result.
128
+ :param hwnd: (int) Window to capture.
129
+ :param rect: (QRect) Global, device-independent rect.
130
+ :param background: QColor
131
+ :return: (tuple[QImage, float | int]) Image in physical pixels (null on failure) and the device pixel ratio.
132
+ """
133
+ if platform != 'win32' or not hwnd or rect.isEmpty():
134
+ return QImage(), 1.0
135
+ from ctypes import c_long, c_void_p, byref, Structure, sizeof, string_at
136
+ from ctypes.wintypes import WORD, DWORD, RECT
137
+ api = _winApi()
138
+ u, g = api['user32'], api['gdi32']
139
+ x0, y0, dpr = toPhysical(rect.topLeft())
140
+ pw, ph = max(1, int(round(rect.width() * dpr))), max(1, int(round(rect.height() * dpr))) # type: int, int
141
+ r = RECT()
142
+ if not u.GetWindowRect(hwnd, byref(r)):
143
+ return QImage(), dpr
144
+ ww, wh = r.right - r.left, r.bottom - r.top # type: int, int
145
+ if ww <= 0 or wh <= 0:
146
+ return QImage(), dpr
147
+
148
+ class BITMAPINFOHEADER(Structure):
149
+ """
150
+ BITMAPINFOHEADER structure.
151
+ """
152
+ _fields_ = [('biSize', DWORD), ('biWidth', c_long), ('biHeight', c_long), ('biPlanes', WORD),
153
+ ('biBitCount', WORD), ('biCompression', DWORD), ('biSizeImage', DWORD),
154
+ ('biXPelsPerMeter', c_long), ('biYPelsPerMeter', c_long), ('biClrUsed', DWORD),
155
+ ('biClrImportant', DWORD)]
156
+
157
+ screenDc = u.GetDC(None)
158
+ fullDc = g.CreateCompatibleDC(screenDc)
159
+ fullBmp = g.CreateCompatibleBitmap(screenDc, ww, wh)
160
+ oldFull = g.SelectObject(fullDc, fullBmp)
161
+ cropDc = g.CreateCompatibleDC(screenDc)
162
+ bmi = BITMAPINFOHEADER(sizeof(BITMAPINFOHEADER), pw, -ph, 1, 32, 0, 0, 0, 0, 0, 0) # Top-down BGRA.
163
+ bits = c_void_p()
164
+ dib = g.CreateDIBSection(cropDc, byref(bmi), 0, byref(bits), None, 0)
165
+ image = QImage() # type: QImage
166
+ try:
167
+ if dib and bits.value:
168
+ oldCrop = g.SelectObject(cropDc, dib)
169
+ PW_RENDERFULLCONTENT, SRCCOPY, BLACKNESS = 0x2, 0x00CC0020, 0x00000042
170
+ ok = u.PrintWindow(hwnd, fullDc, PW_RENDERFULLCONTENT)
171
+ g.PatBlt(cropDc, 0, 0, pw, ph, BLACKNESS)
172
+ if ok:
173
+ g.BitBlt(cropDc, 0, 0, pw, ph, fullDc, x0 - r.left, y0 - r.top, SRCCOPY)
174
+ g.GdiFlush()
175
+ data = string_at(bits.value, pw * ph * 4) # type: bytes
176
+ image = QImage(data, pw, ph, pw * 4, QImage.Format_RGB32).copy()
177
+ g.SelectObject(cropDc, oldCrop)
178
+ finally:
179
+ if dib:
180
+ g.DeleteObject(dib)
181
+ g.SelectObject(fullDc, oldFull)
182
+ g.DeleteObject(fullBmp)
183
+ g.DeleteDC(fullDc)
184
+ g.DeleteDC(cropDc)
185
+ u.ReleaseDC(None, screenDc)
186
+ return image, dpr
187
+
188
+
189
+ def isBlankImage(image):
190
+ """
191
+ :param image: QImage
192
+ :return: (bool) True when the image is null or (almost) entirely black, e.g. a failed window capture.
193
+ """
194
+ if image.isNull():
195
+ return True
196
+ w, h = image.width(), image.height() # type: int, int
197
+ for j in range(1, 8):
198
+ for i in range(1, 8):
199
+ if QColor(image.pixel(min(w - 1, w * i // 8), min(h - 1, h * j // 8))).value() > 6:
200
+ return False
201
+ return True
202
+
203
+
204
+ def globalRect(widget):
205
+ """
206
+ :param widget: QWidget
207
+ :return: (QRect) Widget area in global coordinates (frame included for top-level windows).
208
+ """
209
+ return widget.frameGeometry() if widget.isWindow() else QRect(widget.mapToGlobal(QPoint(0, 0)), widget.size())
210
+
211
+
212
+ class ScreenGrabber(QObject):
213
+ """
214
+ ScreenGrabber class.
215
+ """
216
+ frameReady = pyqtSignal(QImage) # type: pyqtSignal
217
+ captureFailed = pyqtSignal('QString') # type: pyqtSignal
218
+ regionChanged = pyqtSignal(QRect) # type: pyqtSignal
219
+ activeChanged = pyqtSignal(bool) # type: pyqtSignal
220
+ fpsChanged = pyqtSignal(int) # type: pyqtSignal
221
+
222
+ def __init__(self, *args, **kwargs):
223
+ """
224
+ :param region: (QRect) Global region to capture in fixed mode.
225
+ :param fps: (int) Frames per second, 1 .. 120.
226
+ :param followCursor: (bool) Capture around the mouse cursor instead of region.
227
+ :param followSize: (QSize) Follow-mode capture size in output image pixels.
228
+ :param autoStart: bool
229
+ :param ignoreWidgets: (list[QWidget]) In follow mode, frames are not grabbed while the cursor is over
230
+ one of these windows (prevents the "hall of mirrors" effect on the magnifier itself).
231
+ :param background: (QColor | Qt.GlobalColor | int | str) Fill color for areas outside every screen.
232
+ :param captureFunction: (callable | None) f(QRect, QColor) -> (QImage, float) replacing the desktop grab.
233
+ :param frameReady: callable | None
234
+ :param captureFailed: callable | None
235
+ :param args: any
236
+ :param kwargs: any
237
+ """
238
+ region = kwargs.pop('region', QRect()) # type: QRect
239
+ fps = kwargs.pop('fps', 30) # type: int
240
+ followCursor = kwargs.pop('followCursor', False) # type: bool
241
+ followSize = kwargs.pop('followSize', QSize(240, 160)) # type: QSize
242
+ autoStart = kwargs.pop('autoStart', False) # type: bool
243
+ ignoreWidgets = kwargs.pop('ignoreWidgets', []) # type: list
244
+ background = kwargs.pop('background', QColor(16, 16, 20)) # type: QColor
245
+ captureFunction = kwargs.pop('captureFunction', None) # type: callable | None
246
+ frameReady = kwargs.pop('frameReady', None) # type: callable | None
247
+ captureFailed = kwargs.pop('captureFailed', None) # type: callable | None
248
+ super(ScreenGrabber, self).__init__(*args, **kwargs)
249
+ if callable(frameReady):
250
+ self.frameReady.connect(frameReady)
251
+ if callable(captureFailed):
252
+ self.captureFailed.connect(captureFailed)
253
+ # Options.
254
+ self.__m_region = QRect(region) # type: QRect
255
+ self.__m_fps = max(1, min(120, int(fps))) # type: int
256
+ self.__m_followCursor = bool(followCursor) # type: bool
257
+ self.__m_followSize = QSize(max(1, followSize.width()), max(1, followSize.height())) # type: QSize
258
+ self.__m_ignoreWidgets = list(ignoreWidgets) # type: list
259
+ self.__m_background = background if isinstance(background, QColor) else QColor(background) # type: QColor
260
+ self.__m_captureFunction = captureFunction if callable(captureFunction) else None # type: callable | None
261
+ # State.
262
+ self.__m_captureRect = QRect() # type: QRect
263
+ self.__m_devicePixelRatio = 1.0 # type: float
264
+ self.__m_lastGrabMs = 0.0 # type: float
265
+ self.__m_failed = False # type: bool
266
+ self.__m_frameCount = 0 # type: int
267
+ self.__m_clock = QElapsedTimer() # type: QElapsedTimer
268
+ self.__m_timer = QTimer(self) # type: QTimer
269
+ self.__m_timer.setTimerType(Qt.PreciseTimer)
270
+ self.__m_timer.timeout.connect(self._tick)
271
+ if autoStart:
272
+ self.start()
273
+
274
+ # ---------- Helpers ----------
275
+ @staticmethod
276
+ def virtualGeometry():
277
+ """
278
+ :return: (QRect) Union of all screen geometries.
279
+ """
280
+ rect = QRect() # type: QRect
281
+ for screen in QGuiApplication.screens():
282
+ rect = rect.united(screen.geometry()) # type: QRect
283
+ return rect
284
+
285
+ @staticmethod
286
+ def grabRect(rect, background=QColor(16, 16, 20)):
287
+ """
288
+ Grab a global rect, composing every screen it touches, in physical pixels.
289
+ :param rect: QRect
290
+ :param background: QColor
291
+ :return: (tuple[QImage, float]) Image (null on failure) and the device pixel ratio used.
292
+ """
293
+ if rect.isEmpty():
294
+ return QImage(), 1.0
295
+ dpr = float(screenAtPoint(rect.center()).devicePixelRatio()) # type: float
296
+ img = QImage(max(1, int(round(rect.width() * dpr))), max(1, int(round(rect.height() * dpr))),
297
+ QImage.Format_RGB32) # type: QImage
298
+ img.fill(background)
299
+ p = QPainter(img) # type: QPainter
300
+ p.setRenderHint(QPainter.SmoothPixmapTransform, True)
301
+ grabbed = False # type: bool
302
+ for screen in QGuiApplication.screens():
303
+ geo = screen.geometry() # type: QRect
304
+ inter = geo.intersected(rect) # type: QRect
305
+ if inter.isEmpty():
306
+ continue
307
+ pm = screen.grabWindow(0, inter.x() - geo.x(), inter.y() - geo.y(), inter.width(), inter.height())
308
+ if pm.isNull() or pm.width() == 0:
309
+ continue
310
+ pm.setDevicePixelRatio(1.0)
311
+ target = QRectF((inter.x() - rect.x()) * dpr, (inter.y() - rect.y()) * dpr, inter.width() * dpr,
312
+ inter.height() * dpr) # type: QRectF
313
+ p.drawPixmap(target, pm, QRectF(0, 0, pm.width(), pm.height()))
314
+ grabbed = True # type: bool
315
+ p.end()
316
+ return (img if grabbed else QImage()), dpr
317
+
318
+ def _followRect(self):
319
+ """
320
+ :return: (QRect | None) Follow-mode capture rect, None when the cursor is over an ignored widget.
321
+ """
322
+ pos = QCursor.pos() # type: QPoint
323
+ for w in self.__m_ignoreWidgets:
324
+ try:
325
+ if w.isVisible() and globalRect(w).contains(pos):
326
+ return None
327
+ except:
328
+ continue
329
+ dpr = float(screenAtPoint(pos).devicePixelRatio()) # type: float
330
+ w = max(1, int(round(self.__m_followSize.width() / dpr))) # type: int
331
+ h = max(1, int(round(self.__m_followSize.height() / dpr))) # type: int
332
+ return QRect(pos.x() - w // 2, pos.y() - h // 2, w, h)
333
+
334
+ # ---------- Grab tick ----------
335
+ def _tick(self):
336
+ """
337
+ :return: None
338
+ """
339
+ rect = self._followRect() if self.__m_followCursor else QRect(self.__m_region) # type: QRect | None
340
+ if rect is None or rect.isEmpty():
341
+ return
342
+ self.__m_clock.start()
343
+ grab = self.__m_captureFunction or ScreenGrabber.grabRect
344
+ try:
345
+ img, dpr = grab(rect, self.__m_background)
346
+ except Exception:
347
+ img, dpr = QImage(), 1.0
348
+ self.__m_lastGrabMs = float(self.__m_clock.nsecsElapsed()) / 1e6 # type: float
349
+ if img.isNull():
350
+ if not self.__m_failed:
351
+ self.__m_failed = True # type: bool
352
+ self.captureFailed.emit(u'Screen capture returned no image. On Wayland, start the app with '
353
+ 'QT_QPA_PLATFORM=xcb; on macOS, allow Screen Recording permission.')
354
+ return
355
+ self.__m_failed = False # type: bool
356
+ self.__m_captureRect = rect # type: QRect
357
+ self.__m_devicePixelRatio = dpr # type: float
358
+ self.__m_frameCount += 1
359
+ self.frameReady.emit(img)
360
+
361
+ # ---------- Public API ----------
362
+ @pyqtSlot()
363
+ def start(self):
364
+ """
365
+ :return:
366
+ """
367
+ if not self.__m_timer.isActive():
368
+ self.__m_timer.start(int(round(1000.0 / self.__m_fps)))
369
+ self._tick()
370
+ self.activeChanged.emit(True)
371
+
372
+ @pyqtSlot()
373
+ def stop(self):
374
+ """
375
+ :return:
376
+ """
377
+ if self.__m_timer.isActive():
378
+ self.__m_timer.stop()
379
+ self.activeChanged.emit(False)
380
+
381
+ @pyqtSlot()
382
+ def grabNow(self):
383
+ """
384
+ Grab a single frame immediately (works while stopped).
385
+ :return:
386
+ """
387
+ self._tick()
388
+
389
+ def isActive(self):
390
+ """
391
+ :return: bool
392
+ """
393
+ return self.__m_timer.isActive()
394
+
395
+ @pyqtSlot(bool)
396
+ @pyqtSlot(int)
397
+ def setActive(self, active):
398
+ """
399
+ :param active: bool
400
+ :return:
401
+ """
402
+ if bool(active):
403
+ self.start()
404
+ else:
405
+ self.stop()
406
+
407
+ def getRegion(self):
408
+ """
409
+ :return: QRect
410
+ """
411
+ return QRect(self.__m_region)
412
+
413
+ @pyqtSlot(QRect)
414
+ def setRegion(self, region):
415
+ """
416
+ :param region: QRect
417
+ :return:
418
+ """
419
+ region = QRect(region).normalized() # type: QRect
420
+ if region != self.__m_region:
421
+ self.__m_region = region # type: QRect
422
+ self.regionChanged.emit(QRect(region))
423
+
424
+ def getFps(self):
425
+ """
426
+ :return: int
427
+ """
428
+ return self.__m_fps
429
+
430
+ @pyqtSlot(int)
431
+ def setFps(self, fps):
432
+ """
433
+ :param fps: (int) 1 .. 120
434
+ :return:
435
+ """
436
+ fps = max(1, min(120, int(fps))) # type: int
437
+ if fps != self.__m_fps:
438
+ self.__m_fps = fps # type: int
439
+ if self.__m_timer.isActive():
440
+ self.__m_timer.setInterval(int(round(1000.0 / fps)))
441
+ self.fpsChanged.emit(fps)
442
+
443
+ def isFollowCursor(self):
444
+ """
445
+ :return: bool
446
+ """
447
+ return self.__m_followCursor
448
+
449
+ @pyqtSlot(bool)
450
+ @pyqtSlot(int)
451
+ def setFollowCursor(self, followCursor):
452
+ """
453
+ :param followCursor: bool
454
+ :return:
455
+ """
456
+ self.__m_followCursor = bool(followCursor) # type: bool
457
+
458
+ def getFollowSize(self):
459
+ """
460
+ :return: QSize
461
+ """
462
+ return QSize(self.__m_followSize)
463
+
464
+ @pyqtSlot(QSize)
465
+ def setFollowSize(self, followSize):
466
+ """
467
+ :param followSize: (QSize) In output image pixels.
468
+ :return:
469
+ """
470
+ self.__m_followSize = QSize(max(1, followSize.width()), max(1, followSize.height())) # type: QSize
471
+
472
+ def getIgnoreWidgets(self):
473
+ """
474
+ :return: list[QWidget]
475
+ """
476
+ return list(self.__m_ignoreWidgets)
477
+
478
+ def setIgnoreWidgets(self, ignoreWidgets):
479
+ """
480
+ :param ignoreWidgets: list[QWidget]
481
+ :return:
482
+ """
483
+ self.__m_ignoreWidgets = list(ignoreWidgets) # type: list
484
+
485
+ def getBackground(self):
486
+ """
487
+ :return: QColor
488
+ """
489
+ return self.__m_background
490
+
491
+ @pyqtSlot(QColor)
492
+ @pyqtSlot(Qt.GlobalColor)
493
+ @pyqtSlot(int)
494
+ @pyqtSlot(str)
495
+ @pyqtSlot('QString')
496
+ def setBackground(self, background):
497
+ """
498
+ :param background: QColor | Qt.GlobalColor | int | str | QString
499
+ :return:
500
+ """
501
+ self.__m_background = background if isinstance(background, QColor) else QColor(background) # type: QColor
502
+
503
+ def getCaptureFunction(self):
504
+ """
505
+ :return: callable | None
506
+ """
507
+ return self.__m_captureFunction
508
+
509
+ @pyqtSlot(object)
510
+ def setCaptureFunction(self, captureFunction):
511
+ """
512
+ :param captureFunction: (callable | None) f(QRect, QColor) -> (QImage, float); None = desktop grab.
513
+ :return:
514
+ """
515
+ self.__m_captureFunction = captureFunction if callable(captureFunction) else None # type: callable | None
516
+
517
+ def getCaptureRect(self):
518
+ """
519
+ :return: (QRect) Global rect of the last delivered frame.
520
+ """
521
+ return QRect(self.__m_captureRect)
522
+
523
+ def getDevicePixelRatio(self):
524
+ """
525
+ :return: (float | int) Image pixels per logical pixel of the last frame.
526
+ """
527
+ return self.__m_devicePixelRatio
528
+
529
+ def getLastGrabTime(self):
530
+ """
531
+ :return: (float | int) ms spent in the last grab.
532
+ """
533
+ return self.__m_lastGrabMs
534
+
535
+ def getFrameCount(self):
536
+ """
537
+ :return: int
538
+ """
539
+ return self.__m_frameCount
540
+
541
+ def mapToGlobal(self, imagePoint):
542
+ """
543
+ Map a pixel of the last frame to global screen coordinates.
544
+ :param imagePoint: QPoint
545
+ :return: QPoint
546
+ """
547
+ dpr = self.__m_devicePixelRatio # type: float
548
+ return QPoint(self.__m_captureRect.x() + int(imagePoint.x() / dpr),
549
+ self.__m_captureRect.y() + int(imagePoint.y() / dpr))
550
+
551
+ # ---------- Properties ----------
552
+ region = pyqtProperty(QRect, fget=getRegion, fset=setRegion, notify=regionChanged) # type: pyqtProperty
553
+ fps = pyqtProperty(int, fget=getFps, fset=setFps, notify=fpsChanged) # type: pyqtProperty
554
+ followCursor = pyqtProperty(bool, fget=isFollowCursor, fset=setFollowCursor) # type: pyqtProperty
555
+ followSize = pyqtProperty(QSize, fget=getFollowSize, fset=setFollowSize) # type: pyqtProperty
556
+ active = pyqtProperty(bool, fget=isActive, fset=setActive, notify=activeChanged) # type: pyqtProperty
557
+ background = pyqtProperty(QColor, fget=getBackground, fset=setBackground) # type: pyqtProperty
558
+ captureFunction = pyqtProperty(object, fget=getCaptureFunction, fset=setCaptureFunction) # type: pyqtProperty