Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-svg

Source of release 0.9.1

0.9.1 / src / svg / style.lucb

#==============================================================================================
#
#   svg/style - Styles, their inheritance, and paint and color parsing
#
#   DESCRIPTION:
#       A Style is what an element draws with: its fill and stroke paints, their opacities,
#       the stroke's width, caps, joins and dashes, its font (text.lucb), and the product
#       of every enclosing `opacity`. Each property is read from the element's `style="..."` declarations
#       first, then from its presentation attribute, else inherited from the parent. Colors (colors.lucb)
#       are #rgb, #rrggbb, rgb() with numbers or percentages, and the 148 CSS named colors.
#
#==============================================================================================

## What an element draws with. SVG's defaults: a black fill and no stroke.
struct Style:
    var fill: Paint = Paint(painted = true)
    var stroke: Paint = Paint()
    var opacity: f64 = 1.0
    var fill_opacity: f64 = 1.0
    var stroke_opacity: f64 = 1.0
    var pen: Pen = Pen()
    var font: Font = Font()

## `base`, the parent's style, with whatever paint, stroke and opacity properties `tag` sets.
## `opacity` multiplies into the parent's, so a group's fades everything inside it (each
## paint on its own, not the group as one layer). `gradient_ids` names the document's
## gradients, by index, for `url(#id)` paints.
func styled(tag: str, base: Style, gradient_ids: const str[]) -> Style:
    var style = base
    if let value = property(tag, "fill"):
        style.fill = drawing_paint(value, base.fill, gradient_ids)
    if let value = property(tag, "stroke"):
        style.stroke = drawing_paint(value, base.stroke, gradient_ids)
    style.opacity = base.opacity * math.clamp(number_property(tag, "opacity", 1.0), 0.0, 1.0)
    style.fill_opacity = math.clamp(number_property(tag, "fill-opacity", base.fill_opacity), 0.0, 1.0)
    style.stroke_opacity = math.clamp(number_property(tag, "stroke-opacity", base.stroke_opacity), 0.0, 1.0)
    style.pen = penned(tag, base.pen)
    style.font = fonted(tag, base.font)
    return style

## `base` with whatever stroke width, cap, join, miter limit and dash properties `tag` sets.
func penned(tag: str, base: Pen) -> Pen:
    var pen = base
    pen.width = number_property(tag, "stroke-width", base.width)
    if let cap = property(tag, "stroke-linecap"):
        pen.cap = Cap.round if cap == "round" else (Cap.square if cap == "square" else Cap.butt)
    if let join = property(tag, "stroke-linejoin"):
        pen.join = Join.round if join == "round" else (Join.bevel if join == "bevel" else Join.miter)
    pen.miter_limit = math.max(1.0, number_property(tag, "stroke-miterlimit", base.miter_limit))
    if let pattern = property(tag, "stroke-dasharray"):
        pen.dash_count = 0
        if pattern != "none":
            let data = pattern.bytes
            var pos: usize = 0
            while pos < data.length and pen.dash_count < 8:
                skip_separators(data, &pos)
                if pos >= data.length:
                    break
                let value = read_number(data, &pos) catch _:
                    break
                if value > 0.0:
                    pen.dashes[pen.dash_count] = value
                    pen.dash_count += 1
    pen.dash_offset = number_property(tag, "stroke-dashoffset", base.dash_offset)
    return pen

# mark: Properties ============================================================================

## A style property of `tag`, trimmed: its last declaration in `style="..."`, else its
## presentation attribute, else none.
func property(tag: str, name: str) -> str?:
    if let declarations = tag_attribute(tag, "style"):
        var found: str? = none
        var rest = declarations
        while rest.length > 0:
            var piece = rest
            rest = ""
            if let cut = strings.find(piece, ";"):
                rest = (str)piece.bytes[cut + 1..]
                piece = (str)piece.bytes[..<cut]
            let (key, value) = strings.split_once(piece, ":") else continue
            if strings.trim(key) == name:
                found = strings.trim(value)
        if let value = found:
            return value
    let value = tag_attribute(tag, name) else return none
    return strings.trim(value)

## A numeric property (a trailing `px` allowed), or `fallback` when absent or unreadable.
func number_property(tag: str, name: str, fallback: f64) -> f64:
    var value = property(tag, name) else return fallback
    if strings.ends_with(value, "px"):
        value = (str)value.bytes[..<value.length - 2]
    return strings.parse_f64(value) catch _: recover fallback

# mark: Paints and colors =====================================================================

## The paint `value` names. `inherit` keeps the parent's. `url(#id)` paints with the
## gradient of that id among `gradient_ids`, else with the fallback written after it, else
## not at all. An unknown color name is black, so the shape still shows.
func drawing_paint(value: str, inherited: Paint, gradient_ids: const str[]) -> Paint:
    if value == "" or value == "none" or same_folded(value, "transparent"):
        return Paint()
    if value == "inherit":
        return inherited
    if strings.starts_with(value, "url("):
        let close = strings.find(value, ")") else return Paint()
        var id = strings.trim((str)value.bytes[4..<close])
        if strings.starts_with(id, "#"):
            id = (str)id.bytes[1..]
        for index in 0..<gradient_ids.length:
            if id != "" and gradient_ids[index] == id:
                return Paint(painted = true, gradient = index + 1)
        return drawing_paint(strings.trim((str)value.bytes[close + 1..]), Paint(), gradient_ids)
    if same_folded(value, "currentColor"):
        return Paint(painted = true, current = true)
    let color = parse_color(value) else return Paint(painted = true)
    return Paint(painted = true, color = color)

## Whether `a` and `b` match, ignoring ASCII case.
func same_folded(a: str, b: str) -> bool:
    if a.length != b.length:
        return false
    for index in 0..<a.length:
        var x = a.bytes[index]
        var y = b.bytes[index]
        if x >= 'A' and x <= 'Z':
            x += 32
        if y >= 'A' and y <= 'Z':
            y += 32
        if x != y:
            return false
    return true

## `color` decoded from sRGB to linear light, channel by channel.
func to_linear(color: Color) -> Color:
    return Color(r = transfer.srgb_decode(color.r), g = transfer.srgb_decode(color.g), b = transfer.srgb_decode(color.b))