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