Implement framebuffer and mock endpoint

This commit is contained in:
Kai Vogelgesang 2022-09-20 12:16:46 +02:00
parent 92496c8b8e
commit 1fde73778b
Signed by: kai
GPG Key ID: 0A95D3B6E62C0879
14 changed files with 872 additions and 0 deletions

18
lua/cc.d.tl Normal file
View File

@ -0,0 +1,18 @@
global sleep: function(time: number)
global write: function(text: string): number
--global print: function(...: any): number
global printError: function(...: any)
--global type ReadCompletionFunction = function(partial: string): { string } | nil
--global read: function(replaceChar: string | nil, history: table | nil, completeFn: ReadCompletionFunction | nil, default: string | nil): string
global _HOST: string
global _CC_DEFAULT_SETTINGS: string
require("types/colors")
require("types/term")
require("types/parallel")
require("types/http")
require("types/shell")
require("types/window")

132
lua/framebuffer.tl Normal file
View File

@ -0,0 +1,132 @@
local record ScreenContent
x: integer
y: integer
width: integer
height: integer
blink: boolean
fg: integer
text: {string}
fg_color: {string}
bg_color: {string}
palette: {integer}
end
local record Buffer
target: term.Redirect
serialize: function(): ScreenContent
is_dirty: function(): boolean
clear_dirty: function()
end
local COLOR_LOOKUP <const> : {number: integer} = {
[colors.white] = 0x0,
[colors.orange] = 0x1,
[colors.magenta] = 0x2,
[colors.lightBlue] = 0x3,
[colors.yellow] = 0x4,
[colors.lime] = 0x5,
[colors.pink] = 0x6,
[colors.gray] = 0x7,
[colors.lightGray] = 0x8,
[colors.cyan] = 0x9,
[colors.purple] = 0xA,
[colors.blue] = 0xB,
[colors.brown] = 0xC,
[colors.green] = 0xD,
[colors.red] = 0xE,
[colors.black] = 0xF,
}
local function wrap(parent: term.Redirect): Buffer
local x, y = parent.getCursorPos()
local width, height = parent.getSize()
local blink = parent.getCursorBlink()
local fg = COLOR_LOOKUP[parent.getTextColor()]
local palette: {number} = {}
for c = 0, 15 do
palette[c+1] = colors.packRGB(parent.getPaletteColor(2^c))
end
local win = window.create(parent, 1, 1, width, height)
local overrides: table = {}
overrides.setCursorPos = function(new_x: integer, new_y: integer)
win.setCursorPos(new_x, new_y)
x = new_x
y = new_y
end
overrides.setCursorBlink = function(new_blink: boolean)
win.setCursorBlink(new_blink)
blink = new_blink
end
overrides.setTextColor = function(new_color: number)
local r = { pcall(win.setTextColor, new_color) }
if not r[1] then
error((r[2] as string):sub(8))
end
fg = COLOR_LOOKUP[new_color]
end
overrides.setTextColour = overrides.setTextColor
overrides.setPaletteColor = function(color: number, r_rgb: number, g: number | nil, b: number | nil)
local r = { pcall(win.setPaletteColor, color, r_rgb, g, b) }
if not r[1] then
error((r[2] as string):sub(8))
end
local index = COLOR_LOOKUP[color]
if g == nil then
palette[1 + index] = r_rgb
else
palette[1 + index] = colors.packRGB(r_rgb, g, b)
end
end
overrides.setPaletteColour = overrides.setPaletteColor
local target = setmetatable(overrides, { __index = win }) as term.Redirect
target.setTextColor(colors.white)
target.setBackgroundColor(colors.black)
target.setCursorPos(1,1)
target.clear()
local buffer: Buffer = {
target = target
}
buffer.serialize = function(): ScreenContent
local text: {string} = {}
local fg_color: {string} = {}
local bg_color: {string} = {}
for i = 1, height do
local t, f, b = win.getLine(i)
table.insert(text, t)
table.insert(fg_color, f)
table.insert(bg_color, b)
end
return {
x = x,
y = y,
width = width,
height = height,
blink = blink,
fg = fg,
text = text,
fg_color = fg_color,
bg_color = bg_color,
palette = palette
}
end
buffer.is_dirty = function(): boolean
return true
end
buffer.clear_dirty = function() end
return buffer
end
return { wrap = wrap }

