Files
rosetta/src/Formats/vector/svg/Style.luau
T

382 lines
13 KiB
Luau

--!strict
-- vector/svg/Style: the value syntaxes of SVG presentation attributes: colours (CSS Color 3 names, #rgb / #rgba /
-- #rrggbb / #rrggbbaa, rgb() / rgba() / hsl() / hsla() with numbers or percentages, transparent, currentColor),
-- lengths with units, transform lists, style="" declarations, and a CSS subset for <style> (rules of comma-separated
-- compound selectors made of a type, .classes, #id and *, with specificity; @rules and other combinators are skipped).
-- Never throws.
local Raster = require("@formats/codecs/image/Raster")
local Style = {}
local NAMED: { [string]: number } = {
aliceblue = 0xf0f8ff, antiquewhite = 0xfaebd7, aqua = 0x00ffff, aquamarine = 0x7fffd4, azure = 0xf0ffff,
beige = 0xf5f5dc, bisque = 0xffe4c4, black = 0x000000, blanchedalmond = 0xffebcd, blue = 0x0000ff,
blueviolet = 0x8a2be2, brown = 0xa52a2a, burlywood = 0xdeb887, cadetblue = 0x5f9ea0, chartreuse = 0x7fff00,
chocolate = 0xd2691e, coral = 0xff7f50, cornflowerblue = 0x6495ed, cornsilk = 0xfff8dc, crimson = 0xdc143c,
cyan = 0x00ffff, darkblue = 0x00008b, darkcyan = 0x008b8b, darkgoldenrod = 0xb8860b, darkgray = 0xa9a9a9,
darkgreen = 0x006400, darkgrey = 0xa9a9a9, darkkhaki = 0xbdb76b, darkmagenta = 0x8b008b, darkolivegreen = 0x556b2f,
darkorange = 0xff8c00, darkorchid = 0x9932cc, darkred = 0x8b0000, darksalmon = 0xe9967a, darkseagreen = 0x8fbc8f,
darkslateblue = 0x483d8b, darkslategray = 0x2f4f4f, darkslategrey = 0x2f4f4f, darkturquoise = 0x00ced1,
darkviolet = 0x9400d3, deeppink = 0xff1493, deepskyblue = 0x00bfff, dimgray = 0x696969, dimgrey = 0x696969,
dodgerblue = 0x1e90ff, firebrick = 0xb22222, floralwhite = 0xfffaf0, forestgreen = 0x228b22, fuchsia = 0xff00ff,
gainsboro = 0xdcdcdc, ghostwhite = 0xf8f8ff, gold = 0xffd700, goldenrod = 0xdaa520, gray = 0x808080,
grey = 0x808080, green = 0x008000, greenyellow = 0xadff2f, honeydew = 0xf0fff0, hotpink = 0xff69b4,
indianred = 0xcd5c5c, indigo = 0x4b0082, ivory = 0xfffff0, khaki = 0xf0e68c, lavender = 0xe6e6fa,
lavenderblush = 0xfff0f5, lawngreen = 0x7cfc00, lemonchiffon = 0xfffacd, lightblue = 0xadd8e6, lightcoral = 0xf08080,
lightcyan = 0xe0ffff, lightgoldenrodyellow = 0xfafad2, lightgray = 0xd3d3d3, lightgreen = 0x90ee90,
lightgrey = 0xd3d3d3, lightpink = 0xffb6c1, lightsalmon = 0xffa07a, lightseagreen = 0x20b2aa,
lightskyblue = 0x87cefa, lightslategray = 0x778899, lightslategrey = 0x778899, lightsteelblue = 0xb0c4de,
lightyellow = 0xffffe0, lime = 0x00ff00, limegreen = 0x32cd32, linen = 0xfaf0e6, magenta = 0xff00ff,
maroon = 0x800000, mediumaquamarine = 0x66cdaa, mediumblue = 0x0000cd, mediumorchid = 0xba55d3,
mediumpurple = 0x9370db, mediumseagreen = 0x3cb371, mediumslateblue = 0x7b68ee, mediumspringgreen = 0x00fa9a,
mediumturquoise = 0x48d1cc, mediumvioletred = 0xc71585, midnightblue = 0x191970, mintcream = 0xf5fffa,
mistyrose = 0xffe4e1, moccasin = 0xffe4b5, navajowhite = 0xffdead, navy = 0x000080, oldlace = 0xfdf5e6,
olive = 0x808000, olivedrab = 0x6b8e23, orange = 0xffa500, orangered = 0xff4500, orchid = 0xda70d6,
palegoldenrod = 0xeee8aa, palegreen = 0x98fb98, paleturquoise = 0xafeeee, palevioletred = 0xdb7093,
papayawhip = 0xffefd5, peachpuff = 0xffdab9, peru = 0xcd853f, pink = 0xffc0cb, plum = 0xdda0dd,
powderblue = 0xb0e0e6, purple = 0x800080, rebeccapurple = 0x663399, red = 0xff0000, rosybrown = 0xbc8f8f,
royalblue = 0x4169e1, saddlebrown = 0x8b4513, salmon = 0xfa8072, sandybrown = 0xf4a460, seagreen = 0x2e8b57,
seashell = 0xfff5ee, sienna = 0xa0522d, silver = 0xc0c0c0, skyblue = 0x87ceeb, slateblue = 0x6a5acd,
slategray = 0x708090, slategrey = 0x708090, snow = 0xfffafa, springgreen = 0x00ff7f, steelblue = 0x4682b4,
tan = 0xd2b48c, teal = 0x008080, thistle = 0xd8bfd8, tomato = 0xff6347, turquoise = 0x40e0d0, violet = 0xee82ee,
wheat = 0xf5deb3, white = 0xffffff, whitesmoke = 0xf5f5f5, yellow = 0xffff00, yellowgreen = 0x9acd32,
}
local function clamp255(v: number): number
return math.clamp(math.floor(v + 0.5), 0, 255)
end
local function hue(p: number, q: number, t: number): number
t %= 1
if t < 1 / 6 then
return p + (q - p) * 6 * t
elseif t < 1 / 2 then
return q
elseif t < 2 / 3 then
return p + (q - p) * (2 / 3 - t) * 6
end
return p
end
-- color(s, current?) -> { r, g, b, a (0..255) } | "none" | nil (not a colour). current: the currentColor value
function Style.color(s: string, current: { number }?): any
s = string.lower((string.gsub(s, "^%s*(.-)%s*$", "%1")))
if s == "none" then
return "none"
elseif s == "transparent" then
return { 0, 0, 0, 0 }
elseif s == "currentcolor" then
return current or { 0, 0, 0, 255 }
end
local hex = string.match(s, "^#(%x+)$")
if hex then
local n = #hex
if n == 3 or n == 4 then
local v = {}
for k = 1, n do
v[k] = (tonumber(string.sub(hex, k, k), 16) :: number) * 17
end
return { v[1], v[2], v[3], v[4] or 255 }
elseif n == 6 or n == 8 then
local v = {}
for k = 1, n // 2 do
v[k] = tonumber(string.sub(hex, k * 2 - 1, k * 2), 16) :: number
end
return { v[1], v[2], v[3], v[4] or 255 }
end
return nil
end
local fn, args = string.match(s, "^(%a+)%s*%((.*)%)$")
if fn then
local parts = {}
for p in string.gmatch(args :: string, "[^,%s/]+") do
table.insert(parts, p)
end
local function comp(p: string?, scale: number): number?
if p == nil then
return nil
end
local pct = string.match(p, "^([%d.eE+-]+)%%$")
if pct then
local v = tonumber(pct)
return if v then v / 100 * scale else nil
end
return tonumber(p)
end
local function alpha(p: string?): number
if p == nil then
return 255
end
local v = comp(p, 1)
return clamp255((v or 1) * 255)
end
if fn == "rgb" or fn == "rgba" then
local r, g, b = comp(parts[1], 255), comp(parts[2], 255), comp(parts[3], 255)
if not (r and g and b) then
return nil
end
return { clamp255(r :: number), clamp255(g :: number), clamp255(b :: number), alpha(parts[4]) }
elseif fn == "hsl" or fn == "hsla" then
local h = tonumber((string.gsub(parts[1] or "", "deg$", "")))
local sat, l = comp(parts[2], 1), comp(parts[3], 1)
if not (h and sat and l) then
return nil
end
local hh = (h :: number) / 360
local ss, ll = math.clamp(sat :: number, 0, 1), math.clamp(l :: number, 0, 1)
local q = if ll < 0.5 then ll * (1 + ss) else ll + ss - ll * ss
local p = 2 * ll - q
return { clamp255(hue(p, q, hh + 1 / 3) * 255), clamp255(hue(p, q, hh) * 255), clamp255(hue(p, q, hh - 1 / 3) * 255), alpha(parts[4]) }
end
return nil
end
local v = NAMED[s]
if v then
return { v // 65536, v // 256 % 256, v % 256, 255 }
end
return nil
end
-- scan(s, i) -> the SVG number at s[i] (sign? digits? ("." digits)? exponent?), the index after it | nil
local function scan(s: string, i: number): (number?, number)
local n = #s
local st = i
local c = string.byte(s, i)
if c == 43 or c == 45 then
i += 1
end
local any = false
while i <= n do
c = string.byte(s, i)
if c >= 48 and c <= 57 then
i += 1
any = true
else
break
end
end
if i <= n and string.byte(s, i) == 46 then
i += 1
while i <= n do
c = string.byte(s, i)
if c >= 48 and c <= 57 then
i += 1
any = true
else
break
end
end
end
if not any then
return nil, st
end
c = string.byte(s, i)
if c == 101 or c == 69 then
local save = i
i += 1
c = string.byte(s, i)
if c == 43 or c == 45 then
i += 1
end
local e = false
while i <= n do
c = string.byte(s, i)
if c >= 48 and c <= 57 then
i += 1
e = true
else
break
end
end
if not e then
i = save
end
end
return tonumber(string.sub(s, st, i - 1)), i
end
-- length(s, ref?, fontSize?) -> number in user units | nil. ref: what 100% is (default 100)
local UNITS: { [string]: number } = { px = 1, pt = 4 / 3, pc = 16, mm = 96 / 25.4, cm = 96 / 2.54, ["in"] = 96, q = 96 / 101.6 }
function Style.length(s: string?, ref: number?, fontSize: number?): number?
if s == nil then
return nil
end
local t = string.match(s, "^%s*(.-)%s*$") :: string
local x, j = scan(t, 1)
if x == nil then
return nil
end
local u = string.lower(string.sub(t, j))
if u == "" then
return x
elseif u == "%" then
return x / 100 * (ref or 100)
elseif u == "em" then
return x * (fontSize or 16)
elseif u == "ex" then
return x * (fontSize or 16) / 2
end
local k = UNITS[u]
return if k then x * k else nil
end
-- numbers(s) -> the numbers of a whitespace / comma separated list ("1, 2 3e1-4"); stops at anything else
function Style.numbers(s: string?): { number }
local out = {}
if s == nil then
return out
end
local i, n = 1, #s
while i <= n do
local c = string.byte(s, i)
if c == 32 or c == 44 or c == 9 or c == 10 or c == 13 then
i += 1
else
local v, j = scan(s, i)
if v == nil then
break
end
table.insert(out, v)
i = j
end
end
return out
end
-- transform(s) -> { a, b, c, d, e, f } (the product of the list) | nil on a syntax error
local mul = Raster.multiply
Style.multiply = mul
function Style.transform(s: string): { number }?
local m = { 1, 0, 0, 1, 0, 0 }
local rest = s
while true do
rest = string.gsub(rest, "^[%s,]+", "")
if rest == "" then
break
end
local name, args, after = string.match(rest, "^(%a+)%s*(%b())(.*)$")
if not name then
return nil
end
rest = after :: string
local v = Style.numbers(string.sub(args :: string, 2, -2))
local t: { number }
if name == "matrix" and #v == 6 then
t = v
elseif name == "translate" and (#v == 1 or #v == 2) then
t = { 1, 0, 0, 1, v[1], v[2] or 0 }
elseif name == "scale" and (#v == 1 or #v == 2) then
t = { v[1], 0, 0, v[2] or v[1], 0, 0 }
elseif name == "rotate" and (#v == 1 or #v == 3) then
local r = v[1] * math.pi / 180
local c, sn = math.cos(r), math.sin(r)
t = { c, sn, -sn, c, 0, 0 }
if #v == 3 then
t = mul(mul({ 1, 0, 0, 1, v[2], v[3] }, t), { 1, 0, 0, 1, -v[2], -v[3] })
end
elseif name == "skewX" and #v == 1 then
t = { 1, 0, math.tan(v[1] * math.pi / 180), 1, 0, 0 }
elseif name == "skewY" and #v == 1 then
t = { 1, math.tan(v[1] * math.pi / 180), 0, 1, 0, 0 }
else
return nil
end
m = mul(m, t)
end
return m
end
-- declarations("a: b; c: d") -> { [name] = value } (lower-case names, !important dropped)
function Style.declarations(s: string): { [string]: string }
local out: { [string]: string } = {}
for decl in string.gmatch(s, "[^;]+") do
local k, v = string.match(decl, "^%s*([%w-]+)%s*:%s*(.-)%s*$")
if k and v then
v = string.gsub(v :: string, "%s*!important$", "")
out[string.lower(k :: string)] = v :: string
end
end
return out
end
-- ------------------------------------------------------------------------------------------------ CSS
export type Selector = { tag: string?, id: string?, classes: { string }, specificity: number }
export type Rule = { selector: Selector, decls: { [string]: string }, order: number }
local function selector(s: string): Selector?
s = string.gsub(s, "^%s*(.-)%s*$", "%1")
if s == "" or string.find(s, "[%s>+~%[:]") then
return nil -- combinators, attribute and pseudo selectors: not supported
end
local sel: Selector = { classes = {}, specificity = 0 }
local tag = string.match(s, "^([%a_][%w_-]*)")
if tag then
sel.tag = tag
sel.specificity += 1
s = string.sub(s, #tag + 1)
elseif string.sub(s, 1, 1) == "*" then
s = string.sub(s, 2)
end
while s ~= "" do
local kind, name, rest = string.match(s, "^([.#])([%w_-]+)(.*)$")
if not kind then
return nil
end
if kind == "." then
table.insert(sel.classes, name :: string)
sel.specificity += 100
else
sel.id = name
sel.specificity += 10000
end
s = rest :: string
end
return sel
end
-- css(text, rules?) -> rules (appended to the list given)
function Style.css(text: string, rules: { Rule }?): { Rule }
local out: { Rule } = rules or {}
text = string.gsub(text, "/%*.-%*/", "")
text = string.gsub(text, "<!%-%-", "")
text = string.gsub(text, "%-%->", "")
-- drop @rules with blocks (@media { ... { } }) and simple ones (@import ...;)
local guard = 0
while guard < 100 do
guard += 1
local s, e = string.find(text, "@[%w-]+[^{;]*%b{}")
if not s then
break
end
text = string.sub(text, 1, s - 1) .. string.sub(text, (e :: number) + 1)
end
text = string.gsub(text, "@[%w-]+[^;{]*;", "")
for sels, body in string.gmatch(text, "([^{}]+)(%b{})") do
local decls = Style.declarations(string.sub(body :: string, 2, -2))
for one in string.gmatch(sels, "[^,]+") do
local sel = selector(one)
if sel then
table.insert(out, { selector = sel, decls = decls, order = #out + 1 })
end
end
end
return out
end
-- matches(sel, tag, id, classes) -> boolean
function Style.matches(sel: Selector, tag: string, id: string?, classes: { [string]: boolean }): boolean
if sel.tag and sel.tag ~= tag then
return false
end
if sel.id and sel.id ~= id then
return false
end
for _, c in sel.classes do
if not classes[c] then
return false
end
end
return true
end
return Style