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