Basalt2 update

- Finished themes
- Added state plugins for persistance
- Finished reactive plugin
- Added debug plugin (80% finished)
- Added benchmark plugin
- Added Tree, Table, List, Dropdown and Menu Elements
- Bugfixes
This commit is contained in:
Robert Jelic
2025-02-15 18:18:49 +01:00
parent 8ea3ca2465
commit db716636bd
32 changed files with 1700 additions and 165 deletions

325
src/plugins/benchmark.lua Normal file
View File

@@ -0,0 +1,325 @@
local log = require("log")
local activeProfiles = setmetatable({}, {__mode = "k"})
local function createProfile()
return {
methods = {},
}
end
local function wrapMethod(element, methodName)
local originalMethod = element[methodName]
if not activeProfiles[element] then
activeProfiles[element] = createProfile()
end
if not activeProfiles[element].methods[methodName] then
activeProfiles[element].methods[methodName] = {
calls = 0,
totalTime = 0,
minTime = math.huge,
maxTime = 0,
lastTime = 0,
startTime = 0,
path = {},
methodName = methodName,
originalMethod = originalMethod
}
end
element[methodName] = function(self, ...)
self:startProfile(methodName)
local result = originalMethod(self, ...)
self:endProfile(methodName)
return result
end
end
local BaseElement = {}
function BaseElement:startProfile(methodName)
local profile = activeProfiles[self]
if not profile then
profile = createProfile()
activeProfiles[self] = profile
end
if not profile.methods[methodName] then
profile.methods[methodName] = {
calls = 0,
totalTime = 0,
minTime = math.huge,
maxTime = 0,
lastTime = 0,
startTime = 0,
path = {},
methodName = methodName
}
end
local methodProfile = profile.methods[methodName]
methodProfile.startTime = os.clock() * 1000
methodProfile.path = {}
local current = self
while current do
table.insert(methodProfile.path, 1, current.get("name") or current.get("id"))
current = current.parent
end
return self
end
function BaseElement:endProfile(methodName)
local profile = activeProfiles[self]
if not profile or not profile.methods[methodName] then return self end
local methodProfile = profile.methods[methodName]
local endTime = os.clock() * 1000
local duration = endTime - methodProfile.startTime
methodProfile.calls = methodProfile.calls + 1
methodProfile.totalTime = methodProfile.totalTime + duration
methodProfile.minTime = math.min(methodProfile.minTime, duration)
methodProfile.maxTime = math.max(methodProfile.maxTime, duration)
methodProfile.lastTime = duration
return self
end
function BaseElement:benchmark(methodName)
if not self[methodName] then
log.error("Method " .. methodName .. " does not exist")
return self
end
activeProfiles[self] = createProfile()
activeProfiles[self].methodName = methodName
activeProfiles[self].isRunning = true
wrapMethod(self, methodName)
return self
end
function BaseElement:logBenchmark(methodName)
local profile = activeProfiles[self]
if not profile or not profile.methods[methodName] then return self end
local stats = profile.methods[methodName]
if stats then
local averageTime = stats.calls > 0 and (stats.totalTime / stats.calls) or 0
log.info(string.format(
"Benchmark results for %s.%s: " ..
"Path: %s " ..
"Calls: %d " ..
"Average time: %.2fms " ..
"Min time: %.2fms " ..
"Max time: %.2fms " ..
"Last time: %.2fms " ..
"Total time: %.2fms",
table.concat(stats.path, "."),
stats.methodName,
table.concat(stats.path, "/"),
stats.calls,
averageTime,
stats.minTime ~= math.huge and stats.minTime or 0,
stats.maxTime,
stats.lastTime,
stats.totalTime
))
end
return self
end
function BaseElement:stopBenchmark(methodName)
local profile = activeProfiles[self]
if not profile or not profile.methods[methodName] then return self end
local stats = profile.methods[methodName]
if stats and stats.originalMethod then
self[methodName] = stats.originalMethod
end
profile.methods[methodName] = nil
if not next(profile.methods) then
activeProfiles[self] = nil
end
return self
end
function BaseElement:getBenchmarkStats(methodName)
local profile = activeProfiles[self]
if not profile or not profile.methods[methodName] then return nil end
local stats = profile.methods[methodName]
return {
averageTime = stats.totalTime / stats.calls,
totalTime = stats.totalTime,
calls = stats.calls,
minTime = stats.minTime,
maxTime = stats.maxTime,
lastTime = stats.lastTime
}
end
local Container = {}
function Container:benchmarkContainer(methodName)
self:benchmark(methodName)
for _, child in pairs(self.get("children")) do
child:benchmark(methodName)
if child:isType("Container") then
child:benchmarkContainer(methodName)
end
end
return self
end
function Container:logContainerBenchmarks(methodName, depth)
depth = depth or 0
local indent = string.rep(" ", depth)
local childrenTotalTime = 0
local childrenStats = {}
for _, child in pairs(self.get("children")) do
local profile = activeProfiles[child]
if profile and profile.methods[methodName] then
local stats = profile.methods[methodName]
childrenTotalTime = childrenTotalTime + stats.totalTime
table.insert(childrenStats, {
element = child,
type = child.get("type"),
calls = stats.calls,
totalTime = stats.totalTime,
avgTime = stats.totalTime / stats.calls
})
end
end
local profile = activeProfiles[self]
if profile and profile.methods[methodName] then
local stats = profile.methods[methodName]
local selfTime = stats.totalTime - childrenTotalTime
local avgSelfTime = selfTime / stats.calls
log.info(string.format(
"%sBenchmark %s (%s): " ..
"%.2fms/call (Self: %.2fms/call) " ..
"[Total: %dms, Calls: %d]",
indent,
self.get("type"),
methodName,
stats.totalTime / stats.calls,
avgSelfTime,
stats.totalTime,
stats.calls
))
if #childrenStats > 0 then
for _, childStat in ipairs(childrenStats) do
if childStat.element:isType("Container") then
childStat.element:logContainerBenchmarks(methodName, depth + 1)
else
log.info(string.format("%s> %s: %.2fms/call [Total: %dms, Calls: %d]",
indent .. " ",
childStat.type,
childStat.avgTime,
childStat.totalTime,
childStat.calls
))
end
end
end
end
return self
end
function Container:stopContainerBenchmark(methodName)
for _, child in pairs(self.get("children")) do
if child:isType("Container") then
child:stopContainerBenchmark(methodName)
else
child:stopBenchmark(methodName)
end
end
self:stopBenchmark(methodName)
return self
end
local API = {
start = function(name, options)
options = options or {}
local profile = createProfile()
profile.name = name
profile.startTime = os.clock() * 1000
profile.custom = true
activeProfiles[name] = profile
end,
stop = function(name)
local profile = activeProfiles[name]
if not profile or not profile.custom then return end
local endTime = os.clock() * 1000
local duration = endTime - profile.startTime
profile.calls = profile.calls + 1
profile.totalTime = profile.totalTime + duration
profile.minTime = math.min(profile.minTime, duration)
profile.maxTime = math.max(profile.maxTime, duration)
profile.lastTime = duration
log.info(string.format(
"Custom Benchmark '%s': " ..
"Calls: %d " ..
"Average time: %.2fms " ..
"Min time: %.2fms " ..
"Max time: %.2fms " ..
"Last time: %.2fms " ..
"Total time: %.2fms",
name,
profile.calls,
profile.totalTime / profile.calls,
profile.minTime,
profile.maxTime,
profile.lastTime,
profile.totalTime
))
end,
getStats = function(name)
local profile = activeProfiles[name]
if not profile then return nil end
return {
averageTime = profile.totalTime / profile.calls,
totalTime = profile.totalTime,
calls = profile.calls,
minTime = profile.minTime,
maxTime = profile.maxTime,
lastTime = profile.lastTime
}
end,
clear = function(name)
activeProfiles[name] = nil
end,
clearAll = function()
for k,v in pairs(activeProfiles) do
if v.custom then
activeProfiles[k] = nil
end
end
end
}
return {
BaseElement = BaseElement,
Container = Container,
API = API
}

