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