]> git.lyx.org Git - lyx.git/blob - lib/scripts/legacy_lyxpreview2ppm.py
* layouttranslations.review - review of all langs.
[lyx.git] / lib / scripts / legacy_lyxpreview2ppm.py
1 # -*- coding: utf-8 -*-
2
3 # file legacy_lyxpreview2ppm.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 # Full author contact details are available in file CREDITS
9
10 # with much advice from members of the preview-latex project:
11 #   David Kastrup, dak@gnu.org and
12 #   Jan-Åke Larsson, jalar@mai.liu.se.
13 # and with much help testing the code under Windows from
14 #   Paul A. Rubin, rubin@msu.edu.
15
16 # This script takes a LaTeX file and generates a collection of
17 # png or ppm image files, one per previewed snippet.
18 # Example usage:
19 # legacy_lyxpreview2bitmap.py 0lyxpreview.tex 128 ppm 000000 faf0e6
20
21 # This script takes five arguments:
22 # TEXFILE:       the name of the .tex file to be converted.
23 # SCALEFACTOR:   a scale factor, used to ascertain the resolution of the
24 #                generated image which is then passed to gs.
25 # OUTPUTFORMAT:  the format of the output bitmap image files.
26 #                This particular script can produce only "ppm" format output.
27 # FG_COLOR:      the foreground color as a hexadecimal string, eg '000000'.
28 # BG_COLOR:      the background color as a hexadecimal string, eg 'faf0e6'.
29
30 # Decomposing TEXFILE's name as DIR/BASE.tex, this script will,
31 # if executed successfully, leave in DIR:
32 # * a (possibly large) number of image files with names
33 #   like BASE[0-9]+.(ppm|png)
34 # * a file BASE.metrics, containing info needed by LyX to position
35 #   the images correctly on the screen.
36
37 # The script uses several external programs and files:
38 # * python 2.4 or later (subprocess module);
39 # * A latex executable;
40 # * preview.sty;
41 # * dvips;
42 # * gs;
43 # * pdflatex (optional);
44 # * pnmcrop (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 gs to produce bitmaps
60 # 4) Otherwise call 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 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
78 import glob, os, pipes, re, string, sys
79
80 from lyxpreview_tools import copyfileobj, error, filter_pages, find_exe, \
81      find_exe_or_terminate, join_metrics_and_rename, latex_commands, \
82      latex_file_re, make_texcolor, mkstemp, pdflatex_commands, progress, \
83      run_command, run_latex, warning, write_metrics_info
84
85
86 def usage(prog_name):
87     return "Usage: %s <latex file> <dpi> ppm <fg color> <bg color>\n" \
88            "\twhere the colors are hexadecimal strings, eg 'faf0e6'" \
89            % prog_name
90
91 # Returns a list of tuples containing page number and ascent fraction
92 # extracted from dvipng output.
93 # Use write_metrics_info to create the .metrics file with this info
94 def legacy_extract_metrics_info(log_file):
95
96     log_re = re.compile("Preview: ([ST])")
97     data_re = re.compile("(-?[0-9]+) (-?[0-9]+) (-?[0-9]+) (-?[0-9]+)")
98
99     tp_ascent  = 0.0
100     tp_descent = 0.0
101
102     success = 0
103     results = []
104     try:
105         for line in open(log_file, 'r').readlines():
106             match = log_re.match(line)
107             if match == None:
108                 continue
109
110             snippet = (match.group(1) == 'S')
111             success = 1
112             match = data_re.search(line)
113             if match == None:
114                 error("Unexpected data in %s\n%s" % (log_file, line))
115
116             if snippet:
117                 ascent  = string.atoi(match.group(2))
118                 descent = string.atoi(match.group(3))
119
120                 frac = 0.5
121                 if ascent >= 0 and descent >= 0:
122                     ascent = float(ascent) + tp_ascent
123                     descent = float(descent) - tp_descent
124
125                     if abs(ascent + descent) > 0.1:
126                         frac = ascent / (ascent + descent)
127
128                     # Sanity check
129                     if frac < 0 or frac > 1:
130                             frac = 0.5
131
132                 results.append((int(match.group(1)), frac))
133
134             else:
135                 tp_descent = string.atof(match.group(2))
136                 tp_ascent  = string.atof(match.group(4))
137
138     except:
139         # Unable to open the file, but do nothing here because
140         # the calling function will act on the value of 'success'.
141         warning('Warning in legacy_extract_metrics_info! Unable to open "%s"' % log_file)
142         warning(`sys.exc_type` + ',' + `sys.exc_value`)
143
144     if success == 0:
145         error("Failed to extract metrics info from %s" % log_file)
146
147     return results
148
149 def extract_resolution(log_file, dpi):
150     fontsize_re = re.compile("Preview: Fontsize")
151     magnification_re = re.compile("Preview: Magnification")
152     extract_decimal_re = re.compile("([0-9\.]+)")
153     extract_integer_re = re.compile("([0-9]+)")
154
155     found_fontsize = 0
156     found_magnification = 0
157
158     # Default values
159     magnification = 1000.0
160     fontsize = 10.0
161
162     try:
163         for line in open(log_file, 'r').readlines():
164             if found_fontsize and found_magnification:
165                 break
166
167             if not found_fontsize:
168                 match = fontsize_re.match(line)
169                 if match != None:
170                     match = extract_decimal_re.search(line)
171                     if match == None:
172                         error("Unable to parse: %s" % line)
173                     fontsize = string.atof(match.group(1))
174                     found_fontsize = 1
175                     continue
176
177             if not found_magnification:
178                 match = magnification_re.match(line)
179                 if match != None:
180                     match = extract_integer_re.search(line)
181                     if match == None:
182                         error("Unable to parse: %s" % line)
183                     magnification = string.atof(match.group(1))
184                     found_magnification = 1
185                     continue
186
187     except:
188         warning('Warning in extract_resolution! Unable to open "%s"' % log_file)
189         warning(`sys.exc_type` + ',' + `sys.exc_value`)
190
191     # This is safe because both fontsize and magnification have
192     # non-zero default values.
193     return dpi * (10.0 / fontsize) * (1000.0 / magnification)
194
195
196 def legacy_latex_file(latex_file, fg_color, bg_color):
197     use_preview_re = re.compile(r"\s*\\usepackage\[([^]]+)\]{preview}")
198     fg_color_gr = make_texcolor(fg_color, True)
199     bg_color_gr = make_texcolor(bg_color, True)
200
201     tmp = mkstemp()
202
203     success = 0
204     try:
205         f = open(latex_file, 'r')
206     except:
207         # Unable to open the file, but do nothing here because
208         # the calling function will act on the value of 'success'.
209         warning('Warning in legacy_latex_file! Unable to open "%s"' % latex_file)
210         warning(`sys.exc_type` + ',' + `sys.exc_value`)
211
212     for line in f.readlines():
213         if success:
214             tmp.write(line)
215             continue
216         match = use_preview_re.match(line)
217         if match == None:
218             tmp.write(line)
219             continue
220         success = 1
221         # Package order: color should be loaded before preview
222         # Preview options: add the options lyx and tightpage
223         tmp.write(r"""
224 \usepackage{color}
225 \definecolor{fg}{rgb}{%s}
226 \definecolor{bg}{rgb}{%s}
227 \pagecolor{bg}
228 \usepackage[%s,lyx,tightpage]{preview}
229 \makeatletter
230 \g@addto@macro\preview{\begingroup\color{bg}\special{ps::clippath fill}\color{fg}}
231 \g@addto@macro\endpreview{\endgroup}
232 \makeatother
233 """ % (fg_color_gr, bg_color_gr, match.group(1)))
234
235     if success:
236         copyfileobj(tmp, open(latex_file,"wb"), 1)
237
238     return success
239
240
241 def crop_files(pnmcrop, basename):
242     t = pipes.Template()
243     t.append('%s -left' % pnmcrop, '--')
244     t.append('%s -right' % pnmcrop, '--')
245
246     for file in glob.glob("%s*.ppm" % basename):
247         tmp = mkstemp()
248         new = t.open(file, "r")
249         copyfileobj(new, tmp)
250         if not new.close():
251             copyfileobj(tmp, open(file,"wb"), 1)
252
253
254 def legacy_conversion(argv, skipMetrics = False):
255     # Parse and manipulate the command line arguments.
256     if len(argv) == 7:
257         latex = [argv[6]]
258     elif len(argv) != 6:
259         error(usage(argv[0]))
260     else:
261         latex = None
262
263     dir, latex_file = os.path.split(argv[1])
264     if len(dir) != 0:
265         os.chdir(dir)
266
267     dpi = string.atoi(argv[2])
268
269     output_format = argv[3]
270
271     fg_color = argv[4]
272     bg_color = argv[5]
273
274     # External programs used by the script.
275     latex = find_exe_or_terminate(latex or latex_commands)
276
277     pdf_output = latex in pdflatex_commands
278
279     return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
280         bg_color, latex, pdf_output, skipMetrics)
281
282
283 # Add color info to the latex file, since ghostscript doesn't
284 # have the option to set foreground and background colors on
285 # the command line. Run the resulting file through latex.
286 def legacy_conversion_step1(latex_file, dpi, output_format, fg_color, bg_color,
287                             latex, pdf_output = False, skipMetrics = False):
288
289     # Move color information, lyx and tightpage options into the latex file.
290     if not legacy_latex_file(latex_file, fg_color, bg_color):
291         error("""Unable to move the color information, and the lyx and tightpage
292             options of preview-latex, into the latex file""")
293
294     # Compile the latex file.
295     latex_status, latex_stdout = run_latex(latex, latex_file)
296
297     if pdf_output:
298         return legacy_conversion_step3(latex_file, dpi, output_format, True, skipMetrics)
299     else:
300         return legacy_conversion_step2(latex_file, dpi, output_format, skipMetrics)
301
302 # Creates a new LaTeX file from the original with pages specified in
303 # failed_pages, pass it through pdflatex and updates the metrics
304 # from the standard legacy route
305 def legacy_conversion_pdflatex(latex_file, failed_pages, legacy_metrics, gs,
306     gs_device, gs_ext, alpha, resolution, output_format):
307
308     # Search for pdflatex executable
309     pdflatex = find_exe(["pdflatex"])
310     if pdflatex == None:
311         warning("Can't find pdflatex. Some pages failed with all the possible routes.")
312     else:
313         # Create a new LaTeX file from the original but only with failed pages
314         pdf_latex_file = latex_file_re.sub("_pdflatex.tex", latex_file)
315         filter_pages(latex_file, pdf_latex_file, failed_pages)
316
317         # pdflatex call
318         pdflatex_status, pdflatex_stdout = run_latex(pdflatex, pdf_latex_file)
319
320         pdf_file = latex_file_re.sub(".pdf", pdf_latex_file)
321
322         # GhostScript call to produce bitmaps
323         gs_call = '%s -dNOPAUSE -dBATCH -dSAFER -sDEVICE=%s ' \
324                     '-sOutputFile="%s%%d.%s" ' \
325                     '-dGraphicsAlphaBit=%d -dTextAlphaBits=%d ' \
326                     '-r%f "%s"' \
327                     % (gs, gs_device, latex_file_re.sub("", pdf_latex_file), \
328                         gs_ext, alpha, alpha, resolution, pdf_file)
329         gs_status, gs_stdout = run_command(gs_call)
330         if gs_status:
331             # Give up!
332             warning("Some pages failed with all the possible routes")
333         else:
334             # We've done it!
335             pdf_log_file = latex_file_re.sub(".log", pdf_latex_file)
336             pdf_metrics = legacy_extract_metrics_info(pdf_log_file)
337
338             original_bitmap = latex_file_re.sub("%d." + output_format, pdf_latex_file)
339             destination_bitmap = latex_file_re.sub("%d." + output_format, latex_file)
340
341             # Join the metrics with the those from dvips and rename the bitmap images
342             join_metrics_and_rename(legacy_metrics, pdf_metrics, failed_pages,
343                 original_bitmap, destination_bitmap)
344
345
346 # The file has been processed through latex and we expect dvi output.
347 # Run dvips, taking note whether it was successful.
348 def legacy_conversion_step2(latex_file, dpi, output_format, skipMetrics = False):
349     # External programs used by the script.
350     dvips   = find_exe_or_terminate(["dvips"])
351
352     # Run the dvi file through dvips.
353     dvi_file = latex_file_re.sub(".dvi", latex_file)
354     ps_file  = latex_file_re.sub(".ps",  latex_file)
355
356     dvips_call = '%s -i -o "%s" "%s"' % (dvips, ps_file, dvi_file)
357     dvips_failed = False
358
359     dvips_status, dvips_stdout = run_command(dvips_call)
360     if dvips_status:
361         warning('Failed: %s %s ... looking for PDF' \
362             % (os.path.basename(dvips), dvi_file))
363         dvips_failed = True
364
365     return legacy_conversion_step3(latex_file, dpi, output_format, dvips_failed, skipMetrics)
366
367
368 # Either latex and dvips have been run and we have a ps file, or
369 # pdflatex has been run and we have a pdf file. Proceed with gs.
370 def legacy_conversion_step3(latex_file, dpi, output_format, dvips_failed, skipMetrics = False):
371     # External programs used by the script.
372     gs      = find_exe_or_terminate(["gswin32c", "gswin64c", "gs"])
373     pnmcrop = find_exe(["pnmcrop"])
374
375     # Files to process
376     pdf_file  = latex_file_re.sub(".pdf", latex_file)
377     ps_file  = latex_file_re.sub(".ps",  latex_file)
378
379     # Extract resolution data for gs from the log file.
380     log_file = latex_file_re.sub(".log", latex_file)
381     resolution = extract_resolution(log_file, dpi)
382
383     # Older versions of gs have problems with a large degree of
384     # anti-aliasing at high resolutions
385     alpha = 4
386     if resolution > 150:
387         alpha = 2
388
389     gs_device = "png16m"
390     gs_ext = "png"
391     if output_format == "ppm":
392         gs_device = "pnmraw"
393         gs_ext = "ppm"
394
395     # Extract the metrics from the log file
396     legacy_metrics = legacy_extract_metrics_info(log_file)
397
398     # List of pages which failed to produce a correct output
399     failed_pages = []
400
401     # Generate the bitmap images
402     if dvips_failed:
403         # dvips failed, maybe there's a PDF, try to produce bitmaps
404         gs_call = '%s -dNOPAUSE -dBATCH -dSAFER -sDEVICE=%s ' \
405                   '-sOutputFile="%s%%d.%s" ' \
406                   '-dGraphicsAlphaBit=%d -dTextAlphaBits=%d ' \
407                   '-r%f "%s"' \
408                   % (gs, gs_device, latex_file_re.sub("", latex_file), \
409                      gs_ext, alpha, alpha, resolution, pdf_file)
410
411         gs_status, gs_stdout = run_command(gs_call)
412         if gs_status:
413             error("Failed: %s %s" % (os.path.basename(gs), ps_file))
414     else:
415         # Model for calling gs on each file
416         gs_call = '%s -dNOPAUSE -dBATCH -dSAFER -sDEVICE=%s ' \
417                   '-sOutputFile="%s%%d.%s" ' \
418                   '-dGraphicsAlphaBit=%d -dTextAlphaBits=%d ' \
419                   '-r%f "%%s"' \
420                   % (gs, gs_device, latex_file_re.sub("", latex_file), \
421                      gs_ext, alpha, alpha, resolution)
422
423         i = 0
424         # Collect all the PostScript files (like *.001, *.002, ...)
425         ps_files = glob.glob("%s.[0-9][0-9][0-9]" % latex_file_re.sub("", latex_file))
426         ps_files.sort()
427
428         # Call GhostScript for each file
429         for file in ps_files:
430             i = i + 1
431             progress("Processing page %s, file %s" % (i, file))
432             gs_status, gs_stdout = run_command(gs_call % (i, file))
433             if gs_status:
434                 # gs failed, keep track of this
435                 warning("Ghostscript failed on page %s, file %s" % (i, file))
436                 failed_pages.append(i)
437
438     # Pass failed pages to pdflatex
439     if len(failed_pages) > 0:
440         legacy_conversion_pdflatex(latex_file, failed_pages, legacy_metrics, gs,
441             gs_device, gs_ext, alpha, resolution, output_format)
442
443     # Crop the images
444     if pnmcrop != None:
445         crop_files(pnmcrop, latex_file_re.sub("", latex_file))
446
447     # Allow to skip .metrics creation for custom management
448     # (see the dvipng method)
449     if not skipMetrics:
450         # Extract metrics info from the log file.
451         metrics_file = latex_file_re.sub(".metrics", latex_file)
452         write_metrics_info(legacy_metrics, metrics_file)
453
454     return (0, legacy_metrics)
455
456
457 if __name__ == "__main__":
458     sys.exit(legacy_conversion(sys.argv)[0])