]> git.donarmstrong.com Git - lilypond.git/blob - lily/main.cc
dfc986ceb444d80362198ea4065322872405828e
[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 <pwd.h>
17 #include <grp.h>
18 #include <sys/types.h>
19 #include <sys/stat.h>
20
21 #include "config.hh"
22
23 #if HAVE_GETTEXT
24 #include <libintl.h>
25 #endif
26
27 #include "all-font-metrics.hh"
28 #include "file-name.hh"
29 #include "freetype.hh"
30 #include "getopt-long.hh"
31 #include "global-ctor.hh"
32 #include "lily-guile.hh"
33 #include "lily-version.hh"
34 #include "misc.hh"
35 #include "output-def.hh"
36 #include "string-convert.hh"
37 #include "version.hh"
38 #include "warn.hh"
39
40 /*
41  * Global options that can be overridden through command line.
42  */
43
44 /* Names of header fields to be dumped to a separate file. */
45 Array<String> dump_header_fieldnames_global;
46
47 /* Name of initialisation file. */
48 String init_name_global;
49
50 /* Selected output backend
51    One of (gnome, ps [default], scm, svg, tex, texstr)") */
52 String output_backend_global = "ps";
53 /* Output formats to generate.  */
54 String output_format_global = "pdf";
55
56 bool is_pango_format_global;
57 bool is_TeX_format_global;
58
59 /* Current output name. */
60 String output_name_global;
61
62 /* Run in safe mode? */
63 bool be_safe_global = false;
64
65 /* Provide URI links to the original file */
66 bool point_and_click_global = true;
67
68 /* Verbose progress indication? */
69 bool be_verbose_global = false;
70
71 /* Scheme code to execute before parsing, after .scm init.
72    This is where -e arguments are appended to.  */
73 String init_scheme_code_string = "(begin #t ";
74
75 /* Generate preview of first system.  */
76 bool make_preview = false;
77
78 /* Generate printed output.  */
79 bool make_print = true;
80
81 /*
82  * Miscellaneous global stuff.
83  */
84 File_path global_path;
85
86 /*
87  * File globals.
88  */
89
90 static char const *AUTHORS
91 = "  Han-Wen Nienhuys <hanwen@cs.uu.nl>\n"
92   "  Jan Nieuwenhuizen <janneke@gnu.org>\n";
93
94 static char const *PROGRAM_NAME = "lilypond";
95 static char const *PROGRAM_URL = "http://lilypond.org";
96
97 static char const *NOTICE
98 = _i ("This program is free software.  It is covered by the GNU General Public\n"
99       "License and you are welcome to change it and/or distribute copies of it\n"
100       "under certain conditions.  Invoke as `%s --warranty' for more\n"
101       "information.\n");
102
103 static char const *WARRANTY
104 = _i ("    This program is free software; you can redistribute it and/or\n"
105       "modify it under the terms of the GNU General Public License version 2\n"
106       "as published by the Free Software Foundation.\n"
107       "\n"
108       "    This program is distributed in the hope that it will be useful,\n"
109       "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
110       "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
111       "General Public License for more details.\n"
112       "\n"
113       "    You should have received a copy (refer to the file COPYING) of the\n"
114       "GNU General Public License along with this program; if not, write to\n"
115       "the Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n"
116       "Boston, MA 02111-1307, USA.\n");
117
118 /* Where the init files live.  Typically:
119    LILYPOND_DATADIR = /usr/share/lilypond
120 */
121 String prefix_directory;
122
123 /* The jail specification: USER,GROUP,JAIL,DIR. */
124 String jail_spec;
125
126 /*  The option parser */
127 static Getopt_long *option_parser = 0;
128
129 /* Internationalisation kludge in two steps:
130  * use _i () to get entry in POT file
131  * call gettext () explicitely for actual "translation"  */
132
133 static Long_option_init options_static[]
134 = {
135   {_i ("BACK"), "backend", 'b', _i ("use backend BACK (gnome, ps [default],\n                                       scm, svg, tex, texstr)")},
136
137   {_i ("SYM=VAL"), "define-default", 'd',
138    _i ("define a default Scheme setting.")},
139
140   {_i ("EXPR"), "evaluate", 'e', _i ("set scheme option, for help use\n                                       -e '(ly:option-usage)'")},
141   /* Bug in option parser: --output =foe is taken as an abbreviation
142      for --output-format.  */
143   {_i ("FORMATs"), "formats", 'f', _i ("dump FORMAT,...  Also as separate options:")},
144   {0, "dvi", 0, _i ("generate DVI (tex backend only)")},
145   {0, "pdf", 0, _i ("generate PDF (default)")},
146   {0, "png", 0, _i ("generate PNG")},
147   {0, "ps", 0, _i ("generate PostScript")},
148   {0, "tex", 0, _i ("generate TeX (tex backend only)")},
149   {0, "help", 'h',  _i ("print this help")},
150   {_i ("FIELD"), "header", 'H',  _i ("write header field to BASENAME.FIELD")},
151   {_i ("DIR"), "include", 'I',  _i ("add DIR to search path")},
152   {_i ("FILE"), "init", 'i',  _i ("use FILE as init file")},
153   {_i ("FILE"), "output", 'o',  _i ("write output to FILE (suffix will be added)")},
154   {_i ("USER,GROUP,JAIL,DIR"), "jail", 'j', _i ("chroot to JAIL, become USER:GROUP\n                                       and cd into DIR")},
155   {0, "no-print", 0, _i ("do not generate printed output")},
156   {0, "preview", 'p',  _i ("generate a preview of the first system")},
157   {0, "safe-mode", 's',  _i ("run in safe mode")},
158   {0, "version", 'v',  _i ("print version number")},
159   {0, "verbose", 'V', _i ("be verbose")},
160   {0, "warranty", 'w',  _i ("show warranty and copyright")},
161   {0, 0, 0, 0}
162 };
163
164 #define LILYPOND_DATADIR PACKAGE_DATADIR "/" TOPLEVEL_VERSION
165
166 static void
167 dir_info (FILE *out)
168 {
169   fputs ("\n", out);
170   fprintf (out, "LILYPOND_DATADIR=\"%s\"\n", LILYPOND_DATADIR);
171   if (char const *env = getenv ("LILYPONDPREFIX"))
172     fprintf (out, "LILYPONDPREFIX=\"%s\"\n", env);
173   fprintf (out, "LOCALEDIR=\"%s\"\n", LOCALEDIR);
174
175   fprintf (out, "\nEffective prefix: \"%s\"\n", prefix_directory.to_str0 ());
176 }
177
178 static void
179 copyright ()
180 {
181   printf (_f ("Copyright (c) %s by\n%s  and others.",
182               "1996--2005",
183               AUTHORS).to_str0 ());
184   printf ("\n");
185 }
186
187 static void
188 identify (FILE *out)
189 {
190   fputs (gnu_lilypond_version_string ().to_str0 (), out);
191   fputs ("\n", out);
192 }
193
194 static void
195 notice ()
196 {
197   identify (stdout);
198   puts (_f (NOTICE, PROGRAM_NAME).to_str0 ());
199   printf ("\n");
200   copyright ();
201 }
202
203 static void
204 usage ()
205 {
206   /* No version number or newline here.  It confuses help2man.  */
207   printf (_f ("Usage: %s [OPTION]... FILE...", PROGRAM_NAME).to_str0 ());
208   printf ("\n\n");
209   printf (_ ("Typeset music and/or produce MIDI from FILE.").to_str0 ());
210   printf ("\n\n");
211   printf (_ ("LilyPond produces beautiful music notation.").to_str0 ());
212   printf ("\n");
213   printf (_f ("For more information, see %s", PROGRAM_URL).to_str0 ());
214   printf ("\n\n");
215   printf (_ ("Options:").to_str0 ());
216   printf ("\n");
217   printf (Long_option_init::table_string (options_static).to_str0 ());
218   printf ("\n");
219   printf (_f ("Report bugs to %s.", "bug-lilypond@gnu.org").to_str0 ());
220   printf ("\n");
221   printf ("\n");
222 }
223
224 static void
225 warranty ()
226 {
227   identify (stdout);
228   printf ("\n");
229   copyright ();
230   printf ("\n");
231   printf (_ (WARRANTY).to_str0 ());
232 }
233
234 static void
235 setup_paths ()
236 {
237   prefix_directory = LILYPOND_DATADIR;
238   if (char const *env = getenv ("LILYPONDPREFIX"))
239     prefix_directory = env;
240
241   global_path.append ("");
242
243   /* Adding mf/out make lilypond unchanged source directory, when setting
244      LILYPONDPREFIX to lilypond-x.y.z */
245   char *suffixes[] = {"ly", "ps", "scm", 0 };
246
247   Array<String> dirs;
248   for (char **s = suffixes; *s; s++)
249     {
250       String path = prefix_directory + to_string ('/') + String (*s);
251       dirs.push (path);
252     }
253
254   /*
255     ugh. C&P font-config.cc
256   */
257   struct stat statbuf; 
258   String builddir = prefix_directory + "/mf/out/";
259   if (stat (builddir.to_str0 (), &statbuf) == 0)
260     {
261       dirs.push (builddir.to_str0 ());
262     }
263   else
264     {
265       dirs.push (prefix_directory + "/fonts/otf/");
266       dirs.push (prefix_directory + "/fonts/type1/");
267       dirs.push (prefix_directory + "/fonts/cff/");
268       dirs.push (prefix_directory + "/fonts/svg/");
269       dirs.push (prefix_directory + "/fonts/cff/");
270     }
271
272   for (int i = 0; i < dirs.size (); i++)
273     global_path.prepend (dirs[i]);  
274 }
275   
276 static void
277 prepend_load_path (String dir)
278 {
279   String s = "(set! %load-path (cons \"" + dir + "\" %load-path))";
280   scm_c_eval_string (s.to_str0 ());
281 }
282
283 void init_global_tweak_registry ();
284 void init_fontconfig ();
285
286 static void
287 do_chroot_jail ()
288 {
289   /* Now we chroot, setuid/setgrp and chdir.  If something goes wrong,
290      we exit (this is a security-sensitive area).  First we split
291      jail_spec into its components, then we retrieve the user/group id
292      (necessarily *before* chroot'ing) and finally we perform the
293      actual actions.  */
294
295   enum Jail
296     {
297       USER_NAME, GROUP_NAME, JAIL, DIR, JAIL_MAX
298     };
299
300   Array<String> components = String_convert::split (jail_spec, ',');
301   if (components.size () != JAIL_MAX)
302     {
303       error (_f ("expected %d arguments with jail, found: %d", JAIL_MAX,
304                  components.size ()));
305       exit (2);
306     }
307
308   /* Hmm.  */
309   errno = 0;
310
311   int uid;
312   if (passwd * passwd = getpwnam (components[USER_NAME].to_str0 ()))
313     uid = passwd->pw_uid;
314   else
315     {
316       if (errno == 0)
317         error (_f ("no such user: %s", components[USER_NAME]));
318       else
319         error (_f ("can't get user id from user name: %s: %s",
320                    components[USER_NAME],
321                    strerror (errno)));
322       exit (3);
323     }
324
325   /* Hmm.  */
326   errno = 0;
327
328   int gid;
329   if (group * group = getgrnam (components[GROUP_NAME].to_str0 ()))
330     gid = group->gr_gid;
331   else
332     {
333       if (errno == 0)
334         error (_f ("no such group: %s", components[GROUP_NAME]));
335       else
336         error (_f ("can't get group id from group name: %s: %s",
337                    components[GROUP_NAME],
338                    strerror (errno)));
339       exit (3);
340     }
341
342   if (chroot (components[JAIL].to_str0 ()))
343     {
344       error (_f ("can't chroot to: %s: %s", components[JAIL],
345                  strerror (errno)));
346       exit (3);
347     }
348
349   if (setgid (gid))
350     {
351       error (_f ("can't change group id to: %d: %s", gid, strerror (errno)));
352       exit (3);
353     }
354
355   if (setuid (uid))
356     {
357       error (_f ("can't change user id to: %d: %s", uid, strerror (errno)));
358       exit (3);
359     }
360
361   if (chdir (components[DIR].to_str0 ()))
362     {
363       error (_f ("can't change working directory to: %s: %s", components[DIR],
364                  strerror (errno)));
365       exit (3);
366     }
367 }
368
369 void test_pango ();
370
371 static void
372 main_with_guile (void *, int, char **)
373 {
374   /* Engravers use lily.scm contents, need to make Guile find it.
375      Prepend onto GUILE %load-path, very ugh. */
376
377   prepend_load_path (prefix_directory);
378   prepend_load_path (prefix_directory + "/scm");
379
380   if (be_verbose_global)
381     dir_info (stderr);
382   is_TeX_format_global = (output_backend_global == "tex"
383                           || output_backend_global == "texstr");
384
385   is_pango_format_global = !is_TeX_format_global;
386
387   ly_c_init_guile ();
388   call_constructors ();
389   init_global_tweak_registry ();
390   init_fontconfig ();
391
392   init_freetype ();
393
394   all_fonts_global = new All_font_metrics (global_path.to_string ());
395
396   init_scheme_code_string += ")";
397   scm_c_eval_string ((char *) init_scheme_code_string.to_str0 ());
398
399   /* We accept multiple independent music files on the command line to
400      reduce compile time when processing lots of small files.
401      Starting the GUILE engine is very time consuming.  */
402
403   SCM files = SCM_EOL;
404   SCM *tail = &files;
405   while (char const *arg = option_parser->get_next_arg ())
406     {
407       *tail = scm_cons (scm_makfrom0str (arg), SCM_EOL);
408       tail = SCM_CDRLOC (*tail);
409     }
410   delete option_parser;
411   option_parser = 0;
412
413   if (files == SCM_EOL)
414     {
415       /* No FILE arguments is now a usage error to help newbies.  If you
416          want a filter, you're not a newbie and should know to use file
417          argument `-'.  */
418       usage ();
419       exit (2);
420     }
421
422   if (! jail_spec.is_empty ())
423     do_chroot_jail ();
424
425   SCM result = scm_call_1 (ly_lily_module_constant ("lilypond-main"), files);
426   (void) result;
427
428   /* Unreachable.  */
429   exit (0);
430 }
431
432 static void
433 setup_localisation ()
434 {
435 #if HAVE_GETTEXT
436   /* Enable locales */
437   setlocale (LC_ALL, "");
438
439   /* FIXME: check if this is still true.
440      Disable localisation of float values.  This breaks TeX output.  */
441   setlocale (LC_NUMERIC, "C");
442
443   String name (PACKAGE);
444   name.to_lower ();
445   bindtextdomain (name.to_str0 (), LOCALEDIR);
446   textdomain (name.to_str0 ());
447 #endif
448 }
449
450 static void
451 add_output_format (String format)
452 {
453   if (output_format_global != "")
454     output_format_global += ",";
455   output_format_global += format;
456 }
457
458 static void
459 parse_argv (int argc, char **argv)
460 {
461   bool show_help = false;
462   option_parser = new Getopt_long (argc, argv, options_static);
463   while (Long_option_init const *opt = (*option_parser) ())
464     {
465       switch (opt->shortname_char_)
466         {
467         case 0:
468           if (String (opt->longname_str0_) == "dvi"
469               || String (opt->longname_str0_) == "pdf"
470               || String (opt->longname_str0_) == "png"
471               || String (opt->longname_str0_) == "ps"
472               || String (opt->longname_str0_) == "tex")
473             add_output_format (opt->longname_str0_);
474           else if (String (opt->longname_str0_) == "preview")
475             make_preview = true;
476           else if (String (opt->longname_str0_) == "no-pages")
477             make_print = false;
478           break;
479
480         case 'd':
481           
482           break;
483           
484         case 'v':
485           notice ();
486           exit (0);
487           break;
488         case 'o':
489           {
490             String s = option_parser->optional_argument_str0_;
491             File_name file_name (s);
492             output_name_global = file_name.to_string ();
493           }
494           break;
495         case 'j':
496           jail_spec = option_parser->optional_argument_str0_;
497           break;
498         case 'e':
499           init_scheme_code_string += option_parser->optional_argument_str0_;
500           break;
501         case 'w':
502           warranty ();
503           exit (0);
504           break;
505           
506         case 'b':
507           output_backend_global = option_parser->optional_argument_str0_;
508           break;
509
510         case 'f':
511           output_format_global = option_parser->optional_argument_str0_;
512           break;
513           
514         case 'H':
515           dump_header_fieldnames_global
516             .push (option_parser->optional_argument_str0_);
517           break;
518         case 'I':
519           global_path.append (option_parser->optional_argument_str0_);
520           break;
521         case 'i':
522           init_name_global = option_parser->optional_argument_str0_;
523           break;
524         case 'h':
525           show_help = true;
526           break;
527         case 'V':
528           be_verbose_global = true;
529           break;
530         case 's':
531           be_safe_global = true;
532           break;
533         case 'p':
534           make_preview = true;
535           break;
536         default:
537           programming_error (to_string ("unhandled short option: %c",
538                                         opt->shortname_char_));
539           assert (false);
540           break;
541         }
542     }
543
544   if (show_help)
545     {
546       identify (stdout);
547       usage ();
548       if (be_verbose_global)
549         dir_info (stdout);
550       exit (0);
551     }
552 }
553
554 int
555 main (int argc, char **argv)
556 {
557   setup_localisation ();
558   setup_paths ();
559   parse_argv (argc, argv);
560   identify (stderr);
561
562   scm_boot_guile (argc, argv, main_with_guile, 0);
563
564   /* Unreachable */
565   return 0;
566 }