182
src/plugins/debug.lua Normal file
View File

@@ -0,0 +1,182 @@
local log = require("log")
local tHex = require("libraries/colorHex")
local maxLines = 10
local isVisible = false
local function createDebugger(element)
local elementInfo = {
renderCount = 0,
eventCount = {},
lastRender = os.epoch("utc"),
properties = {},
children = {}
}
return {
trackProperty = function(name, value)
elementInfo.properties[name] = value
end,
trackRender = function()
elementInfo.renderCount = elementInfo.renderCount + 1
elementInfo.lastRender = os.epoch("utc")
end,
trackEvent = function(event)
elementInfo.eventCount[event] = (elementInfo.eventCount[event] or 0) + 1
end,
dump = function()
return {
type = element.get("type"),
id = element.get("id"),
stats = elementInfo
}
end
}
end
local BaseElement = {
debug = function(self, level)
self._debugger = createDebugger(self)
self._debugLevel = level or DEBUG_LEVELS.INFO
return self
end,
dumpDebug = function(self)
if not self._debugger then return end
return self._debugger.dump()
end
}
local BaseFrame = {
showDebugLog = function(self)
if not self._debugFrame then
local width = self.get("width")
local height = self.get("height")
self._debugFrame = self:addFrame()
:setWidth(width)
:setHeight(height)
:setBackground(colors.black)
:setZ(999)
:listenEvent("mouse_scroll", true)
self._debugFrame:addButton()
:setWidth(9)
:setHeight(1)
:setX(width - 8)
:setY(height)
:setText("Close")
:setBackground(colors.red)
:onMouseClick(function()
self:hideDebugLog()
end)
self._debugFrame._scrollOffset = 0
self._debugFrame._processedLogs = {}
local function wrapText(text, width)
local lines = {}
while #text > 0 do
local line = text:sub(1, width)
table.insert(lines, line)
text = text:sub(width + 1)
end
return lines
end
local function processLogs()
local processed = {}
local width = self._debugFrame.get("width")
for _, entry in ipairs(log._logs) do
local lines = wrapText(entry.message, width)
for _, line in ipairs(lines) do
table.insert(processed, {
text = line,
level = entry.level
})
end
end
return processed
end
local totalLines = #processLogs() - self.get("height")
self._scrollOffset = totalLines
local originalRender = self._debugFrame.render
self._debugFrame.render = function(frame)
originalRender(frame)
frame._processedLogs = processLogs()
local height = frame.get("height")-2
local totalLines = #frame._processedLogs
local maxScroll = math.max(0, totalLines - height)
frame._scrollOffset = math.min(frame._scrollOffset, maxScroll)
for i = 1, height-2 do
local logIndex = i + frame._scrollOffset
local entry = frame._processedLogs[logIndex]
if entry then
local color = entry.level == log.LEVEL.ERROR and colors.red
or entry.level == log.LEVEL.WARN and colors.yellow
or entry.level == log.LEVEL.DEBUG and colors.lightGray
or colors.white
frame:textFg(2, i, entry.text, color)
end
end
end
local baseDispatchEvent = self._debugFrame.dispatchEvent
self._debugFrame.dispatchEvent = function(self, event, direction, ...)
if(event == "mouse_scroll") then
self._scrollOffset = math.max(0, self._scrollOffset + direction)
self:updateRender()
return true
else
baseDispatchEvent(self, event, direction, ...)
end
end
end
self._debugFrame.set("visible", true)
return self
end,
hideDebugLog = function(self)
if self._debugFrame then
self._debugFrame.set("visible", false)
end
return self
end,
toggleDebugLog = function(self)
if self._debugFrame and self._debugFrame:isVisible() then
self:hideDebugLog()
else
self:showDebugLog()
end
return self
end
}
local Container = {
debugChildren = function(self, level)
self:debug(level)
for _, child in pairs(self.get("children")) do
if child.debug then
child:debug(level)
end
end
return self
end
}
return {
BaseElement = BaseElement,
Container = Container,
BaseFrame = BaseFrame,
}

