# --------------------------------------------------------------------------- #
# $Id: plsetup.py,v 1.19 2004/01/19 21:12:22 pandr Exp $
# --------------------------------------------------------------------------- #

# --------------------------------------------------------------------------- #
# Import stuff

import libpointless, sys
from libpointless import VERSION, PKGDATADIR, SYSCONFDIR, LOCALEDIR
from string import *
import getopt, sys, os, string, re
import ConfigParser
from pllshared import *

# Import pointless options and their default settings
import ploptions

# Import Log module
import pllog

# Import filehandler
import plfiles

# Import export merger
import merger
from merger import ExportMerger

# --------------------------------------------------------------------------- #
# Globals

pllpath = PKGDATADIR+"/fonts"
pllpath += ":"+PKGDATADIR+"/templates/html"
pllpath += ":"+PKGDATADIR+"/templates/xml"
geometry = None
merger = None
me = None

# --------------------------------------------------------------------------- #
# Usage

def usage():
	global me
	print gt('Usage:' )+me+gt(' <FLAG> | [OPTION] <inputfile>')
	if me=='pointless':
		print gt('Flags:')
		print gt('  -b, --banner <text>              specify one-line banner slide')
		print gt('  -h, --help                       display this help')
		print (gt('      --resolutions                print list of possible ')+
			gt('resolutions and exit'))
		print gt('  -V, --version                    output version')
		print gt('Options:')
		print gt('  -a, --aspect w:h                 set aspect ratio (default 4:3)')
		print gt('  -d, --debug                      debug output')
		print gt('      --export <format>            export slideshow merged into templates')
		print gt('      --exportdir <dir>            export directory')
		print gt('  -f <configfile>                  specify configfile')
		print gt('      --firsttemplatefile <file>   templatefile for first screenshot')
		print gt('      --fullscreen                 start in fullscreen mode')
		print gt('  -g, --geometry <geometry-string> specify geometry of window')
		print gt('  -I <path>                        specify additional search path')
		print gt('      --indexfile <file>           templatefile for index')
		print gt('      --lasttemplatefile <file>    templatefile for last screenshot')
		print gt('      --packtgz                    creates selfcontained file foo.pll.tgz')
		print gt('      --powersave                  no fancy slide-transitions')
		print gt('      --resolution <res>           fullscreen at specific resolution')
		print gt('      --templatefile <file>        templatefile for screenshots')
		print gt('  -v, --verbose                    verbose output')
	elif me=='xml2pll':
		print gt('Flags:')
		print gt('  -h, --help                       display this help')
		print gt('  -V, --version                    output version')
		print gt('Options:')
		print gt('  -v, --verbose                    verbose output')
		print gt('      --xsltemplate <file>         templatefile for XML translations')
	else:
		print gt('Internal error - please report to pointless-devel@sourceforge.net')
	sys.exit()

# --------------------------------------------------------------------------- #
# The options handling

def parse_env():
	global pllpath
	pllinput = ""
	from os import environ
	if environ.has_key( 'PLLINPUT'):
		pllinput = environ['PLLINPUT']
	## environment has higher precedence than PKGDATADIR from the installation
	if pllinput:
		pllpath = os.path.expanduser(pllinput) + ":" + pllpath
	home_pointless = ""
	if environ.has_key('HOME'):
		home_pointless = environ['HOME']+"/.pointless/"
	else:
		home_pointless = os.path.expanduser('~/.pointless/')
	plfiles.set_path(pllpath)
	plfiles.set_home(home_pointless)

def parse_rc():
	global pllpath 
	config = ConfigParser.ConfigParser()
	configfiles = []
	if ploptions.configfile:
		# A configfile was specified on cmd line
		if not os.path.isfile(ploptions.configfile):
			raise RuntimeError, "Config file '%s' does not exist."%ploptions.configfile
		configfiles = [ploptions.configfile]
	else:
		rc = plfiles.get_home()+"/pointlessrc"
		configfiles = [SYSCONFDIR+'/pointlessrc', rc]
	config.read(configfiles)
    ## parse section DEFAULT
	try:
		p = config.get('DEFAULT','path')
		plfiles.add_to_path(p)
	except: pass
	try:
		loglevelfound = config.get('DEFAULT','loglevel')
		if (loglevelfound == "DEBUG"):
			ploptions.loglevel = 3
		elif (loglevelfound == "INFO"):
			ploptions.loglevel = 2
	except: pass
	try:
		ploptions.fullscreen = config.get('DEFAULT','fullscreen')
	except: pass
	try:
		ploptions.default_fontname = config.get('DEFAULT','default_fontname')
	except: pass
	try:
		ploptions.default_fontsize = int(config.get('DEFAULT','default_fontsize'))
	except: pass
	try:
		ploptions.tmpwork = config.get('DEFAULT','tmpwork')
	except: pass
	try:
		ploptions.exportdir = config.get('DEFAULT','exportdir')
	except: pass
	## parse section WINDOW
	try:
		ploptions.geomheight = config.get('WINDOW','height')
	except: pass
	try:
		ploptions.geomwidth = config.get('WINDOW','width')
	except: pass
	try:
		ploptions.geomxoffset = config.get('WINDOW','xoffset')
	except: pass
	try:
		ploptions.geomyoffset = config.get('WINDOW','yoffset')
	except: pass
	## parse section EXPORT
	try:
		ploptions.template_file_first = config.get('EXPORT','firsttemplatefile')
	except: pass
	try:
		ploptions.template_file_last = config.get('EXPORT','lasttemplatefile')
	except: pass
	try:
		ploptions.template_file = config.get('EXPORT','templatefile')
	except: pass
	try:
		ploptions.index_file = config.get('EXPORT','indexfile')
	except: pass
	try:
		ploptions.template = config.get('DEFAULT','template_xsl')
	except: pass

