]> git.donarmstrong.com Git - lilypond.git/blob - lily/main.cc
* lily/include/midi-item.hh (class Midi_track): idem.
[lilypond.git] / lily / main.cc
1 /*
2   main.cc -- implement main () entrypoint.
3
4   source file of the GNU LilyPond music typesetter
5
6   (c) 1997--2006 Han-Wen Nienhuys <hanwen@xs4all.nl>
7 */
8
9 #include "main.hh"
10
11 #include <cassert>
12 #include <clocale>
13 #include <cstring>
14 #include <cerrno>
15 using namespace std;
16
17 #include <unistd.h>
18 #include <sys/types.h>
19 #include "config.hh"
20
21 #if HAVE_GRP_H
22 #include <grp.h>
23 #endif
24 #if HAVE_PWD_H
25 #include <pwd.h>
26 #endif
27 #if HAVE_GETTEXT
28 #include <libintl.h>
29 #endif
30
31 #include "all-font-metrics.hh"
32 #include "file-name.hh"
33 #include "freetype.hh"
34 #include "getopt-long.hh"
35 #include "global-ctor.hh"
36 #include "international.hh"
37 #include "lily-guile.hh"
38 #include "lily-version.hh"
39 #include "misc.hh"
40 #include "output-def.hh"
41 #include "program-option.hh"
42 #include "relocate.hh"
43 #include "string-convert.hh"
44 #include "version.hh"
45 #include "warn.hh"
46
47 /*
48  * Global options that can be overridden through command line.
49  */
50
51 /* Names of header fields to be dumped to a separate file. */
52 vector<string> dump_header_fieldnames_global;
53
54 /* Name of initialisation file. */
55 string init_name_global;
56
57 /* Selected output backend
58    One of (gnome, ps [default], eps, scm, svg, tex, texstr)") */
59 string output_backend_global = "ps";
60 /* Output formats to generate.  */
61 string output_format_global = "";
62
63 bool is_pango_format_global;
64 bool is_TeX_format_global;
65
66 /* Current output name. */
67 string output_name_global;
68
69 /* Run in safe mode? */
70 bool be_safe_global = false;
71
72 /* Provide URI links to the original file */
73 bool point_and_click_global = true;
74
75 /* Verbose progress indication? */
76 bool be_verbose_global = false;
77
78 /* Scheme code to execute before parsing, after .scm init.
79    This is where -e arguments are appended to.  */
80 string init_scheme_code_string;
81 string init_scheme_variables;
82
83 /* Generate preview of first system.  */
84 bool make_preview = false;
85
86 /* Generate printed output.  */
87 bool make_print = true;
88
89
90 bool relocate_binary =
91 #if ARGV0_RELOCATION
92   true;
93 #else
94   false
95 #endif
96   ;
97
98
99 /*
100  * Miscellaneous global stuff.
101  */
102 File_path global_path;
103
104 /*
105  * File globals.
106  */
107
108 static char const *AUTHORS
109 = "  Han-Wen Nienhuys <hanwen@xs4all.nl>\n"
110   "  Jan Nieuwenhuizen <janneke@gnu.org>\n";
111
112 static char const *PROGRAM_NAME = "lilypond";
113 static char const *PROGRAM_URL = "http://lilypond.org";
114
115 static char const *NOTICE
116 = _i ("This program is free software.  It is covered by the GNU General Public\n"
117       "License and you are welcome to change it and/or distribute copies of it\n"
118       "under certain conditions.  Invoke as `%s --warranty' for more\n"
119       "information.\n");
120
121 static char const *WARRANTY
122 = _i ("    This program is free software; you can redistribute it and/or\n"
123       "modify it under the terms of the GNU General Public License version 2\n"
124       "as published by the Free Software Foundation.\n"
125       "\n"
126       "    This program is distributed in the hope that it will be useful,\n"
127       "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
128       "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
129       "General Public License for more details.\n"
130       "\n"
131       "    You should have received a copy (refer to the file COPYING) of the\n"
132       "GNU General Public License along with this program; if not, write to\n"
133       "the Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n"
134       "Boston, MA 02111-1307, USA.\n");
135
136 /* Where the init files live.  Typically:
137    LILYPOND_DATADIR = /usr/share/lilypond
138 */
139 string prefix_directory;
140
141 /* The jail specification: USER,GROUP,JAIL,DIR. */
142 string jail_spec;
143
144 /*  The option parser */
145 static Getopt_long *option_parser = 0;
146
147 /* Internationalisation kludge in two steps:
148  * use _i () to get entry in POT file
149  * call gettext () explicitely for actual "translation"  */
150
151 static Long_option_init options_static[]
152 = {
153   {_i ("BACK"), "backend", 'b', _i ("use backend BACK (gnome, ps,eps,\nscm, svg, tex, texstr)\ndefault: PS")},
154
155   {_i ("SYM=VAL"), "define-default", 'd',
156    _i ("set a Scheme program option. Uses #t if VAL is not specified\n"
157        "Try -dhelp for help.")},
158
159   {_i ("EXPR"), "evaluate", 'e', _i ("evaluate scheme code")},
160   /* Bug in option parser: --output =foe is taken as an abbreviation
161      for --output-format.  */
162   {_i ("FORMATs"), "formats", 'f', _i ("dump FORMAT,...  Also as separate options:")},
163   {0, "dvi", 0, _i ("generate DVI (tex backend only)")},
164   {0, "relocate", 0, _i ("relocate using directory of lilypond program")},
165   {0, "pdf", 0, _i ("generate PDF (default)")},
166   {0, "png", 0, _i ("generate PNG")},
167   {0, "ps", 0, _i ("generate PostScript")},
168   {0, "tex", 0, _i ("generate TeX (tex backend only)")},
169   {0, "help", 'h',  _i ("print this help")},
170   {_i ("FIELD"), "header", 'H',  _i ("dump a header field to file BASENAME.FIELD")},
171   {_i ("DIR"), "include", 'I',  _i ("add DIR to search path")},
172   {_i ("FILE"), "init", 'i',  _i ("use FILE as init file")},
173 #if HAVE_CHROOT
174   {_i ("USER,GROUP,JAIL,DIR"), "jail", 'j', _i ("chroot to JAIL, become USER:GROUP\n"
175                                                 "and cd into DIR")},
176 #endif
177   {0, "no-print", 0, _i ("do not generate printed output")},
178   {_i ("FILE"), "output", 'o',  _i ("write output to FILE (suffix will be added)")},
179   {0, "preview", 'p',  _i ("generate a preview of the first system")},
180   {0, "safe-mode", 's',  _i ("disallow unsafe Scheme and PostScript operations")},
181   {0, "version", 'v',  _i ("print version number")},
182   {0, "verbose", 'V', _i ("be verbose")},
183   {0, "warranty", 'w',  _i ("show warranty and copyright")},
184   {0, 0, 0, 0}
185 };
186
187 const char *LILYPOND_DATADIR = PACKAGE_DATADIR "/" TOPLEVEL_VERSION;
188
189 static void
190 env_var_info (FILE *out, char const *key)
191 {
192   if (char const *value = getenv (key))
193     fprintf (out, "%s=\"%s\"\n", key, value);
194 }
195
196 static void
197 dir_info (FILE *out)
198 {
199   fputs ("\n", out);
200   fprintf (out, "LILYPOND_DATADIR=\"%s\"\n", LILYPOND_DATADIR);
201   env_var_info (out, "LILYPONDPREFIX");
202   fprintf (out, "LOCALEDIR=\"%s\"\n", LOCALEDIR);
203
204   fprintf (out, "\nEffective prefix: \"%s\"\n", prefix_directory.c_str ());
205
206   if (relocate_binary)
207     {
208       env_var_info (out, "FONTCONFIG_FILE");
209       env_var_info (out, "FONTCONFIG_PATH");
210       env_var_info (out, "GS_FONTPATH");
211       env_var_info (out, "GS_LIB");
212       env_var_info (out, "GUILE_LOAD_PATH");
213       env_var_info (out, "PANGO_RC_FILE");
214       env_var_info (out, "PATH");
215     }
216 }
217
218 static void
219 copyright ()
220 {
221   printf (_f ("Copyright (c) %s by\n%s  and others.",
222               "1996--2006",
223               AUTHORS).c_str ());
224   printf ("\n");
225 }
226
227 static void
228 identify (FILE *out)
229 {
230   fputs (gnu_lilypond_version_string ().c_str (), out);
231   fputs ("\n", out);
232 }
233
234 static void
235 notice ()
236 {
237   identify (stdout);
238   puts (_f (NOTICE, PROGRAM_NAME).c_str ());
239   printf ("\n");
240   copyright ();
241 }
242
243 LY_DEFINE (ly_usage, "ly:usage",
244            0, 0, 0, (),
245            "Print usage message.")
246 {
247   /* No version number or newline here.  It confuses help2man.  */
248   printf (_f ("Usage: %s [OPTION]... FILE...", PROGRAM_NAME).c_str ());
249   printf ("\n\n");
250   printf (_ ("Typeset music and/or produce MIDI from FILE.").c_str ());
251   printf ("\n\n");
252   printf (_ ("LilyPond produces beautiful music notation.").c_str ());
253   printf ("\n");
254   printf (_f ("For more information, see %s", PROGRAM_URL).c_str ());
255   printf ("\n\n");
256   printf (_ ("Options:").c_str ());
257   printf ("\n");
258   printf (Long_option_init::table_string (options_static).c_str ());
259   printf ("\n");
260   printf (_f ("Report bugs via %s",
261               "http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs"
262               ).c_str ());
263   printf ("\n");
264   printf ("\n");
265   return SCM_UNSPECIFIED;
266 }
267
268 static void
269 warranty ()
270 {
271   identify (stdout);
272   printf ("\n");
273   copyright ();
274   printf ("\n");
275   printf (_ (WARRANTY).c_str ());
276 }
277
278 static void
279 prepend_load_path (string dir)
280 {
281   string s = "(set! %load-path (cons \"" + dir + "\" %load-path))";
282   scm_c_eval_string (s.c_str ());
283 }
284
285 void init_global_tweak_registry ();
286 void init_fontconfig ();
287
288 #if HAVE_CHROOT
289 static void
290 do_chroot_jail ()
291 {
292   /* Now we chroot, setuid/setgrp and chdir.  If something goes wrong,
293      we exit (this is a security-sensitive area).  First we split
294      jail_spec into its components, then we retrieve the user/group id
295      (necessarily *before* chroot'ing) and finally we perform the
296      actual actions.  */
297
298   enum Jail
299     {
300       USER_NAME, GROUP_NAME, JAIL, DIR, JAIL_MAX
301     };
302
303   vector<string> components = split_string (jail_spec, ',');
304   if (components.size () != JAIL_MAX)
305     {
306       error (_f ("expected %d arguments with jail, found: %d", JAIL_MAX,
307                  components.size ()));
308       exit (2);
309     }
310
311   /* Hmm.  */
312   errno = 0;
313
314   int uid;
315   if (passwd * passwd = getpwnam (components[USER_NAME].c_str ()))
316     uid = passwd->pw_uid;
317   else
318     {
319       if (errno == 0)
320         error (_f ("no such user: %s", components[USER_NAME]));
321       else
322         error (_f ("can't get user id from user name: %s: %s",
323                    components[USER_NAME],
324                    strerror (errno)));
325       exit (3);
326     }
327
328   /* Hmm.  */
329   errno = 0;
330
331   int gid;
332   if (group * group = getgrnam (components[GROUP_NAME].c_str ()))
333     gid = group->gr_gid;
334   else
335     {
336       if (errno == 0)
337         error (_f ("no such group: %s", components[GROUP_NAME]));
338       else
339         error (_f ("can't get group id from group name: %s: %s",
340                    components[GROUP_NAME],
341                    strerror (errno)));
342       exit (3);
343     }
344
345   if (chroot (components[JAIL].c_str ()))
346     {
347       error (_f ("can't chroot to: %s: %s", components[JAIL],
348                  strerror (errno)));
349       exit (3);
350     }
351
352   if (setgid (gid))
353     {
354       error (_f ("can't change group id to: %d: %s", gid, strerror (errno)));
355       exit (3);
356     }
357
358   if (setuid (uid))
359     {
360       error (_f ("can't change user id to: %d: %s", uid, strerror (errno)));
361       exit (3);
362     }
363
364   if (chdir (components[DIR].c_str ()))
365     {
366       error (_f ("can't change working directory to: %s: %s", components[DIR],
367                  strerror (errno)));
368       exit (3);
369     }
370 }
371 #endif
372
373 static void
374 main_with_guile (void *, int, char **)
375 {
376   /* Engravers use lily.scm contents, need to make Guile find it.
377      Prepend onto GUILE %load-path, very ugh. */
378
379   prepend_load_path (prefix_directory);
380   prepend_load_path (prefix_directory + "/scm");
381
382   if (be_verbose_global)
383     dir_info (stderr);
384   is_TeX_format_global = (output_backend_global == "tex"
385                           || output_backend_global == "texstr");
386
387   is_pango_format_global = !is_TeX_format_global;
388
389   ly_c_init_guile ();
390   call_constructors ();
391   init_global_tweak_registry ();
392   init_fontconfig ();
393
394   init_freetype ();
395
396   all_fonts_global = new All_font_metrics (global_path.to_string ());
397
398   if (!init_scheme_variables.empty ()
399       || !init_scheme_code_string.empty ())
400     {
401       init_scheme_variables = "(map (lambda (x) (ly:set-option (car x) (cdr x))) (list "
402         + init_scheme_variables + "))";
403
404       init_scheme_code_string
405         += "(begin #t "
406         + init_scheme_variables
407         + init_scheme_code_string
408         + ")";
409
410       char const *str0 = init_scheme_code_string.c_str ();
411
412       if (be_verbose_global)
413         progress_indication (_f ("Evaluating %s", str0));
414       scm_c_eval_string ((char *) str0);
415     }
416
417   /* We accept multiple independent music files on the command line to
418      reduce compile time when processing lots of small files.
419      Starting the GUILE engine is very time consuming.  */
420
421   SCM files = SCM_EOL;
422   SCM *tail = &files;
423   while (char const *arg = option_parser->get_next_arg ())
424     {
425       *tail = scm_cons (scm_makfrom0str (arg), SCM_EOL);
426       tail = SCM_CDRLOC (*tail);
427     }
428   delete option_parser;
429   option_parser = 0;
430
431 #if HAVE_CHROOT
432   if (!jail_spec.empty ())
433     do_chroot_jail ();
434 #endif
435
436   SCM result = scm_call_1 (ly_lily_module_constant ("lilypond-main"), files);
437   (void) result;
438
439   /* Unreachable.  */
440   exit (0);
441 }
442
443 static void
444 setup_localisation ()
445 {
446 #if HAVE_GETTEXT
447   /* Enable locales */
448   setlocale (LC_ALL, "");
449
450   /* FIXME: check if this is still true.
451      Disable localisation of float values.  This breaks TeX output.  */
452   setlocale (LC_NUMERIC, "C");
453
454   string localedir = LOCALEDIR;
455   if (char const *env = getenv ("LILYPOND_LOCALEDIR"))
456     localedir = env;
457
458   bindtextdomain ("lilypond", localedir.c_str ());
459   textdomain ("lilypond");
460 #endif
461 }
462
463 static void
464 add_output_format (string format)
465 {
466   if (output_format_global != "")
467     output_format_global += ",";
468   output_format_global += format;
469 }
470
471 static void
472 parse_argv (int argc, char **argv)
473 {
474   bool show_help = false;
475   option_parser = new Getopt_long (argc, argv, options_static);
476   while (Long_option_init const *opt = (*option_parser) ())
477     {
478       switch (opt->shortname_char_)
479         {
480         case 0:
481           if (string (opt->longname_str0_) == "dvi"
482               || string (opt->longname_str0_) == "pdf"
483               || string (opt->longname_str0_) == "png"
484               || string (opt->longname_str0_) == "ps"
485               || string (opt->longname_str0_) == "tex")
486             add_output_format (opt->longname_str0_);
487           else if (string (opt->longname_str0_) == "preview")
488             make_preview = true;
489           else if (string (opt->longname_str0_) == "no-pages")
490             make_print = false;
491           else if (string (opt->longname_str0_) == "relocate")
492             relocate_binary = true;
493           break;
494
495         case 'd':
496           {
497             string arg (option_parser->optional_argument_str0_);
498             ssize eq = arg.find ('=');
499
500             string key = arg;
501             string val = "#t";
502
503             if (eq != NPOS)
504               {
505                 key = arg.substr (0, eq);
506                 val = arg.substr (eq + 1, key.length () - 1);
507               }
508
509             init_scheme_variables
510               += "(cons \'" + key + "  " + val + ")\n";
511           }
512           break;
513
514         case 'v':
515           notice ();
516           exit (0);
517           break;
518         case 'o':
519           {
520             string s = option_parser->optional_argument_str0_;
521             File_name file_name (s);
522             output_name_global = file_name.to_string ();
523           }
524           break;
525         case 'j':
526           jail_spec = option_parser->optional_argument_str0_;
527           break;
528         case 'e':
529           init_scheme_code_string += option_parser->optional_argument_str0_;
530           break;
531         case 'w':
532           warranty ();
533           exit (0);
534           break;
535
536         case 'b':
537           output_backend_global = option_parser->optional_argument_str0_;
538           break;
539
540         case 'f':
541           output_format_global = option_parser->optional_argument_str0_;
542           break;
543
544         case 'H':
545           dump_header_fieldnames_global
546             .push_back (option_parser->optional_argument_str0_);
547           break;
548         case 'I':
549           global_path.append (option_parser->optional_argument_str0_);
550           break;
551         case 'i':
552           init_name_global = option_parser->optional_argument_str0_;
553           break;
554         case 'h':
555           show_help = true;
556           break;
557         case 'V':
558           be_verbose_global = true;
559           break;
560         case 's':
561           be_safe_global = true;
562           init_scheme_variables
563             += "(cons \'safe #t)\n";
564
565           break;
566         case 'p':
567           make_preview = true;
568           break;
569         default:
570           programming_error (to_string ("unhandled short option: %c",
571                                         opt->shortname_char_));
572           assert (false);
573           break;
574         }
575     }
576
577   if (output_format_global == "")
578     output_format_global = "pdf";
579
580   if (show_help)
581     {
582       identify (stdout);
583       ly_usage ();
584       if (be_verbose_global)
585         dir_info (stdout);
586       exit (0);
587     }
588 }
589
590 void
591 setup_guile_env ()
592 {
593   char *yield = getenv ("LILYPOND_GC_YIELD");
594   bool overwrite = true;
595   if (!yield)
596     {
597       yield = "70";
598       overwrite = false;
599     }
600
601   sane_putenv ("GUILE_MIN_YIELD_1", yield, overwrite);
602   sane_putenv ("GUILE_MIN_YIELD_2", yield, overwrite);
603   sane_putenv ("GUILE_MIN_YIELD_MALLOC", yield, overwrite);
604 }
605
606 int
607 main (int argc, char **argv)
608 {
609   if (getenv ("LILYPOND_VERBOSE"))
610     be_verbose_global = true;
611
612   setup_localisation ();
613   parse_argv (argc, argv);
614   if (isatty (STDIN_FILENO))
615     identify (stderr);
616
617   setup_paths (argv[0]);
618   setup_guile_env ();
619
620   /* Debugging aid.  */
621   try
622     {
623       scm_boot_guile (argc, argv, main_with_guile, 0);
624     }
625   catch (exception e)
626     {
627       error (_f ("exception caught: %s", e.what ()));
628     };
629
630   /* Only reachable if GUILE exits.  That is an error.  */
631   return 1;
632 }