6
lua/json.d.tl Normal file
View File

@ -0,0 +1,6 @@
local record Json
encode: function(value: any): string
decode: function(str: string): any
end
return Json

388
lua/json.lua Normal file
View File

@ -0,0 +1,388 @@
--
-- json.lua
--
-- Copyright (c) 2020 rxi
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy of
-- this software and associated documentation files (the "Software"), to deal in
-- the Software without restriction, including without limitation the rights to
-- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
-- of the Software, and to permit persons to whom the Software is furnished to do
-- so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in all
-- copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-- SOFTWARE.
--
local json = { _version = "0.1.2" }
-------------------------------------------------------------------------------
-- Encode
-------------------------------------------------------------------------------
local encode
local escape_char_map = {
[ "\\" ] = "\\",
[ "\"" ] = "\"",
[ "\b" ] = "b",
[ "\f" ] = "f",
[ "\n" ] = "n",
[ "\r" ] = "r",
[ "\t" ] = "t",
}
local escape_char_map_inv = { [ "/" ] = "/" }
for k, v in pairs(escape_char_map) do
escape_char_map_inv[v] = k
end
local function escape_char(c)
return "\\" .. (escape_char_map[c] or string.format("u%04x", c:byte()))
end
local function encode_nil(val)
return "null"
end
local function encode_table(val, stack)
local res = {}
stack = stack or {}
-- Circular reference?
if stack[val] then error("circular reference") end
stack[val] = true
if rawget(val, 1) ~= nil or next(val) == nil then
-- Treat as array -- check keys are valid and it is not sparse
local n = 0
for k in pairs(val) do
if type(k) ~= "number" then
error("invalid table: mixed or invalid key types")
end
n = n + 1
end
if n ~= #val then
error("invalid table: sparse array")
end
-- Encode
for i, v in ipairs(val) do
table.insert(res, encode(v, stack))
end
stack[val] = nil
return "[" .. table.concat(res, ",") .. "]"
else
-- Treat as an object
for k, v in pairs(val) do
if type(k) ~= "string" then
error("invalid table: mixed or invalid key types")
end
table.insert(res, encode(k, stack) .. ":" .. encode(v, stack))
end
stack[val] = nil
return "{" .. table.concat(res, ",") .. "}"
end
end
local function encode_string(val)
return '"' .. val:gsub('[%z\1-\31\\"]', escape_char) .. '"'
end
local function encode_number(val)
-- Check for NaN, -inf and inf
if val ~= val or val <= -math.huge or val >= math.huge then
error("unexpected number value '" .. tostring(val) .. "'")
end
return string.format("%.14g", val)
end
local type_func_map = {
[ "nil" ] = encode_nil,
[ "table" ] = encode_table,
[ "string" ] = encode_string,
[ "number" ] = encode_number,
[ "boolean" ] = tostring,
}
encode = function(val, stack)
local t = type(val)
local f = type_func_map[t]
if f then
return f(val, stack)
end
error("unexpected type '" .. t .. "'")
end
function json.encode(val)
return ( encode(val) )
end
-------------------------------------------------------------------------------
-- Decode
-------------------------------------------------------------------------------
local parse
local function create_set(...)
local res = {}
for i = 1, select("#", ...) do
res[ select(i, ...) ] = true
end
return res
end
local space_chars = create_set(" ", "\t", "\r", "\n")
local delim_chars = create_set(" ", "\t", "\r", "\n", "]", "}", ",")
local escape_chars = create_set("\\", "/", '"', "b", "f", "n", "r", "t", "u")
local literals = create_set("true", "false", "null")
local literal_map = {
[ "true" ] = true,
[ "false" ] = false,
[ "null" ] = nil,
}
local function next_char(str, idx, set, negate)
for i = idx, #str do
if set[str:sub(i, i)] ~= negate then
return i
end
end
return #str + 1
end
local function decode_error(str, idx, msg)
local line_count = 1
local col_count = 1
for i = 1, idx - 1 do
col_count = col_count + 1
if str:sub(i, i) == "\n" then
line_count = line_count + 1
col_count = 1
end
end
error( string.format("%s at line %d col %d", msg, line_count, col_count) )
end
local function codepoint_to_utf8(n)
-- http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&id=iws-appendixa
local f = math.floor
if n <= 0x7f then
return string.char(n)
elseif n <= 0x7ff then
return string.char(f(n / 64) + 192, n % 64 + 128)
elseif n <= 0xffff then
return string.char(f(n / 4096) + 224, f(n % 4096 / 64) + 128, n % 64 + 128)
elseif n <= 0x10ffff then
return string.char(f(n / 262144) + 240, f(n % 262144 / 4096) + 128,
f(n % 4096 / 64) + 128, n % 64 + 128)
end
error( string.format("invalid unicode codepoint '%x'", n) )
end
local function parse_unicode_escape(s)
local n1 = tonumber( s:sub(1, 4), 16 )
local n2 = tonumber( s:sub(7, 10), 16 )
-- Surrogate pair?
if n2 then
return codepoint_to_utf8((n1 - 0xd800) * 0x400 + (n2 - 0xdc00) + 0x10000)
else
return codepoint_to_utf8(n1)
end
end
local function parse_string(str, i)
local res = ""
local j = i + 1
local k = j
while j <= #str do
local x = str:byte(j)
if x < 32 then
decode_error(str, j, "control character in string")
elseif x == 92 then -- `\`: Escape
res = res .. str:sub(k, j - 1)
j = j + 1
local c = str:sub(j, j)
if c == "u" then
local hex = str:match("^[dD][89aAbB]%x%x\\u%x%x%x%x", j + 1)
or str:match("^%x%x%x%x", j + 1)
or decode_error(str, j - 1, "invalid unicode escape in string")
res = res .. parse_unicode_escape(hex)
j = j + #hex
else
if not escape_chars[c] then
decode_error(str, j - 1, "invalid escape char '" .. c .. "' in string")
end
res = res .. escape_char_map_inv[c]
end
k = j + 1
elseif x == 34 then -- `"`: End of string
res = res .. str:sub(k, j - 1)
return res, j + 1
end
j = j + 1
end
decode_error(str, i, "expected closing quote for string")
end
local function parse_number(str, i)
local x = next_char(str, i, delim_chars)
local s = str:sub(i, x - 1)
local n = tonumber(s)
if not n then
decode_error(str, i, "invalid number '" .. s .. "'")
end
return n, x
end
local function parse_literal(str, i)
local x = next_char(str, i, delim_chars)
local word = str:sub(i, x - 1)
if not literals[word] then
decode_error(str, i, "invalid literal '" .. word .. "'")
end
return literal_map[word], x
end
local function parse_array(str, i)
local res = {}
local n = 1
i = i + 1
while 1 do
local x
i = next_char(str, i, space_chars, true)
-- Empty / end of array?
if str:sub(i, i) == "]" then
i = i + 1
break
end
-- Read token
x, i = parse(str, i)
res[n] = x
n = n + 1
-- Next token
i = next_char(str, i, space_chars, true)
local chr = str:sub(i, i)
i = i + 1
if chr == "]" then break end
if chr ~= "," then decode_error(str, i, "expected ']' or ','") end
end
return res, i
end
local function parse_object(str, i)
local res = {}
i = i + 1
while 1 do
local key, val
i = next_char(str, i, space_chars, true)
-- Empty / end of object?
if str:sub(i, i) == "}" then
i = i + 1
break
end
-- Read key
if str:sub(i, i) ~= '"' then
decode_error(str, i, "expected string for key")
end
key, i = parse(str, i)
-- Read ':' delimiter
i = next_char(str, i, space_chars, true)
if str:sub(i, i) ~= ":" then
decode_error(str, i, "expected ':' after key")
end
i = next_char(str, i + 1, space_chars, true)
-- Read value
val, i = parse(str, i)
-- Set
res[key] = val
-- Next token
i = next_char(str, i, space_chars, true)
local chr = str:sub(i, i)
i = i + 1
if chr == "}" then break end
if chr ~= "," then decode_error(str, i, "expected '}' or ','") end
end
return res, i
end
local char_func_map = {
[ '"' ] = parse_string,
[ "0" ] = parse_number,
[ "1" ] = parse_number,
[ "2" ] = parse_number,
[ "3" ] = parse_number,
[ "4" ] = parse_number,
[ "5" ] = parse_number,
[ "6" ] = parse_number,
[ "7" ] = parse_number,
[ "8" ] = parse_number,
[ "9" ] = parse_number,
[ "-" ] = parse_number,
[ "t" ] = parse_literal,
[ "f" ] = parse_literal,
[ "n" ] = parse_literal,
[ "[" ] = parse_array,
[ "{" ] = parse_object,
}
parse = function(str, idx)
local chr = str:sub(idx, idx)
local f = char_func_map[chr]
if f then
return f(str, idx)
end
decode_error(str, idx, "unexpected character '" .. chr .. "'")
end
function json.decode(str)
if type(str) ~= "string" then
error("expected argument of type string, got " .. type(str))
end
local res, idx = parse(str, next_char(str, 1, space_chars, true))
idx = next_char(str, idx, space_chars, true)
if idx <= #str then
decode_error(str, idx, "trailing garbage")
end
return res
end
return json

