]> git.lyx.org Git - lyx.git/blob - lib/scripts/legacy_lyxpreview2ppm.py
Cut excessively long author lists before parsing them for the GUI
[lyx.git] / lib / scripts / legacy_lyxpreview2ppm.py
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.
4
5 # author Angus Leeming
6 # Full author contact details are available in file CREDITS
7
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.
13
14 # This script takes a LaTeX file and generates a collection of
15 # png or ppm image files, one per previewed snippet.
16 # Example usage:
17 # legacy_lyxpreview2bitmap.py 0lyxpreview.tex 128 ppm 000000 faf0e6
18
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'.
27
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.
34
35 # The script uses several external programs and files:
36 # * python 2.4 or later (subprocess module);
37 # * A latex executable;
38 # * preview.sty;
39 # * dvips;
40 # * gs;
41 # * pdflatex (optional);
42 # * pnmcrop (optional).
43 # * pdftocairo (optional).
44 # * epstopdf (optional).
45
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/
50
51 # What does this script do?
52 # [legacy_conversion]
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)
66
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
72 # (step 3).
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,
75 # (step 5, 6).
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.
79
80 import glob, os, pipes, re, sys, tempfile
81
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
86
87
88 def usage(prog_name):
89     return "Usage: %s <latex file> <dpi> ppm <fg color> <bg color>\n" \
90            "\twhere the colors are hexadecimal strings, eg 'faf0e6'" \
91            % prog_name
92
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):
97
98     log_re = re.compile(b"Preview: ([ST])")
99     data_re = re.compile(b"(-?[0-9]+) (-?[0-9]+) (-?[0-9]+) (-?[0-9]+)")
100
101     tp_ascent  = 0.0
102     tp_descent = 0.0
103
104     success = 0
105     results = []
106     try:
107         for line in open(log_file, 'rb').readlines():
108             match = log_re.match(line)
109             if match == None:
110                 continue
111
112             snippet = (match.group(1) == b'S')
113             success = 1
114             match = data_re.search(line)
115             if match == None:
116                 error(f"Unexpected data in {log_file}\n{line}")
117
118             if snippet:
119                 ascent  = float(match.group(2))
120                 descent = float(match.group(3))
121
122                 frac = 0.5
123                 if ascent == 0 and descent == 0:
124                     # This is an empty image, forbid its display
125                     frac = -1.0
126                 elif ascent >= 0 or descent >= 0:
127                     ascent = ascent + tp_ascent
128                     descent = descent - tp_descent
129
130                     if abs(ascent + descent) > 0.1:
131                         frac = ascent / (ascent + descent)
132
133                     # Sanity check
134                     if frac < 0 or frac > 1:
135                             frac = 0.5
136
137                 results.append((int(match.group(1)), frac))
138
139             else:
140                 tp_descent = float(match.group(2))
141                 tp_ascent  = float(match.group(4))
142
143     except:
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]))
148
149     if success == 0:
150         error(f"Failed to extract metrics info from {log_file}")
151
152     return results
153
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]+)")
159
160     found_fontsize = 0
161     found_magnification = 0
162
163     # Default values
164     magnification = 1000.0
165     fontsize = 10.0
166
167     try:
168         for line in open(log_file, 'rb').readlines():
169             if found_fontsize and found_magnification:
170                 break
171
172             if not found_fontsize:
173                 match = fontsize_re.match(line)
174                 if match != None:
175                     match = extract_decimal_re.search(line)
176                     if match == None:
177                         error(f"Unable to parse: {line}")
178                     fontsize = float(match.group(1))
179                     found_fontsize = 1
180                     continue
181
182             if not found_magnification:
183                 match = magnification_re.match(line)
184                 if match != None:
185                     match = extract_integer_re.search(line)
186                     if match == None:
187                         error("Unable to parse: %s" % line)
188                     magnification = float(match.group(1))
189                     found_magnification = 1
190                     continue
191
192     except:
193         warning('Warning in extract_resolution! Unable to open "%s"' % log_file)
194         warning(repr(sys.exc_info()[0]) + ',' + repr(sys.exc_info()[1]))
195
196     # This is safe because both fontsize and magnification have
197     # non-zero default values.
198     return dpi * (10.0 / fontsize) * (1000.0 / magnification)
199
200
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)
206
207     tmp = tempfile.TemporaryFile()
208
209     success = 0
210     try:
211         f = open(latex_file, 'rb')
212     except:
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]))
217
218     polyglossia = False
219     for line in f.readlines():
220         if success:
221             tmp.write(line)
222             continue
223         match = use_preview_re.match(line)
224         polymatch = use_polyglossia_re.match(line)
225         # Package order:
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
229         if match == None:
230             if polymatch == None:
231                 tmp.write(line)
232                 continue
233             else:
234                 tmp.write(b"""
235 \\usepackage{color}
236 \\definecolor{lyxfg}{rgb}{%s}
237 \\definecolor{lyxbg}{rgb}{%s}
238 \\pagecolor{lyxbg}
239 \\usepackage{polyglossia}
240 """ % (fg_color_gr, bg_color_gr))
241                 polyglossia = True
242                 continue
243         success = 1
244         # Preview options: add the options lyx and tightpage
245         previewopts = match.group(1)
246         if not polyglossia:
247             tmp.write(b"""
248 \\usepackage{color}
249 \\definecolor{lyxfg}{rgb}{%s}
250 \\definecolor{lyxbg}{rgb}{%s}
251 \\pagecolor{lyxbg}
252 \\makeatletter
253 \\def\\@tempa{cmr}
254 \\ifx\\f@family\\@tempa
255   \\IfFileExists{lmodern.sty}{\\usepackage{lmodern}}{\\usepackage{ae,aecompl}}
256 \\fi
257 """ % (fg_color_gr, bg_color_gr))
258         tmp.write(b"""
259 \\usepackage[%s,tightpage]{preview}
260 \\makeatletter
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
269     \\fi
270   }
271 \\fi
272 \\g@addto@macro\\pr@ship@end{\\pr@set@pagerightoffset}
273 \\makeatother
274 """ % previewopts)
275     if success:
276         copyfileobj(tmp, open(latex_file,"wb"), 1)
277
278     return success
279
280
281 def crop_files(pnmcrop, basename):
282     t = pipes.Template()
283     t.append('%s -left' % pnmcrop, '--')
284     t.append('%s -right' % pnmcrop, '--')
285
286     for file in glob.glob("%s*.ppm" % basename):
287         tmp = tempfile.TemporaryFile()
288         new = t.open(file, "r")
289         copyfileobj(new, tmp)
290         if not new.close():
291             copyfileobj(tmp, open(file,"wb"), 1)
292
293
294 def legacy_conversion(argv, skipMetrics = False):
295     # Parse and manipulate the command line arguments.
296     if len(argv) == 7:
297         latex = [argv[6]]
298     elif len(argv) != 6:
299         error(usage(argv[0]))
300     else:
301         latex = None
302
303     dir, latex_file = os.path.split(argv[1])
304     if len(dir) != 0:
305         os.chdir(dir)
306
307     dpi = int(argv[2])
308
309     output_format = argv[3]
310
311     fg_color = argv[4]
312     bg_color = argv[5]
313
314     # External programs used by the script.
315     latex = find_exe_or_terminate(latex or latex_commands)
316
317     pdf_output = latex in pdflatex_commands
318
319     return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
320         bg_color, latex, pdf_output, skipMetrics)
321
322
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):
328
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""")
333
334     # Compile the latex file.
335     latex_status, latex_stdout = run_latex(latex, latex_file)
336     if latex_status:
337         progress("Will try to recover from %s failure" % latex)
338
339     if pdf_output:
340         return legacy_conversion_step3(latex_file, dpi, output_format, True, skipMetrics)
341     else:
342         return legacy_conversion_step2(latex_file, dpi, output_format, skipMetrics)
343
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):
349
350     error_count = 0
351
352     # Search for pdflatex executable
353     pdflatex = find_exe(["pdflatex"])
354     if pdflatex == None:
355         warning("Can't find pdflatex. Some pages failed with all the possible routes.")
356         failed_pages = []
357     else:
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)
361
362         # pdflatex call
363         error_pages = []
364         pdflatex_status, pdflatex_stdout = run_latex(pdflatex, pdf_latex_file)
365         if pdflatex_status:
366             error_pages = check_latex_log(latex_file_re.sub(".log", pdf_latex_file))
367
368         pdf_file = latex_file_re.sub(".pdf", pdf_latex_file)
369         latex_file_root = latex_file_re.sub("", pdf_latex_file)
370
371         # Converter call to produce bitmaps
372         if use_pdftocairo:
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)
376             if not conv_status:
377                 seqnum_re = re.compile("-([0-9]+)")
378                 for name in glob.glob("%s-*.png" % latex_file_root):
379                     match = seqnum_re.search(name)
380                     if match != None:
381                         new_name = seqnum_re.sub(str(int(match.group(1))), name)
382                         os.rename(name, new_name)
383         else:
384             conv_call = '%s -dNOPAUSE -dBATCH -dSAFER -sDEVICE=%s ' \
385                         '-sOutputFile="%s%%d.%s" ' \
386                         '-dGraphicsAlphaBit=%d -dTextAlphaBits=%d ' \
387                         '-r%f "%s"' \
388                         % (conv, gs_device, latex_file_root, \
389                             gs_ext, alpha, alpha, resolution, pdf_file)
390             conv_status, conv_stdout = run_command(conv_call)
391
392         if conv_status:
393             # Give up!
394             warning("Some pages failed with all the possible routes")
395             failed_pages = []
396         else:
397             # We've done it!
398             pdf_log_file = latex_file_re.sub(".log", pdf_latex_file)
399             pdf_metrics = legacy_extract_metrics_info(pdf_log_file)
400
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))
406                     error_count += 1
407
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)
410
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)
414
415     return error_count
416
417
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"])
423
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)
427
428     dvips_call = f'{dvips} -i -o "{ps_file}" "{dvi_file}"'
429     dvips_failed = False
430
431     dvips_status, dvips_stdout = run_command(dvips_call)
432     if dvips_status:
433         warning(f'Failed: {os.path.basename(dvips)} {dvi_file} ... looking for PDF')
434         dvips_failed = True
435
436     return legacy_conversion_step3(latex_file, dpi, output_format, dvips_failed, skipMetrics)
437
438
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
452     if use_pdftocairo:
453         conv = pdftocairo
454     else:
455         conv = gs
456
457     # Files to process
458     pdf_file  = latex_file_re.sub(".pdf", latex_file)
459     ps_file  = latex_file_re.sub(".ps",  latex_file)
460
461     # The latex file name without extension
462     latex_file_root = latex_file_re.sub("", latex_file)
463
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)
467
468     # Check whether some pages produced errors
469     error_pages = check_latex_log(log_file)
470
471     # Older versions of gs have problems with a large degree of
472     # anti-aliasing at high resolutions
473     alpha = 4
474     if resolution > 150:
475         alpha = 2
476
477     gs_device = "png16m"
478     gs_ext = "png"
479     if output_format == "ppm":
480         gs_device = "pnmraw"
481         gs_ext = "ppm"
482
483     # Extract the metrics from the log file
484     legacy_metrics = legacy_extract_metrics_info(log_file)
485
486     # List of pages which failed to produce a correct output
487     failed_pages = []
488
489     # Generate the bitmap images
490     if dvips_failed:
491         # dvips failed, maybe there's a PDF, try to produce bitmaps
492         if use_pdftocairo:
493             conv_call = '%s -png -transp -r %d "%s" "%s"' \
494                         % (pdftocairo, resolution, pdf_file, latex_file_root)
495
496             conv_status, conv_stdout = run_command(conv_call)
497             if not conv_status:
498                 seqnum_re = re.compile("-([0-9]+)")
499                 for name in glob.glob("%s-*.png" % latex_file_root):
500                     match = seqnum_re.search(name)
501                     if match != None:
502                         new_name = seqnum_re.sub(str(int(match.group(1))), name)
503                         os.rename(name, new_name)
504         else:
505             conv_call = '%s -dNOPAUSE -dBATCH -dSAFER -sDEVICE=%s ' \
506                       '-sOutputFile="%s%%d.%s" ' \
507                       '-dGraphicsAlphaBit=%d -dTextAlphaBits=%d ' \
508                       '-r%f "%s"' \
509                       % (gs, gs_device, latex_file_root, \
510                          gs_ext, alpha, alpha, resolution, pdf_file)
511
512             conv_status, conv_stdout = run_command(conv_call)
513
514         if conv_status:
515             error(f"Failed: {os.path.basename(conv)} {pdf_file}")
516     else:
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)
521         else:
522             conv_call = '%s -dNOPAUSE -dBATCH -dSAFER -sDEVICE=%s ' \
523                         '-sOutputFile="%s%%d.%s" ' \
524                         '-dGraphicsAlphaBit=%d -dTextAlphaBits=%d ' \
525                         '-r%f "%%s"' \
526                         % (gs, gs_device, latex_file_root, \
527                            gs_ext, alpha, alpha, resolution)
528
529         i = 0
530         # Collect all the PostScript files (like *.001, *.002, ...)
531         ps_files = glob.glob("%s.[0-9][0-9][0-9]" % latex_file_root)
532         ps_files.sort()
533
534         # Call the converter for each file
535         for file in ps_files:
536             i = i + 1
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}")
541                 if not conv_status:
542                     conv_name = "pdftocairo"
543                     file = file + ".pdf"
544                     conv_status, conv_stdout = run_command(conv_call % (file, i))
545             else:
546                 conv_name = "ghostscript"
547                 conv_status, conv_stdout = run_command(conv_call % (i, file))
548
549             if conv_status:
550                 # The converter failed, keep track of this
551                 warning(f"{conv_name} failed on page {i}, file {file}")
552                 failed_pages.append(i)
553
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)
560     else:
561         error_count = 0
562
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))
569                 error_count += 1
570
571     # Crop the ppm images
572     if pnmcrop != None and output_format == "ppm":
573         crop_files(pnmcrop, latex_file_root)
574
575     # Allow to skip .metrics creation for custom management
576     # (see the dvipng method)
577     if not skipMetrics:
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)
581         if error_count:
582             warning("Failed to produce %d preview snippet(s)" % error_count)
583
584     return (0, legacy_metrics)
585
586
587 if __name__ == "__main__":
588     sys.exit(legacy_conversion(sys.argv)[0])