]> git.lyx.org Git - lyx.git/blob - lib/scripts/lyxpreview_tools.py
b7a89dc92b48fccd18303d05aa6ba014f519490e
[lyx.git] / lib / scripts / lyxpreview_tools.py
1
2 # file lyxpreview_tools.py
3 # This file is part of LyX, the document processor.
4 # Licence details can be found in the file COPYING.
5
6 # author Angus Leeming
7 # Full author contact details are available in file CREDITS
8
9 # and with much help testing the code under Windows from
10 #   Paul A. Rubin, rubin@msu.edu.
11
12 # A repository of the following functions, used by the lyxpreview2xyz scripts.
13 # copyfileobj, error, find_exe, find_exe_or_terminate, make_texcolor, mkstemp,
14 # progress, run_command, run_latex, warning
15
16 # Requires python 2.4 or later (subprocess module).
17
18 import os, re, subprocess, sys, tempfile
19
20
21 # Control the output to stdout
22 debug = False
23 verbose = False
24
25 # Known flavors of latex and bibtex
26 bibtex_commands = ("bibtex", "bibtex8", "biber")
27 latex_commands = ("latex", "pplatex", "platex", "latex2e")
28 pdflatex_commands = ("pdflatex", "xelatex", "lualatex")
29
30 # Pre-compiled regular expressions
31 latex_file_re = re.compile(r"\.tex$")
32
33 # PATH and PATHEXT environment variables
34 path = os.environ["PATH"].split(os.pathsep)
35 extlist = ['']
36 if "PATHEXT" in os.environ:
37     extlist += os.environ["PATHEXT"].split(os.pathsep)
38 extlist.append('.py')
39
40 use_win32_modules = 0
41 if os.name == "nt":
42     use_win32_modules = 1
43     try:
44         import pywintypes
45         import win32con
46         import win32event
47         import win32file
48         import win32pipe
49         import win32process
50         import win32security
51         import winerror
52     except:
53         sys.stderr.write("Consider installing the PyWin extension modules " \
54                          "if you're irritated by windows appearing briefly.\n")
55         use_win32_modules = 0
56
57
58 def progress(message):
59     global verbose
60     if verbose:
61         sys.stdout.write("Progress: %s\n" % message)
62
63
64 def warning(message):
65     sys.stderr.write("Warning: %s\n" % message)
66
67
68 def error(message):
69     sys.stderr.write("Error: %s\n" % message)
70     sys.exit(1)
71
72
73 def make_texcolor(hexcolor, graphics):
74     # Test that the input string contains 6 hexadecimal chars.
75     hexcolor_re = re.compile("^[0-9a-fA-F]{6}$")
76     if not hexcolor_re.match(hexcolor):
77         error("Cannot convert color '%s'" % hexcolor)
78
79     red   = float(int(hexcolor[0:2], 16)) / 255.0
80     green = float(int(hexcolor[2:4], 16)) / 255.0
81     blue  = float(int(hexcolor[4:6], 16)) / 255.0
82
83     if graphics:
84         return "%f,%f,%f" % (red, green, blue)
85     else:
86         return "rgb %f %f %f" % (red, green, blue)
87
88
89 def find_exe(candidates):
90     global extlist, path
91
92     for command in candidates:
93         prog = command.split()[0]
94         for directory in path:
95             for ext in extlist:
96                 full_path = os.path.join(directory, prog + ext)
97                 if os.access(full_path, os.X_OK):
98                     # The thing is in the PATH already (or we wouldn't
99                     # have found it). Return just the basename to avoid
100                     # problems when the path to the executable contains
101                     # spaces.
102                     if full_path.lower().endswith('.py'):
103                         return command.replace(prog, '"%s" "%s"'
104                             % (sys.executable, full_path))
105                     return command
106
107     return None
108
109
110 def find_exe_or_terminate(candidates):
111     exe = find_exe(candidates)
112     if exe == None:
113         error("Unable to find executable from '%s'" % " ".join(candidates))
114
115     return exe
116
117
118 def run_command_popen(cmd, stderr2stdout):
119     if os.name == 'nt':
120         unix = False
121     else:
122         unix = True
123     if stderr2stdout:
124         pipe = subprocess.Popen(cmd, shell=unix, close_fds=unix, stdin=subprocess.PIPE, \
125             stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
126         cmd_stdout = pipe.communicate()[0]
127     else:
128         pipe = subprocess.Popen(cmd, shell=unix, close_fds=unix, stdin=subprocess.PIPE, \
129             stdout=subprocess.PIPE, universal_newlines=True)
130         (cmd_stdout, cmd_stderr) = pipe.communicate()
131         if cmd_stderr:
132             sys.stderr.write(cmd_stderr)
133     cmd_status = pipe.returncode
134
135     global debug
136     if debug:
137         sys.stdout.write(cmd_stdout)
138     return cmd_status, cmd_stdout
139
140
141 def run_command_win32(cmd):
142     sa = win32security.SECURITY_ATTRIBUTES()
143     sa.bInheritHandle = True
144     stdout_r, stdout_w = win32pipe.CreatePipe(sa, 0)
145
146     si = win32process.STARTUPINFO()
147     si.dwFlags = (win32process.STARTF_USESTDHANDLES
148                   | win32process.STARTF_USESHOWWINDOW)
149     si.wShowWindow = win32con.SW_HIDE
150     si.hStdOutput = stdout_w
151
152     process, thread, pid, tid = \
153              win32process.CreateProcess(None, cmd, None, None, True,
154                                         0, None, None, si)
155     if process == None:
156         return -1, ""
157
158     # Must close the write handle in this process, or ReadFile will hang.
159     stdout_w.Close()
160
161     # Read the pipe until we get an error (including ERROR_BROKEN_PIPE,
162     # which is okay because it happens when child process ends).
163     data = ""
164     error = 0
165     while 1:
166         try:
167             hr, buffer = win32file.ReadFile(stdout_r, 4096)
168             if hr != winerror.ERROR_IO_PENDING:
169                 data = data + buffer
170
171         except pywintypes.error as e:
172             if e.args[0] != winerror.ERROR_BROKEN_PIPE:
173                 error = 1
174             break
175
176     if error:
177         return -2, ""
178
179     # Everything is okay --- the called process has closed the pipe.
180     # For safety, check that the process ended, then pick up its exit code.
181     win32event.WaitForSingleObject(process, win32event.INFINITE)
182     if win32process.GetExitCodeProcess(process):
183         return -3, ""
184
185     global debug
186     if debug:
187         sys.stdout.write(data)
188     return 0, data
189
190
191 def run_command(cmd, stderr2stdout = True):
192     progress("Running %s" % cmd)
193     if use_win32_modules:
194         return run_command_win32(cmd)
195     else:
196         return run_command_popen(cmd, stderr2stdout)
197
198
199 def get_version_info():
200     version_re = re.compile("([0-9])\.([0-9])")
201
202     match = version_re.match(sys.version)
203     if match == None:
204         error("Unable to extract version info from 'sys.version'")
205
206     return int(match.group(1)), int(match.group(2))
207
208
209 def copyfileobj(fsrc, fdst, rewind=0, length=16*1024):
210     """copy data from file-like object fsrc to file-like object fdst"""
211     if rewind:
212         fsrc.flush()
213         fsrc.seek(0)
214
215     while 1:
216         buf = fsrc.read(length)
217         if not buf:
218             break
219         fdst.write(buf)
220
221
222 class TempFile:
223     """clone of tempfile.TemporaryFile to use with python < 2.0."""
224     # Cache the unlinker so we don't get spurious errors at shutdown
225     # when the module-level "os" is None'd out.  Note that this must
226     # be referenced as self.unlink, because the name TempFile
227     # may also get None'd out before __del__ is called.
228     unlink = os.unlink
229
230     def __init__(self):
231         self.filename = tempfile.mktemp()
232         self.file = open(self.filename,"w+b")
233         self.close_called = 0
234
235     def close(self):
236         if not self.close_called:
237             self.close_called = 1
238             self.file.close()
239             self.unlink(self.filename)
240
241     def __del__(self):
242         self.close()
243
244     def read(self, size = -1):
245         return self.file.read(size)
246
247     def write(self, line):
248         return self.file.write(line)
249
250     def seek(self, offset):
251         return self.file.seek(offset)
252
253     def flush(self):
254         return self.file.flush()
255
256
257 def mkstemp():
258     """create a secure temporary file and return its object-like file"""
259     major, minor = get_version_info()
260
261     if major >= 2 and minor >= 0:
262         return tempfile.TemporaryFile()
263     else:
264         return TempFile()
265
266 def write_metrics_info(metrics_info, metrics_file):
267     metrics = open(metrics_file, 'w')
268     for metric in metrics_info:
269         metrics.write("Snippet %s %f\n" % metric)
270     metrics.close()
271
272 # Reads a .tex files and create an identical file but only with
273 # pages whose index is in pages_to_keep
274 def filter_pages(source_path, destination_path, pages_to_keep):
275     def_re = re.compile(r"(\\newcommandx|\\renewcommandx|\\global\\long\\def)(\\[a-zA-Z]+)(.+)")
276     source_file = open(source_path, "r")
277     destination_file = open(destination_path, "w")
278
279     page_index = 0
280     skip_page = False
281     macros = []
282     for line in source_file:
283         # We found a new page
284         if line.startswith("\\begin{preview}"):
285             page_index += 1
286             # If the page index isn't in pages_to_keep we don't copy it
287             skip_page = page_index not in pages_to_keep
288
289         if not skip_page:
290             match = def_re.match(line)
291             if match != None:
292                 definecmd = match.group(1)
293                 macroname = match.group(2)
294                 if not macroname in macros:
295                     macros.append(macroname)
296                     if definecmd == "\\renewcommandx":
297                         line = line.replace(definecmd, "\\newcommandx")
298             destination_file.write(line)
299
300         # End of a page, we reset the skip_page bool
301         if line.startswith("\\end{preview}"):
302             skip_page = False
303
304     destination_file.close()
305     source_file.close()
306
307 # Joins two metrics list, that is a list of tuple (page_index, metric)
308 # new_page_indexes contains the original page number of the pages in new_metrics
309 # e.g. new_page_indexes[3] == 14 means that the 4th item in new_metrics is the 15th in the original counting
310 # original_bitmap and destination_bitmap are file name models used to rename the new files
311 # e.g. image_new%d.png and image_%d.png
312 def join_metrics_and_rename(original_metrics, new_metrics, new_page_indexes, original_bitmap, destination_bitmap):
313     legacy_index = 0
314     for (index, metric) in new_metrics:
315         # If the file exists we rename it
316         if os.path.isfile(original_bitmap % (index)):
317             os.rename(original_bitmap % (index), destination_bitmap % new_page_indexes[index-1])
318
319         # Extract the original page index
320         index = new_page_indexes[index-1]
321         # Goes through the array until the end is reached or the correct index is found
322         while legacy_index < len(original_metrics) and original_metrics[legacy_index][0] < index:
323             legacy_index += 1
324
325         # Add or update the metric for this page
326         if legacy_index < len(original_metrics) and original_metrics[legacy_index][0] == index:
327             original_metrics[legacy_index] = (index, metric)
328         else:
329             original_metrics.insert(legacy_index, (index, metric))
330
331
332 def run_latex(latex, latex_file, bibtex = None):
333     # Run latex
334     latex_status, latex_stdout = run_tex(latex, latex_file)
335
336     if bibtex is None:
337         return latex_status, latex_stdout
338
339     # The aux and log output file names
340     aux_file = latex_file_re.sub(".aux", latex_file)
341     log_file = latex_file_re.sub(".log", latex_file)
342
343     # Run bibtex/latex if necessary
344     progress("Checking if a bibtex run is necessary")
345     if string_in_file(r"\bibdata", aux_file):
346         bibtex_status, bibtex_stdout = run_tex(bibtex, aux_file)
347         latex_status, latex_stdout = run_tex(latex, latex_file)
348     # Rerun latex if necessary
349     progress("Checking if a latex rerun is necessary")
350     if string_in_file("Warning: Citation", log_file):
351         latex_status, latex_stdout = run_tex(latex, latex_file)
352
353     return latex_status, latex_stdout
354
355
356 def run_tex(tex, tex_file):
357     tex_call = '%s "%s"' % (tex, tex_file)
358
359     tex_status, tex_stdout = run_command(tex_call)
360     if tex_status:
361         progress("Warning: %s had problems compiling %s" \
362             % (os.path.basename(tex), tex_file))
363     return tex_status, tex_stdout
364
365
366 def string_in_file(string, infile):
367     if not os.path.isfile(infile):
368         return False
369     f = open(infile, 'r')
370     for line in f.readlines():
371         if string in line:
372             f.close()
373             return True
374     f.close()
375     return False
376
377
378 # Returns a list of indexes of pages giving errors extracted from the latex log
379 def check_latex_log(log_file):
380
381     error_re = re.compile("^! ")
382     snippet_re = re.compile("^Preview: Snippet ")
383     data_re = re.compile("([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+)")
384
385     found_error = False
386     error_pages = []
387
388     try:
389         for line in open(log_file, 'r').readlines():
390             if not found_error:
391                 match = error_re.match(line)
392                 if match != None:
393                     found_error = True
394                 continue
395             else:
396                 match = snippet_re.match(line)
397                 if match == None:
398                     continue
399
400                 found_error = False
401                 match = data_re.search(line)
402                 if match == None:
403                     error("Unexpected data in %s\n%s" % (log_file, line))
404
405                 error_pages.append(int(match.group(1)))
406
407     except:
408         warning('check_latex_log: Unable to open "%s"' % log_file)
409         warning(repr(sys.exc_info()[0]) + ',' + repr(sys.exc_info()[1]))
410
411     return error_pages