#! /usr/bin/python3
# vim: set filetype=python:

# opt-png: losslessly optimize PNG files

# Copyright (C) 2004-2026 by Brian Lindholm.  This file is part of the
# littleutils utility set.
#
# The opt-png utility is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 3, or (at your option) any later version.
#
# The opt-png utility is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along with
# the littleutils.  If not, see <https://www.gnu.org/licenses/>.

import concurrent.futures, getopt, os, signal, subprocess, sys, tempfile

### PREP SIGNAL HANDLER ###
interrupted = False
def handler(signum, frame):
    global interrupted
    interrupted = True
for signal_VAL in (signal.SIGHUP, signal.SIGINT, signal.SIGPIPE, signal.SIGQUIT, signal.SIGTERM):
    signal.signal(signal_VAL, handler)

### GET INPUT ARGUMENTS ###
# print online help
def usage(rc: int) -> None:
    print('opt-png 1.4.0')
    print('usage: opt-png [-f filelist] [-g(rayscale)] [-h(elp)] [-p(ipe)]')
    print('         [-q(uiet)] [-r DPI] [-t(ouch)] [-T threads] filename ...')
    sys.exit(rc)
# load list of files
def load_list_from_file() -> None:
    if not os.path.isfile(opt_f):  # abort if file does not exist
        print('opt-png error: file list %s does not exist' % opt_f, file=sys.stderr)
        sys.exit(1)
    try:
        FILE = open(opt_f, 'r')
    except:  # abort if file cannot be opened for read
        print('opt-png error: file list %s cannot be opened' % opt_f, file=sys.stderr)
        sys.exit(1)
    filelist.extend(FILE.read().splitlines())
    FILE.close()
# load list of files from stdin
def load_list_from_stdin() -> None:
    filelist.extend(sys.stdin.read().splitlines())
    sys.stdin.close()
# set defaults
filelist = []
opt_f = None   # file containing list of files to process
opt_g = False  # convert to grayscale
opt_m = 'none' # markers to copy
opt_p = False  # read list of files to process from stdin
opt_q = False  # be quiet
opt_r = None   # resolution in DPI
opt_dpm = '0'  # resolution in DPM
opt_t = False  # "touch" re-written files to preserve timestamps
opt_T = None   # requested thread-count
# get command-line options
try:
    opts, filelist = getopt.getopt(sys.argv[1:], 'f:ghm:pqrtT:', 'help')
except getopt.error as msg:
    # print help if bad opts used, then quit
    print(msg)
    usage(1)
# parse options
for o, v in opts:
    if o in ('-h', '--help'): usage(0)
    elif o == '-f': opt_f = str(v)
    elif o == '-g': opt_g = True
    elif o == '-m': opt_m = str(v)
    elif o == '-p': opt_p = True
    elif o == '-q': opt_q = True
    elif o == '-r':
        opt_r = str(v)
        opt_dpm = '%.0f' % (float(opt_r) * 10000.0 / 254.0)
    elif o == '-t': opt_t = True
    elif o == '-T': opt_T = int(v)
# load file list from file and/or stdin if requested
if opt_f != None: load_list_from_file()
if opt_p: load_list_from_stdin()
# make sure we have at least one file to process
if len(filelist) == 0:
    if (not opt_f) and (not opt_p): usage(1)
    sys.exit(0)
