Refactor main loop

This commit is contained in:
Kai Vogelgesang 2022-09-25 11:47:01 +02:00
parent d1df4ff6a2
commit 36427a41a4
Signed by: kai
GPG Key ID: 0A95D3B6E62C0879

View File

@ -72,10 +72,6 @@ local report_task = coroutine.create(function()
end
end)
local shell_task = coroutine.create(function()
shell.run("shell")
end)
-- basically parallel.waitForAny
local record Task
@ -83,15 +79,39 @@ local record Task
filter: string | nil
end
local tasks: {Task} = {
{coro = shell_task}, -- pid 1
local background_tasks: {Task} = {
{coro = ws_task},
{coro = report_task},
}
local shell_task: Task = {
coro = coroutine.create(function() shell.run("shell") end)
}
local function handle_event(e: table, pid: integer)
if e[1] == "terminate" then return end
local task = background_tasks[pid]
if task.filter == nil or task.filter == e[1] then
local ok, param = coroutine.resume(task.coro, table.unpack(e as {any}))
if not ok then
term.native = orig_native
term.redirect(term.native())
term.clear()
term.setCursorPos(1,1)
print(("OMEGABIG OOF @ PID %d"):format(pid))
error(param, 0)
else
task.filter = param as string
end
end
end
local event_queue: Ringbuffer.Ringbuffer<table> = Ringbuffer.new(64)
event_queue:push({n = 0})
local shell_deaths: {any} = {}
local shell_running = true
while shell_running do
local e: table
@ -112,26 +132,24 @@ while shell_running do
socket:signal_viewer_connect(false)
end
else
for pid = 1, #tasks do
local task = tasks[pid]
if task.filter == nil or task.filter == e[1] or e[1] == "terminate" then
local ok, param = coroutine.resume(task.coro, table.unpack(e as {any}))
for pid = 1, #background_tasks do
handle_event(e, pid)
end
if shell_task.filter == nil or shell_task.filter == e[1] or e[1] == "terminate" then
local ok, param = coroutine.resume(shell_task.coro, table.unpack(e as {any}))
if not ok then
term.redirect(orig_native())
term.clear()
term.setCursorPos(1,1)
print("OMEGABIG OOF")
print(("pid %d"):format(pid))
error(param, 0)
-- shell died i guess?
table.insert(shell_deaths, param)
else
task.filter = param as string
shell_task.filter = param as string
end
if pid == 1 and coroutine.status(task.coro) == "dead" then
end
if coroutine.status(shell_task.coro) == "dead" then
shell_running = false
end
end
end
end
end
socket:close()
@ -140,3 +158,7 @@ term.native = orig_native
term.redirect(prev_term)
term.clear()
term.setCursorPos(1,1)
for i = 1, #shell_deaths do
print(shell_deaths[i])
end