]> git.lyx.org Git - lyx.git/blob - lib/scripts/lyxpreview_tools.py
* lyxpreview_tool.py : Allow to look for commands with arguments.
[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, 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
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
39 use_win32_modules = 0
40 if os.name == "nt":
41     use_win32_modules = 1
42     try:
43         import pywintypes
44         import win32con
45         import win32event
46         import win32file
47         import win32pipe
48         import win32process
49         import win32security
50         import winerror
51     except:
52         sys.stderr.write("Consider installing the PyWin extension modules " \
53                          "if you're irritated by windows appearing briefly.\n")
54         use_win32_modules = 0
55
56
57 def progress(message):
58     global verbose
59     if verbose:
60         sys.stdout.write("Progress: %s\n" % message)
61
62
63 def warning(message):
64     sys.stderr.write("Warning: %s\n" % message)
65
66
67 def error(message):
68     sys.stderr.write("Error: %s\n" % message)
69     sys.exit(1)
70
71
72 def make_texcolor(hexcolor, graphics):
73     # Test that the input string contains 6 hexadecimal chars.
74     hexcolor_re = re.compile("^[0-9a-fA-F]{6}$")
75     if not hexcolor_re.match(hexcolor):
76         error("Cannot convert color '%s'" % hexcolor)
77
78     red   = float(string.atoi(hexcolor[0:2], 16)) / 255.0
79     green = float(string.atoi(hexcolor[2:4], 16)) / 255.0
80     blue  = float(string.atoi(hexcolor[4:6], 16)) / 255.0
81
82     if graphics:
83         return "%f,%f,%f" % (red, green, blue)
84     else:
85         return "rgb %f %f %f" % (red, green, blue)
86
87
88 def find_exe(candidates):
89     global extlist, path
90
91     for command in candidates:
92         prog = command.split()[0]
93         for directory in path:
94             for ext in extlist:
95                 full_path = os.path.join(directory, prog + ext)
96                 if os.access(full_path, os.X_OK):
97                     # The thing is in the PATH already (or we wouldn't
98                     # have found it). Return just the basename to avoid
99                     # problems when the path to the executable contains
100                     # spaces.
101                     return command
102
103     return None
104
105
106 def find_exe_or_terminate(candidates):
107     exe = find_exe(candidates)
108     if exe == None:
109         error("Unable to find executable from '%s'" % string.join(candidates))
110
111     return exe
112
113
114 def run_command_popen(cmd):
115     if os.name == 'nt':
116         unix = False
117     else:
118         unix = True
119     pipe = subprocess.Popen(cmd, shell=unix, close_fds=unix, stdin=subprocess.PIPE, \
120         stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
121     cmd_stdout = pipe.communicate()[0]
122     cmd_status = pipe.returncode
123
124     global debug
125     if debug:
126         sys.stdout.write(cmd_stdout)
127     return cmd_status, cmd_stdout
128
129
130 def run_command_win32(cmd):
131     sa = win32security.SECURITY_ATTRIBUTES()
132     sa.bInheritHandle = True
133     stdout_r, stdout_w = win32pipe.CreatePipe(sa, 0)
134
135     si = win32process.STARTUPINFO()
136     si.dwFlags = (win32process.STARTF_USESTDHANDLES
137                   | win32process.STARTF_USESHOWWINDOW)
138     si.wShowWindow = win32con.SW_HIDE
139     si.hStdOutput = stdout_w
140
141     process, thread, pid, tid = \
142              win32process.CreateProcess(None, cmd, None, None, True,
143                                         0, None, None, si)
144     if process == None:
145         return -1, ""
146
147     # Must close the write handle in this process, or ReadFile will hang.
148     stdout_w.Close()
149
150     # Read the pipe until we get an error (including ERROR_BROKEN_PIPE,
151     # which is okay because it happens when child process ends).
152     data = ""
153     error = 0
154     while 1:
155         try:
156             hr, buffer = win32file.ReadFile(stdout_r, 4096)
157             if hr != winerror.ERROR_IO_PENDING:
158                 data = data + buffer
159
160         except pywintypes.error, e:
161             if e.args[0] != winerror.ERROR_BROKEN_PIPE:
162                 error = 1
163             break
164
165     if error:
166         return -2, ""
167
168     # Everything is okay --- the called process has closed the pipe.
169     # For safety, check that the process ended, then pick up its exit code.
170     win32event.WaitForSingleObject(process, win32event.INFINITE)
171     if win32process.GetExitCodeProcess(process):
172         return -3, ""
173
174     global debug
175     if debug:
176         sys.stdout.write(data)
177     return 0, data
178
179
180 def run_command(cmd):
181     progress("Running %s" % cmd)
182     if use_win32_modules:
183         return run_command_win32(cmd)
184     else:
185         return run_command_popen(cmd)
186
187
188 def get_version_info():
189     version_re = re.compile("([0-9])\.([0-9])")
190
191     match = version_re.match(sys.version)
192     if match == None:
193         error("Unable to extract version info from 'sys.version'")
194
195     return string.atoi(match.group(1)), string.atoi(match.group(2))
196
197
198 def copyfileobj(fsrc, fdst, rewind=0, length=16*1024):
199     """copy data from file-like object fsrc to file-like object fdst"""
200     if rewind:
201         fsrc.flush()
202         fsrc.seek(0)
203
204     while 1:
205         buf = fsrc.read(length)
206         if not buf:
207             break
208         fdst.write(buf)
209
210
211 class TempFile:
212     """clone of tempfile.TemporaryFile to use with python < 2.0."""
213     # Cache the unlinker so we don't get spurious errors at shutdown
214     # when the module-level "os" is None'd out.  Note that this must
215     # be referenced as self.unlink, because the name TempFile
216     # may also get None'd out before __del__ is called.
217     unlink = os.unlink
218
219     def __init__(self):
220         self.filename = tempfile.mktemp()
221         self.file = open(self.filename,"w+b")
222         self.close_called = 0
223
224     def close(self):
225         if not self.close_called:
226             self.close_called = 1
227             self.file.close()
228             self.unlink(self.filename)
229
230     def __del__(self):
231         self.close()
232
233     def read(self, size = -1):
234         return self.file.read(size)
235
236     def write(self, line):
237         return self.file.write(line)
238
239     def seek(self, offset):
240         return self.file.seek(offset)
241
242     def flush(self):
243         return self.file.flush()
244
245
246 def mkstemp():
247     """create a secure temporary file and return its object-like file"""
248     major, minor = get_version_info()
249
250     if major >= 2 and minor >= 0:
251         return tempfile.TemporaryFile()
252     else:
253         return TempFile()
254
255 def write_metrics_info(metrics_info, metrics_file):
256     metrics = open(metrics_file, 'w')
257     for metric in metrics_info:
258         metrics.write("Snippet %s %f\n" % metric)
259     metrics.close()
260
261 # Reads a .tex files and create an identical file but only with
262 # pages whose index is in pages_to_keep
263 def filter_pages(source_path, destination_path, pages_to_keep):
264     source_file = open(source_path, "r")
265     destination_file = open(destination_path, "w")
266
267     page_index = 0
268     skip_page = False
269     for line in source_file:
270         # We found a new page
271         if line.startswith("\\begin{preview}"):
272             page_index += 1
273             # If the page index isn't in pages_to_keep we don't copy it
274             skip_page = page_index not in pages_to_keep
275
276         if not skip_page:
277             destination_file.write(line)
278
279         # End of a page, we reset the skip_page bool
280         if line.startswith("\\end{preview}"):
281             skip_page = False
282
283     destination_file.close()
284     source_file.close()
285
286 # Joins two metrics list, that is a list of tuple (page_index, metric)
287 # new_page_indexes contains the original page number of the pages in new_metrics
288 # e.g. new_page_indexes[3] == 14 means that the 4th item in new_metrics is the 15th in the original counting
289 # original_bitmap and destination_bitmap are file name models used to rename the new files
290 # e.g. image_new%d.png and image_%d.png
291 def join_metrics_and_rename(original_metrics, new_metrics, new_page_indexes, original_bitmap, destination_bitmap):
292     legacy_index = 0
293     for (index, metric) in new_metrics:
294         # If the file exists we rename it
295         if os.path.isfile(original_bitmap % (index)):
296             os.rename(original_bitmap % (index), destination_bitmap % new_page_indexes[index-1])
297
298         # Extract the original page index
299         index = new_page_indexes[index-1]
300         # Goes through the array until the end is reached or the correct index is found
301         while legacy_index < len(original_metrics) and original_metrics[legacy_index][0] < index:
302             legacy_index += 1
303
304         # Add or update the metric for this page
305         if legacy_index < len(original_metrics) and original_metrics[legacy_index][0] == index:
306             original_metrics[legacy_index] = (index, metric)
307         else:
308             original_metrics.insert(legacy_index, (index, metric))