def parse_cmdline_early(opts, args):
	for o, a in opts:
		if o in ('-f',):
			ploptions.configfile = a

def parse_cmdline(opts, args):
	global pllpath
	if me=='pointless':
		for o, a in opts:
			if o in ("-a", "--aspect"):
				as = a.split(':')
				if len(as) != 2:
					print gt("Ignoring invalid aspect '%s'" % a)
				else:
					ploptions.aspect = float(as[0])/float(as[1])
					print gt("Setting aspect to: %f" % ploptions.aspect)
			if o in ("-d", "--debug"):
				ploptions.loglevel = 3
			if o in ("-b", "--banner"):
				ploptions.banner = '=slide\n\n=center '+a+'\n'
			if o in ("--export", ):
				if (a == "raw") or (a == "html") or (a == "ps") or (a == "pdf"):
					ploptions.export = a
					if a == "raw":
						ploptions.exportraw = 1
					if a == "ps":
						ploptions.exportps = 1
					if a == "pdf":
						ploptions.exportpdf = 1
				else:
					print gt("Ignoring invalid exportformat '%s'" % a)
			if o in ("--exportdir", ):
				ploptions.exportdir = a
			if o in ("--firsttemplatefile", ):
				ploptions.template_file_first = a
			if o in ("--fullscreen", ):
				ploptions.fullscreen = 1
			if o in ("-g", "--geometry"):
				ploptions.geometryStr = a
			if o in ("-h", "--help"):
				usage()
				sys.exit()
			if o in ("--indexfile", ):
				ploptions.index_file = a
			if o in ("-I", ):
				plfiles.add_to_path(a)
			if o in ("--lasttemplatefile", ):
				ploptions.template_file_last = a
			if o in ('--packtgz',):
				ploptions.packtgz = 1
			if o in ('--powersave',):
				ploptions.powersave = 1
			if o in ("--resolution", ):
				## --resolution imposes fullscreen and overwrites any geometry setting
				ploptions.wanted_resolution = a
				ploptions.fullscreen = 1
				ploptions.geometryStr = ploptions.wanted_resolution
			if o in ("--resolutions", ):
				ploptions.print_resolutions = 1
				ploptions.banner = 1;
			if o in ("--templatefile", ):
				ploptions.template_file = a
			if o in ("-v", "--verbose"):
				ploptions.loglevel = 2
			if o in ("-V", "--version"):
				print gt('Search path:\n\t')+"\n\t".join(plfiles.get_path_list())
				sys.exit()
		if ploptions.banner: return
	elif me=='xml2pll':
		for o, a in opts:
			if o in ("-v", "--verbose"):
				ploptions.loglevel = 2
			if o in ("-V", "--version"):
				print gt('Search path:\n\t')+"\n\t".join(plfiles.get_path_list())
				sys.exit()
			if o in ("-h", "--help"):
				usage()
				sys.exit()
	else:
		print gt('Internal error - please report to pointless-devel@sourceforge.net')
		sys.exit()
	if len(args) == 1:
		ploptions.inputfile = args[0]
		if ploptions.inputfile == "-":
			f = ploptions.inputfile
		else:
			f = plfiles.find_file(ploptions.inputfile)
		if not f:
				sys.stderr.write(gt('File ')+ploptions.inputfile+gt(' does not exits\n'))
				sys.stderr.write(gt('option -V gives information about the search path\n'))
				sys.exit()
		else:
			ploptions.inputfile = f
		plfiles.add_to_path( os.path.dirname(ploptions.inputfile) )
	else:
		usage()

