]> git.donarmstrong.com Git - lilypond.git/blob - lily/main.cc
(main_with_guile): copy be_verbose_global into
[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--2005 Han-Wen Nienhuys <hanwen@cs.uu.nl>
7 */
8
9 #include "main.hh"
10
11 #include <cassert>
12 #include <clocale>
13 #include <cstring>
14 #include <unistd.h>
15 #include <errno.h>
16 #include <sys/types.h>
17 #include <sys/stat.h>
18
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 "lily-guile.hh"
37 #include "lily-version.hh"
38 #include "misc.hh"
39 #include "output-def.hh"
40 #include "string-convert.hh"
41 #include "version.hh"
42 #include "warn.hh"
43
44 /*
45  * Global options that can be overridden through command line.
46  */
47
48 /* Names of header fields to be dumped to a separate file. */
49 Array<String> dump_header_fieldnames_global;
50
51 /* Name of initialisation file. */
52 String init_name_global;
53
54 /* Selected output backend
55    One of (gnome, ps [default], scm, svg, tex, texstr)") */
56 String output_backend_global = "ps";
57 /* Output formats to generate.  */
58 String output_format_global = "pdf";
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_string;
78 String init_scheme_variables;
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  * Miscellaneous global stuff.
88  */
89 File_path global_path;
90
91 /*
92  * File globals.
93  */
94
95 static char const *AUTHORS
96 = "  Han-Wen Nienhuys <hanwen@cs.uu.nl>\n"
97   "  Jan Nieuwenhuizen <janneke@gnu.org>\n";
98
99 static char const *PROGRAM_NAME = "lilypond";
100 static char const *PROGRAM_URL = "http://lilypond.org";
101
102 static char const *NOTICE
103 = _i ("This program is free software.  It is covered by the GNU General Public\n"
104       "License and you are welcome to change it and/or distribute copies of it\n"
105       "under certain conditions.  Invoke as `%s --warranty' for more\n"
106       "information.\n");
107
108 static char const *WARRANTY
109 = _i ("    This program is free software; you can redistribute it and/or\n"
110       "modify it under the terms of the GNU General Public License version 2\n"
111       "as published by the Free Software Foundation.\n"
112       "\n"
113       "    This program is distributed in the hope that it will be useful,\n"
114       "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
115       "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
116       "General Public License for more details.\n"
117       "\n"
118       "    You should have received a copy (refer to the file COPYING) of the\n"
119       "GNU General Public License along with this program; if not, write to\n"
120       "the Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n"
121       "Boston, MA 02111-1307, USA.\n");
122
123 /* Where the init files live.  Typically:
124    LILYPOND_DATADIR = /usr/share/lilypond
125 */
126 String prefix_directory;
127
128 /* The jail specification: USER,GROUP,JAIL,DIR. */
129 String jail_spec;
130
131 /*  The option parser */
132 static Getopt_long *option_parser = 0;
133
134 /* Internationalisation kludge in two steps:
135  * use _i () to get entry in POT file
136  * call gettext () explicitely for actual "translation"  */
137
138 static Long_option_init options_static[]
139 = {
140   {_i ("BACK"), "backend", 'b', _i ("use backend BACK (gnome, ps [default],\nscm, svg, tex, texstr)")},
141
142   {_i ("SYM=VAL"), "define-default", 'd',
143    _i ("set a Scheme program option. Uses #t if VAL is not specified\n"
144        "Try -dhelp for help.")},
145
146   {_i ("EXPR"), "evaluate", 'e', _i ("evaluate scheme code")},
147   /* Bug in option parser: --output =foe is taken as an abbreviation
148      for --output-format.  */
149   {_i ("FORMATs"), "formats", 'f', _i ("dump FORMAT,...  Also as separate options:")},
150   {0, "dvi", 0, _i ("generate DVI (tex backend only)")},
151   {0, "pdf", 0, _i ("generate PDF (default)")},
152   {0, "png", 0, _i ("generate PNG")},
153   {0, "ps", 0, _i ("generate PostScript")},
154   {0, "tex", 0, _i ("generate TeX (tex backend only)")},
155   {0, "help", 'h',  _i ("print this help")},
156   {_i ("FIELD"), "header", 'H',  _i ("dump a header field to file BASENAME.FIELD")},
157   {_i ("DIR"), "include", 'I',  _i ("add DIR to search path")},
158   {_i ("FILE"), "init", 'i',  _i ("use FILE as init file")},
159   {_i ("FILE"), "output", 'o',  _i ("write output to FILE (suffix will be added)")},
160 #if HAVE_CHROOT
161   {_i ("USER,GROUP,JAIL,DIR"), "jail", 'j', _i ("chroot to JAIL, become USER:GROUP\n"
162                                                 "and cd into DIR")},
163 #endif 
164   {0, "no-print", 0, _i ("do not generate printed output")},
165   {0, "preview", 'p',  _i ("generate a preview of the first system")},
166   {0, "safe-mode", 's',  _i ("run in safe mode")},
167   {0, "version", 'v',  _i ("print version number")},
168   {0, "verbose", 'V', _i ("be verbose")},
169   {0, "warranty", 'w',  _i ("show warranty and copyright")},
170   {0, 0, 0, 0}
171 };
172
173 #define LILYPOND_DATADIR PACKAGE_DATADIR "/" TOPLEVEL_VERSION
174
175 static void
176 env_var_info (FILE *out, char const* key)
177 {
178   if (char const *value = getenv (key))
179     fprintf (out, "%s=\"%s\"\n", key, value);
180 }
181
182 static void
183 dir_info (FILE *out)
184 {
185   fputs ("\n", out);
186   fprintf (out, "LILYPOND_DATADIR=\"%s\"\n", LILYPOND_DATADIR);
187   env_var_info (out, "LILYPONDPREFIX");
188   fprintf (out, "LOCALEDIR=\"%s\"\n", LOCALEDIR);
189
190   fprintf (out, "\nEffective prefix: \"%s\"\n", prefix_directory.to_str0 ());
191
192 #if ARGV0_RELOCATION
193   env_var_info (out, "FONTCONFIG_FILE");
194   env_var_info (out, "FONTCONFIG_PATH");
195   env_var_info (out, "GS_FONTPATH");
196   env_var_info (out, "GS_LIB");
197   env_var_info (out, "GUILE_LOAD_PATH");
198   env_var_info (out, "PANGO_RC_FILE");
199   env_var_info (out, "PATH");
200 #endif  
201 }
202
203 static void
204 copyright ()
205 {
206   printf (_f ("Copyright (c) %s by\n%s  and others.",
207               "1996--2005",
208               AUTHORS).to_str0 ());
209   printf ("\n");
210 }
211
212 static void
213 identify (FILE *out)
214 {
215   fputs (gnu_lilypond_version_string ().to_str0 (), out);
216   fputs ("\n", out);
217 }
218
219 static void
220 notice ()
221 {
222   identify (stdout);
223   puts (_f (NOTICE, PROGRAM_NAME).to_str0 ());
224   printf ("\n");
225   copyright ();
226 }
227
228 LY_DEFINE (ly_usage, "ly:usage",
229            0, 0, 0, (),
230            "Print usage message.")
231 {
232   /* No version number or newline here.  It confuses help2man.  */
233   printf (_f ("Usage: %s [OPTION]... FILE...", PROGRAM_NAME).to_str0 ());
234   printf ("\n\n");
235   printf (_ ("Typeset music and/or produce MIDI from FILE.").to_str0 ());
236   printf ("\n\n");
237   printf (_ ("LilyPond produces beautiful music notation.").to_str0 ());
238   printf ("\n");
239   printf (_f ("For more information, see %s", PROGRAM_URL).to_str0 ());
240   printf ("\n\n");
241   printf (_ ("Options:").to_str0 ());
242   printf ("\n");
243   printf (Long_option_init::table_string (options_static).to_str0 ());
244   printf ("\n");
245   printf (_f ("Report bugs to %s.", "bug-lilypond@gnu.org").to_str0 ());
246   printf ("\n");
247   printf ("\n");
248   return SCM_UNSPECIFIED;
249 }
250
251 static void
252 warranty ()
253 {
254   identify (stdout);
255   printf ("\n");
256   copyright ();
257   printf ("\n");
258   printf (_ (WARRANTY).to_str0 ());
259 }
260
261 #if ARGV0_RELOCATION
262 static int
263 sane_putenv (char const* key, String value, bool overwrite = true)
264 {
265   if (overwrite || !getenv (key))
266     {
267       String combine = String (key) + "=" + value;
268       char *s = strdup (combine.to_str0 ());
269       return putenv (s);
270     }
271   return -1;
272 }
273
274 static int
275 set_env_file (char const* key, String value)
276 {
277   if (is_file (value))
278     return sane_putenv (key, value, false);
279   else if (be_verbose_global)
280     warning (_f ("no such file: %s", value));
281   return -1;
282 }
283
284 static int
285 prepend_env_path (char const *key, String value)
286 {
287   if (is_dir (value))
288     {
289       if (char const* cur = getenv (key))
290         value += to_string (PATHSEP) + cur;
291       return sane_putenv (key, value.to_str0 ());
292     }
293   else if (be_verbose_global)
294     warning (_f ("no such directory: %s", value));
295   return -1;
296 }
297
298 String
299 dir_name (String const file_name)
300 {
301   String s = file_name;
302   s.substitute ('\\', '/');
303   s = s.left_string (s.index_last ('/'));
304   return s;
305 }
306 #endif
307
308 #ifdef __MINGW32__
309 #  include <winbase.h>
310 #endif
311
312 static void
313 setup_paths (char const* argv0)
314 {
315   prefix_directory = LILYPOND_DATADIR;
316
317 #if ARGV0_RELOCATION
318
319   if (getenv ("LILYPOND_VERBOSE"))
320     be_verbose_global = true;
321
322   String bindir = dir_name (argv0);
323   String argv0_prefix = dir_name (bindir);
324   if (argv0_prefix != dir_name (dir_name (dir_name (prefix_directory))))
325     {
326       if (be_verbose_global)
327         warning (_f ("argv0 relocation: argv0=%s, prefix=%s", argv0,
328                      prefix_directory));
329       String datadir = argv0_prefix + "/share";
330       String libdir = argv0_prefix + "/lib";
331       String localedir = datadir + "/locale";
332       String sysconfdir = argv0_prefix + "/etc";
333       String argv0_lilypond_datadir = datadir + "/lilypond/" TOPLEVEL_VERSION;
334
335       if (is_dir (argv0_lilypond_datadir))
336         prefix_directory = argv0_lilypond_datadir;
337
338 #if HAVE_GETTEXT
339       if (is_dir (localedir))
340         bindtextdomain ("lilypond", localedir.to_str0 ());
341 #endif
342
343       set_env_file ("FONTCONFIG_FILE", sysconfdir + "/fonts/fonts.conf");
344 #ifdef __MINGW32__
345       char font_dir[PATH_MAX];
346       ExpandEnvironmentStrings ("%windir%/fonts", font_dir, sizeof (font_dir));
347       prepend_env_path ("GS_FONTPATH", font_dir);
348 #endif
349
350       /* FIXME: *cough* 8.15 *cough* */
351       prepend_env_path ("GS_FONTPATH", datadir + "/ghostscript/8.15/fonts");
352       prepend_env_path ("GS_LIB", datadir + "/ghostscript/8.15/Resource");
353       prepend_env_path ("GS_LIB", datadir + "/ghostscript/8.15/lib");
354
355       prepend_env_path ("GS_FONTPATH", datadir + "/gs/fonts");
356       prepend_env_path ("GS_LIB", datadir + "/gs/Resource");
357       prepend_env_path ("GS_LIB", datadir + "/gs/lib");
358
359       prepend_env_path ("GUILE_LOAD_PATH", datadir
360                         + to_string ("/guile/%d.%d",
361                                      SCM_MAJOR_VERSION, SCM_MINOR_VERSION));
362       set_env_file ("PANGO_RC_FILE", sysconfdir + "/pango/pangorc");
363       prepend_env_path ("PATH", bindir);
364     }
365 #else
366   (void) argv0;
367 #endif /* ARGV0_RELOCATION */
368
369   /* FIXME: use LILYPOND_DATADIR.  */
370   if (char const *env = getenv ("LILYPONDPREFIX"))
371     {
372 #ifdef __MINGW32__
373       /* Normalize file name.  */
374       env = File_name (env).to_string ().get_copy_str0 ();
375 #endif
376       prefix_directory = env;
377     }
378
379   global_path.append ("");
380
381   /* Adding mf/out make lilypond unchanged source directory, when setting
382      LILYPONDPREFIX to lilypond-x.y.z */
383   char *suffixes[] = {"ly", "ps", "scm", 0 };
384
385   Array<String> dirs;
386   for (char **s = suffixes; *s; s++)
387     {
388       String path = prefix_directory + to_string ('/') + String (*s);
389       dirs.push (path);
390     }
391
392   /*
393     ugh. C&P font-config.cc
394   */
395   struct stat statbuf; 
396   String builddir = prefix_directory + "/mf/out/";
397   if (stat (builddir.to_str0 (), &statbuf) == 0)
398     {
399       dirs.push (builddir.to_str0 ());
400     }
401   else
402     {
403       dirs.push (prefix_directory + "/fonts/otf/");
404       dirs.push (prefix_directory + "/fonts/type1/");
405       dirs.push (prefix_directory + "/fonts/cff/");
406       dirs.push (prefix_directory + "/fonts/svg/");
407       dirs.push (prefix_directory + "/fonts/cff/");
408     }
409
410   for (int i = 0; i < dirs.size (); i++)
411     global_path.prepend (dirs[i]);  
412 }
413   
414 static void
415 prepend_load_path (String dir)
416 {
417   String s = "(set! %load-path (cons \"" + dir + "\" %load-path))";
418   scm_c_eval_string (s.to_str0 ());
419 }
420
421 void init_global_tweak_registry ();
422 void init_fontconfig ();
423
424 #if HAVE_CHROOT
425 static void
426 do_chroot_jail ()
427 {
428   /* Now we chroot, setuid/setgrp and chdir.  If something goes wrong,
429      we exit (this is a security-sensitive area).  First we split
430      jail_spec into its components, then we retrieve the user/group id
431      (necessarily *before* chroot'ing) and finally we perform the
432      actual actions.  */
433
434   enum Jail
435     {
436       USER_NAME, GROUP_NAME, JAIL, DIR, JAIL_MAX
437     };
438
439   Array<String> components = String_convert::split (jail_spec, ',');
440   if (components.size () != JAIL_MAX)
441     {
442       error (_f ("expected %d arguments with jail, found: %d", JAIL_MAX,
443                  components.size ()));
444       exit (2);
445     }
446
447   /* Hmm.  */
448   errno = 0;
449
450   int uid;
451   if (passwd * passwd = getpwnam (components[USER_NAME].to_str0 ()))
452     uid = passwd->pw_uid;
453   else
454     {
455       if (errno == 0)
456         error (_f ("no such user: %s", components[USER_NAME]));
457       else
458         error (_f ("can't get user id from user name: %s: %s",
459                    components[USER_NAME],
460                    strerror (errno)));
461       exit (3);
462     }
463
464   /* Hmm.  */
465   errno = 0;
466
467   int gid;
468   if (group * group = getgrnam (components[GROUP_NAME].to_str0 ()))
469     gid = group->gr_gid;
470   else
471     {
472       if (errno == 0)
473         error (_f ("no such group: %s", components[GROUP_NAME]));
474       else
475         error (_f ("can't get group id from group name: %s: %s",
476                    components[GROUP_NAME],
477                    strerror (errno)));
478       exit (3);
479     }
480
481   if (chroot (components[JAIL].to_str0 ()))
482     {
483       error (_f ("can't chroot to: %s: %s", components[JAIL],
484                  strerror (errno)));
485       exit (3);
486     }
487
488   if (setgid (gid))
489     {
490       error (_f ("can't change group id to: %d: %s", gid, strerror (errno)));
491       exit (3);
492     }
493
494   if (setuid (uid))
495     {
496       error (_f ("can't change user id to: %d: %s", uid, strerror (errno)));
497       exit (3);
498     }
499
500   if (chdir (components[DIR].to_str0 ()))
501     {
502       error (_f ("can't change working directory to: %s: %s", components[DIR],
503                  strerror (errno)));
504       exit (3);
505     }
506 }
507 #endif
508
509
510
511 static void
512 main_with_guile (void *, int, char **)
513 {
514   /* Engravers use lily.scm contents, need to make Guile find it.
515      Prepend onto GUILE %load-path, very ugh. */
516
517   prepend_load_path (prefix_directory);
518   prepend_load_path (prefix_directory + "/scm");
519
520   if (be_verbose_global)
521     dir_info (stderr);
522   is_TeX_format_global = (output_backend_global == "tex"
523                           || output_backend_global == "texstr");
524
525   is_pango_format_global = !is_TeX_format_global;
526
527   ly_c_init_guile ();
528   call_constructors ();
529   ly_set_option (ly_symbol2scm ("verbose"), scm_from_bool (be_verbose_global));
530
531   
532   init_global_tweak_registry ();
533   init_fontconfig ();
534
535   init_freetype ();
536
537   all_fonts_global = new All_font_metrics (global_path.to_string ());
538
539   
540   if (!init_scheme_variables.is_empty ()
541       || !init_scheme_code_string.is_empty ())
542     {
543       init_scheme_variables = "(map (lambda (x) (ly:set-option (car x) (cdr x))) (list "
544         + init_scheme_variables + "))";
545       
546       init_scheme_code_string
547         += "(begin #t "
548         + init_scheme_variables
549         + init_scheme_code_string
550         + ")";
551
552       char const *str0 = init_scheme_code_string.to_str0 ();
553       
554       if (be_verbose_global)
555         progress_indication (_f("Evaluating %s", str0));
556       scm_c_eval_string ((char *) str0);
557     }
558
559   
560   /* We accept multiple independent music files on the command line to
561      reduce compile time when processing lots of small files.
562      Starting the GUILE engine is very time consuming.  */
563
564   SCM files = SCM_EOL;
565   SCM *tail = &files;
566   while (char const *arg = option_parser->get_next_arg ())
567     {
568       *tail = scm_cons (scm_makfrom0str (arg), SCM_EOL);
569       tail = SCM_CDRLOC (*tail);
570     }
571   delete option_parser;
572   option_parser = 0;
573
574 #if HAVE_CHROOT
575   if (!jail_spec.is_empty ())
576     do_chroot_jail ();
577 #endif
578
579   SCM result = scm_call_1 (ly_lily_module_constant ("lilypond-main"), files);
580   (void) result;
581
582   /* Unreachable.  */
583   exit (0);
584 }
585
586 static void
587 setup_localisation ()
588 {
589 #if HAVE_GETTEXT
590   /* Enable locales */
591   setlocale (LC_ALL, "");
592
593   /* FIXME: check if this is still true.
594      Disable localisation of float values.  This breaks TeX output.  */
595   setlocale (LC_NUMERIC, "C");
596
597   String localedir = LOCALEDIR;
598   if (char const *env = getenv ("LILYPOND_LOCALEDIR"))
599     localedir = env;
600   
601   bindtextdomain ("lilypond", localedir.to_str0 ());
602   textdomain ("lilypond");
603 #endif
604 }
605
606 static void
607 add_output_format (String format)
608 {
609   if (output_format_global != "")
610     output_format_global += ",";
611   output_format_global += format;
612 }
613
614 static void
615 parse_argv (int argc, char **argv)
616 {
617   bool show_help = false;
618   option_parser = new Getopt_long (argc, argv, options_static);
619   while (Long_option_init const *opt = (*option_parser) ())
620     {
621       switch (opt->shortname_char_)
622         {
623         case 0:
624           if (String (opt->longname_str0_) == "dvi"
625               || String (opt->longname_str0_) == "pdf"
626               || String (opt->longname_str0_) == "png"
627               || String (opt->longname_str0_) == "ps"
628               || String (opt->longname_str0_) == "tex")
629             add_output_format (opt->longname_str0_);
630           else if (String (opt->longname_str0_) == "preview")
631             make_preview = true;
632           else if (String (opt->longname_str0_) == "no-pages")
633             make_print = false;
634           break;
635
636         case 'd':
637           {
638             String arg (option_parser->optional_argument_str0_);
639             int eq = arg.index ('=');
640
641             String key = arg;
642             String val = "#t";
643             
644             if (eq >= 0)
645               {
646                 key = arg.left_string (eq);
647                 val = arg.right_string (arg.length () - eq - 1);
648               }
649
650             init_scheme_variables
651               += "(cons \'" + key  + "  " + val + ")\n";
652           }
653           break;
654           
655         case 'v':
656           notice ();
657           exit (0);
658           break;
659         case 'o':
660           {
661             String s = option_parser->optional_argument_str0_;
662             File_name file_name (s);
663             output_name_global = file_name.to_string ();
664           }
665           break;
666         case 'j':
667           jail_spec = option_parser->optional_argument_str0_;
668           break;
669         case 'e':
670           init_scheme_code_string += option_parser->optional_argument_str0_;
671           break;
672         case 'w':
673           warranty ();
674           exit (0);
675           break;
676           
677         case 'b':
678           output_backend_global = option_parser->optional_argument_str0_;
679           break;
680
681         case 'f':
682           output_format_global = option_parser->optional_argument_str0_;
683           break;
684           
685         case 'H':
686           dump_header_fieldnames_global
687             .push (option_parser->optional_argument_str0_);
688           break;
689         case 'I':
690           global_path.append (option_parser->optional_argument_str0_);
691           break;
692         case 'i':
693           init_name_global = option_parser->optional_argument_str0_;
694           break;
695         case 'h':
696           show_help = true;
697           break;
698         case 'V':
699           be_verbose_global = true;
700           break;
701         case 's':
702           be_safe_global = true;
703           break;
704         case 'p':
705           make_preview = true;
706           break;
707         default:
708           programming_error (to_string ("unhandled short option: %c",
709                                         opt->shortname_char_));
710           assert (false);
711           break;
712         }
713     }
714
715   if (show_help)
716     {
717       identify (stdout);
718       ly_usage ();
719       if (be_verbose_global)
720         dir_info (stdout);
721       exit (0);
722     }
723 }
724
725 int
726 main (int argc, char **argv)
727 {
728   setup_localisation ();
729   setup_paths (argv[0]);
730   parse_argv (argc, argv);
731   if (isatty (STDIN_FILENO))
732     identify (stderr);
733
734   scm_boot_guile (argc, argv, main_with_guile, 0);
735
736   /* Only reachable if GUILE exits.  That is an error.  */
737   return 1;
738 }