]> git.lyx.org Git - lyx.git/blob - lib/scripts/lyxpreview_tools.py
546ed24248aede74c992766bea14f7cac213e750
[lyx.git] / lib / scripts / lyxpreview_tools.py
1 #! /usr/bin/env python
2
3 # file lyxpreview_tools.py
4 # This file is part of LyX, the document processor.
5 # Licence details can be found in the file COPYING.
6
7 # author Angus Leeming
8 # Full author contact details are available in file CREDITS
9
10 # and with much help testing the code under Windows from
11 #   Paul A. Rubin, rubin@msu.edu.
12
13 # A repository of the following functions, used by the lyxpreview2xyz scripts.
14 # copyfileobj, error, find_exe, find_exe_or_terminate, make_texcolor, mkstemp,
15 # progress, run_command, run_latex, warning
16
17 # Requires python 2.4 or later (subprocess module).
18
19 import os, re, string, subprocess, sys, tempfile
20
21
22 # Control the output to stdout
23 debug = False
24 verbose = False
25
26 # Known flavors of latex and bibtex
27 bibtex_commands = ("bibtex", "bibtex8", "biber")
28 latex_commands = ("latex", "pplatex", "platex", "latex2e")
29 pdflatex_commands = ("pdflatex", "xelatex", "lualatex")
30
31 # Pre-compiled regular expressions
32 latex_file_re = re.compile(r"\.tex$")
33
34 # PATH and PATHEXT environment variables
35 path = os.environ["PATH"].split(os.pathsep)
36 extlist = ['']
37 if "PATHEXT" in os.environ:
38     extlist += os.environ["PATHEXT"].split(os.pathsep)
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(string.atoi(hexcolor[0:2], 16)) / 255.0
80     green = float(string.atoi(hexcolor[2:4], 16)) / 255.0
81     blue  = float(string.atoi(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                     return command
103
104     return None
105
106
107 def find_exe_or_terminate(candidates):
108     exe = find_exe(candidates)
109     if exe == None:
110         error("Unable to find executable from '%s'" % string.join(candidates))
111
112     return exe
113
114
115 def run_command_popen(cmd):
116     if os.name == 'nt':
117         unix = False
118     else:
119         unix = True
120     pipe = subprocess.Popen(cmd, shell=unix, close_fds=unix, stdin=subprocess.PIPE, \
121         stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
122     cmd_stdout = pipe.communicate()[0]
123     cmd_status = pipe.returncode
124
125     global debug
126     if debug:
127         sys.stdout.write(cmd_stdout)
128     return cmd_status, cmd_stdout
129
130
131 def run_command_win32(cmd):
132     sa = win32security.SECURITY_ATTRIBUTES()
133     sa.bInheritHandle = True
134     stdout_r, stdout_w = win32pipe.CreatePipe(sa, 0)
135
136     si = win32process.STARTUPINFO()
137     si.dwFlags = (win32process.STARTF_USESTDHANDLES
138                   | win32process.STARTF_USESHOWWINDOW)
139     si.wShowWindow = win32con.SW_HIDE
140     si.hStdOutput = stdout_w
141
142     process, thread, pid, tid = \
143              win32process.CreateProcess(None, cmd, None, None, True,
144                                         0, None, None, si)
145     if process == None:
146         return -1, ""
147
148     # Must close the write handle in this process, or ReadFile will hang.
149     stdout_w.Close()
150
151     # Read the pipe until we get an error (including ERROR_BROKEN_PIPE,
152     # which is okay because it happens when child process ends).
153     data = ""
154     error = 0
155     while 1:
156         try:
157             hr, buffer = win32file.ReadFile(stdout_r, 4096)
158             if hr != winerror.ERROR_IO_PENDING:
159                 data = data + buffer
160
161         except pywintypes.error, e:
162             if e.args[0] != winerror.ERROR_BROKEN_PIPE:
163                 error = 1
164             break
165
166     if error:
167         return -2, ""
168
169     # Everything is okay --- the called process has closed the pipe.
170     # For safety, check that the process ended, then pick up its exit code.
171     win32event.WaitForSingleObject(process, win32event.INFINITE)
172     if win32process.GetExitCodeProcess(process):
173         return -3, ""
174
175     global debug
176     if debug:
177         sys.stdout.write(data)
178     return 0, data
179
180
181 def run_command(cmd):
182     progress("Running %s" % cmd)
183     if use_win32_modules:
184         return run_command_win32(cmd)
185     else:
186         return run_command_popen(cmd)
187
188
189 def get_version_info():
190     version_re = re.compile("([0-9])\.([0-9])")
191
192     match = version_re.match(sys.version)
193     if match == None:
194         error("Unable to extract version info from 'sys.version'")
195
196     return string.atoi(match.group(1)), string.atoi(match.group(2))
197
198
199 def copyfileobj(fsrc, fdst, rewind=0, length=16*1024):
200     """copy data from file-like object fsrc to file-like object fdst"""
201     if rewind:
202         fsrc.flush()
203         fsrc.seek(0)
204
205     while 1:
206         buf = fsrc.read(length)
207         if not buf:
208             break
209         fdst.write(buf)
210
211
212 class TempFile:
213     """clone of tempfile.TemporaryFile to use with python < 2.0."""
214     # Cache the unlinker so we don't get spurious errors at shutdown
215     # when the module-level "os" is None'd out.  Note that this must
216     # be referenced as self.unlink, because the name TempFile
217     # may also get None'd out before __del__ is called.
218     unlink = os.unlink
219
220     def __init__(self):
221         self.filename = tempfile.mktemp()
222         self.file = open(self.filename,"w+b")
223         self.close_called = 0
224
225     def close(self):
226         if not self.close_called:
227             self.close_called = 1
228             self.file.close()
229             self.unlink(self.filename)
230
231     def __del__(self):
232         self.close()
233
234     def read(self, size = -1):
235         return self.file.read(size)
236
237     def write(self, line):
238         return self.file.write(line)
239
240     def seek(self, offset):
241         return self.file.seek(offset)
242
243     def flush(self):
244         return self.file.flush()
245
246
247 def mkstemp():
248     """create a secure temporary file and return its object-like file"""
249     major, minor = get_version_info()
250
251     if major >= 2 and minor >= 0:
252         return tempfile.TemporaryFile()
253     else:
254         return TempFile()
255
256 def write_metrics_info(metrics_info, metrics_file):
257     metrics = open(metrics_file, 'w')
258     for metric in metrics_info:
259         metrics.write("Snippet %s %f\n" % metric)
260     metrics.close()
261
262 # Reads a .tex files and create an identical file but only with
263 # pages whose index is in pages_to_keep
264 def filter_pages(source_path, destination_path, pages_to_keep):
265     source_file = open(source_path, "r")
266     destination_file = open(destination_path, "w")
267
268     page_index = 0
269     skip_page = False
270     for line in source_file:
271         # We found a new page
272         if line.startswith("\\begin{preview}"):
273             page_index += 1
274             # If the page index isn't in pages_to_keep we don't copy it
275             skip_page = page_index not in pages_to_keep
276
277         if not skip_page:
278             destination_file.write(line)
279
280         # End of a page, we reset the skip_page bool
281         if line.startswith("\\end{preview}"):
282             skip_page = False
283
284     destination_file.close()
285     source_file.close()
286
287 # Joins two metrics list, that is a list of tuple (page_index, metric)
288 # new_page_indexes contains the original page number of the pages in new_metrics
289 # e.g. new_page_indexes[3] == 14 means that the 4th item in new_metrics is the 15th in the original counting
290 # original_bitmap and destination_bitmap are file name models used to rename the new files
291 # e.g. image_new%d.png and image_%d.png
292 def join_metrics_and_rename(original_metrics, new_metrics, new_page_indexes, original_bitmap, destination_bitmap):
293     legacy_index = 0
294     for (index, metric) in new_metrics:
295         # If the file exists we rename it
296         if os.path.isfile(original_bitmap % (index)):
297             os.rename(original_bitmap % (index), destination_bitmap % new_page_indexes[index-1])
298
299         # Extract the original page index
300         index = new_page_indexes[index-1]
301         # Goes through the array until the end is reached or the correct index is found
302         while legacy_index < len(original_metrics) and original_metrics[legacy_index][0] < index:
303             legacy_index += 1
304
305         # Add or update the metric for this page
306         if legacy_index < len(original_metrics) and original_metrics[legacy_index][0] == index:
307             original_metrics[legacy_index] = (index, metric)
308         else:
309             original_metrics.insert(legacy_index, (index, metric))
310
311
312 def run_latex(latex, latex_file, bibtex = None):
313     # Run latex
314     latex_status, latex_stdout = run_tex(latex, latex_file)
315
316     if bibtex is None:
317         return latex_status, latex_stdout
318
319     # The aux and log output file names
320     aux_file = latex_file_re.sub(".aux", latex_file)
321     log_file = latex_file_re.sub(".log", latex_file)
322
323     # Run bibtex/latex if necessary
324     progress("Checking if a bibtex run is necessary")
325     if string_in_file(r"\bibdata", aux_file):
326         bibtex_status, bibtex_stdout = run_tex(bibtex, aux_file)
327         latex_status, latex_stdout = run_tex(latex, latex_file)
328     # Rerun latex if necessary
329     progress("Checking if a latex rerun is necessary")
330     if string_in_file("Warning: Citation", log_file):
331         latex_status, latex_stdout = run_tex(latex, latex_file)
332
333     return latex_status, latex_stdout
334
335
336 def run_tex(tex, tex_file):
337     tex_call = '%s "%s"' % (tex, tex_file)
338
339     tex_status, tex_stdout = run_command(tex_call)
340     if tex_status:
341         warning("%s had problems compiling %s" \
342             % (os.path.basename(tex), tex_file))
343     return tex_status, tex_stdout
344
345
346 def string_in_file(string, infile):
347     if not os.path.isfile(infile):
348         return False
349     f = open(infile, 'r')
350     for line in f.readlines():
351         if string in line:
352             f.close()
353             return True
354     f.close()
355     return False