1 # file legacy_lyxpreview2ppm.py
2 # This file is part of LyX, the document processor.
3 # Licence details can be found in the file COPYING.
6 # Full author contact details are available in file CREDITS
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 # and with much help testing the code under Windows from
12 # Paul A. Rubin, rubin@msu.edu.
14 # This script takes a LaTeX file and generates a collection of
15 # png or ppm image files, one per previewed snippet.
17 # legacy_lyxpreview2bitmap.py 0lyxpreview.tex 128 ppm 000000 faf0e6
19 # This script takes five arguments:
20 # TEXFILE: the name of the .tex file to be converted.
21 # SCALEFACTOR: a scale factor, used to ascertain the resolution of the
22 # generated image which is then passed to gs.
23 # OUTPUTFORMAT: the format of the output bitmap image files.
24 # This particular script can produce only "ppm" format output.
25 # FG_COLOR: the foreground color as a hexadecimal string, eg '000000'.
26 # BG_COLOR: the background color as a hexadecimal string, eg 'faf0e6'.
28 # Decomposing TEXFILE's name as DIR/BASE.tex, this script will,
29 # if executed successfully, leave in DIR:
30 # * a (possibly large) number of image files with names
31 # like BASE[0-9]+.(ppm|png)
32 # * a file BASE.metrics, containing info needed by LyX to position
33 # the images correctly on the screen.
35 # The script uses several external programs and files:
36 # * python 2.4 or later (subprocess module);
37 # * A latex executable;
41 # * pdflatex (optional);
42 # * pnmcrop (optional).
43 # * pdftocairo (optional).
44 # * epstopdf (optional).
46 # preview.sty is part of the preview-latex project
47 # http://preview-latex.sourceforge.net/
48 # Alternatively, it can be obtained from
49 # CTAN/support/preview-latex/
51 # What does this script do?
53 # 0) Process command-line arguments
54 # [legacy_conversion_step1]
55 # 1) Call latex to create a DVI file from LaTeX
56 # [legacy_conversion_step2]
57 # 2) Call dvips to create one PS file for each DVI page
58 # [legacy_conversion_step3]
59 # 3) If dvips fails look for PDF and call pdftocairo or gs to produce bitmaps
60 # 4) Otherwise call pdftocairo or gs on each PostScript file to produce bitmaps
61 # [legacy_conversion_pdflatex]
62 # 5) Keep track of pages on which gs failed and pass them to pdflatex
63 # 6) Call pdftocairo or gs on the PDF output from pdflatex to produce bitmaps
64 # 7) Extract and write to file (or return to lyxpreview2bitmap)
65 # metrics from both methods (standard and pdflatex)
67 # The script uses the old dvi->ps->png conversion route,
68 # which is good when using PSTricks, TikZ or other packages involving
69 # PostScript literals (steps 1, 2, 4).
70 # This script also generates bitmaps from PDF created by a call to
71 # lyxpreview2bitmap.py passing "pdflatex" to the CONVERTER parameter
73 # Finally, there's also has a fallback method based on pdflatex, which
74 # is required in certain cases, if hyperref is active for instance,
76 # If possible, dvipng should be used, as it's much faster.
77 # If possible, the script will use pdftocairo instead of gs,
78 # as it's much faster and gives better results.
80 import glob, os, pipes, re, sys, tempfile
82 from lyxpreview_tools import check_latex_log, copyfileobj, error, filter_pages,\
83 find_exe, find_exe_or_terminate, join_metrics_and_rename, latex_commands, \
84 latex_file_re, make_texcolor, pdflatex_commands, progress, \
85 run_command, run_latex, warning, write_metrics_info
89 return "Usage: %s <latex file> <dpi> ppm <fg color> <bg color>\n" \
90 "\twhere the colors are hexadecimal strings, eg 'faf0e6'" \
93 # Returns a list of tuples containing page number and ascent fraction
94 # extracted from dvipng output.
95 # Use write_metrics_info to create the .metrics file with this info
96 def legacy_extract_metrics_info(log_file):
98 log_re = re.compile(b"Preview: ([ST])")
99 data_re = re.compile(b"(-?[0-9]+) (-?[0-9]+) (-?[0-9]+) (-?[0-9]+)")
107 for line in open(log_file, 'rb').readlines():
108 match = log_re.match(line)
112 snippet = (match.group(1) == b'S')
114 match = data_re.search(line)
116 error(f"Unexpected data in {log_file}\n{line}")
119 ascent = float(match.group(2))
120 descent = float(match.group(3))
123 if ascent == 0 and descent == 0:
124 # This is an empty image, forbid its display
126 elif ascent >= 0 or descent >= 0:
127 ascent = ascent + tp_ascent
128 descent = descent - tp_descent
130 if abs(ascent + descent) > 0.1:
131 frac = ascent / (ascent + descent)
134 if frac < 0 or frac > 1:
137 results.append((int(match.group(1)), frac))
140 tp_descent = float(match.group(2))
141 tp_ascent = float(match.group(4))
144 # Unable to open the file, but do nothing here because
145 # the calling function will act on the value of 'success'.
146 warning(f'Warning in legacy_extract_metrics_info! Unable to open "{log_file}"')
147 warning(repr(sys.exc_info()[0]) + ',' + repr(sys.exc_info()[1]))
150 error(f"Failed to extract metrics info from {log_file}")
154 def extract_resolution(log_file, dpi):
155 fontsize_re = re.compile(b"Preview: Fontsize")
156 magnification_re = re.compile(b"Preview: Magnification")
157 extract_decimal_re = re.compile(br"([0-9\.]+)")
158 extract_integer_re = re.compile(b"([0-9]+)")
161 found_magnification = 0
164 magnification = 1000.0
168 for line in open(log_file, 'rb').readlines():
169 if found_fontsize and found_magnification:
172 if not found_fontsize:
173 match = fontsize_re.match(line)
175 match = extract_decimal_re.search(line)
177 error(f"Unable to parse: {line}")
178 fontsize = float(match.group(1))
182 if not found_magnification:
183 match = magnification_re.match(line)
185 match = extract_integer_re.search(line)
187 error("Unable to parse: %s" % line)
188 magnification = float(match.group(1))
189 found_magnification = 1
193 warning('Warning in extract_resolution! Unable to open "%s"' % log_file)
194 warning(repr(sys.exc_info()[0]) + ',' + repr(sys.exc_info()[1]))
196 # This is safe because both fontsize and magnification have
197 # non-zero default values.
198 return dpi * (10.0 / fontsize) * (1000.0 / magnification)
201 def legacy_latex_file(latex_file, fg_color, bg_color):
202 use_polyglossia_re = re.compile(b"\\s*\\\\usepackage{polyglossia}")
203 use_preview_re = re.compile(b"\\s*\\\\usepackage\\[([^]]+)\\]{preview}")
204 fg_color_gr = make_texcolor(fg_color, True)
205 bg_color_gr = make_texcolor(bg_color, True)
207 tmp = tempfile.TemporaryFile()
211 f = open(latex_file, 'rb')
213 # Unable to open the file, but do nothing here because
214 # the calling function will act on the value of 'success'.
215 warning('Warning in legacy_latex_file! Unable to open "%s"' % latex_file)
216 warning(repr(sys.exc_info()[0]) + ',' + repr(sys.exc_info()[1]))
219 for line in f.readlines():
223 match = use_preview_re.match(line)
224 polymatch = use_polyglossia_re.match(line)
226 # * if polyglossia is used, we need to load color before that
227 # (also, we do not have to load lmodern)
228 # * else, color should be loaded before preview
230 if polymatch == None:
236 \\definecolor{lyxfg}{rgb}{%s}
237 \\definecolor{lyxbg}{rgb}{%s}
239 \\usepackage{polyglossia}
240 """ % (fg_color_gr, bg_color_gr))
244 # Preview options: add the options lyx and tightpage
245 previewopts = match.group(1)
249 \\definecolor{lyxfg}{rgb}{%s}
250 \\definecolor{lyxbg}{rgb}{%s}
254 \\ifx\\f@family\\@tempa
255 \\IfFileExists{lmodern.sty}{\\usepackage{lmodern}}{\\usepackage{ae,aecompl}}
257 """ % (fg_color_gr, bg_color_gr))
259 \\usepackage[%s,tightpage]{preview}
261 \\g@addto@macro\\preview{\\leavevmode\\begingroup\\color{lyxbg}\\special{background \\current@color}\\special{ps::clippath fill}\\color{lyxfg}}
262 \\g@addto@macro\\endpreview{\\endgroup}
263 \\let\\pr@set@pagerightoffset\\@empty
264 \\ifx\\pagerightoffset\\@undefined\\else
265 \\def\\pr@set@pagerightoffset{\\ifnum\\pagedirection=1
266 \\pagerightoffset=-1in
267 \\advance\\pagerightoffset-\\pr@bb@i
268 \\advance\\pagerightoffset\\pr@bb@iii
272 \\g@addto@macro\\pr@ship@end{\\pr@set@pagerightoffset}
276 copyfileobj(tmp, open(latex_file,"wb"), 1)
281 def crop_files(pnmcrop, basename):
283 t.append('%s -left' % pnmcrop, '--')
284 t.append('%s -right' % pnmcrop, '--')
286 for file in glob.glob("%s*.ppm" % basename):
287 tmp = tempfile.TemporaryFile()
288 new = t.open(file, "r")
289 copyfileobj(new, tmp)
291 copyfileobj(tmp, open(file,"wb"), 1)
294 def legacy_conversion(argv, skipMetrics = False):
295 # Parse and manipulate the command line arguments.
299 error(usage(argv[0]))
303 dir, latex_file = os.path.split(argv[1])
309 output_format = argv[3]
314 # External programs used by the script.
315 latex = find_exe_or_terminate(latex or latex_commands)
317 pdf_output = latex in pdflatex_commands
319 return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
320 bg_color, latex, pdf_output, skipMetrics)
323 # Add color info to the latex file, since ghostscript doesn't
324 # have the option to set foreground and background colors on
325 # the command line. Run the resulting file through latex.
326 def legacy_conversion_step1(latex_file, dpi, output_format, fg_color, bg_color,
327 latex, pdf_output = False, skipMetrics = False):
329 # Move color information, lyx and tightpage options into the latex file.
330 if not legacy_latex_file(latex_file, fg_color, bg_color):
331 error("""Unable to move the color information, and the lyx and tightpage
332 options of preview-latex, into the latex file""")
334 # Compile the latex file.
335 latex_status, latex_stdout = run_latex(latex, latex_file)
337 progress("Will try to recover from %s failure" % latex)
340 return legacy_conversion_step3(latex_file, dpi, output_format, True, skipMetrics)
342 return legacy_conversion_step2(latex_file, dpi, output_format, skipMetrics)
344 # Creates a new LaTeX file from the original with pages specified in
345 # failed_pages, pass it through pdflatex and updates the metrics
346 # from the standard legacy route
347 def legacy_conversion_pdflatex(latex_file, failed_pages, legacy_metrics,
348 use_pdftocairo, conv, gs_device, gs_ext, alpha, resolution, output_format):
352 # Search for pdflatex executable
353 pdflatex = find_exe(["pdflatex"])
355 warning("Can't find pdflatex. Some pages failed with all the possible routes.")
358 # Create a new LaTeX file from the original but only with failed pages
359 pdf_latex_file = latex_file_re.sub("_pdflatex.tex", latex_file)
360 filter_pages(latex_file, pdf_latex_file, failed_pages)
364 pdflatex_status, pdflatex_stdout = run_latex(pdflatex, pdf_latex_file)
366 error_pages = check_latex_log(latex_file_re.sub(".log", pdf_latex_file))
368 pdf_file = latex_file_re.sub(".pdf", pdf_latex_file)
369 latex_file_root = latex_file_re.sub("", pdf_latex_file)
371 # Converter call to produce bitmaps
373 conv_call = '%s -png -transp -r %d "%s" "%s"' \
374 % (conv, resolution, pdf_file, latex_file_root)
375 conv_status, conv_stdout = run_command(conv_call)
377 seqnum_re = re.compile("-([0-9]+)")
378 for name in glob.glob("%s-*.png" % latex_file_root):
379 match = seqnum_re.search(name)
381 new_name = seqnum_re.sub(str(int(match.group(1))), name)
382 os.rename(name, new_name)
384 conv_call = '%s -dNOPAUSE -dBATCH -dSAFER -sDEVICE=%s ' \
385 '-sOutputFile="%s%%d.%s" ' \
386 '-dGraphicsAlphaBit=%d -dTextAlphaBits=%d ' \
388 % (conv, gs_device, latex_file_root, \
389 gs_ext, alpha, alpha, resolution, pdf_file)
390 conv_status, conv_stdout = run_command(conv_call)
394 warning("Some pages failed with all the possible routes")
398 pdf_log_file = latex_file_re.sub(".log", pdf_latex_file)
399 pdf_metrics = legacy_extract_metrics_info(pdf_log_file)
401 # Invalidate metrics for pages that produced errors
402 if len(error_pages) > 0:
403 for index in error_pages:
404 pdf_metrics.pop(index - 1)
405 pdf_metrics.insert(index - 1, (index, -1.0))
408 original_bitmap = latex_file_re.sub("%d." + output_format, pdf_latex_file)
409 destination_bitmap = latex_file_re.sub("%d." + output_format, latex_file)
411 # Join the metrics with the those from dvips and rename the bitmap images
412 join_metrics_and_rename(legacy_metrics, pdf_metrics, failed_pages,
413 original_bitmap, destination_bitmap)
418 # The file has been processed through latex and we expect dvi output.
419 # Run dvips, taking note whether it was successful.
420 def legacy_conversion_step2(latex_file, dpi, output_format, skipMetrics = False):
421 # External programs used by the script.
422 dvips = find_exe_or_terminate(["dvips"])
424 # Run the dvi file through dvips.
425 dvi_file = latex_file_re.sub(".dvi", latex_file)
426 ps_file = latex_file_re.sub(".ps", latex_file)
428 dvips_call = f'{dvips} -i -o "{ps_file}" "{dvi_file}"'
431 dvips_status, dvips_stdout = run_command(dvips_call)
433 warning(f'Failed: {os.path.basename(dvips)} {dvi_file} ... looking for PDF')
436 return legacy_conversion_step3(latex_file, dpi, output_format, dvips_failed, skipMetrics)
439 # Either latex and dvips have been run and we have a ps file, or
440 # pdflatex has been run and we have a pdf file. Proceed with pdftocairo or gs.
441 def legacy_conversion_step3(latex_file, dpi, output_format, dvips_failed, skipMetrics = False):
442 # External programs used by the script.
443 gs = find_exe_or_terminate(["gswin32c", "gswin64c", "gs"])
444 pnmcrop = find_exe(["pnmcrop"])
445 pdftocairo = find_exe(["pdftocairo"])
446 epstopdf = find_exe(["epstopdf"])
447 use_pdftocairo = pdftocairo != None and output_format == "png"
448 if use_pdftocairo and os.name == 'nt':
449 # On Windows, check for png support (see #10718)
450 conv_status, conv_stdout = run_command("%s --help" % pdftocairo)
451 use_pdftocairo = '-png' in conv_stdout
458 pdf_file = latex_file_re.sub(".pdf", latex_file)
459 ps_file = latex_file_re.sub(".ps", latex_file)
461 # The latex file name without extension
462 latex_file_root = latex_file_re.sub("", latex_file)
464 # Extract resolution data for the converter from the log file.
465 log_file = latex_file_re.sub(".log", latex_file)
466 resolution = extract_resolution(log_file, dpi)
468 # Check whether some pages produced errors
469 error_pages = check_latex_log(log_file)
471 # Older versions of gs have problems with a large degree of
472 # anti-aliasing at high resolutions
479 if output_format == "ppm":
483 # Extract the metrics from the log file
484 legacy_metrics = legacy_extract_metrics_info(log_file)
486 # List of pages which failed to produce a correct output
489 # Generate the bitmap images
491 # dvips failed, maybe there's a PDF, try to produce bitmaps
493 conv_call = '%s -png -transp -r %d "%s" "%s"' \
494 % (pdftocairo, resolution, pdf_file, latex_file_root)
496 conv_status, conv_stdout = run_command(conv_call)
498 seqnum_re = re.compile("-([0-9]+)")
499 for name in glob.glob("%s-*.png" % latex_file_root):
500 match = seqnum_re.search(name)
502 new_name = seqnum_re.sub(str(int(match.group(1))), name)
503 os.rename(name, new_name)
505 conv_call = '%s -dNOPAUSE -dBATCH -dSAFER -sDEVICE=%s ' \
506 '-sOutputFile="%s%%d.%s" ' \
507 '-dGraphicsAlphaBit=%d -dTextAlphaBits=%d ' \
509 % (gs, gs_device, latex_file_root, \
510 gs_ext, alpha, alpha, resolution, pdf_file)
512 conv_status, conv_stdout = run_command(conv_call)
515 error(f"Failed: {os.path.basename(conv)} {pdf_file}")
517 # Model for calling the converter on each file
518 if use_pdftocairo and epstopdf != None:
519 conv_call = '%s -png -transp -singlefile -r %d "%%s" "%s%%d"' \
520 % (pdftocairo, resolution, latex_file_root)
522 conv_call = '%s -dNOPAUSE -dBATCH -dSAFER -sDEVICE=%s ' \
523 '-sOutputFile="%s%%d.%s" ' \
524 '-dGraphicsAlphaBit=%d -dTextAlphaBits=%d ' \
526 % (gs, gs_device, latex_file_root, \
527 gs_ext, alpha, alpha, resolution)
530 # Collect all the PostScript files (like *.001, *.002, ...)
531 ps_files = glob.glob("%s.[0-9][0-9][0-9]" % latex_file_root)
534 # Call the converter for each file
535 for file in ps_files:
537 progress(f"Processing page {i}, file {file}")
538 if use_pdftocairo and epstopdf != None:
539 conv_name = "epstopdf"
540 conv_status, conv_stdout = run_command(f"{epstopdf} --outfile={file}.pdf {file}")
542 conv_name = "pdftocairo"
544 conv_status, conv_stdout = run_command(conv_call % (file, i))
546 conv_name = "ghostscript"
547 conv_status, conv_stdout = run_command(conv_call % (i, file))
550 # The converter failed, keep track of this
551 warning(f"{conv_name} failed on page {i}, file {file}")
552 failed_pages.append(i)
554 # Pass failed pages to pdflatex
555 if len(failed_pages) > 0:
556 warning("Now trying to obtain failed previews through pdflatex")
557 error_count = legacy_conversion_pdflatex(latex_file, failed_pages,
558 legacy_metrics, use_pdftocairo, conv, gs_device, gs_ext, alpha,
559 resolution, output_format)
563 # Invalidate metrics for pages that produced errors
564 if len(error_pages) > 0:
565 for index in error_pages:
566 if index not in failed_pages:
567 legacy_metrics.pop(index - 1)
568 legacy_metrics.insert(index - 1, (index, -1.0))
571 # Crop the ppm images
572 if pnmcrop != None and output_format == "ppm":
573 crop_files(pnmcrop, latex_file_root)
575 # Allow to skip .metrics creation for custom management
576 # (see the dvipng method)
578 # Extract metrics info from the log file.
579 metrics_file = latex_file_re.sub(".metrics", latex_file)
580 write_metrics_info(legacy_metrics, metrics_file)
582 warning("Failed to produce %d preview snippet(s)" % error_count)
584 return (0, legacy_metrics)
587 if __name__ == "__main__":
588 sys.exit(legacy_conversion(sys.argv)[0])