#!/usr/bin/env python3
"""Recolour the xfwm4 PNGs that have no SVG source.

Nine frame pieces -- the thin edge strips and the menu button states -- ship
only as PNGs upstream, with no SVG to re-render from. They are flat fills with
at most a pixel of antialiasing at the corners, so they are remapped in place:
no resampling, no rendering, and nothing to install. Upstream stores them as
indexed images at 1x but as RGBA at some of the hidpi sizes, so both are
handled. Everything else in xfwm4/ comes from render-xfwm4.sh.
"""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "lib"))

import darkmatter as dm
from png import Png
from remap import Remapper

NO_SVG = [
    "bottom-inactive", "bottom-left-inactive", "bottom-right-active",
    "left-active", "left-inactive", "menu-inactive", "menu-prelight",
    "menu-pressed", "right-inactive",
]

# Black and white are anchored to themselves so the corner antialiasing, which
# blends the frame colour toward the window's outer outline, follows along.
#
# The Darkmatter targets are anchored to themselves as well, which makes this
# script idempotent: an already-converted file matches those exactly and maps
# to itself, instead of being re-read as a Nordic blend and drifting a little
# darker on every run. render-xfwm4.sh calls this after rendering, so it does
# get run more than once.
HOVER_TINT = "#131214"

ANCHORS = [
    (dm.rgb("#353c4a"), dm.rgb(dm.DARK)),
    (dm.rgb("#363d4b"), dm.rgb(HOVER_TINT)),   # the menu button's hover tint
    (dm.rgb("#000000"), dm.rgb("#000000")),
    (dm.rgb("#ffffff"), dm.rgb("#ffffff")),
    (dm.rgb(dm.DARK), dm.rgb(dm.DARK)),
    (dm.rgb(HOVER_TINT), dm.rgb(HOVER_TINT)),
]

DIRS = [
    "xfwm4",
    "xfwm4/Darkmatter-hdpi/xfwm4",
    "xfwm4/Darkmatter-xhdpi/xfwm4",
]


def main():
    remap = Remapper(ANCHORS)
    done = 0
    for d in DIRS:
        for name in NO_SVG:
            path = os.path.join(d, name + ".png")
            if not os.path.exists(path):
                continue
            img = Png(path)
            if img.color_type == 3:
                img.set_palette([remap(c) for c in img.palette()])
            elif img.color_type == 6:
                img.set_rgba([remap(p[:3]) + (p[3],) for p in img.rgba()])
            else:
                print("  skipped (colour type %d): %s" % (img.color_type, path))
                continue
            img.save()
            done += 1
    print("recoloured %d frame PNGs" % done)


if __name__ == "__main__":
    main()
