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