2 main.cc -- implement main () entrypoint.
4 source file of the GNU LilyPond music typesetter
6 (c) 1997--2005 Han-Wen Nienhuys <hanwen@xs4all.nl>
18 #include <sys/types.h>
33 #include "all-font-metrics.hh"
34 #include "file-name.hh"
35 #include "freetype.hh"
36 #include "getopt-long.hh"
37 #include "global-ctor.hh"
38 #include "lily-guile.hh"
39 #include "lily-version.hh"
41 #include "output-def.hh"
42 #include "string-convert.hh"
45 #include "program-option.hh"
48 * Global options that can be overridden through command line.
51 /* Names of header fields to be dumped to a separate file. */
52 Array<String> dump_header_fieldnames_global;
54 /* Name of initialisation file. */
55 String init_name_global;
57 /* Selected output backend
58 One of (gnome, ps [default], eps, scm, svg, tex, texstr)") */
59 String output_backend_global = "ps";
60 /* Output formats to generate. */
61 String output_format_global = "";
63 bool is_pango_format_global;
64 bool is_TeX_format_global;
66 /* Current output name. */
67 String output_name_global;
69 /* Run in safe mode? */
70 bool be_safe_global = false;
72 /* Provide URI links to the original file */
73 bool point_and_click_global = true;
75 /* Verbose progress indication? */
76 bool be_verbose_global = false;
78 /* Scheme code to execute before parsing, after .scm init.
79 This is where -e arguments are appended to. */
80 String init_scheme_code_string;
81 String init_scheme_variables;
83 /* Generate preview of first system. */
84 bool make_preview = false;
86 /* Generate printed output. */
87 bool make_print = true;
90 bool relocate_binary =
100 * Miscellaneous global stuff.
102 File_path global_path;
108 static char const *AUTHORS
109 = " Han-Wen Nienhuys <hanwen@xs4all.nl>\n"
110 " Jan Nieuwenhuizen <janneke@gnu.org>\n";
112 static char const *PROGRAM_NAME = "lilypond";
113 static char const *PROGRAM_URL = "http://lilypond.org";
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"
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"
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"
131 " You should have received a copy (refer to the file COPYING) 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");
136 /* Where the init files live. Typically:
137 LILYPOND_DATADIR = /usr/share/lilypond
139 String prefix_directory;
141 /* The jail specification: USER,GROUP,JAIL,DIR. */
144 /* The option parser */
145 static Getopt_long *option_parser = 0;
147 /* Internationalisation kludge in two steps:
148 * use _i () to get entry in POT file
149 * call gettext () explicitely for actual "translation" */
151 static Long_option_init options_static[]
153 {_i ("BACK"), "backend", 'b', _i ("use backend BACK (gnome, ps,eps,\nscm, svg, tex, texstr)\ndefault: PS")},
155 {_i ("SYM=VAL"), "define-default", 'd',
156 _i ("set a Scheme program option. Uses #t if VAL is not specified\n"
157 "Try -dhelp for help.")},
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, "relocate", 0, _i("relocate using path to binary")},
165 {0, "pdf", 0, _i ("generate PDF (default)")},
166 {0, "png", 0, _i ("generate PNG")},
167 {0, "ps", 0, _i ("generate PostScript")},
168 {0, "tex", 0, _i ("generate TeX (tex backend only)")},
169 {0, "help", 'h', _i ("print this help")},
170 {_i ("FIELD"), "header", 'H', _i ("dump a header field to file 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 {_i ("FILE"), "output", 'o', _i ("write output to FILE (suffix will be added)")},
175 {_i ("USER,GROUP,JAIL,DIR"), "jail", 'j', _i ("chroot to JAIL, become USER:GROUP\n"
178 {0, "no-print", 0, _i ("do not generate printed output")},
179 {0, "preview", 'p', _i ("generate a preview of the first system")},
180 {0, "safe-mode", 's', _i ("disallow unsafe Scheme and PostScript operations")},
181 {0, "version", 'v', _i ("print version number")},
182 {0, "verbose", 'V', _i ("be verbose")},
183 {0, "warranty", 'w', _i ("show warranty and copyright")},
187 #define LILYPOND_DATADIR PACKAGE_DATADIR "/" TOPLEVEL_VERSION
190 env_var_info (FILE *out, char const *key)
192 if (char const *value = getenv (key))
193 fprintf (out, "%s=\"%s\"\n", key, value);
200 fprintf (out, "LILYPOND_DATADIR=\"%s\"\n", LILYPOND_DATADIR);
201 env_var_info (out, "LILYPONDPREFIX");
202 fprintf (out, "LOCALEDIR=\"%s\"\n", LOCALEDIR);
204 fprintf (out, "\nEffective prefix: \"%s\"\n", prefix_directory.to_str0 ());
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, "PATH");
221 printf (_f ("Copyright (c) %s by\n%s and others.",
223 AUTHORS).to_str0 ());
230 fputs (gnu_lilypond_version_string ().to_str0 (), out);
238 puts (_f (NOTICE, PROGRAM_NAME).to_str0 ());
243 LY_DEFINE (ly_usage, "ly:usage",
245 "Print usage message.")
247 /* No version number or newline here. It confuses help2man. */
248 printf (_f ("Usage: %s [OPTION]... FILE...", PROGRAM_NAME).to_str0 ());
250 printf (_ ("Typeset music and/or produce MIDI from FILE.").to_str0 ());
252 printf (_ ("LilyPond produces beautiful music notation.").to_str0 ());
254 printf (_f ("For more information, see %s", PROGRAM_URL).to_str0 ());
256 printf (_ ("Options:").to_str0 ());
258 printf (Long_option_init::table_string (options_static).to_str0 ());
260 printf (_f ("Report bugs via %s",
261 "http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs"
265 return SCM_UNSPECIFIED;
275 printf (_ (WARRANTY).to_str0 ());
279 sane_putenv (char const *key, String value, bool overwrite = true)
281 if (overwrite || !getenv (key))
283 String combine = String (key) + "=" + value;
284 char *s = strdup (combine.to_str0 ());
291 set_env_file (char const *key, String value)
294 return sane_putenv (key, value, false);
295 else if (be_verbose_global)
296 warning (_f ("no such file: %s", value));
301 prepend_env_path (char const *key, String value)
305 if (be_verbose_global)
306 progress_indication (_f ("%s=%s\n", key, value.to_str0 ()));
308 if (char const *cur = getenv (key))
309 value += to_string (PATHSEP) + cur;
311 return sane_putenv (key, value.to_str0 ());
313 else if (be_verbose_global)
314 warning (_f ("no such directory: %s for %s", value, key));
319 dir_name (String const file_name)
321 String s = file_name;
322 s.substitute ('\\', '/');
323 s = s.left_string (s.index_last ('/'));
332 set_relocation (String bindir, String prefix)
334 if (be_verbose_global)
335 warning (_f ("Relocation: compile prefix=%s, new prefix=%s",
339 String datadir = prefix + "/share";
340 String libdir = prefix + "/lib";
341 String localedir = datadir + "/locale";
342 String sysconfdir = prefix + "/etc";
343 String lilypond_datadir = datadir + "/lilypond/" TOPLEVEL_VERSION;
345 if (is_dir (lilypond_datadir))
346 prefix_directory = lilypond_datadir;
349 if (is_dir (localedir))
350 bindtextdomain ("lilypond", localedir.to_str0 ());
353 set_env_file ("FONTCONFIG_FILE", sysconfdir + "/fonts/fonts.conf");
355 char font_dir[PATH_MAX];
356 ExpandEnvironmentStrings ("%windir%/fonts", font_dir, sizeof (font_dir));
357 prepend_env_path ("GS_FONTPATH", font_dir);
360 /* FIXME: *cough* 8.15 *cough* */
361 prepend_env_path ("GS_FONTPATH", datadir + "/ghostscript/8.15/fonts");
362 prepend_env_path ("GS_LIB", datadir + "/ghostscript/8.15/Resource");
363 prepend_env_path ("GS_LIB", datadir + "/ghostscript/8.15/lib");
365 prepend_env_path ("GS_FONTPATH", datadir + "/gs/fonts");
366 prepend_env_path ("GS_LIB", datadir + "/gs/Resource");
367 prepend_env_path ("GS_LIB", datadir + "/gs/lib");
369 /* need otherwise dynamic .so's aren't found. */
370 prepend_env_path ("DYLD_LIBRARY_PATH", libdir);
372 prepend_env_path ("GUILE_LOAD_PATH", datadir
373 + to_string ("/guile/%d.%d",
374 SCM_MAJOR_VERSION, SCM_MINOR_VERSION));
375 set_env_file ("PANGO_RC_FILE", sysconfdir + "/pango/pangorc");
376 prepend_env_path ("PATH", bindir);
380 get_working_directory ()
383 getcwd (cwd, PATH_MAX);
389 setup_paths (char const *argv0)
391 prefix_directory = LILYPOND_DATADIR;
395 if (getenv ("LILYPOND_VERBOSE"))
396 be_verbose_global = true;
398 #if defined (__CYGWIN__) || defined (__MINGW32__)
400 s.substitute ('\\', '/');
401 argv0 = s.to_str0 ();
402 #endif /* __CYGWIN__ || __MINGW32__ */
405 /* if name contains slashes, we should not look in $PATH */
408 argv0_abs = argv0_abs;
409 else if (String (argv0).index ('/') > 0)
410 argv0_abs = get_working_directory () + "/" + String (argv0);
413 /* Find absolute ARGV0 name, using PATH. */
415 path.parse_path (getenv ("PATH"));
419 String argv0_abs = path.find (argv0);
420 #else /* __MINGW32__ */
421 char const *ext[] = {"exe", "", 0 };
422 String argv0_abs = path.find (argv0, ext);
423 #endif /* __MINGW32__ */
425 if (argv0_abs.is_empty ())
427 File_name name (argv0);
428 /* If NAME contains slashes and its DIR is not absolute, it can
429 only be referenced from CWD. */
430 if (name.to_string ().index ('/') >= 0 && name.dir_[0] != '/')
432 argv0_abs = get_working_directory () + "/" + argv0;
435 programming_error ("can't find absolute argv0");
439 String bindir = dir_name (argv0_abs);
440 String argv0_prefix = dir_name (bindir);
441 if (argv0_prefix != dir_name (dir_name (dir_name (prefix_directory))))
442 set_relocation (bindir, argv0_prefix);
447 /* FIXME: use LILYPOND_DATADIR. */
448 if (char const *env = getenv ("LILYPONDPREFIX"))
451 /* Normalize file name. */
452 env = File_name (env).to_string ().get_copy_str0 ();
454 prefix_directory = env;
457 global_path.append ("");
461 When running from build dir, a full LILYPOND_PREFIX is set-up at
463 $(OUTBASE)/share/lilypond/TOPLEVEL_VERSION
465 This historical hack will allow the shorthand
467 LILYPONDPREFIX=out lily/out/lilypond ...
472 String build_prefix = prefix_directory + "/share/lilypond/" TOPLEVEL_VERSION;
473 if (stat (build_prefix.to_str0 (), &statbuf) == 0)
474 prefix_directory = build_prefix;
477 /* Adding mf/out make lilypond unchanged source directory, when setting
478 LILYPONDPREFIX to lilypond-x.y.z */
479 char *suffixes[] = {"ly", "ps", "scm", 0 };
483 for (char **s = suffixes; *s; s++)
485 String path = prefix_directory + to_string ('/') + String (*s);
490 dirs.push (prefix_directory + "/fonts/otf/");
491 dirs.push (prefix_directory + "/fonts/type1/");
492 dirs.push (prefix_directory + "/fonts/svg/");
494 for (int i = 0; i < dirs.size (); i++)
495 global_path.prepend (dirs[i]);
499 prepend_load_path (String dir)
501 String s = "(set! %load-path (cons \"" + dir + "\" %load-path))";
502 scm_c_eval_string (s.to_str0 ());
505 void init_global_tweak_registry ();
506 void init_fontconfig ();
512 /* Now we chroot, setuid/setgrp and chdir. If something goes wrong,
513 we exit (this is a security-sensitive area). First we split
514 jail_spec into its components, then we retrieve the user/group id
515 (necessarily *before* chroot'ing) and finally we perform the
520 USER_NAME, GROUP_NAME, JAIL, DIR, JAIL_MAX
523 Array<String> components = String_convert::split (jail_spec, ',');
524 if (components.size () != JAIL_MAX)
526 error (_f ("expected %d arguments with jail, found: %d", JAIL_MAX,
527 components.size ()));
535 if (passwd * passwd = getpwnam (components[USER_NAME].to_str0 ()))
536 uid = passwd->pw_uid;
540 error (_f ("no such user: %s", components[USER_NAME]));
542 error (_f ("can't get user id from user name: %s: %s",
543 components[USER_NAME],
552 if (group * group = getgrnam (components[GROUP_NAME].to_str0 ()))
557 error (_f ("no such group: %s", components[GROUP_NAME]));
559 error (_f ("can't get group id from group name: %s: %s",
560 components[GROUP_NAME],
565 if (chroot (components[JAIL].to_str0 ()))
567 error (_f ("can't chroot to: %s: %s", components[JAIL],
574 error (_f ("can't change group id to: %d: %s", gid, strerror (errno)));
580 error (_f ("can't change user id to: %d: %s", uid, strerror (errno)));
584 if (chdir (components[DIR].to_str0 ()))
586 error (_f ("can't change working directory to: %s: %s", components[DIR],
594 main_with_guile (void *, int, char **)
596 /* Engravers use lily.scm contents, need to make Guile find it.
597 Prepend onto GUILE %load-path, very ugh. */
599 prepend_load_path (prefix_directory);
600 prepend_load_path (prefix_directory + "/scm");
602 if (be_verbose_global)
604 is_TeX_format_global = (output_backend_global == "tex"
605 || output_backend_global == "texstr");
607 is_pango_format_global = !is_TeX_format_global;
610 call_constructors ();
611 ly_set_option (ly_symbol2scm ("verbose"), scm_from_bool (be_verbose_global));
613 init_global_tweak_registry ();
618 all_fonts_global = new All_font_metrics (global_path.to_string ());
620 if (!init_scheme_variables.is_empty ()
621 || !init_scheme_code_string.is_empty ())
623 init_scheme_variables = "(map (lambda (x) (ly:set-option (car x) (cdr x))) (list "
624 + init_scheme_variables + "))";
626 init_scheme_code_string
628 + init_scheme_variables
629 + init_scheme_code_string
632 char const *str0 = init_scheme_code_string.to_str0 ();
634 if (be_verbose_global)
635 progress_indication (_f ("Evaluating %s", str0));
636 scm_c_eval_string ((char *) str0);
639 /* We accept multiple independent music files on the command line to
640 reduce compile time when processing lots of small files.
641 Starting the GUILE engine is very time consuming. */
645 while (char const *arg = option_parser->get_next_arg ())
647 *tail = scm_cons (scm_makfrom0str (arg), SCM_EOL);
648 tail = SCM_CDRLOC (*tail);
650 delete option_parser;
654 if (!jail_spec.is_empty ())
658 SCM result = scm_call_1 (ly_lily_module_constant ("lilypond-main"), files);
666 setup_localisation ()
670 setlocale (LC_ALL, "");
672 /* FIXME: check if this is still true.
673 Disable localisation of float values. This breaks TeX output. */
674 setlocale (LC_NUMERIC, "C");
676 String localedir = LOCALEDIR;
677 if (char const *env = getenv ("LILYPOND_LOCALEDIR"))
680 bindtextdomain ("lilypond", localedir.to_str0 ());
681 textdomain ("lilypond");
686 add_output_format (String format)
688 if (output_format_global != "")
689 output_format_global += ",";
690 output_format_global += format;
694 parse_argv (int argc, char **argv)
696 bool show_help = false;
697 option_parser = new Getopt_long (argc, argv, options_static);
698 while (Long_option_init const *opt = (*option_parser) ())
700 switch (opt->shortname_char_)
703 if (String (opt->longname_str0_) == "dvi"
704 || String (opt->longname_str0_) == "pdf"
705 || String (opt->longname_str0_) == "png"
706 || String (opt->longname_str0_) == "ps"
707 || String (opt->longname_str0_) == "tex")
708 add_output_format (opt->longname_str0_);
709 else if (String (opt->longname_str0_) == "preview")
711 else if (String (opt->longname_str0_) == "no-pages")
713 else if (String (opt->longname_str0_) == "relocate")
714 relocate_binary = true;
719 String arg (option_parser->optional_argument_str0_);
720 int eq = arg.index ('=');
727 key = arg.left_string (eq);
728 val = arg.right_string (arg.length () - eq - 1);
731 init_scheme_variables
732 += "(cons \'" + key + " " + val + ")\n";
742 String s = option_parser->optional_argument_str0_;
743 File_name file_name (s);
744 output_name_global = file_name.to_string ();
748 jail_spec = option_parser->optional_argument_str0_;
751 init_scheme_code_string += option_parser->optional_argument_str0_;
759 output_backend_global = option_parser->optional_argument_str0_;
763 output_format_global = option_parser->optional_argument_str0_;
767 dump_header_fieldnames_global
768 .push (option_parser->optional_argument_str0_);
771 global_path.append (option_parser->optional_argument_str0_);
774 init_name_global = option_parser->optional_argument_str0_;
780 be_verbose_global = true;
783 be_safe_global = true;
789 programming_error (to_string ("unhandled short option: %c",
790 opt->shortname_char_));
796 if (output_format_global == "")
797 output_format_global = "pdf";
803 if (be_verbose_global)
812 char *yield = getenv ("LILYPOND_GC_YIELD");
813 bool overwrite = true;
820 sane_putenv ("GUILE_MIN_YIELD_1", yield, overwrite);
821 sane_putenv ("GUILE_MIN_YIELD_2", yield, overwrite);
822 sane_putenv ("GUILE_MIN_YIELD_MALLOC", yield, overwrite);
826 main (int argc, char **argv)
828 setup_localisation ();
829 parse_argv (argc, argv);
830 if (isatty (STDIN_FILENO))
833 setup_paths (argv[0]);
835 scm_boot_guile (argc, argv, main_with_guile, 0);
837 /* Only reachable if GUILE exits. That is an error. */