"""The "Bois & Laiton" skin of WinZik: a hi-fi amplifier of the 1970s. Walnut cabinet (the grain is computed), brushed
brass face plates, cream ivory keys with engraved dark symbols, amber-lit windows with warm orange digits, small
slotted screws, a lit tuning dial and two knurled knobs under the player. Everything is drawn here pixel by pixel
(no picture of another program is copied, no logo, no brand). Light comes from the top left everywhere.
Every picture has the size and the place the other skins use (see classique.py).
Run: python3 -I tools/skins/boislaiton.py assets/skins/bois-laiton
"""
import math
import os
import random
import sys
from PIL import Image, ImageDraw, ImageFont

OUT = sys.argv[1] if len(sys.argv) > 1 else 'assets/skins/bois-laiton'
os.makedirs(OUT, exist_ok=True)

# --- the palette --------------------------------------------------------------------------------------------------
WOOD_DARK = (46, 25, 12)
WOOD_MID = (98, 57, 30)
WOOD_LIGHT = (146, 92, 52)
WOOD_EDGE_HI = (168, 116, 72)
GAP = (24, 13, 6)                       # the dark joint between two parts of the case

BRASS = (204, 166, 92)
BRASS_HI = (252, 232, 168)
BRASS_LO = (112, 80, 34)
BRASS_INK = (74, 50, 20)                # engraved in brass

IVORY_TOP = (248, 241, 220)
IVORY_BOTTOM = (218, 204, 172)
IVORY_HI = (255, 253, 244)
IVORY_LO = (166, 146, 110)
IVORY_EDGE = (54, 36, 20)
INK = (60, 40, 24)                      # engraved in ivory

LCD = (24, 12, 4)
LCD_GLOW = (30, 14, 3)                  # added at the middle of a window: the backlight
AMBER = (255, 176, 64)
AMBER_DIM = (70, 36, 10)
AMBER_TEXT = (255, 168, 60)


def clamp(c):
    return tuple(max(0, min(255, int(round(v)))) for v in c)


def mix(a, b, t):
    return tuple(a[i] + (b[i] - a[i]) * t for i in range(3))


def scale(c, f):
    return tuple(v * f for v in c)


def font(size):
    try:
        return ImageFont.load_default(size=size)
    except TypeError:
        return ImageFont.load_default()


def new(w, h, color=(0, 0, 0, 0)):
    return Image.new('RGBA', (w, h), color)


def save(im, name):
    im.save(os.path.join(OUT, name + '.png'))


def put(im, x, y, c, a=255):
    if 0 <= x < im.width and 0 <= y < im.height:
        if a >= 255:
            im.putpixel((x, y), clamp(c) + (255,))
        else:
            r, g, b, oa = im.getpixel((x, y))
            t = a / 255
            im.putpixel((x, y), clamp((r + (c[0] - r) * t, g + (c[1] - g) * t, b + (c[2] - b) * t)) + (max(oa, a),))


def shade(im, x, y, f):
    """Darken (f < 1) or lighten (f > 1) one pixel."""
    if 0 <= x < im.width and 0 <= y < im.height:
        r, g, b, a = im.getpixel((x, y))
        im.putpixel((x, y), clamp((r * f, g * f, b * f)) + (a,))


def hline(im, x0, x1, y, c):
    for x in range(x0, x1 + 1):
        put(im, x, y, c)


def vline(im, x, y0, y1, c):
    for y in range(y0, y1 + 1):
        put(im, x, y, c)


# --- a 3 x 5 pixel font for the tiny labels -----------------------------------------------------------------------
PIX = {
    '0': ['111', '101', '101', '101', '111'], '1': ['01', '11', '01', '01', '01'], '2': ['111', '001', '111', '100', '111'],
    '3': ['111', '001', '011', '001', '111'], '4': ['101', '101', '111', '001', '001'], '5': ['111', '100', '111', '001', '111'],
    '6': ['111', '100', '111', '101', '111'], '7': ['111', '001', '010', '010', '010'], '8': ['111', '101', '111', '101', '111'],
    '9': ['111', '101', '111', '001', '111'], 'A': ['010', '101', '111', '101', '101'], 'B': ['110', '101', '110', '101', '110'],
    'C': ['011', '100', '100', '100', '011'], 'D': ['110', '101', '101', '101', '110'], 'E': ['111', '100', '110', '100', '111'],
    'F': ['111', '100', '110', '100', '100'], 'G': ['011', '100', '101', '101', '011'], 'H': ['101', '101', '111', '101', '101'],
    'I': ['111', '010', '010', '010', '111'], 'K': ['101', '110', '100', '110', '101'], 'L': ['100', '100', '100', '100', '111'],
    'M': ['10001', '11011', '10101', '10001', '10001'], 'N': ['1001', '1101', '1011', '1001', '1001'],
    'O': ['111', '101', '101', '101', '111'], 'P': ['110', '101', '110', '100', '100'], 'R': ['110', '101', '110', '101', '101'],
    'S': ['011', '100', '010', '001', '110'], 'T': ['111', '010', '010', '010', '010'], 'U': ['101', '101', '101', '101', '111'],
    'V': ['101', '101', '101', '101', '010'], 'W': ['10001', '10001', '10101', '10101', '01010'], 'Y': ['101', '101', '010', '010', '010'],
    'Z': ['111', '001', '010', '100', '111'], 'z': ['000', '111', '001', '010', '111'], '/': ['001', '001', '010', '100', '100'],
    '-': ['000', '000', '111', '000', '000'], '.': ['0', '0', '0', '0', '1'], ' ': ['00', '00', '00', '00', '00'],
}