View File

@@ -18,14 +18,18 @@ local mathEnv = {
end
}
local function parseExpression(expr, element)
local function parseExpression(expr, element, propName)
expr = expr:gsub("^{(.+)}$", "%1")
for k,v in pairs(colors) do
if type(k) == "string" then
expr = expr:gsub("%f[%w]"..k.."%f[%W]", "colors."..k)
expr = expr:gsub("([%w_]+)%$([%w_]+)", function(obj, prop)
if obj == "self" then
return string.format('__getState("%s")', prop)
elseif obj == "parent" then
return string.format('__getParentState("%s")', prop)
else
return string.format('__getElementState("%s", "%s")', obj, prop)
end
end
end)
expr = expr:gsub("([%w_]+)%.([%w_]+)", function(obj, prop)
if protectedNames[obj] then
@@ -37,6 +41,23 @@ local function parseExpression(expr, element)
local env = setmetatable({
colors = colors,
math = math,
tostring = tostring,
tonumber = tonumber,
__getState = function(prop)
return element:getState(prop)
end,
__getParentState = function(prop)
return element.parent:getState(prop)
end,
__getElementState = function(objName, prop)
local target = element:getBaseFrame():getChild(objName)
if not target then
errorManager.header = "Reactive evaluation error"
errorManager.error("Could not find element: " .. objName)
return nil
end
return target:getState(prop).value
end,
__getProperty = function(objName, propName)
if objName == "self" then
return element.get(propName)
@@ -55,6 +76,12 @@ local function parseExpression(expr, element)
end
}, { __index = mathEnv })
if(element._properties[propName].type == "string")then
expr = "tostring(" .. expr .. ")"
elseif(element._properties[propName].type == "number")then
expr = "tonumber(" .. expr .. ")"
end
local func, err = load("return "..expr, "reactive", "t", env)
if not func then
errorManager.header = "Reactive evaluation error"
@@ -68,7 +95,8 @@ end
local function validateReferences(expr, element)
for ref in expr:gmatch("([%w_]+)%.") do
if not protectedNames[ref] then
if ref == "parent" then
if ref == "self" then
elseif ref == "parent" then
if not element.parent then
errorManager.header = "Reactive evaluation error"
errorManager.error("No parent element available")
@@ -87,12 +115,19 @@ local function validateReferences(expr, element)
return true
end
local functionCache = {}
local observerCache = setmetatable({}, {__mode = "k"})
local functionCache = setmetatable({}, {__mode = "k"})
local function setupObservers(element, expr)
if observerCache[element] then
for _, observer in ipairs(observerCache[element]) do
local observerCache = setmetatable({}, {
__mode = "k",
__index = function(t, k)
t[k] = {}
return t[k]
end
})
local function setupObservers(element, expr, propertyName)
if observerCache[element][propertyName] then
for _, observer in ipairs(observerCache[element][propertyName]) do
observer.target:removeObserver(observer.property, observer.callback)
end
end
@@ -123,7 +158,7 @@ local function setupObservers(element, expr)
end
end
observerCache[element] = observers
observerCache[element][propertyName] = observers
end
PropertySystem.addSetterHook(function(element, propertyName, value, config)
@@ -133,15 +168,18 @@ PropertySystem.addSetterHook(function(element, propertyName, value, config)
return config.default
end
setupObservers(element, expr)
setupObservers(element, expr, propertyName)
if not functionCache[value] then
local parsedFunc = parseExpression(value, element)
functionCache[value] = parsedFunc
if not functionCache[element] then
functionCache[element] = {}
end
if not functionCache[element][value] then
local parsedFunc = parseExpression(value, element, propertyName)
functionCache[element][value] = parsedFunc
end
return function(self)
local success, result = pcall(functionCache[value])
local success, result = pcall(functionCache[element][value])
if not success then
errorManager.header = "Reactive evaluation error"
if type(result) == "string" then
@@ -161,8 +199,10 @@ local BaseElement = {}
BaseElement.hooks = {
destroy = function(self)
if observerCache[self] then
for _, observer in ipairs(observerCache[self]) do
observer.target:observe(observer.property, observer.callback)
for propName, observers in pairs(observerCache[self]) do
for _, observer in ipairs(observers) do
observer.target:removeObserver(observer.property, observer.callback)
end
end
observerCache[self] = nil
end

135
src/plugins/state.lua Normal file
View File

@@ -0,0 +1,135 @@
local PropertySystem = require("propertySystem")
local errorManager = require("errorManager")
local BaseElement = {}
function BaseElement.setup(element)
element.defineProperty(element, "states", {default = {}, type = "table"})
element.defineProperty(element, "computedStates", {default = {}, type = "table"})
element.defineProperty(element, "stateUpdate", {
default = {key = "", value = nil, oldValue = nil},
type = "table"
})
end
function BaseElement:initializeState(name, default, canTriggerRender, persist, path)
local states = self.get("states")
if states[name] then
errorManager.error("State '" .. name .. "' already exists")
return self
end
if persist then
local file = path or ("states/" .. self.get("name") .. "_" .. name .. ".state")
if fs.exists(file) then
local f = fs.open(file, "r")
states[name] = {
value = textutils.unserialize(f.readAll()),
persist = true,
file = file
}
f.close()
else
states[name] = {
value = default,
persist = true,
file = file,
canTriggerRender = canTriggerRender
}
end
else
states[name] = {
value = default,
canTriggerRender = canTriggerRender
}
end
return self
end
function BaseElement:setState(name, value)
local states = self.get("states")
if not states[name] then
error("State '"..name.."' not initialized")
end
local oldValue = states[name].value
states[name].value = value
if states[name].persist then
local dir = fs.getDir(states[name].file)
if not fs.exists(dir) then
fs.makeDir(dir)
end
local f = fs.open(states[name].file, "w")
f.write(textutils.serialize(value))
f.close()
end
if states[name].canTriggerRender then
self:updateRender()
end
self.set("stateUpdate", {
key = name,
value = value,
oldValue = oldValue
})
return self
end
function BaseElement:getState(name)
local states = self.get("states")
if not states[name] then
errorManager.error("State '"..name.."' not initialized")
end
return states[name].value
end
function BaseElement:computed(key, computeFn)
local computed = self.get("computedStates")
computed[key] = setmetatable({}, {
__call = function()
return computeFn(self)
end
})
return self
end
function BaseElement:shareState(stateKey, ...)
local value = self:getState(stateKey)
for _, element in ipairs({...}) do
if element.get("states")[stateKey] then
errorManager.error("Cannot share state '" .. stateKey .. "': Target element already has this state")
return self
end
element:initializeState(stateKey, value)
self:observe("stateUpdate", function(self, update)
if update.key == stateKey then
element:setState(stateKey, update.value)
end
end)
end
return self
end
function BaseElement:onStateChange(stateName, callback)
if not self.get("states")[stateName] then
errorManager.error("Cannot observe state '" .. stateName .. "': State not initialized")
return self
end
self:observe("stateUpdate", function(self, update)
if update.key == stateName then
callback(self, update.value, update.oldValue)
end
end)
return self
end
return {
BaseElement = BaseElement
}

View File

@@ -1,33 +1,36 @@
-- Has to be reworked
local Theme = {}
local defaultTheme = {
colors = {
primary = colors.blue,
secondary = colors.cyan,
background = colors.black,
text = colors.white,
borders = colors.gray,
error = colors.red,
success = colors.green,
default = {
background = colors.lightGray,
foreground = colors.black,
},
elementStyles = {
Button = {
background = "background",
foreground = "text",
activeBackground = "primary",
activeForeground = "text",
},
Input = {
background = "background",
foreground = "text",
focusBackground = "primary",
focusForeground = "text",
},
BaseFrame = {
background = colors.white,
foreground = colors.black,
Frame = {
background = "background",
foreground = "text"
background = colors.gray,
Button = {
background = "{self.clicked and colors.black or colors.blue}",
foreground = "{self.clicked and colors.blue or colors.white}"
}
},
Button = {
background = "{self.clicked and colors.black or colors.cyan}",
foreground = "{self.clicked and colors.cyan or colors.black}"
},
Input = {
background = "{self.focused and colors.cyan or colors.lightGray}",
foreground = colors.black,
placeholderColor = colors.gray
},
List = {
background = colors.cyan,
foreground = colors.black,
selectedColor = colors.blue
}
}
}
@@ -38,10 +41,6 @@ local themes = {
local currentTheme = "default"
function Theme.registerTheme(name, theme)
themes[name] = theme
end
local function resolveThemeValue(value, theme)
if type(value) == "string" and theme.colors[value] then
return theme.colors[value]
@@ -49,10 +48,50 @@ local function resolveThemeValue(value, theme)
return value
end
local function getThemeForElement(element)
local path = {}
local current = element
while current do
table.insert(path, 1, current.get("type"))
current = current.parent
end
local result = {}
local current = defaultTheme
for _, elementType in ipairs(path) do
if current[elementType] then
for k,v in pairs(current[elementType]) do
result[k] = v
end
current = current[elementType]
end
end
return result
end
local function applyTheme(element, props)
local theme = getThemeForElement(element)
if props then
for k,v in pairs(props) do
theme[k] = v
end
end
for k,v in pairs(theme) do
if element:getPropertyConfig(k) then
element.set(k, v)
end
end
end
local BaseElement = {
hooks = {
init = function(self)
-- Theme Properties für das Element registrieren
self.defineProperty(self, "theme", {
default = currentTheme,
type = "string",
@@ -68,7 +107,7 @@ local BaseElement = {
function BaseElement:applyTheme(themeName)
local theme = themes[themeName] or themes.default
local elementType = self.get("type")
if theme.elementStyles[elementType] then
local styles = theme.elementStyles[elementType]
for prop, value in pairs(styles) do
@@ -79,21 +118,67 @@ function BaseElement:applyTheme(themeName)
end
end
local BaseFrame = {
hooks = {
init = function(self)
applyTheme(self)
end
}
}
local Container = {
hooks = {
addChild = function(self, child)
if self.get("themeInherit") then
child.set("theme", self.get("theme"))
hooks = {
init = function(self)
for k, _ in pairs(self.basalt.getElementManager().getElementList()) do
local capitalizedName = k:sub(1,1):upper() .. k:sub(2)
if capitalizedName ~= "BaseFrame" then
local methodName = "add"..capitalizedName
local original = self[methodName]
if original then
self[methodName] = function(self, name, props)
if type(name) == "table" then
props = name
name = nil
end
local element = original(self, name)
applyTheme(element, props)
return element
end
end
end
end
end
}
}
function Container.setup(element)
element.defineProperty(element, "themeInherit", {default = true, type = "boolean"})
end
local themeAPI = {
setTheme = function(newTheme)
defaultTheme = newTheme
end,
return {
BaseElement = BaseElement,
Container = Container,
getTheme = function()
return defaultTheme
end,
loadTheme = function(path)
local file = fs.open(path, "r")
if file then
local content = file.readAll()
file.close()
defaultTheme = textutils.unserializeJSON(content)
end
end
}
local Theme = {
setup = function(basalt)
basalt.setTheme(defaultTheme)
end,
BaseElement = BaseElement,
BaseFrame = BaseFrame,
Container = Container,
API = themeAPI
}
return Theme

View File

@@ -35,7 +35,7 @@ local function parseXML(self, xmlString)
tag.children = {}
tag.content = ""
table.insert(current.children, tag)
if not line:match("/>$") then
table.insert(stack, current)
current = tag