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