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