]> git.lyx.org Git - lyx.git/blob - lib/scripts/lyxpreview2bitmap.py
The way this was previously, it had to fail if the GUI language
[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 extract_resolution, 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, pdf_output):
162     def_re = re.compile(r"(\\newcommandx|\\global\\long\\def)(\\[a-zA-Z]+)")
163
164     tmp = mkstemp()
165
166     changed = False
167     macros = []
168     for line in open(latex_file, 'r').readlines():
169         if not pdf_output and line.startswith("\\documentclass"):
170             changed = True
171             line += "\\PassOptionsToPackage{draft}{microtype}\n"
172         else:
173             match = def_re.match(line)
174             if match != None:
175                 macroname = match.group(2)
176                 if macroname in macros:
177                     definecmd = match.group(1)
178                     if definecmd == "\\newcommandx":
179                         changed = True
180                         line = line.replace(definecmd, "\\renewcommandx")
181                 else:
182                     macros.append(macroname)
183         tmp.write(line)
184
185     if changed:
186         copyfileobj(tmp, open(latex_file,"wb"), 1)
187
188     return changed
189
190
191 def convert_to_ppm_format(pngtopnm, basename):
192     png_file_re = re.compile("\.png$")
193
194     for png_file in glob.glob("%s*.png" % basename):
195         ppm_file = png_file_re.sub(".ppm", png_file)
196
197         p2p_cmd = '%s "%s"' % (pngtopnm, png_file)
198         p2p_status, p2p_stdout = run_command(p2p_cmd)
199         if p2p_status:
200             error("Unable to convert %s to ppm format" % png_file)
201
202         ppm = open(ppm_file, 'w')
203         ppm.write(p2p_stdout)
204         os.remove(png_file)
205
206 # Returns a tuple of:
207 # ps_pages: list of page indexes of pages containing PS literals
208 # pdf_pages: list of page indexes of pages requiring running pdflatex
209 # page_count: total number of pages
210 # pages_parameter: parameter for dvipng to exclude pages with PostScript/PDF
211 def find_ps_pages(dvi_file):
212     # latex failed
213     # FIXME: try with pdflatex
214     if not os.path.isfile(dvi_file):
215         error("No DVI output.")
216
217     # Check for PostScript specials in the dvi, badly supported by dvipng,
218     # and inclusion of PDF/PNG/JPG files. 
219     # This is required for correct rendering of PSTricks and TikZ
220     dv2dt = find_exe_or_terminate(["dv2dt"])
221     dv2dt_call = '%s "%s"' % (dv2dt, dvi_file)
222
223     # The output from dv2dt goes to stdout
224     dv2dt_status, dv2dt_output = run_command(dv2dt_call)
225     psliteral_re = re.compile("^special[1-4] [0-9]+ '(\"|ps:)")
226     hyperref_re = re.compile("^special[1-4] [0-9]+ 'ps:.*/DEST pdfmark")
227     pdffile_re = re.compile("^special[1-4] [0-9]+ 'PSfile=.*\\.(pdf|png|jpg|jpeg|PDF|PNG|JPG|JPEG)")
228
229     # Parse the dtl file looking for PostScript specials and pdflatex files.
230     # Pages using PostScript specials or pdflatex files are recorded in
231     # ps_pages or pdf_pages, respectively, and then used to create a
232     # different LaTeX file for processing in legacy mode.
233     # If hyperref is detected, the corresponding page is recorded in pdf_pages.
234     page_has_ps = False
235     page_has_pdf = False
236     page_index = 0
237     ps_pages = []
238     pdf_pages = []
239     ps_or_pdf_pages = []
240
241     for line in dv2dt_output.split("\n"):
242         # New page
243         if line.startswith("bop"):
244             page_has_ps = False
245             page_has_pdf = False
246             page_index += 1
247
248         # End of page
249         if line.startswith("eop") and (page_has_ps or page_has_pdf):
250             # We save in a list all the PostScript/PDF pages
251             if page_has_ps:
252                 ps_pages.append(page_index)
253             else:
254                 pdf_pages.append(page_index)
255             ps_or_pdf_pages.append(page_index)
256
257         if psliteral_re.match(line) != None:
258             # Literal PostScript special detected!
259             # If hyperref is detected, put this page on the pdf pages list
260             if hyperref_re.match(line) != None:
261                 page_has_ps = False
262                 page_has_pdf = True
263             else:
264                 page_has_ps = True
265         elif pdffile_re.match(line) != None:
266             # Inclusion of pdflatex image file detected!
267             page_has_pdf = True
268
269     # Create the -pp parameter for dvipng
270     pages_parameter = ""
271     if len(ps_or_pdf_pages) > 0 and len(ps_or_pdf_pages) < page_index:
272         # Don't process Postscript/PDF pages with dvipng by selecting the
273         # wanted pages through the -pp parameter. E.g., dvipng -pp 4-12,14,64
274         pages_parameter = " -pp "
275         skip = True
276         last = -1
277
278         # Use page ranges, as a list of pages could exceed command line
279         # maximum length (especially under Win32)
280         for index in xrange(1, page_index + 1):
281             if (not index in ps_or_pdf_pages) and skip:
282                 # We were skipping pages but current page shouldn't be skipped.
283                 # Add this page to -pp, it could stay alone or become the
284                 # start of a range.
285                 pages_parameter += str(index)
286                 # Save the starting index to avoid things such as "11-11"
287                 last = index
288                 # We're not skipping anymore
289                 skip = False
290             elif (index in ps_or_pdf_pages) and (not skip):
291                 # We weren't skipping but current page should be skipped
292                 if last != index - 1:
293                     # If the start index of the range is the previous page
294                     # then it's not a range
295                     pages_parameter += "-" + str(index - 1)
296
297                 # Add a separator
298                 pages_parameter += ","
299                 # Now we're skipping
300                 skip = True
301
302         # Remove the trailing separator
303         pages_parameter = pages_parameter.rstrip(",")
304         # We've to manage the case in which the last page is closing a range
305         if (not index in ps_or_pdf_pages) and (not skip) and (last != index):
306                 pages_parameter += "-" + str(index)
307
308     return (ps_pages, pdf_pages, page_index, pages_parameter)
309
310 def main(argv):
311     # Set defaults.
312     dpi = 128
313     fg_color = "000000"
314     bg_color = "ffffff"
315     bibtex = None
316     latex = None
317     lilypond = False
318     lilypond_book = None
319     output_format = "png"
320     script_name = argv[0]
321
322     # Parse and manipulate the command line arguments.
323     try:
324         (opts, args) = getopt.gnu_getopt(argv[1:], "dhv", ["bibtex=", "bg=",
325             "debug", "dpi=", "fg=", "help", "latex=", "lilypond",
326             "lilypond-book=", "png", "ppm", "verbose"])
327     except getopt.GetoptError, err:
328         error("%s\n%s" % (err, usage(script_name)))
329
330     opts.reverse()
331     for opt, val in opts:
332         if opt in ("-h", "--help"):
333             print usage(script_name)
334             sys.exit(0)
335         elif opt == "--bibtex":
336             bibtex = [val]
337         elif opt == "--bg":
338             bg_color = val
339         elif opt in ("-d", "--debug"):
340             import lyxpreview_tools
341             lyxpreview_tools.debug = True
342         elif opt == "--dpi":
343             try:
344                 dpi = string.atoi(val)
345             except:
346                 error("Cannot convert %s to an integer value" % val)
347         elif opt == "--fg":
348             fg_color = val
349         elif opt == "--latex":
350             latex = [val]
351         elif opt == "--lilypond":
352             lilypond = True
353         elif opt == "--lilypond-book":
354             lilypond_book = [val]
355         elif opt in ("--png", "--ppm"):
356             output_format = opt[2:]
357         elif opt in ("-v", "--verbose"):
358             import lyxpreview_tools
359             lyxpreview_tools.verbose = True
360
361     # Determine input file
362     if len(args) != 1:
363         err = "A single input file is required, %s given" % (len(args) or "none")
364         error("%s\n%s" % (err, usage(script_name)))
365
366     input_path = args[0]
367     dir, latex_file = os.path.split(input_path)
368
369     # Echo the settings
370     progress("Starting %s..." % script_name)
371     progress("Output format: %s" % output_format)
372     progress("Foreground color: %s" % fg_color)
373     progress("Background color: %s" % bg_color)
374     progress("Resolution (dpi): %s" % dpi)
375     progress("File to process: %s" % input_path)
376
377     # Check for the input file
378     if not os.path.exists(input_path):
379         error('File "%s" not found.' % input_path)
380     if len(dir) != 0:
381         os.chdir(dir)
382
383     fg_color_dvipng = make_texcolor(fg_color, False)
384     bg_color_dvipng = make_texcolor(bg_color, False)
385
386     # External programs used by the script.
387     latex = find_exe_or_terminate(latex or latex_commands)
388     bibtex = find_exe(bibtex or bibtex_commands)
389     if lilypond:
390         lilypond_book = find_exe_or_terminate(lilypond_book or
391             ["lilypond-book --safe"])
392
393     # These flavors of latex are known to produce pdf output
394     pdf_output = latex in pdflatex_commands
395
396     progress("Latex command: %s" % latex)
397     progress("Latex produces pdf output: %s" % pdf_output)
398     progress("Bibtex command: %s" % bibtex)
399     progress("Lilypond-book command: %s" % lilypond_book)
400     progress("Preprocess through lilypond-book: %s" % lilypond)
401     progress("Altering the latex file for font size and colors")
402
403     # Make sure that multiple defined macros and the microtype package
404     # don't cause issues in the latex file.
405     fix_latex_file(latex_file, pdf_output)
406
407     if lilypond:
408         progress("Preprocess the latex file through %s" % lilypond_book)
409         if pdf_output:
410             lilypond_book += " --pdf"
411         lilypond_book += " --latex-program=%s" % latex.split()[0]
412
413         # Make a copy of the latex file
414         lytex_file = latex_file_re.sub(".lytex", latex_file)
415         shutil.copyfile(latex_file, lytex_file)
416
417         # Preprocess the latex file through lilypond-book.
418         lytex_status, lytex_stdout = run_tex(lilypond_book, lytex_file)
419
420     if pdf_output:
421         progress("Using the legacy conversion method (PDF support)")
422         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
423             bg_color, latex, pdf_output)
424
425     # This can go once dvipng becomes widespread.
426     dvipng = find_exe(["dvipng"])
427     if dvipng == None:
428         progress("Using the legacy conversion method (dvipng not found)")
429         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
430             bg_color, latex, pdf_output)
431
432     dv2dt = find_exe(["dv2dt"])
433     if dv2dt == None:
434         progress("Using the legacy conversion method (dv2dt not found)")
435         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
436             bg_color, latex, pdf_output)
437
438     pngtopnm = ""
439     if output_format == "ppm":
440         pngtopnm = find_exe(["pngtopnm"])
441         if pngtopnm == None:
442             progress("Using the legacy conversion method (pngtopnm not found)")
443             return legacy_conversion_step1(latex_file, dpi, output_format,
444                 fg_color, bg_color, latex, pdf_output)
445
446     # Compile the latex file.
447     error_pages = []
448     latex_status, latex_stdout = run_latex(latex, latex_file, bibtex)
449     latex_log = latex_file_re.sub(".log", latex_file)
450     if latex_status:
451         progress("Will try to recover from %s failure" % latex)
452         error_pages = check_latex_log(latex_log)
453
454     # The dvi output file name
455     dvi_file = latex_file_re.sub(".dvi", latex_file)
456
457     # If there's no DVI output, look for PDF and go to legacy or fail
458     if not os.path.isfile(dvi_file):
459         # No DVI, is there a PDF?
460         pdf_file = latex_file_re.sub(".pdf", latex_file)
461         if os.path.isfile(pdf_file):
462             progress("%s produced a PDF output, fallback to legacy." \
463                 % (os.path.basename(latex)))
464             progress("Using the legacy conversion method (PDF support)")
465             return legacy_conversion_step1(latex_file, dpi, output_format,
466                 fg_color, bg_color, latex, True)
467         else:
468             error("No DVI or PDF output. %s failed." \
469                 % (os.path.basename(latex)))
470
471     # Look for PS literals or inclusion of pdflatex files in DVI pages
472     # ps_pages: list of indexes of pages containing PS literals
473     # pdf_pages: list of indexes of pages requiring running pdflatex
474     # page_count: total number of pages
475     # pages_parameter: parameter for dvipng to exclude pages with PostScript
476     (ps_pages, pdf_pages, page_count, pages_parameter) = find_ps_pages(dvi_file)
477
478     # If all pages need PostScript or pdflatex, directly use the legacy method.
479     if len(ps_pages) == page_count:
480         progress("Using the legacy conversion method (PostScript support)")
481         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
482             bg_color, latex, pdf_output)
483     elif len(pdf_pages) == page_count:
484         progress("Using the legacy conversion method (PDF support)")
485         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
486             bg_color, "pdflatex", True)
487
488     # Retrieve resolution
489     resolution = extract_resolution(latex_log, dpi)
490
491     # Run the dvi file through dvipng.
492     dvipng_call = '%s -Ttight -depth -height -D %d -fg "%s" -bg "%s" %s "%s"' \
493         % (dvipng, resolution, fg_color_dvipng, bg_color_dvipng, pages_parameter, dvi_file)
494     dvipng_status, dvipng_stdout = run_command(dvipng_call)
495
496     if dvipng_status:
497         warning("%s failed to generate images from %s... fallback to legacy method" \
498               % (os.path.basename(dvipng), dvi_file))
499         progress("Using the legacy conversion method (dvipng failed)")
500         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
501             bg_color, latex, pdf_output)
502
503     # Extract metrics info from dvipng_stdout.
504     metrics_file = latex_file_re.sub(".metrics", latex_file)
505     dvipng_metrics = extract_metrics_info(dvipng_stdout)
506
507     # If some pages require PostScript pass them to legacy method
508     if len(ps_pages) > 0:
509         # Create a new LaTeX file just for the snippets needing
510         # the legacy method
511         legacy_latex_file = latex_file_re.sub("_legacy.tex", latex_file)
512         filter_pages(latex_file, legacy_latex_file, ps_pages)
513
514         # Pass the new LaTeX file to the legacy method
515         progress("Pages %s include postscript specials" % ps_pages)
516         progress("Using the legacy conversion method (PostScript support)")
517         legacy_status, legacy_metrics = legacy_conversion_step1(legacy_latex_file,
518             dpi, output_format, fg_color, bg_color, latex, pdf_output, True)
519
520         # Now we need to mix metrics data from dvipng and the legacy method
521         original_bitmap = latex_file_re.sub("%d." + output_format, legacy_latex_file)
522         destination_bitmap = latex_file_re.sub("%d." + output_format, latex_file)
523
524         # Join metrics from dvipng and legacy, and rename legacy bitmaps
525         join_metrics_and_rename(dvipng_metrics, legacy_metrics, ps_pages,
526             original_bitmap, destination_bitmap)
527
528     # If some pages require running pdflatex pass them to legacy method
529     if len(pdf_pages) > 0:
530         # Create a new LaTeX file just for the snippets needing
531         # the legacy method
532         legacy_latex_file = latex_file_re.sub("_legacy.tex", latex_file)
533         filter_pages(latex_file, legacy_latex_file, pdf_pages)
534
535         # Pass the new LaTeX file to the legacy method
536         progress("Pages %s require processing with pdflatex" % pdf_pages)
537         progress("Using the legacy conversion method (PDF support)")
538         legacy_status, legacy_metrics = legacy_conversion_step1(legacy_latex_file,
539             dpi, output_format, fg_color, bg_color, "pdflatex", True, True)
540
541         # Now we need to mix metrics data from dvipng and the legacy method
542         original_bitmap = latex_file_re.sub("%d." + output_format, legacy_latex_file)
543         destination_bitmap = latex_file_re.sub("%d." + output_format, latex_file)
544
545         # Join metrics from dvipng and legacy, and rename legacy bitmaps
546         join_metrics_and_rename(dvipng_metrics, legacy_metrics, pdf_pages,
547             original_bitmap, destination_bitmap)
548
549     # Invalidate metrics for pages that produced errors
550     if len(error_pages) > 0:
551         error_count = 0
552         for index in error_pages:
553             if index not in ps_pages and index not in pdf_pages:
554                 dvipng_metrics.pop(index - 1)
555                 dvipng_metrics.insert(index - 1, (index, -1.0))
556                 error_count += 1
557         if error_count:
558             warning("Failed to produce %d preview snippet(s)" % error_count)
559
560     # Convert images to ppm format if necessary.
561     if output_format == "ppm":
562         convert_to_ppm_format(pngtopnm, latex_file_re.sub("", latex_file))
563
564     # Actually create the .metrics file
565     write_metrics_info(dvipng_metrics, metrics_file)
566
567     return (0, dvipng_metrics)
568
569 if __name__ == "__main__":
570     sys.exit(main(sys.argv)[0])