diff --git a/Demo/luapaint.lua b/Demo/luapaint.lua new file mode 100644 index 0000000..4173b2d --- /dev/null +++ b/Demo/luapaint.lua @@ -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) diff --git a/Demo/paint/app.lua b/Demo/paint/app.lua new file mode 100644 index 0000000..778af28 --- /dev/null +++ b/Demo/paint/app.lua @@ -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 diff --git a/Demo/paint/canvas.lua b/Demo/paint/canvas.lua new file mode 100644 index 0000000..0a20efa --- /dev/null +++ b/Demo/paint/canvas.lua @@ -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 diff --git a/Demo/paint/palette.lua b/Demo/paint/palette.lua new file mode 100644 index 0000000..b5609bf --- /dev/null +++ b/Demo/paint/palette.lua @@ -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 diff --git a/Demo/paint/session.lua b/Demo/paint/session.lua new file mode 100644 index 0000000..19f643c --- /dev/null +++ b/Demo/paint/session.lua @@ -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 diff --git a/Demo/paint/tests.lua b/Demo/paint/tests.lua new file mode 100644 index 0000000..f6e8069 --- /dev/null +++ b/Demo/paint/tests.lua @@ -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 diff --git a/Demo/tui/screen.lua b/Demo/tui/screen.lua new file mode 100644 index 0000000..a16af6d --- /dev/null +++ b/Demo/tui/screen.lua @@ -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 diff --git a/Demo/tui/theme.lua b/Demo/tui/theme.lua new file mode 100644 index 0000000..0c28148 --- /dev/null +++ b/Demo/tui/theme.lua @@ -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