-
Notifications
You must be signed in to change notification settings - Fork 1
/
MainThread.py
299 lines (266 loc) · 10.8 KB
/
MainThread.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
import mdlog, os
mdlog.initLogging("server", "/tmp", stdOut=True)
log = mdlog.getLogger(__name__)
log.setLevel(20)
log.info("\n--------------------------------------------------------------------------------\n")
import os, sys
from dfly_server import DragonflyThread
from WindowEventWatcher import WindowEventWatcher
import EventLoop
from EventLoop import SubscriptionHandle
import re
import time
import traceback
from EventList import (MicrophoneEvent, ConnectedEvent, WindowListEvent,
ExitEvent, RestartEvent, EventsDrainedEvent)
from rules.ContextualRule import makeContextualRule
import EventList
import select
from protocol import RuleType
from copy import copy
import collections
from threading import Lock
FAIL_ON_ERROR = False
badWindows = {
"Desktop",
".*Edge Panel.*",
"gnome-screensaver",
"Panel",
"$^", # empty string
}
def filterWindows(w):
# filter out known bad names
for bad in badWindows:
if re.search(bad, w.name) is not None:
return False
# filter out windows that don't have
# icons set. typically these only exist
# as an artifact of dealing with X
if not w.hasIcon:
return False
return True
class TimerEntry(object):
def __init__(self, nextExpiration, callback, seconds, priority):
self.nextExpiration = nextExpiration
self.callback = callback
self.seconds = seconds
self.priority = priority
class MainThread(object):
FILE_INPUT = select.EPOLLIN
FILE_PRI = select.EPOLLPRI
FILE_OUTPUT = select.EPOLLOUT
FILE_ERROR = select.EPOLLERR
FILE_HUP = select.EPOLLHUP
def __init__(self):
# this needs to run before any user modes are imported
self.epoll = select.epoll()
self.timers = []
EventLoop.event_loop = self
self.run = True
self.events = collections.deque()
self.eventsLock = Lock()
self.eventSubscribers = {}
self.fileSubscribers = {}
self.dfly = DragonflyThread(('', 23133), self)
self.win = WindowEventWatcher(self, filterWindows)
self.subscribeEvent(RestartEvent, self.restart)
self.subscribeEvent(ExitEvent, self.stop)
mapping = { "restart mandimus" : (lambda x: self.put(RestartEvent())),
"completely exit mandimus" : (lambda x: self.put(ExitEvent())) }
self.MainControlRule = makeContextualRule("MainControlRule", mapping, ruleType=RuleType.INDEPENDENT)
self.MainControlRule.activate()
def subscribeEvent(self, eventType, handler, priority=100):
log.info("Setting up event sub: [%s] [%s] [%s]" % (eventType, handler, priority))
if eventType not in self.eventSubscribers:
self.eventSubscribers[eventType] = []
self.eventSubscribers[eventType].append((priority, handler))
self.eventSubscribers[eventType].sort(key=lambda x: x[0])
return SubscriptionHandle((eventType, priority, handler))
def subscribeTimer(self, seconds, cb, priority=100):
entry = TimerEntry(time.time() + seconds, cb, seconds, priority)
self.timers.append(entry)
self.timers.sort(key=lambda x: x.priority)
return SubscriptionHandle(entry)
def subscribeFile(self, fd, flags, cb, priority=100):
log.info("Subscribing to fd [%s]" % fd)
self.epoll.register(fd, flags)
if fd not in self.fileSubscribers:
self.fileSubscribers[fd] = []
self.fileSubscribers[fd].append((flags, priority, cb))
self.fileSubscribers[fd].sort(key=lambda x: x[1])
return SubscriptionHandle((fd, flags, priority, cb))
def unsubscribe(self, handleData):
log.info("Unsubscribing [%s]" % (handleData,))
if isinstance(handleData, TimerEntry):
self.timers.remove(handleData)
elif isinstance(handleData[0], int):
self.fileSubscribers[handleData[0]].remove((handleData[1], handleData[2], handleData[3]))
# TODO: this is wrong, it should be doing counts for each of the
# event flags if there are really multiple subscriptions to the
# same fd they are probably on different events.
if not len(self.fileSubscribers[handleData[0]]):
self.epoll.unregister(handleData[0])
else:
# regular event subscription
self.eventSubscribers[handleData[0]].remove((handleData[1], handleData[2]))
def timeout(self):
if self.timers:
nextTimer = min(self.timers, key=lambda x: x.nextExpiration)
nextExpiration = nextTimer.nextExpiration
else:
# without a timeout, cgetrl-c doesn't work because.. python
ONEYEAR = 365 * 24 * 60 * 60
nextExpiration = time.time() + ONEYEAR
return max(nextExpiration - time.time(), 0)
def dispatchTimers(self):
# TODO: if these were sorted we could break early
now = time.time()
for t in self.timers:
if now >= t.nextExpiration:
t.nextExpiration = now + t.seconds
try:
t.callback()
except KeyboardInterrupt:
raise
except Exception:
exc_type, exc_value, exc_traceback = sys.exc_info()
log.error(''.join(traceback.format_exception(exc_type, exc_value, exc_traceback)))
if FAIL_ON_ERROR:
raise
continue
def put(self, p):
# with self.eventsLock:
# log.info("Adding [%s] to events" % (type(p),))
self.events.append(p)
def processEvent(self, ev):
#log.debug("processing %s subscribers for event [%s]" % (len(self.eventSubscribers[type(ev)]) if type(ev) in self.eventSubscribers else "wtf", type(ev)))
if type(ev) in self.eventSubscribers:
log.debug("processing %d subscribers for event [%s] : [%s]" % (len(self.eventSubscribers[type(ev)]), ev, self.eventSubscribers[type(ev)]))
subscribers = copy(self.eventSubscribers[type(ev)])
for i, h in enumerate(subscribers):
log.debug("processing subscriber number %d" % i)
try:
h[1](ev)
except KeyboardInterrupt:
raise
except Exception as e:
exc_type, exc_value, exc_traceback = sys.exc_info()
log.error(''.join(traceback.format_exception(exc_type, exc_value, exc_traceback)))
if FAIL_ON_ERROR:
raise
continue
def drainEvents(self, fileEvents):
# with self.eventsLock:
ranOnce = False
try:
# log.info("Checking epoll events")
for fileno, event in fileEvents:
# log.info("Got event on file [%d]!" % fileno)
if fileno in self.fileSubscribers:
# log.info("Dispatching...")
for sub in self.fileSubscribers[fileno]:
# log.info("event [%s] [%s]" % (event, sub[0]))
# log.info("event togethe [%s] [%s]" % (event, sub[0]))
if event & sub[0]:
# log.info("Calling callback")
sub[2]()
ranOnce = True
else:
log.error("Received event for file without subscription [%d] [%s]" % (fileno, event))
while self.run:
try:
ev = self.events.popleft()
#log.info("Processing event: [%s]" % (ev,))
except IndexError:
break
self.processEvent(ev)
ranOnce = True
if ranOnce:
self.processEvent(EventsDrainedEvent())
except KeyboardInterrupt:
self.stop()
sys.exit()
def __call__(self):
try:
while self.run:
events = self.epoll.poll(self.timeout())
#time.sleep(self.timeout())
self.dispatchTimers()
self.drainEvents(events)
except KeyboardInterrupt:
self.stop()
sys.exit()
def stop(self, ev=None):
self.run = False
self.dfly.cleanup()
def restart(self, ev=None):
log.info("Restarting mandimus")
self.processEvent(MicrophoneEvent("server-disconnected"))
mdlog.flush()
self.stop()
sys.stdout.flush()
sys.stderr.flush()
python = sys.executable
os.execl(python, python, *sys.argv)
if __name__ == "__main__":
main = MainThread()
imports = [
('rules.Always', ['']),
('rules.emacs.Build', ['']),
('rules.emacs.Belt', ['']),
('rules.emacs.BufferNames', ['']),
('rules.Chrome', ['']),
('rules.emacs.Comint', ['']),
('rules.emacs.Cpp', ['']),
('rules.CUA', ['']),
('rules.emacs.Dired', ['']),
('rules.emacs.Emacs', ['']),
('rules.emacs.Eww', ['']),
('rules.emacs.Edit', ['']),
('rules.emacs.ERC', ['']),
('rules.emacs.Eshell', ['']),
('rules.emacs.GnuDebugger', ['']),
('rules.emacs.Julia', ['']),
('rules.emacs.Lisp', ['']),
('rules.emacs.Python', ['']),
('rules.emacs.Pairs', ['']),
('rules.emacs.Perl6', ['']),
('rules.emacs.Profiling', ['']),
('rules.emacs.Mic', ['']),
('rules.emacs.Magit', ['']),
('rules.emacs.Nav', ['']),
('rules.emacs.NickNames', ['']),
('rules.emacs.Org', ['']),
('Pedals', ['']),
('rules.PedalConfig', ['']),
('rules.emacs.ProjectFileNames', ['']),
('rules.emacs.ProjectNames', ['']),
('rules.emacs.Term', ['']),
('rules.emacs.ModeLine', ['']),
('rules.emacs.Racket', ['']),
('rules.emacs.Rust', ['']),
('rules.emacs.Shell', ['']),
('rules.emacs.Snippet', ['']),
('rules.emacs.Sql', ['']),
('rules.emacs.SymbolPicker', ['']),
('rules.emacs.VarNames', ['']),
('rules.emacs.Vhdl', ['']),
('rules.emacs.Verilog', ['']),
('rules.Terminal', ['']),
('rules.WindowNames', ['']),
('rules.emacs.Words', ['']),
('rules.XMonad', ['']),
('RefreshClient', ['']),
]
# TODO: catch syntax errors, make copies of module files, then
# try to import again with offending line removed
for module, fromlist in imports:
try:
__import__(module, globals(), locals(), fromlist)
except Exception as e:
log.info("Couldn't import %s" % module)
exc_type, exc_value, exc_traceback = sys.exc_info()
log.error(''.join(traceback.format_exception(exc_type, exc_value, exc_traceback)))
if FAIL_ON_ERROR:
raise
main()