Package common :: Module latex
[hide private]
[frames] | no frames]

Source Code for Module common.latex

  1  # -*- coding:utf-8 -*- 
  2  ## src/common/latex.py 
  3  ## 
  4  ## Copyright (C) 2005 Norman Rasmussen <norman AT rasmussen.co.za> 
  5  ## Copyright (C) 2005-2006 Alex Mauer <hawke AT hawkesnest.net> 
  6  ##                         Travis Shirk <travis AT pobox.com> 
  7  ## Copyright (C) 2005-2007 Nikos Kouremenos <kourem AT gmail.com> 
  8  ## Copyright (C) 2005-2010 Yann Leboulanger <asterix AT lagaule.org> 
  9  ## Copyright (C) 2006 Dimitur Kirov <dkirov AT gmail.com> 
 10  ## Copyright (C) 2006-2008 Jean-Marie Traissard <jim AT lapin.org> 
 11  ## Copyright (C) 2008 Jonathan Schleifer <js-gajim AT webkeks.org> 
 12  ##                    Julien Pivotto <roidelapluie AT gmail.com> 
 13  ##                    Stephan Erb <steve-e AT h3c.de> 
 14  ## 
 15  ## This file is part of Gajim. 
 16  ## 
 17  ## Gajim is free software; you can redistribute it and/or modify 
 18  ## it under the terms of the GNU General Public License as published 
 19  ## by the Free Software Foundation; version 3 only. 
 20  ## 
 21  ## Gajim is distributed in the hope that it will be useful, 
 22  ## but WITHOUT ANY WARRANTY; without even the implied warranty of 
 23  ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
 24  ## GNU General Public License for more details. 
 25  ## 
 26  ## You should have received a copy of the GNU General Public License 
 27  ## along with Gajim. If not, see <http://www.gnu.org/licenses/>. 
 28  ## 
 29   
 30  import os 
 31  import random 
 32  from tempfile import gettempdir 
 33  from subprocess import Popen, PIPE 
 34   
 35  import logging 
 36  log = logging.getLogger('gajim.c.latex') 
 37   
 38  import gajim 
 39  from exceptions import LatexError 
 40  import helpers 
 41   
 42  # some latex commands are really bad 
 43  blacklist = ['\\def', '\\let', '\\futurelet', 
 44          '\\newcommand', '\\renewcomment', '\\else', '\\fi', '\\write', 
 45          '\\input', '\\include', '\\chardef', '\\catcode', '\\makeatletter', 
 46          '\\noexpand', '\\toksdef', '\\every', '\\errhelp', '\\errorstopmode', 
 47          '\\scrollmode', '\\nonstopmode', '\\batchmode', '\\read', '\\csname', 
 48          '\\newhelp', '\\relax', '\\afterground', '\\afterassignment', 
 49          '\\expandafter', '\\noexpand', '\\special', '\\command', '\\loop', 
 50          '\\repeat', '\\toks', '\\output', '\\line', '\\mathcode', '\\name', 
 51          '\\item', '\\section', '\\mbox', '\\DeclareRobustCommand', '\\[', 
 52          '\\]'] 
 53  # True if the string matches the blacklist 
54 -def check_blacklist(str_):
55 for word in blacklist: 56 if word in str_: 57 return True 58 return False
59
60 -def get_tmpfile_name():
61 random.seed() 62 int_ = random.randint(0, 100) 63 return os.path.join(gettempdir(), 'gajimtex_' + int_.__str__())
64
65 -def write_latex(filename, str_):
66 texstr = '\\documentclass[12pt]{article}\\usepackage[dvips]{graphicx}' 67 texstr += '\\usepackage{amsmath}\\usepackage{amssymb}' 68 texstr += '\\pagestyle{empty}' 69 texstr += '\\begin{document}\\begin{large}\\begin{gather*}' 70 texstr += str_ 71 texstr += '\\end{gather*}\\end{large}\\end{document}' 72 73 file_ = open(filename, "w+") 74 file_.write(texstr) 75 file_.flush() 76 file_.close()
77 78 # a wrapper for Popen so that no window gets opened on Windows 79 # (i think this is the reason we're using Popen rather than just system()) 80 # stdout goes to a pipe so that it can be read
81 -def popen_nt_friendly(command):
82 if os.name == 'nt': 83 # CREATE_NO_WINDOW 84 return Popen(command, creationflags=0x08000000, cwd=gettempdir(), stdout=PIPE) 85 else: 86 return Popen(command, cwd=gettempdir(), stdout=PIPE)
87
88 -def check_for_latex_support():
89 """ 90 Check if latex is available and if it can create a picture 91 """ 92 try: 93 filename = latex_to_image("test") 94 if filename: 95 # we have a file, conversion succeeded 96 os.remove(filename) 97 return True 98 return False 99 except LatexError: 100 return False
101
102 -def try_run(argv):
103 try: 104 p = popen_nt_friendly(argv) 105 out = p.communicate()[0] 106 log.info(out) 107 return p.wait() 108 except Exception, e: 109 return _('Error executing "%(command)s": %(error)s') % { 110 'command': " ".join(argv), 111 'error': helpers.decode_string(str(e))}
112 113
114 -def latex_to_image(str_):
115 result = None 116 exitcode = 0 117 118 try: 119 bg_str, fg_str = gajim.interface.get_bg_fg_colors() 120 except: 121 # interface may not be available when we test latext at startup 122 bg_str, fg_str = 'rgb 1.0 1.0 1.0', 'rgb 0.0 0.0 0.0' 123 124 # filter latex code with bad commands 125 if check_blacklist(str_): 126 # we triggered the blacklist, immediately return None 127 return None 128 129 tmpfile = get_tmpfile_name() 130 131 # build latex string 132 write_latex(os.path.join(tmpfile + '.tex'), str_) 133 134 # convert TeX to dvi 135 exitcode = try_run(['latex', '--interaction=nonstopmode', 136 tmpfile + '.tex']) 137 138 if exitcode == 0: 139 # convert dvi to png 140 latex_png_dpi = gajim.config.get('latex_png_dpi') 141 exitcode = try_run(['dvipng', '-bg', bg_str, '-fg', fg_str, '-T', 142 'tight', '-D', latex_png_dpi, tmpfile + '.dvi', '-o', 143 tmpfile + '.png']) 144 145 # remove temp files created by us and TeX 146 extensions = ['.tex', '.log', '.aux', '.dvi'] 147 for ext in extensions: 148 try: 149 os.remove(tmpfile + ext) 150 except Exception: 151 pass 152 153 if isinstance(exitcode, (unicode, str)): 154 raise LatexError(exitcode) 155 156 if exitcode == 0: 157 result = tmpfile + '.png' 158 159 return result
160