35
lua/main.tl Normal file
View File

@ -0,0 +1,35 @@
local json = require("json")
local fb = require("framebuffer")
local ENDPOINT <const> = "http://localhost:8000/monitoring"
local orig_native = term.native
local buffer = fb.wrap(orig_native())
term.native = function(): term.Redirect
return buffer.target
end
term.redirect(buffer.target as term.Redirect)
local function report()
while true do
local body = json.encode({
screen = buffer.serialize()
})
local headers = {
["Content-Type"] = "application/json"
}
local r = { pcall(http.post, ENDPOINT .. "/ping", body, headers) }
sleep(1)
end
end
local function run_shell()
shell.run("shell")
end
parallel.waitForAny(report, run_shell)
term.native = orig_native
term.redirect(term.native())

4
lua/tlconfig.lua Normal file
View File

@ -0,0 +1,4 @@
return {
global_env_def = "cc",
gen_target = "5.1",
}

51
lua/types/colors.d.tl Normal file
View File

@ -0,0 +1,51 @@
global record colors
white: number
orange: number
magenta: number
lightBlue: number
yellow: number
lime: number
pink: number
gray: number
lightGray: number
cyan: number
purple: number
blue: number
brown: number
green: number
red: number
black: number
combine: function(...: number): number
subtract: function(colors: number, ...: number): number
test: function(colors: number, color: number): boolean
packRGB: function(r: number, g: number, b: number): number
unpackRGB: function(rgb: number): number, number, number
toBlit: function(color: number): string
end
global record colours
white: number
orange: number
magenta: number
lightBlue: number
yellow: number
lime: number
pink: number
grey: number
lightGrey: number
cyan: number
purple: number
blue: number
brown: number
green: number
red: number
black: number
combine: function(...: number): number
subtract: function(colors: number, ...: number): number
test: function(colors: number, color: number): boolean
packRGB: function(r: number, g: number, b: number): number
unpackRGB: function(rgb: number): number, number, number
toBlit: function(color: number): string
end