def pwidth(s):
    return sum(len(PIX[ch][0]) + 1 for ch in s) - 1


def ptext(im, x, y, s, color, a=255):
    for ch in s:
        rows = PIX[ch]
        for j, row in enumerate(rows):
            for i, bit in enumerate(row):
                if bit == '1':
                    put(im, x + i, y + j, color, a)
        x += len(rows[0]) + 1


def pengrave(im, x, y, s, dark, light):
    """Pixel text cut into a surface: its light edge below right, the cut itself dark."""
    ptext(im, x + 1, y + 1, s, light, 170)
    ptext(im, x, y, s, dark)


# --- materials ----------------------------------------------------------------------------------------------------
def smooth(values, k):
    n = len(values)
    out = []
    for i in range(n):
        s = 0
        for j in range(-k, k + 1):
            s += values[(i + j) % n]
        out.append(s / (2 * k + 1))
    return out


def wood(im, box, seed):
    """Walnut, the grain running along x: wavy growth rings, fine fibres and a few dark pores."""
    rnd = random.Random(seed)
    x0, y0, x1, y1 = box
    w, h = x1 - x0, y1 - y0
    ph = [rnd.uniform(0, 6.28) for i in range(6)]
    fib = smooth([rnd.uniform(-1, 1) for i in range(h * 3 + 64)], 1)
    for y in range(y0, y1):
        for x in range(x0, x1):
            u, v = x - x0, y - y0
            warp = 2.6 * math.sin(u * 0.021 + ph[0]) + 1.2 * math.sin(u * 0.067 + ph[1] + v * 0.04) + 0.6 * math.sin(u * 0.17 + ph[2])
            g = v + warp
            ring = 0.5 + 0.5 * math.sin(g * 0.62 + 1.6 * math.sin(g * 0.11 + ph[3]) + 0.8 * math.sin(u * 0.009 + ph[4]))
            ring = ring ** 1.6
            f = fib[int((g + 32) * 3) % len(fib)]
            t = 0.18 + 0.5 * ring + 0.16 * f + rnd.uniform(-0.05, 0.05)
            t = max(0.0, min(1.0, t))
            c = mix(WOOD_DARK, WOOD_MID, t / 0.6) if t < 0.6 else mix(WOOD_MID, WOOD_LIGHT, (t - 0.6) / 0.4)
            put(im, x, y, c)
    # the pores: short dark dashes along the grain
    for k in range(w * h // 70):
        u, v = rnd.randrange(w), rnd.randrange(h)
        for i in range(rnd.randint(2, 5)):
            shade(im, x0 + u + i, y0 + v, 0.78)


def brass(im, box, seed):
    """Brushed brass: long horizontal strokes, lighter at the top left (where the light comes from)."""
    rnd = random.Random(seed)
    x0, y0, x1, y1 = box
    w, h = x1 - x0, y1 - y0
    rowj = smooth([rnd.uniform(-1, 1) for i in range(h)], 0)
    for y in range(y0, y1):
        streak = smooth([rnd.uniform(-1, 1) for i in range(w)], 6)
        streak = [s * 2.2 for s in streak]
        ty = (y - y0) / max(1, h - 1)
        for x in range(x0, x1):
            tx = (x - x0) / max(1, w - 1)
            f = 1.07 - 0.13 * ty - 0.07 * tx + 0.05 * math.cos((tx - 0.22) * 5.0) * (1 - ty * 0.5)
            f *= 1 + 0.035 * rowj[y - y0] + 0.045 * streak[x - x0] + rnd.uniform(-0.012, 0.012)
            put(im, x, y, scale(BRASS, f))


def lcd(im, x, y, w, h, vertical_glow=True, grid=False):
    """An amber backlit window: dark warm glass, brighter in the middle."""
    for j in range(h):
        gy = 1 - ((j + 0.5) / h * 2 - 1) ** 2 if vertical_glow else 1
        for i in range(w):
            gx = 1 - ((i + 0.5) / w * 2 - 1) ** 2
            g = (gx ** 0.7) * (gy ** 0.7)
            c = (LCD[0] + LCD_GLOW[0] * g, LCD[1] + LCD_GLOW[1] * g, LCD[2] + LCD_GLOW[2] * g)
            if grid and (i % 2 == 1 and j % 2 == 1):
                c = scale(c, 1.35)
            put(im, x + i, y + j, c)


def sunken(im, x, y, w, h, surface='brass'):
    """The bezel of a window cut into the plate: shadow on the top / left edges, light on the bottom / right."""
    lo, hi = (BRASS_LO, BRASS_HI) if surface == 'brass' else (GAP, WOOD_EDGE_HI)
    hline(im, x - 1, x + w, y - 1, lo)
    vline(im, x - 1, y - 1, y + h, lo)
    hline(im, x - 1, x + w, y + h, hi)
    vline(im, x + w, y - 1, y + h, hi)
    put(im, x - 1, y + h, mix(lo, hi, 0.5))
    put(im, x + w, y - 1, mix(lo, hi, 0.5))
    # an inner black lip makes the glass look set back
    hline(im, x, x + w - 1, y, (10, 5, 2))
    vline(im, x, y, y + h - 1, (10, 5, 2))


def screw(im, cx, cy, slot=1):
    """A slotted screw head, 7 px wide, with its little shadow."""
    for dy in range(-4, 5):
        for dx in range(-4, 5):
            d = math.hypot(dx - 1, dy - 1)
            if d <= 3.3 and math.hypot(dx, dy) > 3.3:
                shade(im, cx + dx, cy + dy, 0.62)
    for dy in range(-3, 4):
        for dx in range(-3, 4):
            d = math.hypot(dx, dy)
            if d > 3.3:
                continue
            lit = 0.5 - (dx + dy) / 8.5
            c = mix((96, 78, 50), (238, 222, 180), max(0, min(1, lit)))
            if d > 2.5:
                c = scale(c, 0.78)
            put(im, cx + dx, cy + dy, c)
    for k in range(-2, 3):
        if slot:
            put(im, cx + k, cy - k, (52, 40, 24))
            put(im, cx + k + 1, cy - k, (240, 226, 190), 150)
        else:
            put(im, cx + k, cy + k, (52, 40, 24))
            put(im, cx + k, cy + k + 1, (240, 226, 190), 150)


def knob(im, cx, cy, r, angle):
    """A knurled brass knob seen from the front: spun face, ridged rim, a dark mark."""
    for dy in range(-r - 3, r + 4):
        for dx in range(-r - 3, r + 4):
            if math.hypot(dx - 2, dy - 2) <= r + 0.4 and math.hypot(dx, dy) > r + 0.4:
                shade(im, cx + dx, cy + dy, 0.55)
    for dy in range(-r, r + 1):
        for dx in range(-r, r + 1):
            d = math.hypot(dx, dy)
            if d > r + 0.4:
                continue
            a = math.atan2(dy, dx)
            lit = 0.55 - (dx + dy) / (2.6 * r)
            if d > r - 2.2:                       # the knurled rim
                ridge = 1.0 if int((a + math.pi) / (2 * math.pi) * 40) % 2 == 0 else 0.72
                c = mix((70, 50, 22), (226, 190, 112), max(0, min(1, lit)))
                c = scale(c, ridge)
            else:                                 # the spun face
                spin = 0.06 * math.sin(d * 2.4)
                sheen = 0.16 * math.cos(2 * (a + math.pi / 4))
                c = mix((120, 88, 40), (250, 226, 160), max(0, min(1, lit + sheen + spin)))
            put(im, cx + dx, cy + dy, c)
    # the mark
    for k in range(2, r - 2):
        x = cx + round(math.cos(angle) * k)
        y = cy + round(math.sin(angle) * k)
        put(im, x, y, (40, 26, 10))


def lamp(im, cx, cy, on):
    """A small round pilot lamp, 7 px."""
    for dy in range(-3, 4):
        for dx in range(-3, 4):
            d = math.hypot(dx, dy)
            if d > 3.2:
                continue
            if on:
                t = max(0, 1 - d / 3.2)
                c = mix((200, 90, 10), (255, 236, 170), t ** 1.4)
            else:
                t = max(0, 0.5 - (dx + dy) / 8)
                c = mix((40, 20, 8), (110, 66, 32), t)
            if d > 2.5:
                c = scale(c, 0.7)
            put(im, cx + dx, cy + dy, c)
    put(im, cx - 1, cy - 1, (255, 250, 230) if on else (150, 110, 70))


# --- the ivory keys -----------------------------------------------------------------------------------------------
def key(w, h, lit=None):
    """A cream ivory key filling the whole picture, its corners rounded, light from the top left."""
    im = new(w, h)
    for y in range(h):
        t = y / max(1, h - 1)
        hline(im, 0, w - 1, y, mix(IVORY_TOP, IVORY_BOTTOM, t))
    hline(im, 1, w - 2, 1, IVORY_HI)
    vline(im, 1, 1, h - 2, IVORY_HI)
    hline(im, 1, w - 2, h - 2, IVORY_LO)
    vline(im, w - 2, 1, h - 2, IVORY_LO)
    put(im, 1, h - 2, mix(IVORY_HI, IVORY_LO, 0.5))
    put(im, w - 2, 1, mix(IVORY_HI, IVORY_LO, 0.5))
    hline(im, 1, w - 2, 0, IVORY_EDGE)
    hline(im, 1, w - 2, h - 1, IVORY_EDGE)
    vline(im, 0, 1, h - 2, IVORY_EDGE)
    vline(im, w - 1, 1, h - 2, IVORY_EDGE)
    for x, y in [(0, 0), (w - 1, 0), (0, h - 1), (w - 1, h - 1)]:
        im.putpixel((x, y), (0, 0, 0, 0))
    for x, y in [(1, 1), (w - 2, 1), (1, h - 2), (w - 2, h - 2)]:
        im.putpixel((x, y), IVORY_EDGE + (255,))
    if lit is not None:
        lamp_small(im, 4, h // 2, lit)
    return im


def lamp_small(im, cx, cy, on):
    """The 3 x 3 indicator of a key."""
    for dy in range(-1, 2):
        for dx in range(-1, 2):
            if on:
                c = (255, 214, 120) if dx == 0 and dy == 0 else (240, 130, 20)
            else:
                c = (120, 84, 50) if dx == 0 and dy == 0 else (88, 58, 32)
            if abs(dx) + abs(dy) == 2:
                c = mix(c, IVORY_LO, 0.5)
            put(im, cx + dx, cy + dy, c)


def engrave_mask(im, mask):
    """Cuts a mask (an L picture of the key's size) into the key: the light edge first, the dark cut over it."""
    hi = Image.new('L', im.size, 0)
    hi.paste(mask, (1, 1))
    im.paste(IVORY_HI + (255,), (0, 0, im.width, im.height), hi)
    im.paste(INK + (255,), (0, 0, im.width, im.height), mask)
    return im


def glyph_mask(w, h, kind, cx, cy):
    m = Image.new('L', (w, h), 0)
    d = ImageDraw.Draw(m)
    f = 255
    if kind == 'prev':
        d.rectangle([cx - 5, cy - 3, cx - 4, cy + 3], fill=f)
        d.polygon([(cx, cy - 3), (cx, cy + 3), (cx - 3, cy)], fill=f)
        d.polygon([(cx + 4, cy - 3), (cx + 4, cy + 3), (cx + 1, cy)], fill=f)
    elif kind == 'next':
        d.polygon([(cx - 4, cy - 3), (cx - 4, cy + 3), (cx - 1, cy)], fill=f)
        d.polygon([(cx, cy - 3), (cx, cy + 3), (cx + 3, cy)], fill=f)
        d.rectangle([cx + 4, cy - 3, cx + 5, cy + 3], fill=f)
    elif kind == 'play':
        d.polygon([(cx - 2, cy - 4), (cx - 2, cy + 4), (cx + 2, cy)], fill=f)
        d.line([(cx - 2, cy - 4), (cx + 2, cy)], fill=f)
        d.line([(cx - 2, cy + 4), (cx + 2, cy)], fill=f)
    elif kind == 'pause':
        d.rectangle([cx - 3, cy - 3, cx - 2, cy + 3], fill=f)
        d.rectangle([cx + 1, cy - 3, cx + 2, cy + 3], fill=f)
    elif kind == 'stop':
        d.rectangle([cx - 3, cy - 3, cx + 3, cy + 3], fill=f)
    elif kind == 'list':
        for k in (-3, 0, 3):
            d.rectangle([cx - 5, cy + k, cx - 4, cy + k], fill=f)
            d.rectangle([cx - 2, cy + k, cx + 5, cy + k], fill=f)
    elif kind == 'shuffle':
        d.line([(cx - 4, cy + 3), (cx - 2, cy + 3), (cx + 2, cy - 2), (cx + 4, cy - 2)], fill=f)
        d.line([(cx - 4, cy - 2), (cx - 2, cy - 2), (cx + 2, cy + 3), (cx + 4, cy + 3)], fill=f)
        d.line([(cx + 3, cy - 4), (cx + 5, cy - 2), (cx + 3, cy)], fill=f)
        d.line([(cx + 3, cy + 1), (cx + 5, cy + 3), (cx + 3, cy + 5)], fill=f)
    elif kind == 'info':
        d.rectangle([cx, cy - 4, cx + 1, cy - 3], fill=f)
        d.rectangle([cx - 1, cy - 1, cx + 1, cy - 1], fill=f)
        d.rectangle([cx, cy - 1, cx + 1, cy + 3], fill=f)
        d.rectangle([cx - 1, cy + 4, cx + 2, cy + 4], fill=f)
    elif kind == 'minimize':
        d.rectangle([cx - 3, cy + 2, cx + 3, cy + 3], fill=f)
    elif kind == 'close':
        d.line([(cx - 3, cy - 3), (cx + 3, cy + 3)], fill=f)
        d.line([(cx - 2, cy - 3), (cx + 3, cy + 2)], fill=f)
        d.line([(cx + 3, cy - 3), (cx - 3, cy + 3)], fill=f)
        d.line([(cx + 2, cy - 3), (cx - 3, cy + 2)], fill=f)
    elif kind == 'tray':
        d.polygon([(cx - 3, cy - 2), (cx + 3, cy - 2), (cx, cy + 1)], fill=f)
        d.rectangle([cx - 3, cy + 3, cx + 3, cy + 3], fill=f)
    elif kind == 'note':
        d.rectangle([cx - 3, cy + 1, cx - 1, cy + 3], fill=f)
        d.rectangle([cx - 4, cy + 2, cx - 4, cy + 2], fill=f)
        d.rectangle([cx - 1, cy - 4, cx - 1, cy + 2], fill=f)
        d.line([(cx, cy - 4), (cx + 2, cy - 2), (cx + 2, cy - 1)], fill=f)
    elif kind == 'restore':
        d.rectangle([cx - 3, cy - 3, cx + 3, cy + 3], outline=f)
        d.rectangle([cx - 3, cy - 3, cx + 3, cy - 2], fill=f)
    elif kind == 'chevron':
        d.line([(cx - 3, cy - 2), (cx, cy + 1), (cx + 3, cy - 2)], fill=f)
        d.line([(cx - 3, cy - 1), (cx, cy + 2), (cx + 3, cy - 1)], fill=f)
    elif kind == 'updown':
        d.polygon([(cx - 3, cy - 2), (cx + 3, cy - 2), (cx, cy - 5)], fill=f)
        d.polygon([(cx - 3, cy + 2), (cx + 3, cy + 2), (cx, cy + 5)], fill=f)
    elif kind == 'plus':
        d.rectangle([cx - 4, cy - 1, cx + 4, cy], fill=f)
        d.rectangle([cx - 1, cy - 4, cx, cy + 3], fill=f)
    elif kind == 'minus':
        d.rectangle([cx - 4, cy - 1, cx + 4, cy], fill=f)
    elif kind == 'folder':
        d.line([(cx - 5, cy - 3), (cx - 2, cy - 3), (cx - 1, cy - 2), (cx + 4, cy - 2), (cx + 4, cy - 1)], fill=f)
        d.line([(cx - 5, cy - 3), (cx - 5, cy + 3), (cx + 3, cy + 3), (cx + 5, cy - 1), (cx - 3, cy - 1), (cx - 5, cy + 3)], fill=f)
    elif kind == 'disk':
        d.rectangle([cx - 4, cy - 4, cx + 4, cy + 4], outline=f)
        d.rectangle([cx - 2, cy - 4, cx + 2, cy - 2], fill=f)
        d.rectangle([cx - 2, cy + 1, cx + 2, cy + 4], outline=f)
    elif kind == 'bin':
        d.rectangle([cx - 4, cy - 3, cx + 4, cy - 3], fill=f)
        d.rectangle([cx - 1, cy - 4, cx + 1, cy - 4], fill=f)
        d.line([(cx - 3, cy - 2), (cx - 3, cy + 4), (cx + 3, cy + 4), (cx + 3, cy - 2)], fill=f)
        d.line([(cx - 1, cy - 1), (cx - 1, cy + 2)], fill=f)
        d.line([(cx + 1, cy - 1), (cx + 1, cy + 2)], fill=f)
    return m


def text_mask(w, h, s, cx, cy, size=8):
    m = Image.new('L', (w, h), 0)
    d = ImageDraw.Draw(m)
    d.fontmode = '1'
    d.text((cx, cy), s, font=font(size), fill=255, anchor='mm')
    return m


def glyph_key(w, h, kind, lit=None, dx=0, dy=0):
    im = key(w, h, lit)
    cx = w // 2 + dx + (2 if lit is not None else 0)
    return engrave_mask(im, glyph_mask(w, h, kind, cx, (h - 1) // 2 + dy))


def label_key(w, h, s, lit=None, size=8):
    im = key(w, h, lit)
    cx = w / 2 + (3 if lit is not None else 0)
    return engrave_mask(im, text_mask(w, h, s, cx, h / 2, size))


# === the player (main.bmp, 258 x 128: 99 shown, 128 opened) ======================================================
main = new(258, 128, (0, 0, 0, 255))
wood(main, (0, 0, 258, 15), 11)
brass(main, (0, 15, 258, 99), 12)
wood(main, (0, 99, 258, 128), 13)

# the joints and the plate's bevel
hline(main, 0, 257, 14, GAP)
hline(main, 1, 256, 15, BRASS_HI)
vline(main, 0, 15, 98, BRASS_HI)
hline(main, 0, 257, 98, BRASS_LO)
vline(main, 257, 15, 98, BRASS_LO)
hline(main, 0, 257, 99, GAP)
hline(main, 1, 256, 0, WOOD_EDGE_HI)
hline(main, 1, 256, 100, WOOD_EDGE_HI)
vline(main, 0, 0, 13, WOOD_EDGE_HI)
vline(main, 0, 100, 127, WOOD_EDGE_HI)
vline(main, 257, 0, 13, GAP)
vline(main, 257, 100, 127, GAP)
hline(main, 0, 257, 127, GAP)

# the windows (where WinZik writes)
sunken(main, 47, 1, 163, 12, 'wood')            # the scrolling title (Text4), text at 48, 1
lcd(main, 47, 1, 163, 12)
sunken(main, 27, 17, 197, 12)                   # the bargraph: blocks at y 19..26
lcd(main, 27, 17, 197, 12)
for i in range(23):                             # the unlit segments under the ones WinZik lights
    for x in (120 - (i + 1) * 4, 133 + i * 4):
        for y in range(19, 27):
            put(main, x, y, AMBER_DIM if i < 19 else (78, 26, 10))
            put(main, x + 1, y, AMBER_DIM if i < 19 else (78, 26, 10))
            put(main, x + 2, y, scale(AMBER_DIM, 0.8) if i < 19 else (62, 20, 8))
ptext(main, 122, 20, 'L', (150, 86, 26))
ptext(main, 128, 20, 'R', (150, 86, 26))
put(main, 126, 21, (150, 86, 26))
put(main, 126, 23, (150, 86, 26))
sunken(main, 1, 31, 69, 13)                     # "Volume : xx %", text at 1, 33
lcd(main, 1, 31, 69, 13)
sunken(main, 112, 31, 32, 13)                   # kbps, text at 118, 33
lcd(main, 112, 31, 32, 13)
sunken(main, 186, 31, 70, 13)                   # "Balance : x %", right-aligned at 252
lcd(main, 186, 31, 70, 13)
sunken(main, 1, 81, 55, 16)                     # the counter, digits at 1 / 19 / 37, y 84
lcd(main, 1, 81, 55, 16, grid=True)
for cx in (16, 34):                             # the colons of the counter
    for cy in (88, 92):
        put(main, cx, cy, (150, 86, 26))
        put(main, cx + 1, cy, (120, 66, 20))
        put(main, cx, cy + 1, (120, 66, 20))
        put(main, cx + 1, cy + 1, (96, 52, 16))
pengrave(main, 148, 35, 'KBIT/S', BRASS_INK, BRASS_HI)

# the lamp's bezel between the two sliders (WinZik lights it at 123..131, 48..56)
for dy in range(-7, 8):
    for dx in range(-7, 8):
        d = math.hypot(dx, dy)
        if 4.6 < d <= 6.3:
            lit = 0.5 + (dx + dy) / 14              # a raised ring: light top left, a hollow inside
            put(main, 127 + dx, 52 + dy, mix(BRASS_LO, BRASS_HI, max(0, min(1, 1 - lit))) if d < 5.4 else mix(BRASS_LO, BRASS_HI, max(0, min(1, lit))))
        elif d <= 4.6:
            put(main, 127 + dx, 52 + dy, (40, 14, 6))

# the screws
screw(main, 36, 7, 1)
screw(main, 216, 7, 0)
screw(main, 92, 37, 0)
screw(main, 221, 85, 1)

# the shadows the keys cast on the plate (the keys are drawn by WinZik over this)
for x in range(65, 210):
    shade(main, x, 94, 0.62)
for y in range(77, 95):
    shade(main, 209, y, 0.62)
# the expand key (Image3 has no picture of its own: it is part of main.bmp)
main.alpha_composite(glyph_key(25, 18, 'updown'), (232, 76))
for x in range(233, 257):
    shade(main, x, 94, 0.62)

# the bottom (opened with that key): two knurled knobs and a lit tuning dial
knob(main, 20, 113, 10, math.radians(-130))
knob(main, 237, 113, 10, math.radians(-40))
DX0, DX1, DY0, DY1 = 42, 215, 104, 122
sunken(main, DX0, DY0, DX1 - DX0 + 1, DY1 - DY0 + 1, 'wood')
lcd(main, DX0, DY0, DX1 - DX0 + 1, DY1 - DY0 + 1)
SCALE = (230, 160, 70)
ptext(main, DX0 + 4, 106, 'FM', SCALE)
ptext(main, DX0 + 4, 116, 'AM', SCALE)
fm = [88, 92, 96, 100, 104, 108]
am = [53, 60, 70, 90, 120, 160]
sx0, sx1 = DX0 + 26, DX1 - 23
for k in range(6):
    x = sx0 + round((sx1 - sx0) * k / 5)
    s = str(fm[k])
    ptext(main, x - pwidth(s) // 2, 106, s, SCALE)
    s = str(am[k])
    ptext(main, x - pwidth(s) // 2, 117, s, SCALE)
for x in range(sx0 - 4, sx1 + 5):
    put(main, x, 113, (150, 90, 30))
    if (x - sx0) % 6 == 0:
        put(main, x, 112, SCALE)
        put(main, x, 114, SCALE)
ptext(main, DX1 - 13, 106, 'MHZ', (180, 110, 40))
ptext(main, DX1 - 13, 117, 'KHZ', (180, 110, 40))
needle = sx0 + 64
for y in range(DY0 + 1, DY1):
    put(main, needle, y, (255, 72, 32))
    put(main, needle + 1, y, (150, 40, 16))
save(main, 'main')

# --- the keys of the player ---------------------------------------------------------------------------------------
save(glyph_key(25, 17, 'shuffle', lit=False), 'hd')
save(glyph_key(25, 17, 'shuffle', lit=True), 'he')
save(glyph_key(25, 17, 'info'), 'info')
save(glyph_key(15, 15, 'minimize'), 'petit')
save(glyph_key(17, 15, 'close'), 'close')
save(glyph_key(17, 15, 'tray'), 'tray')
save(glyph_key(17, 15, 'note'), 'lyr')
for name, kind in [('barr', 'prev'), ('bpause', 'pause'), ('bplay', 'play'), ('bstop', 'stop'), ('bav', 'next'), ('bpl', 'list')]:
    save(glyph_key(25, 18, kind), name)


# --- the sliders: a slot cut in the brass, an amber scale inside, ivory caps -----------------------------------------
def slot(w, h, color_at):
    im = new(w, h)
    x0, x1 = 2, w - 3
    hline(im, x0, x1, 2, BRASS_LO)
    vline(im, x0, 2, h - 3, BRASS_LO)
    hline(im, x0, x1, h - 3, BRASS_HI)
    vline(im, x1, 2, h - 3, BRASS_HI)
    for y in range(3, h - 3):
        for x in range(x0 + 1, x1):
            put(im, x, y, (18, 9, 3))
    for x in range(x0 + 2, x1 - 1):
        c = color_at((x - x0 - 2) / (x1 - x0 - 4))
        if c is not None:
            put(im, x, 4, scale(c, 0.85))
            put(im, x, 5, c)
    return im


save(slot(116, 10, lambda t: mix((110, 50, 10), (255, 190, 80), t)), 'fbson')
save(slot(116, 10, lambda t: mix((255, 190, 80), (110, 50, 10), abs(t - .5) * 2)), 'fbbal')
fpos = slot(255, 10, lambda t: (70, 36, 10))
for k in range(0, 11):                          # the time ticks of the position slot
    x = 4 + round(246 * k / 10)
    put(fpos, x, 4, (170, 100, 34))
    put(fpos, x, 5, (210, 130, 44))
save(fpos, 'fpos')


def cap(face_lit=False):
    im = key(17, 9)
    for y in range(2, 7):
        put(im, 8, y, INK)
        put(im, 9, y, IVORY_HI)
    if face_lit:
        put(im, 8, 4, (240, 130, 20))
    return im


save(cap(), 'bson')
save(cap(), 'bbal')
save(cap(True), 'bpos')

# === the play list (mainpl.bmp, 258 x 362: the top, then the band 296..335 stretched, then the 26 px foot) ========
pl = new(258, 362, (0, 0, 0, 255))
wood(pl, (0, 0, 258, 46), 21)
wood(pl, (0, 350, 258, 362), 22)
TAB0, TAB1 = 52, 205                            # the status window: the list window goes on down between these


def list_glass(x):
    """The colour of the list's glass in column x: lit in the middle, never changing along y (the band stretches)."""
    g = max(0.0, 1 - ((x + 0.5) / 246 * 2 - 1) ** 2) ** 0.7
    return (LCD[0] + LCD_GLOW[0] * g, LCD[1] + LCD_GLOW[1] * g, LCD[2] + LCD_GLOW[2] * g)


# the list and its scroll bar: rows 47..349 are the same row over and over
for y in range(46, 350):
    put(pl, 0, y, GAP)
    put(pl, 257, y, GAP)
    put(pl, 248, y, (60, 36, 18))
    put(pl, 249, y, GAP)
    for x in range(250, 257):
        put(pl, x, y, (18, 9, 3))
    put(pl, 257, y, (128, 84, 46))
for y in range(47, 359):
    for x in range(1, 247) if y < 350 else range(TAB0, TAB1 + 1):
        put(pl, x, y, list_glass(x - 1))
vline(pl, 1, 47, 349, (10, 5, 2))
vline(pl, 247, 46, 349, (128, 84, 46))
# the top joint, the bottom edge of the list and of its status window
hline(pl, 0, 257, 45, GAP)
hline(pl, 1, 247, 46, (10, 5, 2))
hline(pl, 249, 256, 46, (10, 5, 2))
hline(pl, 0, TAB0 - 1, 350, (128, 84, 46))
hline(pl, TAB1 + 1, 257, 350, (128, 84, 46))
vline(pl, TAB0 - 1, 351, 359, GAP)
vline(pl, TAB1 + 1, 350, 359, (128, 84, 46))
hline(pl, TAB0 - 1, TAB1 + 1, 359, (128, 84, 46))
hline(pl, 1, TAB0 - 2, 351, GAP)
hline(pl, TAB1 + 2, 256, 351, GAP)
hline(pl, 1, 256, 0, WOOD_EDGE_HI)
vline(pl, 0, 0, 44, WOOD_EDGE_HI)
vline(pl, 0, 350, 361, WOOD_EDGE_HI)
vline(pl, 257, 0, 44, GAP)
vline(pl, 257, 350, 361, GAP)
hline(pl, 0, 257, 361, GAP)
# the brass name plate
PX0, PX1, PY0, PY1 = 58, 199, 33, 43
brass(pl, (PX0, PY0, PX1 + 1, PY1 + 1), 23)
hline(pl, PX0, PX1, PY0, BRASS_HI)
vline(pl, PX0, PY0, PY1, BRASS_HI)
hline(pl, PX0, PX1, PY1, BRASS_LO)
vline(pl, PX1, PY0, PY1, BRASS_LO)
for x in range(PX0 + 1, PX1 + 2):
    shade(pl, x, PY1 + 1, 0.6)
for y in range(PY0 + 1, PY1 + 2):
    shade(pl, PX1 + 1, y, 0.6)
label = 'LISTE DE LECTURE'
pengrave(pl, 129 - pwidth(label) // 2, 36, label, BRASS_INK, BRASS_HI)
screw(pl, 63, 38, 1)
screw(pl, 194, 38, 0)
# screws in the wood of the header
screw(pl, 40, 8, 0)
screw(pl, 217, 8, 1)
screw(pl, 8, 39, 1)
screw(pl, 249, 39, 0)
# the grips of the two bottom corners (16 x 12): three rows of raised brass studs
for gx0, flip in ((2, False), (242, True)):
    for j in range(3):
        for i in range(3 - j if not flip else 3 - j):
            x = (gx0 + 2 + i * 4) if not flip else (gx0 + 11 - i * 4)
            y = 357 - j * 3 + (1 if j == 2 else 0)
            if not (0 < x < 257):
                continue
            put(pl, x, y, BRASS_HI)
            put(pl, x + 1, y, BRASS)
            put(pl, x, y + 1, BRASS)
            put(pl, x + 1, y + 1, BRASS_LO)
            shade(pl, x + 2, y + 1, 0.6)
            shade(pl, x + 1, y + 2, 0.6)
            shade(pl, x + 2, y + 2, 0.6)
save(pl, 'mainpl')

# the keys of the play list
save(glyph_key(25, 17, 'plus'), 'plp')
save(glyph_key(25, 17, 'minus'), 'plm')
save(glyph_key(25, 17, 'folder'), 'plload')
save(glyph_key(25, 17, 'disk'), 'plsave')
save(glyph_key(25, 17, 'bin'), 'plrem')
save(label_key(82, 16, 'MODE EDITION', lit=False), 'pledit')
save(label_key(82, 16, 'MODE LISTE', lit=True), 'pledit2')

# the scroll bar: its slot (stretched with the list: the same row everywhere but its two ends) and its ivory thumb
track = new(8, 296)
for y in range(296):
    for x in range(7):
        put(track, x, y, (18, 9, 3))
    put(track, 7, y, (128, 84, 46))
    put(track, 3, y, (70, 36, 10))
    put(track, 4, y, (52, 26, 8))
hline(track, 0, 6, 0, (10, 5, 2))
save(track, 'posplay')
thumb = key(8, 17)
for y in (6, 8, 10):
    hline(thumb, 2, 5, y, INK)
    hline(thumb, 2, 5, y + 1, IVORY_HI)
save(thumb, 'btnplay')


# the icons of the lines: the kind of file (an amber tag), the lyrics (a pilot lamp)
def tag(s, color):
    im = new(17, 9)
    dim = scale(color, 0.55)
    hline(im, 1, 15, 0, dim)
    hline(im, 1, 15, 8, dim)
    vline(im, 0, 1, 7, dim)
    vline(im, 16, 1, 7, dim)
    ptext(im, 8 - pwidth(s) // 2 + (1 if pwidth(s) % 2 == 0 else 0), 2, s, color)
    return im


save(tag('MP3', (255, 176, 64)), 'infomp3')
save(tag('WAV', (240, 214, 130)), 'infowav')
save(tag('MID', (255, 120, 60)), 'infomid')
save(tag('CD', (236, 226, 204)), 'infocd')
for name, on in [('lyrok', True), ('lyrno', False)]:
    im = new(17, 9)
    lamp(im, 8, 4, on)
    save(im, name)

# === the compact bar (mainp.bmp, 112 x 12) and its keys (17 x 13, every 16 px) ======================================
mp = new(112, 12, (0, 0, 0, 255))
wood(mp, (0, 0, 112, 12), 31)
hline(mp, 0, 111, 0, WOOD_EDGE_HI)
hline(mp, 0, 111, 11, GAP)
save(mp, 'mainp')
for name, kind in [('arrp', 'prev'), ('pausep', 'pause'), ('playp', 'play'), ('avp', 'next'),
                   ('petitp', 'restore'), ('helpp', 'chevron'), ('lyrp', 'note')]:
    save(glyph_key(17, 13, kind), name)

# === the icon =======================================================================================================
ico = new(32, 32)
wood(ico, (1, 1, 31, 31), 41)
mask = Image.new('L', (32, 32), 0)
ImageDraw.Draw(mask).rounded_rectangle([1, 1, 30, 30], 5, fill=255)
ico.putalpha(mask)
brass(ico, (5, 6, 27, 26), 42)
hline(ico, 5, 26, 6, BRASS_HI)
vline(ico, 5, 6, 25, BRASS_HI)
hline(ico, 5, 26, 25, BRASS_LO)
vline(ico, 26, 6, 25, BRASS_LO)
sunken(ico, 9, 10, 14, 8)
lcd(ico, 9, 10, 14, 8)
for j, h in enumerate([3, 5, 4, 6, 3, 5]):
    for y in range(17 - h, 17):
        put(ico, 10 + j * 2, y, AMBER)
lamp_small(ico, 11, 22, True)
for x in range(15, 23):
    put(ico, x, 21, BRASS_LO)
    put(ico, x, 23, BRASS_LO)
save(ico, 'ico')

# === INFO.txt: the colours, as VB wrote them (&H00BBGGRR&) ===========================================================
def vb(rgb):
    r, g, b = rgb
    return '&H00%02X%02X%02X&' % (b, g, r)


colors = [(255, 182, 72),                                 # title
          AMBER_TEXT, AMBER_TEXT, AMBER_TEXT,              # volume, balance, kbps
          (255, 192, 84), (255, 192, 84), (255, 192, 84),  # hours, minutes, seconds
          (255, 176, 48), (255, 176, 48),                  # the bargraph: amber...
          (255, 126, 30), (255, 126, 30),                  # ...orange...
          (255, 66, 30), (255, 66, 30),                    # ...red
          (255, 240, 200)]                                 # the line playing
lines = ['[INF]', 'Bois & Laiton'] + [vb(c) for c in colors] + [vb((238, 162, 74)) for i in range(23)]
with open(os.path.join(OUT, 'INFO.txt'), 'w', encoding='utf-8') as f:
    f.write('\n'.join(lines) + '\n')
print('skin written in', OUT)

# VIS.txt: where WinZik draws its visualizer (the spectrum of the sound), in the opened part of the player
with open(os.path.join(OUT, 'VIS.txt'), 'w') as f:
    f.write('60 104 140 19\n')
