]> git.lyx.org Git - lyx.git/blob - lib/scripts/lyxpreview2bitmap.py
iucr.layout: use Item_Environment for a style as proposed by Jürgen
[lyx.git] / lib / scripts / lyxpreview2bitmap.py
1 # -*- coding: utf-8 -*-
2
3 # file lyxpreview2bitmap.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 # with much advice from members of the preview-latex project:
9 # David Kastrup, dak@gnu.org and
10 # Jan-Åke Larsson, jalar@mai.liu.se.
11
12 # Full author contact details are available in file CREDITS
13
14 # This script takes a LaTeX file and generates a collection of
15 # png or ppm image files, one per previewed snippet.
16
17 # Pre-requisites:
18 # * python 2.4 or later (subprocess module);
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 #   --bibtex=<exe>: The converter for bibtex files. Default is bibtex.
47 #   --lilypond:    Preprocess through lilypond-book. Default is false.
48 #   --lilypond-book=<exe>:
49 #                  The converter for lytex files. Default is lilypond-book.
50 #
51 #   -d, --debug    Show the output from external commands.
52 #   -h, --help     Show an help screen and exit.
53 #   -v, --verbose  Show progress messages.
54
55 # Decomposing TEXFILE's name as DIR/BASE.tex, this script will,
56 # if executed successfully, leave in DIR:
57 # * a (possibly large) number of image files with names
58 #   like BASE[0-9]+.png
59 # * a file BASE.metrics, containing info needed by LyX to position
60 #   the images correctly on the screen.
61
62 # What does this script do?
63 # 1) Call latex/pdflatex/xelatex/whatever (CONVERTER parameter)
64 # 2) If the output is a PDF fallback to legacy
65 # 3) Otherwise check each page of the DVI (with dv2dt) looking for
66 #    PostScript literals, not well supported by dvipng. Pages
67 #    containing them are passed to the legacy method in a new LaTeX file.
68 # 4) Call dvipng on the pages without PS literals
69 # 5) Join metrics info coming from both methods (legacy and dvipng)
70 #    and write them to file
71
72 # dvipng is fast but gives problem in several cases, like with
73 # PSTricks, TikZ and other packages using PostScript literals
74 # for all these cases the legacy route is taken (step 3).
75 # Moreover dvipng can't work with PDF files, so, if the CONVERTER
76 # paramter is pdflatex we have to fallback to legacy route (step 2).
77
78 import getopt, glob, os, re, shutil, string, sys
79
80 from legacy_lyxpreview2ppm import legacy_conversion_step1
81
82 from lyxpreview_tools import bibtex_commands, check_latex_log, copyfileobj, \
83      error, filter_pages, find_exe, find_exe_or_terminate, \
84      join_metrics_and_rename, latex_commands, latex_file_re, make_texcolor, \
85      mkstemp, pdflatex_commands, progress, run_command, run_latex, run_tex, \
86      warning, write_metrics_info
87
88
89 def usage(prog_name):
90     msg = """
91 Usage: %s <options> <input file>
92
93 Options:
94   --dpi=<res>:   Resolution per inch (default: 128)
95   --png, --ppm:  Select the output format (default: png)
96   --fg=<color>:  Foreground color (default: black, ie '000000')
97   --bg=<color>:  Background color (default: white, ie 'ffffff')
98   --latex=<exe>: Specify the executable for latex (default: latex)
99   --bibtex=<exe>: Specify the executable for bibtex (default: bibtex)
100   --lilypond:    Preprocess through lilypond-book (default: false)
101   --lilypond-book=<exe>:
102                  The executable for lilypond-book (default: lilypond-book)
103
104   -d, --debug:   Show the output from external commands
105   -h, --help:    Show this help screen and exit
106   -v, --verbose: Show progress messages
107
108 The colors are hexadecimal strings, eg 'faf0e6'."""
109     return msg % prog_name
110
111 # Returns a list of tuples containing page number and ascent fraction
112 # extracted from dvipng output.
113 # Use write_metrics_info to create the .metrics file with this info
114 def extract_metrics_info(dvipng_stdout):
115     # "\[[0-9]+" can match two kinds of numbers: page numbers from dvipng
116     # and glyph numbers from mktexpk. The glyph numbers always match
117     # "\[[0-9]+\]" while the page number never is followed by "\]". Thus:
118     page_re = re.compile("\[([0-9]+)[^]]");
119     metrics_re = re.compile("depth=(-?[0-9]+) height=(-?[0-9]+)")
120
121     success = 0
122     page = ""
123     pos = 0
124     results = []
125     while 1:
126         match = page_re.search(dvipng_stdout, pos)
127         if match == None:
128             break
129         page = match.group(1)
130         pos = match.end()
131         match = metrics_re.search(dvipng_stdout, pos)
132         if match == None:
133             break
134         success = 1
135
136         # Calculate the 'ascent fraction'.
137         descent = string.atof(match.group(1))
138         ascent  = string.atof(match.group(2))
139
140         frac = 0.5
141         if ascent < 0:
142             # This is an empty image, forbid its display
143             frac = -1.0
144         elif ascent >= 0 or descent >= 0:
145             if abs(ascent + descent) > 0.1:
146                 frac = ascent / (ascent + descent)
147
148             # Sanity check
149             if frac < 0:
150                 frac = 0.5
151
152         results.append((int(page), frac))
153         pos = match.end() + 2
154
155     if success == 0:
156         error("Failed to extract metrics info from dvipng")
157
158     return results
159
160
161 def fix_latex_file(latex_file):
162     documentclass_re = re.compile("(\\\\documentclass\[)(1[012]pt,?)(.+)")
163
164     tmp = mkstemp()
165
166     changed = 0
167     for line in open(latex_file, 'r').readlines():
168         match = documentclass_re.match(line)
169         if match == None:
170             tmp.write(line)
171             continue
172
173         changed = 1
174         tmp.write("%s%s\n" % (match.group(1), match.group(3)))
175
176     if changed:
177         copyfileobj(tmp, open(latex_file,"wb"), 1)
178
179     return changed
180
181
182 def convert_to_ppm_format(pngtopnm, basename):
183     png_file_re = re.compile("\.png$")
184
185     for png_file in glob.glob("%s*.png" % basename):
186         ppm_file = png_file_re.sub(".ppm", png_file)
187
188         p2p_cmd = '%s "%s"' % (pngtopnm, png_file)
189         p2p_status, p2p_stdout = run_command(p2p_cmd)
190         if p2p_status:
191             error("Unable to convert %s to ppm format" % png_file)
192
193         ppm = open(ppm_file, 'w')
194         ppm.write(p2p_stdout)
195         os.remove(png_file)
196
197 # Returns a tuple of:
198 # ps_pages: list of page indexes of pages containing PS literals
199 # pdf_pages: list of page indexes of pages requiring running pdflatex
200 # page_count: total number of pages
201 # pages_parameter: parameter for dvipng to exclude pages with PostScript/PDF
202 def find_ps_pages(dvi_file):
203     # latex failed
204     # FIXME: try with pdflatex
205     if not os.path.isfile(dvi_file):
206         error("No DVI output.")
207
208     # Check for PostScript specials in the dvi, badly supported by dvipng,
209     # and inclusion of PDF/PNG/JPG files. 
210     # This is required for correct rendering of PSTricks and TikZ
211     dv2dt = find_exe_or_terminate(["dv2dt"])
212     dv2dt_call = '%s "%s"' % (dv2dt, dvi_file)
213
214     # The output from dv2dt goes to stdout
215     dv2dt_status, dv2dt_output = run_command(dv2dt_call)
216     psliteral_re = re.compile("^special[1-4] [0-9]+ '(\"|ps:)")
217     hyperref_re = re.compile("^special[1-4] [0-9]+ 'ps:.*/DEST pdfmark")
218     pdffile_re = re.compile("^special[1-4] [0-9]+ 'PSfile=.*\\.(pdf|png|jpg|jpeg|PDF|PNG|JPG|JPEG)")
219
220     # Parse the dtl file looking for PostScript specials and pdflatex files.
221     # Pages using PostScript specials or pdflatex files are recorded in
222     # ps_pages or pdf_pages, respectively, and then used to create a
223     # different LaTeX file for processing in legacy mode.
224     # If hyperref is detected, the corresponding page is recorded in pdf_pages.
225     page_has_ps = False
226     page_has_pdf = False
227     page_index = 0
228     ps_pages = []
229     pdf_pages = []
230     ps_or_pdf_pages = []
231
232     for line in dv2dt_output.split("\n"):
233         # New page
234         if line.startswith("bop"):
235             page_has_ps = False
236             page_has_pdf = False
237             page_index += 1
238
239         # End of page
240         if line.startswith("eop") and (page_has_ps or page_has_pdf):
241             # We save in a list all the PostScript/PDF pages
242             if page_has_ps:
243                 ps_pages.append(page_index)
244             else:
245                 pdf_pages.append(page_index)
246             ps_or_pdf_pages.append(page_index)
247
248         if psliteral_re.match(line) != None:
249             # Literal PostScript special detected!
250             # If hyperref is detected, put this page on the pdf pages list
251             if hyperref_re.match(line) != None:
252                 page_has_ps = False
253                 page_has_pdf = True
254             else:
255                 page_has_ps = True
256         elif pdffile_re.match(line) != None:
257             # Inclusion of pdflatex image file detected!
258             page_has_pdf = True
259
260     # Create the -pp parameter for dvipng
261     pages_parameter = ""
262     if len(ps_or_pdf_pages) > 0 and len(ps_or_pdf_pages) < page_index:
263         # Don't process Postscript/PDF pages with dvipng by selecting the
264         # wanted pages through the -pp parameter. E.g., dvipng -pp 4-12,14,64
265         pages_parameter = " -pp "
266         skip = True
267         last = -1
268
269         # Use page ranges, as a list of pages could exceed command line
270         # maximum length (especially under Win32)
271         for index in xrange(1, page_index + 1):
272             if (not index in ps_or_pdf_pages) and skip:
273                 # We were skipping pages but current page shouldn't be skipped.
274                 # Add this page to -pp, it could stay alone or become the
275                 # start of a range.
276                 pages_parameter += str(index)
277                 # Save the starting index to avoid things such as "11-11"
278                 last = index
279                 # We're not skipping anymore
280                 skip = False
281             elif (index in ps_or_pdf_pages) and (not skip):
282                 # We weren't skipping but current page should be skipped
283                 if last != index - 1:
284                     # If the start index of the range is the previous page
285                     # then it's not a range
286                     pages_parameter += "-" + str(index - 1)
287
288                 # Add a separator
289                 pages_parameter += ","
290                 # Now we're skipping
291                 skip = True
292
293         # Remove the trailing separator
294         pages_parameter = pages_parameter.rstrip(",")
295         # We've to manage the case in which the last page is closing a range
296         if (not index in ps_or_pdf_pages) and (not skip) and (last != index):
297                 pages_parameter += "-" + str(index)
298
299     return (ps_pages, pdf_pages, page_index, pages_parameter)
300
301 def main(argv):
302     # Set defaults.
303     dpi = 128
304     fg_color = "000000"
305     bg_color = "ffffff"
306     bibtex = None
307     latex = None
308     lilypond = False
309     lilypond_book = None
310     output_format = "png"
311     script_name = argv[0]
312
313     # Parse and manipulate the command line arguments.
314     try:
315         (opts, args) = getopt.gnu_getopt(argv[1:], "dhv", ["bibtex=", "bg=",
316             "debug", "dpi=", "fg=", "help", "latex=", "lilypond",
317             "lilypond-book=", "png", "ppm", "verbose"])
318     except getopt.GetoptError, err:
319         error("%s\n%s" % (err, usage(script_name)))
320
321     opts.reverse()
322     for opt, val in opts:
323         if opt in ("-h", "--help"):
324             print usage(script_name)
325             sys.exit(0)
326         elif opt == "--bibtex":
327             bibtex = [val]
328         elif opt == "--bg":
329             bg_color = val
330         elif opt in ("-d", "--debug"):
331             import lyxpreview_tools
332             lyxpreview_tools.debug = True
333         elif opt == "--dpi":
334             try:
335                 dpi = string.atoi(val)
336             except:
337                 error("Cannot convert %s to an integer value" % val)
338         elif opt == "--fg":
339             fg_color = val
340         elif opt == "--latex":
341             latex = [val]
342         elif opt == "--lilypond":
343             lilypond = True
344         elif opt == "--lilypond-book":
345             lilypond_book = [val]
346         elif opt in ("--png", "--ppm"):
347             output_format = opt[2:]
348         elif opt in ("-v", "--verbose"):
349             import lyxpreview_tools
350             lyxpreview_tools.verbose = True
351
352     # Determine input file
353     if len(args) != 1:
354         err = "A single input file is required, %s given" % (len(args) or "none")
355         error("%s\n%s" % (err, usage(script_name)))
356
357     input_path = args[0]
358     dir, latex_file = os.path.split(input_path)
359
360     # Echo the settings
361     progress("Starting %s..." % script_name)
362     progress("Output format: %s" % output_format)
363     progress("Foreground color: %s" % fg_color)
364     progress("Background color: %s" % bg_color)
365     progress("Resolution (dpi): %s" % dpi)
366     progress("File to process: %s" % input_path)
367
368     # Check for the input file
369     if not os.path.exists(input_path):
370         error('File "%s" not found.' % input_path)
371     if len(dir) != 0:
372         os.chdir(dir)
373
374     fg_color_dvipng = make_texcolor(fg_color, False)
375     bg_color_dvipng = make_texcolor(bg_color, False)
376
377     # External programs used by the script.
378     latex = find_exe_or_terminate(latex or latex_commands)
379     bibtex = find_exe(bibtex or bibtex_commands)
380     if lilypond:
381         lilypond_book = find_exe_or_terminate(lilypond_book or
382             ["lilypond-book --safe"])
383
384     # These flavors of latex are known to produce pdf output
385     pdf_output = latex in pdflatex_commands
386
387     progress("Latex command: %s" % latex)
388     progress("Latex produces pdf output: %s" % pdf_output)
389     progress("Bibtex command: %s" % bibtex)
390     progress("Lilypond-book command: %s" % lilypond_book)
391     progress("Preprocess through lilypond-book: %s" % lilypond)
392     progress("Altering the latex file for font size and colors")
393
394     # Omit font size specification in latex file and make sure multiple
395     # defined macros are not an issue.
396     fix_latex_file(latex_file)
397
398     if lilypond:
399         progress("Preprocess the latex file through %s" % lilypond_book)
400         if pdf_output:
401             lilypond_book += " --pdf"
402         lilypond_book += " --latex-program=%s" % latex.split()[0]
403
404         # Make a copy of the latex file
405         lytex_file = latex_file_re.sub(".lytex", latex_file)
406         shutil.copyfile(latex_file, lytex_file)
407
408         # Preprocess the latex file through lilypond-book.
409         lytex_status, lytex_stdout = run_tex(lilypond_book, lytex_file)
410
411     if pdf_output:
412         progress("Using the legacy conversion method (PDF support)")
413         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
414             bg_color, latex, pdf_output)
415
416     # This can go once dvipng becomes widespread.
417     dvipng = find_exe(["dvipng"])
418     if dvipng == None:
419         progress("Using the legacy conversion method (dvipng not found)")
420         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
421             bg_color, latex, pdf_output)
422
423     dv2dt = find_exe(["dv2dt"])
424     if dv2dt == None:
425         progress("Using the legacy conversion method (dv2dt not found)")
426         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
427             bg_color, latex, pdf_output)
428
429     pngtopnm = ""
430     if output_format == "ppm":
431         pngtopnm = find_exe(["pngtopnm"])
432         if pngtopnm == None:
433             progress("Using the legacy conversion method (pngtopnm not found)")
434             return legacy_conversion_step1(latex_file, dpi, output_format,
435                 fg_color, bg_color, latex, pdf_output)
436
437     # Compile the latex file.
438     error_pages = []
439     latex_status, latex_stdout = run_latex(latex, latex_file, bibtex)
440     if latex_status:
441         warning("trying to recover from failed compilation")
442         error_pages = check_latex_log(latex_file_re.sub(".log", latex_file))
443
444     # The dvi output file name
445     dvi_file = latex_file_re.sub(".dvi", latex_file)
446
447     # If there's no DVI output, look for PDF and go to legacy or fail
448     if not os.path.isfile(dvi_file):
449         # No DVI, is there a PDF?
450         pdf_file = latex_file_re.sub(".pdf", latex_file)
451         if os.path.isfile(pdf_file):
452             progress("%s produced a PDF output, fallback to legacy." \
453                 % (os.path.basename(latex)))
454             progress("Using the legacy conversion method (PDF support)")
455             return legacy_conversion_step1(latex_file, dpi, output_format,
456                 fg_color, bg_color, latex, True)
457         else:
458             error("No DVI or PDF output. %s failed." \
459                 % (os.path.basename(latex)))
460
461     # Look for PS literals or inclusion of pdflatex files in DVI pages
462     # ps_pages: list of indexes of pages containing PS literals
463     # pdf_pages: list of indexes of pages requiring running pdflatex
464     # page_count: total number of pages
465     # pages_parameter: parameter for dvipng to exclude pages with PostScript
466     (ps_pages, pdf_pages, page_count, pages_parameter) = find_ps_pages(dvi_file)
467
468     # If all pages need PostScript or pdflatex, directly use the legacy method.
469     if len(ps_pages) == page_count:
470         progress("Using the legacy conversion method (PostScript support)")
471         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
472             bg_color, latex, pdf_output)
473     elif len(pdf_pages) == page_count:
474         progress("Using the legacy conversion method (PDF support)")
475         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
476             bg_color, "pdflatex", True)
477
478     # Run the dvi file through dvipng.
479     dvipng_call = '%s -Ttight -depth -height -D %d -fg "%s" -bg "%s" %s "%s"' \
480         % (dvipng, dpi, fg_color_dvipng, bg_color_dvipng, pages_parameter, dvi_file)
481     dvipng_status, dvipng_stdout = run_command(dvipng_call)
482
483     if dvipng_status:
484         warning("%s failed to generate images from %s... fallback to legacy method" \
485               % (os.path.basename(dvipng), dvi_file))
486         progress("Using the legacy conversion method (dvipng failed)")
487         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
488             bg_color, latex, pdf_output)
489
490     # Extract metrics info from dvipng_stdout.
491     metrics_file = latex_file_re.sub(".metrics", latex_file)
492     dvipng_metrics = extract_metrics_info(dvipng_stdout)
493
494     # If some pages require PostScript pass them to legacy method
495     if len(ps_pages) > 0:
496         # Create a new LaTeX file just for the snippets needing
497         # the legacy method
498         legacy_latex_file = latex_file_re.sub("_legacy.tex", latex_file)
499         filter_pages(latex_file, legacy_latex_file, ps_pages)
500
501         # Pass the new LaTeX file to the legacy method
502         progress("Pages %s include postscript specials" % ps_pages)
503         progress("Using the legacy conversion method (PostScript support)")
504         legacy_status, legacy_metrics = legacy_conversion_step1(legacy_latex_file,
505             dpi, output_format, fg_color, bg_color, latex, pdf_output, True)
506
507         # Now we need to mix metrics data from dvipng and the legacy method
508         original_bitmap = latex_file_re.sub("%d." + output_format, legacy_latex_file)
509         destination_bitmap = latex_file_re.sub("%d." + output_format, latex_file)
510
511         # Join metrics from dvipng and legacy, and rename legacy bitmaps
512         join_metrics_and_rename(dvipng_metrics, legacy_metrics, ps_pages,
513             original_bitmap, destination_bitmap)
514
515     # If some pages require running pdflatex pass them to legacy method
516     if len(pdf_pages) > 0:
517         # Create a new LaTeX file just for the snippets needing
518         # the legacy method
519         legacy_latex_file = latex_file_re.sub("_legacy.tex", latex_file)
520         filter_pages(latex_file, legacy_latex_file, pdf_pages)
521
522         # Pass the new LaTeX file to the legacy method
523         progress("Pages %s require processing with pdflatex" % pdf_pages)
524         progress("Using the legacy conversion method (PDF support)")
525         legacy_status, legacy_metrics = legacy_conversion_step1(legacy_latex_file,
526             dpi, output_format, fg_color, bg_color, "pdflatex", True, True)
527
528         # Now we need to mix metrics data from dvipng and the legacy method
529         original_bitmap = latex_file_re.sub("%d." + output_format, legacy_latex_file)
530         destination_bitmap = latex_file_re.sub("%d." + output_format, latex_file)
531
532         # Join metrics from dvipng and legacy, and rename legacy bitmaps
533         join_metrics_and_rename(dvipng_metrics, legacy_metrics, pdf_pages,
534             original_bitmap, destination_bitmap)
535
536     # Invalidate metrics for pages that produced errors
537     if len(error_pages) > 0:
538         for index in error_pages:
539             if index not in ps_pages and index not in pdf_pages:
540                 dvipng_metrics.pop(index - 1)
541                 dvipng_metrics.insert(index - 1, (index, -1.0))
542
543     # Convert images to ppm format if necessary.
544     if output_format == "ppm":
545         convert_to_ppm_format(pngtopnm, latex_file_re.sub("", latex_file))
546
547     # Actually create the .metrics file
548     write_metrics_info(dvipng_metrics, metrics_file)
549
550     return (0, dvipng_metrics)
551
552 if __name__ == "__main__":
553     sys.exit(main(sys.argv)[0])