]> git.lyx.org Git - lyx.git/blob - lib/scripts/lyxpreview2bitmap.py
72e6322242638b09a564a51119397b06d472c09a
[lyx.git] / lib / scripts / lyxpreview2bitmap.py
1 #! /usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 # file lyxpreview2bitmap.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 # * dv2dt;
23 # * pngtoppm (if outputing ppm format images).
24
25 # preview.sty and dvipng are part of the preview-latex project
26 # http://preview-latex.sourceforge.net/
27
28 # preview.sty can alternatively be obtained from
29 # CTAN/support/preview-latex/
30
31 # Example usage:
32 # lyxpreview2bitmap.py --bg=faf0e6 0lyxpreview.tex
33
34 # This script takes one obligatory argument:
35 #
36 #   <input file>:  The name of the .tex file to be converted.
37 #
38 # and these optional arguments:
39 #
40 #   --png, --ppm:  The desired output format. Either 'png' or 'ppm'.
41 #   --dpi=<res>:   A scale factor, used to ascertain the resolution of the
42 #                  generated image which is then passed to gs.
43 #   --fg=<color>:  The foreground color as a hexadecimal string, eg '000000'.
44 #   --bg=<color>:  The background color as a hexadecimal string, eg 'faf0e6'.
45 #   --latex=<exe>: The converter for latex files. Default is latex.
46 #   --lilypond:    Preprocess through lilypond-book. Default is false.
47 #   --lilypond-book=<exe>:
48 #                  The converter for lytex files. Default is lilypond-book.
49
50 # Decomposing TEXFILE's name as DIR/BASE.tex, this script will,
51 # if executed successfully, leave in DIR:
52 # * a (possibly large) number of image files with names
53 #   like BASE[0-9]+.png
54 # * a file BASE.metrics, containing info needed by LyX to position
55 #   the images correctly on the screen.
56
57 # What does this script do?
58 # 1) Call latex/pdflatex/xelatex/whatever (CONVERTER parameter)
59 # 2) If the output is a PDF fallback to legacy
60 # 3) Otherwise check each page of the DVI (with dv2dt) looking for
61 #    PostScript literals, not well supported by dvipng. Pages
62 #    containing them are passed to the legacy method in a new LaTeX file.
63 # 4) Call dvipng on the pages without PS literals
64 # 5) Join metrics info coming from both methods (legacy and dvipng)
65 #    and write them to file
66
67 # dvipng is fast but gives problem in several cases, like with
68 # PSTricks, TikZ and other packages using PostScript literals
69 # for all these cases the legacy route is taken (step 3).
70 # Moreover dvipng can't work with PDF files, so, if the CONVERTER
71 # paramter is pdflatex we have to fallback to legacy route (step 2).
72
73 import getopt, glob, os, re, shutil, string, sys
74
75 from legacy_lyxpreview2ppm import legacy_conversion, \
76      legacy_conversion_step2, legacy_extract_metrics_info
77
78 from lyxpreview_tools import copyfileobj, error, filter_pages, find_exe, \
79      find_exe_or_terminate, join_metrics_and_rename, latex_commands, \
80      latex_file_re, make_texcolor, mkstemp, pdflatex_commands, run_command, \
81      warning, write_metrics_info
82
83
84 def usage(prog_name):
85     msg = """
86 Usage: %s <options> <input file>
87
88 Options:
89   -h, --help:    Show this help and exit
90   --dpi=<res>:   Resolution per inch (default: 128)
91   --png, --ppm:  Select the output format (default: png)
92   --fg=<color>:  Foreground color (default: black, ie '000000')
93   --bg=<color>:  Background color (default: white, ie 'ffffff')
94   --latex=<exe>: Specify the executable for latex (default: latex)
95   --lilypond:    Preprocess through lilypond-book (default: false)
96   --lilypond-book=<exe>:
97                  The executable for lilypond-book (default: lilypond-book)
98
99 The colors are hexadecimal strings, eg 'faf0e6'."""
100     return msg % prog_name
101
102 # Returns a list of tuples containing page number and ascent fraction
103 # extracted from dvipng output.
104 # Use write_metrics_info to create the .metrics file with this info
105 def extract_metrics_info(dvipng_stdout):
106     # "\[[0-9]+" can match two kinds of numbers: page numbers from dvipng
107     # and glyph numbers from mktexpk. The glyph numbers always match
108     # "\[[0-9]+\]" while the page number never is followed by "\]". Thus:
109     page_re = re.compile("\[([0-9]+)[^]]");
110     metrics_re = re.compile("depth=(-?[0-9]+) height=(-?[0-9]+)")
111
112     success = 0
113     page = ""
114     pos = 0
115     results = []
116     while 1:
117         match = page_re.search(dvipng_stdout, pos)
118         if match == None:
119             break
120         page = match.group(1)
121         pos = match.end()
122         match = metrics_re.search(dvipng_stdout, pos)
123         if match == None:
124             break
125         success = 1
126
127         # Calculate the 'ascent fraction'.
128         descent = string.atof(match.group(1))
129         ascent  = string.atof(match.group(2))
130
131         frac = 0.5
132         if ascent >= 0 or descent >= 0:
133             if abs(ascent + descent) > 0.1:
134                 frac = ascent / (ascent + descent)
135
136             # Sanity check
137             if frac < 0:
138                 frac = 0.5
139
140         results.append((int(page), frac))
141         pos = match.end() + 2
142
143     if success == 0:
144         error("Failed to extract metrics info from dvipng")
145
146     return results
147
148
149 def color_pdf(latex_file, bg_color, fg_color):
150     use_preview_pdf_re = re.compile("(\s*\\\\usepackage\[[^]]+)((pdftex|xetex)\]{preview})")
151
152     tmp = mkstemp()
153
154     fg = ""
155     if fg_color != "0.000000,0.000000,0.000000":
156         fg = '  \\AtBeginDocument{\\let\\oldpreview\\preview\\renewcommand\\preview{\\oldpreview\\color[rgb]{%s}}}\n' % (fg_color)
157
158     success = 0
159     try:
160         for line in open(latex_file, 'r').readlines():
161             match = use_preview_pdf_re.match(line)
162             if match == None:
163                 tmp.write(line)
164                 continue
165             success = 1
166             tmp.write("  \\usepackage{color}\n" \
167                   "  \\pagecolor[rgb]{%s}\n" \
168                   "%s" \
169                   "%s\n" \
170                   % (bg_color, fg, match.group()))
171             continue
172
173     except:
174         # Unable to open the file, but do nothing here because
175         # the calling function will act on the value of 'success'.
176         warning('Warning in color_pdf! Unable to open "%s"' % latex_file)
177         warning(`sys.exc_type` + ',' + `sys.exc_value`)
178
179     if success:
180         copyfileobj(tmp, open(latex_file,"wb"), 1)
181
182     return success
183
184
185 def fix_latex_file(latex_file):
186     documentclass_re = re.compile("(\\\\documentclass\[)(1[012]pt,?)(.+)")
187
188     tmp = mkstemp()
189
190     changed = 0
191     for line in open(latex_file, 'r').readlines():
192         match = documentclass_re.match(line)
193         if match == None:
194             tmp.write(line)
195             continue
196
197         changed = 1
198         tmp.write("%s%s\n" % (match.group(1), match.group(3)))
199
200     if changed:
201         copyfileobj(tmp, open(latex_file,"wb"), 1)
202
203     return
204
205
206 def convert_to_ppm_format(pngtopnm, basename):
207     png_file_re = re.compile("\.png$")
208
209     for png_file in glob.glob("%s*.png" % basename):
210         ppm_file = png_file_re.sub(".ppm", png_file)
211
212         p2p_cmd = '%s "%s"' % (pngtopnm, png_file)
213         p2p_status, p2p_stdout = run_command(p2p_cmd)
214         if p2p_status != None:
215             error("Unable to convert %s to ppm format" % png_file)
216
217         ppm = open(ppm_file, 'w')
218         ppm.write(p2p_stdout)
219         os.remove(png_file)
220
221 # Returns a tuple of:
222 # ps_pages: list of page indexes of pages containing PS literals
223 # page_count: total number of pages
224 # pages_parameter: parameter for dvipng to exclude pages with PostScript
225 def find_ps_pages(dvi_file):
226     # latex failed
227     # FIXME: try with pdflatex
228     if not os.path.isfile(dvi_file):
229         error("No DVI output.")
230
231     # Check for PostScript specials in the dvi, badly supported by dvipng
232     # This is required for correct rendering of PSTricks and TikZ
233     dv2dt = find_exe_or_terminate(["dv2dt"])
234     dv2dt_call = '%s "%s"' % (dv2dt, dvi_file)
235
236     # The output from dv2dt goes to stdout
237     dv2dt_status, dv2dt_output = run_command(dv2dt_call)
238     psliteral_re = re.compile("^special[1-4] [0-9]+ '(\"|ps:)")
239
240     # Parse the dtl file looking for PostScript specials.
241     # Pages using PostScript specials are recorded in ps_pages and then
242     # used to create a different LaTeX file for processing in legacy mode.
243     page_has_ps = False
244     page_index = 0
245     ps_pages = []
246
247     for line in dv2dt_output.split("\n"):
248         # New page
249         if line.startswith("bop"):
250             page_has_ps = False
251             page_index += 1
252
253         # End of page
254         if line.startswith("eop") and page_has_ps:
255             # We save in a list all the PostScript pages
256             ps_pages.append(page_index)
257
258         if psliteral_re.match(line) != None:
259             # Literal PostScript special detected!
260             page_has_ps = True
261
262     # Create the -pp parameter for dvipng
263     pages_parameter = ""
264     if len(ps_pages) > 0 and len(ps_pages) < page_index:
265         # Don't process Postscript pages with dvipng by selecting the
266         # wanted pages through the -pp parameter. E.g., dvipng -pp 4-12,14,64
267         pages_parameter = " -pp "
268         skip = True
269         last = -1
270
271         # Use page ranges, as a list of pages could exceed command line
272         # maximum length (especially under Win32)
273         for index in xrange(1, page_index + 1):
274             if (not index in ps_pages) and skip:
275                 # We were skipping pages but current page shouldn't be skipped.
276                 # Add this page to -pp, it could stay alone or become the
277                 # start of a range.
278                 pages_parameter += str(index)
279                 # Save the starting index to avoid things such as "11-11"
280                 last = index
281                 # We're not skipping anymore
282                 skip = False
283             elif (index in ps_pages) and (not skip):
284                 # We weren't skipping but current page should be skipped
285                 if last != index - 1:
286                     # If the start index of the range is the previous page
287                     # then it's not a range
288                     pages_parameter += "-" + str(index - 1)
289
290                 # Add a separator
291                 pages_parameter += ","
292                 # Now we're skipping
293                 skip = True
294
295         # Remove the trailing separator
296         pages_parameter = pages_parameter.rstrip(",")
297         # We've to manage the case in which the last page is closing a range
298         if (not index in ps_pages) and (not skip) and (last != index):
299                 pages_parameter += "-" + str(index)
300
301     return (ps_pages, page_index, pages_parameter)
302
303 def main(argv):
304     # Set defaults.
305     dpi = 128
306     fg_color = "000000"
307     bg_color = "ffffff"
308     latex = None
309     lilypond = False
310     lilypond_book = None
311     output_format = "png"
312     script_name = argv[0]
313
314     # Parse and manipulate the command line arguments.
315     try:
316         (opts, args) = getopt.gnu_getopt(argv[1:], "h", ["bg=",
317             "dpi=", "fg=", "help", "latex=", "lilypond", "lilypond-book=",
318             "png", "ppm"])
319     except getopt.GetoptError:
320         error(usage(script_name))
321
322     opts.reverse()
323     for opt, val in opts:
324         if opt in ("-h", "--help"):
325             print usage(script_name)
326             sys.exit(0)
327         elif opt == "--bg":
328             bg_color = val
329         elif opt == "--dpi":
330             try:
331                 dpi = string.atoi(val)
332             except:
333                 error("Cannot convert %s to an integer value" % val)
334         elif opt == "--fg":
335             fg_color = val
336         elif opt == "--latex":
337             latex = [val]
338         elif opt == "--lilypond":
339             lilypond = True
340         elif opt == "--lilypond-book":
341             lilypond_book = [val]
342         elif opt in ("--png", "--ppm"):
343             output_format = opt[2:]
344
345     if len(args) != 1:
346         error(usage(script_name))
347
348     input_path = args[0]
349     dir, latex_file = os.path.split(input_path)
350     if len(dir) != 0:
351         os.chdir(dir)
352
353     fg_color_dvipng = make_texcolor(fg_color, False)
354     bg_color_dvipng = make_texcolor(bg_color, False)
355
356     fg_color_gr = make_texcolor(fg_color, True)
357     bg_color_gr = make_texcolor(bg_color, True)
358
359     # External programs used by the script.
360     latex = find_exe_or_terminate(latex or latex_commands)
361     if lilypond:
362         lilypond_book = find_exe_or_terminate(lilypond_book or ["lilypond-book"])
363
364     # These flavors of latex are known to produce pdf output
365     pdf_output = latex in pdflatex_commands
366
367     # Omit font size specification in latex file.
368     fix_latex_file(latex_file)
369
370     if lilypond:
371         if pdf_output:
372             lilypond_book += ' --pdf'
373
374         # Make a copy of the latex file
375         lytex_file = latex_file_re.sub(".lytex", latex_file)
376         shutil.copyfile(latex_file, lytex_file)
377
378         # Preprocess the latex file through lilypond-book.
379         lytex_call = '%s --safe --latex-program=%s "%s"' % (lilypond_book,
380             latex, lytex_file)
381         lytex_status, lytex_stdout = run_command(lytex_call)
382         if lytex_status != None:
383             warning("%s failed to compile %s" \
384                 % (os.path.basename(lilypond_book), lytex_file))
385
386     # This can go once dvipng becomes widespread.
387     dvipng = find_exe(["dvipng"])
388     if dvipng == None:
389         # The data is input to legacy_conversion in as similar
390         # as possible a manner to that input to the code used in
391         # LyX 1.3.x.
392         vec = [ script_name, input_path, str(dpi), output_format, fg_color, bg_color, latex ]
393         return legacy_conversion(vec)
394
395     pngtopnm = ""
396     if output_format == "ppm":
397         pngtopnm = find_exe_or_terminate(["pngtopnm"])
398
399     # Move color information for PDF into the latex file.
400     if not color_pdf(latex_file, bg_color_gr, fg_color_gr):
401         error("Unable to move color info into the latex file")
402
403     # Compile the latex file.
404     latex_call = '%s "%s"' % (latex, latex_file)
405
406     latex_status, latex_stdout = run_command(latex_call)
407     if latex_status != None:
408         warning("%s had problems compiling %s" \
409               % (os.path.basename(latex), latex_file))
410
411     if latex == "xelatex":
412         warning("Using XeTeX")
413         # FIXME: skip unnecessary dvips trial in legacy_conversion_step2
414         return legacy_conversion_step2(latex_file, dpi, output_format)
415
416     # The dvi output file name
417     dvi_file = latex_file_re.sub(".dvi", latex_file)
418
419     # If there's no DVI output, look for PDF and go to legacy or fail
420     if not os.path.isfile(dvi_file):
421         # No DVI, is there a PDF?
422         pdf_file = latex_file_re.sub(".pdf", latex_file)
423         if os.path.isfile(pdf_file):
424             warning("%s produced a PDF output, fallback to legacy." % \
425                 (os.path.basename(latex)))
426             return legacy_conversion_step2(latex_file, dpi, output_format)
427         else:
428             error("No DVI or PDF output. %s failed." \
429                 % (os.path.basename(latex)))
430
431     # Look for PS literals in DVI pages
432     # ps_pages: list of page indexes of pages containing PS literals
433     # page_count: total number of pages
434     # pages_parameter: parameter for dvipng to exclude pages with PostScript
435     (ps_pages, page_count, pages_parameter) = find_ps_pages(dvi_file)
436
437     # If all pages need PostScript, directly use the legacy method.
438     if len(ps_pages) == page_count:
439         vec = [ script_name, input_path, str(dpi), output_format, fg_color, bg_color, latex ]
440         return legacy_conversion(vec)
441
442     # Run the dvi file through dvipng.
443     dvipng_call = '%s -Ttight -depth -height -D %d -fg "%s" -bg "%s" %s "%s"' \
444         % (dvipng, dpi, fg_color_dvipng, bg_color_dvipng, pages_parameter, dvi_file)
445     dvipng_status, dvipng_stdout = run_command(dvipng_call)
446
447     if dvipng_status != None:
448         warning("%s failed to generate images from %s... fallback to legacy method" \
449               % (os.path.basename(dvipng), dvi_file))
450         # FIXME: skip unnecessary dvips trial in legacy_conversion_step2
451         return legacy_conversion_step2(latex_file, dpi, output_format)
452
453     # Extract metrics info from dvipng_stdout.
454     metrics_file = latex_file_re.sub(".metrics", latex_file)
455     dvipng_metrics = extract_metrics_info(dvipng_stdout)
456
457     # If some pages require PostScript pass them to legacy method
458     if len(ps_pages) > 0:
459         # Create a new LaTeX file just for the snippets needing
460         # the legacy method
461         legacy_latex_file = latex_file_re.sub("_legacy.tex", latex_file)
462         filter_pages(latex_file, legacy_latex_file, ps_pages)
463
464         # Pass the new LaTeX file to the legacy method
465         vec = [ script_name, latex_file_re.sub("_legacy.tex", input_path),
466                 str(dpi), output_format, fg_color, bg_color, latex ]
467         legacy_metrics = legacy_conversion(vec, True)[1]
468
469         # Now we need to mix metrics data from dvipng and the legacy method
470         original_bitmap = latex_file_re.sub("%d." + output_format, legacy_latex_file)
471         destination_bitmap = latex_file_re.sub("%d." + output_format, latex_file)
472
473         # Join metrics from dvipng and legacy, and rename legacy bitmaps
474         join_metrics_and_rename(dvipng_metrics, legacy_metrics, ps_pages,
475             original_bitmap, destination_bitmap)
476
477     # Convert images to ppm format if necessary.
478     if output_format == "ppm":
479         convert_to_ppm_format(pngtopnm, latex_file_re.sub("", latex_file))
480
481     # Actually create the .metrics file
482     write_metrics_info(dvipng_metrics, metrics_file)
483
484     return (0, dvipng_metrics)
485
486 if __name__ == "__main__":
487     exit(main(sys.argv)[0])