]> git.lyx.org Git - features.git/blob - lib/scripts/legacy_lyxpreview2ppm.py
Append ".exe" to the name of the searched-for program on Win32.
[features.git] / lib / scripts / legacy_lyxpreview2ppm.py
1 #! /usr/bin/env python
2
3 # file legacy_lyxpreview2ppm.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
9 # Full author contact details are available in file CREDITS
10
11 # This script converts a LaTeX file to a bunch of ppm files using the
12 # deprecated dvi->ps->ppm conversion route.
13
14 # If possible, please grab 'dvipng'; it's faster and more robust.
15 # This legacy support will be removed one day...
16
17 import glob, os, re, string, sys
18 import pipes, tempfile
19
20
21 # Pre-compiled regular expressions.
22 latex_file_re = re.compile("\.tex$")
23
24
25 def usage(prog_name):
26     return "Usage: %s <latex file> <dpi> <fg color> <bg color>\n"\
27            "\twhere the colors are hexadecimal strings, eg 'faf0e6'"\
28            % prog_name
29
30
31 def error(message):
32     sys.stderr.write(message + '\n')
33     sys.exit(1)
34
35
36 def find_exe(candidates, path):
37     for prog in candidates:
38         for directory in path:
39             if os.name == "nt":
40                 full_path = os.path.join(directory, prog + ".exe")
41             else:
42                 full_path = os.path.join(directory, prog)
43
44             if os.access(full_path, os.X_OK):
45                 return full_path
46
47     return None
48
49
50 def find_exe_or_terminate(candidates, path):
51     exe = find_exe(candidates, path)
52     if exe == None:
53         error("Unable to find executable from '%s'" % string.join(candidates))
54
55     return exe
56
57
58 def run_command(cmd):
59     handle = os.popen(cmd, 'r')
60     cmd_stdout = handle.read()
61     cmd_status = handle.close()
62
63     return cmd_status, cmd_stdout
64
65
66 def extract_metrics_info(log_file, metrics_file):
67     metrics = open(metrics_file, 'w')
68
69     log_re = re.compile("Preview: ([ST])")
70     data_re = re.compile("(-?[0-9]+) (-?[0-9]+) (-?[0-9]+) (-?[0-9]+)")
71
72     tp_ascent  = 0.0
73     tp_descent = 0.0
74
75     success = 0
76     for line in open(log_file, 'r').readlines():
77         match = log_re.match(line)
78         if match == None:
79             continue
80
81         snippet = (match.group(1) == 'S')
82         success = 1
83         match = data_re.search(line)
84         if match == None:
85             error("Unexpected data in %s\n%s" % (log_file, line))
86
87         if snippet:
88             ascent  = string.atof(match.group(2)) + tp_ascent
89             descent = string.atof(match.group(3)) - tp_descent
90
91             frac = 0.5
92             if abs(ascent + descent) > 0.1:
93                 frac = ascent / (ascent + descent)
94
95                 metrics.write("Snippet %s %f\n" % (match.group(1), frac))
96
97         else:
98             tp_descent = string.atof(match.group(2))
99             tp_ascent  = string.atof(match.group(4))
100
101     return success
102
103
104 def extract_resolution(log_file, dpi):
105     fontsize_re = re.compile("Preview: Fontsize")
106     magnification_re = re.compile("Preview: Magnification")
107     extract_decimal_re = re.compile("([0-9\.]+)")
108     extract_integer_re = re.compile("([0-9]+)")
109
110     found_fontsize = 0
111     found_magnification = 0
112
113     # Default values
114     magnification = 1000.0
115     fontsize = 0.0
116
117     for line in open(log_file, 'r').readlines():
118         if found_fontsize and found_magnification:
119             break
120
121         if not found_fontsize:
122             match = fontsize_re.match(line)
123             if match != None:
124                 match = extract_decimal_re.search(line)
125                 if match == None:
126                     error("Unable to parse: %s" % line)
127                 fontsize = string.atof(match.group(1))
128                 found_fontsize = 1
129                 continue
130
131         if not found_magnification:
132             match = magnification_re.match(line)
133             if match != None:
134                 match = extract_integer_re.search(line)
135                 if match == None:
136                     error("Unable to parse: %s" % line)
137                 magnification = string.atof(match.group(1))
138                 found_magnification = 1
139                 continue
140
141     return dpi * (10.0 / fontsize) * (1000.0 / magnification)
142
143     
144 def get_version_info():
145     version_re = re.compile("([0-9])\.([0-9])")
146
147     match = version_re.match(sys.version)
148     if match == None:
149         error("Unable to extract version info from 'sys.version'")
150
151     return string.atoi(match.group(1)), string.atoi(match.group(2))
152
153
154 def copyfileobj(fsrc, fdst, rewind=0, length=16*1024):
155     """copy data from file-like object fsrc to file-like object fdst"""
156     if rewind:
157         fsrc.flush()
158         fsrc.seek(0)
159
160     while 1:
161         buf = fsrc.read(length)
162         if not buf:
163             break
164         fdst.write(buf)
165
166
167 class TempFile:
168     """clone of tempfile.TemporaryFile to use with python < 2.0."""
169     # Cache the unlinker so we don't get spurious errors at shutdown
170     # when the module-level "os" is None'd out.  Note that this must
171     # be referenced as self.unlink, because the name TempFile
172     # may also get None'd out before __del__ is called.
173     unlink = os.unlink
174
175     def __init__(self):
176         self.filename = tempfile.mktemp()
177         self.file = open(self.filename,"w+b")
178         self.close_called = 0
179
180     def close(self):
181         if not self.close_called:
182             self.close_called = 1
183             self.file.close()
184             self.unlink(self.filename)
185
186     def __del__(self):
187         self.close()
188
189     def read(self, size = -1):
190         return self.file.read(size)
191
192     def write(self, line):
193         return self.file.write(line)
194
195     def seek(self, offset):
196         return self.file.seek(offset)
197
198     def flush(self):
199         return self.file.flush()
200
201
202 def mkstemp():
203     """create a secure temporary file and return its object-like file"""
204     major, minor = get_version_info()
205
206     if major >= 2 and minor >= 0:
207         return tempfile.TemporaryFile()
208     else:
209         return TempFile()
210
211
212 def legacy_latex_file(latex_file, fg_color, bg_color):
213     use_preview_re = re.compile("(\\\\usepackage\[[^]]+)(\]{preview})")
214
215     tmp = mkstemp()
216
217     success = 0
218     for line in open(latex_file, 'r').readlines():
219         match = use_preview_re.match(line)
220         if match == None:
221             tmp.write(line)
222             continue
223
224         success = 1
225         tmp.write("%s,dvips,tightpage%s\n\n" \
226                   "\\AtBeginDocument{\\AtBeginDvi{%%\n" \
227                   "\\special{!userdict begin/bop-hook{//bop-hook exec\n" \
228                   "<%s%s>{255 div}forall setrgbcolor\n" \
229                   "clippath fill setrgbcolor}bind def end}}}\n" \
230                   % (match.group(1), match.group(2), fg_color, bg_color))
231
232     if success:
233         copyfileobj(tmp, open(latex_file,"wb"), 1)
234
235     return success
236
237
238 def crop_files(pnmcrop, basename):
239     t = pipes.Template()
240     t.append("%s -left" % pnmcrop, '--')
241     t.append("%s -right" % pnmcrop, '--')
242
243     for file in glob.glob("%s*.ppm" % basename):
244         tmp = mkstemp()
245         new = t.open(file, "r")
246         copyfileobj(new, tmp)
247         if not new.close():
248             copyfileobj(tmp, open(file,"wb"), 1)
249
250
251 def legacy_conversion(argv):
252     # Parse and manipulate the command line arguments.
253     if len(argv) != 6:
254         error(usage(argv[0]))
255
256     # Ignore argv[1]
257
258     dir, latex_file = os.path.split(argv[2])
259     if len(dir) != 0:
260         os.chdir(dir)
261
262     dpi = string.atoi(argv[3])
263     fg_color = argv[4]
264     bg_color = argv[5]
265
266     # External programs used by the script.
267     path = string.split(os.getenv("PATH"), os.pathsep)
268     latex   = find_exe_or_terminate(["pplatex", "latex2e", "latex"], path)
269     dvips   = find_exe_or_terminate(["dvips"], path)
270     gs      = find_exe_or_terminate(["gswin32", "gs"], path)
271     pnmcrop = find_exe(["pnmcrop"], path)
272
273     # Move color information into the latex file.
274     if not legacy_latex_file(latex_file, fg_color, bg_color):
275         error("Unable to move color info into the latex file")
276
277     # Compile the latex file.
278     latex_call = "%s %s" % (latex, latex_file)
279
280     latex_status, latex_stdout = run_command(latex_call)
281     if latex_status != None:
282         error("%s failed to compile %s" \
283               % (os.path.basename(latex), latex_file))
284
285     # Run the dvi file through dvips.
286     dvi_file = latex_file_re.sub(".dvi", latex_file)
287     ps_file  = latex_file_re.sub(".ps",  latex_file)
288
289     dvips_call = "%s -o %s %s" % (dvips, ps_file, dvi_file)
290     
291     dvips_status, dvips_stdout = run_command(dvips_call)
292     if dvips_status != None:
293         error("Failed: %s %s" % (os.path.basename(dvips), dvi_file))
294
295     # Extract resolution data for gs from the log file.
296     log_file = latex_file_re.sub(".log", latex_file)
297     resolution = extract_resolution(log_file, dpi)
298
299     # Older versions of gs have problems with a large degree of
300     # anti-aliasing at high resolutions
301     alpha = 4
302     if resolution > 150:
303         alpha = 2
304
305     # Generate the bitmap images
306     gs_call = "%s -dNOPAUSE -dBATCH -dSAFER -sDEVICE=pnmraw " \
307               "-sOutputFile=%s%%d.ppm " \
308               "-dGraphicsAlphaBit=%d -dTextAlphaBits=%d " \
309               "-r%f %s" \
310               % (gs, latex_file_re.sub("", latex_file), \
311                  alpha, alpha, resolution, ps_file)
312
313     gs_status, gs_stdout = run_command(gs_call)
314     if gs_status != None:
315         error("Failed: %s %s" % (os.path.basename(gs), ps_file))
316
317     # Crop the images
318     if pnmcrop != None:
319         crop_files(pnmcrop, latex_file_re.sub("", latex_file))
320
321     # Extract metrics info from the log file.
322     metrics_file = latex_file_re.sub(".metrics", latex_file)
323     if not extract_metrics_info(log_file, metrics_file):
324         error("Failed to extract metrics info from %s" % log_file)
325
326     return 0