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