]> git.donarmstrong.com Git - lilypond.git/blob - scripts/ly2dvi.py
7b8c519955223992db5600962d5e172d1aba07ad
[lilypond.git] / scripts / ly2dvi.py
1 #!@PYTHON@
2 #
3 # ly2dvi.py -- Run LilyPond, add titles to bare score, generate printable
4 #              document
5 #              Invokes: lilypond, latex (or pdflatex), dvips, ps2pdf, gs
6
7 # source file of the GNU LilyPond music typesetter
8
9 # (c) 1998--2002  Han-Wen Nienhuys <hanwen@cs.uu.nl>
10 #                 Jan Nieuwenhuizen <janneke@gnu.org>
11
12 # This is the third incarnation of ly2dvi.
13 #
14 # Earlier incarnations of ly2dvi were written by
15 # Jeffrey B. Reed<daboys@austin.rr.com> (Python version)
16 # Jan Arne Fagertun <Jan.A.Fagertun@@energy.sintef.no> (Bourne shell script)
17 #
18
19 # Note: gettext work best if we use ' for docstrings and "
20 #       for gettextable strings.
21 #       --> DO NOT USE ''' for docstrings.
22
23
24 '''
25 TODO:
26
27   * figure out which set of command line options should make ly2dvi:
28
29       na: create tex only?  
30       na: create latex only? 
31       na: create tex and latex
32       default: create dvi only
33       na: create tex, latex and dvi
34       -P: create dvi and ps
35       -p: create pdf
36       na: * create ps only
37
38      etc.
39
40   * for foo.ly, rename ly2dvi.dir to out-ly2dvi, foo.ly2dvi, foo.dir ?
41      
42      
43   * move versatile taglines, 
44   
45      \header {
46         beginfooter=\mutopiaPD
47         endfooter=\tagline  -> 'lily was here <version>'
48      }
49
50      lilytagline (->lily was here), usertagline, copyright, lily-version
51      etc.
52
53   * head/header tagline/endfooter
54
55   * dvi from lilypond .tex output?  This is hairy, because we create dvi
56     from lilypond .tex *and* header output.
57
58   * multiple \score blocks?
59
60   * Introduce verbosity levels
61   
62      0  = QUIET: mute all command output, no ly2dvi progress
63      1  = BRIEF: mute all command output, only ly2dvi progress
64      2a = NORMAL: show only LilyPond command output, show ly2dvi progress
65      2b = NORMAL: show command output, show ly2dvi progress
66      3  = VERBOSE: show command output, run lilypond --verbose
67      4  = DEBUGGING: show all command output, run lilypond --verbose, print
68                    environment and all kinds of client side debugging stuff
69
70      Currently, we only have 1 and 4, but we kludge to have 2a and 4.
71 '''
72
73 import operator
74 import stat
75 import string
76 import traceback
77
78 ################################################################
79 # Users of python modules should include this snippet
80 # and customize variables below.
81
82 # We'll suffer this path init stuff as long as we don't install our
83 # python packages in <prefix>/lib/pythonx.y (and don't kludge around
84 # it as we do with teTeX on Red Hat Linux: set some environment var
85 # (PYTHONPATH) in profile)
86
87 # If set, LILYPONDPREFIX must take prevalence
88 # if datadir is not set, we're doing a build and LILYPONDPREFIX
89 import getopt, os, sys
90 datadir = '@local_lilypond_datadir@'
91 if not os.path.isdir (datadir):
92         datadir = '@lilypond_datadir@'
93 if os.environ.has_key ('LILYPONDPREFIX') :
94         datadir = os.environ['LILYPONDPREFIX']
95         while datadir[-1] == os.sep:
96                 datadir= datadir[:-1]
97
98 sys.path.insert (0, os.path.join (datadir, 'python'))
99
100 # Customize these
101 #if __name__ == '__main__':
102
103 import lilylib as ly
104 global _;_=ly._
105 global re;re = ly.re
106
107 # lilylib globals
108 program_name = 'ly2dvi'
109 verbose_p = 0
110 pseudo_filter_p = 0
111 original_dir = os.getcwd ()
112 temp_dir = os.path.join (original_dir,  '%s.dir' % program_name)
113 keep_temp_dir_p = 0
114 preview_resolution = 90
115 debug_p = 0
116
117 ## FIXME
118 ## ly2dvi: silly name?
119 ## do -P or -p by default?
120 ##help_summary = _ ("Run LilyPond using LaTeX for titling")
121 help_summary = _ ("Run LilyPond, add titles, generate printable document")
122 copyright = ('Han-Wen Nienhuys <hanwen@cs.uu.nl',
123              'Jan Nieuwenhuizen <janneke@gnu.org')
124
125 option_definitions = [
126         ('', 'd', 'dependencies',
127          _ ("write Makefile dependencies for every input file")),
128         ('', 'h', 'help', _ ("this help")),
129         ('', '', 'debug', _ ("print even more output")),
130         (_ ("DIR"), 'I', 'include', _ ("add DIR to LilyPond's search path")),
131         ('', 'k', 'keep',
132          _ ("keep all output, output to directory %s.dir") % program_name),
133         ('', '', 'no-lily', _ ("don't run LilyPond")),
134         ('', 'm', 'no-paper', _ ("produce MIDI output only")),
135         (_ ("FILE"), 'o', 'output', _ ("write ouput to FILE")),
136         (_ ("FILE"), 'f', 'find-pfa', _ ("find pfa fonts used in FILE")),
137         (_ ('RES'), '', 'preview-resolution',
138          _ ("set the resolution of the preview to RES")),
139         ('', 'P', 'postscript', _ ("generate PostScript output")),
140         ('', 'p', 'pdf', _ ("generate PDF output")),    
141         ('', '', 'pdftex', _ ("use pdflatex to generate a PDF output")),
142         # FIXME: preview, picture; to indicate creation of a PNG?
143         ('', '', 'preview', _ ("make a picture of the first system")),
144         (_ ("KEY=VAL"), 's', 'set', _ ("change global setting KEY to VAL")),
145         ('', 'V', 'verbose', _ ("verbose")),
146         ('', 'v', 'version', _ ("print version number")),
147         ('', 'w', 'warranty', _ ("show warranty and copyright")),
148         ]
149
150 # other globals
151 preview_p = 0
152 lilypond_error_p = 0
153
154 # Pdftex support
155 pdftex_p = 0
156 latex_cmd = 'latex'
157 tex_extension = '.tex'
158
159 # Debugging support -- do we need this?
160 lilypond_cmd = 'lilypond'
161 #lilypond_cmd = 'valgrind --suppressions=%(home)s/usr/src/guile-1.6.supp --num-callers=10 %(home)s/usr/src/lilypond/lily/out/lilypond '% { 'home' : '/home/hanwen' }
162
163
164 layout_fields = ['dedication', 'title', 'subtitle', 'subsubtitle',
165           'footer', 'head', 'composer', 'arranger', 'instrument',
166           'opus', 'piece', 'metre', 'meter', 'poet', 'texttranslator']
167
168
169 # init to empty; values here take precedence over values in the file
170
171 ## TODO: change name.
172 extra_init = {
173         'language' : [],
174         'latexheaders' : [],
175         'latexpackages' :  ['geometry'],
176         'latexoptions' : [],
177         'papersize' : [],
178         'pagenumber' : [1],
179         'textheight' : [], 
180         'linewidth' : [],
181         'orientation' : [],
182         'unit' : ['pt'],
183 }
184
185 extra_fields = extra_init.keys ()
186 fields = layout_fields + extra_fields
187
188 include_path = ['.']
189 lily_p = 1
190 paper_p = 1
191
192 output_name = ''
193
194 # Output formats that ly2dvi should create
195 targets = ['DVI', 'LATEX', 'MIDI', 'TEX']
196
197 track_dependencies_p = 0
198 dependency_files = []
199
200 #what a name.
201 def set_setting (dict, key, val):
202         try:
203                 val = string.atoi (val)
204         except ValueError:
205                 #ly.warning (_ ("invalid value: %s") % `val`)
206                 pass
207
208         if type(val) == type ('hoi'):
209                 try:
210                         val = string.atof (val)
211                 except ValueError:
212                         #ly.warning (_ ("invalid value: %s") % `val`)
213                         pass
214
215         try:
216                 dict[key].append (val)
217         except KeyError:
218                 ly.warning (_ ("no such setting: `%s'") % `key`)
219                 dict[key] = [val]
220
221
222 def run_lilypond (files, dep_prefix):
223
224         opts = ''
225         opts = opts + ' ' + string.join (map (lambda x : '-I ' + x,
226                                               include_path))
227         if pseudo_filter_p:
228                 opts = opts + ' --output=lelie'
229         if paper_p:
230                 opts = opts + ' ' + string.join (map (lambda x : '-H ' + x,
231                                                       fields))
232         else:
233                 opts = opts + ' --no-paper'
234
235         if pdftex_p:
236                 opts = opts + ' -f pdftex'              
237
238         if track_dependencies_p:
239                 opts = opts + " --dependencies"
240                 if dep_prefix:
241                         opts = opts + ' --dep-prefix=%s' % dep_prefix
242
243         fs = string.join (files)
244
245         global verbose_p
246         if verbose_p:
247                 opts = opts + ' --verbose'
248
249         if debug_p:
250                 ly.print_environment ()
251
252         cmd = string.join ((lilypond_cmd,opts, fs))
253         status = ly.system (cmd, ignore_error = 1, progress_p = 1)
254         signal = 0x0f & status
255         exit_status = status >> 8
256
257         # 2 == user interrupt.
258         if signal and signal != 2:
259                 sys.stderr.write ('\n\n')
260                 ly.error (_ ("LilyPond crashed (signal %d).") % signal)
261                 ly.error (_ ("Please submit a bug report to bug-lilypond@gnu.org"))
262                 ly.exit (status)
263                         
264         if status:
265                 sys.stderr.write ('\n')
266                 if len (files) == 1:
267                         ly.error (_ ("LilyPond failed on input file %s (exit status %d)") % (files[0], exit_status))
268                         ly.exit (status)
269                 else:
270                         ly.error (_ ("LilyPond failed on an input file (exit status %d)") % exit_status)
271                         ly.error (_ ("Continuing..."))
272                         global lilypond_error_p
273                         lilypond_error_p = 1
274                 
275
276 def analyse_lilypond_output (filename, extra):
277         
278         # urg
279         '''Grep FILENAME for interesting stuff, and
280         put relevant info into EXTRA.'''
281         filename = filename+tex_extension
282         ly.progress (_ ("Analyzing %s...") % filename)
283         s = open (filename).read ()
284
285         # search only the first 10k
286         s = s[:10240]
287         for x in extra_fields:
288                 m = re.search (r'\\def\\lilypondpaper%s{([^}]*)}'%x, s)
289                 if m:
290                         set_setting (extra, x, m.group (1))
291         ly.progress ('\n')
292
293 def find_tex_files_for_base (base, extra):
294
295         '''
296         Find the \header fields dumped from BASE.
297         '''
298         
299         headerfiles = {}
300         for f in layout_fields:
301                 if os.path.exists (base + '.' + f):
302                         headerfiles[f] = base+'.'+f
303
304         if os.path.exists (base  +'.dep'):
305                 dependency_files.append (base + '.dep')
306
307         for f in extra_fields:
308                 if os.path.exists (base + '.' + f):
309                         extra[f].append (open (base + '.' + f).read ())
310         
311         return (base+tex_extension,headerfiles)
312          
313
314 def find_tex_files (files, extra):
315         '''
316         Find all .tex files whose prefixes start with some name in FILES. 
317
318         '''
319         
320         tfiles = []
321         
322         for f in files:
323                 x = 0
324                 while 1:
325                         fname = os.path.basename (f)
326                         fname = ly.strip_extension (fname, '.ly')
327                         if x:
328                                 fname = fname + '-%d' % x
329
330                         if os.path.exists (fname + tex_extension):
331                                 tfiles.append (find_tex_files_for_base (fname, extra))
332                                 analyse_lilypond_output (fname, extra)
333                         else:
334                                 break
335
336                         x = x + 1
337         if not x:
338                 fstr = string.join (files, ', ')
339                 ly.warning (_ ("no LilyPond output found for `%s'") % fstr)
340         return tfiles
341
342 def one_latex_definition (defn, first):
343         s = '\n'
344         for (k,v) in defn[1].items ():
345                 val = open (v).read ()
346                 if (string.strip (val)):
347                         s = s + r'''\def\lilypond%s{%s}''' % (k, val)
348                 else:
349                         s = s + r'''\let\lilypond%s\relax''' % k
350                 s = s + '\n'
351
352         if first:
353                 s = s + '\\def\\mustmakelilypondtitle{}\n'
354         else:
355                 s = s + '\\def\\mustmakelilypondpiecetitle{}\n'
356                 
357         s = s + '\\input %s\n' % defn[0] # The final \n seems important here. It ensures that the footers and taglines end up on the right page.
358         return s
359
360
361 ly_paper_to_latexpaper =  {
362         'letter' : 'letterpaper', 
363         'a3' : 'a3paper',
364         'a4' : 'a4paper',
365         'a5' : 'a5paper',
366         'a6' : 'a6paper',
367 }
368
369 #TODO: should set textheight (enlarge) depending on papersize. 
370 def global_latex_preamble (extra):
371         '''construct preamble from EXTRA,'''
372         s = ""
373         s = s + '% generation tag\n'
374
375         options = ''
376
377
378         if extra['papersize']:
379                 try:
380                         options = ly_paper_to_latexpaper[extra['papersize'][0]]
381                 except KeyError:
382                         ly.warning (_ ("invalid value: `%s'") % `extra['papersize'][0]`)
383                         pass
384
385         if extra['latexoptions']:
386                 options = options + ',' + extra['latexoptions'][-1]
387
388         s = s + '\\documentclass[%s]{article}\n' % options
389
390         if extra['language']:
391                 s = s + r'\usepackage[%s]{babel}' % extra['language'][-1] + '\n'
392
393
394         s = s + '\\usepackage{%s}\n' \
395                 % string.join (extra['latexpackages'], ',')
396
397         if extra['latexheaders']:
398                 s = s + '\\include{%s}\n' \
399                         % string.join (extra['latexheaders'], '}\n\\include{')
400
401         unit = extra['unit'][-1]
402
403         textheight = ''
404         if extra['textheight']:
405                 textheight = ',textheight=%f%s' % (extra['textheight'][0], unit)
406
407         orientation = 'portrait'
408         if extra['orientation']:
409                 orientation = extra['orientation'][0]
410
411         # set sane geometry width (a4-width) for linewidth = -1.
412         maxlw = max (extra['linewidth'] + [-1])
413         if maxlw < 0:
414                 # who the hell is 597 ?
415                 linewidth = '597pt'
416         else:
417                 linewidth = '%d%s' % (maxlw, unit)
418         s = s + '\geometry{width=%s%s,headheight=2mm,footskip=2mm,%s}\n' % (linewidth, textheight, orientation)
419
420         if extra['latexoptions']:
421                 s = s + '\geometry{twosideshift=4mm}\n'
422
423         s = s + r'''
424 \usepackage[latin1]{inputenc}
425 \input{titledefs}
426 '''
427         
428         if extra['pagenumber'] and extra['pagenumber'][-1] and extra['pagenumber'][-1] != 'no':
429                 s = s + '\setcounter{page}{%d}\n' % (extra['pagenumber'][-1])
430                 s = s + '\\pagestyle{plain}\n'
431         else:
432                 s = s + '\\pagestyle{empty}\n'
433
434
435         return s
436
437         
438 def global_latex_definition (tfiles, extra):
439         '''construct preamble from EXTRA, dump Latex stuff for each
440 lily output file in TFILES after that, and return the Latex file constructed.  '''
441
442         
443         s = global_latex_preamble (extra) + '\\begin{document}\n'
444         s = s + '\\parindent 0pt\n'
445         s = s + '\\thispagestyle{firstpage}\n'
446
447         first = 1
448         for t in tfiles:
449                 s = s + one_latex_definition (t, first)
450                 first = 0
451
452
453         s = s + '\\thispagestyle{lastpage}\n'
454         s = s + '\\end{document}'
455
456         return s
457
458 def run_latex (files, outbase, extra):
459
460         '''Construct latex file, for FILES and EXTRA, dump it into
461 OUTBASE.latex. Run LaTeX on it.
462
463 RETURN VALUE
464
465 None
466         '''
467
468         latex_fn = outbase + '.latex'
469         
470         wfs = find_tex_files (files, extra)
471         s = global_latex_definition (wfs, extra)
472
473         f = open (latex_fn, 'w')
474         f.write (s)
475         f.close ()
476
477         cmd = latex_cmd + ' \\\\nonstopmode \\\\input %s' % latex_fn
478         # Ugh.  (La)TeX writes progress and error messages on stdout
479         # Redirect to stderr
480         cmd += ' 1>/dev/stderr'
481         status = ly.system (cmd, ignore_error = 1)
482         signal = 0xf & status
483         exit_status = status >> 8
484
485         if exit_status:
486
487                 logstr = ''
488                 try:
489                         logstr = open (outbase + '.log').read ()
490                         m = re.search ("\n!", logstr)
491                         start = m.start (0)
492                         logstr = logstr[start:start+200]
493                 except:
494                         pass
495                         
496                 ly.error (_ ("LaTeX failed on the output file."))
497                 ly.error (_ ("The error log is as follows:"))
498                 sys.stderr.write (logstr + '\n')
499                 ly.exit (1)
500         
501         if preview_p:
502                 # make a preview by rendering only the 1st line.
503                 preview_fn = outbase + '.preview.tex'
504                 f = open (preview_fn, 'w')
505                 wfs = find_tex_files (files, extra)
506                 s = global_latex_definition (wfs, extra)
507
508                 s = re.sub ('thispagestyle{firstpage}', r'''thispagestyle{empty}%
509 \\def\\interscoreline{\\endinput}''',s ) 
510                 s = re.sub ('thispagestyle{lastpage}', r'''thispagestyle{empty}%
511 \\def\\interscoreline{\\endinput}''',s ) 
512                 f.write (s)
513                 f.close()
514                 cmd = '%s \\\\nonstopmode \\\\input %s' % (latex_cmd, preview_fn)
515                 ly.system (cmd)
516         
517
518 def run_dvips (outbase, extra):
519
520
521         '''Run dvips using the correct options taken from EXTRA,
522 leaving a PS file in OUTBASE.ps
523
524 RETURN VALUE
525
526 None.
527 '''
528         opts = ''
529         if extra['papersize']:
530                 opts = opts + ' -t%s' % extra['papersize'][0]
531
532         if extra['orientation'] and extra['orientation'][0] == 'landscape':
533                 opts = opts + ' -tlandscape'
534
535
536         if 'PDF' in targets:
537                 where = ly.read_pipe ('kpsewhich feta20.pfa').strip()
538
539                 pfa_file  = None
540                 if where:
541                         try: 
542                                 pfa_file = open (where, 'r')
543                         except IOError:
544                                 pass
545
546                 if pfa_file:
547                         opts = opts + ' -Ppdf -G0 -u lilypond.map'
548                 else:
549                         ly.warning (_ ('''Trying create PDF, but no PFA fonts found.
550 Using bitmap fonts instead. This will look bad.'''))
551
552         cmd = 'dvips %s -o%s %s' % (opts, outbase + '.ps', outbase + '.dvi')
553         ly.system (cmd)
554
555         if preview_p:
556                 cmd = 'dvips -E -o%s %s' % ( outbase + '.preview.ps', outbase + '.preview.dvi')         
557                 ly.system (cmd)
558
559         if 'PDF' in targets:
560                 cmd = 'ps2pdf %s.ps %s.pdf' % (outbase , outbase)
561                 ly.system (cmd)
562                 
563 def generate_dependency_file (depfile, outname):
564         df = open (depfile, 'w')
565         df.write (outname + ':' )
566         
567         for d in dependency_files:
568                 s = open (d).read ()
569                 s = re.sub ('#[^\n]*\n', '', s)
570                 s = re.sub (r'\\\n', ' ', s)
571                 m = re.search ('.*:(.*)\n', s)
572
573                 # ugh. Different targets?
574                 if m:
575                         df.write ( m.group (1)  + ' ' )
576
577         df.write ('\n')
578         df.close ();
579
580 def find_file_in_path (path, name):
581         for d in string.split (path, os.pathsep):
582                 if name in os.listdir (d):
583                         return os.path.join (d, name)
584
585 # Added as functionality to ly2dvi, because ly2dvi may well need to do this
586 # in future too.
587 PS = '%!PS-Adobe'
588 def find_pfa_fonts (name):
589         s = open (name).read ()
590         if s[:len (PS)] != PS:
591                 # no ps header?
592                 ly.error (_ ("not a PostScript file: `%s\'" % name))
593                 ly.exit (1)
594         here = 0
595         m = re.match ('.*?/(feta[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
596         pfa = []
597         while m:
598                 here = m.end (1)
599                 pfa.append (m.group (1))
600                 m = re.match ('.*?/(feta[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
601         return pfa
602
603         
604 (sh, long) = ly.getopt_args (option_definitions)
605 try:
606         (options, files) = getopt.getopt (sys.argv[1:], sh, long)
607 except getopt.error, s:
608         sys.stderr.write ('\n')
609         ly.error (_ ("getopt says: `%s\'" % s))
610         sys.stderr.write ('\n')
611         ly.help ()
612         ly.exit (2)
613         
614 for opt in options:
615         o = opt[0]
616         a = opt[1]
617
618         if 0:
619                 pass
620         elif o == '--help' or o == '-h':
621                 ly.help ()
622                 sys.exit (0)
623         elif o == '--find-pfa' or o == '-f':
624                 fonts = map (lambda x: x + '.pfa', find_pfa_fonts (a))
625                 files = map (lambda x:
626                              find_file_in_path (os.environ['GS_FONTPATH'], x),
627                              fonts)
628                 print string.join (files, ' ')
629                 sys.exit (0)
630         elif o == '--include' or o == '-I':
631                 include_path.append (a)
632         elif o == '--postscript' or o == '-P':
633                 targets.append ('PS')
634         elif o == '--pdf' or o == '-p':
635                 targets.append ('PS')
636                 targets.append ('PDF')
637         elif o == '--keep' or o == '-k':
638                 keep_temp_dir_p = 1
639         elif o == '--debug':
640                 verbose_p = 1
641                 debug_p = 1 
642         elif o == '--no-lily':
643                 lily_p = 0
644         elif o == '--preview':
645                 preview_p = 1
646                 targets.append ('PNG')
647         elif o == '--preview-resolution':
648                 preview_resolution = string.atoi (a)
649         elif o == '--no-paper' or o == '-m':
650                 targets = ['MIDI'] 
651                 paper_p = 0
652         elif o == '--output' or o == '-o':
653                 output_name = a
654         elif o == '--set' or o == '-s':
655                 ss = string.split (a, '=')
656                 set_setting (extra_init, ss[0], ss[1])
657         elif o == '--dependencies' or o == '-d':
658                 track_dependencies_p = 1
659         elif o == '--verbose' or o == '-V':
660                 verbose_p = 1
661         elif o == '--version' or o == '-v':
662                 ly.identify (sys.stdout)
663                 sys.exit (0)
664         elif o == '--pdftex':
665                 latex_cmd = 'pdflatex'
666                 targets.remove('DVI')
667                 targets.append('PDFTEX')
668                 pdftex_p = 1
669                 tex_extension = '.pdftex'
670         elif o == '--warranty' or o == '-w':
671                 status = os.system ('lilypond -w')
672                 if status:
673                         ly.warranty ()
674                 sys.exit (0)
675
676 # Don't convert input files to abspath, rather prepend '.' to include
677 # path.
678 include_path.insert (0, '.')
679
680 # As a neat trick, add directory part of first input file
681 # to include path.  That way you can do without the clumsy -I in:
682
683 #    ly2dvi -I foe/bar/baz foo/bar/baz/baz.ly
684 if files and files[0] != '-' and os.path.dirname (files[0]) != '.':
685         include_path.append (os.path.dirname (files[0]))
686         
687 include_path = map (ly.abspath, include_path)
688
689 if files and (files[0] == '-' or output_name == '-'):
690         if len (files) == 1:
691                 pseudo_filter_p = 1
692                 output_name = 'lelie'
693                 if verbose_p:
694                         ly.progress (_ ("pseudo filter") + '\n')
695         else:
696                 ly.help ()
697                 ly.error (_ ("pseudo filter only for single input file"))
698                 ly.exit (2)
699                 
700 if not files:
701         ly.help ()
702         ly.error (_ ("no files specified on command line"))
703         ly.exit (2)
704
705 if 1:
706         ly.identify (sys.stderr)
707         original_output = output_name
708         
709         # Ugh, maybe make a setup () function
710         files = map (lambda x: ly.strip_extension (x, '.ly'), files)
711
712         # hmmm. Wish I'd 've written comments when I wrote this.
713         # now it looks complicated.
714         
715         (outdir, outbase) = ('','')
716         if not output_name:
717                 outbase = os.path.basename (files[0])
718                 outdir = ly.abspath ('.')
719         elif output_name[-1] == os.sep:
720                 outdir = ly.abspath (output_name)
721                 outbase = os.path.basename (files[0])
722         else:
723                 (outdir, outbase) = os.path.split (ly.abspath (output_name))
724
725         for i in ('.dvi', '.latex', '.ly', '.ps', '.tex', '.pdftex'):
726                 output_name = ly.strip_extension (output_name, i)
727                 outbase = ly.strip_extension (outbase, i)
728
729         for i in files[:] + [output_name]:
730                 if string.find (i, ' ') >= 0:
731                         ly.error (_ ("filename should not contain spaces: `%s'") %
732                                i)
733                         ly.exit (1)
734                         
735         if os.path.dirname (output_name) != '.':
736                 dep_prefix = os.path.dirname (output_name)
737         else:
738                 dep_prefix = 0
739
740         reldir = os.path.dirname (output_name)
741         if outdir != '.' and (track_dependencies_p or targets):
742                 ly.mkdir_p (outdir, 0777)
743
744         tmpdir = ly.setup_temp ()
745         ly.setup_environment ()
746
747         # to be sure, add tmpdir *in front* of inclusion path.
748         #os.environ['TEXINPUTS'] =  tmpdir + ':' + os.environ['TEXINPUTS']
749         os.chdir (tmpdir)
750
751         # We catch all exceptions, because we need to do stuff at exit:
752         #   * copy any successfully generated stuff from tempdir and
753         #     notify user of that
754         #   * cleanout tempdir
755         if lily_p:
756                 try:
757                         run_lilypond (files, dep_prefix)
758                 except:
759                         ### ARGH. This also catches python programming errors.
760                         ### this should only catch lilypond nonzero exit  status
761                         ### --hwn
762
763                         
764                         # TODO: friendly message about LilyPond setup/failing?
765                         #
766                         targets = []
767                         if verbose_p:
768                                 traceback.print_exc ()
769                         else:
770                                 ly.warning (_("Running LilyPond failed. Rerun with --verbose for a trace."))
771                                 
772         # Our LilyPond pseudo filter always outputs to 'lelie'
773         # have subsequent stages and use 'lelie' output.
774         if pseudo_filter_p:
775                 files[0] = 'lelie'
776                 
777         if 'PNG' in targets and 'PS' not in targets:
778                 targets.append ('PS')
779         if 'PS' in targets and 'DVI' not in targets:
780                 targets.append('DVI')
781
782         if 'DVI' in targets:
783                 try:
784                         run_latex (files, outbase, extra_init)
785                         # unless: add --tex, or --latex?
786                         targets.remove ('TEX')
787                         targets.remove('LATEX')
788                 except:
789                         # TODO: friendly message about TeX/LaTeX setup,
790                         # trying to run tex/latex by hand
791                         if 'DVI' in targets:
792                                 targets.remove ('DVI')
793                         if 'PS' in targets:
794                                 targets.remove ('PS')
795                         if verbose_p:
796                                 traceback.print_exc ()
797
798         if 'PS' in targets:
799                 try:
800                         run_dvips (outbase, extra_init)
801                         
802                 except: 
803                         if 'PS' in targets:
804                                 targets.remove ('PS')
805                         if verbose_p:
806                                 traceback.print_exc ()
807                         else:
808                                 ly.warning (_("Failed to make PS file. Rerun with --verbose for a trace."))
809
810         if 'PNG' in  targets:
811                 ly.make_preview (outbase)
812
813         if 'PDFTEX' in targets:
814                 try:
815                         run_latex (files, outbase, extra_init)
816                         # unless: add --tex, or --latex?
817                         targets.remove ('TEX')
818                         targets.remove ('LATEX')
819                         targets.remove ('PDFTEX')
820                         if 'PDF' not in targets:
821                                 targets.append('PDF')
822                 except:
823                         # TODO: friendly message about TeX/LaTeX setup,
824                         # trying to run tex/latex by hand
825                         if 'PDFTEX' in targets:
826                                 targets.remove ('PDFTEX')
827                         if 'PDF' in targets:
828                                 targets.remove ('PDF')
829                         if 'PS' in targets:
830                                 targets.remove ('PS')
831                         if verbose_p:
832                                 traceback.print_exc ()
833                         else:
834                                 ly.warning (_("Running LaTeX falied. Rerun with --verbose for a trace."))
835                                 
836
837         # add DEP to targets?
838         if track_dependencies_p:
839                 depfile = os.path.join (outdir, outbase + '.dep')
840                 generate_dependency_file (depfile, depfile)
841                 if os.path.isfile (depfile):
842                         ly.progress (_ ("dependencies output to `%s'...") %
843                                   depfile)
844                         ly.progress ('\n')
845
846         if pseudo_filter_p:
847                 main_target = 0
848                 for i in 'PDF', 'PS', 'PNG', 'DVI', 'LATEX':
849                         if i in targets:
850                                 main_target = i
851                                 break
852
853                 ly.progress (_ ("%s output to <stdout>...") % i)
854                 outname = outbase + '.' + string.lower (main_target)
855                 if os.path.isfile (outname):
856                         sys.stdout.write (open (outname).read ())
857                 elif verbose_p:
858                         ly.warning (_ ("can't find file: `%s'") % outname)
859                 targets = []
860                 ly.progress ('\n')
861                 
862         # Hmm, if this were a function, we could call it the except: clauses
863         for i in targets:
864                 ext = string.lower (i)
865                 ly.cp_to_dir ('.*\.%s$' % ext, outdir)
866                 outname = outbase + '.' + string.lower (i)
867                 abs = os.path.join (outdir, outname)
868                 if reldir != '.':
869                         outname = os.path.join (reldir, outname)
870                 if os.path.isfile (abs):
871                         ly.progress (_ ("%s output to `%s'...") % (i, outname))
872                         ly.progress ('\n')
873                 elif verbose_p:
874                         ly.warning (_ ("can't find file: `%s'") % outname)
875                         
876         os.chdir (original_dir)
877         ly.cleanup_temp ()
878
879         sys.exit (lilypond_error_p)