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