]> git.donarmstrong.com Git - lilypond.git/blob - lily/general-scheme.cc
Clean up g++ 4.6.1 compiler warnings (-Wunused-but-set-variable).
[lilypond.git] / lily / general-scheme.cc
1 /*
2   This file is part of LilyPond, the GNU music typesetter.
3
4   Copyright (C) 1998--2011 Jan Nieuwenhuizen <janneke@gnu.org>
5   Han-Wen Nienhuys <hanwen@xs4all.nl>
6
7   LilyPond is free software: you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation, either version 3 of the License, or
10   (at your option) any later version.
11
12   LilyPond is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16
17   You should have received a copy of the GNU General Public License
18   along with LilyPond.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "config.hh"
22
23 #include <cstdio>
24 #include <ctype.h>
25 #include <cstring>  /* memset */
26 #include <glib.h>
27 using namespace std;
28
29 #include "dimensions.hh"
30 #include "file-name.hh"
31 #include "file-path.hh"
32 #include "international.hh"
33 #include "libc-extension.hh"
34 #include "lily-guile.hh"
35 #include "main.hh"
36 #include "misc.hh"
37 #include "program-option.hh"
38 #include "relocate.hh"
39 #include "string-convert.hh"
40 #include "version.hh"
41 #include "warn.hh"
42
43 /* Declaration of log function(s) */
44 SCM ly_progress (SCM, SCM);
45
46 LY_DEFINE (ly_start_environment, "ly:start-environment",
47            0, 0, 0, (),
48            "Return the environment (a list of strings) that was in"
49            " effect at program start.")
50 {
51   SCM l = SCM_EOL;
52   SCM *tail = &l;
53
54   for (vsize i = 0; i < start_environment_global.size (); i++)
55     {
56       *tail = scm_cons (ly_string2scm (start_environment_global[i]),
57                         SCM_EOL);
58       tail = SCM_CDRLOC (*tail);
59     }
60
61   return l;
62 }
63
64 LY_DEFINE (ly_find_file, "ly:find-file",
65            1, 0, 0, (SCM name),
66            "Return the absolute file name of @var{name},"
67            " or @code{#f} if not found.")
68 {
69   LY_ASSERT_TYPE (scm_is_string, name, 1);
70
71   string nm = ly_scm2string (name);
72   string file_name = global_path.find (nm);
73   if (file_name.empty ())
74     return SCM_BOOL_F;
75
76   return ly_string2scm (file_name);
77 }
78
79 /*
80   Ugh. Gulped file is copied twice. (maybe thrice if you count stdio
81   buffering.)
82 */
83 LY_DEFINE (ly_gulp_file, "ly:gulp-file",
84            1, 1, 0, (SCM name, SCM size),
85            "Read @var{size} characters from the file @var{name},"
86            " and return its contents in a string."
87            "  If @var{size} is undefined, the entire file is read."
88            "  The file is looked up using the search path.")
89 {
90   LY_ASSERT_TYPE (scm_is_string, name, 1);
91   int sz = INT_MAX;
92   if (size != SCM_UNDEFINED)
93     {
94       LY_ASSERT_TYPE (scm_is_number, size, 2);
95       sz = scm_to_int (size);
96     }
97
98   string contents = gulp_file_to_string (ly_scm2string (name), true, sz);
99   return scm_from_locale_stringn (contents.c_str (), contents.length ());
100 }
101
102
103 LY_DEFINE (ly_dir_p, "ly:dir?",
104            1, 0, 0, (SCM s),
105            "Is @var{s} a direction?  Valid directions are @code{-1},"
106            " @code{0}, or@tie{}@code{1}, where @code{-1} represents"
107            " left or down, @code{1}@tie{}represents right or up, and @code{0}"
108            " represents a neutral direction.")
109 {
110   if (scm_is_number (s))
111     {
112       int i = scm_to_int (s);
113       return (i >= -1 && i <= 1) ? SCM_BOOL_T : SCM_BOOL_F;
114     }
115   return SCM_BOOL_F;
116 }
117
118 LY_DEFINE (ly_assoc_get, "ly:assoc-get",
119            2, 2, 0,
120            (SCM key, SCM alist, SCM default_value, SCM strict_checking),
121            "Return value if @var{key} in @var{alist}, else @var{default-value}"
122            " (or @code{#f} if not specified).  If @var{strict-checking} is set"
123            " to @code{#t} and @var{key} is not in @var{alist}, a programming_error"
124            " is output.")
125 {
126   LY_ASSERT_TYPE (ly_cheap_is_list, alist, 2);
127
128   SCM handle = scm_assoc (key, alist);
129   if (scm_is_pair (handle))
130     return scm_cdr (handle);
131
132   if (default_value == SCM_UNDEFINED)
133     default_value = SCM_BOOL_F;
134
135   if (strict_checking == SCM_BOOL_T)
136     {
137       string key_string = ly_scm2string
138                           (scm_object_to_string (key, SCM_UNDEFINED));
139       string default_value_string = ly_scm2string
140                                     (scm_object_to_string (default_value,
141                                                            SCM_UNDEFINED));
142       programming_error ("Cannot find key `"
143                          + key_string
144                          + "' in alist, setting to `"
145                          + default_value_string + "'.");
146     }
147
148   return default_value;
149 }
150
151 LY_DEFINE (ly_string_substitute, "ly:string-substitute",
152            3, 0, 0, (SCM a, SCM b, SCM s),
153            "Replace string@tie{}@var{a} by string@tie{}@var{b} in"
154            " string@tie{}@var{s}.")
155 {
156   LY_ASSERT_TYPE (scm_is_string, s, 1);
157   LY_ASSERT_TYPE (scm_is_string, b, 2);
158   LY_ASSERT_TYPE (scm_is_string, s, 3);
159
160   string ss = ly_scm2string (s);
161   replace_all (&ss, ly_scm2string (a),
162                ly_scm2string (b));
163
164   return ly_string2scm (ss);
165 }
166
167 bool
168 is_not_escape_character (Byte c)
169 {
170   switch (c)
171     {
172     case '-':
173     case '.':
174     case '/':
175     case '0'...'9':
176     case ':':
177     case 'A'...'Z':
178     case '_':
179     case 'a'...'z':
180       return true;
181     }
182
183   return false;
184 }
185
186 LY_DEFINE (ly_string_percent_encode, "ly:string-percent-encode",
187            1, 0, 0, (SCM str),
188            "Encode all characters in string @var{str} with hexadecimal"
189            " percent escape sequences, with the following exceptions:"
190            " characters @code{-}, @code{.}, @code{/}, and @code{_}; and"
191            " characters in ranges @code{0-9}, @code{A-Z}, and @code{a-z}.")
192 {
193   LY_ASSERT_TYPE (scm_is_string, str, 1);
194
195   string orig_str = ly_scm2string (str);
196   string new_str = "";
197
198   vsize i = 0;
199   vsize n = orig_str.size ();
200
201   while (i < n)
202     {
203       Byte cur = orig_str[i];
204
205       if (is_not_escape_character (cur))
206         new_str += cur;
207       else
208         {
209           new_str += '%';
210           new_str += String_convert::bin2hex (cur);
211         }
212
213       i++;
214     }
215
216   return ly_string2scm (new_str);
217 }
218
219 LY_DEFINE (ly_number_2_string, "ly:number->string",
220            1, 0, 0, (SCM s),
221            "Convert @var{s} to a string without generating many decimals.")
222 {
223   LY_ASSERT_TYPE (scm_is_number, s, 1);
224
225   char str[400];                        // ugh.
226
227   if (scm_exact_p (s) == SCM_BOOL_F)
228     {
229       Real r (scm_to_double (s));
230       if (isinf (r) || isnan (r))
231         {
232           programming_error (_ ("infinity or NaN encountered while converting Real number"));
233           programming_error (_ ("setting to zero"));
234
235           r = 0.0;
236         }
237
238       snprintf (str, sizeof (str), "%.4f", r);
239     }
240   else
241     snprintf (str, sizeof (str), "%d", int (scm_to_int (s)));
242
243   return scm_from_locale_string (str);
244 }
245
246 LY_DEFINE (ly_version, "ly:version", 0, 0, 0, (),
247            "Return the current lilypond version as a list, e.g.,"
248            " @code{(1 3 127 uu1)}.")
249 {
250   char const *vs = "\'(" MAJOR_VERSION " " MINOR_VERSION " " PATCH_LEVEL " " MY_PATCH_LEVEL ")";
251
252   return scm_c_eval_string ((char *)vs);
253 }
254
255 LY_DEFINE (ly_unit, "ly:unit", 0, 0, 0, (),
256            "Return the unit used for lengths as a string.")
257 {
258   return scm_from_locale_string (INTERNAL_UNIT);
259 }
260
261 LY_DEFINE (ly_dimension_p, "ly:dimension?", 1, 0, 0, (SCM d),
262            "Return @var{d} as a number.  Used to distinguish length"
263            " variables from normal numbers.")
264 {
265   return scm_number_p (d);
266 }
267
268 /*
269   Debugging mem leaks:
270 */
271 LY_DEFINE (ly_protects, "ly:protects",
272            0, 0, 0, (),
273            "Return hash of protected objects.")
274 {
275   return scm_protects;
276 }
277
278 LY_DEFINE (ly_gettext, "ly:gettext",
279            1, 0, 0, (SCM original),
280            "A Scheme wrapper function for @code{gettext}.")
281 {
282   LY_ASSERT_TYPE (scm_is_string, original, 1);
283   return ly_string2scm (_ (ly_scm2string (original).c_str ()));
284 }
285
286 LY_DEFINE (ly_output_formats, "ly:output-formats",
287            0, 0, 0, (),
288            "Formats passed to @option{--format} as a list of strings,"
289            " used for the output.")
290 {
291   vector<string> output_formats = string_split (output_format_global, ',');
292
293   SCM lst = SCM_EOL;
294   int output_formats_count = output_formats.size ();
295   for (int i = 0; i < output_formats_count; i++)
296     lst = scm_cons (ly_string2scm (output_formats[i]), lst);
297
298   return lst;
299 }
300
301 LY_DEFINE (ly_wide_char_2_utf_8, "ly:wide-char->utf-8",
302            1, 0, 0, (SCM wc),
303            "Encode the Unicode codepoint @var{wc}, an integer, as UTF-8.")
304 {
305   char buf[5];
306
307   LY_ASSERT_TYPE (scm_is_integer, wc, 1);
308   unsigned wide_char = (unsigned) scm_to_int (wc);
309   char *p = buf;
310
311   if (wide_char < 0x0080)
312     *p++ = (char)wide_char;
313   else if (wide_char < 0x0800)
314     {
315       *p++ = (char) (((wide_char >> 6)) | 0xC0);
316       *p++ = (char) (((wide_char) & 0x3F) | 0x80);
317     }
318   else if (wide_char < 0x10000)
319     {
320       *p++ = (char) (((wide_char >> 12)) | 0xE0);
321       *p++ = (char) (((wide_char >> 6) & 0x3F) | 0x80);
322       *p++ = (char) (((wide_char) & 0x3F) | 0x80);
323     }
324   else
325     {
326       *p++ = (char) (((wide_char >> 18)) | 0xF0);
327       *p++ = (char) (((wide_char >> 12) & 0x3F) | 0x80);
328       *p++ = (char) (((wide_char >> 6) & 0x3F) | 0x80);
329       *p++ = (char) (((wide_char) & 0x3F) | 0x80);
330     }
331   *p = 0;
332
333   return scm_from_locale_string (buf);
334 }
335
336 LY_DEFINE (ly_effective_prefix, "ly:effective-prefix",
337            0, 0, 0, (),
338            "Return effective prefix.")
339 {
340   return ly_string2scm (lilypond_datadir);
341 }
342
343 LY_DEFINE (ly_chain_assoc_get, "ly:chain-assoc-get",
344            2, 2, 0, (SCM key, SCM achain, SCM default_value, SCM strict_checking),
345            "Return value for @var{key} from a list of alists @var{achain}."
346            "  If no entry is found, return @var{default-value} or @code{#f} if"
347            " @var{default-value} is not specified.  With @var{strict-checking}"
348            " set to @code{#t}, a programming_error is output in such cases.")
349 {
350   if (scm_is_pair (achain))
351     {
352       SCM handle = scm_assoc (key, scm_car (achain));
353       if (scm_is_pair (handle))
354         return scm_cdr (handle);
355       else
356         return ly_chain_assoc_get (key, scm_cdr (achain), default_value);
357     }
358
359   if (strict_checking == SCM_BOOL_T)
360     {
361       string key_string = ly_scm2string
362                           (scm_object_to_string (key, SCM_UNDEFINED));
363       string default_value_string = ly_scm2string
364                                     (scm_object_to_string (default_value,
365                                                            SCM_UNDEFINED));
366       programming_error ("Cannot find key `"
367                          + key_string
368                          + "' in achain, setting to `"
369                          + default_value_string + "'.");
370     }
371
372   return default_value == SCM_UNDEFINED ? SCM_BOOL_F : default_value;
373 }
374
375 LY_DEFINE (ly_stderr_redirect, "ly:stderr-redirect",
376            1, 1, 0, (SCM file_name, SCM mode),
377            "Redirect stderr to @var{file-name}, opened with @var{mode}.")
378 {
379   LY_ASSERT_TYPE (scm_is_string, file_name, 1);
380
381   string m = "w";
382   string f = ly_scm2string (file_name);
383   FILE *stderrfile;
384   if (mode != SCM_UNDEFINED && scm_string_p (mode))
385     m = ly_scm2string (mode);
386   /* dup2 and (fileno (current-error-port)) do not work with mingw'c
387      gcc -mwindows.  */
388   fflush (stderr);
389   stderrfile = freopen (f.c_str (), m.c_str (), stderr);
390   if (!stderrfile)
391     error (_f ("failed redirecting stderr to `%s'", f.c_str ()));
392   return SCM_UNSPECIFIED;
393 }
394
395 static SCM
396 accumulate_symbol (void * /* closure */,
397                    SCM key,
398                    SCM /* val */,
399                    SCM result)
400 {
401   return scm_cons (key, result);
402 }
403
404 LY_DEFINE (ly_hash_table_keys, "ly:hash-table-keys",
405            1, 0, 0, (SCM tab),
406            "Return a list of keys in @var{tab}.")
407 {
408   return scm_internal_hash_fold ((scm_t_hash_fold_fn) &accumulate_symbol,
409                                  NULL, SCM_EOL, tab);
410 }
411
412 LY_DEFINE (ly_camel_case_2_lisp_identifier, "ly:camel-case->lisp-identifier",
413            1, 0, 0, (SCM name_sym),
414            "Convert @code{FooBar_Bla} to @code{foo-bar-bla} style symbol.")
415 {
416   LY_ASSERT_TYPE (ly_is_symbol, name_sym, 1);
417
418   /*
419     TODO: should use strings instead?
420   */
421
422   const string in = ly_symbol2string (name_sym);
423   string result = camel_case_to_lisp_identifier (in);
424
425   return ly_symbol2scm (result.c_str ());
426 }
427
428 LY_DEFINE (ly_expand_environment, "ly:expand-environment",
429            1, 0, 0, (SCM str),
430            "Expand @code{$VAR} and @code{$@{VAR@}} in @var{str}.")
431 {
432   LY_ASSERT_TYPE (scm_is_string, str, 1);
433
434   return ly_string2scm (expand_environment_variables (ly_scm2string (str)));
435 }
436
437 LY_DEFINE (ly_truncate_list_x, "ly:truncate-list!",
438            2, 0, 0, (SCM lst, SCM i),
439            "Take at most the first @var{i} of list @var{lst}.")
440 {
441   LY_ASSERT_TYPE (scm_is_integer, i, 1);
442
443   int k = scm_to_int (i);
444   if (k == 0)
445     lst = SCM_EOL;
446   else
447     {
448       SCM s = lst;
449       k--;
450       for (; scm_is_pair (s) && k--; s = scm_cdr (s))
451         ;
452
453       if (scm_is_pair (s))
454         scm_set_cdr_x (s, SCM_EOL);
455     }
456   return lst;
457 }
458
459 string
460 format_single_argument (SCM arg, int precision, bool escape = false)
461 {
462   if (scm_is_integer (arg) && scm_exact_p (arg) == SCM_BOOL_T)
463     return (String_convert::int_string (scm_to_int (arg)));
464   else if (scm_is_number (arg))
465     {
466       Real val = scm_to_double (arg);
467
468       if (isnan (val) || isinf (val))
469         {
470           warning (_ ("Found infinity or nan in output. Substituting 0.0"));
471           return ("0.0");
472           if (strict_infinity_checking)
473             abort ();
474         }
475       else
476         return (String_convert::form_string ("%.*lf", precision, val));
477     }
478   else if (scm_is_string (arg))
479     {
480       string s = ly_scm2string (arg);
481       if (escape)
482         {
483           // Escape backslashes and double quotes, wrap it in double quotes
484           replace_all (&s, "\\", "\\\\");
485           replace_all (&s, "\"", "\\\"");
486           // don't replace percents, since the png backend uses %d as escape sequence
487           // replace_all (&s, "%", "\\%");
488           replace_all (&s, "$", "\\$");
489           s = "\"" + s + "\"";
490         }
491       return s;
492     }
493   else if (scm_is_symbol (arg))
494     return (ly_symbol2string (arg));
495   else
496     {
497       ly_progress (scm_from_locale_string ("\nUnsupported SCM value for format: ~a"),
498                    scm_list_1 (arg));
499     }
500
501   return "";
502 }
503
504 LY_DEFINE (ly_format, "ly:format",
505            1, 0, 1, (SCM str, SCM rest),
506            "LilyPond specific format, supporting @code{~a} and @code{~[0-9]f}."
507            "  Basic support for @code{~s} is also provided.")
508 {
509   LY_ASSERT_TYPE (scm_is_string, str, 1);
510
511   string format = ly_scm2string (str);
512   vector<string> results;
513
514   vsize i = 0;
515   while (i < format.size ())
516     {
517       vsize tilde = format.find ('~', i);
518
519       results.push_back (format.substr (i, (tilde - i)));
520
521       if (tilde == NPOS)
522         break;
523
524       tilde++;
525
526       char spec = format.at (tilde++);
527       if (spec == '~')
528         results.push_back ("~");
529       else
530         {
531           if (!scm_is_pair (rest))
532             {
533               programming_error (string (__FUNCTION__)
534                                  + ": not enough arguments for format.");
535               return ly_string2scm ("");
536             }
537
538           SCM arg = scm_car (rest);
539           rest = scm_cdr (rest);
540
541           int precision = 8;
542
543           if (spec == '$')
544             precision = 2;
545           else if (isdigit (spec))
546             {
547               precision = spec - '0';
548               spec = format.at (tilde++);
549             }
550
551           if (spec == 'a' || spec == 'A' || spec == 'f' || spec == '$')
552             results.push_back (format_single_argument (arg, precision));
553           else if (spec == 's' || spec == 'S')
554             results.push_back (format_single_argument (arg, precision, true));
555           else if (spec == 'l')
556             {
557               SCM s = arg;
558               for (; scm_is_pair (s); s = scm_cdr (s))
559                 {
560                   results.push_back (format_single_argument (scm_car (s), precision));
561                   if (scm_cdr (s) != SCM_EOL)
562                     results.push_back (" ");
563                 }
564
565               if (s != SCM_EOL)
566                 results.push_back (format_single_argument (s, precision));
567
568             }
569         }
570
571       i = tilde;
572     }
573
574   if (scm_is_pair (rest))
575     programming_error (string (__FUNCTION__)
576                        + ": too many arguments");
577
578   vsize len = 0;
579   for (vsize i = 0; i < results.size (); i++)
580     len += results[i].size ();
581
582   char *result = (char *) scm_malloc (len + 1);
583   char *ptr = result;
584   for (vsize i = 0; i < results.size (); i++)
585     {
586       strncpy (ptr, results[i].c_str (), results[i].size ());
587       ptr += results[i].size ();
588     }
589   *ptr = '\0';
590
591   return scm_take_locale_stringn (result, len);
592 }
593
594 int
595 ly_run_command (char *argv[], char **standard_output, char **standard_error)
596 {
597   GError *error = 0;
598   int exit_status = 0;
599   int flags = G_SPAWN_SEARCH_PATH;
600   if (!standard_output)
601     flags |= G_SPAWN_STDOUT_TO_DEV_NULL;
602   if (!standard_error)
603     flags |= G_SPAWN_STDERR_TO_DEV_NULL;
604   if (!g_spawn_sync (0, argv, 0, GSpawnFlags (flags),
605                      0, 0,
606                      standard_output, standard_error,
607                      &exit_status, &error))
608     {
609       fprintf (stderr, "failed (%d): %s: %s\n", exit_status, argv[0], error->message);
610       g_error_free (error);
611       if (!exit_status)
612         exit_status = -1;
613     }
614
615   return exit_status;
616 }
617
618 static char *
619 ly_scm2utf8 (SCM str)
620 {
621   char *p = ly_scm2str0 (str);
622   char *g = g_locale_to_utf8 (p, -1, 0, 0, 0);
623   free (p);
624   return g;
625 }
626
627 LY_DEFINE (ly_spawn, "ly:spawn",
628            1, 0, 1, (SCM command, SCM rest),
629            "Simple interface to g_spawn_sync"
630            " @var{str}."
631            "  The error is formatted with @code{format} and @var{rest}.")
632
633 {
634   LY_ASSERT_TYPE (scm_is_string, command, 1);
635
636   int argc = scm_is_pair (rest) ? scm_ilength (rest) : 0;
637   char **argv = new char*[argc + 2];
638
639   int n = 0;
640   argv[n++] = ly_scm2utf8 (command);
641   for (SCM s = rest; scm_is_pair (s); s = scm_cdr (s))
642     argv[n++] = ly_scm2utf8 (scm_car (s));
643   argv[n] = 0;
644
645   char *standard_output = 0;
646   char *standard_error = 0;
647   // Always get the pointer to the stdout/stderr messages
648   int exit_status = ly_run_command (argv, &standard_output, &standard_error);
649
650   // Print out stdout and stderr only in debug mode
651   debug_output (string ("\n") + standard_output + standard_error, true);
652
653   for (int i = 0; i < n; i++)
654     free (argv[i]);
655   delete[] argv;
656
657   return scm_from_int (exit_status);
658 }