70
lua/types/http.d.tl Normal file
View File

@ -0,0 +1,70 @@
global record http
record Response
getResponseCode: function(): integer, string
getResponseHeaders: function(): {string: string}
read: function(count: integer | nil): integer, string | nil
readAll: function(): string | nil
readLine: function(withTrailing: boolean | nil): string | nil
seek: function(
whence: string | nil,
offset: integer | nil
): integer | nil, nil | string
close: function()
end
record _RequestParams
url: string
body: string | nil
headers: {string: string} | nil
binary: boolean | nil
method: string | nil
redirect: boolean | nil
end
request: function(
url_or_params: string | _RequestParams,
body: string | nil,
headers: {string: string} | nil,
binary: boolean | nil
)
record _GetParams
url: string
headers: {string: string} | nil
binary: boolean | nil
method: string | nil
redirect: boolean | nil
end
get: function(
url_or_params: string | _GetParams,
headers: {string: string} | nil,
binary: boolean | nil
): Response | nil, nil | string, nil | Response
post: function(
url_or_params: string | _RequestParams,
body: string | nil,
headers: {string: string} | nil,
binary: boolean | nil
): Response | nil, nil | string, nil | Response
checkURLAsync: function(url: string): boolean, string | nil
checkURL: function(url: string): boolean, string | nil
record Websocket
receive: function(timeout: number | nil): string | nil, nil | boolean
send: function(message: any, binary: boolean | nil)
close: function()
end
websocket: function(
url: string,
headers: {string: string} | nil
): Websocket | boolean, nil | string
websocketAsync: function(
url: string,
headers: {string: string} | nil
)
end

