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