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,91 @@
1
+ # coding=utf-8
2
+ """
3
+ Demo window for NetProtocol: a loopback server and client exchanging images; shows round trip and throughput.
4
+ """
5
+ from ManyQt.QtWidgets import QMainWindow, QVBoxLayout, QWidget, QLabel, QPushButton, QComboBox
6
+ from ManyQt.QtGui import QImage, QPainter, QColor, QFont
7
+ from ManyQt.QtCore import Qt, QTimer, QElapsedTimer, pyqtSlot
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 .netprotocol import FrameServer, FrameChannel, encodeImage, decodeImage
16
+ except:
17
+ from netprotocol import FrameServer, FrameChannel, encodeImage, decodeImage
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'NetProtocol demo'))
32
+ self.resize(560, 300)
33
+ self.__m_server = FrameServer(channelOpened=self.onChannel) # type: FrameServer
34
+ self.__m_server.listen('127.0.0.1', 0)
35
+ self.__m_client = FrameChannel(messageReceived=self.onEcho) # type: FrameChannel
36
+ self.__m_client.connectToHost('127.0.0.1', self.__m_server.getPort())
37
+ self.__m_clock = QElapsedTimer() # type: QElapsedTimer
38
+ self.__m_clock.start()
39
+ self.__m_count = 0 # type: int
40
+ self.__m_bytes = 0 # type: int
41
+ self.__m_size = QComboBox() # type: QComboBox
42
+ self.__m_size.addItems(['320x200', '1280x720', '1920x1080'])
43
+ self.__m_info = QLabel(self.tr(u'Press Start')) # type: QLabel
44
+ self.__m_info.setAlignment(Qt.AlignCenter)
45
+ start = QPushButton(self.tr(u'Start / stop')) # type: QPushButton
46
+ self.__m_timer = QTimer(self) # type: QTimer
47
+ self.__m_timer.timeout.connect(self.sendFrame)
48
+ start.clicked.connect(lambda: self.__m_timer.stop() if self.__m_timer.isActive() else self.__m_timer.start(30))
49
+ wdg = QWidget() # type: QWidget
50
+ layout = QVBoxLayout(wdg) # type: QVBoxLayout
51
+ layout.addWidget(QLabel(self.tr(u'Loopback server on port {}').format(self.__m_server.getPort())))
52
+ layout.addWidget(self.__m_size)
53
+ layout.addWidget(start)
54
+ layout.addWidget(self.__m_info, 1)
55
+ self.setCentralWidget(wdg)
56
+
57
+ def onChannel(self, channel):
58
+ """
59
+ :param channel: FrameChannel
60
+ :return:
61
+ """
62
+ channel.messageReceived.connect(lambda h, p, ch=channel: ch.send(dict(h, type='echo'), p))
63
+
64
+ @pyqtSlot()
65
+ def sendFrame(self):
66
+ """
67
+ :return:
68
+ """
69
+ w, h = [int(v) for v in self.__m_size.currentText().split('x')]
70
+ img = QImage(w, h, QImage.Format_RGB32) # type: QImage
71
+ img.fill(QColor.fromHsv(self.__m_count * 5 % 360, 160, 200))
72
+ p = QPainter(img) # type: QPainter
73
+ p.setFont(QFont('Sans Serif', 24))
74
+ p.drawText(img.rect(), Qt.AlignCenter, 'frame {}'.format(self.__m_count))
75
+ p.end()
76
+ self.__m_client.send({'type': 'frame', 'id': self.__m_count, 'sent': self.__m_clock.elapsed()},
77
+ encodeImage(img, 'JPG', 90))
78
+
79
+ def onEcho(self, header, payload):
80
+ """
81
+ :param header: dict
82
+ :param payload: bytes
83
+ :return:
84
+ """
85
+ self.__m_count += 1
86
+ self.__m_bytes += len(payload)
87
+ rtt = self.__m_clock.elapsed() - int(header.get('sent', 0)) # type: int
88
+ secs = max(0.001, self.__m_clock.elapsed() / 1000.0) # type: float
89
+ self.__m_info.setText(self.tr(u'frame {} {}x{}\nround trip {} ms\n{:.0f} KB per frame, {:.1f} MB/s').format(
90
+ header.get('id'), decodeImage(payload).width(), decodeImage(payload).height(), rtt,
91
+ len(payload) / 1024.0, self.__m_bytes / 1048576.0 / secs))
@@ -0,0 +1,372 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ NetProtocol: dependency-free binary messaging over TCP (QtNetwork) for real-time image exchange.
4
+ Wire format of one message (wire.py, pure Python - also used by the Qt-free server):
5
+ b'SMG1' | uint32 header length | uint32 payload length | header (UTF-8 JSON object) | payload (bytes)
6
+ (all integers big-endian). Images travel as encoded bytes (PNG / JPEG) in the payload, never as base64.
7
+ Messages larger than the limits, or a wrong magic, close the connection: a hostile or confused peer cannot make
8
+ the application allocate unbounded memory.
9
+ Classes:
10
+ - FrameChannel : one connection (client side, or a server-side peer), send(header, payload) and
11
+ messageReceived(header, payload).
12
+ - FrameServer : listens and creates a FrameChannel per incoming connection.
13
+ """
14
+ from ManyQt.QtCore import QObject, QBuffer, QByteArray, QIODevice, pyqtSignal, pyqtSlot, pyqtProperty
15
+ from ManyQt.QtNetwork import QTcpServer, QTcpSocket, QHostAddress, QAbstractSocket
16
+ from ManyQt.QtGui import QImage
17
+ from os.path import dirname
18
+ from sys import path
19
+
20
+ if not __package__ and dirname(__file__) not in path:
21
+ path.append(dirname(__file__))
22
+
23
+ try: # The wire format itself is pure Python (shared with the Qt-free server).
24
+ from .wire import MAGIC, PREFIX_SIZE, MAX_HEADER, MAX_PAYLOAD, RAWZ_MAGIC, RAWG_MAGIC, DEFAULT_PORT, packMessage, \
25
+ MessageParser, packRaw, unpackRaw
26
+ except:
27
+ from wire import MAGIC, PREFIX_SIZE, MAX_HEADER, MAX_PAYLOAD, RAWZ_MAGIC, RAWG_MAGIC, DEFAULT_PORT, packMessage, \
28
+ MessageParser, packRaw, unpackRaw
29
+
30
+ def encodeImage(image, fmt='PNG', quality=-1):
31
+ """
32
+ :param image: QImage
33
+ :param fmt: (str | unicode | QString) 'PNG' (lossless), 'JPG' or 'RAWZ' (lossless and several times faster
34
+ than PNG: raw RGB + fast zlib; exact colors, unlike JPEG's chroma sub-sampling).
35
+ :param quality: (int) 0 .. 100 for JPEG, -1 = default.
36
+ :return: bytes
37
+ """
38
+ if u'{}'.format(fmt).upper() == 'RAWZ':
39
+ img = image.convertToFormat(QImage.Format_RGB888) # type: QImage
40
+ w, h, bpl = img.width(), img.height(), img.bytesPerLine() # type: int, int, int
41
+ ptr = img.constBits()
42
+ n = img.sizeInBytes() if hasattr(img, 'sizeInBytes') else img.byteCount() # type: int
43
+ if hasattr(ptr, 'setsize'):
44
+ ptr.setsize(n)
45
+ raw = bytes(ptr) # type: bytes
46
+ rows = raw if bpl == w * 3 else b''.join(raw[y * bpl:y * bpl + w * 3] for y in range(h)) # type: bytes
47
+ return packRaw(w, h, rows)
48
+ data = QByteArray() # type: QByteArray
49
+ buf = QBuffer(data) # type: QBuffer
50
+ buf.open(QIODevice.WriteOnly)
51
+ image.save(buf, u'{}'.format(fmt).upper(), int(quality))
52
+ buf.close()
53
+ return bytes(data.data())
54
+
55
+
56
+ def decodeImage(data):
57
+ """
58
+ :param data: (bytes) RAWZ / RAWG, PNG or JPEG bytes.
59
+ :return: (QImage) Null image on failure.
60
+ """
61
+ image = QImage() # type: QImage
62
+ if data and bytes(data[:4]) in (RAWZ_MAGIC, RAWG_MAGIC): # lossless raw colour / grayscale (bounded zlib)
63
+ raw = unpackRaw(data)
64
+ if raw is None:
65
+ return image
66
+ w, h, channels, rows = raw
67
+ fmt = QImage.Format_Grayscale8 if channels == 1 else QImage.Format_RGB888
68
+ return QImage(rows, w, h, w * channels, fmt).copy()
69
+ if data:
70
+ image.loadFromData(QByteArray(bytes(data)))
71
+ return image
72
+
73
+
74
+ def hostAddress(host):
75
+ """
76
+ :param host: (str | unicode | QString) IP, 'localhost', '0.0.0.0' (all IPv4) or '::' (all).
77
+ :return: QHostAddress
78
+ """
79
+ host = u'{}'.format(host).strip() # type: str
80
+ special = {'': QHostAddress.LocalHost, 'localhost': QHostAddress.LocalHost, '0.0.0.0': QHostAddress.AnyIPv4,
81
+ '::': QHostAddress.Any, '*': QHostAddress.Any} # type: dict
82
+ return QHostAddress(special[host]) if host in special else QHostAddress(host)
83
+
84
+
85
+ class FrameChannel(QObject):
86
+ """
87
+ FrameChannel class: one framed-message connection.
88
+ """
89
+ messageReceived = pyqtSignal(object, object) # type: pyqtSignal # (dict header, bytes payload)
90
+ connected = pyqtSignal() # type: pyqtSignal
91
+ disconnected = pyqtSignal() # type: pyqtSignal
92
+ errorOccurred = pyqtSignal('QString') # type: pyqtSignal
93
+
94
+ def __init__(self, *args, **kwargs):
95
+ """
96
+ :param socket: (QTcpSocket | None) Existing connected socket (server side); None = client channel.
97
+ :param messageReceived: callable | None
98
+ :param connected: callable | None
99
+ :param disconnected: callable | None
100
+ :param errorOccurred: callable | None
101
+ :param args: any
102
+ :param kwargs: any
103
+ """
104
+ socket = kwargs.pop('socket', None) # type: QTcpSocket | None
105
+ messageReceived = kwargs.pop('messageReceived', None) # type: callable | None
106
+ connected = kwargs.pop('connected', None) # type: callable | None
107
+ disconnected = kwargs.pop('disconnected', None) # type: callable | None
108
+ errorOccurred = kwargs.pop('errorOccurred', None) # type: callable | None
109
+ super(FrameChannel, self).__init__(*args, **kwargs)
110
+ for signal, slot in ((self.messageReceived, messageReceived), (self.connected, connected),
111
+ (self.disconnected, disconnected), (self.errorOccurred, errorOccurred)):
112
+ if callable(slot):
113
+ signal.connect(slot)
114
+ self.__m_parser = MessageParser() # type: MessageParser
115
+ self.__m_bytesSent = 0 # type: int
116
+ self.__m_bytesReceived = 0 # type: int
117
+ self.__m_socket = socket if socket is not None else QTcpSocket(self) # type: QTcpSocket
118
+ self.__m_socket.setParent(self)
119
+ self.__m_socket.readyRead.connect(self._onReadyRead)
120
+ self.__m_socket.connected.connect(self._onConnected)
121
+ self.__m_socket.disconnected.connect(self._onDisconnected)
122
+ if hasattr(self.__m_socket, 'errorOccurred'):
123
+ self.__m_socket.errorOccurred.connect(self._onError)
124
+ else:
125
+ self.__m_socket.error.connect(self._onError)
126
+ if self.isConnected():
127
+ self.__m_socket.setSocketOption(QAbstractSocket.LowDelayOption, 1)
128
+
129
+ # ---------- Helpers ----------
130
+ @pyqtSlot()
131
+ def _onReadyRead(self):
132
+ """
133
+ :return:
134
+ """
135
+ data = self.__m_socket.readAll() # type: QByteArray
136
+ data = bytes(data.data()) # type: bytes
137
+ self.__m_bytesReceived += len(data)
138
+ try:
139
+ messages = self.__m_parser.feed(data) # type: list
140
+ except Exception as e:
141
+ self.errorOccurred.emit('Protocol error from {}: {}'.format(self.getPeer(), e))
142
+ self.__m_socket.abort()
143
+ return
144
+ for header, payload in messages:
145
+ self.messageReceived.emit(header, payload)
146
+
147
+ @pyqtSlot()
148
+ def _onConnected(self):
149
+ """
150
+ :return:
151
+ """
152
+ self.__m_socket.setSocketOption(QAbstractSocket.LowDelayOption, 1) # TCP_NODELAY: low latency.
153
+ self.connected.emit()
154
+
155
+ @pyqtSlot()
156
+ def _onDisconnected(self):
157
+ """
158
+ :return:
159
+ """
160
+ self.__m_parser = MessageParser() # type: MessageParser
161
+ self.disconnected.emit()
162
+
163
+ def _onError(self, *args):
164
+ """
165
+ :param args: QAbstractSocket.SocketError
166
+ :return:
167
+ """
168
+ if self.__m_socket.error() != QAbstractSocket.RemoteHostClosedError:
169
+ self.errorOccurred.emit(u'{}'.format(self.__m_socket.errorString()))
170
+
171
+ # ---------- Public API ----------
172
+ @pyqtSlot('QString', int)
173
+ @pyqtSlot(str, int)
174
+ def connectToHost(self, host, port):
175
+ """
176
+ :param host: str | unicode | QString
177
+ :param port: int
178
+ :return:
179
+ """
180
+ self.__m_parser = MessageParser() # type: MessageParser
181
+ self.__m_socket.abort()
182
+ self.__m_socket.connectToHost(u'{}'.format(host), int(port))
183
+
184
+ @pyqtSlot()
185
+ def close(self):
186
+ """
187
+ :return:
188
+ """
189
+ self.__m_socket.disconnectFromHost()
190
+
191
+ def abort(self):
192
+ """
193
+ Close immediately, dropping unsent data.
194
+ :return:
195
+ """
196
+ self.__m_socket.abort()
197
+
198
+ def send(self, header, payload=b''):
199
+ """
200
+ :param header: (dict) JSON-serialisable header.
201
+ :param payload: (bytes) Binary payload.
202
+ :return: (bool) Queued for sending.
203
+ """
204
+ if not self.isConnected():
205
+ return False
206
+ try:
207
+ data = packMessage(header, payload) # type: bytes
208
+ except Exception as e:
209
+ self.errorOccurred.emit('Cannot send message: {}'.format(e))
210
+ return False
211
+ self.__m_socket.write(QByteArray(data))
212
+ self.__m_bytesSent += len(data)
213
+ return True
214
+
215
+ def isConnected(self):
216
+ """
217
+ :return: bool
218
+ """
219
+ return self.__m_socket.state() == QAbstractSocket.ConnectedState
220
+
221
+ def getState(self):
222
+ """
223
+ :return: (str | unicode | QString) 'disconnected', 'connecting' or 'connected'.
224
+ """
225
+ state = self.__m_socket.state()
226
+ if state == QAbstractSocket.ConnectedState:
227
+ return 'connected'
228
+ if state in (QAbstractSocket.HostLookupState, QAbstractSocket.ConnectingState):
229
+ return 'connecting'
230
+ return 'disconnected'
231
+
232
+ def getPeer(self):
233
+ """
234
+ :return: (str | unicode | QString) 'address:port' of the other side.
235
+ """
236
+ return '{}:{}'.format(self.__m_socket.peerAddress().toString(), self.__m_socket.peerPort())
237
+
238
+ def getBytesToWrite(self):
239
+ """
240
+ :return: (int) Bytes queued but not yet sent (backpressure indicator).
241
+ """
242
+ return int(self.__m_socket.bytesToWrite())
243
+
244
+ def getBytesSent(self):
245
+ """
246
+ :return: int
247
+ """
248
+ return self.__m_bytesSent
249
+
250
+ def getBytesReceived(self):
251
+ """
252
+ :return: int
253
+ """
254
+ return self.__m_bytesReceived
255
+
256
+ # ---------- Properties ----------
257
+ bytesSent = pyqtProperty(int, fget=getBytesSent) # type: pyqtProperty
258
+ bytesReceived = pyqtProperty(int, fget=getBytesReceived) # type: pyqtProperty
259
+
260
+
261
+ class FrameServer(QObject):
262
+ """
263
+ FrameServer class: accepts connections and wraps each one in a FrameChannel.
264
+ """
265
+ channelOpened = pyqtSignal(object) # type: pyqtSignal # FrameChannel
266
+ channelClosed = pyqtSignal(object) # type: pyqtSignal # FrameChannel
267
+
268
+ def __init__(self, *args, **kwargs):
269
+ """
270
+ :param maxChannels: (int) Further connections are refused.
271
+ :param channelOpened: callable | None
272
+ :param channelClosed: callable | None
273
+ :param args: any
274
+ :param kwargs: any
275
+ """
276
+ maxChannels = kwargs.pop('maxChannels', 8) # type: int
277
+ channelOpened = kwargs.pop('channelOpened', None) # type: callable | None
278
+ channelClosed = kwargs.pop('channelClosed', None) # type: callable | None
279
+ super(FrameServer, self).__init__(*args, **kwargs)
280
+ if callable(channelOpened):
281
+ self.channelOpened.connect(channelOpened)
282
+ if callable(channelClosed):
283
+ self.channelClosed.connect(channelClosed)
284
+ self.__m_maxChannels = max(1, int(maxChannels)) # type: int
285
+ self.__m_channels = [] # type: list[FrameChannel]
286
+ self.__m_server = QTcpServer(self) # type: QTcpServer
287
+ self.__m_server.newConnection.connect(self._onNewConnection)
288
+
289
+ # ---------- Helpers ----------
290
+ @pyqtSlot()
291
+ def _onNewConnection(self):
292
+ """
293
+ :return:
294
+ """
295
+ while self.__m_server.hasPendingConnections():
296
+ socket = self.__m_server.nextPendingConnection() # type: QTcpSocket
297
+ if len(self.__m_channels) >= self.__m_maxChannels:
298
+ socket.abort()
299
+ continue
300
+ channel = FrameChannel(socket=socket, parent=self) # type: FrameChannel
301
+ channel.disconnected.connect(lambda ch=channel: self._onClosed(ch))
302
+ self.__m_channels.append(channel)
303
+ self.channelOpened.emit(channel)
304
+
305
+ def _onClosed(self, channel):
306
+ """
307
+ :param channel: FrameChannel
308
+ :return:
309
+ """
310
+ if channel in self.__m_channels:
311
+ self.__m_channels.remove(channel)
312
+ self.channelClosed.emit(channel)
313
+ channel.deleteLater()
314
+
315
+ # ---------- Public API ----------
316
+ def listen(self, host='127.0.0.1', port=DEFAULT_PORT):
317
+ """
318
+ :param host: (str | unicode | QString) '127.0.0.1' = this computer only, '0.0.0.0' = the network.
319
+ :param port: (int) 0 = any free port (see getPort()).
320
+ :return: bool
321
+ """
322
+ return bool(self.__m_server.listen(hostAddress(host), int(port)))
323
+
324
+ @pyqtSlot()
325
+ def close(self):
326
+ """
327
+ :return:
328
+ """
329
+ self.__m_server.close()
330
+ for channel in list(self.__m_channels):
331
+ channel.abort()
332
+
333
+ def isListening(self):
334
+ """
335
+ :return: bool
336
+ """
337
+ return self.__m_server.isListening()
338
+
339
+ def getPort(self):
340
+ """
341
+ :return: int
342
+ """
343
+ return int(self.__m_server.serverPort())
344
+
345
+ def getErrorString(self):
346
+ """
347
+ :return: str | unicode | QString
348
+ """
349
+ return u'{}'.format(self.__m_server.errorString())
350
+
351
+ def getChannels(self):
352
+ """
353
+ :return: list[FrameChannel]
354
+ """
355
+ return list(self.__m_channels)
356
+
357
+ def getMaxChannels(self):
358
+ """
359
+ :return: int
360
+ """
361
+ return self.__m_maxChannels
362
+
363
+ @pyqtSlot(int)
364
+ def setMaxChannels(self, maxChannels):
365
+ """
366
+ :param maxChannels: int
367
+ :return:
368
+ """
369
+ self.__m_maxChannels = max(1, int(maxChannels)) # type: int
370
+
371
+ # ---------- Properties ----------
372
+ maxChannels = pyqtProperty(int, fget=getMaxChannels, fset=setMaxChannels) # type: pyqtProperty
@@ -0,0 +1,189 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Wire format of ScreenMagnifier messages - pure Python (no Qt): shared by the Qt client (netprotocol.FrameChannel)
4
+ and the headless server, which also runs where Qt is not available (e.g. Android: Termux, Pydroid).
5
+ One message:
6
+ b'SMG1' | uint32 header length | uint32 payload length | header (UTF-8 JSON object) | payload (bytes)
7
+ (integers big-endian). Images travel in the payload as:
8
+ RAWZ b'RAWZ' | uint32 w | uint32 h | zlib(RGB888 rows) lossless color, only needs zlib
9
+ RAWG b'RAWG' | uint32 w | uint32 h | zlib(gray8 rows) lossless grayscale (label masks)
10
+ PNG / JPEG when OpenCV or Pillow is installed
11
+ Limits protect against hostile peers: header / payload sizes, image sizes, and the zlib expansion of raw images
12
+ (a small payload cannot inflate into gigabytes).
13
+ """
14
+ from zlib import compress, decompressobj
15
+ from struct import pack, unpack
16
+ from json import dumps, loads
17
+
18
+ MAGIC = b'SMG1' # type: bytes
19
+ PREFIX_SIZE = 12 # type: int
20
+ MAX_HEADER = 1 << 20 # type: int # 1 MB of JSON.
21
+ MAX_PAYLOAD = 64 << 20 # type: int # 64 MB image.
22
+ RAWZ_MAGIC = b'RAWZ' # type: bytes
23
+ RAWG_MAGIC = b'RAWG' # type: bytes
24
+ MAX_RAW_PIXELS = 4096 * 4096 # type: int # The largest raw image accepted.
25
+ DEFAULT_PORT = 8765 # type: int
26
+
27
+ try:
28
+ from numpy import ascontiguousarray, frombuffer, uint8, asarray
29
+
30
+ numpyExists = True # type: bool
31
+ except:
32
+ numpyExists = None # type: bool
33
+ try:
34
+ from cv2 import IMWRITE_JPEG_QUALITY, imencode, imdecode, IMREAD_COLOR
35
+
36
+ cv2exists = True # type: bool
37
+ except:
38
+ cv2exists = False # type: bool
39
+ try:
40
+ from PIL.Image import fromarray, open
41
+
42
+ PILImageExists = True # type: bool
43
+ except:
44
+ PILImageExists = False # type: bool
45
+
46
+
47
+ def packMessage(header, payload=b''):
48
+ """
49
+ :param header: (dict) JSON-serialisable message header (must contain 'type').
50
+ :param payload: (bytes) Binary payload.
51
+ :return: bytes
52
+ """
53
+ head = dumps(header, separators=(',', ':')).encode('utf-8') # type: bytes
54
+ payload = bytes(payload or b'') # type: bytes
55
+ if len(head) > MAX_HEADER or len(payload) > MAX_PAYLOAD:
56
+ raise ValueError(u'Message too large ({} + {} bytes)'.format(len(head), len(payload)))
57
+ return MAGIC + pack('>II', len(head), len(payload)) + head + payload
58
+
59
+
60
+ class MessageParser(object):
61
+ """
62
+ MessageParser class: incremental decoder for a TCP byte stream.
63
+ """
64
+
65
+ def __init__(self):
66
+ """
67
+ """
68
+ self.__m_buffer = bytearray() # type: bytearray
69
+
70
+ def feed(self, data):
71
+ """
72
+ :param data: (bytes) Newly received bytes.
73
+ :return: (list[tuple[dict, bytes]]) Complete messages.
74
+ :raise ValueError: on a protocol violation (the connection should be closed).
75
+ """
76
+ self.__m_buffer.extend(data)
77
+ out = [] # type: list
78
+ while len(self.__m_buffer) >= PREFIX_SIZE:
79
+ if bytes(self.__m_buffer[:4]) != MAGIC:
80
+ raise ValueError(u'Bad magic: not a ScreenMagnifier peer')
81
+ headLen, payloadLen = unpack('>II', bytes(self.__m_buffer[4:PREFIX_SIZE]))
82
+ if headLen > MAX_HEADER or payloadLen > MAX_PAYLOAD:
83
+ raise ValueError(u'Message too large ({} + {} bytes)'.format(headLen, payloadLen))
84
+ total = PREFIX_SIZE + headLen + payloadLen # type: int
85
+ if len(self.__m_buffer) < total:
86
+ break
87
+ head = bytes(self.__m_buffer[PREFIX_SIZE:PREFIX_SIZE + headLen]) # type: bytes
88
+ payload = bytes(self.__m_buffer[PREFIX_SIZE + headLen:total]) # type: bytes
89
+ del self.__m_buffer[:total]
90
+ header = loads(head.decode('utf-8')) # type: dict
91
+ if not isinstance(header, dict):
92
+ raise ValueError(u'Header is not a JSON object')
93
+ out.append((header, payload))
94
+ return out
95
+
96
+ def pending(self):
97
+ """
98
+ :return: (int) Buffered bytes of an incomplete message.
99
+ """
100
+ return len(self.__m_buffer)
101
+
102
+
103
+ def packRaw(width, height, rows, gray=False):
104
+ """
105
+ :param width: int
106
+ :param height: int
107
+ :param rows: (bytes) Tightly packed RGB888 (or gray8) rows.
108
+ :param gray: bool
109
+ :return: (bytes) RAWZ / RAWG image.
110
+ """
111
+ return (RAWG_MAGIC if gray else RAWZ_MAGIC) + pack('>II', int(width), int(height)) + compress(bytes(rows), 1)
112
+
113
+
114
+ def unpackRaw(data):
115
+ """
116
+ :param data: bytes
117
+ :return: (tuple[int, int, int, bytes] | None) width, height, channels (3 or 1), rows - None if not a valid
118
+ raw image (wrong magic, size limits, corrupt or over-long zlib data).
119
+ """
120
+ if not data or len(data) < 12 or bytes(data[:4]) not in (RAWZ_MAGIC, RAWG_MAGIC):
121
+ return None
122
+ channels = 1 if bytes(data[:4]) == RAWG_MAGIC else 3 # type: int
123
+ w, h = unpack('>II', bytes(data[4:12]))
124
+ if not (0 < w <= 16384 and 0 < h <= 16384 and w * h <= MAX_RAW_PIXELS):
125
+ return None
126
+ expected = w * h * channels # type: int
127
+ try:
128
+ z = decompressobj()
129
+ rows = z.decompress(bytes(data[12:]), expected + 1) # type: bytes # bounded: no zlib bomb
130
+ except:
131
+ return None
132
+ return (w, h, channels, rows) if len(rows) == expected else None
133
+
134
+
135
+ def availableFormats():
136
+ """
137
+ :return: (list[str | unicode | QString]) Image formats this process can decode and encode ('RAWZ' always).
138
+ """
139
+ return ['RAWZ', 'PNG', 'JPG'] if (cv2exists or PILImageExists) and numpyExists else ['RAWZ']
140
+
141
+
142
+ def encodeArray(arr, fmt='RAWZ', quality=90):
143
+ """
144
+ :param arr: (ndarray) (H, W, 3) RGB or (H, W) gray uint8.
145
+ :param fmt: (str | unicode | QString)
146
+ 'RAWZ' (gray arrays: RAWG), 'PNG' or 'JPG' - falls back to RAWZ when no codec is installed.
147
+ :param quality: (int) JPEG quality.
148
+ :return: (tuple[bytes, str]) Encoded image and the format actually used.
149
+ """
150
+ arr = ascontiguousarray(arr)
151
+ gray = arr.ndim == 2 # type: bool
152
+ fmt = u'{}'.format(fmt).upper() # type: str
153
+ if fmt in ('PNG', 'JPG', 'JPEG') and cv2exists:
154
+ ext = '.png' if fmt == 'PNG' else '.jpg' # type: str
155
+ params = [int(IMWRITE_JPEG_QUALITY), int(quality)] if ext == '.jpg' else [] # type: list
156
+ ok, buf = imencode(ext, arr if gray else arr[..., ::-1], params)
157
+ if ok:
158
+ return buf.tobytes(), 'PNG' if ext == '.png' else 'JPG'
159
+ if fmt in ('PNG', 'JPG', 'JPEG') and PILImageExists:
160
+ from io import BytesIO
161
+ out = BytesIO()
162
+ fromarray(arr).save(out, 'PNG' if fmt == 'PNG' else 'JPEG', quality=int(quality))
163
+ return out.getvalue(), 'PNG' if fmt == 'PNG' else 'JPG'
164
+ h, w = arr.shape[:2]
165
+ return packRaw(w, h, arr.tobytes(), gray), 'RAWZ'
166
+
167
+
168
+ def decodeArray(data):
169
+ """
170
+ :param data: (bytes) RAWZ / RAWG, or PNG / JPEG (with OpenCV or Pillow).
171
+ :return: (ndarray | None) (H, W, 3) RGB or (H, W) gray uint8, None on failure.
172
+ """
173
+ raw = unpackRaw(data)
174
+ if raw is not None:
175
+ w, h, channels, rows = raw
176
+ arr = frombuffer(rows, uint8)
177
+ return (arr.reshape(h, w) if channels == 1 else arr.reshape(h, w, 3)).copy()
178
+ if not data or bytes(data[:4]) in (RAWZ_MAGIC, RAWG_MAGIC):
179
+ return None
180
+ if cv2exists:
181
+ img = imdecode(frombuffer(bytes(data), uint8), IMREAD_COLOR)
182
+ return None if img is None else ascontiguousarray(img[..., ::-1])
183
+ if PILImageExists:
184
+ from io import BytesIO
185
+ try:
186
+ return asarray(open(BytesIO(bytes(data))).convert('RGB')).copy()
187
+ except:
188
+ return None
189
+ return None
@@ -0,0 +1,16 @@
1
+ # coding=utf-8
2
+ """
3
+ regionselector package.
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 .regionselector import RegionSelector
13
+ except:
14
+ from regionselector import RegionSelector
15
+
16
+ __all__ = ['RegionSelector'] # type: list[str]
@@ -0,0 +1,23 @@
1
+ # coding=utf-8
2
+ """
3
+ Entry point for the RegionSelector 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_())