#!/usr/bin/env python3
"""Reads each favicon.ico: lists frame sizes, and for the 16 px frame prints the share of pixels with alpha >= 128 and the
bounding box of those pixels. With --montage <out.png> it also writes a picture of the 16 px frames enlarged 16x (nearest neighbour). Without --montage nothing is written.
Usage: python3 ico-check.py [--montage <out.png>] <favicon.ico> [<favicon.ico> ...]"""
import sys, os
from PIL import Image, ImageDraw
USAGE = 'usage: ico-check.py [--montage <out.png>] <favicon.ico> ...'
args, out = sys.argv[1:], None
if args[:1] == ['--montage']:
    if len(args) < 3: sys.exit(USAGE)
    out, args = args[1], args[2:]
if not args: sys.exit(USAGE)
files = args
if out and (not out.lower().endswith('.png') or out in files): sys.exit('refusing to write the montage over an input or to a non-.png name: ' + out)
tiles = []
for f in files:
    if not os.path.isfile(f) or os.path.getsize(f) == 0: print(f, '=> ERROR: missing or empty file'); continue
    try: ico = Image.open(f)
    except Exception as e: print(f, '=> ERROR: not an ICO file (%s)' % type(e).__name__); continue
    if ico.format != 'ICO': print(f, '=> ERROR: not an ICO file (it is a %s picture with an .ico name)' % ico.format); continue
    sizes = sorted(ico.info.get('sizes', []))
    fr = ico.ico.getimage((16, 16)).convert('RGBA') if (16, 16) in sizes else None
    if fr is None: print(f, 'sizes', sizes, '=> no 16 px frame'); continue
    a = fr.getchannel('A'); px = list(a.tobytes()); solid = sum(1 for v in px if v >= 128)
    bb = a.point(lambda v: 255 if v >= 128 else 0).getbbox()
    print('%s sizes %s | 16 px: %d of 256 pixels alpha>=128 (%.0f%%), box %s' % (f, sizes, solid, 100 * solid / 256, bb))
    tiles.append((os.path.basename(os.path.dirname(f)) or f, fr))
if out and tiles:
    T = 256; pad = 12
    sheet = Image.new('RGB', (len(tiles) * (T + pad) + pad, T + 2 * pad), 'white')
    for i, (n, fr) in enumerate(tiles):
        big = fr.resize((T, T), Image.NEAREST); bg = Image.new('RGBA', (T, T), (230, 230, 230, 255)); bg.alpha_composite(big)
        sheet.paste(bg.convert('RGB'), (pad + i * (T + pad), pad))
    sheet.save(out)
