"""
    MoinMoin - Processor for a LaTeX syntax

    @copyright: 2002 by Won-kyu Park <wkpark@kldp.org>
    @copyright: 2003 by Benny Siegert (added config.latex_header)
    Modified:
    2004-03-22 R.Bauer replaced config. by config_ and imported AttachFile
    @license: GNU GPL, see COPYING for details.
    2004-04-09 imported patch from Daniel Hottinger (pagestyle{empty}, -E switch of dvips, input of latex text replaced)
    2004-04-09 R.Bauer improvement in speed, because only if the image name is different a new image must be created

    2004-08-06 Yaroslav Bulatov modified to work under Cygwin (only)
"""

Dependencies = []

import sys, os, re, sha
from MoinMoin.Page import Page
from MoinMoin.action import AttachFile

config_external_latex = "latex"
config_external_convert = "convert"
config_external_dvips = "dvips"
config_umask = 022

config_latex_cache_dir = "./data"
config_latex_cache_url = "./data"
config_latex_header = "\documentclass[a4paper,12pt]{article}\n\pagestyle{empty}"
config_latex_vartmp_dir = "./data/tmp"

# Executes command using cygwin, captures output
external_shell = 'C:/cygwin/bin/tcsh.exe -c '
def ex(cmd):
    dummy, out = os.popen4(external_shell+"'"+cmd+"'")
    if 0:
        import time
        debug = open(r'G:\public_html\moin\ai\data\tmp\debug.txt', 'a')
        print >>debug, time.asctime()
        print >>debug, cmd
        for line in out:
            print >>debug, line
        dummy.close()
        out.close()
        debug.close()

def process(request, formatter, lines):
    if not config_latex_cache_dir:
    	return
    if lines[0].strip() == "#!latex":
        del lines[0]

    texstr = '\n'.join(lines).strip()

    imgname = re.sub('\s+', ' ', texstr)
    imgname = sha.new(imgname).hexdigest()

    attdir = config_latex_cache_dir + "/LaTex/attachments"
    atturl = config_latex_cache_url + "/LaTex/attachments"
    outpath = "%s/%s.gif" % (attdir, imgname)
    outurl = "%s/%s.gif" % (atturl, imgname)
    if not os.path.isdir(attdir):
        os.makedirs(attdir, 0775)

    pagename=formatter.page.page_name

    url=AttachFile.getAttachUrl(pagename,imgname+'.png',request)
    attach_dir=AttachFile.getAttachDir(pagename,create=1)

    if not os.path.isfile(attach_dir+'/'+imgname+'.png'):
      if not os.path.exists(outpath):
        vartmp = config_latex_vartmp_dir
        data = open("%s/%s.tex" % (vartmp, imgname), "w")

        data.write('%s\n\\begin{document}\n%s\n\\end{document}' % (config_latex_header, texstr))
        data.close()

        cmd = r"cd %(vartmp)s;%(latex)s %(options)s %(tex)s" % {
           "latex": config_external_latex,
           "vartmp": vartmp,
           "options": '-interaction=batchmode',
           "tex": imgname
        }
	os.umask(config_umask)
        ex(cmd)

        cmd = r"cd %(vartmp)s; %(dvips)s -E %(imgname)s.dvi -o %(imgname)s.ps" % {
            "dvips": config_external_dvips,
            "vartmp": vartmp,
            "imgname": imgname,
            }
        ex(cmd)

        # Convert ps file into true color png
        cmd = r"gs -q -dBATCH -dNOPAUSE -dNOPLATFONTS -sDEVICE=png16m -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -dMaxBitmap=50000000 -r120x120 -sOutputFile=%(pngfile)s -- %(psfile)s -c quit"%{
            "pngfile": vartmp+"/"+imgname+".png",
            "psfile": vartmp+"/"+imgname+".ps"
            }
        ex(cmd)

        # convert -crop 0x0 -density 300x300 a.png a.gif

        # Crop and convert png into gif
        cmd = r"%(convert)s -crop 0x0 %(inpath)s %(outpath)s" % {
            "convert": config_external_convert,
            "vartmp": vartmp,
            "outpath": attach_dir.replace('\\','/')+'/'+imgname+'.png',
            "inpath": vartmp+"/"+imgname+".png"
            }
        ex(cmd)

        cmd = r"rm -f %(vartmp)s/%(imgname)s.*" % {
            "vartmp": vartmp,
            "imgname": imgname,
            }
        ex(cmd)

    request.write(formatter.image(src="%s" % url, alt=texstr, align='absmiddle'))


