]> git.donarmstrong.com Git - lilypond.git/blob - lily/main.cc
use -d options for --preview and --no-pages.
[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--2007 Han-Wen Nienhuys <hanwen@xs4all.nl>
7 */
8
9 #include "main.hh"
10
11 #include <cassert>
12 #include <clocale>
13 #include <cstring>
14 #include <cerrno>
15 using namespace std;
16
17 #include <unistd.h>
18 #include <sys/types.h>
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 "international.hh"
37 #include "lily-version.hh"
38 #include "misc.hh"
39 #include "output-def.hh"
40 #include "program-option.hh"
41 #include "relocate.hh"
42 #include "string-convert.hh"
43 #include "version.hh"
44 #include "warn.hh"
45
46 /*
47  * Global options that can be overridden through command line.
48  */
49
50 /* Names of header fields to be dumped to a separate file. */
51 vector<string> dump_header_fieldnames_global;
52
53 /* Name of initialisation file. */
54 string init_name_global;
55
56
57 /* Output formats to generate.  */
58 string output_format_global = "";
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_global;
78 string init_scheme_variables_global;
79
80 bool relocate_binary = true;
81
82
83 /*
84  * Miscellaneous global stuff.
85  */
86 File_path global_path;
87
88 /*
89  * File globals.
90  */
91
92 static char const *AUTHORS
93 = "  Han-Wen Nienhuys <hanwen@xs4all.nl>\n"
94   "  Jan Nieuwenhuizen <janneke@gnu.org>\n";
95
96 static char const *PROGRAM_NAME = "lilypond";
97 static char const *PROGRAM_URL = "http://lilypond.org";
98
99 static char const *NOTICE
100 = _i ("This program is free software.  It is covered by the GNU General Public\n"
101       "License and you are welcome to change it and/or distribute copies of it\n"
102       "under certain conditions.  Invoke as `%s --warranty' for more\n"
103       "information.\n");
104
105 static char const *WARRANTY
106 = _i ("    This program is free software; you can redistribute it and/or\n"
107       "modify it under the terms of the GNU General Public License version 2\n"
108       "as published by the Free Software Foundation.\n"
109       "\n"
110       "    This program is distributed in the hope that it will be useful,\n"
111       "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
112       "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
113       "General Public License for more details.\n"
114       "\n"
115       "    You should have received a copy of the\n"
116       "GNU General Public License along with this program; if not, write to\n"
117       "the Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n"
118       "Boston, MA 02111-1307, USA.\n");
119
120 /* Where the init files live.  Typically:
121    LILYPOND_DATADIR = /usr/share/lilypond
122 */
123 string lilypond_datadir;
124
125 /* The jail specification: USER, GROUP, JAIL, DIR. */
126 string jail_spec;
127
128 /*  The option parser */
129 static Getopt_long *option_parser = 0;
130
131 /* Internationalisation kludge in two steps:
132  * use _i () to get entry in POT file
133  * call gettext () explicitely for actual "translation"  */
134
135 static Long_option_init options_static[]
136 = {
137   {_i ("SYM[=VAL]"), "define-default", 'd',
138    _i ("set Scheme option SYM to VAL (default: #t).\n"
139        "Use -dhelp for help.")},
140
141   {_i ("EXPR"), "evaluate", 'e', _i ("evaluate scheme code")},
142   /* Bug in option parser: --output =foe is taken as an abbreviation
143      for --output-format.  */
144   {_i ("FORMATs"), "formats", 'f', _i ("dump FORMAT,...  Also as separate options:")},
145   {0, "dvi", 0, _i ("generate DVI (tex backend only)")},
146   {0, "pdf", 0, _i ("generate PDF (default)")},
147   {0, "png", 0, _i ("generate PNG")},
148   {0, "ps", 0, _i ("generate PostScript")},
149   {0, "tex", 0, _i ("generate TeX (tex backend only)")},
150   {0, "help", 'h',  _i ("show this help and exit")},
151   {_i ("FIELD"), "header", 'H',  _i ("dump header field FIELD to file\n"
152                                      "named BASENAME.FIELD")},
153   {_i ("DIR"), "include", 'I',  _i ("add DIR to search path")},
154   {_i ("FILE"), "init", 'i',  _i ("use FILE as init file")},
155 #if HAVE_CHROOT
156   {_i ("USER, GROUP, JAIL, DIR"), "jail", 'j', _i ("chroot to JAIL, become USER:GROUP\n"
157                                                 "and cd into DIR")},
158 #endif
159   {0, "no-print", 0, _i ("do not generate printed output")},
160   {_i ("FILE"), "output", 'o',  _i ("write output to FILE (suffix will be added)")},
161   {0, "preview", 'p',  _i ("generate a preview of the first system")},
162   {0, "relocate", 0, _i ("relocate using directory of lilypond program")},
163   {0, "version", 'v',  _i ("show version number and exit")},
164   {0, "verbose", 'V', _i ("be verbose")},
165   {0, "warranty", 'w',  _i ("show warranty and copyright")},
166   {0, 0, 0, 0}
167 };
168
169 char const *LILYPOND_DATADIR = PACKAGE_DATADIR "/" TOPLEVEL_VERSION;
170
171 static void
172 env_var_info (FILE *out, char const *key)
173 {
174   if (char const *value = getenv (key))
175     fprintf (out, "%s=\"%s\"\n", key, value);
176 }
177
178 static void
179 dir_info (FILE *out)
180 {
181   fputs ("\n", out);
182   fprintf (out, "LILYPOND_DATADIR=\"%s\"\n", LILYPOND_DATADIR);
183   env_var_info (out, "LILYPONDPREFIX");
184   env_var_info (out, "LILYPOND_DATADIR");
185   fprintf (out, "LOCALEDIR=\"%s\"\n", LOCALEDIR);
186
187   fprintf (out, "\nEffective prefix: \"%s\"\n", lilypond_datadir.c_str ());
188
189   if (relocate_binary)
190     {
191       env_var_info (out, "FONTCONFIG_FILE");
192       env_var_info (out, "FONTCONFIG_PATH");
193       env_var_info (out, "GS_FONTPATH");
194       env_var_info (out, "GS_LIB");
195       env_var_info (out, "GUILE_LOAD_PATH");
196       env_var_info (out, "PANGO_RC_FILE");
197       env_var_info (out, "PANGO_PREFIX");
198       env_var_info (out, "PATH");
199     }
200 }
201
202 static void
203 copyright ()
204 {
205   printf (_f ("Copyright (c) %s by\n%s  and others.",
206               "1996--2007",
207               AUTHORS).c_str ());
208   printf ("\n");
209 }
210
211 static void
212 identify (FILE *out)
213 {
214   fputs (gnu_lilypond_version_string ().c_str (), out);
215   fputs ("\n", out);
216 }
217
218 static void
219 notice ()
220 {
221   identify (stdout);
222   puts (_f (NOTICE, PROGRAM_NAME).c_str ());
223   printf ("\n");
224   copyright ();
225 }
226
227 LY_DEFINE (ly_usage, "ly:usage",
228            0, 0, 0, (),
229            "Print usage message.")
230 {
231   /* No version number or newline here.  It confuses help2man.  */
232   printf (_f ("Usage: %s [OPTION]... FILE...", PROGRAM_NAME).c_str ());
233   printf ("\n\n");
234   printf (_ ("Typeset music and/or produce MIDI from FILE.").c_str ());
235   printf ("\n\n");
236   printf (_ ("LilyPond produces beautiful music notation.").c_str ());
237   printf ("\n");
238   printf (_f ("For more information, see %s", PROGRAM_URL).c_str ());
239   printf ("\n\n");
240   printf (_ ("Options:").c_str ());
241   printf ("\n");
242   printf (Long_option_init::table_string (options_static).c_str ());
243   printf ("\n");
244   printf (_f ("Report bugs via %s",
245               "http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs"
246               ).c_str ());
247   printf ("\n");
248   printf ("\n");
249   return SCM_UNSPECIFIED;
250 }
251
252 static void
253 warranty ()
254 {
255   identify (stdout);
256   printf ("\n");
257   copyright ();
258   printf ("\n");
259   printf (_ (WARRANTY).c_str ());
260 }
261
262 static void
263 prepend_load_path (string dir)
264 {
265   string s = "(set! %load-path (cons \"" + dir + "\" %load-path))";
266   scm_c_eval_string (s.c_str ());
267 }
268
269 void init_global_tweak_registry ();
270 void init_fontconfig ();
271
272 #if HAVE_CHROOT
273 static void
274 do_chroot_jail ()
275 {
276   /* Now we chroot, setuid/setgrp and chdir.  If something goes wrong,
277      we exit (this is a security-sensitive area).  First we split
278      jail_spec into its components, then we retrieve the user/group id
279      (necessarily *before* chroot'ing) and finally we perform the
280      actual actions.  */
281
282   enum Jail
283     {
284       USER_NAME, GROUP_NAME, JAIL, DIR, JAIL_MAX
285     };
286
287   vector<string> components = string_split (jail_spec, ',');
288   if (components.size () != JAIL_MAX)
289     {
290       error (_f ("expected %d arguments with jail, found: %u", JAIL_MAX,
291                  (unsigned) components.size ()));
292       exit (2);
293     }
294
295   /* Hmm.  */
296   errno = 0;
297
298   int uid;
299   if (passwd * passwd = getpwnam (components[USER_NAME].c_str ()))
300     uid = passwd->pw_uid;
301   else
302     {
303       if (errno == 0)
304         error (_f ("no such user: %s", components[USER_NAME]));
305       else
306         error (_f ("cannot get user id from user name: %s: %s",
307                    components[USER_NAME],
308                    strerror (errno)));
309       exit (3);
310     }
311
312   /* Hmm.  */
313   errno = 0;
314
315   int gid;
316   if (group * group = getgrnam (components[GROUP_NAME].c_str ()))
317     gid = group->gr_gid;
318   else
319     {
320       if (errno == 0)
321         error (_f ("no such group: %s", components[GROUP_NAME]));
322       else
323         error (_f ("cannot get group id from group name: %s: %s",
324                    components[GROUP_NAME],
325                    strerror (errno)));
326       exit (3);
327     }
328
329   if (chroot (components[JAIL].c_str ()))
330     {
331       error (_f ("cannot chroot to: %s: %s", components[JAIL],
332                  strerror (errno)));
333       exit (3);
334     }
335
336   if (setgid (gid))
337     {
338       error (_f ("cannot change group id to: %d: %s", gid, strerror (errno)));
339       exit (3);
340     }
341
342   if (setuid (uid))
343     {
344       error (_f ("cannot change user id to: %d: %s", uid, strerror (errno)));
345       exit (3);
346     }
347
348   if (chdir (components[DIR].c_str ()))
349     {
350       error (_f ("cannot change working directory to: %s: %s", components[DIR],
351                  strerror (errno)));
352       exit (3);
353     }
354 }
355 #endif
356
357 static void
358 main_with_guile (void *, int, char **)
359 {
360   /* Engravers use lily.scm contents, need to make Guile find it.
361      Prepend onto GUILE %load-path, very ugh. */
362
363   prepend_load_path (lilypond_datadir);
364   prepend_load_path (lilypond_datadir + "/scm");
365
366   if (be_verbose_global)
367     dir_info (stderr);
368
369   is_pango_format_global = !is_TeX_format_global;
370   init_scheme_variables_global = "(list " + init_scheme_variables_global + ")";
371   init_scheme_code_global = "(begin " + init_scheme_code_global + ")";
372
373   ly_c_init_guile ();
374   call_constructors ();
375   init_fontconfig ();
376
377   init_freetype ();
378   ly_reset_all_fonts ();
379
380   is_TeX_format_global = (get_output_backend_name () == "tex"
381                           || get_output_backend_name () == "texstr");
382   
383
384   /* We accept multiple independent music files on the command line to
385      reduce compile time when processing lots of small files.
386      Starting the GUILE engine is very time consuming.  */
387
388   SCM files = SCM_EOL;
389   SCM *tail = &files;
390   while (char const *arg = option_parser->get_next_arg ())
391     {
392       *tail = scm_cons (scm_from_locale_string (arg), SCM_EOL);
393       tail = SCM_CDRLOC (*tail);
394     }
395   
396   delete option_parser;
397   option_parser = 0;
398
399 #if HAVE_CHROOT
400   if (!jail_spec.empty ())
401     do_chroot_jail ();
402 #endif
403
404   SCM result = scm_call_1 (ly_lily_module_constant ("lilypond-main"), files);
405   (void) result;
406
407   /* Unreachable.  */
408   exit (0);
409 }
410
411 static void
412 setup_localisation ()
413 {
414 #if HAVE_GETTEXT
415   /* Enable locales */
416   setlocale (LC_ALL, "");
417
418   /* FIXME: check if this is still true.
419      Disable localisation of float values.  This breaks TeX output.  */
420   setlocale (LC_NUMERIC, "C");
421
422   string localedir = LOCALEDIR;
423   if (char const *env = getenv ("LILYPOND_LOCALEDIR"))
424     localedir = env;
425
426   bindtextdomain ("lilypond", localedir.c_str ());
427   textdomain ("lilypond");
428 #endif
429 }
430
431 static void
432 add_output_format (string format)
433 {
434   if (output_format_global != "")
435     output_format_global += ",";
436   output_format_global += format;
437 }
438
439 static void
440 parse_argv (int argc, char **argv)
441 {
442   bool show_help = false;
443   option_parser = new Getopt_long (argc, argv, options_static);
444   while (Long_option_init const *opt = (*option_parser) ())
445     {
446       switch (opt->shortname_char_)
447         {
448         case 0:
449           if (string (opt->longname_str0_) == "dvi"
450               || string (opt->longname_str0_) == "pdf"
451               || string (opt->longname_str0_) == "png"
452               || string (opt->longname_str0_) == "ps"
453               || string (opt->longname_str0_) == "tex")
454             add_output_format (opt->longname_str0_);
455           else if (string (opt->longname_str0_) == "relocate")
456             relocate_binary = true;
457           break;
458
459         case 'd':
460           {
461             string arg (option_parser->optional_argument_str0_);
462             ssize eq = arg.find ('=');
463
464             string key = arg;
465             string val = "#t";
466
467             if (eq != NPOS)
468               {
469                 key = arg.substr (0, eq);
470                 val = arg.substr (eq + 1, arg.length () - 1);
471               }
472
473             init_scheme_variables_global
474               += "(cons \'" + key + " '" + val + ")\n";
475           }
476           break;
477
478         case 'v':
479           notice ();
480           exit (0);
481           break;
482         case 'o':
483           {
484             string s = option_parser->optional_argument_str0_;
485             File_name file_name (s);
486             output_name_global = file_name.to_string ();
487           }
488           break;
489         case 'j':
490           jail_spec = option_parser->optional_argument_str0_;
491           break;
492           
493         case 'e':
494           init_scheme_code_global += option_parser->optional_argument_str0_ + string (" ");
495           break;
496         case 'w':
497           warranty ();
498           exit (0);
499           break;
500
501         case 'f':
502           {
503             vector<string> components
504               = string_split (option_parser->optional_argument_str0_, ',');
505             for (vsize i = 0; i < components.size (); i++)
506               add_output_format (components[i]);
507           }
508           break;
509
510         case 'H':
511           dump_header_fieldnames_global
512             .push_back (option_parser->optional_argument_str0_);
513           break;
514         case 'I':
515           global_path.append (option_parser->optional_argument_str0_);
516           break;
517         case 'i':
518           init_name_global = option_parser->optional_argument_str0_;
519           break;
520         case 'h':
521           show_help = true;
522           break;
523         case 'V':
524           be_verbose_global = true;
525           break;
526         default:
527           programming_error (to_string ("unhandled short option: %c",
528                                         opt->shortname_char_));
529           assert (false);
530           break;
531         }
532     }
533
534   if (output_format_global == "")
535     output_format_global = "pdf";
536
537   if (show_help)
538     {
539       identify (stdout);
540       ly_usage ();
541       if (be_verbose_global)
542         dir_info (stdout);
543       exit (0);
544     }
545 }
546
547 void
548 setup_guile_env ()
549 {
550   const char *yield = getenv ("LILYPOND_GC_YIELD");
551   bool overwrite = true;
552   if (!yield)
553     {
554       yield = "65";
555       overwrite = false;
556     }
557
558   sane_putenv ("GUILE_MIN_YIELD_1", yield, overwrite);
559   sane_putenv ("GUILE_MIN_YIELD_2", yield, overwrite);
560   sane_putenv ("GUILE_MIN_YIELD_MALLOC", yield, overwrite);
561
562
563   sane_putenv ("GUILE_INIT_SEGMENT_SIZE_1",
564                "10485760", overwrite);
565   sane_putenv ("GUILE_MAX_SEGMENT_SIZE",
566                "104857600", overwrite);
567 }
568
569 int
570 main (int argc, char **argv)
571 {
572   if (getenv ("LILYPOND_VERBOSE"))
573     be_verbose_global = true;
574
575   setup_localisation ();
576   parse_argv (argc, argv);
577   if (isatty (STDIN_FILENO))
578     identify (stderr);
579
580   setup_paths (argv[0]);
581   setup_guile_env ();
582
583 #if 0
584   /* Debugging aid.  */
585   try
586     {
587       scm_boot_guile (argc, argv, main_with_guile, 0);
588     }
589   catch (exception e)
590     {
591       error (_f ("exception caught: %s", e.what ()));
592     };
593 #else
594   scm_boot_guile (argc, argv, main_with_guile, 0);
595 #endif
596         
597   /* Only reachable if GUILE exits.  That is an error.  */
598   return 1;
599 }
600
601 SCM atexit_list = SCM_EOL;
602
603 LY_DEFINE (ly_atexit, "ly:atexit",
604            2, 0, 0, (SCM proc, SCM args),
605            "Just before exiting, call the procedure given. "
606 "If this is called multiple times, the procedures are called "
607 "in LIFO order.")
608 {
609   atexit_list = scm_cons (scm_cons (proc, args), atexit_list);
610   scm_gc_protect_object (atexit_list);
611   return SCM_UNSPECIFIED;
612 }
613
614 LY_DEFINE (ly_do_atexit, "ly:do-atexit",
615            0, 0, 0, (),
616            "Call the atexit procedures.")
617 {
618   for (SCM s = atexit_list; scm_is_pair (s); s = scm_cdr (s))
619     scm_apply_0 (scm_caar (s), scm_cdar (s));
620   return SCM_UNSPECIFIED;
621 }