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