4
lua/types/parallel.d.tl Normal file
View File

@ -0,0 +1,4 @@
global record parallel
waitForAny: function(...: function)
waitForAll: function(...: function)
end

33
lua/types/shell.d.tl Normal file
View File

@ -0,0 +1,33 @@
global record shell
execute: function(command: string, ...: string): boolean
run: function(...: string): boolean
exit: function()
dir: function(): string
setDir: function(dir: string)
path: function(): string
setPath: function(path: string)
resolve: function(path: string): string
resolveProgram: function(command: string): string | nil
programs: function(include_hidden: boolean | nil): {string}
complete: function(sLine: string): {string} | nil
completeProgram: function(program: string): {string}
type _CompletionFunction = function(
shell: table,
index: integer,
argument: string,
previous: {string}
): {string} | nil
setCompletionFunction: function(program: string, complete: _CompletionFunction)
record _CompletionInfo
fnComplete: function
end
getCompletionInfo: function(): {string: _CompletionInfo}
getRunningProgram: function(): string
setAlias: function(command: string, program: string)
clearAlias: function(command: string)
aliases: function(): {string:string}
openTab: function(...: string): integer
switchTab: function(id: integer)
end

65
lua/types/term.d.tl Normal file
View File

@ -0,0 +1,65 @@
global record term
record Redirect
write: function(text: string)
blit: function(text: string, textColor: string, backgroundColor: string)
scroll: function(y: integer)
clear: function()
clearLine: function()
getCursorPos: function(): integer, integer
setCursorPos: function(x: integer, y: integer)
getCursorBlink: function(): boolean
setCursorBlink: function(blink: boolean)
getSize: function(): integer, integer
isColor: function(): boolean
isColour: function(): boolean
getTextColor: function(): number
getTextColour: function(): number
setTextColor: function(color: number)
setTextColour: function(colour: number)
getBackgroundColor: function(): number
getBackgroundColour: function(): number
setBackgroundColor: function(color: number)
setBackgroundColour: function(colour: number)
getPaletteColor: function(color: number): number, number, number
getPaletteColour: function(colour: number): number, number, number
setPaletteColour: function(color: number, r_rgb: number, g: number | nil, b: number | nil)
setPaletteColor: function(colour: number, r_rgb: number, g: number | nil, b: number | nil)
end
write: function(text: string)
blit: function(text: string, textColor: string, backgroundColor: string)
scroll: function(y: integer)
clear: function()
clearLine: function()
getCursorPos: function(): integer, integer
setCursorPos: function(x: integer, y: integer)
getCursorBlink: function(): boolean
setCursorBlink: function(blink: boolean)
getSize: function(): integer, integer
isColor: function(): boolean
isColour: function(): boolean
getTextColor: function(): number
getTextColour: function(): number
setTextColor: function(color: number)
setTextColour: function(colour: number)
getBackgroundColor: function(): number
getBackgroundColour: function(): number
setBackgroundColor: function(color: number)
setBackgroundColour: function(colour: number)
getPaletteColor: function(color: number): number, number, number
getPaletteColour: function(colour: number): number, number, number
setPaletteColour: function(color: number, r_rgb: number, g: number | nil, b: number | nil)
setPaletteColor: function(colour: number, r_rgb: number, g: number | nil, b: number | nil)
nativePaletteColor: function(color: number): number, number, number
nativePaletteColour: function(colour: number): number, number, number
redirect: function(target: Redirect): Redirect
current: function(): Redirect
native: function(): Redirect
end