# remove leading './' and trim list to unique items
filelist = [x.removeprefix('./') for x in filelist]
seen = set()
unique_filelist = [x for x in filelist if x not in seen and (seen.add(x) or True)]
# pick a reasonable default if thread-count is unspecified
if opt_T == None: opt_T = max(1, min(os.cpu_count() // 2, len(unique_filelist)))

### MAIN PROGRAM ###
# preload image types
image_type = {}
def preload_image_types() -> None:
    TMPFILE = tempfile.SpooledTemporaryFile(mode='w+')
    for filename in unique_filelist: print(filename, file=TMPFILE)
    TMPFILE.seek(0)
    IMAGSIZE = subprocess.run(['imagsize', '-p'], stdin=TMPFILE, capture_output=True, text=True)
    TMPFILE.close()
    lines = IMAGSIZE.stdout.splitlines()
    for line in lines:
        field = line.split('\t')
        image_type[field[0]] = field[-1].removeprefix('type=')
# optimize the PNG file
def process_file(filename: str) -> None:
    # abort if file does not exist
    if interrupted: return
    if not os.path.isfile(filename):
        if not opt_q: print('opt-png error: %s is not a file' % filename, file=sys.stderr)
        return
    # skip zero-length files
    origsize = os.path.getsize(filename)
    if origsize == 0: return
    # skip non-PNG images
    if filename in image_type:
        if not image_type[filename].startswith('png'):
            if not opt_q: print('opt-png error: %s is not a PNG image' % filename, file=sys.stderr)
            return
    # grab initial timestamp if required
    if opt_t: timestamp = os.path.getmtime(filename)
    # grab copy of original file
    try:
        FILE = open(filename, 'rb', buffering=0)
    except:  # abort if file cannot be opened for read
        print('opt-png error: %s cannot be opened' % opt_f, file=sys.stderr)
        return
    ORIGDATA = FILE.read()
    FILE.close()
    if interrupted: return
    # initialize data structures
    TMPPNG = {}
    PNGDATA = {}
    newsize = {}
    tmpname = {}
    # run pngstrip
    idx = 'strip'
    TMPPNG[idx] = tempfile.NamedTemporaryFile(mode='w+b', buffering=0)
    args = ['pngstrip']
    if opt_r != None: args.extend(['-r', opt_dpm])
    if opt_g and (image_type[filename] != 'png-gray'): args.append('-g')
    args.extend([filename, TMPPNG[idx].name])
    subprocess.run(args, capture_output=True, text=True)
    if interrupted: return
    PNGDATA[idx] = TMPPNG[idx].read()
    newsize[idx] = len(PNGDATA[idx])
    if newsize[idx] == 0:
        if not opt_q: print('opt-png error: failed %s processing of %s' % (idx, filename), file=sys.stderr)
        return
    # run pngcrush to optimally recompress
    idx = 'crush'
    TMPPNG[idx] = tempfile.NamedTemporaryFile(mode='w+b', buffering=0)
    args = ['pngcrush', '-brute', '-l', '9']
    if opt_r != None: args.extend(['-res', opt_r])
    args.extend(['-s', TMPPNG['strip'].name, TMPPNG[idx].name])
    subprocess.run(args, capture_output=True, text=True)
    if interrupted: return
    PNGDATA[idx] = TMPPNG[idx].read()
    newsize[idx] = len(PNGDATA[idx])
    if newsize[idx] == 0:
        if not opt_q: print('opt-png error: failed %s processing of %s' % (idx, filename), file=sys.stderr)
        return
    # run optipng to optimally recompress
    idx = 'opti'
    TMPPNG[idx] = tempfile.NamedTemporaryFile(mode='w+b', delete=False, buffering=0)
    tmpname[idx] = TMPPNG[idx].name
    TMPPNG[idx].write(ORIGDATA)
    TMPPNG[idx].close()
    args = ['optipng', '-quiet', '-clobber', '-zc9', '-zm8-9', '-zs0-3', '-f0-5', TMPPNG[idx].name]
    subprocess.run(args, capture_output=True, text=True)
    if interrupted:
        os.remove(tmpname[idx])
        return
    TMPPNG[idx] = open(tmpname[idx], 'rb')
    PNGDATA[idx] = TMPPNG[idx].read()
    TMPPNG[idx].close()
    os.remove(tmpname[idx])
    newsize[idx] = len(PNGDATA[idx])
    if newsize[idx] == 0:
        if not opt_q: print('opt-png error: failed %s processing of %s' % (idx, filename), file=sys.stderr)
        return
    # if not a grayscape PNG image, attempt to color-reduce
    if image_type[filename] != 'png-gray':
        idx = 'recolor'
        TMPPNG[idx] = tempfile.NamedTemporaryFile(mode='w+b', buffering=0)
        args = ['pngrecolor', '-q', TMPPNG['strip'].name, TMPPNG[idx].name]
        subprocess.run(args, capture_output=True, text=True)
        PNGDATA[idx] = TMPPNG[idx].read()
        newsize[idx] = len(PNGDATA[idx])
        if newsize[idx] == 0:
            del PNGDATA[idx], newsize[idx]
        else:
            # run pngcrush again to optimally recompress
            idx = 'recolor-opti'
            TMPPNG[idx] = tempfile.NamedTemporaryFile(mode='w+b', buffering=0)
            args = ['pngcrush', '-brute', '-l', '9']
            if opt_r != None: args.extend(['-res', opt_r])
            args.extend(['-s', TMPPNG['recolor'].name, TMPPNG[idx].name])
            subprocess.run(args, capture_output=True, text=True)
            if interrupted: return
            PNGDATA[idx] = TMPPNG[idx].read()
            newsize[idx] = len(PNGDATA[idx])
            if newsize[idx] == 0:
                if not opt_q: print('opt-png error: failed %s processing of %s' % (idx, filename), file=sys.stderr)
                return
            # run optipng again to optimally recompress
            idx = 'recolor-crush'
            TMPPNG[idx] = tempfile.NamedTemporaryFile(mode='w+b', delete=False, buffering=0)
            tmpname[idx] = TMPPNG[idx].name
            TMPPNG[idx].write(PNGDATA['recolor'])
            TMPPNG[idx].close()
            args = ['optipng', '-quiet', '-clobber', '-zc9', '-zm8-9', '-zs0-3', '-f0-5', TMPPNG[idx].name]
            subprocess.run(args, capture_output=True, text=True)
            if interrupted:
                os.remove(tmpname[idx])
                return
            TMPPNG[idx] = open(tmpname[idx], 'rb')
            PNGDATA[idx] = TMPPNG[idx].read()
            TMPPNG[idx].close()
            os.remove(tmpname[idx])
            newsize[idx] = len(PNGDATA[idx])
            if newsize[idx] == 0:
                if not opt_q: print('opt-png error: failed %s processing of %s' % (idx, filename), file=sys.stderr)
                return
    # find smallest file of results
    if interrupted: return
    best_idx = None
    for idx in newsize:
        if best_idx == None: best_idx = idx
        elif newsize[idx] < newsize[best_idx]: best_idx = idx
    # use best result if smaller
    if newsize[best_idx] < origsize:
        try:
            FILE = open(filename, 'wb')
        except:  # abort if file cannot be opened for write
            print('opt-png error: %s cannot be opened for write' % opt_f, file=sys.stderr)
            return
        FILE.write(PNGDATA[best_idx])
        FILE.close()
        if not opt_q: print('%s: [%s] %d vs. %d' % (filename, best_idx, origsize, newsize[best_idx]))
        if opt_t: os.utime(filename, (timestamp, timestamp))
    elif not opt_q:
        print('%s: unchanged' % filename)

# process files
preload_image_types()
if opt_T < 2:
    for filename in unique_filelist:
        if interrupted: break
        process_file(filename)
else:
    with concurrent.futures.ThreadPoolExecutor(max_workers=opt_T) as executor:
        executor.map(process_file, unique_filelist)
