- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy paththreaded_ui.py
More file actions
Latest commit
277 lines (250 loc) · 12.6 KB
/
Copy paththreaded_ui.py
File metadata and controls
277 lines (250 loc) · 12.6 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
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
__author__='МакаровАС'
fromqtpyimportQtCore, QtGui, uic, QtWidgets
importsys, queue, pythoncom, types, pathlib, win32con, win32gui
importwin32process, signal
import__main__
DEBUG=False
print_def=lambda*args: notDEBUGorprint(*args, file=sys.__stdout__)
#QtUtils
#https://bitbucket.org/philipstarkey/qtutils
classCaller(QtCore.QObject):
"""An event handler which calls the function held within a CallEvent."""
defevent(self, event):
event.accept()
exception=None
try:
result=event.fn(*event.args, **event.kwargs)
exceptException:
# Store for re-raising the exception in the calling thread:
exception=sys.exc_info()
result=None
ifevent._exceptions_in_main:
# Or, if nobody is listening for this exception,
# better raise it here so it doesn't pass
# silently:
raise
finally:
event._returnval.put([result,exception])
returnTrue
caller=Caller()
definmain(fn, *args, **kwargs):
classCallEvent(QtCore.QEvent):
"""An event containing a request for a function call."""
EVENT_TYPE=QtCore.QEvent.Type(QtCore.QEvent.registerEventType())
def__init__(self, queue, exceptions_in_main, fn, *args, **kwargs):
QtCore.QEvent.__init__(self, self.EVENT_TYPE)
self.fn=fn
self.args=args
self.kwargs=kwargs
self._returnval=queue
# Whether to raise exceptions in the main thread or store them
# for raising in the calling thread:
self._exceptions_in_main=exceptions_in_main
defin_main_later(fn, exceptions_in_main, *args, **kwargs):
"""Asks the mainloop to call a function when it has time. Immediately
returns the queue that was sent to the mainloop. A call to queue.get()
will return a list of [result,exception] where exception=[type,value,traceback]
of the exception. Functions are guaranteed to be called in the order
they were requested."""
q=queue.Queue()
QtCore.QCoreApplication.postEvent(caller, CallEvent(q, exceptions_in_main, fn, *args, **kwargs))
returnq
defget_inmain_result(queue):
result,exception=queue.get()
ifexceptionisnotNone:
type, value, traceback=exception
raisevalue.with_traceback(traceback)
returnresult
returnfn(*args, **kwargs) ifisMainThread() elseget_inmain_result(in_main_later(fn,False,*args,**kwargs))
defbind(func, to):
"Bind function to instance, unbind if needed"
returntypes.MethodType(func.__func__ifhasattr(func, "__self__") elsefunc, to)
classprx():
"Proxies object, automatically calls methods in GUI thread"
GETATTR, CALL=range(2)
builtin=str, bool, int, type(None), complex, bytes, dict
def__init__(self, client, *args, atts={}, **kwargs):
self.__dict__['client'] =client
forkinatts:
self.__dict__[k] =atts[k]
defproxy(self, t, *args, **kwargs):
ift==self.GETATTR:
print_def("THD_UI GET:", self.client, self.client.__class__)
ret=getattr(self.client, args[0])
else:
ifhasattr(self.client, "__self__"):
_mod=self.client.__self__.__module__# FIXME: Qt4->5 "QtWidgets" necessary?
if_mod.endswith("QtGui") or_mod.endswith("QtWidgets"):
#Call QtGui stuff in main thread
print_def("THD_UI CALL IN MAIN:", self.client.__name__)
ret=inmain(self.client, *args, **kwargs)
else: #Call other stuff in the same thread, pass proxied /self/
print_def("THD_UI CALL:", self.client.__name__)
ret=bind(self.client, prx(self.client.__self__))(*args, **kwargs)
else: #Call unbound stuff
print_def("THD_UI CALL UNBOUND:", self.client.__name__)
ret=self.client(*args, **kwargs)
returnretiftype(ret) inself.builtinelseprx(ret) #if type(ret) != types.MethodType else ret
def__getattr__(self, name): returnself.proxy(self.GETATTR, name)
def__call__(self, *args, **kwargs): returnself.proxy(self.CALL, *args, **kwargs)
def__setattr__(self, name, value): returnsetattr(self.client, name, value)
def__str__(self): return"<Proxied %s>"%self.client
def__eq__(self, other): returnself.clientisother.client
classGenericWorker(QtCore.QObject):
finished=QtCore.Signal()
def__init__(self, func, *args, **kwargs):
classEventLoop(QtCore.QRunnable):
defrun(self_):
self.thread=QtCore.QThread.currentThread()
self.loop=QtCore.QEventLoop()
self.loop.exec()
self.finished.emit()
self.isFinished=True
classRunner(QtCore.QObject):
@QtCore.pyqtSlot(object, object, object)
defrun(self_, func, args, kwargs):
pythoncom.CoInitialize()
func(*args, **kwargs)
self.loop.quit()
super().__init__()
self.isFinished=False
QtCore.QThreadPool.globalInstance().start(EventLoop())
whilenotgetattr(self, "loop", None): pass#wait for thread to start
self.runner=Runner()
self.runner.moveToThread(self.thread) #move runner to QRunnable.run thread
ifargsandhasattr(args[0], "sender"): #if 1st arg has /sender/ assume it's Qt widget
args=list(args)
args[0] =prx(args[0], atts={"sender": lambdas=args[0].sender(): s})
invoke(self.runner.run, func, args, kwargs)
isRunning=lambdaself: notself.isFinished
classInvoker():
definvoke(self, member, *args, conn=QtCore.Qt.AutoConnection):
returnQtCore.QMetaObject.invokeMethod(member.__self__, member.__func__.__name__, \
conn, *map(lambda_: QtCore.Q_ARG(object, _), args))
wait=lambdaself, member, *args: self.invoke(member, *args, conn=QtCore.Qt.BlockingQueuedConnection)
invoker=Invoker()
defisMainThread():
ifnotQtCore.QCoreApplication.instance():
print_def("THD_UI ERROR (isMainThread): app instance is None!")
returnTrue
returnQtCore.QThread.currentThread() isQtCore.QCoreApplication.instance().thread()
defpyqtThreadedSlot(*args, **kwargs):
defthreaded_int(func):
@QtCore.pyqtSlot(*args, name=func.__name__, **kwargs)
defwrap_func(self, *args1, **kwargs1):
GenericWorker(func, self, *args1, **kwargs1)
returnwrap_func
returnthreaded_int
defmodule_path(cls):
"Get module folder path from class"
returnpathlib.Path(sys.modules[cls.__module__].__file__).absolute().parent
#Widget events are connected to appropriate defs - <widget>_<signal>()
#To catch terminated signal (QProcess.terminate) connect it manually
defWidgetFactory(Form, args, flags=QtCore.Qt.WindowType(), ui=None, stdout=None, before_init=None, ontop=False, kwargs={}):
classForm_(Form, object):
def__init__(self):
super(Form, self).__init__(flags=(QtCore.Qt.WindowStaysOnTopHintifontopelse0)|flags)
uic.loadUi(str(uiormodule_path(Form).joinpath(Form.__name__.lower()))+".ui", self)
ifstdout: redirect_stdout(getattr(self, stdout))
self.terminated=QtWidgets.qApp.terminated
ifbefore_init:
before_init(self)
self.autoConnectSignals()
if"__init__"inForm.__dict__:
super().__init__(*args, **kwargs)
defautoConnectSignals(self):
widgets, members=super(Form, self).__dict__, Form.__dict__
foriinwidgets:
formin [jforjinmembersifj.startswith(i+"_")]:
signal=getattr(widgets[i], m[len(i)+1:], None)
ifsignal: signal.connect(bind(members[m], self))
else: print("Signal '%s' of '%s' not found"% (m[len(i)+1:], i))
returnForm_()
classQtApp(QtWidgets.QApplication):
terminated=QtCore.Signal()
def__init__(self, Form, *args, flags=QtCore.Qt.WindowType(), ui=None, stdout=None, tray=None, hidden=False, ontop=False, **kwargs):
"Create new QApplication and specified window"
super().__init__(sys.argv)
try: win32gui.EnumWindows(self.findMsgDispatcher, self.applicationPid())
except: pass
global_app
_app=self
self.path=pathlib.Path(__main__.__file__).absolute().parent#Application path
self._tray=tray
self.form=WidgetFactory(Form, args, flags, ui, stdout, self.setupTrayIcon, ontop, kwargs)
ifnothidden:
self.form.show()
defsigint(*args): raiseKeyboardInterrupt
signal.signal(signal.SIGINT, sigint) #pass all KeyboardInterrupt to Python code
sys.exit(self.exec_())
deffindMsgDispatcher(self, hwnd, lParam):
iflParam==win32process.GetWindowThreadProcessId(hwnd)[1]:
ifwin32gui.GetClassName(hwnd
).startswith("QEventDispatcherWin32_Internal_Widget"):
self.msg_dispatcher=hwnd
returnFalse
defwinEventFilter(self, message):
ifmessage.message==win32con.WM_DESTROY:
ifint(message.hwnd) ==self.msg_dispatcher: #GUI thread dispatcher's been killed
print("Application terminated.")
self.terminated.emit()
returnQtWidgets.QApplication.winEventFilter(self, message)
defsetupTrayIcon(self, form):
ifself._tray:
iftype(self._tray["icon"]) isnotQtWidgets.QStyle.StandardPixmap:
f=QtGui.QIcon
path=pathlib.Path(self._tray["icon"])
ifnotpath.is_absolute():
self._tray["icon"] =str(self.path.joinpath(self._tray["icon"]))
else: f=QtWidgets.qApp.style().standardIcon
self.addTrayIcon(form, f(self._tray["icon"]), self._tray.get("tip", None))
ifform.windowIcon().isNull(): #Add icon from tray
form.setWindowIcon(f(self._tray["icon"]))
defaddTrayIcon(self, form, icon, tip=None):
#Tray icon parent is VERY important: http://python.6.x6.nabble.com/QSystemTrayIcon-still-crashed-app-PyQt4-4-9-1-td4976041.html
form.tray=QtWidgets.QSystemTrayIcon(icon, form)
iftip: form.tray.setToolTip(tip)
form.tray.setContextMenu(QtWidgets.QMenu(form)) #Qt doc: "The system tray icon does not take ownership of the menu"
form.tray.show()
form.tray.addMenuItem=bind(self.addMenuItem, form.tray)
QtWidgets.qApp.setQuitOnLastWindowClosed(False) #important! open qdialog, hide main window, close qdialog: trayicon stops working
defaddMenuItem(self, *args):
foriinrange(0, len(args), 2):
self.contextMenu().addAction(args[i]).triggered.connect(args[i+1])
_app=None
defapp():
"app() is a current qApp, app().form is a main widget created by QtApp"
if_appisNone: print("app: Call QtApp first")
return_app
defisConsoleApp():
returnnotpathlib.Path(sys.executable).stem=="pythonw"
defDialog(Form, *args, flags=QtCore.Qt.WindowType(), ui=None, ontop=False, **kwargs):
"Dialog.accept(value) - close dialog and return /value/"
defaccept(self, ret=None):
super(Form, self).accept()
self._answer=ret
ifQtWidgets.QDialognotinForm.__bases__: #inherit from QDialog if needed
#http://stackoverflow.com/questions/9539052
Form=type(Form.__name__, (QtWidgets.QDialog,)+Form.__bases__, Form.__dict__.copy())
form=WidgetFactory(Form, args, flags=flags, ui=flags, ontop=ontop, kwargs=kwargs)
form.accept=bind(accept, form)
form.exec()
returngetattr(form, "_answer", None)
defredirect_stdout(wgt):
"""Redirect standard output to the specified widget"""
classes=wgt.metaObject().className(), wgt.metaObject().superClass().className()
if"QPlainTextEdit"inclasses:
defwrite(self, txt):
self.moveCursor(QtGui.QTextCursor.End)
self.insertPlainText(txt)
else:
print_def("THD_UI ERROR (redirect_stdout): cannot redirect output to unsupported "+classes[0])
return
wgt.write=bind(write, wgt)
wgt.flush=bind(lambdaself: None, wgt)
parent=wgt.parent()
defcloseEvent(e, orig_ce=parent.closeEvent):
sys.stdout=sys.__stdout__
orig_ce(e)
parent.closeEvent=closeEvent
sys.stdout=prx(wgt)