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