]> git.donarmstrong.com Git - lilypond.git/blob - lily/main.cc
*** empty log message ***
[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],\n                                       scm, svg, tex, texstr)")},
141
142   {_i ("SYM=VAL"), "define-default", 'd',
143    _i ("define a default Scheme setting.")},
144
145   {_i ("EXPR"), "evaluate", 'e', _i ("set scheme option, for help use\n                                       -e '(ly:option-usage)'")},
146   /* Bug in option parser: --output =foe is taken as an abbreviation
147      for --output-format.  */
148   {_i ("FORMATs"), "formats", 'f', _i ("dump FORMAT,...  Also as separate options:")},
149   {0, "dvi", 0, _i ("generate DVI (tex backend only)")},
150   {0, "pdf", 0, _i ("generate PDF (default)")},
151   {0, "png", 0, _i ("generate PNG")},
152   {0, "ps", 0, _i ("generate PostScript")},
153   {0, "tex", 0, _i ("generate TeX (tex backend only)")},
154   {0, "help", 'h',  _i ("print this help")},
155   {_i ("FIELD"), "header", 'H',  _i ("dump a header field to file BASENAME.FIELD")},
156   {_i ("DIR"), "include", 'I',  _i ("add DIR to search path")},
157   {_i ("FILE"), "init", 'i',  _i ("use FILE as init file")},
158   {_i ("FILE"), "output", 'o',  _i ("write output to FILE (suffix will be added)")},
159 #if HAVE_CHROOT
160   {_i ("USER,GROUP,JAIL,DIR"), "jail", 'j', _i ("chroot to JAIL, become USER:GROUP\n                                       and cd into DIR")},
161 #endif 
162   {0, "no-print", 0, _i ("do not generate printed output")},
163   {0, "preview", 'p',  _i ("generate a preview of the first system")},
164   {0, "safe-mode", 's',  _i ("run in safe mode")},
165   {0, "version", 'v',  _i ("print version number")},
166   {0, "verbose", 'V', _i ("be verbose")},
167   {0, "warranty", 'w',  _i ("show warranty and copyright")},
168   {0, 0, 0, 0}
169 };
170
171 #define LILYPOND_DATADIR PACKAGE_DATADIR "/" TOPLEVEL_VERSION
172
173 static void
174 env_var_info (FILE *out, char const* key)
175 {
176   if (char const *value = getenv (key))
177     fprintf (out, "%s=\"%s\"\n", key, value);
178 }
179
180 static void
181 dir_info (FILE *out)
182 {
183   fputs ("\n", out);
184   fprintf (out, "LILYPOND_DATADIR=\"%s\"\n", LILYPOND_DATADIR);
185   env_var_info (out, "LILYPONDPREFIX");
186   fprintf (out, "LOCALEDIR=\"%s\"\n", LOCALEDIR);
187
188   fprintf (out, "\nEffective prefix: \"%s\"\n", prefix_directory.to_str0 ());
189
190 #if ARGV0_RELOCATION
191   env_var_info (out, "FONTCONFIG_FILE");
192   env_var_info (out, "FONTCONFIG_PATH");
193   env_var_info (out, "GS_FONTPATH");
194   env_var_info (out, "GS_LIB");
195   env_var_info (out, "GUILE_LOAD_PATH");
196   env_var_info (out, "PANGO_RC_FILE");
197   env_var_info (out, "PATH");
198 #endif  
199 }
200
201 static void
202 copyright ()
203 {
204   printf (_f ("Copyright (c) %s by\n%s  and others.",
205               "1996--2005",
206               AUTHORS).to_str0 ());
207   printf ("\n");
208 }
209
210 static void
211 identify (FILE *out)
212 {
213   fputs (gnu_lilypond_version_string ().to_str0 (), out);
214   fputs ("\n", out);
215 }
216
217 static void
218 notice ()
219 {
220   identify (stdout);
221   puts (_f (NOTICE, PROGRAM_NAME).to_str0 ());
222   printf ("\n");
223   copyright ();
224 }
225
226 LY_DEFINE (ly_usage, "ly:usage",
227            0, 0, 0, (),
228            "Print usage message.")
229 {
230   /* No version number or newline here.  It confuses help2man.  */
231   printf (_f ("Usage: %s [OPTION]... FILE...", PROGRAM_NAME).to_str0 ());
232   printf ("\n\n");
233   printf (_ ("Typeset music and/or produce MIDI from FILE.").to_str0 ());
234   printf ("\n\n");
235   printf (_ ("LilyPond produces beautiful music notation.").to_str0 ());
236   printf ("\n");
237   printf (_f ("For more information, see %s", PROGRAM_URL).to_str0 ());
238   printf ("\n\n");
239   printf (_ ("Options:").to_str0 ());
240   printf ("\n");
241   printf (Long_option_init::table_string (options_static).to_str0 ());
242   printf ("\n");
243   printf (_f ("Report bugs to %s.", "bug-lilypond@gnu.org").to_str0 ());
244   printf ("\n");
245   printf ("\n");
246   return SCM_UNSPECIFIED;
247 }
248
249 static void
250 warranty ()
251 {
252   identify (stdout);
253   printf ("\n");
254   copyright ();
255   printf ("\n");
256   printf (_ (WARRANTY).to_str0 ());
257 }
258
259 #if ARGV0_RELOCATION
260 static int
261 sane_putenv (char const* key, String value, bool overwrite = true)
262 {
263   if (overwrite || !getenv (key))
264     {
265       String combine = String (key) + "=" + value;
266       char *s = strdup (combine.to_str0 ());
267       return putenv (s);
268     }
269   return -1;
270 }
271
272 static int
273 prepend_env_path (char const *key, String value)
274 {
275   if (char const* cur = getenv (key))
276     value += to_string (PATHSEP) + cur;
277   return sane_putenv (key, value.to_str0 ());
278 }
279
280 String
281 dir_name (String const file_name)
282 {
283   String s = file_name;
284   s.substitute ('\\', '/');
285   s = s.left_string (s.index_last ('/'));
286   return s;
287 }
288 #endif
289
290 static void
291 setup_paths (char const* argv0)
292 {
293   prefix_directory = LILYPOND_DATADIR;
294
295 #if ARGV0_RELOCATION
296   String bindir = dir_name (argv0);
297   String argv0_prefix = dir_name (bindir);
298   if (argv0_prefix != dir_name (dir_name (dir_name (prefix_directory))))
299     {
300       warning (_f ("argv0 relocation: argv0=%s, prefix=%s", argv0,
301                    prefix_directory));
302       String datadir = argv0_prefix + "/share";
303       String libdir = argv0_prefix + "/lib";
304       String sysconfdir = argv0_prefix + "/etc";
305       prefix_directory = datadir + "/lilypond/" TOPLEVEL_VERSION;
306
307       sane_putenv ("FONTCONFIG_FILE", sysconfdir + "/fonts/fonts.conf", false);
308       prepend_env_path ("GUILE_LOAD_PATH", datadir
309                         + to_string ("/guile/%d.%d",
310                                      SCM_MAJOR_VERSION, SCM_MINOR_VERSION));
311 #ifdef __MINGW32__
312       /* FIXME: this is broken and must go, but updating the environment
313          takes a relogin/reboot.  Can gs be wrapped?  */
314       prepend_env_path ("GS_FONTPATH", "c:/windows/fonts");
315 #endif
316       prepend_env_path ("GS_FONTPATH", datadir + "/gs/fonts");
317       prepend_env_path ("GS_LIB", datadir + "/gs/Resource");
318       prepend_env_path ("GS_LIB", datadir + "/gs/lib");
319       sane_putenv ("PANGO_RC_FILE", sysconfdir + "/pango/pango.modules", false);
320       prepend_env_path ("PATH", bindir);
321     }
322 #endif /* ARGV0_RELOCATION */
323     
324   if (char const *env = getenv ("LILYPONDPREFIX"))
325     prefix_directory = env;
326
327   global_path.append ("");
328
329   /* Adding mf/out make lilypond unchanged source directory, when setting
330      LILYPONDPREFIX to lilypond-x.y.z */
331   char *suffixes[] = {"ly", "ps", "scm", 0 };
332
333   Array<String> dirs;
334   for (char **s = suffixes; *s; s++)
335     {
336       String path = prefix_directory + to_string ('/') + String (*s);
337       dirs.push (path);
338     }
339
340   /*
341     ugh. C&P font-config.cc
342   */
343   struct stat statbuf; 
344   String builddir = prefix_directory + "/mf/out/";
345   if (stat (builddir.to_str0 (), &statbuf) == 0)
346     {
347       dirs.push (builddir.to_str0 ());
348     }
349   else
350     {
351       dirs.push (prefix_directory + "/fonts/otf/");
352       dirs.push (prefix_directory + "/fonts/type1/");
353       dirs.push (prefix_directory + "/fonts/cff/");
354       dirs.push (prefix_directory + "/fonts/svg/");
355       dirs.push (prefix_directory + "/fonts/cff/");
356     }
357
358   for (int i = 0; i < dirs.size (); i++)
359     global_path.prepend (dirs[i]);  
360 }
361   
362 static void
363 prepend_load_path (String dir)
364 {
365   String s = "(set! %load-path (cons \"" + dir + "\" %load-path))";
366   scm_c_eval_string (s.to_str0 ());
367 }
368
369 void init_global_tweak_registry ();
370 void init_fontconfig ();
371
372 #if HAVE_CHROOT
373 static void
374 do_chroot_jail ()
375 {
376   /* Now we chroot, setuid/setgrp and chdir.  If something goes wrong,
377      we exit (this is a security-sensitive area).  First we split
378      jail_spec into its components, then we retrieve the user/group id
379      (necessarily *before* chroot'ing) and finally we perform the
380      actual actions.  */
381
382   enum Jail
383     {
384       USER_NAME, GROUP_NAME, JAIL, DIR, JAIL_MAX
385     };
386
387   Array<String> components = String_convert::split (jail_spec, ',');
388   if (components.size () != JAIL_MAX)
389     {
390       error (_f ("expected %d arguments with jail, found: %d", JAIL_MAX,
391                  components.size ()));
392       exit (2);
393     }
394
395   /* Hmm.  */
396   errno = 0;
397
398   int uid;
399   if (passwd * passwd = getpwnam (components[USER_NAME].to_str0 ()))
400     uid = passwd->pw_uid;
401   else
402     {
403       if (errno == 0)
404         error (_f ("no such user: %s", components[USER_NAME]));
405       else
406         error (_f ("can't get user id from user name: %s: %s",
407                    components[USER_NAME],
408                    strerror (errno)));
409       exit (3);
410     }
411
412   /* Hmm.  */
413   errno = 0;
414
415   int gid;
416   if (group * group = getgrnam (components[GROUP_NAME].to_str0 ()))
417     gid = group->gr_gid;
418   else
419     {
420       if (errno == 0)
421         error (_f ("no such group: %s", components[GROUP_NAME]));
422       else
423         error (_f ("can't get group id from group name: %s: %s",
424                    components[GROUP_NAME],
425                    strerror (errno)));
426       exit (3);
427     }
428
429   if (chroot (components[JAIL].to_str0 ()))
430     {
431       error (_f ("can't chroot to: %s: %s", components[JAIL],
432                  strerror (errno)));
433       exit (3);
434     }
435
436   if (setgid (gid))
437     {
438       error (_f ("can't change group id to: %d: %s", gid, strerror (errno)));
439       exit (3);
440     }
441
442   if (setuid (uid))
443     {
444       error (_f ("can't change user id to: %d: %s", uid, strerror (errno)));
445       exit (3);
446     }
447
448   if (chdir (components[DIR].to_str0 ()))
449     {
450       error (_f ("can't change working directory to: %s: %s", components[DIR],
451                  strerror (errno)));
452       exit (3);
453     }
454 }
455 #endif
456
457
458
459 static void
460 main_with_guile (void *, int, char **)
461 {
462   /* Engravers use lily.scm contents, need to make Guile find it.
463      Prepend onto GUILE %load-path, very ugh. */
464
465   prepend_load_path (prefix_directory);
466   prepend_load_path (prefix_directory + "/scm");
467
468   if (be_verbose_global)
469     dir_info (stderr);
470   is_TeX_format_global = (output_backend_global == "tex"
471                           || output_backend_global == "texstr");
472
473   is_pango_format_global = !is_TeX_format_global;
474
475   ly_c_init_guile ();
476   call_constructors ();
477   init_global_tweak_registry ();
478   init_fontconfig ();
479
480   init_freetype ();
481
482   all_fonts_global = new All_font_metrics (global_path.to_string ());
483
484   
485   if (!init_scheme_variables.is_empty ()
486       || !init_scheme_code_string.is_empty ())
487     {
488       init_scheme_variables = "(ly:set-option 'command-line-settings (list "
489         + init_scheme_variables + "))";
490       
491       init_scheme_code_string
492         += "(begin #t "
493         + init_scheme_variables
494         + init_scheme_code_string
495         + ")";
496
497       char const *str0 = init_scheme_code_string.to_str0 ();
498       
499       if (be_verbose_global)
500         progress_indication (_f("Evaluating %s", str0));
501       scm_c_eval_string ((char *) str0);
502     }
503
504   
505   /* We accept multiple independent music files on the command line to
506      reduce compile time when processing lots of small files.
507      Starting the GUILE engine is very time consuming.  */
508
509   SCM files = SCM_EOL;
510   SCM *tail = &files;
511   while (char const *arg = option_parser->get_next_arg ())
512     {
513       *tail = scm_cons (scm_makfrom0str (arg), SCM_EOL);
514       tail = SCM_CDRLOC (*tail);
515     }
516   delete option_parser;
517   option_parser = 0;
518
519 #if HAVE_CHROOT
520   if (!jail_spec.is_empty ())
521     do_chroot_jail ();
522 #endif
523
524   SCM result = scm_call_1 (ly_lily_module_constant ("lilypond-main"), files);
525   (void) result;
526
527   /* Unreachable.  */
528   exit (0);
529 }
530
531 static void
532 setup_localisation ()
533 {
534 #if HAVE_GETTEXT
535   /* Enable locales */
536   setlocale (LC_ALL, "");
537
538   /* FIXME: check if this is still true.
539      Disable localisation of float values.  This breaks TeX output.  */
540   setlocale (LC_NUMERIC, "C");
541
542   String name (PACKAGE);
543   name.to_lower ();
544   bindtextdomain (name.to_str0 (), LOCALEDIR);
545   textdomain (name.to_str0 ());
546 #endif
547 }
548
549 static void
550 add_output_format (String format)
551 {
552   if (output_format_global != "")
553     output_format_global += ",";
554   output_format_global += format;
555 }
556
557 static void
558 parse_argv (int argc, char **argv)
559 {
560   bool show_help = false;
561   option_parser = new Getopt_long (argc, argv, options_static);
562   while (Long_option_init const *opt = (*option_parser) ())
563     {
564       switch (opt->shortname_char_)
565         {
566         case 0:
567           if (String (opt->longname_str0_) == "dvi"
568               || String (opt->longname_str0_) == "pdf"
569               || String (opt->longname_str0_) == "png"
570               || String (opt->longname_str0_) == "ps"
571               || String (opt->longname_str0_) == "tex")
572             add_output_format (opt->longname_str0_);
573           else if (String (opt->longname_str0_) == "preview")
574             make_preview = true;
575           else if (String (opt->longname_str0_) == "no-pages")
576             make_print = false;
577           break;
578
579         case 'd':
580           {
581             String arg (option_parser->optional_argument_str0_);
582             int eq = arg.index ('=');
583
584             String key = arg;
585             String val = "#t";
586             
587             if (eq >= 0)
588               {
589                 key = arg.left_string (eq);
590                 val = arg.right_string (arg.length () - eq - 1);
591               }
592
593             init_scheme_variables
594               += "(cons \'" + key  + "  " + val + ")\n";
595           }
596           break;
597           
598         case 'v':
599           notice ();
600           exit (0);
601           break;
602         case 'o':
603           {
604             String s = option_parser->optional_argument_str0_;
605             File_name file_name (s);
606             output_name_global = file_name.to_string ();
607           }
608           break;
609         case 'j':
610           jail_spec = option_parser->optional_argument_str0_;
611           break;
612         case 'e':
613           init_scheme_code_string += option_parser->optional_argument_str0_;
614           break;
615         case 'w':
616           warranty ();
617           exit (0);
618           break;
619           
620         case 'b':
621           output_backend_global = option_parser->optional_argument_str0_;
622           break;
623
624         case 'f':
625           output_format_global = option_parser->optional_argument_str0_;
626           break;
627           
628         case 'H':
629           dump_header_fieldnames_global
630             .push (option_parser->optional_argument_str0_);
631           break;
632         case 'I':
633           global_path.append (option_parser->optional_argument_str0_);
634           break;
635         case 'i':
636           init_name_global = option_parser->optional_argument_str0_;
637           break;
638         case 'h':
639           show_help = true;
640           break;
641         case 'V':
642           be_verbose_global = true;
643           break;
644         case 's':
645           be_safe_global = true;
646           break;
647         case 'p':
648           make_preview = true;
649           break;
650         default:
651           programming_error (to_string ("unhandled short option: %c",
652                                         opt->shortname_char_));
653           assert (false);
654           break;
655         }
656     }
657
658   if (show_help)
659     {
660       identify (stdout);
661       ly_usage ();
662       if (be_verbose_global)
663         dir_info (stdout);
664       exit (0);
665     }
666 }
667
668 #ifdef __MINGW32__
669 /* If no TTY and not using safe, assume running from GUI.
670    For mingw, the test must be inverted.  */
671 #  define isatty(x) (!isatty (x))
672 #endif
673
674 int
675 main (int argc, char **argv)
676 {
677   setup_localisation ();
678   setup_paths (argv[0]);
679   parse_argv (argc, argv);
680   if (isatty (STDIN_FILENO))
681     identify (stderr);
682
683   scm_boot_guile (argc, argv, main_with_guile, 0);
684
685   /* Only reachable if GUILE exits.  That is an error.  */
686   return 1;
687 }