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