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