- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
Latest commit
224 lines (199 loc) · 8.81 KB
/
Copy pathmain.py
File metadata and controls
224 lines (199 loc) · 8.81 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
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 20 13:20:59 2015
@author: Winand
"""
fromgeneralimportgetMacroList, DEF_MODULE, SOURCEDIR, macro_tree, modules, pythoncom, print
fromgeneralimportrun_lock
importcontext
importstruct, json, pathlib
importimportlib, _thread
importwin32file, win32con, winnt
fromthreaded_uiimportQtApp, invoker, QtCore, QtGui, app, isConsoleApp, QtWidgets
importsys, threading, time
importsocketserver
SHARED_SERVER_ADDR, SHARED_SERVER_PORT="127.0.0.1", 50002
classTCPServer(socketserver.TCPServer):
allow_reuse_address=True
defmacro_caller(macro, *args, **kwargs):
pythoncom.CoInitialize()
macro(*args, **kwargs)
classHandler(socketserver.BaseRequestHandler):
defsendString(self, s):
ifs:
msg=s.encode("utf-8")
self.request.sendall(struct.pack('i', len(msg)))
self.request.sendall(msg)
defsendByte(self, b):
self.request.sendall(struct.pack('b', b))
defrecvString(self):
msgl=struct.unpack('i', self.request.recv(4))[0]
returnself.request.recv(msgl).decode("utf-8")
defhandle(self):
msg=json.loads("{%s}"%self.recvString())
self.sendString(self.handle_wrap(msg["Type"], msg))
defhandle_wrap(self, msg, args):
ifmsgin ("Call", "Doc"):
path=args["Macro"].rsplit(".", 1)
iflen(path)==1: path.insert(0, DEF_MODULE)
ifpath[0] inmacro_treeandpath[1] inmacro_tree[path[0]]:
macro=getattr(modules[path[0]], path[1], None)
else: macro=None
ifnotmacro: return"SERVER_NO_MACRO"
elifmsg=="Doc":
print("Help on '%s' requested"%args["Macro"])
returnmacro.__doc__or""
else: #Caller must 'Test' if server is 'OK' before this
print("Macro '%s' called "%path[1])
invoker.invoke(app().form.startMacro, macro, args["Workbook"])
return"OK"
elifmsg=="Request":
print("Macro list requested")
return"|".join(getMacroList(args["Application"]))
elifmsg=="Test":
print("Connection checked")
withrun_lock:
return"Busy"ifnotrun_lock._valueelse"OK"
elifmsg=="Interrupt":
print("Request to interrupt macro")
withrun_lock: #FIXME: It's possible to make several requests before macro is interrupted. Is it ok?
ifnotrun_lock._value:
_thread.interrupt_main()
else: return"Not busy"
return"OK"
else:
print("Unknown message")
return"Unknown"
definitModuleLoader():
watch, loader_lock= {}, threading.RLock()
src_path=str(app().path.joinpath("source"))
defwatcher():
defreadChanges(h, flags):
returnwin32file.ReadDirectoryChangesW(h, 1024, True, flags, None, None)
actions= {1: "add", 2: "del", 3: "add", 4: "del", 5: "add"} #3 - update; 4, 5 - rename
hDir=win32file.CreateFile(src_path, winnt.FILE_LIST_DIRECTORY,
win32con.FILE_SHARE_READ|win32con.FILE_SHARE_WRITE|win32con.FILE_SHARE_DELETE,
None, win32con.OPEN_EXISTING, win32con.FILE_FLAG_BACKUP_SEMANTICS, None)
whileTrue:
foraction, fileinreadChanges(hDir, win32con.FILE_NOTIFY_CHANGE_FILE_NAME|
win32con.FILE_NOTIFY_CHANGE_LAST_WRITE):
filename=pathlib.Path(file)
iffilename.suffix==".py"andnotfilename.stem.startswith("__"):
withloader_lock:
watch[filename.stem] =actions[action]
defunload(mod_name):
ifmod_nameinmodules:
# m = modules[mod_name]
delmodules[mod_name], macro_tree[mod_name], sys.modules[SOURCEDIR+"."+mod_name]
# print(sys.getrefcount(m))
defimport_mod(mod_name):
try:
macro_tree[mod_name] = {}
modules[mod_name] =importlib.import_module(SOURCEDIR+"."+mod_name)
print("Module '%s' updated"%mod_name)
exceptExceptionase:
print("Failed to update '%s' module: %s: %s"%(mod_name, type(e).__name__, e))
delmacro_tree[mod_name]
defreloader():
whileTrue:
withloader_lock:
iflen(watch): #if update needed
foriinwatch:
ifwatch[i] =="add":
ifiinmodules: unload(i)
import_mod(i)
elifwatch[i] =="del":
unload(i)
print("Module '%s' unloaded"%i)
invoker.wait(app().form.updateMacroTree)
watch.clear()
time.sleep(1)
foriin [fforfinpathlib.Path(src_path).iterdir() iff.is_file() and
f.suffix==".py"andnotf.stem.startswith("__")]:
watch[i.stem] ="add"
foriinthreading.Thread(target=watcher), \
threading.Thread(target=reloader):
i.daemon=True
i.start()
classTempTrayIcon:
"Temporary changes tray icon"
def__init__(self, systray, temptext, tempicon):
f=QtWidgets.qApp.style().standardIcon \
iftype(tempicon) isQtWidgets.QStyle.StandardPixmapelseQtGui.QIcon
self.tray=systray
self.oldicon, self.newicon=self.tray.icon(), f(tempicon)
self.oldtip, self.newtip=self.tray.toolTip(), temptext
def__enter__(self):
self.tray.setIcon(self.newicon)
self.tray.setToolTip(self.newtip)
def__exit__(self, *args):
self.tray.setIcon(self.oldicon)
self.tray.setToolTip(self.oldtip)
classSimplePython(QtWidgets.QWidget):
office_icons= {context.Excel: r"res\excel.png", context.Word: r"res\word.png",
context.PowerPoint: r"res\powerpoint.png",
context.Office: r"res\office.png", "Module": r"res\icon.png"}
def__init__(self):
initModuleLoader()
self.server=TCPServer((SHARED_SERVER_ADDR, SHARED_SERVER_PORT), Handler)
threading.Thread(target=self.server.serve_forever).start()
self.tray.addMenuItem("Exit", self.btnExit_clicked)
self.terminated.connect(self.btnExit_clicked)
self.twModules.header().close()
foriinself.office_icons:
self.office_icons[i] =QtGui.QIcon(str(app().path.joinpath(self.office_icons[i])))
deftray_activated(self, reason):
ifreason==QtWidgets.QSystemTrayIcon.Trigger:
self.showWindow()
defshowWindow(self, console=False):
ifconsoleandisConsoleApp():
return
self.show()
self.activateWindow()
ifconsole:
self.tabs.setCurrentIndex(0)
defbtnClear_clicked(self):
self.txtConsole.clear()
deftwModules_currentItemChanged(self, item, previous):
name=item.text(0)
m_item=item.parent()
ifm_item:
mod=m_item.text(0)
type_=macro_tree[mod][name]+" macro"
text=getattr(modules[mod], name).__doc__
name=mod+"."+name
else:
type_="module"
text=modules[name].__doc__
self.lblMacroInfo.setText("<b>%s</b> (%s)<br/><br/>%s"%
(name, type_, (textor"").strip().replace('\n', "<br/>")))
@QtCore.Slot()
defupdateMacroTree(self):
self.twModules.clear()
forminmacro_tree:
wbi=QtWidgets.QTreeWidgetItem(self.twModules, [m])
wbi.setIcon(0, self.office_icons["Module"])
macro_list=macro_tree[m]
forjinmacro_list:
ic=self.office_icons.get(macro_list[j], None)
child=QtWidgets.QTreeWidgetItem([j])
ific:
child.setIcon(0, ic)
wbi.addChild(child)
wbi.setExpanded(True)
defbtnExit_clicked(self):
self.server.shutdown()
self.server.server_close()
QtWidgets.qApp.quit()
defcloseEvent(self, event):
ifevent.type() ==event.Close:
event.ignore()
self.hide()
@QtCore.Slot(object, object)
defstartMacro(self, macro, wb):
withTempTrayIcon(self.tray, "%s\nRunning: %s"%(self.tray.toolTip(), macro.__name__),
QtWidgets.QStyle.SP_ArrowRight):
macro(wb)
stdout=NoneifisConsoleApp() else"txtConsole"#redirect output if no console
QtApp(SimplePython, ontop=True, hidden=True, stdout=stdout,
tray={"icon": r"res\icon.png", "tip": "SimplePython Server"})