]> git.lyx.org Git - features.git/blob - lib/scripts/lyxpreview-lytex2bitmap.py
26efeb612a60c58b31331d6e2bb66737d3f5257f
[features.git] / lib / scripts / lyxpreview-lytex2bitmap.py
1 #! /usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 # file lyxpreview-lytex2bitmap.py
5 # This file is part of LyX, the document processor.
6 # Licence details can be found in the file COPYING.
7
8 # author Angus Leeming
9 # with much advice from members of the preview-latex project:
10 # David Kastrup, dak@gnu.org and
11 # Jan-Åke Larsson, jalar@mai.liu.se.
12
13 # Full author contact details are available in file CREDITS
14
15 # This script takes a LaTeX file and generates a collection of
16 # png or ppm image files, one per previewed snippet.
17
18 # Pre-requisites:
19 # * A latex executable;
20 # * preview.sty;
21 # * dvipng;
22 # * pngtoppm (if outputing ppm format images).
23
24 # preview.sty and dvipng are part of the preview-latex project
25 # http://preview-latex.sourceforge.net/
26
27 # preview.sty can alternatively be obtained from
28 # CTAN/support/preview-latex/
29
30 # Example usage:
31 # lyxpreview-lytex2bitmap.py png 0lyxpreview.tex 128 000000 faf0e6
32
33 # This script takes six arguments:
34 # FORMAT:   The desired output format. Either 'png' or 'ppm'.
35 # TEXFILE:  the name of the .tex file to be converted.
36 # DPI:      a scale factor, used to ascertain the resolution of the
37 #           generated image which is then passed to gs.
38 # FG_COLOR: the foreground color as a hexadecimal string, eg '000000'.
39 # BG_COLOR: the background color as a hexadecimal string, eg 'faf0e6'.
40 # CONVERTER: the converter (optional). Default is latex.
41
42 # Decomposing TEXFILE's name as DIR/BASE.tex, this script will,
43 # if executed successfully, leave in DIR:
44 # * a (possibly large) number of image files with names
45 #   like BASE[0-9]+.png
46 # * a file BASE.metrics, containing info needed by LyX to position
47 #   the images correctly on the screen.
48
49 import glob, os, re, shutil, string, sys
50
51 from legacy_lyxpreview2ppm import legacy_conversion, \
52      legacy_conversion_step2, legacy_extract_metrics_info
53
54 from lyxpreview_tools import copyfileobj, error, find_exe, \
55      find_exe_or_terminate, make_texcolor, mkstemp, run_command, warning, \
56      write_metrics_info
57
58
59 # Pre-compiled regular expressions.
60 latex_file_re = re.compile("\.tex$")
61
62
63 def usage(prog_name):
64     return "Usage: %s <format> <latex file> <dpi> <fg color> <bg color>\n"\
65            "\twhere the colors are hexadecimal strings, eg 'faf0e6'"\
66            % prog_name
67     
68 # Returns a list of tuples containing page number and ascent fraction
69 # extracted from dvipng output.
70 # Use write_metrics_info to create the .metrics file with this info
71 def extract_metrics_info(dvipng_stdout):
72     # "\[[0-9]+" can match two kinds of numbers: page numbers from dvipng
73     # and glyph numbers from mktexpk. The glyph numbers always match
74     # "\[[0-9]+\]" while the page number never is followed by "\]". Thus:
75     page_re = re.compile("\[([0-9]+)[^]]");
76     metrics_re = re.compile("depth=(-?[0-9]+) height=(-?[0-9]+)")
77
78     success = 0
79     page = ""
80     pos = 0
81     results = []
82     while 1:
83         match = page_re.search(dvipng_stdout, pos)
84         if match == None:
85             break
86         page = match.group(1)
87         pos = match.end()
88         match = metrics_re.search(dvipng_stdout, pos)
89         if match == None:
90             break
91         success = 1
92
93         # Calculate the 'ascent fraction'.
94         descent = string.atof(match.group(1))
95         ascent  = string.atof(match.group(2))
96
97         frac = 0.5
98         if ascent >= 0 or descent >= 0:
99             if abs(ascent + descent) > 0.1:
100                 frac = ascent / (ascent + descent)
101
102             # Sanity check
103             if frac < 0:
104                 frac = 0.5
105
106         results.append((page, frac))
107         pos = match.end() + 2
108
109     if success == 0:
110         error("Failed to extract metrics info from dvipng")
111     
112     return results
113
114
115 def color_pdf(latex_file, bg_color, fg_color):
116     use_preview_pdf_re = re.compile("(\s*\\\\usepackage\[[^]]+)((pdftex|xetex)\]{preview})")
117
118     tmp = mkstemp()
119     
120     fg = ""
121     if fg_color != "0.000000,0.000000,0.000000":
122         fg = '  \\AtBeginDocument{\\let\\oldpreview\\preview\\renewcommand\\preview{\\oldpreview\\color[rgb]{%s}}}\n' % (fg_color)
123     
124     success = 0
125     try:
126         for line in open(latex_file, 'r').readlines():
127             match = use_preview_pdf_re.match(line)
128             if match == None:
129                 tmp.write(line)
130                 continue
131             success = 1
132             tmp.write("  \\usepackage{color}\n" \
133                   "  \\pagecolor[rgb]{%s}\n" \
134                   "%s" \
135                   "%s\n" \
136                   % (bg_color, fg, match.group()))
137             continue
138
139     except:
140         # Unable to open the file, but do nothing here because
141         # the calling function will act on the value of 'success'.
142         warning('Warning in color_pdf! Unable to open "%s"' % latex_file)
143         warning(`sys.exc_type` + ',' + `sys.exc_value`)
144
145     if success:
146         copyfileobj(tmp, open(latex_file,"wb"), 1)
147
148     return success
149
150
151 def fix_latex_file(latex_file):
152     documentclass_re = re.compile("(\\\\documentclass\[)(1[012]pt,?)(.+)")
153
154     tmp = mkstemp()
155
156     changed = 0
157     for line in open(latex_file, 'r').readlines():
158         match = documentclass_re.match(line)
159         if match == None:
160             tmp.write(line)
161             continue
162
163         changed = 1
164         tmp.write("%s%s%s\n" % (match.group(1), match.group(3)))
165
166     if changed:
167         copyfileobj(tmp, open(latex_file,"wb"), 1)
168
169     return
170
171
172 def convert_to_ppm_format(pngtopnm, basename):
173     png_file_re = re.compile("\.png$")
174
175     for png_file in glob.glob("%s*.png" % basename):
176         ppm_file = png_file_re.sub(".ppm", png_file)
177
178         p2p_cmd = '%s "%s"' % (pngtopnm, png_file)
179         p2p_status, p2p_stdout = run_command(p2p_cmd)
180         if p2p_status != None:
181             error("Unable to convert %s to ppm format" % png_file)
182
183         ppm = open(ppm_file, 'w')
184         ppm.write(p2p_stdout)
185         os.remove(png_file)
186
187
188 def main(argv):
189     # Parse and manipulate the command line arguments.
190     if len(argv) != 6 and len(argv) != 7:
191         error(usage(argv[0]))
192
193     output_format = string.lower(argv[1])
194
195     dir, latex_file = os.path.split(argv[2])
196     if len(dir) != 0:
197         os.chdir(dir)
198
199     dpi = string.atoi(argv[3])
200     fg_color = make_texcolor(argv[4], False)
201     bg_color = make_texcolor(argv[5], False)
202
203     fg_color_gr = make_texcolor(argv[4], True)
204     bg_color_gr = make_texcolor(argv[5], True)
205
206     # External programs used by the script.
207     path = string.split(os.environ["PATH"], os.pathsep)
208     if len(argv) == 7:
209         latex = argv[6]
210     else:
211         latex = find_exe_or_terminate(["latex", "pplatex", "platex", "latex2e"], path)
212
213     lilypond_book = find_exe_or_terminate(["lilypond-book"], path)
214
215     # Omit font size specification in latex file.
216     fix_latex_file(latex_file)
217
218     # Make a copy of the latex file
219     lytex_file = latex_file_re.sub(".lytex", latex_file)
220     shutil.copyfile(latex_file, lytex_file)
221
222     # Determine whether we need pdf or eps output
223     pdf_output = latex in ["lualatex", "pdflatex", "xelatex"]
224
225     # Preprocess the latex file through lilypond-book.
226     if pdf_output:
227         lytex_call = '%s --safe --pdf --latex-program=%s "%s"' % (lilypond_book, latex, lytex_file)
228     else:
229         lytex_call = '%s --safe --latex-program=%s "%s"' % (lilypond_book, latex, lytex_file)
230     lytex_status, lytex_stdout = run_command(lytex_call)
231     if lytex_status != None:
232         warning("%s failed to compile %s" \
233               % (os.path.basename(lilypond_book), lytex_file))
234         warning(lytex_stdout)
235
236     # This can go once dvipng becomes widespread.
237     dvipng = find_exe(["dvipng"], path)
238     if dvipng == None:
239         # The data is input to legacy_conversion in as similar
240         # as possible a manner to that input to the code used in
241         # LyX 1.3.x.
242         vec = [ argv[0], argv[2], argv[3], argv[1], argv[4], argv[5], latex ]
243         return legacy_conversion(vec)
244
245     pngtopnm = ""
246     if output_format == "ppm":
247         pngtopnm = find_exe_or_terminate(["pngtopnm"], path)
248
249     # Move color information for PDF into the latex file.
250     if not color_pdf(latex_file, bg_color_gr, fg_color_gr):
251         error("Unable to move color info into the latex file")
252
253     # Compile the latex file.
254     latex_call = '%s "%s"' % (latex, latex_file)
255
256     latex_status, latex_stdout = run_command(latex_call)
257     if latex_status != None:
258         warning("%s had problems compiling %s" \
259               % (os.path.basename(latex), latex_file))
260         warning(latex_stdout)
261
262     if latex == "xelatex":
263         warning("Using XeTeX")
264         # FIXME: skip unnecessary dvips trial in legacy_conversion_step2
265         return legacy_conversion_step2(latex_file, dpi, output_format)
266
267     # The dvi output file name
268     dvi_file = latex_file_re.sub(".dvi", latex_file)
269
270     # Check for PostScript specials in the dvi, badly supported by dvipng
271     # This is required for correct rendering of PSTricks and TikZ
272     dv2dt = find_exe_or_terminate(["dv2dt"], path)
273     dv2dt_call = '%s "%s"' % (dv2dt, dvi_file)
274  
275     # The output from dv2dt goes to stdout
276     dv2dt_status, dv2dt_output = run_command(dv2dt_call)
277     psliteral_re = re.compile("^special[1-4] [0-9]+ '(\"|ps:)")
278
279     # Parse the dtl file looking for PostScript specials.
280     # Pages using PostScript specials are recorded in ps_pages and then
281     # used to create a different LaTeX file for processing in legacy mode.
282     page_has_ps = False
283     page_index = 0
284     ps_pages = []
285
286     for line in dv2dt_output.split("\n"):
287         # New page
288         if line.startswith("bop"):
289             page_has_ps = False
290             page_index += 1
291
292         # End of page
293         if line.startswith("eop") and page_has_ps:
294             # We save in a list all the PostScript pages
295             ps_pages.append(page_index)
296
297         if psliteral_re.match(line) != None:
298             # Literal PostScript special detected!
299             page_has_ps = True
300
301     pages_parameter = ""
302     if len(ps_pages) == page_index:
303         # All pages need PostScript, so directly use the legacy method.
304         vec = [argv[0], argv[2], argv[3], argv[1], argv[4], argv[5], latex]
305         return legacy_conversion(vec)
306     elif len(ps_pages) > 0:
307         # Don't process Postscript pages with dvipng by selecting the
308         # wanted pages through the -pp parameter. E.g., dvipng -pp 4-12,14,64
309         pages_parameter = " -pp "
310         skip = True
311         last = -1
312
313         # Use page ranges, as a list of pages could exceed command line
314         # maximum length (especially under Win32)
315         for index in xrange(1, page_index + 1):
316             if (not index in ps_pages) and skip:
317                 # We were skipping pages but current page shouldn't be skipped.
318                 # Add this page to -pp, it could stay alone or become the
319                 # start of a range.
320                 pages_parameter += str(index)
321                 # Save the starting index to avoid things such as "11-11"
322                 last = index
323                 # We're not skipping anymore
324                 skip = False
325             elif (index in ps_pages) and (not skip):
326                 # We weren't skipping but current page should be skipped
327                 if last != index - 1:
328                     # If the start index of the range is the previous page
329                     # then it's not a range
330                     pages_parameter += "-" + str(index - 1)
331
332                 # Add a separator
333                 pages_parameter += ","
334                 # Now we're skipping
335                 skip = True
336
337         # Remove the trailing separator
338         pages_parameter = pages_parameter.rstrip(",")
339         # We've to manage the case in which the last page is closing a range
340         if (not index in ps_pages) and (not skip) and (last != index):
341                 pages_parameter += "-" + str(index)
342
343     # Run the dvi file through dvipng.
344     dvipng_call = '%s -Ttight -depth -height -D %d -fg "%s" -bg "%s" %s "%s"' \
345                   % (dvipng, dpi, fg_color, bg_color, pages_parameter, dvi_file)
346     dvipng_status, dvipng_stdout = run_command(dvipng_call)
347
348     if dvipng_status != None:
349         warning("%s failed to generate images from %s ... looking for PDF" \
350               % (os.path.basename(dvipng), dvi_file))
351         # FIXME: skip unnecessary dvips trial in legacy_conversion_step2
352         return legacy_conversion_step2(latex_file, dpi, output_format)
353
354     if len(ps_pages) > 0:
355         # Some pages require PostScript.
356         # Create a new LaTeX file just for the snippets needing
357         # the legacy method
358         original_latex = open(latex_file, "r")
359         legacy_latex_file = latex_file_re.sub("_legacy.tex", latex_file)
360         legacy_latex = open(legacy_latex_file, "w")
361
362         page_index = 0
363         skip_page = False
364         for line in original_latex:
365             if line.startswith("\\begin{preview}"):
366                 page_index += 1
367                 # Skips all pages processed by dvipng
368                 skip_page = page_index not in ps_pages
369
370             if not skip_page:
371                 legacy_latex.write(line)
372
373             if line.startswith("\\end{preview}"):
374                 skip_page = False
375
376         legacy_latex.close()
377         original_latex.close()
378
379         # Pass the new LaTeX file to the legacy method
380         vec = [ argv[0], latex_file_re.sub("_legacy.tex", argv[2]), \
381                 argv[3], argv[1], argv[4], argv[5], latex ]
382         legacy_conversion(vec, True)
383
384         # Now we need to mix metrics data from dvipng and the legacy method
385         metrics_file = latex_file_re.sub(".metrics", latex_file)
386
387         dvipng_metrics = extract_metrics_info(dvipng_stdout)
388         legacy_metrics = legacy_extract_metrics_info(latex_file_re.sub("_legacy.log", latex_file))
389         
390         # Check whether a page is present in dvipng_metrics, otherwise
391         # add it getting the metrics from legacy_metrics
392         legacy_index = -1;
393         for i in range(page_index):
394             # If we exceed the array bounds or the dvipng_metrics doesn't
395             # match the current one, this page belongs to the legacy method
396             if (i > len(dvipng_metrics) - 1) or (dvipng_metrics[i][0] != str(i + 1)):
397                 legacy_index += 1
398                 
399                 # Add this metric from the legacy output
400                 dvipng_metrics.insert(i, (str(i + 1), legacy_metrics[legacy_index][1]))
401                 # Legacy output filename
402                 legacy_output = os.path.join(dir, latex_file_re.sub("_legacy%s.%s" % 
403                     (legacy_metrics[legacy_index][0], output_format), latex_file))
404
405                 # Check whether legacy method actually created the file
406                 if os.path.isfile(legacy_output):
407                     # Rename the file by removing the "_legacy" suffix
408                     # and adjusting the index
409                     bitmap_output = os.path.join(dir, latex_file_re.sub("%s.%s" % 
410                         (str(i + 1), output_format), latex_file))
411                     os.rename(legacy_output, bitmap_output)
412
413         # Actually create the .metrics file
414         write_metrics_info(dvipng_metrics, metrics_file)
415     else:
416         # Extract metrics info from dvipng_stdout.
417         # In this case we just used dvipng, so no special metrics
418         # handling is needed.
419         metrics_file = latex_file_re.sub(".metrics", latex_file)
420         write_metrics_info(extract_metrics_info(dvipng_stdout), metrics_file)
421
422     # Convert images to ppm format if necessary.
423     if output_format == "ppm":
424         convert_to_ppm_format(pngtopnm, latex_file_re.sub("", latex_file))
425
426     return 0
427
428
429 if __name__ == "__main__":
430     main(sys.argv)