]> 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 <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   {_i ("EXPR"), "evaluate", 'e', _i ("set scheme option, for help use\n                                       -e '(ly:option-usage)'")},
137   /* Bug in option parser: --output =foe is taken as an abbreviation
138      for --output-format.  */
139   {_i ("FORMATs"), "formats", 'f', _i ("dump FORMAT,...  Also as separate options:")},
140   {0, "dvi", 0, _i ("generate DVI (tex backend only)")},
141   {0, "pdf", 0, _i ("generate PDF (default)")},
142   {0, "png", 0, _i ("generate PNG")},
143   {0, "ps", 0, _i ("generate PostScript")},
144   {0, "tex", 0, _i ("generate TeX (tex backend only)")},
145   {0, "help", 'h',  _i ("print this help")},
146   {_i ("FIELD"), "header", 'H',  _i ("write header field to BASENAME.FIELD")},
147   {_i ("DIR"), "include", 'I',  _i ("add DIR to search path")},
148   {_i ("FILE"), "init", 'i',  _i ("use FILE as init file")},
149   {_i ("FILE"), "output", 'o',  _i ("write output to FILE (suffix will be added)")},
150   {_i ("USER,GROUP,JAIL,DIR"), "jail", 'j', _i ("chroot to JAIL, become USER:GROUP\n                                       and cd into DIR")},
151   {0, "no-print", 0, _i ("do not generate printed output")},
152   {0, "preview", 'p',  _i ("generate a preview of the first system")},
153   {0, "safe-mode", 's',  _i ("run in safe mode")},
154   {0, "version", 'v',  _i ("print version number")},
155   {0, "verbose", 'V', _i ("be verbose")},
156   {0, "warranty", 'w',  _i ("show warranty and copyright")},
157   {0, 0, 0, 0}
158 };
159
160 #define LILYPOND_DATADIR PACKAGE_DATADIR "/" TOPLEVEL_VERSION
161
162 static void
163 dir_info (FILE *out)
164 {
165   fputs ("\n", out);
166   fprintf (out, "LILYPOND_DATADIR=\"%s\"\n", LILYPOND_DATADIR);
167   if (char const *env = getenv ("LILYPONDPREFIX"))
168     fprintf (out, "LILYPONDPREFIX=\"%s\"\n", env);
169   fprintf (out, "LOCALEDIR=\"%s\"\n", LOCALEDIR);
170
171   fprintf (out, "\nEffective prefix: \"%s\"\n", prefix_directory.to_str0 ());
172 }
173
174 static void
175 copyright ()
176 {
177   printf (_f ("Copyright (c) %s by\n%s  and others.",
178               "1996--2005",
179               AUTHORS).to_str0 ());
180   printf ("\n");
181 }
182
183 static void
184 identify (FILE *out)
185 {
186   fputs (gnu_lilypond_version_string ().to_str0 (), out);
187   fputs ("\n", out);
188 }
189
190 static void
191 notice ()
192 {
193   identify (stdout);
194   puts (_f (NOTICE, PROGRAM_NAME).to_str0 ());
195   printf ("\n");
196   copyright ();
197 }
198
199 static void
200 usage ()
201 {
202   /* No version number or newline here.  It confuses help2man.  */
203   printf (_f ("Usage: %s [OPTION]... FILE...", PROGRAM_NAME).to_str0 ());
204   printf ("\n\n");
205   printf (_ ("Typeset music and/or produce MIDI from FILE.").to_str0 ());
206   printf ("\n\n");
207   printf (_ ("LilyPond produces beautiful music notation.").to_str0 ());
208   printf ("\n");
209   printf (_f ("For more information, see %s", PROGRAM_URL).to_str0 ());
210   printf ("\n\n");
211   printf (_ ("Options:").to_str0 ());
212   printf ("\n");
213   printf (Long_option_init::table_string (options_static).to_str0 ());
214   printf ("\n");
215   printf (_f ("Report bugs to %s.", "bug-lilypond@gnu.org").to_str0 ());
216   printf ("\n");
217   printf ("\n");
218 }
219
220 static void
221 warranty ()
222 {
223   identify (stdout);
224   printf ("\n");
225   copyright ();
226   printf ("\n");
227   printf (_ (WARRANTY).to_str0 ());
228 }
229
230 static void
231 setup_paths ()
232 {
233   prefix_directory = LILYPOND_DATADIR;
234   if (char const *env = getenv ("LILYPONDPREFIX"))
235     prefix_directory = env;
236
237   global_path.append ("");
238
239   /* Adding mf/out make lilypond unchanged source directory, when setting
240      LILYPONDPREFIX to lilypond-x.y.z */
241   char *suffixes[] = {"ly", "ps", "scm", 0 };
242
243   Array<String> dirs;
244   for (char **s = suffixes; *s; s++)
245     {
246       String path = prefix_directory + to_string ('/') + String (*s);
247       dirs.push (path);
248     }
249
250   /*
251     ugh. C&P font-config.cc
252   */
253   struct stat statbuf; 
254   String builddir = prefix_directory + "/mf/out/";
255   if (stat (builddir.to_str0 (), &statbuf) == 0)
256     {
257       dirs.push (builddir.to_str0 ());
258     }
259   else
260     {
261       dirs.push (prefix_directory + "/fonts/otf/");
262       dirs.push (prefix_directory + "/fonts/type1/");
263       dirs.push (prefix_directory + "/fonts/cff/");
264       dirs.push (prefix_directory + "/fonts/svg/");
265       dirs.push (prefix_directory + "/fonts/cff/");
266     }
267
268   for (int i = 0; i < dirs.size (); i++)
269     global_path.prepend (dirs[i]);  
270 }
271   
272 static void
273 prepend_load_path (String dir)
274 {
275   String s = "(set! %load-path (cons \"" + dir + "\" %load-path))";
276   scm_c_eval_string (s.to_str0 ());
277 }
278
279 void init_global_tweak_registry ();
280 void init_fontconfig ();
281
282 static void
283 do_chroot_jail ()
284 {
285   /* Now we chroot, setuid/setgrp and chdir.  If something goes wrong,
286      we exit (this is a security-sensitive area).  First we split
287      jail_spec into its components, then we retrieve the user/group id
288      (necessarily *before* chroot'ing) and finally we perform the
289      actual actions.  */
290
291   enum Jail
292     {
293       USER_NAME, GROUP_NAME, JAIL, DIR, JAIL_MAX
294     };
295
296   Array<String> components = String_convert::split (jail_spec, ',');
297   if (components.size () != JAIL_MAX)
298     {
299       error (_f ("expected %d arguments with jail, found: %d", JAIL_MAX,
300                  components.size ()));
301       exit (2);
302     }
303
304   /* Hmm.  */
305   errno = 0;
306
307   int uid;
308   if (passwd * passwd = getpwnam (components[USER_NAME].to_str0 ()))
309     uid = passwd->pw_uid;
310   else
311     {
312       if (errno == 0)
313         error (_f ("no such user: %s", components[USER_NAME]));
314       else
315         error (_f ("can't get user id from user name: %s: %s",
316                    components[USER_NAME],
317                    strerror (errno)));
318       exit (3);
319     }
320
321   /* Hmm.  */
322   errno = 0;
323
324   int gid;
325   if (group * group = getgrnam (components[GROUP_NAME].to_str0 ()))
326     gid = group->gr_gid;
327   else
328     {
329       if (errno == 0)
330         error (_f ("no such group: %s", components[GROUP_NAME]));
331       else
332         error (_f ("can't get group id from group name: %s: %s",
333                    components[GROUP_NAME],
334                    strerror (errno)));
335       exit (3);
336     }
337
338   if (chroot (components[JAIL].to_str0 ()))
339     {
340       error (_f ("can't chroot to: %s: %s", components[JAIL],
341                  strerror (errno)));
342       exit (3);
343     }
344
345   if (setgid (gid))
346     {
347       error (_f ("can't change group id to: %d: %s", gid, strerror (errno)));
348       exit (3);
349     }
350
351   if (setuid (uid))
352     {
353       error (_f ("can't change user id to: %d: %s", uid, strerror (errno)));
354       exit (3);
355     }
356
357   if (chdir (components[DIR].to_str0 ()))
358     {
359       error (_f ("can't change working directory to: %s: %s", components[DIR],
360                  strerror (errno)));
361       exit (3);
362     }
363 }
364
365 void test_pango ();
366
367 static void
368 main_with_guile (void *, int, char **)
369 {
370   /* Engravers use lily.scm contents, need to make Guile find it.
371      Prepend onto GUILE %load-path, very ugh. */
372
373   prepend_load_path (prefix_directory);
374   prepend_load_path (prefix_directory + "/scm");
375
376   if (be_verbose_global)
377     dir_info (stderr);
378   is_TeX_format_global = (output_backend_global == "tex"
379                           || output_backend_global == "texstr");
380
381   is_pango_format_global = !is_TeX_format_global;
382
383   ly_c_init_guile ();
384   call_constructors ();
385   init_global_tweak_registry ();
386   init_fontconfig ();
387
388   init_freetype ();
389
390   all_fonts_global = new All_font_metrics (global_path.to_string ());
391
392   init_scheme_code_string += ")";
393   scm_c_eval_string ((char *) init_scheme_code_string.to_str0 ());
394
395   /* We accept multiple independent music files on the command line to
396      reduce compile time when processing lots of small files.
397      Starting the GUILE engine is very time consuming.  */
398
399   SCM files = SCM_EOL;
400   SCM *tail = &files;
401   while (char const *arg = option_parser->get_next_arg ())
402     {
403       *tail = scm_cons (scm_makfrom0str (arg), SCM_EOL);
404       tail = SCM_CDRLOC (*tail);
405     }
406   delete option_parser;
407   option_parser = 0;
408
409   if (files == SCM_EOL)
410     {
411       /* No FILE arguments is now a usage error to help newbies.  If you
412          want a filter, you're not a newbie and should know to use file
413          argument `-'.  */
414       usage ();
415       exit (2);
416     }
417
418   if (! jail_spec.is_empty ())
419     do_chroot_jail ();
420
421   SCM result = scm_call_1 (ly_lily_module_constant ("lilypond-main"), files);
422   (void) result;
423
424   /* Unreachable.  */
425   exit (0);
426 }
427
428 static void
429 setup_localisation ()
430 {
431 #if HAVE_GETTEXT
432   /* Enable locales */
433   setlocale (LC_ALL, "");
434
435   /* FIXME: check if this is still true.
436      Disable localisation of float values.  This breaks TeX output.  */
437   setlocale (LC_NUMERIC, "C");
438
439   String name (PACKAGE);
440   name.to_lower ();
441   bindtextdomain (name.to_str0 (), LOCALEDIR);
442   textdomain (name.to_str0 ());
443 #endif
444 }
445
446 static void
447 add_output_format (String format)
448 {
449   if (output_format_global != "")
450     output_format_global += ",";
451   output_format_global += format;
452 }
453
454 static void
455 parse_argv (int argc, char **argv)
456 {
457   bool show_help = false;
458   option_parser = new Getopt_long (argc, argv, options_static);
459   while (Long_option_init const *opt = (*option_parser) ())
460     {
461       switch (opt->shortname_char_)
462         {
463         case 0:
464           if (String (opt->longname_str0_) == "dvi"
465               || String (opt->longname_str0_) == "pdf"
466               || String (opt->longname_str0_) == "png"
467               || String (opt->longname_str0_) == "ps"
468               || String (opt->longname_str0_) == "tex")
469             add_output_format (opt->longname_str0_);
470           else if (String (opt->longname_str0_) == "preview")
471             make_preview = true;
472           else if (String (opt->longname_str0_) == "no-pages")
473             make_print = false;
474           break;
475
476         case 'v':
477           notice ();
478           exit (0);
479           break;
480         case 'o':
481           {
482             String s = option_parser->optional_argument_str0_;
483             File_name file_name (s);
484             output_name_global = file_name.to_string ();
485           }
486           break;
487         case 'j':
488           jail_spec = option_parser->optional_argument_str0_;
489           break;
490         case 'e':
491           init_scheme_code_string += option_parser->optional_argument_str0_;
492           break;
493         case 'w':
494           warranty ();
495           exit (0);
496           break;
497           
498         case 'b':
499           output_backend_global = option_parser->optional_argument_str0_;
500           break;
501
502         case 'f':
503           output_format_global = option_parser->optional_argument_str0_;
504           break;
505           
506         case 'H':
507           dump_header_fieldnames_global
508             .push (option_parser->optional_argument_str0_);
509           break;
510         case 'I':
511           global_path.append (option_parser->optional_argument_str0_);
512           break;
513         case 'i':
514           init_name_global = option_parser->optional_argument_str0_;
515           break;
516         case 'h':
517           show_help = true;
518           break;
519         case 'V':
520           be_verbose_global = true;
521           break;
522         case 's':
523           be_safe_global = true;
524           break;
525         case 'p':
526           make_preview = true;
527           break;
528         default:
529           programming_error (to_string ("unhandled short option: %c",
530                                         opt->shortname_char_));
531           assert (false);
532           break;
533         }
534     }
535
536   if (show_help)
537     {
538       identify (stdout);
539       usage ();
540       if (be_verbose_global)
541         dir_info (stdout);
542       exit (0);
543     }
544 }
545
546 int
547 main (int argc, char **argv)
548 {
549   setup_localisation ();
550   setup_paths ();
551   parse_argv (argc, argv);
552   identify (stderr);
553
554   scm_boot_guile (argc, argv, main_with_guile, 0);
555
556   /* Unreachable */
557   return 0;
558 }