]> git.donarmstrong.com Git - lilypond.git/blob - lily/main.cc
2ef9af2f5a4f195604f70c7159f673081cd245b4
[lilypond.git] / lily / main.cc
1 /*
2   main.cc -- implement main: entrypoints
3
4   source file of the GNU LilyPond music typesetter
5
6   (c)  1997--2002 Han-Wen Nienhuys <hanwen@cs.uu.nl>
7 */
8
9 #include <stdlib.h>
10 #include <stdio.h>
11 #include <assert.h>
12 #include <locale.h>
13 #include <stdio.h>
14
15 #include <iostream>
16
17 #include "config.h"
18
19 #if HAVE_GETTEXT
20 #include <libintl.h>
21 #endif
22
23 #include "lily-guile.hh"
24 #include "lily-version.hh"
25 #include "all-font-metrics.hh"
26 #include "getopt-long.hh"
27 #include "misc.hh"
28 #include "string.hh"
29 #include "main.hh"
30 #include "file-path.hh"
31 #include "file-results.hh"
32 #include "warn.hh"
33 #include "lily-guile.hh"
34 #include "paper-def.hh"
35 #include "midi-def.hh"
36 #include "global-ctor.hh"
37 #include "kpath.hh"
38
39 static int sane_putenv (char const* key, char const* value, bool overwrite = false);
40
41 /*
42   Global options that can be overridden through command line.
43 */
44
45 /* Write dependencies file? */
46 bool dependency_global_b = false;
47
48 /* Prepend to dependencies */
49 String dependency_prefix_global;
50
51 /* Names of header fields to be dumped to a separate file. */
52 Array<String> dump_header_fieldnames_global;
53
54 /* Name of initialisation file. */
55 String init_name_global;
56
57 /* Do not calculate and write paper output? */
58 bool no_paper_global_b = false;
59
60 /* Selected output format.
61    One of tex, ps, scm, as. */
62 String output_format_global = "tex";
63
64 /* Current output name. */
65 String output_name_global;
66
67 /* Run in safe mode? -- FIXME: should be re-analised */
68 bool safe_global_b = false;
69
70 /* Verbose progress indication? */
71 bool verbose_global_b = false;
72
73 /* Scheme code to execute before parsing, after .scm init */
74 String init_scheme_code_string = "(begin #t ";
75
76
77 /*
78   Misc. global stuff.
79  */
80
81
82 All_font_metrics *all_fonts_global;
83 int exit_status_global;
84 File_path global_path;
85
86 /* Number of current score output block.  If there's more than one
87    score block, this counter will be added to the output filename. */
88 int score_count_global;
89
90
91
92 /*
93   File globals.
94  */
95
96 /*  The option parser */
97 static Getopt_long *oparser_p_static = 0;
98
99 /*
100  Internationalisation kludge in two steps:
101    * use _i () to get entry in POT file
102    * call gettext () explicitely for actual "translation"
103
104  Note: these messages all start with lower case (ie, don't
105        follow regular localisation guidelines).
106  */
107 static Long_option_init options_static[] = {
108   /* print example usage:  lilypond -e "" ? */
109   {_i ("EXPR"), "evaluate", 'e',_i ("Scheme options: try -e \"(set-lily-option 'help 0)\" for more help.")},
110   /* another bug in option parser: --output=foe is taken as an abbreviation
111      for --output-format */
112   {_i ("EXT"), "format", 'f',  _i ("use output format EXT")},
113   {0, "help", 'h',  _i ("this help")},
114   {_i ("FIELD"), "header", 'H',  _i ("write header field to BASENAME.FIELD")},
115   {_i ("DIR"), "include", 'I',  _i ("add DIR to search path")},
116   {_i ("FILE"), "init", 'i',  _i ("use FILE as init file")},
117   {0, "dependencies", 'M',  _i ("write Makefile dependencies for every input file")},
118   {0, "no-paper", 'm',  _i ("produce MIDI output only")},
119   {_i ("FILE"), "output", 'o',  _i ("write output to FILE")},
120   {_i ("DIR"), "dep-prefix", 'P',  _i ("prepend DIR to dependencies")},
121 #if 0
122   /*
123     should audit again.
124    */
125   {0, "safe", 's',  _i ("inhibit file output naming and exporting")},
126 #endif
127   {0, "version", 'v',  _i ("print version number")},
128   {0, "verbose", 'V', _i ("verbose")},
129   {0, "warranty", 'w',  _i ("show warranty and copyright")},
130   {0,0,0,0}
131 };
132
133 void
134 identify (FILE *out)
135 {
136   fputs (gnu_lilypond_version_string ().to_str0 (), out);
137 }
138
139 void
140 dirinfo (FILE *out)
141 {
142   fputs ("\n", out);
143   fprintf (out, "lilypond_datadir: `%s'\n", LILYPOND_DATADIR);
144   fprintf (out, "local_lilypond_datadir: `%s'\n", LOCAL_LILYPOND_DATADIR);
145   fprintf (out, "localedir: `%s'\n", LOCALEDIR);
146
147   char *lilypond_prefix = getenv ("LILYPONDPREFIX");
148   fprintf (out, "LILYPONDPREFIX: `%s'\n",
149            (lilypond_prefix ? lilypond_prefix : ""));
150 }
151
152 void
153 usage ()
154 {
155   std::cout << "\n";
156   /* No version number or newline here. It confuses help2man.  */
157   std::cout << _f ("Usage: %s [OPTION]... FILE...", "lilypond").to_str0 ();
158   std::cout << "\n\n";
159   std::cout << _ ("Typeset music and or play MIDI from FILE").to_str0 ();
160   std::cout << "\n\n";
161   std::cout << 
162 _ (
163 "LilyPond is a music typesetter.  It produces beautiful sheet music\n"
164 "using a high level description file as input.  LilyPond is part of \n"
165 "the GNU Project.\n"
166 ).to_str0 ();
167
168   std::cout << '\n';
169   std::cout << _ ("Options:").to_str0 ();
170   std::cout << '\n';
171   std::cout << Long_option_init::table_string (options_static).to_str0 ();
172   std::cout << '\n';
173   std::cout << std::endl;
174
175   std::cout << _f ("Report bugs to %s", "bug-lilypond@gnu.org").to_str0 () << std::endl;
176 }
177
178 void
179 version ()
180 {
181   identify (stdout);
182   std::cout << '\n';
183   std::cout << _f (""
184   "This is free software.  It is covered by the GNU General Public License,\n"
185   "and you are welcome to change it and/or distribute copies of it under\n"
186   "certain conditions.  Invoke as `%s --warranty' for more information.\n",
187     "lilypond").to_str0 ();
188   std::cout << std::endl;
189
190   std::cout << _f ("Copyright (c) %s by", "1996--2002").to_str0 ();
191   std::cout << '\n';
192   std::cout << "  Han-Wen Nienhuys <hanwen@cs.uu.nl>\n";
193   std::cout << "  Jan Nieuwenhuizen <janneke@gnu.org>\n";
194 }
195
196 void
197 notice ()
198 {
199   std::cout << '\n';
200   std::cout << _ ("GNU LilyPond -- The music typesetter").to_str0 ();
201   std::cout << '\n';
202   std::cout << _f ("Copyright (c) %s by", "1996--2002").to_str0 ();
203   std::cout << '\n';
204   std::cout << "  Han-Wen Nienhuys <hanwen@cs.uu.nl>\n";
205   std::cout << "  Jan Nieuwenhuizen <janneke@gnu.org>\n";
206   std::cout << '\n';
207   std::cout << _ (
208              "    This program is free software; you can redistribute it and/or\n"
209              "modify it under the terms of the GNU General Public License version 2\n"
210              "as published by the Free Software Foundation.\n"
211              "\n"
212              "    This program is distributed in the hope that it will be useful,\n"
213              "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
214              "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
215              "General Public License for more details.\n"
216              "\n"
217              "    You should have received a copy (refer to the file COPYING) of the\n"
218              "GNU General Public License along with this program; if not, write to\n"
219              "the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139,\n"
220              "USA.\n").to_str0 ();
221 }
222
223
224 /* Where LilyPond's init files live.  Typically:
225    LILYPOND_DATADIR = /usr/local/share/lilypond
226    LOCAL_LILYPOND_DATADIR = /usr/local/share/lilypond/1.5.68 */
227 char const *prefix_directory[2] = {LILYPOND_DATADIR, LOCAL_LILYPOND_DATADIR};
228
229 void
230 setup_paths ()
231 {
232   if (char const *lilypond_prefix = getenv ("LILYPONDPREFIX"))
233     prefix_directory[1] = lilypond_prefix;
234
235 #if HAVE_GETTEXT
236   setlocale (LC_ALL, ""); /* enable locales */
237   setlocale (LC_NUMERIC, "C"); /* musn't have comma's in TeX output... */
238   String lily_locale_dir;
239   String name (PACKAGE);
240   name.to_lower ();
241
242   /*
243     urg; what *do* we want with $LILYPONDPREFIX, DIR_DATADIR and $prefix/share
244     handy for multiple source-dir runs, though...
245    */
246   if (!String (prefix_directory[0]).empty_b ())
247     {
248       lily_locale_dir = String (prefix_directory[0]) + "/share/locale";
249       bindtextdomain (name.to_str0 (), lily_locale_dir.to_str0 ());
250     }
251   else
252     bindtextdomain (name.to_str0 (), LOCALEDIR);
253   textdomain (name.to_str0 ());
254 #endif
255
256   global_path.add ("");
257
258
259   /* Adding mf/out make lilypond unchanged source directory, when setting
260      LILYPONDPREFIX to lilypond-x.y.z */
261   char *suffixes[] = {"ly", "afm", "mf/out", "scm", "tfm", "ps", 0};
262
263   for (unsigned i = 0; i < sizeof (prefix_directory)
264          / sizeof (*prefix_directory); i++)
265     for (char **s = suffixes; *s; s++)
266       {
267         String p = prefix_directory[i] + to_string ('/') + String (*s);
268         global_path.add (p);
269         
270 #if !KPATHSEA
271         /* Urg: GNU make's $ (word) index starts at 1 */
272         int i  = 1;
273         while (global_path.try_add (p + to_string (".") + to_string (i)))
274           i++;
275 #endif
276       }
277   }
278   
279 /**
280   Make input file name from command argument.
281
282   Path describes file name with added default extension,
283   ".ly" if none.  "-" is stdin.
284  */
285 Path
286 distill_inname (String str)
287 {
288   Path p = split_path (str);
289   if (str.empty_b () || str == "-")
290     p.base = "-";
291   else
292     {
293       String orig_ext = p.ext;
294       char const *extensions[] = {"ly", "fly", "sly", "", 0};
295       for (int i = 0; extensions[i]; i++)
296         {
297           p.ext = orig_ext;
298           if (*extensions[i] && !p.ext.empty_b ())
299             p.ext += ".";
300           p.ext += extensions[i];
301           if (!global_path.find (p.string ()).empty_b ())
302               break;
303         }
304       /* Reshuffle extension */
305       p = split_path (p.string ());
306     }
307   return p;
308 }
309
310 String
311 format_to_ext (String format)
312 {
313   if (format == "tex")
314     /* .lytex change put off */
315     return "tex"; // "lytex";
316   return format;
317 }
318
319 void
320 prepend_load_path (String dir)
321 {
322   String s = "(set! %load-path (cons \""
323     + dir
324     + "\" %load-path))";
325   scm_c_eval_string (s.to_str0 ());
326 }
327
328 void
329 main_prog (void *, int, char **)
330 {
331   /* Engravers use lily.scm contents, need to make Guile find it.
332      Prepend onto GUILE %load-path, very ugh. */
333      
334   for (unsigned i = 0; i < sizeof (prefix_directory)
335          / sizeof (*prefix_directory); i++)
336     {
337       prepend_load_path (prefix_directory[i]);
338       /* Junk this.  We should make real modules iso. just loading files. */
339       prepend_load_path (String (prefix_directory[i]) + "/scm");
340     }
341
342   SCM_RECORD_POSITIONS_P = 1; 
343   if (verbose_global_b)
344     dirinfo (stderr);
345   
346   ly_init_guile ();
347   
348   std::cout << std::endl;
349
350   call_constructors ();
351   all_fonts_global = new All_font_metrics (global_path.string ());
352
353   init_scheme_code_string += ")";
354   gh_eval_str ((char *)init_scheme_code_string.to_str0 ());
355   
356   int p=0;
357   const char *arg  = oparser_p_static->get_next_arg ();
358
359   if (!arg)
360     {
361       usage ();
362       /* No FILE arguments is now a usage error */
363       exit (2);
364     }
365   
366   do
367     {
368       String infile (arg);
369       Midi_def::reset_score_count ();
370       Paper_def::reset_score_count ();
371
372       Path inpath = distill_inname (infile);
373
374       /* By default, use base name of input file for output file name */
375       Path outpath = inpath;
376       if (inpath.string () != "-")
377         outpath.ext = format_to_ext (output_format_global);
378
379       /* By default, write output to cwd; do not copy directory part
380          of input file name */
381       outpath.root = "";
382       outpath.dir = "";
383       
384       if (!output_name_global.empty_b ())
385         outpath = split_path (output_name_global);
386       
387       String init;
388       if (!init_name_global.empty_b ())
389         init = init_name_global;
390       else if (!inpath.ext.empty_b ())
391         init = "init." + inpath.ext;
392       else
393         init = "init.ly";
394         
395       /* Burp: output name communication goes through _global */
396       String save_output_name_global = output_name_global;
397       output_name_global = outpath.string ();
398       do_one_file (init, inpath.string ());
399       output_name_global = save_output_name_global;
400       
401       p++;
402     } while ((arg  = oparser_p_static->get_next_arg ()));
403   delete oparser_p_static;
404   oparser_p_static = 0;
405   exit (exit_status_global);
406 }
407
408
409 static int
410 sane_putenv (char const* key, char const* value, bool overwrite)
411 {
412   if (overwrite || !getenv (key))
413     return putenv ((char*)((String (key) + "=" + value).to_str0 ()));
414   return -1;
415 }
416
417 int
418 main (int argc, char **argv)
419 {
420   setup_paths ();
421
422   /* Prepare GUILE for heavy memory usage.  If you have plenty memory,
423      this may speed up GUILE a bit.  If you're short on memory, these
424      settings
425     
426          export GUILE_INIT_SEGMENT_SIZE_1=36000
427          export GUILE_MAX_SEGMENT_SIZE=576000
428
429      may considerably decrease memory footprint (~*0.85), with a small
430      execution time penalty (~*1.10).  However, if this 15% gain in memory
431      usage prevents swapping, the execution time falls drastically. */
432   
433   sane_putenv ("GUILE_INIT_SEGMENT_SIZE_1", "4194304", false);
434   sane_putenv ("GUILE_MAX_SEGMENT_SIZE", "8388608", false);
435
436   ly_init_kpath (argv[0]);
437
438   bool help_b = false;
439   oparser_p_static = new Getopt_long (argc, argv, options_static);
440   while (Long_option_init const * opt = (*oparser_p_static) ())
441     {
442       switch (opt->shortname_char_)
443         {
444         case 'v':
445           version ();
446           exit (0);             // we print a version anyway.
447           break;
448         case 'o':
449           {
450             String s = oparser_p_static->optional_argument_str0_;
451             Path p = split_path (s);
452             if (s != "-" && p.ext.empty_b ())
453               p.ext = format_to_ext (output_format_global);
454             output_name_global = p.string ();
455           }
456           break;
457         case 'e':
458           init_scheme_code_string +=
459             oparser_p_static->optional_argument_str0_;
460           break;
461         case 'w':
462           notice ();
463           exit (0);
464           break;
465         case 'f':
466           if (output_name_global == "help")
467             {
468               cout << \
469                 "See http://lilypond.org/wiki?OutputFormats for more information.\n"\
470                 "This option is for developers only.\n";
471               exit (0);
472             }
473           output_format_global = oparser_p_static->optional_argument_str0_;
474           break;
475         case 'P':
476             dependency_prefix_global = oparser_p_static->optional_argument_str0_;
477           break;
478         case 'H':
479           dump_header_fieldnames_global.push (oparser_p_static->optional_argument_str0_);
480           break;
481         case 'I':
482           global_path.push (oparser_p_static->optional_argument_str0_);
483           break;
484         case 'i':
485           init_name_global = oparser_p_static->optional_argument_str0_;
486           break;
487         case 'h':
488           help_b = true;
489           break;
490         case 'V':
491           verbose_global_b = true;
492           break;
493         case 's':
494           safe_global_b = true;
495           break;
496         case 'M':
497           dependency_global_b = true;
498           break; 
499         case 'm':
500           no_paper_global_b = true;
501           break;
502         default:
503           assert (false);
504           break;
505         }
506     }
507   identify (stderr);
508
509   if (help_b)
510     {
511       usage ();
512       if (verbose_global_b)
513         dirinfo (stdout);
514       exit (0);
515     }
516
517 #ifdef WINNT
518   scm_boot_guile (argc, argv, main_prog, 0);
519 #else
520   scm_boot_guile (argc, argv, (void (*) (void*, int, char**))main_prog, 0);
521 #endif
522
523   return 0;                     // unreachable
524 }
525
526