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