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