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