--!strict -- image/xpm: X PixMap (XPM 3 C source and the XPM 2 plain form; the "XPM Manual" by Arnaud Le Hors; new code). Decode: -- the values line (width, height, colours, chars per pixel, hotspot: meta.hotspot), colour lines with the c / g / g4 / -- m / s keys (c preferred, then g, g4, m), #RGB / #RRGGBB / #RRRGGGBBB / #RRRRGGGGBBBB, None (transparent) and colour -- names (image/xpm/Names: the CSS / X11 names and grey0..100; an unknown name is black and listed in -- meta.unknownColours), the extensions section skipped. Encode: rgba8 as XPM 3 with hex colours, alpha < 128 as None, -- the fewest chars per pixel; opts.name (default "image"). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Sniff = require("@formats/core/Sniff") local Types = require("@formats/Types") local Names = require("@formats/image/xpm/Names") -- ------------------------------------------------------------------------------------------------ contract local Xpm = { name = "xpm", category = "image", extensions = { "xpm", "pm" }, mime = { "image/x-xpixmap", "image/x-xpm" }, deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" }, caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 8 } }, } -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { maxPixels: number?, -- refuse larger images (default 2^26) } export type EncodeOptions = { name: string?, -- the C identifier (default "image"; an extension is dropped, other characters become _) } -- the characters of pixel codes (printable ASCII without '"' and '\') local CODE_CHARS = " .XoO+@#$%&*=-;:>,<1234567890qwertyuipasdfghjklzxcvbnmMNBVCZASDFGHJKLPIUYTREWQ!~^/()_`'][{}|" -- ------------------------------------------------------------------------------------------------ sniff function Xpm.sniff(r: Bytes.Reader): number local s = Sniff.text(r, 64, true) if string.sub(s, 1, 9) == "/* XPM */" or string.sub(s, 1, 6) == "! XPM2" then return 1 end return 0 end -- ------------------------------------------------------------------------------------------------ decode -- colour value -> rgba8 u32, or nil for an unknown name local function colour(v: string): number? local l = string.lower(v) if l == "none" or l == "transparent" then return 0 end if string.sub(v, 1, 1) == "#" then local hex = string.sub(v, 2) local n = #hex if n % 3 ~= 0 or n == 0 or n > 12 or not string.match(hex, "^%x+$") then return nil end local k = n // 3 local mx = 16 ^ k - 1 local c = 0 for i = 0, 2 do local x = tonumber(string.sub(hex, i * k + 1, i * k + k), 16) :: number c += math.floor(x * 255 / mx + 0.5) * 256 ^ i end return c + 0xFF000000 end local rgb = Names.lookup(l) return if rgb then rgb + 0xFF000000 else nil end -- the strings of the file: C string literals (XPM 3) or plain lines (XPM 2) local function strings(s: string): { string } local out = {} if string.sub(Sniff.dropBom(s), 1, 6) == "! XPM2" then local first = true for line in string.gmatch(s, "[^\n]+") do if first then first = false else table.insert(out, (string.gsub(line, "\r$", ""))) end end return out end local i, n = 1, #s while i <= n do local c = string.sub(s, i, i) if c == "/" and string.sub(s, i + 1, i + 1) == "*" then local e = string.find(s, "*/", i + 2, true) i = if e then e + 2 else n + 1 elseif c == '"' then local parts = {} local j = i + 1 while j <= n do local d = string.sub(s, j, j) if d == "\\" then table.insert(parts, string.sub(s, j + 1, j + 1)) j += 2 elseif d == '"' then break else local e = string.find(s, '["\\]', j) local stop = (e or n + 1) - 1 table.insert(parts, string.sub(s, j, stop)) j = stop + 1 end end table.insert(out, table.concat(parts)) i = j + 1 else i += 1 end end return out end local KEYS = { c = true, m = true, g4 = true, g = true, s = true } function Xpm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) local n = r.limit - r.base if n > 2 ^ 27 then return nil, Err.new(Err.LIMIT, "file too large") end local list = strings(buffer.readstring(r.buf, r.base, n)) if #list == 0 then return nil, Err.new(Err.CORRUPT, "no XPM strings") end local vals: { number } = {} for tok in string.gmatch(list[1], "%S+") do table.insert(vals, tonumber(tok) or -1) end local w: number, h: number, nc: number, cpp: number = vals[1] or -1, vals[2] or -1, vals[3] or -1, vals[4] or -1 if w < 1 or h < 1 or nc < 1 or cpp < 1 or cpp > 8 or w % 1 ~= 0 or h % 1 ~= 0 then return nil, Err.new(Err.CORRUPT, "bad values line") end local maxPixels = opts and opts.maxPixels or 2 ^ 26 if w * h > maxPixels or nc > 2 ^ 24 then return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) end if #list < 1 + nc then return nil, Err.new(Err.TRUNCATED, "colour table runs past the end") end local map: { [string]: number } = {} local unknown: { string } = {} local palette: { { number } } = {} for i = 1, nc do local line = list[1 + i] local code = string.sub(line, 1, cpp) local rest = string.sub(line, cpp + 1) local found: { [string]: string } = {} local key: string? = nil local acc = {} for tok in string.gmatch(rest, "%S+") do if KEYS[tok] and (key == nil or #acc > 0) then if key then found[key] = table.concat(acc, " ") end key, acc = tok, {} else table.insert(acc, tok) end end if key then found[key] = table.concat(acc, " ") end local v = found.c or found.g or found.g4 or found.m local c = if v then colour(v) else nil if v and not c then c = colour((string.gsub(v, " ", ""))) end local cv: number = c or 0xFF000000 if not c then table.insert(unknown, v or "") end c = cv map[code] = cv palette[i] = { bit32.band(cv, 255), bit32.band(bit32.rshift(cv, 8), 255), bit32.band(bit32.rshift(cv, 16), 255), bit32.rshift(cv, 24) } end local img = Types.Image.new(w, h, "rgba8") local px = img.pixels local truncated = false for y = 0, h - 1 do local row = list[2 + nc + y] if not row then truncated = true break end for x = 0, w - 1 do local c = map[string.sub(row, x * cpp + 1, x * cpp + cpp)] buffer.writeu32(px, (y * w + x) * 4, c or 0) end end if #vals >= 6 and vals[5] >= 0 and vals[6] >= 0 then img.meta.hotspot = { x = vals[5], y = vals[6] } end if #unknown > 0 then img.meta.unknownColours = unknown end if truncated then img.meta.truncated = true end img.meta.palette = palette img.meta.source = { format = "xpm", colours = nc, charsPerPixel = cpp } return img, nil end -- ------------------------------------------------------------------------------------------------ encode function Xpm.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then return nil, Err.new(Err.ARG, "needs an rgba8 Image") end local w, h = img.width, img.height if w < 1 or h < 1 then return nil, Err.new(Err.ARG, "bad size") end -- a C identifier from opts.name (F.save passes the file name: "out.xbm" -> out) local name = string.gsub(string.gsub(opts and opts.name or "image", "%.[^.]*$", ""), "[^%w_]", "_") if name == "" or string.match(name, "^%d") then name = "_" .. name end local px = img.pixels local index: { [number]: number } = {} local order: { number } = {} local keys = table.create(w * h, 0) for i = 0, w * h - 1 do local v = buffer.readu32(px, i * 4) local k = if v < 0x80000000 then -1 else bit32.band(v, 0xFFFFFF) if not index[k] then table.insert(order, k) index[k] = #order end keys[i + 1] = index[k] end local nchars = #CODE_CHARS local cpp = 1 while nchars ^ cpp < #order do cpp += 1 end local codes: { string } = {} for i = 1, #order do local v, s = i - 1, "" for _ = 1, cpp do local d = v % nchars s ..= string.sub(CODE_CHARS, d + 1, d + 1) v //= nchars end codes[i] = s end local parts = { "/* XPM */\n", string.format("static char *%s[] = {\n", name) } local hs: { x: number, y: number }? = img.meta and img.meta.hotspot if hs then table.insert(parts, string.format('"%d %d %d %d %d %d",\n', w, h, #order, cpp, hs.x, hs.y)) else table.insert(parts, string.format('"%d %d %d %d",\n', w, h, #order, cpp)) end for i, k in order do local col = if k < 0 then "None" else string.format("#%02X%02X%02X", bit32.band(k, 255), bit32.band(bit32.rshift(k, 8), 255), bit32.rshift(k, 16)) table.insert(parts, string.format('"%s c %s",\n', codes[i], col)) end for y = 0, h - 1 do local row = table.create(w, "") for x = 0, w - 1 do row[x + 1] = codes[keys[y * w + x + 1]] end table.insert(parts, '"' .. table.concat(row) .. '"' .. (if y < h - 1 then ",\n" else "\n")) end table.insert(parts, "};\n") return buffer.fromstring(table.concat(parts)), nil end return Xpm