-
Notifications
You must be signed in to change notification settings - Fork 35
/
processes.nim
401 lines (358 loc) · 13.6 KB
/
processes.nim
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
# Aporia
# Copyright (C) Dominik Picheta
# Look at copying.txt for more info.
## This module contains functions which deal with running processes,
## such as the Nim process.
## There are also some functions for gathering errors as given by the
## nim compiler and putting them into the error list.
import pegs, times, osproc, streams, parseutils, strutils, re, os
import gtk2, glib2
import utils, CustomStatusBar
# Threading channels
var execThrTaskChan: Channel[ExecThrTask]
execThrTaskChan.open()
var execThrEventChan: Channel[ExecThrEvent]
execThrEventChan.open()
# Threading channels END
var
pegLineError = peg"{[^(]*} '(' {\d+} ', ' \d+ ') Error:' \s* {.*}"
pegLineWarning = peg"{[^(]*} '(' {\d+} ', ' \d+ ') ' ('Warning:'/'Hint:') \s* {.*}"
pegOtherError = peg"'Error:' \s* {.*}"
pegSuccess = peg"'Hint: operation successful'.*"
pegOtherHint = peg"'Hint: '.*"
reLineMessage = re".+\(\d+,\s\d+\)"
pegLineInfo = peg"{[^(]*} '(' {\d+} ', ' \d+ ') Info:' \s* {.*}"
proc `$`(theType: ErrorType): string =
case theType
of TETError: result = "Error"
of TETWarning: result = "Warning"
proc clearErrors*(win: var MainWin) =
var TreeModel = win.errorListWidget.getModel()
# TODO: Why do I have to cast it? Why can't I just do PListStore(TreeModel)?
cast[PListStore](TreeModel).clear()
win.tempStuff.errorList = @[]
proc addError*(win: var MainWin, error: AporiaError) =
# Make the file path a bit shorter, so it's more readable
var fileShort = error.file
var mainDir = win.tabs[win.sourceViewTabs.getCurrentPage()].filename
var i = mainDir.rfind($os.DirSep)
if i > 0 and error.file.startsWith(mainDir.substr(0, i)):
fileShort = "..." & fileShort.substr(i)
var ls = cast[PListStore](win.errorListWidget.getModel())
var iter: TTreeIter
ls.append(addr(iter))
if error.kind == TETError:
ls.set(addr(iter), 0, fileShort, 1, error.line, 2, error.column, 3, $error.kind, 4, error.desc, 5, "red", -1)
else:
ls.set(addr(iter), 0, fileShort, 1, error.line, 2, error.column, 3, $error.kind, 4, error.desc, 5, nil, -1)
# Scroll to last error
var treepath = win.errorListWidget.getModel().get_path(addr(iter));
win.errorListWidget.scrollToCell(treepath, nil, false, 0, 0)
# Activate "Error list" tab
if win.globalSettings.activateErrorTabOnErrors:
win.bottomPanelTabs.setCurrentPage(1)
win.tempStuff.errorList.add(error)
proc parseError(err: string, res: var AporiaError) =
## Parses a line like:
## ``a12.nim(1, 3) Error: undeclared identifier: 'asd'``
##
## or:
##
## lib/system.nim(686, 5) Error: type mismatch: got (string, int literal(5))
## but expected one of:
## <(x: pointer, y: pointer): bool
## <(x: UIntMax32, y: UIntMax32): bool
## <(x: int32, y: int32): bool
## <(x: float, y: float): bool
## <(x: T, y: T): bool
## <(x: int16, y: int16): bool
## <(x: ordinal[T], y: ordinal[T]): bool
## <(x: int, y: int): bool
## <(x: ordinal[T]): T
## <(x: ref T, y: ref T): bool
## <(x: ptr T, y: ptr T): bool
## <(x: char, y: char): bool
## <(x: string, y: string): bool
## <(x: bool, y: bool): bool
## <(x: set[T], y: set[T]): bool
## <(x: int64, y: int64): bool
## <(x: uint64, y: uint64): bool
## <(x: int8, y: int8): bool
##
## or:
##
## Error: execution of an external program failed
var i = 0
if err.startsWith("Error: "):
res.kind = TETError
res.desc = err[7 .. ^1]
res.file = ""
res.line = ""
res.column = ""
return
res.file = ""
i += parseUntil(err, res.file, '(', i)
inc(i) # Skip (
res.line = ""
var lineInt = -1
i += parseInt(err, lineInt, i)
res.line = $lineInt
inc(i) # Skip ,
i += skipWhitespace(err, i)
res.column = ""
var colInt = -1
i += parseInt(err, colInt, i)
# NOTE: Aporia numbers colums from 0,
# but Nim diagnostics column numbers start from 1
res.column = $(max(0, colInt-1))
inc(i) # Skip )
i += skipWhitespace(err, i)
var theType = ""
i += parseUntil(err, theType, ':', i)
case normalize(theType)
of "error", "info":
res.kind = TETError
of "hint", "warning":
res.kind = TETWarning
else:
echod(theType)
assert(false)
inc(i) # Skip :
i += skipWhitespace(err, i)
res.desc = err.substr(i, err.len()-1)
proc execProcAsync*(win: var MainWin, exec: ExecOptions)
proc printProcOutput(win: var MainWin, line: string) =
## This shouldn't have to worry about receiving broken up errors (into new lines)
## continuous errors should be received, errors which span multiple lines
## should be received as one continuous message.
echod("Printing: ", line.repr)
template paErr(): typed =
var parseRes: AporiaError
parseError(line, parseRes)
win.addError(parseRes)
# Colors
var normalTag = createColor(win.outputTextView, "normalTag", "#3d3d3d")
var errorTag = createColor(win.outputTextView, "errorTag", "red")
var warningTag = createColor(win.outputTextView, "warningTag", "darkorange")
var successTag = createColor(win.outputTextView, "successTag", "darkgreen")
assert win.tempStuff.currentExec != nil
case win.tempStuff.currentExec.mode:
of ExecNim:
if line =~ pegLineError / pegOtherError / pegLineInfo:
win.outputTextView.addText(line & "\l", errorTag)
paErr()
win.tempStuff.compileSuccess = false
elif line =~ pegSuccess:
win.outputTextView.addText(line & "\l", successTag)
win.tempStuff.compileSuccess = true
elif line =~ pegLineWarning:
win.outputTextView.addText(line & "\l", warningTag)
paErr()
else:
win.outputTextView.addText(line & "\l", normalTag)
of ExecRun, ExecCustom:
win.outputTextView.addText(line & "\l", normalTag)
proc parseCompilerOutput(win: var MainWin, event: ExecThrEvent) =
if event.line == "" or event.line.startsWith(pegSuccess) or
event.line =~ pegOtherHint:
#echod(1)
if win.tempStuff.errorMsgStarted:
win.tempStuff.errorMsgStarted = false
win.printProcOutput(win.tempStuff.compilationErrorBuffer.strip())
win.tempStuff.compilationErrorBuffer = ""
if event.line != "":
win.printProcOutput(event.line)
elif event.line.startsWith(reLineMessage):
#echod(2)
if not win.tempStuff.errorMsgStarted:
#echod(2.1)
win.tempStuff.errorMsgStarted = true
win.tempStuff.compilationErrorBuffer.add(event.line & "\l")
elif win.tempStuff.compilationErrorBuffer != "":
#echod(2.2)
win.printProcOutput(win.tempStuff.compilationErrorBuffer.strip())
win.tempStuff.compilationErrorBuffer = ""
win.tempStuff.errorMsgStarted = false
win.printProcOutput(event.line)
else:
win.printProcOutput(event.line)
else:
#echod(3)
if win.tempStuff.errorMsgStarted:
win.tempStuff.compilationErrorBuffer.add(event.line & "\l")
else:
win.printProcOutput(event.line)
proc peekProcOutput*(win: ptr MainWin): gboolean {.cdecl.} =
result = true
if win.tempStuff.currentExec != nil:
var events = execThrEventChan.peek()
if epochTime() - win.tempStuff.lastProgressPulse >= 0.1:
win.statusbar.progressbar.pulse()
win.tempStuff.lastProgressPulse = epochTime()
if events > 0:
var successTag = createColor(win.outputTextView, "successTag",
"darkgreen")
var errorTag = createColor(win.outputTextView, "errorTag", "red")
for i in 0..events-1:
var event: ExecThrEvent = execThrEventChan.recv()
case event.typ
of EvStarted:
win.tempStuff.execProcess = event.p
of EvRecv:
event.line = event.line.strip(leading = false)
if win.tempStuff.currentExec.onLine != nil:
win.tempStuff.currentExec.onLine(win[], win.tempStuff.currentExec, event.line)
if win.tempStuff.currentExec.output:
if win.tempStuff.currentExec.mode == ExecNim:
win[].parseCompilerOutput(event)
else:
# TODO: Print "" as a \n?
if event.line != "":
win[].printProcOutput(event.line)
of EvStopped:
echod("[Idle] Process has quit")
if win.tempStuff.currentExec.onExit != nil:
win.tempStuff.currentExec.onExit(win[], win.tempStuff.currentExec, event.exitCode)
if win.tempStuff.currentExec.output:
if win.tempStuff.compilationErrorBuffer.len() > 0:
win[].printProcOutput(win.tempStuff.compilationErrorBuffer)
if event.exitCode == QuitSuccess:
win.outputTextView.addText("> Process terminated with exit code " &
$event.exitCode & "\l", successTag)
# Activate "Output" tab, after successful compilation
win.bottomPanelTabs.setCurrentPage(0)
else:
win.outputTextView.addText("> Process terminated with exit code " &
$event.exitCode & "\l", errorTag)
let runAfter = win.tempStuff.currentExec.runAfter
let runAfterSuccess = win.tempStuff.currentExec.runAfterSuccess
win.tempStuff.currentExec = nil
# remove our progress status if it's in the 'previous status list'
win.statusbar.delPrevious(win.tempStuff.progressStatusID)
if win.statusbar.statusID == win.tempStuff.progressStatusID:
win.statusbar.restorePrevious()
# TODO: Remove idle proc here?
# Execute another process in queue (if any)
if runAfter != nil:
if runAfterSuccess and (not win.tempStuff.compileSuccess):
return
echod("Exec Run-after.")
win[].execProcAsync(runAfter)
else:
echod("idle proc exiting")
return false
proc execProcAsync*(win: var MainWin, exec: ExecOptions) =
## This function executes a process in a new thread, using only idle time
## to add the output of the process to the `outputTextview`.
assert(win.tempStuff.currentExec == nil)
# Reset some things; and set some flags.
# Execute the process
win.tempStuff.currentExec = exec
echod(exec.command)
var task: ExecThrTask
task.typ = ThrRun
task.command = exec.command
task.workDir = exec.workDir
execThrTaskChan.send(task)
# Output
if exec.output:
var normalTag = createColor(win.outputTextView, "normalTag", "#3d3d3d")
win.outputTextView.addText("> " & exec.command & "\l", normalTag)
# Add a function which will be called when the UI is idle.
win.tempStuff.idleFuncId = gTimeoutAdd(50, peekProcOutput, addr(win))
win.tempStuff.progressStatusID = win.statusbar.setProgress("Executing")
win.statusbar.progressbar.pulse()
win.tempStuff.lastProgressPulse = epochTime()
# Clear errors
win.clearErrors()
proc newExec*(command: string, workDir: string, mode: ExecMode, output = true,
onLine: proc (win: var MainWin, opts: ExecOptions, line: string) {.closure.} = nil,
onExit: proc (win: var MainWin, opts: ExecOptions, exitcode: int) {.closure.} = nil,
runAfter: ExecOptions = nil, runAfterSuccess = true): ExecOptions =
new(result)
result.command = command
result.workDir = workDir
result.mode = mode
result.output = output
result.onLine = onLine
result.onExit = onExit
result.runAfter = runAfter
result.runAfterSuccess = runAfterSuccess
template createExecThrEvent(t: ExecThrEventType, todo: typed): typed {.immediate.} =
## Sends a thrEvent of type ``t``, does ``todo`` before sending.
var event {.inject.}: ExecThrEvent
event.typ = t
todo
execThrEventChan.send(event)
proc cmdToArgs(cmd: string): tuple[bin: string, args: seq[string]] =
var spl = cmd.split(' ')
assert spl.len > 0
result.bin = spl[0]
result.args = @[]
for i in 1 .. <spl.len:
result.args.add(spl[i])
proc dispatchTasks(tasks: int, started: var bool, p: var Process, o: var Stream) =
for i in 0..tasks-1:
var task: ExecThrTask = execThrTaskChan.recv()
case task.typ
of ThrRun:
if not started:
let (bin, args) = cmdToArgs(task.command)
p = startProcess(bin, task.workDir, args,
options = {poStdErrToStdOut, poUsePath, poInteractive})
createExecThrEvent(EvStarted):
event.p = p
o = p.outputStream
started = true
else:
echod("[Thread] Process already running")
of ThrStop:
echod("[Thread] Stopping process.")
p.terminate()
started = false
o.close()
var exitCode = p.waitForExit()
createExecThrEvent(EvStopped):
event.exitCode = exitCode
p.close()
proc execThreadProc(){.thread.} =
var p: Process
var o: Stream
var started = false
while true:
var tasks = execThrTaskChan.peek()
if tasks == 0 and not started: tasks = 1
if tasks > 0:
try:
dispatchTasks(tasks, started, p, o)
except:
echo(getCurrentException().repr)
block:
createExecThrEvent(EvRecv):
event.line = "Error: Problem occurred during execution: " &
getCurrentExceptionMsg()
block:
createExecThrEvent(EvStopped):
event.exitCode = QuitFailure
# Check if process exited.
if started:
if not p.running:
echod("[Thread] Process exited.")
if not o.atEnd:
var line = ""
while not o.atEnd:
line = o.readLine()
createExecThrEvent(EvRecv):
event.line = line
# Process exited.
var exitCode = p.waitForExit()
p.close()
started = false
createExecThrEvent(EvStopped):
event.exitCode = exitCode
if started:
var line = o.readLine()
createExecThrEvent(EvRecv):
event.line = line
proc createProcessThreads*(win: var MainWin) =
createThread[void](win.tempStuff.execThread, execThreadProc)