#!/usr/bin/python
"""
Extension to call (La)TeX and view PDF
written by Henning Jacobs <henning@jacobs1.de>, 2003
"""
#  Copyright (C) 2004  Henning Jacobs <henning@srcco.de>
#
#  This program 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 2 of the License, or
#  (at your option) any later version.
#
#  $Id: texwrapper.py 82 2004-07-11 13:01:44Z henning $


import sys
import os
import tkMessageBox
from Tkinter import *   
import ToolTip

class OutputWindow(Toplevel):
    def __init__(self, root, title="OutputWindow"):
        Toplevel.__init__(self, root)
        self.title(title)
        self.vbar = vbar = Scrollbar(self, name='vbar')
        self.text_frame = text_frame = Frame(self)           
        self.text = text = Text(text_frame, wrap="none", background="#bbbbbb",
            foreground="black")
        ToolTip.ToolTip(text, 'There were errors while running LaTeX.\n'+
            'Errors are shown in red.')
        text.tag_configure('error', foreground='#ee0000')
        vbar['command'] = text.yview
        vbar.pack(side=RIGHT, fill=Y)
        text['yscrollcommand'] = vbar.set
        text_frame.pack(side=LEFT, fill=BOTH, expand=1)
        text.pack(side=TOP, fill=BOTH, expand=1)
        text.focus_set()
    def appendtext(self, text, tags=None):
        self.text.insert(END, text, tags)
        self.text.see(END)
        self.text.update()

def view_pdf(texfilename):
    if not texfilename:
        return
    pdfname = os.path.splitext(texfilename)[0] + ".pdf"    
    if not os.access(pdfname, os.R_OK):    
        tkMessageBox.showerror("Error", "File not found: '%s'\n Run TeX first!" % pdfname)
    if sys.platform == "win32":
        # Explorer File-Handling:
        os.startfile(pdfname)    
    else:
        os.spawnv(os.P_NOWAIT, '/usr/bin/xpdf', ['xpdf', pdfname])   

def run_pdflatex(texfilename):
    if not texfilename:
        return

    oldpwd = os.getcwd()
    # TODO: Not working when texfilename includes space characters!
    cmd = 'pdflatex -interaction=nonstopmode %s' % texfilename
    os.chdir(os.path.dirname(texfilename))
    # Check whether .aux and .log files were there before we came:
    root, ext = os.path.splitext(texfilename)
    isOurAuxFile = not os.access(root+'.aux', os.F_OK)
    isOurLogFile = not os.access(root+'.log', os.F_OK)
    # Now run pdfLaTeX:
    pipe = os.popen(cmd, 'r')
    outlines = pipe.readlines()
    pipe.close()
    showoutwin = False
    for line in outlines:
        if line[:1] == '!':
            showoutwin = True
            break
    # Restore Working Directory:
    os.chdir(oldpwd)
    pdfname = os.path.splitext(texfilename)[0] + ".pdf"    
    if os.access(pdfname, os.R_OK):
        # PDF seems to be written -> OK
        # Delete .aux and .log files if they were created by us:
        if isOurAuxFile: os.unlink(root+'.aux')
        if isOurLogFile: os.unlink(root+'.log')    
    else:
        showoutwin = True
    if showoutwin:
        # There were Errors while running pdfLaTeX -> show Output Log:
        outwin = OutputWindow(None,
            title="TeX Output from %s" % os.path.basename(texfilename))
        outwin.appendtext("PyCoCuMa: Calling '%s'\n" % cmd)
        for line in outlines:
            if line[:1] == '!':
                outwin.appendtext(line, 'error')
            else:    
                outwin.appendtext(line)

