]> git.lyx.org Git - features.git/blob - lib/scripts/lyxpreview2bitmap.py
Refine the lyxpreview legacy conversion (the ghostscript one).
[features.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 # * python 2.4 or later (subprocess module);
20 # * A latex executable;
21 # * preview.sty;
22 # * dvipng;
23 # * dv2dt;
24 # * pngtoppm (if outputing ppm format images).
25
26 # preview.sty and dvipng are part of the preview-latex project
27 # http://preview-latex.sourceforge.net/
28
29 # preview.sty can alternatively be obtained from
30 # CTAN/support/preview-latex/
31
32 # Example usage:
33 # lyxpreview2bitmap.py --bg=faf0e6 0lyxpreview.tex
34
35 # This script takes one obligatory argument:
36 #
37 #   <input file>:  The name of the .tex file to be converted.
38 #
39 # and these optional arguments:
40 #
41 #   --png, --ppm:  The desired output format. Either 'png' or 'ppm'.
42 #   --dpi=<res>:   A scale factor, used to ascertain the resolution of the
43 #                  generated image which is then passed to gs.
44 #   --fg=<color>:  The foreground color as a hexadecimal string, eg '000000'.
45 #   --bg=<color>:  The background color as a hexadecimal string, eg 'faf0e6'.
46 #   --latex=<exe>: The converter for latex files. Default is latex.
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 copyfileobj, error, filter_pages, find_exe, \
83      find_exe_or_terminate, join_metrics_and_rename, latex_commands, \
84      latex_file_re, make_texcolor, mkstemp, pdflatex_commands, progress, \
85      run_command, warning, write_metrics_info
86
87
88 def usage(prog_name):
89     msg = """
90 Usage: %s <options> <input file>
91
92 Options:
93   --dpi=<res>:   Resolution per inch (default: 128)
94   --png, --ppm:  Select the output format (default: png)
95   --fg=<color>:  Foreground color (default: black, ie '000000')
96   --bg=<color>:  Background color (default: white, ie 'ffffff')
97   --latex=<exe>: Specify the executable for latex (default: latex)
98   --lilypond:    Preprocess through lilypond-book (default: false)
99   --lilypond-book=<exe>:
100                  The executable for lilypond-book (default: lilypond-book)
101
102   -d, --debug:   Show the output from external commands
103   -h, --help:    Show this help screen and exit
104   -v, --verbose: Show progress messages
105
106 The colors are hexadecimal strings, eg 'faf0e6'."""
107     return msg % prog_name
108
109 # Returns a list of tuples containing page number and ascent fraction
110 # extracted from dvipng output.
111 # Use write_metrics_info to create the .metrics file with this info
112 def extract_metrics_info(dvipng_stdout):
113     # "\[[0-9]+" can match two kinds of numbers: page numbers from dvipng
114     # and glyph numbers from mktexpk. The glyph numbers always match
115     # "\[[0-9]+\]" while the page number never is followed by "\]". Thus:
116     page_re = re.compile("\[([0-9]+)[^]]");
117     metrics_re = re.compile("depth=(-?[0-9]+) height=(-?[0-9]+)")
118
119     success = 0
120     page = ""
121     pos = 0
122     results = []
123     while 1:
124         match = page_re.search(dvipng_stdout, pos)
125         if match == None:
126             break
127         page = match.group(1)
128         pos = match.end()
129         match = metrics_re.search(dvipng_stdout, pos)
130         if match == None:
131             break
132         success = 1
133
134         # Calculate the 'ascent fraction'.
135         descent = string.atof(match.group(1))
136         ascent  = string.atof(match.group(2))
137
138         frac = 0.5
139         if ascent >= 0 or descent >= 0:
140             if abs(ascent + descent) > 0.1:
141                 frac = ascent / (ascent + descent)
142
143             # Sanity check
144             if frac < 0:
145                 frac = 0.5
146
147         results.append((int(page), frac))
148         pos = match.end() + 2
149
150     if success == 0:
151         error("Failed to extract metrics info from dvipng")
152
153     return results
154
155
156 def color_pdf(latex_file, bg_color, fg_color):
157     use_preview_pdf_re = re.compile("(\s*\\\\usepackage\[[^]]+)((pdftex|xetex)\]{preview})")
158
159     tmp = mkstemp()
160
161     fg = ""
162     if fg_color != "0.000000,0.000000,0.000000":
163         fg = '  \\AtBeginDocument{\\let\\oldpreview\\preview\\renewcommand\\preview{\\oldpreview\\color[rgb]{%s}}}\n' % (fg_color)
164
165     success = 0
166     try:
167         for line in open(latex_file, 'r').readlines():
168             match = use_preview_pdf_re.match(line)
169             if match == None:
170                 tmp.write(line)
171                 continue
172             success = 1
173             tmp.write("  \\usepackage{color}\n" \
174                   "  \\pagecolor[rgb]{%s}\n" \
175                   "%s" \
176                   "%s\n" \
177                   % (bg_color, fg, match.group()))
178             continue
179
180     except:
181         # Unable to open the file, but do nothing here because
182         # the calling function will act on the value of 'success'.
183         warning('Warning in color_pdf! Unable to open "%s"' % latex_file)
184         warning(`sys.exc_type` + ',' + `sys.exc_value`)
185
186     if success:
187         copyfileobj(tmp, open(latex_file,"wb"), 1)
188
189     return success
190
191
192 def fix_latex_file(latex_file):
193     documentclass_re = re.compile("(\\\\documentclass\[)(1[012]pt,?)(.+)")
194
195     tmp = mkstemp()
196
197     changed = 0
198     for line in open(latex_file, 'r').readlines():
199         match = documentclass_re.match(line)
200         if match == None:
201             tmp.write(line)
202             continue
203
204         changed = 1
205         tmp.write("%s%s\n" % (match.group(1), match.group(3)))
206
207     if changed:
208         copyfileobj(tmp, open(latex_file,"wb"), 1)
209
210     return changed
211
212
213 def convert_to_ppm_format(pngtopnm, basename):
214     png_file_re = re.compile("\.png$")
215
216     for png_file in glob.glob("%s*.png" % basename):
217         ppm_file = png_file_re.sub(".ppm", png_file)
218
219         p2p_cmd = '%s "%s"' % (pngtopnm, png_file)
220         p2p_status, p2p_stdout = run_command(p2p_cmd)
221         if p2p_status:
222             error("Unable to convert %s to ppm format" % png_file)
223
224         ppm = open(ppm_file, 'w')
225         ppm.write(p2p_stdout)
226         os.remove(png_file)
227
228 # Returns a tuple of:
229 # ps_pages: list of page indexes of pages containing PS literals
230 # page_count: total number of pages
231 # pages_parameter: parameter for dvipng to exclude pages with PostScript
232 def find_ps_pages(dvi_file):
233     # latex failed
234     # FIXME: try with pdflatex
235     if not os.path.isfile(dvi_file):
236         error("No DVI output.")
237
238     # Check for PostScript specials in the dvi, badly supported by dvipng
239     # This is required for correct rendering of PSTricks and TikZ
240     dv2dt = find_exe_or_terminate(["dv2dt"])
241     dv2dt_call = '%s "%s"' % (dv2dt, dvi_file)
242
243     # The output from dv2dt goes to stdout
244     dv2dt_status, dv2dt_output = run_command(dv2dt_call)
245     psliteral_re = re.compile("^special[1-4] [0-9]+ '(\"|ps:)")
246
247     # Parse the dtl file looking for PostScript specials.
248     # Pages using PostScript specials are recorded in ps_pages and then
249     # used to create a different LaTeX file for processing in legacy mode.
250     page_has_ps = False
251     page_index = 0
252     ps_pages = []
253
254     for line in dv2dt_output.split("\n"):
255         # New page
256         if line.startswith("bop"):
257             page_has_ps = False
258             page_index += 1
259
260         # End of page
261         if line.startswith("eop") and page_has_ps:
262             # We save in a list all the PostScript pages
263             ps_pages.append(page_index)
264
265         if psliteral_re.match(line) != None:
266             # Literal PostScript special detected!
267             page_has_ps = True
268
269     # Create the -pp parameter for dvipng
270     pages_parameter = ""
271     if len(ps_pages) > 0 and len(ps_pages) < page_index:
272         # Don't process Postscript 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_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_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_pages) and (not skip) and (last != index):
306                 pages_parameter += "-" + str(index)
307
308     return (ps_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     latex = None
316     lilypond = False
317     lilypond_book = None
318     output_format = "png"
319     script_name = argv[0]
320
321     # Parse and manipulate the command line arguments.
322     try:
323         (opts, args) = getopt.gnu_getopt(argv[1:], "dhv", ["bg=", "debug",
324             "dpi=", "fg=", "help", "latex=", "lilypond", "lilypond-book=",
325             "png", "ppm", "verbose"])
326     except getopt.GetoptError, err:
327         error("%s\n%s" % (err, usage(script_name)))
328
329     opts.reverse()
330     for opt, val in opts:
331         if opt in ("-h", "--help"):
332             print usage(script_name)
333             sys.exit(0)
334         elif opt == "--bg":
335             bg_color = val
336         elif opt in ("-d", "--debug"):
337             import lyxpreview_tools
338             lyxpreview_tools.debug = True
339         elif opt == "--dpi":
340             try:
341                 dpi = string.atoi(val)
342             except:
343                 error("Cannot convert %s to an integer value" % val)
344         elif opt == "--fg":
345             fg_color = val
346         elif opt == "--latex":
347             latex = [val]
348         elif opt == "--lilypond":
349             lilypond = True
350         elif opt == "--lilypond-book":
351             lilypond_book = [val]
352         elif opt in ("--png", "--ppm"):
353             output_format = opt[2:]
354         elif opt in ("-v", "--verbose"):
355             import lyxpreview_tools
356             lyxpreview_tools.verbose = True
357
358     # Determine input file
359     if len(args) != 1:
360         err = "A single input file is required, %s given" % (len(args) or "none")
361         error("%s\n%s" % (err, usage(script_name)))
362
363     input_path = args[0]
364     dir, latex_file = os.path.split(input_path)
365
366     # Echo the settings
367     progress("Starting %s..." % script_name)
368     progress("Output format: %s" % output_format)
369     progress("Foreground color: %s" % fg_color)
370     progress("Background color: %s" % bg_color)
371     progress("Resolution (dpi): %s" % dpi)
372     progress("File to process: %s" % input_path)
373
374     # Check for the input file
375     if not os.path.exists(input_path):
376         error('File "%s" not found.' % input_path)
377     if len(dir) != 0:
378         os.chdir(dir)
379
380     fg_color_dvipng = make_texcolor(fg_color, False)
381     bg_color_dvipng = make_texcolor(bg_color, False)
382
383     fg_color_gr = make_texcolor(fg_color, True)
384     bg_color_gr = make_texcolor(bg_color, True)
385
386     # External programs used by the script.
387     latex = find_exe_or_terminate(latex or latex_commands)
388     if lilypond:
389         lilypond_book = find_exe_or_terminate(lilypond_book or ["lilypond-book"])
390
391     # These flavors of latex are known to produce pdf output
392     pdf_output = latex in pdflatex_commands
393
394     progress("Latex command: %s" % latex)
395     progress("Latex produces pdf output: %s" % pdf_output)
396     progress("Lilypond-book command: %s" % lilypond_book)
397     progress("Preprocess through lilypond-book: %s" % lilypond)
398     progress("Altering the latex file for font size and colors")
399
400     # Omit font size specification in latex file.
401     if not fix_latex_file(latex_file):
402         warning("Unable to remove font size from the latex file")
403
404     if lilypond:
405         progress("Preprocess the latex file through %s" % lilypond_book)
406         if pdf_output:
407             lilypond_book += ' --pdf'
408
409         # Make a copy of the latex file
410         lytex_file = latex_file_re.sub(".lytex", latex_file)
411         shutil.copyfile(latex_file, lytex_file)
412
413         # Preprocess the latex file through lilypond-book.
414         lytex_call = '%s --safe --latex-program=%s "%s"' % (lilypond_book,
415             latex, lytex_file)
416         lytex_status, lytex_stdout = run_command(lytex_call)
417         if lytex_status:
418             warning("%s failed to compile %s" \
419                 % (os.path.basename(lilypond_book), lytex_file))
420
421     if pdf_output:
422         progress("Using the legacy conversion method (PDF support)")
423         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
424             bg_color, latex, pdf_output)
425
426     # This can go once dvipng becomes widespread.
427     dvipng = find_exe(["dvipng"])
428     if dvipng == None:
429         progress("Using the legacy conversion method (dvipng not found)")
430         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
431             bg_color, latex, pdf_output)
432
433     dv2dt = find_exe(["dv2dt"])
434     if dv2dt == None:
435         progress("Using the legacy conversion method (dv2dt not found)")
436         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
437             bg_color, latex, pdf_output)
438
439     pngtopnm = ""
440     if output_format == "ppm":
441         pngtopnm = find_exe(["pngtopnm"])
442         if pngtopnm == None:
443             progress("Using the legacy conversion method (pngtopnm not found)")
444             return legacy_conversion_step1(latex_file, dpi, output_format,
445                 fg_color, bg_color, latex, pdf_output)
446
447     # Move color information for PDF into the latex file.
448     if not color_pdf(latex_file, bg_color_gr, fg_color_gr):
449         warning("Unable to move color info into the latex file")
450
451     # Compile the latex file.
452     latex_call = '%s "%s"' % (latex, latex_file)
453
454     latex_status, latex_stdout = run_command(latex_call)
455     if latex_status:
456         warning("%s had problems compiling %s" \
457               % (os.path.basename(latex), latex_file))
458
459     # The dvi output file name
460     dvi_file = latex_file_re.sub(".dvi", latex_file)
461
462     # If there's no DVI output, look for PDF and go to legacy or fail
463     if not os.path.isfile(dvi_file):
464         # No DVI, is there a PDF?
465         pdf_file = latex_file_re.sub(".pdf", latex_file)
466         if os.path.isfile(pdf_file):
467             progress("%s produced a PDF output, fallback to legacy." \
468                 % (os.path.basename(latex)))
469             progress("Using the legacy conversion method (PDF support)")
470             return legacy_conversion_step1(latex_file, dpi, output_format,
471                 fg_color, bg_color, latex, True)
472         else:
473             error("No DVI or PDF output. %s failed." \
474                 % (os.path.basename(latex)))
475
476     # Look for PS literals in DVI pages
477     # ps_pages: list of page indexes of pages containing PS literals
478     # page_count: total number of pages
479     # pages_parameter: parameter for dvipng to exclude pages with PostScript
480     (ps_pages, page_count, pages_parameter) = find_ps_pages(dvi_file)
481
482     # If all pages need PostScript, directly use the legacy method.
483     if len(ps_pages) == page_count:
484         progress("Using the legacy conversion method (PostScript support)")
485         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
486             bg_color, latex, pdf_output)
487
488     # Run the dvi file through dvipng.
489     dvipng_call = '%s -Ttight -depth -height -D %d -fg "%s" -bg "%s" %s "%s"' \
490         % (dvipng, dpi, fg_color_dvipng, bg_color_dvipng, pages_parameter, dvi_file)
491     dvipng_status, dvipng_stdout = run_command(dvipng_call)
492
493     if dvipng_status:
494         warning("%s failed to generate images from %s... fallback to legacy method" \
495               % (os.path.basename(dvipng), dvi_file))
496         progress("Using the legacy conversion method (dvipng failed)")
497         return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
498             bg_color, latex, pdf_output)
499
500     # Extract metrics info from dvipng_stdout.
501     metrics_file = latex_file_re.sub(".metrics", latex_file)
502     dvipng_metrics = extract_metrics_info(dvipng_stdout)
503
504     # If some pages require PostScript pass them to legacy method
505     if len(ps_pages) > 0:
506         # Create a new LaTeX file just for the snippets needing
507         # the legacy method
508         legacy_latex_file = latex_file_re.sub("_legacy.tex", latex_file)
509         filter_pages(latex_file, legacy_latex_file, ps_pages)
510
511         # Pass the new LaTeX file to the legacy method
512         progress("Pages %s include postscript specials" % ps_pages)
513         progress("Using the legacy conversion method (PostScript support)")
514         legacy_status, legacy_metrics = legacy_conversion_step1(legacy_latex_file,
515             dpi, output_format, fg_color, bg_color, latex, pdf_output, True)
516
517         # Now we need to mix metrics data from dvipng and the legacy method
518         original_bitmap = latex_file_re.sub("%d." + output_format, legacy_latex_file)
519         destination_bitmap = latex_file_re.sub("%d." + output_format, latex_file)
520
521         # Join metrics from dvipng and legacy, and rename legacy bitmaps
522         join_metrics_and_rename(dvipng_metrics, legacy_metrics, ps_pages,
523             original_bitmap, destination_bitmap)
524
525     # Convert images to ppm format if necessary.
526     if output_format == "ppm":
527         convert_to_ppm_format(pngtopnm, latex_file_re.sub("", latex_file))
528
529     # Actually create the .metrics file
530     write_metrics_info(dvipng_metrics, metrics_file)
531
532     return (0, dvipng_metrics)
533
534 if __name__ == "__main__":
535     exit(main(sys.argv)[0])