forked from Kauhsa/padmiss-daemon
/
gui.py
334 lines (271 loc) · 10.9 KB
/
gui.py
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
"""
Padmiss daemon, GUI version.
Initial code from https://evileg.com/en/post/68/.
"""
import io
import logging, logging.handlers
import os
import queue
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QSystemTrayIcon, QMenu, QAction, QStyle, qApp, QFileDialog, QMessageBox
from PyQt5.QtCore import QThread, pyqtSignal, Qt
from PyQt5 import uic
from config import PadmissConfigManager, PadmissConfig, ScannerConfig, DeviceConfig
from hid import listDevices
from daemon import PadmissDaemon
from thread_utils import start_and_wait_for_threads
log = logging.getLogger(__name__)
# from https://stackoverflow.com/a/51061279
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
#
# Threads
#
class LogThread(QThread):
log_event = pyqtSignal('PyQt_PyObject')
threadactive = False
log_queue = None
def __init__(self):
QThread.__init__(self)
self.log_queue = queue.Queue()
queue_handler = logging.handlers.QueueHandler(self.log_queue)
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
logger.addHandler(queue_handler)
def run(self):
formatter = logging.Formatter('%(asctime)s - %(threadName)s - %(levelname)s: %(message)s')
while True:
try:
log_record = self.log_queue.get(block=True, timeout=1)
log_string = formatter.format(log_record)
self.log_event.emit(log_string)
except queue.Empty:
pass # no logs? it's ok. maybe next time.
class PadmissThread(QThread):
def run(self):
try:
start_and_wait_for_threads([PadmissDaemon()], lambda: self.isInterruptionRequested())
except:
log.exception("Exception on Padmiss daemon")
#
# Windows & Widgets
#
Ui_MainWindow, MainWindowBaseClass = uic.loadUiType(resource_path('main-window.ui'))
Ui_ConfigWindow, ConfigWindowBaseClass = uic.loadUiType(resource_path('config-window.ui'))
Ui_DeviceConfigWidget, DeviceConfigWidgetBaseClass = uic.loadUiType(resource_path('device-config-widget.ui'))
Ui_ScannerConfigWidget, ScannerConfigWidgetBaseClass = uic.loadUiType(resource_path('scanner-config-widget.ui'))
class ScannerConfigWidget(Ui_ScannerConfigWidget, ScannerConfigWidgetBaseClass):
def __init__(self, scanner: ScannerConfig):
ScannerConfigWidgetBaseClass.__init__(self)
Ui_ConfigWindow.__init__(self)
self.setupUi(self)
# setup
self.idVendor.setText(scanner.id_vendor)
self.idProduct.setText(scanner.id_product)
self.portNumber.setText(str(scanner.port_number) if scanner.port_number is not None else "")
self.bus.setText(str(scanner.bus) if scanner.bus is not None else "")
self.pickDeviceButton.clicked.connect(self.findScanner)
def getConfig(self):
return ScannerConfig(
id_vendor=self.idVendor.text(),
id_product=self.idProduct.text(),
port_number=int(self.portNumber.text()) if self.portNumber.text() else None,
bus=int(self.bus.text()) if self.bus.text() else None
)
def findScanner(self):
reply = QMessageBox.information(self, 'Padmiss', 'Make sure the device is disconnected')
devices = listDevices()
reply = QMessageBox.information(self, 'Padmiss', 'Plug the device in, and wait 5 seconds')
newDevices = listDevices()
new = [x for x in newDevices if x not in devices]
if not new:
reply = QMessageBox.information(self, 'Padmiss', 'Device not found')
else:
device = new[0]
self.idVendor.setText(device['idVendor'])
self.idProduct.setText(device['idProduct'])
self.portNumber.setText(str(device['port_number']))
self.bus.setText(str(device['bus']))
class DeviceConfigWidget(Ui_DeviceConfigWidget, DeviceConfigWidgetBaseClass):
def __init__(self, device: DeviceConfig):
ScannerConfigWidgetBaseClass.__init__(self)
Ui_ConfigWindow.__init__(self)
self.setupUi(self)
self.device = device
self.path.setText(device.path)
self.browsePath.clicked.connect(self.pickBackupDir)
self.configWidget = None
if device.type == 'scanner':
self.configWidget = ScannerConfigWidget(device.config)
self.deviceSpecificContent.addWidget(self.configWidget)
self.tabCloseRequested.connect(self.closeTab)
def getConfig(self):
if self.device.type == 'scanner':
return DeviceConfig(
type = 'scanner', # todo
path = self.path.text(),
config = self.configWidget.getConfig()
)
return None
def pickBackupDir(self):
folder = str(QFileDialog.getExistingDirectory(self, "Select profile directory"))
if folder:
self.path.setText(folder)
class ConfigWindow(Ui_ConfigWindow, ConfigWindowBaseClass):
configManager = None
callBack = None
config = None
# Override the class constructor
def __init__(self):
ConfigWindowBaseClass.__init__(self)
Ui_ConfigWindow.__init__(self)
self.setupUi(self)
self.configManager = PadmissConfigManager()
# Init buttons
self.backup_dir_browse.clicked.connect(self.pickBackupDir)
self.scores_dir_browse.clicked.connect(self.pickScoresDir)
self.save.clicked.connect(self.saveAndClose)
self.newScannerButton.clicked.connect(self.newScanner)
def showEvent(self, event):
if self.configManager.hasValidConfig():
config = self.configManager.load_config()
else:
config = self.configManager._get_default_config()
# Load current config values
self.padmiss_api_url.setText(config.padmiss_api_url)
self.api_key.setText(config.api_key)
self.profile_dir_name.setText(config.profile_dir_name)
self.backup_dir.setText(config.backup_dir)
self.scores_dir.setText(config.scores_dir)
self.deviceTabs.clear()
for i, device in enumerate(config.devices):
self.deviceTabs.addTab(DeviceConfigWidget(device), str(i + 1))
def pickBackupDir(self):
folder = str(QFileDialog.getExistingDirectory(self, "Select Directory"))
if folder:
self.backup_dir.setText(folder)
def pickScoresDir(self):
folder = str(QFileDialog.getExistingDirectory(self, "Select Directory"))
if folder:
self.scores_dir.setText(folder)
def saveAndClose(self):
config = PadmissConfig(
padmiss_api_url=self.padmiss_api_url.text(),
api_key=self.api_key.text(),
scores_dir=self.scores_dir.text(),
backup_dir=self.backup_dir.text(),
profile_dir_name=self.profile_dir_name.text(),
devices=[self.deviceTabs.widget(index).getConfig() for index in range(self.deviceTabs.count())]
)
self.configManager.save_config(config)
self.close()
#def closeEvent(self, event):
# if self.callBack != None:
# if not self.configManager.hasValidConfig():
# event.ignore()
# else:
# self.callBack()
# self.callBack = None
#def quitEvent(self, event):
#if self.callBack != None:
# if not self.configManager.hasValidConfig():
# event.ignore()
# else:
# self.callBack()
# self.callBack = None
def newScanner(self):
empty = DeviceConfig(
type = 'scanner',
path = '',
config = ScannerConfig(
id_vendor = '',
id_product = ''
)
)
self.deviceTabs.addTab(DeviceConfigWidget(empty), str(len(self.deviceTabs) + 1))
class MainWindow(Ui_MainWindow, MainWindowBaseClass):
trayIcon = None
logThread = None
padmissThread = None
configWindow = None
configManager = None
# Override the class constructor
def __init__(self):
MainWindowBaseClass.__init__(self)
Ui_MainWindow.__init__(self)
self.setupUi(self)
# Init log thread
self.logThread = LogThread()
self.logThread.log_event.connect(self.newLogEvent)
self.logThread.start()
# Init tray icon
self.trayIcon = QSystemTrayIcon(self)
self.trayIcon.setIcon(self.style().standardIcon(QStyle.SP_ComputerIcon))
self.trayIcon.activated.connect(self.show)
show_action = QAction("Settings...", self)
quit_action = QAction("Quit", self)
show_action.triggered.connect(self.show)
quit_action.triggered.connect(self.quitEvent)
tray_menu = QMenu()
tray_menu.addAction(show_action)
tray_menu.addAction(quit_action)
self.trayIcon.setContextMenu(tray_menu)
self.trayIcon.show()
# Init padmiss thread
self.padmissThread = PadmissThread()
self.padmissThread.finished.connect(self.padmissDaemonFinished)
self.startStopButton.clicked.connect(self.togglePadmissThread)
# Init config window
self.configWindow = ConfigWindow()
self.configureButton.clicked.connect(self.openConfigWindow)
# Done!
log.info("Window initialized")
def padmissDaemonFinished(self):
self.startStopButton.setDisabled(False)
self.startStopButton.setText('Start')
def togglePadmissThread(self):
if self.padmissThread.isRunning():
self.startStopButton.setDisabled(True)
self.startStopButton.setText('Stopping...')
self.padmissThread.requestInterruption()
else:
self.startStopButton.setText('Stop')
self.padmissThread.start()
def newLogEvent(self, data):
self.logView.appendPlainText(data)
# Override closeEvent, to intercept the window closing event
def closeEvent(self, event):
event.ignore()
self.hide()
def openConfigWindow(self):
self.configWindow.show()
def quitEvent(self, event):
self.trayIcon.hide()
self.padmissThread.finished.connect(qApp.quit)
if self.padmissThread.isRunning():
self.padmissThread.requestInterruption()
# will quit upon thread stopping
else:
qApp.quit()
def attemptShow(self):
self.configManager = PadmissConfigManager()
def callBack():
self.attemptShow()
if not self.configManager.hasValidConfig():
self.configWindow.callBack = callBack
self.openConfigWindow()
else:
# Start daemon
self.togglePadmissThread()
self.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
mw = MainWindow()
mw.attemptShow()
sys.exit(app.exec())