forked from seiyria/sublime-dreams
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdmc.py
325 lines (245 loc) · 9.38 KB
/
dmc.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
import sublime, sublime_plugin
from os.path import dirname, splitdrive, isfile, join, splitext
import os, sys
import thread
import subprocess
import functools
import time
import processlistener
import asynclistener
path = {
'x32': "C:/Program Files/BYOND/bin/",
'x64': "C:/Program Files (x86)/BYOND/bin/"
}
class ProcessListener(object):
def on_data(self, proc, data):
pass
def on_finished(self, proc):
pass
class DmcCommand(sublime_plugin.WindowCommand, ProcessListener):
dream_daemon = None
dream_seeker = None
#DreamMaker
proc = None
quiet = False
def run(self, cmd = [], file_regex = "", line_regex = "",
encoding = "utf-8", env = {}, quiet = False, kill_old = False,
dream_seeker = False, dream_daemon = False, **kwargs):
file = cmd[0]
dmpath = path[sublime.arch()]
dme_file = self.find_closest_dme(file)
dme_dir = dirname(dme_file)
self.setup_sublime(file_regex, line_regex, dme_dir, encoding)
# kill it to prevent RSC bullshit
if self.dream_seeker and kill_old:
self.dream_seeker.kill()
self.build(dmpath, dme_file)
dmb_dir = self.find_dmb(dme_dir)
if dream_seeker:
self.run_in_seeker(dmpath, dmb_dir)
if dream_daemon:
self.run_in_daemon(dmpath, dmb_dir)
def run_cmd(self, cmd, is_daemon = False, is_seeker = False, is_maker = False, **kwargs):
self.proc = None
merged_env = {}
if self.window.active_view():
user_env = self.window.active_view().settings().get('build_env')
if user_env:
merged_env.update(user_env)
err_type = OSError
if os.name == "nt":
err_type = WindowsError
try:
# I have a large dislike of writing it this way
if is_maker:
sublime.status_message("Building DMB...")
self.proc = AsyncProcess(cmd, merged_env, self, **kwargs)
if is_seeker:
sublime.status_message("Running in DreamSeeker...")
self.dream_seeker = AsyncProcess(cmd, merged_env, self, **kwargs)
if is_daemon:
sublime.status_message("Running in DreamDaemon...")
self.dream_daemon = AsyncProcess(cmd, merged_env, self, **kwargs)
except err_type as e:
self.append_data(None, str(e) + "\n")
self.append_data(None, "[cmd: " + str(cmd) + "]\n")
self.append_data(None, "[dir: " + str(os.getcwdu()) + "]\n")
if "PATH" in merged_env:
self.append_data(None, "[path: " + str(merged_env["PATH"]) + "]\n")
else:
self.append_data(None, "[path: " + str(os.environ["PATH"]) + "]\n")
if not self.quiet:
self.append_data(None, "[Finished]")
#build runners
def build(self, environment_path, dme_path):
cmd = [ environment_path + "dm" , dme_path ]
self.run_cmd(cmd, is_maker = True)
def run_in_seeker(self, environment_path, dmb = ''):
cmd = [ environment_path + "dreamseeker" , dmb ]
self.run_cmd(cmd, is_seeker = True)
def run_in_daemon(self, environment_path, dmb):
cmd = [ environment_path + "dreamdaemon" , dmb , "-trusted" ]
self.run_cmd(cmd, is_daemon = True)
#file finders
def find_closest_dme(self, compile_file):
sublime.status_message("Finding closest DME...")
current_dir = compile_file
dme = compile_file
while current_dir != self.drive_root(current_dir):
current_dir = dirname(current_dir)
file_list = [
current_dir+"\\"+f.encode('ascii', 'ignore')
for f in os.listdir(current_dir)
if isfile(join(current_dir, f)) and splitext(f)[1] == u".dme"
]
#TODO search for the DME containing the file
if len(file_list) is not 0:
dme = file_list[0]
return dme.encode('ascii', 'ignore')
def find_dmb(self, current_dir):
#TODO match the current directory name/dme name
dmb_list = [
current_dir+"\\"+f.encode('ascii', 'ignore')
for f in os.listdir(current_dir)
if isfile(join(current_dir, f)) and splitext(f)[1] == u".dmb"
]
if len(dmb_list) is not 0:
return dmb_list[0]
#get the drive root
def drive_root(self, path):
return splitdrive(path)[0]+"\\"
#sublime configuration
def setup_sublime(self, file_regex, line_regex, working_dir, encoding):
if not hasattr(self, 'output_view'):
self.output_view = self.window.get_output_panel("exec")
if (working_dir == "" and self.window.active_view()
and self.window.active_view().file_name()):
working_dir = os.path.dirname(self.window.active_view().file_name())
self.output_view.settings().set("result_file_regex", file_regex)
self.output_view.settings().set("result_line_regex", line_regex)
self.output_view.settings().set("result_base_dir", working_dir)
self.window.get_output_panel("exec")
self.encoding = encoding
show_panel_on_build = sublime.load_settings("Preferences.sublime-settings").get("show_panel_on_build", True)
if show_panel_on_build:
self.window.run_command("show_panel", {"panel": "output.exec"})
if working_dir != "":
os.chdir(working_dir)
# from exec.py verbatim
def is_enabled(self, kill = False):
if kill:
return hasattr(self, 'proc') and self.proc and self.proc.poll()
else:
return True
def append_data(self, proc, data):
if proc != self.proc:
# a second call to exec has been made before the first one
# finished, ignore it instead of intermingling the output.
if proc:
proc.kill()
return
try:
str = data.decode(self.encoding)
except:
str = "[Decode error - output not " + self.encoding + "]\n"
proc = None
# Normalize newlines, Sublime Text always uses a single \n separator
# in memory.
str = str.replace('\r\n', '\n').replace('\r', '\n')
selection_was_at_end = (len(self.output_view.sel()) == 1
and self.output_view.sel()[0]
== sublime.Region(self.output_view.size()))
self.output_view.set_read_only(False)
edit = self.output_view.begin_edit()
self.output_view.insert(edit, self.output_view.size(), str)
if selection_was_at_end:
self.output_view.show(self.output_view.size())
self.output_view.end_edit(edit)
self.output_view.set_read_only(True)
def finish(self, proc):
if not self.quiet:
elapsed = time.time() - proc.start_time
exit_code = proc.exit_code()
if exit_code == 0 or exit_code == None:
self.append_data(proc, ("[Finished in %.1fs]") % (elapsed))
else:
self.append_data(proc, ("[Finished in %.1fs with exit code %d]") % (elapsed, exit_code))
if proc != self.proc:
return
errs = self.output_view.find_all_results()
if len(errs) == 0:
sublime.status_message("Build finished")
else:
sublime.status_message(("Build finished with %d errors") % len(errs))
# Set the selection to the start, so that next_result will work as expected
edit = self.output_view.begin_edit()
self.output_view.sel().clear()
self.output_view.sel().add(sublime.Region(0))
self.output_view.end_edit(edit)
def on_data(self, proc, data):
sublime.set_timeout(functools.partial(self.append_data, proc, data), 0)
def on_finished(self, proc):
sublime.set_timeout(functools.partial(self.finish, proc), 0)
# Encapsulates subprocess.Popen, forwarding stdout to a supplied
# ProcessListener (on a separate thread)
class AsyncProcess(object):
def __init__(self, arg_list, env, listener,
# "path" is an option in build systems
path="",
# "shell" is an options in build systems
shell=False):
self.listener = listener
self.killed = False
self.start_time = time.time()
# Hide the console window on Windows
startupinfo = None
if os.name == "nt":
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
# Set temporary PATH to locate executable in arg_list
if path:
old_path = os.environ["PATH"]
# The user decides in the build system whether he wants to append $PATH
# or tuck it at the front: "$PATH;C:\\new\\path", "C:\\new\\path;$PATH"
os.environ["PATH"] = os.path.expandvars(path).encode(sys.getfilesystemencoding())
proc_env = os.environ.copy()
proc_env.update(env)
for k, v in proc_env.iteritems():
proc_env[k] = os.path.expandvars(v).encode(sys.getfilesystemencoding())
self.proc = subprocess.Popen(arg_list, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, startupinfo=startupinfo, env=proc_env, shell=shell)
if path:
os.environ["PATH"] = old_path
if self.proc.stdout:
thread.start_new_thread(self.read_stdout, ())
if self.proc.stderr:
thread.start_new_thread(self.read_stderr, ())
def kill(self):
if not self.killed:
self.killed = True
self.proc.terminate()
self.listener = None
def poll(self):
return self.proc.poll() == None
def exit_code(self):
return self.proc.poll()
def read_stdout(self):
while True:
data = os.read(self.proc.stdout.fileno(), 2**15)
if data != "":
if self.listener:
self.listener.on_data(self, data)
else:
self.proc.stdout.close()
if self.listener:
self.listener.on_finished(self)
break
def read_stderr(self):
while True:
data = os.read(self.proc.stderr.fileno(), 2**15)
if data != "":
if self.listener:
self.listener.on_data(self, data)
else:
self.proc.stderr.close()
break