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