]> git.donarmstrong.com Git - lilypond.git/blob - lily/main.cc
* The grand 2005-2006 replace.
[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 "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 #if 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 #if HAVE_CHROOT
173   {_i ("USER,GROUP,JAIL,DIR"), "jail", 'j', _i ("chroot to JAIL, become USER:GROUP\n"
174                                                 "and cd into DIR")},
175 #endif
176   {0, "no-print", 0, _i ("do not generate printed output")},
177   {_i ("FILE"), "output", 'o',  _i ("write output to FILE (suffix will be added)")},
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--2006",
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   init_global_tweak_registry ();
391   init_fontconfig ();
392
393   init_freetype ();
394
395   all_fonts_global = new All_font_metrics (global_path.to_string ());
396
397   if (!init_scheme_variables.is_empty ()
398       || !init_scheme_code_string.is_empty ())
399     {
400       init_scheme_variables = "(map (lambda (x) (ly:set-option (car x) (cdr x))) (list "
401         + init_scheme_variables + "))";
402
403       init_scheme_code_string
404         += "(begin #t "
405         + init_scheme_variables
406         + init_scheme_code_string
407         + ")";
408
409       char const *str0 = init_scheme_code_string.to_str0 ();
410
411       if (be_verbose_global)
412         progress_indication (_f ("Evaluating %s", str0));
413       scm_c_eval_string ((char *) str0);
414     }
415
416   /* We accept multiple independent music files on the command line to
417      reduce compile time when processing lots of small files.
418      Starting the GUILE engine is very time consuming.  */
419
420   SCM files = SCM_EOL;
421   SCM *tail = &files;
422   while (char const *arg = option_parser->get_next_arg ())
423     {
424       *tail = scm_cons (scm_makfrom0str (arg), SCM_EOL);
425       tail = SCM_CDRLOC (*tail);
426     }
427   delete option_parser;
428   option_parser = 0;
429
430 #if HAVE_CHROOT
431   if (!jail_spec.is_empty ())
432     do_chroot_jail ();
433 #endif
434
435   SCM result = scm_call_1 (ly_lily_module_constant ("lilypond-main"), files);
436   (void) result;
437
438   /* Unreachable.  */
439   exit (0);
440 }
441
442 static void
443 setup_localisation ()
444 {
445 #if HAVE_GETTEXT
446   /* Enable locales */
447   setlocale (LC_ALL, "");
448
449   /* FIXME: check if this is still true.
450      Disable localisation of float values.  This breaks TeX output.  */
451   setlocale (LC_NUMERIC, "C");
452
453   String localedir = LOCALEDIR;
454   if (char const *env = getenv ("LILYPOND_LOCALEDIR"))
455     localedir = env;
456
457   bindtextdomain ("lilypond", localedir.to_str0 ());
458   textdomain ("lilypond");
459 #endif
460 }
461
462 static void
463 add_output_format (String format)
464 {
465   if (output_format_global != "")
466     output_format_global += ",";
467   output_format_global += format;
468 }
469
470 static void
471 parse_argv (int argc, char **argv)
472 {
473   bool show_help = false;
474   option_parser = new Getopt_long (argc, argv, options_static);
475   while (Long_option_init const *opt = (*option_parser) ())
476     {
477       switch (opt->shortname_char_)
478         {
479         case 0:
480           if (String (opt->longname_str0_) == "dvi"
481               || String (opt->longname_str0_) == "pdf"
482               || String (opt->longname_str0_) == "png"
483               || String (opt->longname_str0_) == "ps"
484               || String (opt->longname_str0_) == "tex")
485             add_output_format (opt->longname_str0_);
486           else if (String (opt->longname_str0_) == "preview")
487             make_preview = true;
488           else if (String (opt->longname_str0_) == "no-pages")
489             make_print = false;
490           else if (String (opt->longname_str0_) == "relocate")
491             relocate_binary = true;
492           break;
493
494         case 'd':
495           {
496             String arg (option_parser->optional_argument_str0_);
497             int eq = arg.index ('=');
498
499             String key = arg;
500             String val = "#t";
501
502             if (eq >= 0)
503               {
504                 key = arg.left_string (eq);
505                 val = arg.right_string (arg.length () - eq - 1);
506               }
507
508             init_scheme_variables
509               += "(cons \'" + key + "  " + val + ")\n";
510           }
511           break;
512
513         case 'v':
514           notice ();
515           exit (0);
516           break;
517         case 'o':
518           {
519             String s = option_parser->optional_argument_str0_;
520             File_name file_name (s);
521             output_name_global = file_name.to_string ();
522           }
523           break;
524         case 'j':
525           jail_spec = option_parser->optional_argument_str0_;
526           break;
527         case 'e':
528           init_scheme_code_string += option_parser->optional_argument_str0_;
529           break;
530         case 'w':
531           warranty ();
532           exit (0);
533           break;
534
535         case 'b':
536           output_backend_global = option_parser->optional_argument_str0_;
537           break;
538
539         case 'f':
540           output_format_global = option_parser->optional_argument_str0_;
541           break;
542
543         case 'H':
544           dump_header_fieldnames_global
545             .push (option_parser->optional_argument_str0_);
546           break;
547         case 'I':
548           global_path.append (option_parser->optional_argument_str0_);
549           break;
550         case 'i':
551           init_name_global = option_parser->optional_argument_str0_;
552           break;
553         case 'h':
554           show_help = true;
555           break;
556         case 'V':
557           be_verbose_global = true;
558           break;
559         case 's':
560           be_safe_global = true;
561           break;
562         case 'p':
563           make_preview = true;
564           break;
565         default:
566           programming_error (to_string ("unhandled short option: %c",
567                                         opt->shortname_char_));
568           assert (false);
569           break;
570         }
571     }
572
573   if (output_format_global == "")
574     output_format_global = "pdf";
575
576   if (show_help)
577     {
578       identify (stdout);
579       ly_usage ();
580       if (be_verbose_global)
581         dir_info (stdout);
582       exit (0);
583     }
584 }
585
586 void
587 setup_guile_env ()
588 {
589   char *yield = getenv ("LILYPOND_GC_YIELD");
590   bool overwrite = true;
591   if (!yield)
592     {
593       yield = "70";
594       overwrite = false;
595     }
596
597   sane_putenv ("GUILE_MIN_YIELD_1", yield, overwrite);
598   sane_putenv ("GUILE_MIN_YIELD_2", yield, overwrite);
599   sane_putenv ("GUILE_MIN_YIELD_MALLOC", yield, overwrite);
600 }
601
602 int
603 main (int argc, char **argv)
604 {
605   if (getenv ("LILYPOND_VERBOSE"))
606     be_verbose_global = true;
607
608   setup_localisation ();
609   parse_argv (argc, argv);
610   if (isatty (STDIN_FILENO))
611     identify (stderr);
612
613   setup_paths (argv[0]);
614   setup_guile_env ();
615   scm_boot_guile (argc, argv, main_with_guile, 0);
616
617   /* Only reachable if GUILE exits.  That is an error.  */
618   return 1;
619 }