#!/usr/bin/python
#
# AgaView.py 0.4 - Oct 9 1996
#
#   Views `any' picture using ppmtoagafb
#
#   Chris Lawrence <lawrencc@debian.org>
#
# This is free software, subject to the terms of the GNU General Public License
# See /usr/doc/copyright/GPL on a Debian GNU/Linux system for your lack of
# warranty and specific licensing terms.
#
# . No filter is used for PPM and PGM images (duh)
# . 'djpeg' is used for JFIF images
# . You can use 'pngtopnm' if you've compiled it for PNG images
# . NetPBM utils are used for GIF and ILBM images
# . 'convert' (from ImageMagick) is used for everything else
#
# To use this, you must have the NetPBM package.
# To view JFIF images, you'll need 'djpeg' from the Independent JPEG Group
# To view PNG images, you'll need 'pngtoppm' from the PNG developers
# To view odd image formats, you'll need 'convert' from the ImageMagick
#   or you'll need to change identify_file to identify them and convert_file
#   to convert them to pgm or ppm.
#
# Changes since third release: (Sep 26)
# . Using file extensions in identify_file (if there's an extension,
#     assume it is valid)
#
# Changes since second release: (Sep 21)
# . Using new stdin pipe in ppmtoagafb for better throughput
# . Doesn't scale if the image will fit on the display without scaling
#
# Changes since first release: (Sep 16)
# . Added automagic scaling of image (via pnmscale)
#   Set WIDTH and HEIGHT equal to the size of your default console
# . Fixed filtering for PPM/PGM images
# . Added filter for pbm->pgm

VERBOSE   = 0 # Set to 1 for informative messages
NOCLEANUP = 0 # Set to 1 to keep the generated files around

WIDTH   = 640 # Width of fb0current
HEIGHT  = 480 # Height of fb0current

OPTIONS = '--delay 10 --center' # Supply any options to ppmtoagafb here

JPEG_OPTS = '-pnm' # Any options to djpeg go here
                   # '-fast' might be nice here for faster previews

import sys, os, regex, time, string

def debug_message(msg):
        if VERBOSE:
                print msg

def identify_file(filename):
        fields = string.splitfields(filename,'.')
        if len(fields) >= 2: 
                # Our filename has at least one extension
                ext = fields[-1]
                
                debug_message('Using extension '+ext+' for identity.')

                if ext == 'jpg' or ext == 'jpeg':
                        return 'JFIF'
                elif ext == 'ilbm' or ext == 'lbm' or ext == 'iff':
                        return 'ILBM'
                elif ext:
                        return string.upper(ext)

        fd = os.popen('file %s' % filename)
        typestring = fd.readline()
        fd.close()

        typestring = string.strip(typestring)
        debug_message(typestring)

        if regex.search('JFIF', typestring) != -1:
                return 'JFIF'
        elif regex.search('PPM', typestring) != -1:
                return 'PPM'
        elif regex.search('PGM', typestring) != -1:
                return 'PGM'
        elif regex.search('PBM', typestring) != -1:
                return 'PBM'
        elif regex.search('PNG', typestring) != -1:
                return 'PNG'
        elif regex.search('GIF', typestring) != -1:
                return 'GIF'
        elif regex.search('ILBM', typestring) != -1:
                return 'ILBM'

        # The rest of these, we run 'convert' on so don't bother
        # identifying them

        return 'Unidentified'

def convert_file(filename):
        type = identify_file(filename)
        debug_message('Detected type: '+type)

        if type == 'PPM' or type == 'PGM' or type == 'PBM':
                return ''
        
        # The extension tells convert to create a PPM file
        # NB: Python does have a tempfile module, but it doesn't guarantee
        #     any extension.
        tmpnam = '/tmp/agaview.%d.%d.ppm' % (time.time(), os.getpid())
        
        if type == 'JFIF':
                os.system('djpeg %s %s > %s' %
                          (JPEG_OPTS, filename, tmpnam))
        elif type == 'PNG':
                os.system('pngtopnm %s > %s' % (filename, tmpnam) )
        elif type == 'GIF':
                os.system('giftopnm %s > %s' % (filename, tmpnam) )
        elif type == 'ILBM':
                os.system('ilbmtoppm %s > %s' % (filename, tmpnam) )
        else:
                os.system('convert %s %s' % (filename, tmpnam))

        return tmpnam

def scale_file(oldtmpnam):
        fp = os.popen('pnmfile %s' % oldtmpnam)
        info = string.split(fp.read())
        fp.close()

        width = string.atoi(info[3])
        height = string.atoi(info[5])

        if width <= WIDTH and height <= HEIGHT:
                debug_message('Not scaling %s: %d x %d' % (oldtmpnam, width,
                                                           height))
                x = open(oldtmpnam)
        else:
                debug_message('Scaling '+oldtmpnam)
                x = os.popen('pnmscale -xysize %d %d %s' % (WIDTH, HEIGHT,
                                                            oldtmpnam))
        return x

def clean_up_converted_file(tmpnam):
        debug_message('Removing '+tmpnam)

        if not NOCLEANUP:
                os.unlink(tmpnam)

def show_file(filename, fp):
        tmpfile = convert_file(filename)

        if tmpfile != '':
                x = scale_file(tmpfile)
        else:
                x = scale_file(filename)

        txt = x.read()
        if txt:
                fp.write(txt)
                fp.flush()
        x.close()

        if tmpfile != '':
                clean_up_converted_file(tmpfile)

def main():
        ret = 0

        tmpnam = '/tmp/agaview.%d.%d.ppm' % (time.time(), os.getpid())
        
        if len(sys.argv) < 2 or sys.argv[1] == '-h' or sys.argv[1] == '--help':
                print 'Usage: agaview [--grayscale] file1 [file2 ... filen]'
                sys.exit(1)
        
        if sys.argv[1] == "--grayscale" or sys.argv[1] == "-g":
                grayscale = 1
                start = 2
        else:
                grayscale = 0
                start = 1
        
        if grayscale:
                fp = os.popen('ppmtoagafb -g %s -' % OPTIONS, 'w')
        else:
                fp = os.popen('ppmtoagafb %s -' % OPTIONS, 'w')

        if not fp:
                print 'agaview: unable to open pipe to ppmtoagafb.'
                sys.exit(1)


        for x in sys.argv[start:]:
                if os.path.exists(x):
                        show_file(x, fp)
                else:
                        print 'File does not exist:', x
                        ret = 1
        
        fp.flush()
        fp.close()

        if ret:
                print 'agaview: not completely successful'

        sys.exit(ret)

main()