39
lua/types/window.d.tl Normal file
View File

@ -0,0 +1,39 @@
global record window
record Window
write: function(text: string)
blit: function(text: string, textColor: string, backgroundColor: string)
scroll: function(y: integer)
clear: function()
clearLine: function()
getCursorPos: function(): integer, integer
setCursorPos: function(x: integer, y: integer)
getCursorBlink: function(): boolean
setCursorBlink: function(blink: boolean)
getSize: function(): integer, integer
isColor: function(): boolean
isColour: function(): boolean
getTextColor: function(): number
getTextColour: function(): number
setTextColor: function(color: number)
setTextColour: function(colour: number)
getBackgroundColor: function(): number
getBackgroundColour: function(): number
setBackgroundColor: function(color: number)
setBackgroundColour: function(colour: number)
getPaletteColor: function(color: number): number, number, number
getPaletteColour: function(colour: number): number, number, number
setPaletteColour: function(color: number, r_rgb: number, g: number | nil, b: number | nil)
setPaletteColor: function(colour: number, r_rgb: number, g: number | nil, b: number | nil)
getLine: function(y: integer): string, string, string
setVisible: function(visible: boolean)
isVisible: function(): boolean
redraw: function()
getPosition: function(): integer, integer
reposition: function(new_x: integer, new_y: integer, new_width: integer | nil, new_height: integer | nil, new_parent: term.Redirect | nil)
end
create: function(parent: term.Redirect, x: integer, y: integer, width: integer, height: integer, startVisible: boolean | nil): Window
end

View File

@ -6,12 +6,14 @@ from .settings import settings
from .user import user_auth
from .map_tiles import map_tiles, map_meta
from .templates import j2env
from .monitoring import monitoring
app = FastAPI()
app.mount("/user/", user_auth)
app.mount("/map/", map_meta)
app.mount("/tiles/", map_tiles)
app.mount("/monitoring/", monitoring)
frontend = FastAPI()

View File

@ -0,0 +1,25 @@
import binascii
from fastapi import FastAPI, Request
from pydantic import BaseModel
monitoring = FastAPI()
class ScreenContent(BaseModel):
x: int
y: int
width: int
height: int
blink: bool
fg: int
text: list[str]
fg_color: list[str]
bg_color: list[str]
class Ping(BaseModel):
screen: ScreenContent
@monitoring.post("/ping")
async def ping(request: Request, data: Ping):
print("[PING]")
for line in data.screen.text:
print(line)