def setup_resources():
	# Geometry object
	global geometry
	if ploptions.geometryStr is None:
		ploptions.geometryStr = ("%ix%i+%i+%i"%
			(int(ploptions.geomwidth),
			 int(ploptions.geomheight),
			 int(ploptions.geomxoffset),
			 int(ploptions.geomyoffset)))
	try:
		geometry = Geometry(ploptions.geometryStr)
	except:
		sys.stderr.write(gt('Invalid geometry specification: ')+ploptions.geometryStr+"\n")
		sys.exit()
	# Log level
	pllog.set_loglevel(ploptions.loglevel)
	# Export
	global merger
	if ploptions.export:
		if (not ploptions.exportraw) and (not ploptions.template_file):
			pllog.abort("Templatefile unspecified")
		exportbasename  = os.path.basename(ploptions.inputfile)
		exportbasename = "".join(exportbasename.split('.')[:-1]) # strip '.pll'
		if not ploptions.template_file_first:
			ploptions.template_file_first = ploptions.template_file
		if not ploptions.template_file_last:
			ploptions.template_file_last = ploptions.template_file
		ploptions.index_file = \
			plfiles.find_file(ploptions.index_file, include_cwd = 0)
		ploptions.template_file = \
			plfiles.find_file(ploptions.template_file, include_cwd = 0)
		ploptions.template_file_first = \
			plfiles.find_file(ploptions.template_file_first, include_cwd = 0)
		ploptions.template_file_last = \
			plfiles.find_file(ploptions.template_file_last, include_cwd = 0)
		if not ploptions.index_file:
			pllog.abort('Index template not found')
		if not ploptions.template_file:
			pllog.abort('Template not found')
		if not ploptions.template_file_first:
			pllog.abort('First template not found')
		if not ploptions.template_file_last:
			pllog.abort('Last template not found')
		merger = ExportMerger(ploptions.template_file, \
								ploptions.template_file_first, \
							  ploptions.template_file_last, \
							  ploptions.index_file, \
							  ploptions.exportdir, \
							  exportbasename, \
								ploptions.export)


class Geometry:
	def __init__(self, geometrystring):
		## proper default
		self.width  = 0
		self.height = 0
		## offset '-1' corr. to '-' whereas '+1' corr. to '+'
		self.xoffset = +1 
		self.yoffset = +1 
		pattern = "^([0-9]+x[0-9]+)?((\+|\-)0(((\+|\-)0)?))?$"
		if not re.search(pattern, geometrystring):
			sys.stderr.write(gt('geometry-string must match \
			^([0-9]+x[0-9]+)?((\+|\-)0(((\+|\-)0)?))?$\n'))
			raise RuntimeError, "Invalid geometry string"
		dimension = "^([0-9]+)x([0-9]+)"
		matchobj = re.search(dimension, geometrystring)
		if matchobj:
			self.width  = int(matchobj.group(1))
			self.height = int(matchobj.group(2))
		orientation = "(\+|\-)0(\+|\-)0$"
		matchobj = re.search(orientation, geometrystring)
		if matchobj:
			if matchobj.group(1)=='-':
				self.xoffset = int(-1)
			if matchobj.group(2)=='-':
				self.yoffset = int(-1)
	def __str__(self):
		return "Geometry: %ix%i%+i%+i" % (self.width, self.height, self.xoffset, self.yoffset)
	def get_height(self):
		return self.height 
	def get_width(self):
		return self.width 
	def get_placement(self):
		return (0, self.xoffset, 0, self.yoffset)

# --------------------------------------------------------------------------- #

def process_args():
	global me 
	me = os.path.basename(sys.argv[0])
	if len(sys.argv) == 1:
		## special case. our sense of humor is lame! :)
		sys.stderr.write("This is %s. Try --help\n" % me);
		sys.exit()
	## start
	sys.stderr.write("This is %s, Version %s\n" % (me,VERSION))
	## handle environment variables, resources and cmdline options
	parse_env()
	if me=='pointless':
		try:
			opts, args = getopt.getopt(sys.argv[1:], "a:dD:eb:f:g:hI:vVx",
			["aspect=", "banner=", "debug","exportdir=","export=",
			"firsttemplatefile=","fullscreen","geometry=","help",
			"indexfile=","lasttemplatefile=","packtgz","powersave",
			"resolution=", "resolutions", "templatefile=",
			"verbose","version","xml"])
		except getopt.GetoptError:
			usage()
	elif me=='xml2pll':
		try:
			opts, args = getopt.getopt(sys.argv[1:], "h:vVx",
			["help","verbose","version","xml"])
		except getopt.GetoptError:
			usage()
	else:
		print gt('Internal error - please report to pointless-devel@sourceforge.net')
		sys.exit()
	parse_cmdline_early(opts, args)
	parse_rc()
	parse_cmdline(opts, args)
	setup_resources()

# --------------------------------------------------------------------------- #

