Compare commits
4
Commits
4bf42d9179
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a8364972da
|
||
|
|
9587d1ed49
|
||
|
|
0fc96b243a
|
||
|
|
e71907ea86
|
No files matched your search
+31
-1
@@ -40,9 +40,26 @@ else()
|
||||
set(_lua_cflags "-I${LUA_INCLUDE_DIR}")
|
||||
string(REPLACE ";" " " _lua_libs "${LUA_LIBRARIES}")
|
||||
endif()
|
||||
set(LUACPP_RUNTIME_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/include")
|
||||
set(LUACPP_RUNTIME_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/include" CACHE PATH
|
||||
"Directory holding the luacpp runtime headers (include/luacpp/*.hpp)")
|
||||
set(LUACPP_LUA_CFLAGS "${_lua_cflags}")
|
||||
set(LUACPP_LUA_LIBS "${_lua_libs}")
|
||||
|
||||
# --- optional GUI backend -----------------------------------------------------
|
||||
# Programs compiled with `luacpp run` get a global `gui` table (window, drawing
|
||||
# primitives, events) when SDL2 is available. Without SDL2 nothing changes.
|
||||
pkg_check_modules(SDL2 QUIET sdl2)
|
||||
if(SDL2_FOUND)
|
||||
execute_process(COMMAND ${PKG_CONFIG_EXECUTABLE} --cflags sdl2
|
||||
OUTPUT_VARIABLE _sdl_cflags OUTPUT_STRIP_TRAILING_WHITESPACE)
|
||||
execute_process(COMMAND ${PKG_CONFIG_EXECUTABLE} --libs sdl2
|
||||
OUTPUT_VARIABLE _sdl_libs OUTPUT_STRIP_TRAILING_WHITESPACE)
|
||||
set(LUACPP_GUI_FLAGS "-DLUACPP_HAS_GUI=1 ${_sdl_cflags} ${_sdl_libs}")
|
||||
message(STATUS "luacpp: SDL2 found, compiled programs get the 'gui' API")
|
||||
else()
|
||||
set(LUACPP_GUI_FLAGS "")
|
||||
message(STATUS "luacpp: SDL2 not found, the 'gui' API is disabled")
|
||||
endif()
|
||||
configure_file(cmake/luacpp-config.hpp.in
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/generated/luacpp-config.hpp" @ONLY)
|
||||
|
||||
@@ -57,6 +74,19 @@ endif()
|
||||
|
||||
include(cmake/lua-package.cmake)
|
||||
|
||||
# --- install ------------------------------------------------------------------
|
||||
# `cmake --install build --prefix <dir>` produces a relocatable tree:
|
||||
# <dir>/bin/luacpp, <dir>/include/luacpp/*.hpp, <dir>/share/luacpp/examples
|
||||
# `luacpp run` looks for include/ next to its own binary, so the tree can be moved.
|
||||
include(GNUInstallDirs)
|
||||
install(TARGETS luacpp RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}")
|
||||
install(FILES include/luacpp/rt.hpp include/luacpp/gui.hpp
|
||||
DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/luacpp")
|
||||
install(DIRECTORY Demo/
|
||||
DESTINATION "${CMAKE_INSTALL_DATADIR}/luacpp/examples"
|
||||
PATTERN "build" EXCLUDE)
|
||||
install(FILES README.md DESTINATION "${CMAKE_INSTALL_DATADIR}/doc/luacpp")
|
||||
|
||||
if(LUACPP_BUILD_TESTS)
|
||||
enable_testing()
|
||||
add_subdirectory(tests)
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
-- 5x7 bitmap font drawn with filled rectangles, so a compiled Lua program can
|
||||
-- label its interface without linking any font library.
|
||||
local M = {}
|
||||
|
||||
local GLYPH_WIDTH = 5
|
||||
local GLYPH_HEIGHT = 7
|
||||
local SPACING = 1
|
||||
|
||||
local GLYPHS = {
|
||||
[" "] = { "00000", "00000", "00000", "00000", "00000", "00000", "00000" },
|
||||
["A"] = { "01110", "10001", "10001", "11111", "10001", "10001", "10001" },
|
||||
["B"] = { "11110", "10001", "10001", "11110", "10001", "10001", "11110" },
|
||||
["C"] = { "01110", "10001", "10000", "10000", "10000", "10001", "01110" },
|
||||
["D"] = { "11110", "10001", "10001", "10001", "10001", "10001", "11110" },
|
||||
["E"] = { "11111", "10000", "10000", "11110", "10000", "10000", "11111" },
|
||||
["F"] = { "11111", "10000", "10000", "11110", "10000", "10000", "10000" },
|
||||
["G"] = { "01110", "10001", "10000", "10111", "10001", "10001", "01111" },
|
||||
["H"] = { "10001", "10001", "10001", "11111", "10001", "10001", "10001" },
|
||||
["I"] = { "01110", "00100", "00100", "00100", "00100", "00100", "01110" },
|
||||
["J"] = { "00111", "00010", "00010", "00010", "00010", "10010", "01100" },
|
||||
["K"] = { "10001", "10010", "10100", "11000", "10100", "10010", "10001" },
|
||||
["L"] = { "10000", "10000", "10000", "10000", "10000", "10000", "11111" },
|
||||
["M"] = { "10001", "11011", "10101", "10101", "10001", "10001", "10001" },
|
||||
["N"] = { "10001", "11001", "10101", "10011", "10001", "10001", "10001" },
|
||||
["O"] = { "01110", "10001", "10001", "10001", "10001", "10001", "01110" },
|
||||
["P"] = { "11110", "10001", "10001", "11110", "10000", "10000", "10000" },
|
||||
["Q"] = { "01110", "10001", "10001", "10001", "10101", "10010", "01101" },
|
||||
["R"] = { "11110", "10001", "10001", "11110", "10100", "10010", "10001" },
|
||||
["S"] = { "01111", "10000", "10000", "01110", "00001", "00001", "11110" },
|
||||
["T"] = { "11111", "00100", "00100", "00100", "00100", "00100", "00100" },
|
||||
["U"] = { "10001", "10001", "10001", "10001", "10001", "10001", "01110" },
|
||||
["V"] = { "10001", "10001", "10001", "10001", "10001", "01010", "00100" },
|
||||
["W"] = { "10001", "10001", "10001", "10101", "10101", "11011", "10001" },
|
||||
["X"] = { "10001", "10001", "01010", "00100", "01010", "10001", "10001" },
|
||||
["Y"] = { "10001", "10001", "01010", "00100", "00100", "00100", "00100" },
|
||||
["Z"] = { "11111", "00001", "00010", "00100", "01000", "10000", "11111" },
|
||||
["0"] = { "01110", "10001", "10011", "10101", "11001", "10001", "01110" },
|
||||
["1"] = { "00100", "01100", "00100", "00100", "00100", "00100", "01110" },
|
||||
["2"] = { "01110", "10001", "00001", "00010", "00100", "01000", "11111" },
|
||||
["3"] = { "11111", "00010", "00100", "00010", "00001", "10001", "01110" },
|
||||
["4"] = { "00010", "00110", "01010", "10010", "11111", "00010", "00010" },
|
||||
["5"] = { "11111", "10000", "11110", "00001", "00001", "10001", "01110" },
|
||||
["6"] = { "00110", "01000", "10000", "11110", "10001", "10001", "01110" },
|
||||
["7"] = { "11111", "00001", "00010", "00100", "01000", "01000", "01000" },
|
||||
["8"] = { "01110", "10001", "10001", "01110", "10001", "10001", "01110" },
|
||||
["9"] = { "01110", "10001", "10001", "01111", "00001", "00010", "01100" },
|
||||
[":"] = { "00000", "00100", "00100", "00000", "00100", "00100", "00000" },
|
||||
["."] = { "00000", "00000", "00000", "00000", "00000", "00100", "00100" },
|
||||
[","] = { "00000", "00000", "00000", "00000", "00100", "00100", "01000" },
|
||||
["-"] = { "00000", "00000", "00000", "11111", "00000", "00000", "00000" },
|
||||
["/"] = { "00001", "00010", "00010", "00100", "01000", "01000", "10000" },
|
||||
["("] = { "00010", "00100", "01000", "01000", "01000", "00100", "00010" },
|
||||
[")"] = { "01000", "00100", "00010", "00010", "00010", "00100", "01000" },
|
||||
["%"] = { "11001", "11010", "00010", "00100", "01000", "01011", "10011" },
|
||||
["#"] = { "01010", "01010", "11111", "01010", "11111", "01010", "01010" },
|
||||
["!"] = { "00100", "00100", "00100", "00100", "00100", "00000", "00100" },
|
||||
["?"] = { "01110", "10001", "00001", "00010", "00100", "00000", "00100" },
|
||||
["+"] = { "00000", "00100", "00100", "11111", "00100", "00100", "00000" },
|
||||
["="] = { "00000", "00000", "11111", "00000", "11111", "00000", "00000" },
|
||||
["'"] = { "00100", "00100", "00000", "00000", "00000", "00000", "00000" },
|
||||
["<"] = { "00010", "00100", "01000", "10000", "01000", "00100", "00010" },
|
||||
[">"] = { "01000", "00100", "00010", "00001", "00010", "00100", "01000" },
|
||||
["*"] = { "00000", "10101", "01110", "11111", "01110", "10101", "00000" },
|
||||
["|"] = { "00100", "00100", "00100", "00100", "00100", "00100", "00100" },
|
||||
}
|
||||
|
||||
-- Compile every glyph into horizontal pixel runs once, so drawing a label
|
||||
-- does not rescan its bitmap strings on every frame.
|
||||
local function compile_glyph(rows)
|
||||
local compiled = {}
|
||||
for index = 1, GLYPH_HEIGHT do
|
||||
local line = rows[index]
|
||||
local runs = {}
|
||||
local column = 1
|
||||
while column <= GLYPH_WIDTH do
|
||||
if string.sub(line, column, column) == "1" then
|
||||
local run_end = column
|
||||
while run_end < GLYPH_WIDTH and string.sub(line, run_end + 1, run_end + 1) == "1" do
|
||||
run_end = run_end + 1
|
||||
end
|
||||
runs[#runs + 1] = column - 1
|
||||
runs[#runs + 1] = run_end - column + 1
|
||||
column = run_end + 1
|
||||
else
|
||||
column = column + 1
|
||||
end
|
||||
end
|
||||
compiled[index] = runs
|
||||
end
|
||||
return compiled
|
||||
end
|
||||
|
||||
for character, rows in pairs(GLYPHS) do
|
||||
GLYPHS[character] = compile_glyph(rows)
|
||||
end
|
||||
|
||||
M.glyph_width = GLYPH_WIDTH
|
||||
M.glyph_height = GLYPH_HEIGHT
|
||||
M.spacing = SPACING
|
||||
|
||||
function M.width(text, scale)
|
||||
local factor = scale or 1
|
||||
if text == nil or #text == 0 then
|
||||
return 0
|
||||
end
|
||||
return (#text * (GLYPH_WIDTH + SPACING) - SPACING) * factor
|
||||
end
|
||||
|
||||
function M.height(scale)
|
||||
return GLYPH_HEIGHT * (scale or 1)
|
||||
end
|
||||
|
||||
-- Draws uppercase ASCII text with one rectangle per horizontal run of pixels.
|
||||
function M.draw(surface, x, y, text, r, g, b, scale)
|
||||
if text == nil or surface == nil then
|
||||
return 0
|
||||
end
|
||||
local factor = scale or 1
|
||||
local upper = string.upper(text)
|
||||
local cursor = x
|
||||
local drawn = 0
|
||||
for index = 1, #upper do
|
||||
local glyph = GLYPHS[string.sub(upper, index, index)]
|
||||
if glyph ~= nil then
|
||||
for row = 1, GLYPH_HEIGHT do
|
||||
local runs = glyph[row]
|
||||
local row_y = y + (row - 1) * factor
|
||||
for run = 1, #runs, 2 do
|
||||
surface.rect(cursor + runs[run] * factor, row_y, runs[run + 1] * factor, factor, r, g, b)
|
||||
drawn = drawn + 1
|
||||
end
|
||||
end
|
||||
end
|
||||
cursor = cursor + (GLYPH_WIDTH + SPACING) * factor
|
||||
end
|
||||
return drawn
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,603 @@
|
||||
-- Windowed paint application: layout, mouse tools, keyboard shortcuts and
|
||||
-- rendering. The `gui` global only provides a window and rectangles, so every
|
||||
-- piece of application logic lives here and can be tested without a window.
|
||||
local canvas_module = require("paint.canvas")
|
||||
local palette = require("paint.palette")
|
||||
local font = require("gui.font")
|
||||
|
||||
local M = {}
|
||||
|
||||
local App = {}
|
||||
App.__index = App
|
||||
|
||||
M.tools = { "CRAYON", "LIGNE", "RECT", "ELLIPSE", "REMPLIR", "GOMME" }
|
||||
|
||||
local THEME = {
|
||||
background = { 24, 26, 32 },
|
||||
panel = { 38, 42, 50 },
|
||||
button = { 52, 58, 68 },
|
||||
text = { 228, 231, 238 },
|
||||
muted = { 138, 146, 158 },
|
||||
accent = { 64, 160, 240 },
|
||||
accent_text = { 10, 14, 20 },
|
||||
canvas = { 18, 20, 26 },
|
||||
cursor = { 250, 250, 250 },
|
||||
status = { 30, 34, 42 },
|
||||
}
|
||||
|
||||
local WINDOW_WIDTH = 960
|
||||
local WINDOW_HEIGHT = 640
|
||||
local TOOLBAR_HEIGHT = 60
|
||||
local PALETTE_HEIGHT = 28
|
||||
local STATUS_HEIGHT = 28
|
||||
local CELL_SIZE = 6
|
||||
|
||||
local function inside(rectangle, x, y)
|
||||
return x >= rectangle.x and x < rectangle.x + rectangle.w
|
||||
and y >= rectangle.y and y < rectangle.y + rectangle.h
|
||||
end
|
||||
|
||||
function M.new(options)
|
||||
options = options or {}
|
||||
local width = options.width or WINDOW_WIDTH
|
||||
local height = options.height or WINDOW_HEIGHT
|
||||
local cell = options.cell_size or CELL_SIZE
|
||||
local canvas_top = TOOLBAR_HEIGHT + PALETTE_HEIGHT
|
||||
local canvas_pixels = height - canvas_top - STATUS_HEIGHT
|
||||
|
||||
local app = setmetatable({
|
||||
surface = options.surface or gui,
|
||||
width = width,
|
||||
height = height,
|
||||
cell_size = cell,
|
||||
canvas_top = canvas_top,
|
||||
status_top = height - STATUS_HEIGHT,
|
||||
canvas = canvas_module.new(math.floor(width / cell), math.floor(canvas_pixels / cell)),
|
||||
tool = 1,
|
||||
slot = options.slot or palette.default_slot,
|
||||
filled = false,
|
||||
stroke = false,
|
||||
last_x = nil,
|
||||
last_y = nil,
|
||||
anchor_x = nil,
|
||||
anchor_y = nil,
|
||||
cursor_x = 1,
|
||||
cursor_y = 1,
|
||||
cursor_in_canvas = false,
|
||||
erase_button = false,
|
||||
message = "CLIC POUR DESSINER - 1-6 OUTILS - Q QUITTER",
|
||||
tool_buttons = {},
|
||||
action_buttons = {},
|
||||
swatches = {},
|
||||
}, App)
|
||||
|
||||
for index = 1, #M.tools do
|
||||
app.tool_buttons[index] = { x = 8 + (index - 1) * 92, y = 8, w = 86, h = 36, tool = index }
|
||||
end
|
||||
|
||||
app.action_buttons = {
|
||||
{ x = 568, y = 8, w = 80, h = 36, action = "undo", label = "UNDO" },
|
||||
{ x = 652, y = 8, w = 80, h = 36, action = "clear", label = "CLEAR" },
|
||||
{ x = 736, y = 8, w = 80, h = 36, action = "save", label = "SAVE" },
|
||||
{ x = 820, y = 8, w = 80, h = 36, action = "quit", label = "QUIT" },
|
||||
}
|
||||
|
||||
for index = 1, palette.count() do
|
||||
app.swatches[index] = { x = 8 + (index - 1) * 30, y = 62, w = 26, h = 22, slot = index }
|
||||
end
|
||||
|
||||
return app
|
||||
end
|
||||
|
||||
function App:tool_name()
|
||||
return M.tools[self.tool]
|
||||
end
|
||||
|
||||
function App:colour_index()
|
||||
if self.tool == 6 then
|
||||
return 0
|
||||
end
|
||||
return palette.index_of_slot(self.slot)
|
||||
end
|
||||
|
||||
function App:cell_at(x, y)
|
||||
if y < self.canvas_top or y >= self.status_top then
|
||||
return nil
|
||||
end
|
||||
local column = math.floor(x / self.cell_size) + 1
|
||||
local row = math.floor((y - self.canvas_top) / self.cell_size) + 1
|
||||
if column < 1 or row < 1 or column > self.canvas.width or row > self.canvas.height then
|
||||
return nil
|
||||
end
|
||||
return column, row
|
||||
end
|
||||
|
||||
function App:set_tool(index)
|
||||
if index >= 1 and index <= #M.tools then
|
||||
self.tool = index
|
||||
self.anchor_x = nil
|
||||
self.anchor_y = nil
|
||||
self.message = "OUTIL " .. M.tools[index]
|
||||
return "tool"
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
function App:cycle_colour(step)
|
||||
if step > 0 then
|
||||
self.slot = palette.next_slot(self.slot)
|
||||
else
|
||||
self.slot = palette.previous_slot(self.slot)
|
||||
end
|
||||
self.message = "COULEUR " .. string.upper(palette.label(self.slot))
|
||||
return "colour"
|
||||
end
|
||||
|
||||
function App:undo()
|
||||
if self.canvas:undo() then
|
||||
self.message = "ANNULE"
|
||||
else
|
||||
self.message = "RIEN A ANNULER"
|
||||
end
|
||||
return "undo"
|
||||
end
|
||||
|
||||
function App:clear()
|
||||
self.canvas:push_history()
|
||||
self.canvas:clear()
|
||||
self.message = "TOILE VIDE"
|
||||
return "clear"
|
||||
end
|
||||
|
||||
function App:save(path)
|
||||
local name = path or "guipaint.ppm"
|
||||
local handle = io.open(name, "wb")
|
||||
if handle == nil then
|
||||
self.message = "ECRITURE IMPOSSIBLE"
|
||||
return false
|
||||
end
|
||||
local width, height = self.canvas.width, self.canvas.height
|
||||
handle:write(string.format("P6\n%d %d\n255\n", width, height))
|
||||
local chunks = {}
|
||||
for row = 1, height do
|
||||
for column = 1, width do
|
||||
local rgb = palette.rgb_of(self.canvas:get(column, row))
|
||||
chunks[#chunks + 1] = string.char(rgb[1], rgb[2], rgb[3])
|
||||
end
|
||||
end
|
||||
handle:write(table.concat(chunks))
|
||||
handle:close()
|
||||
self.message = "ECRIT " .. string.upper(name)
|
||||
return true
|
||||
end
|
||||
|
||||
function App:preview_canvas()
|
||||
if self.anchor_x == nil then
|
||||
return nil
|
||||
end
|
||||
local scratch = canvas_module.new(self.canvas.width, self.canvas.height)
|
||||
local colour = self:colour_index()
|
||||
if colour == 0 then
|
||||
colour = 1
|
||||
end
|
||||
if self.tool == 2 then
|
||||
scratch:line(self.anchor_x, self.anchor_y, self.cursor_x, self.cursor_y, colour)
|
||||
elseif self.tool == 3 then
|
||||
scratch:rect(self.anchor_x, self.anchor_y, self.cursor_x, self.cursor_y, colour, self.filled)
|
||||
elseif self.tool == 4 then
|
||||
scratch:ellipse(self.anchor_x, self.anchor_y,
|
||||
math.abs(self.cursor_x - self.anchor_x), math.abs(self.cursor_y - self.anchor_y),
|
||||
colour, self.filled)
|
||||
end
|
||||
return scratch
|
||||
end
|
||||
|
||||
function App:press(x, y, button)
|
||||
if y < TOOLBAR_HEIGHT then
|
||||
for index = 1, #self.tool_buttons do
|
||||
if inside(self.tool_buttons[index], x, y) then
|
||||
return self:set_tool(self.tool_buttons[index].tool)
|
||||
end
|
||||
end
|
||||
for index = 1, #self.action_buttons do
|
||||
local button_rect = self.action_buttons[index]
|
||||
if inside(button_rect, x, y) then
|
||||
if button_rect.action == "undo" then
|
||||
return self:undo()
|
||||
elseif button_rect.action == "clear" then
|
||||
return self:clear()
|
||||
elseif button_rect.action == "save" then
|
||||
self:save()
|
||||
return "save"
|
||||
else
|
||||
return "quit"
|
||||
end
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
if y < self.canvas_top then
|
||||
for index = 1, #self.swatches do
|
||||
if inside(self.swatches[index], x, y) then
|
||||
self.slot = self.swatches[index].slot
|
||||
self.message = "COULEUR " .. string.upper(palette.label(self.slot))
|
||||
return "colour"
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
local column, row = self:cell_at(x, y)
|
||||
if column == nil then
|
||||
return nil
|
||||
end
|
||||
|
||||
if button == 3 then
|
||||
self.tool = 6
|
||||
self.erase_button = true
|
||||
end
|
||||
|
||||
self.cursor_x, self.cursor_y = column, row
|
||||
self.cursor_in_canvas = true
|
||||
self.canvas:push_history()
|
||||
self.stroke = true
|
||||
self.last_x, self.last_y = column, row
|
||||
|
||||
local colour = self:colour_index()
|
||||
if self.tool == 5 then
|
||||
local painted = self.canvas:fill(column, row, colour)
|
||||
self.message = string.format("REMPLI %d CASES", painted)
|
||||
self.stroke = false
|
||||
elseif self.tool == 1 or self.tool == 6 then
|
||||
self.canvas:set(column, row, colour)
|
||||
else
|
||||
self.anchor_x, self.anchor_y = column, row
|
||||
end
|
||||
return "draw"
|
||||
end
|
||||
|
||||
function App:motion(x, y)
|
||||
local column, row = self:cell_at(x, y)
|
||||
if column == nil then
|
||||
self.cursor_in_canvas = false
|
||||
return nil
|
||||
end
|
||||
self.cursor_in_canvas = true
|
||||
self.cursor_x, self.cursor_y = column, row
|
||||
if not self.stroke or self.anchor_x ~= nil then
|
||||
return "move"
|
||||
end
|
||||
if self.tool == 1 or self.tool == 6 then
|
||||
if self.last_x ~= nil then
|
||||
self.canvas:line(self.last_x, self.last_y, column, row, self:colour_index())
|
||||
end
|
||||
self.last_x, self.last_y = column, row
|
||||
end
|
||||
return "move"
|
||||
end
|
||||
|
||||
function App:release(x, y, button)
|
||||
local column, row = self:cell_at(x, y)
|
||||
if column ~= nil then
|
||||
self.cursor_x, self.cursor_y = column, row
|
||||
end
|
||||
if not self.stroke then
|
||||
return nil
|
||||
end
|
||||
|
||||
if self.anchor_x ~= nil then
|
||||
local colour = self:colour_index()
|
||||
local target_x = column or self.cursor_x
|
||||
local target_y = row or self.cursor_y
|
||||
if self.tool == 2 then
|
||||
self.canvas:line(self.anchor_x, self.anchor_y, target_x, target_y, colour)
|
||||
elseif self.tool == 3 then
|
||||
self.canvas:rect(self.anchor_x, self.anchor_y, target_x, target_y, colour, self.filled)
|
||||
elseif self.tool == 4 then
|
||||
self.canvas:ellipse(self.anchor_x, self.anchor_y,
|
||||
math.abs(target_x - self.anchor_x), math.abs(target_y - self.anchor_y),
|
||||
colour, self.filled)
|
||||
end
|
||||
self.anchor_x, self.anchor_y = nil, nil
|
||||
end
|
||||
|
||||
self.stroke = false
|
||||
self.last_x, self.last_y = nil, nil
|
||||
if self.erase_button then
|
||||
self.erase_button = false
|
||||
self.tool = 1
|
||||
end
|
||||
return "commit"
|
||||
end
|
||||
|
||||
function App:key(key)
|
||||
if key == "escape" or key == "q" then
|
||||
return "quit"
|
||||
end
|
||||
if key == "u" then
|
||||
return self:undo()
|
||||
end
|
||||
if key == "c" then
|
||||
return self:clear()
|
||||
end
|
||||
if key == "s" then
|
||||
self:save()
|
||||
return "save"
|
||||
end
|
||||
if key == "f" then
|
||||
self.filled = not self.filled
|
||||
if self.filled then
|
||||
self.message = "FORMES PLEINES"
|
||||
else
|
||||
self.message = "FORMES VIDES"
|
||||
end
|
||||
return "mode"
|
||||
end
|
||||
if key == "p" then
|
||||
return self:cycle_colour(1)
|
||||
end
|
||||
if key == "m" then
|
||||
return self:cycle_colour(-1)
|
||||
end
|
||||
local number = tonumber(key)
|
||||
if number ~= nil then
|
||||
return self:set_tool(number)
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
function App:handle(event)
|
||||
if event == nil then
|
||||
return nil
|
||||
end
|
||||
local kind = event.type
|
||||
if kind == "quit" then
|
||||
return "quit"
|
||||
end
|
||||
if kind == "keydown" then
|
||||
if event["repeat"] then
|
||||
return nil
|
||||
end
|
||||
return self:key(event.key)
|
||||
end
|
||||
if kind == "mousedown" then
|
||||
return self:press(event.x, event.y, event.button)
|
||||
end
|
||||
if kind == "mousemove" then
|
||||
return self:motion(event.x, event.y)
|
||||
end
|
||||
if kind == "mouseup" then
|
||||
return self:release(event.x, event.y, event.button)
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- Every drawing primitive is collected in a flat array (x, y, w, h, r, g, b)
|
||||
-- and handed to the window in one native call: one Lua->C crossing per frame
|
||||
-- instead of thousands.
|
||||
-- Plain functions on purpose: the font and the window both draw through a
|
||||
-- three-argument `rect(x, y, w, h, r, g, b)` surface, so the collector must look
|
||||
-- exactly like one.
|
||||
local function new_recorder()
|
||||
local recorder = { flat = {}, n = 0, background = { 0, 0, 0 } }
|
||||
function recorder.clear(r, g, b)
|
||||
local background = recorder.background
|
||||
background[1], background[2], background[3] = r, g, b
|
||||
recorder.n = 0
|
||||
end
|
||||
function recorder.rect(x, y, w, h, r, g, b)
|
||||
if w <= 0 or h <= 0 then
|
||||
return
|
||||
end
|
||||
local flat = recorder.flat
|
||||
local next_index = recorder.n + 1
|
||||
flat[next_index], flat[next_index + 1], flat[next_index + 2], flat[next_index + 3] = x, y, w, h
|
||||
flat[next_index + 4], flat[next_index + 5], flat[next_index + 6] = r, g, b
|
||||
recorder.n = next_index + 6
|
||||
end
|
||||
return recorder
|
||||
end
|
||||
|
||||
local function flush(surface, recorder)
|
||||
local background = recorder.background
|
||||
surface.clear(background[1], background[2], background[3])
|
||||
local count = recorder.n
|
||||
if count == 0 then
|
||||
return 0
|
||||
end
|
||||
local flat = recorder.flat
|
||||
if type(surface.rects) == "function" then
|
||||
surface.rects(flat, count)
|
||||
return count // 7
|
||||
end
|
||||
local rect = surface.rect
|
||||
for index = 1, count, 7 do
|
||||
rect(surface, flat[index], flat[index + 1], flat[index + 2], flat[index + 3],
|
||||
flat[index + 4], flat[index + 5], flat[index + 6])
|
||||
end
|
||||
return count // 7
|
||||
end
|
||||
|
||||
-- Painted cells are cached as horizontal runs: a uniform row costs one
|
||||
-- rectangle instead of one per cell, and the list is only rebuilt when the
|
||||
-- canvas changed (its version counter moved).
|
||||
function App:canvas_runs()
|
||||
local canvas = self.canvas
|
||||
if self.runs_version == canvas.version then
|
||||
return self.runs, self.runs_count
|
||||
end
|
||||
local runs = self.runs or {}
|
||||
local count = 0
|
||||
local cells = canvas.cells
|
||||
local width = canvas.width
|
||||
local size = self.cell_size
|
||||
local top = self.canvas_top
|
||||
local rgb_cache = self.rgb_cache
|
||||
if rgb_cache == nil then
|
||||
rgb_cache = {}
|
||||
self.rgb_cache = rgb_cache
|
||||
end
|
||||
for row = 1, canvas.height do
|
||||
local base = (row - 1) * width
|
||||
local y = top + (row - 1) * size
|
||||
local column = 1
|
||||
while column <= width do
|
||||
local colour = cells[base + column]
|
||||
local run_end = column + 1
|
||||
while run_end <= width and cells[base + run_end] == colour do
|
||||
run_end = run_end + 1
|
||||
end
|
||||
if colour ~= 0 then
|
||||
local rgb = rgb_cache[colour]
|
||||
if rgb == nil then
|
||||
rgb = palette.rgb_of(colour)
|
||||
rgb_cache[colour] = rgb
|
||||
end
|
||||
count = count + 7
|
||||
runs[count - 6] = (column - 1) * size
|
||||
runs[count - 5] = y
|
||||
runs[count - 4] = (run_end - column) * size
|
||||
runs[count - 3] = size
|
||||
runs[count - 2] = rgb[1]
|
||||
runs[count - 1] = rgb[2]
|
||||
runs[count] = rgb[3]
|
||||
end
|
||||
column = run_end
|
||||
end
|
||||
end
|
||||
self.runs = runs
|
||||
self.runs_count = count
|
||||
self.runs_version = canvas.version
|
||||
return runs, count
|
||||
end
|
||||
|
||||
-- Painted cell count, cached until the canvas changes again: the status bar
|
||||
-- asks for it on every frame.
|
||||
function App:painted()
|
||||
local canvas = self.canvas
|
||||
if self.painted_version ~= canvas.version then
|
||||
self.painted_count = canvas:count()
|
||||
self.painted_version = canvas.version
|
||||
end
|
||||
return self.painted_count
|
||||
end
|
||||
|
||||
function App:render()
|
||||
local surface = self.surface
|
||||
if surface == nil then
|
||||
return 0
|
||||
end
|
||||
local recorder = self.recorder
|
||||
if recorder == nil then
|
||||
recorder = new_recorder()
|
||||
self.recorder = recorder
|
||||
end
|
||||
local drawn = 0
|
||||
recorder.clear(THEME.background[1], THEME.background[2], THEME.background[3])
|
||||
|
||||
recorder.rect(0, 0, self.width, TOOLBAR_HEIGHT, THEME.panel[1], THEME.panel[2], THEME.panel[3])
|
||||
for index = 1, #self.tool_buttons do
|
||||
local button = self.tool_buttons[index]
|
||||
local selected = index == self.tool
|
||||
local r, g, b = THEME.button[1], THEME.button[2], THEME.button[3]
|
||||
local text_r, text_g, text_b = THEME.text[1], THEME.text[2], THEME.text[3]
|
||||
if selected then
|
||||
r, g, b = THEME.accent[1], THEME.accent[2], THEME.accent[3]
|
||||
text_r, text_g, text_b = THEME.accent_text[1], THEME.accent_text[2], THEME.accent_text[3]
|
||||
end
|
||||
recorder.rect(button.x, button.y, button.w, button.h, r, g, b)
|
||||
local label = M.tools[index]
|
||||
local text_x = button.x + math.floor((button.w - font.width(label, 2)) / 2)
|
||||
local text_y = button.y + math.floor((button.h - font.height(2)) / 2)
|
||||
drawn = drawn + font.draw(recorder, text_x, text_y, label, text_r, text_g, text_b, 2)
|
||||
end
|
||||
|
||||
for index = 1, #self.action_buttons do
|
||||
local button = self.action_buttons[index]
|
||||
recorder.rect(button.x, button.y, button.w, button.h, THEME.button[1], THEME.button[2], THEME.button[3])
|
||||
local text_x = button.x + math.floor((button.w - font.width(button.label, 1)) / 2)
|
||||
local text_y = button.y + math.floor((button.h - font.height(1)) / 2)
|
||||
drawn = drawn + font.draw(recorder, text_x, text_y, button.label,
|
||||
THEME.text[1], THEME.text[2], THEME.text[3], 1)
|
||||
end
|
||||
|
||||
recorder.rect(0, TOOLBAR_HEIGHT, self.width, PALETTE_HEIGHT,
|
||||
THEME.panel[1], THEME.panel[2], THEME.panel[3])
|
||||
for index = 1, #self.swatches do
|
||||
local swatch = self.swatches[index]
|
||||
local rgb = palette.entries[index].rgb
|
||||
recorder.rect(swatch.x, swatch.y, swatch.w, swatch.h, rgb[1], rgb[2], rgb[3])
|
||||
if index == self.slot then
|
||||
recorder.rect(swatch.x - 2, swatch.y - 2, swatch.w + 4, 2, 250, 250, 250)
|
||||
recorder.rect(swatch.x - 2, swatch.y + swatch.h, swatch.w + 4, 2, 250, 250, 250)
|
||||
recorder.rect(swatch.x - 2, swatch.y - 2, 2, swatch.h + 4, 250, 250, 250)
|
||||
recorder.rect(swatch.x + swatch.w, swatch.y - 2, 2, swatch.h + 4, 250, 250, 250)
|
||||
end
|
||||
drawn = drawn + 1
|
||||
end
|
||||
drawn = drawn + font.draw(recorder, 392, TOOLBAR_HEIGHT + 7,
|
||||
"COULEUR " .. string.upper(palette.label(self.slot)),
|
||||
THEME.muted[1], THEME.muted[2], THEME.muted[3], 1)
|
||||
|
||||
local canvas = self.canvas
|
||||
recorder.rect(0, self.canvas_top, self.width, canvas.height * self.cell_size,
|
||||
THEME.canvas[1], THEME.canvas[2], THEME.canvas[3])
|
||||
local runs, run_count = self:canvas_runs()
|
||||
if run_count > 0 then
|
||||
table.move(runs, 1, run_count, recorder.n + 1, recorder.flat)
|
||||
recorder.n = recorder.n + run_count
|
||||
drawn = drawn + run_count // 7
|
||||
end
|
||||
|
||||
local preview = self:preview_canvas()
|
||||
if preview ~= nil then
|
||||
for row = 1, preview.height do
|
||||
for column = 1, preview.width do
|
||||
if preview:get(column, row) ~= 0 then
|
||||
recorder.rect((column - 1) * self.cell_size + 1,
|
||||
self.canvas_top + (row - 1) * self.cell_size + 1,
|
||||
self.cell_size - 2, self.cell_size - 2,
|
||||
THEME.accent[1], THEME.accent[2], THEME.accent[3])
|
||||
drawn = drawn + 1
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
if self.cursor_in_canvas then
|
||||
local x = (self.cursor_x - 1) * self.cell_size
|
||||
local y = self.canvas_top + (self.cursor_y - 1) * self.cell_size
|
||||
recorder.rect(x, y, self.cell_size, 1, THEME.cursor[1], THEME.cursor[2], THEME.cursor[3])
|
||||
recorder.rect(x, y + self.cell_size - 1, self.cell_size, 1,
|
||||
THEME.cursor[1], THEME.cursor[2], THEME.cursor[3])
|
||||
recorder.rect(x, y, 1, self.cell_size, THEME.cursor[1], THEME.cursor[2], THEME.cursor[3])
|
||||
recorder.rect(x + self.cell_size - 1, y, 1, self.cell_size,
|
||||
THEME.cursor[1], THEME.cursor[2], THEME.cursor[3])
|
||||
end
|
||||
|
||||
recorder.rect(0, self.status_top, self.width, STATUS_HEIGHT,
|
||||
THEME.status[1], THEME.status[2], THEME.status[3])
|
||||
local status = string.format("%s | %s | X %d Y %d | %d CASES",
|
||||
self:tool_name(), string.upper(palette.label(self.slot)),
|
||||
self.cursor_x, self.cursor_y, self:painted())
|
||||
drawn = drawn + font.draw(recorder, 10, self.status_top + 10, status,
|
||||
THEME.text[1], THEME.text[2], THEME.text[3], 1)
|
||||
|
||||
local message = self.message or ""
|
||||
local room = self.width - 20 - font.width(status, 1) - 20
|
||||
local maximum = math.floor(room / 6)
|
||||
if maximum > 0 and #message > maximum then
|
||||
message = string.sub(message, 1, maximum)
|
||||
end
|
||||
if #message > 0 then
|
||||
drawn = drawn + font.draw(recorder, self.width - 10 - font.width(message, 1),
|
||||
self.status_top + 10, message, THEME.accent[1], THEME.accent[2], THEME.accent[3], 1)
|
||||
end
|
||||
|
||||
return flush(surface, recorder)
|
||||
end
|
||||
|
||||
M.App = App
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,60 @@
|
||||
-- The picture drawn by `guipaint shot` and by the tests: same canvas primitives
|
||||
-- as the interactive tools, so the capture shows the real application state.
|
||||
local palette = require("paint.palette")
|
||||
|
||||
local M = {}
|
||||
|
||||
local function index_of(name)
|
||||
local slot = palette.slot_of(name)
|
||||
if slot == nil then
|
||||
return 0
|
||||
end
|
||||
return palette.index_of_slot(slot)
|
||||
end
|
||||
|
||||
local function solid(app, name, x1, y1, x2, y2)
|
||||
app.canvas:rect(x1, y1, x2, y2, index_of(name), true)
|
||||
end
|
||||
|
||||
function M.picture(app)
|
||||
local canvas = app.canvas
|
||||
local width = canvas.width
|
||||
local height = canvas.height
|
||||
local ground = height - 24
|
||||
|
||||
canvas:fill(1, 1, index_of("nuit"))
|
||||
local stars = {
|
||||
{ 14, 6 }, { 28, 12 }, { 52, 5 }, { 71, 9 }, { 120, 7 }, { 134, 13 },
|
||||
}
|
||||
for position = 1, #stars do
|
||||
canvas:set(stars[position][1], stars[position][2], index_of("blanc"))
|
||||
end
|
||||
|
||||
canvas:ellipse(math.floor(width * 0.85), 13, 9, 6, index_of("jaune"), true)
|
||||
|
||||
solid(app, "gris", 20, 17, 40, 19)
|
||||
solid(app, "gris", 24, 15, 36, 17)
|
||||
|
||||
solid(app, "vert", 1, ground, width, height)
|
||||
|
||||
solid(app, "brun", 24, 34, 72, ground)
|
||||
for row = 16, 34 do
|
||||
local half = math.floor((row - 16) * 1.8)
|
||||
solid(app, "brun", 48 - half, row, 48 + half, row)
|
||||
end
|
||||
solid(app, "nuit", 38, 50, 46, ground)
|
||||
solid(app, "cyan", 54, 44, 64, 52)
|
||||
|
||||
solid(app, "brun", 100, 50, 106, ground)
|
||||
canvas:ellipse(103, 40, 14, 12, index_of("vert"), true)
|
||||
|
||||
app.slot = palette.slot_of("jaune")
|
||||
app.tool = 4
|
||||
app.cursor_x = math.floor(width * 0.85)
|
||||
app.cursor_y = 13
|
||||
app.cursor_in_canvas = true
|
||||
app.message = "PAYSAGE - CLIC POUR DESSINER"
|
||||
return app
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,262 @@
|
||||
-- Tests of the windowed application. They run without a window: the surface is
|
||||
-- a recorder that counts the drawing calls and replays queued events.
|
||||
local palette = require("paint.palette")
|
||||
local font = require("gui.font")
|
||||
local paint_module = require("gui.paint")
|
||||
local scene = require("gui.scene")
|
||||
|
||||
local M = {}
|
||||
|
||||
local function fake_surface()
|
||||
local surface = { rects = 0, clears = 0, lines = 0, presents = 0, events = {}, shot = nil }
|
||||
function surface.clear(r, g, b)
|
||||
surface.clears = surface.clears + 1
|
||||
end
|
||||
function surface.rect(x, y, w, h, r, g, b)
|
||||
surface.rects = surface.rects + 1
|
||||
end
|
||||
function surface.line(x1, y1, x2, y2, r, g, b)
|
||||
surface.lines = surface.lines + 1
|
||||
end
|
||||
function surface.present()
|
||||
surface.presents = surface.presents + 1
|
||||
end
|
||||
function surface.poll()
|
||||
return table.remove(surface.events, 1)
|
||||
end
|
||||
function surface.screenshot(path)
|
||||
surface.shot = path
|
||||
return true
|
||||
end
|
||||
function surface.open(title, width, height)
|
||||
return true
|
||||
end
|
||||
function surface.close()
|
||||
return true
|
||||
end
|
||||
function surface.delay(milliseconds)
|
||||
return true
|
||||
end
|
||||
function surface.size()
|
||||
return 960, 640
|
||||
end
|
||||
return surface
|
||||
end
|
||||
|
||||
function M.run()
|
||||
local passed = 0
|
||||
local failures = {}
|
||||
|
||||
local function check(name, actual, expected)
|
||||
if actual == expected then
|
||||
passed = passed + 1
|
||||
else
|
||||
failures[#failures + 1] = string.format("%s : attendu %s, obtenu %s",
|
||||
name, tostring(expected), tostring(actual))
|
||||
end
|
||||
end
|
||||
|
||||
local function check_true(name, condition, detail)
|
||||
if condition then
|
||||
passed = passed + 1
|
||||
else
|
||||
failures[#failures + 1] = name .. " : " .. tostring(detail or "condition fausse")
|
||||
end
|
||||
end
|
||||
|
||||
-- font ----------------------------------------------------------------
|
||||
check("font width", font.width("AB"), 11)
|
||||
check("font width scale 2", font.width("AB", 2), 22)
|
||||
check("font height", font.height(1), 7)
|
||||
check("font height scale 3", font.height(3), 21)
|
||||
check("font empty width", font.width(""), 0)
|
||||
|
||||
local surface = fake_surface()
|
||||
local drawn = font.draw(surface, 0, 0, "A", 255, 255, 255, 1)
|
||||
check("font draws runs", drawn > 0, true)
|
||||
check("font used surface", surface.rects > 0, true)
|
||||
local before = surface.rects
|
||||
font.draw(surface, 0, 20, "ab", 255, 255, 255, 1)
|
||||
check_true("font uppercases", surface.rects > before, surface.rects)
|
||||
local skipped = font.draw(surface, 0, 40, "~", 255, 255, 255, 1)
|
||||
check("font skips unknown glyph", skipped, 0)
|
||||
|
||||
-- palette -------------------------------------------------------------
|
||||
local background = palette.rgb_of(0)
|
||||
check("background rgb", background[3], 34)
|
||||
local yellow = palette.rgb_of(palette.index_of_slot(6))
|
||||
check("yellow red", yellow[1], 245)
|
||||
check("yellow green", yellow[2], 215)
|
||||
check("yellow blue", yellow[3], 60)
|
||||
local fallback = palette.rgb_of(12345)
|
||||
check("unknown colour falls back", fallback[1], 26)
|
||||
|
||||
-- layout --------------------------------------------------------------
|
||||
local app = paint_module.new({ surface = surface })
|
||||
check("canvas width", app.canvas.width, 160)
|
||||
check("canvas height", app.canvas.height, 87)
|
||||
check("viewport top", app.canvas_top, 88)
|
||||
check("status top", app.status_top, 612)
|
||||
check("initial tool", app:tool_name(), "CRAYON")
|
||||
check("initial slot", app.slot, palette.default_slot)
|
||||
|
||||
check("cell at origin", app:cell_at(0, 88), 1)
|
||||
check("cell outside above", app:cell_at(0, 87), nil)
|
||||
check("cell outside status", app:cell_at(0, 612), nil)
|
||||
check("cell outside right", app:cell_at(1200, 100), nil)
|
||||
|
||||
-- toolbar and palette clicks -----------------------------------------
|
||||
check("toolbar click", app:press(143, 26, 1), "tool")
|
||||
check("toolbar selected", app.tool, 2)
|
||||
check("swatch click", app:press(171, 73, 1), "colour")
|
||||
check("swatch selected", app.slot, 6)
|
||||
|
||||
-- pencil + drag -------------------------------------------------------
|
||||
local pencil = paint_module.new({ surface = surface })
|
||||
check("select pencil", pencil:key("1"), "tool")
|
||||
check("press draws", pencil:press(0, 88, 1), "draw")
|
||||
check("pencil painted cell", pencil.canvas:get(1, 1), pencil:colour_index())
|
||||
pencil:motion(30, 88)
|
||||
check("drag painted six cells", pencil.canvas:count(), 6)
|
||||
check("drag end", pencil.canvas:get(6, 1), pencil:colour_index())
|
||||
|
||||
-- line tool -----------------------------------------------------------
|
||||
local line_app = paint_module.new({ surface = surface })
|
||||
line_app:key("2")
|
||||
line_app:press(0, 88, 1)
|
||||
line_app:motion(30, 88 + 18)
|
||||
check_true("line preview", line_app:preview_canvas() ~= nil, "no preview")
|
||||
check("line commit", line_app:release(30, 88 + 18, 1), "commit")
|
||||
check("line start", line_app.canvas:get(1, 1), line_app:colour_index())
|
||||
check("line end", line_app.canvas:get(6, 4), line_app:colour_index())
|
||||
check("line cleared anchor", line_app.anchor_x, nil)
|
||||
|
||||
-- rectangle -----------------------------------------------------------
|
||||
local rectangle = paint_module.new({ surface = surface })
|
||||
rectangle:key("3")
|
||||
rectangle:press(0, 88, 1)
|
||||
rectangle:release(30, 88 + 18, 1)
|
||||
check("rect corner", rectangle.canvas:get(1, 1), rectangle:colour_index())
|
||||
check("rect opposite corner", rectangle.canvas:get(6, 4), rectangle:colour_index())
|
||||
check("rect hollow", rectangle.canvas:get(3, 2), 0)
|
||||
|
||||
-- filled ellipse ------------------------------------------------------
|
||||
local oval = paint_module.new({ surface = surface })
|
||||
oval:key("4")
|
||||
oval:key("f")
|
||||
check_true("filled mode", oval.filled, "not filled")
|
||||
oval:press(30, 88 + 30, 1)
|
||||
oval:release(90, 88 + 54, 1)
|
||||
check_true("ellipse painted", oval.canvas:count() > 20, oval.canvas:count())
|
||||
|
||||
-- flood fill ----------------------------------------------------------
|
||||
local bucket = paint_module.new({ surface = surface })
|
||||
bucket:key("5")
|
||||
bucket:press(0, 88, 1)
|
||||
check("fill whole canvas", bucket.canvas:count(), bucket.canvas.width * bucket.canvas.height)
|
||||
|
||||
-- undo, clear, colour cycling ----------------------------------------
|
||||
check("undo", bucket:key("u"), "undo")
|
||||
check("undo emptied", bucket.canvas:count(), 0)
|
||||
bucket:key("1")
|
||||
bucket:press(0, 88, 1)
|
||||
check("clear", bucket:key("c"), "clear")
|
||||
check("clear emptied", bucket.canvas:count(), 0)
|
||||
local slot_before = bucket.slot
|
||||
bucket:key("p")
|
||||
check("next colour", bucket.slot, palette.next_slot(slot_before))
|
||||
bucket:key("m")
|
||||
check("previous colour", bucket.slot, slot_before)
|
||||
|
||||
-- right button erases -------------------------------------------------
|
||||
local eraser = paint_module.new({ surface = surface })
|
||||
eraser:key("1")
|
||||
eraser:press(0, 88, 1)
|
||||
eraser:release(0, 88, 1)
|
||||
check_true("painted before erase", eraser.canvas:get(1, 1) ~= 0, eraser.canvas:get(1, 1))
|
||||
eraser:press(0, 88, 3)
|
||||
eraser:release(0, 88, 3)
|
||||
check("right click erased", eraser.canvas:get(1, 1), 0)
|
||||
check("tool restored", eraser.tool, 1)
|
||||
|
||||
-- events --------------------------------------------------------------
|
||||
check("quit event", app:handle({ type = "quit" }), "quit")
|
||||
check("escape key", app:handle({ type = "keydown", key = "escape" }), "quit")
|
||||
check("unknown event", app:handle({ type = "wheel" }), nil)
|
||||
local moving = paint_module.new({ surface = surface })
|
||||
moving:handle({ type = "mousemove", x = 12, y = 94 })
|
||||
check("move updates cursor", moving.cursor_x, 3)
|
||||
check("move updates row", moving.cursor_y, 2)
|
||||
moving:handle({ type = "mousemove", x = 12, y = 5 })
|
||||
check("move outside canvas", moving.cursor_in_canvas, false)
|
||||
|
||||
-- rendering -----------------------------------------------------------
|
||||
local render_surface = fake_surface()
|
||||
local rendered = paint_module.new({ surface = render_surface })
|
||||
local calls = rendered:render()
|
||||
check("one clear per frame", render_surface.clears, 1)
|
||||
check_true("render issues many rects", calls > 200, calls)
|
||||
check_true("render counted rects", render_surface.rects > 200, render_surface.rects)
|
||||
|
||||
-- batched surface: one native call per frame, reused while nothing moves --
|
||||
local batch_surface = fake_surface()
|
||||
batch_surface.rect_calls = 0
|
||||
batch_surface.rect_count = 0
|
||||
function batch_surface.rects(flat, count)
|
||||
batch_surface.rect_calls = batch_surface.rect_calls + 1
|
||||
batch_surface.rect_count = count // 7
|
||||
end
|
||||
local fast = paint_module.new({ surface = batch_surface })
|
||||
scene.picture(fast)
|
||||
local fast_drawn = fast:render()
|
||||
check("single batched call", batch_surface.rect_calls, 1)
|
||||
check("batched count matches", batch_surface.rect_count, fast_drawn)
|
||||
check("batched frame clears", batch_surface.clears, 1)
|
||||
check("runs cached between frames", fast:render(), fast_drawn)
|
||||
check("still one call per frame", batch_surface.rect_calls, 2)
|
||||
|
||||
-- a uniform canvas merges into one rectangle per row ----------------------
|
||||
local merged = paint_module.new({ surface = fake_surface() })
|
||||
merged.canvas:fill(1, 1, palette.index_of_slot(7))
|
||||
local merged_drawn = merged:render()
|
||||
check_true("runs merged", merged_drawn < 6000, merged_drawn)
|
||||
check("merged cell count", merged.canvas:count(), merged.canvas.width * merged.canvas.height)
|
||||
|
||||
-- canvas version only moves on a real change ------------------------------
|
||||
local versioned = paint_module.new({ surface = fake_surface() })
|
||||
local start_version = versioned.canvas.version
|
||||
versioned.canvas:set(1, 1, palette.index_of_slot(3))
|
||||
check("version bumps on set", versioned.canvas.version, start_version + 1)
|
||||
versioned.canvas:set(1, 1, palette.index_of_slot(3))
|
||||
check("version stable on no-op", versioned.canvas.version, start_version + 1)
|
||||
check("undo without history", versioned.canvas:undo(), false)
|
||||
check("version stable on failed undo", versioned.canvas.version, start_version + 1)
|
||||
|
||||
-- picture and capture -------------------------------------------------
|
||||
local artist = paint_module.new({ surface = fake_surface() })
|
||||
scene.picture(artist)
|
||||
check_true("picture painted", artist.canvas:count() > 5000, artist.canvas:count())
|
||||
check("picture sun", artist.canvas:get(136, 13), palette.index_of_slot(6))
|
||||
check("picture ground", artist.canvas:get(4, 80), palette.index_of_slot(7))
|
||||
check("picture wall", artist.canvas:get(30, 45), palette.index_of_slot(12))
|
||||
check("picture window", artist.canvas:get(59, 48), palette.index_of_slot(8))
|
||||
check("picture cursor", artist.cursor_in_canvas, true)
|
||||
|
||||
-- save ----------------------------------------------------------------
|
||||
local path = "/tmp/luapaint_test.ppm"
|
||||
check_true("save returns true", artist:save(path), "save failed")
|
||||
local handle = io.open(path, "rb")
|
||||
check_true("ppm written", handle ~= nil, "no file")
|
||||
if handle ~= nil then
|
||||
local data = handle:read("a")
|
||||
handle:close()
|
||||
local header = string.format("P6\n%d %d\n255\n", artist.canvas.width, artist.canvas.height)
|
||||
check("ppm size", #data, #header + artist.canvas.width * artist.canvas.height * 3)
|
||||
check("ppm magic", string.sub(data, 1, 2), "P6")
|
||||
end
|
||||
os.remove(path)
|
||||
|
||||
return { passed = passed, failed = #failures, failures = failures }
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,188 @@
|
||||
-- LuaPaint GUI : un éditeur de dessin dans une vraie fenêtre (SDL2), écrit en
|
||||
-- Lua et compilé en un seul binaire par luacpp.
|
||||
--
|
||||
-- ./build/luacpp run Demo/guipaint.lua fenêtre interactive
|
||||
-- ./build/luacpp run Demo/guipaint.lua shot capture de la fenêtre
|
||||
-- ./build/luacpp run Demo/guipaint.lua test tests internes
|
||||
local paint_module = require("gui.paint")
|
||||
local scene = require("gui.scene")
|
||||
local tests = require("gui.tests")
|
||||
|
||||
local M = {}
|
||||
|
||||
local argv = arg or {}
|
||||
local command = argv[1] or "run"
|
||||
|
||||
local function has_gui()
|
||||
return gui ~= nil and gui.open ~= nil
|
||||
end
|
||||
|
||||
local function explain_missing_gui()
|
||||
print("LuaPaint: ce binaire n'expose pas l'API 'gui'.")
|
||||
print(" -> installe SDL2 (libsdl2-dev) puis relance ./build.sh")
|
||||
print(" -> luacpp ne lie la GUI que si SDL2 est trouvé à la configuration")
|
||||
end
|
||||
|
||||
local function run()
|
||||
if not has_gui() then
|
||||
explain_missing_gui()
|
||||
return 1
|
||||
end
|
||||
local app = paint_module.new({})
|
||||
local opened, error_message = gui.open("LuaPaint - dessin", app.width, app.height)
|
||||
if not opened then
|
||||
print("LuaPaint: impossible d'ouvrir la fenêtre : " .. tostring(error_message))
|
||||
print(" DISPLAY est-il défini ? (X11 ou Wayland requis)")
|
||||
return 1
|
||||
end
|
||||
|
||||
local running = true
|
||||
local dirty = true
|
||||
while running do
|
||||
if dirty then
|
||||
app:render()
|
||||
gui.present()
|
||||
dirty = false
|
||||
end
|
||||
-- Drain every pending event before redrawing: a mouse drag queues dozens
|
||||
-- of moves, and each of them used to trigger a full frame on its own.
|
||||
local event = gui.poll()
|
||||
local handled = false
|
||||
while event ~= nil do
|
||||
handled = true
|
||||
if app:handle(event) == "quit" then
|
||||
running = false
|
||||
end
|
||||
event = gui.poll()
|
||||
end
|
||||
if handled then
|
||||
dirty = true
|
||||
else
|
||||
gui.delay(4)
|
||||
end
|
||||
end
|
||||
|
||||
gui.close()
|
||||
print(string.format("LuaPaint : %d cellules peintes, %d étapes d'historique.",
|
||||
app.canvas:count(), app.canvas:history_size()))
|
||||
return 0
|
||||
end
|
||||
|
||||
local function shot(path)
|
||||
if not has_gui() then
|
||||
explain_missing_gui()
|
||||
return 1
|
||||
end
|
||||
local target = path or "guipaint.ppm"
|
||||
local app = paint_module.new({})
|
||||
local opened, error_message = gui.open("LuaPaint - capture", app.width, app.height)
|
||||
if not opened then
|
||||
print("LuaPaint: impossible d'ouvrir la fenêtre : " .. tostring(error_message))
|
||||
return 1
|
||||
end
|
||||
|
||||
scene.picture(app)
|
||||
app:render()
|
||||
local saved, save_error = gui.screenshot(target)
|
||||
gui.present()
|
||||
gui.close()
|
||||
|
||||
if not saved then
|
||||
print("LuaPaint: capture impossible : " .. tostring(save_error))
|
||||
return 1
|
||||
end
|
||||
print("capture : " .. target)
|
||||
print(string.format("%dx%d, %d cellules peintes", app.width, app.height, app.canvas:count()))
|
||||
return 0
|
||||
end
|
||||
|
||||
local function bench(count)
|
||||
if not has_gui() then
|
||||
explain_missing_gui()
|
||||
return 1
|
||||
end
|
||||
local frames = tonumber(count) or 120
|
||||
local app = paint_module.new({})
|
||||
local opened, error_message = gui.open("LuaPaint - bench", app.width, app.height)
|
||||
if not opened then
|
||||
print("LuaPaint: impossible d'ouvrir la fenêtre : " .. tostring(error_message))
|
||||
return 1
|
||||
end
|
||||
|
||||
scene.picture(app)
|
||||
app:render()
|
||||
gui.present()
|
||||
|
||||
local start = gui.time()
|
||||
for _ = 1, frames do
|
||||
app:render()
|
||||
end
|
||||
local render_ms = (gui.time() - start) / frames
|
||||
|
||||
start = gui.time()
|
||||
for _ = 1, frames do
|
||||
app:render()
|
||||
gui.present()
|
||||
end
|
||||
local frame_ms = (gui.time() - start) / frames
|
||||
gui.close()
|
||||
|
||||
if frames <= 0 or render_ms <= 0 then
|
||||
print("LuaPaint: mesure trop courte")
|
||||
return 1
|
||||
end
|
||||
print(string.format("rendu : %.2f ms/frame (%d cellules, %d rectangles)",
|
||||
render_ms, app:painted(), app:render()))
|
||||
print(string.format("affichage : %.2f ms/frame (%.0f fps)", frame_ms, 1000 / frame_ms))
|
||||
return 0
|
||||
end
|
||||
|
||||
local function run_tests()
|
||||
local summary = tests.run()
|
||||
print("LuaPaint GUI - tests internes")
|
||||
print(string.format(" %d tests OK, %d échec(s)", summary.passed, summary.failed))
|
||||
if summary.failed > 0 then
|
||||
print("")
|
||||
for index = 1, #summary.failures do
|
||||
print(" FAIL " .. summary.failures[index])
|
||||
end
|
||||
return 1
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
local function usage()
|
||||
print("LuaPaint GUI - éditeur de dessin dans une fenêtre SDL2, compilé par luacpp")
|
||||
print("")
|
||||
print(" guipaint run fenêtre interactive (défaut)")
|
||||
print(" guipaint shot [fichier] dessine la scène et capture en PPM")
|
||||
print(" guipaint test tests internes (sans fenêtre)")
|
||||
print(" guipaint bench [frames] mesure le temps de rendu dans une fenêtre")
|
||||
print(" guipaint help cette aide")
|
||||
print("")
|
||||
print("Souris : clic gauche pour dessiner, glisser pour un trait, clic droit pour gommer.")
|
||||
print("Touches : 1-6 outils | f formes pleines | p/m couleur | u annuler")
|
||||
print(" c effacer | s enregistrer guipaint.ppm | q quitter")
|
||||
print("")
|
||||
print("Exemple : luacpp run Demo/guipaint.lua shot /tmp/luapaint.ppm")
|
||||
return 0
|
||||
end
|
||||
|
||||
local commands = {
|
||||
run = run,
|
||||
shot = shot,
|
||||
test = run_tests,
|
||||
bench = bench,
|
||||
help = usage,
|
||||
["--help"] = usage,
|
||||
["-h"] = usage,
|
||||
}
|
||||
|
||||
local handler = commands[command]
|
||||
if handler == nil then
|
||||
print("commande inconnue : " .. command)
|
||||
usage()
|
||||
os.exit(2)
|
||||
end
|
||||
|
||||
os.exit(handler(argv[2]) or 0)
|
||||
@@ -0,0 +1,200 @@
|
||||
-- LuaPaint : éditeur de dessin en terminal, 100% Lua, compilé en un binaire.
|
||||
--
|
||||
-- ./build/luacpp run Demo/luapaint.lua démo (3 images)
|
||||
-- ./build/luacpp run Demo/luapaint.lua play édition interactive
|
||||
-- ./build/luacpp run Demo/luapaint.lua snapshot dessin en texte
|
||||
-- ./build/luacpp run Demo/luapaint.lua test tests internes
|
||||
--
|
||||
-- Options : --mono (sans couleurs), --canvas 60x22 (taille de la toile)
|
||||
local app_module = require("paint.app")
|
||||
local screen_module = require("tui.screen")
|
||||
local session = require("paint.session")
|
||||
local palette = require("paint.palette")
|
||||
local tests = require("paint.tests")
|
||||
local theme = require("tui.theme")
|
||||
|
||||
local M = {}
|
||||
|
||||
local argv = arg or {}
|
||||
|
||||
local options = { mono = false, canvas = nil }
|
||||
local positionals = {}
|
||||
|
||||
local index = 1
|
||||
while index <= #argv do
|
||||
local value = argv[index]
|
||||
if value == "--mono" then
|
||||
options.mono = true
|
||||
elseif value == "--canvas" then
|
||||
index = index + 1
|
||||
options.canvas = argv[index]
|
||||
else
|
||||
positionals[#positionals + 1] = value
|
||||
end
|
||||
index = index + 1
|
||||
end
|
||||
|
||||
local command = positionals[1] or "demo"
|
||||
|
||||
local function canvas_size()
|
||||
local width = 60
|
||||
local height = 22
|
||||
if options.canvas ~= nil then
|
||||
local parsed_width, parsed_height = string.match(options.canvas, "^(%d+)x(%d+)$")
|
||||
if parsed_width ~= nil then
|
||||
width = tonumber(parsed_width)
|
||||
height = tonumber(parsed_height)
|
||||
end
|
||||
end
|
||||
width = math.max(theme.minimum.canvas_width, width)
|
||||
height = math.max(theme.minimum.canvas_height, height)
|
||||
return width, height
|
||||
end
|
||||
|
||||
local ESC = string.char(27)
|
||||
|
||||
local function clear_terminal()
|
||||
io.write(ESC .. "[2J" .. ESC .. "[H")
|
||||
end
|
||||
|
||||
local function demo()
|
||||
local width, height = canvas_size()
|
||||
local app = app_module.new({ width = width, height = height })
|
||||
local screen = screen_module.new(app:screen_width(), app:screen_height())
|
||||
local frame_number = 0
|
||||
local ruler = string.rep("=", app:screen_width())
|
||||
-- Copie locale : une closure imbriquée ne peut pas capturer une locale du
|
||||
-- chunk à travers la fonction englobante.
|
||||
local mono = options.mono
|
||||
|
||||
local function stage(label)
|
||||
frame_number = frame_number + 1
|
||||
print(ruler)
|
||||
print(string.format("LuaPaint - image %d/3 : %s", frame_number, label))
|
||||
print(ruler)
|
||||
app:render(screen, { mono = mono })
|
||||
print(screen_module.frame(screen, { mono = mono }))
|
||||
print("")
|
||||
end
|
||||
|
||||
session.run(app, stage)
|
||||
|
||||
print(string.format("cellules peintes : %d / %d", app.canvas:count(), width * height))
|
||||
print(string.format("etapes d'historique : %d", app.canvas:history_size()))
|
||||
print("couleurs utilisees :")
|
||||
for slot = 1, palette.count() do
|
||||
local count = app.canvas:count(palette.index_of_slot(slot))
|
||||
if count > 0 then
|
||||
print(string.format(" %-8s %5d cases", palette.label(slot), count))
|
||||
end
|
||||
end
|
||||
print("")
|
||||
print("Touches : h j k l bouger, espace dessiner, 1-6 outil, f forme pleine,")
|
||||
print(" p m couleur, u r annuler/refaire, c effacer, w ecrire, q quitter.")
|
||||
return 0
|
||||
end
|
||||
|
||||
local function snapshot()
|
||||
local width, height = canvas_size()
|
||||
local app = app_module.new({ width = width, height = height })
|
||||
session.run(app, nil)
|
||||
print(app.canvas:to_ascii())
|
||||
print(string.format("%d cellules peintes", app.canvas:count()))
|
||||
return 0
|
||||
end
|
||||
|
||||
local function is_tty()
|
||||
local ok = os.execute("test -t 0")
|
||||
return ok == true
|
||||
end
|
||||
|
||||
local function play()
|
||||
local width, height = canvas_size()
|
||||
local app = app_module.new({ width = width, height = height })
|
||||
local screen = screen_module.new(app:screen_width(), app:screen_height())
|
||||
local interactive = is_tty()
|
||||
if interactive then
|
||||
os.execute("stty raw -echo 2>/dev/null")
|
||||
end
|
||||
|
||||
local running = true
|
||||
while running do
|
||||
app:render(screen, { mono = options.mono })
|
||||
if not options.mono then
|
||||
clear_terminal()
|
||||
end
|
||||
io.write(screen_module.frame(screen, { mono = options.mono }))
|
||||
io.write("\n")
|
||||
if options.mono then
|
||||
print(string.format("[x %d y %d] %s", app.cursor_x, app.cursor_y, app.message or ""))
|
||||
end
|
||||
io.flush()
|
||||
local key = io.read(1)
|
||||
if key == nil then
|
||||
running = false
|
||||
elseif app:handle(key) == "quit" then
|
||||
running = false
|
||||
end
|
||||
end
|
||||
|
||||
if interactive then
|
||||
os.execute("stty sane")
|
||||
end
|
||||
io.write(ESC .. "[0m\n")
|
||||
print(string.format("LuaPaint : %d cellules peintes, %d etapes d'historique",
|
||||
app.canvas:count(), app.canvas:history_size()))
|
||||
return 0
|
||||
end
|
||||
|
||||
local function run_tests()
|
||||
local summary = tests.run()
|
||||
print("LuaPaint - tests internes")
|
||||
print(string.format(" %d tests OK, %d echec(s)", summary.passed, summary.failed))
|
||||
if summary.failed > 0 then
|
||||
print("")
|
||||
for failure = 1, #summary.failures do
|
||||
print(" FAIL " .. summary.failures[failure])
|
||||
end
|
||||
return 1
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
local function usage()
|
||||
print("LuaPaint - editeur de dessin en terminal, compile par luacpp")
|
||||
print("")
|
||||
print(" luapaint demo dessine un paysage en 3 images (defaut)")
|
||||
print(" luapaint play edition interactive (h j k l, espace, 1-6, q)")
|
||||
print(" luapaint snapshot le dessin en texte, sans couleurs")
|
||||
print(" luapaint test tests internes")
|
||||
print(" luapaint help cette aide")
|
||||
print("")
|
||||
print("Options :")
|
||||
print(" --mono aucune sequence ANSI (sortie comparable)")
|
||||
print(" --canvas LxH taille de la toile (defaut 60x22, min 20x8)")
|
||||
print("")
|
||||
print("Touches : h j k l bouger | espace dessiner | 1 crayon 2 ligne 3 rectangle")
|
||||
print(" 4 ellipse 5 remplir 6 gomme | f forme pleine | p m couleur")
|
||||
print(" u annuler r refaire c effacer w ecrire q quitter")
|
||||
print(string.format("Palette : %d couleurs (256 couleurs ANSI)", palette.count()))
|
||||
return 0
|
||||
end
|
||||
|
||||
local commands = {
|
||||
demo = demo,
|
||||
play = play,
|
||||
snapshot = snapshot,
|
||||
test = run_tests,
|
||||
help = usage,
|
||||
["--help"] = usage,
|
||||
["-h"] = usage,
|
||||
}
|
||||
|
||||
local handler = commands[command]
|
||||
if handler == nil then
|
||||
print("commande inconnue : " .. command)
|
||||
usage()
|
||||
os.exit(2)
|
||||
end
|
||||
|
||||
os.exit(handler() or 0)
|
||||
@@ -0,0 +1,260 @@
|
||||
-- LuaSheet : un tableur en console, 100% Lua, compilé en un binaire unique.
|
||||
--
|
||||
-- ./build/luacpp run Demo/luasheet.lua classeur Budget (défaut)
|
||||
-- ./build/luacpp run Demo/luasheet.lua ventes second classeur
|
||||
-- ./build/luacpp run Demo/luasheet.lua errors feuille d'erreurs
|
||||
-- ./build/luacpp run Demo/luasheet.lua formula "=SUM(1,2,3)*2"
|
||||
-- ./build/luacpp run Demo/luasheet.lua csv
|
||||
-- ./build/luacpp run Demo/luasheet.lua bench 200
|
||||
-- ./build/luacpp run Demo/luasheet.lua test
|
||||
local sheet_module = require("sheet.sheet")
|
||||
local render = require("sheet.render")
|
||||
local workbooks = require("sheet.workbooks")
|
||||
local tests = require("sheet.tests")
|
||||
local builtins = require("sheet.builtins")
|
||||
local format = require("sheet.format")
|
||||
|
||||
local M = {}
|
||||
|
||||
local argv = arg or {}
|
||||
local command = argv[1] or "demo"
|
||||
|
||||
local function echo(line)
|
||||
print(line or "")
|
||||
end
|
||||
|
||||
local function banner(title)
|
||||
echo(string.rep("=", 64))
|
||||
echo(title)
|
||||
echo(string.rep("=", 64))
|
||||
end
|
||||
|
||||
local function demo()
|
||||
local sheet = sheet_module.from_text(workbooks.budget, "Budget 2026")
|
||||
banner("LuaSheet - classeur Budget 2026")
|
||||
echo("")
|
||||
|
||||
local rendered = render.render(sheet)
|
||||
echo(rendered)
|
||||
echo("")
|
||||
echo(string.format(
|
||||
"%d cellules, %d evaluations, %d erreurs",
|
||||
sheet:count(), sheet.stats.eval, sheet.stats.errors
|
||||
))
|
||||
|
||||
echo("")
|
||||
echo("--- inspecteur de formules ---")
|
||||
local inspected = { "D4", "C11", "D11", "B13", "C16", "B18" }
|
||||
for i = 1, #inspected do
|
||||
local key = inspected[i]
|
||||
echo(string.format(" %-4s %-22s -> %s", key, sheet:raw(key) or "", sheet:display(key)))
|
||||
end
|
||||
|
||||
echo("")
|
||||
echo("--- repartition des charges (B4:B9) ---")
|
||||
local posts = {
|
||||
{ "Loyer", "B4" }, { "Courses", "B5" }, { "Transport", "B6" },
|
||||
{ "Energie", "B7" }, { "Loisirs", "B8" }, { "Epargne", "B9" },
|
||||
}
|
||||
local total = 0
|
||||
for i = 1, #posts do
|
||||
local value = sheet:value(posts[i][2])
|
||||
if type(value) == "number" then
|
||||
total = total + value
|
||||
end
|
||||
end
|
||||
for i = 1, #posts do
|
||||
local value = sheet:value(posts[i][2])
|
||||
local label = posts[i][1]
|
||||
local ratio = 0
|
||||
if total > 0 then
|
||||
ratio = value / total
|
||||
end
|
||||
echo(string.format(
|
||||
" %-10s %6s %s %5s",
|
||||
label, format.number(value), render.bar(value, total, 24), format.percent(ratio, 1)
|
||||
))
|
||||
end
|
||||
|
||||
echo("")
|
||||
echo("--- indicateurs ---")
|
||||
local revenue = sheet:value("B12") or 0
|
||||
local remaining = sheet:value("B13") or 0
|
||||
local remaining_ratio = 0
|
||||
if revenue ~= 0 then
|
||||
remaining_ratio = remaining / revenue
|
||||
end
|
||||
local savings = sheet:value("B21") or 0
|
||||
echo(" charges mensuelles : " .. sheet:display("B11"))
|
||||
echo(" reste a vivre : " .. sheet:display("B13") .. " (" .. format.percent(remaining_ratio, 1) .. " des revenus)")
|
||||
echo(" epargne annuelle : " .. sheet:display("B15"))
|
||||
echo(" objectif epargne : " .. sheet:display("B16") .. " -> " .. sheet:display("C16"))
|
||||
echo(" part de l'epargne : " .. format.percent(savings, 1))
|
||||
|
||||
local found = sheet:errors()
|
||||
if #found > 0 then
|
||||
echo("")
|
||||
echo("--- erreurs ---")
|
||||
for i = 1, #found do
|
||||
echo(string.format(" %-4s %-16s %s", found[i].key, found[i].text, found[i].err))
|
||||
end
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
local function ventes()
|
||||
local sheet = sheet_module.from_text(workbooks.ventes, "Ventes")
|
||||
banner("LuaSheet - classeur Ventes")
|
||||
echo("")
|
||||
echo(render.render(sheet))
|
||||
echo("")
|
||||
echo("vue formules :")
|
||||
echo(render.render(sheet, { show_formulas = true }))
|
||||
return 0
|
||||
end
|
||||
|
||||
local function show_errors()
|
||||
local sheet = sheet_module.from_text(workbooks.errors, "Erreurs")
|
||||
banner("LuaSheet - feuille d'erreurs (volontaires)")
|
||||
echo("")
|
||||
echo(render.render(sheet))
|
||||
echo("")
|
||||
local found = sheet:errors()
|
||||
echo(string.format("%d cellules en erreur :", #found))
|
||||
for i = 1, #found do
|
||||
local entry = found[i]
|
||||
echo(string.format(" %-4s %-14s %-10s %s", entry.key, entry.err, entry.text, entry.detail or ""))
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
local function formula(text)
|
||||
if text == nil or text == "" then
|
||||
echo('usage : luasheet formula "=SUM(1,2,3)*2"')
|
||||
return 2
|
||||
end
|
||||
local sheet = sheet_module.new("formula")
|
||||
sheet:set("A1", "120")
|
||||
sheet:set("A2", "80")
|
||||
sheet:set("A3", "Lua")
|
||||
sheet:set("A4", "=A1+A2")
|
||||
if string.sub(text, 1, 1) == "=" then
|
||||
text = string.sub(text, 2)
|
||||
end
|
||||
sheet:set("B1", "=" .. text)
|
||||
echo(string.format("A1=120 A2=80 A3=\"Lua\" A4=A1+A2=%s", sheet:display("A4")))
|
||||
echo(string.format("%s -> %s", text, sheet:display("B1")))
|
||||
local found = sheet:errors()
|
||||
for i = 1, #found do
|
||||
if found[i].key == "B1" and found[i].detail ~= nil then
|
||||
echo("detail : " .. found[i].detail)
|
||||
end
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
local function csv()
|
||||
local sheet = sheet_module.from_text(workbooks.budget, "Budget 2026")
|
||||
echo(render.csv(sheet))
|
||||
return 0
|
||||
end
|
||||
|
||||
local function bench(argument)
|
||||
local rows = tonumber(argument) or 300
|
||||
if rows < 1 then
|
||||
rows = 1
|
||||
end
|
||||
local sheet = sheet_module.new("bench")
|
||||
for row = 1, rows do
|
||||
for column = 1, 7 do
|
||||
sheet:set(format.column_label(column) .. row, tostring((row * column) % 97))
|
||||
end
|
||||
sheet:set("H" .. row, string.format("=SUM(A%d:G%d)", row, row))
|
||||
end
|
||||
sheet:set("I1", string.format("=SUM(H1:H%d)", rows))
|
||||
|
||||
local best = 0
|
||||
local last = 0
|
||||
for pass = 1, 3 do
|
||||
sheet:invalidate()
|
||||
local started = os.clock()
|
||||
local total = sheet:value("I1")
|
||||
local elapsed = os.clock() - started
|
||||
last = total
|
||||
if pass == 1 or elapsed < best then
|
||||
best = elapsed
|
||||
end
|
||||
echo(string.format(
|
||||
" passe %d : %6.1f ms (%d evaluations, total I1 = %s)",
|
||||
pass, elapsed * 1000, sheet.stats.eval, format.number(total)
|
||||
))
|
||||
end
|
||||
|
||||
local cells = rows * 8 + 1
|
||||
local rate = 0
|
||||
if best > 0 then
|
||||
rate = cells / best
|
||||
end
|
||||
echo("")
|
||||
echo(string.format(" %d lignes x 8 colonnes = %d cellules", rows, cells))
|
||||
echo(string.format(" meilleure passe : %.1f ms -> environ %d cellules/s", best * 1000, math.floor(rate)))
|
||||
echo(string.format(" total recalcule : %s", format.number(last)))
|
||||
return 0
|
||||
end
|
||||
|
||||
local function run_tests()
|
||||
banner("LuaSheet - tests internes")
|
||||
local summary = tests.run()
|
||||
echo("")
|
||||
echo(string.format(" %d tests OK, %d echec(s)", summary.passed, summary.failed))
|
||||
if summary.failed > 0 then
|
||||
echo("")
|
||||
for i = 1, #summary.failures do
|
||||
echo(" FAIL " .. summary.failures[i])
|
||||
end
|
||||
return 1
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
local function usage()
|
||||
banner("LuaSheet - tableur en Lua compilé par luacpp")
|
||||
echo("")
|
||||
echo(" luasheet demo classeur Budget 2026 (défaut)")
|
||||
echo(" luasheet ventes second classeur (texte, IF, &)")
|
||||
echo(" luasheet errors feuille d'erreurs (#DIV/0!, #CYCLE!, ...)")
|
||||
echo(' luasheet formula "=..." évalue une formule')
|
||||
echo(" luasheet csv exporte le classeur Budget en CSV")
|
||||
echo(" luasheet bench [lignes] mesure le recalcul (défaut : 300 lignes)")
|
||||
echo(" luasheet test lance les tests internes")
|
||||
echo(" luasheet help cette aide")
|
||||
echo("")
|
||||
echo("Opérateurs : + - * / % ^ & = <> < > <= >=")
|
||||
echo("Références : A1, $A$1, plages A1:B4")
|
||||
echo("Fonctions : " .. table.concat(builtins.names(), " "))
|
||||
echo("")
|
||||
echo("Exemple : luacpp run Demo/luasheet.lua formula \"=SUM(1,2,3)*2\"")
|
||||
return 0
|
||||
end
|
||||
|
||||
local commands = {
|
||||
demo = demo,
|
||||
ventes = ventes,
|
||||
errors = show_errors,
|
||||
formula = formula,
|
||||
csv = csv,
|
||||
bench = bench,
|
||||
test = run_tests,
|
||||
help = usage,
|
||||
["--help"] = usage,
|
||||
["-h"] = usage,
|
||||
}
|
||||
|
||||
local handler = commands[command]
|
||||
if handler == nil then
|
||||
echo("commande inconnue : " .. command)
|
||||
usage()
|
||||
os.exit(2)
|
||||
end
|
||||
|
||||
os.exit(handler(argv[2]) or 0)
|
||||
@@ -0,0 +1,354 @@
|
||||
-- Application state and interaction: the keyboard-driven paint editor.
|
||||
-- The module is UI-framework free: it updates a canvas from key presses and
|
||||
-- paints itself onto a tui.screen framebuffer.
|
||||
local canvas_module = require("paint.canvas")
|
||||
local palette = require("paint.palette")
|
||||
local theme = require("tui.theme")
|
||||
|
||||
local M = {}
|
||||
|
||||
local App = {}
|
||||
App.__index = App
|
||||
|
||||
M.tools = { "crayon", "ligne", "rectangle", "ellipse", "remplir", "gomme" }
|
||||
|
||||
local ANCHOR_TOOLS = { [2] = true, [3] = true, [4] = true }
|
||||
|
||||
local PANEL_WIDTH = theme.minimum.panel_width
|
||||
local CHROME_HEIGHT = theme.minimum.chrome_height
|
||||
|
||||
function M.new(options)
|
||||
options = options or {}
|
||||
local width = options.width or 60
|
||||
local height = options.height or 22
|
||||
local app = setmetatable({
|
||||
canvas = canvas_module.new(width, height),
|
||||
tool = 1,
|
||||
slot = options.slot or palette.default_slot,
|
||||
cursor_x = math.floor(width / 2) + 1,
|
||||
cursor_y = math.floor(height / 2) + 1,
|
||||
anchor_x = nil,
|
||||
anchor_y = nil,
|
||||
filled = false,
|
||||
message = "h j k l pour bouger, espace pour dessiner, 1-6 pour l'outil.",
|
||||
written = nil,
|
||||
}, App)
|
||||
return app
|
||||
end
|
||||
|
||||
function App:screen_width()
|
||||
return self.canvas.width + PANEL_WIDTH + 3
|
||||
end
|
||||
|
||||
function App:screen_height()
|
||||
return self.canvas.height + CHROME_HEIGHT
|
||||
end
|
||||
|
||||
function App:colour()
|
||||
return palette.index_of_slot(self.slot)
|
||||
end
|
||||
|
||||
function App:tool_name()
|
||||
return M.tools[self.tool]
|
||||
end
|
||||
|
||||
function App:needs_anchor()
|
||||
return ANCHOR_TOOLS[self.tool] == true
|
||||
end
|
||||
|
||||
function App:move(dx, dy)
|
||||
self.cursor_x = math.max(1, math.min(self.canvas.width, self.cursor_x + dx))
|
||||
self.cursor_y = math.max(1, math.min(self.canvas.height, self.cursor_y + dy))
|
||||
end
|
||||
|
||||
function App:cancel_anchor()
|
||||
if self.anchor_x ~= nil then
|
||||
self.anchor_x = nil
|
||||
self.anchor_y = nil
|
||||
return true
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
-- Applies the current tool. Anchor tools need two presses: the first one drops
|
||||
-- the anchor, the second one draws between the anchor and the cursor.
|
||||
function App:apply()
|
||||
local canvas = self.canvas
|
||||
local colour = self:colour()
|
||||
if self.tool == 6 then
|
||||
colour = 0
|
||||
end
|
||||
|
||||
if self:needs_anchor() then
|
||||
if self.anchor_x == nil then
|
||||
self.anchor_x = self.cursor_x
|
||||
self.anchor_y = self.cursor_y
|
||||
self.message = string.format("%s : ancre en %d,%d", self:tool_name(), self.cursor_x, self.cursor_y)
|
||||
return "anchor"
|
||||
end
|
||||
|
||||
canvas:push_history()
|
||||
if self.tool == 2 then
|
||||
canvas:line(self.anchor_x, self.anchor_y, self.cursor_x, self.cursor_y, colour)
|
||||
elseif self.tool == 3 then
|
||||
canvas:rect(self.anchor_x, self.anchor_y, self.cursor_x, self.cursor_y, colour, self.filled)
|
||||
else
|
||||
local radius_x = math.abs(self.cursor_x - self.anchor_x)
|
||||
local radius_y = math.abs(self.cursor_y - self.anchor_y)
|
||||
canvas:ellipse(self.anchor_x, self.anchor_y, radius_x, radius_y, colour, self.filled)
|
||||
end
|
||||
self.anchor_x = nil
|
||||
self.anchor_y = nil
|
||||
self.message = string.format("%s termine", self:tool_name())
|
||||
return "commit"
|
||||
end
|
||||
|
||||
canvas:push_history()
|
||||
if self.tool == 1 then
|
||||
canvas:set(self.cursor_x, self.cursor_y, colour)
|
||||
self.message = "crayon en " .. palette.label(self.slot)
|
||||
elseif self.tool == 5 then
|
||||
local painted = canvas:fill(self.cursor_x, self.cursor_y, colour)
|
||||
self.message = string.format("remplissage : %d cases", painted)
|
||||
else
|
||||
canvas:set(self.cursor_x, self.cursor_y, 0)
|
||||
self.message = "gomme"
|
||||
end
|
||||
return "commit"
|
||||
end
|
||||
|
||||
-- Keyboard handling. Returns a short action word: "quit", "commit", "move",
|
||||
-- "tool", "colour", "undo", "redo", "clear", "write" or nil.
|
||||
function App:handle(key)
|
||||
if key == nil then
|
||||
return "quit"
|
||||
end
|
||||
if key == "q" then
|
||||
return "quit"
|
||||
end
|
||||
if key == "h" then
|
||||
self:move(-1, 0)
|
||||
return "move"
|
||||
end
|
||||
if key == "j" then
|
||||
self:move(0, 1)
|
||||
return "move"
|
||||
end
|
||||
if key == "k" then
|
||||
self:move(0, -1)
|
||||
return "move"
|
||||
end
|
||||
if key == "l" then
|
||||
self:move(1, 0)
|
||||
return "move"
|
||||
end
|
||||
if key == " " then
|
||||
return self:apply()
|
||||
end
|
||||
if key == "f" then
|
||||
self.filled = not self.filled
|
||||
if self.filled then
|
||||
self.message = "formes pleines"
|
||||
else
|
||||
self.message = "formes vides"
|
||||
end
|
||||
return "mode"
|
||||
end
|
||||
if key == "p" then
|
||||
self.slot = palette.next_slot(self.slot)
|
||||
self.message = "couleur " .. palette.label(self.slot)
|
||||
return "colour"
|
||||
end
|
||||
if key == "m" then
|
||||
self.slot = palette.previous_slot(self.slot)
|
||||
self.message = "couleur " .. palette.label(self.slot)
|
||||
return "colour"
|
||||
end
|
||||
if key == "u" then
|
||||
if self.canvas:undo() then
|
||||
self.message = "annule"
|
||||
else
|
||||
self.message = "rien a annuler"
|
||||
end
|
||||
return "undo"
|
||||
end
|
||||
if key == "r" then
|
||||
if self.canvas:redo() then
|
||||
self.message = "refait"
|
||||
else
|
||||
self.message = "rien a refaire"
|
||||
end
|
||||
return "redo"
|
||||
end
|
||||
if key == "c" then
|
||||
self.canvas:push_history()
|
||||
self.canvas:clear()
|
||||
self.message = "toile vide"
|
||||
return "clear"
|
||||
end
|
||||
if key == "w" then
|
||||
local name = "luapaint.txt"
|
||||
local handle = io.open(name, "w")
|
||||
if handle ~= nil then
|
||||
handle:write("LuaPaint " .. self.canvas.width .. "x" .. self.canvas.height .. "\n")
|
||||
handle:write(self.canvas:to_hex())
|
||||
handle:write("\n")
|
||||
handle:close()
|
||||
self.message = "ecrit dans " .. name
|
||||
return "write"
|
||||
end
|
||||
self.message = "impossible d'ecrire " .. name
|
||||
return nil
|
||||
end
|
||||
local number = tonumber(key)
|
||||
if number ~= nil and number >= 1 and number <= #M.tools then
|
||||
self.tool = number
|
||||
self:cancel_anchor()
|
||||
self.message = "outil " .. self:tool_name()
|
||||
return "tool"
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- Shape preview between the anchor and the cursor, drawn on a scratch canvas.
|
||||
function App:preview()
|
||||
if not self:needs_anchor() or self.anchor_x == nil then
|
||||
return nil
|
||||
end
|
||||
local scratch = canvas_module.new(self.canvas.width, self.canvas.height)
|
||||
if self.tool == 2 then
|
||||
scratch:line(self.anchor_x, self.anchor_y, self.cursor_x, self.cursor_y, 1)
|
||||
elseif self.tool == 3 then
|
||||
scratch:rect(self.anchor_x, self.anchor_y, self.cursor_x, self.cursor_y, 1, self.filled)
|
||||
else
|
||||
local radius_x = math.abs(self.cursor_x - self.anchor_x)
|
||||
local radius_y = math.abs(self.cursor_y - self.anchor_y)
|
||||
scratch:ellipse(self.anchor_x, self.anchor_y, radius_x, radius_y, 1, self.filled)
|
||||
end
|
||||
return scratch
|
||||
end
|
||||
|
||||
local function draw_tools_panel(app, screen, x, y, width, height)
|
||||
local background = theme.ui.panel_bg
|
||||
screen:box(x, y, width, height, theme.ui.panel_border, background)
|
||||
screen:title(x, y, width, "Outils", theme.ui.bar_fg, theme.ui.bar_bg)
|
||||
|
||||
local row = y + 2
|
||||
for index = 1, #M.tools do
|
||||
local selected = index == app.tool
|
||||
local fg = theme.ui.panel_fg
|
||||
local bg = background
|
||||
local marker = " "
|
||||
if selected then
|
||||
fg = theme.ui.accent_fg
|
||||
bg = theme.ui.accent_bg
|
||||
marker = "> "
|
||||
end
|
||||
screen:fill_rect(x + 1, row, width - 2, 1, " ", fg, bg)
|
||||
screen:put(x + 2, row, string.format("%s%d %s", marker, index, M.tools[index]), fg, bg)
|
||||
row = row + 1
|
||||
end
|
||||
|
||||
row = row + 1
|
||||
if row < y + height - 1 then
|
||||
screen:bar(x + 1, row, width - 2, "Couleurs", theme.ui.accent_fg, theme.ui.accent_bg)
|
||||
row = row + 1
|
||||
for line = 0, 1 do
|
||||
for column = 0, 5 do
|
||||
local slot = line * 6 + column + 1
|
||||
if slot <= palette.count() then
|
||||
local entry = palette.entries[slot]
|
||||
local swatch_x = x + 2 + column * 3
|
||||
local swatch_y = row + line
|
||||
local fg = 16
|
||||
if slot == app.slot then
|
||||
fg = 231
|
||||
end
|
||||
screen:put(swatch_x, swatch_y, string.format("%2d", slot), fg, entry.index)
|
||||
end
|
||||
end
|
||||
end
|
||||
row = row + 3
|
||||
screen:put(x + 2, row, "couleur : " .. palette.label(app.slot), theme.ui.panel_fg, background)
|
||||
row = row + 2
|
||||
local keys = { "espace dessiner", "f plein/vide", "u / r annuler", "c effacer", "p / m couleur", "w ecrire", "q quitter" }
|
||||
for index = 1, #keys do
|
||||
if row + index - 1 < y + height - 1 then
|
||||
screen:put(x + 2, row + index - 1, keys[index], theme.ui.muted, background)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function App:render(screen, settings)
|
||||
local canvas = self.canvas
|
||||
local ui = theme.ui
|
||||
local mono = false
|
||||
if settings ~= nil then
|
||||
mono = settings.mono == true
|
||||
end
|
||||
local painted = " "
|
||||
if mono then
|
||||
painted = "#"
|
||||
end
|
||||
screen:clear(" ", ui.canvas_fg, ui.canvas_bg)
|
||||
|
||||
local box_width = canvas.width + 2
|
||||
local box_height = canvas.height + 2
|
||||
screen:box(1, 1, box_width, box_height, ui.panel_border, ui.canvas_bg)
|
||||
screen:title(1, 1, box_width, "LuaPaint", ui.bar_fg, ui.bar_bg)
|
||||
|
||||
local preview = self:preview()
|
||||
for y = 1, canvas.height do
|
||||
for x = 1, canvas.width do
|
||||
local colour = canvas:get(x, y)
|
||||
local fg = ui.canvas_fg
|
||||
local bg = ui.canvas_bg
|
||||
local character = "."
|
||||
if colour ~= 0 then
|
||||
fg = colour
|
||||
bg = colour
|
||||
character = painted
|
||||
end
|
||||
if preview ~= nil and preview:get(x, y) ~= 0 then
|
||||
fg = ui.cursor_fg
|
||||
bg = ui.accent_bg
|
||||
character = ":"
|
||||
end
|
||||
screen:put(x + 1, y + 1, character, fg, bg)
|
||||
end
|
||||
end
|
||||
|
||||
if self.anchor_x ~= nil then
|
||||
screen:put(self.anchor_x + 1, self.anchor_y + 1, "o", ui.cursor_fg, ui.cursor_bg)
|
||||
end
|
||||
screen:put(self.cursor_x + 1, self.cursor_y + 1, "+", ui.cursor_fg, ui.cursor_bg)
|
||||
|
||||
draw_tools_panel(self, screen, canvas.width + 4, 1, PANEL_WIDTH, box_height)
|
||||
|
||||
local status_y = canvas.height + 3
|
||||
if status_y <= screen.height then
|
||||
screen:fill_rect(1, status_y, screen.width, 1, " ", ui.status_fg, ui.status_bg)
|
||||
local shape = "vide"
|
||||
if self.filled then
|
||||
shape = "plein"
|
||||
end
|
||||
screen:put(2, status_y, string.format(
|
||||
"outil %s (%s) | couleur %s | x %d y %d | annuler %d | refaire %d",
|
||||
self:tool_name(), shape, palette.label(self.slot), self.cursor_x, self.cursor_y,
|
||||
canvas:history_size(), canvas:future_size()
|
||||
), ui.status_fg, ui.status_bg)
|
||||
end
|
||||
|
||||
local message_y = canvas.height + 4
|
||||
if message_y <= screen.height then
|
||||
screen:fill_rect(1, message_y, screen.width, 1, " ", ui.panel_fg, ui.panel_bg)
|
||||
screen:put(2, message_y, self.message or "", ui.muted, ui.panel_bg)
|
||||
end
|
||||
|
||||
return screen
|
||||
end
|
||||
|
||||
M.App = App
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,296 @@
|
||||
-- Pixel grid with the drawing primitives of the paint application:
|
||||
-- Bresenham lines, rectangles, ellipses, flood fill and an undo/redo stack.
|
||||
local M = {}
|
||||
|
||||
local Canvas = {}
|
||||
Canvas.__index = Canvas
|
||||
|
||||
local HISTORY_LIMIT = 32
|
||||
|
||||
function M.new(width, height)
|
||||
local canvas = setmetatable({
|
||||
width = width,
|
||||
height = height,
|
||||
cells = {},
|
||||
version = 0,
|
||||
history = {},
|
||||
future = {},
|
||||
}, Canvas)
|
||||
for index = 1, width * height do
|
||||
canvas.cells[index] = 0
|
||||
end
|
||||
return canvas
|
||||
end
|
||||
|
||||
function Canvas:in_bounds(x, y)
|
||||
return x >= 1 and y >= 1 and x <= self.width and y <= self.height
|
||||
end
|
||||
|
||||
function Canvas:index(x, y)
|
||||
if not self:in_bounds(x, y) then
|
||||
return nil
|
||||
end
|
||||
return (y - 1) * self.width + x
|
||||
end
|
||||
|
||||
function Canvas:get(x, y)
|
||||
local index = self:index(x, y)
|
||||
if index == nil then
|
||||
return 0
|
||||
end
|
||||
return self.cells[index]
|
||||
end
|
||||
|
||||
function Canvas:set(x, y, colour)
|
||||
local index = self:index(x, y)
|
||||
if index ~= nil and self.cells[index] ~= colour then
|
||||
self.cells[index] = colour
|
||||
self.version = self.version + 1
|
||||
end
|
||||
end
|
||||
|
||||
function Canvas:copy_cells()
|
||||
local copy = {}
|
||||
for index = 1, #self.cells do
|
||||
copy[index] = self.cells[index]
|
||||
end
|
||||
return copy
|
||||
end
|
||||
|
||||
function Canvas:push_history()
|
||||
table.insert(self.history, self:copy_cells())
|
||||
if #self.history > HISTORY_LIMIT then
|
||||
table.remove(self.history, 1)
|
||||
end
|
||||
self.future = {}
|
||||
end
|
||||
|
||||
function Canvas:undo()
|
||||
if #self.history == 0 then
|
||||
return false
|
||||
end
|
||||
table.insert(self.future, self:copy_cells())
|
||||
self.cells = table.remove(self.history)
|
||||
self.version = self.version + 1
|
||||
return true
|
||||
end
|
||||
|
||||
function Canvas:redo()
|
||||
if #self.future == 0 then
|
||||
return false
|
||||
end
|
||||
table.insert(self.history, self:copy_cells())
|
||||
self.cells = table.remove(self.future)
|
||||
self.version = self.version + 1
|
||||
return true
|
||||
end
|
||||
|
||||
function Canvas:history_size()
|
||||
return #self.history
|
||||
end
|
||||
|
||||
function Canvas:future_size()
|
||||
return #self.future
|
||||
end
|
||||
|
||||
function Canvas:line(x1, y1, x2, y2, colour)
|
||||
local dx = math.abs(x2 - x1)
|
||||
local dy = math.abs(y2 - y1)
|
||||
local step_x = 1
|
||||
if x2 < x1 then
|
||||
step_x = -1
|
||||
end
|
||||
local step_y = 1
|
||||
if y2 < y1 then
|
||||
step_y = -1
|
||||
end
|
||||
local error = dx - dy
|
||||
local x, y = x1, y1
|
||||
local guard = (dx + dy) * 2 + 4
|
||||
while guard > 0 do
|
||||
guard = guard - 1
|
||||
self:set(x, y, colour)
|
||||
if x == x2 and y == y2 then
|
||||
break
|
||||
end
|
||||
local doubled = 2 * error
|
||||
if doubled > -dy then
|
||||
error = error - dy
|
||||
x = x + step_x
|
||||
end
|
||||
if doubled < dx then
|
||||
error = error + dx
|
||||
y = y + step_y
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function Canvas:rect(x1, y1, x2, y2, colour, filled)
|
||||
local left = math.min(x1, x2)
|
||||
local right = math.max(x1, x2)
|
||||
local top = math.min(y1, y2)
|
||||
local bottom = math.max(y1, y2)
|
||||
if filled then
|
||||
for y = top, bottom do
|
||||
for x = left, right do
|
||||
self:set(x, y, colour)
|
||||
end
|
||||
end
|
||||
return
|
||||
end
|
||||
self:line(left, top, right, top, colour)
|
||||
self:line(right, top, right, bottom, colour)
|
||||
self:line(right, bottom, left, bottom, colour)
|
||||
self:line(left, bottom, left, top, colour)
|
||||
end
|
||||
|
||||
function Canvas:ellipse(centre_x, centre_y, radius_x, radius_y, colour, filled)
|
||||
local rx = math.abs(radius_x)
|
||||
local ry = math.abs(radius_y)
|
||||
if rx == 0 and ry == 0 then
|
||||
self:set(centre_x, centre_y, colour)
|
||||
return
|
||||
end
|
||||
if ry == 0 then
|
||||
self:line(centre_x - rx, centre_y, centre_x + rx, centre_y, colour)
|
||||
return
|
||||
end
|
||||
if rx == 0 then
|
||||
self:line(centre_x, centre_y - ry, centre_x, centre_y + ry, colour)
|
||||
return
|
||||
end
|
||||
|
||||
local function inside(x, y)
|
||||
local normalised_x = (x - centre_x) / rx
|
||||
local normalised_y = (y - centre_y) / ry
|
||||
return normalised_x * normalised_x + normalised_y * normalised_y <= 1.0
|
||||
end
|
||||
|
||||
for y = centre_y - ry, centre_y + ry do
|
||||
for x = centre_x - rx, centre_x + rx do
|
||||
if inside(x, y) then
|
||||
local edge = not (inside(x - 1, y) and inside(x + 1, y) and inside(x, y - 1) and inside(x, y + 1))
|
||||
if filled or edge then
|
||||
self:set(x, y, colour)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- Flood fill of the connected region sharing the colour under (x, y).
|
||||
-- Iterative on purpose: no recursion depth limit on big areas.
|
||||
function Canvas:fill(x, y, colour)
|
||||
if not self:in_bounds(x, y) then
|
||||
return 0
|
||||
end
|
||||
local target = self:get(x, y)
|
||||
if target == colour then
|
||||
return 0
|
||||
end
|
||||
|
||||
local stack = { (y - 1) * self.width + x }
|
||||
local painted = 0
|
||||
while #stack > 0 do
|
||||
local index = table.remove(stack)
|
||||
if self.cells[index] == target then
|
||||
self.cells[index] = colour
|
||||
painted = painted + 1
|
||||
local zero_based = index - 1
|
||||
local column = zero_based % self.width
|
||||
local row = zero_based // self.width
|
||||
if column > 0 then
|
||||
table.insert(stack, index - 1)
|
||||
end
|
||||
if column < self.width - 1 then
|
||||
table.insert(stack, index + 1)
|
||||
end
|
||||
if row > 0 then
|
||||
table.insert(stack, index - self.width)
|
||||
end
|
||||
if row < self.height - 1 then
|
||||
table.insert(stack, index + self.width)
|
||||
end
|
||||
end
|
||||
end
|
||||
if painted > 0 then
|
||||
self.version = self.version + 1
|
||||
end
|
||||
return painted
|
||||
end
|
||||
|
||||
function Canvas:clear()
|
||||
local touched = false
|
||||
for index = 1, #self.cells do
|
||||
if self.cells[index] ~= 0 then
|
||||
self.cells[index] = 0
|
||||
touched = true
|
||||
end
|
||||
end
|
||||
if touched then
|
||||
self.version = self.version + 1
|
||||
end
|
||||
end
|
||||
|
||||
function Canvas:count(colour)
|
||||
if colour == nil then
|
||||
local total = 0
|
||||
for index = 1, #self.cells do
|
||||
if self.cells[index] ~= 0 then
|
||||
total = total + 1
|
||||
end
|
||||
end
|
||||
return total
|
||||
end
|
||||
local total = 0
|
||||
for index = 1, #self.cells do
|
||||
if self.cells[index] == colour then
|
||||
total = total + 1
|
||||
end
|
||||
end
|
||||
return total
|
||||
end
|
||||
|
||||
function Canvas:is_empty()
|
||||
for index = 1, #self.cells do
|
||||
if self.cells[index] ~= 0 then
|
||||
return false
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
-- Plain text view of the grid: '#' painted, '.' empty. Used by the tests and
|
||||
-- by the `snapshot` command.
|
||||
function Canvas:to_ascii()
|
||||
local lines = {}
|
||||
for y = 1, self.height do
|
||||
local parts = {}
|
||||
for x = 1, self.width do
|
||||
if self:get(x, y) == 0 then
|
||||
parts[#parts + 1] = "."
|
||||
else
|
||||
parts[#parts + 1] = "#"
|
||||
end
|
||||
end
|
||||
lines[#lines + 1] = table.concat(parts)
|
||||
end
|
||||
return table.concat(lines, "\n")
|
||||
end
|
||||
|
||||
-- Colours of each cell as hexadecimal, for the save command.
|
||||
function Canvas:to_hex()
|
||||
local lines = {}
|
||||
for y = 1, self.height do
|
||||
local parts = {}
|
||||
for x = 1, self.width do
|
||||
parts[#parts + 1] = string.format("%02x", self:get(x, y))
|
||||
end
|
||||
lines[#lines + 1] = table.concat(parts, " ")
|
||||
end
|
||||
return table.concat(lines, "\n")
|
||||
end
|
||||
|
||||
M.Canvas = Canvas
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,85 @@
|
||||
-- Drawing palette: each entry is a named 256-colour index.
|
||||
local M = {}
|
||||
|
||||
-- Each entry carries the ANSI 256-colour index used by the terminal editor
|
||||
-- and the RGB triplet used by the windowed one.
|
||||
M.entries = {
|
||||
{ name = "nuit", index = 17, rgb = { 24, 32, 84 } },
|
||||
{ name = "gris", index = 240, rgb = { 120, 120, 126 } },
|
||||
{ name = "blanc", index = 231, rgb = { 245, 245, 245 } },
|
||||
{ name = "rouge", index = 196, rgb = { 214, 40, 60 } },
|
||||
{ name = "orange", index = 208, rgb = { 235, 130, 35 } },
|
||||
{ name = "jaune", index = 226, rgb = { 245, 215, 60 } },
|
||||
{ name = "vert", index = 46, rgb = { 50, 205, 70 } },
|
||||
{ name = "cyan", index = 51, rgb = { 60, 215, 215 } },
|
||||
{ name = "bleu", index = 33, rgb = { 50, 120, 220 } },
|
||||
{ name = "violet", index = 129, rgb = { 140, 90, 220 } },
|
||||
{ name = "rose", index = 205, rgb = { 240, 110, 165 } },
|
||||
{ name = "brun", index = 94, rgb = { 140, 95, 55 } },
|
||||
}
|
||||
|
||||
M.background_rgb = { 26, 28, 34 }
|
||||
|
||||
M.default_slot = 4 -- rouge
|
||||
|
||||
function M.count()
|
||||
return #M.entries
|
||||
end
|
||||
|
||||
function M.is_valid_slot(slot)
|
||||
return type(slot) == "number" and slot >= 1 and slot <= #M.entries
|
||||
end
|
||||
|
||||
function M.index_of_slot(slot)
|
||||
if not M.is_valid_slot(slot) then
|
||||
return 0
|
||||
end
|
||||
return M.entries[slot].index
|
||||
end
|
||||
|
||||
function M.label(slot)
|
||||
if not M.is_valid_slot(slot) then
|
||||
return "?"
|
||||
end
|
||||
return M.entries[slot].name
|
||||
end
|
||||
|
||||
function M.slot_of(name)
|
||||
for slot = 1, #M.entries do
|
||||
if M.entries[slot].name == name then
|
||||
return slot
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- RGB of a cell colour: index 0 is the empty canvas background.
|
||||
function M.rgb_of(index)
|
||||
if index == 0 or index == nil then
|
||||
return M.background_rgb
|
||||
end
|
||||
for slot = 1, #M.entries do
|
||||
if M.entries[slot].index == index then
|
||||
return M.entries[slot].rgb
|
||||
end
|
||||
end
|
||||
return M.background_rgb
|
||||
end
|
||||
|
||||
function M.next_slot(slot)
|
||||
local next_slot = slot + 1
|
||||
if next_slot > #M.entries then
|
||||
next_slot = 1
|
||||
end
|
||||
return next_slot
|
||||
end
|
||||
|
||||
function M.previous_slot(slot)
|
||||
local previous = slot - 1
|
||||
if previous < 1 then
|
||||
previous = #M.entries
|
||||
end
|
||||
return previous
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,78 @@
|
||||
-- A recorded drawing session: draws a small landscape with the real tools of
|
||||
-- the application, so `luapaint demo` and the tests exercise the same code.
|
||||
local palette = require("paint.palette")
|
||||
|
||||
local M = {}
|
||||
|
||||
local function set_cursor(app, x, y)
|
||||
app.cursor_x = x
|
||||
app.cursor_y = y
|
||||
end
|
||||
|
||||
-- Two presses for anchor tools (line, rectangle, ellipse), one for the rest.
|
||||
-- For an ellipse the first point is the centre and the second one a corner of
|
||||
-- its bounding box, exactly like the interactive tool.
|
||||
local function stroke(app, tool, colour_name, x1, y1, x2, y2, filled)
|
||||
app.tool = tool
|
||||
app.filled = filled == true
|
||||
local slot = palette.slot_of(colour_name)
|
||||
if slot ~= nil then
|
||||
app.slot = slot
|
||||
end
|
||||
app.anchor_x = nil
|
||||
app.anchor_y = nil
|
||||
set_cursor(app, x1, y1)
|
||||
app:handle(" ")
|
||||
if x2 ~= nil then
|
||||
set_cursor(app, x2, y2)
|
||||
app:handle(" ")
|
||||
end
|
||||
end
|
||||
|
||||
local function star(app, x, y)
|
||||
stroke(app, 1, "blanc", x, y)
|
||||
end
|
||||
|
||||
function M.run(app, on_stage)
|
||||
local width = app.canvas.width
|
||||
local height = app.canvas.height
|
||||
|
||||
-- sky, stars and sun
|
||||
stroke(app, 5, "nuit", 1, 1)
|
||||
star(app, 5, 2)
|
||||
star(app, 12, 4)
|
||||
star(app, 27, 2)
|
||||
star(app, 44, 6)
|
||||
star(app, 55, 3)
|
||||
stroke(app, 4, "jaune", 50, 4, 54, 6, true)
|
||||
if on_stage ~= nil then
|
||||
on_stage("ciel, etoiles et soleil")
|
||||
end
|
||||
|
||||
-- ground, house and roof
|
||||
stroke(app, 3, "vert", 1, height - 4, width, height, true)
|
||||
stroke(app, 3, "brun", 10, 9, 26, height - 5, true)
|
||||
for row = 3, 9 do
|
||||
local half = math.floor((row - 3) * 1.5)
|
||||
stroke(app, 3, "brun", 18 - half, row, 18 + half, row, true)
|
||||
end
|
||||
stroke(app, 3, "nuit", 16, height - 9, 20, height - 5, true)
|
||||
stroke(app, 3, "cyan", 22, 11, 25, 13, true)
|
||||
if on_stage ~= nil then
|
||||
on_stage("maison, toit, porte et fenetre")
|
||||
end
|
||||
|
||||
-- tree
|
||||
stroke(app, 3, "brun", 33, height - 8, 34, height - 4, true)
|
||||
stroke(app, 4, "vert", 34, 10, 39, 15, true)
|
||||
if on_stage ~= nil then
|
||||
on_stage("arbre et finitions")
|
||||
end
|
||||
|
||||
app.message = "Paysage termine : w pour ecrire, u pour annuler, q pour quitter."
|
||||
app.cursor_x = 18
|
||||
app.cursor_y = 6
|
||||
return app
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,240 @@
|
||||
-- Self tests of the paint application: framebuffer, canvas primitives,
|
||||
-- palette, keyboard handling and the recorded session.
|
||||
local screen_module = require("tui.screen")
|
||||
local canvas_module = require("paint.canvas")
|
||||
local palette = require("paint.palette")
|
||||
local app_module = require("paint.app")
|
||||
local session = require("paint.session")
|
||||
|
||||
local M = {}
|
||||
|
||||
local ESC = string.char(27)
|
||||
|
||||
local function row_text(screen, y)
|
||||
local start = (y - 1) * (screen.width + 1) + 1
|
||||
local snapshot = screen:snapshot()
|
||||
return string.sub(snapshot, start, start + screen.width - 1)
|
||||
end
|
||||
|
||||
function M.run()
|
||||
local passed = 0
|
||||
local failures = {}
|
||||
|
||||
local function check(name, actual, expected)
|
||||
if actual == expected then
|
||||
passed = passed + 1
|
||||
else
|
||||
failures[#failures + 1] = string.format(
|
||||
"%s : attendu %s, obtenu %s",
|
||||
name, tostring(expected), tostring(actual)
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
local function check_true(name, condition, detail)
|
||||
if condition then
|
||||
passed = passed + 1
|
||||
else
|
||||
failures[#failures + 1] = name .. " : " .. tostring(detail or "condition fausse")
|
||||
end
|
||||
end
|
||||
|
||||
-- framebuffer ---------------------------------------------------------
|
||||
local screen = screen_module.new(10, 3)
|
||||
check("screen rows", #screen:snapshot(), 3 * 10 + 2)
|
||||
screen:put(1, 1, "abc")
|
||||
check("put writes", row_text(screen, 1), "abc ")
|
||||
screen:put(8, 1, "abcdef")
|
||||
check("put clips", row_text(screen, 1), "abc abc")
|
||||
screen:put(1, 0, "x")
|
||||
screen:put(99, 1, "x")
|
||||
check("put ignores out of bounds", row_text(screen, 1), "abc abc")
|
||||
|
||||
screen:clear()
|
||||
screen:box(1, 1, 4, 3)
|
||||
check("box top", row_text(screen, 1), "+--+ ")
|
||||
check("box middle", row_text(screen, 2), "| | ")
|
||||
check("box bottom", row_text(screen, 3), "+--+ ")
|
||||
|
||||
screen:title(1, 1, 4, "T", 5, 6)
|
||||
check_true("title visible", string.find(row_text(screen, 1), "T", 1, true) ~= nil, row_text(screen, 1))
|
||||
|
||||
screen:bar(1, 3, 10, "ok", 2, 3)
|
||||
check("bar text", row_text(screen, 3), " ok ")
|
||||
|
||||
local coloured = screen_module.new(4, 2)
|
||||
coloured:fill_rect(1, 1, 2, 1, "#", 9, 10)
|
||||
local escaped = screen_module.frame(coloured)
|
||||
check_true("frame has colour escapes", string.find(escaped, "48;5;10", 1, true) ~= nil, "no bg escape")
|
||||
check_true("frame ends with reset", string.find(escaped, ESC .. "[0m", 1, true) ~= nil, "no reset")
|
||||
local plain_frame = screen_module.frame(coloured, { mono = true })
|
||||
check("mono frame has no escape", string.find(plain_frame, ESC, 1, true), nil)
|
||||
check_true("mono frame keeps characters", string.find(plain_frame, "##", 1, true) ~= nil, plain_frame)
|
||||
|
||||
-- canvas primitives ---------------------------------------------------
|
||||
local canvas = canvas_module.new(10, 10)
|
||||
check_true("new canvas is empty", canvas:is_empty(), "not empty")
|
||||
check("empty count", canvas:count(), 0)
|
||||
canvas:set(3, 4, 7)
|
||||
check("set/get", canvas:get(3, 4), 7)
|
||||
check("set out of bounds", canvas:get(99, 99), 0)
|
||||
canvas:set(99, 99, 7)
|
||||
check("set ignores out of bounds", canvas:count(), 1)
|
||||
|
||||
local horizontal = canvas_module.new(10, 10)
|
||||
horizontal:line(1, 1, 5, 1, 8)
|
||||
check("horizontal line length", horizontal:count(), 5)
|
||||
check("horizontal line middle", horizontal:get(3, 1), 8)
|
||||
check("horizontal line ends", horizontal:get(1, 1) + horizontal:get(5, 1), 16)
|
||||
|
||||
local diagonal = canvas_module.new(10, 10)
|
||||
diagonal:line(1, 1, 5, 5, 8)
|
||||
check("diagonal line length", diagonal:count(), 5)
|
||||
check("diagonal line middle", diagonal:get(3, 3), 8)
|
||||
|
||||
local reversed = canvas_module.new(10, 10)
|
||||
reversed:line(5, 5, 1, 1, 8)
|
||||
check("reversed line length", reversed:count(), 5)
|
||||
check("reversed line middle", reversed:get(3, 3), 8)
|
||||
|
||||
local outline = canvas_module.new(10, 10)
|
||||
outline:rect(2, 2, 6, 5, 3, false)
|
||||
check("rect outline perimeter", outline:count(), 14)
|
||||
check("rect outline corner", outline:get(2, 2), 3)
|
||||
check("rect outline interior empty", outline:get(4, 3), 0)
|
||||
|
||||
local solid = canvas_module.new(10, 10)
|
||||
solid:rect(2, 2, 6, 5, 3, true)
|
||||
check("rect filled area", solid:count(), 20)
|
||||
check("rect filled interior", solid:get(4, 3), 3)
|
||||
|
||||
local oval = canvas_module.new(21, 21)
|
||||
oval:ellipse(11, 11, 5, 3, 4, true)
|
||||
check("ellipse centre", oval:get(11, 11), 4)
|
||||
check_true("ellipse symmetric", oval:get(6, 11) == oval:get(16, 11), "asymmetric")
|
||||
check_true("ellipse painted", oval:count() > 10, oval:count())
|
||||
|
||||
local flat = canvas_module.new(9, 9)
|
||||
flat:ellipse(5, 5, 3, 0, 6, true)
|
||||
check("flat ellipse is a line", flat:count(), 7)
|
||||
|
||||
local bucket = canvas_module.new(7, 5)
|
||||
bucket:rect(1, 1, 7, 5, 3, false)
|
||||
local painted = bucket:fill(4, 3, 7)
|
||||
check("fill painted interior", painted, 15)
|
||||
check("fill kept outline", bucket:get(1, 1), 3)
|
||||
check("fill same colour is a no-op", bucket:fill(4, 3, 7), 0)
|
||||
check("fill outside is untouched", canvas_module.new(3, 3):fill(2, 2, 4), 9)
|
||||
|
||||
-- undo / redo ---------------------------------------------------------
|
||||
local history = canvas_module.new(4, 4)
|
||||
check("undo without history", history:undo(), false)
|
||||
history:push_history()
|
||||
history:set(1, 1, 5)
|
||||
check("after edit", history:get(1, 1), 5)
|
||||
check("undo returns true", history:undo(), true)
|
||||
check("undo restores", history:get(1, 1), 0)
|
||||
check("redo returns true", history:redo(), true)
|
||||
check("redo reapplies", history:get(1, 1), 5)
|
||||
check("history size limited", history:history_size() <= 32, true)
|
||||
|
||||
-- palette -------------------------------------------------------------
|
||||
check("palette size", palette.count(), 12)
|
||||
check("palette default label", palette.label(palette.default_slot), "rouge")
|
||||
check("palette colour index", palette.index_of_slot(6), 226)
|
||||
check("palette slot by name", palette.slot_of("jaune"), 6)
|
||||
check("palette next wraps", palette.next_slot(12), 1)
|
||||
check("palette previous wraps", palette.previous_slot(1), 12)
|
||||
check("palette invalid colour", palette.index_of_slot(99), 0)
|
||||
|
||||
-- text exports --------------------------------------------------------
|
||||
local exported = canvas_module.new(2, 1)
|
||||
exported:set(1, 1, 17)
|
||||
check("hex export", exported:to_hex(), "11 00")
|
||||
check("ascii export", exported:to_ascii(), "#.")
|
||||
|
||||
-- application ---------------------------------------------------------
|
||||
local app = app_module.new({ width = 20, height = 10 })
|
||||
check("initial cursor x", app.cursor_x, 11)
|
||||
check("initial cursor y", app.cursor_y, 6)
|
||||
check("initial tool", app:tool_name(), "crayon")
|
||||
app:handle("h")
|
||||
check("move left", app.cursor_x, 10)
|
||||
app:handle("j")
|
||||
check("move down", app.cursor_y, 7)
|
||||
for _ = 1, 50 do
|
||||
app:handle("h")
|
||||
end
|
||||
check("cursor clamped left", app.cursor_x, 1)
|
||||
app:handle("3")
|
||||
check("tool selection", app:tool_name(), "rectangle")
|
||||
check("anchor tool", app:needs_anchor(), true)
|
||||
check("anchor press", app:handle(" "), "anchor")
|
||||
app.cursor_x = 8
|
||||
app.cursor_y = 6
|
||||
check("shape commit", app:handle(" "), "commit")
|
||||
check("shape drawn", app.canvas:get(8, 6), app:colour())
|
||||
check("anchor cleared", app.anchor_x, nil)
|
||||
|
||||
check("colour cycle", app:handle("p"), "colour")
|
||||
local cycled = app.slot
|
||||
app:handle("m")
|
||||
check("colour back", app.slot, palette.previous_slot(cycled))
|
||||
|
||||
check("undo key", app:handle("u"), "undo")
|
||||
check("clear key", app:handle("c"), "clear")
|
||||
check_true("canvas cleared", app.canvas:is_empty(), "not empty")
|
||||
check("quit key", app:handle("q"), "quit")
|
||||
check("unknown key", app:handle("@"), nil)
|
||||
check("filled toggle", app:handle("f"), "mode")
|
||||
check_true("filled enabled", app.filled, "filled is off")
|
||||
|
||||
local layout_app = app_module.new({ width = 20, height = 10 })
|
||||
check("screen width", layout_app:screen_width(), 45)
|
||||
check("screen height", layout_app:screen_height(), 15)
|
||||
local layout = screen_module.new(layout_app:screen_width(), layout_app:screen_height())
|
||||
layout_app:render(layout)
|
||||
local snapshot = layout:snapshot()
|
||||
check_true("title rendered", string.find(snapshot, "LuaPaint", 1, true) ~= nil, "no title")
|
||||
check_true("panel rendered", string.find(snapshot, "Outils", 1, true) ~= nil, "no panel")
|
||||
check_true("tools rendered", string.find(snapshot, "crayon", 1, true) ~= nil, "no tools")
|
||||
check_true("status rendered", string.find(snapshot, "outil crayon", 1, true) ~= nil, "no status")
|
||||
check_true("message rendered", string.find(snapshot, "espace", 1, true) ~= nil, "no message")
|
||||
|
||||
-- recorded session ----------------------------------------------------
|
||||
local artist = app_module.new({ width = 60, height = 22 })
|
||||
local stages = {}
|
||||
session.run(artist, function(label)
|
||||
stages[#stages + 1] = label
|
||||
end)
|
||||
check("session stages", #stages, 3)
|
||||
check_true("session painted a lot", artist.canvas:count() > 800, artist.canvas:count())
|
||||
check("sky colour", artist.canvas:get(1, 1), palette.index_of_slot(1))
|
||||
check("sun colour", artist.canvas:get(50, 4), palette.index_of_slot(6))
|
||||
check("ground colour", artist.canvas:get(5, 20), palette.index_of_slot(7))
|
||||
check("wall colour", artist.canvas:get(12, 15), palette.index_of_slot(12))
|
||||
check("door colour", artist.canvas:get(18, 15), palette.index_of_slot(1))
|
||||
check("window colour", artist.canvas:get(23, 12), palette.index_of_slot(8))
|
||||
check("trunk colour", artist.canvas:get(34, 17), palette.index_of_slot(12))
|
||||
check("leaf colour", artist.canvas:get(34, 10), palette.index_of_slot(7))
|
||||
check_true("session history", artist.canvas:history_size() > 8, artist.canvas:history_size())
|
||||
check_true("session message", string.find(artist.message, "Paysage", 1, true) ~= nil, artist.message)
|
||||
|
||||
local session_screen = screen_module.new(artist:screen_width(), artist:screen_height())
|
||||
artist:render(session_screen)
|
||||
local session_snapshot = session_screen:snapshot()
|
||||
check("session screen height", #session_snapshot, (artist:screen_height()) * (artist:screen_width() + 1) - 1)
|
||||
|
||||
local preview_app = app_module.new({ width = 30, height = 12 })
|
||||
preview_app:handle("2")
|
||||
preview_app:handle(" ")
|
||||
preview_app.cursor_x = preview_app.cursor_x + 5
|
||||
local preview = preview_app:preview()
|
||||
check_true("preview exists", preview ~= nil, "no preview")
|
||||
check_true("preview painted", preview:count() > 0, preview:count())
|
||||
check_true("preview is not committed", preview_app.canvas:is_empty(), "canvas modified")
|
||||
|
||||
return { passed = passed, failed = #failures, failures = failures }
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,382 @@
|
||||
-- Built-in spreadsheet functions.
|
||||
-- Every function receives the already evaluated arguments; ranges arrive as
|
||||
-- { __range = true, values = { ... } } and are flattened by the helpers below.
|
||||
local format = require("sheet.format")
|
||||
|
||||
local M = {}
|
||||
|
||||
local function fail(code)
|
||||
error(code, 0)
|
||||
end
|
||||
|
||||
local function flatten(args)
|
||||
local out = {}
|
||||
for i = 1, #args do
|
||||
local argument = args[i]
|
||||
if type(argument) == "table" and argument.__range then
|
||||
for j = 1, #argument.values do
|
||||
out[#out + 1] = argument.values[j]
|
||||
end
|
||||
else
|
||||
out[#out + 1] = argument
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- Numbers only: text inside a range is ignored, like a spreadsheet does.
|
||||
local function numeric_values(args)
|
||||
local values = flatten(args)
|
||||
local out = {}
|
||||
for i = 1, #values do
|
||||
local value = values[i]
|
||||
if type(value) == "number" then
|
||||
out[#out + 1] = value
|
||||
elseif type(value) == "string" then
|
||||
local number = tonumber(value)
|
||||
if number then
|
||||
out[#out + 1] = number
|
||||
end
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function number_arg(value)
|
||||
if type(value) == "number" then
|
||||
return value
|
||||
end
|
||||
if type(value) == "string" then
|
||||
local number = tonumber(value)
|
||||
if number then
|
||||
return number
|
||||
end
|
||||
end
|
||||
if type(value) == "boolean" then
|
||||
if value then
|
||||
return 1
|
||||
end
|
||||
return 0
|
||||
end
|
||||
fail("#VALUE!")
|
||||
end
|
||||
|
||||
local function text_arg(value)
|
||||
local kind = type(value)
|
||||
if kind == "string" then
|
||||
return value
|
||||
end
|
||||
if kind == "number" then
|
||||
return format.number(value)
|
||||
end
|
||||
if kind == "boolean" then
|
||||
if value then
|
||||
return "TRUE"
|
||||
end
|
||||
return "FALSE"
|
||||
end
|
||||
fail("#VALUE!")
|
||||
end
|
||||
|
||||
local function boolean_arg(value)
|
||||
local kind = type(value)
|
||||
if kind == "boolean" then
|
||||
return value
|
||||
end
|
||||
if kind == "number" then
|
||||
return value ~= 0
|
||||
end
|
||||
if kind == "string" then
|
||||
local lower = string.lower(value)
|
||||
if lower == "true" or lower == "oui" or lower == "vrai" then
|
||||
return true
|
||||
end
|
||||
if lower == "false" or lower == "non" or lower == "faux" or lower == "" then
|
||||
return false
|
||||
end
|
||||
end
|
||||
fail("#VALUE!")
|
||||
end
|
||||
|
||||
local function sum(args)
|
||||
local values = numeric_values(args)
|
||||
local total = 0
|
||||
for i = 1, #values do
|
||||
total = total + values[i]
|
||||
end
|
||||
return total
|
||||
end
|
||||
|
||||
local function product(args)
|
||||
local values = numeric_values(args)
|
||||
local total = 1
|
||||
for i = 1, #values do
|
||||
total = total * values[i]
|
||||
end
|
||||
return total
|
||||
end
|
||||
|
||||
local function average(args)
|
||||
local values = numeric_values(args)
|
||||
if #values == 0 then
|
||||
fail("#DIV/0!")
|
||||
end
|
||||
local total = 0
|
||||
for i = 1, #values do
|
||||
total = total + values[i]
|
||||
end
|
||||
return total / #values
|
||||
end
|
||||
|
||||
local function minimum(args)
|
||||
local values = numeric_values(args)
|
||||
if #values == 0 then
|
||||
return 0
|
||||
end
|
||||
local best = values[1]
|
||||
for i = 2, #values do
|
||||
if values[i] < best then
|
||||
best = values[i]
|
||||
end
|
||||
end
|
||||
return best
|
||||
end
|
||||
|
||||
local function maximum(args)
|
||||
local values = numeric_values(args)
|
||||
if #values == 0 then
|
||||
return 0
|
||||
end
|
||||
local best = values[1]
|
||||
for i = 2, #values do
|
||||
if values[i] > best then
|
||||
best = values[i]
|
||||
end
|
||||
end
|
||||
return best
|
||||
end
|
||||
|
||||
local function count(args)
|
||||
return #numeric_values(args)
|
||||
end
|
||||
|
||||
local function count_non_empty(args)
|
||||
local values = flatten(args)
|
||||
local total = 0
|
||||
for i = 1, #values do
|
||||
if values[i] ~= nil then
|
||||
total = total + 1
|
||||
end
|
||||
end
|
||||
return total
|
||||
end
|
||||
|
||||
local function median(args)
|
||||
local values = numeric_values(args)
|
||||
if #values == 0 then
|
||||
fail("#DIV/0!")
|
||||
end
|
||||
table.sort(values)
|
||||
local middle = (#values + 1) // 2
|
||||
if #values % 2 == 1 then
|
||||
return values[middle]
|
||||
end
|
||||
return (values[middle] + values[middle + 1]) / 2
|
||||
end
|
||||
|
||||
local function choose(args)
|
||||
if boolean_arg(args[1]) then
|
||||
if args[2] == nil then
|
||||
return true
|
||||
end
|
||||
return args[2]
|
||||
end
|
||||
if args[3] == nil then
|
||||
return false
|
||||
end
|
||||
return args[3]
|
||||
end
|
||||
|
||||
local function all_of(args)
|
||||
local values = flatten(args)
|
||||
for i = 1, #values do
|
||||
if not boolean_arg(values[i]) then
|
||||
return false
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
local function any_of(args)
|
||||
local values = flatten(args)
|
||||
for i = 1, #values do
|
||||
if boolean_arg(values[i]) then
|
||||
return true
|
||||
end
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
local function not_of(args)
|
||||
return not boolean_arg(args[1])
|
||||
end
|
||||
|
||||
local function round(args)
|
||||
local value = number_arg(args[1])
|
||||
local digits = 0
|
||||
if args[2] ~= nil then
|
||||
digits = number_arg(args[2])
|
||||
end
|
||||
local multiplier = 10 ^ digits
|
||||
local scaled = value * multiplier
|
||||
local rounded
|
||||
if scaled >= 0 then
|
||||
rounded = math.floor(scaled + 0.5)
|
||||
else
|
||||
rounded = math.ceil(scaled - 0.5)
|
||||
end
|
||||
if digits == 0 then
|
||||
return rounded
|
||||
end
|
||||
return rounded / multiplier
|
||||
end
|
||||
|
||||
local function absolute(args)
|
||||
return math.abs(number_arg(args[1]))
|
||||
end
|
||||
|
||||
local function square_root(args)
|
||||
local value = number_arg(args[1])
|
||||
if value < 0 then
|
||||
fail("#VALUE!")
|
||||
end
|
||||
return math.sqrt(value)
|
||||
end
|
||||
|
||||
local function integer_part(args)
|
||||
return math.floor(number_arg(args[1]))
|
||||
end
|
||||
|
||||
local function modulo(args)
|
||||
local left = number_arg(args[1])
|
||||
local right = number_arg(args[2])
|
||||
if right == 0 then
|
||||
fail("#DIV/0!")
|
||||
end
|
||||
return left % right
|
||||
end
|
||||
|
||||
local function power(args)
|
||||
return number_arg(args[1]) ^ number_arg(args[2])
|
||||
end
|
||||
|
||||
local function concat(args)
|
||||
local values = flatten(args)
|
||||
local parts = {}
|
||||
for i = 1, #values do
|
||||
parts[#parts + 1] = format.value(values[i])
|
||||
end
|
||||
return table.concat(parts)
|
||||
end
|
||||
|
||||
local function length(args)
|
||||
return #text_arg(args[1])
|
||||
end
|
||||
|
||||
local function upper(args)
|
||||
return string.upper(text_arg(args[1]))
|
||||
end
|
||||
|
||||
local function lower(args)
|
||||
return string.lower(text_arg(args[1]))
|
||||
end
|
||||
|
||||
local function left(args)
|
||||
local text = text_arg(args[1])
|
||||
local amount = number_arg(args[2])
|
||||
if amount < 0 then
|
||||
fail("#VALUE!")
|
||||
end
|
||||
return string.sub(text, 1, amount)
|
||||
end
|
||||
|
||||
local function right(args)
|
||||
local text = text_arg(args[1])
|
||||
local amount = number_arg(args[2])
|
||||
if amount < 0 then
|
||||
fail("#VALUE!")
|
||||
end
|
||||
if amount >= #text then
|
||||
return text
|
||||
end
|
||||
return string.sub(text, #text - amount + 1)
|
||||
end
|
||||
|
||||
local function trim(args)
|
||||
local text = text_arg(args[1])
|
||||
return string.match(text, "^%s*(.-)%s*$")
|
||||
end
|
||||
|
||||
-- name, minimum arguments, maximum arguments (-1 = unlimited), implementation
|
||||
local definitions = {
|
||||
{ "SUM", 1, -1, sum },
|
||||
{ "PRODUCT", 1, -1, product },
|
||||
{ "AVG", 1, -1, average },
|
||||
{ "MIN", 1, -1, minimum },
|
||||
{ "MAX", 1, -1, maximum },
|
||||
{ "COUNT", 1, -1, count },
|
||||
{ "COUNTA", 1, -1, count_non_empty },
|
||||
{ "MEDIAN", 1, -1, median },
|
||||
{ "IF", 2, 3, choose },
|
||||
{ "AND", 1, -1, all_of },
|
||||
{ "OR", 1, -1, any_of },
|
||||
{ "NOT", 1, 1, not_of },
|
||||
{ "ROUND", 1, 2, round },
|
||||
{ "ABS", 1, 1, absolute },
|
||||
{ "SQRT", 1, 1, square_root },
|
||||
{ "INT", 1, 1, integer_part },
|
||||
{ "MOD", 2, 2, modulo },
|
||||
{ "POWER", 2, 2, power },
|
||||
{ "CONCAT", 1, -1, concat },
|
||||
{ "LEN", 1, 1, length },
|
||||
{ "UPPER", 1, 1, upper },
|
||||
{ "LOWER", 1, 1, lower },
|
||||
{ "LEFT", 2, 2, left },
|
||||
{ "RIGHT", 2, 2, right },
|
||||
{ "TRIM", 1, 1, trim },
|
||||
}
|
||||
|
||||
local by_name = {}
|
||||
local names = {}
|
||||
for i = 1, #definitions do
|
||||
local definition = definitions[i]
|
||||
by_name[definition[1]] = { min = definition[2], max = definition[3], fn = definition[4] }
|
||||
names[#names + 1] = definition[1]
|
||||
end
|
||||
|
||||
function M.call(name, args)
|
||||
local builtin = by_name[name]
|
||||
if builtin == nil then
|
||||
fail("#NAME?")
|
||||
end
|
||||
local received = #args
|
||||
if received < builtin.min or (builtin.max >= 0 and received > builtin.max) then
|
||||
fail("#VALUE!")
|
||||
end
|
||||
return builtin.fn(args)
|
||||
end
|
||||
|
||||
function M.exists(name)
|
||||
return by_name[string.upper(name)] ~= nil
|
||||
end
|
||||
|
||||
function M.names()
|
||||
local copy = {}
|
||||
for i = 1, #names do
|
||||
copy[i] = names[i]
|
||||
end
|
||||
table.sort(copy)
|
||||
return copy
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,94 @@
|
||||
-- Shared formatting helpers: cell labels, number rendering, padding.
|
||||
-- Used by the parser, the engine, the renderer and the command line app.
|
||||
local M = {}
|
||||
|
||||
-- 1 -> "A", 26 -> "Z", 27 -> "AA", 703 -> "AAA"
|
||||
function M.column_label(index)
|
||||
local label = ""
|
||||
local n = index
|
||||
while n > 0 do
|
||||
local remainder = (n - 1) % 26
|
||||
label = string.char(65 + remainder) .. label
|
||||
n = (n - 1 - remainder) // 26
|
||||
end
|
||||
return label
|
||||
end
|
||||
|
||||
function M.column_index(letters)
|
||||
local text = string.upper(letters)
|
||||
if text == "" then
|
||||
error("empty column name", 0)
|
||||
end
|
||||
local index = 0
|
||||
for i = 1, #text do
|
||||
local b = string.byte(text, i)
|
||||
if b < 65 or b > 90 then
|
||||
error("bad column name: " .. letters, 0)
|
||||
end
|
||||
index = index * 26 + (b - 64)
|
||||
end
|
||||
return index
|
||||
end
|
||||
|
||||
-- Spreadsheet-ish number rendering: integers stay integers, floats lose
|
||||
-- floating point noise (0.30000000000000004 -> "0.3").
|
||||
function M.number(value)
|
||||
if math.type(value) == "integer" then
|
||||
return tostring(value)
|
||||
end
|
||||
local text = string.format("%.10g", value)
|
||||
if text == "-0" then
|
||||
text = "0"
|
||||
end
|
||||
return text
|
||||
end
|
||||
|
||||
function M.value(value)
|
||||
local kind = type(value)
|
||||
if kind == "nil" then
|
||||
return ""
|
||||
elseif kind == "number" then
|
||||
return M.number(value)
|
||||
elseif kind == "boolean" then
|
||||
if value then
|
||||
return "TRUE"
|
||||
end
|
||||
return "FALSE"
|
||||
elseif kind == "string" then
|
||||
return value
|
||||
elseif kind == "table" and value.__range then
|
||||
local parts = {}
|
||||
for i = 1, #value.values do
|
||||
parts[#parts + 1] = M.value(value.values[i])
|
||||
end
|
||||
return table.concat(parts, " ")
|
||||
end
|
||||
return tostring(value)
|
||||
end
|
||||
|
||||
function M.pad(text, width, right)
|
||||
local length = #text
|
||||
if length >= width then
|
||||
return text
|
||||
end
|
||||
local fill = string.rep(" ", width - length)
|
||||
if right then
|
||||
return fill .. text
|
||||
end
|
||||
return text .. fill
|
||||
end
|
||||
|
||||
-- Keeps a cell readable in a fixed width column instead of blowing it up.
|
||||
function M.fit(text, width)
|
||||
if #text <= width then
|
||||
return text
|
||||
end
|
||||
return string.sub(text, 1, width - 1) .. "~"
|
||||
end
|
||||
|
||||
function M.percent(ratio, digits)
|
||||
local pattern = "%." .. tostring(digits or 1) .. "f%%"
|
||||
return string.format(pattern, ratio * 100)
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,164 @@
|
||||
-- Tokenizer for spreadsheet formulas.
|
||||
--
|
||||
-- =SUM(A1:B4) * 2 >= IF(C1 <> "", "ok", "non")
|
||||
--
|
||||
-- Tokens are { kind = "num"|"str"|"ref"|"ident"|"op"|"punct"|"eof",
|
||||
-- value = ..., pos = <1-based column> }.
|
||||
local M = {}
|
||||
|
||||
local byte = string.byte
|
||||
local sub = string.sub
|
||||
local format = string.format
|
||||
|
||||
local function byte_at(text, index)
|
||||
return byte(text, index) or 0
|
||||
end
|
||||
|
||||
local function is_alpha(b)
|
||||
return (b >= 65 and b <= 90) or (b >= 97 and b <= 122) or b == 95
|
||||
end
|
||||
|
||||
local function is_digit(b)
|
||||
return b >= 48 and b <= 57
|
||||
end
|
||||
|
||||
local function is_alnum(b)
|
||||
return is_alpha(b) or is_digit(b)
|
||||
end
|
||||
|
||||
local TWO_CHAR = { ["<="] = true, [">="] = true, ["<>"] = true, ["!="] = true }
|
||||
local ONE_CHAR = {
|
||||
["+"] = true, ["-"] = true, ["*"] = true, ["/"] = true, ["%"] = true,
|
||||
["^"] = true, ["&"] = true, ["="] = true, ["<"] = true, [">"] = true,
|
||||
}
|
||||
|
||||
local function token(kind, value, pos)
|
||||
return { kind = kind, value = value, pos = pos }
|
||||
end
|
||||
|
||||
function M.tokenize(text)
|
||||
local tokens = {}
|
||||
local i = 1
|
||||
local n = #text
|
||||
|
||||
while i <= n do
|
||||
local c = sub(text, i, i)
|
||||
local b = byte_at(text, i)
|
||||
|
||||
if b == 32 or b == 9 or b == 10 or b == 13 then
|
||||
i = i + 1
|
||||
elseif is_digit(b) or (c == "." and is_digit(byte_at(text, i + 1))) then
|
||||
local start = i
|
||||
while is_digit(byte_at(text, i)) do
|
||||
i = i + 1
|
||||
end
|
||||
if byte_at(text, i) == 46 then
|
||||
i = i + 1
|
||||
while is_digit(byte_at(text, i)) do
|
||||
i = i + 1
|
||||
end
|
||||
end
|
||||
local exponent = byte_at(text, i)
|
||||
if exponent == 101 or exponent == 69 then
|
||||
local save = i
|
||||
i = i + 1
|
||||
local sign = byte_at(text, i)
|
||||
if sign == 43 or sign == 45 then
|
||||
i = i + 1
|
||||
end
|
||||
if is_digit(byte_at(text, i)) then
|
||||
while is_digit(byte_at(text, i)) do
|
||||
i = i + 1
|
||||
end
|
||||
else
|
||||
i = save
|
||||
end
|
||||
end
|
||||
local literal = sub(text, start, i - 1)
|
||||
tokens[#tokens + 1] = token("num", tonumber(literal), start)
|
||||
elseif c == '"' or c == "'" then
|
||||
local quote = c
|
||||
local start = i
|
||||
i = i + 1
|
||||
local parts = {}
|
||||
local closed = false
|
||||
while i <= n do
|
||||
local ch = sub(text, i, i)
|
||||
if ch == "\\" then
|
||||
local escaped = sub(text, i + 1, i + 1)
|
||||
if escaped == "n" then
|
||||
parts[#parts + 1] = "\n"
|
||||
elseif escaped == "t" then
|
||||
parts[#parts + 1] = "\t"
|
||||
elseif escaped == "\\" then
|
||||
parts[#parts + 1] = "\\"
|
||||
elseif escaped == '"' then
|
||||
parts[#parts + 1] = '"'
|
||||
elseif escaped == "'" then
|
||||
parts[#parts + 1] = "'"
|
||||
elseif escaped == "" then
|
||||
error(format("unterminated string at %d", start), 0)
|
||||
else
|
||||
parts[#parts + 1] = escaped
|
||||
end
|
||||
i = i + 2
|
||||
elseif ch == quote then
|
||||
closed = true
|
||||
i = i + 1
|
||||
break
|
||||
else
|
||||
parts[#parts + 1] = ch
|
||||
i = i + 1
|
||||
end
|
||||
end
|
||||
if not closed then
|
||||
error(format("unterminated string at %d", start), 0)
|
||||
end
|
||||
tokens[#tokens + 1] = token("str", table.concat(parts), start)
|
||||
elseif is_alpha(b) or c == "$" then
|
||||
local start = i
|
||||
i = i + 1
|
||||
while i <= n do
|
||||
local next_byte = byte_at(text, i)
|
||||
if is_alnum(next_byte) or next_byte == 36 then
|
||||
i = i + 1
|
||||
else
|
||||
break
|
||||
end
|
||||
end
|
||||
local word = sub(text, start, i - 1)
|
||||
local letters, digits = string.match(word, "^%$?([A-Za-z]+)%$?(%d+)$")
|
||||
if letters then
|
||||
tokens[#tokens + 1] = token("ref", {
|
||||
text = word,
|
||||
letters = letters,
|
||||
row = tonumber(digits),
|
||||
}, start)
|
||||
else
|
||||
tokens[#tokens + 1] = token("ident", word, start)
|
||||
end
|
||||
elseif c == "(" or c == ")" or c == "," or c == ":" then
|
||||
tokens[#tokens + 1] = token("punct", c, i)
|
||||
i = i + 1
|
||||
else
|
||||
local pair = sub(text, i, i + 1)
|
||||
if TWO_CHAR[pair] then
|
||||
if pair == "!=" then
|
||||
pair = "<>"
|
||||
end
|
||||
tokens[#tokens + 1] = token("op", pair, i)
|
||||
i = i + 2
|
||||
elseif ONE_CHAR[c] then
|
||||
tokens[#tokens + 1] = token("op", c, i)
|
||||
i = i + 1
|
||||
else
|
||||
error(format("unexpected character %q at %d", c, i), 0)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
tokens[#tokens + 1] = token("eof", "<eof>", n + 1)
|
||||
return tokens
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,178 @@
|
||||
-- Recursive descent parser for spreadsheet formulas.
|
||||
-- Produces plain tables: { k = "num"|"str"|"bool"|"ref"|"range"|"un"|"bin"|"call", ... }
|
||||
--
|
||||
-- Precedence (low to high): comparisons, &, + -, * / %, unary -, ^
|
||||
-- Unary minus binds tighter than ^ (spreadsheet style: -2^2 = 4).
|
||||
local lexer = require("sheet.lexer")
|
||||
local format = require("sheet.format")
|
||||
|
||||
local M = {}
|
||||
|
||||
local PREC = {
|
||||
["="] = 1, ["<>"] = 1, ["<"] = 1, [">"] = 1, ["<="] = 1, [">="] = 1,
|
||||
["&"] = 2,
|
||||
["+"] = 3, ["-"] = 3,
|
||||
["*"] = 4, ["/"] = 4, ["%"] = 4,
|
||||
["^"] = 6,
|
||||
}
|
||||
|
||||
local Parser = {}
|
||||
Parser.__index = Parser
|
||||
|
||||
function Parser.new(tokens)
|
||||
return setmetatable({ tokens = tokens, pos = 1 }, Parser)
|
||||
end
|
||||
|
||||
function Parser:peek()
|
||||
return self.tokens[self.pos]
|
||||
end
|
||||
|
||||
function Parser:next()
|
||||
local current = self.tokens[self.pos]
|
||||
self.pos = self.pos + 1
|
||||
return current
|
||||
end
|
||||
|
||||
function Parser:expect_punct(value)
|
||||
local current = self:peek()
|
||||
if current.kind ~= "punct" or current.value ~= value then
|
||||
error(string.format("expected %q at %d", value, current.pos), 0)
|
||||
end
|
||||
return self:next()
|
||||
end
|
||||
|
||||
function Parser:parse_primary()
|
||||
local current = self:peek()
|
||||
|
||||
if current.kind == "num" then
|
||||
self:next()
|
||||
return { k = "num", v = current.value }
|
||||
end
|
||||
|
||||
if current.kind == "str" then
|
||||
self:next()
|
||||
return { k = "str", v = current.value }
|
||||
end
|
||||
|
||||
if current.kind == "ref" then
|
||||
self:next()
|
||||
local column = format.column_index(current.value.letters)
|
||||
local row = current.value.row
|
||||
local reference = {
|
||||
k = "ref",
|
||||
col = column,
|
||||
row = row,
|
||||
key = format.column_label(column) .. row,
|
||||
text = current.value.text,
|
||||
}
|
||||
local following = self:peek()
|
||||
if following.kind == "punct" and following.value == ":" then
|
||||
self:next()
|
||||
local last = self:peek()
|
||||
if last.kind ~= "ref" then
|
||||
error(string.format("expected a cell after ':' at %d", last.pos), 0)
|
||||
end
|
||||
self:next()
|
||||
local column2 = format.column_index(last.value.letters)
|
||||
local row2 = last.value.row
|
||||
return {
|
||||
k = "range",
|
||||
c1 = math.min(column, column2),
|
||||
c2 = math.max(column, column2),
|
||||
r1 = math.min(row, row2),
|
||||
r2 = math.max(row, row2),
|
||||
}
|
||||
end
|
||||
return reference
|
||||
end
|
||||
|
||||
if current.kind == "ident" then
|
||||
self:next()
|
||||
local following = self:peek()
|
||||
if following.kind == "punct" and following.value == "(" then
|
||||
self:next()
|
||||
local args = {}
|
||||
local closing = self:peek()
|
||||
if not (closing.kind == "punct" and closing.value == ")") then
|
||||
args[#args + 1] = self:parse_expression(1)
|
||||
while true do
|
||||
local separator = self:peek()
|
||||
if separator.kind == "punct" and separator.value == "," then
|
||||
self:next()
|
||||
args[#args + 1] = self:parse_expression(1)
|
||||
else
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
self:expect_punct(")")
|
||||
return { k = "call", name = string.upper(current.value), args = args }
|
||||
end
|
||||
local upper = string.upper(current.value)
|
||||
if upper == "TRUE" then
|
||||
return { k = "bool", v = true }
|
||||
end
|
||||
if upper == "FALSE" then
|
||||
return { k = "bool", v = false }
|
||||
end
|
||||
error(string.format("unknown name %q at %d", current.value, current.pos), 0)
|
||||
end
|
||||
|
||||
if current.kind == "punct" and current.value == "(" then
|
||||
self:next()
|
||||
local inner = self:parse_expression(1)
|
||||
self:expect_punct(")")
|
||||
return inner
|
||||
end
|
||||
|
||||
error(string.format("unexpected token %q at %d", tostring(current.value), current.pos), 0)
|
||||
end
|
||||
|
||||
function Parser:parse_unary()
|
||||
local current = self:peek()
|
||||
if current.kind == "op" and (current.value == "-" or current.value == "+") then
|
||||
self:next()
|
||||
local operand = self:parse_unary()
|
||||
if current.value == "-" then
|
||||
return { k = "un", op = "-", a = operand }
|
||||
end
|
||||
return { k = "un", op = "+", a = operand }
|
||||
end
|
||||
return self:parse_primary()
|
||||
end
|
||||
|
||||
function Parser:parse_expression(minimum)
|
||||
local left = self:parse_unary()
|
||||
while true do
|
||||
local current = self:peek()
|
||||
if current.kind ~= "op" then
|
||||
break
|
||||
end
|
||||
local precedence = PREC[current.value]
|
||||
if precedence == nil or precedence < minimum then
|
||||
break
|
||||
end
|
||||
self:next()
|
||||
local next_minimum = precedence + 1
|
||||
if current.value == "^" then
|
||||
next_minimum = precedence
|
||||
end
|
||||
local right = self:parse_expression(next_minimum)
|
||||
left = { k = "bin", op = current.value, a = left, b = right }
|
||||
end
|
||||
return left
|
||||
end
|
||||
|
||||
-- Parses the body of a formula, i.e. without the leading '='.
|
||||
function M.parse(text)
|
||||
local tokens = lexer.tokenize(text)
|
||||
local parser = Parser.new(tokens)
|
||||
local ast = parser:parse_expression(1)
|
||||
local last = parser:peek()
|
||||
if last.kind ~= "eof" then
|
||||
error(string.format("unexpected %q at %d", tostring(last.value), last.pos), 0)
|
||||
end
|
||||
return ast
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,108 @@
|
||||
-- ASCII rendering of a sheet: grid, formula view, CSV export and bars.
|
||||
local format = require("sheet.format")
|
||||
|
||||
local M = {}
|
||||
|
||||
local MAX_WIDTH = 24
|
||||
|
||||
function M.render(sheet, options)
|
||||
options = options or {}
|
||||
local show_formulas = options.show_formulas
|
||||
local max_row, max_col = sheet:dimensions()
|
||||
if max_row == 0 or max_col == 0 then
|
||||
return "(feuille vide)"
|
||||
end
|
||||
|
||||
local widths = {}
|
||||
local cells = {}
|
||||
local numeric = {}
|
||||
for column = 1, max_col do
|
||||
widths[column] = #format.column_label(column)
|
||||
end
|
||||
|
||||
for row = 1, max_row do
|
||||
cells[row] = {}
|
||||
numeric[row] = {}
|
||||
for column = 1, max_col do
|
||||
local key = format.column_label(column) .. row
|
||||
local text
|
||||
if show_formulas then
|
||||
text = sheet:raw(key) or ""
|
||||
else
|
||||
text = sheet:display(key)
|
||||
end
|
||||
text = format.fit(text, MAX_WIDTH)
|
||||
cells[row][column] = text
|
||||
if #text > widths[column] then
|
||||
widths[column] = #text
|
||||
end
|
||||
local value = sheet:value(key)
|
||||
numeric[row][column] = type(value) == "number"
|
||||
end
|
||||
end
|
||||
|
||||
local label_width = #tostring(max_row)
|
||||
local lines = {}
|
||||
|
||||
local header = format.pad("", label_width) .. " |"
|
||||
for column = 1, max_col do
|
||||
header = header .. " " .. format.pad(format.column_label(column), widths[column]) .. " |"
|
||||
end
|
||||
lines[#lines + 1] = header
|
||||
|
||||
local separator = string.rep("-", label_width) .. "-+"
|
||||
for column = 1, max_col do
|
||||
separator = separator .. string.rep("-", widths[column] + 2) .. "+"
|
||||
end
|
||||
lines[#lines + 1] = separator
|
||||
|
||||
for row = 1, max_row do
|
||||
local line = format.pad(tostring(row), label_width, true) .. " |"
|
||||
for column = 1, max_col do
|
||||
local text = cells[row][column]
|
||||
line = line .. " " .. format.pad(text, widths[column], numeric[row][column]) .. " |"
|
||||
end
|
||||
lines[#lines + 1] = line
|
||||
end
|
||||
|
||||
return table.concat(lines, "\n")
|
||||
end
|
||||
|
||||
function M.csv(sheet)
|
||||
local max_row, max_col = sheet:dimensions()
|
||||
local lines = {}
|
||||
for row = 1, max_row do
|
||||
local fields = {}
|
||||
for column = 1, max_col do
|
||||
local text = sheet:display(format.column_label(column) .. row)
|
||||
if string.find(text, '[,"\n]') then
|
||||
local escaped = string.gsub(text, '"', '""')
|
||||
text = '"' .. escaped .. '"'
|
||||
end
|
||||
fields[#fields + 1] = text
|
||||
end
|
||||
lines[#lines + 1] = table.concat(fields, ",")
|
||||
end
|
||||
return table.concat(lines, "\n")
|
||||
end
|
||||
|
||||
-- Proportional bar, e.g. bar(820, 1923, 24) = "##########.............."
|
||||
function M.bar(value, maximum, width)
|
||||
if maximum <= 0 or width <= 0 then
|
||||
return ""
|
||||
end
|
||||
local filled = math.floor(value / maximum * width + 0.5)
|
||||
if value > 0 and filled < 1 then
|
||||
filled = 1
|
||||
end
|
||||
if filled > width then
|
||||
filled = width
|
||||
end
|
||||
return string.rep("#", filled) .. string.rep(".", width - filled)
|
||||
end
|
||||
|
||||
function M.fit(text, width)
|
||||
return format.fit(text, width)
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,418 @@
|
||||
-- The sheet engine: cells, lazy evaluation, ranges and error values.
|
||||
--
|
||||
-- A cell holds either a literal (number, boolean, text) or a formula. Formula
|
||||
-- values are computed on demand, memoised, and cycles are detected with a
|
||||
-- "visiting" set, so A1 = B1, B1 = A1 yields #CYCLE! instead of hanging.
|
||||
local parser = require("sheet.parser")
|
||||
local builtins = require("sheet.builtins")
|
||||
local format = require("sheet.format")
|
||||
|
||||
local M = {}
|
||||
|
||||
local Sheet = {}
|
||||
Sheet.__index = Sheet
|
||||
|
||||
local function trim(text)
|
||||
return string.match(text, "^%s*(.-)%s*$")
|
||||
end
|
||||
|
||||
function M.new(name)
|
||||
return setmetatable({
|
||||
name = name or "Sheet1",
|
||||
cells = {},
|
||||
values = {},
|
||||
visiting = {},
|
||||
stats = { eval = 0, errors = 0, cycles = 0 },
|
||||
}, Sheet)
|
||||
end
|
||||
|
||||
function Sheet:invalidate()
|
||||
self.values = {}
|
||||
self.visiting = {}
|
||||
self.stats = { eval = 0, errors = 0, cycles = 0 }
|
||||
end
|
||||
|
||||
function Sheet:normalize(address)
|
||||
local letters, digits = string.match(address, "^%s*%$?([A-Za-z]+)%$?(%d+)%s*$")
|
||||
if letters == nil then
|
||||
error("bad cell address: " .. tostring(address), 0)
|
||||
end
|
||||
local column = format.column_index(letters)
|
||||
local row = tonumber(digits)
|
||||
if row == nil or row < 1 then
|
||||
error("bad cell address: " .. tostring(address), 0)
|
||||
end
|
||||
return format.column_label(column) .. row, column, row
|
||||
end
|
||||
|
||||
function Sheet:set(address, text, number_format)
|
||||
local key, column, row = self:normalize(address)
|
||||
local body = trim(tostring(text or ""))
|
||||
self:invalidate()
|
||||
|
||||
if body == "" then
|
||||
self.cells[key] = nil
|
||||
return key
|
||||
end
|
||||
|
||||
local cell = { text = body, col = column, row = row, format = number_format }
|
||||
if string.sub(body, 1, 1) == "=" then
|
||||
cell.kind = "formula"
|
||||
local ok, ast = pcall(parser.parse, string.sub(body, 2))
|
||||
if ok then
|
||||
cell.ast = ast
|
||||
else
|
||||
cell.parse_error = tostring(ast)
|
||||
end
|
||||
else
|
||||
cell.kind = "literal"
|
||||
local number = tonumber(body)
|
||||
local upper = string.upper(body)
|
||||
if number ~= nil then
|
||||
cell.value = number
|
||||
elseif upper == "TRUE" then
|
||||
cell.value = true
|
||||
elseif upper == "FALSE" then
|
||||
cell.value = false
|
||||
else
|
||||
cell.value = body
|
||||
end
|
||||
end
|
||||
self.cells[key] = cell
|
||||
return key
|
||||
end
|
||||
|
||||
function Sheet:raw(address)
|
||||
local key = self:normalize(address)
|
||||
local cell = self.cells[key]
|
||||
if cell == nil then
|
||||
return nil
|
||||
end
|
||||
return cell.text
|
||||
end
|
||||
|
||||
-- Internal: evaluates a cell key, raising "#CODE" on failure.
|
||||
function Sheet:evaluate(key)
|
||||
local cached = self.values[key]
|
||||
if cached ~= nil then
|
||||
if cached.ok then
|
||||
return cached.value
|
||||
end
|
||||
error(cached.err, 0)
|
||||
end
|
||||
|
||||
local cell = self.cells[key]
|
||||
if cell == nil then
|
||||
return nil
|
||||
end
|
||||
|
||||
if cell.kind == "literal" then
|
||||
self.values[key] = { ok = true, value = cell.value }
|
||||
return cell.value
|
||||
end
|
||||
|
||||
if cell.parse_error ~= nil then
|
||||
self.stats.errors = self.stats.errors + 1
|
||||
self.values[key] = { ok = false, err = "#PARSE!", detail = cell.parse_error }
|
||||
error("#PARSE!", 0)
|
||||
end
|
||||
|
||||
if self.visiting[key] then
|
||||
self.stats.cycles = self.stats.cycles + 1
|
||||
error("#CYCLE!", 0)
|
||||
end
|
||||
|
||||
self.visiting[key] = true
|
||||
self.stats.eval = self.stats.eval + 1
|
||||
local ok, result = pcall(function()
|
||||
return self:run(cell.ast)
|
||||
end)
|
||||
self.visiting[key] = nil
|
||||
|
||||
if ok then
|
||||
self.values[key] = { ok = true, value = result }
|
||||
return result
|
||||
end
|
||||
|
||||
local message = tostring(result)
|
||||
local code = "#VALUE!"
|
||||
if string.sub(message, 1, 1) == "#" then
|
||||
code = message
|
||||
end
|
||||
self.stats.errors = self.stats.errors + 1
|
||||
self.values[key] = { ok = false, err = code, detail = message }
|
||||
error(code, 0)
|
||||
end
|
||||
|
||||
function Sheet:to_number(value)
|
||||
local kind = type(value)
|
||||
if kind == "number" then
|
||||
return value
|
||||
end
|
||||
if kind == "string" then
|
||||
local number = tonumber(value)
|
||||
if number ~= nil then
|
||||
return number
|
||||
end
|
||||
end
|
||||
if kind == "boolean" then
|
||||
if value then
|
||||
return 1
|
||||
end
|
||||
return 0
|
||||
end
|
||||
error("#VALUE!", 0)
|
||||
end
|
||||
|
||||
function Sheet:compare(operator, left, right)
|
||||
if type(left) == "table" or type(right) == "table" then
|
||||
error("#VALUE!", 0)
|
||||
end
|
||||
local a = left
|
||||
local b = right
|
||||
local both_numbers = type(a) == "number" and type(b) == "number"
|
||||
local both_booleans = type(a) == "boolean" and type(b) == "boolean"
|
||||
if not both_numbers and not both_booleans then
|
||||
a = format.value(a)
|
||||
b = format.value(b)
|
||||
end
|
||||
if operator == "=" then
|
||||
return a == b
|
||||
elseif operator == "<>" then
|
||||
return a ~= b
|
||||
elseif operator == "<" then
|
||||
return a < b
|
||||
elseif operator == ">" then
|
||||
return a > b
|
||||
elseif operator == "<=" then
|
||||
return a <= b
|
||||
end
|
||||
return a >= b
|
||||
end
|
||||
|
||||
function Sheet:binary(operator, left_node, right_node)
|
||||
if operator == "&" then
|
||||
local left = format.value(self:run(left_node))
|
||||
local right = format.value(self:run(right_node))
|
||||
return left .. right
|
||||
end
|
||||
|
||||
if operator == "=" or operator == "<>" or operator == "<" or operator == ">"
|
||||
or operator == "<=" or operator == ">=" then
|
||||
return self:compare(operator, self:run(left_node), self:run(right_node))
|
||||
end
|
||||
|
||||
local a = self:to_number(self:run(left_node))
|
||||
local b = self:to_number(self:run(right_node))
|
||||
if operator == "+" then
|
||||
return a + b
|
||||
elseif operator == "-" then
|
||||
return a - b
|
||||
elseif operator == "*" then
|
||||
return a * b
|
||||
elseif operator == "/" then
|
||||
if b == 0 then
|
||||
error("#DIV/0!", 0)
|
||||
end
|
||||
return a / b
|
||||
elseif operator == "%" then
|
||||
if b == 0 then
|
||||
error("#DIV/0!", 0)
|
||||
end
|
||||
return a % b
|
||||
elseif operator == "^" then
|
||||
return a ^ b
|
||||
end
|
||||
error("#PARSE!", 0)
|
||||
end
|
||||
|
||||
function Sheet:run(node)
|
||||
local kind = node.k
|
||||
if kind == "num" or kind == "str" or kind == "bool" then
|
||||
return node.v
|
||||
end
|
||||
|
||||
if kind == "ref" then
|
||||
local value = self:evaluate(node.key)
|
||||
if value == nil then
|
||||
return 0
|
||||
end
|
||||
return value
|
||||
end
|
||||
|
||||
if kind == "range" then
|
||||
local values = {}
|
||||
for row = node.r1, node.r2 do
|
||||
for column = node.c1, node.c2 do
|
||||
local value = self:evaluate(format.column_label(column) .. row)
|
||||
if value ~= nil then
|
||||
values[#values + 1] = value
|
||||
end
|
||||
end
|
||||
end
|
||||
return {
|
||||
__range = true,
|
||||
values = values,
|
||||
c1 = node.c1, c2 = node.c2, r1 = node.r1, r2 = node.r2,
|
||||
}
|
||||
end
|
||||
|
||||
if kind == "call" then
|
||||
local args = {}
|
||||
for i = 1, #node.args do
|
||||
args[i] = self:run(node.args[i])
|
||||
end
|
||||
return builtins.call(node.name, args)
|
||||
end
|
||||
|
||||
if kind == "un" then
|
||||
local value = self:to_number(self:run(node.a))
|
||||
if node.op == "-" then
|
||||
return -value
|
||||
end
|
||||
return value
|
||||
end
|
||||
|
||||
if kind == "bin" then
|
||||
return self:binary(node.op, node.a, node.b)
|
||||
end
|
||||
|
||||
error("#PARSE!", 0)
|
||||
end
|
||||
|
||||
-- Public accessor: returns value, error_code (nil when the cell is fine).
|
||||
function Sheet:value(address)
|
||||
local ok, key = pcall(function()
|
||||
return self:normalize(address)
|
||||
end)
|
||||
if not ok then
|
||||
return nil, "#REF!"
|
||||
end
|
||||
local evaluated, result = pcall(function()
|
||||
return self:evaluate(key)
|
||||
end)
|
||||
if evaluated then
|
||||
return result, nil
|
||||
end
|
||||
return nil, tostring(result)
|
||||
end
|
||||
|
||||
-- What a cell shows: formatted value, or its error code, or "" when blank.
|
||||
-- A cell declared with the '%' format renders its ratio as a percentage.
|
||||
function Sheet:display(address)
|
||||
local value, err = self:value(address)
|
||||
if err ~= nil then
|
||||
return err
|
||||
end
|
||||
if value == nil then
|
||||
return ""
|
||||
end
|
||||
local ok, key = pcall(function()
|
||||
return self:normalize(address)
|
||||
end)
|
||||
local cell = nil
|
||||
if ok then
|
||||
cell = self.cells[key]
|
||||
end
|
||||
if cell ~= nil and cell.format == "percent" and type(value) == "number" then
|
||||
return string.format("%.1f%%", value * 100)
|
||||
end
|
||||
return format.value(value)
|
||||
end
|
||||
|
||||
function Sheet:dimensions()
|
||||
local max_row = 0
|
||||
local max_col = 0
|
||||
for _, cell in pairs(self.cells) do
|
||||
if cell.row > max_row then
|
||||
max_row = cell.row
|
||||
end
|
||||
if cell.col > max_col then
|
||||
max_col = cell.col
|
||||
end
|
||||
end
|
||||
return max_row, max_col
|
||||
end
|
||||
|
||||
function Sheet:count()
|
||||
local total = 0
|
||||
for _ in pairs(self.cells) do
|
||||
total = total + 1
|
||||
end
|
||||
return total
|
||||
end
|
||||
|
||||
-- Named helper (no closure): the generated C++ of a closure capturing a
|
||||
-- mutated local and a generic for loop is fragile, so pcall gets plain args.
|
||||
local function evaluate_entry(sheet, key)
|
||||
return sheet:evaluate(key)
|
||||
end
|
||||
|
||||
function Sheet:evaluate_all()
|
||||
local keys = {}
|
||||
for key in pairs(self.cells) do
|
||||
table.insert(keys, key)
|
||||
end
|
||||
table.sort(keys)
|
||||
for i = 1, #keys do
|
||||
local key = keys[i]
|
||||
local ok = pcall(evaluate_entry, self, key)
|
||||
if not ok then
|
||||
-- errors are recorded in self.values; keep walking the sheet
|
||||
local recorded = self.values[key]
|
||||
if recorded == nil then
|
||||
self.values[key] = { ok = false, err = "#VALUE!" }
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function Sheet:errors()
|
||||
self:evaluate_all()
|
||||
local found = {}
|
||||
for key, cached in pairs(self.values) do
|
||||
if not cached.ok then
|
||||
local cell = self.cells[key]
|
||||
found[#found + 1] = {
|
||||
key = key,
|
||||
err = cached.err,
|
||||
detail = cached.detail,
|
||||
text = cell and cell.text or "",
|
||||
row = cell and cell.row or 0,
|
||||
col = cell and cell.col or 0,
|
||||
}
|
||||
end
|
||||
end
|
||||
table.sort(found, function(a, b)
|
||||
if a.row ~= b.row then
|
||||
return a.row < b.row
|
||||
end
|
||||
return a.col < b.col
|
||||
end)
|
||||
return found
|
||||
end
|
||||
|
||||
-- Reads a tiny worksheet format: one "A1: value" or "B4: =B3*12" per line,
|
||||
-- '#' comments, blank lines ignored.
|
||||
function M.from_text(text, name)
|
||||
local sheet = M.new(name)
|
||||
local line_number = 0
|
||||
for line in string.gmatch(text .. "\n", "([^\n]*)\n") do
|
||||
line_number = line_number + 1
|
||||
local body = trim(line)
|
||||
if body ~= "" and string.sub(body, 1, 1) ~= "#" then
|
||||
local address, marker, content = string.match(body, "^([%$%a%d]+)%s*(%%?)%s*:%s*(.*)$")
|
||||
if address == nil then
|
||||
error(string.format("%s line %d: expected 'A1: value'", name or "sheet", line_number), 0)
|
||||
end
|
||||
local number_format = nil
|
||||
if marker == "%" then
|
||||
number_format = "percent"
|
||||
end
|
||||
sheet:set(address, content, number_format)
|
||||
end
|
||||
end
|
||||
return sheet
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,214 @@
|
||||
-- Self tests for the spreadsheet engine. Returns a summary table:
|
||||
-- { passed = n, failed = n, failures = { "message", ... } }
|
||||
local lexer = require("sheet.lexer")
|
||||
local parser = require("sheet.parser")
|
||||
local builtins = require("sheet.builtins")
|
||||
local sheet_module = require("sheet.sheet")
|
||||
local render = require("sheet.render")
|
||||
local format = require("sheet.format")
|
||||
local workbooks = require("sheet.workbooks")
|
||||
|
||||
local M = {}
|
||||
|
||||
-- Evaluates a single formula on a throw-away sheet and returns what the cell
|
||||
-- displays (so numbers, booleans and error codes compare as strings).
|
||||
local function compute(text)
|
||||
local sheet = sheet_module.new("ad-hoc")
|
||||
sheet:set("A1", text)
|
||||
return sheet:display("A1")
|
||||
end
|
||||
|
||||
local function sample(rows)
|
||||
local sheet = sheet_module.new("case")
|
||||
for i = 1, #rows do
|
||||
sheet:set(rows[i][1], rows[i][2])
|
||||
end
|
||||
return sheet
|
||||
end
|
||||
|
||||
function M.run()
|
||||
local passed = 0
|
||||
local failures = {}
|
||||
|
||||
local function check(name, actual, expected)
|
||||
if actual == expected then
|
||||
passed = passed + 1
|
||||
else
|
||||
failures[#failures + 1] = string.format(
|
||||
"%s : attendu %s, obtenu %s",
|
||||
name, tostring(expected), tostring(actual)
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
local function check_true(name, condition, detail)
|
||||
if condition then
|
||||
passed = passed + 1
|
||||
else
|
||||
failures[#failures + 1] = name .. " : " .. tostring(detail or "condition fausse")
|
||||
end
|
||||
end
|
||||
|
||||
-- addresses -----------------------------------------------------------
|
||||
check("column_label(1)", format.column_label(1), "A")
|
||||
check("column_label(26)", format.column_label(26), "Z")
|
||||
check("column_label(27)", format.column_label(27), "AA")
|
||||
check("column_label(28)", format.column_label(28), "AB")
|
||||
check("column_label(702)", format.column_label(702), "ZZ")
|
||||
check("column_label(703)", format.column_label(703), "AAA")
|
||||
check("column_index(AA)", format.column_index("AA"), 27)
|
||||
check("column_index(zz)", format.column_index("zz"), 702)
|
||||
|
||||
-- lexer ---------------------------------------------------------------
|
||||
local tokens = lexer.tokenize("A1+2.5*$B$3")
|
||||
check("lexer token count", #tokens, 6)
|
||||
check("lexer first kind", tokens[1].kind, "ref")
|
||||
check("lexer first text", tokens[1].value.text, "A1")
|
||||
check("lexer number", tokens[3].value, 2.5)
|
||||
check("lexer absolute ref", tokens[5].value.letters, "B")
|
||||
local lex_ok, lex_err = pcall(lexer.tokenize, "1 @ 2")
|
||||
check("lexer rejects @", lex_ok, false)
|
||||
check_true("lexer error is explicit", string.find(tostring(lex_err), "unexpected") ~= nil, lex_err)
|
||||
|
||||
-- parser --------------------------------------------------------------
|
||||
local parse_ok = pcall(parser.parse, "SUM(")
|
||||
check("parser rejects unclosed call", parse_ok, false)
|
||||
check("precedence add/mul", compute("=1+2*3"), "7")
|
||||
check("precedence parentheses", compute("=(1+2)*3"), "9")
|
||||
check("power is right assoc", compute("=2^3^2"), "512")
|
||||
check("unary minus binds tight", compute("=-2^2"), "4")
|
||||
check("division is float", compute("=10/4"), "2.5")
|
||||
check("modulo", compute("=7%3"), "1")
|
||||
check("concat operator", compute("=1&2"), "12")
|
||||
check("comparison lower", compute("=2<3"), "TRUE")
|
||||
check("comparison not equal", compute("=3<>3"), "FALSE")
|
||||
check("string equality", compute('="a"="a"'), "TRUE")
|
||||
check("string concat", compute('="a"&"b"'), "ab")
|
||||
check("! = alias", compute("=1!=2"), "TRUE")
|
||||
|
||||
-- references and ranges ----------------------------------------------
|
||||
local sheet = sample({
|
||||
{ "A1", "1" }, { "A2", "2" }, { "A3", "3" }, { "A4", "texte" },
|
||||
})
|
||||
sheet:set("B1", "=SUM(A1:A3)")
|
||||
sheet:set("B2", "=AVG(A1:A3)")
|
||||
sheet:set("B3", "=COUNT(A1:A4)")
|
||||
sheet:set("B4", "=MAX(A1:A4)")
|
||||
sheet:set("B5", "=MIN(A1:A3)")
|
||||
sheet:set("B6", "=SUM(A1:A3,B1)")
|
||||
sheet:set("C1", "=$A$1*10")
|
||||
sheet:set("C2", "=Z9+1")
|
||||
sheet:set("C3", "=SUM(A1:A3)")
|
||||
check("SUM range", sheet:display("B1"), "6")
|
||||
check("AVG range", sheet:display("B2"), "2")
|
||||
check("COUNT ignores text", sheet:display("B3"), "3")
|
||||
check("MAX ignores text", sheet:display("B4"), "3")
|
||||
check("MIN range", sheet:display("B5"), "1")
|
||||
check("SUM with scalar cell", sheet:display("B6"), "12")
|
||||
check("absolute reference", sheet:display("C1"), "10")
|
||||
check("blank reference is zero", sheet:display("C2"), "1")
|
||||
check("range order preserved", sheet:display("C3"), "6")
|
||||
|
||||
-- functions -----------------------------------------------------------
|
||||
check("IF true", compute('=IF(1<2,"oui","non")'), "oui")
|
||||
check("IF false", compute('=IF(1>2,"oui","non")'), "non")
|
||||
check("ROUND digits", compute("=ROUND(3.14159,2)"), "3.14")
|
||||
check("ROUND half up", compute("=ROUND(2.5,0)"), "3")
|
||||
check("ROUND negative half", compute("=ROUND(-2.5,0)"), "-3")
|
||||
check("ABS", compute("=ABS(-7)"), "7")
|
||||
check("SQRT", compute("=SQRT(2)*SQRT(2)"), "2")
|
||||
check("INT", compute("=INT(-2.5)"), "-3")
|
||||
check("MOD", compute("=MOD(7,3)"), "1")
|
||||
check("POWER", compute("=POWER(2,10)"), "1024")
|
||||
check("MEDIAN even", compute("=MEDIAN(4,1,3,2)"), "2.5")
|
||||
check("CONCAT mixed", compute('=CONCAT("a",1,TRUE)'), "a1TRUE")
|
||||
check("LEN", compute('=LEN("abc")'), "3")
|
||||
check("UPPER", compute('=UPPER("lua")'), "LUA")
|
||||
check("LOWER", compute('=LOWER("LUA")'), "lua")
|
||||
check("LEFT", compute('=LEFT("abcdef",3)'), "abc")
|
||||
check("RIGHT", compute('=RIGHT("abcdef",3)'), "def")
|
||||
check("TRIM", compute('=TRIM(" x ")'), "x")
|
||||
check("nested calls", compute("=SUM(1,2,MAX(3,4))"), "7")
|
||||
check_true("builtin registry", builtins.exists("sum") and builtins.exists("Median"), "registry incomplete")
|
||||
check_true("builtin names sorted", builtins.names()[1], "ABS")
|
||||
|
||||
-- errors --------------------------------------------------------------
|
||||
check("divide by zero", compute("=1/0"), "#DIV/0!")
|
||||
check("unknown function", compute("=NOPE(1)"), "#NAME?")
|
||||
check("text in arithmetic", compute('=1+"abc"'), "#VALUE!")
|
||||
check("syntax error", compute("=SUM("), "#PARSE!")
|
||||
check("bad operator use", compute("=1+"), "#PARSE!")
|
||||
|
||||
local cyclic = sample({ { "A1", "=B1" }, { "B1", "=A1" }, { "C1", "=A1" } })
|
||||
check("cycle detected", cyclic:display("A1"), "#CYCLE!")
|
||||
check("cycle back edge", cyclic:display("B1"), "#CYCLE!")
|
||||
check("cycle propagates", cyclic:display("C1"), "#CYCLE!")
|
||||
|
||||
local broken = sample({ { "A1", "=1/0" }, { "B1", "=A1+1" } })
|
||||
check("error propagates", broken:display("B1"), "#DIV/0!")
|
||||
|
||||
-- chains and caching --------------------------------------------------
|
||||
local chain = sample({
|
||||
{ "A1", "1" }, { "A2", "=A1+1" }, { "A3", "=A2+1" }, { "A4", "=A3+1" },
|
||||
})
|
||||
check("dependency chain", chain:display("A4"), "4")
|
||||
check_true("evaluation counted", chain.stats.eval >= 3, "stats.eval")
|
||||
chain:set("A1", "10")
|
||||
check("recalc after edit", chain:display("A4"), "13")
|
||||
|
||||
-- rendering -----------------------------------------------------------
|
||||
check("fit keeps short text", format.fit("abc", 10), "abc")
|
||||
check("fit truncates", format.fit("abcdef", 4), "abc~")
|
||||
check("bar full", render.bar(10, 10, 5), "#####")
|
||||
check("bar half", render.bar(5, 10, 10), "#####.....")
|
||||
check("bar minimum", render.bar(1, 1000, 10), "#.........")
|
||||
local viewed = render.render(sheet)
|
||||
check_true("render has header", string.find(viewed, "| A") ~= nil, viewed)
|
||||
check_true("render has separator", string.find(viewed, "%+%-+") ~= nil, viewed)
|
||||
|
||||
-- csv -----------------------------------------------------------------
|
||||
local csv_sheet = sample({ { "A1", "texte, avec virgule" }, { "B1", 'un "guillemet"' } })
|
||||
local csv = render.csv(csv_sheet)
|
||||
check_true("csv quotes comma", string.find(csv, '"texte, avec virgule"', 1, true) ~= nil, csv)
|
||||
check_true("csv doubles quotes", string.find(csv, '""guillemet""', 1, true) ~= nil, csv)
|
||||
|
||||
-- worksheet format ----------------------------------------------------
|
||||
local parsed = sheet_module.from_text("A1: 5\nB1: =A1*2\n# commentaire\n\nA2: =IF(B1>5,\"grand\",\"petit\")\n", "mini")
|
||||
check("from_text literal", parsed:display("A1"), "5")
|
||||
check("from_text formula", parsed:display("B1"), "10")
|
||||
check("from_text if", parsed:display("A2"), "grand")
|
||||
check("from_text cell count", parsed:count(), 3)
|
||||
|
||||
-- workbooks -----------------------------------------------------------
|
||||
local budget = sheet_module.from_text(workbooks.budget, "Budget")
|
||||
check("budget charges", budget:display("B11"), "1923")
|
||||
check("budget annuel", budget:display("C11"), "23076")
|
||||
check("budget reste", budget:display("B13"), "677")
|
||||
check("budget objectif", budget:display("C16"), "atteint")
|
||||
check("budget moyenne", budget:display("B18"), "320.5")
|
||||
check("budget max", budget:display("B19"), "820")
|
||||
check("budget count", budget:display("B20"), "6")
|
||||
check("percent cell", budget:display("D4"), "42.6%")
|
||||
check("percent total", budget:display("D11"), "100.0%")
|
||||
check("percent savings", budget:display("B21"), "11.5%")
|
||||
|
||||
local ventes = sheet_module.from_text(workbooks.ventes, "Ventes")
|
||||
check("ventes total", ventes:display("B9"), "44000")
|
||||
check("ventes statut", ventes:display("E4"), "ok")
|
||||
check("ventes etiquette", ventes:display("E9"), "total 44000 / 43000")
|
||||
check("ventes best", ventes:display("B11"), "14300")
|
||||
|
||||
local errors_sheet = sheet_module.from_text(workbooks.errors, "Erreurs")
|
||||
check("errors cycle", errors_sheet:display("A1"), "#CYCLE!")
|
||||
check("errors div", errors_sheet:display("B1"), "#DIV/0!")
|
||||
check("errors name", errors_sheet:display("C1"), "#NAME?")
|
||||
check("errors value", errors_sheet:display("D1"), "#VALUE!")
|
||||
check("errors parse", errors_sheet:display("E1"), "#PARSE!")
|
||||
check("errors propagation", errors_sheet:display("F1"), "#CYCLE!")
|
||||
check("errors blank ref", errors_sheet:display("G1"), "1")
|
||||
check_true("errors listing", #errors_sheet:errors() >= 6, #errors_sheet:errors())
|
||||
|
||||
return { passed = passed, failed = #failures, failures = failures }
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,132 @@
|
||||
-- Sample workbooks, kept as text in the worksheet format read by
|
||||
-- sheet.from_text(): "A1: value" or "B4: =B3*12", '#' for comments.
|
||||
local M = {}
|
||||
|
||||
M.budget = [[
|
||||
# Budget 2026 : un classeur complet, calcule a la volee.
|
||||
A1: Budget 2026 - foyer
|
||||
A3: Poste
|
||||
B3: Mensuel
|
||||
C3: Annuel
|
||||
D3: Part
|
||||
|
||||
A4: Loyer
|
||||
B4: 820
|
||||
C4: =B4*12
|
||||
D4 %: =C4/$C$11
|
||||
|
||||
A5: Courses
|
||||
B5: 430
|
||||
C5: =B5*12
|
||||
D5 %: =C5/$C$11
|
||||
|
||||
A6: Transport
|
||||
B6: 95
|
||||
C6: =B6*12
|
||||
D6 %: =C6/$C$11
|
||||
|
||||
A7: Energie
|
||||
B7: 118
|
||||
C7: =B7*12
|
||||
D7 %: =C7/$C$11
|
||||
|
||||
A8: Loisirs
|
||||
B8: 160
|
||||
C8: =B8*12
|
||||
D8 %: =C8/$C$11
|
||||
|
||||
A9: Epargne
|
||||
B9: 300
|
||||
C9: =B9*12
|
||||
D9 %: =C9/$C$11
|
||||
|
||||
A11: Total charges
|
||||
B11: =SUM(B4:B9)
|
||||
C11: =SUM(C4:C9)
|
||||
D11 %: =SUM(D4:D9)
|
||||
|
||||
A12: Revenus net
|
||||
B12: 2600
|
||||
C12: =B12*12
|
||||
D12 %: =B12/$B$12
|
||||
|
||||
A13: Reste a vivre
|
||||
B13: =B12-B11
|
||||
C13: =C12-C11
|
||||
D13 %: =B13/B12
|
||||
|
||||
A15: Epargne sur 12 mois
|
||||
B15: =C9
|
||||
A16: Objectif epargne
|
||||
B16: 3600
|
||||
C16: =IF(B15>=B16,"atteint","a revoir")
|
||||
|
||||
A18: Moyenne par poste
|
||||
B18: =ROUND(AVG(B4:B9),2)
|
||||
A19: Poste le plus lourd
|
||||
B19: =MAX(B4:B9)
|
||||
A20: Nombre de postes
|
||||
B20: =COUNT(B4:B9)
|
||||
A21: Part epargne
|
||||
B21 %: =B9/B12
|
||||
]]
|
||||
|
||||
M.ventes = [[
|
||||
# Ventes : texte, concatenation et comparaisons.
|
||||
A1: Ventes par region
|
||||
A3: Region
|
||||
B3: Ventes
|
||||
C3: Objectif
|
||||
D3: Taux
|
||||
E3: Statut
|
||||
|
||||
A4: Nord
|
||||
B4: 12500
|
||||
C4: 11000
|
||||
D4 %: =B4/C4
|
||||
E4: =IF(D4>=1,"ok","alerte")
|
||||
|
||||
A5: Sud
|
||||
B5: 9800
|
||||
C5: 11000
|
||||
D5 %: =B5/C5
|
||||
E5: =IF(D5>=1,"ok","alerte")
|
||||
|
||||
A6: Est
|
||||
B6: 14300
|
||||
C6: 12000
|
||||
D6 %: =B6/C6
|
||||
E6: =IF(D6>=1,"ok","alerte")
|
||||
|
||||
A7: Ouest
|
||||
B7: 7400
|
||||
C7: 9000
|
||||
D7 %: =B7/C7
|
||||
E7: =IF(D7>=1,"ok","alerte")
|
||||
|
||||
A9: Total
|
||||
B9: =SUM(B4:B7)
|
||||
C9: =SUM(C4:C7)
|
||||
D9 %: =B9/C9
|
||||
E9: =CONCAT("total ", B9, " / ", C9)
|
||||
|
||||
A11: Meilleure region
|
||||
B11: =MAX(B4:B7)
|
||||
A12: Taux median
|
||||
B12 %: =ROUND(MEDIAN(D4:D7),3)
|
||||
A13: Etiquette
|
||||
B13: ="Taux global " & ROUND(D9,2)
|
||||
]]
|
||||
|
||||
M.errors = [[
|
||||
# Une feuille qui casse volontairement, pour montrer les codes d'erreur.
|
||||
A1: =A1+1
|
||||
B1: =1/0
|
||||
C1: =NOPE(1)
|
||||
D1: =1+"abc"
|
||||
E1: =SUM(
|
||||
F1: =A1+B1
|
||||
G1: =Z9+1
|
||||
]]
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,165 @@
|
||||
-- Tiny framebuffer with 256-colour ANSI rendering.
|
||||
-- A screen is a grid of cells { character, foreground, background } and can be
|
||||
-- drawn on like a canvas, then serialised to one string of terminal escapes.
|
||||
local M = {}
|
||||
|
||||
local Screen = {}
|
||||
Screen.__index = Screen
|
||||
|
||||
local ESC = string.char(27)
|
||||
|
||||
function M.new(width, height)
|
||||
local screen = setmetatable({
|
||||
width = width,
|
||||
height = height,
|
||||
chars = {},
|
||||
fg = {},
|
||||
bg = {},
|
||||
}, Screen)
|
||||
screen:clear()
|
||||
return screen
|
||||
end
|
||||
|
||||
function Screen:clear(ch, fg, bg)
|
||||
local character = ch or " "
|
||||
local foreground = fg or 7
|
||||
local background = bg or 0
|
||||
local total = self.width * self.height
|
||||
for index = 1, total do
|
||||
self.chars[index] = character
|
||||
self.fg[index] = foreground
|
||||
self.bg[index] = background
|
||||
end
|
||||
end
|
||||
|
||||
function Screen:index(x, y)
|
||||
if x < 1 or y < 1 or x > self.width or y > self.height then
|
||||
return nil
|
||||
end
|
||||
return (y - 1) * self.width + x
|
||||
end
|
||||
|
||||
function Screen:put(x, y, text, fg, bg)
|
||||
if text == nil then
|
||||
return
|
||||
end
|
||||
local foreground = fg or 7
|
||||
local background = bg or 0
|
||||
for offset = 1, #text do
|
||||
local index = self:index(x + offset - 1, y)
|
||||
if index ~= nil then
|
||||
self.chars[index] = string.sub(text, offset, offset)
|
||||
self.fg[index] = foreground
|
||||
self.bg[index] = background
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function Screen:fill_rect(x, y, width, height, ch, fg, bg)
|
||||
local character = ch or " "
|
||||
for row = y, y + height - 1 do
|
||||
for column = x, x + width - 1 do
|
||||
local index = self:index(column, row)
|
||||
if index ~= nil then
|
||||
self.chars[index] = character
|
||||
self.fg[index] = fg or 7
|
||||
self.bg[index] = bg or 0
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function Screen:hline(y, x1, x2, ch, fg, bg)
|
||||
local left = math.min(x1, x2)
|
||||
local right = math.max(x1, x2)
|
||||
self:fill_rect(left, y, right - left + 1, 1, ch or "-", fg, bg)
|
||||
end
|
||||
|
||||
function Screen:vline(x, y1, y2, ch, fg, bg)
|
||||
local top = math.min(y1, y2)
|
||||
local bottom = math.max(y1, y2)
|
||||
self:fill_rect(x, top, 1, bottom - top + 1, ch or "|", fg, bg)
|
||||
end
|
||||
|
||||
-- Plain ASCII frame: corners are '+', horizontal '-', vertical '|'.
|
||||
function Screen:box(x, y, width, height, fg, bg)
|
||||
self:hline(y, x, x + width - 1, "-", fg, bg)
|
||||
self:hline(y + height - 1, x, x + width - 1, "-", fg, bg)
|
||||
self:vline(x, y, y + height - 1, "|", fg, bg)
|
||||
self:vline(x + width - 1, y, y + height - 1, "|", fg, bg)
|
||||
self:put(x, y, "+", fg, bg)
|
||||
self:put(x + width - 1, y, "+", fg, bg)
|
||||
self:put(x, y + height - 1, "+", fg, bg)
|
||||
self:put(x + width - 1, y + height - 1, "+", fg, bg)
|
||||
end
|
||||
|
||||
-- Writes a label on top of an existing border row.
|
||||
function Screen:title(x, y, width, text, fg, bg)
|
||||
local padded = " " .. text .. " "
|
||||
self:put(x, y, "+", fg, bg)
|
||||
self:put(x + 1, y, padded, fg, bg)
|
||||
local rest = width - 1 - #padded
|
||||
if rest > 0 then
|
||||
self:put(x + 1 + #padded, y, string.rep("-", rest - 1) .. "+", fg, bg)
|
||||
end
|
||||
end
|
||||
|
||||
-- Fills one row with text and the given colours (used for menus and bars).
|
||||
function Screen:bar(x, y, width, text, fg, bg)
|
||||
self:fill_rect(x, y, width, 1, " ", fg, bg)
|
||||
if text ~= nil then
|
||||
self:put(x + 1, y, text, fg, bg)
|
||||
end
|
||||
end
|
||||
|
||||
function Screen:snapshot()
|
||||
local lines = {}
|
||||
for y = 1, self.height do
|
||||
local parts = {}
|
||||
for x = 1, self.width do
|
||||
parts[#parts + 1] = self.chars[self:index(x, y)]
|
||||
end
|
||||
lines[#lines + 1] = table.concat(parts)
|
||||
end
|
||||
return table.concat(lines, "\n")
|
||||
end
|
||||
|
||||
local function colour_code(fg, bg)
|
||||
return string.format("%s[38;5;%dm%s[48;5;%dm", ESC, fg, ESC, bg)
|
||||
end
|
||||
|
||||
-- Serialises the screen. options.mono drops every escape sequence, which keeps
|
||||
-- the output diffable and usable on a dumb terminal.
|
||||
function M.frame(screen, options)
|
||||
options = options or {}
|
||||
local mono = options.mono
|
||||
local lines = {}
|
||||
for y = 1, screen.height do
|
||||
local parts = {}
|
||||
local current_fg = -1
|
||||
local current_bg = -1
|
||||
local base = (y - 1) * screen.width
|
||||
for x = 1, screen.width do
|
||||
local index = base + x
|
||||
if not mono then
|
||||
local fg = screen.fg[index]
|
||||
local bg = screen.bg[index]
|
||||
if fg ~= current_fg or bg ~= current_bg then
|
||||
parts[#parts + 1] = colour_code(fg, bg)
|
||||
current_fg = fg
|
||||
current_bg = bg
|
||||
end
|
||||
end
|
||||
parts[#parts + 1] = screen.chars[index]
|
||||
end
|
||||
if not mono then
|
||||
parts[#parts + 1] = ESC .. "[0m"
|
||||
end
|
||||
lines[#lines + 1] = table.concat(parts)
|
||||
end
|
||||
return table.concat(lines, "\n")
|
||||
end
|
||||
|
||||
M.Screen = Screen
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,31 @@
|
||||
-- Colour palette of the interface (256-colour ANSI indexes).
|
||||
local M = {}
|
||||
|
||||
M.ui = {
|
||||
bar_fg = 16,
|
||||
bar_bg = 45,
|
||||
panel_fg = 252,
|
||||
panel_bg = 236,
|
||||
panel_border = 244,
|
||||
canvas_fg = 238,
|
||||
canvas_bg = 232,
|
||||
cursor_fg = 16,
|
||||
cursor_bg = 231,
|
||||
status_fg = 231,
|
||||
status_bg = 24,
|
||||
accent_fg = 16,
|
||||
accent_bg = 220,
|
||||
muted = 250,
|
||||
warn_fg = 231,
|
||||
warn_bg = 160,
|
||||
}
|
||||
|
||||
-- Minimum size that still shows the tools panel and the canvas.
|
||||
M.minimum = {
|
||||
canvas_width = 20,
|
||||
canvas_height = 8,
|
||||
panel_width = 22,
|
||||
chrome_height = 5,
|
||||
}
|
||||
|
||||
return M
|
||||
@@ -22,6 +22,8 @@ coroutines, bibliothèques standard) reste celle de Lua.
|
||||
## Compiler et lancer
|
||||
|
||||
Prérequis : CMake ≥ 3.20, un compilateur C++17, Lua 5.4 (`liblua5.4-dev`).
|
||||
SDL2 (`libsdl2-dev`) est optionnel : quand elle est présente, les programmes
|
||||
compilés reçoivent une API `gui` (fenêtres, rectangles, événements).
|
||||
|
||||
```bash
|
||||
./build.sh # compile UNIQUEMENT le compilateur (build/luacpp)
|
||||
@@ -112,18 +114,181 @@ Les erreurs Lua sont converties en exceptions C++ côté hôte, et les erreurs C
|
||||
restent des erreurs Lua côté script. `luacpp::Module::call` protège chaque appel
|
||||
avec `pcall`.
|
||||
|
||||
## Demo
|
||||
## Démos
|
||||
|
||||
`Demo/` ne contient que du Lua, aucun C++ :
|
||||
`Demo/` ne contient que du Lua, aucun C++ : chaque script est transpilé puis lié en
|
||||
un exécutable autonome rangé dans `Demo/build/` (dossier ignoré par git).
|
||||
|
||||
- `Demo/hello.lua` : script seul (fonctions, boucles, `table.concat`) ;
|
||||
- `Demo/todo.lua` : module — tables, closures, `ipairs` ;
|
||||
- `Demo/report.lua` : module qui fait `require("todo")` et calcule des stats ;
|
||||
- `Demo/main.lua` : utilise les deux modules et affiche le rapport.
|
||||
### `hello.lua` — un script, aucun module
|
||||
|
||||
```bash
|
||||
./build/luacpp run Demo/hello.lua # un fichier, aucun require
|
||||
./build/luacpp run Demo/main.lua # plusieurs modules compilés ensemble
|
||||
./build/luacpp run Demo/hello.lua # -> Demo/build/hello
|
||||
```
|
||||
|
||||
Fonctions récursives, boucles, `table.concat`, `string.format` : le plus petit
|
||||
programme compilé possible.
|
||||
|
||||
### `main.lua` — des modules qui s'appellent
|
||||
|
||||
```bash
|
||||
./build/luacpp run Demo/main.lua # -> Demo/build/main
|
||||
```
|
||||
|
||||
`todo.lua` est un module (tables, closures, `ipairs`), `report.lua` le charge avec
|
||||
`require("todo")` et calcule des statistiques, `main.lua` utilise les deux. C'est
|
||||
la démonstration du multi-fichiers : `luacpp` compile tous les `.lua` du dossier
|
||||
d'un coup et résout `require` vers les modules compilés.
|
||||
|
||||
### `luasheet.lua` — un tableur (`Demo/sheet/*.lua`)
|
||||
|
||||
```bash
|
||||
./build/luacpp run Demo/luasheet.lua # -> Demo/build/luasheet
|
||||
```
|
||||
|
||||
Un vrai moteur de tableur, en huit modules :
|
||||
|
||||
- `sheet/lexer.lua` et `sheet/parser.lua` : nombres, chaînes, références `A1`,
|
||||
`$A$1`, plages `A1:B4`, opérateurs `+ - * / % ^ & = <> < > <= >=` et les
|
||||
parenthèses, avec précédences (`^` associatif à droite, `-2^2 = 4`) ;
|
||||
- `sheet/builtins.lua` : 26 fonctions (`SUM`, `AVG`, `MIN`, `MAX`, `COUNT`,
|
||||
`MEDIAN`, `IF`, `ROUND`, `MOD`, `CONCAT`, `LEN`, `LEFT`, `UPPER`…) ;
|
||||
- `sheet/sheet.lua` : cellules littérales ou formules, évaluation paresseuse avec
|
||||
cache, plages, détection de cycles et propagation d'erreurs ;
|
||||
- `sheet/render.lua` : grille ASCII alignée, vue formules, export CSV, barres ;
|
||||
- `sheet/workbooks.lua` : classeurs d'exemple au format `A1: =SUM(B4:B9)`, avec le
|
||||
suffixe `%` sur l'adresse pour formater une cellule en pourcentage ;
|
||||
- `sheet/tests.lua` : 105 tests internes.
|
||||
|
||||
Les erreurs sont celles d'un tableur : `#DIV/0!`, `#NAME?`, `#VALUE!`, `#PARSE!`
|
||||
et `#CYCLE!` (une cellule qui dépend d'elle-même est détectée, pas de boucle
|
||||
infinie).
|
||||
|
||||
```bash
|
||||
./build/luacpp run Demo/luasheet.lua demo # classeur Budget 2026
|
||||
./build/luacpp run Demo/luasheet.lua ventes # texte, IF, &
|
||||
./build/luacpp run Demo/luasheet.lua errors # feuille d'erreurs
|
||||
./build/luacpp run Demo/luasheet.lua formula "=SUM(1,2,3)*2"
|
||||
./build/luacpp run Demo/luasheet.lua csv # export CSV
|
||||
./build/luacpp run Demo/luasheet.lua bench 300 # 300 lignes, recalcul
|
||||
./build/luacpp run Demo/luasheet.lua test # 105 tests
|
||||
```
|
||||
|
||||
```
|
||||
| A | B | C | D |
|
||||
---+---------------------+---------+---------+--------+
|
||||
4 | Loyer | 820 | 9840 | 42.6% |
|
||||
5 | Courses | 430 | 5160 | 22.4% |
|
||||
...
|
||||
11 | Total charges | 1923 | 23076 | 100.0% |
|
||||
```
|
||||
|
||||
### `luapaint.lua` — un éditeur de dessin en terminal (`Demo/tui`, `Demo/paint`)
|
||||
|
||||
```bash
|
||||
./build/luacpp run Demo/luapaint.lua # -> Demo/build/luapaint
|
||||
```
|
||||
|
||||
Une interface graphique complète dans le terminal : framebuffer de cellules
|
||||
(character, couleur de texte, couleur de fond) rendu en ANSI 256 couleurs, panneau
|
||||
d'outils, palette, barre d'état, curseur, aperçu de forme et historique.
|
||||
|
||||
- `tui/screen.lua` : framebuffer, rectangles, cadres, titres, barres, rendu ANSI
|
||||
(et rendu `--mono` sans aucune séquence d'échappement) ;
|
||||
- `tui/theme.lua` : couleurs de l'interface et taille minimale ;
|
||||
- `paint/canvas.lua` : grille de pixels, ligne de Bresenham, rectangle, ellipse
|
||||
(contour ou pleine), remplissage par diffusion itératif, annuler/refaire ;
|
||||
- `paint/palette.lua` : douze couleurs nommées ;
|
||||
- `paint/app.lua` : état, touches, outils, disposition et rendu de l'écran ;
|
||||
- `paint/session.lua` : une session enregistrée qui dessine un paysage avec les
|
||||
vrais outils ;
|
||||
- `paint/tests.lua` : 98 tests internes.
|
||||
|
||||
```bash
|
||||
./build/luacpp run Demo/luapaint.lua demo # paysage en 3 images
|
||||
./build/luacpp run Demo/luapaint.lua play # édition interactive
|
||||
./build/luacpp run Demo/luapaint.lua snapshot # le dessin en texte
|
||||
./build/luacpp run Demo/luapaint.lua test # 98 tests
|
||||
./build/luacpp run Demo/luapaint.lua demo --mono --canvas 40x14
|
||||
```
|
||||
|
||||
Commandes de l'interface :
|
||||
|
||||
| Touche | Effet |
|
||||
| --- | --- |
|
||||
| `h` `j` `k` `l` | déplacer le curseur |
|
||||
| `espace` | dessiner (deux fois pour une ligne, un rectangle ou une ellipse) |
|
||||
| `1`…`6` | crayon, ligne, rectangle, ellipse, remplissage, gomme |
|
||||
| `f` | formes pleines ou contour |
|
||||
| `p` / `m` | couleur suivante / précédente |
|
||||
| `u` / `r` | annuler / refaire |
|
||||
| `c` | effacer la toile |
|
||||
| `w` | écrire `luapaint.txt` (couleurs en hexadécimal) |
|
||||
| `q` | quitter |
|
||||
|
||||
`play` passe le terminal en mode brut (`stty raw`) quand l'entrée est un
|
||||
terminal, et le restaure en sortie ; sur une entrée redirigée (`printf 'llllj 3 q'
|
||||
| ./luapaint play --mono`), il lit caractère par caractère sans toucher au mode.
|
||||
|
||||
### `guipaint.lua` — une vraie fenêtre (`Demo/gui/*.lua`)
|
||||
|
||||
```bash
|
||||
./build/luacpp run Demo/guipaint.lua # fenêtre 960x640
|
||||
./build/luacpp run Demo/guipaint.lua shot /tmp/x.ppm # dessine et capture la fenêtre
|
||||
./build/luacpp run Demo/guipaint.lua test # tests sans fenêtre
|
||||
./build/luacpp run Demo/guipaint.lua bench 120 # temps de rendu mesuré
|
||||
```
|
||||
|
||||
Contrairement à `luapaint.lua`, qui reste dans le terminal, celle-ci ouvre une
|
||||
**vraie fenêtre** : barre d'outils cliquable, palette, toile, curseur, aperçu de
|
||||
forme, barre d'état et raccourcis clavier. Toute la logique est en Lua ; seul le
|
||||
côté « fenêtre » vient de l'API `gui` fournie par le runtime (SDL2), décrite plus
|
||||
bas.
|
||||
|
||||
- `gui/font.lua` : police bitmap 5x7 dessinée en rectangles (aucune bibliothèque
|
||||
de polices) ;
|
||||
- `gui/paint.lua` : disposition, outils souris (crayon, ligne, rectangle, ellipse,
|
||||
remplissage, gomme), couleurs, annuler/refaire et rendu ;
|
||||
- `gui/scene.lua` : la scène dessinée par `shot` et par les tests ;
|
||||
- `gui/tests.lua` : tests sans fenêtre, via une surface factice qui enregistre les
|
||||
appels de dessin et rejoue des événements.
|
||||
|
||||
Souris : clic gauche pour dessiner, glisser pour un trait continu, clic droit pour
|
||||
gommer. Touches : `1`-`6` outils, `f` formes pleines, `p`/`m` couleur, `u` annuler,
|
||||
`c` effacer, `s` enregistrer `guipaint.ppm`, `q` quitter.
|
||||
|
||||
Rendu : la toile est mise en cache sous forme de segments horizontaux (une ligne
|
||||
de couleur uniforme coûte un rectangle, pas 160), la liste n'est reconstruite que
|
||||
lorsque la toile change (compteur de version), la police est précompilée en
|
||||
segments, et tout le dessin d'une trame part dans **un seul** appel `gui.rects`
|
||||
au lieu de milliers d'appels Lua→C. Les événements en attente sont vidés avant
|
||||
chaque redessin, donc un glissement de souris ne déclenche plus une trame par
|
||||
événement.
|
||||
|
||||
## Interface graphique (SDL2)
|
||||
|
||||
`cmake` détecte SDL2 avec `pkg-config` et, si elle est là, chaque programme
|
||||
compilé par `luacpp run` trouve une globale `gui` :
|
||||
|
||||
| Fonction | Rôle |
|
||||
| --- | --- |
|
||||
| `gui.open(titre, largeur, hauteur)` | ouvre une fenêtre ; retourne `true` ou `nil, erreur` |
|
||||
| `gui.clear(r, g, b)` | efface le fond |
|
||||
| `gui.rect(x, y, w, h, r, g, b)` | rectangle plein |
|
||||
| `gui.rects(flat, count)` | rectangles en lot (7 nombres par rectangle), un seul appel natif |
|
||||
| `gui.line(x1, y1, x2, y2, r, g, b)` | segment |
|
||||
| `gui.present()` | affiche la trame dessinée |
|
||||
| `gui.poll()` | événement suivant, ou `nil` : `quit`, `keydown` (`key`, `sym`, `repeat`), `mousedown`/`mouseup` (`x`, `y`, `button`), `mousemove` (`x`, `y`, `buttons`), `wheel` |
|
||||
| `gui.screenshot(chemin)` | écrit la trame courante en PPM (à appeler avant `present`) |
|
||||
| `gui.delay(ms)`, `gui.time()`, `gui.size()`, `gui.set_title(t)`, `gui.close()` | utilitaires |
|
||||
|
||||
Sans SDL2, tout compile encore : la globale `gui` est simplement absente et
|
||||
`Demo/guipaint.lua` affiche un message explicite. La liaison est dans
|
||||
`include/luacpp/gui.hpp`, les drapeaux de compilation sont injectés par CMake
|
||||
dans `luacpp-config.hpp` (`LUACPP_GUI_FLAGS`).
|
||||
|
||||
```bash
|
||||
# vérifier que la fenêtre s'ouvre et récupérer une capture
|
||||
DISPLAY=:0 ./Demo/build/guipaint shot /tmp/luapaint.ppm
|
||||
```
|
||||
|
||||
## Tests de conformité
|
||||
@@ -162,6 +327,16 @@ bash tests/compare.sh build/tests/luacpp_conformance
|
||||
l'émission de C++ natif typé est prévue ensuite.
|
||||
- `require` n'est intercepté que pour un nom littéral ; les noms dynamiques
|
||||
passent par le `require` standard.
|
||||
- **Closures boxées dans une boucle générique** : une closure qui capture une
|
||||
locale mutée (`t[#t + 1] = v`) dans le corps d'un `for ... in pairs(...)` peut
|
||||
produire du code C++ incorrect (plantage à l'exécution). Contournement :
|
||||
`table.insert` et `pcall(fonction_nommee, ...)` plutôt qu'une closure — c'est ce
|
||||
que fait `Demo/sheet/sheet.lua`.
|
||||
- **Captures à deux niveaux** : une fonction imbriquée qui référence une locale du
|
||||
chunk à travers sa fonction englobante échoue à la compilation
|
||||
(`internal error: upvalue 'x' is not a captured local`). Contournement : copier
|
||||
la valeur dans une locale de la fonction englobante avant de la capturer
|
||||
(`local mono = options.mono` dans `Demo/luapaint.lua`).
|
||||
|
||||
## Structure
|
||||
|
||||
|
||||
@@ -5,3 +5,4 @@
|
||||
#define LUACPP_RUNTIME_INCLUDE_DIR "@LUACPP_RUNTIME_INCLUDE_DIR@"
|
||||
#define LUACPP_LUA_CFLAGS "@LUACPP_LUA_CFLAGS@"
|
||||
#define LUACPP_LUA_LIBS "@LUACPP_LUA_LIBS@"
|
||||
#define LUACPP_GUI_FLAGS "@LUACPP_GUI_FLAGS@"
|
||||
@@ -0,0 +1,379 @@
|
||||
// Optional GUI backend for compiled Lua programs.
|
||||
//
|
||||
// When luacpp is configured with SDL2, every compiled program finds a global
|
||||
// table `gui` offering a tiny immediate-mode window API:
|
||||
//
|
||||
// local ok, err = gui.open("title", 960, 640)
|
||||
// gui.clear(r, g, b)
|
||||
// gui.rect(x, y, w, h, r, g, b)
|
||||
// gui.rects(flat, count) -- batched rects, 7 numbers per rect
|
||||
// gui.line(x1, y1, x2, y2, r, g, b)
|
||||
// gui.present()
|
||||
// local event = gui.poll() -- nil, or { type = ... }
|
||||
// gui.screenshot("out.ppm") -- reads the current back buffer
|
||||
// gui.close()
|
||||
//
|
||||
// The Lua side keeps all the application logic (layout, tools, events); this
|
||||
// layer only owns the window, the drawing primitives and the event queue.
|
||||
#pragma once
|
||||
|
||||
#if defined(LUACPP_HAS_GUI)
|
||||
|
||||
#include <SDL2/SDL.h>
|
||||
#include <lua.hpp>
|
||||
|
||||
#include <cctype>
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace luacpp {
|
||||
namespace gui {
|
||||
|
||||
struct WindowState {
|
||||
SDL_Window* window = nullptr;
|
||||
SDL_Renderer* renderer = nullptr;
|
||||
int width = 0;
|
||||
int height = 0;
|
||||
bool open = false;
|
||||
bool sdl_ready = false;
|
||||
std::vector<unsigned char> pixels;
|
||||
std::vector<SDL_Rect> batch;
|
||||
};
|
||||
|
||||
inline WindowState& state() {
|
||||
static WindowState instance;
|
||||
return instance;
|
||||
}
|
||||
|
||||
inline int fail(lua_State* L, const char* message) {
|
||||
lua_pushnil(L);
|
||||
lua_pushstring(L, message);
|
||||
return 2;
|
||||
}
|
||||
|
||||
inline int l_open(lua_State* L) {
|
||||
const char* title = luaL_checkstring(L, 1);
|
||||
const int width = static_cast<int>(luaL_checkinteger(L, 2));
|
||||
const int height = static_cast<int>(luaL_checkinteger(L, 3));
|
||||
WindowState& window = state();
|
||||
if (window.open) return fail(L, "a window is already open");
|
||||
if (!window.sdl_ready) {
|
||||
if (SDL_Init(SDL_INIT_VIDEO) != 0) return fail(L, SDL_GetError());
|
||||
window.sdl_ready = true;
|
||||
}
|
||||
window.window = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
|
||||
width, height, SDL_WINDOW_SHOWN);
|
||||
if (!window.window) return fail(L, SDL_GetError());
|
||||
window.renderer = SDL_CreateRenderer(
|
||||
window.window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
|
||||
if (!window.renderer) {
|
||||
window.renderer = SDL_CreateRenderer(window.window, -1, SDL_RENDERER_SOFTWARE);
|
||||
}
|
||||
if (!window.renderer) {
|
||||
SDL_DestroyWindow(window.window);
|
||||
window.window = nullptr;
|
||||
return fail(L, SDL_GetError());
|
||||
}
|
||||
SDL_SetRenderDrawBlendMode(window.renderer, SDL_BLENDMODE_BLEND);
|
||||
window.width = width;
|
||||
window.height = height;
|
||||
window.open = true;
|
||||
lua_pushboolean(L, 1);
|
||||
return 1;
|
||||
}
|
||||
|
||||
inline int l_close(lua_State* L) {
|
||||
WindowState& window = state();
|
||||
if (window.renderer) {
|
||||
SDL_DestroyRenderer(window.renderer);
|
||||
window.renderer = nullptr;
|
||||
}
|
||||
if (window.window) {
|
||||
SDL_DestroyWindow(window.window);
|
||||
window.window = nullptr;
|
||||
}
|
||||
window.open = false;
|
||||
window.width = 0;
|
||||
window.height = 0;
|
||||
lua_pushboolean(L, 1);
|
||||
return 1;
|
||||
}
|
||||
|
||||
inline int l_size(lua_State* L) {
|
||||
WindowState& window = state();
|
||||
if (!window.open) {
|
||||
lua_pushinteger(L, 0);
|
||||
lua_pushinteger(L, 0);
|
||||
return 2;
|
||||
}
|
||||
lua_pushinteger(L, window.width);
|
||||
lua_pushinteger(L, window.height);
|
||||
return 2;
|
||||
}
|
||||
|
||||
inline int l_clear(lua_State* L) {
|
||||
WindowState& window = state();
|
||||
if (!window.open) return fail(L, "no window");
|
||||
const int r = static_cast<int>(luaL_optinteger(L, 1, 0));
|
||||
const int g = static_cast<int>(luaL_optinteger(L, 2, 0));
|
||||
const int b = static_cast<int>(luaL_optinteger(L, 3, 0));
|
||||
SDL_SetRenderDrawColor(window.renderer, static_cast<Uint8>(r), static_cast<Uint8>(g),
|
||||
static_cast<Uint8>(b), 255);
|
||||
SDL_RenderClear(window.renderer);
|
||||
lua_pushboolean(L, 1);
|
||||
return 1;
|
||||
}
|
||||
|
||||
inline int l_rect(lua_State* L) {
|
||||
WindowState& window = state();
|
||||
if (!window.open) return fail(L, "no window");
|
||||
const int x = static_cast<int>(luaL_checkinteger(L, 1));
|
||||
const int y = static_cast<int>(luaL_checkinteger(L, 2));
|
||||
const int width = static_cast<int>(luaL_checkinteger(L, 3));
|
||||
const int height = static_cast<int>(luaL_checkinteger(L, 4));
|
||||
const int r = static_cast<int>(luaL_optinteger(L, 5, 255));
|
||||
const int g = static_cast<int>(luaL_optinteger(L, 6, 255));
|
||||
const int b = static_cast<int>(luaL_optinteger(L, 7, 255));
|
||||
if (width <= 0 || height <= 0) {
|
||||
lua_pushboolean(L, 0);
|
||||
return 1;
|
||||
}
|
||||
const SDL_Rect rectangle{x, y, width, height};
|
||||
SDL_SetRenderDrawColor(window.renderer, static_cast<Uint8>(r), static_cast<Uint8>(g),
|
||||
static_cast<Uint8>(b), 255);
|
||||
SDL_RenderFillRect(window.renderer, &rectangle);
|
||||
lua_pushboolean(L, 1);
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Batched rectangles: a flat array holding seven numbers per rectangle
|
||||
// (x, y, w, h, r, g, b) and how many numbers are used. Consecutive rectangles
|
||||
// sharing a colour are filled with one SDL_RenderFillRects call, which keeps
|
||||
// the per-frame cost of a whole-tile redraw down to a few native calls.
|
||||
inline int l_rects(lua_State* L) {
|
||||
WindowState& window = state();
|
||||
if (!window.open) return fail(L, "no window");
|
||||
luaL_checktype(L, 1, LUA_TTABLE);
|
||||
const lua_Integer count = luaL_optinteger(L, 2, static_cast<lua_Integer>(lua_rawlen(L, 1)));
|
||||
std::vector<SDL_Rect>& batch = window.batch;
|
||||
batch.clear();
|
||||
int last_r = -1;
|
||||
int last_g = -1;
|
||||
int last_b = -1;
|
||||
int drawn = 0;
|
||||
for (lua_Integer index = 1; index + 6 <= count; index += 7) {
|
||||
lua_Integer values[7];
|
||||
for (int offset = 0; offset < 7; ++offset) {
|
||||
lua_rawgeti(L, 1, static_cast<int>(index + offset));
|
||||
values[offset] = lua_tointeger(L, -1);
|
||||
lua_pop(L, 1);
|
||||
}
|
||||
const int width = static_cast<int>(values[2]);
|
||||
const int height = static_cast<int>(values[3]);
|
||||
if (width <= 0 || height <= 0) continue;
|
||||
const int r = static_cast<int>(values[4]);
|
||||
const int g = static_cast<int>(values[5]);
|
||||
const int b = static_cast<int>(values[6]);
|
||||
if (r != last_r || g != last_g || b != last_b) {
|
||||
if (!batch.empty()) {
|
||||
SDL_RenderFillRects(window.renderer, batch.data(), static_cast<int>(batch.size()));
|
||||
batch.clear();
|
||||
}
|
||||
SDL_SetRenderDrawColor(window.renderer, static_cast<Uint8>(r), static_cast<Uint8>(g),
|
||||
static_cast<Uint8>(b), 255);
|
||||
last_r = r;
|
||||
last_g = g;
|
||||
last_b = b;
|
||||
}
|
||||
batch.push_back(SDL_Rect{static_cast<int>(values[0]), static_cast<int>(values[1]), width, height});
|
||||
++drawn;
|
||||
}
|
||||
if (!batch.empty()) {
|
||||
SDL_RenderFillRects(window.renderer, batch.data(), static_cast<int>(batch.size()));
|
||||
batch.clear();
|
||||
}
|
||||
lua_pushinteger(L, drawn);
|
||||
return 1;
|
||||
}
|
||||
|
||||
inline int l_line(lua_State* L) {
|
||||
WindowState& window = state();
|
||||
if (!window.open) return fail(L, "no window");
|
||||
const int x1 = static_cast<int>(luaL_checkinteger(L, 1));
|
||||
const int y1 = static_cast<int>(luaL_checkinteger(L, 2));
|
||||
const int x2 = static_cast<int>(luaL_checkinteger(L, 3));
|
||||
const int y2 = static_cast<int>(luaL_checkinteger(L, 4));
|
||||
const int r = static_cast<int>(luaL_optinteger(L, 5, 255));
|
||||
const int g = static_cast<int>(luaL_optinteger(L, 6, 255));
|
||||
const int b = static_cast<int>(luaL_optinteger(L, 7, 255));
|
||||
SDL_SetRenderDrawColor(window.renderer, static_cast<Uint8>(r), static_cast<Uint8>(g),
|
||||
static_cast<Uint8>(b), 255);
|
||||
SDL_RenderDrawLine(window.renderer, x1, y1, x2, y2);
|
||||
lua_pushboolean(L, 1);
|
||||
return 1;
|
||||
}
|
||||
|
||||
inline int l_present(lua_State* L) {
|
||||
WindowState& window = state();
|
||||
if (!window.open) return fail(L, "no window");
|
||||
SDL_RenderPresent(window.renderer);
|
||||
lua_pushboolean(L, 1);
|
||||
return 1;
|
||||
}
|
||||
|
||||
inline int l_delay(lua_State* L) {
|
||||
const int milliseconds = static_cast<int>(luaL_optinteger(L, 1, 10));
|
||||
SDL_Delay(static_cast<Uint32>(milliseconds < 0 ? 0 : milliseconds));
|
||||
lua_pushboolean(L, 1);
|
||||
return 1;
|
||||
}
|
||||
|
||||
inline int l_time(lua_State* L) {
|
||||
lua_pushnumber(L, static_cast<lua_Number>(SDL_GetTicks64()));
|
||||
return 1;
|
||||
}
|
||||
|
||||
inline void set_field_string(lua_State* L, const char* name, const std::string& value) {
|
||||
lua_pushlstring(L, value.data(), value.size());
|
||||
lua_setfield(L, -2, name);
|
||||
}
|
||||
|
||||
inline int l_poll(lua_State* L) {
|
||||
WindowState& window = state();
|
||||
if (!window.open) {
|
||||
lua_pushnil(L);
|
||||
return 1;
|
||||
}
|
||||
SDL_Event event;
|
||||
if (SDL_PollEvent(&event) == 0) {
|
||||
lua_pushnil(L);
|
||||
return 1;
|
||||
}
|
||||
lua_newtable(L);
|
||||
const char* kind = "other";
|
||||
switch (event.type) {
|
||||
case SDL_QUIT:
|
||||
kind = "quit";
|
||||
break;
|
||||
case SDL_KEYDOWN: {
|
||||
kind = "keydown";
|
||||
const char* raw = SDL_GetKeyName(event.key.keysym.sym);
|
||||
std::string name = raw ? raw : "";
|
||||
for (char& character : name) {
|
||||
character = static_cast<char>(std::tolower(static_cast<unsigned char>(character)));
|
||||
}
|
||||
set_field_string(L, "key", name);
|
||||
lua_pushinteger(L, event.key.keysym.sym);
|
||||
lua_setfield(L, -2, "sym");
|
||||
lua_pushboolean(L, event.key.repeat);
|
||||
lua_setfield(L, -2, "repeat");
|
||||
break;
|
||||
}
|
||||
case SDL_KEYUP:
|
||||
kind = "keyup";
|
||||
break;
|
||||
case SDL_MOUSEMOTION:
|
||||
kind = "mousemove";
|
||||
lua_pushinteger(L, event.motion.x);
|
||||
lua_setfield(L, -2, "x");
|
||||
lua_pushinteger(L, event.motion.y);
|
||||
lua_setfield(L, -2, "y");
|
||||
lua_pushinteger(L, event.motion.state);
|
||||
lua_setfield(L, -2, "buttons");
|
||||
break;
|
||||
case SDL_MOUSEBUTTONDOWN:
|
||||
kind = "mousedown";
|
||||
lua_pushinteger(L, event.button.x);
|
||||
lua_setfield(L, -2, "x");
|
||||
lua_pushinteger(L, event.button.y);
|
||||
lua_setfield(L, -2, "y");
|
||||
lua_pushinteger(L, event.button.button);
|
||||
lua_setfield(L, -2, "button");
|
||||
break;
|
||||
case SDL_MOUSEBUTTONUP:
|
||||
kind = "mouseup";
|
||||
lua_pushinteger(L, event.button.x);
|
||||
lua_setfield(L, -2, "x");
|
||||
lua_pushinteger(L, event.button.y);
|
||||
lua_setfield(L, -2, "y");
|
||||
lua_pushinteger(L, event.button.button);
|
||||
lua_setfield(L, -2, "button");
|
||||
break;
|
||||
case SDL_MOUSEWHEEL:
|
||||
kind = "wheel";
|
||||
lua_pushinteger(L, event.wheel.y);
|
||||
lua_setfield(L, -2, "y");
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
lua_pushstring(L, kind);
|
||||
lua_setfield(L, -2, "type");
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Reads the current back buffer and writes a binary PPM (P6) file. The buffer
|
||||
// is only guaranteed to hold the last drawn frame, so call it before present().
|
||||
inline int l_screenshot(lua_State* L) {
|
||||
WindowState& window = state();
|
||||
if (!window.open) return fail(L, "no window");
|
||||
const char* path = luaL_checkstring(L, 1);
|
||||
const int width = window.width;
|
||||
const int height = window.height;
|
||||
window.pixels.resize(static_cast<size_t>(width) * static_cast<size_t>(height) * 4);
|
||||
if (SDL_RenderReadPixels(window.renderer, nullptr, SDL_PIXELFORMAT_RGBA32,
|
||||
window.pixels.data(), width * 4) != 0) {
|
||||
return fail(L, SDL_GetError());
|
||||
}
|
||||
std::FILE* file = std::fopen(path, "wb");
|
||||
if (!file) return fail(L, "cannot write the screenshot");
|
||||
std::fprintf(file, "P6\n%d %d\n255\n", width, height);
|
||||
for (int index = 0; index < width * height; ++index) {
|
||||
std::fwrite(&window.pixels[static_cast<size_t>(index) * 4], 1, 3, file);
|
||||
}
|
||||
std::fclose(file);
|
||||
lua_pushboolean(L, 1);
|
||||
return 1;
|
||||
}
|
||||
|
||||
inline int l_set_title(lua_State* L) {
|
||||
WindowState& window = state();
|
||||
if (!window.open) return fail(L, "no window");
|
||||
SDL_SetWindowTitle(window.window, luaL_checkstring(L, 1));
|
||||
lua_pushboolean(L, 1);
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Installs the `gui` global. Called by luacpp::State when starting a program.
|
||||
inline void register_gui(lua_State* L) {
|
||||
lua_newtable(L);
|
||||
const luaL_Reg functions[] = {
|
||||
{"open", l_open}, {"close", l_close}, {"size", l_size},
|
||||
{"clear", l_clear}, {"rect", l_rect}, {"rects", l_rects},
|
||||
{"line", l_line},
|
||||
{"present", l_present}, {"poll", l_poll}, {"delay", l_delay},
|
||||
{"time", l_time}, {"screenshot", l_screenshot},
|
||||
{"set_title", l_set_title}, {nullptr, nullptr},
|
||||
};
|
||||
for (const luaL_Reg* entry = functions; entry->name != nullptr; ++entry) {
|
||||
lua_pushcfunction(L, entry->func);
|
||||
lua_setfield(L, -2, entry->name);
|
||||
}
|
||||
lua_setglobal(L, "gui");
|
||||
}
|
||||
|
||||
} // namespace gui
|
||||
} // namespace luacpp
|
||||
|
||||
#else
|
||||
|
||||
#include <lua.hpp>
|
||||
|
||||
namespace luacpp {
|
||||
namespace gui {
|
||||
inline void register_gui(lua_State*) {}
|
||||
} // namespace gui
|
||||
} // namespace luacpp
|
||||
|
||||
#endif // LUACPP_HAS_GUI
|
||||
@@ -5,6 +5,8 @@
|
||||
|
||||
#include <lua.hpp>
|
||||
|
||||
#include "gui.hpp"
|
||||
|
||||
#if LUA_VERSION_NUM != 504
|
||||
#error "luacpp requires Lua 5.4 (LUA_VERSION_NUM == 504)"
|
||||
#endif
|
||||
@@ -638,10 +640,14 @@ public:
|
||||
if (!L_) throw Error("cannot create a Lua state");
|
||||
own_ = true;
|
||||
luaL_openlibs(L_);
|
||||
gui::register_gui(L_);
|
||||
}
|
||||
|
||||
explicit State(lua_State* L, bool own = false) : L_(L), own_(own) {
|
||||
if (own_ && L_) luaL_openlibs(L_);
|
||||
if (own_ && L_) {
|
||||
luaL_openlibs(L_);
|
||||
gui::register_gui(L_);
|
||||
}
|
||||
}
|
||||
|
||||
~State() {
|
||||
|
||||
+22
-1
@@ -278,6 +278,25 @@ std::vector<fs::path> collect_lua_files(const fs::path& root) {
|
||||
return files;
|
||||
}
|
||||
|
||||
// A release tarball ships the runtime headers next to the binary
|
||||
// (<prefix>/bin/luacpp + <prefix>/include/luacpp), while a local build keeps
|
||||
// using the include directory configured by CMake. LUACPP_INCLUDE wins over both.
|
||||
std::string runtime_include_dir() {
|
||||
if (const char* env = std::getenv("LUACPP_INCLUDE")) {
|
||||
if (*env != '\0') return env;
|
||||
}
|
||||
#if defined(__linux__)
|
||||
std::error_code ec;
|
||||
fs::path exe = fs::read_symlink("/proc/self/exe", ec);
|
||||
if (!ec) {
|
||||
fs::path beside = exe.parent_path().parent_path() / "include";
|
||||
std::error_code missing;
|
||||
if (fs::exists(beside / "luacpp" / "rt.hpp", missing)) return beside.string();
|
||||
}
|
||||
#endif
|
||||
return LUACPP_RUNTIME_INCLUDE_DIR;
|
||||
}
|
||||
|
||||
int run_script(const Options& opt) {
|
||||
fs::path entry = opt.inputs.front();
|
||||
if (!fs::exists(entry)) {
|
||||
@@ -323,8 +342,10 @@ int run_script(const Options& opt) {
|
||||
for (const auto& job : jobs) command += " " + quoted(job.cpp.string());
|
||||
command += " " + quoted(driver.string());
|
||||
command += " -I" + quoted(srcDir.string());
|
||||
command += " -I" + quoted(LUACPP_RUNTIME_INCLUDE_DIR);
|
||||
command += " -I" + quoted(runtime_include_dir());
|
||||
command += " " + lua_link_flags();
|
||||
std::string gui_flags = LUACPP_GUI_FLAGS;
|
||||
if (!gui_flags.empty()) command += " " + gui_flags;
|
||||
|
||||
if (opt.verbose) std::cerr << "luacpp: compile: " << command << "\n";
|
||||
if (!opt.quiet) std::cout << "luacpp: building " << display(exe) << "\n";
|
||||
|
||||
Reference in new issue
Block a user