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